{"text": "(* 定数の定義 (再定義はできない) *)\nDefinition one : nat := 1.\n\n(* 関数の定義 *)\nDefinition double x := x + x.\n\nPrint double. (* double = fun x : nat => x + x : nat -> nat *)\n\nEval compute in double 2. (* = 4 : nat (式の計算) *)\n\n(* 局所的な名前束縛 *)\nDefinition quad x := let y := double x in 2 * y.\nEval compute in quad 2. (* = 8 : nat *)\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.\n\nEval compute in triple 3. (* = 9 : nat *)\nEval compute in 1 - 2. (* = 0 : nat (自然数の引き算は整数と違う) *)\n\nRequire Import ZArith. (* 整数モジュールのインポート *)\n\nModule Z. (* 定義の範囲を区切るために Module を使う *)\n  Open Scope Z_scope. (* 数値や演算子を整数として解釈する *)\n  Eval compute in 1 - 2. (* = -1 : Z (Z は整数の型) *)\n  Eval compute in (2 + 3) / 2. (* = 2 : Z *)\n  Definition p (x y : Z) := 2 * x - y * y.\n  Print p. (* p = fun x y : Z => 2 * x - y * y : Z -> Z -> Z *)\n  Eval compute in p 3 4. (* = -10 : Z *)\n  Definition p' := fun x => fun y => 2 * x - y * y.\n  Print p'. (* p' = fun x y : Z => 2 * x - y * y : Z -> Z -> Z *)\n  Definition q := p 3. (* 部分適用 *)\n  Eval compute [p q] in q. (* p と q の定義だけを展開する *)\n", "meta": {"author": "0918nobita", "repo": "Coq", "sha": "da804200fa18645a422e77e76157652c5fedd05f", "save_path": "github-repos/coq/0918nobita-Coq", "path": "github-repos/coq/0918nobita-Coq/Coq-da804200fa18645a422e77e76157652c5fedd05f/example2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7999418095882633}}
{"text": "(**\nA Gentle Introduction to Type Classes and Relations in Coq\nの\nChapter 3. Lost in Manhattan (抜萃、つづき)\n\ntypeclassestut.pdf\ntypeclassesTut/Lost_in_NY.v\n\nこのうち、\n3.7 Deciding Route Equivalence の Ex1'\nを証明するまでを抜粋する。\n\n3.7 では、それ以前の節の\n「Type Classを使って reflexivityとrewriteを拡張する」\nという内容とは打って変わって、起点と終点が同じなら、同じルートであること、\nto prove some path equivalences through a simple computation\nを説明している。\n\nつまり、3.7で証明したことだけを使うなら、ルートの中に変数が含まれていてはいけない。\nしかし、そうでない場合は、a simple computation になる。\n*)\n\n(* We consider the discrete plan the coordinate system of which \n    is based on Z *)\nRequire Import List.\nRequire Import ZArith.\nRequire Import Bool.\nOpen Scope Z_scope.\nRequire Import Relations.\nRequire Import Setoid.\n\n(* Require Import coq_gitcrc_3_digest. *)\n(*************************************************************)\n(**\n3.2 Data Type and Definitions\n *)\n(* Types for representing routes in the dicrete  plane *)\nInductive direction : Type := North | East | South | West.\nDefinition route := list direction.\n\nRecord Point : Type :=\n  {\n    Point_x : Z;\n    Point_y : Z\n  }.\n\nDefinition Point_O := Build_Point 0 0.\n\n(**\n3.3 Route Semantics\n *)\nDefinition translate (dx dy:Z) (P : Point) :=\n  Build_Point (Point_x P + dx) (Point_y P + dy).\n\n(* Equality test  between Points *)\nDefinition Point_eqb (P P':Point) :=\n  Zeq_bool (Point_x P) (Point_x P') &&\n           Zeq_bool (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\nDefinition route_equiv : relation route :=\n  fun r r' => forall P:Point , move r P = move  r' P.\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\n(**\n3.7 Deciding Route Equivalence\n*)\n\n(* Prove the correctness of Point_eqb *)\nLemma Point_eqb_correct :\n  forall p p',\n    Point_eqb p p' = true <-> p = p'.\nProof.\n  destruct p; destruct p'; simpl; split.\n  unfold Point_eqb;  simpl;  rewrite andb_true_iff; destruct 1.\n  repeat rewrite <- Zeq_is_eq_bool in *.\n  rewrite H, H0; reflexivity.\n  injection 1; intros H0 H1; rewrite H0, H1; unfold Point_eqb; simpl;\n  rewrite andb_true_iff; repeat rewrite <- Zeq_is_eq_bool; now split.\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  unfold translate; simpl; intros; f_equal; ring.\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  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.\nQed.\n\nDefinition route_eqb r r' : bool :=\n  Point_eqb (move r Point_O) (move r' Point_O).\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  rewrite route_equiv_equivb.\n  unfold route_eqb, Point_eqb, Zeq_bool.\n  simpl.                                    (* true = true *)\n  reflexivity.\n  \n  Restart.\n  route_eq_tac.\nQed.\n\n(*****************\nオリジナル文書にはない補足説明\n@suharahiromichi\n\nroute_equiv と route_eqb は、reflect の関係にあるので、それを証明すれば、\nEx1 の =r= (route_equiv) を route_eqb にして証明することができる。\n\nSSReflectの上で、Morphisms を使うのは難しそうなので、\nここで、試験的に局所的にSSReflectをImportしている。\n******************\n*)\nSection SSR.\n  From mathcomp Require Import all_ssreflect.\n  \n  Lemma route_equivP (r r' : route) :\n    reflect (r =r= r') (route_eqb r r').\n  Proof.\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').\n  Qed.\n  \n  Example Ex1'' : East::North::West::South::East::nil =r= East::nil.\n  Proof.\n    apply/route_equivP.\n      by [].\n  Qed.\nEnd SSR.\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/coq_gitcrc_3_7_digest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.7999418045071239}}
{"text": "Require Import Setoid\n    Sigma.Algebra.Hierarchy\n    Coq.Classes.Morphisms\n    Coq.Unicode.Utf8.\n\nSection Monoid.\n  \n\n  Context \n    {T : Type} \n    {eq : T -> T -> Prop} \n    {op : T -> T -> T}\n    {id : T}\n    {Hmonoid : @monoid T eq op id}.\n\n\n  Local Infix \"=\" := eq : type_scope.\n  Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Infix \"*\" := op.\n  \n  \n\n  Lemma monoid_cancel_left z iz (Hinv : op iz z = id) :\n    forall x y, (z * x) = (z * y) <-> x = y.\n  Proof.\n    intros ? ?; \n    split; intros H.\n    assert (Hcut : (iz * (z * x))  = (iz * (z * y))).\n    rewrite H. reflexivity.\n    rewrite !(@monoid_is_associative T eq op id Hmonoid) in Hcut.\n    rewrite Hinv in Hcut. \n    rewrite !monoid_is_left_idenity in Hcut.\n    exact Hcut.\n    rewrite H. \n    reflexivity.\n  Qed.\n  \n  \n  Lemma monoid_cancel_right z iz (Hinv : op z iz = id) :  \n    forall x y, x * z = y * z <-> x = y.\n  Proof.\n    intros ? ?; split; intro H.\n    assert (op (op x z) iz = op (op y z) iz) as Hcut.\n    rewrite H; reflexivity.\n    rewrite <- !(@monoid_is_associative T eq op id Hmonoid) in Hcut.\n    rewrite Hinv in Hcut.\n    rewrite !monoid_is_right_identity in Hcut.\n    exact Hcut.\n    rewrite H; reflexivity.\n  Qed.\n\n\n  \n\n  (* what can I say about the reverse direction? *)\n  Lemma monoid_both_identity : \n    forall a b, a = id ∧ b = id -> a * b = id.\n  Proof. \n    intros ? ? H.\n    destruct H as [H₁ H₂]; \n    rewrite H₁.\n    rewrite monoid_is_left_idenity.\n    exact H₂.\n  Qed.\n  \n  \n  \n  Lemma monoid_inv_inv a b c : b * a = id -> c * b = id -> c = a.\n  Proof.\n    intros H₁ H₂. \n    assert (Ht : c * (b * a) = c * id) \n      by (rewrite H₁; reflexivity).\n    rewrite (@monoid_is_associative T eq op id Hmonoid) in Ht.\n    rewrite H₂, \n      monoid_is_left_idenity,\n      monoid_is_right_identity in Ht. \n    symmetry in Ht.\n    exact Ht.\n  Qed.\n\n\n  Lemma monoid_inv_op x y a b : \n    a * x = id -> b * y = id -> (b * a) * (x * y) = id.\n  Proof.\n    intros Hx Hy.\n    assert(Ht : (a * (x * y)) = ((a * x) * y)) \n      by (rewrite associative; reflexivity).\n    rewrite <- associative.\n    rewrite Ht, Hx, left_identity. \n    exact Hy.\n  Qed.\n  \nEnd Monoid. \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/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7996441731760321}}
{"text": "(* Some useful definitions and lemmas *)\nRequire Import Arith Omega.\nRequire Export Vectors.\n\n\n Set Implicit Arguments.\n\n\n Section Addition_subtraction_multiplication.\n\n  (* addition, subtraction and composition *)\n    (* addition, subtraction and composition *)\n   Fixpoint vAdd (n : nat) (i : Vec nat n) : Vec nat n -> Vec nat n :=\n     match i in Vec _ e return (Vec nat e -> Vec nat e) with\n    | vnil => fun _ => vnil _\n    | vcons _ x xs => fun j => match vCons j with \n                               | isvcons y ys => vcons (x + y) (vAdd xs ys)\n                               end\n    end.\n\n    Fixpoint vSub (n : nat) (i : Vec nat n) : Vec nat n -> Vec nat n :=\n     match i in Vec _ e return (Vec nat e -> Vec nat e) with\n    | vnil => fun _ => vnil _\n    | vcons _ x xs => fun j => match vCons j with \n                               | isvcons y ys => vcons (x - y) (vSub xs ys)\n                               end\n    end. \n\n\n    (* compute the evaluation matrix *)\n   Fixpoint Vtimes (n : nat) (l : Vec nat n)  : Vec nat n -> Vec nat n :=\n    match l as l in (Vec _ e) return Vec nat e -> Vec nat e with\n    | vnil => fun _ => vnil _\n    | vcons _ x ls =>\n              fun j => match vCons j with\n                       | isvcons y ys => vcons (x * y) (Vtimes ls ys)\n                       end\n    end.\n  \n\n  (* sum the elements of a vector *)\n  Fixpoint vsum (n : nat) (i : Vec nat n)  :=  \n   match i with\n   | vnil  => 0\n   | vcons _ n ns => n + vsum ns\n   end.\n\n  Lemma vsum_vplus n m (i : Vec nat n) (j : Vec nat m) :  vsum (vPlus i j)  = vsum i + vsum j.\n  Proof.\n      induction i; simpl; trivial.\n      intros j; rewrite (IHi j); auto with arith.\n  Qed.\n\n  Lemma vsum_plus n m (v : Vec nat (n + m)): \n       vsum v = match vplusView _ _ v with\n                | vplus a b => vsum a + vsum b\n                end.\n  Proof.\n    intros n m v; vSimp; apply vsum_vplus. \n  Qed.\n\n   Fixpoint ZSumz (n : nat) (l : Vec nat n)   :=\n     match l as l in (Vec _ e)  with\n       | vnil => 0\n       | vcons _ x ls =>  (ZSumz ls) + x\n     end. \n\n Lemma ZSz_Vtms (n : nat ) (v i0 i : Vec nat n) :\n   ZSumz (Vtimes (vAdd v i0) i) = ZSumz (Vtimes v i) + ZSumz (Vtimes i0 i).\n Proof.\n    induction v; intros; vSimp; simpl; trivial. rewrite (IHv i0 i); ring.\n  Qed.\n\n \n(* Lemma ZSz_sub (n : nat ) (v i0 i : Vec nat n) :\n   ZSumz (Vtimes (vSub v i0) i) = ZSumz (Vtimes v i) - ZSumz (Vtimes i0 i).\n  Proof.\n   induction v; intros; vSimp; simpl; trivial. rewrite (IHv i0 i).   \n   replace ((x - a0) * a) with (x * a - a0 * a); auto with arith. omega. \n  Qed. *)\n\n  Lemma vtimesPlus (n m : nat) (i i1  : Vec nat n) (j j1 : Vec nat m) :\n     Vtimes (vPlus i j) (vPlus i1 j1) = vPlus (Vtimes i i1) (Vtimes j j1).\n  Proof.\n   induction i;  intros; vSimp; simpl; trivial. rewrite (IHi i0 j j1); trivial.\n  Qed.\n\n Lemma zSumzPlus (n m: nat) (i : Vec nat n) (j : Vec nat m) : ZSumz (vPlus i j) = ZSumz i + ZSumz j.\n Proof.\n   induction i; simpl; trivial. intro j; rewrite (IHi j);  ring.\n Qed.\n\n\n  Lemma ZSumz_vmap_Vtimes (n : nat) (v : Vec nat n) (a  : nat) :\n     forall x,  ZSumz (Vtimes (vmap (fun x1  => a * x1) v) x) =  a * (ZSumz (Vtimes v x) ). \n  Proof.\n    induction v; intros; vSimp; simpl; trivial; try auto with arith.\n    rewrite (IHv a i); ring.\n  Qed. \n\n (* misc *)\n Ltac vsimpl :=  unfold vhead in *; unfold vtail in *;  simpl in *.\n\n Lemma vtimes0 n i j : i = vec n 0 -> Vtimes i j = vec n 0.\n  Proof.\n    induction n; intros; vSimp; simpl; auto. destruct (VeqInj2 H); vsimpl.\n    rewrite (IHn i i0 H1); subst; trivial.\n Qed. \n\n Lemma vtimes_comm (n : nat) (i j : Vec nat n):  Vtimes i j = Vtimes j i.\n Proof.\n  induction i; intros; vSimp; simpl; auto.\n   rewrite (IHi i0). replace (a * x) with (x * a); trivial; try ring.\n Qed.\n\n Lemma Zsumz_0 : forall n , ZSumz (vec n 0) = 0.\n  Proof. \n    induction n; simpl; trivial. rewrite IHn; trivial.\n  Qed.\n \n Lemma vecPlus0  n m i j :\n   i = vec n 0 -> j = vec m 0 -> vPlus i j = vec (n + m) 0.\n  Proof. \n    induction i; intros; simpl; trivial. destruct (VeqInj2 H); vsimpl.\n    rewrite H1. rewrite (IHi j H2 H0); trivial.\n Qed.\n\n  Lemma vPluz_0 : forall n m, \n    match vplusView _ _ (vec (n + m) 0)  with\n     | vplus x y => x = vec n 0 /\\ y = vec m 0\n    end.\n   induction n; intros; simpl;  auto.\n    generalize ( IHn m); intro. destruct (vplusView _ _ (vec (n + m) 0)).\n   destruct H. rewrite H; auto.\n  Qed.\n\n  Lemma vPluz_1 (A : Set) (n m : nat) (i : Vec  A n) (j : Vec A m) :\n    match vplusView _ _ (vPlus i j)  with\n     | vplus x y => x = i /\\ y = j\n    end.\n   induction i; intros; simpl; auto.\n    generalize ( IHi j).  destruct (vplusView _ _ (vPlus i j)).\n    intro H; destruct H; subst; auto.\n  Qed.\n\n  Lemma vecPlus00  n m i j :  vPlus i j = vec (n + m) 0 ->  i = vec n 0 /\\ j = vec m 0 .\n  Proof.\n    induction n; intros; vSimp; simpl; auto.\n    destruct (VeqInj2 H); vsimpl. destruct (IHn m i j H1). rewrite H0.\n    rewrite H2; auto.\n  Qed.\n\n  Lemma vadd_id  n i : vAdd i (vec n 0) = i.\n    induction i;  simpl; trivial. rewrite plus_0_r; rewrite IHi ; trivial.\n  Qed.\n\n  Lemma vtimesPlus1 (n m : nat) ( v : Vec nat n) (v0 : Vec nat m) (i0 : Vec nat n) (j0 : Vec nat m) : \n    ZSumz (Vtimes (vPlus v v0) (vPlus i0 j0))  = ZSumz (Vtimes v i0) + ZSumz (Vtimes v0 j0) .\n  Proof. \n    induction v; intros; vSimp; simpl; trivial.  rewrite (IHv v0 i j0); ring.\n  Qed.\n  \n  Lemma vtimes_vcons_vsnoc n (xs : Vec nat n) (ys : Vec nat (S n)) x :\n      ZSumz (Vtimes (vSnoc x xs) ys) = ZSumz (Vtimes xs (vfirst ys)) + x * (vlast ys).\n  Proof.\n    induction xs; intros; vSimp; vsimpl; simpl; trivial; try vecRwt. \n    unfold vfirst;  vsimpl.\n    rewrite (IHxs (vcons a0 i) x0 );  unfold vfirst; unfold vlast; vsimpl; ring.\n  Qed.\n\n \n   Lemma Vtimes_vSnoc n (v v1 : Vec nat (S n)) : \n     ZSumz (Vtimes v (vSnoc (vlast v1) (vfirst v1))) =\n     ZSumz (Vtimes (vfirst v) (vfirst v1)) +  vlast v * vlast v1.\n   Proof. \n     intros n v; destruct (vCons v) as [vh vt]. \n     generalize vh; clear; induction vt.\n     intros vh v1; destruct (vCons v1); unfold vlast; unfold vfirst; vsimpl; vSimp; trivial.\n     intros vh v1; destruct (vCons v1) as [b bs].\n     destruct (vCons bs) as [y ys];  generalize (IHvt x (vcons y ys)); clear; \n     unfold vlast; unfold vfirst; vsimpl. \n     destruct ( vCons (vSnoc (vlast_aux y ys) (vfirst_aux y ys))); simpl.\n     intro H;  rewrite H; ring.\n   Qed.\n\n  \n End Addition_subtraction_multiplication.\n\n (* exporting tactics *)\n \n", "meta": {"author": "rawlep", "repo": "ArithmeticAnaysisOfPolymorphicPrograms", "sha": "1e7919ade56888a7134597e25d9fb1438e24a75b", "save_path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms", "path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms/ArithmeticAnaysisOfPolymorphicPrograms-1e7919ade56888a7134597e25d9fb1438e24a75b/VNArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.7995390514018811}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\n\nOpen Scope Z_scope.\n\nLocate \"_ * _\".\n\nPrint Scope Z_scope.\n\nCheck 33. (* default scope is Z *)\nCheck 33%nat. (* 33 interpreted within scope nat_scope with key 'nat' *)\nCheck 0. (* : Z *)\nCheck O. (* : nat *)\n\nOpen Scope nat_scope.\nCheck 33. (* : nat *)\nCheck 0. (* nat *)\nCheck 33%Z.\nCheck (-12)%Z.\nCheck (33%nat).\n\nCheck true. (* : bool *)\nCheck false. (* : bool *)\n\n\nCheck plus.\nCheck Zplus.\nCheck negb.\nCheck ifb. \nCheck S.\nCheck 0.\nCheck O.\nCheck S (S (S 0)).\nCheck mult (mult 5 (minus 5 4)) 7.\nCheck (5*(5-4)*7).\n\nUnset Printing Notations.\nCheck 4.\nCheck (5*(5-4)*7).\nSet Printing Notations.\nOpen Scope Z_scope.\nCheck (Zopp (Zmult 3 (Zmult (-5) (-8)))).\nCheck ((-4)*(7-7)).\nOpen Scope nat_scope.\nCheck Zabs_nat.\nCheck (5 + Zabs_nat (5-19)).\n\nCheck (fun n (z:Z) f => (n + (Zabs_nat(f z)))%nat).\nCheck (fun n _ : nat => n).\nCheck (fun n p:nat => n).\n\nDefinition f := \n  fun n p: nat => (let diff := n-p in\n                   let square := diff*diff in\n                   square*(square+n)%nat).\nCheck f.\nParameter max_int : Z.\n\nOpen Scope Z_scope.\nDefinition min_int := 1 - max_int.\nPrint min_int.\n\nDefinition cube1 := fun z:Z => z*z*z.\nDefinition cube2 (z:Z) : Z := z*z*z.\nDefinition cube3 z := z*z*z.\nPrint cube1.\nPrint cube2.\nPrint cube3.\n\nDefinition Z_thrice (f:Z->Z)(z:Z) := f (f (f z)).\nPrint Z_thrice.\nDefinition plus9 := Z_thrice (Z_thrice (fun z:Z => z + 1)).\nEval compute in plus9 2.\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/test2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.867035752930664, "lm_q1q2_score": 0.7993391978067392}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive bin :=\n| o : bin -> bin\n| i : bin -> bin\n| z : bin.\n\nCheck (i (i (o z))).\n\nFixpoint binnat (b : bin) : nat :=          (* f *)\n  match b with\n  | z => 0\n  | o b => (binnat b).*2\n  | i b => (binnat b).*2 + 1\n  end.\n\nCompute binnat (o (i (i (o (o z))))).\n\nFixpoint bininc (b : bin) : bin :=\n  match b with\n  | i b => o (bininc b)\n  | o b => i b\n  | z => i z\n  end.\n\nCompute bininc (o (i (i (o (o z))))).\nCompute bininc (i (i (i (o (o z))))).\nCompute bininc (o (i (i z))).\nCompute bininc (i (i (i z))).\n\nFixpoint natbin (n : nat) : bin :=          (* g *)\n  match n with\n  | 0 => z\n  | n.+1 => bininc (natbin n)\n  end.\n\n(* 直接的な正規化 *)\nFixpoint normalize (b : bin) : bin :=\n  match b with\n  | o b =>\n    match (binnat b) with\n    | 0 => z\n    | _ => o (normalize b)\n    end\n  | i b => i (normalize b)\n  | z => z\n  end.\n\nCompute normalize (o (i (i (o (o z))))).\nCompute natbin (binnat (o (i (i (o (o z)))))).\n\nLemma hodai1 n :\n  natbin n.+1.*2 = o (natbin n.+1).\nProof.\n  elim: n.\n  - by [].\n  - move=> /= n' H /=.\n    by rewrite H /=.\nQed.\n(*\nnatbin n.*2 = o (natbin n) を証明するには、\nz = o z を認める必要がある。\nつまり、一般的過ぎて証明できない。\n *)\n\nLemma hodai2 n :\n  natbin (n.*2 + 1) = i (natbin n).\nProof.\n  elim: n.\n  - by [].\n  - move=> /= n' H /=.\n    by rewrite H /=.\nQed.\n\n(* natを経由する正規化と、直接的な正規化が、同じ結果になることを証明する。 *)\nGoal forall (b : bin),\n    natbin (binnat b) = normalize b.\nProof.\n  elim=> [b IHb|b IHb|] /=.\n  - rewrite -IHb.\n    case: (binnat b).\n    + by [].\n    + elim.\n      * by [].\n      * move=> n H.\n          by apply hodai1.\n  - rewrite -IHb.\n    case: (binnat b).\n    + by [].\n    + elim.\n      * by [].\n      * move=> n H.\n          by apply hodai2.\n  - by [].\nQed.\n\n(* ******** *)\n(* **別解** *)\n(* ******** *)\n\n(* 再帰関数の、関数呼び出しに関する帰納法をできるようにする。\n * パターンマッチが入れ子になったりしている複雑な再帰関数のときに便利\n * https://gist.github.com/yoshihiro503/fc51fef8b94c3a42c3ca\n *)\nFunctional Scheme normalize_ind := Induction for normalize Sort Prop.\nGoal forall (b : bin),\n    natbin (binnat b) = normalize b.\nProof.\n  move=> b.\n  functional induction (normalize b) => /=.\n  (* natbin (binnat b0).*2 = z *)\n  - by rewrite e0 /=.\n  (* natbin (binnat b0).*2 = o (normalize b0) *)\n  - by rewrite -IHb0 e0 hodai1 /=.\n  (* natbin ((binnat b0).*2 + 1) = i (normalize b0) *)\n  - by rewrite -IHb0 hodai2 /=.\n  (* z = z *)\n  - by [].\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/sf/coq_bin_norm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.799286873837931}}
{"text": "Require Import ZArith.\nOpen Local Scope Z_scope.\n\nInductive fact_domain : Z -> Prop :=\n| fact_domain_zero :\n  fact_domain 0\n| fact_domain_pos :\n  forall z : Z, z >= 0 -> fact_domain (Zminus z 1) -> fact_domain z.\n\nTheorem fact_domain_pos_true : forall z : Z, fact_domain z -> z >= 0.\nintros x H.\ncase H.\nunfold Zge.\ndiscriminate.\nintros.\nassumption.\nDefined.\n\nTheorem fact_domain_inv :\n  forall z : Z, fact_domain z -> z > 0 -> fact_domain (Zminus z 1).\nintros z H.\ncase H.\nintros.\ndiscriminate.\nintros.\nassumption.\nDefined.\n\nFixpoint fact (z : Z) (h : fact_domain z) {struct h} : Z :=\nmatch Z_gt_le_dec z 0 with\n  | right hle =>\n    match Z_ge_lt_dec z 0 with\n      | right hlt => False_rec Z (fact_domain_pos_true z h hlt)\n      | left _ => 1\n    end\n  | left hgt =>\n    z * (fact (Zminus z 1) (fact_domain_inv z h hgt))\nend.", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/FactEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7991721375953189}}
{"text": "Theorem example1 : forall a b: Prop, a /\\ b -> b /\\ a.\n  intros a b H.\n  split.\n  destruct H as [H1 H2].\n  exact H2.\n  destruct H as [H1 H2].\n  exact H1.\nQed.\n\nTheorem example2 : forall A B, A \\/ B -> B \\/ A.\n  intros A B H.\n  destruct H as [H1 | H2].\n  right.\n  exact H1.\n  left.\n  exact H2.\nQed.\n\nCheck le_n.\nCheck le_S.\n\nTheorem example3 : 3 <= 5.      (* dependent type here! *)\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\nRequire Export Arith.\n\nCheck le_trans.\n\nTheorem example4 : forall x y, x <= 10 -> 10 <= y -> x <= y.\n  intros x y x10 y10.\n  apply le_trans with (m := 10).\n  exact x10.                    (* can also use assuption *)\n  exact y10.\nQed.\n\n\nTheorem example5 : forall x y, (x + y) * (x + y) = x * x + 2 * x * y + y * y.\n  intros x y.\n  SearchRewrite (_ * (_ + _)).\n  rewrite mult_plus_distr_l.\n  SearchRewrite ((_ + _) * _).\n  rewrite mult_plus_distr_r.\n  rewrite mult_plus_distr_r.\n  SearchRewrite (_ + (_ + _)).\n  rewrite plus_assoc.\n  rewrite <- plus_assoc with (n := x * x).\n  SearchPattern (?x * ?y = ?y * ?x).\n  rewrite mult_comm with (n := y) (m := x).\n  SearchRewrite (S _ * _).\n  pattern (x * y) at 1; rewrite <- mult_1_l.\n  rewrite <- mult_succ_l with (m := (x * y)). (* or can simply use rewrite <- mult_succ_l *)\n  SearchRewrite (_ * (_ * _)).\n  rewrite -> mult_assoc with (n := 2) (m := x) (p := y). (* or can simply use rewrite mult_assoc *)\n  reflexivity.\nQed.\n\nRequire Import Omega.\n\nTheorem omega_example : forall f x y, 0 < x -> 0 < f x -> 3 * f x <= 2 * y -> f x <= y.\n  intros; omega.\nQed.\n\nFixpoint sum_n n :=\n  match n with\n    O => O\n  | S p => p + sum_n p\nend.\n                    \nCheck sum_n.\n\nTheorem sum_n_p : forall n, 2 * sum_n n + n = n * n.\n  induction n.                  (* 归纳证明 *)\n  reflexivity.\n  assert (SnSn : S n * S n = n * n + 2 * n + 1).\n  ring.\n  rewrite -> SnSn.\n  rewrite <- IHn.\n  simpl.                        (* replace with the sum_n symbolic computation *)\n  ring.\nQed.\n\nRequire Import Bool.\n\nFixpoint evenb n :=\n  match n with\n    0 => true\n  | 1 => false\n  | S (S p) => evenb p\nend.\n\nCheck evenb.\n\nTheorem evenb_p : forall n, evenb n = true -> exists x, n = 2 * x.\n  assert (Main : forall n, (evenb n = true -> exists x, n = 2 * x) /\\ (evenb (S n) = true -> exists x, S n = 2 * x)).\n  induction n.\n  split.                        (* split conjunction *)\n  exists O; ring.\n  simpl.\n  intros H.\n  discriminate.\n  split.\n  destruct IHn as [_ IHn'].\n  exact IHn'.\n  simpl.\n  intros H.\n  destruct IHn as [IHn' _].\n  assert (H' : exists x, n = 2 * x).\n  apply IHn'.\n  exact H.\n  destruct H' as [x q].\n  exists (x + 1).\n  rewrite -> q.\n  ring.\n  intros n ev.\n  destruct (Main n) as [H _].\n  apply H.\n  exact ev.\nQed.\n\nRequire Import List.\nPrint beq_nat.\n\nFixpoint leb (n : nat) : nat -> bool :=\n  match n with\n    | O => fun _ : nat => true\n    | S n' => fun m : nat => match m with\n                         | O => false\n                         | S m' => leb n' m'\n                       end\n  end.\n\nEval compute in leb 3 3.\nEval compute in leb 3 6.\nEval compute in leb 6 3.\n\nFixpoint insert n l :=\n  match l with\n    nil => n :: nil\n  | h :: t => if leb n h then n :: l else h :: insert n t\nend.\n\nFixpoint count n l :=\n  match l with\n    nil => 0\n  | h :: t => let r := count n t in if beq_nat n h then 1 + r else r\nend.\n\n(* induction nat O | S _ *)\n(* induction list nil | _ :: _ *)\n\nTheorem insert_incr : forall n l, count n (insert n l) = 1 + count n l.\n  intros n l.\n  induction l.\n  simpl.\n  SearchAbout beq_nat.\n  rewrite <- beq_nat_refl.\n  reflexivity.                  (* or ring *)\n  simpl.\n  case (leb n a).\n  simpl.\n  rewrite <- beq_nat_refl.\n  reflexivity.\n  simpl.\n  case (beq_nat n a).\n  rewrite IHl; reflexivity.\n  rewrite IHl; reflexivity.\nQed.\n\n(* define new datatypes *)\n\nInductive bin : Type :=          (* binary tree *)\n  | L : bin                     (* leaf *)\n  | N : bin -> bin -> bin.        (* node *)\n\nCheck N L (N L L).              (* nonsense but match the specification *)\n\nDefinition is_single_node (t : bin) : bool :=\n  match t with\n    | N L L => false\n    | _ => true\n  end.\n\nFixpoint flatten_aux (t1 t2 : bin) : bin :=\n  match t1 with\n    | L => N L t2\n    | N t1' t2' => flatten_aux t1' (flatten_aux t2' t2)\n  end.\n\nFixpoint flatten (t : bin) : bin :=\n  match t with\n    | L => L\n    | N t1 t2 => flatten_aux t1 (flatten t2)\n  end.\n\nFixpoint size (t : bin) : nat :=\n  match t with\n   | L => 1\n   | N t1 t2 => 1 + size t1 + size t2\n  end.\n\nEval compute in flatten_aux (N L L) L.\nEval compute in size (N (N L L) L).\nEval compute in size (N L L).\n\n(* prove properties of functions *)\n\nTheorem example_size : forall t, is_single_node t = false -> size t = 3.\n  intro t.\n  destruct t.                   (* the tactic destruct is quite similiar to induction but one is for hypothesis and one is for conclution *)\n  simpl.\n  intro H.\n  discriminate H.               (* just got a contradiction assume true = false *)\n  destruct t1.\n  destruct t2.\n  simpl.\n  reflexivity.                  (* or use auto instead *)\n  simpl.\n  intro H.\n  discriminate H.\n  simpl.\n  intro H; discriminate.\nQed.\n\nTheorem flatten_aux_size : forall t1 t2, size (flatten_aux t1 t2) = size t1 + size t2 + 1.\n  induction t1.\n  intro t2.\n  simpl.\n  ring.\n  intro t2.\n  simpl.\n  rewrite IHt1_1.\n  rewrite IHt1_2.\n  ring.\nQed.\n\nTheorem not_subterm_self_1 : forall x y, ~ x = N x y.\n  induction x.\n  intro y.\n  intro H.\n  discriminate.\n  intro y.\n  intro abs.\n  injection abs.\n  intros h2 h1.\n  assert (IHx1' : x1 <> N x1 x2).\n  apply IHx1.\n  case IHx1'.\n  exact h1.\nQed.\n\nPrint nat.\n\nFixpoint nat_fact (n : nat) : nat :=\n  match n with\n    | O => 1\n    | S p => S p * nat_fact p\n  end.\n\nFixpoint fib (n : nat) : nat :=\n  match n with\n    | O => 0\n    | S q => match q with\n              | O => 1\n              | S p => fib p + fib q\n            end\n  end.\n\nInductive even : nat -> Prop :=       (* even x is a proposition *)\n  | evenO : even O\n  | evenS : forall x : nat , even x -> even (S (S x)).\n\n(*\njudgement and inference rule\n\n             n even\n ——————    ————————————\n 0 even    S(S(n)) even\n\n       ——————\n       0 even\n    ————————————\n    S(S(0)) even\n ——————————————————\n S(S(S(S(0)))) even\n*)\n\nTheorem even_mult : forall x, even x -> exists y, x = 2 * y.\n  intros x H.\n  elim H.                       (* elim and induction are almose the same here *)\n  exists 0.\n  reflexivity.\n  intros xO HevenO IHx.\n  destruct IHx as [y Heq].\n  rewrite Heq.\n  exists (S y).\n  ring.\nQed.\n\nTheorem not_even_1 : ~even 1.\n  intros even1.\n  inversion even1.\nQed.\n\nTheorem even_inv : forall x, even (S (S x)) -> even x. (* inversion of evenS *)\n  intros x H.\n  inversion H.\n  exact H1.\nQed.\n\n(*\nInductive properties can be used to express very complex notions. For instance, the semantics of a programming language can be defined as an inductive definition, using dozens of constructors, each one describing a an elementary step of computation.\n*)\n", "meta": {"author": "zjhmale", "repo": "MFCS", "sha": "e82b0e2425b4988ce8dfc558901ae2e76e1b23f1", "save_path": "github-repos/coq/zjhmale-MFCS", "path": "github-repos/coq/zjhmale-MFCS/MFCS-e82b0e2425b4988ce8dfc558901ae2e76e1b23f1/cih.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7991579410874349}}
{"text": "Require Import Omega.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFrom q3_2001 Require Export misc.\n\n(* TODO Retire in favour of largest_elt? *)\nDefinition nat_list_max (l : list nat) : nat :=\n  fold_right max 0 l.\n\nLemma nat_list_max_spec_0 : forall m l,\n  m <= nat_list_max (m::l).\nProof. intros. simpl. apply Nat.le_max_l. Qed.\n\nLemma nat_list_max_spec_1 : forall m l,\n  nat_list_max l <= nat_list_max (m::l).\nProof. intros. simpl. fold nat_list_max. apply Nat.le_max_r. Qed.\n\nLemma nat_list_max_spec_2 : forall (l : list nat),\n  l <> [] -> In (nat_list_max l) l.\nProof.\n  intros l Hl. generalize dependent l. induction l as [| x l IHl]; try contradiction.\n  destruct (Nat.max_spec_le x (nat_list_max l)) as [[Hmax Hmax'] | [Hmax Hmax']];\n  intros H; simpl; rewrite Hmax'.\n  + destruct (list_empty_dec l) as [Hl' | Hl'].\n    * left. subst. simpl. simpl in Hmax. omega.\n    * right. apply IHl in Hl'. apply Hl'.\n  + left. reflexivity.\nQed.\n\nLemma nat_list_max_spec_3 : forall (l : list nat) (m : nat),\n  In m l -> m <= nat_list_max l.\nProof.\n  intros l m Hm. induction l as [| x l IHl]; try contradiction.\n  destruct Hm as [H | H].\n  - subst. apply nat_list_max_spec_0.\n  - apply IHl in H. pose (H' := (nat_list_max_spec_1 x l)). omega.\nQed.\n\nLemma nat_list_max_spec_4 : forall (l : list nat),\n  nat_list_max l = 0 <-> (forall x, In x l -> x = 0).\nProof.\n  intros l.\n  split.\n  - intros H x Hx.\n    apply nat_list_max_spec_3 in Hx. rewrite H in Hx. omega.\n  - intros H. destruct (list_empty_dec l) as [Hl | Hl].\n    + rewrite Hl. auto.\n    + apply nat_list_max_spec_2 in Hl. apply H in Hl. 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/nat_list_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8757869900269367, "lm_q1q2_score": 0.7990997227465058}}
{"text": "Require Import Recdef.\n\nInductive Z : Type :=\n| Pos : nat -> Z\n| Zero : Z\n| Neg : nat -> Z.\n\nInductive Z' : Type :=\n| Zero' : Z'\n| MinusOne : Z'\n| Next : Z' -> Z'.\n\n\n(* Add for Z *)\nFunction succ (n: Z) : Z :=\nmatch n with\n| Pos k => Pos (S k)\n| Zero => Pos O\n| Neg O => Zero\n| Neg (S n) => Neg n\nend.\n\nFunction pred (n: Z) : Z :=\nmatch n with\n| Pos (S n) => Pos n\n| Pos O => Zero\n| Zero => Neg O\n| Neg n => Neg (S n)\nend.\n\nFunction map_n {A: Type} (n: nat) (f: A -> A) (x: A) : A :=\nmatch n with\n| O => x\n| S n' => f (map_n n' f x)\nend.\n\nFunction add (a b : Z) : Z :=\nmatch a with \n| Pos n => map_n (S n) succ b\n| Zero => b\n| Neg n => map_n (S n) pred b\nend.\n\nTheorem Z_ind' (P : Z -> Prop) (base: P Zero) (base_pos: P (Pos O)) (base_neg: P (Neg O))\n  (suc: forall n: nat, P (Pos n) -> P (Pos (S n))) \n  (pre: forall n: nat, P (Neg n) -> P (Neg (S n))) : forall z: Z, P z.\nProof.\n  intro z. destruct z.\n  - induction n.\n    + assumption.\n    + apply suc. assumption.\n  - assumption.\n  - induction n.\n    + assumption.\n    + apply pre. assumption.\nQed.\n\nTheorem one_is_zero_succ : Pos O = succ Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem succ_S : forall n: nat, Pos (S n) = succ (Pos n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem minus_one_is_zero_pred : Neg O = pred Zero.\nProof.\n  cbn. trivial.\nQed.\n\nTheorem pred_S : forall n: nat, Neg (S n) = pred (Neg n).\nProof.\n  destruct n; cbn; trivial. \nQed.\n\nTheorem succ_pred : forall n: Z, succ (pred n) = n.\nProof.\n  intro n. induction n.\n  - destruct n; cbn; trivial.\n  - cbn. trivial.\n  - destruct n; cbn; trivial.\nQed.\n\nTheorem pred_succ : forall n: Z, pred (succ n) = n.\nProof.\n  intro n. induction n.\n  - destruct n; cbn; trivial.\n  - cbn. trivial.\n  - destruct n; cbn; trivial.\nQed.\n\n\nTheorem add_r_zero : forall x: Z, add x Zero = x.\nProof.\n  induction x using Z_ind'; trivial.\n  - cbn; rewrite succ_S; f_equal; apply IHx.\n  - cbn; rewrite pred_S; f_equal; apply IHx.\nQed.\n\nTheorem add_r_succ : forall x y: Z, add x (succ y) = succ (add x y).\nProof.\n  intros x y. revert x. induction x using Z_ind'; trivial.\n  - cbn. rewrite pred_succ. rewrite succ_pred. trivial.\n  - cbn in *. f_equal. apply IHx.\n  - cbn in *. rewrite succ_pred. rewrite succ_pred in IHx. rewrite IHx. trivial.\nQed.\n\nTheorem add_r_pred : forall x y: Z, add x (pred y) = pred (add x y).\nProof.\n  intros x y. revert x. induction x using Z_ind'; trivial.\n  - cbn. rewrite pred_succ. rewrite succ_pred. trivial.\n  - cbn in *. rewrite pred_succ in *. rewrite IHx. trivial.\n  - cbn in *. f_equal. apply IHx.\nQed.\n\nTheorem add_sym: forall x y: Z, add x y = add y x.\nProof.\n  intro x. induction x using Z_ind'; intro y.\n  - rewrite add_r_zero. cbn. trivial.\n  - cbn. rewrite one_is_zero_succ. rewrite add_r_succ. rewrite add_r_zero. trivial.\n  - cbn. rewrite minus_one_is_zero_pred. rewrite add_r_pred.\n    rewrite add_r_zero. trivial.\n  - cbn. rewrite succ_S. rewrite add_r_succ. f_equal. apply IHx.\n  - cbn. rewrite pred_S. rewrite add_r_pred. f_equal. apply IHx.\nQed.\n\n\nTheorem add_pred_succ : forall x y: Z, add (pred x) (succ y) = add x y.\nProof.\n  intros x y. rewrite add_r_succ. rewrite (add_sym (pred x) y). rewrite add_r_pred.\n  rewrite succ_pred. rewrite add_sym. trivial.\nQed.\n\n\nTheorem add_l_succ : forall x y: Z, add (succ x) y = succ (add x y).\nProof.\n  intros x y. rewrite (add_sym (succ x) y). rewrite add_r_succ. f_equal.\n  apply add_sym.\nQed.\n\nTheorem add_succ_swap : forall x y: Z,  add x (succ y) = add (succ x) y.\nProof.\n  intros x y. rewrite add_r_succ. rewrite add_l_succ. trivial.\nQed.\n\nTheorem add_l_pred : forall x y: Z, add (pred x) y = pred (add x y).\nProof.\n  intros x y. rewrite (add_sym (pred x) y). rewrite add_r_pred. f_equal.\n  apply add_sym.\nQed.\n\nTheorem add_pred_swap : forall x y: Z, add x (pred y) = add (pred x) y.\nProof.\n  intros x y. rewrite add_r_pred. rewrite add_l_pred. trivial.\nQed.\n\n\n\n\n(* Add for Z' *)\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 abs (k: Z') : nat :=\nmatch k with\n| Zero'    => 0\n| MinusOne => 1\n| Next k'  => S (abs k')\nend.\n\nFunction pos (k: Z') : bool :=\nmatch k with\n| Zero'    => true\n| MinusOne => false\n| Next k'  => pos k'\nend.\n\nDefinition add' (a b : Z') : Z' :=\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: Z', pos z = pos (Next z).\nProof.\n  intros z. induction z; auto.\nQed.\n\nLemma if_pos_next_is_succ : forall z: Z', 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: Z', 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 Z'_ind' (P : Z' -> Prop) (base: P Zero') (suc: forall z: Z', P z -> P (succ' z)) \n  (pre: forall z: Z', P z -> P (pred' z)) : forall z: Z', 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: Z') : 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) : Z' :=\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: Z', 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: Z', 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.\n  - cbn. rewrite pos_for_map_n, abs_for_map_n. auto.\n  - cbn. rewrite pos_for_map_n', abs_for_map_n'. auto.\nQed.\n\nTheorem h_bijection' : forall x : Z', h_inv (h x) = x.\nProof.\n  intros x. destruct x; auto. cbn. destruct (pos x) eqn:P.\n  - cbn. f_equal. apply map_n_abs_pos. assumption.\n  - cbn. apply map_n_abs_neg. assumption.\nQed.\n\nLemma h_surjection : forall y: Z, exists x: Z', h x = y.\nProof.\n  intros y. exists (h_inv y). apply h_bijection.\nQed.\n\nLemma h_iniection : forall x y: Z', 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 : Z', pos x = true -> pred' (Next x) = x.\nProof.\n  intros x P. induction x; cbn in *; try discriminate; auto. specialize (IHx P).\n  rewrite IHx. auto.\nQed.\n\nLemma succ'_for_neg : forall x : Z', pos x = false -> succ' (Next x) = x.\nProof.\n  intros x P. induction x; cbn in *; try discriminate; auto. specialize (IHx P).\n  rewrite IHx. auto.\nQed.\n\nLemma pred'_for_neg : forall x : Z', pos x = false -> pred' x = Next x.\nProof.\n  intros x P. induction x; cbn in *; try discriminate; auto. specialize (IHx P).\n  rewrite IHx. destruct x; auto. cbn in *. discriminate.\nQed.\n\nLemma succ'_for_pos : forall x : Z', pos x = true -> succ' x = Next x.\nProof.\n  intros x P. induction x; cbn in *; try discriminate; auto. specialize (IHx P).\n  rewrite IHx. destruct x; auto. cbn in *. discriminate.\nQed.\n\nLemma succ'_pred': forall k : Z', succ' (pred' k) = k.\nProof.\n  intros x. functional induction (pred' x); cbn; auto. rewrite IHz.\n  functional induction (pred' k'); cbn; auto. contradiction.\nQed.\n\nLemma pred'_succ' : forall k : Z', pred' (succ' k) = k.\nProof.\n  intros k; functional induction (succ' k); cbn; auto.\n  rewrite IHz. functional induction (succ' k'); cbn in *; auto.\n  contradiction.\nQed.\n\nLemma pred_h : forall x: Z', pred (h x) = h (pred' x).\nProof.\n  intro x. destruct (pos x) eqn:P.\n  - destruct x; auto. cbn in P. rewrite pred'_for_pos; auto.\n    cbn. rewrite P. destruct x; cbn in *; try discriminate; auto.\n    rewrite P. auto.\n  - destruct x; auto. cbn in P. rewrite pred'_for_neg; auto.\n    cbn. rewrite P. auto.\nQed.\n\nLemma succ_h : forall x: Z', succ (h x) = h (succ' x).\nProof.\n  intro x. destruct (pos x) eqn:P.\n  - destruct x; auto. cbn in P. rewrite succ'_for_pos; auto.\n    cbn. rewrite P. auto.\n  - destruct x; auto. cbn in P. rewrite succ'_for_neg; auto.\n    cbn. rewrite P. destruct x; cbn in *; try discriminate; auto.\n    rewrite P. auto.\nQed.\n\nLemma add'_l_succ' : forall x y: Z', add' (succ' x) y = succ' (add' x y).\nProof.\n  intros x y. revert x. induction y using Z'_ind'; auto; intro.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite succ'_for_pos; auto. cbn. rewrite P. auto.\n    + rewrite succ'_for_neg; auto. cbn. rewrite P, succ'_pred'. auto.\n  - destruct x; auto.\n    + cbn. rewrite succ'_pred'. auto.\n    + unfold add'. destruct (pos x) eqn:P.\n      * rewrite succ'_for_pos; auto. cbn. rewrite P. auto.\n      * rewrite succ'_for_neg; auto. cbn. rewrite P, succ'_pred'. auto.\n  - destruct x; auto.\n    + cbn. rewrite succ'_pred'. auto.\n    + unfold add'. destruct (pos x) eqn:P.\n      * rewrite succ'_for_pos; auto. cbn. rewrite P. auto.\n      * rewrite succ'_for_neg; auto. cbn. rewrite P, succ'_pred'. auto.\nQed.\n\nLemma add'_l_pred' : forall x y: Z', add' (pred' x) y = pred' (add' x y).\nProof.\n  intros x y. revert x. induction y using Z'_ind'; auto; intro.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. rewrite P, pred'_succ'. auto.\n    + rewrite pred'_for_neg; auto. cbn. rewrite P. auto.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. rewrite P, pred'_succ'. auto.\n    + rewrite pred'_for_neg; auto. cbn. rewrite P. auto.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. rewrite P, pred'_succ'. auto.\n    + rewrite pred'_for_neg; auto. cbn. rewrite P. auto.\nQed.\n\n(* Homomorphism of algebraic structures *)\nTheorem Z_Z'_homo : forall x y: Z', add (h x) (h y) = h (add' x y).\nProof.\n  intros x. induction x using Z'_ind'; auto; intros y.\n  - rewrite add'_l_succ', <- succ_h, <- succ_h, <- IHx, add_l_succ. auto.\n  - rewrite add'_l_pred', <- pred_h, <- pred_h, <- IHx, add_l_pred. auto.\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/backup/integer_izo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.7990997135323639}}
{"text": "Inductive N: Set:=\n| zero : N\n| S: N -> N.\n\nDefinition I: N:= S zero.\n\nDefinition II: N:= S I.\n\nDefinition III: N:= S II.\n\nFixpoint sum (m n :N):=\nmatch n with\n   | zero => m\n   | S n'=> S (sum m n')\nend.\n\nNotation \"a '+' b\" := (sum a b)(at level 50, left associativity).\nLemma ghazie1: sum I II=III.\nProof.\nsimpl.\ntrivial.\nQed.\n\nLemma unity: forall n:N, sum zero n=n.\nProof.\ninduction n.\n-trivial.\n-simpl. rewrite IHn. trivial.\nQed.\n\nLemma komaki2: forall m n:N, sum (S m) n=sum m (S n).\nProof.\ninduction n.\n-simpl. trivial.\n-simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem comm: forall m n:N, sum m n=sum n m.\nProof.\nintros.\ninduction m.\n- simpl. apply unity.\n- simpl. rewrite <- IHm. apply komaki2.\nQed.\n(*****************************       All   Done!       ******************)\nFixpoint mult (m n:N):=\nmatch n with\n  |zero => zero\n  |S n'=> sum (mult m n') m\nend.\n\nNotation \"a '*' b\" := (mult a b)(at level 40, left associativity).\n\nDefinition VI: N:= S (S (S III)).\n(*Albatte in nemade 7 ha :D--> :)*)\nLemma do_seta_shishta: mult II III=VI.\nProof. \nsimpl. trivial.\nQed.\n\nTheorem mozdavaj:forall n, mult n I=n.\nProof.\nintros.\nsimpl.\napply unity.\nQed.\n\nLemma Zero_Mult: forall a:N , mult zero a = zero.\nProof.\ninduction a.\n-trivial.\n-simpl. apply IHa.\nQed.\nLemma Helper3: forall a b :N , sum ( S a ) b = S (sum a b).\nProof.\nintros.\nrewrite komaki2. simpl. trivial.\nQed.\n\nLemma Helper2: forall a b c :N, sum (sum a b ) c = sum a (sum b c).\nProof.\nintros.\ninduction a.\n- rewrite unity. rewrite unity. trivial.\n-repeat rewrite Helper3; rewrite IHa. trivial.\nQed.\n\nLemma Helper1: forall a b:N, mult (S a) b = sum (mult a b) b.\nProof.\nintros.\ninduction b.\n-trivial.\n-simpl. rewrite IHb. rewrite Helper2. \nrewrite Helper2. rewrite comm with a b. trivial. (*ino tozih bede*)\nQed.\nLemma Jabejaei_Mult: forall a b :N, mult a b = mult b a.\nProof. \nintros.\ninduction a.\n-simpl. apply Zero_Mult.\n- simpl. rewrite <-IHa. apply Helper1.\nQed.\n\nLemma distribut_mult: forall a m n :N, mult a (sum m n) = \nsum (mult a m) (mult a n).\nProof.\nintros.\ninduction a.\n- repeat rewrite Zero_Mult in *. trivial.\n- rewrite Helper1 in *. rewrite Helper1. rewrite Helper1. rewrite IHa. eauto.  \nrewrite Helper2 with (mult a m) m (sum (mult a n) n). rewrite comm with m (sum (mult a n) n).\nrewrite Helper2 with (mult a n) n m. rewrite comm with n m. \nrewrite Helper2 with (mult a m) (mult a n) (sum m n). trivial.\nQed.\n\n(*proof next lemma as exercise*)\nLemma Comutativity_Mult: forall l m n:N, mult (mult l m) n=mult l (mult m n).\nProof.\nintros.\ninduction n.\n-auto.\n-simpl. rewrite IHn. rewrite distribut_mult. trivial.\nQed.\n\n\n\n\n\n\n", "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/natural numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7990100645187708}}
{"text": "(*\nCalculus of construcctions\nSet - type of sets\nType - type of type constructors\nA -> B - type of functions from A to B\n(forall x:T, U) family of types indexed on T\n(fun (x:T) => U) - function from x of type T of body U (in CoC: [x:U] U)\n( T U ) - T applied to U\n\nTactics to use\ncbv flag1 flag2\n\t- call by value rewrite of term using flag1 and flag2 reductions (beta or delta for now)\nlazy flag1 flag2\n\t- lazy evaluation rewrite of term using flag1 and flag2 reductions (beta or delta for now)\ncompute\n\t- alias for cbv beta iota\nsimpl\n\t- performs β-reductions and expands transparent constants (non lemmas)\nInfix \n\t- defines infix syntax \n*)\n\nSection E4.\nVariable A : Set.\n\nDefinition composition { A B C } := fun (x:B->C)(y:A->B)(z:A)=>(x (y z)).\nInfix \"o\" := composition (left associativity, at level 94).\n\n\nDefinition id { A } := ....\n\nTheorem e4 : forall x:A, (id o id) x = id x.\nProof.\n\nQed.\n\nEnd E4.\n\n\nSection E6.\n(* Church encoded naturals *)\nDefinition N := forall X : Set, X -> (X -> X) -> X.\nDefinition Zero (X : Set) (o : X) (f : X -> X) := o.\nDefinition One  (X : Set) (o : X) (f : X -> X) := f (Zero X o f).\n\n(* 6.1 *)\nDefinition Two  ...\n\n(* 6.2 *)\nDefinition Succ ...\n\nLemma succOne : Succ One = Two.\nProof.\n\nQed.\n\n(* 6.3 *)\nDefinition Plus (n m : N) : N\n                := fun (X : Set) (o : X) (f : X -> X) => n X (m X o f) f.\n\n\nInfix \"++\" := Plus (left associativity, at level 94).\n\nLemma sum1: (One ++ Zero) = One.\nProof.\n\nQed.\n\nLemma sum2: (One ++ One) = Two.\nProof.\n\nQed.\n\n(* 6.4 *)\nDefinition Prod (n m : N) : N\n                := fun (X:Set) (o:X) (f:X->X) => m X o (fun y:X => n X y f).\n\n\nInfix \"**\" := ...\n\n(* 6.5 *)\nLemma prod1 : (One ** Zero) = Zero.\nProof.\n\nQed.\n\nLemma prod2: (One ** Two) = Two.\nProof.\n\nQed.\n\nEnd E6.\n\n\n", "meta": {"author": "gclaramunt", "repo": "CoqWorkshop", "sha": "5456f2191d4fe35c38eef50c93a417e0366b3739", "save_path": "github-repos/coq/gclaramunt-CoqWorkshop", "path": "github-repos/coq/gclaramunt-CoqWorkshop/CoqWorkshop-5456f2191d4fe35c38eef50c93a417e0366b3739/Coc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7990062251159088}}
{"text": "Inductive bool :=\n  | true\n  | false.\n\nParameter prop_variables : Set.\n\nCheck prop_variables.\n\nInductive prop_formula : Set := \n                       | Var : prop_variables -> prop_formula\n                       | Top : prop_formula \n                       | Bottom : prop_formula \n                       | Not : prop_formula -> prop_formula\n                       | And : prop_formula -> prop_formula -> prop_formula\n                       | Or : prop_formula -> prop_formula -> prop_formula.\n\nNotation \"⊥\" := Bottom.\nNotation \"⊤\" := Top.\nNotation \"¬ P\" := (Not P) (at level 51).\nInfix \"∧\" := And (left associativity, at level 52).\nInfix \"∨\" := Or (left associativity, at level 53).\n\nDefinition Implication (φ ψ : prop_formula) : prop_formula := ¬φ ∨ ψ.\nDefinition Equivalence (φ ψ : prop_formula) : prop_formula := φ ∧ ψ ∨ ¬φ ∧ ¬ψ.\n\nInfix \"→\" := Implication (left associativity, at level 54).\nInfix \"↔\" := Equivalence (left associativity, at level 55).\n\nFixpoint Interpretation (φ : prop_formula) (M : prop_variables -> bool) : bool := \n  match φ with\n  | Var p => M p\n  | ⊤ => true\n  | ⊥ => false\n  | ¬ψ => match Interpretation ψ M with \n         | true => false\n         | false => true\n         end\n  | ψ ∧ υ => match (Interpretation ψ M), (Interpretation υ M) with \n            | false, _ => false\n            | _, false => false\n            | _, _ => true\n            end\n  | ψ ∨ υ => match (Interpretation ψ M), (Interpretation υ M) with \n            | true, _ => true\n            | _, true => true\n            | _, _ => false\n            end\n  end.\n\nDefinition Satisfies (φ : prop_formula) M  := (Interpretation φ M) = true.\nDefinition DoubleTurnstile φ ψ := forall M, (Satisfies φ M) -> (Satisfies ψ M).\nDefinition Tautology φ := forall M, Satisfies φ M.\nInfix \"⊨\" := DoubleTurnstile (left associativity, at level 56).\nNotation \"_⊨\" := Tautology.\n\nDefinition SemanticEquivalence φ ψ := and (φ ⊨ ψ) (ψ ⊨ φ).\nInfix \"~\" := SemanticEquivalence (left associativity, at level 56).\n\nModule Problem_1.\n\nTheorem Problem_1_a: forall φ ψ : prop_formula,\n  _⊨ (φ → ψ) <-> φ ⊨ ψ.\nProof.\n  intros φ ψ.\n  split.\n  - intros H1. unfold Tautology in H1. unfold DoubleTurnstile. intros M1 H2.\n    unfold Satisfies. unfold Satisfies in H1. unfold Satisfies in H1, H2.\n    assert (H3: Interpretation (φ → ψ) M1 = true). { apply H1. }\n    unfold Implication in H3. unfold Interpretation in  H2, H3.\n    rewrite -> H2 in H3. \n    destruct (Interpretation ψ M1) eqn: E1.\n    * reflexivity.\n    * unfold Interpretation in E1. rewrite -> E1 in H3. discriminate H3.\n  - intros H1. unfold Tautology. unfold DoubleTurnstile in H1. intros M1.\n    unfold Satisfies. unfold Satisfies in H1.\n    assert (H2: Interpretation φ M1 = true -> Interpretation ψ M1 = true). { apply H1. }\n    unfold Implication.\n    destruct (Interpretation φ M1) eqn: E1.\n    * assert (H3: Interpretation ψ M1 = true). { apply H2. reflexivity. } \n      unfold Interpretation. unfold Interpretation in E1, H3. rewrite -> E1. rewrite H3. reflexivity.\n    * unfold Interpretation. unfold Interpretation in E1. rewrite -> E1. reflexivity.\nQed.\n\nTheorem Problem_1_b: forall φ ψ : prop_formula,\n  _⊨ (φ ↔ ψ) <-> φ ~ ψ.\nProof.\n  intros φ ψ.\n  split.\n  - intros H1. unfold SemanticEquivalence. unfold Tautology in H1.\n    split.\n    * unfold DoubleTurnstile. intros M1 H2.\n      unfold Satisfies. unfold Satisfies in H1. unfold Satisfies in H1, H2.\n      assert (H3: Interpretation (φ ↔ ψ) M1 = true). { apply H1. } \n      unfold Equivalence in H3. unfold Interpretation in H2, H3.\n      rewrite -> H2 in H3.\n      destruct (Interpretation ψ M1) eqn: E1.\n      + reflexivity.\n      + unfold Interpretation in E1. rewrite -> E1 in H3. discriminate H3. \n    * unfold DoubleTurnstile. intros M1 H2.\n      unfold Satisfies. unfold Satisfies in H1. unfold Satisfies in H1, H2.\n      assert (H3: Interpretation (φ ↔ ψ) M1 = true). { apply H1. } \n      unfold Equivalence in H3. unfold Interpretation in H2, H3.\n      rewrite -> H2 in H3.\n      destruct (Interpretation φ M1) eqn: E1.\n      + reflexivity.\n      + unfold Interpretation in E1. rewrite -> E1 in H3. discriminate H3.\n  - intros H. unfold SemanticEquivalence in H. unfold Equivalence.\n    destruct H as [ H1 H2 ]. unfold Tautology. intros M1.\n    unfold Satisfies. unfold DoubleTurnstile in H1, H2. unfold Satisfies in H1, H2.\n    assert (H3: Interpretation φ M1 = true -> Interpretation ψ M1 = true). { apply H1. }\n    assert (H4: Interpretation ψ M1 = true -> Interpretation φ M1 = true). { apply H2. }\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * assert (H5: Interpretation ψ M1 = true). { apply H3. reflexivity. }\n      simpl. rewrite -> H5. rewrite -> Eφ. reflexivity.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + discriminate H4. reflexivity.\n      + unfold Interpretation. unfold Interpretation in Eφ, Eψ. rewrite -> Eφ. rewrite -> Eψ. reflexivity.\nQed.\n\nEnd Problem_1.\n\nModule Problem_2.\n\nTheorem Problem_2_a: forall φ : prop_formula,\n  (¬¬φ)~φ.\nProof.\n  intros φ. unfold SemanticEquivalence.\n  split.\n  - unfold DoubleTurnstile. unfold Satisfies. intros M1 H1. simpl in H1.\n    destruct (Interpretation φ M1).\n    * reflexivity.\n    * discriminate H1.\n  - unfold DoubleTurnstile. unfold Satisfies. intros M1 H1. simpl. rewrite -> H1. reflexivity.\nQed.\n\nTheorem Problem_2_b: forall φ : prop_formula,\n  _⊨ (φ ∨ ¬φ).\nProof.\n  intros φ.\n  unfold Tautology. intros M1. unfold Satisfies. unfold Interpretation.\n  destruct (Interpretation φ M1) eqn: E1.\n  - unfold Interpretation in E1. rewrite -> E1. reflexivity.\n  - unfold Interpretation in E1. rewrite -> E1. reflexivity. \nQed.\n\nTheorem Problem_2_c: forall φ ψ η: prop_formula,\n  φ ∧ (ψ ∨ η) ~ (φ ∧ ψ) ∨ (φ ∧ η).\nProof.\n  intros φ ψ η. unfold SemanticEquivalence.\n  split.\n  - unfold DoubleTurnstile. intros M1. unfold Satisfies. intros H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. reflexivity.\n      + unfold Interpretation in Eφ, Eψ. \n        unfold Interpretation in H1. rewrite -> Eφ in H1. rewrite -> Eψ in H1.\n        unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. rewrite -> H1. reflexivity.\n    * unfold Interpretation in H1, Eφ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eφ in H1. discriminate H1.\n  - unfold DoubleTurnstile. intros M1. unfold Satisfies. intros H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. reflexivity.\n      + unfold Interpretation in Eφ, Eψ. \n        unfold Interpretation in H1. rewrite -> Eφ in H1. rewrite -> Eψ in H1.\n        unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. rewrite -> H1. reflexivity.\n    * unfold Interpretation in H1, Eφ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eφ in H1. discriminate H1.\nQed.\n\nTheorem Problem_2_d: forall φ ψ η: prop_formula,\n  φ ∨ (ψ ∧ η) ~ (φ ∨ ψ) ∧ (φ ∨ η).\nProof.\n  intros φ ψ η. unfold SemanticEquivalence.\n  split.\n  - unfold DoubleTurnstile. intros M1. unfold Satisfies. intros H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. unfold Interpretation.\n        rewrite -> Eφ. rewrite -> Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1. rewrite -> H1. reflexivity.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1. discriminate H1.\n  - unfold DoubleTurnstile. intros M1. unfold Satisfies. intros H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. unfold Interpretation.\n        rewrite -> Eφ. rewrite -> Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1. rewrite -> H1. reflexivity.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1. discriminate H1.\nQed.\n\nTheorem Problem_2_e: forall φ ψ: prop_formula,\n  φ ∨ (φ ∧ ψ) ~ φ.\nProof.\n  intros φ ψ. unfold SemanticEquivalence. unfold DoubleTurnstile.\n  split.\n  - intros M1. unfold Satisfies.\n    destruct (Interpretation φ M1) eqn: E1.\n    * reflexivity.\n    * intros H1. unfold Interpretation in H1, E1. rewrite -> E1 in H1. discriminate H1.\n  - intros M1. unfold Satisfies.\n    destruct (Interpretation φ M1) eqn: E1.\n    * intros H1. unfold Interpretation in E1. unfold Interpretation. rewrite -> E1. reflexivity.\n    * intros H1. discriminate H1.\nQed.\n\nTheorem Problem_2_f: forall φ ψ: prop_formula,\n  φ ∧ (φ ∨ ψ) ~ φ.\nProof.\n  intros φ ψ. unfold SemanticEquivalence. unfold DoubleTurnstile. unfold Satisfies. \n  split.\n  - intros M1 H1.\n    destruct (Interpretation φ M1) eqn: E1.\n    * reflexivity.\n    * unfold Interpretation in H1, E1. rewrite -> E1 in H1. discriminate H1.\n  - intros M1 H1. unfold Interpretation in H1. unfold Interpretation. rewrite -> H1. reflexivity.\nQed.\n\nTheorem Problem_2_g: forall φ ψ: prop_formula,\n  ¬(φ ∧ ψ) ~ ¬φ ∨ ¬ψ.\nProof.\n  intros φ ψ. unfold SemanticEquivalence. unfold DoubleTurnstile. unfold Satisfies. \n  split.\n  - intros M1 H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1.\n        unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ.\n        discriminate H1.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. reflexivity.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\n      + unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\n  - intros M1 H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eφ in H1. rewrite -> Eψ in H1.\n        unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ.\n        discriminate H1.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eφ. rewrite -> Eψ. reflexivity.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\n      + unfold Interpretation in Eφ. unfold Interpretation. rewrite -> Eφ. reflexivity.\nQed.\n\nTheorem Problem_2_h: forall φ ψ: prop_formula,\n  ¬(φ ∨ ψ) ~ ¬φ ∧ ¬ψ.\nProof.\n  intros φ ψ. unfold SemanticEquivalence. unfold DoubleTurnstile. unfold Satisfies. \n  split.\n  - intros M1 H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ. reflexivity.\n  - intros M1 H1.\n    destruct (Interpretation φ M1) eqn: Eφ.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n    * destruct (Interpretation ψ M1) eqn: Eψ.\n      + unfold Interpretation in H1, Eφ, Eψ. rewrite -> Eψ in H1. rewrite -> Eφ in H1.\n        unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ.\n        discriminate H1.\n      + unfold Interpretation in Eφ, Eψ. unfold Interpretation. rewrite -> Eψ. rewrite -> Eφ. reflexivity.\nQed.\n\nEnd Problem_2.\n\nModule Problem_3.\n\nTheorem Problem_3_a: forall p q : prop_formula,\n  _⊨ ((p → q) ↔ (¬q → ¬p)).\nProof.\n  intros p q. unfold Tautology. intros M1. unfold Satisfies.\n  destruct (Interpretation p M1) eqn: Ep.\n    - destruct (Interpretation q M1) eqn: Eq.\n      * unfold Interpretation in Ep, Eq. unfold Interpretation. simpl. rewrite -> Eq. rewrite -> Ep. reflexivity.\n      * unfold Interpretation in Ep, Eq. unfold Interpretation. simpl. rewrite -> Eq. rewrite -> Ep. reflexivity.\n    - destruct (Interpretation q M1) eqn: Eq.\n      * unfold Interpretation in Ep, Eq. unfold Interpretation. simpl. rewrite -> Eq. rewrite -> Ep. reflexivity.\n      * unfold Interpretation in Ep, Eq. unfold Interpretation. simpl. rewrite -> Eq. rewrite -> Ep. reflexivity.\nQed.\n\nTheorem Problem_3_b: forall p q r : prop_formula,\n  _⊨ ((p → (q → r)) ↔ (¬r → (¬q → ¬p))).\nProof.\n  intros p q r. unfold Tautology. intros M1. unfold Satisfies.\n  destruct (Interpretation p M1) eqn: Ep.\n    - destruct (Interpretation q M1) eqn: Eq.\n      * destruct (Interpretation r M1) eqn: Er.\n        -- unfold Interpretation in Ep, Eq, Er. unfold Interpretation. simpl. \n           rewrite -> Eq. rewrite -> Ep. rewrite -> Er. reflexivity.\n        -- unfold Interpretation in Ep, Eq, Er. unfold Interpretation. simpl. \n           rewrite -> Eq. rewrite -> Ep. rewrite -> Er. Abort.\n\n(* \n  При интерпретации M:\n    M[p] = true\n    M[q] = true\n    M[r] = false\n  формула неверна. Т.е она необщезначимая,\n  но при интерпретации M':\n    M[p] = true\n    M[q] = true\n    M[r] = true\n  формула выполнима.\n *)\n\nEnd Problem_3.\n\nModule Problem_4.\n\n(*\n  ННФ и КНФ:\n  ¬(¬(p ∧ q) → ¬r) ~ ¬((p ∧ q) ∨ ¬r) ~ ¬(p ∧ q) ∧ r ~ (¬p ∨ ¬q) ∧ r\n  (¬p ∨ ¬q) и r — дизъюнкты, т.е данная формула — конъюнкция дизъюнктов\n *)\nTheorem Problem_4_a: forall p q r : prop_variables,\n  ¬(¬((Var p) ∧ (Var q)) → ¬(Var r)) ~ (¬(Var p) ∨ ¬(Var q)) ∧ (Var r).\nProof.\n  intros p q r. unfold SemanticEquivalence. unfold DoubleTurnstile. unfold Satisfies.\n  split.\n  - intros M1 H1.\n    destruct (M1 p) eqn: Ep.\n    * destruct (M1 q) eqn: Eq.\n       + simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. discriminate H1.\n       + destruct (M1 r) eqn: Er.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            simpl. rewrite -> Ep. rewrite -> Eq. rewrite -> Er. reflexivity.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            discriminate H1.\n    * destruct (M1 r) eqn: Er.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1.\n        simpl. rewrite -> Ep. rewrite -> Er. reflexivity.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1. discriminate H1.\n  - intros M1 H1.\n    destruct (M1 p) eqn: Ep.\n    * destruct (M1 q) eqn: Eq.\n       + simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. discriminate H1.\n       + destruct (M1 r) eqn: Er.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            simpl. rewrite -> Ep. rewrite -> Eq. rewrite -> Er. reflexivity.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            discriminate H1.\n    * destruct (M1 r) eqn: Er.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1.\n        simpl. rewrite -> Ep. rewrite -> Er. reflexivity.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1. discriminate H1.\nQed.\n\n(*\n  ДНФ:\n  ¬(¬(p ∧ q) → ¬r) ~ ¬((p ∧ q) ∨ ¬r) ~ ¬(p ∧ q) ∧ r ~ (¬p ∨ ¬q) ∧ r ~ (¬p ∧ r) ∨ (¬q ∧ r)\n  (¬p ∧ r) и (¬q ∧ r) — конъюнкты, т.е данная формула — дизъюнкция конъюнктов\n *)\nTheorem Problem_4_b: forall p q r : prop_variables,\n  ¬(¬((Var p) ∧ (Var q)) → ¬(Var r)) ~ (¬(Var p) ∧ (Var r)) ∨ (¬(Var q) ∧ (Var r)).\nProof.\n  intros p q r. unfold SemanticEquivalence. unfold DoubleTurnstile. unfold Satisfies.\n  split.\n  - intros M1 H1.\n    destruct (M1 p) eqn: Ep.\n    * destruct (M1 q) eqn: Eq.\n       + simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. discriminate H1.\n       + destruct (M1 r) eqn: Er.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            simpl. rewrite -> Ep. rewrite -> Eq. rewrite -> Er. reflexivity.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            discriminate H1.\n    * destruct (M1 r) eqn: Er.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1.\n        simpl. rewrite -> Ep. rewrite -> Er. reflexivity.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1. discriminate H1.\n  - intros M1 H1.\n    destruct (M1 p) eqn: Ep.\n    * destruct (M1 q) eqn: Eq.\n       + simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. discriminate H1.\n       + destruct (M1 r) eqn: Er.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            simpl. rewrite -> Ep. rewrite -> Eq. rewrite -> Er. reflexivity.\n         -- simpl in H1. rewrite -> Ep in H1. rewrite -> Eq in H1. rewrite -> Er in H1.\n            discriminate H1.\n    * destruct (M1 r) eqn: Er.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1.\n        simpl. rewrite -> Ep. rewrite -> Er. reflexivity.\n      + simpl in H1. rewrite -> Ep in H1. rewrite -> Er in H1.\n        destruct (M1 q) eqn: Eq.\n        -- discriminate H1.\n        -- discriminate H1.\nQed.\n\nEnd Problem_4.\n\nModule Problem_5.\nEnd Problem_5.\n\nModule Problem_6.\nEnd Problem_6.\n\nModule Problem_7.\nEnd Problem_7.\n\nModule Problem_8.\nEnd Problem_8.\n\nModule Problem_9.\nEnd Problem_9.\n\nModule Problem_10.\nEnd Problem_10.", "meta": {"author": "vkutuev", "repo": "ACMLAT-HW", "sha": "4b46d501be1d9ddc806c86b0c58ccedd7a56d04f", "save_path": "github-repos/coq/vkutuev-ACMLAT-HW", "path": "github-repos/coq/vkutuev-ACMLAT-HW/ACMLAT-HW-4b46d501be1d9ddc806c86b0c58ccedd7a56d04f/lecture_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7990062250692999}}
{"text": "Require Import Arith Lia.\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 inj {X Y} (f : X -> Y) :=\n  forall x x', f x = f x' -> x = x'.\n  \nDefinition inv {X Y} (g : Y -> X) (f : X -> Y) :=\n  forall x, g (f x) = x.\n\nDefinition bijection X Y :=\n  { f : X -> Y & { g & inv g f /\\ inv f g }}.\n\n\nLemma size_rect {X} σ f : \n  (forall x, (forall y : X, σ y < σ x -> f y) -> f x) -> forall x, f x.\nrefine (fun size_rec x => size_rec x\n  (nat_rect (fun n => forall y, σ y < n -> f y)\n    (fun y Hy0 => ltac:(lia))\n    (fun x S_rec y Hyx => size_rec y \n      (fun z Hzy => S_rec z ltac:(lia)))\n    (σ x))).\nDefined.\n\nSection Cantor.\n\nDefinition next '(x,y) := \n  match x with\n  | O => (S y, O)\n  | S x' => (x', S y)\n  end.\n\nFact n00_next : forall p, (0,0) <> next p.\nProof. destruct p as [[] ]; discriminate. Qed.\n\nFact inj_next : inj next.\nProof. intros [[] ][[] ]; cbn; congruence. Qed.\n\n\nFixpoint decode n := \n  match n with\n  | 0 => (0,0)\n  | S x => next (decode x)\n  end.\n\n\nLemma inj_decode : inj decode.\nProof.\n  intros n. induction n; intros []; auto.\n  - now intros ?%n00_next.\n  - now intros ?%eq_sym%n00_next.\n  - intros [=?%inj_next%IHn]. congruence.\nQed.\n\n(* show that next is almost surj. *)\nFact zero_or_next : forall p, {a | p = next a} + {p = (0,0)}.\nProof.\n  intros [x []].\n  - destruct x. now right. left; now exists (0,x).\n  - left; now exists (S x, n).\nDefined.\n\n\nFixpoint Σ n := match n with 0 => 0 | S x => n + Σ x end. \n\nDefinition code '(x,y) := Σ(x+y)+y.\n\nLemma code_next : forall p, code(next p) = S(code p).\nProof.\n  intros [[|x] y]; cbn.\n  - rewrite <-!plus_n_O, Nat.add_comm. auto.\n  - rewrite !Nat.add_succ_r. cbn. auto.\nQed.\n\nLemma inv_dc : inv decode code.\nProof.\n  unfold inv.\n  apply (size_rect code). intros p rec.\n  destruct (zero_or_next p) as [[? ->] | ->].\n  - rewrite code_next. cbn. f_equal. apply rec.\n    rewrite code_next; auto.\n  - reflexivity.\nQed.\n\nFact inv_cd : inv code decode.\nProof.\n  intros ?. apply inj_decode. now rewrite inv_dc.\nQed.\n\nCorollary Bij_Nat_NatNat : bijection nat (nat * nat).\nProof.\n  exists decode, code. split. apply inv_cd. apply inv_dc.\nQed.\n\nFact bound x y n : code (x, y) = n -> y < S n.\nProof. cbn. lia. Qed.\n\nSection Cantor.", "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/CantorPairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7989788260231401}}
{"text": "Require Import Setoid.\n(*  Logique intuitionniste *)\n\nSection LJ.\n Variables P Q R S T : Prop.\n (*  Tactiques pour la conjonction \n\n    Introduction : pour prouver A /\\ B : split (il faudra prouver A, puis B)\n    Elimination : destruct H, si H : A /\\ B \n                  variante : destruct H as [H1 H2].\n        Dans les deux cas, on récupère deux hypothèses pour A et B (et on \n        choisit leurs noms, pour la variante \"as..\")\n  *)\n Lemma and_comm : P /\\ Q -> Q /\\ P.\n Proof.\n   intro H.\n   destruct H as [H0 H1]. (* /\\e *) \n   (* \" split /\\i \" *)\n   split;assumption. (* \"assumption\" résout les deux sous-buts *)\n Qed.\n\n (* tactiques pour la disjonction \n    Introduction:\n     pour prouver A \\/ B a partir de A : left\n     pour prouver A \\/ B a partir de B : right\n\n    Elimination:\n     preuve par cas : destruct H, si H: A \\/ B\n                      variante : destruct H as [H1 | H2]\n        On aura a faire deux preuves, une pour chaque cas (cas A, cas B)\n  *)\n\n  Lemma or_not : P \\/ Q -> ~P -> Q.\n  Proof.\n   intros H H0.     \n   destruct H.\n   - exfalso.\n     apply H0; assumption.\n     (* alternative: \n     assert (f:False).    \n     {\n       apply H0; trivial.\n     }\n     destruct f. *)\n     (* \"destruct f\" sur f:False résoud n'importe quel but *)\n   - assumption.\n   Qed.\n\n  (* Structuration de la preuve: +,*,+\n     utiles quand on a plusieurs sous-preuves non triviales;\n     améliorent la lisibilité du script *)\n  \n   (*  equivalence logique (<->, iff):\n       unfold iff transforme A <-> B en\n                             (A -> B) /\\ (B -> A).\n       donc split, destruct, etc, marchent\n\n       (iff pour \"if and only if\", le \"si et seulement si\" en anglais)\n    *)\n\n  Lemma iff_comm : (P <-> Q) -> (Q <-> P).\n  Proof.\n    intro H.\n    destruct H.\n    split.\n    - assumption.\n    - assumption.\n    (* \"assumption\" résoud les deux sous-buts engendrés par \"split\"\n    donc on peut remplacer les trois dernières lignes par\n    split; assumption.\n    *)\n  Qed.\n\n  (* la regle de remplacement est implantée en Coq *)\n  (* \"rewrite H\" fait un remplacement uniforme quand H est une\n     équivalence *)\n  (* \"rewrite H\" réécrit le but courant avec H *)\n  (* \"rewrite H in H'\" fait la réécriture de H dans une autre hypothèse H' *)\n  (* \"rewrite <- H\" réécrit dans l'autre sens, le membre droit par le gauche *)\n  Lemma L1 : (P <-> Q) -> ~(Q <-> ~P).\n  Proof.  \n     intro H.\n     rewrite H.\n     intro H0.\n     destruct H0.\n     assert (~Q).\n     { intro H2.\n       apply H0; assumption.\n     }\n     apply H2. apply H1. assumption. \n  Qed.\n\n  (* Fin des exemples, début des exercices *)\n\n  (* Exercice : remplacer tauto par des vraies preuves \n     interactives *)\n  (*  Exercices de la feuille 4 *)\n\n  Lemma and_false : P /\\ False -> False.\n  Proof.\n    intro Hpf.\n    destruct Hpf.\n    assumption. \n  Qed.\n\n  Lemma and_assoc : (P /\\ Q) /\\ R <-> P /\\ (Q /\\ R).\n  Proof.\n    split.\n    - intros.\n      destruct H as [Hpq Hr].\n      destruct Hpq as [Hp Hq].\n      split.\n      assumption.\n      split;assumption.\n    - intros.\n      destruct H as [Hp Hqr].\n      destruct Hqr as [Hq Hr].\n      split.\n      split;assumption.\n      assumption.\n  Qed.\n\n  (* Ex. 2 *)\n  Lemma or_to_imp: ~ P \\/ Q -> P -> Q.\n  Proof.\n    intros.\n    destruct H.\n    absurd (P);assumption.\n    assumption.\n  Qed.   \n\n  Lemma not_or_and_not: ~(P\\/Q) -> ~P /\\ ~Q.\n  Proof.\n    intros.\n    split .\n    (* but ~P *)\n    - intro.\n      apply H.\n      left;assumption.\n    (* but ~Q *)\n    - intro.\n      apply H.\n      right;assumption.\n  Qed.\n\n  (* Exercice 4 *)\n\n  Lemma absorption_or: P \\/ False <-> P.\n  Proof.\n    split.\n    - intro.\n      destruct H.\n      + assumption.\n      + exfalso.\n        assumption.\n    - intro.\n      left;assumption.\n  Qed.\n\n  Lemma and_or_dist : P /\\ (Q \\/ R) <-> P /\\ Q \\/ P /\\ R.\n  Proof.\n    split.\n    - intros.\n      destruct H as [Hp Hqr].\n      destruct Hqr.\n      (* avec Q  *)\n      + left.\n        split;assumption.\n      (* avec R *)\n      + right.\n        split;assumption.\n    - intros.\n      destruct H .\n      (* avec p /\\ Q *)\n      + destruct H .\n        split.\n        * assumption.\n        * left.\n          assumption.\n       (* avec P/\\R  *)\n      + destruct H.\n        split.\n        * assumption.\n        * right.\n          assumption.\n  Qed.\n\n  Lemma or_and_dist : P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\n  Proof.\n    split.\n    - intros.\n      destruct H.  \n      split.\n      (* avec P  *)\n       left;assumption.\n       left; assumption.\n      (* avec (Q /\\ R) *)\n       destruct H.\n       split.\n       right;assumption.\n       right;assumption.\n    - intros.\n      destruct H.\n      destruct H.\n      + left;assumption.\n      + destruct H0.\n        * left ; assumption .\n        * right .\n        split;assumption.\n  Qed.\n\n  Lemma and_not_not_impl: P /\\ ~ Q -> ~(P -> Q).\n  Proof.\n    intros.\n    intro.\n    destruct H.\n    apply H1.\n    apply H0;assumption.\n  Qed.\n\n  Lemma de_morgan1 : ~ (P \\/ Q) <-> ~P /\\ ~Q.\n  Proof.\n    split.\n    (* not_or_and_not *)\n    - auto.\n    - intros.\n      intro.\n      destruct H.\n      destruct H0.\n      absurd (P);assumption.\n      absurd Q ;assumption .\n  Qed.\n\n  Lemma reductio_ad_absurdum: (P -> ~P) -> ~P.\n  Proof.\n    intro.\n    intro.\n    absurd P .\n    - apply H ; assumption .\n    - assumption.\n  Qed.\n\n  Lemma np_p_nnp: (~P -> P) -> ~~P.\n  Proof.\n    intro.\n    intro.\n    absurd P .\n    - assumption.\n    - apply H.\n      assumption.\n  Qed.\n\n  (* Exercice: reprendre toutes les preuves précédentes, \n     en simplifiant et clarifiant les scripts:\n     - structurer les sous-preuves avec +/-/*\n     - inversement, quand c'est possible, factoriser avec \n       l'enchainement de tactiques (par \";\")\n\n     Le but est de faire que le script soit plus facile à lire\n     par un humain, pas pour la machine.\n   *)\n  \nEnd LJ.", "meta": {"author": "NiNejah", "repo": "logique-coq", "sha": "812a6bd6ce0814c7c6c87b2d3d516a91b5aa728d", "save_path": "github-repos/coq/NiNejah-logique-coq", "path": "github-repos/coq/NiNejah-logique-coq/logique-coq-812a6bd6ce0814c7c6c87b2d3d516a91b5aa728d/logique_propositionnelle_intuitionniste.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8872045944627057, "lm_q1q2_score": 0.7989541565889489}}
{"text": "Require Import String.\nRequire Import ZArith.\n\nSet Implicit Arguments.\n\nOpen Scope string.\nOpen Scope Z.\n\nRequire Import imp.\n\n(* Defining a pure subset of expressions,\n   extented to allow functions from the logic *)\nInductive exp :=\n  | var : string -> exp\n  | con : Z -> exp\n  | plus : exp -> exp -> exp\n  | app : (Z -> Z) -> exp -> exp\n  .\nInductive bexp :=\n  | bcon : bool -> bexp\n  | le : exp -> exp -> bexp\n  | eql : exp -> exp -> bexp\n  | not : bexp -> bexp\n  | and : bexp -> bexp -> bexp\n  .\nFixpoint eval_e env e :=\n  match e with\n    | var v => env v\n    | con z => z\n    | plus e1 e2 => eval_e env e1 + eval_e env e2\n    | app f e => f (eval_e env e)\n  end.\nFixpoint eval_b env e :=\n  match e with\n    | bcon b => b\n    | le e1 e2 => Z.leb (eval_e env e1) (eval_e env e2)\n    | eql e1 e2 => Z.eqb (eval_e env e1) (eval_e env e2)\n    | not b => negb (eval_b env b)\n    | and b1 b2 => if eval_b env b1 then eval_b env b2 else false\n  end.\n\n(* pure boolean expressions are currently re-used as formulas.\n   Supporting quantifiers probably requires distinguishing the types *)\nDefinition formula := bexp.\nDefinition holds f env := eval_b env f = true.\n\n(* Identification and extraction of pure from general\n   expressions is done with partial functions *)\nDefinition lift {A B} (f : A -> B) (oa : option A) : option B :=\n  match oa with\n    | Some a => Some (f a)\n    | None => None\n  end.\nArguments lift _ _ f !oa.\nDefinition lift2 {A B C} (f : A -> B -> C) (oa : option A) (ob : option B) : option C :=\n  match oa with\n    | Some a => lift (f a) ob\n    | _ => None\n  end.\nFixpoint is_pure_e (e : imp.exp) : option exp :=\n  match e with\n    | imp.var x => Some (var x)\n    | imp.con z => Some (con z)\n    | imp.plus e1 e2 => lift2 plus (is_pure_e e1) (is_pure_e e2)\n    | _ => None\n  end.\nFixpoint is_pure_b (b : imp.bexp) : option bexp :=\n  match b with\n    | imp.bcon b => Some (bcon b)\n    | imp.le e1 e2 => lift2 le (is_pure_e e1) (is_pure_e e2)\n    | imp.eql e1 e2 => lift2 eql (is_pure_e e1) (is_pure_e e2)\n    | imp.not e => lift not (is_pure_b e)\n    | imp.and e1 e2 => lift2 and (is_pure_b e1) (is_pure_b e2)\n  end.\n\n(* Defining the semantic notion of satisfaction of a triple,\n   and the proof system *)\nDefinition valid (P : formula) (s : stmt) (Q : formula) : Prop :=\n  forall env, holds P env -> forall n env', trc step_s n (s,env) (skip,env') -> holds Q env'.\n\nDefinition impl P Q := forall env, holds P env -> holds Q env.\n\nFixpoint subst_e x r e :=\n  match e with\n    | var x' => if string_dec x x' then r else e\n    | con _ => e\n    | plus e1 e2 => plus (subst_e x r e1) (subst_e x r e2)\n    | app f e => app f (subst_e x r e)\n  end.\nFixpoint subst x r b :=\n  match b with\n    | bcon _ => b\n    | le e1 e2 => le (subst_e x r e1) (subst_e x r e2)\n    | eql e1 e2 => eql (subst_e x r e1) (subst_e x r e2)\n    | not b1 => not (subst x r b1)\n    | and b1 b2 => and (subst x r b1) (subst x r b2)\n  end.\n\nInductive proof : formula -> stmt -> formula -> Set :=\n  | p_conseq_l : forall P P' Q s, proof P' s Q -> impl P P' -> proof P s Q\n  | p_conseq_r : forall P Q Q' s, proof P s Q' -> impl Q' Q -> proof P s Q\n  | p_assign : forall Q x e0 e, is_pure_e e0 = Some e -> proof (subst x e Q) (assign x e0) Q\n  | p_skip : forall Q, proof Q skip Q\n  | p_seq : forall P Q R s1 s2, proof P s1 Q -> proof Q s2 R -> proof P (seq s1 s2) R\n  | p_cond : forall P b0 b s1 s2 Q, is_pure_b b0 = Some b ->\n          proof (and P b) s1 Q -> proof (and P (not b)) s2 Q ->\n                 proof P (cond b0 s1 s2) Q\n  | p_while : forall P b0 b s, is_pure_b b0 = Some b -> \n     proof (and P b) s P -> proof P (while b0 s) (and P (not b))\n  .\n\n(* Proving soundness requires various lemmas.\n   Relating small-step execution of pure expresions to\n   the evaluation functions takes much of the effort.\n *)\n\n(* relating \"set\" and substitution *)\nLemma eval_e_subst : forall x r e env, eval_e env (subst_e x r e) = eval_e (set env x (eval_e env r)) e.\nProof. induction e;simpl;[unfold set;destruct (string_dec x s);simpl|..];congruence. Qed.\n\nLemma eval_subst : forall x r env e, eval_b env (subst x r e) = eval_b (set env x (eval_e env r)) e.\nProof.\ninduction e;simpl;rewrite ?eval_e_subst;try congruence.\nrewrite IHe1, IHe2; reflexivity.\nQed.\n\nDefinition pure_pres {E Epure : Set} (is_pure : E -> option Epure)\n                     {Res : Set} (eval : Env -> Epure -> Res) e e1 :=\n  match is_pure (fst e) with\n    | Some e' => snd e1 = snd e /\\\n        match is_pure (fst e1) with\n          | Some e1' => eval (snd e) e1' = eval (snd e) e'\n          | None => False\n        end\n    | None => True\n  end.\n\nLemma pure_pres_refl : forall {E Ep} is {R} eval a, @pure_pres E Ep is R eval a a.\nProof. intros;unfold pure_pres. destruct (is (fst a));split;reflexivity. Qed.\nLemma pure_pres_trans : forall {E Ep} is {R} eval a b c,\n   @pure_pres E Ep is R eval a b -> pure_pres is eval b c -> pure_pres is eval a c.\nProof. unfold pure_pres;intros.\n  destruct (is (fst a));[destruct H|trivial]. \n  destruct (is (fst b));[destruct H0|destruct H1].\n  split;[|destruct (is (fst c))];congruence.\nQed.\n\nLemma pure_pres_trc : forall {E Ep} is {R} eval n a b,\n  trc (@pure_pres E Ep is R eval) n a b -> pure_pres is eval a b.\nProof. induction 1;subst;eauto using pure_pres_trans,pure_pres_refl. Qed.\n\nLtac pure_pres_tac := repeat match goal with\n| [H : match is_pure_e ?x with _ => _ end |- _] => destruct (is_pure_e x);simpl;[|destruct H;exact I]\n| [H : match is_pure_b ?x with _ => _ end |- _] => destruct (is_pure_b x);simpl;[|destruct H;exact I]\n| [H : True |- _] => clear H\n| [H : False |- _] => destruct H\n| [H : _ /\\ _ |- _] => destruct H\nend;try (split;congruence).\n\nLemma eval_e_step : forall a b, step_e a b -> pure_pres is_pure_e eval_e a b.\nProof.\ninduction 1;unfold pure_pres in * |- *;simpl in * |- *;pure_pres_tac.\ndestruct (is_pure_e b);simpl;split;congruence.\nQed.\n\nLemma eval_e_result : forall e v n env env', trc step_e n (e, env) (imp.con v, env') ->\n  forall e', is_pure_e e = Some e' -> env' = env /\\ v = eval_e env e'.\nProof.\nintros. apply (map_trc eval_e_step) in H. apply pure_pres_trc in H.\nunfold pure_pres in H;simpl in H;rewrite H0 in H. assumption.\nQed.\n\nLemma eval_b_step : forall a b, step_b a b -> pure_pres is_pure_b eval_b a b.\nProof.\ninduction 1;repeat match goal with [H : step_e _ _ |- _] => apply eval_e_step in H end;\nunfold pure_pres in * |- *;simpl in * |- *;pure_pres_tac;\nmatch goal with [|- match lift _ ?x with _ => _ end] =>\n  destruct x eqn:?;simpl;pure_pres_tac\nend.\ndestruct b;[rewrite Heqo|];split;reflexivity.\nrewrite H1;split;congruence.\nQed.\n\nLemma eval_b_result : forall e v n env env', trc step_b n (e, env) (imp.bcon v, env') ->\n  forall e', is_pure_b e = Some e' -> env' = env /\\ v = eval_b env e'.\nProof.\nintros. apply (map_trc eval_b_step) in H. apply pure_pres_trc in H.\nunfold pure_pres in H;simpl in H;rewrite H0 in H. assumption.\nQed.\n\n(* tactics for working with option *)\nLtac option_lift_cleanup := repeat match goal with\n| [H : lift ?f ?e = Some ?v |- _] => is_var v;\n  destruct e eqn:?;[|discriminate H];injection H;clear H;intro;subst v\n| [H : Some ?e = Some ?v |- _] => is_var v;\n  injection H;clear H;intro;subst v\n| [H : None = Some _ |- _] => discriminate H\n| [H : lift2 ?f ?e1 ?e2 = Some ?v |- _] => is_var v;\n  destruct e1 eqn:?;[simpl in H|discriminate H]\n| [H : forall x, Some _ = Some x -> _ |- _] => specialize (H _ (eq_refl _))\n| [H : forall x, ?e = Some x -> _, H2 : ?e = Some _ |- _] => specialize (H _ H2)\n| [H : _ /\\ _ |- _] => destruct H\n| [H : exists _, _ |- _] => destruct H\nend.\n\n(* Tactics for induction over trc of step -\n   The built-in induction tactics do not usually give useful induction hypotheses\n   if indices of a dependent type have structure, like \"step_e (a,b) (c,d)\".\n   This case should work because every pair has that form, and we help it along by\n   abstracting a given pair to a single variable.\n *)\nLtac prep_trc :=\n  match goal with [H : trc _ _ ?P ?Q |- _] =>\n  remember P as p eqn:Heqp; remember Q as q eqn:Heqq; move Heqq at top; move Heqp at top; move H at top\n  end.\nLtac trc_ind := intros;prep_trc;let rec reverts := match goal with [H : _ |- _] =>\n  match type of H with trc _ _ _ _ => induction H | _ => revert H;reverts end end\nin reverts.\n\nLemma assign_dec : forall x e n env env', trc step_s n (assign x e, env) (skip, env') ->\n  exists v k env'', trc step_e k (e, env) (imp.con v, env'') /\\ (k < n)%nat /\\ set env'' x v = env'.\nProof.\ntrc_ind;intros;subst;[congruence| ].\ninversion H;subst. (* splitting on how assign x e took a step *)\n  (* at last step *)\n  clear IHtrc. inversion H0;subst;[ | inversion H1]. injection H1.\n  repeat eexists;eauto using done.\n  (* stepping in e. *)\n  specialize (IHtrc _ _ _ (eq_refl _) _ (eq_refl _)).\n  destruct IHtrc as (v & k & env''& [? []]). exists v, (S k), env''.\n  intuition. eapply step;eassumption.\nQed.\n\nLemma seq_dec : forall s1 s2 n env env', trc step_s n (seq s1 s2, env) (skip, env') ->\n  exists env'' k1 k2, trc step_s k1 (s1, env) (skip, env'') /\\ trc step_s k2 (s2, env'') (skip, env')\n    /\\ (k1 + k2 < n)%nat.\nProof.\ntrc_ind;intros;subst.\ncongruence.\ninversion H;subst.\n  (* was finished *)\n  clear IHtrc;repeat eexists;eauto using done with arith.\n  (* evaluating statement 1 *)\n  specialize (IHtrc _ _ _ (eq_refl _) _ (eq_refl _)).\n  decompose record IHtrc;clear IHtrc.\n  repeat eexists;eauto using step with arith.\nQed.\n\nLemma cond_dec : forall c s1 s2 n env env', trc step_s n (cond c s1 s2, env) (skip, env') ->\n  exists b env'' k1 k2, trc step_b k1 (c, env) (imp.bcon b, env'') /\\\n       trc step_s k2 (if b then s1 else s2, env'') (skip, env') /\\\n       (k1 + k2 < n)%nat.\nProof.\ntrc_ind;intros;subst;[congruence| ].\ninversion H; clear H; subst.\n  (* was finished *)\n  repeat eexists;eauto using done with arith.\n  (* evaluating in condition *)\n  specialize (IHtrc _ _ _ _ (eq_refl _) _ (eq_refl _)).\n  decompose record IHtrc;clear IHtrc.\n  repeat eexists;eauto using step with arith.\nQed.\n\nInductive while_trace b s env : Env -> Prop :=\n | while_done : eval_b env b = false -> forall env', env' = env -> while_trace b s env env'\n | while_step : eval_b env b = true ->\n     forall n env', trc step_s n (s, env) (skip, env') ->\n     forall env'', while_trace b s env' env'' ->\n        while_trace b s env env''\n .\n\nLemma while_dec : forall n b s env env', trc step_s n (while b s, env) (skip, env') ->\n  forall b', is_pure_b b = Some b' -> while_trace b' s env env'.\nProof.\nintro n. pattern n. apply (well_founded_induction lt_wf). clear n.\nintros.\nmatch goal with [H : trc _ _ _ _  |- _] => inversion H;clear H;subst end. congruence.\nmatch goal with [H : step_s _ _  |- _] => inversion H;clear H;subst end.\nmatch goal with [H : _ |- _] => apply cond_dec in H;decompose record H;clear H end.\nmatch goal with [H : _ |- _] => eapply eval_b_result in H;[|eassumption];destruct H;subst end.\ndestruct (eval_b env b') eqn:?.\n(* loop condition evaluated to true, take a step *)\napply seq_dec in H2;decompose record H2;clear H2.\n  eapply while_step, H;try eassumption. omega.\n(* false, finish now *)\napply while_done. assumption.\ninversion H2;[|solve[inversion H0]];congruence.\nQed.\n\nLemma sound : forall P s Q, proof P s Q -> valid P s Q.\ninduction 1;unfold valid in * |- *;simpl;intros.\n(* conseq l *)\neauto.\n(* conseq r *) \neauto.\n(* assign *)\napply assign_dec in H0;decompose record H0;clear H0.\neapply eval_e_result in H2;[|eassumption]. destruct H2. subst.\nunfold holds. rewrite <- eval_subst. assumption.\n(* skip *)\ninversion H0;subst. congruence. inversion H1.\n(* seq *)\nspecialize (IHproof1 _ H1); clear H1.\napply seq_dec in H2. decompose record H2;clear H2.\n  specialize (IHproof1 _ _ H3). specialize (IHproof2 _ IHproof1 _ _ H1). assumption.\n(* cond *)\napply cond_dec in H2;decompose record H2;clear H2.\neapply eval_b_result in H3;[|eassumption];destruct H3;subst.\nrevert H4. destruct (eval_b env b) eqn:?;[apply IHproof1|apply IHproof2];\nunfold holds;simpl;rewrite H1, Heqb1;reflexivity.\n(* while *)\neapply while_dec in H1;[|eassumption]. induction H1.\nsubst env'. unfold holds. simpl. rewrite H1, H0. reflexivity.\napply IHproof in H2. auto. unfold holds. simpl. rewrite H0. assumption.\nQed.\n\nRequire Import example.\n\nDefinition zero_loop_pf : proof (le (con 0) (var \"x\"))\n                                zero_loop\n           (and (le (con 0) (var \"x\")) (le (var \"x\") (con 0))).\neapply p_conseq_r.\neapply p_while. reflexivity.\neapply p_conseq_l.\neapply p_assign. reflexivity.\nLtac pre_impl := let env := fresh \"env\" in intro env; unfold holds; simpl;\n  repeat match goal with [|- context[env ?v]] => generalize (env v);intro end;clear env.\npre_impl. destruct (Z.leb_spec 0 z);[|discriminate]. rewrite ?Z.leb_le. auto with zarith.\npre_impl. destruct (Z.leb_spec 0 z);[|discriminate]. rewrite Bool.negb_true_iff, ?Z.leb_le, ?Z.leb_gt.\n  auto with zarith.\nDefined.\n\nLemma zero_loop : valid (le (con 0) (var \"x\")) (while (imp.le (imp.con 1) (imp.var \"x\"))\n                                          (assign \"x\" (imp.plus (imp.var \"x\") (imp.con (-1)))))\n           (and (le (con 0) (var \"x\")) (le (var \"x\") (con 0))).\nProof. exact (sound zero_loop_pf). Qed.\n\nSection sum_code.\nImport imp.\nLocal Coercion con : Z >-> exp.\nLocal Coercion var : string >-> exp.\n\nDefinition sum_loop' : stmt :=\n  seq (while (not (eql \"n\" 0)) (seq (assign \"n\" (plus \"n\" (-1)))\n                                    (assign \"s\" (plus \"s\" \"n\"))))\n      (assign \"n\" (plus \"n\" (-1))).\nEnd sum_code.\n\nLemma bool_if : forall (a b c d : bool),\n  ((if a then b else c) = d) <-> (a = true /\\ b = d) \\/ (a = false /\\ c = d).\nProof. destruct a;intuition congruence. Qed.\n\nLemma diff_false_true_iff : false = true <-> False.\nProof. pose proof Bool.diff_true_false. intuition. Qed.\nLemma and_false : forall P, (P /\\ False) <-> False.\nProof. tauto. Qed.\nLemma or_false : forall P, (P \\/ False) <-> P.\nProof. tauto. Qed.\n\nLocal Coercion con : Z >-> exp.\nLocal Coercion var : string >-> exp.\n\nDefinition sum_pf : proof (and (le 0 \"n\") (eql (plus \"s\" (app sum_to (plus \"n\" (-1))))\n                                               (plus \"S\" (app sum_to \"N\"))))\n                          sum_loop'\n                          (eql (var \"s\") (plus (var \"S\") (app sum_to (var \"N\")))).\nProof.\neapply p_seq;[|eapply p_assign;reflexivity].\neapply p_conseq_r.\neapply p_while;[reflexivity|].\neapply p_seq;[|eapply p_assign;reflexivity];eapply p_conseq_l;[eapply p_assign;reflexivity|].\n\nsimpl. pre_impl.\nrewrite ?bool_if, ?Bool.negb_true_iff, ?Bool.negb_false_iff, ?diff_false_true_iff,\n  ?and_false, ?or_false,\n  ?Z.eqb_eq, ?Z.eqb_neq, ?Z.leb_le, ?Z.leb_gt.\n  intuition.  rewrite <- H2;clear H2.\nrewrite (sum_to_equation (z + -1)).\ndestruct (Z.ltb_spec (z + -1) 0);[exfalso|];auto with zarith.\n\nsimpl. pre_impl.\nrewrite ?bool_if, ?Bool.negb_true_iff, ?Bool.negb_false_iff, ?diff_false_true_iff,\n  ?and_false, ?or_false,\n  ?Z.eqb_eq, ?Z.eqb_neq, ?Z.leb_le, ?Z.leb_gt.\n  intuition.  rewrite <- H2;clear H2.\nsubst. rewrite sum_to_equation. simpl. auto with zarith.\nQed.", "meta": {"author": "Formal-Systems-Laboratory", "repo": "coinduction", "sha": "1031da11c4a4523ea9b7347036b6bdabc7620e1d", "save_path": "github-repos/coq/Formal-Systems-Laboratory-coinduction", "path": "github-repos/coq/Formal-Systems-Laboratory-coinduction/coinduction-1031da11c4a4523ea9b7347036b6bdabc7620e1d/coinduction-proofs/imp/hoare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7988357793052759}}
{"text": "Require Import Ensembles. \nRequire Import Coq.Setoids.Setoid.\n\nVariable U : Type.\n\nTheorem distri_and_over_or : forall p q r : Prop, (p /\\ (q \\/ r)) <-> ((p /\\ q) \\/ (p /\\ r)).\n\nProof.\nintros.\nsplit.\nintro.\ndestruct H as (H0,H1).\ndestruct H1 as [H3|H3].\nleft.\nsplit.\nassumption.\nassumption.\nright.\nsplit.\nassumption.\nassumption.\n\nintro.\ndestruct H as [H4|H4].\nsplit.\ndestruct H4 as (H5,H6).\nassumption.\nleft.\ndestruct H4 as (H5,H6).\nassumption.\n\nsplit.\ndestruct H4 as (H5,H6).\nassumption.\nright.\ndestruct H4 as (H5,H6).\nassumption.\nQed.\n\nTheorem IntersectionToAnd : forall A B : Ensemble U, forall x : U,\n   In U (Intersection U A B) x <-> (In U A x) /\\ (In U B x).\nProof.\nintros.\nsplit.\nintro.\ndestruct H.\nsplit.\nassumption.\nassumption.\nintro.\ndestruct H.\nsplit.\nassumption.\nassumption.\nQed.\n\nTheorem UnionToOr : forall A B : Ensemble U, forall x : U,\n   In U (Union U A B) x <-> (In U A x) \\/ (In U B x).\n\nProof.\nintros.\nsplit.\nintro.\ndestruct H.\nleft.\nassumption.\nright.\nassumption.\nintro.\ndestruct H.\nleft.\nassumption.\nright.\nassumption.\nQed.\n\n\nTheorem SetDistri : forall A B C : Ensemble U,\n             Intersection U A (Union U B C) =\n             Union U (Intersection U A B) (Intersection U A C). \nProof.\nintros.\napply Extensionality_Ensembles.\n\nsplit.\n\nintro. intro.\ndestruct H.\ndestruct H0.\nleft.\nsplit.\nassumption.\nassumption.\n\napply UnionToOr.\nright.\napply IntersectionToAnd.\nsplit.\nassumption.\nassumption.\n\nsplit.\napply UnionToOr in H.\ndestruct H.\ndestruct H.\nassumption.\ndestruct H.\nassumption.\n\ndestruct H.\ndestruct H.\nleft.\nassumption.\ndestruct H.\nright.\nassumption.\n\nQed.\n\nVariable A : Ensemble U.\nVariable B : nat -> (Ensemble U).\n\nFixpoint unionB (n : nat) : Ensemble U :=\n  match n with\n  | 0   => B 0\n  | S m => Union U (unionB m) (B (S m))\n  end.\n\nFixpoint intersectionAB (n : nat) : Ensemble U :=\n  match n with\n  | 0   => Intersection U A (B 0) \n  | S m => Union U (intersectionAB m) (Intersection U A (B (S m)))\n  end.\n\nTheorem generalizedSetDistri :\n        forall n : nat, intersectionAB n = Intersection U A (unionB n).\nProof.\n\nintro.\napply Extensionality_Ensembles.\ninduction n.\n\nsplit.\nsplit.\ndestruct H.\nassumption.\ndestruct H.\napply H0.\n\nsplit.\ndestruct H.\nassumption.\ndestruct H.\napply H0.\n\nsplit.\nsplit.\ndestruct H.\napply IHn in H.\ndestruct H.\nassumption.\ndestruct H.\nassumption.\ndestruct H.\napply IHn in H.\ndestruct H.\nleft.\nassumption.\ndestruct H.\nright.\nassumption.\n\nintro.\nintro.\nright.\nconstructor 1.\ndestruct H.\nassumption.\ndestruct H.\ndestruct H0.\n\n(* alt attempt *)\nintro.\nintro.\nleft.\n\napply IHn.\nsplit.\ndestruct H.\nassumption.\ndestruct H.\ndestruct H0.\nassumption.\n\n(*alt attempt*)\n(* to be completed *)\n\n\nQed.\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/lab6/lab6_task5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7988357769094796}}
{"text": "From LF Require Export Basics.\n\n\n(* Proof by Induction *)\n\nTheorem plus_n_O : 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,\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, n * 0 = 0.\nProof.\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.\n  induction n as [| n' IHn' ].\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 m.\n  induction n as [| n' IHn'].\n  - simpl. rewrite <-plus_n_O. reflexivity.\n  - 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'].\n  - rewrite plus_O_n. simpl. reflexivity.\n  - simpl. rewrite IHn'. 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 : 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\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'. rewrite -> negation_fn_applied_twice.\n    + simpl. reflexivity.\n    + reflexivity.\nQed.\n\n(* Proofs within Proofs *)\n", "meta": {"author": "chrisnevers", "repo": "software-foundations", "sha": "f5936d8f37c637349a6ba3d0f29923fe70e43553", "save_path": "github-repos/coq/chrisnevers-software-foundations", "path": "github-repos/coq/chrisnevers-software-foundations/software-foundations-f5936d8f37c637349a6ba3d0f29923fe70e43553/logical-foundations/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7987043101046218}}
{"text": "Require Import Arith.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import List.\nRequire Import Recdef.\n\n(**\n  Arithmétique\n*)\n\n(* Sur la soustraction (entière) *)\nLemma minus_Sn_n : forall (n:nat), (minus (S n) n) = (S 0).\ninduction n; auto.\nQed.\n\nLemma lt_S_r : forall (n1 n2:nat),\n  (lt n1 n2) -> exists (n:nat), n2 = (S n).\ndestruct n2.\n  intro. exfalso. apply (lt_n_0 n1). assumption.\n  intro. exists n2. trivial.\nQed.\n\nLemma minus_lt_S : forall (n1 n2:nat),\n  (lt n1 n2) -> exists (n:nat), (minus n2 n1) = (S n).\nintros. elim (lt_S_r n1 n2 H). intros n H1. rewrite H1.\nexists (minus n n1). rewrite minus_Sn_m.\n  trivial.\n  apply le_S_n. rewrite H1 in H. auto.\nQed.\n\n(* Sur l'ordre strict 'lt' *)\nLemma lt_1_0 : forall (n:nat), (lt n 1) -> (n=0).\ndestruct n.\n  auto.\n  intro. inversion H. exfalso. apply (le_Sn_0 (S n)). assumption.\nQed.\n\nLemma lt_S_case : forall (m n:nat), (lt m (S n)) -> (lt m n) \\/ (m=n).\nintros m n. generalize m. induction n.\n  intros. rewrite (lt_1_0 m0 H). tauto.\n  destruct m0.    \n    intro. auto with arith.\n    intro. elim IHn with (m:=m0); auto with arith.\nQed.\n\nLemma not_lt_Sn_n : forall (n:nat), not (lt (S n) n).\ninduction n.\n  auto with arith.\n  intro. auto with arith.\nQed.\n\n(* Sur l'ordre large 'le' *)\nLemma not_le_Sn_n : forall (n:nat), not (le (S n) n).\ninduction n.\n  auto with arith.\n  intro. auto with arith.\nQed.\n\n(* Cas sur les entiers *)\nLemma nat_compare_case : forall (n1 n2:nat),\n (lt n1 n2) \\/ (n1=n2) \\/ (lt n2 n1).\ninduction n1.\n  destruct n2.\n    tauto.\n    left. auto with arith.\n  destruct n2.\n    right. right. auto with arith.\n    elim (IHn1 n2).\n      intro. left. auto with arith.\n      intro. elim H.\n        intro. right. left. auto.\n        intro. right. right. auto with arith.\nQed.\n\n(**\n  Sur les listes\n*)\n\n(* Sur la longueur. *)\nLemma length_0_nil : forall (w:(list nat)),\n  (length w)=0 -> w=nil.\ndestruct w.\n  auto.\n  intro. discriminate H.\nQed.\n\nLemma length_Sn_cons : forall (w:(list nat)) (n:nat),\n  (length w)=(S n) -> exists (a:nat) (w':(list nat)), w = (cons a w').\ndestruct w.\n  intros. discriminate H.\n  intros. exists n. exists w. trivial.\nQed.\n\n(* Principe d'induction sur la longueur des listes *)\nLemma list_length_ind_S : forall (P: (list nat) -> Prop),\n  (P nil)\n  -> (forall (n:nat), (forall (xs:(list nat)), (lt (length xs) (S n)) -> (P xs))\n                      -> forall (xs:(list nat)), (length xs)=(S n) -> (P xs))\n  -> forall (n:nat) (xs:(list nat)), (lt (length xs) (S n) -> (P xs)).\nintros P P0 Plt. induction n.\n  intros. assert (xs=nil).\n    apply length_0_nil. apply lt_1_0. assumption.\n    rewrite H0. assumption.\n  intros. elim (lt_S_case (length xs) (S n) H).\n    auto.\n    intro. apply (Plt n); auto.\nQed.\n\nLemma list_length_ind : forall (P: (list nat) -> Prop),\n  (P nil)\n  -> (forall (n:nat), (forall (xs:(list nat)), (lt (length xs) (S n)) -> (P xs))\n                      -> forall (xs:(list nat)), (length xs)=(S n) -> (P xs))\n  -> forall (xs:(list nat)), (P xs).\nintros. apply list_length_ind_S with (n:=(length xs)).\n  assumption.\n  assumption.\n  auto with arith.\nQed.\n\n(* Extension d'une liste avec des 0 (en tête) *)\nFixpoint zs (n:nat) : (list nat) :=\n  match n with\n      0 => nil\n    | (S n) => (cons 0 (zs n))\n  end.\n\nLemma zs_len: forall (n:nat), (length (zs n))=n.\ninduction n.\n  auto.\n  simpl. rewrite IHn. trivial.\nQed.\n\n(* Complétion d'une liste en fonction d'une autre. \n   Le résultat est une liste de la longueur de la\n   plus grande.                                   *)\nDefinition dist (w1:(list nat)) (w2:(list nat)) :=\n  (minus (length w1) (length w2)).\n\nDefinition padd (w1:(list nat)) (w2:(list nat)) :=\n  (app (zs (dist w2 w1)) w1).\n\nLemma padd_len_lt_cons : forall (w1 w2:(list nat)),\n  (lt (length w1) (length w2)) \n  -> exists (w:(list nat)), (padd w1 w2)=(cons 0 w).\nintros. unfold padd. unfold dist. \nelim (minus_lt_S (length w1) (length w2) H).\nintros. rewrite H0. simpl. exists (app (zs x) w1). trivial.\nQed.\n\nLemma padd_len_le_len : forall (w1 w2:(list nat)),\n  (le (length w1) (length w2))\n  -> (length (padd w1 w2)) = (length w2).\nintros. unfold padd. unfold dist. rewrite app_length.\nrewrite zs_len. rewrite plus_comm. \nrewrite le_plus_minus with (n:=(length w1)); trivial.\nQed.\n\nLemma padd_cons_0 : forall (w1 w2:(list nat)) (a:nat),\n  (length w1) = (length w2) -> (padd w1 (cons a w2)) = (cons 0 w1).\nintros. unfold padd. unfold dist. rewrite H. simpl length. \nrewrite (minus_Sn_n (length w2)). simpl. trivial.\nQed.\n\n(**\n  Sur l'accessibilité.\n  Tribute to P. Casteran: \n      http://www.labri.fr/perso/casteran/Cantor/HTML/AccP.html#AccElim3\n*)\nTheorem AccElim2 :\nforall (A B:Set) \n       (RA: A -> A -> Prop) (RB: B -> B -> Prop),\n forall (P : A -> B -> Prop),\n (forall x y,\n    (forall (t : A), RA t x -> forall y', Acc RB y' -> P t y') ->\n    (forall (t : B), RB t y -> P x t) -> \n    (P x y)) ->\n  forall x y, Acc RA x -> Acc RB y -> P x y.\nProof.\n intros A B RA RB P H x y Ax; generalize y; clear y.\n elim Ax. clear Ax x; intros x HAccx Hrecx y Ay.\n elim Ay. clear Ay y. intros y HAccy Hrecy. apply H.\n   auto.   \n   auto.\nQed.\n\n(**\n  Relation d'ordre sur les listes d'entiers considérés comme des\n  ordinaux (formes normales de Cantor à exposants finis).\n*)\nInductive wlt : (list nat) -> (list nat) -> Prop :=\n  wlt_nil : forall (a:nat)(w:(list nat)), (wlt nil (cons (S a) w))\n| wlt_0_w : forall (w1 w2:(list nat)), (wlt w1 w2) -> (wlt (cons 0 w1) w2)\n| wlt_w_0 : forall (w1 w2:(list nat)), (wlt w1 w2) -> (wlt w1 (cons 0 w2))\n| wlt_len : forall (w1 w2:(list nat)) (a1 a2:nat),\n   (length w1 < length w2) -> (wlt (cons (S a1) w1) (cons (S a2) w2))\n| wlt_lt :  forall (w1 w2:(list nat)) (a1 a2:nat),\n  (length w1 = length w2) -> (lt a1 a2) \n    -> (wlt (cons (S a1) w1) (cons (S a2) w2))\n| wlt_wlt : forall (w1 w2:(list nat)) (a:nat),\n  (length w1 = length w2) ->  (wlt w1 w2) \n    -> (wlt (cons (S a) w1) (cons (S a) w2)).\n\n(* 'nil' est minimal *)\nLemma not_wlt_nil : forall (w:(list nat)), \n  not (wlt w nil).\ninduction w.\n  intro. inversion H.\n  case a.\n   intro. inversion H. auto.\n   intro. intro. inversion H.\nQed.\n\n(* Lemmes d'inversion *)\nLemma wlt_0_w_inv: forall (w1 w2:(list nat)),\n  (wlt (cons 0 w1) w2) -> (wlt w1 w2).\ninduction w2.\n  intros. absurd (wlt (cons 0 w1) nil).\n    apply (not_wlt_nil (cons 0 w1)).\n    assumption.\n  intro. inversion H.\n    assumption.\n    apply wlt_w_0. auto.\nQed.\n\nLemma wlt_w_0_inv: forall (w1 w2:(list nat)),\n  (wlt w1 (cons 0 w2)) -> (wlt w1 w2).\ninduction w1.\n  intros. inversion H. assumption.\n  intros. inversion H. \n    apply wlt_0_w. auto.\n    assumption.\nQed.\n\n(* Autres résultats négatifs *)\nLemma not_wlt_len_left : forall (w1 w2:(list nat)) (a:nat),\n  (le (length w2) (length w1)) -> not (wlt (cons (S a) w1) w2).\ninduction w2.\n\n  intros. apply not_wlt_nil.\n\n  intros. destruct a.\n    intro. absurd (wlt (cons (S a0) w1) w2).\n      apply IHw2. \n        apply le_trans with (m:=(length (cons 0 w2))).\n          auto with arith.\n          assumption.\n        apply wlt_w_0_inv. assumption.\n    intro. inversion H0.\n      assert (lt (length (cons (S a) w2)) (length w2)).\n        apply le_lt_trans with (m := (length w1)); assumption.\n        apply (not_lt_Sn_n (length w2)). assumption.      \n      rewrite H4 in H. apply (not_le_Sn_n (length w2)); assumption.\n      rewrite H4 in H. apply (not_le_Sn_n (length w2)); assumption.\nQed.\n\nLemma not_wlt_Sn_0 : forall (w1 w2:(list nat)) (a:nat),\n  (length w1) = (length w2) -> not (wlt (cons (S a) w1) (cons 0 w2)).\nintros. intro. inversion H0. \n  apply (not_wlt_len_left w1 w2 a). \n    rewrite H. auto with arith.\n    apply wlt_w_0_inv. assumption.  \nQed.\n\nLemma not_wlt_len: forall (w1 w2:(list nat)) (a:nat),\n  (length w2 <= length w1) -> not (wlt (cons (S a) w1) w2).\ninduction w2.\n  intros. intro. exfalso. apply (not_wlt_nil (cons (S a) w1)). assumption.\n  intro. case a.\n    intro. intro. apply IHw2 with (a:=a0).\n      apply le_trans with (m:=(length (cons 0 w2))).\n        simpl. auto with arith.\n        assumption.\n      apply wlt_w_0_inv. assumption.\n    intros. intro. inversion H0.\n      apply (lt_irrefl (length w1)).\n        simpl in H. apply lt_trans with (m:=(length w2)); assumption.\n      rewrite H4 in H. apply (le_Sn_n (length w2)). assumption.\n      rewrite H4 in H. apply (le_Sn_n (length w2)). assumption.\nQed. \n\n(* Invariance de 'wlt' pour la complétion à 0 (en tête) *)\nLemma wlt_wlt_zs_right : forall (n:nat) (w1 w2:(list nat)),\n  (wlt w1 w2) -> (wlt w1 (app (zs n) w2)).\ninduction n.\n  auto.\n  intros. simpl. apply wlt_w_0. auto.\nQed.\n\nLemma wlt_zs_wlt_right : forall (n:nat) (w1 w2:(list nat)),\n  (wlt w1 (app (zs n) w2)) -> (wlt w1 w2).\ninduction n.\n  auto.\n  simpl. intros. apply IHn. apply wlt_w_0_inv. assumption.\nQed.\n\nLemma wlt_wlt_zs_left : forall (n:nat) (w1 w2:(list nat)),\n  (wlt w1 w2) -> (wlt (app (zs n) w1) (w2)).\ninduction n.\n  auto.\n  intros. simpl. apply wlt_0_w. auto.\nQed.     \n\n(* Caractérisation en fonction de la longueur:\n   si '(wlt w1 w2)' et '#w2 < #w1' alors 'w1' commence par des 0 *)\nLemma wlt_gt_length : forall (w1 w2:(list nat)),\n  (wlt w1 w2) -> (lt (length w2) (length w1))\n  -> exists (n:nat) (w:(list nat)),\n       (w1 = (app (zs n) w))\n       /\\ (length w)=(length w2)\n       /\\ (wlt w w2).\ninduction w1.\n\n  intros. exfalso. apply (lt_n_0 (length w2)). auto.\n\n  intros. simpl in H0. assert (length w2 <= length w1).\n    apply lt_n_Sm_le. assumption.\n    destruct a.\n      elim (le_lt_or_eq (length w2) (length w1) H1).\n        intro. elim IHw1 with (w2:=w2).\n          intros z H3. elim H3. intros w1' H4. decompose [and] H4.\n          exists (S z). exists w1'. split.\n              simpl. rewrite H5. trivial.\n              tauto.\n          apply wlt_0_w_inv. assumption. \n         assumption.\n        intro. exists (S 0). exists w1. split.\n          simpl. trivial.\n          split. \n            rewrite H2. trivial.\n            apply wlt_0_w_inv. assumption.\n      exfalso. apply (not_wlt_len w1 w2 a); assumption.\nQed.\n   \n(**\n   Restriction de l'ordre aux listes de même longueur.\n   (avec complémentation possible à 0): \n   c'est l'ordre lexicographique.\n*)\n(* La relation sur les listes de même longueur *)\nInductive wlt_pad : (list nat) -> (list nat) -> Prop :=\n  wlt_pad_len : forall (a:nat) (w1 w2:(list nat)),\n    (le (length w1) (length w2)) ->\n     (wlt_pad (padd  w1 (cons (S a) w2)) (cons (S a) w2))\n| wlt_pad_lt : forall (a1 a2:nat) (w1 w2:(list nat)),\n    (length w1) = (length w2) -> (lt a1 a2) ->\n     (wlt_pad (cons (S a1) w1) (cons (S a2) w2))\n| wlt_pad_wlt_pad : forall (a:nat) (w1 w2:(list nat)),\n    (length w1) = (length w2) -> (wlt_pad w1 w2) ->\n     (wlt_pad (cons a w1) (cons a w2)).\n\n(* Relations entre l'ordre sur toute liste et l'ordre restreint. *)\nLemma wlt_wlt_pad : forall (w1 w2:(list nat)),\n  (length w1) = (length w2) -> (wlt w1 w2)\n  -> (wlt_pad w1 w2).\nintros w1 w2. generalize w1. clear w1. induction w2.\n\n  intros. exfalso. apply (not_wlt_nil w1). assumption.\n\n  destruct w1.\n\n    intros. discriminate H.       \n\n    intros. inversion H0.\n    (* 1: wlt_0_w *)\n    destruct a.\n      apply wlt_pad_wlt_pad.\n        auto.\n        apply IHw2.\n          auto.\n          apply wlt_w_0_inv. assumption. \n      rewrite <- (padd_cons_0 w1 w2 a). \n        apply wlt_pad_len. injection H. intro. rewrite H5. auto with arith.\n        auto.\n    (* 2: wlt_w_0 *)\n    destruct n.    \n      apply wlt_pad_wlt_pad.\n        auto with arith.\n        apply IHw2.\n          auto with arith.\n          apply wlt_w_0_inv. apply wlt_0_w_inv. rewrite <- H1 in H0. assumption.\n      exfalso. apply (not_wlt_Sn_0 w1 w2 n). \n        auto with arith.\n        rewrite <- H1 in H0. assumption.\n    (* 3 *)\n    exfalso. apply (lt_irrefl (length w2)). injection H.\n    intro. rewrite H6 in H2. assumption.\n    (* 4 *)\n    apply wlt_pad_lt.\n      auto with arith.\n      assumption.\n    (* 5 *)\n    apply wlt_pad_wlt_pad.  \n      auto with arith.\n      apply IHw2.\n        auto with arith.\n        assumption.\nQed.\n\nLemma wlt_wlt_pad_zs : forall (w1 w2:(list nat)),\n  (length w1) < (length w2) -> (wlt w1 w2)\n  -> (wlt_pad (padd w1 w2) w2).\nintros. apply wlt_wlt_pad. \n  apply padd_len_le_len. auto with arith.\n  apply wlt_wlt_zs_left. assumption. \nQed.\n  \n(**\n  Accessibilité pour l'ordre restreint.\n*)\nLemma Acc_wlt_pad_ind : forall (n:nat),\n  (forall (w:(list nat)), (lt (length w) (S n)) -> Acc wlt_pad w) \n    -> forall (w:(list nat)), (length w)=(S n) -> Acc wlt_pad w. \nintros. elim (length_Sn_cons w n H0). intros a H1. elim H1. clear H1.\nintros w' H1. rewrite H1. rewrite H1 in H0. clear H1. generalize H0. \npattern a, w'.\napply AccElim2 with (RA:=lt) (RB:=wlt_pad).\n \n  intros a' w'' H1 H2 H3. apply Acc_intro. intros w''' H4.\n  inversion H4.   \n\n    elim (padd_len_lt_cons  w1 (cons (S a0) w'')).\n      intros w0 H9. rewrite H9. apply H1.  \n        rewrite <- H5. auto with arith.    \n        apply H.    \n          assert (lt (length (cons 0 w0)) (S (S n))).        \n            rewrite <- H9. rewrite padd_len_le_len.\n              rewrite H5. rewrite H3. auto with arith.\n              simpl. auto with arith.\n            auto with arith.\n          rewrite <- H9. rewrite padd_len_le_len. \n            rewrite H5. assumption.\n            simpl. auto with arith.\n      simpl. auto with arith.\n\n    apply H1.\n      rewrite <- H5. auto with arith.\n      apply H.\n        rewrite H8. rewrite <- H3. auto with arith.\n      simpl. rewrite H8. auto.\n\n    apply H2.\n      assumption.\n      simpl. rewrite H8. auto.\n\n  apply lt_wf.\n\n  apply H.\n    rewrite <- H0. auto with arith.\n\nQed.\n\nLemma Acc_wlt_pad_nil : (Acc wlt_pad nil).\napply Acc_intro. intros. inversion H.\nQed.\n\nLemma Acc_wlt_pad : forall (w:(list nat)), (Acc wlt_pad w).\ninduction w using list_length_ind.\n  apply Acc_wlt_pad_nil.\n  apply Acc_wlt_pad_ind with (n:=n); assumption.\nQed.\n\n(**\n  De l'accessibilté pour l'ordre restreint à l'accessibilité\n  pour l'ordre sur tout liste.\n*)\nLemma Acc_wlt_zs_Acc_wlt : forall (n:nat) (w:(list nat)),\n  (Acc wlt (app (zs n) w)) -> (Acc wlt w).\nintros. apply Acc_intro. intros w' H0. apply H.\napply wlt_wlt_zs_right. assumption.\nQed.\n\nLemma Acc_wlt_Acc_wlt_zs : forall (n:nat) (w:(list nat)),\n  (Acc wlt w) -> (Acc wlt (app (zs n) w)).\nintros. apply Acc_intro. intros w' H0. apply H. \napply wlt_zs_wlt_right with (n:=n). assumption.\nQed.\n\nLemma Acc_wlt_pad_Acc_wlt : forall (w:(list nat)),\n  (Acc wlt_pad w) -> (Acc wlt w).\nintros. elim H. intros w' H0 H1. apply Acc_intro.\nintros w'' H2. elim (nat_compare_case (length w'') (length w')).\n  (* #w'' < #w' *)\n  intro. apply Acc_wlt_zs_Acc_wlt with (n:=(dist w' w'')).\n  apply H1. apply wlt_wlt_pad_zs; assumption.\n  (* #w'' = #w4 \\/ #w' < #w'' *)\n  intro. elim H3.\n    (* #w'' = #w' *)\n    intro. apply H1. apply wlt_wlt_pad; assumption.\n    (* #w' < #w'' *)\n    intro. elim (wlt_gt_length w'' w' H2 H4). intros a H5.\n    elim H5. intro w0. intro. decompose [and] H6.\n    rewrite H7. apply Acc_wlt_Acc_wlt_zs. apply H1.\n    apply wlt_wlt_pad; assumption.\nQed.\n\n(**\n  L'ordre sur toute liste est bien fondé !\n*)\nTheorem Acc_wlt : forall (w:(list nat)), (Acc wlt w).\nintro. apply Acc_wlt_pad_Acc_wlt.\napply Acc_wlt_pad.\nQed.\n\n(**\n   Sur wlt\n*)\nLemma wlt_len_gen : forall (w1 w2:list nat) (a:nat),\n  (lt (length w1) (length (cons (S a) w2))) -> (wlt w1 (cons (S a) w2)).\ninduction w1.\n  intros. apply wlt_nil.\n  intros. destruct a. \n    apply wlt_0_w. apply IHw1. apply lt_trans with (m:=(length (cons 0 w1))).\n      auto with arith.\n      assumption.\n    apply wlt_len. auto with arith.\nQed.\n\nLemma wlt_lt_gen : forall (a1 a2:nat) (w1 w2:list nat),\n  (length w1) = (length w2) -> (lt a1 a2) \n    -> (wlt (cons a1 w1) (cons a2 w2)).\nintros. destruct a2.\n  exfalso. apply (lt_n_0 a1). assumption.\n  destruct a1.\n    apply wlt_0_w. apply wlt_len_gen. rewrite H. auto with arith.\n    apply wlt_lt; auto with arith.\nQed.\n\nLemma wlt_wlt_gen : forall (a:nat) (w1 w2:list nat),\n  (length w1) = (length w2) -> (wlt w1 w2) \n  -> (wlt (cons a w1) (cons a w2)).                                 \ndestruct a.\n  intros. apply wlt_0_w. apply wlt_w_0. assumption.\n  intros. apply wlt_wlt; assumption.\nQed.\n\nLemma wlt_wf_ind : forall (P: (list nat) -> Prop),\n  (forall (w1:list nat), (forall (w2:list nat), (wlt w2 w1) -> P w2) -> P w1)\n  -> forall (w:list nat), P w.\nintros. apply well_founded_ind with (R:=wlt).\n  unfold well_founded. apply Acc_wlt.\n  intros. apply H. assumption.\nQed.\n\n(* Utilitaire pour la définition des ordres *)\nDefinition make_mwlt (A:Set) (m : A -> list nat) (a1 a2:A) :=\n  (wlt (m a1) (m a2)).\n \n(** Un ordre basé sur une mesure ordinale est bien fondé *)\nLemma Acc_wlt_eq : \n  forall (A:Set) (m: A -> list nat) (w:list nat) (x:A) , \n    w = (m x) -> (Acc (fun x1 x2 : A => wlt (m x1) (m x2)) x).\ninduction w using wlt_wf_ind. intros. apply Acc_intro. intros.\n  apply H with (w2:=(m y)).\n    rewrite H0. assumption.    \n    trivial.\nQed.\n\nLemma Acc_mwlt : forall (A:Set) (m: A -> list nat),\n  forall (x:A), (Acc (fun x1 x2 => (wlt (m x1) (m x2))) x).\nintros. apply Acc_wlt_eq with (w:=(m x)). trivial.\nQed.\n\n(**\n  Applications avec Program Fixpoint\n*)\nRequire Coq.Program.Wf.\n\n(* Tactique pour les preuves de bonne fondation. *)\nLtac by_Acc_mwlt mwlt := \n  unfold Wf.MR; unfold well_founded; intros; unfold mwlt; apply Acc_mwlt.\n\n(* Ordre lexicographique sur les entiers *)\nDefinition wm_natxnat (xy:nat*nat) :=\n  match xy with\n    (x,y) => (cons x (cons y nil))\n  end.\n\nDefinition lex_natxnat :=\n  (make_mwlt (nat*nat) wm_natxnat).\n\nLemma lex_natxnat_fst : forall (x1 y1 x2 y2:nat),\n  (lt x1 x2) -> (lex_natxnat (x1,y1) (x2,y2)).\nintros. unfold lex_natxnat. unfold make_mwlt. simpl.\napply wlt_lt_gen; auto.\nQed.\n\nLemma lex_natxnat_snd : forall (x y1 y2:nat),\n  (lt y1 y2) -> (lex_natxnat (x,y1) (x,y2)). \nintros. unfold lex_natxnat. unfold make_mwlt. simpl.\napply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto.\nQed.\n\nProgram Fixpoint ack_like (xy:nat*nat) {wf lex_natxnat xy} : nat :=\n  match xy with\n    (0, y) => (S y)\n  | (S x, 0) => (ack_like (x, S 0))\n  | (S x, S y) => (ack_like (x, (x + y))) +  (ack_like (S x, y))\n  end.\n\nObligation 1.\napply lex_natxnat_fst.\nauto with arith.\nQed.\n\nObligation 2.\napply lex_natxnat_fst.\nauto with arith.\nQed.\n\nObligation 3. \napply lex_natxnat_snd.\nauto with arith.\nQed.\n\nObligation 4.\nby_Acc_mwlt lex_natxnat.\nDefined.\n\nProgram Fixpoint ack (xy:nat*nat) {wf lex_natxnat xy} : nat :=\n  match xy with\n    (0, y) => (S y)\n  | (S x, 0) => (ack (x, S 0))\n  | (S x, S y) => (ack (x, ack (S x, y)))\n  end.\n \nObligation 1.\napply lex_natxnat_fst.\nauto with arith.\nQed.\n\nObligation 2.\napply lex_natxnat_snd.\nauto with arith.\nQed.\n\nObligation 3.\napply lex_natxnat_fst. inversion Heq_xy. auto with arith.\nQed.\n\nObligation 4.\nby_Acc_mwlt lex_natxnat.\nDefined.\n\n(* Ordre lexicographique sur les longueurs des listes *)\nDefinition wm_listxlist (A:Set) (xys: list A * list A) :=\n  match xys with\n    (xs,ys) => (wm_natxnat (length xs, length ys))\n  end.\n\nDefinition lex_listxlist (A:Set) :=\n  (make_mwlt (list A * list A) (wm_listxlist A)).\n\nParameter ltb : nat -> nat -> bool.\n\nProgram Fixpoint merge (xys: list nat * list nat) {wf (lex_listxlist nat) xys} : list nat :=\n  match xys with\n      (nil, ys) => ys\n    | (xs, nil) => xs\n    | (cons x xs, cons y ys) =>\n      if (ltb x y) then (cons x (merge (xs, (cons y ys))))\n      else (cons y (merge ((cons x xs), ys)))\n  end.\n\nObligation 1.\nunfold lex_listxlist. unfold make_mwlt. simpl. \napply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lex_listxlist. unfold make_mwlt. simpl. apply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 4.\nby_Acc_mwlt lex_natxnat.\nDefined.\n\n(* Ordre sur les listes d'entiers:\n     ordre lexicographique sur la taille et le premier élément *)\nDefinition m_list (xs:list nat) :=\n  match xs with\n      nil => nil\n    | (cons x xs) => (cons (length (cons x xs)) (cons x nil))\n  end.\n\nDefinition lt_list  :=\n  (make_mwlt (list nat) m_list).\n\nProgram Fixpoint sum_list (xs:list nat) {wf lt_list xs} : nat :=\n  match xs with\n      nil => 0\n    | (cons 0 xs) => (sum_list xs)\n    | (cons (S x) xs) => S (sum_list (cons x xs))\n  end.\n\nObligation 1.\nunfold lt_list. unfold make_mwlt. simpl. destruct xs.\n  simpl. apply wlt_nil.\n  simpl. apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lt_list. unfold make_mwlt. simpl. apply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 3.\nby_Acc_mwlt lex_natxnat.\nDefined.\n\n(* Analogue sur les listes de listes *)\nDefinition m_listlist (A:Set) (xss : list (list A)) :=\n  match xss with\n      nil => nil\n    | (cons xs _) => (cons (length xss) (cons (length xs) nil))\n  end.\n\nDefinition lt_listlist (A:Set) (xss yss : list (list A)) :=\n  (wlt (m_listlist A xss) (m_listlist A yss)).\n\nParameter A:Set.\n\nProgram Fixpoint list_concat (xss : list (list A))\n        {wf (lt_listlist A) xss} : list A :=\n  match xss with\n      nil => nil\n    | (cons nil xss) => (list_concat xss)\n    | (cons (cons x xs) xss) => (cons x (list_concat (cons xs xss)))\n  end.\n\nObligation 1.\nunfold lt_listlist. destruct xss.\n  simpl. apply wlt_nil.\n  simpl. apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lt_listlist. simpl. apply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 3.\nby_Acc_mwlt lex_natxnat.\nDefined.\n\n(* Sur la longueur des listes *)\nDefinition mw_list (A:Set) (xs: list A) :=\n  (cons (length xs) nil).\n\nDefinition lt_len_list (A:Set) :=\n  (make_mwlt (list A) (mw_list A)).\n\nProgram Fixpoint bubble (xs:list nat) {wf (lt_len_list nat) xs} : list nat :=\n  match xs with\n      nil => nil\n    | (cons x nil) => (cons x nil)\n    | (cons x1 (cons x2 xs)) =>\n      if (ltb x1 x2) then (cons x1 (bubble (cons x2 xs)))\n      else (cons x2 (bubble (cons x1 xs)))\n  end.\n\nObligation 1.\nunfold lt_len_list. unfold make_mwlt. unfold mw_list. simpl. \napply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lt_len_list. unfold make_mwlt. unfold mw_list. simpl. \napply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 3. \nby_Acc_mwlt lt_len_list.\nDefined.\n\n(* Le peigne *)\nInductive btree (A:Set) : Set :=\n  Empty : (btree A)\n| Node : (btree A) -> A -> (btree A) -> (btree A).\n\nArguments  Empty {A}.\nArguments Node [A] _ _ _.\n\nFixpoint btree_size (A:Set) (bt:btree A) :=\n  match bt with\n      Empty => 0\n    | (Node bt1 x bt2) => S (plus (btree_size A bt1) (btree_size A bt2))\n  end.\n\nDefinition m_btree (A:Set) (bt:btree A) :=\n  match bt with\n      Empty => nil\n    | (Node bt1 x bt2) => (cons (btree_size A bt) (cons (btree_size A bt1) nil))\n  end.\n\nDefinition lt_btree (A:Set) (bt1 bt2:btree A) :=\n  (wlt (m_btree A bt1) (m_btree A bt2)).\n\nProgram Fixpoint to_list (bt:btree A)\n        {wf (lt_btree A) bt} : list A :=\n  match bt with\n      Empty => nil\n    | (Node Empty x bt) => (cons x (to_list bt))\n    | (Node (Node bt1 x1 bt2) x2 bt3) => (to_list (Node bt1 x1 (Node bt2 x2 bt3)))\n  end.\n\nObligation 1.\nunfold lt_btree. destruct bt.\n  simpl. apply wlt_nil.\n  simpl. apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lt_btree. simpl. rewrite <- plus_Snm_nSm. simpl.\nrewrite plus_assoc. apply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 3.\nby_Acc_mwlt lt_btree.\nDefined.\n\n(* Theory *)\nAxiom g1 : nat -> nat.\nAxiom g2 : nat -> nat -> nat.\nAxiom g3 : nat -> nat -> nat.\nAxiom g4 : nat -> nat -> nat.\nAxiom g5 : nat -> nat -> nat -> nat.\nAxiom g6 : nat -> nat -> nat -> nat.\nAxiom g7 : nat -> nat -> nat -> nat.\nAxiom h1 : nat -> nat -> nat -> nat.\nAxiom h2 : nat -> nat -> nat -> nat.\nAxiom h3 : nat -> nat -> nat -> nat -> nat -> nat.\n\nDefinition wm_nat3 (xyz:nat * nat * nat) :=\n  match xyz with\n      (0, y, 0) => nil\n    | (0, y, S z) => (cons (S z) nil)\n    | (S x, 0, z) => (cons (S x) (cons 0 nil))\n    | (S x, S y, z) => (cons (S x) (cons (S y) nil))\n  end.\n\nDefinition rlex_nat3 :=\n  (make_mwlt (nat * nat * nat) wm_nat3).\n\nProgram Fixpoint f (xyz : nat * nat * nat) {wf rlex_nat3 xyz} : nat :=\n  match xyz with\n      (0, y, 0) => (g1 y)\n    | (0, y, S z) => (h1 y z (f (0, (g2 y z), z)))\n    | (S x, 0, z) => (h2 x z (f (x, (g3 x z), (g4 x z))))\n    | (S x, S y, z) =>\n         (h3 x y z (f (x, (g5 x y z), (g6 x y z)))\n                   (f (S x, y, (g7 x y z))))\n  end.\n\nLemma rlex_nat3_1 : forall (y z m : nat),\n  (rlex_nat3 (0, y, z) (0, m, S z)).\nintros. unfold rlex_nat3. unfold make_mwlt. destruct z.\n  simpl. apply wlt_nil.\n  simpl. apply wlt_lt; auto with arith.\nQed.\n\nLemma rlex_nat3_2 : forall (x z m1 m2 : nat),\n  (rlex_nat3 (x, m1, m2) (S x, 0, z)).\nunfold rlex_nat3. unfold make_mwlt. destruct x.\n  destruct m2.\n    simpl. apply wlt_nil.\n    simpl. apply wlt_len; auto with arith.\n  intros. destruct m1.\n    simpl. apply wlt_lt; auto with arith.\n    simpl. apply wlt_lt; auto with arith.\nQed.\n\nLemma rlex_nat3_3 : forall (x y z m1 m2 : nat),\n  (rlex_nat3 (x, m1, m2) (S x, S y, z)).\nunfold rlex_nat3. unfold make_mwlt. destruct x.                     \n  intros. destruct m2.\n    simpl. apply wlt_nil.\n    simpl. apply wlt_len; auto with arith.\n  intros. destruct m1.\n    simpl. apply wlt_lt; auto with arith.\n    simpl. apply wlt_lt; auto with arith.\nQed.\n\nLemma rlex_nat3_4 : forall (x y z m : nat),\n  (rlex_nat3 (S x, y, m) (S x, S y, z)).\nunfold rlex_nat3. unfold make_mwlt. destruct y.\n  intros. simpl. apply wlt_wlt. \n    auto with arith.\n    simpl. apply wlt_0_w. apply wlt_nil.\n  intros. simpl. apply wlt_wlt.\n    auto with arith.\n    apply wlt_lt; auto with arith.\nQed.\n\nObligation 1.\napply rlex_nat3_1. \nQed.\n\nObligation 2.\napply rlex_nat3_2.\nQed.\n\nObligation 3.\napply rlex_nat3_3.\nQed.\n\nObligation 4.\napply rlex_nat3_4.\nQed.\n \nObligation 5.\nby_Acc_mwlt wm_nat3.\nDefined.\n\n(* Bootstrap *)\nParameter eqb : nat -> nat -> bool.\n\nProgram Fixpoint listordi (xsys : list nat * list nat) {wf (lex_listxlist nat) xsys} : bool :=\n  match xsys with\n    (_, nil) => false\n  | (xs, (cons 0 ys)) => (listordi (xs, ys))\n  | (nil, (cons (S y) ys)) => true\n  | ((cons 0 xs), (cons (S y) ys)) => (listordi (xs, (cons (S y) ys)))\n  | ((cons (S x) xs), (cons (S y) ys)) =>\n     (orb (ltb (length xs) (length ys))\n\t  (andb (eqb (length xs) (length ys))\n\t\t(orb (ltb x y) (listordi (xs, ys)))))\n  end.\n\nObligation 1.\nunfold lex_listxlist. unfold make_mwlt. simpl.\napply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lex_listxlist. unfold make_mwlt. simpl.\napply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 3.\nunfold lex_listxlist. unfold make_mwlt. simpl.\napply wlt_lt_gen; auto with arith.\nQed.\n \nObligation 4.  \nby_Acc_mwlt lex_natxnat.\nDefined.\n\n(* Dershowitz/Manna: \"counting tips of binary trees\" *)\n\nFixpoint list_btree_size (A:Set) (bts:list (btree A)) : nat :=\n  match bts with\n      nil => 0\n    | (cons bt bts) => (plus (btree_size A bt) (list_btree_size A bts))\n  end.\n\nDefinition wm_list_btree (A:Set) (bts:list (btree A)) : (list nat) :=\n  (cons (list_btree_size A bts) (cons (length bts) nil)).\n\nDefinition lt_list_btree (A:Set) :=\n  (make_mwlt (list (btree A)) (wm_list_btree A)).\n\nProgram Fixpoint count_tips (bts:(list (btree A))) \n        {wf (lt_list_btree A) bts} : nat :=\n  match bts with\n      nil => 0\n    | (cons Empty bts) => S (count_tips bts)\n    | (cons (Node bt1 x bt2) bts) => (count_tips (cons bt1 (cons bt2 bts)))\n  end.\n\nObligation 1.\nunfold lt_list_btree. unfold make_mwlt. unfold wm_list_btree. \nsimpl. apply wlt_wlt_gen.\n  auto.\n  apply wlt_lt_gen; auto with arith.\nQed.\n\nObligation 2.\nunfold lt_list_btree. unfold make_mwlt. unfold wm_list_btree.\napply wlt_lt_gen.\n  auto.\n  simpl. rewrite plus_assoc. auto with arith.\nQed.\n\nObligation 3.\nby_Acc_mwlt lt_list_btree.\nDefined.\n\nPrint Assumptions count_tips.", "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/ordinals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7986357090779977}}
{"text": "(* Simple inductive types: lists *)\n\nInductive list_nat :=\n  nil\n| cons : nat -> list_nat -> list_nat.\n\nCheck (cons 2 (cons 3 nil)).\n(* [2, 3] *)\n                         \n(* Mutual inductive types: even/odd lists *)\n\nInductive oddList :=\n  ocons : nat -> evenList -> oddList\nwith evenList :=\n  enil\n| econs : nat -> oddList -> evenList.\n\n\n(* indexed inductive types: vectors (fixed-size lists) *)\nInductive vector : nat -> Type :=\n  vnil : vector 0\n| vcons : forall n, nat -> vector n -> vector (1 + n).\n\nCheck (vcons _ 2 (vcons _ 3 vnil)).\n\n\n(* inductive-inductive type: contextes and types of a dependent type theory \nΓ ⊢ and Γ ⊢ A type\n*)\n(*\nInductive context :=\n  cnil : context\n| cext : forall (Γ : context), types Γ -> context\n                                      (*\nΓ ⊢   Γ ⊢ A\n-----------\n  Γ, A ⊢\n                                      *)\n  with types : context -> Type :=\n    (* Γ ⊢ N type *)\n    N : forall Γ, types Γ.\n\n\n*)\n\n\n(* Transport hell example:\n\n   rev_append vector1 vector2 = rev vector1 ++ vector2\n   rev_append [1,2] [3,4] = [2,1,3,4]\n\n *)\nFixpoint rev_append n1 (v1 : vector n1) n2 (v2 : vector n2)\n         { struct v1 } : vector (n1 + n2).\n\n  refine (\n  match v1 with\n    vnil => v2\n  | vcons n1' hd tl =>\n    rev_append n1' tl (1 + n2) (vcons n2 hd v2)\n               end).\n\nCheck plus_n_Sm.\n\n(* other example : lib.agda in omegatt *)\n", "meta": {"author": "amblafont", "repo": "slides", "sha": "93b877426c7e87d8f1f6a9a3438042a1542627c4", "save_path": "github-repos/coq/amblafont-slides", "path": "github-repos/coq/amblafont-slides/slides-93b877426c7e87d8f1f6a9a3438042a1542627c4/inductifinductif/examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.798623844924919}}
{"text": "Require Import QArith.\nRequire Import Omega.\nRequire Import QvecArith PerceptronDef.\nRequire Import TerminationRefinement. (* needs inner_perceptron_MCE_sum_m_w *)\n\n(************************************************************************************************************\n         Defines an injection from natural numbers to rationals and proves some basic properties.\n ************************************************************************************************************)\n\nFixpoint inject_nat (n : nat) : Q :=\nmatch n with\n| O => 0\n| S n' => 1 + (inject_nat n')\nend.\n\nLemma Qnat_le : forall (A B : nat),\n  (A <= B)%nat -> (inject_nat A) <= (inject_nat B).\nProof.\n  intros. induction H. apply Qle_refl. simpl. rewrite <- Qplus_0_l.\n  unfold Qplus; rewrite Qred_correct.\n  apply (Qplus_le_compat 0 1 (inject_nat A) (inject_nat m)).\n  unfold Qle. simpl. omega. apply IHle. Qed.\n\nLemma Qnat_lt : forall (A B : nat),\n  (A < B)%nat -> (inject_nat A) < (inject_nat B).\nProof.\n  intros. induction H. simpl. rewrite <- Qplus_0_l at 1. unfold Qplus; rewrite Qred_correct.\n  apply Qplus_lt_le_compat. reflexivity. apply Qle_refl. simpl. rewrite <- Qplus_0_l.\n  unfold Qplus; rewrite Qred_correct. apply Qplus_lt_le_compat. reflexivity.\n  apply Qlt_le_weak. apply IHle. Qed.\n\nLemma Qnat_le_0 : forall (A : nat),\n  0 <= (inject_nat A).\nProof.\n  intros. induction A. apply Qle_refl. simpl. unfold Qplus; rewrite Qred_correct.\n  apply (Qplus_le_compat 0 _ 0). apply Qlt_le_weak. reflexivity. apply IHA. Qed.\n\nLemma Square_preserves_le : forall (A B : Q),\n  0 <= A -> 0 <= B ->\n  A <= B -> A*A <= B*B.\nProof.\n  intros. unfold Qle in H, H0, H1. unfold Qmult; repeat rewrite Qred_correct.\n  unfold Qle. simpl. simpl in H, H0, H1.\n  rewrite Z.mul_1_r in H, H0. assert (forall (A B C D : Z), (A*B*(C*D) = (A*C)*(B*D))%Z).\n  intros. repeat rewrite <- Z.mul_assoc. rewrite (Z.mul_assoc B0 C D).\n  rewrite (Z.mul_comm B0 C). rewrite (Z.mul_assoc C B0 D). reflexivity.\n  repeat rewrite Pos2Z.inj_mul. rewrite H2. rewrite (H2 (Qnum B) _ _ _).\n  apply (Zmult_le_compat _ _ _ _ H1 H1); apply (Z.mul_nonneg_nonneg _ _ H (Zle_0_pos _)). Qed.\n\n (****************************************************************************************\n  Show that any element in MCE must be in T. Therefore properties of elements of T holds\n  for elements of MCE.\n  ****************************************************************************************)\nLemma In_inner_perceptron_MCE_In_T : forall {n : nat} (T : list ((Qvec n)*bool)) \n      (w0 : Qvec (S n)) (L : list ((Qvec n)*bool)) (w : Qvec (S n)) (f : Qvec n) (l : bool),\n  inner_perceptron_MCE T w0 = Some (L, w) -> List.In (f, l) L -> List.In (f, l) T.\nProof.\n  intros n T. induction T; intros. inversion H.\n  destruct a as [f' l']. simpl in H. destruct (correct_class (Qvec_dot w0 (consb f')) l').\n  apply IHT with w0 L w f l in H. right. apply H. apply H0.\n  destruct (inner_perceptron_MCE T (Qvec_plus w0 (Qvec_mult_class l' (consb f')))) eqn:H1.\n  destruct p as [L' w']. inversion H; subst; clear H.\n  inversion H0. left. apply H. right. apply IHT with _ _ _ f l in H1. apply H1. apply H.\n  inversion H; subst; clear H. inversion H0. left. apply H. inversion H. Qed.\n\nLemma In_MCE_In_T : forall {n : nat} (E : nat ) (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)) (f : Qvec n) (l : bool),\n  List.In (f, l) (MCE E T w0) -> List.In (f, l) T.\nProof.\n  intros n E. induction E; intros. inversion H.\n  simpl in H. destruct (inner_perceptron_MCE T w0) eqn: H0. destruct p as [L w'].\n  apply List.in_app_or in H. inversion H.\n  apply In_inner_perceptron_MCE_In_T with _ _ _ _ f l in H0. apply H0. apply H1.\n  apply IHE in H1. apply H1. inversion H. Qed.\n\n (****************************************************************************************\n                This section Proves the lower bound A*k^2 of length (MCE ...)\n  ****************************************************************************************)\nDefinition limit_A {n : nat} (T : list ((Qvec n)*bool)) (wStar: Qvec (S n)) : Q :=\n  Qmult (min_element_product wStar T) (min_element_product wStar T).\n\nLemma correct_class_w_dot_f_pos : forall {n : nat} (w : Qvec (S n)) (f : Qvec n) (l : bool),\n correct_class (Qvec_dot w (consb f)) l = true ->\n (Qvec_dot w (Qvec_mult_class l (consb f))) > 0.\nProof.\n  intros. destruct l; unfold correct_class in H. simpl.\n  destruct (class (Qvec_dot w (consb f))) eqn:H0. simpl in H.\n  unfold class in H0. apply Bool.negb_true_iff in H.\n  apply Qle_bool_imp_le in H0. apply Qeq_bool_neq in H.\n  apply (Qle_neq_lt _ _ H0). unfold not. intros. apply H.\n  symmetry. apply H1. inversion H.\n  destruct (class (Qvec_dot w (consb f))) eqn:H0. inversion H. simpl in H.\n  unfold class in H0. simpl in H0.\n  assert (0 > (Qvec_dot w (consb f))). apply Qnot_le_lt. unfold not. intros.\n  apply Qle_bool_iff in H1. rewrite H0 in H1. inversion H1.\n  unfold Qvec_mult_class. rewrite Qvec_dot_mult_neg_1. unfold Qmult; rewrite Qred_correct.\n  unfold Qlt. simpl. unfold Qlt in H1. simpl in H1.\n  destruct (Qnum (Qvec_dot w (consb f))); try inversion H1.\n  rewrite Z.mul_1_r. rewrite Z.mul_1_r in H1.\n  apply Z.sgn_pos_iff. reflexivity. Qed.\n\nLemma correct_class_T_limit_A_pos : forall {n : nat} (T : list ((Qvec n)*bool)) (w : Qvec (S n)),\n  correctly_classifiedP T w -> (limit_A T w) > 0.\nProof.\n  intros n T; induction T; intros. reflexivity.\n  inversion H; subst.\n  unfold limit_A, min_element_product. fold (min_element_product w T).\n  destruct T. apply correct_class_w_dot_f_pos in H4. unfold Qmult; rewrite Qred_correct.\n  apply Qsquare_gt_0. unfold not. intros. apply Qlt_not_le in H4. apply H4.\n  rewrite H0. apply Qle_refl.\n  destruct (Qle_bool (Qvec_dot w (Qvec_mult_class l (consb f)))).\n  apply correct_class_w_dot_f_pos in H4. unfold Qmult; rewrite Qred_correct.\n  apply Qsquare_gt_0. unfold not. intros. apply Qlt_not_le in H4. apply H4.\n  rewrite H0. apply Qle_refl. apply IHT in H2.\n  unfold limit_A in H2. apply H2. Qed.\n\nLemma correct_class_T_min_element_product : forall {n : nat} (T : list ((Qvec n)*bool)) (w : Qvec (S n)),\n  correctly_classifiedP T w -> 0 < (min_element_product w T).\nProof.\n  intros. induction T. simpl. reflexivity. inversion H; subst. apply IHT in H2.\n  apply correct_class_w_dot_f_pos in H4. destruct T. simpl. apply H4.\n  unfold min_element_product. fold (min_element_product w (List.cons p T)).\n  destruct (Qle_bool _ _); assumption. Qed.\n\nLemma correct_class_T_Qvec_normsq_wstar : forall {n : nat} (T : list ((Qvec n)*bool)) (w : Qvec (S n)),\n  correctly_classifiedP T w -> (Qvec_normsq w) > 0 \\/ T = List.nil.\nProof.\n  intros n T; induction T; intros. right. reflexivity. inversion H; subst. apply IHT in H2.\n  inversion H2. left. apply H0. subst. left. apply correct_class_w_dot_f_pos in H4.\n  inversion H; subst. apply correct_class_w_dot_f_pos in H7. apply Qlt_not_eq in H7.\n  apply Qnot_eq_sym in H7. apply Qvec_dot_Not_Qvec_zero in H7. destruct H7 as [Hw Hlf].\n  apply (Qvec_normsq_Not_Qvec_Zero w Hw). Qed.\n\nLemma correct_class_T_Qvec_sum_dot_inner_perceptron_MCE : forall {n : nat} \n                                   (T M: list ((Qvec n)*bool)) (wstar w0 w : Qvec (S n)),\n  correctly_classifiedP T wstar -> inner_perceptron_MCE T w0 = Some (M, w) -> 0 <= Qvec_sum_dot wstar M.\nProof.\n  intros n T M wstar; generalize dependent M; induction T; intros. inversion H0. destruct a as [f l].\n  simpl in H0. inversion H; subst. destruct (correct_class (Qvec_dot w0 (consb f)) l). apply (IHT _ _ _ H5 H0).\n  destruct (inner_perceptron_MCE T (Qvec_plus w0 (Qvec_mult_class l (consb f)))) eqn:H1. destruct p as [M' w'].\n  inversion H0; subst. simpl. apply IHT in H1. apply correct_class_w_dot_f_pos in H6.\n  apply Qlt_le_weak in H6. unfold Qplus; rewrite Qred_correct. apply (Qplus_le_compat 0 _ 0 _ H6 H1).\n  apply H5. inversion H0; subst. simpl. apply correct_class_w_dot_f_pos in H6. apply Qlt_le_weak.\n  unfold Qplus; rewrite Qred_correct. rewrite Qplus_0_r. apply H6. Qed.\n\nLemma correct_class_T_Qvec_sum_dot_MCE : forall {n : nat} (E : nat) (T : list ((Qvec n)*bool)) (w w0 : Qvec (S n)),\n  correctly_classifiedP T w -> 0 <= Qvec_sum_dot w (MCE E T w0).\nProof.\n  intros n E; induction E; intros. apply Qle_refl. unfold MCE. destruct (inner_perceptron_MCE T w0) eqn:H0.\n  destruct p as [L w']. fold (MCE E T w'). rewrite Qvec_sum_dot_append.\n  apply correct_class_T_Qvec_sum_dot_inner_perceptron_MCE with (wstar := w) in H0.\n  apply IHE with (w0 := w') in H. unfold Qplus; rewrite Qred_correct.\n  apply (Qplus_le_compat 0 _ 0 _ H0 H). apply H. apply Qle_refl. Qed.\n\nLemma Constant_le_element_le_sum_min_product : forall {n : nat} (L : list ((Qvec n)*bool)) (w : Qvec (S n)) (A : Q),\n  0 < A ->\n  (forall (f : Qvec n) (l : bool), List.In (f, l) L -> \n   A <= (Qvec_dot w (Qvec_mult_class l (consb f)))) ->\n   (0 <= (Qvec_sum_dot w L)) /\\\n  A * (inject_nat (length L)) <= (Qvec_sum_dot w L).\nProof.\n  intros n L; induction L; intros. simpl. split; [|unfold Qmult; rewrite Qmult_0_r]; apply Qle_refl.\n  destruct a as [f l]. simpl. unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  rewrite Qmult_plus_distr_r. rewrite Qmult_1_r.\n  assert (H1 := H0 f l). assert (H2 : forall f l, List.In (f, l) L ->\n  A <= (Qvec_dot w (Qvec_mult_class l (consb f)))). intros.\n  assert (H3 : List.In (f0, l0) (List.cons (f, l) L)). right. apply H2. apply (H0 _ _ H3).\n  assert (H3 := IHL w A H H2). assert (List.In (f, l) (List.cons (f, l) L)). left. reflexivity.\n  apply H1 in H4. split. apply (Qplus_le_compat 0 _ 0 _). apply Qlt_le_weak in H.\n  apply (Qle_trans 0 A _ H H4). apply H3. apply Qplus_le_compat. apply H4.\n  unfold Qmult in H3; rewrite Qred_correct in H3; apply H3. Qed.\n\nLemma Element_T_le_limit_A : forall {n : nat} (T : list ((Qvec n)*bool)) (w : Qvec (S n)) (f : Qvec n) (l : bool),\n List.In (f, l) T -> min_element_product w T <= Qvec_dot w (Qvec_mult_class l (consb f)).\nProof.\n  intros n T w; induction T; intros. inversion H. destruct a as [f' l']. inversion H. inversion H0; subst.\n  unfold min_element_product. fold (min_element_product w T). destruct T. apply Qle_refl.\n  destruct (Qle_bool _ _) eqn:H1. apply Qle_refl.\n  assert (~ (Qvec_dot w (Qvec_mult_class l (consb f))) <= (min_element_product w (p :: T))).\n  unfold not. intros. apply Qle_bool_iff in H2. rewrite H1 in H2. inversion H2.\n  apply Qnot_le_lt in H2. apply Qlt_le_weak in H2. apply H2. apply IHT in H0.\n  destruct T. inversion H. inversion H1; subst; apply Qle_refl. inversion H1.\n  unfold min_element_product. fold (min_element_product w (p :: T)).\n  destruct (Qle_bool _ _) eqn:H1. apply Qle_bool_iff in H1. apply (Qle_trans _ _ _ H1 H0).\n  apply H0. Qed.\n\nLemma linearly_separable_lower_bound : forall {n : nat} (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)),\n  linearly_separable T -> (exists (A B : Q), forall (E : nat),\n  0 < A /\\ 0 < B /\\\n  A*(inject_nat (length (MCE E T w0)))*(inject_nat (length (MCE E T w0))) <=\n  B*(Qvec_normsq (Qvec_sum (MCE E T w0)))).\nProof.\n  intros. unfold linearly_separable in H. destruct H as [wstar H]. assert (H0 := H). assert (H1 := H).\n  apply correct_class_T_limit_A_pos in H. apply correct_class_T_Qvec_normsq_wstar in H0.\n  exists (limit_A T wstar). inversion H0. exists (Qvec_normsq wstar).\n  intros E. split. apply H. split. apply H2.\n  { apply (Qle_trans _ ((Qvec_dot wstar (Qvec_sum (MCE E T w0)))*(Qvec_dot wstar (Qvec_sum (MCE E T w0)))) _).\n    { rewrite Qvec_dot_sum_eq. assert (H3 := H1). apply correct_class_T_min_element_product in H3.\n      unfold limit_A. unfold Qmult; repeat rewrite Qred_correct. repeat rewrite <- Qmult_assoc.\n      rewrite (Qmult_assoc _ (inject_nat _) (inject_nat _)).\n      rewrite (Qmult_comm (min_element_product _ _) (inject_nat _)). repeat rewrite <- Qmult_assoc.\n      rewrite Qmult_assoc. assert (H4 := Square_preserves_le (QArith_base.Qmult (min_element_product wstar T)\n      (inject_nat (length (MCE E T w0)))) (Qvec_sum_dot wstar (MCE E T w0))). unfold Qmult in H4;\n      repeat rewrite Qred_correct in H4. apply H4.\n      rewrite <- (Qmult_0_l (inject_nat (length (MCE E T w0)))).\n      apply Qlt_le_weak in H3. apply (Qmult_le_compat_r _ _ _ H3 (Qnat_le_0 _)).\n      apply (correct_class_T_Qvec_sum_dot_MCE _ _ _ _ H1).\n      rewrite <- (Qred_correct (QArith_base.Qmult (min_element_product _ _) _)).\n      apply Constant_le_element_le_sum_min_product. apply H3.\n      intros. apply In_MCE_In_T in H5. apply (Element_T_le_limit_A _ wstar _ _ H5).\n    } apply Cauchy_Schwarz_inequality.\n  } exists 1. intros E. split. apply H. split. reflexivity. subst. unfold limit_A. simpl.\n  unfold Qmult at 3. simpl. unfold Qmult; repeat rewrite Qred_correct.\n  repeat rewrite (Qmult_1_l). destruct E; simpl; rewrite Qmult_0_l; apply Qvec_normsq_nonneg. Qed.\n\n (****************************************************************************************\n        This section will contains the proof of upper bound B*k on length (MCE ...)\n  ****************************************************************************************)\nDefinition limit_B {n : nat} (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)): Q :=\n  Qminus (max_element_normsq T) (Qmult (2#1) (min_element_product w0 T)).\n\nLemma not_correct_z_mu_neg: forall {n:nat} (f : Qvec n) (l:bool) (w: Qvec (S n)),\n  correct_class (Qvec_dot w (consb f)) l = false -> \n  ((Qvec_dot w (Qvec_mult_class l (consb f)))) <= 0.\nProof.\n  intros. unfold correct_class in H. destruct l.\n  destruct (class (Qvec_dot w (consb f))) eqn:H0. simpl in H.\n  apply Bool.negb_false_iff in H. apply Qeq_bool_iff in H.\n  unfold Qvec_mult_class. rewrite H. apply Qle_refl.\n  unfold class in H0. simpl. apply Qnot_lt_le. unfold not. intros.\n  apply Qlt_le_weak in H1. apply Qle_bool_iff in H1. rewrite H0 in H1.\n  inversion H1. apply andb_false_iff in H. unfold Qvec_mult_class.\n  rewrite Qvec_dot_mult_neg_1. inversion H. apply eqb_false_iff in H0.\n  assert (class (Qvec_dot w (consb f)) <> false). unfold not. intros.\n  apply H0. symmetry. apply H1. apply not_false_is_true in H1.\n  unfold class in H1. apply Qle_bool_iff in H1. unfold Qmult; rewrite Qred_correct.\n  unfold Qle. unfold Qle in H1.\n  simpl. simpl in H1. destruct (Qnum (Qvec_dot w (consb f))). reflexivity.\n  rewrite Z.mul_1_r in H1. rewrite Z.mul_1_r. apply Zlt_le_weak. apply Zlt_neg_0.\n  rewrite Z.mul_1_r in H1. assert (H2 := Zlt_neg_0 p). exfalso.\n  apply Zle_not_lt in H1. apply H1. apply H2.\n  apply Bool.negb_false_iff in H0. apply Qeq_bool_iff in H0. rewrite H0.\n  unfold Qmult; rewrite Qred_correct. rewrite Qmult_0_r. apply Qle_refl. Qed.\n\nLemma inner_perceptron_MCE_mu_neg: forall {n:nat} (T L: (list ((Qvec n)*bool))) (w0 w: Qvec (S n)),\n  inner_perceptron_MCE T w0 = Some (L, w) -> (Qmult (2#1) (min_element_product w0 T)) <= 0.\nProof.\n  intros n T; induction T; intros; unfold Qmult; repeat rewrite Qred_correct. inversion H.\n  destruct a as [f l]. simpl in H.\n  destruct (correct_class (Qvec_dot w0 (consb f)) l) eqn:H0.\n  { apply IHT in H. destruct T. simpl in H. unfold Qmult in H. rewrite Qmult_1_r in H.\n    unfold Qle in H. simpl in H. omega. unfold min_element_product.\n    fold (min_element_product w0 (List.cons p T)). destruct (Qle_bool _ _) eqn:H1.\n    apply Qle_bool_iff in H1. apply Qmult_le_l with (z := 2#1) in H1. unfold Qmult in H.\n    rewrite Qred_correct in H. apply (Qle_trans _ _ _ H1 H). reflexivity. unfold Qmult in H;\n    rewrite Qred_correct in H; apply H.\n  } apply not_correct_z_mu_neg in H0.\n    destruct T. simpl. apply Qmult_le_l with (z := 2#1) in H0. rewrite Qmult_0_r in H0.\n    apply H0. reflexivity. unfold min_element_product. fold (min_element_product w0 (List.cons p T)).\n    destruct (Qle_bool _ _) eqn:H1. apply Qmult_le_l with (z := 2#1) in H0. rewrite Qmult_0_r in H0.\n    apply H0. reflexivity.\n    assert (Qvec_dot w0 (Qvec_mult_class l (consb f)) > (min_element_product w0 (p :: T))).\n    apply Qnot_le_lt. unfold not. intros. apply Qle_bool_iff in H2. rewrite H1 in H2. inversion H2.\n    apply Qlt_le_weak in H2. rewrite <- (Qmult_0_r (2#1)). apply Qmult_le_l. reflexivity.\n    apply (Qle_trans _ _ _ H2 H0). Qed.\n\nTheorem mu_neg_or_pos: forall {n:nat} (w0 : Qvec (S n)) (T : (list ((Qvec n)*bool))),\n  (2#1)*(min_element_product w0 T) <= 0\n  \\/ (forall (E : nat), length (MCE E T w0) = 0%nat).\nProof.\n  intros. induction T. right; intros. destruct E; reflexivity.\n  inversion IHT. left. destruct a as [f l]. destruct T. simpl in H.\n  unfold Qle in H. simpl in H. omega. unfold min_element_product.\n  fold (min_element_product w0 (List.cons p T)). destruct (Qle_bool _ _) eqn:H0.\n  apply Qle_bool_iff in H0. apply Qmult_le_l with (z := 2#1) in H0.\n  unfold Qmult; rewrite Qred_correct; unfold  Qmult in H; rewrite Qred_correct in H.\n  apply (Qle_trans _ _ _ H0 H). reflexivity. apply H.\n  destruct (inner_perceptron_MCE (a :: T) w0) eqn:H0. destruct p as [L w].\n  apply inner_perceptron_MCE_mu_neg in H0. left. apply H0.\n  right. intros. destruct E. reflexivity. unfold MCE. rewrite H0. reflexivity. Qed.\n\nTheorem max_element_normsq_pos : forall {n : nat} (T : (list ((Qvec n)*bool))),\n  max_element_normsq T > 0.\nProof.\n  intros. induction T. simpl. reflexivity.\n  destruct a as [f l].\n  destruct T.\n  { simpl. apply Qvec_consb_gt_0.\n  } unfold max_element_normsq. fold (max_element_normsq (List.cons p T)).\n  destruct Qge_bool; [apply Qvec_consb_gt_0 | apply IHT ]. Qed.\n\nTheorem limit_B_pos_or_MCE_nil : forall {n : nat} (w0 : Qvec (S n)) (T : (list ((Qvec n)*bool))),\n  limit_B T w0 > 0 \\/ (forall (E : nat), length (MCE E T w0) = 0%nat).\nProof.\n  intros n w T. assert (H := mu_neg_or_pos w T). inversion H.\n  left. assert (H1 := max_element_normsq_pos T). unfold limit_B.\n  apply Qopp_le_compat in H0. assert (0 = - 0). reflexivity. rewrite <- H2 in H0.\n  unfold Qminus. apply (Qplus_lt_le_compat 0 _ 0 _ H1 H0).\n  right. apply H0. Qed.\n\nLemma MCE_Qvec_sum_normsq_expand : forall {n : nat} (E : nat) (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)),\n  Qvec_normsq (Qvec_sum (MCE E T w0)) == (Qvec_sum_normsq (MCE E T w0)) + \n                              (2#1)*((Qvec_foil w0 (MCE E T w0)) - (Qvec_sum_dot w0 (MCE E T w0))).\nProof.\n  intros. assert (H := Qvec_normsq_eq_sum_normsq_foil (MCE E T w0)).\n  rewrite H; clear H. assert (H := Qvec_foil_0_w (Qvec_zero (S n)) w0 (MCE E T w0)).\n  rewrite Qvec_plus_Qvec_zero in H. rewrite H. reflexivity. Qed.\n\nLemma Qvec_foil_inner_perceptron_MCE_w0_le_0 : forall {n : nat} (T M : list ((Qvec n)*bool)) (w0 w: Qvec (S n)),\n  inner_perceptron_MCE T w0 = Some (M, w) -> Qvec_foil w0 M <= 0.\nProof.\n  intros n T; induction T; intros. inversion H. destruct a as [f l].\n  inversion H. destruct (correct_class (Qvec_dot w0 (consb f)) l) eqn:H2.\n  apply (IHT _ _ _ H1). destruct (inner_perceptron_MCE T (Qvec_plus w0 (Qvec_mult_class l (consb f)))) eqn:H3.\n  { destruct p as [M' w']. inversion H1; subst. simpl. apply IHT in H3.\n    apply not_correct_z_mu_neg in H2. unfold Qplus; rewrite Qred_correct.\n    apply (Qplus_le_compat _ 0 _ 0 H2 H3).\n  } simpl in H1. inversion H1; subst. simpl. unfold Qplus; rewrite Qred_correct.\n  rewrite Qplus_0_r. apply (not_correct_z_mu_neg _ _ _ H2). Qed.\n\nLemma Qvec_foil_MCE_w0_le_0 : forall {n : nat} (E : nat) (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)),\n  Qvec_foil w0 (MCE E T w0) <= 0.\nProof.\n  intros n E. induction E; intros. apply Qle_refl.\n  simpl. destruct (inner_perceptron_MCE T w0) eqn:H.\n  { destruct p as [M w]. rewrite Qvec_foil_append. assert (H0 := H).\n    apply Qvec_foil_inner_perceptron_MCE_w0_le_0 in H.\n    apply inner_perceptron_MCE_sum_m_w in H0. rewrite Qvec_sum_sum_class. rewrite <- H0.\n    assert (H1 := IHE T w). unfold Qplus; rewrite Qred_correct; apply (Qplus_le_compat _ 0 _ 0 H H1).\n  } apply Qle_refl. Qed. \n\nLemma Constant_le_element_le_sum : forall {n : nat} (L : list ((Qvec n)*bool)) (w : Qvec (S n)) (A : Q),\n  0 < A ->\n  (forall (f : Qvec n) (l : bool), List.In (f, l) L ->\n  (Qvec_normsq (consb f)) + ((-2#1)*(Qvec_dot w (Qvec_mult_class l (consb f)))) <= A) ->\n  (Qvec_sum_normsq L) + ((-2#1)*(Qvec_sum_dot w L)) <= A * (inject_nat (length L)).\nProof.\n  intros n L. induction L; intros. simpl. unfold Qmult; rewrite Qred_correct;\n  repeat rewrite Qmult_0_r. apply Qle_refl.\n  destruct a as [f l]. unfold Qvec_sum_normsq. fold (Qvec_sum_normsq L).\n  unfold Qvec_sum_dot. fold (Qvec_sum_dot w L). simpl. unfold Qplus, Qmult; repeat rewrite Qred_correct.\n  repeat rewrite Qmult_plus_distr_r. rewrite Qmult_1_r. repeat rewrite <- Qplus_assoc.\n  rewrite (Qplus_assoc (Qvec_sum_normsq L) _ _).\n  rewrite (Qplus_comm (Qvec_sum_normsq L) _). repeat rewrite <- Qplus_assoc. rewrite Qplus_assoc.\n  apply Qplus_le_compat. assert (H1 := H0 f l). unfold Qplus, Qmult in H1; repeat rewrite Qred_correct in H1;\n  apply H1. left. reflexivity. assert (H1 := IHL w A H). unfold Qplus, Qmult in H1;\n  repeat rewrite Qred_correct in H1. apply H1. intros. apply H0. right. apply H2. Qed.\n\nLemma Qmult_neg_le : forall (x y z : Q),\n  z < 0 -> x <= y -> z * y <= z * x.\nProof.\n  intros. unfold Qmult; repeat rewrite Qred_correct.\n  unfold Qle. unfold Qle in H0. simpl. unfold Qlt in H.\n  simpl in H. rewrite Z.mul_1_r in H. destruct x, y, z. simpl.\n  simpl in H0. simpl in H. repeat rewrite (Pos.mul_comm Qden1 _).\n  repeat rewrite Pos2Z.inj_mul. repeat rewrite Z.mul_assoc.\n  apply Zmult_le_compat_r. repeat rewrite <- Z.mul_assoc.\n  apply Z.mul_le_mono_nonpos_l. apply (Zlt_le_weak _ _ H).\n  apply H0. apply Zle_0_pos. Qed.\n\nLemma Element_T_le_limit_B : forall {n : nat} (T : list ((Qvec n)*bool)) (w : Qvec (S n)) (f : Qvec n) (l : bool),\n List.In (f, l) T ->\n       (Qvec_normsq (consb f)) + ((-2#1)*(Qvec_dot w (Qvec_mult_class l (consb f)))) <= (limit_B T w).\nProof.\n  intros n T. induction T; intros. inversion H. unfold limit_B.\n  unfold Qminus. unfold Qmult at 2. rewrite <- Qred_opp. rewrite Qopp_mult_distr_l.\n  fold (Qmult (Qopp (2#1)) (min_element_product w (a :: T))).\n  assert (- (2#1) = (-2#1)). reflexivity. repeat rewrite H0; clear H0. inversion H.\n  { subst. unfold max_element_normsq, min_element_product. fold (max_element_normsq T).\n    fold (min_element_product w T). destruct T. unfold Qplus; rewrite Qred_correct. apply Qle_refl.\n    unfold Qge_bool. destruct (Qle_bool (max_element_normsq _) _) eqn:H0.\n    destruct (Qle_bool (Qvec_dot _ _) _) eqn:H1. unfold Qplus; rewrite Qred_correct; apply Qle_refl.\n    assert (min_element_product w (p :: T) < Qvec_dot w (Qvec_mult_class l (consb f))).\n    apply Qnot_le_lt. unfold not. intros. apply Qle_bool_iff in H2. rewrite H1 in H2. inversion H2.\n    unfold Qplus. rewrite Qred_correct. apply Qplus_le_compat. apply Qle_refl. apply Qlt_le_weak in H2.\n    apply Qmult_neg_le. reflexivity. apply H2.\n    assert (Qvec_normsq (consb f) <= max_element_normsq (p :: T)).\n    apply Qlt_le_weak. apply Qnot_le_lt. unfold not. intros.\n    apply Qle_bool_iff in H1. rewrite H0 in H1. inversion H1. unfold Qplus; rewrite Qred_correct.\n    apply (Qplus_le_compat _ _ _ _ H1). clear H0. clear H1.\n    destruct (Qle_bool (Qvec_dot w _) _) eqn:H2. apply Qle_refl.\n    apply Qmult_neg_le. reflexivity. apply Qlt_le_weak. apply Qnot_le_lt.\n    red. intros. apply Qle_bool_iff in H0. rewrite H2 in H0. inversion H0.\n  } apply IHT with (w := w) in H0. destruct a as [f' l'].\n  unfold max_element_normsq, min_element_product. fold (max_element_normsq T). fold (min_element_product w T).\n  destruct T. inversion H. inversion H1; subst. unfold Qplus; rewrite Qred_correct. apply Qle_refl. inversion H1.\n  unfold Qge_bool. destruct (Qle_bool (max_element_normsq _) _) eqn:H1. apply Qle_bool_iff in H1.\n  destruct (Qle_bool (Qvec_dot w _) _) eqn:H2. unfold Qopp; simpl. apply Qle_bool_iff in H2.\n  unfold limit_B in H0. apply (Qle_trans _ _ _ H0). apply (Qplus_le_compat _ _ _ _ H1).\n  unfold Qmult. rewrite <- Qred_opp.\n  rewrite Qopp_mult_distr_l. apply Qmult_neg_le. reflexivity. apply H2.\n  apply (Qle_trans _ _ _ H0). unfold limit_B. unfold Qminus. unfold Qmult.\n  rewrite <- Qred_opp. rewrite Qopp_mult_distr_l.\n  apply (Qplus_le_compat _ _ _ _ H1). assert (-(2#1) = -2#1). reflexivity. rewrite H3.\n  apply Qle_refl. apply (Qle_trans _ _ _ H0). unfold limit_B. unfold Qminus.\n  unfold Qmult. rewrite <- Qred_opp. rewrite Qopp_mult_distr_l. apply Qplus_le_compat. apply Qle_refl.\n  apply Qmult_neg_le. reflexivity. clear H1. destruct (Qle_bool (Qvec_dot w _) _) eqn:H1.\n  apply Qle_bool_iff in H1. apply H1. apply Qle_refl. Qed.\n\n(* The upper bound of errors does not require T to be linearly seperable *)\nLemma MCE_upper_bound : forall {n : nat} (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)),\n exists (B : Q), forall (E : nat),\n 0 < B /\\\n Qvec_normsq (Qvec_sum (MCE E T w0)) <= B * inject_nat (length (MCE E T w0)).\nProof.\n  intros. assert (H := limit_B_pos_or_MCE_nil w0 T). inversion H.\n  { exists (limit_B T w0). intros E. split. apply H0.\n    unfold limit_B, Qminus. unfold Qmult. rewrite <- Qred_opp.\n    rewrite Qopp_mult_distr_l. assert (-(2#1) = (-2#1)). reflexivity.\n    rewrite H1; clear H1. rewrite MCE_Qvec_sum_normsq_expand.\n    assert ((Qvec_sum_normsq (MCE E T w0)) + (2#1)*((Qvec_foil w0 (MCE E T w0)) - (Qvec_sum_dot w0 (MCE E T w0)))\n                                       <= (Qvec_sum_normsq (MCE E T w0)) + (-2#1)*(Qvec_sum_dot w0 (MCE E T w0))).\n    unfold Qminus. unfold Qmult, Qplus; repeat rewrite Qred_correct.\n    rewrite Qmult_plus_distr_r. assert (H3 := Qvec_foil_MCE_w0_le_0 E T w0).\n    apply Qplus_le_compat. apply Qle_refl. rewrite <- (Qplus_0_l (_ (-2#1) (Qvec_sum_dot _ _))).\n    apply Qplus_le_compat. rewrite <- (Qmult_0_r (2#1)). apply Qmult_le_l. reflexivity. apply H3.\n    rewrite <- Qopp_mult_distr_r. rewrite Qopp_mult_distr_l. rewrite <- Qred_correct.\n    fold (Qmult (Qopp (2#1)) (Qvec_sum_dot w0 (MCE E T w0))). rewrite <- (Qred_correct (_ (-2#1) _)) .\n    fold (Qmult (-2#1) (Qvec_sum_dot w0 (MCE E T w0))). apply Qmult_neg_le; [reflexivity | apply Qle_refl].\n    apply (Qle_trans _ _ _ H1). apply Constant_le_element_le_sum. unfold limit_B, Qminus in H0.\n    unfold Qmult in H0. rewrite <- Qred_opp in H0.\n    rewrite Qopp_mult_distr_l in H0. apply H0. intros. apply In_MCE_In_T in H2.\n    apply Element_T_le_limit_B with (w:= w0) in H2. unfold limit_B in H2. unfold Qminus in H2.\n    unfold Qmult in H2. rewrite <- Qred_opp in H2. rewrite Qopp_mult_distr_l in H2. apply H2.\n  } exists 1. intros E. split. reflexivity. rewrite H0. simpl. assert (H1 := H0 E). unfold Qmult.\n  rewrite Qmult_0_r. destruct (MCE E T w0); simpl. rewrite Qvec_normsq_Qvec_0. apply Qle_refl. inversion H1. Qed.\n\n (****************************************************************************************\n    Combine Upper and Lower Bound into single Lemma.\n  ****************************************************************************************)\nLemma linearly_separable_bound: forall {n : nat} (T : list ((Qvec n)*bool)) (w0 : Qvec (S n)),\n  linearly_separable T -> (exists (A B C : Q), forall (E : nat),\n  0 < A /\\ 0 < B /\\ 0 < C /\\\n  A * (inject_nat (length (MCE E T w0))) *(inject_nat (length (MCE E T w0))) <=\n  B * Qvec_normsq (Qvec_sum (MCE E T w0)) <=\n  C * (inject_nat (length (MCE E T w0)))).\nProof.\n  intros. apply (linearly_separable_lower_bound T w0) in H. destruct H as [A [B H]].\n  assert (H0 := MCE_upper_bound T w0). destruct H0 as [C H0].\n  exists A. exists B. exists (B*C). intros. split. apply (H E). split. apply (H E). split.\n  rewrite <- (Qmult_0_l C). unfold Qmult; rewrite Qred_correct. apply Qmult_lt_r. apply (H0 E). apply (H E).\n  split. apply H. unfold Qmult; repeat rewrite Qred_correct. rewrite (Qmult_comm B _). rewrite <- Qmult_assoc.\n  rewrite (Qmult_comm _ (_ C _)). apply Qmult_le_compat_r. assert (H1 := H0 E).\n  unfold Qmult in H1; rewrite Qred_correct in H1. apply H1. apply Qlt_le_weak. apply (H E). Qed.", "meta": {"author": "tm507211", "repo": "CoqPerceptron", "sha": "ce154b357c0cd6f072159d26c9b6c88f28c6af5b", "save_path": "github-repos/coq/tm507211-CoqPerceptron", "path": "github-repos/coq/tm507211-CoqPerceptron/CoqPerceptron-ce154b357c0cd6f072159d26c9b6c88f28c6af5b/MCEBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7984923607293632}}
{"text": "Require Import Unicode.Utf8.\nRequire Import Classical.\n\n(* Level 1 *)\n(* `split`: Prove each part of a conjunction separately *)\n(* Goal of the form `A ∧ B` *)\n\nLemma example_1_adv_add (P Q : Prop) (p : P) (q : Q) : P ∧ Q.\nProof.\n  split.\n  exact p.\n  apply q.\nQed.\n\n(* Level 2 *)\n(* `destruct f as [g h]`: Split conjunction hypothesis into two child hypotheses *)\n(* Hypothesis of the form `A ∧ B` *)\n\nLemma and_symm (P Q : Prop) : P ∧ Q → Q ∧ P.\nProof.\n  intro f.\n  destruct f as [p q].\n  split.\n  exact q.\n  exact p.\nQed.\n\n(* Level 3 *)\n\nLemma and_trans (P Q R : Prop) : P ∧ Q → Q ∧ R → P ∧ R.\nProof.\n  intro f.\n  intro g.\n  destruct f as [p q].\n  destruct g as [q' r].\n  split.\n  exact p.\n  exact r.\nQed.\n\n(* Level 4 *)\n\nLemma iff_trans (P Q R : Prop) : (P ↔ Q) → (Q ↔ R) → (P ↔ R).\nProof.\n  intro f.\n  intro g.\n  destruct f as [pq qp].\n  destruct g as [gr rg].\n  split.\n  intro p.\n  apply gr.\n  apply pq.\n  exact p.\n  intro r.\n  apply qp.\n  apply rg.\n  exact r.\nQed.\n\n(* Level 5 *)\n(* Lean `apply f.1` ~ Coq ??? *)\n\nLemma iff_trans' (P Q R : Prop) : (P ↔ Q) → (Q ↔ R) → (P ↔ R).\nProof.\n  intro f.\n  intro g.\n  rewrite f.\n  rewrite g.\n  reflexivity.\nQed.\n\n(* Level 6 *)\n(* `left`: Prove LHS of disjunction *)\n(* Goal of the form `A ∨ B` *)\n\n(* `right`: Prove RHS of disjunction *)\n(* Goal of the form `A ∨ B` *)\n\nLemma example_6_adv_add (P Q : Prop) : Q → (P ∨ Q).\nProof.\n  intro q.\n  right.\n  exact q.\nQed.\n\n(* Level 7 *)\n(* `destruct f as [g|h]`: Split disjunction hypothesis into two child hypotheses *)\n(* Hypothesis of the form `A ∨ B` *)\n\nLemma or_symm (P Q : Prop) : P ∨ Q → Q ∨ P.\nProof.\n  intro f.\n  destruct f as [p|q].\n  right.\n  exact p.\n  left.\n  exact q.\nQed.\n\n(* Level 8 *)\n(* `assumption`: Solve goal that is already a hypothesis *)\n(* `tactic1; tactic2`: Run tactic2 on all sub-goals produced by tactic1 *)\n\nLemma and_or_distrib_left (P Q R : Prop) : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R).\nProof.\n  split.\n  intro f.\n  destruct f as [p qr].\n  destruct qr as [q|r].\n  left.\n  split; assumption.\n  right.\n  split; assumption.\n  intro f.\n  destruct f as [pq|pr].\n  destruct pq as [p q].\n  split.\n  exact p.\n  left.\n  exact q.\n  destruct pr as [p r].\n  split.\n  exact p.\n  right.\n  exact r.\nQed.\n\n(* Level 9 *)\n(* `exfalso`: Change any goal into `False` *)\n\nLemma contra (P Q : Prop) : (P ∧ ¬ P) → Q.\nProof.\n  intro f.\n  destruct f as [p np].\n  exfalso.\n  apply np.\n  exact p.\nQed.\n\n(* Level 10 *)\n(* `destruct (classic P) as [p|np]`: Do case distinction on `P` *)\n(* In other words, handle cases `P` and `¬P` separately *)\n(* Requires classical logic `Classical` *)\n\nLemma contrapositive2 (P Q : Prop) : (¬ Q → ¬ P) → (P → Q).\nProof.\n  intro f.\n  intro p'.\n  destruct (classic P) as [p|np];\n  destruct (classic Q) as [q|nq];\n  tauto.\nQed.\n", "meta": {"author": "uncomputable", "repo": "natural-number-game", "sha": "602e06e352f1accb13ef1a1a23f40c19d10c5444", "save_path": "github-repos/coq/uncomputable-natural-number-game", "path": "github-repos/coq/uncomputable-natural-number-game/natural-number-game-602e06e352f1accb13ef1a1a23f40c19d10c5444/Game/World/AdvancedProposition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7984222757938146}}
{"text": "Require Export P01.\n\n(** **** Problem #2: 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\n    Note that plus and multiplication are already defined in Coq.\n    use \"+\" for plus and \"*\" for multiplication.\n*)\n\nEval compute in 3 * 5.\nEval compute in 3+5*6.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => n * factorial n' end.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = 10 * 12.\nProof. reflexivity. Qed.\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/00/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.7983575753456034}}
{"text": "(* A sorting example : \n   (C) Yves Bertot, Pierre Casteran \n*)\n\n(**\nThis version uses some new features of Coq : Type Classes and User Defined Relations.\n\nThe function called \"aux\" in the book has been renamed to \"insert\" and \"equiv\" has \nbeen renamed to \"permutation\".\n*)\n\n\nRequire Import List  ZArith RelationClasses Morphisms\n               Extraction.\nOpen Scope Z_scope.\n\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 ->\n        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\nHint Constructors sorted :  sort.\n\nLemma sort_2357 :\n sorted (2 :: 3 :: 5 :: 7 :: nil).\nProof.\n auto with sort zarith.\nQed.\n\n(**\n  inversion lemma \n*)\n  \nTheorem sorted_inv :\n forall (z:Z) (l:list Z), sorted (z :: l) -> sorted l.\nProof.\n intros z l H; inversion H; auto with sort.\nQed.\n\n(*  Number of occurrences of z in l *)\n\nFixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%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\nExample ex0 : nb_occ 3 (3 :: 7 :: 3 :: nil) = 2%nat.\nProof. reflexivity. Qed.\n\n(* list l' is a permutation of list l *)\n\nDefinition permutation (l l':list Z) : Prop := \n    forall z:Z, nb_occ z l = nb_occ z l'.\n\n(* permutation is an equivalence ! *)\n\nInstance permutation_refl : Reflexive permutation.\nProof.\n intro x; red; trivial.\nQed.\n\nInstance  permutation_sym : Symmetric permutation.\nProof.\n intros x y Hxy ; unfold permutation; auto.\nQed.\n\nInstance permutation_trans : Transitive permutation.\nProof.\n intros l l' l'' H H0 z; rewrite H; now apply H0.\nQed.\n\n\nLemma permutation_cons :\n forall (z:Z) (l l':list Z), permutation l l' -> \n                             permutation (z :: l) (z :: l').\nProof.\n intros z l l' H z'; simpl; case (Z_eq_dec z' z); auto. \nQed.\n\n\nInstance cons_proper : Proper (eq ==> permutation ==> permutation) (@cons Z).\nProof.\n intros x y Hxy l l' Hll'; subst y; now apply permutation_cons.\nQed.\n\nLemma permutation_transpose :\n forall (a b:Z) (l l':list Z),\n   permutation l l' -> \n   permutation (a :: b :: l) (b :: a :: l').\nProof.\n intros a b l l' H z; simpl.\n case (Z_eq_dec z a); case (Z_eq_dec z b); \n  simpl; case (H z); auto.\nQed.\n\nHint Resolve permutation_cons permutation_refl permutation_transpose : sort.\n\n\n(* insertion of z into l at the right place \n   (assuming l is sorted) \n*)\n\nFixpoint insert (z:Z) (l:list Z)  : 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 :: (insert z l')\n      end\n  end.\n   \n\nLemma insert_permutation : forall (l:list Z) (x:Z), \n                  permutation (x :: l) (insert x l).\nProof.\n induction l as [|a l0 H]; simpl ; auto with sort.\n -  intros x; case (Z_le_gt_dec x a);\n      simpl; auto with sort.\n    +  intro H0; apply permutation_trans with (a :: x :: l0); \n       auto with sort.\nQed.\n\n\nLemma insert_sorted :\n forall (l:list Z) (x:Z), sorted l -> sorted (insert x l).\nProof.\n intros l x H; induction  H; simpl; auto with sort.\n -  case (Z_le_gt_dec x z); simpl;  auto with sort zarith.\n -   revert H H0 IHsorted; simpl; \n     case (Z_le_gt_dec x z2) ,  (Z_le_gt_dec x z1); \n       simpl; auto with sort zarith.\nQed.\n\n(* the sorting function *)\n\nDefinition sort :\n  forall l:list Z, {l' : list Z | permutation l l' /\\ sorted l'}.\n induction l as [| a l IHl]. \n -  exists (nil (A:=Z)); split; auto with sort.\n -  case IHl; intros l' [H0 H1].\n    exists (insert a l'); split.\n    + transitivity (a::l').\n      * now  rewrite H0. \n      * apply insert_permutation.\n    +  now apply insert_sorted. \nDefined.\n\nExtraction \"insert-sort\" insert sort.\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/ch1_overview/SRC/chap1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7983575709030353}}
{"text": "Require Import HoTT Nat.\n\nFixpoint plus (n m : nat) :=\n  match n with\n    | O => m\n    | S n' => S (n' + m)\n  end\n    \nwhere \"n + m\" := (plus n m) : nat_scope.\n\nDefinition lt (n m : nat) := {k : nat & n + S k = m}.\nNotation \"n < m\" := (lt n m) (at level 70) : nat_scope.\n\nTheorem O_S : forall n : nat, O <> S n.\nProof.\n  intros n H. apply nat_encode in H. contradiction.\nDefined.\n\nLemma plus_n_Sm : forall n m : nat, n + S m = S (n + m).\nProof.\n  intro n. induction n. \n  - reflexivity.\n  - intro m. apply (ap S). apply IHn.\nDefined.\n  \nLemma n_lt_O : forall n, ~ (n < O).\nProof.\n  intros n w.\n  induction w as [m p].\n  simpl in p.\n  apply (O_S (n + m)).\n  path_via (n + S m).\n  apply plus_n_Sm.\nDefined.\n\nLemma plus_n_O : forall n, n = n + O.\nProof.\n  induction n; simpl.\n  - reflexivity.\n  - apply (ap S IHn).\nDefined.\n\nLemma plus_comm : forall n m, n + m = m + n.\nProof.\n  induction n.\n  - intro m. apply plus_n_O.\n  - intro m. refine (_ @ (plus_n_Sm _ _)^). apply (ap S). apply IHn.\nDefined.\n\nLemma plus_n_k : forall n k, n + k = O -> n = O.\nProof.\n  induction n.\n  - reflexivity.\n  - intros k p. simpl in p. contradiction (O_S _ p^).\nDefined.\n\n\nLemma plus_O_r (n : nat) : n + O = n.\nProof.\n  induction n.\n  - reflexivity.\n  - apply (ap S IHn).\nDefined.\n\n\nLemma cancelL_plus : forall n m k, n + m = n + k -> m = k.\nProof.\n  induction n.\n  - intros m k p. apply p.\n  - intros m k p. apply IHn. apply S_inj. apply p.\nDefined.\n\nLemma cancelR_plus : forall n m k, m + n = k + n -> m = k.\nProof.\n  induction n.\n  - intros m k p. \n    path_via (m + O). symmetry. apply plus_O_r.\n    path_via (k + O). apply plus_O_r.\n  - intros m k p. apply IHn.\n    apply S_inj. simpl.\n    path_via (m + S n). symmetry. apply plus_n_Sm.\n    path_via (k + S n). apply plus_n_Sm.\nDefined.\n  \n\nGlobal Instance ishprop_lt : forall n m, IsHProp (n < m).\nProof.\n  intros n m. apply hprop_allpath. intros x y.\n  induction x as [k p], y as [r q].\n  apply path_sigma_hprop. simpl.\n  apply (S_inj _ _). apply (cancelL_plus n).\n  path_via m.\nDefined.\n\nLemma S_predn (n : nat) : n <> O -> S (pred n) = n.\nProof.\n  induction n; intro p; [contradiction p |]; reflexivity.\nDefined.\n    \n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n    | O, _ => n\n    | S k, O => n\n    | S k, S l => k - l\n  end\n\nwhere \"n - m\" := (minus n m) : nat_scope.\n\nLemma minus_O_r (n : nat) : n - O = n.\nProof.\n  by induction n.\nDefined.\n\nLemma minus_n_n (n : nat) : n - n = O.\nProof.\n  induction n.\n  - reflexivity.\n  - apply IHn.\nDefined.\n\nLemma not_nltn (n : nat) : ~ (n < n).\nProof.\n  intro p. induction p as [k p].\n  apply (O_S k). symmetry.\n  apply (cancelL_plus n).\n  path_via n.\n  symmetry. apply plus_O_r.\nDefined.\n  \n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => m + n' * m\n  end\n    \nwhere \"n * m\" := (mult n m) : nat_scope.\n\nLemma cancelL_plus_lt (n m k : nat) : (n + m < n + k) -> (m < k).\nProof.\n  induction n.\n  - apply idmap.\n  - intro p. apply IHn.\n    destruct p as [l r]. exists l. apply S_inj. path_via (S n + m + S l). \nDefined.\n\nLemma plus_assoc : forall n m k, (n + m) + k = n + (m + k).\nProof.\n  induction n.\n  - reflexivity.\n  - intros m k. simpl. apply (ap S (IHn m k)).\nDefined.\n\n\nLemma mult_1_r (n : nat) : n * 1 = n.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. apply (ap S IHn).\nDefined.\n\nLemma mult_O_r (n : nat) : n * O = O.\nProof.\n  induction n.\n  - reflexivity.\n  - apply IHn.\nDefined.\n\nLemma nat_dist_l (n m k : nat) : n * (m + k) = (n * m) + (n * k).\nProof.\n  induction n.\n  - reflexivity.\n  - refine ((ap (plus (m + k)) IHn) @ _).\n    refine (_ @ (plus_assoc _ _ _)).\n    refine ((plus_assoc _ _ _)^ @ _).\n    apply (ap (fun s => s + (n * k))). \n    refine ((plus_assoc _ _ _) @ _).\n    refine (_ @ (plus_assoc _ _ _)^).\n    apply (ap (plus m)).\n    apply plus_comm.\nDefined.\n\nLemma nat_dist_r (n m k : nat) : (n + m) * k = (n * k) + (m * k).\nProof.\n  induction n.\n  - reflexivity.\n  - refine (_ @ (plus_assoc _ _ _)^).\n    apply (ap (plus k) IHn).\nDefined.\n\n\nLemma mult_assoc (n m k : nat) : (n * m) * k = n * (m * k).\nProof.\n  induction n.\n  - reflexivity.\n  - simpl.\n    refine (_ @ (ap (fun s => (m * k) + s) IHn)).\n    apply (nat_dist_r m (n * m) k).\nDefined.\n\nLemma mult_comm (n m : nat) : n * m = m * n.\nProof.\n  induction n.\n  - symmetry. apply mult_O_r.\n  - refine ((ap (plus m) IHn) @ _).\n    refine (_ @ (nat_dist_l m 1 n)^).\n    f_ap. symmetry. apply mult_1_r.\nDefined.\n    \n\n(** * Exponential *)\n\nFixpoint exp (b e : nat) :=\n  match e with\n    | O => S O\n    | S e' => b * (exp b e')\n  end.\n\nLemma exp_sum (b n m : nat) : (exp b (n + m)) = (exp b n) * (exp b m).\nProof.\n  induction n.\n  - symmetry. apply plus_O_r.\n  - refine (_ @ (mult_assoc _ _ _)^). simpl. f_ap.\nDefined.\n\nLemma exp_power (b n m : nat) : (exp (exp b n) m) = (exp b (n * m)).\nProof.\n  induction m.\n  - apply (ap (exp b) (mult_O_r n))^.\n  - refine ((ap (mult (exp b n)) IHm) @ _).\n    refine ((exp_sum _ _ _)^ @ _). f_ap.\n    refine (_ @ (mult_comm _ _)^).\n    simpl. f_ap. apply mult_comm.\nDefined.\n\n\n(** * Factorial *)\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n    | O => (S O)\n    | S n' => S n' * fact n'\n  end.\n\nLemma fact_ne_O : forall n : nat, fact n <> O.\nProof.\n  induction n.\n  - intro p. apply (O_S _ p^).\n  - simpl. intro p. apply plus_n_k in p. contradiction.\nDefined.\n\nLemma O_lt_Sn (n : nat) : O < S n.\nProof.\n  exists n. reflexivity.\nDefined.\n\nDefinition le (n m : nat) := {k : nat & n + k = m}.\nNotation \"n <= m\" := (le n m) (at level 70) : nat_scope.\n\nLemma le_partition (n : nat) : forall m, (m <= n) + (n < m).\nProof.\n  induction n, m.\n  - left. exists O. reflexivity.\n  - right. apply O_lt_Sn.\n  - left. exists (S n). reflexivity.\n  - destruct (IHn m) as [H | H]; [left | right];\n      destruct H as [k p]; exists k; simpl; apply (ap S); apply p.\nDefined.\n\n(** * Division *)\n\nFixpoint sgn (n : nat) :=\n  match n with\n    | O => O\n    | S n' => (S O)\n  end.\n\nDefinition adf (n m : nat) := (n - m) + (m - n).\n\nLemma dec_nat (n m : nat) : (n = m) + ~ (n = m).\nAdmitted.\n\nFixpoint rem (n m : nat) :=\n  match n with\n    | O => O\n    | S n' => match m with\n                | O => O\n                | S m' => match (dec_nat (rem n' (S m')) m') with\n                            | inl _ => O\n                            | inr _ => S (rem n' (S m'))\n                          end\n              end\n  end.\n\nFixpoint quot (n m : nat) :=\n  match n with\n    | O => O\n    | S n' => match m with\n                | O => O\n                | S m' => match (dec_nat (rem (S n') m') O) with\n                            | inl _ => S (quot n' (S m'))\n                            | inr _ => quot n' (S m')\n                          end\n              end\n  end.\n\nDefinition nPk (n k : nat) := \n  match (le_partition n k) with\n    | inl _ => quot (fact n) (fact (n - k))\n    | inr _ => O\n  end.\n\nDefinition nCk (n k : nat) := quot (nPk n k) (fact k).\n\nLemma quot_n_1 (n : nat) : quot n 1 = n.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. destruct (dec_nat O O). \n    + apply (ap S IHn).\n    + contradiction (n0 1).\nDefined.\n\nLemma quot_n_n (n : nat) : (n <> O) -> (quot n n = 1%nat).\nAdmitted.\n\nLemma quot_plus (n m d : nat) : (quot n d) + (quot m d) = quot (n + m) d.\nAdmitted.\n\nLemma quot_mult (n1 n2 d1 d2 : nat) \n  : (quot n1 d1) * (quot n2 d2) = quot (n1 * n2) (d1 * d2).\nAdmitted.\n\nLemma nCO (n : nat) : nCk n O = (S O).\nProof.\n  induction n.\n  - unfold nCk. unfold nPk. simpl. destruct (dec_nat O O).\n    + simpl. destruct (dec_nat O O).\n      * reflexivity.\n      * contradiction (n 1).\n    + contradiction (n 1).\n  - unfold nCk in *. unfold nPk in *. simpl in *.\n    refine ((quot_n_1 _) @ _). apply quot_n_n. apply (fact_ne_O (S n)).\nDefined.\n\nLemma nCn (n : nat) : nCk n n = (S O).\nProof.\n  induction n.\n  - unfold nCk. refine ((quot_n_1 _) @ _).\n    unfold nPk. simpl. destruct (dec_nat O O).\n    + reflexivity.\n    + contradiction (n 1).\n  - unfold nCk. simpl. unfold nPk.\n    destruct (le_partition (S n) (S n)).\n    + rewrite minus_n_n. rewrite quot_n_1. apply quot_n_n.\n      apply (fact_ne_O (S n)).\n    + destruct l as [m p].\n      contradiction (O_S m). symmetry.\n      apply (cancelL_plus (S n)). refine (p @ _).\n      symmetry. apply plus_O_r.\nDefined.\n\nLemma nPO (n : nat) : nPk n O = (S O).\nProof.\n  induction n.\n  - unfold nPk. simpl. destruct (dec_nat O O).\n    + reflexivity.\n    + contradiction (n 1).\n  - unfold nPk. simpl. apply quot_n_n.\n    apply (fact_ne_O (S n)).\nDefined.\n\nLemma OPO : nPk O O = (S O).\nProof.\n  unfold nPk. simpl. destruct (dec_nat O O).\n  - reflexivity.\n  - contradiction (n 1).\nDefined.\n\nLemma OPn (n : nat) : (n <> O) -> (nPk O n = O).\nProof.\n  intro p. unfold nPk. destruct (le_partition O n).\n  - contradiction p. destruct l as [m q]. apply (plus_n_k _ _ q).\n  - reflexivity.\nDefined.\n\nLemma nPn (n : nat) : nPk n n = fact n.\nProof.\n  induction n.\n  - unfold nPk. simpl. destruct (dec_nat O O).\n    + reflexivity.\n    + contradiction (n 1).\n  - unfold nPk. simpl. destruct (le_partition n n).\n    + path_via (quot (fact (S n)) (S O)).\n      * f_ap. path_via (fact O). f_ap. apply minus_n_n.\n      * apply quot_n_1.\n    + contradiction (not_nltn _ l).\nDefined.\n\nLemma SnPSk (n k : nat) : nPk (S n) (S k) = (S n) * (nPk n k).\nProof.\n  unfold nPk. simpl. destruct (le_partition n k).\n  - symmetry. \n    path_via (quot (fact n) (fact (n - k)) + quot (n * (fact n)) (fact (n - k))).\n    + f_ap. path_via (quot n 1 * quot (fact n) (fact (n - k))).\n      * f_ap. symmetry. apply quot_n_1.\n      * refine ((quot_mult _ _ _ _) @ _). f_ap. apply plus_O_r.\n    + apply quot_plus.\n  - simpl. symmetry. apply mult_O_r.\nDefined.\n  \nLemma nP1 (n : nat) : nPk n 1 = n.\nProof.\n  induction n.\n  - reflexivity.\n  - unfold nPk. destruct (le_partition (S n) 1).\n    + refine ((quot_plus _ _ _)^ @ _).\n      path_via (1 + quot (n * fact n) (fact ((S n) - 1))).\n      * refine (ap (fun s => s + quot (n * fact n) (fact ((S n) - 1))) _).\n        simpl. path_via (quot (fact n) (fact n)). f_ap. f_ap. apply minus_O_r.\n        apply quot_n_n. apply (fact_ne_O n).\n      * apply (ap S). path_via (quot (n * fact n) (1 * fact n)).\n        f_ap. simpl. refine (ap fact (minus_O_r n) @ (plus_O_r _)^).\n        refine ((quot_mult _ _ _ _)^ @ _).\n        refine (_ @ (quot_n_1 n)). refine (_ @ (mult_1_r _)).\n        apply (ap (mult (quot n 1))). apply quot_n_n. apply fact_ne_O.\n    + destruct l as [m p].\n      simpl in p. apply S_inj in p.\n      contradiction (O_S (n + m)). refine (p^ @ _).\n      apply plus_n_Sm.\nDefined.\n      \n      \n      \nLemma foo (n k : nat)\n  : quot n.+1 k.+1 = 1 + quot (nPk n k.+1) (fact k.+1).\nProof.\n  induction k.\n  - refine ((quot_n_1 _) @ _). apply (ap S).\n    symmetry. refine ((quot_n_1 _) @ (nP1 _)). \nAdmitted.\n\nLemma SnCSk (n k : nat) : nCk (S n) (S k) = (nCk n k) + (nCk n (S k)).\nProof.\nAdmitted.\n", "meta": {"author": "jdoughertyii", "repo": "hott-species", "sha": "d0d45a7897e262b39c9ef13ca336be587acec901", "save_path": "github-repos/coq/jdoughertyii-hott-species", "path": "github-repos/coq/jdoughertyii-hott-species/hott-species-d0d45a7897e262b39c9ef13ca336be587acec901/coq/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7980460538936165}}
{"text": "Require Import nat.\nRequire Import syntax.\nRequire Import state.\nRequire Import fold_constants.\n\n\nExample fold_aexp1 : fold_constants_aexp\n    (AMult (APlus (ANum 1) (ANum 2)) (AKey x)) = AMult (ANum 3) (AKey x).\nProof. reflexivity. Qed.\n\nExample fold_aexp2 : fold_constants_aexp\n    (AMinus \n        (AKey x) \n        (APlus \n            (AMult \n                (ANum 0) \n                (ANum 6))\n             (AKey y))) =\n    (AMinus\n        (AKey x)\n        (APlus\n            (ANum 0)\n            (AKey y))).\nProof. reflexivity. Qed.\n\n\nExample fold_bexp1 : fold_constants_bexp \n    (BAnd BTrue (BNot (BAnd BFalse BTrue))) = BTrue.\nProof. reflexivity. Qed.\n\n\nExample fold_bexp2 : fold_constants_bexp\n    (BAnd (BEq (AKey x) (AKey y))\n          (BEq (ANum 0)\n               (AMinus (ANum 2) (APlus (ANum 1) (ANum 2))))) =\n    BAnd (BEq (AKey x) (AKey y)) BTrue.\nProof. reflexivity. Qed.\n\nExample fold_com1 : fold_constants_com \n    (x ::= APlus (ANum 4) (ANum 5) ;;\n     y ::= AMinus (AKey x) (ANum 3);;\n     IFB BEq (AMinus (AKey x) (AKey y))\n             (APlus (ANum 2) (ANum 4))\n     THEN\n        SKIP\n     ELSE\n        y ::= ANum 0\n     FI;;\n     IFB BLe (ANum 0) \n             (AMinus (ANum 4) (APlus (ANum 2) (ANum 1)))\n     THEN\n        y ::= ANum 0\n     ELSE\n        SKIP\n     FI;;\n     WHILE BEq (AKey y) (ANum 0) DO\n        x ::= APlus (AKey x) (ANum 1)\n     END)\n     =\n     (x ::= ANum 9;;\n      y ::= AMinus (AKey x) (ANum 3);;\n      IFB BEq (AMinus (AKey x) (AKey y)) (ANum 6)\n      THEN\n        SKIP\n      ELSE\n        y ::= ANum 0\n      FI;;\n      y ::= ANum 0;;\n      WHILE BEq (AKey y) (ANum 0) DO\n        x ::= APlus (AKey x) (ANum 1)\n      END).\nProof. reflexivity. Qed.      \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/test_fold_constants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7980460537874137}}
{"text": "\n\nRequire Import Ring.\nDefinition v2 (A : Type) := A -> A -> A.\n(* Really it should be a linear function. *)\n\nDefinition xhat {A : Type} : v2 A := fun  x y => x.\nDefinition yhat {A : Type} : v2 A := fun  x y => y.\n \nClass SemiRing (A : Type) :=\n  {\n    plus : A -> A -> A ;\n    one : A ;\n    zero : A ;\n    times : A -> A -> A ;\n    (* Plus all the laws. *)\n                             \n  }.\n\nSearch Nat.add.\nLocate \"+\".\nInstance seminat : SemiRing nat := {\n                        plus := Nat.add;\n                        one := 1;\n                        zero := 0;\n                        times := Nat.mul\n                                }.\nDefinition vadd {A : Type} {ringa : SemiRing A} (v : v2 A) (w : v2 A) : v2 A :=\n  fun x1 y1 => plus (v x1 y1) (w x1 y1).\n\nCompute vadd xhat yhat 1 2.\n\nDefinition smul {A : Type} {ringa : SemiRing A} (s : A) (v : v2 A) : v2 A :=\n  fun x1 y1 => times s (v x1 y1).\n\nDefinition dot {A : Type} {ringa : SemiRing A} (v : v2 A) (w : v2 A) : A :=\n  plus (times (v one zero) (w one zero)) (times (v zero one ) (w zero one)).\n\nCompute dot xhat yhat.\nCompute dot xhat xhat.\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/dvec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7980177483960073}}
{"text": "(* looked this one up  *)\n\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   | B0 n => B1 n  \n   | B1 n => B0 (incr n)\n   end. \n  \nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with \n  | Z => O \n  | B0 n => 2 * bin_to_nat n \n  | B1 n => 1 + 2 * bin_to_nat n \n  end. \n   \n\nExample test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr5 : bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr6 : bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\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/basics/exercises/binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.7980002162187103}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Logic.\nFrom Coq Require Import Lia.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS (n : nat) (H : ev n) : ev (S (S n)).\n  \n  Theorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\nintros.\ninduction n.\nsimpl.\napply ev_0.\nsimpl.\napply ev_SS.\nexact IHn.\nQed.\n\nTheorem ev_inversion :\n  forall (n : nat), ev n ->\n    (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n  intros n E.\n  destruct E as [ | n' E'] eqn:EE.\n  - (* E = ev_0 : ev 0 *)\n    left. reflexivity.\n  - (* E = ev_SS n' E' : ev (S (S n')) *)\n    right. exists n'. split. reflexivity. apply E'.\nQed.\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'] eqn:EE.\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\nTheorem  evSS_ev_remember : forall n,\n  ev (S (S n)) -> ev n.\n  Proof.\n  intros n E.\n  remember (S (S n)) as k eqn:Hk.\n  destruct E as [|n' E'] eqn:EE.\n  discriminate Hk.\n  injection Hk as Heq.\n  rewrite <- Heq.\n  exact E'.\n  Qed.\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\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\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.\nProof.\n  intros H. inversion H. Qed.\n  \nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros.\n  inversion H. inversion H1.\n  exact H3.\n  Qed.\nTheorem ev5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H3.\n  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 : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\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    unfold Even. 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.\n    unfold Even. exists (S k). simpl. 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.\nintros.\ninduction H.\napply H0.\nsimpl.\napply ev_SS.\napply IHev.\nQed.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\nintros.\ninduction H0.\nsimpl in H.\nexact H.\nsimpl in H.\n\ninversion H.\napply IHev in H2.\nexact H2.\nQed.\n\nModule Playground.\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\nDefinition lt (n m:nat) := le (S n) m.\nNotation \"m < n\" := (lt m n).\nEnd Playground.\n \n \nInductive square_of : nat -> nat -> Prop :=\n  | sq n : square_of n (n * n).\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : next_nat n (S 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  \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\n\nInductive subseq : list nat -> list nat -> Prop :=\n| empty k: subseq [] k\n| extend a b c (H:subseq a b): subseq a (c::b)\n| same a b c (H:subseq a b): subseq (c::a) (c::b)\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\nintros.\ninduction l.\napply (empty []).\napply (same).\napply IHl.\nQed.\n\nLemma lemma1: forall (x:nat) l1 l2, (x::l1) ++ l2 = x::(l1++l2).\nintros.\ninduction l1.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2->\n  subseq l1 (l2 ++ l3).\nProof.\nintros.\ninduction H.\napply empty.\nrewrite lemma1.\napply extend.\nexact IHsubseq.\nrewrite lemma1.\napply same.\nexact IHsubseq.\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\nintros.\ngeneralize dependent l1.\ninduction H0.\nintros.\ninversion H.\napply empty.\nintros.\napply extend.\napply IHsubseq in H.\nexact H.\nintros.\ninversion H.\napply empty.\napply extend.\napply IHsubseq.\napply H3.\napply same.\napply IHsubseq.\napply H3.\nQed.\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).\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n  | MEmpty : [] =~ EmptyStr\n  | MChar x : [x] =~ (Char x)\n  | MApp s1 re1 s2 re2\n             (H1 : s1 =~ re1)\n             (H2 : s2 =~ re2)\n           : (s1 ++ s2) =~ (App re1 re2)\n  | MUnionL s1 re1 re2\n                (H1 : s1 =~ re1)\n              : s1 =~ (Union re1 re2)\n  | MUnionR re1 s2 re2\n                (H2 : s2 =~ re2)\n              : s2 =~ (Union re1 re2)\n  | MStar0 re : [] =~ (Star re)\n  | MStarApp s1 s2 re\n                 (H1 : s1 =~ re)\n                 (H2 : s2 =~ (Star re))\n               : (s1 ++ s2) =~ (Star re)\n  where \"s =~ re\" := (exp_match s re).\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n  match l with\n  | [] => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n  \n  Lemma MStar1 :\n forall T s (re : reg_exp T) ,\n    s =~ re ->\n    s =~ Star re.\n    Proof.\n    intros.\n    assert (forall X (l:list X), l++[] = l).\n    induction l.\n    reflexivity.\n    simpl.\n    rewrite IHl.\n    reflexivity.\n    rewrite <- (H0 T s).\n    apply (MStarApp s [] re).\n    exact H.\n    apply MStar0.\n    Qed.\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros.\n  unfold not.\n  intros.\n  inversion H.\n  Qed.\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros.\n  destruct H.\n  apply MUnionL.\n  exact H.\n  apply MUnionR.\n  exact H.\n  Qed.\n  \n  \nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros.\n  induction ss.\n  simpl.\n  apply MStar0.\n  simpl.\n  apply MStarApp.\n  apply H.\n  simpl.\n  left.\n  reflexivity.\n  apply IHss.\n  intros.\n  apply H.\n  simpl.\n  right.\n  apply H0.\n  Qed.\n\nFixpoint re_not_empty {T : Type} (re : reg_exp T) : bool :=\nmatch re with \n|EmptySet => false\n|EmptyStr => true\n|Char _ => true\n| App r1 r2 => re_not_empty r1 && re_not_empty r2\n| Union r1 r2 => re_not_empty r1 ||re_not_empty r2\n|Star _ => true\nend.\n\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros.\n  split.\n  intros.\n  destruct H.\n  induction H.\n  reflexivity.\n  reflexivity.\n  simpl.\n  rewrite IHexp_match1, IHexp_match2.\n  reflexivity.\n  simpl.\n  rewrite IHexp_match.\n  reflexivity.\n  simpl.\n  rewrite IHexp_match.\n  destruct (re_not_empty re1).\n  reflexivity.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  intros.\n  induction re.\n  simpl in H.\n  discriminate H.\n  exists [].\n  apply MEmpty.\n  exists [t].\n  apply MChar.\n  simpl in H.\n  apply andb_true_iff in H.\n  destruct H.\n  apply IHre1 in H.\n  apply IHre2 in H0.\n  destruct H.\n  destruct H0.\n  exists (x++x0).\n  apply MApp.\n  exact H.\n  exact H0.\n  simpl in H.\n  apply orb_true_iff in H.\n  destruct H.\n  apply IHre1 in H.\n  destruct H.\n  exists x.\n  apply MUnionL.\n  exact H.\n  apply IHre2 in H.\n  destruct H.\n  exists x.\n  apply MUnionR.\n  exact H.\n  exists [].\n  apply MStar0.\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  \nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  (* WORKED IN CLASS *)\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.\n  split.\n  intros.\n  inversion H.\n  reflexivity.\n  unfold not in H1.\n  apply H1 in H0.\n  destruct H0.\n  intros.\n  rewrite H0 in H.\n  inversion H.\n  exact H1.\n  Qed.\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\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\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.\nTheorem eqbP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros n l.\n  induction l.\n  simpl.\n  intros.\n  intros f.\n  destruct f.\n  simpl.\n  destruct (eqbP n x).\n  intros.\n  simpl in H0.\n  discriminate H0.\n  intros.\n  intros f.\n  destruct f.\n  apply H.\n  symmetry.\n  exact H1.\n  apply IHl.\n  apply H0.\n  apply H1.\n  \n Qed.\n  \nInductive nostutter {X:Type} : list X -> Prop :=\n| emptylist: nostutter []\n| single x:  nostutter [x]\n| diff x y l (H:nostutter (y::l)) (K: x<>y) : nostutter (x::y::l).\n\nInductive merge {X:Type} : list X -> list X -> list X -> Prop:=\n| doubleempty: merge [] [] []\n| left x y z l(H:merge y z l) : merge (x::y) z (x::l)\n| right x y z l ( H:merge y z l): merge y (x::z) (x::l).\n\nTheorem add_in_front_same: forall X (x:X) l1 l2, l1=l2-> x::l1=x::l2.\nintros.\nrewrite H.\nreflexivity.\nQed.\nTheorem filtertest: \nforall (X:Type) l l1 l2 (test: X->bool), merge l1 l2 l-> forallb test l1=true -> \nforallb  (fun x => negb (test x)) l2 = true -> filter test l =l1.\nintros.\ninduction H.\nreflexivity.\nsimpl.\nsimpl in H0.\ndestruct (test x) eqn:K.\napply add_in_front_same.\napply IHmerge.\napply H0.\napply H1.\ndiscriminate H0.\nsimpl.\ndestruct (test x) eqn:k.\nsimpl in H1.\nrewrite k in H1.\nsimpl in H1.\ndiscriminate H1.\napply IHmerge.\napply H0.\nsimpl in H1.\nrewrite k in H1.\nsimpl in H1.\nexact H1.\nQed.\n\n", "meta": {"author": "hei411", "repo": "software_foundations_coq", "sha": "49e302afc90941ef142cea64a910051e8d15749d", "save_path": "github-repos/coq/hei411-software_foundations_coq", "path": "github-repos/coq/hei411-software_foundations_coq/software_foundations_coq-49e302afc90941ef142cea64a910051e8d15749d/logical_foundations/Indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984213, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7979931960135836}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Tactics.\nRequire Import Poly.\nRequire Import Nat.\nRequire Import Arith.\nRequire Import Induction.\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma and_intro: forall A B: Prop, A->B->A/\\B.\nProof.\n  intros A B HA HB.\n  split.\n  apply HA.\n  apply HB.\nQed.\n\nExample and_exercise:\n  forall n m: nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  destruct n as [|n'] eqn: En.\n  - simpl in H. split. \n    * reflexivity.\n    * apply H.\n  - discriminate 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] eqn: HE.\n  rewrite Hn. apply Hm.\nQed.\n\nLemma proj1: forall P Q: Prop, P /\\ Q -> P.\nProof.\n  intros P Q [PH _].\n  apply PH.\nQed.\n\nLemma proj2: forall P Q: Prop, P /\\ Q -> Q.\nProof.\n  intros P Q [_ QH].\n  apply QH.\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. split.\n  apply HP. apply HQ. apply HR.\nQed.\n\nLemma or_intro_l: forall a b: Prop, a-> a \\/ b.\nProof.\n  intros a b H.\n  left. apply H.\nQed.\n\nLemma zero_or_succ: forall n: nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n'].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nCheck not.\n\nTheorem ex_falso_quodlibet: forall p: Prop, False -> p.\nProof.\n  intros p contra.\n  destruct contra.\nQed.\n\nFact not_implies_our_not: forall P: Prop, ~P -> (forall Q:Prop, P->Q).\nProof.\n  intros P H1 Q H2.\n  apply H1 in H2.\n  destruct H2.\nQed.\n\nTheorem not_False: ~False.\nProof. \n  unfold not.\n  intros H. apply H.\nQed.\n\nTheorem contradiction_implies_anything: forall P Q: Prop, (P/\\~P) -> Q.\nProof.\n  intros P Q [H1 H2].\n  apply H2 in H1.\n  destruct H1.\nQed.\n\nTheorem double_neg: forall P: Prop, P -> ~~P.\nProof.\n  intros P H.\n  unfold not.\n  intros H1.\n  apply H1 in H.\n  apply H.\nQed.\n\nTheorem contraposite: forall (p q: Prop), (p->q)->(~q->~p).\nProof.\n  intros p q H.\n  unfold not. intros H1.\n  intros H2.\n  apply H in H2.\n  apply H1 in H2.\n  apply H2.\nQed.\n\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\nTheorem not_true_is_false: forall b: bool,\n  b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn: E.\n  - exfalso. apply H. reflexivity.\n  - reflexivity.\nQed.\n\nLemma True_is_true: True.\nProof. apply I. Qed.\n\nTheorem iff_sym: forall p q: Prop, (p<->q) -> (q<->p).\nProof.\n  intros P Q [H1 H2].\n  split.\n  - apply H2.\n  - apply H1.\nQed.\n\nLemma not_true_iff_false: forall b, b<>true <-> b = false.\nProof.\n  intros b.\n  split.\n  - apply not_true_is_false.\n  - intros H. unfold not. rewrite H. intros H1. discriminate H1.\nQed.\n\nTheorem  or_distributes_over_and: forall p q r: Prop, 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\nCheck mult_comm.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0\\/ m = 0.\nProof.\n  split.\n  - intros H. destruct n as [|n'] eqn: E.\n    + left. reflexivity.\n    + simpl in H. right. destruct m as [|m'] eqn:E1.\n      * reflexivity.\n      * simpl in H. discriminate H.\n  - intros H. destruct H as [H|H].\n    + rewrite H. reflexivity.\n    + rewrite H. apply mult_comm.\nQed.\n\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: 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.\n  apply mult_0.\n  apply H.\nQed.\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 H.\n  unfold not.\n  intros H1.\n  destruct H1 as [x E].\n  apply E. 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' H]. destruct H as [H|H].\n    * left. exists x'. apply H.\n    * right. exists x'. apply H.\n  - intros [[x' H]|[x' H]].\n    * exists x'. left. apply H.\n    * exists x'. right. apply H.\nQed.\n\n\nFixpoint In {X: Type} (x: X) (l: list X): Prop :=\n  match l with\n  | nil => False\n  | h::t => x = h \\/ In x t\n  end.\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.\n  induction l as [|h t H].\n  - intros H1. simpl. unfold In in H1. apply H1.\n  - simpl.\n    intros H1.\n    destruct H1 as [H1|H1].\n    * left. rewrite H1. reflexivity.\n    * apply H in H1.\n      right. apply H1.\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 A B f l y. split.\n  - induction l as [|h t H].\n    * simpl. intros H'. destruct H'.\n    * simpl. intros H'. destruct H' as [H'|H'].\n      + exists h. split.\n        { rewrite H'. reflexivity. }\n        { left. reflexivity. }\n      + apply H in H'.\n        destruct H' as [x' H'].\n        exists x'.\n        destruct H' as [H'1 H'2].\n        split.\n        { apply H'1. }\n        { right. apply H'2. }\n  - intros [x' H].\n    induction l as [|h t iH].\n    * destruct H as [H1 H2].\n      simpl in H2.\n      destruct H2.\n    * simpl. destruct H as [H1 H2].\n      simpl in H2.\n      destruct H2 as [H2 | H2].\n      + rewrite H2 in H1.\n        left. symmetry. apply H1.\n      + right. apply iH. split.\n        { apply H1. }\n        { apply H2. }\nQed.\n\n\nLemma In_app_iff: forall A l1 l2 (a: A),\n  In a (l1 ++ l2) <-> In a l1 \\/ In a l2.\nProof.\n  split. \n  - intros H. induction l1 as [|h t iH].\n    + right. simpl in H. apply H.\n    + simpl in H. destruct H as [H | H].\n      * left. rewrite H. simpl. left. reflexivity.\n      * simpl. apply or_assoc. right.\n        apply iH. apply H.\n  - intros H. destruct H as [H | H].\n    + induction l1 as [|h t iH].\n      * destruct H.\n      * simpl. simpl in H. destruct H as [H|H].\n        { left. apply H. }\n        { right. apply iH. apply H. }\n    + induction l1 as [|h t iH].\n      * apply H.\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: \n  forall T (P: T->Prop) (l: list T), \n    (forall x, In x l -> P x) <-> All P l.\nProof.\n  split.\n  - intros H.\n    induction l as [|h t iH].\n    + reflexivity.\n    + simpl. simpl in H.\n      split. \n      * apply H. left. reflexivity.\n      * apply iH. intros x H'. apply H. right. apply H'.\n  - intros H.\n    induction l as [|h t iH].\n    + intros x H'. destruct H'.\n    + simpl. intros x H'. destruct H' as [H' | H'].\n      * simpl in H. destruct H as [H0 H1]. rewrite <- H' in H0. apply H0.\n      * simpl in H. destruct H as [H0 H1]. \n        specialize (iH H1). apply iH with (x) in H'.\n        apply H'.\nQed.\n\n\nDefinition combine_odd_even (Podd Peven: nat -> Prop): nat-> Prop :=\n  fun n: nat => if odd n then Podd n else Peven n.\n\nTheorem combine_odd_even_intro:\n  forall (Podd Peven: nat -> Prop) (n: nat),\n    (odd n = true -> Podd n) -> (odd n = false -> Peven n) -> combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n H1 H2.\n  unfold combine_odd_even.\n  destruct (odd 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 -> odd n = true -> 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.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven: nat -> Prop) (n: nat),\n    combine_odd_even Podd Peven n -> odd n = false -> 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\nLemma plus_comm3_take3: 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\nTheorem in_not_nil: forall A (x: A) (l: list A), In x l -> l <> [].\nProof.\n  intros A x l H.\n  unfold not. intro H1. destruct l eqn: E.\n  - simpl in H. destruct H.\n  - discriminate H1.\nQed.\n\n\nExample lemma_application_ex:\n  forall {n: nat} {ns: list nat}, In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H) as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\nFixpoint rev_append {X} (l1 l2: list X) : list X :=\n  match l1 with\n  | [] => l2\n  | x :: xs => rev_append xs (x :: l2)\n  end.\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\nAxiom functional_extensionlity: \n  forall (X Y: Type) {f g: X -> Y}, (forall x: X, f x = g x) -> f = g.\n\n\nLemma rev_app: forall X (a b c: list X), rev_append a (b ++ c) = rev_append a b ++ c.\nProof.\n  intros X a.\n  induction a as [|h t iH].\n  - reflexivity.\n  - simpl. intros b c. \n    rewrite <- iH. apply f_equal.\n    induction c as [|hc tc iHc].\n    * reflexivity.\n    * simpl. reflexivity.\nQed.\n\nLemma tr_rev_correct: forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionlity.\n  intros x.\n  induction x as [|h t iH].\n  - reflexivity.\n  - unfold tr_rev . simpl.\n    unfold tr_rev in iH. \n    rewrite <- iH.\n    replace ([h]) with ([] ++ [h]). rewrite rev_app. reflexivity.\n    unfold app. reflexivity.\nQed.\n\n\n\nLemma evenb_double: forall k, evenb (double k) = true.\nProof.\n  intros k.\n  induction k as [|k' iHk].\n  - reflexivity.\n  - simpl. apply iHk.\nQed.\n\nLemma evenb_double_conv: \n  forall n, exists k, n = if evenb n then double k else S (double k).\nProof.\n  intros n.\n  induction n as [|n' iHn].\n  - simpl. exists 0. reflexivity.\n  - destruct (evenb n') eqn: E.\n    + rewrite evenb_S. rewrite E. simpl. destruct iHn as [n'' iHn].\n      exists n''. f_equal. apply iHn.\n    + rewrite evenb_S.  rewrite E. simpl. destruct iHn as [n'' iHn].\n      exists (S n'').  rewrite iHn.\n      assert (H: forall x, double (S x) = S (S (double x))).\n      * destruct x as [|x'].\n        { reflexivity. }\n        { simpl. reflexivity. }\n      * rewrite H. reflexivity.\nQed.\n\nTheorem eqb_true: forall n m, n =? m = true -> n = m.\nProof.\n  intros n.\n  induction n as [|n' iHn'].\n  - intros m H. destruct m as [| m'].\n    + reflexivity.\n    + discriminate H.\n  - intros m H. destruct m as [| m'].\n    + discriminate H.\n    + apply f_equal.\n      apply iHn'.\n      apply H.\nQed.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n  n1 =? n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply eqb_true.\n  - intros H. rewrite H. rewrite <- eqb_refl. reflexivity.\nQed.\n\nLemma andb_truee_iff: forall b1 b2: bool,\n  andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  split.\n  - intros H.\n    destruct b1 eqn: E1.\n    + destruct b2 eqn: E2.\n      * split. \n        { reflexivity. }\n        { reflexivity. }\n      * discriminate H.\n    + destruct b2 eqn: E2.\n      * discriminate H.\n      * discriminate H.\n  - intros [H1 H2].\n    rewrite H1. apply H2.\nQed.\n\nCheck eqb_refl.\n\nTheorem eqb_neq: \n  forall (x y: nat), x =? y = false <-> x<>y.\nProof.\n  split.\n  - intros H.\n    unfold not.\n    intros H1.\n    rewrite H1 in H.\n    rewrite <- eqb_refl in H.\n    discriminate H.\n  - intros H1.\n    unfold not in H1.\n    destruct (x=?y) eqn: E.\n    + apply eqb_eq in E. \n      apply H1 in E.\n      destruct E.\n    + reflexivity.\nQed.\n\nFixpoint eqb_list {A: Type} (eqb: A->A->bool) (l1 l2: list A): bool :=\n  match l1, l2 with\n  | [], [] => true\n  | h1::t1, h2::t2 => if eqb h1 h2 then eqb_list eqb t1 t2 else false\n  | _, _ => false\n  end.\n\n\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 [|h t iH1].\n  + destruct l2.\n    - split. \n      * intros _. reflexivity.\n      * intros _. reflexivity.\n    - split. \n      * simpl. intros H'. discriminate H'.\n      * simpl. intros H'. discriminate H'. \n  + destruct l2.\n    - split. \n      * simpl. intros H'. discriminate H'.\n      * simpl. intros H'. discriminate H'.\n    - split. \n      * simpl. intros H'. destruct (eqb h x) eqn: E.\n        { apply iH1 in H'. rewrite H'. f_equal.\n          apply H. apply E. }\n        { discriminate H'. }\n      * simpl. intros H'. injection H' as H1 H2.\n        apply H in H1.  rewrite H1.  apply iH1. apply H2. \nQed.\n\nFixpoint forallb {X: Type} (test: X->bool) (l: list X): bool :=\n  match l with\n  | [] => true\n  | h::t => andb (test h) (forallb test t)\n  end.\nTheorem forallb_true_iff: forall X test (l: list X),\n  forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  split. \n  - intros H.\n    induction l as [|h t iH].\n    + reflexivity. \n    + simpl. simpl in H. destruct (test h) eqn: E.\n      * simpl in H. split. \n        { reflexivity. } \n        { apply iH.  apply H. }\n      * discriminate H. \n  - intros H. \n    induction l as [|h t iH].\n    + reflexivity.\n    + simpl. simpl in H. destruct H as [H1 H2].\n      rewrite H1. simpl. apply iH.  apply H2. \nQed.\n\nTheorem excluded_middle_irrefutable: forall (P: Prop), ~~(P\\/~P).\nProof.\n  unfold not.\n  intros P H.\n  apply H. \n  right.\n  intros H1.\n  apply H. \n  left.\n  apply H1. \nQed.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~P.\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 H1 X P H2 x.\n  unfold excluded_middle in H1. \n  destruct (H1 (P x)) as [H1' | H1''].\n  - apply H1'. \n  - exfalso. apply H2. exists x. apply H1''.\nQed.\n    \n\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, ~(~P/\\~Q) -> P\\/Q.\nDefinition implies_to_or := forall P Q:Prop, (P->Q) -> (~P\\/Q).\n\nTheorem excluded_middle_to_double_negation_elimination: excluded_middle -> double_negation_elimination.\nProof.\n  unfold double_negation_elimination.\n  unfold excluded_middle.\n  intros H P.\n  unfold not.\n  intros H1.\n  destruct (H P) as [H'|H'].\n  + apply H'.\n  + exfalso. apply H1. apply H'.\nQed.\n\n\nTheorem double_negation_elimination_to_de_morgan_not_and_not:\n  double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  unfold de_morgan_not_and_not. \n  unfold double_negation_elimination.\n  unfold not.\n  intros H P Q H1.\n \n  \n  \n\n", "meta": {"author": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7979931676062952}}
{"text": "(* Definition *)\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\nTheorem nat_equals_self : forall n : nat, n =? n = true.\nProof.\n  intros n. induction n as [| n' IH].\n    - reflexivity.\n    - simpl. rewrite -> IH. reflexivity.\nQed.\n\nModule NatList.\n\n(* Definition *)\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\n(* Definition *)\nTheorem add_0_r : forall n:nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n.\n  - simpl. rewrite add_0_r. reflexivity.\n  - simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity.\nQed.\n\n(* Definition *)\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' : 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\n(* Exercise *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\n(* Exercise *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p.\n  rewrite <- snd_fst_is_swap.\n  simpl. reflexivity.\nQed.\n\n(* Definition *)\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 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\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\n(* Exercise *)\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | n :: t => n :: nonzeros t\n  end.\n\nExample test_nonzeros : nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl nonzeros. reflexivity.\nQed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | n :: t => if odd n \n                  then n :: oddmembers t \n                else \n                  oddmembers t\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  | n :: t => if odd n \n                  then 1 + countoddmembers t \n                else \n                  countoddmembers t\n  end.\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. simpl. reflexivity. Qed.\nExample test_countoddmembers3 : countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise *)\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:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n(* Definition *)\nDefinition bag := natlist.\n\n(* Exercise *)\nFixpoint count (v:nat) (s:bag) : nat := \n  match s with\n  | nil => 0\n  | x :: t => count v t + (if eqb x v then 1 else 0)\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 : bag -> bag -> bag := \n  app.\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  v :: s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v : nat) (s : bag) : bool := \n  leb 1 (count v s).\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 *)\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with \n  | nil => nil\n  | x :: t => if eqb x v \n                  then t \n                else \n                  x :: 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  | x :: t => if eqb x v \n                  then remove_all v t \n                else \n                  x :: remove_all v t\n  end. \n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool := \n  match s1, s2 with\n  | nil, _ => true\n  | _, nil => false\n  | x :: t, s2 => if member x s2 \n                        then subset t (remove_all x s2) \n                      else \n                        false\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise *)\nTheorem bag_count_add :\n  forall v n bag, count v bag = n -> count v (add v bag) = S n.\nProof.\n  intros v n bag.\n  simpl. intros H.\n  rewrite H.\n  assert (forall m, eqb m m = true) as HH. \n  { induction m.\n    - reflexivity.\n    - simpl. rewrite IHm. reflexivity.\n  }\n  rewrite HH. apply add_comm.\nQed.\n\n(* Definition *)\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. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\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\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite-> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length.\n    simpl. rewrite -> IHl'. rewrite add_comm.\n    reflexivity.\nQed.\n\n(* Exercise *)\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [|x xs].\n  - reflexivity.\n  - simpl. rewrite -> IHxs. 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 [|x xs].\n  - (*Case \"[]\"*)\n    simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  - (*Case \"x :: xs\"*)\n    simpl.\n    rewrite IHxs.\n    simpl.\n    rewrite app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. simpl. rewrite -> IH.\n    reflexivity.\nQed.\n\n(* Exercise *)\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  rewrite -> (app_assoc (l1 ++ l2) l3 l4).\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 [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. destruct a.\n    + reflexivity.\n    + reflexivity.\nQed.\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  | a :: l1', b :: l2' =>\n    if a =? b then eqblist l1' l2'\n    else 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  induction l as [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> nat_equals_self. rewrite <- IH.\n    reflexivity.\nQed.\n\n(* Exercise *)\nTheorem count_member_nonzero : forall s : bag,\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  simpl. 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\n(* Exercise *)\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'].\n  - simpl. reflexivity.\n  - destruct n.\n    + simpl. rewrite leb_n_Sn. reflexivity.\n    + simpl. rewrite IHs'. reflexivity. Qed.\n\n(* Exercise *)\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(* Definition *)\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' n'\n               end\n  end.\n\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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(* Exercise *)\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: _ => Some a\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(* Exercise *)\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default.\n  destruct l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\n\n(* Definition *)\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 => eqb n1 n2\n  end.\n\n(* Exercise *)\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  intro x.\n  destruct x.\n    simpl.\n    rewrite -> nat_equals_self.\n    reflexivity.\nQed.\n\n(* Definition *)\nModule PartialMap.\n\nExport NatList.\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\n(* Exercise *)\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(* Exercise *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o.\n  intro H.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n\n(* Exercise *)\n\n(* It has 2^n elements. *)\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8902942268497306, "lm_q1q2_score": 0.797927423307006}}
{"text": "Add LoadPath \"/Users/danielle/projects/software-foundations/chapter03\".\nRequire Import case.\n\nRequire Import Utf8.\n\nTheorem plus_0_r: ∀ n: nat, n + 0 = n. \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.\n    Qed.\n\n(* Exercises *)\n\nTheorem mult_0_r: ∀ n: nat,\n  n * 0 = 0.\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.\n  Qed.\n\nTheorem plus_n_Sm: ∀ 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    reflexivity.\n  Case \"n = S n’\".\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nTheorem plus_comm: ∀ n m: nat,\n  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.\n    rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\n  Qed.\n\nTheorem plus_assoc: ∀ 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    reflexivity.\n  Case \"n = S n’\".\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n", "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/exercise02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7978962907267525}}
{"text": "(* Matrix manipulation \n\n   File: 'matrix.v'\n\n   Description: The main purpose of this file\n   is to make available the necessary operations\n   on matrices to test identities of the fibonacci\n   sequence *)\n   \nRequire Import Arith.\n\nRequire Import Lists.List.\n\n(* Coq library from the fibonacci.v file\n\n   Compile by entering the following in command line\n   > coqc fibonacci.v *)\n\nRequire Import fibonacci.\n\n\n(* A 2x2 matrix is a simple constructor\n   with 4 nats.\n\n   |a00 a01|\n   |a10 a11|\n\n*)\n\nInductive matrix22 :=\n| Matrix22 : nat -> nat -> nat -> nat -> matrix22.\n\n\nDefinition matrix_1 := Matrix22 1 2 3 4.\nDefinition matrix_2 := Matrix22 5 6 7 8.\nDefinition matrix_3 := Matrix22 9 8 7 6.\n\n\n(* The identity matrix\n\n   |1 0|\n   |0 1|\n\n*)\n\nDefinition matrix_identity := Matrix22 1 0 0 1.\n\nLemma unfold_matrix_identity :\n  matrix_identity = Matrix22 1 0 0 1.\nProof.\n  unfold matrix_identity.\n  reflexivity.\nQed.\n\n\n(* Addition of two matrices *)\n\nDefinition matrix_plus (m m' : matrix22) : matrix22 :=\n  match (m, m') with\n    | (Matrix22 a00 a01 a10 a11, Matrix22 b00 b01 b10 b11)\n      => Matrix22 (a00 + b00) (a01 + b01) (a10 + b10) (a11 + b11)\n  end. \n  \n\nLemma unfold_matrix_plus :  \n  forall m m' : matrix22,\n    matrix_plus m m' = \n    match (m, m') with\n      | (Matrix22 a00 a01 a10 a11, Matrix22 b00 b01 b10 b11)\n        => Matrix22 (a00 + b00) (a01 + b01) (a10 + b10) (a11 + b11)\n    end. \nProof.\n  unfold matrix_plus.\n  reflexivity.\nQed.\n\n\n(* Addition test\n\n   |1 2|  +  |5 6|  =  | 6  8|\n   |3 4|  +  |7 8|  =  |10 12|\n\n*)\n\nCompute matrix_plus matrix_1 matrix_2.\n\n(* Matrix22 6 8 10 12\n    : matrix22      *)\n\n\n(* Scalar product of natural number and matrix *)\n\nDefinition matrix_scalar (c : nat) (m : matrix22) :=\n  match m with\n    | Matrix22 a00 a01 a10 a11\n      => Matrix22 (a00 * c) (a01 * c) (a10 * c) (a11 * c)\n  end. \n\nLemma unfold_matrix_scalar :  \n  forall (m : matrix22) (c : nat),\n    matrix_scalar c m = \n    match m with\n      | Matrix22 a00 a01 a10 a11\n        => Matrix22 (a00 * c) (a01 * c) (a10 * c) (a11 * c)\n    end. \nProof.\n  unfold matrix_scalar.\n  reflexivity.\nQed.\n\nCompute matrix_scalar 10 matrix_1.\n\n(* Matrix22 10 20 30 40\n    : matrix22        *)\n\n\n(* Ordinary matrix multiplication *)\n\nDefinition matrix_multiplication (m m' : matrix22) :=\n  match (m, m') with\n    | (Matrix22 a00 a01 a10 a11, Matrix22 b00 b01 b10 b11)\n      => Matrix22 (a00 * b00 + a01 * b10) (a00 * b01 + a01 * b11) (a10 * b00 + a11 * b10) (a10 * b01 + a11 * b11)\n  end. \n\nLemma unfold_matrix_multiplication :\n  forall m m' : matrix22,\n    matrix_multiplication m m' = match (m, m') with\n    | (Matrix22 a00 a01 a10 a11, Matrix22 b00 b01 b10 b11)\n      => Matrix22 (a00 * b00 + a01 * b10) (a00 * b01 + a01 * b11) (a10 * b00 + a11 * b10) (a10 * b01 + a11 * b11)\n  end. \nProof.\n  unfold matrix_multiplication.\n  reflexivity.\nQed.\n\n\n(* Multiplication test\n\n   |1 2|  *  |5 6|  =  | 19  22|\n   |3 4|  *  |7 8|  =  | 43  50|\n\n*)\n\nCompute matrix_multiplication matrix_1 matrix_2.\n\n(* Matrix22 19 22 43 50\n    : matrix22    *)\n\n\n(* Identity matrix is neutral *)\n\nLemma matrix_identity_is_neutral_on_the_left :\n  forall m : matrix22,\n    matrix_multiplication matrix_identity m = m.\nProof.\n  intro m.\n  rewrite unfold_matrix_identity.\n  rewrite unfold_matrix_multiplication.\n  case m as [ a00 a01 a10 a11 ].\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\n\nLemma matrix_identity_is_neutral_on_the_right :\n  forall m : matrix22,\n    matrix_multiplication m matrix_identity = m.\nProof.\n  intro m.\n  rewrite unfold_matrix_identity.\n  rewrite unfold_matrix_multiplication.\n  case m as [ m00 m01 m10 m11 ].\n  rewrite 4 mult_1_r.\n  rewrite 4 mult_0_r.\n  rewrite 2 plus_0_r.\n  rewrite 2 plus_0_l.\n  reflexivity.\nQed.\n\n\n(* Matrix multiplication is associative *)\n\nLemma matrix_multiplication_is_associative :\n  forall a b c : matrix22,\n    matrix_multiplication (matrix_multiplication a b) c = matrix_multiplication a (matrix_multiplication b c).\nProof.\n  intros a b c.\n  rewrite 4 unfold_matrix_multiplication.\n  destruct a as [a00 a01 a10 a11].\n  destruct b as [b00 b01 b10 b11].\n  destruct c as [c00 c01 c10 c11].\n  rewrite 8 mult_plus_distr_r.\n  rewrite 8 mult_plus_distr_l.\n  rewrite 16 mult_assoc.\n  rewrite 8 plus_assoc.\n  rewrite <- (plus_assoc (a00 * b00 * c00)).\n  rewrite (plus_comm (a01 * b10 * c00)).\n  rewrite <- (plus_assoc (a00 * b00 * c01)).\n  rewrite (plus_comm (a01 * b10 * c01)).\n  rewrite <- (plus_assoc (a10 * b00 * c00)).\n  rewrite (plus_comm (a11 * b10 * c00)).\n  rewrite <- (plus_assoc (a10 * b00 * c01)).\n  rewrite (plus_comm (a11 * b10 * c01)).\n  rewrite 4 plus_assoc.\n  reflexivity.\nQed.\n\n\n(* Multiplication is associative test\n  \n   (A * B) * C = A * (B * C)\n*)\n\nCompute (matrix_multiplication \n        (matrix_multiplication matrix_1 matrix_2) \n         matrix_3) \n        = \n        (matrix_multiplication \n         matrix_1\n        (matrix_multiplication  matrix_2 matrix_3)).\n\n(* Matrix22 325 284 737 644 = Matrix22 325 284 737 644\n     : Prop  *)\n\n\n(* Matrix exponentiation function\n   \n   Base case is defined by the identity\n   matrix thus A^0=I *)\n\nFixpoint matrix_exponentiation (m : matrix22) (n : nat) : matrix22 :=\n  match n with\n    | 0 => matrix_identity\n    | S n' => matrix_multiplication (matrix_exponentiation m n') m\n  end.\n\n\nLemma unfold_matrix_exponentiation_bc :\n  forall (m : matrix22),\n    matrix_exponentiation m 0 = matrix_identity.\nProof.\n  unfold matrix_exponentiation.\n  reflexivity.\nQed.\n\nLemma unfold_matrix_exponentiation_ic :\n  forall (m : matrix22) (n : nat),\n    matrix_exponentiation m (S n) = matrix_multiplication (matrix_exponentiation m n) m.\nProof.\n  unfold matrix_exponentiation.\n  reflexivity.\nQed.\n\n\n(* Properties of matrix exponentiation \n\n   This identity is proposition 14\n   in dProgSprog notes. *)\n\nTheorem exponentiation_of_a_matrix :\n  forall (n : nat),\n    matrix_exponentiation (Matrix22 1 1 0 1) n =\n    Matrix22 1 n 0 1.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite unfold_matrix_identity.\n  reflexivity.\n  \n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_multiplication.\n  rewrite IHn'.\n  rewrite 3 mult_1_r.\n  rewrite 2 mult_0_r.\n  rewrite 2 plus_0_r.\n  rewrite plus_Sn_m.\n  rewrite 2 plus_0_l.\n  reflexivity.\nQed.\n\n\nLemma about_matrix_exponentiation_left :\n  forall (a : matrix22) (n : nat),\n    matrix_multiplication a (matrix_exponentiation a n) =\n    matrix_exponentiation a (S n).\nProof.\n  intros a n.\n  induction n as [ | n'].\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite matrix_identity_is_neutral_on_the_left.\n  rewrite matrix_identity_is_neutral_on_the_right.\n  reflexivity.\n\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite <- IHn'.\n  rewrite matrix_multiplication_is_associative.\n  reflexivity.\nQed.\n\nLemma about_matrix_exponentiation_right :\n  forall (a : matrix22) (n : nat),\n    matrix_multiplication (matrix_exponentiation a n) a =\n    matrix_exponentiation a (S n).\nProof.\n  intros a n.\n  induction n as [ | n'].\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite matrix_identity_is_neutral_on_the_left.\n  reflexivity.\n\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite <- IHn'.\n  reflexivity.\nQed.\n\n\n(* Proposition 29 in dProgSprog notes *)\n\nProposition about_matrix_exponentiation :\n  forall (m : matrix22) (n : nat),\n    matrix_multiplication (matrix_exponentiation m n) m =\n    matrix_multiplication m (matrix_exponentiation m n).\nProof.\n  intros m n.\n  rewrite about_matrix_exponentiation_left.\n  apply about_matrix_exponentiation_right.\nQed.  \n\n\n(* Transposition of matrix *)\n\nDefinition matrix_transposition (m : matrix22) : matrix22 :=\n  match m with\n    | Matrix22 a00 a01 a10 a11 \n      => Matrix22 a00 a10 a01 a11\n  end.\n\nLemma unfold_matrix_transposition :\n  forall m : matrix22,\n    matrix_transposition m = \n      match m with\n        | Matrix22 a00 a01 a10 a11 \n          => Matrix22 a00 a10 a01 a11\n      end.\nProof.\n  unfold matrix_transposition.\n  reflexivity.\nQed.\n\n\n(* Transposition of a matrix test\n  \n       T\n  |1 2|  =  |1  3|\n  |3 4|  =  |2  4|   *)\n\nCompute matrix_transposition matrix_1.\n \n(* Matrix22 1 3 2 4\n    : matrix22       *)\n\n\n(* Properties about matrix transposition *)\n\nLemma matrix_identity_is_symmetric :\n  matrix_transposition matrix_identity = \n  matrix_identity.\nProof.\n  rewrite unfold_matrix_transposition.\n  rewrite unfold_matrix_identity.\n  reflexivity.\nQed.\n\nLemma matrix_transposition_is_involutive :\n  forall m : matrix22,\n    matrix_transposition (matrix_transposition m) = m.\nProof.\n  intro a.\n  rewrite 2 unfold_matrix_transposition.\n  destruct a as [a00 a01 a10 a11].\n  reflexivity.\nQed.\n\n\n(* Transposition of a matrix product \n\n   When you transpose a product you\n   get the product of the transposed\n   matrices in reverse order *)\n\nProposition transposition_of_a_product :\n  forall a b : matrix22,\n    matrix_transposition (matrix_multiplication a b) =\n    matrix_multiplication (matrix_transposition b) (matrix_transposition a). \nProof.\n  intros a b.\n  destruct a as [a00 a01 a10 a11].\n  destruct b as [b00 b01 b10 b11].\n  rewrite 3 unfold_matrix_transposition.\n  rewrite 2 unfold_matrix_multiplication.\n  rewrite (mult_comm a00).\n  rewrite (mult_comm a01).\n  rewrite (mult_comm a10).\n  rewrite (mult_comm a11).\n  rewrite (mult_comm b01).\n  rewrite (mult_comm b11).\n  rewrite (mult_comm b01).\n  rewrite (mult_comm b11).\n  reflexivity.\nQed.\n\n\n(* Transposition and exponentiation commutes\n\n   Proposition 38 in dProgSprog notes *)\n\nTheorem matrix_transposition_and_exponentiation_commutes :\n  forall (m : matrix22) (n : nat),\n    matrix_transposition (matrix_exponentiation m n) =\n    matrix_exponentiation (matrix_transposition m) n.\nProof.\n  intros m n.\n  induction n as [ | n' IHn'].\n  rewrite 2 unfold_matrix_exponentiation_bc.\n  rewrite matrix_identity_is_symmetric.\n  reflexivity.\n  \n  destruct m as [m00 m01 m10 m11].\n  rewrite (unfold_matrix_exponentiation_ic (matrix_transposition (Matrix22 m00 m01 m10 m11))).\n  rewrite <- IHn'.\n  rewrite <- transposition_of_a_product.\n  rewrite about_matrix_exponentiation_left.\n  reflexivity.\nQed.\n\n\n(* Determinant of 2x2 matrix *)\n\nDefinition matrix_determinant (m : matrix22) : nat :=\n  match m with \n    | Matrix22 a00 a01 a10 a11 \n      => a00 * a11 - a01 * a10\n  end.\n\nLemma unfold_matrix_determinant :\n  forall m : matrix22,\n    matrix_determinant m =   \n    match m with \n      | Matrix22 a00 a01 a10 a11 \n        => a00 * a11 - a01 * a10\n    end.\nProof.\n  unfold matrix_determinant.\n  reflexivity.\nQed.\n\nCompute matrix_determinant (Matrix22 10 4 9 9).\n(*  54\n    : nat *)\n\n\n(* Defining the fibonacci matrix to raise to a power *)\n\nDefinition matrix_fib := Matrix22 1 1 1 0.\n\nLemma unfold_matrix_fib :\n  matrix_fib = Matrix22 1 1 1 0.\nProof.\n  unfold matrix_fib.\n  reflexivity.\nQed.\n\n\n(* Matrix exponentiation and fibonacci \n\n   Showing the beautiful relation between\n   matrix exponentiation of the matrix_fib\n   and the fibonacci sequence *)\n\nTheorem matrix_exponentiation_and_fibonacci :\n  forall (fib : nat -> nat),\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      (matrix_exponentiation matrix_fib (S n)) = Matrix22 (fib (S (S n))) (fib (S n)) (fib (S n)) (fib n).\nProof.\n  intro fib.\n  intro H_fib.\n  destruct H_fib as [H_fib_bc0 [H_fib_bc1 H_fib_ic]].\n  intro n.\n  induction n as [ | n' IHn'].\n  rewrite H_fib_ic.\n  rewrite H_fib_bc0.\n  rewrite H_fib_bc1.\n  rewrite plus_0_r.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite matrix_identity_is_neutral_on_the_left.\n  reflexivity.\n  \n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_multiplication.\n  rewrite IHn'.\n  rewrite unfold_matrix_fib.\n  rewrite 3 mult_1_r.\n  rewrite 2 mult_0_r.\n  rewrite 2 plus_0_r.\n  rewrite <- 2 H_fib_ic.\n  reflexivity.\nQed.\n\n\n(* Matrix implementation of fibonacci \n\n   New implementation of the Fibonacci function \n   maybe also be a bit more efficient *)\n\nFixpoint fib_v3 (n : nat) : nat :=\n  match (matrix_exponentiation (Matrix22 1 1 1 0) n) with\n    | Matrix22 _ a01 _ _ => a01\n  end.\n\nCompute map fib_v3 (0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil).\n(*                  0 :: 1 :: 1 :: 2 :: 3 :: 5 :: 8 :: 13 :: nil\n                    : list nat *)\n\n\nLemma unfold_fib_v3_bc :\n  fib_v3 0 = \n  match (matrix_exponentiation matrix_fib 0) with\n    | Matrix22 _ a01 _ _ => a01\n  end.\nProof.\n  unfold fib_v3.\n  reflexivity.\nQed.\n\nLemma fib_v3_of_0 :\n  fib_v3 0 = 0.\nProof.\n  rewrite unfold_fib_v3_bc.\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite unfold_matrix_identity.\n  reflexivity.\nQed.\n\nLemma unfold_fib_v3_ic :\n  forall n : nat,\n    fib_v3 (S n) =\n    match (matrix_exponentiation matrix_fib (S n)) with\n      | Matrix22 _ a01 _ _ => a01\n    end.\nProof.\n  unfold fib_v3.\n  reflexivity.\nQed.\n\n\n(* Fibonacci function in direct style\n\n   Implementation from \n   'fibonacci-with-some-solutions.v' *)\n\nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' => match n' with\n                | 0 => 1\n                | S n'' => fib_v1 n' + fib_v1 n''\n              end\n  end.\n\nLemma unfold_fib_v1_base_case_0 :\n  fib_v1 0 = 0.\nProof.\n  unfold fib_v1.\n  reflexivity.\nQed.\n\nLemma unfold_fib_v1_base_case_1 :\n  fib_v1 1 = 1.\nProof.\n  unfold fib_v1.\n  reflexivity.\nQed.\n\nLemma unfold_fib_v1_induction_case :\n  forall n'' : nat,\n    fib_v1 (S (S n'')) = fib_v1 (S n'') + fib_v1 n''.\nProof.\n  intro n''.\n  unfold fib_v1; fold fib_v1.\n  reflexivity.\nQed.\n\n\nTheorem fib_v1_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v1.\nProof.\n  unfold specification_of_fibonacci.\n  split.\n  apply unfold_fib_v1_base_case_0.\n  split.\n  apply unfold_fib_v1_base_case_1.\n  apply unfold_fib_v1_induction_case.\nQed.\n\n\n(* fib_v1 and fib_v3 are functionally equal\n\n   For any natural number n the output\n   of fib_v1 and fib_v3 are the same *)\n\nProposition fib_v1_and_fib_v3_are_functionally_equal :\n  forall n : nat,\n    fib_v3 n = fib_v1 n.\nProof.\n  intro n.\n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n  rewrite fib_v3_of_0.\n  rewrite unfold_fib_v1_base_case_0.\n  reflexivity.\n  \n  rewrite unfold_fib_v3_ic.\n  rewrite unfold_fib_v1_base_case_1.\n  rewrite unfold_matrix_exponentiation_ic.\n  rewrite unfold_matrix_exponentiation_bc.\n  rewrite matrix_identity_is_neutral_on_the_left.\n  rewrite unfold_matrix_fib.\n  reflexivity.\n\n  rewrite unfold_fib_v3_ic.\n  rewrite (matrix_exponentiation_and_fibonacci fib_v1 fib_v1_fits_the_specification_of_fibonacci).\n  reflexivity.\nQed.\n\n\n(* fib_v3 satisfies the specification of Fibonacci \n\n   Since fib_v1 and fib_v3 are functionally equal\n   it is straight forward to show that fib_v3 satisfies the \n   specification since it is already shown that\n   fib_v1 satisfies the specification. *)\n\nTheorem fib_v3_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v3.\nProof.\n  unfold specification_of_fibonacci.\n  rewrite 2 fib_v1_and_fib_v3_are_functionally_equal.\n  destruct fib_v1_fits_the_specification_of_fibonacci \n    as [fib_v1_bc0 [fib_v1_bc1 fib_v1_ic]].\n  split.\n  apply fib_v1_bc0.\n  split.\n  apply fib_v1_bc1.\n  intro n.\n  rewrite 3 fib_v1_and_fib_v3_are_functionally_equal.\n  apply fib_v1_ic.\nQed.\n  \n\n(* Cassini's identity with matrices \n\n   This implementation uses a fibonacci\n   function to create the fibonacci matrix.\n   And afterwards the definition of the\n   determinant ensures an expression\n   where Cassini_s_identity_for_even_numbers\n   can be used. *)\n\n\nTheorem Cassini_and_matrices_even :\n  forall (fib : nat -> nat) (n : nat),\n    specification_of_fibonacci fib ->\n    matrix_determinant (matrix_exponentiation matrix_fib (2 * (S n))) = 1.\nProof.\n  intros fib n.\n  intro H_fib.\n  assert (H_tmp := H_fib).\n  destruct H_fib as [H_fib_bc0 [H_fib_bc1 H_fib_ic]].\n\n  rewrite unfold_matrix_fib.\n  rewrite mult_succ_l.\n  rewrite mult_1_l.\n  rewrite plus_Sn_m.\n  rewrite <- plus_n_Sm.\n  rewrite (matrix_exponentiation_and_fibonacci fib H_tmp).\n  rewrite <- plus_Sn_m.\n  rewrite plus_n_Sm.\n  rewrite (plus_Sn_m n n).\n  rewrite 2 plus_2_mult.\n  rewrite unfold_matrix_determinant.\n  rewrite <- (Cassini_s_identity_for_even_numbers fib H_tmp n).\n  rewrite unfold_square.\n  rewrite <- minus_Sn_m.\n  rewrite minus_diag.\n  reflexivity.\n  \n  reflexivity.\nQed.\n\n\nTheorem Cassini_and_matrices_odd :\n  forall (fib : nat -> nat) (n : nat),\n    specification_of_fibonacci fib ->\n   S (S (matrix_determinant (matrix_exponentiation matrix_fib (S (2 * n))))) = 1.\nProof.\n  intros fib n.\n  intro H_fib.\n  assert (H_tmp := H_fib).\n  destruct H_fib as [H_fib_bc0 [H_fib_bc1 H_fib_ic]].\n\n  rewrite unfold_matrix_fib.\n  rewrite mult_succ_l.\n  rewrite mult_1_l.\n  rewrite (matrix_exponentiation_and_fibonacci fib H_tmp).\n  rewrite <- plus_Sn_m.\n  rewrite plus_n_Sm.\n  rewrite 2 plus_2_mult.\n  rewrite plus_Sn_m.\n  rewrite plus_2_mult.\n  rewrite unfold_matrix_determinant.\n  rewrite <- fibonacci.unfold_square.\n  rewrite (Cassini_s_identity_for_odd_numbers fib H_tmp n).\n  rewrite minus_Sn_m.\n  rewrite minus_diag.\n  reflexivity.\n  (* Will not appear in the report *)\n  Abort.\n\n(* End of 'matrix.v' *)\n\n", "meta": {"author": "akonring", "repo": "coq-fibonacci", "sha": "9b13fcfca871ee0465544b1e38045bd174502662", "save_path": "github-repos/coq/akonring-coq-fibonacci", "path": "github-repos/coq/akonring-coq-fibonacci/coq-fibonacci-9b13fcfca871ee0465544b1e38045bd174502662/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.797895099389363}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars (nostutter)  *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all.\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| ns_nil : nostutter []\n| ns_single : forall n, nostutter [n]\n| ns_cons : forall x1 x2 l, (x1<>x2) -> nostutter (x2::l) -> nostutter (x1::x2::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].\nProof. apply ns_cons. \n  intro c. inversion c. apply ns_cons. intro c. inversion c. apply ns_cons. intro c. inversion c. apply ns_cons. intro c. inversion c. apply ns_cons. intro c. inversion c. apply ns_single. Qed.\n\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\nProof. apply ns_nil. Qed.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\nProof. apply ns_single. Qed.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\nProof. \n  unfold not. intro c. inversion c. inversion H3. unfold not in H6. apply H6. reflexivity. Qed.  \n\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", "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/P29.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8887588001219789, "lm_q1q2_score": 0.7978346004186032}}
{"text": "Require Import ZArith.\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nOpen Scope Z_scope.\n\nDefinition manhattan_dist (p1 p2 : plane) : Z :=\n (Zabs (abscissa p1 - abscissa p2)) +\n (Zabs (ordinate p1 - ordinate p2)).\n \n\nEval compute in (manhattan_dist (point 2 5) (point 7 (-9))).\n \n\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/structinduct/SRC/manhattan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9597620562254525, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7976995546085573}}
{"text": "From LF Require Export Basics.\n\nTheorem add_0_r_firsttry: forall n:nat,\n  n + 0 = n.\n\nProof.\n  intros n.\n  simpl.\nAbort.\n\nTheorem add_0_r: forall n: nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem minus_n_n : forall n, minus n n = 0.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem mul_0_r : forall n: nat,\n  n * 0 = 0.\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_n_Sm: forall n m : nat,\n  S(n+m) = n + (S m).\nProof.\n  induction n as [|n' IHn'].\n  - intros m. simpl. reflexivity.\n  - intros m. simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem add_comm: forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [|n' IHn'].\n  - intros m. simpl. rewrite -> add_0_r. reflexivity.\n  - intros m. simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity. Qed.\n\nTheorem add_assoc: forall n m p:nat,\n  n+(m+p) = (n+m)+p.\nProof.\n  induction n as [|n' IHn'].\n  - intros. simpl. reflexivity.\n  - intros. simpl. rewrite -> IHn'. reflexivity. Qed.\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  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity. Qed.\n\nTheorem eqb_refl: forall n: nat,\n  (n =? n) = true.\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. apply IHn'. Qed.\n\nTheorem even_S : forall n : nat,\n  even (S n) = negb (even n).\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - rewrite IHn'. rewrite negb_involutive. simpl. reflexivity. Qed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (n + 0 + 0) * m = n * m.\nProof.\n  intros n m.\n  assert (H: n + 0 + 0 = n).\n    { rewrite add_comm. simpl. rewrite add_comm. reflexivity. }\n  rewrite -> H.\n  reflexivity. Qed.\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 add_comm. reflexivity. }\n  rewrite H. reflexivity. Qed.\n\nTheorem add_shuffle3: forall n m p:nat,\n  n+(m+p) = m+(n+p).\nProof.\n  intros.\n  rewrite add_assoc.\n  rewrite add_assoc.\n  assert (H:n+m=m+n). apply add_comm.\n  rewrite H. reflexivity. Qed.\n\nTheorem mul_comm: forall m n : nat,\n  m * n = n * m.\nProof.\n  induction m.\n  - intros. simpl. rewrite mul_0_r. reflexivity.\n  - intros. simpl. rewrite IHm. assert (H: n + n * m = n * S m).\n    { induction n.\n    - simpl. reflexivity.\n    - simpl. rewrite <- IHn. rewrite add_shuffle3. reflexivity. }\n    apply H. Qed.\n\nCheck leb.\n\nTheorem plus_leb_compat_l: forall n m p: nat,\n  n <=? m = true -> (p + n) <=? (p +  m) = true.\nProof.\n  intros n. intros m. induction p.\n  - simpl. intros. apply H.\n  - intros. simpl. rewrite IHp. reflexivity. apply H. Qed.\n\nTheorem leb_refl: forall n: nat,\n  (n <=? n) = true.\nProof.\n  induction n. simpl. reflexivity. simpl. apply IHn. Qed.\n\nTheorem zero_neqb_S: forall n: nat,\n  0 =? (S n) = false.\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nTheorem andb_false_r: forall b: bool,\n  andb b false = false.\nProof.\n  intros. destruct b. simpl. reflexivity. simpl. reflexivity.\nQed.\n\nTheorem S_neqb_0: forall n:nat,\n  (S n) =? 0 = false.\nProof.\n  reflexivity.\nQed.\n\nTheorem mult_1_l: forall n:nat, 1 * n = n.\nProof.\n  intros n.\n  simpl.\n  rewrite <- plus_n_O.\n  reflexivity. Qed.\n\n  Theorem all3_spec : forall b c : bool,\n  orb (andb b c) (orb (negb b) (negb c)) = true.\nProof.\n  destruct b.\n  - simpl. 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. induction n as [| n IHn].\n  - reflexivity.\n  - simpl. rewrite -> IHn. rewrite <- add_assoc. reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros.\n  induction n as [| n IHn].\n  - reflexivity.\n  - simpl. rewrite -> IHn. rewrite <- mult_plus_distr_r. reflexivity.\nQed.\n\nTheorem add_shuffle3': forall n m p:nat,\n  n+(m+p) = m+(n+p).\nProof.\n  intros.\n  rewrite add_assoc.\n  rewrite add_assoc.\n  replace (n + m) with (m + n). reflexivity. apply add_comm. Qed.\n\nTheorem bin_to_nat_pres_incr : forall n:bin,\n  bin_to_nat (incr n) = S (bin_to_nat n).\nProof.\n  assert (H: forall m: nat, m * 2 = m + m). {\n    intros.\n    rewrite -> mul_comm. simpl. rewrite <- plus_n_O. reflexivity.\n  }\n  induction n as [|n IHn|n IHn].\n  - reflexivity.\n  - simpl.\n    rewrite -> H. rewrite -> plus_n_Sm. replace (S (bin_to_nat n)) with (bin_to_nat n + 1).\n    + rewrite -> add_assoc. reflexivity.\n    + rewrite -> add_comm. rewrite -> plus_1_l. reflexivity.\n  - simpl. rewrite -> H. rewrite -> H. rewrite -> IHn. rewrite -> plus_n_Sm.\n    rewrite <- plus_1_l. rewrite -> add_assoc.\n    assert (H2: forall k:nat, 1 + k + 1 + k = k + k + 2). {\n      intros. replace (k + k + 2) with (k + 2 + k).\n      + replace (k + 2) with (1 + k + 1).\n        * reflexivity.\n        * rewrite <- add_assoc. rewrite add_comm. replace (k+1+1) with\n        (k+(1+1)). reflexivity. rewrite add_assoc. reflexivity.\n      + rewrite <- add_assoc. replace (2+k) with (k+2). rewrite add_assoc.\n      reflexivity. apply add_comm.\n    }\n    rewrite -> H2. 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')) end.\n\nTheorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite bin_to_nat_pres_incr. rewrite IHn'. reflexivity. Qed.\n\n(* TODO: solve Bin to Nat and Back to Bin. *)", "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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7975625348430916}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\n\nInductive tree : Set :=\n| leaf : tree\n| node : tree -> nat -> tree -> tree.\n\nFixpoint all_leq(n: nat)(t: tree): Prop :=\n  match t with\n    | leaf => True\n    | node l val r => (val <= n) /\\ (all_leq n l) /\\ (all_leq n r)\n  end.\n\nFixpoint all_geq(n: nat)(t: tree): Prop := \n  match t with\n    | leaf => True\n    | node l val r => (val > n) /\\ (all_geq n l) /\\ (all_geq n r)\n  end. \n\nFixpoint bst (T: tree): Prop :=\n  match T with\n  | leaf => True\n  | node l v r => (all_leq v l) /\\ (all_geq v r) /\\ bst l /\\ bst r\nend.\n\nFixpoint insert(n: nat)(T: tree): tree :=\n  match T with\n  | leaf => node leaf n leaf\n  | node l v r => if Nat.leb n v then (insert n l) else (insert n r)\n  end.\n\n(*Print Nat.*)\n\nLemma insert_correctness: forall t: tree, forall n: nat, bst t -> bst (insert n t).\nProof.\nintros.\ninduction t.\n* simpl.\n  auto.\n* simpl insert.\n  destruct (n <=? n0).\n  apply IHt1.\n  destruct H as [H1 [H2 [H3 H4]]].\n  auto.\n  apply IHt2.\n  destruct H as [H1 [H2 [H3 H4]]].\n  auto.\nQed.\n\nFixpoint occurs(n: nat)(t: tree): Prop :=\n  match t with\n    | leaf => False\n    | node l v r => v = n \\/ occurs n l \\/ occurs n r\n  end.\n\nFixpoint to_list(T: tree): (list nat) :=\n  match T with\n    | leaf => nil\n    | node l v r => (to_list l) ++  v::(to_list r)\n  end.\n\nLemma list_tree_equality: forall t1 t2: tree, forall n: nat, \n  to_list (node t1 n t2) = (to_list t1) ++ n::(to_list t2).\nProof.\nintros.\ninduction t1.\n  * induction t2.\n    simpl; reflexivity.\n    simpl. reflexivity.\n  * induction t2.\n    simpl. reflexivity.\n    simpl; reflexivity.\nDefined.\n\n\n\nLemma to_list_retains_elements: forall t: tree, forall x: nat,\n  occurs x t -> In x (to_list t).\nProof.\nintros.\ninduction t.\n- simpl. simpl in H. assumption.\n- simpl in H.\n  destruct H.\n  * rewrite H.\n    simpl.\n    apply in_elt.\n  * destruct H.\n    + simpl.\n      apply in_or_app.\n      left; apply IHt1; assumption.\n    + simpl.\n      apply in_or_app.\n      right.\n      apply in_cons.\n      apply IHt2; assumption.\nDefined.\n\n\nFixpoint insert_sorted(l: (list nat))(ele: nat): (list nat) :=\n  match l with\n    | nil => [ele]\n    | cons x xs => if x <? ele then [x] ++ (insert_sorted xs ele) \n      else ele::x::nil ++ xs\n  end.\n\nLemma insert_sorted_retains_elements: forall l :(list nat), forall x n: nat,\n  In x l -> In x (insert_sorted l n).\nProof.\nintros.\ninduction l.\n- simpl; right; contradiction.\n- simpl.\n  destruct (a <? n).\n  * simpl.\n    simpl in H.\n    destruct H as [H1 | H2].\n    left; assumption.\n    right; apply IHl; assumption.\n  * simpl; simpl in H.\n    destruct H as [H1 | H2].\n    right; left; assumption.\n    right; right; assumption.\nDefined.\n\nLemma insert_sorted_inserts_element: forall l: (list nat), forall n: nat,\n  In n (insert_sorted l n).\nProof.\nintros.\ninduction l.\n- simpl. left. reflexivity.\n- simpl.\n  destruct (a <? n).\n  * simpl; right; assumption.\n  * simpl. left. reflexivity.\nDefined.\n  \n  \nFixpoint sort_list(l: (list nat)): (list nat) :=\n  match l with\n    | nil => nil\n    | cons x xs => insert_sorted (sort_list xs) x\n  end.\n\n(*\nCompute(sort_list (5::1::3::2::nil)).\nCompute(sort_list nil).\nCompute(sort_list (22::22::11::11::5::1::2::nil)).\n*)\n\n\nLemma sorted_list_contains_elements: forall l: (list nat), forall n: nat,\n  In n l -> In n (sort_list l).\nProof.\nintros.\ninduction l.\n- simpl; auto.\n- simpl.\n  simpl in H.\n  destruct H.\n  * rewrite H.\n    apply insert_sorted_inserts_element.\n  * apply insert_sorted_retains_elements.\n    apply IHl.\n    assumption.\nDefined.\n\nFixpoint to_tree(l: (list nat)): tree :=\n  match l with\n    | nil => leaf\n    | cons x xs => node leaf x (to_tree xs)\n  end.\n\nDefinition sort(t: tree): tree :=\n  to_tree (sort_list (to_list t)).\n\n(*\nCompute(sort (node (node leaf 11 leaf) 44 (node leaf 1 leaf))).\nCompute(sort (node leaf 1 (node leaf 2 (node leaf 3 leaf)))).\n*)\n\n\n\n(*sort_list (to_list t1 ++ n :: to_list t2))*)\n\nLemma occurs_bst_forward: forall t: tree, forall x: nat,\n  occurs x t -> occurs x (sort t).\nProof.\nintros.\nunfold sort.\n\n\nLemma sort_result_bst: forall t: tree, bst (sort t).\nProof.\nintros.\nunfold sort.\n(* then here *)\n\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/assignment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8705972734445508, "lm_q1q2_score": 0.797562523791255}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\nFixpoint div2 (n:nat) : nat := match n with S (S p) => S (div2 p) | _ => 0 end.\n\n(* as we advised in chapter 9, we use a specific induction principle\n   to reason on the division function. *)\n\nTheorem div2_ind :\n forall P:nat->Prop,\n   P 0 -> P 1 -> (forall n, P n -> P (S (S n))) ->\n   forall n, P n.\nProof.\n intros.\n assert (H' : P n /\\ P (S n)).\n elim n; intuition.\n intuition.\nQed.\n\n(* Once the induction principle breaks down the problem into the\n   various cases, the omega tactic can handle them. *)\n\nTheorem double_div2_le : forall x:nat, div2 x + div2 x <= x.\nProof.\n intros x; elim x using div2_ind; simpl; auto.\n intros; omega.\nQed.\n\n(* Here we don't even need a proof by induction, but the previous\n   theorem must be re-used. *)\nTheorem f_lemma : forall x v, v <= div2 x -> div2 x + v <= x.\nProof.\n intros; generalize (double_div2_le x); omega.\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/gen-rec/SRC/exo_15_13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8670357460591569, "lm_q1q2_score": 0.7973629519465811}}
{"text": "Require Import Omega.\n\nModule Beaf.\n\n  Notation \"a ^ b\" := (Nat.pow a b) (right associativity, at level 30).\n\n  Example power_example1 :\n    2 ^ 2 ^ 3 = 256.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Definition googol := 10 ^ 100.\n  Definition googolplex := 10 ^ googol.\n\n  Fixpoint tetration (a:nat) (b:nat) : nat :=\n    match b with\n    | O => 1\n    | S b' => a ^ (tetration a b')\n    end.\n\n  Notation \"a ^^ b\" := (tetration a b) (right associativity, at level 30).\n\n  Inductive arrowR : nat -> nat -> nat -> nat -> Prop :=\n  | ArrowBaseN : forall a b,\n      arrowR a 1 b (a ^ b)\n  | ArrowBaseRhs : forall a n,\n      arrowR a (S n) 0 1\n  | ArrowInd : forall a b n x y,\n      arrowR a (S n) b y ->\n      arrowR a n y x ->\n      arrowR a (S n) (S b) x.\n\n  Notation \"[ a ^{ n } b == x ]\" := (arrowR a n b x) (at level 100).\n\n  Lemma arrowR_0 : forall a b x,\n      ~ [a ^{0} b == x].\n  Proof.\n    intros a b x E. inversion E.\n  Qed.\n\n  Proposition arrowR_eq_x : forall a n b x x',\n      [a ^{n} b == x] -> [a ^{n} b == x'] -> x = x'.\n  Proof.\n    intros a n b x x' Ex Ex'.\n    generalize dependent x'.\n    induction Ex; intros x' Ex';\n      inversion Ex'; subst; try reflexivity.\n    - (* contradiction *)\n      exfalso. eapply arrowR_0. apply H2.\n    - exfalso. eapply arrowR_0. apply Ex2.\n    - apply IHEx2. replace y with y0. assumption.\n      symmetry. apply IHEx1. assumption.\n  Qed.\n\n  Proposition arrowR_exists_x : forall a n b,\n      exists x, [a ^{S n} b == x].\n  Proof.\n    intros a n.\n    induction n as [| n' IHn']; intros b.\n    - exists (a ^ b). apply ArrowBaseN.\n    - induction b as [| b' IHb'].\n      + (* b = 0 *)\n        exists 1. constructor.\n      + (* b > 0 *)\n        destruct IHb' as [y IHb'].\n        specialize (IHn' y). destruct IHn' as [x IHn'].\n        exists x. apply ArrowInd with y.\n        assumption. assumption.\n  Qed.\n\n  Example tetration_arrowR2_equiv : forall a b,\n      [a ^{2} b == a ^^ b].\n  Proof.\n    intros a b. induction b as [|b' IHb'].\n    - (* b = 0 *)\n      simpl. apply ArrowBaseRhs.\n    - (* b > 0 *)\n      inversion IHb'; subst.\n      + simpl. eapply ArrowInd.\n        apply ArrowBaseRhs. apply ArrowBaseN.\n      + eapply ArrowInd.\n        apply IHb'.\n        apply ArrowBaseN.\n  Qed.\n\nEnd Beaf.\n", "meta": {"author": "1995hnagamin", "repo": "proof", "sha": "10dd0b6a46dd25e890059915a35b6d6156cc658b", "save_path": "github-repos/coq/1995hnagamin-proof", "path": "github-repos/coq/1995hnagamin-proof/proof-10dd0b6a46dd25e890059915a35b6d6156cc658b/2018/beaf/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7971932550296011}}
{"text": "Require Import ssreflect.\n\n(* Type *)\nCheck true.\nCheck 0.\nCheck 5.\n\n(* functions *)\n\nParameter f : nat -> nat.\nCheck f.\nParameter g : nat -> nat -> nat.\nParameter g' : (nat -> nat) -> nat.\nCheck g'.\nCheck g.\n\nCheck (g 2). (* partial application *)\nCheck (g 2 3). \n\nParameter weirdo : nat -> bool -> nat.\nCheck (weirdo 5 false).\n\nCheck (g 2 (f 5)).\n\n(* predefined addition *)\nCheck Nat.add.\nCheck (Nat.add 4 5).\n\n(* defining a function : identity *)\nCheck (fun x : nat =>  x).\n\n\nDefinition d :=\n  fun x : nat =>  x + x.\nCheck d.\n\n(* a function over functions *)\nDefinition iter2 :=\n  fun f : nat->nat =>\n    fun x : nat =>  f (f x).\nCheck iter2.\n\n(* Properties *)\n\nParameter even : nat -> Prop.\nCheck (even 5).\n\nLemma ex0 : (even 4)\\/(even 5).\nAbort.\n\nCheck (2 = 4).\n\nCheck  forall x : nat, x = 2.\nCheck  exists y : nat, y = 2.\nCheck forall x, x = 2.\n\n\n(* quantifiers and proofs over quantifiers *)\nLemma ex1 : (forall x : nat, even x)\n            ->\n              (forall y : nat, even y).\n  move => h.\nmove => z.\napply h.\nQed.\n\nParameter odd : nat -> Prop.\n\n\n\nParameter P Q : nat -> Prop.\n\nLemma ex11 : (forall x, P x) -> P 3.\nProof.\nmove => h.  \napply h.\nQed.\n\n\nLemma ex2 : (forall x, P x) ->\n                   (forall y, P y).\nProof.\n  move => h.\n  move => z.\n  apply h.\nQed.\n\n\nLemma ex3 :\n  (forall x, P x -> Q x) ->\n    Q 4.\nmove => h.\napply h.\nAbort.\n\n\nLemma hh : (forall x, P x) ->\n                   exists x, P x.\nProof.\nmove => h.\nexists 97. (* we can chose any number *)\napply h.\nQed.\n\n\nLemma last : (forall y, P y -> Q y) ->\n             (exists x, P x) ->\n             exists x, Q x.\nProof.\nmove => h1.\nmove => h2. \ncase h2 => [t pt].\nexists t.\napply h1.\napply pt.\nQed. \n\n\n(* Here R is the relation in mathematical meaning *)\nParameter R : nat -> nat -> Prop.\n\nAxiom R_trans : forall x y z, R x y ->\n                              R y z ->\n                              R x z.\n\n\nLemma exR : R 1 2 -> R 2 3 -> R 1 3.\nmove => r12 r23.\napply R_trans with 2.\napply r12.\napply r23.\nQed.\n\n\n\nLemma sym : forall (x: nat) y,\n    x = y ->\n    y = x.\nProof.\nmove => x y xy.\nrewrite xy.\nreflexivity.\nQed.\n\nLemma refl : forall x : nat, x = x.\nmove => x.\nreflexivity.\nQed.\n\n\nLemma trans : forall (x:nat) y z,\n    x = y -> y = z -> x = z.\n  move => x y z xy yz.\n  rewrite xy yz. reflexivity.\n  (*  rewrite -yz; exact xy. *)\nQed.\n\nLemma exx :\n  (forall x, P x -> Q x) ->\n  (forall y, Q y -> y = 5) ->\n  ~P 5 ->\n  forall z,  ~P z.\n  move => h1 h2 h3.\n  move => z.\n  move => pz.\n  apply h3.\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/Tutorial_2/script2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7970919856839864}}
{"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.", "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/reverseDistributive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7970919833867217}}
{"text": "(*\n * その6: https://www.fos.kuis.kyoto-u.ac.jp/~igarashi/class/cal/handout6.pdf\n * 論理演算の練習\n *)\n\nRequire Import Arith List Omega ZArith.\nFrom mathcomp Require Import all_ssreflect.\nImport ListNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*\n論理演算の練習\n*)\n\nTheorem ex_falso : forall P: Prop, False -> P.\nProof.\n  intros P falso.\n  destruct falso.\nQed.\n\nTheorem double_neg : forall (P:Prop), P -> ~ ~P.\nProof.\n  intros P HP.\n  unfold not.\n  intro HnotP.\n  apply (HnotP HP).\nQed.\n\nTheorem iff_sym : forall P Q: Prop, (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [PQ QP].\n  split.\n  - exact.\n  - exact.\nQed.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  split.\n  - (* => *)\n    case n as [|n'].\n    + (* when n = 0 *)\n      by left.\n    + (* when n = S n' *)\n      case m as [|m'].\n      * (* when m = 0 *)\n        by right.\n      * (* when m = S m' *)\n        discriminate.\n  - (* <= *)\n    case.\n    + intro n_is_0.\n      rewrite n_is_0.\n      done.\n    + intro m_is_0.\n      rewrite m_is_0.\n      done.\nQed.\n\nLemma mult_0_3 : forall n m p,\n  n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite !mult_0.\n  by rewrite or_assoc.\nQed.\n\n(*\nexists の練習\n*)\n\nTheorem exists_ex2 : forall n,\n  (exists m, n = 4 + m) -> (exists k, n = 2 + k).\nProof.\n  intros n.\n  intros H.\n  destruct H.\n  exists (2 + x).\n  rewrite H.\n  done.\nQed.\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_ex : (fun x => x + 1) = (fun x => 1 + x).\nProof.\n  apply functional_extensionality.\n  intro x.\n  rewrite [x+1] addnC.\n  done.\nQed.\n\n(*\n証明に用いた公理の確認\n*)\nPrint Assumptions function_equality_ex.\n\n(*\n古典論理の話\n*)\n\n(* 排中律 *)\nDefinition ext_mid := forall P, P \\/ ~P.\n\n(*\n を仮定すると以下が成り立つ\n *)\n\nTheorem Peirce_law : forall P Q : Prop,\n  ext_mid -> ((P -> Q) -> P) -> P.\nProof.\n  unfold ext_mid.\n  intros P Q ExtMidLaw.\n  move: (ExtMidLaw P).\n  case.\n  - (* when P *)\n    done.\n  - (* when not P *)\n    move => HnotP H.\n    apply H.\n    move/HnotP.\n    done.\nQed.\n\nTheorem ClassicTheorem : ext_mid -> forall (P Q : Prop), (P -> Q) -> ~P \\/ Q.\nProof.\n  unfold ext_mid.\n  intros ExtMidLaw P Q HPQ.\n  move: (ExtMidLaw P).\n  case.\n  - (* when P *)\n    move/HPQ.\n    by right.\n  - (* when not P *)\n    by left.\nQed.\n", "meta": {"author": "cympfh", "repo": "coq-etude", "sha": "83deac7d6931ad48540b999e3c1649cf93b0a41e", "save_path": "github-repos/coq/cympfh-coq-etude", "path": "github-repos/coq/cympfh-coq-etude/coq-etude-83deac7d6931ad48540b999e3c1649cf93b0a41e/igarashi/class06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8723473879530492, "lm_q1q2_score": 0.7970433347855067}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Examples for other tactics provided by TLC                              *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics.\n\n\n(* ********************************************************************** *)\n(** * How to do recursion/induction on terms with list of subterms *)\n\nModule SubtermIndDemos.\n\nRequire Import LibLogic LibList.\n\n(** Definition of trees with list of subtrees *)\n\nInductive tree : Type :=\n  | leaf : nat -> tree\n  | node : list tree -> tree.\n\n(** Example of a primitive-recursive function on trees\n    using an inlined fixed point -- not recommended *)\n\nFixpoint tree_incr' (t:tree) :=\n  match t with\n  | leaf n => leaf (S n)\n  | node ts =>\n     node ((fix aux ts := match ts with\n            | nil => nil\n            | t::ts' => tree_incr' t :: aux ts'\n            end) ts)\n  end.\n\n(** Same example but using the map function on lists\n    -- recommended\n    -- this works only because List.map has exactly\n    the same form as the local [fix] used above.\n    -- if you wanted to use LibList.map instead of\n    List.map, it would not work; you would have to\n    either use the optimal fixed point (see LibFixDemos)\n    or you would have to exploit [List.map = LibList.map] *)\n\nFixpoint tree_incr (t:tree) :=\n  match t with\n  | leaf n => leaf (S n)\n  | node ts => node (List.map tree_incr ts)\n  end.\n\n(** Another example -- recommended *)\n\nFixpoint tree_map (f:nat->nat) (t:tree) :=\n  match t with\n  | leaf n => leaf (f n)\n  | node ts => node (List.map (tree_map f) ts)\n  end.\n\n(** Another example using List.fold -- recommended *)\n\nFixpoint tree_sum (t:tree) :=\n  match t with\n  | leaf n => n\n  | node ts => List.fold_left (fun acc t => acc + tree_sum t) ts 0\n  end.\n\n(** Proof of the recursion principle *)\n\nSection Tree_induct.\n(* Note: some hypotheses are given directly by [Check tree_ind] *)\nVariables\n(P : tree -> Prop)\n(Q : list tree -> Prop)\n(P1 : forall n, P (leaf n))\n(P2 : forall ts, Q ts -> P (node ts))\n(Q1 : Q nil)\n(Q2 : forall t ts, P t -> Q ts -> Q (t::ts)).\n\nFixpoint tree_induct_gen (t : tree) : P t :=\n  match t as x return P x with\n  | leaf n => P1 n\n  | node ts => P2\n      ((fix tree_list_induct (ts:list tree) : Q ts :=\n      match ts as x return Q x with\n      | nil   => Q1\n      | t::ts' => Q2 (tree_induct_gen t) (tree_list_induct ts')\n      end) ts)\n  end.\n\nEnd Tree_induct.\n\n(** Example of a direct inductive proof -- not recommended *)\n\nLemma tree_map_pred_succ_1 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof using.\n  intros. pattern t. match goal with |- ?F _ => sets P: F end.\n  eapply tree_induct_gen with (Q := Forall P); subst P; simpl; intros.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    inverts H. fequals~.\n  constructors.\n  constructors~.\nQed.\n\n(** Proof of the induction principle with Forall *)\n\nLemma tree_induct_forall : forall (P : tree -> Prop),\n  (forall n : nat, P (leaf n)) ->\n  (forall ts : list tree, Forall P ts -> P (node ts)) ->\n  forall t : tree, P t.\nProof using.\n  introv Hl Hn. eapply tree_induct_gen with (Q := Forall P); intros.\n  auto. auto. constructors~. constructors~.\nQed.\n\n(** Example of an inductive proof with Forall\n    -- recommended *)\n\nLemma tree_map_pred_succ_2 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof using.\n  intros. induction t using tree_induct_forall; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    auto.\n    inverts H. fequals~.\nQed.\n\n(** Proof of the induction principle with Mem *)\n\nLemma tree_induct_mem : forall (P : tree -> Prop),\n  (forall n : nat, P (leaf n)) ->\n  (forall ts : list tree,\n    (forall t, Mem t ts -> P t) -> P (node ts)) ->\n  forall t : tree, P t.\nProof using.\n  introv Hl Hn. eapply tree_induct_gen with (Q := fun ts =>\n    forall t, Mem t ts -> P t); intros.\n  auto. auto. inverts H. inverts~ H1.\nQed.\n\nHint Constructors Mem.\n\n(** Example of an inductive proof with Mem\n    -- usually not as good as the one with [Forall] *)\n\nLemma tree_map_pred_succ_3 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof using.\n  intros. induction t using tree_induct_mem; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    fequals.\n      apply H. constructor.\n      apply IHts. introv M. apply H. auto.\nQed.\n\n(** Definition of the relation \"immediate subtree of\" *)\n\nRequire Import LibRelation LibWf.\n\nInductive subtree : binary tree :=\n  | subtree_intro : forall t ts,\n     Mem t ts -> subtree t (node ts).\n  (* there is typically more than one case here *)\n\nHint Constructors subtree.\n\n(** Proof of well-foundedness of the subtree relation *)\n\nLemma subtree_wf : wf subtree.\nProof using.\n  intros t. induction t using tree_induct_mem;\n  constructor; introv K; inversions~ K.\nQed.\n\n(** Example of a proof on the well-founded subtree order\n    -- usually a bit longer, so not recommended *)\n\nLemma tree_map_pred_succ_4 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof using.\n  intros. induction_wf IH: subtree_wf t.\n  destruct t as [|ts]; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    fequals.\n      applys IH. auto.\n      applys IHts. introv M. inverts M.\n       auto. (* apply IH. constructors. constructors. *)\nQed.\n\nEnd SubtermIndDemos.\n\n\n(* ********************************************************************** *)\n(** * Tactics exported by LibVar *)\n\nModule LibVarDemos.\nRequire Import LibList LibLN.\nSection LibVarDemo.\nImplicit Types x y : var.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo for notin *)\n\nLemma test_notin_solve_1 : forall x E F G,\n  x \\notin E \\u F -> x \\notin G -> x \\notin (E \\u G).\nProof using.\n  intros. dup.\n  notin_simpl. notin_solve. notin_solve.\n  notin_solve.\nQed.\n\nLemma test_notin_solve_2 : forall x y E F G,\n  x \\notin E \\u \\{y} \\u F -> x \\notin G ->\n  x \\notin \\{y} /\\ y \\notin \\{x}.\nProof using.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_solve_3 : forall x y,\n  x <> y -> x \\notin \\{y} /\\ y \\notin \\{x}.\nProof using.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_solve_4 : forall x y,\n  x \\notin \\{y} -> x <> y /\\ y <> x.\nProof using.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_false_1 : forall x y E F G,\n  x \\notin (E \\u \\{x} \\u F) -> y \\notin G.\nProof using.\n  intros. dup 3.\n    false. notin_false.\n    notin_false.\n    notin_false.\nQed.\n\nLemma test_notin_false_2 : forall x y : var,\n  x <> x -> y = x.\nProof using.\n  intros. notin_false.\nQed.\n\nLemma test_neq_solve : forall x y E F,\n  x \\notin (E \\u \\{y} \\u F) -> y \\notin E ->\n  y <> x /\\ x <> y.\nProof using.\n  split. notin_solve. notin_solve.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo for fresh *)\n\nLemma test_fresh_solve_1 : forall xs L1 L2 n,\n  fresh (L1 \\u L2) n xs -> fresh L1 n xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_2 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh L2 n xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_3 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh \\{} n xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_4 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh L1 (length xs) xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_5 : forall xs L1 n m,\n  m = n ->\n  fresh L1 m xs ->\n  fresh L1 n xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_6 : forall xs L1 L2 n m,\n  m = n ->\n  fresh (L1 \\u L2) n xs ->\n  fresh L1 m xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_7 : forall xs L1 L2 n m,\n  n = m ->\n  fresh (L1 \\u L2) n xs ->\n  fresh L1 m xs.\nProof using.\n  intros. fresh_solve.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of automation of [notin] *)\n\n(* LibVar exports the following hints:\n     Hint Extern 1 (_ \\notin _) => notin_solve.\n     Hint Extern 1 (_ <> _ :> var) => notin_solve.\n     Hint Extern 1 ((_ \\notin _) /\\ _) => splits. *)\n\nLemma test_notin_by_auto : forall x E F G,\n  x \\notin E \\u F -> x \\notin G -> x \\notin (E \\u G).\nProof using. auto. Qed.\n\nLemma test_neq_by_auto : forall x y E,\n  x \\notin E \\u \\{y} -> y <> x.\nProof using. auto. Qed.\n\nLemma test_notin_false_by_hand : forall x,\n  ~ x \\notin \\{x}.\nProof using. intros_all. notin_false. Qed.\n\nHint Extern 1 (~ _ \\notin _) => intros_all; notin_false.\n\nLemma test_notin_false_by_auto : forall x,\n  ~ x \\notin \\{x}.\nProof using. intros_all. notin_false. Qed.\n\n(* Comment: using the following hint is a bad idea because it will\n            lead to very inefficient proof scripts.\n   Hint Extern 1 (False) => notin_false. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of pick_fresh_gen *)\n\nParameter trm : Type.\nParameter fv : trm -> vars.\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 : trm => fv x) in\n  constr:(A \\u B \\u C).\n\nLtac pick_fresh Y :=\n  let L := gather_vars in (pick_fresh_gen L Y).\n\nLemma test_pick_fresh :\n  forall (x y z : var) (L1 L2 L3 : vars) (t1 t2 : trm), True.\nProof using.\n  intros. pick_fresh a.\nAbort.\n\nEnd LibVarDemo.\nEnd LibVarDemos.\n\n\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/LibOtherDemos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969193, "lm_q2_score": 0.9136765281148513, "lm_q1q2_score": 0.7970433236383191}}
{"text": "(* Copyright (c) 2011, Thorsten Altenkirch *)\n\n(** %\\chapter{%#<H0>#Peano Arithmetic%}%#</H0># *)\n\nSection Arith.\n\n(** * The natural numbers *)\n\n(** Guiseppe Peano defined the natural numbers as given by [0 : nat]\n    and if [n] is a natural number then [S n : nat] is a natural number\n    called the successor of [n]. Given this we can construct all the \n    natural numbers, e.g.\n    - 1 = S 0\n    - 2 = S 1 = S (S 0)\n    - 3 = S 2 = S (S (S 0))\n    Moreover these are all natural numbers (we say they are defined _inductively_).\n\n    Peano went on to represent the fundamental properties of the natural \n    numbers using axioms. Some of the axioms express general properties of \n    equality, which we have already seen. But the following three are \n    specific to the natural numbers. Indeed, they are provable propositions\n    in Coq:\n\n    - Axiom 7 : 0 is not the successor of any number.\n      [forall n:nat, S n <> 0]\n    - Axiom 8 : If two numbers have the same successor, then they are equal.\n      [forall m n:nat, S m = S n -> m = n ]\n    - Axiom 9 : If any property holds for 0, and is closed under successor, \n      then it holds \n      for all natural numbers (principle of induction).\n      [forall P : nat -> Prop, P 0 \n                      -> (forall m : nat, P m -> P (S m))\n                      -> forall n : nat, P n]\n\n    For illustration we are going to prove these principles:\n*)\n\nLemma peano7 : forall n:nat, S n <> 0.\nintro n.\nintro h.\n\n(** This is basically the same problem as proving [true <> false], we\n    could apply the same technique here. To avoid repetetion we just\n    use the [discriminate] tactic.\n*)\n\ndiscriminate h.\nQed.\n  \n(** To prove the next axiom, it is useful to define the inverse to\n    S, the predecessor function pred. We arbitrarily decide that the \n    predecessor of 0 is 0. *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n => n\n  end.\n  \nLemma peano8 : forall m n:nat, S m = S n -> m = n.\nintros m n h.\n\n(** By folding with [pred] we can change the current goal so that we can\n    apply our hypothesis. *)\n\nfold (pred (S m)).\nrewrite h.\n\n(** And now we just have to unfold. simpl would have done the job too. *)\n\nunfold pred.\nreflexivity.\nQed.\n\n(** The 8th axiom says that the successor function is injective. \n    Can we prove the other direction too? \n    [forall m n:nat, m = n -> S m = S n]\n    Does this tell us anything new\n    about the successor function? *)\n\n(** The proof of the induction axiom is rather boring. It just uses a tactic\n    which is called [induction]... *)\n\nLemma peano9 : forall P : nat -> Prop, P 0 \n                      -> (forall m : nat, P m -> P (S m))\n                      -> forall n : nat, P n.\nintros P h0 hS n.\ninduction n.\nexact h0.\napply hS.\nexact IHn.\nQed.\n\n(** * Addition and multiplication *)\n\n(** Peano defined the operations addition and multiplication.\n    These are actually examples of functions defined by _primitive\n    recursion_ a general scheme which can be used to define many \n    other functions. A function is definable by primitive recursion\n    if we can give a case for 0 and reduce the computation for the\n    value at [S n] to the value at [n]. In Coq we have to use the \n    keyword [fixpoint] instead of [definition] and we have to indicate\n    on which argument we want to do primitive recursion.\n*)\n\n(** The idea is that we can define addition like this:\n   - to add 0 to a number is just this number,\n   - to add one more that n to a number is one more than adding\n     n to the number.\n*)\n\nFixpoint add (m n : nat) {struct m} : nat :=\n  match m with\n  | 0 => n\n  | S m => S (add m n)\n  end.\n\nEval compute in (add 2 3).\n\n(** In the Coq library addition is defined using the usual infix\n    notation [+]. *)\n\n(** To define multiplication we use primitive recursion again. This time\n    the idea is the following.\n    - multiplying 0 with a number is just 0.\n    - multiplying one more than n with a number is obtained by adding \n      the number to multiplying n with the number.\n*)\n\nFixpoint mult (m n : nat) {struct m} : nat :=\n  match m with\n  | 0 => 0\n  | S m => add n (mult m n)\n  end.\n\nEval compute in (mult 2 3).\n\n(** In the Coq library addition is defined using the usual infix\n    notation [+] and [*] with the usual rules of precedence.\n    From now on we shall use the library versions which are defined\n    exactly in the same way as we have defined [add] and [mult] *)\n\n(** * Algebraic properties *)\n\n(** Addition and multiplication satisfy a number of important equations:\n   - 0 is a neutral element for addition\n     [0 + m = m] and [m + 0 = m]\n   - Addition is associative.\n     [m + (n + l) = (m + l) + n]\n   - Addition is commutative.\n     [m + n = n + m]\n   - 1 is a neutral element for multiplication\n     [1 * m = m] and [m * 1 = m]\n   - Multiplication is associative.\n     [m * (n * l) = (m * n) * l]\n   - Multiplication is commutative.\n     [m * n = n * m]\n   - 0 is a null for multiplication.\n     [m * 0 = 0] and [0 * m = 0]\n   - Addition distributes over multiplication.\n     [m * (n + l) = m * n + m * l]\n     and\n     [(m + n) * l = m * l + n * l]\n\n   In the language of universal algebra, we say that \n   - (+,0) is a _commutative monoid_,\n     because 0 is neutral, [+] is associative and commutative.\n   - ( *,1) is a commutative monoid,\n     because 1 is neutral, [*] is associative and commutative.\n   - (+,0,*,1) is a _commutative semiring_ because\n     (+,0) and ( *,1) are commutative monoids and\n     [0] is a zero for multiplication and \n     addition distributes over multiplication. \n\n   We are going to prove that (+,0) is a commutative monoid \n   and leave the remaining properties as an exercise. *)\n \nLemma plus_O_n : forall n:nat, n = 0 + n.\n(** This property is very easy to prove.\n    Can you see why?\n*)\nintro n.\nreflexivity.\nQed.\n\nLemma plus_n_O : forall n:nat, n = n + 0.\nintro n.\n\n(** This one cannot be proven by reflexivity.\n    So we have to use induction. *)\n\ninduction n.\n\n(** n = 0 \n    This is easy. *)\n\nsimpl.\nreflexivity.\n\n(** We can simplify [S n + 0] using the definition of [+] *)\n\nsimpl.\nrewrite<- IHn.\nreflexivity.\nQed.\n\n\nLemma plus_assoc : forall (l m n:nat),l + (m + n) = (l + m) + n.\nintros l m n.\n\n(** There seems to be quite a choice what to do induction over:\n    [l],[m],[n] but only one of them works. Why? *)\n\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHl.\nreflexivity.\nQed.\n\n(** To prove commutativity we first prove a lemma \n    we know already that [0 + m = m = m + 0]\n    but what about [S m + n = S (m + n) = m + S n] ?\n*)\n\nLemma plus_n_Sm : forall n m : nat, S (m + n) = m + S n.\nintros.\ninduction m.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHm.\nreflexivity.\nQed.\n\n(** We are now ready to prove commutativity. *)\n\nLemma plus_comm : forall n m:nat, n + m = m + n.\nintros.\ninduction n.\nsimpl.\napply plus_n_O.\nsimpl.\nrewrite IHn.\napply plus_n_Sm.\nQed.\n\n(** * Ordering the numbers *)\n\n(** We define the relation [<=] on natural numbers by saying \n    that [m <= n] holds if there is a number [k] such that \n    [m = k + n]. *)\n\nDefinition leq (m n : nat) : Prop :=\n  exists k : nat, n = k + m.\n\nNotation \"m <= n\" := (leq m n).\n\n(** We verify some basic properties of [<=]:\n    - [<=] is reflexive.\n      [forall n:nat, n <= n]\n    - [<=] is transitive.\n      [forall l m n:nat, l <= m -> m <= n -> l <= n]\n    - [<=] is antisymmetric.\n      [forall l m : nat, l <= m -> m <= l -> m = l]\n\n  Any relation which is reflexive, transitive and antisymmetric is a _partial order_.\n  Here the word _partial_ is used to differentiate [<=] from a total order like [<].\n  We verify the first two properties in Coq, but leave antisymmetry as an exercise.\n*)\n\nLemma le_refl: forall n:nat,n <= n.\nintro n.\nexists 0.\nreflexivity.\nQed.\n\nLemma le_trans : forall (l m n : nat), l <= m -> m <= n -> l <= n.\nintros l m n lm mn.\ndestruct lm as [k klm].\ndestruct mn as [j jmn].\nexists (j+k).\nrewrite<- plus_assoc.\nrewrite<- klm.\nrewrite<- jmn.\nreflexivity.\nQed.\n\n(** * Decidable properties *)\n\n(** We say a predicate is [P : A -> Prop] _decidable_ if we can define\n    a boolean function [decP : A -> bool] which agrees with the predicate,\n    i.e. [forall a:A, P a <-> decP a = true]. This also extends to relations\n    in the obvious way.\n\n    We show below that equality on natural numbers is decidable. \n    Do you know any undecidable predicates? \n    Is equality always decidable?\n*)\n\n\n(** First we define the _decision procedure_. In the case of equality this is quite obvious:\n   we inspect both parameters, if they start with different constructors (i.e. 0 vs S) they are certainly \n   not equal. If they are both [0] they are equal, and if they both start with [S] then we recursively \n   compare the arguments. *)\n\nFixpoint eqnat (m n : nat) {struct m} : bool :=\n  match m with \n  | 0 => match n with \n         | 0 => true\n         | S n' => false\n         end\n  | S m' => match n with \n            | 0 => false\n            | S n' => eqnat m' n'\n            end\n  end.\n\n(** Now we show both direction seperately. The [->] direction just boils down\n   to showing that [eqnat] is reflexive. Why? *)\n\nLemma eqnat_refl : forall m : nat,  eqnat m m = true.\nintro m.\ninduction m.\nreflexivity.\nsimpl.\nexact IHm.\nQed.\n\n(** The other direction is more interesting and requires a _double induction_\n   over [m] and [n]. *)\n\nLemma eqnat_compl : forall m n : nat, eqnat m n = true -> m = n.\nintro m.\n(** Here it would have been a mistake to do [intros m n]. Why? *)\n(** m = 0 *)\ninduction m.\nintro n.\ninduction n.\n(** n = 0 *)\nintro h.\nreflexivity.\n(** n = S n' *)\nintro h.\nsimpl in h.\ndiscriminate h.\n(** m = S m' *)\nintro n.\ninduction n.\n(** n = 0 *)\nintro h.\ndiscriminate h.\n(** n = S n' *)\nintro h.\nassert (h' : m = n).\napply IHm.\nexact h.\nrewrite h'.\nreflexivity.\nQed.\n\n(** Finally, we can prove the theorem that equality for natural numbers is decidable. *)\n\nTheorem eqnat_dec : forall m n : nat, m = n <-> eqnat m n = true.\nintros m n.\nsplit.\nintro h.\nrewrite h.\napply eqnat_refl.\napply eqnat_compl.\nQed.\n\n\nEnd Arith.", "meta": {"author": "radu07", "repo": "automat", "sha": "5d8c4ec7414025cb83ec094e45e09a7cd1d607da", "save_path": "github-repos/coq/radu07-automat", "path": "github-repos/coq/radu07-automat/automat-5d8c4ec7414025cb83ec094e45e09a7cd1d607da/auto/auto/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.7970433088374498}}
{"text": "(** * Logic: Logic in Coq *)\n\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 nat -> 3 = 3 : Prop.\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nLemma myproof1: 3 = 3.\nProof. auto. Qed.\n\nLemma myproof2: 3 = 3.\nProof. reflexivity. Qed.\n\nCheck myproof1 = myproof2.\n\nAxiom prop_extensionality:\n  forall (P: Prop) (p q: Prop),\n    p = q.\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\n(* Inductive or (A B : Prop) : Prop := *)\n(* | or_intro_l : A -> A \\/ B *)\n(* | or_intro_r : B -> A \\/ B *)\n(* . *)\n\n(* Inductive and (A B : Prop) : Prop := *)\n(* | conj : A -> B -> A /\\ B *)\n(* . *)\n\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 H.\n  apply and_intro.\n  - (* n = 0 *) induction n as [| n'].\n    + reflexivity.\n    + inversion H.\n  - (* m = 0 *) induction m as [| m'].\n    + reflexivity.\n    + rewrite plus_comm in H. inversion H.\nQed.\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].\n  apply HQ. Qed.\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]].\n  split.\n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR.\nQed.\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\nPrint mult_0_r.\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].\n  - intros m H. rewrite mult_0_l in H. left. apply H.\n  - intros [|m].\n    + intros H. rewrite mult_0_r in H. right. apply H.\n    + intros H. inversion H.\nQed.\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(** ** 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(* False means that there is no constructor, so you don't have any subgoals to be solved. *)\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\nPrint ex_falso_quodlibet.\n\nLemma foo: 3 = 4 -> False.\n  intros.\n  inversion H.\nQed.\n\nLemma foo': ~ 3 = 4.\n  red.\n  intros.\n  inversion H.\nQed.\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 HPnot Q HP.\n  contradiction.\nQed.\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(* 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 HQnot.\n  unfold not. unfold not in HQnot. intros P'. apply HQnot. apply H. apply P'.\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 [HP HPnot].\n  apply HPnot. apply HP.\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(* 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\nPrint True.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nLemma True_is_true' : True.\n  auto.\nQed.\n\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 P'. apply P'.\n  - (* <- *) intros P'. apply P'.\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 P'. apply HPQ in P'. apply HQR in P'. apply P'.\n  - (* <- *) intros R'. apply HRQ in R'. apply HQP in R'. apply R'.\nQed.\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. inversion H.\n    + split.\n      { left. apply H0. }\n      { left. apply H0. }\n    + split.\n      { apply proj1 in H0. right. apply H0. }\n      { apply proj2 in H0. right. apply H0. }\n  - (* <- *) intros H. inversion H.\n    + destruct H1.\n      { left. apply H1. }\n      { destruct H0.\n        { left. apply H0. }\n        { right. split.\n          { apply H0. }\n          { apply H1. } } }\nQed.\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 H.\n  destruct H as [x Hx].\n  exists (2+x).\n  simpl. simpl in Hx.\n  apply Hx.\nQed.\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 Hall Hexist.\n  destruct Hexist as [x HPnot].\n  unfold not in HPnot. apply HPnot. apply Hall.\nQed.\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 H. destruct H as [X' H]. destruct H as [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' HP]. exists X'. left. apply HP.\n    + destruct HQ as [X' HQ]. exists X'. right. apply HQ.\nQed.\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.) *)\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\nCompute In 3 (4::2::nil).\n\nCompute In 5 (2::5::6::nil).\n\nLemma gil: forall n m (l: list nat), In n l -> n = m -> In m l.\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  intros A B f l y. split.\n  - (* -> *) intros H. induction l as [| x' l' IHl'].\n    + (* l = [] *)\n      simpl in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl in H. destruct H as [H1 | H2].\n      { exists x'. split.\n        - apply H1.\n        - simpl. left. reflexivity. }\n      { apply IHl' in H2. destruct H2 as [x2 H2]. exists x2. split.\n        - apply proj1 in H2. apply H2.\n        - simpl. right. apply proj2 in H2. apply H2. }\n  - (* <- *) intros H. induction l as [| x' l' IHl'].\n    + (* l = [] *)\n      simpl in H. destruct H as [x' H]. apply proj2 in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl. simpl in H. destruct H as [x'' H]. inversion H. destruct H1 as [H2 | H3].\n      { left. rewrite H2. apply H0. }\n      { right. apply IHl'. exists x''. split.\n        - apply H0.\n        - apply H3. }\nQed.\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' x. split.\n  - intros H. induction l.\n    + simpl. simpl in H. right. apply H.\n    + simpl. simpl in H. destruct H.\n      { left. left. apply H. }\n      { apply IHl in H. apply or_assoc. right. apply H. }\n  - intros H. induction l.\n    + simpl. simpl in H. destruct H.\n      { contradiction. }\n      { apply H. }\n    + simpl. simpl in H. apply or_assoc in H. destruct H as [H1 | [H2 | H3]].\n      { left. apply H1. }\n      { right. apply IHl. left. apply H2. }\n      { right. apply IHl. right. apply H3. }\nQed.\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  | [] => 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  - (* -> *) intros H. induction l.\n    + simpl. auto.\n    + simpl. split.\n      { apply H. simpl. left. reflexivity. }\n      { apply IHl. intros x0 H0. apply H. simpl. right. apply H0. }\n  - (* <- *) intros H. induction l.\n    + simpl. intros x0 H0. contradiction.\n    + simpl. intros x0 H0. destruct H0 as [|H1 H2].\n      { simpl in H. apply proj1 in H. rewrite H0 in H. apply H. }\n      { simpl in H. apply proj2 in H. apply IHl with x0 in H. apply H. apply H1. }\nQed.\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 : 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 Hodd Heven.\n  unfold combine_odd_even. destruct (oddb n) eqn: H.\n  - apply Hodd. reflexivity.\n  - apply Heven. 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 Hcomb Hodd.\n  unfold combine_odd_even in Hcomb.\n  rewrite Hodd in Hcomb. assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n Hcomb Heven.\n  unfold combine_odd_even in Hcomb.\n  rewrite Heven in Hcomb. assumption.\nQed.\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  Check @functional_extensionality.\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(* FILL IN HERE *) 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)  *)\n(* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\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'].\n  - simpl. exists 0. reflexivity.\n  - destruct (evenb n') eqn: Heq.\n    + rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists n''. rewrite IHn'. reflexivity.\n    + rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists (n''+1). rewrite IHn'. rewrite double_plus. rewrite double_plus.\n      rewrite plus_n_Sm. rewrite <- plus_1_l. rewrite <- plus_n_Sm. rewrite <- (plus_1_l (n'' + n'')).\n      rewrite plus_comm. rewrite plus_assoc.  rewrite (plus_comm 1).\n      rewrite plus_assoc. 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\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\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. split.\n    + rewrite andb_commutative in H. apply andb_true_elim2 in H. apply H.\n    + apply andb_true_elim2 in H. apply H.\n  - (* <- *) intros H. inversion H. rewrite H0. rewrite H1. 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  - (* -> *) intros H. destruct H. destruct b1.\n    + simpl. left. reflexivity.\n    + simpl. right. reflexivity.\n  - (* -> *) intros H. destruct H as [H1 | H2].\n    + rewrite H1. simpl. reflexivity.\n    + rewrite H2. destruct b1.\n      { reflexivity. }\n      { reflexivity. }\nQed.\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  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\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, l2 with\n  | [] , [] => true\n  | _  , [] => false\n  | [] , _  => false\n  | h1 :: t1 , h2 :: t2 => if(beq h1 h2) then beq_list beq t1 t2 else 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 l1 l2. split.\n  - (* -> *) generalize dependent l2. induction l1 as [| h1 l1' IHl1'].\n    + induction l2 as [| h2 l2' IHl2'].\n      { reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (beq h1 h2) eqn:Heq.\n        + apply H in Heq. rewrite <- Heq.\n          assert (l1' = l2' -> h1 :: l1' = h1 :: l2') as H2.\n          { intros H3. rewrite H3. reflexivity. } apply H2. apply IHl1'. apply H1.\n        + inversion H1. }\n  - (* <- *) generalize dependent l2. induction l1 as [| h1 l1' IHl1'].\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (beq h1 h2) eqn:Heq.\n        + apply IHl1'. apply H in Heq. rewrite Heq in H1.\n          assert (h1 :: l1' = h1 :: l2' -> l1' = l2') as H2.\n          { intros H3. inversion H1. reflexivity. } apply H2. rewrite Heq. apply H1.\n        + inversion H1. apply H in H2. rewrite H2 in Heq. symmetry. apply Heq. }\nQed.\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. split.\n  - (* -> *) intros. induction l.\n    + simpl. auto.\n    + simpl. split.\n      { unfold forallb in H. rewrite andb_true_iff in H. apply proj1 in H. assumption. }\n      { apply IHl. inversion H. rewrite andb_true_iff in H1. destruct H1 as [H2 H3]. rewrite H2.\n        rewrite H3. auto. }\n  - (* <- *) intros. induction l.\n    + reflexivity.\n    + simpl. rewrite andb_true_iff. split.\n      { simpl in H. apply proj1 in H. assumption. }\n      { simpl in H. apply proj2 in H. apply IHl in H. assumption. }\nQed.\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  unfold not. intros P H. apply H. right. intros. apply H. left. apply H0.\nQed.\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  unfold excluded_middle. intros ex X f H x. unfold not in H. unfold not in ex.\n  destruct (ex (f x)) as [H1 | H2]. apply H1. destruct H. exists x. apply H2.\nQed.\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": "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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.796884729676565}}
{"text": "(*** Introduction to Computational Logic, Coq part of Assignment 2 ***)\n\n\n\n(*** Exercise 2.1 ***)\n\nDefinition swap X Y (p : X * Y) : Y * X :=\n  match p with (x, y) => (y, x) end.\n\nArguments swap [_ _].\n\nLemma swap_invol X Y (p : X * Y) :\n  swap (swap p) = p.\nProof.\n  destruct p. reflexivity.\nQed.\n\nLemma prod_eta X Y (p : X * Y) :\n  (fst p, snd p) = p.\nProof.\n  destruct p. reflexivity.\nQed.\n\n\n(*** Exercise 2.2 ***)\n\n(* State the definitions and equations on your own. *)\nDefinition f X Y Z (p: X * (Y * Z)) : (X * Y) * Z :=\n  match p with (x, (y, z)) => ((x, y), z) end.\n\nDefinition g X Y Z (q: (X * Y) * Z) : X * (Y * Z) :=\n  match q with ((x, y), z) => (x, (y, z)) end.\n\nLemma fug X Y Z (t: X * (Y * Z)) : g X Y Z (f X Y Z t) = t.\nProof.\n  destruct t; destruct p; reflexivity.\nQed.\n\nLemma guf X Y Z (t: (X * Y) * Z) : f X Y Z (g X Y Z t) = t.\nProof.\n  destruct t; destruct p; reflexivity.\nQed.\n\n(*** Exercise 2.3 ***)\n\nFixpoint iter X (f : X -> X) n x :=\n  match n with\n  | O => x\n  | S n => f (iter X f n x)\n  end.\n\nArguments iter [_].\n\nLemma iter_shift X (f : X -> X) n x :\n  f (iter f n x) = iter f n (f x).\nProof.\n  induction n as [|n IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\n\n(*** Exercise 2.4 ***)\n\nFixpoint fac (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n => (1 + n) * fac n\n  end.\n\nDefinition step (p : nat * nat) : nat * nat :=\n  match p with\n  | (n, fn) => let k := 1 + n in (k, k * fn)\n  end.\n\nLemma it_step n :\n  (n, fac n) = iter step n (0, 1).\nProof.\n  induction n as [|n IH].\n  - reflexivity.\n  - simpl. rewrite <- IH. reflexivity.\nQed.\n\nLemma it_fac n :\n  fac n = snd (iter step n (0, 1)).\nProof.\n  rewrite <- it_step. reflexivity.\nQed.\n\n\n(*** Exercise 2.5 ***)\n\nPrint True.\nAbout I.\n\nPrint False.\n\nPrint and.\nAbout conj.\n\nPrint or.\nAbout or_introl.\nAbout or_intror.\n\n\n(*** Exercise 2.6 ***)\n\nSection Ex6.\n\n  Variables X Y Z : Prop.\n\n  Goal X -> Y -> X.\n  Proof.\n    intros x y. exact x.\n  Qed.\n\n  Goal (X -> Y -> Z) -> (X -> Y) -> X -> Z.\n  Proof.\n    intros f g x.\n    apply f.\n    - exact x.\n    - apply g. exact x.\n  Qed.\n      \n  Goal (X -> Y) -> ~ Y -> ~ X.\n  Proof.\n    intros f g x. exact (g (f x)).\n  Qed.\n\n  Goal (X -> False) -> (~ X -> False) -> False.\n  Proof.\n    intros f g. apply g. exact f.\n    Show Proof.\n  Qed.\n\n  Goal ~ (X <-> ~ X).\n  Proof.\n    intros [f g].\n    assert (x: X).\n    - apply g. intros x. exact (f x x).\n    - exact (f x x).\n    Show Proof.\n  Qed.\n\n  Goal ~ (X <-> ~ X).\n  Proof.\n    refine (fun h => match h with conj f g => _ end).\n    refine (let x := g (fun x => f x x) in _).\n    exact (f x x).\n    Show Proof.\n  Qed.\nEnd Ex6.\n\n\n(*** Exercise 2.7 ***)\n\nSection Ex7.\n\n  Variables X Y Z : Prop.\n\n\n  Goal X /\\ (Y \\/ Z) -> X /\\ Y \\/ X /\\ Z.\n  Proof.\n    refine (fun h => match h with conj x disj => match disj with\n                                                 | or_introl y => or_introl (conj x y)\n                                                 | or_intror z => or_intror (conj x z)\n                                                 end\n                     end).\n    Qed.\n\n  Goal X /\\ (Y \\/ Z) -> X /\\ Y \\/ X /\\ Z.\n  Proof.\n    intros [x [y|z]].\n    - exact (or_introl (conj x y)).\n    - exact (or_intror (conj x z)).\n  Qed.\n\n  Goal X \\/ (Y /\\ Z) -> (X \\/ Y) /\\ (X \\/ Z).\n  Proof.\n    exact (fun h => match h with\n                    | or_introl x => conj (or_introl x) (or_introl x) \n                    | or_intror (conj y z) => conj (or_intror y) (or_intror z)\n                    end).\n  Qed.\n\n  Goal X \\/ (Y /\\ Z) -> (X \\/ Y) /\\ (X \\/ Z).\n  Proof.\n    intros [x |[y z]].\n    - exact (conj (or_introl x) (or_introl x)).\n    - exact (conj (or_intror y) (or_intror z)).\n  Qed.\n\n  Goal X \\/ (X /\\ Y) <-> X.\n  Proof.\n    exact (conj (fun h => match h with\n                          | or_introl x => x\n                          | or_intror (conj x y) => x\n                          end)\n                (fun x => or_introl x)).\n  Qed.\n\n  Goal X \\/ (X /\\ Y) <-> X.\n  Proof.\n    split.\n    - intros [x |[x y]]; exact x.\n    - intros x. exact (or_introl x).\n  Qed.\n\n  Goal X /\\ (X \\/ Y) <-> X.\n  Proof.\n    refine (conj (fun h => match h with conj x dist => x end) (fun x => conj x (or_introl x))).\n  Qed.    \n\n  Goal X /\\ (X \\/ Y) <-> X.\n  Proof.\n    split.\n    - intros [x [x'|y]]; exact x.\n    - intros x. exact (conj x (or_introl x)).\n  Qed.\n\nEnd Ex7.\n\n\n\n(*** Exercise 2.8 ***)\n\nLemma demorgan1 X Y :\n  ~ (X \\/ Y) <-> ~ X /\\ ~ Y.\nProof.\n  split.\n  - intros f. split.\n    + intros x. apply f. left. exact x.\n    + intros y. apply f. right. exact y.\n  - intros f. destruct f as [nX nY]. intros dist. destruct dist as [x|y].\n    + exact (nX x).\n    + exact (nY y).\n  Show Proof.\nQed.\n\nLemma demorgan1' X Y:\n  ~ (X \\/ Y) <-> ~ X /\\ ~Y.\nProof.\n  refine (conj (fun h => conj (fun x => h (or_introl x)) (fun y => h (or_intror y)))\n               (fun h => fun z => match h with conj f g => _ end)).\n  destruct z as [x | y].\n  - exact (f x).\n  - exact (g y).\n  Show Proof.\nQed.\n\nLemma demorgan2 X Y :\n  ~ X \\/ ~ Y <-> ~ (X /\\ Y).\nProof.\n  split.\n  - intros dist con. destruct dist as [nX | nY].\n    + destruct con as [x y]. exact (nX x).\n    + destruct con as [x y]. exact (nY y).\n  - (* This direction can't be proven without excluded middle *)\n    Abort.\n  \n\n(*** Exercise 2.9 ***)\n\nLemma ex9a :\n  False <-> forall Z : Prop, Z.\nProof.\n  split.\n  - intros H. destruct H.\n  - intros H. apply H.\n  Show Proof.\nQed.\n\nLemma ex9a' :\n  False <-> forall Z : Prop, Z.\nProof.\n  refine (conj (fun h : False => match h with end) (fun h => h False)).\n  Show Proof.\nQed.\n\nLemma ex9b X Y :\n  X /\\ Y <-> forall Z : Prop, (X -> Y -> Z) -> Z.\nProof.\n  split.\n  - intros H z f. destruct H as [x y]. exact (f x y).\n  - intros f. split.\n    + apply (f X). intros x y. exact x.\n    + apply (f Y). intros x y. exact y.\n  Show Proof.\nQed.\n\nLemma ex9b' X Y :\n  X /\\ Y <-> forall Z : Prop, (X -> Y -> Z) -> Z.\nProof.\n  exact (conj (fun h z f => match h with conj x y => f x y end)\n              (fun f => conj (f X (fun x _ => x)) (f Y (fun _ y => y)) )).\nQed.\n\nLemma ex9c X Y :\n  X \\/ Y <-> forall Z : Prop, (X -> Z) -> (Y -> Z) -> Z.\nProof.\n  split.\n  - intros h Z f g. destruct h as [x|y].\n    + exact (f x).\n    + exact (g y).\n  - intros f. apply (f (X \\/ Y)).\n    + intros x. left. exact x.\n    + intros y. right. exact y.\n  Show Proof.\nQed.\n\nLemma ex9c' X Y :\n  X \\/ Y <-> forall Z : Prop, (X -> Z) -> (Y -> Z) -> Z.\nProof.\n  refine (conj (fun h Z f g => match h with\n                               | or_introl x => f x\n                               | or_intror y => g y\n                               end)\n               (fun f => f (X \\/ Y) _ _)).\n  - exact (fun x => or_introl x).\n  - exact (fun y => or_intror y).\nQed.\n\nLemma ex9d :\n  (forall X, X \\/ ~ X) <-> (forall X, ~ ~ X -> X).\nProof.\n  split.\n  - intros H X f. destruct (H X) as [x | nX].\n    + exact x.\n    + destruct (f nX).\n  - intros H X. apply (H (X \\/ ~X)). intros fx. apply fx. right. apply (H (~ X)). intros g.\n    apply fx. assert X.\n    + apply (H X g).\n    + exact (or_introl H0).\n  Show Proof.\nQed.\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/2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.9046505357435622, "lm_q1q2_score": 0.7968135371512582}}
{"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\n    Definition lst_mem (lst_mem_arg0 : natural) (lst_mem_arg1 : lst) : bool\n    := match lst_mem_arg0, lst_mem_arg1 with\n       | n, x => mem x n\n       end.\n\n\n  Fixpoint lst_union (lst_union_arg0 : lst) (lst_union_arg1 : lst) : lst\n  := match lst_union_arg0, lst_union_arg1 with\n     | Nil, x => x\n     | Cons n x, y => if lst_mem n y then lst_union x y else Cons n (lst_union x 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   - intros. destruct y.\n   + discriminate.\n   + reflexivity.\nQed.\n\nLemma mem_union : forall (x : natural) (y z : lst), lst_mem x y = true -> lst_mem x (lst_union z y) = true.\nProof.\n   intros.\n   induction z.\n   - simpl. destruct (lst_mem n y).\n   + assumption.\n   + simpl. rewrite IHz. apply Bool.orb_true_r.\n   - assumption.\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : lst) (z : lst), eq (lst_mem x y) true -> eq (lst_mem x (lst_union y z)) true.\nProof.\n   intros.\n   induction y.\n   - simpl in H. apply Bool.orb_prop in H. destruct H.\n   + simpl. destruct (lst_mem n z) eqn:?.\n      * \n      rewrite mem_union.\n         -- reflexivity.\n         -- rewrite (Nat_beq_eq x n H). assumption.\n      * simpl. rewrite H. reflexivity.\n   + apply IHy in H. simpl. destruct (lst_mem n z).\n      * assumption.\n      * simpl. rewrite H. apply Bool.orb_true_r.\n   - discriminate.\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/goal42.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7966893990884707}}
{"text": "From LF Require Export Logic.\nFrom Coq Require Import Lia.\n\nModule IndProp.\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\n\n(*\n  Definition ev (n : nat) : Prop := even n = true.\n  Defivition Ev (n : nat) : Prop := exists (x : nat), n = double x.\n*)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS (n : nat) (H : ev n) : ev (S (S n)).\n\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\nSearch (nat -> nat).\n\nTheorem ev_double : forall n,\n  ev (Logic.double n).\nProof.\n  intros n.\n  induction n as [| n' H ].\n  - simpl.\n    apply ev_0.\n  - simpl.\n    apply ev_SS.\n    apply H.\nQed.\n\nTheorem ev_inversion : forall (n : nat), \n  ev n -> (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n  intros n [ | n' Hev ].\n  - left. reflexivity.\n  - right. exists n'. split.\n    + reflexivity.\n    + apply Hev.\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'] eqn:EE.\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\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\nTheorem evSS_ev_remember : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  remember (S (S n)) as k eqn:Hk.\n  destruct E as [|n' E'] eqn:EE.\n  - discriminate Hk.\n  - injection Hk as Hk'. rewrite <- Hk'. apply E'.\nQed.\n\nTheorem evSS_ev : forall n, ev (S (S n)) -> ev n.\nProof.\n  intros n H. \n  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\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\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H.\n  inversion H as [| n' E' Heq ].\n  inversion E' as [| n'' E'' Heq' ].\n  apply E''.\nQed.\n\nTheorem ev5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros H.\n  inversion H as [| n E Heq].\n  inversion E as [| n' E' Heq'].\n  inversion E'.\nQed.\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).\nSearch cons.\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 -> 2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\n\nLemma tst : forall n, \n  (exists k, n = Logic.double k) -> (exists k', S (S n) = Logic.double k').\nProof.\n  intros n [k H].\n  exists (S k).\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\nLemma ev_Even_firsttry : forall n,\n  ev n -> Logic.Even n.\nProof.\n  unfold Logic.Even.\n  intros n H.\n  inversion H as [HEq | n' E HEq].\n  - exists O. reflexivity.\n  - apply tst.\n    generalize dependent E. (* Prooving the same theorem *)\nAbort.\n\nInclude Logic.\n\nLemma ev_Even : forall n, ev n -> Even n.\nProof.\n  intros n E.\n  induction E as [| n' E' IH ].\n  - (* E = ev_0 *)\n    unfold Even. 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.\n    unfold Even. exists (S k). simpl. 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.\n  induction Hn as [| n' Hn' H ].\n  - simpl. apply Hm.\n  - simpl. apply ev_SS. apply H.\nQed.\n\n\n\n\n\n\n\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  intros n.\n  split.\n  - intros H'.\n    induction H' as [ | | n m Hn Hn' Hm Hm'].\n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum.\n      * apply Hn'.\n      * apply Hm'.\n  - intros H'.\n    induction H' as [ | n Hn H ].\n    + apply ev'_0.\n    + apply (ev'_sum 2 n ev'_2 H).\nQed.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n + m) -> ev n -> ev m.\nProof.\n  intros n m Hnm Hn.\n  induction Hn as [| n' Hn' H].\n  - simpl in Hnm. apply Hnm.\n  - apply H. simpl in Hnm.\n    remember (S (S (n' + m))) as k eqn:Hk.\n    destruct Hnm as [| nm' Hnm'] eqn:E.\n    + discriminate Hk.\n    + injection Hk as Hk'.\n      rewrite <- Hk'.\n      apply Hnm'.\nQed.\n\n\nLemma es_sum : forall n m, \n  ev (n + m) -> (ev n /\\ ev m) \\/ (~(ev n) /\\ ~(ev m)).\nProof.\n  intros n m H.\n  induction n as [| n' Hn ].\n  - simpl in H.\n    left. split.\n    + apply ev_0.\n    + apply H.\nAbort.\n\nTheorem ev_ev__ev1 : forall n m,\n  ev n -> ev m -> ev (n + m).\nProof.\n  intros n m Hn Hm.\n  induction Hn as [| n' Hn' H].\n  - simpl. apply Hm.\n  - simpl. apply ev_SS. apply H.\nQed.\n\nLemma tst1 : forall n, ev (n + n).\nProof.\n  intros n.\n  induction n as [| n' H'].\n  - simpl. apply ev_0.\n  - simpl. rewrite -> PeanoNat.Nat.add_comm. simpl. apply ev_SS. apply H'.\nQed.\n\nSearch (?a + (?b + ?c) = ?a + ?b + ?c).\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(H: ev (n + m + (n + p))). {\n    apply (ev_ev__ev1 (n + m) (n + p) Hnm Hnp).\n  }\n  rewrite -> PeanoNat.Nat.add_assoc in H.\n  rewrite -> PeanoNat.Nat.add_comm in H.\n  rewrite -> (PeanoNat.Nat.add_comm (n + m) n) in H.\n  rewrite -> PeanoNat.Nat.add_comm in H.\n  rewrite -> (PeanoNat.Nat.add_assoc) in H.\n  rewrite <- (PeanoNat.Nat.add_assoc) in H.\n  apply (ev_ev__ev _ _ H (tst1 n)).\nQed.\n\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.\nProof. apply le_n. Qed.\n\nTheorem test_le2 : 3 <= 6.\nProof. apply le_S. apply le_S. apply le_S. apply le_n. Qed.\n\nTheorem test_le3 : (2 <= 1) -> 2 + 2 = 5.\nProof. intros H. inversion H. inversion H2. Qed.\n\nDefinition lt (n m : nat) := le (S n) m.\nNotation \"m < n\" := (lt m n).\n\nTheorem test_lt1 : 2 < 3.\nProof. unfold lt. apply le_n. Qed.\n\n\nLemma O_lowest : forall n, 0 <= n.\nProof.\n  intros n.\n  induction n as [| n' IH ].\n  - apply le_n.\n  - apply le_S. apply IH.\nQed.\n\nLemma O_split : forall a b, \n  0 = a + b -> a = 0 /\\ b = 0.\nProof.\n  intros a b H.\n  destruct a as [| a'].\n  - destruct b as [| b'].\n    + split. reflexivity. reflexivity.\n    + simpl in H. discriminate H.\n  - simpl in H. discriminate H.\nQed.\n\nLemma m_le_mplus : forall m k, \n  m <= m + k.\nProof.\n  intros m k.\n  induction k as [| k' IH].\n  - rewrite -> PeanoNat.Nat.add_comm. simpl. apply le_n.\n  - rewrite -> PeanoNat.Nat.add_comm.\n    simpl.\n    apply le_S.\n    rewrite -> PeanoNat.Nat.add_comm.\n    apply IH.\nQed.\n\nLemma tst : forall m n, \n  m <= n <-> exists k, n = m + k.\nProof.\n  intros m n.\n  split.\n  {\n    intros Hmn.\n    induction Hmn as [mn | m n Hmn' IH ].\n    - exists O.\n      rewrite -> PeanoNat.Nat.add_comm.\n      reflexivity.\n    - destruct IH as [k IH'].\n      exists (S k).\n      rewrite -> IH'.\n      rewrite -> (PeanoNat.Nat.add_comm m (S k)).\n      simpl.\n      rewrite -> (PeanoNat.Nat.add_comm m k).\n      reflexivity.\n    }\n    {\n      intros [k He].\n      rewrite -> He.\n      apply m_le_mplus.\n    }\nQed.\n\nLemma le_trans : forall m n o, \n  m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hno.\n  destruct (tst m n) as [H1mn H2mn].\n  destruct (tst n o) as [H1no H2no].\n  destruct (H1mn Hmn) as [k1 E1].\n  destruct (H1no Hno) as [k2 E2].\n  rewrite -> E1 in E2.\n  rewrite <- PeanoNat.Nat.add_assoc in E2.\n  rewrite -> tst.\n  exists (k1 + k2).\n  apply E2.\nQed. \n\nTheorem O_le_n : forall n, 0 <= n.\nProof. apply O_lowest. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m Hnm.\n  induction Hnm as [n | n m Hnm' IH].\n  - apply le_n.\n  - apply le_S.\n    apply IH.\nQed.\n\nTheorem n_lower_O_is_O: forall n, n <= 0 -> n = 0.\nProof.\n  intros n H.\n  remember 0 as o.\n  destruct H as [k | x y Hxy].\n  - rewrite -> Heqo.\n    reflexivity.\n  - discriminate Heqo.\nQed.\n\nTheorem Sn_le_m__n_le_m : forall n m,\n  S n <= m -> n <= m.\nProof.\n  intros n m Hsnm.\n  remember (S n) as sn.\n  destruct Hsnm as [nm | n' m' Hnm ].\n  - rewrite -> Heqsn.\n    apply le_S.\n    apply le_n.\n  - apply le_S.\n    destruct (tst n n') as [Htstl Htstr].\n    assert (G: n <= n'). {\n      apply Htstr.\n      exists 1.\n      rewrite -> PeanoNat.Nat.add_comm.\n      simpl.\n      apply Heqsn.\n    }\n    apply (le_trans n n' m').\n    apply G.\n    apply Hnm.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m Hsnsm.\n  rewrite -> tst.\n  assert (H: exists k : nat, m = n + k). {\n    destruct (tst (S n) (S m)) as [Htstl Htstr].\n    simpl in Htstl.\n    destruct (Htstl Hsnsm) as [k G].\n    injection G as G'.\n    exists k.\n    apply G'.\n  }\n  apply H.\nQed.\n\nTheorem Sn_le_Sm__n_le_m' : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m H.\n  remember (S n) as sn eqn:Esn.\n  remember (S m) as sm eqn:Esm.\n  induction H as [n' | n' m' H' IH].\n  - rewrite -> Esn in Esm.\n    injection Esm as G.\n    rewrite -> G.\n    apply (le_n m).\n  - injection Esm as G.\n    rewrite -> G in H'.\n    rewrite -> Esn in H'.\n    apply Sn_le_m__n_le_m.\n    apply H'.\nQed.\n\nTheorem lt_ge_cases : forall n m,\n  n < m \\/ m <= n.\nProof.\n  intros n.\n  induction n as [| n' IHn ].\n  - unfold lt.\n    intros m.\n    induction m as [| m' IHm].\n    + right. apply le_n.\n    + destruct IHm as [IHml | IHmr].\n      * left. apply le_S. apply IHml.\n      * assert (G: m' = 0). {apply n_lower_O_is_O. apply IHmr. }\n        left.\n        rewrite -> G.\n        apply le_n.\n  - unfold lt.\n    intros m.\n    induction m as [| m' IHm].\n    + right. apply O_lowest.\n    + destruct IHm as [IHml | IHmr].\n      * left. \n        apply le_S in IHml.\n        apply IHml.\n      * unfold lt in IHn.\n        destruct (IHn m') as [IHnl | IHnr].\n        -- left. apply n_le_m__Sn_le_Sm. apply IHnl.\n        -- right. apply n_le_m__Sn_le_Sm. apply IHnr.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. apply m_le_mplus. Qed. \n\nTheorem plus_le : forall a b m,\n  a + b <= m -> a <= m /\\ b <= m.\nProof.\n  intros a b m H.\n  assert (G: exists k, m = a + b + k). {\n    destruct (tst (a + b) m) as [Tl Tr].\n    apply (Tl H).\n  }\n  split.\n  - destruct (tst a m) as [Tl Tr].\n    apply Tr.\n    destruct G as [k Hd].\n    exists (b + k).\n    rewrite -> PeanoNat.Nat.add_assoc.\n    apply Hd.\n  - destruct (tst b m) as [Tl Tr].\n    apply Tr.\n    destruct G as [k Hd].\n    exists (a + k).\n    rewrite -> PeanoNat.Nat.add_assoc.\n    rewrite -> (PeanoNat.Nat.add_comm b a).\n    apply Hd.\nQed.\n\nTheorem t: forall n m, n < S m -> S n <= m. \nProof.\n  unfold lt.\n  Admitted.\n\nTheorem le_symm_fw : forall n m p, n + m <= n + p -> m <= p.\nProof.\n  intros n.\n  induction n as [| n' IH ].\n  - simpl. intros m p H. apply H.\n  - intros m p. simpl. intros H. \n    apply (Sn_le_Sm__n_le_m (n' + m) (n' + p)) in H.\n    apply IH.\n    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.\n  induction n as [| n' IH ].\n  - simpl. intros m p q H.\n    left. apply O_lowest.\n  - simpl. intros m p q H.\n    assert (G' : n' <= p \\/ S m <= q). {\n      apply IH.\n      rewrite -> (PeanoNat.Nat.add_comm n' (S m)).\n      simpl.\n      rewrite -> (PeanoNat.Nat.add_comm m n').\n      apply H.\n    }\n    destruct G' as [G'l | G'r].\n    + destruct G'l as [n' | n' p HH].\n      * assert (H0: S m <= q). {\n          apply (le_symm_fw n').\n          rewrite -> (PeanoNat.Nat.add_comm n' (S m)).\n          simpl.\n          rewrite -> (PeanoNat.Nat.add_comm m n').\n          apply H.\n        }\n        right.\n        apply Sn_le_m__n_le_m.\n        apply H0.\n      * left.\n        apply n_le_m__Sn_le_Sm.\n        apply HH.\n    + right. apply Sn_le_m__n_le_m. apply G'r.\nQed.\n\nTheorem plus_le_compat_l : forall n m p,\n  n <= m -> p + n <= p + m.\nProof.\n  intros n m p.\n  induction p as [| p' IH ].\n  - simpl. intros H. apply H.\n  - intros H. simpl. \n    apply n_le_m__Sn_le_Sm.\n    apply IH.\n    apply H.\nQed.\n\nTheorem plus_le_compat_r : forall n m p,\n  n <= m -> n + p <= m + p.\nProof.\n  intros n m p.\n  rewrite -> (PeanoNat.Nat.add_comm n p).\n  rewrite -> (PeanoNat.Nat.add_comm m p).\n  apply plus_le_compat_l.\nQed.\n\nTheorem le_plus_trans : forall n m p,\n  n <= m ->\n  n <= m + p.\nProof.\n  intros n m p.\n  induction p as [| p' IH].\n  - intros H. rewrite -> (PeanoNat.Nat.add_comm m 0). simpl. apply H.\n  - intros H.\n    rewrite -> (PeanoNat.Nat.add_comm m (S p')).\n    simpl.\n    apply le_S.\n    rewrite -> (PeanoNat.Nat.add_comm p' m).\n    apply IH.\n    apply H.\nQed.\n\nTheorem n_lt_m__n_le_m : forall n m,\n  n < m ->\n  n <= m.\nProof.\n  intros n m.\n  unfold lt.\n  apply Sn_le_m__n_le_m.\nQed.\n\n\nLemma less_one: forall a b,  S a <= b -> 1 <= b.\nProof.\n  intros a b.\n  induction a as [| a' IH ].\n  - intros H. apply H.\n  - intros H. \n    apply Sn_le_m__n_le_m in H.\n    apply IH.\n    apply H.\nQed.\n\nLemma nothing_less_O : forall n, \n  S n <= 0 -> False.\nProof.\n  intros n H.\n  remember (S n) as k.\n  remember 0 as o.\n  destruct H as [n' | n' o'].\n  - rewrite -> Heqo in Heqk.\n    discriminate Heqk.\n  - discriminate Heqo.\nQed.\n\nTheorem plus_lt : forall a b m,\n  a + b < m -> a < m /\\ b < m.\nProof.\n  intros a.\n  unfold lt.\n  induction a as [| a' IH ].\n  - intros b m H.\n    simpl in H.\n    split.\n    + apply (less_one b). apply H.\n    + apply H.\n  - intros b m H.\n    destruct m as [| m'].\n    + exfalso.\n      apply (nothing_less_O (S a' + b) H).\n    + destruct m' as [| m''].\n      * apply Sn_le_Sm__n_le_m' in H.\n        simpl in H.\n        exfalso.\n        apply (nothing_less_O (a' + b) H).\n      * apply Sn_le_Sm__n_le_m' in H.\n        simpl in H.\n        destruct (IH b (S m'') H) as [IHl IHr].\n        split.\n        -- apply n_le_m__Sn_le_Sm.\n           apply IHl.\n        -- apply le_S.\n           apply IHr.\nQed.\n\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intros n.\n  induction n as [| n' IHn ].\n  - intros m H. apply O_lowest.\n  - destruct m as [| m'].\n    + intros H.\n      simpl in H. discriminate H.\n    + intros H. simpl in H.\n      apply n_le_m__Sn_le_Sm.\n      apply IHn.\n      apply H.\nQed.\n\nLemma leb_refl : forall n,\n  n <=? n = true.\nProof.\n  intros n.\n  induction n as [| n' IH ].\n  - reflexivity.\n  - simpl. apply IH.\nQed.\n\nLemma leb_s_rev : forall n m,\n  S n <=? m = true -> n <=? m = true.\nProof.\n  intros n m H.\n  generalize dependent n.\n  induction m as [| m' IHm ].\n  - intros n H. simpl in H. discriminate H.\n  - intros n H. simpl in H.\n    destruct n as [| n'] eqn: En.\n    + reflexivity.\n    + simpl.\n      apply (IHm n').\n      apply H.\nQed.\n\nLemma leb_s : forall n m,\n  n <=? m = true -> n <=? S m = true.\nProof.\n  intros n m H.\n  generalize dependent m.\n  induction n as [| n' IHn ].\n  - reflexivity.\n  - destruct m as [| m'] eqn: Em.\n    + intros H. simpl in H. discriminate H.\n    + simpl. intros H.\n      apply (IHn m').\n      apply H.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m -> n <=? m = true.\nProof.\n  intros n m H.\n  induction m as [| m' IHm ].\n  - apply n_lower_O_is_O in H.\n    rewrite -> H.\n    reflexivity.\n  - remember (S m') as sm' eqn:Hsm.\n    destruct H as [n | n m H'].\n    + apply leb_refl.\n    + injection Hsm as Hsm'.\n      rewrite <- Hsm' in IHm.\n      apply IHm in H'.\n      apply leb_s.\n      apply H'.\nQed.\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  intros n m. split.\n  - apply leb_complete.\n  - 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 n m o Hnm Hmo.\n  rewrite -> leb_iff in Hnm.\n  rewrite -> leb_iff in Hmo.\n  rewrite -> leb_iff.\n  apply (le_trans n m o Hnm Hmo).\nQed.\n\nEnd Playground.\n\n\nInductive total_relation : nat -> nat -> Prop :=\n  | total n m : total_relation n m.\n\nExample total_ex: total_relation 9 666.\nProof. apply total. Qed.\n\n\nInductive empty_relation : nat -> nat -> Prop :=.\nExample empty_ex: empty_relation 1 1.\nProof. Abort.\n\n\nModule R.\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.\n\nLemma exr1: R 1 1 2.\nProof. apply c3. apply c2. apply c1. Qed. \n\nLemma exr2: R 2 2 6.\nProof. apply c3. apply c2. Abort.\n\nSearch (nat -> nat -> nat).\nDefinition fR : nat -> nat -> nat := PeanoNat.Nat.add.\n\n\nTheorem R_equiv_fR : forall m n o, \n  R m n o <-> fR m n = o.\nProof.\n  intros m n o.\n  split.\n  - intros H.\n    induction H as [| m n o H2 IH2 | m n o H3 IH3 ].\n    + reflexivity.\n    + simpl. rewrite -> IH2. reflexivity.\n    + unfold fR. \n      unfold fR in IH3. \n      rewrite -> PeanoNat.Nat.add_comm. \n      simpl. \n      rewrite -> PeanoNat.Nat.add_comm. \n      rewrite -> IH3. \n      reflexivity.\n  - intros H.\n    generalize dependent n.\n    generalize dependent o.\n    induction m as [| m' IHm ].\n    + intros o n H.\n      simpl in H.\n      rewrite -> H.\n      assert (R_0_n_n : forall n, R 0 n n). {\n        intros k.\n        induction k as [| k' IHk ].\n        - apply c1.\n        - apply c3. apply IHk.\n      }\n      apply R_0_n_n.\n    + intros o n H.\n      simpl in H.\n      unfold fR in IHm.\n      unfold fR in H.\n      destruct o as [| o'].\n      * discriminate H.\n      * apply c2.\n        apply IHm.\n        injection H as H'.\n        apply H'.\nQed.\n\nEnd R.\n\n\n\nModule Sublist.\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | empty l                     : subseq nil        l\n  | add   a s l (H: subseq s l) : subseq (cons a s) (cons a l)\n  | add_l a s l (H: subseq s l) : subseq s          (cons a l)\n.\n\nNotation \"a $ b\" := (subseq a b)\n                    (at level 60).\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  intros l.\n  induction l as [| hl tl IHl].\n  - apply empty.\n  - apply (add hl). apply IHl.\nQed.\n\nTheorem subseq_app : forall (s l l' : list nat),\n  subseq s l ->\n  subseq s (l ++ l').\nProof.\n  intros s l l' H.\n  generalize dependent s.\n  generalize dependent l'.\n  induction l as [| hl tl IHl ].\n  - intros l' s H. simpl.\n    remember [] as k eqn:Ek. \n    destruct H as [l | a s l | a s l].\n    + apply empty.\n    + discriminate Ek.\n    + discriminate Ek.\n  - remember (hl :: tl) as k eqn:Ek.\n    intros l' s H.\n    rewrite -> Ek.\n    simpl.\n    destruct H as [lh | ah sh lh H' | ah sh lh H'].\n    + apply empty.\n    + \n      injection Ek as Ea Es.\n      rewrite -> Ea.\n      apply add.\n      apply IHl.\n      rewrite <- Es.\n      apply H'.\n    + injection Ek as Ea Es.\n      apply add_l.\n      apply IHl.\n      rewrite <- Es.\n      apply H'.\nQed.\n\nLemma ht_subset_then_t_subset : forall a s l, \n  subseq (a :: s) l -> subseq s l.\nProof.\n  intros a s l H.\n  remember (a :: s) as k eqn:Ek.\n  induction H as [l | a' s' l' H' IH | a' s' l' H' IH].\n  - discriminate Ek.\n  - injection Ek as Eka Eks.\n    apply add_l.\n    rewrite -> Eks in H'.\n    apply H'.\n  - apply add_l.\n    apply IH.\n    apply Ek.\nQed.\n\nLemma false_sublist: forall s, subseq s [ ] -> s = [ ].\nProof.\n  intros s H.\n  remember [ ] as k eqn:Ek.\n  destruct H as [ l | a s' l | a s' l].\n  - rewrite -> Ek. reflexivity.\n  - discriminate Ek.\n  - discriminate Ek.\nQed.\n\nLemma destruct_second_cons : forall a h t, \n  subseq a (h :: t) -> \n  (exists at', a = h :: at' /\\ subseq at' t)\n  \\/\n  subseq a t.\nProof.\n  intros a h t H.\n  remember (h :: t) as k eqn:Ek.\n  destruct a as [| ah at' ] eqn:Ea.\n  - right. apply empty.\n  - destruct H as [l | hH sH lH H' | hH sH lH H' ].\n    + right. apply empty.\n    + left.\n      exists sH.\n      injection Ek as Ek1 Ek2.\n      split.\n      * rewrite -> Ek1. reflexivity.\n      * rewrite <- Ek2. apply H'.\n    + right.\n      injection Ek as Ek1 Ek2.\n      rewrite <- Ek2.\n      apply H'.\nQed.\n\n\nLemma elim_same_head : forall h a b, (h :: a) $ (h :: b) -> a $ b.\nProof.\n  intros h a b H.\n  remember (h :: a) as ra eqn:Era.\n  remember (h :: b) as rb eqn:Erb.\n  induction H as [l | h' s l H' IH | h' s l H' IH].\n  - discriminate Era.\n  - injection Era as Era1 Era2.\n    injection Erb as Erb1 Erb2.\n    rewrite <- Erb2.\n    rewrite <- Era2.\n    apply H'.\n  - rewrite -> Era in H'.\n    injection Erb as Erb1 Erb2.\n    rewrite -> Erb2 in H'.\n    apply ht_subset_then_t_subset in H'.\n    apply H'.\nQed.\n\n\nTheorem subseq_trans_h2: forall a b c,\n  a $ b -> b $ c -> a $ c.\nProof.\n  intros a b c H1 H2.\n  generalize dependent a.\n  induction H2 as [l | h s l H2' IH | h s l H2' IH ].\n  - intros a H1.\n    apply false_sublist in H1.\n    rewrite -> H1.\n    apply empty.\n  - intros a H1.\n    assert (G: (exists at', a = h :: at' /\\ subseq at' s) \\/ subseq a s). {\n      apply destruct_second_cons.\n      apply H1.\n    }\n    destruct G as [[atail [HAeq Hatail]] | Has ].\n    + rewrite -> HAeq.\n      apply add.\n      rewrite -> HAeq in H1.\n      apply elim_same_head in H1.\n      apply IH.\n      apply H1.\n    + apply add_l.\n      apply IH.\n      apply Has.\n  - intros a H1.\n    apply add_l.\n    apply IH.\n    apply H1.\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  apply subseq_trans_h2.\nQed.\n\nEnd Sublist.\n\nInductive 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? *)\nTheorem tr1: R 2 [1;0].\nProof. apply c2. apply c2. apply c1. Qed.\n\nTheorem tr2: R 1 [1;2;1;0].\nProof. apply c3. apply c2. apply c3. apply c3. apply c2. apply c2. apply c2. apply c1. Qed.\n\nTheorem tr3: R 6 [3;2;1;0].\nProof. Abort.\n\n\nModule RegExp.\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*)\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\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof. apply MChar. Qed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2] _).\n  - apply MChar.\n  - apply MChar.\nQed.\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. \n(*  remember ([1; 2]) as k eqn:Ek.\n\n  destruct H as [| c | s1 re1 s2 re2 h1 h2 | s1 re1 re2 h1 | re1 s2 re2 h2 | re | s1s2 h1 h2] eqn:E.\n  - \n*)\n  inversion H.\nQed.\n\nFixpoint reg_exp_of_list {T} (l : list T) : reg_exp T:=\n  match l with\n  | [ ]     => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n\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\nSearch (?s ++ [] = ?s).\nLemma MStar1 : forall T s (re : reg_exp T) ,\n    s =~ re -> s =~ Star re.\nProof.\n  intros T s re H.\n  assert (G: s ++ [] =~ Star re). {\n   apply (MStarApp s [] re).\n   - apply H.\n   - apply MStar0.\n  }\n  rewrite -> List.app_nil_r in G.\n  apply G.\nQed.\n\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros T s.\n  unfold not.\n  intros H.\n  inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s re1 re2 H.\n  destruct H as [Hl | Hr].\n  - apply (MUnionL).\n    apply Hl.\n  - apply (MUnionR).\n    apply Hr.\nQed.\n\n(* \n  The next lemma is stated in terms of the fold function from the Poly chapter: \n  If ss : list (list T) represents a sequence of strings s1, ..., sn, then fold \n  app ss [] is the result of concatenating them all together.\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\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold (@app T) ss [] =~ Star re.\nProof.\n  intros T ss.\n  induction ss as [| h t IH].\n  - simpl. intros re H. apply MStar0.\n  - simpl. intros re H.\n    apply (MStarApp h (fold (@app T) t [ ])).\n    + apply H. left. reflexivity.\n    + apply IH.\n      intros l H'.\n      apply H.\n      right.\n      apply H'.\nQed.\n\nTheorem reg_exp_of_list_refl: forall T (s: list T),\n  s =~ reg_exp_of_list s.\nProof.\n  intros T s.\n  induction s as [| h t IH ].\n  - simpl. apply MEmpty.\n  - simpl.\n    assert (G: h :: t = [h] ++ t). {\n      reflexivity.\n    }\n    rewrite -> G.\n    apply MApp.\n    + apply MChar.\n    + apply IH.\nQed.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  intros T s1 s2.\n  split.\n  - generalize dependent s1.\n    induction s2 as [| h t IH ].\n    + intros s1 H.\n      simpl in H. \n      inversion H.\n      reflexivity.\n    + intros s1 H.\n      simpl in H.\n      inversion H. (* Only one branch with App *)\n      inversion H3.\n      simpl.\n      rewrite -> (IH s2 H4).\n      reflexivity.\n  - intros H.\n    rewrite <- H.\n    apply reg_exp_of_list_refl.\nQed.\n\n\nFixpoint re_chars {T} (re : reg_exp T) : list T :=\n  match re with\n  | EmptySet      => []\n  | EmptyStr      => []\n  | Char x        => [x]\n  | App re1 re2   => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re       => re_chars re\n  end.\n\nTheorem in_re_match : forall T (s : list T) (re : reg_exp T) (x : T),\n  s =~ re ->\n  In x s ->\n  In x (re_chars re).\nProof.\n  intros T s re x H Hin.\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  *)\n    simpl in Hin. exfalso. apply Hin.\n  - (* MChar *)\n    simpl. simpl in Hin. apply Hin.\n  - (* MApp *)\n    simpl. rewrite In_app_iff. \n    rewrite In_app_iff in Hin. \n    destruct Hin as [Hinl | Hinr]. \n    + left.  apply IH1. apply Hinl.\n    + right. apply IH2. apply Hinr.\n  - (* MUnionL *)\n    simpl. rewrite In_app_iff. left. apply IH. apply Hin.\n  - (* MUnionR *)\n    simpl. rewrite In_app_iff. right. apply IH. apply Hin.\n  - (* MStar0 *)\n    simpl in Hin. exfalso. apply Hin.\n  - (* MStarApp *)\n    rewrite In_app_iff in Hin. \n    destruct Hin as [Hinl | Hinr].\n    + simpl. apply IH1. apply Hinl.\n    + simpl. apply IH2. apply Hinr.\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\nSearch (orb ?a ?b = orb ?b ?a).\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros T re.\n  split.\n  - intros [s H].\n    induction H 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  *)\n      simpl. reflexivity.\n    + (* MChar *)\n      simpl. reflexivity.\n    + (* MApp *)\n      simpl. rewrite -> IH1. rewrite -> IH2. reflexivity.\n    + (* MUnionL *)\n      simpl. rewrite -> IH. reflexivity.\n    + (* MUnionR *)\n      simpl. rewrite -> IH. rewrite Bool.orb_comm. reflexivity.\n    + (* MStar0 *)\n      reflexivity. \n    + (* MStarApp *)\n      reflexivity.\n  - intros H.\n    induction re as [|\n                    | c\n                    | re1 IH1 re2 IH2\n                    | re1 IH1 re2 IH2\n                    | r IH ].\n    + (* EmptySet *)\n      simpl in H. discriminate H.\n    + (* EmptyStr *)\n      simpl in H. exists [ ]. apply MEmpty.\n    + (* Char (c : T) *)\n      exists [c]. apply MChar.\n    + (* App (r1 r2 : reg_exp T) *)\n      simpl in H.\n      destruct (re_not_empty re1).\n      -- destruct (re_not_empty re2).\n         ++ simpl in H.\n            destruct (IH1 H) as [s1 H'1].\n            destruct (IH2 H) as [s2 H'2].\n            exists (s1 ++ s2).\n            apply (MApp _ _ _ _ H'1 H'2).\n         ++ discriminate H.\n      -- discriminate H.\n    + (* Union (r1 r2 : reg_exp T) *)\n      simpl in H.\n      destruct (re_not_empty re1).\n      -- destruct (IH1 H) as [s H'].\n         exists s.\n         apply (MUnionL _ _ _ H').\n      -- destruct (re_not_empty re2).\n         ++ destruct (IH2 H) as [s H'].\n            exists s.\n            apply (MUnionR _ _ _ H').\n         ++ discriminate H.\n    + (* Star (r : reg_exp T). *)\n      exists [].\n      apply MStar0.\nQed.\n\n\n\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\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' eqn: Ere'.\n  generalize dependent s2.\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  - (* MEmpty *) discriminate.\n  - (* MChar *) discriminate.\n  - (* MApp *) discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n  - (* MStar0 *)\n    injection Ere' as Heqre''. intros s H. apply H.\n  - (* MStarApp *)\n    injection Ere' 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\nLemma Star_lemm: forall T (s1 s2 : list T) re,\n  s1 =~ re -> s2 =~ Star re -> (s1 ++ s2) =~ Star re.\nProof.\n  intros T s1 s2 re H1 H2.\n  apply (MStarApp s1 _ _ H1) in H2.\n  apply H2.\nQed.\n\nSearch (?l ++ [] = ?l).\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 T) ss []) /\\ (forall s', In s' ss -> s' =~ re).\nProof.\n  intros T s re H.\n  remember (Star re) 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                  | re1\n                  | s1 s2 re1 H1 IH1 H2 IH2 ].\n  - discriminate Ek.\n  - discriminate Ek.\n  - discriminate Ek.\n  - discriminate Ek.\n  - discriminate Ek.\n  - exists [].\n    simpl.\n    split.\n    + reflexivity.\n    + intros s' F. exfalso. apply F.\n  - destruct (IH2 Ek) as [ss [H'1 H'2]]. (* Get list of matched strings from Inductive Hypo *)\n    exists ([s1] ++ ss).\n    split.\n    + simpl.\n      rewrite <- H'1.\n      reflexivity.\n    + intros s'.\n      simpl. \n      intros G.\n      destruct G as [G1 | G2].\n      * rewrite <- G1.\n        injection Ek as Ek'.\n        rewrite <- Ek'.\n        apply H1.\n      * apply H'2.\n        apply G2.\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 =>\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\nLemma pumping_constant_ge_1 : forall T (re : reg_exp T),\n    pumping_constant re >= 1.\nProof.\nAdmitted.\n(*\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*)\n\nLemma pumping_constant_0_false : 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\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\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\nSearch (?l ++ [] = ?l).\nSearch (length (?s1 ++ ?s2) = length (?s1) + length (?s2)).\nSearch (?a + ?b <= ?c + ?d -> ?a <= ?c \\/ ?b <= ?d).\nSearch (?a + ?b <= ?c -> ?a <= ?c /\\ ?b <= ?c).\nSearch (?a <= ?b + ?c -> ?a <= ?b /\\ ?a <= ?c).\n(*Search (plus_le).\nSearch (le_plus).*)\nLemma plus_le: forall a b c, a + b <= c -> a <= c /\\ b <= c.\nProof. Admitted.\n\nLemma le_plus: forall a b c, a <= b + c -> a <= b /\\ a <= c.\nProof. Admitted.\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.\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  - (* MChar *)\n    exists [].\n    simpl in H.\n    inversion H.\n    inversion H1.\n  - (* MApp *)\n    simpl.\n    intros H.\n    rewrite -> List.app_length in H.\n    destruct (PeanoNat.Nat.add_le_cases _ _ _ _ H) as [Hl | Hr ].\n    + destruct (IH1 Hl) as [s2' [s3' [s4' [G1 [G2 G3]]]]].\n      exists s2'.\n      exists s3'.\n      exists (s4' ++ s2).\n      split.\n      * rewrite -> G1.\n        rewrite <- app_assoc.\n        rewrite <- app_assoc.\n        reflexivity.\n      * split.\n        -- apply G2.\n        -- intros m.\n           rewrite -> app_assoc.\n           rewrite -> app_assoc.\n           rewrite <- (app_assoc _ s2' (napp m s3') s4').\n           apply MApp.\n           ++ apply (G3 m).\n           ++ apply Hmatch2.\n    + destruct (IH2 Hr) as [s2' [s3' [s4' [G1 [G2 G3]]]]].\n      exists (s1 ++ s2').\n      exists s3'.\n      exists s4'.\n      split.\n      * rewrite -> G1.\n        rewrite <- app_assoc.\n        reflexivity.\n      * split.\n        -- apply G2.\n        -- intros m.\n           rewrite <- app_assoc.\n           apply MApp.\n           ++ apply Hmatch1.\n           ++ apply (G3 m).\n  - (* MUnionL *) \n    simpl.\n    intros H.\n    destruct (plus_le _ _ _ H) as [Hre1 Hre2].\n    destruct (IH Hre1) as [s2' [s3' [s4' [G1 [G2 G3]]]]].\n    exists s2'.\n    exists s3'.\n    exists s4'.\n    split.\n    + apply G1.\n    + split.\n      * apply G2.\n      * intros m.\n        apply MUnionL.\n        apply G3.\n  - (* MUnionR *)\n    simpl.\n    intros H.\n    destruct (plus_le _ _ _ H) as [Hre1 Hre2].\n    destruct (IH Hre2) as [s2' [s3' [s4' [G1 [G2 G3]]]]].\n    exists s2'.\n    exists s3'.\n    exists s4'.\n    split.\n    + apply G1.\n    + split.\n      * apply G2.\n      * intros m.\n        apply MUnionR.\n        apply G3.\n  - (* MStar0 *)\n    intros H.\n    simpl in H.\n    destruct (pumping_constant_ge_1 T re).\n    + inversion H.\n    + inversion H.\n  - (* MStarApp *)\n    simpl.\n    intros H.\n    rewrite -> List.app_length in H.\n    destruct (le_plus _ _ _ H) as [Hl Hr ].\n    destruct (IH1 Hl) as [s2' [s3' [s4' [G1 [G2 G3]]]]].\n    destruct (IH2 Hr) as [s2'2 [s3'2 [s4'2 [G12 [G22 G32]]]]].\n    exists s2'.\n    exists s3'.\n    exists (s4' ++ s2).\n    split.\n    + rewrite -> G1.\n      rewrite <- (app_assoc _).\n      rewrite <- (app_assoc _).\n      reflexivity.\n    + split.\n      * apply G2.\n      * intros m.\n        rewrite -> (app_assoc _).\n        rewrite -> (app_assoc _).\n        rewrite <- (app_assoc _ s2').\n        apply MStarApp.\n        -- apply (G3 m).\n        -- apply Hmatch2.\nQed.\n\nLemma pumping : forall T (re : reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\ s2 <> [] \n      /\\ length s1 + length s2 <= pumping_constant re /\\ forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - (* MEmpty *)\n    simpl. intros contra. inversion contra.\nAdmitted.\n\n\nEnd Pumping.\n\nEnd RegExp.\n\n\nInductive reflect (P : Prop) : bool -> Prop :=\n  | ReflectT (H : P) : reflect P true\n  | ReflectF (H : ~ P) : reflect P false.\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros P b H. destruct b 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.\n  destruct H as [p | p].\n  - split.\n    + intros P'. reflexivity.\n    + intros T. apply p.\n  - split.\n    + intros P'. exfalso. apply (p P').\n    + intros F. discriminate F.\nQed.\n\nLemma eqb_eq : forall m n, n = m <-> (n =? m) = true.\nProof.\n  intros m n.\n  split.\n  - intros H.\n    rewrite -> H.\n    assert(G: forall n, (n =? n) = true). {\n      intros k.\n      induction k as [| k' IH].\n      - reflexivity.\n      - simpl. rewrite -> IH. reflexivity.\n    }\n    apply G. \n  - generalize dependent m.\n    induction n as [| n' IH].\n    + destruct m as [| m'].\n      * simpl. intros H. reflexivity.\n      * simpl. intros H. discriminate H.\n    + destruct m as [| m'].\n      * simpl. intros H. discriminate H.\n      * simpl. intros H. rewrite -> (IH m' H). reflexivity.\nQed.\n\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\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\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\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 H.\n  induction l as [| h t IH ].\n  - simpl in H. simpl. unfold not. intros F. apply F.\n  - simpl.\n    simpl in H.\n    destruct (eqbP n h) as [Heq | Heq].\n    + simpl in H.\n      discriminate H.\n    + simpl in H.\n      apply IH in H.\n      unfold not.\n      intros G.\n      destruct G as [G1 | G2].\n      * apply Heq.\n        symmetry.\n        apply G1.\n      * apply H.\n        apply G2.\nQed.\n\n\nModule Stutter.\nInductive nostutter {X:Type} : list X -> Prop :=\n  | empty : nostutter nil\n  | one x : nostutter [x]\n  | add n x t (Hneq : n <> x) (Hh : nostutter (x :: t)) : nostutter (n :: x :: t)\n.\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof. repeat constructor; apply eqb_neq; auto. Qed.\n\nExample test_nostutter_2: nostutter (@nil nat).\nProof. repeat constructor; apply eqb_neq; auto. Qed.\n\nExample test_nostutter_3: nostutter [5].\nProof. 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. Qed.\nEnd Stutter.\n\n\nModule InOrderMerged.\nInductive in_order_merged {X:Type} : list X -> list X -> list X -> Prop :=\n  | empty : in_order_merged nil nil nil\n  | addl n l1 l2 lr (H: in_order_merged l1 l2 lr) : in_order_merged (n :: l1) l2 (n :: lr)\n  | addr n l1 l2 lr (H: in_order_merged l1 l2 lr) : in_order_merged l1 (n :: l2) (n :: lr)\n.\n\nExample ex1 : in_order_merged [1;6;2] [4;3] [1;4;6;2;3].\nProof. apply addl. apply addr. apply addl. apply addl. apply addr. apply empty. Qed.\n\nFixpoint elem_of (l: list nat) (x : nat) : bool :=\n  match l with\n  | nil => false\n  | cons h t => if h =? x then true else elem_of t x\n  end.\n\nLemma same_start_list: forall T (h : T) (t t': list T), t = t' -> h :: t = h :: t'.\nProof.\n  intros T h t t' H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nLemma add_false_simpl: forall P, (False \\/ P) -> P.\nProof.\n  intros P H.\n  destruct H as [l | r].\n  - exfalso. apply l.\n  - apply r.\nQed.\n\n\nLemma inP : forall (x : nat) (l : list nat), \n  reflect (In x l) (elem_of l x).\nProof.\n  intros x l.\n  induction l as [| h t H].\n  - simpl. apply ReflectF. unfold not. intros F. apply F.\n  - simpl. \n    destruct (eqbP h x) as [Hhx|Hhx].\n    + apply ReflectT.\n      left. apply Hhx.\n    + unfold not in Hhx.\n      destruct H.\n      * apply ReflectT. right. apply H.\n      * apply ReflectF. unfold not.\n        intros HF.\n        destruct HF as [HFl|HFr].\n        -- apply Hhx. apply HFl.\n        -- apply H. apply HFr.\nQed.\n\nLemma neg_app: forall A B, (~ (A \\/ B)) <-> ~A /\\ ~B.\nProof.\n  intros A B.\n  split.\n  * intros H.\n    split.\n    - unfold not in H.\n      unfold not.\n      intros AH.\n      apply H.\n      apply (or_intro_l A _ AH).\n    - unfold not in H.\n      unfold not.\n      intros BH.\n      apply H.\n      apply (or_intro_r A B BH).\n  * intros [Hl Hr].\n    unfold not.\n    intros Hor.\n    destruct Hor as [Horl | Horr].\n    - apply Hl. apply Horl.\n    - apply Hr. apply Horr.\nQed.\n\nTheorem sum_nas_no_item: forall A (x: A) l1 l2 lr, \n  in_order_merged l1 l2 lr -> (~ In x l1 /\\ ~ In x l2 ) -> (~ (In x lr)).\nProof.\n  intros A x l1 l2 lr H1 H2.\n  induction H1 as [| n l1' l2' lr' H1' IH| n l1' l2' lr' H1' IH].\n  - destruct H2 as [H2l H2r].\n    apply H2l.\n  - simpl. apply neg_app.\n    simpl in H2. rewrite -> neg_app in H2.\n    destruct H2 as [[Hneq Hxl1] Hxl2].\n    split.\n    + apply Hneq.\n    + apply IH.\n      split.\n      * apply Hxl1.\n      * apply Hxl2.\n  - simpl. apply neg_app.\n    simpl in H2. rewrite -> neg_app in H2.\n    destruct H2 as [Hxl1 [Hneq Hxl2]].\n    split.\n    + apply Hneq.\n    + apply IH.\n      split.\n      * apply Hxl1.\n      * apply Hxl2.\nQed.\n\nLemma elem_of_h: forall h t, \n  elem_of (h :: t) h = true.\nProof.\n  intros h t.\n  simpl.\n  destruct (eqbP h h) as [Hr | Hr].\n  - reflexivity.\n  - exfalso. apply Hr. reflexivity.\nQed.\n\nLemma n_eq_n: forall n, n =? n = true.\nProof.\n  intros n.\n  destruct (eqbP n n) as [Hl | Hr].\n  - reflexivity.\n  - exfalso. apply Hr. reflexivity.\nQed.\n\nLemma if_with_same_res: forall A (b : bool) (r: A), (if b then r else r) = r.\nProof.\n  intros A b r.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma add_existed: forall n l, \n  In n l -> (forall x, elem_of (n :: l) x = elem_of l x).\nProof.\n  intros n l H x.\n  simpl.\n  destruct (eqbP n x) as [Hl | Hr].\n  - rewrite <- Hl.\n    destruct (inP n l) as [Hl' | Hr'].\n    + reflexivity.\n    + exfalso. apply Hr'. apply H.\n  - reflexivity.\nQed.\n\nLemma filter_lemm: forall n l m, \n  In n l -> filter (elem_of (n :: l)) m = filter (elem_of l) m.\nProof.\n  intros n l m H.\n  simpl.\n  induction m as [| mh mt IH].\n  - reflexivity.\n  - simpl.\n    destruct (eqbP n mh) as [Hl | Hr].\n    + rewrite <- Hl.\n      destruct (inP n l) as [Hl' | Hr'].\n      * rewrite <- IH. reflexivity.\n      * exfalso. apply Hr'. apply H.\n    + rewrite -> IH. reflexivity.\nQed.\n  \nLemma tst: forall n p l, ~ In n l -> filter (fun x : nat => if n =? x then true else p x) l = filter p l.\nProof.\n  intros n p l H.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl.\n    destruct (eqbP n h).\n    + exfalso. apply H. simpl. left. rewrite -> H0. reflexivity.\n    + assert (G: ~ In n t). {\n        simpl in H.\n        apply neg_app in H.\n        destruct H as [Hl Hr].\n        apply Hr.\n      }\n      rewrite -> (IH G).\n      reflexivity.\nQed.\n\nLemma exclusion_rev: forall A (l1 l2 : list A), \n  (forall x, In x l1 -> ~(In x l2)) -> (forall x, In x l2 -> ~(In x l1)).\nProof.\n  intros A l1 l2 H x H2.\n  unfold not.\n  intros G.\n  apply (H x G).\n  apply H2.\nQed.\n\nTheorem filter_preserve_ord: forall l1 l2 lr, \n  in_order_merged l1 l2 lr -> (forall x, In x l1 -> ~(In x l2)) -> filter (elem_of l1) lr = l1.\nProof.\n  intros l1 l2 lr H Hexcl.\n  induction H as [| n l1' l2' lr' H' IH| n l1' l2' lr' H' IH].\n  - reflexivity.\n  - destruct (inP n l1') as [Hl | Hr].\n    + rewrite -> (filter_lemm _ _ _ Hl).\n      simpl.\n      assert (G: elem_of l1' n = true). {\n        destruct (inP n l1').\n        - reflexivity.\n        - exfalso. apply H. apply Hl.\n      }\n      rewrite -> G.\n      assert (G': forall x : nat, In x l1' -> ~ In x l2'). {\n        intros x HIn.\n        apply Hexcl.\n        simpl. right. apply HIn.\n      }\n      rewrite -> (IH G').\n      reflexivity.\n    + simpl.\n      rewrite -> n_eq_n.\n      assert (Hnl2': ~ In n l2'). {\n        apply Hexcl.\n        simpl. left. reflexivity.\n      }\n      assert (Hnlr': ~ In n lr'). {\n        apply (sum_nas_no_item _ _ _ _ _ H').\n        split. apply Hr. apply Hnl2'.\n      }\n      rewrite -> (tst n (elem_of l1') lr' Hnlr').\n      assert (G: forall x : nat, In x l1' -> ~ In x l2'). {\n        intros x H.\n        apply Hexcl.\n        simpl.\n        right. apply H.\n      }\n      rewrite -> (IH G).\n      reflexivity.\n  - simpl.\n    destruct (inP n l1') as [Hl | Hr].\n    + apply Hexcl in Hl.\n      simpl in Hl.\n      rewrite -> neg_app in Hl.\n      destruct Hl as [Hll Hlr].\n      exfalso. apply Hll. reflexivity.\n    + assert (G: forall x : nat, In x l1' -> ~ In x l2'). {\n        intros x H.\n        apply Hexcl in H.\n        simpl in H.\n        rewrite -> neg_app in H.\n        destruct H as [Hl' Hr'].\n        apply Hr'.\n      }\n      rewrite -> (IH G).\n      reflexivity.\nQed.\n\nEnd InOrderMerged.\n\n(*\nA different way to characterize the behavior of filter goes like this: \n  Among all subsequences of l with the property that test \n  evaluates to true on all their members, filter test l is \n  the longest. Formalize this claim and prove it. \n*)\n\n\nModule Pal.\n\nInductive pal {X:Type} : list X -> Prop :=\n  | empty : pal nil \n  | one (c : X) : pal [c]\n  | step (c: X) (l: list X) (H: pal l): pal (c :: l ++ [c])\n.\n\nExample pal_e1: pal [1; 2; 3; 3; 2; 1].\nProof. Admitted.\n\nTheorem pal_app_rev: forall {X:Type} (l: list X), \n  pal (l ++ rev l).\nProof.\n  intros X l.\n  induction l as [|h t IH].\n  - simpl. apply empty.\n  - simpl. \n    assert (G: (h :: t ++ rev t ++ [h]) = (h :: (t ++ rev t) ++ [h])). {\n      rewrite <- (app_assoc ).\n      reflexivity.\n    }\n    rewrite -> G.\n    apply step.\n    apply IH.\nQed.\n\nLemma Geq: forall {X: Type} (l1 l2 l3: list X), \n  l1 = l2 -> l1 ++ l3 = l2 ++ l3.\nProof.\n  intros X l1 l2 l3 H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nLemma Rev_concat: forall {X: Type} l (c: X), \n  rev (l ++ [c]) = c :: (rev l).\nProof.\n  intros X l c.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl. \n    apply (Geq (rev (t ++ [c])) (c :: rev t) [h]).\n    apply IH.\nQed.\n\nLemma concat_inj: forall {X: Type} (l1 l2: list X) (x1 x2: X),\n  l1 ++ [x1] = l2 ++ [x2] -> l1 = l2 /\\ x1 = x2.\nProof.\n  intros X l1.\n  induction l1 as [| h t IH].\n  - simpl.\n    destruct l2 as [| l2h l2t ] eqn: El2.\n    + simpl.\n      intros x1 x2 H.\n      split.\n      * reflexivity.\n      * injection H as H'.\n        apply H'.\n    + intros x1 x2.\n      simpl.\n      intros H.\n      injection H as H1 H2.\n      destruct l2t as [|l2th l2tt].\n      * simpl in H2. discriminate H2.\n      * simpl in H2. discriminate H2.\n  - simpl.\n    intros l2 x1 x2 H.\n    destruct l2 as [| l2h l2t] eqn:El2.\n    + simpl in H.\n      injection H as H'1 H'2.\n      destruct t as [| th tt ] eqn:Et.\n      * simpl in H'2. discriminate H'2.\n      * simpl in H'2. discriminate H'2.\n    + simpl in H.\n      injection H as H'1 H'2.\n      destruct (IH l2t x1 x2 H'2) as [G1 G2].\n      split.\n      * rewrite <- H'1.\n        rewrite <- G1.\n        reflexivity.\n      * apply G2.\nQed.\n\nTheorem pal_rev: forall {X: Type} (l: list X),\n  pal l -> l = rev l.\nProof.\n  intros X l H.\n  induction H as [| c | c l H' IH].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl.\n    apply (Geq (c ::l) (rev (l ++ [c])) [c]).\n    rewrite -> Rev_concat.\n    rewrite <- IH.\n    reflexivity.\nQed.\n\n(*\nLemma tst: forall {X: Type} l m (x: X), \n  x :: l = m ++ [x] -> ((l = nil /\\ m = nil) \\/ (exists l', l = l' ++ [x] /\\ m = x :: l')).\nProof.\n  intros X l m x H.\n  generalize dependent m.\n  generalize dependent x.\n  destruct l as [| h t ].\n  - left. split.\n    + reflexivity.\n    + destruct m as [| mh mt] eqn:Em.\n      * reflexivity.\n      * simpl in H.\n        injection H as InjH.\n        destruct mt as [| mtH mtT].\n        -- simpl in H. discriminate H.\n        -- simpl in H. discriminate H.\n  - intros x m H.\n    assert(G: exists k, m = x :: k). {\n      destruct m as [| mh mt].\n      + simpl in H. injection H as H'. discriminate H'.\n      + simpl in H. injection H as H'.\n        exists mt. \n        rewrite -> H'.\n        reflexivity.\n    }\n    destruct G as [k Hm].\n    right.\n    exists k.\n    split.\n    + rewrite -> Hm in H.\n      simpl in H.\n      injection H as Hr.\n      apply Hr.\n    + apply Hm.\nQed.\n*)\n\nLemma rev_empty: forall {X: Type} (l: list X), \n  rev l = [] -> l = [].\nProof.\n  intros X l H.\n  destruct l as [|h t] eqn:El.\n  - reflexivity.\n  - simpl in H. \n    destruct (rev t) as [| rh rt] eqn:Erev.\n    + simpl in H.\n      discriminate H.\n    + simpl in H.\n      discriminate H.\nQed.\n\nLemma destruct_last: forall {X: Type} (l: list X),\n  l = [] \\/ exists l' t, l = l' ++ [t].\nProof.\n  intros X l.\n  induction l as [|h t IH].\n  - left. reflexivity.\n  - right.\n    destruct IH as [IHl | IHr].\n    + exists [].\n      exists h.\n      rewrite -> IHl.\n      reflexivity.\n    + destruct IHr as [lH [tH Hh]].\n      exists (h :: lH).\n      exists tH.\n      simpl.\n      rewrite <- Hh.\n      reflexivity.\nQed.\n\nLemma rev_add_last: forall {X: Type} l (t: X), \n  rev (l ++ [t]) = t :: (rev l).\nProof.\n  intros X l.\n  induction l as [| lh lt IH].\n  - intros t. simpl. reflexivity.\n  - intros t. simpl.\n    rewrite -> IH.\n    simpl.\n    reflexivity.\nQed.\n(*\nLemma tst3 : forall {X: Type} (h: X) l,\n  h :: l = rev (h :: l) -> l = [] \\/ exists l', l' = rev l' /\\ h :: l' ++ [h] = h :: l.\nProof.\n  intros X h l H.\n  simpl in H.\n  destruct (rev l) as [|revH revT] eqn:Erev.\n  - apply rev_empty in Erev.\n    left. apply Erev.\n  - right.\n    exists revT.\n    split.\n    + destruct (destruct_last l) as [H1 | H2].\n      * rewrite -> H1 in Erev.\n        simpl in Erev.\n        discriminate Erev.\n      * destruct H2 as [lStart [lLast lEq]].\n        rewrite -> lEq in H.\n        rewrite -> lEq in Erev.\n        assert (G1: rev lStart = revT). {\n          rewrite -> rev_add_last in Erev.\n          injection Erev as Erev'1 Erev'2.\n          apply Erev'2.\n        }\n        assert (G2: lStart = revT). {\n          simpl in H.\n          injection H as H'1 H'2.\n          destruct (concat_inj lStart revT lLast h H'2) as [ErevT Eh].\n          apply ErevT.\n        }\n        rewrite -> G2 in G1.\n        symmetry.\n        apply G1.\n    + assert (G: revT ++ [h] = l -> h :: revT ++ [h] = h :: l). {\n        intros Hg.\n        rewrite -> Hg.\n        reflexivity.\n      }\n      apply G.\n      simpl in H.\n      injection H as H'1 H'2.\n      symmetry. apply H'2.\nQed.\n*)\nLemma add_any_side_same_len: forall {X: Type} (l: list X) (a b: X), \n  length (a :: l) = length (l ++ [b]).\nProof.\n  intros X l.\n  induction l as [| h t IH].\n  - intros a b. reflexivity.\n  - intros a b. simpl. rewrite <- (IH a b). reflexivity.\nQed.\n\nLemma list_split: forall {X: Type} (l: list X),\n  (exists l1   l2, length l1 = length l2 /\\ l = l1 ++        l2) \\/ \n  (exists l1 c l2, length l1 = length l2 /\\ l = l1 ++ [c] ++ l2).\nProof.\n  intros X l.\n  induction l as [| h t IH].\n  - left. exists []. exists [].\n    simpl.\n    split.\n    + reflexivity.\n    + reflexivity.\n  - assert (G: forall l m, l = m -> h :: l = h :: m). {\n      intros l m Hg.\n      rewrite -> Hg. \n      reflexivity.\n    }\n    destruct IH as [[l1 [l2 H ]] | [l1 [c [l2 H]]]].\n    + right.\n      destruct (destruct_last l1) as [Hd | Hd].\n      * exists []. exists h. exists [].\n        simpl.\n        rewrite -> Hd in H.\n        simpl in H.\n        destruct H as [H1 H2].\n        assert (G': l2 = []). {\n          destruct l2 as [| hl2 tl2].\n          - reflexivity.\n          - simpl in H1. discriminate H1.\n        }\n        rewrite -> G' in H2.\n        split. reflexivity. rewrite -> H2. reflexivity.\n      * destruct Hd as [l' [t' Hl1]].\n        exists (h :: l').\n        exists t'.\n        exists l2.\n        destruct H as [H1 H2].\n        split.\n        -- rewrite -> (add_any_side_same_len l' h t').\n           rewrite <- Hl1.\n           apply H1.\n        -- rewrite -> H2.\n           rewrite -> Hl1.\n           simpl.\n           apply G.\n           rewrite -> app_assoc.\n           simpl.\n           reflexivity.\n    + left.\n      exists (h :: l1).\n      exists (c :: l2).\n      destruct H as [H1 H2].\n      split.\n      * simpl. rewrite -> H1. reflexivity.\n      * simpl. rewrite -> H2.\n        apply G.\n        simpl.\n        reflexivity.\nQed.\n\nLemma len_add_last: forall {X: Type} l (x: X), \n  length (l ++ [x]) = S (length l).\nProof.\n  intros X l x.\n  rewrite <- (add_any_side_same_len l x x).\n  reflexivity.\nQed.\n\n\nLemma step_rev: forall {X: Type} l (x: X), \n  (x :: l ++ [x]) = rev (x :: l ++ [x]) -> l = rev l.\nProof.\n  intros X l x H.\n  simpl in H.\n  rewrite -> rev_add_last in H.\n  simpl in H.\n  injection H as H1.\n  destruct (concat_inj l (rev l) x x H1).\n  apply H.\nQed.\n\nTheorem pal_rev': forall {X: Type} (l : list X), \n  l = rev l -> pal l.\nProof.\n  intros X l H.\n  destruct (list_split l) as [Hl | Hr].\n  - destruct Hl as [l1 [l2 [EqLen EqL ]]].\n    generalize dependent l.\n    generalize dependent l2.\n    induction l1 as [| h t IH].\n    + intros l2 EqLen l H EqL.\n      assert (Hl2Empty: l2 = []). {\n        simpl in EqLen.\n        destruct l2 as [| l2h l2t].\n        - reflexivity.\n        - simpl in EqLen. discriminate EqLen.\n      }\n      rewrite -> Hl2Empty in EqL.\n      simpl in EqL.\n      rewrite -> EqL.\n      apply empty.\n    + intros l2 EqLen l H EqL.\n      destruct (destruct_last l2) as [Hd | Hd].\n      * rewrite -> Hd in EqLen. discriminate EqLen.\n      * destruct Hd as [l' [h' El2]].\n        rewrite -> El2 in EqL.\n        assert (G: h = h'). {\n          rewrite -> EqL in H.\n          rewrite <- (app_assoc) in H.\n          rewrite -> (rev_add_last ((h :: t) ++ l') h') in H.\n          rewrite -> (app_assoc) in H.\n          simpl in H.\n          injection H as H1.\n          apply H1.\n        }\n        rewrite <- G in EqL.\n        rewrite -> EqL.\n        simpl.\n        rewrite <- (app_assoc).\n        apply step.\n        assert (G1: length t = length l'). {\n          rewrite -> El2 in EqLen.\n          rewrite -> len_add_last in EqLen.\n          simpl.\n          injection EqLen as EqLen'.\n          apply EqLen'.\n        }\n        assert (G2: (t ++ l') = rev (t ++ l')). {\n          simpl in EqL.\n          rewrite -> EqL in H.\n          rewrite <- (app_assoc) in H.\n          destruct (step_rev (t ++ l') h H) as [H'].\n          reflexivity.\n        }\n        apply (IH l' G1 (t ++ l') G2).\n        reflexivity.\n  - destruct Hr as [l1 [c [l2 [EqLen EqL ]]]].\n    generalize dependent l.\n    generalize dependent l2.\n    induction l1 as [| h t IH].\n    + intros l2 EqLen l H EqL.\n      assert (Hl2Empty: l2 = []). {\n        simpl in EqLen.\n        destruct l2 as [| l2h l2t].\n        - reflexivity.\n        - simpl in EqLen. discriminate EqLen.\n      }\n      rewrite -> Hl2Empty in EqL.\n      simpl in EqL.\n      rewrite -> EqL.\n      apply one.\n    + intros l2 EqLen l H EqL.\n      destruct (destruct_last l2) as [Hd | Hd].\n      * rewrite -> Hd in EqLen. discriminate EqLen.\n      * destruct Hd as [l' [h' El2]].\n        rewrite -> El2 in EqL.\n        assert (G: h = h'). {\n          rewrite -> EqL in H.\n          rewrite <- (app_assoc) in H.\n          rewrite <- (app_assoc) in H.\n          rewrite -> (rev_add_last (((h :: t) ++ [c]) ++ l') h') in H.\n          rewrite -> (app_assoc) in H.\n          simpl in H.\n          injection H as H1.\n          apply H1.\n        }\n        rewrite <- G in EqL.\n        rewrite -> EqL.\n        rewrite <- (app_assoc).\n        rewrite <- (app_assoc).\n        simpl.\n        apply step.\n        rewrite -> (app_assoc).\n        assert (G1: length t = length l'). {\n          rewrite -> El2 in EqLen.\n          rewrite -> len_add_last in EqLen.\n          simpl.\n          injection EqLen as EqLen'.\n          apply EqLen'.\n        }\n        assert (G2: (t ++ [c] ++ l') = rev (t ++ [c] ++ l')). {\n          rewrite <- (app_assoc) in EqL.\n          rewrite <- (app_assoc) in EqL.\n          simpl in EqL.\n          rewrite -> EqL in H.\n          rewrite -> (app_assoc _ t [c] l') in H.\n          destruct (step_rev (t ++ [c] ++ l') h H) as [H'].\n          reflexivity.\n        }\n        apply (IH l' G1 (t ++ [c] ++ l') G2).\n        reflexivity.\nQed.\n\n\nEnd Pal.\n\nDefinition disjoint {X: Type} (l1 l2 : list X): Prop := \n  forall (a: X), In a l1 -> ~(In a l2).\n\nInductive NoDup {X: Type} : list X -> Prop :=\n  | emptyNoDup : NoDup []\n  | consNoDup (l: list X) (x: X) (H: NoDup l) (N: ~(In x l)) : NoDup (x :: l)\n.\n\nSearch or.\n\nLemma not_in_sum: forall {X: Type} (x: X) (a b: list X), \n  ~ In x a /\\ ~ In x b -> ~ In x (a ++ b).\nProof.\n  intros X x a b [Ha Hb].\n  induction a as [| h t IH].\n  - simpl. apply Hb.\n  - simpl.\n    simpl in Ha.\n    assert (G: forall A B, ~(A \\/ B) -> ~A /\\ ~B). {\n      intros A B H.\n      unfold not in H.\n      split.\n      + unfold not. intros HA. apply H. apply (or_introl HA).\n      + unfold not. intros HB. apply H. apply (or_intror HB).\n    }\n    unfold not.\n    intros [Hl | Hr].\n    + apply (Ha (or_introl Hl)).\n    + apply G in Ha.\n      destruct Ha as [Hal Har].\n      apply IH.\n      apply Har.\n      apply Hr.\nQed.\n\n\n\nTheorem no_dup_in_concat: forall {X: Type} (l1 l2: list X), \n  NoDup l1 /\\ NoDup l2 /\\ disjoint l1 l2 -> NoDup (l1 ++ l2).\nProof.\n  intros X l1 l2 [Hnd1 [Hnd2 Hd]].\n  induction l1 as [| h t IH].\n  - simpl. apply Hnd2.\n  - assert (G: NoDup t). {\n      remember (h :: t) as k.\n      destruct Hnd1 as [| l x H' N'] eqn:E.\n      + discriminate Heqk.\n      + injection Heqk as Heqk1 Heqk2.\n        rewrite <- Heqk2.\n        apply H'.\n    }\n    assert (G1: disjoint t l2). {\n      unfold disjoint.\n      unfold disjoint in Hd.\n      simpl in Hd.\n      intros a Inat.\n      apply (Hd a (or_intror Inat)).\n    }\n    assert (G2': ~ In h l2). {\n      unfold disjoint in Hd.\n      apply Hd.\n      simpl. left. reflexivity.\n    }\n    assert (G2'': ~ In h t). {\n      remember (h :: t) as k.\n      destruct Hnd1 as [| l x H' N'] eqn:E.\n      - discriminate Heqk.\n      - injection Heqk as Heqk1 Heqk2.\n        rewrite <- Heqk2.\n        rewrite <- Heqk1.\n        apply N'.\n    }\n    assert (G2: ~ In h (t ++ l2)). {\n      unfold disjoint in Hd.\n      apply not_in_sum.\n      split.\n      + apply G2''.\n      + apply G2'.\n    }\n    simpl.\n    apply (consNoDup (t ++ l2) h (IH G G1)).\n    apply G2.\nQed.\n\n\n\nModule PigeonHoles.\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l -> exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  intros X x l H.\n  induction l as [| h t IH].\n  - simpl in H. exfalso. apply H.\n  - simpl in H.\n    destruct H as [Hl | Hr].\n    + rewrite <- Hl.\n      exists [].\n      exists t.\n      reflexivity.\n    + destruct (IH Hr) as [l1 [l2 H']].\n      exists (h :: l1).\n      exists l2.\n      simpl.\n      rewrite <- H'.\n      reflexivity.\nQed.\n\nInductive repeats {X:Type} : list X -> Prop :=\n  | add_repeated    (l: list X) (x: X) (H: In x l):    repeats (x :: l)\n  | add_to_repeated (l: list X) (x: X) (H: repeats l): repeats (x :: l) \n.\n\n\nSearch \"<\".\n\n(* PeanoNat.Nat.nlt_0_r *)\nLemma nothing_less_0: forall n, n < 0 -> False.\nProof.\n  intros n H.\nAdmitted.\n\n\nDefinition contains_items {X: Type} (l2 l1: list X) := \n  (forall x : X, In x l1 -> In x l2).\n\n\nInductive uniques {X:Type} : list X -> Prop :=\n  | nil_unique : uniques []\n  | add_unique (l: list X) (x: X) (H: ~ In x l): uniques (x :: l)\n.\n\nLemma unique_shorter: forall {X: Type} (l1 l2: list X),\n  contains_items l2 l1 -> uniques l2 -> length l2 <= length l1.\nProof. Admitted.\n\nSearch (length ?l = 0 -> ?l = []).\n\n\nLemma remove_uniq_item: forall {X: Type} l (x: X), \n  ~(repeats l) -> In x l -> \n  exists l', ~ In x l' /\\ S (length l') = length l /\\ (~ repeats l') /\\ contains_items l l'.\nProof.\n  intros X l x Hnr Hin.\n  induction l as [| h t IH].\n  - simpl in Hin. exfalso. apply Hin.\n  - simpl in Hin.\n    destruct Hin as [Ehx | Hxint] eqn:Ehin.\n    + exists t.\n      split.\n      * intros Hxint.\n        rewrite <- Ehx in Hxint.\n        apply Hnr.\n        apply add_repeated.\n        apply Hxint.\n      * split.\n        ** reflexivity.\n        ** split.\n           *** intros Hrt. apply Hnr. apply add_to_repeated. apply Hrt.\n           *** unfold contains_items.\n               intros x' Hx'int. simpl.\n               right. apply Hx'int.\n    + assert (G: ~ repeats t). {\n        intros Hrt. apply Hnr. apply add_to_repeated. apply Hrt.\n      }\n      destruct (IH G Hxint) as [l' Hs].\n      exists (h :: l').\n      split.\n      * intros Hxinhl'. simpl in Hxinhl'.\n        destruct Hxinhl' as [Ehx | Hxinl'].\n        ** rewrite -> Ehx in Hnr.\n           apply Hnr. apply add_repeated. apply Hxint.\n        ** destruct Hs as [Hxninl' Q].\n           apply Hxninl'. apply Hxinl'.\n      * split.\n        ** simpl. \n           destruct Hs as [Q [Hlenl't W]].\n           rewrite <- Hlenl't.\n           reflexivity.\n        ** split.\n           *** intros Hrhl'.\n               remember (h :: l') as k eqn:Ek.\n               destruct Hrhl' as [dl' dh dG | dl' dh dG].\n               **** injection Ek as Ehdh Eldl.\n                    rewrite -> Ehdh in dG.\n                    rewrite -> Eldl in dG.\n                    destruct Hs as [_ [_ [_ Hci]]].\n                    unfold contains_items in Hci.\n                    apply Hnr.\n                    apply add_repeated.\n                    apply (Hci h dG).\n               **** injection Ek as Ehdh Eldl.\n                    rewrite -> Eldl in dG.\n                    destruct Hs as [_ [_ [Hnrl' _]]].\n                    apply Hnrl'. apply dG.\n           *** unfold contains_items.\n               intros x' Hinx'hl'.\n               simpl in Hinx'hl'.\n               simpl.\n               destruct Hinx'hl' as [Ehx' | Hx'int].\n               **** left. apply Ehx'.\n               **** right. destruct Hs as [_ [_ [_ Hci]]]. apply Hci. apply Hx'int.\nQed.\n\nLemma remove_item: forall {X: Type} l (x: X), \n  In x l -> \n  exists l', S (length l') = length l /\\ contains_items l l' /\\ (forall i : X, In i l -> (i = x) \\/ In i l').\nProof.\n  intros X l x Hxinl.\n  induction l as [| h t IH].\n  - simpl in Hxinl. exfalso. apply Hxinl.\n  - simpl in Hxinl.\n    destruct Hxinl as [Ehx | Hxint].\n    + exists t.\n      simpl. split.\n      * reflexivity.\n      * split.\n        ++ unfold contains_items. simpl.\n           intros j Hj. right. apply Hj.\n        ++ intros x' [Hx'l | Hx'r].\n            ** rewrite <- Hx'l.\n               left. apply Ehx.\n            ** right. apply Hx'r.\n    + destruct (IH Hxint) as [l' [Hlen [Hci Hcirev]]].\n      exists (h :: l').\n      split.\n      * simpl. rewrite -> Hlen. reflexivity.\n      * split.\n        ++ unfold contains_items. simpl.\n            intros x' [Geq | Gin].\n            +++ left. apply Geq.\n            +++ right. apply (Hci x' Gin).\n        ++ intros x' Hiinht.\n           destruct Hiinht as [Hx'h | Hx'int].\n           -- right. simpl. left. apply Hx'h.\n           -- apply (Hcirev x') in Hx'int.\n              destruct Hx'int as [Hx'intl | Hx'intr].\n              --- left. apply Hx'intl.\n              --- right. simpl. right. apply Hx'intr.\nQed.\n\n\n(*\nLemma same_items: forall {X: Type} (l1 l2: list X),\n  length l1 = length l2 -> \n  ~(repeats l1) -> \n  contains_items l2 l1 -> \n  contains_items l1 l2.\nProof.\n  intros X l1.\n  induction l1 as [| h t IH].\n  - intros l2 Hlen Hnr Hci.\n    assert (G: l2 = []). {\n      remember [] as k eqn: Ek.\n      destruct l2 as [| h' t' ].\n      + rewrite -> Ek. reflexivity.\n      + rewrite -> Ek in Hlen. simpl in Hlen. discriminate Hlen.\n    }\n    rewrite -> G in Hci.\n    rewrite -> G.\n    apply Hci.\n  - intros l2 Hlen Hnr Hci.\n    unfold contains_items.\n    intros x Hxl2.\n    simpl.\n    unfold contains_items in IH.\n    destruct l2 as [| l2h l2t].\n    + simpl in Hlen. discriminate Hlen.\n    + \n*)\n\nLemma step_contains_items:forall {X: Type} l (h: X) t,\n  contains_items l (h :: t) -> contains_items l t.\nProof.\n  intros X l h t.\n  unfold contains_items.\n  simpl.\n  intros H.\n  intros x H'.\n  apply (H x (or_intror H')).\nQed.\n\nDefinition excluded_middle := forall P : Prop, P \\/ ~P.\n\nLemma empty_nas_no_repeats: forall {X: Type}, repeats (@nil X) -> False.\nProof.\n  intros X H.\n  remember [] as k eqn:Ek.\n  destruct H as [l x H' | l x H'].\n  - discriminate Ek.\n  - discriminate Ek.\nQed.\n\nLemma qwe: forall {X: Type} (l1 l2: list X) (x: X), \n  length (x :: l1) = length l2 -> contains_items l2 (x :: l1) -> \n  exists l2', length l1 = length l2' /\\ contains_items l2' l1.\nProof.\nAdmitted.\n\nLemma tst: forall {X: Type} (l1 l2: list X) (x: X), \n  excluded_middle ->\n  length l1 = length l2 -> contains_items l2 (x :: l1) \n  -> repeats (x :: l1).\nProof.\n  intros X l1.\n  induction l1 as [| h t IH].\n  - intros l2 x EM Hlen Hci.\n    assert (G: l2 = []). {\n      simpl in Hlen.\n      destruct l2 as [| h' t'].\n      + reflexivity.\n      + simpl in Hlen. discriminate Hlen.\n    }\n    rewrite -> G in Hci.\n    unfold contains_items in Hci.\n    simpl in Hci.\n    exfalso. apply (Hci x).\n    left. reflexivity.\n  - intros l2 x EM Hlen Hci.\n    assert (G: In h l2). {\n      unfold contains_items in Hci.\n      apply Hci.\n      simpl. right. left. reflexivity.\n    }\n    assert (G1: repeats (x :: t)). {\n      destruct (remove_item l2 h G) as [l' [Hlen' [Hci' Hcirev]]].\n      apply (IH l' x EM).\n      + rewrite <- Hlen in Hlen'. simpl in Hlen'. injection Hlen' as Hlen'.\n        symmetry. apply Hlen'.\n      + unfold contains_items.\n        intros i Hiin.\n  (*TODO*)\nAdmitted.\n\nTheorem pigeonhole_principle: excluded_middle ->\n  forall (X:Type) (l1 l2: list X),\n  (forall x, In x l1 -> In x l2) ->\n  length l2 < length l1 ->\n  repeats l1.\nProof.\n  intros EM X l1. \n  induction l1 as [|x l1' IHl1'].\n  - intros l2 HIn HLen.\n    simpl in HLen.\n    exfalso.\n    apply (PeanoNat.Nat.nlt_0_r (length l2) HLen).\n  - intros l2 HIn HLen.\n    remember (length(x :: l1')) as k eqn: Ek.\n    destruct HLen as [| k' HLen'].\n    + simpl in Ek.\n      injection Ek as Ek.\n      symmetry in Ek.\n      apply (tst l1' l2 x EM Ek HIn).\n    + simpl in Ek.\n      injection Ek as Ek.\n      rewrite -> Ek in HLen'.\n      assert (G: repeats l1'). {\n        apply (IHl1' l2 (step_contains_items l2 x l1' HIn) HLen').\n      }\n      apply add_to_repeated.\n      apply G.\nQed.\n\nEnd PigeonHoles.\n\n\nEnd IndProp.", "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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.7966632029121411}}
{"text": "From mathcomp Require Import ssreflect.\n\nDefinition one : nat := 1. (* 定義 *)\n(* one is defined *)\n\n(* Definition one := 1.\n   Error: one already exists. (* 再定義はできない *) *)\n\nDefinition one' := 1. (* 型を書かなくてもいい *)\nPrint one'. (* 定義の確認 *)\n(* one' = 1 \n        : nat *) (* nat は自然数の型 *) \n\nDefinition double x := x + x. (* 関数の定義 *)\nPrint double.\n(* double = fun x : nat => x + x (* 関数も値 *)\n        : nat -> nat *) (* 関数の型 *)\n\nEval compute in double 2. (* 式を計算する *)\n(* = 4\n   : nat *)\nDefinition double' := fun x => x + x. (* 関数式で定義 *)\nPrint double'.\n(* double' = fun x : nat => x + x\n        : nat -> nat *)\n\nDefinition quad x := let y := double x in 2 * y. (* 局所的な定義 *)\nEval compute in quad 2.\n(* = 8\n   : nat *)\n\nDefinition quad' x := double (double x). (* 関数適用の入れ子 *)\nEval compute in quad' 2.\n(* = 8\n   : nat *)\n\nDefinition triple x :=\n  let double x := x + x in (* 局所的な関数定義。上書きもできる *)\n  double x + x.\nEval compute in triple 3.\n(* = 9\n   : nat *)\n\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(* = choki\n   : janken *)\n\nPrint bool.\n(* Inductive bool : Set := true : bool | false : bool *)\n\nPrint janken.\n(*Inductive janken : Set := gu : janken | choki : janken | pa : janken *)\n\nDefinition wins t1 t2 := (* 「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.\n(* wins : janken -> janken -> bool *) (* 関係は bool への多引数関数 *)\nEval compute in wins gu pa.\n(*= false\n  : bool  *)\n\n(* 場合分けによる証明 *)\nLemma weakness_wins t1 t2 :\nwins t1 t2 = true <-> weakness t2 = t1.\nProof.\n  split.\n  - by case: t1; case: t2. (* 全ての場合を考える *)\n  - move=> <-; by case: t2. (* t2 の場合分けで十分 *)\n    Restart.\n    case: t1; case: t2; by split. (* 最初から全ての場合でも OK *)\nQed.\n\n\n(* 再帰データ型と再帰関数*)\n  \nModule MyNat. (* nat を新しく定義する *)\n  Inductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n    \n  (*\n    Fixpoint plus (m n : nat) {struct m} : nat := (* 帰納法の対象を明示する *)\n    match m with (* 減らないとエラーになる *)\n    | O => n\n    | S m’ => S (plus m n)\n    end.\n    Error: Recursive definition of plus is ill-formed.\n    In environment ...\n    Recursive call to plus has principal argument equal to m instead of m’.\n   *)\n\n  Fixpoint 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  Print plus.\n\n  Check plus (S (S O)) (S O).\n\n  Eval compute in plus (S (S O)) (S O). (* 式を評価する *)\n  (* = S (S (S O))\n     : nat *)\n\n  Fixpoint mult (m n : nat) {struct m} : nat := O.\n  Eval compute in mult (S (S O)) (S O).\n  (* = S (S O) (* 期待している値 *)\n     : nat   *)\n\nEnd MyNat.\n\n(* 練習問題 1.1 mult を正しく定義せよ．*)\n\n\nCheck nat_ind.\nLemma plusnS m n : m + S n = S (m + n). (* m, n は仮定 *)\nProof.\n  elim: m => /=. (* nat_ind を使う *)\n  - done. (* O の場合 *)\n  - move => m IH. (* S の場合 *)\n      by rewrite IH. (* 帰納法の仮定で書き換える *)\n      Restart.\n      elim: m => /= [|m ->] //. (* 一行にまとめた *)\nQed.\n\nCheck plusnS. (* ∀ m n : nat, m + S n = S (m + n) *)\n\nLemma plusSn m n : S m + n = S (m + n).\nProof. rewrite /=. done. Show Proof. Qed. (* 簡約できるので帰納法は不要 *)\n\nLemma plusn0 n : n + 0 = n.\nAdmitted. (* 定理を認めて証明を終わらせる *)\n\nLemma plusC m n : m + n = n + m.\nAdmitted.\n\nLemma plusA m n p : m + (n + p) = (m + n) + p.\nAdmitted.\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.\nAdmitted.\n\nLemma multC m n : m * n = n * m.\nAdmitted.\n\nLemma multnDr m n p : (m + n) * p = m * p + n * p.\nAdmitted.\n\nLemma multA m n p : m * (n * p) = (m * n) * p.\nAdmitted.\n\nFixpoint sum n :=\nif n is S m then n + sum m else 0.\nPrint sum. (* if .. is は match .. with に展開される *)\n\nLemma double_sum n : 2 * sum n = n * (n + 1).\nAdmitted.\n\nLemma square_eq a b : (a + b) * (a + b) = a * a + 2 * a * b + b * b.\nAdmitted. (* 帰納法なしで証明できる *)\n\n(* 練習問題 2.1 上の Admitted を全て証明せよ．*)\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/ssrcoq03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.7966631890157087}}
{"text": "From mathcomp Require Import ssreflect.all_ssreflect solvable.all_solvable.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Nested Proofs Allowed.\n\nModule SsrSyntax.\n\n(* Defines n, p and q, where p and q are primes, \n   and n is the product of p and q *)\nDefinition valid_mod_primes (n p q: nat):=\n  n = p * q\n  /\\\n  prime p\n  /\\\n  prime q\n  /\\\n  p <> q.\n\n(* Defines totient n, which is the product \n   of p -c1 and q - 1*)\nDefinition valid_totient_n (n p q: nat):=\n  totient n = (p - 1) * (q - 1).\n\n(* Checks that n, p, q and totient n are within \n   their set parameters *)\nDefinition valid_mod (n p q: nat):=\n  valid_mod_primes n p q\n  /\\\n  valid_totient_n n p q.\n\n(* Defines e and d *)\nDefinition valid_exponents (d e n: nat):=\n  e * d = 1 %% (totient n).\n\n(* Defines Euler's Totient Theorem *)\nDefinition Eulers_theorem (n: nat) :=\n  1 %% totient n = 1.\n\n(* Checks that d, e, n, p, and q are within \n   their set parameters *)\nDefinition valid_key_pair (d e n p q: nat):=\n  valid_exponents d e n\n  /\\\n  valid_mod n p q.\n\n(* Defines the encryption and decryption schemes\n   for RSA *)\nDefinition spec_of_RSA_encrypt (encrypt: nat -> nat -> nat -> nat):=\n  forall m e n: nat,\n    encrypt m e n = m ^ e %% n.\n\nDefinition spec_of_RSA_decrypt (decrypt: nat -> nat -> nat -> nat):=\n  forall c d n: nat,\n    decrypt c d n = c ^ d %% n.\n\nDefinition RSA_encrypt (m e n: nat): nat :=\n  m ^ e %% n.\n\nDefinition RSA_decrypt (c d n: nat): nat :=\n  c ^ d %% n.\n\n(* The assertion that decrypting an encrypted message will\n   result in m %% n *)\nTheorem RSA_encryption_scheme_valid:\nforall encrypt decrypt: nat -> nat -> nat -> nat,\n    spec_of_RSA_encrypt encrypt ->\n    spec_of_RSA_decrypt decrypt ->\n    forall d e n p q m : nat,\n      valid_key_pair d e n p q ->\n      Eulers_theorem n ->\n      decrypt (encrypt m e n) d n = m %% n.\n\n(* The proof to validate the RSA theorem *)\nProof.\n  intros encrypt decrypt h_encrypt h_decrypt d e n p q m h_valid_key_pair h_Eulers_theorem.\n  assert (h_temp := h_valid_key_pair).\n  unfold valid_key_pair in h_temp.\n  destruct h_temp as [h_valid_exponents h_valid_mod].\n  unfold valid_mod in h_valid_mod.\n  destruct h_valid_mod as [h_valid_mod_primes h_valid_totient_n].\n  destruct h_valid_mod_primes as [h_valid_n h_valid_mod_primes].\n  unfold valid_mod_primes in h_valid_mod_primes.\n  unfold valid_totient_n in h_valid_totient_n.\n  unfold valid_exponents in h_valid_exponents.\n  unfold spec_of_RSA_encrypt in h_encrypt.\n  unfold spec_of_RSA_decrypt in h_decrypt.\n  unfold Eulers_theorem in h_Eulers_theorem.\n\n  rewrite -> h_encrypt.\n  rewrite -> h_decrypt.\n  rewrite -> modnXm.\n  rewrite <- expnM.\n  rewrite -> h_valid_exponents.\n  rewrite -> h_Eulers_theorem.\n  rewrite -> expn1.\n  reflexivity.\nQed.\nPrint RSA_encryption_scheme_valid.\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/RSAProofV2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7965701612279668}}
{"text": "(* week_40a_binary_trees.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\nLemma plus_1_l :\n  forall n : nat,\n    1 + n = S n.\nProof.\n  intro n.\n  rewrite -> plus_Sn_m.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\n\nLemma plus_1_r :\n  forall n : nat,\n    n + 1 = S n.\nProof.\n  intro n.\n  rewrite -> (plus_comm).\n  apply plus_1_l.\nQed.\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\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(*\nPrint bt_2.\nbt_2 = Node (Node (Leaf 10) (Leaf 20)) (Leaf 30)\n     : binary_tree_nat\n*)\n\n(* ********** *)\n\n(* How many leaves are there in a given binary tree? *)\n\n(* A unit test: *)\n\nDefinition unit_test_for_number_of_leaves (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\n(* A specification: *)\n\nDefinition specification_of_number_of_leaves (number_of_leaves : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     number_of_leaves (Leaf n) = 1)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     number_of_leaves (Node t1 t2) = number_of_leaves t1 + number_of_leaves t2).\n\n(* ***** *)\n\n(* Uniqueness of the specification: *)\n\nTheorem there_is_only_one_number_of_leaves :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_number_of_leaves f ->\n    specification_of_number_of_leaves g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_number_of_leaves.\n  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> Hf_leaf.\n  rewrite -> Hg_leaf.\n  reflexivity.\n\n  rewrite -> Hf_node.\n  rewrite -> Hg_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* A first implementation, in direct style: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_ds (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n =>\n      1\n    | Node t1 t2 =>\n      (number_of_leaves_ds t1) + (number_of_leaves_ds t2)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_ds_Leaf :\n  forall n : nat,\n    number_of_leaves_ds (Leaf n) = 1.\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\nLemma unfold_number_of_leaves_ds_Node :\n  forall t1 t2 : binary_tree_nat,\n    number_of_leaves_ds (Node t1 t2) =\n    (number_of_leaves_ds t1) + (number_of_leaves_ds t2).\nProof.\n  unfold_tactic number_of_leaves_ds.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v0 (t : binary_tree_nat) : nat :=\n  number_of_leaves_ds t.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v0.\n(*\n     = true\n     : bool\n*)\n\n(* ***** *)\n\n(* The first implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v0.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v0.\n  split.\n\n  exact unfold_number_of_leaves_ds_Leaf.\n\n  exact unfold_number_of_leaves_ds_Node.\nQed.\n\n(* ***** *)\n\n(* A second implementation, with an accumulator: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_acc (t : binary_tree_nat) (a : nat) : nat :=\n  match t with\n    | Leaf n =>\n      1 + a  (* or even better: S a *)\n    | Node t1 t2 =>\n      number_of_leaves_acc t1 (number_of_leaves_acc t2 a)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_acc_Leaf :\n  forall n a : nat,\n    number_of_leaves_acc (Leaf n) a = 1 + a.\nProof.\n  unfold_tactic number_of_leaves_acc.\nQed.\n\nLemma unfold_number_of_leaves_acc_Node :\n  forall (t1 t2 : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc (Node t1 t2) a =\n    number_of_leaves_acc t1 (number_of_leaves_acc t2 a).\nProof.\n  unfold_tactic number_of_leaves_acc.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v1 (t : binary_tree_nat) : nat :=\n  number_of_leaves_acc t 0.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v1.\n(*\n     = true\n     : bool\n*)\n\n(* The second implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  (* Hum, we are stuck.  Let's venture a helpful lemma: *)\nAbort.\n\nLemma about_number_of_leaves_acc_tentative :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc t a = (number_of_leaves_acc t 0) + a.\nProof.\nAdmitted.\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves_second_attempt :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc_tentative.\n  reflexivity.\n  (* Yay, the proof goes through.\n     So let's prove the helpful lemma. *)\nAbort.\n\nLemma about_number_of_leaves_acc :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_acc t a = (number_of_leaves_acc t 0) + a.\nProof.\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intro a.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  (* Induction case: *)\n  intro a.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> (IHt1 (number_of_leaves_acc t2 0)).\n  (* postlude: *)\n  apply plus_assoc.\nQed.\n\nTheorem number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v1.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v1.\n  split.\n\n  intro n.\n  apply (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* The two implementations implement the same function: *)\n\nTheorem number_of_leaves_v0_and_v1_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v0 t = number_of_leaves_v1 t.\nProof.\n  (* Pedestrian attempt: *)\n  intro t.\n  unfold number_of_leaves_v0.\n  unfold number_of_leaves_v1.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> unfold_number_of_leaves_ds_Leaf.\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  rewrite -> unfold_number_of_leaves_ds_Node.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\n\n  Restart.\n\n  (* Reusing what we did before: *)\n\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v1\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves).\n\n  Restart.\n\n  (* Reusing what we did before, less concisely: *)\n\n  intro t.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v1\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves\n           t).\nQed.\n\n(* ***** *)\n\n(* A third implementation, with higher-order functions: *)\n\nDefinition compose_nat (f g : nat -> nat) (n : nat) :=\n  f (g n).\n\nNotation \"F << G\" := (compose_nat F G) (at level 70, right associativity).\n\nCompute (S << S) 40.\n\nCompute ((fun x => 2 + x) << (fun y => 10 * y)) 4.\n\nLemma unfold_compose_nat :\n  forall (f g : nat -> nat)\n          (n : nat),\n    compose_nat f g n = f (g n).\nProof.\n  unfold_tactic compose_nat.\nQed.\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_higher_order (t : binary_tree_nat) : nat -> nat :=\n  match t with\n    | Leaf n =>\n      S\n    | Node t1 t2 =>\n      (number_of_leaves_higher_order t1) << (number_of_leaves_higher_order t2)\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_higher_order_Leaf :\n  forall n : nat,\n    number_of_leaves_higher_order (Leaf n) = S.\nProof.\n  unfold_tactic number_of_leaves_higher_order.\nQed.\n\nLemma unfold_number_of_leaves_higher_order_Node :\n  forall (t1 t2 : binary_tree_nat),\n    number_of_leaves_higher_order (Node t1 t2) =\n    ((number_of_leaves_higher_order t1) << (number_of_leaves_higher_order t2)).\nProof.\n  unfold_tactic number_of_leaves_higher_order.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v2 (t : binary_tree_nat) : nat :=\n  number_of_leaves_higher_order t 0.\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v2.\n(*\n     = true\n     : bool\n*)\n\n(* The second implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v2.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v2.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_higher_order_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_higher_order_Node.\n  rewrite -> unfold_compose_nat.\n(* Aha: number_of_leaves_v2 is the same as number_of_leaves_v1! *)\nAbort.\n\nLemma about_number_of_leaves_higher_order :\n  forall (t : binary_tree_nat)\n         (a : nat),\n    number_of_leaves_higher_order t a =\n    number_of_leaves_acc t a.\nProof.\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  intro a.\n  rewrite -> unfold_number_of_leaves_higher_order_Leaf.\n  rewrite -> unfold_number_of_leaves_acc_Leaf.\n  rewrite -> (plus_1_l a).\n  reflexivity.\n\n  intro a.\n  rewrite -> unfold_number_of_leaves_higher_order_Node.\n  rewrite -> unfold_compose_nat.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  reflexivity.\nQed.\n\nTheorem number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v2.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v2.\n  split.\n\n  intro n.\n  rewrite -> about_number_of_leaves_higher_order.\n  exact (unfold_number_of_leaves_acc_Leaf n 0).\n\n  intros t1 t2.\n  rewrite -> about_number_of_leaves_higher_order.\n  rewrite -> unfold_number_of_leaves_acc_Node.\n  rewrite -> about_number_of_leaves_acc.\n  rewrite -> about_number_of_leaves_higher_order.\n  rewrite -> about_number_of_leaves_higher_order.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* A fourth implementation, in CPS: *)\n\n(* The auxiliary (recursive) function: *)\n\nFixpoint number_of_leaves_cps (ans : Type) (t : binary_tree_nat) (k : nat -> ans) : ans :=\n  match t with\n    | Leaf n =>\n      k 1\n    | Node t1 t2 =>\n      number_of_leaves_cps\n        ans\n        t1\n        (fun n1 => number_of_leaves_cps\n                     ans\n                     t2\n                     (fun n2 => k (n1 + n2)))\n  end.\n\n(* The canonical unfold lemmas: *)\n\nLemma unfold_number_of_leaves_cps_Leaf :\n  forall (ans : Type)\n         (n : nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans (Leaf n) k = k 1.\nProof.\n  unfold_tactic number_of_leaves_cps.\nQed.\n\nLemma unfold_number_of_leaves_cps_Node :\n  forall (ans : Type)\n         (t1 t2 : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans (Node t1 t2) k =\n    number_of_leaves_cps\n      ans\n      t1\n      (fun n1 => number_of_leaves_cps\n                   ans\n                   t2\n                   (fun n2 => k (n1 + n2))).\nProof.\n  unfold_tactic number_of_leaves_cps.\nQed.\n\n(* The main (non-recursive) function: *)\n\nDefinition number_of_leaves_v3 (t : binary_tree_nat) : nat :=\n  number_of_leaves_cps nat t (fun n => n).\n\n(* ***** *)\n\n(* The standard sanity check: *)\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v3.\n(*\n     = true\n     : bool\n*)\n\n(* The fourth implementation satisfies the specification: *)\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves_first_attempt :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  (* Hum, we are stuck.  Let's venture a helpful lemma: *)\nAbort.\n\nLemma about_number_of_leaves_cps_tentative :\n  forall (ans : Type)\n         (t : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans t k =\n    k (number_of_leaves_cps nat t (fun n => n)).\nProof.\nAdmitted.\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves_second_attempt :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> about_number_of_leaves_cps_tentative.\n  rewrite -> about_number_of_leaves_cps_tentative.\n  reflexivity.\n  (* Yay, the proof goes through.\n     So let's prove the helpful lemma. *)\nAbort.\n\nLemma about_number_of_leaves_cps :\n  forall (ans : Type)\n         (t : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps ans t k =\n    k (number_of_leaves_cps nat t (fun n => n)).\nProof.\n  intros ans t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intro k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  (* Induction case: *)\n  intro k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  symmetry.\n  (* OK, left-hand side then: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  (* And we are stuck.\n     Let's strengthen the induction hypothesis. *)\n\n  Restart.\n\n  intros ans t.\n  revert ans.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  (* Induction case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  (* right-hand side: *)\n  symmetry.\n  (* OK, left-hand side then: *)\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\nTheorem number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v3.\nProof.\n  unfold specification_of_number_of_leaves.\n  unfold number_of_leaves_v3.\n  split.\n\n  intro n.\n  rewrite -> unfold_number_of_leaves_cps_Leaf.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_number_of_leaves_cps_Node.\n  rewrite -> about_number_of_leaves_cps.\n  rewrite -> about_number_of_leaves_cps.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* The four implementations implement the same function: *)\n\nTheorem number_of_leaves_v0_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v0 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v0\n           number_of_leaves_v3\n           number_of_leaves_v0_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\nTheorem number_of_leaves_v1_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v1 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v1\n           number_of_leaves_v3\n           number_of_leaves_v1_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\nTheorem number_of_leaves_v2_and_v3_implement_the_same_function :\n  forall t : binary_tree_nat,\n    number_of_leaves_v2 t = number_of_leaves_v3 t.\nProof.\n  exact (there_is_only_one_number_of_leaves\n           number_of_leaves_v2\n           number_of_leaves_v3\n           number_of_leaves_v2_satisfies_the_specification_of_number_of_leaves\n           number_of_leaves_v3_satisfies_the_specification_of_number_of_leaves).\nQed.\n\n(* ********** *)\n(* ********** *)\n(* EXERCISES BEGIN HERE! *)\n\n\n(* Exercise:\n   Revisit how to compute the number of nodes\n   of a binary tree.\n*)\n\nDefinition specification_of_number_of_nodes (number_of_nodes : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     number_of_nodes (Leaf n) = 0)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     number_of_nodes (Node t1 t2) = S (number_of_nodes t1 + number_of_nodes t2)).\n\n\n\n Fixpoint number_of_leaves_acc' (t : binary_tree_nat) (a : nat) : nat :=\n   match t with\n     | Leaf n =>\n       1 + a\n     | Node t1 t2 =>\n       (number_of_leaves_acc' t2 (number_of_leaves_acc' t1 a))\n   end.\n    \n Definition number_of_leaves_v1' (t : binary_tree_nat) : nat :=\n   number_of_leaves_acc' t 0.\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v1'.\n(* \n  = true\n  : bool\n*)\n\nLemma unfold_number_of_leaves_acc'_bc :\n  forall (n a : nat),\n    number_of_leaves_acc' (Leaf n) a = 1 + a.\nProof.\n  unfold_tactic number_of_leaves_acc'.\nQed.\n\nLemma unfold_number_of_leaves_acc'_ic :\n  forall (t1 t2 : binary_tree_nat) (a : nat),\n    number_of_leaves_acc' (Node t1 t2) a = number_of_leaves_acc' t2 ( number_of_leaves_acc' t1 a).\nProof.\n  unfold_tactic number_of_leaves_acc'.\nQed.\n\nLemma eureka_now :\n  forall (t : binary_tree_nat) (a : nat),\n    number_of_leaves_acc' t a = a + number_of_leaves_acc' t 0.\nProof.\n  intro t.\n  induction t as [ t' | t1 IHt1 t2 IHt2].\n  intro a.\n  rewrite -> unfold_number_of_leaves_acc'_bc.\n  rewrite -> unfold_number_of_leaves_acc'_bc.\n  rewrite -> (plus_0_r).\n  rewrite -> (plus_comm).\n  reflexivity.\n\n  intro a.\n  rewrite -> (unfold_number_of_leaves_acc'_ic).\n  rewrite -> (unfold_number_of_leaves_acc'_ic).\n  rewrite -> IHt2.\n  rewrite -> IHt1.\n  rewrite -> (IHt2 (number_of_leaves_acc' t1 0)).\n  rewrite <- (plus_assoc).\n  reflexivity.\nQed.\n\n\nLemma number_of_leaves_acc'_fits_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v1'.\nProof.\n  unfold number_of_leaves_v1'.\n  unfold specification_of_number_of_leaves.\n  split.\n  intro n.\n  rewrite -> (unfold_number_of_leaves_acc'_bc).\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> (unfold_number_of_leaves_acc'_ic).\n  rewrite -> (eureka_now).\n  reflexivity.\nQed.\n\n\n\nFixpoint number_of_leaves_cps' (ans : Type) (t : binary_tree_nat) (k : nat -> ans) : ans :=\n   match t with\n     | Leaf n =>\n       k 1\n     | Node t1 t2 =>\n       number_of_leaves_cps'\n         ans\n         t2\n         (fun n2 => number_of_leaves_cps'\n                      ans\n                      t1\n                      (fun n1 => k (n1 + n2)))\n   end.\n \n Definition number_of_leaves_v3' (t : binary_tree_nat) : nat :=\n   number_of_leaves_cps' nat t (fun n => n).\n\nCompute unit_test_for_number_of_leaves number_of_leaves_v3'.\n(*\n  = true\n  : bool\n*)\nLemma unfold_number_of_leaves_cps'_bc :\n  forall (ans : Type)\n         (n : nat)\n         (k : nat -> ans),\n    number_of_leaves_cps' ans (Leaf n) k = k 1.\nProof.\n  unfold_tactic number_of_leaves_cps'.\nQed.\n\nLemma unfold_number_of_leaves_cps'_ic :\n  forall (ans : Type)\n         (t1 t2 : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps' ans (Node t1 t2) k =\n    number_of_leaves_cps'\n      ans\n      t2\n      (fun n2 => number_of_leaves_cps'\n                   ans\n                   t1\n                   (fun n1 => k (n1 + n2))).\nProof.\n  unfold_tactic number_of_leaves_cps'.\nQed.\n\nLemma about_number_of_leaves_cps' :\n  forall (ans : Type)\n         (t : binary_tree_nat)\n         (k : nat -> ans),\n    number_of_leaves_cps' ans t k =\n    k (number_of_leaves_cps' nat t (fun n => n)).\nProof.\n  intros ans t.\n  revert ans.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  (* Base case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps'_bc.\n  (* right-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps'_bc.\n  reflexivity.\n\n  (* Induction case: *)\n  intros ans k.\n  (* left-hand side: *)\n  rewrite -> unfold_number_of_leaves_cps'_ic.\n\n  rewrite -> IHt2.\n  rewrite -> IHt1.\n  (* right-hand side: *)\n  symmetry.\n  (* OK, left-hand side then: *)\n  rewrite -> unfold_number_of_leaves_cps'_ic.\n\n  rewrite -> IHt2.\n  rewrite -> IHt1.\n  reflexivity.\nQed.\n\nLemma number_of_leaves_cps'_fits_the_specification_of_number_of_leaves :\n  specification_of_number_of_leaves number_of_leaves_v3'.\nProof.\n  unfold specification_of_number_of_leaves.\n  split.\n  intro n.\n  unfold number_of_leaves_v3'.\n  rewrite -> (unfold_number_of_leaves_cps'_bc).\n  reflexivity.\n\n  intros t1 t2.\n  unfold number_of_leaves_v3'.\n  rewrite -> (unfold_number_of_leaves_cps'_ic).\n  rewrite -> (about_number_of_leaves_cps').\n  rewrite -> (about_number_of_leaves_cps').\n  reflexivity.\nQed.\n\nDefinition specification_of_product_of_leaves (product_of_leaves : binary_tree_nat -> nat) :=\n  (forall n : nat,\n     product_of_leaves (Leaf n) = n)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     product_of_leaves (Node t1 t2) = product_of_leaves t1 * product_of_leaves t2).\n\nDefinition bt_3 :=\n  Node (Leaf 20)\n       (Node (Leaf 3) (Leaf 4)).\n\nDefinition unit_test_for_product_of_leaves (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 42)\n  &&\n  (candidate bt_1 =n= 200)\n  &&\n  (candidate bt_3 =n= 240)\n  .\n\nTheorem there_is_only_one_product_of_leaves :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_product_of_leaves f ->\n    specification_of_product_of_leaves g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_product_of_leaves.\n  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].\n  intro t.\n  induction t as [ t' | t1 IHt1 t2 IHt2].\n  rewrite -> Hf_leaf.\n  rewrite -> Hg_leaf.\n  reflexivity.\n  \n  rewrite -> Hf_node.\n  rewrite -> Hg_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\nFixpoint product_of_leaves_ds (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node t1 t2 => (product_of_leaves_ds t1) * (product_of_leaves_ds t2)\nend.\n\nLemma unfold_product_of_leaves_ds_bc :\n  forall n : nat,\n    product_of_leaves_ds (Leaf n) = n.\nProof.\n  unfold_tactic product_of_leaves_ds.\nQed.\n\nLemma unfold_product_of_leaves_ds_ic :\n  forall t1 t2 : binary_tree_nat,\n    product_of_leaves_ds (Node t1 t2) = (product_of_leaves_ds t1) * (product_of_leaves_ds t2).\nProof.\n  unfold_tactic product_of_leaves_ds.\nQed.\n\nDefinition product_of_leaves_v0 (t : binary_tree_nat) : nat :=\n  product_of_leaves_ds t.\n\nCompute unit_test_for_product_of_leaves product_of_leaves_v0.\n(*\n  = true\n  : bool\n*)\nLemma product_of_leaves_v0_fits_the_specification_of_product_of_leaves :\n  specification_of_product_of_leaves product_of_leaves_v0.\nProof.\n  unfold specification_of_product_of_leaves.\n  unfold product_of_leaves_v0.\n  split.\n  intro n.\n  rewrite -> (unfold_product_of_leaves_ds_bc).\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> (unfold_product_of_leaves_ds_ic).\n  reflexivity.\nQed.\n\nFixpoint product_of_leaves_good  (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node t1 t2 =>\n      match (product_of_leaves_good t1) with\n        | 0 => 0\n        | x => x * (product_of_leaves_good t2)\n      end\n  end.\n\nFixpoint product_of_leaves_cps (ans : Type) (t : binary_tree_nat) (k : nat -> ans) : ans :=\n  match t with\n    | Leaf n =>\n      k n\n    | Node t1 t2 =>\n      product_of_leaves_cps\n        ans\n        t1\n        (fun n1 => product_of_leaves_cps\n                     ans\n                     t2\n                     (fun n2 => k (n1 * n2)))\n  end.\n\nCompute bt_1.\nCompute product_of_leaves_cps nat bt_1 (fun n => n).\n\nLemma unfold_product_of_leaves_good_bc :\n  forall n : nat,\n    product_of_leaves_good (Leaf n) = n.\nProof.    \n  unfold_tactic product_of_leaves_good.\nQed.\n\nLemma unfold_product_of_leaves_good_ic :\n  forall (t1 t2 : binary_tree_nat),\n    product_of_leaves_good (Node t1 t2) =  match (product_of_leaves_good t1) with\n        | 0 => 0\n        | x => x * (product_of_leaves_good t2)\n      end.\nProof.\n  unfold_tactic product_of_leaves_good.\nQed.\n\nDefinition product_of_leaves_v1 (t : binary_tree_nat) : nat :=\n  product_of_leaves_good t.\n\nCompute unit_test_for_product_of_leaves product_of_leaves_v1.\n(*\n  = true\n  : bool\n*)\nLemma product_of_leaves_v1_fits_the_specification_of_product_of_leaves :\n  specification_of_product_of_leaves product_of_leaves_v1.\n  unfold specification_of_product_of_leaves.\n  unfold product_of_leaves_v1.\n  split.\n  intro n.\n  rewrite -> unfold_product_of_leaves_good_bc.\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> unfold_product_of_leaves_good_ic.\n  case (product_of_leaves_good t1) as [ | n'].\n    rewrite -> (mult_0_l).\n    reflexivity.\n  reflexivity.\nQed.\n\nTheorem product_of_leaves_v0_and_v1_implement_the_same_function :\n  forall t : binary_tree_nat,\n    product_of_leaves_v0 t = product_of_leaves_v1 t.\nProof.\n  exact (there_is_only_one_product_of_leaves\n           product_of_leaves_v0\n           product_of_leaves_v1\n           product_of_leaves_v0_fits_the_specification_of_product_of_leaves\n           product_of_leaves_v1_fits_the_specification_of_product_of_leaves ).\nQed.\n\n\n\n(* ********** *)\n\n(* Food for thought (with thanks to John Anker):\n   For any binary tree,\n   how would you compare its number of leaves and its number of nodes?\n   Is there a relation?  If so, could you formalize it in Coq?\n*)\n\nDefinition unit_test_for_number_of_nodes (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 0)\n  &&\n  (candidate bt_1 =n= 1)\n  &&\n  (candidate bt_2 =n= 2)\n  &&\n  (candidate (Node bt_1 bt_2) =n= 4)\n  .\n\nTheorem there_is_only_one_number_of_nodes :\n  forall f g : binary_tree_nat -> nat,\n    specification_of_number_of_nodes f ->\n    specification_of_number_of_nodes g ->\n    forall t : binary_tree_nat,\n      f t = g t.\nProof.\n  intros f g.\n  unfold specification_of_number_of_nodes.\n  intros [Hf_leaf Hf_node] [Hg_leaf Hg_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> Hf_leaf.\n  rewrite -> Hg_leaf.\n  reflexivity.\n\n  rewrite -> Hf_node.\n  rewrite -> Hg_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\nFixpoint number_of_nodes_ds (t : binary_tree_nat) : nat :=\n  match t with\n    | Leaf n =>\n      0\n    | Node t1 t2 =>\n      (number_of_nodes_ds t1) + (number_of_nodes_ds t2) + 1\n  end.\n\nLemma unfold_number_of_nodes_ds_leaf :\n  forall n : nat,\n    number_of_nodes_ds (Leaf n) = 0.\nProof.\n  unfold_tactic number_of_nodes_ds.\nQed.\n\nLemma unfold_number_of_nodes_ds_node :\n  forall t1 t2 : binary_tree_nat,\n    number_of_nodes_ds (Node t1 t2) =\n    (number_of_nodes_ds t1) + (number_of_nodes_ds t2) + 1.\nProof.\n  unfold_tactic number_of_nodes_ds.\nQed.\n\nDefinition number_of_nodes_v0 (t : binary_tree_nat) : nat :=\n  number_of_nodes_ds t.\n\nCompute unit_test_for_number_of_nodes number_of_nodes_v0.\n(*\n  = true\n  : bool\n*)\n\nLemma number_of_nodes_v0_fits_the_specification_of_number_of_nodes :\n  specification_of_number_of_nodes number_of_nodes_v0.\nProof.    \n  unfold specification_of_number_of_nodes.\n  unfold number_of_nodes_v0.\n  split.\n  intro n.\n  rewrite -> (unfold_number_of_nodes_ds_leaf).\n  reflexivity.\n\n  intros t1 t2.\n  rewrite -> (unfold_number_of_nodes_ds_node).\n  rewrite -> (plus_1_r).\n  reflexivity.\nQed.\n\n\nTheorem number_of_leaves_relates_to_number_of_nodes :\n  forall t : binary_tree_nat,\n    number_of_leaves_v0 t = 1 + number_of_nodes_v0 t.\nProof.\n  intro t.\n  unfold number_of_nodes_v0.\n  unfold number_of_leaves_v0.\n  induction t as [ t' | t1 IHt1 t2 IHt2 ].\n  rewrite -> (unfold_number_of_leaves_ds_Leaf).\n  rewrite -> (unfold_number_of_nodes_ds_leaf).\n  rewrite -> (plus_0_r).\n  reflexivity.\n\n  rewrite -> (unfold_number_of_nodes_ds_node).\n  rewrite -> (unfold_number_of_leaves_ds_Node).\n  rewrite <- (plus_assoc).\n  rewrite -> (plus_comm (number_of_nodes_ds t2) 1). \n  rewrite <- (IHt2).\n  rewrite -> (plus_assoc).\n  rewrite <- (IHt1).\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of week_40a_binary_trees.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_40a_binary_trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.9059898203834278, "lm_q1q2_score": 0.7964980305928869}}
{"text": "(* week_38a_recap.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* Learning goals for this week:\n\n   - Using previous lemmas (with rewrite or apply)\n     without giving them all their arguments,\n     and\n     acquiring a sense of which arguments are actually needed,\n     to disambiguate.\n\n     To this end, all the proofs of this week's exercises\n     should be in two versions, separated by \"Restart.\":\n     * in the first version,\n       all the uses of previous lemmas\n       should have _complete arguments_; and\n     * in the second version,\n       all the uses of previous lemmas\n       should have _as few arguments as possible_.\n\n   - at\n\n   - The exact tactic:\n     it is like apply, requires all the arguments,\n     and is used to complete a subgoal.\n\n   - The f_equal tactic:\n     it is like f_equal_S,\n     just for any function rather than just for S.\n\n   - Proofs by case.\n\n   - Searching the libraries.\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nSearch (_ + _ = _ + _ -> _ = _).\nSearch (S _ + _ = _).\n\nSearchAbout plus.\n\n(* ********** *)\n\nRequire Import unfold_tactic.\n\nLemma unfold_plus_bc :\n  forall y : nat,\n    0 + y = y.\n(* left-hand side in the base case of plus\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall x' y : nat,\n    (S x') + y = S (x' + y).\n(* left-hand side in the inductive case of plus\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\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\n(* ***** *)\n\nLemma plus_1_l :\n  forall x : nat,\n    1 + x = S x.\nProof.\n  intro x.\n  rewrite -> (unfold_plus_ic 0).\n  rewrite -> (unfold_plus_bc x).\n  reflexivity.\n\n  Restart.\n\n  intro x.\n  rewrite -> unfold_plus_ic.\n  rewrite -> unfold_plus_bc.\n  reflexivity.\nQed.\n\nLemma plus_1_r :\n  forall x : nat,\n    x + 1 = S x.\nProof.\n  intro x.\n  rewrite -> (plus_comm x 1).\n  exact (plus_1_l x).\n\n  Restart.\n\n  intro x.\n  rewrite -> plus_comm.\n  apply plus_1_l.\nQed.\n\n(* ***** *)\n\nLemma f_equal_S :\n  forall x y : nat,\n    x = y -> S x = S y.\nProof.\n  intros x y.\n  intro H_xy.\n  rewrite -> H_xy.\n  reflexivity.\n\n  Restart.\n\n  Check f_equal.\n  Check (f_equal S).\n  apply (f_equal S).\n\n  Restart.\n\n  exact (f_equal S).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_1 :\n  forall x y : nat,\n    x = y -> 1 + x = 1 + y.\nProof.\n  exact (f_equal (plus 1)).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_10 :\n  forall x y : nat,\n    x = y -> 10 + x = 10 + y.\nProof.\n  exact (f_equal (plus 10)).\n\n  Restart.\n\n  apply f_equal.\nQed.\n\nLemma f_equal_plus_20 :\n  forall x y : nat,\n    x = y -> x + 20 = 20 + y.\nProof.\n  intros x y H_xy.\n  rewrite -> (plus_comm x 20).\n  exact (f_equal (plus 20) H_xy).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> plus_comm.\n  apply f_equal.\n  exact H_xy.\nQed.\n\nLemma f_equal_plus_30 :\n  forall x y : nat,\n    x = y -> 30 + x = y + 30.\nProof.\n  intros x y H_xy.\n  rewrite -> (plus_comm y 30).\n  exact (f_equal (plus 30) H_xy).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> plus_comm.\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm y 30).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm y _).\n\n  Restart.\n\n  intros x y H_xy.\n  rewrite -> (plus_comm _ 30).\n\n  apply f_equal.\n  exact H_xy.\nQed.\n\n(* ********** *)\n\n(* Binomial expansion at rank 2: *)\n\nDefinition square (x : nat) : nat :=\n  x * x.\n\nLemma unfold_square :\n  forall x : nat,\n    square x = x * x.\nProof.\n  unfold_tactic square.\nQed.\n\nLemma binomial_2 :\n  forall x y : nat,\n    square (x + y) = square x + 2 * x * y + square y.\nProof.\n  intros x y.\n  rewrite -> unfold_square.\n  Search((_ + _) * _ = _).\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  rewrite -> unfold_square.\n  rewrite -> unfold_square.\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.\n\n  Restart.\n\n\n  intros x y.\n  rewrite ->3 unfold_square.\n  Restart. \n  \n  intros x y.\n\n  rewrite -> unfold_square.\n  rewrite -> unfold_square.\n  rewrite -> unfold_square.\n  ring.\nQed.\n\n\n(* ********** *)\n\n(* [To be done at home, let's skip to the evenp example.] *)\n\n(* The power (i.e., exponentiation) function: *)\n\n(* A unit test: *)\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_test_for_power (candidate : nat -> nat -> nat) :=\n  (candidate 2 0 =n= 1)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 10 =n= 1024)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_power (power : nat -> nat -> nat) :=\n  (forall x : nat,\n     power x 0 = 1)\n  /\\\n  (forall x n' : nat,\n     power x (S n') = x * (power x n')).\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_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.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* Some lemmas about power: *)\n\nLemma about_power_base_one :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall n : nat,\n      power 1 n = 1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_base_mult :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x y n : nat,\n      power (x * y) n = (power x n) * (power y n).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_exponent_plus :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x i j : nat,\n      power x (i + j) = (power x i) * (power x j).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nLemma about_power_exponent_mult :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    forall x i j : nat,\n      power x (i * j) = power (power x i) j.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* First implementation: *)\n\nFixpoint power_v1 (x n : nat) : nat :=\n  match n with\n    | 0 => 1\n    | S n' => x * (power_v1 x n')\n  end.\n\nCompute unit_test_for_power power_v1.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_v1_bc :\n  forall x : nat,\n    power_v1 x 0 = 1.\nProof.\n  unfold_tactic power_v1.\nQed.\n\nLemma unfold_power_v1_ic :\n  forall x n' : nat,\n    power_v1 x (S n') = x * (power_v1 x n').\nProof.\n  unfold_tactic power_v1.\nQed.\n\nProposition power_v1_satisfies_the_specification_of_power :\n  specification_of_power power_v1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* Second implementation\n   (lambda-dropped version of the first): *)\n\nDefinition power_v2 (x n_orig : nat) : nat :=\n  let fix visit (n : nat) : nat :=\n      match n with\n        | 0 => 1\n        | S n' => x * (visit n')\n      end\n  in visit n_orig.\n\nCompute unit_test_for_power power_v2.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_v2_bc :\n  forall x : nat,\n    power_v2 x 0 = 1.\nProof.\n  unfold_tactic power_v2.\nQed.\n\nLemma unfold_power_v2_ic :\n  forall x n' : nat,\n    power_v2 x (S n') = x * (power_v2 x n').\nProof.\n  unfold_tactic power_v2.\nQed.\n\nProposition power_v2_satisfies_the_specification_of_power :\n  specification_of_power power_v2.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ***** *)\n\n(* Third implementation (version with an accumulator): *)\n\nFixpoint power_acc (x n a : nat) : nat :=\n  match n with\n    | 0 => a\n    | S n' => power_acc x n' (x * a)\n  end.\n\nDefinition power_v3 (x n : nat) : nat :=\n  power_acc x n 1.\n\nCompute unit_test_for_power power_v3.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_power_acc_bc :\n  forall x a : nat,\n    power_acc x 0 a = a.\nProof.\n  unfold_tactic power_acc.\nQed.\n\nLemma unfold_power_acc_ic :\n  forall x n' a : nat,\n    power_acc x (S n') a = power_acc x n' (x * a).\nProof.\n  unfold_tactic power_acc.\nQed.\n\nProposition power_v3_satisfies_the_specification_of_power :\n  specification_of_power power_v3.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ********** *)\n\n(* The even predicate: *)\n\n(* A unit test: *)\n\nNotation \"A =b= B\" := (eqb A B) (at level 70, right associativity).\n\nDefinition unit_test_for_evenp (candidate : nat -> bool) :=\n  (candidate 0 =b= true)\n  &&\n  (candidate 1 =b= false)\n  &&\n  (candidate 2 =b= true)\n  &&\n  (candidate 3 =b= false)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_evenp (evenp : nat -> bool) :=\n  (evenp 0 = true)\n  /\\\n  (evenp 1 = false)\n  /\\\n  (forall n'' : nat,\n     evenp (S (S n'')) = evenp n'').\n\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_evenp :\n  forall f g : nat -> bool,\n    specification_of_evenp f ->\n    specification_of_evenp g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_evenp.\n  intros [Hf_0 [Hf_1 Hf_SS]]\n         [Hg_0 [Hg_1 Hg_SS]].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  rewrite -> Hf_0.\n  rewrite -> Hg_0.\n  reflexivity.\n\n\n  case n' as [ | n''] eqn:Hn'.\n  \n  rewrite -> Hf_1.\n  rewrite -> Hg_1.\n  reflexivity.\n\n  rewrite -> Hf_SS.\n  rewrite -> Hg_SS.\n  \n  case n'' as [ | n'''] eqn:Hn''.\n  rewrite -> Hf_0.\n  rewrite -> Hg_0.\n  reflexivity.\n\n  Restart.\n\n  intros f g.\n  unfold specification_of_evenp.\n  intros [Hf_0 [Hf_1 Hf_SS]]\n         [Hg_0 [Hg_1 Hg_SS]].\n  intro n.\n  \n  assert(consecutive :\n           forall x : nat,\n             f x = g x /\\ f (S x) = g (S x)).\n\n\n  intro x.\n  induction x as [ | x' [IHx' IHSx']].\n\n  split.\n  \n    rewrite -> Hf_0.\n    rewrite -> Hg_0.\n    reflexivity.\n\n    rewrite -> Hf_1.\n    rewrite -> Hg_1.\n    reflexivity.\n    \n    split.\n\n    exact IHSx'.\n\n    rewrite -> Hf_SS.\n    rewrite -> Hg_SS.\n\n    exact IHx'.\n\n    destruct(consecutive n) as [H_magic _].\n    exact H_magic.\nQed.    \n\n\n\n    (* Properties: *)\n\nLemma about_evenp :\n  forall evenp : nat -> bool,\n    specification_of_evenp evenp ->\n    forall x : nat,\n      evenp (S x) = negb (evenp x).\nProof.\n  intros evenp.\n  unfold specification_of_evenp.\n  intros [H_0 [H_1 H_SS]].\n  intro x.\n  induction x as [ | x' IHx'].\n\n  rewrite -> H_1.\n  rewrite -> H_0.\n  unfold negb.\n  reflexivity.\n\n  rewrite -> H_SS.\n  rewrite -> IHx'.\n  destruct (evenp x') eqn:H_evenp_x'.\n\n    unfold negb.\n    reflexivity.\n\n  unfold negb.\n  reflexivity.\nQed.\n\nLemma about_evenp_of_a_sum :\n  forall evenp : nat -> bool,\n    specification_of_evenp evenp ->\n    forall x y : nat,\n      evenp (x + y) = eqb (evenp x) (evenp y).\nProof.\n  intros evenp.\n  unfold specification_of_evenp.\n  intros [H_0 [H_1 H_SS]].\n  intro x.\n  induction x as [ | x' IHx'].\n\n  intro y.\n  rewrite -> plus_0_l.\n  rewrite -> H_0.\n  unfold eqb.\n  destruct (evenp y) eqn:H_y.\n    reflexivity.\n  reflexivity.\n\n  (* Det samme som \n  intro y.\n  destruct y as [ | y' ].\n  *)\n\n  intros [ | y' ].\n\n  rewrite -> plus_0_r.\n  rewrite -> H_0.\n  destruct (evenp (S x')) eqn:H_evenp_Sx'.\n  unfold eqb.\n  reflexivity.\n\n  unfold eqb.\n  reflexivity.\n\n  rewrite -> unfold_plus_ic.\n  rewrite -> plus_comm.\n  rewrite -> unfold_plus_ic.\n  rewrite -> plus_comm.\n  rewrite -> H_SS.\n  rewrite -> IHx'.\n  rewrite -> about_evenp.\n  rewrite -> about_evenp.\n  destruct (evenp x') eqn:H_evenp_x'.\n    destruct (evenp y') eqn:H_evenp_y'.\n      unfold negb.\n      unfold eqb.\n      reflexivity.\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n  destruct (evenp y') eqn:H_evenp_y'.\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n  unfold negb.\n  unfold eqb.\n  reflexivity.\n\nQed.\n\n(* An implementation: *)\n\nFixpoint evenp_v0 (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S n' => match n' with\n                | 0 => false\n                | S n'' => evenp_v0 n''\n              end\n  end.\n\nCompute unit_test_for_evenp evenp_v0.\n(*\n     = true\n     : bool\n*)\n\n(* Or equivalently (syntactic sugar): *)\n\nFixpoint evenp_v0' (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S 0 => false\n    | S (S n'') => evenp_v0' n''\n  end.\n\nCompute unit_test_for_evenp evenp_v0'.\n(*\n     = true\n     : bool\n*)\n\nLemma unfold_evenp_v0_bc0 :\n  evenp_v0 0 = true.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nLemma unfold_evenp_v0_bc1 :\n  evenp_v0 1 = false.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nLemma unfold_evenp_v0_ic :\n  forall n'' : nat,\n    evenp_v0 (S (S n'')) = evenp_v0 n''.\nProof.\n  unfold_tactic evenp_v0.\nQed.\n\nProposition evenp_satisfies_the_specification_of_evenp :\n  specification_of_evenp evenp_v0.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\n(* ********** *)\n\n(* The Fibonacci numbers: *)\n\n(* A unit test: *)\n\nDefinition unit_test_for_fib (candidate: nat -> nat) :=\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  (candidate 9 =n= 34)\n  .\n\n(* A specification: *)\n\nDefinition specification_of_the_fibonacci_function (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\n(* Uniqueness of the specification: *)\n\nProposition there_is_only_one_fibonacci_function :\n  forall fib1 fib2 : nat -> nat,\n    specification_of_the_fibonacci_function fib1 ->\n    specification_of_the_fibonacci_function fib2 ->\n    forall n : nat,\n      fib1 n = fib2 n.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* A first implementation: *)\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\nDefinition fib_v0 (n : nat) : nat :=\n  fib_ds n.\n\nCompute unit_test_for_fib fib_v0.\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 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 fib_ds_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_ds.\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nCorollary fib_v0_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v0.\nProof.\n  unfold fib_v0.\n  apply fib_ds_fits_the_specification_of_the_fibonacci_function.\nQed.\n\n(* ***** *)\n\n(* A second implementation, 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\nDefinition fib_v1 (n : nat) : nat :=\n  fib_acc n 1 0.\n\nCompute unit_test_for_fib fib_v1.\n\nLemma unfold_fib_acc_base_case :\n  forall a1 a0 : nat,\n    fib_acc 0 a1 a0 = a0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\nLemma unfold_fib_acc_induction_case :\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\nLemma unfold_fib_v1 :\n  forall n : nat,\n    fib_v1 n = fib_acc n 1 0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_acc :\n  forall fib : nat -> nat,\n    specification_of_the_fibonacci_function fib ->\n    forall k i : nat,\n      fib_acc k (fib (S i)) (fib i) = fib (k + i).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\nQed.\n\nTheorem fib_v1_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\n(* A third implementation, 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\nDefinition fib_v2 (n : nat) : nat :=\n  match n with\n    | O => 0\n    | S n' => let (a1, a0) := fib_co_acc n'\n              in a1\n  end.\n\nCompute unit_test_for_fib fib_v2.\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 (a1, a0) := fib_co_acc n'\n                        in (a1 + a0, a1).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_v2_0 :\n  fib_v2 0 = 0.\nProof.\n  unfold_tactic fib_v2.\nQed.\n\nLemma unfold_fib_v2_Sn' :\n  forall n' : nat,\n    fib_v2 (S n') = let (a1, a0) := fib_co_acc n'\n                    in a1.\nProof.\n  unfold_tactic fib_v2.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_co_acc :\n  forall fib : nat -> nat,\n    specification_of_the_fibonacci_function fib ->\n    forall n : nat,\n      fib_co_acc n = (fib (S n), fib n).\nProof.\nAbort.\n(* Replace \"Abort.\" with a (standard) proof. *)\n\nTheorem fib_v2_fits_the_specification_of_the_fibonacci_function :\n  specification_of_the_fibonacci_function fib_v2.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* end of week_38a_recap.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_38a_recap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.7964980286813267}}
{"text": "From LF Require Export Lists.\n\n\nInductive list (X : Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\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.\nCheck cons : forall X : Type, X -> list X -> list X. \n\n\nCheck (cons nat 2 (cons nat 1 (nil nat))) : list nat.\n\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\nExample test_repeat1 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_repeat2 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nModule NumberGrumble.\n  Inductive number : Type :=\n  | a\n  | b (x : number) (y : nat)\n  | c.\n\n  Inductive grumble (X : Type) :=\n  | d (m : number)\n  | e (x : X).\n\n  (* \n  Which of the following are well-typed elements of grumble X\n  for some type X? (Add YES or NO to each line.)\n\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)    YES\n    e bool (b c 0)      No\n    c                   NO\n *)\n\n  Check d number (b a 5) : grumble number.\n  Check d bool (b a 5) : grumble bool.\n  Check e bool true : grumble bool.\n  Check e number (b c 0) : grumble number.\n\nEnd NumberGrumble.\n\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | O => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat' : forall X : Type, X -> nat -> list X.\nCheck repeat : forall X : Type, X -> nat -> list X.\n\n\n(* \nThis may sound similar to type annotation inference -- and, indeed, the two procedures rely on the same underlying mechanisms. Instead of simply omitting the types of some arguments to a function, like\n    repeat' X x count : list X :=\nwe can also replace the types with holes\n    repeat' (X : _) (x : _) (count : _) : list X :=\nto tell Coq to attempt to infer the missing information.\n*)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | O => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n\n(* \nThe Arguments directive specifies the name of the function\n(or constructor) and then lists the (leading) argument names\nto be treated as implicit, each surrounded by curly braces.\n*)\n\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | O => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(* \nWe will use the latter style whenever possible, but __we will\ncontinue to use explicit Argument declarations for Inductive\nconstructors.__ The reason for this is that marking the parameter\nof an inductive type as implicit causes it to become implicit\nfor the type itself, not just for its constructors. For instance,\nconsider the following alternative definition of the list type:\n*)\n\nInductive list' {X : Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons e' l1' => cons e' (app l1' l2)\n  end.\n\n\nFixpoint rev {X : Type} (l : list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h tl => app (rev tl) (cons h nil)\n  end.\n\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => O\n  | cons h tl => S (length tl)\n  end.\n\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = cons 2 (cons 1 nil).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample test_rev2 :\n  rev (cons true nil) = (cons true nil).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample test_length1 :\n  length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\n\nCheck @nil : forall (X : Type), list X.\n\nDefinition mylist' := @nil nat.\n\n\nNotation \"x :: y\" :=\n  (cons x y)\n  (at level 60, right associativity).\n\nNotation \"[ ]\" := nil.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n\nNotation \"x ++ y\" :=\n  (app x y)\n  (at level 60, right associativity).\n\nDefinition list123''' := [1;2;3].\n\nFail Definition mynil'' := [].\nDefinition mynil'' : list nat := [].\n\n\nTheorem app_nil_r:\n  forall (X : Type), forall (l : list X), l ++ [] = l.\nProof.\n  intros.\n  induction l as [|l'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\n\nTheorem app_assoc :\n  forall (X : Type), forall (l1 l2 l3: list X),\n  app (app l1 l2) l3 = app l1 (app l2 l3).\nProof.\n  intros.\n  induction l1 as [|l1'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity.\nQed.\n\n\nTheorem app_length :\n  forall (X : Type), forall (l1 l2 : list X),\n  length (app l1 l2) = (length l1) + (length l2).\nProof.\n  intros.\n  induction l1 as [|l1'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity. \nQed.\n\n\nTheorem rev_app_distr :\n  forall (X : Type), forall (l1 l2 : list X),\n  rev (app l1 l2) = app (rev l2) (rev l1).\nProof.\n  intros.\n  induction l1 as [| l1'].\n  - simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    rewrite app_assoc.\n    reflexivity. \nQed.\n\n\nTheorem rev_involution :\n  forall (X : Type), forall (l : list X),\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| l'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite rev_app_distr.\n    rewrite IHl.\n    simpl.\n    reflexivity.\nQed.\n\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\n\nArguments pair {X} {Y}.\n\n\nNotation \"( x , y )\" := (pair x y).\n\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\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\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n\nFixpoint combine {X Y : Type} (l1 : list X) (l2 : list Y) : list (X * Y) :=\n  match l1, l2 with\n  | _, nil => nil\n  | nil, _ => nil\n  | cons h1 tl1, cons h2 tl2 => cons (h1, h2) (combine tl1 tl2)\n  end.\n\n\nCompute combine [1; 2] [true; false; true].\n\n\nFixpoint split { X Y : Type} (l : list (X * Y)) : ((list X) * (list Y)) :=\n  match l with\n  | nil => (nil, nil)\n  | cons (hx, hy) tl => \n    match (split tl) with\n    | (lx, ly) => (cons hx lx, cons hy ly)\n    end\n  end.\n\nExample test_split :\n  split [(1, true); (2, false)] = ([1; 2], [true; false]).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nModule OptionPlayground.\n  Inductive option (X : Type) : Type :=\n  | None\n  | Some (x : X).\n\n  Arguments Some {X}.\n  Arguments None {X}.\nEnd OptionPlayground.\n\n\nFixpoint nth_err {X : Type} (l : list X) (n : nat) : option X :=\n  match n, l with\n  | O, h :: tl => Some h\n  | _, nil => None\n  | S n', h :: tl => nth_err tl n'\n  end.\n\nExample test_nth_err1 :\n  nth_err [4;5;6;7] 0 = Some 4.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample test_nth_err2 :\n  nth_err [[1];[2]] 1 = Some [2].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nth_err3 :\n  nth_err [true] 2 = None.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nDefinition hd_err {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | h :: _ => Some h\n  end.\n\n\nCheck @hd_err : forall (X : Type), list X -> option X.\n\nExample test_hd_err1 :\n  hd_err [1; 2] = Some 1.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_hd_err2 :\n  hd_err [[1]; [2]] = Some [1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\n(* Higher-Order Functions *)\n\nDefinition doit3times {X : Type} (f : X -> X) (n : X) : X :=\n  f (f (f n)).\n\n\nCheck @doit3times : forall (X : Type), (X -> X) -> X -> X.\n\n\nExample test_doit3times :\n  doit3times minustwo 9 = 3.\nProof.\n  (* compute. *)\n  reflexivity.\nQed.\n\nExample test_doit3times' :\n  doit3times negb true = false.\nProof.\n  (* compute. *)\n  reflexivity.\nQed.\n\n\nFixpoint filter {X : Type} (test : X -> bool) (l : list X) : (list X) :=\n  match l with\n  | nil => nil\n  | h :: tl =>\n    match test h with\n    | true => h :: (filter test tl)\n    | false => (filter test tl)\n    end\n  end.\n\n\nExample test_filter1 :\n  filter even [1;2;3;4] = [2;4].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  length l =? 1.\n\n\nExample test_filter2 :\n  filter length_is_1 [[1;2];[3];[4];[5;6;7];[];[8]] = [[3];[4];[8]].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nDefinition countoddmember' (l : list nat) : nat :=\n  length (filter odd l).\n\n\nExample test_countoddmember'1 :\n  countoddmember' [1;0;3;1;4;5] = 4.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nExample test_countoddmember'2 :\n  countoddmember' [0;2;4] = 0.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nExample test_countoddmember'3 :\n  countoddmember' nil = 0.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\n(* Anonymous Functions *)\n\nExample test_anno_fun' :\n  doit3times (fun n => n * n) 2 = 256.\nProof.\n  reflexivity.\nQed.\n\n\nExample test_filter2' :\n  filter (fun l => length l =? 1)\n    [[1;2];[3];[4];[5;6;7];[];[8]] = [[3];[4];[8]].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nDefinition filter_even_gt7 (l : list nat) : list nat:=\n  filter (fun n => (even n) && (n >=? 7)) l.\n\n\nExample test_filter_even_gt7 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nDefinition partition {X : Type} (f : X -> bool) (l : list X) : ((list X) * (list X)) :=\n  (filter f l, filter (fun n => negb (f n)) l).\n\n\nExample test_patition1 :\n  partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nExample test_partition2 :\n  partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nFixpoint map {X Y : Type} (f : X -> Y) (l : list X) : (list Y) :=\n  match l with\n  | nil => nil\n  | h :: tl => (f h) :: (map f tl)\n  end.\n\n\nExample test_map1 :\n  map (fun x => plus x 3) [2;0;2] = [5;3;5].\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\n\nExample test_map3:\n  map (fun n => [even n; odd n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nLemma map_app_distr :\n  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 [| l1'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity. \nQed.\n\n\n\nTheorem map_rev :\n  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 [| l'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- IHl.\n    simpl.\n    rewrite map_app_distr.\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  | h :: tl => (f h) ++ (flat_map f tl)\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.\n  compute.\n  reflexivity.\nQed.\n\n\nDefinition option_map {X Y : Type} (f : X -> Y) (ox : option X) : option Y :=\n  match ox with\n  | None => None\n  | Some x => Some (f x)\n  end.\n\n\nFixpoint fold {X Y : Type} (f : X -> Y -> Y) (l : list X) (acc : Y) : Y :=\n  match l with\n  | nil => acc\n  | h :: tl => f h (fold f tl acc)\n  end.\n\n\nExample test_fold1 :\n  fold plus [1;2;3;4] 0 = 10.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nCheck (fold andb) : list bool -> bool -> bool.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nDefinition constfun {X : Type} (x : X) : nat -> X :=\n  fun (k : nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 :\n  ftrue 0 = true.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nCheck plus : nat -> nat -> nat.\n\nDefinition plus3 := plus 3.\n\nCheck plus3 : nat -> nat.\n\n\nExample test_plus3 : plus3 4 = 7.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nExample test_plus3' : doit3times plus3 0 = 9.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof.\n  compute.\n  reflexivity.\nQed.\n\n\nModule Exercises.\n  Definition fold_length {X : Type} (l : list X) : nat :=\n    fold (fun _ acc => S acc) l 0.\n    \n  Example test_fold_length1 : fold_length [4;7;0] = 3.\n  Proof.\n    compute.\n    reflexivity.\n  Qed.\n\n  (* Lemma fole_length_: .\n  Proof.\n    \n  Qed. *)\n  \n\n  Theorem fold_length_correct : forall (X : Type) (l : list X),\n    fold_length l = length l.\n  Proof.\n    induction l as [|l'].\n    - simpl.\n      reflexivity.\n    - simpl.\n      rewrite <- IHl. \n      reflexivity.\n  Qed.\n\n  Definition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n    fold (fun h acc => (f h) :: acc) l [].\n  \n  Theorem fold_map_correct :\n    forall (X Y : Type) (f : X -> Y) (l : list X),\n    fold_map f l = map f l.\n  Proof.\n    intros.\n    induction l as [|l'].\n    - simpl.\n      compute.\n      reflexivity.\n    - simpl.\n      rewrite <- IHl.\n      reflexivity.\n  Qed.\n  \n(* \n  It is possible to convert a function between these two types.\n  Converting from X × Y → Z to X → Y → Z is called currying, in\n  honor of the logician Haskell Curry. Converting from X → Y → Z\n  to X × Y → Z is called uncurrying.\n*)\n\n  Definition prod_curry {X Y Z : Type} (f : X * Y -> Z) (x : X)\n                                       (y : Y) : Z :=\n    f (x, y).\n\n  Definition prod_uncurry {X Y Z : Type} (f : X -> Y -> Z)\n                                         (p: X * Y) : Z :=\n    match p with\n    | (x, y) => f x y\n    end.\n  \n  Example test_map1': map (plus 3) [2;0;2] = [5;3;5].\n  Proof.\n    compute.\n    reflexivity.\n  Qed.\n\n  Check @prod_curry.\n  Check @prod_uncurry.\n\n  Theorem uncurry_curry :\n    forall (X Y Z : Type) (f : X -> Y -> Z) (x : X) (y : Y),\n    prod_curry (prod_uncurry f) x y = f x y.\n  Proof.\n    intros.\n    compute.\n    reflexivity.\n  Qed.\n\n  Theorem curry_uncurry :\n    forall (X Y Z : Type) (f : (X * Y) -> Z) (p : X * Y),\n    prod_uncurry (prod_curry f) p = f p.\n  Proof.\n    intros.\n    destruct p.\n    simpl.\n    compute.\n    reflexivity.\n  Qed.\n\n  Theorem nth_err_formal:\n    forall (X : Type) (l : list X) (n : nat),\n    length l = n -> @nth_err X l n = None.\n  Proof.\n    intros.\n    induction l as [|l'].\n    - rewrite <- H.\n      simpl.\n      reflexivity.\n    - rewrite <- H.\n      simpl.\n      rewrite <- IHl.\n  Admitted.\n\nModule Church. \n  Definition cnat :=\n    forall (X : Type), (X -> X) -> X -> X.\n\n  Definition zero : cnat :=\n    fun (X : Type) (succ : X -> X) (zero : X) => zero.\n\n  Definition one : cnat :=\n    fun (X : Type) (succ : X -> X) (zero : X) => succ zero.\n  \n  Definition two : cnat :=\n    fun (X : Type) (succ : X -> X) (zero : X) => succ (succ zero).\n\n  Definition three : cnat := @doit3times.\n  \n\n  Example zero_church_peano : zero nat S O = 0.\n  Proof.\n    compute.\n    reflexivity.\n  Qed.\n\n  Example one_church_peano : one nat S O = 1.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example two_church_peano : two nat S O = 2.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Definition scc (n : cnat) : cnat :=\n    fun (X : Type) (succ : X -> X) (x : X) => succ (n X succ x).\n\n  Example scc_1 : scc zero = one.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example scc_2 : scc one = two.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example scc_3 : scc two = three.\n  Proof.\n    reflexivity.\n  Qed.\n    \n  Definition plus (n m : cnat) : cnat :=\n    fun (X : Type) (succ : X -> X) (x : X) =>\n      n X succ (m X succ 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  Definition mult (n m : cnat) : cnat :=\n    fun (X : Type) (succ : X -> X) (x : X) =>\n      (n X (fun x' => m X succ x')) 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\n  Definition exp (n m : cnat) : cnat :=\n    fun (X : Type) (succ : X -> X) (x : X) =>\n      (m (X -> X) (n X) succ) x.\n\n\n  Example exp_1 : exp two two = plus two two.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example exp_2 : exp three zero = one.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example exp_3 : exp three two = plus (mult two (mult two two)) one.\n  Proof.\n    reflexivity.\n  Qed.\n\nEnd Church.\nEnd Exercises.\n", "meta": {"author": "tor4z", "repo": "SoftwareFoundations", "sha": "ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6", "save_path": "github-repos/coq/tor4z-SoftwareFoundations", "path": "github-repos/coq/tor4z-SoftwareFoundations/SoftwareFoundations-ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6/lf/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.9059898165759307, "lm_q1q2_score": 0.7964980272455381}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Use SSReflect tactics.\n    DO NOT use automation like [tauto], [intuition], [firstorder], etc.,\n    except for [by], [done], [exact] tactic(al)s. *)\n\n\n(** * Exercise *)\nLemma nlem (A : Prop):\n  ~ (A \\/ ~ A) -> A.\nProof.\nrewrite /not.\nmove=> f.\nmove: (f).\ncase.\nright.\nmove=> a.\napply f.\nleft.\ndone.\nQed.\n\n(** Hint: you might want to use a separate lemma here to make progress.\nOr, use the `have` tactic: `have: statement` creates a new subgoal and asks\nyou to prove the statement. This is like a local lemma. *)\n\n\n(** * Exercise *)\nLemma weak_Peirce (A B : Prop) :\n  ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\nmove=> f1.\napply (f1).\nmove=> f2.\napply (f2).\nmove=> a.\napply f1.\nmove=> _.\ndone.\nQed.\n\n\n\n(** * Exercise *)\n(* Prove that having a general fixed-point combinator in Coq would be incosistent *)\nDefinition FIX := forall A : Type, (A -> A) -> A.\n\nLemma fix_inconsistent :\n  FIX -> False.\nProof.\nrewrite /FIX.\napply.\ndone.\nQed.\n\n\nSection Boolean.\n(** * Exercise *)\nLemma negbNE b : ~~ ~~ b -> b.\nProof.\nby case: b; done.\nQed.\n\n\n(** * Exercise *)\nLemma negbK : involutive negb.\nProof.\nrewrite /involutive /cancel.\nby case.  \nQed.\n\n\n(** * Exercise *)\nLemma negb_inj : injective negb.\nProof.\nby case ; case.\nQed.\n\nEnd Boolean.\n\n\n(** * Exercise *)\nFixpoint triple (n : nat) : nat :=\n  if n is n'.+1 then (triple n').+3\n  else n.\n\nLemma triple_mul3 n :\n  triple n = 3 * n.\nProof.\nmove: n.\nelim=> [// | n IHn /=] ; by rewrite mulnS -IHn.\nQed.\n(** Hints:\n- use the /= action to simplify your goal: e.g. move=> /=.\n- use `Search (<pattern>)` to find a useful lemma about multiplication\n*)\n\n(** * Exercise\nProve by it induction: you may re-use the addnS and addSn lemmas only *)\nLemma double_inj m n :\n  m + m = n + n -> m = n.\nProof.\nmove: m n.\nelim=> [| m IHm] ; case=> [| n] //.\nrewrite !addSn !addnS.\ncase=> /IHm -> //.\nQed.\n\n(* This is a harder exercise than the previous ones but\n   the tactics you already know are sufficient *)\n\n\n\n\n(** * Optional exercise\n    [negb \\o odd] means \"even\".\n    The expression here says, informally,\n    the sum of two numbers is even if the summands have the same \"evenness\",\n    or, equivalently, \"even\" is a morphism from [nat] to [bool] with respect\n    to addition and equivalence correspondingly.\n    Hint: [Unset Printing Notations.] and [rewrite /definition] are your friends :)\n *)\nLemma even_add :\n  {morph (negb \\o odd) : x y / x + y >-> x == y}.\nProof.\nAdmitted.\n\n\n(** * Optional exercise *)\nLemma DNE_iff_nppp :\n  (forall P, ~ ~ P -> P) <-> (forall P, (~ P -> P) -> P).\nProof.\nAdmitted.\n\n\n(** * Optional exercise *)\nLemma leq_add1l p m n :\n  m <= n -> m <= p + n.\nProof.\nSearch (_ <= _ + _).\nAdmitted.\n(** Hint: this lemmas does not require induction, just look for a couple lemmas *)\n\n\n\n\n\n(* ================================================ *)\n\n(*\nMore fun with functions, OPTIONAL\n*)\n\nSection PropertiesOfFunctions.\n\nSection SurjectiveEpic.\nContext {A B : Type}.\n\n(* https://en.wikipedia.org/wiki/Surjective_function *)\n(** Note: This definition is too strong in Coq's setting, see [epic_surj] below *)\nDefinition surjective (f : A -> B) :=\n  exists g : B -> A, f \\o g =1 id.\n\n(** This is a category-theoretical counterpart of surjectivity:\n    https://en.wikipedia.org/wiki/Epimorphism *)\nDefinition epic (f : A -> B) :=\n  forall C (g1 g2 : B -> C), g1 \\o f =1 g2 \\o f -> g1 =1 g2.\n\n(** * Optional exercise *)\nLemma surj_epic f : surjective f -> epic f.\nProof.\nAdmitted.\n\n(** * Optional exercise *)\nLemma epic_surj f : epic f -> surjective f.\n  (** Why is this not provable? *)\nAbort.\n\nEnd SurjectiveEpic.\n\n\nSection EpicProperties.\nContext {A B C : Type}.\n\n(** * Optional exercise *)\nLemma epic_comp (f : B -> C) (g : A -> B) :\n  epic f -> epic g -> epic (f \\o g).\nAdmitted.\n\n(** * Optional exercise *)\nLemma comp_epicl (f : B -> C) (g : A -> B) :\n  epic (f \\o g) -> epic f.\nAdmitted.\n\n(** * Optional exercise *)\nLemma retraction_epic (f : B -> A) (g : A -> B) :\n  (f \\o g =1 id) -> epic f.\nAdmitted.\n\nEnd EpicProperties.\n\n\n(** The following section treats some properties of injective functions:\n    https://en.wikipedia.org/wiki/Injective_function *)\n\nSection InjectiveMonic.\n\nContext {B C : Type}.\n\n(** This is a category-theoretical counterpart of injectivity:\n    https://en.wikipedia.org/wiki/Monomorphism *)\nDefinition monic (f : B -> C) :=\n  forall A (g1 g2 : A -> B), f \\o g1 =1 f \\o g2 -> g1 =1 g2.\n\n(** * Optional exercise *)\nLemma inj_monic f : injective f -> monic f.\nProof.\nAdmitted.\n\n\n(** * Optional exercise *)\nLemma monic_inj f : monic f -> injective f.\nProof.\nAdmitted.\n\nEnd InjectiveMonic.\n\n\nSection MonicProperties.\nContext {A B C : Type}.\n\n(** * Optional exercise *)\nLemma monic_comp (f : B -> C) (g : A -> B) :\n  monic f -> monic g -> monic (f \\o g).\nProof.\nAdmitted.\n\n(** * Optional exercise *)\nLemma comp_monicr (f : B -> C) (g : A -> B) :\n  monic (f \\o g) -> monic g.\nProof.\nAdmitted.\n\n(** * Optional exercise *)\nLemma section_monic (f : B -> A) (g : A -> B) :\n  (g \\o f =1 id) -> monic f.\nProof.\nAdmitted.\n\nEnd MonicProperties.\n\nEnd PropertiesOfFunctions.", "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/hw05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8791467627598856, "lm_q1q2_score": 0.7964980199150664}}
{"text": "Require Import Arith.\n\nInductive le' : nat -> nat -> Prop :=\n  | le'_0_p : forall p:nat, le' 0 p\n  | le'_Sn_Sp : forall n p:nat, le' n p -> le' (S n) (S p).\n\nHint Resolve le'_0_p le'_Sn_Sp.\n\nLemma le'_n : forall n : nat, le' n n.\nProof.\n simple induction n; auto.\nQed.\n\nLemma le'_n_Sp : forall n p : nat, le' n p -> le' n (S p).\nProof.\n  simple induction n.\n  auto.\n  intros n0 Hn0 p Hp.\n  inversion_clear Hp.\n  auto.\nQed.\nHint Resolve le'_n le'_n_Sp.\n\nLemma le_le' : forall n p: nat, le n p -> le' n p.\nProof.\n simple induction 1; auto with arith.\nQed.\n\nLemma le'_le : forall n p: nat, le' n p -> le n p.\nProof.\n simple induction n; auto with arith.\n intros n0 Hn0 p; case p.\n inversion 1.\n inversion 1.\n auto with arith.\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/le_prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7964456081478635}}
{"text": "(* Exercise 1 *)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Arith.PeanoNat.\n\n(* 1.1. *)\n\nDefinition tl(l: list nat) : list nat :=\n  match l with\n  | [] => []\n  | h::t => t\nend.  \n\nCompute tl [1;2;3].\n\n(* 1.2. *)\n\nDefinition removelast (l: list nat) : list nat :=\n  match l with\n  | [] => []\n  | h :: t => h :: removelast t\nend.\n\nCompute removelast [1;2;3;4;5].\n\n(* 1.3. *)\n\nDefinition firstn (n: nat) (l: list nat) : list nat :=\n  match n with\n  | O => l\n  | S n' => match l with\n            | [] => []\n            | h :: t => h :: firstn n' t\n            end\nend.\n\nCompute firstn 3 [1;2;3;4;5].\n\n(* 1.4.*)\n\nDefinition skipn (n: nat) (l: list nat) : list nat :=\n  match n with\n  | O => l\n  | S n' => match l with\n            | [] => []\n            | h :: t => skipn n' t\n            end\nend.\n\nCompute skipn 3 [1;2;3;4;5].\n\n(* 1.5.*)\n\nInductive option (X :Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\n\nArguments Some {X} _.\nArguments None {X}.\n\nCheck Some 1.\n\nFixpoint last {X:Type} (l: list X) : option X := \n  match l with\n  | [] => None\n  | h :: [] => Some h\n  | h :: t => last t\nend.\n\nCompute last [].\nCompute last [1;2;3].\n\n(* 1.6.*)\n\nFixpoint seq (start: nat) (len: nat) : list nat :=\n  match len with\n  | 0 => []\n  | S len' => start :: (seq (S start) len')\nend.\n\nCompute seq 3 4. \n\n(* 1.7.*)\n\nFixpoint split {X Y : Type} (l: list (X*Y)) : (list X)*(list Y) :=\n  match l with\n  | [] => ([],[])\n  | (x, y) :: t => (x :: fst (split t), y :: snd (split t))\nend.\n\nCompute split [(1,true);(2,false);(3,true)].\n\nFixpoint split2 {X Y : Type} (l: list (X*Y)) : (list X)*(list Y) :=\n  match l with\n  | [] => ([],[])\n  | (x, y) :: t => let( left, right) := split t in (x:: left, y::right)\nend.\n\nCompute split [(1,true);(2,false);(3,true)].\n\n(* 1.8.*)\n\nFixpoint append { X : Type} (l1: list X) (l2 : list X) : list X :=\n  match l1 with\n  | [] => l2\n  | h :: t => h :: append t l2\nend.\n\nCompute append [1;2;3] [4;5;6].\n\n(* 1.9.*)\n\nFixpoint rev {X : Type} (l: list X) : list X :=\n  match l with\n  | [] => []\n  | h :: t => append (rev t) [h]\nend.\n\nCompute rev [1;2;3].\n\n(* 1.10.*)\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\n                        else existsb test t\nend.\n\nCompute existsb (fun e => e <=? 3) [2;4;5].\nCompute existsb (fun e => e <=? 3) [4;5].\n\n(* 1.11.*)\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\n                        else false\nend.\n\nCompute forallb (fun e => e <=? 3) [1;2;3].\nCompute forallb (fun e => e <=? 3) [1;2;4].\n\n(* 1.12.*)\n\nFixpoint find {X: Type}(test: X -> bool) (l:list X) : option X:=\n  match l with\n  | [] => None\n  | h :: t => if test h then Some h\n                        else find test t\nend.\n\nCompute find (fun e => e <=? 3) [6;4;1;3;7].\nCompute find (fun e => e <=? 3) [6;4;4;5;7].\n\n(* 1.13.*)\n\n\n(* Exercise 2 *)\n\n(* 2.1. *)\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 partition {X: Type} (test: X -> bool) (l: list X) : (list X) * (list X) :=\n  (filter test l , filter (fun e => negb (test e)) l).\n\nCompute partition (fun e => e <=? 3) [6;4;1;3;7].\n\n(* 2.2. *)\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\nFixpoint list_prod {X Y: Type} (l1: list X) (l2: list Y) : list (X*Y) :=\n  match l1 with\n  | [] => []\n  | h1 :: t1 => (map (fun e => (h1 , e)) l2) ++ (list_prod t1 l2)\nend.\n\n(* Duvida *)\n\nCompute list_prod [1; 2] [true; false].\n\n\n(* 2.3. *)\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\nDefinition length {X : Type} (l: list X) : nat :=\n  fold (fun e c => c + 1) l 0.\n\nCompute length [6;4;1;3;7].\n\n(* 2.4. *)\n\nDefinition new_map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  fold (fun x y => f x :: y) l [].\n\n\nFixpoint list_prod' {X Y: Type} (l1: list X) (l2: list Y) : list (X*Y) :=\n  match l1 with\n  | [] => []\n  | h1 :: t1 => (new_map (fun e => (h1 , e)) l2) ++ (list_prod t1 l2)\nend.\n\nCompute list_prod' [1; 2] [true; false].\n\n(* 2.5. *)\n\nDefinition new_filter {X:Type} (test: X->bool) (l:list X): (list X) :=\n  fold (fun x y => if test x then x :: y else y ) l [].\n\nFixpoint partition' {X: Type} (test: X -> bool) (l: list X) : (list X) * (list X) :=\n  (filter test l , new_filter (fun e => negb (test e)) l).\n\nCompute partition' (fun e => e <=? 3) [6;4;1;3;7].\n\n(* 2.6. *)\n\nCheck andb.\n\nDefinition new_forallb {X: Type} (test: X -> bool) (l: list X) : bool :=\n  fold andb (map test l) true.\n\nCompute new_forallb (fun e => e <=? 3) [1;2;3].\nCompute new_forallb (fun e => e <=? 3) [1;2;4].\n\n(* Exercise 3 *)\n\n(* 3.1. *)\n\nTheorem thm_simpl1: forall a b c:nat,\n    a = 0 -> b*(a+b) = b*b.\nProof.\n  intros.\n  rewrite -> H.\n  simpl.\n  reflexivity.\nQed.\n\n(* 3.2. *)\n\nTheorem thm_simpl2: forall (a b c d:nat) (f: nat -> nat -> nat),\n    a=b -> c=d -> (forall x y, f x y = f y x) -> f a c = f d b.\nProof.\n  intros.\n  rewrite -> H1.\n  rewrite -> H.\n  rewrite -> H0.\n  reflexivity.\nQed.\n\n(* 3.3. *)\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\n(* 3.4. *)\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. rewrite H.\n  \n  rewrite identity_fn_applied_twice.\n  -reflexivity.\n  - intros.\n    rewrite H.\n\n\n", "meta": {"author": "ChikoGitHub", "repo": "LProg", "sha": "46a9c3ee4717c9116fc4a6d6fd7d36ccc00c41d3", "save_path": "github-repos/coq/ChikoGitHub-LProg", "path": "github-repos/coq/ChikoGitHub-LProg/LProg-46a9c3ee4717c9116fc4a6d6fd7d36ccc00c41d3/Praticas/AP2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.9263037277508773, "lm_q1q2_score": 0.7963097367096361}}
{"text": "(** * Rel: Properties of Relations *)\n\nRequire Export SfLib.\n\n(** This short, optional chapter develops some basic definitions and a\n    few theorems about binary relations in Coq.  The key definitions\n    are repeated where they are actually used (in the [Smallstep]\n    chapter), so readers who are already comfortable with these ideas\n    can safely skim or skip this chapter.  However, relations are also\n    a good source of exercises for developing facility with Coq's\n    basic reasoning facilities, so it may be useful to look at it just\n    after the [Logic] chapter. *)\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(** 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(* ====> 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\n(* ######################################################### *)\n(** * Basic Properties of Relations *)\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    ways of classifying relations (are they reflexive, transitive,\n    etc.), theorems that can be proved generically about classes of\n    relations, constructions that build one relation from another,\n    etc.  For example... *)\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 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 function.\n    In short: 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   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 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] defined earlier is a partial\n    function. *)\n\n(* FILL IN HERE *)\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\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 ->\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    another chapter.  You can ignore them if you haven't read the\n    explanation 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  (* 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(** $Date: 2014-12-31 15:31:47 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "elfi", "repo": "sf", "sha": "169c89f59bec1415ddf8d290a40c533d19f862d5", "save_path": "github-repos/coq/elfi-sf", "path": "github-repos/coq/elfi-sf/sf-169c89f59bec1415ddf8d290a40c533d19f862d5/orig_files/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.7962901872221805}}
{"text": "From LF Require Export Basics.\n\n(*\n * PROOF BY INDUCTION\n *)\n\n(* Let's recap the definition of `plus`... *)\n\nModule plus_recap.\n    Fixpoint plus (a b : nat) : nat :=\n        match a with\n        | O => b\n        | S n' => S (plus n' b)\n        end.\n\n    Example test_plus'_1 : plus 2 3 = 5.\n    Proof. reflexivity. Qed.\nEnd plus_recap.\n\n(* By that definition, the simplification of `plus` depends on the parameter\n * `a`. Let's try to prove the neutrality of `0` when it is passed on the left.\n *)\n\nTheorem add_0_l : forall n : nat, 0 + n = n.\nProof.\n    (* This simplification is quite trivial. Recall the definition. When applied\n     * on the left, the zero will be simply pattern matched which will, in turn,\n     * return the right-hand side argument (in our theorem, `n`).\n     *)\n    simpl.\n    reflexivity.\nQed.\n\n(* However, when the `0` is on the right, things aren't so simple. Not because\n * of the zero on the right-hand side, but because of `n` on the left side.\n *)\n\nTheorem add_0_r_first_try : forall n : nat, n + 0 = n.\nProof.\n    (* This simplification does nothing. Well, that's quite fair. How would you\n     * simplify the expression `n + 0` by that `plus` definition? Since `n` is\n     * arbitrary (i.e. `n` can be any of the natural numbers), it could be\n     * `O` or even `S n'`, being `n'` another arbitrary natural number.\n     *)\n    simpl.\nAbort.\n\n(* We can not even use something like `destruct` to solve this problem since,\n * when destructing `n: nat`, we would get `S n'`, being `n'` another arbitrary\n * natural number. If we try to `destruct` again, we'd get `S (S n'')`, which\n * also didn't help much. The `match` definition can't be simplified.\n *\n * You can see some kind of “growing recursion” pattern here. Indeed, natural\n * numbers may be inductively defined!\n *\n * Hence, most proofs on inductively-defined types also need to be implemented\n * using induction, a more powerful reasoning technique.\n *\n * For example, if we want to prove some proposition `P(n)` for all natural\n * numbers, we may proceed with induction as follows:\n *\n *   - Show that `P(O)` holds;\n *   - Show that, for any `n'`, if `P(n')` holds, then so does `P(S n')`;\n *   - Conclude that `P(n)` holds for all `n: nat`.\n *\n * In Coq, we may use the `induction` tactic to break a goal involving some\n * `n: nat` into two sub-goals:\n *\n *   - One to show `P(O)`;\n *   - One to show `P(n') -> P(S n')`.\n *)\n\nTheorem add_0_r : forall n : nat, n + 0 = n.\nProof.\n    intros n.\n    (* The `induction` tactic will break `n + 0 = n` into two sub-goals:\n     *   - `0 + 0 = 0`, the base case (`P(O)`);\n     *   - `n' + 0 = n' -> S n' + 0 = S n'`, (`P(n') -> P(S n')`).\n     *)\n    induction n as [| n' IHn' (* Induction hypothesis for n' *)].\n    - reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nTheorem mul_0_r : forall n : nat,\n  n * 0 = 0.\nProof.\n    intros n.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n    intros n m.\n    induction n as [| n' IHn'].\n    - 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.\n    induction n as [| n' IHn'].\n    - 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.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\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\n(* Exercise *)\n\nCheck negb_involutive: forall b : bool, negb (negb b) = b.\n\nTheorem even_S : forall n : nat,\n  even (S n) = negb (even n).\nProof.\n    induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - rewrite -> IHn'.\n      simpl.\n      rewrite -> negb_involutive.\n      reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\n(* Briefly explain the difference between the tactics `destruct` and\n * `induction`.\n *)\n\n(* At first glance, both tactics appear similar. Indeed, both break an\n * inductively-defined type over two N sub-goals, one for each constructor.\n *\n * However, `destruct` simply “breaks” a variable over its constructors, doing\n * nothing more than that. Indeed, it may be useful to prove definitions that\n * “go up”.\n *\n * On the other hand, `induction` is more powerful since, besides breaking a\n * variable over its constructors, it also creates assumptions that facilitate\n * proving some property for all possible values of a given inductively-defined\n * type. In general it is useful to prove definitions that “go down”.\n *\n * I should note that I am not still 100% sure about that “up” and “down”\n * metaphors. I might amend or even remove them later.\n *)\n\nDefinition manual_grade_for_destruct_induction : option (nat * string) := None.\n\n(******************************************************************************)\n\n(*\n * PROOFS WITHIN PROOFS\n *)\n\n(* Sometimes it is useful to create a “proof within a proof”. For example, it\n * may be desirable to not pollute the top-level environment with a name that\n * won't be reused in another place.\n *\n * In such cases, the `assert` tactic may be used. It essentially asserts a\n * named assertion and introduces two sub-goals. The first one that is used to\n * prove assertion. The second sub-goal being the original goal (i.e. the one\n * before the `assert`, but with the proven assertion on its context).\n *\n * The `assert` tactic can also be used as a technique to better specify where\n * the `replace` tactic should act on.\n *\n * One may also use the `replace` tactic as an alternative to the combination of\n * the `assert` and `rewrite` tactics. The former takes the following form:\n *\n *     replace (a) with (b).\n *\n * It will generate two sub-goals, a) the expression with (a) is in place of (b)\n * and (b) is in place of (a); and b) a goal where `a = b`.\n *)\n\nTheorem plus_rearrange_first_try : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* Here we only want to rewrite `n + m` as `m + n`. However, `replace` is also\n   * rewriting `p + q`, which is not desirable here.\n   *)\n  rewrite add_comm.\nAbort.\n\n(* So we may use `assert` to specify where the rewrite should take place. And\n * prove such assertion with the `add_comm` theorem. *)\n\n Theorem 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    (* Here we prove the assertion. *)\n    rewrite -> add_comm. reflexivity.\n  }\n  (* Here we prove the original goal with the given assertion in the context.*)\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(******************************************************************************)\n\n(*\n * MORE EXERCISES\n *)\n\n(******************************************************************************)\n\n(* Exercises *)\n\nTheorem add_shuffle3 : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  do 2 (rewrite -> add_assoc).\n  assert (H: n + m = m + n). { rewrite -> add_comm. reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* Helper *)\nTheorem mul_n_0 : forall n : nat, n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(* Helper *)\nTheorem mul_n_Sm : forall n m : nat,\n  n * (S m) = n + n * m.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> add_shuffle3. reflexivity.\nQed.\n\nTheorem mul_comm : forall n m : nat,\n  n * m = m * n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - rewrite -> mul_n_0. reflexivity.\n  - simpl. rewrite -> mul_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nCheck leb: nat -> nat -> bool.\n\n(* Guess: Induction; equal comparison is at the bottom, ref. “go down”. *)\nTheorem leb_refl : forall n : nat,\n  (n <=? n) = true.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(* Guess: Simplification; this case is covered in the def. with “depth 1”. *)\nTheorem zero_neqb_S : forall n : nat,\n  0 =? (S n) = false.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\n(* Guess: Case analysis; since first argument is matched first. *)\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Guess: Simplification and rewriting; since has assumption. *)\nTheorem plus_leb_compat_l : forall n m p : nat,\n  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\n  intros n m p H.\n  induction p as [| n' IHn'].\n  - simpl. rewrite -> H. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed. (* Wrong guess. *)\n\n(* Guess: Simplification; this case is covered in the def. with “depth 1”. *)\nTheorem S_neqb_0 : forall n : nat,\n  (S n) =? 0 = false.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\n(* Guess: Induction; `n` (on the right) won't match with “depth 1”. *)\nTheorem mult_1_l : forall n : nat, 1 * n = n.\nProof.\n  intros n. simpl.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(* Guess: Case analysis; bool is not really a inductively-defined type. *)\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 eqn:Eb.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\n(* Guess: Induction. *)\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' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> add_assoc. reflexivity.\nQed.\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.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> mult_plus_distr_r. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\nTheorem eqb_refl : forall n : nat,\n  (n =? n) = true.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\nTheorem add_shuffle3' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  do 2 (rewrite -> add_assoc).\n  replace (n + m) with (m + n).\n  - reflexivity.\n  - rewrite -> add_comm. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\n(* Taken from `Basics.v`, repeated for convenience. *)\nInductive bin : Type :=\n  | Z\n  | B0 (n : bin)\n  | B1 (n : bin).\n\n(* Taken from `Basics.v`, repeated for convenience. *)\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\n(* Taken from `Basics.v`, repeated for convenience. *)\nFixpoint decr (m : bin) : bin :=\n  match m with\n  | Z => Z\n  | B0 m' => B1 (decr m')\n  | B1 Z => Z\n  | B1 m' => B0 m'\n  end.\n\n(* Taken from `Basics.v`, repeated for convenience. *)\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\n(* Theorem bin_to_nat_pres_incr : forall b : bin,\n  S (bin_to_nat b) = bin_to_nat (incr b).\nProof.\n  intros b.\n  induction b as [| b0' IHb0' | b1' IHb1'].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite <- IHb1'.\n    simpl.\n    rewrite plus_n_Sm.\n    reflexivity. *)\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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.7962901775627169}}
{"text": "Require Import List.\n\nInductive quicksort1 : list nat -> list nat -> Prop :=\n| Q1nil: quicksort1 nil nil\n| Q1cons (head : nat) (tail l r : list nat) :\n    quicksort1 (filter (fun x => Nat.ltb x head) tail) l ->\n    quicksort1 (filter (fun x => Nat.leb head x) tail) r ->\n    quicksort1 (head :: tail) (l ++ (cons head nil) ++ r).\n\nInductive quicksort2 : list nat -> list nat -> Prop :=\n| Q2nil: quicksort2 nil nil\n| Q2cons (head : nat) (tail l r : list nat) :\n    quicksort2 (filter (fun x => Nat.leb x head) tail) l ->\n    quicksort2 (filter (fun x => Nat.ltb head x) tail) r ->\n    quicksort2 (head :: tail) (l ++ (cons head nil) ++ r).\n\nDefinition task :=\n  forall x ret1 ret2, quicksort1 x ret1 -> quicksort2 x ret2 -> ret1 = ret2.\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/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7961997638658319}}
{"text": "Require Import Basics.\n\n(* Check that below three functions are working. *)\n(* If they don't work, run build.sh *)\nCheck test.\nCheck true || true.\nCheck Basics.test.\n\n(* The function should return true if either or both of its inputs are false. *)\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match (b1, b2) with\n  | (false, false) => true\n  | (false, _) => true\n  | (_, false) => true\n  | _ => false\n  end.\n\nExample test_nandb2: (nandb false false) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb1: (nandb true 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\n(* This function should return true when all of its inputs are true, and false otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool := andb (andb b1 b2) b3.\n\n(* This doesn't work unless symbols are defined in that module. Why ? *)\n(* Definition andb3_symbol (b1:bool) (b2:bool) (b3:bool) : bool := b1 && b2 && b3. *)\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_andb34: (andb3 true true false) = false.\nProof. reflexivity. Qed.\n\nCheck negb.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => S O\n    | S p => mult n (factorial p)\n  end.\n\nCompute (factorial 5).\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(* The blt_nat function tests natural numbers for less-than, yielding a boolean. *)\n\nFixpoint blt_nat_rec (n m : nat) : 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_rec n' m'\n  end.\n\nCheck test.\n\nDefinition blt_nat (n m : nat) : bool := \n  match (n,m) with\n    | (O,O) => false\n    | _ => if (beq_nat n m)\n           then false\n           else leb n m\n  end.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. 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. reflexivity. Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H1.\n  intros H2.\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity.\nQed.\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 -> plus_1_l.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c.\n  intros H.\n  destruct c.\n  reflexivity.\n  rewrite <- H.\n  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.\n  destruct n.\n  - simpl.\n    reflexivity.\n  - simpl.\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 H1 b.\n  rewrite -> H1.\n  rewrite -> H1.\n  reflexivity.\nQed.\n\nLemma andb_true_l : forall (b : bool), (true && b) = b.\nProof.\n  intros b.\n  destruct b.\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_true_l.\n  destruct c.\n  reflexivity.\n  simpl. simpl. intros H1. rewrite -> H1. reflexivity.\n  destruct c.\n  simpl. intros H1. rewrite -> H1. reflexivity.\n  simpl. reflexivity.\nQed.\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/chapter1/Exercise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7961454059747678}}
{"text": "From mathcomp Require Import ssreflect.\n\nModule Lesson1.\n\nInductive bool : Type := \n| true\n| false.\n\nCheck false : bool.\nCheck false.\n\nCheck bool : Type.\nCheck (bool -> bool) : Type.\nCheck (fun (b : bool) => b) : (bool -> bool). (* Lambda  id *)\nCheck (fun t: Type => t): (Type -> Type).\nCheck ((fun t: Type => t) bool): Type.\n\nCheck (fun b => b).\n\nCheck ((fun b => b) true).\n\nCheck (fun (f : bool -> bool) => f true).\n\nCompute (fun b : bool => b) true.\n\n\nDefinition idb := (fun b : bool => b).\n\nCheck idb.\nCheck idb true : bool.\nCheck (fun (f : bool -> bool) => f true) idb.\n\nFail Check (fun (f : bool -> bool) => f true) false.\n\n\n\nDefinition negb :=\n  fun (b: bool) =>\n    match b with\n    | true => false\n    | false => true\n    end.\n\nCheck negb true : bool.\n\n(* cbv - call by value *)\nEval cbv beta delta in negb true.\n\nVariable c : bool.\n\nCompute negb c.\n\n\nDefinition andb (b c : bool) : bool :=\n  match b with\n  | false => false\n  | true => c\n  end.\n\nDefinition andb' (b c : bool) : bool :=\n  match c with\n  | false => false\n  | true => b\n  end.\n\nDefinition orb (b c : bool) : bool :=\n  match b with \n  | true => true\n  | false => c\n  end.\n\nCompute orb true false.\nCompute orb false false.\nCompute orb false true.\n\n\nDefinition eqb (b c : bool) : bool := \n  match (b, c) with \n  | (true, true) => true\n  | (false, false) => true\n  | (_, _) => false\n  end.\n\n\n\n\n\n\n\nInductive nat : Type :=\n| Z\n| S of nat. (* 'of' taken from ssreflect, S : nat -> nat*)\n\nInductive nat2 : Type :=\n| Z2 : nat2\n| S2 : nat2 -> nat2.\n\n\nCheck S Z.\n\nDefinition succn := S.\n\nCompute succn (S Z).\n\n\nDefinition predn' (n : nat) : nat :=\n  match n with \n  | S m => m\n  | Z => Z\n  end.\n\n(*\n  Definition predn : forall n : nat, (n <> Z) -> nat := \n    match n with \n    | S m => m\n    | Z => Z\n    end.\n*)\n\n(* {struct n} indicates which parameter recursion run on *)\nFixpoint addn (n m : nat) {struct n} : nat :=\n  match n with \n  | Z => m\n  | S n' => S (addn n' m)\n  end.\n\nCompute addn (S Z) (S Z).\n\nFixpoint addn' (n m : nat) : nat :=\n  if n is S n' then S (addn' n' m) else m.\n\nDefinition addn_no_sugar := \n  fix addn (n m : nat) {struct n} : nat :=\n    match n with \n    | Z => m\n    | S n' => S (addn n' m)\n    end.\n\n\nFail Fixpoint addn_loop (n m : nat) {struct n} : nat :=\n  if n is S n' then addn_loop n m else m.\n\nFixpoint is_even (n : nat) : bool := \n  if n is S n' then is_odd n' else true\nwith is_odd (n : nat) : bool := \n  if n is S n' then is_even n' else false.\n\nCompute is_even (S (S (S Z))).\nCompute is_even (S (S Z)).\nCompute is_odd (S (S (S Z))).\nCompute is_odd (S (S Z)).\n\nDefinition dec2 (n : nat) : nat :=\n  match n with \n  | S (S n') => n'\n  | _ => Z\n  end.\n\nCompute dec2 (S(S(S(Z)))).\nCompute dec2 (S(S Z)).\nCompute dec2 (S Z).\n\n\nFixpoint subn (m n : nat) {struct m} : nat :=\n  match (m, n) with\n  | (m, Z) => m\n  | (Z, n) => Z\n  | (S m', S n') => subn m' n'\n  end.\n\nCompute subn Z Z.\nCompute subn (S Z) Z.\nCompute subn (S Z) (S Z).\nCompute subn (S (S Z)) (S Z).\nCompute subn (S Z) (S (S Z)).\n\nFixpoint muln (m n : nat) : nat :=\n  match n with \n  | Z => Z\n  | S Z => m\n  | S n' => addn m (muln m n')\n  end.\n\nCompute muln Z Z.\nCompute muln (S Z) Z.\nCompute muln (S Z) (S Z).\nCompute muln (S (S Z)) (S Z).\nCompute muln (S (S Z)) (S (S Z)).\n\nFixpoint leq (m n : nat) : bool :=\n  match (m, n) with\n  | (Z, Z) => true\n  | (Z, _) => true\n  | (_, Z) => false\n  | (S m', S n') => leq m' n'\n  end.\n\nCompute leq Z Z.\nCompute leq (S Z) Z.\nCompute leq (S Z) (S Z).\nCompute leq (S (S Z)) (S Z).\nCompute leq (S (S Z)) (S (S Z)).\nCompute leq (S Z) (S (S Z)).\n\nFixpoint divn_helper (m n rest acc: nat) {struct m} : nat := \n  match (m, rest) with\n  | (S m', S Z) => divn_helper m' n n (S acc)\n  | (S m', S rest') => divn_helper m' n rest' acc\n  | (S _, Z) => Z\n  | (Z, Z) => S acc\n  | (Z, _) => acc\n  end.\n\nDefinition divn (m n : nat) : nat :=\n  divn_helper m n n Z.\n\nCompute divn (S (S Z)) (S Z).\n\n\nEnd Lesson1.\n\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/comp_sci_club-formal_verif_2021/Lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.7961037059036989}}
{"text": "Inductive N : Set :=\n  | zero : N\n  | succ : N -> N.\n\nFixpoint plus (m n : N) :=\n  match m with\n    | zero => n\n    | succ m' => succ (plus m' n)\n  end.\n\nLemma plus_succ: forall m n, succ (plus n m) = plus n (succ m).\nProof.\n  intros.\n  induction n.\n  auto.\n  simpl.\n  f_equal.\n  assumption.\nQed.\n\nLemma plus_n_zero: forall n, n = plus n zero.\nProof.\n  induction n.\n  auto.\n  simpl.\n  f_equal.\n  assumption.\nQed.\n\nTheorem plus_comm: forall m n, plus m n = plus n m.\nProof.\n  intros.\n  induction m.\n  simpl.\n  apply plus_n_zero.\n  simpl.\n  rewrite IHm.\n  apply plus_succ.\nQed.\n\nPrint plus_comm.\n", "meta": {"author": "glsscnnn", "repo": "sumbullshit", "sha": "326e545889303b4bb34e1ff9e52881c29185c2c3", "save_path": "github-repos/coq/glsscnnn-sumbullshit", "path": "github-repos/coq/glsscnnn-sumbullshit/sumbullshit-326e545889303b4bb34e1ff9e52881c29185c2c3/comm_plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7960605737595029}}
{"text": "Require Import Lia.\nRequire Import Bool.\nRequire Import List.\nRequire Import Arith.Arith.\nImport ListNotations.\n\nRequire Extraction.\n\n(** * Heading test *)\n\n(** Define extraction to Ocaml. *)\n(** Quite unsafe! *)\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\" ].\n\nEnd ExtractionDefs.\n\n(** https://codeforces.com/contest/1519/problem/A *)\n\nDefinition absLeq (x y d : nat) := x-y <= d /\\ y-x <= d.\n\nDefinition can_distribute (r b d : nat) : bool :=\n  (b <=? (r * (d + 1))) && (r <=? (b * (d + 1))).\n\n(** Define problem specification *)\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\nModule InductiveSpec.\nInductive correct_distribution (d : nat) : nat -> nat -> Prop :=\n  | no_packets : correct_distribution d 0 0\n  | add_packet : forall r b r' b',\n      correct_distribution d r b ->\n      r' > 0 ->\n      b' > 0 ->\n      absLeq r' b' d ->\n      correct_distribution d (r'+r) (b'+b).\nHint Constructors correct_distribution : core.\n\nLemma distribution_flip : forall r b d,\n  correct_distribution d r b <-> correct_distribution d b r.\n  assert (H:forall r b d, correct_distribution d r b -> correct_distribution d b r). { \n  intros r b d H.\n  induction H.\n  - auto.\n  - constructor; auto. unfold absLeq 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 d r b.\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 absLeq; try apply IHr; try lia. \nQed.\n\nDefinition algorithm_iff_correct_distribution := \n  forall r b d, \n    can_distribute r b d = true <-> correct_distribution d r b.\nTheorem algorithm_correct : algorithm_iff_correct_distribution.\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 d_bound; unfold absLeq in H2; try lia.\nQed.\n\nEnd InductiveSpec.\n\nModule ListSpec.\n  \n(** Prove that our program returns true if and only if there exists a correct distribution. *)\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\n(** There exists a *correct distribution* for (r,b,d) if and only if there exists a set of packets which sum to (r,d), where each packet has a nonzero number of red and blue elements. *)\nDefinition correct_distribution (r b d : nat) :=\n  exists l, packet_sum l = (r,b) /\\ Forall (fun '(x,y) => absLeq x y d /\\ x > 0 /\\ y > 0) l.\n\nExample ex1 : correct_distribution 1 1 0.\nProof.\n  exists [(1,1)].\n  split; unfold absLeq; auto.\n  repeat constructor; lia.\nQed.\n\nExample ex2 : correct_distribution 2 7 3.\nProof.\n  exists [(1,4);(1,3)].\n  split; unfold absLeq; auto.\n  repeat constructor; lia.\nQed.\n\n(** We can exchange the uses of r and b: *)\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 absLeq in *; try lia.\n  }\n  split; apply H.\nQed.\n\n(** The crucial lemma proving that our algorithm's conditions is sufficient: *)\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 absLeq; 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\nDefinition algorithm_iff_correct_distribution := \n  forall r b d, \n    can_distribute r b d = true <-> correct_distribution r b d.\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  - 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 absLeq in H1.\n      split; apply d_bound; lia.\nQed.\nEnd ListSpec.\n\n\n(** Extract the program to Ocaml. \n   See sol.ml for the boilerplate input/output plumbing. *)\nExtraction \"imp.ml\" can_distribute.\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/1519A/CF_1519A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.795961290104491}}
{"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 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 :\nforall (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 :\nforall (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 :\nforall (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 :\nforall (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 :\nforall (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 :\nforall (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 :\nforall (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 :\nforall (k:Z), (even (2%Z * k)%Z).\nProof.\nintros k.\nnow exists k.\nQed.\n\n(* Why3 goal *)\nLemma odd_2k1 :\nforall (k:Z), (odd ((2%Z * k)%Z + 1%Z)%Z).\nProof.\nintros k.\nnow exists k.\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/number/Parity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7959612859502003}}
{"text": "Require Import ZArith.\nRequire Import QArith.\nOpen Scope Q_scope.\n\nInductive Seq (T:Set) := mkSeq (seq_elt:nat->T).\nDefinition elt {T:Set} (seq: Seq T) n := match seq with\n                                         | mkSeq _ f => f n\n                                         end.\n\nInductive converging_qseq: Seq Q -> Prop :=\n ex_limit (s:Seq Q) (a:Q) (H: forall eps:Q, eps>0 -> exists (n0:nat), forall (n:nat), (n0 <= n)%nat -> a - eps < elt s n /\\\n                                                                       a + eps > elt s n)\n : converging_qseq s.\n\nDefinition qseq_const := fun a => mkSeq Q (fun n => a).\nDefinition qseq_plus sx sy := mkSeq Q (fun n => elt sx n + elt sy n).\n\n\nOpen Scope Q_scope.\nLemma lt_lower: forall a p, p > 0 -> a - p < a.\nProof. intros. unfold Qminus. rewrite <- Qplus_0_r with (x:=a) at 2.\n       rewrite Qplus_comm. rewrite (Qplus_comm a 0). apply (Qplus_lt_le_compat (-p) 0 a a ).\n       - unfold Qlt. simpl. rewrite Z.mul_comm. rewrite (Z.mul_1_l (-Qnum p)).\n         unfold Qlt in H. simpl in H. rewrite Z.mul_comm in H. rewrite (Z.mul_1_l (Qnum p)) in H.\n         apply Z.opp_lt_mono. rewrite Z.opp_involutive. rewrite Z.opp_0. exact H.\n       - apply Z.le_refl.\nQed.\n\nTheorem converging_const: forall a, converging_qseq (qseq_const a).\nProof. intros. apply (ex_limit (qseq_const a) a).\n       intros eps Heps. exists 0%nat. intros.\n       split.\n       - simpl. apply lt_lower. exact Heps.\n       - simpl. rewrite <- Qplus_0_l at 1.  rewrite (Qplus_comm a eps). rewrite Qplus_lt_l. exact Heps.\nQed.\n\n\nLemma split_halfs: forall a, a == a * (1#2) + a * (1#2).\nProof. intros. ring_simplify. easy.\nQed.\n\nLemma dswap: forall a b c d, a+b+c+d == (a+c) +(b+d).\n  intros. ring_simplify. easy.\nQed.\n\nTheorem converging_sum: forall s1 s2, converging_qseq s1 -> converging_qseq s2 -> converging_qseq (qseq_plus s1 s2).\nProof. intros s1 s2 H1 H2. destruct H1 as [s1 a Ha]. destruct H2 as [s2 b Hb].\n       apply (ex_limit (qseq_plus s1 s2) (a+b)). intros.\n\n       assert (0 < 1#2) as Heps2. { unfold Qlt. simpl. apply Z.lt_0_1. }\n       assert (HH := Qmult_lt_compat_r 0 eps (1#2) Heps2 H).  rewrite Qmult_0_l in HH.\n       assert (Ha := Ha (eps * (1#2) ) HH).\n       assert (Hb := Hb (eps * (1#2) ) HH).\n       destruct Ha as [na Ha]. destruct Hb as [nb Hb].\n       set (mab := max na nb).\n       exists mab. intros n Hmax.\n\n       split.\n       (* lower bound *)\n       - rewrite (split_halfs eps) at 1. unfold Qminus. rewrite Qopp_plus. rewrite Qplus_assoc.\n         rewrite dswap. simpl.\n         apply Qplus_lt_le_compat.\n         + apply Ha.  apply Nat.le_trans with (m:= mab). apply Nat.le_max_l. exact Hmax.\n         + unfold Qminus in Hb. apply Qlt_le_weak. apply Hb.\n           apply Nat.le_trans with (m:= mab). apply Nat.le_max_r. exact Hmax.\n       (* upper bound *)\n       - rewrite (split_halfs eps). rewrite Qplus_assoc, dswap.\n         apply Qplus_lt_le_compat.\n         + apply Ha. apply Nat.le_trans with (m:= mab). apply Nat.le_max_l. exact Hmax.\n         + apply Qlt_le_weak. apply Hb. apply Nat.le_trans with (m:= mab). apply Nat.le_max_r. exact Hmax.\nQed.\n\n", "meta": {"author": "akamaus", "repo": "coq_experiments", "sha": "e21b67cf6be5f0b1ab2d186e825e12a95b92973d", "save_path": "github-repos/coq/akamaus-coq_experiments", "path": "github-repos/coq/akamaus-coq_experiments/coq_experiments-e21b67cf6be5f0b1ab2d186e825e12a95b92973d/limits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.7959405520527095}}
{"text": "Require Import FSets.\nRequire Import FSetAVL.\nRequire Import ZArith.\nRequire Import Omega.\nOpen Scope Z_scope.\nSet Implicit Arguments.\n\n(** For the purpose of the demo, let's show how basic things are defined, \n    without interfering with Coq's stdlib, thanks to the following module. *)\nModule LOCAL.\n\n(** * Ordered types *)\n\n(* Starting point: the OrderedType interface of Ocaml: \n\nmodule type OrderedType =\n  sig\n    type t\n    val compare : t -> t -> int\n  end\n*)\n\n(* The corresponding OrderedType in Coq: *)\n\n(*excerpt from OrderedType.v *)\nInductive Compare (X : Type) (lt eq : X -> X -> Prop) (x y : X) : Type :=\n  | LT : lt x y -> Compare lt eq x y\n  | EQ : eq x y -> Compare lt eq x y\n  | GT : lt y x -> Compare lt eq x y.\n\nExtraction Compare.\n\nModule Type OrderedType.\n\n  Parameter t : Type.\n\n  Parameter eq : t -> t -> Prop.\n  Parameter lt : t -> t -> Prop.\n\n  Axiom eq_refl : forall x : t, eq x x.\n  Axiom eq_sym : forall x y : t, eq x y -> eq y x.\n  Axiom eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Axiom lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Axiom lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n\n  Parameter compare : forall x y : t, Compare lt eq x y.\n\nEnd OrderedType.\n(*/excerpt*)\n\n\n\n(** * An example of OrderedType : *)\n(** [Z] integers seen as Orderered Types : Z_as_OT *)\n\n(* excerpt from OrderedTypeEx.v *)\nModule Z_as_OT <: OrderedType.\n\n  Definition t := Z.\n  Definition eq (x y:Z) := (x=y).\n  Definition lt (x y:Z) := (x<y).\n\n  Section xyz.\n  Variables x y z : Z.\n\n  Lemma eq_refl : x=x .  \n  Proof. auto. Qed.\n\n  Lemma eq_sym : x=y -> y=x.\n  Proof. auto. Qed.\n\n  Lemma eq_trans : x=y -> y=z -> x=z.\n  Proof. auto with zarith. Qed.\n\n  Lemma lt_trans : x<y -> y<z -> x<z.\n  Proof. auto with zarith. Qed.\n\n  Lemma lt_not_eq : x<y -> ~ x=y.\n  Proof. auto with zarith. Qed.\n\n  Definition compare : Compare lt eq x y.\n  Proof.\n    case_eq (x ?= y); intros.\n    apply EQ; unfold eq; apply Zcompare_Eq_eq; auto.\n    apply LT; unfold lt, Zlt; auto.\n    apply GT; unfold lt, Zlt; rewrite <- Zcompare_Gt_Lt_antisym; auto.\n  Defined.\n\n  End xyz.\nEnd Z_as_OT.\n(* /excerpt *)\n\n(* Extraction Z_as_OT. Extraction under a module that dont work for the moment *)\n\nEnd LOCAL.\n\nExtraction LOCAL.Z_as_OT.\n\n\n\n(** * Let's now build some sets of [Z] integers ... *)\n\nModule M := FSetAVL.Make(Z_as_OT).\n\n(* This module M provides plenty of functions on Z-sets *)\nCheck M.add.\n\n(* Let's play with them : *)\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.\nEval compute in (M.mem 2 ens3).\nEval compute in (M.elements ens3).\n\n(* M also provides some basic properties, for instance: *)\nCheck (M.elements_3 ens3). \n(* elements always returns a sorted list\n   with respect to the underlying order. *)\n\n(* The M.t type for sets is meant to be used as an abstract type \n   since it will vary amongst the different implementations of FSets. \n   An M.t can and should always be inspected by using [mem], [elements], etc.\n   But for once, let's have a look at the raw aspect of a set: *)\nSet Printing Implicit.\nImport M.MSet.Raw.\nEval compute in ens1.\n(* Here for FSetAVL, a set is a pair of a tree (see 1st line) and some proofs *)\nEval compute in ens3. (* The proofs parts can grow quite fast *)\nUnset Printing Implicit.\n\n(* Here, in order to avoid the continuous expansion of proofs parts, \n   we can work on \"pure\" or \"raw\" datatypes \n   (i.e. without built-in invariants). *)\nModule R:=M.MSet.Raw.\n\nDefinition raw1 := R.add 3 (R.add 0 (R.add 2 R.empty)).\nDefinition raw2 := R.add 0 (R.add 2 (R.add 4 R.empty)).\nDefinition raw3 := R.inter raw1 raw2.\n\nEval compute in raw3.\nEval compute in (R.elements raw3).\n\n(* ... but then there is more work for deriving properties. *)\n\nInstance : Ok raw3.\nProof. unfold raw3; auto with *. Qed.\n\nCheck (elements_spec1 raw3).\nCheck (@elements_spec2 raw3 _).\n\n\n\n\n(** * union *)\n\n(* This function is now based on a structural recursion.\n   It used to be a well-founded one (via Function's measure), \n   for this version see FSetFullAVL. *)\nEval vm_compute in (@R.union raw1 raw2).\n\nExtraction M.\n\n\n\n\n(** * Some sets of sets ... *)\n\nModule MM := FSetAVL.Make(M).\n\nDefinition eens1 := MM.add ens1 (MM.add ens2 (MM.empty)).\n\n(* ... that can now computes in Coq (due to the new [compare]) *)\nEval vm_compute in List.map M.elements (MM.elements eens1).\n\n\n\n\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 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 compute in (M.elements (M.inter bigens1 bigens2)).\n(* takes a few seconds, but we can also take advantage of Coq new virtual \n    machine (VM), that performs the same job in almost no time. *) \nTime Eval vm_compute in (M.elements (M.inter bigens1 bigens2)).\n\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.elements (M.inter bigens3 bigens4)).\n(* 11s for this intersection of 2 sets of 10000 elements !! \n   In fact, 5s per construction of each bigens, but the inter \n   is done in no time: \n*)\nTime Eval vm_compute in (M.elements (M.inter bigens3 bigens4)).\n(* 0.8s *)\n\n\n\n\n\n\n\n(** * Proving with FSets : the facts/properties functors *)\n\n(* The properties provided by FSetAVL are deliberately minimalistic. \n   They correspond to the minimal specifications present in FSetInterface. \n   This way, building new implementations is fairly simple.\n   Now, lots of additional facts can be derived from this common interface. *) \n\n(* Simple ones are locating in the functor FSetFacts.Facts *)\nModule MF := FSetFacts.Facts M.\n\n(* It contains mainly rephrasing of the specifications in alternative styles \n  like equivalences or boolean *)\nCheck MF.add_iff.\nCheck MF.add_b.\n\n(* More complex properties are located in the functors FSetProperties.Properties *)\nModule MP := FSetProperties.Properties M.\n\n(* For instance: usual stuff about set operations: *)\nCheck MP.union_inter_1.\n\n(* Also useful: one induction principle (in fact several) *)\nCheck MP.set_induction.\n\n(* And lot of stuff concerning the hard-to-handle [fold] function *)\nCheck MP.fold_add.\n\n(* Most advance property: the law on cardinal of unions *)\nCheck MP.union_inter_cardinal.\n\n\n\n\n\n\n(** * What about maps ? it's the same ! *)\n\nRequire Import FMapAVL.\n\n(* Now, the elements of the OrderedType will serve as keys for the maps. *)\nModule F := FMapAVL.Make(Z_as_OT).\n\n(* And as in Ocaml, maps contains data whose type is polymorphic: *) \nCheck F.add.\n\n(* Let's for instance define a map with Z keys and lists as data *)\nDefinition map1 := \n  F.add 2 (1::2::nil) \n   (F.add 3 nil \n     (F.add 1 (0::nil) \n       (F.empty _))).\n\nEval compute in (F.find 1 map1).\nEval compute in (F.mem 1 map1).\n\nEval compute in (F.map (@length _) map1).(F.this).\n\n(* Not in Ocaml's map: [elements] *)\n\nEval compute in (F.elements (F.map (@length _) map1)).\n\n(* ... and [map2] *)\n\nCheck F.map2.\n\n(* Unlike keys, we need no particular structure over datas.\n    Only two exceptions: [equal] and [compare]. *)\n\nCheck F.equal.\n\n(* Concerning [compare], we need a ternary decidable comparison  \n over datas. We hence diverge slightly apart from Ocaml, by placing \n this [compare] in a separate functor requiring 2 [OrderedType], \n one for the keys and one for the datas, see FMapAVL.Make_ord *)\n\n(* FMaps also come with additional properties in the same spirit as for \n   FSets, see file FMapFacts.v *)\n\n\n\n\n\n\n\n(** How to get more efficient AVL trees after extraction : \n     the [Int] module to get rid of [Z] not-so-fast integers. *)\n\n(* [FSetAVL] now uses an abstract [Int] structure for every height of trees. \n   This gives a first [FSetAVL.IntMake(I:Int)(X:OrderedType)]. \n   Then the [Int] part can either be filled with [Z_as_Int] for computing \n   in Coq, giving the above [FSetAVL.Make], or instead extracted as is, \n   and filled after extraction by some fast ocaml code based on machine \n   integers. \n*)\n\nPrint R.tree.\nEval compute in Int.Z_as_Int.t.\n\n\n(*excerpt from Int.v*)\nModule Type Int.\n\n Parameter t : Set.\n\n Parameter i2z : t -> Z.\n\n Parameter _0 : t.\n Parameter _1 : t.\n Parameter plus : t -> t -> t.\n Parameter opp : t -> t.\n Parameter minus : t -> t -> t.\n Parameter mult : t -> t -> t.\n Parameter max : t -> t -> t.\n\n(* Concerning logical relations, there is no need for additional \n   parameters: we take directly advantage of the [Z] ones, via \n   [i2z]. This simplifies the writing of translation tactics from  \n   [t] to [Z].  *)\n\n Notation \"x == y\" := (i2z x = i2z y)\n   (at level 70, y at next level, no associativity) : Int_scope.\n Notation \"x <= y\" := (Zle (i2z x) (i2z y)): Int_scope.\n Notation \"x < y\" := (Zlt (i2z x) (i2z y)) : Int_scope.\n Notation \"x >= y\" := (Zge (i2z x) (i2z y)) : Int_scope.\n Notation \"x > y\" := (Zgt (i2z x) (i2z y)): Int_scope.\n\n (* We also need some decidability facts. *) \n\n Open Scope Int_scope.\n Parameter gt_le_dec : forall x y: t, {x > y} + {x <= y}.\n Parameter ge_lt_dec :  forall x y : t, {x >= y} + {x < y}.\n Parameter eq_dec : forall x y : t, { x == y } + {~ x==y }.\n Open Scope Z_scope.\n\n (* Specification of previous parameters. *)\n\n (* First, [i2z] is an injection. *)\n\n Axiom i2z_eq : forall n p, n == p -> n = p.\n\n (* Then, all the operators are morphisms. *)\n\n Axiom i2z_0 : i2z _0 = 0.\n Axiom i2z_1 : i2z _1 = 1.\n Axiom i2z_plus : forall n p, i2z (plus n p) = i2z n + i2z p.\n Axiom i2z_opp : forall n, i2z (opp n) = -i2z n.\n Axiom i2z_minus : forall n p, i2z (minus n p) = i2z n - i2z p.\n Axiom i2z_mult : forall n p, i2z (mult n p) = i2z n * i2z p.\n Axiom i2z_max : forall n p, i2z (max n p) = Zmax (i2z n) (i2z p).\n\nEnd Int. \n(*/excerpt*)\n\n\n\n\n\n\n(** * The Weak Sets and Maps *) \n\n(* Sometimes, one may need finite sets and maps over a base type \n   that does not come with a decidable order. As long as this type\n   can still be equipped with a decidable equality, the FSetWeak and \n   FMapWeak counterparts of FSets and FMap provides such structures. \n*)\n  \nModule W := FSetWeakList.Make (Z_as_DT).\n\n(* Of course, we cannot provide efficient functions anymore : the \n   underlying structure is unsorted lists (but without redundancies). *)\n\nEval compute in (W.elements (W.add 1 (W.add 3 (W.add 2 W.empty)))).\n\n(* Apart from efficiency questions and the lack of order-related functions\n   like [min_elt], FSetWeak/FMapWeak are as close as possible\n   to FSet/FMap (same function signatures, same properties, etc). \n*)\n\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/demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.7958799477111967}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom Equations Require Import Equations.\nRequire Import Arith.\nImport Wellfounded.\n\nSection wf_rel.\n\nVariable T : finType.\n\nVariable rel : T -> T -> bool.\n\nHypothesis rel_trans :\n  forall (t1 t2 t3 : T), rel t1 t2 -> rel t2 t3 -> rel t1 t3.\n\nHypothesis rel_anti_refl :\n  forall (t : T), ~ rel t t.\n\nDefinition rel_inv (t1 t2 : T) := rel t2 t1.\n \nDefinition subSetRel (t : T) := finset (rel_inv t).\n\nLemma decrease_card :\n  forall (t1 t2 : T),\n  t2 \\in subSetRel t1 -> #|subSetRel t2| < #|subSetRel t1|.\nProof.\nmove => t1 t2 h.\nrewrite /subSetRel in_set /rel_inv in h.\nhave proper : subSetRel t2 \\proper subSetRel t1.\n  have subset : subSetRel t2 \\subset subSetRel t1.\n    apply /subsetP.\n    rewrite /subSetRel /sub_mem => x.\n    rewrite !in_set /rel_inv => in1.\n    by apply: (rel_trans x t2 t1).\n  have diff : subSetRel t2 != subSetRel t1.\n    rewrite eqEsubset.\n    apply /nandP.\n    rewrite subset /=.\n    apply /orP.\n    rewrite /=.\n    apply /subsetPn.\n    exists t2.\n      by rewrite in_set.\n    rewrite in_set /rel_inv.\n    apply/negP.\n    by apply: rel_anti_refl.\n  by rewrite properEneq subset diff.\nrewrite properEcard in proper.\nmove/andP: proper.\nmove => proper.\ndestruct proper.\napply: H0.\nQed.\n\nDefinition f (t : T) : nat := #|subSetRel t|.\n\nDefinition rel_in_nat (t1 t2 : T) :=  lt (f t1) (f t2).\n\nLemma rel_to_nat : Relation_Definitions.inclusion T rel rel_in_nat.\nProof.\nrewrite /Relation_Definitions.inclusion.\nmove => t1 t2 h.\nrewrite /rel_in_nat /f.\napply /ltP.\napply: decrease_card.\nby rewrite in_set /rel_inv.\nQed.\n\nLemma wf_rel_in_nat : well_founded rel_in_nat.\nProof.\nrewrite /rel_in_nat.\napply: (wf_inverse_image T nat lt f).\nby apply: lt_wf.\nQed.\n\nLemma wf_rel : well_founded rel.\nProof.\napply: wf_incl.\napply: rel_to_nat.\nby apply : wf_rel_in_nat.\nQed.\n\nEnd wf_rel.", "meta": {"author": "cneyrand", "repo": "Formal-proofs-for-the-convergence-of-visibility-walks-in-triangulations", "sha": "100c525bea7c2ba93a0c1728baab203f973f232d", "save_path": "github-repos/coq/cneyrand-Formal-proofs-for-the-convergence-of-visibility-walks-in-triangulations", "path": "github-repos/coq/cneyrand-Formal-proofs-for-the-convergence-of-visibility-walks-in-triangulations/Formal-proofs-for-the-convergence-of-visibility-walks-in-triangulations-100c525bea7c2ba93a0c1728baab203f973f232d/wf_finset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7958152706444712}}
{"text": "(* -- DISCLAIMER: definitions in this file remain to be renamed,\n      e.g. mmin and mmax. *)\n\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Minimum/Maximum w.r.t. an order relation                                *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibReflect LibOperation\n  LibRelation LibOrder LibEpsilon.\nGeneralizable Variables A.\n\n(* This module offers the functions [mmin] and [mmax] which produce\n   the minimum and maximum elements of a non-empty, bounded set. *)\n\n\n(**************************************************************************)\n(* * Lower bound and minimum*)\n\n(* [lower_bound le P x] means that [x] is a lower bound for the\n   set [P] with respect to the ordering [le]. *)\n\nDefinition lower_bound A (le:binary A) (P:A->Prop) (x:A) :=\n  forall y, P y -> le x y.\n\n(* [min_element le P x] means that [x] is a minimal element of\n   [P], i.e., it is both a member of [P] and a lower bound for\n   [P]. *)\n\nDefinition min_element A (le:binary A) (P:A->Prop) (x:A) :=\n  P x /\\ lower_bound le P x.\n\n(* [mmin le P] is a minimal element of [P] with respect to [le],\n   when such an element exists. *)\n\nDefinition mmin `{Inhab A} (le:binary A) (P:A->Prop) :=\n  epsilon (min_element le P).\n\n\n(**************************************************************************)\n(* * Upper bound and maximum *)\n\n(* [upper_bound le P x] means that [x] is a lower bound for the\n   set [P] with respect to the ordering [le]. *)\n\nDefinition upper_bound A (le:binary A) (P:A->Prop) (x:A) :=\n  forall y, P y -> le y x.\n\n(* [max_element le P x] means that [x] is a maximal element of\n   [P], i.e., it is both a member of [P] and a lower bound for\n   [P]. *)\n\nDefinition max_element A (le:binary A) (P:A->Prop) (x:A) :=\n  P x /\\ upper_bound le P x.\n\n(* [mmax le P] is a minimal element of [P] with respect to [le],\n   when such an element exists. *)\n\nDefinition mmax `{Inhab A} (le:binary A) (P:A->Prop) :=\n  epsilon (max_element le P).\n\n\n(**************************************************************************)\n(* * Least upper bound and greatest lower bound *)\n\n(* [lub le P x] means that [x] is a least upper bound\n   for the set [P] with respect to the ordering [le]. *)\n\nDefinition lub A (le:binary A) (P:A->Prop) (x:A) :=\n  min_element le (upper_bound le P) x.\n\n(* [glb le P x] means that [x] is a greatest lower bound\n   for the set [P] with respect to the ordering [le]. *)\n\nDefinition glb A (le:binary A) (P:A->Prop) (x:A) :=\n  max_element le (lower_bound le P) x.\n\n\n(**************************************************************************)\n(* * Connexion between lower and bounds *)\n\nLemma upper_bound_inverse : forall A (le:binary A),\n  upper_bound le = lower_bound (inverse le).\nProof using.\n  extens. intros P x. unfolds lower_bound, upper_bound. iff*.\nQed.\n\nLemma max_element_inverse : forall A (le:binary A) (P:A->Prop) (x:A),\n  max_element le P x = min_element (inverse le) P x.\nProof using.\n  extens. unfold max_element, min_element. rewrite* upper_bound_inverse.\nQed.\n\nLemma mmax_inverse : forall `{Inhab A} (le:binary A) (P:A->Prop),\n  mmax le P = mmin (inverse le) P.\nProof using.\n  intros. applys epsilon_eq. intros x. rewrite* max_element_inverse.\nQed.\n\n\n(**************************************************************************)\n(* * Elimination roperties *)\n\n(* [bounded_has_minimal le] means that, at type [A], it is\n   the case that every non-empty set that admits a lower\n   bound has a minimal element. *)\n\nDefinition bounded_has_minimal A (le:binary A) :=\n  (* Recall that [ex P] means that [P] has an inhabitant; i.e.,\n     it is equivalent to [exists x, P x]. *)\n  forall P,\n  ex P ->\n  ex (lower_bound le P) ->\n  ex (min_element le P).\n\n\n(* If the set [P] is non-empty and admits a lower bound, and if the type\n   [A] is such that every such set has a minimal element, then [P] has a\n   minimal element, and this element is [mmin le P]. *)\n\nLemma mmin_spec : forall `{Inhab A} (le:binary A) (P:A->Prop) m,\n  m = mmin le P ->\n  ex P ->\n  ex (lower_bound le P) ->\n  bounded_has_minimal le ->\n  min_element le P m.\nProof using.\n  intros. subst. unfold mmin. epsilon* m.\nQed.\n\n\n\n(**************************************************************************)\n(* * Application to [nat] *)\n\nFrom TLC Require Import LibNat.\n\n(* The type [nat] enjoys this property. *)\n\nLemma increment_lower_bound_nat : forall (P : nat->Prop) x,\n  lower_bound le P x ->\n  ~ P x ->\n  lower_bound le P (x + 1)%nat.\nProof using.\n  introv hlo ?. intros y ?.\n  destruct (eq_nat_dec x y).\n    { subst. tauto. }\n    { forwards: hlo; eauto. nat_math. }\nQed.\n\nLemma bounded_has_minimal_nat :\n  @bounded_has_minimal nat le.\nProof using.\n  (* Assume a set [P], such that [y] is an inhabitant of [P]\n     and [x] is a lower bound for [P]. *)\n  intros P [ y ? ].\n  (* We reason by induction on the difference [y + 1 - x].\n     Reasoning with [y - x] would work too, but this choice\n     is more elegant, as it makes the base case a contradiction,\n     and avoids a little duplication. *)\n  cut (\n    forall (k x : nat), (y + 1 - x)%nat = k ->\n    lower_bound le P x ->\n    exists z, min_element le P z\n  ). { intros ? [ x ? ]. eauto. }\n  induction k; introv ? hlo.\n  (* Base. *)\n  (* Our hypotheses imply that [x] must be less than or equal to\n     [y]. Because in this case the difference [y + 1 - x] is zero,\n     this leads to a contradiction. *)\n  { false. forwards: hlo; eauto. nat_math. }\n  (* Step. *)\n  (* Eeither [P x] holds, or it does not. If it does, then [x]\n     is the desired minimal element. If it does not, this implies\n     that [x + 1] is a lower bound for [P], and the induction\n     hypothesis can be used. *)\n  destruct (prop_inv (P x)).\n    { exists x. split; eauto. }\n    { eapply (IHk (x + 1)%nat). nat_math. eauto using increment_lower_bound_nat. }\nQed.\n\n#[global]\nHint Resolve bounded_has_minimal_nat : bounded_has_minimal.\n\n(* Furthermore, at type [nat], every set admits a lower bound. *)\n\nLemma admits_lower_bound_nat : forall (P : nat->Prop),\n  ex (lower_bound le P).\nProof using.\n  exists 0%nat. unfold lower_bound. nat_math.\nQed.\n\n#[global]\nHint Resolve admits_lower_bound_nat : admits_lower_bound.\n\n(* At type [nat], every non-empty set that admits an upper bound\n   has a maximal element. *)\n\nLemma bounded_has_maximal_nat :\n  @bounded_has_minimal nat (inverse le).\nProof using.\n  (* Assume a set [P], such that [y] is an inhabitant of [P]\n     and [x] is an upper bound for [P]. *)\n  intros P [ y ? ] [ x h ].\n  assert (y <= x).\n    { forwards: h. eauto. eauto. }\n  (* We apply our previous result to the image of [P] through\n     the function that maps [i] to [x - i]. (We note that this\n     function is its own inverse.) This yields a minimal\n     element [z] of this image. Thus, [x - z] is the desired\n     maximal element of [P]. *)\n  assert (self_inverse: forall i, i <= x -> (x - (x - i))%nat = i).\n    intros. nat_math.\n  forwards [ z [ ? hz ]]: (@bounded_has_minimal_nat (fun i => P (x - i)%nat)).\n    { exists (x - y)%nat. rewrite self_inverse by eauto. eauto. }\n    { eauto using admits_lower_bound_nat. }\n  exists (x - z)%nat.\n  clear dependent y.\n  split; [ assumption | ].\n  intros y ?.\n  assert (y <= x).\n    { forwards: h. eauto. eauto. }\n  forwards: hz (x - y)%nat.\n    { rewrite self_inverse by eauto. eauto. }\n  unfold inverse. nat_math.\nQed.\n\n#[global]\nHint Resolve bounded_has_maximal_nat : bounded_has_minimal.\n\nLemma mmin_spec_nat:\n  forall (P:nat->Prop) m,\n  m = mmin le P ->\n  ex P ->\n  P m /\\ (forall x, P x -> m <= x).\nProof using.\n  introv E Q. applys (@mmin_spec _ _ _ P m E Q).\n  applys admits_lower_bound_nat.\n  applys bounded_has_minimal_nat.\nQed.\n\n\n(**************************************************************************)\n(* * Typeclasses *)\n\n(* [MMin P] is [mmin le P], in a context where the desired\n   ordering can be inferred. *)\n\nDefinition MMin `{Inhab A} `{Le A} := mmin le.\n\n(* [MMax P] is [mmax le P], in a context where the desired\n   ordering can be inferred. *)\n\nDefinition MMax `{Inhab A} `{Le A} := mmax le.\n\n\n\n\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibMin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.795696876830774}}
{"text": "\nRequire Import UniMath.MoreFoundations.PartA.\nRequire Import UniMath.MoreFoundations.Nat.\nRequire Import UniMath.MoreFoundations.Tactics.\n\nRequire Import UniMath.Algebra.Matrix.\n\nRequire Import UniMath.Algebra.Domains_and_Fields.\nRequire Import UniMath.Algebra.Matrix.\nRequire Import UniMath.Algebra.RigsAndRings.\nRequire Import UniMath.Algebra.IteratedBinaryOperations.\n\nRequire Import UniMath.Algebra.GaussianElimination.Auxiliary.\nRequire Import UniMath.Algebra.GaussianElimination.Vectors.\nRequire Import UniMath.Algebra.GaussianElimination.Matrices.\nRequire Import UniMath.Algebra.GaussianElimination.Elimination.\n\n(**\n  In this module, we define a back-substitution procedure that works on\n  nxn matrices that are upper triangular with all non-zero diagonal.\n\n  We use this procedure to show that any nxn matrix either not invertible,\n  or calculate its inverse.\n\n  Primary Author: Daniel @Skantz (November 2022)\n*)\n\nDefinition matrix_inverse_or_non_invertible_stmt\n  { n : nat } {F : fld}\n  (A : Matrix F n n)\n  := coprod (@matrix_inverse F n A)\n            (@matrix_inverse F n A -> empty).\n\nDefinition back_sub_stmt\n  { n : nat } {F : fld}\n  (mat : Matrix F n n)\n  (vec : Vector F n)\n  (ut : @is_upper_triangular F _ _ mat)\n  (df : @diagonal_all_nonzero F _ mat)\n  := ∑ v : (Vector F n),\n    (@matrix_mult F _ _ mat _ (col_vec v)) = (col_vec vec).\n\n\nSection BackSub.\n\n  Context (F : fld).\n\n  Local Notation Σ := (iterop_fun (@ringunel1 F) op1).\n  Local Notation \"A ** B\" := (@matrix_mult F _ _ A _ B) (at level 40, left associativity).\n  Local Notation \"R1 *pw R2\" := ((pointwise _ op2) R1 R2) (at level 40, left associativity).\n\n  (** output: a solution [x]_[row] to [mat ** x = b]_[row] if one exists\n     - given mat upper triangular, non-zero diagonal. Later applied inductively in [back_sub]. *)\n  Definition back_sub_step { n : nat } ( row : (⟦ n ⟧)%stn )\n    (mat : Matrix F n n) (x : Vector F n) (b : Vector F n) : Vector F n.\n  Proof.\n    intros i.\n    destruct (nat_eq_or_neq row i).\n    - exact (((b i) * fldmultinv' (mat i i))\n           - ((Σ (mat i *pw x) - (x  i)* (mat i i))\n           * (fldmultinv' (mat i i))))%ring.\n    - exact (x i).\n  Defined.\n\n  (** procedure gives [x_i] s.t. [(mat ** x)_i = b_i], given previous assumptions *)\n  Lemma back_sub_step_inv0 { n : nat }\n    (row : ⟦ n ⟧%stn) (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (p: @is_upper_triangular F n n mat)\n    (p' : (mat row row != 0)%ring)\n    : (mat ** (col_vec (back_sub_step row mat x b))) row = (col_vec b) row.\n  Proof.\n    unfold back_sub_step, col_vec.\n    unfold fldmultinv'.\n    rewrite matrix_mult_eq; unfold matrix_mult_unf, pointwise.\n    set (m := n - (S row)).\n    assert (split_eq : n = (S row) + m).\n    { unfold m.\n      rewrite natpluscomm, minusplusnmm.\n      - apply idpath.\n      - exact (pr2 row). }\n    destruct (stn_inhabited_implies_succ row)\n      as [s_row s_row_eq], (!s_row_eq).\n    apply funextfun; intros ?.\n    rewrite (@vecsum_dni _ (s_row) _ row)\n    , nat_eq_or_neq_refl.\n    destruct (fldchoice0 _) as [? | neq].\n    {contradiction. }\n    etrans.\n    { apply maponpaths_2; apply maponpaths.\n      apply funextfun; intros q.\n      unfold funcomp.\n      now rewrite (nat_eq_or_neq_right (dni_neq_i row q)). }\n    rewrite (@vecsum_dni F (s_row) _ row).\n    etrans.\n    { apply maponpaths.\n      etrans.\n      { apply maponpaths.\n        rewrite (@ringcomm2 F).\n        apply maponpaths.\n        now rewrite (@ringcomm2 F). }\n      apply (@ringminusdistr' F (mat row row)).\n    }\n    etrans.\n    { apply maponpaths; apply map_on_two_paths.\n      - rewrite <- (@rigassoc2 F), (@fldmultinvrax F).\n      { now rewrite (@riglunax2 F). }\n      - apply maponpaths.\n        rewrite <- (@rigassoc2 F), (@fldmultinvrax F).\n        apply (@riglunax2 F). }\n    etrans.\n    { do 3 apply maponpaths.\n      now rewrite (@rigcomm2 F), (@ringplusminus F). }\n    rewrite (@rigcomm1 F); rewrite (@rigassoc1 F).\n    now rewrite (@ringlinvax1 F), (@rigrunax1 F).\n  Defined.\n\n  (** [back_sub_step] only modifies target element *)\n  Lemma back_sub_step_inv1\n    { n : nat } (row : ⟦ n ⟧%stn)\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    : ∏ i : ⟦ n ⟧%stn, i ≠ row ->\n      (col_vec (back_sub_step row mat x b) i = (col_vec x) i).\n  Proof.\n    intros i ne.\n    unfold back_sub_step, col_vec.\n    apply funextfun. intros j; simpl.\n    destruct (nat_eq_or_neq row i) as [eq | ?];\n      try apply idpath.\n    rewrite eq in ne.\n    contradiction (isirrefl_natneq _ ne).\n  Defined.\n\n  Lemma back_sub_step_inv2\n    { n : nat }\n    (row : ⟦ n ⟧%stn)\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (is_ut: @is_upper_triangular F n n mat)\n    : ∏ i : ⟦ n ⟧%stn, i ≥ row\n    -> (mat i i != 0)%ring\n    -> (mat ** (col_vec x)) i = (col_vec b) i\n    -> (mat ** (col_vec (back_sub_step row mat x b))) i = (col_vec b) i.\n  Proof.\n    unfold transpose, flip.\n    intros i le neq0 H.\n    rewrite <- H.\n    destruct (natlehchoice row i) as [lt | eq]. {apply le. }\n    - rewrite matrix_mult_eq in *.\n      apply pathsinv0.\n      rewrite matrix_mult_eq.\n      unfold matrix_mult_unf in *.\n      apply funextfun; intros ?.\n      apply maponpaths, funextfun; intros i'.\n      destruct (stn_eq_or_neq i' (row)) as [eq | neq].\n      2 : { now rewrite back_sub_step_inv1. }\n      rewrite is_ut. 2: { rewrite eq. assumption. }\n      do 2 rewrite (@rigmult0x F).\n      apply idpath.\n    - rewrite (stn_eq _ _ eq)\n      , back_sub_step_inv0; try assumption.\n      now rewrite H.\n  Defined.\n\n  (** Back-substituting repeatedly using step procedure defined earlier.\n      Carries an additional [row] parameter that allows for partially applying the substition,\n      that is used later for showing that diagonal must be non-zero. *)\n  Definition back_sub_internal\n    { n : nat }\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (sep : ⟦ S n ⟧%stn)\n    (row : ⟦ S n ⟧%stn)\n    : Vector F n.\n  Proof.\n    destruct sep as [sep p].\n    induction sep as [| m IH]. {exact x. }\n    destruct (natlthorgeh (dualelement (m,, p)) row).\n    2: {exact x. }\n    refine (back_sub_step (dualelement (m,, p)) mat (IH _) b).\n    apply (istransnatlth _ _ _ (natgthsnn m) p).\n  Defined.\n\n  Lemma back_sub_internal_inv0\n    { n : nat }\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (sep : ⟦ S n ⟧%stn)\n    (row : ⟦ S n ⟧%stn)\n    : ∏ (i : ⟦ n ⟧%stn), i >= row\n    -> (col_vec (back_sub_internal mat x b sep row)) i = (col_vec x) i.\n  Proof.\n    destruct sep as [sep p].\n    induction sep as [| sep IH].\n    { intros i H; now destruct (natchoice0 (S n)) in H. }\n    unfold back_sub_internal.\n    intros i i_lt_row.\n    rewrite nat_rect_step.\n    destruct (natlthorgeh _ _) as [lt | geh].\n    2: {reflexivity. }\n    assert (p': sep < S n). { apply (istransnatlth _ _ _ (natgthsnn sep) p). }\n    rewrite <- (IH p'); try assumption.\n    unfold back_sub_internal.\n    rewrite back_sub_step_inv1; try easy.\n    {apply maponpaths_2, maponpaths, proofirrelevance, propproperty. }\n    apply natgthtoneq.\n    refine (natlthlehtrans _ _ _ lt i_lt_row).\n  Defined.\n\n  Lemma back_sub_internal_inv1\n    { n : nat }\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (sep : ⟦ S n ⟧%stn)\n    (row : ⟦ S n ⟧%stn)\n    : ∏ i : stn n, i >= row\n    -> (back_sub_internal mat x b sep row) i = x i.\n  Proof.\n    intros.\n    rewrite (@col_vec_inj_pointwise F n\n      (back_sub_internal mat x b sep row) x i).\n    - apply idpath.\n    - now apply (back_sub_internal_inv0).\n  Defined.\n\n  Lemma back_sub_internal_inv2\n    { n : nat }\n    (mat : Matrix F n n)\n    (x : Vector F n) (b : Vector F n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (sep : ⟦ S n ⟧%stn)\n    (row : ⟦ S n ⟧%stn)\n    : ∏ (i : ⟦ n ⟧%stn), i ≥ (dualelement sep)\n    -> (mat i i != 0)%ring\n    -> i < row\n    -> (mat ** (col_vec (back_sub_internal mat x b sep row))) i = (col_vec b) i.\n  Proof.\n    unfold transpose, flip.\n    intros i i_le_sep neq0 lt.\n    unfold back_sub_internal.\n    destruct sep as [sep p].\n    induction sep as [| sep IH].\n    { apply fromempty, (dualelement_sn_stn_nge_0 _ _ i_le_sep). }\n    rewrite nat_rect_step.\n    destruct (natlehchoice (dualelement (sep,, p)) i) as [leh | eq].\n    { refine (istransnatleh _ i_le_sep).\n      now apply (@dualelement_sn_le). }\n    - destruct (natlthorgeh _ _) as [? | contr_geh].\n      2 : { contradiction (isirreflnatlth _\n              (natlthlehtrans _ _ _ (istransnatlth _ _ _ leh lt) contr_geh)).\n      }\n      rewrite back_sub_step_inv2; try easy.\n      { unfold dualelement. unfold dualelement in leh.\n        destruct (natchoice0 _) as [contr_eq | ?].\n        {apply fromstn0. now rewrite contr_eq. }\n        now apply natgthtogeh. }\n      rewrite IH; try reflexivity.\n        now apply dualelement_lt_to_le_s.\n    - destruct (natlthorgeh _ _) as [? | contr_geh].\n      + rewrite (stn_eq _ _ eq).\n        now rewrite back_sub_step_inv0.\n      + rewrite <- (stn_eq _ _ eq) in lt.\n        contradiction (isirreflnatlth _ (natlthlehtrans _ _ _ lt contr_geh)).\n  Defined.\n\n  Definition back_sub\n    {n : nat}\n    (mat : Matrix F n n)\n    (vec : Vector F n)\n  := back_sub_internal mat vec vec (n,, natgthsnn _) (n,, natgthsnn _).\n\n  Lemma back_sub_inv0\n    { n : nat }\n    (mat : Matrix F n n) (b : Vector F n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (df : @diagonal_all_nonzero F _ mat)\n    : back_sub_stmt mat b ut df.\n  Proof.\n    exists (back_sub mat b).\n    intros; unfold back_sub.\n    destruct (natchoice0 n) as [eq0 | ?].\n    { apply funextfun. intros i. apply fromstn0. now rewrite eq0. }\n    apply funextfun; intros i.\n    apply back_sub_internal_inv2;\n      try assumption; unfold dualelement; try easy.\n    2: {exact (pr2 i). }\n    destruct (natchoice0 _) as [eq0 | ?].\n    { apply fromempty; now apply negpaths0sx in eq0. }\n    simpl; now rewrite natminuseqn, minuseq0'.\n  Defined.\n\nEnd BackSub.\n\n\nSection BackSubZero.\n\n  (** First, Helper functions for finding first zero value in a vector.\n      Then proof we can't have invertible, upper triangular matrix unless\n      non-zero diagonal *)\n\n  Context (F : fld).\n\n  Local Notation Σ := (iterop_fun (@ringunel1 F) op1).\n  Local Notation \"A ** B\" := (@matrix_mult F _ _ A _ B) (at level 40, left associativity).\n  Local Notation \"R1 *pw R2\" := ((pointwise _ op2) R1 R2) (at level 40, left associativity).\n  Local Notation \"0\" := (@rigunel1 F).\n\n  (* For using nonzeroax *)\n  Local Definition flip_fld_bin\n    (e : F) : F.\n  Proof.\n  destruct (fldchoice0 e).\n  - exact 1%ring.\n  - exact 0%ring.\n  Defined.\n\n  Local Definition flip_fld_bin_vec\n  {n : nat} (v : Vector F n) := λ i : (stn n), flip_fld_bin (v i).\n\n  (* Below, we find the first zero value in a vector [v] by looking for the leading element\n     in the transformed vector. Perhaps not a pretty solution, maybe we instead want to generalize\n     the notion of leading entry. *)\n\n  Local Definition vector_all_nonzero_compute_internal\n  {n : nat} (v : Vector F n)\n  : coprod (∏ j : (stn n), (v j) != 0%ring)\n          (∑ i : (stn n), ((v i) = 0%ring)\n        × (forall j : stn n, (j < (pr1 i) -> (v j) != 0%ring))).\n  Proof.\n  pose (leading_entry := leading_entry_compute F (flip_fld_bin_vec v)).\n  destruct (maybe_choice' leading_entry) as [some | none].\n  - right; use tpair; simpl. {apply some. }\n    destruct (@leading_entry_compute_inv2 F _ (flip_fld_bin_vec v) (pr1 some) (pr2 some))\n      as [some_neq_0 prev_eq_0].\n    unfold is_leading_entry, flip_fld_bin_vec, flip_fld_bin in * |-.\n    destruct (fldchoice0 (v _)); try contradiction.\n    use tpair; try assumption.\n    intros ? lt.\n    specialize (prev_eq_0 _ lt).\n    now destruct (fldchoice0 (v j)).\n  - left; intros j.\n    rewrite <- (@leading_entry_compute_inv1 _ _ (flip_fld_bin_vec v) none j).\n    try apply (pr2 (dualelement j)).\n    destruct (fldchoice0 (v j)) as [eq | neq];\n      unfold is_leading_entry, flip_fld_bin_vec, flip_fld_bin in *\n      ; destruct (fldchoice0 _); try assumption.\n    + rewrite eq; intros contr_neq.\n      contradiction (nonzeroax _ (pathsinv0 contr_neq)).\n    + destruct (fldchoice0 (v j)) as [contr_eq | ?].\n      * rewrite contr_eq in neq.\n        contradiction.\n      * contradiction.\n  Defined.\n\n  Local Definition vector_all_nonzero_compute\n  {n : nat} (v : Vector F n)\n  : coprod (∏ j : (stn n), (v j) != 0%ring)\n           (∑ i : (stn n), (v i)  = 0%ring).\n  Proof.\n    destruct (@vector_all_nonzero_compute_internal n v) as [l | r]. {now left. }\n    right; exists (pr1 r); exact (pr1 (pr2 r)).\n  Defined.\n\n  (** Showing that right invertible matrix, upper triangular,\n     must have all non-zero diagonal. *)\n\n  (** Ax = 0 would have two solutions for x, but A invertible... *)\n  Lemma back_sub_zero\n    { n : nat }\n    (mat : Matrix F n n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (zero: ∑ i : stn n, (mat i i = 0)%ring\n      × (forall j : stn n, j < i -> ((mat j j) != 0)%ring))\n    (inv : @matrix_left_inverse F _ _ mat)\n    : empty.\n  Proof.\n    unfold transpose, flip.\n    destruct (natchoice0 (pr1 zero)) as [eq0_1 | gt].\n    { apply (zero_row_to_non_right_invertibility (transpose mat) (pr1 zero));\n        try assumption.\n      2: { now apply (@matrix_left_inverse_to_transpose_right_inverse F). }\n      apply funextfun; intros k.\n      destruct (natchoice0 k) as [eq0_2 | ?].\n      - rewrite <- (pr1 (pr2 zero)).\n        unfold const_vec.\n        rewrite eq0_1 in eq0_2.\n        now rewrite (stn_eq _ _ eq0_2).\n      - unfold transpose, flip.\n        rewrite ut; try reflexivity.\n        now rewrite <- eq0_1.\n    }\n    assert (contr_exists :  ∑ x : (Vector F n), (∑ i' : stn n,\n      (x i' != 0) × (mat ** (col_vec x)) = (@col_vec F _ (const_vec 0)))).\n    2: { assert (eqz : (mat ** (@col_vec F _ (const_vec 0)))\n          = (@col_vec F _ (const_vec 0))).\n        { rewrite matrix_mult_eq; unfold matrix_mult_unf.\n          apply funextfun; intros k.\n          unfold col_vec, const_vec.\n          etrans.\n          { rewrite vecsum_eq_zero.\n            - apply idpath.\n            - intros ?; apply rigmultx0. }\n          reflexivity.\n        }\n        assert (contr_eq' : (@ringunel1 F) != (@ringunel1 F)).\n        2: {contradiction. }\n        rewrite <- eqz in contr_exists.\n        destruct contr_exists as [x1 [x2 [x3 contr_exists]]].\n        destruct inv as [inv isinv].\n        rewrite <- contr_exists in eqz.\n        assert (eq : @matrix_mult F _ _ inv _\n          (@matrix_mult F _ _ mat _ (col_vec x1)) =\n           @matrix_mult F _ _ inv _ (@col_vec F _ (const_vec 0))).\n        {now rewrite eqz. }\n        rewrite <- matrix_mult_assoc, isinv, matlunax2 in eq.\n        pose (eq' := @matrix_mult_zero_vec_eq _ _ _ inv).\n        unfold col_vec, const_vec in * |-.\n        rewrite eq' in eq.\n        destruct zero as [zero iszero].\n        apply toforallpaths in eq.\n        set (idx0 := (make_stn _ 0 (stn_implies_ngt0 zero))).\n        assert (contr_eq' :\n          (λ (_ : _) (_ : _), (@rigunel1 F)) idx0 =\n          (λ (_ : _) (_ : (⟦ 1 ⟧)%stn), x1 x2) idx0\n        ). { now rewrite eq. }\n        apply toforallpaths in contr_eq'.\n        rewrite contr_eq' in x3.\n        2: { exact (make_stn _ _ (natgthsnn 0)). }\n        contradiction.\n    }\n    destruct zero as [zero iszero].\n    use tpair.\n    { apply back_sub_internal.\n      - exact mat.\n      - intros j.\n        destruct (natlthorgeh (pr1 zero) j).\n        + exact 0.\n        + destruct (natgehchoice (pr1 zero) j); try assumption.\n          * exact 0.\n          * exact (@rigunel2 F).\n      - exact (const_vec 0).\n      - exact (n,, natgthsnn _).\n      - exact (pr1 zero,, (istransnatlth _ _ _ (pr2 zero) (natgthsnn _))).\n    }\n    exists zero.\n    use tpair.\n    - rewrite back_sub_internal_inv1; try assumption.\n      2: {apply isreflnatleh. }\n      destruct (natlthorgeh _ _) as [lt | ge].\n      * contradiction (isirreflnatgth _ lt).\n      * simpl; clear gt. destruct (natgehchoice _ _) as [gt | eq].\n        {contradiction (isirreflnatlth _ gt). }\n        apply (@nonzeroax F).\n    - apply funextfun; intros j.\n      destruct (natlthorgeh j zero) as [? | ge].\n      + rewrite back_sub_internal_inv2; try easy.\n        * apply dualelement_sn_stn_ge_n.\n        * now apply (pr2 iszero).\n      + rewrite matrix_mult_eq; unfold matrix_mult_unf.\n        unfold col_vec, const_vec.\n        apply funextfun; intros ?.\n        eapply (@vecsum_eq_zero F).\n        intros k.\n        destruct (natgthorleh j k) as [? | le].\n        {rewrite ut; try assumption; apply rigmult0x. }\n        destruct (stn_eq_or_neq (zero) k) as [eq | ?].\n        * rewrite <- eq in *.\n          rewrite <- (stn_eq _ _ (isantisymmnatgeh _ _ le ge)).\n          rewrite (pr1 iszero); apply rigmult0x.\n        * etrans. 2: {apply rigmultx0. }\n          apply maponpaths.\n          rewrite back_sub_internal_inv1; try assumption.\n          2: {apply (istransnatleh ge le). }\n          destruct (natlthorgeh _ _) as [? | ?]; try reflexivity.\n          destruct (natgehchoice _ _) as [? | eq];\n            try reflexivity.\n          rewrite (stn_eq _ _ eq) in * |-.\n          contradiction (isirrefl_natneq k).\n  Defined.\n\nEnd BackSubZero.\n\n(** Some results that are useful in the next section. *)\nSection Misc.\n\n  Context (F: fld).\n\n  (** Row echelon form implies upper triangularity*)\n  Lemma row_echelon_partial_to_upper_triangular_partial\n    { m n : nat }\n    (mat : Matrix F m n)\n    (p : n > 0)\n    (iter : ⟦ S m ⟧%stn)\n    : @is_row_echelon_partial F m n mat iter\n   -> @is_upper_triangular_partial F m n iter mat.\n  Proof.\n    unfold is_row_echelon_partial, is_upper_triangular_partial.\n    destruct iter as [iter p'].\n    unfold is_row_echelon_partial_1, is_row_echelon_partial_2.\n    induction iter as [| iter IH].\n    { intros ? ? ? ? contr; contradiction (negnatlthn0 n contr). }\n    intros [re_1 re_2] i j lt lt'.\n    simpl in p'.\n    pose (iter_lt_sn := (istransnatlth _ _ _ p' (natgthsnn m))).\n    destruct (natlehchoice i iter) as [? | eq]. {now apply natlthsntoleh. }\n    - destruct (maybe_choice' (leading_entry_compute _ (mat i))) as [t | none].\n      + destruct t as [t eq].\n        rewrite (IH iter_lt_sn); try easy.\n        use tpair; simpl.\n        * intros i_1 i_2 j_1 j_2 i1_lt_iter H ? ?.\n          rewrite (re_1 i_1 i_2 j_1 j_2); try easy.\n          apply (istransnatlth _ _ _ i1_lt_iter (natgthsnn iter)).\n        * intros i_1 i_2 i1_lt_iter ? ?; rewrite (re_2 i_1 i_2); try easy.\n          apply (istransnatlth _ _ _ i1_lt_iter (natgthsnn iter)).\n      + now rewrite (leading_entry_compute_inv1 _ _ none).\n    - assert (eq' : i = (iter,, p')). { apply subtypePath_prop; apply eq. }\n      destruct (maybe_choice' (leading_entry_compute F (mat i))) as [[t jst] | none].\n      2: { now rewrite (leading_entry_compute_inv1 _ _ none). }\n      destruct (natlthorgeh j t) as [j_lt_t | contr_gt].\n      { rewrite (pr2 (leading_entry_compute_inv2 _ _ _ jst)); try easy. }\n      pose (H1 := leading_entry_compute_inv2 _ _ _ jst).\n      destruct (natchoice0 i) as [contr0 | ?].\n      { apply fromempty; refine (negnatgth0n _ _); rewrite contr0; apply lt. }\n      destruct (prev_stn i) as [u u_lt]; try assumption.\n      destruct (maybe_choice' (leading_entry_compute _ (mat u)))\n        as [[prev eq''] | none_prev].\n      + pose (H2 := (leading_entry_compute_inv2 _ _ _ eq'')).\n        contradiction (pr1 H2); rewrite (IH iter_lt_sn); try easy.\n        * use tpair; simpl.\n          -- intros i_1 i_2 j_1 j_2 i1_lt_iter H' ? ?.\n             rewrite (re_1 i_1 i_2 j_1 j_2); try easy.\n             apply (istransnatlth _ _ _ i1_lt_iter (natgthsnn iter)).\n          -- intros i_1 i_2 i1_lt_iter ? ?; rewrite (re_2 i_1 i_2); try easy.\n             apply (istransnatlth _ _ _ i1_lt_iter (natgthsnn _)).\n        * destruct (natgthorleh u prev) as [gt | leh]; try assumption.\n          contradiction (pr1 H1); rewrite (re_1 u i t prev); try easy.\n          -- apply natgehsntogth; rewrite u_lt, eq'; apply natgehsnn.\n          -- apply natgehsntogth; rewrite u_lt, eq'; apply isreflnatleh.\n          -- destruct (natgthorleh t prev) as [gt | leh']; try assumption.\n             apply (istransnatleh contr_gt); refine (istransnatleh _ leh).\n             apply natlehsntolth, natlthsntoleh; rewrite u_lt; apply lt.\n        * apply natgehsntogth; rewrite u_lt, eq'; apply (isreflnatleh).\n      + rewrite (re_2 u i ); try easy.\n        * simpl; apply natlthtolths. rewrite <- eq.\n          try apply (natlehlthtrans _ _ _ contr_gt lt ).\n          apply natgehsntogth; rewrite u_lt, eq'; apply isreflnatleh.\n        * apply funextfun; intros j';\n          rewrite ((leading_entry_compute_inv1 _ _ none_prev) j');\n          reflexivity.\n        * try apply (natlehlthtrans _ _ _ contr_gt lt).\n          apply natgehsntogth; rewrite u_lt, eq'; apply isreflnatleh.\n  Defined.\n\n  Lemma row_echelon_to_upper_triangular\n    { m n : nat }\n    (mat : Matrix F m n)\n    : is_row_echelon mat\n    -> @is_upper_triangular F _ _ mat.\n  Proof.\n    destruct (natchoice0 n) as [contr_eq0 | p].\n    { intros ? ? j; apply fromstn0; now rewrite contr_eq0. }\n    intros H; unfold is_upper_triangular; intros.\n    rewrite (row_echelon_partial_to_upper_triangular_partial mat p (m,, natgthsnn _))\n    ; try easy. 2: {exact (pr2 i). }\n    use tpair; intros i_1 i_2 j_1 j_2; intros; simpl.\n    - destruct (H i_1 i_2) as [H1 _]; now rewrite (H1 j_2 j_1).\n    - destruct (H i_1 i_2) as [_ H2]; now rewrite H2.\n  Defined.\n\nEnd Misc.\n\n\nSection Inverse.\n\n  (** Some additional properties of matrix inverses,\n      having now defined Gaussian elimination and\n      back-substitution.\n\n      Computes a matrix inverse or shows it is non-invertible. *)\n\n  Context (F : fld).\n\n  Local Notation Σ := (iterop_fun (@ringunel1 F) op1).\n  Local Notation \"A ** B\" := (@matrix_mult F _ _ A _ B) (at level 40, left associativity).\n  Local Notation \"R1 *pw R2\" := ((pointwise _ op2) R1 R2) (at level 40, left associativity).\n\n  (** Construct the inverse,\n    if additionally mat is upper triangular with non-zero diagonal *)\n  Definition upper_triangular_right_inverse_construction\n    { n : nat }\n    (mat : Matrix F n n)\n    := transpose (λ i : (stn n), (back_sub _ mat (@identity_matrix F n i))).\n\n  Lemma left_invertible_upper_triangular_to_diagonal_all_nonzero\n    {n : nat }\n    (A : Matrix F n n)\n    (p : @is_upper_triangular F _ _ A)\n    (p': @matrix_left_inverse F _ _ A)\n    : (@diagonal_all_nonzero F _ A).\n  Proof.\n    destruct (@vector_all_nonzero_compute_internal _ _ (@diagonal_sq F _ A)) as [l | r].\n    { unfold diagonal_all_nonzero; intros; unfold diagonal_sq in l; apply l. }\n    unfold diagonal_sq in r; apply fromempty; now apply (@back_sub_zero _ _ A p).\n  Defined.\n\n  Lemma matrix_right_inverse_construction_inv\n    { n : nat } (mat : Matrix F n n)\n    (ut : @is_upper_triangular F _ _ mat)\n    (df: @diagonal_all_nonzero F _ mat)\n    : (mat ** (upper_triangular_right_inverse_construction mat))\n      = (@identity_matrix F n).\n  Proof.\n    apply funextfun; intros i.\n    unfold matrix_mult, row, col, transpose, flip.\n    apply funextfun; intros ?.\n    unfold upper_triangular_right_inverse_construction.\n    rewrite (@col_vec_mult_eq F _ _ mat _ (@identity_matrix F _ x)).\n    - destruct (stn_eq_or_neq i x) as [eq | neq].\n      { now rewrite eq. }\n      rewrite id_mat_ij; try rewrite id_mat_ij; try easy.\n      apply (issymm_natneq _ _ neq).\n    - unfold upper_triangular_right_inverse_construction.\n      pose (back_sub_inv := @back_sub_inv0).\n      destruct (natchoice0 n) as [eq | ?].\n      {apply fromstn0; now rewrite eq. }\n      apply (back_sub_inv _ _ _ _ ut df).\n  Defined.\n\n  Lemma matrix_left_inverse_implies_right { n : nat } (A B: Matrix F n n)\n    : (B ** A) = (@identity_matrix F n)\n    -> (@matrix_right_inverse F n n A).\n  Proof.\n    intros ?.\n    destruct (natchoice0 n) as [eq0 | gt]. { destruct eq0; now use tpair. }\n    pose (C := pr1 (gaussian_elimination _ A)).\n    pose (is_gauss := pr2 (gaussian_elimination _ A)).\n    destruct is_gauss as [inv is_re].\n    pose (CA := C ** A).\n    pose (D := @upper_triangular_right_inverse_construction _ CA).\n    exists (D ** C).\n    assert (CA_ut : is_upper_triangular CA).\n    { apply (@row_echelon_to_upper_triangular _ _ _ CA), is_re. }\n    assert (nonz : @diagonal_all_nonzero F _ CA).\n    { apply left_invertible_upper_triangular_to_diagonal_all_nonzero;\n      try assumption.\n      apply left_inv_matrix_prod_is_left_inv.\n      - exists (pr1 inv).\n        apply (pr2 (pr2 inv)).\n      - now exists B.\n    }\n    pose (invmat := @matrix_right_inverse_construction_inv _ _ CA_ut nonz).\n    unfold CA in invmat.\n    rewrite matrix_mult_assoc in invmat.\n    assert (eq : (C ** A ** D) = (A ** D ** C)).\n    { unfold CA in invmat. unfold D, CA.\n      rewrite matrix_mult_assoc, invmat.\n      pose (left_inv_eq_right := @matrix_left_inverse_equals_right_inverse).\n      apply pathsinv0.\n      pose (gauss_mat_invertible := inv).\n      apply (matrix_inverse_to_right_and_left_inverse) in gauss_mat_invertible.\n      destruct gauss_mat_invertible as [gauss_mat gauss_mat_invertible].\n      pose (left_inv_eq_right_app\n        := left_inv_eq_right F n _ n C gauss_mat ((A ** D),, invmat)).\n      set (constr := (upper_triangular_right_inverse_construction\n        (@matrix_mult F _ _ C _ A))).\n      assert (eq: (@matrix_mult F _ _ A n constr) = (pr1 gauss_mat)).\n      { apply pathsinv0. apply (left_inv_eq_right_app). }\n      rewrite eq.\n      apply gauss_mat.\n    }\n    refine (_ @ invmat); rewrite <- matrix_mult_assoc; refine (!eq @ _).\n    apply matrix_mult_assoc.\n  Defined.\n\n  Lemma matrix_right_inverse_implies_left\n    { n : nat } (A B: Matrix F n n)\n    : @matrix_right_inverse F _ _ A -> (@matrix_left_inverse F _ _ A).\n  Proof.\n    intros [rinv isrinv].\n    pose (linv := @make_matrix_left_inverse F _ _ n A rinv isrinv).\n    pose (linv_to_rinv := @matrix_left_inverse_implies_right _ _ _ isrinv).\n    exists rinv.\n    pose (inv_eq := @matrix_left_inverse_equals_right_inverse _ n _ n _ linv linv_to_rinv).\n    simpl in inv_eq; rewrite inv_eq;\n    apply linv_to_rinv.\n  Defined.\n\n  Theorem matrix_inverse_or_non_invertible { n : nat }\n    (A : Matrix F n n)\n    : @matrix_inverse_or_non_invertible_stmt _ _ A.\n  Proof.\n    unfold matrix_inverse_or_non_invertible_stmt.\n    destruct (natchoice0 n) as [eq0 | gt].\n    { left; destruct eq0; apply (@nil_matrix_invertible F 0 A). }\n    set (B:= @gauss_clear_all_rows_as_left_matrix _ _ _ A gt).\n    set (BA := B ** A).\n    set (C := upper_triangular_right_inverse_construction BA).\n    assert (ut : is_upper_triangular BA).\n    { unfold BA.\n      pose (is_echelon := @gauss_clear_all_rows_inv3 F _ _ A gt).\n      rewrite <- (gauss_clear_all_rows_as_matrix_eq _ _ gt) in is_echelon.\n      now apply row_echelon_to_upper_triangular. }\n    destruct (vector_all_nonzero_compute _ (λ i : stn n, BA i i)) as [nz | [idx isnotz]].\n    - left.\n      set (BAC_id := @matrix_right_inverse_construction_inv _ _ ut nz).\n      assert (rinv_eq : (C ** BA) = identity_matrix).\n      { apply (@matrix_right_inverse_implies_left _ _ C (C,, BAC_id)). }\n      exists (C ** B); simpl; use tpair.\n      2: { simpl; rewrite matrix_mult_assoc; apply rinv_eq. }\n      rewrite <- matrix_mult_assoc.\n      unfold BA in BAC_id.\n      assert (linv_eq : ((B ** A ** C) = (A ** C ** B))).\n      { rewrite matrix_mult_assoc in BAC_id |- *.\n        unfold C in *; clear C;\n        set (C := (upper_triangular_right_inverse_construction BA)).\n        pose (B_rinv := @make_matrix_right_inverse F _ _ n B (A ** C) BAC_id).\n        pose (linv := @matrix_right_inverse_implies_left _ _ C B_rinv).\n        pose (eq := @matrix_left_inverse_equals_right_inverse F n _ n B linv ((A ** C),, BAC_id)).\n        etrans.\n        { change (@matrix_mult F _ _ A _ C) with (pr1 B_rinv).\n          rewrite (pr2 B_rinv); reflexivity. }\n        change (pr1 (@matrix_mult F _ _ A _ C,, BAC_id))\n          with (@matrix_mult F _ _ A _ C) in *.\n        rewrite <- eq, (pr2 linv).\n        apply idpath.\n      }\n      simpl in * |- ;\n      now rewrite <- BAC_id, <- linv_eq.\n    - right.\n      intros [invM [isl isr]].\n      pose (isinv := @make_matrix_left_inverse _ _ _ n _ _ isr).\n      assert (isinvprod : (matrix_left_inverse BA)).\n      { apply left_inv_matrix_prod_is_left_inv; try assumption.\n        apply (@matrix_inverse_to_right_and_left_inverse F _ B),\n          gauss_clear_all_rows_matrix_invertible. }\n      pose (contr_eq := @left_invertible_upper_triangular_to_diagonal_all_nonzero _ _ ut isinvprod idx).\n      rewrite isnotz in contr_eq.\n      contradiction.\n  Defined.\n\nEnd Inverse.\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/GaussianElimination/Corollaries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7954626601161001}}
{"text": "(* Discrete Mathematics in Coq, based on definitions in Epp, 4th Edition *)\n\nRequire Import Omega.\nRequire Import Nat.\nRequire Import List.\nRequire Import Arith.\nRequire Import Coq.Program.Wf.\n\n(* Section 2.1 *)\n\n(* This is the encoding of a definition of a statement, p. 24.\n   It's called \"lem\" because the formal name for this property is the\n   \"Law of the Excluded Middle.\"\n\n   Not all logics include this notion, so it's not built into Coq. Instead,\n   we declare it as an axiom. A logic that doesn't have L.E.M. is called\n   constructive. A logic that does include L.E.M. is called classical. *)\nAxiom lem : forall p, p \\/ ~p.\n\nTheorem and_comm : forall p q, p /\\ q <-> q /\\ p.\nProof.\n  intro p.\n  intro q.\n  split.\n  - intro p_and_q.\n    destruct p_and_q.\n    split.\n    + assumption.\n    + assumption.\n  - intro q_and_p.\n    destruct q_and_p.\n    split.\n    + assumption.\n    + assumption.\nQed.\n  \nTheorem or_comm : forall p q, p \\/ q <-> q \\/ p.\nProof.\n  intro p. intro q.\n  split.\n  - intro p_or_q.\n    destruct p_or_q.\n    + right.\n      assumption.\n    + left.\n      assumption.\n  - intro q_or_p.\n    destruct q_or_p.\n    + right.\n      assumption.\n    + left.\n      assumption.\nQed.\n\nTheorem and_assoc : forall p q r, (p /\\ q) /\\ r <-> p /\\ (q /\\ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro pq_r.\n    destruct pq_r.\n    destruct H.\n    split.\n    + assumption.\n    + split.\n      * assumption.\n      * assumption.\n  - intro p_qr.\n    destruct p_qr.\n    destruct H0.\n    split.\n    + split.\n      * assumption.\n      * assumption.\n    + assumption.\nQed.\n\nTheorem or_assoc : forall p q r, (p \\/ q) \\/ r <-> p \\/ (q \\/ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro pq_r.\n    destruct pq_r.\n    + destruct H.\n      * left.\n        assumption.\n      * right.\n        left.\n        assumption.\n    + right.\n      right.\n      assumption.\n  - intro p_qr.\n    destruct p_qr.\n    + left.\n      left.\n      assumption.\n    + destruct H.\n      * left.\n        right.\n        assumption.\n      * right.\n        assumption.\nQed.\n\nTheorem and_distrib : forall p q r,\n    p /\\ (q \\/ r) <-> (p /\\ q) \\/ (p /\\ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro and_or.\n    destruct and_or.\n    destruct H0.\n    + left.\n      split.\n      * assumption.\n      * assumption.\n    + right.\n      split.\n      * assumption.\n      * assumption.\n  - intro and_or_and.\n    destruct and_or_and.\n    + destruct H.\n      split.\n      * assumption.\n      * left.\n        assumption.\n    + destruct H.\n      split.\n      * assumption.\n      * right.\n        assumption.\nQed.\n\nTheorem or_distrib : forall p q r, p \\/ (q /\\ r) <-> (p \\/ q) /\\ (p \\/ r).\nProof.\n  intro p. intro q. intro r.\n  split.\n  - intro or_and.\n    destruct or_and.\n    + split.\n      * left.\n        assumption.\n      * left.\n        assumption.\n    + destruct H.\n      split.\n      * right.\n        assumption.\n      * right.\n        assumption.\n  - intro or_and_or.\n    destruct or_and_or.\n    destruct H.\n    + left.\n      assumption.\n    + destruct H0.\n      * left.\n        assumption.\n      * right.\n        split.\n        -- assumption.\n        -- assumption.\nQed.\n\nTheorem and_ident : forall p, p /\\ True <-> p.\nProof.\n  intro p.\n  split.\n  - intro p_and_true.\n    destruct p_and_true.\n    assumption.\n  - intro pf_p.\n    split.\n    + assumption.\n    + constructor.\nQed.\n\nTheorem or_ident : forall p, p \\/ False <-> p.\nProof.\n  intro p.\n  split.\n  - intro p_or_false.\n    destruct p_or_false.\n    + assumption.\n    + contradiction.\n  - intro pf_p.\n    left.\n    assumption.\nQed.\n\nTheorem and_neg : forall p, p /\\ ~p <-> False.\nProof.\n  intro p.\n  split.\n  - intro p_and_not_p.\n    destruct p_and_not_p.\n    contradiction.\n  - intro false.\n    contradiction.\nQed.\n\nTheorem or_neg : forall p, p \\/ ~p <-> True.\nProof.\n  intro p.\n  split.\n  - intro p_or_not_p.\n    constructor.\n  - intro true.\n    apply lem.\nQed.\n\nTheorem double_neg : forall p, ~(~p) <-> p.\nProof.\n  intro p.\n  split.\n  - intro not_not_p.\n    pose proof (lem p).\n    destruct H.\n    + assumption.\n    + contradiction.\n  - intro pf_p.\n    intro not_p.\n    contradiction.\nQed.\n\nTheorem and_idempotent : forall p, p /\\ p <-> p.\nAdmitted. (* This is what you tell Coq when you don't want to prove it.\n             Here, I'm leaving this as an exercise. *)\n\nTheorem or_idempotent : forall p, p \\/ p <-> p.\nAdmitted.\n\nTheorem and_bound : forall p, p /\\ False <-> False.\nAdmitted.\n\nTheorem or_bound : forall p, p \\/ True <-> True.\nAdmitted.\n\nTheorem and_deMorgan : forall p q, ~(p /\\ q) <-> ~p \\/ ~q.\nProof.\n  intro p. intro q.\n  split.\n  - intro not_p_and_q.\n    pose proof (lem p) as lem_p.\n    pose proof (lem q) as lem_q.\n    destruct lem_p.\n    + destruct lem_q.\n      * exfalso. (* Use this when you know you have a contradiction *)\n        apply not_p_and_q. (* If you're proving False, you can apply a ~(...) to\n                              change the goal to prove (...). *)\n        split.\n        -- assumption.\n        -- assumption.\n      * right.\n        assumption.\n    + left.\n      assumption.\n  - intro not_p_or_not_q.\n    destruct not_p_or_not_q.\n    + intro p_and_q.\n      destruct p_and_q.\n      contradiction.\n    + intro p_and_q.\n      destruct p_and_q.\n      contradiction.\nQed.\n\nTheorem or_deMorgan : forall p q, ~(p \\/ q) <-> ~p /\\ ~q.\nProof.\n  intro p. intro q.\n  split.\n  - intro not_p_or_q.\n    split.\n    + intro pf_p.\n      apply not_p_or_q.\n      left.\n      assumption.\n    + intro pf_q.\n      apply not_p_or_q.\n      right.\n      assumption.\n  - intro not_p_and_not_q.\n    destruct not_p_and_not_q.\n    intro p_or_q.\n    destruct p_or_q.\n    + contradiction.\n    + contradiction.\nQed.\n\nTheorem and_absorption : forall p q, p /\\ (p \\/ q) <-> p.\nAdmitted.\n\nTheorem or_absorption : forall p q, p \\/ (p /\\ q) <-> p.\nAdmitted.\n\nTheorem not_true : ~ True <-> False.\nProof.\n  split.\n  - intro not_true.\n    contradiction.\n  - intro false.\n    contradiction.\nQed.\n\nTheorem not_false : ~ False <-> True.\nProof.\n  split.\n  - intro not_false.\n    constructor.\n  - intro true.\n    intro false.\n    contradiction.\nQed.\n\nTheorem problem_2_1_53 :\n  forall p q, ~((~p /\\ q) \\/ (~p /\\ ~q)) \\/ (p /\\ q) <-> p.\nProof.\n  intro p. intro q.\n  rewrite or_deMorgan. (* rewrite uses a proof of equivalence to rewrite the goal *)\n  rewrite and_deMorgan.\n  rewrite and_deMorgan.\n  rewrite double_neg.\n  rewrite double_neg.\n  rewrite <- or_distrib. (* this variant rewrites right-to-left *)\n  rewrite and_comm.\n  rewrite and_neg.\n  rewrite or_ident.\n  rewrite or_absorption.\n  reflexivity. (* this solves a reflexive equivalence goal *)\nQed.\n\nTheorem problem_2_1_52 : forall p q, ~(p \\/ ~q) \\/ (~p /\\ ~q) <-> ~p.\nAdmitted. (* Exercise *)\n\n(* Section 2.2 *)\n\nTheorem implication : forall (p q : Prop), (p -> q) <-> (~p \\/ q).\n(* Note that Coq allows us to say what we're quantifying over. Above, it could\n   always infer it. But, (->) is overloaded, so we need to tell Coq. *)\nProof.\n  intro p. intro q.\n  split.\n  - intro implic.\n    pose proof (lem p) as lem_p.\n    destruct lem_p.\n    + right.\n      (* Here, we know (p -> q) and we're trying to prove q. If we `apply implic`, then\n         our goal will reduce to just p. *)\n      apply implic.\n      assumption.\n    + left.\n      assumption.\n  - intro or.\n    intro pf_p. (* we can assume p here, because we're proving (p -> q) *)\n    destruct or.\n    + contradiction.\n    + assumption.\nQed.\n\nTheorem neg_implication : forall (p q : Prop), ~(p -> q) <-> p /\\ ~q.\nAdmitted.\n\nTheorem contrapositive : forall (p q : Prop), (p -> q) <-> (~q -> ~p).\nProof.\n  intro p. intro q.\n  rewrite implication.\n  rewrite implication.\n  rewrite double_neg.\n  rewrite or_comm.\n  reflexivity.\nQed.\n\n(* Section 3.2 *)\n\nTheorem forall_deMorgan : forall {A} {P : A -> Prop},\n    ~(forall x, P x) <-> exists y, ~(P y).\nProof.\n  intro A. intro P.\n  split.\n  - intro not_forall.\n    rewrite <- double_neg.\n    intro not_exists.\n    apply not_forall.\n    intro x.\n    rewrite <- double_neg.\n    intro not_pred.\n    apply not_exists.\n    exists x. (* This is how we choose the value of an existential variable. *)\n    assumption.\n  - intro ex.\n    destruct ex. (* You can use destruct to get a given existential variable. *)\n    intro all.\n    specialize (all x). (* instantiate a forall *)\n    contradiction.\nQed.\n\nTheorem exists_deMorgan : forall {A} {P : A -> Prop},\n    ~(exists x, P x) <-> forall y, ~(P y).\nProof.\n  intro A. intro P.\n  split.\n  - intro not_exists.\n    intro y.\n    intro pred_y.\n    apply not_exists.\n    exists y.\n    assumption.\n  - intro all.\n    intro ex.\n    destruct ex.\n    specialize (all x).\n    contradiction.\nQed.\n\n(* Section 3.3 *)\n\n(* There exists a positive integer m such that for all\n   positive integers n, m <= n. *)\nTheorem example_3_3_5 : exists m,\n    m > 0 /\\ forall n, n > 0 -> m <= n.\nProof.\n  exists 1.\n  split.\n  - omega.\n  - intro n.\n    intro n_gt_0.\n    omega.\nQed.\n  \n(* Section 4.1 *)\nDefinition even n := exists k, n = 2 * k.\nDefinition odd n  := exists k, n = 2 * k + 1.\n\nDefinition prime n := n > 1 /\\ forall r s, (r > 0 /\\ s > 0 /\\ n = r * s) -> (r = n \\/ s = n).\nDefinition composite n := exists r s, r > 0 /\\ s > 0 /\\ n = r * s /\\ 1 < r < n /\\ 1 < s < n.\n\nTheorem two_prime : prime 2.\nProof.\n  unfold prime. (* This unfolds a definition in the goal. *)\n  split.\n  - omega.\n  - intro r.\n    intro s.\n    intro Hyp.\n    destruct Hyp.\n    destruct H0.\n    destruct r. (* either r is 0 or greater than 0. *)\n    + omega.\n    + destruct s.\n      * omega.\n      * destruct r.\n        -- destruct s.\n           ++ omega.\n           ++ destruct s.\n              ** omega.\n              ** omega.\n        -- destruct s.\n           ++ omega.\n           ++ simpl in H1.\n              rewrite <- plus_n_Sm in H1.\n              inversion H1.\nQed.\n(* That proof got a little ugly, because we had to look at all possibilities for r and s\n   below two. *)\n\nTheorem six_composite : composite 6.\nProof.\n  unfold composite.\n  exists 2.\n  exists 3.\n  split.\n  - omega.\n  - split.\n    + omega.\n    + split.\n      * omega.\n      * split.\n        -- omega.\n        -- omega.\nQed.\n\n(* Coq can do induction! *)\nTheorem even_or_odd : forall n, even n \\/ odd n.\nProof.\n  intro n.\n  induction n.\n  - left.\n    unfold even.\n    exists 0.\n    omega.\n  - destruct IHn.\n    + right.\n      unfold even in H.\n      destruct H.\n      unfold odd.\n      exists x.\n      omega.\n    + left.\n      unfold odd in H.\n      destruct H.\n      unfold even.\n      exists (x + 1).\n      omega.\nQed.\n      \n\nTheorem not_odd__even : forall n, ~ (odd n) <-> even n.\nProof.\n  intro n.\n  split.\n  * intro not_odd.\n    pose proof (even_or_odd n).\n    destruct H.\n    - assumption.\n    - contradiction.\n  * intro pf_even.\n    intro pf_odd.\n    destruct pf_even.\n    destruct pf_odd.\n    subst. (* This performs all substitutions Coq can find. *)\n    omega.\nQed.\n\nTheorem problem_4_1_28 : forall n, odd n -> odd (n * n).\nProof.\n  intro n. intro Hodd.\n  unfold odd in *. (* unfold everywhere *)\n  destruct Hodd.\n  (* (2x+1)(2x+1) = 4x^2 + 4x + 1 = 2(2*x^2 + 2*x) + 1 *)\n  exists (2 * x * x + 2 * x).\n  subst.\n  ring. (* like omega, but works better with multiplication *)\nQed.\n\nTheorem problem_4_1_27 : forall n m, (odd m /\\ odd n) -> odd (m + n).\nAdmitted.\n\nTheorem problem_4_1_30 : forall m, even m -> odd (3 * m + 5).\nAdmitted.\n\nInductive ltpair : (nat * nat) -> (nat * nat) -> Prop :=\n| lt_left : forall a b c d, a < c -> ltpair (a,b) (c,d)\n| lt_right : forall a b d, b < d -> ltpair (a,b) (a,d).\n\nProgram Fixpoint Ack m n { measure (m,n) (ltpair) } :=\n  match m with\n  | 0 => n + 1\n  | S m' => match n with\n            | 0 => Ack m' 1\n            | S n' => Ack m' (Ack m n')\n            end\n  end.\nNext Obligation.\n  apply lt_left.\n  omega.\nQed.\nNext Obligation.\n  apply lt_right.\n  omega.\nQed.\nNext Obligation.\n  apply lt_left.\n  omega.\nQed.\nNext Obligation.\nAdmitted. (* Not enough time to figure this one out. *)\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/demo_class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7954626321876224}}
{"text": "\nRequire Export Basics.\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.\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\nEval simpl in (fst (3, 4)).\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' :\n  forall (n m : nat), (n, m) = (fst (n, m), snd (n, m)).\nProof.\n  reflexivity. Qed.\n\nTheorem surjective_pairing_stuck :\n  forall (p : natprod), p = (fst p, snd p).\nProof.\n  simpl. Admitted.\n\nTheorem surjective_pairing :\n  forall (p : natprod), p = (fst p, snd p).\nProof.\n  intros p. destruct p as (n, m). simpl. reflexivity. Qed.\n\n\n(* 練習問題: ★ (snd_fst_is_swap) *)\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). simpl. reflexivity. Qed.\n(* ☐ *)\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\nDefinition l_123' := 1 :: (2 :: (3 :: nil)).\nDefinition l_123'0 := 1 :: (2 :: (3 :: [ ])).\nDefinition l_123'' := 1 :: 2 :: 3 :: nil.\nDefinition l_123''' := [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 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(*\n練習問題: ★★, recommended (list_funs)\n\n以下の nonzeros、 oddmembers、 countoddmembers の定義を完成させなさい。\n *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n    | O :: xs => nonzeros xs\n    | x :: xs => x :: nonzeros xs\n    | [ ]     => []\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    | x :: xs =>\n        match oddb x with\n          | true  => x :: oddmembers xs\n          | false => oddmembers xs\n        end\n    | [ ]     => [ ]\n  end.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  match l with\n    | x :: xs =>\n        match oddb x with\n          | true  => S (countoddmembers xs)\n          | false => countoddmembers xs\n        end\n    | [ ]     => O\n  end.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0,2,4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(* ☐ *)\n\n(*\n練習問題: ★★ (alternate)\n\nalternate の定義を完成させなさい。この関数は、ふたつのリストから交互に要素を取り\n出しひとつに「綴じ合わせる」関数です。具体的な例は下のテストを見てください。\n\n注意: alternate の自然な定義のひとつは、「Fixpoint による定義は『明らかに停止する\n』ものでなければならない」という Coq の要求を満たすことができません。このパターン\nにはまってしまったようであれば、両方のリストの要素を同時に見ていくような少し冗長\nな方法を探してみてください。\n *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    | x :: xs, y :: ys => x :: y :: alternate xs ys\n    | x :: xs, [ ]     => l1\n    | [ ],     _       => l2\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\nDefinition bag := natlist.\n\n(*\n練習問題: ★★★ (bag_functions)\n\nバッグに対する count、 sum、 add、 member 関数の定義を完成させなさい。\n *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n    | [ ] => 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\n(* 下の証明はすべて 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\n(*\n多重集合の sum （直和。または非交和）は集合の union （和）と同じようなものです。\nsum a b は a と b の両方の要素を持つ多重集合です。（数学者は通常、多重集合の\nunion にもう少し異なる定義を与えます。それが、この関数の名前を union にしなかった\n理由です。） sum のヘッダには引数の名前を与えませんでした。さらに、 Fixpoint では\nなく Definition を使っています。ですから、引数に名前がついていたとしても再帰的な\n処理はできません。問題をこのように設定したのは、 sum を（定義済みの関数を使うとい\nった）別の方法で定義できないか考えさせるためです。\n *)\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  ble_nat 1 (count v s).\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★★★, optional (bag_more_functions)\n\n練習として、さらにいくつかの関数を作成してください。\n *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    | [ ] => [ ]\n    | x :: xs =>\n        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:\n  count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\nProof. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n    | [ ] => [ ]\n    | x :: xs =>\n        match (beq_nat x v) with\n          | true  => remove_all v xs\n          | false => x :: remove_all v xs\n        end\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. reflexivity. Qed.\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    | [ ] => true\n    | e :: es =>\n        match member e s2 with\n          | true  => subset es (remove_one e s2)\n          | false => false\n        end\n  end.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\nProof. reflexivity. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★★★, recommended (bag_theorem)\n\ncount や add を使ったバッグに関する面白い定理書き、それを証明しなさい。この問題は\nいわゆる自由課題で、真になることがわかっていても、証明にはまだ習っていない技を使\nわなければならない定理を思いついてしまうこともあります。証明に行き詰まってしまっ\nたら気軽に質問してください。\n *)\n\nTheorem count_add_bag :\n  forall (v : nat) (s : bag), count v (add v s) = 1 + count v s.\nProof.\n  intros v s. simpl. rewrite <- beq_nat_refl. reflexivity. Qed.\n\nTheorem count_sum_bag :\n  forall (v : nat) (xs ys : bag), count v (sum xs ys) = count v xs + count v ys.\nProof.\n  intros v xs ys. induction xs as [| x xs'].\n  Case \"xs = [ ]\". reflexivity.\n  Case \"xs = x :: xs'\".\n    simpl. rewrite -> IHxs'. destruct (beq_nat x v).\n    reflexivity. reflexivity. Qed.\n\n(* ☐ *)\n\n\nTheorem nil_app :\n  forall l:natlist, [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred :\n  forall l:natlist, 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 :\n  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 :\n  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\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 :\n  forall l : natlist, 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    simpl. Admitted.\n\nTheorem length_snoc :\n  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 :\n  forall l : natlist, 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 l'\".\n    simpl. rewrite -> length_snoc.\n    rewrite -> IHl'. reflexivity. Qed.\n\n\n(*\nリストについての練習問題 (1)\n\n練習問題: ★★★, recommended (list_exercises)\n\nリストについてさらに練習しましょう。\n *)\n\nTheorem app_nil_end :\n  forall l : natlist, l ++ [] = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nLemma rev_snoc :\n  forall (l : natlist) (n : nat), rev (snoc l n) = n :: rev l.\nProof.\n  intros l n. induction l as [| m l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHl'.\n    simpl. reflexivity. Qed.\n\nTheorem rev_involutive :\n  forall l : natlist, rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> rev_snoc. rewrite -> IHl'.\n    reflexivity. Qed.\n\nLemma app_snoc :\n  forall (l1 l2 : natlist) (n : nat), snoc (l1 ++ l2) n = l1 ++ snoc l2 n.\nProof.\n  intros l1 l2 n. induction l1 as [| m l1'].\n  Case \"l1 = nil\". reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem distr_rev :\n  forall l1 l2 : natlist, rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\". simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. rewrite -> app_snoc.\n    reflexivity. Qed.\n\n(*\n次の問題には簡単な解法があります。こんがらがってしまったようであれば、少し戻って\n単純な方法を探してみましょう。\n *)\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. rewrite <- app_ass. rewrite <- app_ass.\n  reflexivity. Qed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros l n. induction l as [| m l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons m l'\".\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\n(* 前に書いた nonzeros 関数に関する練習問題です。 *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\". reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. destruct n.\n    reflexivity. reflexivity. Qed.\n(* ☐ *)\n\n(*\nリストについての練習問題 (2)\n\n練習問題: ★★, recommended (list_design)\n\n自分で問題を考えましょう。\n\n ・ cons （::）、 snoc、 append （++）に関する、自明でない定理を考えて書きなさい\n    。\n ・ それを証明しなさい。\n *)\n\nLemma snoc_cons_app :\n  forall (l1 l2 : natlist) (n:nat), (snoc l1 n) ++ l2 = l1 ++ n :: l2.\nProof.\n  intros l1 l2 n. rewrite -> snoc_append. rewrite -> app_ass.\n  simpl. reflexivity. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★★, optional (bag_proofs)\n\n前のバッグについての optional な練習問題に挑戦したのであれば、その定義について、\n以下の定理を証明しなさい。\n *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. reflexivity. Qed.\n\n(* 以下の ble_nat に関する補題は、この次の証明に使えるかもしれません。 *)\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intros n. induction n as [| n'].\n  Case \"0\".\n    simpl. reflexivity.\n  Case \"S n'\".\n    simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. induction s as [| n s'].\n  Case \"s = nil\". reflexivity.\n  Case \"s = cons n s'\".\n    simpl. destruct (beq_nat n 0) as [] eqn: H.\n    SCase \"beq_nat n 0 = true\".\n      rewrite -> ble_n_Sn. reflexivity.\n    SCase \"beq_nat n 0 = false\".\n      simpl. rewrite -> H. rewrite -> IHs'. reflexivity.\nQed.\n\n(* ☐ *)\n\n(*\n練習問題: ★★★★, optional (rev_injective)\n\nrev 関数が単射である、すなわち\n    forall X (l1 l2 : list X), rev l1 = rev l2 -> l1 = l2\n\nであることを証明しなさい。\n\nこの練習問題には簡単な解法と難しい解法があります。\n *)\n\nModule PlayGroundRevInjective.\n\nRequire Import List.\n\nLemma rev_snoc :\n  forall X (l : list X) (x : X), rev (l ++ x :: nil) = x :: rev l.\nProof.\n  intros X l x. induction l as [| x' l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = x' :: l'\".\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nLemma rev_involutive' :\n  forall X (l : list X), rev (rev l) = l.\nProof.\n  intros X l. induction l as [| x l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons x l'\".\n    simpl. rewrite -> rev_snoc. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem rev_injective :\n  forall X (l1 l2 : list X), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros X l1 l2 H.\n  rewrite <- rev_involutive'.\n  rewrite <- H.\n  rewrite -> rev_involutive'.\n  reflexivity.\nQed.\n\n(* ☐ *)\nEnd PlayGroundRevInjective.\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\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\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\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\n(*\n練習問題: ★★ (hd_opt)\n\n同じ考え方を使って、以前定義した hd 関数を修正し、 nil の場合に返す値を渡\nさなくて済むようにしなさい。\n *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n    | x :: xs => Some x\n    | [ ]     => None\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(*\n練習問題: ★★, optional (option_elim_hd)\n\n新しい hd_opt と古い hd の関係についての練習問題です。\n *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim (hd_opt l) default.\nProof.\n  intros l default. destruct l as [| x xs].\n  Case \"l = nil\". reflexivity.\n  Case \"l = case x xs\". reflexivity. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★★, recommended (beq_natlist)\n\n数のリストふたつを比較し等価性を判定する関数 beq_natlist の定義を完成させ\nなさい。そして、 beq_natlist l l が任意のリスト l で true となることを証\n明しなさい。\n *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n    | x1 :: l1', x2 :: l2' =>\n        match beq_nat x1 x2 with\n          | true  => beq_natlist l1' l2'\n          | false => false\n        end\n    | [ ], [ ]             => true\n    | _ :: _ , [ ]         => 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 :\n  forall l:natlist, true = beq_natlist l l.\nProof.\n  intros l. induction l as [|n l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons n l'\".\n    simpl. rewrite <- beq_nat_refl. rewrite <- IHl'.\n    reflexivity. Qed.\n(* ☐ *)\n\nTheorem silly1 :\n  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 :\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 n m o p eq1 eq2.\n  apply eq2. apply eq1. Qed.\n\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 n m o p eq1 eq2.\n  rewrite <- eq1.\nAdmitted.\n *)\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 eq1 eq2.\n  apply eq2. apply eq1. Qed.\n\n(*\n練習問題: ★★, optional (silly_ex)\n\n次の証明を simpl を使わずに完成させなさい。\n *)\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 H0 H1. apply H0. apply H1. Qed.\n(* ☐ *)\n\n\nTheorem silly3_firsttry :\n  forall (n : nat),\n    true = beq_nat n 5 ->\n    beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\nAdmitted.\n\nTheorem silly3 :\n  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\n\n(* 練習問題: ★★★, recommended (apply_exercise1) *)\n\nTheorem rev_exercise1 :\n  forall (l l' : natlist),\n    l = rev l' ->\n    l' = rev l.\nProof.\n  intros l l' H. rewrite -> H. symmetry. apply rev_involutive. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★ (apply_rewrite)\n\napply と rewrite の違いを簡単に説明しなさい。どちらもうまく使えるような場\n面はありますか？\n *)\n\n(*\n結果の型が一致しているときに使えるのが apply。\nequalityが示せているときに使えるのが rewrite。\n結果の型がequalityであるときにはどちらも使える場合がある。\n *)\n(* ☐ *)\n\n(*\n練習問題: ★★, optional (app_ass')\n\n++ の結合則をより一般的な仮定のもとで証明しなさい。（最初の行を変更せずに\n）次の証明を完成させること。\n *)\n\nTheorem app_ass' :\n  forall l1 l2 l3 : natlist, (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1. induction l1 as [ | n l1'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons n l1'\".\n    simpl. intros l2 l3.\n    rewrite -> IHl1'. reflexivity. Qed.\n(* ☐ *)\n\n(*\n練習問題: ★★★ (apply_exercise2)\n\ninduction の前に m を intros していないことに注意してください。これによっ\nて仮定が一般化され、帰納法の仮定が特定の m に縛られることがなくなり、より\n使いやすくなりました。\n *)\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\".\n    destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". reflexivity.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [| m'].\n      SCase \"m = 0\". reflexivity.\n      SCase \"m = S m'\".\n        simpl. apply IHn'.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★★, recommended (beq_nat_sym_informal)\n\n以下の補題について上の証明と対応する非形式的な証明を書きなさい。\n\n定理: 任意の nat n m について、 beq_nat n m = beq_nat m n。\n *)\n\n(*\n証明: n についての帰納法を適用する。\n   □ まず n = 0 と置くと以下のようになる\n        forall m, beq_nat 0 m = beq_nat m 0\n        m = 0 のとき\n          beq_nat 0 0 = beq_nat 0 0 で成り立つ\n        m = S m' のとき\n          beq_nat の定義から、\n          beq_nat 0 (S m') = false = beq_nat (S m') 0\n          で成り立つ\n   □ 次に n = S n' と置き、帰納法の仮定を\n        forall m, beq_nat n' m = beq_nat m n'\n        とすると、\n\n        m = 0 のとき\n          beq_nat (S n') 0 = false = beq_nat 0 (S n')\n          で成り立つ\n        m = S m' のとき、forall m に注意すると帰納法の仮定から\n          beq_nat n' m' = beq_nat m' n'\n        も成り立つ。\n        これを beq_nat の定義から逆変換すると\n          beq_nat (S n') (S m') = beq_nat (S m') (S n')\n\n        これは n = S n ' についても帰納法の仮定が成り立つことを示している ☐\n *)\n\nEnd NatList.\n\n(* 練習問題: 辞書 *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n  | empty : dictionary\n  | record : nat -> nat -> dictionary -> dictionary.\n\n(*\nこの宣言は次のように読めます。「dictionary を構成する方法はふたつある。構\n成子 empty で空の辞書を表現するか、構成子 record をキーと値と既存の\ndictionary に適用してキーと値の対応を追加した dictionary を構成するかのい\nずれかである」。\n *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n  (record key value d).\n\nEval simpl in insert 0 1 empty.\nEval simpl in record 0 1 empty.\n\n(*\n下の find 関数は、 dictionary から与えられたキーに対応する値を探し出すも\nのです。キーが見つからなかった場合には None に評価され、キーが val に結び\n付けられていた場合には Some val に評価されます。同じキーが複数の値に結び\n付けられている場合には、最初に見つかったほうの値を返します。\n *)\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\n(* 練習問題: ★ (dictionary_invariant1) *)\n\nTheorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros d k v. simpl. rewrite <- beq_nat_refl. reflexivity. Qed.\n(* ☐ *)\n\n(* 練習問題: ★ (dictionary_invariant2) *)\n\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n  (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n  intros d m n o H. simpl. rewrite -> H. reflexivity. Qed.\n(* ☐ *)\n\nEnd Dictionary.\n\nDefinition beq_nat_sym := NatList.beq_nat_sym.\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7954442767986084}}
{"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(** * Shared libraries *)\n\n(** ** Finitary sums and products over monoids *)\n\nRequire Import List Arith Omega Eqdep_dec ZArith.\n\nRequire Import utils_tac utils_list binomial.\n\nSet Implicit Arguments.\n\nRecord monoid_theory (X : Type) (m : X -> X -> X) (u : X) := mk_monoid {\n  monoid_unit_l : forall x, m u x = x;\n  monoid_unit_r : forall x, m x u = x;\n  monoid_assoc  : forall x y z, m x (m y z) = m (m x y) z;\n}.\n\nFact Nat_plus_monoid : monoid_theory plus 0.\nProof. exists; intros; ring. Qed.\n\nFact Nat_mult_monoid : monoid_theory mult 1.\nProof. exists; intros; ring. Qed.\n\nFact Zplus_monoid : monoid_theory Zplus 0%Z.\nProof. exists; intros; ring. Qed.\n\nFact Zmult_monoid : monoid_theory Zmult 1%Z.\nProof. exists; intros; ring. Qed.\n\nHint Resolve Nat_plus_monoid Nat_mult_monoid\n             Zplus_monoid Zmult_monoid.\n\nSection msum.\n\n  Variable (X : Type) (m : X -> X -> X) (u : X).\n\n  Infix \"⊕\" := m (at level 50, left associativity).\n\n  Fixpoint msum n f := \n    match n with \n      | 0   => u\n      | S n => f 0 ⊕ msum n (fun n => f (S n))\n    end.\n\n  Notation \"∑\" := msum.\n\n  Fact msum_fold_map n f : ∑ n f = fold_right m u (map f (list_an 0 n)).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; f_equal; auto.\n    rewrite IHn, <-  map_S_list_an, map_map; auto.\n  Qed.\n\n  Fact msum_0 f : ∑ 0 f = u.\n  Proof. auto. Qed.\n\n  Fact msum_S n f : ∑ (S n) f = f 0 ⊕ ∑ n (fun n => f (S n)).\n  Proof. auto. Qed.\n\n  Hypothesis Hmonoid : monoid_theory m u.\n\n  Fact msum_1 f : ∑ 1 f = f 0.\n  Proof.\n    destruct Hmonoid as [ H1 H2 ].\n    rewrite msum_S, msum_0, H2; auto.\n  Qed.\n\n  Fact msum_plus a b f : ∑ (a+b) f = ∑ a f ⊕ ∑ b (fun i => f (a+i)).\n  Proof.\n    destruct Hmonoid as [ H1 _ H3 ].\n    revert f; induction a as [ | a IHa ]; intros f; simpl; auto.\n    rewrite <- H3; f_equal; apply IHa.\n  Qed.\n\n  Fact msum_plus1 n f : ∑ (S n) f = ∑ n f ⊕ f n.\n  Proof.\n    destruct Hmonoid as [ _ H2 _ ].\n    replace (S n) with (n+1) by omega.\n    rewrite msum_plus; simpl; f_equal.\n    rewrite H2; f_equal; omega.\n  Qed.\n\n  Fact msum_ext n f g : (forall i, i < n -> f i = g i) -> ∑ n f = ∑ n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g Hfg; simpl; f_equal; auto.\n    + apply Hfg; omega.\n    + apply IHn; intros; apply Hfg; omega.\n  Qed.\n\n  Fact msum_unit n : ∑ n (fun _ => u) = u.\n  Proof.\n    destruct Hmonoid as [ H1 _ _ ].\n    induction n as [ | n IHn ]; simpl; auto.\n    rewrite IHn; auto.\n  Qed.\n\n  Fact msum_comm a n f : (forall i, i < n -> f i ⊕ a = a ⊕ f i) -> ∑ n f ⊕ a = a ⊕ ∑ n f.\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f; induction n as [ | n IHn ]; intros f H; simpl; auto.\n    + rewrite H1, H2; auto.\n    + rewrite H3, <- H; try omega.\n      repeat rewrite <- H3; f_equal.\n      apply IHn.\n      intros; apply H; omega.\n  Qed.\n\n  Fact msum_sum n f g : (forall i j, i < j < n -> f j ⊕ g i = g i ⊕ f j) -> ∑ n (fun i => f i ⊕ g i) = ∑ n f ⊕ ∑ n g.\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    revert f g; induction n as [ | n IHn ]; intros f g H; simpl; auto.\n    rewrite IHn.\n    + repeat rewrite <- H3; f_equal.\n      repeat rewrite H3; f_equal.\n      symmetry; apply msum_comm.\n      intros; apply H; omega.\n    + intros; apply H; omega.\n  Qed.\n\n  Fact msum_of_unit n f : (forall i, i < n -> f i = u) -> ∑ n f = u.\n  Proof.\n    intros H.\n    rewrite <- (msum_unit n).\n    apply msum_ext; auto.\n  Qed.\n\n  Fact msum_only_one n f i : i < n\n                          -> (forall j, j < n -> i <> j -> f j = u)\n                          -> ∑ n f = f i.\n  Proof.\n    destruct Hmonoid as [ M1 M2 M3 ].\n    intros H1 H2.\n    replace n with (i + 1 + (n-i-1)) by omega.\n    do 2 rewrite msum_plus.\n    rewrite msum_of_unit, msum_1, msum_of_unit, M1, M2.\n    + f_equal; omega.\n    + intros j Hj; destruct (H2 (i+1+j)); auto; omega.\n    + intros j Hj; destruct (H2 j); auto; omega.\n  Qed.\n\n  Fact msum_msum n k f :\n          (forall i1 j1 i2 j2, i1 < n -> j1 < k -> i2 < n -> j2 < k -> f i1 j1 ⊕ f i2 j2 = f i2 j2 ⊕ f i1 j1)\n       -> ∑ n (fun i => ∑ k (f i)) = ∑ k (fun j => ∑ n (fun i => f i j)).\n  Proof.\n    revert k f; induction n as [ | n IHn ]; intros k f Hf.\n    + rewrite msum_0, msum_of_unit; auto.\n    + rewrite msum_S, IHn.\n      * rewrite <- msum_sum.\n        - apply msum_ext.\n          intros; rewrite msum_S; trivial.\n        - intros; symmetry; apply msum_comm.\n          intros; apply Hf; omega.\n      * intros; apply Hf; omega.\n  Qed.\n\n  Fact msum_ends n f : (forall i, 0 < i <= n -> f i = u) -> ∑ (n+2) f = f 0 ⊕ f (S n).\n  Proof.\n    destruct Hmonoid as [ H1 H2 H3 ].\n    intros H.\n    replace (n+2) with (1 + n + 1) by omega.\n    do 2 rewrite msum_plus; simpl.\n    rewrite msum_of_unit.\n    + rewrite H2, H2, H2; do 2 f_equal; omega.\n    + intros; apply H; omega.\n  Qed.\n\n  Fact msum_first_two n f : 2 <= n -> (forall i, 2 <= i -> f i = u) -> ∑ n f = f 0 ⊕ f 1.\n  Proof.\n    destruct Hmonoid as [ _ M2 _ ].\n    intros Hn H1.\n    destruct n as [ | [ | n ] ]; try omega.\n    do 2 rewrite msum_S.\n    rewrite msum_of_unit.\n    + rewrite M2; trivial.\n    + intros; apply H1; omega.\n  Qed.\n\n  Definition mscal n x := msum n (fun _ => x).\n\n  Fact mscal_0 x : mscal 0 x = u.\n  Proof. apply msum_0. Qed.\n\n  Fact mscal_S n x : mscal (S n) x = x ⊕ mscal n x.\n  Proof. apply msum_S. Qed.\n\n  Fact mscal_1 x : mscal 1 x = x.\n  Proof. \n    destruct Hmonoid as [ _ H2 _ ].\n    rewrite mscal_S, mscal_0, H2; trivial.\n  Qed.\n\n  Fact mscal_of_unit n : mscal n u = u.\n  Proof. apply msum_of_unit; auto. Qed.\n\n  Fact mscal_plus a b x : mscal (a+b) x = mscal a x ⊕ mscal b x.\n  Proof. apply msum_plus. Qed.\n\n  Fact mscal_plus1 n x : mscal (S n) x = mscal n x ⊕ x.\n  Proof. apply msum_plus1. Qed.\n\n  Fact mscal_comm n x y : x ⊕ y = y ⊕ x -> mscal n x ⊕ y = y ⊕ mscal n x.\n  Proof. intros H; apply msum_comm; auto. Qed.\n\n  Fact mscal_sum n x y : x ⊕ y = y ⊕ x -> mscal n (x ⊕ y) = mscal n x ⊕ mscal n y.\n  Proof. intro; apply msum_sum; auto. Qed.\n\n  Fact mscal_mult a b x : mscal (a*b) x = mscal a (mscal b x).\n  Proof.\n    induction a as [ | a IHa ]; simpl.\n    + do 2 rewrite mscal_0; auto.\n    + rewrite mscal_plus, IHa, mscal_S; auto.\n  Qed.\n\n  Fact msum_mscal n k f : (forall i j, i < n -> j < n -> f i ⊕ f j = f j ⊕ f i) \n                       -> ∑ n (fun i => mscal k (f i)) = mscal k (∑ n f).\n  Proof. intros H; apply msum_msum; auto. Qed.\n\nEnd msum.\n\nSection msum_morphism.\n\n  Variable (X Y : Type) (m1 : X -> X -> X) (u1 : X) \n                        (m2 : Y -> Y -> Y) (u2 : Y)\n           (H1 : monoid_theory m1 u1)\n           (H2 : monoid_theory m2 u2)\n           (phi : X -> Y)\n           (Hphi1 : phi u1 = u2)\n           (Hphi2 : forall x y, phi (m1 x y) = m2 (phi x) (phi y)).\n\n  Fact msum_morph n f : phi (msum m1 u1 n f) = msum m2 u2 n (fun x => phi (f x)).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; auto.\n    rewrite Hphi2, IHn; trivial.\n  Qed.\n\n  Fact mscal_morph n x : phi (mscal m1 u1 n x) = mscal m2 u2 n (phi x).\n  Proof. apply msum_morph. Qed.\n\nEnd msum_morphism.\n\nSection binomial_Newton.\n\n  Variable (X : Type) (sum times : X -> X -> X) (zero one : X).\n\n  Infix \"⊕\" := sum (at level 50, left associativity).\n  Infix \"⊗\" := times (at level 40, left associativity).\n  \n  Notation z := zero.\n  Notation o := one.\n\n  Notation scal := (mscal sum zero).\n  Notation expo := (mscal times one).\n\n  Hypothesis (M_sum : monoid_theory sum zero) \n             (sum_comm : forall x y, x ⊕ y = y ⊕ x)\n             (sum_cancel : forall x u v, x ⊕ u = x ⊕ v -> u = v)\n             (M_times : monoid_theory times one)\n             (distr_l : forall x y z, x ⊗ (y⊕z) = x⊗y ⊕ x⊗z)\n             (distr_r : forall x y z, (y⊕z) ⊗ x = y⊗x ⊕ z⊗x).\n\n  Fact times_zero_l x : z ⊗ x = z.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (z⊗x).\n    rewrite S2, <- distr_r, S1; trivial.\n  Qed.\n\n  Fact times_zero_r x : x ⊗ z = z.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    apply sum_cancel with (x⊗z).\n    rewrite S2, <- distr_l, S1; trivial.\n  Qed.\n\n  Notation \"∑\" := (msum sum zero).\n\n  Fact sum_0n_scal n k f : ∑ n (fun i => scal k (f i)) = scal k (∑ n f).\n  Proof. apply msum_mscal; auto. Qed.\n\n  Fact scal_times k x y : scal k (x⊗y) = x⊗scal k y.\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, mscal_0, times_zero_r; auto.\n    + rewrite mscal_S, mscal_S, IHk, distr_l; auto.\n  Qed.\n\n  Fact scal_one_comm k x : scal k o ⊗ x = x ⊗ scal k o.\n  Proof.\n    destruct M_times as [ T1 T2 T3 ].\n    induction k as [ | k IHk ].\n    + rewrite mscal_0, times_zero_l, times_zero_r; auto.\n    + rewrite mscal_S, distr_l, distr_r; f_equal; auto.\n      rewrite T1, T2; auto.\n  Qed.\n\n  Corollary scal_one k x : scal k x = scal k o ⊗ x.\n  Proof. \n    destruct M_times as [ T1 T2 T3 ].\n    rewrite <- (T2 x) at 1.\n    rewrite scal_times.\n    symmetry; apply scal_one_comm.\n  Qed.\n\n  Fact sum_0n_distr_l b n f : ∑ n (fun i => b⊗f i) = b⊗∑ n f.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_r; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_l; auto.\n  Qed.\n\n  Fact sum_0n_distr_r b n f : ∑ n (fun i => f i⊗b) = ∑ n f ⊗ b.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f.\n    + do 2 rewrite msum_0; rewrite times_zero_l; auto.\n    + do 2 rewrite msum_S; rewrite IHn, distr_r; auto.\n  Qed.\n\n  (**   Newton Binomial theorem for (X,⊕,z,⊗,o) where\n          1) (X,⊕,z) is a cancellative commutative monoid\n          2) (X,⊗,o) is a monoid\n          3) ⊗ distributes over ⊕ on the left and one the right \n\n        cancellative could be weakened into z is left and right\n        absorbing for ⊗, ie a⊗z = z⊗a = z \n\n   *)\n\n  Theorem binomial_Newton n a b :\n        a ⊗ b = b ⊗ a\n     -> expo n (a ⊕ b) = ∑ (S n) (fun i => scal (binomial n i) (expo (n - i) a ⊗ expo i b)).\n  Proof.\n    destruct M_sum as [ S1 S2 S3 ].\n    destruct M_times as [ T1 T2 T3 ].\n    intros Hab; induction n as [ | n IHn ].\n    + rewrite mscal_0, msum_S, msum_0; simpl.\n      rewrite mscal_0, mscal_0, mscal_1; auto.\n      rewrite S2, T1; auto.\n    + rewrite msum_S with (n := S n), binomial_n0, mscal_1; auto.\n      rewrite mscal_0, Nat.sub_0_r; auto.\n      rewrite T2.\n      rewrite msum_ext with (g := fun i => b ⊗ scal (binomial n i) (expo (n-i) a ⊗ expo i b)\n                                         ⊕ a ⊗ scal (binomial n (S i)) (expo (n-S i) a ⊗ expo (S i) b)).\n      2: { intros; rewrite binomial_SS, mscal_plus; auto.\n           replace (S n - S i) with (n-i) by omega; f_equal.\n           * rewrite mscal_S. \n             do 3 rewrite scal_times.\n             do 2 rewrite T3; f_equal.\n             apply mscal_comm; auto.\n           * destruct (le_lt_dec n i).\n             + rewrite binomial_gt; try omega.\n               do 2 rewrite mscal_0.\n               rewrite times_zero_r; auto.\n             + replace (n - i) with (S (n - S i)) by omega.\n               rewrite mscal_S.\n               repeat rewrite scal_times.\n               repeat rewrite T3; auto. }\n      rewrite msum_sum; auto.\n      do 2 rewrite sum_0n_distr_l.\n      rewrite <- IHn.\n      rewrite msum_plus1, binomial_gt; auto.\n      rewrite mscal_0, S2.\n      generalize (msum_S sum z n (fun i => scal (binomial n i) (expo (n-i) a ⊗ expo i b))); intros H.\n      rewrite Nat.sub_0_r, binomial_n0, mscal_1, mscal_0, T2 in H; auto.\n      rewrite S3, (sum_comm (expo _ _)), <- S3.\n      rewrite mscal_S with (x :=a), <- distr_l, <- H, <- IHn.\n      rewrite mscal_S, distr_r.\n      apply sum_comm.\n  Qed.\n\nEnd binomial_Newton.\n\nSection Newton_nat.\n\n  Notation power := (mscal mult 1).\n  Notation \"∑\" := (msum plus 0).\n\n  Fact sum_fold_map n f : ∑ n f = fold_right plus 0 (map f (list_an 0 n)).\n  Proof. apply msum_fold_map. Qed.\n\n  Fact power_0 x : power 0 x = 1.\n  Proof. apply mscal_0. Qed.\n\n  Fact power_S n x : power (S n) x = x * power n x.\n  Proof. apply mscal_S. Qed.\n\n  Fact power_1 x : power 1 x = x.\n  Proof. apply mscal_1, Nat_mult_monoid. Qed.\n\n  Fact power_of_0 n : 0 < n -> power n 0 = 0.\n  Proof. destruct n; try omega; rewrite power_S; auto. Qed.\n\n  Fact power_of_1 n : power n 1 = 1.\n  Proof. rewrite mscal_of_unit; auto. Qed.\n\n  Fact power_plus p a b : power (a+b) p = power a p * power b p.\n  Proof. apply mscal_plus, Nat_mult_monoid. Qed.\n\n  Fact power_mult p a b : power (a*b) p = power a (power b p).\n  Proof. apply mscal_mult; auto. Qed.\n  \n  Fact power_ge_1 k p : p <> 0 -> 1 <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + rewrite power_S.\n      apply (mult_le_compat 1 _ 1); omega.\n  Qed.\n\n  Fact power2_gt_0 n : 0 < power n 2.\n  Proof. apply power_ge_1; discriminate. Qed.\n\n  Fact power_sinc k p : 2 <= p -> power k p < power (S k) p.\n  Proof.\n    intros Hp; rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power k p)) at 1.\n    apply mult_lt_compat_r; try omega.\n    apply power_ge_1; omega.\n  Qed.\n\n  Fact power_ge_n k p : 2 <= p -> k <= power k p.\n  Proof.\n    intros Hp.\n    induction k as [ | k IHk ].\n    + rewrite power_0; auto.\n    + apply le_lt_trans with (2 := power_sinc _ Hp); auto.\n  Qed.\n\n  Fact power_mono_l p q x : 1 <= x -> p <= q -> power p x <= power q x.\n  Proof.\n    intros Hx.\n    induction 1 as [ | q H IH ]; auto.\n    apply le_trans with (1 := IH).\n    rewrite power_S.\n    rewrite <- (Nat.mul_1_l (power _ _)) at 1.\n    apply mult_le_compat; auto.\n  Qed.\n\n  Definition power_mono := power_mono_l.\n  \n  Fact power_smono_l p q x : 2 <= x -> p < q -> power p x < power q x.\n  Proof.\n    intros H1 H2.\n    apply lt_le_trans with (1 := power_sinc _ H1).\n    apply power_mono_l; omega.\n  Qed.\n\n  Fact power_mono_r n p q : p <= q -> power n p <= power n q.\n  Proof.\n    intros H.\n    induction n as [ | n IHn ].\n    + do 2 rewrite power_0; auto.\n    + do 2 rewrite power_S; apply mult_le_compat; auto.\n  Qed. \n\n  Fact power_0_inv p n : power p n = 0 <-> n = 0 /\\ 0 < p.\n  Proof.\n    induction p as [ | p IHp ].\n    + rewrite power_0; omega.\n    + rewrite power_S; split.\n      * intros H.\n        apply mult_is_O in H.\n        rewrite IHp in H; omega.\n      * intros (?&?); subst; simpl; auto.\n  Qed.\n\n  Fact plus_cancel_l : forall a b c, a + b = a + c -> b = c.\n  Proof. intros; omega. Qed.\n\n  Let plus_cancel_l':= plus_cancel_l.\n\n  Fact sum_0n_scal_l n k f : ∑ n (fun i => k*f i) = k*∑ n f.\n  Proof. \n    apply sum_0n_distr_l with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_scal_r n k f : ∑ n (fun i => (f i)*k) = (∑ n f)*k.\n  Proof. \n    apply sum_0n_distr_r with (3 := Nat_mult_monoid); auto.\n    intros; ring.\n  Qed.\n\n  Fact sum_0n_mono n f g : (forall i, i < n -> f i <= g i) -> ∑ n f <= ∑ n g.\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g H.\n    + do 2 rewrite msum_0; auto.\n    + do 2 rewrite msum_S; apply plus_le_compat.\n      * apply H; omega.\n      * apply IHn; intros; apply H; omega.\n  Qed.\n\n  Fact sum_0n_le_one n f i : i < n -> f i <= ∑ n f.\n  Proof.\n    revert f i; induction n as [ | n IHn ]; intros f i H.\n    + omega.\n    + rewrite msum_S.\n      destruct i as [ | i ]; try omega.\n      apply lt_S_n, IHn with (f := fun i => f (S i)) in H.\n      omega.\n  Qed.\n\n  Fact sum_power_lt k n f : k <> 0 -> (forall i, i < n -> f i < k) -> ∑ n (fun i => f i * power i k) < power n k.\n  Proof.\n    intros Hk.\n    revert f; induction n as [ | n IHn ]; intros f Hf.\n    + rewrite msum_0, power_0; omega.\n    + rewrite msum_S, power_S, power_0, Nat.mul_1_r.\n      apply le_trans with (k+ k * (power n k-1)).\n      * apply (@plus_le_compat (S (f 0))).\n        - apply Hf; omega.\n        - rewrite msum_ext with (g := fun i => k*(f (S i)*power i k)).\n          ++ rewrite sum_0n_distr_l with (one := 1); auto; try (intros; ring).\n             apply mult_le_compat_l.\n             apply le_S_n, le_trans with (power n k); try omega.\n             apply IHn; intros; apply Hf; omega.\n          ++ intros; rewrite power_S; ring.\n      * generalize (power_ge_1 n Hk); intros ?.\n        replace (power n k) with (1+(power n k - 1)) at 2 by omega.\n        rewrite Nat.mul_add_distr_l.\n        apply plus_le_compat; omega.\n  Qed. \n\n  Theorem Newton_nat a b n :\n       power n (a + b) = ∑ (S n) (fun i => binomial n i * power (n - i) a * power i b).\n  Proof.\n    rewrite binomial_Newton with (1 := Nat_plus_monoid) (4 := Nat_mult_monoid); try (intros; ring); auto.\n    apply msum_ext; intros i Hi.\n    rewrite scal_one with (1 := Nat_plus_monoid) (3 := Nat_mult_monoid); auto; try (intros; ring).\n    rewrite <-mult_assoc; f_equal; auto.\n    generalize (binomial n i); intros k.\n    induction k as [ | k IHk ].\n    + rewrite mscal_0; auto.\n    + rewrite mscal_S, IHk; auto; apply plus_cancel_l.\n  Qed.\n\n  Theorem Newton_nat_S a n :\n       power n (1 + a) = ∑ (S n) (fun i => binomial n i * power i a).\n  Proof.\n    rewrite Newton_nat.\n    apply msum_ext.\n    intros; rewrite power_of_1; ring.\n  Qed.\n\n  Lemma binomial_le_power n i : binomial n i <= power n 2.\n  Proof.\n    destruct (le_lt_dec i n) as [ Hi | Hi ].\n    + change 2 with (1+1).\n      rewrite Newton_nat_S.\n      eapply le_trans.\n      2:{ apply sum_0n_le_one with (f := fun i => binomial n i * power i 1).\n          apply le_n_S, Hi. }\n      rewrite power_of_1; omega.\n    + rewrite binomial_gt; auto; omega.\n  Qed.\n\n  Corollary binomial_lt_power n i : binomial n i < power (S n) 2.\n  Proof.\n    apply le_lt_trans with (1 := binomial_le_power _ _), power_sinc; auto.\n  Qed.\n\nEnd Newton_nat.\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/sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8670357683915537, "lm_q1q2_score": 0.7953342143413619}}
{"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 saturday).\n\nExample test_next:\n  (next_weekday(next_weekday(saturday))) = tuesday.\n  \nProof. simpl. reflexivity. Qed. *)\n\n(*\nInductive bool : Type :=\n  | true\n  | false.\n  \nDefinition negb (b: 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) : 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*)\n\n(*Level 1 -- nandb*)\n\nDefinition 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\n\n(*Level 1 -- nandb3*)\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. 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(* Check 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) := \n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\n\n\nInductive bit : Type :=\n  | B0\n  | B1.\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\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    | (bits _ _ _ _) => false\n  end.\n  \nCompute (all_zero (bits B1 B0 B1 B0)).\nCompute (all_zero (bits B1 B1 B1 B1)).\nCompute (all_zero (bits B0 B0 B0 B0)).\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 2))). *)\n\n(*Level 1 -- factorial*)\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  \nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => (mult (factorial n') 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\n\n\n\n\n\n", "meta": {"author": "pheihuihui", "repo": "learn-to-prove", "sha": "1a6d6ad36f6309f58a6a928288700d343c40f614", "save_path": "github-repos/coq/pheihuihui-learn-to-prove", "path": "github-repos/coq/pheihuihui-learn-to-prove/learn-to-prove-1a6d6ad36f6309f58a6a928288700d343c40f614/exersices/_001_Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7953289941254729}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export ProofObjects.\n\nCheck nat_ind.\n\nTheorem mult_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - simpl. intros n' IHn'. apply IHn'.\nQed.\n\n(* Exercise: 2 stars, optional (plus_one_r') *)\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - simpl. intros n' IHn'. rewrite IHn'. reflexivity.\nQed.\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n\n(* Exercise: 1 star, optional (rgb) *)\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\n\n(* rgb_ind : forall P : rgb -> Prop,\n  P red -> P green -> P blue -> forall r : rgb, P r.*)\n\nCheck rgb_ind.\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\n(* Exercise: 1 star, optional (natlist1) *)\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(* natlist1_ind : forall P : natlist1 -> Prop,\n  P nnil1 ->\n  (forall (ns : natlist1),\n  P ns -> forall n:nat, P (nsnoc1 ns n) ->\n  forall ns : natlist1, P ns *)\nCheck natlist1_ind.\n\n(* Exercise: 1 star, optional (byntree_ind) *)\n\nInductive byntree : Type :=\n  | bempty : byntree\n  | bleaf : yesno -> byntree\n  | nbranch : yesno -> byntree -> byntree -> byntree.\n\n(* byntree_ind : forall P : byntree -> Prop.\n  P bempty ->\n  (forall (y:yesno), P (bleaf y)) ->\n  (forall (y:yesno) (b : byntree),\n  P b ->\n  forall (b0 : byntree) P b0 -> P (nbranch y b b0)) ->\n  forall b : byntree, P b *)\n\nCheck byntree_ind.\n\n(* Exercise: 1 star, optional (ex_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\nInductive ExSet : Type :=\n  | con1 : bool -> ExSet\n  | con2 : nat -> ExSet -> ExSet.\n\nCheck ExSet_ind.\n\n(* Polymorphism *)\n\nInductive list (X:Type) : Type :=\n| nil : list X\n| cons : X -> list X -> list X.\n\nCheck list_ind.\n\n(* Exercise: 1 star, optional (tree) *)\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\n\n(* tree_ind :\n  forall (X : Type) (P : tree X -> Prop),\n  (forall (x : X), P (leaf X x)) ->\n  (forall (x : X) (t : tree X),\n  P t -> \n  (forall (t0: tree X), P t0 -> P (node X t t0))) ->\n  forall t : tree X, P t. *)\n\nCheck tree_ind.\n\n(* Exercise: 1 star, optional (mytype) *)\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\n(* Exercise: 1 star, optional (foo) *)\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\n(* Exercise: 1 star, optional (foo') *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\n\n(*  foo'_ind :\n  forall (X : Type) (P : foo' X -> Prop),\n    (forall (l : list X) (f : foo' X),\n        P f ->\n        P (C1 X l f)) ->\n    P (C2 X) ->\n    forall f : foo' X, P f *)\nCheck foo'_ind.\n\n(* Induction Hypotheses *)\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  - reflexivity.\n  - intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn.\nQed.\n\n\n(* More on the 'induction' tactic *)\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'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - intros m. simpl. rewrite <- plus_n_O. reflexivity.\n  - intros m. simpl. rewrite IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n\nTheorem plus_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction m as [| m'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite <- IHm'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(* Exercise: 1 star, optional (plus_explicit_prop) *)\nDefinition P_plus_assoc (n m p: nat) : Prop :=\n  n + (m + p) = (n + m) + p.\n\nDefinition plus_assoc''' : forall n m p : nat,\n  P_plus_assoc n m p.\nProof.\n  intros.\n  apply nat_ind.\n  - unfold P_plus_assoc. rewrite <- plus_n_O. rewrite <- plus_n_O. reflexivity.\n  - intros. unfold P_plus_assoc in *. rewrite <- plus_n_Sm. rewrite <- plus_n_Sm. rewrite H. rewrite plus_n_Sm. reflexivity.\nQed.\n\nDefinition P_plus_comm (n m : nat) : Prop :=\n  n + m = m + n.\n\nDefinition plus_comm''' : forall n m : nat,\n  P_plus_comm n m.\nProof.\n  intros.\n  apply nat_ind.\n  - unfold P_plus_comm. simpl. rewrite <- plus_n_O. reflexivity.\n  - intros. unfold P_plus_comm in *. simpl. rewrite <- H. rewrite plus_n_Sm. reflexivity.\nQed.\n\n\n(* Induction Principles in Prop *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nCheck ev_ind.\n\nTheorem ev_ev' : forall n, ev n -> ev' n.\nProof.\n  apply ev_ind.\n  - apply ev'_0.\n  - intros m Hm IH. apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\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\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": "prashantpawar", "repo": "logical-foundations", "sha": "8c2126869f2104e2fe38249e3b86de080ea12d2f", "save_path": "github-repos/coq/prashantpawar-logical-foundations", "path": "github-repos/coq/prashantpawar-logical-foundations/logical-foundations-8c2126869f2104e2fe38249e3b86de080ea12d2f/IndPrinciples_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.904650527388829, "lm_q1q2_score": 0.7953205754216326}}
{"text": "Require Import List.\nRequire Import String.\nOpen Scope string_scope.\n\nDefinition var := string.\n\n(** Lambda calculus syntax.\n\n We have variables, application, and abstraction. These are all we\n need in order to write programs to compute every computable function.\n *)\nInductive Expr : Set :=\n| EConst                        (* The one and only constant     *)\n| EVar (v : var)                (* Variables                     *)\n| EApp (e1 : Expr) (e2 : Expr)  (* Application, e1 applied to e2 *)\n| EAbs (x : var) (body : Expr). (* Abstraction, \\x -> body       *)\n\n(**\n\nIn this homework you will implement call by value semantics of\nlambda calculus. This means that when evaluating a function\napplication, (e1 e2) you will:\n\n  1. evaluate e1 down as far as possible (it had better end up an abstraction)\n\n  2. next, evaluate e2 down to a VALUE.\n      NOTE: in our simple lambda calculus, abstractions and constants are values\n\n  3. next, substitute the value we got for e2 into the simplified form of e1\n      NOTE: we define a relation for what it means to be a well formed substitution below\n\n*)\n\n(* Here we formally define what it means to be a value (not able to be evaluated any more) *)\nDefinition isValue (e : Expr) : Prop :=\n  match e with\n    | EVar _ => False\n    | EAbs _ _ => True\n    | EConst => True\n    | EApp _ _ => False\n  end.\n\n(**\n\nHere we introduce what is called a decidability lemma.\nEssentially we are saying that for any expression you have, it's either a value or not.\nWe need this because we can write down undecidable things as Props.\n\n*)\nLemma isValueDec :\n  forall e,\n    { isValue e } + {~ isValue e}.\nProof.\n  intros. destruct e; simpl; auto.\nDefined.\n\n(* Here we define what it means for a particular substitution to be valid *)\n(* e1[e2/x] = e3 *)\nInductive Subst : Expr -> Expr -> var -> Expr -> Prop :=\n| SubstConst : forall e x, (* substituting into a const is just that const *)\n  Subst EConst e x EConst\n| SubstVar_same : forall e x, (* substitute an expression in for a variable *)\n  Subst (EVar x) e x e \n| SubstVar_diff : forall e x1 x2,\n  x1 <> x2 ->\n  Subst (EVar x1) e x2 (EVar x1)\n| SubstApp : forall eA eB e x eA' eB',\n  Subst eA e x eA' ->\n  Subst eB e x eB' ->\n  Subst (EApp eA eB) e x (EApp eA' eB')\n| SubstAbs_same : forall eA e x,\n  Subst (EAbs x eA) e x (EAbs x eA)\n| SubstAbs_diff : forall eA e x1 x2 eA',\n  x1 <> x2 ->\n  Subst eA e x2 eA' ->\n  Subst (EAbs x1 eA) e x2 (EAbs x1 eA').\n\n(* Here we give semantics to our simple language *)\nInductive Step : Expr -> Expr -> Prop :=\n| ScrunchLeft :\n    forall e1 e1' e2,\n      Step e1 e1' ->\n      Step (EApp e1 e2) (EApp e1' e2)\n| ScrunchRight :\n    forall e1 e2 e2',\n      isValue e1 ->\n      Step e2 e2' ->\n      Step (EApp e1 e2) (EApp e1 e2')\n| Ssubst :\n    forall x e1 e2 e1',\n      isValue e2 ->\n      Subst e1 e2 x e1' ->\n      Step (EApp (EAbs x e1) e2) e1'.\n\n(* Here we define the transitive closure of a step relation. Note that\nwe are able to define this once for any step relation, which is just\nkinda cool *)\nInductive star (step : Expr -> Expr -> Prop) : Expr -> Expr -> Prop :=\n | star_refl :\n     forall e,\n       star step e e\n | star_right :\n     forall e1 e2 e3,\n       star step e1 e2 ->\n       step e2 e3 ->\n       star step e1 e3.\n\n(* [Problem 1] *)\n(* Implement a function to perform substitution *)\n(* e1[e2/x] = e3 *)\n(* Given e1, e2, and x, produce e3 *)\n(* Your function should be a total function (no option in the return type *)\n(* Hint: for equality of vars, use \"string_dec\" *)\n\n(* [Problem 2] *)\n(* Prove that, given a valid term of the Subst relation, your function *)\n(* from problem 1 will produce the same substitution. *)\n\n(* [Problem 3] *)\n(* Prove that if your function from problem 1 produces a substitution, *)\n(* it's modeled by the Subst relation *)\n(* This should look like problem 2 with the hypothesis and conclusion flipped *)\n\n(* [Problem 4] *)\n(* Define a step function *)\n(* The skeleton of one has been provided *)\nFixpoint step (e : Expr) : option Expr := None.\n\n(* In lambda calculus, we like to reason about what values can take\nsteps, and can't. We would love to know that if we have a value,\ni.e. something that we have decided is the end result of a\ncomputation, then it can't take a step *)\n\n(* [Problem 5] *)\n(* Prove that any value cannot take a step *)\n\n(* We have step function, and a Step relation *)\n(* That means we can prove them equivalent *)\n(* Let's make sure the step function is implemented correctly *)\n\n(* In proving the next two lemmas, you may find bugs in your step *)\n(* function. Change it all you need. Don't modify the Step relation. *)\n\n(* When you've proven the next two lemmas, you will know that you got *)\n(* your step function right *)\n\n(* [Problem 6] *)\n(* Prove that if the Step relation says e1 can step to e2, then your *)\n(* step function will take e1 and produce \"Some e2\" *)\n\n(* [Problem 7] *)\n(* Prove that if your step function produces \"Some\", that the Step *)\n(* relation models that step *)\n\n(* That's awesome, we defined relations and functions for evaluation *)\n(* Now, we were able to prove that if something is a value, it can't take a step *)\n(* What if we were to try to prove the other way, that if something\n   can't take a step, then it's not a value? *)\n\nLemma no_step_value :\n  forall v,\n    step v = None ->\n    isValue v.\nProof.\n\nAbort.\n\n(* Turns out we can have malformed expressions, which can't step, but aren't values. *)\n\n(* [Problem 8] *)\n(* Explain in English how we can have expressions that both can't step and aren't values *)\n\n(* [Problem 9] *)\n(* Prove the following lemma in Coq to show you have a counterexample *)\nLemma no_step_and_not_value :\n  exists e,\n    step e = None /\\ ~ isValue e.\nProof.\n  admit.\nQed.\n\n(* How do we solve this? With types! *)\n\n(* Here we define the types for the simply typed lambda calculus *)\nInductive SimpleType :=\n  | TUnit\n  | TFun (arg : SimpleType) (res : SimpleType).\n\n(* Here we define what a type environment is *)\n(* Simply a mapping from variables to types *)\nDefinition Env := var -> option SimpleType.\n\n(* Here is how we extend a typing environment with another variable binding *)\nDefinition extend (env : Env) x t :=\n  fun y => if string_dec x y then Some t else env y.\n\n(* What it means for a lambda expression to be well typed *)\n(* These are the type rules for STLC *)\n(* You will frequently see them in the literature with horizontal lines *)\nInductive WellTyped : Env -> Expr -> SimpleType -> Prop :=\n  | WtConst :\n      forall env,\n        WellTyped env EConst TUnit\n  | WtVar :\n      forall env x t,\n        env x = Some t ->\n        WellTyped env (EVar x) t\n  | WtAbs :\n      forall env x t exp t',\n        WellTyped (extend env x t) exp t' ->\n        WellTyped env (EAbs x exp) (TFun t t')\n  | WtApp :\n      forall env f arg t t',\n        WellTyped env arg t ->\n        WellTyped env f (TFun t t') ->\n        WellTyped env (EApp f arg) t'.\n\n(* [Problem 10] *)\n\n(* Explain in English why we will run into trouble if we try to write *)\n(* a typechecker as a function. For everything else, we write a relation *)\n(* and a function, and prove the two equivalent. Why, in this particular *)\n(* case, can we not simply write the \"well_typed\" function, of type *)\n(* Env -> Expr -> SimpleType -> Bool? *)\n\n(* Here's another decidability lemma for types *)\nLemma st_eq_dec :\n  forall (t1 t2 : SimpleType),\n    {t1 = t2} + {t1 <> t2}.\nProof.\n  decide equality.\nQed.\n\n(* The empty environment *)\nDefinition Empty : Env := fun x => None.\n\n(* [Problem 11] *)\n(* Here's what we call a \"canonical forms\" lemma *)\n(* We want to say that if something has a type of a value in an empty *)\n(* context, it is in its \"canonical form\" *)\nLemma canonical_const :\n  forall e,\n    isValue e ->\n    WellTyped Empty e TUnit ->\n    e = EConst.\nProof.\n  admit.\nQed.\n\n(* [Problem 12] *)\n(* Here's something more interesting. Canonical forms for functions *)\nLemma canonical_abs :\n  forall e t t',\n    isValue e ->\n    WellTyped Empty e (TFun t t') ->\n    exists x body,\n      e = EAbs x body.\nProof.\n  admit.\nQed.\n\n(* [Problem 13] *)\n(* In order to prove type soundness, we destructure the proof into two lemmas *)\n(* The first one is called progress *)\n(* If I have a well typed term, it can either take a step, or is a value *)\n(* Prove the progress lemma *)\n(* Hint: before inducting, use \"remember Empty as env\" to preserve the *)\n(* knowledge that the environment is Empty *)\n(* Hint: you will need one of your canonical forms lemmas from above *)\nLemma type_progress :\n  forall e t,\n    WellTyped Empty e t ->\n    ((exists e', Step e e') \\/ isValue e).\nProof.\n  admit.\nQed.\n\n(* The second lemma is called type preservation *)\n(* In order to prove that, we're going to need a lot of auxiliary machinery *)\n(* Don't worry, I'll walk you through it. *)\n\n(* FROM THIS POINT ON *)\n(* I may not tell you to use a lemma that you've previously proved *)\n(* but you absolutely should *)\n\n(* I give you the lemmas I think you need to succeed. If you need more *)\n(* lemmas that's completely fine. If you try to do some of these proofs *)\n(* without using the lemmas you've already proven, you will not have a *)\n(* good time. *)\n\n(* Here we define what it means for two environments to be extensionally equivalent *)\n(* Extensional Equality for functions means they return the same result for every argument *)\n(* for example, \\x -> 1 + x and \\x -> x + 1 are extensionally equivalent, but not the same function *)\nDefinition ext_equiv (env1 env2 : Env) : Prop :=\n  forall x,\n    env1 x = env2 x.\n\n(* [Problem 14] *)\n(* Prove a lemma about extending extensionally equivalent environments *)\nLemma extend_pres_ext_equiv :\n  forall env env2,\n    ext_equiv env env2 ->\n    forall x t,\n      ext_equiv (extend env x t) (extend env2 x t).\nProof.\n  admit.\nQed.\n\n(* [Problem 15] *)\n(* Prove that if a term is well typed in an environment, it is also *)\n(* well typed in any extensionally equivalent environment *)\n(* Hint: Be careful with your induction *)\nLemma well_typed_ext_equiv :\n  forall env1 e t,\n    WellTyped env1 e t ->\n    forall env2,\n      ext_equiv env1 env2 ->\n      WellTyped env2 e t.\nProof.\n  admit.\nQed.\n\n(* [Problem 16] *)\n(* Prove that extending an environment with the same variable twice is *)\n(* the same as extending it once *)\n(* Hint: use well_typed_ext_equiv *)\nLemma extend_same:\n  forall env x t t' e t'',\n    WellTyped (extend (extend env x t) x t') e t'' <->\n    WellTyped (extend env x t') e t''.\nProof.\n  admit.\nQed.\n\n(* [Problem 17] *)\n(* Prove that extending an environment with two different variables is *)\n(* ok to do in either order *)\nLemma extend_different:\n  forall e t env x1 x2 t1 t2,\n    x1 <> x2 ->\n    (WellTyped (extend (extend env x2 t2) x1 t1) e t <->\n    WellTyped (extend (extend env x1 t1) x2 t2) e t).\nProof.\n  admit.\nQed.\n\n(* Here we define what free variables exist in an expression *)\n(* Intuitively, these are all the variables which exist, but are not *)\n(* bound by an abstraction *)\nFixpoint free_variables (e : Expr) : list var :=\n  match e with\n    | EConst => nil\n    | EVar x => x :: nil\n    | EAbs x body => remove string_dec x (free_variables body)\n    | EApp e1 e2 => app (free_variables e1) (free_variables e2)\n  end.\n\n(* [Problem 18] *)\n(* This may seem to be an obvious lemma about remove and lists *)\n(* It does not happen to be in the standard library *)\n(* Let's go prove it *)\nLemma remove_different :\n  forall {A} (eq_dec : forall (a b : A), {a = b} + {a <> b}) l x y,\n    x <> y ->\n    (In x l <->\n    In x (remove eq_dec y l)).\nProof.\n  admit.\nQed.\n\n(* [Problem 19] *)\n(* Here we prove what's called weakening *)\n(* If a variable isn't in the free variables of an expression, *)\n(* we can extend the context with that variable, and produce the same *)\n(* typing derivation *)\nLemma weakening :\n  forall e env t x t',\n    ~ (In x (free_variables e)) ->\n    (WellTyped (extend env x t') e t <->\n    WellTyped env e t).\nProof.\n  admit.\nQed.\n\n(* [Problem 20] *)\n(* Here we prove that a correct substitution preserves typing *)\n(* This one's a bit tricky, but remember to use inversion where *)\n(* necessary, and to use previously proven lemmas *)\nLemma subst_type_pres :\n  forall e e' e'' x,\n    Subst e' e x e'' ->\n    forall env t t',\n      WellTyped env e t ->\n      free_variables e = nil ->\n      WellTyped (extend env x t) e' t' ->\n      WellTyped env e'' t'.\nProof.\n  admit.\nQed.\n\n(* [Problem 21] *)\n(* Here we prove that if we have free variables in an expression, we *)\n(* need them in the type environment if that is well typed *)\nLemma env_vars_required :\n  forall env e t,\n    WellTyped env e t ->\n    (forall x, In x (free_variables e) -> env x <> None).\nProof.\n  admit.\nQed.\n\n(* [Problem 22] *)\n(* Here we prove that something that's well typed in the empty *)\n(* environment has no free variables *)\n(* Hint: Use a previously proven lemma *)\nLemma no_free_vars_empty :\n  forall e t,\n    WellTyped Empty e t ->\n    free_variables e = nil.\nProof.\n  admit.\nQed.\n\n(* [Problem 23] *)\n(* We finally have enough lemmas to prove type preservation, the other *)\n(* lemma necessary for type soundness. It says that if we have a well *)\n(* typed term, and take a step, then the result is still well typed with *)\n(* the same type. *)\nLemma type_preservation :\n  forall e t,\n    WellTyped Empty e t ->\n    forall e',\n      Step e e' ->\n      WellTyped Empty e' t.\nProof.\n  admit.\nQed.\n\n(* [Problem 24] *)\n(* Prove type preservation over any sequence of steps *)\n(* The lemma should look almost identical to the previous problem *)\n\n(* [Problem 25] *)\n(* Prove that our simple type system for lambda calculus is sound *)\n(* Prove that any term reachable from any well typed term can either *)\n(* take a step, or is a value *)\nTheorem type_soundness :\n  forall e t,\n    WellTyped Empty e t ->\n    forall e',\n      star Step e e' ->\n      (exists e'', Step e' e'') \\/ isValue e'.\nProof.\n  admit.\nQed.\n\n(* Crowning Achievement *)\n(* [Problem 26] *)\n(* Prove the lemma we originally set out to prove, but with the *)\n(* additional hypothesis of the term being well typed *)\nLemma no_step_value_typed :\n  forall e t,\n    WellTyped Empty e t ->\n    step e = None ->\n    isValue e.\nProof.\n  admit.\nQed.\n  \n(* Bonus Problem 1 *)\n(* Hint: you will need strong induction on the size of the type *)\n(* which means you will need to define what the size of the type means *)\n(* Theorem strong_normalization : *)\n(*   forall t e, *)\n(*     WellTyped Empty e t -> *)\n(*     exists v, *)\n(*       star Step e v /\\ isValue v. *)\n(* Proof. *)\n(* Note: the implication of this is interesting. This says that every *)\n(* well typed term will halt. *)\n\n\n(* Bonus Problem 2 *)\n(* Construct your own definitions of the simply typed lambda calculus *)\n(* that allow you to write a typechecker as a function (i.e. to get *)\n(* around the problem you describe above) *)\n\n\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/hw03/hw03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8933094138654242, "lm_q1q2_score": 0.795308215905091}}
{"text": "(*\nhttps://softwarefoundations.cis.upenn.edu/lf-current/Basics.html\n*)\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (nandb) *)\nDefinition nandb (b c : bool) : bool :=\n  match b, c with\n  | false, _ | _, false => true\n  | _, _ => false\n  end.\nExample test_nandb1 : (nandb true false = true). Proof. reflexivity. Qed.\nExample test_nandb2 : (nandb false false = true). Proof. reflexivity. Qed.\nExample test_nandb3 : (nandb false true = true). Proof. reflexivity. Qed.\nExample test_nandb4 : (nandb true true = false). Proof. reflexivity. Qed.\n\n(* Exercise: 1 star, standard (nandb) - experiments *)\nDefinition notb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\nDefinition andb (b c : bool) : bool :=\n  match b, c with\n  | true, true => true\n  | _, _ => false\n  end.\nDefinition nandb_bis (b c : bool) : bool := notb (andb b c).\nTheorem nandbs_equivalents : forall b c : bool,\n    (nandb b c) = (nandb_bis b c).\nProof.\n  intros b c.\n  destruct b, c.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (andb3) *)\nDefinition andb3 (b c d : bool) : bool :=\n  match b, c, d with\n  | true, true, true => true\n  | _, _, _ => false\n  end.\nExample test_andb31: (andb3 true true true) = true. Proof. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false. Proof. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false. Proof. reflexivity. Qed.\nExample test_andb34: (andb3 true true false) = false. Proof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (factorial) *)\nFixpoint factorial (n : nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => n * factorial (n')\n  end.\nExample test_factorial1: (factorial 3) = 6. Proof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (10 * 12). Proof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (ltb) *)\nFixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ | S _, O => false\n  | S n', S m' => eqb n' m'\n end.\nFixpoint leb (n m : nat) : bool :=\n  match n, m with\n  | O, O | O, S _ => true\n  | S _, O => false\n  | S n', S m' => leb n' m'\n  end.\nDefinition ltb (n m : nat) : bool :=\n  match eqb n m, leb n m with\n  | false, true => true\n  | _, _ => false\n  end.\nExample test_ltb1: (ltb 2 2) = false. Proof. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true. Proof. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false. Proof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (plus_id_exercise) *)\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 H1 H2.\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (mult_n_1) *)\nCheck mult_n_Sm.\nCheck mult_n_O.\nTheorem mult_n_1 : forall p : nat, p * 1 = p.\nProof.\n  intro a.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 2 stars, standard (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 b, c.\n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (zero_nbeq_plus_1) *)\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nTheorem zero_nbeq_plus_1 : forall n : nat, 0 =? (n + 1) = false.\nProof.\n  intros [].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 2 stars, standard, optional (decreasing) *)\nFail Fixpoint forever (n m: nat) : nat :=\n  match n, m with\n  | S n, S m => forever m n\n  | _, _ => O\n  end.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (identity_fn_applied_twice) *)\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\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard (negation_fn_applied_twice) *)\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\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 b.\n  rewrite -> H.\n  rewrite -> H.\n  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 3 stars, standard, optional (andb_eq_orb)\n\nfalse & false = false | false  ||| false = false\n true &  true =  true | true   ||| true = true\n\n true & false =  true | false  ||| false = true\nfalse &  true = false | true   ||| false = true *)\nTheorem andb_eq_orb_cheat : forall b c, andb b c = orb b c -> b = c.\nProof.\n  intros b c.\n  destruct b, c.\n  - reflexivity.\n  - simpl. intros H. rewrite -> H.  reflexivity.\n  - simpl. intros H. rewrite -> H.  reflexivity.\n  - reflexivity.\nQed.\nTheorem andb_eq_orb_cheat2 : forall b c, andb b c = orb b c -> b = c.\nProof.\nintros [|] [|] H.\n- reflexivity.\n- simpl in H. rewrite H. reflexivity.\n- simpl in H. exact H.\n- reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 3 stars, standard (binary) *)\n\n(* bin *)\nInductive bin : Type :=\n| Z\n| B0 (n : bin)\n| B1 (n : bin).\nDefinition zero_bin : bin := Z.\nDefinition one_bin : bin := B1 Z.\nDefinition two_bin : bin := B0 one_bin.\nDefinition three_bin : bin := B1 one_bin.\nDefinition four_bin : bin := B0 two_bin.\nDefinition five_bin : bin := B1 two_bin.\nDefinition six_bin : bin := B0 three_bin.\nDefinition seven_bin : bin := B1 three_bin.\nFixpoint incr (m : bin) : bin :=\n  match m with\n  | Z => B1 Z\n  | B0 n => B1 n\n  | B1 n => B0 (incr n)\n  end.\nExample test_bin_incr0 : incr zero_bin = one_bin. Proof. reflexivity. Qed.\nExample test_bin_incr1 : incr one_bin = two_bin. Proof. reflexivity. Qed.\nExample test_bin_incr2 : incr two_bin = three_bin. Proof. reflexivity. Qed.\nExample test_bin_incr3 : incr three_bin = four_bin. Proof. reflexivity. Qed.\nExample test_bin_incr4 : incr four_bin = five_bin. Proof. reflexivity. Qed.\nExample test_bin_incr5 : incr five_bin = six_bin. Proof. reflexivity. Qed.\nExample test_bin_incr6 : incr six_bin = seven_bin. Proof. reflexivity. Qed.\n\n(* conversions *)\nFixpoint bin_to_nat' (m : bin) (weight : nat) : nat :=\n  match m with\n  | Z => O\n  | B1 m' => weight + bin_to_nat' m' (weight * 2)\n  | B0 m' => bin_to_nat' m' (weight * 2)\n  end.\nDefinition bin_to_nat (m : bin) : nat := bin_to_nat' m 1.\nDefinition zero_nat : nat := O.\nDefinition one_nat : nat := S zero_nat.\nDefinition two_nat : nat := S one_nat.\nDefinition three_nat : nat := S two_nat.\nDefinition four_nat : nat := S three_nat.\nDefinition five_nat : nat := S four_nat.\nDefinition six_nat : nat := S five_nat.\nDefinition seven_nat : nat := S six_nat.\nExample test_bin_to_nat_0 : bin_to_nat zero_bin = zero_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_1 : bin_to_nat one_bin = one_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_2 : bin_to_nat two_bin = two_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_3 : bin_to_nat three_bin = three_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_4 : bin_to_nat four_bin = four_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_5 : bin_to_nat five_bin = five_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_6 : bin_to_nat six_bin = six_nat. Proof. reflexivity. Qed.\nExample test_bin_to_nat_7 : bin_to_nat seven_bin = seven_nat. Proof. reflexivity. Qed.\n\n(* experiments *)\nFixpoint decr (m : bin) : bin :=\n  match m with\n  | Z => Z\n  | B1 Z => Z\n  | B0 (B1 Z) => B1 Z\n  | B1 x => B0 x\n  | B0 x => B1 (decr x)\n  end.\nExample test_bin_decr0 : decr zero_bin = zero_bin. Proof. reflexivity. Qed.\nExample test_bin_decr1 : decr one_bin = zero_bin. Proof. reflexivity. Qed.\nExample test_bin_decr2 : decr two_bin = one_bin. Proof. reflexivity. Qed.\nExample test_bin_decr3 : decr three_bin = two_bin. Proof. reflexivity. Qed.\nExample test_bin_decr4 : decr four_bin = three_bin. Proof. reflexivity. Qed.\nExample test_bin_decr5 : decr five_bin = four_bin. Proof. reflexivity. Qed.\nExample test_bin_decr6 : decr six_bin = five_bin. Proof. reflexivity. Qed.\nExample test_bin_decr7 : decr seven_bin = six_bin. Proof. reflexivity. Qed.\nTheorem incr_decr_inverse : forall x, decr (incr x) = x.\nProof.\nAdmitted.\n\n(* experiments *)\nFixpoint nat_to_bin (x : nat) : bin :=\n  match x with\n  | O => Z\n  | S x => incr (nat_to_bin x)\n  end.\nTheorem bin_to_nat_to_bin : forall x : bin, nat_to_bin (bin_to_nat x) = x.\nProof.\nAdmitted.\n", "meta": {"author": "Ngoguey42", "repo": "software_foundations", "sha": "c797cb94aa1f6e8de6537d3a376164ab1beb6c5f", "save_path": "github-repos/coq/Ngoguey42-software_foundations", "path": "github-repos/coq/Ngoguey42-software_foundations/software_foundations-c797cb94aa1f6e8de6537d3a376164ab1beb6c5f/lf/MyBasics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8887587912826161, "lm_q1q2_score": 0.7952519968651313}}
{"text": "Fixpoint elsonfvsum (n:nat)(f:nat->nat):nat:=\n  match n with\n  | 0 => 0\n  | S(n0) => elsonfvsum(n0)(f) +f (S(n0))\n  end.\n\nDefinition fv1(k:nat):=\n  k+k.\n\n\nDefinition alap (k:nat):=\n  k.\n\nEval compute in elsonfvsum 3 fv1.\n\nTheorem lemma (n:nat): n * (n + 1) + 2 * S n = S n * (S n + 1).\nProof.\n  induction n.\n  compute;auto.\n  \n  simpl (S(n) + 1).\n  simpl (2 * S(S n)).\n  simpl.\n  Require Import Omega.\n  Require Import Lia.\n  lia.\nQed.\nTheorem gauss: forall n:nat, 2*(elsonfvsum n alap) = n*(n+1).\n  intros.\n  induction n.\n  compute.\n  auto.\n  simpl (elsonfvsum (S n) alap).\n  enough (2 * (elsonfvsum n alap + alap (S n)) = 2 * (elsonfvsum n alap) + 2*alap (S n)).\n  rewrite H.\n  rewrite IHn.\n  unfold alap.\n  induction n.\n  compute.\n  auto.\n  Require Import Lia.\n  lia.\n  lia.\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/molnarbarna/ZH_7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7951125938806222}}
{"text": "Definition 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\n\nLemma excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n unfold peirce; intros H P Q H0.\n destruct (H P) as [p | np].\n -  assumption.\n -  apply H0; intro H1; now absurd P.\nQed.\n\nLemma peirce_classic : peirce -> classic.\nProof.\n intros HPeirce P H0; apply (HPeirce P False).\n intro H1; now destruct H0.\nQed.\n\nLemma classic_excluded_middle: classic -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intro H0; absurd P.\n -  intro H1; apply H0 ; now left.\n -  apply H; intro H1; apply H0; now right.\nQed.\n\n\nLemma excluded_middle_implies_to_or :  excluded_middle -> implies_to_or.\nProof.\n intros H P Q H0;\n  destruct (H P) as [p | np].\n  -  right; auto.\n  - now  left.\nQed.\n\nLemma implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P; destruct (H P P);auto.\nQed.\n\nLemma classic_de_morgan_not_and_not : classic -> \n                                      de_morgan_not_and_not.\nProof.\n unfold de_morgan_not_and_not; intros H P Q H0.\n apply H.\n intro H1; apply H0; split;intro;apply H1; auto.\nQed.\n\nLemma de_morgan_not_and_not_excluded_middle : de_morgan_not_and_not ->\n                                              excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intros [H1 H2]; contradiction. \nQed.\n\n", "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/ch5_everydays_logic/SRC/class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7951125906315073}}
{"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 list_utils.\n\nSet Implicit Arguments.\n\nDefinition finite_t X (P : X -> Prop) := { l | forall x, In x l <-> P x }.\n\nSection finite_t.\n\n  Fact finite_t_pair X Y (P : X -> Prop) (Q : Y -> Prop) :\n    finite_t P -> finite_t Q -> finite_t (fun c => P (fst c) /\\ Q (snd c)).\n  Proof.\n    intros (l & Hl) (m & Hm).\n    exists (list_prod (@pair _ _) l m).\n    intro c; rewrite list_prod_spec, <- Hl, <- Hm.\n    split.\n    intros (x & y & ? & ? & ?); subst; simpl; auto.\n    destruct c as (x,y); exists x, y; simpl; auto.\n  Qed. \n\n  Fact finite_t_Forall X Y (R : X -> Y -> Prop) l : \n    (forall x, In x l -> finite_t (R x)) -> finite_t (Forall2 R l).\n  Proof.\n    intros Hl; induction l as [ | x l IHl ].\n    exists (nil::nil).\n    intros x; split.\n    intros [ ? | [] ]; subst; constructor.\n    inversion_clear 1; left; auto.\n    destruct (Hl _ (or_introl eq_refl)) as (l1 & Hl1).\n    destruct IHl as (mm1 & Hmm1).\n    intros; apply Hl; right; auto.\n    exists (list_prod (@cons _) l1 mm1); intros c.\n    rewrite list_prod_spec.\n    split.\n    intros (y & m & ? & ? & ?); subst; constructor.\n    apply Hl1; auto.\n    apply Hmm1; auto.\n    intros H.\n    destruct c as [ | y m ].\n    inversion H.\n    rewrite Forall2_cons_inv in H.\n    destruct H as (H1 & H2).\n    exists y, m; split; auto; split.\n    apply Hl1; auto.\n    apply Hmm1; auto.\n  Qed.\n  \n  (* Filtering out a finite set with a decidable functions gives a finite set \n     A VERY handy result *) \n  \n  Fact finite_t_dec X (P Q : X -> Prop) : (forall x, { P x } + { ~ P x }) -> finite_t Q -> finite_t (fun x => P x /\\ Q x).\n  Proof.\n    intros HP (l & Hl).\n    exists (filter (fun x => if HP x then true else false) l).\n    intros x.\n    rewrite filter_In, <- Hl.\n    destruct (HP x); split; try tauto.\n    intros (_ & C); discriminate C.\n  Qed.\n  \n  (* Mapping a finite set by a finitetary relation gives a finite set *)\n  \n  Fact finite_t_map X Y (P : X -> Prop) (Q : X -> Y -> Prop) : \n      finite_t P\n   -> (forall x, P x -> finite_t (Q x)) \n   -> finite_t (fun y => exists x, P x /\\ Q x y).\n  Proof.\n    intros (l & Hll) H.\n    assert (forall x, In x l -> finite_t (Q x)) as H1.\n      intros x Hx; rewrite Hll in Hx; auto.\n    assert (finite_t (fun y => exists x, In x l /\\ Q x y)) as H2.\n      clear P Hll H.\n      induction l as [ | x l IHl ].\n      exists nil.\n      intros x; split.\n      intros [].\n      intros (? & [] & _).\n      destruct (H1 _ (or_introl eq_refl)) as (l1 & Hl1).\n      destruct IHl as (l2 & Hl2).\n      intros; apply H1; right; auto.\n      exists (l1++l2).\n      intros y; split.\n      intros Hy; apply in_app_or in Hy.\n      destruct Hy as [ Hy | Hy ].\n      exists x; split; simpl; auto; apply Hl1; auto.\n      apply Hl2 in Hy. \n      destruct Hy as (v & ? & ?); exists v; split; auto.\n      right; auto.\n      intros (u & [ ? | ? ] & H2); subst; apply in_or_app.\n      left; apply Hl1; auto.\n      right; apply Hl2; exists u; auto.\n    destruct H2 as (m & Hm).\n    exists m; intro; rewrite Hm.\n    split; intros (u & ? & ?); exists u; split; auto; apply Hll; auto.\n  Qed.\n  \n  Fact finite_t_plus n : finite_t (fun c => fst c + snd c = n).\n  Proof.\n    exists (map (fun x => (x,n-x)) (list_n (S n))).\n    intros c; rewrite in_map_iff; split.\n    intros (a & ? & H); subst; simpl.\n    apply list_n_spec in H; omega.\n    destruct c as (x,y); exists x.\n    rewrite list_n_spec; simpl in H.\n    split; [ f_equal | ]; omega.\n  Qed.\n  \n  Fact finite_t_plus_lt n : finite_t (fun c => 0 < fst c /\\ 0 < snd c /\\ fst c + snd c = n).\n  Proof.\n    do 2 (apply finite_t_dec; [ intro; apply lt_dec | ]).\n    apply finite_t_plus.\n  Qed.\n  \n  (* There are only finitely many bounded lists of nat (bound on elements + bound on length *)\n\n  Definition finite_t_list_bounded n m : finite_t (fun l => Forall (ge n) l /\\ length l < m).\n  Proof.\n    induction m as [ | m (l & Hl) ].\n    exists nil; simpl; intros; split; omega.\n    exists (nil::list_prod (@cons _) (list_n (S n)) l).\n    intros [ | a k ].\n    simpl; split; auto; split; auto; omega.\n    split.\n    intros [ H | H ].\n    discriminate H.\n    apply list_prod_spec in H.\n    destruct H as (x & y & E & H1 & H2).\n    injection E; clear E; intros; subst x y.\n    apply list_n_spec in H1.\n    apply Hl in H2.\n    split; simpl; try omega; constructor; try tauto; omega.\n    intros (H1 & H2).\n    apply Forall_cons_inv in H1.\n    simpl in H2.\n    right; apply list_prod_spec.\n    exists a, k; split; auto.\n    split.\n    apply list_n_spec; omega.\n    apply Hl; split; try tauto; omega.\n  Qed.\n  \n  (* By filtering, lists of bounded length with a given total sum are in finite number *)\n    \n  Definition finite_t_part_lsum n m : finite_t (fun l => lsum l = n /\\ length l < m).\n  Proof.\n    generalize (finite_t_list_bounded n m).\n    intros H.\n    apply finite_t_dec with (P := fun l => lsum l = n) in H.\n    2: intro; apply eq_nat_dec.\n    destruct H as (l & Hl); exists l.\n    intros x; rewrite Hl.\n    split; try tauto.\n    intros (H1 & H2); repeat split; auto.\n    rewrite Forall_forall.\n    intros y Hy.\n    generalize (lsum_le y x Hy); omega.\n  Qed.\n  \n  (* By filterging again, lists of strictly positive numbers of a given total sum \n     are in finite number as well *)\n\n  Definition finite_t_partition n : finite_t (fun l => Forall (lt 0) l /\\ lsum l = n).\n  Proof.\n    generalize (finite_t_part_lsum n (S n)); intros H.\n    apply finite_t_dec with (P := Forall (lt 0)) in H.\n    2: intro; apply Forall_dec; intros; apply lt_dec.\n    destruct H as (l & Hl); exists l; intros x; rewrite Hl.\n    split; try tauto.\n    intros (H1 & H2); repeat split; auto.\n    clear Hl l; apply le_n_S.\n    revert H1 n H2.\n    induction 1 as [ | x l Hx Hl IH ]; intros n ?; simpl.\n    omega.\n    simpl in H2.\n    specialize (IH (n - x)).\n    apply le_trans with (S (n-x)).\n    apply le_n_S, IH; omega.\n    omega.\n  Qed.\n  \n  Fact finite_t_part n : finite_t (fun ln => match ln with \n                                               | nil   => False \n                                               | x::ln => Forall (lt 0) ln \n                                                       /\\ x + lsum ln = n\n                                             end).\n  Proof.\n    set (P c := fst c + snd c = n).\n    set (Q c l := match l with \n                    | nil  => False\n                    | x::l => x = fst c /\\ Forall (lt 0) l /\\ lsum l = snd c\n                  end).\n    destruct (@finite_t_map _ _ P Q (finite_t_plus n)) as (l & Hl).\n    unfold P, Q; intros (a,b); simpl; intros Hab.\n    destruct (finite_t_partition b) as (m & Hm).\n    exists (map (cons a) m).\n    intros l; rewrite in_map_iff.\n    split.\n    intros (x & ? & Hx); subst; split; auto; apply Hm; auto.\n    destruct l as [ | x l ].\n    intros [].\n    intros (? & H1 & H2); subst; exists l; split; auto.\n    apply Hm; auto.\n    \n    exists l; intros x.\n    rewrite Hl; unfold P, Q.\n    split; destruct x as [ | u m ].\n    intros (? & ? & []).\n    intros ( (a,b) & ? & ? & ? & ?); simpl in *; split; auto; omega.\n    intros [].\n    intros (? & ?); exists (u,lsum m); simpl; auto.\n  Qed.\n  \nEnd finite_t.", "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/finite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.8459424314825852, "lm_q1q2_score": 0.7951125888062176}}
{"text": "(**\nExercises from http://adam.chlipala.net/cpdt/html/Subset.html\n*)\n\nRequire Import Arith.\nRequire Import MoreSpecif.\nRequire Import CpdtTactics.\nSet Implicit Arguments.\n\nLocal Open Scope specif_scope.\n\n(**\nWrite a function of type [forall n m : nat, {][n <= m} + {][n > m}].  That is, this function decides whether one natural is less than another, and its dependent type guarantees that its results are accurate.\n*)\nDefinition leq_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, _ => Yes\n      | _, O => No\n      | S n', S m' => Reduce (f n' m')\n    end); crush.\nDefined.\n\n(** Ex 2 *)\n\n(** Define [var], a type of propositional variables, as a synonym for [nat]. *)\nDefinition var := nat.\n\n(** Define an inductive type [prop] of propositional logic formulas, consisting of variables, negation, and binary conjunction and disjunction. *)\nInductive prop : Set :=\n| Var : var -> prop\n| Not : prop -> prop\n| And : prop -> prop -> prop\n| Or  : prop -> prop -> prop.\n\n(** Define a function [propDenote] from variable truth assignments and [prop]s to [Prop], based on the usual meanings of the connectives.  Represent truth assignments as functions from [var] to [bool]. *)\nFixpoint propDenote (truth : var -> bool) (p : prop) : Prop :=\n  match p with\n    | Var v     =>  is_true (truth v)\n    | Not p'    => ~(propDenote truth p')\n    | And p1 p2 =>  (propDenote truth p1) /\\ (propDenote truth p2)\n    | Or  p1 p2 =>  (propDenote truth p1) \\/ (propDenote truth p2)\n  end.\n\n(** Define a function [bool_true_dec] that checks whether a boolean is true, with a maximally expressive dependent type.  That is, the function should have type [forall b, {b = true} + {b = true -> False}]. *)\nDefinition bool_true_dec : forall b, {b = true} + {b = true -> False}.\n  refine (fun b =>\n    match b with\n      | true => Yes\n      | false => No\n    end); crush.\nDefined.\n\n(** Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment.  That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}].  This function is probably easiest to write in the usual tactical style, instead of programming with [refine].  The function [bool_true_dec] may come in handy as a hint. *)\nDefinition decide : forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}.\n  induction p; crush. apply bool_true_dec.\nDefined.\n\n(** Define a function [negate] that returns a simplified version of the negation of a [prop].  That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}].  To simplify a variable, just negate it.  Simplify a negation by returning its argument.  Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective.  Your [decide] function may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition.  Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC. *)\nFixpoint negateProp (p : prop) : prop :=\n  match p with\n    | Var v     => Not p\n    | Not p'    => p'\n    | And p1 p2 => Or (negateProp p1) (negateProp p2)\n    | Or  p1 p2 => And (negateProp p1) (negateProp p2)\n  end.\nDefinition negate : forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}.\n  refine (fun p => [ negateProp p ]).\n    intro truth. destruct (decide truth p); induction p; crush.\nDefined.\n\n(** Ex 3 in dpll.v *)", "meta": {"author": "namin", "repo": "coq-sandbox", "sha": "7b4a7ebd766e1da022686b67c9e14e0b026956d3", "save_path": "github-repos/coq/namin-coq-sandbox", "path": "github-repos/coq/namin-coq-sandbox/coq-sandbox-7b4a7ebd766e1da022686b67c9e14e0b026956d3/SubsetEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.7950271964592519}}
{"text": "\n\n(*\nTheorem plus_id_example : forall n m :nat,\n                            n = m -> n+n = m + m.\n\nProof.\nintros.\nrewrite -> H.\nreflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n                             n = m -> m = o -> n + m = m + o.\nProof.\nintros.\nrewrite -> H.\nrewrite -> H0.\nsimpl.\nreflexivity.\nQed.\n\nTheorem mult_0_plus : forall n m : nat,\n(0 + n) * m = n *m.\nintros n m.\nrewrite -> plus_0_n.\nreflexivity. Qed.\n\n*)\n", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/ProofByRewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7950175675306652}}
{"text": "Require Import List.\nRequire Import Setoid.\nRequire Import PeanoNat.\nRequire Import Coq.omega.Omega. \nRequire Import Matrix. \nRequire Import Coq.setoid_ring.Ring.\nRequire Import Coq.setoid_ring.Ring_theory.\nRequire Import MyHelpers. \n\nDefinition DenseMatrix_t A := list A.\n\nSection A.\n Context {ME : MatrixElem}.\n Add Field Afield : MEfield.\n\n Definition DenseMatrix_get (m n: nat) (M: DenseMatrix_t MEt) (i j : nat) :=\n   nth_default MEzero M (i * n + j). \n\n Fixpoint Generate (m n k: nat) (f: nat -> MEt) :=\n   match k with \n   | 0 => @nil(MEt)\n   | S k' => (f (m * n - k)) :: Generate m n k' f\n   end.\n\n Definition DenseMatrix_mul (m n p: nat) (M1 M2: DenseMatrix_t MEt):=\n   Generate m p (m * p) (fun k => (sum n (fun i => DenseMatrix_get m n M1 (Nat.div k  p) i *e DenseMatrix_get n p M2 i (Nat.modulo k p)))).\n\n Definition Matrix_elem_op (op: MEt -> MEt -> MEt) (m n: nat) (M1 M2: DenseMatrix_t MEt):=\n   Generate m n (m * n) (fun k => op (DenseMatrix_get m n M1 (Nat.div k n) (Nat.modulo k n)) (DenseMatrix_get m n M2 (Nat.div k n) (Nat.modulo k n))).\n\n Lemma Generate_index: forall (m n l i: nat) (f: nat -> MEt),\n     i < l -> \n     nth_default MEzero (Generate m n l f) i = f(m * n + i - l).\n Proof.\n   intros.\n   generalize dependent i. induction l; intros.\n   - inversion H.\n   - cbn.\n     destruct i.\n     + rewrite nth_default_0.  auto.\n     + rewrite nth_default_S.\n       rewrite IHl; try omega.\n       replace (m * n + i - l) with (m * n + (S i) - (S l)) by omega.\n       reflexivity.\n Qed. \n\n Corollary Generate_get: forall (m n i j: nat) (f: nat -> MEt),\n     i < m -> j < n -> \n     DenseMatrix_get m n (Generate m n (m * n) f) i j = f(i * n + j).\n Proof.\n   intros.\n   unfold DenseMatrix_get.\n   rewrite Generate_index.\n   - rewrite minus_plus. reflexivity.\n   - destruct m; try omega.\n     destruct n; try omega.\n     \n     assert (i <= m) by omega.\n     assert (j <= n) by omega.\n     assert (i * S n <= m * S n) by (apply mult_le_compat_r; assumption).\n     assert (i * S n + j <= m * S n + j) by (apply plus_le_compat_r; assumption).\n     assert (m * S n + j <= m * S n + n) by (apply plus_le_compat_l; assumption).\n     assert (m * S n + n < S m * S n).\n     {\n       simpl.\n       rewrite <- mult_n_Sm.\n       omega.\n     }\n     omega.\n Qed.\nEnd A. \n\nDefinition DenseMatrix_fill {ME: MatrixElem} m n f := Generate m n (m * n) (fun x => f (x / n) (x mod n)).\nDefinition DenseMatrix_elementwise_op {ME: MatrixElem} m n op m1 m2 := Matrix_elem_op op m n m1 m2.\n\nDefinition DenseMatrix {ME: MatrixElem} : Matrix.\n unshelve eapply {| Mt m n := DenseMatrix_t MEt;\n                    Mget := DenseMatrix_get;\n                    Mtimes := DenseMatrix_mul;\n                    Mfill := DenseMatrix_fill;\n                    Melementwise_op := DenseMatrix_elementwise_op |};\n   unfold DenseMatrix_fill, DenseMatrix_elementwise_op.\n - intros.  \n   unfold DenseMatrix_mul. \n   rewrite Generate_get; try assumption.\n   replace ((i * p + j) / p) with (i).\n   replace ((i * p + j) mod p) with (j).\n   reflexivity.\n   + rewrite plus_comm. rewrite Nat.mod_add; try omega.\n     rewrite Nat.mod_small; auto.\n   + apply Nat.div_unique with (a := (i * p + j)) (b := p) (r := j); auto.\n     rewrite mult_comm. reflexivity.\n - intros.\n   simpl.\n   rewrite Generate_get; auto.\n   Print Nat.div_unique.\n   rewrite <- Nat.div_unique with (b := n) (q := i) (r := j) (a := i * n + j); auto; try omega.\n   Focus 2.\n   rewrite Nat.mul_comm. reflexivity.\n\n   rewrite Nat.add_comm. \n   rewrite Nat.mod_add; try omega.\n   rewrite Nat.mod_small; try omega.\n   reflexivity.\n\n - intros.\n   unfold Matrix_elem_op. \n   rewrite Generate_get; try assumption.\n   replace ((i * n + j) / n) with (i).\n   replace ((i * n + j) mod n) with (j).\n   reflexivity.\n   + rewrite plus_comm. rewrite Nat.mod_add; try omega.\n     rewrite Nat.mod_small; auto.\n   + apply Nat.div_unique with (a := (i * n + j)) (b := n) (r := j); auto.\n     rewrite mult_comm. reflexivity.\nDefined.\n", "meta": {"author": "mit-plv", "repo": "Fiat_matrix", "sha": "cc68414a55b90212d855587bffc59cecaf999e58", "save_path": "github-repos/coq/mit-plv-Fiat_matrix", "path": "github-repos/coq/mit-plv-Fiat_matrix/Fiat_matrix-cc68414a55b90212d855587bffc59cecaf999e58/DenseMatrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7948893744877801}}
{"text": "(**\n<<\n  1. Introduction\n>>\n*)\n\n\n  \n  Fixpoint fact_aux (acc: nat) (n:nat):=\n    match n with\n      | O => acc\n      | S n' => (fact_aux (acc*n) n')\n    end.\n  Functional Scheme fact_aux_ind := Induction for fact_aux Sort Prop.\n  \n  Definition fact_tr (n: nat) := fact_aux 1 n.\n\n\n  Require Import Arith Ring.\n  \n  Lemma fact_aux_assoc: forall n acc m,\n      m * (fact_aux acc n) = fact_aux (m*acc) n.\n  Proof.\n    intro n. \n    induction n as [| n']; intros. \n    - simpl.\n      rewrite mult_comm.\n      reflexivity.\n    - simpl (fact_aux acc (S n')).\n      rewrite IHn'.\n      simpl.\n      rewrite <- mult_assoc.      \n      reflexivity.\n  Qed.   \n\n  \n  Fixpoint fact_seed (seed n:nat):=\n    match n with\n      | O => seed\n      | S n' => n * (fact_seed seed n')\n    end.\n  Functional Scheme fact_seed_ind := Induction for fact_seed Sort Prop.\n  \n  Theorem fact_seed__fact_aux: forall n acc,\n      fact_seed acc n = fact_aux acc n.\n  Proof.\n    intros.\n    functional induction (fact_seed acc n). \n    - simpl. reflexivity.\n    - simpl (fact_aux acc (S n')).\n      symmetry.\n      rewrite mult_comm.\n      rewrite <- fact_aux_assoc.\n      rewrite IHn0.\n      reflexivity.\n  Qed. \n  \n  Theorem fact_tr_div: forall n acc,\n      n > 0 -> Nat.divide n (fact_aux acc n).\n  Proof. \n    intros * Ngt0.\n    destruct n as [| n'].\n    - inversion Ngt0.\n    - simpl.\n\n  Restart. \n    intros * Ngt0.\n    rewrite <- fact_seed__fact_aux.\n    destruct n as [| n'].\n    - inversion Ngt0.\n    - unfold fact_seed; fold fact_seed. \n      apply Nat.divide_factor_l. \n  Qed.\n\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/Fact/Fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.7948586110703232}}
{"text": "Require Import List.\n\nDefinition char := nat.\nDefinition string := list char.\n\n(* regular expressions defined as an inductive type *)\nInductive Exp : Set :=\n  | Lit : char -> Exp\n  | And : Exp -> Exp -> Exp\n  | Or  : Exp -> Exp -> Exp\n  | Many: Exp -> Exp.\n\n(* each regular expression has an associated 'language', namely a set of \nstrings which are 'recognized' by the regular expression. Normally, this set \nof strings can easily be defined recursively. However, it is not finite in \ngeneral. Here we are attempting to define this set of strings as a type\n'Language r'. So we are defining a family of types (indexed by a regular \nexpression) with an inductive definition. Now given a regular expression\nr:Exp, the type 'Language r' is not quite a set of strings. It is more like\nan inductive type, i.e. some free algebra of some sort. However, any element\nof type Language r can easily be translated into a string via some\n'semantics' function defined below *)\n\nInductive Language : Exp -> Set := \n  | LangLit     : forall c:char, Language (Lit c)\n  | LangAnd     : forall r1 r2: Exp, \n                    Language r1  -> Language r2  -> Language (And r1 r2)\n  | LangOrLeft  : forall r1 r2: Exp, Language r1  -> Language (Or r1 r2)\n  | LangOrRight : forall r1 r2: Exp, Language r2  -> Language (Or r1 r2)\n  | LangEmpty   : forall r: Exp, Language (Many r)\n  | LangMany    : forall r: Exp, \n                    Language (Many r) -> Language r -> Language (Many r).\n\nFixpoint semantics {r:Exp}(s:Language r) : string :=\n  match s with\n    | LangLit c           => (c::nil)\n    | LangAnd r1 r2 s1 s2 => semantics s1 ++ semantics s2\n    | LangOrLeft r1 r2 s  => semantics s\n    | LangOrRight r1 r2 s => semantics s\n    | LangEmpty r         => nil\n    | LangMany r s1 s2    => semantics s1 ++ semantics s2\n  end.\n\n(* We now attempt to formalize the relation 'recognize' which expresses the \nfact that a string is an element of the language defined by a regular expression. \nSince we have already formalized the notion of 'Language', the fact that s:string \nis 'recognized' by a regular expression r (i.e. that it belongs to its language), \ncan be expressed as the fact that s = semantics x for some x:Language r. Rather \nthan proceeding this way, we now attempt to define the 'recognize' relation \ndirectly as an inductive predicate. We shall then attempt to prove the equivalence \nbetween the two approaches. *)\n\nInductive recognize : Exp -> string -> Prop :=\n  | recogLit    : forall c:char, recognize (Lit c) (c::nil)\n  | recogAnd    : forall (r1 r2:Exp)(s1 s2:string), \n      recognize r1 s1 -> recognize r2 s2 -> recognize (And r1 r2) (s1 ++ s2)\n  | recogOrLeft : forall (r1 r2:Exp)(s :string), \n      recognize r1 s -> recognize (Or r1 r2) s\n  | recogOrRight: forall (r1 r2:Exp)(s :string), \n      recognize r2 s -> recognize (Or r1 r2) s\n  | recogEmpty  : forall (r:Exp), recognize (Many r) nil\n  | recogMany   : forall (r:Exp) (s1 s2: string), \n      recognize (Many r) s1 -> recognize r s2 -> recognize (Many r) (s1 ++ s2).\n\n(* First we show that a recognized string is part of the language *)\n(* The proof flows naturally from an induction on the inductive predicate *)\nLemma recognize_imp_in_language: forall (r:Exp)(s:string),\n  recognize r s -> (exists x:Language r, semantics x = s).\nProof.\n  (* induction on the recognize predicate *)\n  intros r s H. generalize H. elim H.\n\n  clear H r s. intros c H. exists (LangLit c). simpl. reflexivity.\n\n  clear H r s. intros r1 r2 s1 s2 H1 H1' H2 H2' H.\n  elim H1'. intros x1 S1. clear H1'. \n  elim H2'. intros x2 S2. clear H2'.\n  exists (LangAnd r1 r2 x1 x2). simpl. rewrite S1, S2. reflexivity.\n  exact H2. exact H1.\n\n  clear H r s. intros r1 r2 s H H' H0. clear H0.\n  elim H'. intros x S. exists (LangOrLeft r1 r2 x). simpl. exact S. exact H.\n\n  clear H r s. intros r1 r2 s H H' H0. clear H0.\n  elim H'. intros x S. exists (LangOrRight r1 r2 x). simpl. exact S. exact H.\n\n  clear H r s. intros r H. exists (LangEmpty r). simpl. reflexivity. \n\n  clear H r s. intros r s1 s2 H1 H1' H2 H2' H.\n  elim H1'. intros x1 S1. clear H1'. \n  elim H2'. intros x2 S2. clear H2'.\n  exists (LangMany r x1 x2). simpl. rewrite S1, S2. reflexivity.\n  exact H2. exact H1.\nQed.\n\n(* Next we show that all strings of the language are recognized *)\n(* very simple coq proof with an induction on x                 *)\nLemma recognize_language: forall (r:Exp)(x: Language r),\n  recognize r (semantics x).\nProof.\n  (* induction on x *)\n  intros r x. elim x. \n  (* x = LangLit c *)\n  clear r x. simpl. apply recogLit.\n  (* x = LangAnd r1 r2 x1 x2 *)\n  clear r x. intros r1 r2 x1 H1 x2 H2. simpl. \n  apply recogAnd. exact H1. exact H2. \n  (* x = LangOrLeft r1 r2 x1 *)\n  clear r x. intros r1 r2 x1 H1. simpl.\n  apply recogOrLeft. exact H1.\n  (* x = LangOrRight r1 r2 x2 *)\n  clear r x. intros r1 r2 x2 H2. simpl.\n  apply recogOrRight. exact H2.\n  (* x = LangEmpty r *)\n  clear r x. intros r. simpl. apply recogEmpty.\n  (* x = LangMany r x1 x2 *)\n  clear r x. intros r x1 H1 x2 H2. simpl.\n  apply recogMany. exact H1. exact H2.\nQed.\n \n\n(* re-formatting previous lemma *)\nLemma in_language_imp_recognize: forall (r:Exp)(s:string),\n  (exists x:Language r, semantics x = s) -> recognize r s. \nProof.\n  intros r s H. elim H. intros x Hx. clear H. rewrite <- Hx.\n  apply recognize_language.\nQed.\n\n\n(* This efectively show the equivalence between the two approaches *)\nLemma in_language_is_recognize: forall (r:Exp)(s:string),\n  (exists x:Language r, semantics x = s) <-> recognize r s.\nProof.\n  intros r s. split. apply in_language_imp_recognize.\n  apply recognize_imp_in_language.\nQed.\n\n(* At this stage, we have defined what a regular expression is as well\nas what it means for a string to be recognized by a regular expression.\nNow an obvious question arises: given a regular expression (r:Exp) and \na string (s:string), how do I decide whether s is recognized by r? \nFrom a mathematical point of view, there exists a function \nf : Exp -> string -> bool which returns 1 if and only if s belongs to \nthe language of r (i.e. s = semantics x for some x:Language r)\nHowever, we would like a program which implements such a function *)\n\n\n\n\n\n\n\n(*\n(* this definition is needed for the next lemma *)\nDefinition Lang_of_Lit_Pred {r:Exp}(x:Language r) := (* major trick *)\n  match r (* return Language r -> Prop *) with\n   | Lit c => fun x => x = LangLit c\n   | other => fun _ => True\n end x.\n \nLemma Lang_of_Lit: forall (c:char)(x:Language (Lit c)),\n  x = LangLit c.\nProof.\n  intros c x. fold (Lang_of_Lit_Pred x).\n  cut(forall (r:Exp)(x:Language r), Lang_of_Lit_Pred x). eauto.\n  clear c x. intros r x. destruct x; simpl; auto.\nQed.\n\n(* this definition is needed for the next lemma *)\nDefinition Lang_of_And_Pred {r:Exp}(x:Language r) := (* major trick *)\n  match r with\n    | And r1 r2   => fun x => \n        exists (x1: Language r1)(x2: Language r2), x = LangAnd r1 r2 x1 x2\n    | other       => fun _ => \n        True\n  end x.\n\nLemma Lang_of_And: forall (r1 r2: Exp)(x: Language (And r1 r2)),\n  exists (x1: Language r1)(x2: Language r2), \n  x = LangAnd r1 r2 x1 x2.\nProof. \n  intros r1 r2 x. fold (Lang_of_And_Pred x).\n  cut(forall (r:Exp)(x:Language r), Lang_of_And_Pred x). eauto.\n  clear r1 r2 x. intros r x. destruct x; simpl; eauto.\nQed.\n\n(* this definition is needed for the next lemma *)\nDefinition Lang_of_Or_Pred {r:Exp}(x:Language r) := (* major trick *)\n  match r with\n    | Or r1 r2   => fun x => \n        (exists (x1: Language r1), x = LangOrLeft r1 r2 x1) \\/\n        (exists (x2: Language r2), x = LangOrRight r1 r2 x2)\n    | other       => fun _ => \n        True\n  end x.\n\nLemma Lang_of_Or: forall (r1 r2: Exp)(x: Language (Or r1 r2)),\n  (exists (x1: Language r1), x = LangOrLeft r1 r2 x1) \\/\n  (exists (x2: Language r2), x = LangOrRight r1 r2 x2).\nProof.\n  intros r1 r2 x. fold (Lang_of_Or_Pred x). \n  cut(forall (r:Exp)(x:Language r), Lang_of_Or_Pred x). eauto.\n  clear r1 r2 x. intros r x. destruct x; simpl; eauto.\nQed.\n\n\n\n(* this definition is needed for the next lemma *)\nDefinition Lang_of_Many_Pred {r:Exp}(x:Language r) := (* major trick *)\n  match r with\n    | Many r'     => fun x => \n        (x = LangEmpty r') \\/\n        (exists (x1: Language (Many r'))(x2: Language r'), \n          x = LangMany r' x1 x2)\n    | other       => fun _ => \n        True\n  end x.\n\n\nLemma Lang_of_Many: forall (r: Exp)(x: Language (Many r)),\n  (x = LangEmpty r) \\/\n  (exists (x1: Language (Many r))(x2: Language r),\n    x = LangMany r x1 x2).\nProof. \n  intros r x. fold (Lang_of_Many_Pred x).\n  cut (forall (r: Exp)(x:Language r), Lang_of_Many_Pred x). eauto.\n  clear r x. intros r x. destruct x; simpl; eauto.\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/regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7947245321130522}}
{"text": "Module ForallExists.\n\nRequire Import Classical.\n\nTheorem forall_exists : forall D, forall P : D -> Prop,\n  ~ (forall x : D, P x) <-> (exists x : D, ~ P x).\nsplit.\nintros.\nCheck Peirce.\napply Peirce.\nintros.\nexfalso.\napply H.\nintros.\napply Peirce.\nintros.\nexfalso.\napply H0.\nexists x.\nassumption.\nintros.\nunfold not.\nintros.\nelim H.\nintros.\nassert (P x).\napply H0.\ncontradiction.\nQed.\n\nPrint forall_exists.\n\nEnd ForallExists.\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/playground/testforallexists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7947245297653219}}
{"text": "Require Import Verse.Word.\nRequire Import Verse.NFacts.\n\nRequire Import Coq.setoid_ring.Ring_theory.\nRequire Import BinNums.\nRequire Import BinInt.\n\nRequire Import NArith.\n\nLocal Notation wO   := (bits (N2Bv_gen _ 0)).\nLocal Notation wI   := (bits (N2Bv_gen _ 1)).\nLocal Notation wadd := (numBinOp N.add).\nLocal Notation wmul := (numBinOp N.mul).\nLocal Notation weq  := (@eq (Word.t _)).\n\nSection WordRing.\n\n  Variable n : nat.\n\n  Infix \"==\" := weq (at level 70).\n\n  Ltac crush_mod_ring :=\n    repeat (intros []); unfold numBinOp, numUnaryOp;\n    apply f_equal;\n    apply Bv2N_inj; rewrite ?Bv2N_N2Bv_gen_mod;\n    simpl;\n    try (rewrite ?N.add_mod_idemp_l);\n    try rewrite ?N.add_mod_idemp_r;\n    try rewrite ?N.mul_mod_idemp_l;\n    try rewrite ?N.mul_mod_idemp_r;\n    try rewrite N.mul_1_l;\n    try rewrite N.mul_add_distr_l;\n    try rewrite N.mul_add_distr_r;\n    trivial;\n    try rewrite N.add_assoc +\n    rewrite N.mul_assoc +\n    rewrite N.add_comm  +\n    rewrite N.mul_comm  +\n    rewrite N.mod_small;\n    trivial;\n    try (discriminate + apply two_power_nonzero + apply Bv2N_small).\n\n  Lemma wadd_0_l : forall (x : Word.t n), wadd wO x == x.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wadd_comm : forall (x y : Word.t n), wadd x y == wadd y x.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wadd_assoc : forall (x y z : Word.t n), wadd x (wadd y z) == wadd (wadd x y) z.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wmul_1_l : forall x : Word.t n, wmul wI x == x.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wmul_0_l : forall x : Word.t n, wmul wO x == wO.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wmul_comm : forall x y : Word.t n, wmul x y == wmul y x.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wmul_assoc : forall x y z : Word.t n, wmul x (wmul y z) == wmul (wmul x y) z.\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Lemma wdistr_l : forall x y z : Word.t n, wmul (wadd x y) z == wadd (wmul x z) (wmul y z).\n  Proof.\n    crush_mod_ring.\n  Qed.\n\n  Definition mod_semi_ring : semi_ring_theory wO wI wadd wmul weq :=\n    {|\n      SRadd_0_l := wadd_0_l;\n      SRadd_comm := wadd_comm;\n      SRadd_assoc := wadd_assoc;\n      SRmul_1_l := wmul_1_l;\n      SRmul_0_l := wmul_0_l;\n      SRmul_comm := wmul_comm;\n      SRmul_assoc := wmul_assoc;\n      SRdistr_l := wdistr_l\n    |}.\n\n  Add Ring Word : mod_semi_ring.\n\nEnd WordRing.\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/WordRing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7946636662480753}}
{"text": "Require Import Arith Omega.\n\nDefinition divides (n m:nat) := exists p:nat, p*n = m.\n\nLtac first_step :=  \n  unfold divides;\n  intros.\n\nLemma divides_O : forall n:nat, divides n 0.\n  first_step.\n  exists 0.\n  ring.\nQed.\n\nLemma divides_plus : forall n m:nat, divides n m -> divides n (n+m).\n  first_step.\n  destruct H.\n  exists (S x).\n  rewrite mult_succ_l.\n  omega.\nQed.\n\nLemma not_divides_plus : forall n m:nat, ~ divides n m -> ~ divides n (n+m).\n  first_step.\n  unfold not in *.\n  intros.\n  apply H.\n  destruct H0.\n  exists(x - 1).\n  rewrite mult_minus_distr_r.\n  omega.\nQed.\n\nLemma not_divides_lt : forall n m:nat, 0<m ->  m<n -> ~ divides n m.\n  first_step.\n  unfold not.\n  intros.\n  destruct H1.\n  rewrite <- H1 in *.\n  destruct x.\n  omega.\n  clear H H1.\n  absurd(S x * n < n).\n  apply le_not_lt.\n  rewrite mult_succ_l.\n  apply le_plus_r.\n  assumption.\nQed.\n\nLemma not_lt_2_divides : forall n m:nat, n <> 1 -> n < 2 -> 0 < m -> ~ divides n m.\n  first_step.\n  unfold not.\n  intros.\n  destruct H2.\n  destruct n.\n  omega.\n  destruct n.\n  auto.\n  absurd(S (S n) < 2).\n  omega.\n  auto.\nQed.\n\nLemma le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\n  intros.\n  omega.\nQed.\n\nLemma lt_lt_or_eq : forall n m:nat, n < S m ->  n < m \\/ n = m.\n  intros.\n  omega. \nQed.\n\nGoal forall n p:nat, n <= p -> p < S n -> n = p.\n  intros.\n  omega.\nQed.", "meta": {"author": "DKXXXL", "repo": "CoqArt", "sha": "ae8f577a618aeb7182c4478642a9d5ce4b289b46", "save_path": "github-repos/coq/DKXXXL-CoqArt", "path": "github-repos/coq/DKXXXL-CoqArt/CoqArt-ae8f577a618aeb7182c4478642a9d5ce4b289b46/Chapter7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7945797419072281}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import ssr_frap.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\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. *)\n  \nModule ArithWithVariables.\n\n  Inductive arith : Set :=\n  | Const (n : nat)\n  | Var (x : var)\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 => (size e1 + size e2).+1\n    | Times e1 e2 => (size e1 + size e2).+1\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 => (maxn (depth e1) (depth e2)).+1\n    | Times e1 e2 => (maxn (depth e1) (depth e2)).+1\n    end.\n\n  Compute depth ex1.\n  Compute depth ex2.\n\n  (* linear_arithmetic で解く補題のサンプル *)\n  Lemma max_le_add m1 n1 m2 n2 : m1 <= m2 -> n1 <= n2 ->\n                                 maxn m1 n1 <= m2 + n2.\n  Proof.\n    rewrite /maxn.\n    case H : (m1 < n1) => Hm Hn. (* destruct (m1 < n1) eqn: H => Hm Hn *)\n    - rewrite -[n1]add0n. by apply: leq_add.\n    - rewrite addnC -[m1]add0n. by apply: leq_add.\n\n    Restart.\n    rewrite /maxn.\n    case H : (m1 < n1) => Hm Hn.\n    - by ssromega.\n    - by ssromega.\n\n    Restart.\n      by linear_arithmetic.\n  Qed.\n  \n  Theorem depth_le_size e : depth e <= size e.\n  Proof.\n    elim: e => [n | x | e1 He1 e2 He2 | e1 He1 e2 He2] //=.\n    - by linear_arithmetic.                (* by apply: max_le_add. *)\n    - by linear_arithmetic.                (* by apply: max_le_add. *)      \n  Qed.\n  \n  Theorem depth_le_size_snazzy e : depth e <= size e.\n  Proof.\n      by elim: e => //=; 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    | 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  (* [commuter] has all the appropriate interactions with other functions (and itself). *)\n  \n  Theorem size_commuter e : size (commuter e) = size e.\n  Proof.\n    by elim: e => //=; linear_arithmetic.\n  Qed.\n  \n  Theorem depth_commuter e : depth (commuter e) = depth e.\n  Proof.\n    elim: e => //= [e1 He1 e2 He2 | e1 He1 e2 He2];\n                 (* congr (_ + _) *)\n                 by rewrite He1 He2 maxnC.\n  Qed.\n  \n  Theorem commuter_inverse e : commuter (commuter e) = e.\n  Proof.\n      by elim: e => //= [e1 He1 e2 He2 | e1 He1 e2 He2]; equality. (* rewrite He1 He2. *)\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\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   * (To dig into it more on your own, the appropriate keyword is \"dependent types.\") *)\n  Fixpoint substitute (inThis : arith) (replaceThis : var) (withThis : arith) : arith :=\n    match inThis with\n    | Const _ => inThis\n    | Var x =>\n      if x == replaceThis then withThis else inThis (* eqType の == を使う。 *)\n    | Plus e1 e2 =>\n      Plus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n    | Times e1 e2 =>\n      Times (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n    end.\n\n  Lemma max_le_add_c m1 n1 m2 n2 c : m1 <= m2 + c -> n1 <= n2 + c ->\n                                 maxn m1 n1 <= maxn m2 n2 + c.\n  Proof.\n    by linear_arithmetic.\n    \n    Restart.\n    (* linear_arithemtic' の repeat が効いている例 *)\n    move=> Hm Hn.\n    rewrite {1}/maxn.\n    case H1 : (m1 < n1).\n    - rewrite /maxn.\n      case H2 : (m2 < n2); by ssromega.\n    - rewrite /maxn.\n      case H2 : (m2 < n2); by ssromega.\n  Qed.\n  \n  (* An intuitive property about how much [substitute] might increase depth. *)\n  Theorem substitute_depth replaceThis withThis inThis :\n    depth (substitute inThis replaceThis withThis) <= depth inThis + depth withThis.\n  Proof.\n    elim: inThis => //= [x | e1 He1 e2 He2 | e1 He1 e2 He2].\n    - case H : (x == 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\n      + by linear_arithmetic.\n      + rewrite /depth.\n        by linear_arithmetic.\n    - (* rewrite -addnA leq_add2l. *)\n        by apply: max_le_add_c.\n    - (* rewrite -addnA leq_add2l. *)\n        by apply: max_le_add_c.\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  \n  Theorem substitute_depth_snazzy replaceThis withThis inThis :\n    depth (substitute inThis replaceThis withThis) <= depth inThis + depth withThis.\n  Proof.\n    elim: inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a == ?b then _ else _] ] => cases (a == b); simplify\n        end; linear_arithmetic.\n    Qed.\n  \n  (* A silly self-substitution has no effect. *)\n  \n  Theorem substitute_self replaceThis inThis :\n    substitute inThis replaceThis (Var replaceThis) = inThis.\n  Proof.\n    elim: inThis => //= [x | e1 He1 e2 He2 | e1 He1 e2 He2].\n    - case H : (x == replaceThis).\n      + move/eqP in H.\n        by rewrite H.\n      + done.\n    - by rewrite He1 He2.\n    - by rewrite He1 He2.\n  Qed.\n  \n  Theorem substitute_self_snazzy replaceThis inThis :\n    substitute inThis replaceThis (Var replaceThis) = inThis.\n  Proof.\n    elim: inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a == ?b then _ else _] ] => cases (a == b); simplify\n        end; try equality.\n    (* H : x == replaceThis が残ってしまう。 *)\n    by move/eqP in Heq; equality.\n  Qed.\n  \n  (* We can do substitution and commuting in either order. *)\n  \n  Theorem substitute_commuter replaceThis withThis inThis :\n    commuter (substitute inThis replaceThis withThis)\n    = substitute (commuter inThis) replaceThis (commuter withThis).\n  Proof.\n    elim: inThis => //= [x | e1 He1 e2 He2 | e1 He1 e2 He2].\n    - by case H : (x == replaceThis).\n    - by rewrite He1 He2.\n    - by rewrite He1 He2.\n  Qed.\n  \n  Theorem substitute_commuter_snazzy replaceThis withThis inThis :\n    commuter (substitute inThis replaceThis withThis)\n    = substitute (commuter inThis) replaceThis (commuter withThis).\n  Proof.\n    elim: inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a == ?b then _ else _] ] => cases (a == 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 e : size (constantFold e) <= size e.\n  Proof.\n    induction e; simpl;\n      repeat match goal with\n             | [ |- context[match ?E with _ => _ end] ] =>\n               destruct E; simpl in *\n             end;\n        by ssromega.\n  Qed.\n  \n  (* Business as usual, with another commuting law *)\n  Theorem commuter_constantFold e :\n    commuter (constantFold e) = constantFold (commuter e).\n  Proof.\n    (*\n    induction e; simpl;\n    repeat match goal with\n           | [ |- context[match ?E with _ => _ end] ] => destruct E; simpl; simpl in *\n           | [ H : ?f _ = ?f _ |- _ ] => inversion H\n           | [ |- ?f _ = ?f _ ] => f_equal\n           end.\n     *)\n    (* Error: Out of memory. *)\n    Admitted.\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 n : n * 0 = 0.\n  Proof.\n      by 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 e multiplyBy :\n    depth (pushMultiplicationInside' multiplyBy e)\n    = depth (pushMultiplicationInside' 0 e).\n  Proof.\n    elim: e multiplyBy => //= [e1 IHe1 e2 IHe2 n | e1 IHe1 e2 IHe2 n].\n    - move: (IHe1 n) (IHe2 n).\n        by linear_arithmetic.\n    - case H : (isConst e1) => /=.\n      + rewrite IHe2 n_times_0.\n        by linear_arithmetic.\n      + rewrite IHe1.\n        by 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 e multiplyBy :\n    depth (pushMultiplicationInside' multiplyBy e)\n    = depth (pushMultiplicationInside' 0 e).\n  Proof.\n    elim: e multiplyBy => //= [e1 IHe1 e2 IHe2 n | e1 IHe1 e2 IHe2 n];\n    try match goal with\n        | [ |- context[match ?E with _ => _ end] ] => cases E; simplify\n        end; equality.\n(*\n    try match goal with\n        | [ |- context[match ?E with _ => _ end] ] => destruct E; simpl\n        end; congruence.\n*)\n  Qed.\n\n  (* Now the general corollary about irrelevance of coefficients for depth. *)\n  Lemma depth_pushMultiplicationInside'_irrelevance e multiplyBy1 multiplyBy2 :\n    depth (pushMultiplicationInside' multiplyBy1 e)\n    = depth (pushMultiplicationInside' multiplyBy2 e).\n  Proof.\n    transitivity (depth (pushMultiplicationInside' 0 e)).\n    (* [transitivity X]: when proving [Y = Z], switch to proving [Y = X]\n     * and [X = Z]. *)\n    - by 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        by 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' e :\n    depth (pushMultiplicationInside' 0 e) <= (depth e).+1.\n  Proof.\n    elim: e => //= [e1 IHe1 e2 IHe2 | e1 IHe1 e2 IHe2].\n    - by linear_arithmetic.\n    - case H : (isConst e1) => /=.\n      + rewrite n_times_0.\n          by linear_arithmetic.\n      + by linear_arithmetic.\n  Qed.\n  \n  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 e :\n    depth (pushMultiplicationInside' 0 e) <= (depth e).+1.\n  Proof.\n    elim: e => //= [e1 IHe1 e2 IHe2 | e1 IHe1 e2 IHe2];\n    try match goal with\n        | [ |- context[match ?E with _ => _ end] ] =>\n          cases E; simplify\n       (* destruct E; try autorewrite with core; simpl *)\n        end; linear_arithmetic.\n  Qed.\n  \n  Theorem depth_pushMultiplicationInside e :\n    depth (pushMultiplicationInside e) <= (depth e).+1.\n  Proof.\n    unfold pushMultiplicationInside.\n    (* [unfold X]: replace [X] by its definition. *)\n    rewrite depth_pushMultiplicationInside'_irrelevance0.\n    by apply depth_pushMultiplicationInside'.\n  Qed.\n  \nEnd ArithWithVariables.\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/frap/ssr_basic_syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7944512232354389}}
{"text": "(** Algoritmo de Ordenação por Inserção em listas *)\n\nRequire Import List Arith.\nOpen Scope nat_scope.\n\n(** * Definição de ordenação *)\n\nInductive ordenada: list nat -> Prop :=\n| lista_vazia: ordenada nil\n| lista_unit: forall x, ordenada (x :: nil)\n| lista_mult: forall x y l, x <= y -> ordenada (y :: l) -> ordenada (x :: y :: l).\n\n(** * Definição da função de inserção *)\n\nFixpoint insere (n:nat) (l: list nat) :=\n  match l with\n  | nil => n :: nil\n  | h :: tl => if n <=? h then (n :: l)\n             else (h :: (insere n tl)) \n                      end.\n\n(** * Definição da função principal do algoritmo. *)\n\n Fixpoint ord_insercao l :=\n  match l with\n    | nil => nil\n    | h :: tl => insere h (ord_insercao tl)\n  end.\n\n(** A função [insert] preserva a ordenação. *)\n\nLemma insere_preserva_ordem: forall l x, ordenada l -> ordenada (insere x l). \nProof.\n(* Substitua esta linha pela sua prova. Provas completas terminam com Qed. *)  Admitted.\n\n(** O algoritmo ord_insercao ordena. *)\n\nLemma ord_insercao_ordena: forall l, ordenada (ord_insercao l).\nProof.\n(* Substitua esta linha pela sua prova. Provas completas terminam com Qed. *)  Admitted.\n  \n(** * Permutação *)\n\nInductive perm: list nat -> list nat -> Prop :=\n| perm_refl: forall l, perm l l\n| perm_hd: forall x l l', perm l l' -> perm (x::l) (x::l')\n| perm_swap: forall x y l l', perm l l' -> perm (x::y::l) (y::x::l')\n| perm_trans: forall l l' l'', perm l l' -> perm l' l'' -> perm l l''.\n\nLemma ord_insercao_perm: forall l, perm l (ord_insercao l).\nProof.\n(* Substitua esta linha pela sua prova. Provas completas terminam com Qed. *)  Admitted.\n\n\nTheorem correcao_ord_insercao: forall l, ordenada (ord_insercao l) /\\ perm l (ord_insercao l).\nProof.\n  Admitted.\n  \n(** Extração de código certificado *)\n\nRequire Extraction.\n\nRecursive Extraction ord_insercao.\nExtraction \"ord_insercao.ml\" ord_insercao.\n\n", "meta": {"author": "flaviodemoura", "repo": "paa-2020-1-projeto1", "sha": "bf834a1dc86540525d6ab455a65bf2f754294123", "save_path": "github-repos/coq/flaviodemoura-paa-2020-1-projeto1", "path": "github-repos/coq/flaviodemoura-paa-2020-1-projeto1/paa-2020-1-projeto1-bf834a1dc86540525d6ab455a65bf2f754294123/ord_insercao.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.9019206686206199, "lm_q1q2_score": 0.7944090951332144}}
{"text": "Require Export List.\nRequire Export Omega.\n\nModule Type Comparable_data.\nParameter A : Set.\nParameter Ale : A -> A -> Prop.\nParameter Ale_dec : forall x y:A, {Ale x y} + {Ale y x}.\nEnd Comparable_data.\n\nModule Type SORTING_BASICS.\nParameter A : Set.\nParameter Ale : A -> A -> Prop.\nParameter Ale_dec : forall x y:A, {Ale x y} + {Ale y x}.\nParameter sort : list A -> list A.\n\nInductive 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        Ale x y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nInductive permutation : list A -> list A -> Prop :=\n  | transpose_first :\n      forall (a b:A) (l:list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_same_head :\n      forall (a:A) (l1 l2:list A),\n        permutation l1 l2 -> permutation (a :: l1) (a :: l2)\n  | permutation_empty : permutation nil nil\n  | permutation_transitive :\n      forall l1 l2 l3:list A,\n        permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\n\nParameter sort_sorted : forall l:list A, sorted (sort l).\n\nParameter sort_permutation : forall l:list A, permutation (sort l) l.\n\nEnd SORTING_BASICS.\n\nModule merge_sort_basics (Data: Comparable_data) : \n  SORTING_BASICS \n  with   Definition A := Data.A \n  with Definition Ale := Data.Ale \n  with Definition  Ale_dec := Data.Ale_dec.\n\nDefinition A := Data.A.\nDefinition Ale := Data.Ale.\nDefinition Ale_dec := Data.Ale_dec.\n\nFixpoint merge_aux (l1 l2:list A) (b:nat) {struct b} : \n list A :=\n  match b with\n  | O => nil (A:=A)\n  | S b' =>\n      match l1, l2 with\n      | nil, l => l\n      | l, nil => l\n      | a :: l, b :: l' =>\n          match Ale_dec a b with\n          | left _ => a :: merge_aux l (b :: l') b'\n          | right _ => b :: merge_aux (a :: l) l' b'\n          end\n      end\n  end.\n\nDefinition merge (l1 l2:list A) := merge_aux l1 l2 (length l1 + length l2).\n\n(* Make a list of singleton lists to initiate merging. *)\n\nFixpoint mk_singletons (l:list A) : list (list A) :=\n  match l with\n  | nil => nil (A:=(list A))\n  | a :: tl => (a :: nil) :: mk_singletons tl\n  end.\n\n(* Given a list of lists, merge the first with the second,\n  then the third with the fourth, and so on. *)\n\nFixpoint sort_aux1 (l:list (list A)) : list (list A) :=\n  match l with\n  | l1 :: l2 :: tl => merge l1 l2 :: sort_aux1 tl\n  | _ => l\n  end.\n\n\nFixpoint sort_aux2 (l:list (list A)) (b:nat) {struct b} : \n list A :=\n  match b with\n  | O => nil (A:=A)\n  | S b' =>\n      match l with\n      | nil => nil (A:=A)\n      | l' :: nil => l'\n      | _ => sort_aux2 (sort_aux1 l) b'\n      end\n  end.\n\nDefinition sort (l:list A) := sort_aux2 (mk_singletons l) (length l).\n\n(* In principle the exercise stops here.  But what follows is\n  used to ensure that the sorting function we have defined does really\n  sort a list of data. *)\n\nInductive 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        Ale x y -> sorted (y :: l) -> sorted (x :: y :: l).\n\n\nTheorem sorted_inv : forall (a:A) (l:list A), sorted (a :: l) -> sorted l.\nProof.\n intros a l H; inversion H; assumption || constructor.\nQed.\n\n\nInductive all_sorted : list (list A) -> Prop :=\n  | all_sorted_nil : all_sorted nil\n  | all_sorted_rec :\n      forall (l:list A) (tl:list (list A)),\n        sorted l -> all_sorted tl -> all_sorted (l :: tl).\n\nTheorem mk_singletons_all_sorted :\n forall l:list A, all_sorted (mk_singletons l).\nProof.\n intros l; elim l; simpl in |- *; repeat (intros; constructor || assumption).\nQed.\n\nTheorem mk_singletons_length :\n forall l:list A, length (mk_singletons l) = length l.\nProof.\n simple induction l; simpl in |- *; auto.\nQed.\n\nInductive first_elem_prop : list A -> list A -> list A -> Prop :=\n  | all_empty : first_elem_prop nil nil nil\n  | fep_first :\n      forall (a:A) (l1 l2 l3:list A), \n        first_elem_prop (a :: l1) l2 (a :: l3)\n  | fep_second :\n      forall (a:A) (l1 l2 l3:list A), \n       first_elem_prop l1 (a :: l2) (a :: l3).\n\nTheorem merge_aux_sorted :\n forall (b:nat) (l1 l2:list A),\n   length l1 + length l2 <= b ->\n   sorted l1 ->\n   sorted l2 ->\n   sorted (merge_aux l1 l2 b) /\\ \n   first_elem_prop l1 l2 (merge_aux l1 l2 b).\nProof.\n intros b; elim b.\n intros l1 l2.\n case l1; case l2; simpl in |- *;\n  try (intros; match goal with\n               | id:(S _ <= _) |- _ => inversion id; fail\n               end).\n repeat constructor.\n\n intros b' Hrec l1; case l1.\n simpl in |- *; intros; split; [ assumption | case l2; constructor ].\n intros a l l2; case l2.\n simpl in |- *; intros; split; [ assumption | constructor ].\n simpl in |- *; intros a' l' Hle Hsorted1 Hsorted2; case (Ale_dec a a').\n elim (Hrec l (a' :: l')); auto.\n intros Hsorted' Hfep.\n generalize Hsorted' Hsorted1 Hsorted2; clear Hsorted1 Hsorted2 Hsorted'. \n inversion Hfep.\n intros Hsorted' Hsorted1 Hsorted2 Hale.\n inversion Hsorted1; repeat constructor || assumption.\n intros Hsorted' Hsorted1 Hsorted2 Hale.\n inversion Hsorted2; repeat constructor || assumption.\n simpl in |- *; omega.\n eapply sorted_inv; eauto.\n elim (Hrec (a :: l) l'); auto.\n intros Hsorted' Hfep.\n generalize Hsorted' Hsorted1 Hsorted2; clear Hsorted1 Hsorted2 Hsorted'. \n inversion Hfep.\n intros Hsorted' Hsorted1 Hsorted2 Hale.\n inversion Hsorted1; repeat constructor || assumption.\n intros Hsorted' Hsorted1 Hsorted2 Hale.\n inversion Hsorted2; repeat constructor || assumption.\n simpl in |- *; omega.\n eapply sorted_inv; eauto.\nQed.\n\nTheorem merge_sorted :\n forall l1 l2:list A, sorted l1 -> sorted l2 -> sorted (merge l1 l2).\nProof.\n unfold merge in |- *.\n intros l1 l2 H1 H2; \n  elim (merge_aux_sorted (length l1 + length l2) l1 l2);\n  auto.\nQed.\n\n(* sort_aux1 has a multiple recursion step, we need a\n   specific induction principle to work on this function. *)\n\nTheorem list_ind2 :\n forall (B:Set) (P:list B -> Prop),\n   P nil ->\n   (forall x:B, P (x :: nil)) ->\n   (forall (x1 x2:B) (l:list B), P l -> P (x1 :: x2 :: l)) ->\n   forall l:list B, P l.\nProof.\n intros B P P0 P1 Pr l.\n cut (P l /\\ (forall x:B, P (x :: l))).\n intuition.\n elim l; intuition.\nQed.\n\nTheorem sort_aux1_all_sorted :\n forall l:list (list A), all_sorted l -> all_sorted (sort_aux1 l).\nProof.\n intros l; elim l using list_ind2.\n simpl in |- *; trivial.\n simpl in |- *; trivial.\n intros x1 x2 tl Hrec Has.\n inversion Has; clear Has.\n match goal with\n | id:(all_sorted _) |- _ => inversion id\n end.\n simpl in |- *; constructor.\n apply merge_sorted; assumption.\n auto.\nQed.\n\nTheorem sort_aux1_shorter :\n forall l:list (list A), length (sort_aux1 l) <= length l.\nProof.\n intros l; elim l using list_ind2; simpl in |- *; auto with arith.\nQed.\n\nTheorem sort_aux2_sorted :\n forall (b:nat) (l:list (list A)),\n   length l <= b -> all_sorted l -> sorted (sort_aux2 l b).\nProof.\n intros b; elim b.\n intros l; case l.\n intros; constructor.\n simpl in |- *; intros a l' Hle; inversion Hle.\n intros b' Hrec l; case l.\n simpl in |- *; intros; constructor.\n intros l1 tl; case tl.\n intros Hle Has; inversion Has; assumption.\n simpl in |- *; intros l2 tl' Hle Has.\n apply Hrec.\n simpl in |- *.\n generalize (sort_aux1_shorter tl'); intros; omega.\n inversion Has; clear Has.\n match goal with\n | id:(all_sorted _) |- _ => inversion id\n end.\n constructor.\n apply merge_sorted; assumption.\n apply sort_aux1_all_sorted; assumption.\nQed.\n\nTheorem sort_sorted : forall l:list A, sorted (sort l).\nProof.\n intros l; unfold sort in |- *.\n apply sort_aux2_sorted.\n rewrite mk_singletons_length; auto.\n apply mk_singletons_all_sorted.\nQed.\n\nInductive permutation : list A -> list A -> Prop :=\n  | transpose_first :\n      forall (a b:A) (l:list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_same_head :\n      forall (a:A) (l1 l2:list A),\n        permutation l1 l2 -> permutation (a :: l1) (a :: l2)\n  | permutation_empty : permutation nil nil\n  | permutation_transitive :\n      forall l1 l2 l3:list A,\n        permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\n        \nTheorem permutation_reflexive : forall l:list A, permutation l l.\nProof.\n intros l; elim l; constructor; assumption.\nQed.\n\nTheorem permutation_symetric :\n forall l1 l2:list A, permutation l1 l2 -> permutation l2 l1.\nProof.\n intros l1 l2 H; elim H; try (intros; constructor; assumption).\n intros l3 l4 l5; intros; apply permutation_transitive with l4; \n  assumption.\nQed.\n\nTheorem permutation_app_cons :\n forall (l:list A) (a:A) (l':list A),\n   permutation (l ++ a :: l') (a :: l ++ l').\nProof.\n intros l; elim l.\n simpl in |- *; intros; apply permutation_reflexive.\n simpl in |- *; intros a' tl Hrec a l'.\n apply permutation_transitive with (a' :: a :: tl ++ l'); \n  constructor; auto.\nQed.\n\nTheorem merge_aux_permutation :\n forall (b:nat) (l1 l2:list A),\n   length l1 + length l2 <= b -> \n   permutation (merge_aux l1 l2 b) (l1 ++ l2).\nProof.\n intros b; elim b.\n intros l1 l2; case l1; case l2;\n  try\n   (simpl in |- *; intros;\n     match goal with\n     | id:(S _ <= _) |- _ => inversion id; fail\n     end).\n simpl in |- *; constructor.\n intros b' Hrec l1 l2; case l1.\n simpl in |- *; intros Hle; apply permutation_reflexive.\n simpl in |- *; intros a l; case l2.\n simpl in |- *; intros Hle; rewrite <- app_nil_end;\n  apply permutation_reflexive.\n simpl in |- *; intros a' l'; case (Ale_dec a a').\n intros Hale Hle.\n apply permutation_transitive with (a :: a' :: l ++ l').\n apply permutation_same_head.\n apply permutation_transitive with (l ++ a' :: l').\n apply (Hrec l (a' :: l')).\n simpl in |- *; omega.\n apply permutation_app_cons.\n constructor.\n apply permutation_symetric.\n apply permutation_app_cons.\n intros Hale Hle.\n apply permutation_transitive with (a' :: a :: l ++ l').\n apply permutation_same_head.\n apply (Hrec (a :: l) l').\n simpl in |- *; omega.\n apply permutation_transitive with (a :: a' :: l ++ l').\n constructor.\n apply permutation_same_head.\n apply permutation_symetric.\n apply permutation_app_cons.\nQed.\n\nTheorem merge_permutation :\n forall l1 l2:list A, permutation (merge l1 l2) (l1 ++ l2).\nProof.\n unfold merge in |- *; intros l1 l2; apply merge_aux_permutation; auto.\nQed.\n\nFixpoint app_all (l:list (list A)) : list A :=\n  match l with\n  | nil => nil (A:=A)\n  | l1 :: tl => l1 ++ app_all tl\n  end.\n\nTheorem app_all_mk_singletons_eq :\n forall l:list A, app_all (mk_singletons l) = l.\nProof.\n intros l; elim l; simpl in |- *; auto.\n intros a l' Hrec; rewrite Hrec; auto.\nQed.\n\nTheorem permutation_app :\n forall l1 l2:list A, permutation (l1 ++ l2) (l2 ++ l1).\nProof.\n intros l1; elim l1; simpl in |- *.\n intros l2; rewrite <- app_nil_end.\n apply permutation_reflexive.\n intros a tl Hrec l2.\n apply permutation_transitive with (a :: l2 ++ tl).\n apply permutation_same_head.\n apply Hrec.\n apply permutation_symetric.\n apply permutation_app_cons.\nQed.\n\nTheorem permutation_long_head :\n forall l1 l2 l3:list A,\n   permutation l2 l3 -> permutation (l1 ++ l2) (l1 ++ l3).\nProof.\n intros l1; elim l1; simpl in |- *; auto.\n intros a l1' Hrec l2 l3 H.\n constructor.\n auto.\nQed.\n\nTheorem permutation_app4 :\n forall l1 l2 l3 l4:list A,\n   permutation l1 l2 ->\n   permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nProof.\n intros l1 l2 l3 l4 H H0.\n apply permutation_transitive with (l1 ++ l4).\n apply permutation_long_head; assumption.\n apply permutation_transitive with (l4 ++ l1).\n apply permutation_app.\n apply permutation_transitive with (l4 ++ l2).\n apply permutation_long_head; assumption.\n apply permutation_app.\nQed.\n\nTheorem sort_aux1_permutation :\n forall l:list (list A), permutation (app_all (sort_aux1 l)) (app_all l).\nProof.\n intros l; elim l using list_ind2.\n simpl in |- *; constructor.\n simpl in |- *; intros; apply permutation_reflexive.\n intros l1 l2 tl Hrec; simpl in |- *.\n rewrite ass_app.\n apply permutation_app4.\n apply merge_permutation.\n auto.\nQed.\n\nTheorem sort_aux2_permutation :\n forall (b:nat) (l:list (list A)),\n   length l <= b -> permutation (sort_aux2 l b) (app_all l).\nProof.\n intros b; elim b; simpl in |- *; auto.\n intros l; case l; simpl in |- *; try constructor.\n intros l' tl H; inversion H.\n intros b' Hrec l; case l.\n simpl in |- *; intros; constructor.\n intros l1 tl; case tl.\n simpl in |- *; intros; \n   rewrite <- app_nil_end; apply permutation_reflexive.\n intros l2 tl' Hle;\n apply permutation_transitive with \n    (app_all (sort_aux1 (l1 :: l2 :: tl'))).\n apply Hrec.\n simpl in Hle.\n generalize (sort_aux1_shorter tl').\n simpl in |- *; intros Hle'; omega.\n apply sort_aux1_permutation.\nQed.\n\nTheorem sort_permutation : forall l:list A, permutation (sort l) l.\nProof.\n unfold sort in |- *; intros l; rewrite <- mk_singletons_length.\n pattern l at 3 in |- *; rewrite <- app_all_mk_singletons_eq.\n apply sort_aux2_permutation.\n auto.\nQed.\n\n(* A nice complement to the exercise would be to define another merge-sorting\n  function, but this time using well-founded induction, and yet another\n  step would be to use an ad-hoc domain predicate. *)\n\nEnd merge_sort_basics.\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/merge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7943644129576556}}
{"text": "(*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\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\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\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\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).\n\n\n\n", "meta": {"author": "victorz3", "repo": "Tarea4VF", "sha": "0ea4d50086df1024e3002a581902dc60733c2c6b", "save_path": "github-repos/coq/victorz3-Tarea4VF", "path": "github-repos/coq/victorz3-Tarea4VF/Tarea4VF-0ea4d50086df1024e3002a581902dc60733c2c6b/Defs_BN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191284552528, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7940068501037978}}
{"text": "(* Lecture 8, CIS 670, Fall 2012 *)\n\nRequire Import List.\n\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(** * Introducing Subset Types *)\n\n(* Note about the exercises:\n\nFor all of the versions of pred, to get some hands on practice,\ntry to implement a safe head function (for plain coq lists).\n\nI've pointed out a few versions of pred which I think are good\nto do this exercise on, but feel free to skip or add exercises\nas you see fit. \n\nSome hints: if you want to do this for polymorphic lists (and why not?),\nthe type of the list elements should be in Set, not Type (try it).\n\nDepending on how you set up the postcondition, you may need to add [eauto]\ninstead of just using [crush].\n*)\n\n(* Suppose we want to write a safe predecessor function. *)\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\n(* Exercise (Optional): Do the same for head. It should have type\n\nhead_strong1 (A : type) (l : list A) : (length l) > 0 -> nat\n*)\n\nLemma egtz {A : Set} : length (nil : list A) > 0 -> False.\n  crush.\nQed.\n\nDefinition head_strong1 (A : Set) (l : list A) : length l > 0 -> A :=\n  match l with\n  | nil => fun pf : length nil > 0 => match egtz pf with end\n  | cons h t => fun _ => h\n  end.\n\nTheorem two_gt0 : 2 > 0.\n  crush.\nQed.\n\nEval compute in pred_strong1 two_gt0.\n\n(* We can do this with less ad-hoc types, using the [sig] type. *)\nPrint sig.\n\n(* This type is similar to the existential type [ex], except that it\nlives in [Set] instead of [Prop].\n\nThe main difference: we can project the witness out of a value of type\n[sig], while we can't for a value of type [ex]. *)\n\n(* Exercise (10 min.)\nWrite a function that takes a value of type sig, and returns\nthe witness value.\n\nTry to write the same function for ex. What goes wrong?\n*)\n\nPrint sig.\nDefinition myproj1_sig (A : Type) (P : A -> Prop) (s : sig P) : A :=\n  match s with\n  | exist x _ => x\n  end.\n\nPrint ex.\n(*\nDefinition myproj1_ex (A : Type) (P : A -> Prop) (s : ex P) : A :=\n  match s with\n  | ex_intro x _ => x\n  end.\n\nError:\nIncorrect elimination of \"s\" in the inductive type \"ex\":\nthe return type has sort \"Type\" while it should be \"Prop\".\nElimination of an inductive object of sort Prop\nis not allowed on a predicate in sort Type\nbecause proofs can be eliminated only to build proofs.\n*)\n\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\nEval compute in pred_strong2 (exist _ 2 two_gt0).\n\n(* We can guarantee the output is correct, as well *)\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\nEval compute in pred_strong3 (exist _ 2 two_gt0).\n\n(* Exercise (Optional): Do the same thing for head. *)\nPrint ex.\nDefinition head_strong3 {A : Set} (s : {l : list A | length l > 0})\n    : {h : A | ex (fun t => cons h t = proj1_sig s)} :=\n  match s with\n  | exist nil pf => match egtz pf with end\n  | exist (cons h t) _ => exist _ h (ex_intro _ t (eq_refl (cons h t)))\n  end.\n\n(* We have managed to reach a type that is, in a formal sense, the most\nexpressive possible for [pred].  Any other implementation of the same\ntype must have the same input-output behavior.  However, there is\nstill room for improvement in making this kind of code easier to\nwrite. Since we are explicitly passing around proofs in our functions,\nit can get tedious to construct proof terms by hand everywhere.\n\nA different approach: we write the skeleton of the function, then use\ntactics to fill in the missing proofs. This uses the [refine] tactic,\nwhich generates subgoals for missing proofs. *)\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); crush.\nDefined.\n\n(* Exercise: Do the same thing for head. *)\n\nDefinition head_strong4 {A : Set} : forall l : list A, length l > 0 ->\n    {h : A | ex (fun t => cons h t = l)}.\n  refine (fun l =>\n    match l with\n    | nil => fun _ => False_rec _ _\n    | h :: t => fun _ => exist _ h _\n    end\n  ); crush; eauto.\nDefined.\nPrint head_strong4. Extraction head_strong4.\n(* We end the \"proof\" with [Defined] instead of [Qed]. Proofs marked\nQed can't be unfolded, while proofs marked with Defined can be. *)\n\nPrint pred_strong4.\n\nEval compute in pred_strong4 two_gt0.\n\n(* Now, some syntax to make things more readable... *)\n\n(* Read: Contradicted hypothesis. *)\nNotation \"!\" := (False_rec _ _).\n\n(* Read: Produced a value e, along with a proof that proposition\nholds of e. *)\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\n(* Exercise (30 min.)\n\nUse this safe predecessor function to define a safe \"minus 2\" function,\nwith type\n\npred2_strong : forall (n : nat), n > 1 -> {m : nat | n = S (S m)}\n\n*)\nSearch (_ > _ -> _ > _ -> _).\nRequire Import Arith.\nSearch (_ > O). Search (_ > _ -> _ > _). Check gt_S_n.\nDefinition pred2_strong : forall n, n > 1 -> {m : nat | n = S (S m)}.\n  refine (fun n p =>\n    match pred_strong5 (gt_trans n 1 O p (gt_Sn_O O)) with\n    | exist n' e' =>\n        match pred_strong5 (gt_S_n O n' _) with\n        | exist n'' e'' => exist _ n'' _\n        end\n    end\n  ); crush.\nDefined.\n\nDefinition pred2_strong' : forall n : nat, n > 1 -> {m : nat | n = S (S m)}.\n  refine (fun n =>\n    match n with\n    | O => fun _ => !\n    | S O => fun _ => !\n    | S (S n') => fun _ => [n']\n    end\n  ); crush.\nDefined.\n\nExtraction pred2_strong.\nExtraction pred2_strong'.\n\n(* Exercise (Optional)\n\nThough defining functions that offer correctness guarantees is\nrequires a little more upfront work, they often compose better than\nmore weakly typed functions. For example, suppose we start with our\noriginal predecessor function:\n\npred_strong1 : forall (n : nat), (n > 0) -> nat.\n\nTry to use pred_strong1 to define a function\n\npred2_partial : forall (n : nat), (n > 1) -> nat.\n\n*)\n\nHint Unfold pred_strong1.\nDefinition pred2_partial : forall n : nat, n > 1 -> nat. Print gt_trans.\n  refine (fun n p =>\n    pred_strong1 (_ : pred_strong1 (gt_trans n 1 O p (gt_Sn_O O)) > 0)\n  ); unfold pred_strong1; destruct n; crush. Qed.\n\n\n(*\n  One other alternative is worth demonstrating.  Recent Coq versions\n  include a facility called [Program] that\n  streamlines this style of definition.  Here is a complete\n  implementation using [Program].\n*)\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\nPrint pred_strong6.\n\n(* [Program] and [refine] generate similar programs in this case.\nIn general, [refine] gives more control over the shape of the program. *)\n\nEval compute in pred_strong6 two_gt0.\n\n(** * Detour: Decidable Proposition Types *)\n\n(* There is another type in the standard library which captures the\nidea of program values that indicate which of two propositions is\ntrue. *)\n\nPrint sumbool.\n\n(* Convention: the left constructor corresponds to success, while\nthe right constructor corresponds to failure. *)\n\n(* Read: Found a witness of success, and a proof. *)\nNotation \"'Yes'\" := (left _ _).\n\n(* Read: Found a witness of failure, and a proof. *)\nNotation \"'No'\" := (right _ _).\n\n(* Read: If x succeeds, then take the proof of success and\nconvert to a proof of success for the entire expression.\nSame if x fails. *)\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n\n(* Note that the [if] construct is overloaded: it works on a value of\nany type with two constructors, returning either the first thing, or\nthe second thing. *)\n\n(* A one example of [sumbool] is the decidable equality type,\nwhich indicates that given two values, we can come up with a proof of\nequality, or a proof of disequality. For instance, we can do this for\n[nat]. *)\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); congruence.\nDefined.\n\n(* Exercise (20 min.)\n\nWrite down the proof obligations that are generated by refine.\nThere's no need to write down every last hypothesis, just try to\nwrite informally what is to be proved, under what hypothesis.\nTry to do this without peeking.\n\nFor example, the first obligation should be:\n\nProve (0 = 0) under no hypothesis.\n---\nProve (O <> S m') under no hypothesis\nProve (S n' <> O) under no hypothesis\nProve (S n' = S m') under hyp n' = m'\nProve (S n' <> S m') under hyp n' <> m'\n\n*)\n\nEval compute in eq_nat_dec 2 2.\n\nEval compute in eq_nat_dec 2 3.\n\n(* Exercise (Optional)\n\nWrite a decidable equality for lists of natural numbers.\n\n*)\nPrint list_eq_dec.\n\nSearch ( _ -> _ :: _  = _ :: _).\n\nLemma eq_h_t : forall h1 h2 : nat, h1 = h2\n    -> forall t1 t2 : list nat, t1 = t2 ->\n    h1 :: t1 = h2 :: t2.\nProof.\n  crush.\nQed.\n\nDefinition eq_list_nat_dec : forall l1 l2 : list nat, {l1 = l2} + {l1 <> l2}.\n  induction l1, l2.\n    auto 3.\n    refine (right _); discriminate.\n    refine (right _); discriminate.\n    destruct (IHl1 l2), (eq_nat_dec a n).\n      refine (left _); rewrite e, e0; reflexivity.\n      refine (right _); crush.\n      refine (right _); crush.\n      refine (right _); crush.\nDefined.\nPrint eq_list_nat_dec.\n\nLemma head_inj : forall (h1 h2 : nat) (t1 t2 : list nat), h1 :: t1 = h2 :: t2 -> h1 = h2.\ncrush. Qed.\n\nLemma tail_inj : forall (h1 h2 : nat) (t1 t2 : list nat), h1 :: t1 = h2 :: t2 -> t1 = t2.\ncrush. Qed.\n\nDefinition eq_list_nat_dec' : forall l1 l2 : list nat, {l1 = l2} + {l1 <> l2}.\n  refine (fix f (l1 l2 : list nat) : {l1 = l2} + {l1 <> l2} :=\n    match l1, l2 return {l1 = l2} + {l1 <> l2} with\n    | nil, nil => left _ _\n    | h1 :: t1, h2 :: t2 => match Reduce (eq_nat_dec h1 h2) with\n        | left ph => match Reduce (f t1 t2) with\n            | left p1 => left (eq_h_t ph p1)\n            | right p2 => right (fun k => p2 (tail_inj k))\n            end\n        | right p3 => right (fun k => p3 (head_inj k))\n        end\n    | _, _ => No\n    end\n  ); crush.\nDefined.\n\n(* Or, we can use a tactic, [decide equality] *)\nDefinition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.\n  decide equality.\nDefined.\n\n(* We can now write a list membership function which returns a proof\nof membership, or a proof that the element is not in the list. *)\n\n(* Read: if x returns a positive result, return a positive result.\nOtherwise, evaluate y. *)\nNotation \"x || y\" := (if x then Yes else Reduce y).\n\nSection In_dec.\n  Variable A : Set.\n  Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.\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\t| nil => No\n\t| x' :: ls' => A_eq_dec x x' || f x ls'\n      end); crush.\n  Defined.\nEnd In_dec.\n\nEval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil).\nEval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil).\n\n(* Exercise (30 min.): Write a decidable equality function for\nlist A, assuming a decidable equality for A.\n\nHint: It might be good to start with some new notation...\n*)\n\nSection eq_list_dec.\n  Variable A : Set.\n\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Notation \"x && y\" := (if x then Reduce y else No).\n\n  Definition list_A_eq_dec : forall l1 l2 : list A, {l1 = l2} + {~ l1 = l2}.\n    refine (fix f (l1 l2 : list A ) : {l1 = l2} + {~ l1 = l2} :=\n      match l1, l2 with\n      | nil, nil => Yes\n      | h1 :: t1, h2 :: t2 => A_eq_dec h1 h2 && f t1 t2\n      | h :: t , _ => No\n      | _, h :: t => No\n      end\n    ); crush.\n  Qed.\n\nEnd eq_list_dec.\n\n(** * Partial Subset Types *)\n\n(* Up to this point, our types guarantee that on valid input, the output\nof our function is correct. What if we want our functions to handle bad\ninput, say by producing a proof that the input is bad? *)\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\nfor subset types. *)\n\n(* Read: there is maybe an element x that satisfies P. *)\nNotation \"{{ x | P }}\" := (maybe (fun x => P)).\n\n(* Read: we failed to find an x, for some reason. *)\nNotation \"??\" := (Unknown _).\n\n(* Read: we found an x, and here is the proof that P x is\nis satisfiable. *)\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\n(* Exercise (Optional): Do the same for head. *)\nNotation \"[| x , y |]\" := (Found _ x y).\n\nDefinition head_strong7 {A : Set} : forall l : list A, {{ h | ex (fun t => h :: t = l)}}.\n  refine (fun l =>\n    match l with\n    | nil => ??\n    | h :: t => [| h , ex_intro _ t (eq_refl (h :: t)) |]\n    end\n  ).\nDefined.\n\nEval compute in pred_strong7 2.\n\nEval compute in pred_strong7 0.\n\n(* In the failure case, we don't provide any proof at all. The\nimplementation that always fails could be given this type. We\nwant to rule these out, and we'll use the [sumor] type, which\nis either a value, or a proof. *)\n\nPrint sumor.\n\n(* We add notations for easy use of the [sumor] constructors. *)\n\n(* Read: here is a proof of B. (Convention: proof of failure) *)\nNotation \"!!\" := (inright _ _).\n\n(* Read: we found a witness x to the proposition P, and a proof that\nP x. Note: only works when the \"value\" type in [sumor] is a subset\ntype. *)\nNotation \"[|| x ||]\" := (inleft _ [x]).\n\n(* Now, we can give a version of pred that works on all inputs,\nand is fully specified. *)\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\nEval compute in pred_strong8 2.\nEval compute in pred_strong8 0.\n\nDefinition head_strong8 {A : Set} : forall l : list A,\n    {h : A | ex (fun t => h :: t = l)} + {l = nil}.\n  refine (fun l : list A =>\n    match l return {h : A | ex (fun t => h :: t = l)} + {l = nil} with\n    | nil => inright _ _\n    | h :: t => inleft _ (exist _ h (ex_intro _ t _))\n    end\n  ); reflexivity.\nDefined.\n\n(* Composing specified functions\n\nUntil now, we have been working with just the pred function. How\ncan we compose these functions together? Plumbing around all the\nproofs is tedious, so we'll define some notation so we don't have\nto deal with this. *)\n\n(** * Monadic Notations *)\n\n(** We can treat [maybe] like a monad, like how the Maybe type in\nHaskell is interpreted as possible failure. *)\n\n(* Read: If e1 produces a witness, see if e2 produces a witness.\nIf e1 fails, fail. *)\nNotation \"x <- e1 ; e2\" := (match e1 with\n                             | Unknown => ??\n                             | Found x _ => e2\n                           end)\n(right associativity, at level 60).\n\n(* Now, say we want to use [pred] to take the predecessor of two\nvalues (at the same time!) *)\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)|]); tauto.\nDefined.\n\n(* Exercise (Optional): do the same for head. *)\nDefinition doubleHead {A B : Set} : forall (l1 : list A) (l2 : list B),\n    {{p | ex (fun t => fst p :: t = l1) /\\ ex (fun t => snd p :: t = l2)}}.\n  refine (fun l1 l2 =>\n    h1 <- head_strong7 l1;\n    h2 <- head_strong7 l2;\n    [|(h1, h2)|]\n  ); tauto.\nDefined.\n\n(** We can build a [sumor] version of the \"bind\" notation and use it\nto write a similarly straightforward version of this function. *)\n\n(* Read: If e1 produces a proof of failure, produce a proof of failure.\nIf e1 produces a witness and a proof of success, evaulate e2. *)\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)||]); tauto.\nDefined.\n\n(** * A Type-Checking Example *)\n\n(* Let's use these ideas to build a certified typechecker. First,\nour language... *)\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\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(* We build a equality type decision procedure for [type]. *)\n\nDefinition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.\n  decide equality.\nDefined.\n\n(* In the process of generating the type, our typechecker will need\nto assert that certain terms have specific types. We'll introduce\nsome notation to capture this pattern. *)\n\n(* Read: If e1 succeeds (produces a witness), then do e2. Else, fail. *)\nNotation \"e1 ;; e2\" := (if e1 then e2 else ??)\n  (right associativity, at level 60).\n\n(* With the notation we've defined and some automation, we can create\na certified typechecker that is only a little more complex than the\nuncertified typechecker. *)\n\nDefinition typeCheck : forall e : exp, {{t | hasType e t}}.\n  Hint Constructors hasType.\n\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;; (* Assert that t1 is a nat *)\n        eq_type_dec t2 TNat;; (* Assert that t2 is a nat *)\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); crush.\nDefined.\n\n(** Despite manipulating proofs, our type checker is easy to run. *)\n\nEval simpl in typeCheck (Nat 0).\n\nEval simpl in typeCheck (Plus (Nat 1) (Nat 2)).\n\nEval simpl in 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\nour type-checker only fails on ill-typed inputs.  First, we define an\nanalogue to the \"assertion\" notation. *)\n\n(* Read: Same as e1 ;; e2, except if we fail this time, we get a proof\nof failure, which we can return. *)\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\nexpression can have at most one type. *)\n\nLemma hasType_det : forall e t1,\n  hasType e t1\n  -> forall t2, hasType e t2\n    -> t1 = t2.\n  induction 1; inversion 1; crush.\nQed.\n\n(** Now we can define the type-checker.  Its type expresses that it\nonly fails on untypable expressions. *)\n\nDefinition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}.\n  Hint Constructors hasType.\n  (** We register all of the typing rules as hints. *)\n\n  Hint Resolve hasType_det.\n  (* Note that [hasType_det] has forall bound variables that don't\n     show up in the final type, and so we need [eauto] to apply it. *)\n\n  (** The implementation can be translated from our previous\n      implementation, just by switching a few notations. *)\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); clear F; crush' tt hasType; eauto.\n\n  (** We clear [F], the local name for the recursive function, to\n  avoid strange proofs that refer to recursive calls that we never\n  make. *)\n\n  (* [crush'] is similar to [crush], except that it performs inversion\n     on the types that we specify. We need [eauto] to apply [hasType_det]. *)\nDefined.\n\n(* Exercise (45 min.)\n\nAdd products to the language.\n\n*)\n\n(** The short implementation here hides just how time-saving\nautomation is.  Every use of one of the notations adds a proof\nobligation, giving us 12 in total.  Most of these obligations require\nmultiple inversions and either uses of [hasType_det] or applications\nof [hasType] rules.\n\nOur new function remains easy to test, and now have additional\ninformation in the failure case. *)\n\nEval simpl in typeCheck' (Nat 0).\n\nEval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).\n\nEval simpl in typeCheck' (Plus (Nat 1) (Bool false)).\n", "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/HW8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8902942283051332, "lm_q1q2_score": 0.7939742188121647}}
{"text": "(** * ProofObjects: Working with Explicit Evidence in Coq *)\n \nRequire Export Logic.\n\n(* ##################################################### *)\n\n(**  We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types (like [nat] or [list]) and functions\n    over these types, and for _proving_ properties of these programs,\n    using inductive propositions (like [ev] or [eq]), implication, and \n    universal quantification.  So far, we have treated these mechanisms\n    as if they were quite separate, and for many purposes this is\n    a good way to think. But we have also seen hints that Coq's programming and \n    proving facilities are closely related. For example, the\n    keyword [Inductive] is used to declare both data types and \n    propositions, and [->] is used both to describe the type of\n    functions on data and logical implication. This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are almost\n    the same thing.  In this chapter we will study how this 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 evidence, \n    which can be thought of as a data structure. If the proposition\n    is an implication like [A -> B], then its proof will be an \n    evidence _transformer_: a recipe for converting evidence for\n    A into evidence for B.  So at a fundamental level, proofs are simply\n    programs that manipulate evidence.\n*)\n(**\n    Q. If evidence is data, what are propositions themselves?\n\n    A. They are types!\n\n    Look again at the formal definition of the [beautiful] property.  *)\n\nPrint beautiful. \n(* ==>\n  Inductive beautiful : nat -> Prop :=\n      b_0 : beautiful 0\n    | b_3 : beautiful 3\n    | b_5 : beautiful 5\n    | b_sum : forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m)\n*)\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(** 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(** Now let's look again at a previous proof involving [beautiful]. *)\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. Qed.\n\n(** Just as with ordinary data values and functions, we can use the [Print]\ncommand to see the _proof object_ that results from this proof script. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful = b_sum 3 5 b_3 b_5  \n     : beautiful 8  *)\n\n(** In view of this, we might wonder whether we can write such\n    an expression ourselves. Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_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   apply (b_sum 3 5 b_3 b_5).\nQed.\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(* ##################################################### *)\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   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(**\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, 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 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 3 3 b_3 b_3). Qed.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  b_sum 3 3 b_3 b_3.\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  apply (b_sum 6 3 six_is_beautiful' b_3). Qed.\n  \n\nDefinition nine_is_beautiful' : beautiful 9 :=\n  b_sum 6 3 six_is_beautiful' b_3.\n\n\n(* ##################################################### *)\n(** ** Quantification, 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, beautiful n -> beautiful (3+n).\nProof.\n   intros n H.\n   apply b_sum.\n   apply b_3.\n   apply H.\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 : nat) => fun (H : beautiful n) =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n : nat, 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(** When we view the proposition being proved by [b_plus3] as a function type,\n    one aspect of it may seem a little unusual. The second argument's\n    type, [beautiful n], mentions the _value_ of the first argument, [n].\n    While such _dependent types_ are not commonly found in programming\n    languages, even functional ones like ML or Haskell, they can\n    be useful there too.  \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 name\n    to the type on the LHS of the arrow. *)                                           \n\n(** For example, consider this proposition: *)\n\nDefinition beautiful_plus3 : Prop := \n  forall n, forall (E : beautiful n), beautiful (n+3).\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    beautiful.  But the name [E] for this evidence is not used in the\n    rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name for it.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition beautiful_plus3' : Prop := \n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition beatiful_plus3'' : Prop :=\n  forall n, beautiful n -> beautiful (n+3). \n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n\n(** **** Exercise: 3 stars (b_times2) *)\n(** First prove this theorem using tactics. *)\nPrint beautiful.\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. Qed.\n\n(** Now write a corresponding proof object directly. *)\n\n\n\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  fun (n : nat) => fun (E : beautiful n) => \n                     b_sum n (n+0) E (b_sum n 0 E b_0).\n\n\n\n(** **** Exercise: 2 stars, optional (gorgeous_plus13_po) *) \n(** Give a proof object corresponding to the theorem [gorgeous_plus13] from Prop.v *)\n\nDefinition gorgeous_plus13_po: forall n, gorgeous n -> gorgeous (13+n):=\n  fun (n : nat) => \n    fun (E : gorgeous n) => g_plus5 (8+n) (g_plus5 (3+n) (g_plus3 n E)).\n                     \n(** It is particularly revealing to look at proof objects involving the \nlogical connectives that we defined with inductive propositions in Logic.v. *)\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(** **** Exercise: 1 star, optional (case_proof_objects) *)\n(** The [Case] tactics were commented out in the proof of\n    [and_example] to avoid cluttering the proof object.  What would\n    you guess the proof object will look like if we uncomment them?\n    Try it and see. *)\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    (* 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 easier to understand. It is still\n    a little complicated, but after performing some simple reduction\n    steps, we can see that all that is really happening is taking apart \n    a record 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        (fun H0 : Q /\\ P => H0)\n            match H with\n            | conj HP HQ => (fun (HP0 : P) (HQ0 : Q) => conj Q P HQ0 HP0) HP HQ\n            end\n      : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** After simplifying some direct application of [fun] expressions to arguments,\nwe get: *)\n\n(* ===> \n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     match H with\n     | conj HP HQ => conj Q P HQ HP\n     end \n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\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 :=\n  fun (P Q R : Prop) => \n    fun (H0 : P /\\ Q) =>\n      fun (H1 : Q /\\ R) => match H0, H1 with\n                               |conj P' _, conj _ R' => conj P R P' R'\n                           end.\n\n\n(** **** Exercise: 2 stars, advanced (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\n(*\ngorgeous__beautiful: forall n : nat, gorgeous n -> beautiful n\nbeautiful__gorgeous: forall n : nat, beautiful n -> gorgeous n\n*)\n\nPrint conj.\n\nDefinition beautiful_iff_gorgeous : forall n, beautiful n <-> gorgeous n :=\n  fun (n : nat) => \n    conj _ _ (beautiful__gorgeous n) (gorgeous__beautiful n).\n\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 : forall P Q : Prop, P \\/ Q -> Q \\/ P :=\n  fun (P Q : Prop) =>\n    fun(H : P \\/ Q) => 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(** Recall that we model an existential for a property as a pair consisting of \na witness value and a proof that the witness obeys that property. \nWe can choose to construct the proof explicitly. \n\nFor example, consider this existentially quantified proposition: *)\n\n\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\n(** **** Exercise: 2 stars (ex_beautiful_Sn) *)\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n  ex_intro nat (fun n => beautiful (S n)) 2 b_3.\n\n\n(* ##################################################### *)\n(** ** Giving Explicit Arguments to Lemmas and Hypotheses *)\n\n(** Even when we are using tactic-based proof, it can be very useful to\nunderstand the underlying functional nature of implications and quantification. \n\nFor example, it is often convenient to [apply] or [rewrite] \nusing a lemma or hypothesis with one or more quantifiers or \nassumptions already instantiated in order to direct what\nhappens.  For example: *)\n\nCheck plus_comm.\n(* ==> \n    plus_comm\n     : forall n m : nat, n + m = m + n *)\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. *) \n      (* rewrites in the first possible spot; not what we want *)\n   rewrite (plus_comm b a).  (* directs rewriting to the right spot *)\n   reflexivity.  Qed.\n\n\n(** In this case, giving just one argument would be sufficient. *)\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.  Qed.\n\n(** Arguments must be given in order, but wildcards (_)\nmay be used to skip arguments that Coq can infer.  *)\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. Qed.\n\n(** The author of a lemma can choose to declare easily inferable arguments\nto be implicit, just as with functions and constructors. \n\n  The [with] clauses we've already seen is really just a way of\n  specifying selected arguments by name rather than position:  *)\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. Qed.\n\n\n(** **** Exercise: 2 stars (trans_eq_example_redux) *)\n(** Redo the proof of the following theorem (from MoreCoq.v) using\nan [apply] of [trans_eq] but _not_ using a [with] clause. *)\n\nPrint trans_eq. \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 (list nat) [a;b] [c;d] [e;f] H H0).\n  Qed.\n\n(* ##################################################### *)\n(** ** Programming with Tactics *)\n\n(** If we can build proofs with explicit terms rather than\ntactics, you may be wondering if we can build programs using\ntactics rather than explicit terms.  Sure! *)\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\nEval compute in add1 2. \n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than with\n[:=] followed by a term.  This tells Coq to enter proof scripting mode\nto build an object of type [nat -> nat].  Also, we terminate the proof\nwith [Defined] rather than [Qed]; this makes the definition _transparent_\nso that it can be used in computation like a normally-defined function.  \n\nThis feature is mainly useful for writing functions with dependent types,\nwhich we won't explore much further in this book.\nBut it does illustrate the uniformity and orthogonality of the basic ideas in Coq. *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.793974212322444}}
{"text": "Require Import ZArith.\nRequire Import PolTac.\n\nOpen Scope Z_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  y < 0 -> x + y < x.\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 zarith.\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 + y * (y + z) = 2 * z ->\n  2 * x + y * (y + z) = (x + z) + z.\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 -> x + y + z < 2 * y.\nProof.\nintros H.\npolr H.\npols.\nauto.\npols.\nauto with zarith.\nQed.\n", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/Zex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611563610179, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7939418863305507}}
{"text": "(* Exercise coq_list_03 *)\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 let us define the length function that returns the \n   length of a given list. *)\n\nFixpoint length (l : natlist) {struct l} : nat :=\n  (***** write the body of a function here *****)\n  match l with\n  | nil => 0\n  | cons x xs => 1 + length xs\n  end.\n(* Now let us try this definition on two simple examples.\n   (Hint: usually this is a good idea to do that with newly \n   introduced definitions) *)\n\nLemma length_nil : length nil = 0.\n\nProof.\n  unfold length.\n  reflexivity.\nQed.\n\nLemma length_3 : forall a b c,\n  length (cons a (cons b (cons c nil))) = 3.\n  \nProof.\n  intros.\n  simpl.\nreflexivity.\n  \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_03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8887588052782736, "lm_q1q2_score": 0.7939366055175523}}
{"text": "From LF Require Export induction.\n\n\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\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\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. Abort.\n\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\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end. \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]. 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]. simpl. reflexivity.\nQed.\n\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)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\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\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\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match h with\n              | 0 => ([] ++ (nonzeros t))\n              | _ => ([h]  ++ (nonzeros t))\n              end\n  end.\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              | _    => h :: (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\n\nDefinition countoddmembers (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | t   => length (oddmembers t)\nend.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h1 :: t1 => match l2 with\n                | nil => l1\n                | h2 :: t2 => [h1] ++ [h2] ++ (alternate t1 t2)\n                end\nend.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n\nDefinition bag := natlist.\n\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 => S (count v t)\n              | _ =>    count v t\n              end\nend.\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. 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. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match (count v s) with \n  | O => false\n  | _ => true\nend.\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n\nDefinition nlist2bag (n:natlist) : bag :=\n  n.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil    => []\n  | h :: t => match (eqb v h) with \n              | true => t \n              | _ => h :: (remove_one v t)\n              end\nend.\n\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\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil    => []\n  | h :: t => match (eqb v h) with \n              | true => remove_all v t\n              | _ => h :: (remove_all v t)\n              end\nend.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h :: t => match (member h s2) with \n              | true => subset t (remove_one h s2)\n              | _ => false\n              end\nend.\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\nTheorem eqb_nn : forall n:nat,\n  eqb n n = true.\nProof.\n intros n. induction n. reflexivity.  simpl. rewrite IHn. reflexivity.\nQed.\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 (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  -\n    reflexivity.\n  -\n    reflexivity. Qed.\n\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\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 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  -\n    reflexivity.\n  -\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  -\n    reflexivity.\n  -\n    simpl. rewrite -> app_length. rewrite -> plus_comm.\n    simpl. rewrite -> IHl'. reflexivity. Qed.\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.\n  - 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. induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. simpl. rewrite -> IHl.\n    reflexivity.\nQed.\n\nTheorem app_nat : forall (n : nat) (l : natlist),\n  n :: l = [n] ++ l.\nProof.\n  intros n l. 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.  rewrite app_assoc, 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. Search app. induction l1 as [ | n l' IHl].\n  - reflexivity. \n  - destruct n as [| n'].\n    + simpl. rewrite IHl. reflexivity.\n    + simpl. rewrite IHl. reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1 with \n  | nil => match l2 with \n           | nil => true\n           | _   => false\n           end\n  | h :: t => match l2 with\n              | h1 :: t1 => match (eqb h h1) with \n                            | true => eqblist t t1\n                            | false => false\n                            end\n              | _ => false\n              end\nend.\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  intros l. induction l.\n  - reflexivity.\n  -  simpl. rewrite IHl. \n     induction n.\n     + reflexivity.\n     + rewrite <- eq_succ. rewrite <- IHn. reflexivity.\nQed.\n\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\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1  (count 1 (1 :: s)) = true.\nProof.\n  intros s. reflexivity.\nQed.\n\nTheorem leb_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  -\n    simpl. reflexivity.\n  -\n    simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem remove_does_not_increase_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros s. induction s.\n  - reflexivity.\n  - destruct n.\n    + simpl. rewrite leb_n_Sn. reflexivity.\n    + simpl. rewrite IHs. reflexivity.\nQed.\n\nTheorem rev_unit : forall (l1 l2 : natlist), \n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H. rewrite <- rev_involutive. rewrite <- H. rewrite rev_involutive.\n  reflexivity.\nQed.\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match eqb 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\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if eqb n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\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\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. induction l.\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\n\nNotation \"x == y\" := (eqb x y) \n                         (at level 70) : nat_scope.\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  intros x. induction x.\n  simpl. rewrite eqb_nn. 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 :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros d x v. simpl. rewrite <- eqb_id_refl.\n  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 H. simpl. rewrite -> H. reflexivity.\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/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8933094003735664, "lm_q1q2_score": 0.7939365954198618}}
{"text": "Require Export D.\n\n(********** Discussion and Variations **********)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n| el_nil: ev_list []\n| el_cc : forall x y l, ev_list l -> ev_list (x::y::l)\n.\n\nLemma ev_list__ev_length: forall X (l:list X),\n  ev_list l -> ev (length l).\nProof. intros. induction H.\n  Case \"el_nil\". simpl. apply ev_0.\n  Case \"el_cc\". simpl. apply ev_SS. apply IHev_list.\nQed.\n \nLemma ev_length__ev_list: forall X n,\n  ev n -> forall (l:list X), n = length l -> ev_list l.\nProof. intros X n H. induction H. \n  Case \"ev_0\". destruct l.\n    SCase \"[]\". intros. apply el_nil. \n    SCase \"x::l\". intros. inversion H.\n  Case \"ev_SS\". intros. destruct l.\n    SCase \"[]\". apply el_nil. destruct l.\n    SCase \"[x]\". inversion H0. \n    SCase \"x::x0::l\". inversion H0. apply IHev in H2. apply el_cc. apply H2.\nQed.\n\nInductive pal {X:Type} : list X -> Prop :=\n| pal_nil: pal []\n| pal_sgl: forall (x:X), pal [x]\n| pal_rcs: forall (x:X) (l:list X), pal l -> pal (x::(snoc l x)).\n\nTheorem pal_app_rev : forall (X:Type) (l:list X), pal (l ++ (rev l)).\nProof.\n  intros. induction l.\n  Case \"[]\". simpl. apply pal_nil.\n  Case \"x::l\". simpl. replace (x :: l ++ snoc (rev l) x) with (x :: snoc (l ++ rev l) x). apply pal_rcs. apply IHl.\n    Lemma snoc_app_lem : forall (X:Type) (x:X) l1 l2, snoc (l1 ++ l2) x = l1 ++ snoc l2 x.\n    Proof. intros. induction l1. reflexivity.\n    simpl. rewrite IHl1. reflexivity. Qed.\n  rewrite snoc_app_lem with (l2:=(rev l)). reflexivity.\nQed.\n\nTheorem pal_rev : forall (X:Type) (l:list X), pal l -> l = rev l.\nProof. intros. induction H.\n  Case \"[]\". reflexivity.\n  Case \"[x]\". reflexivity.\n  Case \"x::l\". simpl.\n    Lemma x_snoc_lem : forall (X:Type) (x y:X) l,\n      x :: snoc l y = snoc (x::l) y.\n    Proof. intros. simpl. reflexivity. Qed.\n    rewrite x_snoc_lem.\n    Lemma snoc_rev_lem : forall (X:Type) (x:X) l,\n       x :: (rev l)  = rev (snoc l x).\n    Proof. intros.  induction l.\n      Case \"[]\". simpl. reflexivity.\n      Case \"x0::l\". simpl. rewrite<-IHl. simpl. reflexivity. Qed.\n    assert (Hrev : x::l = x::(rev l)).\n    Proof.  rewrite<-IHpal. reflexivity.\n    rewrite -> Hrev. rewrite->snoc_rev_lem. reflexivity.\nQed.\n\nPrint le.\n\n\nDefinition lt (n m:nat) := le (S n) m.\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n*n).\n\n\nTheorem sq_3_9 : square_of 3 9.\nProof.\n  apply sq. Qed.\n\nInductive next_nat : nat -> nat -> Prop :=\n  nxt : forall n, next_nat n (S n).\nTheorem next_2_3 : next_nat 2 3.\nProof. apply nxt. Qed.\n\nPrint ev.\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\nLemma le_trans : forall m n o,\n  m <= n -> n <= o -> m <= o.\nProof. intros m n o Hmn Hno. induction Hno as [|n o]. \n  Case \"le_n\". apply Hmn.\n  Case \"le_S\". apply le_S. apply IHHno. assumption. Qed.\n\nTheorem test_le3:  2<=1 -> 2+2=5.\nProof. intro H. inversion H. inversion H2. Qed.\n\nTheorem O_le_n : forall n, 0<=n.\nProof. intros. induction n as [|n']. apply le_n. apply le_S. assumption. Qed.\n\n\n(*********************************************************)\nPrint le.\nTheorem n_le_m__Sn_le_Sm: forall n m, S n <= S m -> n <= m.\nProof. intros. inversion H. apply le_n. apply le_trans with (m:=n) (n:=S n) (o:=m). apply le_S. apply le_n. apply H2.  \nQed.\n\nTheorem Sn_le_Sm__n_le_m: forall n m, n <= m -> S n <= S m.\nProof. intros. induction H. apply le_n. apply le_S. apply IHle. Qed.\n(*********************************************************)\n\nLemma n_plus_O__n: forall n, n+0=n.\nProof. intros. induction n. reflexivity. simpl. rewrite->IHn. reflexivity. Qed.\n\nLemma a_Sb__S_a_b : forall a b, a + S b= S (a+b).\nProof. intros. induction a. reflexivity. simpl. rewrite IHa. reflexivity. Qed.\n\nLemma plus_comm: forall a b, a + b = b + a.\nProof. intros. induction a.\n  Case \"a\". simpl. symmetry. apply n_plus_O__n.\n  Case \"S a\". simpl. rewrite a_Sb__S_a_b. rewrite IHa. reflexivity. Qed.\n\nTheorem le_plus_l: forall a b, a <= a + b.\nProof. intro a. induction a.\n  Case \"O\". simpl. apply O_le_n.\n  Case \"S a\". simpl. induction b.\n    SCase \"O\". rewrite n_plus_O__n. apply le_n.\n    SCase \"S b\". replace (a + S b) with (S (a + b)). apply le_S. apply IHb. symmetry. apply a_Sb__S_a_b. Qed. \n\nTheorem plus_lt: forall n1 n2 m,\n  n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof. intros n1 n2 m. unfold \"<\". split.\n  Case \"n1\". apply le_trans with (m:=S n1) (n:= S(n1+n2)) (o:=m).\n    replace (S (n1 + n2)) with (S n1 + n2). apply le_plus_l.\n    simpl. reflexivity. apply H.\n  Case \"n2\". apply le_trans with (m:=S n2) (n:=S (n1 + n2)) (o:= m). replace (S (n1 + n2)) with (S n2 + n1). apply le_plus_l. simpl. rewrite plus_comm.  reflexivity. apply H. Qed.\n\nTheorem lt_S: forall n m, n < m -> n < S m.\nProof. intros n m. unfold \"<\". intro H. apply le_S. apply H. Qed.\n\n\nTheorem ble_nat_true: forall n m,\n  ble_nat n m = true -> n <= m.\nProof. intros. generalize dependent n. induction m.\n  Case \"O\". induction n.\n    SCase \"O\". intros. apply le_n.\n    SCase \"S n\". intros. inversion H. \n  Case \"S m\". intros. induction n.\n    SCase \"O\". apply O_le_n.\n    SCase \"S n\". inversion H. apply IHm in H1. apply Sn_le_Sm__n_le_m. assumption. Qed.\n\n\nTheorem le_ble_nat: forall n m,\n  n <= m -> ble_nat n m = true.\nProof. intro n. induction n.\n  Case \"O\". intros. induction m.\n    SCase \"O\". reflexivity. \n    SCase \"S m\". reflexivity.\n  Case \"S n\". intros. induction m.\n    SCase \"O\". inversion H.\n    SCase \"S m\". simpl. apply IHn. apply n_le_m__Sn_le_Sm.\n    assumption. Qed.\n\nTheorem ble_nat_true_trans: forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof. intros. apply ble_nat_true in H. apply ble_nat_true in H0.\n  apply le_ble_nat. apply le_trans with (m:=n) (n:=m). assumption. assumption. Qed.\n\nTheorem ble_nat_false: forall n m,\n  ble_nat n m = false -> ~(n<=m).\nProof. intros. unfold not. intro Hnm. apply le_ble_nat in Hnm. rewrite H in Hnm. inversion Hnm. Qed.\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\nTheorem R112 : R 1 1 2.\nProof. apply c2. apply c3. apply c1. Qed.\n\n(***************************************************)\nTheorem R_mno :forall m n o,  R m n o -> m + n = o.\nProof. intros. generalize dependent n. generalize dependent m. induction o.\n  Case \"O\". intros. inversion H. reflexivity. inversion H0. inversion H7. subst. Abort.\n\nInductive RR: nat -> list nat -> Prop :=\n| Rc1: RR 0 []\n| Rc2: forall n l, RR n l -> RR (S n) (n::l)\n| Rc3: forall n l, RR (S n) l -> RR n l.\n\n  Theorem RR1210: RR 2 [1;2;1;0].\n  Proof.  apply Rc2. apply Rc3. apply Rc3. apply Rc2. apply Rc2. apply Rc2. apply Rc1. Qed.\n\n\n\n(********** Programming with Propositions **********)\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\nTheorem plus_fact_is_true : plus_fact.\nProof. reflexivity. Qed.\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\nDefinition true_for_all_numbers (P:nat -> Prop) : Prop :=\n  forall n, P n.\nDefinition preserved_by_S (P:nat -> Prop): Prop :=\n  forall (n:nat), P n -> P (S n).\n\nDefinition natural_number_induction: Prop :=\n  forall (P:nat->Prop),\n  true_for_zero P ->\n    preserved_by_S P ->\n      true_for_all_numbers P.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) :\n  nat -> Prop :=\nfun n => if oddb n then Podd n else Peven n.\n\nTheorem combbine_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. intros. unfold combine_odd_even. destruct (oddb n) eqn:Hodd. apply H. reflexivity.  apply H0. reflexivity. Qed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n      oddb n = true ->\n        Podd n.\nProof. intros. unfold combine_odd_even in H. rewrite H0 in H. assumption. 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/practice/Prop_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8947894527758053, "lm_q1q2_score": 0.7938613049064611}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreProp. \n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\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 a 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(** 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\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 (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\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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  (* 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\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\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 (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] (advanced) *)\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_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  (* FILL IN HERE *) Admitted.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\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\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(* #################################################### *)\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\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, 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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (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, 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\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     from evidence for [P]. *) \n  Abort.\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\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\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  (* FILL IN HERE *) Admitted.\n(** [] *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P]. \n\n*)\n\n\n(** Coq's [Notation] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2). \n  reflexivity.  Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n    time, we can use the convenient shorthand [exists e], which means\n    the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\n\n(** 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(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\" *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* Print dist_exists_or. *)\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has (roughly)\n    the following inductive definition. *)\n\n(* (We enclose the definition in a module to avoid confusion with the\n    standard library equality, which we have used extensively\n    already.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n  refl_equal : forall x, eq x x.\n(** Standard infix notation: *)\n\nNotation \"x = y\" := (eq x y) \n                    (at level 70, no associativity) \n                    : type_scope.\n\n(** The definition of [=] is a bit subtle.  The way to think about it\n    is that, given a set [X], it defines a _family_ of propositions\n    \"[x] is equal to [y],\" indexed by pairs of values ([x] and [y])\n    from [X].  There is just one way of constructing evidence for\n    members of this family: applying the constructor [refl_equal] to a\n    type [X] and a value [x : X] yields evidence that [x] is equal to\n    [x]. *)\n\n\n(** **** Exercise: 2 stars (leibniz_equality) *)\n(** The inductive definitions of equality corresponds to _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 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\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 compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n*)\n\nLemma four: 2 + 2 = 1 + 3. \nProof.\n  apply refl_equal. \nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\nto now is essentially just short-hand for [apply refl_equal]. *)\n\nEnd MyEquality.\n\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues.  The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests \nin _computations_.  While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious. \n\nIt turns out that we can get the benefits of both forms at once \nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B \n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" :=  (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction \nthat allows us to compute with them.) *) \n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      right. intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. intros contra. inversion contra.\n    SCase \"m = S m'\". \n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply f_equal.  apply eq.\n      right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined. \n\n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either \nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right] \nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean]. \n(Notice that we ended this proof with [Defined] rather than [Qed]. \nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n\nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 -> \n  (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f. intros Hx1.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).   (* observe what appears as a hypothesis *)\n  Case \"k1 = k2\".\n    rewrite <- e.\n    symmetry. apply Hx1.\n  Case \"k1 <> k2\". \n    reflexivity.  Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the \n   version of [override] defined using [beq_nat], where we had to\n   use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n   to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ####################################################### *)\n(** ** Inversion, Again (Advanced) *)\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(** **** Exercise: 1 star, optional (dist_and_or_eq_implies_and) *)  \nLemma dist_and_or_eq_implies_and : forall P Q R,\n       P /\\ (Q \\/ R) /\\ Q = R -> P/\\Q.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Using the property [all], write down a specification for [forallb],\n    and prove that it satisfies the specification. Try to make your \n    specification as precise as possible.\n\n    Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example, \n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l]. \n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X), \n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma app_appears_in : forall (X:Type) (xs ys : list X) (x:X), \n     appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n    which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [appears_in] to define an inductive proposition\n    [no_repeats X l], which should be provable exactly when [l] is a\n    list (with elements of type [X]) where every member is different\n    from every other.  For example, [no_repeats nat [1,2,3,4]] and\n    [no_repeats bool []] should be provable, while [no_repeats nat\n    [1,2,1]] and [no_repeats bool [true,true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but you are free\n    to change the proof if the given one doesn't work for you.\n    Your definition might be different from mine and still correct,\n    in which case the examples might need a different proof.\n   \n    The suggested proofs for the examples (in comments) use a number\n    of tactics we haven't talked about, to try to make them robust\n    with respect to different possible ways of defining [nostutter].\n    You should be able to just uncomment and use them as-is, but if\n    you prefer you can also prove each example with more basic\n    tactics.  *)\n\nExample test_nostutter_1:      nostutter [3;1;4;1;5;6].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. intro.\n  repeat match goal with \n    h: nostutter _ |- _ => inversion h; clear h; subst \n  end.\n  contradiction H1; auto. Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some \n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2. \nProof. \n  (* FILL IN HERE *) Admitted.\n\nLemma appears_in_app_split : forall (X:Type) (x:X) (l:list X),\n  appears_in x l -> \n  exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n   exercise above), such that [repeats X l] asserts that [l] contains\n   at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n   represents a list of pigeonhole labels, and list [l1] represents 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(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7937549888941726}}
{"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* Order relations                                                         *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF Require Import LibTactics LibLogic LibReflect LibOperation LibRelation.\nGeneralizable Variables A.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Preorder *)\n\n(** Definition *)\n\nRecord preorder A (R:binary A) : Prop := {\n   preorder_refl : refl R;\n   preorder_trans : trans R }.\n\nArguments preorder_trans [A] [R] [p] y [x] [z].\n\n(** Transformations *)\n\nLemma preorder_inverse : forall A (R:binary A),\n  preorder R ->\n  preorder (inverse R).\nProof using. hint trans_inverse. introv [Re Tr]. constructor~. Qed.\n\nLemma preorder_rclosure : forall A (R:binary A),\n  preorder R ->\n  preorder (rclosure R).\nProof using. hint refl_rclosure, trans_rclosure. introv [Re Tr]. constructor~. Qed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total preorder *)\n\n(** Definition of total preorder relations *)\n\nRecord total_preorder A (R:binary A) : Prop := {\n   total_preorder_trans : trans R;\n   total_preorder_total : total R }.\n\nArguments total_preorder_trans [A] [R] t y [x] [z].\n\n(** Conversion to preorder *)\n\nLemma total_preorder_refl : forall A (le:binary A),\n  total_preorder le ->\n  refl le.\nProof using. introv [Tr To]. intros x. destruct~ (To x x). Qed.\n\nHint Resolve total_preorder_refl.\n\nCoercion total_preorder_to_preorder A (R:binary A)\n  (O:total_preorder R) : preorder R.\nProof using. lets [M _]: O. constructor~. Qed.\n\nHint Resolve total_preorder_to_preorder.\n\n(** Transformations *)\n\nLemma total_preorder_inverse : forall A (R:binary A),\n  total_preorder R ->\n  total_preorder (inverse R).\nProof using. hint trans_inverse, total_inverse. introv [Tr To]. constructor~. Qed.\n\nLemma total_preorder_rclosure : forall A (R:binary A),\n  total_preorder R ->\n  total_preorder (rclosure R).\nProof using. hint trans_rclosure, total_rclosure. introv [Re Tr]. constructor~. Qed.\n\n(** Properties *)\n\nLemma inverse_of_not : forall A (R:binary A) x y,\n  total R ->\n  ~ R x y ->\n  inverse R x y.\nProof using. introv T H. destruct (T x y); auto_false~. Qed.\n\nLemma inverse_strict_of_not : forall A (R:binary A) x y,\n  total R ->\n  ~ R x y ->\n  inverse (strict R) x y.\nProof using.\n  introv T H. destruct (T x y). auto_false~.\n  hnf. split~. intro_subst~.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Order *)\n\n(** Definition *)\n\nRecord order A (R:binary A) : Prop := {\n   order_refl : refl R;\n   order_trans : trans R;\n   order_antisym : antisym R }.\n\nArguments order_trans [A] [R] [o] y [x] [z].\nArguments order_antisym [A] [R] [o] [x] [y].\n\n(** Conversion to preorder *)\n\nCoercion order_to_preorder A (R:binary A)\n  (O:order R) : preorder R.\nProof using. destruct* O. constructors*. Qed.\n\nHint Resolve order_to_preorder.\n\n(** Transformations *)\n\nLemma order_inverse : forall A (R:binary A),\n  order R ->\n  order (inverse R).\nProof using.\n  hint trans_inverse, antisym_inverse.\n  introv [Re Tr An]. constructor~.\nQed.\n\nLemma order_rclosure : forall A (R:binary A),\n  order R ->\n  order (rclosure R).\nProof using.\n  hint refl_rclosure, trans_rclosure, antisym_rclosure.\n  introv [Re Tr An]. constructor~.\nQed.\n\n(** Properties *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Order relation upto an equivalence relation *)\n\n(** Note: this is used in LibFix *)\n\nRecord order_wrt (A:Type) (E:binary A) (R:binary A) : Prop := {\n   order_wrt_refl : refl R;\n   order_wrt_trans : trans R;\n   order_wrt_antisym : antisym_wrt E R }.\n\nArguments order_wrt_trans [A] [E] [R] [o] y [x] [z].\nArguments order_wrt_antisym [A] [E] [R] [o] [x] [y].\n\n(** Conversion to preorder *)\n\nCoercion order_wrt_to_preorder A (E:binary A) (R:binary A)\n  (O:order_wrt E R) : preorder R.\nProof using. destruct* O. constructors*. Qed.\n\nHint Resolve order_wrt_to_preorder.\n\n(** Transformations *)\n\nLemma order_wrt_inverse : forall A (E:binary A) (R:binary A),\n  order_wrt E R ->\n  order_wrt E (inverse R).\nProof using.\n  hint trans_inverse, antisym_wrt_inverse.\n  introv [Re Tr An]. constructor~.\nQed.\n\nLemma order_wrt_rclosure : forall A (E:binary A) (R:binary A),\n  order_wrt E R ->\n  order_wrt (rclosure E) (rclosure R).\nProof using.\n  hint refl_rclosure, trans_rclosure, antisym_wrt_rclosure.\n  introv [Re Tr An]. constructor~.\nQed.\n\n(** Properties *)\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total Order *)\n\n(** Definition *)\n\nRecord total_order A (R:binary A) : Prop := {\n   total_order_order : order R;\n   total_order_total : total R }.\n\n(** Projections *)\n\nDefinition total_order_refl := order_refl.\nDefinition total_order_trans := order_trans.\nDefinition total_order_antisym := order_antisym.\n\nArguments total_order_trans [A] [R] [o] y [x] [z].\nArguments total_order_antisym [A] [R] [o] [x] [y].\n\n(** Construction *)\n\nLemma total_order_intro : forall A (R:binary A),\n   trans R ->\n   antisym R ->\n   total R ->\n   total_order R.\nProof using.\n  introv Tra Ant Tot. constructor~. constructor~.\n  intros_all. destruct~ (Tot x x).\nQed.\n\n(** Conversion to order *)\n\nCoercion total_order_to_total_preorder A (R:binary A)\n  (O:total_order R) : total_preorder R.\nProof using. destruct* O. constructors*. applys* order_trans. Qed.\n\nDefinition total_order_to_order := total_order_order.\n\nHint Resolve total_order_to_order total_order_to_total_preorder.\n\n(** Transformations *)\n\nLemma total_order_inverse : forall A (R:binary A),\n  total_order R ->\n  total_order (inverse R).\nProof using.\n  hint total_inverse, order_inverse.\n  introv [Or To]. constructor~.\nQed.\n\nLemma total_order_rclosure : forall A (R:binary A),\n  total_order R ->\n  total_order (rclosure R).\nProof using.\n  hint total_rclosure, order_rclosure.\n  introv [Or To]. constructor~.\nQed.\n\n(** Properties *)\n\nSection TotalOrderProp.\nVariables (A:Type) (R : binary A).\n\n(** WARNING: notations here are not typeclass operators\n    -- TODO: is this really what we want?\n    perhaps it would be clearer to inline these notations. *)\n\nNotation \"'le'\" := (R).\nNotation \"'ge'\" := (inverse R).\nNotation \"'lt'\" := (strict R).\nNotation \"'gt'\" := (inverse lt).\n\nLtac total_order_normalize :=\n  repeat rewrite rclosure_eq_fun;\n  repeat rewrite inverse_eq_fun;\n  repeat rewrite strict_eq_fun.\n\nLemma total_order_le_is_rclosure_lt : forall (To:total_order R),\n  le = rclosure lt.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_lt_is_strict_le : forall (To:total_order R),\n  lt = strict le.\nProof using.\n  auto.\nQed.\n\nLemma total_order_ge_is_rclosure_gt : forall (To:total_order R),\n  ge = rclosure gt.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_gt_is_strict_ge : forall (To:total_order R),\n  gt = strict ge.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*.\n  destruct M. autos*.\nQed.\n\nLemma total_order_lt_or_eq_or_gt : forall (To:total_order R) x y,\n  lt x y \\/ x = y \\/ gt x y.\nProof using.\n  introv H. intros. total_order_normalize. tests: (x = y).\n    branch~ 2.\n    destruct (total_order_total H x y).\n     branch~ 1.\n     branch~ 3.\nQed.\n\nLemma total_order_lt_or_ge : forall (To:total_order R) x y,\n  lt x y \\/ ge x y.\nProof using.\n  intros. branches (total_order_lt_or_eq_or_gt To x y).\n  left~.\n  right~. subst. hnf. apply~ total_order_refl.\n  right~. rewrite~ total_order_ge_is_rclosure_gt.\n   total_order_normalize. hnfs~.\nQed.\n\nLemma total_order_le_or_gt : forall (To:total_order R) x y,\n  le x y \\/ gt x y.\nProof using.\n  intros. branches~ (total_order_lt_or_eq_or_gt To x y).\n  left~. rewrite~ total_order_le_is_rclosure_lt. total_order_normalize. hnfs~.\n  left~. subst. apply~ total_order_refl.\nQed.\n\nEnd TotalOrderProp.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Strict order *)\n\n(** Definition *)\n\nRecord strict_order A (R:binary A) : Prop := {\n   strict_order_irrefl : irrefl R;\n   strict_order_asym : asym R;\n   strict_order_trans : trans R }.\n\nArguments strict_order_trans [A] [R] [s] y [x] [z].\n\n(** Transformations *)\n\nLemma strict_order_inverse : forall A (R:binary A),\n  strict_order R ->\n  strict_order (inverse R).\nProof using.\n  hint antisym_inverse, trans_inverse, asym_inverse.\n  introv [Ir As Tr]. constructor~.\nQed.\n\nLemma strict_order_strict : forall A (R:binary A),\n  order R ->\n  strict_order (strict R).\nProof using.\n  introv [Re As Tr]. unfold strict. constructor; intros_all; simpls.\n  destruct* H.\n  applys* antisym_inv x y.\n  split. applys* As. intros E. subst. applys* antisym_inv y z.\nQed.\n\nLemma order_rclosure_of_strict_order : forall A (R:binary A),\n  strict_order R ->\n  order (rclosure R).\nProof using.\n  introv [Re As Tr]. rewrite rclosure_eq_fun. constructor; simpl.\n  intros_all~.\n  introv [H1|E1] [H2|E2]; subst; auto.\n    left. apply* trans_inv.\n  introv [H1|E1] [H2|E2]; try subst; auto.\n    false. apply* As.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total strict order *)\n\n(** Definition *)\n\nRecord strict_total_order A (R:binary A) : Prop := {\n   strict_total_order_trans : trans R;\n   strict_total_order_trichotomous : trichotomous R }.\n\nArguments strict_total_order_trans [A] [R] [s] y [x] [z].\n\n(** Conversion to strict order and back *)\n\nLemma strict_total_order_irrefl : forall A (R:binary A),\n  strict_total_order R ->\n  irrefl R.\nProof using. introv [Tr Tk]. intros x. lets: (Tk x x). inverts~ H. Qed.\n\nLemma strict_total_order_asym : forall A (R:binary A),\n  strict_total_order R ->\n  asym R.\nProof using. introv [Tr Tk]. intros x y. lets: (Tk x y). inverts~ H. Qed.\n\nCoercion strict_total_order_to_strict_order A (R:binary A)\n  (O:strict_total_order R) : strict_order R.\nProof using.\n  lets [M _]: O. constructor;\n  autos~ strict_total_order_irrefl strict_total_order_asym.\nQed.\n\nHint Resolve strict_total_order_to_strict_order.\n\n(** Transformation *)\n\nLemma strict_total_order_inverse : forall A (R:binary A),\n  strict_total_order R ->\n  strict_total_order (inverse R).\nProof using.\n  introv [Tr Tk]. constructor. apply~ trans_inverse.\n  apply~ trichotomous_inverse.\nQed.\n(** From total order *)\n\nLemma strict_total_order_of_total_order : forall A (R:binary A),\n  total_order R ->\n  strict_total_order (strict R).\nProof using.\n  introv [[Re Tr As] To]. constructor.\n  apply~ trans_strict.\n  intros x y. tests: (x = y).\n    subst. apply trichotomy_eq. unfolds* strict.\n    unfold strict. destruct (To x y).\n      apply* trichotomy_left.\n      apply* trichotomy_right.\nQed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Definition of order operators *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Classes and notation for comparison operators *)\n\n(** Operators *)\n\nClass Le (A : Type) := { le : binary A }.\nClass Ge (A : Type) := { ge : binary A }.\nClass Lt (A : Type) := { lt : binary A }.\nClass Gt (A : Type) := { gt : binary A }.\n\nGlobal Opaque le lt ge gt.\n\n(** Structures *)\n\nClass Le_preorder `{Le A} : Prop :=\n  { le_preorder : preorder le }.\n\nClass Le_total_preorder `{Le A} : Prop :=\n  { le_total_preorder : total_preorder le }.\n\nClass Le_order `{Le A} : Prop :=\n  { le_order : order le }.\n\nClass Le_total_order `{Le A} : Prop :=\n  { le_total_order : total_order le }.\n\nClass Lt_strict_order `{Lt A} : Prop :=\n  { lt_strict_order : strict_order lt }.\n\nClass Lt_strict_total_order `{Lt A} : Prop :=\n  { lt_strict_total_order : strict_total_order lt }.\n\n(** Notation *)\n\nDeclare Scope comp_scope.\n\nNotation \"x <= y\" := (le x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x >= y\" := (ge x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x < y\" := (lt x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x > y\" := (gt x y)\n  (at level 70, no associativity) : comp_scope.\n\nOpen Scope comp_scope.\n\nNotation \"x <= y <= z\" := (x <= y /\\ y <= z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x <= y < z\" := (x <= y /\\ y < z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x < y <= z\" := (x < y /\\ y <= z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x < y < z\" := (x < y /\\ y < z)\n  (at level 70, y at next level) : comp_scope.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** The operators [ge], [lt] and [gt] are deduced from [le] *)\n\nInstance ge_of_le : forall `{Le A}, Ge A.\n  constructor. apply (inverse le). Defined.\nInstance lt_of_le : forall `{Le A}, Lt A.\n  constructor. apply (strict le). Defined.\nInstance gt_of_le : forall `{Le A}, Gt A.\n  constructor. apply (inverse lt). Defined.\n\nLemma ge_is_inverse_le : forall `{Le A}, ge = inverse le.\nProof using. extens*. Qed.\n\nLemma lt_is_strict_le : forall `{Le A}, lt = strict le.\nProof using. extens*. Qed.\n\nLemma gt_is_inverse_lt : forall `{Le A}, gt = inverse lt.\nProof using. extens*. Qed.\n\nLemma gt_is_inverse_strict_le : forall `{Le A}, gt = inverse (strict le).\nProof using. extens. intros. rewrite gt_is_inverse_lt. rewrite* lt_is_strict_le. Qed.\n\nGlobal Opaque ge_of_le lt_of_le gt_of_le.\n\n(** Local tactic [rew_to_le] *)\n\nHint Rewrite @gt_is_inverse_strict_le @ge_is_inverse_le @lt_is_strict_le : rew_to_le.\n\nTactic Notation \"rew_to_le\" :=\n  autorewrite with rew_to_le in *.\n\nHint Rewrite @ge_is_inverse_le @gt_is_inverse_lt : rew_to_le_lt.\n\nTactic Notation \"rew_to_le_lt\" :=\n  autorewrite with rew_to_le_lt in *.\n\nLemma gt_is_strict_inverse_le : forall `{Le A},\n  gt = strict (inverse le).\nProof using. intros. rew_to_le. apply inverse_strict. Qed.\n\nLemma le_is_rclosure_lt : forall `{Le A},\n  refl le ->\n  le = rclosure lt.\nProof using. intros. rew_to_le. rewrite~ rclosure_strict. Qed.\n\nLemma le_is_inverse_ge : forall `{Le A},\n  le = inverse ge.\nProof using. intros. rew_to_le. rewrite~ inverse_inverse. Qed.\n\nLemma lt_is_inverse_gt : forall `{Le A},\n  lt = inverse gt.\nProof using. intros. rew_to_le. rewrite~ inverse_inverse. Qed.\n\nLemma gt_is_strict_ge : forall `{Le A},\n  gt = strict ge.\nProof using. intros. rew_to_le. apply inverse_strict. Qed.\n\nLemma ge_is_rclosure_gt : forall `{Le A},\n  refl le ->\n  ge = rclosure gt.\nProof using. intros. rewrite gt_is_strict_ge. rewrite~ rclosure_strict. Qed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Classes for comparison properties *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Definition of classes *)\n\n(** symmetric structure *)\n\nClass Ge_preorder `{Le A} : Prop :=\n  { ge_preorder : preorder ge }.\nClass Ge_total_preorder `{Le A} : Prop :=\n  { ge_total_preorder : total_preorder ge }.\nClass Ge_order `{Le A} : Prop :=\n  { ge_order : order ge }.\nClass Ge_total_order `{Le A} : Prop :=\n  { ge_total_order : total_order le }.\nClass Gt_strict_order `{Le A} : Prop :=\n  { gt_strict_order : strict_order gt }.\nClass Gt_strict_total_order `{Le A} : Prop :=\n  { gt_strict_total_order : strict_total_order gt }.\n\n(** properties of le *)\n\nClass Le_refl `{Le A} :=\n  { le_refl : refl le }.\nClass Le_trans `{Le A} :=\n  { le_trans : trans le }.\nClass Le_antisym `{Le A} :=\n  { le_antisym : antisym le }.\nClass Le_total `{Le A} :=\n  { le_total : total le }.\n\n(** properties of ge *)\n\nClass Ge_refl `{Ge A} :=\n  { ge_refl : refl ge }.\nClass Ge_trans `{Ge A} :=\n  { ge_trans : trans ge }.\nClass Ge_antisym `{Ge A} :=\n  { ge_antisym : antisym ge }.\nClass Ge_total `{Ge A} :=\n  { ge_total : total ge }.\n\n(** properties of lt *)\n\nClass Lt_irrefl `{Lt A} :=\n  { lt_irrefl : irrefl lt }.\nClass Lt_trans `{Lt A} :=\n  { lt_trans : trans lt }.\n\n(** properties of gt *)\n\nClass Gt_irrefl `{Gt A} :=\n  { gt_irrefl : irrefl gt }.\nClass Gt_trans `{Gt A} :=\n  { gt_trans : trans gt }.\n\n(** mixed transitivity results *)\n\nClass Lt_le_trans `{Le A} :=\n  { lt_le_trans : forall y x z, x < y -> y <= z -> x < z }.\nClass Le_lt_trans `{Le A} :=\n  { le_lt_trans : forall y x z, x <= y -> y < z -> x < z }.\nClass Gt_ge_trans `{Le A} :=\n  { gt_ge_trans : forall y x z, x > y -> y >= z -> x > z }.\nClass Ge_gt_trans `{Le A} :=\n  { ge_gt_trans : forall y x z, x >= y -> y > z -> x > z }.\n\nArguments lt_irrefl [A] [H] [Lt_irrefl].\nArguments le_trans {A} {H} {Le_trans} y [x] [z].\nArguments ge_trans {A} {H} {Ge_trans} y [x] [z].\nArguments lt_trans {A} {H} {Lt_trans} y [x] [z].\nArguments gt_trans {A} {H} {Gt_trans} y [x] [z].\n\n(** conversion between operators *)\n\nClass Ge_as_sle `{Le A} : Prop :=\n  { ge_as_sle : forall x y : A, (x >= y) = (y <= x) }.\n\nClass Gt_as_slt `{Le A} : Prop :=\n  { gt_as_slt : forall x y : A, (x > y) = (y < x) }.\n\nClass Ngt_as_sle `{Le A} : Prop :=\n  { ngt_as_sle : forall x y : A, (~ x < y) = (y <= x) }.\n\nClass Nlt_as_ge `{Le A} : Prop :=\n  { nlt_as_ge : forall x y : A, (~ x < y) = (x >= y) }.\n\nClass Ngt_as_le `{Le A} : Prop :=\n  { ngt_as_le : forall x y : A, (~ x > y) = (x <= y) }.\n\nClass Nle_as_gt `{Le A} : Prop :=\n  { nle_as_gt : forall x y : A, (~ x <= y) = (x > y) }.\n\nClass Nge_as_lt `{Le A} : Prop :=\n  { nge_as_lt : forall x y : A, (~ x >= y) = (x < y) }.\n\n(** inclusion between operators *)\n\nClass Lt_to_le `{Le A} : Prop :=\n  { lt_to_le : forall x y : A, (x < y) -> (x <= y) }.\n\nClass Gt_to_ge `{Le A} : Prop :=\n  { gt_to_ge : forall x y : A, (x > y) -> (x >= y) }.\n\nClass Nle_to_sle `{Le A} : Prop :=\n  { nle_to_sle : forall x y : A, (~ x <= y) -> (y <= x) }.\n\nClass Nle_to_slt `{Le A} : Prop :=\n  { nle_to_slt : forall x y : A, (~ x <= y) -> (y < x) }.\n\n(** case analysis *)\n\nClass Case_eq_lt_gt `{Le A} : Prop :=\n  { case_eq_lt_gt : forall x y : A, x = y \\/ x < y \\/ x > y }.\n\nClass Case_eq_lt_slt `{Le A} : Prop :=\n  { case_eq_lt_slt : forall x y : A, x = y \\/ x < y \\/ y < x }.\n\nClass Case_le_gt `{Le A} : Prop :=\n  { case_le_gt : forall x y : A, x <= y \\/ x > y }.\n\nClass Case_le_slt `{Le A} : Prop :=\n  { case_le_slt : forall x y : A, x <= y \\/ y < x }.\n\nClass Case_lt_ge `{Le A} : Prop :=\n  { case_lt_ge : forall x y : A, x < y \\/ x >= y }.\n\nClass Case_lt_sle `{Le A} : Prop :=\n  { case_lt_sle : forall x y : A, x < y \\/ y <= x }.\n\n(** case analysis under one assumption *)\n\nClass Neq_case_lt_gt `{Le A} : Prop :=\n  { neq_case_lt_gt : forall x y : A, x <> y -> x < y \\/ x > y }.\n\nClass Neq_case_lt_slt `{Le A} : Prop :=\n  { neq_case_lt_slt : forall x y : A, x <> y -> x < y \\/ y < x }.\n\nClass Le_case_eq_lt `{Le A} : Prop :=\n  { le_case_eq_lt : forall x y : A, x <= y -> x = y \\/ x < y }.\n\nClass Ge_case_eq_gt `{Le A} : Prop :=\n  { ge_case_eq_gt : forall x y : A, x >= y -> x = y \\/ x > y }.\n\n(** case analysis under two assumptions *)\n\nClass Le_neq_to_lt `{Le A} : Prop :=\n  { le_neq_to_lt : forall x y : A, x <= y -> x <> y -> x < y }.\n\nClass Ge_neq_to_gt `{Le A} : Prop :=\n  { ge_neq_to_gt : forall x y : A, x >= y -> x <> y -> x > y }.\n\nClass Nlt_nslt_to_eq `{Le A} : Prop :=\n  { nlt_nslt_to_eq : forall x y : A, ~ (lt x y) -> ~ (lt y x) -> x = y }.\n\n(** contradiction from case analysis *)\n\nClass Lt_ge_false `{Le A} : Prop :=\n  { lt_ge_false : forall x y : A, x < y -> x >= y -> False }.\n\nClass Lt_gt_false `{Le A} : Prop :=\n  { lt_gt_false : forall x y : A, x < y -> x > y -> False }.\n\nClass Lt_slt_false `{Le A} : Prop :=\n  { lt_slt_false : forall x y : A, x < y -> y < x -> False }.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Instances for comparison structures *)\n\nSection Instances.\nContext `{Le A}.\n\nLtac auto_star ::= try solve [ dauto ].\n\n(** derived structures *)\n\nGlobal Instance Le_preorder_of_Le_order :\n  Le_order ->\n  Le_preorder.\nProof using. constructor. intros. apply* order_to_preorder. Qed.\n\nGlobal Instance Le_total_preorder_of_Le_total_order :\n  Le_total_order ->\n  Le_total_preorder.\nProof using. constructor. intros. apply* total_order_to_total_preorder. Qed.\n\nGlobal Instance Le_preorder_of_Total_preorder :\n  Le_total_preorder ->\n  Le_preorder.\nProof using. constructor. intros. apply* total_preorder_to_preorder. Qed.\n\nGlobal Instance Le_order_of_Le_total_order :\n  Le_total_order ->\n  Le_order.\nProof using. constructor. intros. apply* total_order_to_order. Qed.\n\nGlobal Instance lt_strict_order_of_lt_strict_total_order :\n  Lt_strict_total_order ->\n  Lt_strict_order.\nProof using. constructor. intros. apply* strict_total_order_to_strict_order. Qed.\n\nGlobal Instance Lt_strict_order_of_Le_order :\n  Le_order ->\n  Lt_strict_order.\nProof using. constructor. intros. rew_to_le. apply* strict_order_strict. Qed.\n\nGlobal Instance Lt_strict_total_order_of_Le_total_order :\n  Le_total_order ->\n  Lt_strict_total_order.\nProof using. constructor. intros. rew_to_le. apply* strict_total_order_of_total_order. Qed.\n\n(** symmetric structures *)\n\nGlobal Instance Ge_preorder_of_Le_order :\n  Le_order ->\n  Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_inverse. apply le_preorder. Qed.\n\nGlobal Instance Ge_total_preorder_of_Le_total_order :\n  Le_total_order ->\n  Ge_total_preorder.\nProof using. constructor. rew_to_le. apply total_preorder_inverse. apply le_total_preorder. Qed.\n\nGlobal Instance Ge_preorder_of_Total_preorder :\n  Le_total_preorder ->\n  Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_inverse. apply le_preorder. Qed.\n\nGlobal Instance Ge_order_of_Le_total_order :\n  Le_total_order ->\n  Ge_order.\nProof using. constructor. rew_to_le. apply order_inverse. apply le_order. Qed.\n\nGlobal Instance Gt_strict_order_of_lt_strict_total_order :\n  Lt_strict_total_order ->\n  Gt_strict_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_order_inverse. apply lt_strict_order. Qed.\n\nGlobal Instance Gt_strict_order_of_Le_order :\n  Le_order ->\n  Gt_strict_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_order_inverse. apply lt_strict_order. Qed.\n\nGlobal Instance Gt_strict_total_order_of_Le_total_order :\n  Le_total_order ->\n  Gt_strict_total_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_total_order_inverse. apply lt_strict_total_order. Qed.\n\n(** properties of le *)\n\nGlobal Instance Le_refl_of_Le_preorder :\n  Le_preorder ->\n  Le_refl.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance Le_trans_of_Le_preorder :\n  Le_preorder ->\n  Le_trans.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance Le_antisym_of_Le_order :\n  Le_order ->\n  Le_antisym.\nProof using. constructor. intros. apply* order_antisym. Qed.\n\nGlobal Instance Le_total_of_Le_total_order :\n  Le_total_order ->\n  Le_total.\nProof using. constructor. intros. apply* total_order_total. Qed.\n\n(** properties of ge *)\n\nGlobal Instance Ge_refl_of_Le_preorder :\n  Le_preorder ->\n  Ge_refl.\nProof using. constructor. rew_to_le. apply refl_inverse. apply le_refl. Qed.\n\nGlobal Instance Ge_trans_of_Le_preorder :\n  Le_preorder ->\n  Ge_trans.\nProof using. constructor. rew_to_le. apply trans_inverse. apply le_trans. Qed.\n\nGlobal Instance Ge_antisym_of_Le_order :\n  Le_order ->\n  Ge_antisym.\nProof using. constructor. rew_to_le. apply antisym_inverse. apply le_antisym. Qed.\n\nGlobal Instance Ge_total_of_Le_total_order :\n  Le_total_order ->\n  Ge_total.\nProof using. constructor. rew_to_le. apply total_inverse. apply le_total. Qed.\n\n(** properties of lt *)\n\nGlobal Instance Lt_irrefl_of_Le_order :\n  Le_order ->\n  Lt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply lt_strict_order. Qed.\n\nGlobal Instance Lt_trans_of_Le_order :\n  Le_order ->\n  Lt_trans.\nProof using. constructor. apply strict_order_trans. apply lt_strict_order. Qed.\n\n(** properties of gt *)\n\nGlobal Instance Gt_irrefl_of_Le_order :\n  Le_order ->\n  Gt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply gt_strict_order. Qed.\n\nGlobal Instance Gt_trans_of_Le_order :\n  Le_order ->\n  Gt_trans.\nProof using. constructor. apply strict_order_trans. apply gt_strict_order. Qed.\n\n(** mixed transitivity results *)\n\nGlobal Instance Lt_le_trans_of_Le_order :\n  Le_order ->\n  Lt_le_trans.\nProof using.\n  constructor. introv K L. rew_to_le. destruct K as [U V].\n  split~. apply* le_trans. intro_subst. apply V. apply* le_antisym.\nQed.\n\nGlobal Instance Le_lt_trans_of_Le_order :\n  Le_order ->\n  Le_lt_trans.\nProof using.\n  constructor. introv K L. rew_to_le. destruct L as [U V].\n  split~. apply* le_trans. intro_subst. apply V. apply* le_antisym.\nQed.\n\nGlobal Instance gt_ge_trans_of_Le_order :\n  Le_order ->\n  Gt_ge_trans.\nProof using.\n  constructor. introv K L. rew_to_le_lt. hnf in *. apply* le_lt_trans.\nQed.\n\nGlobal Instance ge_gt_trans_of_Le_order :\n  Le_order ->\n  Ge_gt_trans.\nProof using.\n  constructor. introv K L. rew_to_le_lt. hnf in *. apply* lt_le_trans.\nQed.\n(** conversion between operators *)\n\nGlobal Instance Ge_as_sle_of :\n  Ge_as_sle.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance Gt_as_slt_of :\n  Gt_as_slt.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance Ngt_as_sle_of_Le_total_order :\n  Le_total_order ->\n  Ngt_as_sle.\nProof using.\n  constructor. intros. rew_to_le. unfold strict. rew_logic. iff M.\n  destruct M.\n    forwards K:(inverse_strict_of_not (R:=le)); eauto.\n      apply le_total. apply (proj1 K).\n    subst. apply le_refl.\n  apply or_classic_l. intros P Q. apply P. apply* le_antisym.\nQed.\n\nGlobal Instance Nlt_as_ge_of_Le_total_order :\n  Le_total_order ->\n  Nlt_as_ge.\nProof using. constructor. intros. rew_to_le_lt. unfold inverse. apply ngt_as_sle. Qed.\n\nGlobal Instance Ngt_as_le_of_Le_total_order :\n  Le_total_order ->\n  Ngt_as_le.\nProof using. constructor. intros. rew_to_le_lt. unfold inverse. apply ngt_as_sle. Qed.\n\nGlobal Instance Nle_as_gt_of_Le_total_order :\n  Le_total_order ->\n  Nle_as_gt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold inverse.\n  rewrite <- ngt_as_sle. rewrite~ not_not_eq.\nQed.\n\nGlobal Instance Nge_as_lt_of_Le_total_order :\n  Le_total_order ->\n  Nge_as_lt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold inverse.\n  rewrite nle_as_gt. rewrite~ gt_is_inverse_lt.\nQed.\n\n(** inclusion between operators *)\n\nGlobal Instance Lt_to_le_of :\n  Lt_to_le.\nProof using. constructor. intros. rew_to_le. unfolds* strict. Qed.\n\nGlobal Instance Gt_to_ge_of :\n  Gt_to_ge.\nProof using. constructor. intros. rew_to_le. unfolds* inverse, strict. Qed.\n\nGlobal Instance Nle_to_sle_of_Le_total_order :\n  Le_total_order ->\n  Nle_to_sle.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* inverse, strict.\nQed.\n\nGlobal Instance Nle_to_slt_of_Le_total_order :\n  Le_total_order ->\n  Nle_to_slt.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* inverse, strict.\nQed.\n\n(** case analysis under no assumption *)\n\nGlobal Instance Case_eq_lt_gt_of_Le_total_order :\n  Le_total_order ->\n  Case_eq_lt_gt.\nProof using.\n  introv K. constructor. intros.\n  lets [(M1&M2)|[M|(M1&M2)]]: (total_order_lt_or_eq_or_gt le_total_order x y).\n    rewrite le_is_rclosure_lt in M1 by applys* total_order_refl. destruct* M1.\n    autos*.\n    rewrite le_is_rclosure_lt in M1 by applys* total_order_refl. destruct* M1.\nQed.\n\nGlobal Instance Case_eq_lt_slt_of_Le_total_order :\n  Le_total_order ->\n  Case_eq_lt_slt.\nProof using.\n  constructor. intros. pattern lt at 2. rewrite lt_is_inverse_gt.\n  apply case_eq_lt_gt.\nQed.\n\nGlobal Instance Case_le_gt_of_Le_total_order :\n  Le_total_order ->\n  Case_le_gt.\nProof using.\n  constructor. intros.\n  rewrite le_is_rclosure_lt by applys* total_order_refl. rewrite rclosure_eq.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance Case_eq_lt_ge_of_Le_total_order :\n  Le_total_order ->\n  Case_lt_ge.\nProof using.\n  constructor. intros.\n  rewrite ge_is_rclosure_gt by applys* total_order_refl. rewrite rclosure_eq.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance Case_le_slt_of_Le_total_order :\n  Le_total_order ->\n  Case_le_slt.\nProof using. constructor. intros. rewrite lt_is_inverse_gt. apply case_le_gt. Qed.\n\nGlobal Instance Case_eq_lt_sle_of_Le_total_order :\n  Le_total_order ->\n  Case_lt_sle.\nProof using. constructor. intros. rewrite le_is_inverse_ge. apply case_lt_ge. Qed.\n\n(** case analysis under one assumption *)\n\nGlobal Instance Neq_case_lt_gt_of_Le_total_order :\n  Le_total_order ->\n  Neq_case_lt_gt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance Neq_case_lt_slt_of_Le_total_order :\n  Le_total_order ->\n  Neq_case_lt_slt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance Le_case_eq_lt_of_Le_total_order :\n  Le_total_order ->\n  Le_case_eq_lt.\nProof using. constructor. intros. rew_to_le. unfold strict. tests*: (x = y). Qed.\n\nGlobal Instance Ge_case_eq_gt_of_Le_total_order :\n  Le_total_order ->\n  Ge_case_eq_gt.\nProof using. constructor. intros. rew_to_le. unfold inverse, strict. tests*: (x = y). Qed.\n\n(** case analysis under two assumptions *)\n\nGlobal Instance Le_neq_to_lt_of_Le_total_order :\n  Le_total_order ->\n  Le_neq_to_lt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance Ge_neq_to_gt_of_Le_total_order :\n  Le_total_order ->\n  Ge_neq_to_gt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance Nlt_nslt_to_eq_of_Le_total_order :\n  Le_total_order ->\n  Nlt_nslt_to_eq.\nProof using. constructor. intros. branches* (case_eq_lt_gt x y). Qed.\n\n(** contradiction from case analysis *)\n\nGlobal Instance Lt_ge_false_of_Le_total_order :\n  Le_total_order ->\n  Lt_ge_false.\nProof using. constructor. introv H1 H2. rewrite~ <- nlt_as_ge in H2. Qed.\n\nGlobal Instance Lt_gt_false_of_Le_total_order :\n  Le_total_order ->\n  Lt_gt_false.\nProof using.\n  constructor. introv H1 H2. rewrite~ <- nle_as_gt in H2.\n  apply H2. apply* lt_to_le.\nQed.\n\nGlobal Instance Lt_slt_false_of_Le_total_order :\n  Le_total_order ->\n  Lt_slt_false.\nProof using.\n  constructor. introv H1 H2. rewrite <- gt_as_slt in H2.\n  apply* lt_gt_false.\nQed.\n\nEnd Instances.\n\n(** -- Other lemmas needs arguments to be implicit? *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Boolean comparison *)\n\nModule BooleanComparison.\n\nOpen Scope comp_scope.\n\n(** Additional notation for reflected boolean comparison.\n    Use [Open Scope comp_scope_reflect] to use them. *)\n\nDeclare Scope comp_scope_reflect.\n\nNotation \"x ''<=' y\" := (isTrue (@le _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''>=' y\" := (isTrue (@ge _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''<' y\" := (isTrue (@lt _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''>' y\" := (isTrue (@gt _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\n\nEnd BooleanComparison.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Order on relations and on predicates *)\n\nLemma order_rel_incl : forall A B,\n  order (@rel_incl A B).\nProof using.\n  hint refl_rel_incl, antisym_rel_incl, trans_rel_incl.\n  constructors*.\nQed.\n\nLemma order_pred_incl : forall A B,\n  order (@rel_incl A B).\nProof using.\n  hint refl_rel_incl, antisym_rel_incl, trans_rel_incl.\n  constructors*.\nQed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Min and max *)\n\nDefinition min `{Le A} (n m:A) : A :=\n  If n <= m then n else m.\n\nLemma min_l : forall `{Le A} (n m:A),\n  antisym le ->\n  n <= m ->\n  min n m = n.\nProof using. introv T M. unfold min. case_if*. Qed.\n\nLemma min_r : forall `{Le A} (n m:A),\n  antisym le ->\n  m <= n ->\n  min n m = m.\nProof using. introv T M. unfold min. case_if*. Qed.\n\nDefinition max `{Le A} (n m:A) : A :=\n  If n <= m then m else n.\n\nLemma max_l : forall `{Le A} (n m:A),\n  antisym le ->\n  n >= m ->\n  max n m = n.\nProof using. introv T M. unfold max. case_if*. Qed.\n\nLemma max_r : forall `{Le A} (n m:A),\n  antisym le ->\n  n <= m ->\n  max n m = m.\nProof using. introv T M. unfold max. case_if*. Qed.\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/LibOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7936723444779225}}
{"text": "(* ================================================================== *)\nSection EX_1.\n\nVariable A:Prop. \nVariable B:Prop. \nVariable C:Prop. \nVariable D:Prop.\n\n\nLemma ex_1_1 : (A -> C) /\\ (B -> C) -> (A /\\ B) -> C.\nProof.\n  intros.\n  apply H.\n  apply H0.\nQed.\n\nLemma ex_1_2 : (~A \\/ ~B) -> ~(A /\\ B).\nProof.\n  intros.\n  intro.\n  destruct H.\n  destruct H0.\n  apply H.\n  apply H0.\n  destruct H0.\n  apply H.\n  apply H1.\nQed.\n\nLemma ex_1_3 : (A -> (B \\/ C)) /\\ (B -> D) /\\ (C -> D) -> (A -> D).\nProof.\n  intros.\n  destruct H.\n  destruct H1.\n  destruct H.\n  assumption.\n  apply H1.\n  assumption.\n  apply H2.\n  assumption.\nQed.\n\nLemma ex_1_4 : (A /\\ B) -> ~(~A \\/ ~B).\nProof.\n  intros.\n  intro.\n  destruct H.\n  destruct H0.\n  contradiction.\n  contradiction.\nQed.\n  \nEnd EX_1.\n\nSection EX_2.\n\nVariable X : Set.\nVariables P Q R : X -> Prop.\n\nLemma ex_2_1 : (forall x : X, P x -> Q x) -> (forall y : X, ~(Q y)) -> (forall x : X, ~(P x)).\nProof.\n  intros.\n  intro.\n  destruct (H0 x).\n  apply H.\n  assumption.\nQed.\n\nLemma ex_2_2 : (forall x:X, P x \\/ Q x) -> (exists y:X, ~Q y) -> (forall x:X, R x -> ~P x) -> (exists x:X, ~R x).\nProof.\n  intros.\n  destruct H0.\n  exists x.\n  intro.\n  destruct (H1 x).\n  assumption.\n  destruct (H x).\n  assumption.\n  contradiction. \nQed.\n\nEnd EX_2.\n\nSection EX_3.\n\nVariable A B : Prop.\nVariable X : Set.\nVariable P : X -> Prop.\n\nHypothesis Excluded_middle : forall P : Prop, P \\/ ~P.\n\nLemma ex_3_1 : (~A -> B) -> (~B -> A).\nProof.\n  intros.\n  destruct Excluded_middle with A.\n  assumption.\n  destruct H0.\n  apply H.\n  assumption.\nQed.\n\nLemma ex_3_2 : ~(exists x:X, ~P x) -> (forall x:X, P x).\nProof.\n  intros.\n  destruct Excluded_middle with (P x).\n  exact H0.\n  destruct H.\n  exists x.\n  assumption.\nQed.\n\nLemma ex_3_3 : ~(forall x:X, ~P x) -> (exists x:X, P x).\nProof.\n  intros.\n  destruct Excluded_middle with (exists x, P x).\n  exact H0.\n  destruct H.\n  intro x0.\n  destruct Excluded_middle with (~P x0).\n  assumption.\n  unfold not.\n  intro.\n  destruct H0.\n  exists x0.\n  assumption.\nQed.\n\nEnd EX_3.", "meta": {"author": "Th0l", "repo": "VF", "sha": "2c7393433656dc395fd6a3c7c79e1051f53afcf3", "save_path": "github-repos/coq/Th0l-VF", "path": "github-repos/coq/Th0l-VF/VF-2c7393433656dc395fd6a3c7c79e1051f53afcf3/TPCs/6_CoqTpc1/A81716_Coq1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7936610155931944}}
{"text": "Class Eq (a : Type) : Type :=\n    { equal : a -> a -> Prop \n    ; refl  : forall (x:a), equal x x \n    ; sym   : forall (x y:a), equal x y -> equal y x\n    ; trans : forall (x y z:a), equal x y -> equal y z -> equal x z \n    }.\n\nDefinition notEqual (a:Type) (_:Eq a) (x y:a) : Prop := ~ equal x y.\n\nDefinition prodEqual (a b:Type) (_:Eq a) (_:Eq b) (p q:a * b) : Prop :=\n    match p with\n    | (x,y) =>\n        match q with\n        | (x',y') => equal x x' /\\ equal y y'\n        end\n    end.\n\nArguments prodEqual {a} {b}.\n\nLemma prodRefl : forall (a b:Type) (e:Eq a) (e':Eq b) (p:a * b), \n    prodEqual _ _ p p.\nProof.\n    intros a b e e' p. destruct p as (x,y). unfold prodEqual. split; apply refl.\nQed.\n\nArguments prodRefl {a} {b}.\n\nLemma prodSym : forall (a b:Type) (e:Eq a) (e':Eq b) (p q:a * b),\n    prodEqual _ _ p q -> prodEqual _ _ q p.\nProof.\n    intros a b e e' p q. destruct p as (x,x'), q as (y,y'). simpl.\n    intros [H H']. split; apply sym; assumption.\nQed.\n\nArguments prodSym {a} {b}.\n\nLemma prodTrans : forall (a b:Type) (e:Eq a) (e':Eq b) (p q r:a * b),\n    prodEqual _ _ p q -> prodEqual _ _ q r -> prodEqual _ _ p r.\nProof.\n    intros a  b e e' p q r. destruct p as (x,x'), q as (y,y'), r as (z,z'). simpl.\n    intros [H H'] [I I']. split.\n    - apply trans with y;  assumption.\n    - apply trans with y'; assumption.\nQed.\n\nArguments prodTrans {a} {b}.\n\nInstance prodEq (a b:Type) (_:Eq a) (_:Eq b) : Eq (a * b) :=\n    { equal := prodEqual _ _\n    ; refl  := prodRefl _ _\n    ; sym   := prodSym _ _ \n    ; trans := prodTrans _ _\n    }.\n\n\nInstance defaultEq (a:Type) : Eq a :=\n    { equal := fun (x y:a)                      => x = y\n    ; refl  := fun (x:a)                        => eq_refl x\n    ; sym   := fun (x y:a) (p:x=y)              => eq_sym p\n    ; trans := fun (x y z:a) (p:x=y) (q:y=z)    => eq_trans p q\n    }.\n\nClass Ord (a :Type) (e:Eq a) : Type :=\n    { le     : a -> a -> Prop\n    ; cong   : forall (x x' y y':a), equal x x' -> equal y y' -> le x y -> le x' y'\n    ; refl'  : forall (x:a), le x x\n    ; trans' : forall (x y z:a), le x y -> le y z -> le x z\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/Class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7936327382189974}}
{"text": "Require Export Basic.\n\nTheorem n_plus_O: forall n:nat,\n  n = n + O.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag: forall n:nat,\n  n - n = O.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_O_r: forall n:nat,\n  n * O = O.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m:nat,\n  S (n + m) = n + (S m).\nProof.\n  intros.\n  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  induction n as [| n' IHn'].\n  - simpl. rewrite <- plus_O_r. reflexivity.\n  - induction m as [| m' IHm'].\n    + simpl. rewrite <- plus_O_r. reflexivity.\n    + simpl. rewrite -> IHn'. simpl. 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 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:nat, 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\nTheorem mult_O_plus: forall n m:nat,\n  (O + n) * m = n * m.\nProof.\n  intros.\n  assert (H: O + n = n). { reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange : forall n m p q:nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros.\n  assert (H: n + m = m + n). { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p:nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite <- plus_assoc.\n  assert (H: m + (n + p) = (m + n) + p). { rewrite -> plus_assoc. reflexivity. }\n  rewrite -> H.\n  rewrite <- plus_comm.\n  assert (I: m + n + p = p + (m + n)). { rewrite -> plus_comm. reflexivity. }\n  rewrite -> I.\n  assert (J: n + m = m + n). { rewrite -> plus_comm. reflexivity. }\n  rewrite -> J.\n  reflexivity.\nQed.\n\nTheorem mult_a_Sb: forall a b:nat,\n  a * S b = a + a * b.\nProof.\n  intros.\n  induction a as [| a' IHa'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHa'.\n    rewrite -> plus_swap.\n    reflexivity.\nQed.\n\nTheorem mult_comm: forall n m:nat,\n  m * n = n * m.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - rewrite -> mult_O_l. rewrite -> mult_O_r. reflexivity.\n  - simpl. rewrite <- IHn'. induction m as [| m' IHm'].\n    + simpl. reflexivity.\n    + simpl.\n      rewrite -> mult_a_Sb.\n      rewrite -> plus_swap.\n      reflexivity.\nQed.\n\n(* exercises *)\nTheorem leb_refl : forall n:nat,\n  true = leb n n.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros.\n  destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros.\n  destruct b as [| b'].\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  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  intros.\n  replace (S n) with (n + 1).\n  - rewrite -> plus_1_neq_0. reflexivity.\n  - rewrite <- plus_1_r. reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  intros.\n  destruct n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- plus_O_r. 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 as [| b'].\n  destruct c as [| 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 n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_assoc. reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> mult_plus_distr_r. 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 plus_swap' : forall n m p:nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  intros.\n  rewrite <- plus_assoc.\n  assert (H: m + (n + p) = (m + n) + p). { rewrite -> plus_assoc. reflexivity. }\n  rewrite -> H.\n  rewrite <- plus_comm.\n  replace (m + n + p) with (p + (m + n)).\n  - replace (n + m) with (m + n).\n    + reflexivity.\n    + rewrite -> plus_comm. reflexivity.\n  - rewrite -> plus_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.\n  induction b as [| b' | b'' IHb'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHb'. simpl.\n    replace (bin_to_nat b' + 0) with (bin_to_nat b').\n    + rewrite <- plus_1_r. rewrite <- plus_n_Sm. reflexivity.\n    + rewrite <- plus_O_r. reflexivity.\n  - simpl. rewrite <- plus_1_r. reflexivity.\nQed.\n\n(* binary inverse *)\nFixpoint nat_to_bin (n: nat) : bin :=\n  match n with\n  | O => Zero\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' IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IH.\n    reflexivity.\nQed.\n\nFixpoint normalize (b: bin) : bin :=\n  match b with\n  | Zero => Zero\n  | Twice b' => match (normalize b') with\n                | Zero => Zero\n                | _ => Twice (normalize b')\n                end\n  | TwicePlusOne b' => TwicePlusOne (normalize b')\n  end.\n\nCompute (normalize (TwicePlusOne (Twice (TwicePlusOne (Twice (TwicePlusOne (Twice Zero))))))).\n\nCompute (normalize (normalize (Twice Zero))).\n\nTheorem nat_twice_plus_one: forall (n:nat),\n    nat_to_bin (n + n + 1) = TwicePlusOne (nat_to_bin n).\nProof.\n  intros.\n  induction n as [| n' IH].\n  - reflexivity.\n  - simpl.\n    replace (n' + S n') with (S (n' + n')).\n    + simpl.\n      rewrite -> IH.\n      reflexivity.\n    + rewrite -> plus_n_Sm.\n      reflexivity.\nQed.\n\nTheorem normalize_incr: forall (b: bin),\n  incr (normalize b) = normalize (incr b).\nProof.\n  intros.\n  induction b as [| b' | b'' IH].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHb'.\n    destruct (normalize b').\n    + reflexivity.\n    + reflexivity.\n    + reflexivity.\n  - simpl.\n    destruct (normalize b'').\n    + reflexivity.\n    + reflexivity.\n    + reflexivity. \nQed.\n\nTheorem nat_twice: forall (n: nat),\n    nat_to_bin (n + n) = normalize (Twice (nat_to_bin n)).\nProof.\n  intros.\n  induction n as [| n' IH].\n  - reflexivity.\n  - rewrite <- plus_n_Sm.\n    simpl.\n    rewrite <- normalize_incr.\n    rewrite -> IH.\n    induction (nat_to_bin n') as [| b | b' IHb].\n    + reflexivity.\n    + reflexivity.\n    + rewrite <- IH.\nAdmitted.\n\nTheorem normalize_idemp: forall (b: bin),\n  normalize (normalize b) = normalize b.\nProof.\n  intros.\n  induction b as [| b' | b'' IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHb'.\n    reflexivity.\n  - induction (normalize (Twice b'')).\n    + reflexivity.\n    + simpl.\n      rewrite -> IHb.\n      reflexivity.\n    + \n      rewrite -> IHb.\n      simpl.\n\n  - induction b'' as [| c | c' IH'].\n    + reflexivity.\n    + simpl.\n      simpl in IH.\n      rewrite -> IH.\n      reflexivity.\nAdmitted.\n\n\nTheorem bin_nat_bin: forall (b: bin),\n  nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  intros.\n  induction b as [| b' | b'' IH].\n  - reflexivity.\n  - simpl.\n    rewrite <- plus_O_r.\n    rewrite -> nat_twice_plus_one.\n    rewrite -> IHb'.\n    reflexivity.\n  - simpl.\n    rewrite <- plus_O_r.\n    rewrite -> nat_twice.\n    simpl.\n    rewrite -> IH.\n    rewrite -> normalize_idemp.\n    reflexivity.\nQed.", "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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7935033010744226}}
{"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\nFixpoint len (len_arg0 : lst) : natural\n:= match len_arg0 with\n   | Nil => Zero\n   | Cons x y => Succ (len y)\n   end.\n\nTheorem insort_len: forall (n: natural) (x : lst), len (insort x n) = Succ (len x).\n   intro.\n   induction x.\n   { simpl. destruct (less n n0).\n      {\n      simpl. reflexivity.\n      }\n      {\n      simpl. rewrite IHx.\n      reflexivity.\n      }\n   }\n   {\n      simpl. reflexivity.\n   }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (len (sort x)) (len x).\nProof.\n   induction x; simpl; try reflexivity.\n   rewrite insort_len.\n   f_equal; assumption.\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/goal48.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7933892771503023}}
{"text": "Require Import Reals.\nRequire Import Lra.\nRequire Import Omega.\nLocal Open Scope R_scope.\n\n\n\nDefinition three_x (x : R) := 3 * x.\n\nDefinition neighborhood (eps : R) (point : R) :=\n  fun x => point - eps < x < point + eps.\n\nDefinition continuous_c (f : R -> R) (c : R) :=\n  forall (eps : R), exists (delt : R),\n      eps > 0 -> delt > 0 ->\n      forall x, neighborhood delt c x -> neighborhood eps (f c) (f x).\n\nTheorem three_x_continuous_at_0 : continuous_c three_x 0.\nProof.\n  unfold continuous_c.\n  intros. exists (eps / 3). intros.\n  unfold neighborhood.\n  split; unfold three_x; unfold neighborhood in H1; lra.\nQed.\n\nDefinition continuous (f : R -> R) :=\n  forall (c : R), continuous_c f c.\n\nTheorem three_x_continuous : continuous three_x.\n  unfold continuous.\n  intros; unfold continuous_c; intros.\n  exists (eps / 3).\n  intros; unfold neighborhood; unfold three_x.\n  unfold neighborhood in H1.\n  lra.\nQed.\n\nDefinition uniformly_continuous' (f : R -> R) :=\n  forall (eps : R), exists (delt : R),\n      eps > 0 -> delt > 0 ->\n      forall (x y : R), Rabs (x - y) < delt -> Rabs (f x - f y) < eps.\n\nDefinition uniformly_continuous (f : R -> R) :=\n  forall (eps : R), exists (delt : R),\n      eps > 0 -> delt > 0 ->\n      forall (x y : R), neighborhood delt x y -> neighborhood eps (f x) (f y).\n\nTheorem three_x_uniformly_continuous : uniformly_continuous three_x.\nProof.\n  unfold uniformly_continuous.\n  intros eps.\n  exists (eps / 3).\n  intros H1 H2 x y G1.\n  unfold neighborhood. unfold neighborhood in G1.\n  unfold three_x.\n  lra.\nQed.\n\nCheck neighborhood 1 1.\n\n\n(*compactness*)\nDefinition closed_unit_interval (x : R) := 0 <= x <= 1.\n\nDefinition limit_point (A : R -> Prop) (x : R) :=\n  forall eps, exists x', eps > 0 /\\ neighborhood eps x x' /\\ A x' /\\ x <> x'.\n\nDefinition closed' (A : R -> Prop) :=\n  forall x, limit_point A x -> A x.\n\nDefinition complement (A : R -> Prop) :=\n  fun (x : R) => ~ (A x).\n\nDefinition open (A : R -> Prop) :=\n  forall x, A x -> exists eps, eps > 0 /\\ (forall x', neighborhood eps x x' -> A x').\n\nDefinition closed (A : R -> Prop) :=\n  open A -> forall x, complement A x.\n\nTheorem closed_unit_interval_is_closed : closed closed_unit_interval.\nProof.\n  unfold closed.\n  intros H x.\n  unfold complement; unfold not; intro G.\n  unfold open in H.\n  assert (E : closed_unit_interval 1). { unfold closed_unit_interval; lra. }\n  destruct (H 1 E) as [eps1 H'].\n  destruct H' as [H1' H2'].\n  unfold neighborhood in H2'.\n  destruct (H2' (1 + eps1 / 2)).\n  - lra.\n  - lra.\nQed.\n\nDefinition is_upper_bound (A : R -> Prop) (b : R) := forall x, A x -> x <= b.\n\nDefinition is_lower_bound (A : R -> Prop) (b : R) := forall x, A x -> x >= b.\n\nDefinition bounded (A : R -> Prop) := (exists m, is_upper_bound A m) /\\ (exists b, is_lower_bound A b).\n\nLtac show_boundedness b is_bound A :=\n  exists b; unfold is_bound; intros x H; unfold A in H; lra.\n\nTheorem closed_unit_interval_is_bounded : bounded closed_unit_interval.\nProof.\n  unfold bounded.\n  split.\n  - show_boundedness 2 is_upper_bound closed_unit_interval.\n  - show_boundedness (0-1) is_lower_bound closed_unit_interval.\nQed.\n\nDefinition compact (A : R -> Prop) := closed A /\\ bounded A.\n\nTheorem closed_unit_interval_is_compact : compact closed_unit_interval.\nProof.\n  unfold compact.\n  split.\n  - apply closed_unit_interval_is_closed.\n  - apply closed_unit_interval_is_bounded.\nQed.\n\n(**Preservation of compactness*)\n\nDefinition empty (x : R) := x < 5 /\\ x > 6.\n\nDefinition image' (f : R -> R) (A : R -> Prop) (B : R -> Prop) := forall x, A x -> B (f x).\n(*I really want image to land in R -> Prop *)\n\nCheck image' three_x closed_unit_interval.\n\nTheorem image'_test1 : image' three_x closed_unit_interval (fun x => 0 <= x <= 3).\nProof.\n  unfold image'.\n  intros x H.\n  unfold three_x.\n  unfold closed_unit_interval in H.\n  lra.\nQed.\n\nTheorem image'_test2 : image' three_x empty empty.\nProof.\n  unfold image'.\n  intros x H.\n  unfold three_x.\n  unfold empty in H.\n  unfold empty.\n  lra.\nQed.\n(*Now that i have image as a relation between two sets, i want image as a function R -> Prop *)\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_first_attempt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7932954844124375}}
{"text": "Section NaturalNumbers.\n\nInductive peano : Set :=\n    | Z : peano\n    | S : peano -> peano.\n\n(* Def 1.2 *)\nInductive Plus : peano -> peano -> peano -> Prop :=\n    | P_Zero : forall n : peano, Plus Z n n\n    | P_Succ : forall n1 n2 n3 : peano,\n               Plus n1 n2 n3 -> Plus (S n1) n2 (S n3).\n\n(* Def 1.3 *)\nInductive Times : peano -> peano -> peano -> Prop :=\n    | T_Zero : forall n : peano, Times Z n Z\n    | T_Succ : forall n1 n2 n3 n4 : peano,\n               Times n1 n2 n3 -> Plus n2 n3 n4 -> Times (S n1) n2 n4.\n\n(* Fig 1.3 *)\nInductive LessThan1 : peano -> peano -> Prop :=\n    | L1_Succ  : forall n : peano, LessThan1 n (S n)\n    | L1_Trans : forall n1 n2 n3 : peano,\n                 LessThan1 n1 n2 -> LessThan1 n2 n3 -> LessThan1 n1 n3.\n\n(* Fig 1.4 *)\nInductive LessThan2 : peano -> peano -> Prop :=\n    | L2_Zero     : forall n : peano, LessThan2 Z (S n)\n    | L2_SuccSucc : forall n1 n2 : peano,\n                    LessThan2 n1 n2 -> LessThan2 (S n1) (S n2).\n\n(* Fig 1.5 *)\nInductive LessThan3 : peano -> peano -> Prop :=\n    | L3_Succ  : forall n : peano, LessThan3 n (S n)\n    | L3_SuccR : forall n1 n2 : peano, LessThan3 n1 n2 -> LessThan3 n1 (S n2).\n\n(* Def 1.5 *)\nInductive Exp : Set :=\n    | ENum   : peano -> Exp\n    | EPlus  : Exp -> Exp -> Exp\n    | ETimes : Exp -> Exp -> Exp.\n\n(* Fig 1.7 *)\nInductive EvalTo : Exp -> peano -> Prop :=\n    | E_Const : forall n : peano, EvalTo (ENum n) n\n    | E_Plus  : forall (e1 e2 : Exp) (n1 n2 n : peano),\n                EvalTo e1 n1 -> EvalTo e2 n2 -> Plus n1 n2 n ->\n                EvalTo (EPlus e1 e2) n\n    | E_Times : forall (e1 e2 : Exp) (n1 n2 n : peano),\n                EvalTo e1 n1 -> EvalTo e2 n2 -> Times n1 n2 n ->\n                EvalTo (ETimes e1 e2) n.\n\n(* Fig 1.8 *)\nInductive ReduceTo : Exp -> Exp -> Prop :=\n    | R_Plus   : forall n1 n2 n3 : peano,\n                 Plus n1 n2 n3 -> ReduceTo (EPlus (ENum n1) (ENum n2)) (ENum n3)\n    | R_Times  : forall n1 n2 n3 : peano,\n                 Times n1 n2 n3 ->\n                 ReduceTo (ETimes (ENum n1) (ENum n2)) (ENum n3)\n    | R_PlusL  : forall e1 e1' e2 : Exp,\n                 ReduceTo e1 e1' -> ReduceTo (EPlus e1 e2) (EPlus e1' e2)\n    | R_PlusR  : forall e1 e2 e2' : Exp,\n                 ReduceTo e2 e2' -> ReduceTo (EPlus e1 e2) (EPlus e1 e2')\n    | R_TimesL : forall e1 e1' e2 : Exp,\n                 ReduceTo e1 e1' -> ReduceTo (ETimes e1 e2) (ETimes e1' e2)\n    | R_TimesR : forall e1 e2 e2' : Exp,\n                 ReduceTo e2 e2' -> ReduceTo (ETimes e1 e2) (ETimes e1 e2').\n\n(* Fig 1.9 *)\nInductive MultiReduceTo : Exp -> Exp -> Prop :=\n    | MR_Zero  : forall e : Exp, MultiReduceTo e e\n    | MR_One   : forall e e' : Exp, ReduceTo e e' -> MultiReduceTo e e'\n    | MR_Multi : forall e e' e'' : Exp,\n                 MultiReduceTo e e' -> MultiReduceTo e' e'' ->\n                 MultiReduceTo e e''.\n\n(* Fig 1.10 *)\nInductive DetReduceTo : Exp -> Exp -> Prop :=\n    | DR_Plus   : forall n1 n2 n3 : peano,\n                  Plus n1 n2 n3 ->\n                  DetReduceTo (EPlus (ENum n1) (ENum n2)) (ENum n3)\n    | DR_Times  : forall n1 n2 n3 : peano,\n                  Times n1 n2 n3 ->\n                  DetReduceTo (ETimes (ENum n1) (ENum n2)) (ENum n3)\n    | DR_PlusL  : forall e1 e1' e2 : Exp,\n                  DetReduceTo e1 e1' ->\n                  DetReduceTo (EPlus e1 e2) (EPlus e1' e2)\n    | DR_PlusR  : forall (n1 : peano) (e2 e2' : Exp),\n                  DetReduceTo e2 e2' ->\n                  DetReduceTo (EPlus (ENum n1) e2) (EPlus (ENum n1) e2')\n    | DR_TimesL : forall e1 e1' e2 : Exp,\n                  DetReduceTo e1 e1' ->\n                  DetReduceTo (ETimes e1 e2) (ETimes e1' e2)\n    | DR_TimesR : forall (n1 : peano) (e2 e2' : Exp),\n                  DetReduceTo e2 e2' ->\n                  DetReduceTo (ETimes (ENum n1) e2) (ETimes (ENum n1) e2').\n\nEnd NaturalNumbers.\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/NaturalNumbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7932954837194143}}
{"text": "(*Practica 4*)\n\nSection Ejercicio1.\n\n(*Ejercicio 1*)\n(* 1.1 *)\nInductive list (A:Set) : Set :=\n                nil : list A\n              | cons : A -> list A -> list A.\n\nInductive bintree (A:Set) : Set :=\n                nilB : bintree A\n              | consB : A -> bintree A -> bintree A -> bintree A.\n\n(* 1.2 *)\nInductive Array (A:Set) : nat -> Set :=\n                nilA : Array A 0\n              | consA : forall n:nat, A -> Array A n -> Array A (n+1).\n\nInductive Matrix (A:Set) : nat -> nat -> Set :=\n   oneF : forall n:nat, Array A (n+1) -> Matrix A 1 (n+1)\n | consMf : forall (m n:nat), Array A n -> Matrix A m n -> Matrix A (m+1) n.\n\n(* 1.3 *)\nInductive leq : nat -> nat -> Prop := \n   leqI : forall n:nat, leq n n\n | leqS : forall (m n:nat), leq m n -> leq m (S n).\n\n(* 1.4 *)\nInductive eq_list (A:Set) (P:A->A->Prop) : list A -> list A -> Prop :=\n   eqEmpty : eq_list A P (nil A) (nil A)\n | eqOther : forall (xs ys:list A) (x y: A), P x y -> eq_list A P xs ys\n                        -> eq_list A P (cons A x xs) (cons A y ys).\n\n(* 1.5 *)\nInductive sorted (A:Set) (R:A->A->Prop) : list A -> Prop :=\n   sortEmpty : sorted A R (nil A)\n | sortOne : forall x:A, sorted A R (cons A x (nil A))\n | sortMore : forall (xs: list A) (x y:A), R x y -> sorted A R xs\n                       -> sorted A R (cons A x (cons A y xs)).\n\n(* 1.6 *)\nInductive mirror (A:Set) : bintree A -> bintree A -> Prop :=\n   mirrNil : mirror A (nilB A) (nilB A)\n | mirrCons : forall (t1 t2 t3 t4 : bintree A) (x y : A),\n                    mirror A t1 t4 -> mirror A t2 t3\n                       -> mirror A (consB A x t1 t2) (consB A y t3 t4).\n\n(* 1.7 *)\nInductive isomorfo (A B:Set) : bintree A -> bintree B -> Prop :=\n   isoNil : isomorfo A B (nilB A) (nilB B)\n | isoCons : forall (t1 t2 : bintree A) (t3 t4 : bintree B) (x : A) (y : B),\n                  isomorfo A B t1 t3 -> isomorfo A B t2 t4\n                       -> isomorfo A B (consB A x t1 t2) (consB B y t3 t4).\n\n(* 1.8 *)\nInductive Gtree (A B:Set) : Set :=\n     node: A -> Gforest A B -> Gtree A B\n   | hoja: B -> Gtree A B\nwith\n  Gforest (A B:Set) : Set :=\n             oneTree : Gtree A B -> Gforest A B\n           | add_tree: Gtree A B -> Gforest A B -> Gforest A B.\n\nEnd Ejercicio1.\n\nSection Ejercicio2.\n\n(* 2.1 *)\nFixpoint Or (a b: bool) : bool := match a with\n                                        true => true\n                                      | false => b\n                                  end.\n\nFixpoint And (a b: bool) : bool := match a with\n                                         true => b\n                                       | false => false\n                                   end.\n\nFixpoint Not (a: bool) : bool := match a with\n                                       true => false\n                                     | _ => true\n                                 end.\n\nFixpoint Xor (a b: bool) : bool := match a with\n                                         false => b\n                                       | true => Not b\n                                   end.\n\n(* 2.2 *)\n\nFixpoint is_nil (A:Set) (xs : list A) : bool :=\n  match xs with\n        nil => true                                    \n      | cons y ys => false\n  end.\n\nEnd Ejercicio2.\n\nSection Ejercicio3.\n\nFixpoint Sum (a b :nat) {struct b} :nat :=\n  match b with\n        0   => a                                    \n      | S k => S (Sum a k)\n  end.\n\nFixpoint Prod (a b :nat) : nat :=\n  match a with\n        0   => 0                                   \n      | S k => (Sum (Prod k b) b)\n  end.\n\nFixpoint Pot (a b: nat) : nat :=\n  match b with\n        0   => 1\n      | S k => Prod a (Pot a k)\n  end.\n\nFixpoint leBool (a b : nat) : bool :=\n  match a, b with\n        0, _     => true\n      | S k, 0   => false\n      | S k, S j => leBool k j \n  end.\n\nEnd Ejercicio3.\n\nSection Ejercicio4.\n\nFixpoint length (A:Set) (xs : list A) : nat :=\n  match xs with\n        nil => 0\n      | cons y ys => S (length A ys)\n  end.\n\nFixpoint append (A:Set) (xs ys : list A) : list A :=\n  match xs with\n        nil => ys\n      | cons z zs => cons A z (append A zs ys)\n  end.\n\nFixpoint reverse (A:Set) (xs : list A) : list A :=\n  match xs with\n        nil => nil A\n      | cons z zs => append A (reverse A zs) (cons A z (nil A))\n  end.\n\nFixpoint filter (A:Set) (f : A -> bool) (xs : list A) : list A :=\n  match xs with\n        nil => nil A\n      | cons z zs => match f z with\n                           true => cons A z (filter A f zs)\n                         | _    => filter A f zs\n                     end\n  end.\n\nFixpoint map (A B:Set) (f : A -> B) (xs : list A) : list B :=\n  match xs with\n        nil => nil B\n      | cons z zs => cons B (f z) (map A B f zs)\n  end.\n\nFixpoint exists_ (A:Set) (f : A -> bool) (xs : list A) : bool :=\n  match xs with\n        nil => false\n      | cons z zs => match f z with\n                           true  => true\n                         | false => exists_ A f zs\n                     end\n  end.\n\nEnd Ejercicio4.\n\n\nSection Ejercicio5.\n\n(* 5.1 *)\nFixpoint inverse (A:Set) (t : bintree A) : bintree A := \n  match t with\n        nilB => nilB A\n      | consB x t1 t2 => consB A x (inverse A t2) (inverse A t1)\n  end.\n\n(* 5.2 *)\n(* Funciones auxiliares *)\nFixpoint nodosInternosT (A B:Set) (t: Gtree A B) : nat := \n  match t with\n        hoja x    => 0\n      | node x ft => S (nodosInternosF A B ft)\n  end\nwith\n  nodosInternosF (A B:Set) (f: Gforest A B) : nat := \n    match f with\n          oneTree t     => nodosInternosT A B t\n        | add_tree t ft => (nodosInternosT A B t) + (nodosInternosF A B ft)\n    end.\n\nFixpoint nodosExternosT (A B:Set) (t: Gtree A B) : nat := \n  match t with\n        hoja x    => 1\n      | node x ft => nodosExternosF A B ft\n  end\nwith\n  nodosExternosF (A B:Set) (f: Gforest A B) : nat := \n    match f with\n          oneTree t     => nodosExternosT A B t\n        | add_tree t ft => (nodosExternosT A B t) + (nodosExternosF A B ft)\n    end.\n\n(* Función pedida *)\nFixpoint moreInternal (A B:Set) (t : Gtree A B) : bool := \n  leBool (nodosExternosT A B t) (nodosInternosT A B t).\n\nEnd Ejercicio5.\n\n\nSection Ejercicio6.\n\nDefinition ListN : Set := list nat.\n\n(*Función auxiliar*)\nFixpoint is_equal (x y:nat) : bool :=\n  match x, y with\n        0, 0 => true\n      | 0, _ => false\n      | _, 0 => false\n      | S a, S b => is_equal a b\n  end.\n\n(*6.1*)\nFixpoint member (n:nat) (xs : ListN) : bool := \n  exists_ nat (is_equal n) xs.\n\n(*6.2*)\nFixpoint delete (ls : ListN) (n : nat) : ListN :=\n  match ls with\n        nil => nil nat\n      | cons x xs => match is_equal n x with\n                           true  => delete xs n\n                         | false => cons nat x (delete xs n)\n                     end\n  end.\n\n(*6.3*)\nFixpoint insert (n:nat) (ls : ListN) : ListN :=\n  match ls with\n        nil => cons nat n (nil nat)\n      | cons x xs => match leBool n x with\n                           true  => cons nat n (cons nat x xs)\n                         | false => cons nat x (insert n xs)\n                     end\n  end.\n\nFixpoint insert_sort (ls : ListN) : ListN :=\n  match ls with\n        nil => nil nat\n      | cons x xs => insert x (insert_sort xs)\n  end.\n\n\n\nEnd Ejercicio6.\n\n\nSection Ejercicio7.\n\nInductive Exp (A: Set) : Set :=\n              atom     : A -> Exp A\n            | SumExp   : Exp A -> Exp A -> Exp A\n            | ProdExp  : Exp A -> Exp A -> Exp A\n            | NegExp   : Exp A -> Exp A.\n\nFixpoint EvalExpNat (e : Exp nat) : nat :=\n  match e with\n        atom n        => n\n      | SumExp e1 e2  => (EvalExpNat e1) + (EvalExpNat e2)\n      | ProdExp e1 e2 => (EvalExpNat e1) * (EvalExpNat e2)\n      | NegExp e1     => 0 - (EvalExpNat e1)\n  end.\n\nFixpoint EvalExpBool (e : Exp bool) : bool :=\n  match e with\n        atom b        => b\n      | SumExp e1 e2  => Or (EvalExpBool e1) (EvalExpBool e2)\n      | ProdExp e1 e2 => And (EvalExpBool e1) (EvalExpBool e2)\n      | NegExp e1     => Not (EvalExpBool e1)\n  end.\n\nEnd Ejercicio7.\n\n\nSection Ejercicio8.\n\nLemma AsocAnd : forall a b c: bool, And (And a b) c = And a (And b c).\nProof.\n  intros.\n  case a, b, c; trivial.\nQed.\n\nLemma AsocOr : forall a b c: bool, Or (Or a b) c = Or a (Or b c).\nProof.\n  case a, b, c; trivial.\nQed.\n\nLemma ConmutAnd : forall a b: bool, And a b = And b a.\nProof.\n  case a, b; trivial.\nQed.\n\nLemma ConmutOr : forall a b: bool, Or a b = Or b a.\nProof.\n  case a, b; trivial.\nQed.\n\nLemma LAnd : forall a b : bool, And a b = true <-> a = true /\\ b = true.\nProof.\n  unfold iff.\n  split; intro.\n  split;trivial.\n  induction a; trivial.\n  induction b; trivial.\n  elim H.\n  case a; trivial.\n  elim H; intros.\n  rewrite -> H0.\n  rewrite -> H1.\n  trivial.\nQed.\n\nLemma LOr1 : forall a b : bool, Or a b = false <-> a = false /\\ b = false.\nProof.\n  unfold iff.\n  split; intro.\n  split.\n  destruct a; trivial.\n  destruct a. \n  discriminate.\n  trivial.\n  elim H; intros.\n  rewrite -> H0.\n  rewrite -> H1.\n  trivial.\nQed.\n\nLemma LOr2 : forall a b : bool, Or a b = true <-> a = true \\/ b = true.\nProof.\n  unfold iff.\n  split; intro.\n  destruct a, b.\n  left; trivial.\n  left; trivial.\n  right; trivial.\n  right; trivial.\n  elim H; intro; rewrite -> H0.\n  trivial.\n  case a; trivial.\nQed.\n\nLemma LXor : forall a b : bool, Xor a b = true <-> a <> b.\nProof.\n  unfold iff.\n  split; unfold not; intros; destruct a; simpl.\n  rewrite <- H0 in H; discriminate.\n  rewrite <- H0 in H; discriminate.\n  destruct b; simpl; [elim H|]; trivial.\n  destruct b.\n  trivial.\n  elim H; trivial.\nQed.\n\nLemma LNot : forall b : bool, Not (Not b) = b.\nProof.\n  destruct b; trivial.\nQed.\n\n\nEnd Ejercicio8.\n\n(*----------------------SE ENTREGA------------------------*)\n(*Requiere Ej3 (Prod, Sum) *)\nSection Ejercicio9.\n\n(* 9.1 *)\nLemma SumO : forall n : nat, Sum n 0 = n.\nProof.\n  constructor.\nQed.\n\n(* 9.2 *)\nLemma SumS : forall n m : nat, Sum n (S m) = Sum (S n) m.\nProof.\n  induction m; simpl.\n  constructor.\n  rewrite <- IHm.\n  simpl.\n  trivial.\nQed.\n\n(* 9.3 *)\nLemma SumConm : forall n m : nat, Sum n m = Sum m n.\nProof.\n  induction m; simpl.\n  induction n; trivial.\n  simpl.\n  elim IHn.\n  trivial.\n  elim (SumS m n).\n  simpl.\n  elim IHm.\n  trivial.\nQed.\n\n(* 9.4 *)\nLemma SumAsoc : forall n m p : nat, Sum n (Sum m p) = Sum (Sum n m) p.\nProof.\n  induction p; simpl.\n  trivial.\n  rewrite -> IHp.\n  trivial.\nQed.\n\n(* Lema Auxiliar *)\nLemma ProdS : forall n m : nat, Prod n (S m) = Sum (Prod n m) n.\nProof.\n  intros.\n  induction n; simpl.\n  trivial.\n  rewrite -> IHn.\n  elim SumConm.\n  apply f_equal.\n  rewrite -> SumAsoc.\n  replace (Sum m (Prod n m)) with (Sum (Prod n m) m).\n  trivial.\n  elim SumConm.\n  trivial.\nQed.\n\n(* 9.5 *)\nLemma ProdConm : forall n m : nat, Prod n m = Prod m n.\nProof.\n  induction m; simpl.\n  induction n; simpl.\n  trivial.\n  rewrite -> IHn.\n  trivial.\n  rewrite <- IHm.\n  apply (ProdS n m).\nQed.\n\n(* 9.7 *)\nLemma ProdDistr : forall n m p : nat, Prod n (Sum m p) = Sum (Prod n m) (Prod n p).\nProof.\n  induction n; simpl.\n  trivial.\n  intros.\n  rewrite -> IHn.\n  rewrite -> SumAsoc.\n  symmetry.\n  rewrite -> SumAsoc.\n  pattern (Sum (Sum (Prod n m) m) (Prod n p)).\n  elim SumAsoc.\n  pattern (Sum m (Prod n p)).\n  elim SumConm.\n  rewrite -> SumAsoc.\n  trivial.\nQed.\n\n(* 9.6 *)\nLemma ProdAsoc : forall n m p : nat, Prod n (Prod m p) = Prod (Prod n m) p.\nProof.\n  intros. \n  induction n; simpl.\n  trivial.\n  rewrite -> IHn.\n  symmetry.\n  elim ProdConm.\n  rewrite -> (ProdDistr p (Prod n m) m).\n  elim ProdConm.\n  rewrite -> (ProdConm p m).\n  trivial.\nQed.\n\nEnd Ejercicio9.\n(*--------------------------------------------------------*)\n\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio10.\n(* 10.1 *)\n(* \nFixpoint append (A:Set) (xs ys : list A) : list A :=\n  match xs with\n        nil => ys\n      | cons z zs => cons A z (append A zs ys)\n  end.\n*)\n\nLemma L1 : forall (A : Set) (l : list A), append A l (nil A) = l.\nProof.\n  intros.\n  induction l.\n  trivial.\n  simpl.\n  rewrite -> IHl.\n  trivial.\nQed.\n\n(* 10.2 *)\nLemma L2 : forall (A : Set) (l : list A) (a : A), ~(cons A a l) = nil A.\nProof.\n  discriminate.\nQed.\n\n(* 10.3 *)\nLemma L3 : forall (A : Set) (l m : list A) (a : A),\n           cons A a (append A l m) = append A (cons A a l) m.\nProof.\n  trivial.\nQed.\n\n(* 10.4 *)\n(*\nFixpoint length (A:Set) (xs : list A) : nat :=\n  match xs with\n        nil => 0\n      | cons y ys => S (length A ys)\n  end.\n*)\nLemma L4 : forall (A : Set) (l m : list A),\n           length A (append A l m) = Sum (length A l) (length A m).\nProof.\n  intros.\n  induction l.\n  elim SumConm.\n  simpl.\n  trivial.\n  simpl.\n  rewrite -> IHl.\n  elim SumS.\n  simpl.\n  trivial.\nQed.\n\n(* 10.5 *)\nLemma L5 : forall (A : Set) (l : list A), length A (reverse A l) = length A l.\nProof.\n  intros.\n  induction l; simpl.\n  trivial.\n  rewrite <- IHl.  \n  rewrite -> L4.\n  simpl.\n  trivial.\nQed.\n\n(* Lema auxiliar (Ojo, igual a L9) *)\nLemma L6Aux: forall (A : Set) (l m p: list A),\n      append A l (append A m p) = append A (append A l m) p.\nProof.\n  intros.\n  induction l; simpl.\n  trivial.\n  rewrite -> IHl.\n  trivial.\nQed.\n\n(* 10.6 *)\nLemma L6 : forall (A : Set) (l m : list A),\nreverse A (append A l m) = append A (reverse A m) (reverse A l).\nProof.\n  intros.\n  induction l; simpl.\n  rewrite -> L1.\n  trivial.\n  rewrite -> IHl.\n  induction m; simpl.\n  trivial.\n  rewrite -> L6Aux.\n  trivial.\nQed.\n\nEnd Ejercicio10.\n(*--------------------------------------------------------*)\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio11.\n\n(* 11.1 *)\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  trivial.\n  rewrite -> IHl.\n  trivial.\nQed.\n\n(* 11.2 *)\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  trivial.\n  rewrite -> IHl.\n  case (P a); simpl; trivial.\nQed.\n\n(* 11.3 *)\nLemma L9 : 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  exact L6Aux.\nQed.\n\n(* 11.4 *)\nLemma L10 : forall (A : Set) (l : list A), reverse A (reverse A l) = l.\nProof.\n  intros.\n  induction l; simpl.\n  trivial.\n  rewrite -> L6.\n  simpl.\n  rewrite -> IHl.\n  trivial.\nQed.\n\nEnd Ejercicio11.\n(*--------------------------------------------------------*)\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio12.\n\nFixpoint filterMap (A B : Set) (P : B -> bool) (f : A -> B)\n         (l : list A) {struct l} : list B :=\n         match l with\n             | nil => nil B\n             | cons a l1 => match P (f a) with\n                                | true => cons B (f a) (filterMap A B P f l1)\n                                | false => filterMap A B P f l1\n                            end\n         end.\n\nLemma FusionFilterMap :\n      forall (A B : Set) (P : B -> bool) (f : A -> B) (l : list A),\n      filter B P (map A B f l) = filterMap A B P f l.\nProof.\n  intros.\n  induction l; simpl.\n  trivial.\n  rewrite -> IHl.\n  trivial.\nQed.\n\nEnd Ejercicio12.\n(*--------------------------------------------------------*)\n\nSection Ejercicio13.\n\nLemma L11: forall (A : Set) (t : bintree A), mirror A t (inverse A t).\nProof.\n  intros.\n  induction t; simpl; constructor; assumption.\nQed.\n\nEnd Ejercicio13.\n\nSection Ejercicio14.\n\nPrint isomorfo.\n\nDefinition id_arbol (A : Set) (t : bintree A) : bintree A := t.\n\nLemma L12 : forall (A : Set) (t : bintree A), isomorfo A A (id_arbol A t) t.\nProof.\n  intros.\n  unfold id_arbol.\n  induction t; constructor; assumption.\nQed.\n\nLemma isoReflexiva : forall (A : Set) (t : bintree A), isomorfo A A t t.\nProof.\n  intros.\n  replace (isomorfo A A t t) with (isomorfo A A (id_arbol A t) t).\n  apply L12.\n  unfold id_arbol.\n  trivial.\nQed.\n\nLemma isoSimetrica : forall (A B : Set) (t1 : bintree A) (t2 : bintree B), \n                     isomorfo A B t1 t2 -> isomorfo B A t2 t1.\nProof.\n  intros.\n  elim H.\n  constructor.\n  intros.\n  constructor; assumption.\nQed.\n\nEnd Ejercicio14.\n\nSection Ejercicio15.\n\nInductive Tree (A:Set) : Set :=\n                nilT : A -> Tree A\n              | consT : Tree A -> Tree A -> Tree A.\n\nFixpoint mapTree (A B:Set) (f : A -> B) (t : Tree A) : Tree B :=\n  match t with\n        nilT a => nilT B (f a)\n      | consT t1 t2 => consT B (mapTree A B f t1) (mapTree A B f t2)\n  end.\n\nFixpoint countTree (A : Set) (t : Tree A) : nat :=\n  match t with\n        nilT a => 1\n      | consT t1 t2 => Sum (countTree A t1) (countTree A t2)\n  end.\n\nLemma L13 : forall (A B: Set) (f : A -> B) (t : Tree A),\n            countTree B (mapTree A B f t) = countTree A t.\nProof.\n  intros.\n  induction t; simpl.\n  trivial.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  trivial.\nQed.\n\nFixpoint hojasTree (A : Set) (t: Tree A) : list A :=\n  match t with\n        nilT a => cons A a (nil A) \n      | consT t1 t2 => append A (hojasTree A t1) (hojasTree A t2)\n  end.\n\nLemma L14 : forall (A : Set) (t : Tree A),\n            length A (hojasTree A t) = countTree A t.\nProof.\n  intros.\n  induction t; simpl.\n  trivial.\n  rewrite -> L4.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  trivial.\nQed.\n\nEnd Ejercicio15.\n\n\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio16.\n\n(* Set Implicit Arguments *)\n\nVariable A : Set.\n\nInductive posfijo : list A -> list A -> Prop :=\n   pos1 : forall (l : list A), posfijo l l\n | pos2 : forall (a:A) (l1 l2 : list A),\n          posfijo l1 l2 -> posfijo l1 (cons A a l2).\n\nInfix \"<<\" := posfijo (at level 2).\nInfix \"+++\" := (append A) (at level 1).\n(*\nNo puedo hacerla infija porque requiere 3 argumentos\nInfix \"++\" :=  append.\nInfix \"<<\" := posfijo (at level 93).\n*)\nLemma L15 : forall (l1 l2 l3 : list A),\n            l2 = l3 +++ l1 -> l1 << l2.\nProof.\n  intros.\n  rewrite H.\n  clear H.         (* Si no pongo esto, me cambia la hipótesis inductiva *)\n  induction l3; simpl.\n  constructor.\n  constructor.\n  assumption.\nQed.\n\nLemma L16 : forall (l2 l1 : list A), posfijo l1 l2 -> \n            exists l3 : list A, l2 = append A l3 l1.\nProof.\n  intros.\n  induction H; simpl.\n  exists (nil A).\n  simpl.\n  trivial.\n  elim IHposfijo.\n  intros.\n  exists (cons A a x).\n  simpl.\n  rewrite <- H0.\n  trivial.\nQed.\n\nFixpoint ultimo (l : list A) : list A :=\n  match l with\n        nil => nil A\n      | cons a nil => cons A a (nil A)\n      | cons a xs => ultimo xs\n  end.\n\nLemma L17 : forall (l : list A), (ultimo l) << l.\nProof.\n  intros.\n  induction l.\n  simpl.\n  constructor.\n  destruct l; constructor.\n  assumption.\n(*\n  intros.\n  induction l.\n  simpl.\n  constructor.\n  destruct l.\n  simpl.\n  constructor.\n\n  replace (ultimo (cons A a (cons A a0 l))) with (ultimo (cons A a0 l)).\n  constructor.\n  assumption.\n  simpl.\n  trivial. *)\nQed.\n\nEnd Ejercicio16.\n(*--------------------------------------------------------*)\n\nSection Ejercicio17.\n\nInductive ABin (A B : Set) : Set :=\n                nilAB  : B -> ABin A B\n              | consAB : A -> ABin A B -> ABin A B -> ABin A B.\n\nFixpoint countExternal (A B : Set) (t : ABin A B) : nat :=\n  match t with\n        nilAB b => 1\n      | consAB a t1 t2 => Sum (countExternal A B t1) (countExternal A B t2)\n  end.\n\nFixpoint countInternal (A B : Set) (t : ABin A B) : nat :=\n  match t with\n        nilAB b => 0\n      | consAB a t1 t2 => S (Sum (countInternal A B t1) (countInternal A B t2))\n  end.\n\nLemma L18 : forall (A B : Set) (t : ABin A B), \n            countExternal A B t = 1 + countInternal A B t.\nProof.\n  induction t; simpl.\n  trivial.\n  rewrite IHt1.\n  rewrite IHt2.\n  elim SumS.\n  simpl.\n  trivial.\nQed.\n\nEnd Ejercicio17.\n\n\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio18.\n\nVariable A : Set.\n\nInductive Tree_ : Set :=\n  | nullTT : Tree_\n  | consTT : A -> Tree_ -> Tree_ -> Tree_ .\n\nInductive isSubtree : Tree_ -> Tree_ -> Prop :=\n  | isSub1 : forall t : Tree_ , isSubtree t t\n  | isSub2 : forall (a : A) (t1 t2 t3 : Tree_), \n             isSubtree t1 t2 -> isSubtree t1 (consTT a t2 t3)  \n  | isSub3 : forall (a : A) (t1 t2 t3 : Tree_), \n             isSubtree t1 t3 -> isSubtree t1 (consTT a t2 t3).\n\n\nLemma L19 : forall t : Tree_, isSubtree t t.\nProof.\n  constructor.\nQed.\n\nLemma L20 : forall t1 t2 t3 : Tree_,\n            isSubtree t1 t2 /\\ isSubtree t2 t3 -> isSubtree t1 t3.\nProof.\n  intros.\n  elim H; intros; clear H.\n  induction H1.\n  assumption.\n\n  apply isSub2.\n  apply IHisSubtree.\n  assumption.\n\n  apply isSub3.\n  apply IHisSubtree.\n  assumption.\nQed.\n\nEnd Ejercicio18.\n(*--------------------------------------------------------*)\n\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio19.\n\nVariable A : Set.\n\nInductive ACom : nat -> Set :=\n  | hojaCom : A -> ACom 0\n  | consCom : forall n : nat, A -> ACom n -> ACom n -> ACom (S n).\n\nFixpoint cantHojasACom (n:nat) (t : ACom n) : nat :=\n  match t with\n        hojaCom a => 1\n      | consCom p a t1 t2 => \n          Sum (cantHojasACom p t1) (cantHojasACom p t2)\n  end.\n\nParameter pot: nat -> nat -> nat.\n\n(* n^0 = 1, n>0 *)\nAxiom potO : forall n : nat, pot (S n) 0 = 1. \n\n(* 2^(m+1) = 2^m + 2^m *)\nAxiom potS : forall m: nat, pot 2 (S m) = Sum (pot 2 m) (pot 2 m).\n\nLemma L21 : forall (n : nat) (t : ACom n), cantHojasACom n t = pot 2 n. \nProof.\n  induction t; simpl.\n  rewrite -> potO.\n  trivial.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  rewrite -> potS.\n  trivial.\nQed.\n\nEnd Ejercicio19.\n(*--------------------------------------------------------*)\n\n(*----------------------SE ENTREGA------------------------*)\nSection Ejercicio20.\n\n\n(* Funciones auxiliares *)\nFixpoint GeBool (m n : nat) {struct n} : bool :=\n  match n with\n    | O => true\n    | S k => match m with\n                 | O => false\n                 | S k2 => GeBool k2 k\n                   end\n  end.\n\nFixpoint Max (m n : nat) : nat :=\n  match GeBool m n with\n    | true => m\n    | false => n\n  end.\n(* ------------------- *)\n\nInductive AB (A:Set) : nat -> Set :=\n                nullAB : AB A 0\n              | constAB : forall (m n : nat), A -> AB A m -> AB A n -> AB A (S (Max m n)).\n\nFixpoint camino (A: Set) (n: nat) (t : AB A n) : list A :=\n  match t with\n        nullAB => nil A\n      | constAB n1 n2 a t1 t2 => match (GeBool n1 n2) with\n                                       true => cons A a (camino A n1 t1)\n                                     | false => cons A a (camino A n2 t2)\n                                 end\n  end.\n\nLemma AuxIfLength : forall (c : bool) (A:Set) (l1 l2 : list A),\n      length A (if c then l1 else l2) = if c then length A l1 else length A l2.\nProof.\n  induction c; trivial.\nQed.\n\nLemma CaminoN : forall (A: Set) (n : nat) (t : AB A n), \n                length A (camino A n t) = n.\nProof.\n  induction t; simpl.\n  trivial.\n  rewrite AuxIfLength.\n  simpl.\n  rewrite IHt1.\n  rewrite IHt2.\n  destruct m; destruct n; simpl; trivial.\n  case (GeBool m n); trivial.\nQed.\n\nEnd Ejercicio20.\n(*--------------------------------------------------------*)\n", "meta": {"author": "adrielulanovsky", "repo": "Coq", "sha": "f75a35e28d171239ec6c8af3f24b64dc04628202", "save_path": "github-repos/coq/adrielulanovsky-Coq", "path": "github-repos/coq/adrielulanovsky-Coq/Coq-f75a35e28d171239ec6c8af3f24b64dc04628202/TP4/adrielUlanovsky_full.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7932518477994438}}
{"text": "(** INITIATION A LΑ RÉCURRENCE EN COQ *)\n\n(*\nLe TD est destiné à exprimer en Coq la preuve par récurrence\nsur les expressions arithmétiques vue au TD1.\n*)\n\n(**\nAttention : il faut être capable de rédiger sous forme de texte usuel\nle raisonnement formalisé en Coq, soit avant, soit a posteriori.\n*)\n\n(** * Expressions arithmétiques *)\n\n(** ** Définitions *)\n\n(** On considère une variante simplifiée des expressions arithmétiques vues en cours/TD,\n    ne comportant des opérateurs que pour l'addition et la multiplication.\n    On utilisera le type nat (entiers naturels de Coq) pour représenter les entiers\n    et on nommera les différents constructeurs/opérateurs\n    Cst (pour les naturels), Apl et Amu pour l'addition et la multiplication *)\n\nInductive aexp : Set :=\n| Cst: nat -> aexp\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp.\n\n(* Définir les expressions aexp correspondant à\n  (1 + 2) * 3 et  (1 * 2) + 3\n *)\n\nDefinition exp_1 := Amu (Apl (Cst 1) (Cst 2)) (Cst 3). \n\nDefinition exp_2 :=  Apl (Amu (Cst 1) (Cst 2)) (Cst 3).\n\n(** Définir en Coq la fonction d'évaluation sémantique fonctionnelle Sf de aexp\n    en utilisant les operateurs arithmétiques de Coq sur le type nat : + *       *)\n\nFixpoint eval (a: aexp) : nat :=\n  match a with\n  | Cst n => n\n  | Apl e1 e2 => (eval e1) + (eval e2)\n  | Amu e1 e2 => (eval e1) * (eval e2)\n  end.\n               \n\n(** Evaluer avec Eval ou Compute la sémantique de exp_1 et exp_2 *)\n\n(* à compléter *)\nEval compute in (eval exp_1).\nCompute (eval exp_2).\n\n(** Nombre de feuilles *)\n\n(** Définir en Coq la fonction de calcul du nombre de feuilles dans un\n    arbre d'expression (c'est-à-dire le nombre de constantes de\n    l'expression) *)\n\nFixpoint nbf (a:aexp) :=\n  match a with\n    (* à compléter *)\n    | Cst n => 1\n    | Apl e1 e2 => nbf e1 + nbf e2\n    | Amu e1 e2 => nbf e1 + nbf e2\n  end.\n\nCompute (nbf exp_1).\nCompute (nbf exp_2).\n\n(** ** Raisonnement par cas sur un AST *)\n\n(** Écrire une fonction qui transforme une expression\n   (ou plus exactement un AST d'expression) de la façon suivante :\n   - si l'expression représente une constante, rendre la constante 1\n   - si l'expression représente une somme, rendre la constante 2\n   - si l'expression représente un produit, rendre la constante 3\n *)\n\nDefinition categorise (a:aexp) :=\n  match a with\n    (* à compléter *)\n    | Cst n => Cst 1\n    | Apl e1 e2 => Cst 2\n    | Amu e1 e2 => Cst 3\n  end.\n\n(** Démontrer que le résultat de la fonction précédente\n    rend un AST de taille 1 au sens de nbf.\n    Raisonner par cas en utilisant la tactique destruct.\n *)\n\nLemma nbf_cat : forall a, nbf (categorise a) = 1.\nProof.\n(* à compléter *)\n  intro a0.\n  destruct a0 as [(*Cst*) n |\n                   (*Apl*) e1 e2 |\n                   (*Amu*) e1 e2].\n  - cbn [categorise]. cbn [nbf]. reflexivity.\n  - cbn [categorise]. cbn [nbf]. reflexivity.\n  - cbn [categorise]. cbn [nbf]. reflexivity.\nQed.\n\n(** Nombre d'opérateurs *)\n\n(** Définir en Coq la fonction de calcul du nombre de noeuds dans un\n    arbre d'expression (c'est-à-dire le nombre d'opérateurs binaires de\n    l'expression) *)\n\nFixpoint nbo (a:aexp) :=\n  match a with\n    (* à compléter *)\n    | Cst n => 0\n    | Apl e1 e2 => nbo e1 + 1 + nbo e2\n    | Amu e1 e2 => nbo e1 + 1 + nbo e2\n  end.\n\nCompute (nbo exp_1).\nCompute (nbo exp_2).\n\n(** Démontrer la relation entre nbf et nbo par récurrence structurelle *)\n\n(** On utilisera dans la suite quelques lemmes simples d'arithmétique *)\n\nRequire Import Arith. Import Nat.\nCheck add_assoc.\n\nLemma nbf_nbo_plus_1: forall a:aexp, nbf a = nbo a + 1.\nProof.\n  intro a.\n  induction a as [ (*Cst*) n\n                 | (*Apl*) e1 Hrec_e1 e2 Hrec_e2\n                 | (*Amu*) e1 Hrec_e1 e2 Hrec_e2 ].\n\n  (* à compléter *)\n  - cbn [nbf]. cbn [nbo]. reflexivity.\n  - cbn [nbf]. cbn [nbo].  rewrite Hrec_e1. rewrite Hrec_e2. rewrite add_assoc. reflexivity.\n  - cbn [nbf]. cbn [nbo]. rewrite Hrec_e1. rewrite Hrec_e2. rewrite add_assoc. reflexivity.\nQed.\n\n(** Transformation d'expressions *)\n\n\n(* Écrire une fonction qui transforme une expression\n * en remplaçant toutes les constantes par 1\n * et tous les opérateurs binaires par +\n *)\n\nFixpoint transform (a:aexp) :=\n  (* à compléter *)\n  match a with\n  | Cst n => Cst 1\n  | Apl e1 e2 => Apl (transform e1) (transform e2)\n  | Amu e1 e2 => Apl (transform e1) (transform e2)\n  end.\n(** Évaluer la fonction transform sur les expressions exp_1 et exp_2 *)\n\n(* à compléter *)\nCompute (transform exp_1).\nCompute (transform exp_2).\nCompute (eval (transform exp_1)).\nCompute (nbf (exp_1)).\n(** Montrer maintenant que l'évaluation de transform e donne le nombre\n * de feuilles de e (nbf e). *)\n\nLemma eval_transform_nbf : forall a, eval (transform a) = nbf a.\nProof.\n  (* à compléter *)\n  intro a0.\n  induction a0 as [(*Cst*) n \n                   |(*Apl*) e1 Hrec_e1 e2 Hrec_e2 \n                   |(*Amu*) e1 Hrec_e1 e2 Hrec_e2].\n  - cbn [transform]. cbn [eval]. cbn [nbf]. reflexivity.\n  - cbn [transform]. cbn [eval]. cbn [nbf]. rewrite Hrec_e1. rewrite Hrec_e2. reflexivity.  \n  - cbn [transform]. cbn [eval]. cbn [nbf]. rewrite Hrec_e1. rewrite Hrec_e2. reflexivity.\nQed.\n\n(** Simplification d'expressions *)\n\n(* Définir ici la fonction simpl0 du TD1 *)\n\nDefinition simpl0 (a:aexp) :=\n  match a with\n  (* à compléter *)\n  | Apl (Cst 0) e2 => e2\n  | Amu (Cst 0) e2 => Cst 0\n  (* fin de zone à compléter *)\n  | _ => a\n  end.\n\n(* ------------------------------------------------------------------------------- *)\n(*                     LΑ SUITE EST FACULTATIVE POUR LE DM.                        *)\n(*                                                                                 *)\n(* Vous êtes bien sûr encouragés à la faire si vous êtes à l'aise avec ce qui a    *)\n(* été vu jusqu'ici.                                                               *)\n(* ------------------------------------------------------------------------------- *)\n\n(* Prouver que simpl0 préserve le résultat de l'évaluation *)\n\n(* On introduit une tactique utilisateur signifiant :\n   prouver les cas \"0 + e2\" et \"0 * e2\", \n   considérant à l'avance que tous les autres cas se prouvent par simplification et \n   réflexivité.\n   A ce stade on va simplement utiliser cette tactique, son fonctionnement\n   sera expliqué plus tard.\n*)\nLtac cas_simpl0 e :=\n  refine ( match e with\n           | Apl (Cst 0) e2 => _\n           | Amu (Cst 0) e2 => _\n           | _ => eq_refl _\n           end).\n\n(** Deux lemmes utiles *)\nCheck add_0_l.\nCheck mul_0_l.\n\nLemma eval_simpl0: forall a, eval (simpl0 a) = eval a.\nProof.\n  intro a. cas_simpl0 a.\n  - cbn [simpl0]. cbn [eval]. rewrite add_0_l. reflexivity.\n    (* à compléter *)\n  - cbn [simpl0]. cbn [eval]. rewrite mul_0_l. reflexivity.  \nQed.\n\n(* écrire la fonction simpl_rec qui applique récursivement simpl0 à toutes les sous-expressions. *)\n\nFixpoint simpl_rec (a:aexp) :=\n  (* à compléter *)\n  match a with\n  | Cst n => Cst n\n  | Apl e1 e2 => simpl0 (Apl (simpl_rec e1) (simpl_rec e2))\n  | Amu e1 e2 => simpl0 (Amu (simpl_rec e1) (simpl_rec e2))\n  end.\n\n(* Prouver que simpl_rec préserve l'évaluation des expressions *)\n\nLemma eval_simpl_rec: forall a, eval(simpl_rec a) = eval a.\nProof.\n  (* à compléter *)\n  intro a0.\n  induction a0 as [(*Cst*) n\n                 | (*Apl*) e1 Hrec_e1 e2 Hrec_e2\n                 |(*Amu*) e1 Hrec_e1 e2 Hrec_e2].\n  - cbn [simpl_rec]. reflexivity.\n  - cbn [simpl_rec]. \nAdmitted.\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/TD2/TD02_intro_coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.9005297787765765, "lm_q1q2_score": 0.7931840062318924}}
{"text": "Goal forall (n : nat), n = n + 0.\n  intros.\n  induction n.\n  reflexivity.\n  simpl.\n  f_equal.\n  apply IHn.\nQed.\n\nRequire Import Arith.\nGoal forall (n : nat), (exists m : nat,  n = m * 4) -> (exists k : nat, n = k * 2).\n  intros.\n  destruct H.\n  exists (x * 2).\n  rewrite mult_assoc_reverse.\n  simpl.\n  apply H.\nQed.\n\nRequire Import Arith.\n\nTheorem lt_Snm_nm : forall (n m : nat), S n < m -> n < m.\n  intros.\n  rewrite lt_n_Sn.\n  apply H.\nQed.\n\nInductive InList (A : Type)(a : A) : list A -> Prop :=\n  | headIL : forall xs, InList A a (a :: xs)\n  | consIL : forall x xs, InList A a xs -> InList A a (x :: xs).\n\nRequire Import List.\nRequire Import Arith.\nTheorem pigeonhole : forall (xs : list nat),\n    length xs < fold_right plus 0 xs -> exists x : nat, InList nat (S (S x)) xs.\n  intros.\n  induction xs.\n  simpl in H.\n  apply False_ind.\n  apply (lt_n_O 0).\n  apply H.\n  simpl in H.\n  destruct a.\n  apply lt_Snm_nm in H.\n  apply IHxs in H.\n  destruct H.\n  exists x.\n  constructor.\n  apply H.\n  destruct a.\n  simpl in H.\n  apply lt_S_n in H.\n  apply IHxs in H.\n  destruct H. (* H : exists x : ... の時に exists を外すために使う*)\n  exists x.\n  constructor.\n  apply H.\n  exists a.\n  constructor.\nQed.\n\nGoal forall (n : nat), 0 = n * 0.\ntrivial.\nQed.\n\n(*\nGoal forall (n : nat), 0 = n * 0.\n  intros.\n  destruct 0.\n  simpl.\n  reflexivity.\n  simpl.\n  \nQed.\n *)\n\nGoal forall (n m : nat), n * m = m * n.\nauto with arith.\nQed.\n\n(*\nGoal forall (n m : nat), n * m = m * n.\n  intros.\n  destruct n.\nQed.\n *)\n\nRequire Import Omega.\nGoal forall n m, 1 + 2 * n = 2 * m -> False.\nintros.\nomega.\nQed.\n\n(*\nGoal forall n m, 1 + 2 * n = 2 * m -> False.\nintros.\nomega.\nQed.\n *)\n\n", "meta": {"author": "shokohara", "repo": "coq-sandbox", "sha": "6bb86843ea36faed24e5b500083d49036318d1b9", "save_path": "github-repos/coq/shokohara-coq-sandbox", "path": "github-repos/coq/shokohara-coq-sandbox/coq-sandbox-6bb86843ea36faed24e5b500083d49036318d1b9/coqt4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7931840004749009}}
{"text": "Module Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(* \\f\\x.x *)\nDefinition zero : cnat :=\n  fun (X : Type)(f : X -> X)(x : X) => x.\n\n(* \\f\\x.f x *)\nDefinition one : cnat :=\n  fun (X : Type)(f : X -> X)(x : X) => f x.\n\n(* \\f\\x.f (f x) *)\nDefinition two : cnat :=\n  fun (X : Type)(f : X -> X)(x : X) => f (f x).\n\n(* \\f\\x.f (f (f x)) *)\nDefinition three : cnat :=\n  fun (X : Type)(f : X -> X)(x : X) => f (f (f x)).\n\nDefinition succ(n: cnat) : cnat :=\n  fun (X: Type) (f: X -> X) (x : X) => f (n X f x).\n\nCompute succ one.\n\nDefinition plus(m n: cnat) : cnat :=\n  fun (X: Type) (f: X -> X) (x : X) => m X f (n X f x).\n\nExample zero_plus_one : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample two_p_three_eq_three_p_two : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample assoc_test : plus one (plus two three) = plus (plus one two) three.\nProof. reflexivity. Qed.\n\nDefinition multiply(m n: cnat) : cnat :=\n  fun (X: Type) (f: X -> X) (x : X) => m X (n X f) x.\n\nDefinition cbool := forall X : Type, X -> X -> X.\n\nDefinition true : cbool :=\n  fun (X : Type) (t f: X) => t.\n\nDefinition false : cbool :=\n  fun (X : Type) (t f: X) => f.\n\nDefinition not (b : cbool) :=\n  fun (X : Type) (t f: X) => b X f t.\n\nExample not_involutive : not (not true) = true.\nProof. reflexivity. Qed.\n\nDefinition and (b c : cbool) :=\n  fun (X: Type) (t f: X) => b X (c X t f) f.\n\nDefinition or (b c : cbool) := \n  fun (X: Type) (t f: X) => b X t (c X t f).\n\nExample and_comm : and true false = and false true.\nProof. reflexivity. Qed.\n\nDefinition xor (b c : cbool) := \n  fun (X: Type) (t f: X) => b X ((not c) X t f) (c X t f).\n\nExample xor_test : xor true true = false.\nProof. reflexivity. Qed.\n\nEnd Church.\n\n\n\n\n\n\n\n\n", "meta": {"author": "wags-1314", "repo": "church-encoding-in-coq", "sha": "1eb7a0248924f4777207eb8e5663400623d825c9", "save_path": "github-repos/coq/wags-1314-church-encoding-in-coq", "path": "github-repos/coq/wags-1314-church-encoding-in-coq/church-encoding-in-coq-1eb7a0248924f4777207eb8e5663400623d825c9/Church.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7931436837940121}}
{"text": "Require Import ZArith.\n(*Require Import Coq.Arith.Even. *)\nRequire Import Nat.\nOpen Scope Z_scope.\nRequire Import FunInd.\n\nFixpoint power (x:Z)(n:nat):=\n  match n with 0%nat => 1\n          | S p => x * power x p\n  end.\n\nCompute power 2 40.\nSearch nat.\n(*\nFunction binary_power_mult (acc x:Z)(n:nat)\n         {measure (fun i=>i) n} : Z\n(* acc * (power x n) *) :=\n  match n with 0%nat => acc\n          | _ => if Nat.Even n Nat.Odd n\n                 then binary_power_mult\n                        acc (x * x) (Nat.div2 n)\n                 else binary_power_mult\n                        (acc * x) (x * x) (Nat.div2 n)\n  end.\nProof.\n  intros; apply lt_div2; auto with arith.\n  intros; apply lt_div2; auto with arith.\nDefined.\n*)\n\nFixpoint sum_odd_n (n:nat) : nat :=\n  match n with\n    O => O\n  | S p => 1 + 2*p + sum_odd_n p\n  end.\nSearch (Nat.mul).\n\nLemma sum_odd_n_p : forall (n:nat), sum_odd_n (n:nat) = n*n.\n  induction n.\n  simpl. reflexivity.\n  simpl. rewrite IHn. ring.", "meta": {"author": "ihasson", "repo": "coq", "sha": "0da545a4966f48b1874183812f61f54eac7b1976", "save_path": "github-repos/coq/ihasson-coq", "path": "github-repos/coq/ihasson-coq/coq-0da545a4966f48b1874183812f61f54eac7b1976/typeclasstut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7930081417732262}}
{"text": "Inductive light : Set :=\n  | Blue   : light\n  | Yellow : light\n  | Red    : light.\n\nDefinition next x :=\n  match x with\n    | Blue   => Yellow\n    | Yellow => Red\n    | Red    => Blue\n  end.\n\nCheck next Yellow.\nEval compute in next Yellow.\n\nTheorem light_cycles : forall (l : light), next (next (next l)) = l.\nProof.\n  intros l.\n  destruct l.\n  (* Blue *)\n  simpl.\n  reflexivity.\n\n  (* Yellow *)\n  simpl.\n  reflexivity.\n\n  (* Red *)\n  simpl.\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/e1.27.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7930081289117146}}
{"text": "Definition even (n : nat) := exists k, n = k + k.\nDefinition odd (n : nat) := exists k, n = S (k + k).\n\nAxiom double_negation : forall P, P = ~~P.\n\nLemma contrapositive : forall P Q : Prop, (P -> Q) -> (~Q -> ~P).\nProof. intuition. Qed.\n\nLemma plus_n_0 : forall n, n + 0 = n.\nProof.\n  intros n.\n  induction n as [|n' IHn]. reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma plus_n_Sm : forall n m, n + S m = S n + m.\nProof.\n  intros n m.\n  induction n as [|n' IHn]. reflexivity.\n  simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma plus_commutative : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [|n' IHn]. rewrite plus_n_0. reflexivity.\n  rewrite plus_n_Sm. simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma plus_associative : forall n m o, (n + m) + o = n + (m + o).\nProof.\n  intros n m o.\n  induction n as [|n' IHn]. reflexivity.\n  simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma plus_result_0 : forall n m, n + m = 0 <-> n = 0 /\\ m = 0.\nProof.\n  intros n m.\n  split.\n  - intros H.\n    destruct n as [|n'] eqn : En.\n    + destruct m as [|m'] eqn : Em.\n      * split. reflexivity. reflexivity.\n      * discriminate H.\n    + discriminate H.\n  - intros [Hl Hr].\n    rewrite Hl, Hr.\n    reflexivity.\nQed.\n\nLemma mult_n_0 : forall n, n * 0 = 0.\nProof.\n  intros n.\n  induction n as [|n' IHn]. reflexivity.\n  simpl. apply IHn.\nQed.\n\nLemma mult_1_n : forall n, 1 * n = n.\nProof. intros n. simpl. rewrite plus_n_0. reflexivity. Qed.\n\nLemma mult_n_1 : forall n, n * 1 = n.\nProof.\n  intros n.\n  induction n as [|n' IHn]. reflexivity.\n  simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma mult_n_Sm : forall n m, n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [|n' IHn]. reflexivity.\n  simpl. rewrite IHn.\n  rewrite <- (plus_associative m n' _).\n  rewrite (plus_commutative m n').\n  rewrite (plus_associative n' m _).\n  reflexivity.\nQed.\n\nLemma mult_commutative : forall n m, n * m = m * n.\nProof.\n  intros n m.\n  induction n as [|n' IHn]. rewrite mult_n_0. reflexivity.\n  simpl. rewrite mult_n_Sm. rewrite IHn. reflexivity.\nQed.\n\nLemma mult_left_distributive : forall n m o, n * (m + o) = n * m + n * o.\nProof.\n  intros n m o.\n  induction n. reflexivity.\n  simpl. rewrite IHn.\n  rewrite (plus_associative m (n * m) _).\n  rewrite <- (plus_associative (n * m) o (n * o)).\n  rewrite (plus_commutative (n * m) o).\n  rewrite (plus_associative o (n * m) _).\n  rewrite (plus_associative m o _).\n  reflexivity.\nQed.\n\nLemma mult_right_distributive : forall n m o, (n + m) * o = n * o + m * o.\nProof.\n  intros n m o.\n  induction o as [|o' IHo].\n  - rewrite mult_n_0.\n    rewrite (mult_n_0 n).\n    rewrite (mult_n_0 m).\n    reflexivity.\n  - rewrite mult_n_Sm.\n    rewrite (mult_n_Sm n).\n    rewrite (mult_n_Sm m).\n    rewrite IHo.\n    rewrite (plus_associative n (n * o') _).\n    rewrite <- (plus_associative (n * o') m _).\n    rewrite (plus_commutative (n * o') m).\n    rewrite (plus_associative m (n * o')).\n    rewrite (plus_associative n m _).\n    reflexivity.\nQed.\n\nLemma mult_associative : forall n m o, (n * m) * o = n * (m * o).\nProof.\n  intros n m o.\n  induction n. reflexivity.\n  simpl. rewrite <- IHn. apply mult_right_distributive.\nQed.\n\nLemma mult_result_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  split.\n  - intros H.\n    destruct n as [|n'] eqn : En.\n    + left. reflexivity.\n    + right. destruct m as [|m'] eqn : Em.\n      * reflexivity.\n      * simpl in H.\n        discriminate H.\n  - intros [Hl | Hr].\n    + rewrite Hl. reflexivity.\n    + rewrite Hr. apply mult_n_0.\nQed.\n\nLemma even_n__even_SSn : forall n, even n -> even (S (S n)).\nProof.\n  intros n H.\n  induction H.\n  exists (S x).\n  simpl.\n  rewrite plus_n_Sm.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma odd_n__odd_SSn : forall n, odd n -> odd (S (S n)).\nProof.\n  intros n H.\n  induction H.\n  exists (S x).\n  simpl.\n  rewrite plus_n_Sm.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma even_SSn__even_n : forall n, even (S (S n)) -> even n.\nProof.\n  intros n H.\n  induction H.\n  assert(H' : exists k, x = S k). {\n    induction x as [|x' IHx].\n    - discriminate H.\n    - exists x'. reflexivity.\n  }\n  destruct H' as [k H'].\n  exists k.\n  rewrite H' in H.\n  rewrite plus_n_Sm in H.\n  simpl in H.\n  inversion H.\n  reflexivity.\nQed.\n\nLemma odd_SSn__odd_n : forall n, odd (S (S n)) -> odd n.\nProof.\n  intros n H.\n  inversion H.\n  assert(H' : exists k, x = S k). {\n    induction x as [|x' IHx].\n    - discriminate H0.\n    - exists x'. reflexivity.\n  }\n  destruct H' as [k H'].\n  exists k.\n  rewrite H' in H0.\n  rewrite plus_n_Sm in H0.\n  simpl in H0.\n  inversion H0.\n  reflexivity.\nQed.\n\nLemma even_n__not_odd_n : forall n, even n -> ~odd n.\nProof.\n  intros n [k H]. generalize dependent n.\n  induction k as [|k' IHk].\n  - intros n H.\n    rewrite H.\n    intros [x H'].\n    inversion H'.\n  - intros n H.\n    rewrite H.\n    rewrite plus_n_Sm.\n    simpl.\n    assert(H'' : forall a, ~odd (S (S a)) <-> ~odd a). {\n      intros a. split.\n      - intros H'' H'''.\n        apply odd_n__odd_SSn in H'''.\n        apply H'' in H'''.\n        apply H'''.\n      - intros H'' H'''.\n        apply odd_SSn__odd_n in H'''.\n        apply H'' in H'''.\n        apply H'''.\n    }\n    apply H''.\n    apply IHk.\n    reflexivity.\nQed.\n\nLemma odd_n__not_even_n : forall n, odd n -> ~even n.\nProof.\n  intros n [k H]. generalize dependent n.\n  induction k as [| k' IHk].\n  - intros n H.\n    rewrite H.\n    intros [x H'].\n    destruct x. inversion H'.\n    rewrite plus_n_Sm in H'. inversion H'.\n  - intros n H.\n    rewrite H.\n    rewrite plus_n_Sm.\n    simpl.\n    assert(H'' : forall a, ~even (S (S a)) <-> ~even a). {\n      intros a. split.\n      - intros H'' H'''.\n        apply even_n__even_SSn in H'''.\n        apply H'' in H'''.\n        apply H'''.\n      - intros H'' H'''.\n        apply even_SSn__even_n in H'''.\n        apply H'' in H'''.\n        apply H'''.\n    }\n    apply H''.\n    apply IHk.\n    reflexivity.\nQed.\n\nLemma even_n__odd_Sn : forall n, even n -> odd (S n).\nProof.\n  intros n [k H].\n  exists k.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma odd_n__even_Sn : forall n, odd n -> even (S n).\nProof.\n  intros n [k H].\n  exists (S k).\n  rewrite H, plus_n_Sm.\n  reflexivity.\nQed.\n\nLemma odd_n__not_odd_Sn : forall n, odd n -> ~odd (S n).\nProof.\n  intros n H.\n  apply odd_n__even_Sn in H.\n  apply even_n__not_odd_n in H.\n  apply H.\nQed.\n\nLemma even_n__not_odd_Sn : forall n, even n -> ~even (S n).\nProof.\n  intros n H.\n  apply even_n__odd_Sn in H.\n  apply odd_n__not_even_n in H.\n  apply H.\nQed.\n\nLemma even_Sn__odd_n : forall n, even (S n) -> odd n.\nProof.\n  intros n [[|k] H].\n  - discriminate H.\n  - exists k.\n    rewrite plus_n_Sm in H.\n    inversion H.\n    reflexivity.\nQed.\n\nLemma odd_Sn__even_n : forall n, odd (S n) -> even n.\nProof.\n  intros n [[|k] H].\n  - inversion H.\n    exists 0.\n    reflexivity.\n  - exists (S k).\n    inversion H.\n    reflexivity.\nQed.\n\nLemma even_Sn__not_even_n : forall n, even (S n) -> ~even n.\nProof.\n  intros n H.\n  apply even_Sn__odd_n in H.\n  apply odd_n__not_even_n in H.\n  apply H.\nQed.\n\nLemma odd_Sn__not_odd_n : forall n, odd (S n) -> ~odd n.\nProof.\n  intros n H.\n  apply odd_Sn__even_n in H.\n  apply even_n__not_odd_n in H.\n  apply H.\nQed.\n\nLemma not_odd_n__odd_Sn : forall n, ~odd n -> odd (S n).\nProof.\n  intros n.\n  induction n as [|n' IHn].\n  - exists 0. reflexivity.\n  - intros H. apply odd_n__odd_SSn.\n    apply contrapositive in IHn.\n    rewrite <- double_negation in IHn.\n    apply IHn.\n    apply H.\nQed.\n\nLemma not_even_n__even_Sn : forall n, ~even n -> even (S n).\nProof.\n  intros n H.\n  induction n as [|n' IHn].\n  - assert(H' : even 0). exists 0. reflexivity.\n    apply H in H'.\n    destruct H'.\n  - apply even_n__even_SSn.\n    apply contrapositive in IHn.\n    rewrite <- double_negation in IHn.\n    apply IHn.\n    apply H.\nQed.\n\nLemma not_odd_n__even_n : forall n, ~odd n -> even n.\nProof.\n  intros n H.\n  apply not_odd_n__odd_Sn in H.\n  apply odd_Sn__even_n.\n  apply H.\nQed.\n\nLemma not_even_n__odd_n : forall n, ~even n -> odd n.\nProof.\n  intros n H.\n  apply not_even_n__even_Sn in H.\n  apply even_Sn__odd_n.\n  apply H.\nQed.\n\nLemma not_odd_Sn__odd_n : forall n, ~odd (S n) -> odd n.\nProof.\n  intros n H.\n  apply not_odd_n__odd_Sn in H.\n  apply odd_SSn__odd_n.\n  apply H.\nQed.\n\nLemma not_even_Sn__even_n : forall n, ~even (S n) -> even n.\nProof.\n  intros n H.\n  apply not_even_n__even_Sn in H.\n  apply even_SSn__even_n.\n  apply H.\nQed.\n\nLemma nat_odd_or_even : forall n, even n \\/ odd n.\nProof.\n  intros n.\n  induction n as [|n' [Hl | Hr]].\n  - left. exists 0. reflexivity.\n  - right. apply even_n__odd_Sn. apply Hl.\n  - left. apply odd_n__even_Sn. apply Hr.\nQed.\n\nLemma odd_n__even_n__false : forall n, odd n /\\ even n -> False.\nProof.\n  intros n [Hl Hr].\n  apply even_n__not_odd_n in Hr.\n  apply Hr in Hl.\n  apply Hl.\nQed.\n\nLemma even_n__even_m__even_plus_n_m : forall n m, even n /\\ even m -> even (n + m).\nProof.\n  intros n m [[l Hl] [r Hr]].\n  rewrite Hl, Hr.\n  rewrite <- plus_associative.\n  rewrite (plus_commutative (l + l) r).\n  rewrite <- plus_associative.\n  rewrite (plus_commutative r l).\n  exists (l + r).\n  rewrite <- plus_associative.\n  reflexivity.\nQed.\n\nLemma even_plus_n_m__even_n__even_m : forall n m, even (n + m) /\\ even n -> even m.\nProof.\n  intros n m [[l Hl] [r Hr]].\n  induction l as [|l IHl].\n  - apply plus_result_0 in Hl.\n    destruct Hl as [Hll Hlr].\n    exists 0. apply Hlr.\nQed.", "meta": {"author": "qawbecrdtey", "repo": "All-of-even-and-odd", "sha": "a0c270342b0f89a0b8671c2c2a4a5879aecaf4bc", "save_path": "github-repos/coq/qawbecrdtey-All-of-even-and-odd", "path": "github-repos/coq/qawbecrdtey-All-of-even-and-odd/All-of-even-and-odd-a0c270342b0f89a0b8671c2c2a4a5879aecaf4bc/All_of_even_and_odd_0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7930081259955122}}
{"text": "(*\n  Some exercises come from Software Foundations Book1 CH3.\n  Author : Brethland.\n*)\n\nFrom Coq Require Import Setoid.\n\nFixpoint evenb(n : nat) :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nInductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair n m => n\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair n m => m\n  end.\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nLemma snd_fst_is_swap : forall p : natprod, (snd p, fst p) = swap p.\nProof.\n  intros.\n  destruct p as [n m].\n  simpl.\n  auto.\nQed.\n\nLemma fst_swap_is_snd : forall p : natprod, fst (swap p) = snd p.\nProof.\n  intros.\n  destruct p as [n m].\n  simpl.\n  auto.\nQed.\n\nInductive natlist: Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> 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 repeat (n count : nat) :natlist :=\n  match count with\n  | O => nil\n  | S count' => cons n (repeat n count')\n  end.\n\nFixpoint length (p : natlist) : nat :=\n  match p with\n  | nil => O\n  | x :: l => S (length l)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | x :: y => x :: (app y l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                      (right associativity , at level 60).\n\nDefinition hd(default : nat) (l : natlist) :=\n  match l with\n  | nil => default\n  | x :: y => x\n  end.\n\nDefinition tl(l : natlist) := \n  match l with\n  | nil => nil\n  | x :: y => y\n  end.\n\nFixpoint beq_n (n m :nat) :=\n  match n , m with\n  | O, O => true\n  | O, S m' => false\n  | S n', O => false\n  | S n', S m' => beq_n n' m'\n  end.\n\nLemma beq_n_refl : forall n : nat, beq_n n n = true.\nProof.\n  intros.\n  induction n.\n  - auto.\n  - trivial.\nQed.\n\nFixpoint nonzero (l : natlist) :=\n  match l with\n  | nil => nil\n  | x :: y => if beq_n x O then nonzero y\n                            else x :: nonzero y\n  end.\n\nFixpoint oddnumbers (l : natlist) :=\n  match l with \n  | nil => nil\n  | x :: y => match evenb x with \n                    | true => oddnumbers y\n                    | false => x :: oddnumbers y\n                    end\n  end.\n\nDefinition conutoddnumbers (l : natlist) :=\n  length (oddnumbers l).\n\nInductive tree a :=\n  | leaf\n  | node : tree a -> a -> tree a -> tree a.\n\nCheck nat_rect.\nCheck nat_ind.\nCheck nat_rec.\n\n\nCheck tree_ind.\n\nFixpoint alternative (l1 l2 : natlist ) :natlist :=\n  match l1,l2 with\n  | nil,_ => l2\n  | _,nil => l1\n  | x :: y , z :: p => x :: z :: (alternative y p)\n  end.\n\nDefinition bag := natlist.\n\nFixpoint count (ele: nat) (s : bag) :=\n  match s with\n  | nil => O\n  | x :: y => match beq_n ele x with\n              | true => S (count ele y)\n              | false => count ele y\n            end\n  end.\n\nDefinition sum : bag -> bag -> bag := app.\n\nDefinition add (v : nat) (s : bag) :=\n  v :: s.\n\nDefinition member(v : nat) (s : bag) :=\n  match count v s with\n  | O => false\n  | _ => true\n  end.\n\nFixpoint remove_one (v : nat) (s : bag) :=\n  match s with\n  | nil => nil\n  | x :: y => match beq_n v x with\n              | true => y\n              | false => x :: (remove_one v y)\n             end\n  end.\n\nFixpoint remove_all (v : nat) (s : bag) :=\n  match s with\n  | nil => nil\n  | x :: y => match beq_n v x with\n              | true => (remove_all v y)\n              | false => x :: (remove_all v y)\n             end\n  end.\n\nFixpoint subset (s1 s2 :bag) :=\n  match s1 with\n  | nil => true\n  | x :: y => if member x s2 then subset y (remove_one x s2)\n                              else false\n  end.\n\nLemma add_and_cons: forall (x : nat) (s : bag), add x s = x :: s.\nProof.\n  auto.\nQed.\n\n(* Lemma add_1_for_count: forall (b : nat) (s : bag), count b s = 0 -> count b (add b s) = 1.\nProof.\n  intros.\n  destruct s.\n  - simpl. rewrite <- H. simpl.\n    induction b.\n    + auto.\n    + apply IHb. simpl. auto.\n  - rewrite -> add_and_cons.\n\n    induction b.\n    + rewrite <- H. auto.\nAbort. *)\n\nLemma silly_lemma_that_you_dont_need_if_you_use_std_lib : forall p : nat,\n  beq_n p p = true.\nProof.\n  intro.\n  induction p.\n  - trivial.\n  - simpl.\n    rewrite IHp.\n    reflexivity.\nQed.\n\nLemma add_1_for_count: forall (b : nat) (s : bag),\n  count b s = 0 -> count b (b :: s) = 1.\nProof.\n  intros.\n  unfold count.\n  rewrite silly_lemma_that_you_dont_need_if_you_use_std_lib.\n  fold count.\n  rewrite H.\n  auto.\nQed.\n\nFixpoint rev (l : natlist) :=\n  match l with\n  | nil => nil\n  | x :: s => rev s ++ [x]\n  end.\n\nCompute (rev [1;2;3]).\n\nLemma app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros.\n  induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl.\n    auto.\nQed.\n\nLemma silly_pred : forall n : nat, n + 1 = S n.\nProof.\n  intros.\n  induction n.\n  - auto.\n  - simpl.\n    rewrite <- IHn.\n    auto.\nQed.\n\n\nLemma rev_length : forall l : natlist,\n  length l = length (rev l).\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    rewrite -> app_length,silly_pred.\n    rewrite <- IHl.\n    auto.\nQed.\n\nLemma app_nil_r : forall l : natlist, l ++ [] = l.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    rewrite -> IHl.\n    auto.\nQed.\n\nLemma app_assoc : forall l1 l2 l3 : natlist,\n  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n  intros.\n  induction l1.\n  - auto.\n  - simpl.\n    rewrite <- IHl1.\n    auto.\nQed.\n\n\nLemma rev_app_distr : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1.\n  - simpl. \n    rewrite -> app_nil_r.\n    auto.\n  - simpl.\n    rewrite -> IHl1.\n    rewrite <- app_assoc.\n    auto.\nQed.\n\nLemma rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> IHl.\n    auto.\nQed.\n\n(* Lemma app_assoc4: forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = (l1 ++ (l2 ++ l3)) ++ l4.\nProof.\n  intros.\n  induction l1.\n  - rewrite -> app_assoc.\n    simpl.\n    rewrite -> app_assoc.\n    auto.\n  - simpl.\n    rewrite -> IHl1.\n    auto.\nQed. *)\n\nLemma app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = (l1 ++ (l2 ++ l3)) ++ l4.\nProof.\n  intros.\n  rewrite 3 app_assoc.\n  auto.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzero (l1 ++ l2) = (nonzero l1) ++ (nonzero l2).\nProof.\n  intros.\n  induction l1.\n  - auto.\n  - destruct n.\n    + auto.\n    + simpl.\n      rewrite -> IHl1.\n      auto.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) :=\n  match l1 with\n  | nil => match l2 with\n           | nil => true\n           | x :: s => false\n          end\n  | x :: s => match l2 with\n            | nil => false\n            | y :: t => if beq_n x y then beq_natlist s t\n                                    else false\n          end\n  end.\n\nCompute (beq_natlist [1;2;3] [1;2;4]).\n\nLemma beq_natlist_refl : forall l : natlist,\n  beq_natlist l l = true.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    rewrite -> beq_n_refl.\n    trivial.\nQed.\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\nLemma count_member_nonzero : \n  forall (s : bag), leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros.\n  induction s.\n  - auto.\n  - trivial.\nQed.\n\nLemma ble_n_Sn : forall n : nat,\n  leb n (S n) = true.\nProof.\n  intros.\n  induction n.\n  - auto.\n  - simpl. rewrite -> IHn.\n    auto.\nQed.\n\nLemma remove_does_not_increase_count :\n  forall (s : bag), leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros.\n  induction s.\n  - auto.\n  - destruct n.\n    + simpl. rewrite -> ble_n_Sn.\n      auto.\n    + simpl.\n      trivial.\nQed.\n\nLemma rev_app : forall (n : nat) (l : natlist),\n  rev (n :: l) = rev l ++ [n].\nProof.\n  intros.\n  induction l.\n  - auto.\n  - auto.\nQed.\n\nCheck f_equal.\n\nLemma rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros. rewrite <- rev_involutive. \n  rewrite <- H.\n  rewrite  rev_involutive. auto.\nQed. \n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nDefinition hd_error (l : natlist) :=\n  match l with\n  | nil => None\n  | x :: s => Some x\n  end.\n\nDefinition option_elim (n : natoption) (d : nat) :=\n  match n with\n  | Some n' => n'\n  | None => d\n  end.\n\nLemma option_elim_hd : forall (l : natlist) (d : nat),\n  hd d l = option_elim (hd_error l) d.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - auto.\nQed.\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (a b : id) :=\n  match a,b with\n  | Id a', Id b' => beq_n a' b'\n  end.\n\nLemma beq_id_refl : forall x : id, beq_id x x = true.\nProof.\n  intros.\n  destruct x.\n  - simpl.\n    apply beq_n_refl.\nQed.\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) :=\n  record x value d.\n\nFixpoint find (x : id) (d : partial_map) :=\n  match d with\n  | empty => None\n  | record y v d' => if beq_id x y then Some v\n                                else find x d'\n  end.\n\nLemma update_eq : forall (d : partial_map) (x : id) (o : nat),\n  find x (update d x o) = Some o.\nProof.\n  intros.\n  simpl.\n  rewrite -> beq_id_refl.\n  auto.\nQed.\n\nLemma update_neq : forall (d : partial_map) (x y : id) (o : nat),\n  beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros.\n  simpl.\n  rewrite -> H.\n  auto.\nQed.\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\nDefinition bazp (b : baz) := Baz2 b true.\n\nDefinition baz_elim (b : baz) :=\n  match b with\n  | Baz1 b' => b'\n  | Baz2 b' _ => b'\n  end.\n\nLemma baz_exp : forall b : baz, baz_elim (bazp b) = b.\nProof.\n  intros.\n  destruct b.\n  - auto.\n  - auto.\nQed.\n\n \n\n\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/Coq07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.7929206623034897}}
{"text": "\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  exists x. reflexivity.\nQed.\n\nLemma refl x :\n  x <= x.\nProof.\n  exists 0. lia.\nQed.\n\nLemma trans x y z :\n  x <= y -> y <= z -> x <= z.\nProof.\n  intros [k <-] [l <-].\n  exists (k + l). lia.\nQed.\n\nLemma antisym x y :\n  x <= y -> y <= x -> x = y.\nProof.\n  intros [k Hk] [l Hl]. lia.\nQed.\n\nLemma shift x y :\n  S x <= S y <-> x <= y.\nProof.\n  split; intros [k Hk].\n  - exists k. lia.\n  - exists k. lia.\nQed.\n\nLemma strict x :\n  ~ x < x.\nProof.\n  intros [k Hk]. lia.\nQed.\n\nLemma minimum x :\n  ~ x < 0.\nProof.\n  intros [k Hk]. lia.\nQed.\n\n\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  - destruct y; reflexivity.\n  - exact IH.\nQed.\n\nLemma le_add_sub x y :\n  x <= y -> x + (y - x) = y.\nProof.\n  intros [k <-]. rewrite add_sub_eq. reflexivity.\nQed.\n\n\n\n(*** Exercise 9.3 ***)\n\nLemma linearity :\n  forall n m, n <= m \\/ m <= n.\nProof.\n induction n; destruct m.\n - left. exists 0. reflexivity.\n - left. exists (S m). reflexivity.\n - right. exists (S n). reflexivity.\n - destruct (IHn m) as [[k H]|[k H]].\n   + left. exists k. lia.\n   + right. exists k. lia.\nQed.\n\nLemma trichotomy : \n  forall n m, n < m \\/ n = m \\/ m < n.\nProof.\n induction n; destruct m.\n - right. left. reflexivity.\n - left. exists m. reflexivity.\n - right. right. exists n. reflexivity.\n - destruct (IHn m) as [[k H]|[H|[k H]]].\n   + left. exists k. lia.\n   + right. left. congruence.\n   + right. right. exists k. lia.\nQed.\n\n(* The stronger statements using + have (almost) the same proof scripts\n   and of course imply the weaker statements using ∨. *)\n  \nLemma linearity_sum :\n  forall n m, {n <= m} + {m <= n}.\nProof.\n induction n; destruct m.\n - left. exists 0. reflexivity.\n - left. exists (S m). reflexivity.\n - right. exists (S n). reflexivity.\n - destruct (IHn m) as [H|H].\n   + left. destruct H as [k H]. exists k. lia.\n   + right. destruct H as [k H]. exists k. lia.\nQed.\n\nLemma trichotomy_sum :\n  forall n m, {n < m} + {n = m} + {m < n}.\nProof.\n induction n; destruct m.\n - left. right. reflexivity.\n - left. left. exists m. reflexivity.\n - right. exists n. reflexivity.\n - destruct (IHn m) as [[H|H]|H].\n   + left. left. destruct H as [k H]. exists k. lia.\n   + left. right. congruence.\n   + right. destruct H as [k H]. exists k. lia.\nQed.\n\nLemma not_lt_le x y :\n  ~ (y < x) -> x <= y.\nProof.\n  intros HX. destruct (trichotomy x y) as [H|[H|H]]; trivial.\n  - destruct H as [k <-]. exists (S k). lia.\n  - subst. apply refl.\n  - contradiction.\nQed.\n\nLemma not_lt_eq x y :\n  ~ (x < y) -> ~ (y < x) -> x = y.\nProof.\n  intros H1 H2. apply antisym; now apply not_lt_le.\nQed.\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  destruct (x - y) eqn : H.\n  - left. now apply le_iff.\n  - right. intros H' % le_iff.\n    congruence.\nQed.\n\nLemma le_dec' x y :\n  dec (x <= y).\nProof.\n  revert y. induction x; intros [].\n  - left. apply origin.\n  - left. apply origin.\n  - right. apply minimum.\n  - destruct (IHx n) as [H|H].\n    + left. now apply shift.\n    + right. intros H'. now apply H, shift.\nQed.\n\nFixpoint le_bool (x y : nat) : bool :=\n  match x, y with \n  | 0, y => true\n  | S x, 0 => 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  revert y. induction x; intros []; cbn.\n  - split; trivial. intros _. apply refl.\n  - split; trivial. intros _. apply origin.\n  - split; try congruence. now intros H % minimum.\n  - (* propositional equivalences can be used for rewriting: *)\n    rewrite shift. apply IHx.\nQed.\n\n\n\n(*** Exercise 9.5 ***)\n\nLemma nat_dec (x y : nat) :\n  dec (x = y).\nProof.\n  destruct (trichotomy_sum x y) as [[H|H]|H].\n  - right. intros ->. now apply strict in H.\n  - now left.\n  - right. intros ->. now apply strict in H.\nQed.\n\nEnd LE.\n\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\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 destruct x.\n - right. intros [H _]. now apply H.\n - destruct (M y x) eqn : H.\n   + left. split; try congruence. exists (D y x).\n     rewrite (DM_spec1 y x) at 1. lia.\n   + right. intros [_ [k H']].\n     destruct (div_mod_unique x (D y x) (M y x) k 0).\n     * apply DM_spec2.\n     * lia.\n     * rewrite <- (DM_spec1 y x). lia.\n     * congruence.\nQed.\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  destruct (le_lt_dec x y) as [H|H].\n  - destruct (divides_dec k (y - x)) as [H'|H'].\n    + left. left. now split.\n    + right. intros [[H1 H2]|[H1 H2]]; auto. lia.\n  - destruct (divides_dec k (x - y)) as [H'|H'].\n    + left. right. now split.\n    + right. intros [[H1 H2]|[H1 H2]]; auto. lia.\nQed.\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  intros HM f [n Hn]. exists (mu f n). destruct (f (mu f n)) eqn : H.\n  - split; trivial. intros n' Hn'. apply HM in H.\n    destruct (le_lt_dec (mu f n) n'); trivial.\n    apply H in l. congruence.\n  - exfalso. apply HM in H as [_ H].\n    assert (H' : n <= n) by lia.\n    specialize (H n H'). congruence.\nQed.\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    induction n as [|n IH].\n    - rewrite R1. destruct (f 0) eqn:H1.\n      + intuition. lia.\n      + intuition. assert (k=0) as -> by lia. exact H1.\n    - rewrite R2. destruct (f (mu n)) eqn:H1.\n      + rewrite H1. intuition.\n      + destruct (f (S n)) eqn:H2.\n        * intuition.\n        * intuition.\n          assert (k = S n \\/ k <= n) as [->|H4] by lia; auto.\n  Qed.\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    induction n as [|n IH].\n    - congruence.\n    - rewrite R2, R2'. rewrite <-IH. reflexivity.\n  Qed.\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    intros *. generalize (R n). destruct (f (mu n)) eqn:H1; lia.\n  Qed.\n\n  Goal forall n k, k < mu n -> f k = false.\n  Proof.\n    intros *. generalize (R n).\n    destruct (f (mu n)) eqn:H1; intuition.\n  Qed.\n\n  Goal forall n, mu n < n -> f (mu n) = true.\n  Proof.\n     intros *. generalize (R n).\n     destruct (f (mu n)) eqn:H1; intuition.\n  Qed.\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  Lemma L1 n :\n    ~ mu n < n -> mu n = n.\n  Proof.\n    specialize (R1 n). lia.\n  Qed.\n\n  Goal mu 0 = 0.\n  Proof.\n    generalize (R1 0). lia.\n  Qed.\n\n  Lemma not_lt_eq' x y :\n    ~ x < y -> ~ y < x -> x = y.\n  Proof.\n    intros H1 H2. lia.\n  Qed.\n\n  Goal forall n, mu (S n) = if f (mu n) then mu n else S n.\n  Proof.\n    intros n. destruct (f (mu n)) eqn:H1.\n    - apply not_lt_eq'; intros H2.\n      + assert (H3: f (mu (S n)) = false) by eapply R2, H2.\n        enough (f (mu (S n)) = true) by congruence.\n        apply R3. specialize (R1 n). lia.\n      + apply R2 in H2. congruence.\n    - assert (H2: mu n = n).\n      { apply L1. intros H2%R3. congruence. }\n      apply L1. intros H3.\n      assert (H4: f (mu (S n)) = true) by apply R3, H3.        \n      assert (mu (S n) = n \\/ mu (S n) < mu n) as [H5|H5] by lia.    \n      + congruence.\n      + apply R2 in H5. congruence.\n  Qed.\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    intros x y H. apply (div_mod_unique y (D x y) (M x y) (S (D (x - S y) y)) (M (x - S y) y)).\n    - apply DM2.\n    - apply DM2.\n    - generalize (DM1 x y) (DM1 (x - S y) y). lia.\n  Qed.\n\n  Goal forall x y, x <= y -> D x y = 0.\n  Proof.\n    intros x y H. apply (div_mod_unique y (D x y) (M x y) 0 x).\n    - apply DM2.\n    - apply H.\n    - cbn. symmetry. apply DM1.\n  Qed.\n\nEnd Challenge.\n  \n  \n\n\n\n\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. apply H.\n  enough (G : forall n y, f y < n -> p y) by apply G.\n  intros n. induction n; intros y Hy.\n  - exfalso. lia.\n  - apply H. intros z HZ. apply IHn. lia.\nQed.\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 nat (fun n => n)).\nQed.\n\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  (* the pattern \"in a' |-*\" generalises a' in the induction *)\n  induction a as [|a IH] in a' |-*; destruct a'; cbn.\n  - tauto.\n  - intros ->. exfalso. lia.\n  - intros <-. exfalso. lia.\n  - (* the = in the intro pattern applies injectivity *)\n    intros [= H3]. destruct (IH a') as [-> ->]; lia.\nQed.\n\nTheorem div_mod x y :\n  { a & { b & x = a * S y + b /\\ b <= y}}.\nProof.\n  induction x as [x IH] using complete_induction.\n  destruct (le_lt_dec x y) as [H|H].\n  - exists 0, x. split; trivial.\n  - destruct (IH (x - S y)) as (a&b&H2&H3).\n    + lia.\n    + exists (S a), b. lia.\nQed.\n\nDefinition D (x y : nat) := projT1 (div_mod x y).\nDefinition M (x y : nat) := projT1 (projT2 (div_mod x y)).\n\nLemma DM_spec1 x y :\n  x = D x y * S y + M x y.\nProof.\n  apply (projT2 (projT2 (div_mod x y))).\nQed.\n\nLemma DM_spec2 x y :\n  M x y <= y.\nProof.\n  apply (projT2 (projT2 (div_mod x y))).\nQed.\n\n", "meta": {"author": "NeuralCoder3", "repo": "nat_seq", "sha": "cbfc618bd1098fb7d5ced1df168a5c6f5d2f190f", "save_path": "github-repos/coq/NeuralCoder3-nat_seq", "path": "github-repos/coq/NeuralCoder3-nat_seq/nat_seq-cbfc618bd1098fb7d5ced1df168a5c6f5d2f190f/other_coind/other.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.79292065731649}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq.\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\nSection Order.\n\n  Context {T: eqType}.\n  Variable rel: T -> T -> bool.\n  Variable l: seq T.\n  \n  Definition total_over_list :=\n    forall x1 x2,\n      x1 \\in l ->\n      x2 \\in l ->\n      (rel x1 x2 \\/ rel x2 x1).\n      \n  Definition antisymmetric_over_list :=\n    forall x1 x2,\n      x1 \\in l ->\n      x2 \\in l ->\n      rel x1 x2 ->\n      rel x2 x1 ->\n      x1 = x2.\n\nEnd Order.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7928263856020149}}
{"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 Max Omega List Permutation.\n\nRequire Import list_in.\n\nSet Implicit Arguments.\n\nFact In_map_nat_find X (f : X -> nat) x l : In x (map f l) -> { u | x = f u /\\ In u l }.\nProof.\n  induction l as [ | y l IH ].\n  intros [].\n  destruct (eq_nat_dec x (f y)) as [ | C ].\n  exists y; split; auto; left; auto.\n  intros H.\n  destruct IH as (u & H1 & H2).\n  destruct H; auto; contradict C; auto.\n  exists u; split; auto; right; auto.\nQed.\n\nNotation lsum := (fold_right plus 0).\n \nFact lsum_prop x ll : In x ll -> x <= lsum ll.\nProof.\n  induction ll as [ | y ll IH ]; simpl.\n  intros [].\n  intros [ | H ]; subst.\n  omega.\n  specialize (IH H); omega.\nQed.\n\nFact lsum_perm l m : Permutation l m -> lsum l = lsum m.\nProof.\n  induction 1; simpl; auto; omega.\nQed.\n\nFact lsum_app l r : lsum (l++r) = lsum l + lsum r.\nProof.\n  induction l; simpl; auto; omega.\nQed.\n\nSection lmax.\n\n  Definition lmax := fold_right max 0.\n  \n  Fact lmax_fix x l : lmax (x::l) = max x (lmax l).\n  Proof. auto. Qed.\n\n  Fact Forall2_lmax ll mm : Forall2 le ll mm -> lmax ll <= lmax mm.\n  Proof.\n    induction 1; auto.\n    do 2 rewrite lmax_fix.\n    apply max_lub.\n    apply le_trans with (2 := le_max_l _ _); auto.\n    apply le_trans with (2 := le_max_r _ _); auto.\n  Qed.\n\n  Fact lmax_In x ll : In x ll -> x <= lmax ll.\n  Proof.\n    induction ll as [ | y ll IH ].\n    simpl; omega.\n    rewrite lmax_fix.\n    intros [ H | H ]; subst.\n    apply le_max_l.\n    apply le_trans with (1 := IH H), le_max_r.\n  Qed.\n  \n  Fact lmax_inv l : { l = nil } + { In (lmax l) l }.\n  Proof.\n    induction l as [ | x l IHl ].\n    left; auto.\n    right.\n    simpl.\n    destruct IHl.\n    subst; left; simpl.\n    rewrite max_0_r; auto.\n    destruct (le_lt_dec x (lmax l)).\n    right; rewrite max_r; auto.\n    left; rewrite max_l; auto.\n    apply lt_le_weak; assumption.\n  Qed.\n\n  Fact lmax_inv' l : 0 < lmax l -> { x | In x l /\\ x = lmax l }.\n  Proof.\n    intros H0; destruct (lmax_inv l) as [ H | H ].\n    exfalso; subst; simpl in H0; omega.\n    exists (lmax l); auto.\n  Qed.\n  \n  Fact lmax_map_inv X (f : X -> nat) l : l <> nil -> { x | In x l /\\ f x = lmax (map f l) }.\n  Proof.\n    intros H0.\n    destruct (lmax_inv (map f l)) as [ H | H ].\n    contradict H0.\n    destruct l; auto; discriminate H.\n    apply In_map_nat_find in H.\n    destruct H as (u & ? & ?); exists u; auto.\n  Qed.\n\n  Fact lmax_inv_t l : 0 < lmax l -> { x : _ & { _ : In_t x l | x = lmax l } }.\n  Proof.\n    induction l as [ | x l IH ].\n    simpl; omega.\n    intros H0.\n    destruct (eq_nat_dec (lmax l) 0) as [ H1 | H1 ].\n\n    rewrite lmax_fix, H1, max_0_r in H0.\n    exists x; split; simpl; auto.\n    rewrite H1, max_0_r; auto.\n    \n    destruct IH as (z & H2 & H3).\n    omega.\n    destruct (le_lt_dec x z) as [ H4 | H4 ].\n    exists z; split; simpl; auto.\n    rewrite max_r; omega.\n    exists x; split; simpl; auto.\n    rewrite max_l; omega.\n  Qed.\n\n  Fact lmax_0_inv l : lmax l = 0 -> (In_t 0 l + { l = nil })%type.\n  Proof.\n    destruct l as [ | x l ].\n    right; auto.\n    rewrite lmax_fix.\n    intros H.\n    destruct (max_dec x (lmax l)) as [ E | E ];\n    rewrite H in E.\n    subst x; left; left; auto.\n    rewrite <- E, max_0_r in H.\n    subst x; left; left; auto.\n  Qed.\n  \n  Fact lmax_app l m : lmax (l++m) = max (lmax l) (lmax m).\n  Proof.\n    induction l as [ | x l IH ]; simpl; auto.\n    rewrite IH; apply max_assoc.\n  Qed.\n  \n  Variable (f : nat -> nat) (Hf : forall m n, m <= n -> f m <= f n).\n  \n  Fact max_monotone n m : f (max n m) = max (f n) (f m).\n  Proof.\n    symmetry; destruct (max_dec n m) as [ H | H ]; rewrite H.\n    apply max_l, Hf; rewrite <- H; apply le_max_r.\n    apply max_r, Hf; rewrite <- H; apply le_max_l.\n  Qed.\n  \n  Fact lmax_mono l : l <> nil -> lmax (map f l) = f (lmax l).\n  Proof.\n    induction l as [ | x [ | y l ] IH ]; simpl.\n    intros H; contradict H; auto.\n    do 2 rewrite max_0_r; auto.\n    intros _; rewrite max_monotone; f_equal.\n    apply IH; discriminate.\n  Qed.\n  \nEnd lmax.\n\nFixpoint list_n n := match n with 0 => nil | S n => n::list_n n end.\n  \nFact list_n_prop n x : x < n <-> In x (list_n n).\nProof.\n  revert x; induction n as [ | ? IH ]; intros ?.\n  split. \n  omega.\n  intros [].\n  simpl; rewrite <- IH.\n  split; omega.\nQed.\n\nFact list_n_length x : length (list_n x) = x.\nProof. induction x; simpl; f_equal; auto. Qed.\n\nFact largest_nat_prefix n (P : nat -> Prop) : (forall i, i <= n -> { P i } + { ~ P i })\n                                           -> P 0\n                                           -> { i | i <= n \n                                                 /\\ P i \n                                                 /\\ (P (S i) -> n <= i) \n                                                 /\\ forall j, j <= i -> P j }.\nProof.\n  revert P.\n  induction n as [ | n IHn ]; intros P HP H.\n\n  exists 0.\n  repeat split; auto.\n  intros j Hj.\n  cutrewrite (j = 0); auto; omega.\n  \n  destruct (HP 1) as [ H1 | H1 ]; try omega.\n\n  destruct (IHn (fun x => P (S x))) as (i & H3 & H4 & H5 & H6); auto.\n  intros; apply  HP; omega.\n  exists (S i); repeat split; auto. \n  omega.\n  intros H'; apply H5 in H'; omega.\n  intros [ | j ]; auto.\n  intros H7; apply H6; omega.\n  \n  exists 0; repeat split; auto.\n  omega.\n  tauto.\n  intros j Hj; cutrewrite (j=0); auto; omega.\nQed.\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_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.853912754810561, "lm_q1q2_score": 0.7927801113982818}}
{"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 := true | 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.\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 (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.\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 (b_1:bool) (b_2:bool) (b_3:bool) : bool :=\n  b_1 && b_2 && b_3.\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 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\nInductive bit : Type := B0 | 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  | (bits _ _ _ _) => false\n  end.\n\nCompute all_zero (bits B1 B0 B1 B0).\nCompute all_zero (bits B0 B0 B0 B0).\n\nModule NatPlayground.\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 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  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  Compute plus 3 2.\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  Example test_mult1: (mult 3 3) = 9.\n  Proof. simpl. reflexivity. Qed.\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.\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 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\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).\n\nFixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | O, _ => false\n  | _, O => false\n  | S n', S m' => eqb n' m'\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n, m with\n  | O, _ => true\n  | S _, 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.\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition ltb (n m : nat) : bool :=\n  match n, m with\n  | _, O => false\n  | O, _ => true\n  | S _, S m' => leb n m'\n  end.\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, 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.\n\nProof.\n  (* move both quantifiers into ctx *)\n  intros n m.\n  (* move hypothesis into ctx *)\n  intros H.\n  (* rewrite goal using hypothesis *)\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.\n\nProof.\n  intros n m o.\n  intros H I.\n  rewrite -> H.\n  rewrite -> I.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus: forall n m : nat,\n  (0 + n) * m = n * m.\n\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_l: forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\n\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry: forall n : nat,\n  (n + 1) =? 0 = false.\n\nProof.\n  intros n.\n  simpl.\nAbort.\n\nTheorem plus_1_neq_0: forall n : nat,\n  (n + 1) =? 0 = false.\n\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive: forall b : bool,\n  negb (negb b) = b.\n\nProof.\n  intros b.\n  destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative: forall b c,\n  andb b c = andb c b.\n\nProof.\n  intros b c.\n  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: forall b c d,\n  andb (andb b c) d = andb (andb b d) c.\n\nProof.\n  intros b c d.\n  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.\n\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative'': forall b c,\n  andb b c = andb c b.\n\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.\n\nProof.\n  intros [] [] H.\n  - reflexivity.\n  - rewrite <- H.\n    reflexivity.\n  - reflexivity.\n  - rewrite <- H.\n    reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1: forall n : nat,\n  0 =? (n + 1) = false.\n\nProof.\n  intros [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n", "meta": {"author": "g-s-k", "repo": "logf", "sha": "4514dc722aceede1eb71ec653853965c3d30adc3", "save_path": "github-repos/coq/g-s-k-logf", "path": "github-repos/coq/g-s-k-logf/logf-4514dc722aceede1eb71ec653853965c3d30adc3/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.7927489750587664}}
{"text": "(* ================================================================= *)\n(** ** Booleans *)\n\n(** Another familiar enumerated type: *)\n\nInductive bool : Type :=\n  | true\n  | false.\n\n(** Booleans are also available from Coq's standard library, but\n    in this course we'll define everything from scratch, just to see\n    how it's done. *)\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(** Note the syntax for defining multi-argument\n    functions ([andb] and [orb]).  *)\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 define new symbolic notations for existing definitions. *)\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 write these function using Coq's \"if\" expressions.  *)\n\nDefinition negb' (b:bool) : bool :=\n  if b then false\n  else true.\n\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(** **** Exercise: 1 star, standard (nandb)\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    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    Hint: if [simpl] will not simplify the goal in your proof, it's\n    probably because you defined [nandb] without using a [match]\n    expression. Try a different definition of [nandb], or just\n    skip over [simpl] and go directly to [reflexivity]. We'll\n    explain this phenomenon later in the chapter. *)\n\nDefinition nandb (b1:bool) (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\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(** [] *)\n\n(** Most exercises are omitted from the \"terse\" version of the\n    notes used in lecture.\n    The \"full\" version contains both the assigned reading and all the\n    exercises for your homework assignment. *)", "meta": {"author": "ljdavns", "repo": "software-fundations", "sha": "78a537ff9327d9c936fb661ab94d2a3ba49fa83c", "save_path": "github-repos/coq/ljdavns-software-fundations", "path": "github-repos/coq/ljdavns-software-fundations/software-fundations-78a537ff9327d9c936fb661ab94d2a3ba49fa83c/basics/B_boolean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.9416541626630935, "lm_q1q2_score": 0.7927086324445906}}
{"text": "From AG Require Export Basics.\n\nCheck bin_to_nat. (*Export works*)\n\nDefinition  add_0_r : forall  n:nat, n + 0 = n.\nintro n. induction n  as [| n' IH].\n  - reflexivity.\n  - simpl. rewrite IH. reflexivity.\nDefined.\n\nDefinition  minus_n_n : forall  n, minus n n = 0.\n  intro n. induction n as [| n' IH].\n  - simpl. reflexivity.\n  - simpl. apply IH.\nDefined.\n\nDefinition mul_0_r : forall n : nat, n * 0 = 0.\n  intro n. induction n as [| n' IH].\n  - simpl. reflexivity.\n  - simpl. apply IH.\nDefined.\n\nDefinition plus_n_Sm : forall n m : nat, S (n + m) = n + (S m).\n  intros n m. induction n as [| n' IH].\n  - simpl. reflexivity.\n  - simpl. rewrite IH. reflexivity.\nDefined.\n\nDefinition add_comm : forall n m : nat, n + m = m + n.\n  intros n m. induction m as [|m IHm].\n  - simpl. rewrite (add_0_r n). reflexivity.\n  - simpl. rewrite <-  plus_n_Sm. rewrite IHm. reflexivity.\nDefined.\n\nDefinition add_assoc : forall  n m p : nat,  n + (m + p) = (n + m) + p.\n  intros n m p. induction n as [|n IHn].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nDefined.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nDefinition double_plus : forall n, double n = n + n.\n  intro n. induction n as [| n IHn].\n  - simpl. reflexivity.\n  -  simpl. rewrite IHn. Search plus. rewrite plus_n_Sm. reflexivity.\nDefined.\n\nDefinition even_S : forall n : nat, even (S n) = negb (even n).\n  intro n. induction n as [|n IHn].\n  - simpl. reflexivity.\n  - rewrite ->  IHn. simpl. Search negb. rewrite negb_involutive. reflexivity.\nDefined.\n\nDefinition plus_rearrange : forall n m p q : nat, (n + m) + (p + q) = (m + n) + (p + q).\n  intros n m p q. assert (H_comm : n + m = m + n).\n  {rewrite add_comm. reflexivity. }(*Note: Assertions are non-transparent*)\n  rewrite H_comm. reflexivity.\nDefined.\n\n(*Exercises*)\n\nDefinition add_shuffle3 : forall n m p : nat, n + (m+p) = m + (n + p).\n  intros n m p. destruct n as [| n Sn].\n  - simpl. reflexivity.\n  - Search plus. rewrite plus_Sn_m. rewrite plus_Sn_m. rewrite <-  plus_n_Sm. rewrite add_assoc. rewrite  (add_comm n m). rewrite add_assoc. reflexivity.\nDefined.\n\nDefinition mul_comm : forall n m : nat, n * m = m * n.\n  intros n m. induction n as [| n IHn].\n  - simpl. Search mult. rewrite <- mult_n_O. reflexivity.\n  - simpl. Search mult. rewrite <-  mult_n_Sm. rewrite IHn. rewrite add_comm. reflexivity.\nDefined.\n\nCheck leb.\n\nDefinition leb_refl : forall n : nat, (n <=? n) = true.\n  intro n. induction  n.\n  - simpl. reflexivity.\n  - simpl. assumption.\nDefined.\n\nDefinition zero_neqb_S : forall n : nat, 0 =? (S n) = false.\n  intro n. simpl. reflexivity.\nDefined.\n\nDefinition andb_false_r : forall b : bool, andb b false = false.\n  intro b. destruct b as [].\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nDefined.\n\nDefinition plus_leb_compat_1 : forall n m p : nat, n <=? m = true -> (p + n) <=? (p + m) = true.\n  intros n m p q. induction p as [| p IHp].\n  - simpl. assumption.\n  - simpl. assumption.\nDefined.\n\nDefinition S_neqb_0 : forall n : nat, (S n) =? 0 = false.\n  intro n. destruct n.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nDefined.\n\nDefinition mult_1_1 : forall n : nat, 1 * n = n.\n  intro n. rewrite mul_comm. Search mult. rewrite mult_n_1. reflexivity.\nDefined.\n\nDefinition all3_spec : forall b c : bool,\n    orb (andb b c) (orb (negb b) (negb c)) = true.\n  intros b c. destruct b.\n  - simpl. destruct c.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. reflexivity.\nDefined.\n\nDefinition mult_plus_distr_r : forall n m p : nat, (n + m) * p = (n * p) + (m * p).\n  intros n m p. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. rewrite add_assoc. reflexivity.\nDefined.\n\nDefinition mult_assoc : forall n m p : nat,\n    n * (m * p) = (n * m) * p.\n  intros n m p. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite mult_plus_distr_r. rewrite IHn. reflexivity.\nDefined.\n\nDefinition eqb_refl : forall n : nat, (n =? n) = true.\n  intro n. induction n.\n  - simpl. reflexivity.\n  - simpl. assumption.\nDefined.\n\n(*\"Replace\" tactic*)\n\nDefinition bin_to_nat_pres_incr : forall x : bin, bin_to_nat (incr x) = S (bin_to_nat x).\n  intro x. induction x.\n  - simpl. reflexivity.\n  - simpl. rewrite add_0_r. rewrite plus_n_Sm. rewrite <- plus_n_Sm. rewrite <- plus_n_Sm. rewrite add_0_r. reflexivity.\n  - simpl. rewrite_all add_0_r. rewrite <- plus_n_Sm. rewrite add_0_r. rewrite plus_n_Sm. rewrite IHx. rewrite <- plus_n_Sm. rewrite <-  (plus_n_Sm (bin_to_nat x) (bin_to_nat x)). reflexivity.\nDefined.\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\nDefinition nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n.\n  intro n. induction n.\n  - simpl. reflexivity.\n  - simpl. Search bin. rewrite bin_to_nat_pres_incr. rewrite IHn. reflexivity.\nDefined.\n", "meta": {"author": "agureev", "repo": "Coq-Files", "sha": "d5e70f7fe99a30319403a14ef39fb4bba67e248f", "save_path": "github-repos/coq/agureev-Coq-Files", "path": "github-repos/coq/agureev-Coq-Files/Coq-Files-d5e70f7fe99a30319403a14ef39fb4bba67e248f/SF/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7926993774412197}}
{"text": "Print bool.\n\nPrint bool_rect.\nPrint bool_ind.\nPrint bool_rec.\n\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\nRequire 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\nRequire 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(*\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 boolP_example : forall n : nat, n * n - 1 < n ^ n.\nProof.\nmove=> n.\ncase: (boolP (n == O)).\n  move/eqP.\n  move=> ->.\n  rewrite expn0.\n  rewrite muln0.\n  rewrite sub0n.\n  done.\nmove=> n0.\ncase: (boolP (n == 1)).\n  move/eqP.\n  move=> ->.\n  rewrite expn1.\n  rewrite muln1.\n  by rewrite subnn.\nmove=> n1.\nhave [m Hm] : exists m, n = m.+2.\n  case: n n0 n1 => //.\n  case=> // n _ _.\n  by exists n.\nrewrite Hm.\nrewrite expnS.  \nrewrite expnS.\nrewrite mulnA.\nrewrite subn1.\nrewrite prednK; last first.\n  by rewrite muln_gt0.\nrewrite leq_pmulr //.\nby rewrite expn_gt0.\nQed.\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": "ProofCafe", "repo": "AffeldtSsreflectTutorialNagoya", "sha": "4e4cb908306184e5c71e0e1b512836af3197bc26", "save_path": "github-repos/coq/ProofCafe-AffeldtSsreflectTutorialNagoya", "path": "github-repos/coq/ProofCafe-AffeldtSsreflectTutorialNagoya/AffeldtSsreflectTutorialNagoya-4e4cb908306184e5c71e0e1b512836af3197bc26/src/ssrbool_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7926993691529353}}
{"text": "Require Import Arith.Le.\n\nPrint ex.\n\n(*\nInductive ex (a : Type) (P : a -> Prop) : Prop :=\n| ex_intro : forall x : a, P x -> exists y, P y\n*)\n\nInductive ex2 (a:Type) (P:a -> Prop) : Prop :=\n| ex2_intro : forall (x:a), P x -> ex2 a P\n.\n\nArguments ex2 {a} _.\nArguments ex2_intro {a} {P} _ _.\n\n(* there exists n:nat, n + 3 = 5 *)\nLemma test1 : ex2 (fun (n:nat) => n + 3 = 5).\nProof. apply ex2_intro with 2. reflexivity. Qed.\n\nCheck ex2_intro.\n\nLemma test2 : ex2 (fun (n:nat) => n + 3 = 5).\nProof. apply (ex2_intro 2). reflexivity. Qed.\n\n\nLemma exist1 : exists (n:nat), n + 3 = 5.\nProof. exists 2. reflexivity. Qed.\n\nLemma exist2 : forall (n m:nat), (exists (p:nat), n + p = m) -> n <= m.\nProof.\n    intros n m [p H]. revert p n m H. induction p as [|p IH]; intros n m.\n    - intros H. rewrite <- plus_n_O in H. rewrite H. constructor.\n    - intros H. apply le_trans with (S n).\n        + constructor. constructor.\n        + apply IH. simpl. rewrite <- plus_n_Sm in 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/cpdt/ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.792640083259526}}
{"text": "(* Exercise 74 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\n(* A universal statement does not carry existential import,\n   but if we know the domain is not empty, then we can\n   prove that universal predication implies singular\n   predication of a property P *)\n\nHypothesis Domain : exists x1 : D, exists x2 : D, exists x3 : D,\n  forall x : D, (x = x1 \\/ x = x2 \\/ x = x3).\n\nTheorem exercise_074 : (forall x : D, P x) -> (exists x : D, P x).\nProof.\nexi_e (exists x1 : D, exists x2 : D, exists x3 : D,\n  forall x : D, (x = x1 \\/ x = x2 \\/ x = x3)) a a1.\n  hyp Domain.\nexi_e (exists x2 : D, exists x3 : D,\n  forall x : D, (x = a \\/ x = x2 \\/ x = x3)) b a2.\nhyp a1.\nexi_e (exists x3 : D,\n  forall x : D, (x = a \\/ x = b \\/ x = x3)) c a3.\nhyp a2.\nimp_i a4.\nexi_i a.\nall_e (forall x:D, P x) a.\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/Taak11/Taak11_pred074.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.792610209836527}}
{"text": "Require Export case.\nRequire String.\n(* Software Foundations Chapter 8 : Logic in Coq *)\n\n\n(**************************************************\n Exercise: 1 star, optional (proj2)\n**************************************************)\nTheorem proj2 : forall P Q : Prop,\n                  P /\\ Q -> Q.\nProof.\n  intros P Q E.\n  inversion E as [p q].\n  apply q.\nQed.\n\n\n\n(**************************************************\nExercise: 2 stars (and_assoc)\nIn the following proof, notice how the nested pattern in the inversion breaks the hypothesis H : P ∧ (Q ∧ R) down into 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. split. apply HP. apply HQ. apply HR.\nQed.\n\n\n\n(**************************************************\nExercise: 2 stars (even__ev)\nNow we can prove the other direction of the equivalence of even and ev, which we left hanging in chapter Prop. Notice that the left-hand conjunct here is the statement we are actually interested in; the right-hand conjunct is needed in order to make the induction hypothesis strong enough that we can carry out the reasoning in the inductive step. (To see why this is needed, try proving the left conjunct by itself and observe where things get stuck.)\n**************************************************)\nInductive ev : nat -> Prop :=\n  ev_0 : ev 0\n| ev_SS : forall n, ev n -> ev (S (S n)).\n\nFixpoint evenb n : bool :=\n  match n with\n    | O => true\n    | S O => false\n    | S (S n) => evenb n\n  end.\n\nDefinition even n : Prop := evenb n = true.\n\nTheorem even__ev : forall n : nat,\n                     (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  intros n.\n  induction n as [|nn].\n  split.\n  intro H. apply ev_0.\n  intro H. inversion H.\n  inversion IHnn as [E1 E2].\n  split.\n  apply E2.\n  intro H.\n  unfold even in H. simpl in H.\n  apply ev_SS.\n  generalize H.\n  unfold even in E1.\n  apply E1.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star, optional (iff_properties)\n  Using the above proof that ↔ is symmetric (iff_sym) as 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  intro H. apply H.\n  intro H. 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 HPQ HQR.\n  inversion HPQ as [HP2Q HQ2P]. inversion HQR as [HQ2R HR2Q].\n  split.\n  intro HP. \n  apply HQ2R in HP2Q. apply HP2Q. apply HP.\n  intro HR.\n  apply HQ2P in HR2Q. apply HR2Q. apply HR.\nQed.\n\n\n\n(**************************************************\n  Exercise: 2 stars (or_distributes_over_and_2)\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 [[HP1 | HQ ] [HP2 | HR]].\n  left. apply HP1. left. apply HP1. left. apply HP2.\n  right. split. apply HQ. apply HR.\nQed.\n\n\n\n(**************************************************\n Exercise: 1 star, optional (or_distributes_over_and)\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  intro H. split.\n  inversion H as [HP | [HQ  HR]].\n  left. apply HP. right. apply HQ.\n  inversion H as [HP | [HQ HR]].\n  left. apply HP. right. apply HR.\n  intro H. \n  inversion H as [[HP1 | HQ] [HP2 | HR]].\n  left. apply HP1. left. apply HP1. left. apply HP2.\n  right. split. apply HQ. apply HR.\nQed.\n\n\n\n(**************************************************\n Exercise: 2 stars, optional (bool_prop)\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. destruct c.\n  simpl in H. left. apply H.\n  simpl in H. right. apply H.\n  destruct c.\n  simpl in H. left. apply H.\n  simpl in H. left. apply H.\nQed.\n\nTheorem orb_prop : forall b c,\n                     orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b. destruct c.\n  simpl in H. left. apply H.\n  simpl in H. left. apply H.\n  destruct c.\n  simpl in H. right. apply H.\n  simpl in H. right. apply 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.\n  split.\n  destruct b. simpl in H. apply H.\n  destruct c. simpl in H. inversion H.\n  apply H.\n  destruct b. inversion H.\n  simpl in H. apply H.\nQed.\n\n(**************************************************\n Exercise: 2 stars, advanced (True)\n Define True as another inductively defined proposition. (The intution is that True should be a proposition for which it is trivial to give evidence.)\n **************************************************)\nInductive True : Prop :=\n| triv : True.\n\n(*** Check this constructor ***)\nTheorem check_true : forall A, A -> True.\nProof.\n  intros A H.\n  apply triv.\n Qed.\n\n(**************************************************\n Exercise: 2 stars, advanced (double_neg_inf)\n Write an informal proof of double_neg:\n **************************************************)\nTheorem double_neg_inf : forall P : Prop,\n                           P -> ~~P.\nProof. \n  intros P H1.\n  unfold not. intro H2.\n  apply H2 in H1.\n  inversion H1.\nQed.\n(** \nTheorem: P implies ~~P, for any proposition P.\nProof: Let P be some proposition. First consider ~P. This is equivalent to the statement that\nthe proposition P implies the proposition False. Now consider ~~P. This states the if ~P holds, then we can \nderive False. Therefore, the statement we are really trying to prove is P -> (P -> False) -> False. Assume P and P -> False. From these two assumptions we can derive False and use this evidence to complete the proof. \n**)\n\n(***\nTheorem double_neg_imp : forall P : Prop,\n                           ~~ P -> P.\nProof. \n  unfold not.\n  intros P H.\n  (no evidence to say anything else)\n***)\n\n(**************************************************\n  Exercise: 2 stars (contrapositive)\n **************************************************)\n\nTheorem contrapositive : forall P Q : Prop,\n                           (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q E1.\n  unfold not.\n  intros E2 E3.\n  apply E1 in E3.\n  apply E2 in E3.\n  apply E3.\nQed.  \n\n\n\n(**************************************************\n Exercise: 1 star (not_both_true_and_false)\n **************************************************)\nTheorem not_both_true_and_false : forall P : Prop,\n                                    ~ (P /\\ ~P).\nProof.\n  intros P. unfold not.\n  intros H.\n  inversion H as [P' P'False].\n  apply P'False in P'.\n  apply P'.\nQed.\n\n\n\n(**************************************************\n Exercise: 1 star, advanced (informal_not_PNP)\n Write an informal proof (in English) of the proposition ∀ P : Prop, ~(P ∧ ~P).\n**************************************************)\n(** Proof:\n Let ~(P /\\ ~P) be represented instead as P /\\ (P -> False) -> False. Assume the premises: P /\\ (P -> False). Using the left side of the conjunction (P) as evidence for the right (P -> False), we derive False. Use this derivation as evidence for the goal. \n**)\n\n\n\n(**************************************************\n Exercise: 1 star (ev_not_ev_S)\n\n Theorem five_not_even confirms the unsurprising fact that five 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  intro E. inversion E.\n  intro E. inversion E as [|nn HevS1 Hnh].\n  apply IHev in HevS1. inversion HevS1.\nQed.\n\n(**\nNote that some theorems that are true in classical logic are not provable in Coq's (constructive) logic. E.g., let's look at how this proof gets stuck...\n**)\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     from evidence for P. *)\n  Abort.\n\n\n\n(***************************************************\n Exercise: 5 stars, advanced, optional (classical_axioms)\n\n For those who like a challenge, here is an exercise taken from the Coq'Art book (p. 123). The following five statements are often considered as characterizations of classical logic (as opposed to constructive logic, which is what is \"built in\" to Coq). We can't prove them in Coq, but we can consistently add any one of them as an unproven axiom if we wish to work in classical logic. Prove that these five propositions are equivalent.\n**************************************************)\nTheorem ex_falso_quot_liblet : forall P : Prop, \n                                 False -> P.\nProof. intros P H. inversion H. 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 classic_peirce : classic <-> peirce.\nProof. \n  split. unfold classic. unfold peirce.\n  intros classic P Q.\n  intro H1. apply classic.\n  unfold not. intro notP. apply notP. apply H1.\n  intro H2. apply classic. unfold not.\n  intro notQ. apply notP in H2.\n  apply H2.\n  unfold classic. unfold peirce.\n  intros peirce P notnotP.\n  unfold not in notnotP.\n  apply peirce with (P:=P) (Q:=False).\n  intro H1.\n  apply ex_falso_quot_liblet.\n  apply notnotP.\n  apply H1.\nQed.  \n\nTheorem peirce_de_morgan_not_and_not : peirce <-> de_morgan_not_and_not.\nProof.\n  split. unfold peirce. unfold de_morgan_not_and_not.\n  intros peirce P Q H1. \n  unfold not in H1.\n  apply peirce with (Q:=False). intros H2. \n  left. apply peirce with (Q:=False). intros H3.\n  apply ex_falso_quot_liblet.\n  apply H2. right. apply peirce with (Q:=False). intros H4.\n  apply ex_falso_quot_liblet. \n  \n\nTheorem excluded_middle_implies_to_or : implies_to_or <-> excluded_middle.\nProof.\n  split. unfold excluded_middle. unfold implies_to_or.\n  intros ex_mid.\n(*  apply or_introl with (A:=Q->R) (B:=(Q->R) -> False) in H1. *)\nAdmitted.\n  \n  \n\n\nTheorem imples_to_or_de_morgan_not_and_not : implies_to_or <-> de_morgan_not_and_not.\nProof.\n  split. unfold implies_to_or. unfold de_morgan_not_and_not.\n  intros implies_to_or P Q H1.\nAdmitted.  \n\n(* Theorem peirce_excluded_middle : peirce <-> excluded_middle. *)\n(* Proof.  *)\n(*   split. unfold peirce. unfold excluded_middle. *)\n(*   intros peirce P. *)\n(*   left. *)\n(*   apply peirce with (P:=P) (Q:=False). *)\n(*   intro notP. *)\n(*   apply ex_falso_quot_liblet. *)\n(*   generalize notP. *)\n  \n(*   apply peirce with (P:=False) (Q:=P). *)\n(*   intro H. *)\n\n\n(* Theorem classic_excluded_middle : classic <-> excluded_middle. *)\n(* Proof.  *)\n(*   split. unfold classic. unfold excluded_middle. *)\n(*   intros classic P. *)\n(*   left.  *)\n(*   apply classic. *)\n(*   intro notP. *)\n(*   apply notP. *)\n  \n\n\n(**************************************************\n Exercise: 2 stars (false_beq_nat)\n**************************************************)\nFixpoint beq_nat n m :=\n  match (n, m) with\n    | (O, O) => true\n    | (O, _) | (_, O) => false\n    | (S nn, S mm) => beq_nat nn mm\n  end.\n\n\nTheorem false_beq_nat : forall n m : nat,\n                          n <> m ->\n                          beq_nat n m = false.\nProof.\n  intros n m H.\n  unfold not in H.\n  generalize dependent n.\n  induction m as [|mm].\n  intros n H.\n  destruct n. \n  simpl. apply ex_falso_quot_liblet. apply H. reflexivity.\n  simpl. reflexivity.\n  intros n. destruct n as [|nn].\n  intros H. simpl. reflexivity.\n  simpl. intro H. apply IHmm. intro E. \n  apply H. SearchAbout S.\n  apply eq_S. apply E.\nQed.\n\n\n\n(**************************************************\nExercise: 2 stars, optional (beq_nat_false)\n**************************************************)\nTheorem beq_nat_false :  forall n m,\n                           beq_nat n m = false -> n <> m.\nProof.\n  intros n.\n  unfold not.\n  induction n as [|nn].\n  destruct m as [|mm].\n  simpl. intro H. inversion H.\n  simpl. intro H1. intro H2. inversion H2.\n  destruct m as [|mm].\n  simpl. intros H1 H2. inversion H2.\n  simpl. intros H1 H2. apply eq_add_S in H2.\n  generalize H2. generalize H1. apply IHnn.\nQed.\n \n\n\n(**************************************************\nExercise: 2 stars, optional (ble_nat_false)\n**************************************************)\nFixpoint ble_nat (n:nat) (m:nat) := match (n, m) with \n                                      | (O, _) => true\n                                      | (S _, O) => false\n                                      | (S nn, S mm) => ble_nat nn mm\n                                    end.\n\nTheorem ble_nat_false : forall n m,\n                          ble_nat n m = false -> ~(n <= m).\nProof.\n  intros n. induction n as [|nn].\n  intros m H E.\n  destruct m as [|mm].\n  simpl in H. inversion H.\n  simpl in H. inversion H.\n  intros m E. destruct m as [|mm].\n  unfold not. intro EE. inversion EE.\n  simpl in E. unfold not. intro EE.\n  simpl in EE. apply Le.le_S_n in EE.\n  generalize dependent EE.\n  generalize dependent E.\n  apply IHnn.\nQed.\n\n\n\n(**************************************************\nExercise: 1 star (dist_not_exists)\nProve that \"P holds for all x\" implies \"there is no x for 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 H1 H2.\n  inversion H2.\n  unfold not in H.\n  apply H.\n  apply H1.\nQed.\n\n\n\n(**************************************************\nExercise: 3 stars, optional (not_exists_dist)\n(The other direction of this theorem requires the classical \"law of the excluded middle\".)\n**************************************************)\nTheorem not_exists_dist : excluded_middle ->\n                          forall (X:Type) (P : X -> Prop),\n                            ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros ex_mid X P. \n  unfold excluded_middle in ex_mid.\n  intros H x. unfold not in H.\n  \n  Admitted.\n  \n  \n\n(**************************************************\nExercise: 2 stars (dist_exists_or)\nProve that existential quantification distributes over disjunction.\n**************************************************)\nTheorem dist_exists_or : forall (X:Type) \n                                (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 H1. inversion H1.\n  inversion H as [HL|HR].\n  left. exists x. apply HL.\n  right. exists x. apply HR.\n  intros H. inversion H as [HL|HR].\n  inversion HL.\n  exists x.\n  left. apply H0.\n  inversion HR.\n  exists x.\n  right.\n  apply H0.\nQed.\n\n\n\n\n(**************************************************\nExercise: 2 stars (leibniz_equality)\nThe inductive definitions of equality corresponds to Leibniz equality: what we mean when we say \"x and y are equal\" is that every property on P that is true of x is also true of y.\n**************************************************)\nLemma 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 E.\n  rewrite -> H in E.\n  apply E.\nQed.\n\n\n\n(**************************************************\nExercise: 1 star (override_shadow')\n**************************************************)\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  intros n.\n  induction n as [|nn].\n  destruct m as [|mm].\n  left. reflexivity.\n  right. intros H. inversion H.\n  intros m. destruct m as [|mm].\n  right. intros H. inversion H.\n  destruct IHnn with (m:=mm) as [eq|neq].\n  left. apply f_equal. apply eq.\n  right. intros H. inversion H. generalize H1. apply neq.\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_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'. destruct (eq_nat_dec k1 k2) as [E1|E2].\n  reflexivity. reflexivity.\nQed.\n\n\n\n(**************************************************\nExercise: 1 star, optional (dist_and_or_eq_implies_and)\n**************************************************)\nLemma dist_and_or_eq_implies_and : forall P Q R,\n                                     P /\\ (Q \\/ R) /\\ Q = R -> P\\/ Q.\nProof.\n  intros P Q R H.\n  inversion H.\n  left. apply H0.\nQed.\n\n\n(**************************************************\nExercise: 3 stars (all_forallb)\nInductively define a property all of lists, parameterized by a type X and a property P : X → Prop, such that all X P l asserts that P is true for every element of the list l.\n**************************************************)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n| empty : all X P []\n| rest_true : forall x l, P x -> all X P l -> all X P (x::l).\n\n(** Recall the function forallb, from the exercise forall_exists_challenge in chapter Poly: **)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | nil => true\n    | cons x l' => andb (test x) (forallb test l')\n  end.\n\n(* Using the property all, write down a specification for forallb, and prove that it satisfies the specification. Try to make your specification as precise as possible.\nAre there any important properties of the function forallb which are not captured by your specification? *)\n\n(* FILL IN HERE *)\n\n(**************************************************\nExercise: 4 stars, advanced (filter_challenge)\nOne of the main purposes of Coq is to prove that programs match their specifications. To this end, let's prove that our definition of filter matches a specification. Here is the specification, written out informally in English.\nSuppose we have a set X, a function test: X→bool, and a list l of type list X. Suppose further that l is an \"in-order merge\" of two lists, l1 and l2, such that every item in l1 satisfies test and no item in l2 satisfies test. Then filter test l = l1.\nA list l is an \"in-order merge\" of l1 and l2 if it contains all the same elements as l1 and l2, in the same order as l1 and l2, but possibly interleaved. For example,\n    [1,4,6,2,3]\nis an in-order merge of\n    [1,6,2]\nand\n    [4,3].\nYour job is to translate this specification into a Coq theorem and prove it. (Hint: You'll need to begin by defining what it means for one list to be a merge of two others. Do this with an inductive relation, not a Fixpoint.)\n**************************************************)\n\n\n(**************************************************\nExercise: 5 stars, advanced, optional (filter_challenge_2)\nA different way to formally characterize the behavior of filter goes like this: Among all subsequences of l with the property that test evaluates to true on all their members, filter test l is the longest. Express this claim formally and prove it.\n**************************************************)\n\n\n(**************************************************\nExercise: 4 stars, advanced (no_repeats)\nThe 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 least once as a member of a list l.\nHere'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.\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, which should be provable exactly when l1 and l2 are 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 no_repeats X l, which should be provable exactly when l is a list (with elements of type X) where every member is different from every other. For example, no_repeats nat [1,2,3,4] and no_repeats bool [] should be provable, while no_repeats nat [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 disjoint, no_repeats and ++ (list append). *)\n\n(* FILL IN HERE *)\n\n(**************************************************\nExercise: 3 stars (nostutter)\nFormulating inductive definitions of predicates is an important skill you'll need in this course. Try to solve this exercise without any help at all (except from your study group partner, if you have one).\nWe say that a list of numbers \"stutters\" if it repeats the same number consecutively. The predicate \"nostutter mylist\" means that mylist does not stutter. Formulate an inductive definition for nostutter. (This is different from the no_repeats predicate in the exercise above; the sequence 1,4,1 repeats but 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 to change the proof if the given one doesn't work for you. Your definition might be different from mine and still correct, in which case the examples might need a different proof.\nThe suggested proofs for the examples (in comments) use a number of tactics we haven't talked about, to try to make them robust with respect to different possible ways of defining nostutter. You should be able to just uncomment and use them as-is, but if you prefer you can also prove each 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; auto. Qed.\n*)\n\nExample test_nostutter_2: nostutter [].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_3: nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n*)\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. intro.\n  repeat match goal with \n    h: nostutter _ |- _ => inversion h; clear h; subst \n  end.\n  contradiction H1; auto. Qed.\n*)\n\n(**************************************************\nExercise: 4 stars, advanced (pigeonhole principle)\nThe \"pigeonhole principle\" states a basic fact about counting: if you distribute more than n items into n pigeonholes, some pigeonhole must contain at least two items. As is often the case, this apparently trivial fact about numbers requires non-trivial machinery to prove, but we now have enough...\nFirst a pair of useful lemmas (we already proved these for lists of naturals, but not for arbitrary lists).\n**************************************************)\nLemma app_length : ∀(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 : ∀(X:Type) (x:X) (l:list X),\n  appears_in x l → \n  ∃l1, ∃l2, l = l1 ++ (x::l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(* Now define a predicate repeats (analogous to no_repeats in the exercise above), such that repeats X l asserts 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. List l2 represents a list of pigeonhole labels, and list l1 represents an assignment of items to labels: if there are more items than labels, at least two items must have the same label. You will almost certainly need to use the excluded_middle hypothesis. *)\n\nTheorem pigeonhole_principle: ∀(X:Type) (l1 l2:list X),\n  excluded_middle → \n  (∀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", "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/lesson8_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8947894654011352, "lm_q1q2_score": 0.7924537184022694}}
{"text": "(*** Logical conjunction ***)\nVariables A B C : Prop.\n\n(* Comutatividade *)\nLemma and_commutativity : A /\\ B -> B /\\ A.\nProof.\n  intro Hab.\n  destruct Hab as [Ha Hb].\n  split.\n  +\n    assumption.\n  +\n    assumption.\nQed.\n\n(* Associatividade *)\nLemma and_associativity : A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n  intro Habc.\n  destruct Habc as [Ha [Hb Hc]].\n  split.\n  +\n    split.\n    *\n      assumption.\n    *\n      assumption.\n  +\n    assumption.\nQed.\n\n(* Leis de De Morgan *)\nLemma and_de_morgan : ~A /\\ ~B -> ~(A \\/ B).\nProof.\n  intros NHab DHab.\n  destruct NHab as [NHa NHb].\n  destruct DHab as [Ha|Hb].\n  apply NHa.\n  exact Ha.\n  apply NHb.\n  exact Hb.\nQed.\n\n(* A contradição é sempre falsa *)\nLemma and_contradiction_always_false : A /\\ ~A -> False.\nProof.\n  intro CHa.\n  destruct CHa as [Ha NHa].\n  apply NHa.\n  exact Ha.\nQed.\n\n(* A verdade é o elemento neutro da conjunção *)\nLemma and_truth_neutral_element : A /\\ True -> A.\nProof.\n  intro CHa.\n  destruct CHa as [Ha true].\n  exact Ha.\nQed.\n\n(* A falsidade é o elemento absorvente da conjunção *)\nLemma and_false_absorbent_element : A /\\ False -> False.\nProof.\n  intro CHa.\n  destruct CHa as [Ha false].\n  exact false.\nQed.\n\n(* Distributividade em relação à disjunção lógica *)\nLemma and_distributivity_disjunction : A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C).\nProof.\n  intro Habc.\n  destruct Habc as [Ha [Hb|Hc]].\n  +\n    split.\n  intro.\n  intro.\n  intro.\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/extras/conjuncao_propriedades.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7923071692937602}}
{"text": "(*\n   Functional Programming 2018\n   Term project\n   Artihmetic expression decompiler\n\n   Christoffer Müller Madsen and\n   Jon Michael Aanes\n\n   December 2018\n *)\n\nRequire Import List Coq.Arith.Arith Coq.Arith.EqNat Bool.\nImport ListNotations.\n\n\n(* ################################################################# *)\n\nModule Main.\n\n(** * Syntax *)\n\n(** ** Expression language *)\n\n(** The expression language considered in this project is very\n    simple. It can describe arithmetics on natural numbers with a select\n    set of unary and binary operations. The operations defined for the\n    basic version of the language were the unary operations successor\n    and predecessor, and the binary operations addition and\n    multiplication.\n\n    Since then, we have added subtraction and conditional expressions.\n\n    We define the expression language inductively. *)\n\nInductive unop :=\n  | OSucc : unop\n  | OPred : unop.\n\nInductive binop :=\n  | OPlus : binop\n  | OMult : binop\n  | OMinus : binop.\n\nInductive exp :=\n  | ENat   : nat   -> exp\n  | EUnOp  : unop  -> exp -> exp\n  | EBinOp : binop -> exp -> exp -> exp\n  | EIf    : exp   -> exp -> exp -> exp.\n\n\n(** ** Stack machine language *)\n\n(** The stack machine language considered is similarly simple. It\n    supports pushing natural numbers to the stack and performing unary\n    and binary operations on these. The instructions are in reverse\n    Polish notation. *)\n\nInductive instruction :=\n  | IPush   : nat   -> instruction\n  | IUnOp   : unop  -> instruction\n  | IBinOp  : binop -> instruction\n  | IChoose : instruction.\n\n(** We define the type [stack] to lighten the syntactical weight of the\n    Coq code. *)\n\nDefinition stack := list nat.\nDefinition program := list instruction.\n\n(* ================================================================= *)\n(** * Expression evaluation *)\n\n(** We define the function [eval] to give semantics to expressions. *)\n\nDefinition eval_unop (op : unop) (v : nat) : nat :=\n  match op with\n    | OSucc => S v\n    | OPred => pred v\n  end.\n\nDefinition eval_binop (op : binop) (v1 v2 : nat) : nat :=\n  match op with\n    | OPlus => v1 + v2\n    | OMult => v1 * v2\n    | OMinus => v1 - v2\n  end.\n\nFixpoint eval (e : exp) : nat :=\n  match e with\n    | ENat   n          => n\n    | EUnOp  op   e     => eval_unop op (eval e)\n    | EBinOp op   e1 e2 => eval_binop op (eval e1) (eval e2)\n    | EIf    cond e1 e2 => if eval cond then eval e2 else eval e1\n  end.\n\n\n(** We test the [eval] function  *)\n\nExample eval_1 : eval (EBinOp OMult (ENat 4) (ENat 3)) = 12.\nProof. simpl. reflexivity. Qed.\n\nExample eval_2 : eval (ENat 4) = 4.\nProof. simpl. reflexivity. Qed.\n\nExample eval_3 : eval (EUnOp OSucc (ENat 4)) = 5.\nProof. simpl. reflexivity. Qed.\n\nExample eval_4 : eval (EUnOp OPred (ENat 4)) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample eval_5 : eval (EBinOp OPlus (EUnOp OPred (ENat 0)) (EUnOp OSucc (EBinOp OMult (ENat 5) (ENat 3)))) = 16.\nProof. simpl. reflexivity. Qed.\n\nExample eval_6 : eval (EBinOp OMinus (ENat 4) (ENat 3)) = 1.\nProof. simpl. reflexivity. Qed.\n\nExample eval_7 : eval (EBinOp OMinus (ENat 3) (ENat 4)) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample eval_if_1 : eval (EIf (ENat 0) (ENat 1) (ENat 2)) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample eval_if_2 : eval (EIf (ENat 3) (ENat 1) (ENat 2)) = 1.\nProof. simpl. reflexivity. Qed.\n\nExample eval_if_3 : eval (EIf (EBinOp OMult (ENat 4) (ENat 3)) (ENat 1) (ENat 2)) = 1.\nProof. simpl. reflexivity. Qed.\n\n(** It seems to work.  *)\n\n\n(* ================================================================= *)\n(** * Stack machine *)\n\n(** ** General stack machine  *)\n\n(** We observed that the virtual machine and decompiler were nearly\n    equivalent in implementation.  For this reason, we generalised the\n    shared parts.  The record type [stack_machine_functions] specifies\n    the semantics of the general stack machine.\n\n    The function [exp_to_elem] is not used in the actual implementation\n    of the stack machine; its purpose is solely to signify what the\n    equivalent of running the stack machine on an input would\n    be. Running the stack machine on a compiled expression [e] should be\n    equivalent to evaluating [exp_to_elem e]. We provide a proof for\n    this later.\n\n    The [props] element is a proof that applying [exp_to_elem] on an\n    expression is equivalent to running the stack machine with the\n    functions specified in the record.\n\n    This will become more clear as you read along. *)\n\nDefinition exp_to_elem_props\n           {A : Type}\n           (exp_to_elem : exp -> A)\n           exp_to_elem_push\n           exp_to_elem_unop\n           exp_to_elem_binop\n           exp_to_elem_if : Prop :=\n\n  (forall (n : nat),\n      exp_to_elem (ENat n) = exp_to_elem_push n) /\\\n\n  (forall (e : exp) (op : unop),\n      exp_to_elem (EUnOp op e) = exp_to_elem_unop op (exp_to_elem e)) /\\\n\n  (forall (e1 e2 : exp) (op : binop),\n      exp_to_elem (EBinOp op e1 e2) = exp_to_elem_binop op (exp_to_elem e1) (exp_to_elem e2)) /\\\n\n  (forall (cond e1 e2 : exp),\n      exp_to_elem (EIf cond e1 e2) =\n      exp_to_elem_if (exp_to_elem cond) (exp_to_elem e2) (exp_to_elem e1)).\n\nRecord stack_machine_functions {A : Type} :=\n  {\n    constr_push  : nat -> A;\n    constr_unop  : unop -> A -> A;\n    constr_binop : binop -> A -> A -> A;\n    constr_if    : A -> A -> A -> A;\n    exp_to_elem  : exp -> A;\n      }.\n\n(** For later use: A proof tactic to unpack the propositions from a\n    record of type [stack_machine_functions] into the local proof\n    context.  *)\n\n\n\n(** We define a function to execute a single step of the stack\n    machine. It takes as input a [stack_machine_functions] and a single\n    instruction and outputs a correspondingly updated stack. \n*)\n\nDefinition stack_machine_state_transition\n           {A: Type}\n           (funcs: stack_machine_functions)\n           (insn: instruction)\n           (s: list A) : option (list A) :=\n\n  match insn, s with\n    | IPush n, s'\n      => Some ((constr_push funcs n) :: s')\n\n    | IUnOp op, x :: s'\n      => Some ((constr_unop funcs op x) :: s')\n\n    | IBinOp op, y :: x :: s'\n      => Some ((constr_binop funcs op x y) :: s')\n\n    | IChoose, cond :: v2 :: v1 :: s'\n      => Some ((constr_if funcs cond v1 v2) :: s')\n\n    | _, _ => None\n  end.\n\n(** We can now define the general stack machine as the recursive\n    application of [stack_machine_state_transition] on a [program],\n    returning the final stack when all instructions have been\n    executed. *)\n\nFixpoint stack_machine {A : Type} (funcs : stack_machine_functions) (insns : program) (s : list A) : option (list A) :=\n  match insns with\n    | insn :: insns' => match stack_machine_state_transition funcs insn s with\n                          | Some s' => stack_machine funcs insns' s'\n                          | _       => None\n                        end\n    | [] => Some s\n  end.\n\n(** ** Virtual machine  *)\n\n(** We can now begin defining the specialisation of the general stack\n    machine to be used as the virtual machine.\n\n    First, look at [vm_functions], which specifies the functions used\n    for the virtual machine. The proof needed to specify the record is\n    provided as [vm_functions_props].\n\n    [exp_to_elem] is set to be the [eval] function, signifying that\n    running the virtual machine on a compiled expression is equivalent\n    to evaluating the expression using [eval]. *)\n\nLemma vm_functions_props : exp_to_elem_props eval id eval_unop eval_binop (fun (cond v1 v2 : nat) => (if cond then v1 else v2)).\nProof.\n  unfold exp_to_elem_props. auto.\nQed.\n\nDefinition vm_functions :=\n  {|\n    constr_push  := fun (n : nat) => n;\n    constr_unop  := eval_unop;\n    constr_binop := eval_binop;\n    constr_if    := fun (cond v1 v2 : nat) => (if cond then v1 else v2);\n    exp_to_elem  := eval;\n  |}.\n\n\n(** The main virtual machine function [vm] can now be defined succinctly\n    in terms of [stack_machine]. *)\n\nDefinition vm (insns : program) : option nat :=\n  match stack_machine vm_functions insns nil with\n    | Some (x :: _) => Some x\n    | _ => None\n  end.\n\n(** We test the [vm] function *)\n\nExample vm_test_1 : vm [IPush 2] = Some 2.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_2 : vm [IPush 2 ; IPush 3] = Some 3.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_3 : vm [IPush 2 ; IPush 3 ; IBinOp OPlus] = Some 5.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_4 : vm [IPush 4 ; IPush 2 ; IPush 3 ; IBinOp OPlus ; IBinOp OMult] = Some 20.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_5 : vm [IPush 4 ; IPush 2 ; IPush 3 ; IBinOp OPlus ; IBinOp OMult ; IUnOp OSucc] = Some 21.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_6 : vm [IPush 4 ; IPush 2 ; IPush 3 ; IUnOp OPred ; IBinOp OPlus ; IBinOp OMult ; IUnOp OSucc] = Some 17.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_7 : vm [] = None.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_8 : vm [IUnOp OSucc] = None.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_9 : vm [IPush 2 ; IBinOp OPlus] = None.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_10 : vm [IPush 4 ; IPush 1 ; IBinOp OMinus] = Some 3.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_11 : vm [IPush 1 ; IPush 4 ; IBinOp OMinus] = Some 0.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_choose_1 : vm [ IPush 4 ; IPush 1 ; IPush 0 ; IChoose ] = Some 4.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_choose_2 : vm [ IPush 4 ; IPush 2 ; IPush 1 ; IChoose ] = Some 2.\nProof. simpl. reflexivity. Qed.\n\nExample vm_test_choose_3 : vm ([IPush 4 ; IPush 2 ; IPush 3 ; IBinOp OPlus ; IBinOp OMult] ++ [IPush 2 ; IPush 3 ; IBinOp OPlus] ++ [IPush 4 ; IPush 2 ; IPush 3 ; IUnOp OPred ; IBinOp OPlus ; IBinOp OMult ; IUnOp OSucc] ++ [IChoose]) = Some 5.\nProof. simpl. reflexivity. Qed.\n\n(** It seems to work. *)\n\n(* ================================================================= *)\n(** * Compiler *)\n\n(** We give a functional definition of the compiler for the stack\n    machine, which is fairly trivial.  *)\n\nFixpoint compile (e : exp) : program :=\n  match e with\n    | ENat   n          => [ IPush n ]\n    | EUnOp  op e       => compile e ++ [ IUnOp op ]\n    | EBinOp op e1 e2   => compile e1 ++ compile e2 ++ [ IBinOp op ]\n    | EIf    cond e1 e2 => compile e2 ++ compile e1 ++ compile cond ++ [ IChoose ]\n  end.\n\nExample compile_test_1 : compile (ENat 3) = [ IPush 3 ].\nProof. simpl. reflexivity. Qed.\n\nExample compile_test_2 : compile (EBinOp OPlus (ENat 3) (ENat 4)) = [ IPush 3 ; IPush 4 ; IBinOp OPlus ].\nProof. simpl. reflexivity. Qed.\n\nExample compile_test_3 : compile (EBinOp OPlus (EUnOp OSucc (ENat 3)) (ENat 4)) = [ IPush 3 ; IUnOp OSucc ; IPush 4 ; IBinOp OPlus ].\nProof. simpl. reflexivity. Qed.\n\nExample compile_test_4 : compile (EBinOp OMult (EUnOp OPred (ENat 3)) (ENat 4)) = [ IPush 3 ; IUnOp OPred ; IPush 4 ; IBinOp OMult ].\nProof. simpl. reflexivity. Qed.\n\nExample compile_test_5 : compile (EBinOp OMult (EUnOp OPred (EUnOp OSucc (ENat 3))) (ENat 4)) = [ IPush 3 ; IUnOp OSucc ; IUnOp OPred ; IPush 4 ; IBinOp OMult ].\nProof. simpl. reflexivity. Qed.\n\nExample compile_test_if_1 : compile (EBinOp OPlus\n                                            (EIf (EUnOp OSucc (ENat 0))\n                                                 (EUnOp OPred (ENat 2))\n                                                 (EUnOp OSucc (ENat 4)))\n                                            (ENat 41))\n                            = [ IPush 4 ; IUnOp OSucc ; IPush 2 ; IUnOp OPred ; IPush 0 ; IUnOp OSucc ; IChoose ; IPush 41 ; IBinOp OPlus ].\nProof. simpl. reflexivity. Qed.\n\n(* ================================================================= *)\n(** * Correctness of virtual machine and compiler *)\n\n(** We previously postulated that running the virtual machine on a\n    compiled expression is equivalent to applying [eval] to that\n    expression.\n\n    In this section, we prove that this proposition holds. *)\n\n\n(** ** QuickChick intermezzo *)\n\n(** Before giving a formal proof of the proposition, we see if\n    QuickChick can find a counter-example. *)\n\n(** The proposition is posed as *)\n\n(* Definition vm_correct_prop (e : exp) := vm (compile e) = Some (eval e)?. *)\n\n(** Before we can check the propositions, we need to do some plumbing\n    for QuickChick. *)\n\n(** Deriving the [Show] typeclass for the inductive datatypes is\n    necessary for QuickChick usage. *)\n\n(* Derive Show for unop.\nDerive Show for binop.\nDerive Show for exp.\n\n(** Equality of two expressions is easily decidable, it is trivially\n    proved by [dec_eq].  *)\n\nInstance eq_dec_exp (exp1 exp2 : exp) : Dec (exp1 = exp2) := {}.\nProof. dec_eq. Defined.\n\n *)\n(** Next, we implement a function for generating expressions with some\n    notion of size. We generate expressions in a straight-forward\n    recursive way. *)\n\n(* Fixpoint genSizedexp (size : nat) : G exp :=\n  match size with\n    | O => (n <- choose (1, 40) ;;\n            ret (ENat n))\n    | S size' =>\n      freq [ (1, (n <- choose (1, 40) ;;\n                  ret (ENat n))) ;\n             (size, e <- genSizedexp size' ;;\n                    op <- (elems [ OSucc ; OPred ]) ;;\n                    ret (EUnOp op e)) ;\n             (size, e1 <- genSizedexp size' ;;\n                    e2 <- genSizedexp size' ;;\n                    op <- (elems [ OPlus ; OMult ; OMinus ]) ;;\n                   ret (EBinOp op e1 e2)) ;\n             (size, e1 <- genSizedexp size' ;;\n                    e2 <- genSizedexp size' ;;\n                    e3 <- genSizedexp size' ;;\n                    ret (EIf e1 e2 e3))]\n  end.\n *)\n(** We also need to implement a shrinker for expressions. We shrink by\n    either\n    - shrinking an expression to one of its parts, i.e. shrinking a\n      binary operation to one of the expressions it operates on, or\n    - mapping an expression to an expression of the same types, with one\n      of its parts shrunk, i.e. shrinking a binary operation to the same\n      binary operation, with one of the expressions it operates on being\n      shrunk.  *)\n(* \nFixpoint shrinkExp (e : exp) : list exp :=\n  match e with\n    | ENat v => map (fun n => ENat n) (shrink v)\n    | EUnOp op e1 => e1 :: shrinkExp e1\n    | EBinOp op e1 e2 =>\n      [e1 ; e2]\n        ++ map (fun e' => EBinOp op e' e2) (shrinkExp e1)\n        ++ map (fun e' => EBinOp op e1 e') (shrinkExp e2)\n    | EIf cond e1 e2 =>\n      [e1 ; e2]\n        ++ map (fun cond' => EIf cond' e1 e2) (shrinkExp cond)\n        ++ map (fun e' => EIf cond e' e2) (shrinkExp e1)\n        ++ map (fun e' => EIf cond e1 e') (shrinkExp e2)\n  end.\n *)\n(** Now that we have done the necessary plumbing, we can check the proposition. *)\n\n(* QuickChick (forAllShrink (genSizedexp 2) shrinkExp vm_correct_prop).\n *)\n(**\n    +++ Passed 10000 tests (0 discards)\n\n    It seems to work!\n*)\n\n(** ** A formal proof  *)\n\n(** We now give a formal proof of the same proposition.\n\n    In order to give the proof, we need a few lemmas stating properties\n    about the virtual stack machine. We state these propositions as\n    properties of the general stack machine in order to be able to\n    re-use the propositions for later proofs.\n *)\n\n(** The stack machine should have the transitive property,\n    i.e. evaluating a list of instructions combined from two sublists\n    should be the same as evaluating the two sublists sequentially. *)\n\nLemma stack_machine_trans : forall (A : Type) funcs insns1 insns2 s s',\n    @stack_machine A funcs insns1 s = Some s' ->\n    stack_machine funcs (insns1 ++ insns2) s =\n    stack_machine funcs (insns2) s'.\n\n(** The proof is by induction over the first list of instructions. *)\n\nProof.\n  intros A funcs insns1.\n  induction insns1; intros insns2 s s' H1. \n\n  (** The case of the empty list of instructions is trivial; the stack\n      remains the same.  *)\n\n  - inversion H1. reflexivity.\n\n  (** The induction case requires a bit more work. Here, we do case\n      analysis on the type of the instruction at the head of the\n      list. *)\n\n  - rewrite <- app_comm_cons.\n    destruct a;\n\n      (** In the [INat] case the induction hypothesis and the assumption\n          easily proves the proposition. *)\n\n      apply IHinsns1, H1 ||\n\n      (** The cases of [IUnOp], [IBinOp], and [IChoose] require a bit more work.\n\n          We destruct the stack. The stack cannot be empty. These cases\n          are solved by [inversion]. In the [cons] case, we apply the\n          induction hypothesis after which the proofs is finalised by\n          the anitial assumption.\n\n          [IUnOp] requires a single pass of the stack destruction,\n          [IBinOp] requires two, and [IChoose] requires three. *)\n\n      (repeat (destruct s; inversion H1; try apply IHinsns1, H1)).\n\n    (** And we are done! *)\n\nQed.\n\n\n(** Evaluating a list of instructions, where the prefix of the list is a\n    compiled expression should be equivalent to evaluting the rest of\n    the list of instructions with the value of the expression on top of\n    the original stack.\n\n    The proof is by induction on [e]. The [props] entry of the\n    [stack_machine_functions] can be used in all cases to rewriting the\n    terms. Rewriting with the induction hypotheses then solves each case.\n *)\n\n(* Lemma stack_machine_compile : forall {A : Type} (funcs : stack_machine_functions)\n                                     (e : exp) (insns : program) (s : list A),\n    @stack_machine A funcs (compile e ++ insns) s =\n    stack_machine funcs insns ((exp_to_elem funcs e) :: s).\nProof.\n  intros A funcs e.\n  UnpackFunctionPropositions funcs.\n  induction e; (intros insns s; apply stack_machine_trans; simpl).\n  - rewrite H_push. reflexivity.\n  - rewrite H_unop, IHe. reflexivity.\n  - rewrite H_binop, IHe1, IHe2. reflexivity.\n  - rewrite H_if, IHe3, IHe2, IHe1. reflexivity.\nQed. *)\n\n(** We now prove a general version of the main proposition of this\n    section.\n\n    The proof is by case analysis of the expression [e]. All cases can\n    be solved by rewriting a number of times with\n    [stack_machine_compile] and the propositions given by the\n    [stack_machine_functions] record.\n\n    Rewriting with [stack_machine_compile] is equivalent to stepping the\n    stack machine through a complete expression. The [props] in the\n    [stack_machine_functions] record gives us the properties needed to\n    do this. *)\n\n(* Lemma stack_machine_correct : forall {A : Type} (funcs : stack_machine_functions) (e : exp),\n    @stack_machine A funcs (compile e) [] = Some [(exp_to_elem funcs) e].\nProof.\n  intros A funcs e.\n  UnpackFunctionPropositions funcs.\n  destruct e; simpl; repeat rewrite stack_machine_compile; simpl; congruence.\nQed. *)\n\n\n(** The final proposition of this section follows as a specialisation of\n    the general lemma above: the composition of [vm] and [compile] are\n    equivalent to [eval] for all expressions. *)\n(* \nTheorem vm_correct : forall e,\n    vm (compile e) = Some (eval e).\nProof.\n  intros e.\n  unfold vm.\n  rewrite stack_machine_correct.\n  reflexivity.\nQed. *)\n\n(* ================================================================= *)\n(** * Decompiler *)\n\n(** With the interpreter, compiler and virtual machine defined and proved\n    correct, we now begin the work on the decompiler. *)\n\n(** As with the virtual machine, we use the general stack machine as the\n    foundation of the decompiler. The [exp_to_elem] function is [id]:\n    compiling an expression and executing the result with the decompiler\n    should be equivalent to the original expression. *)\n\nLemma decompile_functions_props : exp_to_elem_props id ENat EUnOp EBinOp (fun (cond e1 e2 : exp) => EIf cond e2 e1).\nProof.\n  unfold exp_to_elem_props. auto.\nQed.\n\nDefinition decompile_functions :=\n  {|\n    constr_push  := ENat;\n    constr_unop  := EUnOp;\n    constr_binop := EBinOp;\n    constr_if    := fun (cond e1 e2 : exp) => EIf cond e2 e1;\n    exp_to_elem  := id;\n\n  |}.\n\nDefinition decompile (insns : program) : option exp :=\n    match stack_machine decompile_functions insns [] with\n      | Some [res] => Some res\n      | _ => None\n    end.\n\n(** We test the decompiler with some simple tests. *)\n\nExample decompile_test_1 : decompile [IPush 42] =\n                           Some (ENat 42).\nProof. simpl. reflexivity. Qed.\n\nExample decompile_test_2\n  : decompile [ IPush 2 ; IPush 40 ; IBinOp OPlus ] =\n    Some (EBinOp OPlus (ENat 2) (ENat 40)).\nProof. simpl. reflexivity. Qed.\n\nExample decompile_test_3\n  : decompile [ IPush 1 ; IUnOp OSucc ; IPush 40 ; IBinOp OPlus ] =\n    Some (EBinOp OPlus (EUnOp OSucc (ENat 1)) (ENat 40)).\nProof. simpl. reflexivity. Qed.\n\nExample decompile_test_if_1\n  : decompile [ IPush 4 ; IUnOp OSucc ; IPush 2 ; IUnOp OPred ; IPush 0 ; IUnOp OSucc ; IChoose ; IPush 41 ; IBinOp OPlus ] =\n    Some ((EBinOp OPlus\n            (EIf (EUnOp OSucc (ENat 0))\n                 (EUnOp OPred (ENat 2))\n                 (EUnOp OSucc (ENat 4)))\n            (ENat 41))).\nProof. simpl. reflexivity. Qed.\n\n(** It seems to work. *)\n\n(** ** Left-inverse *)\n\n(** We want the decompiler to be the left-inverse of the compiler,\n    i.e. decompiling any compiled expression should yield a result equal\n    to the original expression. *)\n\n(** *** QuickChick intermezzo  *)\n\n(** Before we give a formal proof of the proposition, we use QuickChick\n    to check for counter-examples.\n\n    We state the proposition: *)\n\n(* Definition decompile_correct_prop (e : exp) := decompile (compile e) = (Some e)?.\n\n(** And check it with QuickChick:  *)\n\nQuickChick (forAllShrink (genSizedexp 2) shrinkExp vm_correct_prop).\n *)\n(**\n    +++ Passed 10000 tests (0 discards)\n\n    It seems to work!\n*)\n\n(** *** A formal proof  *)\n\n(** Proving that the result of decompiling any compiled expression is\n    the original expression is closely related to the proposition\n    [vm_correct] made for the virtual machine. Again, the proof follows\n    from the more general proposition [stack_machine_correct]. *)\n(* \nLemma decompile_correct : forall e,\n    decompile (compile e) = Some e.\nProof.\n  intros e.\n  unfold decompile.\n  rewrite stack_machine_correct.\n  reflexivity.\nQed. *)\n\n\n(** ** Right-inverse  *)\n\n(** The decompiler should be the right-inverse of the compiler,\n    i.e. compiling the result of any decompiled [program] should yield\n    an identical [program]. *)\n\n(** *** QuickChick intermezzo  *)\n\n(** Again, we would like to check for counter-examples before proving\n    the proposition formally. In order to use QuickChick for this, we\n    need to do a bit of plumbing. *)\n\n(** As with the [exp] type, we need to derive the [Show] typeclass for\n    [instruction] and derive decidability of equality between two\n    elements of this type. *)\n(* \nDerive Show for instruction. *)\n\n(* Instance eq_dec_insns (insns1 insns2 : list instruction) : Dec (insns1 = insns2) := {}.\nProof. dec_eq. Defined.\n\n(** We implement an instruction generator that generates programs\n    guaranteed to not fail with a stack underflow. We do this by\n    conditioning the generation of instructions based on the current\n    size of the stack, e.g. if the stack size is lower than 2,\n    generating a binary operation would cause a stack underflow; thus,\n    we do not allow generation that instruction in this specific case.\n*)\n\nFixpoint genSizedinsns_helper (size : nat) (s : nat) (insns : list instruction) :=\n  match size with\n    | O => ret insns\n    | S size' =>\n      freq [ (if (s = 1)? then 1 else 0, ret insns) ;\n             (size,\n               (n <- choose (1, 40) ;;\n                (genSizedinsns_helper size' (s + 1) (IPush n :: insns)))) ;\n             (if (s >= 1)? then 1 else 0,\n               (op <- (elems [ OSucc ; OPred ]) ;;\n               (genSizedinsns_helper size' s (IUnOp op :: insns)))) ;\n             (if (s >= 2)? then 1 else 0,\n               (op <- (elems [ OPlus ; OMult ; OMinus ]) ;;\n               (genSizedinsns_helper size' (s - 1) (IBinOp op :: insns)))) ;\n             (if (s >= 3)? then 1 else 0,\n               (genSizedinsns_helper size' (s - 2) (IChoose :: insns)))\n           ]\n  end.\n\nFixpoint genSizedinsns (size : nat) : G (list instruction) :=\n  rev_insns <- (genSizedinsns_helper size 0 []) ;;\n  ret (rev rev_insns).\n\n(** Not all programs generated by the generator can be decompiled\n    successfully by [decompile]---some programs would decompile to more\n    than one expression, which we disallow in the [decompile]\n    function. To accomodate this, we state a predicate for successful\n    decompilation using the [decompile] function.\n\n    (Note: The predicate is a QuickChick Checker, since it returns a\n    boolean as opposed to a Prop.)\n\n *)*)\n\nDefinition decompiles (insns : list instruction) :=\n  match decompile insns with\n    | Some _ => true\n    | None => false\n  end.\n\n(** We are now able to state the proposition we want to check: the\n    successful decompilation of a program implies that compiling the result\n    of this is equal to the original program. *)\n\n(* Definition compile_decompile_test (ins : list instruction) :=\n  (decompiles ins) ==> match (decompile ins) with\n                         | Some e => (compile e = ins)?\n                         | None => false\n                       end.\n *)\n(** We check the proposition *)\n\n(* QuickChick (forAll (genSizedinsns 5) compile_decompile_test). *)\n\n(** and get\n\n    +++ Passed 10000 tests (10547 discards)\n    \n    The proposition seems to hold. The discards come from generated\n    programs that were discarded because they did not satisfy the\n    [decompiles] predicate. \n*)\n\n\n(** *** An attempt at a formal proof *)\n\n(** Compared to the proof of the left-inverse property, the formal proof\n    of the right-inverse property is more difficult.\n\n    (Note: We do not succeed in proving the proposition stated. We have\n    kept the proof attempts in the document to illustrate our work and\n    the thoughts made during this.)\n\n    We try to prove the proposition by induction on [e]: *)\n(* \nTheorem compile_decompile : forall insns e,\n    decompile insns = Some e -> compile e = insns.\nProof.\n  intros. generalize dependent insns. induction e; intros insns H.\n  - simpl. destruct insns.\n    + inversion H.\n    + destruct i.\n      * destruct insns.\n      * inversion H. reflexivity.\n        -- destruct i.\n           ++ destruct insns.\n              ** inversion H.\n              ** (* ? *)\n\n(** At this point in the proof, we are stuck. We can keep on alternating\n    between destructing [insns] and [i]. In the cases where [insns] is\n    [nil], we can use inversion to prove the subgoals:\n\n        H : decompile [IPush n0; IPush n1] = Some (ENat n)\n\n    is obviously not a valid hypothesis. However, in the case where\n    [insns] contains an instruction [i], we need to destruct this.  This\n    cycle can keep on ad infinitum.\n\n    The main issue with this approach for the proof is that the\n    [decompile] function can not yield an answer until it has walked\n    fully through the list, e.g. a single [IPush] instruction in the\n    head of the list does not indicate that the decompiled expression\n    should be a [ENat]; it might as well be that a [IUnOp] instruction\n    follows, and the correct decompilation should be a [EUnOp] with an\n    [ENat] as sub-expression.\n\n    The logical way of getting around this problem would be by induction\n    over the list of instructions. We abort the proof, and try this\n    approach instead.  *)\nAbort. *)\n\nTheorem compile_decompile : forall insns e,\n    decompile insns = Some e -> compile e = insns.\nProof.\n  intro insns. induction insns; intros.\n  - inversion H.\n  - unfold decompile in H. destruct a. simpl in H.\n\n\n(** It seems that we are stuck yet again. Being able to decompile a\n    single instruction could help us progress in the proof. The\n    [decompile] function is implemented using [stack_machine], which\n    operates in single steps on the list of instructions. This is,\n    however, not what we need. Decompiling a single instruction is not\n    enough to uniquely determine the expression being decompiled.\n\n    Let us abort this proof for now. *)\nAbort.\n\n(* ================================================================= *)\n(** *** Inductive relations  *)\n\n(** In an attempt to attack the proof of the right-inverse property of\n    the decompiler from another angle, we define the compiler as an\n    inductive relation between expressions and programs. *)\n\nInductive compileR : exp -> program -> Prop :=\n  | C_ENat : forall (n : nat),\n      compileR (ENat n) [IPush n]\n\n  | C_EUnOp : forall (op : unop) (e : exp) (insns : program),\n      compileR e insns\n      -> compileR (EUnOp op e) (insns ++ [IUnOp op])\n\n  | C_EBinOp : forall (op : binop) (e1 e2 : exp) (insns1 insns2 : program),\n      compileR e1 insns1\n      -> compileR e2 insns2\n      -> compileR (EBinOp op e1 e2) (insns1 ++ insns2 ++ [IBinOp op])\n\n  | C_EIf : forall (cond e1 e2 : exp) (cond_insns insns1 insns2 : program),\n      compileR e1 insns1\n      -> compileR e2 insns2\n      -> compileR cond cond_insns\n      -> compileR (EIf cond e1 e2) (insns2 ++ insns1 ++ cond_insns ++ [ IChoose ]).\n\n(** A pair of an expression and a program should satisfy this relation\n    iff the applying [compile] to the expression yields the program. *)\n\nLemma compile_iff_compileR : forall e insns,\n    compileR e insns <-> compile e = insns.\nProof.\n  intros e insns.\n  split; intro H.\n  - induction H; subst; reflexivity.\n  - generalize dependent insns.\n    induction e; intros insns H; subst; constructor; auto.\nQed.\n\n(** Note that the inductive relation also describes decompilation of\n    programs. *)\n\nDefinition decompileR (insns : program) (e : exp) : Prop :=\n  compileR e insns.\n\n(** This definition leads to [compileR] being equivalent to [decompileR]\n    (with swapped arguments). *)\n\nLemma compileR_iff_decompileR : forall ins e,\n    compileR e ins <-> decompileR ins e.\nProof.\n  unfold decompileR.\n  intros. reflexivity.\nQed.\n\n(** We now want to prove that decompilation of a program [insns]\n    yielding some expression [e] implies that [insns] and [e] satisfy\n    the [decompileR] relation. Having this lemma at our hands would\n    allow us to prove the [compile_decompile] lemma that we struggled\n    with earlier.  *)\n\nLemma decompile_implies_decompileR : forall e insns,\n   decompile insns = Some e -> decompileR insns e.\nProof.\n  intros e insns. generalize dependent e. induction insns; intros.\n  - inversion H.\n  - destruct a.\n    (** We are back in the same situation as before. Stuck, yet again. *)\nAbort.\n\n(** We abort the quest of proving the right-inverse property. It seems\n    to be possible, but we need to know more of the properties of the\n    [decompile] function in order to progress in these proofs.  *)\n\n(* ================================================================= *)\n(** * Eval not unique  *)\n\n(** In this section, we show that for all expressions, there exists a\n    different expression which evaluates to the same value. This makes\n    it impossible to prove a right-hand version of [vm_correct], as\n    opposed to [compile_decompile], which is the right-hand version of\n    [decompile_correct].\n\n    To prove this, we need to state a lemma to help us: *)\n\nLemma binop_cannot_contain_self : forall e e' op, e <> EBinOp op e' e.\n  unfold not.\n  induction e; intros; inversion H.\n  - subst. apply IHe2 in H3. apply H3.\nQed.\n\n(** We now formally state and prove the [eval_not_unique]\n    proposition. *)\n\nLemma eval_not_unique : forall e1, exists e2, eval e1 = eval e2 /\\ ~(e1 = e2).\nProof.\n  intros e1.\n  unfold not.\n  destruct e1 eqn:He1; simpl; exists (EBinOp OPlus (ENat 0) e1);\n    subst; split; simpl; (reflexivity || intros H; inversion H).\n  - subst. apply binop_cannot_contain_self in H3. apply H3.\nQed.\n\nEnd Main.\n\n(* ================================================================= *)\n(** * Adding a no-op instruction *)\n\n(** In this last section, we show that adding a no-op instruction to the\n    instruction set invalidates the right-inverse property of\n    [decompile] for [compile]. We do this by reimplementing the compiler\n    and decompiler and checking the right-inverse proposition with\n    QuickChick, which should find a fairly trivial counter-example.\n\n    Illustrating this requires duplicating a fair amount of code. We\n    have added comments to show when new code is added.\n\n*)\n\nModule Nop.\n\n  Inductive unop :=\n    | OSucc : unop\n    | OPred : unop.\n  \n  Inductive binop :=\n    | OPlus : binop\n    | OMult : binop\n    | OMinus : binop.\n\n  Inductive exp :=\n    | ENat   : nat   -> exp\n    | EUnOp  : unop  -> exp -> exp\n    | EBinOp : binop -> exp -> exp -> exp\n    | EIf    : exp   -> exp -> exp -> exp.\n\n  Inductive instruction :=\n  | IPush   : nat   -> instruction\n  | IUnOp   : unop  -> instruction\n  | IBinOp  : binop -> instruction\n  | IChoose : instruction\n\n  (** We add the IDont instruction. *)\n  | IDont : instruction.\n\n  Definition program := list instruction.\n(*   Derive Show for unop.\n  Derive Show for binop.\n  Derive Show for exp.\n *)\n  (* The compiler remains unchanged from the main program. There is no\n     case where the compiler outputs an [IDont] instruction. This is an\n     important point to note. *)\n  Fixpoint compile (e : exp) : program :=\n    match e with\n    | ENat   n          => [ IPush n ]\n    | EUnOp  op e       => compile e ++ [ IUnOp op ]\n    | EBinOp op e1 e2   => compile e1 ++ compile e2 ++ [ IBinOp op ]\n    | EIf    cond e1 e2 => compile e2 ++ compile e1 ++ compile cond ++ [ IChoose ]\n    end.\n\n  Definition exp_to_elem_props\n             {A : Type}\n             (exp_to_elem : exp -> A)\n             exp_to_elem_push\n             exp_to_elem_unop\n             exp_to_elem_binop\n             exp_to_elem_if : Prop :=\n\n    (forall (n : nat),\n        exp_to_elem (ENat n) = exp_to_elem_push n) /\\\n\n    (forall (e : exp) (op : unop),\n        exp_to_elem (EUnOp op e) = exp_to_elem_unop op (exp_to_elem e)) /\\\n\n    (forall (e1 e2 : exp) (op : binop),\n        exp_to_elem (EBinOp op e1 e2) = exp_to_elem_binop op (exp_to_elem e1) (exp_to_elem e2)) /\\\n\n    (forall (cond e1 e2 : exp),\n        exp_to_elem (EIf cond e1 e2) =\n        exp_to_elem_if (exp_to_elem cond) (exp_to_elem e2) (exp_to_elem e1)).\n\n\n  Record stack_machine_functions {A : Type} :=\n    {\n      constr_push  : nat -> A;\n      constr_unop  : unop -> A -> A;\n      constr_binop : binop -> A -> A -> A;\n      constr_if    : A -> A -> A -> A;\n      exp_to_elem  : exp -> A;\n      props        : @exp_to_elem_props A exp_to_elem constr_push constr_unop constr_binop constr_if\n    }.\n\n\n  Definition stack_machine_state_transition\n             {A: Type}\n             (funcs: stack_machine_functions)\n             (insn: instruction)\n             (s: list A) : option (list A) :=\n\n    match insn, s with\n    | IPush n, s'\n      => Some ((constr_push funcs n) :: s')\n\n    | IUnOp op, x :: s'\n      => Some ((constr_unop funcs op x) :: s')\n\n    | IBinOp op, y :: x :: s'\n      => Some ((constr_binop funcs op x y) :: s')\n\n    | IChoose, cond :: v2 :: v1 :: s'\n      => Some ((constr_if funcs cond v1 v2) :: s')\n\n    (** We add a new case to handle the [IDont] instruction by making no\n       changes to the stack.  *)\n    | IDont, s' => Some s'\n\n    | _, _ => None\n    end.\n\n  Fixpoint stack_machine {A : Type} (funcs : stack_machine_functions) (insns : program) (s : list A) : option (list A) :=\n    match insns with\n    | insn :: insns' => match stack_machine_state_transition funcs insn s with\n                        | Some s' => stack_machine funcs insns' s'\n                        | _       => None\n                        end\n    | [] => Some s\n    end.\n\n  Lemma decompile_functions_props : exp_to_elem_props id ENat EUnOp EBinOp (fun (cond e1 e2 : exp) => EIf cond e2 e1).\n  Proof.\n    unfold exp_to_elem_props. auto.\n  Qed.\n\n  Definition decompile_functions :=\n    {|\n      constr_push  := ENat;\n      constr_unop  := EUnOp;\n      constr_binop := EBinOp;\n      constr_if    := fun (cond e1 e2 : exp) => EIf cond e2 e1;\n      exp_to_elem  := id;\n      props        := decompile_functions_props;\n    |}.\n\n\n  Definition decompile (insns : program) : option exp :=\n    match stack_machine decompile_functions insns [] with\n    | Some [res] => Some res\n    | _ => None\n    end.\n\n\n(*   Derive Show for instruction. *)\n(* \n  Fixpoint genSizedinsns_helper (size : nat) (s : nat) (insns : list instruction) :=\n    match size with\n    | O => ret insns\n    | S size' =>\n      freq [ (if (s = 1)? then 1 else 0, ret insns) ;\n               (size,\n                (n <- choose (1, 40) ;;\n                   (genSizedinsns_helper size' (s + 1) (IPush n :: insns)))) ;\n               (if (s >= 1)? then 1 else 0,\n                (op <- (elems [ OSucc ; OPred ]) ;;\n                    (genSizedinsns_helper size' s (IUnOp op :: insns)))) ;\n               (if (s >= 2)? then 1 else 0,\n                (op <- (elems [ OPlus ; OMult ; OMinus ]) ;;\n                    (genSizedinsns_helper size' (s - 1) (IBinOp op :: insns)))) ;\n               (if (s >= 3)? then 1 else 0,\n                (genSizedinsns_helper size' (s - 2) (IChoose :: insns))) ;\n               (** We add a case to generate the [IDont] instruction *)\n               (size, genSizedinsns_helper size' s (IDont :: insns))\n           ]\n    end.\n\n  Fixpoint genSizedinsns (size : nat) : G (list instruction) :=\n    rev_insns <- (genSizedinsns_helper size 0 []) ;;\n              ret (rev rev_insns).\n *)\n  Definition decompiles (insns : list instruction) :=\n    match decompile insns with\n    | Some _ => true\n    | None => false\n    end.\n\n(*   Instance eq_dec_insns (insns1 insns2 : list instruction) : Dec (insns1 = insns2) := {}.\n  Proof. dec_eq. Defined.\n *)\n  (** We state the right-inverse proposition again for use with\n      QuickChick.  *)\n\n(*   Definition compile_decompile_test (ins : list instruction) :=\n    (decompiles ins) ==> match (decompile ins) with\n                         | Some e => (compile e = ins)?\n                         | None => false\n                         end.\n *)\n  (** Checking should result in an error as soon as a program contains\n      the [IDont] instruction.  *)\n\n(*   QuickChick (forAll (genSizedinsns 5) compile_decompile_test). *)\n\n  (** QuickChick returns the expected results:\n   \n   > [IDont; IDont; IPush 20; IDont; IDont]\n   \n   > Failed after 1 tests and 0 shrinks. (0 discards)\n\n   The right-inverse property does not hold.\n  *)\n\n  (** The reasoning behind the right-inverse property not holding for\n      this language (with the added no-op) is that that there is no way\n      of producing an [IDont] instruction from the compiler. Decompiling\n      an expression simply ignores [IDont] instructions, causing there\n      to be multiple programs decompiling to the same\n      expression. Decompiling a program containing [IDont] instructions\n      and compiling it imediately afterwards should yield the same\n      program with the [IDont] instructions removed.\n\n*)\n\nEnd Nop.\n\n\n\n\nFrom Coq Require Import Extraction.\nFrom Coq Require Import List.\nDeclare ML Module \"coq_spec\".\nFrom Hammer Require Import Hammer.\nFrom Hammer Require Import Reconstr.\nAdd LoadPath \"~/Documents/cpdt/src\" as Cpdt.\nRequire Import Cpdt.CpdtTactics.\n\nExtract Inductive bool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\nExtract Inductive option => \"Prelude.Maybe\" [ \"Prelude.Just\" \"Prelude.Nothing\" ].\nExtract Inductive unit => \"()\" [ \"()\" ].\nExtract Inductive list => \"([])\" [ \"([])\" \"(:)\" ].\nExtract Inductive prod => \"(,)\" [ \"(,)\" ].\n\nExtract Inductive sumbool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\nExtract Inductive sumor => \"Prelude.Maybe\" [ \"Prelude.Just\" \"Prelude.Nothing\" ].\nExtract Inductive sum => \"Prelude.Either\" [ \"Prelude.Left\" \"Prelude.Right\" ].\n\nExtract Inlined Constant andb => \"(Prelude.&&)\".\nExtract Inlined Constant orb => \"(Prelude.||)\".\nExtract Inlined Constant negb => \"(Prelude.not)\".\nExtract Inlined Constant app => \"(Prelude.++)\".\n\n(* DiscoverLemmas \"DecompilerTest\" Main.stack_machine_functions Main.eval  Main.compile . *)\n\n(** END OF DOCUMENT. *)\n\n(* Local Variables: *)\n(* fill-column: 72 *)\n(* End: *)\n", "meta": {"author": "mikkelmilo", "repo": "rooster-spec", "sha": "a922f7a27d7c34b2584bdb7213e1b8960201271a", "save_path": "github-repos/coq/mikkelmilo-rooster-spec", "path": "github-repos/coq/mikkelmilo-rooster-spec/rooster-spec-a922f7a27d7c34b2584bdb7213e1b8960201271a/theories/DecompilerTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.9046505447409665, "lm_q1q2_score": 0.7922811820042622}}
{"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  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  f_equal.\n  rewrite IHn.\n  ring.\nQed.\n\nRequire Import Lists.List.\n\nFixpoint sum (xs : list nat) : nat :=\n  match xs with\n  | nil => 0\n  | x :: xs => x + sum xs\n  end.\n\nTheorem Pigeon_Hole_Principle :\n  forall (xs : list nat), length xs < sum xs -> (exists x, 1 < x /\\ In x xs).\nProof.\n  intros.\n  induction xs.\n  contradict H.\n  simpl.\n  apply Lt.lt_irrefl.\n  simpl in H.\n  \n  \n  ", "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/exercise3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7922220226868114}}
{"text": "Add LoadPath \"C:\\Users\\Jonathan\\source\\repos\\PLT-Coq\\Software Foundations\\Logical Foundations\".\nRequire Export Induction.\n\nModule NatList.\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\nend.\n\nDefinition snd (p: natprod) : nat :=\n  match p with\n  | pair x y => y\nend.\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\nend.\n\nDefinition snd' (p: natprod) : nat :=\n  match p with\n  | (x,y) => y\nend.\n\nDefinition swap_pair (p: natprod) : natprod :=\n  match p with\n  | (x, y) => (y,x)\nend.\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_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 [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(* Exercise snd_fst_is_swap *)\n\nTheorem snd_fst_is_swap : forall (p: natprod),\n (snd p, fst p) = swap_pair p.\nProof.\n  intros [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(* Exercise fst_swap_is_snd *)\n\nTheorem fst_swap_is_snd : forall (p: natprod),\n  fst(swap_pair p ) = snd p.\nProof.\n  intros [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(* Lists of Numbers *)\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')\nend.\n\nFixpoint length (l: natlist) : nat :=\n  match l with \n  | nil => 0\n  | h :: t => S (length t)\nend.\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)\nend.\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\nend.\n\nDefinition tl (l: natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\nend.\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 list_funs *)\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. 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 : oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers (l: natlist) : nat := length (oddmembers l).\n\nExample test_coundoddmembers1 : 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_countmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(* Exercise alternate *)\nFixpoint alternate (l_1 l_2 : natlist) : natlist :=\n  match l_1 with\n  | nil => l_2\n  | h_1 :: t_1 => match l_2 with\n              | nil => h_1 :: t_1\n              | h_2 :: t_2 => h_1 :: h_2 :: (alternate t_1 t_2)\n              end\nend.\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\nDefinition bag := natlist.\n\n(* Exercise bag_functions *)\n\nFixpoint count (v: nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => match (beq_nat v h) with\n              | true => 1 + (count v t)\n              | false => 0 + (count v t)\n  end\nend.\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.\n\nExample test_add2 : count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v: nat) (s: bag) : bool := blt_nat 0 (count v s).\n\nExample test_member : member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2 : member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* Exercise bag_more_functions *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match (beq_nat h v) with\n              | true => t\n              | false => h :: (remove_one v t)\n  end\nend.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2 : count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one3 : count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\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  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\nend.\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 => andb (member h s_2) (subset t (remove_one h s_2))\nend.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* Reasoning about lists *)\n\nTheorem nil_app : forall l:natlist, [] ++ 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\n(* Induction on lists *)\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. induction l_1 as [| n l' IHl1'].\n  - reflexivity.\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]\nend.\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 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. rewrite <- IHl'.\nAbort.\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 IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. 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  - reflexivity.\n  - simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(* Exercise list_exercises *)\n\nTheorem app_nil_r : forall l : natlist, l ++ [] = l.\nProof.\n  induction l.\n  - reflexivity.\n  - intros. simpl. rewrite -> IHl. reflexivity.\nQed.\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  induction l_1.\n  - intros. \n    rewrite nil_app.\n    simpl. \n    rewrite app_nil_r.\n    reflexivity.\n  - intros.\n    simpl.\n    rewrite IHl_1.\n    rewrite app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist, \n  rev (rev l) = l.\nProof.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl'. reflexivity.\nQed.\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. rewrite -> app_assoc. rewrite -> app_assoc. 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. induction l_1 as [| n l_1' IHl1'].\n  + reflexivity.\n  + destruct n as [| n']. \n    - simpl. rewrite -> IHl1'. reflexivity.\n    - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n(* Exercises beq_natlist *)\nFixpoint beq_natlist (l_1 l_2 : natlist) : bool :=\n  match l_1 with\n  | [] => beq_nat (length l_2) 0\n  | h_1 :: t_1 => match l_2 with\n                  | [] => false\n                  | h_2 :: t_2 => match beq_nat h_1 h_2 with\n                                  | true => beq_natlist t_1 t_2\n                                  | false => false\n                  end\n  end\nend.\n\nExample test_beq_natlist : (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_nat_refl: forall n, beq_nat n n = true.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem beq_natlist_refl : forall l: natlist,\n  true = beq_natlist l l.\nProof.\n  induction l as [|n' l' IHl'].\n  + reflexivity.\n  + simpl. rewrite -> beq_nat_refl. rewrite -> IHl'. reflexivity.\nQed.\n\n(* Exercise  count_member_nonzero *)\nTheorem count_member_nonzero : forall (s: bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros. reflexivity.\nQed.\n\nTheorem ble_n_Sn: forall n : nat,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. 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  induction s as [|n s' IHs'].\n  - reflexivity.\n  - induction n as [|n' IHn'].\n    + simpl. rewrite -> ble_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs'. reflexivity.\nQed.\n\nTheorem rev_injective : forall (l_1 l_2 : natlist),\n  rev l_1 = rev l_2 -> l_1 = l_2.\nProof.\n  intros. \n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive. \n  reflexivity.\nQed.\n\nFixpoint nth_bad (l: natlist) (n: nat) : nat :=\n  match l with\n  | nil => 42\n  | a :: l' => match beq_nat n 0 with\n                | true => a\n                | false => nth_bad l' (pred n)\n  end\nend.\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\nend.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\n\nExample test_nth_error2: nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\n\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' => if beq_nat n O then Some a else nth_error' l' (pred n)\nend.\n\nDefinition option_elim (d: nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\nend.\n\n(* Exercise hd_error *)\n\nDefinition hd_error (l : natlist): natoption :=\n  match l with\n  | [] => None\n  | a :: t' => Some a\nend.\n\nExample test_hd_error1: hd_error [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(* Exercise option_elim_hd *)\n\nTheorem option_elim_hd : forall (l: natlist) (default: nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n\n(* Partial Maps *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x_1 x_2 : id) :=\n  match x_1, x_2 with\n  | Id n_1, Id n_2 => beq_nat n_1 n_2\nend.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  destruct x.\n  simpl.\n  rewrite beq_nat_refl.\n  reflexivity.\nQed.\nEnd NatList.\nModule PartialMap.\nExport NatList.\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'\nend.\n\n(* Exercise update_eq *)\n\nTheorem update_eq : forall (d: partial_map) (x : id) (v: nat),\n  find x (update d x v) = Some v.\nProof.\n  intros.\n  simpl.\n  rewrite <- beq_id_refl.\n  reflexivity.\nQed.\n\n(* Exercise udpate_neq *)\n\nTheorem update_neq : forall (d: partial_map) (x y : id) (o : nat),\n  beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\nEnd PartialMap.\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.9136765269395709, "lm_q1q2_score": 0.7921902186092922}}
{"text": "(**\nCoq/SSReflect/MathComp による定理証明\n\n3.15 コマンド Record, Canonical\n======\n2018_04_22 @suharahiromichi\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n(**\n# 3.15.1 コマンド Record - Magma マグマ の定義\n*)\n\n(**\n## 例1: 集合Mと、M上の二項演算*の組 [(M, * )] Magma の形式化\n*)\nRecord magma : Type :=                      (* 型クラス *)\n  Magma {\n      carrier : Type;\n      operator : carrier -> carrier -> carrier\n    }.\n\nCheck magma : Type.\nCheck Magma : forall carrier : Type, (carrier -> carrier -> carrier) -> magma.\n\n(** ****************** *)\n(** Magma [(Prop, /\\)] *)\n(** ****************** *)\nCheck and.                             (* Prop -> Prop -> Prop *)\nDefinition prop_and_magma := @Magma Prop and. (* 型インスタンス *)\n\nPrint prop_and_magma.\n(** [{| carrier := Prop; operator := and |} : magma] *)\nCompute carrier prop_and_magma.      (* 台 Prop を取り出す。 *)\nCompute @operator prop_and_magma.    (* オペレータ and を取り出す。 *)\n\nLemma PropMagmaFalse (x y : carrier prop_and_magma) :\n  operator x False -> y.\nProof.\n  rewrite /=; by case.\nQed.\n\nLemma PropMagmaFalse'' (x y : carrier prop_and_magma) :\n  @operator prop_and_magma x False -> y.\nProof.\n  rewrite /=; by case.\nQed.\n\n(** 同じことを Magma を使わずに定義する。 *)\nLemma PropFalse (x y : Prop) : and x False -> y.\nProof.\n    by case.\nQed.\n\n(** **************** *)\n(** Magma [(nat, +)] *)\n(** **************** *)\nDefinition nat_plus_magma := @Magma nat plus. (* 型インスタンス *)\n\nPrint nat_plus_magma.\n(** [{| carrier := nat; operator := Init.Nat.add |} : magma] *)\nCompute carrier nat_plus_magma.     (* 台 nat を取り出す。 *)\nCompute @operator nat_plus_magma.   (* オペレータ plus を取り出す。 *)\n\nLemma NatMagmaPlus (x y : carrier nat_plus_magma) :\n  operator x y = x + y.\nProof.\n  rewrite /=; by [].\nQed.\n\nLemma NatMagmaPlus'' (x y : carrier nat_plus_magma) :\n  @operator nat_plus_magma x y = x + y.\nProof.\n  rewrite /=; by [].\nQed.\n\n(** 同じことを Magma を使わずに定義する。 *)\nLemma NatPlus (x y : nat) :\n  plus x y = x + y.\nProof.\n  done.\nQed.\n\n(**\n## 例2: 代数構造の階層、半群の例\n*)\nRecord semigroup : Type :=                  (* 型クラス *)\n  Semigroup {\n      scarrier : magma;\n      assoc : forall a b c : carrier scarrier,\n          operator a (operator b c)\n          = operator (operator a b) c\n    }.\n(**\ncarrier の型引数が省略されている。\n[[\n      assoc : forall a b c : carrier scarrier,\n          @operator scarrier a (@operator scarrier b c)\n          = @operator scarrier (@operator scarrier a b) c\n]]\n*)\n\n(** *************** *)\n(** 半群 [(nat, +)] *)\n(** *************** *)\nCheck addnA : associative addn.\nCheck addnA 1 2 3 : 1 + (2 + 3) = 1 + 2 + 3.\n\nDefinition nat_plus_semigroup := @Semigroup nat_plus_magma addnA. (* 型インスタンス *)\n\nPrint nat_plus_semigroup.\n(** [{| scarrier := nat_plus_magma; assoc := addnA |}] *)\n\n(**\n# 3.15.2 コマンド Canonical\n*)\n\nCanonical nat_plus_magma.\nPrint Canonical Projections.                (* カノニカルの表示 *)\n(** [nat <- carrier ( nat_plus_magma )]  *)\n\nLemma NatMagmaPlus' (x y : nat) :\n  operator x y = x + y.\nProof.\n  rewrite /=; by [].\nQed.\n\n(* ********* *)\n\nCanonical nat_plus_semigroup.\nPrint Canonical Projections.                (* カノニカルの表示 *)\n(** [nat_plus_magma <- scarrier ( nat_plus_semigroup )] *)\n\nNotation \"a ^^ b\" := (@operator _ a b) (at level 30, right associativity).\n(** 次でも同じ： *)\n(** [Notation \"a ^^ b\" := (operator a b) (at level 30, right associativity).] *)\n\n(** [Canonical nat_plus_magma]  がなくても良い例  *)\n(** [Canonical nat_plus_semigroup] がなくても良い例  *)\nSection TEST1.\n  Variable a b : carrier nat_plus_magma.\n  \n  Check @operator nat_plus_magma :\n    carrier nat_plus_magma -> carrier nat_plus_magma -> carrier nat_plus_magma.\n  Check @operator nat_plus_magma a b : carrier nat_plus_magma.\n  Check a ^^ b : carrier nat_plus_magma.\n  \n  Lemma natPlusExample1 (x y z : carrier nat_plus_magma) :\n    x ^^ (y ^^ z) = (x ^^ y) ^^ z.\n  Proof.\n      by rewrite (@assoc nat_plus_semigroup).\n  Qed.\nEnd TEST1.\n\n\n(** [Canonical nat_plus_magma] は必要。 *)\n(** [Canonical nat_plus_semigroup] がなくても良い例  *)\nSection TEST2.\n  Variable a b : nat.\n  \n  Check @operator nat_plus_magma :\n    carrier nat_plus_magma -> carrier nat_plus_magma -> carrier nat_plus_magma.\n  Compute carrier nat_plus_magma.           (* nat *)\n  Check @operator nat_plus_magma : nat -> nat -> nat.\n  Check @operator nat_plus_magma a b : carrier nat_plus_magma.\n  \n  Check operator a b : carrier nat_plus_magma. (* canonical 宣言が必要 *)\n  Check a ^^ b  : carrier nat_plus_magma.\n\n  Check @operator nat_plus_magma a b : nat.\n  Check operator a b : nat.\n  Check a ^^ b  : nat.\n  \n  Lemma natPlusExample2 (x y z : nat) :\n    x ^^ (y ^^ z) = (x ^^ y) ^^ z.\n  Proof.\n      by rewrite (@assoc nat_plus_semigroup).\n  Qed.\nEnd TEST2.\n\n(** [Canonical nat_plus_magma] は必要。 *)\n(** [Canonical nat_plus_semigroup]  は必要。 *)\nLemma natPlusExample3 (x y z : nat) :\n  x ^^ (y ^^ z) = (x ^^ y) ^^ z.\nProof.\n    by rewrite assoc.\nQed.\n\n(**\n# 補足\n*)\n\n(** ****************** *)\n(** Magma [(Prop, /\\)] *)\n(** ****************** *)\n\n(**\n既存の [^] の定義により、Propに対する演算ができない（？）ので、\n全体に対して [^^] を使うようにした。\n *)\n\n(** [Canonical prop_and_magma] がなくても良い例  *)\nLemma PropMagmaFalse1 (x y : carrier prop_and_magma) :\n  x ^^ False -> y.\nProof.\n  rewrite /=; by case.\nQed.\n\n(* ********* *)\n(* ********* *)\n\nCanonical prop_and_magma.\nPrint Canonical Projections.                (* カノニカルの表示 *)\n(** [Prop <- carrier ( prop_and_magma )] *)\n\nLemma PropMagmaFalse2' (x y : Prop) :\n  operator x False -> y.\nProof.\n  rewrite /=; by case.\nQed.\n\n(** [Canonical prop_and_magma] が必要 *)\nLemma PropMagmaFalse2 (x y : Prop) :\n  x ^^ False -> y.\nProof.\n  rewrite /=; by case.\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/csm/csm_3_15_magma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.7921625646547718}}
{"text": "\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\n\nLemma excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n unfold peirce; intros H P Q H0.\n destruct (H P) as [p | np].\n -  assumption.\n -  apply H0; intro H1; now absurd P.\nQed.\n\nLemma peirce_classic : peirce -> classic.\nProof.\n intros HPeirce P H0; apply (HPeirce P False).\n intro H1; now destruct H0.\nQed.\n\nLemma classic_excluded_middle: classic -> excluded_middle.\nProof.\n unfold excluded_middle, classic; intros H P.\n apply H. intro H0. absurd P.\n -  intro H1. apply H0. now left.\n -  apply H; intro H1; apply H0; now right.\nQed.\n\n\nLemma excluded_middle_implies_to_or :  excluded_middle -> implies_to_or.\nProof.\n intros H P Q H0;\n  destruct (H P) as [p | np].\n  -  right; auto.\n  - now  left.\nQed.\n\nLemma implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P; destruct (H P P);auto.\nQed.\n\nLemma classic_de_morgan_not_and_not : classic -> \n                                      de_morgan_not_and_not.\nProof.\n unfold de_morgan_not_and_not; intros H P Q H0.\n apply H.\n intro H1; apply H0; split;intro;apply H1; auto.\nQed.\n\nLemma de_morgan_not_and_not_excluded_middle : de_morgan_not_and_not ->\n                                              excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intros [H1 H2]; contradiction. \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/class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7921610021156611}}
{"text": "Require Import Vector Arith Bool List Nat.\n\n(** Remove the following axiom when you've finished all the exercises. This\naxoim provides a value of any type to allow the file to compile and incomplete\nexpressions to be used.\n *)\nAxiom fill_me : forall {X : Type}, X.\n\n(** Definitions used in the exercises **)\n\nDefinition leq : nat -> nat -> Prop :=\n  fun m n => exists k, k + m = n.\n\nDefinition Even : nat -> Prop :=\n  fun n => exists k, n = 2 * k.\n\n\n(** Exercise 1.1\n\nState and prove that 3 is not less than 1.\n\n *)\n\nLemma three_not_leq_one : ~ (leq 3 1).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 1.2\n\nProve that any natural number is not equal to its sucessor.\n\nHints:\n\n1. The following facts are available in the library:\n\n[[\n   O_S: forall n : nat, 0 <> S n\n\n   eq_add_S: forall n m : nat, S n = S m -> n = m\n]] \n\nYou can find these facts using:\n\n[[\n   Search (0 = S _).\n   Search (S _ = S _ -> _ = _).\n]]\n\n2. The notation <> corresponds to not. You can find this out using:\n[[\n   Locate \"<>\".\n]]\n *)\n\nLemma n_not_S_n : forall n, n <> S n.\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 1.3\n\nState and prove that for every Nat n, the successor of n is not less\nthan or equal to n.\n\n*)\n\nLemma Sn_not_leq_n : forall n, ~ (leq (S n) n).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 1.4\n\nState and prove that 1 is not Even.\n\n *)\n\nLemma three_is_not_even : ~ (Even 1).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 1.5\n\nUsing induction on a Vector, define a function called [rest] that\naccepts any non-nil vector and returns a new vector with the first element\nremoved.\n\nHint:\n\nTry to use the [induction] tactic on a vector. You'll probably need to define\nan auxilliary function that plays the same role as the nested [ind-Vec] in\nframe 15.74 of the little typer book.\n *)\n\nDefinition rest : forall E l, Vector.t E (S l) -> Vector.t E l.\n  exact fill_me.\nQed.\n\n(** Logical exercises **)\n\n(** Exercise 1.6\n\nProve that the Principle of the Excluded Middle (PEM) is equivalent to using double\nnegation to prove a proposition.\n\nHint:\n\nTo prove that double negation imples excluded middle you'll need to use the evidence\nfor the double negation of the exluded middle, [double_neg_pem].\n *)\n\nDefinition double_neg_pem : forall X, ~~ (X \\/ ~ X) :=\n  fun X pem_false => (pem_false (or_intror (fun x => (pem_false (or_introl x))))).\n\n(** NB: This theorem can be proved with only a single quantifier. The converse is not\ntrue with a single quantifier. It's still possible to prove that excluded middle and double\nnegation are equivalent but quantifiers on both sides of the implication are required ([double_neg_imples_pem]) *)\nTheorem pem_X_imples_double_neg_X : forall X, (X \\/ ~ X) -> ((~~ X) -> X).\nProof.\n  exact fill_me.\nQed.\n\nTheorem pem_imples_double_neg : (forall X, (X \\/ ~ X)) -> (forall Y, ((~~ Y) -> Y)).\nProof.\n  exact fill_me.\nQed.\n\nTheorem double_neg_implies_pem : (forall X, ((~~ X) -> X)) -> (forall Y, (Y \\/ ~ Y)).\nProof.\n  exact fill_me.\nQed.\n", "meta": {"author": "paulcadman", "repo": "certified-programming", "sha": "0ad19c922948c1c05e19f7805a9a54f1f9903df5", "save_path": "github-repos/coq/paulcadman-certified-programming", "path": "github-repos/coq/paulcadman-certified-programming/certified-programming-0ad19c922948c1c05e19f7805a9a54f1f9903df5/src/exercises/little-typer-01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.7921513375375044}}
{"text": "From Coq Require Import Nat.\n\nInductive even: nat -> Prop :=\n  | evenO : even  O \n  | evenS : forall n, odd n -> even (S n)\n  with\n    odd  : nat -> Prop :=\n    | oddS : forall n, even n -> odd (S n).\n\nTheorem even_plus_four : forall n:nat, even n -> even (4 + n).\nProof.\n intros n H.\n elim H.\n  - simpl. repeat constructor.\n  - simpl. repeat constructor. assumption.\nQed. \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/Elim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561676667172, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7921120802468159}}
{"text": "Require Import ZArith.\nRequire Import Reals.\nRequire Import Flocq.Core.Fcore_Raux.\nRequire Import Flocq.Core.Fcore_defs.\nRequire Import Flocq.Core.Fcore_float_prop.\nRequire Import Flocq.Calc.Fcalc_ops.\nRequire Import Gappa_definitions.\n\nLemma float2_zero :\n  forall e : Z, Float2 0 e = R0 :>R.\nProof.\nintro e.\napply F2R_0.\nQed.\n\nDefinition Fopp2 (x : float2) :=\n  Float2 (- Fnum x) (Fexp x).\n\nLemma Fopp2_correct :\n  forall x : float2,\n  Fopp2 x = (- x)%R :>R.\nProof.\nintros x.\nunfold float2R, Fopp2. simpl.\napply F2R_Zopp.\nQed.\n\nDefinition Fmult2 (x y : float2) :=\n  Float2 (Fnum x * Fnum y) (Fexp x + Fexp y).\n\nDefinition Fmult2_correct :\n  forall x y : float2,\n  Fmult2 x y = (x * y)%R :>R.\nProof.\nintros (mx, ex) (my, ey).\nexact (F2R_mult radix2 (Float radix2 mx ex) (Float radix2 my ey)).\nQed.\n\nDefinition shl (m : Z) (d : positive) :=\n match m with\n | Z0 => Z0\n | Zpos p => Zpos (shift_pos d p)\n | Zneg p => Zneg (shift_pos d p)\n end.\n\nLemma float2_shl_correct :\n  forall m e : Z, forall d : positive,\n  Float2 (shl m d) (e - Zpos d) = Float2 m e :>R.\nProof.\nintros m e d.\nreplace (shl m d) with (m * Zpower_pos 2 d)%Z.\nunfold float2R.\nrewrite (F2R_change_exp _ (e - Zpos d) _ e).\nsimpl.\nnow replace (e - (e - Zpos d))%Z with (Zpos d) by ring.\ngeneralize (Zgt_pos_0 d).\nomega.\nrewrite Zmult_comm.\ndestruct m as [|m|m] ; simpl.\napply Zmult_0_r.\nnow rewrite shift_pos_correct.\nchange (Zneg (shift_pos d m)) with (- Zpos (shift_pos d m))%Z.\nrewrite shift_pos_correct.\nnow rewrite Zopp_mult_distr_r.\nQed.\n\nDefinition Fshift2 (x y : float2) :=\n match (Fexp x - Fexp y)%Z with\n | Zpos p => (shl (Fnum x) p, Fnum y, Fexp y)\n | Zneg p => (Fnum x, shl (Fnum y) p, Fexp x)\n | Z0 => (Fnum x, Fnum y, Fexp x)\n end.\n\nLemma Fshift2_correct :\n  forall x y : float2,\n  match Fshift2 x y with\n  | (mx, my, e) => Float2 mx e = x :>R /\\ Float2 my e = y :>R\n  end.\nProof.\nintros (mx, ex) (my, ey).\nunfold Fshift2. simpl.\nassert (ex = ex - ey + ey)%Z by ring.\npattern ex at - 1 ; rewrite H.\ndestruct (ex - ey)%Z as [|d|d] ; repeat split.\nrewrite <- (float2_shl_correct mx _ d).\nnow ring_simplify (Zpos d + ey - Zpos d)%Z.\nrewrite Zplus_comm.\napply float2_shl_correct.\nQed.\n\nDefinition Fplus2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, e) => Float2 (mx + my) e\n end.\n\nLemma Fplus2_correct :\n  forall x y : float2,\n  Fplus2 x y = (x + y)%R :>R.\nProof.\nintros x y.\nunfold Fplus2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite Z2R_plus.\napply Rmult_plus_distr_r.\nQed.\n\nDefinition Fminus2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, e) => Float2 (mx - my) e\n end.\n\nLemma Fminus2_correct :\n  forall x y : float2,\n  Fminus2 x y = (x - y)%R :>R.\nProof.\nintros x y.\nunfold Fminus2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite Z2R_minus.\napply Rmult_minus_distr_r.\nQed.\n\nDefinition Fcomp2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, _) => (mx ?= my)%Z\n end.\n\nLemma Fcomp2_correct :\n  forall x y : float2,\n  Fcomp2 x y = Rcompare x y.\nProof.\nintros x y.\nunfold Fcomp2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite Rcompare_mult_r.\nnow rewrite Rcompare_Z2R.\napply bpow_gt_0.\nQed.\n\nLemma power_radix_pos :\n  forall r e, (0 < powerRZ (P2R r) e)%R.\nintros.\napply powerRZ_lt.\nchange (P2R r) with (Z2R (Zpos r)).\napply (Z2R_lt 0).\nexact (refl_equal _).\nQed.\n\nDefinition Feq2 (x y : float2) :=\n match Fcomp2 x y with\n | Eq => true\n | _ => false\n end.\n\nLemma Feq2_correct :\n  forall x y : float2,\n  Feq2 x y = true -> x = y :>R.\nProof.\nintros x y Hb.\napply Rcompare_Eq_inv.\nrewrite <- Fcomp2_correct.\nrevert Hb.\nunfold Feq2.\nnow case Fcomp2.\nQed.\n\nDefinition Flt2 (x y : float2) :=\n match Fcomp2 x y with\n | Lt => true\n | _ => false\n end.\n\nLemma Flt2_correct :\n  forall x y : float2,\n  Flt2 x y = true -> (x < y)%R.\nProof.\nintros x y Hb.\napply Rcompare_Lt_inv.\nrewrite <- Fcomp2_correct.\nrevert Hb.\nunfold Flt2.\nnow case Fcomp2.\nQed.\n\nDefinition Fle2 (x y : float2) :=\n match Fcomp2 x y with\n | Gt => false\n | _ => true\n end.\n\nLemma Fle2_correct :\n  forall x y : float2,\n  Fle2 x y = true -> (x <= y)%R.\nProof.\nintros x y Hb.\napply Rcompare_not_Gt_inv.\nrewrite <- Fcomp2_correct.\nintros H.\nunfold Fle2 in Hb.\nnow rewrite H in Hb.\nQed.\n\nInductive Fle2_prop (x y : float2) : bool -> Prop :=\n  | Fle2_true : (x <= y)%R -> Fle2_prop x y true\n  | Fle2_false : (y < x)%R -> Fle2_prop x y false.\n\nLemma Fle2_spec :\n  forall x y, Fle2_prop x y (Fle2 x y).\nProof.\nintros x y.\ncase_eq (Fle2 x y) ; intros H.\napply Fle2_true.\napply Fle2_correct.\nexact H.\ngeneralize H. clear H.\nunfold Fle2.\ncase_eq (Fcomp2 x y) ; try (intros ; discriminate).\nintros H _.\napply Fle2_false.\napply Rcompare_Gt_inv.\nnow rewrite <- Fcomp2_correct.\nQed.\n\nDefinition Fis0 (x : float2) :=\n match (Fnum x) with\n   Z0 => true\n | _ => false\n end.\n\nLemma Fis0_correct :\n forall x : float2,\n Fis0 x = true -> x = R0 :>R.\nintros x.\nunfold Fis0.\ninduction x.\ninduction Fnum ; intro H0 ; try discriminate.\napply float2_zero.\nQed.\n\nDefinition Fpos (x : float2) :=\n match (Fnum x) with\n   Zpos _ => true\n | _ => false\n end.\n\nLemma Fpos_correct :\n  forall x : float2,\n  Fpos x = true -> (0 < x)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_gt_0_compat. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fneg (x : float2) :=\n match (Fnum x) with\n   Zneg _ => true\n | _ => false\n end.\n\nLemma Fneg_correct :\n  forall x : float2,\n  Fneg x = true -> (x < 0)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_lt_0_compat. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fpos0 (x : float2) :=\n match (Fnum x) with\n   Zneg _ => false\n | _ => true\n end.\n\nLemma Fpos0_correct :\n  forall x : float2,\n  Fpos0 x = true -> (0 <= x)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_ge_0_compat. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fneg0 (x : float2) :=\n match (Fnum x) with\n   Zpos _ => false\n | _ => true\n end.\n\nLemma Fneg0_correct :\n  forall x : float2,\n  Fneg0 x = true -> (x <= 0)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_le_0_compat. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Flt2_m1 f :=\n  Flt2 (Float2 (-1) 0) f.\n\nLemma Flt2_m1_correct :\n  forall f,\n  Flt2_m1 f = true ->\n  (-1 < f)%R.\nProof.\nintros f Hb.\ngeneralize (Flt2_correct _ _ Hb).\nunfold float2R, F2R. simpl.\nnow rewrite Rmult_1_r.\nQed.\n\nDefinition Fle2_m1 f :=\n  Fle2 (Float2 (-1) 0) f.\n\nLemma Fle2_m1_correct :\n  forall f,\n  Fle2_m1 f = true ->\n  (-1 <= f)%R.\nProof.\nintros f Hb.\ngeneralize (Fle2_correct _ _ Hb).\nunfold float2R, F2R. simpl.\nnow rewrite Rmult_1_r.\nQed.\n", "meta": {"author": "cartazio", "repo": "gappa-coq", "sha": "2d72e2f71a9f52a04bdf878b2fddea573aced0fa", "save_path": "github-repos/coq/cartazio-gappa-coq", "path": "github-repos/coq/cartazio-gappa-coq/gappa-coq-2d72e2f71a9f52a04bdf878b2fddea573aced0fa/src/Gappa_dyadic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.792043218273934}}
{"text": "From Coq Require Import Arith.\nFrom Coq Require Import Lt.\nFrom Coq Require Export Setoid.\nFrom Coq Require Lia.\nSet Implicit Arguments.\nSet Strict Implicit.\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\nArguments full : clear implicits.\nArguments empty : clear implicits.\n\nLemma equiv_refl : forall P:set, equiv P P.\nunfold equiv; intuition.\nQed.\n\nLemma equiv_sym : forall P Q:set, equiv P Q -> equiv Q P.\nunfold equiv; firstorder.\nQed.\n\nLemma equiv_trans : forall P Q R:set, \n   equiv P Q -> equiv Q R -> equiv P R.\nunfold equiv; firstorder.\nQed.\n\nHint Resolve equiv_refl: core.\nHint Immediate equiv_sym: core.\n\n(** ** Setoid structure *)\nLemma set_setoid : Setoid_Theory set equiv.\nsplit; red; auto.\nexact equiv_trans.\nQed. \n\n\n\nAdd Relation set equiv\n  reflexivity proved by equiv_refl\n  symmetry proved by equiv_sym\n  transitivity proved by equiv_trans\nas Set_setoid.\n\n\n\nAdd Parametric Morphism a : (add a)\nwith signature (equiv ==> equiv) as equiv_add. \nunfold equiv,add; firstorder.\nQed.\n\nAdd Parametric Morphism a : (rem a)\nwith signature (equiv ==> equiv) as equiv_rem. \nunfold equiv,rem; firstorder.\nQed.\nHint Resolve equiv_add equiv_rem: core.\n\nAdd Morphism union \n with signature (equiv ==> equiv ==> equiv) as equiv_union.\nunfold equiv,union; firstorder.\nQed.\nHint Immediate equiv_union: core.\n\nLemma equiv_union_left : \n  forall P1 Q P2,\n   equiv P1 P2 -> equiv (union P1 Q) (union P2 Q).\nauto.\nQed.\n\nLemma equiv_union_right : \n  forall P Q1 Q2 ,\n   equiv Q1 Q2 -> equiv (union P Q1) (union P Q2).\nauto.\nQed.\n\nHint Resolve equiv_union_left equiv_union_right: core.\n\nAdd Morphism inter \n with signature (equiv ==> equiv ==> equiv) as equiv_inter.\nunfold equiv,inter; firstorder.\nQed.\nHint Immediate equiv_inter: core.\n\nAdd Morphism compl \n with signature (equiv ==> equiv) as equiv_compl.\nunfold equiv,union; firstorder.\nQed.\nHint Resolve equiv_compl: core.\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.\nQed.\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: core.\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: core.\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.\nQed.\n\n(** *** Size of a finite set *)\nFixpoint size (P:set) (f:finite P) {struct f}: nat :=\n   match f with \n              | fin_eq_empty _ => 0%nat\n              | fin_eq_add  _ 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.\nQed.\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.\nQed.\n\nLemma incl_trans : forall (P Q R:set), \nincl P Q -> incl Q R -> incl P R.\nunfold incl; intuition.\nQed.\n\nLemma equiv_incl : forall (P Q : set),  equiv P Q -> incl P Q.\nunfold equiv, incl; firstorder.\nQed.\n\nLemma equiv_incl_sym : forall (P Q : set), equiv P Q -> incl Q P.\nunfold equiv, incl; firstorder.\nQed.\n\nLemma equiv_incl_intro : \nforall (P Q : set), incl P Q -> incl Q P -> equiv P Q.\nunfold equiv, incl; firstorder.\nQed.\n\nHint Resolve incl_refl incl_trans equiv_incl_intro: core. \nHint Immediate equiv_incl equiv_incl_sym: core. \n\n(** ** Properties of operations on sets *)\n\nLemma incl_empty : forall P, incl empty P.\nunfold incl,empty; intuition.\nQed.\n\n\nLemma incl_empty_false : forall P a, incl P empty -> ~ P a.\nunfold incl; firstorder.\nQed.\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.\nQed.\n\nLemma equiv_empty_false : forall P a, equiv P empty -> P a -> False.\nunfold equiv; firstorder.\nQed.\n\nHint Immediate incl_empty_false equiv_empty_false incl_add_empty: core.\n\nLemma incl_rem_stable :   forall a P Q, incl P Q -> incl (rem a P) (rem a Q).\nunfold incl,rem;intuition.\nQed.\n\nLemma incl_add_stable :   forall a P Q, incl P Q -> incl (add a P) (add a Q).\nunfold incl,add;intuition.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\n\nHint Immediate incl_rem_add incl_add_rem: core.\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.\nQed.\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.\nQed.\n\nHint Immediate equiv_rem_add equiv_add_rem: core.\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.\nQed.\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.\nQed.\n\nLemma add_equiv_in : \n  forall x (P:set), P x -> equiv (add x P) P.\nunfold equiv, add; intuition.\nsubst;auto.\nQed.\n\nHint Resolve add_rem_eq_equiv add_rem_diff_equiv add_equiv_in: core.\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.\nQed.\n\nHint Resolve add_rem_equiv_in: core.\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.\nQed.\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.\nQed.\n\nLemma rem_equiv_notin : \n  forall x (P:set), ~P x -> equiv (rem x P) P.\nunfold equiv, rem; intuition.\nsubst;auto.\nQed.\n\nHint Resolve rem_add_eq_equiv rem_add_diff_equiv rem_equiv_notin: core.\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.\nQed.\n\nHint Resolve rem_add_equiv_notin: core.\n\n\nLemma rem_not_in : forall x (P:set), ~ rem x P x.\nunfold rem; intuition.\nQed.\n\nLemma add_in : forall x (P:set), add x P x.\nunfold add; intuition.\nQed.\n\nLemma add_in_eq : forall x y P, x=y -> add x P y.\nunfold add; intuition.\nQed.\n\nLemma add_intro : forall x (P:set) y, P y -> add x P y.\nunfold add; intuition.\nQed.\n\nLemma add_incl : forall x (P:set), incl P (add x P).\nunfold incl,add; intuition.\nQed.\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.\nQed.\n\nLemma rem_incl : forall x (P:set), incl (rem x P) P.\nunfold incl, rem; intuition.\nQed.\n\nHint Resolve rem_not_in add_in rem_incl add_incl: core.\n\nLemma union_sym : forall P Q : set,\n      equiv (union P Q) (union Q P).\nunfold equiv, union; intuition.\nQed.\n\nLemma union_empty_left : forall P : set,\n      equiv P (union P empty).\nunfold equiv, union, empty; intuition.\nQed.\n\nLemma union_empty_right : forall P : set,\n      equiv P (union empty P).\nunfold equiv, union, empty; intuition.\nQed.\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.\nQed.\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.\nQed.\n\nHint Resolve union_sym union_empty_left union_empty_right\nunion_add_left union_add_right : core.\n\nLemma union_incl_left : forall P Q, incl P (union P Q).\nunfold incl,union; intuition.\nQed.\n\nLemma union_incl_right : forall P Q, incl Q (union P Q).\nunfold incl,union; intuition.\nQed.\n\nLemma union_incl_intro : forall P Q R, incl P R -> incl Q R -> incl (union P Q) R.\nunfold incl,union; intuition.\nQed.\n\nHint Resolve union_incl_left union_incl_right union_incl_intro: core.\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.\nQed.\nHint Immediate incl_union_stable: core.\n\nLemma inter_sym : forall P Q : set,\n      equiv (inter P Q) (inter Q P).\nunfold equiv, inter; intuition.\nQed.\n\nLemma inter_empty_left : forall P : set,\n      equiv empty (inter P empty).\nunfold equiv, inter, empty; intuition.\nQed.\n\nLemma inter_empty_right : forall P : set,\n      equiv empty (inter empty P).\nunfold equiv, inter, empty; intuition.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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 : core.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\n\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.\nQed.\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.\nQed.\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.\nQed.\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.\nQed.\n\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). auto with arith. apply H.\nexists x; destruct FP; simpl in H.\nabsurd (1<1); auto with arith.\nexists x0; intuition.\ncase (e x); auto.\ncase (e0 x0); case (e x0); unfold add; intuition.\nsubst; case (e0 x0); intuition.\nQed.\n\nEnd sets.\n\nHint Resolve equiv_refl: core.\nHint Resolve equiv_add equiv_rem: core.\nHint Immediate equiv_sym finite_dec finite_full_dec equiv_incl equiv_incl_sym equiv_incl_intro: core.\n\nHint Resolve incl_refl: core.\nHint Immediate incl_union_stable: core.\nHint Resolve union_incl_left union_incl_right union_incl_intro incl_empty rem_incl\nincl_rem_stable incl_add_stable : core.\n\nHint Constructors finite: core.\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 : core.\nArguments full : clear implicits.\nArguments empty : clear implicits.\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": "coq-community", "repo": "alea", "sha": "0cd68687229aaa26623c7092d4b40e9a812f17bc", "save_path": "github-repos/coq/coq-community-alea", "path": "github-repos/coq/coq-community-alea/alea-0cd68687229aaa26623c7092d4b40e9a812f17bc/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.791991416868553}}
{"text": "Lemma L1: 6*6 = 9*4.\nProof.\n  reflexivity.\nQed.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(* you cannot use 'reflexivity here', a b are free variables\nunlike 6 9 4 and no reduction can take place, not unification *)\n\nLemma diff_of_squares : forall a b:Z, (a+b)*(a-b) = a*a - b*b.\nProof.\n  intros. ring.\nQed.\n\n\nTheorem eq_sym' : forall (A:Type)(a b :A), a = b -> b = a.\nProof.\n  intros A a b H. rewrite -> H. reflexivity.\nQed.\n\nCheck Zmult_plus_distr_l. (* forall n m p : Z, (n + m) * p = n * p + m * p *)\nCheck Zmult_1_l.          (* forall n : Z, 1 * n = n *)\n\nTheorem Zmult_distr_1 : forall n x:Z, n*x+x = (n+1)*x.\nProof.\n  intros n x.\n  (*\n  ring.\n  *)\n  rewrite Zmult_plus_distr_l.\n  rewrite Zmult_1_l.\n  reflexivity.\nQed.\n\n(* can also use 'rewrite ... in H', 'rewrite -> ... in H' or 'rewrite <- ... in H' *)\n\n\nTheorem regroup : forall x:Z, x+x+x+x+x = 5*x.\nProof.\n(*\n  intro x. ring.\n*)\n  intro. pattern x at 1. rewrite <- Zmult_1_l.\n  repeat rewrite Zmult_distr_1.\n  reflexivity.\nQed.\n\nOpen Scope nat_scope.\nCheck plus_comm.  (* forall n m : nat, n + m = m + n *)\nCheck plus_assoc. (* forall n m p : nat, n + (m + p) = n + m + p *)\n\nTheorem plus_permute2: forall n m p:nat, n+m+p = n+p+m.\nProof.\n  intros n m p. rewrite <- plus_assoc. rewrite plus_comm with (n:=m)(m:=p). \n  rewrite plus_assoc. reflexivity.\nQed.\n\nLemma le_lt_S_eq : forall n p:nat, n <= p -> p < S n -> n = p.\nProof.\n  intros n p. omega. (* we ll see this tactic later *)\nQed.\n\nCheck plus_lt_reg_l. (* forall n m p : nat, p + n < p + m -> n < m *)\nCheck plus_le_reg_l. (* forall n m p : nat, p + n <= p + m -> n <= m *)\nCheck plus_comm. (* forall n m : nat, n + m = m + n *)\n\n\nLemma cond_rewrite_example : forall n:nat,\n  8 <= n+6 -> 3+n < 6 -> n*n = n+n.\nProof.\n  intros n H0 H1.\n  rewrite <- le_lt_S_eq with (p:=n)(n:=2).\n  reflexivity.\n  apply plus_le_reg_l with (p:=6).\n  rewrite plus_comm with (n:=6)(m:=n). exact H0.\n  apply plus_lt_reg_l with (p:=3). exact H1.\nQed.\n\n\nCheck eq_ind. (* forall (A : Type) (x : A) (P : A -> Prop),\n                 P x -> forall y : A, x = y -> P y *)\n\nTheorem eq_trans1 : forall (A:Type)(x y z:A), x = y -> y = z -> x = z.\nProof.\n  intros A x y z eq_xy eq_yz. \n  apply eq_ind with (y:=z)(x:=y)(P:= fun u => x = u).\n  exact eq_xy. exact eq_yz.\nQed.\n\nTheorem eq_trans2 : forall (A:Type)(x y z:A), x = y -> y = z -> x = z.\nProof.\n  intros A x y z eq_xy eq_yz.\n  rewrite <- eq_yz. exact eq_xy.\nQed.\n\nCheck Zmult_1_l. (* forall n : Z, (1 * n)%Z = n *)\nSearchRewrite (1 * _).\n(*\nmult_1_l: forall n : nat, 1 * n = n\n*)\n\nSearchRewrite (1 * _)%Z. (* fail *)\n\nOpen Scope Z_scope.\nSearchRewrite (1 * _). (* fail *)\n\n\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/equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7919434823885431}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\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 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      evenb 4 = true ->\n      oddb 3 = true.\nProof.\n  intros eq1 eq2.\n  apply eq1. apply eq2.\nQed.\n(** [] *)\n\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl. \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  intros l l' H1.\n  rewrite ->H1.\n  symmetry.\n  apply rev_involutive.\nQed.\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(*\nrewrite 是重写，而apply是应用定理\n*)\n(* ################################################################# *)\n\n(** * The [apply with] 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  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. 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\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  intros n m o p eq1 eq2.\n  apply trans_eq with m.\n  -apply eq2.\n  -apply eq1.\nQed.\n  \n(** [] *)\n\n(* ################################################################# *)\n(** * The [injection] and [discriminate] Tactics *)\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\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(** 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\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  intros X x y z l j H1 H2.\n  injection H2 as H3 H4.\n  symmetry.\n  apply H3.\nQed.\n(** [] *)\n\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n  - (* n = S n' *)\n    simpl.\n    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\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  intros X x y z l j H1.\n  discriminate H1.\nQed.\n(** [] *)\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\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\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    intros m eq.\n    destruct m as [| m'] eqn:E.\n    + (* m = O *) simpl.\n      discriminate eq.\n    + (* m = S m' *)\n      apply f_equal.\n      apply IHn'. injection eq as goal. apply goal. Qed.\n      \n(** **** Exercise: 2 stars, standard (eqb_true)  *)\nLemma injective_S : forall n m,\n  n=m -> S n = S m.\nProof.\n  intros n m H.\n  rewrite -> H.\n  reflexivity.\nQed.\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  intros n. induction n as [|n' ].\n  -simpl. intros m eq. destruct m.\n    + reflexivity.\n    + discriminate eq.\n  -simpl. intros m eq. destruct m.\n    + discriminate eq.\n    + apply injective_S. apply IHn'. apply eq.\nQed.\n(** [] *)\n\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\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  -simpl. intros m eq. destruct m.\n    + reflexivity.\n    + discriminate eq.\n  -simpl. intros m eq. destruct m.\n    + discriminate eq.\n    + apply f_equal. apply IHn'. simpl in eq. apply S_injective' in eq. \n      rewrite <- plus_n_Sm in eq.\n      rewrite <- plus_n_Sm in eq.\n      apply S_injective' in eq.\n      apply eq.\nQed.\n(** [] *)\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\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  intros n X l.\n  generalize dependent n.\n  induction l.\n  -simpl. intros n eq. destruct n.\n    +reflexivity.\n    +discriminate eq.\n  -simpl. intros n eq. destruct n.\n    +discriminate eq.\n    +apply IHl. apply S_injective' in eq. rewrite -> eq. reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\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  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. 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  simpl.\n  reflexivity.\nQed.\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 : 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\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\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(** **** 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  intros X Y l.\n  induction l as[|x l].\n  -intros l1 l2 H.\n    simpl in H. injection H as H1 H2. rewrite <-H1. rewrite <- H2. reflexivity.\n  -intros l1 l2 H.\n    destruct x as [a b].\n    simpl in H. \n    destruct (split l) as [lx ly].\n    inversion H.\n    simpl.\n    assert(H': combine lx ly=l). { apply (IHl lx ly). reflexivity. }\n    rewrite H'.\n    reflexivity.\nQed.\n  \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  (* 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  intros f b.\n  destruct (f b) eqn:Bool.\n  -destruct b eqn:Bool1.\n    +rewrite -> Bool. rewrite -> Bool. reflexivity.\n    + destruct (f true) eqn:Bool2.\n      {rewrite-> Bool2. reflexivity. }\n      {rewrite->Bool. reflexivity. }\n  -destruct b eqn:flag.\n    + destruct (f false) eqn:flag1.\n      {rewrite ->Bool. reflexivity. }\n      {rewrite ->flag1. reflexivity. }\n    +rewrite -> Bool. rewrite -> Bool. reflexivity.\nQed.\n(** [] *)\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  intros n m.\n  destruct (n=?m) eqn:flag.\n  -apply eqb_true in flag. rewrite -> flag. rewrite <- eqb_refl. reflexivity. \n  -destruct (m=?n) eqn:flag1.\n    + apply eqb_true in flag1. rewrite ->flag1 in flag. rewrite <- eqb_refl in flag. discriminate flag.\n    +reflexivity.\nQed.\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  intros  n m p H1 H2.\n  apply eqb_true in H1.\n  apply eqb_true in H2.\n  rewrite -> H2 in H1.\n  rewrite -> H1.\n  rewrite <- eqb_refl.\n  reflexivity.\nQed.\n \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\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:Type) (l1 :list X) (l2 :list Y),length l1 = length l2 -> split (combine l1 l2)=(l1,l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X Y l1.\n  induction l1.\n  -intros l2.\n    intros H.  destruct l2 eqn: H1.\n    +reflexivity.\n    +discriminate H.\n  -intros l2.\n    intros H. destruct l2 eqn: H1.\n    +discriminate H.\n    +simpl in H. apply S_injective in H. simpl. rewrite -> IHl1. reflexivity. apply H.\nQed.\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\nLemma eq_len: forall (X:Type) (l1 l2: list X),\n  l1=l2 -> length l1 =length l2.\nProof.\n  intros X l1 l2.\n  intros H.\n  rewrite ->H.\n  reflexivity.\nQed.\nLemma eq_empty: forall (X:Type) (test : X-> bool) (l :list X),\n  length l=0 -> filter test l=[].\nProof.\n  intros X test l.\n  induction l.\n  - reflexivity.\n  - intros H. discriminate H.\nQed.\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 H.\n  induction l as [|y l].\n  -simpl in H.\n   discriminate H.\n  -simpl in H.\n   destruct (test y) eqn:H1.\n   +injection H as H2.\n    rewrite -> H2 in H1.\n    apply H1.\n   +apply IHl.\n    apply H.\nQed.\n    \n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool:=\n  match l with\n  |nil =>true\n  |h::l => match (test h) with\n      |false =>false\n      |true => forallb test l\n  end\nend.\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.\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::l => match (test h) with\n      |true => true\n      |false => existsb test l\n  end\nend.\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:X =>negb(test x) ) l).\n\nLemma forall_existsb':forall (X :Type) (test : X -> bool)(x :X) (l :list X),\n  test x =false ->\n  existsb' test (x::l) = existsb' test l.\nProof.\n  intros X test x l H.\n  unfold existsb'.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\nTheorem existsb_existsb' : 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 [|y l].\n  -reflexivity.\n  -simpl. destruct (test y) eqn:H1.\n    +unfold existsb'. simpl. rewrite H1.\n    reflexivity.\n    +symmetry. rewrite forall_existsb' with (X:=X) (test:=test) (x:=y) (l:=l).\n      *symmetry;apply IHl.\n      *apply H1.\nQed.\n(** [] *)\n\n(* Wed Jan 9 12:02:44 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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.9059898153067649, "lm_q1q2_score": 0.7919050698790121}}
{"text": "Set Warnings \"-notation-overridden, -parsing\".\nRequire Export IndProp.\n\n(* Relations *)\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\n(* Partial Relations *)\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. inversion H. inversion H0.\n  reflexivity.\nQed.\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold partial_function. unfold not.\n  intros Hc.\n  assert (0 = 1) as Nonsense.\n  { apply Hc with (x := 0).\n    - apply le_n. - apply le_S. apply le_n. }\n  inversion Nonsense.\nQed.\n\n(* Reflexive Relations *)\n\nDefinition reflexive {X : Type} (R : relation X) :=\n  forall a : X, R a a.\n\nTheorem le_refleixive : reflexive le.\nProof.\n  unfold reflexive. intros.\n  apply le_n.\nQed.\n\n(* Transitive Relations *)\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 : transitive le.\nProof.\n  unfold transitive. intros.\n  induction H0.\n  - apply H.\n  - apply le_S. apply IHle.\nQed.\n\n(* TODO: Exercises *)\n\n(* Symmetric and Antisymmetric Relations *)\n\nDefinition symmetric {X : Type} (R : relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\nTheorem le_not_symmetric : ~ (symmetric le).\nProof.\n  unfold not. unfold symmetric.\n  intros. assert (4 <= 3).\n  { apply H. apply le_S. reflexivity. }\n  intuition.\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 : antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros. inversion H.\n  - reflexivity.\n  - intuition.\nQed.\n\nTheorem le_step : forall n m p, n < m -> m <= S p -> n <= p.\nProof.\n  Admitted.\n\n(* Equivalence Relations *)\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\nTheorem le_order : order le.\nProof.\n  unfold order.\n  split.\n  - apply le_refleixive.\n  - split. + apply le_antisymmetric. + apply le_trans.\nQed.\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\n   and transitive. *)\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(* TODO *)\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.7919050632025331}}
{"text": "Require Export Maps MapNotations MapInterface MapFacts.\n\n(* Constructing the empty map *)\n\nDefinition M' : Map[nat, nat] := [].\n(* Equiv: Definition M' : Map[nat, nat] := empty nat. *)\n\n(* Constructing a map with values *)\n\nDefinition N' := (M' [ 0 <- 5 ]) [1 <- 6].\n\n(* Intuition: map [ key <- value ] *)\n(* Equiv: Definition n' := add 1 6 (add 0 5 m'). *)\n\n\n(*** Properties of maps *)\n\n(** Emptiness *)\n(* Remark: 'empty' is the empty map, 'is_empty' is a function bool -> dict *)\n(* Remark: 'dict' is a constructor for maps *)\n\nExample empty_is_empty'' :\n  is_empty M' = true.\nProof. reflexivity. Qed.\n\nExample empty_is_empty_with_prop :\n  Empty M'.\nProof. intuition. Qed.\n\nExample not_empty_is_not_empty' :\n  is_empty N' = false.\nProof. reflexivity. Qed.\n\n\n(** Cardinality: How many keys does the map have? *)\n\nExample empty_has_zero' :\n  cardinal M' = 0.\nProof. reflexivity. Qed.\n\nExample non_zero' :\n  cardinal N' = 2.\nProof. reflexivity. Qed.\n\t\n\n(** Membership: is key X in this map? *)\n\nExample is_member' :\n  mem 1 N' = true. (* Key 1 is in N' *)\nProof. reflexivity. Qed.\n\nExample is_member_with_prop :\n  In 1 N'. (* Key 1 is in N' *)\nProof. intuition. Qed.\n\nExample is_not_member' :\n  mem 4 M' = false.\nProof. reflexivity. Qed.\n\n\n(** Find: Give me the value at key X *)\n\n(* Finding a value using convenient notation *)\n(* Remark: value is 'option (element_type)' *)\nExample get_value_with_notation' :\n  N'[ 0 ] = Some 5.\nProof. reflexivity. Qed.\n\n(* Finding the same value with an explicit function call *)\n\nExample get_value_no_notation' :\n  find 0 N' = Some 5.\nProof. reflexivity. Qed.\n\nExample not_found' :\n  N'[ 2 ] = None.\nProof. reflexivity. Qed.\n\n(**\n  Note that if we state something false, such as:\n    M' [ 3 ] = Some 1.\n  coq does not complain or fail. It simply leaves us with\n  the obligation of proving false.\n  Remember that M' is the empty map.\n*)\n  \n\n(** Remove: Give me a map without key X *)\n\n(* Copied from exercises *)\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(* Two maps con be considered equal if all their keys are equal *)\n(* However, this may not be the best defintion *)\nExample remove_element :\n  equal beq_nat (remove 1 (add 1 5 [])) [] = true.\nProof. reflexivity. Qed.\n\nExample remove_element_with_prop :\n  Equivb beq_nat (remove 1 (add 1 5 [])) [].\nProof. rewrite equal_iff. reflexivity. Qed.\n\nExample remove_empty :\n  Equivb beq_nat (remove 1 []) [].\nProof. rewrite equal_iff. reflexivity. Qed.\n  \n\n\n(** Mapping over elements *)\n\n(* Add 1 to each element *)\n\nExample map_plus' :\n  equal beq_nat (map (plus 1) (add 2 6 (add 1 5 []))) (add 2 7 (add 1 6 [])) = true.\nProof. reflexivity. Qed.\n\n\n(** Folding over elements *)\n\n(* We only need the key as input here because 'fold' expects it *)\nDefinition mult' (key elem acc : nat) := elem * acc.\n\nExample fold_mult' :\n  fold mult' (add 2 6 (add 1 5 [])) 1 = 30.\nProof.  reflexivity. Qed.\n", "meta": {"author": "tdidriksen", "repo": "SASP-Project", "sha": "2ab0796d9abc3f997ce74ad96ba8e0dee1c00df9", "save_path": "github-repos/coq/tdidriksen-SASP-Project", "path": "github-repos/coq/tdidriksen-SASP-Project/SASP-Project-2ab0796d9abc3f997ce74ad96ba8e0dee1c00df9/src/SLImp/MapExamples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.79188734821012}}
{"text": "(* Basic notions from set theory. *)\n\nFrom set_theory Require Import lib fn pair.\n\nSection Definitions.\n\nVariable X : Type.\n\n(* The power set *)\nDefinition P := X -> Prop.\n\nVariable V : P.\nVariable W : P.\nVariable Y : nat -> P.\n\n(* A function range. *)\nDefinition Rng {D} (f : D -> X) x := ∃d, f d = x.\n\n(* The empty set. *)\nDefinition EmptySet (x : X) := False.\n\n(* An infinite set *)\nDefinition Infinite := ∃f : nat -> X, Injective f /\\ ∀n, V (f n).\n\n(* A countable set *)\nDefinition Countable := ∃f : nat -> X, ∀x, V x -> ∃n, f n = x.\n\n(* Singleton set *)\nDefinition Singleton (x y : X) := x = y.\n\n(* V is a subset of W. *)\nDefinition Inclusion := ∀x, V x -> W x.\n\n(* The difference of V relative to W is equal to V - W. *)\nDefinition Difference x := V x /\\ ¬W x.\n\n(* V is a proper superset of W. *)\nDefinition ProperSuperset := Inclusion /\\ Difference ≠ EmptySet.\n\n(* Binary union *)\nDefinition Union x := V x \\/ W x.\n\n(* Binary intersection *)\nDefinition Isect x := V x /\\ W x.\n\n(* Countable union *)\nDefinition ωUnion x := ∃n, Y n x.\n\n(* Countable intersection *)\nDefinition ωIsect x := ∀n, Y n x.\n\nEnd Definitions.\n\nArguments Rng {_ _}.\nArguments EmptySet {_}.\nArguments Infinite {_}.\nArguments Countable {_}.\nArguments Singleton {_}.\nArguments Inclusion {_}.\nArguments Difference {_}.\nArguments ProperSuperset {_}.\nArguments Union {_}.\nArguments Isect {_}.\nArguments ωUnion {_}.\nArguments ωIsect {_}.\n\nNotation \"'∅'\" := (EmptySet).\nNotation \"⦃ x ⦄\" := (Singleton x).\nNotation \"V ⊆ W\" := (Inclusion V W) (at level 50).\nNotation \"V ⊃ W\" := (ProperSuperset V W) (at level 50).\nNotation \"V ⧵ W\" := (Difference V W) (at level 40, left associativity).\nNotation \"V ∪ W\" := (Union V W) (at level 40, left associativity).\nNotation \"V ∩ W\" := (Isect V W) (at level 40, left associativity).\nNotation \"⋃ V\" := (ωUnion V) (at level 30).\nNotation \"⋂ V\" := (ωIsect V) (at level 30).\n\n(* This is quite useful. *)\nLemma prop_ext {X} (V W : P X) :\n  V = W <-> ∀x, V x <-> W x.\nProof.\nsplit; intros. now subst.\nextensionality x; now apply propositional_extensionality.\nQed.\n\nSection Basic_lemmas.\n\nVariable X : Type.\nVariable V : P X.\nVariable W : P X.\nVariable U : P X.\n\n(* Set inclusion is transitive *)\nLemma incl_trans : U ⊆ V -> V ⊆ W -> U ⊆ W.\nProof. intros HU HV x; auto. Qed.\n\n(* Equal sets are included in each other. *)\nLemma eq_incl : V = W -> V ⊆ W /\\ W ⊆ V.\nProof. intros; now subst. Qed.\n\n(* Sets that are included in each other are equal. *)\nLemma incl_eq : V ⊆ W -> W ⊆ V -> V = W.\nProof. intros; apply prop_ext; split; auto. Qed.\n\n(*\nIf V is included in U, and W removes at least as much from U as V,\nthen V is included in W.\n*)\nLemma diff_incl :\n  V ⊆ U -> U ⧵ W ⊆ U ⧵ V -> V ⊆ W.\nProof.\nintros HVU H x HV. apply HVU in HV as HU.\nassert(Hx := H x). eapply contra in Hx; unfold Difference in *.\napply not_and_or in Hx as [Hx|Hx]. easy. now apply NNPP.\nnow intros [_ HVx].\nQed.\n\nEnd Basic_lemmas.\n\n(* Re-use basic lemmas in a non-trivial way. *)\nSection Other_lemmas.\n\nVariable X : Type.\nVariable V : P X.\nVariable W : P X.\nVariable U : P X.\nVariable Y : nat -> P X.\n\n(* A set is empty iff it contains no elements. *)\nLemma empty : V = ∅ <-> ∀x, ¬V x.\nProof. split; intros. now rewrite H. now apply incl_eq. Qed.\n\n(* A set is non-empty iff it contains an element. *)\nLemma not_empty :\n  V ≠ ∅ <-> ∃x, V x.\nProof.\nsplit.\n- intros H; apply not_all_not_ex; intros H'; apply H.\n  apply prop_ext; intros; split; unfold EmptySet; intros.\n  now apply (H' x). easy.\n- intros [x Hx] H; apply eq_incl in H as [H _].\n  now apply (H x).\nQed.\n\n(* The difference of V relative to ∅ is all of V. *)\nLemma diff_empty : V ⧵ ∅ = V.\nProof. apply incl_eq. now intros x [H _]. easy. Qed.\n\n(* The empty set does not add any elements. *)\nLemma union_empty : V ∪ ∅ = V.\nProof. apply incl_eq. now intros x [H|H]. intros x H; now left. Qed.\n\n(* If V is included in W, and W is empty, then V is empty. *)\nLemma incl_empty : V ⊆ W -> W = ∅ -> V = ∅.\nProof. intros HV HW; apply incl_eq. now rewrite <-HW. easy. Qed.\n\n(* Intersection distributes over union. *)\nLemma isect_distr_union :\n  (V ∪ W) ∩ U = (V ∩ U) ∪ (W ∩ U).\nProof.\napply incl_eq; intros x.\n- intros [[HV|HW] HU]. now left. now right.\n- intros [[HV HU]|[HW HU]]; split; try easy. now left. now right.\nQed.\n\n(*\nIf V is included in W, then the intersection between\nV and U is included in the intersection between W and U.\n*)\nLemma incl_isect_incl : V ⊆ W -> V ∩ U ⊆ W ∩ U.\nProof. intros HV x [H1x H2x]. split; auto. Qed.\n\n(*\nRemoving only shared elements is equal to\nre-adding elements not removed by others.\n*)\nLemma diff_ωisect_eq_ωunion_diff :\n  V ⧵ ⋂ Y = ⋃ (λ n, V ⧵ Y n).\nProof.\napply incl_eq.\n- intros x [H1x H2x]. apply not_all_ex_not in H2x as [n Hn]; now exists n.\n- intros x [n [H1n H2n]]; split. easy. apply ex_not_not_all; now exists n.\nQed.\n\n(*\nSuppose V is included in W is included in U. Removing all elements in V from U\nis equal to removing all elements in W and adding the elements not in V back.\n*)\nLemma diff_union :\n  V ⊆ W -> W ⊆ U -> U ⧵ V = (U ⧵ W) ∪ (W ⧵ V).\nProof.\nintros HV HW; apply incl_eq; intros x.\n- intros [H1x H2x]. destruct (classic (W x)). now right. now left.\n- intros [[H1x H2x]|[H1x H2x]]; split; try easy.\n  eapply contra. apply HV. easy. now apply HW.\nQed.\n\n(* A union of countable sets is countable. *)\nLemma countable_union :\n  Countable V -> Countable W -> Countable (V ∪ W).\nProof.\nintros [v Hv] [w Hw].\npose(f c m := if c =? 0 then v m else w m).\npose(g n := let (c, m) := π_inv n in f c m).\nexists g; intros x [Hx|Hx].\n1: destruct (Hv x Hx) as [m Hm]; exists (π (0, m)).\n2: destruct (Hw x Hx) as [m Hm]; exists (π (1, m)).\nall: unfold g, f; now rewrite π_inv_π_id.\nQed.\n\n(* A countable union of countable sets is countable. *)\nLemma countable_ωunion :\n  (∀n, Countable (Y n)) -> Countable (⋃ Y).\nProof.\nintros; apply choice in H as [F HY].\npose(f n := let (i, m) := π_inv n in F i m).\nexists f; intros x [i Hx]. apply HY in Hx as [m Hm].\nexists (π (i, m)); unfold f; now rewrite π_inv_π_id.\nQed.\n\nEnd Other_lemmas.\n\n(*\nWe used the choice axiom to prove countable_ωunion. There seems to be no way to\navoid this, except by changing the definition of Countable. This is possible\nwhile preserving the use of classical logic; by using function relations that\ncan be effectively obtained.\n\nUnfortunately this also means proofs that involve Countable must be within Type,\nwhich would require induction on CB to be within Type. Hence proofs about CB can\nthen no longer use classical logic.\n*)\nSection Countable_ωunion_without_choice.\n\nDefinition CountableRel {X} (V : P X) := {F : nat -> X -> Prop |\n  (∀n, ∃!x, F n x) /\\ ∀x, V x -> ∃n, F n x}.\n\n(* A countable union of countable sets is countable. *)\nLemma countable_rel_ωunion {X} (Y : nat -> P X) :\n  (∀n, CountableRel (Y n)) -> CountableRel (⋃ Y).\nProof.\nintros H;\npose(F n := sig1 (H n));\npose(HF n := sig2 (H n));\npose(G x y := let (n, i) := π_inv x in F n i y).\nexists G; split; intros x; unfold G.\n- destruct (π_inv x) as [n i]. apply (proj1 (HF n)).\n- intros [n Hn]. apply (proj2 (HF n)) in Hn as [i Hi].\n  exists (π ((n, i))). now rewrite π_inv_π_id.\nQed.\n\nEnd Countable_ωunion_without_choice.\n", "meta": {"author": "bergwerf", "repo": "settheory", "sha": "e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd", "save_path": "github-repos/coq/bergwerf-settheory", "path": "github-repos/coq/bergwerf-settheory/settheory-e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd/set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8539127529517044, "lm_q1q2_score": 0.7918873379151234}}
{"text": "Require Import Arith.\n\nAxiom todo : forall A, A.\nLtac todo := apply todo.\n\nGoal True.\n  exact I.\nQed.\n\nCheck True.\n\nPrint Module Init.Nat.\n\nParameter A B C : Prop.\n\nLemma AimpA : A -> A.\nProof.\n  intro.\n  assumption.\nQed.\n\nLemma imp_trans : (A -> B) -> (B -> C) -> A -> C.\nProof.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nLemma and_comm : A /\\ B -> B /\\ A.\nProof.\n  intro.\n  destruct H.\n  split; assumption.\nQed.\n\nLemma or_comm : A \\/ B -> B \\/ A.\nProof.\n  intro.\n  destruct H; [right | left]; assumption.\nQed.\n\nLemma A_imp_nnA : A -> ~~A.\nProof.\n  unfold not.  \n  intros.\n  apply H0.\n  assumption.\nQed.\n\nLemma distr_and_or : (A\\/B)/\\C -> A/\\C \\/ B/\\C.\nProof.\n  intros.\n  destruct H. \n  destruct H. \n  + left. split; assumption.\n  + right. split; assumption.\nQed.\n\nLemma equiv_refl : A <-> A.\nProof.\n  unfold iff.\n  split; intro; assumption.\nQed.\n\n(** 2.2 Classical logic *)\n\nLemma equiv_classic :\n  (forall P, P \\/ ~P) <-> (forall P, ~~P -> P).\nProof.\n  unfold iff. \n  split; unfold not; intros.  \n  - destruct H with P. \n    + assumption.\n    + apply H0 in H1. contradiction.\n  - apply H.\n    intro.\n    apply H0.\n    right.\n    intro.\n    destruct H0; left; assumption.\nQed.\n\n(* 2.2.1 {Classical formulae in an intuitionistic world *)\n(* Modelization of a definition and lemmas *)\n\nDefinition is_classical (P:Prop) := ~~P -> P. \n\nLemma nn_funct (P Q : Prop) : ~~ P /\\ (P -> Q) -> ~~Q.\nProof.\n  unfold not.  \n  intro.\n  \n  destruct H.\n  intro. \n  apply H1.\n  apply H0. \n  destruct H.\n  intro.\n  apply H1.\n  apply H0.\n  assumption.\nQed.\n\nLemma class_t : is_classical True.\nProof.\n  unfold is_classical.\n  unfold not.\n  intro.\n  trivial.\nQed.\n  \nLemma class_f : is_classical False.\nProof.\n  unfold is_classical.\n  unfold not.\n  intro.\n  destruct H.\n  intro.\n  assumption.\nQed.\n\nLemma class_conj (P Q : Prop) : is_classical P /\\ is_classical Q -> is_classical (P /\\ Q).\nProof.\n  unfold is_classical.\n  unfold not.\n  intro.\n  destruct H.\n  intro.\n  split.\n  - apply H.\n    intro.\n    apply H1.\n    intro.\n    destruct H3. apply H2. apply H3.\n  - apply H0.\n    intro.\n    apply H1.\n    intro.\n    destruct H3. apply H2. apply H4.\nQed.  \n\n\n\n(* 3.1 Socrates *)\n(* Modelization using axioms *)\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  intro.\n  destruct H.\n  apply H0 in H.\n  assumption.\nQed.\n\nPrint socrateMortal.\n\n(* 3.2 Drinkers paradox *)\n(* Modelization using axioms + classical logic *)\nParameter EM : forall P, ~~ P -> P.\n\nLemma drinker : exists p:Person, ~ Mortal p -> forall q:Person, ~ (Mortal q).\nProof.\n  apply EM.\n  intro.\n  apply H.\n  exists Socrate.\n  intros.\n  intro.\n  apply H.\n  exists q.\n  intro.\n  contradiction.\nQed.\n\n(* 3.3 Equality *)\n\n(* Example *)\n\nGoal forall x y : nat, x = S y -> y = pred x.\nProof.\n  intros x y e.\n  rewrite e. \n  simpl.\n  reflexivity.\nQed.\n\n(* Require Import Classical.\nCheck NNPP. *)\n\n(* 3.4 Groups *)\n(* Modelization using axioms + equational reasoning using rewrite/reflexivity/symmetry/transivitity *)\n\nParameter (G:Type).\nParameter op : G -> G -> G.\nParameter inv : G -> G.\nParameter e : G.\n\nAxiom assoc  : forall (a b c : G),  op (op a b)  c = op a  (op b c).\nAxiom id_l : forall (a: G), op a e = a.  \nAxiom id_r : forall (a: G), op e a = a.\n\nAxiom inv_r : forall (a:G), op a (inv a) = e.\nAxiom inv_l : forall (a:G), op (inv a) a = e.\n\nLemma group (x y:G) : inv (op x y) = op (inv y) (inv x).\nProof.\n  transitivity (op (inv y) (op (inv x) (op (op x y) (inv (op x y))))).\n  - rewrite assoc.\n    rewrite <- assoc with (a:=inv x) (b:=x).\n    rewrite inv_l.\n    rewrite id_r.\n    rewrite <- assoc.\n    rewrite inv_l.\n    rewrite id_r.\n    reflexivity.\n  \n  - rewrite inv_r.\n    rewrite id_l.\n    reflexivity.\nQed.\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/tp1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7916782600916303}}
{"text": "Require Import List.\n\n(* 1.28 *)\nTheorem app_length : forall {A : Set} (xs ys : list A),\n                       length (xs ++ ys) = length xs + length ys.\nProof.\n  intros A xs ys.\n  induction xs.\n  simpl.\n  reflexivity.\n\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\n(* 練習問題 *)\n(* 問4.2 *)\nTheorem app_assoc : forall {A:Set} (xs ys zs : list A),\n                      xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\nProof.\n  intros A xs ys zs.\n  induction xs.\n  simpl.\n  reflexivity.\n\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\n(* 問4.3 *)\nTheorem app_nil : forall {A:Set} (xs: list A),\n                    xs ++ nil = xs.\nProof.\n  intros A xs.\n  induction xs.\n  simpl.\n  reflexivity.\n\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\n(* IH  Inductive Hypothesis *)\n\n\n(* 問4.4 *)\nTheorem app_rev : forall {A:Set} (xs ys: list A),\n                    rev (xs ++ ys) = rev ys ++ rev xs.\nProof.\n  intros A xs ys.\n  induction xs.\n\n  simpl.\n  rewrite app_nil.\n  reflexivity.\n\n  simpl.\n  rewrite IHxs.\n  rewrite <- app_assoc.\n  reflexivity.\nQed.\n\n\n(* 問4.5 *)\nTheorem rev_rev : forall {A:Set} (xs: list A),\n                    rev (rev xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n\n  simpl.\n  reflexivity.\n\n  simpl.\n  rewrite app_rev.\n  simpl.\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/e1.28.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.7916573363098859}}
{"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.\nImport ListNotations.\n\n(** * Cyclic permutations\n\nThis file contains a permutation development based on cycling:\n\n[[\nInductive Perm2 {A}: list A -> list A -> Prop :=\n| perm2_nil : Perm2 [] []\n| perm2_cons : forall x y a,\n    Perm2 x y -> Perm2 (a :: x) (a :: y)\n| perm2_cycle : forall x y a,\n    Perm2 (a :: x) y -> Perm2 (x ++ [a]) y.\n]]\n\nWe prove that cycling permutations are equivalent to Coq Permutations.\nAs you’ve seen, though, this definition is radically difficult to work with.\nThere is no way I’ve found to prove anything about Perm2 directly\n(the equivalent of the [Permutation_Add_inv] lemma must be assumed).\n\nInstead we work with a stronger definition, [NatCyclePerm], about which\nwe can prove stronger properties. [NatCyclePerm] is a cyclic permutation\nfor _distinct natural numbers_:\n\n[[\nInductive NatCyclePerm : list nat -> list nat -> Prop :=\n| ncp_nil : NatCyclePerm [] []\n| ncp_cons : forall is js i,\n    NatCyclePerm is js ->\n    ~ In i is ->\n    NatCyclePerm (i::is) (i::js)\n| ncp_cycle : forall is js i,\n    NatCyclePerm (i::is) js -> NatCyclePerm (is++[i]) js.\n]]\n\nWhen the members of a set are distinct, it becomes easier to prove\nproperties about permutations. In particular, we can prove this strong\nstatement:\n\n[[\n  Lemma ncp_all is js:\n    NoDup is ->\n    NoDup js ->\n    (forall i, In i is <-> In i js) ->\n    NatCyclePerm is js.\n]]\n\nThat is, if [is] and [js] are lists of distinct [nat]s, and they are subsets\nof each other (every element of [is] is in [js] and vice versa), then there\nexists a cycle-based permutation between [is] and [js].\n\nBut how can we go from permutations of [nat]s to permutations of anything?\nWe use this function, which looks up the [i]th element of a list:\n\n[[\nFixpoint map_nth {A} is l : list A :=\n  match is with\n  | [] => []\n  | i::is' => match nth_error l i with\n              | Some a => a :: map_nth is' l\n              | None => []\n              end\n  end.\n]]\n\nWorking through the proof still involved a lot of excitement, and (as almost\nevery Coq development seems to require) proving facts about lists. A critical\nlemma was [NoDup_nat_complete], which allows us to assert the existence of\na [NatCyclePerm] at an important point.\n\n*)\n\n\n(* ** Facts about [In] *)\n\nSection InFacts.\n  Context {A:Type}.\n  Implicit Types l:list A.\n\n  Lemma in_middle a l1 l2:\n    In a (l1 ++ a :: l2).\n\n    induction l1; intros; simpl; [ left | right ]; auto.\n  Qed.\n\n  Lemma in_add_middle a b l1 l2:\n    In a (l1 ++ l2) ->\n    In a (l1 ++ b :: l2).\n\n    intros; apply in_app_or in H; intuition.\n  Qed.\n\n  Lemma in_remove_middle a b l1 l2:\n    In a (l1 ++ b :: l2) ->\n    a <> b ->\n    In a (l1 ++ l2).\n\n    intros; apply in_app_or in H; intuition.\n    destruct H1; intuition.\n  Qed.\n\n  Lemma in_remove_left a l1 l2:\n    In a (l1 ++ l2) ->\n    ~ In a l1 ->\n    In a l2.\n\n    intros; apply in_app_or in H; intuition.\n  Qed.\n\n  Lemma in_remove_right a l1 l2:\n    In a (l1 ++ l2) ->\n    ~ In a l2 ->\n    In a l1.\n\n    intros; apply in_app_or in H; intuition.\n  Qed.\n\nEnd InFacts.\n\n\n(** ** [AllLess]\n\n   This predicate says that everything in a [list nat] is less than\n   a number. We could’ve written it as [Forall (ge n)]. *)\n\nSection AllLess.\n\n  Definition AllLess n l :=\n    forall i, In i l -> i < n.\n\n  (** These facts make [AllLess] easier to work with in proofs. *)\n  Lemma AllLess_cons n l i:\n    AllLess n l -> i < n -> AllLess n (i :: l).\n\n    unfold AllLess; intros.\n    destruct H1; intuition.\n  Qed.\n\n  Lemma AllLess_skip {n l i}:\n    AllLess n (i :: l) -> AllLess n l.\n\n    unfold AllLess; intros; apply H; intuition.\n  Qed.\n\n  Lemma AllLess_app_1 {n l1 l2}:\n    AllLess n (l1 ++ l2) -> AllLess n l1.\n\n    unfold AllLess; intros; apply H; intuition.\n  Qed.\n\n  Lemma AllLess_app_2 {n l1 l2}:\n    AllLess n (l1 ++ l2) -> AllLess n l2.\n\n    unfold AllLess; intros; apply H; intuition.\n  Qed.\n\n  Lemma AllLess_zero_nil l:\n    AllLess 0 l -> l = [].\n\n    destruct l; intros; auto.\n    assert (n < 0) by (apply H; intuition).\n    omega.\n  Qed.\n\nEnd AllLess.\n\n\n(** ** Facts about [map_nth] *)\n\nFixpoint map_nth {A} is l : list A :=\n  match is with\n  | [] => []\n  | i::is' => match nth_error l i with\n              | Some a => a :: map_nth is' l\n              | None => []\n              end\n  end.\n\nSection MapNthFacts.\n  Context {A:Type}.\n  Implicit Types l:list A.\n  Implicit Types is js:list nat.\n\n  (* A useful Ltac tactic *)\n  Ltac map_nth_head :=\n    match goal with\n    | [ H : context [ AllLess (length ?l) (?a :: ?is) ] |- _ ] =>\n      let M := fresh \"SO\" in\n      let ne := fresh \"ne\" in\n      assert (a < length l) as M by (apply H; intuition);\n      rewrite <- nth_error_Some in M; simpl;\n      remember (nth_error l a) as ne; destruct ne; [ clear M | contradiction ]\n    end.\n\n\n  (** Easy facts about [map_nth] *)\n\n  Lemma in_map_nth_position is l a:\n    In a (map_nth is l) ->\n    exists i, In i is /\\ i < length l /\\ nth_error l i = Some a.\n\n    revert is l a; induction is; simpl; intros.\n    contradiction.\n    remember (nth_error l a) as ne; destruct ne; [ | destruct H ].\n    simpl in H; destruct or H; subst.\n    - assert (nth_error l a <> None) by (rewrite <- Heqne; discriminate).\n      rewrite nth_error_None in H.\n      exists a; intuition.\n    - apply IHis in H; destruct H as [x H].\n      exists x; intuition.\n  Qed.\n\n  Lemma in_map_nth is l a:\n    In a (map_nth is l) ->\n    In a l.\n\n    intros; apply in_map_nth_position in H.\n    destruct H as [i [X [L Y]]].\n    now apply nth_error_In in Y.\n  Qed.\n\n  Lemma map_nth_empty is:\n    map_nth is ([]:list A) = ([]:list A).\n\n    induction is; auto; simpl.\n    rewrite IHis.\n    assert (length ([]:list A) <= a) by (simpl; omega).\n    rewrite <- nth_error_None in H.\n    now rewrite H.\n  Qed.\n\n  Lemma map_nth_app is1 is2 l:\n    AllLess (length l) is1 ->\n    map_nth (is1 ++ is2) l = map_nth is1 l ++ map_nth is2 l.\n\n    induction is1; intros AL.\n    - intuition.\n    - map_nth_head; now rewrite (IHis1 (AllLess_skip AL)).\n  Qed.\n\n  Lemma map_nth_cons is l a:\n    map_nth (map S is) (a :: l) = map_nth is l.\n\n    induction is; simpl; auto.\n    remember (nth_error l a0) as mm; destruct mm; auto.\n    now rewrite IHis.\n  Qed.\n\n  Lemma map_nth_length is l:\n    AllLess (length l) is <->\n    length is = length (map_nth is l).\n\n    revert l; induction is; intros l.\n    - unfold AllLess; intuition.\n    - split; intros H.\n      + map_nth_head; simpl; apply eq_S.\n        rewrite <- IHis; now apply (AllLess_skip H).\n      + unfold AllLess; intros i I; simpl in I.\n        simpl in H.\n        remember (nth_error l a) as ne; destruct ne; try discriminate.\n        simpl in H; apply eq_add_S in H; rewrite <- IHis in H.\n        assert (a < length l) by (apply nth_error_Some; rewrite <- Heqne; discriminate).\n        destruct I; [ omega | now apply H ].\n  Qed.\n\n\n  (* NoDup is Coq’s inductive type representing the absence of\n     duplicates in a list. *)\n  Local Hint Constructors NoDup.\n\n  Lemma map_nth_NoDup is l:\n    NoDup is ->\n    NoDup l ->\n    NoDup (map_nth is l).\n\n    remember (map_nth is l) as ks.\n    revert is l Heqks; induction ks; intros is l Heqks NDi NDl; auto.\n    destruct is; simpl in Heqks; [ discriminate | ].\n    remember (nth_error l n) as ne; destruct ne; [ | discriminate ].\n    inversion Heqks; subst; clear Heqks.\n    constructor.\n    + contradict NDi.\n      apply in_map_nth_position in NDi.\n      destruct NDi as [i [INi [INl NTHi]]].\n      rewrite Heqne in NTHi.\n      rewrite (NoDup_nth_error l) in NDl.\n      apply (NDl _ _ INl) in NTHi.\n      subst; intro H; inversion H; contradiction.\n    + apply (IHks is l); auto.\n      inversion NDi; auto.\n  Qed.\n\n  Lemma map_nth_nth is i j l:\n    nth_error is i = Some j ->\n    AllLess (length l) is ->\n    nth_error (map_nth is l) i = nth_error l j.\n\n    intros SO AL; apply nth_error_split in SO.\n    destruct SO as [l1 [l2 [Hi Hl]]]; subst.\n\n    assert (length (map_nth l1 l) = length l1) as LL1.\n    symmetry; apply map_nth_length; now apply (AllLess_app_1 AL).\n\n    rewrite map_nth_app by (apply (AllLess_app_1 AL)).\n    rewrite nth_error_app2 by omega.\n    rewrite LL1; rewrite minus_diag.\n    simpl.\n    remember (nth_error l j) as ne; destruct ne; auto.\n  Qed.\n\n  (** A critical lemma for proving [Perm2] transitivity. *)\n  Lemma map_nth_compose is js l:\n    AllLess (length js) is ->\n    AllLess (length l) js ->\n    map_nth is (map_nth js l) = map_nth (map_nth is js) l.\n\n    revert js l; induction is; intros js l ALi ALj; auto.\n    map_nth_head.\n    simpl (map_nth (n :: map_nth is js) l).\n    remember (nth_error l n) as ne2; destruct ne2.\n    remember (nth_error (map_nth js l) a) as ne3; destruct ne3;\n      rewrite map_nth_nth with (j:=n) in Heqne3; auto.\n    - rewrite <- Heqne3 in Heqne2; inversion Heqne2; subst.\n      rewrite (IHis _ _ (AllLess_skip ALi) ALj); reflexivity.\n    - rewrite <- Heqne3 in Heqne2; discriminate.\n    - symmetry in Heqne2; rewrite nth_error_None in Heqne2.\n      symmetry in Heqne; apply nth_error_In in Heqne.\n      apply ALj in Heqne; omega.\n  Qed.\n\nEnd MapNthFacts.\n\n\n(** ** Facts about [NoDup] *)\n\nSection NoDupFacts.\n  Context {A:Type}.\n  Implicit Types a b:A.\n  Implicit Types l:list A.\n\n  Lemma in_NoDup_inv a b l:\n    NoDup (b :: l) ->\n    a <> b ->\n    In a (b :: l) ->\n    In a l.\n\n    intros ND neq I.\n    inversion ND; destruct I; intuition.\n  Qed.\n\n  Lemma NoDup_app_swap l1 l2:\n    NoDup (l1 ++ l2) <-> NoDup (l2 ++ l1).\n\n    induction l1.\n    - simpl; rewrite app_nil_r; intuition.\n    - rewrite <- app_comm_cons; split; intro ND.\n      + inversion ND; subst.\n        assert (Add a (l2 ++ l1) (l2 ++ a :: l1)) by (apply Add_app).\n        rewrite (NoDup_Add H).\n        rewrite <- IHl1; split; auto.\n        contradict H1; rewrite in_app_iff in *; intuition.\n      + apply NoDup_remove in ND; destruct ND as [ND NI].\n        apply NoDup_cons.\n        contradict NI; rewrite in_app_iff in *; intuition.\n        rewrite IHl1; assumption.\n  Qed.\n\n  Lemma NoDup_remove_iff a x1 x2 y:\n    NoDup (x1 ++ a :: x2) ->\n    NoDup (a :: y) ->\n    (forall i, In i (x1 ++ a :: x2) <-> In i (a :: y)) ->\n    forall i, In i (x1 ++ x2) <-> In i y.\n\n    intros NDx NDy EQ i.\n    apply NoDup_remove in NDx.\n    destruct NDx as [NDx NIx].\n    inversion NDy; subst.\n\n    split; intros.\n    - apply in_remove_left with (l1:=[a]).\n      apply EQ.\n      now apply in_add_middle.\n      contradict NIx.\n      inversion NIx; subst; intuition.\n    - apply in_remove_middle with (b:=a).\n      apply EQ.\n      intuition.\n      contradict H1.\n      subst; assumption.\n  Qed.\n\n  Lemma NoDup_in_iff_length l1 l2:\n    NoDup l1 ->\n    NoDup l2 ->\n    (forall i, In i l1 <-> In i l2) ->\n    length l1 = length l2.\n\n    intros NX; revert l2; induction NX;\n      intros l2 NY HI.\n    - destruct l2; auto.\n      assert (In a (a :: l2)) by intuition.\n      rewrite <- HI in H; destruct H.\n    - assert (In x l2) by (rewrite <- HI; intuition).\n      apply in_split in H0.\n      destruct H0 as [m1 [m2 Hm2]]; subst.\n      rewrite app_length; simpl.\n      rewrite <- plus_n_Sm; apply eq_S.\n      rewrite <- app_length.\n      apply IHNX.\n      apply NoDup_remove_1 with (a:=x); auto.\n      symmetry; revert i.\n      apply NoDup_remove_iff with (a:=x); auto.\n      now constructor.\n      symmetry; revert i; now assumption.\n  Qed.\n\nEnd NoDupFacts.\n\n\n\n(** ** Facts about [iota]\n\n   [iota n] counts from 0 to [n - 1], and is defined in terms of\n   the library’s [seq]. *)\n\nDefinition iota n := seq 0 n.\n\nSection IotaFacts.\n\n  Lemma in_iota_iff n i:\n    In i (iota n) <-> i < n.\n\n    split; intros.\n    apply in_seq in H; omega.\n    apply in_seq; omega.\n  Qed.\n\n  Lemma iota_NoDup n:\n    NoDup (iota n).\n\n    now apply seq_NoDup.\n  Qed.\n\n  Lemma iota_length n:\n    length (iota n) = n.\n\n    now apply seq_length.\n  Qed.\n\n  Lemma iota_AllLess n:\n    AllLess n (iota n).\n\n    unfold AllLess; intros; now apply in_iota_iff.\n  Qed.\n\n  Lemma seq_app start len1 len2:\n    seq start (len1 + len2) = seq start len1 ++ seq (start + len1) len2.\n\n    revert start len2; induction len1; intros.\n    - simpl; auto.\n    - cbn; rewrite IHlen1; rewrite plus_Sn_m; rewrite <- plus_n_Sm; reflexivity.\n  Qed.\n\n  Lemma iota_nth n i:\n    i < n -> nth_error (iota n) i = Some i.\n\n    intros L; pose L as L'; rewrite <- iota_length in L'.\n    apply nth_split with (d:=0) in L'.\n    destruct L' as [l1 [l2 [IEQ L1L]]].\n    unfold iota in *; rewrite (seq_nth 0 0 L) in IEQ.\n    rewrite IEQ.\n    rewrite nth_error_app2.\n    rewrite L1L; rewrite minus_diag; now simpl.\n    omega.\n  Qed.\n\n  Lemma iota_S n:\n    iota (S n) = 0 :: map S (iota n).\n\n    unfold iota; rewrite seq_shift; reflexivity.\n  Qed.\n\n  Lemma map_nth_iota {A} (xs:list A):\n    map_nth (iota (length xs)) xs = xs.\n\n    induction xs; cbn in *; auto.\n    rewrite <- seq_shift.\n    rewrite map_nth_cons.\n    unfold iota in IHxs; now rewrite IHxs.\n  Qed.\n\nEnd IotaFacts.\n\n\n(** ** [NoDup_nat_complete]\n\n   This section states and proves this lemma: If a list [l] contains\n   [n] [nat]s with no duplicates, and all elements of [l] are less\n   than [n], then [l] contains _every_ [nat] less than [n]. We need\n   it to prove that [Perm2]s are transitive.\n\n   This is too hard to prove in a single induction, so we introduce\n   a [transfer] type to let us state the induction-aware lemma,\n   [NoDup_AllLess_transfer]. *)\n\nSection NoDupNatComplete.\n\n  Inductive transfer {A}: list A -> list A -> list A -> Prop :=\n  | transfer_nil : forall ys, transfer [] ys ys\n  | transfer_cons : forall xs ys1 y ys2 zs,\n      transfer xs (ys1 ++ y :: ys2) zs ->\n      transfer (y :: xs) (ys1 ++ ys2) zs.\n  Hint Constructors transfer.\n\n  Lemma in_transfer_iff {A} (xs ys zs:list A) a:\n    transfer xs ys zs ->\n    In a zs <-> In a (xs ++ ys).\n\n    intro TR; induction TR.\n    - intuition.\n    - rewrite IHTR.\n      repeat rewrite in_app_iff; simpl; intuition.\n  Qed.\n\n  Lemma transfer_length {A} (xs ys zs:list A):\n    transfer xs ys zs ->\n    length zs = length xs + length ys.\n\n    intro TR; induction TR.\n    - simpl; auto.\n    - simpl; rewrite IHTR.\n      repeat rewrite app_length; simpl; omega.\n  Qed.\n\n  Lemma in_transfer_rest {A} (xs ys zs:list A) a:\n    transfer xs ys zs ->\n    In a zs ->\n    ~ In a xs ->\n    In a ys.\n\n    intros TR; induction TR; intros Iz NIx.\n    - auto.\n    - apply not_in_cons in NIx.\n      destruct NIx as [Ny NIx].\n      apply in_remove_middle with (b:=y); auto.\n  Qed.\n\n\n  Lemma NoDup_AllLess_transfer n xs:\n    NoDup xs ->\n    AllLess n xs ->\n    exists ys, transfer xs ys (iota n).\n\n    induction xs; intros ND AL.\n    - exists (iota n); constructor.\n    - inversion ND; subst.\n      generalize (AllLess_skip AL); intro AL0.\n      generalize (IHxs H2 AL0); intro IH.\n      destruct IH as [ys IH].\n      assert (In a ys). {\n        apply (in_transfer_rest _ _ _ a IH).\n        rewrite in_iota_iff; auto.\n        apply AL; intuition.\n        auto.\n      }\n      apply in_split in H.\n      destruct H as [y1 [y2 H]]; subst.\n      exists (y1 ++ y2); now constructor.\n  Qed.\n\n  Lemma NoDup_nat_complete i is:\n    NoDup is ->\n    AllLess (length is) is ->\n    i < length is ->\n    In i is.\n\n    intros ND AL Less.\n    generalize (NoDup_AllLess_transfer (length is) is ND AL);\n      intros TR.\n    destruct TR as [ys TR].\n    generalize (transfer_length _ _ _ TR); intros TRlen.\n    rewrite iota_length in TRlen.\n    assert (length ys = 0) by omega.\n    apply length_zero_iff_nil in H; subst.\n    rewrite <- app_nil_r.\n    rewrite <- (in_transfer_iff _ _ _ _ TR).\n    now rewrite in_iota_iff.\n  Qed.\n\nEnd NoDupNatComplete.\n\n\n(** ** [NatCyclePerm]\n\n   This is the cycle-based permutation definition that lets us show\n   reflexivity, symmetry, and transitivity without further\n   assumptions. *)\n\nSection NatCyclePerm.\n\n  Inductive NatCyclePerm : list nat -> list nat -> Prop :=\n  | ncp_nil : NatCyclePerm [] []\n  | ncp_cons : forall is js i,\n      NatCyclePerm is js ->\n      ~ In i is ->\n      NatCyclePerm (i::is) (i::js)\n  | ncp_cycle : forall is js i,\n      NatCyclePerm (i::is) js -> NatCyclePerm (is++[i]) js.\n  Hint Constructors NatCyclePerm.\n\n  Lemma ncp_length_eq {is js}:\n    NatCyclePerm is js ->\n    length is = length js.\n\n    intro PE; induction PE; auto.\n    now apply eq_S.\n    rewrite app_length; simpl in *. omega.\n  Qed.\n\n  Lemma ncp_eq_nil is:\n    NatCyclePerm is [] ->\n    is = [].\n\n    intros; apply ncp_length_eq in H.\n    simpl; apply length_zero_iff_nil; subst; auto.\n  Qed.\n\n\n  Lemma ncp_refl is:\n    NoDup is ->\n    NatCyclePerm is is.\n\n    induction is; auto; intros.\n    constructor.\n    - apply IHis; inversion H; auto.\n    - inversion H; auto.\n  Qed.\n\n  Lemma ncp_app_cycle is1 is2 js:\n    NatCyclePerm (is1 ++ is2) js ->\n    NatCyclePerm (is2 ++ is1) js.\n\n    revert is2; induction is1; intros.\n    simpl; rewrite app_nil_r; auto.\n    replace (is2 ++ a :: is1) with ((is2 ++ [a]) ++ is1).\n    apply IHis1; rewrite app_assoc; apply ncp_cycle; apply H.\n    rewrite <- app_assoc; apply eq_refl.\n  Qed.\n\n  (** This important lemma lets us construct a [NatCyclePerm]\n      from _any_ [nat] lists that meet some simple conditions. *)\n  Lemma ncp_all is js:\n    NoDup is ->\n    NoDup js ->\n    (forall i, In i is <-> In i js) ->\n    NatCyclePerm is js.\n\n    revert is; induction js; intros is NDx NDy I.\n    - assert (length is = length ([]:list nat)).\n      apply NoDup_in_iff_length; auto.\n      simpl in H.\n      apply length_zero_iff_nil in H.\n      subst; auto.\n    - assert (In a is) by (apply I; intuition).\n      apply in_split in H.\n      destruct H as [l1 [l2 H]]; subst.\n      apply ncp_app_cycle.\n      rewrite <- app_comm_cons.\n      constructor.\n      apply ncp_app_cycle.\n      apply IHjs.\n      + now apply NoDup_remove_1 with (a:=a).\n      + now apply NoDup_remove_1 with (a:=a) (l:=[]).\n      + now apply NoDup_remove_iff with (a0:=a).\n      + rewrite in_app_iff.\n        rewrite or_comm.\n        rewrite <- in_app_iff.\n        now apply NoDup_remove_2 with (a:=a).\n  Qed.\n\n  Lemma ncp_expand is js:\n    NatCyclePerm is js ->\n    NoDup is\n    /\\ NoDup js\n    /\\ (forall i, In i is <-> In i js).\n\n    intro PE; induction PE; auto.\n    - repeat split; try apply NoDup_nil; auto.\n    - destruct IHPE as [NDx [NDy IH]].\n      split; [ now apply NoDup_cons | ].\n      split; [ apply NoDup_cons;\n               try rewrite <- IH; auto | ].\n      intros; simpl; rewrite <- IH; intuition.\n    - destruct IHPE as [NDx [NDy IH]].\n      split; [ | split].\n      + apply NoDup_app_swap; now assumption.\n      + assumption.\n      + intros; rewrite <- IH; rewrite in_app_iff.\n        simpl; intuition.\n  Qed.\n\n  Lemma ncp_NoDup_is {is js}:\n    NatCyclePerm is js -> NoDup is.\n\n    intros PE; apply ncp_expand in PE; intuition.\n  Qed.\n\n  Lemma ncp_NoDup_js {is js}:\n    NatCyclePerm is js -> NoDup js.\n\n    intros PE; apply ncp_expand in PE; intuition.\n  Qed.\n\n  Lemma ncp_in_iff {is js}:\n    NatCyclePerm is js -> forall i, In i is <-> In i js.\n\n    intro PE; apply ncp_expand in PE; intuition.\n  Qed.\n\n\n\n  (** Once we have [ncp_expand] and [ncp_all], we can prove symmetry\n      and transitivity. *)\n\n  Lemma ncp_sym is js:\n    NatCyclePerm is js ->\n    NatCyclePerm js is.\n\n    intros.\n    apply ncp_expand in H.\n    destruct_conjs.\n    apply ncp_all; auto.\n    split; intros; now apply H1.\n  Qed.\n\n  Lemma ncp_trans is js ks:\n    NatCyclePerm is js ->\n    NatCyclePerm js ks ->\n    NatCyclePerm is ks.\n\n    intros.\n    apply ncp_expand in H.\n    apply ncp_expand in H0.\n    destruct_conjs.\n    apply ncp_all; auto.\n    split; intros.\n    apply H2; now apply H4.\n    apply H4; now apply H2.\n  Qed.\n\n\n  (** Given symmetry and transitivity, we can prove the equivalence\n      of the library’s [Permutation] and [NatCyclePerm] (for\n      duplicate-free lists). *)\n\n  Lemma perm_ncp is js:\n    NoDup is ->\n    Permutation is js ->\n    NatCyclePerm is js.\n\n    intros ND PE; induction PE; auto.\n    - inversion ND; subst.\n      apply IHPE in H2.\n      apply ncp_expand in H2.\n      destruct H2 as [NDl [NDl' IN]].\n      apply ncp_all; auto.\n      apply NoDup_cons.\n      now rewrite <- IN.\n      assumption.\n      intros i; simpl; rewrite <- IN; reflexivity.\n    - inversion ND; subst.\n      inversion H2; subst.\n      apply ncp_all; auto.\n      + apply NoDup_cons.\n        contradict H1; simpl in *; intuition.\n        apply NoDup_cons; auto.\n        contradict H1; simpl in *; intuition.\n      + intros i; simpl.\n        intuition.\n    - apply IHPE1 in ND.\n      generalize (ncp_expand _ _ ND); intros H.\n      destruct H as [NDl [NDl' IN]].\n      apply IHPE2 in NDl'.\n      now apply ncp_trans with (js:=l').\n  Qed.\n\n  Lemma ncp_perm is js:\n    NatCyclePerm is js ->\n    Permutation is js.\n\n    intros ND; induction ND; auto.\n    rewrite (Permutation_app_comm is [i]).\n    now apply IHND.\n  Qed.\n\nEnd NatCyclePerm.\n\n\n(** ** [Perm2] Facts\n\n   We are finally ready to state the [Perm2] definition\n   and prove it equivalent to [NatCyclePerm], and therefore\n   [Permutation]. *)\n\nSection Perm2.\n  Hint Constructors NatCyclePerm.\n\n  Inductive Perm2 {A}: list A -> list A -> Prop :=\n  | perm2_nil : Perm2 [] []\n  | perm2_cons : forall x y a,\n      Perm2 x y -> Perm2 (a :: x) (a :: y)\n  | perm2_cycle : forall x y a,\n      Perm2 (a :: x) y -> Perm2 (x ++ [a]) y.\n  Hint Constructors Perm2.\n\n  Lemma perm2_length_eq {A} (xs ys:list A):\n    Perm2 xs ys ->\n    length xs = length ys.\n\n    intros PE; induction PE; auto.\n    simpl; now apply eq_S.\n    rewrite app_length; rewrite <- IHPE; simpl. omega.\n  Qed.\n\n\n  Lemma ncp_perm2 {A} is js (ctx:list A):\n    NatCyclePerm is js ->\n    AllLess (length ctx) is ->\n    Perm2 (map_nth is ctx) (map_nth js ctx).\n\n    intros PE AL.\n    induction PE; simpl.\n    - auto.\n    - remember (nth_error ctx i) as a.\n      destruct a; constructor.\n      apply IHPE; now apply (AllLess_skip AL).\n    - assert (AllLess (length ctx) is) as ALX by (now apply (AllLess_app_1 AL)).\n      assert (Perm2 (map_nth (i :: is) ctx) (map_nth js ctx)) as IPE.\n      apply IHPE.\n      apply AllLess_cons; auto; apply (AllLess_app_2 AL); intuition.\n      clear IHPE.\n      rewrite map_nth_app by (apply ALX).\n      simpl in *.\n      remember (nth_error ctx i) as a; destruct a.\n      + now apply perm2_cycle.\n      + symmetry in Heqa; apply nth_error_None in Heqa.\n        assert (i < length ctx) by (apply AL; intuition).\n        omega.\n  Qed.\n\n  Lemma perm2_np {A} (xs ys:list A):\n    Perm2 xs ys ->\n    exists is, NatCyclePerm is (iota (length xs))\n               /\\ map_nth is ys = xs.\n\n    intros PE; induction PE.\n    - exists []; repeat split; auto.\n    - destruct IHPE as [is [NPE MX]].\n      exists (0 :: map S is).\n      apply ncp_expand in NPE.\n      destruct NPE as [NDi [NDj IN]].\n      split.\n      + simpl length.\n        rewrite iota_S; constructor.\n        apply ncp_all.\n        * apply FinFun.Injective_map_NoDup; auto.\n          unfold FinFun.Injective; now apply eq_add_S.\n        * apply FinFun.Injective_map_NoDup; auto.\n          unfold FinFun.Injective; now apply eq_add_S.\n        * intros; repeat rewrite in_map_iff.\n          split; intros.\n          destruct H as [m [S I]].\n          exists m; rewrite <- IN; intuition.\n          destruct H as [m [S I]].\n          exists m; rewrite IN; intuition.\n        * rewrite in_map_iff.\n          intro H; destruct H as [m [S I]]; omega.\n      + simpl.\n        rewrite map_nth_cons.\n        rewrite MX; auto.\n    - destruct IHPE as [is [NP MX]].\n      assert (length is = length (iota (length (a :: x)))) as Lis\n          by (apply (ncp_length_eq NP)).\n      rewrite iota_length in Lis; simpl in Lis.\n      destruct is; simpl in MX; try discriminate.\n      remember (nth_error y n) as b.\n      destruct b; try discriminate.\n      exists (is ++ [n]); split.\n      + apply ncp_cycle.\n        rewrite app_length; rewrite plus_comm;\n          rewrite <- app_length; now apply NP.\n      + inversion MX; subst.\n        rewrite map_nth_app; simpl.\n        now rewrite <- Heqb.\n        rewrite map_nth_length.\n        now apply eq_add_S.\n  Qed.\n\n\n  Lemma perm2_refl {A} (xs:list A):\n    Perm2 xs xs.\n\n    rewrite <- (map_nth_iota xs).\n    apply ncp_perm2.\n    apply ncp_refl.\n    apply iota_NoDup.\n    apply iota_AllLess.\n  Qed.\n\n  Lemma perm2_sym {A} (xs ys:list A):\n    Perm2 xs ys -> Perm2 ys xs.\n\n    intros.\n    assert (length xs = length ys) as LE by (now apply perm2_length_eq).\n    apply perm2_np in H.\n    destruct H as [is [NP MX]].\n    apply ncp_sym in NP.\n    rewrite <- MX.\n    rewrite <- (map_nth_iota ys) at 1.\n    rewrite <- LE.\n    apply ncp_perm2; auto.\n    rewrite <- LE; now apply iota_AllLess.\n  Qed.\n\n  (* Transitivity in [Perm2] doesn’t follow immediately from\n     transitivity in [NatCyclePerm], for a funny reason. The\n     [perm2_np] lemma lets us construct [NatCyclePerm]s\n     between [xs] and [ys], and between [ys] and [zs]---but\n     unfortunately, those [NatCyclePerm]s are unrelated!\n     (The [nat] list used to represent [ys] differs.) So we\n     need to add another link to the transitive chain.\n     That’s what NoDup_nat_complete is for. *)\n\n  Lemma perm2_trans {A} (xs ys zs:list A):\n    Perm2 xs ys ->\n    Perm2 ys zs ->\n    Perm2 xs zs.\n\n    intros PX PY.\n    remember (length xs) as n.\n    generalize (perm2_length_eq _ _ PX); intros Heqys.\n    generalize (perm2_length_eq _ _ PY); intros Heqzs.\n    rewrite <- Heqn in *; rewrite <- Heqys in *.\n\n    apply perm2_np in PX.\n    destruct PX as [is [NPX MX]].\n    apply perm2_np in PY.\n    destruct PY as [js [NPY MZ]].\n    rewrite <- Heqn in *; rewrite <- Heqys in *.\n    generalize (ncp_length_eq NPX); intros Heqjs.\n    generalize (ncp_length_eq NPY); intros Heqks.\n    rewrite iota_length in *.\n\n    assert (AllLess n is) as ALI. {\n      unfold AllLess; intros i H.\n      apply in_iota_iff.\n      now apply (ncp_in_iff NPX).\n    }\n    assert (AllLess n js) as ALJ. {\n      unfold AllLess; intros j H.\n      apply in_iota_iff.\n      now apply (ncp_in_iff NPY).\n    }\n    generalize (ncp_NoDup_is NPX); intros NDi.\n    generalize (ncp_NoDup_is NPY); intros NDj.\n    assert (length (map_nth is js) = n) as Heqmij. {\n      pose (map_nth_length is js).\n      rewrite Heqks in i.\n      rewrite i in ALI.\n      rewrite <- ALI; now rewrite Heqjs.\n    }\n    assert (forall a, In a (map_nth is js) <-> In a (iota n)) as IN. {\n      intros i; split; intros.\n      - apply in_map_nth in H; now apply (ncp_in_iff NPY).\n      - apply NoDup_nat_complete.\n        apply map_nth_NoDup; auto.\n        unfold AllLess; intros ii HH.\n        rewrite Heqmij.\n        apply ALJ.\n        now apply in_map_nth with (is0:=is).\n        rewrite Heqmij; now apply in_iota_iff.\n    }\n\n    replace xs with (map_nth (map_nth is js) zs).\n    replace zs with (map_nth (iota n) zs) at 2.\n\n    - apply ncp_perm2.\n      apply ncp_all; auto.\n      apply map_nth_NoDup; auto.\n      now apply iota_NoDup.\n      rewrite <- Heqzs; unfold AllLess; intros i H.\n      apply ALJ; now apply (in_map_nth is).\n    - rewrite Heqzs; apply map_nth_iota.\n    - rewrite <- map_nth_compose.\n      now rewrite MZ.\n      now rewrite Heqks.\n      now rewrite <- Heqzs.\n  Qed.\n\nEnd Perm2.\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/exsolutions/natcycleperm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7916573247357847}}
{"text": "\nRequire Import Arith Bool.\n\nSearch ((_+_) = (_+_)).\n(*\nNat.add_comm:\n        forall n m : nat, \n        n + m = m + n\nNat.add_assoc: forall n m p : nat, n + (m + p) = n + m + p\n *)\n\n\nProposition foo :\n  forall n1 n2 n3 : nat,\n    (n3 + n1) + n2 = n1 + (n2 + n3).\n\nProof.\n  intro x.\n  \n  Restart.\n  \n  intro n1.\n  intro n2.\n  intro n3.\n  \n  Restart.\n  \n  intros n1 n2 n3.\n  (*Note that in goals the parenthesis on LHS is gone because coq is implicitly left-to-right already.*)\n\n  Check (Nat.add_comm n3 n1).\n  rewrite -> (Nat.add_comm n3 n1).\n\n  Check (Nat.add_assoc n1 n3 n2).\n  rewrite <- (Nat.add_assoc n1 n3 n2).\n\n  Check (Nat.add_comm n3 n2).\n  rewrite -> (Nat.add_comm n3 n2).\n\n  reflexivity.\n\n  Restart.\n\n  intros n1 n2 n3.\n  \n  Check (Nat.add_comm n2 n3).\n  rewrite -> (Nat.add_comm n2 n3).\n\n  Check (Nat.add_assoc n1 n3 n2).\n  rewrite -> (Nat.add_assoc n1 n3 n2).\n\n  Check (Nat.add_comm n1 n3).\n  rewrite -> (Nat.add_comm n1 n3).\n\n  reflexivity.\n\n  Restart.\n\n  intros n1 n2 n3. \n  Check (Nat.add_comm n1 (n2 + n3)).\n  rewrite -> (Nat.add_comm n1 (n2 + n3)).\n  \n  Check (Nat.add_comm n2 (n3 + n1)).\n  rewrite -> (Nat.add_comm (n3 + n1) n2).\n \n  Check (Nat.add_assoc n2 n3 n1).\n  rewrite -> (Nat.add_assoc n2 n3 n1).\n\n  reflexivity.\nQed.\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/w2_class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7915212704813777}}
{"text": "From LF Require Export Basics.\n\nTheorem plus_n_O : forall n : nat, n = n + 0.\nProof.\n  intro 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  intro n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. apply IHn'.\nQed.\n\nTheorem mult_O_r : forall n : nat, n * 0 = 0.\nProof.\n  intro n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. apply IHn'.\nQed.\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' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [|n' IHn'].\n  - simpl. apply plus_n_O.\n  - simpl. rewrite IHn'. apply plus_n_Sm.\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) : 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  intro n; induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite IHn'. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n    evenb (S n) = negb (evenb n).\nProof.\n  intro n. induction n as [|n' IHn'].\n  - reflexivity.\n  - rewrite IHn'. simpl. rewrite negb_involutive.\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). { apply plus_comm. }\n  rewrite H. reflexivity.\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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7914914388340539}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\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\nPrint next_nat.\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.\nQed.\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\nTheorem total_relation_not_a_partial_function :\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply (tr 0 0).\n    - apply (tr 0 1).\n  }\n  inversion Nonsense. Qed.\n\nTheorem empty_relation_is_a_partial_function :\n  partial_function empty_relation.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  rewrite <- H6. rewrite <- H3.\n  reflexivity.\nQed.\n\nDefinition reflexive {X : Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive : 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).\n\nTheorem le_trans : transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - apply Hnm.\n  - apply le_S. apply IHHmo. Qed.\n\nTheorem lt_trans : 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.\nQed.\n\nTheorem lt_trans' : transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm' o].\n  - inversion Hnm.\n    + rewrite -> H in Hnm. rewrite -> H. apply le_S.\n      apply le_n.\n    + rewrite H0. apply le_S. apply Hnm.\n  - apply le_S. apply 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  - inversion Hmo.\n    + rewrite <- H0. apply le_S. apply Hnm.\n    + apply le_S. apply IHo'. apply H0.\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 n m H.\n  inversion H.\n  - apply le_n.\n  - apply le_Sn_le. apply H1.\nQed.\n\nTheorem le_Sn_n : forall n, ~ (S n <= n).\nProof.\n  intros n. unfold not.\n  intros H. induction n.\n  - inversion H.\n  - apply IHn. apply le_S_n. 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 : ~ (symmetric le).\nProof.\n  unfold not.\n  unfold symmetric.\n  intro H.\n  assert (1 <= 0). {\n    apply (H 0). apply le_S. apply le_n.\n  }\n  inversion H0.\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 : antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a b H1 H2.\n  inversion H1.\n  - reflexivity.\n  - apply (le_trans a b a) in H1.\nAdmitted.\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\nTheorem le_order : order le.\nProof.\n  unfold order. split.\n  - apply le_reflexive.\n  - split.\n    + apply le_antisymmetric.\n    + apply le_trans. Qed.\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. split.\n  - intro H. induction H.\n    + apply rt_refl.\n    + apply rt_trans with m. apply IHle.\n      apply rt_step. apply nn.\n  - intro H. induction H.\n    + inversion H. apply le_S. apply le_n.\n    + apply le_n.\n    + apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\n\nInductive clos_refl_trans_ln {A : Type}\n  (R : relation A) (x : A) : A -> Prop :=\n  | rtln_refl : clos_refl_trans_ln R x x\n  | rtln_trans (y z : A) : \n      R x y -> clos_refl_trans_ln R y z ->\n      clos_refl_trans_ln R x z.\n\n\nLemma rsc_R : forall (X : Type) (R : relation X) (x y : X),\n  R x y -> clos_refl_trans_ln R x y.\nProof.\n  intros X R x y H.\n  apply rtln_trans with y. apply H. apply rtln_refl. Qed.\n\n\nLemma rsc_trans : forall (X:Type) (R : relation X) (x y z : X),\n  clos_refl_trans_ln R x y ->\n  clos_refl_trans_ln R y z ->\n  clos_refl_trans_ln R x z.\nProof.\n  intros X R x y z H1 H2.\n  induction H1.\n  - apply H2.\n  - induction H1.\n    +\nAbort.\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7913058258883658}}
{"text": "Require Export Basics.\n\nTheorem plus_n_O : forall n : nat, n = n + 0.\nProof.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat, minus n n = 0.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nLemma plus_one : forall n : nat,\n  S n = n + 1.\nProof.\n  induction n.\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  induction n as [| n' IHn'].\n  - simpl. tauto.\n  - intros m. simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_comm: forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  - rewrite <- plus_n_O. rewrite plus_O_n. reflexivity.\n  - simpl. rewrite IHn. rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n.\n  - 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 : nat,\n  double n = n + n.\nProof.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\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\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | S n' => negb (evenb n')\n  end.\n\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  intros n.\n  simpl.\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  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity.\nQed.", "meta": {"author": "btwooton", "repo": "SoftwareFoundationsSolutions", "sha": "06afe12ecf2ac79bb51171b2ddc8833d5c4d1cdf", "save_path": "github-repos/coq/btwooton-SoftwareFoundationsSolutions", "path": "github-repos/coq/btwooton-SoftwareFoundationsSolutions/SoftwareFoundationsSolutions-06afe12ecf2ac79bb51171b2ddc8833d5c4d1cdf/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.791305817725091}}
{"text": "From LF Require Export Induction.\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) (x:X) : X :=\n  f (f (f x)).\n\nCheck doit3times.\n\nCheck @doit3times.\n\nDefinition minustwo (x:nat) : nat := x - 2.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\n(* minustwo (minustwo (minustwo 9) )*)\nProof. reflexivity. Qed.\n\n\n(* List notation *)\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n    \n(** Filter function *)\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)\n              else filter test t\n  end.\n\nExample test_filter1: filter even [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (List.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(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(* Write a function [filter_lt_10] that filters all numbers less than \n   10 from a given list list of numbers. *)\n\nCompute (filter (fun xs => List.length xs =? 1)\n[ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]).    \n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\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(* Write a function [map_to_length] that maps a list of lists to list \n   of their lengths *)\n\nDefinition map_to_length {X:Type} (l : list (list X)) : list nat := \n  map (fun xs => List.length xs) l.\n\nExample test_map_to_length : \n  map_to_length [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ] = \n                      [2; 1; 1; 3; 0; 1].\nProof. reflexivity. Qed.\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(* \n   sum[2; 3; 4; 5]\n   = sum [2; 3; 4] + 5\n   = sum [2;3] + 4 + 5\n   .. = 2 + 3 + 4 +5\n\n   sum[2; 3; 4; 5]\n   = 2 + sum [3;4;5]\n   = 2 + 3 + sum [4;5]\n   = ..\n   = 2 + 3 + 4 +5\n*)\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\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nCheck @fold.\nCheck fold mult.\n\n(* ================================================================= *)\n(** ** Currying and Uncurrying *)\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", "meta": {"author": "csci5535", "repo": "csci5535.github.io", "sha": "591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d", "save_path": "github-repos/coq/csci5535-csci5535.github.io", "path": "github-repos/coq/csci5535-csci5535.github.io/csci5535.github.io-591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d/coq/MyPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.890294223211224, "lm_q1q2_score": 0.7912568301673562}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*** Proofs by induction *)\n\n(** * Generalizing Induction Hypothesis *)\n\n(** The standard (non-tail-recursive) factorial function *)\nLocate \"`!\".\nPrint factorial.\nPrint fact_rec.\n\nFixpoint factorial_mul (n : nat) (k : nat) : nat :=\n  if n is n'.+1 then\n    factorial_mul n' (n * k)\n  else\n    k.\n\nDefinition factorial_iter (n : nat) : nat :=\n  factorial_mul n 1.\n\nLemma factorial_mul_correct n k :\n  factorial_mul n k = n`! * k.\nProof.\nelim: n k=> [|n IHn] k; first by rewrite fact0 mul1n.\nby rewrite factS /= IHn mulnCA mulnA.\nQed.\n\nLemma factorial_iter_correct n :\n  factorial_iter n = n`!.\nProof.\nby rewrite /factorial_iter factorial_mul_correct muln1.\nQed.\n\n\n\n(** * Fibonacci numbers and custom induction principles *)\n\n(** Let's define a recursive Fibonacci function *)\n\n(** Coq cannot figure out that we are using\n    structural recursion here. It needs a hint. *)\nFail Fixpoint fib (n : nat) : nat :=\n  if n is n''.+2 then fib n'' + fib n''.+1\n  else n.\n\n(** Here is the hint: name a structural subterm explicitly\n    using [as]-annotation *)\nFixpoint fib (n : nat) : nat :=\n  if n is (n''.+1 as n').+1 then fib n'' + fib n'\n  else n.\n\n\n(** Illustrate how [simpl nomatch] works *)\n\nSection Illustrate_simpl_nomatch.\nVariable n : nat.\n\nLemma default_behavior :\n  fib n.+1 = 0.\nProof.\nmove=> /=.  (* fib n.+1 should not get simplified *)\nAbort.\n\nArguments fib n : simpl nomatch.\n\nLemma after_simpl_nomatch :\n  fib n.+2 = 0.\nProof.\nmove=> /=.  (* this is what we want *)\nAbort.\n\nEnd Illustrate_simpl_nomatch.\n\n\n(** The results of the [Arguments] command does not survive\n    sections so we have to repeat it here *)\nArguments fib n : simpl nomatch.\n\n\n(** And here is a more efficient iterative version *)\nFixpoint fib_iter (n : nat) (f0 f1 : nat) : nat :=\n  if n is n'.+1 then fib_iter n' f1 (f0 + f1)\n  else f0.\n\nArguments fib_iter : simpl nomatch.\n\nLemma fib_iterS n f0 f1 :\n  fib_iter n.+1 f0 f1 = fib_iter n f1 (f0 + f1).\nProof. by []. Qed.\n\nLemma fib_iter_sum n f0 f1 :\n  fib_iter n.+2 f0 f1 =\n  fib_iter n f0 f1 + fib_iter n.+1 f0 f1.\nProof.\nelim: n f0 f1 => [//|n IHn] f0 f1.\nby rewrite fib_iterS IHn.\nQed.\n\nLemma dup {A} : A -> A * A. Proof. by []. Qed.\n\n(** This induction principle repeats, in a sense,\n    the structure of the (recursive) Fibonacci function *)\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 Istep n; suffices: P n /\\ P n.+1 by case.\nby elim: n=> // n [/Istep pn12] /dup[/pn12].\nQed.\n\nLemma fib_iter_correct n :\n  fib_iter n 0 1 = fib n.\nProof.\nelim/nat_ind2: n=> // n IHn1 IHn2.\nby rewrite fib_iter_sum IHn1 IHn2.\nQed.\n(** Note: fib_iter_correct can be proven using\n    suffices:\n     (fib_iter n 0 1 = fib n /\\ fib_iter n.+1 0 1 = fib n.+1).\n *)\n\n\n\n(** * Another way is to provide a spec for fib_iter *)\n\nFrom Coq Require Import Omega.  (* to use [omega] tactic *)\nFrom Coq Require Import Psatz.  (* to use [lia] tactic *)\n\n(**\n- [omega] is a solver for Presburger arithmetic:\n  https://en.wikipedia.org/wiki/Presburger_arithmetic\n\n- [lia] is a solver for Linear Integer Arithmetic\n*)\n\nLemma fib_iter_spec n f0 f1 :\n  fib_iter n.+1 f0 f1 = f0 * fib n + f1 * fib n.+1.\nProof.\nelim: n f0 f1=> [|n IHn] f0 f1; first by rewrite muln0 muln1.\nrewrite fib_iterS IHn /=.\n(** Using a bit of automation to finish off the proof *)\nFail rewrite -!plusE -!multE; omega.\nby rewrite -!plusE -!multE; lia.\n\nRestart.\n\n(** Manual solution *)\nelim: n f0 f1=> [|n IHn] f0 f1; first by rewrite muln0 muln1.\nby rewrite fib_iterS IHn /= mulnDr mulnDl addnCA.\nQed.\n\nLemma fib_iter_correct' n :\n  fib_iter n 0 1 = fib n.\nProof.\nby case: n=> // n; rewrite fib_iter_spec mul1n.\nQed.\n\n\n\n(** * Yet another solutiton *)\n\n(* due to D.A. Turner, see his \"Total Functional Programming\" (2004) *)\nLemma fib_iter_spec' n p :\n  fib_iter n (fib p) (fib p.+1) = fib (p + n).\nProof.\nelim: n p=> [|n IHn] p; first by rewrite addn0.\nby rewrite fib_iterS IHn addnS.\nQed.\n\nLemma fib_iter_correct'' n :\n  fib_iter n 0 1 = fib n.\nProof.\nFail apply: fib_iter_spec'.\nby apply: (fib_iter_spec' n 0).\n(* Alternative (longer, but more explicit) solution: *)\nRestart.\nsuffices: (fib_iter n (fib 0) (fib 1) = fib n) by [].\nby apply: fib_iter_spec'.\nQed.\n\n\n\n(** * Complete induction *)\n\n(** It's also called:\n    - strong induction;\n    - well-founded induction;\n    - course-of-values induction\n *)\n\nLemma lt_wf_ind (P : nat -> Prop) :\n  (forall m, (forall k : nat, (k < m) -> P k) -> P m) ->\n  forall n, P n.\nProof.\n  (* exercise! *)\nAdmitted.\n\n\n(** In SSReflect/Mathcomp one does not use\n    a custom principle like above\n    directly, but rather generates it on the fly\n    using [leqnn] lemma.\n *)\n\nLemma fib_iter_correct''' n :\n  fib_iter n 0 1 = fib n.\nProof.\nmove: (leqnn n).\nmove: {-2}n.\nmove: n.\nelim.\ncase.\ndone.\nby case.\nmove=> n IHn.\n(* ^ the proof steps above correspond to one line below\n   marked <- *)\n\nRestart.\n\nelim: n {-2}n (leqnn n)=> [[]//|n IHn].  (* <- *)\ncase=> //; case=> // n0.\nrewrite fib_iter_sum.\nmove=> /dup[/ltnW/IHn-> ].\nby rewrite ltnS=> /IHn->.\nQed.\n\n\n\n\n\n(*** Lists *)\n\nFrom mathcomp Require Import ssrnat ssrbool eqtype seq path.\n(** Note that we added [seq] and [path] modules to imports *)\n\n(** [seq] is a Mathcomp's notation for [list] data type *)\nPrint seq.\nPrint list.\n\n(**\n   Inductive list (A : Type) : Type :=\n   | nil : seq A\n   | cons : A -> seq A -> seq A\n*)\n\n(** A simple example *)\nCompute [:: 1; 2; 3] ++ [::].\n\n(** List concatenation *)\nLocate \"++\".\nPrint cat.\n\n\n(** * Structural Induction for Lists *)\n\nSection StructuralInduction.\n\nVariable T : Type.\n\nImplicit Types xs ys zs : seq T.\n\nLemma catA xs ys zs :\n  xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\nProof.\n\n\nCheck list_ind :\n  forall (A : Type) (P : seq A -> Prop),\n    P [::] ->\n    (forall (a : A) (l : seq A), P l -> P (a :: l)) ->\n    forall l : seq A, P l.\n\nby elim: xs => //= x xs' ->.\nQed.\n\nEnd StructuralInduction.\n\n\n(** * Classical example: list reversal function *)\n\n(** The standard implementation is tail recursive *)\nPrint rev.\nPrint catrev.\n\nFixpoint rev_rec {A : Type} (xs : seq A) : seq A :=\n  if xs is (x::xs') then\n    rev_rec xs' ++ [:: x]\n  else xs.\n\nLemma rev_rec_inv A :\n  involutive (@rev A).\nProof.\nAdmitted.\n\nLemma rev_correct A (xs : seq A):\n  rev xs = rev_rec xs.\nProof.\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/code/lecture04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8902942312159383, "lm_q1q2_score": 0.7912568241655605}}
{"text": "(* QUIZ *)\n(** Recall the types of [cons] and [nil]:\n       nil : forall X : Type, list X \n       cons : forall X : Type, X -> list X -> list X \n    What is the type of [cons bool true (cons nat 3 (nil nat))]?\n\n    (1) [nat -> list nat -> list nat]\n\n    (2) [forall (X:Type), X -> list X -> list X]\n\n    (3) [list nat]\n    \n    (4) [list bool]\n\n    (5) No type can be assigned.\n*)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nFail Check (cons bool true (cons nat 3 (nil nat))).\n\n(* The command has indeed failed with message:\nThe term \"cons nat 3 (nil nat)\" has type \"list nat\"\nwhile it is expected to have type \"list bool\". *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** Recall the definition of [repeat]: *)\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(*  What is the type of [repeat?\n\n    (1) [nat -> nat -> list nat]\n\n    (2) [X -> nat -> list X]\n\n    (3) [forall (X Y:Type), X -> nat -> list Y]\n\n    (4) [forall (X:Type), X -> nat -> list X]\n\n    (5) No type can be assigned.\n\n*)\n\nCheck repeat.\n(* repeat\n     : forall X : Type, X -> nat -> list X *)\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What is the type of [repeat nat 1 2]?\n\n    (1) [list nat]\n\n    (2) [forall (X:Type), X -> nat -> list X]\n\n    (3) [list bool]\n\n    (4) No type can be assigned.\n\n*)\nCheck (repeat nat 1 2).\nArguments nil {X}.\nArguments cons {X} _ _.\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n\nCheck (repeat nat 1 2).\n(* repeat nat 1 2\n     : list nat *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n\n(** Which type does Coq assign to the following expression?\n    [1;2;3]\n    (1) [list nat]\n\n    (2) [list bool]\n\n    (3) [bool]\n\n    (4) No type can be assigned \n*)\n\nCheck [1;2;3].\n(* [1; 2; 3]\n     : list nat *)\n(* /QUIZ *)\n\n(* QUIZ *)\n(** Which type does Coq assign to the following expression?\n    [3 + 4] ++ nil\n    (1) [list nat]\n\n    (2) [list bool]\n\n    (3) [bool]\n\n    (4) No type can be assigned\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\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nCheck @app.\n(* app\n     : forall X : Type, list X -> list X -> list X *)\n\nCheck ([3 + 4] ++ nil).\n(* [3 + 4] ++ [ ]\n     : list nat *)\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n    [andb true false ++ nil]\n    (1) [list nat]\n\n    (2) [list bool]\n\n    (3) [bool]\n\n    (4) No type can be assigned\n*)\n\nFail Check [andb true false ++ nil].\n(* The command has indeed failed with message:\nThe term \"(true && false)%bool\" has type \"bool\"\nwhile it is expected to have type \"list ?X0\" *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n    [1; nil]\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n*)\n\nFail Check [1;nil].\n(* The command has indeed failed with message:\nThe term \"[[ ]]\" has type \"list (list ?X)\" while it is expected to have type\n \"list nat\". *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n\n        [[1]; nil]\n\n\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n *)\n\nCheck [[1]; nil].\n(* [[1]; [ ]]\n     : list (list nat) *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** And what about this one?\n\n         [1] :: [nil]\n\n\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n*)\n\nCheck [1] :: [nil].\n(* [[1]; [ ]]\n     : list (list nat) *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n\n        @nil bool\n\n\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n*)\n\nCheck (@nil bool).\n(* [ ]\n     : list bool *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n\n        nil bool\n\n\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n*)\n\nFail Check (nil bool).\n\n(* The command has indeed failed with message:\nIllegal application (Non-functional construction): \nThe expression \"[ ]\" of type \"list ?X\" cannot be applied to the term\n \"bool\" : \"Set\" *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What about this one?\n   [@nil 3]\n    (1) [list nat]\n\n    (2) [list (list nat)]\n\n    (3) [list bool]\n\n    (4) No type can be assigned\n*)\nCheck nil.\nCheck @nil.\nCheck (@nil nat).\n\nFail Check (@nil 3).\n(* The command has indeed failed with message:\nThe term \"3\" has type \"nat\" while it is expected to have type \"Type\". *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** Recall the definition of [map]: *)\n      Fixpoint 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(*    What is the type of [map]?\n\n    (1) [forall X Y : Type, X -> Y -> list X -> list Y]\n\n    (2) [X -> Y -> list X -> list Y]\n\n    (3) [forall X Y : Type, (X -> Y) -> list X -> list Y]\n\n    (4) [forall X : Type, (X -> X) -> list X -> list X]\n\n*)\n\nCheck @map.\n(* map\n     : forall X Y : Type, (X -> Y) -> list X -> list Y *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** Recall that [evenb] has type [nat -> bool].  \n\n    What is the type of [map evenb]?\n\n    (1) [forall X Y : Type, (X -> Y) -> list X -> list Y]\n\n    (2) [list nat -> list bool]\n\n    (3) [list nat -> list Y]\n\n    (4) [forall Y : Type, list nat -> list Y]\n\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\nCheck (map evenb).\n\n(* map evenb\n     : list nat -> list bool *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** Here is the definition of [fold] again: *)\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(*    What is the type of [fold]?\n\n    (1) [forall X Y : Type, (X -> Y -> Y) -> list X -> Y -> Y]\n\n    (2) [X -> Y -> (X -> Y -> Y) -> list X -> Y -> Y]\n\n    (3) [forall X Y : Type, X -> Y -> Y -> list X -> Y -> Y]\n\n    (4) [X -> Y->  X -> Y -> Y -> list X -> Y -> Y]\n\n*)\n\nCheck @fold.\n\n(* fold\n     : forall X Y : Type, (X -> Y -> Y) -> list X -> Y -> Y *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What is the type of [fold plus]?\n\n    (1) [forall X Y : Type, list X -> Y -> Y]\n\n    (2) [nat -> nat -> list nat -> nat -> nat]\n\n    (3) [forall Y : Type, list nat -> Y -> nat]\n\n    (4) [list nat -> nat -> nat]\n\n    (5) [forall X Y : Type, list nat -> nat -> nat]\n\n*)\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nCheck (fold plus).\n(* fold plus\n     : list nat -> nat -> nat *)\n\n(* /QUIZ *)\n\n(* QUIZ *)\n(** What does [fold plus [1;2;3;4] 0] simplify to?\n\n   (1) [[1;2;3;4]]\n\n   (2) [0]\n\n   (3) [10]\n\n   (4) [[3;7;0]]\n\n*)\n\nCompute (fold plus [1;2;3;4] 0).\n(* 10 : nat *)\n(* /QUIZ *)\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/PolyQuizSol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8933093982432729, "lm_q1q2_score": 0.7911429135486894}}
{"text": "Inductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem ev_4 : ev 4.\nProof. \napply ev_SS. \napply ev_SS. \napply ev_0. \nQed.\n\n\nTheorem ev_4' : ev 4.\nProof. \napply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\nintros n.\nsimpl.\nintros Hn.\napply ev_SS.\napply ev_SS.\napply Hn.\nQed.\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 double n := n * 2.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\ninduction n  as [| n'].\napply ev_0.\nsimpl.\napply ev_SS.\napply IHn'.\nQed.\n\nTheorem evenb_minus2: forall n,\n  evenb n = true -> evenb (pred (pred n)) = true.\nProof.\nintros [| [| n ]].\nreflexivity.\nintros H.\ninversion H.\nsimpl.\nintros H.\napply H.\nQed.\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\nintros n H.\ninversion H.\nsimpl.\napply ev_0.\nsimpl.\napply H0.\nQed.\n\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\nintros n H.\ninversion H.\napply H1.\nQed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\nintros H.\ninversion H.\nQed.\n\n\nTheorem SSSSev__even : forall n, ev (S (S (S (S n)))) -> ev n.\nProof.\nintros n H.\ninversion H.\ninversion H1.\napply H3.\nQed.\n\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\nintros absurd.\ninversion absurd.\ninversion H0.\ninversion H2.\nQed.\n\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n    exists 0. reflexivity.\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists(S k'). reflexivity.\nQed.\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\nintros.\nsplit.\napply ev_even.\nintros [k Hk].\nrewrite Hk.\napply ev_double.\nQed.\n\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\nintros.\ninduction H as [| h].\nsimpl.\napply H0.\nsimpl.\napply ev_SS.\napply IHev.\nQed.\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\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\nintros n.\nsplit.\nAbort.\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\nintros n m E En. \ngeneralize dependent E.\ninduction En.\nsimpl. \nintros. \napply E.\nsimpl. \nintros.\ninversion E.\napply IHEn in H0.\napply H0.\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/ComputationalLogic10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7910933191251167}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export ProofObjects.\n\nCheck nat_ind.\n\nTheorem mult_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity. Qed.\n\n(*standard, optional (plus_one_r')*)\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros n H. simpl. rewrite -> H. reflexivity. Qed.\n(*/standard, optional (plus_one_r')*)\n\nInductive yesno : Type :=\n  | yes\n  | no.\n\nCheck yesno_ind.\n\n(*standard, optional (rgb)*)\n(*forall P : rgb -> Prop, P red -> P green -> P blue -> forall y : rgb, P y*)\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nCheck rgb_ind.\n(*/standard, optional (rgb)*)\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\nCheck natlist_ind.\n\n(*standard, optional (natlist1)*)\n(*forall P : natlist1 -> Prop,\n       P nnil1 ->\n       (forall l : natlist1, P l -> forall n : nat, P (nsnoc1 l n)) ->\n       forall n : natlist1, P n*)\nInductive natlist1 : Type :=\n  | nnil1\n  | nsnoc1 (l : natlist1) (n : nat).\n\nCheck natlist1_ind.\n(*/standard, optional (natlist1)*)\n\n(*standard, optional (byntree_ind)*)\n(*forall P : byntree -> Prop,\n       P bempty ->\n       (forall yn : yesno, P (bleaf yn)) ->\n       (forall (yn : yesno) (t1 : byntree),\n        P t1 -> forall t2 : byntree, P t2 -> P (nbranch yn t1 t2)) ->\n       forall b : byntree, P b*)\nInductive byntree : Type :=\n | bempty\n | bleaf (yn : yesno)\n | nbranch (yn : yesno) (t1 t2 : byntree).\n\nCheck byntree_ind.\n(*/standard, optional (byntree_ind)*)\n\n(*standard, optional (ex_set)*)\nInductive ExSet : Type := \n  | con1 : bool -> ExSet\n  | con2 : nat -> ExSet -> ExSet.\n(*/standard, optional (ex_set)*)\n\n(*standard, optional (tree)*)\n(*forall (X : Type) (P : tree X -> Prop),\n       (forall x : X, P (leaf X x)) ->\n       (forall t1 : tree X, P t1 -> forall t2 : tree X, P t2 -> P (node X t1 t2)) ->\n       forall t : tree X, P t*)\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n(*/standard, optional (tree)*)\n\n(*standard, optional (mytype)*)\nInductive mytype (X: Type) : Type :=\n  | constr1 (x : X)\n  | constr2 (n : nat)\n  | constr3 (m : mytype X) (n : nat).\nCheck mytype_ind.\n(*/standard, optional (mytype)*)\n\n(*standard, optional (foo)*)\nInductive foo (X:Type) (Y:Type) :=\n  | bar (x : X) \n  | baz (y : Y)\n  | quux (f1 : nat -> foo X Y).\n\nCheck foo_ind.\n(*/standard, optional (foo)*)\n\n(*standard, optional (foo')*)\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\nCheck foo'_ind.\n(*/standard, optional (foo')*)\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  - unfold P_m0r. simpl. reflexivity.\n  - intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\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'].\n  - reflexivity.\n  -\n    \n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - intros m. rewrite <- plus_n_O. reflexivity.\n  - intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity. Qed.\n\nTheorem plus_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction m as [| m'].\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity. Qed.\n\nInductive even : nat -> Prop := \n| ev_0 : even 0 \n| ev_SS : forall n : nat, even n -> even (S (S n)).\n\nCheck even_ind.\n\nInductive even' : nat -> Prop :=\n| even'_0 : even' 0\n| even'_2 : even' 2\n| even'_sum n m (Hn : even' n) (Hm : even' m) : even' (n + m).\n\nTheorem ev_ev' : forall n, even n -> even' n.\nProof.\n  apply even_ind.\n  -\n    apply even'_0.\n  -\n    intros m Hm IH.\n    apply (even'_sum 2 m).\n    + apply even'_2.\n    + apply IH.\nQed.\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\nCheck le_ind.\n\n\n\n\n\n", "meta": {"author": "unisuke82", "repo": "SoftwareFoundation", "sha": "1911ed60b7dff597eac434734cb26d67162b6805", "save_path": "github-repos/coq/unisuke82-SoftwareFoundation", "path": "github-repos/coq/unisuke82-SoftwareFoundation/SoftwareFoundation-1911ed60b7dff597eac434734cb26d67162b6805/volume1/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8947894710123925, "lm_q1q2_score": 0.7910290467351409}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export Tactics.\nRequire Export Basics.\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\nLemma plus_O_lem : forall n m, n + m = 0 -> n = 0.\nProof.\n  induction n.\n  - intros. reflexivity.\n    - intros. simpl in H. inversion H.\nQed.\n    (** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros. split.\n  - apply (plus_O_lem _ _ H). \n  - rewrite plus_comm in H. apply (plus_O_lem _ _ H).\nQed.\n\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. destruct H. assumption.\nQed.\n\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]].\n  - apply and_intro. apply (and_intro _ _ HP HQ). assumption.\nQed.\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. destruct n.\n  - intros. left. reflexivity.\n  - intros. simpl in H. right. pose proof (and_exercise _ _ H) as H0.\n    destruct H0. assumption.\nQed.\n\n(** [] *)\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(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [].\n  - intros. apply (or_intro_r _ _ H).\n  - intros. apply (or_intro _ _ H).\nQed.\n  \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. unfold not in H. apply (ex_falso_quodlibet _ (H H0)).\nQed.\n\n\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   Since ~P expands to (P -> _|_) what we need to prove is\n   H:P -> (G:P -> _|_) -> _|_\n   Since we assume H which is a proof of P, we can apply G to obtain _|_\n   and we're done.\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not in *. intros. apply (H0 (H H1)).\nQed.\n\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. intros P []. intros. apply (H0 H).\nQed.\n\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(* We have to prove (P /\\ (P -> _|_)) -> _|_.\n   We can assume H:(P /\\ (P -> _|_)). Using and elimination we can also\n   assume H1:P and H2:P -> _|_. Applying H with H1 we get _|_ and we're done.\n *)\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\n(* NOTE: Since I used I for the binary exercise, I need to qualify it. *)\nLemma True_is_true : True.\nProof. apply Logic.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. unfold iff. split.\n  - intros. assumption.\n  - intros. assumption.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  unfold iff. intros P Q R [] []. intros. split.\n  - intros. apply (H1 (H H3)).\n  - intros. apply (H0 (H2 H3)).\nQed.\n\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  unfold iff. intros. split.\n  - intros []. intros. split.\n    + apply (or_intro _ _ H).\n    + apply (or_intro _ _ H).\n    + destruct H. split.\n      * apply (or_intro_r _ _ H).\n      * apply (or_intro_r _ _ H0).\n  - intros [ [] [] ].\n    + intros. left. assumption.\n    + intros. left. assumption.\n    + intros. left. assumption.\n    + intros. right. apply (and_intro _ _ H H0).\nQed.\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. unfold not. intros. destruct H0. apply (H0 (H x)).\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. split.\n  - intros. destruct H. destruct H.\n    + left. exists x. assumption.\n    + right. exists x. assumption.\n  - intros. destruct H.\n    + destruct H. exists x. left. assumption.\n    + destruct H. exists x. right. assumption.\nQed.\n\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.) *)\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nOpen Scope list_scope.\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 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.\n  - simpl. intros. unfold iff. split.\n    + intros. contradict H.\n    + intros. destruct H. destruct H. assumption.\n  - simpl. intros. unfold iff. split.\n    + intros. destruct H.\n      * {exists x. split.\n         - assumption.\n         - left. reflexivity.\n        }\n      * { pose proof (IHl y). rewrite H0 in H. destruct H.\n          - exists x0. split.\n            + destruct H. assumption.\n            + destruct H. right. assumption.\n        }\n    + intros. destruct H.\n      * { destruct H. destruct H0.\n          - left. rewrite <- H0 in H. assumption.\n          - right. pose proof (IHl y). rewrite H1. exists x0. split.\n            + assumption.\n            + assumption.\n          }\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. split.\n  - generalize dependent l'. induction l.\n    + simpl. intros. right. assumption.\n    + simpl. intros. destruct H.\n      * left. left. assumption.\n      * rewrite <- or_assoc. right. apply (IHl _ H).\n  - intros. generalize dependent l'. induction l.\n    + simpl. intros. destruct H.\n      * contradiction H.\n      * assumption.\n    + simpl. intros. rewrite <- or_assoc in H. destruct H.\n      * left. assumption.\n      * right. apply (IHl _ H).\nQed.\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    | [] => True\n    | x :: xs => P x /\\ All P xs\n  end.\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. induction l.\n  - simpl. unfold iff. split.\n    + intros. apply Logic.I.\n    + intros. contradict H0.\n  - simpl. split.\n    + intros. split.\n      * apply H. left. reflexivity.\n      * apply IHl. intros. apply H. right. assumption.\n    + intros. destruct H. destruct H0.\n      * rewrite <- H0. assumption.\n      * rewrite <- IHl in H1. apply H1. assumption.\nQed.\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 (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. simpl. 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. unfold combine_odd_even in H. rewrite H0 in H. assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros. unfold combine_odd_even in H. rewrite H0 in H. assumption.\nQed.\n\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\nLemma rev_append_app : forall {X : Type} (l1 : list X) (l2 : list X),\n    rev_append l1 l2 = rev_append l1 [] ++ l2.\nProof.\n  induction l1.\n  - reflexivity.\n  - simpl. intros. rewrite (IHl1 (x :: l2)). rewrite (IHl1 [x]).\n    rewrite <- app_assoc. reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n  intros. apply functional_extensionality.\n  intros l. induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. unfold tr_rev. simpl. rewrite rev_append_app.\n    reflexivity.\nQed.\n\n\n\n\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  intros. induction n.\n  - simpl. exists 0. reflexivity.\n  - destruct IHn. destruct (evenb n).\n    + rewrite evenb_S. rewrite H. exists x. rewrite evenb_double. simpl. reflexivity.\n    + rewrite H. simpl. rewrite evenb_double. exists (S x). reflexivity.\nQed.\n\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, 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\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros. split.\n  - intros. split.\n    + rewrite andb_commutative in H. apply (andb_true_elim2 _ _ H).\n    + apply (andb_true_elim2 _ _ H).\n  - intros. destruct H. rewrite H. rewrite H0. reflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros. split.\n  - intros. destruct b1.\n    + left. reflexivity.\n    + destruct b2.\n      * right. reflexivity.\n      * inversion H.\n  - intros. destruct H.\n    + rewrite H. reflexivity.\n    + rewrite H. destruct b1.\n      * reflexivity.\n      * reflexivity.\nQed.\n\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  intros. split.\n  - intros. unfold not. intros. rewrite H0 in H. \n    assert (forall n, beq_nat n n = true).\n    + induction n.\n      * reflexivity.\n      * simpl. rewrite IHn. reflexivity.\n    + rewrite (H1 y) in H. inversion H.\n  - unfold not. intros. destruct (beq_nat x y) eqn:H0.\n    + pose proof (beq_nat_true x y H0). contradiction (H H1).\n    + reflexivity.\nQed.\n    \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, l2 with\n  | [], [] => true\n  | x :: xs, y :: ys => beq x y && beq_list beq xs ys\n  | _ , _ => false\n  end.\n                                       \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. unfold iff. induction l1.\n  - split.\n    + intros. destruct l2.\n      * reflexivity.\n      * inversion H0.\n    + intros. destruct l2.\n      * reflexivity.\n      * inversion H0.\n  - split.\n    + intros. destruct l2.\n      * inversion H0.\n        * simpl in H0. \n          rewrite andb_commutative in H0.\n          pose proof (andb_true_elim2 _ _ H0).\n          rewrite (H x a) in H1. rewrite <- H1. apply f_equal.\n          rewrite andb_commutative in H0.\n          pose proof (andb_true_elim2 _ _ H0).\n          pose proof (IHl1 l2) as H3. destruct H3.\n          apply (H3 H2).\n    + intros. rewrite <- H0. \n      pose proof IHl1 (l1) as H1. destruct H1. simpl. rewrite H2.\n      * {assert (beq x x = true).\n         - rewrite H. reflexivity.\n         - rewrite H3. reflexivity.\n        }\n      * reflexivity.\nQed.\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. induction l.\n  - split.\n    + intros. reflexivity.\n    + intros. reflexivity.\n  - split.\n    + simpl. intros. split.\n      * rewrite andb_commutative in H.\n        apply (andb_true_elim2 _ _ H).\n      * pose proof (andb_true_elim2 _ _ H).\n        rewrite IHl in H0. apply H0.\n    + simpl. intros. destruct H. rewrite H. rewrite IHl. apply H0.\nQed.\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  unfold not. intros. apply H. right. intros. apply H.\n  apply (or_intro _ _ H0).\nQed.\n\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  intros. unfold excluded_middle in H. unfold not in H0. destruct (H (P x)).\n  - apply H1.\n  - unfold not in H1. exfalso. apply H0. exists x. apply H1.\nQed.\n\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\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_peirce : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle. unfold peirce. intros. unfold not in H.\n  destruct (H P).\n  - assumption.\n  - apply H0. intros. exfalso. apply H1. apply H2.\nQed.\n\nTheorem peirce_dne : peirce -> double_negation_elimination.\nProof.\n  unfold peirce. unfold double_negation_elimination. intros.\n  unfold not in H0. apply (H P False). intros. exfalso. apply H0.\n  intros. apply (H1 H2).\nQed.\n\nTheorem dne_de_morgan : double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  unfold double_negation_elimination. unfold de_morgan_not_and_not. unfold not.\n  intros. apply H. intros. apply H0. split.\n  + intros. apply H1. left. assumption.\n  + intros. apply H1. right. assumption.\nQed.\n\nTheorem de_morgan_implies_to_or : de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not. unfold implies_to_or. unfold not.\n  intros. apply H. intros. destruct H1. apply H1. intros. apply H2.\n  apply (H0 H3).\nQed.\n\nTheorem implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or. unfold excluded_middle. unfold not.\n  intros. apply or_commut. apply H. intros. assumption.\nQed.\n\n\n(** [] *)\n\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)", "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_03/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8840392909114835, "lm_q1q2_score": 0.7910290426480704}}
{"text": "(* La librairie strandard est décrite ici\n\n   https://coq.inria.fr/distrib/current/stdlib/\n\n*)\n\nRequire Import List. (* Voir https://coq.inria.fr/distrib/current/stdlib/Coq.Lists.List.html *)\n\nReserved Notation \"x '~p' y\" (at level 70, no associativity).\n\nSection list_perm.\n\n  Variable X : Type.\n\n  Inductive perm : list X -> list X -> Prop :=\n\n    | perm_nil   :                    nil ~p nil\n\n    | perm_cons  : forall x l1 l2,     l1 ~p l2 \n                               ->   x::l1 ~p x::l2\n\n    | perm_swap  : forall x y l,  x::y::l ~p y::x::l\n\n    | perm_trans : forall l1 l2 l3,    l1 ~p l2 \n                               ->      l2 ~p l3 \n                               ->      l1 ~p l3\n\n  where \"x '~p' y \" := (perm x y).\n\n  Fact perm_refl l : l ~p l. (* Cours *)\n  Proof.\n   induction l as [\n                  |list head IH]. (*Division en deux subgoals*)\n   apply perm_nil. (*Afin d'enlever le premier subgoal*)\n   apply perm_cons. (* Afin d'enlever le second subgoal*)\n   apply IH. (*Appliquer IH pour enlever le dernier subgoal*)\n  Qed.\n\n  Fact perm_length l1 l2 : l1 ~p l2 -> length l1 = length l2.\n  Proof.\n    intros H. (*Introduire hypothèse qui dit que l1 permute avec l2*)\n    induction H as [ \n                   | x l1 l2 H1 IH1 (*Si on ajoute x à l1 et à l2 et que length l1 = length l2 \n                   alors elles font toujours la même taille*)\n                   | x y l (*Ajouter deux éléments pas dans le même ordre \n                   pour montrer que l'ordre n'influe pas*)\n                   | l1 l2 l3 H1 IH1 H2 IH2 \n                   ].\n    apply refl_equal. (* Reflexivity :S'applique sur le but length nil = length nil*)\n    simpl. (* Permet d'enlever les x:: et de travailler directement\n    sur les listes *)\n    f_equal. (* Permet d'éliminer la fonction S des deux côtés*)\n    apply IH1. (* Appliquer IH1 *)\n    simpl. (* Enleve les x et y des sous buts *) \n    apply refl_equal. (* Reflexivity *)\n    transitivity (length l2). (* Transitivité sur l2 *)\n    apply IH1.\n    apply IH2.\n   Qed.\n\n  Fact perm_sym l1 l2 : l1 ~p l2 -> l2 ~p l1.\n  Proof.\n   intros H.\n   induction H. (* Création des 4 cas possibles *)\n   apply perm_nil.\n   apply perm_cons.\n   assumption. (* Applique IHperm *)\n   apply perm_swap.\n   apply perm_trans with l2. (* Pour pouvoir utiliser IHperm1 et IHperm2 *) \n   apply IHperm2.\n   apply IHperm1.\n  Qed.\n\n  Fact perm_middle x l r : x::l++r ~p l++x::r.\n  Proof.\n    induction l as [ | y list IHl ]. (* 1 sous but avec le cas de la liste vide et\n    un sous but avec le swap *)\n    simpl. (* Enlever les nil *)\n    apply perm_refl. (* Permet d'enlever un sous but *)\n    simpl. (*Permet d'enlever les parenthèses inutiles *)\n    apply perm_trans with (1 := perm_swap _ _ _).\n    apply perm_cons.\n    apply IHl.\n  Qed.\n\n  Let perm_app_left l r1 r2 : r1 ~p r2 -> l++r1 ~p l++r2.\n  Proof.\n    intros H.\n    induction l. (*Sous but avec le cas de la liste vide \n    et un sous but avec le swap*)\n    simpl. (* Enlever les nil *)\n    apply H.\n    simpl. (* Enlever parenthèses*)\n    apply perm_cons.\n    apply IHl.\n  Qed.\n\n  Fact perm_app l1 l2 r1 r2 : l1 ~p l2 -> r1 ~p r2 -> l1++r1 ~p l2++r2.\n  Proof.\n   intros H.\n   revert H r1 r2. (* Rentre les hypothèses dans le subgoal *)\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    simpl . (* Enlever les nil *)\n    intros H3 H4 H5.\n    apply H5.  (*Enlever le premier subgoal*)\n    intros H3 H4 H5.\n    simpl.\n    apply perm_cons. (*Permet d'enlever les x*)\n    apply IH1.\n    apply H5. (* Enlever le second subgoal *)\n    intros H3 H4 H5.\n    simpl.\n    apply perm_trans with (1 := perm_swap _ _ _). (*Permet de rendre le memvre de gauche \n    identique à celui de droite*)\n    apply perm_cons. (*enlève y*)  \n    apply perm_cons. (*Enlève x*)\n    apply perm_app_left.\n    apply H5. (* Enlève le troisième sous but *)\n    (*subgoal 4 *)\n    intros H3 H4 H5.\n    apply perm_trans with (l2 ++ H4). (* Faire le lien entre l1 et l3 *)\n    apply IH1.\n    apply H5.\n    apply perm_trans with (l3++H3).\n    apply IH2.\n    apply perm_sym. (* Pour appliquer H5 *)\n    apply H5.\n    apply perm_app_left.\n    apply H5. (* Résolution du dernier sous but *)\n   Qed.\n\n\n  (* incl est défini dans la librairie standard, fichier List.v *)\n\n  Print incl.\n\n  Fact perm_incl l m : l ~p m -> incl l m.\n  Proof.\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. (* Afin de récupérer x = Hyp1 *)\n    apply H.\n    right. (* Afin de récupérer l2 = Hyp1 *)\n    apply IH1. (* Pour pouvoir utiliser H ensuite *)\n    apply H.\n    intros ? ?.\n    revert H.\n    simpl. (* Pour faire fonctionner le tauto *)\n    tauto. (* Pas arrivé à trouver autrement *)\n    revert IH2.\n    revert IH1.\n    apply incl_tran. (* Transitivité sur les listes *)\n  Qed.\n\n\nEnd list_perm.\n\nInfix \"~p\" := (perm _) (at level 70, no associativity).\n", "meta": {"author": "Steven-Klinger", "repo": "Preuve", "sha": "a462b0b7eed677a9c0bce9c218f485879386c673", "save_path": "github-repos/coq/Steven-Klinger-Preuve", "path": "github-repos/coq/Steven-Klinger-Preuve/Preuve-a462b0b7eed677a9c0bce9c218f485879386c673/perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8947894527758053, "lm_q1q2_score": 0.7910290224121329}}
{"text": "Add LoadPath \"/Users/Henry/Documents/Drive/Coq/Math/sorting\".\nLoad natlist.\n\nFixpoint eqb (n m : nat) :=\n  match n,m with\n  | O,O => true\n  | O,_ => false\n  | _,O => false\n  | S n,S m => eqb n m\n  end.\n\nFixpoint leb (n m : nat) :=\n  match n,m with\n  | O,_ => true\n  | _,O => false\n  | S n,S m => leb n m\n  end.\n\nDefinition can_head (n : nat) (l : natlist) :=\n  match l with\n  | []   => true\n  | m::_ => leb n m\n  end.\n\nInductive sorted : natlist -> Prop :=\n  | sorted_nil  : sorted []\n  | sorted_cons : forall (n : nat) (l : natlist),\n      sorted l -> can_head n l = true -> sorted (cons n l).\n\nExample sorted_singleton : forall n, sorted (cons n nil).\nProof.\n  intros.\n  refine (sorted_cons _ _ _ _ ).\n  apply sorted_nil.\n  exact (eq_refl : can_head n [] = true).\nQed.\n\nLtac red_sorted_cons := (refine (sorted_cons _ _ _ _)).\n\n(* Example example1 : sorted (cons 1 (cons 2 (cons 3 nil))). *)\nExample sorted_example1 : sorted [1;2;3].\nProof.\n  red_sorted_cons. red_sorted_cons. red_sorted_cons.\n  apply sorted_nil.\n  apply eq_refl. apply eq_refl. apply eq_refl.\nQed.\n\nExample sorted_example2 : ~ sorted [2;1].\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  simpl in H3.\n  discriminate.\nQed.\n\nExample sorted_example3 : forall n, sorted [n;S n].\nProof.\n  intros. red_sorted_cons. red_sorted_cons.\n  apply sorted_nil.\n  simpl. reflexivity.\n  simpl. cut (leb n (S n) = true). intros. exact H.\n  induction n.\n    simpl. reflexivity.\n    simpl. apply IHn.\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/Math/sorting/ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7909825649610093}}
{"text": "\n\n(*---------------------------------- Descriptions ---------------------------------------\n\nIn this file we define the idea of graph isomorphism. This is done by defining following\npredicates:\n\nDefinition iso (G G': @UG A) :=\n     exists (f: A->A), (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n                 (forall x y, edg G x y = edg G' (f x) (f y)).\n\nDefinition iso_using (f: A->A)(G G': @UG A) :=\n     (forall x, f (f x) = x) /\\ \n     (nodes G') = (img f G) /\\ \n     (forall x y, edg G x y = edg G' (f x) (f y)).\n\nWhen we say (iso_using f G1 G2), we mean f is the function establishing the isomorphism\nbetween G1 and G2. We also prove that this relation is symmetric.\nNote that the self invertible nature of f makes it one_one on both G1 and G2. \nFollowing are some useful property of f:\n \n Lemma fx_is_one_one (l: list A)(f: A->A): (forall x, f (f x) = x) -> one_one_on l f.\n Lemma img_of_img (l: list A)(f: A->A)(Hl: IsOrd l):\n    (forall x, f (f x) = x)-> img f (img f l) = l.\n\n Lemma iso_sym1 (G G': @UG A)(f: A-> A): iso_using f G G' -> iso_using f G' G.\n Lemma iso_sym (G G': @UG A): iso G G' -> iso G' G.\n\n Lemma iso_one_one1 (G G': @UG A)(f: A-> A): iso_using f G G' -> one_one_on G f.\n Lemma iso_using_G' (G G': @UG A)(f: A-> A): iso_using f G G' -> nodes G' = (img f G).\n Lemma iso_one_one (G G': @UG A)(f: A-> A)(l: list A): iso_using f G G'-> one_one_on l f.\n Lemma iso_cardinal (G G': @UG A)(f: A-> A): iso_using f G G' -> |G|=|G'|.\n Lemma iso_sub_cardinal (G G': @UG A)(X: list A)(f: A->A): iso_using f G G' ->\n                                                           NoDup X -> |X|= | img f X |.\n Lemma iso_edg1  (G G': @UG A)(f: A-> A)(x y:A): iso_using f G G' ->\n                                                (edg G x y = edg G' (f x) (f y)).\n Lemma iso_edg2  (G G': @UG A)(f: A-> A)(x y: A): iso_using f G G' ->\n                                                (edg G' x y = edg G (f x) (f y)).\n-------------------------------------------------------------------------------------\n\n Stable Set, Cliq and Coloring of graphs has exact counterpart in the isomorphic Graphs.\n These results of existence of counterparts are summarized below: \n\n\n Lemma iso_cliq_in (G G': @UG A)(f: A-> A)(K: list A): iso_using f G G' -> \n                                                      Cliq_in G K -> Cliq_in G' (img f K).\n Lemma iso_cliq_in1 (G G': @UG A)(K: list A): iso G G' -> Cliq_in G K ->\n                                              (exists K', Cliq_in G' K' /\\ |K|=|K'|).\n Lemma max_K_in_G' (G G': @UG A)(f: A-> A)(K: list A): iso_using f G G' ->\n                                                    Max_K_in G K -> Max_K_in G' (img f K).\n\n\nLemma iso_stable (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G' -> \n                                                     Stable G I -> Stable G' (img f I).\nLemma iso_stable_in (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G'-> \n                                                Stable_in G I -> Stable_in G' (img f I).\nLemma max_I_in_G' (G G': @UG A)(f: A-> A)(I: list A): iso_using f G G' -> \n                                                  Max_I_in G I -> Max_I_in G' (img f I).\n\nLemma cliq_num_G' (G G': @UG A)(n: nat): iso G G' -> cliq_num G n -> cliq_num G' n.\nLemma i_num_G' (G G': @UG A)(n: nat):  iso G G' -> i_num G n -> i_num G' n. \nLemma chrom_num_G' (G G': @UG A)(n:nat): iso G G' -> chrom_num G n -> chrom_num G' n.\n\nLemma nice_G' (G G': @UG A): iso G G' -> Nice G -> Nice G'.\nLemma iso_subgraphs (G G' H: @UG A)(f: A->A):  iso_using f G G' -> Ind_subgraph H G -> \n                                      (exists H', Ind_subgraph H' G' /\\ iso_using f H H').\nLemma perfect_G' (G G': @UG A): iso G G' -> Perfect G -> Perfect G'.\n\n------------------------------------------------------------------------------------------*)\n\nRequire Export MoreDecUG.\n\nSet Implicit Arguments.\n\nSection GraphIsomorphism.\n\n  Context { A: ordType }.\n\n   Definition iso (G G': @dG A) :=\n     exists (f: A->A), (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n                 (forall x y, In x G-> In y G-> edg G x y = edg G' (f x) (f y)).\n\n   Definition iso_using (f: A->A)(G G': @dG A) :=\n     (forall x, f (f x) = x) /\\ (nodes G') = (img f G) /\\\n     (forall x y, In x G-> In y G-> edg G x y = edg G' (f x) (f y)).\n\n   (*--------------------- properties of bijective function for isomorphism----------------*)\n\n   Lemma f_is_one_one (f: A->A): (forall x, f (f x) = x) -> one_one f.\n   Proof.  { intros H. unfold one_one. intros x y  Hxy HC. absurd (x=y).\n               auto. replace y with (f (f y)). rewrite <- HC. symmetry;auto. auto. } Qed.\n     \n  Lemma fx_is_one_one (l: list A)(f: A->A): (forall x, f (f x) = x) -> one_one_on l f.\n  Proof. { intros H. unfold one_one_on. intros x y Hx Hy Hxy HC. absurd (x=y).\n           auto. replace y with (f (f y)). rewrite <- HC. symmetry;auto. auto. } Qed.\n  \n  Lemma img_of_img (l: list A)(f: A->A)(Hl: IsOrd l):\n    (forall x, f (f x) = x)-> img f (img f l) = l.\n  Proof. { intro H.\n         assert (H1: Equal (img f (img f l)) l).\n         { unfold Equal. split.\n           { unfold Subset. intros a H1.\n             assert (H2: exists b, In b (img f l) /\\ a = f b); auto.\n             destruct H2 as [b H2]. destruct H2 as [H2a H2b].\n             assert (H3: exists x, In x l /\\ b = f x ); auto.\n             destruct H3 as [x H3]. destruct H3 as [H3a H3b].\n             subst a. subst b. replace (f (f x)) with x. auto. symmetry;auto. }\n           { unfold Subset. intros a H1.\n             assert (H2: In (f a) (img f l)). auto.\n             assert (H2a: In (f (f a)) (img f (img f l))). auto.\n             replace (f (f a)) with a in H2a. auto. symmetry;auto. } } \n         auto. } Qed.\n\n   Lemma img_of_img1 (l: list A)(f: A->A)(Hl: IsOrd l):\n     (forall x, f (f x) = x)-> l= img f (img f l).\n   Proof. intros. symmetry. auto using img_of_img. Qed.\n   \n   Hint Resolve f_is_one_one fx_is_one_one img_of_img img_of_img1: core.   \n\n   (* ---------------------- Isomorphism is commutative ------------------*)\n  Lemma iso_sym1 (G G': @dG A)(f: A-> A): iso_using f G G' -> iso_using f G' G.\n    Proof. { intro H. destruct H as [Ha H]; destruct H as [Hb H].\n           split.\n           { auto. }\n           split.\n           { rewrite Hb;  auto. }\n           { intros; symmetry.\n             replace (edg G' x y) with ( edg G' (f (f x)) (f (f y))).\n             assert (H2: In (f x) G). \n             { rewrite Hb in H0.\n               assert (h1: exists x0, In x0 G /\\ x = f x0). auto.\n               destruct h1 as [x0 h1]. destruct h1 as [h1 h2].\n               subst x. specialize (Ha x0) as Hx0. rewrite Hx0. auto. }\n             assert (H3: In (f y) G).\n              { rewrite Hb in H1.\n               assert (h1: exists y0, In y0 G /\\ y = f y0). auto.\n               destruct h1 as [y0 h1]. destruct h1 as [h1 h2].\n               subst y. specialize (Ha y0) as Hy0. rewrite Hy0. auto. }\n             auto. replace (f (f x)) with x. replace (f (f y)) with y.\n             auto. all: symmetry;auto. } } Qed.\n\n  Lemma iso_elim1 (G G': @dG A)(f: A->A)(x:A): iso_using f G G'-> In x G-> In (f x) G'.\n   Proof. intros H Hx. replace (nodes G') with (img f G). auto. symmetry; apply H. Qed.  \n\n  Lemma iso_elim2 (G G': @dG A)(f: A->A)(x:A): iso_using f G G'-> In x G'-> In (f x) G.\n  Proof. intros H Hx. replace (nodes G) with (img f G'). auto. symmetry.\n         apply iso_sym1 in H as Ha. apply Ha. Qed.\n   \n  Lemma iso_sym (G G': @dG A): iso G G' -> iso G' G.\n  Proof. { intro H. destruct H as [f H].  exists f. apply iso_sym1. auto. } Qed.\n\n  Lemma iso_using_iso (G G':@dG A)(f: A->A): iso_using f G G' -> iso G G'.\n  Proof. intros h. exists f. auto. Qed.\n\n  Lemma iso_using_iso1 (G G':@dG A)(f: A->A): iso_using f G G' -> iso G' G.\n  Proof. intro h. apply iso_sym. eapply iso_using_iso. eauto. Qed.\n  \n  \n  Hint Immediate iso_sym1 iso_sym iso_elim1 iso_elim2: core.\n\n  Hint Resolve iso_using_iso iso_using_iso1: core.\n\n  \n\n  Lemma iso_one_one1 (G G': @dG A)(f: A-> A): iso_using f G G' -> one_one_on G f.\n  Proof.  intro H; apply fx_is_one_one; apply H. Qed.\n\n  Lemma iso_one_one2 (G G': @dG A)(f: A-> A): iso_using f G G' -> one_one_on G' f.\n  Proof. intro H; apply fx_is_one_one; apply H. Qed. \n\n  Lemma iso_using_G' (G G': @dG A)(f: A-> A): iso_using f G G' -> nodes G' = (img f G).\n  Proof.  intro H;apply H. Qed.\n\n  Lemma iso_using_G (G G': @dG A)(f: A-> A): iso_using f G G' -> nodes G = (img f G').\n  Proof. intro H0. cut (iso_using f G' G). intro H;apply H. auto. Qed.\n\n  Lemma iso_one_one (G G': @dG A)(f: A-> A)(l: list A):\n    iso_using f G G'-> one_one_on l f.\n  Proof. intro H; apply fx_is_one_one; apply H. Qed.\n\n  Lemma iso_f_one_one (G G': @dG A)(f: A-> A): iso_using f G G'-> one_one f.\n    Proof. intro H; apply f_is_one_one; apply H. Qed.\n  \n  \n    Hint Immediate iso_one_one1 iso_one_one2 iso_one_one iso_f_one_one\n         iso_using_G iso_using_G': core.\n\n  Lemma iso_cardinal (G G': @dG A)(f: A-> A): iso_using f G G' -> |G|=|G'|.\n  Proof. { intro H.  apply iso_one_one1 in H as H1.\n           replace (nodes G') with (img f G). auto. \n           symmetry; auto using iso_using_G'. } Qed.\n  Lemma iso_sub_cardinal (G G': @dG A)(X: list A)(f: A->A):\n    iso_using f G G' -> NoDup X -> |X|= | img f X |.\n  Proof. { intros H H0.\n         assert (H2: one_one_on G f). eauto.\n         assert (H2a: one_one_on X f). eauto. auto. } Qed.\n\n  Lemma iso_edg1  (G G': @dG A)(f: A-> A)(x y:A): iso_using f G G' -> In x G -> In y G->\n                                                (edg G x y = edg G' (f x) (f y)).\n  Proof. intro H;apply H. Qed.\n\n  Lemma iso_edg2  (G G': @dG A)(f: A-> A)(x y: A): iso_using f G G' -> In x G'-> In y G'->\n                                                (edg G' x y = edg G (f x) (f y)).\n  Proof. intro H0. cut (iso_using f G' G). intro H;apply H. auto. Qed.\n\n  \n\n  Hint Immediate iso_cardinal iso_sub_cardinal iso_edg1 iso_edg2: core.\n\n  Lemma iso_edg3(G G': @dG A)(f: A-> A)(x y:A): iso_using f G G' -> In x G -> In y G->\n                                                edg G x y -> edg G' (f x) (f y).\n  Proof.  intros; replace (edg G' (f x) (f y)) with (edg G x y); auto.  Qed.\n\n  Lemma iso_edg4  (G G': @dG A)(f: A-> A)(x y: A): iso_using f G G' -> In x G -> In y G-> \n                                                ~ edg G x y -> ~ edg G' (f x) (f y).\n  Proof. intros ; replace (edg G' (f x) (f y)) with (edg G x y); auto. Qed.\n\n  Hint Immediate iso_edg3 iso_edg4: core.\n\n\n  (* ------------- Isomorphism preserves Cliques and Cliq_num for a graph-----------------*)\n  \n  Lemma iso_cliq (G G': @dG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> K [<=] G-> Cliq G K -> Cliq G' (img f K).\n  Proof. {  unfold Cliq. intros H H1 h1.  intros x y Hx Hy.\n          assert (H2: exists x0, In x0 K /\\ x = f x0). auto.\n          destruct H2 as [x0 H2]. destruct H2 as [H2a H2b].\n          assert (H3: exists y0, In y0 K /\\ y = f y0). auto.\n          destruct H3 as [y0 H3]. destruct H3 as [H3a H3b].\n          replace x with (f x0). replace y with (f y0).\n          assert (H2:  x0 = y0 \\/ edg G x0 y0). auto.\n          destruct H2.\n          { left. subst x0. auto. }\n          { right. replace (edg G' (f x0) (f y0)) with (edg G x0 y0).\n            auto. apply H. all: auto. }  }  Qed.\n  \n   Lemma iso_cliq1 (G G': @dG A)(K: list A): iso G G' -> K [<=] G -> Cliq G K -> NoDup K ->\n                                           (exists K', Cliq G' K' /\\ |K|=|K'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H].\n         exists (img f K). split. eauto using iso_cliq.\n         assert (H3: one_one_on K f). eauto.\n         auto. } Qed.\n\n  Lemma iso_cliq_in (G G': @dG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> Cliq_in G K -> Cliq_in G' (img f K).\n  Proof. { intros H H1.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c].\n         split.\n         { destruct H as [Ha H]. destruct H as [Hb Hc]. rewrite Hb; auto. }\n         split.\n         { auto. }\n         { eauto using iso_cliq. }  } Qed.\n\n  Lemma iso_cliq_in1 (G G': @dG A)(K: list A): iso G G' -> Cliq_in G K ->\n                                              (exists K', Cliq_in G' K' /\\ |K|=|K'|).\n  Proof. { intros H H1. destruct H as [f H].\n         exists (img f K). split. eauto using iso_cliq_in.\n         assert (H3: one_one_on K f). eauto.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c]. auto. } Qed.\n\n  Hint Immediate iso_cliq iso_cliq1 iso_cliq_in iso_cliq_in1: core.\n\n  Lemma max_K_in_G' (G G': @dG A)(f: A-> A)(K: list A):\n    iso_using f G G' -> Max_K_in G K -> Max_K_in G' (img f K). \n  Proof. { intros H H1. assert (H0: iso_using f G' G); auto.\n         apply  Max_K_in_intro.         \n         { cut (Cliq_in G K); eauto. }\n         { intros Y H2.\n           replace (|Y|) with (|img f Y|).\n           replace (|img f K|) with (|K|).\n            assert (H3: Cliq_in G (img f Y)). eauto.\n           eauto using Max_K_in_elim. eapply iso_sub_cardinal;eauto.\n           symmetry. eapply iso_sub_cardinal; eauto. } } Qed.\n\n  Lemma cliq_num_G' (G G': @dG A)(n: nat):\n    iso G G' -> cliq_num G n -> cliq_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [K H1].\n         destruct H1 as [H1 H1b]. exists (img f K).\n         split. eauto using max_K_in_G'. replace n with (|K|).\n         symmetry. eapply iso_sub_cardinal;eauto. } Qed.\n  \n  Hint Immediate max_K_in_G' cliq_num_G': core.       \n\n\n  (*---------- Isomorphism preserves Stable set and i_num ----------------------------*)\n\n   Lemma iso_stable (G G': @dG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> I [<=] G-> Stable G I -> Stable G' (img f I).\n  Proof. {  unfold Stable. intros H h1 H1.  intros x y Hx Hy.\n          assert (H2: exists x0, In x0 I /\\ x = f x0). auto.\n          destruct H2 as [x0 H2]. destruct H2 as [H2a H2b].\n          assert (H3: exists y0, In y0 I /\\ y = f y0). auto.\n          destruct H3 as [y0 H3]. destruct H3 as [H3a H3b].\n          replace x with (f x0). replace y with (f y0).\n          assert (H2: edg G x0 y0 = false). auto. \n          replace (edg G' (f x0) (f y0)) with (edg G x0 y0).\n            auto. apply H. all: auto. } Qed.\n  \n   Lemma iso_stable1 (G G': @dG A)(I: list A): iso G G' -> I [<=] G-> Stable G I -> NoDup I ->\n                                           (exists I', Stable G' I' /\\ |I|=|I'|).\n  Proof. { intros H h1 H1 H2. destruct H as [f H].\n         exists (img f I). split. eauto using iso_stable.\n         assert (H3: one_one_on I f). eauto.\n         auto. } Qed.\n\n  Lemma iso_stable_in (G G': @dG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> Stable_in G I -> Stable_in G' (img f I).\n  Proof. { intros H H1.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c].\n         split.\n         { destruct H as [Ha H]. destruct H as [Hb Hc]. rewrite Hb; auto. }\n         split.\n         { auto. }\n         { eauto using iso_stable. }  } Qed.\n\n  Lemma iso_stable_in1 (G G': @dG A)(I: list A): iso G G' -> Stable_in G I ->\n                                              (exists I', Stable_in G' I' /\\ |I|=|I'|).\n  Proof. { intros H H1. destruct H as [f H].\n         exists (img f I). split. eauto using iso_stable_in.\n         assert (H3: one_one_on I f). eauto.\n         destruct H1 as [H1a H1]. destruct H1 as [H1b H1c]. auto. } Qed.\n\n  Hint Immediate iso_stable iso_stable1 iso_stable_in iso_stable_in1: core.\n\n  Lemma max_I_in_G' (G G': @dG A)(f: A-> A)(I: list A):\n    iso_using f G G' -> Max_I_in G I -> Max_I_in G' (img f I).\n  Proof. { intros H H1. assert (H0: iso_using f G' G); auto.\n         apply  Max_I_in_intro.         \n         { cut (Stable_in G I); eauto. }\n         { intros Y H2.\n           replace (|Y|) with (|img f Y|).\n           replace (|img f I|) with (|I|).\n           assert (H3: Stable_in G (img f Y)). eauto.\n           eauto using Max_I_in_elim. eapply iso_sub_cardinal;eauto.\n           symmetry. eapply iso_sub_cardinal; eauto. } } Qed.\n\n  Lemma i_num_G' (G G': @dG A)(n: nat):\n    iso G G' -> i_num G n -> i_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [I H1].\n         destruct H1 as [H1 H1b]. exists (img f I).\n         split. eauto using max_I_in_G'. replace n with (|I|).\n         symmetry. eapply iso_sub_cardinal;eauto. } Qed.\n  \n  Hint Immediate max_I_in_G' i_num_G': core.\n\n  (*----------- Isomorphism , graph coloring and chromatic number-------------------------*)\n  \n  \n  Lemma iso_coloring (G G': @dG A)(f: A->A)(C: A->nat):\n    iso_using f G G' -> Coloring_of G C -> Coloring_of G' (fun (x:A) => C (f x)).\n  Proof. { intros H H1. assert (Ha: iso_using f G' G);auto. unfold Coloring_of.\n           intros x y Hx Hy H2. assert (H3: edg G (f x) (f y)). eauto. apply H1; eauto. } Qed.\n          \n  Lemma iso_same_clrs (G G': @dG A)(f: A->A)(C: A->nat):\n    iso_using f G G' -> Coloring_of G C -> (clrs_of C G) = clrs_of (fun (x:A) => C (f x)) G'.\n  Proof. { intros H H1. assert (Ha: iso_using f G' G). auto.\n         assert (H2: (nodes G) = img f G'). auto. unfold clrs_of; rewrite H2; auto. } Qed.\n\n  Lemma best_coloring_of_G' (G G': @dG A)(f: A-> A)(C: A->nat):\n    iso_using f G G' -> Best_coloring_of G C -> Best_coloring_of G' (fun (x:A) => C (f x)).\n  Proof. { unfold Best_coloring_of. intros H H1.\n         assert (H0: iso_using f G' G). auto.\n         destruct H1 as [H1 H2].\n         split. { eauto using iso_coloring. }\n                { intros C' H3.\n                  assert (H4: (clrs_of C G) = clrs_of (fun (x:A) => C (f x)) G').\n                  auto using iso_same_clrs. rewrite <- H4.\n                  assert (H5: (clrs_of C' G') = clrs_of (fun (x:A) => C' (f x)) G).\n                  auto using iso_same_clrs. rewrite H5.\n                  apply H2. eauto using iso_coloring. } } Qed. \n                  \n  Lemma chrom_num_G' (G G': @dG A)(n:nat):\n    iso G G' -> chrom_num G n -> chrom_num G' n.\n  Proof. { intros H H1. destruct H as [f H]. destruct H1 as [C H1].\n         destruct H1 as [H1 H2].\n         exists (fun (x:A) => C (f x)). split. eauto using best_coloring_of_G'.\n         subst n. replace (clrs_of (fun x : A => C (f x)) G') with (clrs_of C G).\n         auto. destruct H1 as [H1 H2]. auto using iso_same_clrs. } Qed.\n\n  Hint Resolve iso_coloring iso_same_clrs best_coloring_of_G': core.\n  Hint Immediate chrom_num_G': core.\n\n\n  (*------------Isomorphism , nice graphs and perfect graph--------------------------------*)\n\n  Lemma nice_G' (G G': @dG A): iso G G' -> Nice G -> Nice G'.\n  Proof. { intro H.  assert (H0: iso G' G). auto.\n         unfold Nice. intros H1 n H2.\n         cut (chrom_num G n). eauto. cut (cliq_num G n); eauto. } Qed.\n\n  Lemma iso_subgraphs (G G' H: @dG A)(f: A->A):\n    iso_using f G G' -> Ind_subgraph H G -> (exists H', Ind_subgraph H' G' /\\ iso_using f H H').\n  Proof.  { intros F1 F2.\n            assert (F0: iso_using f G' G). auto. \n            assert (Nk: IsOrd (img f H)). auto.\n            pose H' := (Ind_at (img f H) G').\n            exists H'.\n            assert (h0: H' [<=] G').\n            { replace (nodes G') with (img f G). simpl.\n              cut (img f H [<=] img f G). auto. \n              eapply img_subset. apply F2. symmetry. auto. }\n            assert (h1: img f H [<=] G').\n            { replace (nodes G') with (img f G).\n                cut (H [<=] G). auto. apply F2.  symmetry.\n                assert(F3: iso_using f G G'). auto. apply F3. }\n            assert (h2: img f H = inter (img f H) G').\n            { apply set_equal; auto. }\n            split.\n            (* Ind_subgraph H' G' *)\n            {  unfold Ind_subgraph. split.\n               { auto. }\n               { unfold H'. simpl. intros. symmetry. auto. } }\n           \n            {  (* iso_using f H H' *)\n              unfold iso_using.\n              split.\n              { apply F1. }\n              split.\n              { simpl. symmetry. auto.  }\n              { (* forall x y : A, edg H x y = edg (Ind_at Nk G') (f x) (f y) *)\n                simpl. intros x y Hx Hy.\n                replace (edg H x y) with (edg G x y).\n                cut (In y G). cut (In x G). auto.\n                apply F2; auto. apply F2; auto. symmetry; auto. } } } Qed.\n            \n  Lemma perfect_G' (G G': @dG A): iso G G' -> Perfect G -> Perfect G'.\n  Proof. { intro F.  assert (F0: iso G' G). auto.\n         unfold Perfect. destruct F0 as [f F0].\n         intros F1 H' F2.\n         assert (F3: exists H, Ind_subgraph H G /\\ iso_using f H' H).\n         { eapply iso_subgraphs. apply F0. auto. }\n         destruct F3 as [H F3]. destruct F3 as [F3 F4]. \n         cut (Nice H).\n         { cut (iso H H'). eauto using nice_G'.\n           exists f. cut (iso_using f H H'); auto. } auto.  } Qed.\n\n  Hint Immediate nice_G' induced_fact1 iso_subgraphs perfect_G': core.\n\nEnd GraphIsomorphism.\n\n\nHint Resolve f_is_one_one fx_is_one_one img_of_img img_of_img1: core.\n\nHint Immediate iso_sym1 iso_sym iso_elim1 iso_elim2: core.\n Hint Resolve iso_using_iso iso_using_iso1: core.\nHint Immediate iso_one_one1 iso_one_one2: core.\nHint Immediate iso_one_one iso_f_one_one iso_using_G iso_using_G': core.\n\nHint Immediate iso_cardinal iso_sub_cardinal iso_edg1 iso_edg2: core.\nHint Immediate iso_edg3 iso_edg4: core.\n\nHint Immediate iso_cliq iso_cliq1 iso_cliq_in iso_cliq_in1: core.\nHint Immediate max_K_in_G' cliq_num_G': core.\n\nHint Immediate iso_stable iso_stable1 iso_stable_in iso_stable_in1: core.\nHint Immediate max_I_in_G' i_num_G': core.\n\nHint Resolve iso_coloring iso_same_clrs best_coloring_of_G': core.\nHint Immediate chrom_num_G': core.\n\nHint Immediate nice_G' iso_subgraphs perfect_G': core.\n\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/IsoDecUG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7909604790625896}}
{"text": "Require Import Arith.\nRequire Import List.\n\nDefinition iota (n:nat) : list nat :=\n  (fix f (p:nat)(l:(list nat)){struct p}:list nat :=\n       match p with\n       | 0 => l \n       | S q => f q ((S q)::l) \n       end) \n   n nil.\n\n\n\n(** Test:\nCompute  (iota 7).\n\n= 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil\n     : list nat\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/iota.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7909076054055049}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nFrom PolyAI Require Export TotalMap ssrZ ssrstring Tactic.\nRequire Export Coq.Sets.Ensembles.\nRequire Export Coq.ZArith.BinInt.\n\nRequire Import String.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\n\n(* An affine function *)\n\nInductive Aff :=\n| AConst (c: Z)\n| AVar (v: string)\n| APlus (a1 a2: Aff)\n| AMinus (a1 a2: Aff)\n| AMul (c: Z) (a: Aff).\n\n(* Check if a variable is used in an affine function *)\n\nFixpoint used_in_aff (a: Aff) (v: string) :=\n  match a with\n  | AConst _ => true\n  | AVar v' => (v == v')\n  | APlus a1 a2 => used_in_aff a1 v || used_in_aff a2 v\n  | AMinus a1 a2 => used_in_aff a1 v || used_in_aff a2 v\n  | AMul c a' => used_in_aff a' v\n  end.\n\n(* Evaluate an affine function given values for each variable *)\n\nFixpoint eval_aff (a: Aff) (m: string -> Z) :=\n  match a with\n  | AConst c => c\n  | AVar v => m v\n  | APlus a1 a2 => (eval_aff a1 m) + (eval_aff a2 m)\n  | AMinus a1 a2 => (eval_aff a1 m) - (eval_aff a2 m)\n  | AMul c a => c * (eval_aff a m)\n  end.\n\n(* Implementation of a Presburger set / pw_aff library *)\n\nClass PresburgerImpl (PMap PSet PwAff: eqType) :=\n  {\n    eval_pset : PSet -> (string -> Z) -> bool;\n\n    empty_set : PSet;\n    empty_set_spec : forall x, ~~(eval_pset empty_set x);\n\n    universe_set : PSet;\n    universe_set_spec : forall x, eval_pset universe_set x;\n\n    union_set : PSet -> PSet -> PSet;\n    union_set_spec : forall p1 p2 x,\n        eval_pset (union_set p1 p2) x = eval_pset p1 x || eval_pset p2 x;\n\n    intersect_set : PSet -> PSet -> PSet;\n    intersect_set_spec : forall p1 p2 x,\n        eval_pset (intersect_set p1 p2) x = eval_pset p1 x && eval_pset p2 x;\n\n    subtract_set : PSet -> PSet -> PSet;\n    subtract_set_spec : forall p1 p2 x,\n        eval_pset (subtract_set p1 p2) x = eval_pset p1 x && ~~ (eval_pset p2 x);\n\n    is_subset : PSet -> PSet -> bool;\n    is_subset_spec : forall p1 p2, is_subset p1 p2 <->\n                              forall x, eval_pset p1 x -> eval_pset p2 x;\n\n    set_project_out : PSet -> string -> PSet;\n    set_project_out_spec : forall p d (m: total_map), eval_pset (set_project_out p d) m <->\n                                    exists v, eval_pset p (d !-> v; m);\n\n    eval_pmap : PMap -> (string -> Z) -> (string -> Z) -> bool;\n\n    empty_map : PMap;\n    empty_map_spec : forall x y, ~~(eval_pmap empty_map x y);\n\n    universe_map : PMap;\n    universe_map_spec : forall x y, eval_pmap universe_map x y;\n\n    id_map : PMap;\n    id_map_spec : forall (x y: total_map), eval_pmap id_map x y = (x == y);\n\n    union_map : PMap -> PMap -> PMap;\n    union_map_spec : forall p1 p2 x y,\n        eval_pmap (union_map p1 p2) x y = eval_pmap p1 x y || eval_pmap p2 x y;\n\n    intersect_map : PMap -> PMap -> PMap;\n    intersect_map_spec : forall p1 p2 x y,\n        eval_pmap (intersect_map p1 p2) x y = eval_pmap p1 x y && eval_pmap p2 x y;\n\n    is_subset_map : PMap -> PMap -> bool;\n    is_subset_map_spec : forall p1 p2, is_subset_map p1 p2 <->\n                                  forall (x y: total_map), eval_pmap p1 x y -> eval_pmap p2 x y;\n\n    map_project_out_in : PMap -> string -> PMap;\n    map_project_out_in_spec : forall p d (m_in: total_map) m_out, eval_pmap (map_project_out_in p d) m_in m_out <->\n                                                             exists v, eval_pmap p (d !-> v; m_in) m_out;\n\n    map_project_out_out : PMap -> string -> PMap;\n    map_project_out_out_spec : forall p d m_in (m_out: total_map), eval_pmap (map_project_out_out p d) m_in m_out <->\n                                                              exists v, eval_pmap p m_in (d !-> v; m_out);\n\n    map_apply_range : PMap -> PMap -> PMap;\n    map_apply_range_spec : forall a1 a2 m_in m_out, eval_pmap (map_apply_range a1 a2) m_in m_out <-> exists (m_mid: total_map), eval_pmap a1 m_in m_mid /\\ eval_pmap a2 m_mid m_out;\n\n    map_apply_range_bot : forall a, map_apply_range a empty_map = empty_map;\n\n    transitive_closure_map : PMap -> PMap;\n    transitive_closure_map_ge_step : forall a, is_subset_map a (transitive_closure_map a);\n    transitive_closure_map_ge_id : forall a, is_subset_map id_map (transitive_closure_map a);\n    transitive_closure_map_eq_compose : forall a, is_subset_map (map_apply_range (transitive_closure_map a) a) (transitive_closure_map a);\n\n    eval_pw_aff : PwAff -> (string -> Z) -> option Z;\n\n    pw_aff_from_aff : Aff -> PwAff;\n    pw_aff_from_aff_spec : forall a x, eval_pw_aff (pw_aff_from_aff a) x = Some (eval_aff a x);\n\n    empty_pw_aff : PwAff;\n    empty_pw_aff_spec : forall x, eval_pw_aff empty_pw_aff x = None;\n\n    intersect_domain : PwAff -> PSet -> PwAff;\n    intersect_domain_spec : forall p s x, eval_pw_aff (intersect_domain p s) x =\n                                     if eval_pset s x then\n                                       eval_pw_aff p x\n                                     else\n                                       None;\n\n    union_pw_aff : PwAff -> PwAff -> PwAff;\n    union_pw_aff_spec : forall p1 p2 x, eval_pw_aff (union_pw_aff p1 p2) x =\n                                   match eval_pw_aff p1 x with\n                                   | None => eval_pw_aff p2 x\n                                   | r => r\n                                   end;\n\n    add_pw_aff : PwAff -> PwAff -> PwAff;\n    add_pw_aff_spec : forall p1 p2 x, eval_pw_aff (add_pw_aff p1 p2) x =\n                                 match (eval_pw_aff p1 x, eval_pw_aff p2 x) with\n                                 | (Some v1, Some v2) => Some (v1 + v2)\n                                 | _ => None\n                                 end;\n\n    eq_set : PwAff -> PwAff -> PSet;\n    eq_set_spec : forall p1 p2 x, eval_pset (eq_set p1 p2) x =\n                                          match (eval_pw_aff p1 x, eval_pw_aff p2 x) with\n                                          | (Some v1, Some v2) => v1 == v2\n                                          | _ => false\n                                          end;\n\n    ne_set : PwAff -> PwAff -> PSet;\n    ne_set_spec : forall p1 p2 x, eval_pset (ne_set p1 p2) x =\n                                          match (eval_pw_aff p1 x, eval_pw_aff p2 x) with\n                                          | (Some v1, Some v2) => (v1 != v2)\n                                          | _ => false\n                                          end;\n\n    le_set : PwAff -> PwAff -> PSet;\n    le_set_spec : forall p1 p2 x, eval_pset (le_set p1 p2) x =\n                             match (eval_pw_aff p1 x, eval_pw_aff p2 x) with\n                             | (Some v1, Some v2) => v1 <=? v2\n                             | _ => false\n                             end;\n\n    indicator_function : PSet -> PwAff;\n    indicator_function_spec : forall s x, eval_pw_aff (indicator_function s) x =\n                                     if eval_pset s x then\n                                       Some 1\n                                     else\n                                       Some 0;\n\n    eq_map : PwAff -> PwAff -> PwAff -> PwAff -> PMap;\n    eq_map_spec : forall p1 p2 p1' p2' x y, eval_pmap (eq_map p1 p2 p1' p2') x y =\n                                       match (eval_pw_aff p1 x, eval_pw_aff p2 y, eval_pw_aff p1' x, eval_pw_aff p2' y) with\n                                       | (Some v1, Some v2, Some v1', Some v2') => v1 + v2 == v1' + v2'\n                                       | _ => false\n                                       end;\n\n    ne_map : PwAff -> PwAff -> PwAff -> PwAff -> PMap;\n    ne_map_spec : forall p1 p2 p1' p2' x y, eval_pmap (ne_map p1 p2 p1' p2') x y =\n                                       match (eval_pw_aff p1 x, eval_pw_aff p2 y, eval_pw_aff p1' x, eval_pw_aff p2' y) with\n                                       | (Some v1, Some v2, Some v1', Some v2') => v1 + v2 != v1' + v2'\n                                       | _ => false\n                                       end;\n\n    pw_aff_involves_dim : PwAff -> string -> bool;\n    pw_aff_involves_dim_spec :\n      forall p s, pw_aff_involves_dim p s <-> forall (x: total_map) v, eval_pw_aff p x = eval_pw_aff p (s !-> v ; x);\n\n    get_involved_dim : PwAff -> seq string;\n    get_involved_dim_spec :\n      forall p s, s \\in get_involved_dim p = pw_aff_involves_dim p s;\n\n    pullback_dims : PwAff -> seq (string * PwAff) -> PwAff;\n    pullback_dims_spec :\n      forall p l (x: total_map),\n        let l_option_Z := [seq (v.1, eval_pw_aff v.2 x) | v <- l] in\n        eval_pw_aff (pullback_dims p l) x =\n        if all (fun x => x.2 != None) l_option_Z then\n          let l_Z := [seq (v.1, if v.2 is Some z then z else 0) | v <- l_option_Z] in\n          eval_pw_aff p (t_update_multiple x l_Z)\n        else\n          None;\n  }.\n\nSection PresburgerTheorems.\n\n  Context {PMap PSet PwAff: eqType}\n          {PI: PresburgerImpl PMap PSet PwAff}.\n\n  Theorem empty_set_spec_rw :\n    forall x, eval_pset empty_set x = false.\n  Proof.\n    move => x.\n      by rewrite (negbTE (empty_set_spec _)).\n  Qed.\n\n  Theorem empty_map_spec_rw :\n    forall x y, eval_pmap empty_map x y = false.\n  Proof.\n    move => x y.\n      by rewrite (negbTE (empty_map_spec _ _)).\n  Qed.\n\n  Theorem is_subset_refl :\n    forall p, is_subset p p.\n  Proof.\n    move => p.\n      by apply is_subset_spec.\n  Qed.\n\n  Theorem is_subset_map_refl :\n    forall p, is_subset_map p p.\n  Proof.\n    move => p.\n      by apply is_subset_map_spec.\n  Qed.\n\n  Theorem is_subset_trans :\n    forall p1 p2 p3, is_subset p1 p2 ->\n                is_subset p2 p3 ->\n                is_subset p1 p3.\n  Proof.\n    move => p1 p2 p3.\n    rewrite !is_subset_spec.\n      by auto.\n  Qed.\n\n  Theorem is_subset_map_trans :\n    forall p1 p2 p3, is_subset_map p1 p2 ->\n                is_subset_map p2 p3 ->\n                is_subset_map p1 p3.\n  Proof.\n    move => p1 p2 p3.\n    rewrite !is_subset_map_spec.\n    by auto.\n  Qed.\n\n  Theorem is_subset_union_l :\n    forall p1 p2, is_subset p1 (union_set p1 p2).\n  Proof.\n    move => p1 p2.\n    rewrite is_subset_spec => x Hp1.\n      by rewrite union_set_spec Hp1.\n  Qed.\n\n  Theorem is_subset_union_r :\n    forall p1 p2, is_subset p2 (union_set p1 p2).\n  Proof.\n    move => p1 p2.\n    rewrite is_subset_spec => x Hp2.\n      by rewrite union_set_spec Hp2 orbT.\n  Qed.\n\nEnd PresburgerTheorems.\n\nHint Rewrite @empty_set_spec_rw @universe_set_spec @union_set_spec @intersect_set_spec\n     @subtract_set_spec @map_apply_range_spec\n     @empty_map_spec_rw @universe_map_spec @id_map_spec @union_map_spec @intersect_map_spec\n     @pw_aff_from_aff_spec @intersect_domain_spec @union_pw_aff_spec @eq_set_spec @ne_set_spec @le_set_spec @indicator_function_spec\n     @add_pw_aff_spec\n     @eq_map_spec @ne_map_spec @empty_pw_aff_spec\n  using by first [liassr | autossr ] : prw.\n\nHint Resolve @is_subset_spec @is_subset_map_spec @is_subset_refl @is_subset_map_refl @set_project_out_spec @is_subset_map_spec : core.\n\nLtac simpl_presburger_ := repeat (autorewrite with prw; simpl_map).\nLtac simpl_presburger := reflect_ne_in simpl_presburger_.\n\nLtac auto_presburger := intros ; simpl_presburger; autossr.\n", "meta": {"author": "math-fehr", "repo": "PresburgerAI-Coq", "sha": "ad081f935c3c88aac60464fda7beeaa3deca6f26", "save_path": "github-repos/coq/math-fehr-PresburgerAI-Coq", "path": "github-repos/coq/math-fehr-PresburgerAI-Coq/PresburgerAI-Coq-ad081f935c3c88aac60464fda7beeaa3deca6f26/src/Presburger.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7909075991666731}}
{"text": "(** * Lógica Computacional 1 - 2021-2 *)\n(** ** Equivalência entre o Princípio da Indução Matemática (PIM) e o Princípio da Indução Forte (PIF) *)\n\nRequire Import Arith.\n\n(** Seja [P] uma propriedade sobre os números naturais. O PIM pode ser enunciado da seguinte forma: *)\n\nDefinition PIM :=\n  forall P: nat -> Prop,\n    (P 0) ->\n    (forall n, P n -> P (S n)) ->\n    forall n, P n.\n\n(** Seja [Q] uma propriedade sobre os números naturais. O PIF pode ser enunciado da seguinte forma:  *)\n\nDefinition PIF :=\n  forall Q: nat -> Prop,\n    (forall n, (forall m, m<n -> Q m) -> Q n) ->\n    forall n, Q n.\n\n(** Prove que PIM e PIF são equivalentes, ou seja, prove os lemas e o teorema a seguir: *)\n\nLemma PIF_to_PIM: PIF -> PIM.\nProof.\n(* Substitua esta linha pela sua prova*) Admitted.\n\nLemma PIM_to_PIF: PIM -> PIF.\nProof.\n(* Substitua esta linha pela sua prova*) Admitted.\n\nTheorem PIM_equiv_PIF: PIM <-> PIF.\nProof.\n  (* Substitua esta linha pela sua prova*) Admitted.\n", "meta": {"author": "ensino-unb", "repo": "lc1-2021-2-inicial", "sha": "b29b4e5f70e225945ea6e2dd9908b0603e3a343c", "save_path": "github-repos/coq/ensino-unb-lc1-2021-2-inicial", "path": "github-repos/coq/ensino-unb-lc1-2021-2-inicial/lc1-2021-2-inicial-b29b4e5f70e225945ea6e2dd9908b0603e3a343c/lc1_2021_2_pim_equiv_pif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8962513759047848, "lm_q1q2_score": 0.790877178361871}}
{"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(** ** Binomial theorem *)\n\nRequire Import Arith Omega.\n\nRequire Import utils_tac gcd.\n\nSet Implicit Arguments.\n\nSection factorial.\n\n  Fixpoint fact n := match n with 0 => 1 | S n => (S n) * fact n end.\n\n  Fact fact_0 : fact 0 = 1.\n  Proof. trivial. Qed.\n\n  Fact fact_S n : fact (S n) = (S n)*fact n.\n  Proof. trivial. Qed.\n\n  Fact fact_gt_0 n : 0 < fact n.\n  Proof.\n    unfold lt; simpl.\n    induction n as [ | n IHn ]; simpl; auto.\n    generalize (n*fact n); intros; omega.\n  Qed.\n\nEnd factorial.\n\nSection binomial.\n\n  Infix \"<d\" := divides (at level 70, no associativity).\n\n  Hint Resolve divides_refl.\n\n  Let fact_neq_0 n : fact n <> 0.\n  Proof. generalize (fact_gt_0 n); omega. Qed.\n\n  Fixpoint binomial n p :=\n    match n, p with\n      | n, 0     => 1\n      | 0, S _   => 0\n      | S n, S p => binomial n p + binomial n (S p)\n    end.\n\n  Fact binomial_n0 n : binomial n 0 = 1.\n  Proof. destruct n; auto. Qed.\n\n  Fact binomial_SS n p : binomial (S n) (S p) = binomial n p + binomial n (S p).\n  Proof. auto. Qed.\n\n  Fact binomial_n1 n : 1 <= n -> binomial n 1 = n.\n  Proof.\n    destruct n as [ | n ]; try omega; intros _.\n    induction n as [ | n IHn ]; auto.\n    rewrite binomial_SS, IHn, binomial_n0; omega.\n  Qed.\n\n  Fact binomial_gt n : forall p, n < p -> binomial n p = 0.\n  Proof.\n    induction n as [ | n IHn ]; intros [|] ?; simpl; auto; try omega.\n    do 2 (rewrite IHn; try omega).\n  Qed.\n\n  Fact binomial_nn n : binomial n n = 1.\n  Proof.\n    induction n; auto; rewrite binomial_SS, binomial_gt with (p := S _); omega.\n  Qed.\n\n  Theorem binomial_thm n p : p <= n -> fact n = binomial n p * fact p * fact (n-p).\n  Proof.\n    intros H.\n    replace n with (n-p+p) at 1 2 by omega.\n    generalize (n-p); clear n H; intros n.\n    induction on n p as IH with measure (n+p).\n    revert n p IH; intros [ | n ] [ | p ] IH; simpl plus; auto.\n    + rewrite binomial_nn; simpl; omega.\n    + rewrite Nat.add_0_r, binomial_n0; simpl; omega.\n    + rewrite fact_S, binomial_SS.\n      replace (S (n+S p)) with (S p+S n) by omega.\n      do 3 rewrite Nat.mul_add_distr_r; f_equal.\n      * replace (n+S p) with (S n+p) by omega.\n        rewrite fact_S, IH; try omega; ring.\n      * rewrite (fact_S n), IH; try omega; ring.\n  Qed.\n\n  Fact binomial_le n p : p <= n -> binomial n p = div (fact n) (fact p * fact (n-p)).\n  Proof.\n    intros H.\n    symmetry; apply div_prop with (r := 0).\n    + rewrite binomial_thm with (p := p); auto; ring.\n    + red; change 1 with (1*1); apply mult_le_compat; apply fact_gt_0.\n  Qed.\n\n  Fact binomial_sym n p : p <= n -> binomial n p = binomial n (n-p).\n  Proof.\n    intros H; do 2 (rewrite binomial_le; try omega).\n    rewrite mult_comm; do 3 f_equal; omega.\n  Qed.\n\n  Fact binomial_spec n p : p <= n -> fact n = binomial n p * fact p * fact (n-p).\n  Proof. apply binomial_thm. Qed.\n\n  Fact binomial_0n n : 0 < n -> binomial 0 n = 0.\n  Proof. intros; rewrite binomial_gt; auto; simpl. Qed.\n\n  Theorem binomial_pascal n p : binomial (S n) (S p) = binomial n p + binomial n (S p).\n  Proof. auto. Qed.\n\nEnd binomial.\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/binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7907951539409159}}
{"text": "(* This module defines Tarjan's variant of Ackermann's function,\n   and establishes some of its properties. *)\n\nFrom iris_time.union_find.math Require Import LibNatExtra LibFunOrd\n  LibIter LibRewrite.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Tarjan's definition, formulated in terms of [iter]. *)\n\nDefinition Abase :=\n  fun x => 1 + x.\n\nDefinition Astep :=\n  fun Ak x => iter (1 + x) Ak x.\n\nDefinition A k :=\n  iter k Astep Abase.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Tarjan's characteristic equations are satisfied. *)\n\nLemma Abase_eq:\n  forall x,\n  A 0 x = 1 + x.\nProof using.\n  reflexivity.\nQed.\n\nLemma Astep_eq:\n  forall k x,\n  A (1 + k) x = iter (1 + x) (A k) x.\nProof using.\n  reflexivity.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Closed forms for [A 1] and [A 2], from Cormen et al. *)\n\nLemma A_1_eq:\n  forall x,\n  A 1 x = 2 * x + 1.\nProof using.\n  assert (fact: forall x y, iter x (A 0) y = x + y).\n    induction x; intros; simpl.\n    auto.\n    rewrite IHx. auto.\n  intro x.\n  rewrite Astep_eq.\n  rewrite fact.\n  lia.\nQed.\n\nLemma iter_A_1_eq:\n  forall i x,\n  iter i (A 1) x =\n  2^i * (1 + x) - 1.\nProof using.\n  Opaque plus. (* TEMPORARY ugly *)\n  induction i; simpl; intros.\n  lia.\n  rewrite A_1_eq. rewrite IHi.\n  (* Now for some pain... *)\n  assert (0 < 2^i). { eauto using power_positive. }\n  assert (0 < 1+x). { lia. }\n  generalize dependent (2^i); intro n; intros.\n  generalize dependent (1+x); intro y; intros.\n  assert (0 < n * y). { eauto using mult_positive. }\n  rewrite <- Mult.mult_assoc.\n  generalize dependent (n * y); intros ny; intros.\n  lia. (* phew! *)\n  Transparent plus.\nQed.\n\nLemma A_2_eq:\n  forall x,\n  A 2 x = 2^(1 + x) * (1 + x) - 1.\nProof using.\n  intros. rewrite Astep_eq. eapply iter_A_1_eq.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* Every [A k] is inflationary. That is, [x <= A k x] holds. *)\n\nLocal Notation everywhere :=\n  (fun _ => True).\n\nLocal Notation inflationary_ :=\n  (inflationary everywhere le).\n\nLemma inflationary_Abase:\n  inflationary_ Abase.\nProof using.\n  unfold inflationary, Abase. intros. lia.\nQed.\n\nLemma preserves_inflationary_Astep:\n  preserves inflationary_ Astep.\nProof using.\n  unfold preserves, within, inflationary, Astep. intros.\n  eapply iter_inflationary with (okA := everywhere);\n    unfold preserves, within;\n    eauto using Nat.le_trans.\nQed.\n\nLemma Ak_inflationary:\n  forall k,\n  inflationary_ (A k).\nProof using.\n  intro. unfold A.\n  eapply iter_invariant.\n    eapply inflationary_Abase.\n    eapply preserves_inflationary_Astep.\nQed.\n\nLemma iter_Ak_inflationary:\n  forall n k x,\n  x <= iter n (A k) x.\nProof using.\n  intros.\n  (* Kind of reproving the same thing again... *)\n  eapply iter_inflationary with (okA := everywhere);\n    unfold preserves, within;\n    eauto using Nat.le_trans, Ak_inflationary.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* [Astep] is inflationary. That is, for every inflationary function [Ak],\n   [Ak <= Astep Ak] holds -- this is a pointwise inequality. *)\n\nLemma inflationary_Astep:\n  inflationary inflationary_ (pointwise everywhere le) Astep.\nProof using.\n  unfold inflationary, pointwise, Astep. intros.\n  simpl. rewrite iter_iter_1.\n  eapply iter_inflationary with (okA := everywhere);\n    unfold preserves, within; eauto using Nat.le_trans.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The function [A] is monotonic. (That is, it is monotonic in its first\n   argument [k], and the results, which are functions, are compared using\n   pointwise inequality.) *)\n\nLemma A_monotonic:\n  monotonic le (pointwise everywhere le) A.\nProof using.\n  unfold A.\n  (* We must prove that [iter k Astep Abase] is monotonic with respect to [k].\n     Because the lemma [inflationary_Astep] has an inflation hypothesis, we\n     must carry the information that [A k] is inflationary. This is done by\n    picking an appropriate [okA]. *)\n  eapply iter_monotonic_in_n_specialized with (okA := inflationary_);\n    unfold pointwise; eauto using Nat.le_trans, inflationary_Abase,\n    preserves_inflationary_Astep, inflationary_Astep.\nQed.\n\n(* As a corollary, the function [fun k => A k x] is monotonic. In other\n   words, Ackermann's function is monotonic in its first argument. *)\n\nLemma Akx_monotonic_in_k:\n  forall x,\n  monotonic le le (fun k => A k x).\nProof using.\n  (* Forgetting [x], it suffices to argue that [A] is monotonic. *)\n  intro.\n  eapply monotonic_pointwise_specialize with (okB := everywhere);\n    eauto using A_monotonic.\nQed.\n\nHint Resolve Akx_monotonic_in_k : monotonic typeclass_instances.\n\n(* Example. *)\n\nGoal\n  forall k1 k2 x, k1 <= k2 -> A k1 x <= A k2 x.\nProof using.\n  eauto with monotonic. (* cool *)\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The function [fun x => A k x] is monotonic. In other words, Ackermann's\n   function is monotonic in its second argument. *)\n\nLemma monotonic_Abase:\n  monotonic le le Abase.\nProof using.\n  unfold monotonic, Abase. intros. lia.\nQed.\n\nLemma preserves_monotonic_Astep:\n  forall f,\n  inflationary_ f ->\n  monotonic le le f ->\n  monotonic le le (Astep f).\nProof using.\n  intros. intros x1 x2 ?. unfold Astep.\n  eapply Nat.le_trans; [ | eapply iter_monotonic_in_x; eauto ].\n  eapply iter_monotonic_in_n with (okA := everywhere);\n    unfold preserves, within; eauto using Nat.le_trans.\n  lia.\nQed.\n\nLemma Akx_monotonic_in_x:\n  forall k,\n  monotonic le le (A k).\nProof using.\n  (* Because the lemma [preserves_monotonic_Astep] has an inflation\n     hypothesis, we argue simultaneously that [A k] is inflationary\n     and monotonic. This is a little redundant, but seems acceptable. *)\n  cut (forall k, inflationary_ (A k) /\\ monotonic le le (A k)).\n    { intro h. eapply h. }\n  intro. unfold A.\n  eapply iter_invariant; split; simpl in *;\n  intuition eauto using inflationary_Abase, monotonic_Abase,\n    preserves_inflationary_Astep, preserves_monotonic_Astep.\nQed.\n\nHint Resolve Akx_monotonic_in_x Akx_monotonic_in_k : monotonic typeclass_instances.\n\n(* Example. *)\n\nGoal\n  forall k x1 x2, x1 <= x2 -> A k x1 <= A k x2.\nProof using.\n  eauto with monotonic. (* cool *)\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The power function [pow] can be defined in terms of [iter]. *)\n\nLemma pow_iter:\n  forall x y,\n  x ^ y = iter y (fun a => x * a) 1.\nProof using.\n  induction y; simpl; eauto.\nQed.\n\n(* [2 ^ x <= A 2 x]. *)\n\nLemma A_2_lower_bound:\n  forall x,\n  2 ^ x <= A 2 x.\nProof using.\n  (* Tarjan's course notes claim a strict inequality, but in fact there\n     is equality when [x] is zero. *)\n  intro.\n  rewrite pow_iter.\n  rewrite Astep_eq.\n  rewrite iter_iter_1p.\n  rewrite A_1_eq.\n  (* We are now comparing two applications of [iter]. It suffices to\n     exploit the fact that [iter n f x] is monotonic in [f] and [x]. *)\n  eapply Nat.le_trans; [ eapply iter_monotonic_in_f | eapply iter_monotonic_in_x ].\n    (* from [iter_monotonic_in_f] *)\n    eauto.\n    eauto using Nat.le_trans.\n    split.\n      eauto with monotonic.\n      unfold pointwise. intros. rewrite A_1_eq. lia.\n    (* from [iter_monotonic_in_x] *)\n    eauto with monotonic.\n    lia.\nQed.\n\n(* A slightly more powerful version of the previous lemma. It is not a\n   direct consequence of the previous lemma, because [2 ^ (log2 n)] is\n   in general less than or equal to [n]. *)\n\nLemma A_2_log2_lower_bound:\n  forall n,\n  n <= A 2 (log2 n).\nProof using.\n  (* It is somewhat miraculous that this auxiliary assertion holds. *)\n  assert (forall b n, n <= 2 * iter (log2 n) (A 1) b + 1).\n  { intros. eapply (log2_induction (fun k n => n <= 2 * iter k (A 1) b + 1)). lia. lia.\n    intros. simpl. rewrite A_1_eq. eauto with div2. }\n  intros. rewrite Astep_eq. simpl. rewrite A_1_eq. eauto.\n  (* An alternative proof would consist in using [A_2_eq] together\n     with the fact that [2^(1 + log2 n)] is at least [n + 1]. *)\nQed.\n\n(* [2 ^ (2 ^ ( ... 2)) { x + 1 times } <= A 3 x]. *)\n\nLemma A_3_lower_bound:\n  forall x,\n  iter (1 + x) (fun a => 2 ^ a) 0 <= A 3 x.\nProof using.\n  intro.\n  rewrite Astep_eq.\n  (* We are now comparing two applications of [iter]. It suffices to\n     exploit the fact that [iter n f x] is monotonic in [f] and [x]. *)\n  eapply Nat.le_trans; [ eapply iter_monotonic_in_f | eapply iter_monotonic_in_x ].\n    (* from [iter_monotonic_in_f] *)\n    eauto.\n    eauto using Nat.le_trans.\n    split.\n      eauto with monotonic.\n      unfold pointwise. eauto using A_2_lower_bound.\n    (* from [iter_monotonic_in_x] *)\n    eauto with monotonic.\n    lia.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\nFrom iris_time.union_find.math Require Import Filter.\nFrom iris_time.union_find.math Require Import FilterTowardsInfinity.\n\n(* For every [k], the function [fun x => A k x] tends towards infinity. *)\n\nLemma Akx_tends_to_infinity_along_x:\n  forall k,\n  limit towards_infinity towards_infinity (fun x => A k x).\nProof using.\n  intro.\n  eapply prove_tends_towards_infinity.\n  (* It suffices to exploit the fact that [A k] is inflationary,\n     i.e. [x <= A k x] holds. *)\n  intros. exists y. intros ? h.\n  rewrite h. eapply Ak_inflationary; eauto.\nQed.\n\n(* For every [x] greater than zero, the function [fun k => A k x] tends\n   towards infinity. We prove this via a very weak lower bound, namely\n   [k <= A k x]. *)\n\nLemma Ax_inflationary:\n  forall x,\n  x > 0 ->\n  inflationary_ (fun k => A k x).\nProof using.\n  unfold inflationary.\n  intros x ? k _.\n  induction k; intros; simpl.\n  (* Base. *)\n  lia.\n  (* Step. *)\n  rewrite Astep_eq.\n  (* [1 + x] is at least 2, and [iter] is monotonic in [n]. *)\n  transitivity (iter 2 (A k) x).\n    2: eapply iter_monotonic_in_n_specialized with (okA := everywhere);\n         unfold preserves, within;\n         eauto using Nat.le_trans, Ak_inflationary\n                with lia.\n  (* Unfold [iter], and exploit the induction hypothesis (which is\n     possible because [A k] is monotonic). *)\n  simpl.\n  transitivity (A k k).\n    2: eauto with monotonic.\n  (* Now, [A k k] is at least [A 0 k]. *)\n  transitivity (A 0 k).\n    2: eauto with monotonic lia.\n  (* And [A 0 k] is precisely [1 + k]. *)\n  rewrite Abase_eq at 1.\n  lia.\nQed.\n\nLemma Akx_tends_to_infinity_along_k:\n  forall x,\n  x > 0 ->\n  limit towards_infinity towards_infinity (fun k => A k x).\nProof using.\n  intros.\n  eapply prove_tends_towards_infinity.\n  intros. exists y. intros.\n  rewrite Ax_inflationary by eauto.\n  eauto with monotonic.\nQed.\n\nHint Resolve Akx_tends_to_infinity_along_k : monotonic typeclass_instances.\n  (* exploited in [InverseAckermann.v] *)\n\n(* -------------------------------------------------------------------------- *)\n\n(* Every [A k] is strictly inflationary. That is, [x < A k x] holds. *)\n\nLemma Ak_strictly_inflationary:\n  forall k x,\n  x < A k x.\nProof using.\n  (* [A 0] is strictly inflationary already, and [A k] is no less than\n     [A 0]. The result follows by transitivity. *)\n  intros.\n  assert (x < A 0 x).\n    { rewrite Abase_eq. lia. }\n  assert (A 0 x <= A k x).\n    { eauto with monotonic lia. }\n  lia.\nQed.\n\n(* For every [n] other than zero, [iter n (A k)] is strictly inflationary. *)\n\nLemma iter_Ak_strictly_inflationary:\n  forall n k x,\n  n > 0 ->\n  x < iter n (A k) x.\nProof using.\n  intros. destruct n; [ lia | ]. simpl.\n  assert (x < A k x).\n    { eapply Ak_strictly_inflationary. }\n  assert (A k x <= A k (iter n (A k) x)).\n    { eauto using iter_Ak_inflationary with monotonic. }\n  lia.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The function [fun k => A k x] is strictly monotonic in [k]. *)\n\nLemma Akx_strictly_monotonic_in_k_step:\n  forall k x,\n  x > 0 ->\n  A k x < A (1 + k) x.\nProof using.\n  intros. rewrite Astep_eq. simpl. rewrite iter_iter_1.\n  eauto using iter_Ak_strictly_inflationary.\nQed.\n\nLemma Akx_strictly_monotonic_in_k:\n  forall x,\n  x > 0 ->\n  monotonic lt lt (fun k => A k x).\nProof using.\n  intros. intros k1 k2 ?.\n  assert (A k1 x < A (1 + k1) x).\n    { eauto using Akx_strictly_monotonic_in_k_step. }\n  assert (A (1 + k1) x <= A k2 x).\n    { eauto with monotonic lia. }\n  lia.\nQed.\n\nHint Resolve Akx_strictly_monotonic_in_k : monotonic typeclass_instances.\n\n(* -------------------------------------------------------------------------- *)\n\n(* The orbit of a strictly inflationary function goes to infinity. *)\n\nLemma iter_strictly_inflationary_tends_to_infinity:\n  forall f x,\n  (forall x, x < f x) ->\n  limit towards_infinity towards_infinity (fun i => iter i f x).\nProof using.\n  (* This lemma has nothing to do with Ackermann's function and could\n     be placed in a separate file. *)\n  (* A strictly inflationary function grows by at least one at each\n     iteration, so we can give a linear lower bound for it. This\n     implies that iterating over and over takes us to infinity. *)\n  intros f x hinfl.\n  assert (bound: forall i, x + i <= iter i f x).\n  { intro. eapply iter_indexed_invariant; [ | lia ]. intros j y ?.\n    generalize (hinfl y). lia. }\n  (* Manual proof. *)\n  eapply prove_tends_towards_infinity.\n  intro y. exists y. intros z ?.\n  generalize (bound z). lia.\nQed.\n\n(* The orbit of [A k] out of [x] goes to infinity. *)\n\nLemma iter_i_Akx_tends_to_infinity_along_i:\n  forall k x,\n  limit towards_infinity towards_infinity (fun i => iter i (A k) x).\nProof using.\n  eauto using iter_strictly_inflationary_tends_to_infinity, Ak_strictly_inflationary.\nQed.\n\n(* Iterating [i] times an inflationary function [f] yields a monotonic function\n   of [i]. *)\n\nLemma iter_inflationary_monotonic:\n  forall f x,\n  (forall x, x <= f x) ->\n  monotonic le le (fun i => iter i f x).\nProof using.\n  intros f x hinfl i j ?.\n  replace j with ((j - i) + i) by lia.\n  rewrite iter_iter.\n  generalize (iter i f x). intro y.\n  eapply iter_inflationary with (okA := everywhere);\n    unfold preserves, within, inflationary; eauto using Nat.le_trans.\nQed.\n\n(* [fun i => iter i (A k) x] is monotonic. *)\n\nLemma iter_Ak_monotonic_in_i:\n  forall k x,\n  monotonic le le (fun i => iter i (A k) x).\nProof using.\n  intros.\n  eapply iter_inflationary_monotonic.\n  intro. eapply Ak_inflationary. tauto.\nQed.\n", "meta": {"author": "Ricagraca", "repo": "i-splay-tree", "sha": "263215b780f52dd0168143def37be537bb07e0ea", "save_path": "github-repos/coq/Ricagraca-i-splay-tree", "path": "github-repos/coq/Ricagraca-i-splay-tree/i-splay-tree-263215b780f52dd0168143def37be537bb07e0ea/theories/union_find/math/Ackermann.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7907951440488339}}
{"text": "Require Import Arith.\n\nFixpoint div3 (n:nat): nat :=\n  match n with\n    | 0 | 1 | 2 => 0\n    | S (S (S p)) => S (div3 p)\n  end.\n\nLemma nat_ind3 (P : nat -> Prop) :\n  P 0 -> P 1 -> P 2 ->\n  (forall i:nat, P i -> P (3 + i)) ->\n  forall n:nat, P n.\nProof.\n intros H0 H1 H2 HS n.\n assert (H :P n /\\ P (S n) /\\ P (S (S n))).\n induction n.\n split;auto.\n destruct IHn as [Hn [HSn HSSn]];repeat split;auto.\n - apply HS;auto.\n -  tauto.\nQed.\n\nLemma div3_le : forall n, div3 n <= n.\nProof. \ninduction n using nat_ind3; auto.\n - simpl; apply le_trans with (S n);auto with arith.\nQed.\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch9_function_specification/SRC/div3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.8397339636614178, "lm_q1q2_score": 0.7907389810363833}}
{"text": "Require Import PeanoNat.\nLocal Open Scope nat_scope.\n\nInductive Var := x | y | result.\n\nFixpoint var_eq (v1 v2 : Var) :=\n  match v1, v2 with\n  | x, x => true\n  | y, y => true\n  | result,result =>true\n  | _, _ => false\n  end.\n\nInductive AExp :=\n\n| anum : nat -> AExp\n| avar : Var -> AExp\n| aplus : AExp -> AExp -> AExp\n| amul : AExp -> AExp -> AExp\n| aminus : AExp -> AExp -> AExp\n| adivision : AExp -> AExp -> AExp\n| amodulo : AExp->AExp->AExp.\n\nNotation \"A +' B\" := (aplus A B) (at level 50).\nNotation \"A *' B\" := (amul A B) (at level 46).\nNotation \"A -' B\" := (aminus A B) (at level 50).\nNotation \"A /' B \" := (adivision A B) (at level 45).\nNotation \"A %' B\" := (amodulo A B) (at level 35).\n\nCoercion anum : nat >-> AExp.\nCoercion avar : Var >-> AExp.\n\nDefinition State := Var -> nat.\n(* lookup:  *)\nDefinition sigma0 : State := fun n => 0.\nCheck sigma0.\nCompute (sigma0 x).\nCompute (sigma0 y).\n\n\n(* update *)\nDefinition update (sigma : State)\n           (v : Var) (val : nat) : State :=\n  fun v' => if (var_eq v v')\n            then val\n            else (sigma v').\nDefinition sigma1 := (update sigma0 x 10).\nCompute (sigma1 x).\n\nReserved Notation \"A =[ S ]=> N\" (at level 60).\n\n\nInductive aeval : AExp -> State -> nat -> Prop :=\n| aconst : forall n st, anum n =[ st ]=> n\n| alookup : forall v st, avar v =[ st ]=> (st v)\n| aadd : forall a1 a2 i1 i2 st n,\n    a1 =[ st ]=> i1 ->\n    a2 =[ st ]=> i2 ->\n    n = i1 + i2 ->\n    a1 +' a2 =[ st ]=> n\n| atimes : forall a1 a2 i1 i2 st n,\n    a1 =[ st ]=> i1 ->\n    a2 =[ st ]=> i2 ->\n    n = i1 * i2 ->\n    a1 *' a2 =[ st ]=> n\n| aminusRule : forall a1 a2 i1 i2 st n,\n    a1 =[ st ]=> i1 -> \n    a2 =[ st ]=> i2 -> \n    n = i1 -i2 ->\n    i1 > i2 -> \n    a1 -' a2 =[ st ]=> n\n| adivisionRule : forall a1 a2 i1 i2 st n,\n    a1 =[ st ]=> i1 ->\n    a2 =[ st ]=> i2 ->\n    n = i1 / i2 ->\n    i2 <> 0 -> \n    a1 /' a2 =[ st ]=> n\n| amoduloRule : forall a1 a2 i1 i2 st n,\n    a1 =[ st ]=> i1 ->\n    a2 =[ st ]=> i2 ->\n    i2 <> 0 ->\n    n = i1 mod i2 ->\n    a1 %' a2 =[ st ]=> n\nwhere \"A =[ S ]=> N\" := (aeval A S N).\n\nExample e1 :\n  2 +' x =[ sigma1 ]=> 2 + 10.\nProof.\n  apply aadd with\n      (i1 := 2)(i2 := 10); auto.\n  - apply aconst.\n  - apply alookup.\nQed.\n\n\nExample e2 :\n  2 +' x =[ sigma1 ]=> 12.\nProof.\n  apply aadd with\n      (i1 := 2)(i2 := 10); auto.\n  - apply aconst.\n  - apply alookup.\nQed.\n\nExample e2' :\n  2 +' x =[ sigma1 ]=> 12.\nProof.\n  eapply aadd.\n  - apply aconst.\n  - apply alookup.\n  - auto.\nQed.\n\n(*\nLemma aeval_is_deterministic:\n  forall aexp st n n',\n    aexp =[ st ]=> n ->\n    aexp =[ st ]=> n' ->\n    n = n'.\nProof.\n  induction aexp; intros;\n    inversion H; inversion H0;\n      subst; auto.\n  - assert (IH1: i1 = i0).\n    eapply IHaexp1; eauto.\n    assert (IH2 : i2 = i3).\n    eapply IHaexp2; eauto.\n    subst.\n    reflexivity.\n  - assert (IH1: i1 = i0).\n    eapply IHaexp1; eauto.\n    assert (IH2 : i2 = i3).\n    eapply IHaexp2; eauto.\n    subst.\n    reflexivity.\nQed.\n*)\n\nFixpoint aeval_fun (a : AExp) (sigma : State):=\n  match a with\n  | anum n => n\n  | avar v => sigma v\n  | a1 +' a2 => (aeval_fun a1 sigma) +\n                (aeval_fun a2 sigma)\n  | a1 *' a2 => (aeval_fun a1 sigma) *\n                (aeval_fun a2 sigma)\n  | a1 -' a2 => (aeval_fun a1 sigma) -\n               (aeval_fun a2 sigma)\n  | a1 /' a2 => (aeval_fun a1 sigma) /\n                 (aeval_fun a2 sigma)\n  | a1 %' a2=> (aeval_fun a1 sigma) mod\n                (aeval_fun a2 sigma)\n  end.\n\nCompute (aeval_fun (2 +' 3)).\nCompute (aeval_fun (12/'10)).\nExample e3 :\n  2 +' (4 *' 3) /' 3 =[ sigma1 ]=> 6.\nProof.\n  eapply aadd.\n    -apply aconst.\n    -eapply adivisionRule.\n      +eapply atimes.\n        *apply aconst.\n        *apply aconst.\n        * eauto.\n     +apply aconst.\n      +eauto.\n      +eauto.\n      -eauto.\nQed.\n\nExample e4: \n  2 +' (4 *' x) /' x =[ sigma1 ]=> 6.\n Proof.\n eapply aadd.\n  -apply aconst.\n  -eapply adivisionRule.\n    +eapply atimes.\n      *apply aconst.\n      *eapply alookup.\n      *eauto\n    +eauto.\n    +intros. \n    eapply alookup.\n    \n Qed.\n\n\n(*\nLemma equiv :\n  forall a st,\n    a =[ st ]=> (aeval_fun a st).\nProof.\n  induction a; intros; simpl.\n  - apply aconst.\n  - apply alookup.\n  - eapply aadd; eauto.\n  - eapply atimes; eauto.\nQed.\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/imp(cu inferente).v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.7905515643647287}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #21 : 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. generalize dependent n. induction m. induction n. apply H. apply H1. apply IHn.\n  induction n. apply H0. apply IHm.\n  apply H2. apply IHm.\n\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/P22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8791467627598856, "lm_q1q2_score": 0.7904596481550805}}
{"text": "(* ========================================================================== *]\n SIMPLE PROOFS IN COQ\n[* ========================================================================== *)\nRequire Import Nat List Lia. \n\n(* -------------------------------------------------------------------------- *]\n To specify a property we are trying to prove we use the keyword `Lemma` or\n `Theorem`.\n\n To start writting the proof we use the keyword `Proof` and end it with the\n `Qed` keyword. This opens up the tactics environment.\n[* -------------------------------------------------------------------------- *)\n\n(* \nLemma trivial_things (a : nat) (b : nat) (H0 : a = 1) (H1 : b = 2) :\n    a + b = 3.\nProof.\n    (* But how do we write proofs??? *)\nQed. \n*)\n\n\n(* -------------------------------------------------------------------------- *]\n The tactics language in which we write proofs has a wide array of tools to\n use. We will focus on the essentials so that we can quickly get to more\n interesting examples.\n\n `assumption` \n    We have a hypothesis that matches what we want to prove\n\n `reflexivity` \n    It holds because `=` is reflexive, and our goal is to prove something along the lines of `x = x`\n\n `contradiction` \n    We have a contradiction in our hypotheses (and from that we are able to\n    show anything).\n[* -------------------------------------------------------------------------- *)\n\nLemma assumption_showcase (a : nat) (H0 : a = 1) :\n    a = 1.\nProof.\n    admit.\nQed.\n\nLemma reflexivity_showcase (a : nat) :\n    a = a.\nProof.\n    admit.\nQed.\n\n(* We use a variable `P` for any proposition (like we often do in logic). *)\nLemma contradiction_showcase (P : Prop) (p_holds : P) (p_doesnt_hold : ~P):\n    False. (* Can we prove that `False` is true?! *)\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n The above tactics complete proofs. But we also require tactics that transform\n proofs.\n\n `simpl` \n    simplifies the terms in the goal /\n\n `unfold t`\n    substitutes the term `t` with its definition (useful with functions)\n\n `rewrite H`\n    if hypothesis `H` is of form `x = y` it replaces all occurencess of `x`\n    with `y`\n\n NOTE: All of these tactics can also be used as `rewrite H0 in H1`, which uses\n       the tactic in a hypothesis instead of our goal.\n\n[* -------------------------------------------------------------------------- *)\n\nDefinition double x := x + x.\n\nLemma calculate_this (x y z : nat) (H0 : x = y + z) (H1 : double z = y):\n    x = z + z + z.\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n Since the propositions we are trying to prove are writen in a logic, it is\n necessary to know at least some of the tactics for working with the logic.\n\n LOGIC IN GOALS\n \n `split`\n    Transforms the goal `A /\\ B` into two separate goals for `A` and `B`.\n \n `left / right`\n    Transforms the goal `A \\/ B` into `A` (or `B`) as it suffices to prove\n    one side of an `or` statement.\n\n `intros`\n    Transforms the goal `A -> B -> C -> ... -> P` into `P` but adds `A`, `B`, \n    `C`, ... to the hypotheses.\n `intros name1 name2 ...`\n    You can (and often should) name the new hypotheses.\n\n `revert H`\n    The opposite of `intros` where we take a hypothesis `H` and transform the\n    goal of `A` back to `H -> A`.\n\n LOGIC IN HYPOTHESES\n \n `destruct`\n    For `H : A /\\ B` it separates the hypotheses into two new hypotheses, one \n    for `A` and one for `B`.\n\n    For `H : A \\/ B` it splits the proof into two goals. In the first case\n    you have the hypothesis for `A` and in the second one for `B`.\n\n `apply H`\n   If you have a `H : A -> B` and need to prove `B`, then by applying the\n   implication it suffices to show `A`.\n\n `apply H0 in H1 as H2`\n   For `H0 : A -> B` and `H1 : A` it generates a new hypothesis `H2 : B`.\n   The naming part can be dropped in which case `H1 : A` is replaced with\n   `H1 : B`.\n\n\n Since we now have tactics that also split our goals into multiple goals,\n we can use `+`, '-', or '*' as bullet points to focus each case separately\n (reduces visualclutter).\n \n[* -------------------------------------------------------------------------- *)\n\nLemma example_for_logic (P Q R : Prop):\n    (P \\/ R) /\\ (P \\/ Q) -> ~P -> Q /\\ R.\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n For data types we also have some additional tactics.\n \n `discriminate`\n    One of our hypotheses equates something that cannot be equal (more\n    specifically equates two values that have different constructors, such\n    as `0 = 1` or `nil = 1 :: nil`).\n\n `inversion`\n    For `H : x :: xs = y :: ys` we can use `inversion H` to get `x = y` and\n    `xs = ys`. It also does a rewrite of the equalities in the goal.\n\n `induction x`\n    This tactic makes a case split on all possible ways to construct a value\n    of type `x` and automatically generates induction hypotheses.\n[* -------------------------------------------------------------------------- *)\n\nLemma discriminate_showcase (nonsense : 0 = 1):\n    False.\nProof.\n    admit.\nQed.\n\nLemma inversion_showcase A (x y : A) (xs ys : list A) :\n    (x :: xs = y :: ys) -> xs = ys.\nProof.\n    admit.\nQed.\n\n\nFixpoint length {A : Type} (lst : list A) :=\n    match lst with\n    | nil => 0\n    | x :: xs => 1 + length xs\n    end.\n\nLemma zero_length A (lst : list A) :\n    length lst = 0 -> lst = nil.\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n It is good to see the basic tactics (as we sometimes need them), but to keep\n proofs short Coq provides tactics that help us automate the process.\n\n `auto`\n    Tries to automatically complete the proof. If it cannot it simply leaves\n    everything as is.\n\n `lia` (in older versions `omega`)\n    Solver for numeric proofs. A true lifesaver (see example bellow).\n\n There are plent other usefull ways to help write shorter proofs, but we will\n stick to the basics.\n\n Do not forget you can use `_` to ask Coq to infer things for you.\n[* -------------------------------------------------------------------------- *)\n\nFixpoint sum_nats n :=\n    match n with\n    | 0 => 0\n    | S m => n + sum_nats m\n    end. \n\n(* We multiply since division is not properly defined on naturals. *)\n(* You do not want to write this proof by hand... *)\nLemma sum_of_naturals n:\n    2 * (sum_nats n) = n * (1 + n).\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n PRACTICE: Show that if `P \\/ Q -> R` and `P` hold, we can show that `R` holds.\n Do it without `auto`.\n[* -------------------------------------------------------------------------- *)\n\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/intro_to_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.7904596386611187}}
{"text": "Fixpoint plus' (n m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus' n' m)\n  end.\nCompute plus' 3 2.     (* 5 *)\nCompute plus' 123 2.   (* 125 *)\n\nFixpoint mult' (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => m + (mult' n' m)\n  end.\nCompute mult' 3 2.     (* 6 *)\nCompute mult' 12 3.    (* 36 *)\n\nFixpoint minus' (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O    (* No negative numbers *)\n  | _, O => n\n  | S n', S m' => minus' n' m'\n  end.\nCompute minus' 3 2.    (* 1 *)\nCompute minus' 23 12.  (* 11 *)\nCompute minus' 1 2.    (* 0 because negative numbers not handled *)\n\nCheck plus.\nCheck Nat.add.\nCheck Nat.div.\nPrint Nat.div.\n(*\n#+BEGIN_OUTPUT (Info)\nNat.div = \nfun x y : nat =>\nmatch y with\n| 0 => y\n| S y' => fst (Nat.divmod x y' 0 y')\nend\n     : nat -> nat -> nat\n\nArguments Nat.div (_ _)%nat_scope\n#+END_OUTPUT (Info) *)\nPrint Nat.divmod.\n(*\n#+BEGIN_OUTPUT (Info)\nNat.divmod = \nfix divmod (x y q u : nat) {struct x} : nat * nat :=\n  match x with\n  | 0 => (q, u)\n  | S x' =>\n      match u with\n      | 0 => divmod x' y (S q) y\n      | S u' => divmod x' y q u'\n      end\n  end\n     : nat -> nat -> nat -> nat -> nat * nat\n\nArguments Nat.divmod (_ _ _ _)%nat_scope\n#+END_OUTPUT (Info) *)\nPrint Nat.sub.\n\nFixpoint div' (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | _, O => O\n  | _, _ => S (div' (minus n m) m)\n  end.\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/arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.790444519663702}}
{"text": "Require Export D.\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. split.\n  Case \"->\". intros. destruct H as [x H]. 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", "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/P25.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7904445186564726}}
{"text": "Inductive bool : Type := true : bool | false : bool.\n\n\nDefinition negb (b:bool) :=\nmatch b with \n|true => false \n|false => true   \nend.\n\nDefinition andb (b1:bool) (b2:bool) :=\nmatch b1,b2 with \n|true,true => true \n|_,_ => false\nend.\n\nEval compute in (fun x:bool => negb (andb false x)).\n\nEval compute in (fun x:bool => negb (andb x false)).\n\nParameter T1 T2 : Type.\nParameter t1:T1.\nParameter t2:T2.\n\nDefinition g (b:bool) := \nmatch b return if b then T1 else T2 with \n| true => t1 \n| false => t2 end.\n\nDefinition g2 (b:bool) := \nmatch negb b as b2 return if b2 then T2 else T1 with \n| true => t2 \n| false => t1 end.\n\nLocate and.\n\nInductive even : nat -> Prop :=\n| even0 : even 0\n| evenS n : even n -> even (S (S n)).\n\n\nLemma even_is_double : forall n, even n -> exists m, n=m+m.\nProof.\n\tinduction 1.\n\texists 0.\n\treflexivity.\n\tdestruct IHeven as (m, H0).\n\texists (S m).\n\trewrite H0.\n\tunfold plus.\n\tauto.\nQed.\n\t\n\nLemma even_is_double' n : \n(even n -> exists m, n=m+m) /\\\n(even (S n) -> exists m, S n=m+m).\nProof.\n\t\n \tinduction n; simpl;split;intros.\n\tsplit.\n\tintros.\n\texists 0.\n\t\n\treflexivity.\n\tintro.\n\tinversion H.\n\t\n\tdestruct IHn.\n\tsplit.\n\tdestruct H0.\n\tinversion_clear H.\n\t\n\t\n\t\n\t\n\t\n\t\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/TP3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7903378458067418}}
{"text": "(* week_39b_arithmetic_expressions.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Working version, make sure to download\n   the updated version after class.\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool List unfold_tactic.\n\n(* ********** *)\n\n(* Source syntax: *)\n\nInductive arithmetic_expression : Type :=\n  | Lit : nat -> arithmetic_expression\n  | Plus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n  | Times : arithmetic_expression -> arithmetic_expression -> arithmetic_expression.\n\n(* Exercise 0:\n   Write samples of arithmetic expressions.\n*)\n\nDefinition arth_0 :=\n  Lit 5.\n\nDefinition arth_1 :=\n  Plus (Lit 4) (Lit 2).\n\nDefinition arth_2 :=\n  Plus (Times (Lit 4) (Lit 9)) (Lit 2).\n\n(* ********** *)\n\nDefinition specification_of_interpret (interpret : arithmetic_expression -> nat) :=\n  (forall n : nat,\n     interpret (Lit n) = n)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Plus ae1 ae2) = (interpret ae1) + (interpret ae2))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Times ae1 ae2) = (interpret ae1) * (interpret ae2)).\n\n(* Exercise 1:\n   Write unit tests.\n*)\n\nNotation \"A =n= B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_test_for_arithmetic_expression (interpret : arithmetic_expression -> nat) :=\n  (interpret arth_0 =n= 5)\n  &&\n  (interpret arth_1 =n= 6)\n  &&\n  (interpret arth_2 =n= 38)\n  .\n\n(* Exercise 2:\n   Define an interpreter as a function\n   that satisfies the specification above\n   and verify that it passes the unit tests.\n*)\n\nFixpoint interpret_arithmetic (exp : arithmetic_expression) : nat :=\n  match exp with\n    | Lit n => n\n    | Plus a b => interpret_arithmetic a + interpret_arithmetic b\n    | Times a b => interpret_arithmetic a * interpret_arithmetic b\n  end.\n\nCompute unit_test_for_arithmetic_expression interpret_arithmetic.\n\n(* Byte-code instructions: *)\n\nInductive byte_code_instruction : Type :=\n  | PUSH : nat -> byte_code_instruction\n  | ADD : byte_code_instruction\n  | MUL : byte_code_instruction.\n\n(* ********** *)\n\n(* Byte-code programs: *)\n\nDefinition byte_code_program := list byte_code_instruction.\n\n(* Data stack: *)\n\nDefinition data_stack := list nat.\n\n(* ********** *)\n\n(* Exercise 3:\n   specify a function\n     execute_byte_code_instruction : instr -> data_stack -> data_stack\n   that executes a byte-code instruction, given a data stack\n   and returns this stack after the instruction is executed.\n\n   * Executing (PUSH n) given s has the effect of pushing n on s.\n\n   * Executing ADD given s has the effect of popping two numbers\n     from s and then pushing the result of adding them.\n\n   * Executing MUL given s has the effect of popping two numbers\n     from s and then pushing the result of multiplying them.\n\n   For now, if the stack underflows, just assume it contains zeroes.\n *)\n\nFixpoint f_on_stack (f : nat -> nat -> nat) (l : data_stack) :=\n  match l with\n    | nil => 0 :: nil\n    | a :: y => \n      match y with\n        | nil => (f a 0) :: nil\n        | b :: x => (f a b) :: x\n      end\n  end.\n\nLemma unfold_f_on_stack_zero :\n  (forall f : nat -> nat -> nat,\n  f_on_stack f nil = 0 :: nil).\nProof.\n  unfold_tactic f_on_stack.\nQed.\n\nLemma unfold_f_on_stack_one :\n  (forall (f : nat -> nat -> nat) (n : nat),\n  f_on_stack f (n :: nil) = (f n 0) :: nil).\nProof.\n  unfold_tactic f_on_stack.\nQed.\n\nLemma unfold_f_on_stack_two :\n  (forall (f : nat -> nat -> nat) (x y : nat) (xy : list nat),\n  f_on_stack f (x :: y :: xy) = (f x y) :: xy).\nProof.\n  unfold_tactic f_on_stack.\nQed.\n\nDefinition specification_of_execute_byte_code_instruction\n           (instr : byte_code_instruction -> data_stack -> data_stack) :=\n  (forall (n : nat) (s : data_stack),\n     instr (PUSH n) s = n :: s)\n  /\\\n  (forall (s : data_stack),\n     instr ADD s = (f_on_stack plus s))\n  /\\\n  (forall (s : data_stack),\n     instr MUL s = (f_on_stack mult s))\n.\n\nFixpoint execute_byte_code_instruction (inst : byte_code_instruction) (s : data_stack): data_stack :=\n    match inst with\n      | PUSH n => n :: s\n      | ADD => f_on_stack plus s\n      | MUL => f_on_stack mult s\n  end.\n\nLemma unfold_execute_byte_code_instruction_push :\n  forall (n : nat) (s : data_stack),\n    execute_byte_code_instruction (PUSH n) s = n :: s.\nProof.\n  unfold_tactic execute_byte_code_instruction.\nQed.\n\nLemma unfold_execute_byte_code_instruction_add :\n  forall (s : data_stack),\n    execute_byte_code_instruction ADD s = f_on_stack plus s.\nProof.\n  unfold_tactic execute_byte_code_instruction.\nQed.\n\nLemma unfold_execute_byte_code_instruction_mul :\n  forall (s : data_stack),\n    execute_byte_code_instruction MUL s = f_on_stack mult s.\nProof.\n  unfold_tactic execute_byte_code_instruction.\nQed.\n\nProposition execute_byte_code_instruction_fits_the_specification_of_execute_byte_code_instruction :\n  specification_of_execute_byte_code_instruction execute_byte_code_instruction.\nProof.\n  unfold specification_of_execute_byte_code_instruction.\n  unfold execute_byte_code_instruction.\n  split.\n\n  intros n s.\n  reflexivity.\n\n  split.\n  intro s.\n  reflexivity.\n\n  intro s.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Exercise 4:\n   Define a function\n     execute_byte_code_program : byte_code_program -> data_stack -> data_stack\n   that executes a given byte-code program on a given data stack,\n   and returns this stack after the program is executed.\n*)\n\nFixpoint execute_byte_code_program (prog : byte_code_program) (s : data_stack): data_stack :=\n  match prog with\n    | nil => s\n    | x :: y => (execute_byte_code_program y (execute_byte_code_instruction x s))\n  end.\n\nLemma unfold_execute_byte_code_program_bc :\n  forall (s : data_stack),\n    (execute_byte_code_program nil s) = s.\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\nLemma unfold_execute_byte_code_program_ic :\n  forall (x : byte_code_instruction) (xs : byte_code_program) (s : data_stack),\n    (execute_byte_code_program (x :: xs) s) = (execute_byte_code_program xs (execute_byte_code_instruction x s)).\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\n\n(* ********** *)\n\n(* Exercise 5:\n   Prove that for all programs p1, p2 and data stacks s,\n   executing (p1 ++ p2) with s\n   gives the same result as\n   (1) executing p1 with s, and then\n   (2) executing p2 with the resulting stack.\n*)\n\nLemma unfold_append_bc :\n  forall (bcis : list byte_code_instruction),\n    nil ++ bcis = bcis.\nProof.\n  apply app_nil_l.\nQed.\n\nLemma unfold_append_ic :\n  forall (bci1 : byte_code_instruction) (bci1s' bci2s : list byte_code_instruction),\n    (bci1 :: bci1s') ++ bci2s = bci1 :: (bci1s' ++ bci2s).\nProof.\n  intros bci1 bci1s' bci2s.\n  symmetry.\n  apply app_comm_cons.\nQed.\n\nTheorem append_before_execute_yields_same_result :\n  (forall (p1 p2 : byte_code_program) (s : data_stack),\n     (execute_byte_code_program (p1 ++ p2) s) =\n     (execute_byte_code_program p2 (execute_byte_code_program p1 s))).\nProof.\n  intro p1.\n  induction p1 as [| x xs IHx].\n    intros p2 s.\n    rewrite -> unfold_execute_byte_code_program_bc.\n    rewrite -> app_nil_l.\n    reflexivity.\n  intros p2 s.\n  rewrite -> unfold_append_ic.\n  rewrite -> (unfold_execute_byte_code_program_ic x (xs ++ p2) s).\n  rewrite -> IHx.\n  rewrite -> unfold_execute_byte_code_program_ic.\n  reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_compile (compile : arithmetic_expression -> byte_code_program) :=\n  (forall n : nat,\n     compile (Lit n) = PUSH n :: nil)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Plus ae1 ae2) = (compile ae1) ++ (compile ae2) ++ (ADD :: nil))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Times ae1 ae2) = (compile ae1) ++ (compile ae2)++ (MUL :: nil)).\n\n(* Exercise 6:\n   Define a compiler as a function\n   that satisfies the specification above\n   and uses list concatenation, i.e., ++.\n*)\n\nFixpoint compile_expression_v0 (exp : arithmetic_expression) : byte_code_program :=\n  match exp with\n  | Lit n => PUSH n :: nil\n  | Plus ae1 ae2 => compile_expression_v0 ae1 ++ compile_expression_v0 ae2 ++ ADD :: nil\n  | Times ae1 ae2 => compile_expression_v0 ae1 ++ compile_expression_v0 ae2 ++ MUL :: nil\n  end.\n\nLemma unfold_compile_expression_lit :\n  forall n : nat,\n    compile_expression_v0 (Lit n) = PUSH n :: nil.\nProof.\n  unfold_tactic compile_expression_v0.\nQed.\n\nLemma unfold_compile_expression_plus :\n  forall ae1 ae2 : arithmetic_expression,\n    compile_expression_v0 (Plus ae1 ae2) = compile_expression_v0 ae1 ++ compile_expression_v0 ae2 ++ ADD :: nil.\nProof.\n  unfold_tactic compile_expression_v0.\nQed.\n\nLemma unfold_compile_expression_times :\n  forall ae1 ae2 : arithmetic_expression,\n    compile_expression_v0 (Times ae1 ae2) = compile_expression_v0 ae1 ++ compile_expression_v0 ae2 ++ MUL :: nil.\nProof.\n  unfold_tactic compile_expression_v0.\nQed.\n\n\nProposition compile_expression_v0_fits_the_specification_of_compile :\n  specification_of_compile compile_expression_v0.\nProof.\n  unfold specification_of_compile.\n  split.\n    exact unfold_compile_expression_lit.\n  split.\n    exact unfold_compile_expression_plus.\n  exact unfold_compile_expression_times.\nQed.\n\n(* Exercise 7:\n   Write a compiler as a function with an accumulator\n   that does not use ++ but :: instead,\n   and prove it equivalent to the compiler of Exercise 6.\n*)\n\nFixpoint compile_expression_acc (exp : arithmetic_expression) (prog : byte_code_program) : byte_code_program :=\n  match exp with\n  | Lit n => PUSH n :: prog\n  | Plus ae1 ae2 => (compile_expression_acc ae1 (compile_expression_acc ae2 (ADD :: prog)))  \n  | Times ae1 ae2 => (compile_expression_acc ae1 (compile_expression_acc ae2 (MUL :: prog)))\n  end.\n    \nLemma unfold_compile_expression_acc_lit :\n  forall (n : nat) (prog : byte_code_program),\n    compile_expression_acc (Lit n) prog = PUSH n :: prog.\nProof.\n  unfold_tactic compile_expression_acc.\nQed.\n\nLemma unfold_compile_expression_acc_plus :\n  forall (ae1 ae2 : arithmetic_expression) (prog : byte_code_program),\n    compile_expression_acc (Plus ae1 ae2) prog = (compile_expression_acc ae1 (compile_expression_acc ae2 (ADD :: prog))).\nProof.\n  unfold_tactic compile_expression_acc.\nQed.\n\nLemma unfold_compile_expression_acc_times :\n  forall (ae1 ae2 : arithmetic_expression) (prog : byte_code_program),\n    compile_expression_acc (Times ae1 ae2) prog = (compile_expression_acc ae1 (compile_expression_acc ae2 (MUL :: prog))).\nProof.\n  unfold_tactic compile_expression_acc.\nQed.\n\nDefinition compile_expression_v1 (exp : arithmetic_expression) : byte_code_program :=\n  compile_expression_acc exp nil.\n\nLemma about_compile_expression_acc :\n  forall (exp : arithmetic_expression) (prog : byte_code_program),\n    compile_expression_acc exp prog = compile_expression_acc exp nil ++ prog.\nProof.\n  intros exp.\n  induction exp as [ | exp1' IHexp1' exp2' IHexp2' | exp1'' IHexp1'' exp2'' IHexp2'' ].\n      intro prog.\n      rewrite ->2 unfold_compile_expression_acc_lit.\n      rewrite -> unfold_append_ic.\n      rewrite -> app_nil_l.\n      reflexivity.\n    intro prog.\n    rewrite ->2 unfold_compile_expression_acc_plus.\n    rewrite -> IHexp1'.\n    rewrite -> IHexp2'.\n    rewrite -> (IHexp1' (compile_expression_acc exp2' (ADD :: nil))).\n    rewrite -> (IHexp2' (ADD :: nil)).\n    rewrite -> app_assoc_reverse.\n    rewrite -> app_assoc_reverse.\n    rewrite -> unfold_append_ic.\n    rewrite -> app_nil_l.\n    reflexivity.\n  intro prog.  \n  rewrite ->2 unfold_compile_expression_acc_times.\n  rewrite -> IHexp1''.\n  rewrite -> IHexp2''.\n  rewrite -> (IHexp1'' (compile_expression_acc exp2'' (MUL :: nil))).\n  rewrite -> (IHexp2'' (MUL :: nil)).\n  rewrite -> app_assoc_reverse.\n  rewrite -> app_assoc_reverse.\n  rewrite -> unfold_append_ic.\n  rewrite -> app_nil_l.\n  reflexivity.\nQed.\n\nProposition compile_expression_v1_fits_the_specification_of_compile :\n  specification_of_compile compile_expression_v1.\nProof.\n  unfold specification_of_compile.\n  split.\n    intro n.\n    unfold compile_expression_v1.\n    rewrite -> unfold_compile_expression_acc_lit.\n    reflexivity.\n  split.\n    intros ae1 ae2.\n    unfold compile_expression_v1.\n    rewrite -> unfold_compile_expression_acc_plus.\n    rewrite -> about_compile_expression_acc.\n    rewrite -> (about_compile_expression_acc ae2 (ADD :: nil)).\n    reflexivity.\n  intros ae1 ae2.\n  unfold compile_expression_v1.\n  rewrite -> unfold_compile_expression_acc_times.\n  rewrite -> about_compile_expression_acc.\n  rewrite -> (about_compile_expression_acc ae2 (MUL :: nil)).\n  reflexivity.\nQed.\n\nTheorem there_is_only_one_compile_expression :\n  forall (compiler1 compiler2 : arithmetic_expression -> byte_code_program),\n    specification_of_compile compiler1 ->\n    specification_of_compile compiler2 ->\n    forall (exp : arithmetic_expression),\n      compiler1 exp = compiler2 exp.\nProof.\n  intros compiler1 compiler2.\n  unfold specification_of_compile.\n  intros [H_c1_lit [H_c1_plus H_c1_times]].\n  intros [H_c2_lit [H_c2_plus H_c2_times]].\n  intro exp.\n  induction exp as [ | exp1' IHexp1' exp2' IHexp2' | exp1'' IHexp1'' exp2'' IHexp2'' ].\n      rewrite -> H_c1_lit.\n      rewrite -> H_c2_lit.\n      reflexivity.\n    rewrite -> H_c1_plus.\n    rewrite -> H_c2_plus.\n    rewrite -> IHexp1'.\n    rewrite -> IHexp2'.\n    reflexivity.\n  rewrite -> H_c1_times.\n  rewrite -> H_c2_times.\n  rewrite -> IHexp1''.\n  rewrite -> IHexp2''.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Exercise 8:\n   Prove that interpreting an arithmetic expression gives the same result\n   as first compiling it and then executing the compiled program\n   over an empty data stack.\n*)\n\nDefinition run (prog : byte_code_program) : nat :=\n  match execute_byte_code_program prog nil with\n  | nil => 0\n  | result :: _ => result\n  end.\n\nLemma unfold_interpret_lit :\n  forall n : nat,\n    interpret_arithmetic (Lit n) = n.\nProof.\n  unfold_tactic interpret_arithmetic.\nQed.\n\nLemma unfold_interpret_plus :\n  forall a b : arithmetic_expression,\n    interpret_arithmetic (Plus a b) = interpret_arithmetic a + interpret_arithmetic b.\nProof.\n  unfold_tactic interpret_arithmetic.\nQed.\n\nLemma unfold_interpret_times :\n  forall a b : arithmetic_expression,\n    interpret_arithmetic (Times a b) = interpret_arithmetic a * interpret_arithmetic b.\nProof.\n  unfold_tactic interpret_arithmetic.\nQed.\n\nLemma interpret_cons_datastack_eq_compile_execute :\n  forall (exp : arithmetic_expression) (ds : data_stack),\n    interpret_arithmetic exp :: ds = execute_byte_code_program (compile_expression_v0 exp) ds.\nProof.\n  intro exp.\n  induction exp as [ n | exp1' IHexp1' exp2' IHexp2' | exp1'' IHexp1'' exp2'' IHexp2''].\n      intro ds.\n      rewrite -> unfold_interpret_lit.\n      rewrite -> unfold_compile_expression_lit.\n      rewrite -> unfold_execute_byte_code_program_ic.\n      rewrite -> unfold_execute_byte_code_instruction_push.\n      rewrite -> unfold_execute_byte_code_program_bc.\n      reflexivity.\n    intro ds.\n    rewrite -> unfold_interpret_plus.\n    rewrite -> unfold_compile_expression_plus.\n    rewrite ->2 append_before_execute_yields_same_result.\n    rewrite -> unfold_execute_byte_code_program_ic.\n    rewrite -> unfold_execute_byte_code_instruction_add.\n    rewrite -> unfold_execute_byte_code_program_bc.\n    rewrite <- IHexp1'.\n    rewrite <- IHexp2'.\n    rewrite -> unfold_f_on_stack_two.\n    rewrite -> plus_comm.\n    reflexivity.\n  intro ds.\n  rewrite -> unfold_interpret_times.\n  rewrite -> unfold_compile_expression_times.\n  rewrite ->2 append_before_execute_yields_same_result.\n  rewrite -> unfold_execute_byte_code_program_ic.\n  rewrite -> unfold_execute_byte_code_instruction_mul.\n  rewrite -> unfold_execute_byte_code_program_bc.\n  rewrite <- IHexp1''.\n  rewrite <- IHexp2''.\n  rewrite -> unfold_f_on_stack_two.\n  rewrite -> mult_comm.\n  reflexivity.\nQed.\n\nTheorem interpret_exp_eq_run_compile_exp :\n  forall (exp : arithmetic_expression),\n    interpret_arithmetic exp = run (compile_expression_v0 exp).\nProof.\n  intro exp.\n  unfold run.\n  rewrite <- interpret_cons_datastack_eq_compile_execute.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Exercise 9:\n   Write a Magritte-style execution function for a byte-code program\n   that does not operate on natural numbers but on syntactic representations\n   of natural numbers:\n\n   Definition data_stack := list arithmetic_expression.\n\n   * Executing (PUSH n) given s has the effect of pushing (Lit n) on s.\n\n   * Executing ADD given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their addition.\n\n   * Executing MUL given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their multiplication.\n\n   Again, for this week's exercise,\n   assume there are enough arithmetic expressions on the data stack.\n   If that is not the case, just pad it up with syntactic representations\n   of zero.\n\n*)\n\nDefinition data_stack2 := list arithmetic_expression.\n\nFixpoint magritte_v0 (prog : byte_code_program) (s : data_stack2) :=\n  match prog with\n  | nil => s\n  | (PUSH n) :: prog' => magritte_v0 prog' ((Lit n) :: s)\n  | ADD :: prog' => \n      match s with\n      | nil => magritte_v0 prog' ((Plus (Lit 0) (Lit 0)) :: nil)\n      | exp :: nil => magritte_v0 prog' ((Plus (Lit 0) exp) :: nil)\n      | exp1 :: exp2 :: exps => magritte_v0 prog' ((Plus exp2 exp1) :: exps)\n      end\n  | MUL :: prog' => \n      match s with\n      | nil => magritte_v0 prog' ((Times (Lit 0) (Lit 0)) :: nil)\n      | exp :: nil => magritte_v0 prog' ((Times (Lit 0) exp) :: nil)\n      | exp1 :: exp2 :: exps => magritte_v0 prog' ((Times exp2 exp1) :: exps)\n      end\n  end.\n\nLemma unfold_magritte_v0_nil_prog :\n  forall (s : data_stack2),\n    magritte_v0 nil s = s.\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_push :\n  forall (n : nat) (prog' : byte_code_program) (s : data_stack2),\n    magritte_v0 ((PUSH n) :: prog') s = magritte_v0 prog' ((Lit n) :: s).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_add_nil :\n  forall (prog' : byte_code_program) (s : data_stack2),\n    magritte_v0 (ADD :: prog') nil = magritte_v0 prog' ((Plus (Lit 0) (Lit 0)) :: nil).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_add_1 :\n  forall (prog' : byte_code_program) (exp : arithmetic_expression) (s : data_stack2),\n    magritte_v0 (ADD :: prog') (exp :: nil) = magritte_v0 prog' ((Plus (Lit 0) exp) :: nil).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_add_2 :\n  forall (prog' : byte_code_program) (exp1 exp2 : arithmetic_expression) (s : data_stack2),\n    magritte_v0 (ADD :: prog') (exp1 :: exp2 :: s) = magritte_v0 prog' ((Plus exp2 exp1) :: s).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_mul_nil :\n  forall (prog' : byte_code_program) (s : data_stack2),\n    magritte_v0 (MUL :: prog') nil = magritte_v0 prog' ((Times (Lit 0) (Lit 0)) :: nil).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_mul_1 :\n  forall (prog' : byte_code_program) (exp : arithmetic_expression) (s : data_stack2),\n    magritte_v0 (MUL :: prog') (exp :: nil) = magritte_v0 prog' ((Times (Lit 0) exp) :: nil).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nLemma unfold_magritte_v0_mul_2 :\n  forall (prog' : byte_code_program) (exp1 exp2 : arithmetic_expression) (s : data_stack2),\n    magritte_v0 (MUL :: prog') (exp1 :: exp2 :: s) = magritte_v0 prog' ((Times exp2 exp1) :: s).\nProof.\n  unfold_tactic magritte_v0.\nQed.\n\nDefinition run_magritte (prog : byte_code_program) : arithmetic_expression :=\n  match (magritte_v0 prog nil) with\n  | nil => Lit 0\n  | exp :: _ => exp\n  end.\n\nCompute arth_2.\nCompute compile_expression_v0 arth_2.\nCompute run_magritte (compile_expression_v0 arth_2).\n\n(* Exercise 10:\n   Prove that the Magrite-style execution function from Exercise 9\n   implements a decompiler that is the left inverse of the compiler\n   of Exercise 6.\n*)\n\nLemma append_before_magritte_yields_same_result :\n  forall (p1 p2 : byte_code_program) (s : data_stack2),\n       magritte_v0 (p1 ++ p2) s =\n       magritte_v0 p2 (magritte_v0 p1 s).\nProof.\n  intro p1.\n  induction p1 as [ | x xs' IHxs'].\n    intros p2 s.\n    rewrite -> unfold_magritte_v0_nil_prog.\n    rewrite -> app_nil_l.\n    reflexivity.\n  intros p2 s.\n  Check unfold_append_ic.\n  rewrite -> unfold_append_ic.\n  induction x.\n      rewrite ->2 unfold_magritte_v0_push.\n      rewrite -> IHxs'.\n      reflexivity.\n    induction s.\n    rewrite ->2 unfold_magritte_v0_add_nil.\n    rewrite ->2 unfold_magritte_v0_add_1.\n\nLemma exp_cons_exps_eq_magritte_compile_exp :\n  forall (exp : arithmetic_expression) (s : data_stack2),\n    exp :: s = magritte_v0 (compile_expression_v0 exp) s.\nProof.\n  intro exp.\n  induction exp as [ | exp1' IHexp1' exp2' IHexp2' | exp1'' IHexp1'' exp2'' IHexp2''].\n      intro s.\n      rewrite -> unfold_compile_expression_lit.\n      rewrite -> unfold_magritte_v0_push.\n      rewrite -> unfold_magritte_v0_nil_prog.\n      reflexivity.\n    intro s.\n    rewrite -> unfold_compile_expression_plus.\n    rewrite ->2 append_before_magritte_yields_same_result.\n    rewrite <- IHexp1'.\n    rewrite <- IHexp2'.\n    rewrite -> unfold_magritte_v0_add_2.\n    rewrite -> unfold_magritte_v0_nil_prog.\n    reflexivity.\n  intro s.\n  rewrite -> unfold_compile_expression_times.\n  rewrite ->2 append_before_magritte_yields_same_result.\n  rewrite <- IHexp1''.\n  rewrite <- IHexp2''.\n  rewrite -> unfold_magritte_v0_mul_2.\n  rewrite -> unfold_magritte_v0_nil_prog.\n  reflexivity.\nQed.\n\nTheorem compile_exp_and_run_magritte_gives_exp :\n  forall exp : arithmetic_expression,\n    exp = run_magritte (compile_expression_v0 exp).\nProof.\n  intro exp.\n  unfold run_magritte.\n  rewrite <- exp_cons_exps_eq_magritte_compile_exp.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of week_39b_arithmetic_expressions.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w39/week_39b_arithmetic_expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.7903378405857177}}
{"text": "(* The set of the group. *)\nParameter G : Set.\n\n(* The binary operator. *)\nParameter f : G -> G -> G.\n\n(* The group identity. *)\nParameter e : G.\n\n(* The inverse operator. *)\nParameter i : G -> G.\n\n(* For readability, we use infix <+> to stand for the binary operator. *)\nInfix \"<+>\" := f (at level 50, left associativity).\n\n(* The operator [f] is associative. *)\nAxiom assoc : forall a b c, a <+> b <+> c = a <+> (b <+> c).\n\n(* [e] is the right-identity for all elements [a] *)\nAxiom id_r : forall a, a <+> e = a.\n\n(* [i a] is the right-inverse of [a]. *)\nAxiom inv_r : forall a, a <+> i a = e.\n\n\nLemma mult_both : \n  forall a b c d1 d2, \n    a <+> c = d1\n    -> b <+> c = d2\n    -> a = b\n    -> d1 = d2.\nProof.\n  intros.\n  subst.\n  reflexivity.  \nQed.\n\nHint Extern 100 (_ = _) =>\nmatch goal with\n  | [ _ : True |- _ ] => fail 1\n  | _ => assert True by constructor; eapply mult_both \nend.\n\n\n(* The identity [e] is unique. *)\nTheorem unique_id : forall a, a <+> a = a -> a = e.\nProof.\n  intros.\n  pose proof mult_both a (a <+> a) (i a) e a (inv_r a) as m.\n  symmetry.\n  apply m.\n  rewrite assoc.\n  rewrite inv_r.\n  rewrite id_r.\n  reflexivity.\n  symmetry.\n  assumption.\nQed.\nHint Resolve unique_id.\n\n(* [i a] is the left-inverse of [a]. *)\nTheorem inv_l : forall a, i a <+> a = e.\nProof.\n  intros.\n  pose proof mult_both (i a <+> a) e e (i a <+> a) e as m.\n  apply m.\n  rewrite assoc.\n  rewrite id_r.\n  reflexivity.\n  rewrite id_r.\n  reflexivity.\n  \n(* [e] is the left-identity. *)\nAxiom id_l : forall a, e <+> a = a.\n\n(* [x] can be cancelled on the right. *)\nAxiom cancel_r : forall a b x, a <+> x = b <+> x -> a = b.\n\n(* [x] can be cancelled on the left. *)\nAxiom cancel_l: forall a b x, x <+> a = x <+> b -> a = b.\n\n(* The left identity is unique. *)\nAxiom e_uniq_l : forall a p, p <+> a = a -> p = e.\n\n(* The left inverse is unique. *)\nAxiom inv_uniq_l : forall a b, a <+> b = e -> a = i b.\n\n(* The left identity is unique. *)\nAxiom e_uniq_r : forall a p, a <+> p = a -> p = e.\n\n(* The right inverse is unique. *)\nAxiom inv_uniq_r : forall a b, a <+> b = e -> b = i a.\n\n(* The inverse operator distributes over the group operator. *)\nAxiom inv_distr : forall a b, i (a <+> b) = i b <+> i a.\n\n(* The inverse of an inverse produces the original element. *)\nAxiom double_inv : forall a, i (i a) = a.\n\n(* The identity is its own inverse. *)\nAxiom id_inv : i e = e.\n", "meta": {"author": "ankitku", "repo": "awotap", "sha": "1354a1f0e2f77c0157398553e666b6ff0be6d1ee", "save_path": "github-repos/coq/ankitku-awotap", "path": "github-repos/coq/ankitku-awotap/awotap-1354a1f0e2f77c0157398553e666b6ff0be6d1ee/Groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7903378241302336}}
{"text": "Require Export Induction.\nModule NatList.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n   | (x,y) => x\n  end.\n\nCheck (pair 3 5).\nExample fst_eq_3: fst (pair 3 5) = 3.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n   | (x,y) => y\n  end.\n\nExample snd_eq_5: fst (pair 3 5) = 5.\n\nCompute (fst (pair 3 5)).\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n    | (x,y) => (y,x)\n  end.\n\nExample swap_pair_test: swap_pair (3, 2) = (2, 3).\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. 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 [x y]. 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 [x y]. 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).\n\nNotation \"[ ]\" := nil.\n\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 length (l:natlist) : nat :=\n  match l with\n   | [] => 0\n   | _ :: xs  => 1 + (length xs)\n  end.\n\nExample length_3: length [1; 2; 3] = 3.\nProof. reflexivity. Qed.\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n   | 0 => []\n   | S count' => n :: (repeat n count')\n  end.\n\nFixpoint repeat' (n count : nat) : natlist :=\n  if beq_nat count 5 then []\n  else repeat n count\n  .\n\nExample repeat_42_3: repeat 42 3 = [42; 42; 42].\n  Proof. reflexivity. Qed.\nExample repeat'_42_4: repeat' 42 3 = [42; 42; 42].\n  Proof. reflexivity. Qed.\nExample repeat'_42_5: repeat' 42 5 = [].\n  Proof. reflexivity. Qed.\n\nTheorem repeat_length : forall n : nat,\n    length(repeat 0 n) = n.\nProof.\n  intros n.\n  simpl.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\nFixpoint one_exactly (el : nat) (l : natlist) (ok : bool) : bool :=\n  match l with\n  | [] => ok\n  | n :: xs => if beq_nat n el\n                 then (one_exactly el xs ok)\n                 else (one_exactly el xs false)\n  end.\n\nExample one_exactly1 : one_exactly 10 [10;10;10] true = true.\nProof. reflexivity. Qed.\n\nExample  one_exactly2 := one_exactly 11 [11; 10; 11] true = false.\nProof. reflexivity. Qed.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n  | [] => l2\n  | h :: xs => h :: (app xs l2)\n end.\n\nExample append_ex1: app [1; 2] [3; 4; 5] = [1; 2; 3; 4; 5]. \n\nNotation \"x ++ y\" := (app x y)\n                     (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  | [] => default\n  | h :: _ => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | [] => []\n  | _ :: xs => xs\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  | 0 :: xs => nonzeros xs\n  | h :: xs => h :: nonzeros xs\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n\nInductive natlistprod : Type :=\n  pairl : natlist -> natlist -> natlistprod.\n\nNotation \"( x , y )\" := (pairl x y).\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match (l1, l2) with\n    | (nil, _) => l2\n    | (_, nil) => l1\n    | (h1 :: t1, h2 :: t2) => h1 :: h2 :: alternate t1 t2\n  end.\n\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  Check e bool (b c 0).\nalternate [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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n   | [] => 0\n   | x :: xs => match beq_nat x v with\n                | true =>  1 + (count v xs) \n                | false => count v xs\n                end\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\n   Proof. reflexivity. Qed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\n    Proof. 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. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n v :: s.\n  \n  \nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\n Proof. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\n Proof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match count v s with\n   | 0 => false\n   | _ => true\n  end.\n\nExample test_member1: member 1 [1;4;1] = true.\n Proof. reflexivity. Qed.\n\nExample test_member2: member 2 [1;4;1] = false.\n Proof. reflexivity. Qed.\n\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 :: tl => match (beq_nat h v) with\n                   | true => tl\n                   | false => h :: remove_one v tl\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  match s with\n    | nil => nil\n    | h :: t => match (beq_nat h v) with\n                   | true => remove_all v t\n                   | false => h :: remove_all v t\n                 end\n  end.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2:          count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3:          count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\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   | [] => true\n   | x :: xs => andb  (member x s2) (subset xs (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\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. induction l1 as [|n1' l1' IHl1'].\n simpl. reflexivity.\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\nLemma app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n intros l1 l2. induction l1 as [| n' l1' Hl1'].\n simpl. reflexivity.\n simpl. rewrite -> Hl1'. 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. rewrite -> app_length. \n rewrite -> IHl'. simpl. rewrite -> plus_comm. reflexivity.\nQed.\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.\n  rewrite -> nil_app.\n  assert (H1: rev [] = []). { reflexivity. }\n  rewrite -> H1. \n  rewrite -> app_nil_r.\n  reflexivity.\n  simpl.\n  rewrite -> IHl1.\n  rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l.\n  simpl. reflexivity.\n  simpl. rewrite -> rev_app_distr.\n  rewrite -> 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.\n rewrite -> app_assoc.\n rewrite <- app_assoc.\n reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\nnonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1.\n  reflexivity.\n  simpl.\n  destruct n.\n  rewrite -> IHl1. reflexivity.\n  simpl. rewrite -> IHl1. reflexivity.\nQed.\n\n", "meta": {"author": "avatar29A", "repo": "SoftwareFoundationSolutions", "sha": "c8f6ab5a6a6ead61668ee800e49e578f303bf473", "save_path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions", "path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions/SoftwareFoundationSolutions-c8f6ab5a6a6ead61668ee800e49e578f303bf473/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8774767874818408, "lm_q1q2_score": 0.7901939837544378}}
{"text": "Require Import Arith Lia.\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 iter_plus {X: Type} {f: X -> X} {x: X} {n m: nat} : \n  Nat.iter (n + m) f x = Nat.iter m f (Nat.iter n f x).\nProof. by rewrite Nat.add_comm /Nat.iter nat_rect_plus. Qed.\n\nLemma mod_frac_lt {n m: nat} : (S m) mod (n + 1) = 0 -> S m < (S m * (n + 2)) / (n + 1).\nProof.\n    have ->: S m * (n + 2) = S m + S m * (n + 1) by lia.\n    have := Nat.div_mod_eq (S m) (n + 1).\n    rewrite Nat.div_add; lia.\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 /Nat.div_exact : S m mod (1 + n) = 0 by lia. move /(_ ltac:(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=> /Nat.div_exact => /(_ ltac:(lia)) ?.\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-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/StackMachines/Util/Nat_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7900697633323346}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\nRequire Import OrderedType.\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 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 _ H => left _\n                     | right _ H => right _\n                   end\n                 | Some a', None => right _\n                 | None, Some b' => right _\n                 | None, None => left _\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 using. \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 using. \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 using. \n  intros.\n  unfold fin_lt. simpl.\n  intuition.\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 using. \n  intros.\n  unfold fin_lt. simpl.\n  intuition.\nQed.\n\nLemma None_lt_Some :\n  forall n (x : fin n),\n    @fin_lt (S n) None (Some x).\nProof using. \n  unfold fin_lt. simpl. auto with *.\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 using. \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 using. \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 (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 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 (N : NatValue) <: OrderedType.\n  Definition t := fin N.n.\n  Definition eq : t -> t -> Prop := eq.\n  Definition lt : t -> t -> Prop := fin_lt.\n  Definition eq_refl : forall x : t, eq x x := @eq_refl _.\n  Definition eq_sym : forall x y: t, eq x y -> eq y x := @eq_sym _.\n  Definition eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z := @eq_trans _.\n  Definition lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z := @fin_lt_trans N.n.\n  Definition lt_not_eq : forall x y : t, lt x y -> ~ eq x y := @fin_lt_not_eq N.n. \n  Definition compare : forall x y : t, Compare lt eq x y := fin_compare N.n.\n  Definition eq_dec : forall x y : t, {eq x y} + {~ eq x y} := fin_eq_dec N.n.\nEnd fin_OT_compat.\n\nRequire Import Orders.\n\nLemma fin_lt_irrefl : \n  forall n, Irreflexive (@fin_lt n).\nProof using. \n  intros.\n  unfold Irreflexive, complement, Reflexive, fin_lt.\n  intuition.\nQed.\n\nLemma fin_lt_strorder : forall n, StrictOrder (@fin_lt n).\nProof using. \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 using. \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 using. \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 using. \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 using. \n  intros.\n  solve_by_inversion.\nQed.\n\nFixpoint fin_comparison_dec (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_comparison_dec 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\nDefinition fin_comparison (n : nat) (x y : fin n) : comparison :=\nmatch fin_comparison_dec n x y with exist _ cmp _ => cmp end.\n\nLemma fin_compare_spec : forall (n : nat) (x y : fin n), \n    CompSpec eq fin_lt x y (fin_comparison n x y).\nProof using. \n  intros.\n  unfold fin_comparison.\n  break_match.\n  assumption.\nQed.\n\nModule fin_OT (N : NatValue) <: OrderedType.\n  Definition t := fin N.n.\n  Definition eq := eq (A := fin N.n).\n  Definition eq_equiv := eq_equivalence (A := fin N.n).\n  Definition lt := fin_lt (n := N.n).\n  Definition lt_strorder := fin_lt_strorder N.n.\n  Definition lt_compat := fin_lt_lt_compat N.n.\n  Definition compare := fin_comparison N.n.\n  Definition compare_spec := fin_compare_spec N.n.\n  Definition eq_dec := fin_eq_dec N.n.\nEnd fin_OT.\n\nFixpoint fin_of_nat (m n : nat) : fin n + {exists p, m = n + p} :=\n  match n as n0 return fin n0 + {exists p, m = n0 + p} with\n  | 0 => inright (ex_intro _ m eq_refl)\n  | S n' =>\n    match m as m0 return fin (S n') + {exists p, m0 = (S n') + p} 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 => inright (let 'ex_intro _ x H := pf in\n                              ex_intro _ x (f_equal S H))\n      end\n    end\n  end.\n\nLemma fin_of_nat_fin_to_nat:\n  forall (n : nat) (a : fin n), fin_of_nat (fin_to_nat a) n = inleft a.\nProof using. \n  induction n; simpl; intuition.\n  destruct a; simpl in *; auto.\n  now rewrite IHn.\nQed.", "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/structtact/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7900656546142403}}
{"text": "Require Import Common.\n\nModule MyList.\n  Inductive list (A : Type) : Type :=\n  | nil : list A\n  | cons : A -> list A -> list A.\n  Arguments nil {_}.\n\n\n  Notation \"[ ]\" := nil (format \"[ ]\").\n  Notation \"x :: xs\" := (cons x xs).\n  Notation \"[ x ]\" := (cons x nil).\n  Notation \"[ x ; y ; .. ; z ]\" :=  (cons x (cons y .. (cons z nil) ..)).\n\n  Fixpoint app A (xs ys : list A) : list A :=\n    match xs with\n    | [] => ys\n    | x :: xs => x :: app xs ys\n    end.\n\n  Notation \"xs ++ ys\" := (app xs ys) (right associativity, at level 60).\n\n  Lemma app_nil_r : forall A (xs : list A), xs ++ [] = xs.\n  Proof.\n    induction xs.\n    - simpl.\n      reflexivity.\n    - simpl.\n      rewrite IHxs.\n      reflexivity.\n  Qed.\n\n  Lemma app_assoc : forall A (xs ys zs : list A), (xs ++ ys) ++ zs = xs ++ (ys ++ zs).\n  (* Detailed paper proof.\n     By induction on xs.\n     - xs is nil,\n         goal is forall ys zs, ([] ++ ys) ++ zs = [] ++ (ys ++ zs).\n       let ys and zs be arbitrary,\n         goal is ([] ++ ys) ++ zs = [] ++ (ys ++ zs).\n       ([] ++ ys) computes to ys; [] ++ (ys ++ zs) computes to ys ++ zs.\n         goal is ys ++ zs = ys ++ zs.\n       conclude by reflexivity.\n     - xs is x :: xs,\n         goal is forall ys zs, ((x :: xs) ++ ys) ++ zs = (x :: xs) ++ (ys ++ zs)\n         IH is forall ys zs, (xs ++ ys) ++ zs = xs ++ (ys ++ zs)\n       let ys and zs be arbitrary.\n         goal is ((x :: xs) ++ ys) ++ zs = (x :: xs) ++ (ys ++ zs)\n       (x :: xs) ++ ys computes to x :: (xs ++ ys)\n         goal is (x :: (xs ++ ys)) ++ zs = (x :: xs) ++ (ys ++ zs)\n       (x :: (xs ++ ys)) ++ zs computes to x :: ((xs ++ ys) ++ zs)\n         goal is x :: ((xs ++ ys) ++ zs) = (x :: xs) ++ (ys ++ zs)\n       (x :: xs) ++ (ys ++ zs) computes to x :: (xs ++ (ys ++ zs))\n         goal is x :: ((xs ++ ys) ++ zs) = x :: (xs ++ (ys ++ zs))\n       use IH instantiated with (ys := ys) and (zs := zs)\n       and conclude by reflexivity\n   *)\n  Proof.\n    induction xs as [|x xs].\n    - (* xs is [] *)\n      intros ys zs.\n      simpl.\n      reflexivity.\n    - (* xs is x :: xs *)\n      intros ys zs.\n      simpl.\n      rewrite IHxs.\n      reflexivity.\n  Qed.\n\n  Fixpoint rev A (xs : list A) : list A :=\n    match xs with\n    | [] => []\n    | x :: xs => rev xs ++ [x]\n    end.\n\n  Fixpoint rev_tail' A (xs : list A) (acc : list A) : list A :=\n    match xs with\n    | [] => acc\n    | x :: xs => rev_tail' xs (x :: acc)\n    end.\n\n  Definition rev_tail A (xs : list A) : list A := rev_tail' xs [].\n\n  Theorem rev_is_rev_tail :\n    forall A (xs : list A),\n      rev_tail xs = rev xs.\n  Proof.\n    induction xs.\n    - simpl. unfold rev_tail. simpl. reflexivity.\n    - simpl. unfold rev_tail. simpl. (* ? *) rewrite <- IHxs. (* ??? *)\n  Abort.\n\n  (* Rule of thumb: if a function is a fixpoint, statements about it should be\n     proved by induction. If it's a definition, induction is unlikely to be\n     effective.\n\n     Since rev_tail is a definition, theorems about it should just unfold it and\n     then use some lemma about rev_tail'.\n\n     Since rev_tail' is a fixpoint, statements about it should be proved by\n     induction.\n   *)\n\n  (* There are three flavors of argument to a fixpoint:\n     1) the \"structural\" argument (the one being recursed on)\n     2) \"constant\" arguments, which don't change through any recursive calls\n     3) \"variable\" arguments, which change on recursive calls\n\n     Rule of thumb: in order for a statement about a fixpoint to be provable by\n     induction, the structural and variable arguments should be\n     forall-quantified.\n\n     Pro tip: the structural argument should be quantified before *any*\n     variable arguments.\n   *)\n\n  (* So, we're looking for a stament about rev_tail' that forall-quantifies\n     over `xs` and `acc`, and which implies `rev_is_rev_tail`. Something\n     like this:\n\n     forall A (xs : list A) acc,\n        rev_tail' xs acc = (* ??? *)\n\n     How would you describe the general behavior of `rev_tail'`? You might say\n     something like \"it reverses `xs` and prepends the result to `acc`\". This\n     turns out to work!\n   *)\n\n  Lemma rev_tail'_is_rev_then_prepend :\n    forall A (xs acc : list A),\n      rev_tail' xs acc = rev xs ++ acc.\n  (* Detailed paper proof:\n     By induction on xs.\n     - x is [],\n         goal becomes forall acc, rev_tail [] acc = rev [] ++ acc.\n       let acc be arbitrary,\n         goal becomes rev_tail [] acc = rev [] ++ acc.\n       rev_tail [] acc computes to acc,\n         goal becomes acc = rev [] ++ acc.\n       rev [] computes to [],\n         goal becomes acc = [] ++ acc.\n       [] ++ acc computes to acc,\n         goal becomes acc = acc.\n       conclude by reflexivity.\n     - xs is x :: xs,\n         goal becomes forall acc, rev_tail (x :: xs) acc = rev (x :: xs) ++ acc.\n         IH is forall acc, rev_tail xs acc = rev xs ++ acc.\n       let acc be arbitrary,\n         goal becomes rev_tail (x :: xs) acc = rev (x :: xs) ++ acc.\n       rev_tail (x :: xs) acc computes to rev_tail xs (x :: acc)\n         goal becomes rev_tail xs (x :: acc) = rev (x :: xs) ++ acc.\n       rev (x :: xs) computes to rev xs ++ [x]\n         goal becomes rev_tail xs (x :: acc) = (rev xs ++ [x]) ++ acc.\n       instantiate IH with (x :: acc)\n         IH becomes rev_tail xs (x :: acc) = rev xs ++ x :: acc.\n       use IH in goal,\n         goal becomes rev xs ++ x :: acc = (rev xs ++ [x]) ++ acc.\n       use associativity of append (lemma)\n         goal becomes rev xs ++ x :: acc = rev xs ++ ([x] ++ acc).\n       [x] ++ acc computes to x :: acc,\n         goal becomes rev xs ++ x :: acc = rev xs ++ x :: acc.\n       conclude by reflexivity. *)\n  Proof.\n    induction xs as [|x xs].\n    - intros acc.\n      simpl.\n      reflexivity.\n    - intros acc.\n      simpl.\n      specialize (IHxs (x :: acc)).\n      rewrite IHxs.\n      rewrite app_assoc.\n      simpl.\n      reflexivity.\n  Qed.\n\n  Theorem rev_tail_is_rev :\n    forall A (xs : list A),\n      rev_tail xs = rev xs.\n  Proof.\n    unfold rev_tail.\n    intros.\n    rewrite rev_tail'_is_rev_then_prepend.\n    rewrite app_nil_r.\n    reflexivity.\n  Qed.\n\n  (* Proof engineering tip: unfold at most one definition per theorem.\n\n     Even better: rely on computational behavior of at most one definition per\n     theorem.\n   *)\nEnd MyList.\n\n(* Switch back to stdlib lists and nats, since what we're about to do isn't\n   there already. *)\nRequire Import List.\nImport ListNotations.\n\nFixpoint sum (xs : list nat) : nat :=\n  match xs with\n  | [] => 0\n  | x :: xs => x + sum xs\n  end.\n\nFixpoint sum_tail' (xs : list nat) (acc : nat) : nat :=\n  match xs with\n  | [] => acc\n  | x :: xs => sum_tail' xs (x + acc)\n  end.\n\nDefinition sum_tail (xs : list nat) : nat := sum_tail' xs 0.\n\nTheorem sum_tail_is_sum :\n  forall xs, sum_tail xs = sum xs.\nProof.\n  induction xs.\n  - simpl. unfold sum_tail. simpl. reflexivity.\n  - simpl. unfold sum_tail. simpl.\nAbort.\n\nLemma sum_tail'_is_sum_plus_acc :\n  forall xs acc, sum_tail' xs acc = sum xs + acc.\nProof.\n  induction xs.\n  - intros acc.\n    simpl.\n    reflexivity.\n  - intros acc.\n    simpl.\n    rewrite IHxs.\n    omega.\nQed.\n\nTheorem sum_tail_is_sum :\n  forall xs, sum_tail xs = sum xs.\nProof.\n  intros xs.\n  unfold sum_tail.\n  rewrite sum_tail'_is_sum_plus_acc.\n  omega.\nQed.\n\nFixpoint sum_cps' (xs : list nat) A (k : nat -> A) : A :=\n  match xs with\n  | [] => k 0\n\n  (* See what happens if you change x + n to n + x in the following line.\n\n     Nothing too bad, but the proof below breaks because we need an extra\n     commutativity step. Carefully designed to make proofs simple. This is\n     something that will come up again and again. *)\n  | x :: xs => sum_cps' xs (fun n => k (x + n))\n  end.\n\nDefinition sum_cps (xs : list nat) : nat := sum_cps' xs (fun x => x).\n\n(* TODO: probably worth getting stuck here when attempting to fix k as fun x => x. *)\n\nLemma sum_cps'_calls_k_with_sum :\n  forall xs A (k : nat -> A),\n    sum_cps' xs k = k (sum xs).\nProof.\n  induction xs.\n  - intros.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nTheorem sum_cps_is_sum :\n  forall xs, sum_cps xs = sum xs.\nProof.\n  intros.\n  unfold sum_cps.\n  rewrite sum_cps'_calls_k_with_sum.\n  reflexivity.\nQed.\n\n\n\nInductive expr :=\n| Const (n : nat)\n| Plus (e1 e2 : expr).\n\nFixpoint eval (e : expr) : nat :=\n  match e with\n  | Const n => n\n  | Plus e1 e2 => eval e1 + eval e2\n  end.\n\nFixpoint eval_cps' (e : expr) A (k : nat -> A) : A :=\n  match e with\n  | Const n => k n\n\n  (* Change n1 + n2 to n2 + n1 for a good time. *)\n  | Plus e1 e2 => eval_cps' e1 (fun n1 => eval_cps' e2 (fun n2 => k (n1 + n2)))\n  end.\n\nDefinition eval_cps (e : expr) : nat := eval_cps' e (fun x => x).\n\nLemma eval_cps'_calls_k_with_eval :\n  forall e A (k : nat -> A),\n    eval_cps' e k = k (eval e).\nProof.\n  induction e.\n  - intros.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n    rewrite IHe1.\n    rewrite IHe2.\n    reflexivity.\nQed.\n\nTheorem eval_cps_is_eval : forall e, eval_cps e = eval e.\nProof.\n  intros.\n  unfold eval_cps.\n  rewrite eval_cps'_calls_k_with_eval.\n  reflexivity.\nQed.\n\n\n\n\n(* Stack machine *)\n\nInductive instr :=\n| Push (n : nat)\n| Add.\n\nDefinition prog := list instr.\n\nDefinition stack := list nat.\n\nDefinition exec_instr (i : instr) (s : stack) : stack :=\n  match i with\n  | Push n => n :: s\n  | Add => match s with\n          | x :: y :: s => y + x :: s (* forth order *)\n          | _ => s (* bogus!\n\n                     TODO: interesting point here about doing a type-correct but\n                     wrong thing vs introducing options to capture failure;\n                     corresponding proof engineering tradeoffs *)\n          end\n  end.\n\nFixpoint exec_prog' (p : prog) (s : stack) : stack :=\n  match p with\n  | [] => s\n  | i :: p => exec_prog' p (exec_instr i s)\n  end.\n\nDefinition exec_prog (p : prog) : nat := hd 0 (exec_prog' p []).\n(* TODO: Could also return stack here. jrw thinks stack is right thing, but also\n   that readers won't agree :) But returning nat has advantage of making things\n   a little harder. *)\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\nTheorem compile_correct :\n  forall e,\n    exec_prog (compile e) = eval e.\nProof.\n  (* TODO: get stuck*)\nAbort.\n\n(* Nothing obviously wrong with this lemma statement.\n\n   TODO: Brings up interesting discussion of rule of thumb, since we're\n   forall-quantified over e, but then call compile, instead of just being\n   forall-quantified over a program. *)\nLemma exec_prog'_of_compile_is_push_eval :\n  forall e s,\n    exec_prog' (compile e) s = eval e :: s.\nProof.\n  induction e.\n  - intros.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n    Fail rewrite IHe1. (* oh no! *)\n    (* We need to know that exec_prog' executes appends in the right way.\n       Two reasonable ways of proceeding: prove exec_prog'_app lemma or\n       generalize current lemma statement to account for it. Showing both\n       is interesting. *)\n\n    Lemma exec_prog'_app :\n      forall p1 p2 s,\n        exec_prog' (p1 ++ p2) s = exec_prog' p2 (exec_prog' p1 s).\n    Proof.\n      induction p1.\n      - intros.\n        simpl.\n        reflexivity.\n      - intros.\n        simpl.\n        rewrite IHp1.\n        reflexivity.\n    Qed.\n\n    rewrite exec_prog'_app.\n    rewrite IHe1.\n\n    rewrite exec_prog'_app.\n    rewrite IHe2.\n    simpl. (* Notice we can skip the error case. *)\n    reflexivity.\nQed.\n\nTheorem compile_correct :\n  forall e,\n    exec_prog (compile e) = eval e.\nProof.\n  unfold exec_prog.\n  intros.\n  rewrite exec_prog'_of_compile_is_push_eval.\n  simpl. (* Notice we can skip the error case. *)\n  reflexivity.\nQed.\n\n(* Other way of doing it in one go. *)\nLemma exec_prog'_of_compile_of_e_appended_to_p_is_exec_prog'_of_p_with_eval_e_pushed :\n  forall e p s,\n    exec_prog' (compile e ++ p) s = exec_prog' p (eval e :: s).\nProof.\n  induction e.\n  - intros.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n    rewrite app_ass.\n    rewrite IHe1.\n    rewrite app_ass.\n    rewrite IHe2.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem compile_correct_another_way :\n  forall e,\n    exec_prog (compile e) = eval e.\nProof.\n  intros.\n  unfold exec_prog.\n  rewrite <- app_nil_r with (l := compile e).\n  rewrite exec_prog'_of_compile_of_e_appended_to_p_is_exec_prog'_of_p_with_eval_e_pushed.\n  simpl.\n  reflexivity.\nQed.\n\n\n\n(* Insertion sort *)\n\n(* TODO: Discussion of spec for sorting. Usually if you ask people who haven't\n   thought about it before, they will say \"well it should be sorted\" and not\n   remember to say permutation. *)\n\nFixpoint insert (a : nat) (xs : list nat) : list nat :=\n  match xs with\n  | [] => [a]\n  | x :: xs => if a <=? x then a :: x :: xs\n              else x :: (insert a xs)\n  end.\n\n(* Just for fun... *)\nFixpoint insert_tail' (a : nat) (xs acc : list nat) : list nat :=\n  match xs with\n  | [] => List.rev' (a :: acc)\n  | x :: xs => if a <=? x then List.rev_append acc (a :: x :: xs)\n              else insert_tail' a xs (x :: acc)\n  end.\n\nDefinition insert_tail (a : nat) (xs : list nat) : list nat :=\n  insert_tail' a xs [].\n\n(* :D *)\nLemma insert_tail'_is_prepend_reversed_acc_to_insert_xs :\n  forall a xs acc,\n    insert_tail' a xs acc = List.rev acc ++ insert a xs.\nProof.\n  induction xs.\n  - intros.\n    simpl.\n    unfold rev'.\n    simpl.\n    rewrite rev_append_rev.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n    break_if.\n    + rewrite rev_append_rev.\n      reflexivity.\n    + rewrite IHxs.\n      simpl.\n      rewrite app_ass.\n      simpl.\n      reflexivity.\nQed.\n\nTheorem insert_tail_is_insert :\n  forall a xs,\n    insert_tail a xs = insert a xs.\nProof.\n  intros.\n  unfold insert_tail.\n  rewrite insert_tail'_is_prepend_reversed_acc_to_insert_xs.\n  simpl.\n  reflexivity.\nQed.\n\nLemma insert_insert_comm :\n  forall a b xs,\n    insert a (insert b xs) = insert b (insert a xs).\nProof.\n  induction xs.\n  - simpl.\n    repeat break_if.\n    + rewrite Nat.leb_le in *.\n      assert (a = b) by omega.\n      subst.\n      reflexivity.\n    + reflexivity.\n    + reflexivity.\n    + rewrite Nat.leb_nle in *.\n      omega.\n  - simpl.\n    repeat (break_if; simpl).\n    all: try rewrite Nat.leb_le in *.\n    all: try rewrite Nat.leb_nle in *.\n    all: auto.\n    all: try omega.\n    all: try discriminate.\n    + assert (a = b) by omega.\n      subst.\n      reflexivity.\n    + rewrite IHxs.\n      reflexivity.\nQed.\n\nFixpoint insertion_sort (xs : list nat) : list nat :=\n  match xs with\n  | [] => []\n  | x :: xs => insert x (insertion_sort xs)\n  end.\n\nFixpoint insertion_sort_tail' (xs acc : list nat) : list nat :=\n  match xs with\n  | [] => acc\n  | x :: xs => insertion_sort_tail' xs (insert_tail x acc)\n  end.\n\nDefinition insertion_sort_tail (xs : list nat) : list nat :=\n  insertion_sort_tail' xs [].\n\nTheorem insertion_sort_tail_is_insertion_sort :\n  forall xs,\n    insertion_sort_tail xs = insertion_sort xs.\nProof.\n  intros.\n  unfold insertion_sort_tail.\n  induction xs.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- IHxs.\n    rewrite insert_tail_is_insert.\n\n    Lemma insertion_sort_tail'_insert_comm :\n      forall xs a ys,\n        insertion_sort_tail' xs (insert a ys) = insert a (insertion_sort_tail' xs ys).\n    Proof.\n      induction xs.\n      - intros.\n        simpl.\n        reflexivity.\n      - intros.\n        simpl.\n        rewrite insert_tail_is_insert.\n        rewrite insert_tail_is_insert.\n        rewrite insert_insert_comm.\n        rewrite IHxs.\n        reflexivity.\n    Qed.\n\n    rewrite insertion_sort_tail'_insert_comm.\n    reflexivity.\nQed.\n\n(* Roll our own sorted because it's a good exercise and the stdlib is more\n   general than we need. *)\nInductive sorted : list nat -> Prop :=\n| sorted_nil : sorted []\n| sorted_cons : forall a xs, sorted xs -> List.Forall (fun x => a <= x) xs -> sorted (a :: xs).\n\nTheorem insertion_sort_sorted :\n  forall xs, sorted (insertion_sort xs).\nProof.\n  induction xs.\n  - simpl.\n    apply sorted_nil.\n  - simpl.\n\n    Lemma insert_sorted :\n      forall a xs,\n        sorted xs ->\n        sorted (insert a xs).\n    Proof.\n      induction xs.\n      - intros.\n        simpl.\n        apply sorted_cons.\n        + apply sorted_nil.\n        + apply Forall_nil.\n      - intros.\n        simpl.\n        break_if.\n        + rewrite Nat.leb_le in *.\n          apply sorted_cons.\n          * assumption.\n          * invc H.\n            apply Forall_cons.\n            -- assumption.\n            -- eapply Forall_impl; try eassumption.\n               intros.\n               simpl in *.\n               omega.\n        + rewrite Nat.leb_nle in *.\n          invc H.\n          apply sorted_cons.\n          * apply IHxs. assumption.\n          *\n            Lemma insert_Forall_le:\n              forall (a b : nat) (xs : list nat),\n                a <= b ->\n                Forall (fun x : nat => a <= x) xs -> Forall (fun x : nat => a <= x) (insert b xs).\n            Proof.\n              intros.\n              (* Pro tip: induct on the Forall instead of the xs. In general,\n                 induct on the \"most dependent\" thing you have. *)\n              induction H0.\n              - simpl.\n                apply Forall_cons.\n                + assumption.\n                + apply Forall_nil.\n              - simpl.\n                break_if.\n                + apply Forall_cons.\n                  * assumption.\n                  * apply Forall_cons.\n                    -- assumption.\n                    -- assumption.\n                + apply Forall_cons.\n                  * assumption.\n                  * assumption.\n            Qed.\n\n            apply insert_Forall_le.\n            -- omega.\n            -- assumption.\n    Qed.\n\n    apply insert_sorted.\n    assumption.\nQed.\n\n(* The permutation library is pretty good already, so we can just use it directly. *)\n\nRequire Import Permutation.\n\nTheorem insertion_sort_perm :\n  forall xs, Permutation (insertion_sort xs) xs.\nProof.\n  induction xs.\n  - simpl.\n    reflexivity.\n  - simpl.\n\n    Lemma insert_perm :\n      forall a xs, Permutation (insert a xs) (a :: xs).\n    Proof.\n      induction xs.\n      - simpl.\n        reflexivity.\n      - simpl.\n        break_if.\n        + reflexivity.\n        + (* Pro tip: rewriting with Permutations works and is typically more\n             convenient than trying to apply lemmas directly. *)\n          rewrite perm_swap.\n          apply Permutation_cons.\n          * reflexivity.\n          * apply IHxs.\n    Qed.\n\n    rewrite insert_perm.\n    apply Permutation_cons.\n    + reflexivity.\n    + apply IHxs.\nQed.\n\n(* We have proved that insertion_sort is correct (sorted and permutation) and\n   that insertion_sort_tail (which is the code we actually want to run) is\n   equivalent to it. We can combine these to get correctness of\n   insertion_sort_tail. *)\n\nTheorem insertion_sort_tail_sorted :\n  forall xs, sorted (insertion_sort_tail xs).\nProof.\n  intros.\n  rewrite insertion_sort_tail_is_insertion_sort.\n  apply insertion_sort_sorted.\nQed.\n\nTheorem insertion_sort_tail_perm :\n  forall xs, Permutation (insertion_sort_tail xs) xs.\nProof.\n  intros.\n  rewrite insertion_sort_tail_is_insertion_sort.\n  apply insertion_sort_perm.\nQed.\n", "meta": {"author": "palmskog", "repo": "street-fighting-proof-assistants", "sha": "f89660fab17a8c1a6c9cd9c14484ed8d72fb0088", "save_path": "github-repos/coq/palmskog-street-fighting-proof-assistants", "path": "github-repos/coq/palmskog-street-fighting-proof-assistants/street-fighting-proof-assistants-f89660fab17a8c1a6c9cd9c14484ed8d72fb0088/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.911179702173019, "lm_q1q2_score": 0.7900253947816649}}
{"text": "Require Import Frap Helpers.\n\nRequire Import Problem.\n\nFixpoint fact (n: nat): nat :=\n  match n with\n  | 0 => 1\n  | S n' => n * fact n'\n  end.\n\nTheorem fact_thm1:\n  fact 5 = 120.\nProof.\n  simplify.\n  equality.\nQed.\n\nTheorem fact_thm2: forall (n: nat),\n  n > 1 -> (exists (k: nat), fact n = 2 * k).\nProof.\n  simplify.\n  induct n.\n  * linear_arithmetic.\n  * cases (n =? 1).\n    - comparison_bool_to_prop.\n      rewrite Heq.\n      simplify.\n      exists 1.\n      linear_arithmetic.\n    - comparison_bool_to_prop.\n      assert (n > 1) by linear_arithmetic.\n      propositional.\n      clear H Heq H0.\n      invert H1.\n      exists (x * S n).\n      simplify.\n      rewrite H.\n      ring.\nQed.\n\nFixpoint fact_CPS (n: nat) (C: nat -> nat): nat :=\n  match n with\n  | 0 => C 1\n  | S n' => fact_CPS n' (fun R => C (n * R))\n  end.\n\nTheorem CPS_correct: forall (n: nat) (f: nat -> nat),\n fact_CPS n f = f (fact n).\nProof.\n  induct n; simplify.\n  + trivial.\n  + apply IHn with (f := fun R: nat => f ( S n * R )).\nQed.\n\nTheorem fact_CPS_thm2: forall (n: nat),\n  n > 1 -> (exists (k: nat), fact_CPS n (fun R => R) = 2 * k).\nProof.\n  simplify.\n  rewrite CPS_correct.\n  apply fact_thm2.\n  assumption.\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/solutions1/Problem1/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7900253921989556}}
{"text": "Require Import aula3 aula4.\n(** Prove the following claim, marking cases (and subcases) with\n    bullets when you use [destruct]. *)\n\n(** **** Exercise: 2 stars (andb_true_elim2)  *)\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + simpl. reflexivity.\n    + simpl. intros h. rewrite h. reflexivity.\n  - intros h. destruct c.\n    + reflexivity.\n    + rewrite <- h. simpl. reflexivity.\n Qed. \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. destruct n.\n - simpl. reflexivity.\n - simpl. reflexivity.\n Qed.\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 x. intros b. rewrite x. rewrite x. reflexivity.\nQed.\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.\nintros b c. destruct b.\n -simpl. intros h. rewrite h. reflexivity.\n -simpl. intros h. rewrite <- h. reflexivity.\nQed.", "meta": {"author": "nobreconfrade", "repo": "reidocoq", "sha": "98fc4c357cbc38041b1e83e1a2c468aac0d6ef70", "save_path": "github-repos/coq/nobreconfrade-reidocoq", "path": "github-repos/coq/nobreconfrade-reidocoq/reidocoq-98fc4c357cbc38041b1e83e1a2c468aac0d6ef70/doit2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.7898904001193437}}
{"text": "Set Implicit Arguments.    (* Allows us to use inference for dependent arguments *)\n\nRequire Import Reals.      (* Imports real arithmetic. *)\nDelimit Scope R with Real.    (* Notice: due to the absence of overloading, from this *)\n                           (* point on constants and operators are real-typed,     *)\nNotation Real := R.           (* unless stated otherwise with the scope indicator '%' *)\n\nCheck 3 + 4.           (* : ℕ  (nat)  *)\nCheck (3 + 4) % R.     (* : ℝ  (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\nCheck VCons.\nPrint Implicit VCons.\n\n\nFail Definition c1 := repeat 1.\nDefinition c2 n := VCons (n:=n) 2.\n\n\n\nFixpoint repeat e n :=\n  match n with\n    0 => VNil\n  | S k => VCons e (repeat e k)\n  end.\n\nCheck repeat.\n\n\nCompute repeat 4 5.\nEval simpl in repeat 4 5.\n\n\nCheck nat_rec.\n\nDefinition repeat' e :=\n  nat_rec Vec VNil (fun x y => VCons e y).\n\nEval simpl in repeat' 4 5.\n\n\nCheck Vec_rec.\n\n\n(* Notice that a return type is needed here *)\nFixpoint concat m n (v1 : Vec m) (v2 : Vec n) : Vec (m+n):=\n  match v1 with\n    VNil => v2\n  | VCons x xs => VCons x (concat xs v2)\n  end.\n\nDefinition ifz n (t1 t2 : Type) := match n with\n                                   | 0 => t1\n                                   | _ => t2 end.\n\nDefinition hd' n (v : Vec n) : ifz n unit R :=\n  match v with\n    VNil => tt\n  | VCons x xs => x\n  end.\n\nDefinition hd n (v : Vec (S n)) := hd' v.\n\n\n\n\nFixpoint Vec' n : Set :=\n  match n with\n    0 => unit\n  | S k => R * Vec' k\n  end.\n\nFixpoint vec_to_vec' n (v: Vec n) : Vec' n :=\n  match v with\n    VNil => tt\n  | VCons x xs => (x, vec_to_vec' xs)\n  end.\n\n\n\nFixpoint inner_product' n : Vec' n -> Vec' n -> Real :=\n  match n with\n    0 => fun _ _ => 0\n  | S k => fun v1 v2 =>\n            match v1, v2 with\n              (x, xs), (y, ys) =>\n              x * y + inner_product' k xs ys\n            end\n  end.\n\nFixpoint inner_product n (v1 v2 : Vec n) :=\n  inner_product' n (vec_to_vec' v1) (vec_to_vec' v2).\n\nPrint inner_product.\n\nHint Unfold inner_product.\n\nExample test_inner_product :\n  inner_product <<1>> <<4>> = 4.\nProof. field. Qed.\n\nEval field in inner_product <<1>> <<4>>.\n\n\nCheck inner_product << 5, 9, 6 >> << 1, 3, 7 >>.\nFail Check inner_product << 9, 6 >> << 1, 3, 7 >>.\n\n\n\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/vecn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.7898903834598864}}
{"text": "\nRequire Import Arith Lia.\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\n(* Task 0 : Example of iso in finite sets *)\n(* Find a bijection between bool and bit. (provided for you as an example) *)\nInductive bit : Set := b0 | b1.\n\nDefinition bool2bit (b : bool) : bit :=\n  match b with true => b1 | false => b0\n  end.\n\nDefinition bit2bool (b : bit) : bool :=\n  match b with b1 => true | b0 => false\n  end.\n\nDefinition bool_iso_bit : iso bool bit.\nProof.\n  apply (bijection _ _ bool2bit bit2bool).\n  intros.\n  case a.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  intros.\n  case b.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\n\n(******************************************)\n(* Task 1 : General properties of iso *)\n(* Task 1-1. Prove that any set has the same cardinality as itself. *)\nTheorem iso_refl : forall A : Set, iso A A.\nProof.\n  intros.\n  apply (bijection _ _ id id);\n    unfold id; reflexivity.\n  Qed.\n\n(* Task 1-2. Prove that iso is symmetric. *)\nTheorem iso_sym : forall A B : Set, iso A B -> iso B A.\nProof.\n  intros.\n  elim H.\n  intros.\n  exact (bijection B A B_to_A0 A_to_B0 B_A_B0 A_B_A0).\nQed.\n\n\n\n\n(* Task 1-3. Prove that iso is transitive. *)\nTheorem iso_trans : forall A B C : Set, iso A B -> iso B C -> iso A C.\nProof.\n  intros.\n  case H as [AB BA ABA BAB].\n  case H0 as [BC CB BCB CBC].\n  apply (bijection A C (fun a => BC (AB a)) (fun c =>  BA (CB c))).\n  intros.\n  specialize (BCB (AB a)).\n  rewrite BCB.\n  specialize (ABA a).\n  rewrite ABA.\n  reflexivity.\n  intros.\n  specialize (BAB (CB b)).\n  rewrite BAB.\n  specialize (CBC b).\n  rewrite CBC.\n  reflexivity.\nQed.\n\n\n(* Task 1-4. Prove the following statement:\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  apply (bijection _ _ A2B B2A).\n  assumption.\n  intros.\n  rewrite (H0 (A2B (B2A b)) b).\n  reflexivity.\n  rewrite (H (B2A b)).\n  reflexivity.\nQed.\n\n(******************************************)\n(* Task 2 : iso relations between nat and various supersets of nat *)\n\n(* nat_plus_1 : a set having one more element than nat. (provided in preloaded) *)\n(* Inductive nat_plus_1 : Set := null | is_nat (n : nat). *)\n\n(* Task 2-1. Prove that nat has the same cardinality as nat_plus_1. *)\n\nInductive nat_plus_1 : Set := null | is_nat (n : nat).\n\nTheorem nat_iso_natp1 : iso nat nat_plus_1.\nProof.\n  apply (bijection _ _ (fun n => match n with\n                                | 0 => null\n                                | S m => is_nat m\n                       end) (fun n => match n with\n                                | null => 0\n                                | is_nat m => S m\n                       end)).\n  intros.\n  induction a;\n  reflexivity.\n  induction b;\n  reflexivity.\nQed.\n\n(* nat_plus_nat : a set having size(nat) more elements than nat. (provided in preloaded) *)\nInductive nat_plus_nat : Set := left (n : nat) | right (n : nat).\n\nFixpoint nat_to_nn (n : nat) : nat_plus_nat\n  := match n with\n       | 0 => left 0\n       | 1 => right 0\n       | S (S m) => match nat_to_nn m with\n                     | left a => left (S a)\n                     | right a => right (S a)\n                    end\n     end.\n\nDefinition nn_to_nat (n : nat_plus_nat) : nat\n  := match n with\n       | left l => l + l\n       | right r => S (r + r)\n     end.\n\nDefinition nat_ind_two : forall P, \n  P 0 -> P 1 -> (forall n, P n -> P (S (S n))) -> (forall n, P n).\nProof.\n  intros P P0 P1 PSS.\n  exact (fix go (n:nat): P n := match n with\n    | 0 => P0\n    | 1 => P1\n    | S (S n_bez_dvou) => PSS n_bez_dvou (go n_bez_dvou)\n  end\n  ).\nQed.\n\nDefinition nat_ind_two2 : forall P, \n  P 0 -> P 1 -> (forall n, P n -> P (S (S n))) -> (forall n, P n).\nProof.\n  intros P P0 P1 PSS.\n  fix IPn 1.\n  intro m.\n  destruct m.\n  exact P0.\n  destruct m.\n  exact P1.\n  apply PSS.\n  exact (IPn m).\nQed.\n\n\n(* Task 2-2. Prove that nat has the same cardinality as nat_plus_nat. *)\nTheorem nat_iso_natpnat : iso nat nat_plus_nat.\nProof.\n  apply (bijection _ _ nat_to_nn nn_to_nat).\n  - intros.\n    induction a using nat_ind_two.\n    compute. easy.\n    compute. easy.\n    simpl.\n    destruct (nat_to_nn a).\n    simpl in IHa.\n    simpl.\n    lia.\n    simpl in IHa.\n    simpl.\n    lia.\n  - intros.\n    destruct b. \n    simpl.\n    induction n.\n    compute.\n    reflexivity.\n    assert (S n + S n = S (S (n + n))) by lia.\n    rewrite -> H.\n    simpl.\n    rewrite -> IHn.\n    reflexivity.\n    simpl nn_to_nat.\n    induction n.\n    compute.\n    reflexivity.\n    simpl.\n    assert (n + S n = S (n + n)) by lia.\n    rewrite -> H.\n    rewrite -> IHn.\n    reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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/bijec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7898501860441272}}
{"text": "(* 1 *)\nFixpoint ravno (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' => ravno n' m'\n                  end\n      end.\n\nEval compute in ravno 5 3.\nEval compute in ravno 5 5.\nEval compute in ravno 5 7.\n\n(* 2 *)\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\nEval compute in leb 5 3.\nEval compute in leb 5 5.\nEval compute in leb 5 7.\n\n(* 3 *)\nFixpoint leb2 (n m : nat) : bool :=\n      match n with\n        | O    => match m with\n                    | O    => false\n                    | S m' => true\n                    end\n        | S n' => match m with\n                    | O    => false\n                    | S m' => leb2 n' m'\n                  end\n      end.\n\nEval compute in leb2 5 3.\nEval compute in leb2 5 5.\nEval compute in leb2 5 7.\n\n(* 4 *)\nFixpoint evennum (n : nat) : bool :=\n       match n with\n         | O        => true\n         | S O      => false\n         | S (S n') => evennum n'\n       end.\n\nEval simpl in evennum 1.\nEval simpl in evennum 6.\n\n(* 5 *)\nDefinition oddnum (n : nat) : bool :=\n       negb (evennum n).\n\nEval compute in oddnum 1.\nEval compute in oddnum 6.\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/Lab7/R3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7898240168668927}}
{"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\nExample test_net_weekay :\n  (next_weekday (next_weekday saturday)) = tuesday.\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. 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.\n\nDefinition nandb (b1 : bool) (b2 : bool) : bool :=\n  match (b1, b2) with\n  | (true,  true)  => false\n  | _              => true\n  end.\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\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\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_andb34: (andb3 true true false) = false.\nProof. reflexivity. Qed.\n\nCheck true.\nCheck negb.\n\nModule Playground1.\n\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.\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\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. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. 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\nExample test_mult1: (mult 3 3) = 9.\nProof. reflexivity. Qed.\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O , _ => O\n  | S _ , O => n\n  | S n', S m' => minus n' m'\n  end.\n\nEnd Playground2.\n\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    => 1\n  | S n' => mult (S n') (factorial n')\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y) \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x - y\" := (minus x y) \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x * y\" := (mult x y) \n                       (at level 40, left associativity) \n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S m' => false\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => beq_nat n' m'\n            end\n  end.\n\nFixpoint ble_nat (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => ble_nat n' m'\n      end\n  end.\n\nExample test_ble_nat1: (ble_nat 2 2) = true.\nProof. 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 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nTheorem plus_0_n : forall n : nat, 0 + n = n.\nProof. intros n. reflexivity. Qed.\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\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 = m -> n + n = m + m.\nProof. intros n m. intros H. rewrite -> H. reflexivity. Qed.\nTheorem plus_id_exercise: forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof. intros. rewrite -> H. rewrite <- H0. reflexivity. Qed.\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\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\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 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. 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. Qed.\n\nTheorem andb_eq_orb_lemma1 :\n  forall (c : bool), andb true c = c.\nProof.\n  destruct c.\n    reflexivity.\n    reflexivity. Qed.\n\nTheorem andb_eq_orb_lemma2 :\n  forall (c : bool), orb true c = true.\nProof.\n  destruct c.\n    reflexivity.\n    reflexivity. Qed.\n\nTheorem andb_eq_orb_lemma3 :\n  forall (c : bool), andb false c = false.\nProof.\n  destruct c.\n    reflexivity.\n    reflexivity. Qed.\n\nTheorem andb_eq_orb_lemma4 :\n  forall (c : bool), orb false c = c.\nProof.\n  destruct c.\n    reflexivity.\n    reflexivity. Qed.\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    rewrite -> andb_eq_orb_lemma1.\n    rewrite -> andb_eq_orb_lemma2.\n    intro H.\n    rewrite -> H.\n    reflexivity.\n    rewrite -> andb_eq_orb_lemma3.\n    rewrite -> andb_eq_orb_lemma4.\n    intro H.\n    rewrite -> H.\n    reflexivity.\n  Qed.\n\nInductive bin : Type :=\n  | Zero  : bin\n  | Twice : bin -> bin\n  | TwicePlusOne : bin -> bin.\n\nFixpoint increment_bin (n : bin) : bin :=\n  match n with\n  | Zero     => TwicePlusOne Zero\n  | Twice n' => TwicePlusOne n'\n  | TwicePlusOne n' => Twice (increment_bin n')\n  end.\n\nFixpoint convert_to_unary (n : bin) : nat :=\n  match n with\n  | Zero => 0\n  | Twice n' => (convert_to_unary n') + (convert_to_unary n')\n  | TwicePlusOne n' => S ((convert_to_unary n') + (convert_to_unary n'))\n  end.\n\nEval compute in convert_to_unary (increment_bin (Twice (Twice (TwicePlusOne Zero)))).\n\nTheorem convert_increment :\n  forall (n : bin), S (convert_to_unary n) = convert_to_unary (increment_bin n).\nProof.\n  destruct n as [|n'|n'].\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n    simpl.\n    Admitted.\n    ", "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/chapter01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7898240114639248}}
{"text": "\nRequire 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\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\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\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\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\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\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\nDefinition mynil : list nat := 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\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 := \n  match count with\n  |0 => []\n  |S count' => n::(repeat X n count')\n  end.\n\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.\n  intros X l.\n  reflexivity. \nQed.\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 X v s.\n  induction s.\n  Case \"s = []\".\n  reflexivity. \n  Case \"s = x :: s\".\n  simpl.\n  rewrite IHs.\n  reflexivity. \nQed.\n  \n\nTheorem snoc_append : forall X : Type, forall (l : list X) (n:X),\n  snoc l n = l ++ [n].\nProof.\n  intros X l n. induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev1 :forall X : Type, forall (l : list X) (n:X),\n  rev  (l ++ [n]) = n::(rev l) .\nProof.\n  intros X l n. induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    rewrite -> IHl'.\n    rewrite -> snoc_append.\n    rewrite -> snoc_append.\n    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 l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    rewrite -> snoc_append.\n    rewrite -> rev1.\n    rewrite -> IHl'.\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  \n  intros X l1 l2 v.\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(** [] *)\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nImplicit Arguments 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\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\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, 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    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\nDefinition addPair {X Y : Type} (p : X * Y) \n(l : (list X)*(list Y))  :  (list X)*(list Y) := \n  match p,l with \n  |(x,y), (l1,l2) => (x::l1,y::l2)\n  end. \nFixpoint split {X Y : Type} (l : list (X*Y))  \n           : (list X)*(list Y) :=\n  match l with\n  |h::l'=>addPair h (split l')\n  |[] => ([],[])\n  end.\n\n\n\nExample test_split:\n  split [(1,false),(2,false)] = ([1,2],[false,false]).\nProof. reflexivity.  Qed.\n\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\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  |[] => None\n  |n::l' => Some n\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\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X := \n  f (f (f n)).\n\n\nCheck @doit3times.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n\nCheck plus.\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(** **** Exercise: 2 stars, optional (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  match p with \n  |(x,y) => f x y\n  end. \n\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.  \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\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\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\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] which takes a list of natural numbers as input\n    and keeps only those numbers which are even and greater than 7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n=>andb (evenb n) (ble_nat 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 (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\nDefinition partition {X : Type} (test : X -> bool) (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\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\n\n(** **** Exercise: 3 stars, optional (map_rev) *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map1 : forall (X Y : Type) (f : X -> Y) (l : list X) (n: X),\n  map f (l++[n]) = (map f l)++[f n].\nProof.\n  intros X Y f l n.\n  induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    rewrite IHl'.\n  reflexivity. \nQed.\n\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 [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    rewrite snoc_append.\n    rewrite map1.\n    rewrite <- IHl'.\n    rewrite snoc_append.\n    reflexivity. \nQed.\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        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\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\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 plus).\nEval simpl in (fold plus [1,2,3,4] 0).\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, optional (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Например: Y - дерево, f - добавление эелмента в дерево.\n\n\n *)\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\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\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  reflexivity. \nQed.\n(** [] *)\n\nInductive boolllist : nat -> Type :=\n  boollnil  : boolllist O\n| boollcons : forall n, bool -> boolllist n -> boolllist (S n).\n\nImplicit Arguments boollcons [[n]].\n\nCheck (boollcons true (boollcons false (boollcons true boollnil))).\n\nFixpoint blapp {n1} (l1: boolllist n1) \n               {n2} (l2: boolllist n2) \n             : boolllist (n1 + n2) := \n  match l1 with\n  | boollnil        => l2\n  | boollcons _ h t => boollcons h (blapp t l2)\n  end.\n\nInductive llist (X:Type) : nat -> Type :=\n  lnil  : llist X O\n| lcons : forall n, X -> llist X n -> llist X (S n).\n\nImplicit Arguments lnil [[X]].\nImplicit Arguments lcons [[X] [n]].\n\nCheck (lcons true (lcons false (lcons true lnil))).\n\nFixpoint lapp (X:Type)\n              {n1} (l1: llist X n1) \n              {n2} (l2: llist X n2) \n            : llist X (n1 + n2) := \n  match l1 with\n  | lnil        => l2\n  | lcons _ h t => lcons h (lapp X t l2)\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  (* 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\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\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.  Qed.\n\n(** [] *)\n\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 *)\nAdmitted.\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, recommended (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' H.\n  rewrite H.\n  symmetry.\n  apply rev_involutive.\nQed. \n  \n\n\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\napply пвтается полностью сопоставить цель и гипотезу/теорему.\nrewrite ищет в цели вхождения левой или правой части равенства из \nгипотезы/теоремы и заменяет их.\napply может не сработать, если левая и правя части в одном из равенств\nпоменены местами.\n*)\n(** [] *)\n\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 f H1 H2.\n  unfold override.\n  rewrite  H2.\n  rewrite  H1.\n  reflexivity.  \nQed.\n(** [] *)\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\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.\n  inversion H2.\n  reflexivity.  \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 H1 H2.\n  inversion H1.\nQed.\n(** [] *)\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\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\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(** **** Exercise: 2 stars (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    destruct n.\n    SCase \"n = 0\". \n      reflexivity.  \n    SCase \"n = S n'\".\n      intros H. inversion H.\n  Case \"m = S m'\".\n    destruct n.\n    SCase \"n = 0\". \n      intros H. inversion H.\n    SCase \"n = S n'\".\n      intros H. \n      apply eq_remove_S.\n      apply IHm'.\n      inversion H.\n      reflexivity.  \nQed.\n(** [] *)\n\n\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 H.\n  destruct n as [| n'].\n  Case \"n = 0\". \n    reflexivity. \n  SCase \"n = S n'\". \n  inversion H.\nQed.\n\nTheorem beq_nat_0_r : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n H.\n  destruct n as [| n'].\n  Case \"n = 0\". \n    reflexivity. \n  SCase \"n = S n'\". \n  inversion H.\nQed.\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\". \n  destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.  \n    SCase \"m = S m'\".\n      reflexivity. \n  Case \"n = S n'\". \n  destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.  \n    SCase \"m = S m'\".\n    apply IHn'.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (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\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\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(** **** Exercise: 3 stars, recommended (plus_n_n_injective) *)\n(** You can practice using the \"in\" variants in this exercise. *)\n\nTheorem unS : forall n m,\n     n  = m  ->\n     S n = S m.\nProof.\n  intros n m H.\n  rewrite H.\n  reflexivity. \nQed.\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  Case \"n = 0\". \n  destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.  \n    SCase \"m = S m'\".\n    intros H.\n    inversion H.\n  Case \"n = S n'\". \n  destruct m as [| m'].\n    SCase \"m = 0\".\n    intros H.\n    inversion H.   \n    SCase \"m = S m'\".\n    rewrite <- plus_n_Sm.\n    rewrite <- plus_n_Sm.\nsimpl.\n    intros H.\n    apply unS.\n    apply IHn'.\n    inversion H.  \n  reflexivity. \nQed.\n\n    (* Hint: use the plus_n_Sm lemma *)\n(** [] *)\n\n(* ###################################################### *)\n(** ** Using [destruct] on Compound Expressions *)\n\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  intros X x1 x3 k1 k2 f.\n  unfold override.\n  destruct (beq_nat k1 k2).\n    Case \"beq_nat k1 k2 = true\". reflexivity.\n    Case \"beq_nat k1 k2 = false\". reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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 l. induction l as [| [x y] l'].\n  Case \"l = []\".\n    intros.\n    inversion H.  \n    reflexivity.\n  Case \"l = (x, y) :: l'\".\n    intros.\n    inversion H.\n    destruct (split l').\nAdmitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (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 (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 remember (beq_nat k1 k2) as e3.\n   \n   destruct e3.\n     Case \"e3 = true\". apply beq_nat_eq in Heqe3.\n       rewrite -> Heqe3 in H.\n       symmetry.\n       apply H.\n     Case \"e3 = false\".\n       reflexivity.\n Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (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  intros X test x l lf.\n  induction l as [| h l'].\n  Case \"l = []\".\n  intros.\n    inversion H.\n  Case \"l = h::l'\".\n    remember (test h) as e3.\n    destruct e3.\n    SCase \"e3 = true\". \n      simpl.\n      rewrite <- Heqe3.\n      intros.\n      inversion H.\n      rewrite H1 in Heqe3.\n      symmetry.\n      apply Heqe3.\n    SCase \"e3 = false\".\n      simpl.\n      rewrite <- Heqe3.\n      apply IHl'.\nQed.\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, recommended (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  intros.\n  rewrite H0.\n  apply H.\nQed.\n\nTheorem beqTrue : forall n, true = beq_nat n n.\nProof.  \n  intros.\n  induction n as[| n'].\n  \n  reflexivity.\n  simpl.  \n  apply IHn'.\nQed.\n\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  \n  intros.\napply beq_nat_eq in H.\napply beq_nat_eq in H0.\n  rewrite H.\n  rewrite H0.\n  apply beqTrue.\nQed.\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  intros.\n  unfold override.\n remember (beq_nat k1 k3) as e3.\n   \n   destruct e3.\n     Case \"e3 = true\". apply beq_nat_eq in Heqe3.\n       rewrite -> Heqe3 in H.\n       rewrite <- H.\n       reflexivity.\n     Case \"e3 = false\".\n       reflexivity.\n Qed.\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: 2 stars, optional (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\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    unfold fold_length.\n    simpl.\n    rewrite <- IHl'.\n    unfold fold_length.\n    reflexivity. \nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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 n1 n2 => (f n1) :: n2) l [].\n\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.\n  induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    unfold fold_length.\n    simpl.\n    rewrite <- IHl'.\n    unfold fold_length.\n    reflexivity. \nQed.\n(** [] *)\n\nModule MumbleBaz.\n(** **** Exercise: 2 stars, optional (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)] - нет типа после d \n      - [d mumble (b a 5)] - well-typed\n      - [d bool (b a 5)] - well-typed\n      - [e bool true] - well-typed\n      - [e mumble (b c 0)] - well-typed\n      - [e bool (b c 0)] - вместо bool должен быть mumble, \n                           или в скобках должан быть bool\n      - [c] - well-typed\n\n[] *)\n(** **** Exercise: 2 stars, optional (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\nЗдесь не хватает базисного элемента. \n=> нельзя постоить ни одного элемента\n\n[] *)\n\nEnd MumbleBaz.\n\n(** **** Exercise: 4 stars, recommended (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\nFixpoint forallb {X :Type} (f : X -> bool) (l : list X) : bool :=\n  match l with \n  |[] => true\n  |h::l' => if f h then forallb f l' else false\n  end.\nExample forallb_example1 : forallb oddb [1,3,5,7,9] = true.\nProof. reflexivity. Qed.\nExample forallb_example2 : forallb evenb [0,2,4,5] = false.\nProof. reflexivity. Qed.\nExample forallb_example3 : forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\nExample forallb_example4 : forallb negb [false,false] = true.\nProof. reflexivity. Qed.\nFixpoint existsb {X :Type} (f : X -> bool) (l : list X) : bool :=\n  match l with \n  |[] => false\n  |h::l' => if f h then true else existsb f l'\n  end.\nExample existsb_example1 : existsb (beq_nat 5) [0,2,3,6] = false.\nProof. reflexivity. Qed.\nExample existsb_example2 : existsb (andb true) [true,true,false] = true.\nProof. reflexivity. Qed.\nExample existsb_example3 : existsb oddb [1,0,0,0,0,3] = true.\nProof. reflexivity. Qed.\nExample existsb_example4 : existsb evenb [] = false.\nProof. reflexivity. Qed.\nDefinition existsb' {X :Type} (f : X -> bool) (l : list X) : bool :=\nnegb (forallb (fun n => negb(f n)) l).\nTheorem fold_existsb_correct : forall X (l : list X) (f : X -> bool),\n  existsb f l = existsb' f l.\nProof.\n  intros.\n  induction l as [| h l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = h :: l'\".\n    simpl.\n    unfold existsb'.\n    simpl.\n    remember (f h) as e3.\n    destruct e3.\n    SCase \"e3 = true\". \n      reflexivity. \n    SCase \"e3 = false\".\n      simpl.\n      rewrite -> IHl'.\n      unfold existsb'.\n      reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (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", "meta": {"author": "AntonMilenin", "repo": "CoqBook", "sha": "2f8fc7f5da81079fbbb2a2fa86437d02adf7638f", "save_path": "github-repos/coq/AntonMilenin-CoqBook", "path": "github-repos/coq/AntonMilenin-CoqBook/CoqBook-2f8fc7f5da81079fbbb2a2fa86437d02adf7638f/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.7898159267186481}}
{"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.Main.\nFrom Categories Require Import Archetypal.PreOrder_Cat.PreOrder_Cat.\n\nRequire Import Coq.Arith.Arith.\n\nDelimit Scope omegacat_scope with omegacat.\n\nLocal Open Scope omegacat_scope.\n\n(** Since we can't eliminate prop to define functors in a simple way,\nwe redefine the notion of le (less than or equal) for natural numbers\nin Type (Tle).\n\nWe show that le implies Tle (and vise versa).\n\nWhat follows are some properties of Tle.\n *)\nInductive Tle (n : nat) : nat → Type :=\n| Tle_n : Tle n n\n| Tle_S : ∀ m, Tle n m → Tle n (S m)\n.\n\nHint Constructors Tle.\n\nNotation \"n ≤ m\" := (Tle n m) : omegacat_scope.\n\nDefinition Tle_addS (n m : nat) : n ≤ m → S n ≤ S m.\nProof.\n  intros H.\n  induction H; auto.\nQed.\n\nDefinition Tle_trans (n m t : nat) : n ≤ m → m ≤ t → n ≤ t.\nProof.\n  intros H1 H2.\n  induction H2; auto.\nDefined.\n\nDefinition Tle_remS (n m : nat) : S n ≤ S m → n ≤ m.\nProof.\n  revert n.\n  induction m.\n  intros n H.\n  induction n; auto.\n  inversion H as [Hx | m H1 H2]; inversion H1.\n  intros n H.\n  inversion H; auto.\nQed.\n\nTheorem Not_S_Tle (n : nat) : Tle (S n) n → False.\nProof.\n  intros H.\n  induction n; inversion H; auto.\n  apply IHn.\n  apply Tle_remS; trivial.\nQed.\n\n(** Tle is decidable. This is crutial in conversion from le to Tle. *)\nDefinition Tle_dec (n m : nat) : (n ≤ m) + ((n ≤ m) → False).\nProof.\n  revert m.\n  induction n.\n  - left; induction m; auto.\n  - induction m.\n    + right; intros H; inversion H.\n    + destruct IHm as [H1|H1].\n      left; auto.\n      destruct (IHn m) as [H2|H2].\n      * left; apply Tle_addS; trivial.\n      * right.\n        intros H3.\n        contradict H2.\n        apply Tle_remS; trivial.\nQed.\n\n(** This is prety straightforward. *)\nDefinition Tle_le {n m : nat} : n ≤ m → le n m.\nProof.\n  intros H.\n  induction H; auto.\nQed.\n\n(** The contrapositive of conversion from le to Tle. *)\nDefinition NTle_Nle {n m : nat} : (n ≤ m → False) → (le n m → False).\nProof.\n  intros H1 H2.\n  induction H2.\n  + apply H1; trivial.\n  + apply IHle.\n    intros H3.\n    apply H1; auto.\nQed.\n\n(** This is the actual conversion from le to Tle.\n\nHere, the trick is that we use decidability of Tle.\nIn case the relation holds, we have the proof.\nIn case it does not, we can refute the le relation.\n\nHence, this conversion is (as expected) does not\npreform an explicit elimination of le (as it is\nimpossible) and hence is not computationally\nsimplifiable.\n *)\nDefinition le_Tle {n m : nat} : le n m → n ≤ m.\nProof.\n  intros H.\n  destruct (Tle_dec n m) as [H1|H1]; auto.\n  contradict H.\n  unfold not; apply NTle_Nle; trivial.\nQed.\n\n(** We show that (homotopy-type-theoretically speaking) Tle is a mere\n    proposition. That is, any two proofs of a ≤ b are equal. Note that\nTle is in Type and not in Pop and hence we can't use proof-irrelevance.\n\nThis is a proof in a hurry, and can perhaps be simplified later.\n *)\nTheorem Tle_is_HProp {n m : nat} (H H' : Tle n m) : H = H'.\nProof.\n  dependent induction H.\n  dependent induction H'; trivial.\n  {\n    inversion H' as [H1| m' H1 H2].\n    {\n      contradict H1; clear.\n      induction m; auto.\n    }\n    {\n      subst.\n      contradict H1; clear.\n      induction m'.\n      + intros H; inversion H.\n      + intros H.\n        apply IHm'.\n        apply Tle_remS; trivial.\n    }\n  }\n  {\n    inversion H'.\n    + subst.\n      clear IHTle.\n      contradict H; clear.\n      intros H.\n      induction m.\n      * inversion H.\n      * apply IHm.\n        apply Tle_remS; trivial.\n    + subst.\n      dependent destruction H'.\n      {\n        clear IHTle.\n        contradict H; clear.\n        intros H.\n        induction m.\n        * inversion H.\n        * apply IHm.\n          apply Tle_remS; trivial.\n      }\n      {\n        apply f_equal.\n        apply IHTle.\n      }\n  }\nQed.\n\n(** Natural numbers form a preorder with le (less than or equal relation). *)\nDefinition OmegaPreOrder :=\n  {|\n    PreOrder_car := nat : Type;\n    PreOrder_rel := Tle : _ → _ → Type;\n    PreOrder_rel_isProp :=\n      fun _ _ h h' => Tle_is_HProp h h';\n    PreOrder_refl := Tle_n;\n    PreOrder_trans := Tle_trans\n  |}.\n\n(** The pre-order category ω. *)\nDefinition OmegaCat : Category := PreOrder_Cat OmegaPreOrder.\n\nNotation \"'ω'\" := (OmegaCat) : omegacat_scope.\n\nLemma le_Tle_n (n : nat) : le_Tle (le_n n) = Tle_n n.\nProof.\n  apply Tle_is_HProp.\nQed.\n\nLemma le_Tle_S (n m : nat) (H : le n m) :\n  le_Tle (le_S _ _ H) = Tle_S _ _ (le_Tle H).\nProof.\n  apply Tle_is_HProp.\nQed.\n\nLemma le_Tle_trans (n m k : nat) (H : le n m) (H' : le m k) :\n  le_Tle (le_trans _ _ _ H H') = Tle_trans _ _ _ (le_Tle H) (le_Tle H').\nProof.\n  apply Tle_is_HProp.\nQed.\n\n(** Given a map f from natural numbers to objects of a category C\nand a map from (f (S n) –≻ f n), we construct a functor from\nωᵒᵖ to C. *)\n(** This is the arrow map of the functor being constructed. *)\nLocal Fixpoint FA_fx {C : Category}\n      (OOF_O : nat → C)\n      (OOF_A : ∀ n, ((OOF_O (S n)) –≻ (OOF_O n))%morphism)\n      (n m : nat) (h : Tle n m)\n      {struct h} : (OOF_O m –≻ OOF_O n)%morphism\n  :=\n    match h in _ ≤ w return\n          (OOF_O w –≻ OOF_O n)%morphism\n    with\n    | Tle_n _ =>\n      id (OOF_O n)\n    | Tle_S _ m' H' =>\n      ((FA_fx OOF_O OOF_A _ _ H') ∘ (OOF_A m'))%morphism\n    end\n.\n\n(** This is the the functor described above. *)\nProgram Definition OmegaCat_Op_Func {C : Category}\n      (OOF_O : nat → C)\n      (OOF_A : ∀ n, ((OOF_O (S n)) –≻ (OOF_O n))%morphism)\n  : ((ω^op) –≻ C)%functor :=\n  {|\n    FO := OOF_O;\n    FA := fun m n h => FA_fx OOF_O OOF_A _ _ h\n  |}\n.\n\nNext Obligation.\nProof.\n  induction f as [|m t IHt].\n  + cbn; auto.\n  + replace (Tle_trans _ _ _ g (Tle_S _ _ t))\n    with (Tle_S _ _ (Tle_trans _ _ _ g t)).\n    cbn.\n    rewrite IHt.\n    auto.\n    apply Tle_is_HProp.\nQed.\n\n(** Similar functor from ω to C. *)\nDefinition OmegaCat_Func {C : Category}\n           (OMF_O : nat → C)\n           (OMF_A : ∀ n, ((OMF_O n) –≻ (OMF_O (S n)))%morphism)\n  : (OmegaCat –≻ C)%functor\n  := (@OmegaCat_Op_Func (C^op) OMF_O OMF_A)^op.\n\n(** Any functor from ωᵒᵖ to C is freely generated by its object map and the\n    image of the arrow map under (le_S _ _ (le_n n)) (proof of (le n (S n))). *)\nLemma OmegaCat_Op_Func_unique {C : Category} (F : ((ω^op) –≻ C)%functor) :\n  F = OmegaCat_Op_Func (FO F) (fun n => FA F (Tle_S _ _ (Tle_n n))).\nProof.\n  Func_eq_simpl.\n  extensionality y.\n  extensionality x.\n  extensionality h.\n  cbn in *.\n  revert x y h.\n  induction x.\n  {\n    intros y h.\n    induction y.\n    + dependent destruction h.\n      rewrite (F_id F).\n      trivial.\n    + dependent destruction h.\n      cbn in *.\n      rewrite <- (IHy h).\n      rewrite <- F_compose.\n      match goal with\n        [|- (F _a)%morphism ?A = (F _a)%morphism ?B] =>\n        set (l := A); set (l' := B); cbn in l, l'; PIR\n      end.\n      trivial.\n  }\n  {\n    intros y h.\n    induction y.\n    + inversion h.\n    + dependent destruction h.\n      * rewrite (F_id F).\n        trivial.\n      * cbn.\n        rewrite <- (IHy h).\n        rewrite <- F_compose.\n        match goal with\n          [|- (F _a)%morphism ?A = (F _a)%morphism ?B] =>\n          set (l := A); set (l' := B); cbn in l, l'; PIR\n        end.\n        trivial.\n  }\nQed.\n\n(** Any functor from ω to C is freely generated by its object map and the image\n    of the arrow map under (le_S _ _ (le_n n)) (proof of (le n (S n))). *)\nLemma OmegaCat_Func_unique {C : Category} (F : (ω –≻ C)%functor) :\n  F = OmegaCat_Func (FO F) (fun n => FA F (Tle_S _ _ (Tle_n n))).\nProof.\n  unfold OmegaCat_Func.\n  cbn_rewrite <- ((OmegaCat_Op_Func_unique (F^op))).\n  trivial.\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/Categories/Archetypal/PreOrder_Cat/OmegaCat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7895841663945652}}
{"text": "(** * Equivalência entre o Princípio da Indução Matemática e o Princípio da Indução Forte *)\n\nRequire Import Arith.\n\n(** Seja [P] uma propriedade sobre os números naturais. O Princípio da *)\n(** Indução Matemática (PIM) pode ser enunciado da seguinte forma:  *)\n\nDefinition PIM :=\n  forall P: nat -> Prop,\n    (P 0) ->\n    (forall n, P n -> P (S n)) ->\n    forall n, P n.\n\n(** Seja [Q] uma propriedade sobre os números naturais. O Princípio da *)\n(** Indução Forte (PIF) pode ser enunciado da seguinte forma:  *)\n\n\nDefinition PIF :=\n  forall Q: nat -> Prop,\n    (forall n, (forall m, m<n -> Q m) -> Q n) ->\n    forall n, Q n.\n\n(** Prove que estes princípios são equivalentes: *)\n\nLemma PIF_to_PIM: PIF -> PIM.\nProof.\n(* Substitua esta linha pela sua prova*) Admitted.\n\nLemma PIM_to_PIF: PIM -> PIF.\nProof.\n(* Substitua esta linha pela sua prova*) Admitted.\n\nTheorem PIM_equiv_PIF: PIM <-> PIF.\nProof.\n  (* Substitua esta linha pela sua prova*) Admitted.\n", "meta": {"author": "flcm", "repo": "ind-equiv", "sha": "ba703b99c9e6ca7527d3449cbd7817cba9c7aa11", "save_path": "github-repos/coq/flcm-ind-equiv", "path": "github-repos/coq/flcm-ind-equiv/ind-equiv-ba703b99c9e6ca7527d3449cbd7817cba9c7aa11/ind-equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7895489071806863}}
{"text": "Require Import Arith.\nRequire Import Coq.Lists.List.\nRequire Import extEqualNat.\nRequire Import primRec.\nRequire Vector.\nRequire Import Div2.\n\nDefinition sumToN (n : nat) :=\n  nat_rec (fun _ => nat) 0 (fun x y : nat => S x + y) n.\n\nLemma sumToN1 : forall n : nat, n <= sumToN n.\nProof.\nintros.\ninduction n as [| n Hrecn].\nauto.\nsimpl in |- *.\napply le_n_S.\napply le_plus_l.\nQed.\n\nLemma sumToN2 : forall b a : nat, a <= b -> sumToN a <= sumToN b.\nProof.\nintro.\ninduction b as [| b Hrecb]; intros.\nsimpl in |- *.\nrewrite <- (le_n_O_eq _ H).\nsimpl in |- *.\nauto.\ninduction (le_lt_or_eq _ _ H).\napply le_trans with (sumToN b).\napply Hrecb.\napply lt_n_Sm_le.\nauto.\nsimpl in |- *.\napply le_S.\napply le_plus_r.\nrewrite H0.\nauto.\nQed.\n\nLemma sumToNIsPR : isPR 1 sumToN.\nProof.\nunfold sumToN in |- *.\napply indIsPR with (f := fun x y : nat => S x + y).\napply\n compose2_2IsPR\n  with (f := fun x y : nat => S x) (g := fun x y : nat => y) (h := plus).\napply filter10IsPR.\napply succIsPR.\napply pi2_2IsPR.\napply plusIsPR.\nQed.\n\nDefinition cPair (a b : nat) := a + sumToN (a + b).\n\nLemma cPairIsPR : isPR 2 cPair.\nProof.\nintros.\nunfold cPair in |- *.\napply\n compose2_2IsPR\n  with\n    (f := fun x y : nat => x)\n    (g := fun x y : nat => sumToN (x + y))\n    (h := plus).\napply pi1_2IsPR.\napply compose2_1IsPR.\napply plusIsPR.\napply sumToNIsPR.\napply plusIsPR.\nQed.\n\nSection CPair_Injectivity.\n\nRemark cPairInjHelp :\n forall a b c d : nat, cPair a b = cPair c d -> a + b = c + d.\nProof.\nassert (forall a b : nat, a < b -> a + sumToN a < sumToN b).\nsimple induction b.\nintros.\nelim (lt_n_O _ H).\nintros.\nsimpl in |- *.\nassert (a <= n).\napply lt_n_Sm_le.\nassumption.\ninduction (le_lt_or_eq a n H1).\napply lt_trans with (sumToN n).\nauto.\napply le_lt_n_Sm.\napply le_plus_r.\nrewrite H2.\napply lt_n_Sn.\nunfold cPair in |- *.\nassert\n (forall a b c d : nat,\n  a <= c -> b <= d -> a + sumToN c = b + sumToN d -> c = d).\nintros.\ninduction (le_or_lt c d).\ninduction (le_lt_or_eq _ _ H3).\nassert (a + sumToN c < sumToN d).\napply le_lt_trans with (c + sumToN c).\napply plus_le_compat_r.\nauto.\nauto.\nrewrite H2 in H5.\nelim (lt_not_le _ _ H5).\napply le_plus_r.\nauto.\nassert (b + sumToN d < sumToN c).\napply le_lt_trans with (d + sumToN d).\napply plus_le_compat_r.\nauto.\nauto.\nrewrite <- H2 in H4.\nelim (lt_not_le _ _ H4).\napply le_plus_r.\nintros.\neapply H0.\napply le_plus_l.\napply le_plus_l.\nauto.\nQed.\n\nLemma cPairInj1 : forall a b c d : nat, cPair a b = cPair c d -> a = c.\nProof.\nintros.\nassert (a + b = c + d).\napply cPairInjHelp.\nauto.\neapply plus_reg_l.\nunfold cPair in H.\nrewrite (plus_comm a) in H.\nrewrite (plus_comm c) in H.\nrewrite H0 in H.\napply H.\nQed.\n\nLemma cPairInj2 : forall a b c d : nat, cPair a b = cPair c d -> b = d.\nProof.\nintros.\nassert (a + b = c + d).\napply cPairInjHelp.\nauto.\nassert (a = c).\neapply cPairInj1.\napply H.\neapply plus_reg_l.\nrewrite H1 in H0.\napply H0.\nQed.\n\nEnd CPair_Injectivity.\n\nSection CPair_projections.\n\nLet searchXY (a : nat) :=\n  boundedSearch (fun a y : nat => ltBool a (sumToN (S y))) a.\n\nDefinition cPairPi1 (a : nat) := a - sumToN (searchXY a).\nDefinition cPairPi2 (a : nat) := searchXY a - cPairPi1 a.\n\nLemma cPairProjectionsHelp :\n forall a b : nat, b < sumToN (S a) -> sumToN a <= b -> searchXY b = a.\nProof.\nintros.\nunfold searchXY in |- *.\ninduction (boundedSearch2 (fun b y : nat => ltBool b (sumToN (S y))) b).\nrewrite H1.\ninduction (eq_nat_dec b a).\nauto.\nelim (ltBoolFalse b (sumToN (S a))).\napply (boundedSearch1 (fun b y : nat => ltBool b (sumToN (S y))) b).\nrewrite H1.\ninduction (nat_total_order _ _ b0).\nelim (lt_not_le _ _ H2).\napply le_trans with (sumToN a).\napply sumToN1.\nauto.\nauto.\nauto.\nset (c := boundedSearch (fun b y : nat => ltBool b (sumToN (S y))) b) in *.\ninduction (eq_nat_dec c a).\nauto.\nelim (ltBoolFalse b (sumToN (S a))).\napply (boundedSearch1 (fun b y : nat => ltBool b (sumToN (S y))) b).\nfold c in |- *.\ninduction (nat_total_order _ _ b0).\nelim (le_not_lt _ _ H0).\napply lt_le_trans with (sumToN (S c)).\napply ltBoolTrue.\nauto.\nassert (S c <= a).\napply lt_n_Sm_le.\napply lt_n_S.\nauto.\napply sumToN2.\nauto.\nauto.\nauto.\nQed.\n\nLemma cPairProjections : forall a : nat, cPair (cPairPi1 a) (cPairPi2 a) = a.\nProof.\nassert\n (forall a b : nat, b < sumToN a -> cPair (cPairPi1 b) (cPairPi2 b) = b).\nintros.\ninduction a as [| a Hreca].\nsimpl in H.\nelim (lt_n_O _ H).\ninduction (le_or_lt (sumToN a) b).\nassert (searchXY b = a).\napply cPairProjectionsHelp; auto.\nunfold cPair in |- *.\nreplace (cPairPi1 b + cPairPi2 b) with a.\nunfold cPairPi1 in |- *.\nrewrite H1.\nrewrite plus_comm.\nrewrite <- le_plus_minus.\nreflexivity.\nauto.\nunfold cPairPi2 in |- *.\nrewrite <- le_plus_minus.\nauto.\nunfold cPairPi1 in |- *.\nrewrite H1.\nsimpl in H.\napply (fun p n m : nat => plus_le_reg_l n m p) with (sumToN a).\nrewrite <- le_plus_minus.\nrewrite plus_comm.\napply lt_n_Sm_le.\nauto.\nauto.\napply Hreca.\nauto.\nintros.\napply H with (S a).\napply lt_le_trans with (S a).\napply lt_n_Sn.\napply sumToN1.\nQed.\n\nRemark searchXYIsPR : isPR 1 searchXY.\nProof.\nunfold searchXY in |- *.\napply boundSearchIsPR with (P := fun a y : nat => ltBool a (sumToN (S y))).\nunfold isPRrel in |- *.\napply\n compose2_2IsPR\n  with\n    (h := charFunction 2 ltBool)\n    (f := fun a y : nat => a)\n    (g := fun a y : nat => sumToN (S y)).\napply pi1_2IsPR.\napply filter01IsPR with (g := fun y : nat => sumToN (S y)).\napply compose1_1IsPR.\napply succIsPR.\napply sumToNIsPR.\napply ltIsPR.\nQed.\n\nLemma cPairPi1IsPR : isPR 1 cPairPi1.\nProof.\nunfold cPairPi1 in |- *.\napply\n compose1_2IsPR\n  with\n    (g := minus)\n    (f := fun x : nat => x)\n    (f' := fun a : nat => sumToN (searchXY a)).\napply idIsPR.\napply compose1_1IsPR.\napply searchXYIsPR.\napply sumToNIsPR.\napply minusIsPR.\nQed.\n\nLemma cPairPi2IsPR : isPR 1 cPairPi2.\nProof.\nunfold cPairPi2 in |- *.\napply compose1_2IsPR with (g := minus) (f := searchXY) (f' := cPairPi1).\napply searchXYIsPR.\napply cPairPi1IsPR.\napply minusIsPR.\nQed.\n\nLemma cPairProjections1 : forall a b : nat, cPairPi1 (cPair a b) = a.\nProof.\nintros.\nunfold cPair in |- *.\nunfold cPairPi1 in |- *.\nreplace (searchXY (a + sumToN (a + b))) with (a + b).\nrewrite plus_comm.\napply minus_plus.\nsymmetry  in |- *.\napply cPairProjectionsHelp.\nsimpl in |- *.\napply le_lt_n_Sm.\napply plus_le_compat_r.\napply le_plus_l.\napply le_plus_r.\nQed.\n\nLemma cPairProjections2 : forall a b : nat, cPairPi2 (cPair a b) = b.\nProof.\nintros.\nunfold cPairPi2 in |- *.\nrewrite cPairProjections1.\nunfold cPair in |- *.\nreplace (searchXY (a + sumToN (a + b))) with (a + b).\napply minus_plus.\nsymmetry  in |- *.\napply cPairProjectionsHelp.\nsimpl in |- *.\napply le_lt_n_Sm.\napply plus_le_compat_r.\napply le_plus_l.\napply le_plus_r.\nQed.\n\nEnd CPair_projections.\n\nSection CPair_Order.\n\nLemma cPairLe1 : forall a b : nat, a <= cPair a b.\nProof.\nintros.\nunfold cPair in |- *.\napply le_plus_l.\nQed.\n\nLemma cPairLe1A : forall a : nat, cPairPi1 a <= a.\nintros.\napply le_trans with (cPair (cPairPi1 a) (cPairPi2 a)).\napply cPairLe1.\nrewrite cPairProjections.\napply le_n.\nQed.\n\nLemma cPairLe2 : forall a b : nat, b <= cPair a b.\nProof.\nintros.\nunfold cPair in |- *.\neapply le_trans.\napply le_plus_r.\napply plus_le_compat_l.\napply le_trans with (a + b).\napply le_plus_r.\napply sumToN1.\nQed.\n\nLemma cPairLe2A : forall a : nat, cPairPi2 a <= a.\nintros.\napply le_trans with (cPair (cPairPi1 a) (cPairPi2 a)).\napply cPairLe2.\nrewrite cPairProjections.\napply le_n.\nQed.\n\nLemma cPairLe3 :\n forall a b c d : nat, a <= b -> c <= d -> cPair a c <= cPair b d.\nProof.\nintros.\nunfold cPair in |- *.\napply le_trans with (a + sumToN (b + d)).\napply plus_le_compat_l.\napply sumToN2.\napply le_trans with (a + d).\napply plus_le_compat_l.\nauto.\napply plus_le_compat_r.\nauto.\napply plus_le_compat_r.\nauto.\nQed.\n\nLemma cPairLt1 : forall a b : nat, a < cPair a (S b).\nProof.\nintros.\nunfold cPair in |- *.\nrewrite (plus_comm a (S b)).\nsimpl in |- *.\nrewrite plus_comm.\nsimpl in |- *.\nrewrite plus_comm.\nunfold lt in |- *.\napply le_n_S.\napply le_plus_l.\nQed.\n\nLemma cPairLt2 : forall a b : nat, b < cPair (S a) b.\nProof.\nintros.\nunfold cPair in |- *.\nsimpl in |- *.\nunfold lt in |- *.\napply le_n_S.\neapply le_trans.\napply le_plus_r.\napply plus_le_compat_l.\napply le_S.\neapply le_trans.\napply le_plus_l.\nrewrite plus_comm.\napply le_plus_l.\nQed.\n\nEnd CPair_Order.\n\nSection code_nat_list.\n\nFixpoint codeList (l : list nat) : nat :=\n  match l with\n  | nil => 0\n  | n :: l' => S (cPair n (codeList l'))\n  end.\n\nLemma codeListInj : forall l m : list nat, codeList l = codeList m -> l = m.\nProof.\nintro.\ninduction l as [| a l Hrecl].\nintros.\ndestruct m as [| n l].\nreflexivity.\ndiscriminate H.\nintros.\ndestruct m as [| n l0].\ndiscriminate H.\nsimpl in H.\nreplace n with a.\nrewrite (Hrecl l0).\nreflexivity.\neapply cPairInj2.\napply eq_add_S.\napply H.\neapply cPairInj1.\napply eq_add_S.\napply H.\nQed.\n\nDefinition codeNth (n m : nat) : nat.\nintros.\nassert nat.\ninduction n as [| n Hrecn].\nexact m.\nexact (cPairPi2 (pred Hrecn)).\nexact (cPairPi1 (pred H)).\nDefined.\n\nLet drop (n : nat) : forall (l : list nat), list nat.\ninduction n as [| n Hrecn].\nexact (fun l => l).\nintros.\napply Hrecn.\ndestruct l.\nexact (nil (A:=nat)).\nexact l.\nDefined.\n\nLemma codeNthCorrect :\n forall (n : nat) (l : list nat), codeNth n (codeList l) = nth n l 0.\nProof.\nunfold codeNth in |- *.\nset\n (A :=\n  fun l : list nat => match l with\n                      | nil => nil (A:=nat)\n                      | _ :: l0 => l0\n                      end) in *.\nassert (forall l : list nat, cPairPi2 (pred (codeList l)) = codeList (A l)).\ndestruct l.\nsimpl in |- *.\napply (cPairProjections2 0 0).\nsimpl in |- *.\napply cPairProjections2.\nassert\n (forall (n : nat) (l : list nat),\n  nat_rec (fun _ : nat => nat) (codeList l)\n    (fun _ Hrecn : nat => cPairPi2 (pred Hrecn)) n = \n  codeList (drop n l)).\nsimple induction n.\nsimpl in |- *.\nreflexivity.\nsimpl in |- *.\nintros.\nrewrite H0.\nrewrite H.\nunfold A in |- *.\nclear H0.\ngeneralize l.\nclear l.\ninduction n0 as [| n0 Hrecn0]; simpl in |- *; intros.\nreflexivity.\ndestruct l.\napply (Hrecn0 nil).\napply Hrecn0.\nintros.\nreplace (nth n l 0) with match drop n l with\n                         | nil => 0\n                         | a :: _ => a\n                         end.\nrewrite H0.\ndestruct (drop n l).\nsimpl in |- *.\napply (cPairProjections1 0 0).\nsimpl in |- *.\napply cPairProjections1.\ngeneralize l.\nclear l.\ninduction n as [| n Hrecn].\ndestruct l; reflexivity.\ndestruct l.\nsimpl in Hrecn.\ndestruct n; apply (Hrecn nil).\nsimpl in |- *.\nauto.\nQed.\n\nLemma codeNthIsPR : isPR 2 codeNth.\nProof.\nintros.\nunfold codeNth in |- *.\napply\n compose2_1IsPR\n  with\n    (g := fun x : nat => cPairPi1 (pred x))\n    (f := fun n m : nat =>\n          nat_rec (fun _ : nat => nat) m\n            (fun _ Hrecn : nat => cPairPi2 (pred Hrecn)) n).\napply\n ind1ParamIsPR\n  with\n    (g := fun m : nat => m)\n    (f := fun _ Hrecn m : nat => cPairPi2 (pred Hrecn)).\napply filter010IsPR with (g := fun x : nat => cPairPi2 (pred x)).\napply compose1_1IsPR.\napply predIsPR.\napply cPairPi2IsPR.\napply idIsPR.\napply compose1_1IsPR.\napply predIsPR.\napply cPairPi1IsPR.\nQed.\n\nEnd code_nat_list.\n\nSection Strong_Recursion.\n\nDefinition evalStrongRecHelp (n : nat) (f : naryFunc (S (S n))) :\n  naryFunc (S n) :=\n  evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil _) (codeList nil))\n    (evalComposeFunc (S (S n)) 2\n       (Vector.cons _ f _\n          (Vector.cons _ (evalProjFunc (S (S n)) n (lt_S _ _ (lt_n_Sn _))) _\n             (Vector.nil _))) (fun a b : nat => S (cPair a b))).\n\nDefinition evalStrongRec (n : nat) (f : naryFunc (S (S n))) :\n  naryFunc (S n) :=\n  evalComposeFunc (S n) 1\n    (Vector.cons _ (fun z : nat => evalStrongRecHelp n f (S z)) _ (Vector.nil _))\n    (fun z : nat => cPairPi1 (pred z)).\n\nLemma evalStrongRecIsPR :\n forall (n : nat) (f : naryFunc (S (S n))),\n isPR _ f -> isPR _ (evalStrongRec n f).\nProof.\nintros.\nunfold evalStrongRec, evalStrongRecHelp in |- *.\nfold (naryFunc (S n)) in |- *.\nset\n (A :=\n  evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil (naryFunc n)) (codeList nil))\n    (evalComposeFunc (S (S n)) 2\n       (Vector.cons (naryFunc (S (S n))) f 1\n          (Vector.cons (naryFunc (S (S n)))\n             (evalProjFunc (S (S n)) n (lt_S n (S n) (lt_n_Sn n))) 0\n             (Vector.nil (naryFunc (S (S n)))))) (fun a b : nat => S (cPair a b))))\n in *.\nassert (isPR (S n) A).\nunfold A in |- *.\nassert (isPR 2 (fun a b : nat => S (cPair a b))).\napply compose2_1IsPR.\napply cPairIsPR.\napply succIsPR.\nassert (isPR 1 (fun z : nat => cPairPi1 (pred z))).\napply compose1_1IsPR.\napply predIsPR.\napply cPairPi1IsPR.\ninduction H as (x, p).\ninduction H0 as (x0, p0).\ninduction H1 as (x1, p1).\nexists\n (primRecFunc n (composeFunc n 0 (PRnil _) zeroFunc)\n    (composeFunc (S (S n)) 2\n       (PRcons _ _ x\n          (PRcons _ _ (projFunc (S (S n)) n (lt_S n (S n) (lt_n_Sn n)))\n             (PRnil _))) x0)).\napply\n extEqualTrans\n  with\n    (evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil _) 0)\n       (evalComposeFunc (S (S n)) 2\n          (Vector.cons _ (evalPrimRec _ x) _\n             (Vector.cons _ (evalProjFunc (S (S n)) n (lt_S n (S n) (lt_n_Sn n))) _\n                (Vector.nil _))) (evalPrimRec _ x0))).\napply extEqualRefl.\napply extEqualPrimRec.\nsimpl in |- *.\napply extEqualRefl.\napply extEqualCompose.\nunfold extEqualVector, extEqualVectorGeneral, Vector.t_rect in |- *.\nrepeat split; auto.\napply extEqualRefl.\nauto.\nassert (isPR (S n) (fun z : nat => A (S z))).\napply compose1_NIsPR.\nauto.\napply succIsPR.\nclear H0.\nassert (isPR 1 (fun z : nat => cPairPi1 (pred z))).\napply compose1_1IsPR.\napply predIsPR.\napply cPairPi1IsPR.\ninduction H0 as (x, p).\ninduction H1 as (x0, p0).\nexists (composeFunc (S n) 1 (PRcons _ _ x0 (PRnil _)) x).\nsimpl in |- *.\nfold (naryFunc n) in |- *.\nintros.\napply extEqualCompose.\nunfold extEqualVector in |- *.\nsimpl in |- *.\nrepeat split.\napply (p0 c).\nauto.\nQed.\n\nLemma computeEvalStrongRecHelp :\n forall (n : nat) (f : naryFunc (S (S n))) (c : nat),\n evalStrongRecHelp n f (S c) =\n compose2 n (evalStrongRecHelp n f c)\n   (fun a0 : nat =>\n    evalComposeFunc n 2\n      (Vector.cons (naryFunc n) (f c a0) 1\n         (Vector.cons (naryFunc n) (evalConstFunc n a0) 0 (Vector.nil (naryFunc n))))\n      (fun a1 b0 : nat => S (cPair a1 b0))).\nProof.\nintros.\nunfold evalStrongRecHelp at 1 in |- *.\nsimpl in |- *.\nfold (naryFunc n) in |- *.\ninduction (eq_nat_dec n (S n)).\nelim (lt_not_le n (S n)).\napply lt_n_Sn.\nrewrite <- a.\nauto.\ninduction (eq_nat_dec n n).\nreplace\n (evalPrimRecFunc n (evalComposeFunc n 0 (Vector.nil (naryFunc n)) 0)\n    (fun a0 a1 : nat =>\n     evalComposeFunc n 2\n       (Vector.cons (naryFunc n) (f a0 a1) 1\n          (Vector.cons (naryFunc n) (evalConstFunc n a1) 0 (Vector.nil (naryFunc n))))\n       (fun a2 b0 : nat => S (cPair a2 b0))) c) with\n (evalStrongRecHelp n f c).\nreflexivity.\nunfold evalStrongRecHelp at 1 in |- *.\nsimpl in |- *.\nfold (naryFunc n) in |- *.\ninduction (eq_nat_dec n (S n)).\nelim b.\nauto.\ninduction (eq_nat_dec n n).\nreflexivity.\nelim b1.\nauto.\nelim b0.\nauto.\nQed.\n\nLet listValues (f : naryFunc 2) (n : nat) : list nat.\nintros.\ninduction n as [| n Hrecn].\nexact nil.\nexact (evalStrongRec _ f n :: Hrecn).\nDefined.\n\nLemma evalStrongRecHelp1 :\n forall (f : naryFunc 2) (n m : nat),\n m < n -> codeNth (n - S m) (evalStrongRecHelp _ f n) = evalStrongRec _ f m.\nProof.\nassert\n (forall (f : naryFunc 2) (n : nat),\n  evalStrongRecHelp _ f n = codeList (listValues f n)).\nintros.\ninduction n as [| n Hrecn].\nsimpl in |- *.\nunfold evalStrongRecHelp in |- *.\nsimpl in |- *.\nreflexivity.\nunfold evalStrongRecHelp in |- *.\nsimpl in |- *.\nunfold evalStrongRecHelp in Hrecn.\nsimpl in Hrecn.\nrewrite Hrecn.\nunfold evalStrongRec in |- *.\nsimpl in |- *.\nrewrite cPairProjections1.\nrewrite Hrecn.\nreflexivity.\nintros.\nrewrite H.\nrewrite codeNthCorrect.\ninduction n as [| n Hrecn].\nelim (lt_n_O _ H0).\ninduction (le_lt_or_eq _ _ H0).\nrewrite <- minus_Sn_m.\nsimpl in |- *.\nrewrite Hrecn.\nreflexivity.\napply lt_S_n.\nauto.\napply lt_n_Sm_le.\nauto.\ninversion H1.\nrewrite <- minus_n_n.\nclear H3 H1 Hrecn H0 m.\nsimpl in |- *.\nreflexivity.\nQed.\n\nLemma evalStrongRecHelpParam :\n forall (a n c : nat) (f : naryFunc (S (S (S a)))),\n extEqual a (evalStrongRecHelp (S a) f n c)\n   (evalStrongRecHelp a (fun x y : nat => f x y c) n).\nProof.\nintros.\nunfold evalStrongRecHelp in |- *.\neapply extEqualTrans.\napply extEqualSym.\napply evalPrimRecParam.\nassert\n (extEqual (S a)\n    (evalPrimRecFunc a\n       (evalComposeFunc (S a) 0 (Vector.nil (naryFunc (S a))) (codeList nil) c)\n       (fun x y : nat =>\n        evalComposeFunc (S (S (S a))) 2\n          (Vector.cons (naryFunc (S (S (S a)))) f 1\n             (Vector.cons (naryFunc (S (S (S a))))\n                (evalProjFunc (S (S (S a))) (S a)\n                   (lt_S (S a) (S (S a)) (lt_n_Sn (S a)))) 0\n                (Vector.nil (naryFunc (S (S (S a)))))))\n          (fun a0 b : nat => S (cPair a0 b)) x y c))\n    (evalPrimRecFunc a\n       (evalComposeFunc a 0 (Vector.nil (naryFunc a)) (codeList nil))\n       (evalComposeFunc (S (S a)) 2\n          (Vector.cons (naryFunc (S (S a))) (fun x y : nat => f x y c) 1\n             (Vector.cons (naryFunc (S (S a)))\n                (evalProjFunc (S (S a)) a (lt_S a (S a) (lt_n_Sn a))) 0\n                (Vector.nil (naryFunc (S (S a))))))\n          (fun a0 b : nat => S (cPair a0 b))))).\napply\n (extEqualPrimRec a\n    (evalComposeFunc (S a) 0 (Vector.nil (naryFunc (S a))) (codeList nil) c)).\nsimpl in |- *.\napply extEqualRefl.\nsimpl in |- *.\nfold (naryFunc a) in |- *.\ninduction\n (sumbool_rec\n    (fun _ : {a = S a} + {a <> S a} => {S a = S (S a)} + {S a <> S (S a)})\n    (fun a0 : a = S a => left (S a <> S (S a)) (f_equal S a0))\n    (fun b : a <> S a => right (S a = S (S a)) (not_eq_S a (S a) b))\n    (eq_nat_dec a (S a))).\nelim (lt_not_le (S a) (S (S a))).\napply lt_n_Sn.\nrewrite <- a0.\nauto.\ninduction\n (sumbool_rec (fun _ : {a = a} + {a <> a} => {S a = S a} + {S a <> S a})\n    (fun a0 : a = a => left (S a <> S a) (f_equal S a0))\n    (fun b0 : a <> a => right (S a = S a) (not_eq_S a a b0)) \n    (eq_nat_dec a a)).\ninduction (eq_nat_dec a (S a)).\nelim (lt_not_le a (S a)).\napply lt_n_Sn.\nrewrite <- a1.\nauto.\ninduction (eq_nat_dec a a).\nintros.\napply extEqualRefl.\nelim b1.\nauto.\nelim b0.\nauto.\napply (H n).\nQed.\n\nLemma evalStrongRecHelp2 :\n forall (a : nat) (f : naryFunc (S (S a))) (n m : nat),\n m < n ->\n extEqual _\n   (evalComposeFunc _ 1 (Vector.cons _ (evalStrongRecHelp _ f n) 0 (Vector.nil _))\n      (fun b : nat => codeNth (n - S m) b)) (evalStrongRec _ f m).\nProof.\nintro.\nfold (naryFunc a) in |- *.\ninduction a as [| a Hreca].\nsimpl in |- *.\napply evalStrongRecHelp1.\nsimpl in |- *.\nintros.\nfold (naryFunc a) in |- *.\nset (g := fun x y : nat => f x y c) in *.\nassert\n (extEqual a\n    (evalComposeFunc a 1\n       (Vector.cons (naryFunc a) (evalStrongRecHelp a g n) 0 (Vector.nil (naryFunc a)))\n       (fun b : nat => codeNth (n - S m) b)) (evalStrongRec a g m)).\napply Hreca.\nauto.\nunfold g in H0.\nclear g Hreca.\napply extEqualTrans with (evalStrongRec a (fun x y : nat => f x y c) m).\napply\n extEqualTrans\n  with\n    (evalComposeFunc a 1\n       (Vector.cons (naryFunc a) (evalStrongRecHelp a (fun x y : nat => f x y c) n)\n          0 (Vector.nil (naryFunc a))) (fun b : nat => codeNth (n - S m) b)).\napply extEqualCompose.\nunfold extEqualVector in |- *.\nsimpl in |- *.\nrepeat split.\napply evalStrongRecHelpParam.\napply extEqualRefl.\napply H0.\nunfold evalStrongRec in |- *.\nsimpl in |- *.\nfold (naryFunc a) in |- *.\napply extEqualCompose.\nunfold extEqualVector in |- *.\nsimpl in |- *.\nrepeat split.\napply extEqualSym.\napply evalStrongRecHelpParam.\napply extEqualRefl.\nQed.\n\nLemma callIsPR :\n forall g : nat -> nat,\n isPR 1 g -> isPR 2 (fun a recs : nat => codeNth (a - S (g a)) recs).\nProof.\nintros.\napply\n compose2_2IsPR\n  with (f := fun a recs : nat => a - S (g a)) (g := fun a recs : nat => recs).\napply filter10IsPR with (g := fun a : nat => a - S (g a)).\napply\n compose1_2IsPR with (f := fun a : nat => a) (f' := fun a : nat => S (g a)).\napply idIsPR.\napply compose1_1IsPR.\nassumption.\napply succIsPR.\napply minusIsPR.\napply pi2_2IsPR.\napply codeNthIsPR.\nQed.\n\nEnd Strong_Recursion.\n\nLemma div2IsPR : isPR 1 div2.\nProof.\nassert\n (isPR 1\n    (evalStrongRec 0\n       (fun n recs : nat =>\n        switchPR n\n          (switchPR (pred n) (S (codeNth (n - S (pred (pred n))) recs)) 0) 0))).\napply evalStrongRecIsPR.\nassert (isPR 2 (fun n recs : nat => 0)).\nexists (composeFunc 2 0 (PRnil _) zeroFunc).\nsimpl in |- *.\nauto.\napply\n compose2_3IsPR\n  with\n    (f1 := fun n recs : nat => n)\n    (f2 := fun n recs : nat =>\n           switchPR (pred n) (S (codeNth (n - S (pred (pred n))) recs)) 0)\n    (f3 := fun n recs : nat => 0).\napply pi1_2IsPR.\napply\n compose2_3IsPR\n  with\n    (f1 := fun n recs : nat => pred n)\n    (f2 := fun n recs : nat => S (codeNth (n - S (pred (pred n))) recs))\n    (f3 := fun n recs : nat => 0).\napply filter10IsPR.\napply predIsPR.\napply\n compose2_1IsPR\n  with (f := fun n recs : nat => codeNth (n - S (pred (pred n))) recs).\napply\n compose2_2IsPR\n  with\n    (f := fun n recs : nat => n - S (pred (pred n)))\n    (g := fun n recs : nat => recs).\napply filter10IsPR with (g := fun n : nat => n - S (pred (pred n))).\napply\n compose1_2IsPR\n  with (f := fun n : nat => n) (f' := fun n : nat => S (pred (pred n))).\napply idIsPR.\napply compose1_1IsPR with (f := fun n : nat => pred (pred n)).\napply compose1_1IsPR; apply predIsPR.\napply succIsPR.\napply minusIsPR.\napply pi2_2IsPR.\napply codeNthIsPR.\napply succIsPR.\nauto.\napply switchIsPR.\nauto.\napply switchIsPR.\ninduction H as (x, p).\nexists x.\neapply extEqualTrans.\napply p.\nclear p x.\nsimpl in |- *.\nintros.\nset\n (f :=\n  fun n recs : nat =>\n  switchPR n (switchPR (pred n) (S (codeNth (n - S (pred (pred n))) recs)) 0)\n    0) in *.\nelim c using ind_0_1_SS.\nunfold evalStrongRec in |- *.\nsimpl in |- *.\nauto.\nunfold evalStrongRec in |- *.\nsimpl in |- *.\napply cPairProjections1.\nintros.\nunfold evalStrongRec in |- *.\nunfold evalComposeFunc in |- *.\nunfold evalOneParamList in |- *.\nrewrite computeEvalStrongRecHelp.\nunfold f at 2 in |- *.\nset (A := S (S n) - S (pred (pred (S (S n))))) in *.\nsimpl in |- *.\nrewrite cPairProjections1.\napply eq_S.\nrewrite <- H.\nunfold A in |- *.\napply evalStrongRecHelp1.\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/goedel/cPair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809829, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7894759248317373}}
{"text": "Lemma mult_0_r : forall n: nat,\n                   n * 0 = 0.\nProof.\n  intros n.\n  induction n.\n  + simpl.\n    reflexivity.\n  + simpl.\n    apply IHn.\nQed.\n\n\nLemma add_swap: forall l n m:nat, l + (n + m) = n + (l + m).\n- intros.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHl.\n  assert(I: forall m n: nat, S(m + n) = m + S n).\n  * intros m1 m2.\n    induction m1.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite IHm1.\n    reflexivity.\n  * rewrite I.\n    reflexivity.\nQed.\n\n\nLemma add_remove_l: forall j k l m n:nat,\n                      j + k = l + m ->\n                      n + j + k = n + l + m.\nProof.\n  intros j k l m n.\n  intros H.\n  induction n.\n  + simpl.\n    apply H.\n  + simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nLemma mult_succ : forall m n:nat,\n                    n * S m = n + n * m.\nProof.\n  intros m n.\n  induction n.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHn.\n    - assert(H: (m + (n + n*m)) = (n + (m + n * m))).\n      rewrite add_swap.\n      reflexivity.\n      rewrite H.\n      reflexivity.\nQed.\n\n\nTheorem mult_plus_distr_r : forall m n p: nat,\n                              (n + m) * p = n * p + m * p.\nProof.\n  intros m n p.\n  induction p.\n  + rewrite mult_0_r.\n    rewrite mult_0_r.\n    rewrite mult_0_r.\n    reflexivity.\n  + rewrite mult_succ.\n    rewrite mult_succ.\n    rewrite mult_succ.\n    rewrite IHp.\n    assert (H: m + (n * p + m *p) = n * p + (m + m * p)).\n    - rewrite add_swap.\n      reflexivity.\n    - apply add_remove_l.\n      apply add_swap.\nQed.\n\nTheorem mult_plus_distr_l : forall m n p: nat,\n                              p * (n + m) = p *n + p * m.\nProof.\n  intros m n p.\n  induction p.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHp.\n    assert(H: m + (p * n + p * m) = p * n + (m + p * m)).\n    - rewrite add_swap.\n      reflexivity.\n    - apply add_remove_l.\n      apply add_swap.\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 m.\n  + simpl.\n    rewrite mult_0_r.\n    simpl.\n    reflexivity.\n  + simpl.\n    rewrite mult_succ.\n    rewrite mult_plus_distr_r.\n    rewrite mult_plus_distr_l.\n    rewrite IHm.\n    reflexivity.\nQed.\n\nLemma add_succ : forall n m: nat,\n                   n + S m = S (n + m).\nProof.\n  intros n m.\n  induction n.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\n\nTheorem plus_swap' : forall n m p: nat,\n                       n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  induction n.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHn.\n    rewrite add_succ.\n    reflexivity.\nQed.\n\nInductive bin: Type :=\n| O  : bin\n| B  : bin -> bin\n| BPlus : bin -> bin.\n\nFixpoint incb(b: bin) : bin :=\n  match b with\n    | O => BPlus O\n    | B b' => BPlus b'\n    | BPlus b' => B (incb b')\n  end.\n\n\nFixpoint to_nat (b: bin) : nat :=\n  match b with\n    | O => 0\n    | B b' => (to_nat b') * 2\n    | BPlus b' => (to_nat b') * 2 + 1\n  end.\n\nLemma add_0_r: forall n: nat,\n                 n + 0 = n.\nProof.  \n  intros n.\n  induction n.\n  + reflexivity.\n  + simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem to_nat_comm: forall b: bin,\n         to_nat (incb b) = S (to_nat b).\nProof.\n  intros b.\n  induction b.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite add_succ.\n    rewrite add_0_r.\n    reflexivity.\n  + simpl.\n    rewrite add_succ.\n    rewrite add_0_r.\n    rewrite IHb.\n    simpl.\n    reflexivity.\nQed.\n\nFixpoint to_bin (n :nat) :bin :=\n  match n with\n    | 0 => O\n    | S n => incb (to_bin n)\n  end.\n\nTheorem nat_bin_nat: forall n: nat,\n                       to_nat (to_bin n) = n.\nProof.\n  intros n.\n  induction n.\n  + simpl. reflexivity.\n  + simpl.\n    rewrite to_nat_comm.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nDefinition id_bin (b: bin): bin :=\n  to_bin (to_nat b).\n\nTheorem bin_nat_bin: forall b: bin,\n                       to_bin (to_nat b) = b.\nProof.\n  intros b.\n  induction b.\n  + simpl.\n    reflexivity.\n  + simpl.\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/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.789462442547217}}
{"text": "(* Exercise coq_nat_11 *)\n\n(* Do you know that having stamps of nominals 3 and 5 you can\n   pay any value greater or equal than 8? \n   Below is a Coq specification of this statemant - can you\n   prove it? *)\nRequire Import Arith.\n\n(* Hint: for arithmetical reasoning you may try to use the \n         'lia' tactic. If you do that you will only get\n\t Correct for this exercise (and not Solved), as this \n\t is one of the powerful automated Coq tactics, that \n\t are in principle not allowed to be used for solving\n\t those exercises. In this case, however, it is ok\n\t to use lia.\n\t \n   Remark: if afterwards you decide to try to prove it without\n           the use of lia, it should give you a good idea\n\t   of how helpful such automated tactics can be!\n*)   \nRequire Import Lia.\n\nLemma stamps : forall i, exists v3, exists v5, i + 8 = 3*v3 + 5*v5.\n\nProof.\nintros.\ninduction i.\nexists 1.\nexists 1.\nsimpl.\nreflexivity.\n(* Remove 3*3 and add 2* 5*)\nQed.\n\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_11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7894624419896845}}
{"text": "Require Import ZArith.\nOpen Scope Z_scope.\n\nDefinition square (a b:Z) := a^2 = b.\nDefinition pre_sqrt (x n:Z) := x^2 <= n.\nDefinition sqrt (x n:Z) := x^2 <= n < (x+1)^2.\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/context_sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7892391032074582}}
{"text": "(**\nA Gentle Introduction to Type Classes and Relations in Coq\nの Chapter 2 An Introductory Example: Computing x^n\nの抜萃をもとに説明のための修正を加えました。\n\n@suharahiromichi\n\n2017_09_10\n*)\n\nSet Implicit Arguments.\n\nRequire Import Arith.                       (* for ring. *)\nRequire Import ZArith.\nRequire Import Div2.\nRequire Import Program.\n\n(** Monoid モノイド\n- carrier (台) A\n- binary, associative operation 'dot' on A\n- neutral element 1 ∈ A for 'dot'\n *)\nClass Monoid {A : Type} (dot : A -> A -> A) (one : A) : Type :=\n  {\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(* 自然数 (nat,*,1) *)\n(* **************** *)\nProgram Instance Mult : Monoid mult 1%nat.\nObligation 1.                               (* x * (y * z) = x * y * z *)\nProof.\n  ring.\nQed.\nObligation 3.                               (* x * 1 = x *)\nProof.\n  ring.\nQed.\n\n(* ************ *)\n(* 整数 (Z,*,1) *)\n(* ************ *)\nOpen Scope Z_scope.                         (* 以降、自然数は 1%nat のように。 *)\n\nProgram Instance ZMult : Monoid Zmult 1.\nObligation 1.                               (* x * (y * z) = x * y * z *)\nProof.\n  ring.\nQed.\nObligation 2.                               (* 1 * x = x *)\nProof.\n  now destruct x.\nQed.\nObligation 3.                               (* x * 1 = x *)\nProof.\n  ring.\nQed.\n\n(* 2x2 行列 Matrix の定義 *)\nSection M2_def.\n  \n  Variable (A : Type).\n  Variable (zero one : A).\n  Variable (plus mult : A -> A -> A).\n  \n  (*\n  (* ring タクティクのために ring_theory を使う場合。 *)\n  Variable (minus : A -> A -> A).\n  Variable (sym : A -> A).\n  Variable rth : ring_theory zero one plus mult minus sym (@eq A).\n  Add Ring Aring : rth.\n   *)\n  (* ring タクティクのために semi_ring_theory を使う場合。 *)  \n  Variable sth : semi_ring_theory zero one plus mult (@eq A).\n  Add Ring Aring : sth.\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  Structure M2 : Type := {c00 : A;  c01 : A;\n                          c10 : A;  c11 : A}.\n  \n  Definition Id2 : M2 := Build_M2 1 0 0 1.\n  \n  Definition 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  Lemma 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'.\n  Proof. \n    intros; now f_equal.\n  Qed.\n  \n  Program Instance M2_Monoid : Monoid M2_mult Id2.\n  Obligation 1.\n  (*\n  M2_mult plus mult x (M2_mult plus mult y z) =\n   M2_mult plus mult (M2_mult plus mult x y) z\n   *)\n  Proof.\n    destruct x; destruct y; destruct z; simpl.\n    unfold M2_mult; apply M2_eq_intros; simpl; ring.\n  Qed.\n  Obligation 2.                             (* M2_mult plus mult (Id2 0 1) x = x *)\n    destruct x; simpl;\n    unfold M2_mult; apply M2_eq_intros; simpl; ring.\n  Qed.\n  Obligation 3.                             (* M2_mult plus mult x (Id2 0 1) = x *)\n    destruct x; simpl;\n    unfold M2_mult; apply M2_eq_intros; simpl; ring.\n  Qed.\n\n  Check M2_Monoid : Monoid M2_mult Id2.\nEnd M2_def.\nCheck M2_Monoid : forall (A : Type) (zero one : A) (plus mult : A -> A -> A),\n    semi_ring_theory zero one plus mult eq ->\n    Monoid (M2_mult plus mult) (Id2 zero one).\n\n(* ************* *)\n(* 自然数2x2行列 *)\n(* ************* *)\nLemma nat_sth : semi_ring_theory 0%nat 1%nat plus mult (@eq nat).\nProof.\n  split.\n  - exact plus_0_l.\n  - exact plus_comm.\n  - exact plus_assoc.\n  - exact mult_1_l.\n  - exact mult_0_l.\n  - exact mult_comm.\n  - exact mult_assoc.\n  - exact mult_plus_distr_r.\nQed.\n\nInstance M2nat : Monoid _ _ := M2_Monoid nat_sth.\nCheck Monoid (M2_mult plus mult) (Id2 0%nat 1%nat). (* 左辺 *)\nCheck @M2_Monoid nat 0%nat 1%nat plus mult nat_sth. (* 右辺 *)\n\n(* *********** *)\n(* 整数2x2行列 *)\n(* *********** *)\nCheck Zth : ring_theory 0 1 Z.add Z.mul Z.sub Z.opp eq.\n(* https://coq.inria.fr/library/Coq.setoid_ring.InitialRing.html で定義 *)\n(* ./plugins/setoid_ring/InitialRing.v *)\n\nLemma Z_sth : semi_ring_theory 0 1 Z.add Z.mul eq.\nProof.\n  split.\n  - exact Z.add_0_l.\n  - exact Z.add_comm.\n  - exact Z.add_assoc.\n  - exact Z.mul_1_l.\n  - exact Z.mul_0_l.\n  - exact Z.mul_comm.\n  - exact Z.mul_assoc.\n  - exact Z.mul_add_distr_r.\nQed.\n\nInstance M2Z : Monoid _ _ := M2_Monoid Z_sth.\nCheck Monoid (M2_mult Z.add Z.mul) (Id2 0 1). (* 左辺 *)\nCheck @M2_Monoid Z 0 1 Z.add Z.mul Z_sth.     (* 右辺 *)\n\n(***************)\n(* ベキ乗の定義 *)\n(***************)\nGeneralizable Variables A dot one.\n\nFixpoint power `{Monoid A dot one} (a : A) (n : nat) := (* 「`」 でコンテキスト *)\n  match n with\n    | 0%nat => one\n    | S p => dot a (power a p)\n  end.\n\nSection binary_power. \n  Context `{M : Monoid A dot one}.          (* コンテキスト *)\n  \n  Program Fixpoint binary_power_mult (acc : A) (x : A) (n : nat) {measure n} : A :=\n    (* Implicit generalization によって、\n       (A:Type) (dot:A->A->A) (one:A) (M: @Monoid A dot one)\n       が省かれている。 *)\n    (* acc * (x ** n) *) \n    let M' := M in\n    match n with\n      | 0%nat => acc\n      | _ => if  Even.even_odd_dec n\n             then\n               binary_power_mult  acc (dot x x) (div2 n)\n             else\n               binary_power_mult  (dot acc  x) (dot  x  x) (div2 n)\n    end.\n  Obligations.\n  Next Obligation.                          (* Obligation 1 *)\n    set (M' := M); apply lt_div2.\n    apply neq_0_lt in H.\n    apply H.\n    Defined.\n  Next Obligation.                          (* Obligation 2 と 3 *)\n    set (M' := M); apply lt_div2; auto with arith.\n    Defined.\n  Check binary_power_mult.                  (* A -> A -> nat -> A *)\n(*\n  証明を1行にまとめると、以下になる。Next Obligation も要らないので、注意。\n  Solve Obligations using program_simpl; set (M' := M); apply lt_div2; auto with arith.\n *)\n\n  Import WfExtensionality.\n  Lemma binary_power_mult_equation (acc x : A) (n : nat) :\n    binary_power_mult acc x n =\n    match n with\n      | 0%nat => acc\n      | _ => if Even.even_odd_dec n\n             then\n               binary_power_mult acc (dot x x) (div2 n)\n             else\n               binary_power_mult (dot acc  x) (dot  x  x) (div2 n)\n    end.\n  Proof.\n    unfold binary_power_mult at 1.\n    on_call binary_power_mult_func\n            ltac:(fun c => \n                    unfold_sub @binary_power_mult_func c;\n                    fold binary_power_mult_func).\n    simpl. destruct n; reflexivity.\n  Qed.\n  \n  Definition binary_power x n := binary_power_mult one x n.\n  \nEnd binary_power.\n\nCheck binary_power : Z -> nat -> Z.\nCheck binary_power : nat -> nat -> nat.\nCheck binary_power : M2 Z -> nat -> M2 Z.\nCheck binary_power : M2 nat -> nat -> M2 nat.\n\n(****************)\n(* 整数のベキ乗 *)\n(****************)\nCompute binary_power 2%nat 5.               (* = 32%nat : nat *)\nCompute binary_power 2 5.                   (* = 32 : Z *)\nCompute binary_power 2 100.\n(* = 1267650600228229401496703205376 : Z *)\n\n(************************)\n(* 整数の2x2行列のベキ乗 *)\n(************************)\nCompute power (Build_M2 1 1 1 0) 40.\nCompute binary_power (Build_M2 1 1 1 0) 40.\n(* = {|\n       c00 := 165580141;\n       c01 := 102334155;\n       c10 := 102334155;\n       c11 := 63245986 |}\n     : M2 Z\n *)\n\nDefinition fibonacci (n : nat) :=\n  c00 (power (Build_M2 1 1 1 0) n).\nCompute fibonacci 20.                       (* = 10946 : Z *)\n\n(* ********************************************* *)\n(* power と binary_power が等価なことを証明する。 *)\n(* ********************************************* *)\nSection About_power.\n  \n  Require Import Arith.\n  Context `(M : Monoid A dot one ).\n  \n  Ltac 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  (* \"+\" はnat のplusである。power : A -> nat -> A だから。 *)\n  \n  Lemma power_x_plus :\n    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 :\n    forall x n p, x ** n * x ** p = x ** p * x ** n. \n  Proof.\n    intros x n p; power_simpl; rewrite (plus_comm n p); trivial.\n  (* plus_comm は、nat のそれ。 *)\n  Qed.\n  \n  Lemma power_commute_with_x :\n    forall x 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 :\n    forall x n p,  (x ** n) ** p = x ** (p * n).\n  Proof.\n    induction p; simpl; [| rewrite power_x_plus; rewrite IHp]; trivial.\n  Qed.\n  \n  Lemma power_S :\n    forall x n, x *  x ** n = x ** S n.\n  Proof.\n    intros; simpl; auto.\n  Qed.\n  \n  Lemma sqr : forall x, x ** 2 =  x * x.\n  Proof.\n    simpl; intros; monoid_simpl; trivial.\n  Qed.\n  \n  Ltac 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 :\n    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 binary_power_mult_ok :\n    forall n a x,  binary_power_mult a x n = a * x ** n.\n  Proof.\n    intro n; pattern n;apply lt_wf_ind.\n    clear n; intros n Hn; destruct n.\n    intros; simpl; monoid_simpl; trivial.\n    intros; rewrite binary_power_mult_equation. \n    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.\n  Qed.\n  \n  Lemma binary_power_ok :\n    forall (x : A) (n : nat), binary_power x n = x ** n.\n  Proof.\n    intros n x; unfold binary_power; rewrite binary_power_mult_ok;\n    monoid_simpl; auto.\n  Qed.\n  About binary_power_ok.\nEnd About_power.\n\n(* ****************************** *)\n(** 可換モノイド、アーベルモノイド *)\n(* ****************************** *)\n(** モノイド M に可換則を追加して得られる。 *)\nClass Abelian_Monoid `(M : Monoid ):=\n  {\n    dot_comm : forall x y, dot x y = dot y x\n  }.\nPrint Abelian_Monoid.\n\n(**\nZMult_Abelian は、\nZMultモノイド（整数積のモノイド）に可換則を追加したもの。\n *)\nInstance ZMult_Abelian : Abelian_Monoid ZMult.\nProof.\n  split. \n  exact Zmult_comm.\nQed.\n\n(*************************************)\n(* (x * y)^n = x^n * y^n を証明する。 *)\n(*************************************)\nSection Power_of_dot.\n  Context `{M : Monoid A} {AM : Abelian_Monoid M}.\n \n  Theorem power_of_mult :\n    forall n x y, power (dot x y)  n =  dot (power x n) (power y n). \n  Proof.\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.\n  Qed.\nEnd Power_of_dot.\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/coq_gitcrc_2_Monoid_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7892059227921617}}
{"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. *)\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. *)\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.\nintros n m H.\nsplit.\n-\ndestruct n.\nreflexivity.  \ninversion H.\n-\ndestruct m.\nreflexivity.\nSearch (?n + ?m).\nrewrite <- plus_n_Sm in H.\ninversion H.\nQed.\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  (* 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\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].\n  apply HQ.  Qed.\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  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.\nsplit.\napply HP.\napply HQ.  \napply HR.\nQed.\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  (* WORKED IN CLASS *)\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.\ninduction n.\n  simpl. left. reflexivity.\ninduction m.\n  simpl. right. reflexivity.\nintros H.\ninversion H.\nQed.\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\nintros P Q [HP | HQ].\nright.\napply HP.\nleft.\napply HQ.\nQed.\n\n(* ================================================================= *)\n(** ** Falsehood and Negation *)\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\n    we assume a contradiction, then any other proposition can be\n    derived.  Following this intuition, we could define [~ P] (\"not\n    [P]\") as [forall Q, P -> Q].  Coq actually makes a slightly\n    different choice, defining [~ P] as [P -> False], where [False] is\n    a specific 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.\nintros P NP Q PP.\ndestruct NP.\napply PP.\nQed.\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 H NQ.\n  unfold not.\n  intros PP.\n  unfold not in NQ.\n  apply NQ in H.\n  inversion H.\n  apply PP.\n  Qed.  \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.\n  intros P H.\n  inversion H.  \n  apply H1 in H0.\n  inversion H0.  \n  Qed.\n\n  (** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\nDefinition informal_not_PNP_TODO := 0.\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.\nsplit.\ntrivial.\ntrivial.\nQed.  \n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\nintros P Q R PQ QR.\ndestruct QR.\ndestruct PQ.\nsplit.\nintros PP.\napply H1 in PP.\napply H in PP. \napply PP.\nintros RR.\napply H0 in RR.\napply H2 in RR.\napply RR.\nQed.\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.\nintros P Q R.\nsplit.\n-\nintros H.\ndestruct H.\n+\nsplit.\n*\nleft.\ntrivial.\n*  \nleft.\ntrivial.\n+\nsplit.\n*\nright.\napply H.  \n*\nright.\napply H.\n-\nintros H.\ninversion H as [[HP1 | HQ] [HP2 | HR]].  \nleft. apply HP1.\nleft. apply HP1.\nleft. apply HP2.\nright.\nsplit.\ntrivial.\ntrivial.\nQed.\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 Coq library that supports it: *)\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, recommended (dist_not_exists)  *)\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.\nintros X P x. \nunfold not.\nintros x0.\ninversion x0. destruct H.\napply x.\nQed.\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.\nintros X P Q.\nsplit.\n-\nintros x.\ninversion x.\ndestruct H.\n+\nleft.\nexists x0.\napply H.\n+\nright.\nexists x0.\nexact H.\n-\nintros H.\ndestruct H.\n+\ninversion H.\nexists x.\nleft.\nexact H0.  \n+\ninversion H.\nexists x.  \nright.\nexact H0.\nQed.\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 taking an element and a list and returning a proposition: *)\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 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\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\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.\n    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)  *)\n Lemma 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.\nintros A B f l y.\nsplit.\n-\nintros H.\ninduction l.\n+\nsimpl in H.\ninversion H.\n+\nsimpl in H.\ndestruct H as [H1 | H2].\n*\n  exists x.\n  split.\n  exact H1.\n  simpl.\n  left.\n  reflexivity.\n*\n  apply IHl in H2.\n  destruct H2 as [x2 H2].\n  exists x2.\n  split.\n  apply proj1 in H2. exact H2.\n  apply proj2 in H2. simpl. right. exact H2.\n-\nintros H.\ninduction l.  \n+\n  simpl in H.\n  simpl.\n  destruct H.\n  apply proj2 in H. exact H.\n+\n  simpl.\n  destruct H.\n  destruct H.\n  destruct H0.\n  rewrite <- H0 in H.\n  left. exact H.\n  right. apply IHl. exists x0. split. exact H. exact H0.\nQed.\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.\nintros A l1 l2 a.\nsplit.\n-\nintros H. induction l1.\n+\nsimpl. simpl in H. right. exact H.\n+  \nsimpl. simpl in H. destruct H.\n*\nleft. left. exact H.\n*\napply IHl1 in H.\ndestruct H.\nleft. right. exact H.\nright. exact H.\n-\nintros H.\ninduction l1.\n+\nsimpl in H. simpl. destruct H.\ninversion H. exact H.\n+\nsimpl. simpl in H. apply or_assoc in H. destruct H.\n*\nleft. exact H.\n*\nright. apply IHl1. exact H.\nQed.  \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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\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 :=\nfun x => if (oddb x) then Podd x else Peven x.  \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  unfold oddb.\n  intros odd.\n  intros even.\ninduction n.  \n-\nunfold combine_odd_even.\nunfold oddb.\napply even.\nsimpl.\nreflexivity.\n-\nunfold combine_odd_even.\nunfold oddb.\ndestruct evenb.\n+\napply even.\nsimpl.  \nreflexivity.\n+\napply odd.\nsimpl.\nreflexivity.  \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.\nintros Podd Peven n. \nintros H odd.\nunfold combine_odd_even in H.\nrewrite odd in H.\nexact 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.\nintros Podd Peven n.\nintros H odd.\nunfold combine_odd_even in H.\nrewrite odd in H.\nexact H.\nQed.\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 x y z, x + (y + z) = (z + y) + x.\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 x y z.\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 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\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 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(** 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\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    Fortunately, 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_correct)  *)\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 the two definitions are indeed equivalent. *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\nintros X.\napply  functional_extensionality.\nintros x.\ninduction x.\n-\nunfold tr_rev.\nsimpl.\nreflexivity.\n-\nAbort.\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    Of course, it would be very strange if these two characterizations\n    of evenness did not describe the same set of natural numbers!\n    Fortunately, we can prove that they do... *)\n\n(** We first need two helper lemmas. *)\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\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  Check @evenb_S.\n  intros n.\n  exists n.\n  induction n.\n  -\nsimpl. reflexivity.\n-\nrewrite evenb_S.\nsimpl.\ninversion IHn.\nAbort.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* FILL IN HERE *) \n\n(** Theorem 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\n(** In view of this theorem, we say that the boolean\n    computation [evenb n] _reflects_ the logical proposition \n    [exists k, n = double k]. *)\n\n(** 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].  Again, 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_.\n\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little direct help in the middle of a proof\n    involving [n] and [m]; however, if we convert the statement to the\n    equivalent form [n = m], we can rewrite with it. *)\n\n(** The case of even numbers is also interesting.  Recall that,\n    when proving the backwards direction of [even_bool_prop] (i.e.,\n    [evenb_double], going from the propositional to the boolean\n    claim), we used a simple induction on [k].  On the other hand, the\n    converse (the [evenb_double_conv] exercise) required a clever\n    generalization, since we can't directly prove [(exists k, n =\n    double k) -> evenb n = true]. *)\n\n(** For these examples, the propositional claims are more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects 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\n(** Example 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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\nintros b1 b2.\nsplit.\n-\nintros H.\nsplit.\ndestruct b1.\nreflexivity.\ninversion H.\ndestruct b2.\nreflexivity.\nrewrite <- H.\nrewrite andb_false_r in H.\ninversion H.\n-\nintros H.\ndestruct H.\nrewrite H.\nrewrite H0.\nreflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\nintros b1 b2.\nsplit.  \n-\nintros H.\ndestruct b1.\n+\nleft. reflexivity.\n+\nright. apply H.\n-\nintros H.\ndestruct H.\n+ rewrite H. reflexivity.  \n+ rewrite H.\nSearch (?a || ?b).\nassert (or_com: forall (b:bool),  b|| true = true || b).\n*\nintros b. destruct b. reflexivity. reflexivity.\n*\nrewrite or_com. reflexivity.\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.\nintros x y.\nunfold not.\nsplit.\n-\nintros H H2.\napply beq_nat_true_iff in H2.\nrewrite H2 in H.\ninversion H.\n-\nintros H.\ninduction x.\n+\ninduction y.\nexfalso.\napply H.  \nreflexivity.\nsimpl.\nreflexivity.\n+\ninduction y.\nsimpl. reflexivity.\nsimpl.\ndestruct (beq_nat x y) eqn:HH.\nexfalso. apply H. apply f_equal. apply beq_nat_true_iff. apply HH.\nreflexivity.\nQed.\n\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  | [], [] => true\n  | [], h::tl => false\n  | h::tl, [] => false\n  | h1::tl1, h2::tl2 => if (beq h1 h2) then beq_list beq tl1 tl2 else 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 (* FILL IN HERE *) Admitted. \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  (* FILL IN HERE *) Admitted.\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(** Proving the consistency of Coq with the general excluded middle\n    axiom requires complicated reasoning that cannot be carried out\n    within Coq itself.  However, the following theorem implies that it\n    is always safe to assume a decidability axiom (i.e., an instance\n    of excluded middle) for any _particular_ Prop [P].  Why?  Because\n    we cannot prove the negation of such an axiom.  If we could, we\n    would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)] (since [P]\n    implies [~ ~ P], by the exercise below), which would be a\n    contradiction.  But since we can't, it is safe to add [P \\/ ~P] as\n    an axiom. *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\nintros P.\nunfold not.\nintros H.\napply H.\nright.\nintros HH.\napply H.\nleft.\napply HH.\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(* FILL IN HERE *) Admitted.\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\n(* FILL IN HERE *)\n\n\n(** $Date: 2017-11-14 17:52:45 -0500 (Tue, 14 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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7892059189646936}}
{"text": "(* Coq Advent Calender *)\n(* http://study-func-prog.blogspot.com/2010/12/coq-coq-advent-calender-reflexivity-25.html *)\n\n\n(* 1/25 apply *)\n(*\n   「この仮定（下記の例では pq）を使うとゴール（下記の例では Q）が出て来る」という時に、\n   apply pq とすると、ゴール Q が変化します。学校で習う普通の証明の順序と違って、\n   Coqの証明はゴールを一歩一歩、仮定に戻して行きます。その時使うのが apply です。\n*)\n\n\nLemma Sample_of_apply : forall P Q:Prop, P -> (P->Q) -> Q.\nProof.\n  intros P Q p pq.\n  apply pq.\n  apply p.\nQed.\n\n\n(* 2/25 auto *)\n(*\n   Coq は簡単な証明は自動的に証明してくれる機能が幾つかありますが、\n   auto はよく使われます。autoが何をやっているか知りたい場合は、\n   autoの代わりにinfo autoと入力すると、autoの中で何をしてるかが判ります。\n   Coqの初学者にはinfoは便利ですよ。\n*)\n\n\nLemma Sample_of_auto : forall A B:Prop, ((((A->B)->A)->A)->B)->B.\nProof.\n  info auto.\nQed.\n\n\n(* 3/25 rewrite *)\n(*\n   rewrite は仮定にある等式を使ってゴールを書き換えます。\n   下記の例では、リスト xs について帰納法を用いて証明していますが、\n   ゴールの中に含まれるlength (xs ++ ys)を、\n   帰納法の仮定IHxsを用いてrewriteすることでlength xs + length ysに書き換えています。\n*)\n\n\nRequire Import List.\nLemma Sample_of_rewrite : forall (A:Set)(xs ys:list A),\n  length (xs ++ ys) = length xs + length ys.\nProof.\n  intros A xs ys.\n  induction xs.\n  reflexivity.\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\n\n(* 4/25 destruct *)\n(*\n   destruct は基本的にはある項を場合分けする時使うのですが、\n   仮定の中にある /\\ とか \\/ とか exists とかを分解するのに使うのに便利です。\n   （それ以外のときは induction とか case_eq とか使う事が多い様にも思います。）\n   下記の例では仮定 abc を分解して仮定 a, b, c を作っています。\n*)\n\n\nLemma Sample_of_destruct : forall A B C:Prop,\n  A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n  intros A B C abc.\n  destruct abc as (a, (b, c)).\n  split; [ split | idtac ]; assumption.\nQed.\n\n\n(* 5/25 intros *)\n(*\n   実は過去４回の記事でも毎回 intros を使用していました。\n   forall とかで定義された変数や -> の左の式とかを仮定に持って行く為に使います。\n   introの複数形なので、introを必要な回数繰り返してもOKです。\n   intros. だけでも勝手に適当に名前（仮定は通常 H? みたいな名前）を付けてくれますが、\n   判りやすさを考えると自分で適切な名前を付けた方が良いと思います。\n*)\n\n\nLemma Sample_of_intros : forall A B C:Prop, (A->B->C) -> (A->B) -> A -> C.\nProof.\n  intros A B C abc ab a.\n  apply abc.\n  exact a.\n  apply ab; exact a.\nQed.\n\n\n(* 6/25 omega *)\n(*\n   Coq でよく使われる tactic の６つ目は omega です...\n   ってanarchy proofは課題が数学寄りに偏っているから、\n   順序が６つ目というのはあまり気にしないで下さい。\n   omega タクティックは、\n   forallとかexistsとかを含まない形のPresburger算術の式を自動証明してくれます。\n   端的に言うと、\n   \n   ・割り算無し。\n   ・変数と変数の掛け算が入っていない。\n   ・変数と定数（2, 3などの具体的な整数）の掛け算はOK。\n   \n   みたいな感じの等式 or 不等式を証明します。\n   Coqがよく使われる理由は、この手の数式関係の自動証明が便利に使えるからだと思います。\n   整数の等式不等式に関する公理定理を組み合わせて証明するとか大変ですからね。\n\n\n   簡単な例はこんなのです。\n   使い方は簡単で、Require Import Omega して、introsとかして、omega と入力するだけ。\n*)\n\n\nRequire Import Omega.\nLemma Sample_of_omega : forall x:nat, x > 1 -> 3 * x > x + 2.\nProof.\n  intros.\n  info omega.\nQed.\n\n\n(* 7/25 assert *)\n(*\n   １つ目のapplyのところで書いた様に、Coqの証明は最初にゴールがあって、\n   それを仮定と逆に戻して行く格好になっています。\n   しかし証明する人間は仮定からゴールを考える方が楽な場合、\n   つまり証明途中で適当な補題を作りたくなる場合があります。\n   補題はある程度汎用性があるならば、予め切り出して証明しておいた方が良いと思いますが、\n   使い捨て的な補題は assert を使うと、証明内証明みたいに作る事ができます。\n   例えば下記の例で、\n*)\nLemma Sample_of_assert : forall P Q, (P /\\ P) -> (Q /\\ Q) -> (P /\\ Q).\nProof.\n  intros P Q pp qq.\n(*\n   ここまで証明した段階で、forall X, X /\\ X -> Xという補題があれば、\n   ppからPを、qqからQを取り出せて便利そうだと考えました。\n   そこでassertを使います。すると現在の証明課題より先に、\n   まずこの補題が証明課題になります。\n*)\n  assert(H: forall X, X /\\ X -> X).\n  intros X xx.\n  destruct xx as [x _].\n  exact x.\n(*\n   assertで設定した補題 H の証明が終わると、以後は仮定 H としてそれを使う事が出来ます。\n*)\n  split.\n  apply (H P).\n  exact pp.\n  apply (H Q).\n  exact qq.\nQed.\n\n\n(* 8/25 intro *)\n(*\n   基本的には前に説明したintrosと同じで、introsと違って一度に１つしかintro出来ないのが違います。\n   あと、introsと違ってintroの場合は、\n   ~Pの形のゴールを、Pという仮定と、Falseというゴールに変形出来ます。\n   ~PはP->Falseなのですが、intros.では~Pは~Pのままです。\n*)\n\n\nLemma Sample_of_intro : forall P, ~~~P -> ~P.\nProof.\n  intro P.\n  intro nnnp.\n  intro p.\n  elim nnnp.\n  intro np.\n  elim np.\n  exact p.\nQed.\n\n\n(* 9/25 simpl *)\n(*\n   simpl はβι簡約(beta, iota)をして式を簡単にします。\n   βι簡約が何かについては「言語ゲーム」の記事が判りやすいです。\n   β簡約は関数適用で、ι簡約だと再帰的に関数が適用される、と考えると良いです。\n\n\n   予め、足し算の定義を示しておきます。plus を含んだ式を simpl すると、\n   一つ目の変数 n について再帰的にパターンマッチして式を変形してくれます。\n*)\nPrint plus.\n(* 足し算を使った simpl の使用例です。 *)\nLemma Sample_of_simpl : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  simpl.\n(*\n   simpl を使うと左辺の0 + mがnに簡約されますが、右辺は変化がありません。\n   ここは別途証明しておいた（というか標準ライブラリにはいっている）\n   定理のplus_n_Oを使って書き換える事にします。\n*)\n  Check plus_n_O.\n  erewrite <- plus_n_O.\n  reflexivity.\n\n\n(* 帰納法の後半も simpl を使い、別の補題plus_n_Smを使います。*)\n  Check plus_n_Sm.\n  erewrite <- plus_n_Sm.\n  erewrite <- IHn.\n  reflexivity.\nQed.\n\n\n(* 10/25 unfold *)\n(*\n   unfold は関数定義を展開します。\n   unfold だけで使う場合も有りますが、fold と組み合わせて使う事もあります。\n   fold は展開された関数を元に戻します。\n   unfold して、simpl とか rewrite とかして、\n   また fold して戻すと式が良い具合に変形されている場合があります。\n   ここではそういう例を見てみましょう。\n*)\n(* まず、sum n := 1 + 2 + ... + nという関数を定義します。*)\n\n\nFixpoint sum n :=\n  match n with\n    | O => O\n    | S n' => S n' + sum n'\n  end.\n\n\n(*\n   次に、sum n = 1/2 * n * (n + 1) であることを証明したいのですが、\n   割り算が入ると面倒ですから、次の定理を証明する事にします。\n   今回は環に関する自動証明器の ring を使いたいのでArithとRingをImportしておきます。\n   nに関する帰納法で、n=0の場合はさらっと証明を流すことにします。\n*)\nRequire Import Arith Ring.\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(* 11/25 exists *)\n(*\n   証明のゴールが exists x, P x とか { n:nat | isPrime n } とか、\n   ある性質を満たす要素が存在することを求めている時に、\n   「具体的に」その要素を与えてゴールを変形します。\n\n\n   下記は exists を使う簡単な例です。\n   mの具体的な値としてS n = n+1 を与えています。\n   具体的なmを何か与えないとomegaでの自動証明は通りません。\n*)\n\n\nLemma Sample_of_exists : forall n, exists m, n < m.\nProof.\n  intros.\n  exists (S n).\n  omega.\nQed.\n\n\n(* 12/25 replace *)\n(*\n   Coq でよく使われる tactic の12番目は replace です。\n   replace t1 with t2 とすると、t2 = t1 という等式をsubgoalに追加し、\n   t2 = t1 を用いてゴールの書き換えを行います。\n   書き換え規則 t2 = t1 の証明を先送りにすることで本筋の証明の見通しがよくなります。\n   また、simpl, unfold, rewriteを使う場合とかで、\n   「ゴールのこの部分だけ書き換えたいのだが別のところも書き換えられてしまう」\n   と悩む場面もありますが、\n   そういうときは replace でとりあえず部分的に書き換え、\n   あとでその箇所の書き換えを証明すると楽です。\n   replace を多用するのは、等式変形を繰り返す場合です。今回はそういう例を。\n*)\n\n\n(* 下記の様に群 G を定義してみます。 *)\n\n\nAxiom G : Set.                                           (* 群G *)\nAxiom G_dec : forall a b:G, {a=b} + {a <> b}.            (* 単位元や逆元の一意性とかを示す時に必要 *)\nAxiom mult : G -> G -> G.                                (* 乗法 *)\nNotation \"a * b\" := (mult a b).                          (* 記号 * で書ける様にする *)\nAxiom assoc : forall a b c:G, (a * b) * c = a * (b * c). (* 結合則 *)\nAxiom G1 : G.                                            (* 単位元 *)\nNotation \"1\" := G1.                                      (* 記号 1 で書ける様にする *)\nAxiom id_l : forall a:G, 1 * a = a.                      (* 左単位元である *)\nAxiom inv : G -> G.                                      (* 逆元 *)\nAxiom inv_l : forall a:G, (inv a) * a = 1.               (* 左逆元 *)\n\n\n(*\n   では、左逆元は右逆元でもあることを証明してみます。\n   長くなるのでゴールを示すのは要所要所だけです。\n   replaceを使うと、subgoalが増えているのが判ります。\n*)\n\n\nTheorem inv_r : forall a:G, a * (inv a) = 1.\nProof.\n  intros.\n  replace (a * inv a) with (1 * a * inv a) .\n  replace (1 * a * inv a) with (inv (inv a) * inv a * a * inv a) .\n  replace (inv (inv a) * inv a * a * inv a) with\n    (inv (inv a) * (inv a * a) * inv a) .\n  rewrite inv_l.                            (* ここからは replace を使わなくても\n                                               rewrite で簡単に変形出来る *)\n  rewrite assoc.\n  rewrite id_l.\n  rewrite inv_l.\n  reflexivity.                              (* メインゴールの証明完了。\n                                               残りは replace の書き換えの証明 *)\n  rewrite <- assoc; reflexivity.\n  erewrite inv_l; reflexivity.\n  rewrite assoc; rewrite id_l; reflexivity.\nQed.\n\n\n(* 13/25 induction *)\n(*\n   Coq は帰納的な型を定義すると、その型に対する帰納法を自動で定義してくれます。\n   例えば\n\n\n   Inductive nat : Set :=\n   | O : nat\n   | S : nat -> nat.\n\n\n   という自然数natに対して、\n\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\n   というnat_indを定義してくれます。\n   これを使って、自然数nについての帰納法の証明の時に、\n\n\n   ・n=0 の場合のゴール\n   ・nの時成り立つという仮定IHnと、S nの場合のゴール\n\n\n   を作ってくれます。同様にリストであれば、nilとconsの場合などです。\n   今までにも何度か induction を使った証明を示してきましたが、今回も簡単な例を。\n*)\n\n\nLemma plus_comm : forall n m, n + m = m + n.\nProof.\n  induction n.\n  intro m.\n  simpl.\n  erewrite <- plus_n_O.\n  reflexivity.\n  intro m.\n  simpl.\n  erewrite <- plus_n_Sm.\n  erewrite IHn.\n  reflexivity.\nQed.\n\n\n(* 14/25 split *)\n(*\n   split はゴールが P /\\ Q の形をしている時に、\n   二つのゴール P, Q に分割します。あとはそれぞれを別々に証明すればOKです。\n*)\n\n\nLemma Sample_of_split : forall A B C:Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n  intros A B C abc.\n  destruct abc as [a [b c]].\n  split.\n  split.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n\n(* 15/25 case *)\n(*\n   帰納的な型について自動で場合分けをしてくれるという意味では、13番目のinductionと同じですが、\n   inductionと違って単に場合分けを行うだけで帰納法の仮定とかは作ってくれません。\n\n\n   今回は３値論理を定義してみます。帰納的な bool3 という型を定義し、\n   それらに対する否定、論理積、論理和を定義します。\n*)\nInductive bool3 : Set := yes | maybe | no.\nDefinition not3(b:bool3) :=\n  match b with\n    | yes => no\n    | maybe => maybe\n    | no => yes\n  end.\n\n\nDefinition and3(a b:bool3) :=\n  match a,b with\n    | yes,yes => yes\n    | no, _ => no\n    | _, no => no\n    | _,_ => maybe\n  end.\n\n\nDefinition or3(a b:bool3) :=\n  match a,b with\n    | no,no => no\n    | yes,_ => yes\n    | _,yes => yes\n    | _,_ => maybe\n  end.\n\n\n(*\n   では、bool3 における簡単な証明をしてみます。\n   a, b についての場合分けを行うのに case タクティックを使用します。\n   下記の例では case でゴールが増えるのを示したいので個別に case を使っていますが、\n   普通は、\n   case a; case b; reflexivity.\n   で一行で９通りの場合分けを実施して終了とするでしょう。\n*)\nLemma Sample_of_case : forall a b:bool3,\n  not3 (or3 a b) = and3 (not3 a) (not3 b).\nProof.\n  intros a b.\n  case a.\n  case b.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  case b; reflexivity.\n  case b; reflexivity.\nQed.\n\n\n\n\n(* 16/25 ring *)\n(*\n   ring は可換な半環（演算 +, * があって、それぞれ単位元 0, 1 があって、\n   それぞれ交換則と結合則が成り立って、分配法則があってな数学的構造）\n   での計算を行ってくれます。\n   基本的には多項式の掛け算を展開し、標準形に直して比較するようなことをします。\n   使用するにはRequire Import Ring.が必要です。\n   下記で色々試してみましたが、適宜 rewrite, replace なども併用しないとうまくいきませんでした。\n*)\n\n\nRequire Import ZArith Ring.\nOpen Scope Z_scope.\nLemma Sample_of_ring : forall a b:Z, a + b = 7 -> a * b = 12 -> a^2 + b^2 = 25.\nProof.\n  intros a b H1 H2.\n  replace (a^2 + b^2) with ((a+b)^2 - 2*a*b) by ring.\n  rewrite H1.\n  replace (2*a*b) with (2*12) by ring [H2].\n  reflexivity.\nQed.\nClose Scope Z_scope.\n\n\n(* 17/25 elim *)\n(*\n   elim はほとんど induction と同じ事が出来ます。\n   例えばこんな感じ。帰納法の仮定を自分で intro する必要があるのが違います。\n*)\n\n\nLemma Sample_of_elim : forall n, n + 0 = n.\nProof.  \n  intros.\n  elim n.\nAbort.\n\n\n(*\n   ただこうやって帰納法で使うときはinductionする方が多い様にも思います。\n   下記の様にゴールが False で、仮定が ~P の形をしている時は、\n   私は習慣で他のタクティックではなく elim を使います。こんな感じ。\n   *)\n\n\nLemma Sample_of_elim' : forall P, ~~(P \\/ ~P).\nProof.\n  intros.\n  intro npnp.\n  elim npnp.\n  right.\n  intro p.\n  elim npnp.\n  left.\n  exact p.\nQed.\n\n\n(* 18/25 clear *)\n(*\n   clear Hとすると、仮定 H が消えます。下記の様な感じです。\n*)\n\n\nLemma Sample_of_clear : forall A B C, (A->B->C)->(A->B)->A->C.\nProof.\n  intros A B C abc ab a.\n  apply abc; clear abc.\n  exact a.\n  apply ab; clear ab.\n  exact a.\nQed.\n\n\n(*\n   使い終わって不要になった仮定をclearで消すと多少見通しが良くなる事もありますが、\n   あまり使わないのではないかなぁ。\n   むしろ、各種 tactic の中で内部的に使われる事が多い様な気がします。\n   例えば下記の簡単な tactic の swap の中で使われています。\n   apply して一回使った仮定は不要なので clear で消しているようです。\n*)\n\n\nLtac swap H := \n  idtac \"swap is OBSOLETE: use contradict instead.\";\n  intro; apply H; clear H.\n\n\n(* これを使った証明です。*)\n\n\nLemma Sample_of_claer : forall P, ~~~P -> ~P.\nProof.\n  intros.\n  swap H.\n  swap ipattern:H.\n  exact H0.\nQed.\n\n\n(* 19/25 inversion *)\n(*\n   inversion は仮定に対して帰納的な定義を適用し、その仮定が成立する為の前提を導き出すか、\n   あるいはそもそもそのような前提が存在しない（＝仮定が間違っている）ので証明終了、\n   を導いてくれます。\n   ある種の証明では inversion を使うと証明が非常に簡単なのですが、\n   中で何をしているのかは簡単には説明するのは難しいです。\n*)\n\n\n(* inversionの使用例というと典型的にはこの関数を定義することになっています。*)\nInductive even : nat -> Prop :=\n| EvenO : even O\n| EvenSS : forall n, even n -> even (S (S n)).\n\n\n(*\n   偶数である事を、上記の様に帰納的に定義します。\n   では３が偶数でない事を証明しましょう。\n   こういう定理の証明の時にはinversionが有用です。\n   今回はinversionの中で何をしているかみたいのでinfo inversionとして使っています。\n*)\n\n\nLemma Sample_of_inversion : ~(even 3).\nProof.\n  intro.\n  info inversion H.\n(* H: even 3の前提にH1: even 1が前提である事が判りました。\n   このH1について再度inversionを使います。 *)\n  info inversion H1.\nQed.\n(* H1を成立させる前提が無いので、証明完了になります。*)\n\n\n(* あと、inversionが役に立つ例というとsmall-stepの決定性の証明とかです。*)\nInductive term : Set :=\n| TmTrue : term\n| TmFalse : term\n| TmIf : term -> term -> term -> term.\n\n\nInductive eval : term -> term -> Prop :=\n| EvIfTrue : forall t2 t3, eval (TmIf TmTrue t2 t3) t2 \n| EvIfFalse : forall t2 t3, eval (TmIf TmFalse t2 t3) t3\n| EvIf : forall t1 t1' t2 t3, eval t1 t1' ->\n  eval (TmIf t1 t2 t3) (TmIf t1' t2 t3).\n\n\n(* 上記の様にsmall-stepの規則を定義して、下記を証明します。*)\n\n\nTheorem eval_deterministic : forall t t' t'', (eval t t') -> (eval t t'') -> (t' = t'').\nProof.\n  intros t t' t'' tEt' tEt''.\n  \n  (* まず tEt' について induction で場合分けをします。*)\n  induction tEt' as [t2 t3|t2 t3|t1 t1' t2 t3 t1Et1'] in t'', tEt'' |-*.\n  (*\n     最初の場合は、t' = TmIf TmTrue t2 t3 の場合です。\n     ここで tEt'' については induction ではなくinversion を使うと、\n     tEt'' が成立するような t'' の場合分けを自動で行ってくれます。\n     *)\n  inversion tEt'' as [t2_ t3_| t2_ t3_| t1_ t1'_ t2_ t3_ t1Et1'_].\n  reflexivity.\n  (*\n     ここでinversion t1Et1'_を行います。\n     TmTrueが何かにevalされる規則はevalに無いので、仮定が不成立となり、\n     goalの証明が終わります。\n     *)\n  inversion t1Et1'_.\n  \n  (* t' = TmIfFalse t2 t3 の場合は同様の証明をすればOKです。*)\n  inversion tEt'' as [t2_ t3_| t2_ t3_| t1_ t1'_ t2_ t3_ t1Et1'_].\n  reflexivity.\n  inversion t1Et1'_.\n  \n  (*\n     最後は、t' = TmIf t1 t2 t3 の場合についてです。\n     やはりtEt''についてinversionします。\n     *)\n  inversion tEt'' as [t2_ t3_| t2_ t3_| t1_ t1'_ t2_ t3_ t1Et1'_].\n  (*\n   ここでも、H0とt1Et1'から、eval TmTrue t1'を作って\n   inversionして仮定が成立しない事を使って証明します。\n   *)\n  rewrite <- H0 in t1Et1'.\n  inversion t1Et1'.\n\n\n  (* 同様にして、TmFalse の場合も証明出来ます。*)\n  rewrite <- H0 in t1Et1'.\n  inversion t1Et1'.\n  \n  (* 最後はIHt1Et1'のt''をt1'_にして、t1Et1'_と組み合わせてゴールを導きます。*)\n  rewrite (IHt1Et1' t1'_ t1Et1'_).\n  reflexivity.\nQed.\n\n\n(* 20/25 generalize *)\n(*\n   generalize は intro の逆で、具体的な値の term を、\"forall t\" のような形に戻します。\n   簡単な使用例は下記の様なものです。\n*)\nLemma sample_of_generalize : forall x y, 0 <= x + y + y.\nProof.\n  intros.\n  generalize (x + y + y).\n  Require Import Arith.Le.\n  apply le_O_n.\nQed.\n\n\n(*\n   単純に generalize で戻せない場合は、generalize dependent t のような形で使います。\n   例えば下記の証明（TAPLの練習問題の証明）で使っています。\n   よほど明らかな場合以外は、generalize dependentの形で使う事が多い様に思います。\n   まず証明の前提の定義を幾つか。\n*)\nInductive term2 : Set :=\n| Tm2True : term2\n| Tm2False : term2\n| Tm2If : term2 -> term2 -> term2 -> term2\n| Tm2Zero : term2\n| Tm2Succ : term2 -> term2\n| Tm2Pred : term2 -> term2\n| Tm2Iszero : term2 -> term2.\n\n\nInductive nvalue : term2 -> Prop :=\n| NvZero : nvalue Tm2Zero\n| NvSucc : forall t, nvalue t -> nvalue (Tm2Succ t).\n\n\nInductive bvalue : term2 -> Prop :=\n| BvTrue : bvalue Tm2True\n| BvFalse : bvalue Tm2False.\n\n\nDefinition value(t:term2) : Prop := bvalue t \\/ nvalue t.\n\n\nInductive eval2 : term2 -> term2 -> Prop :=\n| Ev2IfTrue : forall t2 t3, eval2 (Tm2If Tm2True t2 t3) t2\n| Ev2IfFalse : forall t2 t3, eval2 (Tm2If Tm2False t2 t3) t3\n| Ev2If : forall t1 t1' t2 t3, eval2 t1 t1' -> eval2 (Tm2If t1 t2 t3) (Tm2If t1' t2 t3)\n| Ev2Succ : forall t1 t1', eval2 t1 t1' -> eval2 (Tm2Succ t1) (Tm2Succ t1')\n| Ev2Pred : forall t1 t1', eval2 t1 t1' -> eval2 (Tm2Pred t1) (Tm2Pred t1')\n| Ev2PredZero : eval2 (Tm2Pred Tm2Zero) Tm2Zero\n| Ev2PredSucc : forall nv, nvalue nv -> eval2 (Tm2Pred (Tm2Succ nv)) nv\n| Ev2IszeroZero : eval2 (Tm2Iszero Tm2Zero) Tm2True\n| Ev2IszeroSucc : forall nv, nvalue nv -> eval2 (Tm2Iszero (Tm2Succ nv)) Tm2False\n| Ev2Iszero : forall t1 t1', eval2 t1 t1' -> eval2 (Tm2Iszero t1) (Tm2Iszero t1').\n\n\nNotation \"t1 ---> t2\" := (eval2 t1 t2) (at level 80, no associativity).\n\n\nDefinition normal_form (t : term2) : Prop := ~ exists t', eval2 t t'.\n\n\n(* ここで下記の定理を証明します。\n   intros を下記の様にすると予めdestructした形で intros 可能です。\n*)\nLemma value_is_normal_form : forall v, value v -> normal_form v.\nProof.\n  intros v [bv|nv] [t vEt].\n  destruct bv; inversion vEt.\n(*\n   ここで t をgeneralize dependentします。\n   （generalize t だと、forall t:term2, にならずうまくいかない。）\n*)\n  generalize dependent t.\n  induction nv.\n  intros t zEt.\n  inversion zEt.\n  intros t0 stEt0.\n  inversion stEt0.\n  elim (IHnv t1').\n  exact H0.\nQed.\n\n\n(* 21,22/25 left, right *)\n(*\n   left は constructor 1 、right は constructor 2 の意味で、\n   実は goal が A \\/ B の場合に限らず、\n   コンストラクタが２通りあってどちらかを明示的に指定したい時に使えます。\n   大抵そういう場合は左右と対応している訳ですが、例えば nat とかも left が O を指すはず。\n   同様に n:nat に対して destruct n ではなく split とかも使えるはず。\n   単に他人に判りにくいだけですが。\n   \n   今回は sumbool について left, right を使う例です。やはり左右に対応しています。\n*)\nLemma Sample_of_left_right : forall n:nat, {n = 0} + {n <> 0}.\nProof.\n  induction n.\n  left.\n  reflexivity.\n  \n  right.\n  intro.\n  inversion H.\nQed.\n\n\n(* 23/25 specialize *)\n(*\n   公理とかライブラリにある定理とか証明済み補題とかに、\n   特定の引数を適用した物を仮定に使いたい事があります。\n   forall n, P n. みたいな補題Lのnに特定の値 n0 を代入した P n0 が仮定にあると良いなぁ、とか。\n   勿論、assert(H:P n0)とかcut (P n0)とか書いても良いのですが、\n   specialize (L n0). と書けば cut (P n0)してapply (L n0) するのと同じになり、\n   証明が短く判りやすくなります。\n   \n   replaceの説明の時と同じ定理を、replaceを使わず、specializeとrewriteを使って証明してみます。\n   証明の前提と成る公理は replace の回を参照して下さい。\n*)\nTheorem inv_r' : forall a:G, a * (inv a) = 1.\nProof.  \n  intros.\n  specialize (id_l (a * inv a)).\n  (*\n     specializeすると、公理 id_l に (a * inv a) を適用した物が得られますので、\n     intro して書き換えて消去します。あとは同様に。\n     *)\n  intro H; rewrite <- H; clear H.\n  specialize (inv_l (inv a)); intro H; rewrite <- H; clear H.\n  specialize (assoc (inv (inv a)) (inv a) (a * inv a)); intro H; rewrite H; clear H.\n  specialize (assoc (inv a) a (inv a)); intro H; rewrite <- H; clear H.\n  specialize (inv_l a); intro H; rewrite H; clear H.\n  specialize (id_l (inv a)); intro H; rewrite H; clear H.\n  reflexivity.\nQed.\n\n\n(* 24/25 exact *)\n(*\n   現在のゴールが、仮定のどれか、あるいは既存の定理にマッチする時に\n   exact H?. とか exact my_theorem. とかするとゴールが証明されます。\n   前者の場合は assumption. で済みますし、\n   exact ではなく apply でもOKなんで、無理に使う必要は無いですが、\n   ゴールと同じ物があったという意図を多少は示せるのかも。\n   exact を使って書いてみました。\n*)\n\n\nLemma Sample_of_exact : forall n m, n + m = m + n.\nProof.\n  intros.\n  induction n.\n  simpl.\n  exact (plus_n_O m).\n  simpl.\n  rewrite IHn.\n  exact (plus_n_Sm m n).\nQed.\n\n\n(* 25/25 reflexivity *)\n(*\n   reflexivity はゴールが等式で、左辺と右辺の値が等しい時に使います。\n   内容的には apply refl_equal. と同じです。refl_equal はこんな公理。\n\n\nInductive eq (A : Type) (x : A) : A -> Prop :=  refl_equal : x = x.\n\n\n   左辺と右辺が全く同じ形をしていないと等式は成り立ちません\n   （が、reflexivity は内部的に simpl を実行しているので\n   simpl で簡単化して等しくなる物は成立します）。\n   \n   ところで、同じ形というのはどこまで同じならば = が成り立つかというのは良く解らないので、\n   色々試してみました。\n*)\n\n\nDefinition f : nat -> nat := fun x => x.\nDefinition h : nat -> nat := fun y => y .\nGoal f = h.\n  simpl.\n  unfold f.\n  unfold h.\n  reflexivity.\nQed.\n(*\n   これを見ると、(fun x : nat => x) = (fun y : nat => y) は成立するようです。同様に、\n*)\n\n\nGoal forall P:nat->Prop, (forall n, P n) = (forall m, P m).\n  intros P.\n  reflexivity.\nQed.\n(*\n   これを見ると、(forall n : nat, P n) = (forall m : nat, P m) も成立。\n   上記の f, h の場合はreflexivityで等しい事が示せましたが、\n   一般には関数が等しい事を reflexivity で証明する事は出来ません。\n   \n   f, g : nat -> nat について、f = g ⇔ ∀n:nat, f n = g n. を以て等しいとする場合は、\n   こんな感じで証明します。\n*)\n\n\nDefinition f' : nat -> nat := fun x => x.\nFixpoint g' (x:nat) : nat :=\n  match x with\n    | O => O\n    | S n' => S (g' n')\n  end.\n\n\nRequire Import Logic.FunctionalExtensionality.\n\n\nLemma Sample_of_reflexivity : f' = g'.\nProof.\n  extensionality n.\n  unfold f'.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\nQed.\n\n\n(*\n   他にも、= を同値関係を以て定義する場合は Setoid というものを使って考える\n   （Coqの型理論には集合論の商集合が無いので、代わりに = を同値関係で置き換えた物を使う）\n   とか有るらしいのですが、そっちはちょっと調べきれませんでした。\n*)\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_advent_calender.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8723473763375643, "lm_q1q2_score": 0.7891695118275066}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\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\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_app : 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\nScheme even_list_mut := Induction for even_list Sort Prop\n  with odd_list_mut := Induction for odd_list Sort Prop.\n    \nCheck even_list_mut.\n\nTheorem elength_eapp : forall el1 el2 : even_list,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).\n\n  apply (even_list_mut\n           (fun el1 : even_list => forall el2 : even_list,\n                elength (eapp el1 el2) = plus (elength el1) (elength el2))\n           (fun ol : odd_list => forall el : even_list,\n                olength (oapp ol el) = plus (olength ol) (elength el))); crush.\n  Qed.\n", "meta": {"author": "ytakano", "repo": "cpdt", "sha": "04c8ffb185fe02b6ed4ee9e15f8a724c05d28c20", "save_path": "github-repos/coq/ytakano-cpdt", "path": "github-repos/coq/ytakano-cpdt/cpdt-04c8ffb185fe02b6ed4ee9e15f8a724c05d28c20/src/chap3-5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7891670584976302}}
{"text": "Require Import Nat.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint len (l : lst) : nat :=\n  match l with\n  | Nil => 0\n  | Cons x y => 1 + len y\n  end.\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 rev (l : lst) : lst :=\n  match l with\n  | Nil => Nil\n  | Cons x y => append (rev y) (Cons x Nil)\n  end.\n\nLemma len_append : forall x y : lst, len (append x y) = len x + len y.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem len_rev : forall x : lst, len (rev x) = len x.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl.\n    rewrite len_append.\n    rewrite IHx.\n    simpl.\n    rewrite <- plus_n_Sm.\n    auto.\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/list_rev_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7891364823125495}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Bool.\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp Require Import eqtype ssrnat div prime. \n(*Imports, check \"lib\" folder.*)\n\n(*Inductive nat : Set :=\n| O : nat\n| S : nat -> nat.*)\n\nPrint nat.\n\nEval compute in 0.\nEval compute in S(O). (*1*)\n\nFixpoint add(a b :nat) : nat :=\n  match a with\n  | 0 => b\n  | S n => S(add n b)\nend.\n\nCompute add 1 3.\n\nTheorem add_assoc : forall (a b c : nat), \n  (add a (add b c)) = (add (add a b) c).\nProof. (*Begin proof*)\n  intros a b c. (*Introduce a b c as \"given\".*)\n  induction a as [|n].  (*Induction on a, as n.*)\n    simpl. reflexivity. (*Base case*)\n    simpl. rewrite -> IHn. reflexivity. (*General case*)\nQed. (*Begin proof*)\n\nPrint add_assoc.\n\nPrint nat_ind.\n\nTheorem one_not_eq_two : ~ 1 = 2.\nProof.\nunfold not. \nintros H.\ninversion H.\nQed.\n\nTheorem n_geq_zero : ~ 0 > 0.\nProof.\nunfold not. unfold gt. unfold lt.\nintros H.\ninversion H.\nQed.\n\nDefinition pred (n : nat) : n > 0 -> nat :=\n  match n with\n  | O => fun pf => match (n_geq_zero pf) with end\n  | S n' => fun _ => n'\nend.\n\nTheorem one_exists : exists (n : nat), n = 1.\nProof.\nexists 1. reflexivity.\nQed.\n\nEval compute in pred 3.\n\n\nNotation \"x | y\" := (y mod x = 0)\n(at level 50, left associativity).\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/Introduction_to_Coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7891364823125495}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import riscv.util.div_mod_to_quot_rem.\nRequire Import Coq.micromega.Lia.\n\nLocal Open Scope Z_scope.\n\n\nDefinition bitSlice(x: Z)(start eend: Z): Z :=\n  Z.land (Z.shiftr x start) (Z.lnot (Z.shiftl (-1) (eend - start))).\n\nDefinition signExtend(l: Z)(n: Z): Z :=\n  if Z.testbit n (l-1) then (n - (Z.setbit 0 l)) else n.\n\nDefinition bitSlice'(w start eend: Z): Z :=\n  (w / 2 ^ start) mod (2 ^ (eend - start)).\n\nLemma bitSlice_alt: forall w start eend,\n    0 <= start <= eend ->\n    bitSlice w start eend = bitSlice' w start eend.\nProof.\n  intros. unfold bitSlice, bitSlice'.\n  rewrite <- Z.land_ones by omega.\n  rewrite <- Z.shiftr_div_pow2 by omega.\n  f_equal.\n  rewrite Z.shiftl_mul_pow2 by omega.\n  rewrite Z.mul_comm.\n  rewrite <- Z.opp_eq_mul_m1.\n  replace (Z.lnot (- 2 ^ (eend - start))) with (2 ^ (eend - start) - 1).\n  - rewrite Z.ones_equiv. reflexivity.\n  - pose proof (Z.add_lnot_diag (- 2 ^ (eend - start))). omega.\nQed.\n\nLemma bitSlice_range: forall sz z,\n    0 <= sz ->\n    0 <= bitSlice z 0 sz < 2 ^ sz.\nProof.\n  intros.\n  rewrite bitSlice_alt by omega.\n  unfold bitSlice'.\n  change (2 ^ 0) with 1.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  apply Z.mod_pos_bound.\n  apply Z.pow_pos_nonneg; omega.\nQed.\n\nLemma bitSlice_split: forall sz1 sz2 v,\n    (0 <= sz1)%Z ->\n    (0 <= sz2)%Z ->\n    (bitSlice v sz1 (sz1 + sz2) * 2 ^ sz1 + bitSlice v 0 sz1)%Z = bitSlice v 0 (sz1 + sz2).\nProof.\n  intros. rewrite? bitSlice_alt by omega. unfold bitSlice'.\n  change (2 ^ 0)%Z with 1%Z.\n  rewrite Z.div_1_r.\n  rewrite! Z.sub_0_r.\n  replace (sz1 + sz2 - sz1)%Z with sz2 by omega.\n  rewrite Z.pow_add_r by assumption.\n  assert (0 < 2 ^ sz1)%Z by (apply Z.pow_pos_nonneg; omega).\n  assert (0 < 2 ^ sz2)%Z by (apply Z.pow_pos_nonneg; omega).\n  rewrite Z.rem_mul_r by omega.\n  nia.\nQed.\n\nDefinition signExtend'(l n: Z): Z := n - ((n / 2 ^ (l - 1)) mod 2) * 2 ^ l.\n\nLemma signExtend_alt: forall l n,\n    0 < l ->\n    signExtend l n = signExtend' l n.\nProof.\n  intros. unfold signExtend, signExtend'.\n  destruct (Z.testbit n (l - 1)) eqn: E.\n  - apply (f_equal Z.b2z) in E.\n    rewrite Z.testbit_spec' in E by omega.\n    rewrite E.\n    rewrite Z.setbit_spec'.\n    rewrite Z.lor_0_l.\n    change (Z.b2z true) with 1.\n    rewrite Z.mul_1_l.\n    reflexivity.\n  - apply (f_equal Z.b2z) in E.\n    rewrite Z.testbit_spec' in E by omega.\n    rewrite E.\n    change (Z.b2z false) with 0.\n    rewrite Z.mul_0_l.\n    rewrite Z.sub_0_r.\n    reflexivity.\nQed.\n\nLemma mul_div2_undo_mod: forall a, 2 * (a / 2) = a - a mod 2.\nProof.\n  intros.\n  pose proof (Z.div_mod a 2).\n  omega.\nQed.\n\nLemma or_to_plus: forall a b,\n    Z.land a b = 0 ->\n    Z.lor a b = a + b.\nProof.\n  intros.\n  rewrite <- Z.lxor_lor by assumption.\n  symmetry. apply Z.add_nocarry_lxor. assumption.\nQed.  \n\nDefinition signExtend_alt': forall l n,\n    0 < l ->\n    (exists q, n / 2 ^ (l - 1) = 2 * q /\\ signExtend l n = n) \\/\n    (exists q, n / 2 ^ (l - 1) = 2 * q + 1 /\\ signExtend l n = n - 2 ^ l).\nProof.\n  intros. rewrite signExtend_alt by assumption. unfold signExtend'.\n  pose proof (Z.mod_pos_bound (n / 2 ^ (l - 1)) 2).\n  assert ((n / 2 ^ (l - 1)) mod 2 = 0 \\/ (n / 2 ^ (l - 1)) mod 2 = 1) as C by omega.\n  destruct C as [C | C]; rewrite C.\n  - left. exists (n / 2 ^ (l - 1) / 2). rewrite mul_div2_undo_mod. omega.\n  - right. exists (n / 2 ^ (l - 1) / 2). rewrite mul_div2_undo_mod. omega.\nQed.\n\nDefinition signExtend2(l n: Z): Z :=\n  if Z.testbit n (l - 1) then Z.lor n (Z.shiftl (-1) l) else n.\n\nLemma signExtend_alt2: forall l n,\n    0 < l ->\n    Z.land (Z.shiftl (-1) l) n = 0 ->\n    signExtend l n = signExtend2 l n.\nProof.\n  intros.\n  unfold signExtend, signExtend2.\n  destruct (Z.testbit n (l - 1)) eqn: E; [|reflexivity].\n  rewrite <- Z.add_opp_r.\n  pose proof (Z.add_lnot_diag (Z.setbit 0 l)).\n  replace (- (Z.setbit 0 l)) with (Z.lnot (Z.setbit 0 l) + 1) by omega.\n  replace (Z.lnot (Z.setbit 0 l) + 1) with (Z.shiftl (-1) l).\n  - symmetry. apply or_to_plus. rewrite Z.land_comm. assumption.\n  - replace (Z.lnot (Z.setbit 0 l)) with (- Z.setbit 0 l - 1) by omega.\n    rewrite Z.shiftl_mul_pow2 by omega.\n    rewrite Z.setbit_spec'.\n    rewrite Z.lor_0_l.\n    omega.\nQed.\n\nLemma bitSlice_all_nonneg: forall n v : Z,\n    (0 <= n)%Z ->\n    (0 <= v < 2 ^ n)%Z ->\n    bitSlice v 0 n = v.\nProof.\n  clear. intros.\n  rewrite bitSlice_alt by omega.\n  unfold bitSlice'.\n  change (2 ^ 0)%Z with 1%Z.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  apply Z.mod_small.\n  assumption.\nQed.\n      \nLemma bitSlice_all_neg: forall n v : Z,\n    (0 <= n)%Z ->\n    (- 2 ^ n <= v < 0)%Z ->\n    bitSlice v 0 n = (2 ^ n + v)%Z.\nProof.\n  clear. intros.\n  rewrite bitSlice_alt by omega.\n  unfold bitSlice'.\n  change (2 ^ 0)%Z with 1%Z.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  assert (0 < 2 ^ n)%Z. {\n    apply Z.pow_pos_nonneg; omega.\n  }\n  div_mod_to_quot_rem.\n  subst v.\n  rewrite Z.add_assoc.\n  assert (q = -1)%Z by nia.\n  subst q.\n  nia.\nQed.\n", "meta": {"author": "samuelgruetter", "repo": "riscv-coq", "sha": "bd89fbff49704b4476633a88abdedb4e410c200b", "save_path": "github-repos/coq/samuelgruetter-riscv-coq", "path": "github-repos/coq/samuelgruetter-riscv-coq/riscv-coq-bd89fbff49704b4476633a88abdedb4e410c200b/src/util/ZBitOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7891207146479865}}
{"text": "Require Export TopologicalSpaces.\nRequire Export OpenBases.\nRequire Export FiniteTypes.\nRequire 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\nRequire 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": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/Subbases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7890278510183986}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Tactics.\nRequire Export Poly.\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. *)\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: *)\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. split.\n  - destruct n. \n    * reflexivity.\n    * destruct m. \n    + inversion H.\n    + inversion H.\n  - destruct m.  \n    * reflexivity.\n    * rewrite <- plus_n_Sm in H.\n      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  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  (* 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\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].\n  apply HQ.  Qed.\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  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    [intros] 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.\n    +  apply HP.\n    + apply HQ.\n  -  apply HR.\n     Qed.\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  (* WORKED IN CLASS *)\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  destruct n as [| n'] eqn:eq.\n  - left. reflexivity.\n  - right. simpl in H. destruct m.\n    * reflexivity.\n      * inversion H. \nQed.\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros.\n  destruct H.\n  right. apply H.\n  left. apply H.\nQed.\n\n\n(* ================================================================= *)\n(** ** Falsehood and Negation *)\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\n    we assume a contradiction, then any other proposition can be\n    derived.  Following this intuition, we could define [~ P] (\"not\n    [P]\") as [forall Q, P -> Q].  Coq actually makes a slightly\n    different choice, defining [~ P] as [P -> False], where [False] is\n    a specific 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.\n  destruct H.\n  apply H0.\nQed.\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\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(** P -> ~~P is syntatict sugar for P-> ((P->False) -> False)\n\nassume P is true,\nand also P-> False, we need to show False.\nSince P-> False and P, we know False.*)\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  intros.  \n  unfold not in H0.\n  apply H in H1.\n  apply H0 in H1.\n  apply H1.\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.\nunfold not.\nintros.\ndestruct H.\napply H0 in H.\ndestruct H.\nQed.\n\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\nDefinition informal_not_PNP_TODO := 0.\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(** ** 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.\n  split.\n  intros.\n  apply H.\n  intros.\n  apply H.\nQed.\n\n\n  Theorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  split.\n  intros.\napply H in H3.  \napply H0 in H3.\napply H3.\nintros.\napply H2 in H3.\napply H1 in H3.\napply H3.\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.  \n  split.\n  \n  intros.\n  inversion H.\n  split.\n  left. apply H0.\n  left. apply H0.\n  split.\n  destruct H0.\n  right. apply H0.\n  destruct H0. right. apply H1.\n  intros. \n  destruct H as [[HP1 | HQ] [HP2 | HR]].\n  left. apply HP1.\n  left.  apply HP1.\n  left. apply HP2.\n  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 Coq library that supports it: *)\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). simpl.\nsimpl in Hm.  apply Hm.  Qed.\n\n(** **** Exercise: 1 star, recommended (dist_not_exists)  *)\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.\n  unfold not.\n  intros. destruct H0.\n  apply H0 in H.\n  apply H.\nQed.\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.\nintros.\nsplit.\nintros.\ndestruct H.\ndestruct H.\nleft.\nexists x.\napply H.\nright.\nexists x.\napply H.\nintros.\ndestruct H.\ndestruct H.\nexists x.\nleft. \napply H.\ndestruct H.\nexists x.\nright.\napply H.\nQed.\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 taking an element and a list and returning a proposition: *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | nil => False\n  | cons 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  intros.\n  simpl in H.\n  destruct H as [H | [H | H]].\n  exists 1.\n  simpl.\n  symmetry.\n  apply H.\n  exists 2.\n  simpl.\n  symmetry. apply H.\n  inversion H.\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  split.\n  intros.\n  induction l.\n  simpl in H.\n  inversion H.\n  simpl In in H.\n  destruct H.\n  exists x.\n  split.\n  apply H.\n  simpl.\n  left.\n  reflexivity.\n  apply IHl in H.\n  destruct H.\n  exists x0.\n  destruct H.\n  split.\n  apply H.\n  simpl. \n  right. apply H0.\n\ninduction l.\n- intros.\n  destruct H.\n  inversion H.\n  inversion H1.\n- \n  simpl.\n  intros.\n  generalize dependent IHl.\n  destruct H.\n  destruct H.\n  destruct H0.\n  intros.\n  rewrite H0.\n  left. apply H.\n  intros.\n  right.\n  apply IHl.\n  exists x0.\n  split. apply H. apply H0.\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.\nsplit.\n- intros.\ninduction l.\n+ simpl in H. right.  apply H.\n+ simpl. simpl in H.\n  destruct H.\n  left. left. apply H.\n  rewrite <- or_assoc.\n  right.\n  apply IHl.\n  apply H.\n-\n  intros.\n  induction l.\n + simpl.\n  destruct H.\n  inversion H.\n  apply H.\n + simpl.\n   destruct H.\n   destruct H.\n   left. apply H.\n   right. apply IHl. \n   left. apply H.\n   right. apply IHl.\n   right. apply H.\nQed.   \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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 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 x y z, x + (y + z) = (z + y) + x.\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 x y z.\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 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\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 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(** 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    Fortunately, 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_correct)  *)\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 the two definitions are indeed equivalent. *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** We've seen two different ways of encoding logical facts in Coq:\n    with _booleans_ (of type [bool]), and with _propositions_ (of type\n    [Prop]).\n\n    For instance, to claim that a number [n] is even, we can say\n    either\n       - (1) that [evenb n] returns [true], or\n       - (2) that there exists some [k] such that [n = double k].\n             Indeed, these two notions of evenness are equivalent, as\n             can easily be shown with a couple of auxiliary lemmas.\n\n    Of course, it would be very strange if these two characterizations\n    of evenness did not describe the same set of natural numbers!\n    Fortunately, we can prove that they do... *)\n\n(** We first need two helper lemmas. *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** In view of this theorem, we say that the boolean\n    computation [evenb n] _reflects_ the logical proposition\n    [exists k, n = double k]. *)\n\n(** 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].  Again, 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_.\n\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little direct help in the middle of a proof\n    involving [n] and [m]; however, if we convert the statement to the\n    equivalent form [n = m], we can rewrite with it. *)\n\n(** The case of even numbers is also interesting.  Recall that,\n    when proving the backwards direction of [even_bool_prop] (i.e.,\n    [evenb_double], going from the propositional to the boolean\n    claim), we used a simple induction on [k].  On the other hand, the\n    converse (the [evenb_double_conv] exercise) required a clever\n    generalization, since we can't directly prove [(exists k, n =\n    double k) -> evenb n = true]. *)\n\n(** For these examples, the propositional claims are more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects 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  (* FILL IN HERE *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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(* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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(** Proving the consistency of Coq with the general excluded middle\n    axiom requires complicated reasoning that cannot be carried out\n    within Coq itself.  However, the following theorem implies that it\n    is always safe to assume a decidability axiom (i.e., an instance\n    of excluded middle) for any _particular_ Prop [P].  Why?  Because\n    we cannot prove the negation of such an axiom.  If we could, we\n    would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)] (since [P]\n    implies [~ ~ P], by the exercise below), which would be a\n    contradiction.  But since we can't, it is safe to add [P \\/ ~P] as\n    an axiom. *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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\n(* FILL IN HERE *)\n(** [] *)\n\n", "meta": {"author": "gpfarina", "repo": "logical-foundations-exercises", "sha": "49335480409aeb7d0bfebcea4f888717fe097366", "save_path": "github-repos/coq/gpfarina-logical-foundations-exercises", "path": "github-repos/coq/gpfarina-logical-foundations-exercises/logical-foundations-exercises-49335480409aeb7d0bfebcea4f888717fe097366/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.89912137659416, "lm_q1q2_score": 0.7889581428518178}}
{"text": "(*|\n##########################################################\nWhy can I use the constructor tactic to prove reflexivity?\n##########################################################\n\n:Link: https://stackoverflow.com/q/65959309\n|*)\n\n(*|\nQuestion\n********\n\nThe constructor tactic allows you to discharge a goal which is an\ninductive datatype by automatically applying constructors. However,\ndefinitional equality is not an inductive product in Coq. Then why\ndoes Coq accept this proof?\n|*)\n\nExample zeqz : 0 = 0. constructor.\n\n(*|\nAnswer\n******\n\nThe equality type in Coq is defined as follows\n|*)\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\n(*|\nthat is it has a single reflexivity constructor.\n\nTo prove that ``0 = 0`` you need to construct a term of this type. The\nonly way to do this is to invoke ``eq_refl``. However in order to\ninvoke ``eq_refl`` the type checker needs to know that ``0`` is\nconvertible to ``0`` (that is they are definitionally equal).\n\n----\n\nThe type ``eq`` is a semantic notion of equality, whereas definitional\nequality is a syntactic notion. **This means that the proof assistant\ncannot distinguish between definitionally equal terms, but it can\ndistinguish between semantically equal terms.** So the constructor\n``eq_refl`` can be seen as a guarantee that definitional (syntactic)\nequality *subsumes* semantic equality.\n\nIt is fruitful to ask whether terms may be semantically equal without\nbeing syntactically equal. Such examples may only be obtained through\nan axiom. For example, by the definition of the recursor (``nat_rec``,\nor more technically, ``nat_ind``) for the natural numbers, or by an\n`extensionality\n<https://coq.inria.fr/library/Coq.Logic.FunctionalExtensionality.html>`__\naxiom.\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/why-can-i-use-the-constructor-tactic-to-prove-reflexivity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7889581381056597}}
{"text": "Require Import Arith.\n\nFixpoint pow (b e:nat) :=\n  match e with\n  | 0 => 1\n  | S f => b * pow b f\n  end.\n\nFixpoint aux_div n m a :=\n  match m, a with\n  | _, 0 => None (* NOT REACHED *)\n  | 0, _ => None\n  | S q, S b =>\n      match lt_dec n m with\n      | left _ => Some 0\n      | right _ => \n          match aux_div (n - m) m b with\n          | None => None (* NOT REACHED *)\n          | Some k => Some (S k)\n          end\n      end\n  end.\n\nDefinition div (n m:nat) := aux_div n m (S n).\n\nDefinition rem (n m:nat) :=\n  match div n m with\n  | None => None\n  | Some q => Some (n - q * m)\n  end.\n\nLemma nat_strong_ind (P:nat->Prop):\n  P 0 ->\n  (forall n:nat,\n   (forall m:nat, m < n -> P m) -> P n) ->\n  (forall n:nat, P n).\nProof.\n  intros P0 Hrec n.\n  cut (forall n m:nat, m < n -> P m).\n  intros Hcut.\n  apply Hcut with (n := S n).\n  auto.\n  clear n.\n  induction n.\n  intros m m_imp.\n  apply False_ind, lt_n_O with (n := m), m_imp.\n  intros m mainH.\n  cut (m < n \\/ m = n).\n  intros [baseH | stepH].\n  apply IHn, baseH.\n  rewrite stepH.\n  apply Hrec with (n := n), IHn.\n  apply le_lt_or_eq.\n  apply le_S_n, mainH.\nQed.\n\nLemma S_exchange:\n  forall a b:nat,\n  S a + b * S a = S b + a * S b.\nProof.\n  intros a b.\n  rewrite mult_comm with (n := b),\n          mult_comm with (n := a).\n  simpl.\n  repeat rewrite plus_assoc.\n  rewrite mult_comm, plus_comm with (n := a).\n  reflexivity.\nQed.\n\nLemma not_lt_le:\n  forall n m:nat, ~ n < m -> m <= n.\nProof.\n  intros n m H.\n  cut (m <= n \\/ n < m).\n  tauto.\n  apply le_or_lt.\nQed.\n\nLemma minus_to_plus:\n  forall n m p:nat,\n  p <= m -> n = m - p -> m = n + p.\nProof.\n  intros n m p p_le_m H.\n  rewrite H, plus_comm.\n  symmetry.\n  apply le_plus_minus_r, p_le_m.\nQed.\n\nLemma n_le_0:\n  forall n:nat, n <= 0 -> n = 0.\nProof.\n  intros n n_le_0.\n  destruct n.\n  reflexivity.\n  absurd (S n <= 0).  \n  apply le_Sn_0.\n  assumption.\nQed.\n\nLemma div_works:\n  forall n d:nat,\n  d <> 0 ->\n  exists q:nat, div n d = Some q /\\\n  d * q <= n < d * S q.\nProof.\n  unfold div.\n  cut (forall n d k:nat,\n       d <> 0 -> n < k ->\n       exists q:nat,\n       aux_div n d k = Some q /\\\n       d * q <= n < d * S q).\n  intros Hcut n d d_ne_0.\n  apply Hcut with (k := S n); auto.\n  intros n.\n  elim n using nat_strong_ind.\n  intros d k d_ne_0 k_gt_0.\n  destruct d as [|d'], k as [|k'].\n  apply False_ind; auto.\n  apply False_ind; auto.\n  apply False_ind, lt_irrefl with (n := 0); auto.\n  exists 0; simpl.\n  rewrite mult_0_r; split; split;\n    [auto | apply lt_0_Sn].\n  clear n.\n  intros n Hrec.\n  intros d k d_ne_0 k_gt_n.\n  destruct d as [|d'], k as [|k'].\n  apply False_ind; auto.\n  apply False_ind; auto.\n  apply False_ind, lt_n_O with (n := n); auto.\n  simpl.\n  destruct lt_dec with (n := n) (m := (S d'))\n           as [n_lt_d | n_ge_d].\n  exists 0.\n  rewrite mult_0_r, plus_0_l, plus_0_l,\n          mult_1_r.\n  split; split; auto.\n  apply le_0_n.\n  cut (exists q':nat,\n       aux_div (n - S d') (S d') k' = Some q' /\\\n       S d' * q' <= n - S d' < S d' * S q').\n  intros [q' [HrecI1 [HrecI2 HrecI3]]].\n  exists (S q').\n  rewrite HrecI1.\n  split; auto.\n  split.\n  cut (S d' * q' + S d' <= n).\n  intros n_lo_bound.\n  rewrite S_exchange, mult_comm, plus_comm; auto.\n  rewrite le_plus_minus \n    with (n := S d') (m := n).\n  rewrite plus_comm with (n := S d').\n  apply plus_le_compat_r; auto.\n  apply not_lt_le; auto.\n  cut (n - S d' + S d' < S d' * S q' + S d').\n  intros n_hi_bound.\n  rewrite <-le_plus_minus_r\n    with (n := S d') (m := n).\n  rewrite plus_comm.\n  rewrite <-plus_Sn_m, S_exchange.\n  rewrite plus_comm with (n := S d').\n  rewrite mult_comm; auto.\n  apply not_lt_le; auto.\n  apply plus_lt_compat_r; auto.\n  apply Hrec.\n  assert (n - S d' < n) as sub_is_lt.\n  apply lt_minus.\n  apply not_lt_le; auto.\n  apply lt_O_Sn.\n  auto.\n  auto.\n  apply lt_le_trans with (m := n).\n  apply lt_minus.\n  apply not_lt_le; auto.\n  apply lt_0_Sn.\n  apply lt_n_Sm_le; auto.\nQed.\n\nLemma d_q_step:\n  forall q q' d:nat,\n  q < q' -> d * S q <= d * q'.\nProof.\n  intros q q' d q_lt_q'.\n  apply mult_le_compat_l, q_lt_q'.\nQed.\n\nLemma div_unique:\n  forall n d q:nat,\n  d * q <= n < d * S q -> div n d = Some q.\nProof.\n  intros n d q [Hlo Hhi].\n  destruct d as [|d'].\n  simpl in Hhi.\n  absurd (n < 0).\n  apply lt_n_O.\n  assumption.\n  cut (exists q:nat,\n       div n (S d') = Some q /\\\n       S d' * q <= n < S d' * S q).\n  intros [q' [EHq' [Hq'lo Hq'hi]]].\n  cut (q' < q \\/ q = q' \\/ q' > q).\n  intros [Hqrel | [Hqrel | Hqrel]].\n  absurd (S d' * S q' <= S d' * q).\n  apply lt_not_le, le_lt_trans with (m := n);\n    assumption.\n  apply d_q_step; assumption.\n  rewrite EHq', Hqrel; reflexivity.\n  absurd (S d' * S q <= S d' * q').\n  apply lt_not_le, le_lt_trans with (m := n);\n    assumption.\n  apply d_q_step; assumption.\n  cut (q <= q' \\/ q' < q).\n  intros [Hqle | Hq'lt].\n  right.\n  unfold gt.\n  rewrite or_comm.\n  apply le_lt_or_eq; assumption.\n  left; assumption.\n  apply le_or_lt.\n  apply div_works.\n  discriminate.\nQed.\n\nLemma rem_works:\n  forall n d:nat,\n  d <> 0 ->\n  exists q:nat, div n d = Some q /\\\n  exists r:nat, rem n d = Some r /\\\n  n = d * q + r.\nProof.\n  intros n d d_ne_0.\n  cut (exists q:nat, div n d = Some q /\\\n       d * q <= n < d * S q).\n  intros [q [div_result [div_lo_bound \n                         div_hi_bound]]]. \n  cut (exists r:nat, rem n d = Some r).\n  intros [r rem_result].\n  exists q.\n  split.\n  apply div_result.\n  exists r.\n  split.\n  apply rem_result.\n  unfold rem in rem_result.\n  rewrite div_result in rem_result.\n  injection rem_result.\n  intros div_rem_rel.\n  rewrite plus_comm.\n  apply minus_to_plus.\n  apply div_lo_bound.\n  rewrite <-div_rem_rel, mult_comm.\n  reflexivity.\n  unfold rem.\n  rewrite div_result.\n  exists (n - q * d).\n  reflexivity.\n  apply div_works, d_ne_0.\nQed.\n\nLemma rem_unique:\n  forall n d q r:nat,\n  (d * q <= n < d * S q /\\ r = n - d * q) ->\n  rem n d = Some r.\nProof.\n  intros n d q r [Hbounds Hrel].\n  unfold rem.\n  rewrite div_unique with (q := q).\n  rewrite Hrel, mult_comm; reflexivity.\n  assumption.  \nQed.\n\nLemma div_ge:\n  forall n m:nat,\n  m <> 0 -> m <= n ->\n  exists q, div n m = Some q /\\ 1 <= q.\nProof.\n  intros n m m_ne_0 m_le_n.\n  cut (exists q:nat,\n       div n m = Some q /\\\n       m * q <= n < m * S q).\n  intros [q [EHq [Hblo Hbhi]]].\n  exists q.\n  split; [assumption | ..].  \n  destruct q as [|q'].\n  rewrite mult_1_r in Hbhi.\n  absurd (n < m).\n  apply le_not_lt; assumption.\n  assumption.\n  apply le_n_S, le_0_n.\n  apply div_works; assumption.\nQed.\n\n(*\n\nExtended GCD adapted from\n\negcd :: Natural -> Natural -> (Natural,(Natural,Natural))\negcd a 0 = (a,(1,0))\negcd a b =\n    if c == 0\n    then (b, (1, a `div` b - 1))\n    else (g, (u, t + (a `div` b) * u))\n  where\n    c = a `mod` b\n    (g,(s,t)) = egcd c (b `mod` c)\n    u = s + (b `div` c) * t\n\nobtained from\n\nhttps://gilith.wordpress.com/2015/06/24/\nnatural-number-greatest-common-divisor/\n\n*)\n\nFixpoint egcd_aux (a b x:nat) :=\n  match a, b, x with\n  | S _, 0, _ => Some (a, 1, 0)\n  | S _, S _, S y =>\n    match rem a b, div a b with\n    | Some c, Some a_div_b =>\n      match c with\n      | 0 => Some (b, 1, a_div_b - 1)\n      | _ =>\n        match rem b c with\n        | Some rem_b_c =>\n          match egcd_aux c rem_b_c y with\n          | Some (g, s, t) =>\n            match div b c with\n            | Some b_div_c =>\n              let u := s + b_div_c * t in\n              Some (g, u, t + a_div_b * u)\n            | _ => None\n            end\n          | None => None\n          end\n        | None => None\n        end\n      end\n      | _, _ => None\n    end\n  | _, _, _ => None\n  end.\n\nDefinition egcd (n m:nat) :=\n  egcd_aux n m (S(m + n)).\n\nLemma egcd_works:\n  forall n m:nat,\n  m <= n -> m <> 0 ->\n  exists g, exists s, exists t,\n  Some (g, s, t) = egcd n m /\\\n  rem n g = Some 0 /\\\n  rem m g = Some 0 /\\\n  s * n = t * m + g.\nProof.\n  (* let's start by generalizing the auxiliary\n     parameter *)\n  cut (forall n m x:nat,\n       m <= n -> m <> 0 -> n + m < x ->\n       exists g, exists s, exists t,\n       Some (g, s, t) = egcd_aux n m x /\\\n       rem n g = Some 0 /\\\n       rem m g = Some 0 /\\\n       s * n = t * m + g).\n  intros Hgen n m m_le_n m_ne_0.\n  unfold egcd.\n  apply Hgen; auto.\n  rewrite plus_comm.\n  apply lt_n_Sn.\n\n  (* starts the strong induction *)\n  intros n.\n  elim n using nat_strong_ind.\n  \n  (* eliminates the n = 0 case *)\n  intros m x m_le_0 m_ne_0 _.\n  absurd (m = 0).\n  assumption.\n  apply n_le_0; assumption.\n\n  (* starts introducing the strong induction\n     hypothesis *)\n  clear n.\n  intros n Hrec.\n  intros m x m_le_n m_ne_0 n_p_m_lt_x.\n\n  (* unfolding the definitions gives us a\n     cluttered result *)\n  (* let's isolate the right branch *)\n  destruct n as [|n'].\n  absurd (m = 0).\n  assumption.\n  apply n_le_0; assumption.\n  simpl.\n  destruct m as [|m'].\n  absurd (0 = 0).\n  assumption.\n  reflexivity.\n  simpl.\n  destruct x as [|x'].\n  absurd (S n' + S m' < 0).\n  apply lt_n_O.\n  assumption.\n  simpl.\n  cut (exists c, rem (S n') (S m') = Some c).\n  intros [c EHc].\n  rewrite EHc.\n  cut (exists a_div_b,\n       div (S n') (S m') = Some a_div_b).\n  intros [a_div_b EHa_div_b].\n  rewrite EHa_div_b.\n  \n  (* now we have two different cases, depending\n     if c is 0 *)\n\n  (* the c = 0 case is quite simple *)\n  destruct c as [|c'].\n  exists (S m'), 1, (a_div_b - 1).\n  rewrite rem_unique\n    with (q := a_div_b) (r := 0).\n  rewrite rem_unique\n    with (q := 1) (r := 0).\n  split.\n  reflexivity.\n  split.\n  reflexivity.\n  split.\n  reflexivity.\n  rewrite mult_minus_distr_r.\n  repeat rewrite mult_1_l.\n  rewrite plus_comm, le_plus_minus_r.\n  cut (exists q:nat,\n       div (S n') (S m') = Some q /\\\n       exists r:nat,\n       rem (S n') (S m') = Some r /\\\n       (S n') = (S m') * q + r).\n  intros [q [EHq [r [EHr Hqr]]]].\n  rewrite EHc in EHr.\n  injection EHr.\n  intros r_eq_0.\n  rewrite <-r_eq_0 in Hqr.\n  rewrite EHq in EHa_div_b.\n  injection EHa_div_b.\n  intros q_eq_a_div_b.\n  rewrite plus_0_r, q_eq_a_div_b,\n          mult_comm in Hqr.\n  assumption.\n  apply rem_works.\n  assumption.\n  rewrite <-mult_1_l at 1.\n  apply mult_le_compat_r.\n  cut (exists q,\n       div (S n') (S m') = Some q /\\\n       1 <= q).\n  intros [q [q_is_quot quot_ge_1]].\n  rewrite EHa_div_b in q_is_quot. \n  injection q_is_quot.\n  intros q_is_a_div_b.\n  rewrite q_is_a_div_b; assumption.\n  apply div_ge.\n  assumption.\n  assumption.\n  split.\n  split.\n  rewrite mult_1_r; apply le_n.\n  rewrite mult_comm.\n  unfold mult.\n  rewrite plus_0_r, <-plus_0_l at 1.\n  apply plus_lt_compat_r, lt_0_Sn.\n  rewrite mult_1_r, <-minus_n_n; reflexivity.\n  (* FIXME: ADMIT *)\n  admit.\n\n  (* we start the other case by asssuming the\n     existence of some terms *)\n  cut (exists rem_b_c,\n       rem (S m') (S c') = Some rem_b_c).\n  intros [rem_b_c EHrem_b_c].\n  rewrite EHrem_b_c.\n  cut (exists b_div_c,\n       div (S m') (S c') = Some b_div_c).\n  intros [b_div_c EHb_div_c].\n  rewrite EHb_div_c.\n\n  (* FIXME: INCLUDE THE PROOF IN THE UNFOLDING *)\n  admit.\n  admit.\n  admit.\n  admit.\n  admit.\nQed.\n\nFixpoint sum_series\n  (f:nat->option nat) (a n:nat) :=\n  match n with\n  | 0 => Some 0\n  | S m => \n      match (f a), (sum_series f (S a) m) with\n      | Some fa, Some s => Some (fa + s)\n      | _, _ => None\n      end\n  end.\n\nTheorem num_zeros_end_fact:\n  forall n m p q:nat,\n  fact n = p * (pow 10 m) /\\\n  ~exists q, fact n = q * (pow 10 (S m)) ->\n  sum_series\n    (fun i:nat => (div n (pow 5 i))) 1 n =\n  Some m.", "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/factorial_zeros.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7889219174716852}}
{"text": "(**********************************************************************\n    Permutation.v                        \n                                                                     \n    Definition and properties of permutations                         \n                                                                     \n    Definition: permutation                                          \n                                                                     \n                                    Laurent.Thery@inria.fr (2006)    \n  **********************************************************************)\nRequire Export List.\nRequire Export ListAux.\n \nSection permutation.\n\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.\n\nHint Constructors permutation : core.\n\n(************************************** \n   Reflexivity\n **************************************)\n \nTheorem permutation_refl l : permutation l l.\nProof.\ninduction l as [|a l1 H].\n  apply permutation_nil.\napply permutation_skip with (1 := H).\nQed.\n\nHint Resolve permutation_refl : core.\n\n(************************************** \n   Symmetry\n   **************************************)\n \nTheorem permutation_sym l m : permutation l m -> permutation m l.\nProof.\nintro H'; elim H'.\n- apply permutation_nil.\n- intros a l1' l2' H1 H2.\n  apply permutation_skip with (1 := H2).\n- intros a b l1'.\n  apply permutation_swap.\n- intros l1' l2' l3' H1 H2 H3 H4.\n  apply permutation_trans with (1 := H4) (2 := H2).\nQed.\n\n(************************************** \n   Compatibility with list length\n   **************************************)\n \nTheorem permutation_length l m : permutation l m -> length l = length m.\nProof.\nintros 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 l : permutation l nil -> l = nil.\nProof.\nintros 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 l1 l2 :\n  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.\nProof.\nintro H; elim H; clear H l1 l2; auto.\n  intros a l3 l4 H0 H1 b H2.\n  eq_tac.\n    injection H2; auto.\n  apply permutation_nil_inv; auto.\n  injection H2; intros H3 H4; rewrite <- H3; auto.\n  apply permutation_sym; auto.\nintros; discriminate.\nQed.\n\nTheorem permutation_one_inv a l : permutation (a :: nil) l -> l = a :: nil.\nProof.\nintro H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.\nQed.\n\n(************************************** \n   Compatibility with the belonging\n   **************************************)\n \nTheorem permutation_in a l m : permutation l m -> In a l -> In a m.\nProof.\nintro H; elim H; simpl in |- *; auto; intuition.\nQed.\n\n(************************************** \n   Compatibility with the append function\n   **************************************)\n \nTheorem permutation_app_comp l1 l2 l3 l4 :\n permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nProof.\nintro H; revert l3 l4; elim H; clear H l1 l2;\n simpl in |- *; auto.\n  intros a b l l3 l4 H.\n  cut (permutation (l ++ l3) (l ++ l4)); auto.\n    intros; apply permutation_trans with (a :: b :: l ++ l4); auto.\n  elim l; simpl in |- *; auto.\nintros l1 l2 l3 H H0 H1 H2 l4 l5 H3.\napply permutation_trans with (l2 ++ l4); auto.\nQed.\n\nHint Resolve permutation_app_comp : core.\n\n(************************************** \n   Swap two sublists\n   **************************************)\n \nTheorem permutation_app_swap  l1 l2 : permutation (l1 ++ l2) (l2 ++ l1).\nProof.\nrevert l2; elim l1; auto.\n  intros; rewrite <- app_nil_end; auto.\nintros a l H l2.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\n  apply permutation_trans with (l ++ l2 ++ a :: nil); auto.\n  apply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.\n    simpl in |- *; auto.\n  apply permutation_trans with (l ++ (a :: nil) ++ l2); auto.\n    apply permutation_sym; auto.\n  replace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\n    apply permutation_app_comp; auto.\n    elim l2; simpl in |- *; auto.\n    intros a0 l0 H0.\n    apply permutation_trans with (a0 :: a :: l0); auto.\n  apply (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 a b l1 l2 l3 :\n permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).\nProof.\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.\n  apply 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 a l : \n  In a l -> exists l1 : list A, permutation (a :: l1) l.\nProof.\nelim 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 a l1 l2 :\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)).\nintro H; elim H; clear H l1 l2.\n- intros l11 l12; case l11; simpl in |- *; intros; discriminate.\n- intros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.\n    exists (nil (A:=A)); exists l1; simpl in |- *; split; auto.\n      eq_tac; injection H1; auto.\n    injection H1; intros H2 H3; rewrite <- H2; auto.\n  intros a1 l111 H1.\n  case (H0 l111 l12); auto.\n    injection H1; auto.\n  intros l3 (l4, (Hl1, Hl2)).\n  exists (a0 :: l3); exists l4; split; simpl in |- *; auto.\n    eq_tac; injection H1; auto.\n  injection H1; intros H2 H3; rewrite H3; auto.\n- intros a0 b l l11 l12; case l11; simpl in |- *.\n    case l12; try (intros; discriminate).\n    intros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.\n      repeat eq_tac; injection H; auto.\n    injection H; intros H1 H2 H3; rewrite H2; auto.\n  intros a1 l111; case l111; simpl in |- *.\n    intros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.\n      repeat eq_tac; injection H; auto.\n    injection H; intros H1 H2 H3; rewrite H3; auto.\n  intros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;\n  split; auto.\n  repeat eq_tac; injection H; auto.\n- intros l1 l2 l3 H H0 H1 H2 l11 l12 H3.\n  case H0 with (1 := H3).\n  intros l4 (l5, (Hl1, Hl2)).\n  case H2 with (1 := Hl1).\n  intros l6 (l7, (Hl3, Hl4)).\n  exists l6; exists l7; split; auto.\n  apply permutation_trans with (1 := Hl2); auto.\nQed.\n \nTheorem permutation_cons_ex a l1 l2 :\n permutation (a :: l1) l2 ->\n exists l3 : list A,\n   (exists l4 : list A, l2 = l3 ++ a :: l4 /\\ permutation l1 (l3 ++ l4)).\nProof.\nintro 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 a l1 l2 : \n permutation (a :: l1) (a :: l2) -> permutation l1 l2.\nProof.\nintro 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.\n  intros 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 a l1 l2 :\n In (a, l1) (split_one l2) -> permutation (a :: l1) l2.\nProof.\nrevert a l1; elim l2; clear l2; simpl in |- *; auto.\n  intros a l1 H1; case H1.\nintros a l H a0 l1 [H0| H0].\n  injection H0; intros H1 H2; rewrite H2; rewrite H1; auto.\ngeneralize H H0; elim (split_one l); simpl in |- *; auto.\n  intros 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 a l1 :\n In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).\nProof.\nelim l1; simpl in |- *; auto.\n  intros H; case H.\nintros a0 l H [H0| H0]; auto.\n  exists 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(************************************** \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 l1 l2 :\n  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.\nProof.\nrevert l1 l2; elim n; simpl in |- *; auto.\n  intros l1 l2; case l2.\n    simpl in |- *; intros H0 [H1| H1].\n      rewrite <- H1; auto.\n    case H1.\n  simpl 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.\n  apply permutation_skip; auto.\n  apply H with (2 := H3).\n  apply eq_add_S.\n  apply trans_equal with (1 := H0).\n  change (length l2 = length (a1 :: l3)) in |- *.\n  apply permutation_length; auto.\n  apply permutation_sym; apply split_one_permutation; auto.\napply split_one_permutation; auto.\nQed.\n \nTheorem all_permutations_permutation l1 l2 :\n  In l1 (all_permutations l2) -> permutation l1 l2.\nProof.\nintro 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 l1 l2 :\n  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).\nProof.\nrevert l1 l2; elim n; simpl in |- *; auto.\n  intros l1 l2; case l2.\n    intros H H0; rewrite permutation_nil_inv with (1 := H0); auto.\n  simpl in |- *; intros; discriminate.\n  intros n0 H l1; case l1.\n  intros 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.\n  apply 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.\n  apply eq_add_S.\n  apply trans_equal with (1 := H1).\n  change (length l2 = length (a1 :: x)) in |- *.\n  apply permutation_length; auto.\n  apply 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 l1 l2 :\n  permutation l1 l2 -> In l1 (all_permutations l2).\nProof.\nintro 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, {permutation l1 l2} + {~ permutation l1 l2}.\nProof.\nintros H l1 l2.\ncase (In_dec (list_eq_dec H) l1 (all_permutations l2)).\n  intros i; left; apply all_permutations_permutation; auto.\nintros i; right; contradict i; apply permutation_all_permutations; auto.\nDefined.\n\n(* A more efficient version *)\nDefinition permutation_dec1 :\n  (forall a b : A, {a = b} + {a <> b}) ->\n  forall l1 l2, {permutation l1 l2} + {~ permutation l1 l2}.\nProof.\nintros dec; fix permutation_dec1 1; intros l1; case l1.\n  intros l2; case l2.\n    left; auto.\n  intros a l3; right; intros H; generalize (permutation_length _ _ H); \n  discriminate.\nintros a l3 l2.\ncase (In_dec1 dec a l2); intros H1.\n  case H1.\n  intros x; case x; simpl.\n  intros l4 l5 Hl4l5.\n  case (permutation_dec1 l3 (l4 ++ l5)); intros H2.\n    left; subst.\n    apply permutation_trans with ((a::l5) ++ l4); auto.\n      simpl; apply permutation_skip; auto.\n      apply permutation_trans with (1 := H2); auto.\n      apply permutation_app_swap.\n    apply permutation_app_swap.\n  right; contradict H2.\n  apply permutation_inv with a.\n  apply permutation_trans with (1 := H2).\n  rewrite Hl4l5.\n  apply permutation_trans with ((a::l5) ++ l4); auto.\n    apply permutation_app_swap.\n  simpl; apply permutation_skip; auto.\n  apply permutation_app_swap.\nright; contradict H1.\napply permutation_in with (1 := H1); auto with datatypes.\nDefined.\n\nEnd permutation.\n\n(************************************** \n   Hints\n   **************************************)\n\nHint Constructors permutation : core.\nHint Resolve permutation_refl : core.\nHint Resolve permutation_app_comp : core.\nHint 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].\nArguments permutation_dec1 [A].\n\n(************************************** \n   Permutation is compatible with map\n   **************************************)\n \nTheorem permutation_map  (A B : Set) (f : A -> B) l1 l2 :\n permutation l1 l2 -> permutation (map f l1) (map f l2).\nProof.\nintro 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 : core.\n \n(************************************** \n  Permutation  of a map can be inverted\n  *************************************)\n\nLocal Definition permutation_map_ex_aux (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.\nProof.\nintro H; generalize l3; elim H; clear H l1 l2 l3.\n- intros l3; case l3; simpl in |- *; auto.\n    intros H; exists (nil (A := A)); auto.\n  intros; discriminate.\n- intros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.\n    intros; discriminate.\n  intros a1 l H1; case (H0 l); auto.\n    injection H1; auto.\n  intros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.\n  eq_tac; auto; injection H1; auto.\n- intros a0 b l l3; case l3.\n  intros; discriminate.\n  intros a1 l0; case l0; simpl in |- *.\n    intros; discriminate.\n  intros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.\n  repeat eq_tac; injection H; auto.\n- intros l1 l2 l3 H H0 H1 H2 l0 H3.\n  case H0 with (1 := H3); auto.\n  intros l4 (HH1, HH2).\n  case H2 with (1 := HH2); auto.\n  intros l5 (HH3, HH4); exists l5; split; auto.\n  apply permutation_trans with (1 := HH3); auto.\nQed.\n \nTheorem permutation_map_ex (A B : Set) (f : A -> B) l1 l2 :\n permutation (map f l1) l2 ->\n exists l3, permutation l3 l1 /\\ l2 = map f l3.\nProof.\nintro 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 (A B : Set) (f : A -> list B) l1 l2 :\n permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).\nProof.\nintro H; elim H; simpl in |- *; auto.\n  intros a b l; auto.\n  repeat rewrite <- app_ass.\n  apply 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": "sudoku", "sha": "7e38b82006a76b54691be3c57f5426b4da750ca6", "save_path": "github-repos/coq/thery-sudoku", "path": "github-repos/coq/thery-sudoku/sudoku-7e38b82006a76b54691be3c57f5426b4da750ca6/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7888400295647942}}
{"text": "(*******************************************************)\n(* Theorem: there exist infinitely many prime numbers. *)\n(*******************************************************)\n(* Euclid's proof *)\n(******************)\n(* Coq file largely inspired by a proof given by Frédéric Blanqui in a blog discussion *)\n(***************************************************************************************)\n\n\nRequire Import Arith Omega.\n\n\n(**********************************************)\n(* Two lemmas about multiplication and order. *)\n(**********************************************)\n\nLemma mult_gt_0 : forall x y : nat, x * y > 0 <-> x > 0 /\\ y > 0.\nProof.\n  intros x y. destruct x. omega. destruct y. omega.\n  split. omega. intros _. simpl. apply gt_Sn_O.\nQed.\n\nLemma mult_le_r : forall x y : nat, y > 0 -> x <= x * y.\nProof.\n  intros x y H. rewrite <- (mult_1_r x) at 1. apply mult_le_compat_l. exact H.\nQed.\n\n\n(*****************)\n(* Divisibility. *)\n(*****************)\n\nDefinition div (x y : nat) := exists z : nat, y = x * z.\n\nNotation \"x & y\" := (div x y) (at level 70).\n\n(* Four lemmas about divisibility. *)\n\nLemma div_le : forall x y : nat, y > 0 -> x & y -> x <= y.\nProof.\n  intros x y. intros Hy [z Hdiv].\n  subst. apply mult_le_r. rewrite mult_gt_0 in Hy. tauto.\nQed.\n\nLemma div_mult_l : forall x y z : nat, x & y -> x & z * y.\nProof.\n  intros x y z [z' Hdiv]. subst. exists (z * z'). ring.\nQed.\n\nLemma div_minus : forall x y z : nat, x & y -> x & z -> x & y - z.\nProof.\n  intros x y z [z1 Hdiv_xy] [z2 Hdiv_xz]. subst. exists (z1 - z2).\n  rewrite <- mult_minus_distr_l. reflexivity.\nQed.\n\nLemma div_trans : forall x y z : nat, x & y -> y & z -> x & z.\nProof.\n  intros x y z [z1 Hdiv_xy] [z2 Hdiv_yz]. exists (z1 * z2). subst. ring.\nQed.\n\n\n(*****************************************)\n(* Product of a list of natural numbers. *)\n(*****************************************)\n\nRequire Import List.\n\nFixpoint prod (l : list nat) : nat :=\n  match l with\n    | nil => 1\n    | x::l' => x * prod l'\n  end.\n\n(* Three lemmas about product and order. *)\n\nLemma prod_gt_0 : forall l : list nat, ~In 0 l <-> prod l > 0.\nProof.\n  induction l; simpl. omega. rewrite mult_gt_0. intuition.\nQed.\n\nLemma prod_div : forall l : list nat, forall x : nat, In x l -> x & prod l.\nProof.\n  intros l x. induction l; simpl. tauto.\n  intros [Ha|Hx]. subst. exists (prod l). reflexivity.\n  destruct (IHl Hx) as [z Hdiv]. rewrite Hdiv. exists (a * z). ring.\nQed.\n\nCorollary prod_le_x : forall l : list nat, forall x : nat, ~In 0 l -> In x l -> x <= prod l.\nProof.\n  intros l x H0 Hx.\n  apply prod_gt_0 in H0.\n  exact (div_le x (prod l) H0 (prod_div l x Hx)).\nQed.\n\n\n(******************)\n(* Prime numbers. *)\n(******************)\n\nDefinition prime (p : nat) := p >= 2 /\\ (forall x : nat, x & p -> x = 1 \\/ x = p).\n\nLemma zero_is_not_prime : ~prime 0.\nProof.\n  unfold prime. omega.\nQed.\n\n(* We use classical reasoning to simplify the proof a little bit. *)\nRequire Import Classical.\n\nLemma nontrivial_divisor : forall x : nat, x >= 2 -> ~prime x -> exists y, y >= 2 /\\ y < x /\\ y & x.\nProof.\n  intros x x_le_2 x_is_not_prime.\n  apply not_and_or in x_is_not_prime. intuition. apply not_all_ex_not in H.\n  destruct H as [d Hd]. apply imply_to_and in Hd. destruct Hd as [H1 H2].\n  apply not_or_and in H2.\n  assert (p_lt_x : d < x). apply div_le in H1. omega. omega.\n  assert (p_ge_2 : d >= 2). destruct H2 as [Hd_not_1 Hd_not_x].\n  destruct (eq_nat_dec d 0). subst. destruct H1. omega. omega. clear H2.\n  exists d. tauto.\nQed.\n\nLemma prime_divisor : forall x : nat, x >= 2 -> exists p, prime p /\\ p & x.\nProof.\n  intro x. pattern x. apply lt_wf_ind. clear x. intros n H n_le_2.\n  (* Law of excluded middle: x is prime or x is not prime. *)\n  destruct (classic (prime n)) as [n_is_prime | n_is_not_prime].\n  (* n is prime *)\n  exists n. split ; [assumption | exists 1 ; ring].\n  (* n is not prime *)\n  set (divisor := nontrivial_divisor n n_le_2 n_is_not_prime).\n  destruct divisor as [d Hdiv]. destruct Hdiv as [d_le_2 [d_lt_n Hdn]].\n  destruct (H d d_lt_n d_le_2) as [p Hyp].\n  exists p. split. tauto. apply div_trans with (x := p) (y := d) (z := n) ; tauto.\nQed.\n\nTheorem primes_are_infinite : ~ (exists l : list nat, forall x : nat, prime x <-> In x l).\nProof.\n  intros [l all_primes_in_l]. set (n := S (prod l)).\n  (* We prove that n is prime. *)\n    assert (n_is_prime : prime n). split.\n    (* n >= 2 *)\n    apply le_n_S. apply lt_le_S. apply prod_gt_0.\n    rewrite <- all_primes_in_l. apply zero_is_not_prime.\n    (* We now prove that assuming that there is a divider a of n that is\n    different from 1 and n leads to a contradiction. *)\n    intros a a_div_n. destruct (eq_nat_dec a 1). tauto.\n    right. destruct (eq_nat_dec a n). assumption. apply False_rec.\n    (* We prove that a is >= 2. *)\n    assert (a_ge_2 : a >= 2). destruct a_div_n as [q hn].\n    destruct (eq_nat_dec a 0). subst. rewrite mult_0_l in hn. omega. omega.\n    (* Hence, a has a prime divider p. *)\n    destruct (prime_divisor a a_ge_2) as [p [p1 p2]].\n    (* By transitivity, p divides n. *)\n    generalize (div_trans p a n p2 a_div_n) ; intro p_div_n.\n    (* Since all primes are in l, p is in l and p divides prod l. *)\n    assert (p_in_l : In p l). rewrite <- all_primes_in_l. assumption.\n    apply (prod_div l p) in p_in_l.\n    (* Thus p divides n - (prod l) = 1. *)\n    generalize (div_minus p n (prod l) p_div_n p_in_l).\n    unfold n. rewrite <- minus_Sn_m, minus_diag. 2: reflexivity.\n    (* Therefore p = 1 but 1 is not prime. Hence, n is prime. *)\n    intro p_div_1. apply div_le in p_div_1. 2: omega. unfold prime in p1. omega.\n  (* We now prove that n is not in l. *)\n  rewrite all_primes_in_l in n_is_prime.\n  assert (zero_not_in_l : ~In 0 l).\n  rewrite <- all_primes_in_l. exact zero_is_not_prime.\n  generalize (prod_le_x l n zero_not_in_l n_is_prime).\n  unfold n. omega.\nQed.\n", "meta": {"author": "AurelienAlvarez", "repo": "Infinitely-many-primes", "sha": "cf6226b862b7b531078c5b2eebcf1f67f70cf027", "save_path": "github-repos/coq/AurelienAlvarez-Infinitely-many-primes", "path": "github-repos/coq/AurelienAlvarez-Infinitely-many-primes/Infinitely-many-primes-cf6226b862b7b531078c5b2eebcf1f67f70cf027/infinitely-many-prime-numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.788801824550825}}
{"text": "Load MyLists.\n\nRequire Import PeanoNat.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | []       => match l2 with\n          | [] => true\n          | _  => false\n          end\n  | cons x l1' => match l2 with\n          | []         => false\n          | cons y l2' => match (Nat.eqb x y) with\n                          | true  => beq_natlist l1' l2'\n                          | false => false\n                          end\n          end\n  end.\n\nExample test_beq_natlist1 : (beq_natlist nil nil = true).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n(*\nAxiom woot : forall n, Nat.eqb n n = true.\nSearch (Nat.eqb _ _). (* We find Nat.eqb_refl *)\n*)\n\nTheorem beq_natlist_refl : forall l:natlist, true = beq_natlist l l.\nProof.\n  intros l.\n  induction l.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. (* use simpl to rewrite from definition of beq_natlist *)\n               rewrite Nat.eqb_refl. exact IHl.\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/9_beq_natlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7887522567479444}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives.\n\n*)\n\n(* ########################################################### *)\n(** * Propositions *)\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\n\n(** In Coq, the type of things that can (potentially)\n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated\n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P].\n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on\nequality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat\n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that\ntakes evidence for [P] as input and produces evidence for [Q] as its\noutput.\n*)\n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?\n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other\n      datatype.\n\n    - Sometimes a proposition is declared to be true without\n      substantiating evidence.  Such propositions are called _axioms_.\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\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(** 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(** ** \"Introducing\" conjunctions *)\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  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' :\n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\n(** Conversely, the [destruct] 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  destruct 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  destruct H as [HP HQ].\n  apply HQ.\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  destruct 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    [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  split.\n  split.\n  apply HP. apply HQ. apply HR.\nQed.\n\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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)\n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  destruct 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  destruct 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; split; intros; assumption.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R H H0.\n  split; intros. apply H0, H. assumption. destruct H as [PQ QP].\n  destruct H0 as [QR RQ]. apply QP, RQ, 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\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 (Logical \"or\") *)\n\n(** ** Implementing 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(** *** *)\n(** Since [P \\/ Q] has two constructors, doing [destruct] 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  destruct 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  destruct 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. destruct 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  destruct H as [[ | HQ] [ | HR]].\n  left. assumption.\n  left. assumption.\n  left. assumption.\n  right. split; assumption.\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; intros.\n    - destruct H as [ HP | [ HQ HR ]]; split.\n      left. assumption.\n      left. assumption.\n      right. assumption.\n      right. assumption.\n    - destruct H as [ [ | HQ ] [HP | HR]].\n      + left. assumption.\n      + left. assumption.\n      + left. assumption.\n      + right. split; assumption.\nQed.\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_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  destruct H.\n  rewrite H. rewrite H0. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (andb_false)  *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b; simpl in H; [right | left] ; assumption.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false)  *)\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b; simpl in H; [left | right]; assumption.\nQed.\n\n(** **** Exercise: 2 stars, optional (orb_false_elim)  *)\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b; simpl in H.\n  split. assumption.\n  inversion H.\n  split. reflexivity.\n  assumption.\nQed.\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\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(** *** *)\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), False -> P.\nProof. intros P contra. 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(* #################################################### *)\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, advanced (True)  *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := truth.\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to\n    higher-order [Prop]s. *)\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. assumption.  Qed.\n\n(** *** *)\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. destruct 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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros p q H NQ.\n  unfold not.\n  intros P.\n  apply H in P.\n  unfold not in NQ.\n  apply NQ.\n  apply P.\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.\n  unfold not.\n  intros H.\n  destruct H as [HP HH].\n  apply HH, HP.\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(* FILL IN HERE *)\n(** [] *)\n\n(** *** Constructive logic *)\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     from evidence for [P]. *)\n  Abort.\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\n(* FILL IN HERE *)\n(** [] *)\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), ~ ~ (P \\/ ~ P).\nProof.\n  intros P.\n  unfold not.\n  intros H.\n  apply H.\n  right.\n  intros.\n  apply H.\n  left.\n  apply H0.\nQed.\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\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\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 m H.\n  unfold not in H.\n  generalize dependent m.\n  induction n.\n  intros.\n  - destruct m.\n    + simpl. apply ex_falso_quodlibet. apply H. reflexivity.\n    + simpl. reflexivity.\n  - destruct m.\n    + simpl. reflexivity.\n    + simpl. intros. apply IHn. intros NMeq.\n      apply H. rewrite NMeq. reflexivity.\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  induction n; intros; unfold not.\n    - intros Meq. rewrite <- Meq in H. simpl in H. inversion H.\n    - intros SnMeq. rewrite SnMeq in H. destruct m; inversion SnMeq.\n      + rewrite H1 in IHn. apply IHn in H. unfold not in H. apply H. reflexivity.\nQed.\n(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)\n", "meta": {"author": "dredozubov", "repo": "sf", "sha": "e48b559c657036e567df689d183903702f6e580e", "save_path": "github-repos/coq/dredozubov-sf", "path": "github-repos/coq/dredozubov-sf/sf-e48b559c657036e567df689d183903702f6e580e/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.9173026607161, "lm_q1q2_score": 0.7885718522600889}}
{"text": "(** * Induction: Proof by Induction *)\n\n(* ################################################################# *)\n(** * Separate Compilation *)\n\n(** Before getting started on this chapter, we need to import\n    all of our definitions from the previous chapter: *)\n\nFrom COC Require Export Basics.\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We can prove that [0] is a neutral element for [+] on the left\n    using just [reflexivity].  But the proof that it is also a neutral\n    element on the _right_ ... *)\n\nTheorem plus_n_O_firsttry : \n  forall n:nat,\n  n = n + 0.\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 plust_n_O_secondtry : \n  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.\nAbort.\n\n(** We could use [destruct n'] to get one step further, but,\n    since [n] can be arbitrarily large, we'll never get all the there\n    if we just go on like this. *)\n\n(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we often need a more powerful reasoning\n    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 : \n  forall n:nat, \n  n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *) \n    simpl. \n    rewrite <- IHn'. \n    reflexivity.\nQed.\n\n(** 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 [|].\n\n    The assumption [n' + 0 = n'] is added to the context with the name\n    [IHn'] (i.e., the Induction Hypothesis for [n']). **)\n\nTheorem minus_n_n : \n  forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(** 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, standard, especially useful (basic_induction) **)\n\nTheorem mult_n_O : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* 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. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    intros m.\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. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    rewrite <- plus_n_O.\n    reflexivity.\n  - (* n = S n' *)\n    rewrite <- plus_n_Sm.\n    rewrite <- IHn'.\n    simpl.\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' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard (double_plus) \n\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, \n  double n = n + n .\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite -> IHn'.\n    rewrite <- plus_n_Sm.\n    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  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    rewrite -> IHn'.\n    rewrite -> negb_involutive.\n    simpl.\n    reflexivity.\nQed.\n\n(** Large proofs are often broken into a sequence of theorems, with later \n    proofs referring to earlier theorems.\n    But sometimes a proof will require some miscellaneous fact that is too\n    trivial and of too little general interest to bother giving it its own \n    top-level name.\n\n    It is convenient to be able to simply state and prove the\n    needed \"sub-theorem\" right at the point where it is used.  \n    The [assert] tactic. *)\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  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    rewrite -> H.\n    reflexivity.\nQed.\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(** 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... *)\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.\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.\n    reflexivity. }\n  rewrite -> H.\n  reflexivity.\nQed.\n\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite <- plus_n_Sm.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  assert (H: n + m = m + n). { rewrite -> plus_comm. reflexivity. } rewrite -> H.\n  rewrite -> plus_assoc. reflexivity.\nQed.\n\n(** Now prove commutativity of multiplication.  You will probably\n    want to define and prove a \"helper\" theorem to be used\n    in the proof of this one. Hint: what is [n * (1 + k)]? *)\nLemma mult_n_Sm : forall n m:nat,\n  n * (S m) = n + n * m.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_swap.\n    reflexivity.\nQed.\n\nTheorem mult_comm : forall n m:nat,\n  n * m = m * n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    rewrite -> mult_n_O.\n    reflexivity.\n  - (* n = S n' *)\n    rewrite -> mult_n_Sm.\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (more_exercises) \n\n    a) it can be proved using only simplification and rewriting.\n    b) it also requires case analysis [destruct].\n    c) it also requires induction. **)\n\nCheck leb.\n\nTheorem leb_refl : forall n:nat,\n  true = (n <=? n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  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. destruct b eqn:Eb.\n  - (* b = true *)\n    simpl.\n    reflexivity.\n  - (* b = false *)\n    simpl.\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 m p H. induction p as [| p' IHp'].\n  - (* p = 0 *)\n    simpl.\n    rewrite -> H.\n    reflexivity.\n  - (* p = S p' *)\n    simpl.\n    rewrite -> IHp'.\n    reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  (S n) =? 0 = false.\nProof.\n  intros n.\n  simpl.\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 b1 b2:bool,\n    orb (andb b1 b2) (orb (negb b1) (negb b2)) = true.\nProof.\n  intros [] [].\n  - (* b1 = true, b2 = true *)\n    simpl.\n    reflexivity.\n  - (* b1 = true, b2 = false *)\n    simpl.\n    reflexivity.\n  - (* b1 = false, b2 = true *)\n    simpl.\n    reflexivity.\n  - (* b1 = false, b2 = 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. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* 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. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    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. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl.\n    reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, especially useful (binary_commute) \n\n    Recall the [incr] and [bin_to_nat] functions that you\n    wrote for the [binary] exercise in the [Basics] chapter.  Prove\n    that the following diagram commutes:\n\n                            incr\n              bin ----------------------> bin\n               |                           |\n    bin_to_nat |                           |  bin_to_nat\n               |                           |\n               v                           v\n              nat ----------------------> nat\n                             S\n\n    That is, incrementing a binary number and then converting it to\n    a (unary) natural number yields the same result as first converting\n    it to a natural number and then incrementing.\n    Name your theorem [bin_to_nat_pres_incr] (\"pres\" for \"preserves\").\n\n    Before you start working on this exercise, copy the definitions of\n    [incr] and [bin_to_nat] from your solution to the [binary]\n    exercise here so that this file can be graded on its own.  If you\n    want to change your original definitions to make the property\n    easier to prove, feel free to do so! \n\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\nFixpoint incr (n:bin) : bin :=\n  match n with\n  | Z => B1 Z\n  | B0 n' => B1 n'\n  | B1 n' => B0 (incr n')\n  end.\n\nFixpoint bin_to_nat (b:bin) : nat :=\n  match b with\n  | Z => O\n  | B0 b' => 2 * (bin_to_nat b')\n  | B1 b' => 1 + 2 * (bin_to_nat b')\n  end.\n\nExample test_bin_to_nat1 :\n  bin_to_nat(incr (B0 (B0 (B1 Z)))) = 5.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_to_nat2 :\n  bin_to_nat(B1 Z) = 1.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_to_nat3 :\n  bin_to_nat(B0 (B1 Z)) = 2.\nProof. simpl. reflexivity. Qed.\n\n\n\n\n\n", "meta": {"author": "antferdom", "repo": "logic", "sha": "9831d136bb72828c9be619561cad2f2315c63284", "save_path": "github-repos/coq/antferdom-logic", "path": "github-repos/coq/antferdom-logic/logic-9831d136bb72828c9be619561cad2f2315c63284/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663754105328, "lm_q2_score": 0.9173026635420488, "lm_q1q2_score": 0.7885718513913743}}
{"text": "Require Import BinNat.\nRequire Import BinPos.\n\n(* Definiciones para números binarios. *)\n\n(* Nos dice si el m-ésimo bit de k es 0. *)\nDefinition zeroBit (k m: N) : bool :=\nN.eqb (N.land k m) 0.\n\n(* Función de máscara.\n * m es un entero de la forma 2^i *)\nDefinition mask (k m: N): N :=\nN.land k (N.pred m).\n\n(* Función que revisa si dos enteros tienen los primeros x bits iguales. \n * m es 2^x *)\nDefinition matchPrefix (k p m: N) : bool :=\nN.eqb (mask k m) p.\n\n(* Función que decide si un número positivo es impar. *)\nDefinition podd (n: positive) : bool :=\nmatch n with\n| xH => true\n| xO _ => false\n| xI _ => true\nend.\n\n(* División entre 2 para números positivos. \n * Esta operación funciona solo para números distintos de 1. *)\nDefinition pdiv2 (n: positive) : positive :=\nmatch n with\n| xH => xH \n| xO n' => n'\n| xI n' => n'\nend.\n\n(* Función auxiliar que calcula el bit menos significativo de un número\n * positivo. *)\nFixpoint lowestBitP (x: positive): positive :=\nmatch x with\n| xO x' => xO (lowestBitP x')\n| _ => xH\nend.\n\n(* Función que obtiene el primer bit encendido de un número.\n * Esta función se puede calcular más rápidamente usando complemento a 2.\n * Pero como solo queremos verificar, no lo haremos de la manera más \n * eficiente. *)\nDefinition lowestBit (x: N) : N :=\nmatch x with\n| N0 => N0\n| Npos p => Npos (lowestBitP p)\nend.\n\n(* Función que obtiene el primer bit en que dos números difieren *)\nDefinition branchingBit (p0 p1: N) : N := lowestBit (N.lxor p0 p1).\n", "meta": {"author": "victorz3", "repo": "CoqPatriciaTrees", "sha": "8ffecd6276845d20b954283f08936367e87eed1d", "save_path": "github-repos/coq/victorz3-CoqPatriciaTrees", "path": "github-repos/coq/victorz3-CoqPatriciaTrees/CoqPatriciaTrees-8ffecd6276845d20b954283f08936367e87eed1d/Defs_Bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7885718488736196}}
{"text": "Require Import Arith Omega.\n\nFixpoint fast (a b n: nat): nat :=\n  match n with\n    | O => a\n    | S p => fast b (a+b) p\n  end.\n\nFixpoint slow (a b n: nat): nat :=\n  match n with\n    | O => a\n    | 1 => b\n    | S (S pp as p) => slow a b pp + slow a b p\n  end.\n\nLemma equiv:\n  forall n a b, slow a b n = fast a b n.\nProof.\n  induction n using lt_wf_ind; intros.\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/fibonacci.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7885314984355106}}
{"text": "(*==================================================================*)\n(*======================= Propositional Logic ======================*)\n(*==================================================================*)\nSection PL.\n\nVariables A B C D: Prop.\n\nLemma ex11: (A -> C) /\\ (B -> C) -> (A /\\ B) -> C.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  apply H1.\n  apply H0.\nQed.\n\nLemma ex12: ~A \\/ ~B -> ~(A /\\ B).\nProof.\n  intros.\n  intro.\n  destruct H0 as [H1 H2].\n  elim H.\n    - intro. apply H0. apply H1.\n    - intro. apply H0. apply H2.\nQed.\n\nLemma ex13: (A -> (B \\/ C)) /\\ (B -> D) /\\ (C -> D) -> (A -> D).\nProof.\n  intros.\n  destruct H as [H1 H2].\n  destruct H2 as [H3 H4].\n  elim H1.\n    - apply H3.\n    - apply H4.\n    - apply H0.\nQed.\n\nLemma ex14: (A /\\ B) -> ~(~A \\/ ~B).\nProof.\n  intros.\n  intro.\n  destruct H as [H1 H2].\n  elim H0.\n    - intro. apply H. apply H1.\n    - intro. apply H. apply H2.\nQed.\n\nEnd PL.\n\n(*==================================================================*)\n(*======================== First-Order Logic =======================*)\n(*==================================================================*)\nSection FOL.\n\nVariable X: Set.\nVariable t: X.\nVariable P Q R: X -> Prop.\n\nLemma ex21: (forall x, (P x) -> (Q x)) -> (forall y, ~(Q y)) -> (forall x, ~(P x)).\nProof.\n  intros.\n  intro.\n  apply (H0 x).\n  apply H.\n  exact H1.\nQed.\n\nLemma ex22: (forall x, (P x) \\/ (Q x)) -> (exists y, ~(Q y)) -> (forall x, (R x) -> ~(P x)) -> (exists x, ~(R x)).\nProof.\n  intros.\n  destruct H0.\n  exists x.\n  intro.\n  destruct (H x).\n  - apply (H1 x). exact H2. exact H3.\n  - apply H0. exact H3.\nQed.\n\nEnd FOL.\n\n(*==================================================================*)\n(*========================= Classical Logic ========================*)\n(*==================================================================*)\nSection CL.\n\nVariable A B: Prop.\nVariable X: Set.\nVariable t: X.\nVariable P: X -> Prop.\n\nAxiom pme: forall Q: Prop, Q \\/ ~Q.\nAxiom double_neg_law : forall A:Prop, ~~A -> A.\n\nLemma ex31: (~A -> B) -> (~B -> A).\nProof.\n  intros.\n  elim (pme A).\n  trivial.\n  intros.\n  apply H in H1.\n  contradiction.\nQed.\n\nLemma ex32: ~(exists x: X, ~(P x)) -> (forall x: X, P x).\nProof.\n  intros.\n  elim (pme (P x)).\n  trivial.\n  intro.\n  absurd (exists x0, ~(P x0)).\n  trivial.\n  exists x.\n  assumption.\nQed.\n\nLemma ex33: ~(forall x: X, ~(P x)) -> (exists x: X, P x).\nProof.\n  intros.\n  elim (pme (exists x, P x)).\n  intro.\n  assumption.\n  intro H1.\n  elim H.\n  red.\n  intros.\n  apply H1.\n  exists x.\n  apply H0.\nQed.\n\nEnd CL.", "meta": {"author": "GoncaloEsteves", "repo": "Formal-Verification", "sha": "e865fa4dbf3b50bb4823cc3963fdc43c0e3c25df", "save_path": "github-repos/coq/GoncaloEsteves-Formal-Verification", "path": "github-repos/coq/GoncaloEsteves-Formal-Verification/Formal-Verification-e865fa4dbf3b50bb4823cc3963fdc43c0e3c25df/Exercises/06_Coq(1)/questoesCoq1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7885310423141509}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\n(** We have seen many examples of factual claims (_propositions_)\n    and ways of presenting evidence of their truth (_proofs_).  In\n    particular, we have worked extensively with _equality\n    propositions_ ([e1 = e2]), implications ([P -> Q]), and quantified\n    propositions ([forall x, P]).  In this chapter, we will see how\n    Coq can be used to carry out other familiar forms of logical\n    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) : Prop.\n\nCheck (forall n m : nat, n + m = m + n) : Prop.\n\n(** Note that _all_ syntactically well-formed propositions have type\n    [Prop] in Coq, regardless of whether they are true.\n\n    Simply _being_ a proposition is one thing; being _provable_ is\n    a different thing! *)\n\nCheck 2 = 2 : Prop.\n\nCheck 3 = 2 : Prop.\n\nCheck forall n : nat, n = 2 : Prop.\n\n(** Indeed, propositions not only have types: they are\n    _first-class_ entities that can be manipulated in all the same\n    ways as any of the other things 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 other kinds of expressions. *)\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : 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_claim_is_true :\n  plus_claim.\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 : 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. injection H as H1. apply H1.\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 in\n    Coq's standard library using the [Notation] mechanism). Because\n    [eq] can be used with elements of any type, it is also\n    polymorphic: *)\n\nCheck @eq : 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, and we need to turn\n    off the inference of this implicit argument to see the full type\n    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  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 that [B] is true, we can conclude that [A /\\ B] is also\n    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, standard (and_exercise) *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H. destruct n as [| n'].\n  - simpl in H. split. \n    + reflexivity.\n    + apply H.\n  - discriminate.\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 specific theorem, both formulations are fine.  But\n    it's important to understand how to work with conjunctive\n    hypotheses because conjunctions often arise from intermediate\n    steps in proofs, especially in larger developments.  Here's a\n    simple example: *)\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  apply and_exercise in 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    In such cases we can do a [destruct] (possibly as part of\n    an [intros]) and use an underscore pattern [_] to indicate\n    that the unneeded conjunct should just be thrown away. *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (proj2) *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [_ HQ].\n  apply HQ. Qed.\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  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n\n(** **** Exercise: 2 stars, standard (and_assoc)\n\n    (In the following proof of associativity, notice how the _nested_\n    [intros] 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.\n    + apply HP. \n    + 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 : 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.  (This infix notation stands for [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 with other data types like [nat], can be done\n    explicitly with [destruct] or implicitly with an [intros]\n    pattern): *)\n\nLemma eq_mult_0 :\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, it suffices to show\n    that one of its sides holds. This is done via two tactics, [left]\n    and [right].  As their names imply, the first one requires proving\n    the left side of the disjunction, while the second requires\n    proving its right side.  Here is a trivial use... *)\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\n(** ... and here is a slightly more interesting example requiring both\n    [left] and [right]: *)\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 [] [] H.\n  - left. reflexivity.  \n  - left. reflexivity.\n  - right. reflexivity.\n  - 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\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, demonstrating that some given proposition is\n    _not_ true. Such statements are expressed with the logical\n    negation operator [~]. *)\n\n(** To see how negation works, recall the _principle of explosion_\n    from the [Tactics] chapter, which asserts that, if we assume a\n    contradiction, then any other proposition can be derived. \n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].\n\n    Coq actually makes a slightly different (but equivalent) choice,\n    defining [~ P] as [P -> False], where [False] is a specific\n    contradictory proposition defined in the standard library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not : 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 np Q p.\n  apply np in p.\n  destruct p.\nQed.\n\n(** [] *)\n\n(** Inequality is a frequent enough example of negated statement\n    that there is a special notation for it, [x <> y]:\n\n      Notation \"x <> y\" := (~(x = y)).\n*)\n\n(** We can use [not] to state that [0] and [1] are different elements\n    of [nat]: *)\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  (** The proposition [0 <> 1] is exactly the same as\n      [~(0 = 1)], that is [not (0 = 1)], which unfolds to\n      [(0 = 1) -> False]. (We use [unfold not] explicitly here\n      to illustrate that point, but generally it can be omitted.) *)\n  unfold not.\n  (** To prove an inequality, we may assume the opposite\n      equality... *)\n  intros contra.\n  (** ... and deduce a contradiction from it. Here, the\n      equality [O = S O] contradicts the disjointness of\n      constructors [O] and [S], so [discriminate] takes care\n      of it. *)\n  discriminate contra.\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    make Coq understand it!  Here are proofs of a few familiar facts\n    to get you warmed 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 (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, especially useful (contrapositive) *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q HPQ HNQ HP.\n  apply HNQ. apply HPQ. apply HP. Qed. \n\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 [HP HNP].\n  apply HNP 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\n(** Since inequality involves a negation, it also requires a little\n    practice to be able to work with it fluently.  Here is one useful\n    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 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  - (* 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.          (* note implicit [destruct b] here *)\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(** Unlike [False], which is used extensively, [True] is used\n    relatively rarely, since it is trivial (and therefore\n    uninteresting) to prove as a goal, and conversely it provides no\n    useful information as a hypothesis.\n\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 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 simply the conjunction\n    of 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.\n  intros P. split.\n  - intros H. apply H.\n  - intros H. 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 [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\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. 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. split. { apply HQ. } { apply HR. }\nQed.\n   \n     \n(** [] *)\n\n(* ================================================================= *)\n(** ** Setoids and Logical Equivalence *)\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 have\n    to import the Coq library that supports it: *)\n\nFrom Coq Require Import Setoids.Setoid.\n\n(** A \"setoid\" is a set equipped with an equivalence relation,\n    that is, a relation that is reflexive, symmetric, and transitive.\n    When two elements of a set are equivalent according to the\n    relation, [rewrite] can be used to replace one element with the\n    other. We've seen that already with the equality relation [=] in\n    Coq: when [x = y], we can use [rewrite] to replace [x] with [y],\n    or vice-versa.\n\n    Similarly, the logical equivalence relation [<->] is reflexive,\n    symmetric, and transitive, so we can use it to replace one part of\n    a proposition with another: if [P <-> Q], then we can use\n    [rewrite] to replace [P] with [Q], or vice-versa. *)\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 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\n(** We can now use these facts with [rewrite] and [reflexivity]\n    to give smooth proofs of statements involving equivalences.  For\n    example, here is a ternary version of the previous [mult_0]\n    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\n    direction of the equivalence will be useful. *)\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\nDefinition evend x := exists n : nat, x = double n.\n\nLemma four_is_evend : evend 4.\nProof.\n  unfold evend. exists 2. reflexivity.\nQed.\n\n(** Conversely, if we have an existential hypothesis [exists x, P] in\n    the context, we can destruct it to obtain a witness [x] and a\n    hypothesis stating that [P] holds of [x]. *)\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  (* WORKED IN CLASS *)\n  intros n [m Hm]. (* note implicit [destruct] here *)\n  exists (2 + m).\n  apply Hm.  Qed.\n\n(** **** Exercise: 1 star, standard, especially useful (dist_not_exists)\n\n    Prove that \"[P] holds for all [x]\" implies \"there is no [x] for\n    which [P] does not hold.\"  (Hint: [destruct H as [x E]] works on\n    existential assumptions!)  *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros X P HPx [x HNPx].\n  apply HNPx. apply HPx.\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. 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(** [] *)\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 in 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 recursive\n    function taking an element and a list and returning a 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 how [In] starts out applied to a variable and only gets\n    expanded when we do case analysis on this variable.) *)\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l ->\n    In (f x) (map f l).\nProof.\n  intros A B f l x.\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: 3 stars, standard (In_map_iff) *)\nTheorem In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\n  - intros H. induction l as [|x' l' IHl'].\n    * simpl in H. destruct H.\n    * simpl in H. destruct H as [H1 | H2].\n      + exists x'. split. { apply H1. } { simpl. left. reflexivity. }\n      + apply IHl' in H2. destruct H2 as [x'' [H H']]. exists x''.\n        split. { apply H. } { simpl. right. apply H'. }\n  - intros [x [H H']]. induction l as [|x' l' IHl'].\n    * simpl in H'. destruct H'.\n    * simpl. destruct H' as [H' | H'].\n      + left. rewrite -> H'. apply H.\n      + right. apply IHl' in H'. apply H'.\nQed. \n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (In_app_iff) *)\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  - split.\n    * simpl. intros H. right. apply H.\n    * simpl. intros [H' | H']. { destruct H'. } { apply H'. }\n  - split.\n    * simpl. intros [H' | H']. \n      + left. left. apply H'. \n      + rewrite <- or_assoc. right. apply IH. apply H'.\n    * simpl. intros [[H' | H'] | H' ].\n      + left. apply H'.\n      + right. apply IH. left. apply H'.\n      + right. apply IH. right. apply H'.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (All)\n\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\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. induction l as [|x' l' IHl'].\n  - split.\n    * simpl. intros. apply I.\n    * simpl. intros. destruct H0.\n  - split.\n    * simpl. intros H. split.\n      + apply H. left. reflexivity.\n      + apply IHl'. intros. apply H. right. apply H0.\n    * simpl. intros. destruct H0.\n      + destruct H. rewrite <- H0. apply H.\n      + apply IHl'. { destruct H. apply H1. } { apply H0. }\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (combine_odd_evend)\n\n    Complete the definition of the [combine_odd_evend] 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_evend (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if oddb n then Podd n else Peven n.\n\n(** To test your definition, prove the following facts: *)\n\nTheorem combine_odd_evend_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_evend Podd Peven n.\nProof.\n  intros. unfold combine_odd_evend.\n  destruct (oddb n).\n  - apply H. reflexivity.\n  - apply H0. reflexivity.\nQed. \n\nTheorem combine_odd_evend_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_evend Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros Podd Peven n.\n  unfold combine_odd_evend. intros.\n  rewrite H0 in H.\n  apply H.\nQed.\n\nTheorem combine_odd_evend_elim_evend :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_evend Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n. unfold combine_odd_evend. intros.\n  rewrite H0 in H. apply H.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature that distinguishes Coq from some other popular\n    proof assistants (e.g., ACL2 and Isabelle) is that it treats\n    _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 all in detail in order to use Coq.\n    This 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 [Check] to ask Coq to print the type\n    of an expression.  We can also use it to ask what theorem a\n    particular identifier refers to. *)\n\nCheck plus      : nat -> nat -> nat.\nCheck plus_comm : forall n m : nat, n + m = m + n.\n\n(** Coq checks the _statement_ of the [plus_comm] theorem (or prints\n    it for us, if we leave off the part beginning with the colon) in\n    the same way that it checks the _type_ of any term (e.g., plus)\n    that we ask it to [Check]. Why? *)\n\n(** The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_, which represents a logical derivation establishing\n    of the truth of the statement [forall n m : nat, n + m = m + n].  The\n    type of this object is the proposition which it is a proof of. *)\n\n(** Intuitively, this makes sense because the statement of a\n    theorem tells us what we can use that theorem for. *)\n\n(** Operationally, this analogy goes even further: by applying a\n    theorem as if it were a function, i.e., applying it to values and\n    hypotheses with matching types, we can specialize its result\n    without having to resort to intermediate assertions.  For example,\n    suppose we wanted to prove the following result: *)\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\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  (* WORKED IN CLASS *)\n  intros x y z.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\nAbort.\n\n(** We saw similar problems back in Chapter [Induction], and saw one\n    way to work around them by using [assert] to derive a specialized\n    version of [plus_comm] that can be used to rewrite exactly where\n    we want. *)\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\n(** A more elegant alternative is to apply [plus_comm] directly\n    to the arguments we want to instantiate it with, in much the same\n    way as we apply a polymorphic function to a type argument. *)\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(** Let's see another example of using a theorem like a function. \n\n    The following theorem says: any list [l] containing some element\n    must be nonempty. *)\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. intro Hl.\n  rewrite Hl in H.\n  simpl in H.\n  apply H.\nQed.\n\n(** What makes this interesting is that one quantified variable\n    ([x]) does not appear in the conclusion ([l <> []]). *)\n\n(** We should be able to use this theorem to prove the special case\n    where [x] is [42]. However, naively, the tactic [apply in_not_nil]\n    will fail because it cannot infer the value of [x]. *)\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\n(** There are several ways to work around this: *)\n\n(** Use [apply ... with ...] *)\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(** Use [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(** 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. (The details of how this proof\n    works are not critical -- the goal here is just to illustrate what\n    can be done.) *)\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(** Coq's logical core, the _Calculus of Inductive\n    Constructions_, differs in some important ways from other formal\n    systems that are used by mathematicians to write down precise and\n    rigorous definitions and proofs.  For example, in the most popular\n    foundation for 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, about equally natural and\n    easy to work with.  For example, instead of saying that a natural\n    number [n] belongs to the set of even numbers, we would say in Coq\n    that [even n] holds, where [even : nat -> Prop] is a property\n    describing even numbers.\n\n    We conclude this chapter with a brief discussion of some of the\n    most significant differences between the two worlds. *)\n\n(* ================================================================= *)\n(** ** Functional Extensionality *)\n\n(** Coq's logic is intentionally quite minimal.  This means that there\n    are occasionally some cases where translating standard\n    mathematical reasoning into Coq can be cumbersome or sometimes\n    even impossible, unless we enrich the core logic with additional\n    axioms. *)\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, we can use it at\n    _any_ type -- in particular, we can write propositions claiming\n    that two _functions_ are equal to each other: *)\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same output on every input:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_. *)\n\n(** Informally, an \"extensional property\" is one that pertains to an\n    object's observable behavior.  Thus, functional extensionality\n    simply means that a function's identity is completely determined\n    by what we can observe from it -- i.e., the results we obtain\n    after applying it. *)\n\n(** However, functional extensionality is not part of Coq's built-in\n    logic.  This means that some apparently \"obvious\" propositions are\n    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 using\n    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(** Defining something as an [Axiom] has the same effect as stating a\n    theorem and skipping its proof using [Admitted], but it alerts the\n    reader that this isn't just something we're going to come back and\n    fill in 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 this can render it _inconsistent_ -- that is, it may\n    become possible to prove every proposition, including [False],\n    [2+2=5], etc.!\n\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe to add: hard work by highly trained mathematicians is\n    often required to establish the consistency of any particular\n    combination of axioms.\n\n    Fortunately, 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    (You may also see [plus_comm] listed as an assumption, depending\n    on whether the copy of [Tactics.v] in the local directory has the\n    proof of [plus_comm] filled in.) *)\n\n(** **** Exercise: 4 stars, standard (tr_rev_correct)\n\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] is asymptotically quadratic.\n    We can improve this with the following definitions: *)\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 of [rev] is said to be _tail-recursive_, because the\n    recursive call to the function is the last operation that needs to\n    be performed (i.e., we don't have to execute [++] after the\n    recursive call); a decent compiler will generate very efficient\n    code in this case.\n\n    Prove that the two definitions are indeed equivalent. *)\n\nLemma lemma1 : forall {X} (l1 l2 : list X), rev_append l1 l2 = rev_append l1 [] ++ l2.\nProof.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. intros. rewrite -> IHl1. destruct l2. \n    * rewrite -> app_nil_r. rewrite <- IHl1. reflexivity.\n    * rewrite -> (IHl1 [x]). rewrite <- app_assoc. reflexivity.\nQed.\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros. apply functional_extensionality.\n  intros l. \n  induction l as [| x' l' IHl'].\n  - reflexivity.\n  - simpl. unfold tr_rev. simpl. unfold tr_rev in IHl'. rewrite <- IHl'. apply lemma1.\nQed.\n  \n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions vs. Booleans\n\n    We've seen two different ways of expressing logical claims in Coq:\n    with _booleans_ (of type [bool]), and with _propositions_ (of type\n    [Prop]).\n\n    Here are the key differences between [bool] and [Prop]:\n\n                                       bool     Prop\n                                    -------------------\n       decidable?                   |  yes   |   no   |\n                                    -------------------\n       useable with match?          |  yes   |   no   |\n                                    -------------------\n       useable with forall?         |  no    |   yes  |\n                                    -------------------\n*)\n(** The most essential difference between the two worlds is\n    _decidability_.  Every Coq expression of type [bool] can be\n    simplified in a finite number of steps to either [true] or\n    [false] -- i.e., there is a terminating mechanical procedure for\n    deciding whether or not it is [true].  This means that, for\n    example, the type [nat -> bool] is inhabited only by functions\n    that, given a [nat], always return either [true] or [false]; and\n    this, in turn, means that there is no function in [nat -> bool]\n    that checks whether a given number is the code of a terminating\n    Turing machine.  By contrast, the type [Prop] includes both\n    decidable and undecidable mathematical propositions; in\n    particular, the type [nat -> Prop] does contain functions\n    representing properties like \"the nth Turing machine halts.\"\n\n    The other two rows in the table above follow directly from this\n    essential difference.  To evaluate a pattern match (or\n    conditional) on a boolean, we need to know whether the scrutinee\n    evaluates to [true] or [false]; this only works for [bool], not\n    [Prop].  On the other hand, if [X] is an infinite type, then\n    [forall (x:X), e] makes sense if [e] has type [Prop], but not if\n    it has type [bool], since in general there is no effective way to\n    check whether a boolean expression yields [true] for every one of\n    an infinite number of choices for [x]. *)\n\n(* ================================================================= *)\n(** ** Working with Decidable Properties *)\n\n(** Since [Prop] includes _both_ decidable and undecidable properties,\n    we have two choices when when we are dealing with a property that\n    happens to be decidable: we can express it as a boolean\n    computation or as a function into [Prop].\n\n    For instance, to claim that a number [n] is even, we can say\n    either... *)\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 : evend 42.\nProof. unfold evend. exists 21. reflexivity. Qed.\n\n(** Of course, it would be pretty strange if these two\n    characterizations of evenness did not describe the same set of\n    natural numbers!  Fortunately, we can prove that they do... *)\n\n(** We first need two helper lemmas. *)\nLemma 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) *)\nLemma evenb_double_conv : forall n, exists k,\n  n = if evenb n then double k else S (double k).\nProof.\n  Check evenb_S.\n  induction n.\n  - simpl. exists 0. reflexivity.\n  - rewrite -> evenb_S. destruct IHn as [n' H]. destruct (evenb n).\n    + simpl. exists n'. f_equal. apply H.\n    + simpl. rewrite -> H. exists (S n'). reflexivity.\nQed.\n\n(** [] *)\n\n(** Now the main theorem: *)\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> evend n.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** In view of this theorem, we say that the boolean computation\n    [evenb n] is _reflected_ in the truth of the proposition\n    [exists k, n = double k]. *)\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either\n      - (1) that [n =? m] returns [true], or\n      - (2) that [n = m].\n    Again, these two notions are equivalent. *)\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\n(** Even when the boolean and propositional formulations of a claim\n    are equivalent from a purely logical perspective, they are often\n    not equivalent from the point of view of convenience for some\n    specific purpose. *)\n\n(** In the case of even numbers above, when proving the\n    backwards direction of [even_bool_prop] (i.e., [evenb_double],\n    going from the propositional to the boolean claim), we used a\n    simple induction on [k].  On the other hand, the converse (the\n    [evenb_double_conv] exercise) required a clever generalization,\n    since we can't directly prove [(evenb n = true) -> evend\n    n]. *)\n\n(** We cannot _test_ whether a [Prop] is true or not in a\n    function definition; as a consequence, the following code fragment\n    is rejected: *)\n\nFail\nDefinition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects\n    an element of [bool] (or some other inductive type with two\n    elements).  The reason has to do with the _computational_ nature\n    of Coq's core language, which is designed so that every function\n    it can express is computable and total.  One reason for this is to\n    allow the extraction of executable programs from Coq developments.\n    As a consequence, [Prop] in Coq does _not_ have a universal case\n    analysis operation telling whether any given proposition is true\n    or false, since such an operation would allow us to write\n    non-computable functions.\n\n    Beyond the fact that non-computable properties are impossible in\n    general to phrase as boolean computations, even many _computable_\n    properties are easier to express using [Prop] than [bool], since\n    recursive function definitions in Coq are subject to significant\n    restrictions.  For instance, the next chapter shows how to define\n    the property that a regular expression matches a given string\n    using [Prop].  Doing the same with [bool] would amount to writing\n    a regular expression matching algorithm, which would be more\n    complicated, harder to understand, and harder to reason about than\n    a simple (non-algorithmic) definition of this property.\n\n    Conversely, an important side benefit of stating facts using\n    booleans is enabling some proof automation through computation\n    with Coq terms, a technique known as _proof by reflection_.\n\n    Consider the following statement: *)\n\nExample evend_1000 : evend 1000.\n\n(** The most direct way to prove this is to give the value of [k]\n    explicitly. *)\n\nProof. unfold evend. exists 500. reflexivity. Qed.\n\n(** The proof of the corresponding boolean statement is even\n    simpler (because we don't have to invent the witness: Coq's\n    computation mechanism does it for us!). *)\n\nExample evend_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 evend_1000'' : evend 1000.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n(** Although we haven't gained much in terms of proof-script\n    size in this case, larger proofs can often be made considerably\n    simpler by the use of reflection.  As an extreme example, a famous\n    Coq proof of the even more famous _4-color theorem_ uses\n    reflection to reduce the analysis of hundreds of different cases\n    to a boolean computation. *)\n\n(** Another notable difference is that the negation of a \"boolean\n    fact\" is straightforward to state and prove: simply flip the\n    expected boolean result. *)\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  (* WORKED IN CLASS *)\n  reflexivity.\nQed.\n\n(** In contrast, propositional negation can be more difficult\n    to work with directly. *)\n\nExample not_even_1001' : ~(evend 1001).\nProof.\n  (* WORKED IN CLASS *)\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intro H.\n  discriminate H.\nQed.\n\n(** Equality provides a complementary example, where it is sometimes\n    easier to work in the propositional world.\n\n    Knowing that [(n =? m) = true] is generally of little direct help in\n    the middle of a proof involving [n] and [m]; however, if we\n    convert the statement to the equivalent form [n = m], we can\n    rewrite with it. *)\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\n(** We won't discuss reflection any further for the moment, but it\n    serves as a good example showing the complementary strengths of\n    booleans and general propositions, and being able to cross back\n    and forth between the boolean and propositional worlds will often\n    be convenient in later chapters. *)\n\n(** **** Exercise: 2 stars, standard (logical_connectives)\n\n    The following theorems relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\nSearch (_ && _ = true).\n\nTheorem andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  split.\n  - intros. destruct b1. \n    + destruct b2.\n      * split. { reflexivity. } { reflexivity. }\n      * discriminate H.\n    +  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. destruct b1.\n    + left. reflexivity.\n    + destruct b2.\n      * right. reflexivity.\n      * destruct H. left. reflexivity.\n  - intros [].\n    + rewrite -> H. reflexivity.\n    + rewrite -> H. destruct b1. { reflexivity. } { reflexivity. }\nQed.  \n(** [] *)\n\n(** **** Exercise: 1 star, standard (eqb_neq)\n\n    The following theorem is an alternate \"negative\" formulation of\n    [eqb_eq] that is more convenient in certain situations.  (We'll see\n    examples in later chapters.)  Hint: [not_true_iff_false]. *)\n\nCheck not_true_iff_false.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  split.\n  - rewrite <- not_true_iff_false. intros H H'. apply H. rewrite H'. rewrite <- eqb_refl. reflexivity.\n  - intros H. destruct (x =? y) eqn:xy.\n    + apply eqb_eq in xy. rewrite xy in H. destruct H. reflexivity.\n    + reflexivity.\nQed. \n    \n(** [] *)\n\n(** **** Exercise: 3 stars, standard (eqb_list)\n\n    Given a boolean operator [eqb] for testing equality of elements of\n    some type [A], we can define a function [eqb_list] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [eqb_list] function below.  To make sure that your\n    definition is correct, prove the lemma [eqb_list_true_iff]. *)\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  | h1 :: t1, h2 :: t2 => if eqb h1 h2 then eqb_list eqb t1 t2 else false \n  | _, _ => false \n  end.\n\nCheck eqb_eq.\nSearch (_ :: _ = _ :: _).\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 [|x' l1' IHl1']. \n  - destruct l2.\n    * split. reflexivity. reflexivity.\n    * simpl. split. discriminate. discriminate. \n  - destruct l2.\n    * simpl. split. discriminate. discriminate.\n    * simpl. destruct (eqb x' x) eqn:x'x.\n      + rewrite -> IHl1'. split. \n        { intros. f_equal. apply H. apply x'x. apply H0. }\n        { intros. injection H0 as []. apply H0. }\n      + split. \n        { discriminate. }\n        { intros. injection H0 as a b. apply H in a. rewrite a in x'x. discriminate x'x. }\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, especially useful (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 defined above. *)\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. induction l as [|x' l' IHl'].\n    - simpl. split. { intros. apply I. } { intros. reflexivity. }\n    - simpl. rewrite <- IHl'. \n      Search (_ && _ = true <-> _ = true /\\ _ = true).\n      apply andb_true_iff.\nQed.\n\n(** (Ungraded thought question) Are there any important properties of\n    the function [forallb] which are not captured by this\n    specification? *)\n\n(*  p1 : forall X test (x : X) (l : list X), \n    test x = true /\\ forallb test l = true <-> forallb test (x :: l) = true\n\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. discriminate contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m]. *)\n\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n  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(** It may seem strange that the general excluded middle is not\n    available by default in Coq, since it is a standard feature of\n    familiar logics like ZFC.  But there is a distinct advantage in\n    not assuming the excluded middle: statements in Coq make stronger\n    claims than the analogous statements in standard mathematics.\n    Notably, when there is a Coq proof of [exists x, P x], it is\n    always possible to explicitly exhibit a value of [x] for which we\n    can prove [P x] -- in other words, every proof of existence is\n    _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\n    [a ^ b] ([a] to the power [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 finish the proof knowing that such [a] and [b]\n    exist but we cannot determine what their actual values are (at least,\n    not from 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 only 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\n    here: 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, standard (excluded_middle_irrefutable)\n\n    Proving the consistency of Coq with the general excluded middle\n    axiom requires complicated reasoning that cannot be carried out\n    within Coq itself.  However, the following theorem implies that it\n    is always safe to assume a decidability axiom (i.e., an instance\n    of excluded middle) for any _particular_ Prop [P].  Why?  Because\n    we cannot prove the negation of such an axiom.  If we could, we\n    would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)] (since [P]\n    implies [~ ~ P], by lemma [double_neg], which we proved above),\n    which would be a  contradiction.  But since we can't, it is safe\n    to add [P \\/ ~P] as an axiom.\n\n    Succinctly: for any proposition P,\n       [Coq is consistent ==> (Coq + P \\/ ~P) is consistent].\n\n    (Hint: You may need to come up with a clever assertion as the\n    next step in the proof.) *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H.\n  apply H. right. intros. apply H. left. apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (not_exists_dist)\n\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  unfold excluded_middle. intros. \n  assert (H1: P x \\/ ~ (P x)).\n  - apply H.\n  - destruct H1.\n    + apply H1.\n    + exfalso. apply H0. exists x. apply H1.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (classical_axioms)\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 [excluded_middle])\n    are equivalent.\n\n    Hint: Rather than considering all pairs of statements pairwise,\n    prove a single circular chain of implications that connects them\n    all. *)\n\n(* https://github.com/marshall-lee/software_foundations/blob/master/lf/Logic.v *)\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_to_perice : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle. unfold peirce.\n  intros H P' Q H1.\n  assert (H2: P' \\/ ~ P'). { apply H. }\n  destruct H2.\n  - apply H0.\n  - apply H1. intros H2. apply H0 in H2. destruct H2.\nQed.\n\nTheorem em_to_raa :\n  excluded_middle -> double_negation_elimination.\nProof.\n  unfold excluded_middle. unfold double_negation_elimination. unfold not.\n  intros H P'. intros nnp. assert (H2 : P' \\/ ~ P'). { apply H. }\n  destruct H2.\n  - apply H0.\n  - exfalso. apply nnp. assumption.\nQed.\n\nTheorem peirce_to_dne :\n  peirce -> double_negation_elimination.\nProof.\n  unfold peirce. unfold double_negation_elimination.\n  intros H P'. unfold not. intros H1.\n  apply H with (Q := False). \n  intros H2. apply H1 in H2. destruct H2.\nQed.\n\nTheorem dne_to_demorgan : double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  unfold double_negation_elimination. unfold de_morgan_not_and_not. unfold not.\n  intros H. intros P' Q. intros H1. apply H. intros. apply H1. split. \n  - intros. apply H0. left. apply H2.\n  - intros. apply H0. right. apply H2.\nQed.\n\nTheorem demorgan_to_ito : de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not. unfold implies_to_or. unfold not.\n  intros H P' Q H1. apply H. intros [H2 H3]. apply H2. intros HP'. apply H3. apply H1. apply HP'.\nQed.\n\nTheorem ito_to_em : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or. unfold excluded_middle. unfold not.\n  intros H P'. apply or_commut. apply H. intros. apply H0.\nQed.\n\n(* 2020-10-01 08:07 *)\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8887587912826163, "lm_q1q2_score": 0.7885108902842921}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nSection CaseTacticForTypeFamilies.\n\n(** * Exercise *)\n(* CONSTRAINTS: do _not_ use `rewrite`, `->` or any lemmas to solve this exercise.\n   Use _only_ the `case` tactic *)\nLemma sym T (x y : T) :\n  x = y -> y = x.\nProof.\nmove=> eqxy.\nby case e: y / eqxy.\nQed.\n(* Hint: use the `case: ... / ...` variant *)\n\n\n(** * Exercise *)\n(* Figure out what `alt_spec` means and prove the lemma *)\nLemma altP P b :\n  reflect P b -> alt_spec P b b.\nProof.\nPrint alt_spec.\nmove=> R.\ncase E: b / R ; by constructor.\nQed.\n(* Hint: use the `case: ... / ...` variant *)\n\nEnd CaseTacticForTypeFamilies.\n\n\n\nSection MultiRules.\n\n(** * Exercise: A spec for boolean equality *)\nVariant eq_xor_neq (T : eqType) (x y : T) : bool -> bool -> Type :=\n  | EqNotNeq of x = y : eq_xor_neq x y true true\n  | NeqNotEq of x != y : eq_xor_neq x y false false.\n\n\nLemma eqVneq (T : eqType) (x y : T) :\n  eq_xor_neq x y (y == x) (x == y).\nProof.\ncase: (altP eqP) => [-> | yx].\nby case: eqP => [_ | //] ; constructor.\ncase: eqP=> xy ; [rewrite xy in yx ; move: yx | constructor] ; case: eqP => //.\nQed.\n(** Hint: Use `case: (altP eqP)` to get the right assumptions.\n          Also, try using `case: eqP` instead to see the difference. *)\n\n\n(** * Exercise: use `eqVneq` to prove this lemma *)\nLemma eqVneq_example (T : eqType) (w x y z : T) :\n  w == x -> z == y ->\n  (x == w) /\\ (y == z) /\\ (z == y).\nProof.\nmove=> wx zy.\nsplit; [move: wx | split ; [move: zy | ]] ; last done ; case: eqVneq => //.\nQed.\n\n\n\n(** * Exercise *)\nLemma andX (a b : bool) : reflect (a * b) (a && b).\nProof.\nby apply/(iffP idP) ; [case/andP | case=> ->].\nQed.\nArguments andX {a b}.\n\n\n(** * Exercise: prove the following lemma using `andX` lemma. *)\n(* CONSTRAINTS: you may only use `move` and `rewrite` to solve this;\n     no `case` or `[]` or any other form of case-splitting is allowed!\n     and no lemmas other than `andX` *)\nLemma andX_example a b :\n  a && b -> b && a && a && b.\nProof.\nmove=> ab.\nby rewrite !(andX ab).\nQed.\n\n(** Hint: `reflect`-lemmas may act like functions (implications) *)\n\nEnd MultiRules.\n\n\nLemma ltn_ind P :\n  (forall n, (forall m, m < n -> P m) -> P n) ->\n  forall n, P n.\nProof.\nmove=> proof n.\napply: (proof).\nelim: n=> // n f m lemn.\napply/proof=> p lepm.\napply/f.\nexact: (leq_trans lepm lemn).\nQed.", "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/hw07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.7885108869436119}}
{"text": "Inductive BinTree :=\n|leaf : BinTree\n|node : nat -> BinTree -> BinTree -> BinTree.\n\nPrint BinTree_ind.\n\nRequire Import Nat.\nRequire Import List.\nImport ListNotations.\n\nFixpoint preorder (b : BinTree) : list nat :=\n  match b with\n  | leaf => []\n  | node n ltree rtree => n::(preorder ltree)++(preorder rtree)\n  end.\n\nDefinition one := (node 1 leaf leaf).\nDefinition two := (node 2 leaf leaf).\nDefinition three := (node 3 one two).\n\nCompute (preorder one).\nCompute (preorder leaf).\nCompute (preorder three).\n\nFixpoint search (b : BinTree) (x : nat) : bool :=\n  match b with\n  | leaf => false\n  | node n ltree rtree => if (n =? x) then true\n                           else orb (search ltree x)(search rtree x)\n  end.\n\nCompute (search three 0).\nCompute (search three 1).\n\nLemma search_correct:\n  forall b x, In x (preorder b) -> search b x = true.\nProof.\n  induction b. \n  - intros.\n    simpl.\n    simpl in H.\n    contradiction.\n  - intros.\n    simpl in H.\n    destruct H as [H | H].\n    + rewrite H.\n      simpl.\n      rewrite PeanoNat.Nat.eqb_refl.\n      trivial.\n    + simpl in H.\n      SearchPattern (In _ (_ ++ _) <-> _).\n      rewrite in_app_iff in H.\n      destruct H as [H | H].\n      * simpl.\n        case_eq (Nat.eqb n x).\n        ** intros H1. trivial.\n        ** intros H1.\n           apply IHb1 in H.\n           rewrite H.\n           trivial.\n      * simpl.\n        case_eq (Nat.eqb n x).\n        ** intros H1. reflexivity.\n        ** intros H1.\n           apply IHb2 in H.\n           rewrite H.\n           simpl.\n           rewrite Bool.orb_true_r.\n           trivial.\nQed.\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/curs2_arbori.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8902942239389253, "lm_q1q2_score": 0.7884725964287197}}
{"text": "(**\n  This module defines the Group record type which can be used to\n  represent algebraic groups and provides a collection of theorems\n  and axioms 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 ProofIrrelevance.\nRequire Import Description.\nRequire Import base.\nRequire Import function.\nRequire Import monoid.\n\nModule Group.\n\n(** Represents algebraic groups. *)\nStructure Group : Type := group {\n\n  (** Represents the set of group elements. *)\n  E: Set;\n\n  (** Represents the identity element. *)\n  E_0: E;\n\n  (** Represents the group operation. *)\n  op: E -> E -> E;\n\n  (** Asserts that the group operator is associative. *)\n  op_is_assoc : Monoid.is_assoc E op;\n\n  (** Asserts that E_0 is the left identity element. *)\n  op_id_l : Monoid.is_id_l E op E_0;\n\n  (** Asserts that E_0 is the right identity element. *)\n  op_id_r : Monoid.is_id_r E op E_0;\n\n  (**\n    Asserts that every group element has a\n    left inverse.\n  *)\n  op_inv_l_ex : forall x : E, exists y : E, Monoid.is_inv_l E op E_0 (conj op_id_l op_id_r) x y;\n\n  (**\n    Asserts that every group element has a\n    right inverse.\n  *)\n  op_inv_r_ex : forall x : E, exists y : E, Monoid.is_inv_r E op E_0 (conj op_id_l op_id_r) x y\n}.\n\n(** Enable implicit arguments for group properties. *)\n\nArguments E_0 {g}.\n\nArguments op {g} x y.\n\nArguments op_is_assoc {g} x y z.\n\nArguments op_id_l {g} x.\n\nArguments op_id_r {g} x.\n\nArguments op_inv_l_ex {g} x.\n\nArguments op_inv_r_ex {g} x.\n\n(** Define notations for group properties. *)\n\nNotation \"0\" := E_0 : group_scope.\n\nNotation \"x + y\" := (op x y) (at level 50, left associativity) : group_scope.\n\nNotation \"{+}\" := op : group_scope.\n\nOpen Scope group_scope.\n\nSection Theorems.\n\n(**\n  Represents an arbitrary group.\n\n  Note: we use Variable rather than Parameter\n  to ensure that the following theorems are\n  generalized w.r.t g.\n*)\nVariable g : Group.\n\n(** Represents the set of group elements. *)\nLet E := E g.\n\n(**\n  Represents the monoid structure formed by\n  op over E.\n*)\nDefinition op_monoid := Monoid.monoid E 0 {+} op_is_assoc op_id_l op_id_r.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the left identity element.\n*)\nDefinition op_is_id_l := Monoid.op_is_id_l op_monoid.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the right identity element.\n*)\nDefinition op_is_id_r := Monoid.op_is_id_r op_monoid.\n\n(**\n  Accepts one group element, x, and asserts\n  that x is the identity element.\n*)\nDefinition op_is_id := Monoid.op_is_id op_monoid.\n\n(** Proves that 0 is the identity element. *)\nTheorem op_id\n  :  op_is_id 0.\nProof Monoid.op_id op_monoid.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's left inverse.\n*)\nDefinition op_is_inv_l := Monoid.op_is_inv_l op_monoid.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's right inverse.\n*)\nDefinition op_is_inv_r := Monoid.op_is_inv_r op_monoid.\n\n(** Proves that the left identity element is unique. *)\nTheorem op_id_l_uniq\n  :  forall x : E, (op_is_id_l x) -> x = 0.\nProof Monoid.op_id_l_uniq op_monoid.\n\n(** Proves that the right identity element is unique. *)\nTheorem op_id_r_uniq \n  :  forall x : E, (op_is_id_r x) -> x = 0.\nProof Monoid.op_id_r_uniq op_monoid.\n\n(** Proves that the identity element is unique. *)\nTheorem op_id_uniq\n  :  forall x : E, (op_is_id x) -> x = 0.\nProof Monoid.op_id_uniq op_monoid.\n\n(** Proves the left introduction rule. *)\nTheorem op_intro_l\n  :  forall x y z : E, x = y -> z + x = z + y.\nProof Monoid.op_intro_l op_monoid.\n\n(** Proves the right introduction rule. *)\nTheorem op_intro_r\n  :  forall x y z : E, x = y -> x + z = y + z.\nProof Monoid.op_intro_r op_monoid.\n\n(**\n  Accepts two group elements, x and y, and\n  asserts that y is x's inverse.\n*)\nDefinition op_is_inv := Monoid.op_is_inv op_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a left inverse.\n*)\nDefinition has_inv_l := Monoid.has_inv_l op_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a right inverse.\n*)\nDefinition has_inv_r := Monoid.has_inv_r op_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has an inverse.\n*)\nDefinition has_inv := Monoid.has_inv op_monoid.\n\n(**\n  Proves that for every group element, x,\n  its left and right inverses are equal.\n*)\nTheorem op_inv_l_r_eq\n  :  forall x y : E, op_is_inv_l x y -> forall z : E, op_is_inv_r x z -> y = z.\nProof Monoid.op_inv_l_r_eq op_monoid.\n\n(**\n  Proves that the inverse relation is\n  symmetrical.\n*)\nTheorem op_inv_sym\n  :  forall x y : E, op_is_inv x y <-> op_is_inv y x.\nProof Monoid.op_inv_sym op_monoid.\n\n(**\n  Proves that every group element has an\n  inverse.\n*)\nTheorem op_inv_ex\n  :  forall x : E, exists y : E, op_is_inv x y.\nProof\n  fun x : E\n    => ex_ind\n            (fun y H\n              => ex_ind\n                   (fun z H0\n                     => let H1\n                          :  op_is_inv_r x y\n                          :=  H0\n                          || op_is_inv_r x a @a\n                             by op_inv_l_r_eq x y H z H0 in\n                        ex_intro\n                          (fun a => op_is_inv x a)\n                          y\n                          (conj H H1))\n                   (op_inv_r_ex x))\n            (op_inv_l_ex x).\n\n(** Proves the left cancellation rule. *)\nTheorem op_cancel_l\n  :  forall x y z : E, z + x = z + y -> x = y.\nProof\n  fun x y z H \n    => Monoid.op_cancel_l op_monoid x y z (op_inv_l_ex z) H.\n\n(** Proves the right cancellation rule. *)\nTheorem op_cancel_r\n  :  forall x y z : E, x + z = y + z -> x = y.\nProof\n  fun x y z\n    => Monoid.op_cancel_r op_monoid x y z (op_inv_r_ex z).\n\n(**\n  Proves that an element's left inverse\n  is unique.\n*)\nTheorem op_inv_l_uniq\n  :  forall x y z : E, op_is_inv_l x y -> op_is_inv_l x z -> z = y.\nProof\n  fun x\n    => Monoid.op_inv_l_uniq op_monoid x (op_inv_r_ex x).\n\n(**\n  Proves that an element's right inverse\n  is unique.\n*)\nTheorem op_inv_r_uniq\n  :  forall x y z : E, op_is_inv_r x y -> op_is_inv_r x z -> z = y.\nProof\n  fun x\n    => Monoid.op_inv_r_uniq op_monoid x (op_inv_l_ex x).\n\n(** Proves that an element's inverse is unique. *)\nTheorem op_inv_uniq\n  :  forall x y z : E, op_is_inv x y -> op_is_inv x z -> z = y.\nProof Monoid.op_inv_uniq op_monoid.\n\n(**\n  Proves explicitly that every element has a\n  unique inverse.\n*)\nTheorem op_inv_uniq_ex\n  :  forall x : E, exists! y : E, op_is_inv x y.\nProof\n  fun x\n    => ex_ind\n            (fun y (H : op_is_inv x y)\n              => ex_intro \n                   (fun y => op_is_inv x y /\\ forall z, op_is_inv x z -> y = z)\n                   y\n                   (conj H (fun z H0 => eq_sym (op_inv_uniq x y z H H0))))\n            (op_inv_ex x).\n\n(**\n  Proves that the identity element is its own\n  left inverse.\n*)\nTheorem op_inv_0_l\n  :  op_is_inv_l 0 0.\nProof Monoid.op_inv_0_l op_monoid.\n\n(**\n  Proves that the identity element is its own\n  right inverse.\n*)\nTheorem op_inv_0_r\n  :  op_is_inv_r 0 0.\nProof Monoid.op_inv_0_r op_monoid.\n\n(**\n  Proves that the identity element is its own\n  inverse.\n*)\nTheorem op_inv_0\n  :  op_is_inv 0 0.\nProof Monoid.op_inv_0 op_monoid.\n\n(**\n  Proves that the identity element has a\n  left inverse.\n*)\nTheorem op_has_inv_l_0\n  :  has_inv_l 0.\nProof Monoid.op_has_inv_l_0 op_monoid.\n\n(**\n  Proves that the identity element has a\n  right inverse.\n*)\nTheorem op_has_inv_r_0\n  :  has_inv_r 0.\nProof Monoid.op_has_inv_r_0 op_monoid.\n\n(**\n  Proves that the identity element has an\n  inverse.\n*)\nTheorem op_has_inv_0\n  :  has_inv 0.\nProof Monoid.op_has_inv_0 op_monoid.\n\n(**\n  Proves that if an element's, x, inverse\n  equals 0, x equals 0.\n*)\nTheorem op_inv_0_eq_0\n  :  forall x : E, op_is_inv x 0 -> x = 0.\nProof Monoid.op_inv_0_eq_0 op_monoid.\n\n(**\n  Proves that 0 is the only element whose\n  inverse is 0.\n*)\nTheorem op_inv_0_uniq\n  :  unique (fun x => op_is_inv x 0) 0.\nProof Monoid.op_inv_0_uniq op_monoid.\n \n(** Represents strongly-specified negation. *)\nDefinition op_neg_strong\n  :  forall x : E, { y | op_is_inv x y }\n  := fun x => Monoid.op_neg_strong op_monoid x (op_inv_ex x).\n\n(** Represents negation. *)\nDefinition op_neg\n  :  E -> E\n  := fun x => Monoid.op_neg op_monoid x (op_inv_ex x).\n\nNotation \"{-}\" := (op_neg) : group_scope.\n\nNotation \"- x\" := (op_neg x) : group_scope.\n\n(** Asserts that the negation returns the inverse of its argument *)\nTheorem op_neg_def\n  :  forall x : E, op_is_inv x (- x).\nProof\n  fun x\n    => Monoid.op_neg_def op_monoid x (op_inv_ex x).\n\n(** Proves that negation is one-to-one *)\n(** 0 = 0\n   x + -x = 0\n   x + -x = y + -y\n   x + -x = y + -x\n        x = y\n*)\nTheorem op_neg_inj\n  :  is_injective E E op_neg.\nProof\n  fun x y\n    => Monoid.op_neg_inj op_monoid x (op_inv_ex x) y (op_inv_ex y).\n\n(** Proves the cancellation property for negation. *)\nTheorem op_cancel_neg\n  :  forall x : E, - (- x) = x.\nProof\n  fun x\n    => Monoid.op_cancel_neg_gen op_monoid x (op_inv_ex x) (op_inv_ex (- x)).\n\n(** Proves that negation is surjective - onto *)\nTheorem op_neg_onto\n  :  is_onto E E {-}.\nProof\n  fun x => ex_intro (fun y => - y = x) (- x) (op_cancel_neg x).\n\n(** Proves that negation is bijective. *)\nTheorem op_neg_bijective\n  :  is_bijective E E {-}.\nProof\n  conj op_neg_inj op_neg_onto.\n\n(** Proves that neg x = y -> neg y = x *)\nTheorem op_neg_rev\n  :  forall x y : E, - x = y -> - y = x.\nProof\n  fun x y H\n    => eq_sym\n            (f_equal {-} H\n             || a = - y @a by <- op_cancel_neg x).\n\n(**\n  Proves that the left inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv_l\n  :  forall x y : E, op_is_inv_l (x + y) (- y + - x).\nProof\n  fun x y\n    => ((proj2 (op_neg_def (- y)))\n            || - y + a = 0                 @a by <- op_cancel_neg y\n            || - y + a = 0                 @a by op_id_l y\n            || - y + (a + y) = 0           @a by proj2 (op_neg_def (- x))\n            || - y + ((- x + a) + y) = 0 @a by <- op_cancel_neg x\n            || - y + a = 0                 @a by op_is_assoc (- x) x y\n            || a = 0                         @a by <- op_is_assoc (- y) (- x) (x + y)).\n\n(**\n  Proves that the right inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv_r\n  :  forall x y : E, op_is_inv_r (x + y) (- y + - x).\nProof\n  fun x y\n    => ((proj2 (op_neg_def x))\n            || x + a = 0           @a by op_id_l (- x)\n            || x + (a + - x) = 0 @a by proj2 (op_neg_def y)\n            || x + a = 0           @a by op_is_assoc y (- y) (- x)\n            || a = 0               @a by <- op_is_assoc x y (- y + - x)).\n\n(**\n  Proves that the inverse of x + y is -y + -x.\n*)\nTheorem op_neg_distrib_inv\n  :  forall x y : E, op_is_inv (x + y) (- y + - x).\nProof\n  fun x y\n    => conj\n            (op_neg_distrib_inv_l x y)\n            (op_neg_distrib_inv_r x y).\n\n(**\n  Proves that negation is distributive: i.e.\n  -(x + y) = -y + -x.\n*)\nTheorem op_neg_distrib\n  :  forall x y : E, - (x + y) = - y + - x.\nProof\n  fun x y\n    => ex_ind\n            (fun z (H : unique (op_is_inv (x + y)) z)\n              => let H0\n                   :  z = - (x + y)\n                   := (proj2 H) \n                       (- (x + y))\n                       (op_neg_def (x + y)) in\n                 let H1\n                   :  z = (- y + - x)\n                   := (proj2 H)\n                        (- y + - x)\n                        (op_neg_distrib_inv x y) in\n                 (H1 || a = - y + - x @a by <- H0))\n            (op_inv_uniq_ex (x + y)).\n\nEnd Theorems.\n\nEnd Group.\n\nNotation \"0\" := (Group.E_0) : group_scope.\n\nNotation \"x + y\" := (Group.op x y) (at level 50, left associativity) : group_scope.\n\nNotation \"{+}\" := (Group.op) : group_scope.\n\nNotation \"{-}\" := (Group.op_neg _) : group_scope.\n\nNotation \"- x\" := (Group.op_neg _ x) : group_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/group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.7884725941118106}}
{"text": "From LF Require Export Lists.\n\n(*Cap: POLY\nPOLYMORPHISM AND HIGHER-ORDER FUNCTIONS*)\n\n(*********1.1: POLYMORPHISM*********)\n\n(******1.1.1: Polymorphic Lists******)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : 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 1 (nil nat)))\n      : 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_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. simpl. reflexivity. Qed.\n\n(*Exercise: 2 stars, standard (mumble_grumble)\nConsider the following two inductively defined types.*)\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(*Which of the following are well-typed elements of grumble X for some type X? \n(Add YES or NO to each line.)\nd (b a 5)\nd mumble (b a 5)\nd bool (b a 5)\ne bool true\ne mumble (b c 0)\ne bool (b c 0)\nc\n NO, YES, NO, YES, YES, NO*)\nEnd MumbleGrumble.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n\n(***1.1.1.1 Type Annotation Inference***)\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.\nCheck repeat'\n  : forall X : Type, X -> nat -> list X.\nCheck repeat\n  : forall X : Type, X -> nat -> list X.\n\n(***1.1.1.2 Type Argument Synthesis***)\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\n(***1.1.1.3 Implicit Arguments***)\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(*don't make like this*)\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\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.\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.\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. simpl. reflexivity. Qed.\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. simpl. reflexivity. Qed.\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. simpl. reflexivity. Qed.\n\n(***1.1.1.4 Supplying Type Arguments Explicitly***)\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\nCheck @nil : forall X : Type, list X.\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\n(*Exercise: 2 stars, standard, optional (poly_exercises)\nHere are a few simple exercises, just like ones in the Lists chapter,\nfor 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. intros l. induction l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. reflexivity. Qed.\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A. intros l m n. induction l as [| n' l'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. reflexivity. Qed.\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X. intros l1 l2. induction l1 as [| n l1'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1'. reflexivity. Qed.\n\n(*Exercise: 2 stars, standard, optional (more_poly_exercises)\nHere 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.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1. rewrite app_assoc. reflexivity. Qed.\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros. induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity. Qed.\n\n(******1.1.2 Polymorphic Pairs******)\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\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)\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(*Try answering the following questions on paper and checking your answers in Coq:\nWhat is the type of combine (i.e., what does Check @combine print?)\nWhat does\n        Compute (combine [1;2] [false;false;true;true]).\nprint?*)\nCheck @combine. (*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     : list (nat * bool)*)\n\n(*Exercise: 2 stars, standard, especially useful (split)\nThe function split is the right inverse of combine: it takes a list of pairs \nand returns a pair of lists. In many functional languages, it is called unzip.\nFill in the definition of split below. Make sure it passes the 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) :: rest => let (xs, ys) := split rest\n                       in  (x :: xs, y :: ys)\n  end.\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. simpl. reflexivity. Qed.\n\n(******1.1.3  Polymorphic Options******)\nModule OptionPlayground.\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X} _.\nArguments None {X}.\nEnd OptionPlayground.\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.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. simpl. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. simpl. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. simpl. reflexivity. Qed.\n\n(*Exercise: 1 star, standard, optional (hd_error_poly)\nComplete the definition of a polymorphic version of the hd_error \nfunction from the last chapter. Be sure that it 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 :: t => Some h\n  end.\n\n(*Once again, to force the implicit arguments to be explicit, \nwe can use @ before the name of the function.*)\n\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(*********1.2: Functions as Data*********)\n\n(******1.2.1: Higher-Order Functions******)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. simpl. reflexivity. Qed.\nExample test_doit3times': doit3times negb true = false.\nProof. simpl. reflexivity. Qed.\n\n(******1.2.2: Filter******)\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 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. simpl. reflexivity. Qed.\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. simpl. reflexivity. Qed.\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\nExample test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof. simpl. reflexivity. Qed.\n\n(******1.2.2: Anonymous Functions******)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. simpl. 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. simpl. reflexivity. Qed.\n\n(*Exercise: 2 stars, standard (filter_even_gt7)\nUse filter (instead of Fixpoint) to write a Coq function filter_even_gt7 \nthat takes a list of natural numbers as input and returns a list of just \nthose that are even and greater than 7.*)\nDefinition filter_even_gt7 (l : list nat) : list nat:=\n  filter (leb 7) (filter evenb l).\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: 3 stars, standard (partition)\nUse 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 \nreturn a pair of lists. The first member of the pair is the sublist of the \noriginal list containing the elements that satisfy the test, and the second \nis the sublist containing those that fail the test. The order of elements in \nthe two sublists should be the same as their order in the original list.*)\nFixpoint filter_not {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then filter_not test t\n                        else h :: (filter_not test t)\n  end.\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  pair (filter test l) (filter_not test l).\nCheck @partition. \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(******1.2.3: Maps******)\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\n(*Exercise: 3 stars, standard (map_rev)\nShow that map and rev commute. You may need to \ndefine an auxiliary lemma.*)\nLemma map_l_n : forall (X Y: Type) (f : X -> Y) (l : list X) (n : X),\n  map f l ++ [f n] = map f (l ++ [n]).\nProof.\n  intros X Y f l n. induction l as [| s l'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. reflexivity. 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.\n  intros X Y f l. induction l as [| s l'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- map_l_n. rewrite <- IHl'. reflexivity. Qed.\n\n(*Exercise: 2 stars, standard, especially useful (flat_map)\nThe function map maps a list X to a list Y using a function \nof type X → Y. We can define a similar function, flat_map, \nwhich maps a list X to a list Y using a function f of \ntype X → list Y. Your definition should work by 'flattening' \nthe 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\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.\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.\nExample test_flat_map2: flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\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\n(******1.2.4: Fold******)\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\nCheck (fold andb) : list bool -> bool -> bool.\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(******1.2.5: Functions That Construct Functions******)\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.\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nCheck plus : nat -> nat -> nat.\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\n(*********1.3: Additional Exercises*********)\nModule Exercises.\n\n(*Exercise: 2 stars, standard (fold_length)\nMany common functions on lists can be implemented in terms of fold. \nFor 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.\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n(*Prove the correctness of fold_length. \n(Hint: It may help to know that reflexivity simplifies \nexpressions a bit more aggressively than simpl does -- i.e.,\n you may find yourself in a situation where simpl does nothing \nbut reflexivity solves the goal.)*)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof. \n  intros X l. induction l as [|s l'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'. reflexivity. Qed.\n\n(*Exercise: 3 stars, standard (fold_map)\nWe can also define map in terms of fold. Finish fold_map below.*)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y:=\n  fold (fun x lx => [f x] ++ lx) l [].\n\nExample test_fold_map1: fold_map (fun x => plus3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n(*Write down a theorem fold_map_correct in Coq stating that fold_map\n is correct, and prove it. (Hint: again, remember that reflexivity\n simplifies expressions a bit more aggressively than simpl.)*)\n\n(*Exercise: 2 stars, advanced (currying)\nIn Coq, a function f : A → B → C really has the type A → (B → C). \nThat is, if you give f a value of type A, it will give you \nfunction f' : B → C. If you then give f' a value of type B, it will \nreturn a value of type C. This allows for partial application, as in \nplus3. Processing a list of arguments with functions that return functions \nis called currying, in honor of the logician Haskell Curry.\nConversely, we can reinterpret the type A → B → C as (A × B) → C. \nThis is called uncurrying. With an uncurried binary function, both \narguments must be given at once as a pair; there is no partial application.\nWe 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 the theorems \nbelow 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(*As a (trivial) example of the usefulness of currying, we can use it to shorten \none of the examples that we saw above:*)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n(*Thought exercise: before running the following commands, \ncan you calculate the types of prod_curry and prod_uncurry?*)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\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. reflexivity. Qed.\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. destruct p. reflexivity. Qed.\n\n(*Exercise: 2 stars, advanced (nth_error_informal)\nRecall the definition of the nth_error function:*)\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(*Write an informal proof of the following theorem:\n   forall X l n, length l = n -> @nth_error X l n = None\n(* FILL IN HERE *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat×string) := None.*)\n\n(*** Church numerals***)\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(*Complete the definitions of the following functions. Make sure that the \ncorresponding unit tests pass by proving them with reflexivity.*)\n(*************************\n(*Exercise: 1 star, advanced (church_succ)\nSuccessor of a natural number: given a Church numeral n, \nthe successor succ n is a function that iterates its argument once more than n.*)\nDefinition succ (n : cnat) : cnat:=\n  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\nExample succ_2 : succ one = two.\nProof. simpl. reflexivity. Qed.\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(*Exercise: 1 star, advanced (church_plus)\nAddition 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)).\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: 2 stars, advanced (church_mult)\nMultiplication:*)\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\n(*Exercise: 2 stars, advanced (church_exp)\nExponentiation:\n(Hint: Polymorphism plays a crucial role here. However, choosing the \nright type to iterate over can be tricky. If you hit a \"Universe inconsistency\" \nerror, try iterating over a different type. Iterating over cnat itself is \nusually problematic.)*)\n\nDefinition exp (n m : cnat) : cnat:=\n  fun (X : Type) (f : X -> X) (x : X) => (m (X -> X) (n X) f) 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": "maguro2", "repo": "estudo-orientado1", "sha": "06f937b35ea5ee589793b7c3200579635630f495", "save_path": "github-repos/coq/maguro2-estudo-orientado1", "path": "github-repos/coq/maguro2-estudo-orientado1/estudo-orientado1-06f937b35ea5ee589793b7c3200579635630f495/cap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.9111797148356994, "lm_q1q2_score": 0.7883746359981432}}
{"text": "\n  \n(* This file contains  DEFINITIONS of some basic notions related to Finite Partial Orders.\n     It also contains some elementary RESULTS on Chains, antichains and finite posets. Following \n     is a partial list of these definitions and results. \n\n\nDEFINITIONS: ---------------------------------------------------------------------------\n  1. Record FPO: Defines the notion of Finite Partial orders.\n  \n  2. Is_a_chain_in: Defines a chain as a predicate.\n\n  3. Is_an_antichain_in: Defines antichain as a predicate.\n\n  4. Is_the_largest_element_in: Defines the largest element  of a finite poset. \n            \n  5. Is_the_smallest_element_in: Defines the smallest element of a finite poset.                \n\n  6. Is_a_chain_cover: Defines a chain cover of finite posets.    \n\n  7. Is_an_antichain_cover: Defines an antichain cover of finite posets.\n\n  8. Is_a_disjoint_cover: Defines the notion of a disjoint chain cover.    \n\nRESULTS on finite posets: --------------------------------------------------------------\n\n0.Lemma NoTwoCommon: A chain and an antichain intersects at atmost one point.\n\n1.Lemma Antichain_exists: In every finite poset there is an antichain.\n\n2.Lemma Chain_exists: In every finite poset there is a chain.\n\n3.Lemma Minimal_element_exists: There exists a minimal element in every finite poset. \n        \n4.Lemma Maximal_element_exists: There exists a maximal element in every finite poset.  \n         \n5.Lemma Minimal_for_every_y: In a finite poset for every element y there exists x such that R x y\n\n6.Lemma Maximal_for_every_x: In a finite poset for every element x there exists y such that R x y\n\n7.Lemma Largest_element_exists: In a totally ordered finite poset there exists a largest element.\n\n8.Lemma Maximal_is_largest:In totally ordered finite posets Maximal element is largest element. \n\n9.Lemma Smallest_element_exists:In a totally ordered finite poset there exists a smallest element\n\n----------------------------------------------------------------------------------------    *)  \n\nRequire Export PigeonHole.\nRequire Export BasicFacts.\nRequire Export Partial_Order .\n\n\n\nSection Finite_Chain_Def.\n\n\n  Variable U:Type.\n  \n  Check PO U.\n  Print PO.\n  Print Finite.\n\n  Record FPO (U : Type) : Type := Definition_of_FPO\n  { PO_of :> PO U ;\n    \n    FPO_cond : Finite _ (Carrier_of _ PO_of  ) }.\n  \n  Variable P :FPO U.\n  Let C := @ Carrier_of U P.\n\n  Let R := @Rel_of U P.\n\n  Check FPO.\n  Check Carrier_of _ P.\n\n  Lemma Finite_PO: forall (P: FPO U), Finite _ (Carrier_of _ P).\n  Proof. intro. apply FPO_cond. Qed.\n\n  Set Implicit Arguments. \n  Definition Is_a_chain_in (e: Ensemble U): Prop:=\n    (Included U e C /\\ Inhabited U e)/\\\n                (forall x y:U, (Included U (Couple U x y) e)-> R x y \\/ R y x). \n    \n\n\n\n  Definition Is_an_antichain_in (e: Ensemble U): Prop := (Included U e C /\\ Inhabited U e)/\\\n                (forall x y:U, (Included U (Couple U x y) e)-> (R x y \\/ R y x)-> x=y). \n\n\n\n Inductive Is_largest_chain_in (e: Ensemble U): Prop:=\n   largest_chain_cond:  Is_a_chain_in e ->\n                        (forall (e1: Ensemble U) (n n1:nat),\n                        Is_a_chain_in e1 -> cardinal _ e n -> cardinal _ e1 n1 ->\n                        n1<= n) -> Is_largest_chain_in e.\n\n Inductive Is_largest_antichain_in (e: Ensemble U): Prop:=\n   largest_antichain_cond:  Is_an_antichain_in e ->\n                            (forall (e1: Ensemble U) (n n1: nat),\n                              Is_an_antichain_in e1 -> cardinal _ e n ->\n                              cardinal _ e1 n1 -> n1<=n ) ->\n                              Is_largest_antichain_in e.\n\n\n                                                             \n\n\n (* ---------------------- MINIMAL AND MAXIMAL ARE ANTICHAINS ------------------------ *)\n (* ---------------------------------------------------------------------------------- *)\n \n\nDefinition Is_a_maximal_element (x:U): Prop:= In _ C x /\\  ~(exists y:U, In _ C y /\\ x<>y /\\ R x y  ).\n \n\n\nDefinition Is_a_minimal_element (x: U): Prop:= In _ C x /\\ ~(exists y:U, In _ C y /\\ x<>y /\\ R y x ). \n\n\n\nDefinition Maximal_elements_of: Ensemble U:=\n    fun x:U => Is_a_maximal_element x.\n\n  \n\nDefinition Minimal_elements_of: Ensemble U:=\n    fun x:U => Is_a_minimal_element x.\n\n\nDefinition Is_the_largest_element_in (U:Type)(FP: FPO U)(y:U): Prop:= let C0:= Carrier_of _ FP in let R0:= Rel_of _ FP in ( In _ C0 y /\\ forall x:U, (In _ C0 x -> R0 x y) ).\n\nDefinition Is_the_smallest_element_in (U:Type)(FP: FPO U)(x:U): Prop:= let C0:= Carrier_of _ FP in let R0:= Rel_of _ FP in ( In _ C0 x /\\ forall y:U, (In _ C0 y -> R0 x y) ). \n\n\n\n  (* _________________________ CHAIN COVER AND ANTICHAIN COVER ___________________________  *)\n  \n\n  Inductive Is_a_chain_cover (cover: Ensemble (Ensemble U)): Prop:=\n    cover_cond: (forall (e: Ensemble U), In _ cover e -> Is_a_chain_in e)->\n                (forall x:U, In _ C x -> (exists e: Ensemble U, In _ cover e /\\ In _ e x)) ->\n                Is_a_chain_cover cover.\n\n  Inductive Is_an_antichain_cover (cover: Ensemble (Ensemble U)): Prop:=\n    AC_cover_cond: (forall (e: Ensemble U), In _ cover e -> Is_an_antichain_in e)->\n                (forall x:U, In _ C x -> (exists e: Ensemble U, In _ cover e /\\ In _ e x)) ->\n                Is_an_antichain_cover cover.\n\n\n\n                                                               \n  \n  Lemma NoTwoCommon : forall (X Y : Ensemble U) (x y :U),\n                        Is_a_chain_in X -> Is_an_antichain_in Y ->\n                        Included U (Couple U x y) X -> Included U (Couple U x y) Y ->\n                        x = y.\n\n  Proof. { intros X Y x y. intros chainX antichainY H1 H2.\n         assert (H:R x y \\/ R y x ). destruct chainX. apply H0.\n         assumption.\n         destruct antichainY. apply H3.\n         assumption. assumption. }  Qed.\n\n \n\n  Definition Is_a_disjoint_cover (cover : Ensemble ( Ensemble U)): Prop:=\n  Is_a_chain_cover  cover /\\ (forall e1 e2 : Ensemble U,\n                            (In _ cover e1 /\\ In _ cover e2)-> (e1=e2 \\/ Disjoint _ e1 e2 )).\n\n\n  Unset Implicit Arguments.\n\n                          \n\nEnd Finite_Chain_Def.\n\n\n\n\n Ltac apply_fpo_def := match goal with\n                        |_:_|- Is_largest_chain_in ?P ?e => (eapply largest_chain_cond)\n                        |_:_ |- Is_largest_antichain_in ?P ?e => (eapply largest_antichain_cond)\n                        |_:_ |- Is_a_chain_cover ?P ?cover => (eapply cover_cond)\n                        |_:_ |- Is_an_antichain_cover ?P ?cover => (eapply AC_cover_cond)\n                        end.\n \n\n\nSection Finite_Chain_Facts.\n\n  Variable U: Type.\n  Variable FP: FPO U.\n\n  Let C := @ Carrier_of U FP.\n\n  Let R := @Rel_of U FP.\n\n  Lemma Singleton_is_chain: forall x: U, In _ C x -> Is_a_chain_in FP (Singleton _ x).\n  Proof. { intros. unfold Is_a_chain_in. split. \n              { split. unfold Included. intros. destruct H0. apply H.\n                apply Inhabited_intro with (x:=x). auto with sets. }\n              { intros. unfold Included in H0.\n                assert (In U (Singleton U x) x0).\n                { apply H0. auto with sets. }\n                assert (In U (Singleton U x) y).\n                { apply H0. auto with sets. }\n                destruct H1; destruct H2. left. apply PO_cond2.  }   }  Qed.\n\n  Lemma Singleton_is_antichain: forall x: U, In _ C x -> Is_an_antichain_in FP (Singleton _ x).\n    Proof. { intros.  unfold Is_an_antichain_in. split. \n              { split. unfold Included. intros. destruct H0. apply H.\n                apply Inhabited_intro with (x:=x). auto with sets. }\n              { intros. unfold Included in H0.\n                assert (In U (Singleton U x) x0).\n                { apply H0. auto with sets. }\n                assert (In U (Singleton U x) y).\n                { apply H0. auto with sets. }\n                destruct H2; destruct H3. reflexivity.  }  } Qed.\n\nLemma Antichain_exists:  exists e: Ensemble U, Is_an_antichain_in FP e.\n    Proof.  { assert (T: Inhabited _ C). Print PO. apply PO_cond1.  destruct T.\n              exists (Singleton _ x). apply Singleton_is_antichain. auto. }  Qed.\n    \nLemma Chain_exists:  exists e: Ensemble U, Is_a_chain_in FP e.\nProof.  { assert (T: Inhabited _ C). Print PO. apply PO_cond1.  destruct T.\n              exists (Singleton _ x). apply Singleton_is_chain. auto.  }  Qed.\n\nLemma Chain_cover_exists: exists cover: Ensemble (Ensemble U), Is_a_chain_cover FP cover.\nProof. { pose (cover (e: Ensemble U):= exists x: U, In _ C x /\\ e = Singleton _ x).\n         exists cover.\n         Print Is_a_chain_cover. apply cover_cond.\n         { intros. unfold In in H. unfold cover in H. destruct H. destruct H.\n           rewrite H0. apply Singleton_is_chain.  auto. }\n         { intros. exists (Singleton _ x).  split. unfold In. unfold cover. exists x. tauto.\n           auto with sets.  }  }  Qed.\n\nLemma Antichain_cover_exists: exists cover: Ensemble (Ensemble U), Is_an_antichain_cover FP cover.\nProof. { pose (cover (e: Ensemble U):= exists x: U, In _ C x /\\ e = Singleton _ x).\n         exists cover.\n         Print Is_an_antichain_cover. apply AC_cover_cond.\n         { intros. unfold In in H. unfold cover in H. destruct H. destruct H.\n           rewrite H0. apply Singleton_is_antichain.  auto. }\n         { intros. exists (Singleton _ x).  split. unfold In. unfold cover. exists x. tauto.\n           auto with sets.  }   }  Qed. \n\nLemma Minimal_element_exists: forall (P: FPO U), exists x: U, Is_a_minimal_element P x.\nProof. { intros P'.\n       pose (C':= Carrier_of _ P').\n       pose ( R':= Rel_of _ P' ).\n       assert (H: exists n: nat, cardinal _ C' n).\n       { apply finite_cardinal. Print FPO. eapply FPO_cond. }\n\n       destruct H as [n' H]. generalize H. unfold C'.  generalize P' as P0.\n       generalize n' as n0. clear H. clear P' C' R' n'. intro n0. \n       induction n0.\n       (* Base Case: n=0 then P0 cannot be  a Poset *)\n       { intros. apply cardinal_elim  with (p:= 0) in H.\n         assert (H1: Inhabited _ (Carrier_of U P0)). (* since PO_cond1 says so *)\n         Print PO. apply PO_cond1. rewrite H in H1.\n         inversion H1. inversion H0.  } \n\n       (* Induction Step: When P0 is inhabited. *) \n       intros. \n       assert (H0: exists x: U, In _ (Carrier_of U P0) x).\n       { Print PO. destruct (PO_cond1 _ P0). exists x. tauto.  }\n       destruct H0 as [a H0].\n\n       pose (C':= Subtract _ (Carrier_of _ P0) a).\n       pose (R0:= Rel_of _ P0).\n\n       assert (T: Carrier_of _ P0 = Add _ C' a).\n       { apply Extensionality_Ensembles. unfold C'. auto with sets.  } \n\n       elim (EM (Inhabited _ C')).\n\n       (* CASE1: When C' is non-empty then P' will be the Poset with carrier C' *)\n       { intros. Print FPO.\n         assert (PS_Finite: Finite _ C').\n         { cut (Finite _ (Carrier_of _ P0)).\n           intro. eapply Finite_downward_closed.  exact H2. rewrite T.\n           auto with sets. apply (FPO_cond _ P0). }\n\n         Print PO.\n         pose (P_small:= {| Carrier_of:= C';\n                            Rel_of:= Rel_of _ P0;\n                            PO_cond1:= H1;\n                            PO_cond2:= PO_cond2 _ P0 |}).\n         Print FPO.\n         pose (S_P0:= {| PO_of:= P_small ; FPO_cond:= PS_Finite |}).\n\n         assert (T0: ~ In _ C' a).\n         { unfold C'. intro. inversion H2. apply H4.  auto with sets.  }\n\n         assert (H2: cardinal _ C' n0).\n         { rewrite T in H.\n           assert (n0 = pred (S n0)).\n           { auto with arith. } rewrite H2. eapply card_soustr_1.  rewrite T. tauto.  tauto.  } \n\n         assert (H3: exists x : U, Is_a_minimal_element S_P0 x). (* Using IHn0 *)\n         { eapply IHn0. auto.  } destruct H3 as [b H3].\n\n         (* At this point a is an element in P0 and b is in S_P0 *)\n         (* Moreover b is a minimal element of S_P0 *)\n         (* Either R a b is true or false ; in each case we produce a witness *)\n         elim (EM ( R0 a b)).\n         (* CASE A: when R0 a b *)\n         { (* In this case a is the minimal_element. We prove it by contradiction. \n              We assume that a ia not the minimal then there must exists some a0, which\n              is smaller than a. by transitivity it must also be smaller than b. Hence\n              b canot be the minimal of C' which contradicts H3.  *)\n           intro. exists a.  unfold Is_a_minimal_element.\n           split.\n           { tauto. }\n           { intro. (* assuming there is a a0 smaller than a we produce a contradiction *)\n            destruct H5 as [a0 H5].\n            assert (H6: R0 a0 b). (* Using the transitivity of R0 *)\n            { Print Order. cut (Transitive _ R0). intro. eapply H6 with (y:=a); tauto.  \n              apply PO_cond2. }\n\n            assert (H7: a <> b). (* since b is in C' and a is outside it *)\n            { intro. absurd ( In _ C' a). auto. rewrite H7. apply H3. }\n\n            assert (H8: a0 <> b). \n            (* otherwise R0 a b and R b a will become true for diffrent a and b *)\n            (* this violets the antysymmetricity of R0 *)\n            { intro. absurd ( R0 b a). cut (Antisymmetric _ R0).\n              intro. intro. apply H7. apply H9; tauto. apply PO_cond2.\n              rewrite <- H8. tauto.  } \n\n            assert (H9: In _ C' a0). (* since it is in P0 but not equal to a *)\n            { unfold C'. unfold Subtract. unfold Setminus.  unfold In.\n              split. tauto. intro. destruct H9.\n              absurd (a = a). tauto. reflexivity.  }\n\n            assert (H10: ~ Is_a_minimal_element S_P0 b).\n            { intro.  unfold Is_a_minimal_element in H10.\n              destruct H10 as [H10 H11]. apply H11.\n              exists a0. split. tauto. split. intro. apply H8. symmetry. auto.\n              simpl. auto. }\n\n            contradiction. }   } \n\n         (* CASE B: When ~ R0 a b *)\n         {  intro.  exists b.\n            unfold Is_a_minimal_element.\n            rewrite T.\n            split.\n            { unfold Add.  apply Union_introl. destruct H3. simpl in H3. auto. }\n            { intro.  destruct H3. apply H6.\n              destruct H5 as [b0 H5].\n              assert ( H7: b0<>a).\n              { intro. absurd (R0 a b). auto.  rewrite <- H7.   tauto.  }\n              assert (H8: In _ C' b0).\n              { unfold C'. unfold Subtract. unfold In. unfold Setminus.\n                split. rewrite T. tauto. intro. destruct H8. tauto. }\n\n              exists b0.  simpl. tauto.  }      }  }  \n       \n\n       (* CASE2: When C' is empty then a is the minimal element. *)\n       { intros. exists a. unfold Is_a_minimal_element.  split. auto.\n         intro. apply H1. destruct H2 as [b H2]. Print Inhabited.\n         apply Inhabited_intro with (x:=b). unfold C'. unfold Subtract. unfold Setminus.\n         unfold In.  split. tauto. intro.\n         destruct H3. destruct H2 as [H2 H3]. destruct H3 as [H3 H4].\n         apply H3. reflexivity.  }   }   Qed.  \n\nLemma Maximal_element_exists:  forall (P: FPO U), exists x: U, Is_a_maximal_element P x.\nProof. { intro P. Print PO.\n         pose ( C':= Carrier_of _ P).\n         pose ( R'(x:U)(y:U):= (Rel_of _ P) y x ).\n         assert (T: Order _ R' ).\n         { assert (T1: Order _ (Rel_of _ P)).\n           { apply PO_cond2. } Print Order. destruct T1. \n           apply Definition_of_order.\n           { unfold R'. apply H. }\n           { unfold R'. unfold Transitive.  Print Transitive.\n             intros. eapply H0. exact H3. auto. }\n           { unfold R'. unfold Antisymmetric. intros. apply H1; tauto. }\n         } \n\n         pose (PO_P':= {| Carrier_of:= C' ;\n                          Rel_of:= R' ;\n                          PO_cond1:= (PO_cond1 _ P);\n                          PO_cond2:= T |}).\n\n         pose (P':= {| PO_of:= PO_P' ; FPO_cond:= (FPO_cond _ P) |}).\n         \n         assert (T1: forall x: U, Is_a_minimal_element P' x -> Is_a_maximal_element P x ).\n         { intros. unfold Is_a_maximal_element.\n           split. apply H. destruct H as [H H1].\n           intro H2. apply H1. destruct H2 as [y H2].\n           exists y. simpl. unfold C'. unfold R'. tauto.  } \n\n         assert (H: exists x: U, Is_a_minimal_element P' x).\n         { apply Minimal_element_exists.  } destruct H as [x H].\n\n         exists x. auto.   }    Qed.   \n\nLemma Minimal_is_antichain: Is_an_antichain_in FP  (Minimal_elements_of FP).\nProof. { unfold Is_an_antichain_in. split.\n         (* Minimal_elements_of is Included in C and is also Inhabited *)\n         { split.\n           { unfold Included.  intros. unfold Minimal_elements_of in H. unfold In in H.\n             destruct H. auto. }\n           { unfold Minimal_elements_of.\n             assert ( H: exists x: U, Is_a_minimal_element FP x ).\n             { eapply Minimal_element_exists. }\n             destruct H as [x H].  eapply Inhabited_intro with (x:=x).\n             unfold In. auto. } } \n\n         (* No two elements are related in Minimal_elements_of. *)\n         { intros.\n           assert (H1: Is_a_minimal_element FP x).\n           { unfold Included in H. unfold In in H at 2. unfold Minimal_elements_of in H.\n             apply H.  auto with sets.  }\n           assert (H2: Is_a_minimal_element FP y).\n           { unfold Included in H. unfold In in H at 2. unfold Minimal_elements_of in H.\n             apply H.  auto with sets.  }\n\n           \n           unfold Is_a_minimal_element in H1. unfold Is_a_minimal_element in H2.\n           elim (EM ( x=y )). tauto. intro.\n           elim H0.\n           { intro.\n           absurd (exists y0 : U, In U C y0 /\\ y <> y0 /\\ R y0 y).\n           tauto. exists x. split. tauto. split. intro. apply H3. symmetry. auto. auto. }\n           { intro.\n           absurd (exists y : U, In U C y /\\ x <> y /\\ R y x).\n           tauto. exists y. split. tauto. split. intro. apply H3. symmetry. auto. auto. }  }    }   Qed.\n\nLemma Maximal_is_antichain: Is_an_antichain_in FP (Maximal_elements_of FP).\nProof. { unfold Is_an_antichain_in. split.\n         (* Maximal_elements_of is Included in C and is also Inhabited *)\n         { split.\n           { unfold Included.  intros. unfold Maximal_elements_of in H. unfold In in H.\n             destruct H. auto. }\n           { unfold Maximal_elements_of.\n             assert ( H: exists x: U, Is_a_maximal_element FP x ).\n             { eapply Maximal_element_exists.  }\n             destruct H as [x H].  eapply Inhabited_intro with (x:=x).\n             unfold In. auto. } } \n\n         (* No two elements are related in Maximal_elements_of. *)\n         { intros.\n           assert (H1: Is_a_maximal_element FP x).\n           { unfold Included in H. unfold In in H at 2. unfold Maximal_elements_of in H.\n             apply H.  auto with sets.  }\n           assert (H2: Is_a_maximal_element FP y).\n           { unfold Included in H. unfold In in H at 2. unfold Maximal_elements_of in H.\n             apply H.  auto with sets.  }\n\n           \n           unfold Is_a_maximal_element in H1. unfold Is_a_maximal_element in H2.\n           elim (EM ( x=y )). tauto. intro.\n           elim H0. Focus 2. \n           intro.\n           absurd (exists y0 : U, In U C y0 /\\ y <> y0 /\\ R y y0).\n           tauto. exists x. split. tauto. split. intro. apply H3. symmetry. auto. auto. \n           intro.\n           absurd (exists y : U, In U C y /\\ x <> y /\\ R  x y).\n           tauto. exists y. split. tauto. split. intro. apply H3. symmetry. auto. auto.   }    }  Qed.\n\nLemma Minimal_for_every_y: forall y: U, (In _ C y) -> (exists x:U, Is_a_minimal_element FP x /\\ R x y ).\nProof. { intros.\n         (* We consider the set of all elements Cy which are less than y and in C *)\n         (* We show that it form a partial oredr with R as relation *)\n         (* Therefore there must exists a minimal_element m in this set Cy *)\n         (* This element is less than y i.e R m y and we show that this is also a \n            minimal element in C *)\n         pose (Cy (x:U):= In _ C x /\\ R x y).\n\n         assert (T: Order _ R).\n         {apply PO_cond2. }\n         destruct T as [T1 T2 T3].\n\n         assert (T4: In _ Cy y).\n         {unfold In.  unfold Cy. split. auto. apply T1.  }\n\n         assert (H0: Included _ Cy C).\n         { unfold Included. intros. apply H0.  }\n\n         assert (H1: Inhabited _ Cy).\n         { Print Inhabited. apply Inhabited_intro with (x:=y). tauto. }\n\n         assert (H2: Finite _ Cy).\n         { eapply Finite_downward_closed with (A:=C). apply FPO_cond. auto. }\n         \n          pose (P_y:= {| Carrier_of:= Cy;\n                            Rel_of:= R;\n                            PO_cond1:= H1;\n                            PO_cond2:= PO_cond2 _ FP |}).\n         pose (FP_y:= {| PO_of:= P_y; FPO_cond:= H2 |}).\n\n         assert (H3:  exists x: U, Is_a_minimal_element FP_y x).\n         apply Minimal_element_exists. destruct H3 as [m H3].\n\n         assert (T5: R m y).\n         { unfold Is_a_minimal_element in H3. simpl in H3.  apply H3. }\n\n         exists m.\n         split.\n         { unfold Is_a_minimal_element. unfold C in H0.\n           split.\n           { apply H0. apply H3. }\n           { intro. destruct H4 as [m0 H4].\n             assert (H5: R m0 y).\n             { eapply T2 with (y:=m); tauto.  }\n             assert (H6: In _ Cy m0).\n             { unfold In. unfold Cy. tauto. }\n             assert (H7: ~ R  m0 m). (* since m is the minimal in Cy and m0 is also in  Cy *)\n             { intro. unfold Is_a_minimal_element in H3. destruct H3 as [H3 HT].\n               apply HT. exists m0. tauto.  }\n             absurd ( R m0 m );tauto.  }  }\n         { tauto. } \n\n         \n       } Qed. \n\nLemma Maximal_for_every_x: forall x:U, (In _ C x) -> (exists y: U, Is_a_maximal_element FP y /\\ R x y ).\nProof.  { intros.\n         (* We consider the set of all elements Cx which are greater than x and in C *)\n         (* We show that it form a partial oredr with R as relation *)\n         (* Therefore there must exists a maximal_element m in this set Cx *)\n         (* This element is bigger than x i.e R x m  and we show that this is also a \n            maximal element in C *)\n         pose (Cx (y:U):= In _ C y /\\ R x y).\n\n         assert (T: Order _ R).\n         {apply PO_cond2. }\n         destruct T as [T1 T2 T3].\n\n         assert (T4: In _ Cx x).\n         {unfold In.  unfold Cx. split. auto. apply T1.  }\n\n         assert (H0: Included _ Cx C).\n         { unfold Included. intros.  apply H0.  }\n\n         assert (H1: Inhabited _ Cx).\n         { Print Inhabited. apply Inhabited_intro with (x:=x). tauto. }\n\n         assert (H2: Finite _ Cx).\n         { eapply Finite_downward_closed with (A:=C). apply FPO_cond. auto. }\n         \n          pose (P_x:= {| Carrier_of:= Cx;\n                            Rel_of:= R;\n                            PO_cond1:= H1;\n                            PO_cond2:= PO_cond2 _ FP |}).\n         pose (FP_x:= {| PO_of:= P_x; FPO_cond:= H2 |}).\n\n         assert (H3:  exists x: U, Is_a_maximal_element FP_x x).\n         apply Maximal_element_exists. destruct H3 as [m H3].\n\n         assert (T5: R x m ).\n         { unfold Is_a_maximal_element in H3. simpl in H3.  apply H3. }\n\n         exists m.\n         split.\n         { unfold Is_a_maximal_element. unfold C in H0.\n           split.\n           { apply H0. apply H3. }\n           { intro. destruct H4 as [m0 H4].\n             assert (H5: R x m0 ).\n             { eapply T2 with (y:=m); tauto.  }\n             assert (H6: In _ Cx m0).\n             { unfold In. unfold Cx. tauto. }\n             assert (H7: ~ R m m0). (* since m is the maximal in Cx and m0 is also in  Cx *)\n             { intro. unfold Is_a_maximal_element in H3. destruct H3 as [H3 HT].\n               apply HT. exists m0. tauto.  }\n             absurd ( R  m m0 );tauto.  }  }\n         { tauto. } \n\n         \n       } Qed. \n\n\n\n     \n Lemma Every_minimal_has_a_maximal:\n    forall x:U, (In _ (Minimal_elements_of FP)  x)->\n                (exists y:U, In _  (Maximal_elements_of FP)  y /\\ R x y).\n Proof. { intros.\n          assert (H1: In _ C x).\n          { apply H. }\n          assert (H2: exists y: U, Is_a_maximal_element FP y /\\ R x y ).\n          { apply Maximal_for_every_x. auto. }\n\n          destruct H2 as [y H2].\n          exists y. unfold Maximal_elements_of. unfold In. tauto.  } Qed. \n  \n  Lemma Every_maximal_has_a_minimal:\n      forall y:U, (In _ (Maximal_elements_of FP) y)->\n                  (exists x:U, In _ (Minimal_elements_of FP) x /\\ R x y).\n  Proof.  { intros.\n          assert (H1: In _ C y).\n          { apply H. }\n          assert (H2: exists x: U, Is_a_minimal_element FP x /\\ R x y ).\n          { apply Minimal_for_every_y. auto. }\n\n          destruct H2 as [x H2].\n          exists x. unfold Minimal_elements_of. unfold In. tauto.  } Qed.  \n\n  Lemma Exists_pair_xy:\n    exists (x y:U), (In _ (Minimal_elements_of FP) x)/\\ (In _ (Maximal_elements_of FP) y)/\\ R x y.\n  Proof. { assert(H: exists x:U, In _ (Minimal_elements_of FP) x ). elim Minimal_is_antichain.\n         intros. destruct H as [H H1]. destruct H1.  exists x.\n         assumption. destruct H as [x0 H].\n         exists x0. elim Every_minimal_has_a_maximal with (x:=x0). intros y0 H1.\n         exists y0. split. assumption. assumption. assumption. }\n  Qed. \n\n\n\n  Lemma Largest_card_same: forall (e1 e2: Ensemble U)(n:nat),\n                              Is_largest_antichain_in FP e1 -> Is_largest_antichain_in FP e2 ->\n                              (cardinal _ e1 n) -> cardinal _ e2 n.\n  Proof. { intros.\n           assert (exists m:nat, cardinal _ e2 m).\n           { apply finite_cardinal. destruct H0. destruct H0.\n             apply Finite_downward_closed with (A:= C). apply FPO_cond.\n             tauto. } destruct H2 as [m H2].\n\n           assert (H3: m<=n).\n           {  Print Is_largest_antichain_in. destruct H.  eapply H3 with (e2:= e2).\n              apply H0. auto. auto.  }\n\n           assert (H4: n<=m).\n           { destruct H0. eapply H4 with (e1:= e1). apply H. auto. auto. }\n\n           assert (H5: m=n).\n           { auto with arith.  }\n\n           rewrite <- H5. auto. } Qed. \n\n  \n  Lemma Card_same_largest: forall (e1 e2: Ensemble U)(n: nat),\n                             Is_largest_antichain_in FP e1 -> Is_an_antichain_in FP e2 ->\n                             (cardinal _ e1 n)-> (cardinal _ e2 n)->\n                             Is_largest_antichain_in FP e2.\n  Proof. { intros.  Print Is_largest_antichain_in.\n           apply largest_antichain_cond.\n           auto.\n           { intros.\n             assert (H6: n0=n).\n             { eapply cardinal_unicity. exact H4.  auto. }\n             rewrite H6.\n             destruct H. eapply H7. exact H3. auto. auto.  }   }  Qed.\n\n\n\nLemma Largest_element_exists: Totally_ordered _ FP C ->  exists x: U, Is_the_largest_element_in FP x.\nProof. { intros. destruct H. elim Maximal_element_exists with (P:= FP).\n       intro max. intro. exists max.\n       assert (Order _ R).\n       { apply PO_cond2. }\n       destruct H1. \n       unfold Is_the_largest_element_in. unfold Is_a_maximal_element in H0.\n       split. tauto. intros.\n       elim (classic (max = x)).\n       { intro. rewrite H5.  apply H1. }\n       { intro.\n         assert (Rel_of U FP x max \\/ Rel_of U FP max x).\n         { apply H. unfold C. auto with sets. unfold Included. intros. destruct H6.\n           apply H4. apply H0. }\n         elim H6. tauto.\n         intro. absurd (exists y : U, In U (Carrier_of U FP) y /\\ max <> y /\\ Rel_of U FP max y).\n         apply H0.\n         exists x. tauto.   }  } Qed.\n\nLemma Maximal_is_largest: Totally_ordered _ FP C -> (forall x: U, Is_a_maximal_element FP x ->\n                                                            Is_the_largest_element_in FP x).\n  Proof.  { intro. intro max. intro. \n       assert (Order _ R).\n       { apply PO_cond2. }\n       destruct H1. \n       unfold Is_the_largest_element_in. unfold Is_a_maximal_element in H0.\n       split. tauto. intros.\n       elim (classic (max = x)).\n       { intro. rewrite H5.  apply H1. }\n       { intro.\n         assert (Rel_of U FP x max \\/ Rel_of U FP max x).\n         { apply H. unfold C. auto with sets. unfold Included. intros. destruct H6.\n           apply H4. apply H0. }\n         elim H6. tauto.\n         intro. absurd (exists y : U, In U (Carrier_of U FP) y /\\ max <> y /\\ Rel_of U FP max y).\n         apply H0.\n         exists x. tauto.   }  } Qed.\n\nLemma Minimal_is_smallest:  Totally_ordered _ FP C -> (forall x: U, Is_a_minimal_element FP x ->\n                                                              Is_the_smallest_element_in FP x).\n  Proof.  { intro. intro min. intro. \n       assert (Order _ R).\n       { apply PO_cond2. }\n       destruct H1. \n       unfold Is_the_smallest_element_in. unfold Is_a_minimal_element in H0.\n       split. tauto. intro x.  intros.\n       elim (classic (min = x)).\n       { intro. rewrite H5.  apply H1. }\n       { intro.\n         assert (Rel_of U FP x min \\/ Rel_of U FP min x).\n         { apply H. unfold C. auto with sets. unfold Included. intros. destruct H6.\n           apply H4. apply H0. }\n         elim H6. \n         intro. absurd (exists y : U, In U (Carrier_of U FP) y /\\ min <> y /\\ Rel_of U FP y min).\n         apply H0.\n         exists x. tauto.  tauto. }  } Qed.\n\nLemma Smallest_element_exists: Totally_ordered _ FP C -> exists x: U, Is_the_smallest_element_in FP x.\nProof.   { intros. destruct H. elim Minimal_element_exists with (P:= FP).\n       intro min. intro. exists min.\n       assert (Order _ R).\n       { apply PO_cond2. }\n       destruct H1. \n       unfold Is_the_smallest_element_in. unfold Is_a_minimal_element in H0.\n       split. tauto. intro x.  intros.\n       elim (classic (min = x)).\n       { intro. rewrite H5.  apply H1. }\n       { intro.\n         assert (Rel_of U FP x min \\/ Rel_of U FP min x).\n         { apply H. unfold C. auto with sets. unfold Included. intros. destruct H6.\n           apply H4. apply H0. }\n         elim H6. \n         intro. absurd (exists y : U, In U (Carrier_of U FP) y /\\ min <> y /\\ Rel_of U FP y min).\n         apply H0.\n         exists x. tauto.  tauto. }  } Qed.      \n\n\nEnd Finite_Chain_Facts.\n\n                                                                                      \n\nHint Resolve NoTwoCommon Singleton_is_chain Singleton_is_antichain :fpo_facts.\nHint Resolve Antichain_exists Chain_exists Chain_cover_exists Antichain_cover_exists: fpo_facts.\nHint Resolve Minimal_element_exists Maximal_element_exists: fpo_facts.\nHint Resolve Minimal_is_antichain Maximal_is_antichain: fpo_facts.\nHint Resolve Minimal_for_every_y Maximal_for_every_x: fpo_facts.\nHint Resolve Largest_card_same Card_same_largest Largest_element_exists: fpo_facts.\nHint Resolve Maximal_is_largest Minimal_is_smallest Smallest_element_exists: fpo_facts.", "meta": {"author": "Abhishek-TIFR", "repo": "Dilworth-Hall-Erdos-Theorems", "sha": "74c0cde97967149b7f44b775fabdc7d909760ebd", "save_path": "github-repos/coq/Abhishek-TIFR-Dilworth-Hall-Erdos-Theorems", "path": "github-repos/coq/Abhishek-TIFR-Dilworth-Hall-Erdos-Theorems/Dilworth-Hall-Erdos-Theorems-74c0cde97967149b7f44b775fabdc7d909760ebd/FPO_Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.7883483371959799}}
{"text": "(** * Sort: Insertion sort *)\n\n(** Sorting can be done in 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.  And it's certainly easier\n    to implement -- and to prove correct. *)\n\n(* ################################################################# *)\n(** * Recommended reading *)\n\n(** If you don't already know how insertion sort works, see Wikipedia\n    or read any standard textbook; for example:\n\n   Sections 2.0 and 2.1 of _Algorithms, Fourth Edition_,\n       by Sedgewick and Wayne, Addison Wesley 2011;  or\n\n   Section 2.1 of _Introduction to Algorithms, 3rd Edition_,\n       by Cormen, Leiserson, and Rivest, MIT Press 2009. *)\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\nRequire Import Perm. \n\nFixpoint insert (i:nat) (l: list nat) := \n  match l with\n  | nil => i::nil\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  | 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]\n                    = [1;1;2;3;3;4;5;5;5;6;9].\nProof. simpl. reflexivity. Qed.\n\n(** What Sedgewick/Wayne and Cormen/Leiserson/Rivest don't acknowlege\n    is that the arrays-and-swaps model of sorting is not the only one\n    in the world.  We are writing _functional programs_, where our\n    sequences are (typically) represented as linked lists, and where\n    we do _not_ destructively splice elements into those lists.\n    Instead, we build new lists that (sometimes) share structure with\n    the old ones.\n\n    So, for example: *)\n\nEval compute in insert 7 [1; 3; 4; 8; 12; 14; 18].\n(* = [1; 3; 4; 7; 8; 12; 14; 18] *)\n\n(** The tail of this list, [12::14::18::nil], is not disturbed or\n   rebuilt by the [insert] algorithm.  The nodes [1::3::4::7::_] are\n   new, constructed by [insert].  The first three nodes of the old\n   list, [1::3::4::_] will likely be garbage-collected, if no other\n   data structure is still pointing at them.  Thus, in this typical\n   case,\n     - Time cost = 4X\n     - Space cost = (4-3)Y = Y\n\n   where X and Y are constants, independent of the length of the tail.\n   The value Y is the number of bytes in one list node: 2 to 4 words,\n   depending on how the implementation handles constructor-tags.\n   We write (4-3) to indicate that four list nodes are constructed,\n   while three list nodes become eligible for garbage collection.  \n\n   We will not _prove_ such things about the time and space cost, but\n   they are _true_ anyway, and we should keep them in\n   consideration. *)\n\n(* ################################################################# *)\n(** * Specification of correctness *)\n\n(** A sorting algorithm must rearrange the elements into a list that\n    is totally ordered. *)\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(** Is this really the right definition of what it means for a list to\n    be sorted?  One might have thought that it should go more like this: *)\n\nDefinition sorted' (al: list nat) :=\n forall i j, i < j < length al -> nth i al 0 <= nth j al 0.\n\n(** This is a reasonable definition too.  It should be equivalent.\n    Later on, we'll prove that the two definitions really are\n    equivalent.  For now, let's use the first one to define what it\n    means to be a correct sorting algorthm. *)\n    \nDefinition is_a_sorting_algorithm (f: list nat -> list nat) :=\n  forall al, Permutation al (f al) /\\ sorted (f al).\n\n(** The result [(f al)] should not only be a [sorted] sequence,\n    but it should be some rearrangement (Permutation) of the input sequence. *)\n(* ################################################################# *)\n(** * Proof of correctness *)\n\n(** **** Exercise: 3 stars  *)\n(** Prove the following auxiliary lemma, [insert_perm], which will be\n    useful for proving [sort_perm] below.  Your proof will be by\n    induction, but you'll need some of the permutation facts from the\n    library, so first remind yourself by doing [SearchAbout]. *)\n  \nSearchAbout Permutation.\n\nLemma insert_perm: forall x l, Permutation (x::l) (insert x l).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars  *)\n(** Now prove that sort is a permutation. *)\n\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars  *)\n(** This one is a bit tricky.  However, there just a single induction\n   right at the beginning, and you do _not_ need to use [insert_perm]\n   or [sort_perm]. *)\n\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars  *)\n(** This one is easy.   *)\n\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n(* FILL IN HERE *) Admitted.\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_perm. apply sort_sorted.\nQed.\n\n(* ################################################################# *)\n(** * Making sure the specification is right *)\n\n(** It's really important to get the _specification_ right.  You can\n    prove that your program satisfies its specification (and Coq will\n    check that proof for you), but you can't prove that you have the\n    right specification.  Therefore, we take the trouble to write two\n    different specifications of sortedness ([sorted] and [sorted']),\n    and prove that they mean the same thing.  This increases our\n    confidence that we have the right specification, though of course\n    it doesn't _prove_ that we do. *)\n\n(** **** Exercise: 4 stars, optional (sorted_sorted')  *)\nLemma sorted_sorted': forall al, sorted al -> sorted' al.\n\n(** Hint: Instead of doing induction on the list [al], do induction\n    on the _sortedness_ of [al]. This proof is a bit tricky, so\n    you may have to think about how to approach it, and try out\n    one or two different ideas.*)\n\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (sorted'_sorted)  *)\nLemma sorted'_sorted: forall al, sorted' al -> sorted al.\n\n(** Here, you can't do induction on the sorted'-ness of the list,\n    because [sorted'] is not an inductive predicate. *)\n\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proving correctness from the alternate spec *)\n\n(** Depending on how you write the specification of a program, it can\n    be _much_ harder or easier to prove correctness.  We saw that the\n    predicates [sorted] and [sorted'] are equivalent; but it is really\n    difficult to prove correctness of insertion sort directly from\n    [sorted'].\n\n    Try it yourself, if you dare!  I managed it, but my proof is quite\n    long and complicated.  I found that I needed all these facts:\n    - [insert_perm], [sort_perm]\n    - [Forall_perm], [Permutation_length]\n    - [Permutation_sym], [Permutation_trans]\n    - a new lemma [Forall_nth], stated below.\n\n    Maybe you will find a better way that's not so complicated.\n\n    DO NOT USE [sorted_sorted'], [sorted'_sorted], [insert_sorted], or\n    [sort_sorted] in these proofs! *)\n\n(** **** Exercise: 3 stars, optional (Forall_nth)  *)\nLemma Forall_nth:\n  forall {A: Type} (P: A -> Prop) d (al: list A),\n     Forall P al <-> (forall i,  i < length al -> P (nth i al d)).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 4 stars, optional (insert_sorted')  *)\nLemma insert_sorted':\n  forall a l, sorted' l -> sorted' (insert a l).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (insert_sorted')  *)\nTheorem sort_sorted': forall l, sorted' (sort l).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The moral of this story *)\n\n(** The proofs of [insert_sorted] and [sort_sorted] were easy; the\n    proofs of [insert_sorted'] and [sort_sorted'] were difficult; and\n    yet [sorted al <-> sorted' al].  _Different formulations of the\n    functional specification can lead to great differences in the\n    difficulty of the correctness proofs_.\n\n   Suppose someone required you to prove [sort_sorted'], and never\n   mentioned the [sorted] predicate to you.  Instead of proving\n   [sort_sorted'] directly, it would be much easier to design a new\n   predicate ([sorted]), and then prove [sort_sorted] and\n   [sorted_sorted']. *)\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/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.9019206732341566, "lm_q1q2_score": 0.7883483224815349}}
{"text": "Require Import bool.\nRequire Import nat.\n\nRequire Import inductive_prop.\nRequire Import induction.\n\n\nInductive le : nat -> nat -> Prop :=\n| le_n : forall (n:nat), le n n\n| le_S : forall (n m:nat), le n m -> le n (S m)\n.\n\nNotation \"n <= m\" := (le n m).\n\nDefinition lt (n m:nat) : Prop := le (S n) m.\n\nNotation \"n < m\" := (lt n m).\n\nLemma le_refl : forall (n:nat), n <= n.\nProof. intros n. apply le_n. Qed.\n\n\nLemma le_trans : forall (n m p:nat), \n    n <= m -> m <= p -> n <= p.\nProof.\n    intros n m p H. revert p. induction H as [n|n m H IH].\n    - intros p H'. exact H'.\n    - intros p H'. remember (S m) as m' eqn:H0. revert H0 IH H.\n        revert n m. induction H' as [p|m' p H' IH'].  \n        + intros n m Hp IH Hnm. apply IH. rewrite Hp. apply le_S, le_n.\n        + intros n m Hm IH Hnm. apply le_S. apply (IH' n m).\n            { exact Hm. }\n            { exact IH. }\n            { exact Hnm. } \nQed.\n\n\nLemma le_0_n : forall (n:nat), 0 <= n.\nProof. \n    induction n as [|n H].\n    - apply le_n.\n    - apply le_S. exact H.\nQed.\n\n\nLemma n_le_m__Sn_le_Sm : forall (n m:nat),\n    n <= m -> S n <= S m.\nProof.\n    intros n m H. induction H as [n|n m H IH].\n    - apply le_n.\n    - apply le_S. exact IH.\nQed.\n\n\nLemma Sn_le_Sm__n_le_m : forall (n m:nat),\n    S n <= S m -> n <= m.\nProof.\n    intros n m H. inversion H as [H0|p H1].\n    - apply le_n.\n    - apply le_trans with (m := S n).\n      +  apply le_S, le_n.\n      +  auto. \nQed.\n        \n\nLemma le_plus_l : forall (n m: nat), n <= n + m.\nProof.\n    intros n m. induction m as [|m H].\n    - rewrite plus_n_0. apply le_n.\n    - rewrite plus_n_Sm. apply le_S. exact H.\nQed.\n\nLemma plus_lt : forall (n m p:nat),\n    n + m < p -> n < p /\\ m < p.\nProof.\n    intros n m p H. unfold lt in H. split.\n    - unfold lt. apply le_trans with (m := S (n + m)).\n        + rewrite <- plus_Sn_m. apply le_plus_l.\n        + exact H.\n    - unfold lt. apply le_trans with (m := S (n + m)).\n        + rewrite plus_comm. rewrite <- plus_Sn_m. apply le_plus_l.\n        + exact H.\nQed.\n\n\nLemma lt_S :  forall (n m:nat), n < m -> n < S m.\nProof.\n    intros n m. unfold lt. intros H. apply le_S. exact H.\nQed.\n\n\nLemma leb_complete : forall (n m:nat),\n    leb n m = true -> n <= m.\nProof.\n    induction n as [|n H].\n    - intros. apply le_0_n.\n    - induction m as[|m H'].\n        + simpl. intros H'. inversion H'.\n        + simpl. intros H0. apply n_le_m__Sn_le_Sm. apply H. exact H0.\nQed.\n\nLemma leb_correct : forall (n m:nat),\n    n <= m-> leb n m = true.\nProof.\n    intros n m. generalize n. clear n. induction m as [|m H].\n    - intros n H. inversion H. reflexivity.\n    - induction n as [|n H'].\n        + intros H'. reflexivity.\n        + intros H0. simpl. apply Sn_le_Sm__n_le_m in H0. \n            apply H. exact H0.\nQed.\n\nLemma leb_trans : forall (n m p:nat),\n    leb n m = true -> leb m p = true -> leb n p = true.\nProof.\n    intros n m p Hnm Hmp. apply leb_correct. apply le_trans with (m:=m).\n    - apply leb_complete. exact Hnm.\n    - apply leb_complete. exact Hmp.\nQed.\n\nLemma leb_iff : forall (n m:nat),\n    leb n m = true <-> n <= m.\nProof. \n    intros n m. split.\n    - exact (leb_complete n m).\n    - exact (leb_correct n m).\nQed.\n\nLemma le_n_0 : forall (n:nat), n <= 0 -> n = 0.\nProof. intros n H. inversion H. reflexivity. Qed.\n\nLemma not_le_Sm_n : forall (n m:nat), n <= m -> ~(S m <= n).\nProof.\n  intros n m. revert n. induction m as [|m IH]. \n  - intros n H H'. apply le_n_0 in H. rewrite H in H'. inversion H'.\n  - intros n H H'. remember (S m) as q eqn:H0. destruct H as [|p n].\n    + apply (IH n). \n      { apply Sn_le_Sm__n_le_m. rewrite <- H0. exact H'. }\n      { apply le_n. }\n    + apply (IH p). \n      { inversion H0 as [H2]. rewrite H2 in H. exact H. }\n      { apply le_trans with (m:=S (S n)).\n        { apply le_S, le_n. }\n        { exact H'. }\n      }\nQed.\n\nLemma not_le_Sn_n : forall (n:nat), ~(S n <= n).\nProof. intro n. apply not_le_Sm_n. apply le_n. Qed.\n\n\nLemma le_antisym : forall (n m:nat),\n  n <= m -> m <= n -> n = m.\nProof.\n  intros n m H. destruct H as [|n p H].\n  - intros _. reflexivity.\n  - intros H'. exfalso. apply (not_le_Sn_n p).\n    apply le_trans with (m:=n).\n      + exact H'.\n      + exact H.\nQed.\n\n\nLemma n_lt_m__Sn_lt_Sm : forall (n m:nat), n < m -> S n < S m.\nProof.\n    intros n m H. unfold lt in H. unfold lt. apply n_le_m__Sn_le_Sm. exact H.\nQed.\n\nLemma Sn_lt_Sm__n_lt_m : forall (n m:nat), S n < S m -> n < m.\nProof.\n    intros n m H. unfold lt in H. unfold lt. apply Sn_le_Sm__n_le_m. exact H.\nQed.\n\nLemma le_lt_dec : forall (n m:nat), {n <= m} + {m < n}. \nProof.\n    intros n. induction n as [|n IH].\n    - left. apply le_0_n.\n    - intros m. revert IH. revert n. induction m as [|m IH].\n        + intros n _. right. unfold lt. apply n_le_m__Sn_le_Sm. apply le_0_n.\n        + intros n H. destruct (H m) as [H'|H'].\n            { left. apply n_le_m__Sn_le_Sm. exact H'. }\n            { right. apply n_lt_m__Sn_lt_Sm. exact H'. }\nQed.\n\n\nLemma plus_le_compat_l : forall (n m p:nat),\n    m <= p -> n + m <= n + p.\nProof.\n    intros p. induction p as [|p IH].\n    - intros m p H. exact H.\n    - intros n m H. simpl. apply n_le_m__Sn_le_Sm. apply IH. exact H.\nQed.\n\nLemma plus_lt_compat_l : forall (n m p:nat),\n    m < p -> n + m < n + p.\nProof.\n    intros n m p H. unfold lt in H. unfold lt.\n    rewrite <- plus_n_Sm. apply plus_le_compat_l. exact H.\nQed.\n\nLemma plus_le_compat : forall (n m n' m':nat),\n    n <= n' -> m <= m' -> n + m <= n' + m'.\nProof.\n    intros n m n' m' Hn Hm. apply le_trans with (m:=n + m').\n    - apply plus_le_compat_l. exact Hm.\n    - rewrite (plus_comm n m'), (plus_comm n' m'). apply plus_le_compat_l. exact Hn.\nQed.\n\nLemma plus_lt_compat : forall (n m n' m':nat),\n    n < n' -> m < m' -> n + m < n' + m'.\nProof.\n    intros n m n' m' Hn Hm. unfold lt in Hn. unfold lt in Hm. unfold lt.\n    rewrite <- plus_n_Sm. apply le_trans with (m:=S n + S m).\n    - rewrite (plus_comm n (S m)). rewrite (plus_comm (S n) (S m)).\n        apply plus_le_compat_l. apply le_S, le_n.\n    - apply plus_le_compat.\n        + exact Hn.\n        + exact Hm.\nQed.\n\n\nLemma sum_leq_sum : forall (n m p q:nat),\n    n + m <= p + q -> n <= p \\/ m <= q.\nProof.\n    intros n m p q H. \n    assert ({n <= p} + {p < n}) as [H0|H0]. {apply le_lt_dec. }\n    - left. exact H0.\n    - assert ({m <= q} + {q < m}) as [H1|H1]. {apply le_lt_dec. }\n        + right. exact H1.\n        + exfalso. assert (p + q < n + m) as H2. apply plus_lt_compat.\n            { exact H0. } { exact H1. } \n            unfold lt in H2. assert ( S (p + q) <= p + q ) as H3.\n            { apply le_trans with (m:=n+m). \n                { exact H2. }\n                { exact H. } }\n            apply (not_le_Sn_n (p + q)). exact H3.\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/sf/le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7882971610363442}}
{"text": "(** * Logic: Logic in Coq *)\n\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 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. *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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(* FILL IN HERE *)\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, 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  (* 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\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 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 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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\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  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 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\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. *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** We've seen two different ways of encoding logical facts in Coq:\n    with _booleans_ (of type [bool]), and with _propositions_ (of type\n    [Prop]).\n\n    For instance, to claim that a number [n] is even, we can say\n    either\n       - (1) that [evenb n] returns [true], or\n       - (2) that there exists some [k] such that [n = double k].\n             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  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* FILL IN HERE *) Admitted.\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, while 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  (* FILL IN HERE *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.\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(* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "hkrsnd", "repo": "coq", "sha": "199cec72dd10c5b08b32f4bd14679a1b544d758f", "save_path": "github-repos/coq/hkrsnd-coq", "path": "github-repos/coq/hkrsnd-coq/coq-199cec72dd10c5b08b32f4bd14679a1b544d758f/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.7882811235496643}}
{"text": "(** Exercise sheet for lecture 2: Fundamentals of Coq.\n\nThe goal is to replace all of the \"...\" by suitable Coq code\nsatisfying the specification below.\n\nWritten by Anders Mörtberg.\nMinor modifications made by Marco Maggesi.\n\n*)\nRequire Import UniMath.Foundations.Preamble.\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\n(* Definition orbool (b : bool) : bool -> bool := ... *)\n\n(* This should satisfy:\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\n\n(** * Natural numbers *)\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n  nat_rect (fun _ : nat => A) a f.\n\nDefinition pred : nat -> nat := nat_rec nat 0 (const nat nat).\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 *)\n\n(* Definition odd : nat -> bool := ... *)\n\n(* This should satisfy\nEval compute in odd 24.    (* false *)\nEval compute in odd 19.   (* true *)\n\nBeware of big numbers: [UniMath.Foundations.Preamble] only defines notation up to 24.\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\n(* Notation \"...\" := (...) (at level 1). *)\n\n(** Note that we cannot introduce the notation \"if b then x else y\" as\nthis is already used. *)\n\n(* Definition negbool' (b : bool) : bool := ... *)\n\n(* Check that negbool' uses ifbool by disabling printing of notations *)\n(* Command palette Display All Basic Low-level Contents. *)\nPrint negbool'.\n(* Command palette Display All Basic Low-level Contents. *)\n\n(* This should satisfy:\nEval compute in negbool' true.   (* false *)\nEval compute in negbool' false.  (* true *)\n*)\n\n(* Definition andbool' (b1 b2 : bool) : bool := ... *)\n\n(* This should satisfy:\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\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\n(* Type space and then \\hat to enter the symbol  ̂. *)\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 *)\n\n(* Definition add' (m : nat) : nat → nat := ... *)\n\n(* This should satisfy:\nEval compute in add' 4 9.   (* 13 *)\n*)\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\n(* Definition ltnat (m n : nat) : bool := ... *)\n\n(* Notation \"x < y\" := (ltnat x y). *)\n\n(* This should satisfy:\nEval compute in (2 < 3). (* true *)\nEval compute in (3 < 3). (* false *)\nEval compute in (4 < 3). (* false *)\n*)\n\n(* Definition gtnat (m n : nat) : bool := ... *)\n\n(* Notation \"x > y\" := (gtnat x y). *)\n\n(* This should satisfy:\nEval compute in (2 > 3). (* false *)\nEval compute in (3 > 3). (* false *)\nEval compute in (4 > 3). (* true *)\n*)\n\n(* Definition leqnat (m n : nat) : bool := ... *)\n\n(* Notation \"x ≤ y\" := (leqnat x y) (at level 10). *)\n\n(* This should satisfy:\nEval compute in (2 ≤ 3). (* true *)\nEval compute in (3 ≤ 3). (* true *)\nEval compute in (4 ≤ 3). (* false *)\n*)\n\n(* Definition geqnat (m n : nat) : bool := ... *)\n\n(* Notation \"x ≥ y\" := (geqnat x y) (at level 10). *)\n\n(* This should satisfy:\nEval compute in (2 ≥ 3). (* false *)\nEval compute in (3 ≥ 3). (* true *)\nEval compute in (4 ≥ 3). (* true *)\n*)\n\n\n(** * Coproduct and integers *)\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\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\n(* Definition Zadd : Z -> Z -> Z := ... *)\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*)\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2022-07-Cortona/2_Fundamentals-Coq/coq_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686201, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7882522491576804}}
{"text": "Require Export Basics.\n\nTheorem plus_n_0 : forall n : nat, n = n + 0.\nProof.\n  intros n.\n  induction n as [| n' Sn'].\n  - reflexivity. (* n = 0 *)\n  - simpl. (* S n' = S n' + 0 -> S n' = S (n' + 0) *)\n    rewrite <- Sn'. (* Sn' : n' = n' + 0, S n' = S (n' + 0) -> S n' = S n' *)\n    reflexivity.\nQed.\n\nTheorem minus_diag : forall n, minus n n = 0.\nProof.\n  induction n as [| n' Sn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> Sn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  induction n as [| n' Sn' ].\n  - reflexivity.\n  - simpl. rewrite -> Sn'. reflexivity.\nQed.\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' Sn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite -> Sn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n' Sn' ].\n  - simpl. rewrite <- plus_n_0. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite <- Sn'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat, n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.\n  induction n as [| n' Sn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite <- Sn'. 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  induction n as [| n' Sn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite <- Sn'. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  induction n as [| n' Sn' ].\n  - simpl. reflexivity.\n  - rewrite -> Sn'. simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n\nTheorem plus_rearrange : forall n m p q : nat, (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H : m + n = n + m).\n  - rewrite -> plus_comm. reflexivity.\n  - rewrite -> H. reflexivity.\nQed.\n", "meta": {"author": "dinosaure", "repo": "-", "sha": "3cdcc49a0da2c64e7b60448ac55aac28a2ce9b1d", "save_path": "github-repos/coq/dinosaure--", "path": "github-repos/coq/dinosaure--/--3cdcc49a0da2c64e7b60448ac55aac28a2ce9b1d/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7882320723129864}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** *** Exercise :\n    - Define the option container with constructors None and Some\n    - Define the \"projection\" default\n*)\nInductive option\n(*D*)A := Some (a : A) | None.\nArguments Some {_}.\nArguments None {_}.\n\nDefinition default\n(*D*)A (a : A) (x : option A) := if x is Some v then v else a.\nEval lazy in default 3 None. (* 3 *)\nEval lazy in default 3 (Some 4). (* 4 *)\n\n(** *** Exercise :\n    Define boolean negation\n*)\nDefinition negb b :=\n(*D*)if b then false else true.\nNotation \"~~ x\" := (negb x).\n\nEval lazy in negb true.\nEval lazy in negb false.\n\n(** *** Exercise :\n    Use the [iter] function below to define:\n    - addition over natural numbers.\n    - multiplication over natural unmbers.\n*)\nFixpoint iter (T : Type) n op (x : T) :=\n  if n is p.+1 then op (iter p op x) else x.\nArguments iter {T}.\n\nDefinition addn n m :=\n(*D*)iter n S m.\n\nEval lazy in addn 3 4.\n\nDefinition muln n m :=\n(*D*)iter n (addn m) 0.\n\nEval lazy in muln 3 4.\n\n(** *** Exercise :\n    - Define muln by recursion\n*)\nFixpoint muln_rec n m :=\n(*D*)if n is p.+1 then m + (muln_rec p m) else 0.\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/exercise1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7882320654318536}}
{"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(* ** Prime numbers *)\n\nRequire Import List Arith Lia Bool Permutation.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list utils_nat gcd sums.\n\nSet Implicit Arguments.\n\nSection prime.\n\n  Hint Resolve divides_0 divides_mult divides_refl divides_0_inv : core.\n\n  Infix \"<d\" := divides (at level 70, no associativity).\n\n  Definition prime p := p <> 1 /\\ forall q, q <d p -> q = 1 \\/ q = p.\n\n  Fact prime_2 : prime 2.\n  Proof. \n    split; try lia.\n    apply divides_2_inv.\n  Qed.\n\n  Hint Resolve prime_2 : core.\n\n  Fact prime_algo p : prime p <-> p = 2 \\/ 3 <= p /\\ ~ 2 <d p /\\ forall n, 3+2*n < p -> ~ 3+2*n <d p.\n  Proof.\n    split.\n    + intros (H1 & H2).\n      destruct (le_lt_dec 3 p) as [ H | H ].\n      * right; split; auto; split.\n        - intros H3; apply H2 in H3; lia.\n        - intros n Hn C; apply H2 in C; lia.\n      * left; destruct p as [ | [ | [ | p ] ] ]; try lia.\n        destruct (H2 2); try lia.\n        exists 0; auto.\n    + intros [ H1 | (H1 & H2 & H3) ].\n      * subst; auto.\n      * split; try lia.\n        intros q Hq.\n        destruct (euclid_2 q) as (k & [ H4 | H4 ]).\n        - destruct H2; apply divides_trans with (2 := Hq).\n          exists k; lia.\n        - destruct k; try lia.\n          destruct (le_lt_dec p (3+2*k)) as [ H5 | H5 ].\n          ++ apply divides_le in Hq; lia.\n          ++ destruct (H3 k); auto.\n             eq goal Hq; f_equal; lia.\n  Qed.\n\n  Definition divides_bool n p := \n    match p mod n with\n      | 0 => true\n      | _ => false\n    end.\n\n  Fact modS_divide n p : p mod S n = 0 <-> S n <d p.\n  Proof.\n    rewrite Nat.mod_divide; try discriminate; tauto.\n  Qed.\n\n  Fact divides_bool_spec n p : divides_bool (S n) p = true <-> S n <d p.\n  Proof.\n    unfold divides_bool.\n    generalize (modS_divide n p).\n    case_eq (p mod S n); try tauto.\n    intros k H1 <-; split; discriminate.\n  Qed.\n\n  Fact divides_bool_spec' n p : divides_bool (S n) p = false <-> ~ S n <d p.\n  Proof.\n    rewrite <- divides_bool_spec.\n    destruct (divides_bool (S n) p); now split.\n  Qed.\n\n  Fixpoint prime_bool_rec n p : bool := \n    match n with \n      | 0       => true\n      | 1       => true\n      | 2       => true \n      | S (S n') => negb (divides_bool n p) && prime_bool_rec n' p\n    end.\n\n  Fact prime_bool_rec_spec n p : n <= p -> prime_bool_rec n p = true <-> forall k, 3 <= n-2*k -> ~ n-2*k <d p.\n  Proof.\n    induction on n as IHn with measure n; intros Hn.\n    destruct n as [ | [ | [ | n' ] ] ].\n    1-3: split; try (simpl; auto; fail); intros _ k H; lia.\n    unfold prime_bool_rec; fold (prime_bool_rec (S n') p).\n    revert Hn; set (m := S n'); intros Hn. \n    rewrite andb_true_iff, negb_true_iff, divides_bool_spec', IHn; try lia.\n    split.\n    + intros (H1 & H2) [ | q ] G1 G2.\n      * apply H1 in G2; auto.\n      * apply (H2 q); try lia.\n        eq goal G2; f_equal; lia.\n    + intros H1; split.\n      * apply (H1 0); lia.\n      * intros k G1 G2; apply (H1 (S k)); try lia.\n        eq goal G2; f_equal; lia.\n  Qed.\n\n  (* This is a somewhat naive algo. to test for primality *)\n\n  Definition prime_bool p := \n    Nat.eqb p 2 || Nat.leb 3 p && negb (divides_bool 2 p) && prime_bool_rec (p-2) p.\n\n  Theorem prime_bool_spec p : prime_bool p = true <-> prime p.\n  Proof.\n    unfold prime_bool.\n    rewrite orb_true_iff, !andb_true_iff, negb_true_iff, divides_bool_spec'.\n    rewrite Nat.eqb_eq, Nat.leb_le.\n    split.\n    + intros [ H1 | ((H1 & H2) & H3) ].\n      * subst; auto.\n      * split; try lia.\n        destruct (euclid_2 p) as (p' & [ Hp | Hp ]).\n        { destruct H2; exists p'; lia. }\n        destruct p' as [ | p' ]; try (exfalso; lia).\n        rewrite prime_bool_rec_spec in H3; try lia.\n        intros q Hq.\n        destruct (euclid_2 q) as (k & [ H4 | H4 ]).\n        - destruct H2; apply divides_trans with (2 := Hq); exists k; lia.\n        - destruct k as [ | k ]; try lia.\n          destruct (le_lt_dec p q) as [ H5 | H5 ].\n          ++ apply divides_le in Hq; lia.\n          ++ assert (k < p') as H6 by lia.\n             destruct (H3 (p'-S k)); try lia.\n             eq goal Hq; f_equal; lia.\n    + intros (H1 & H2).\n      destruct (le_lt_dec 3 p) as [ H3 | H3 ].\n      * right; lsplit 2; auto.\n        - intros C; apply H2 in C; lia.\n        - apply prime_bool_rec_spec; try lia.\n          intros q H4 H5.\n          apply H2 in H5; lia.\n      * left; destruct p; try lia.\n        destruct (H2 2); try lia.\n        exists 0; auto.\n  Qed.\n\n  Fact prime_ge_2 p : prime p -> 2 <= p.\n  Proof.\n    destruct p as [ | [ | p ] ]; try lia.\n    + intros [ _ H ]; subst.\n      destruct (H 2); auto; discriminate.\n    + intros [ [] _ ]; auto.\n  Qed.\n\n  Fact prime_gcd p q : prime p -> is_gcd p q 1 \\/ p <d q.\n  Proof.\n    intros H.\n    generalize (gcd p q) (gcd_spec p q); intros g Hg.\n    destruct (proj2 H _ (proj1 Hg)); subst; auto.\n    right; apply Hg.\n  Qed.\n\n  Fact prime_div_mult p x y : prime p -> p <d x*y -> p <d x \\/ p <d y. \n  Proof.\n    intros H1 H2.\n    destruct (prime_gcd x H1); auto.\n    right; revert H H2; apply is_rel_prime_div.\n  Qed.\n\n  Definition prime_or_div p : 2 <= p -> { q | 2 <= q < p /\\ q <d p } + { prime p }.\n  Proof.\n    intros Hp.\n    destruct bounded_search with (m := S p) (P := fun n => 2 <= n < p /\\ n <d p)\n      as [ (q & H1 & H2) | H1 ].\n    + intros n _.\n      destruct (le_lt_dec p n).\n      { right; intros; lia. }\n      destruct (le_lt_dec 2 n).\n      * destruct (divides_dec p n) as [ (?&?) | ].\n        - left; subst; auto.\n        - right; tauto.\n      * right; lia.\n    + left; exists q; split; try tauto; try lia.\n    + right; split; auto.\n      * lia.\n      * intros q Hq.\n        destruct q as [ | q]; auto.\n        - apply divides_0_inv in Hq; auto.\n        - assert (~ 2 <= S q < p) as H2.\n          { intros H; apply (H1 (S q)); auto.\n            apply le_n_S, divides_le; auto; lia. }\n          apply divides_le in Hq; lia.\n  Qed.\n\n  Theorem prime_factor n : 2 <= n -> { p | prime p /\\ p <d n }.\n  Proof.\n    induction on n as IHn with measure n; intro Hn.\n    destruct (prime_or_div Hn) as [ (q & H1 & H2) | H1 ].\n    2: exists n; auto.\n    destruct (IHn q) as (p & H3 & H4); try lia.\n    exists p; split; auto.\n    apply divides_trans with (1 := H4); auto.\n  Qed.\n\n  Section prime_rect.\n\n    Variables (P : nat -> Type)\n              (HP0 : P 0)\n              (HP1 : P 1)\n              (HPp : forall p, prime p -> P p)\n              (HPm : forall x y, P x -> P y -> P (x*y)).\n\n    Theorem prime_rect n : P n.\n    Proof.\n      induction on n as IHn with measure n.\n      destruct n as [ | [ | n ] ]; auto.\n      destruct (@prime_factor (S (S n))) as (p & H1 & H2); try lia.\n      apply divides_div in H2.\n      rewrite H2.\n      apply HPm.\n      + apply IHn.\n        rewrite H2 at 2.\n        rewrite <- Nat.mul_1_r at 1.\n        apply prime_ge_2 in H1.\n        apply mult_lt_compat_l; try lia.\n      + apply HPp, H1.\n    Qed.\n\n  End prime_rect.\n\n  Corollary no_common_prime_is_coprime x y : x <> 0 -> (forall p, prime p -> p <d x -> p <d y -> False) -> is_gcd x y 1.\n  Proof.\n    intros Hx H; split; [ | split ].\n    + apply divides_1.\n    + apply divides_1.\n    + intros k H1 H2.\n      destruct k as [ | [ | k ] ].\n      * apply divides_0_inv in H1; lia.\n      * apply divides_1.\n      * destruct prime_factor with (n := S (S k)) as (p & P1 & P2); try lia.\n        exfalso; apply H with p; auto; apply divides_trans with (S (S k)); auto.\n  Qed.\n\n  Fact rel_prime_mult a b c : is_gcd a c 1 -> is_gcd b c 1 -> is_gcd (a*b) c 1.\n  Proof.\n    intros H1 H2; msplit 2; try apply divides_1.\n    intros k H3 H4.\n    apply H2; auto.\n    apply is_rel_prime_div with (2 := H3).\n    apply is_gcd_sym in H1.\n    revert H1; apply divides_is_gcd; auto.\n  Qed.\n\n  Fact is_rel_prime_mult p q l : is_gcd p q 1 -> is_gcd p l 1 -> is_gcd p (q*l) 1.\n  Proof.\n    intros H1 H2.\n    destruct p as [ | p ].\n    + generalize (is_gcd_fun H1 (is_gcd_0l _)) (is_gcd_fun H2 (is_gcd_0l _)).\n      intros; subst; auto.\n    + apply no_common_prime_is_coprime; try lia.\n      do 2 (apply proj2 in H1; apply proj2 in H2).\n      intros k Hk H3 H4.\n      apply prime_div_mult with (1 := Hk) in H4.\n      destruct H4 as [ H4 | H4 ]; \n      [ generalize (H1 _ H3 H4) \n      | generalize (H2 _ H3 H4) ];\n        intro H5; apply divides_1_inv in H5; subst; \n        destruct Hk; lia.\n  Qed.\n\n  Fact is_rel_prime_expo p q l : is_gcd p q 1 -> is_gcd p (mscal mult 1 l q) 1.\n  Proof.\n    intros H.\n    induction l as [ | l IHl ].\n    + rewrite mscal_0; apply is_gcd_1r.\n    + rewrite mscal_S; apply is_rel_prime_mult; auto.\n  Qed.\n\n  (* Every positive number is the product of a list of primes *)\n\n  Notation lprod := (fold_right mult 1).\n\n  Fact lprod_ge_1 l : Forall prime l -> 1 <= lprod l.\n  Proof.\n    induction 1 as [ | x l H IH ]; simpl; auto.\n    change 1 with (1*1) at 1; apply mult_le_compat; auto.\n    apply prime_ge_2 in H; lia.\n  Qed.\n\n  Fact lprod_app l m : lprod (l++m) = lprod l * lprod m.\n  Proof. induction l; simpl; lia. Qed.\n\n  Theorem prime_decomp n : n <> 0 -> { l | n = lprod l /\\ Forall prime l }.\n  Proof.\n    induction on n as IHn with measure n; intro Hn.\n    destruct (eq_nat_dec n 1) as [ Hn' | Hn' ].\n    + exists nil; simpl; auto.\n    + destruct (@prime_factor n) as (p & H1 & H2); try lia.\n      apply divides_div in H2; revert H2.\n      generalize (div n p); intros k Hk.\n      assert (k <> 0) as Hk'.\n      { intros ?; subst; destruct Hn; auto. }\n      destruct (IHn k) as (l & H2 & H3); auto.\n      - rewrite Hk.\n        generalize (prime_ge_2 H1).\n        rewrite mult_comm.\n        destruct p as [ | [ | p ] ]; simpl; intros; lia.\n      - exists (p::l); split; auto.\n        simpl; rewrite <- H2, mult_comm; auto.\n  Qed.\n\n  Hint Resolve lprod_ge_1 prime_ge_2 : core.\n\n  Fact prime_in_decomp p l : prime p -> Forall prime l -> p <d lprod l -> In p l.\n  Proof.\n    intros H1.\n    induction 1 as [ | x l Hl IHl ]; simpl; intros H2.\n    + apply divides_1_inv in H2; apply (proj1 H1); auto.\n    + destruct (prime_gcd x H1) as [ H3 | H3 ].\n      apply is_rel_prime_div with (1 := H3) in H2; auto.\n      apply (proj2 Hl) in H3.\n      destruct H3 as [ H3 | H3 ]; auto.\n      contradict H3;apply H1.\n  Qed.\n\n  (* Prime decomposition is unique up-to permutation *) \n\n  Theorem prime_decomp_uniq l m : Forall prime l -> Forall prime m -> lprod l = lprod m -> l ~p m.\n  Proof.\n    intros H; revert H m.\n    induction 1 as [ | x l Hx Hl IHl ].\n    + induction 1 as [ | y m Hy Hm IHm ]; simpl; auto.\n      intros C; exfalso.\n      assert (2*1 <= y*lprod m) as D.\n      { apply mult_le_compat; auto. }\n      simpl in D; lia.\n    + simpl; intros m Hm H1.\n      assert (In x m) as H2.\n      { apply prime_in_decomp with (1 := Hx); auto.\n        exists (lprod l); rewrite mult_comm; auto. }\n      apply in_split in H2.\n      destruct H2 as (m1 & m2 & H2); subst.\n      apply Permutation_cons_app, IHl.\n      * rewrite Forall_app in Hm.\n        destruct Hm as [ ? Hm ].\n        inversion Hm.\n        apply Forall_app; auto.\n      * rewrite lprod_app.\n        rewrite lprod_app in H1; simpl in H1.\n        rewrite mult_assoc, (mult_comm _ x), <- mult_assoc in H1.\n        apply Nat.mul_cancel_l in H1; auto.\n        apply prime_ge_2 in Hx; lia.\n  Qed.\n\nEnd prime.\n\nSection base_decomp.\n\n  (* [m0;m1;...;mk] -> m0 + p*(m1+....) *)\n\n  Fixpoint expand p l :=\n    match l with\n      | nil  => 0\n      | x::l => x+p*expand p l\n    end.\n\n  Notation power := (mscal mult 1).\n\n  Fact expand_app p l m : expand p (l++m) = expand p l + power (length l) p * expand p m.\n  Proof.\n    induction l as [ | x l IH ]; simpl; try lia.\n    rewrite power_S, IH, Nat.mul_add_distr_l, mult_assoc; lia.\n  Qed.\n\n  Fact expand_0 p l : Forall (eq 0) l -> expand p l = 0.\n  Proof.\n    induction 1 as [ | x l H1 H2 IH2 ]; simpl; subst; auto.\n    rewrite IH2, mult_comm; auto.\n  Qed.\n\n  Section base_p.\n\n    Variables (p : nat) (Hp : 2 <= p).\n\n    Let base_p_full n : { l | n = expand p l }.\n    Proof.\n      induction on n as IH with measure n.\n      destruct (eq_nat_dec n 0) as [ Hn | Hn ].\n      + exists nil; auto.\n      + destruct (@euclid n p) as (m & r & H1 & H2); try lia.\n        destruct (IH m) as (l & H3).\n        * destruct m; try lia.\n          rewrite H1, mult_comm.\n          apply lt_le_trans with (2*S m + r); try lia.\n          apply plus_le_compat; auto.\n          apply mult_le_compat; auto.\n        * exists (r::l); simpl.\n          rewrite mult_comm, plus_comm, <- H3, H1; auto.\n    Qed.\n\n    Definition base_p n := proj1_sig (base_p_full n).\n    Fact base_p_spec n : n = expand p (base_p n).\n    Proof. apply (proj2_sig (base_p_full n)). Qed.\n\n    Fact base_p_uniq l1 l2 : Forall2 (fun x y => x < p /\\ y < p) l1 l2 -> expand p l1 = expand p l2 -> l1 = l2.\n    Proof.\n      induction 1 as [ | x1 x2 l1 l2 H1 H2 IH2 ]; auto; simpl; intros H3.\n      rewrite (plus_comm x1), (plus_comm x2), (mult_comm p), (mult_comm p) in H3.\n      apply div_rem_uniq in H3; try lia.\n      destruct H3 as [ H3 ]; subst; f_equal; auto.\n    Qed.\n\n  End base_p.\n\nEnd base_decomp.\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/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7881887209125706}}
{"text": "Require Export LClos.\nRequire Import FunInd. \nOpen Scope LClos.\n\n(** *** Closure calculus interpreter *)\n\nDefinition CompBeta s t :=\n  match s,t with\n    |CompClos (lam ls) A,CompClos (lam lt) B => Some (CompClos ls (CompClos (lam lt) B::A))\n    |_,_ => None\n  end.\n\nDefinition CompAppCount j u v :=\n  match u,v with\n    (l,u),(k,v) => (j+(l+k),CompApp u v)\n  end.\n\nFixpoint CompSeval n (u: nat * Comp) : nat * Comp:=\n  match n with\n      S n =>\n      match u with\n        | (l,CompApp s t) =>\n          match CompBeta s t with\n            | Some u => CompSeval n (S l,u)\n            | None => CompSeval n (CompAppCount l (CompSeval n (0,s)) (CompSeval n (0,t)))\n          end\n        | (l,CompClos (app s t) A) => CompSeval n (l,(CompClos s A) (CompClos t A))\n        | (l,CompClos (var x) A) => (l,nth x A (CompVar x))\n        | u => u \n      end\n    | _ => u\n  end.\n\nLemma CompBeta_validComp s t u: validComp s -> validComp t -> CompBeta s t = Some u -> validComp u.\nProof with repeat (auto || congruence || subst || simpl in * || intuition).\n  intros vs vt eq. inv vs; inv vt... destruct s0... destruct s,s0... inv eq. repeat constructor... inv H1...\nQed.\n\nLemma CompSeval_validComp s k n: validComp s -> validComp (snd (CompSeval n (k,s))).\nProof with repeat (apply validCompApp ||apply validCompClos || eauto || congruence || subst || simpl in * || intuition). \n  revert s k. induction n; intros s k vs... inv vs...\n  case_eq (CompBeta s0 t);intros...\n  -apply CompBeta_validComp in H1...\n  -assert (IHn1 := IHn s0 0 H). assert (IHn2 := IHn t 0 H0).\n   unfold snd in *. do 2 destruct ((CompSeval n (_,_)))...\n  -destruct s0...\nQed.\n\nHint Resolve CompSeval_validComp.\n\nLemma CompBeta_sound s t u: CompBeta s t = Some u -> s t >[(1)] u.\nProof with repeat (auto || congruence || subst || simpl in * || intuition).\n  intros eq. destruct s,t... destruct s... destruct s... destruct s... destruct s0... inv eq. repeat constructor...\nQed.\n\nFunctional Scheme CompSeval_ind := Induction for CompSeval Sort Prop.\n\nLemma CompSeval_sound' n s l : let (k,t) := CompSeval n (l,s) in k >= l /\\ s >[(k-l)] t.\nProof with (repeat inv_validComp;repeat (constructor || intuition|| subst ; eauto using star || rewrite Nat.sub_diag||cbn in *)).\n  pose (p:= (l,s)).\n  change (let (k, t) := CompSeval n p in k >= fst p /\\ (snd p) >[(k-(fst p))] t).\n  generalize p. clear l s p. intros p. \n  functional induction (CompSeval n p); intros;cbn...\n  -apply CompBeta_sound in e2. destruct (CompSeval _ _);split... eapply CPow_trans;try  eassumption. omega.\n  -repeat destruct (CompSeval _ _)... eapply CPow_trans...\n  -repeat destruct (CompSeval _ _)... eapply CPow_trans...\nQed.\n\nLemma CompSeval_sound (n k:nat) s t : CompSeval n (0,s) = (k,t) -> s >[(k)] t.\nProof.\n  specialize (CompSeval_sound' n s 0). destruct _;intros.\n  inv H0. rewrite <- minus_n_O in H. tauto.\nQed.\n\n  \n", "meta": {"author": "uds-psl", "repo": "certifying-extraction-with-time-bounds", "sha": "248fb52fd0a9d38532727ea95256fec07eafa372", "save_path": "github-repos/coq/uds-psl-certifying-extraction-with-time-bounds", "path": "github-repos/coq/uds-psl-certifying-extraction-with-time-bounds/certifying-extraction-with-time-bounds-248fb52fd0a9d38532727ea95256fec07eafa372/Tactics/LClos_Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7881354942376838}}
{"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.\n  -reflexivity.\n  -simpl.\n  rewrite IHn.\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  induction l. {\n    simpl.\n    apply Exists_nil.\n  }\n  split. {\n    intros.\n    induction H. subst. { \n      simpl.\n      left.\n      reflexivity.\n    }\n  subst.\n  simpl.\n  right.\n  apply IHExists.\n  }\n  intros.\n  induction H. {\n    left.\n    symmetry.\n    apply H.\n  }\n  apply IHl in H.\n  right.\n  apply H.\nQed.\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),\n      succ x y (x :: y :: l)\n  | R2: forall (z:X) (l:list X),\n      succ x y l -> succ x y (z::l).\n\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\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  unfold not.\n  intros.\n  inversion H.\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  unfold not.\n  intros.\n  inversion H; \n  subst; \n  clear H.\n  inversion H1;\n  subst; \n  clear H1.\n  inversion H0;\n  subst; \n  clear H0.\n  inversion H1;\n  subst; \n  clear H1.\n  inversion H0;\n  subst; \n  clear.\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.\n  - simpl.\n    constructor.\n  - simpl.\n    induction l1. \n      + simpl.\n        apply R2.\n        apply R1.\n      + simpl.\n        simpl in IHl1.\n        apply R2.\n        apply IHl1.\nQed.\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  intros.\n  induction l.\n  - inversion H.\n  - inversion H. subst. \n    +  exists [],l0.\n       simpl. reflexivity.\n    +  subst. apply IHl in H1. destruct H1 as (n1,(n2,n3)).\n       subst. exists  (a::n1),(n2) . reflexivity.\nQed.\n\n\n\nStudent\nDivya Thota\nAutograder Score\n101.0 / 100.0\nQuestion 2\nDeductions\n0.0 / 0.0 pts\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/hw2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.9294404082102515, "lm_q1q2_score": 0.7881354852119214}}
{"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 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(* additional lemma *)\nLemma map_distrib : 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. induction l1 as [| n l1' IHl1'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl1'. reflexivity.\n    Qed.\n\n\n(* Exercise *)\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. induction l as [| n l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> map_distrib. 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/map_rev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.8947894696095783, "lm_q1q2_score": 0.7881279614368687}}
{"text": "(** Exercício de Programação Funcional**)\n\n(** Defina um programa que compute o antecessor do antecessor de um dado número n **)\n\n(** 1 star **)\n\nDefinition minustwo (n : nat) : nat :=\n\tmatch n with\n\t| 0        => 0\n\t| S 0      => 0\n\t| S (S n') =>  n'\n\tend.\n\n(** Teste a função minustwo **)\n(** 1 star **)\n\nExample test_minustwo_1 : minustwo 4 = 2.\n  Proof. simpl. reflexivity. Qed.\n\n(** 1 star **)\nExample test_minustwo_2 : minustwo 1 = 0.\n  Proof. reflexivity. Qed.\n\n(** 1 star **)\nExample test_minustwo_3 : minustwo 0 = 0.\n  Proof. reflexivity. Qed.\n\n(** Defina uma função que some 2 **)\n(** 1 star **)\n\nDefinition plustwo (n : nat) : nat :=\n  match n with\n  | 0    => S (S 0)\n  | S n' => S (S (S n'))\n  end.\n\n(** Teste a função plustwo **)\n(** 1 star **)\n\nExample test_plustwo_1 : plustwo 2 = 4.\n  Proof. simpl. reflexivity. Qed.\n\n(** 1 star **)\nExample test_plustwo_2 : plustwo 0 = 2.\n  Proof. simpl. reflexivity. Qed.\n\n(** Defina o tipo fruta (morango, uva e laranja) **)\n(** 1 star **)\nInductive fruta : Type :=\n  | morango : fruta\n  | uva     : fruta\n  | laranja : fruta .\n\n(** Defina o tipo salada, onde uma salada é formada pela combinação de até três frutas **)\n(** 1 star **)\nInductive salada : Type :=\n  | s1 : fruta -> salada\n  | s2 : fruta -> fruta -> salada\n  | s3 : fruta -> fruta -> fruta -> salada.\n  \n\n", "meta": {"author": "AndressaUmetsu", "repo": "coqExercicios", "sha": "f583bea6a32ef359cbddb786f7fb71803d7bf189", "save_path": "github-repos/coq/AndressaUmetsu-coqExercicios", "path": "github-repos/coq/AndressaUmetsu-coqExercicios/coqExercicios-f583bea6a32ef359cbddb786f7fb71803d7bf189/doit1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7880588894000942}}
{"text": "Require Export SfLib_J.\n\nModule AExp.\n  Inductive aexp: Type :=\n| ANum : nat -> aexp\n| APlus : aexp -> aexp -> aexp\n| AMinus : aexp -> aexp -> aexp\n| AMult : aexp -> aexp -> aexp.\n\n\n  Inductive 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\n  Fixpoint 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\n  Example test_aeval1: aeval(APlus (ANum 2) (ANum 2)) = 4.\n  Proof. reflexivity. Qed.\n\n  Fixpoint 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\n  Fixpoint optimize_0plus (e:aexp) : aexp :=\n    match e with\n      | ANum n => ANum n\n      | APlus (ANum 0) e2 => optimize_0plus e2\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                                           \n  Example test_optimize_0plus:\n    optimize_0plus (APlus (ANum 2)\n                          (APlus (ANum 0)\n                                 (APlus (ANum 0)\n                                        (ANum 1))))\n    = APlus (ANum 2) (ANum 1).\n  Proof. reflexivity. Qed.\n\n  Theorem optimize_0plus_sound: forall e,\n                                  aeval (optimize_0plus e) = aeval e.\n    Proof.\n      intros e. induction e.\n      + reflexivity.\n      + destruct e1.\n      - destruct n.\n        apply IHe2.\n        simpl. rewrite IHe2. reflexivity.\n      - simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.\n      - simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.\n      - simpl. simpl in IHe1. rewrite IHe1. rewrite IHe2. reflexivity.\n        + simpl. rewrite IHe1. rewrite IHe2. reflexivity.\n        + simpl. rewrite IHe1. rewrite IHe2. reflexivity.\n    Qed.\n\n    Lemma foo: forall n, ble_nat 0 n = true.\n    Proof.\n      intros. destruct n.\n      + simpl. reflexivity.\n      + simpl. reflexivity.\n    Qed.\n\n    Lemma foo': forall n, ble_nat 0 n = true.\n    Proof.\n      intros.\n      destruct n; simpl; reflexivity.\n    Qed.\n\n    Theorem optimize_0plus_sound': forall e,\n                                     aeval (optimize_0plus e) = aeval e.\n    Proof.\n      intros e.\n      induction e;\n        try (simpl; rewrite IHe1; rewrite IHe2; reflexivity).\n      Case \"ANum\". reflexivity.\n      Case \"APlus\".\n      destruct e1; try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n      SCase \"e1 = ANum n\". destruct n; simpl; rewrite IHe2; reflexivity. Qed.\n\n    Theorem optimize_0plus_sound'': forall e,\n                                      aeval (optimize_0plus e) = aeval e.\n    Proof.\n      intros e.\n      induction e;\n        try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);\n        try reflexivity.\n      Case \"APlus\".\n      destruct e1; try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n      SCase \"e1 = ANum n\". destruct n; simpl; rewrite IHe2; reflexivity. Qed.\n\n    Tactic Notation \"simpl_and_try\" tactic(c) := simpl; try c.\n\n    Tactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n      first;\n      [Case_aux c \"ANum\" | Case_aux c \"APlus\"\n       | Case_aux c \"AMinus\" | Case_aux c \"AMult\"].\n\n    Theorem optimize_0plus_sound''': forall e,\n                                       aeval (optimize_0plus e) = aeval e.\n    Proof.\n      intros e.\n      aexp_cases (induction e) Case;\n        try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);\n        try reflexivity.\n      Case \"APlus\".\n      aexp_cases (destruct e1) SCase;\n        try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n      SCase \"ANum\". destruct n;\n        simpl; rewrite IHe2; reflexivity. Qed.\n\n    Fixpoint optimize_0plus_b (e: bexp) : bexp :=\n      match e with\n        | BTrue => BTrue\n        | BFalse => BFalse\n        | BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)\n        | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n        | BNot b1 => BNot (optimize_0plus_b b1)\n        | BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)\n      end.\n\n    Theorem optimize_0plus_b_sound: forall e, beval (optimize_0plus_b e) = beval e.\n    Proof.\n      intros e.\n      induction e;\n        simpl;\n        try (rewrite optimize_0plus_sound;\n                     rewrite optimize_0plus_sound;\n                     reflexivity);\n        try reflexivity.\n      rewrite IHe. reflexivity.\n      rewrite IHe1. rewrite IHe2. reflexivity.\n    Qed.\n\n    Example silly_presburger_example: forall n m o p,\n                                        m + n <= n + o /\\ o + 3 = p + 3 -> m <= p.\n    Proof.\n      intros. omega.\n    Qed.\n\n    Module aevalR_first_try.\n      Inductive aevalR: aexp -> nat -> Prop :=\n    | E_ANum: forall (n: nat),\n                aevalR (ANum n) n\n    | E_APlus: forall (e1 e2: aexp) (n1 n2: nat),\n                 aevalR e1 n1 ->\n                 aevalR e2 n2 ->\n                 aevalR (APlus e1 e2) (n1 + n2)\n    | E_AMinus: forall (e1 e2: aexp) (n1 n2: nat),\n                  aevalR e1 n1 ->\n                  aevalR e2 n2 ->\n                  aevalR (AMinus e1 e2) (n1 - n2)\n    | E_AMult: forall (e1 e2: aexp) (n1 n2: nat),\n                 aevalR e1 n1 ->\n                 aevalR e2 n2 ->\n                 aevalR (AMult e1 e2) (n1 * n2).\n\n      Notation \"e '||' n\" := (aevalR e n) : type_scope.\n    End aevalR_first_try.\n\n    Reserved Notation \"e '||' n\" (at level 50, left associativity).\n\n    Inductive aevalR: aexp -> nat -> Prop :=\n    | E_ANum: forall (n: nat),\n                (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) : type_scope.\n\n    Tactic Notation \"aevalR_cases\" tactic(first) ident(c) :=\n      first;\n      [ Case_aux c \"E_ANum\" | Case_aux c \"E_APlus\" | Case_aux c \"E_AMinus\" | Case_aux c \"E_AMult\"].\n\n    Theorem aeval_iff_aevalR: forall a n,\n                                (a || n) <-> aeval a = n.\n    Proof.\n      split.\n      Case \"->\".\n      intros H; induction H; subst; reflexivity.\n      Case \"<-\".\n      generalize dependent n.\n      induction a; simpl; intros; subst; constructor;\n      try apply IHa1; try apply IHa2; reflexivity.\n    Qed.\n\nEnd AExp.\n\nTheorem beq_id_refl: forall X,\n                       true = beq_id X X.\nProof.\n  intros. destruct X.\n  apply beq_nat_refl.\nQed.\n\nTheorem beq_id_eq: forall i1 i2,\n                     true = beq_id i1 i2 -> i1 = i2.\nProof.\n  intros i1 i2.\n  destruct i1.\n  destruct i2.\n  unfold beq_id.\n  intros H.\n  apply beq_nat_eq in H.\n  subst.\n  reflexivity.\nQed.\n\nDefinition state := id -> nat.\nDefinition empty_state: state :=\n  fun _ => 0.\nDefinition update (st: state) (X: id) (n: nat) : state :=\n  fun X' => if beq_id X X' then n else st X'.\n\nTheorem update_eq: forall n X st,\n                     (update st X n) X = n.\nProof.\n  intros n X st.\n  unfold update. replace (beq_id X X) with true.\n  reflexivity.\n  apply beq_id_refl.\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 V2 V1 n st H.\n  unfold update.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem update_example: forall (n: nat),\n                          (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  intros n.\n  unfold update. simpl. unfold empty_state. 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 x1 x2 k1 k2 f.\n  unfold update.\n  case (beq_id k2 k1).\n  + reflexivity.\n  + reflexivity.\nQed.\n\nTheorem update_some: forall x1 k1 k2 (f: state),\n                       f k1 = x1 -> (update f k1 x1) k2 = f k2.\nProof.\n  intros x1 k1 k2 f H.\n  unfold update.\n  subst.\n  remember (beq_id k1 k2) as H.\n  destruct H.\n  replace k1 with k2. reflexivity.\n  apply beq_id_eq. rewrite beq_id_sym.\n  apply HeqH. reflexivity.\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 x1 x2 k1 k2 k3 f H.\n  unfold update.\n  remember (beq_id k1 k3) as A.\n  remember (beq_id k2 k3) as B.\n  destruct A.\n  replace k3 with k1 in HeqB.\n  rewrite H in HeqB.\n  subst. reflexivity.\n  apply beq_id_eq. apply HeqA.\n  reflexivity.\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\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [Case_aux c \"ANum\" | Case_aux c \"AId\" | Case_aux c \"APlus\"\n   |Case_aux c \"AMinus\" | Case_aux c \"AMult\"].\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\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\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\" | Case_aux c \"BEq\"\n    | Case_aux c \"BLe\" | Case_aux c \"BNot\" | Case_aux c \"BAnd\" ].\n\nFixpoint aeval (st: state) (e: aexp): nat :=\n  match e with\n    | ANum n => n\n    | AId X => st X\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\nExample aexp1:\n  aeval (update empty_state X 5)\n        (APlus (ANum 3) (AMult (AId X) (ANum 2)))\n        = 13.\nProof. reflexivity. Qed.\n\nExample bexp1: beval (update empty_state X 5)\n                     (BAnd BTrue (BNot (BLe (AId X) (ANum 4))))\n               = true.\nProof. reflexivity. Qed.\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\nTactic Notation \"com_cases\" tactic(first) ident(c) :=\n  first;\n  [Case_aux c \"SKIP\" | Case_aux c \"::=\" | Case_aux c \";\"\n   | Case_aux c \"IFB\" | Case_aux c \"WHILE\"].\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' e1 'THEN' e2 'ELSE' e3 'FI'\" :=\n  (CIf e1 e2 e3) (at level 80, right associativity).\n\nDefinition fact_in_coq: com :=\n  Z ::= AId X;\n  Y ::= ANum 1;\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n        Y ::= AMult (AId Y) (AId Z);\n        Z ::= AMinus (AId Z) (ANum 1)\n  END.\n\nDefinition plus2: com :=\n  X ::= (APlus (AId X) (ANum 2)).\n\nDefinition XtimesYinZ: com :=\n  Z ::= (AMult (AId X) (AId Y)).\n\nDefinition substract_slowly_body : com :=\n  Z ::= AMinus (AId Z) (ANum 1);\n  X ::= AMinus (AId X) (ANum 1).\n\nDefinition substract_slowly: com :=\n  WHILE BNot (BEq (AId X) (ANum 0)) DO\n        substract_slowly_body\n  END.\n\nDefinition substract_3_from_5_slowly: com :=\n  X ::= ANum 3;\n  Z ::= ANum 5;\n  substract_slowly.\n\nDefinition loop : com :=\n  WHILE BTrue DO\n        SKIP\n  END.\n\nDefinition fact_body: com :=\n  Y ::= AMult (AId Y) (AId Z);\n  Z ::= AMinus (AId Z) (ANum 1).\n\nDefinition fact_loop: com :=\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n        fact_body\n  END.\n\nDefinition fact_com : com :=\n  Z ::= AId X;\n  Y ::= ANum 1;\n  fact_loop.\n\nFixpoint ceval_step1 (st: state) (c: com) : state :=\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_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 =>\n      st\n  end.\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_step1 st' c2\n        | IFB b THEN c1 ELSE c2 FI =>\n          if (beval st b)\n          then ceval_step2 st c1 i'\n          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)\n          then ceval_step3 st c1 i'\n          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\nNotation \"'LETOPT' x <== e1 'IN' e2\"\n  := (match e1 with\n        | Some x => e2\n        | None => None\n      end)\n       (right associativity, at level 60).\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          LETOPT st' <== ceval_step st c1 i' IN\n                 ceval_step st' c2 i'\n        | IFB b THEN c1 ELSE c2 FI =>\n              if (beval st b)\n              then ceval_step st c1 i'\n              else ceval_step st c2 i'\n        | WHILE b1 DO c1 END =>\n          if (beval st b1)\n          then LETOPT st' <== ceval_step st c1 i' IN\n                      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  WHILE BNot (BEq (AId X)  (ANum 0)) DO\n        Y ::= APlus (AId X) (AId Y);\n        X ::= AMinus (AId X) (ANum 1)\n  END.\n\nReserved Notation \"c1 '/' st '||' st'\" (at level 40, st at level 39).\n\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\n\nTactic Notation \"ceval_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"E_SKip\" | Case_aux c \"E_Ass\" | Case_aux c \"E_Seq\"\n    | Case_aux c \"E_IfTrue\" | Case_aux c \"E_IfFalse\"\n    | Case_aux c \"E_WhileEnd\" | Case_aux c \"E_WhileLoop\" ].\n\nExample ceval_example1:\n  (X ::= ANum 2;\n   IFB BLe (AId X) (ANum 1)\n       THEN Y ::= ANum 3\n       ELSE Z ::= ANum 4\n    FI)\n    / empty_state\n    || (update (update empty_state X 2) Z 4).\nProof.\n  apply E_Seq with (update empty_state X 2).\n  apply E_Ass. reflexivity.\n  apply E_IfFalse. reflexivity.\n  apply E_Ass. reflexivity.\nQed.\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 c st st' H.\n  inversion H as [i E].\n  clear H.\n  generalize dependent st'.\n  generalize dependent st.\n  generalize dependent c.\n  induction i as [| i'].\n\n  Case \"i = 0 -- contradictory\".\n  intros c st st' H. inversion H. \n  Case \"i = S i'\".\n  intros c st st' H.\n  com_cases (destruct c) SCase;\n    simpl in H; inversion H; subst; clear H.\n  SCase \"SKIP\". apply E_Skip.\n  SCase \"::=\". apply E_Ass. reflexivity.\n  SCase \";\".\n  remember (ceval_step st c1 i') as r1. destruct r1.\n  SSCase \"Evaluation of r1 terminates normally\".\n  apply E_Seq with s.\n  apply IHi'. rewrite Heqr1. reflexivity.\n  apply IHi'. assumption.\n  SSCase \"Othervise --contradiction\".\n  inversion H1.\n  SCase \"IFB\".\n  remember (beval st b) as r. destruct r.\n  SSCase \"r = true\".\n  apply E_IfTrue. rewrite Heqr. reflexivity.\n  apply IHi'. assumption.\n  SSCase \"r = false\".\n  apply E_IfFalse. rewrite Heqr. reflexivity.\n  apply IHi'. assumption.\n  SCase \"WHILE\". remember (beval st b) as r. destruct r.\n  SSCase \"r = true\".\n  remember (ceval_step st c i') as r1. destruct r1.\n  SSSCase \"r1 = Some s\".\n  apply E_WhileLoop with s. rewrite Heqr. reflexivity.\n  apply IHi'. rewrite Heqr1. reflexivity.\n  apply IHi'. assumption.\n  SSSCase \"r1 = None\".\n  inversion H1.\n  SSCase \"r = false\".\n  inversion H1.\n  apply E_WhileEnd. rewrite Heqr. subst.\n  reflexivity.\nQed.\n\nTheorem ceval_deterministic: forall c st st1 st2,\n                               c / st || st1 ->\n                               c / st || st2 ->\n                               st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  ceval_cases (induction E1) Case; intros st2 E2; inversion E2; subst.\n  Case \"E_SKip\". reflexivity.\n  Case \"E_Ass\". reflexivity.\n  Case \"E_Seq\". assert (st' = st'0) as EQ1.\n  SCase \"Proof of assertion\". apply IHE1_1; assumption.\n  subst st'0. apply IHE1_2. assumption.\n  Case \"E_IfTrue\".\n  SCase \"b1 evaluates to true\".\n  apply IHE1. assumption.\n  SCase \"b1 evaluates to false (contradiction)\".\n  rewrite H in H5. inversion H5.\n  Case \"E_IfFalse\".\n  SCase \"b1 evaluates to true (contradiction)\".\n  rewrite H in H5. inversion H5.\n  SCase \"b1 evaluates to false\".\n  apply IHE1. assumption.\n  Case \"E_WhileEnd\".\n  SCase \"b1 evaluates to true\".\n  reflexivity.\n  SCase \"b1 evaluates to false (contradiction)\".\n  rewrite H in H2. inversion H2.\n  Case \"E_WhileLoop\".\n  SCase \"b1 evaluates to true (contradiction)\".\n  rewrite H4 in H. inversion H.\n  SCase \"b1 evaluates to false\".\n  assert (st' = st'0) as EQ1.\n  SSCase \"Proof of assertion\". apply IHE1_1; assumption.\n  subst st'0. apply IHE1_2. assumption.\nQed.\n\nTheorem plus2_spec: forall st n st',\n                      st X = n ->\n                      plus2 / st || st' ->\n                      st' X = n + 2.\nProof.\n  intros st n st' HX Heval.\n  inversion Heval. subst.\n  apply update_eq.\nQed.\n\nTheorem loop_never_stops: forall st st',\n                            ~(loop / st || st').\nProof.\n  intros st st' contra. unfold loop in contra.\n  remember (WHILE BTrue DO SKIP END) as loopdef.\n  rewrite Heqloopdef in contra. inversion contra.\n  subst. inversion H3.\n  subst. inversion H2. subst.\nAdmitted.\n\nFixpoint no_whiles (c: com): bool :=\n  match c with\n    | SKIP => true\n    | _ ::= _ => true\n    | c1 ; c2 => andb (no_whiles c1) (no_whiles c2)\n    | IFB _ THEN ct ELSE cf FI => andb (no_whiles ct) (no_whiles cf)\n    | WHILE _ DO _ END => false\n  end.\nTheorem no_whiles_termnating: forall com st,\n                                no_whiles com = true ->  exists st', com / st || st'.\nProof.\n  intros com st H.\n  generalize dependent st.\n  induction com; intros st.\n  + exists st. apply E_Skip.\n  + exists (update st i (aeval st a)).\n    apply E_Ass. reflexivity.\n  + inversion H. remember (no_whiles com1) as r.\n    destruct r. simpl in H1. rewrite H1 in IHcom2.\n    destruct IHcom1 with st. reflexivity.\n    destruct IHcom2 with x. reflexivity.\n    exists x0.\n    apply E_Seq with x.\n    assumption. assumption. inversion H1.\n  + destruct b.\n    destruct IHcom1 with st. inversion H.\n    rewrite H1. unfold andb in H1. remember (no_whiles com1) as r.\n    destruct r. reflexivity. inversion H1.\n    exists x. apply E_IfTrue. reflexivity. assumption.\n    destruct IHcom2 with st. inversion H.\n    rewrite H1. unfold andb in H1. remember (no_whiles com1) as r.\n    destruct r. assumption. inversion H1.\n    exists x. apply E_IfFalse. reflexivity. assumption.\n    remember (BEq a a0). destruct b.\nAdmitted.\n\nPrint fact_body.\nPrint fact_loop.\nPrint fact_com.\n\nFixpoint real_fact (n: nat): nat :=\n  match n with\n    | O => 1\n    | S n' => n * (real_fact n')\n  end.\n\nDefinition fact_invariant (x: nat) (st: state) :=\n  (st Y) * (real_fact (st Z)) = real_fact x.\n\nTheorem fact_body_preserves_invariant: forall st st' x,\n                                         fact_invariant x st ->\n                                         st Z <> 0 ->\n                                         fact_body / st || st' ->\n                                         fact_invariant x st'.\nProof.\n  unfold fact_invariant, fact_body.\n  intros st st' x Hm HZnz He.\n  inversion He; subst; clear He.\n  inversion H1; subst; clear H1.\n  inversion H4; subst; clear H4.\n  unfold update. simpl.\n  destruct (st Z) as [| z'].\n  apply ex_falso_quodlibet. apply HZnz. reflexivity.\n  rewrite <- Hm. rewrite <- mult_assoc.\n  replace (S z' - 1) with z' by omega.\n  reflexivity.\nQed.\n\nTheorem fact_loop_preserves_invariant: forall st st' x,\n                                         fact_invariant x st ->\n                                         fact_loop / st || st' ->\n                                         fact_invariant x st'.\nProof.\n  intros st st' x H Hce.\n  remember fact_loop as c.\n  ceval_cases (induction Hce) Case;\n    inversion Heqc; subst; clear Heqc.\n  Case \"E_WhileEnd\".\n  assumption.\n  Case \"E_WhileLoop\".\n  apply IHHce2.\n  apply fact_body_preserves_invariant with st;\n    try assumption.\n  intros contra. simpl in H0; subst.\n  rewrite contra in H0. inversion H0.\n  reflexivity.\nQed.\n\nTheorem guard_false_after_loop: forall b c st st',\n                                  (WHILE b DO c END) / st || st' ->\n                                  beval st' b = false.\nProof.\n  intros b c st st' Hce.\n  remember (WHILE b DO c END) as cloop.\n  ceval_cases(induction Hce) Case;\n    inversion Heqcloop; subst; clear Heqcloop.\n  Case \"E_WhileEnd\".\n  assumption.\n  Case \"E_WhileLoop\".\n  apply IHHce2. reflexivity.\nQed.\n\nTheorem fact_com_correct: forall st st' x,\n                            st X = x ->\n                            fact_com / st || st' ->\n                            st' Y = real_fact x.\nProof.\n  intros st st' x HX Hce.\n  inversion Hce; subst; clear Hce.\n  inversion H1; subst; clear H1.\n  inversion H4; subst; clear H4.\n  inversion H1; subst; clear H1.\n  rename st' into st''. simpl in H5.\n  remember (update (update st Z (st X)) Y 1) as st'.\n  assert (fact_invariant (st X) st').\n  subst. unfold fact_invariant, update. simpl. omega.\n  assert (fact_invariant (st X) st'').\n  apply fact_loop_preserves_invariant with st'; assumption.\n  unfold fact_invariant in H0.\n  apply guard_false_after_loop in H5. simpl in H5.\n  destruct (st'' Z).\n  Case \"st'' Z = 0\". simpl in H0. omega.\n  Case \"st'' Z > 0 (impossible)\". inversion H5.\nQed.\n\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/imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7878430552931487}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nImport Coq.Lists.List.ListNotations.\n\nRequire Import BWT.Sorting.Ord.\nRequire Import BWT.Sorting.Sorted.\nRequire Import BWT.Sorting.StablePerm.\nRequire Import BWT.Sorting.Sort.\nRequire Import BWT.Lib.Sumbool.\nRequire Import BWT.Lib.Permutation.\n\nSection InsertionSort.\n  Context {A : Type} {O : Preord A}.\n\n  Fixpoint insert (x : A) (l : list A) :=\n    match l with\n    | [] => [x]\n    | h :: t =>\n      if le_dec x h then x :: h :: t else h :: insert x t\n    end.\n\n  Fixpoint sort (l : list A) : list A :=\n    match l with\n    | [] => []\n    | h :: t => insert h (sort t)\n    end.\n\n  Remark sort_fold_right : forall l,\n      sort l = fold_right insert [] l.\n  Proof. reflexivity. Qed.\n\n  Lemma insert_perm: forall x l,\n      Permutation (x :: l) (insert x l).\n  Proof.\n    intros; revert x; induction l as [|h t IH]; intros x;\n      [reflexivity|].\n    cbn. destruct (le_dec x h); [reflexivity|].\n    rewrite perm_swap.\n    apply Permutation_cons; [easy|apply IH].\n  Qed.\n\n  Theorem sort_perm: forall l, Permutation l (sort l).\n  Proof.\n    induction l as [|h t IH]; [reflexivity|].\n    cbn.\n    transitivity (h :: sort t); [apply perm_skip; easy|].\n    apply insert_perm.\n  Qed.\n\n  Lemma insert_forall_le : forall x l,\n      Forall (le x) l -> insert x l = x :: l.\n  Proof.\n    intros x l HF.\n    destruct l as [|h t]; [easy|].\n    cbn. rewrite if_true by (eapply Forall_inv; apply HF).\n    reflexivity.\n  Qed.\n\n  Lemma insert_sorted: forall x l,\n      Sorted l -> Sorted (insert x l).\n  Proof.\n    intros x l Sl; revert x.\n    induction Sl as [|h t HF HS IH]; intros x; [apply Sorted_1|].\n    cbn; destruct (le_dec x h).\n    - revert IH; setoid_rewrite SortedLocal_iff; intros IH.\n      apply SortedLocal_cons; [|easy].\n      rewrite <- insert_forall_le by easy.\n      apply IH.\n    - apply Sorted_cons; [|easy].\n      apply Permutation_forall with (l := x :: t);\n        [apply insert_perm|].\n      constructor; [apply lt_le; easy|easy].\n  Qed.\n\n  Theorem sort_sorted: forall l, Sorted (sort l).\n  Proof.\n    induction l as [|h t IH]; [apply Sorted_nil|].\n    cbn. apply insert_sorted. apply IH.\n  Qed.\n\n  Lemma insert_stable : forall x l,\n      @StablePerm A eqv _ _ (x :: l) (insert x l).\n  Proof.\n    induction l as [|h t]; [apply StablePerm_skip; reflexivity|].\n    cbn. destruct (le_dec x h); [reflexivity|].\n    transitivity (h :: x :: t).\n    apply StablePerm_swap.\n    intros []; contradiction.\n    apply StablePerm_skip. easy.\n  Qed.\n\n  Theorem sort_stable : forall l, @StablePerm A eqv _ _ l (sort l).\n  Proof.\n    induction l; [reflexivity|].\n    cbn. transitivity (a :: sort l).\n    apply StablePerm_skip. apply IHl.\n    apply insert_stable.\n  Qed.\n\n  Theorem sort_StableSort : StableSort sort.\n  Proof. split; [apply sort_sorted|symmetry; apply sort_stable]. Qed.\n\n  Lemma Sorted_insert_cons : forall h t,\n      Sorted (h :: t) -> insert h t = h :: t.\n  Proof.\n    intros h [|x t] HS; [easy|].\n    cbn.\n    rewrite if_true; [easy|].\n    apply Sorted_cons_inv in HS.\n    apply Forall_inv with (l := t).\n    apply HS.\n  Qed.\n\n  Lemma Sorted_sort_cons : forall t h,\n      Sorted (h :: t) -> sort (h :: t) = h :: t.\n  Proof.\n    induction t as [|x t IH]; intros h HS; [easy|].\n    replace (sort (h :: x :: t)) with (insert h (sort (x :: t))) by easy.\n    rewrite IH by (eapply Sorted_cons_inv; apply HS).\n    apply Sorted_insert_cons; easy.\n  Qed.\n\n  Theorem insert_app : forall x l1 l2,\n      insert x (l1 ++ l2) = insert x l1 ++ l2 \\/ insert x (l1 ++ l2) = l1 ++ insert x l2.\n  Proof.\n    intros x; induction l1; intros l2.\n    right; easy.\n    cbn. destruct (le_dec x a).\n    left; easy.\n    cbn.\n    destruct (IHl1 l2).\n    left; f_equal; easy.\n    right; f_equal; easy.\n  Qed.\n\n  Theorem insert_destr : forall x l,\n      Sorted l ->\n      exists l1 l2,\n        insert x l = l1 ++ x :: l2 /\\\n        l = l1 ++ l2 /\\\n        Forall (gt x) l1 /\\\n        Forall (le x) l2.\n  Proof.\n    induction l; intros HS; [exists [], []; split; [|split]; easy|].\n    destruct IHl as [l1 [l2 [HLI [HL [HL1 Hl2]]]]];\n      [eapply Sorted_cons_inv; apply HS|].\n    cbn.\n    destruct (le_dec x a).\n    - exists [], (a :: l).\n      repeat try split; [constructor|].\n      constructor; [easy|].\n      apply Forall_impl with (P := le a); [|apply Sorted_cons_inv; apply HS].\n      intros y; transitivity a; easy.\n    - rewrite HL.\n      exists (a :: l1), l2.\n      repeat try split.\n      + rewrite <- HL, HLI; easy.\n      + constructor; easy.\n      + easy.\n  Qed.\nEnd InsertionSort.\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/InsertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.7878042043459952}}
{"text": "Require Import Arith List.\nImport ListNotations.\n\nInductive sorted  : list nat -> Prop\n  :=\n  | sorted0 : sorted []\n  | sorted1 (n : nat) : sorted [n]\n  | sorted_n (n0 n1 : nat) (ns : list nat) :\n      n0 <= n1\n      -> sorted (n1 :: ns)\n      -> sorted (n0 :: n1 :: ns).\n\n#[export] Hint Constructors sorted :  sort.\n\nExample sorted_ex : sorted [1; 3; 7].\nProof.\n  auto with sort arith.\nQed.\n\nTheorem sorted_inv (n : nat) (ns : list nat) : sorted (n :: ns) -> sorted ns.\nProof.\n  intros H. inversion H; auto with sort.\nQed.\n\nTheorem sorted_order (n0 n1 : nat) (ns : list nat)\n  : sorted (n0 :: n1 :: ns) -> n0 <= n1.\nProof.\n  intros H. inversion H. assumption.\nQed.\n\nFixpoint nb_occ (m : nat) (ns : list nat) : nat\n  := match ns with\n     | [] => 0\n     | n :: ns' => Nat.b2n (m =? n) + nb_occ m ns'\n     end.\n\nExample nb_occ_ex : nb_occ 3 [1; 3; 2; 3] = 2.\nProof. reflexivity. Qed.\n\nTheorem nb_occ_cons (n m : nat) (ns : list nat)\n  : nb_occ n (m :: ns) = Nat.b2n (n =? m) + nb_occ n ns.\nProof.\n  simpl. case (Nat.eq_dec n m); auto.\nQed.\n\nTheorem nb_occ_cons_same (n : nat) (ns : list nat)\n  : nb_occ n (n :: ns) = S (nb_occ n ns).\nProof.\n  simpl. rewrite Nat.eqb_refl. simpl. ring.\nQed.\n\nTheorem nb_occ_cons_other (n m : nat) (ns : list nat)\n  : n <> m -> nb_occ n (m :: ns) = nb_occ n ns.\nProof.\n  simpl. intros neq. apply Nat.eqb_neq in neq.\n  rewrite neq. reflexivity.\nQed.\n\nDefinition permutation (ns ms : list nat) : Prop\n  := forall n : nat, nb_occ n ns = nb_occ n ms.\n\nTheorem permutation_is_sym (ns ms : list nat)\n  : permutation ns ms -> permutation ms ns.\nProof.\n  unfold permutation. intros H n. auto.\nQed.\n\nTheorem permutation_is_refl (ns : list nat) : permutation ns ns.\nProof. easy. Qed.\n\nTheorem permutation_is_trans (ns ms ks : list nat)\n  : permutation ns ms -> permutation ms ks -> permutation ns ks.\nProof.\n  unfold permutation. intros Hnm Hmk n.\n  now rewrite Hnm.\nQed.\n\nTheorem permutation_cons (k : nat) (ns ms : list nat)\n  : permutation ns ms -> permutation (k :: ns) (k :: ms).\nProof.\n  unfold permutation. intros H n.\n  repeat rewrite nb_occ_cons.\n  now rewrite H.\nQed.\n\nTheorem permutation_perm (k1 k2 : nat) (ns ms : list nat)\n  : permutation ns ms -> permutation (k1 :: k2 :: ns) (k2 :: k1 :: ms).\nProof.\n  unfold permutation. intros H n.\n  repeat rewrite nb_occ_cons. rewrite H.\n  ring.\nQed.\n\n#[export] Hint Resolve permutation_cons permutation_is_refl permutation_perm : sort.\n\nFixpoint insert (m : nat) (ns : list nat)\n  := match ns with\n     | [] => [m]\n     | n :: ns' => if m <=? n then m :: ns\n                   else n :: (insert m ns')\n     end.\n\nTheorem insert_sorted (m : nat) (ns : list nat)\n  : sorted ns -> sorted (insert m ns).\nProof.\n  induction ns as [| n1 ns1 IH]; intros H.\n  - (*[ ns = [] ]*) simpl. constructor.\n  - (*[ ns = n1 :: ns1 ]*)\n    simpl. destruct (m <=? n1) eqn:neq.\n    + (*[ m <= n1 ]*) apply sorted_n.\n      { apply Nat.leb_le, neq. }\n      assumption.\n    + (*[ m > n1 ]*)\n      apply Nat.leb_gt in neq as neq'.\n      apply sorted_inv in H as H1.\n      apply IH in H1 as H2.\n      remember (insert m ns1) as ms eqn:eq_ms.\n      destruct ms as [| m1 ms1].\n      * (*[ ms = [] ]*) constructor. \n      * (*[ ms = m1 :: ms1 ]*)\n        apply sorted_n; try assumption.\n        { (* proof that [n1 <= m1] *)\n          destruct ns1 as [| n2 ns2].\n          - (*[ ns1 = [] ]*) simpl in eq_ms.\n            inversion eq_ms. apply Nat.lt_le_incl. assumption.\n          - (*[ ns1 = n2 :: ns2 ]*)\n            simpl in eq_ms.\n            destruct (m <=? n2) eqn:neq1.\n            + (*[ m <= n2 ]*) inversion eq_ms.\n              apply Nat.lt_le_incl. assumption.\n            + (*[ m > n2 ]*) inversion eq_ms.\n              apply sorted_order in H. assumption.\n        }\nQed.\n\nTheorem insert_ob_occ (n m : nat) (ks : list nat)\n  : nb_occ m (insert n ks) = Nat.b2n (m =? n) + nb_occ m ks.\nProof.\n  induction ks as [| k ks' IH].\n  - (* ks = [] *) reflexivity.\n  - (* ks = k :: ks' *) simpl.\n    destruct (n <=? k) eqn:neq.\n    + (* n <= k *) repeat rewrite nb_occ_cons. reflexivity.\n    + (* n > k *) rewrite nb_occ_cons, IH. ring.\nQed.\n\nTheorem insert_is_permutaion (k : nat) (ns ms : list nat)\n  : permutation ns ms -> permutation (k :: ns) (insert k ms).\nProof.\n  unfold permutation. intros H n.\n  rewrite nb_occ_cons, insert_ob_occ, (H n).\n  reflexivity.\nQed.\n\n(* modified theorem from book *)\nLemma insert_permutation : forall (ns : list nat) (m : nat),\n    permutation (m :: ns) (insert m ns).\nProof.\n  induction ns as [| n ns' IH]; simpl; auto with sort.\n  intros m.\n  destruct (m <=? n) eqn:neq;\n    try apply permutation_is_trans with (n :: m :: ns');\n    auto with sort.\nQed.\n\nFixpoint insertion_sort (ns : list nat)\n  := match ns with\n     | [] => []\n     | n :: ns' => insert n (insertion_sort ns')\n     end.\n\nExample insertion_sort_ex : insertion_sort [4; 2; 3; 1; 3] = [1; 2; 3; 3; 4].\nProof. reflexivity. Qed.\n\nTheorem insertion_sort_sorts (ns : list nat) : sorted (insertion_sort ns).\nProof.\n  induction ns as [| n ns' IH].\n  - (*[ ns = [] ]*) simpl. constructor.\n  - (*[ ns = n :: ns' ]*)\n    simpl. apply insert_sorted, IH.\nQed.\n\nTheorem insertion_sort_save_elements (ns : list nat)\n  : permutation ns (insertion_sort ns).\nProof.\n  induction ns as [| n ns' IH].\n  - (*[ ns = [] ]*) simpl. apply permutation_is_refl.\n  - (*[ ns = n :: ns' ]*)\n    simpl. apply insert_is_permutaion, IH.\nQed.\n\nDefinition nat_sort : (list nat -> list nat) -> Prop\n  := fun fn => forall ns : list nat,\n         sorted (fn ns) /\\ permutation ns (fn ns).\n\nTheorem insertion_sort_is_nat_sort : nat_sort insertion_sort.\nProof.\n  intros ns. split.\n  - apply insertion_sort_sorts.\n  - apply insertion_sort_save_elements.\nQed.\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/ch01/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.7877897365708731}}
{"text": "Require Export TopologicalSpaces.\nRequire Export OpenBases.\nRequire Export FiniteTypes.\nRequire 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\nImplicit Arguments subbasis [[X]].\n\nSection build_from_subbasis.\n\nVariable X:Type.\nVariable S:Family X.\n\nRequire 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": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Subbases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7877897365708729}}
{"text": "Require Import Bool Arith List.\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\n\n\n(* 2.1 - Arithmetic Expressions Over Natural Numbers *)\n\n(* Source Language *)\nInductive binop : Set :=\n| Plus\n| 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\nExample exp_1 : expDenote (Const 42) = 42.\nProof. reflexivity. Qed.\n\nExample exp_2 : expDenote (Binop Plus (Const 2) (Const 2)) = 4.\nProof. reflexivity. Qed.\n\nExample exp_3 :\n  expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)) = 28.\nProof. reflexivity. Qed.\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\n(* An instruction either pushes a constant onto the stack or pops two\n   arguments, applies a binary operator to them, and then pushes the\n   result onto the stack.\n*)\n\n(* Give instructions meanings as functions from stacks to optional\n   stacks to handle stack underflows.\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\n(* Function which iterates application of instrDenote through a whole\n   program.\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\n(* Translation *)\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\nExample compile_1 :\n  compile (Const 42) = iConst 42 :: nil.\nProof. reflexivity. Qed.\n\nExample compile_2 :\n  compile (Binop Plus (Const 2) (Const 2))\n  = iConst 2 :: iConst 2 :: iBinop Plus :: nil.\nProof. reflexivity. Qed.\n\nExample compile_3 :\n  compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))\n  = iConst 7 :: iConst 2 :: iConst 2 :: iBinop Plus :: iBinop Times :: nil.\nProof. reflexivity. Qed.\n\nExample progDenote_1 :\n  progDenote (compile (Const 42)) nil = Some (42 :: nil).\nProof. reflexivity. Qed.\n\nExample progDenote_2 :\n  progDenote (\n    compile (Binop Plus (Const 2) (Const 2)))\n    nil = Some (4 :: nil).\nProof. reflexivity. Qed.\n\nExample progDenote_3 :\n  progDenote (\n    compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)))\n    nil = Some (28 :: nil).\nProof. reflexivity. Qed.\n\n(* Translation Correctness *)\nTheorem compile_correct :\n  forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  (* Prove auxiliary lemma that strengthens the induction hypothesis on e *)\nAbort.\n\n(* Manual proof *)\nLemma compile_correct'' :\n  forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e as [n | b e1 IHe1 e2 IHe2].\n  - (* e = Const n *)\n    simpl; intros; reflexivity.\n  - (* e = Binop b e1 e2 *)\n    intros.\n    unfold compile.\n    fold compile.\n    unfold expDenote.\n    fold expDenote.\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\n(* Automated proof *)\nLemma compile_correct' :\n  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 :\n  forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  intros;\n  rewrite (app_nil_end (compile e));\n  rewrite compile_correct';\n  reflexivity.\nQed.\n\n\n(* 2.2 - Typed Expressions *)\n\n(* Source Language *)\n\n(* Trivial language of types to classify expressions *)\nInductive type : Set :=\n| Nat\n| Bool.\n\n(* Expanded set of binary operators *)\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\n(* Type family for typed expressions *)\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(* Map types of our 'object' language into Coq types *)\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", "meta": {"author": "vishallama", "repo": "cpdt", "sha": "5ee71a2fbd2ffbf43780e49d0d842505c9dbe7dc", "save_path": "github-repos/coq/vishallama-cpdt", "path": "github-repos/coq/vishallama-cpdt/cpdt-5ee71a2fbd2ffbf43780e49d0d842505c9dbe7dc/src/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8774767970940974, "lm_q1q2_score": 0.7877067848814981}}
{"text": "Require Import PeanoNat.\n\n(* Strong induction on Natural numbers with properties sending to Type. *)\n\nTheorem strong_induction:\nforall P : nat -> Prop,\n(forall n : nat, (forall k : nat, (k < n -> P k)) -> P n) ->\nforall n : nat, P n.\nProof.\nintros P H. assert (Lem : forall n, (forall m, m <= n -> P m)).\n{ induction n. intros.\n  - assert (E: m = 0). inversion H0.  reflexivity. rewrite E. apply H.\n    intros. exfalso. inversion H1.\n  - intros. apply H. intros. apply IHn. inversion H0.\n    * rewrite H2 in H1. apply Nat.lt_succ_r. apply H1.\n    * assert (E: k <= m). apply Nat.lt_le_incl. apply H1. \n      apply Nat.le_trans with (m:=m). apply E. apply H3. }\nintro n. apply H. intros. apply Lem with (n:=n) (m:=k).\napply Nat.lt_le_incl. apply H0.\nQed.\n", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/Toolbox_ModLog/Completeness/wKL/K_strong_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191271831558, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7876242499620142}}
{"text": "(** \n_AUTHOR_\n\n<<\nZhi Zhang\nDepartment of Computer and Information Sciences\nKansas State University\nzhangzhi@ksu.edu\n>>\n*)\n\nRequire Export Coq.ZArith.Zbool.\nRequire Export Coq.ZArith.BinInt.\nRequire Export Coq.ZArith.Zorder.\nRequire Export Coq.ZArith.Zquot.\nRequire Export Coq.ZArith.Zdiv.\nRequire Export Coq.ZArith.Zcompare.\nRequire Export values.\n\n(*\nCoq.ZArith.Zorder: \n     http://coq.inria.fr/V8.1/stdlib/Coq.ZArith.Zorder.html#Zle_ge\n     http://coq.inria.fr/V8.1/stdlib/Coq.ZArith.Zbool.html\n     http://coq.inria.fr/V8.1/stdlib/Coq.ZArith.Zbool.html#Zle_bool\n\n     https://coq.inria.fr/library/Coq.Numbers.NatInt.NZOrder.html\n     http://flint.cs.yale.edu/cs428/coq/library/Coq.ZArith.Zorder.html\n     https://coq.inria.fr/V8.1/stdlib/Coq.ZArith.Zorder.html\n     https://coq.inria.fr/V8.1/stdlib/Coq.ZArith.BinInt.html\n\n     Logic: https://coq.inria.fr/library/Coq.Init.Logic.html\n\n\n** MinMax **\n\n   https://coq.inria.fr/library/Coq.Structures.GenericMinMax.html\n   - lemmas about min and max\n   \n   https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n   - Lemma max_l n m : m<=n -> max n m = n.\n   - Lemma max_r n m : n<=m -> max n m = m.\n   - Lemma min_l n m : n<=m -> min n m = n.\n   - Lemma min_r n m : m<=n -> min n m = m.\n\n** abs (absolute value) **\n\n   https://coq.inria.fr/library/Coq.ZArith.BinInt.html#Z.abs\n   - Lemma abs_eq n : 0 <= n -> abs n = n.\n   - Lemma abs_neq n : n <= 0 -> abs n = - n.\n\n** Multiply **\n \n    https://coq.inria.fr/library/Coq.ZArith.Zorder.html\n    https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n    - Compatibility of multiplication, such as: Lemma Zmult_gt_0_lt_compat_r: p > 0 -> n < m -> n * p < m * p.\n\n** Modulus **\n\n    https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n    - Lemma mod_pos_bound a b : 0 < b -> 0 <= a mod b < b.\n    - Lemma mod_neg_bound a b : b < 0 -> b < a mod b <= 0.\n\n** Zquot (÷) / Divide (/) **\n  \n    https://coq.inria.fr/library/Coq.ZArith.Zquot.html\n    https://coq.inria.fr/library/Coq.ZArith.Zdiv.html\n\n    - Theorem Zquot_Zdiv_pos : forall a b, 0 <= a -> 0 <= b -> a÷b = a/b.\n   \n  \n** neg/pos/opp(e.g. -x) **\n\n    https://coq.inria.fr/library/Coq.ZArith.Zorder.html\n    https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n\n    - Lemma Zle_neg_pos : forall p q:positive, Zneg p <= Zpos q.\n    - Lemma Zgt_pos_0 : forall p:positive, Zpos p > 0.\n    - Lemma Zle_0_pos : forall p:positive, 0 <= Zpos p.\n    - Lemma Zlt_neg_0 : forall p:positive, Zneg p < 0.\n\n** Zlt/Zgt/Zle/Zge **\n   \n    https://coq.inria.fr/library/Coq.ZArith.Zorder.html\n    https://coq.inria.fr/library/Coq.ZArith.Zbool.html\n    https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n    \n\nTheorem le_lt_trans : forall n m p, n <= m -> m < p -> n < p.\n\nTheorem lt_le_trans : forall n m p, n < m -> m <= p -> n < p.\n\nTheorem le_antisymm : forall n m, n <= m -> m <= n -> n == m.\n\nMore properties of < and <= with respect to S and 0.\n\nTheorem le_succ_r : forall n m, n <= S m <-> n <= m \\/ n == S m.\n\nTheorem lt_succ_l : forall n m, S n < m -> n < m.\n\nTheorem le_le_succ_r : forall n m, n <= m -> n <= S m.\n\nTheorem lt_lt_succ_r : forall n m, n < m -> n < S m.\n\nTheorem succ_lt_mono : forall n m, n < m <-> S n < S m.\n\nTheorem succ_le_mono : forall n m, n <= m <-> S n <= S m.\n\nLemma gt_lt_iff n m : n > m <-> m < n.\n\nhttps://coq.inria.fr/library/Coq.ZArith.BinInt.html\nhttps://coq.inria.fr/V8.1/stdlib/Coq.ZArith.BinInt.html\n - Lemma gt_lt n m : n > m -> m < n.\n - Lemma lt_gt n m : n < m -> m > n.\n - Lemma ge_le_iff n m : n >= m <-> m <= n.\n - Lemma ge_le n m : n >= m -> m <= n.\n - Lemma le_ge n m : n <= m -> m >= n.\n\nhttps://coq.inria.fr/library/Coq.Numbers.NatInt.NZOrder.html\n - Theorem le_succ_r : forall n m, n <= S m <-> n <= m \\/ n == S m.\n - Theorem lt_succ_l : forall n m, S n < m -> n < m.\n - Theorem le_le_succ_r : forall n m, n <= m -> n <= S m.\n - Theorem lt_lt_succ_r : forall n m, n < m -> n < S m.\n - Theorem succ_lt_mono : forall n m, n < m <-> S n < S m.\n - Theorem succ_le_mono : forall n m, n <= m <-> S n <= S m.\n - Theorem le_succ_l : forall n m, S n <= m <-> n < m.\n\n lemma Z_eq_mult : forall n m : Z, m = 0%Z -> (m * n)%Z = 0%Z\n\n Lemma Zlt_neg_0 : forall p : positive, (Z.neg p < 0)%Z\n\napply them with: \n  Z.le_succ_r\n  Z.le_le_succ_r\n*)\n\n\n(** * ZArith (Mult, Div, Mod) *)\n\nFunction min_abs_f (u : Z) (v: Z) : Z :=\n  Z.min (Z.abs u) (Z.abs v).\n\nFunction max_abs_f (u : Z) (v: Z) : Z :=\n  Z.max (Z.abs u) (Z.abs v).\n\n(** ** Mult *)\n\n(** e1: [u, v], e2: [u', v'], e1 * e2: min(u*u', u*v', v*u', v*v') *)\nFunction multiply_min_f (u : Z) (v: Z) (u' : Z) (v': Z) : Z :=\n  Z.min (Z.min (u * u') (u * v')) (Z.min (v * u') (v * v')).\n  \n(** max(u*u', u*v', v*u', v*v') *)\nFunction multiply_max_f (u : Z) (v: Z) (u' : Z) (v': Z) : Z :=\n  Z.max (Z.max (u * u') (u * v')) (Z.max (v * u') (v * v')).\n\n(** ** Div *)\n\n(** e1: [u, v], e2: [u', v'], e1/e2: min, max *)\nFunction divide_min_max_f (u : Z) (v: Z) (u' : Z) (v': Z) : Z * Z :=\n  if Zle_bool v' (-1) then\n    (* case 1: v' < 0 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      ((Z.quot v u'), (Z.quot u v'))\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      ((Z.quot v v'), (Z.quot u u'))\n    else\n      (* subcase 3 *)\n      ((Z.quot v v'), (Z.quot u v'))\n  else if Zle_bool 1 u' then\n    (* case 2: u' > 0 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      ((Z.quot u u'), (Z.quot v v'))\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      ((Z.quot u v'), (Z.quot v u'))\n    else\n      (* subcase 3 *)\n      ((Z.quot u u'), (Z.quot v u'))\n  else\n    (* case 3 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      (u, (Z.abs u))\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      (Z.opp v, v)\n    else\n      (* subcase 3 *)\n      (Z.opp (max_abs_f u v), (max_abs_f u v)).\n\n(*\nFunction divide_min_max_f (u : Z) (v: Z) (u' : Z) (v': Z) : Z * Z :=\n  if Zle_bool v' (-1) then\n    (* case 1: v' < 0 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      ((Z.quot v u'), min_f (Z.quot u v') max_signed)\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      ((Z.quot v v'), (Z.quot u u'))\n    else\n      (* subcase 3 *)\n      ((Z.quot v v'), min_f (Z.quot u v') max_signed)\n  else if Zle_bool 1 u' then\n    (* case 2: u' > 0 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      ((Z.quot u u'), (Z.quot v v'))\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      ((Z.quot u v'), (Z.quot v u'))\n    else\n      (* subcase 3 *)\n      ((Z.quot u u'), (Z.quot v u'))\n  else\n    (* case 3 *)\n    if Zle_bool v (-1) then\n      (* subcase 1: v < 0 *)\n      (u, min_f (Z.abs u) max_signed)\n    else if Zle_bool 1 u then\n      (* subcase 2: u > 0 *)\n      (Z.opp v, v)\n    else\n      (* subcase 3 *)\n      (Z.opp (max_abs_f u v), min_f (max_abs_f u v) max_signed).\n*)\n\n(** ** Mod *)\n\n(** e1: [u, v], e2: [u', v'], e1 mod e2: min, max \n    e.g. x mod 9, then its result range is: [0..8]\n*)\nFunction modulus_min_max_f (u : Z) (v: Z) (u' : Z) (v': Z) : Z * Z :=\n  if Zle_bool v' (-1) then\n    (* case 1: v' < 0 *)\n    ((u'+1)%Z, 0%Z)\n  else if Zle_bool 1 u' then\n    (* subcase 2: u' > 0 *)\n    (0%Z, (v'-1)%Z)\n  else\n    (if Zeq_bool u' 0 then 0 else (u'+1), if Zeq_bool v' 0 then 0 else (v'-1))%Z.\n\n(** * Relation (Zeq, Zlt, Zle, Zgt, Zge) *)\n\n(** ** Relation between Zlt and Zlt_bool *)\n\n(** the following three lemmas are from Coq.ZArith.BinInt *)\nLemma Zeqb_eq: forall n m : Z, \n  (n =? m)%Z = true <-> n = m.\nProof. \n  apply Z.eqb_eq; auto. \nQed.\n\nLemma Zltb_lt: forall n m : Z, \n  (n <? m)%Z = true <-> (n < m)%Z.\nProof.\n  intros; apply Z.ltb_lt; auto.\nQed.\n\nLemma Zleb_le: forall n m : Z, \n  (n <=? m)%Z = true <-> (n <= m)%Z.\nProof.\n  intros; apply Z.leb_le; auto.\nQed.\n\nLemma Lt_Le_Bool_False: forall u v,\n  (u < v)%Z ->\n    Zle_bool v u = false.\nProof.\n  intros.\n  specialize (Zltb_lt u v); intro HZ.\n  destruct HZ as [HZa HZb].\n  specialize (HZb H).\n  unfold Zlt_bool in HZb; unfold Zle_bool.\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto. \nQed.\n\nLemma Le_False_Lt: forall u v,\n  (Zle_bool v u) = false ->\n    (u < v)%Z.\nProof.\n  intros.\n  remember (Zle_bool v u) as b1.\n  symmetry in Heqb1.\n  destruct b1; inversion H.\n  specialize (Zle_cases v u); intros HZ.\n  rewrite Heqb1 in HZ; smack.\nQed.\n\nLemma Lte_Lt_Bool_False: forall u v,\n  (u <= v)%Z ->\n    Zlt_bool v u = false.\nProof.\n  intros.\n  specialize (Zleb_le u v); intro HZ.\n  destruct HZ as [HZa HZb].\n  specialize (HZb H).\n  unfold Zle_bool in HZb; unfold Zlt_bool.\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto.\nQed.\n\nLemma Lt_False_Le: forall u v,\n  (Zlt_bool v u) = false ->\n    (u <= v)%Z.\nProof.\n  intros;\n  apply Zleb_le; auto;\n  unfold Zle_bool; unfold Zlt_bool in H;\n  rewrite <- Zcompare_antisym;\n  destruct (v ?= u)%Z; auto.  \nQed.\n\n\nLemma Zgele_Bool_Imp_GeLe_T: forall v l u,\n  (Zge_bool v l) && (Zle_bool v u) = true ->\n    (l <= v)%Z /\\ (v <= u)%Z.\nProof.\n  intros.\n  specialize (andb_prop _ _ H); clear H; intros HZ.\n  destruct HZ as [HZ1 HZ2].\n  split.\n- specialize (Zge_cases v l); intros HZ.\n  rewrite HZ1 in HZ; smack.\n- apply Zle_bool_imp_le; auto.  \nQed.\n\nLemma Zgele_Bool_Imp_GeLe_F: forall v l u,\n  (Zge_bool v l) && (Zle_bool v u) = false ->\n    (v < l)%Z \\/ (u < v)%Z.\nProof.\n  intros.\n  unfold andb in H.\n  remember (Zge_bool v l) as b1; \n  remember (Zle_bool v u) as b2.\n  symmetry in Heqb1, Heqb2.\n  destruct b1, b2; inversion H.\n- specialize (Zle_cases v u); intros HZ;\n  rewrite Heqb2 in HZ; smack.\n- specialize (Zge_cases v l); intros HZ;\n  rewrite Heqb1 in HZ; smack.\n- specialize (Zge_cases v l); intros HZ;\n  rewrite Heqb1 in HZ; smack.  \nQed.\n\nLemma Zlele_Bool_Imp_LeLe_T: forall v l u,\n  (Zle_bool l v) && (Zle_bool v u) = true ->\n    (l <= v)%Z /\\ (v <= u)%Z.\nProof.\n  intros.\n  specialize (andb_prop _ _ H); clear H; intros HZ.\n  destruct HZ as [HZ1 HZ2].\n  split.\n- specialize (Zle_cases l v); intros HZ.\n  rewrite HZ1 in HZ; smack.\n- apply Zle_bool_imp_le; auto.  \nQed.\n\nLemma Zlele_Bool_Imp_LeLe_F: forall v l u,\n  (Zle_bool l v) && (Zle_bool v u) = false ->\n    (v < l)%Z \\/ (u < v)%Z.\nProof.\n  intros.\n  unfold andb in H.\n  remember (Zle_bool l v) as b1; \n  remember (Zle_bool v u) as b2.\n  symmetry in Heqb1, Heqb2.\n  destruct b1, b2; inversion H.\n- specialize (Zle_cases v u); intros HZ;\n  rewrite Heqb2 in HZ; smack.\n- specialize (Zle_cases l v); intros HZ;\n  rewrite Heqb1 in HZ; smack.\n- specialize (Zle_cases l v); intros HZ;\n  rewrite Heqb1 in HZ; smack.  \nQed.\n\nLemma Zleb_true_le_true: forall v l u,\n  (Zle_bool l v) && (Zle_bool v u) = true ->\n    ((Zle_bool l v) = true /\\ (Zle_bool v u) = true) /\\ ((l <= v)%Z /\\ (v <= u)%Z).\nProof.\n  intros.\n  remember (Zle_bool l v) as b1.\n  remember (Zle_bool v u) as b2.\n  destruct b1, b2; inversion H; subst;\n  symmetry in Heqb1, Heqb2.\n  smack;\n  apply Zleb_le; auto.\nQed.\n\nLtac apply_Zleb_true_le_true :=\n  match goal with\n  | [H: (Zle_bool ?l ?v) && (Zle_bool ?v ?u) = true |- _] =>\n      specialize (Zleb_true_le_true _ _ _ H); \n      let HZ := fresh \"HZ\" in intro HZ;\n      let HZa := fresh \"HZa\" in\n      let HZb := fresh \"HZb\" in\n      let HZa1 := fresh \"HZa1\" in\n      let HZb1 := fresh \"HZb1\" in\n      destruct HZ as [[HZa HZb] [HZa1 HZb1]];\n      clear H\n  end.\n\nLemma Zle_true_leb_true: forall u v u' v',\n  (u <= v)%Z ->\n    (u' <= v')%Z ->\n      (Zle_bool u v) && (Zle_bool u' v') = true.\nProof.\n  intros.\n  assert(HA1: Zle_bool u v = true).\n    apply Zleb_le; auto.\n  assert(HA2: Zle_bool u' v' = true).\n    apply Zleb_le; auto.\n  rewrite HA1, HA2; auto.\nQed.\n\nLemma leb_lt_false: forall x y,\n  (x <=? y)%Z = true ->\n    (y < x)%Z ->\n      False.\nProof.\n  intros.\n  assert(HA1: ~ (x <= y)%Z).\n    apply Zlt_not_le; auto.\n  assert(HA2: (x <= y)%Z).\n    apply Zleb_le; auto.\n  smack.\nQed.\n\nLtac apply_leb_lt_false :=\n  match goal with\n  | [H1: (?x <=? ?y)%Z = true,\n     H2: (?y < ?x)%Z |- _] => \n      specialize (leb_lt_false _ _ H1 H2); intro; smack\n  end.\n\n(** ** Zlt_bool *)\n\nLemma Zltb_imp_leb: forall u v,\n  (Zlt_bool u v) = true ->\n    (Zle_bool u v) = true.\nProof.\n  intros.\n  assert(H1: v = ((v + 1) - 1)%Z). smack.\n  rewrite H1.\n  apply Zlt_is_le_bool; auto. \n  clear H1.\n  apply Zlt_lt_succ; auto.\n  apply Zltb_lt; auto.\nQed.\n\nLemma Zge_le_bool: forall u v b,\n  Zge_bool u v = b -> Zle_bool v u = b.\nProof.\n  intros;\n  unfold Zle_bool; unfold Zge_bool in H;\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto. \nQed.\n\nLemma Zle_ge_bool: forall u v b,\n  Zle_bool u v = b -> Zge_bool v u = b.\nProof.\n  intros;\n  unfold Zge_bool; unfold Zle_bool in H;\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto. \nQed.\n\nLemma Zgt_lt_bool: forall u v b,\n  Zgt_bool u v = b -> Zlt_bool v u = b.\nProof.\n  intros;\n  unfold Zlt_bool; unfold Zgt_bool in H;\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto. \nQed.\n\nLemma Zlt_gt_bool: forall u v b,\n  Zlt_bool u v = b -> Zgt_bool v u = b.\nProof.\n  intros;\n  unfold Zgt_bool; unfold Zlt_bool in H;\n  rewrite <- Zcompare_antisym;\n  destruct (u ?= v)%Z; auto. \nQed.\n\n(** u < v /\\ v <= w => u <= w *)\nLemma Zltb_leb_trans_leb: forall u v w,\n  (Zlt_bool u v) = true ->\n    (Zle_bool v w) = true ->\n      (Zle_bool u w) = true.\nProof.\n  intros.\n  apply Zltb_imp_leb.\n  apply Zltb_lt.\n  apply Z.lt_le_trans with (m:=v); auto;\n  [ apply Z.ltb_lt; auto |\n    apply Z.leb_le; auto\n  ].\nQed.\n\n(** n < m /\\ m <= p ==> n < p \n    - Theorem lt_le_trans : forall n m p, n < m -> m <= p -> n < p.\n*)\nLemma Zltb_leb_trans_ltb: forall n m p,\n  (Zlt_bool n m) = true ->\n    (Zle_bool m p) = true ->\n      (Zlt_bool n p) = true.\nProof.\n  intros.\n  apply Zltb_lt.\n  apply Z.lt_le_trans with (m:=m);\n  [ apply Z.ltb_lt; auto |\n    apply Z.leb_le; auto\n  ].\nQed.\n\n(** n <= m -> m < p ==> n <= p\n *)\nLemma Zleb_ltb_trans_leb: forall n m p, \n  (Zle_bool n m) = true ->\n    (Zlt_bool m p) = true ->\n      (Zle_bool n p) = true.\nProof.\n  intros.\n  apply Zltb_imp_leb.\n  apply Zltb_lt.\n  apply Z.le_lt_trans with (m:=m);\n  [ apply Z.leb_le; auto |\n    apply Z.ltb_lt; auto\n  ].\nQed.\n\n(** n <= m -> m < p ==> n < p\n    - Theorem le_lt_trans : forall n m p, n <= m -> m < p -> n < p.\n *)\nLemma Zleb_ltb_trans_ltb: forall n m p, \n  (Zle_bool n m) = true ->\n    (Zlt_bool m p) = true ->\n      (Zlt_bool n p) = true.\nProof.\n  intros.\n  apply Zltb_lt.\n  apply Z.le_lt_trans with (m:=m);\n  [ apply Z.leb_le; auto |\n    apply Z.ltb_lt; auto\n  ].\nQed.\n\n(** n < m -> m < p ==> n < p\n    - Theorem lt_trans : forall n m p, n < m -> m < p -> n < p.\n*)\nLemma Zltb_trans : forall n m p,\n  (Zlt_bool n m) = true ->\n    (Zlt_bool m p) = true ->\n      (Zlt_bool n p) = true.\nProof.\n  intros.\n  apply Zltb_lt.\n  apply Z.lt_trans with (m:=m);\n  apply Z.ltb_lt; auto.\nQed.\n\n(** n <= m -> m <= p ==> n <= p\n    - Theorem le_trans : forall n m p, n <= m -> m <= p -> n <= p.\n*)  \nLemma Zleb_trans : forall n m p,\n  (Zle_bool n m) = true ->\n    (Zle_bool m p) = true ->\n      (Zle_bool n p) = true.\nProof.\n  intros.\n  apply Zleb_le.\n  apply Z.le_trans with (m:=m);\n  apply Z.leb_le; auto.\nQed.\n\n(** Lemma lt_succ_r n m : n < succ m <-> n<=m.\n*)\nLemma Zltb_pred_r: forall n m, \n  (n <? m)%Z = true <-> (n <=? Z.pred m)%Z = true.\nProof.\n  intros.\n  assert(HA1: m = Z.succ (Z.pred m)). \n    rewrite Z.succ_pred; auto.\n  rewrite HA1; \n  split; intros.  \n - (*case 1*)\n  assert(HA2: (n < Z.succ (Z.pred m))%Z).\n  apply Zltb_lt; auto.\n  apply Zleb_le.\n  apply Z.lt_succ_r; auto.\n  rewrite Z.succ_pred; auto.\n - (*case 2*)\n  assert(HA2: (n <= Z.pred (Z.succ (Z.pred m)))%Z).\n  apply Zleb_le; auto.\n  rewrite Z.pred_succ in *.\n  specialize (Z.lt_succ_r n (Z.pred m)); intro HZ.\n  destruct HZ as [HZa HZb].\n  specialize (HZb HA2).\n  apply Zltb_lt; auto.\nQed.\n\nLemma Zltb_succ_l: forall n m, \n  (n <? m)%Z = true <-> (Z.succ n <=? m)%Z = true.\nProof.\n  intros.\n  assert(HA: m = Z.succ (Z.pred m)). \n    rewrite Z.succ_pred; auto.\n  rewrite HA.  \n  split; intros.\n - (*case 1*)\n  apply Zleb_le; auto.\n  specialize (Z.succ_le_mono n (Z.pred m)); intro HZ1.\n  destruct HZ1 as [HZ1a HZ1b].\n  apply HZ1a; auto.\n  apply Z.lt_succ_r; auto.\n  apply Zltb_lt; auto.\n - (*case 2*)  \n  apply Zltb_lt; auto.\n  specialize (Z.succ_le_mono n (Z.pred m)); intro HZ1.\n  destruct HZ1 as [HZ1a HZ1b].\n  apply Z.lt_succ_r; auto.\n  apply HZ1b.\n  apply Zleb_le; auto.\nQed.\n\n(** ** Zlt *)\n\nLemma Zlt_le: forall n m, \n  (n < m)%Z -> \n    (n <= m)%Z.\nProof.\n  intros.\n  assert(HA1: (m <= m)%Z). smack.\n  apply Zleb_le; auto.\n  apply Zltb_leb_trans_leb with (v:=m); auto.\n  apply Zltb_lt; auto.  \n  apply Zleb_le; auto.\nQed.\n\n(** \n  - Lemma Zlt_succ_le: forall n m : Z, (n < Z.succ m)%Z -> (n <= m)%Z\n  - Lemma Z.le_succ_l: forall n m : Z, (Z.succ n <= m)%Z <-> (n < m)%Z\n*)\nLemma Zlt_le_succ_l: forall n m, \n  (n < m)%Z -> \n    (Z.succ n <= m)%Z.\nProof.\n  intros.\n  specialize (Z.le_succ_l n m); intro HZ.\n  destruct HZ as [HZa HZb].\n  apply HZb; auto.\nQed.\n\nLemma Zlt_le_pred_r: forall n m, \n  (n < m)%Z -> \n    (n <= Z.pred m)%Z.\nProof.\n  intros.\n  apply Zleb_le; auto.\n  apply Zltb_pred_r; auto.\n  apply Zltb_lt; auto.\nQed.\n\nLemma Zle_eq_e_l: forall u v,\n  Zeq_bool v u = false ->\n    (u <= v)%Z ->\n      (u < v)%Z.\nProof.\n  intros.\n  specialize (Zle_lt_or_eq _ _ H0); intro HZ1.\n  destruct HZ1; smack.\n  specialize (Zeq_bool_neq _ _ H); intro.\n  smack.\nQed.\n\nLemma Zle_eq_e_r: forall u v,\n  Zeq_bool u v = false ->\n    (u <= v)%Z ->\n      (u < v)%Z.\nProof.\n  intros.\n  specialize (Zle_lt_or_eq _ _ H0); intro HZ1.\n  destruct HZ1; smack.\n  specialize (Zeq_bool_neq _ _ H); intro.\n  smack.\nQed.\n\nLemma Zle_n1_0: forall v,\n  (v <= -1)%Z ->\n    (v < 0)%Z /\\ (v <= 0)%Z.\nProof.\n  intros; split.\n  apply Z.le_lt_trans with (m:=(-1)%Z); smack.\n  apply Z.le_trans with (m:=(-1)%Z); smack.\nQed.\n\nLtac apply_Zle_n1_0 :=\n  match goal with\n  | [H: (?v <= -1)%Z |- _] => \n      specialize (Zle_n1_0 _ H); let HZ := fresh \"HZ\" in intro HZ; destruct HZ; clear H\n  end.\n\nLemma Zge_p1_0: forall v,\n  (1 <= v)%Z ->\n    (0 < v)%Z /\\ (0 <= v)%Z.\nProof.\n  intros; \n  smack.\nQed.\n\nLtac apply_Zge_p1_0 :=\n  match goal with\n  | [H: (1 <= ?v)%Z |- _] => \n      specialize (Zge_p1_0 _ H); let HZ := fresh \"HZ\" in intro HZ; destruct HZ; clear H\n  end.\n\n\n(** In run time check semantics, Zge_bool and Zle_bool is used to define overflow check,\n    and in eval_expr_value_in_domain, <= and >= are used, the following lemmas are used\n    to build their relationships;\n*)\nLemma Le_Neg_Ge: forall x y,  \n  (x <= y)%Z ->\n    (-y <= -x)%Z.\nProof.\n  intros.\n  apply Zplus_le_reg_l with (p := y). \n  smack. (*lia*)\nQed.\n\nLemma Lt_Neg_Gt: forall x y,  \n  (x < y)%Z ->\n    (-y < -x)%Z.\nProof.\n  intros.\n  apply Zplus_lt_reg_l with (p := y). \n  smack.\nQed.\n\n\n(** * ZArith Lemma *)\n\n(** ** Min Lemmas *)\n\nLemma le_min_ll: forall a b c d,\n  (Z.min (Z.min a b) (Z.min c d) <= a)%Z.\nProof.\n  intros.\n  assert(HA1: (Z.min (Z.min a b) (Z.min c d) <= (Z.min a b))%Z).\n    apply Z.le_min_l; auto.\n  assert(HA2: ((Z.min a b) <= a)%Z).\n    apply Z.le_min_l; auto.\n  apply Z.le_trans with (m:=Z.min a b); auto.\nQed.\n\nLemma le_min_lr: forall a b c d,\n  (Z.min (Z.min a b) (Z.min c d) <= b)%Z.\nProof.\n  intros.\n  assert(HA1: (Z.min (Z.min a b) (Z.min c d) <= (Z.min a b))%Z).\n    apply Z.le_min_l; auto.\n  assert(HA2: ((Z.min a b) <= b)%Z).\n    apply Z.le_min_r; auto.\n  apply Z.le_trans with (m:=Z.min a b); auto.\nQed.\n\nLemma le_min_rl: forall a b c d,\n  (Z.min (Z.min a b) (Z.min c d) <= c)%Z.\nProof.\n  intros.\n  assert(HA1: (Z.min (Z.min a b) (Z.min c d) <= (Z.min c d))%Z).\n    apply Z.le_min_r; auto.\n  assert(HA2: ((Z.min c d) <= c)%Z).\n    apply Z.le_min_l; auto.\n  apply Z.le_trans with (m:=Z.min c d); auto.\nQed.\n\nLemma le_min_rr: forall a b c d,\n  (Z.min (Z.min a b) (Z.min c d) <= d)%Z.\nProof.\n  intros.\n  assert(HA1: (Z.min (Z.min a b) (Z.min c d) <= (Z.min c d))%Z).\n    apply Z.le_min_r; auto.\n  assert(HA2: ((Z.min c d) <= d)%Z).\n    apply Z.le_min_r; auto.\n  apply Z.le_trans with (m:=Z.min c d); auto.\nQed.\n\n(** ** Max Lemmas *)\n\nLemma le_max_ll: forall a b c d,\n  (a <= Z.max (Z.max a b) (Z.max c d))%Z.\nProof.\n  intros.\n  assert(HA1: ((Z.max a b) <= Z.max (Z.max a b) (Z.max c d))%Z).\n    apply Z.le_max_l; auto.\n  assert(HA2: (a <= (Z.max a b))%Z).\n    apply Z.le_max_l; auto.\n  apply Z.le_trans with (m:=Z.max a b); auto.\nQed.\n\nLemma le_max_lr: forall a b c d,\n  (b <= Z.max (Z.max a b) (Z.max c d))%Z.\nProof.\n  intros.\n  assert(HA1: ((Z.max a b) <= Z.max (Z.max a b) (Z.max c d))%Z).\n    apply Z.le_max_l; auto.\n  assert(HA2: (b <= (Z.max a b))%Z).\n    apply Z.le_max_r; auto.\n  apply Z.le_trans with (m:=Z.max a b); auto.\nQed.\n\nLemma le_max_rl: forall a b c d,\n  (c <= Z.max (Z.max a b) (Z.max c d))%Z.\nProof.\n  intros.\n  assert(HA1: ((Z.max c d) <= Z.max (Z.max a b) (Z.max c d))%Z).\n    apply Z.le_max_r; auto.\n  assert(HA2: (c <= (Z.max c d))%Z).\n    apply Z.le_max_l; auto.\n  apply Z.le_trans with (m:=Z.max c d); auto.\nQed.\n\nLemma le_max_rr: forall a b c d,\n  (d <= Z.max (Z.max a b) (Z.max c d))%Z.\nProof.\n  intros.\n  assert(HA1: ((Z.max c d) <= Z.max (Z.max a b) (Z.max c d))%Z).\n    apply Z.le_max_r; auto.\n  assert(HA2: (d <= (Z.max c d))%Z).\n    apply Z.le_max_r; auto.\n  apply Z.le_trans with (m:=Z.max c d); auto.\nQed.\n\nLemma max_abs_f_opp_le0: forall l u,\n  (Z.opp (max_abs_f l u) <= 0)%Z.\nProof.\n  intros.\n  unfold max_abs_f.\n  replace 0%Z with (-0)%Z; auto.\n  apply Le_Neg_Ge; auto.\n  apply Z.le_trans with (m:=(Z.abs l)%Z); auto.\n  destruct l; smack.\n  apply Z.le_max_l; auto.\nQed.\n\nLemma max_abs_f_ge0: forall l u,\n  (0 <= (max_abs_f l u))%Z.\nProof.\n  intros.\n  unfold max_abs_f.\n  apply Z.le_trans with (m:=(Z.abs l)%Z); auto.\n  destruct l; smack.\n  apply Z.le_max_l; auto.\nQed.\n\n(** ** Zmult Lemmas *)\n\n(**\n   - Lemman Z.mul_comm : forall n m : Z, (n * m)%Z = (m * n)%Z\n   - Lemma Z_eq_mult n m : m = 0 -> m * n = 0.\n*)\n\nLemma Zmult_le_le: forall u v,\n  (u <= 0)%Z ->\n    (v <= 0)%Z ->\n      (0 <= u * v)%Z.\nProof.\n  intros.\n  assert(HA1: (-0 <= (-u))%Z).\n    apply Le_Neg_Ge; auto.\n  assert(HA2: (-0 <= (-v))%Z).\n    apply Le_Neg_Ge; auto.\n  simpl in HA1, HA2.  \n  assert (HA3: (0*(-v) <= (-u)*(-v))%Z).\n    apply Zmult_le_compat_r; auto. \n  clear - HA3. \n  rewrite Zmult_opp_opp in HA3.\n  smack.\nQed.\n\nLemma Zmult_le_lt: forall u v,\n  (u <= 0)%Z ->\n    (v < 0)%Z ->\n      (0 <= u * v)%Z.\nProof.\n  intros.\n  assert(HA1: (v <= 0)%Z).\n    assert(HA2: (v <=? 0)%Z = true).\n    apply Zltb_leb_trans_leb with (v:=0%Z); auto.\n    apply Zltb_lt; auto.\n    apply Zleb_le; auto.\n  apply Zmult_le_le; auto.\nQed.\n\nLemma Zmult_lt_lt: forall u v,\n  (u < 0)%Z ->\n    (v < 0)%Z ->\n      (0 < u * v)%Z.\nProof.\n  intros.\n  assert(HA1: (-0 < (-u))%Z).\n    apply Lt_Neg_Gt; auto. simpl in HA1.\n  assert(HA2: (-0 < (-v))%Z).\n    apply Lt_Neg_Gt; auto. simpl in HA2.\n  assert(HA3: (0 * (-v) < (-u) * (-v))%Z).\n    apply Zmult_lt_compat_r; auto. \n  rewrite Zmult_opp_opp in HA3.\n  smack.\nQed.\n\nLemma Zmult_le_ge_r: forall u v,\n  (u <= 0)%Z ->\n    (0 <= v)%Z ->\n      (u * v <= 0)%Z.\nProof.\n  intros.\n  assert(HA3: (u * v <= 0 * v)%Z).\n    apply Zmult_le_compat_r; auto. \n  smack.\nQed.\n\nLemma Zmult_le_ge_l: forall u v,\n  (u <= 0)%Z ->\n    (0 <= v)%Z ->\n      (v * u <= 0)%Z.\nProof.\n  intros.\n  assert(HA3: (v*u <= v*0)%Z).\n    apply Zmult_le_compat_l; auto. \n  smack.\nQed.\n\n(**\n  - https://coq.inria.fr/V8.1/stdlib/Coq.ZArith.BinInt.html\n  - Lemma Zopp_mult_distr_l : forall n m:Z, - (n * m) = - n * m.\n  - Lemma Zopp_mult_distr_r : forall n m:Z, - (n * m) = n * - m.\n  - Lemma Zopp_mult_distr_l_reverse : forall n m:Z, - n * m = - (n * m).\n  - Lemma Zmult_opp_comm : forall n m:Z, - n * m = n * - m.\n  - Lemma Zmult_opp_opp : forall n m:Z, - n * - m = n * m.\n*)\n\nLemma Zmult_le_rev_l: forall n m p,\n  (n <= m)%Z ->\n    (p <= 0)%Z ->\n      (p * m <= p * n)%Z.\nProof.\n  intros.\n  specialize (Le_Neg_Ge _ _ H0); intro HZ; smack.\n  assert(HA1: ((-p)*n <= (-p)*m)%Z).\n    apply Zmult_le_compat_l; auto.\n  specialize (Le_Neg_Ge _ _ HA1); intro HZ1.\n  rewrite Zmult_opp_comm in HZ1. rewrite Zmult_opp_comm in HZ1. \n  rewrite Zopp_mult_distr_l in HZ1. rewrite Zopp_mult_distr_l in HZ1.\n  rewrite Zmult_opp_opp in HZ1.\n  rewrite Zmult_opp_opp in HZ1.\n  auto.\nQed.\n\nLemma Zmult_le_rev_r: forall n m p,\n  (n <= m)%Z ->\n    (p <= 0)%Z ->\n      (m * p <= n * p)%Z.\nProof.\n  intros.\n  specialize (Le_Neg_Ge _ _ H0); intro HZ; smack.\n  assert(HA1: (n*(-p) <= m*(-p))%Z).\n    apply Zmult_le_compat_r; auto.\n  specialize (Le_Neg_Ge _ _ HA1); intro HZ1.\n  rewrite Zopp_mult_distr_l in HZ1. rewrite Zopp_mult_distr_l in HZ1.\n  rewrite Zmult_opp_opp in HZ1.\n  rewrite Zmult_opp_opp in HZ1.\n  auto.\nQed.\n\n(** ** Zquot Lemmas *)\n\n(*\n   https://coq.inria.fr/V8.1/stdlib/Coq.ZArith.BinInt.html\n   - Theorem Zopp_mult_distr_l : forall n m:Z, - (n * m) = - n * m.\n   - Theorem Zopp_mult_distr_r : forall n m:Z, - (n * m) = n * - m.\n   - Lemma Zopp_mult_distr_l_reverse : forall n m:Z, - n * m = - (n * m).\n   - Theorem Zmult_opp_comm : forall n m:Z, - n * m = n * - m.\n   - Theorem Zmult_opp_opp : forall n m:Z, - n * - m = n * m.\n\n   https://coq.inria.fr/library/Coq.ZArith.Zquot.html \n   - Lemma Z_quot_monotone a b c : 0<=c -> a<=b -> a÷c <= b÷c.\n   - Lemma Zquot_0_r a : a ÷ 0 = 0.\n   - Lemma Zquot_0_l a : 0÷a = 0.\n   - Theorem Zquot_opp_l a b : (-a)÷b = -(a÷b).\n   - Theorem Zquot_opp_r a b : a÷(-b) = -(a÷b).\n   - Theorem Zquot_opp_opp a b : (-a)÷(-b) = a÷b.\n   - Theorem Z.quot_1_r : forall a : Z, (a ÷ 1)%Z = a\n*)\n\nLemma Zquot_antitone: forall a b c, \n  (c <= 0)%Z -> \n    (a <= b)%Z ->\n      (Z.quot b c <= Z.quot a c)%Z.\nProof.\n  intros.\n  assert(HA1: (-0 <= -c)%Z).\n    apply Le_Neg_Ge; auto. simpl in HA1.\n  specialize (Z_quot_monotone _ _ _ HA1 H0); intro HZ1.\n  assert(HA2: (-(b ÷ -c) <= - (a ÷ -c))%Z).\n    apply Le_Neg_Ge; auto.\n  repeat progress rewrite <- Zquot_opp_l in HA2.\n  repeat progress rewrite Zquot_opp_opp in HA2.\n  auto.\nQed.\n\nLemma Zquot_le_compat_p_p: forall a b c, \n  (0 <= a)%Z -> \n    (0 < b)%Z -> (b <= c)%Z ->\n      (Z.quot a c <= Z.quot a b)%Z.\nProof.\n  intros.\n  assert(Hb: (0 <= b)%Z).\n    apply Zlt_le; auto.\n  assert(Hc: (0 <= c)%Z).\n    apply Z.le_trans with (m:=b); auto.\n  specialize (Zle_lt_or_eq _ _ H1); intro HZ1.\n  destruct HZ1 as [HZ1a | HZ1b].\n  repeat progress rewrite Zquot_Zdiv_pos; auto.\n  apply Zdiv_le_compat_l; smack.\n  subst.\n  apply Z.le_refl.\nQed.\n\nLemma Zquot_le_compat_n_p: forall a b c, \n  (a <= 0)%Z -> \n    (0 < b)%Z -> (b <= c)%Z ->\n      (Z.quot a b <= Z.quot a c)%Z.\nProof.\n  intros.\n  assert(Ha: (-0 <= -a)%Z).\n    apply Le_Neg_Ge; auto. simpl in Ha.\n  specialize (Zquot_le_compat_p_p _ _ _ Ha H0 H1); intro HZ1.\n  repeat progress rewrite Zquot_opp_l in HZ1.\n  specialize (Le_Neg_Ge _ _ HZ1); intro HZ2.\n  smack.\nQed.\n\nLemma Zquot_le_compat_p_n: forall a b c, \n  (0 <= a)%Z -> \n    (c < 0)%Z -> (b <= c)%Z ->\n      (Z.quot a c <= Z.quot a b)%Z.\nProof.\n  intros.\n  assert(Hc: (-0 < -c)%Z).\n    apply Lt_Neg_Gt; auto. simpl in Hc.\n  assert(Hbc: (-c <= -b)%Z).\n    apply Le_Neg_Ge; auto.\n  specialize (Zquot_le_compat_p_p _ _ _ H Hc Hbc); intro HZ1.\n  specialize (Le_Neg_Ge _ _ HZ1); intro HZ2.\n  repeat progress rewrite Zquot_opp_r in HZ2.\n  smack.\nQed.\n\nLemma Zquot_le_compat_n_n: forall a b c, \n  (a <= 0)%Z -> \n    (c < 0)%Z -> (b <= c)%Z ->\n      (Z.quot a b <= Z.quot a c)%Z.\nProof.\n  intros.\n  assert(Ha: (-0 <= -a)%Z).\n    apply Le_Neg_Ge; auto. simpl in Ha.\n  specialize (Zquot_le_compat_p_n _ _ _ Ha H0 H1); intro HZ1.\n  repeat progress rewrite Zquot_opp_l in HZ1.\n  specialize (Le_Neg_Ge _ _ HZ1); intro HZ2.\n  smack.  \nQed.\n\nLemma Zquot_p_p_p: forall u v,\n  (0 <= u)%Z ->\n    (0 < v)%Z ->\n      (0 <= Z.quot u v)%Z.\nProof.\n  intros.\n  assert (HA1: (0 * v <= u)%Z).\n    smack.\n  specialize (Zquot_le_lower_bound _ _ _ H0 HA1); intro HZ1.\n  auto.\nQed.\n\nLemma Zquot_n_n_p: forall u v,\n  (u <= 0)%Z ->\n    (v < 0)%Z ->\n      (0 <= Z.quot u v)%Z.\nProof.\n  intros.\n  assert (HA1: (-0 < -v)%Z).\n    apply Lt_Neg_Gt; auto. simpl in HA1.\n  assert (HA2: (-0 <= -u)%Z).\n    apply Le_Neg_Ge; auto. simpl in HA2.\n  assert (HA3: (0 * (-v) <= -u)%Z).\n    smack.\n  specialize (Zquot_le_lower_bound _ _ _ HA1 HA3); intro HZ1.\n  rewrite Zquot_opp_opp in HZ1.\n  auto.\nQed.\n\nLemma Zquot_p_n_n: forall u v,\n  (0 <= u)%Z ->\n    (v < 0)%Z ->\n      (Z.quot u v <= 0)%Z.\nProof.\n  intros.\n  assert (HA1: (-0 < -v)%Z).\n    apply Lt_Neg_Gt; auto. simpl in HA1.\n  assert (HA2: (0 * (-v) <= u)%Z).\n    smack.\n  specialize (Zquot_le_lower_bound _ _ _ HA1 HA2); intro HZ1.\n  rewrite Zquot_opp_r in HZ1.\n  specialize (Le_Neg_Ge _ _ HZ1); intro HZ2.\n  smack.\nQed.\n\nLemma Zquot_n_p_n: forall u v,\n  (u <= 0)%Z ->\n    (0 < v)%Z ->\n      (Z.quot u v <= 0)%Z.\nProof.\n  intros.\n  assert (HA1: (-0 <= -u)%Z).\n    apply Le_Neg_Ge; auto. simpl in HA1.\n  specialize (Zquot_p_p_p _ _ HA1 H0); intro HZ1.\n  rewrite Zquot_opp_l in HZ1.\n  specialize (Le_Neg_Ge _ _ HZ1); intro HZ2.\n  smack.\nQed.\n\n(**\n   https://coq.inria.fr/library/Coq.ZArith.BinInt.html\n   - Lemma abs_eq n : 0 <= n -> abs n = n.\n   - Lemma abs_neq n : n <= 0 -> abs n = - n.\n*)\n\nLemma Zabs_ge_v: forall v,\n  (v <= Z.abs v)%Z.\nProof.\n  intros.\n  destruct v; smack.\n  (* apply Zle_neg_pos; auto. *)\nQed.\n\nLemma Zabs_ge_neg_v: forall v,\n  (-v <= Z.abs v)%Z.\nProof.\n  intros.\n  destruct v; smack.\n  (* apply Zle_neg_pos; auto. *)\nQed.\n\nLemma Zquot_n1_opp: forall v,\n  (Z.quot v (-1) = -v)%Z.\nProof.\n  intros.\n  replace (-1)%Z with (Z.opp 1).\n  rewrite Zquot_opp_r.\n  destruct v.\n  smack.\n  rewrite Zquot_Zdiv_pos; smack.\n    rewrite Zdiv_1_r; auto.\n  rewrite <- Zquot_opp_l.\n  rewrite Zquot_Zdiv_pos; smack.\n  smack.\nQed.\n\nLemma Zabs_quot_neg1: forall v,\n  (v <= 0)%Z ->\n    (Z.abs v = Z.quot v (-1))%Z.\nProof.\n  intros.\n  specialize (Z.abs_neq _ H); intro HZ.\n  rewrite HZ.\n  rewrite Zquot_n1_opp; auto.\nQed.\n\nLemma Zquot_p1_interval: forall l v u,\n  (l <= v)%Z ->\n    (v <= u)%Z ->\n      (Z.opp (max_abs_f l u) <= Z.quot v 1 <= (max_abs_f l u))%Z.\nProof.\n  intros.\n  replace (v ÷ 1)%Z with v.\n  unfold max_abs_f;\n  split.\n - (*case 1*)\n  apply Z.le_trans with (m:=l); auto.\n  replace l with (--l)%Z; smack.\n(*  apply Le_Neg_Ge; smack.\n  replace (--l)%Z with l; smack.\n  apply Z.le_trans with (m:=Z.abs l); auto.  \n  apply Zabs_ge_neg_v; auto.\n  apply Z.le_max_l; auto. *)\n - (*case 2*)  \n  apply Z.le_trans with (m:=u); auto.\n  apply Z.le_trans with (m:=Z.abs u); auto.\n  apply Zabs_ge_v; auto.\n  apply Z.le_max_r; auto.\n - (*case 3*)\n  smack.  \nQed.\n\nLemma Zquot_n1_interval: forall l v u,\n  (l <= v)%Z ->\n    (v <= u)%Z ->\n      (Z.opp (max_abs_f l u) <= Z.quot v (-1) <= (max_abs_f l u))%Z.\nProof.\n  intros.\n  rewrite Zquot_n1_opp.\n  unfold max_abs_f.\n  split.\n - (*case 1*)  \n  apply Z.le_trans with (m:=(-u)%Z); auto.\n  apply Le_Neg_Ge; auto.\n  apply Z.le_trans with (m:=(Z.abs u)%Z); auto.\n  apply Zabs_ge_v; auto.\n  apply Z.le_max_r; auto.\n  apply Le_Neg_Ge; auto.  \n - (*case 2*)  \n  apply Z.le_trans with (m:=(-l)%Z); auto.\n  apply Le_Neg_Ge; auto.\n  apply Z.le_trans with (m:=(Z.abs l)%Z); auto.\n  apply Zabs_ge_neg_v; auto.\n  apply Z.le_max_l; auto.\nQed.\n\n(********************************************************************)\n(********************************************************************)\n\n(** * Modulus Interval Correctness *)\n(**\n   The following three lemmas can be manually proved to be correct.\n*)\nLemma modulus_in_bound: forall v1 v2 l1 l2 u1 u2 l u,\n  in_bound v1 (Interval l1 u1) true ->\n  in_bound v2 (Interval l2 u2) true -> \n  Zeq_bool v2 0 = false ->\n  modulus_min_max_f l1 u1 l2 u2 = (l, u) ->\n  in_bound (Z.modulo v1 v2) (Interval l u) true.\nProof.\n  intros;\n  destruct v2; auto.\n - (* case 1: v2 = 0: conflict *)\n   smack.\n - (* case 2: v2 > 0 *)\n   assert(HA1: ((Z.pos p) > 0)%Z). smack.\n   specialize (Z_mod_lt v1 _ HA1); intro HZ1.\n   destruct HZ1 as [HZ1a HZ1b].\n   inversion H0; subst.\n   remember ((l2 <=? Z.pos p)%Z) as x1.\n   remember ((Z.pos p <=? u2)%Z) as x2.\n   destruct x1, x2; inversion H5; clear H5.\n   symmetry in Heqx1, Heqx2.\n   \n   unfold modulus_min_max_f in H2.\n   remember ((u2 <=? -1)%Z) as y1.\n   destruct y1; subst;\n   symmetry in Heqy1.\n   (* sub-case 1: [l2, u2] < 0 : conflict *)\n   specialize (Zleb_trans _ _ _ Heqx2 Heqy1); smack.\n\n   remember ((1 <=? l2)%Z) as y2; \n   destruct y2; subst;\n   symmetry in Heqy2;\n   symmetry in H2; inversion H2; subst.\n   (* sub-case 2: [l2, u2] > 0 *)\n   constructor; auto.\n   assert(HA2: (0 <=? v1 mod Z.pos p)%Z = true).\n     apply Zleb_le; auto.\n   rewrite HA2; simpl.\n   assert(HA3: (v1 mod Z.pos p <? Z.pos p)%Z = true).\n     apply Zltb_lt; auto.\n   assert(HA4: (v1 mod Z.pos p <? u2)%Z = true).\n     apply Zltb_leb_trans_ltb with (m:=Z.pos p); auto.\n   apply Zltb_pred_r; auto.  \n   (* sub-case 3: 0 is in [l2, u2] *)\n   constructor; auto.\n   assert(HA2: ((if Zeq_bool l2 0 then 0 else l2 + 1) <=? v1 mod Z.pos p)%Z = true).\n     remember (Zeq_bool l2 0) as b1.\n     destruct b1; subst;\n     apply Zleb_le; auto.\n     specialize (Le_False_Lt _ _ Heqy2); intro HZ.\n     replace 1%Z with (Z.succ 0) in HZ; auto.\n     specialize (Zlt_succ_le _ _ HZ); intro HZ2.\n     specialize (Zle_lt_or_eq _ _ HZ2); intro HZ3.\n     destruct HZ3 as [HZ3a | HZ3b].\n     apply Zlt_le_succ; auto.\n     apply Z.lt_le_trans with (m:=0%Z); auto. smack.\n   rewrite HA2; simpl.\n   remember (Zeq_bool u2 0) as b2.\n   destruct b2; symmetry in Heqb2.\n   rewrite (Zeq_bool_eq _ _ Heqb2) in Heqx2; inversion Heqx2.\n   apply Zltb_pred_r; auto.\n   apply Zltb_leb_trans_ltb with (m := Z.pos p); auto.\n   apply Zltb_lt; auto.\n - (* case 3: v2 < 0 *)\n   assert(HA1: ((Z.neg p) < 0)%Z). constructor; auto.\n   specialize (Z_mod_neg v1 _ HA1); intro HZ1.\n   destruct HZ1 as [HZ1a HZ1b].\n   inversion H0; subst.\n   remember ((l2 <=? Z.neg p)%Z) as x1.\n   remember ((Z.neg p <=? u2)%Z) as x2.\n   destruct x1, x2; inversion H5; clear H5.\n   symmetry in Heqx1, Heqx2.\n   \n   unfold modulus_min_max_f in H2.\n   remember ((u2 <=? -1)%Z) as y1.\n   destruct y1; subst;\n   symmetry in Heqy1.\n   (* sub-case 1: [l2, u2] < 0 *)\n   inversion H2; subst.\n   constructor; auto.\n   assert(HA2: (v1 mod Z.neg p <=? 0)%Z = true).\n     apply Zleb_le; auto.\n   rewrite HA2; auto.\n   assert(HA3: (l2 <? v1 mod Z.neg p)%Z = true).\n     apply Zleb_ltb_trans_ltb with (m:=Z.neg p); auto.\n     apply Zltb_lt; auto.\n   assert(HA4: (l2 + 1 <=? v1 mod Z.neg p)%Z = true).\n     replace (l2 + 1)%Z with (Z.succ l2); smack.\n     apply Zltb_succ_l; auto.\n   rewrite HA4; auto.\n   (* sub-case 2: [l2, u2] > 0 : conflict *)\n   remember ((1 <=? l2)%Z) as y2; \n   destruct y2; subst;\n   symmetry in Heqy2;\n   symmetry in H2; inversion H2; subst.\n\n   specialize (Zleb_trans _ _ _ Heqy2 Heqx1); smack.\n   (* sub-case 3: 0 is in [l2, u2] *)\n   constructor; auto.\n   assert(HA2: ((if Zeq_bool l2 0 then 0 else l2 + 1) <=? v1 mod Z.neg p)%Z = true).\n     remember (Zeq_bool l2 0) as b1.\n     destruct b1; subst;\n     apply Zleb_le; auto;\n     symmetry in Heqb1.\n     rewrite (Zeq_bool_eq _ _ Heqb1) in Heqx1; inversion Heqx1.\n     apply Zlt_le_succ; auto.\n     apply Z.le_lt_trans with (m:=Z.neg p); auto.\n     apply Zleb_le; auto.\n   rewrite HA2; simpl.\n   \n   remember (Zeq_bool u2 0) as b2.\n   destruct b2; symmetry in Heqb2.\n   apply Zleb_le; auto.\n   specialize (Le_False_Lt _ _ Heqy1); intro HZ.\n   specialize (Z.le_succ_l (-1)%Z u2); intro HZ3.\n   destruct HZ3 as [HZ3a HZ3b].\n   specialize (HZ3b HZ). simpl in HZ3b.\n   specialize (Zle_lt_or_eq _ _ HZ3b); intro HZ4.\n     destruct HZ4 as [HZ4a | HZ4b]; smack.\n   assert(HA3: (v1 mod Z.neg p <? u2)%Z = true).\n     apply Zleb_ltb_trans_ltb with (m:=0%Z); auto.\n     apply Zleb_le; auto. \n     apply Zltb_lt; auto.\n     apply Zltb_pred_r; auto.\nQed.\n\nLtac apply_modulus_in_bound :=\n  match goal with\n  | [H1: in_bound ?v1 (Interval ?l1 ?u1) true,\n     H2: in_bound ?v2 (Interval ?l2 ?u2) true, \n     H3: Zeq_bool ?v2 0 = false,\n     H4: modulus_min_max_f ?l1 ?u1 ?l2 ?u2 = (?l, ?u) |- _] =>\n      specialize (modulus_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4);\n      let HZ:=fresh \"HZ\" in intro HZ\n  | [H1: in_bound ?v1 (Interval ?l1 ?u1) true,\n     H2: in_bound ?v2 (Interval ?l2 ?u2) true, \n     H3: Zeq_bool ?v2 0 = false,\n     H4: (?l, ?u) = modulus_min_max_f ?l1 ?u1 ?l2 ?u2 |- _] =>\n      symmetry in H4;\n      specialize (modulus_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4);\n      let HZ:=fresh \"HZ\" in intro HZ\n  end.\n\n(** * Multiply Interval Correctness *)\n\nLemma multiply_in_bound: forall v1 v2 l1 l2 u1 u2,\n  in_bound v1 (Interval l1 u1) true ->\n  in_bound v2 (Interval l2 u2) true -> \n  in_bound (v1*v2) (Interval (multiply_min_f l1 u1 l2 u2) (multiply_max_f l1 u1 l2 u2)) true.\nProof.\n  intros;\n  unfold multiply_min_f, multiply_max_f;\n  destruct v1, v2; smack;\n  repeat progress match goal with\n  | [H: in_bound ?v (Interval ?l ?u) true |- _] => inversion H; subst; clear H\n  end;\n  repeat progress apply_Zleb_true_le_true;\n  constructor; auto.\n - (* case 1: v1 = 0, v2 = 0 *)\n  (* l1 <= v1 <= u1, 0 <= u2 ==> l1*u2 <= v1*u2 <= u1 * u2, here v1 is 0*)\n  assert (HA1: (l1*u2 <= 0*u2)%Z).\n    apply Zmult_le_compat_r; auto.\n  assert (HA2: (0*u2 <= u1*u2)%Z).\n    apply Zmult_le_compat_r; auto.\n  clear - HA1 HA2. smack.\n  assert(HA3: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= 0)%Z).\n    apply Z.le_trans with (m:=(l1*u2)%Z); auto.\n  apply le_min_lr; auto.\n  assert(HA4: (0 <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(u1*u2)%Z); auto.\n  apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n - (* case 2: v1 = 0, v2 > 0 *)\n  assert(HA: (0 <= u2)%Z).\n    apply Z.le_trans with (m:=Z.pos p); smack.\n  (* l1 <= v1 <= u1, 0 <= u2 ==> l1*u2 <= v1*u2 <= u1 * u2, here v1 is 0*)\n  assert (HA1: (l1*u2 <= 0*u2)%Z).\n    apply Zmult_le_compat_r; auto.\n  assert (HA2: (0*u2 <= u1*u2)%Z).\n    apply Zmult_le_compat_r; auto.\n  clear - HA1 HA2. smack.\n  assert(HA3: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= 0)%Z).\n    apply Z.le_trans with (m:=(l1*u2)%Z); auto.\n  apply le_min_lr; auto. \n  assert(HA4: (0 <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(u1*u2)%Z); auto.\n  apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.  \n - (* case 3: v1 = 0, v2 < 0 *)\n  assert(HA: (l2 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p); auto. \n    apply Pos2Z.neg_is_nonpos; auto.\n  (* l2 <= 0, 0 <= u1 ==> l2*u1 <= 0*)\n  assert (HA1: (u1 * l2 <= u1 * 0)%Z).\n    apply Zmult_le_compat_l; auto. \n  rewrite (Z.mul_comm u1 0%Z) in HA1. smack.\n  assert (HA2: (0 <= l1 * l2)%Z).\n    apply Zmult_le_le; auto.\n  assert(HA3: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= 0)%Z).\n    apply Z.le_trans with (m:=(u1*l2)%Z); auto.\n  apply le_min_rl; auto.\n  assert(HA4: (0 <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(l1*l2)%Z); auto.\n    apply le_max_ll; auto.\n  apply Zle_true_leb_true; auto.\n - (* case 4: v1 > 0, v2 = 0 *)\n  assert(HA: (0 <= u1)%Z).\n    apply Z.le_trans with (m:=Z.pos p); smack.\n  (* l2 <= 0 <= u2 ==> u1*l2 <= u1*0 <= u1*u2*)\n  assert (HA1: (u1 * l2 <= u1 * 0)%Z).\n    apply Zmult_le_compat_l; auto. \n  rewrite (Z.mul_comm u1 0%Z) in HA1. smack.\n  assert (HA2: (u1 * 0 <= u1 * u2)%Z).\n    apply Zmult_le_compat_l; auto.\n  rewrite (Z.mul_comm u1 0%Z) in HA2. smack.\n  assert(HA3: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= 0)%Z).\n    apply Z.le_trans with (m:=(u1*l2)%Z); auto.\n  apply le_min_rl; auto.\n  assert(HA4: (0 <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(u1*u2)%Z); auto.\n    apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n - (* case 5: v1 > 0, v2 > 0 *)\n  (* l1 <= v1 <= u1 ==> l1*u2 <= (v1*v2 <=) <= v1*u2 <= u1*u2; l1*l2<=v1*v2 *)\n  assert(HA1a: (0 <= u1)%Z).\n    apply Z.le_trans with (m:=Z.pos p); smack. \n  assert(HA1b: (0 <= u2)%Z).\n    apply Z.le_trans with (m:=Z.pos p0); smack. \n  assert (HA2: ((Z.pos p) * u2 <= u1 * u2)%Z).\n    apply Zmult_le_compat_r; auto.\n  assert (HA3: ((Z.pos p) * (Z.pos p0) <= (Z.pos p) * u2)%Z).\n    apply Zmult_le_compat_l; smack.\n  assert(HA4: (Z.pos p * Z.pos p0 <= u1 * u2)%Z).\n    apply Z.le_trans with (m:=(Z.pos p * u2)%Z); auto.\n  assert(HZ1: ((Z.pos p) * (Z.pos p0) <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(u1*u2)%Z); auto.\n    apply le_max_rr; auto.\n\n  destruct l1; subst.\n  (* 1. l1 = 0 *)\n  assert(HZ2: (Z.min (Z.min (0 * l2) (0 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= (Z.pos p) * (Z.pos p0))%Z).\n    apply Z.le_trans with (m:=(0*l2)%Z); auto.\n    apply le_min_lr; auto.\n  apply Zle_true_leb_true; auto.  \n  (* 2. l1 > 0 *)\n  destruct l2; subst.\n  (* - 2.1 l2 = 0 *)\n  assert(HZ2: (Z.min (Z.min (Z.pos p1 * 0) (Z.pos p1 * u2)) (Z.min (u1 * 0) (u1 * u2)) <= (Z.pos p) * (Z.pos p0))%Z).\n    apply Z.le_trans with (m:=(u1 * 0)%Z); auto.\n    apply le_min_rl; auto.\n    rewrite (Z.mul_comm u1 0%Z). smack.\n  apply Zle_true_leb_true; auto.  \n  (* - 2.2 l2 > 0 *)\n  assert(HZ2: (Z.min (Z.min (Z.pos p1 * Z.pos p2) (Z.pos p1 * u2)) (Z.min (u1 * Z.pos p2) (u1 * u2)) <= (Z.pos p) * (Z.pos p0))%Z).\n    apply Z.le_trans with (m:=((Z.pos p1) * (Z.pos p2))%Z); auto.\n    apply le_min_ll; auto.\n    apply Zmult_le_compat; smack.\n  apply Zle_true_leb_true; auto.    \n  (* - 2.3 l2 < 0 *)\n  assert(HA_1: (u1 * (Z.neg p2) <= u1 * 0)%Z).\n    apply Zmult_le_compat_l; smack.\n  rewrite (Z.mul_comm u1 0) in HA_1. rewrite (Z_eq_mult u1 0%Z) in HA_1; auto.\n  assert(HZ2: (Z.min (Z.min (Z.pos p1 * Z.neg p2) (Z.pos p1 * u2)) (Z.min (u1 * Z.neg p2) (u1 * u2)) <= (Z.pos p) * (Z.pos p0))%Z).\n    apply Z.le_trans with (m:=(u1 * (Z.neg p2))%Z); auto.\n    apply le_min_rl; auto.\n    apply Z.le_trans with (m:=0%Z); auto.\n  apply Zle_true_leb_true; auto.\n  (* 3. l1 < 0 *)\n  assert(HA_1: ((Z.neg p1) * u2 <= 0 * u2)%Z).\n    apply Zmult_le_compat_r; smack.\n  rewrite (Z_eq_mult u2 0%Z) in HA_1; auto.\n  assert(HZ2: (Z.min (Z.min (Z.neg p1 * l2) (Z.neg p1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= (Z.pos p) * (Z.pos p0))%Z).\n    apply Z.le_trans with (m:=(Z.neg p1 * u2)%Z); auto.\n    apply le_min_lr; auto.\n    apply Z.le_trans with (m:=0%Z); auto.\n  apply Zle_true_leb_true; auto.\n - (* case 6: v1 > 0, v2 < 0 *)\n  assert(HA1a: (0 <= u1)%Z).\n    apply Z.le_trans with (m:=Z.pos p); smack.\n  assert(HA1b: (l2 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p0); auto.\n    specialize (Zlt_neg_0 p0); intro HZ1. smack.\n  assert(HA1c: ((Z.pos p)*(Z.neg p0) <= 0)%Z).\n    apply Zmult_le_ge_l; auto.\n      specialize (Zlt_neg_0 p0); intro; smack.\n    smack.\n\n  (* u1*l2 <= v1*v2 *)\n  assert(HA2: (u1*l2 <= (Z.pos p)*(Z.neg p0))%Z).\n    (* l2 <= v2 and 0 <= u1, so u1*l2 <= u1*v2 *)\n    assert(HA2a: (u1*l2 <= u1*(Z.neg p0))%Z).\n      apply Zmult_le_compat_l; smack.\n    assert(HA2b: (u1*(Z.neg p0) <= (Z.pos p)*(Z.neg p0))%Z).\n      apply Zmult_le_rev_r; auto.\n    apply Z.le_trans with (m:=(u1 * Z.neg p0)%Z); auto.\n\n  assert(HZ1: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= Z.neg (p * p0))%Z).\n    apply Z.le_trans with (m:=(u1 * l2)%Z); auto.\n    apply le_min_rl; auto.\n      \n  destruct l1; subst.\n  (* 1. l1 = 0 *)  \n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (0 * l2) (0 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(0 * u2)%Z); auto.\n    apply le_max_lr; auto.\n  apply Zle_true_leb_true; auto.\n  (* 2. l1 > 0 *)  \n  destruct u2; subst.\n  (* - 2.1. u2 = 0 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (Z.pos p1 * l2) (Z.pos p1 * 0)) (Z.max (u1 * l2) (u1 * 0)))%Z).\n    apply Z.le_trans with (m:=(u1 * 0)%Z); auto.\n    rewrite (Z.mul_comm u1 0%Z); smack.\n    apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n  (* - 2.2. u2 > 0 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (Z.pos p1 * l2) (Z.pos p1 * Z.pos p2)) (Z.max (u1 * l2) (u1 * Z.pos p2)))%Z).\n    apply Z.le_trans with (m:=(u1 * (Z.pos p2))%Z); auto.\n    apply Z.le_trans with (m:=(u1 * 0)%Z); smack.\n    apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n  (* - 2.3. u2 < 0 *)\n  (* v1*v2 <= l1*u2 *)\n  assert(HA3: ((Z.pos p)*(Z.neg p0) <= (Z.pos p1)*(Z.neg p2))%Z).\n    (* v1*v2 <= v1*u2 *)\n    assert(HA3a: ((Z.pos p)*(Z.neg p0) <= (Z.pos p)*(Z.neg p2))%Z).\n      apply Zmult_le_compat_l; smack.\n    (* v1*u2 <= l1*u2 *)\n    assert(HA3b: ((Z.pos p)*(Z.neg p2) <= (Z.pos p1)*(Z.neg p2))%Z).\n      apply Zmult_le_rev_r; smack.   \n    apply Z.le_trans with (m:=(Z.pos p * Z.neg p2)%Z); auto.\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (Z.pos p1 * l2) (Z.pos p1 * Z.neg p2)) (Z.max (u1 * l2) (u1 * Z.neg p2)))%Z).\n    apply Z.le_trans with (m:=((Z.pos p1)*(Z.neg p2))%Z); auto.\n    apply le_max_lr; auto.\n  apply Zle_true_leb_true; auto.\n  (* 3. l1 < 0 *)  \n  (* v1*v2 <= l1*l2 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (Z.neg p1 * l2) (Z.neg p1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(0)%Z); auto.\n    apply Z.le_trans with (m:=(Z.neg p1 * l2)%Z); auto.\n    apply Zmult_le_le; auto.\n    apply le_max_ll; auto.\n  apply Zle_true_leb_true; auto.\n - (* case 7: v1 < 0, v2 = 0 *)\n  assert(HA: (l1 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p); auto.\n    specialize (Zlt_neg_0 p); intro; smack.\n  (* l1*u2 <= v1*v2 *)\n  assert (HA1: (l1*u2 <= (Z.neg p)*0)%Z).\n    apply Zmult_le_ge_r; auto.\n  (* v1*v2 <= l1*l2 *)\n  assert (HA2: ((Z.neg p)*0 <= l1 * l2)%Z).\n    rewrite (Z.mul_comm (Z.neg p) 0). simpl.\n    apply Zmult_le_le; auto.\n  rewrite (Z.mul_comm (Z.neg p) 0) in HA2; simpl in HA2.\n\n  assert(HZ1: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= 0)%Z).\n    apply Z.le_trans with (m:=(l1*u2)%Z); auto.\n    apply le_min_lr; auto. \n  assert(HZ2: (0 <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(l1*l2)%Z); auto.\n    apply le_max_ll; auto.\n  apply Zle_true_leb_true; auto.   \n - (* case 8: v1 < 0, v2 > 0 *)\n  assert(HA1a: (0 <= u2)%Z).\n    apply Z.le_trans with (m:=Z.pos p0); smack.\n  assert(HA1b: (l1 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p); auto.\n    specialize (Zlt_neg_0 p); intro HZ1. smack.\n  assert(HA1c: ((Z.pos p)*(Z.neg p0) <= 0)%Z).\n    apply Zmult_le_ge_l; auto. \n      specialize (Zlt_neg_0 p0); intro; smack.\n    smack.\n\n  (* l1*u2 <= v1*v2 *)\n  assert(HA2: (l1*u2 <= (Z.neg p)*(Z.pos p0))%Z).\n    (* l1 <= v1 and 0 <= u2, so l1*u2 <= v1*u2 *)\n    assert(HA2a: (l1*u2 <= (Z.neg p)*u2)%Z).\n      apply Zmult_le_compat_r; smack.\n    assert(HA2b: ((Z.neg p)*u2 <= (Z.neg p)*(Z.pos p0))%Z).\n      apply Zmult_le_rev_l; auto.\n    apply Z.le_trans with (m:=((Z.neg p)*u2)%Z); auto.\n\n  assert(HZ1: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (u1 * l2) (u1 * u2)) <= Z.neg (p * p0))%Z).\n    apply Z.le_trans with (m:=(l1 * u2)%Z); auto.\n    apply le_min_lr; auto.\n      \n  destruct l2; subst.\n  (* 1. l2 = 0 *)  \n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (l1 * 0) (l1 * u2)) (Z.max (u1 * 0) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(u1*0)%Z); auto.\n    rewrite (Z.mul_comm u1 0%Z); smack.\n    apply le_max_rl; auto.\n  apply Zle_true_leb_true; auto.\n  (* 2. l2 > 0 *)  \n  destruct u1; subst.\n  (* - 2.1. u1 = 0 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (l1 * Z.pos p1) (l1 * u2)) (Z.max (0 * Z.pos p1) (0 * u2)))%Z).\n    apply Z.le_trans with (m:=(0*u2)%Z); auto.\n    apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n  (* - 2.2. u1 > 0 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (l1 * Z.pos p1) (l1 * u2)) (Z.max (Z.pos p2 * Z.pos p1) (Z.pos p2 * u2)))%Z).\n    apply Z.le_trans with (m:=((Z.pos p2)*u2)%Z); auto.\n    apply Z.le_trans with (m:=(0*u2)%Z); auto. \n    apply Zmult_le_compat_r; smack.\n    apply le_max_rr; auto.\n  apply Zle_true_leb_true; auto.\n  (* - 2.3. u1 < 0 *)\n  (* v1*v2 <= u1*l2 *)\n  assert(HA3: ((Z.neg p)*(Z.pos p0) <= (Z.neg p2)*(Z.pos p1))%Z).\n    (* v1*v2 <= u1*v2 *)\n    assert(HA3a: ((Z.neg p)*(Z.pos p0) <= (Z.neg p2)*(Z.pos p0))%Z).\n      apply Zmult_le_compat_r; auto.\n    (* u1*v2 <= u1*l2 *)\n    assert(HA3b: ((Z.neg p2)*(Z.pos p0) <= (Z.neg p2)*(Z.pos p1))%Z).\n      apply Zmult_le_rev_l; smack.   \n    apply Z.le_trans with (m:=(Z.neg p2 * Z.pos p0)%Z); auto.\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (l1 * Z.pos p1) (l1 * u2)) (Z.max (Z.neg p2 * Z.pos p1) (Z.neg p2 * u2)))%Z).\n    apply Z.le_trans with (m:=((Z.neg p2)*(Z.pos p1))%Z); auto.\n    apply le_max_rl; auto.\n  apply Zle_true_leb_true; auto.\n  (* 3. l2 < 0 *)  \n  (* v1*v2 <= l1*l2 *)\n  assert(HZ2: (Z.neg (p * p0) <= Z.max (Z.max (l1 * Z.neg p1) (l1 * u2)) (Z.max (u1 * Z.neg p1) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(0)%Z); auto.\n    apply Z.le_trans with (m:=(l1*Z.neg p1)%Z); auto.\n    apply Zmult_le_le; auto.\n    apply le_max_ll; auto.\n  apply Zle_true_leb_true; auto.\n - (* case 9: v1 < 0, v2 < 0 *)\n  (* v1*v2 <= l1*l2 *)\n  assert(HA1a: (l1 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p); auto. \n    specialize (Zlt_neg_0 p); intro; smack.\n  assert(HA1b: (l2 <= 0)%Z).\n    apply Z.le_trans with (m:=Z.neg p0); auto. \n    specialize (Zlt_neg_0 p0); intro; smack.\n  (* v1*l2 <= l1*l2 *)\n  assert (HA2: ((Z.neg p) * l2 <= l1 * l2)%Z).\n    apply Zmult_le_rev_r; auto.\n  (* v1*v2 <= v1*l2 *)\n  assert (HA3: ((Z.neg p) * (Z.neg p0) <= (Z.neg p) * l2)%Z).\n    apply Zmult_le_rev_l; auto.\n    specialize (Zlt_neg_0 p); intro; smack.\n  (* v1*v2 <= l1*l2 *)\n  assert(HA4: (Z.neg p * Z.neg p0 <= l1 * l2)%Z).\n    apply Z.le_trans with (m:=(Z.neg p * l2)%Z); auto.\n  assert(HZ1: (Z.pos (p * p0) <= Z.max (Z.max (l1 * l2) (l1 * u2)) (Z.max (u1 * l2) (u1 * u2)))%Z).\n    apply Z.le_trans with (m:=(l1*l2)%Z); auto.\n    apply le_max_ll; auto.\n\n  destruct u1; subst.\n  (* 1. u1 = 0 *)\n  assert(HZ2: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (0 * l2) (0 * u2)) <= Z.pos (p * p0))%Z).\n    apply Z.le_trans with (m:=(0*l2)%Z); auto.\n    apply le_min_rl; auto.\n  apply Zle_true_leb_true; auto.  \n  (* 2. u1 > 0 *)\n  (* u1*l2 <= 0 <= v1*v2 *)\n  assert(HZ2: (Z.min (Z.min (l1 * l2) (l1 * u2)) (Z.min (Z.pos p1 * l2) (Z.pos p1 * u2)) <= Z.pos (p * p0))%Z).\n    apply Z.le_trans with (m:=((Z.pos p1)*l2)%Z); auto.\n    apply le_min_rl; auto.\n    (* u1*l2 <= v1*v2 *)\n    apply Z.le_trans with (m:=0%Z); auto.\n    (* u1*l2 <= 0 *)\n    apply Zmult_le_ge_l; auto.\n    (* 0 <= v1*v2 *)\n  apply Zle_true_leb_true; auto.\n  (* 3. u1 < 0 *)    \n  destruct u2; subst.\n  (* - 3.1 u2 = 0 *)\n  assert(HZ2: (Z.min (Z.min (l1 * l2) (l1 * 0)) (Z.min (Z.neg p1 * l2) (Z.neg p1 * 0)) <= Z.pos (p * p0))%Z).\n    apply Z.le_trans with (m:=(l1 * 0)%Z); auto.\n    apply le_min_lr; auto.\n    rewrite (Z.mul_comm l1 0%Z). smack.\n  apply Zle_true_leb_true; auto.  \n  (* - 3.2 u2 > 0 *)\n  (* u1*u2 <= 0 <= v1*v2 *)\n  assert(HZ2: (Z.min (Z.min (l1 * l2) (l1 * Z.pos p2)) (Z.min (Z.neg p1 * l2) (Z.neg p1 * Z.pos p2)) <= Z.pos (p * p0))%Z).\n    apply Z.le_trans with (m:=((Z.neg p1) * (Z.pos p2))%Z); auto.\n    apply le_min_rr; auto.\n  apply Zle_true_leb_true; auto.    \n  (* - 3.3 u2 < 0 *)\n  (* u1*u2 <= v1*v2 *)\n  (* step 1: u1*u2 <= v1*u2 *)\n  assert(HA_1: ((Z.neg p1) * (Z.neg p2) <= (Z.neg p) * (Z.neg p2))%Z).\n    apply Zmult_le_rev_r; auto.\n    specialize (Zlt_neg_0 p2); intro; smack.\n  (* step 2: v1*u2 <= v1*v2 *)\n  assert(HA_2: ((Z.neg p) * (Z.neg p2) <= (Z.neg p) * (Z.neg p0))%Z).\n    apply Zmult_le_rev_l; auto.\n    specialize (Zlt_neg_0 p); intro; smack.\n  (* final: u1*u2 <= v1*v2 *)\n  assert(HA_3: ((Z.neg p1) * (Z.neg p2) <= (Z.neg p) * (Z.neg p0))%Z).\n    apply Z.le_trans with (m:=((Z.neg p) * (Z.neg p2))%Z); auto.\n\n  assert(HZ2: (Z.min (Z.min (l1 * l2) (l1 * Z.neg p2)) (Z.min (Z.neg p1 * l2) (Z.neg p1 * Z.neg p2)) <= \n    Z.pos (p * p0))%Z).\n    apply Z.le_trans with (m:=((Z.neg p1) * (Z.neg p2))%Z); auto.\n    apply le_min_rr; auto.\n  apply Zle_true_leb_true; auto.\nQed.\n\nLtac apply_multiply_in_bound := \n  match goal with\n  | [H1: in_bound ?v1 (Interval ?l1 ?u1) true,\n     H2: in_bound ?v2 (Interval ?l2 ?u2) true |- _] =>\n      specialize (multiply_in_bound _ _ _ _ _ _ H1 H2); \n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n  \n(** * Divide Interval Correctness *)\n  \nLemma divide_in_bound: forall v1 v2 l1 l2 u1 u2 l u,\n  in_bound v1 (Interval l1 u1) true ->\n  in_bound v2 (Interval l2 u2) true -> \n  Zeq_bool v2 0 = false ->\n  divide_min_max_f l1 u1 l2 u2 = (l, u) ->\n  in_bound (Z.quot v1 v2) (Interval l u) true.\nProof.\n  intros.\n  repeat progress match goal with\n  | [H: in_bound ?v (Interval ?l ?u) true |- _] => inversion H; subst; clear H\n  end;\n  repeat progress apply_Zleb_true_le_true;\n  constructor; auto.\n  clear HZa HZb HZa0 HZb0.\n  unfold divide_min_max_f in H2.\n  remember ((u2 <=? -1)%Z) as u2b.\n  destruct u2b; subst.\n  symmetry in Hequ2b.\n  assert(Hu2bT: (u2 <= -1)%Z).\n    apply Zleb_le; auto.\n  apply_Zle_n1_0.\n - (* 1. [l2, u2] <= -1 *)\n  assert(HA1: (v2 < 0)%Z).\n    apply Z.le_lt_trans with (m:=u2); auto.\n  remember ((u1 <=? -1)%Z) as u1b.\n  destruct u1b; subst.\n  assert(Hu1bT: (u1 <= -1)%Z).\n    apply Zleb_le; auto.\n  apply_Zle_n1_0.\n  (* - case 1.1: [l2, u2] <= -1, [l1, u1] <= -1 *)\n  inversion H2; subst.  \n  assert(HZ1: (u1 ÷ l2 <= v1 ÷ v2)%Z).\n    (* u1/l2 <= [u1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(u1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_n_n; auto.\n    apply Zquot_antitone; auto.\n    apply Zlt_le; auto.\n  assert(HZ2: (v1 ÷ v2 <= l1 ÷ u2)%Z).\n    (* v1/v2 <= [l1/v2] <= l1/u2 *)\n    apply Z.le_trans with (m:=(l1 ÷ v2)%Z); auto.\n    apply Zquot_antitone; auto.\n    apply Zlt_le; auto.\n    apply Zquot_le_compat_n_n; auto.\n    apply Z.le_trans with (m:=u1); auto.\n    apply Z.le_trans with (m:=v1); auto.\n  apply Zle_true_leb_true; auto.\n  \n  remember ((1 <=? l1)%Z) as l1b.   \n  destruct l1b; subst. \n  symmetry in Heql1b.\n  assert(Hl1bT: (1 <= l1)%Z).\n    apply Zleb_le; auto.\n  apply_Zge_p1_0.\n  (* - case 1.2: [l2, u2] <= -1, 1 <= [l1, u1] *)  \n  inversion H2; subst.\n  assert(HZ1: (u1 ÷ u2 <= v1 ÷ v2)%Z).\n    (* u1/u2 <= [u1/v2] <= v1/v2 *)  \n    apply Z.le_trans with (m:=(u1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_p_n; auto.\n      apply Z.le_trans with (m:=l1); auto.\n      apply Z.le_trans with (m:=v1); auto.\n    apply Zquot_antitone; auto.\n      apply Zlt_le; auto.\n  assert(HZ2: (v1 ÷ v2 <= l1 ÷ l2)%Z).\n    (* v1/v2 <= [v1/l2] <= l1/l2 *)  \n    apply Z.le_trans with (m:=(v1 ÷ l2)%Z); auto.\n    apply Zquot_le_compat_p_n; auto.\n      apply Z.le_trans with (m:=l1); auto.\n    apply Zquot_antitone; auto.\n      apply Z.le_trans with (m:=u2); auto.\n      apply Z.le_trans with (m:=v2); auto.\n  apply Zle_true_leb_true; auto.\n  (* - case 1.3: [l2, u2] <= -1, 0 in [l1, u1] *)  \n  inversion H2; subst.\n  assert(HZ12: (u1 ÷ u2 <= v1 ÷ v2)%Z /\\ (v1 ÷ v2 <= l1 ÷ u2)%Z).\n    (* u1/u2 <= [u1/v2] <= v1/v2;  v1/v2 <= [v1/u2] <= l1/u2*)\n    remember (0 <=? v1)%Z as v1b.\n    destruct v1b;\n    symmetry in Heqv1b.\n    (* 1.3.1. 0 <= v1 *)\n    assert(Hv1bT: (0 <= v1)%Z).\n      apply Zleb_le; auto.\n    split.\n    (* - *)\n    apply Z.le_trans with (m:=(u1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_p_n; auto.\n      apply Z.le_trans with (m:=v1); auto.\n    apply Zquot_antitone; auto.\n      apply Zlt_le; auto.\n    (* - *)\n    (* v1/v2 <= 0 <= l1/u2*)\n    apply Z.le_trans with (m:=0%Z); auto.\n    apply Zquot_p_n_n; auto.\n    apply Zquot_n_n_p; auto.\n      symmetry in Heql1b.\n      specialize (Le_False_Lt _ _ Heql1b); intro HZ2.\n      replace (0%Z) with (Z.pred 1); auto.\n      apply Zlt_le_pred_r; auto.\n    (* 1.3.2. v1 <= 0 *)\n    assert(Hv1bT: (v1 <= 0)%Z).\n      specialize (Le_False_Lt _ _ Heqv1b); intro.\n      apply Zlt_le; auto.\n    split.\n    (* - *)\n    (* u1/u2 <= 0 <= v1/v2 *)\n    apply Z.le_trans with (m:=0%Z); auto.\n    apply Zquot_p_n_n; auto.\n      symmetry in Hequ1b.\n      specialize (Le_False_Lt _ _ Hequ1b); intro HZ2.\n      replace (0%Z) with (Z.succ (-1)%Z); auto.\n      apply Zlt_le_succ_l; auto.    \n    apply Zquot_n_n_p; auto.\n    (* - *)\n    (* v1/v2 <= [v1/u2] <= l1/u2*)\n    apply Z.le_trans with (m:=(v1 ÷ u2)%Z); auto.\n    apply Zquot_le_compat_n_n; auto.\n    apply Zquot_antitone; auto.\n  destruct HZ12 as [HZ1 HZ2].\n  apply Zle_true_leb_true; auto.\n - (* 2. 1 <= [l2, u2] *)\n  remember ((1 <=? l2)%Z) as l2b.\n  destruct l2b; subst.\n  symmetry in Heql2b.\n  assert(Hl2bT: (1 <= l2)%Z).\n    apply Zleb_le; auto.\n  apply_Zge_p1_0.\n  \n  remember ((u1 <=? -1)%Z) as u1b.\n  destruct u1b; subst.\n  symmetry in Hequ1b.\n  assert(Hu1bT: (u1 <= -1)%Z).\n    apply Zleb_le; auto.\n  apply_Zle_n1_0.\n\n  (* - case 2.1: 1 <= [l2, u2], [l1, u1] <= -1 *)\n  inversion H2; subst.  \n  assert(HZ1: (l1 ÷ l2 <= v1 ÷ v2)%Z).\n    (* l1/l2 <= [l1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(l1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_n_p; auto.\n      apply Z.le_trans with (m:=u1); auto.\n      apply Z.le_trans with (m:=v1); auto.\n    apply Z_quot_monotone; auto.\n      apply Z.le_trans with (m:=l2); auto.\n  assert(HZ2: (v1 ÷ v2 <= u1 ÷ u2)%Z).\n    (* v1/v2 <= [v1/u2] <= u1/u2 *)\n    apply Z.le_trans with (m:=(v1 ÷ u2)%Z); auto.\n    apply Zquot_le_compat_n_p; auto.\n      apply Z.le_trans with (m:=u1); auto.\n      apply Z.lt_le_trans with (m:=l2); auto.\n    apply Z_quot_monotone; auto.\n      apply Z.le_trans with (m:=l2); auto.    \n      apply Z.le_trans with (m:=v2); auto.\n  apply Zle_true_leb_true; auto.\n  \n  remember ((1 <=? l1)%Z) as l1b.\n  destruct l1b; subst.\n  symmetry in Heql1b.\n  assert(Hl1bT: (1 <= l1)%Z).\n    apply Zleb_le; auto.\n  apply_Zge_p1_0.  \n\n  (* - case 2.2: 1 <= [l2, u2], 1 <= [l1, u1] *)\n  inversion H2; subst.  \n  assert(HZ1: (l1 ÷ u2 <= v1 ÷ v2)%Z).\n    (* l1/u2 <= [l1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(l1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_p_p; auto.\n      apply Z.lt_le_trans with (m:=l2); auto.\n    apply Z_quot_monotone; auto.\n      apply Z.le_trans with (m:=l2); auto.\n  assert(HZ2: (v1 ÷ v2 <= u1 ÷ l2)%Z).\n    (* v1/v2 <= [v1/l2] <= u1/l2 *)\n    apply Z.le_trans with (m:=(v1 ÷ l2)%Z); auto.\n    apply Zquot_le_compat_p_p; auto.\n      apply Z.le_trans with (m:=l1); auto.\n    apply Z_quot_monotone; auto.\n  apply Zle_true_leb_true; auto.\n  \n  (* - case 2.3: 1 <= [l2, u2], 0 in [l1, u1] *)\n  inversion H2; subst.\n  assert(HA1: (l1 <= 0)%Z).\n    symmetry in Heql1b.\n    specialize (Le_False_Lt _ _ Heql1b); intro HZ2.\n    replace (0%Z) with (Z.pred 1); auto.\n    apply Zlt_le_pred_r; auto.\n  assert(HZ12: (l1 ÷ l2 <= v1 ÷ v2)%Z /\\ (v1 ÷ v2 <= u1 ÷ l2)%Z).\n    (* l1/l2 <= [l1/v2] <= v1/v2;  v1/v2 <= [v1/l2] <= u1/l2*)\n    remember (0 <=? v1)%Z as v1b.\n    destruct v1b;\n    symmetry in Heqv1b.\n    (* 2.3.1. 0 <= v1 *)\n    assert(Hv1bT: (0 <= v1)%Z).\n      apply Zleb_le; auto.\n    split.\n    (* - *)\n    (* l1/l2 <= [l1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(l1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_n_p; auto.\n    apply Z_quot_monotone; auto.\n      apply Z.le_trans with (m:=l2%Z); auto.\n    (* - *)\n    (* v1/v2 <= [v1/l2] <= u1/l2*)\n    apply Z.le_trans with (m:=(v1 ÷ l2)%Z); auto.\n    apply Zquot_le_compat_p_p; auto.\n    apply Z_quot_monotone; auto.\n    (* 2.3.2. v1 <= 0 *)\n    assert(Hv1bT: (v1 <= 0)%Z).\n      specialize (Le_False_Lt _ _ Heqv1b); intro.\n      apply Zlt_le; auto.\n    split.\n    (* - *)\n    (* l1/l2 <= [l1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(l1 ÷ v2)%Z); auto.\n    apply Zquot_le_compat_n_p; auto.\n    apply Z_quot_monotone; auto.\n      apply Z.le_trans with (m:=l2%Z); auto.\n    (* - *)\n    (* v1/v2 <= 0 <= u1/l2*)\n    apply Z.le_trans with (m:=0%Z); auto.\n    apply Zquot_n_p_n; auto.\n      apply Z.lt_le_trans with (m:=l2); auto.\n    apply Zquot_p_p_p; auto.\n      symmetry in Hequ1b.\n      specialize (Le_False_Lt _ _ Hequ1b); intro HZ2.\n      replace (0%Z) with (Z.succ (-1)%Z); auto.\n      apply Zlt_le_succ_l; auto.    \n  destruct HZ12 as [HZ1 HZ2].\n  apply Zle_true_leb_true; auto.  \n  \n  (* - case 3: 0 in [l2, u2] *)\n\n  remember ((u1 <=? -1)%Z) as u1b.\n  destruct u1b; subst.\n  symmetry in Hequ1b.\n  assert(Hu1bT: (u1 <= -1)%Z).\n    apply Zleb_le; auto.\n  apply_Zle_n1_0.\n  \n  (* - case 3.1: 0 in [l2, u2], [l1, u1] <= -1 *)\n  inversion H2; subst.\n  (* assert(Hv1lt0: ) *)\n  assert(HZ12: (l ÷ 1 <= v1 ÷ v2)%Z /\\ (v1 ÷ v2 <= (Z.abs l))%Z).\n    (* l1/1 <= [l1/v2] <= v1/v2, v1/v2 <= v1/1 <= (Z.abs l1) *)  \n    remember (0 <=? v2)%Z as v2b.\n    destruct v2b;\n    symmetry in Heqv2b.\n    (* 3.1.1. 0 <= v2 *)\n    assert(Hv2bT: (0 <= v2)%Z).\n      apply Zleb_le; auto.\n    split.\n    (* - *)\n    (* l1/1 <= [l1/v2] <= v1/v2 *)\n    apply Z.le_trans with (m:=(l ÷ v2)%Z); auto.\n      specialize (Zle_lt_or_eq _ _ Hv2bT); intro HZ2.\n      destruct HZ2; subst.\n    apply Zquot_le_compat_n_p; smack.\n    inversion H1.\n    apply Z_quot_monotone; auto.\n    (* - *)\n    (* v1/v2 <= 0 <= (Z.abs l1) *) \n    apply Z.le_trans with (m:=0%Z); auto.\n      apply Zquot_n_p_n; auto.\n      apply Z.le_trans with (m:=u1%Z); auto.\n      apply Zle_eq_e_l; auto.\n      smack.\n    (* 3.1.2. v2 <= 0 *)\n    assert(Hv2bT: (v2 <= 0)%Z).\n      specialize (Le_False_Lt _ _ Heqv2b); intro.\n      apply Zlt_le; auto.\n    split.\n    (* - *)\n    (* l1/1 <= 0 <= v1/v2 *)\n    apply Z.le_trans with (m:=0%Z); auto.\n      rewrite Z.quot_1_r.\n      apply Z.le_trans with (m:=u1%Z); auto.\n      apply Z.le_trans with (m:=v1%Z); auto.\n    apply Zquot_n_n_p; auto.\n      apply Z.le_trans with (m:=u1%Z); auto.\n      apply Zle_eq_e_r; auto.\n    (* - *)\n    (* v1/v2 <= v1/(-1) <= (Z.abs l1)/(-1) *)\n    assert(HA1: (l <= 0)%Z).\n      apply Z.le_trans with (m:= u1%Z); auto.\n      apply Z.le_trans with (m:= v1%Z); auto.\n    rewrite Zabs_quot_neg1; auto.\n    apply Z.le_trans with (m:= (v1 ÷ -1)%Z); auto.\n      apply Zquot_le_compat_n_n; auto.\n      apply Z.le_trans with (m:= u1%Z); auto.\n      smack.\n      apply Zlt_succ_le; auto. simpl.\n      apply Zle_eq_e_r; auto.\n    apply Zquot_antitone; smack.\n  rewrite Z.quot_1_r in HZ12.\n  destruct HZ12 as [HZ3 HZ4].\n  apply Zle_true_leb_true; auto.\n\n\n  remember ((1 <=? l1)%Z) as l1b.\n  destruct l1b; subst.\n  symmetry in Heql1b.\n  assert(Hl1bT: (1 <= l1)%Z).\n    apply Zleb_le; auto.\n  apply_Zge_p1_0.\n  \n  (* - case 3.2: 0 in [l2, u2], 1 <= [l1, u1] *)\n  inversion H2; subst.\n  assert(HZ12: (-u <= v1 ÷ v2)%Z /\\ (v1 ÷ v2 <= u)%Z).\n    (* -u/1 <= [-u/v2] <= v1/v2, v1/v2 <= v1/1 <= u/1 *)  \n    remember (0 <=? v2)%Z as v2b.\n    destruct v2b;\n    symmetry in Heqv2b.\n    (* 3.1.1. 0 <= v2 *)\n    assert(Hv2bT: (0 <= v2)%Z).\n      apply Zleb_le; auto.\n    split.\n    (* - *)\n    (* -u <= 0 <= v1/v2 *)\n    apply Z.le_trans with (m:=0%Z); auto.\n      replace 0%Z with (-0)%Z; auto.\n      apply Le_Neg_Ge; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      apply Z.le_trans with (m:= v1%Z); auto.\n      apply Zquot_p_p_p; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      apply Zle_eq_e_l; auto.\n    (* - *)\n    (* v1/v2 <= v1/1 <= u1/1 *) \n    apply Z.le_trans with (m:=(v1 ÷ 1)%Z); auto.\n      apply Zquot_le_compat_p_p; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      smack.\n      replace 1%Z with (Z.succ 0); auto.\n      apply Zlt_le_succ_l; auto.\n      apply Zle_eq_e_l; auto.\n      replace u with (u ÷ 1)%Z; auto.\n      apply Z_quot_monotone; auto. smack.\n      smack.\n    (* 3.1.2. v2 <= 0 *)\n    assert(Hv2bT: (v2 <= 0)%Z).\n      specialize (Le_False_Lt _ _ Heqv2b); intro.\n      apply Zlt_le; auto.\n    split.\n    (* - *)\n    (* u1/-1 <= u/v2 <= v1/v2 *)\n    assert(HA1: (-u = (u ÷ -1))%Z).\n      rewrite Zquot_n1_opp; auto.\n    rewrite HA1. \n    apply Z.le_trans with (m:=(u ÷ v2)%Z); auto.\n      apply Zquot_le_compat_p_n; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      apply Z.le_trans with (m:= v1%Z); auto.\n      smack.\n      replace (-1)%Z with (Z.pred 0); auto.\n      apply Zlt_le_pred_r; auto.\n      apply Zle_eq_e_r; auto.\n      apply Zquot_antitone; auto.\n    (* - *)\n    (* v1/v2 <= 0 <= u *)\n    apply Z.le_trans with (m:= 0%Z); auto.\n      apply Zquot_p_n_n; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      apply Zle_eq_e_r; auto.\n      apply Z.le_trans with (m:= l1%Z); auto.\n      apply Z.le_trans with (m:= v1%Z); auto.\n  destruct HZ12 as [HZ3 HZ4].\n  apply Zle_true_leb_true; auto.\n\n  (* - case 3.3: 0 in [l2, u2], 0 in [l1, u1] *)\n  inversion H2; subst.\n  assert(HZ12: (- max_abs_f l1 u1 <= v1 ÷ v2)%Z /\\ (v1 ÷ v2 <= max_abs_f l1 u1)%Z).\n    repeat progress match goal with\n    | [H: false = (_ <=? _)%Z |- _] => \n        symmetry in H; specialize (Le_False_Lt _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ; clear H\n    end.\n    repeat progress match goal with\n    | [H: (-1 < ?v)%Z |- _] =>\n        specialize (Zlt_le_succ_l _ _ H); \n        let HZ := fresh \"HZ\" in intro HZ; simpl in HZ; clear H\n    | [H: (?v < 1)%Z |- _] => \n        specialize (Zlt_le_pred_r _ _ H);\n        let HZ := fresh \"HZ\" in intro HZ; simpl in HZ; clear H\n    end.\n\n    remember (0 <=? v1)%Z as v1b.\n    destruct v1b;\n    symmetry in Heqv1b.\n    (* 3.3.1. 0 <= v1 *)\n    assert(Hv1bT: (0 <= v1)%Z).\n      apply Zleb_le; auto.\n      split.\n    (* - *)\n    (* - max_abs_f l1 u1 <= v1 ÷ v2)%Z *)\n    destruct v2.\n    (* 3.3.1.1: 0 <= v1, v2 = 0: conflict *)\n    inversion H1.\n    (* 3.3.1.2: 0 <= v1, v2 > 0 *)\n    apply Z.le_trans with (m:=0%Z).\n      apply max_abs_f_opp_le0; auto.\n      apply Zquot_p_p_p; smack.\n    (* 3.3.1.3: 0 <= v1, v2 < 0 *)\n    apply Z.le_trans with (m:=(v1 ÷ (-1))%Z).    \n      apply Zquot_n1_interval; auto.\n      apply Zquot_le_compat_p_n; auto.\n      smack.\n      replace (-1)%Z with (Z.pred 0); auto.\n      apply Zlt_le_pred_r; auto.\n      apply Zlt_neg_0.\n    (* - *)\n    (* (v1 ÷ v2 <= max_abs_f l1 u1)%Z *)\n    destruct v2.\n    (* 3.3.1.1: 0 <= v1, v2 = 0: conflict *)\n    inversion H1.\n    (* 3.3.1.2: 0 <= v1, v2 > 0 *)\n    apply Z.le_trans with (m:=(v1 ÷ 1)%Z).\n      apply Zquot_le_compat_p_p; auto.\n      smack.\n      replace 1%Z with (Z.succ 0); auto.\n      apply Zlt_le_succ_l; smack.\n      apply Zquot_p1_interval; auto.\n    (* 3.3.1.3: 0 <= v1, v2 < 0 *)\n    apply Z.le_trans with (m:=0%Z).\n      apply Zquot_p_n_n; auto.\n      apply Zlt_neg_0; auto.\n      apply max_abs_f_ge0; auto.\n\n    (* 3.3.2. v1 <= 0 *)\n    assert(Hv1bT: (v1 <= 0)%Z).\n      specialize (Le_False_Lt _ _ Heqv1b); intro.\n      apply Zlt_le; auto.\n    split.\n    (* - *)\n    (* - max_abs_f l1 u1 <= v1 ÷ v2)%Z *)\n    destruct v2.\n    (* 3.3.2.1: v1 <= 0, v2 = 0: conflict *)\n    inversion H1.\n    (* 3.3.2.2: v1 <= 0, v2 > 0 *)\n    apply Z.le_trans with (m:=(v1 ÷ 1)%Z).    \n      apply Zquot_p1_interval; auto.\n      apply Zquot_le_compat_n_p; auto.\n      smack.\n      replace 1%Z with (Z.succ 0); auto.\n      apply Zlt_le_succ_l; smack.\n    (* 3.3.2.3: v1 <= 0, v2 < 0 *)\n    apply Z.le_trans with (m:=0%Z).\n      apply max_abs_f_opp_le0; auto.\n      apply Zquot_n_n_p; auto.\n      apply Zlt_neg_0; auto.\n    (* - *)\n    (* (v1 ÷ v2 <= max_abs_f l1 u1)%Z *)\n    destruct v2.\n    (* 3.3.2.1: v1 <= 0, v2 = 0: conflict *)\n    inversion H1.\n    (* 3.3.2.2: v1 <= 0, v2 > 0 *)\n    apply Z.le_trans with (m:=0%Z).\n      apply Zquot_n_p_n; smack.\n      apply max_abs_f_ge0; auto.    \n    (* 3.3.2.3: v1 <= 0, v2 < 0 *)\n    apply Z.le_trans with (m:=(v1 ÷ -1)%Z).\n      apply Zquot_le_compat_n_n; auto.\n      smack.\n      replace (-1)%Z with (Z.pred 0); auto.\n      apply Zlt_le_pred_r; auto.\n      apply Zlt_neg_0; auto.\n      apply Zquot_n1_interval; auto.\n  destruct HZ12 as [HZ3 HZ4].\n  apply Zle_true_leb_true; auto.\nQed.\n\nLtac apply_divide_in_bound :=\n  match goal with\n  | [H1: in_bound ?v1 (Interval ?l1 ?u1) true,\n     H2: in_bound ?v2 (Interval ?l2 ?u2) true,\n     H3: Zeq_bool ?v2 0 = false,\n     H4: divide_min_max_f ?l1 ?u1 ?l2 ?u2 = (?l, ?u) |- _] =>\n      specialize (divide_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4);\n      let HZ := fresh \"HZ\" in intro HZ\n  | [H1: in_bound ?v1 (Interval ?l1 ?u1) true,\n     H2: in_bound ?v2 (Interval ?l2 ?u2) true,\n     H3: Zeq_bool ?v2 0 = false,\n     H4: (?l, ?u) = divide_min_max_f ?l1 ?u1 ?l2 ?u2 |- _] =>\n      symmetry in H4;\n      specialize (divide_in_bound _ _ _ _ _ _ _ _ H1 H2 H3 H4);\n      let HZ := fresh \"HZ\" in intro HZ\n  end.\n  \n", "meta": {"author": "AdaCore", "repo": "sparkformal", "sha": "51ed67be1b1d80f7f2681237dfbf4ee7add395d6", "save_path": "github-repos/coq/AdaCore-sparkformal", "path": "github-repos/coq/AdaCore-sparkformal/sparkformal-51ed67be1b1d80f7f2681237dfbf4ee7add395d6/spark2014_semantics/src/rt_opt_ZArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.870597266729631, "lm_q1q2_score": 0.7875862832043334}}
{"text": "Require Export Basics.\nRequire Export List.\n\nModule Poly.\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\nFixpoint repeat {X : Type} (x : X) (n : nat) : (list X) :=\n  match n with\n  | 0 => nil\n  | S n' => cons x (repeat x n')\n  end.\n\nCheck repeat.\nExample repeat_1 : repeat 3 3 = cons 3 ( cons 3 ( cons 3 (nil) )).\nProof. reflexivity. Qed.\n\nExample test_repeat2 :\n  repeat false 1 = cons false (nil).\nProof. reflexivity. Qed.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n    | nil => l2\n    | cons h xs => cons h (app xs l2)\n  end.\n\nExample app_1 : app (cons 1 (cons 2 ( cons 3 nil))) (cons 4 (cons 5 nil)) = (cons 1 (cons 2 (cons 3 ( cons 4 ( cons 5 nil))))).\nProof. reflexivity. Qed.\n\nFixpoint snoc {X:Type} (l:list X) (v:X) : (list X) :=\n  match l with\n  | nil      => cons v (nil)\n  | cons h t => cons h (snoc t v)\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.\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.\nExample test_rev2:\n  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\nDefinition mynil : list nat := 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\nDefinition list123''' := [1; 2; 3].\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l0.\n  reflexivity.\n  simpl.\n  rewrite -> IHl0.\n  reflexivity.\nQed.\n\nTheorem app_nil_l : forall (X:Type), forall l: list X,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n\nTheorem app_assoc : forall (A : Type) (l m n : list A),\n l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\n  reflexivity.\nQed.\n\nLemma app_length : forall (A : Type) (l1 l2 : list A),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros A l1 l2.    \n  (* length (l1 ++ l2) = length l1 + length l2 *)\n  induction l1. \n  (* length ([ ] ++ l2) = length [ ] + length l2 *)\n  simpl. \n  (* length l2 = length l2 *)\n  reflexivity.\n  (* length ((x :: l1) ++ l2) = length (x :: l1) + length l2 *)\n  simpl.\n  (* S (length (l1 ++ l2)) = S (length l1 + length l2) *) \n  (* IHl1 : length (l1 ++ l2) = length l1 + length l2 *)\n  rewrite <- IHl1.\n  (* S (length (l1 ++ l2)) = S (length (l1 ++ l2)) *)\n  reflexivity.\nQed.\n\nTheorem rev_app_distr : forall (X : Type) (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1.\n  (* rev ([ ] ++ l2) = rev [ ] ++ rev l2 *)\n  simpl.\n  rewrite -> app_nil_r.\n  reflexivity.\n  (* rev ((x :: l1) ++ l2) = rev (x :: l1) ++ rev l2 *)\n  simpl.\n  rewrite -> IHl1.\n  rewrite <- app_assoc.\n  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  reflexivity.\n  simpl.\n  rewrite -> rev_app_distr. \n  rewrite -> IHl.\n  reflexivity.\nQed.\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\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\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, _) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (_, 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 :: xs, y :: ys => (x, y) :: (combine xs ys)\n  end.\n\nCompute combine [1; 2] [3; 4].\nCompute combine [1; 2] [3; 4; 5].\n\nCheck @combine.\n\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => (nil, nil)\n  | (x, y) :: xs => (x :: fst (split xs), y :: snd (split xs))\n  end.\n\n\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\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\nArguments Some {X} _.\nArguments None {X}.\n\n(** *** *)\n(** We can now rewrite the [index] function so that it works\n    with any type of lists. *)\n\nFixpoint beq_nat (n m : nat) : bool := \n  match n, m with\n  | O, O => true\n  | S _, O => false\n  | O, S _ => false\n  | S n1, S m1 => beq_nat n1 m1\n  end.\n\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_error {X : Type} (l : list X) : option X :=\n  match l with\n    | [] => None\n    | x :: _ => Some x\n  end.\n\nCheck @hd_error.\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.\n\nExample test_hd_error3 : hd_error mynil = None.\nProof. reflexivity. Qed.\n\n\n(* ###################################################### *)\n(** ** High order function *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\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\nExample test_filter1: filter (fun l => beq_nat l 2) [1;2;3;4] = [2].\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 partition {X : Type} (t: X -> bool) (l : list X) : list X * list X :=\n  (filter t l, filter (fun x => negb (t x)) l).\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\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(** *** *)\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\nArguments snoc {X} l v.\n\nTheorem map_snoc : forall (X Y : Type) (f : X -> Y) (x : X) (l : list X),\n  map f (snoc l x) = snoc (map f l) (f x).\nProof.\n  intros X Y f x l.\n  induction l.\n  reflexivity.\n  simpl. rewrite -> IHl. reflexivity.\nQed.\n\nLemma map_distr : 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.\n  reflexivity.\n  simpl. rewrite -> IHl1.\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.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\n  rewrite -> map_distr.\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\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. reflexivity. Qed.\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) : Y :=\n   match l with\n   | nil => b\n   | h :: t => f h ( fold f t b)\n   end.\n\n Compute fold plus [1;2;3;4] 0.\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.\n  reflexivity.\n  simpl.\n  rewrite <- IHl.\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  fold (fun x y => f x :: y) 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.\n  reflexivity.\n  simpl. \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\nCheck @prod_curry.\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  f (fst p) (snd p).\n                     \nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\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\nFixpoint 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(** **** 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\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\nDefinition zero : nat' :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition succ (n : nat') : nat' :=\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\nDefinition plus (n m : nat') : nat' :=\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.\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  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(** Exponentiation *)\n\n(** Hint: Polymorphism plays a crucial role here. However, choosing\n    the right type to iterate over can be tricky. If you hit a\n    \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic. *)\n\nDefinition exp (n m : nat') : nat' :=\n  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 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.", "meta": {"author": "avatar29A", "repo": "SoftwareFoundationSolutions", "sha": "c8f6ab5a6a6ead61668ee800e49e578f303bf473", "save_path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions", "path": "github-repos/coq/avatar29A-SoftwareFoundationSolutions/SoftwareFoundationSolutions-c8f6ab5a6a6ead61668ee800e49e578f303bf473/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7875862712148722}}
{"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\n\n\nTheorem implicate {A B : Prop}:\n  (A -> B) <-> (~ A \\/ B).\nProof.\n  split => [H | H a].\n  + case (ExcludedMiddle A) as [a | nota].\n    - apply (or_intror (H a)).\n    - apply (or_introl nota).\n  + induction H as [nota | b].\n    - case (nota a).\n    - done.\nQed.    \n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "MK", "sha": "ac16a400fa4fcb4c7568d010ec8677defd0a5b94", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-MK", "path": "github-repos/coq/gaxiiiiiiiiiiii-MK/MK-ac16a400fa4fcb4c7568d010ec8677defd0a5b94/Logics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7875462305564757}}
{"text": "Load lab5_task1.\n\nRequire Import Coq.omega.Omega. \n\nFixpoint size (pair : nat*nat) := \n   match pair with\n    | (a,b) => plus a b\n   end.\n\nFunction computeCD (pair : nat*nat) {measure size pair} :=  \n  match pair with\n  | (a,b) => if      beq_nat b 0 then Divisors  ( Z.of_nat a)\n             else if beq_nat a 0 then Divisors  ( Z.of_nat b)\n             else if leb     b a then computeCD ((a-b)%nat,b)\n             else                     computeCD ((b-a)%nat,a)\n  end.\nintros.\nunfold size.\napply leb_complete in teq2.\napply beq_nat_false in teq0.\nomega.\nintros.\nunfold size.\napply beq_nat_false in teq1.\napply leb_iff_conv in teq2.\nomega.\nDefined.\n\n\nEval compute in computeCD (24,16)%nat.\nEval compute in computeCD (144,48)%nat.\nEval compute in computeCD (144,688)%nat.\nEval compute in computeCD (1147,899)%nat.\n\n\nTheorem CDcomputeCorrect : forall p : nat*nat, computeCD p = CD (Z.of_nat (fst p)) (Z.of_nat (snd p)).\n\nProof.\n\n  intros.\n  functional induction (computeCD p) using computeCD_ind.\n\n- apply beq_nat_true in e0.\n  rewrite e0.\n  simpl.\n  rewrite CD0.\n  reflexivity.\n\n- simpl.\n  apply beq_nat_true in e1.\n  rewrite e1.\n  rewrite CDsymmetric.\n  rewrite CD0.\n  reflexivity.\n\n- simpl.\n  rewrite IHe.\n  simpl.\n  apply leb_complete in e2.  \n  assert (Z.of_nat (a-b) = (Z.of_nat a) - (Z.of_nat b)).\n  apply Nat2Z.inj_sub.\n  assumption.\n  rewrite H.\n  rewrite <- CDsubtract.\n  reflexivity.\n\n- simpl.\n  apply leb_complete_conv in e2.\n  rewrite CDsymmetric.\n  rewrite CDsubtract.\n  rewrite IHe.\n  simpl.\n  assert (Z.of_nat (b-a) = (Z.of_nat b) - (Z.of_nat a)).\n  apply Nat2Z.inj_sub.\n  omega.\n  rewrite H.\n  reflexivity.\n\nQed.\n", "meta": {"author": "Toskah", "repo": "Coq", "sha": "956df87bfc60f2ae32b80851978d211f60768de0", "save_path": "github-repos/coq/Toskah-Coq", "path": "github-repos/coq/Toskah-Coq/Coq-956df87bfc60f2ae32b80851978d211f60768de0/lab5/lab5_task2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7875462269406136}}
{"text": "Require Import List Arith.\nSet  Implicit Arguments.\nImport Peano.\n \nSection perms.\nVariable A : Type.\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 \nVariable A_eq_dec : forall a b:A, {a = b} + {a <> b}.\n \nFixpoint nb_occ (a : A) (l : list A)  : nat :=\n match l with\n  | nil => 0\n  | x :: l' =>\n      match A_eq_dec  a x with\n        | left _ => S (nb_occ a l')\n        | right _ => nb_occ a l'\n      end\n end.\n\n \nLemma transpose_nb_occ:\n forall (l l' : list A),\n transpose l l' -> forall (a : A),  nb_occ a l = nb_occ a l'.\nProof.\nintros l l' H; elim H; simpl.\n- intros a b l0 x; case (A_eq_dec x a); case (A_eq_dec x b); simpl; auto.\n- intros a l0 l'0 H0 H1 x; case (A_eq_dec x a); simpl; auto.\nQed.\n \nLemma perm_nb_occ:\n forall (l l' : list A),\n perm l l' -> forall (a : A),  nb_occ a l = nb_occ a l'.\nProof.\nintros l l' H; elim H; auto.\nintros l'0; intros; transitivity (nb_occ a l'0);auto.\napply transpose_nb_occ; auto.\nQed.\n \n\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 check_all_occs (l1 l2 l3 : list A)  : bool :=\n match l3 with\n   nil => true\n  | a :: tl =>\n      if Nat.eqb  (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, Nat.eqb n1 n2 = false ->   n1 <> n2.\nProof.\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 a : A , nb_occ a l1 <> nb_occ a l2 ).\nProof. \n simple induction l3.\n - simpl; intros; discriminate.\n - intros n l IHl; simpl.\n  generalize (@eq_nat_bool_false (nb_occ n l1) (nb_occ n l2)).\n  case (Nat.eqb (nb_occ n l1) (nb_occ n l2)).\n  + auto.\n  + intros; 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.\nProof. \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 \n\nEnd perms.\n\nArguments perm {A} _ _.\n\nLtac\nnoperm eqdec := match goal with\n          | |- ~ perm ?l1 ?l2 => apply (check_all_occs_not_perm  eqdec) end.\n\nRequire Import Peano_dec.\nTheorem not_perm2:\n ~ perm (1 :: (3 :: (2 :: nil))) (3 :: (1 :: (1 :: (4 :: (2 :: nil))))).\nProof. now noperm eq_nat_dec. Qed.\n\n\n\n", "meta": {"author": "raduom", "repo": "coq-art", "sha": "092a8df8e74d7d7a90a2405e4eacf902e528d83a", "save_path": "github-repos/coq/raduom-coq-art", "path": "github-repos/coq/raduom-coq-art/coq-art-092a8df8e74d7d7a90a2405e4eacf902e528d83a/ch9_function_specification/SRC/moreperms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7873314671026955}}
{"text": "Require Import ZArith.\nLocal Open Scope Z_scope.\n\nLtac to_ctx H := generalize H; intro.\n\n(** The following two arithmetic lemma will be used in the proof of\n * correctness. *)\nLemma Z_div_mod_spec :\n  forall a b,\n    b > 0 ->\n    0 <= a - b * (a / b) < b.\nProof.\n  intros.\n  to_ctx (Z_div_mod_eq a b H);\n  to_ctx (Z_mod_lt a b H);\n  omega.\nQed.\n\nLemma seg_dec :\n  forall a b n, a <= n <= b \\/ n < a \\/ n > b.\nProof.\n  intros.\n  destruct Z_le_gt_dec with a n;\n    destruct Z_le_gt_dec with n b;\n  firstorder.\nQed.\n\nLtac destr_case b :=\n  let bb := fresh in\n  let Hbb := fresh in\n  remember b as bb eqn:Hbb;\n  symmetry in Hbb; destruct bb;\n  (apply Z.eqb_eq in Hbb || apply Z.eqb_neq in Hbb);\n  try (exfalso; omega).\n\nLtac destr_case_lt b :=\n  let bb := fresh in\n  let Hbb := fresh in\n  remember b as bb eqn:Hbb;\n  symmetry in Hbb; destruct bb;\n  (apply Z.ltb_lt in Hbb || apply Z.ltb_ge in Hbb);\n  try (exfalso; omega).\n\n", "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/examples/Utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7872607415345119}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_numeric.\nRequire Import numeric_extensions.\nRequire Import kernel_graph.\nRequire Import graph_examples.\nRequire Import graph_handshake.\n\n(** \nGraph examples theorems. \n**)\n\n(* Full graph theorems. *)\n(*#####>*)\nTheorem full_graph_points_number: \n  (forall n : nat, V (K n) = n).\nProof.\n  intro.\n  auto.\nQed.\n\nTheorem full_graph_edges_number_part (n : nat) :\n  edges (K n) = sum' n (fun x => sum' x (fun y => 1)).\nProof. \n  apply change_sum.\n  intros x p.\n  apply change_sum.\n  intros y q.\n  destruct (E_decidable (K n) x y) as [_|G].\n  - reflexivity.\n  - simpl in G.\n    omega.\nQed.\n\nTheorem full_graph_edges_number (n : nat) :\n  2 * edges (K n) = n * (n - 1).\nProof.\n  rewrite full_graph_edges_number_part.\n  rewrite sum_sum_n.\n  auto.\nQed.\n\nTheorem full_graph_degree_part1 (n : nat) (x : nat) (p : x < n):\n  sum' (K n) (fun (i : nat) => if E_decidable (K n) x i then 1 else 0) = \n  sum' (K n) (fun (i : nat) => if Nat.eq_dec x i then 0 else 1).\nProof.\n  apply change_sum.\n  intros y q.\n  set (G := (K n)).\n  destruct (E_decidable G x y) as [A|B].\n  - destruct (Nat.eq_dec x y) as [C|D].\n    + absurd (G x x).\n      * now apply E_irreflexive.\n      * replace y with x in A. \n        apply A.\n    + auto.\n  - destruct (Nat.eq_dec x y) as [C|D].\n    + auto.\n    + absurd (G x y).\n      * auto.\n      * apply D.\nQed.\n\nTheorem full_graph_degree (n : nat) (x : nat) (p : x < n):\n  degree (K n) x = (n - 1).\nProof.\n  unfold degree.\n  unfold count.\n  rewrite (full_graph_degree_part1 n x p).\n  rewrite one_is_found_general.\n  - replace (V (K n)) with n.\n    + omega.\n    + auto. (* omega ne zna razbit definicij auto pa *)\n  - auto.\nQed.\n\n\n(* tole ostaja noter samo ker is tega ideja za splosen hand_shake *)\nTheorem full_graph_sum_degree (n : nat) :\n  sum' n (degree (K n)) = n * (n - 1).\nProof.\n  unfold sum'.\n  replace (sum n (fun (i : nat) (_ : i < n) => degree (K n) i))\n    with  (sum n (fun (i : nat) (_ : i < n) => (n - 1))).\n  - apply (sum_n_krat_k n (n - 1)).\n  - apply change_sum.\n    intros j p.\n    rewrite (full_graph_degree n j); auto.\nQed.\n\nTheorem full_graph_hand_shake (n : nat) :\n  2 * edges (K n) = sum' n (degree (K n)).\nProof.\n  rewrite full_graph_sum_degree.\n  rewrite full_graph_edges_number.\n  auto.\nQed.\n(*#####<*)\n(* Full graph theorems. *)\n\n(* Path theorems. *)\n(*#####>*)\nTheorem path_points_number: \n  (forall n : nat, V (Path n) = n).\nProof.\n  intro.\n  auto.\nQed.\n\nTheorem path_edges_number_part1 (n : nat) (x : nat) (p : x < n):\n  (sum' x (fun y : nat => if E_decidable (Path n) x y then 1 else 0)) =\n  (sum' x (fun y : nat => (if Nat.eq_dec x (S y) then 1 else 0))).\nProof.\n  apply change_sum.\n  intros y q. \n  set (G := (Path n)).\n  destruct (E_decidable G x y) as [A|B].\n  - destruct A.\n    + omega.\n    + rewrite H.\n      destruct (Nat.eq_dec (S y) (S y)); omega.\n  - destruct (Nat.eq_dec x (S y)).\n    + absurd (G x y).\n      * auto.\n      * simpl.\n        auto.\n    + auto.\nQed.\n\nTheorem path_edges_number_part2 (n : nat) (x : nat) (p : x < n):\n  (sum' x (fun y : nat => if E_decidable (Path n) x y then 1 else 0)) = if Nat.eq_dec x 0 then 0 else 1.\nProof.\n  rewrite path_edges_number_part1; auto.\n  destruct (Nat.eq_dec x 0) as [A|B].\n  - rewrite A.\n    apply zero_is_not_succ.\n  - rewrite sum_succ_transformation; auto.\n    + rewrite one_is_found_general; omega.\n    + omega.\nQed.\n\nTheorem path_edges_number_part3 (n : nat):\n  (sum' (Path n) (fun (i : nat) =>\n     sum' i (fun x : nat => if E_decidable (Path n) i x then 1 else 0))) =\n  (sum' (Path n) (fun (i : nat) => if Nat.eq_dec i 0 then 0 else 1)).\nProof.\n  apply change_sum'.\n  intros j p.\n  rewrite (path_edges_number_part2 n j); auto.\nQed.\n\nTheorem path_edges_number (n : nat) :\n  edges (Path n) = n - 1.\nProof.\n  unfold edges.\n  unfold count.\n  rewrite (path_edges_number_part3 n).\n  replace (V (Path n)) with n.\n  - induction n.\n    + auto.\n    + simpl.\n      rewrite sum'_S.\n      rewrite IHn.\n      destruct (Nat.eq_dec n 0); omega.\n  - auto.\nQed.\n(*#####<*)\n(* Path theorems. *)\n\n\n(* Cycle theorems. *)\n(*#####>*)\nTheorem cycle_points_number (n : nat):\n  V (Cycle n) = 3+n.\nProof.\n  auto.\nQed.\n\nTheorem cycle_edges_number_part1 (n : nat) (x : nat) (p : x < 2+n):\n  (sum' x (fun y : nat => if E_decidable (Cycle n) x y then 1 else 0)) =\n  (sum' x (fun y : nat => (if Nat.eq_dec x (S y) then 1 else 0))).\nProof.\n  apply change_sum.\n  intros y q. \n  set (G := (Cycle n)).\n  destruct (E_decidable G x y) as [A|B].\n  - destruct A as [[H1|H2]|[H3|H4]]; try omega.\n    rewrite H2.\n    destruct (Nat.eq_dec (S y) (S y)); omega.\n  - destruct (Nat.eq_dec x (S y)); auto.\n    absurd (G x y); auto.\n    simpl.\n    auto.\nQed.\n  \nTheorem cycle_edges_number_part2 (n : nat) (x : nat) (p : x < 2+n):\n  (sum' x (fun y : nat => if E_decidable (Cycle n) x y then 1 else 0))=if Nat.eq_dec x 0 then 0 else 1.\nProof.\n  rewrite cycle_edges_number_part1; auto.\n  destruct (Nat.eq_dec x 0) as [A|B].\n  - rewrite A.\n    apply zero_is_not_succ.\n  - rewrite sum_succ_transformation; auto.\n    + rewrite one_is_found_general; omega.\n    + omega.\nQed.\n\nTheorem cycle_edges_number_part3 (n : nat) (x : nat) (p : x = 2+n):\n  (sum' x (fun y : nat => if E_decidable (Cycle n) x y then 1 else 0)) =\n  (sum' x (fun y : nat => (if Nat.eq_dec 0 y then 1 else 0) + (if Nat.eq_dec (1+n) y then 1 else 0))).\nProof.\n  apply change_sum.\n  intros y q. \n  set (G := (Cycle n)).\n  destruct (E_decidable G x y) as [A|B].\n  - destruct A as [[H1|H2]|[H3|H4]]; try omega.\n    + assert (y = S n).\n      * omega.\n      * rewrite H.\n        destruct (Nat.eq_dec 0 (S n)); destruct (Nat.eq_dec (1+n) (S n)); auto; omega.\n    + destruct H4 as [_ w].\n      rewrite w.\n      destruct (Nat.eq_dec 0 0); destruct (Nat.eq_dec (1+n) 0); auto; omega.\n  - destruct (Nat.eq_dec 0 y); destruct (Nat.eq_dec (1+n) y); auto; try omega.\n    + absurd (G x y); auto; simpl; auto.\n    + absurd (G x y); auto; simpl; left; right; omega.\nQed.\n\nTheorem cycle_edges_number_part4 (n : nat) (x : nat) (p : x < 3+n):\n  (sum' x (fun y : nat => if E_decidable (Cycle n) x y then 1 else 0))=\n  (if Nat.eq_dec x (2+n) then 1 else 0) + (if Nat.eq_dec x 0 then 0 else 1).\nProof.\n  destruct (Nat.eq_dec x (2+n)) as [A|B].\n  - rewrite (cycle_edges_number_part3 n x A).\n    rewrite vsota_funkcij.\n    assert (q : 0 < x).\n    + omega.\n    + rewrite (one_is_found x 0 q).\n      assert (w : (1+n) < x).\n      * omega.\n      * rewrite (one_is_found x (1+n) w).\n        destruct (Nat.eq_dec x 0); omega.\n  - apply cycle_edges_number_part2.\n    omega.\nQed.\n\nTheorem cycle_edges_number (n : nat):\n  edges (Cycle n) = 3+n.\nProof.\n  unfold edges.\n  assert (sum' (Cycle n) (fun x : nat => count x (E_decidable (Cycle n) x)) =\n         (sum' (Cycle n) (fun x : nat => \n            (if Nat.eq_dec x (2+n) then 1 else 0) + (if Nat.eq_dec x 0 then 0 else 1)))).\n  - apply change_sum.\n    intros x p.\n    unfold count.\n    apply cycle_edges_number_part4.\n    auto.\n  - rewrite H.\n    rewrite vsota_funkcij.\n    replace (V (Cycle n)) with (3+n); auto.\n    assert (q : (2 + n) < (3 + n)).\n    + omega.\n    + rewrite (one_is_found_rv (3 + n) (2 + n) q).\n      assert (p : 0 < (3 + n)).\n      * omega.\n      * rewrite (one_is_found_general_rv (3 + n) 0 0 1 p).\n        omega.\nQed.\n\n\nTheorem cycle_point_degree_part1 (n x y : nat) (p : x < 3+n) (q : y < 3+n):\n  (if E_decidable (Cycle n) x y then 1 else 0) = \n  (if (eq_nat_dec (S x) y) then 1 else 0) +\n  (if (eq_nat_dec x (S y)) then 1 else 0) +\n  (if (eq_nat_dec x 0) then (if (eq_nat_dec y (2 + n)) then 1 else 0) else 0) +\n  (if (eq_nat_dec y 0) then (if (eq_nat_dec x (2 + n)) then 1 else 0) else 0).\nProof.\n  destruct (eq_nat_dec (S x) y);\n  destruct (eq_nat_dec x (S y)); try omega;\n  destruct (eq_nat_dec x 0); destruct (eq_nat_dec y (2 + n));\n  destruct (eq_nat_dec y 0); destruct (eq_nat_dec x (2 + n));\n  try omega;\n  destruct (E_decidable (Cycle n) x y) as [A|B];\n  try omega; \n  try destruct A; try omega; absurd ((Cycle n) x y); auto; simpl; auto.\n  (*\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - destruct A; omega.\n  - destruct A; omega.\n  - destruct A; omega.\n  - destruct A; omega.\n  - absurd ((Cycle n) x y); auto; simpl; auto.\n  - destruct A; omega.\n  - destruct A; omega.\n  - destruct A; omega.\n  *)\nQed.\n\nTheorem cycle_point_degree_part2 (n x : nat) (p : x < 3+n):\n  sum' (3 + n) (fun y : nat => \n  if E_decidable (Cycle n) x y then 1 else 0) = \n  sum' (3 + n) (fun y : nat => \n  (if (eq_nat_dec (S x) y) then 1 else 0) +\n  (if (eq_nat_dec x (S y)) then 1 else 0) +\n  (if (eq_nat_dec x 0) then (if (eq_nat_dec y (2 + n)) then 1 else 0) else 0) +\n  (if (eq_nat_dec y 0) then (if (eq_nat_dec x (2 + n)) then 1 else 0) else 0)).\nProof.\n  apply change_sum.\n  intros y q.\n  apply cycle_point_degree_part1; auto.\nQed.\n\nTheorem cycle_point_degree_part3 (n x : nat) (p : x < 3+n):\n  sum' (3 + n) (fun y : nat => \n  (if (eq_nat_dec (S x) y) then 1 else 0) +\n  (if (eq_nat_dec x (S y)) then 1 else 0) +\n  (if (eq_nat_dec x 0) then (if (eq_nat_dec y (2 + n)) then 1 else 0) else 0) +\n  (if (eq_nat_dec y 0) then (if (eq_nat_dec x (2 + n)) then 1 else 0) else 0)) = 2.\nProof.\n  do 3 rewrite vsota_funkcij.\n  destruct (Nat.eq_dec x 0); destruct (Nat.eq_dec x (2 + n)).\n  - omega.\n  - assert (2 + n < 3 + n) as w; try omega.\n    rewrite (one_is_found_rv (3 + n) (2 + n) w).\n    assert ((S x) < 3 + n) as q; try omega.\n    rewrite (one_is_found (3 + n) (S x) q).\n    rewrite (same_sum' (3 + n) 0). \n    + rewrite (same_sum' (3 + n) 0).\n      * omega.\n      * intros j g1.\n        destruct (Nat.eq_dec j 0); auto.\n    + intros j g1.\n      destruct (Nat.eq_dec x (S j)); auto.\n      omega.\n  - assert (0 < 3 + n) as q; try omega.\n    rewrite (one_is_found_rv (3 + n) 0 q).\n    rewrite (sum_n_krat_k (3 + n) 0).\n    rewrite (same_sum' (3 + n) 0).\n    + replace (sum' (3 + n) (fun x0 : nat => if Nat.eq_dec x (S x0) then 1 else 0))\n        with (sum' (3 + n) (fun x0 : nat => if Nat.eq_dec (x-1) x0 then 1 else 0)).\n      * assert (x - 1 < 3 + n) as w; try omega.\n        rewrite (one_is_found (3 + n) (x - 1) w).\n        omega.\n      * apply change_sum.\n        intros j g1.\n        destruct (Nat.eq_dec x (S j)); destruct (Nat.eq_dec (x - 1) j); omega.\n    + intros j g1.\n      destruct (Nat.eq_dec (S x) j); omega.\n  - rewrite (sum_n_krat_k (3 + n) 0).\n    assert ((S x) < 3 + n) as q; try omega.\n    rewrite (one_is_found (3 + n) (S x) q).\n    replace (sum' (3 + n) (fun x0 : nat => if Nat.eq_dec x (S x0) then 1 else 0))\n      with (sum' (3 + n) (fun x0 : nat => if Nat.eq_dec (x-1) x0 then 1 else 0)).\n    + assert (x - 1 < 3 + n) as w; try omega.\n      rewrite (one_is_found (3 + n) (x - 1) w).\n      rewrite (same_sum' (3 + n) 0).\n      * omega.\n      * intros j g1.\n        destruct (Nat.eq_dec j 0); omega.\n    + apply change_sum.\n      intros j g1.\n      destruct (Nat.eq_dec x (S j)); destruct (Nat.eq_dec (x - 1) j); omega.\nQed.\n\nTheorem cycle_point_degree (n : nat):\n  forall (x : nat),  x < 3 + n -> (degree (Cycle n) x = 2).\nProof.\n  intros x p.\n  unfold degree.\n  unfold count.\n  replace (V (Cycle n)) with (3+n); auto.\n  set (G := Cycle n).\n  rewrite cycle_point_degree_part2; auto.\n  rewrite cycle_point_degree_part3; auto.\nQed.\n\nTheorem cycle_edges_number' (n : nat):\n  2 * edges (Cycle n) = 6 + 2 * n.\nProof.\n  rewrite handshake.\n  assert (sum' (Cycle n) (degree (Cycle n)) = sum' (Cycle n) (fun x => 2)) as A.\n  - apply change_sum.\n    apply cycle_point_degree.\n  - rewrite A.\n    rewrite sum_n_krat_k.\n    simpl.\n    omega.\nQed.\n\n(*#####<*)\n(* Cycle theorems. *)\n\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_examples_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7872607257944196}}
{"text": "(*Functions*)\n\nDefinition f (n: nat) : nat := n + 1.\n\nAbout f.\nPrint f.\nCheck f 3.\nCompute f 3.\n\nDefinition g (n m : nat) : nat := n + m * 2.\nDefinition h (n : nat) : nat -> nat := fun m => n + m * 2.\nCheck g.\nCheck h.\nCompute g 2 3.\nCompute h 2 3.\n\nDefinition repeat_twice (g: nat -> nat) : nat -> nat := \n    fun x => g (g x).\n\nCompute repeat_twice f 2.\nCheck (repeat_twice f).\n\n(*Data types*)\n\nInductive bool := true | false.\nCheck true.\n\nDefinition andb (b1 b2 : bool) := if b1 then b2 else false.\nDefinition orb (b1 b2 : bool) := if b1 then true else b2.\nCheck andb.\nCheck orb.\n\nInductive nat := O | S (n : nat).\nCheck fun n => n+1.\n\nDefinition non_zero n :=\n    match n with\n    | O => false\n    | S p => true\n    end.\n\nFixpoint addn n m :=\n    match n with\n    | O => m\n    | S p => S (addn p m)\n    end.\n\nFixpoint subn m n :=\n    match m, n with\n    | (S p), (S q) => subn p q\n    | _, _ => m\n    end.\n\nFixpoint eqn m n :=\n    match m, n with\n    | O, O => true\n    | S p, S q => eqn p q\n    | _, _ => false\n    end.\n\n", "meta": {"author": "superestos", "repo": "Math-Component", "sha": "e296c4dc129f13e38b6bd2919f0b321c0dc2b009", "save_path": "github-repos/coq/superestos-Math-Component", "path": "github-repos/coq/superestos-Math-Component/Math-Component-e296c4dc129f13e38b6bd2919f0b321c0dc2b009/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693688269984, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7872177888749238}}
{"text": "Require Import Arith Nat.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint len (l : lst) : nat :=\nmatch l with\n  | Nil => 0\n  | Cons a l1 => 1 + (len l1)\nend.\n\nFixpoint rev (l1 l2: lst): lst :=\n  match l1 with\n  | Nil => l2\n  | Cons x l1' => rev l1' (Cons x l2)\n  end. \n\nLemma list_rev2_len_lem: forall l1 l2, \nlen (rev l1 l2) <= (len l1) + (len l2).\nProof.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. intros. \n    apply (le_trans (len (rev l1 (Cons n l2))) (len l1 + len (Cons n l2))\n                    (S (len l1 + len l2))).\n    apply IHl1. simpl. rewrite <- plus_n_Sm. apply le_refl.\nQed.\n\n\nTheorem list_rev2_len: forall l: lst, len (rev l Nil) <= len l.\nProof.\n  induction l.\n  - simpl. apply le_refl.\n  - simpl. rewrite list_rev2_len_lem. simpl. rewrite <- plus_n_O. 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/inequalities/list_rev2_len_le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8615382147637195, "lm_q1q2_score": 0.7871672449035824}}
{"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.\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\nEnd SumArithmetic.\n\n(* Additional lemmas about sum and max big operators. *)\nSection ExtraLemmasSumMax.\n  \n  Lemma leq_big_max I r (P : pred I) (E1 E2 : I -> nat) :\n    (forall i, P i -> E1 i <= E2 i) ->\n      \\max_(i <- r | P i) E1 i <= \\max_(i <- r | P i) E2 i.\n  Proof.\n    move => leE12; elim/big_ind2 : _ => // m1 m2 n1 n2.\n    intros LE1 LE2; rewrite leq_max; unfold maxn.\n    by destruct (m2 < n2) eqn:LT; [by apply/orP; right | by apply/orP; left].\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 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  \nEnd ExtraLemmasSumMax.\n", "meta": {"author": "theAlm", "repo": "prosa_working_dir", "sha": "3d80bb5b069d6923699c30d0c17c7aabaf39e6ec", "save_path": "github-repos/coq/theAlm-prosa_working_dir", "path": "github-repos/coq/theAlm-prosa_working_dir/prosa_working_dir-3d80bb5b069d6923699c30d0c17c7aabaf39e6ec/util/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7871672331539763}}
{"text": "Inductive 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) ..).\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 appendEmptyList : forall list : natlist, list ++ [] = list.   \nProof.\n  intros.\n    \n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. \n    rewrite -> IHxs.\n    reflexivity.\nQed.\n\nTheorem rev_snoc : forall l :natlist, forall n:nat, reverse(snoc l n) = n :: reverse l.\nProof.\nintros.\ninduction l.\nsimpl.\nsimpl. reflexivity.\nsimpl. rewrite -> IHl.\nsimpl. reflexivity.\nQed.\n\nTheorem reverseInvolutive : forall list : natlist, reverse(reverse list) = list.   \nProof.\n  intros.\n    induction list as [| x xs].\n    simpl. reflexivity.\n    simpl.\n    rewrite -> rev_snoc.\nrewrite IHxs.\nreflexivity.\nQed.\n\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_Backup/reverseInvolutive1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7871482166919491}}
{"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), so readers who are already comfortable with\n    these ideas can safely skim or skip this chapter.  However,\n    relations are also a good source of exercises for developing\n    facility with Coq's basic reasoning facilities, so it may be\n    useful to look at this material just after the [IndProp]\n    chapter. *)\n\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(** *** 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. *)\nPrint total_relation.\n(* FILL IN HERE *)\nTheorem total_relation_not_partial :\n  ~ (partial_function total_relation).\nProof. unfold not. unfold partial_function. intros H.\n  assert (ns: 0 = 1). {\n  apply H with (x := 23).\n   - apply tr.\n   - apply tr.\n  }\n  inversion ns.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [empty_relation] that we defined earlier is a\n    partial function. *)\n\nCheck empty_relation.\nPrint empty_relation.\n(* FILL IN HERE *)\nTheorem empty_relation_partial :\n  partial_function empty_relation.\nProof. unfold partial_function.\n  intros x y1 y2 H1 H2.\n  destruct H1. inversion H.\nQed.\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(** *** 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).\nPrint le.\nCheck le.\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 *) \n  - apply le_S in Hnm. apply Hnm.\n  - apply le_S in IHHm'o. apply IHHm'o.\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  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  (* FILL IN HERE *) \n  - inversion Hmo.\n  - apply le_S in Hnm. apply le_trans with (b:= S m).\n    apply Hnm. apply Hmo.\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  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  (* FILL IN HERE *) \n  intros. inversion H.\n  - apply le_n.\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\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 *) intros n H.\n  induction n as [|n' IHn'].\n  - inversion H.\n  - apply IHn'. apply le_S_n. apply H.\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(** *** 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 *) intro H. unfold symmetric in H.\n  assert (1 <= 0) as ns.\n   { apply H. apply le_S. apply le_n. }\n   inversion ns.\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  (* FILL IN HERE *) \n  intros a b Hab Hba. inversion Hab.\n  - reflexivity.\n  - inversion Hba.\n    + rewrite <- H1. symmetry. apply H0.\n    + rewrite <- H0 in H1. rewrite <- H2 in H.\n      assert (contra: S m <= m).\n       { apply le_trans with m0. apply H1.\n         apply le_trans with (S m0). apply le_S. apply le_n. apply H. }\n      apply le_Sn_n in contra. inversion contra.\nQed.\n\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 *) \n  intros n m p H1 H2. unfold lt in H1.\n  apply le_S_n. apply le_trans with m. apply H1. apply H2.\nQed.\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(** *** 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\nPrint clos_refl_trans_ind.\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 *) \n  intros X R x y z Hxy.\n  induction Hxy.\n  - intro H. apply H. \n  - intro H'. apply IHHxy in H'.  apply rt1n_trans with y.\n    apply H. apply H'.\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, 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 *) \n  intros X R x y. split.\n  - intro H. induction H.\n    + apply rsc_R. apply H.\n    + apply rt1n_refl.\n    + apply rsc_trans with y. apply IHclos_refl_trans1. \n      apply IHclos_refl_trans2.\n  - intro H. 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(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/Solutions/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.7871127693561129}}
{"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\nRequire Import Orders NatOrderedType GenericMinMax.\n\n(** * Maximum and Minimum of two natural numbers *)\n\nFixpoint max n m : nat :=\n  match n, m with\n    | O, _ => m\n    | S n', O => n\n    | S n', S m' => S (max n' m')\n  end.\n\nFixpoint min n m : nat :=\n  match n, m with\n    | O, _ => 0\n    | S n', O => 0\n    | S n', S m' => S (min n' m')\n  end.\n\n(** These functions implement indeed a maximum and a minimum *)\n\nLemma max_l : forall x y, y<=x -> max x y = x.\nProof.\n induction x; destruct y; simpl; auto with arith.\nQed.\n\nLemma max_r : forall x y, x<=y -> max x y = y.\nProof.\n induction x; destruct y; simpl; auto with arith.\nQed.\n\nLemma min_l : forall x y, x<=y -> min x y = x.\nProof.\n induction x; destruct y; simpl; auto with arith.\nQed.\n\nLemma min_r : forall x y, y<=x -> min x y = y.\nProof.\n induction x; destruct y; simpl; auto with arith.\nQed.\n\n\nModule NatHasMinMax <: HasMinMax Nat_as_OT.\n Definition max := max.\n Definition min := min.\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 NatHasMinMax.\n\n(** We obtain hence all the generic properties of [max] and [min],\n    see file [GenericMinMax] or use SearchAbout. *)\n\nModule Export MMP := UsualMinMaxProperties Nat_as_OT NatHasMinMax.\n\n\n(** * Properties specific to the [nat] domain *)\n\n(** Simplifications *)\n\nLemma max_0_l : forall n, max 0 n = n.\nProof. reflexivity. Qed.\n\nLemma max_0_r : forall n, max n 0 = n.\nProof. destruct n; auto. Qed.\n\nLemma min_0_l : forall n, min 0 n = 0.\nProof. reflexivity. Qed.\n\nLemma min_0_r : forall n, min n 0 = 0.\nProof. destruct n; auto. Qed.\n\n(** Compatibilities (consequences of monotonicity) *)\n\nLemma succ_max_distr : forall n m, S (max n m) = max (S n) (S m).\nProof. auto. Qed.\n\nLemma succ_min_distr : forall n m, S (min n m) = min (S n) (S m).\nProof. auto. Qed.\n\nLemma plus_max_distr_l : forall n m p, max (p + n) (p + m) = p + max n m.\nProof.\nintros. apply max_monotone. repeat red; auto with arith.\nQed.\n\nLemma plus_max_distr_r : forall n m p, max (n + p) (m + p) = max n m + p.\nProof.\nintros. apply max_monotone with (f:=fun x => x + p).\nrepeat red; auto with arith.\nQed.\n\nLemma plus_min_distr_l : forall n m p, min (p + n) (p + m) = p + min n m.\nProof.\nintros. apply min_monotone. repeat red; auto with arith.\nQed.\n\nLemma plus_min_distr_r : forall n m p, min (n + p) (m + p) = min n m + p.\nProof.\nintros. apply min_monotone with (f:=fun x => x + p).\nrepeat red; auto with arith.\nQed.\n\nHint Resolve\n max_l max_r le_max_l le_max_r\n min_l min_r le_min_l le_min_r : arith v62.\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/MinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.7870550757766408}}
{"text": "From NaturalNumbers Require Export Base Tutorial Addition Multiplication AdvProposition.\n\nRequire Coq.Classes.RelationClasses.\n\nFact succ_inj {a b : mynat} : S a = S b -> a = b.\nProof.\n    intro h.\n    inversion h.\n    reflexivity.\nQed.\n\nFact zero_ne_succ (a : mynat) : 0 <> S a.\nProof.\n    discriminate.\nQed.\n\n(* Level 0 data *)\n(* name `succ_inj`. A function. *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nPeano's axioms actually included two more assumptions, which\nwe haven't seen (or used) yet:\n<ul>\n    <li>`Fact succ_inj {a b : mynat} : S a = S b -> a = b.`</li>\n    <li>`Fact zero_ne_succ (a : mynat) : 0 <> S a.`</li>\n</ul>\nIn the second statement, we see the `<>`, which is the \"not equal\" operator.\nThe reason they have not been introduced yet is that they are implications.\n\nFor `succ_inj a b` this is obvious, as there is an implication in the statement.\nFor the second statement it's a bit more subtle, as `zero_ne_succ a` actually means\n```\n0 = S a -> False.\n``` \nLet's first learn to use `succ_inj` by using it to prove our own variant\nof the statement: `succ_inj'`.\n*)\nLemma succ_inj' {a b : mynat} (hs : S a = S b) : a = b.\nProof.\n    exact (succ_inj hs).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name `succ_succ_inj` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nIn this theorem, we will need to use the `succ_inj` axiom twice.\nYou can do it with `exact` (and maybe some `specialize` statements) or `apply`.\nTry either way to get more used to these tactics!\n*)\nLemma succ_succ_inj {a b : mynat} (h : S (S a) = S (S b)) : a = b.\nProof.\n    exact (succ_inj (succ_inj h)).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 2 data *)\n(* name `succ_eq_succ_of_eq` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nNow let's prove something completely obvious, using the same\ninput for the successor gives the same output. Remember our\nrule of thumb about implications and the `intro` tactic,\nand use it to prove this lemma!\n*)\nLemma succ_eq_succ_of_eq {a b : mynat} : a = b -> S a = S b.\nProof.\n    intro h.\n    now rewrite h.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 data *)\n(* name `eq_iff_succ_eq_succ` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nNow let's combine our previous lemmas into an `<->` statement.\nRemember the `split` tactic to prove the implications separately!\n\nThe first goal will be the same as `succ_inj`, so we can simply\n`exact succ_inj.` to prove it. For the second goal we can do something\nsimilar, but with the statement from the previous lemma.\n*)\nLemma eq_iff_succ_eq_succ (a b : mynat) : S a = S b <-> a = b.\nProof.\n    split.\n    - exact succ_inj.\n    - exact succ_eq_succ_of_eq.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 4 data *)\n(* name `add_right_cancel` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nNow we show that we can cancel on the right when doing addition,\ni.e. that `a = b` whenever `a + t = b + t` for some `t`.\n\nNow the `rewrite` tactic has some more magic to it. We can\nrewrite theorems/hypothesis in <i>other hypotheses</i>!\n\nIf we `intro h.` in this level we get `h : a + t = b + t`.\nDoing induction on `t` gives us hypotheses and a subgoal\n```plaintext\na, b : mynat\nh : a + 0 = b + 0\n============================\na = b\n```\nnow we can type \n```\nrewrite add_zero in h.\n```\nto turn `h : a + 0 = b + 0` into `h : a = b`.\nTry it out below!\n*)\nLemma add_right_cancel (a b t : mynat) : a + t = b + t -> a = b.\nProof.\n    intro h.\n    induction t as [| ? Ht].\n    - rewrite add_zero in h.\n      exact h.\n    - repeat rewrite add_succ in h.\n      inversion h.\n      exact (Ht H0).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 5 data *)\n(* name `add_left_cancel` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nUsing `add_comm`, you can rewrite `add_left_cancel` in a way that\nallows us to simply `exact (add_right_cancel _ _ _).`, i.e. we can\ntell Coq that `add_right_cancel` finishes off the goal, with three\nparamters, which Coq can deduce by itself (denoted by the `_` wildcards).\n*)\nLemma add_left_cancel (t a b : mynat) : t + a = t + b -> a = b.\nProof.\n    rewrite add_comm, (add_comm t b).\n    exact (add_right_cancel _ _ _).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 6 data *)\n(* name `add_right_cancel_iff` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nSimilar to before, it may be useful to have an if and only if\nstatement, so we can `rewrite` it later on. Use the previous \nlevel (`add_right_cancel`) to show this if and only if statement.\n\nTip: if you type\n```\nexact (add_right_cancel _ _ _).\n```\nCoq will figure out what inputs to use by itself!\n*)\nLemma add_right_cancel_iff (t a b : mynat) : a + t = b + t <-> a = b.\nProof.\n    split.\n    - exact (add_right_cancel _ _ _).\n    - intro h.\n      now rewrite h.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 7 data *)\n(* name `eq_zero_of_add_right_eq_self` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nThis next level will be useful later on in Inequality World, when\nwe will prove that `<=` is an antisymmetric relation.\n*)\nLemma eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a -> b = 0.\nProof.\n    intro h.\n    specialize (add_left_cancel a b 0) as h_simpl.\n    rewrite (add_zero a) in h_simpl.\n    exact (h_simpl h).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Unused 8 data *)\n(* name `succ_ne_zero` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Unused prologue *)\n(*\nI don't want to use this level because it introduces\na new tactic that we are not going to use in other levels.\n*)\nLemma succ_ne_zero (a : mynat) : S a <> 0.\nProof.\n    (* todo: symmetry for <>? *)\n    discriminate.\nQed.\n(* Unused epilogue *)\n(* Unused end *)\n\n(* Level 8 data *)\n(* name `add_left_eq_zero` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nInequalities `a <> b` in Coq are defined as `a = b -> False`.\nSo if you read `a <> b`, you should read it as `a = b -> False`.\n\nThe following lemma will be useful in Inequality World.\nIt will require a lot of the tactics you have learnt before,\nlike `destruct`, which similar to logical ors, we can use to\ngo over the cases of a natural number. In this level, it will be\nuseful to start with \n```\ndestruct b.\n- ...\n```\nwhich will create two subgoals, one for `b = 0`, and one for `b = S n`\nfor some natural number `n : mynat`.\n\nAlso remember that any negations (like `~` but also `<>`) can be turned\ninto their `-> False` form by typing `unfold not`. In fact, we can also do\nthis in any hypotheses. Suppose we have `a b : mynat`, then we can\n```\nspecialize (succ_ne_zero (a + b)) as snz.\n```\nto obtain a hypothesis\n```\nsnz : S (a + b) <> 0.\n```\nIf we then\n```\nunfold not in snz.\n```\nit gets turned into\n```\nsnz : S (a + b) = 0 -> False.\n```\nwhich we may be able to use for an `exfalso` proof!\n\n*)\nLemma add_left_eq_zero {a b : mynat} (h : a + b = 0) : b = 0.\nProof.\n    destruct b.\n    - reflexivity.\n    - exfalso.\n      rewrite add_succ in h.\n      specialize (succ_ne_zero (a + b)) as snz.\n      unfold not in snz.\n      exact (snz h).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 9 data *)\n(* name `add_right_eq_zero` *)\n(* tactics exfalso *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nNow that we know `add_left_eq_zero`, proving `add_right_eq_zero` should\nnot be too hard, especially knowing that addition is commutative,\nwitnessed by `add_comm`!\n*)\nLemma add_right_eq_zero {a b : mynat} : a + b = 0 -> a = 0.\nProof.\n    rewrite add_comm.\n    apply add_left_eq_zero.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 10 data *)\n(* name `add_one_eq_succ` *)\n(* tactics symmetry *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nWe know that `succ_eq_add_one (n : mynat) : S n = n + 1.`\nbut it may be useful to know it the other way around as well.\nDid you know that for equalities, we can use the \n`symmetry` tactic to flip the sides of the goal?\n\nTry it out below!\n*)\nLemma add_one_eq_succ (d : mynat) : d + 1 = S d.\nProof.\n    symmetry.\n    exact (succ_eq_add_one _).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 11 data *)\n(* name `ne_succ_self` (boss level!) *)\n(* tactics symmetry *)\n(* theorems zero_ne_succ *)\n(* Level prologue *)\n(*\nAnother boss level! Try to show that numbers\nare not equal to their successor. Remember that\n`unfold not` will turn negations and inequalities\ninto `-> False`!\n*)\nLemma ne_succ_self (n : mynat) : n <> S n.\nProof.\n    unfold not.\n    induction n as [| ? h].\n    - easy.\n    - intro h1.\n      now specialize (succ_inj h1) as h2.\nQed.\n(* Level epilogue *)\n(* Level end *)", "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/AdvAddition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8902942239389253, "lm_q1q2_score": 0.7870550581136616}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export MoreCoq.\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions \n    ([forall x, P]).  \n\n    This chapter will take us on a first tour of the\n    propositional (logical) side of Coq.\n    In particular, we will expand our repertoire of primitive\n    propositions to include _user-defined_ propositions, not just\n    equality propositions (which are more-or-less \"built in\" to Coq). \n*)\n\n\n(** Material covered at OPLSS proper starts here. *)\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.  \n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful]. \n       - Rule [b_5]: The number [5] is [beautiful]. \n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n                              \n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5    \n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)   \n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion hold unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8   \n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8   \n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(** Infinitely many, because we can just keep adding 0: 0 + (3 + 5) is\n    beautiful (0 + 0) + (3 + 5) is beautiful; etc. *)\n\n(** Is it possible to prove this sort of metaproperty in Coq?  Can I\n    prove that there are infinite proofs of the beauty of 8? *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n\n    The rules introduced this way have the same status as proven \n    theorems; that is, they are true axiomatically. \n    So we can use Coq's [apply] tactic with the rule names to prove \n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** Here, B is just a name; we could have used some other name as\n    well. Moreover, here's another proof of the same theorem, where we\n    don't have to provide (m:=n): *)\n\nTheorem beautiful_plus_eight_2: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8). (* Here n is bound in b_sum, not in this proof! *)\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n(** **** Exercise: 2 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    four constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** Was that a typo in the previous para? *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]), \n      - [E] is [b_5] (and [n] is [5]), or \n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n    \n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n \n(* FILL IN HERE *)\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n, \n  gorgeous n -> gorgeous (13+n).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\". \n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous. \nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *) \n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n, \n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n   (* FILL IN HERE *) Admitted.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl. \n   induction H.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"  \n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.  \n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". \n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".  \n    unfold even. apply IHE'.  \nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n))] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)). \nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0. \n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. \n  inversion E as [| n' E']. \n  apply E'. Qed.\n\n(** Why do you only get one case here -- only the inductive case, and\n    not the base case?  According to Tolmach, it's because Coq is\n    smart enough to know that the ev_0 constructor couldn't possibly\n    have been used to build ev (S (S n)), because they don't unify.\n    So, the case that we don't care about gets thrown away.  (If we\n    had been doing this proof on paper, we'd have just written\n    something like \"Can't happen\" for that case.) *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but \n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)    \n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n \n    - Prove that \n       forall l, pal (l ++ rev l).\n    - Prove that \n       forall l, pal l -> l = rev l.\n*)\n\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.  \n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\n\n(** [] *)\n\n\n(* $Date: 2013-07-01 18:48:47 -0400 (Mon, 01 Jul 2013) $ *)\n\n\n", "meta": {"author": "rhs0266", "repo": "software-foundations-1", "sha": "d2b5dd7ac0f936bb5f83451eb0af8c10d57254d9", "save_path": "github-repos/coq/rhs0266-software-foundations-1", "path": "github-repos/coq/rhs0266-software-foundations-1/software-foundations-1-d2b5dd7ac0f936bb5f83451eb0af8c10d57254d9/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.7869589162874884}}
{"text": "Inductive nat : Type := \n  | O\n  | S (n: nat).\n\nDefinition inc (n: nat): nat :=\n  S n.\n\nDefinition dec (n: nat): nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\nFixpoint recur (n: nat): nat :=\n  match n with\n  | O => O\n  | S n' => (recur n')\n  end.\n\nCompute (inc O).\nCompute (dec (S (S O))).\n\nExample arith:\n  (inc O) = (dec (S (S O))).\n\nProof. simpl. reflexivity. Qed.\n\n(* Prove that for all n, (recur n) = 0 by induction *)\nTheorem recur_O: forall n : nat, recur n = O.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = O *) simpl. reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.\n  Qed.\n", "meta": {"author": "ibebrett", "repo": "magpie", "sha": "bd1de5f63ed9a47c36fe81baec117e6153c7aa06", "save_path": "github-repos/coq/ibebrett-magpie", "path": "github-repos/coq/ibebrett-magpie/magpie-bd1de5f63ed9a47c36fe81baec117e6153c7aa06/naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7868927911978558}}
{"text": "\nRequire Import Arith.\n\nSet Implicit Arguments.\nRequire Import List.\nRequire Import ZArith.\n\n\nFixpoint sum (l:list nat) {struct l} : nat :=\n  match l with\n  | nil => O      \n  | b :: m => b + sum(m)\n  end.\n\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\n\n\nLemma Ex1A : forall l1 l2, sum (l1 ++ l2) = sum l1 + sum l2.\nProof.\ninduction l1.\n(* base *)\nintro l2.\nsimpl.\nreflexivity.\n(* ind *)\nsimpl.\nintro l2.\nrewrite IHl1.\nSearchRewrite (_ + _).\nrewrite plus_assoc_reverse.\nreflexivity.\nQed.\n\n\nLemma Ex1B : forall l, sum (rev l) = sum l.\nProof.\ninduction l.\n(* base *)\nsimpl.\nreflexivity.\n(* ind *)\nsimpl.\nrewrite Ex1A.\nsimpl.\nrewrite IHl.\nSearchRewrite (_ + 0).\nrewrite plus_0_r.\nSearchPattern (?x + ?y = ?y + ?x).\nrewrite plus_comm.\nreflexivity.\nQed.\n\nLemma Ex1C : forall l1 l2, Prefix l1 l2 -> sum l1 <= sum l2.\nProof.\ninduction l1.\n(* base *)\nintros l2 H.\nsimpl.\napply le_0_n.\n(* ind *)\nintros l2.\nintro.\ninduction H.\nsimpl.\napply le_0_n.\nsimpl.\nSearchPattern (?x + _ <= ?x + _).\napply plus_le_compat_l.\nassumption.\nQed.s\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/p2ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7868329642868027}}
{"text": "Require Import Omega.\n\nFixpoint lt_rem (a b : nat) : option nat :=\n  match b with\n    | 0 => Some a\n    | S b' => match a with\n                | 0 => None\n                | S a' => lt_rem a' b'\n              end\n  end.\n\nLemma lt_rem_sound\n: forall b a,\n    match lt_rem a b with\n      | None => a < b\n      | Some c => a >= b /\\ a - b = c\n    end.\nProof.\n  induction b; destruct a; simpl; intros; auto.\n  { split; auto. red. omega. }\n  { omega. }\n  { specialize (IHb a).\n    destruct (lt_rem a b); intuition. }\nQed.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/Util/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7868329612612861}}
{"text": "﻿(* 4 Coq で定理の証明 *)\n\n(* \n前述の Curry-Howard 同型のおかげで，Coq の中で直接に命題を書くことができる．その型を\n満すプログラムが見付かれば，定理になる．\n*)\n\n(*\n変数宣言 まずは，準備として論理変数の宣言を行う．Section というコマンドを使うと，局所\n的な論理変数が宣言できるようになる．宣言自体は Variables コマンドを使う．そして，宣言範\n囲が終ると End コマンドでセクションを閉じる．\n*)\n\nSection Koushin.\nVariables P Q : Prop.\n(* P is assumed *)\n(* Q is assumed *)\n\n(*\n論理式自身は型であると先に説明したが，通常の型の型だった Set と異なり，論理式の型は Prop\nになる．普段はあまり影響はないが，区別すると便利なことができる．\n*)\n\n\n(* 命題と証明プログラム *)\n\n(*\nまず，前の二つの恒真式を証明してみよう．\n2 つ目は関数適用だけなので，簡単にできる．\n*)\n\nTheorem modus_ponens : P -> (P -> Q) -> Q. (* 名前を付けなければならない *)\nProof (fun p pq => pq p).\n(* modus_ponens is defined *)\n\nPrint modus_ponens. (* 実際には関数定義と変わらない *)\n(* modus_ponens = fun (p : P) (pq : P -> Q) => pq p *)\n(* : P -> (P -> Q) -> Q  *)\n\n(* しかし，一つ目ではデータの直積ではなく，命題の論理積を使ったので，作り方を調べなければならない．*)\n\nLocate \"/\\\". (* 論理積の定義を調べる *)\n(* Notation Scope                   *)\n(* \"A /\\ B\" := and A B : type_scope *)\n\nPrint and.\n(* Inductive and (A B : Prop) : Prop := conj : A -> B -> A / B *)\n\n(* conj が論理積の証明の構成子だとわかる． *)\nTheorem and_self : P -> P /\\ P.\nProof (fun x => conj x x).\n(* and_self is defined *)\n\n\n(* 作戦 (tactic) の利用 *)\n\n(*\n上のように，プログラムを与えることで定理を証明することができる．しかし，複雑な定理に\nなると，途中で出て来る命題が煩雑になり，正しいプログラムを書くのが至難の技になる．\n通常は，定理は関数と違う定義方法を使う．証明モードに入り，作戦 (tactic) によって証明を\n構築していく．各 tactic は導出規則と対応している．\n *)\n\nTheorem modus_ponens' : P -> (P -> Q) -> Q. (* 異なる名前にする *)\n\n(*\n1 subgoal (* 証明の状況が表示される *)\n\nP : Prop\nQ : Prop\n\n============================\nP -> (P -> Q) -> Q\n*)\n\nProof.\nintros p pq. (* 仮定に名前を付ける (抽象) *)\n\n(*\np : P\npq : P -> Q\n============================\nQ\n *)\n\napply pq. (* 目標を関数 pq の結果とみなす (適用) *)\n\n(*\np : P\npq : P -> Q\n============================\nP\n*)\n\nassumption.\n(* Proof completed. *)\nQed.\n(* modus_ponens’ is defined *)\n\n(* 実際の証明をもう一度みよう．*)\n\nTheorem modus_ponens'' : P -> (P -> Q) -> Q.\nProof.\nintros p pq.\napply pq.\nassumption.\nQed.\n\n(* and_self について同じことをする．*)\nTheorem and_self' : P -> P /\\ P.\nProof.\nintros p.\n\n(*\n1 subgoal\np : P\n============================\nP /\\ P\n*)\n\nsplit. (* 論理積の導入 (∧ 導入) *)\n\n(*\n2 subgoals (* 前提が二つある *)\np : P\n============================\nP\n\nsubgoal 2 is:\nP\n*)\n\nassumption. (* 順番に解いていく *)\n\n(*\n1 subgoal\np : P\n============================\nP\n*)\n\nassumption.\nQed.\n\n(* and_self’ is defined *)\n\nPrint and_self'. (* 実際の定義は前と変わらない *)\n\n(* and_self’ = fun p : P => conj p p *)\n(* : P -> P /\\ P *)\n\n(* セクションを閉じる *)\nEnd Koushin.\n\nPrint and_self.\n(* and_self = *) (* 必要な変数が定義に挿入される *)\n(* fun (P : Prop) (x : P) => conj x x *)\n(* : forall P : Prop, P -> P /\\ P     *)\n\n\n(* 否定に関する定理 *)\n(* 証明状態の表示が作戦を読みにくくするので，これ以降は省くことにする．自分で Coq の中で実行して，確認して下さい．*)\nSection Negation.\n\nVariables P Q : Prop.\nTheorem DeMorgan : ~ (P \\/ Q) -> ~ P /\\ ~ Q.\nProof.\n  unfold not. (* ~ の定義を展開する *)\n  intros npq.\n  split; intros q. (* ; で両方の subgoal について intros q を行う *)\n  apply npq.\n  left. (* ∨ 導入の左を使う *)\n  assumption.\n  apply npq.\n  right.\n  assumption.\nQed.\n(* DeMorgan is defined *)\n\n(*\nしかし，双対的な定理 (￢(P ∧ Q) ⊃ ￢P ∨ ￢Q) は直観主義論理ではなりたたない．\nHypothesisコマンドによって二重否定の除去を仮定すると証明できる．ちなみに，Hypothesis コマンドはVariables の異名でしかなくて，動作は全く同じである．\n*)\n\nHypothesis classic : forall P, ~~P -> P. (* 任意の P について *)\n(* classic is assumed *)\n\nTheorem DeMorgan' : ~ (P /\\ Q) -> ~ P \\/ ~ Q.\nProof.\n  intros npq.\n  apply classic.\n  intro nnpq.\n  apply npq.\n  clear npq. (* 不要な仮定を忘れる *)\n  split; apply classic.\n  intros np.\n  apply nnpq.\n  left.\n  assumption.\n  intros np; apply nnpq; right; assumption.\nQed.\n(* DeMorgan’ is defined *)\nEnd Negation.\n\n(* 仮定を破壊する *)\n\n(*\nCoq の帰納的データ型に対して，値を破壊しながら中身を取り出すという tactic が便利であ\nる．直接に対応する論理規則はないが，当然ながら他の論理規則から同じ結果を導くことは可能である．\n*)\n\nSection Destruct.\nVariables P Q : Prop.\nTheorem and_comm : P /\\ Q -> Q /\\ P.\nProof.\n  intros pq.\n  destruct pq as [p q]. (* 中身を取り出す *)\n  split; assumption. (* 一気に終らせる *)\nQed.\n(* and_comm is defined *)\n\nTheorem or_comm : P \\/ Q -> Q \\/P.\nProof.\n  intros pq.\n  destruct pq as [p | q]. (* 場合が二つある *)\n  right; assumption.\n  left; assumption.\nQed.\n(* or_comm is defined *)\nEnd Destruct.\n\n(* 論理規則と tactic の対応 *)\n\n(*\n論理規則 型付け規則 作戦\n公理 変数 assumption\n⊃ 導入 抽象 intros h\n⊃ 除去 適用 apply h\n矛盾 elimtype False\n∧ 導入 直積 split\n∧ 除去 射影 destruct h as [h1 h2]\n∨ 導入 直和 left, right\n∨ 除去 match destruct h as [h1 | h2]\n*)\n\n\n(* 練習問題 4.1 以下の定理を Coq で証明せよ．*)\nSection Coq2.\nVariables P Q R : Prop.\n\nTheorem imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\nAdmitted.\nTheorem not_false : ~False.\nProof.\nAdmitted.\nTheorem double_neg : P -> ~~P.\nProof.\nAdmitted.\nTheorem contraposition : (P -> Q) -> ~Q -> ~P.\nProof.\nAdmitted.\nTheorem and_assoc : P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\nAdmitted.\nTheorem and_distr : P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\nProof.\nAdmitted.\nTheorem absurd : P -> ~P -> Q.\nProof.\nAdmitted.\n\nEnd Coq2.\n", "meta": {"author": "nagaet", "repo": "Garrigue-lecture-2018_AW", "sha": "9e374dddd36d00928cbfc4c566ce6d622dea003c", "save_path": "github-repos/coq/nagaet-Garrigue-lecture-2018_AW", "path": "github-repos/coq/nagaet-Garrigue-lecture-2018_AW/Garrigue-lecture-2018_AW-9e374dddd36d00928cbfc4c566ce6d622dea003c/coq2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7868243173780404}}
{"text": "(** * Review: Midterm I  *)\n\nRequire Import Coq.omega.Omega.\nRequire Export Logic.\n\n(* ####################################################### *)\n(** \n\nQuestions:\n\n1.  Check (nat -> list nat)    :: Set\n2.  are forall and exists necesary and sufficient to enclose\n    a Prop? what type of expression are allowed to be inside a prop?\n     Set, Prop or Type ??\n\n\n    {Set | Prop } << Type << ... << Type_{n+1} << ..\n\n*)\n\n\nCheck (nat -> list nat).\n\n(* Check (forall n : nat, n). not ok since n in nat *)\nCheck (forall n:Type, n).     (* ok since n in type *)\nCheck (forall n:nat, n = n).  (* ok since [n=n] in prop *)\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\nCheck (le 4).\nCheck (le_S 5 5).\nCheck (forall m : nat, le 5 m -> le 5 (S m)).\n\n\n(* list a = nil | cons a (list a) *)\n\nInductive lists (X : Type) : Type :=\n  | nils  : lists X\n  | conss : X -> lists X -> lists X.          \n\nCheck (conss).             (* forall X : Type, X -> lists X -> lists X *)\nCheck (conss nat 12).      (* lists nat -> lists nat*)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_l :  P -> or P Q\n  | or_r :  Q -> or P Q.\n\nCheck (or_l True).\n                    ", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/midterm1/Review.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7868058086063722}}
{"text": "Add LoadPath \"/home/sami/Programming/langs/coq/\".\nRequire Export Basics.\nRequire Export SZUtility.\n\n(*<------------------------------------------------------------------------->*)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(*<------------------------------------------------------------------------->*)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros.\n  induction n as [| n'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem 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\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros.\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_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros.\n  induction n as [| n'].\n  Case \"n = 0\".\n    simpl.\n    rewrite <- plus_n_O.\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  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\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 : forall n,\n  double n = n + n.\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    rewrite <- plus_n_Sm.\n    reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (m + (n + p) = (m + n) + p).\n    Case \"Proof of assertion\".\n      rewrite -> plus_assoc.\n      reflexivity.\n  assert (n + (m + p) = (n + m) + p).\n    Case \"Proof of assertion\".\n      rewrite -> plus_assoc.\n      reflexivity.\n  rewrite -> H.\n  rewrite -> H0.\n  assert (n + m = m + n).\n    Case \"Proof of assertion\".\n      rewrite -> plus_comm.\n      reflexivity.\n  rewrite -> H1.\n  reflexivity.\nQed.\n\nTheorem plus_swap2 : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_comm.\n  assert (n + p = p + n) as H.\n    Case \"Proof of assertion\".\n      rewrite -> plus_comm.\n      reflexivity.\n  rewrite -> H.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nTheorem mult_m_Sn : forall m n : nat,\n  m * S n = m + m * n.\nProof.\n  intros.\n  induction m as [| m'].\n  Case \"m = 0\".\n    reflexivity.\n  Case \"m = S m'\".\n    simpl.\n    rewrite -> IHm'.\n    rewrite -> plus_swap.\n    reflexivity.\nQed.\n\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    simpl.\n    rewrite -> mult_0_r.\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite <- IHn'.\n    rewrite <- mult_m_Sn.\n    reflexivity.\nQed.\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n  evenb n = negb (evenb (S n)).\nProof.\n  intros.\n  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    destruct n' as [| m].\n      reflexivity.\n      rewrite -> IHn'.\n    rewrite -> negb_involutive.\n    reflexivity.\nQed.\n\n(*<------------------------------------------------------------------------->*)\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\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 zero_nbeq_S : forall n : nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros.\n  destruct n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros.\n  destruct b.\n    reflexivity.\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  induction p as [| p'].\n  Case \"p = 0\".\n    simpl.\n    rewrite -> H.\n    reflexivity.\n  Case \"p = S p'\".\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  destruct n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat,\n  1 * n = n.\nProof.\n  intros.\n  simpl.\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.\n  destruct b as [| b'].\n  Case \"b = true\".\n    simpl.\n    destruct c as [| c'].\n    SCase \"c = true\".\n      reflexivity.\n    SCase \"c = false\".\n      reflexivity.\n  Case \"b = false\".\n    reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros.\n  induction n as [| n'].\n  Case \"n = 0\".\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  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> mult_plus_distr_r.\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'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = Sn'\".\n    simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  replace (n + p) with (p + n).\n  rewrite -> plus_comm.\n  rewrite -> plus_assoc.\n  reflexivity.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\n(*<------------------------------------------------------------------------->*)\n\nInductive bin : Type :=\n  | BO :  bin\n  | BT :  bin -> bin\n  | BST : bin -> bin.\n\nFixpoint bin_incr (a : bin) : bin :=\n  match a with\n  | BO    => BST a\n  | BT b  => BST b\n  | BST c => BT (bin_incr c)\n  end.\n\nFixpoint bin_to_nat (a : bin) : nat :=\n  match a with\n  | BO    => O\n  | BT b  => 2 * (bin_to_nat b)\n  | BST c => 1 + 2 * (bin_to_nat c)\n  end.\n\nTheorem bin_to_nat_pres_incr : forall n : bin,\n  bin_to_nat (bin_incr n) = S (bin_to_nat n).\nProof.\n  intros n.\n  induction n.\n  Case \"n = BO\".\n    reflexivity.\n  Case \"n = BT b\".\n    reflexivity.\n  Case \"n = BST c\".\n    simpl.\n    rewrite -> IHn.\n    rewrite <- plus_n_O.\n    rewrite <- plus_n_O.\n    assert (forall x: nat, S(x) + S(x) = S(S(x + x))) as H.\n      intros x.\n      simpl.\n      rewrite <- plus_n_Sm.\n      reflexivity.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nFixpoint nat_to_bin(n : nat) : bin :=\n  match n with\n  | O    => BO\n  | S n' => bin_incr (nat_to_bin n')\n  end.\n\nTheorem nat_bin_nat : forall n : nat,\n  n = bin_to_nat (nat_to_bin n).\nProof.\n  intros n.\n  induction n.\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> bin_to_nat_pres_incr.\n    rewrite <- IHn.\n    reflexivity.\nQed.\n", "meta": {"author": "sazl", "repo": "SoftwareFoundations", "sha": "547bf8d06459945e42284a6025d2caae00e1544a", "save_path": "github-repos/coq/sazl-SoftwareFoundations", "path": "github-repos/coq/sazl-SoftwareFoundations/SoftwareFoundations-547bf8d06459945e42284a6025d2caae00e1544a/SZInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8723473713594992, "lm_q1q2_score": 0.786788126745775}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreProp. \n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\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 a 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(** 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.\n  inversion H.\n  apply H1. Qed.\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. split.\n  apply HP. apply HQ. apply HR.\n  Qed.\n\n(** **** Exercise: 2 stars (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  induction n. split. intros. apply ev_0.\n  unfold even. intros. inversion H.\n  split. inversion IHn. apply H0.\n  unfold even. simpl. intros. apply ev_SS.\n  inversion IHn. generalize H. unfold even in H0. apply H0.\n  Qed.\n\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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  split. intros. apply H. intros. apply H. Qed.\n  \nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros. inversion H. inversion H0. split.\n  intros. apply H1 in H5. apply H3 in H5. apply H5.\n  intros. apply H4 in H5. apply H2 in H5. apply H5.\n  Qed.\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\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 (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. inversion H. inversion H0. left. apply H2.\n  inversion H1. left. apply H3. assert(H4 : Q /\\ R).\n  split.  apply H2. apply H3. right. apply H4.\n  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. split. intros. split. inversion H. left.\n  apply H0. inversion H0. right. apply H1.\n  inversion H. left. apply H0. inversion H0.\n  right. apply H2. apply or_distributes_over_and_2.\n  Qed.\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\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_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. destruct b.\n  {destruct c.\n   {inversion H. }\n   {right. reflexivity. }\n  }\n  {destruct c.\n   {left. reflexivity. } \n   {left.  reflexivity. } \n  }\nQed.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros. destruct b.\n  {left. reflexivity. }\n  {destruct c.\n   {right. reflexivity. }\n   {inversion H. }\n  }\nQed.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros. destruct b.\n  {destruct c.\n   {inversion H. }\n   {inversion H. }\n  }\n  {destruct c.\n   {inversion H. }\n   {split. reflexivity. reflexivity. }\n  }\nQed.\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\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(* #################################################### *)\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive TrueP : Prop :=\n  |True : TrueP.\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\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, 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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros. unfold not in *. intros. apply H in H1.\n  apply H0 in H1. apply H1. Qed.\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. unfold not. intros. inversion H.\n  apply H1 in H0. apply H0. Qed.\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\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. inversion H. intros. apply SSev__even in H0.\n  apply IHev in H0. apply H0. Qed.\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     from evidence for [P]. *) \n  Abort.\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\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\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  induction n. intros. unfold not in H.\n  {destruct m. \n   {simpl. apply ex_falso_quodlibet.\n    apply H. reflexivity. }\n   {reflexivity. }\n  }\n  {intros. destruct m.\n   {reflexivity. }\n   {simpl. apply IHn. unfold not in *.\n    assert((S n = S m -> False) -> (n = m -> False)).\n    intros. apply H0. rewrite -> H1. reflexivity.\n    apply H0. apply H. }\n  }\n  Qed.\n    \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  unfold not. intros. rewrite -> H0 in H. \n  assert(H1:beq_nat m m = true). apply XEqX.\n  rewrite -> H1 in H. inversion H.\n  Qed.\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  unfold not. intros. apply le_ble_nat in H0.\n  rewrite -> H0 in H. inversion H.\n  Qed.\n\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P]. \n\n*)\n\n\n(** Coq's [Notation] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2). \n  reflexivity.  Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n    time, we can use the convenient shorthand [exists e], which means\n    the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\n\n(** 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(** **** 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.\n  unfold not. intros. inversion H0 as [m Hm].\n  apply Hm. apply H. Qed.\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  unfold excluded_middle. unfold not. intros.\n  assert(H1:P x \\/ (P x -> False)). apply H.\n  inversion H1. apply H2. assert(H3 : exists x : X, P x -> False). \n  exists x. apply H2. apply H0 in H3. inversion H3.\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. split. intros. inversion H. inversion H0.\n  left. exists witness. apply H1. right. exists witness. apply H1.\n  intros. inversion H. inversion H0. exists witness. left. apply H1.\n  inversion H0. exists witness. right. apply H1.\n  Qed.\n\n\n(* Print dist_exists_or. *)\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has (roughly)\n    the following inductive definition. *)\n\n(* (We enclose the definition in a module to avoid confusion with the\n    standard library equality, which we have used extensively\n    already.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n  refl_equal : forall x, eq x x.\n(** Standard infix notation: *)\n\nNotation \"x = y\" := (eq x y) \n                    (at level 70, no associativity) \n                    : type_scope.\n\n(** The definition of [=] is a bit subtle.  The way to think about it\n    is that, given a set [X], it defines a _family_ of propositions\n    \"[x] is equal to [y],\" indexed by pairs of values ([x] and [y])\n    from [X].  There is just one way of constructing evidence for\n    members of this family: applying the constructor [refl_equal] to a\n    type [X] and a value [x : X] yields evidence that [x] is equal to\n    [x]. *)\n\n\n(** **** Exercise: 2 stars (leibniz_equality) *)\n(** The inductive definitions of equality corresponds to _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 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 H1. inversion H. rewrite <- H2. apply H1. Qed.\n\n\n(** 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 compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n*)\n\nLemma four: 2 + 2 = 1 + 3. \nProof.\n  apply refl_equal. \nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\nto now is essentially just short-hand for [apply refl_equal]. *)\n\nEnd MyEquality.\n\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues.  The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests \nin _computations_.  While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious. \n\nIt turns out that we can get the benefits of both forms at once \nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B \n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" :=  (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction \nthat allows us to compute with them.) *) \n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      right. intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. intros contra. inversion contra.\n    SCase \"m = S m'\". \n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply f_equal.  apply eq.\n      right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined. \n\n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either \nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right] \nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean]. \n(Notice that we ended this proof with [Defined] rather than [Qed]. \nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n\nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 -> \n  (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f. intros Hx1.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).   (* observe what appears as a hypothesis *)\n  Case \"k1 = k2\".\n    rewrite <- e.\n    symmetry. apply Hx1.\n  Case \"k1 <> k2\". \n    reflexivity.  Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the \n   version of [override] defined using [beq_nat], where we had to\n   use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n   to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n  intros. unfold override'.\n  destruct (eq_nat_dec k1 k2). reflexivity. reflexivity. Qed.\n\n(* ####################################################### *)\n(** ** Inversion, Again (Advanced) *)\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(** **** Exercise: 1 star, optional (dist_and_or_eq_implies_and) *)  \nLemma dist_and_or_eq_implies_and : forall P Q R,\n       P /\\ (Q \\/ R) /\\ Q = R -> P/\\Q.\nProof.\n  intros.\n  inversion H. inversion H1. split. apply H0. inversion H2.\n  apply H4. rewrite -> H3. apply H4. Qed.\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  |allNil : all X P nil\n  |allCons : forall (x : X) (l : list X), 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 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\nTheorem forallbSpec : forall (X : Type) (test:X -> bool) (l : list X),\n                        forallb test l = true -> all X (fun x => test x = true) l.\nProof.\n  induction l.\n  {intros. apply allNil. }\n  {intros. inversion H. apply andb_prop in H1. inversion H1.\n   apply allCons with (x := x). apply andb_true_intro in H1. symmetry.\n   rewrite -> H0. rewrite -> H0 in H1. apply H1. \n  \n  Admitted.\n\nTheorem forallbSpec2 : 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. induction H. reflexivity.\n  {simpl. apply andb_true_intro. split.\n   {apply H. }\n   {apply IHall. }\n  }\n  Qed.\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example, \n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\nInductive InOrderMerge : forall (X : Type) (l1 l2 l3 : list X), Prop :=\n  |mergeNil : forall (X : Type), InOrderMerge X nil nil nil\n  |mergenilL : forall(X : Type) (l1 : list X), InOrderMerge X l1 nil l1\n  |mergeNilR : forall(X : Type) (l1 : list X), InOrderMerge X l1 l1 nil\n  |mergeCons : forall(X : Type) (x y : X) (l1 l2 l3 : list X), \n                InOrderMerge X l1 l2 l3 -> InOrderMerge X (x::y::l1) (x::l2) (y::l3).\n\n\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l]. \n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X), \n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  induction xs. \n  {intros. simpl in *. inversion H.\n   {right. rewrite <- H0 in H. apply H. }\n   {rewrite <- H1 in H. right. apply H. }\n  }\n  intros. simpl in *. inversion H. left. apply ai_later. \n  Admitted. \n   \n  \n\n\nLemma app_appears_helper : forall (X : Type) (xs ys : list X) (x : X),\n                             appears_in x (xs ++ (x::ys)).\nProof.\n  intros.\n  induction xs.\n  {simpl. apply ai_here. }\n  {simpl. apply ai_later. apply IHxs. }\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. generalize dependent ys. induction xs.\n  {intros. simpl. inversion H. inversion H0. apply H0. }\n  { intros. simpl. inversion H. inversion H0. apply ai_here.\n    apply ai_later. apply IHxs. left. apply H2. apply ai_later.\n    apply IHxs. right. apply H0. }\nQed.\n\n\n \n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n    which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in common. *)\n\nInductive disjoint (X : Type) : list X -> list X -> Prop :=\n  |disjointNil : forall (l : list X), disjoint X nil l\n  |disjointCons : forall (x : X) (l1 l2 : list X), \n                    disjoint X l1 l2 -> not(appears_in x l2) -> \n                    disjoint X (x::l1) 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\nInductive no_repeats (X : Type) : list X -> Prop :=\n  |no_repeats_nil : no_repeats X nil\n  |no_repeats_cons : forall (x : X) (l : list X), \n                       no_repeats X l -> not(appears_in x l) -> no_repeats X (x::l).\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\nTheorem AppNoRepeats : forall (X : Type) (l1 l2 : list X),\n                         no_repeats X l1 -> no_repeats X l2 -> \n                         disjoint X l1 l2 -> no_repeats X (l1++l2).\nProof.\n  induction l1. \n  {intros. simpl. apply H0. }\n  intros. simpl. apply no_repeats_cons. apply IHl1.\n   inversion H. apply H4. apply H0. inversion H1. apply H4.\n   inversion H. apply IHl1 in H4. inversion H4. inversion H1.\n   assert(H12 : l1 = []). destruct l1. reflexivity. inversion H7.\n   rewrite -> H12. simpl. apply H11. Admitted.\n\n\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n  |nostutterNil : nostutter nil\n  |noStutterCons : forall (n : nat), nostutter (n::nil)\n  |nostutterCons2 : forall (n1 n2 : nat) (l : list nat), nostutter (n2 :: l) -> (n1 <> n2) -> nostutter(n1::n2::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].\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\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. unfold not in H5. apply H5. reflexivity. Qed.\n\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some \n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2. \nProof. \n  intros. induction l1.\n  {simpl. reflexivity. }\n  {simpl. apply f_equal. apply IHl1. }\n  Qed.\n    \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 H. \n  {exists []. exists l. simpl. reflexivity. }\n  {inversion IHappears_in. inversion H0. rewrite -> H1.\n   exists (b::witness). exists witness0. simpl. reflexivity. }\n  Qed.\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 |repeatsHit : forall (x : X) (l : list X), appears_in x l -> repeats (x::l)\n |repeatsMiss : forall (x : X) (l : list 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\nTheorem pigeonhole_principle: forall (X:Type) (l1 l2:list X),\n  excluded_middle -> \n  (forall x, appears_in x l1 -> appears_in x l2) -> \n  length l2 < length l1 -> \n  repeats l1.  \nProof.  \n  intros X l1. induction l1.\n  {intros. simpl in *. inversion H1. }\n  {intros. unfold excluded_middle in *. \n   apply IHl1 with(l2 := l2) in H. apply repeatsMiss. apply H. \n   intros. apply IHl1 with(l2 := l2) in H. Admitted.\n\n\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/software_foundations/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7866721312589181}}
{"text": "Require Import Cpdt.CpdtTactics.\n\nCheck (fun x : nat => x).\n\nCheck (fun x : True => x).\n\nCheck I.\n\nCheck (fun _ : False => I).\n\n(* Enumeration *)\n\nInductive unit : Set := tt.\n\nTheorem unit_singleton : forall x : unit, x = tt.\nProof.\n  induction x. reflexivity.\nQed.\n\nCheck unit_ind.\n\n(* Set: the type of normal types, the values of Set are programs.\n * Prop: the type of logical propositions, the values of Prop are proofs\n *)\n\nInductive EmptySet : Set := .\n\nTheorem the_sky_is_falling : forall x : EmptySet, 2 + 2 = 5.\nProof.\n  intros. destruct x.\nQed.\n\nCheck EmptySet_ind.\n\nDefinition e2u (e : EmptySet) : unit := match e with end.\n\nInductive bool : Set :=\n| true\n| false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true => false\n  | false => 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; simpl; reflexivity.\nQed.\n\nTheorem negb_ineq : forall b : bool, negb b <> b.\n  destruct b; discriminate.\nQed.\n\nCheck bool_ind.\n\n(* Simple Recursive Types *)\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\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.\n  intro; reflexivity.\nQed.\n\nTheorem n_plus_O : forall n : nat, plus n O = n.\n  induction n; simpl; auto.\n  rewrite IHn. reflexivity.\nQed.\n\nCheck nat_ind.\n\nTheorem S_inj : forall n m : nat, S n = S m -> n = m.\n  intros. inversion H. auto.\nQed.\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 : forall ls1 ls2 : nat_list,\n    nlength (napp ls1 ls2) = 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 tr1 _ tr2 => plus (nsize tr1) (nsize tr2)\n  end.\n\nFixpoint nsplice (t1 t2 : nat_btree) : nat_btree :=\n  match t1 with\n  | NLeaf => NNode t2 O NLeaf\n  | NNode t1' n t2' => NNode (nsplice t1' t2) n t2'\n  end.\n\nTheorem plus_assoc : forall n1 n2 n3 : nat, 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 : forall tr1 tr2 : nat_btree,\n    nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1).\n  induction tr1; crush.\nQed.\n\nCheck nat_btree_ind.\n\n(* Parameterized Types *)\n\nSection list.\n  Variable T : Set.\n\n  Inductive list : Set :=\n  | Nil : list\n  | Cons : T -> list -> list.\n  \n\n  Fixpoint length (ls : list) : nat :=\n    match ls with\n      | Nil => O\n      | Cons _ ls' => S (length ls')\n    end.\n\n  Fixpoint app (ls1 ls2 : list) : list :=\n    match ls1 with\n      | Nil => ls2\n      | Cons x ls1' => Cons x (app ls1' ls2)\n    end.\n\n  Theorem length_app : forall ls1 ls2 : list, length (app ls1 ls2)\n    = plus (length ls1) (length ls2).\n    induction ls1; crush.\n  Qed.\n\nEnd list.\n\nArguments Nil {T}.\n\nPrint list.\n\nCheck length.\n\nCheck list_ind.\n\n(* Mutually Inductive Types *)\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.\n\nFixpoint elength (el : even_list) : nat :=\n  match el with\n  | ENil => O\n  | ECons _ ol => S (olength ol)\n  end\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\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\nScheme even_list_mut := Induction for even_list Sort Prop\nwith odd_list_mut := Induction for odd_list Sort Prop.\n\nCheck even_list_mut.\nCheck odd_list_mut.\n\nTheorem n_plus_O' : forall n, plus n O = n.\n  apply nat_ind.\n  Undo.\n  apply (nat_ind (fun n => plus n O = n)); crush.\nQed.\n\nTheorem elength_eapp : forall el1 el2 : even_list,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).\nProof.\n  apply (even_list_mut\n           (fun el1 : even_list => forall el2 : even_list,\n                elength (eapp el1 el2) = plus (elength el1) (elength el2))\n           (fun ol : odd_list => forall el : even_list,\n                olength (oapp ol el) = plus (olength ol) (elength el))).\n  - intros. simpl. reflexivity.\n  - intros. simpl. f_equal. rewrite H. reflexivity.\n  - intros. simpl. f_equal. rewrite H. reflexivity.\nQed.\n\n(* Reflexive Types *)\n\n(* Encoding the syntax of first-order logic *)\n\nInductive pformula : Set :=\n| Truth : pformula\n| Falsehood : pformula\n| Conjunction : pformula -> pformula -> pformula\n.\n\nFixpoint pformulaDenote (f : pformula) : Prop :=\n  match f with\n  | Truth => True\n  | Falsehood => False\n  | Conjunction 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.\n\nExample forall_refl : formula := Forall (fun x => Eq x x).\n\nFixpoint formulaDenote (f : formula) : Prop :=\n  match f with\n    | Eq n1 n2 => n1 = n2\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 n1 n2 => Eq n2 n1\n    | And f1 f2 => And (swapper f2) (swapper f1)\n    | Forall f' => Forall (fun n => swapper (f' n))\n  end.\n\nTheorem swapper_preserves_truth : forall f, formulaDenote f -> formulaDenote (swapper f).\n  induction f; crush.\nQed.\n\nCheck formula_ind.\n\n(* An Interlude on Induction Principles *)\n\n(* difference: P ranges over Prop, Type, or Set *)\n\nPrint nat_ind.  (* Prop *)\nPrint nat_rect. (* Type *)\nPrint nat_rec.  (* Set *)\n\n(* Type is a supertype of Set and Prop *)\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 _ rec m => S (rec m)).\n\nTheorem plus_equivalent : plus_recursive = plus_rec.\n  reflexivity.\nQed.\n\n(* nat_rect can be defined manually *)\n\nFixpoint nat_rect' (P : nat -> Type)\n         (HO : P O)\n         (HS : forall n, P n -> P (S n)) (n : nat) : P n :=\n  match n return P n with\n  | O => HO\n  | S n' => HS n' (nat_rect' P HO HS n')\n  end.\n\nSection nat_ind'.\n  Variable P : nat -> Prop.\n  Hypothesis O_case : P O.\n  Hypothesis S_case : forall n : nat, P n -> P (S n).\n\n  Fixpoint nat_ind' (n : nat) : P n :=\n    match n with\n    | O => O_case\n    | S n' => S_case n' (nat_ind' n')\n    end.\n\nEnd nat_ind'.\n\nCheck nat_ind'.\n\n(* Implementing even_list_mut directly *)\n\nSection even_list_mut'.\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),\n      Podd o -> Peven (ECons n o).\n  Hypothesis OCons_case : forall (n : nat) (e : even_list),\n      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 o (odd_list_mut' o)\n    end\n  with\n    odd_list_mut' (o : odd_list) : Podd o :=\n    match o with\n    | OCons n e => OCons_case n e (even_list_mut' e)\n    end.\nEnd even_list_mut'.\n\nSection formula_ind'.\n  Variable P : formula -> Prop.\n  Hypothesis Eq_case : forall n1 n2 : nat, P (Eq n1 n2).\n  Hypothesis And_case : forall f1 f2 : formula,\n    P f1 -> P f2 -> P (And f1 f2).\n  Hypothesis Forall_case : forall f : nat -> formula,\n    (forall n : nat, P (f n)) -> P (Forall f).\n\n  Fixpoint formula_ind' (f : formula) : P f :=\n    match f with\n      | Eq n1 n2 => Eq_case n1 n2\n      | And f1 f2 => And_case f1 f2 (formula_ind' f1) (formula_ind' f2)\n      | Forall f' => Forall_case f' (fun n => formula_ind' (f' n))\n    end.\nEnd formula_ind'.\n\n(* Nested Inductive Types *)\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\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\nPrint True.\nLocate \"/\\\".\nPrint and.\n\nSection nat_tree_ind'.\n  Variable P : nat_tree -> Prop.\n  Hypothesis NNode'_case : forall (n : nat) (ls : list nat_tree),\n      All nat_tree P ls -> P (NNode' n ls).\n\n  (* Neste types requrie neste recursion *)\n  Fixpoint nat_tree_ind' (tr : nat_tree) : P tr :=\n    match tr with\n    | NNode' n ls =>\n        NNode'_case n ls\n                    ((fix list_nat_tree_ind (ls : list nat_tree) : All nat_tree P ls :=\n                        match ls with\n                        | Nil => I\n                        | Cons _ tr' rest => conj (nat_tree_ind' tr')\n                                               (list_nat_tree_ind rest)\n                        end)\n                       ls)\n    end.\n  \nEnd nat_tree_ind'.\n\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 _ h t => plus h (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 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 trs) => NNode' n (Cons _ (ntsplice tr tr2) trs)\n  end.\n\nLemma plus_S : forall n1 n2 : nat,\n  plus n1 (S n2) = S (plus n1 n2).\n  induction n1; crush.\nQed.\n\n#[global] Hint Rewrite plus_S.\n\nTheorem ntsize_ntsplice : forall tr1 tr2 : nat_tree,\n    ntsize (ntsplice tr1 tr2) = plus (ntsize tr2) (ntsize tr1).\nProof.\n  induction tr1 using nat_tree_ind'.\n  crush. destruct ls; crush.\nQed.\n\n(* Manual Proofs About Constructors *)\n\nDefinition toProp (b : bool) := if b then True else False.\n\nTheorem true_neq_false : true <> false.\nProof.\n  red. intro. change (toProp false). rewrite <- H. red. 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. reflexivity.\nQed.\n\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/my_cpdt/InductiveTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.8670357512127873, "lm_q1q2_score": 0.7866721269128516}}
{"text": "From Coq Require Import Arith.\n\nLemma mult_distr_S : forall n p : nat, n * p + p =  S n * p.\nProof. \n simpl; auto with arith. \nQed.\n\nLemma four_n : forall n:nat, \n  n + n + n + n = 4 * n.\nProof.\n  intro n. pattern n at 1.\n  rewrite <- mult_1_l.\n  rewrite mult_distr_S. rewrite mult_distr_S. \n  now rewrite mult_distr_S. \nQed. \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/Pattern.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551495568569, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7865812654373328}}
{"text": "Require Import Arith.\n\nModule Type SemiGroup.\n  Parameter G : Type.\n  Parameter mult : G -> G -> G.\n  Axiom mult_assoc :\n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\nEnd SemiGroup.\n\nModule NatMult_SemiGroup <: SemiGroup.\n  Definition G := nat.\n  Definition mult:= mult%nat.\n  Proposition mult_assoc: \n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\n    apply Nat.mul_assoc.\n  Qed.\n  End NatMult_SemiGroup.\n\nModule NatMax_SemiGroup <: SemiGroup.\n  Definition G := nat.\n  Definition mult:= max%nat.\n  Proposition mult_assoc: \n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\n    apply Nat.max_assoc.\n  Qed.\nEnd NatMax_SemiGroup.\n\nModule SemiGroup_Product (G0 G1:SemiGroup) <: SemiGroup.\n  Definition G := prod G0.G G1.G.\n  Definition mult x y := \n    match x with |(a1, a2) =>\n      match y with |(b1, b2) => (G0.mult a1 b1, G1.mult a2 b2)\n      end\n    end.\n  Proposition mult_assoc: \n    forall x y z : G, mult x (mult y z) = mult (mult x y) z.\n  intros x y z.\n  destruct x, y, z.\n  unfold mult.\n  rewrite G0.mult_assoc.\n  rewrite G1.mult_assoc.\n  reflexivity.\n  Qed.\nEnd SemiGroup_Product.\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/SemiGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724488, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7865342369064059}}
{"text": "Theorem plus_0_r : forall n:nat, n+0=n.\nProof. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_assoc : forall n m l:nat, (m+n)+l=m+(n+l).\nProof. induction m. reflexivity. intros l. simpl. rewrite IHm. reflexivity. Qed.\nTheorem plus_suc_r : forall m n:nat, m+S n=S(m+n).\nProof. induction m. reflexivity. simpl. intros n. rewrite IHm. reflexivity. Qed.\nTheorem mult_1_r : forall n:nat, n*1=n.\nProof. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem plus_comm : forall n m:nat, n+m=m+n.\nProof. induction n. simpl. intros m. rewrite plus_0_r. reflexivity. simpl.\nintros m. rewrite plus_suc_r. rewrite IHn. reflexivity. Qed.\nTheorem mult_0_r : forall n:nat, n*0=0.\nProof. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\nTheorem mult_suc_r : forall n m:nat, n*(S m)=n+n*m.\nProof. induction n. reflexivity. simpl. intros m. rewrite IHn.\nrewrite <- plus_assoc. assert (H1:m+n=n+m). rewrite plus_comm. reflexivity.\nrewrite H1. rewrite plus_assoc. reflexivity. Qed.\nTheorem mult_comm : forall m n:nat, n*m=m*n.\nProof. induction n. simpl. rewrite mult_0_r. reflexivity.\nrewrite mult_suc_r. simpl. rewrite IHn. reflexivity. Qed. \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/mult_comm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7865087379920862}}
{"text": "Require Import Problem.\n\n(*\n  Prove task1 or task2. You can choose either one you like.\n *)\n\n(*Lemma solution1: task1.\nProof.\n  unfold task1.\n  intros.\n  destruct P,Q.\n  (* FILL IN HERE *)\nQed.\n*)\n\nTheorem deMorgan1 (A B: Prop): ~(A\\/B) -> ~A/\\~B.\nProof.\n  intro NAB.\n  split.\n\n  (* NAB: ~(A\\/B) |- ~A *)\n  - intro A1.\n    apply NAB.\n    left.\n    exact A1.\n\n  (* NAB ~(A\\/B) |- ~B *)\n  - intro B1.\n    apply NAB.\n    right.\n    exact B1.\nQed.\n\nTheorem deMorgan2 (A B: Prop): ~A/\\~B -> ~(A\\/B).\nProof.\n  intros NANB AB.\n  destruct NANB as [NA NB].\n  destruct AB as [A1 | B1].\n\n  (* NA:~A, NB:~B A1:A |- False *)\n  - apply NA.\n    exact A1.\n\n  (* NA:~A, NB:~B B1:B |- False *)\n  - apply NB.\n    exact B1.\nQed.\n\nPrint deMorgan2.\n\n\nLemma solution2: task2.\nProof.\n  unfold task2.\n  intros.\n  split.\n  - apply deMorgan2.\n  - apply deMorgan1.\nQed.\n\n\nTheorem solution: task1 \\/ task2.\nProof.\n  right. apply solution2.\nQed.", "meta": {"author": "minaminao", "repo": "proof-assistant-contest", "sha": "d037e5dcff21467f77cdf972a6885412d618f43f", "save_path": "github-repos/coq/minaminao-proof-assistant-contest", "path": "github-repos/coq/minaminao-proof-assistant-contest/proof-assistant-contest-d037e5dcff21467f77cdf972a6885412d618f43f/TopProver/22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7865071863143697}}
{"text": "Inductive bin : Type := \n  | Z : bin\n  | T : bin -> bin\n  | TPO: bin -> bin.\n\nCheck Z.\nCheck T Z.\nCheck TPO Z.\nCheck T (TPO Z).\nCheck TPO (T (TPO Z)).\n\nDefinition incr (n : bin) : bin := \n  match n with\n  | Z => TPO Z \n  | T n' => TPO n'\n  | TPO n' => T (match n' with\n                 | Z => TPO Z\n                 | TPO n'' => T (T n'')\n                 | T n'' => TPO n''\n                 end)\n  end.\n\nCheck incr Z.\nCheck incr (TPO Z).\nCheck incr (T (TPO Z)).\n\nFixpoint bin_to_nat (n: bin): nat := \n  match n with\n  | Z => O\n  | T n' => mult (S (S O)) (bin_to_nat n')\n  | TPO n' => S (mult (S (S O)) (bin_to_nat n'))\n  end.\n\nCheck bin_to_nat Z.\nCheck bin_to_nat (TPO Z).\nCheck bin_to_nat (T (TPO Z)).\nCheck bin_to_nat (TPO (T (T (T (TPO Z))))).\n\nExample bin_0_equals_nat_0: bin_to_nat Z = 0.\nProof. reflexivity. Qed.\nExample bin_1_equals_nat_1: bin_to_nat (TPO Z) = 1.\nProof. reflexivity. Qed.\nExample bin_2_equals_nat_2: bin_to_nat (T (TPO Z)) = 2.\nProof. reflexivity. Qed.\nExample bin_9_equals_nat_9:  bin_to_nat (TPO (T (T (TPO Z)))) = 9.\nProof. reflexivity. Qed.\n\nExample test_bin_incr1: bin_to_nat (incr Z) = 1.\nProof. reflexivity. Qed.\nExample test_bin_incr2: bin_to_nat (incr (TPO Z)) = 2.\nProof. reflexivity. Qed.\nExample test_bin_incr6: bin_to_nat (incr (TPO (T (TPO Z)))) = 6.\nProof. reflexivity. Qed.\nExample test_bin_incr9: bin_to_nat (incr (T (T (T (TPO Z))))) = 9.\nProof. reflexivity. Qed.\n\n\n\n\n\n", "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/chapter02/exercise09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7865071717566803}}
{"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.\nRequire Import Permutation.\n\nRequire Omega.\n\nSet Implicit Arguments.\n\n(* Various Permutation results *)\n\nInfix \"~p\" := (@Permutation _) (at level 80).\n\nSection perm_t.\n\n  Variable X : Type.\n\n  Inductive perm_t : list X -> list X -> Type :=\n    | perm_t_nil   : perm_t nil nil\n    | perm_t_cons  : forall x l m, perm_t l m -> perm_t (x::l) (x::m)\n    | perm_t_swap  : forall x y l, perm_t (x::y::l) (y::x::l)\n    | perm_t_trans : forall l m k, perm_t l m -> perm_t m k -> perm_t l k.\n    \n  Fact perm_t_refl l : perm_t l l.\n  Proof.\n    induction l; simpl; constructor; auto.\n  Qed.\n  \n  Fact perm_t_sym l m : perm_t l m -> perm_t m l.\n  Proof.\n    induction 1; try constructor; auto.\n    apply perm_t_trans with m; auto.\n  Qed.\n  \n  Fact perm_t_app a b l m : perm_t a b -> perm_t l m -> perm_t (a++l) (b++m).\n  Proof.\n    intros H1 H2.\n    apply perm_t_trans with (a++m).\n    clear H1.\n    induction a; simpl; auto; constructor; auto.\n    clear H2.\n    induction H1; simpl; auto.\n    apply perm_t_refl.\n    constructor; auto.\n    constructor.\n    apply perm_t_trans with (m0++m); auto.\n  Qed.\n \n  Fact perm_t_exchg a x b y c : perm_t (a++x::b++y::c) (a++y::b++x::c).\n  Proof.\n    apply perm_t_app.\n    apply perm_t_refl.\n    replace (perm_t (x :: b ++ y :: c) (y :: b ++ x :: c))\n    with (perm_t ((x::b++y::nil)++c) ((y::b++x::nil)++c)).\n    apply perm_t_app.\n    2: apply perm_t_refl.\n    2: repeat (simpl; rewrite app_ass); auto. \n    clear a c.\n    revert x y; induction b as [ | u b IH ]; intros x y; simpl.\n    constructor.\n    apply perm_t_trans with (1 := perm_t_swap _ _ _).\n    apply perm_t_trans with (2 := perm_t_swap _ _ _).\n    constructor; auto.\n  Qed.\n  \n  Fact perm_t_middle x l m : perm_t (x::l++m) (l++x::m).\n  Proof.\n    induction l as [ | y l IH ]; simpl.\n    apply perm_t_refl.\n    apply perm_t_trans with (1 := perm_t_swap _ _ _).\n    constructor; auto.\n  Qed.\n\n  Fact perm_t_Permutation l m : perm_t l m -> l ~p m.\n  Proof.\n    induction 1; auto; try constructor.\n    apply perm_trans with m; auto.\n  Qed.\n  \nEnd perm_t.\n\nSection Permutation_rect.\n\n  Variable (X : Type) (dec : forall x y : X, { x = y } + { x <> y }) (P : list X -> list X -> Type).\n  \n  Definition In_split_dec (x : X) m : In x m -> { l : _ & { r | m = l++x::r } }.\n  Proof.\n    induction m as [ | y m IH ].\n    intros [].\n    destruct (dec x y) as [ E | C ].\n    subst; exists nil, m; auto.\n    intros H.\n    destruct IH as (l & r & ?).\n    destruct H as [ ? | ]; auto.\n    contradict C; auto.\n    exists (y::l), r; simpl; f_equal; auto.\n  Qed.\n  \n  (* Permutation and perm_t are equivalent when equality is decidable\n     on the base type *)\n  \n  Theorem Permutation_perm_t (l m : list X) : l ~p m -> perm_t l m.\n  Proof.\n    revert m; induction l as [ | x l IHl ]; intros m H.\n    apply Permutation_nil in H; subst; auto.\n    constructor.\n    destruct (@In_split_dec x m) as (ll & rr & E).\n    apply Permutation_in with (1 := H); left; auto.\n    subst.\n    apply perm_t_trans with (x::ll++rr).\n    constructor.\n    apply IHl; auto.\n    apply Permutation_cons_app_inv in H; auto.\n    apply perm_t_middle.\n  Qed.\n  \n  (* we derive a Type recursion principle for Permutation when\n     the base type is decidable *)\n \n  Hypothesis (HP0 : P nil nil)\n             (HP1 : forall x l m, l ~p m -> P l m -> P (x::l) (x::m))\n             (HP2 : forall x y l, P (x::y::l) (y::x::l))\n             (HP3 : forall l m k, l ~p m -> P l m -> m ~p k -> P m k -> P l k).\n           \n  Theorem Permutation_rect l m : l ~p m -> P l m.\n  Proof.\n    intros H.\n    apply Permutation_perm_t in H.\n    induction H; auto.\n    apply HP1; auto.\n    apply perm_t_Permutation; auto.\n    apply HP3 with m; auto; \n      apply perm_t_Permutation; auto.\n  Qed.\n\nEnd Permutation_rect.\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.\n    intros H x Hx.\n    apply in_split.\n    apply Permutation_in with (1 := H).\n    auto.\n  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\n  Theorem Permutation_add_one l1 l2 a r1 r2 : l1++r1 ~p l2++r2 -> l1++a::r1 ~p l2++a::r2.\n  Proof.\n    intros H.\n    apply Permutation_trans with (2 := Permutation_middle _ _ _).\n    apply Permutation_sym.\n    apply Permutation_trans with (2 := Permutation_middle _ _ _).\n    apply Permutation_sym.\n    auto.\n  Qed.\n\n  Hint Resolve Permutation_add_one : core.\n    \n  Theorem Permutation_app_intro l1 l2 k r1 r2 : l1++r1 ~p l2++r2 -> l1++k++r1 ~p l2++k++r2.\n  Proof. induction k; auto; simpl;intro; auto. Qed.\n\n  Theorem Permutation_simpl_middle l1 l2 k r1 r2 : l1++k++r1 ~p l2++k++r2 -> l1++r1 ~p l2++r2.\n  Proof.\n    induction k; auto.\n    intros H; simpl in H.\n    apply Permutation_app_inv in H.\n    auto.\n  Qed.\n  \n  Hypothesis eqX_dec : forall x y : X, { x = y } + { x <> y }.\n  \n  Theorem Permutation_dec l m : { l ~p m } + { ~ (l ~p m) }.\n  Proof.\n    revert m; induction l as [ | x l IHl ].\n    intros [ | y m ].\n    left; auto.\n    right; intros C; apply Permutation_nil in C; discriminate.\n    intros m.\n    destruct (In_dec eqX_dec x m) as [ H | H ].\n    assert { m1 : _ & { m2 | m = m1++x::m2 } } as E.\n      induction m as [ | y m IHm ].\n      destruct H.\n      destruct (eqX_dec x y) as [ E | D ].\n      subst; exists nil, m; simpl; auto.\n      destruct IHm as (m1 & m2 & Hm).\n      destruct H; auto; contradict D; auto.\n      exists (y::m1), m2; simpl; f_equal; auto.\n    clear H; destruct E as (m1 & m2 & E).\n    destruct (IHl (m1++m2)) as [ H | H ].\n    subst; left; apply Permutation_cons_app; auto.\n    subst; right; contradict H.\n    apply Permutation_cons_app_inv in H; auto.\n    right; contradict H.\n    apply Permutation_in with (1 := H); left; auto.\n  Qed.\n\n  Fact Permutation_cons_2_inv (x y : X) l m : x::l ~p y::m -> (x = y /\\ l ~p m) \\/ exists k, l ~p y::k /\\ m ~p x::k.\n  Proof.\n    intros H.\n    assert (In x (y::m)) as H1.\n      apply Permutation_in with (1 := H); left; auto.\n    destruct H1 as [ H1 | H1 ].\n    subst x; left; split; auto; revert H; apply Permutation_cons_inv.\n    assert (exists k, m ~p x::k) as Hk.\n      apply in_split in H1.\n      destruct H1 as (m1 & m2 & H1).\n      exists (m1++m2); subst.\n      apply Permutation_sym, Permutation_cons_app; auto.\n    clear H1.\n    destruct Hk as (k & Hk).\n    right; exists k; split; auto.\n    apply Permutation_trans with (2 := perm_skip _ Hk) in H.\n    apply Permutation_trans with (2 := perm_swap _ _ _) in H.\n    revert H; apply Permutation_cons_inv.\n  Qed.\n\nEnd Permutation_tools.\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_perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7864187961355211}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\nModule NatList.\n\n(* Problem examples *)\n(* filterList in terms of a fold does not satisfy any proofs *)\n(* but in terms of pattern matching it does *)\n(* Coq could not determine that subset was reducing in size when in a fold *)\n(* nonzeros when expressed with a filter became hard to prove *)\n(* same with remove decrease count, if count is expressed via a fold it becomes very hard to prove. *)\n\n\n\n(* ################################################################# *)\n(** * Pairs of Numbers *)\n\n(** In an [Inductive] type definition, each constructor can take\n    any number of arguments -- none (as with [true] and [O]), one (as\n    with [S]), or more than one, as here: *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** This declaration can be read: \"There is just one way to\n    construct a pair of numbers: by applying the constructor [pair] to\n    two arguments of type [nat].\" *)\n\nCheck (pair 3 5).\n\n(** Here are two simple functions for extracting the first and\n    second components of a pair.  The definitions also illustrate how\n    to do pattern matching on two-argument constructors. *)\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x y => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new pair notation can be used both in expressions and in\n    pattern matches (indeed, we've actually seen this already in the\n    [Basics] chapter, in the definition of the [minus] function --\n    this works because the pair notation is also provided as part of\n    the standard library): *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try to prove a few simple facts about pairs.\n\n    If we state things in a particular (and slightly peculiar) way, we\n    can complete proofs with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But [reflexivity] is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct]. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** Notice that, unlike its behavior with [nat]s, [destruct]\n    generates just one subgoal here.  That's because [natprod]s can\n    only be constructed in one way. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs, we can describe the\n    type of _lists_ of numbers like this: \"A list is either the empty\n    list or else a pair of a number and another list.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to understand the details of these\n    declarations, but in case you are interested, here is roughly\n    what's going on.  The [right associativity] annotation tells Coq\n    how to parenthesize expressions involving several uses of [::] so\n    that, for example, the next three declarations mean exactly the\n    same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\n\n  Notation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n    + (2 :: [3])].\n\n    (Expressions like \"[1 + 2 :: [3]]\" can be a little confusing when\n    you read them in a [.v] file.  The inner brackets, around 3, indicate\n    a list, but the outer brackets, which are invisible in the HTML\n    rendering, are there to instruct the \"coqdoc\" tool that the bracketed\n    part should be displayed as Coq code rather than running text.)\n\n    The second and third [Notation] declarations above introduce the\n    standard square-bracket notation for lists; the right-hand side of\n    the third one illustrates Coq's syntax for declaring n-ary\n    notations and translating them to nested sequences of binary\n    constructors. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Length *)\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* ----------------------------------------------------------------- *)\n(** *** Append *)\n\n(** The [app] function concatenates (appends) two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4;5] = [4;5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Head (with default) and Tail *)\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tl] returns everything but the first\n    element (the \"tail\").\n    Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1;2;3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tl:              tl [1;2;3] = [2;3].\nProof. reflexivity.  Qed.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, recommended (list_funs)  *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint foldList {b : Type} (f : b -> nat -> b) (acc : b)  (l : natlist) : b :=\n  match l with\n  | nil => acc\n  | h :: t => foldList f (f acc h) t\n  end.\n\nArguments foldList [b].\n\nDefinition mapList (f : nat -> nat) (l : natlist) : natlist :=\n  let\n    myf := fun acc n => f n :: acc\n  in\n  foldList myf [] l.\n\n\n(* Why doesn't this work? *)\nDefinition filterList' (f : nat -> bool) (l : natlist) : natlist :=\n  let\n    myf := fun acc n => if f n\n                     then n :: acc\n                     else acc\n  in\n  foldList myf [] l.\n\n(* But this does? *)\nFixpoint filterList (f : nat -> bool) (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => if f h\n             then h :: filterList f t\n             else filterList f t\n  end.\n\n\nFixpoint nonzeros' (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros' t\n  | h :: t => h :: nonzeros' t\n  end.\n\nDefinition isZero (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | _ => false\n  end.\n\n\nFixpoint nonzeros (l:natlist) : natlist := filterList (fun x => negb (isZero x)) l.\n\nExample test_nonzeros:\n  nonzeros' [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_nonzeros *)\n\nFixpoint oddmembers (l:natlist) : natlist := filterList (fun a => negb (evenb a)) l.\n  (* match l with *)\n  (* | nil => nil *)\n  (* | h :: t => if (negB (even)) *)\n\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_oddmembers *)\n\nDefinition countoddmembers (l:natlist) : nat := length (oddmembers l).\n\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** 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  | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  | l1', nil => l1'\n  | nil, l2' => l2'\n  end.\n\n\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, except that each element\n    can appear multiple times rather than just once.  One possible\n    implementation is to represent a bag of numbers as a list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, recommended (bag_functions)  *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat := length (filterList (beq_nat v) s).\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_count2 *)\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains all\n    the elements of [a] and of [b].  (Mathematicians usually define\n    [union] on multisets a little bit differently -- using max instead\n    of sum -- which is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag :=\n  alternate.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_sum1 *)\n\nDefinition add (v:nat) (s:bag) : bag := app [v] s.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\n(* GRADE_THEOREM 0.5: NatList.test_add1 *)\n(* GRADE_THEOREM 0.5: NatList.test_add2 *)\n\n(* again, what is wrong with the fold definition *)\nDefinition member' (v:nat) (s:bag) : bool :=\n  foldList (fun acc n => beq_nat n v || acc) false s.\n\nDefinition isNil (l :natlist) : bool :=\n  match l with\n  | nil => true\n  | _ => false\n  end.\n\nDefinition member (v:nat) (s:bag) : bool := negb (isNil (filterList (beq_nat v) s)).\n\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.test_member1 *)\n(* GRADE_THEOREM 0.5: NatList.test_member2 *)\n\nExample test_member2:             member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions)  *)\n(** Here are some more [bag] functions for you to practice with. *)\n\n(** When [remove_one] is applied to a bag without the number to remove,\n   it should return the same bag unchanged. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => if (beq_nat h v)\n             then t\n             else h :: remove_one v t\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag := filterList (fun x => negb (beq_nat v x)) s.\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\n(* damn, coq cannot determine the decreasing terms *)\n(* Fixpoint subset' (s1:bag) (s2:bag) : bool := *)\n(*   foldList (fun acc a => *)\n(*               member a s2 && subset' (tl s1) (tl s2)) true s1. *)\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | h :: t => if member h s2\n             then subset t (remove_one h s2)\n             else false\n  end.\n\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_subset3:              subset [2;1;4;1] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (bag_theorem)  *)\n(** Write down an interesting theorem [bag_theorem] about bags\n    involving the functions [count] and [add], and prove it.  Note\n    that, since this problem is somewhat open-ended, it's possible\n    that you may come up with a theorem which is true, but whose proof\n    requires techniques you haven't learned yet.  Feel free to ask for\n    help if you get stuck! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Reasoning About Lists *)\n\n(** As with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification.  For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ...because the [[]] is substituted into the\n    \"scrutinee\" (the expression whose value is being \"scrutinized\" by\n    the match) in the definition of [app], allowing the match itself\n    to be simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons n l' *)\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tl nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Micro-Sermon *)\n\n(** Simply reading example proof scripts will not get you very far!\n    It is important to work through the details of each one, using Coq\n    and thinking about what each step achieves.  Otherwise it is more\n    or less guaranteed that the exercises will make no sense when you\n    get to them.  'Nuff said. *)\n\n(* ================================================================= *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are a\n    little less familiar than standard natural number induction, but\n    the idea is equally simple.  Each [Inductive] declaration defines\n    a set of data values that can be built up using the declared\n    constructors: a boolean can be either [true] or [false]; a number\n    can be either [O] or [S] applied to another number; a list can be\n    either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two arguments together establish\n    the truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros 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 prove it as a separate\n    lemma. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Note that, to make the lemma as general as possible, we\n    quantify over _all_ [natlist]s, not just those that result from an\n    application of [rev].  This should seem natural, because the truth\n    of the goal clearly doesn't depend on the list having been\n    reversed.  Moreover, it is easier to prove the more general\n    property. *)\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all lists [l1] and [l2],\n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _Proof_: By induction on [l1].\n\n    - First, suppose [l1 = []].  We must show\n\n        length ([] ++ l2) = length [] + length l2,\n\n      which follows directly from the definitions of\n      [length] and [++].\n\n    - Next, suppose [l1 = n::l1'], with\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      We must show\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      This follows directly from the definitions of [length] and [++]\n      together with the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n\n          length (rev []) = length [],\n\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n\n          length (rev l') = length l'.\n\n        We must show\n\n          length (rev (n :: l')) = length (n :: l').\n\n        By the definition of [rev], this follows from\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        which, by the previous lemma, is the same as\n\n          length (rev l') + length [n] = S (length l').\n\n        This follows directly from the induction hypothesis and the\n        definition of [length]. [] *)\n\n(** The style of these proofs is rather longwinded and pedantic.\n    After the first few, we might find it easier to follow proofs that\n    give fewer details (which can easily work out in our own minds or\n    on scratch paper if necessary) and just highlight the non-obvious\n    steps.  In this more compressed style, the above proof might look\n    like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]\n     for any [l] (this follows by a straightforward induction on [l]).\n     The main property again follows by induction on [l], using the\n     observation together with the induction hypothesis in the case\n     where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for our\n    present purposes. *)\n\n\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, e.g., using [rewrite].  But in order to refer to a\n    theorem, we need to know its name!  Indeed, it is often hard even\n    to remember what theorems have been proven, much less what they\n    are called.\n\n    Coq's [Search] command is quite helpful with this.  Typing\n    [Search foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following line\n    to see a list of theorems that we have proved about [rev]: *)\n\n(*  Search rev. *)\n\n(** Keep [Search] in mind as you do the following exercises and\n    throughout the rest of the book; it can save you a lot of time!\n\n    If you are using ProofGeneral, you can run [Search] with [C-c\n    C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ================================================================= *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises)  *)\n(** More practice with lists: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. simpl. induction l as [].\n  - (* nil case *) reflexivity.\n  - (* cons case *) simpl. rewrite -> IHl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.app_nil_r *)\n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros. induction l1  as [].\n  - (* nil case *) simpl. rewrite -> app_nil_r. reflexivity.\n  - (* cons *) simpl. rewrite -> IHl1, app_assoc. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.rev_app_distr *)\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n\n  - (* nil *) simpl. reflexivity.\n  - (* cons *) simpl. rewrite -> rev_app_distr, IHl'. simpl. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.rev_involutive *)\n\n(** There is a short solution to the next one.  If you find yourself\n    getting tangled up, step back and try to look for a simpler\n    way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros. rewrite -> app_assoc, app_assoc. reflexivity. Qed.\n(* GRADE_THEOREM 0.5: NatList.app_assoc4 *)\n\n(** An exercise about your implementation of [nonzeros]: *)\n\n\n(* with my fold implementation this became hard to prove *)\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros' (l1 ++ l2) = (nonzeros' l1) ++ (nonzeros' l2).\nProof.\n  intros.  induction l1  as [].\n  - simpl. reflexivity.\n  - destruct n as [| m].\n    + simpl. rewrite -> IHl1. reflexivity.\n    + simpl. rewrite -> IHl1. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist)  *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist' (l1 l2 : natlist) : bool := subset l1 l2 && subset l2 l1.\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | h1 :: t1, h2 :: t2 => beq_nat h1 h2 && beq_natlist t1 t2\n  | nil     , nil      => true\n  | _       , _        => false\n  end.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\nProof. reflexivity.  Qed.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity.  Qed.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity.  Qed.\n\nLemma beq_nat_eq : forall (n:nat),\n    true = beq_nat n n.\nProof.\n  intros. induction n as [].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros. induction l as [].\n  - reflexivity.\n  - simpl. rewrite <- IHl. rewrite <- beq_nat_eq. simpl. 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  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros. simpl. reflexivity. Qed.\n(** [] *)\n\n(** The following lemma about [leb] might help you in the next exercise. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(** **** Exercise: 3 stars, advanced (remove_decreases_count)  *)\nFixpoint count'' (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t => (if beq_nat v h then 1 else 0) + count'' v t\n  end.\n\nFixpoint remove_one' (v:nat) (s:bag) : bag :=\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\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count'' 0 (remove_one' 0 s)) (count'' 0 s) = true.\nProof.\n  intros. induction s as [].\n  - simpl. reflexivity.\n  - destruct n as [| n'].\n    + rewrite -> ble_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum)  *)\n(** Write down an interesting theorem [bag_count_sum] about bags\n    involving the functions [count] and [sum], and prove it using\n    Coq.  (You may find that the difficulty of the proof depends on\n    how you defined [count]!) *)\n(* Ehhhhh no thanks *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective)  *)\n(** Prove that the [rev] function is injective -- that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n    (There is a hard way and an easy way to do this.) *)\n\nTheorem rev_inj: forall (l1 l2 : natlist),\n    rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Options *)\n\n(** Suppose we want to write a function that returns the [n]th\n    element of some list.  If we give it type [nat -> natlist -> nat],\n    then we'll have to choose some number to return when the list is\n    too short... *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** This solution is not so good: If [nth_bad] returns [42], we\n    can't tell whether that value actually appears on the input\n    without further processing. A better alternative is to change the\n    return type of [nth_bad] to include an error value as a possible\n    outcome. We call this type [natoption]. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** We can then change the above definition of [nth_bad] to\n    return [None] when the list is too short and [Some a] when the\n    list has enough members and [a] appears at position [n]. We call\n    this new function [nth_error] to indicate that it may result in an\n    error. *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_error)  *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n    have to pass a default element for the [nil] case.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* FILL IN HERE *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd)  *)\n(** This exercise relates your new [hd_error] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * Partial Maps *)\n\n(** As a final illustration of how data structures can be defined in\n    Coq, here is a simple _partial map_ data type, analogous to the\n    map or dictionary data structures found in most programming\n    languages. *)\n\n(** First, we define a new inductive datatype [id] to serve as the\n    \"keys\" of our partial maps. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** Internally, an [id] is just a number.  Introducing a separate type\n    by wrapping each nat with the tag [Id] makes definitions more\n    readable and gives us the flexibility to change representations\n    later if we wish. *)\n\n(** We'll also need an equality test for [id]s: *)\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(** **** Exercise: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we define the type of partial maps: *)\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [partial_map]: either using the constructor [empty] to represent an\n    empty partial map, or by applying the constructor [record] to\n    a key, a value, and an existing [partial_map] to construct a\n    [partial_map] with an additional key-to-value mapping.\" *)\n\n(** The [update] function overrides the entry for a given key in a\n    partial map (or adds a new entry if the given key is not already\n    present). *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** Last, the [find] function searches a [partial_map] for a given\n    key.  It returns [None] if the key was not found and [Some val] if\n    the key was associated with [val]. If the same key is mapped to\n    multiple values, [find] will return the first one it\n    encounters. *)\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_id x y\n                     then Some v\n                     else find x d'\n  end.\n\n\n(** **** Exercise: 1 star (update_eq)  *)\nTheorem update_eq :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** Exercise: 2 stars (baz_num_elts)  *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have?\n    (Explain your answer in words, preferrably English.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n", "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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.9252299586383206, "lm_q1q2_score": 0.7864187886649394}}
{"text": "Theorem biconditional_elimination :\n  forall (p q : Prop), (p <-> q) <-> ((p -> q) /\\ (q -> p)).\nProof.\n  intros p q.\n  split.\n\n  intro H.\n  destruct H as [H G].\n  split.\n\n  apply H.\n  apply G.\n\n  intro H.\n  destruct H as [H G].\n  split.\n\n  apply H.\n  apply G.\nQed.\n\nTheorem non_contradiction :\n  forall (p : Prop), (p /\\ ~p) <-> False.\nProof.\n  intro p.\n  split.\n\n  intro H.\n  destruct H as [H G].\n\n  absurd p.\n  apply G.\n  apply H.\n\n  intro H.\n  contradict H.\nQed.\n\nTheorem commutativity_and :\n  forall (p q : Prop), p /\\ q <-> q /\\ p.\nProof.\n  intros p q.\n  split.\n\n  intro H.\n  destruct H as [H G].\n  split.\n\n  apply G.\n  apply H.\n\n  intro H.\n  destruct H as [H G].\n  split.\n\n  apply G.\n  apply H.\nQed.\n\nTheorem commutativity_or :\n  forall (p q : Prop), p \\/ q <-> q \\/ p.\nProof.\n  intros p q.\n  split.\n\n  intro H.\n  destruct H as [H | H].\n\n  right.\n  apply H.\n\n  left.\n  apply H.\n\n  intro H.\n  destruct H as [H | H].\n\n  right.\n  apply H.\n\n  left.\n  apply H.\nQed.\n\nTheorem associativity_and :\n  forall (p q r : Prop), p /\\ (q /\\ r) <-> (p /\\ q) /\\ r.\nProof.\n  intros p q r.\n  split.\n\n  intro H.\n  destruct H as [H G].\n  destruct G as [G I].\n  split.\n  split.\n\n  apply H.\n  apply G.\n  apply I.\n\n  intro H.\n  destruct H as [H G].\n  destruct H as [H I].\n\n  split.\n  apply H.\n\n  split.\n  apply I.\n\n  apply G.\nQed.\n\nTheorem associativity_or :\n  forall (p q r : Prop), p \\/ (q \\/ r) <-> (p \\/ q) \\/ r.\nProof.\n  intros p q r.\n  split.\n\n  intro H.\n  destruct H as [H | H].\n\n  left.\n  left.\n  apply H.\n\n  destruct H as [H | H].\n  left.\n  right.\n  apply H.\n\n  right.\n  apply H.\n\n  intro H.\n  destruct H as [H | H].\n  destruct H as [H | H].\n\n  left.\n  apply H.\n\n  right.\n  left.\n  apply H.\n\n  right.\n  right.\n  apply H.\nQed.\n\nTheorem idempotency_and :\n  forall (p : Prop), p /\\ p <-> p.\nProof.\n  intro p.\n  split.\n\n  intro H.\n  destruct H as [H _].\n\n  apply H.\n\n  intro H.\n  split.\n\n  apply H.\n  apply H.\nQed.\n\nTheorem idempotency_or :\n  forall (p : Prop), p \\/ p <-> p.\nProof.\n  intro p.\n  split.\n\n  intro H.\n  destruct H as [H | G].\n\n  apply H.\n  apply G.\n\n  intro H.\n  left.\n\n  apply H.\nQed.\n\nTheorem absorption_and :\n  forall (p q : Prop), (p /\\ (p \\/ q)) <-> p.\nProof.\n  intros p q.\n  split.\n\n  intro H.\n  destruct H as [H _].\n  apply H.\n\n  intro H.\n  split.\n\n  apply H.\n\n  left.\n  apply H.\nQed.\n", "meta": {"author": "kit-ty-kate", "repo": "coq-playground", "sha": "f70e7d23a7fd5949488b8ef7c298820ac2365021", "save_path": "github-repos/coq/kit-ty-kate-coq-playground", "path": "github-repos/coq/kit-ty-kate-coq-playground/coq-playground-f70e7d23a7fd5949488b8ef7c298820ac2365021/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.7864054772412774}}
{"text": "Require Import ZArith.\nSection section_for_chapter_6.\nInductive month : Set :=\n  | January : month\n  | February : month\n  | March : month\n  | April : month\n  | May : month\n  | June : month\n  | July : month\n  | August : month\n  | September : month\n  | October : month\n  | November : month\n  | December : month.\n  \n(* 6.1 p127 *)\nInductive season : Set :=\n  | Spring : season\n  | Summer : season\n  | Autumn : season\n  | Winter : season.\n\n(* 6.2 p127 *)\nCheck bool_ind.\nCheck bool_rec.\n\n(* 6.3 p128 *)\nTheorem bool_equal : forall b:bool, b = true \\/ b = false.\nProof.\nintros.\npattern b.\napply bool_ind;[left; reflexivity | right; reflexivity].\nQed.\n\nTheorem bool_equal' : forall b:bool, b = true \\/ b = false.\nProof(bool_ind \n  (fun b => b = true \\/ b = false) \n  (or_introl (eq_refl true))\n  (or_intror (eq_refl false))).\n\n(* 6.4 p132 *)\nCheck month_rec.\n\nDefinition mtos := month_rect (fun m:month => season) \n  Winter Winter Winter\n  Spring Spring Spring\n  Summer Summer Summer\n  Autumn Autumn Autumn.\n\n(* 6.5 p132 *)\n\nDefinition month_length (leap:bool) :=\n  month_rec (fun m:month => nat)\n  31 (if leap then 29 else 28) 31 30 31 30 31 31 30 31 30 31.\n\nFixpoint nat_even (n:nat) : bool :=\n  match n with\n    | O => true\n    | (S O) => false\n    | (S (S m)) => nat_even m\n  end.\n\nDefinition month_length_even (leap:bool) (m:month):=\n  if nat_even (month_length leap m) then true else false.\n\nEval compute in month_length_even true February.\nEval compute in month_length_even false February.\n\n(* 6.6 p132 *)\n\nDefinition bool_not (b:bool) : bool := if b then false else true.\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\nDefinition bool_eq (b b':bool) := if b then b' else bool_not b'.\n\nTheorem bool_xor_not_eq :\n forall b1 b2:bool, bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof.\nintros. \ncase b1. simpl; trivial. \ncase b2. simpl; trivial. simpl; trivial.\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.\nintros. \ncase b1. simpl; trivial. \ncase b2. simpl; trivial. simpl; trivial.\nQed.\n\nTheorem bool_not_not : forall b:bool, bool_not (bool_not b) = b.\nProof.\nintros. \ncase b. simpl; trivial. simpl; trivial.\nQed.\n\nTheorem bool_ex_middle : forall b:bool, bool_or b (bool_not b) = true.\nProof.\nintros. \ncase b. simpl; trivial. simpl; trivial.\nQed.\n\nTheorem bool_eq_reflect : forall b1 b2:bool, bool_eq b1 b2 = true -> b1 = b2.\nProof.\nintros b1 b2. \ncase b1. simpl. intros. rewrite H. trivial.  \ncase b2. simpl; trivial. simpl; trivial.\nQed.\n\nTheorem bool_eq_reflect' : forall b1 b2:bool, bool_eq b1 b2 = true -> b1 = b2.\nProof.\n  intros b1 b2. case b1; case b2; simpl; trivial.\n  discriminate.\nQed.\n\n\nTheorem bool_eq_reflect2 : forall b1 b2:bool, b1 = b2 -> bool_eq b1 b2 = true.\nProof.\nintros b1 b2. \ncase b1. simpl. intros. rewrite H. trivial.  \ncase b2. simpl; trivial. simpl; trivial.\nQed.\n\nTheorem bool_eq_reflect2' : forall b1 b2:bool, b1 = b2 -> bool_eq b1 b2 = true.\nProof.\n  intros b1 b2. case b1; case b2; simpl; trivial.\n  discriminate.\nQed.\n\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.\nintros b1 b2. \ncase b1; case b2; simpl; trivial.  \nQed.\n\n\nTheorem bool_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.\nintros b1 b2 b3. \ncase b1; case b2; case b3; simpl; trivial.\nQed.\n\n(* 6.7 p133 *)\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n\nCheck plane_rec.\n\n(* 6.8 p133*)\n\nDefinition manhattan_dist (p1 p2 : plane) : Z :=\n Z.add (Z.abs (abscissa p1 - abscissa p2)) (Z.abs (ordinate p1 - ordinate p2)).\n\n(* 6.9 p135 *)\n\nInductive vehicle : Set :=\n  | bicycle : nat -> vehicle \n  | motorized : nat -> nat -> vehicle.\n\nCheck vehicle_rec.\n\nDefinition nb_seats := vehicle_rec (fun v => nat) (fun x => 2) (fun x n => n).\n\nEval compute in nb_seats (bicycle 5).\n\nEval compute in nb_seats (motorized 2 3).\n\n(* 6.10 p140 *)\n\nDefinition is_Jan := month_rect (fun m => bool) \n  true false false false \n  false false false false \n  false false false false.\n\nEval compute in is_Jan January.\nEval compute in is_Jan February.\n\n(* 6.11 p140 *)\n\nCheck bool_rect.\n\nTheorem neq_tf : true <> false.\nProof.\nunfold not.\ndiscriminate.\nQed.\n\nSection proof_of_bool_discr.\n\n Let is_true (b:bool) : Prop :=\n   match b with\n   | true => True\n   | _ => False\n   end.\n\n Theorem bool_discr : true <> false.\n Proof.\n  intro e.\n  change (is_true false).\n  rewrite <- e. simpl. trivial.\n Qed.\n\nEnd proof_of_bool_discr.\n\nPrint bool_discr.\n\n(* 6.12 p140 *)\n\nTheorem neq_bm : forall (x y z:nat), bicycle x <> motorized y z.\nProof.\nunfold not.\ndiscriminate.\nQed.\n\nSection proof_of_vehicle_discr.\n\n Let is_bicycle (v:vehicle) : Prop :=\n   match v with\n   | (bicycle x) => True\n   | _ => False\n   end.\n\n Theorem vehicle_discr : forall (x y z:nat), bicycle x <> motorized y z.\n Proof.\n  intros.\n  unfold not.\n  intros.\n  change (is_bicycle (motorized y z)).\n  rewrite <- H. simpl. trivial.\n Qed.\n\nEnd proof_of_vehicle_discr.\n\n(* 6.13 p143 *)\n(* this part includes a proof of false *) \n(*\nRequire Import Arith.\nRecord RatPlus : Set := mkRat\n  {top : nat; bottom : nat; bottom_condition : bottom <> 0}.\n\nAxiom\n  eq_RatPlus :\n    forall r r':RatPlus, top r * bottom r' = top r' * bottom r -> r = r'.\n\nTheorem rp1 : forall (x0 y0 x1 y1:nat) (p0:y0<>0) (p1:y1<>0), mkRat x0 y0 p0 = mkRat x1 y1 p1 -> x0 = x1.\nProof.\nintros.\ninjection H.\ntrivial.\nQed.\n\nSearchPattern (_ <> _).\n\nDefinition n0 := mkRat 2 6 (not_eq_sym (O_S 5)).\n\nDefinition n1 := mkRat 1 3 (not_eq_sym (O_S 2)).\n\nTheorem rp2 : mkRat 2 6 (not_eq_sym (O_S 5)) = mkRat 1 3 (not_eq_sym (O_S 2)) -> False.\nProof.\nintros.\ndiscriminate.\nQed.\n\nTheorem rp3 : mkRat 2 6 (not_eq_sym (O_S 5)) = mkRat 1 3 (not_eq_sym (O_S 2)).\nProof.\napply eq_RatPlus.\ncompute.\ntrivial.\nQed.\n\nTheorem proof_false : False.\nProof.\napply rp2.\nexact rp3.\nQed.\n*)\n\n(* 6.14 p152 *)\n(* 6.15 p152 *)\nDefinition lt3 (n:nat) : bool :=\n  match n with\n    | O => true\n    | S O => true\n    | (S (S O)) => true\n    | _ => false\n  end.\n\n(* 6.16 p152 *)\nFixpoint add' (n m:nat) : nat :=\n  match m with\n    | O => n\n    | S a => S (add' n a)\n  end.\n\n(* 6.17 p152 *)\nFixpoint sum_f (n:nat) (f:nat->Z) : Z :=\n  match n with\n    | O => f O\n    | S a => Z.add (f (S a)) (sum_f a f)\n  end.\n\n(* 6.18 p152 *)\nFixpoint two_power (n:nat) : nat :=\n  match n with\n    | O => S O\n    | S a => (two_power a) + (two_power a)\n  end.\n\nEval compute in two_power 3.\n\n(* 6.19 p154 *)\n\nOpen Scope Z_scope.\n\nPrint Z.\n\nPrint positive.\n\nCheck Zpos (xO (xO (xO (xI (xO (xI (xI (xI (xI xH))))))))).\nCheck Zpos (xI (xO (xO (xI xH)))).\nCheck Zpos (xO (xO (xO (xO (xO (xO (xO (xO (xO xH))))))))).\n\n(* 6.20 p154 *)\n\nDefinition pos_even_bool (n:positive) : bool :=\n  match n with\n    | (xO _) => true\n    | _ => false\n  end.\n\n(* 6.21 p154 *)\n\nDefinition pos_div4 (n:positive) : Z :=\n  match n with\n    | (xO (xO x)) => Zpos x\n    | (xO (xI x)) => Zpos x\n    | (xI (xO x)) => Zpos x\n    | (xI (xI x)) => Zpos x\n    | _ => Z0\n  end.\n\n(* 6.22 p154 *)\n\nOpen Scope positive_scope.\n\nFixpoint pos_succ (n : positive) : positive :=\n  match n with\n    | xH => (xO xH)\n    | xO x => xI x\n    | xI x => xO (pos_succ x)\n  end.\n\nFixpoint pos_add (a b : positive) : positive :=\n  match (a, b) with\n    | (xH, b) => pos_succ b\n    | (a, xH) => pos_succ a\n    | ((xO a'), (xO b')) => xO (pos_add a' b')\n    | ((xI a'), (xO b')) => xI (pos_add a' b')\n    | ((xO a'), (xI b')) => xI (pos_add a' b')\n    | ((xI a'), (xI b')) => xO (pos_succ (pos_add a' b'))\n  end.\n\nEval compute in pos_succ xH.\nEval compute in (pos_succ (xI (xI (xI (xI xH))))).\nEval compute in (pos_add (xI (xI (xI (xI xH)))) (xI (xI (xI (xI xH))))).\n\nSearch positive.\n\nEval compute in shift (5) (xI xH).\n\nFixpoint pos_mult (a b : positive) : positive :=\n  match (a, b) with\n    | (xH, b) => b\n    | (a, xH) => a\n    | ((xO a'), (xO b')) => xO (xO (pos_mult a' b'))\n    | ((xI a'), (xO b')) => pos_add (xO (xO (pos_mult a' b'))) b\n    | ((xO a'), (xI b')) => pos_add (xO (xO (pos_mult a' b'))) a\n    | ((xI a'), (xI b')) => pos_add (xO (xO (pos_mult a' b'))) (pos_add (xO a') b)\n  end.\n\nEval compute in (pos_mult (xI (xI (xI (xI xH)))) (xI (xI (xI (xI xH))))).\nEval compute in (pos_mult (xI (xO (xI (xO xH)))) (xI (xO (xI (xO xH))))).\n\nPrint Z.\n\nDefinition Z_mult (a b : Z) : Z :=\n  match (a, b) with\n    | (Z0, b) => Z0\n    | (a, Z0) => Z0\n    | (Zpos x, Zpos y) => Zpos (pos_mult x y)\n    | (Zpos x, Zneg y) => Zneg (pos_mult x y)\n    | (Zneg x, Zpos y) => Zneg (pos_mult x y)\n    | (Zneg x, Zneg y) => Zpos (pos_mult x y)\n  end.\n\n(* 6.23 p154 *)\n\nInductive L : Set :=\n  | L_true : L\n  | L_false : L\n  | L_disj : L -> L -> L\n  | L_conj : L -> L -> L\n  | L_impl : L -> L -> L\n  | L_not : L -> L.\n\n(* 6.24 p155 *)\n\nInductive F: Set :=\n | F_one : F\n | F_n : F -> F\n | F_d : F -> F.\n\n(* 6.25 p155 *)\n\nInductive Z_btree : Set :=\n | Z_leaf : Z_btree \n | Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nSearch bool.\n\nFixpoint value_present (z:Z) (t:Z_btree) : bool :=\n  match t with\n    | Z_leaf => false\n    | (Z_bnode x' t1 t2) => if (Zeq_bool x' z) then true else orb (value_present z t1) (value_present z t2)\n  end.\n\n(* 6.26 p155 *)\n\nFixpoint power (z:Z) (n:nat) : Z := \n  match n with\n    | O => 1%Z\n    | (S x) => Z_mult z (power z x)\n  end.\n\nEval compute in power 3 10.\n\nFixpoint discrete_log (n:positive) : nat :=\n  match n with\n    | xH => O\n    | (xI x) => S (discrete_log x) \n    | (xO x) => S (discrete_log x) \n  end.\n\nEval compute in discrete_log (xI (xI (xI (xI xH)))).\n\n(* 6.27 p156 *)\n\nInductive Z_fbtree : Set :=\n  | Z_fleaf : Z_fbtree\n  | Z_fnode : Z -> (bool -> Z_fbtree) -> Z_fbtree.\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 =>\n    v + fsum_all_values (f true) + fsum_all_values (f false)\n  end)%Z.\n\nCheck Z.eq_dec.\n\nFixpoint fzero_present (t:Z_fbtree) : bool :=\n  match t with\n  | Z_fleaf => false\n  | Z_fnode v f => if (Z.eq_dec v 0%Z) then true else orb (fzero_present (f true)) (fzero_present (f false))\n  end.\n\n(* 6.28 p157 *)\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\n(* Error: Cannot guess decreasing argument of fix. *)\n(*\nFixpoint izero_present (n:nat) (t:Z_inf_branch_tree) : bool :=\n  match (t, n) with\n  | (Z_inf_leaf, _) => false\n  | (Z_inf_node 0%Z f, _) => true\n  | (Z_inf_node _ f, 0%nat) => izero_present n (f 0%nat)\n  | (Z_inf_node _ f, (S m)) => orb (izero_present n (f m)) (izero_present m t)\n  end.\n*)\n\nFixpoint any_true (n:nat) (f:nat->bool):bool :=\n  match n with \n  | 0%nat => f 0%nat\n  | S m => orb (f (S m)) (any_true m f)\n  end.\n\nFixpoint izero_present (n:nat) (t:Z_inf_branch_tree) : bool :=\n  match t with\n  | Z_inf_leaf => false\n  | Z_inf_node v f =>\n    match v with\n    | 0%Z => true\n    | _ => any_true n (fun x => izero_present n (f x))\n    end\n  end.\n\n(* 6.29 p158 *)\n\nOpen Scope nat_scope.\n\nTheorem plus_n_O : forall (n:nat), n = n + 0.\nProof.\nintro n.\nelim n.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nelim H.\nreflexivity.\nQed.\n\n(* 6.30 p158 *)\n\nFixpoint f1 (bt:Z_btree) : Z_fbtree :=\n  match bt with\n  | Z_leaf => Z_fleaf\n  | Z_bnode v t1 t2 => Z_fnode v (fun b => if b then (f1 t1) else (f1 t2))\n  end.\n\nFixpoint f2 (ft:Z_fbtree) : Z_btree :=\n  match ft with\n  | Z_fleaf => Z_leaf\n  | Z_fnode v f => Z_bnode v (f2 (f true)) (f2 (f false))\n  end.\n\nTheorem f2_f1 : forall t: Z_btree, f2 (f1 t) = t.\nProof.\nintros.\nelim t.\nsimpl.\ntrivial.\nintros.\nsimpl.\nrewrite H.\nrewrite H0.\ntrivial.\nQed.\n\nRequire Import Logic.FunctionalExtensionality.\n\nTheorem f1_f2 : forall t: Z_fbtree, f1 (f2 t) = t.\nProof.\nintros.\ninduction t.\nsimpl; trivial.\nsimpl. rewrite H. rewrite H.\nrewrite <- (functional_extensionality (fun b:bool => if b then z0 true else z0 false) z0).\ntrivial.\nintros. elim x; trivial.\nQed.\n\n(* 6.31 p158 *)\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => O\n  | (S p) => (S (S (mult2 p)))\n  end.\n\nLemma mult2_double : forall n:nat, mult2 n = n + n.\nProof.\nintros.\nelim n.\nsimpl. trivial.\nintros.\nsimpl. rewrite H. rewrite plus_n_Sm. trivial.\nQed.\n\n(* 6.32 p158 *)\n\nFixpoint sum_n (n:nat) : nat :=\n  match n with\n  | O => O\n  | S p => S p + sum_n p\n  end.\n\nRequire Import ArithRing.\n\nTheorem sum_closed_form : forall n:nat, 2 * sum_n n = n * S n.\nProof.\nintro n.\ninduction n.\nsimpl. trivial.\nsimpl (sum_n (S n)).\nring_simplify.\nrewrite IHn.\nring_simplify.\ntrivial.\nQed.\n\nTheorem sum_closed_form' : forall n:nat, 2 * sum_n n = n * S n.\nProof.\ninduction n; trivial.\nunfold sum_n; fold sum_n.\nrewrite mult_plus_distr_l.\nrewrite IHn.\nsimpl.\nf_equal.\nrewrite <- plus_n_O.\nrepeat rewrite mult_succ_r.\nrepeat rewrite plus_n_Sm.\nrewrite plus_assoc_reverse.\nf_equal.\nrewrite <- plus_comm.\ntrivial.\nQed.\n\nPrint sum_closed_form'.\n\n(* 6.33 p159 *)\n\nRequire Import Omega.\n\nTheorem sum_n_le_n : forall n:nat, n <= sum_n n.\nProof.\nintro n.\nassert ((2 * n) <= (2 * sum_n n)).\nrewrite sum_closed_form.\nring_simplify.\ninduction n.\nsimpl; omega.\nring_simplify. omega.\nomega.\nQed.\n\nPrint sum_n_le_n.\n\nTheorem sum_n_le_n' : forall n:nat, n <= sum_n n.\nProof.\n simple induction n.\n auto with arith.\n intros n1 Hn0. simpl.\n auto with arith.\nQed.\n\nPrint sum_n_le_n'.\n\n(* 6.34 p161 *)\nRequire Import List.\nDefinition two_first (A:Set)(l:list A) : list A :=\n match l with \n | a :: b :: l' => a :: b :: nil\n | _ => (nil (A:=A))\n end.\n\n(* 6.35 p161 *)\n\nFixpoint take (A:Set)(n:nat)(l:list A): list A :=\n   match (n,l) with\n   | (0, l') => nil\n   | (S n', nil) => nil\n   | (S n', a::l') => \n     match take _ n' l' with\n     | nil => nil\n     | l'' => a :: l''\n     end\n  end.\n\n(* 6.36 p161 *)\n\nFixpoint sum_list (l:list nat) : nat :=\n  match l with\n  | nil => 0\n  | a::l' => a + sum_list l'\n  end.\n\n(* 6.37 p161 *)\n\nFixpoint ones (n:nat) : list nat :=\n  match n with\n  | O => nil\n  | (S m) => 1 :: ones m\n  end.\n\n(* 6.38 p162 *)\n\nFixpoint natlist (n:nat) : list nat :=\n  (fix f (m:nat):list nat :=\n    match m with\n    | O => nil\n    | (S x) => (n - x)::(f x)\n    end) n.\n\nEval compute in natlist 5.\n\n(* 6.39 p163 *)\n\nFixpoint nth_option (A:Set)(n:nat)(l:list A) {struct l}: option A :=\n  match n, l with\n  | O, cons a tl =>  Some a\n  | S p, cons a tl => nth_option A p tl\n  | _, nil => None\n  end.\n\nFixpoint nth_option' (A:Set)(n:nat)(l:list A) {struct n}: option A :=\n  match n, l with\n  | O, cons a tl =>  Some a\n  | O, nil => None\n  | S p, cons a tl => nth_option' A p tl\n  | S p, nil => None\n  end.\n\n(* 6.40 p163 *)\n\nLemma nth_length : forall (A:Set)(n:nat)(l:list A), nth_option A n l = None <-> length l <= n.\nProof.\nsimple induction n.\ndestruct l.\nsimpl; split; auto.\nsimpl; split; [discriminate | inversion 1].\ndestruct l; split; simpl; auto with arith.\ncase (H l); auto with arith.\ncase (H l); auto with arith.\nQed.\n\n(* 6.41 p163 *)\n\nFixpoint first_in_list (A:Set)(f:A->bool)(l:list A) : option A :=\n  match l with\n  | nil => None\n  | a::l' => if f a then Some a else first_in_list A f l'\n  end.\n\n(* 6.42 p163 *)\n\nFixpoint split (A B: Set)(l: list (A * B)) : (list A)*(list B) :=\n  match l with\n  | nil => (nil, nil)\n  | (a,b)::l' => let ll := (split _ _ l') in (a::(fst ll), b::(snd ll))\n  end.\n\nFixpoint combine (A B: Set)(l1 : list A)(l2 :list B): list (A*B):=\n  match l1, l2 with\n  | nil, _ => nil\n  | _, nil => nil\n  | a::l1', b::l2' => (a,b)::(combine _ _ l1' l2')\n  end.\n\n(*copy from the answer*)\nTheorem combine_of_split : forall (A B:Set) (l:list (A*B)),\n   let ( l1,l2) :=  (split _ _ l) \n   in combine _ _ l1 l2 = l.\nProof.\n simple induction l; simpl; auto.\n intros p l0; case (split A B l0); simpl; auto.\n case p; simpl; auto.\n destruct 1; auto. \nQed.\n\nPrint combine_of_split.\n\n(* 6.43 p163 *)\n\nInductive btree (A:Set) :Set :=\n  | bleaf : btree A \n  | bnode : A ->btree A->btree A->btree A.\n\nFixpoint Z_btree_to_btree (t:Z_btree) : btree Z :=\n  match t with\n  | Z_leaf => bleaf Z\n  | Z_bnode x t1 t2 => \n      bnode Z x (Z_btree_to_btree t1) (Z_btree_to_btree t2)\n  end.\n\nFixpoint btree_to_Z_btree (t:btree Z) : Z_btree :=\n  match t with\n  | bleaf => Z_leaf\n  | bnode x t1 t2 => \n      Z_bnode x (btree_to_Z_btree t1) (btree_to_Z_btree t2)\n  end.\n\nTheorem btree_to_Z_inv : forall t, Z_btree_to_btree (btree_to_Z_btree t) = t.\nProof.\nintros.\ninduction t.\nsimpl.\ntrivial.\nsimpl.\nrewrite IHt1.\nrewrite IHt2.\ntrivial.\nQed.\n\nTheorem Z_btree_to_inv : forall t, btree_to_Z_btree (Z_btree_to_btree t) = t.\nProof.\nintros.\ninduction t; simpl; trivial.\nsimpl; rewrite IHt1; rewrite IHt2; trivial.\nQed.\n\n(* 6.44 p164 *)\n\nFixpoint F_to_PQ (f:F) : nat * nat :=\n  match f with\n  | F_one => (1, 1)\n  | F_n g => let (p,q) := F_to_PQ g in (p+q,q)\n  | F_d g => let (p,q) := F_to_PQ g in (p,p+q)\n  end.\n\nEval compute in F_to_PQ (F_one).\n\nEval compute in F_to_PQ (F_n F_one).\n\nEval compute in F_to_PQ (F_d (F_n F_one)).\n\n(* 6.45 p164 *)\n\nInductive cmp : Set := \n  | Less : cmp\n  | Equal : cmp\n  | Greater : cmp.\n\nFixpoint three_way_compare (a b:nat) : cmp :=\n  match a, b with\n  | O, O => Equal\n  | S _, O => Greater\n  | O, S _ => Less\n  | S n, S m => three_way_compare n m\n  end.\n\nFixpoint update_primes (k:nat) (l:list (nat*nat)) : (list (nat*nat))*bool :=\n  match l with\n  | nil => (nil, false)\n  | (p,m)::l' => let (a, b) := update_primes k l' in\n    match three_way_compare k m with\n    | Less => ((p, m)::a, b)\n    | Equal => ((p, m+p)::a, true)\n    | Greater => ((p, m+p)::a, b)\n    end\n  end.\n\nFixpoint prime_sieve (n:nat) : (list (nat*nat)) :=\n  match n with\n  | O => nil\n  | S O => nil\n  | S m => let (a, b) := update_primes (S m) (prime_sieve m) in\n    if b then a else (S m, 2 * (S m))::a\n  end.\n\nEval compute in prime_sieve 100.\n\n(* It is so hard to prove the soundness and completeness! *)\n\n(* 6.46 p167 *)\n\nInductive htree (A:Set) : nat -> Set :=\n  | hleaf : A -> (htree A O)\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\nFixpoint invert (A:Set)(n:nat)(t:htree A n) : htree A n :=\n  match t with\n  | hleaf v => hleaf A v\n  | hnode p v t1 t2 =>\n    hnode A p v (invert A p t2) (invert A p t1)\n  end.\n\n(*copy from the answer*)\n\nDefinition first_of_htree :\n  forall (A:Set) (n:nat), htree A n -> htree A (S n) -> htree A n.\n intros A n v t.\n\n generalize v.\n change (htree A (pred (S n)) -> htree A (pred (S n))).\n case t.\n intros x v'; exact v'.\n intros p x t1 t2 v'; exact t1.\nDefined.\n \nPrint first_of_htree.\n\nEval compute in (pred O).\n\nTheorem injection_first_htree :\n forall (n:nat) (t1 t2 t3 t4:htree nat n),\n   hnode nat n 0 t1 t2 = hnode nat n 0 t3 t4 -> t1 = t3.\n intros n t1 t2 t3 t4 h.\n change\n  (first_of_htree nat n t1 (hnode nat n 0 t1 t2) =\n   first_of_htree nat n t1 (hnode nat n 0 t3 t4)).\n rewrite h.\n reflexivity.\nQed.\n\n(* 6.47 p167 *)\n\nFixpoint make_htree (n:nat) : htree Z n :=\n  match n with\n  | O => hleaf Z 0%Z\n  | (S m) => hnode Z m 0%Z (make_htree m) (make_htree m)\n  end.\n\n(* 6.48 p167 *)\n\nInductive binary_word : nat -> Set :=\n  | empty_binary_word :  binary_word 0\n  | cons_binary_word :\n    forall p:nat, bool -> binary_word p -> binary_word (S p).\n\nFixpoint binary_word_concat (n:nat)(w1:binary_word n)(m:nat)(w2:binary_word m) : binary_word (n+m) :=\n  match w1 with\n  | empty_binary_word => w2\n  | cons_binary_word q b w1' =>\n    cons_binary_word (q+m) b (binary_word_concat q w1' m w2)\n end.\n\n(* 6.49 p167 *)\nFixpoint binary_word_or (l : nat) (wl wr : binary_word l) : binary_word l.\n  destruct wl.\n  exact wr.\n  inversion wr.\n  exact(cons_binary_word p (orb b H0) (binary_word_or p wl H1)).\nDefined.\n\nDefinition bw1:= cons_binary_word 1 false (cons_binary_word 0 true empty_binary_word).\nDefinition bw2:= cons_binary_word 1 true (cons_binary_word 0 false empty_binary_word).\n\nEval compute in binary_word_or 2 bw1 bw2.\n\nPrint binary_word_or.\n\nEval compute in eq_rec 2 binary_word bw1 2 eq_refl.\n\n(* lolisa's solution *)\n\nFixpoint binary_word_or1 (l : nat) (wl wr : binary_word l) : binary_word l.\n  refine(\n    match wl in binary_word n return binary_word n -> binary_word n with\n    | empty_binary_word => (fun x => x)\n    | cons_binary_word ll lb lw => \n        (fun wr' : binary_word (S ll) => match wr' with\n        | empty_binary_word => (fun p : False => wr')\n        | cons_binary_word rl rb rw => \n            (fun p : ll = rl => \n              cons_binary_word\n              rl\n              (bool_or lb rb) \n              (binary_word_or rl (eq_rec ll binary_word lw rl p) rw))\n        end _)\n    end wr).\n    reflexivity.\nDefined.\n\nPrint binary_word_or1.\n\nFixpoint binary_word_or2 (n:nat)(w1 w2:binary_word n) : binary_word n.\n  refine(\n  match w1 in binary_word p return binary_word p -> binary_word p with\n  | empty_binary_word => (fun x => x)\n  | cons_binary_word q1 b1 w1' => (fun w3 =>\n    match w3 with \n    | empty_binary_word => w3\n    | cons_binary_word q2 b2 w2' => (fun P:q1=q2 =>\n      cons_binary_word q2 (orb b1 b2) (binary_word_or q2 (eq_rec q1 binary_word w1' q2 P) w2'))\n    end eq_refl\n  )\n  end w2).\nQed.\n\nPrint binary_word_or2.\n\n(* 6.50 p167 *)\n\n(* copy from answer *)\n\nFixpoint bool_nat_type (n:nat) : Set :=\n  match n with 0 => nat | 1 => bool | S (S n) => bool_nat_type n end.\n\nFixpoint bool_nat_fun_aux (n:nat) :  bool_nat_type n -> bool_nat_type n :=\n match n return bool_nat_type n -> bool_nat_type n with\n   0 => S | 1 => negb | S (S n) => bool_nat_fun_aux n\n end.\n\nPrint bool_nat_fun_aux.\n\nFixpoint bool_nat_fun (n:nat) : bool_nat_type n :=\n match n return bool_nat_type n with\n   0 => 0 \n | 1 => true\n | S (S n) => bool_nat_fun_aux n (bool_nat_fun n)\n end.\n\nEval compute in bool_nat_fun_aux 6 (bool_nat_fun 6).\n\nEval compute in (bool_nat_fun 7).\n\nEval compute in (bool_nat_fun 9).\n\nEval compute in (bool_nat_fun 7 : bool).\n\nEval compute in (bool_nat_fun 6 : nat).\n\n(* 6.51 p169 *)\n\nCheck Empty_set.\n\nTheorem all_equal : forall x y : Empty_set, x = y.\nProof.\ndestruct x.\nQed.\n\nTheorem all_diff : forall x y : Empty_set, x <> y.\nProof.\ndestruct x.\nQed.\n\nEnd section_for_chapter_6.", "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_chapter6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.9032941975921684, "lm_q1q2_score": 0.7864054670584123}}
{"text": "(********************** Begin: FRAP Preamble **********************)\nRequire Import Frap.\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\nExample ex1 := Const 42.\nExample ex2 := Plus (Var \"y\") (Times (Var \"x\") (Const 3)).\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  | Minus e1 e2 => interp e1 v - interp e2 v\n  | Times e1 e2 => interp e1 v * interp e2 v\n  end.\n\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\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  | Times e1 e2 => Times (commuter e2) (commuter e1)\n  end.\n(********************** End: FRAP Preamble **********************)\n\n(********************** Begin: Studio talk **********************)\nTheorem commuter_ok : forall v e, interp (commuter e) v = interp e v.\nProof.\n  intros.\n  induct e; simplify.\n  - equality.\n  - equality.\n  - linear_arithmetic.\n  - equality.\n  - rewrite IHe1, IHe2.\n    remember (interp e2 v) as a.\n    remember (interp e1 v) as b.\n    (* ring.              [> ring knows a*b = b*a <] *)\n    (* Show Proof.        [> 259 line proof <] *)\n    linear_arithmetic. (* why does linear_arithmetic work here? :shrug: *)\n    (* Show Proof.        [> 333 line proof <] *)\n    Locate linear_arithmetic.\nQed.\n(* Ring is just a decision procedure; as long as your datatype has proven its\n*  axioms, you can use proofs about rings for free. *)\n\n(* Note: linear_arithmetic is not equivalent to ring *)\n(* Recall: ring can only prove equalities, l_a can prove both equalities and\n*  inequalities. *)\n(********************** End: Studio Talk **********************)\n\n(********************** Begin: my solution **********************)\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\n(* Just case bashin' *)\nTheorem doSomeArithmetic_ok : forall e v, interp (doSomeArithmetic e) v = interp e v.\nProof.\n  induct e; simplify.\n  - equality.\n  - equality.\n  - cases e1; simplify; try equality.\n    cases e2; simplify; equality.\n  - cases e1; simplify; equality.\n  - cases e1; simplify; try equality.\n    cases e2; simplify; equality.\nQed.\n(********************** End: my solution **********************)\n\n(********************** Begin: FRAP Stuff **********************)\nInductive instruction :=\n| PushConst (n : nat)\n| PushVar (x : var)\n| Add\n| Subtract\n| Multiply.\n\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\n    end\n  | Subtract =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 - arg2 :: stack'\n    | _ => stack\n    end\n  | Multiply =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 * arg2 :: stack'\n    | _ => stack\n    end\n  end.\n\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\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(********************** End: FRAP Stuff **********************)\n\n(********************** Begin: Studio Talk **********************)\nTheorem compile_ok' : forall e v, run (compile e) v nil = interp e v :: nil.\nProof.\n  induct e; intros; simplify; auto.\n  - try rewrite IHe1. (* this hypothesis is not syntactically equivalent to the current goal\n                         in particular, it only hypothesizes running a single compilation\n                         we NEED a stronger induction hypothesis! hence compile_ok_stronger *)\nAdmitted.\n\n(* so lets do this for all instruction lists, not just single compiles *)\nTheorem compile_ok_stronger :\n  forall e v is,\n    run (compile e ++ is) v nil = run is v (interp e v :: nil).\nProof.\n  induct e; intros; simplify; auto.\n  - try rewrite IHe1. (* still doesn't work, BUT just a silly nesting reason. *)\n    Search ((_ ++ _) ++ _ = _ ++ (_ ++ _)). (* so let's find what we need *)\n    rewrite app_assoc_reverse.\n    rewrite IHe1. (* great! *)\n    rewrite app_assoc_reverse.\n    try rewrite IHe2.\n    (* BUT this doesn't work for the second side! the IH works\n       for empty instruction stacks but what we need to prove is no longer\n       empty! there's an `interp e1 v` sitting in there. So this theorem statement\n       is NOT inductive. *)\nAdmitted.\n\n(* so lets make sure we have a statement for ALL stacks, not just nil *)\nTheorem compile_ok_even_stronger :\n  forall e v is stack,\n    run (compile e ++ is) v stack = run is v (interp e v :: stack).\nProof.\n  induct e; intros; simplify; auto.\n  - rewrite <- app_assoc. (* same thing as rewrite app_assoc_reverse. *)\n    rewrite IHe1.\n    rewrite <- app_assoc.\n    rewrite IHe2. (* Notice IHe2 is now strong enough for the goal! *)\n    simplify. reflexivity.\n  (* the other cases are identical *)\n  - rewrite <- app_assoc. rewrite IHe1.\n    rewrite <- app_assoc. rewrite IHe2. simplify. reflexivity.\n  - rewrite <- app_assoc. rewrite IHe1.\n    rewrite <- app_assoc. rewrite IHe2. simplify. reflexivity.\nQed.\n\n(* Finding the right inductive hypothesis is an art. It needs to be weak enough\n   to prove base cases but strong enough to induct. *)\n\nTheorem compile_ok : forall e v, run (compile e) v nil = interp e v :: nil.\nProof.\n  intros.\n  try apply compile_ok_even_stronger. (* doesn't work directly *)\n  SearchRewrite (_ ++ nil).\n  rewrite (app_nil_end (compile e)). (* pass (compile e ++ []) instead of (compile e) *)\n  apply compile_ok_even_stronger.\nQed.\n\n(********************** End: Studio Talk **********************)\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/03-studio-04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7863857935434524}}
{"text": "(*\nNoel-Lardin Thomas\nTurki Sanekli Hedi\n*)\n\n(**********************************************************\n*                         Partie 1                        *\n***********************************************************)\n\n(* -------------- Lambda calcul simplement typé ----------------*)\nSection type_booleen.\nVariable T: Set.\nVariable E F:T.\nDefinition cbool := T -> T -> T.\nDefinition cnat := (T->T) -> T->T.\n\n(* # 1 #*)\n(* Définition des Booléens *)\nDefinition ctr : cbool := fun x y => x. (* TRUE *)\nDefinition cfa : cbool := fun x y => y. (* FALSE *)\nCompute ctr E F.\nCompute cfa E F.\n\n(* # 2 #*)\n(* Définition de la contion if *)\nDefinition cif : cbool -> T -> T -> T := fun c : cbool => fun x y => c x y.\nCompute (cif ctr E F).\nCompute (cif cfa E F).\n\n(* Définition de la négation *)\nDefinition cnot : cbool->cbool := fun b : cbool => fun x y => cif b y x.\nCompute(cnot ctr).\nCompute(cnot cfa).\n\n(* Définition de la contion and *)\nDefinition cand : cbool-> cbool->cbool := fun a b : cbool=> fun x y : T => a (b x y) y.\nCompute (cand ctr cfa).\nCompute (cand ctr ctr).\nCompute (cand cfa cfa).\nCompute (cand cfa ctr).\n\n(* Définition de la contion or *)\nDefinition cor : cbool->cbool->cbool := fun a b : cbool=> fun x y : T => a x (b x y).\nCompute (cor ctr cfa).\nCompute (cor ctr ctr).\nCompute (cor cfa cfa).\nCompute (cor cfa ctr).\n\n(* # 2 # *)\nSection type_entier.\n\n(* Définition des constantes *)\nDefinition c0 : cnat := fun f x => x.\nDefinition c1 : cnat := fun f x => f x.\nDefinition c2 : cnat := fun f x => f (f x).\nDefinition c3 : cnat := fun f x => f (f (f x)). \nCompute (c0).\nCompute (c1).\nCompute (c2).\nCompute (c3).\n\n(* Définition de l'opération successeur *)\nDefinition csucc : cnat-> cnat := fun n => fun f => fun x => f(n f x).\nCompute (csucc c0).\nCompute (csucc c1).\nCompute (csucc c2).\nCompute (csucc c3).\nCompute (csucc (csucc c3)).\n\n(* Définition de l'opération addition *)\nDefinition cadd : cnat->cnat->cnat := fun n m f x => n f ( m f x ).\nCompute(cadd c1 c2).\nCompute (cadd c3 (csucc c3)).\nCompute (cadd (csucc c2) (csucc c3)).\n\n(* Définition de l'opération multiplication *)\nDefinition cmult: cnat->cnat->cnat := fun n m f => n ( m f ).\nCompute(cmult c2 c3).\nCompute (cmult (cadd c2 c3) (csucc c1)).\n\n(* Définition du test à 0 *)\nDefinition ceq0: cnat->cbool := fun n => fun x y => n (fun z => y) x.\nCompute (ceq0 c0).\nCompute (ceq0 c1).\nCompute (ceq0 (cmult c0 (cadd c3 (cmult c2 c3)))). (* Multiplication par 0 *)\nCompute (ceq0 (cmult c3 (cadd c3 (cmult c2 c3)))).\n\nEnd type_entier.\nEnd type_booleen.\n\n", "meta": {"author": "hediturki123", "repo": "LambdaCalculus", "sha": "5b7010f8649902f2c77d984a1ea106c11fd0900d", "save_path": "github-repos/coq/hediturki123-LambdaCalculus", "path": "github-repos/coq/hediturki123-LambdaCalculus/LambdaCalculus-5b7010f8649902f2c77d984a1ea106c11fd0900d/1.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7863857935434524}}
{"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(* ** Euclidian division and Bezout's identity *)\n\nRequire Import List Arith Lia Permutation Extraction.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list.\n\nSet Implicit Arguments.\n\nSection Euclid.\n\n  (* Simultaneous comparison and difference *)\n\n  Fixpoint cmp_sub x y : { z | z+y = x } + { x < y }.\n  Proof.\n    refine (match y as y' return { z | z+y' = x } + { x < y' } with\n      | 0    => inleft (exist _ x _)\n      | S y' => match x as x' return { z | z+_ = x' } + { x' < _ } with\n        | 0    => inright _\n        | S x' => match cmp_sub x' y' with\n          | inleft (exist _ z Hz) => inleft (exist _ z _)\n          | inright H => inright _\n        end\n      end\n    end); abstract lia.\n  Defined.  \n\n  Definition euclid n d : d <> 0 -> { q : nat & { r | n = q*d+r /\\ r < d } }.\n  Proof.\n    intros Hd; induction on n as euclid with measure n.\n    refine (match cmp_sub n d with\n      | inleft (exist _ z Hz) => \n      match euclid z _ with\n        | existT _ q (exist _ r Hr) => existT _ (S q) (exist _ r _) \n      end\n      | inright H      => existT _ 0 (exist _ n _)\n    end); abstract (simpl; lia).\n  Defined.\n\nEnd Euclid.\n\nDefinition arem n d q j := j <= d /\\ (n = 2*q*d+j \\/ q <> 0 /\\ n = 2*q*d-j).\n\nFact division_by_even n d : d <> 0 -> { q : nat & { j | arem n d q j } }.\nProof.\n  intros Hd.\n  destruct (@euclid n (2*d)) as (q & r & H1 & H2); try lia.\n  destruct (le_lt_dec r d) as [ Hr | Hr ].\n  + exists q, r; split; auto; left.\n    rewrite H1; ring.\n  + exists (S q), (2*d-r); split; lia.\nQed.\n\nFact own_multiple x p : x = p*x -> x = 0 \\/ p = 1.\nProof.\n  destruct x as [ | x ].\n  + left; trivial.\n  + right.\n    destruct p as [ | [ | p ] ].\n    - simpl in H; discriminate.\n    - trivial.\n    - exfalso; revert H.\n      do 2 (rewrite Nat.mul_comm; simpl).\n      generalize (p*x); intros; lia.\nQed.\n\nFact mult_is_one p q : p*q = 1 -> p = 1 /\\ q = 1.\nProof.\n  destruct p as [ | [ | p ] ].\n  + simpl; discriminate.\n  + simpl; lia.\n  + rewrite Nat.mul_comm.\n    destruct q as [ | [ | q ] ].\n    - simpl; discriminate.\n    - simpl; lia.\n    - simpl; discriminate.\nQed.\n\nDefinition divides n k := exists p, k = p*n.\n\nSection divides.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Fact divides_refl x : x div x.\n  Proof. exists 1; simpl; lia. Qed.\n\n  Fact divides_anti x y : x div y -> y div x -> x = y.\n  Proof.\n    intros (p & H1) (q & H2).\n    rewrite H1, Nat.mul_assoc in H2.\n    apply own_multiple in H2.\n    destruct H2 as [ H2 | H2 ].\n    + subst; rewrite Nat.mul_comm; auto.\n    + apply mult_is_one in H2; destruct H2; subst; lia.\n  Qed.\n\n  Fact divides_trans x y z : x div y -> y div z -> x div z.\n  Proof.\n    intros (p & H1) (q & H2).\n    exists (q*p); rewrite <- Nat.mul_assoc, <- H1; auto.\n  Qed.\n\n  Fact divides_0 p : p div 0.\n  Proof. exists 0; auto. Qed.\n\n  Fact divides_0_inv p : 0 div p -> p = 0.\n  Proof. intros (?&?); subst; rewrite Nat.mul_0_r; auto. Qed.\n\n  Fact divides_1 p : 1 div p.\n  Proof. exists p; rewrite Nat.mul_comm; simpl; auto. Qed.\n\n  Fact divides_1_inv p : p div 1 -> p = 1.\n  Proof.\n    intros (q & Hq).\n    apply mult_is_one with q; auto.\n  Qed.\n\n  Fact divides_2_inv p : p div 2 -> p = 1 \\/ p = 2.\n  Proof.\n    intros ([ | k ] & Hk); try discriminate.\n    destruct p as [ | [ | [|] ] ]; lia.\n  Qed.\n\n  Fact divides_mult p q k : p div q -> p div k*q.\n  Proof.\n    intros (r & ?); subst.\n    exists (k*r); rewrite Nat.mul_assoc; auto.\n  Qed.\n\n  Fact divides_mult_r p q k : p div q -> p div q*k.\n  Proof.\n    rewrite Nat.mul_comm; apply divides_mult; auto.\n  Qed.\n\n  Fact divides_left x k : divides x (x*k).\n  Proof.\n    apply divides_mult_r, divides_refl. \n  Qed.\n\n  Fact divides_mult_compat a b c d : a div b -> c div d -> a*c div b*d.\n  Proof. \n    intros (u & ?) (v & ?); exists (u*v); subst.\n    repeat rewrite Nat.mul_assoc; f_equal.\n    repeat rewrite <- Nat.mul_assoc; f_equal.\n    apply Nat.mul_comm.\n  Qed.\n\n  Fact divides_minus p q1 q2 : p div q1 -> p div q2 -> p div q1 - q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 - s2).\n    rewrite Nat.mul_sub_distr_r; lia.\n  Qed.\n\n  Fact divides_plus p q1 q2 : p div q1 -> p div q2 -> p div q1+q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 + s2).\n    rewrite Nat.mul_add_distr_r; lia.\n  Qed.\n\n  Fact divides_plus_inv p q1 q2 : p div q1 -> p div q1+q2 -> p div q2.\n  Proof.\n     intros H1 H2.\n     replace q2 with (q1+q2-q1) by lia.\n     apply divides_minus; auto.\n  Qed.\n\n  Fact divides_le p q : q <> 0 -> p div q -> p <= q.\n  Proof.\n    intros ? ([] & ?); subst; lia.\n  Qed. \n\n  Fact divides_mult_inv k p q : k <> 0 -> k*p div k*q -> p div q.\n  Proof.\n    intros H (n & Hn); exists n.\n    apply Nat.mul_cancel_r with (1 := H).\n    rewrite Nat.mul_comm, Hn; ring.\n  Qed.\n\n  Lemma divides_fact m p : 1 < p <= m -> p div fact m.\n  Proof.\n    intros (H1 & H2); induction H2.\n    + destruct p; cbn. lia. unfold divides. exists (fact p). ring.\n    + cbn. eauto using divides_plus, divides_mult.\n  Qed.\n\n  Lemma divides_mult_inv_l p q r : p * q div r -> p div r /\\ q div r.\n  Proof.\n    intros []; split; subst.\n    - exists (x * q); ring.\n    - exists (x * p); ring.\n  Qed.\n\nEnd divides.\n\nSection gcd_lcm.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve divides_0 divides_refl divides_mult divides_1 : core.\n\n  Definition is_gcd p q r := r div p /\\ r div q /\\ forall k, k div p -> k div q -> k div r.\n  Definition is_lcm p q r := p div r /\\ q div r /\\ forall k, p div k -> q div k -> r div k.\n\n  Fact is_gcd_sym p q r : is_gcd p q r -> is_gcd q p r.\n  Proof. intros (? & ? & ?); repeat split; auto. Qed.\n\n  Fact is_gcd_0l p : is_gcd 0 p p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_0r p : is_gcd p 0 p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1l p : is_gcd 1 p 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1r p : is_gcd p 1 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_modulus p q k r : p div k -> k <= q -> is_gcd p q r -> is_gcd p (q-k) r.\n  Proof.\n    intros (n & Hn) Hq (H1 & H2 & H3); subst.\n    split; auto.\n    split.\n    + apply divides_minus; auto.\n    + intros k H4 H5.\n      apply H3; auto.\n      replace q with (q - n*p + n*p) by lia.\n      apply divides_plus; auto.\n  Qed.\n\n  Fact is_gcd_minus p q r : p <= q -> is_gcd p q r -> is_gcd p (q-p) r.\n  Proof. intros H1; apply is_gcd_modulus; auto. Qed.\n\n  Hint Resolve divides_plus : core.\n\n  Fact is_gcd_moduplus p q k r : p div k -> is_gcd p q r -> is_gcd p (q+k) r.\n  Proof.\n    intros (n & Hn) (H1 & H2 & H3); subst.\n    repeat (split; auto).\n    intros k H4 H5.\n    apply H3; auto.\n    rewrite Nat.add_comm in H5.\n    apply divides_plus_inv with (2 := H5); auto. \n  Qed.\n\n  Fact is_gcd_plus p q r : is_gcd p q r -> is_gcd p (q+p) r.\n  Proof. apply is_gcd_moduplus; auto. Qed.\n\n  Fact is_gcd_mult p q r n : is_gcd p (n*p+q) r <-> is_gcd p q r.\n  Proof.\n    split.\n    + replace q with ((n*p+q)-n*p) at 2 by lia.\n      apply is_gcd_modulus; auto; lia.\n    + rewrite Nat.add_comm; apply is_gcd_moduplus; auto.\n  Qed.\n\n  Fact is_gcd_div p q : p div q -> is_gcd p q p.\n  Proof. intros (?&?); subst; split; auto. Qed.\n\n  Fact is_gcd_refl p : is_gcd p p p.\n  Proof. split; auto. Qed.\n\n  Fact is_gcd_fun p q r1 r2 : is_gcd p q r1 -> is_gcd p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\n  Fact is_lcm_0l p : is_lcm 0 p 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_0r p : is_lcm p 0 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_sym p q r : is_lcm p q r -> is_lcm q p r.\n  Proof. intros (?&?&?); repeat split; auto. Qed.\n\n  Fact is_lcm_fun p q r1 r2 : is_lcm p q r1 -> is_lcm p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\nEnd gcd_lcm.\n\nSection bezout.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve is_gcd_0l is_gcd_0r is_lcm_0l is_lcm_0r divides_refl divides_mult divides_0 is_gcd_minus : core.\n\n  Section bezout_rel_prime.\n \n    (* A Bezout procedure with better extraction *)\n\n    Definition bezout_rel_prime_lt p q : \n            0 < p < q \n         -> is_gcd p q 1 \n         -> { a : nat & { b | a*p+b*q = 1+p*q \n                           /\\ a <= q \n                           /\\ b <= p } }.\n    Proof.\n      induction on p q as bezout with measure q; intros (Hp & Hq) H.\n      refine (match @euclid q p _ with\n        | existT _ n (exist _ r H0) => \n        match eq_nat_dec r 0 with\n          | left Hr => existT _ 1 (exist _ 1 _)\n          | right Hr => match @bezout r p Hq _ _ with\n            | existT _ a (exist _ b G0) => \n               existT _ (b+n*p-n*a) (exist _ a _)\n          end\n        end \n      end); try lia.\n      + destruct H0 as (H1 & H2).\n        subst r; rewrite Nat.add_comm in H1; simpl in H1.\n        assert (is_gcd p q p) as H3.\n        { apply is_gcd_div; subst; auto. }\n        rewrite (is_gcd_fun H3 H) in *.\n        simpl; lia.\n      + replace r with (q-n*p) by lia.\n        apply is_gcd_sym, is_gcd_modulus; auto; lia.\n      + destruct H0 as (H1 & H2).\n        destruct G0 as (H3 & H4 & H5).\n        split; [ | split ]; auto.\n        * rewrite H1, Nat.mul_sub_distr_r, (Nat.mul_comm _ p).\n          do 3 rewrite Nat.mul_add_distr_l.\n          rewrite (Nat.add_comm _ (p*r)), (Nat.add_assoc 1), (Nat.mul_comm p r), <- H3.\n          rewrite (Nat.mul_comm n a), (Nat.mul_comm p b), Nat.mul_assoc, Nat.mul_assoc.\n          assert (a*n*p <= p*n*p) as H6.\n          { repeat (apply Nat.mul_le_mono; auto). }\n          revert H6; generalize (b*p) (a*r) (a*n*p) (p*n*p); intros; lia.\n        * rewrite H1; generalize (n*p) (n*a); intros; lia.\n    Defined.\n\n    Definition bezout_rel_prime p q : is_gcd p q 1 -> { a : nat & { b | a*p+b*q = 1+p*q } }.\n    Proof.\n      intros H.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0l _) H); exists 0, 1; auto. }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0r _) H); exists 1, 0; auto. }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct bezout_rel_prime_lt with (2 := H)\n          as (a & b & H2 & _); try lia.\n        exists a, b; auto.\n      + subst; rewrite (is_gcd_fun (is_gcd_refl _) H); exists 1, 1; auto.\n      + destruct bezout_rel_prime_lt with (2 := is_gcd_sym H)\n          as (a & b & H2 & _); try lia.\n        exists b, a; rewrite (Nat.mul_comm p q); lia.\n    Defined.\n\n    Lemma bezout_nc p q : is_gcd p q 1 -> exists a b, a*p+b*q = 1+p*q.\n    Proof.\n      intros H.\n      destruct bezout_rel_prime with (1 := H) as (a & b & ?).\n      exists a, b; auto.\n    Qed.\n\n    Hint Resolve divides_1 : core.\n\n    Lemma bezout_sc p q a b m : a*p+b*q = 1 + m -> p div m \\/ q div m -> is_gcd p q 1.\n    Proof.\n      intros H1 H2; do 2 (split; auto).\n      intros k H4 H5.\n      apply divides_plus_inv with m.\n      +  destruct H2 as [ H2 | H2 ];\n         apply divides_trans with (2 := H2); auto.\n      + rewrite Nat.add_comm, <- H1.\n        apply divides_plus; auto.\n    Qed.\n\n  End bezout_rel_prime.\n\n  (* We need the simple form of Bezout above to show this *)\n\n  Fact is_rel_prime_div p q k : is_gcd p q 1 -> p div q*k -> p div k.\n  Proof.\n    intros H1 (u & H2); subst.\n    destruct bezout_nc with (1 := H1) as (a & b & H3).\n    replace k with (k*(1+p*q) - k*p*q).\n    + apply divides_minus.\n      - rewrite <- H3, Nat.mul_add_distr_l.\n        apply divides_plus.\n        * rewrite Nat.mul_assoc; auto.\n        * rewrite (Nat.mul_comm b), Nat.mul_assoc, (Nat.mul_comm k), H2.\n          rewrite Nat.mul_comm, Nat.mul_assoc; auto.\n      - rewrite Nat.mul_comm, Nat.mul_assoc; auto.\n    + rewrite Nat.mul_add_distr_l, Nat.mul_assoc.\n      generalize (k*p*q); intros; lia.\n  Qed.\n\n  Fact is_rel_prime_div_r p q k : is_gcd p q 1 -> p div k*q -> p div k.\n  Proof. rewrite Nat.mul_comm; apply is_rel_prime_div. Qed.\n\n  Fact divides_is_gcd a b c : divides a b -> is_gcd b c 1 -> is_gcd a c 1.\n  Proof.\n    intros H1 H2; msplit 2; try apply divides_1.\n    intros k H3 H4.\n    apply H2; auto.\n    apply divides_trans with a; auto.\n  Qed.\n\n  Fact is_rel_prime_lcm p q : is_gcd p q 1 -> is_lcm p q (p*q).\n  Proof.\n    intros H.\n    repeat (split; auto).\n    rewrite Nat.mul_comm; auto.\n    intros k (u & ?) (v & ?); subst.\n    rewrite (Nat.mul_comm u).\n    apply divides_mult_compat; auto.\n    apply is_gcd_sym in H.\n    apply is_rel_prime_div with (1 := H) (k := u).\n    rewrite Nat.mul_comm, H1; auto.\n  Qed.\n\n  Hint Resolve divides_1 divides_mult_compat is_gcd_refl : core.\n\n  Fact is_gcd_0 p q : is_gcd p q 0 -> p = 0 /\\ q = 0.\n  Proof.\n    intros ((a & Ha) & (b & Hb) & H).\n    subst; do 2 rewrite Nat.mul_0_r; auto.\n  Qed.\n\n  Fact is_gcd_rel_prime p q g : is_gcd p q g -> exists a b, p = a*g /\\ q = b*g /\\ is_gcd a b 1.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    * intros H; subst.\n      apply is_gcd_0 in H; destruct H; subst.\n      exists 1, 1 ; simpl; auto.\n    * intros ((a & Ha) & (b & Hb) & H).\n      exists a, b; repeat (split; auto).\n      intros k H1 H2.\n      destruct (H (k*g)) as (d & Hd); subst.\n      + do 2 rewrite (Nat.mul_comm _ g); auto.\n      + do 2 rewrite (Nat.mul_comm _ g); auto.\n      + rewrite Nat.mul_assoc in Hd.\n        replace g with (1*g) in Hd at 1 by (simpl; lia).\n        apply Nat.mul_cancel_r in Hd; auto.\n        symmetry in Hd.\n        apply mult_is_one in Hd.\n        destruct Hd; subst; auto.\n  Qed.\n\n  Fact is_lcm_mult p q l k : is_lcm p q l -> is_lcm (k*p) (k*q) (k*l).\n  Proof.\n    intros (H1 & H2 & H3); repeat (split; auto).\n    intros r (a & Ha) (b & Hb).\n    destruct (eq_nat_dec k 0) as [ Hk | Hk ].\n    + subst; simpl; auto.\n    + assert (a*p = b*q) as H4.\n      { rewrite <- Nat.mul_cancel_r with (1 := Hk).\n        do 2 rewrite <- Nat.mul_assoc, (Nat.mul_comm _ k).\n        rewrite <- Hb; auto. }\n      rewrite Ha, Nat.mul_assoc, (Nat.mul_comm _ k), <- Nat.mul_assoc.\n      apply divides_mult_compat; auto.\n      apply H3; auto.\n      rewrite H4; auto.\n  Qed.\n\n  Theorem is_gcd_lcm_mult p q g l : is_gcd p q g -> is_lcm p q l -> p*q = g*l.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ]; intros H1.\n    * subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl; auto.\n    * destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H2).\n      intros H3. \n      rewrite Hu, Hv, (Nat.mul_comm u), <- Nat.mul_assoc; f_equal.\n      rewrite (Nat.mul_comm u), (Nat.mul_comm v), <- Nat.mul_assoc, (Nat.mul_comm v).\n      apply is_lcm_fun with (2 := H3).\n      subst; rewrite (Nat.mul_comm u), (Nat.mul_comm v).\n      apply is_lcm_mult, is_rel_prime_lcm; auto.\n  Qed.\n\n  Theorem is_gcd_mult_lcm p q g l : g <> 0 -> is_gcd p q g -> g*l = p*q -> is_lcm p q l.\n  Proof.\n    intros H0 H1 H2.\n    destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H3).\n    rewrite Hu, Hv, (Nat.mul_comm u), (Nat.mul_comm v).\n    replace l with (g*(u*v)).\n    + apply is_lcm_mult, is_rel_prime_lcm; auto.\n    + rewrite <- Nat.mul_cancel_r with (1 := H0).\n      rewrite (Nat.mul_comm l), H2, Hu, Hv,\n              (Nat.mul_comm u g), Nat.mul_assoc, Nat.mul_assoc; auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-p) = g \n           B) lcm p (q-p) = l-u*p *)\n\n  Lemma is_lcm_minus p q g l u : p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-p) (l-u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite Nat.mul_0_r, Nat.sub_0_r; auto.\n    + intros H1 H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_minus; auto.\n      * do 2 rewrite Nat.mul_sub_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite Nat.mul_assoc, (Nat.mul_comm g); auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-k*p) = g \n           B) lcm p (q-p) = l-k*u*p *)\n\n  Lemma is_lcm_modulus k p q g l u : k*p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-k*p) (l-k*u*p).\n  Proof.\n    rewrite <- Nat.mul_assoc.\n    intros H1 H2 H3 H4. revert H1.\n    induction k as [ | k IHk ]; intros H1.\n    + simpl; do 2 rewrite Nat.sub_0_r; auto.\n    + replace (q - S k*p) with (q -k*p -p) by (simpl; lia).\n      replace (l - S k*(u*p)) with (l - k*(u*p) - u*p).\n      - apply is_lcm_minus with (g := g); auto.\n        * simpl in H1; lia.\n        * apply is_gcd_modulus; auto.\n          simpl in H1; lia.\n        * apply IHk; simpl in H1; lia.\n      - simpl; generalize (u*p) (k*(u*p)); intros; lia.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q+p) = g \n           B) lcm p (q+p) = l+u*p *)\n\n  Lemma is_lcm_plus p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+p) (l+u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite Nat.mul_0_r, Nat.add_0_r; auto.\n    + intros H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_plus; auto.\n      * do 2 rewrite Nat.mul_add_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite Nat.mul_assoc, (Nat.mul_comm g); auto.\n  Qed.\n\n  Lemma is_lcm_moduplus k p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+k*p) (l+k*u*p).\n  Proof.\n    rewrite <- Nat.mul_assoc.\n    intros H2 H3 H4.\n    induction k as [ | k IHk ].\n    + simpl; do 2 rewrite Nat.add_0_r; auto.\n    + replace (q + S k*p) with (q +k*p +p) by (simpl; lia).\n      replace (l + S k*(u*p)) with (l + k*(u*p) + u*p) by (simpl; lia).\n      apply is_lcm_plus with (g := g); auto.\n      apply is_gcd_moduplus; auto.\n  Qed.\n\n  Section bezout_generalized.\n\n    (* TODO, write this FULLY specified Bezout with a better extraction, following bezout_rel_prime above *)\n\n    Definition bezout_generalized_lt p q : \n                         0 < p < q \n                      -> { a : nat \n                       & { b : nat \n                       & { g : nat\n                       & { l : nat \n                       & { u : nat\n                       & { v : nat\n                         | a*p+b*q = g + l\n                        /\\ is_gcd p q g\n                        /\\ is_lcm p q l\n                        /\\ p = u*g\n                        /\\ q = v*g\n                        /\\ a <= v\n                        /\\ b <= u } } } } } }.\n    Proof.\n      induction on p q as IH with measure q; intros (Hp & Hq).\n      destruct (@euclid q p) as (k & r & H1 & H2); try lia.\n      destruct (eq_nat_dec r 0) as [ Hr | Hr ].\n      + exists 1, 1, p, (k*p), 1, k.\n        rewrite Nat.add_comm in H1; simpl in H1.\n        subst; repeat split; simpl; auto.\n        destruct k; lia.\n      + destruct (IH r _ Hq) as (a & b & g & l & u & v & H3 & H4 & H5 & H6 & H7 & H8 & H9); try lia.\n        exists (b+k*v-k*a), a, g, (l+k*v*p), v, (k*v+u).\n        apply is_gcd_sym in H4.\n        apply is_lcm_sym in H5.\n        rewrite Nat.add_comm in H1.\n        assert (g <> 0) as Hg.\n        { intro; subst g; apply is_gcd_0, proj1 in H4; lia. }\n        split.\n        { rewrite H1, Nat.add_assoc, Nat.mul_add_distr_l, <- H3.\n          rewrite Nat.mul_sub_distr_r, Nat.mul_add_distr_r.\n          rewrite Nat.mul_assoc, (Nat.mul_comm a k).\n          assert (k*a*p <= k*v*p) as G.\n          { repeat (apply Nat.mul_le_mono; auto). }\n          revert G; generalize (b*p) (a*r) (k*a*p) (k*v*p); intros; lia. }\n        split.\n        { rewrite H1; apply is_gcd_moduplus; auto. }\n        split.\n        { rewrite H1; apply is_lcm_moduplus with g; auto. }\n        split; auto.\n        split.\n        { rewrite H1, H6, H7, Nat.mul_add_distr_r, Nat.mul_assoc; lia. }\n        split; auto.\n        { rewrite (Nat.add_comm _ u), <- Nat.add_sub_assoc.\n          +  apply Nat.add_le_mono; auto. \n             generalize (k*v) (k*a); intros; lia.\n          + apply Nat.mul_le_mono; auto. }\n    Defined.\n  \n    Hint Resolve is_gcd_sym is_lcm_sym : core.\n\n    Definition bezout_generalized p q : { a : nat \n                                      & { b : nat \n                                      & { g : nat\n                                      & { l : nat \n                                        | a*p+b*q = g + l\n                                       /\\ is_gcd p q g\n                                       /\\ is_lcm p q l } } } }.\n    Proof.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; exists 0, 1, q, 0; repeat (split; auto). }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; exists 1, 0, p, 0; repeat (split; auto). }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct (@bezout_generalized_lt p q)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.\n        exists a, b, g, l; auto.\n      + subst q; exists 1, 1, p, p.\n        repeat split; auto; lia.\n      + destruct (@bezout_generalized_lt q p)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.\n        exists b, a, g, l; repeat (split; auto); lia.\n    Qed.\n\n  End bezout_generalized.\n\n  Section gcd_lcm.\n\n    Let gcd_full p q : sig (is_gcd p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & g & _ & _ & ? & _).\n      exists g; auto.\n    Qed.\n\n    Definition gcd p q := proj1_sig (gcd_full p q).\n    Fact gcd_spec p q : is_gcd p q (gcd p q).\n    Proof. apply (proj2_sig _). Qed.\n\n    Let lcm_full p q : sig (is_lcm p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & _ & l & _ & _ & ?).\n      exists l; auto.\n    Qed.\n\n    Definition lcm p q := proj1_sig (lcm_full p q).\n    Fact lcm_spec p q : is_lcm p q (lcm p q).\n    Proof. apply (proj2_sig _). Qed.\n\n  End gcd_lcm.\n     \nEnd bezout.\n\nSection division.\n\n  Fact div_full q p : { n : nat & { r | q = n*p+r /\\ (p <> 0 -> r < p) } }.\n  Proof.\n    case_eq p.\n    + intro; exists 0, q; subst; split; auto; intros []; auto.\n    + intros k H; destruct (@euclid q p) as (n & r & H1 & H2); try lia.\n      exists n, r; rewrite <- H; split; auto.\n  Qed.\n\n  Definition div q p := projT1 (div_full q p).\n  Definition rem q p := proj1_sig (projT2 (div_full q p)).\n\n  Fact div_rem_spec1 q p : q = div q p * p + rem q p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact div_rem_spec2 q p : p <> 0 -> rem q p < p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact rem_0 q : rem q 0 = q.\n  Proof.\n    generalize (div_rem_spec1 q 0).\n    rewrite Nat.mul_comm; auto.\n  Qed.\n\n  Fact div_rem_uniq p n1 r1 n2 r2 : \n        p <> 0 -> n1*p + r1 = n2*p + r2 -> r1 < p -> r2 < p -> n1 = n2 /\\ r1 = r2.\n  Proof.\n    intros H1 H2 H3 H4.\n    assert (n1 = n2) as E.\n    destruct (lt_eq_lt_dec n1 n2) as [ [ H | ] | H ]; auto.\n    + replace n2 with (n2-n1 + n1) in H2 by lia.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n2-n1)*p) as H5.\n      { apply Nat.mul_le_mono; lia. }\n      simpl in H5; lia.\n    + replace n1 with (n1-n2 + n2) in H2 by lia.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n1-n2)*p) as H5.\n      { apply Nat.mul_le_mono; lia. }\n      simpl in H5; lia.\n    + subst; lia.\n  Qed.\n\n  Fact div_prop q p n r : q = n*p+r -> r < p -> div q p = n.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p _ (rem q p) n r); auto.\n    + lia.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; lia.\n  Qed.\n\n  Fact rem_prop q p n r : q = n*p+r -> r < p -> rem q p = r.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p (div q p) _ n r); auto.\n    + lia.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; lia.\n  Qed.\n\n  Fact rem_idem q p : q < p -> rem q p = q.\n  Proof. apply rem_prop with 0; auto. Qed.\n\n  Fact rem_rem x m : rem (rem x m) m = rem x m.\n  Proof.\n    destruct (eq_nat_dec m 0).\n    + subst; rewrite !rem_0; auto.\n    + apply rem_idem, div_rem_spec2; auto.\n  Qed.\n\n  Fact is_gcd_rem p n a : is_gcd p n a <-> is_gcd p (rem n p) a.\n  Proof.\n    rewrite (div_rem_spec1 n p) at 1; apply is_gcd_mult.\n  Qed.\n\n  Fact rem_erase q n p r : q = n*p+r -> rem q p = rem r p.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ | Hp ]; subst.\n    + rewrite Nat.mul_comm, rem_0, rem_0; auto.\n    + destruct (div_full r p) as (m & r' & H1 & H2).\n      specialize (H2 Hp).\n      rewrite rem_prop with r p m r'; auto.\n      intros; apply rem_prop with (n+m); auto.\n      rewrite Nat.mul_add_distr_r; lia.\n  Qed.\n\n  Fact divides_div q p : divides p q -> q = div q p * p.\n  Proof.\n    intros (k & Hk).\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + subst; do 2 (rewrite Nat.mul_comm; simpl); auto.\n    + rewrite (@div_prop q p k 0); lia.\n  Qed.\n\n  Fact divides_rem_eq q p : divides p q <-> rem q p = 0.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    * subst; rewrite rem_0; split.\n      + apply divides_0_inv.\n      + intros; subst; apply divides_0.\n    * split.\n      + intros (n & Hn).\n        apply rem_prop with n; lia.\n      + intros H.\n        generalize (div_rem_spec1 q p).\n        exists (div q p); lia.\n  Qed.\n\n  Fact rem_of_0 p : rem 0 p = 0.\n  Proof.\n    destruct p.\n    + apply rem_0.\n    + apply rem_prop with 0; lia.\n  Qed.\n\n  Hint Resolve divides_0_inv : core.\n\n  Fact divides_dec q p : { k | q = k*p } + { ~ divides p q }.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + destruct (eq_nat_dec q 0) as [ Hq | Hq ].\n      * left; subst; exists 1; auto.\n      * right; contradict Hq; subst; auto.\n    + destruct (@euclid q p Hp) as (n & [ | r ] & H1 & H2).\n      * left; exists n; subst; rewrite Nat.add_comm; auto.\n      * right; intros (m & Hm).\n        rewrite <- Nat.add_0_r in Hm.\n        rewrite Hm in H1.\n        destruct (div_rem_uniq _ _ Hp H1); lia.\n  Qed.\n\nEnd division.\n\nSection rem.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Fact rem_plus_rem a b : rem (a+rem b p) p = rem (a+b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite Nat.add_assoc.\n    symmetry; apply rem_erase with (div (b) p); ring.\n  Qed.\n\n  Fact rem_mult_rem a b : rem (a*rem b p) p = rem (a*b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite Nat.mul_add_distr_l, Nat.mul_assoc.\n    symmetry; apply rem_erase with (a*div b p); auto.\n  Qed.\n\n  Fact rem_diag : rem p p = 0.\n  Proof using Hp. apply rem_prop with 1; lia. Qed.\n\n  Fact rem_lt a : a < p -> rem a p = a.\n  Proof using Hp. apply rem_prop with 0; lia. Qed.\n\n  Fact rem_plus a b : rem (a+b) p = rem (rem a p + rem b p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite (div_rem_spec1 b p) at 1.\n    apply rem_erase with (div a p + div b p).\n    ring.\n  Qed.\n\n  Fact rem_scal k a : rem (k*a) p = rem (k*rem a p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite Nat.mul_add_distr_l.\n    apply rem_erase with (k*div a p).  \n    ring.\n  Qed.\n\n  Fact rem_plus_div a b : divides p b -> rem a p = rem (a+b) p.\n  Proof using Hp. \n    intros (n & Hn); subst.\n    rewrite <- rem_plus_rem.\n    f_equal.  \n    rewrite <- rem_mult_rem, rem_diag, Nat.mul_0_r, rem_of_0; lia.\n  Qed.\n\n  Fact div_eq_0 n : n < p -> div n p = 0.\n  Proof using Hp. intros; apply div_prop with n; lia. Qed.\n\n  Fact div_of_0 : div 0 p = 0.\n  Proof using Hp. apply div_eq_0; lia. Qed.\n\n  Fact div_ge_1 n : p <= n -> 1 <= div n p.\n  Proof using Hp.\n    intros H2.\n    rewrite (div_rem_spec1 n p) in H2.\n    generalize (div_rem_spec2 n Hp); intros H3.\n    destruct (div n p); lia.\n  Qed.\n\nEnd rem.\n\nFact divides_rem_rem p q a : divides p q -> rem (rem a q) p = rem a p.\nProof.\n  destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n  { intros (k & ->); subst; rewrite Nat.mul_0_r.\n    repeat rewrite rem_0; auto. }\n  intros H.\n  generalize (div_rem_spec1 a q); intros H1.\n  destruct H as (k & ->).\n  rewrite H1 at 2.\n  rewrite Nat.add_comm.\n  apply rem_plus_div; auto.\n  do 2 apply divides_mult.\n  apply divides_refl.\nQed.\n \nFact divides_rem_congr p q a b : divides p q -> rem a q = rem b q -> rem a p = rem b p.\nProof.\n  intros H1 H2.\n  rewrite <- (divides_rem_rem a H1),\n          <- (divides_rem_rem b H1).\n  f_equal; auto.\nQed.\n\nFact div_by_p_lt p n : 2 <= p -> n <> 0 -> div n p < n.\nProof.\n  intros H1 H2.\n  rewrite (div_rem_spec1 n p) at 2.\n  replace p with (2+(p-2)) at 3 by lia.\n  rewrite Nat.mul_add_distr_l.\n  generalize (div n p*(p-2)); intros x.\n  destruct (le_lt_dec p n) as [ Hp | Hp ].\n  + apply div_ge_1 in Hp; lia.\n  + rewrite rem_lt; lia.\nQed.\n\nSection rem_2.\n\n  Fact rem_2_is_0_or_1 x : rem x 2 = 0 \\/ rem x 2 = 1.\n  Proof. generalize (rem x 2) (@div_rem_spec2 x 2); intros; lia. Qed.\n\n  Fact rem_2_mult x y : rem (x*y) 2 = 1 <-> rem x 2 = 1 /\\ rem y 2 = 1.\n  Proof. \n    generalize (rem_2_is_0_or_1 x) (rem_2_is_0_or_1 y).\n    do 2 rewrite <- rem_mult_rem, Nat.mul_comm.\n    intros [ H1 | H1 ] [ H2 | H2 ]; rewrite H1, H2; simpl; rewrite rem_lt; lia.\n  Qed.\n\n  Fact rem_2_fix_0 : rem 0 2 = 0.\n  Proof. apply rem_lt; lia. Qed.\n\n  Fact rem_2_fix_1 n : rem (2*n) 2 = 0.\n  Proof. apply divides_rem_eq; exists n; ring. Qed.\n\n  Fact rem_2_fix_2 n : rem (1+2*n) 2 = 1.\n  Proof.\n    rewrite <- rem_plus_rem,rem_2_fix_1, rem_lt; lia.\n  Qed.\n\n  Fact rem_2_lt n : rem n 2 < 2.\n  Proof. apply div_rem_spec2; lia. Qed.\n\n  Fact div_2_fix_0 : div 0 2 = 0.\n  Proof. apply div_of_0; lia. Qed.\n\n  Fact div_2_fix_1 n : div (2*n) 2 = n.\n  Proof. apply div_prop with 0; lia. Qed.\n\n  Fact div_2_fix_2 n : div (1+2*n) 2 = n.\n  Proof. apply div_prop with 1; lia. Qed.\n\n  Fact euclid_2_div n : n = rem n 2 + 2*div n 2 /\\ (rem n 2 = 0 \\/ rem n 2 = 1).\n  Proof.\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.\n  Qed.\n\n  Fact euclid_2 n : exists q, n = 2*q \\/ n = 1+2*q.\n  Proof. \n    exists (div n 2).\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.\n  Qed.\n\nEnd rem_2.\n\nLocal Hint Resolve divides_mult divides_mult_r divides_refl : core.\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/Shared/Libs/DLW/Utils/gcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7863741784160134}}
{"text": "Require Import Nat PeanoNat.\n\nDefinition PredTh := forall n m, n <= m -> pred n <= pred m.\n\nTheorem predTh : PredTh.\nProof.\n  unfold PredTh.\n  induction n.\n  - intros m H.\n    exact (le_0_n _).\n  - intros [] H; simpl.\n    + exfalso.\n      exact (Nat.nle_succ_0 _ H).\n    + apply le_S_n.\n      exact H.\nQed.\n\nRequire Import ssreflect.\n\nTheorem predTh2 : PredTh.\nProof.\n  elim=> [ |n IHn] m H /=.\n  - by apply: le_0_n.\n  - case: m H => [| m] H /=.\n    + by case: (Nat.nle_succ_0 _ H).\n    + exact (le_S_n _ _ H).\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/csim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7862740450289484}}
{"text": "Require Export NArith.\nRequire Export base.\nRequire Import Sets SetInterface SetProperties Relations.\nRequire Import Vectors.Vector.\n\n\n(** Boolean strict less-than order on values of type [nat]. *)\n\nFixpoint ltb (n m:nat) : bool :=\n  match n,m with\n    | O , S _ => true\n    | S k, S l => ltb k l\n    | _,_ => false\n  end.\n\n(** Some basic properties of [ltb] *)\n\nProposition ltb0 : forall n, ltb n 0 = false.\nProof.\n  induction n;simpl;intros;auto.\nQed.\n\nProposition ltb_S : forall n, ltb n (S n) = true.\nProof.\n  induction n;simpl;eauto.\nQed.\n\nLemma ltb_correct : forall n m, ltb n m = true -> n < m.\nProof.\n  induction n.\n  - intros. destruct m. discriminate. omega.\n  - simpl. intros. destruct m. \n    + discriminate.\n    + apply IHn in H. omega.\nDefined.\n\nLemma ltb_complete : forall n m, n < m -> ltb n m = true.\nProof.\n  induction n.\n  - intros. destruct m.\n    + omega. \n    + auto.\n  - intros. inv H.\n    + simpl. apply ltb_S.\n    + simpl. apply IHn. omega.\nDefined.\n\nLemma ord_lt_correct :\n  forall m n, ltb m n = true -> ltb (S m) (S n) = true.\nProof.\n  intros.\n  apply ltb_correct in H.\n  apply ltb_complete.\n  abstract(omega).\nQed.\n\n(** * Definition of finite ordinal *)\n(** The structure [ord] contains a number a number [m] and a proof involving [ltb] *)\n\nRecord ord (n:N) := Ord {nat_of_ord:> N; ord_lt: ltb nat_of_ord n = true }.\n\n(** [O] and [S _] smart constructors for [ord] *)\n  \nDefinition ord0 n : ord (S n) := @Ord  (S n) 0 eq_refl.\nDefinition ordS n (m:ord n) := @Ord (S n) (S m) ((ord_lt n m)). \n\n(** * Equality and strict orderings over [ord] *)\n(** We consider only the underlying natural number, and ignore the proofs. *)\n\nDefinition ord_Eq n := \n  fun x y:ord n => @eq nat x y.\n  \nDefinition ord_Lt n := \n  fun (x y:ord n) => (nat_of_ord n x) <<< (nat_of_ord n y).\n\nDefinition ord_Cmp n := \n  fun (x y:ord n) => _cmp (nat_of_ord n x) (nat_of_ord n y).\n\n\n(** Bureaucratic instances to register [ord] as an ordered typ *)\n\nInstance ord_Eq_equiv : forall n, Equivalence (ord_Eq n).\nProof.\n  intros;constructor;repeat red;auto.\n  intros;inversion H;inversion H0;auto.\nQed.\n\nInstance ord_Lt_trans : forall n, Transitive (ord_Lt n).\nProof.\n  intro;repeat red;intros.\n  inversion H;inversion H0;subst;now(omega).\nQed.\n\nProposition ord_Lt_irrefl n :\n  forall  x y,\n    ord_Lt n x y -> ~ord_Eq n x y.\nProof.\n  intros.\n  intro.\n  inversion H.\n  - inversion H0;omega.\n  - inversion H0;omega.\nQed.\n\nInstance ord_StrictOrder : forall n, StrictOrder (ord_Lt n) (ord_Eq n).\nProof.\n  intro;constructor;autotc.\n  intros;apply ord_Lt_irrefl;auto.\nQed.\n\nLemma ord_Eq_unique :  \n  forall n (x y:ord n), ord_Eq n x y -> x = y.\nProof.\n  unfold ord_Eq.\n  destruct x. destruct y.\n  simpl.\n  intros.\n  subst.\n  f_equal.\n  eapply Eqdep_dec.UIP_dec.\n  decide equality.\nQed.\n\nLtac ord_eq_un H := apply ord_Eq_unique in H;subst.\n\nInstance ord_UStrict : forall n : nat, StrictOrder (ord_Lt n) eq.\nProof.\n  intro.\n  constructor;autotc.\n  intros.\n  unfold ord_Lt in H.\n  intro.\n  rewrite H0 in H.\n  order.\nQed.\n\nInstance ord_UOrderedType : forall n, UsualOrderedType (ord n) :=\n  { SOT_lt  := ord_Lt n ;\n    SOT_cmp := ord_Cmp n }.\nProof.\n  intros.\n  case_eq(ord_Cmp n x y);intros;constructor.\n  - apply compare_2,ord_Eq_unique in H;auto.\n  - apply compare_1 in H;unfold ord_Lt;auto.\n  - apply compare_3 in H;unfold ord_Lt;auto.\nDefined.\n\n(*Definition ordS_map n (l:list (ord n)) : list (ord (S n)) := List.map (@ordS n) l.*)\n(** Mapping adition to a list of ordinals *)\n\nDefinition ordS_mapS n (s:set (ord n)) : set (ord (S n)) := map (@ordS n) s.\n\n(* Fixpoint smaller_ords n  {struct n} : list (ord n) := *)\n(*   match n with *)\n(*     | 0 => nil *)\n(*     | S m => cons (ord0 m) (@ordS_map m (smaller_ords m)) *)\n(*   end. *)\n\n(** * Function to generate the set of all ordinals under a natural [n] *)\n\nFixpoint smaller_ordsS n  {struct n} : set (ord n) :=\n  match n with\n    | 0 => {}\n    | S m => add (ord0 m) (@ordS_mapS m (smaller_ordsS m))\n  end.\n\n(* Lemma all_in_smaller_ord :  *)\n(*   forall n (x:ord n),  List.In x (smaller_ords n). *)\n(* Proof. *)\n(*   induction n. *)\n(*   - simpl;intros;inv x;pose proof ltb0 nat_of_ord0;congruence. *)\n(*   - intros;simpl. right.  unfold ordS_map. *)\n(*     destruct x. *)\n(*     assert(ltb nat_of_ord0 n = true). *)\n(*     simpl in ord_lt0. *)\n(*     apply ltb_correct in ord_lt0. *)\n(*     apply ltb_complete. *)\n(*     omega. *)\n(*     Check @Ord . *)\n\nLemma ord_ind' (P: forall n, ord n -> Prop) \n  (H0: forall n, P (S n) (ord0 n))\n  (HS: forall n i, P n i -> P (S n) (ordS n i)): \n  forall n i, P n i.\nProof. \n  induction n.\n  - intro i. inv i. pose proof ltb0 nat_of_ord0. congruence. \n  - destruct i as [[|i] Hi].\n    replace ({| nat_of_ord := 0; ord_lt := Hi |}) with\n      ((ord0 n)). apply H0.\n    apply ord_Eq_unique.\n    unfold ord0.\n    unfold ord_Eq. simpl.\n    reflexivity.\n    change ({| nat_of_ord := S i; ord_lt := Hi |}) with (@ordS n (@Ord n i Hi)).\n    apply HS.\n    apply IHn.\nQed.\n\n(* Lemma all_in_smaller_ords :  *)\n(*   forall n i,  List.In i (smaller_ords n). *)\n(* Proof. *)\n(*   induction i using ord_ind'. *)\n(*   - simpl. left;auto. *)\n(*   - simpl. right. apply List.in_map_iff. exists i. auto. *)\n(* Qed. *)\n\nGlobal Instance ord_S_m : forall n,  Proper (_eq ==> _eq) (ordS n).\nProof.\n  repeat red;intros.\n  f_equal.\n  repeat red in H.\n  assumption.\nQed.\n\nLemma all_in_smaller_ordsS : \n  forall n i,  i \\In (smaller_ordsS n).\nProof.\n  induction i using ord_ind'.\n  - simpl. apply add_1. reflexivity. \n  - simpl. apply add_2. apply map_iff. \n    + autotc.\n    + exists i. auto.\nQed.\n\nFixpoint pow2(n:nat):nat :=\n  match n with\n    | O   => 1\n    | S m => 2*pow2 m\n  end.\n\n\nProposition pow2_geq_1 :\n  forall n, 1 <= pow2 n .\nProof.\n  induction n;simpl;auto with arith.\nQed.\n\n(** Evaluate the nth-bit of the natural number wrapped in the ordinal *)\n\nDefinition nth_bit(m:nat)(k:ord m)(n:nat):bool := N.testbit_nat (N.of_nat k) n.\n", "meta": {"author": "dmrpereira", "repo": "PDCoq", "sha": "c0f6a96177538eae3e933f35265522a5f05582fa", "save_path": "github-repos/coq/dmrpereira-PDCoq", "path": "github-repos/coq/dmrpereira-PDCoq/PDCoq-c0f6a96177538eae3e933f35265522a5f05582fa/KAT/theories/atoms_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.786274038182484}}
{"text": "Require Import nat.\nRequire Import bool.\nRequire Import syntax.\nRequire Import eval.\nRequire Import state.\n\n\nInductive aevalR:State -> aexp -> nat -> Prop :=\n| E_ANum  : forall e n, aevalR e (ANum n) n\n| E_AKey  : forall e k, aevalR e (AKey k) (e k)\n| E_APlus : forall e n1 n2 a1 a2, \n    aevalR e a1 n1 -> aevalR e a2 n2 -> aevalR e (APlus  a1 a2) (n1 + n2)\n| E_AMinus: forall e n1 n2 a1 a2, \n    aevalR e a1 n1 -> aevalR e a2 n2 -> aevalR e (AMinus a1 a2) (n1 - n2)\n| E_AMult : forall e n1 n2 a1 a2, \n    aevalR e a1 n1 -> aevalR e a2 n2 -> aevalR e (AMult  a1 a2) (n1 * n2)\n.\n\nInductive bevalR:State-> bexp -> bool -> Prop :=\n| E_BTrue : forall e, bevalR e BTrue true\n| E_BFalse: forall e, bevalR e BFalse false\n| E_BEq   : forall e n1 n2 a1 a2, \n    aevalR e a1 n1 -> aevalR e a2 n2 -> bevalR e (BEq a1 a2) (eqb n1 n2) \n| E_BLe   : forall e n1 n2 a1 a2, \n    aevalR e a1 n1 -> aevalR e a2 n2 -> bevalR e (BLe a1 a2) (leb n1 n2)\n| E_BNot  : forall e b1 e1, \n    bevalR e e1 b1 -> bevalR e (BNot e1) (negb b1)\n| E_BAnd  : forall e b1 b2 e1 e2,\n    bevalR e e1 b1 -> bevalR e e2 b2 -> bevalR e (BAnd e1 e2) (andb b1 b2) \n.\n\nTheorem aeval_iff_aevalR : forall (env:State) (a:aexp) (n:nat),\n    aevalR env a n <-> aeval env a = n.\nProof.\n    intros env a n. split.\n    - intro H. induction H as   [ n\n                                | k\n                                | e n1 n2 a1 a2 H1 IH1 H2 IH2\n                                | e n1 n2 a1 a2 H1 IH1 H2 IH2\n                                | e n1 n2 a1 a2 H1 IH1 H2 IH2\n                                ].\n        + reflexivity.\n        + reflexivity.\n        + simpl. rewrite IH1, IH2. reflexivity.\n        + simpl. rewrite IH1, IH2. reflexivity.\n        + simpl. rewrite IH1, IH2. reflexivity.\n\n    - revert n env. induction a as [n|k|a1 H1 a2 H2| a1 H1 a2 H2| a1 H1 a2 H2].\n        + simpl. intros p e H. subst. apply E_ANum.\n        + simpl. intros p e H. subst. apply E_AKey.\n        + simpl. intros p e H. subst. apply E_APlus. \n            { apply H1. reflexivity. }\n            { apply H2. reflexivity. }\n        + simpl. intros p e H. subst. apply E_AMinus. \n            { apply H1. reflexivity. }\n            { apply H2. reflexivity. }\n        + simpl. intros p e H. subst. apply E_AMult. \n            { apply H1. reflexivity. }\n            { apply H2. reflexivity. }\nQed.\n\nTheorem aeval_iff_aevalR' : forall (env:State) (a:aexp) (n:nat),\n    aevalR env a n <-> aeval env a = n.\nProof. \n    split. \n    - intros H. induction H; subst; reflexivity.\n    - revert n env. induction a as [n|k|a1 H1 a2 H2| a1 H1 a2 H2| a1 H1 a2 H2]; \n        simpl; intros; subst; constructor; \n        try apply H1; try apply H2; reflexivity.  \nQed.\n\n\nTheorem beval_iff_bevalR : forall (env:State) (e:bexp) (b:bool),\n    bevalR env e b <-> beval env e = b.\nProof.\n    split.\n    - intros H. induction H; subst; try reflexivity; simpl.\n        + assert (aeval e a1 = n1) as H1. \n            { apply aeval_iff_aevalR. assumption. }\n          assert (aeval e a2 = n2) as H2. \n            { apply aeval_iff_aevalR. assumption. }\n           rewrite H1, H2. reflexivity.\n        +  assert (aeval e a1 = n1) as H1. \n            { apply aeval_iff_aevalR. assumption. }\n           assert (aeval e a2 = n2) as H2. \n               { apply aeval_iff_aevalR. assumption. }\n           rewrite H1, H2. reflexivity.\n    - revert b. induction e as [ | |a1 a2|a1 a2|e1 H1|e1 H1 e2 H2];\n        intros; subst; simpl; constructor; try apply aeval_iff_aevalR; \n        try reflexivity; try apply H1; try apply H2; 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/sf/evalR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7862303253958557}}
{"text": "(** * Basic programming in Coq *)\n\n(** First, a few keywords about Coq as a programming language:\n    - Purely functional (cf. Haskell or a subset of OCaml)\n    - Closed world (no I/O, no random, ...)\n    - Typed (includes ML-like types, and a lot more)\n    - Terminating (hence not Turing-complete)\n    - In fact, strongly normalizing (pick your favorite\n      reduction strategy !)\n    - Total: no exception or abnormal outputs.\n\n    These design choices allow an easy reasoning about \"(f x)\".\n*)\n\n\n(** I) A quick tour of predefined datatypes and functions. *)\n\nRequire Import Bool Arith ZArith List.\n\n(** bool *)\nCheck true.\nCheck false.\nCheck true && false.\nCompute true && false.\nPrint \"&&\".\nPrint \"||\".\nPrint negb.\nPrint xorb.\nCompute if true && false then false else true.\n\n(** nat : natural numbers via unary encoding *)\nCheck 0.\nCheck 10000.\nPrint Nat.pred. (** or simply pred *)\nCompute pred 2.\nCompute pred 0. (** Rounded to 0 *)\nCheck 1+1.\nCompute 1+1.\nPrint \"+\". (* Nat.add or plus *)\nPrint \"-\".\nCompute 1-2. (* Rounded to 0 *)\nCompute Nat.log2 ((2^10)/3).\n\n\n(** N : natural numbers via binary encoding *)\nCheck 10.\nOpen Scope N.\nCheck 10.\nCheck 10%nat.\nCompute N.pred 2.\nCompute N.pred 0.\nCompute (2^(2^8)).\nCompute (3^(3^8)).\nCompute N.log2 (3^(3^8)).\nCheck 1+1.\nPrint \"+\".\nCompute 1-2.\nClose Scope N.\n\n(** Z : integers via binary encoding *)\nOpen Scope Z.\nCheck 10.\nCheck -1.\nCheck 1+1.\nPrint \"+\".\nCompute 1-2.\nCompute 1/0.\nClose Scope Z.\n\n(** Pairs *)\nCheck (1,true).\nCheck fun (p:nat*bool) => let (a,b) := p in (b,a).\n\n(** Lists *)\nCheck 1::2::3::nil.\nCompute (1::2::3::nil)++(4::5::6::nil).\nLocate \"::\".\nPrint \"++\".\n\n\n\n(** II) Inductive types *)\n\n(** How are defined these usual types ? *)\n(** How do we define new ones ? *)\n\nPrint bool.\n(* Inductive bool : Set :=\n     | true : bool\n     | false : bool.  *)\n\nPrint nat.\n(* Inductive nat : Set :=\n     | O : nat\n     | S : nat -> nat.  *)\n\nPrint N.\n(* Inductive N : Set :=\n     | N0 : N\n     | Npos : positive -> N. *)\n\nPrint Z.\n(* Inductive Z : Set :=\n      | Z0 : Z\n      | Zpos : positive -> Z\n      | Zneg : positive -> Z. *)\n\nPrint positive.\n(* Inductive positive : Set :=\n     | xI : positive -> positive\n     | xO : positive -> positive\n     | xH : positive. *)\n(* xH is 1, xI adds a lower 1 digit, xO adds a lower 0 digit:\n   Hence 6 = 110 = (xO (xI xH)). *)\n\nPrint list.\n(* Inductive list (A:Type) : Type :=\n     | nil : list A\n     | cons : A -> list A -> list A. *)\n(* This is a first \"parameterized\" type (by another type A). *)\nCheck list.\nCheck list nat.\nCheck cons 1 nil.\nCheck nil.\nCheck nil (A:=bool).\n\n(** Another parameterized type : *)\nPrint option.\n(* Inductive option (A:Type) : Type :=\n      | Some : A -> option A\n      | None : option A.\n*)\n\n(** Nota : some inductive definitions are refused by Coq, since\n    they would endanger the coherence of the system.\n    Cf. the \"positivity condition\" in the documentation. *)\n\n\n\n(** III) Function abstraction *)\n\nDefinition id_nat (n:nat) := n.\nDefinition id_nat2 (n:nat) : nat := n.\nDefinition id_nat3 : nat -> nat := fun n => n.\nDefinition id_nat4 := fun (n:nat) => n.\n\n(** Polymorphism *)\n\nDefinition id (A:Type) : A -> A := fun x => x.\nCheck id.\nDefinition id2 : forall A, A->A := fun _ x => x.\nCheck id2.\nDefinition id3 := fun (A:Type)(x:A) => x.\nCheck id3.\n\nCompute id _ 0.  (* Coq infers the type argument *)\nCompute id nat.  (* Partial application, we're back to id_nat *)\n\n(* Via \"implicit arguments\", we can hide the types. *)\n\nDefinition id4 := fun {A:Type}(x:A) => x.\nCheck id4 0.\nCheck id4 (A:=nat).\nCheck @id4.\n\n(* See also \"Set Implicit Arguments\". *)\n\n\n\n(** IV) Pattern matching *)\n\nDefinition negb (b:bool) :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nPrint negb. (* we end back with an \"if ... then ... else\" *)\n\nDefinition iszero (n:nat) :=\n match n with\n | O => true\n | S _ => false\n end.\n\nCompute iszero 55.\nPrint iszero.\n\nDefinition pred n := match n with\n | O => O\n | S p => p\n end.\n\nCheck pred.\nCompute pred 10000.\n\nDefinition succ n := S n.\nDefinition succ' := fun n => S n.\nDefinition succ'' := S.\n\n(** Complex pattern matching : bi-predecessor *)\n\nDefinition predpred n :=\n  match n with\n   | S (S m) => m\n   | _ => O\n  end.\n\nPrint predpred.\n\n\n\n(** V) Recursion *)\n\nFixpoint double n :=\n  match n with\n  | O => O\n  | S n => S (S (double n))\n  end.\n\nCompute double 6.\n\nFixpoint plus n m :=\n match n with\n  | O => m\n  | S n' => S (plus n' m)\n end.\n\nFixpoint div2 n :=\n  match n with\n   | S (S m) => S (div2 m)\n   | _ => O\n  end.\n\nCompute div2 22.\n\n(** Fixpoint is no more than a Definition followed by an inner\n    recursion operator \"fix\". *)\n\nDefinition plus' :=\n  fix plusrec n m :=\n    match n with\n    | O => m\n    | S n' => S (plusrec n' m)\n    end.\n\n(** This \"fix\" construct may help for some tricky recursive\n    definitions (ackermann, list merge, ...). *)\n\n(** Fixpoint and polymorphism *)\n\nFixpoint length {A:Type} (l:list A) :=\n  match l with\n  | nil => 0\n  | x::l' => S (length l')\n  end.\n\n\n(** Restrictions on recursion : the termination checker.\n    Coq avoids infinite computations by checking that one\n    specific argument gets \"structurally smaller\" at each\n    recursive call.\n    Otherwise:\n     - undefined objects (e.g. a boolean value not true nor false)\n     - contradictory objects (e.g. implying true=false)\n     - direct inhabitant of False (you can program your proofs).\n*)\n\n(* Fixpoint alien (b:bool) : bool := alien b. *)\n\n(* Fixpoint bogus (b:bool) : bool := negb (bogus b). *)\n\n(* Fixpoint loop (n:nat) : False := loop n.\n   Definition impossible : False := loop 0. *)\n\n\n(** This decreasing constraint might get into the way: *)\n\nCompute 3 <=? 5.\nPrint \"<=?\".\n\nFail Fixpoint div (a b:nat) : nat :=\n  if b <=? a\n  then S (div (a-b) b)\n  else 0.\n\n(** Possible workarounds:\n    1) an extra argument used as counter, or \"fuel\"\n    2) old-style approach: use of accessibility relation \"acc\"\n    3) use of modern extensions of Coq: \"Function\" or \"Program\"\n       (see later). *)\n\n\n(** The previous \"div\", with a counter *)\n\nFixpoint div_count (n:nat)(a b:nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' =>\n        if b <=? a\n        then S (div_count n' (a-b) b)\n        else 0\n  end.\n\n(** Here starting with n=a is always enough. *)\n\nDefinition div (a b:nat) : nat := div_count a a b.\n\nCompute (div 100 3).\nCompute (div 100 0).\n\n(** Btw, another (awkward) definition of div is directly accepted *)\n\nFixpoint div_direct a b :=\n  match a with\n    | O => O\n    | S a' =>\n      let c := div_direct a' b in\n      if ((S c)*b) <=? a then S c else c\n  end.\n\nCompute div_direct 100 3.\n\n\n(** VI) Totality *)\n\n(** By design, all Coq functions are total :\n    - when f:A->B and x:A, then (f x) is always meaningful\n      (and has type B).\n    - no exceptions, failure, non-exhaustive patterns, ...\n\n    Three ways to handle partial functions :\n    1) answer an arbitrary value for problematic inputs\n      (for instance 2-3=0, or 3/0 = 0)\n    2) use the \"option\" type to mark the lack of output\n      (for instance 2-3 = None, 3-2 = Some 1)\n    3) use \"dependent types\" and restrict the input via a\n      logical precondition.\n       minus : forall a b, b<=a -> nat. *)\n\nDefinition pred_option (n:nat) : option nat :=\n  match n with\n    | O => None\n    | S n' => Some n'\n  end.\n\nFixpoint minus_option (a b:nat) : option nat :=\n  match a, b with\n    | _, 0 => Some a\n    | 0, S _ => None\n    | S a', S b' => minus_option a' b'\n  end.\n\nCompute (minus_option 2 3).\nCompute (minus_option 2 2).\n\n(* So far so good, but a real use would be quite painful.\n   Think of 3+(5-(4-2)): *)\n\nDefinition smallcomputation :=\n match minus_option 4 2 with\n | Some r =>\n   match minus_option 5 r with\n   | Some r' => Some (3+r')\n   | None => None\n   end\n | None => None\n end.\n\nCompute smallcomputation.\n\n(** Monads might help in this situation, but that's another story. *)\n", "meta": {"author": "yurug", "repo": "coqepit", "sha": "3a305c888d3e909b4525e18a16a6b5127f583e1b", "save_path": "github-repos/coq/yurug-coqepit", "path": "github-repos/coq/yurug-coqepit/coqepit-3a305c888d3e909b4525e18a16a6b5127f583e1b/support/day1/lesson2-progs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7861898627148817}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export logic.\nRequire Coq.omega.Omega.\n\nInductive even : nat -> Prop :=\n  | ev_0 : even 0\n  | ev_SS (n : nat) (H : even n) : even (S (S n)).\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\nInductive even' : nat -> Prop :=\n  | ev_0' : even' 0\n  | ev_SS' : forall n, even' n -> even' (S (S n)). \n\nTheorem ev_4 : even 4.\nProof. \n  apply ev_SS.\n  apply ev_SS.\n  apply ev_0.\nQed.\n\nTheorem ev_4' : even 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\nTheorem ev_plus4 :\n  forall n, even n -> even (4 + n).\nProof.\n  intros n. \n  simpl.\n  intros Hn.\n  apply ev_SS.\n  apply ev_SS.\n  apply Hn.\nQed.\n\nTheorem ev_double :\n  forall n,\n  even (double n).\nProof.\n  induction n.\n  - simpl.\n    apply  ev_0.\n  - simpl.\n    apply ev_SS.\n    apply IHn.\nQed.\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  - left.\n    reflexivity.\n  - right.\n    exists n'.\n    split.\n    reflexivity.\n    apply E'.\nQed.\n\nTheorem ev_minus2 : \n  forall n,\n  even n -> even (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - simpl.\n    apply ev_0.\n  - simpl.\n    apply E'.\nQed.\n\nTheorem evSS_ev : \n  forall n,\n  even (S (S n)) -> even n.\nProof.\n  intros n E.\n  destruct E as [| n' E'].\nAbort.\n\nTheorem evSS_ev : \n  forall n, \n  even (S (S n)) -> even n.\nProof. \n  intros n H.\n  apply ev_inversion in H. \n  destruct H.\n - discriminate H.\n - destruct H as [n' [Hnm Hev]].\n   injection Hnm.\n   intro Heq.\n   rewrite Heq.\n   apply Hev.\nQed.\n\nTheorem evSS_ev' : \n  forall n,\n  even (S (S n)) -> even n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'.\nQed.\n\nTheorem one_not_even : ~ even 1.\nProof.\n  intros H. \n  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.\nProof.\n  intros H.\n  inversion H.\nQed.\n\nTheorem SSSSev__even : \n  forall n,\n  even (S (S (S (S n)))) -> even n.\nProof.\n  intros n H.\n  inversion H.\n  inversion H1.\n  apply H3.\nQed.\n\nTheorem SSSSev__even' : \n  forall n,\n  even (S (S (S (S n)))) -> even n.\nProof.\n  intros n H.\n  apply ev_inversion in H.\n  destruct H.\n  + discriminate.\n  + destruct H. \n    destruct H.\n    injection H.\n    intros.\n    apply ev_inversion in H0.\n    destruct H0.\n    - rewrite H0 in H1.\n      discriminate.\n    - destruct H0.\n      destruct H0.\n      rewrite H0 in H1.\n      injection H1.\n      intros. \n      rewrite <- H3 in H2.\n      apply H2.\nQed.\n\nTheorem even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n\nTheorem inversion_ex1 :\n  forall(n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. \n  inversion H.\n  reflexivity.\nQed.\n\nTheorem inversion_ex2 :\n  forall(n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra.\n  inversion contra.\nQed.\n\nLemma ev_even_firsttry :\n  forall n,\n  even n -> exists k, n = double k.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  - exists 0.\n    reflexivity.\n  - simpl.\n    assert (I : (exists k', n' = double k') ->\n           (exists k, S (S n') = double k)).\n   { intros [k' Hk']. \n     rewrite Hk'. exists(S k').\n     reflexivity. }\n   apply I.\nAbort.\n\nLemma ev_even : \n  forall n,\n  even n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - exists 0.\n    reflexivity.\n  - destruct IH as [k' Hk'].\n    rewrite Hk'.\n    exists(S k').\n    reflexivity.\nQed.\n\nTheorem ev_even_iff : \n  forall n,\n  even n <-> exists k, n = double k.\nProof.\n  intros n. \n  split.\n  - apply ev_even.\n  - intros [k Hk].\n    rewrite Hk.\n    apply ev_double.\nQed.\n\nTheorem ev_sum : \n  forall n m,\n  even n -> even m -> even (n + m).\nProof.\n  intros n m Hn Hm.\n  induction Hn.\n  - simpl.\n    apply Hm.\n  - inversion Hm. \n    + simpl.\n      rewrite <- plus_n_O.\n      apply ev_SS.\n      apply Hn.\n    + simpl.\n      apply ev_SS.\n      rewrite H0.\n      apply IHHn.\nQed.\n\nInductive even'' : nat -> Prop :=\n  | even'_0 : even'' 0\n  | even'_2 : even'' 2\n  | even'_sum n m (Hn : even'' n) (Hm : even'' m) : even'' (n + m).\n\nTheorem even'_ev :\n  forall n, \n  even'' n <-> even n.\nProof.\n  intros n.\n  split.\n  + intros.\n    induction H.\n    - apply ev_0.\n    - apply ev_SS.\n      apply ev_0.\n    - apply ev_sum.\n      apply IHeven''1.\n      apply IHeven''2.\n  + intros.\n    induction H.\n    - apply even'_0.\n    - assert (H1: (S (S n)) = 2 + n). \n      * reflexivity.\n      * rewrite H1.\n        apply (even'_sum 2 n).\n        apply even'_2.\n        apply IHeven.\nQed.\n\nTheorem ev_ev__ev : \n  forall n m,\n  even (n + m) -> even n -> even m.\nProof.\n  intros.\n  induction H0. \n  - apply H.\n  - inversion H. \n    apply IHeven.\n    apply H2.\nQed.\n\nTheorem ev_plus_plus : \n  forall n m p,\n  even (n + m) -> even (n + p) -> even (m + p).\nProof.\n  intros n m p H.\n  apply ev_ev__ev. \n  rewrite plus_comm.\n  Search plus.\n  rewrite PeanoNat.Nat.add_shuffle3.\n  rewrite <- plus_assoc.\n  rewrite plus_assoc.\n  apply ev_sum.\n  apply H.\n  rewrite <- double_plus.\n  apply ev_double.\nQed.\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n n : le n n\n  | le_S n m (H : le n m) : le n (S m).\n\nNotation \"m ≤ n\" := (le m n)\n(at level 50).\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.\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\nTheorem test_le3 :\n  (2 ≤ 1) -> 2 + 2 = 5.\nProof.\n  intros H.\n  inversion H.\n  inversion H2.\nQed.\n\nEnd Playground.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nInductive square_of : nat -> nat -> Prop :=\n  | sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 n : even (S n) -> next_even n (S n)\n  | ne_2 n (H : even (S (S n))) : next_even n (S (S n)).\n\nInductive total_relation : nat -> nat -> Prop :=\n  | tr : forall n m, total_relation n m.\n\nInductive empty_relation : nat -> nat -> Prop :=.\n\nLemma le_trans : \n  forall m n o,\n  m <= n -> n <= o -> m <= o.\nProof.\n  intros.\n  rewrite H.\n  apply H0.\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  - reflexivity.\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  inversion H.\n  - reflexivity.\n  - rewrite <- H1.\n    apply le_S.\n    reflexivity.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  induction a.\n  - apply O_le_n.\n  - intros b.\n    simpl.\n    apply n_le_m__Sn_le_Sm.\n    apply IHa.\nQed.\n\nTheorem plus_le : forall n1 n2 m,\n  n1 + n2 <= m ->\n  n1 <= m /\\ n2 <= m.\nProof.\n  intros.\n  split.\n  - rewrite <- H.\n    apply le_plus_l.\n  - rewrite <- H.\n    rewrite plus_comm.\n    apply le_plus_l.\nQed.\n\nTheorem lt_succ_r p q : p < S q <-> p <= q.\nProof.\n  split.\n  - induction p. \n    + intros.\n      apply O_le_n.\n    + intros.\n      apply Sn_le_Sm__n_le_m in H.\n      apply H.\n  - induction p. \n    + intros.\n      unfold lt.\n      apply n_le_m__Sn_le_Sm.\n      apply H.\n    + intros.\n      unfold lt.\n      apply n_le_m__Sn_le_Sm.\n      apply H.\nQed.\n\n Theorem lt_S : \n   forall n m,\n   n < m ->\n   n < S m.\nProof.\n  intros.\n  unfold lt in H.\n  unfold lt.\n  apply le_S in H.\n  apply H.\nQed.\n\nTheorem plus_lt :\n  forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  intros.\n  unfold \"<\" in H.\n  unfold \"<\".\n  induction H.\n  - split. \n    * apply n_le_m__Sn_le_Sm. \n      apply le_plus_l.\n    * apply n_le_m__Sn_le_Sm.\n      rewrite plus_comm.\n      apply le_plus_l.\n  - split.\n    * apply le_S.\n      apply IHle.\n    * apply le_S.\n      apply IHle.\nQed.\n\nTheorem leb_complete : \n  forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  induction n.\n  - induction m.\n    + simpl.\n      intros.\n      reflexivity.\n    + intros.\n      apply le_S.\n      apply IHm.\n      unfold \"<=?\".\n      reflexivity.\n  - induction m.\n    + unfold \"<=?\".\n      intros.\n      inversion H.\n    + intros.\n      apply n_le_m__Sn_le_Sm.\n      apply IHn.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\nProof.\n  intros n m.\n  generalize n as n'.\n  induction m. \n  - intros. \n    destruct n'.\n    + reflexivity.\n    + inversion H. \n  - intros.\n    induction n'.\n    + reflexivity.\n    + apply Sn_le_Sm__n_le_m in H.\n      apply IHm in H.\n      apply H.\nQed.\n\nTheorem leb_true_trans : forall n m o,\n  n <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n  intros.\n  apply leb_correct. \n  apply leb_complete in H.\n  apply leb_complete in H0.\n  rewrite H.\n  apply H0.\nQed.\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  intros.\n  split.\n  - intros.\n    apply leb_complete.\n    apply H.\n  - intros.\n    apply leb_correct.\n    apply H.\nQed.\n\nModule R.\n  \n", "meta": {"author": "s3141p", "repo": "software-foundations", "sha": "a6eee47da487495fff2bba8b3ff7b5e330efe18e", "save_path": "github-repos/coq/s3141p-software-foundations", "path": "github-repos/coq/s3141p-software-foundations/software-foundations-a6eee47da487495fff2bba8b3ff7b5e330efe18e/ind-prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8976952996340946, "lm_q1q2_score": 0.7861898600623535}}
{"text": "Section Group.\n  Variable G : Type.\n  Variable e : G.\n  Variable f : G -> G -> G.\n  Variable i : G -> G.\n\n  Infix \"*\" := f.\n\n  Hypothesis Assoc : forall a b c, a * b * c = a * (b * c).\n  Hypothesis RightIdent : forall a, a * e = a.\n  Hypothesis RightInv : forall a, a * i a = e.\n  \n  Lemma assoc_rewrite : forall a b,\n      a * b * i b = a * (b * i b).\n  Proof.\n    auto.\n  Qed.\n  \n  Hint Rewrite RightInv RightIdent assoc_rewrite.\n\n  Hint Rewrite RightIdent : aux. (* Just a declaration, CreateDb didn't work for rewrite dbs *)\n\n  Hint Extern 50 => repeat rewrite <- Assoc in *; autorewrite with core aux in *.\n  \n  Lemma mult_both_right : forall x a b,\n      a = b -> a * x = b * x.\n  Proof.\n    intros. rewrite H. reflexivity.\n  Qed.\n\n  Lemma mult_both_left: forall x a b,\n      a = b -> x * a = x * b.\n  Proof.\n    intros. rewrite H. reflexivity.\n  Qed.\n\n  Hint Extern 200 => match goal with\n                     | [H : _ * ?a = _ |- _] => apply (mult_both_right (i a)) in H\n                     end.\n\n  Hint Extern 250 => match goal with\n                     | [H : ?a * _ = _ |- _] => apply (mult_both_left (i a)) in H\n                     end.\n\n  Theorem RightCancellation : forall x a b, a * x = b * x -> a = b.\n  Proof.\n    auto.\n  Qed.\n\n  Hint Extern 150 (_ * ?a = _) => apply (RightCancellation (i a)).\n  \n  Theorem LeftIdentity : forall a,\n      e * a = a.\n  Proof.\n    auto.\n  Qed.\n\n  Hint Rewrite LeftIdentity : aux.\n\n  Theorem LeftInverse : forall a,\n      i a * a = e.\n  Proof.\n    auto.\n  Qed.\n\n  Hint Rewrite LeftInverse.\n\n  Theorem LeftCancellation : forall x a b, x * a = x * b -> a = b.\n  Proof.\n    auto.\n  Qed.\n\n  Hint Extern 100 ( _ = i ?a ) => apply (LeftCancellation a).\n  Hint Extern 100 ( i ?a = _ ) => apply (LeftCancellation a).\n\n  Theorem LeftIdentityUnique : forall a p,\n      p * a = a -> p = e.\n  Proof.\n    auto.\n  Qed.\n  \n  Theorem CharacterizingIdentity : forall a,\n      a * a = a -> a = e.\n  Proof.\n    auto.\n  Qed.\n  \n  Theorem RightInverseUnique : forall a b,\n      a * b = e -> b = i a.\n  Proof.\n    auto.\n  Qed.\n  \n  Theorem LeftInverseUnique : forall a b,\n      a * b = e -> a = i b.\n  Proof.\n    auto.\n  Qed.\n\n  Theorem InverseDistributivity : forall a b,\n      i (a * b) = i b * i a.\n  Proof.\n    auto.\n  Qed.\n  \n  Theorem DoubleInverse : forall a,\n      i (i a) = a.\n  Proof.\n    auto.\n  Qed.\n  \n  Theorem IdentityInverse :\n    i e = e.\n  Proof.\n    auto.\n  Qed.\nEnd Group.\n", "meta": {"author": "eldargab", "repo": "cpdt", "sha": "a7b41081e90e245014b4f4918c0a3837864bec56", "save_path": "github-repos/coq/eldargab-cpdt", "path": "github-repos/coq/eldargab-cpdt/cpdt-a7b41081e90e245014b4f4918c0a3837864bec56/LogicProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7861580871958311}}
{"text": "(* sort.v *)\n\n(**** Sorting algorithm ****)\n\nRequire Import Arith.\nRequire Omega.\nOpen Scope list_scope.\n\n(* Specification *)\n\nInductive is_perm : list nat -> list nat -> Prop :=\n| is_perm_cons : forall (a : nat) (l0 l1 : list nat),\n    is_perm l0 l1 -> is_perm (a :: l0) (a :: l1)\n| is_perm_append : forall (a : nat) (l : list nat),\n    is_perm (a :: l) (l ++ a :: nil)\n| is_perm_refl : forall l : list nat, is_perm l l\n| is_perm_trans : forall l0 l1 l2 : list nat,\n    is_perm l0 l1 -> is_perm l1 l2 -> is_perm l0 l2\n| is_perm_sym : forall l1 l2 : list nat, is_perm l1 l2 -> is_perm l2 l1.\n\nLemma is_perm_ex1 : is_perm (1::2::3::nil) (3::2::1::nil).\nProof.\n  apply (is_perm_trans (1::2::3::nil) ((2::3::nil) ++ 1::nil) (3::2::1::nil));\n    [ apply is_perm_append | simpl ].\n  apply (is_perm_trans (2::3::1::nil) ((3::1::nil) ++ 2::nil) (3::2::1::nil));\n    [ apply is_perm_append | simpl ].\n  apply is_perm_cons.\n  apply (is_perm_trans (1::2::nil) ((2::nil) ++ 1::nil) (2::1::nil));\n    [ apply is_perm_append | simpl ].\n  apply is_perm_refl.\nQed.\n\nLtac is_perm_tac :=\n  repeat\n    (apply is_perm_refl || apply is_perm_cons ||\n     (match goal with\n      | |- is_perm (?a1::?tl1) ?l =>\n        apply (is_perm_trans (a1::tl1) (tl1 ++ a1::nil) l);\n          [ apply is_perm_append | simpl ]\n      end)).\n\nLemma is_perm_ex2 : is_perm (1::2::3::nil) (3::2::1::nil).\nProof.\n  is_perm_tac.\nQed.\n\nInductive is_sorted : list nat -> Prop :=\n| is_sorted_nil : is_sorted nil\n| is_sorted_sing : forall n : nat, is_sorted (n::nil)\n| is_sorted_cons : forall (n m : nat) (l : list nat),\n    n <= m -> is_sorted (m::l) -> is_sorted (n::m::l).\n\nLemma is_sorted_ex1 : is_sorted (1::2::3::4::5::nil).\nProof.\n  apply is_sorted_cons; auto.\n  apply is_sorted_cons; auto.\n  apply is_sorted_cons; auto.\n  apply is_sorted_cons; auto.\n  apply is_sorted_sing.\nQed.\n\n(* Automation *)\n\nLtac is_sorted_tac :=\n  repeat (apply is_sorted_cons; auto);\n  apply is_sorted_sing || apply is_sorted_nil.\n\nLemma is_sorted_ex2 : is_sorted (1::2::3::4::5::nil).\nProof.\n  is_sorted_tac.\nQed.\n\nLemma is_sorted_ex3 : is_sorted (1::nil).\nProof.\n  is_sorted_tac.\nQed.\n\nLemma is_sorted_ex4 : is_sorted nil.\nProof.\n  is_sorted_tac.\nQed.\n\n(* Sorting function: insertion sort *)\n\nFixpoint insert (x : nat) (l : list nat) {struct l} : list nat :=\n  match l with\n  | nil => x::nil\n  | h::t =>\n        match le_dec x h with\n        | left _ => x::h::t\n        | right _ => h::(insert x t)\n        end\n  end.\n\nFixpoint isort (l : list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (isort t)\n  end.\n\nLemma isort_ex1 : isort (5::4::3::2::1::nil) = 1::2::3::4::5::nil.\nProof.\n  simpl; reflexivity.\nQed.\n\n(* Correctness proof *)\n\nLemma head_is_perm : forall (x1 x2 : nat) (l : list nat),\n  is_perm (x1 :: x2 :: l) (x2 :: x1 :: l).\nProof.\n  intros; apply is_perm_trans with (x2::l ++ x1::nil);\n    [ apply is_perm_append | apply is_perm_cons; \n      apply is_perm_sym; apply is_perm_append ].\nQed.\n\nLemma insert_is_perm : forall (x : nat) (l : list nat),\n  is_perm (x::l) (insert x l).\nProof.\n  induction l; intros; simpl.\n  apply is_perm_refl.\n  elim (le_dec x a); intros.\n  apply is_perm_refl.\n  apply is_perm_trans with (a::x::l);\n    [ apply head_is_perm | apply is_perm_cons; auto ].\nQed.\n\nRequire Export Omega.\nLemma insert_is_sorted : forall (x : nat) (l : list nat),\n  is_sorted l -> is_sorted (insert x l).\nProof.\n  intros; elim H; simpl; auto.\n  apply is_sorted_sing.\n  intros; elim (le_dec x n); simpl; intros; auto.\n  apply is_sorted_cons; [ auto | apply is_sorted_sing ].\n  apply is_sorted_cons; [ omega | apply is_sorted_sing ].\n\n  intros n m; elim (le_dec x m); intros; elim (le_dec x n); intros.\n    repeat (apply is_sorted_cons; auto); omega.\n    repeat (apply is_sorted_cons; auto); omega.\n    repeat (apply is_sorted_cons; auto); omega.\n    apply is_sorted_cons.\n    auto.\n\n    auto.\n\n\n (apply is_sorted_cons; auto).\nomega.\napply is_sorted_cons.\nQed.\nintros n m.\nelim (le_dec x m).\nintros.\nelim (le_dec x n).\nintros.\nLemma isort_correct : forall (l l' : list nat),\n  l' = isort l -> is_perm l l' /\\ is_sorted l'.\nProof.\n  induction l; intros.\n  rewrite H; simpl; split; [ is_perm_tac | is_sorted_tac ].\n  rewrite H; simpl; elim (IHl (isort l)); intros; auto; split.\n  apply is_perm_trans with (a::(isort l));\n    [ apply is_perm_cons; auto | apply insert_is_perm ].\n  apply insert_is_sorted; auto.\nQed.\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/sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7861580783925131}}
{"text": "Require Import Nat.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nInductive queue : Type :=\n  | Queue : lst -> lst -> queue.\n\nFixpoint len (l : lst) : nat :=\nmatch l with\n  | Nil => 0\n  | Cons a l1 => 1 + (len l1)\nend.\n\nLemma len_pos: forall l, (len l) >= 0.\nProof.\n  induction l.\n  - simpl. apply le_0_n.\n  - simpl. apply le_0_n.\nQed.\n\nDefinition qlen (q : queue) : nat :=\nmatch q with\n  | Queue l1 l2 => (len l1) + (len l2)\nend. \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 :=\nmatch l with\n  | Nil => Nil\n  | Cons a l1 => app (rev l1) (Cons a Nil)\nend.\n\nFixpoint leb (n m : nat) : bool :=\nmatch (n, m) with\n  | (0, _) => true\n  | (S n', S m') => leb n' m'\n  | _ => false\nend. \n\nDefinition amortizeQueue (l1 l2 : lst) : queue :=\n  if leb (len l2)  (len l1) then Queue l1 l2\n  else Queue (app l1 (rev l2)) Nil.\n\n\nLemma len_app : forall l1 l2, len (app l1 l2) = (len l1) + (len l2).\nProof.\n  intros. induction l1.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nLemma plus_comm: forall m n, m + n = n + m.\nProof.\ninduction m.\n- intros. simpl. rewrite <- plus_n_O. reflexivity.\n- intros. simpl. rewrite IHm. rewrite plus_n_Sm. reflexivity.\nQed.\n\nLemma len_rev : forall l, len (rev l) = len l.\nProof.\ninduction l.\n- reflexivity.\n- simpl. rewrite len_app. simpl. rewrite plus_comm. simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem queue_len : forall l1 l2, qlen (amortizeQueue l1 l2) = (len l1) + (len l2).\nProof.\n  intros. unfold amortizeQueue. destruct (leb (len l2) (len l1)).\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_O. \n    rewrite len_app.\n    apply f_equal2_plus.\n    * reflexivity.\n    * rewrite len_rev. 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_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7860986220716554}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Bool.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma eqb_cases x y : if x =? y then x = y else x <> y.\n  Proof.\n    pose proof (Z.eqb_spec x y) as H.\n    inversion H; trivial.\n  Qed.\n\n  Lemma geb_spec0 : forall x y : Z, Bool.reflect (x >= y) (x >=? y).\n  Proof.\n    intros x y; pose proof (Zge_cases x y) as H; destruct (Z.geb x y); constructor; omega.\n  Qed.\n  Lemma gtb_spec0 : forall x y : Z, Bool.reflect (x > y) (x >? y).\n  Proof.\n    intros x y; pose proof (Zgt_cases x y) as H; destruct (Z.gtb x y); constructor; omega.\n  Qed.\n\n  Ltac ltb_to_lt_with_hyp H lem :=\n    let H' := fresh in\n    rename H into H';\n    pose proof lem as H;\n    rewrite H' in H;\n    clear H'.\n\n  Ltac ltb_to_lt_in_goal b' lem :=\n    refine (proj1 (@reflect_iff_gen _ _ lem b') _);\n    cbv beta iota.\n\n  Ltac ltb_to_lt_hyps_step :=\n    match goal with\n    | [ H : (?x <? ?y) = ?b |- _ ]\n      => ltb_to_lt_with_hyp H (Zlt_cases x y)\n    | [ H : (?x <=? ?y) = ?b |- _ ]\n      => ltb_to_lt_with_hyp H (Zle_cases x y)\n    | [ H : (?x >? ?y) = ?b |- _ ]\n      => ltb_to_lt_with_hyp H (Zgt_cases x y)\n    | [ H : (?x >=? ?y) = ?b |- _ ]\n      => ltb_to_lt_with_hyp H (Zge_cases x y)\n    | [ H : (?x =? ?y) = ?b |- _ ]\n      => ltb_to_lt_with_hyp H (eqb_cases x y)\n    end.\n  Ltac ltb_to_lt_goal_step :=\n    match goal with\n    | [ |- (?x <? ?y) = ?b ]\n      => ltb_to_lt_in_goal b (Z.ltb_spec0 x y)\n    | [ |- (?x <=? ?y) = ?b ]\n      => ltb_to_lt_in_goal b (Z.leb_spec0 x y)\n    | [ |- (?x >? ?y) = ?b ]\n      => ltb_to_lt_in_goal b (Z.gtb_spec0 x y)\n    | [ |- (?x >=? ?y) = ?b ]\n      => ltb_to_lt_in_goal b (Z.geb_spec0 x y)\n    | [ |- (?x =? ?y) = ?b ]\n      => ltb_to_lt_in_goal b (Z.eqb_spec x y)\n    end.\n  Ltac ltb_to_lt_step :=\n    first [ ltb_to_lt_hyps_step\n          | ltb_to_lt_goal_step ].\n  Ltac ltb_to_lt := repeat ltb_to_lt_step.\n\n  Section R_Rb.\n    Local Ltac t := intros ? ? []; split; intro; ltb_to_lt; omega.\n    Local Notation R_Rb Rb R nR := (forall x y b, Rb x y = b <-> if b then R x y else nR x y).\n    Lemma ltb_lt_iff : R_Rb Z.ltb Z.lt Z.ge. Proof. t. Qed.\n    Lemma leb_le_iff : R_Rb Z.leb Z.le Z.gt. Proof. t. Qed.\n    Lemma gtb_gt_iff : R_Rb Z.gtb Z.gt Z.le. Proof. t. Qed.\n    Lemma geb_ge_iff : R_Rb Z.geb Z.ge Z.lt. Proof. t. Qed.\n    Lemma eqb_eq_iff : R_Rb Z.eqb (@Logic.eq Z) (fun x y => x <> y). Proof. t. Qed.\n  End R_Rb.\n  Hint Rewrite ltb_lt_iff leb_le_iff gtb_gt_iff geb_ge_iff eqb_eq_iff : ltb_to_lt.\n  Ltac ltb_to_lt_in_context :=\n    repeat autorewrite with ltb_to_lt in *;\n    cbv beta iota in *.\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/LtbToLt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7860986081412992}}
{"text": "Require Export D.\n\n\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof. \n  intros. induction n. reflexivity.\n  simpl. rewrite -> IHn. 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/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.8558511469672595, "lm_q1q2_score": 0.7860823741353449}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import list_util.\nRequire Import ModEq.\n\n\nSet Implicit Arguments.\n\nFixpoint combi (n k:nat) :=\n  match k with |O => 1\n               |S k'=> match n with |O => 0 |S n'=> combi n' k + combi n' k' end end.\n\nTheorem Combi_0: forall n, combi n 0 = 1. Proof. intros. destruct n; simpl; auto. Qed.\nTheorem Combi_1: forall n, combi n 1 = n. Proof. induction n; simpl; auto. rewrite IHn. rewrite Combi_0. rewrite plus_comm; auto. Qed.\nTheorem Combi_lt: forall n k, n<k -> combi n k = 0. Proof. induction n; intros; auto. destruct k; auto. inversion H. destruct k. inversion H. simpl. rewrite IHn; auto. rewrite IHn; auto. Qed.\nTheorem Combi_S: forall n k, combi (S n) (S k) = combi n (S k) + combi n k. Proof. intros. auto. Qed.\nTheorem Combi_n_n: forall n, combi n n = 1. Proof. induction n; auto. rewrite Combi_S; auto. rewrite IHn. rewrite Combi_lt; auto. Qed.\nTheorem Combi_fact: forall n k, k<=n -> combi n k * fact k * fact (n-k) = fact n. Proof. induction n; intros. inversion H; auto. destruct k. simpl. rewrite plus_n_O; auto. rewrite Combi_S. apply le_S_n in H. apply le_lt_or_eq in H. destruct H as [H|H]. replace (S n-S k) with (n-k); auto. rewrite <- mult_assoc. rewrite mult_plus_distr_r. replace (fact (n-k)) with (fact (n-S k)*(n-k)) at 1. repeat rewrite mult_assoc. rewrite IHn; auto. \n  replace (fact (S k)) with (S k*fact k); auto. replace (combi n k*(S k*fact k)*fact (n-k)) with (combi n k*fact k*fact (n-k)*S k); auto. rewrite IHn; auto. rewrite <- mult_plus_distr_l. rewrite <- plus_n_Sm. rewrite plus_comm. rewrite <- le_plus_minus; auto. rewrite mult_comm; auto. repeat rewrite <- mult_assoc. f_equal. symmetry. rewrite mult_comm. rewrite mult_assoc; auto. replace (n-k) with (S(n-S k)). rewrite mult_comm; auto. rewrite minus_Sn_m; auto. subst k. rewrite Combi_lt; auto. rewrite Combi_n_n. rewrite <- minus_n_n. rewrite mult_1_r. auto. Qed.\nTheorem Combi_nz: forall n k, k<=n -> combi n k<>0. Proof. induction n; intros. inversion H. simpl; auto. destruct k. simpl; auto. rewrite Combi_S. intros C. apply plus_is_O in C. destruct C. contradict H1. apply IHn; auto. Qed.\nLemma fact_Prime: forall p n, Prime p -> n<p -> ~Divide p (fact n). Proof. induction n; intros. intros C. apply Divide_le in C; auto. contradict C; auto. rewrite fact_S. intros C. apply Euclid_Prime in C; auto. destruct C. apply Divide_le in H1; auto. contradict H1; auto. contradict H1; auto. Qed.\nTheorem Combi_Prime: forall p k, Prime p -> 0<k<p -> Divide p (combi p k). Proof. intros. destruct H0. assert (combi p k*fact k*fact (p-k)=fact p). apply Combi_fact; auto. assert (Divide p (combi p k*fact k*fact (p-k))). rewrite H2; auto. apply Euclid_Prime in H3; auto. destruct H3. apply Euclid_Prime in H3; auto. destruct H3; auto. contradict H3. apply fact_Prime; auto. contradict H3. apply fact_Prime; auto. destruct k. contradict H0; auto. destruct p; auto. simpl. apply le_lt_trans with p; auto. apply le_minus. Qed.\n\nTheorem poly_combi: forall x y n, pow (x+y) n = fold_right plus 0 (map (fun k=>combi n k*pow x (n - k)*pow y k) (seq 0 (S n))). Proof. induction n. simpl; auto. rewrite powS. rewrite seqS. rewrite map_app. replace (map (fun k=>combi (S n) k*pow x (S n-k)*pow y k) (0+S n::nil)) with (pow y (S n)::nil). rewrite fold_plus_app. rewrite IHn. rewrite mult_plus_distr_r. rewrite seqS at 2. rewrite map_app. rewrite fold_plus_app. rewrite mult_plus_distr_l. rewrite plus_assoc. f_equal. replace (seq 0 (S n)) with (0::seq 1 n). simpl. rewrite mult_plus_distr_l. rewrite <- plus_assoc. f_equal. rewrite Combi_0. repeat rewrite mult_1_r. rewrite <- plus_n_O. f_equal. rewrite <- minus_n_O; auto. rewrite mult_fold_plus. rewrite mult_fold_plus. repeat rewrite mult_0_r. rewrite map_map. rewrite map_map. replace (seq 0 n) with (map (fun x=>x-1) (seq 1 n)). rewrite map_map. rewrite fold_plus_map.\n  f_equal. apply map_ext_in. clear IHn. intros a Ha. apply in_seq in Ha. destruct Ha. simpl in H0. apply le_S_n in H0. destruct a. inversion H. replace (S a -1) with a. repeat rewrite mult_plus_distr_r. f_equal. rewrite mult_assoc. f_equal. rewrite mult_comm. rewrite <- mult_assoc. f_equal. rewrite mult_comm. rewrite <- powS. f_equal. rewrite minus_Sn_m; auto. rewrite mult_comm. repeat rewrite <- mult_assoc. f_equal. f_equal. rewrite powS; auto. simpl; rewrite <- minus_n_O; auto. clear -n. induction n. simpl; auto. repeat rewrite seqS. rewrite map_app. f_equal; auto. simpl. rewrite <- minus_n_O; auto. simpl; auto.\n  simpl. repeat rewrite <- plus_n_O. f_equal. rewrite Combi_n_n. rewrite <- minus_n_n. rewrite mult_1_l; auto. simpl. f_equal. rewrite Combi_n_n. rewrite Combi_lt; auto. rewrite <- minus_n_n. rewrite mult_1_l; auto. Qed.\n\nTheorem poly2: forall x y, pow (x+y) 2 = x*x + 2*x*y + y*y. Proof. intros. rewrite poly_combi. simpl. repeat rewrite <- plus_n_O. repeat rewrite mult_1_r. rewrite <- plus_assoc; auto. Qed.\n\nHint Resolve Combi_0 Combi_1 Combi_lt Combi_S Combi_n_n Combi_fact Combi_nz fact_Prime Combi_Prime poly_combi poly2.", "meta": {"author": "ysfmssk", "repo": "coq", "sha": "07e0aa439df36339e3b6a27c3699a34f6eee4f8a", "save_path": "github-repos/coq/ysfmssk-coq", "path": "github-repos/coq/ysfmssk-coq/coq-07e0aa439df36339e3b6a27c3699a34f6eee4f8a/combi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7860143459943226}}
{"text": "(* ***** examples: intuitionistic logic ***** *)\n\n(* The logical connectives for true, false, conjunction,\ndisjunction are defined by means of inductive predicates.\nRoughly the constructors correspond to the introduction\nrules, and the induction principle corresponds to the\nelimination rules. *)\n\nPrint True.\n(* True_ind states that P holds if we can prove True from it *)\nCheck True_ind.\n\nPrint False.\n(* False_ind gives the elimination rule for False:\nany P follows from False *)\nCheck False_ind.\n\nParameters A B C : Prop.\nLemma about_false: False -> A.\n\nProof.\nintro x.\nelim x.\n(* alternative:\nelimtype False.\nassumption.      *)\n(* alternative:\napply False_ind.\nassumption.      *)\nQed.\n\nPrint and.\nCheck and_ind.\n\nLemma about_intro_and : A -> B -> A /\\ B.\n\nProof.\nintro x.\nintro y.\nsplit.\nassumption.\nassumption.\n(* alternative:\napply conj.\nassumption.\nassumption.      *)\nQed.\n\nLemma about_elim_and : A /\\ B -> C -> A.\n(* elim or apply and_ind *)\n\nProof.\nintros x y.\napply and_ind with A B.\nintros.\nassumption.\nassumption.\nQed.\n\n\n(* ***** examples: even ***** *)\n\n(* an inductive definition of even *)\nInductive even : nat -> Prop :=\n| evenO : even O\n| evenSS : forall n:nat , even n -> even (S (S n)).\n\nCheck evenO.\nCheck (even O).\nCheck (even 1).\nCheck (evenSS O evenO).\nCheck (even 2).\nCheck (evenSS 2 (evenSS O evenO)).\nCheck (even 4).\n\n(* example *)\nTheorem evenzero : (even O).\n\nProof.\napply evenO.\nQed.\n\n(* example *)\nTheorem evenss : forall n:nat , (even n) -> (even (S (S n))).\n\nProof.\nintro n.\nintro H.\napply evenSS.\nexact H.\nQed.\n\n(*\nalternative proof:\nintro n.\nintro H.\napply evenSS.\nexact H.\nQed.\n*)\n\n\n(* ***** examples: le ***** *)\n\nInductive le (n:nat) : nat -> Prop :=\n| le_n : le n n\n| le_S : forall m:nat , le n m -> le n (S m).\n\n\nCheck (le 0).\nCheck (le 0 0). (* a type, which can be regarded as a\n  proposition. We don't know whether the proposition\n  is true or false yet. *)\nCheck (le_n 0). (* a value of the above type, which can\n  be regarded as a proof that the above proposition\n  is true. *)\nCheck (le 5 10).\nCheck (le_n 100).\nCheck (le_S 0 0 (le_n 0)).\nDefinition zero_smaller_than_one := (le_S 0 0 (le_n 0)).\nCheck zero_smaller_than_one.\nCheck (le_n 7).\n\n(* We claim that zero is smaller than two.\n  This is equivalent to giving a declaration of an\n  identifier with the appropriate type.\n\n  The proof of the claim is to give a value that has\n  exactly this type.\n*)\nLemma zero_smaller_than_two : le 0 (S (S 0)).\nProof.\napply le_S.\napply le_S.\napply le_n.\nQed.\n\n(* what did we just do?\nto prove: the type le 0 (S (S 0)) is inhabited\n\n  last step in the proof: this is an axiom\nle_n 0 : le 0 0\n  because we know now that le_n is of type le 0 0, we can give this value as\n  the second argument of the constructor of le_S.\nle_S 0 (le_n 0) : le 0 (S 0)\n  We have just proved that the *value* le_S 0 (le_n 0) is of *type* le 0 (S 0).\n  As the last step, we apply the constructor le_S again.\nle_S (S 0) (le_S 0 (le_n 0) : le 0 (S (S 0))\n*)\n\n\n(* Question: can we give a data-type \"ancestor\"? *)\nInductive ancestor (n:nat) : nat -> Prop :=\n    (* the successor of a number is an ancestor of that number *)\n  | anc_S : ancestor n (S n)\n    (* the ancestor of the sucessor of n is also an ancestor of n*)\n  | anc_anc : forall m:nat , ancestor n m -> ancestor n (S m)\n  .\n\nCheck ancestor 100 0.\nCheck anc_S 0.\n\nCheck ancestor 1 0.\nCheck anc_anc 0 0.\n\n(*\nLemma no_number_is_its_own_ancestor : forall m:nat , not (ancestor m m).\nProof.\nunfold not.\nintro m.\nelim m.\nintro.\n\nQed.\n*)\n\n(* examples: sorted *)\n\n(* an inductive type for finite lists of natural numbers *)\nInductive natlist : Set :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\n(* an inductive predicate sorted *)\nInductive sorted : natlist -> Prop :=\n| sorted0 : sorted nil (* the empty list is sorted *)\n| sorted1 : forall n:nat , sorted (cons n nil) (* the singleton list is sorted *)\n(* if n < h\n  and cons h t is sorted\n then cons n (cons h t) is sorted. *)\n| sorted2 : forall n h:nat , forall t:natlist ,\n            le n h -> sorted (cons h t) -> sorted (cons n (cons h t)).\n\nCheck (sorted1 1).\nDefinition list_one_sorted := (sorted1 1).\nCheck list_one_sorted.\nCheck (sorted2 O 1 nil zero_smaller_than_one list_one_sorted).\nDefinition list_zero_one_sorted := (sorted2 O 1 nil zero_smaller_than_one list_one_sorted).\nCheck list_zero_one_sorted.\n\n\n\n\n(* ***** examples: inversion ***** *)\nParameter P : nat -> Prop.\nParameter Q : nat -> nat -> Prop.\nParameter R : natlist -> Prop.\n\nLemma one : forall n : nat, even n -> P n.\n\nProof.\nintros n H.\napply even_ind.\ninversion H.\nAbort.\n\nLemma two : forall n m : nat, le n m -> Q n m.\n\nintros n m H.\ninversion H.\nAbort.\n\nLemma three : forall l : natlist, sorted l -> R l.\n\nProof.\nintros l H.\ninversion H.\nAbort.\n\n\n\n(* *************** now the exercises start ********** *)\n(* *************** we use definition given above **** *)\n\n(* exercise 1 *)\nTheorem even2 : (even 2 ).\nProof.\napply evenSS.\napply evenO.\nQed.\n\n(* a few checks *)\nCheck evenO.\nCheck evenzero.\nPrint evenzero.\nCheck evenSS.\nCheck even2.\nPrint even2.\n\n(* exercise 2\n   use inversion *)\nTheorem noteven1 : ~(even 1).\nProof.\nintro.\ninversion H.\nQed.\n\n(* exercise 3\n   you may want to use an earlier proved result *)\nTheorem even4 : even 4.\nProof.\napply evenSS.\napply even2.\nQed.\n\n(* exercise 4 *)\nTheorem noteven3 : ~(even 3).\nProof.\nintro.\ninversion H.\napply noteven1.\nassumption.\nQed.\n\n(* an inductive definition of even and odd *)\nInductive ev : nat -> Prop :=\n| evO : ev O\n| evS : forall n:nat , odd n -> ev (S n)\nwith odd : nat -> Prop :=\n| oddS : forall n:nat , ev n -> odd (S n).\n\n(* example *)\nTheorem evzero : ev O.\nProof.\nexact evO.\nQed.\n\n(* example *)\nTheorem odd1 : odd 1.\nProof.\nexact (oddS O evzero).\nQed.\n\n(* exercise 5 *)\nTheorem ev2 : ev 2.\nProof.\napply evS.\napply odd1.\nQed.\n\n(* exercise 6 *)\nTheorem notodd2 : ~ odd 2.\nProof.\nintro.\ninversion H.\ninversion H1.\ninversion H3.\nQed.\n\n(* exercise 7\n   use induction *)\nTheorem evorodd : forall n:nat, ev n \\/ odd n.\nProof.\nintro.\ninduction n.\nleft.\nexact evO.\ninversion IHn.\nright.\napply oddS.\nassumption.\nleft.\napply evS.\nassumption.\nQed.\n\n(* exercise 8 *)\nTheorem zero_and_zero : le O O.\nProof.\nexact (le_n 0).\nQed.\n\n(* exercise 9 *)\nTheorem zero_and_one  : le 0 1.\nProof.\nexact (le_S 0 0 zero_and_zero).\nQed.\n\n(* some checks *)\nPrint zero_and_one.\nCheck zero_and_one.\n\n(* exercise 10 *)\nTheorem one_and_zero : ~ (le 1 0).\nProof.\nintro.\ninversion H.\nQed.\n\n\n(* exercise 11 *)\nTheorem sortednil : sorted nil.\nProof.\nexact sorted0.\nQed.\n\n\n(* exercise 12 *)\nTheorem sortedone : sorted (cons 0 nil).\nProof.\nPrint sorted.\nexact (sorted1 0).\nQed.\n\n(* exercise 13 *)\nTheorem sorted_one_two_three :\n  sorted (cons 1 (cons 2 (cons 3 nil))).\nProof.\nPrint sorted.\napply sorted2.\nLemma le_succ : forall n , le n (S n).\nProof.\nintro.\napply le_S.\napply le_n.\nQed.\napply le_succ.\napply sorted2.\napply le_succ.\napply sorted1.\nQed.\n\n(* exercise 14 *)\nTheorem sorted_tail :\n  forall (n : nat) (l : natlist),\n  sorted (cons n l) ->\n  sorted l.\nProof.\nintros.\ninversion H.\nexact sorted0.\nassumption.\nQed.\n\n(* given for exercise 15\n   without_last n k l holds if\n   n is the last element of k\n   and\n   l is k without the last element *)\nInductive without_last (n:nat) : natlist -> natlist -> Prop :=\n| without_last_one :\n  without_last n (cons n nil) nil\n| without_last_more :\n    forall m:nat, forall l k : natlist,\n    without_last n k l -> without_last n (cons m k) (cons m l).\n\n(* exercise 15 *)\n(* define a predicate palindrome : natlist -> Prop\n   that holds exactly if the input list is equal to its reverse.\n   use three clauses: for the empty list, for a list of one\n   element, for a list of two or more elements *)\n\nInductive palindrome : natlist -> Prop :=\n  | pali_nil : palindrome nil\n  | pali_one : forall n:nat, palindrome (cons n nil)\n  | pali_more : forall n:nat, forall l k:natlist,\n        without_last n k l -> palindrome l -> palindrome (cons n k)\n  .\n\n  (* l ++  [n]   and  l is a palindrome, then    n : k      is a palindrome\n     |-- k --|                                n : l ++ [n]*)\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/pw05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7859845981188145}}
{"text": "Require SQIR.UnitaryOps.\nRequire SQIR.DensitySem.\nRequire SQIR.NDSem.\n\n(** Unitary Teleportation Circuit and Proof **)\nModule UTeleport.\n\nImport UnitaryOps.\n\nOpen Scope ucom.\n\n(* a = alice; b = bob; q = qubit to be teleported *)\nDefinition bell {n} (a b : nat) : base_ucom n := H a ; CNOT a b.\nDefinition alice {n} (q a : nat) : base_ucom n := CNOT q a ; H q.\nDefinition bob {n} (q a b: nat) : base_ucom n := CNOT a b; CZ q b.\nDefinition teleport {n} (q a b : nat) : base_ucom n := alice q a; bob q a b.\n\nDefinition epr00 : Vector 4 :=\n  fun x y => match x, y with\n             | 0, 0 => 1/√2\n             | 3, 0 => 1/√2\n             | _, _ => 0\n             end.\n\nLemma epr_correct : \n  forall (ψ : Vector 2), WF_Matrix ψ -> (@uc_eval 3 (bell 1 2)) × (ψ ⊗ ∣0⟩ ⊗ ∣0⟩) = ψ ⊗ epr00. \nProof.\n  intros.\n  unfold bell. \n  simpl; autorewrite with eval_db; simpl.\n  solve_matrix.\nQed.\n\nLemma teleport_correct : forall (ψ : Vector 2), \n    WF_Matrix ψ -> @uc_eval 3 (teleport 0 1 2) × (ψ ⊗ epr00) = (∣ + ⟩ ⊗ ∣ + ⟩ ⊗ ψ).\nProof.\n  intros.\n  unfold teleport. simpl.\n  autorewrite with eval_db. simpl.\n  solve_matrix.\n  all: repeat (try rewrite Cmult_plus_distr_l; \n               try rewrite Cmult_plus_distr_r;\n               try rewrite <- Copp_mult_distr_r;\n               try rewrite <- Copp_mult_distr_l).\n  all: group_radicals.\n  all: lca.\nQed.  \n\nEnd UTeleport.\n\n(** Non-unitary teleport, proof with density matrices **)\nModule DensityTeleport.\n\nImport DensitySem.\n\nLocal Open Scope com.\n\nDefinition q : nat := 0. (* qubit for transmission *)\nDefinition a : nat := 1. (* alice's qubit *)\nDefinition b : nat := 2. (* bob's qubit *)\n\nDefinition bell : base_com 3 := H a ; CNOT a b.\nDefinition alice : base_com 3 := CNOT q a ; H q; measure a; measure q.\nDefinition bob : base_com 3 := CNOT a b; CZ q b; reset a; reset q.\nDefinition teleport : base_com 3 := bell; alice; bob.\n\n(* Short proof, but very very slow.\n\nLemma teleport_correct : forall (ρ : Density 2),\n  WF_Matrix ρ -> \n  c_eval teleport (ρ ⊗ ∣0⟩⟨0∣ ⊗ ∣0⟩⟨0∣) = (∣0⟩⟨0∣ ⊗ ∣0⟩⟨0∣ ⊗ ρ).\nProof.\n  intros.\n  simpl.\n  repeat rewrite compose_super_eq.\n  unfold compose_super.\n  autorewrite with eval_db; simpl.\n  Msimpl_light.\n  unfold Splus, super.\n  Msimpl.\n  solve_matrix. (* very slow! *)\n  all: group_radicals; lca.\nQed. *)\n\nLemma combine_super : forall {n} (A B : Square n) ρ, \n  super A (super B ρ) = super (A × B) ρ.\nProof.\n  intros.\n  unfold super.\n  rewrite Mmult_adjoint.\n  repeat rewrite Mmult_assoc.\n  reflexivity.\nQed.\n\nLemma super_add : forall {n} (A B C : Square n) ρ, \n  super A (super B ρ .+ super C ρ) = super (A × B) ρ .+ super (A × C) ρ.\nProof.\n  intros.\n  unfold super.\n  repeat rewrite Mmult_adjoint.\n  distribute_plus.\n  repeat rewrite Mmult_assoc.\n  reflexivity.\nQed.\n\nLemma teleport_correct : forall (ρ : Density 2),\n  WF_Matrix ρ -> \n  c_eval teleport (ρ ⊗ ∣0⟩⟨0∣ ⊗ ∣0⟩⟨0∣) = (∣0⟩⟨0∣ ⊗ ∣0⟩⟨0∣ ⊗ ρ).\nProof.\n  intros.\n  simpl. \n  repeat rewrite compose_super_eq. \n  repeat rewrite compose_super_assoc.\n  rewrite compose_super_eq. \n  unfold compose_super.\n  unfold proj.\n  autorewrite with eval_db; simpl.\n  Msimpl_light.\n  replace (I 4) with (I 2 ⊗ I 2).\n  2: { rewrite id_kron. reflexivity. }\n  repeat (distribute_plus;\n          repeat rewrite <- kron_assoc by auto with wf_db;\n          restore_dims).\n  repeat rewrite kron_mixed_product.\n  repeat rewrite <- (Mmult_assoc _ _ hadamard).\n  Qsimpl.\n  replace (hadamard × σx × hadamard) with σz by solve_matrix.  \n  unfold Splus. \n  repeat rewrite combine_super.\n  restore_dims.\n  distribute_plus.\n  repeat rewrite kron_mixed_product.\n  repeat rewrite <- (Mmult_assoc _ _ hadamard).\n  Qsimpl.\n  repeat (try rewrite super_add; try rewrite combine_super).\n  repeat (distribute_plus;\n          repeat rewrite <- kron_assoc by auto with wf_db;\n          restore_dims).\n  repeat rewrite kron_mixed_product.\n  repeat rewrite <- (Mmult_assoc _ _ hadamard).\n  Qsimpl. \n  unfold super; Msimpl_light.\n  (* Tired of manually simplifying; solve_matrix should be reasonable now. *)\n  solve_matrix.\nQed.\n\nEnd DensityTeleport.\n\n(** Non-unitary teleport, proof with non-deterministic semantics **)\nModule NDTeleport.\n\nImport UnitaryOps.\nImport NDSem.\nImport Proportional.\n\nLocal Open Scope com.\n\nDefinition q : nat := 0. (* qubit for transmission *)\nDefinition a : nat := 1. (* alice's qubit *)\nDefinition b : nat := 2. (* bob's qubit *)\n\nDefinition bell : base_com 3 := H a ; CNOT a b.\nDefinition alice : base_com 3 := CNOT q a ; H q; measure a; measure q.\nDefinition bob : base_com 3 := CNOT a b; CZ q b; reset a; reset q.\nDefinition teleport : base_com 3 := bell; alice; bob.\n\nLocal Open Scope R_scope.\nLocal Open Scope C_scope.\n\nDefinition epr00 : Vector 4 := / √ 2 .* ∣ 0, 0 ⟩ .+ / √ 2 .* ∣ 1, 1 ⟩.\n\n(* Alternative form of proportional for unscaled vectors. *)\nDefinition proportional {m n : nat} (A B : Matrix m n) := \n  exists s, A = s .* B. \n\nLemma teleport_correct : forall (ψ : Vector (2^1)) (ψ' : Vector (2^3)),\n  WF_Matrix ψ ->\n  teleport / (ψ  ⊗ ∣ 0 , 0 ⟩) ⇩ ψ' -> proportional ψ' (∣ 0 , 0 ⟩ ⊗ ψ).   \nProof.\n  intros ψ ψ' WF S.\n  dependent destruction S.\n  dependent destruction S1.\n  rename S1_1 into Bell.\n  rename S1_2 into Alice.\n  rename S2 into Bob.\n  (* compute the result of the bell program *)\n  assert (E00 : ψ' = ψ ⊗ epr00).\n  { clear Alice Bob.\n    repeat match goal with\n    | H : _ / _ ⇩ _ |- _ => dependent destruction H\n    end.\n    autorewrite with eval_db; simpl.\n    Msimpl.\n    setoid_rewrite cnot_decomposition.\n    restore_dims.\n    rewrite kron_assoc by auto with wf_db. \n    restore_dims.\n    rewrite kron_mixed_product.\n    Msimpl.\n    autorewrite with ket_db.\n    unfold epr00. \n    autorewrite with ket_db.\n    reflexivity.\n  }\n  subst. clear Bell.\n  (* simplify the unitary part of the Alice program *)\n  repeat match goal with\n  | H : (_ ; _) / _ ⇩ _ |- _ => dependent destruction H\n  end.\n  dependent destruction Alice1_1_1.\n  dependent destruction Alice1_1_2.\n  dependent destruction Bob1_1_1.\n  dependent destruction Bob1_1_2.\n  evar (ψA : Vector (2^3)).\n  assert (EA : uc_eval (H q) × (uc_eval (CNOT q a) × (ψ ⊗ epr00)) = ψA).\n  { clear Alice1_2 Alice2 Bob1_2 Bob2. \n    autorewrite with eval_db; simpl. \n    Msimpl.\n    unfold epr00.\n    replace 4%nat with (2 * 2)%nat by reflexivity.\n    rewrite <- id_kron.\n    repeat rewrite <- kron_assoc by auto with wf_db.\n    restore_dims.\n    rewrite cnot_decomposition.\n    autorewrite with Q_db ket_db. \n    repeat rewrite <- kron_assoc by auto with wf_db.\n    restore_dims.\n    repeat rewrite kron_mixed_product.\n    Msimpl.\n    rewrite (ket_decomposition ψ) by auto. \n    autorewrite with Q_db ket_db. \n    Qsimpl.\n    autorewrite with Q_db ket_db. \n    rewrite <- Copp_mult_distr_r.\n    group_radicals.\n    subst ψA. \n    reflexivity.\n  }    \n  subst ψA. rewrite EA in Alice1_2. clear EA.\n  (* now destruct measurements to get four cases: a ∈ {0,1}, q ∈ {0,1} *)\n  dependent destruction Alice1_2.\n  - (* measured a = 1 *)\n    evar (ψ'pad : Vector (2^3)).\n    assert(Epad : ψ' = ψ'pad).\n    { subst ψ'.\n      unfold proj, pad_u, pad; simpl.\n      repeat rewrite Mmult_plus_distr_l.\n      repeat rewrite Mscale_mult_dist_r. \n      restore_dims.\n      repeat rewrite kron_mixed_product.\n      replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix.\n      replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix.\n      Msimpl_light.\n      subst ψ'pad.\n      reflexivity.\n    }\n    subst ψ'pad. rewrite Epad in Alice1_2. clear H Epad ψ'.\n    dependent destruction Alice1_2.\n    dependent destruction Alice2.\n    + (* measured q = 1 *)\n      evar (ψ'pad : Vector (2^3)).\n      assert(Epad : ψ' = ψ'pad).\n      { subst ψ'.\n        unfold proj, pad_u, pad; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        Msimpl_light.\n        restore_dims.\n        repeat rewrite Mmult_plus_distr_l.\n        repeat rewrite Mscale_mult_dist_r. \n        restore_dims.\n        repeat rewrite kron_mixed_product.\n        replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix.\n        replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix.\n        Msimpl_light.\n        subst ψ'pad.\n        reflexivity.\n      }\n      subst ψ'pad. rewrite Epad in Alice2. clear H Epad ψ'.\n      evar (ψBob : Vector (2^3)).\n      assert(EBob : uc_eval (CZ 0 b) × (uc_eval (CNOT 1 b) × ψ'') = ψBob).\n      { simpl; autorewrite with eval_db; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        Msimpl_light.\n        restore_dims.\n        distribute_plus.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        restore_dims.\n        repeat rewrite kron_mixed_product; Msimpl_light.\n        distribute_plus. \n        repeat rewrite <- Mmult_assoc.\n        repeat rewrite kron_mixed_product; Qsimpl.\n        replace (hadamard × σx × hadamard) with σz by solve_matrix.\n        subst ψBob.\n        reflexivity.\n      }\n      subst ψBob. rewrite EBob in Bob1_2. clear EBob.\n      repeat match goal with\n      | H : _ / _ ⇩ _ |- _ => dependent destruction H\n      end.\n      all: unfold proj; simpl; autorewrite with eval_db; simpl.\n      all: replace 4%nat with (2 * 2)%nat by reflexivity;\n           rewrite <- id_kron;\n           repeat rewrite <- kron_assoc by auto with wf_db;\n           Msimpl_light;\n           restore_dims.\n      all: repeat rewrite <- Mmult_assoc;\n           repeat rewrite kron_mixed_product;\n           Qsimpl.\n      all: distribute_plus; distribute_scale.\n      all: repeat rewrite kron_mixed_product.\n      all: Qsimpl.\n      all: replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix;\n           replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      (* last 3 cases are Zero because values measured by Bob are pre-determined *)\n      2,3,4: exists 0; solve_matrix. (* or show that the norm ≠ 0 condition is violated *)\n      replace (∣0⟩⟨1∣ × ∣ 1 ⟩) with (∣ 0 ⟩) by solve_matrix.\n      rewrite (ket_decomposition ψ WF).\n      exists (/ 2).\n      solve_matrix.\n    + (* measured q = 0 *)\n      evar (ψ'pad : Vector (2^3)).\n      assert(Epad : ψ' = ψ'pad).\n      { subst ψ'.\n        unfold proj, pad_u, pad; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        Msimpl_light.\n        restore_dims.\n        repeat rewrite Mmult_plus_distr_l.\n        repeat rewrite Mscale_mult_dist_r. \n        restore_dims.\n        repeat rewrite kron_mixed_product.\n        replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix.\n        replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix.\n        Msimpl_light.\n        subst ψ'pad.\n        reflexivity.\n      }\n      subst ψ'pad. rewrite Epad in Alice2. clear H Epad ψ'.\n      evar (ψBob : Vector (2^3)).\n      assert(EBob : uc_eval (CZ 0 b) × (uc_eval (CNOT 1 b) × ψ'') = ψBob).\n      { simpl; autorewrite with eval_db; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        Msimpl_light.\n        restore_dims.\n        distribute_plus.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        restore_dims.\n        repeat rewrite kron_mixed_product; Msimpl_light.\n        distribute_plus. \n        repeat rewrite <- Mmult_assoc.\n        repeat rewrite kron_mixed_product; Qsimpl.\n        replace (hadamard × σx × hadamard) with σz by solve_matrix.\n        subst ψBob.\n        reflexivity.\n      }\n      subst ψBob. rewrite EBob in Bob1_2. clear EBob.\n      repeat match goal with\n      | H : _ / _ ⇩ _ |- _ => dependent destruction H\n      end.\n      all: unfold proj; simpl; autorewrite with eval_db; simpl.\n      all: replace 4%nat with (2 * 2)%nat by reflexivity;\n           rewrite <- id_kron;\n           repeat rewrite <- kron_assoc by auto with wf_db;\n           Msimpl_light;\n           restore_dims.\n      all: repeat rewrite <- Mmult_assoc;\n           repeat rewrite kron_mixed_product;\n           Qsimpl.\n      all: distribute_plus; distribute_scale.\n      all: repeat rewrite kron_mixed_product.\n      all: Qsimpl.\n      all: replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix;\n           replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣0⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      1,2,4: exists 0; solve_matrix.      \n      rewrite (ket_decomposition ψ WF).\n      exists (/ 2).\n      solve_matrix.\n  - (* measured a = 0 *)\n    evar (ψ'pad : Vector (2^3)).\n    assert(Epad : ψ' = ψ'pad).\n    { subst ψ'.\n      unfold proj, pad_u, pad; simpl.\n      repeat rewrite Mmult_plus_distr_l.\n      repeat rewrite Mscale_mult_dist_r. \n      restore_dims.\n      repeat rewrite kron_mixed_product.\n      replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix.\n      replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix.\n      Msimpl_light.\n      subst ψ'pad.\n      reflexivity.\n    }\n    subst ψ'pad. rewrite Epad in Alice1_2. clear H Epad ψ'.\n    dependent destruction Alice1_2.\n    dependent destruction Alice2.\n    + (* measured q = 1 *)\n      evar (ψ'pad : Vector (2^3)).\n      assert(Epad : ψ' = ψ'pad).\n      { subst ψ'.\n        unfold proj, pad_u, pad; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        Msimpl_light.\n        restore_dims.\n        repeat rewrite Mmult_plus_distr_l.\n        repeat rewrite Mscale_mult_dist_r. \n        restore_dims.\n        repeat rewrite kron_mixed_product.\n        replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix.\n        replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix.\n        Msimpl_light.\n        subst ψ'pad.\n        reflexivity.\n      }\n      subst ψ'pad. rewrite Epad in Alice2. clear H Epad ψ'.\n      evar (ψBob : Vector (2^3)).\n      assert(EBob : uc_eval (CZ 0 b) × (uc_eval (CNOT 1 b) × ψ'') = ψBob).\n      { simpl; autorewrite with eval_db; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        Msimpl_light.\n        restore_dims.\n        distribute_plus.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        restore_dims.\n        repeat rewrite kron_mixed_product; Msimpl_light.\n        distribute_plus. \n        repeat rewrite <- Mmult_assoc.\n        repeat rewrite kron_mixed_product; Qsimpl.\n        replace (hadamard × σx × hadamard) with σz by solve_matrix.\n        subst ψBob.\n        reflexivity.\n      }\n      subst ψBob. rewrite EBob in Bob1_2. clear EBob.\n      repeat match goal with\n      | H : _ / _ ⇩ _ |- _ => dependent destruction H\n      end.\n      all: unfold proj; simpl; autorewrite with eval_db; simpl.\n      all: replace 4%nat with (2 * 2)%nat by reflexivity;\n           rewrite <- id_kron;\n           repeat rewrite <- kron_assoc by auto with wf_db;\n           Msimpl_light;\n           restore_dims.\n      all: repeat rewrite <- Mmult_assoc;\n           repeat rewrite kron_mixed_product;\n           Qsimpl.\n      all: distribute_plus; distribute_scale.\n      all: repeat rewrite kron_mixed_product.\n      all: Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣1⟩⟨1∣ × ∣ 1 ⟩) with (∣ 1 ⟩) by solve_matrix;\n           replace (∣0⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      1,3,4: exists 0; solve_matrix.\n      replace (∣0⟩⟨1∣ × ∣ 1 ⟩) with (∣ 0 ⟩) by solve_matrix.\n      replace (σz × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix.\n      replace (σz × ∣ 1 ⟩) with (- 1 .* ∣ 1 ⟩) by solve_matrix.\n      rewrite (ket_decomposition ψ WF).\n      exists (/ 2).\n      solve_matrix.   \n    + (* measured q = 0 *)\n      evar (ψ'pad : Vector (2^3)).\n      assert(Epad : ψ' = ψ'pad).\n      { subst ψ'.\n        unfold proj, pad_u, pad; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        Msimpl_light.\n        restore_dims.\n        repeat rewrite Mmult_plus_distr_l.\n        repeat rewrite Mscale_mult_dist_r. \n        restore_dims.\n        repeat rewrite kron_mixed_product.\n        replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix.\n        replace (∣0⟩⟨0∣ × ∣ 1 ⟩) with (@Zero 2 1) by solve_matrix.\n        Msimpl_light.\n        subst ψ'pad.\n        reflexivity.\n      }\n      subst ψ'pad. rewrite Epad in Alice2. clear H Epad ψ'.\n      evar (ψBob : Vector (2^3)).\n      assert(EBob : uc_eval (CZ 0 b) × (uc_eval (CNOT 1 b) × ψ'') = ψBob).\n      { simpl; autorewrite with eval_db; simpl.\n        replace 4%nat with (2 * 2)%nat by reflexivity.\n        rewrite <- id_kron.\n        Msimpl_light.\n        restore_dims.\n        distribute_plus.\n        repeat rewrite <- kron_assoc by auto with wf_db.\n        restore_dims.\n        repeat rewrite kron_mixed_product; Msimpl_light.\n        distribute_plus. \n        repeat rewrite <- Mmult_assoc.\n        repeat rewrite kron_mixed_product; Qsimpl.\n        replace (hadamard × σx × hadamard) with σz by solve_matrix.\n        subst ψBob.\n        reflexivity.\n      }\n      subst ψBob. rewrite EBob in Bob1_2. clear EBob.\n      repeat match goal with\n      | H : _ / _ ⇩ _ |- _ => dependent destruction H\n      end.\n      all: unfold proj; simpl; autorewrite with eval_db; simpl.\n      all: replace 4%nat with (2 * 2)%nat by reflexivity;\n           rewrite <- id_kron;\n           repeat rewrite <- kron_assoc by auto with wf_db;\n           Msimpl_light;\n           restore_dims.\n      all: repeat rewrite <- Mmult_assoc;\n           repeat rewrite kron_mixed_product;\n           Qsimpl.\n      all: distribute_plus; distribute_scale.\n      all: repeat rewrite kron_mixed_product.\n      all: Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣1⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      all: replace (∣0⟩⟨0∣ × ∣ 0 ⟩) with (∣ 0 ⟩) by solve_matrix;\n           replace (∣0⟩⟨1∣ × ∣ 0 ⟩) with (@Zero 2 1) by solve_matrix;\n           Qsimpl.\n      1,2,3: exists 0; solve_matrix.      \n      rewrite (ket_decomposition ψ WF).\n      exists (/ 2).\n      solve_matrix.\nQed.\n\nEnd NDTeleport.\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/Teleport.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7858096097747654}}
{"text": "Definition NatE : forall (p:nat -> Prop), \n    p 0 -> (forall (n:nat), p n -> p (S n)) -> forall (n:nat), p n := \n        fun (p:nat -> Prop) (H0:p 0) (IH:forall(m:nat),p m -> p (S m)) => \n            fix f (n:nat):p n := \n                match n with\n                | 0     => H0\n                | S m   => IH m (f m)\n                end. \n\nDefinition NatRec : forall (c:nat -> Type),\n    c 0 -> (forall (n:nat), c n -> c (S n)) -> forall (n:nat), c n := \n        fun (c:nat -> Type) (H0:c 0) (IH:forall(m:nat),c m -> c (S m)) =>\n            fix f(n:nat):c n := \n                match n with\n                | 0     => H0\n                | S m   => IH m (f m)\n                end.\n\nLemma NatRec0 : forall (c:nat -> Type) (a:c 0) (s:forall (n:nat), c n -> c (S n)),\n    NatRec c a s 0 = a.\nProof. intros c a s. reflexivity. Qed.\n\nLemma NatRecn : forall (c:nat -> Type) (a:c 0) (s:forall (n:nat), c n -> c (S n)),\n    forall (n:nat), NatRec c a s (S n) = s n (NatRec c a s n).\nProof. intros c a s n. reflexivity. Qed.\n\n\nDefinition F1 : nat -> nat := NatRec (fun _ => nat) 0 (fun _ n => S (S n)).\nDefinition F2 : nat -> nat := fix f (n:nat) : nat :=\n    match n with\n    | 0     => 0\n    | S n   => S (S (f n))\n    end.\n\nDefinition F3 : F1 = F2.\nProof. reflexivity. Qed.\n\nDefinition F4 : nat -> nat -> nat := fun (n:nat) => NatRec (fun _ => nat) n (fun _ => S).\nDefinition F5 : nat -> nat -> nat := fun (n:nat) => fix f(m:nat):nat :=\n    match m with\n    | 0     => n\n    | S m   => S (f m) \n    end.\n\nDefinition F6 : F4 = F5.\nProof. reflexivity. Qed.\n\nFixpoint sub (m n:nat) : nat :=\n    match m with\n    | 0     => 0\n    | S m   =>\n        match n with\n        | 0     => S m\n        | S n   => sub m n\n        end\n    end.\n\nDefinition F7 : nat -> nat -> nat. \nProof.\nrefine( NatRec (fun _ => nat -> nat) \n    (fun _ => 0)\n    (fun (m:nat) (f:nat -> nat) => NatRec (fun _ => nat)\n        (S m)\n        (fun n _ => f n)\n)).\nDefined.\n\n\n\nDefinition subst (a:Type) (p:a -> Prop) (x y:a) : x = y -> p x -> p y :=\n    fun (e:x = y) (px:p x) =>\n        match e with\n        | eq_refl _ => px\n        end.\n\nDefinition cong (a b:Type) (f:a -> b) (x y:a) : x = y -> f x = f y :=\n    fun (e:x = y) =>\n        subst a (fun (z:a) => f x = f z) x y e (eq_refl (f x)).\n\nDefinition L1 : forall (n:nat), n + 0 = n.\nProof.\nrefine ( fun(n:nat) => \n    NatE (fun (n:nat) => n + 0 = n) \n    (eq_refl 0) \n    (fun (m:nat) (H:m + 0 = m) => cong nat nat S (m + 0) m H)\n    n\n).\nQed.\n\nDefinition z_not_s : forall (n:nat), 0 = S n -> False :=\n    fun (n:nat) (e:0 = S n) =>\n        subst nat (fun (m:nat) =>\n            match m with\n            | 0     => True\n            | S _   => False\n            end) 0 (S n) e I.\n\nDefinition sinj : forall (m n:nat), S m = S n -> m = n :=\n    fun (m n:nat) (e:S m = S n) => \n        subst nat (fun (k:nat) =>\n            match k with\n            | 0     => True\n            | S k   => m = k\n            end) (S m) (S n) e (eq_refl m).\n\n\nDefinition L2 : forall (n:nat), S n = n -> False.\nProof.\nrefine ( NatE (fun (n:nat) => S n = n -> False) \n    (fun (e:1 = 0) => z_not_s 0 (eq_sym e))\n    (fun (n:nat) (IH:S n = n -> False) (e:S (S n) = S n) => \n        IH (sinj (S n) n e)\n)).\nQed.\n\nDefinition L3 : forall (n k:nat), n + S k = n -> False.\nProof.\nrefine ( NatE (fun (n:nat) => forall (k:nat), n + S k = n -> False)\n    (fun (k:nat) (e:0 + S k = 0) => z_not_s k (eq_sym e))\n    (fun (n:nat) (IH:forall (k:nat), n + S k = n -> False) =>\n        fun (k:nat) (e:S n + S k = S n) => IH k (sinj (n + S k) n e) \n)).\nQed.\n\nDefinition L4 : forall (m n p:nat), m + n = m + p -> n = p.\nProof.\nrefine ( NatE (fun (m:nat) => forall (n p:nat), m + n = m + p -> n = p)\n    (fun(n p:nat) (e:0 + n = 0 + p) => e)\n    (fun(m:nat) (IH:forall (n p:nat), m + n = m + p -> n = p) =>\n        fun (n p:nat) (e:S m + n = S m + p) => IH n p (sinj (m + n) (m + p) e)\n)).\nQed.\n\nDefinition L5 : forall (m n:nat), m = n \\/ ~ m = n.\nrefine (NatE (fun (m:nat) => forall (n:nat), m = n \\/ ~ m = n)\n       (fun (n:nat) => \n        match n with\n        | 0     => or_introl (eq_refl 0)\n        | S n   => or_intror (z_not_s _) \n        end)\n        (fun (m:nat) (IH:forall (n:nat), m = n \\/ ~ m = n) =>\n            fun (n:nat) => \n                match n with\n                | 0     => or_intror (fun (p:S m = 0) => z_not_s m (eq_sym p))\n                | S n   => \n                    match (IH n) with\n                    | or_introl e   => or_introl (cong nat nat S m n e)\n                    | or_intror ne  => or_intror (fun (se:S m = S n) => ne (sinj m n se))\n                    end \n            end\n)).\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/cttwc/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7858095966207194}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export indprop.\nDefinition relation (X: Type) := X -> X -> Prop.\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\n(*部分関数*)\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nPrint next_nat.\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\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\nInductive total_relation : nat -> nat -> Prop :=\n  tot : forall n m : nat, total_relation n m.\n\nCheck total_relation : relation nat.\n\nTheorem not_partial_total_relation :\n  ~(partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros.\n  assert (0 = 1) as Nonsense. {\n    apply H with (x:= 0) (y1:= 0) (y2:= 1).\n    - apply tot. - apply tot. }\n  discriminate Nonsense.\nQed.\n\nInductive empty_relation : nat -> nat -> Prop := .\n\nTheorem not_partial_empty_relation :\n  partial_function empty_relation.\nProof.\n  unfold partial_function. intros x y1 y2 H1 H2.\n  inversion H1. Qed.\n\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  - apply Hnm.\n  - apply le_S. apply IHHmo. apply Hnm. 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 lt_trans' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hnm.\n  - apply le_leftS in Hmo. apply Hmo.\n  - apply IHHnm. apply le_leftS. apply Hmo.\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. apply IHo'.\n    Abort.\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.\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 H2. apply H2.\nQed.\n\nTheorem not_le_Sn_n : forall n, ~(S n <= n).\nProof.\n  unfold not. intros. induction n.\n  - inversion H.\n  - apply IHn. apply le_S_n in H. apply H.\nQed.\n\n\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 Nonsense. {\n    apply H with (a:= 0) (b:= 1). apply le_S. apply le_n. }\n  inversion Nonsense.\nQed.\n\n\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.\n  generalize dependent a.\n  induction b.\n  intros a.\n  intros H.\n  intros H1.\n  inversion H.\n  reflexivity.\n\n  intros a H1 H2.\n  destruct a.\n  inversion H2.\n\n  apply Sn_le_Sm__n_le_m in H1.\n  apply Sn_le_Sm__n_le_m in H2.\n  apply IHb in H1.\n  rewrite H1.\n  reflexivity.\n\n  apply H2.\nQed.\n\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof.\n  unfold lt. intros. apply Sn_le_Sm__n_le_m. apply le_trans with m. apply H. apply H0.\nQed.\n\n(*同値関係*)\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(*半順序関係*)\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\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    - apply le_reflexive.\n    - split.\n      + apply le_antisymmetric.\n      + apply le_trans. Qed.\n\n(*反射推移閉包\nRを含み反射性と推移性の両者を満たす最小の関係 *)\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\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    + apply rt_refl.\n    +\n      apply rt_trans with m. apply IHle. apply rt_step.\n      apply nn.\n  -\n    intro H. induction H.\n    + inversion H. apply le_S. apply le_n.\n    + apply le_n.\n    +\n      apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\n\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\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\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. apply H0. apply rt1n_trans with (y0:= y). apply Hxy. apply IHclos_refl_trans_1n.\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 <-> clos_refl_trans_1n R x y.\nProof.\n  \n  intros. split.\n  - intros. induction H. apply rt1n_trans with (y0 := y). apply H. apply rt1n_refl. apply rt1n_refl.\n    apply rsc_trans with (y:= y).  apply IHclos_refl_trans1. apply IHclos_refl_trans2.\n  - intros. induction H. apply rt_refl. apply rt_trans with (y0:= y).\n    apply rt_step in Hxy. apply Hxy. apply IHclos_refl_trans_1n.\nQed.\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/rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7857914023481145}}
{"text": "(* Toy language of expressions https://www-verimag.imag.fr/~monin/Proof/Small_inversions/2021/eval_exp.v  *)\nInductive te : Type :=\n  | Te_const : nat -> te\n  | Te_plus : te -> te -> te\n  | Te_div0 : te -> te.\n\nInductive val : Type :=\n  | Nval  : nat -> val\n  | Bval  : bool -> val.\n\n(* Evaluation *)\nInductive eval : te -> val -> Prop :=\n  | E_Const : forall n,\n      eval (Te_const n) (Nval n)\n  | E_Plus : forall t1 t2 n1 n2,\n      eval t1 (Nval n1) ->\n      eval t2 (Nval n2) ->\n      eval (Te_plus t1 t2) (Nval (n1 + n2)).\n\n(* Auxiliary inductive definitions when the 1st arg is constructed *)\nInductive eval_Const_1 n : val -> Prop :=\n  | E_Const_1 : eval_Const_1 n (Nval n).\nInductive eval_Plus_1 t1 t2 : val -> Prop :=\n  | E_Plus_1 : forall n1 n2,\n      eval t1 (Nval n1) ->\n      eval t2 (Nval n2) ->\n      eval_Plus_1 t1 t2 (Nval (n1 + n2)).\nInductive eval_Div0_1 (t1: te) : val -> Prop :=.\n\nDefinition eval_1 : te -> val -> Prop :=\n  fun t =>\n    match t with\n    | Te_const n => eval_Const_1 n\n    | Te_plus t1 t2 => eval_Plus_1 t1 t2\n    | Te_div0 t1 => eval_Div0_1 t1\n    end.\n\nDefinition eval_eval_1 {t v} : eval t v -> eval_1 t v :=\n  fun e =>\n    match e with\n    | E_Const n => E_Const_1 n\n    | E_Plus t1 t2 n1 n2 e1 e2 => E_Plus_1 t1 t2 n1 n2 e1 e2\n    end.\n\n(* Interactive version *)\nDefinition eval_eval_1_inter {t v} : eval t v -> eval_1 t v.\nProof. intro e; destruct e; constructor; assumption. Qed.\n\n(* Explicit version *)\nDefinition eval_eval_1_bavard {t v} : eval t v -> eval_1 t v :=\n  fun e =>\n    match e in eval t v return eval_1 t v with\n    | E_Const n (*t := Te_const n, v := Nval n*) => E_Const_1 n : (eval_Const_1 n) (Nval n)\n    | E_Plus t1 t2 n1 n2 e1 e2 (*t := Te_plus t1 t2, v := Nval (n1 + n2)*) \n      => E_Plus_1 t1 t2 n1 n2 e1 e2 : (eval_Plus_1 t1 t2) (Nval (n1 + n2))\n    end.\n\n(* Auxiliary inductive definitions when the 2nd arg is constructed *)\n(* Moderately useful, because the contents of 2nd argument is not \n   constructed itself. \n   No cases for Bval, and 2 cases for Nval.\n   For the second, an auxiliary equality is introduced. *)\n\nInductive eval_Nat_2 (n: nat) : te -> Prop :=\n  | E_Const_2 : eval_Nat_2 n (Te_const n)\n  | E_Plus_2 : forall t1 t2 n1 n2,\n      eval t1 (Nval n1) ->\n      eval t2 (Nval n2) ->\n      n = n1 + n2 ->\n      eval_Nat_2 n (Te_plus t1 t2).\n\nInductive eval_Bool_2 (b: bool) : te -> Prop :=.\n\nDefinition eval_2 : te -> val -> Prop :=\n  fun t v =>\n    match v with\n    | Nval n => eval_Nat_2 n\n    | Bval b => eval_Bool_2 b\n    end t.\n\nDefinition eval_eval_2 {t v} : eval t v -> eval_2 t v :=\n  fun e =>\n    match e with\n    | E_Const n => E_Const_2 n\n    | E_Plus t1 t2 n1 n2 e1 e2 => E_Plus_2 (n1 + n2) t1 t2 n1 n2 e1 e2 eq_refl\n    end.\n\n(* Auxiliary inductive definitions when args 1 and 2 are constructed *)\n\n(* Symmetrical version, with 2 indices. \n   Combines _1 and _2, with cumbersome additional equalities *)\nModule S. \nInductive eval_Const_Nval_1_2 (c n : nat) : Prop :=\n  | E_Const_Nval_1_2 : c = n -> eval_Const_Nval_1_2 c n.\nInductive eval_Plus_Nval_1_2 t1 t2 n : Prop :=\n  | E_Plus_Nval_1_2 : forall n1 n2,\n      eval t1 (Nval n1) ->\n      eval t2 (Nval n2) ->\n      n = n1 + n2 ->\n      eval_Plus_Nval_1_2 t1 t2 n.\nInductive eval_other_Nval_1_2 : Prop :=.\n\nDefinition eval_1_2 : te -> val -> Prop :=\n  fun t v =>\n    match t, v with\n    | Te_const c, Nval n => eval_Const_Nval_1_2 c n\n    | Te_plus t1 t2, Nval n => eval_Plus_Nval_1_2 t1 t2 n\n    | _, _ => eval_other_Nval_1_2\n    end.\n\nDefinition eval_eval_1_2 {t v} : eval t v -> eval_1_2 t v :=\n  fun e =>\n    match e with\n    | E_Const n => E_Const_Nval_1_2 n n eq_refl\n    | E_Plus t1 t2 n1 n2 e1 e2 => E_Plus_Nval_1_2 t1 t2 (n1 + n2) n1 n2 e1 e2 eq_refl\n    end.\nEnd S.\n\n(* Asymmetrical version, with 1 param and 1 indice:\n   the first has precedence over the second, because it is\n   \"more constructed\". Then the cumbersome equalities can be removed *)\nModule A.\nInductive eval_Const_Nval_1_2 n : nat -> Prop :=\n  | E_Const_Nval_1_2 : eval_Const_Nval_1_2 n n.\nInductive eval_Plus_Nval_1_2 t1 t2 : nat -> Prop :=\n  | E_Plus_Nval_1_2 : forall n1 n2,\n      eval t1 (Nval n1) ->\n      eval t2 (Nval n2) ->\n      eval_Plus_Nval_1_2 t1 t2 (n1 + n2).\nInductive eval_other_Nval_1_2 : Prop :=.\n\nDefinition eval_1_2 : te -> val -> Prop :=\n  fun t v =>\n    match t, v with\n    | Te_const c, Nval n => eval_Const_Nval_1_2 c n\n    | Te_plus t1 t2, Nval n => eval_Plus_Nval_1_2 t1 t2 n\n    | _, _ => eval_other_Nval_1_2\n    end.\n\nDefinition eval_eval_1_2 {t v} : eval t v -> eval_1_2 t v :=\n  fun e =>\n    match e with\n    | E_Const n => E_Const_Nval_1_2 n\n    | E_Plus t1 t2 n1 n2 e1 e2 => E_Plus_Nval_1_2 t1 t2 n1 n2 e1 e2\n    end.\nEnd A.\n\nNotation eval_eval_1_2 := A.eval_eval_1_2.\n\nSection varP.\n\nVariable P : val -> Prop.\n\nLemma test_ev1 :\n  forall v , P v -> eval (Te_plus (Te_const 1) (Te_const 0)) v -> v = Nval 1.\nProof.\n  intros v p e.\n  destruct (eval_eval_1 e) as [n1 n2 e1 e2].\n  destruct (eval_eval_1_2 e1).\n  destruct (eval_eval_1_2 e2).\n  reflexivity.\nQed.\n\nLemma test_ev1_S :\n  forall v , P v -> eval (Te_plus (Te_const 1) (Te_const 0)) v -> v = Nval 1.\nProof.\n  intros v p e.\n  destruct (eval_eval_1 e) as [n1 n2 e1 e2].\n  generalize (S.eval_eval_1_2 e1). simpl. intro e1'.\n  destruct (S.eval_eval_1_2 e1) as [eq1].\n  destruct (S.eval_eval_1_2 e2) as [eq2].\n  subst. reflexivity.\nQed.\n\nLemma test_ev2:\n  eval (Te_plus (Te_const 1) (Te_const 0)) (Bval true) -> False.\nProof.\nintro e. destruct (S.eval_eval_1_2 e).\nQed.\n\nLemma test_ev2':\n  eval (Te_plus (Te_const 1) (Te_const 0)) (Nval 0) -> False.\nProof.\n  intro e.\n  cut (0=1). discriminate.\n  pattern 0 at 1.\n  destruct (eval_eval_1_2 e) as [n1 n2 e1 e2].\n  destruct (eval_eval_1_2 e1).\n  destruct (eval_eval_1_2 e2).\n  reflexivity.\nQed.\n\nLemma test_ev3:\n  forall n, n < 5 -> eval (Te_plus (Te_const 1) (Te_const 0)) (Nval n) -> n = 1.\nProof.\n  intros n l e. \n  destruct (eval_eval_1_2 e) as [n1 n2 e1 e2].\n  destruct (eval_eval_1_2 e1).\n  destruct (eval_eval_1_2 e2).\n  reflexivity.\nQed.\n\nLemma test_ev3_S:\n  forall n, n < 5 -> eval (Te_plus (Te_const 1) (Te_const 0)) (Nval n) -> n = 1.\nProof.\n  intros n l e. \n  destruct (S.eval_eval_1_2 e) as [n1 n2 e1 e2 eq].\n  destruct (S.eval_eval_1_2 e1) as [eq1].\n  destruct (S.eval_eval_1_2 e2) as [eq2].\n  subst. reflexivity.\nQed.\n\nEnd varP.\n\n(* ------------------------------------------------------------ *)\n\n(* Non-deterministic evaluation, in order to illustrate\n   several cases matching an \"input\"\n*)\n\nSection varQ.\n\nVariable Q : te -> Prop.\n\nInductive eval_nd: te -> val -> Prop :=\n  | E_Const_nd : forall n,\n      eval_nd (Te_const n) (Nval n)\n  | E_Plus_nd1 : forall t1 t2 n1 n2,\n      eval_nd t1 (Nval n1) ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd (Te_plus t1 t2) (Nval (n1 + n2))\n  | E_Plus_nd2 : forall t1 t2 n2,\n      Q t1 ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd (Te_plus t1 t2) (Nval n2).\n\n(* Auxiliary inductive definitions *)\nInductive eval_nd_Const_1 n : val -> Prop :=\n  | E_Const_nd_1 : eval_nd_Const_1 n (Nval n).\nInductive eval_nd_Plus_1 t1 t2 : val -> Prop :=\n  | E_Plus_nd1_1 : forall n1 n2,\n      eval_nd t1 (Nval n1) ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd_Plus_1 t1 t2 (Nval (n1 + n2))\n  | E_Plus_nd2_1 : forall n2,\n      Q t1 ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd_Plus_1 t1 t2 (Nval n2).\nInductive eval_Div0_1_2 (t1 : te) : val -> Prop :=.\n\nDefinition eval_nd_1 : te -> val -> Prop :=\n  fun t =>\n    match t with\n    | Te_const n => eval_nd_Const_1 n\n    | Te_plus t1 t2 => eval_nd_Plus_1 t1 t2\n    | Te_div0 t1 => eval_Div0_1_2 t1\n    end.\n\nDefinition eval_nd_eval_nd_1 {t v} : eval_nd t v -> eval_nd_1 t v :=\n  fun e =>\n    match e with\n    | E_Const_nd n => E_Const_nd_1 n\n    | E_Plus_nd1 t1 t2 n1 n2 e1 e2 => E_Plus_nd1_1 t1 t2 n1 n2 e1 e2\n    | E_Plus_nd2 t1 t2 n2 q e2 => E_Plus_nd2_1 t1 t2 n2 q e2\n    end.\n\nInductive eval_nd_Const_Nval_1_2 n : nat -> Prop :=\n  | E_Const_nd_Nval_1_2 : eval_nd_Const_Nval_1_2 n n.\nInductive eval_nd_Plus_Nval_1_2 t1 t2 : nat -> Prop :=\n  | E_Plus_nd_Nval1_1_2 : forall n1 n2,\n      eval_nd t1 (Nval n1) ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd_Plus_Nval_1_2 t1 t2 (n1 + n2)\n  | E_Plus_nd_Nval2_1_2 : forall n2,\n      Q t1 ->\n      eval_nd t2 (Nval n2) ->\n      eval_nd_Plus_Nval_1_2 t1 t2 n2.\n\nDefinition eval_nd_1_2 : te -> val -> Prop :=\n  fun t v =>\n    match t, v with\n    | Te_const c, Nval n => eval_nd_Const_Nval_1_2 c n\n    | Te_plus t1 t2, Nval n => eval_nd_Plus_Nval_1_2 t1 t2 n\n    | _, _ => False\n    end.\n\nDefinition eval_nd_eval_nd_1_2 {t v} : eval_nd t v -> eval_nd_1_2 t v :=\n  fun e =>\n    match e with\n    | E_Const_nd n => E_Const_nd_Nval_1_2 n\n    | E_Plus_nd1 t1 t2 n1 n2 e1 e2 => E_Plus_nd_Nval1_1_2 t1 t2 n1 n2 e1 e2\n    | E_Plus_nd2 t1 t2 n2 q e2 => E_Plus_nd_Nval2_1_2 t1 t2 n2 q e2\n    end.\n\nLemma test_ev_nd2:\n  forall t, eval_nd (Te_plus (Te_const 0) (Te_const 1)) t-> t = Nval 1.\nProof.\n  intros t e.\n  destruct (eval_nd_eval_nd_1 e) as [n1 n2 e1 e2 | n2 q e2].\n  - destruct (eval_nd_eval_nd_1_2 e1). destruct (eval_nd_eval_nd_1_2 e2). reflexivity.\n  - destruct (eval_nd_eval_nd_1_2 e2). reflexivity.\nQed.\n\n\nLemma test_ev_nd3:\n  forall n, eval_nd (Te_plus (Te_const 0) (Te_const 1)) (Nval n) -> n = 1.\nProof.\n  intros n e.\n  destruct (eval_nd_eval_nd_1_2 e) as [n1 n2 e1 e2 | n2 q e2].\n  - destruct (eval_nd_eval_nd_1_2 e1). destruct (eval_nd_eval_nd_1_2 e2). reflexivity.\n  - destruct (eval_nd_eval_nd_1_2 e2). reflexivity.\nQed.\n\nEnd varQ.\n", "meta": {"author": "mukeshtiwari", "repo": "CoqUtil", "sha": "1652ce26841d9eb706d0c0b847dc2c66283646cb", "save_path": "github-repos/coq/mukeshtiwari-CoqUtil", "path": "github-repos/coq/mukeshtiwari-CoqUtil/CoqUtil-1652ce26841d9eb706d0c0b847dc2c66283646cb/val_exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7857860025088621}}
{"text": "Require Import Omega Init.Nat Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat Coq.Structures.Equalities.\n\n\n\nLemma obvio_1: forall (N:nat) , (2< N) %nat -> (0 < N) %nat.\nProof.\nintros. omega.\nQed.\n\n\nLemma obvio_2: forall (n m:nat) , (n < m)%nat -> (n-m)%nat = zero.\nProof.\nintros. \ninduction n.\ninduction m. reflexivity. simpl. reflexivity.\ncut ( (S n- m)%nat = pred (n-m)).\n+ intros. rewrite H0. rewrite IHn. simpl. reflexivity. omega.\n+ omega.\nQed. \n\nLemma obvio_3: forall (n:nat) , (n-n)%nat =zero.\nProof.\nintros.\ninduction n.\nauto. \nsimpl. rewrite IHn. reflexivity.\nQed.\n\n", "meta": {"author": "mohittkr", "repo": "Lax_equivalence", "sha": "c19b626513ce8ec1a6426f2364e6c45e8caa85ae", "save_path": "github-repos/coq/mohittkr-Lax_equivalence", "path": "github-repos/coq/mohittkr-Lax_equivalence/Lax_equivalence-c19b626513ce8ec1a6426f2364e6c45e8caa85ae/obvio_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113863, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7857159688387647}}
{"text": "(* Ejercicio 6.3 *)\nSection ej63.\n\nDefinition Value := bool.\nInductive BoolExpr : Set :=\n  | bbool : bool -> BoolExpr\n  | band : BoolExpr -> BoolExpr -> BoolExpr\n  | bnot : BoolExpr -> BoolExpr.\nInductive BEval : BoolExpr -> Value -> Prop :=\n  | ebool : forall b : bool, BEval (bbool b) (b:Value)\n  | eandl : forall e1 e2 : BoolExpr, BEval e1 false -> BEval (band e1 e2) false\n  | eandr : forall e1 e2 : BoolExpr, BEval e2 false -> BEval (band e1 e2) false\n  | eandrl : forall e1 e2 : BoolExpr, BEval e1 true -> BEval e2 true -> BEval (band e1 e2) true\n  | enott : forall e : BoolExpr, BEval e true -> BEval (bnot e) false\n  | enotf : forall e : BoolExpr, BEval e false -> BEval (bnot e) true.\n\nFixpoint beval1 (e : BoolExpr) : Value :=\n  match e with\n  | bbool b => b\n  | band e1 e2 =>\n    match beval1 e1, beval1 e2 with\n    | true, true => true\n    | _, _ => false\n    end\n  | bnot e1 => if beval1 e1 then false else true\nend.\n \nFixpoint beval2 (e : BoolExpr) : Value :=\n  match e with\n  | bbool b => b\n  | band e1 e2 =>\n    match beval2 e1 with\n    | false => false\n    | _ => beval2 e2\n    end\n  | bnot e1 => if beval2 e1 then false else true\n  end.\n\n(* Ejercicio 6.3.1 - sin hints *)\n\nLemma beval1C : forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval1 e).\ninduction e; simpl.\n  - constructor.\n  - destruct (beval1 e1); try constructor; auto.\n    destruct (beval1 e2); try apply eandr; try constructor; auto.\n  - destruct (beval1 e); constructor; auto.\nQed.\n\nLemma beval2C : forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval2 e).\ninduction e; simpl.\n  - constructor.\n  - destruct (beval2 e1); try constructor; auto.\n    destruct (beval2 e2); try apply eandr; try constructor; auto.\n  - destruct (beval2 e); constructor; auto.\nQed.\n\n(* Ejercicio 6.3.2 - con hints *)\n\nHint Constructors BEval.\n\nLemma beval1CH : forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval1 e).\ninduction e; simpl; auto.\n  - destruct (beval1 e1), (beval1 e2); auto.\n  - destruct (beval1 e); auto.\nQed.\n\nLemma beval2CH : forall e:BoolExpr, {b:Value |(BEval e b)}.\nProof.\nintros.\nexists (beval2 e).\ninduction e; simpl; auto.\n  - destruct (beval2 e1), (beval2 e2); auto.\n  - destruct (beval2 e); auto.\nQed.\n\nEnd ej63.\n\n(* Ejercicio 6.3.3/4 - extracción *)\nRequire Extraction.\nExtraction Language Haskell.\n(* Ejercicio 6.3.4 - usar tipo bool de Haskell *)\nExtract Inductive bool => \"Prelude.Bool\" [ \"Prelude.True\" \"Prelude.False\" ].\n\nExtraction \"beval1C.hs\" beval1C.\nExtraction \"beval2C.hs\" beval2C.\nExtraction \"beval1CH.hs\" beval1CH.\nExtraction \"beval2CH.hs\" beval2CH.\n\n\n(* Ejercicio 6.5 *)\nSection ej65.\n\n(* Ejercicio 6.5.1 *)\nInductive Le : nat -> nat -> Prop :=\n  | Le_0  : forall n: nat, Le 0 n\n  | Le_Sn : forall n m: nat, Le n m -> Le (S n) (S m).\n\nInductive Gt : nat -> nat -> Prop :=\n  | Gt_n  : forall n: nat, Gt (S n) 0\n  | Gt_Sn : forall n m: nat, Gt n m -> Gt (S n) (S m).\n\n(* Ejercicio 6.5.2 *)\nFixpoint leBool (n m: nat) :=\n  match n, m with\n    | 0, _           => true\n    | _, 0           => false\n    | (S ni), (S mi) => leBool ni mi\n  end.\n\nRequire Import FunInd.\nFunctional Scheme leBool_ind := Induction for leBool Sort Set.\n\nHint Constructors Le.\nHint Constructors Gt.\n\nLemma Le_Gt_dec: forall n m:nat, {(Le n m)}+{(Gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m) using leBool_ind; simpl; auto.\ndestruct IHb; [ left | right ]; auto.\nQed.\n\n(* Ejercicio 6.5.3 *)\nRequire Import Omega.\n\nLemma le_gt_dec: forall n m:nat, {(le n m)}+{(gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m) using leBool_ind; simpl; auto with arith.\ndestruct IHb; [ left | right ]; omega. (* sirve auto with arith *)\nQed.\n\nEnd ej65.\n\n\n(* Ejercicio 6.6 *)\nSection ej66.\n\nRequire Import Omega.\nRequire Import DecBool.\nRequire Import Compare_dec.\nRequire Import Plus.\nRequire Import Mult.\n\nDefinition spec_res_nat_div_mod (a b:nat) (qr:nat*nat) :=\n  match qr with\n    (q,r) => (a = b*q + r) /\\ r < b\n  end.\n\nDefinition nat_div_mod : forall a b:nat, not(b=0) -> {qr:nat*nat | spec_res_nat_div_mod a b qr}.\nProof.\nintros.\ninduction a.\n  * exists (0,0); simpl; omega.\n  * destruct IHa.\n    destruct x.\n    induction s.\n    case_eq (le_lt_eq_dec (S n0) b); auto.\n      + exists (n, (S n0)).\n        simpl.\n        split; auto with arith; omega.\n      + exists ((S n), 0).\n        simpl.\n        rewrite -> H0.\n        rewrite <- e.\n        simpl.\n        replace (n0 * S n) with (n0 * n + n0); auto with arith.\n        split; omega.\nQed.\n\nEnd ej66.\n\n\n(* Ejercicio 6.7 *)\nSection ej67.\n\nInductive tree (A:Set) : Set :=\n  | leaf : tree A\n  | node : A -> tree A -> tree A -> tree A.\n\nInductive tree_sub (A:Set) (t:tree A) : tree A -> Prop :=\n  | tree_sub1 : forall (t':tree A) (x:A), tree_sub A t (node A x t t')\n  | tree_sub2 : forall (t':tree A) (x:A), tree_sub A t (node A x t' t).\n\nTheorem well_founded_tree_sub : forall A:Set, well_founded (tree_sub A).\nProof.\nunfold well_founded.\nintros.\ninduction a;\nconstructor;\nintros;\ninversion H;\nauto.\nQed.\n\nEnd ej67.\n\n\n(* Ejercicio 6.8 *)\nSection ej68.\n\n(* Ejercicio 6.8.1 *)\nFixpoint size (x: BoolExpr) :=\n  match x with\n  | bbool _  => 1\n  | band x y => size x + size y + 1\n  | bnot x   => size x + 1\n  end.\n\nDefinition elt (e1 e2 : BoolExpr) := size e1 < size e2. \n\n(* Ejercicio 6.8.2 *)\nRequire Import Wf_nat.\nRequire Import Inverse_Image.\n\nTheorem well_founded_elt : well_founded (elt).\nProof.\napply (wf_inverse_image BoolExpr nat).\nexact lt_wf.\nQed.\n\nEnd ej68.", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 6/p6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8840392909114835, "lm_q1q2_score": 0.7856976883808544}}
{"text": "(* Copied and modified from Xavier Leroy's lectures. *)\n\n(** 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/auto/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7854757013676082}}
{"text": "Section LPPO_1.\nVariable A : Set.\nVariables P Q : A -> Prop.\nLemma lppo_exrc_1 :\n(exists x : A, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\nsplit.\nintro.\ndestruct H.\ndestruct H.\nleft.\nexists x.\nassumption.\nright.\nexists x.\nassumption.\nintro.\ndestruct H.\ndestruct H.\nexists x.\nleft.\nassumption.\ndestruct H.\nexists x.\nright.\nassumption.\nQed.\nLemma lppo_exrc_2 : ~(exists x : A, P x) <-> forall x : A, ~P x.\nProof.\nsplit.\nintro.\nintro x0.\nintro.\napply H.\nexists x0.\nassumption.\nintro.\nintro.\ndestruct H0.\nassert (H1 := H x).\napply H1.\nassumption.\nQed.\nEnd LPPO_1.\n\nSection natProofs.\nVariable a b c d: nat. (*variables de tipo nat*)\n\n(*B) a*)\nTheorem identity : forall a, a + 0 = a.\nintro.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nreflexivity.\nQed.\n\n(*B) b*)\nTheorem associative : forall a b c, a + (b + c) = (a + b) + c.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nreflexivity.\nQed.\n\nTheorem subCommutative : forall a b, S (b + a) = b + S (a).\nProof.\nintros.\ninduction b0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHb0.\nreflexivity.\nQed.\n\n(*B) c*)\nTheorem commutative : forall a b, a + b = b + a.\nintros.\ninduction a0.\nsimpl.\nrewrite identity.\nreflexivity.\nsimpl.\nrewrite IHa0.\nrewrite subCommutative.\nreflexivity.\nQed.\n\n(*B) d*)\nTheorem equality: forall a b c, b = c -> b + a = c + a.\nProof.\nintros.\ninduction a0.\nrewrite identity.\nrewrite -> identity.\nrewrite H.\nreflexivity.\nrewrite commutative.\nsimpl.\nrewrite commutative.\nrewrite IHa0.\nrewrite subCommutative.\nreflexivity.\nQed.\n\n(*C) a*)\nTheorem multIdentity: forall a, a * 1 = a.\nProof.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nreflexivity.\nQed.\n\n(*C) b*)\nTheorem zeroProduct: forall a, a * 0 = 0.\nProof.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nreflexivity.\nQed.\n\nTheorem auxSubCommutative: forall a b, a * b + b = b + a * b.\nProof.\nintros.\ninduction b0.\nsimpl.\nrewrite identity.\nrewrite zeroProduct.\nreflexivity.\nrewrite commutative.\nsimpl.\nreflexivity.    \nQed.\n\n(*C) c*)\nTheorem auxCommutative: forall a b, a * S b = a + a * b.\nProof.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite commutative.\nrewrite IHa0.\nrewrite commutative.\nrewrite associative.\nrewrite commutative.\nrewrite associative.\nrewrite commutative.\nrewrite auxSubCommutative.\nreflexivity.\nQed.\n\n(*C) d*)\nTheorem multCommutative: forall a b, a * b = b * a.\nProof.\nintros.\ninduction b0.\nsimpl.\nrewrite zeroProduct.\nreflexivity.\nsimpl.\nrewrite auxCommutative.\nrewrite IHb0.\nreflexivity.\nQed.\n\n(*C) e*)\nTheorem multDistributive: forall a b c, a * (b + c) = (a * b) + (a * c).\nProof.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nrewrite associative.\nrewrite commutative.\nassert (H: b0 + c0 = c0 + b0).\nrewrite commutative.\nreflexivity.\nrewrite H.\nrewrite commutative.\nassert (H1: c0 + b0 + a0 * b0 = c0 + (b0 + a0 * b0)).\nrewrite associative.\nreflexivity.\nassert (H2: c0 + (b0 + a0 * b0) = (b0 + a0 * b0) + c0).\nrewrite commutative.\nsimpl.\nreflexivity.\nrewrite H1.\nrewrite H2.\nrewrite associative.\nreflexivity.\nQed.\n\n(*C) f*)\nTheorem multAssociative: forall a b c, a * (b * c) = (a * b) * c.\nProof.\nintros.\ninduction a0.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHa0.\nrewrite commutative.\nsimpl.\nrewrite multCommutative.\nrewrite commutative.\nrewrite multCommutative.\nrewrite <- multDistributive.\nrewrite multCommutative.\nreflexivity.\nQed.\n\nEnd natProofs.\n\n\n\n\n\n\n\n\n\n    ", "meta": {"author": "antoyneGG", "repo": "My-coq-files", "sha": "92c2b986d5108c395b34d002e387df8dc9903984", "save_path": "github-repos/coq/antoyneGG-My-coq-files", "path": "github-repos/coq/antoyneGG-My-coq-files/My-coq-files-92c2b986d5108c395b34d002e387df8dc9903984/Taller_5_FabianAntoyne_GarciaGallego.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746092, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7853803964760308}}
{"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: Gt.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Theorems about [gt] in [nat]. [gt] is defined in [Init/Peano.v] as:\n<<\nDefinition gt (n m:nat) := m < n.\n>>\n*)\n\nRequire Import Le.\nRequire Import Lt.\nRequire Import Plus.\nOpen Local Scope nat_scope.\n\nImplicit Types m n p : nat.\n\n(** * Order and successor *)\n\nTheorem gt_Sn_O : forall n, S n > 0.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_Sn_O: arith v62.\n\nTheorem gt_Sn_n : forall n, S n > n.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_Sn_n: arith v62.\n\nTheorem gt_n_S : forall n m, n > m -> S n > S m.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_n_S: arith v62.\n\nLemma gt_S_n : forall n m, S m > S n -> m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate gt_S_n: arith v62.\n\nTheorem gt_S : forall n m, S n > m -> n > m \\/ m = n.\nProof.\n  intros n m H; unfold gt in |- *; apply le_lt_or_eq; auto with arith.\nQed.\n\nLemma gt_pred : forall n m, m > S n -> pred m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate gt_pred: arith v62.\n\n(** * Irreflexivity *)\n\nLemma gt_irrefl : forall n, ~ n > n.\nProof lt_irrefl.\nHint Resolve gt_irrefl: arith v62.\n\n(** * Asymmetry *)\n\nLemma gt_asym : forall n m, n > m -> ~ m > n.\nProof fun n m => lt_asym m n.\n\nHint Resolve gt_asym: arith v62.\n\n(** * Relating strict and large orders *)\n\nLemma le_not_gt : forall n m, n <= m -> ~ n > m.\nProof le_not_lt.\nHint Resolve le_not_gt: arith v62.\n\nLemma gt_not_le : forall n m, n > m -> ~ n <= m.\nProof.\nauto with arith.\nQed.\n\nHint Resolve gt_not_le: arith v62.\n\nTheorem le_S_gt : forall n m, S n <= m -> m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate le_S_gt: arith v62.\n\nLemma gt_S_le : forall n m, S m > n -> n <= m.\nProof.\n  intros n p; exact (lt_n_Sm_le n p).\nQed.\nHint Immediate gt_S_le: arith v62.\n\nLemma gt_le_S : forall n m, m > n -> S n <= m.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_le_S: arith v62.\n\nLemma le_gt_S : forall n m, n <= m -> S m > n.\nProof.\n  auto with arith.\nQed.\nHint Resolve le_gt_S: arith v62.\n\n(** * Transitivity *)\n\nTheorem le_gt_trans : forall n m p, m <= n -> m > p -> n > p.\nProof.\n  red in |- *; intros; apply lt_le_trans with m; auto with arith.\nQed.\n\nTheorem gt_le_trans : forall n m p, n > m -> p <= m -> n > p.\nProof.\n  red in |- *; intros; apply le_lt_trans with m; auto with arith.\nQed.\n\nLemma gt_trans : forall n m p, n > m -> m > p -> n > p.\nProof.\n  red in |- *; intros n m p H1 H2.\n  apply lt_trans with m; auto with arith.\nQed.\n\nTheorem gt_trans_S : forall n m p, S n > m -> m > p -> n > p.\nProof.\n  red in |- *; intros; apply lt_le_trans with m; auto with arith.\nQed.\n\nHint Resolve gt_trans_S le_gt_trans gt_le_trans: arith v62.\n\n(** * Comparison to 0 *)\n\nTheorem gt_0_eq : forall n, n > 0 \\/ 0 = n.\nProof.\n  intro n; apply gt_S; auto with arith.\nQed.\n\n(** * Simplification and compatibility *)\n\nLemma plus_gt_reg_l : forall n m p, p + n > p + m -> n > m.\nProof.\n  red in |- *; intros n m p H; apply plus_lt_reg_l with p; auto with arith.\nQed.\n\nLemma plus_gt_compat_l : forall n m p, n > m -> p + n > p + m.\nProof.\n  auto with arith.\nQed.\nHint Resolve plus_gt_compat_l: arith v62.\n\n(* begin hide *)\nNotation gt_O_eq := gt_0_eq (only parsing).\n(* end hide *)\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/Gt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7852096673939917}}
{"text": "Require Import HoTT.Basics.\n\nSection Definitions.\n\tVariable A:Set.\n\tDefinition prod A := A->A->A.\n\tDefinition associative {A} (m : prod A) :=\n\t\tforall a b c : A, m (m a b) c = m a (m b c).\n\tDefinition commutative {A} (m : prod A) :=\n\t\tforall a b : A, m a b = m b a.\n\tDefinition neutral {A} (e:A) (m:prod A) :=\n\t\tforall a:A, (m e a = a) /\\ (m a e = a).\n\tDefinition exists_inverse {A} (m:prod A) (e:A) :=\n\t\tforall a:A, exists a', m a a' = e /\\ m a' a = e.\n\t\n\tDefinition isMonoid A (m : prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m.\n\tDefinition isCommutative_Monoid A (m : prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ commutative m.\n\tDefinition isGroup A (m:prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ exists_inverse m e.\n\tDefinition isAbelian_Group A (m:prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ exists_inverse m e /\\ commutative m.\nEnd Definitions.\n\nSection Nat.\n\tFixpoint add (m:nat) : nat->nat :=\n\t\tmatch m with\n\t\t\t| O => (fun n:nat => n)\n\t\t\t| S m => (fun n:nat => S (add m n) )\n\t\tend.\n\t\t\n\t\n\t(*Addition is defined recursively on the first variable.\n\tIt also decreases on second variable: *)\n\tLemma pred_second : forall m n : nat, add m (S n) = S (add m n).\n\tProof.\n\t\tintros m n.\n\t\tinduction m.\n\t\t(*Base case*) * reflexivity.\n\t\t(*Induction step*) *\n\t\t\tsimpl.\n\t\t\trewrite IHm. reflexivity.\n\tDefined.\n\t\n\tLemma addzero : forall n : nat, add n 0 = n.\n\tProof.\n\tinduction n. reflexivity. (*Base case done*)\n\t(*Induction step:*)\n\tsimpl. rewrite IHn. reflexivity.\n\tDefined.\n\n\tLemma zeroadd : forall n : nat, add 0 n = n.\n\tProof. reflexivity. Defined.\t\n\n\tLemma add_associative : forall l m n:nat, add (add l m) n = add l (add m n).\n\t\tinduction l.\n\t\t\tinduction m.\n\t\t\t\tinduction n.\n\t\t\t\t\t(*l m n = 0*) * reflexivity.\n\t\t\t\t\t(*l = m = 0, Step n*)* reflexivity.\n\t\t\t\t\t(*l = 0, Step m *)* reflexivity.\n\t\t\t\t\t(*Step l*)*\n\t\t\t\t\t\tintros m n.\n\t\t\t\t\t\tsimpl.\n\t\t\t\t\t\tapply (ap S).\n\t\t\t\t\t\tapply IHl.\n\tDefined.\n\t\n\tLemma add_commutative : forall n m:nat, add n m = add m n.\n\t\tinduction n.\n\t\t(*Base case*) *\n\t\t\tintro m.\n\t\t\trewrite addzero. reflexivity.\n\t\t(*Induction step*) *\n\t\t\tintro m.\n\t\t\tsimpl.\n\t\t\trewrite IHn.\n\t\t\tsymmetry.\n\t\t\tapply pred_second.\n\tDefined.\n\t\n\tProposition nat_comm_monoid : isCommutative_Monoid nat add O.\n\t\tunfold isCommutative_Monoid.\n\t\tsplit.\n\t\t\t(*Associativity*) *\n\t\t\t\t\tunfold associative.\n\t\t\t\t\tapply add_associative.\n\t\t\t\t* split.\n\t\t\t\t(*Neutral element*) **\n\t\t\t\t\tunfold neutral.\n\t\t\t\t\tintro n.\n\t\t\t\t\tsplit.\n\t\t\t\t\t\t\t***apply zeroadd. ***apply addzero.\n\t\t\t(*Commutativity*) **\n\t\t\t\tunfold commutative.\n\t\t\t\tapply add_commutative.\n\tDefined.\n\t\t\t\n\n\n\t(*Define addition by recursion on the second variable.*)\n\tFixpoint add' (m n : nat) : nat :=\n\t\tmatch n with\n\t\t|O => m\n\t\t|S n1 => S (add' m n1)\n\tend.\n\t\n\t\n\tProposition equaladditions : forall m n:nat, add m n = add' m n.\n\t\tinduction n.\n\t\t(*Base case*) * simpl. rewrite addzero. reflexivity.\n\t\t(*Induction step*) *\n\t\t\tsimpl.\n\t\t\trewrite pred_second.\n\t\t\trewrite IHn.\n\t\t\treflexivity.\n\tDefined.\n\n\t\t\t\n\t(*Slightly different proof showing that the two additions are equal (doesn't use lemmas)*)\n\tProposition equaladditions2 : forall m n:nat, add m n = add' m n.\n\t\tinduction m.\n\t\t(*Base case m*) *\n\t\t\tinduction n.\n\t\t\t\t(*Base case n*) ** reflexivity.\n\t\t\t\t(*Induction step n*) ** \n\t\t\t\t\tsimpl.\n\t\t\t\t\trewrite <- IHn. \n\t\t\t\t\treflexivity.\n\t\t(*Induction step m*) *\n \t\t\tintro n.\n\t\t\tsimpl.\n\t\t\trewrite IHm.\n\t\t\t\tinduction n.\n\t\t\t\t\t(*Base case n*) ** reflexivity.\n\t\t\t\t\t(*Induction step n*) **\n\t\t\t\t\t\tsimpl.\n\t\t\t\t\t\trewrite IHn. reflexivity.\n\tDefined.\n\nEnd Nat.\n\nSection Bad_Idea.\n\tInductive Z' : Set :=\n\t\t|minus (n0 n1:nat) : Z'\n\t.\n\t\n\tAxiom eq_Z : forall m1 m2 n1 n2 : nat, \n\t\tadd m1 n2 = add n1 m2 <-> minus m1 m2 = minus n1 n2.\n\t\n\tDefinition f (n : Z') : nat :=\n\t\tmatch n with\n\t\t\tminus n1 n2 => n1\n\t\tend.\n\t\n\tLemma eq1 : minus 1 1 = minus 0 0.\n\t\tapply eq_Z. reflexivity.\n\tQed.\n\t\n\tTheorem wrong : 1=0.\n\t\tapply ((ap f) eq1).\n\tQed.\n\nEnd Bad_Idea.\n\n\n\nSection Integers.\t\n\n\tInductive Z : Set :=\n\t\t|subt (n0 n1:nat) : Z\n\t.\n\t\n\tDefinition EqZ (m n : Z) : Type :=\n\t\tmatch m,n with\n\t\t\t| subt m1 m2, subt n1 n2 =>\n\t\t\t\tadd m1 n2 = add m2 n1\n\t\tend.\n\t\n\tLemma refl_Z : Reflexive EqZ.\n\t\tunfold Reflexive. Abort.\n\t\n\t(*TODO: This is equiv relation*)\n\t\n\t\n\tDefinition WellDefined_Z {A:Type} (f:Z->A) : Type.\n\t\t(*TODO*) exact A. Defined.\n(* \tAxiom eq_Z_1 : forall m1 m2 n1 n2 : nat, \n\t\tadd m1 n2 = add n1 m2 -> subt m1 m2 = subt n1 n2.\n\t\n\tAxiom eq_Z_2 : forall m1 m2 n1 n2 : nat, \n\t\tsubt m1 m2 = subt n1 n2 -> add m1 n2 = add n1 m2. *)\n\t\n\tDefinition inj (n: nat) : Z := subt n O.\n\t\n\tDefinition neg (m:Z) :=\n\t\tmatch m with\n\t\t|subt m1 m2 => subt m2 m1\n\tend.\n\t\n(* \tDefinition add_Z (m n : Z) : Z :=\n\t\tmatch m with\n\t\t| subt m1 m2 => match n with\n\t\t\t|subt n1 n2 => subt (add m1 n1) (add m2 n2)\n\t\tend\n\tend.\n *)\t\n\tDefinition add_Z (m n : Z) : Z :=\n\t\tmatch m,n with\n\t\t|subt m1 m2, subt n1 n2 => subt (add m1 n1) (add m2 n2)\n\tend.\n\t\n\tDefinition subt_Z (m n: Z) : Z :=\n\t\tadd_Z m (neg n).\n\t\t\n\tProposition injection : forall m n:nat, inj m = inj n -> m = n.\n\tProof.\n\t\tunfold inj.\n\t\tintros m n p.\n \t\trewrite <- (addzero m). rewrite <- (addzero n).\n\t\tapply eq_Z_2.\n\t\tassumption.\n\tDefined.\n\t\n\t(*Abelian group axioms*)\n\tLemma add_Z_associative : forall l m n : Z, \n\t\tadd_Z (add_Z l m) n = add_Z l (add_Z m n).\n\tProof.\n\t\tinduction l.\n\t\tinduction m.\n\t\tinduction n.\n\t\tunfold add_Z.\n\t\trewrite add_associative. rewrite add_associative. reflexivity.\n\tDefined.\n\t\n\tLemma add_Z_commutative : forall m n : Z,\n\t\tadd_Z m n = add_Z n m.\n\t\tinduction m.\n\t\tinduction n.\n\t\tsimpl.\n\t\trewrite (add_commutative n2 n0). rewrite (add_commutative n3 n1). reflexivity.\n\tDefined.\n\t\t\n\tDefinition O_Z := subt O O.\n\t\n\tLemma addzero_Z : forall n : Z, add_Z n O_Z = n.\n\tProof.\n\t\tinduction n.\n\t\tunfold O_Z.\n\t\tunfold add_Z.\n\t\trewrite addzero. rewrite addzero. reflexivity.\n\tDefined.\n\tLemma zeroadd_Z : forall n : Z, add_Z O_Z n = n.\n\t\tinduction n.\n\t\tunfold O_Z.\n\t\tunfold add_Z.\n\t\trewrite zeroadd. rewrite zeroadd. reflexivity.\n\tDefined.\n\t\n\tLemma inverse_neg : forall n : Z, add_Z n (neg n) = O_Z /\\ add_Z (neg n) n = O_Z.\n\tProof.\n\t\tinduction n.\n\t\tunfold neg.\n\t\tunfold add_Z.\n\t\tunfold O_Z.\n\t\tsplit.\n\t\t*apply eq_Z_1.\n\t\trewrite addzero. rewrite zeroadd. \n\t\tapply add_commutative.\n\t\t*apply eq_Z_1.\n\t\trewrite addzero. rewrite zeroadd. \n\t\tapply add_commutative.\n\tDefined.\n\t\n\tProposition Z_abelian : isAbelian_Group Z add_Z O_Z.\n\t\tunfold isAbelian_Group.\n\t\t\n\t\tsplit.\n\t\t(*Associativity*) *\n\t\t\tunfold associative. apply add_Z_associative.\n\t\t* split.\n\t\t(*Neutral element*) **\n\t\t\tunfold neutral. intro n. split.\n\t\t\t\t***apply zeroadd_Z. ***apply addzero_Z.\n\t\t** split.\n\t\t(*Exists inverse*) ***\n\t\t\tunfold exists_inverse.\n\t\t\t\tintro n.\n\t\t\t\texists (neg n). apply inverse_neg.\n\t\t(*Commutativity*) ***\n\t\t\tunfold commutative.\n\t\t\tapply add_Z_commutative.\n\tDefined.\n\nEnd Integers.\n\nSection Problem.\n\tDefinition f (n : Z) : nat :=\n\t\tmatch n with\n\t\t\tsubt n1 n2 => n1\n\t\tend.\n\t\n\tLemma eq1 : subt 1 1 = subt 0 0.\n\t\tapply eq_Z_1. reflexivity.\n\tQed.\n\t\n\tTheorem wrong : 1=0.\n\t\tapply ((ap f) eq1).\n\tQed.", "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/misc/Integers_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7852096666609903}}
{"text": "Require Import Unicode.Utf8.\nRequire Import Game.Mynat.Definition.\nRequire Import Game.Mynat.Add.\n\n(* Level 1 *)\n(* `induction a`: induction on term `a` *)\n\nLemma zero_add (a : mynat) : 0 + a = a.\nProof.\n  induction a.\n  rewrite add_zero.\n  reflexivity.\n  rewrite add_succ.\n  rewrite IHa.\n  reflexivity.\nQed.\n\n(* Level 2 *)\n\nLemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c).\nProof.\n  induction c.\n  rewrite add_zero.\n  rewrite add_zero.\n  reflexivity.\n  rewrite add_succ.\n  rewrite IHc.\n  rewrite add_succ.\n  rewrite add_succ.\n  reflexivity.\nQed.\n\n(* Level 3 *)\n\nLemma succ_add (a b : mynat) : succ a + b = succ (a + b).\nProof.\n  induction b.\n  rewrite add_zero.\n  rewrite add_zero.\n  reflexivity.\n  rewrite add_succ.\n  rewrite IHb.\n  rewrite add_succ.\n  reflexivity.\nQed.\n\n(* Level 4 *)\n\nLemma add_comm (a b : mynat) : a + b = b + a.\nProof.\n  induction b.\n  rewrite add_zero.\n  rewrite zero_add.\n  reflexivity.\n  rewrite add_succ.\n  rewrite IHb.\n  rewrite succ_add.\n  reflexivity.\nQed.\n\n(* Level 5 *)\n\nTheorem succ_eq_add_one (n : mynat) : succ n = n + 1.\nProof.\n  rewrite one_eq_succ_zero.\n  rewrite add_succ.\n  rewrite add_zero.\n  reflexivity.\nQed.\n\n(* Level 6 *)\n(* `rewrite (f x)`: Substitute `f` with bindings `x` *)\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  rewrite add_assoc.\n  reflexivity.\nQed.\n", "meta": {"author": "uncomputable", "repo": "natural-number-game", "sha": "602e06e352f1accb13ef1a1a23f40c19d10c5444", "save_path": "github-repos/coq/uncomputable-natural-number-game", "path": "github-repos/coq/uncomputable-natural-number-game/natural-number-game-602e06e352f1accb13ef1a1a23f40c19d10c5444/Game/World/Addition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.785209175304555}}
{"text": "From Coq Require Import List. Import ListNotations.\nFrom Coq Require Import ZArith.\n\nInductive even : nat -> Prop :=\n  | even_0 : even 0\n  | even_SS (n : nat) (H : even n) : even (S (S n)).\n\nTheorem plus_2_even_inv : forall n: nat, \n  even (S (S n)) -> even n.\nProof.\n  intros n H. inversion H as [ | ns IHn Eq ]. apply IHn.\nQed.\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 :\n      forall (z1 z2: Z) (l: list Z),\n        z1 <= z2 ->\n        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\nTheorem sorted_inv: forall (z : Z) (l : list Z), \n  sorted (z :: l) -> sorted l.\nProof.\n  intros.\n  inversion H as [ | | z1 z2 L Cond Heq ].\n  - apply sorted0.\n  - apply Heq.\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/Inversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7851028690482769}}
{"text": "Require Export P01.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof. \n  intros n m p. induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. 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/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.785026472529481}}
{"text": "Record Category5 : Type := category5\n    { Obj5          : Type\n    ; Hom5          : Obj5 -> Obj5 -> Type\n    ; compose5      : forall (a b c:Obj5), Hom5 a b -> Hom5 b c -> Hom5 a c\n    ; id5           : forall (a:Obj5), Hom5 a a\n    ; proof_idl5    : forall (a b:Obj5)(f:Hom5 a b), compose5 _ _ _ (id5 a) f = f\n    ; proof_idr5    : forall (a b:Obj5)(f:Hom5 a b), compose5 _ _ _ f (id5 b) = f\n    ; proof_asc5    : forall (a b c d:Obj5)(f:Hom5 a b)(g:Hom5 b c)(h:Hom5 c d),\n        compose5 _ _ _ (compose5 _ _ _ f g) h = \n        compose5 _ _ _ f (compose5 _ _ _ g h)\n    }\n    .\n\nDefinition Obj (C:Category5) : Type := Obj5 C.\nDefinition Hom (C:Category5)(a b:Obj C) : Type := Hom5 C a b.\n\nArguments Hom {C} _ _.\n\nDefinition compose(C:Category5)(a b c:Obj C)(f:Hom a b)(g:Hom b c) : Hom a c :=\n    compose5 C _ _ _ f g.\n\nArguments compose {C} {a} {b} {c} _ _.\n\nDefinition id (C:Category5) (a:Obj C) : Hom a a := id5 C a.\n\nArguments id {C} _.\n\n\nNotation \"f ; g\" := (compose f g) (at level 40, left associativity). \n\nTheorem id_left : forall (C:Category5) (a b:Obj C) (f: Hom a b), id a ; f = f.\nProof. intros C a b f. apply proof_idl5. Qed.\n\nTheorem id_right : forall (C:Category5) (a b:Obj C) (f: Hom a b), f ; id b = f.\nProof. intros C a b f. apply proof_idr5. Qed.\n\nTheorem compose_assoc : forall (C:Category5) (a b c d:Obj C),\n    forall (f:Hom a b) (g:Hom b c) (h: Hom c d), \n        (f ; g) ; h = f ; (g ; h).\nProof. intros C a b c d f g h. apply proof_asc5. Qed.\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/Category5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7849631012825052}}
{"text": "Require Import List. Import ListNotations.\nRequire Import Coq.ZArith.BinInt. (* Z *)\nRequire Import XorCorrespondence. (* Blist *)\nRequire Import Integers.          (* byte *)\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import HMAC_functional_prog_Z.\n\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Program.Tactics.\nRequire Import Bruteforce.\n\nOpen Scope Z_scope.\n\n(* ----- Inductive *)\n\n(* In XorCorrespondence *)\n(* Definition asZ (x : bool) : Z := if x then 1 else 0. *)\n\n(*\nDefinition convertByteBits (bits : Blist) (byte : Z) : Prop :=\n  exists (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n   bits = [b0; b1; b2; b3; b4; b5; b6; b7] /\\\n   byte =  (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\nInductive bytes_bits_lists : Blist -> list Z -> Prop :=\n  | eq_empty : bytes_bits_lists nil nil\n  | eq_cons : forall (bits : Blist) (bytes : list Z)\n                     (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (byte : Z),\n                bytes_bits_lists bits bytes ->\n                convertByteBits [b0; b1; b2; b3; b4; b5; b6; b7] byte ->\n                bytes_bits_lists (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: bits)\n                                 (byte :: bytes).\n\n(* ----- Computational *)\n\n(* TODO: assumes Z is positive and in range, does not use Z.positive *)\n\nDefinition div_mod (num : Z) (denom : Z) : bool * Z :=\n  (Z.gtb (num / denom) 0, num mod denom).\n\nEval compute in div_mod 129 128.\nEval compute in div_mod 1 64.\n\nDefinition byteToBits (byte : Z) : Blist :=\n  let (b7, rem7) := div_mod byte 128 in\n  let (b6, rem6) := div_mod rem7 64 in\n  let (b5, rem5) := div_mod rem6 32 in\n  let (b4, rem4) := div_mod rem5 16 in\n  let (b3, rem3) := div_mod rem4 8 in\n  let (b2, rem2) := div_mod rem3 4 in\n  let (b1, rem1) := div_mod rem2 2 in\n  let (b0, rem0) := div_mod rem1 1 in\n  [b0; b1; b2; b3; b4; b5; b6; b7].\n\nFixpoint bytesToBits (bytes : list Z) : Blist :=\n  match bytes with\n    | [] => []\n    | byte :: xs => byteToBits byte ++ bytesToBits xs\n  end.\n\nDefinition bitsToByte (bits : Blist) : Z :=\n  match bits with\n    | b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: nil =>\n      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    | _ => -1                   (* should not happen *)\n  end.\n\nFixpoint bitsToBytes (bits : Blist) : list Z :=\n  match bits with\n    | b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: xs =>\n      bitsToByte [b0; b1; b2; b3; b4; b5; b6; b7] :: bitsToBytes xs\n    | _ => []\n  end.\n\n(* -------------------- Various theorems and lemmas *)\n\nLemma bytes_bits_length : forall (bits : Blist) (bytes : list Z),\n  bytes_bits_lists bits bytes -> length bits = (length bytes * 8)%nat.\nProof.\n  intros bits bytes corr.\n  induction corr.\n  - reflexivity.\n  - simpl. repeat f_equal. apply IHcorr.\nQed.\n\nLemma bytesToBits_app : forall (l1 l2 : list Z),\n                          bytesToBits (l1 ++ l2) = bytesToBits l1 ++ bytesToBits l2.\nProof.\n  induction l1; intros.\n  * reflexivity.\n  *\n    simpl. rewrite -> IHl1. reflexivity.\nQed.    \n\nLemma bytesToBits_len : forall (l : list Z),\n                          length (bytesToBits l) = (length l * 8)%nat.\nProof.\n  induction l; intros; try reflexivity.\n  -\n    simpl.\n    rewrite -> IHl.\n    reflexivity.\nQed.    \n\n(* Prove by brute force (test all Z in range) *)\nTheorem byte_bit_byte_id : forall (byte : Z),\n                             0 <= byte < 256 ->\n                                bitsToByte (byteToBits byte) = byte.\nProof.\n  intros byte range.\n  do_range range reflexivity.\nQed.\n\nTheorem bits_byte_bits_id : forall (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n                              [b0; b1; b2; b3; b4; b5; b6; b7] =\n                              byteToBits (bitsToByte [b0; b1; b2; b3; b4; b5; b6; b7]).\nProof.\n  intros.\n  destruct b0; destruct b1; destruct b2; destruct b3;\n  destruct b4; destruct b5; destruct b6; destruct b7;\n  reflexivity.\nQed.\n\nTheorem bytes_bits_bytes_id : forall (bytes : list Z),\n                                Forall (fun b => 0 <= b < 256) bytes ->\n                                bitsToBytes (bytesToBits bytes) = bytes.\nProof.\n  intros range bytes.\n  induction bytes as [ | byte bytes].\n  - reflexivity.\n  -\n    unfold bytesToBits.\n    fold bytesToBits.\n    unfold byteToBits.\n    unfold bitsToBytes.\n    Opaque bitsToByte. Opaque bitsToBytes. Opaque bytesToBits.\n    simpl.\n    Transparent bitsToBytes. fold bitsToBytes.\n    rewrite -> IHbytes.\n    \n    Transparent bitsToByte.\n    unfold bitsToByte. f_equal.\n    apply byte_bit_byte_id.\n    \n    apply H. Transparent bytesToBits.\nQed.\n\nClose Scope string_scope.\n\n(* ------------------ Theorems relating inductive and computational definitions *)\n\nTheorem bytes_bits_def_eq : forall (bytes : list Z),\n                              Forall (fun b => 0 <= b < 256) bytes ->\n                              bytes_bits_lists (bytesToBits bytes) bytes.\nProof.\n  intros range bytes.\n  induction bytes as [ | byte bytes ].\n  -\n    simpl. apply eq_empty.\n  -\n    apply eq_cons.\n\n    *\n      apply IHbytes.\n    *\n      unfold convertByteBits.\n      do 8 eexists.\n      split.\n      +\n        reflexivity.\n      +\n        do_range H reflexivity.\nQed.\n\nTheorem bytes_bits_comp_ind : forall (bits : Blist) (bytes : list Z),\n                               Forall (fun b => 0 <= b < 256) bytes ->\n                               bits = bytesToBits bytes ->\n                               bytes_bits_lists bits bytes.\nProof.\n  intros bits bytes range corr.\n  rewrite -> corr.\n  apply bytes_bits_def_eq.\n  assumption.\nQed.\n\nTheorem bytes_bits_ind_comp : forall (bits : Blist) (bytes : list Z),\n                                 Forall (fun b => 0 <= b < 256) bytes ->\n                                 bytes_bits_lists bits bytes ->\n                                 bytes = bitsToBytes bits.\nProof.\n  intros bits bytes range corr.\n  induction corr.\n  - reflexivity.\n  -\n    rewrite -> IHcorr.\n    *\n      unfold convertByteBits in H.\n      unfold bitsToBytes.\n      fold bitsToBytes.\n      f_equal.\n\n      assert (range' : 0 <= byte < 256). admit.\n\n      unfold bitsToByte.\n      Print convertByteBits.\n      destruct_exists. destruct H7. inversion H7.\n      subst. reflexivity.\n\n      * admit.                  (* bytes in range *)\nQed.\n\nTheorem bits_bytes_ind_comp : forall (bits : Blist) (bytes : list Z),\n                                 Forall (fun b => 0 <= b < 256) bytes ->\n                                 bytes_bits_lists bits bytes ->\n                                 bits = bytesToBits bytes.\nProof.\n  intros bits bytes range corr.\n  induction corr.\n  - reflexivity.\n  -\n    unfold convertByteBits in H.\n    destruct_exists.\n    destruct H7.\n    inversion H7.\n    subst.\n    clear H7.\n    rewrite -> IHcorr.\n    unfold bytesToBits.\n    fold bytesToBits.\n    assert (list_8 : forall {A : Type} (e0 e1 e2 e3 e4 e5 e6 e7 : A) (l : list A),\n                       e0 :: e1 :: e2 :: e3 :: e4 :: e5 :: e6 :: e7 :: l =\n                       [e0; e1; e2; e3; e4; e5; e6; e7] ++ l).\n    reflexivity.\n    rewrite -> list_8.\n    f_equal.\n    apply bits_byte_bits_id.\n\n    admit.                      (* in range *)\nQed.\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/ByteBitRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.8757869803008765, "lm_q1q2_score": 0.7849252860941571}}
{"text": "Variables P Q R : Prop.\n\nTheorem one : (P /\\ ~ P) -> Q.\n\nProof.\n  intro pnpH.\n  destruct pnpH as [pH npH].\n  cut False.                        (* assume a contradiction *)\n  intro fH.\n  case fH.\n  apply npH.                    (* ~p <-> p -> False *)\n  exact pH.\nQed.\n\nTheorem C : (P -> Q -> R) -> (Q -> P -> R).\n\nProof.\n  intro pqrH.\n  intro qH.\n  intro pH.\n  apply pqrH.\n  exact pH.\n  exact qH.\nQed.\n\n(* simply use auto *)\n\nTheorem C1 : (P -> Q -> R) -> (Q -> P -> R).\n\nProof.\n  auto.\nQed.\n\nSection auto.\n  Variables P1 P2 P3 P4 P5 P6 : Prop.\n  \n  Theorem had : (P1 -> P2) -> (P2 -> P3) -> (P3 -> P4) -> (P4 -> P5) -> (P5 -> P6) -> (P1 -> P6).\n  Proof.\n    auto 6.\n  Qed.\n\n  (* suger *)\n  Goal (P1 \\/ P1) -> P1.\n  tauto.\n  Save p1.\n\n  Print p1.\nEnd auto.\n\nRequire Import Coq.Logic.Classical.\n\nPrint classic. (* Axiom tnd : P \\/ ~ P. *)\n\nTheorem nnpp : ~~ P -> P.\n\nProof.\n  cut (P \\/ ~P).\n  intro pnpH.\n  case pnpH.\n  intros pH nnpH.\n  exact pH.\n  intros npH nnpH.\n  unfold not in npH.\n  unfold not in nnpH.\n  contradict nnpH.              (* a small trick *)\n  exact npH.\n  apply classic.\nQed.", "meta": {"author": "zjhmale", "repo": "MFCS", "sha": "e82b0e2425b4988ce8dfc558901ae2e76e1b23f1", "save_path": "github-repos/coq/zjhmale-MFCS", "path": "github-repos/coq/zjhmale-MFCS/MFCS-e82b0e2425b4988ce8dfc558901ae2e76e1b23f1/classic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8688267864276107, "lm_q1q2_score": 0.7848061937617826}}
{"text": "From mathcomp\n  Require Import ssreflect ssrnat.\n\nHypothesis ExMidLaw : forall P : Prop, P \\/ ~P.\n\nLemma notnotEq (P : Prop) : ~ ~ P -> P.\nProof.\n  move=> HnotnotP.\n  - case: (ExMidLaw (~ P)).\n    + by move /HnotnotP.\n    + by case: (ExMidLaw P).\nQed.\n\n(* 問2.2 *)\nLemma ex2_2 : forall A B C : Prop, (A -> B) /\\ (B -> C) -> (A -> C).\nProof.\n  move=> A B C; case.\n  move=> Hyp1 Hyp2 Hyp3.\n  by apply: (Hyp2 (Hyp1 Hyp3)).\nQed.\n\n(* 問2.7 *)\nLemma ex2_7 (A B : Prop) : ~(A /\\ B) <-> (~A) \\/ (~B).\nProof.\n  apply: conj.\n  + move=> HnotAandB.\n    case: (ExMidLaw ((~A) \\/ (~B))).\n    + by [].\n    + case: (ExMidLaw A).\n      + move=> HA HnotnotAornotB.\n        case: (ExMidLaw B).\n        + move=> HB.\n          case: HnotAandB.\n          apply: conj.\n          by [].\n          by [].\n        + move=> HnotB.\n          right.\n          by [].\n      + move=> HnotA HnotnotAornotB.\n        left.\n        by [].\n  + move=> HnotAornotB HAandB.\n    case: HnotAornotB.\n    + case: HAandB.\n      by [].\n    + case: HAandB.\n      by [].\nQed.\n\n(* 問2.8 *)\nLemma ex2_8 (T : Type) (P : T -> Prop) : ~(forall x : T, P x) <-> (exists x : T, ~P x).\nProof.\n  apply: conj.\n  + move=> HnotforallPx.\n    apply: notnotEq.\n    move=> HnotexistsnotPx.\n    apply: HnotforallPx.\n    move=> x.\n    apply: notnotEq.\n    move=> HnotforallPx.\n    apply HnotexistsnotPx.\n    exists x.\n    by [].\n  + case.\n    move=> x HnotPx HnotforallPx.\n    apply: HnotPx.\n    move: x.\n    by [].\nQed.\n", "meta": {"author": "ishioka0222", "repo": "theorem-proving-in-coq", "sha": "a67e7e5cfa837cefa776c0ec76f26152e80a6c39", "save_path": "github-repos/coq/ishioka0222-theorem-proving-in-coq", "path": "github-repos/coq/ishioka0222-theorem-proving-in-coq/theorem-proving-in-coq-a67e7e5cfa837cefa776c0ec76f26152e80a6c39/src/萩原学, アフェルト・レナルド (2018) Coq_SSReflect_MathCompによる定理証明/chap2-ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8577681122619885, "lm_q1q2_score": 0.7847728571098141}}
{"text": "Require Export BinPos.\n\nFixpoint Pshift (n:nat) (x:positive) {struct n} : positive :=\nmatch n with \n| O => x\n| (S m) => xO (Pshift m x)\nend.\n\nDefinition Pow2 (n:nat) := Pshift n 1.\n\nLocal Open Scope positive_scope.\n\nLemma Pshift1 : forall x y n, (Pshift n x)*y=(Pshift n (x*y)).\nProof.\ninduction n;\nsimpl;\ncongruence.\nQed.\n\nLemma Pshift2 : forall x n m, (Pshift n (Pshift m x))=(Pshift (n+m) x).\nProof.\ninduction n;\nsimpl;\nintros;\ntry rewrite IHn;\nreflexivity.\nQed.\n\nLemma Pshift3 : forall x y n, (Pshift n x)+(Pshift n y)=(Pshift n (x+y)).\nProof.\ninduction n;\nsimpl;\ncongruence.\nQed.\n\nLemma PshiftExpand : forall x n, (Pshift n x)= (Pow2 n)*x.\nProof.\nintros.\nunfold Pow2.\nrewrite Pshift1.\nreflexivity.\nQed.\n\nHint Rewrite PshiftExpand : PshiftExpand.\nHint Rewrite <- Pshift2 : PshiftExpand.\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/Pshift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7847728550914371}}
{"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\n\nLemma lem: forall m n, plus (succ m) n = plus m (succ n).\nProof.\nintros. simpl. induction m.\n  - simpl. rewrite IHm. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Nat), eq (half (plus x x)) x.\nProof.\ninduction x.\n  - simpl. destruct x.\n    * simpl. rewrite <- lem. rewrite IHx. reflexivity.\n    * reflexivity.\n  - 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/goal13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7847460210488175}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Ascii.\nImport ListNotations.\nRequire Import Omega.\n\nRequire Import StructTact.StructTactics.\nRequire Import oeuf.StuartTact.\nRequire Import Recdef.\n\n\n(* \"String to nat\" conversion, for use as a spec.\n\n   The \"strings\" throughout this module are actually lists of nats, where each\n   nat is a single digit 0-9.  They're stored little-endian, so `123` is\n   represented as the list `[3; 2; 1]`.\n *)\nFixpoint s2n' (s : list nat) (pow : nat) : nat :=\n    match s with\n    | [] => 0\n    | n :: s' => pow * n + s2n' s' (pow * 10)\n    end.\n\nDefinition s2n s := s2n' s 1.\n\n\n\n(* Implementation *)\n\n(* `inc` uses a modified little-endian representation, where each digit `n` is\n   instead represented by `9 - n`.  This lets us use normal pattern matching\n   instead of `eq_nat_dec` inside `inc`.\n\n   Examples:\n   \n   \"0\" = [9]\n   \"1\" = [8]\n   \"9\" = [0]\n   \"10\" = [9, 8]\n   \"19\" = [0, 8]\n   \"20\" = [9, 7]\n   \"123\" = [6, 7, 8]\n*)\n\nFixpoint inc s :=\n    match s with\n    | [] => [8]\n    | 0 :: s' => 9 :: inc s'\n    | S n' :: s' => n' :: s'\n    end.\n\n(* `fixup` converts a modified little-endian digit string to a normal one. *)\nDefinition fixup' n := 9 - n.\nDefinition fixup s := map fixup' s.\n\nFixpoint n2s' n s :=\n    match n with\n    | 0 => s\n    | S n' => n2s' n' (inc s)\n    end.\n\nDefinition n2s n := fixup (n2s' n []).\n\n\n\n(* Main correctness proofs:\n    (1) `s2n (n2s n) = n`\n    (2) Forall (fun n => n <= 9) (n2s n)\n *)\n\nLemma s2n'_pow : forall s pow,\n    s2n' s pow = pow * s2n s.\ninduction s; intros; unfold s2n in *; simpl in *.\n{ omega. }\nrewrite IHs. rewrite IHs with (pow := 10).\nring.\nQed.\n\n(* We need this property for some of the proofs. *)\nDefinition digits_ok s := Forall (fun n => n <= 9) s.\n\nLemma inc_digits_ok : forall s,\n    digits_ok s -> digits_ok (inc s).\ninduction s; intros0 Hok.\n{ simpl. constructor; [ omega | constructor ]. }\n\nsimpl. break_match.\n- invc Hok. constructor; eauto. eapply IHs; eauto.\n- invc Hok. constructor; eauto. omega.\nQed.\n\n(* fixup + s2n = fs2n *)\nDefinition fs2n s := s2n (fixup s).\n\nLemma inc_s2n : forall s, digits_ok s -> fs2n (inc s) = S (fs2n s).\ninduction s; intros0 Hok; simpl.\n{ reflexivity. }\n\nbreak_match.\n\n- unfold fs2n, fixup, s2n in *. simpl in *.\n  do 2 rewrite s2n'_pow.\n  unfold s2n. rewrite IHs by (invc Hok; auto).\n  ring.\n\n- unfold fs2n, fixup, s2n in *. simpl in *.\n  cut (fixup' n = S (fixup' (S n))). { intro. omega. }\n  unfold fixup'. invc Hok. omega.\nQed.\n\nLemma n2s'_fs2n : forall n s, digits_ok s -> fs2n (n2s' n s) = n + fs2n s.\ninduction n; intros; simpl.\n- reflexivity.\n- rewrite IHn, inc_s2n; eauto.\n  eapply inc_digits_ok; eauto.\nQed.\n\n(* Main proof #1 *)\nLemma n2s_s2n : forall n, s2n (n2s n) = n.\nintros.\nunfold n2s. change (s2n (fixup ?x)) with (fs2n x).\nrewrite n2s'_fs2n; eauto.\nconstructor.\nQed.\n\nLemma n2s'_digits_ok : forall n s, digits_ok s -> digits_ok (n2s' n s).\ninduction n; intros; simpl; auto using inc_digits_ok.\nQed.\n\nLemma fixup_digits_ok : forall s, digits_ok s -> digits_ok (fixup s).\ninduction s; intros0 Hok; simpl.\n- constructor.\n- invc Hok. constructor; eauto.\n  + unfold fixup'. omega.\n  + eapply IHs. eauto.\nQed.\n\n(* Main proof #2 *)\nLemma n2s_digits_ok : forall n, digits_ok (n2s n).\nintros. eapply fixup_digits_ok. eapply n2s'_digits_ok. constructor.\nQed.\n\n\n\n(* Elim version *)\n\nDefinition inc_elim s :=\n    list_rect (fun _ => list nat)\n        [8]\n        (fun n s' IHs =>\n            nat_rect (fun _ => list nat)\n                (9 :: IHs)\n                (fun n' IHn => n' :: s')\n                n)\n        s.\n\nDefinition n2s_elim' n :=\n    nat_rect (fun _ => list nat -> list nat)\n        (fun s => s)\n        (fun n' IHn s => IHn (inc_elim s))\n        n.\n\nDefinition nat_sub_elim x y :=\n    nat_rect (fun _ => nat -> nat)\n        (fun y => 0)\n        (fun x' IHx y =>\n            nat_rect (fun _ => nat)\n                (S x')\n                (fun y' IHy => IHx y')\n                y)\n        x y.\n\nDefinition fixup'_elim n := nat_sub_elim 9 n.\n\nDefinition list_map_elim {A B} (f : A -> B) xs :=\n    list_rect (fun _ => list B)\n        []\n        (fun x xs IHxs => f x :: IHxs)\n        xs.\n\nDefinition fixup_elim s := list_map_elim fixup'_elim s.\n\nDefinition n2s_elim n :=\n    fixup_elim (n2s_elim' n []).\n\n\n\n(* Elim version equivalence proofs *)\n\nLemma inc_elim_eq : forall s, inc_elim s = inc s.\ninduction s; simpl.\n{ reflexivity. }\nbreak_match; simpl.\n- congruence.\n- reflexivity.\nQed.\n\nLemma n2s_elim'_eq : forall n s, n2s_elim' n s = n2s' n s.\ninduction n; intros; simpl.\n- reflexivity.\n- rewrite inc_elim_eq. eapply IHn.\nQed.\n\nLemma nat_sub_elim_eq : forall x y, nat_sub_elim x y = Nat.sub x y.\ninduction x; destruct y; simpl; try reflexivity.\nrewrite <- IHx. reflexivity.\nQed.\n\nLemma fixup'_elim_eq : forall n, fixup'_elim n = fixup' n.\nintros. unfold fixup'_elim, fixup'. eapply nat_sub_elim_eq.\nQed.\n\nLemma list_map_elim_eq : forall A B (f f' : A -> B) xs,\n    (forall x, f x = f' x) ->\n    list_map_elim f xs = List.map f' xs.\ninduction xs; intros; simpl.\n- reflexivity.\n- f_equal; eauto.\nQed.\n\nLemma fixup_elim_eq : forall s, fixup_elim s = fixup s.\nintros. eapply list_map_elim_eq.\nintros. eapply fixup'_elim_eq.\nQed.\n\nLemma n2s_elim_eq : forall n, n2s_elim n = n2s n.\nintros. unfold n2s_elim, n2s.\nrewrite n2s_elim'_eq, fixup_elim_eq.\nreflexivity.\nQed.\n\n\n\n(* Digit to string conversion *)\n\nDefinition digit_char n :=\n    match n with\n    | 0 => \"0\"%char\n    | 1 => \"1\"%char\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    | 8 => \"8\"%char\n    | 9 => \"9\"%char\n    | _ => \"?\"%char\n    end.\n\nDefinition string_of_nat n := map digit_char (rev (n2s n)).\nEval compute in string_of_nat 123.\n\n\n\n(* Digit to string with eliminators *)\n\nDefinition digit_char_elim n :=\n    nat_rect (fun _ => ascii) \"0\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"1\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"2\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"3\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"4\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"5\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"6\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"7\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"8\"%char (fun n _ =>\n    nat_rect (fun _ => ascii) \"9\"%char (fun n _ =>\n        \"?\"%char) n) n) n) n) n) n) n) n) n) n.\n\n(* Reimplementations of List.rev in a more Oeuf-friendly style *)\nFixpoint list_rev' {A} xs acc : list A :=\n    match xs with\n    | [] => acc\n    | x :: xs => list_rev' xs (x :: acc)\n    end.\n\nDefinition list_rev {A} xs : list A := list_rev' xs [].\n\n(* Eliminator implementations of list_rev *)\nDefinition list_rev'_elim {A} xs acc :=\n    list_rect (fun _ => list A -> list A)\n        (fun acc => acc)\n        (fun x xs IHxs acc => IHxs (x :: acc))\n        xs acc.\n\nDefinition list_rev_elim {A} xs : list A := list_rev'_elim xs [].\n\nDefinition string_of_nat_elim n :=\n    list_map_elim digit_char_elim (list_rev_elim (n2s_elim n)).\n\n\n\n(* Proofs *)\n\nLemma digit_char_elim_eq : forall n, digit_char_elim n = digit_char n.\ndo 10 (destruct n; simpl; [reflexivity|]).\nreflexivity.\nQed.\n\nLemma list_rev'_eq : forall A (xs acc : list A),\n    list_rev' xs acc = List.rev xs ++ acc.\ninduction xs; intros; simpl.\n- reflexivity.\n- rewrite IHxs. rewrite <- app_assoc. reflexivity.\nQed.\n\nLemma list_rev_eq : forall A (xs : list A), list_rev xs = List.rev xs.\nintros. unfold list_rev. rewrite list_rev'_eq. rewrite app_nil_r. reflexivity.\nQed.\n\nLemma list_rev'_elim_eq : forall A (xs acc : list A),\n    list_rev'_elim xs acc = list_rev' xs acc.\ninduction xs; intros; simpl.\n- reflexivity.\n- rewrite IHxs. reflexivity.\nQed.\n\nLemma list_rev_elim_eq : forall A (xs : list A),\n    list_rev_elim xs = list_rev xs.\nintros. eapply list_rev'_elim_eq.\nQed.\n\nLemma string_of_nat_elim_eq : forall n, string_of_nat_elim n = string_of_nat n.\nintros. unfold string_of_nat_elim, string_of_nat.\nrewrite n2s_elim_eq. rewrite list_rev_elim_eq.  rewrite list_rev_eq.\neapply list_map_elim_eq. eapply digit_char_elim_eq.\nQed.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/demos/word_freq/src/string_of_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.7846550196811637}}
{"text": "(* exercise 8.5 *)\n(****************)\n\nRequire Export List.\nRequire Export Arith.\n(* In our exercises we consider strings with only opeing 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.\n apply wp_concat.\n trivial.\n apply wp_encapsulate.\n trivial.\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\nEval compute in (bin_to_string (N (N L L) L)).\nEval compute in (bin_to_string (N (N L L) (N L L))).\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.\n simpl.\n rewrite app_ass.\n rewrite Hr1.\n simpl.\n rewrite Hr2.\n reflexivity.\n reflexivity.\n intro l; 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.\n 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(* 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.\n simpl.\n rewrite app_ass.\n simpl.\n apply wp'_cons; auto.\nQed.\n\nHint Resolve wp'_nil wp'_cons wp'_concat.\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.\n 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(* 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); rewrite recognize_complete_aux; auto.\nQed.\n\n(* solution of exercise 8.22 *)\nTheorem app_decompose :\n forall (A:Set) (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''; exists l2'; split; auto.\n rewrite Heq''; rewrite Heq3; auto.\nQed.\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:Set) (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:Set) (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 \nTheorem cons_to_app_end :\n forall (A:Set) (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 (cons a l)) but we\n  need to say that this list has at least one element. *)\n cut (0 < length (rev (a :: l))).\n case (rev (a :: l)).\n (* If (rev (cons a l)) was nil, then there would be a contradiction. *)\n simpl ; intros H'; elim (lt_n_O 0); auto.\n intros b l'; exists b; exists (rev l'); simpl ; auto.\n (* Now we need to show that the reversed list has more than one element *)\n rewrite <- length_rev; simpl ; auto with arith.\nQed.\n \n\nTheorem last_same :\n forall (A:Set) (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 cut (a :: rev l1 = b :: rev l2).\n intros H'; injection H'; intros H1 H2; split; auto.\n rewrite <- (rev_involutive l1).\n rewrite H1.\n apply rev_involutive.\n repeat rewrite <- rev_unit.\n rewrite H; auto.\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 (* 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 intros l1 l2 H1; elim (app_eq_nil _ _ H1); auto.\n simpl in |- *; intros Heq1 Heq2; rewrite Heq1; rewrite Heq2; apply wp_oc.\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]].\n rewrite Heq1.\n rewrite 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(* In the third case, we haev 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'.\n elim (cons_to_app_end par l2' c').\n intros c'' [l2'' Heq]; rewrite Heq.\n rewrite ass_app; intros Heq1.\n injection Heq1; intros Heq2 Heq3.\n 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:Set) (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:Set) (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.\n rewrite make_list_end.\n apply wp_remove_oc.\n 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).\n simpl; auto.\nQed.\n\n(* Now we want to write a real parser, that is, a function that constructs a term\n  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 .\n 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.\n 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.\n replace l with (l ++ nil).\n red in |- *; intros H'.\n cut (parse nil L nil = None).\n simpl; discriminate.\n apply parse_complete_aux with (2 := H'); auto.\n apply wp_imp_wp'; auto.\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.\n rewrite Hrec with (1 := H).\n simpl.\n repeat (rewrite app_ass; simpl).\n 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.\n repeat (rewrite app_ass; simpl).\n 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": "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/parsing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.7846550130564155}}
{"text": "Inductive expr : Type :=\n | Int : nat -> expr\n | Add : expr -> expr -> expr\n | Mul : expr -> expr -> expr.\n\n(* Fixpoint = let rec *)\nFixpoint eval (e:expr) : nat := \nmatch e with\n| Int x => x\n| Add e1 e2 => (eval e1) + (eval e2)\n| Mul e1 e2 => (eval e1) * (eval e2)\nend.\n\n(* Calcul 3+4 *)\nCompute (eval (Add (Int 3) (Int 4))).\n\n(* 1 + 1 = 2 *)\nLemma onePlusone : (eval (Add (Int 1) (Int 1))) = 2.\nProof.\n    simpl.\n    reflexivity. \nQed.\n\n(* x + 0 = x*)\n(* Preuve sur les entiers naturel (type de Coq) *)\nLemma nPlusZero : forall n, n = n+0.\nProof.\n    intro n.\n    induction n.\n    - simpl. reflexivity.\n    - simpl. rewrite <- IHn. reflexivity. Qed.\n\n(* Preuve sur notre système d'expression *)\nLemma xPlusZero : forall n, (eval (Add (Int n) (Int 0))) = n.\nProof.\n    intro n.\n    induction n.\n    - simpl. reflexivity.\n    - rewrite <- IHn. simpl. rewrite <- nPlusZero. reflexivity. Qed.\n\n\nLemma xPlusB : forall a b, a+b = b+a.\nProof.\n    intros a b.\n    induction a.\n    - simpl. rewrite <- nPlusZero. reflexivity.\n    - simpl. \n(* Assert = preuve auxiliaire *)\nassert (forall x y, S (x+y) = x + S y) as H_assert.\n{ intros x y.\n  induction x.\n  - simpl. reflexivity.\n  - simpl. rewrite IHx. reflexivity. }\n  rewrite IHa. rewrite H_assert. reflexivity. \nQed.", "meta": {"author": "staceb", "repo": "rebasing", "sha": "9fa227fcc169d32493c2f0440320ead8b9d8bf85", "save_path": "github-repos/coq/staceb-rebasing", "path": "github-repos/coq/staceb-rebasing/rebasing-9fa227fcc169d32493c2f0440320ead8b9d8bf85/Arithmetic-proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.784643359767548}}
{"text": "Require Import \n  Arith\n  List\n  Omega\n  Orders\n  Recdef\n  Relations\n  Permutation \n  Setoid\n  Sorted.\n\nSet Implicit Arguments.\n\nModule Type InsertionSort(Import X:Orders.TotalLeBool).\n\n  Fixpoint Insertion(n : X.t)(l : list X.t) := \n    match l with\n    | nil => n :: nil\n    | l_head :: l_tail => \n        match X.leb n l_head with\n        | true => n :: l_head ::l_tail\n        | false => l_head :: Insertion n l_tail\n        end\n    end.\n\n  Fixpoint InsertionSort(l : list X.t) : list X.t :=\n    match l with\n    | nil => nil\n    | l_head :: l_tail => Insertion l_head (InsertionSort l_tail)\n    end.\n\n  Theorem InsertionLength : forall n l, length(Insertion n l) = S (length l).\n    intro.\n    induction l.\n    trivial.\n    simpl in *.\n    destruct (leb n a).\n    trivial.\n    intuition.\n    simpl in *.\n    auto.\n  Qed.\n\n  Theorem InsertionSortSameLength : forall l, length (InsertionSort l) = length l.\n    intros.\n    induction l.\n    trivial.\n    simpl in *.\n    rewrite InsertionLength.\n    auto.\n  Qed.\n\n  Theorem InsertionPermutationSelf : forall n l, \n    Permutation (n :: l) (Insertion n l).\n    intros.\n    induction l.\n    trivial.\n    simpl in *.\n    case (leb n a).\n    trivial.\n    intros.\n    assert(Permutation (n :: a :: l) (a :: n :: l)).\n    constructor.\n    apply(perm_trans H).\n    auto.\n  Qed.\n\n  Theorem InsertionPermutation : \n    forall n l r, Permutation l r -> Permutation (n :: l) (Insertion n r).\n    induction 1.\n    trivial.\n    simpl in *.\n    case(leb n x).\n    auto.\n    intros.\n    assert (Permutation (n :: x :: l) (x :: n :: l)) as T.\n    constructor.\n    apply(perm_trans T).\n    auto.\n    simpl in *.\n    case(leb n x),(leb n y).\n    constructor.\n    constructor.\n    constructor.\n    constructor.\n    assert (Permutation (n :: y :: x :: l) (n :: x :: y :: l)) as T.\n    constructor.\n    constructor.\n    apply(perm_trans T).\n    constructor.\n    assert(Permutation (n :: y :: x :: l) (x :: y :: n :: l)) as T.\n    assert(Permutation (n :: y :: x :: l) (x :: n :: y :: l)) as T.\n    assert(Permutation (n :: y :: x :: l) (n :: x :: y :: l)) as T.\n    constructor.\n    constructor.\n    apply(perm_trans T).\n    constructor.\n    apply(perm_trans T).\n    constructor.\n    constructor.\n    apply(perm_trans T).\n    constructor.\n    constructor.\n    apply InsertionPermutationSelf.\n    assert (Permutation (n :: l) (n :: l')) as T.\n    auto.\n    apply(perm_trans T).\n    trivial.\n  Qed.\n\n  Theorem InsertionSortPermutation : forall l, Permutation l (InsertionSort l).\n    induction l.\n    trivial.\n    inversion IHl.\n    trivial.\n    subst.\n    simpl in *.\n    apply InsertionPermutation.\n    trivial.\n    subst.\n    simpl in *.\n    apply InsertionPermutation.\n    trivial.\n    subst.\n    simpl in *.\n    apply InsertionPermutation.\n    trivial.\n  Qed.\n\n  Theorem InsertionSortNil : forall l, InsertionSort l = nil -> l = nil.\n    intros.\n    destruct l.\n    trivial.\n    simpl in *.\n    remember(InsertionSort l).\n    destruct l0.\n    simpl in *.\n    inversion H.\n    simpl in *.\n    destruct (leb t0 t1).\n    inversion H.\n    inversion H.\n  Qed.\n\n  Definition Sorted := Sorted (fun l r => is_true(X.leb l r)).\n\n  Theorem SortedCons : forall e l, \n    Sorted (e :: l) -> \n      Sorted l.\n    intros.\n    induction l.\n    constructor.\n    inversion H.\n    trivial.\n  Qed.\n\n  Theorem InsertionSorted : forall e l, \n    Sorted l -> \n      Sorted (Insertion e l).\n    intros.\n    induction l.\n    simpl in *.\n    constructor.\n    auto.\n    trivial.\n    simpl in *.\n    remember (X.leb e a).\n    destruct b.\n    constructor.\n    trivial.\n    auto.\n    constructor.\n    apply IHl.\n    eapply SortedCons.\n    eauto.\n    induction l.\n    simpl in *.\n    constructor.\n    case(X.leb_total a e).\n    trivial.\n    subst.\n    eauto with *.\n    simpl in *.\n    remember (X.leb e a0).\n    destruct b.\n    constructor.\n    case(X.leb_total a e).\n    trivial.\n    eauto with *.\n    constructor.\n    inversion H.\n    subst.\n    inversion H3.\n    trivial.\n  Qed.\n\n  Theorem InsertionSortSorted : forall l, Sorted (InsertionSort l).\n    induction l.\n    simpl in *.\n    constructor.\n    simpl in *.\n    apply InsertionSorted.\n    trivial.\n  Qed.\n\nEnd InsertionSort.", "meta": {"author": "MarisaKirisame", "repo": "Coq_code", "sha": "b2b96d4be269781d1249fc5191fb590de671ef28", "save_path": "github-repos/coq/MarisaKirisame-Coq_code", "path": "github-repos/coq/MarisaKirisame-Coq_code/Coq_code-b2b96d4be269781d1249fc5191fb590de671ef28/Introduction_To_algorithms/InsertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7845566801990289}}
{"text": "Require Export aula3 aula4.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n.\n  simpl. \nAbort.\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  - (* n = 0 *)\n    reflexivity. \n  - (* n = S n' *)\n    simpl.\nAbort.\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl.  rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n.\n  induction n as [ | n' IHn'].\n  - simpl. reflexivity.\n  - simpl. assumption.\nQed.\n", "meta": {"author": "AndressaUmetsu", "repo": "coqExercicios", "sha": "f583bea6a32ef359cbddb786f7fb71803d7bf189", "save_path": "github-repos/coq/AndressaUmetsu-coqExercicios", "path": "github-repos/coq/AndressaUmetsu-coqExercicios/coqExercicios-f583bea6a32ef359cbddb786f7fb71803d7bf189/aula5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7845566801080078}}
{"text": "Require Import PeanoNat.\n\n(* bijection from nat * nat to nat *)\nDefinition embed '(x, y) : nat := \n  y + (nat_rec _ 0 (fun i m => (S i) + m) (y + x)).\n\n(* bijection from nat to nat * nat *)\nDefinition unembed (n : nat) : nat * nat := \n  nat_rec _ (0, 0) (fun _ '(x, y) => match x with S x => (x, S y) | _ => (S y, 0) end) n.\n\nLemma embedP {xy: nat * nat} : unembed (embed xy) = xy.\nProof.\n  assert (forall n, embed xy = n -> unembed n = xy).\n    intro n. revert xy. induction n as [|n IH].\n      intros [[|?] [|?]]; intro H; inversion H; reflexivity.\n    intros [x [|y]]; simpl.\n      case x as [|x]; simpl; intro H.\n        inversion H.\n      rewrite (IH (0, x)); [reflexivity|].\n      inversion H; simpl. rewrite Nat.add_0_r. reflexivity.\n    intro H. rewrite (IH (S x, y)); [reflexivity|]. \n    inversion H. simpl. rewrite Nat.add_succ_r. reflexivity.\n  apply H. reflexivity.\nQed.\n\nLemma unembedP {n: nat} : embed (unembed n) = n.\nProof.\n  induction n as [|n IH]; [reflexivity|].\n  simpl. revert IH. case (unembed n). intros x y.\n  case x as [|x]; intro Hx; rewrite <- Hx; simpl.\n    rewrite Nat.add_0_r. reflexivity.\n  rewrite ?Nat.add_succ_r. simpl. rewrite ?Nat.add_succ_r. reflexivity. \nQed.\nArguments embed : simpl never.\n\n\nModule EmbedNatNotations.\n  Notation \"⟨ a , b ⟩\" := (embed (a, b)) (at level 0).\nEnd EmbedNatNotations.\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/embed_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7845397793093388}}
{"text": "(* ----------------------------------------------------------------- *)\n(*                        Elementary Algebra                         *)\n(* ----------------------------------------------------------------- *)\n\nFrom Practice Require Import Basin.Base.\nRequire Import Permutation.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\n\n(* ----------------------------------------------------------------- *)\n(*                       Equivalence on list                         *)\n(* ----------------------------------------------------------------- *)\n\n(* Equivalence on list *)\nInstance equiv_list U `(D: Setoid U): Equivalence (Forall2 equiv).\nProof with eauto.\n  split; red.\n  - (* Reflexivity *)\n    elim=> [|a x' IH]; constructor...\n  - (* Symmetry *)\n    move=> x y. elim=> []...\n  - (* Transitivity *)\n    move=> x y + H.\n    elim: H => [|hx hy x' y' E Hxy IH] z Hy...\n    inversion Hy; subst. constructor...\nQed.\n\n(* Setoid on list required *)\nInstance setoid_list U `(D: Setoid U): Setoid (list U) := {\n  equiv := Forall2 equiv\n}.\n\nAdd Parametric Morphism U `(Setoid U): (@app U)\n  with signature equiv ==> equiv ==> equiv as app_mor.\nProof with auto.\n  move=> l1 l2.\n  elim=> [|h1 h2 l1' l2' Eh El IH] m1 m2 Em...\n  simpl. constructor... by apply: IH.\nQed.\n\n\n(* ----------------------------------------------------------------- *)\n(*               Elementary Algebra on single operator               *)\n(* ----------------------------------------------------------------- *)\n\nCreate HintDb alg discriminated.\n\nDefinition Operator U: Type := U -> U -> U.\n\n\nSection Op.\nContext {U} `(D: Setoid U) (op: Operator U).\n\nClass Magma: Type := {\n  op_proper: Proper (equiv ==> equiv ==> equiv) op\n}.\n\nLocal Add Parametric Morphism `(Magma): op\n  with signature equiv ==> equiv ==> equiv as mop_mor.\nProof. apply op_proper. Qed.\n\nLocal Infix \"@\" := op (at level 25, left associativity).\n\nClass Associative: Prop :=\n  associativity: forall x y z, x @ (y @ z) == (x @ y) @ z.\nClass Commutative: Prop :=\n  commutativity: forall x y, x @ y == y @ x.\nClass HasIdentity: Type := {\n  mid: U\n; mid_left: forall x, mid @ x == x\n; mid_right: forall x, x @ mid == x\n}.\n\n\nClass Semigroup: Type := {\n  sem_mag :> Magma\n; sem_assoc :> Associative\n}.\n\nClass Monoid: Type := {\n  mon_sem :> Semigroup\n; mon_hasid :> HasIdentity\n}.\n\nClass CommMonoid: Type := {\n  cm_mon :> Monoid\n; cm_comm :> Commutative\n}.\n\n\n(* Semigroup concatenation with starting element on right *)\nDefinition SCatWith `{S: Semigroup} (d: U) (l: list U): U :=\n  fold_right op d l.\n\nAdd Parametric Morphism `(Semigroup): (@SCatWith _)\n  with signature equiv ==> equiv ==> equiv as scatwith_mor.\nProof.\n  move=> a b E x y.\n  elim=> {x y} [|hx hy x' y' Hh _ IH] //=.\n  rewrite Hh IH. auto.\nQed.\n\nLemma scatwith_app: forall `(Semigroup) d e l1 l2,\n  SCatWith d l1 @ SCatWith e l2 == SCatWith e (l1 ++ d :: l2).\nProof.\n  move=> ? d e l1 l2.\n  elim: l1 => [|h l1' IH] /=; auto.\n  rewrite <- associativity. rw_refl.\nQed.\n\n\n(* Monoid concatenation *)\nDefinition MCat `{M: Monoid} (l: list U): U :=\n  fold_right op mid l.\n\nAdd Parametric Morphism `(Monoid): (@MCat _)\nwith signature equiv ==> equiv as mcat_mor.\nProof.\n  move=> x y. elim=> {x y} [|hx hy x' y' Hh Hl IH] //=.\n  all: rw_refl.\nQed.\n\n\nLemma mcat_nil: forall `(Monoid),\n  MCat [] == mid.\nProof. reflexivity. Qed.\n\nLemma mcat_app: forall `(Monoid) (l1 l2: list U),\n  MCat l1 @ MCat l2 == MCat (l1 ++ l2).\nProof.\n  move=> ? l1 l2. elim: l1 => [|h l1' IH] /=.\n  - apply: mid_left.\n  - rewrite <- associativity. rw_refl.\nQed.\n\nLemma mcat_single: forall `(Monoid) a,\n  MCat [a] == a.\nProof. move=> > /=. apply: mid_right. Qed.\n\nLemma mcat_couple: forall `(Monoid) a b,\n  MCat [a; b] == a @ b.\nProof. move=> > /=. rewrite mid_right. reflexivity. Qed.\n\n(* Induction on mcat *)\nLemma mcat_ind: forall `(Monoid) (l: list U) (P: U -> Prop),\n  P mid -> (forall a b, P a -> P b -> P (a @ b)) ->\n  Forall P l -> P (MCat l).\nProof.\n  move=> M l P Hid Hop.\n  elim=> {l} [|x l' Hx Hl' IH] //=.\n  by apply: Hop.\nQed.\n\n(* Commutative monoid -> Can permutate *)\nLemma mcat_perm: forall `(CommMonoid) (l m: list U),\n  Permutation l m -> MCat l == MCat m.\nProof with eauto.\n  move=> C l m. elim=> {l m} [| a l m HP IH | a b l |] /=...\n  - rw_refl.\n  - rewrite !associativity (commutativity a)...\nQed.\n\nDefinition MCatOver {V} `{M: Monoid} (f: V -> U) (l: list V): U :=\n  MCat (map f l).\n\n\nEnd Op.\n\nArguments mid {U D} op {HasIdentity}.\nArguments SCatWith {U D} op {S}.\nArguments MCat {U D} op {M}.\nArguments MCatOver {U D} op {V M}.\n\n#[export]\nHint Resolve associativity commutativity mid_left mid_right\n  scatwith_app\n  mcat_nil mcat_app mcat_perm: alg.\n\n\n\n(* ----------------------------------------------------------------- *)\n(*                          El. Alg. Examples                        *)\n(* ----------------------------------------------------------------- *)\n\n(* List: monoid *)\nProgram Instance magma_list U `(Setoid U): Magma _ (@app U).\n\nProgram Instance assoc_app U `(Setoid U): Associative _ (@app U).\nNext Obligation. rewrite app_assoc. reflexivity. Qed.\n\nProgram Instance hasid_app U `(Setoid U): HasIdentity _ (@app U) := { mid := [] }.\nNext Obligation. reflexivity. Qed.\nNext Obligation. rewrite app_nil_r. reflexivity. Qed.\n\nProgram Instance semigroup_app U `(Setoid U): Semigroup _ (@app U).\nProgram Instance monoid_app U `(Setoid U): Monoid _ (@app U).\n\n\n(* Nat add: commutative monoid *)\nProgram Instance magma_nat_add: Magma _ Nat.add.\n\nProgram Instance assoc_nat_add: Associative _ Nat.add.\nNext Obligation. apply Nat.add_assoc. Qed.\n\nProgram Instance comm_nat_add: Commutative _ Nat.add.\nNext Obligation. apply Nat.add_comm. Qed.\n\nProgram Instance hasid_nat_add: HasIdentity _ Nat.add := { mid := 0 }.\n\nProgram Instance semigroup_nat_add: Semigroup _ Nat.add.\nProgram Instance monoid_nat_add: Monoid _ Nat.add.\nProgram Instance cmon_nat_add: CommMonoid _ Nat.add.\n\n\n(* Nat mul: commutative monoid *)\nProgram Instance magma_nat_mul: Magma _ Nat.mul.\n\nProgram Instance assoc_nat_mul: Associative _ Nat.mul.\nNext Obligation. apply Nat.mul_assoc. Qed.\n\nProgram Instance comm_nat_mul: Commutative _ Nat.mul.\nNext Obligation. apply Nat.mul_comm. Qed.\n\nProgram Instance hasid_nat_mul: HasIdentity _ Nat.mul := { mid := 1 }.\nNext Obligation. apply Nat.mul_1_r. Qed.\n\nProgram Instance semigroup_nat_mul: Semigroup _ Nat.mul.\nProgram Instance monoid_nat_mul: Monoid _ Nat.mul.\nProgram Instance cmon_nat_mul: CommMonoid _ Nat.mul.\n", "meta": {"author": "Abastro", "repo": "Coq-Practice", "sha": "2117c3e3a62ac0019ff2d7461fbd41eb561700dd", "save_path": "github-repos/coq/Abastro-Coq-Practice", "path": "github-repos/coq/Abastro-Coq-Practice/Coq-Practice-2117c3e3a62ac0019ff2d7461fbd41eb561700dd/Basin/ElemAlg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8633916187614822, "lm_q1q2_score": 0.7844930854144384}}
{"text": "Require Export Poly_J.\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\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\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\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  apply okd_before in H0. apply H0.\n  apply okd_before in H1. apply H1.\n  apply H. Qed.\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\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\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\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 ExSet : Type :=\n  | con1 : bool -> ExSet\n  | con2 : nat -> ExSet -> ExSet.\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): 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'' : 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\n", "meta": {"author": "denjiry", "repo": "pgeneral", "sha": "190a607a5071af6d41d1abe2af85b86dc085b9ea", "save_path": "github-repos/coq/denjiry-pgeneral", "path": "github-repos/coq/denjiry-pgeneral/pgeneral-190a607a5071af6d41d1abe2af85b86dc085b9ea/Prop_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7844693552674409}}
{"text": "Inductive Nat : Type :=\n  | O : Nat\n  | S : Nat -> Nat.\n\n\nDefinition one  : Nat := S O.\nDefinition two : Nat := S (S O).\nDefinition three : Nat := S (S (S O)).\nDefinition four : Nat := S (S (S (S O))).\nDefinition five : Nat := S (S (S (S O))).\nDefinition six  : Nat := S (S four).\n\nDefinition isOne (n : Nat) : bool := \n  match n with\n  | S O => true\n  | _ => false\n  end.\n\nEval compute in isOne four.\nEval compute in isOne six.\nEval compute in isOne O.\nEval compute in isOne (S O).\n\nFixpoint twice (n : Nat) : Nat := \n   match n with\n   | O => O\n   | S n' => S (S (twice n'))\n   end.\n\nEval compute in twice six.\n\nLemma SStwice : forall (n : Nat), S (S (S (twice n))) = S (twice (S n)).\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\n\n\nFixpoint f (n : Nat) : Nat := match n with\n  | O => O\n  | S n => f n\n  end.\n\nCheck Type.\n\nLemma a (a : Nat) : f a = O.\nProof.\n induction a.\n - simpl. reflexivity.\n - simpl. rewrite IHa. reflexivity.\nQed.\n\n(* Fixpoint f (n : Nat) : Nat := f n. *)\n\nFixpoint plus (n m : Nat) {struct n} : Nat :=\n  match n with \n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nEval compute in plus (twice six) (twice four).\n\nNotation \"x + y\" := (plus x y)\n  (at level 50, left associativity).\n\nLemma leftid (n : Nat) : O + n = n.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma rightid (n : Nat) : n + O = n.\nProof.\n induction n.\n - simpl. reflexivity.\n - simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma assoc (a b c : Nat) : (a + b) + c = a + (b + c).\nProof.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite IHa. reflexivity.\nQed.\n\nLemma cong (f : Nat -> Nat)(a b : Nat) : a = b -> f a = f b.\nProof.\n  intros a_eq_b.\n  rewrite a_eq_b.\n  reflexivity.\nQed.\n\nLemma plus_r_s : forall (a b : Nat), S a + b = a + S b.\nProof.\n  intros.\n  induction a0.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHa0. simpl. reflexivity.\nQed.\n\n\nFixpoint max (a b : Nat) : Nat :=\n  match a, b with\n  | O, b => b\n  | S a, O => S a\n  | S a, S b => S (max a b)\n  end.\n\nCompute (max four six).\n\nLemma idmax : forall (n : Nat ), (max O n) = n.\n intros n.\n simpl.\n reflexivity.\nQed.\n\nLemma idleftmax : forall (n : Nat ), (max n O) = n.\n induction n.\n all: simpl. \n all: reflexivity.\nQed.\n\nLemma comm (a b : Nat) : a + b = b + a.\nProof.\n  induction a.\n  - Check (rightid b). rewrite (rightid b). simpl. reflexivity.\n  - rewrite <- (plus_r_s). simpl. rewrite IHa. reflexivity.\nQed.\n\n\nFixpoint pred (n : Nat) : Nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\n(*Lemma S_inj (a b : Nat) : S a = S b -> a = b.\nProof.\n  intros.*)\n\n\n(*Definition P : Nat -> Prop := fun n => *)\n\n(*Lemma O_S_disj (a : Nat) : O <> S a.\nProof. *)\n  \n\nFixpoint times (a b : Nat) : Nat :=\n  match a with\n  | O => O\n  | S O => b\n  | S a' => b + (times a' b)\n  end.\n\nNotation \"x * y\" := (times x y)\n  (at level 40, left associativity).\n\nLemma times_leftid (a : Nat) : S O * a = a.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma times_rightid (a : Nat) : a * S O = a.\nProof.\n  induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite IHa. induction a0.\n    * simpl. reflexivity.\n    * reflexivity.\nQed. \n\nLemma times_leftzero (a : Nat) : O * a = O.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma times_rightzero (a : Nat) : a * O = O.\nProof.\n  induction a.\n  - simpl. reflexivity.\n  - simpl.  rewrite IHa. induction a0. all: auto.\nQed.\n\n\nLemma times_assoc (a b c : Nat) : (a * b) * c = a * (b * c).\n\n(*Lemma times_comm (a b : Nat) : a * b = b * a.*)\n\n\n(*Lemma decEq (a b : Nat) : a = b \\/ a <> b.*)\n\n*)\n\nInductive BinaryTree : Type :=\n| Leaf (n : Nat)\n| Node (l r : BinaryTree).\n\nDefinition tree : BinaryTree := Node (Node (Leaf one) (Node (Leaf  two) (Leaf three))) (Node (Leaf four) (Leaf five)).\n\nFixpoint height (t : BinaryTree) : Nat := \n  match t with\n  | Leaf _ => O\n  | Node t t' => one + (max (height t) (height t'))\n  end.\n\n\nFixpoint leaves_count (t : BinaryTree) : Nat :=\n  match t with\n  | Leaf _ => one\n  | Node l r => (leaves_count l) + (leaves_count r)\n  end.\n\n(*\n nehez HF:\n  exp2 (height t)\n  leaves_count t \n*)\n\nFixpoint sum1 (t : BinaryTree) : Nat :=\nmatch t with\n| Leaf n => n\n| Node l r => sum1 l + sum1 r\nend.\n\nFixpoint sum2 (t : BinaryTree) : Nat :=\nmatch t with\n| Leaf n => n\n| Node l r => sum2 r + sum2 l\nend.\n\n\nLemma sum1_2_eq : forall t : BinaryTree, sum1 t = sum2 t.\nProof.\n  intros.\n  induction t.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt2. rewrite <- IHt1. rewrite (comm). reflexivity.\nQed.\n\n\nFixpoint exp2 (n : Nat) : Nat :=\n  match n with\n  | O => S O\n  | S m => exp2 m + exp2 m (* 2*2^m *)\n  end.\n\nLemma leaves_height (t : BinaryTree) :\n  max (exp2 (height t)) (leaves_count t) =\n  exp2 (height t).\n\n\n\n\n\n\n", "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/gy02pre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7844693464931888}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export logic.\nRequire Coq.omega.Omega.\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\nLemma double_plus : forall n, double n = n + n.\n  Proof.\nAdmitted.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\nAdmitted.\n(** intros.\ninduction n.\n-  apply ev_0.\n- rewrite double_plus in IHn. unfold double. simpl.\n  rewrite plus_comm. simpl. apply ev_SS. apply IHn.\nQed.\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\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\nintros. inversion H.\napply H1. Qed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\nintros. inversion H. inversion H1. apply H3. Qed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\nintros. inversion H. inversion H1. inversion H3. Qed.\n\nLemma ev_even_firsttry : forall n,\n  ev n -> exists k, n = double k.\nProof.\nintros.\ninversion H.\n- exists 0. reflexivity.\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.**)\nAdmitted.\n\nLemma doublenum : forall n,\ndouble n = n + n.\nProof.\nAdmitted.\n \n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\nAdmitted.\n(** \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'). simpl. rewrite plus_comm. simpl. \n    symmetry. rewrite doublenum. reflexivity.\nQed.\n**)\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\nintros.\nsplit.\n- apply ev_even.\n- intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\nintros.\ninduction H as [| n' En' EIHn' ].\n- simpl. apply H0.\n- apply ev_SS. apply EIHn'.\nQed. \n\nTheorem ev_ev_ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\nintros.\ninduction H0.\n- simpl in H. apply H.\n- simpl in H. inversion H.\n  + apply IHev. apply H2.\nQed.\n\nLemma plus00 : forall n m,\nm+n = 0 -> m =0 /\\ n= 0.\nProof.\nAdmitted.\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\nintros n m p Enm Enp.\napply ev_sum with (n:= n+m) (m:= n+p) in Enm.\nreplace (n+m +(n+p)) with ((n+n)+(m+p)) in Enm.\nreplace (n+n) with (double n) in Enm.\napply ev_ev_ev with (m:= m+p) in Enm.\napply Enm.\nreplace (double n+ (m+p)+(m+p)) with (double n + double (m+p)).\napply ev_sum.\napply ev_double.\napply ev_double.\nrewrite double_plus with (n:=m+p).\nrewrite plus_assoc. reflexivity.\nrewrite double_plus. reflexivity.\nrewrite <- plus_assoc.\nreplace (n+(m+p)) with (m+(n+p)).\nrewrite plus_assoc.\nreflexivity.\nrewrite plus_assoc.\nrewrite ( plus_comm m n).\nrewrite <- plus_assoc. reflexivity.\napply Enp.\nQed.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* 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.\nintros.\ninversion H. inversion H2. Qed.\n\nDefinition relation (X:Type) := X -> X -> Prop.\nDefinition reflexive {X:Type} (R: relation X) :=\n\tforall a : X, R a a.\nDefinition transitive {X:Type} (R: relation X) :=\nforall n m o : X, (R n m) -> (R m o) -> (R n o).\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\nintros m n o Hnm Hno.\n  induction Hno.\n  - apply Hnm.\n  - apply le_S. apply IHHno. apply Hnm. Qed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\nintros.\ninduction n.\n- apply le_n.\n- apply le_S. apply IHn.\nQed.\n\nLemma nleSn : forall n,\nn<= S n.\nProof.\nAdmitted.\n\nLemma nlessSm : forall n m,\nn<=m -> n <= S m.\nProof.\nAdmitted.\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\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\nintros. inversion H.\n- apply le_n.\n- apply le_trans with (n := S n). apply nleSn.\n apply H2. Qed.\n\n\nLemma plusO : forall n,\nn+0 = n.\nProof.\nAdmitted.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\nintros.\ninduction b.\n- rewrite plusO. apply le_n.\n- rewrite plus_comm. simpl. apply le_S.\nrewrite plus_comm. apply IHb.\nQed.\n\nDefinition lt (n m:nat) := le (S n) m.\nNotation \"m < n\" := (lt m n).\n\nLemma O_lt_n : forall n,\n  0 < n.\nProof.\nAdmitted.\nLemma lessS : forall n m,\n n <= m ->  n <= S m.\nProof.\nAdmitted.\n\nLemma nleqn : forall n,\nn<= n.\nProof.\nAdmitted.\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\nunfold lt.\nAdmitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\nintros.\ninversion H.\n- unfold lt. apply le_S. apply nleqn.\n- unfold lt. apply le_S. apply lessS in H0. apply H0.\nQed.\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\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\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\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.\napply (MApp [1] _ [2]).\n- apply MChar.\n- apply MChar.\nQed.\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\nFixpoint reg_exp_of_list {T: Type} (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.\nsimpl. apply ( MApp [1]). apply MChar. apply ( MApp [2]).\napply MChar. apply ( MApp [3]). apply MChar. apply MEmpty.\nQed.\n\nLemma MStar1 :\n  forall T s (re : @reg_exp T) ,\n    s =~ re ->\n    s =~ Star re.\nProof.\nintros.\nrewrite <- (app_nil_r T s).\napply (MStarApp s [] re).\napply H. apply MStar0.\nQed.\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\nintros.\ninduction s.\n- unfold not.\nintros.\ninversion H.\nAdmitted.\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.\ninversion H.\n- apply MUnionL. apply H0.\n- apply MUnionR. apply H0.\nQed.\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.\nintros.\nAdmitted.\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\nintros.\nunfold iff.\nsplit.\n- intros. \nAdmitted.\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.\nLemma equalrelist : forall T (s : list T) (re : reg_exp),\n s =~ re -> s = (re_chars re).\nProof.\nAdmitted.\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. apply equalrelist in H. rewrite <- H. apply H0.**)\nintros T s re x Hmatch Hin.\n  induction Hmatch\n    as [| x'\n        | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n        | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n        | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n  - (* MEmpty *)\n    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- (* 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\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\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/indprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7843882811614203}}
{"text": "Require Import Bool.\n\n(* Please ignore:\n   negb is just another name for\n   the not function for booleans,\n   more on that later.\n*)\nDefinition not := negb.\n\nTheorem deMorgen: forall x y:bool,\n  not (x || y) = (not x) && (not y).\nProof.\nAbort.\n\nTheorem deMorgen_answer: forall x y:bool,\n  not (x || y) = (not x) && (not y).\nProof.\nintros.\n(* We can start by doing case analysis on x into its two cases.\n   Almost like a truth table for computer scientists or\n   A very lame induction for mathematicians.\n*)\nPrint bool.\n(*\n  We can see that a bool is either true of false\n*)\ncase x.\n(* Now we have two cases to prove,\n   lets focus on our first goal\n*)\n- \n(* Seems like some of this equation is simply solvable.\n   simpl can partially apply functions,\n   for you have only supplied limited arguments. *)\n  simpl.\n(* false = false is true by reflexivity *)\n  reflexivity.\n(* Coq helps us remember all cases.\n   The proof cannot complete,\n   if we haven't proved it for all cases.\n*)\n- (* seems like this can also be simplified *)\n  simpl.\n  (* not y = not y, no matter what y is *)\n  reflexivity.\nQed.\n(* Qed = Proven *)\n\n", "meta": {"author": "awalterschulze", "repo": "advertising-coq", "sha": "551d59906bea41c9cbb470e4a5b3bc2762e9f0cc", "save_path": "github-repos/coq/awalterschulze-advertising-coq", "path": "github-repos/coq/awalterschulze-advertising-coq/advertising-coq-551d59906bea41c9cbb470e4a5b3bc2762e9f0cc/deMorgenBool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8670357735451834, "lm_q1q2_score": 0.7843643742603869}}
{"text": "Require Import Ashley.Set.\n\nClass Equivalence (A:Type) : Type :=\n{\n  eqv : A -> A -> Prop;\n  equiv_reflexive : forall a, eqv a a;\n  equiv_symmetric : forall a b, eqv a b -> eqv b a;\n  equiv_transitive : forall a b c, (eqv a b /\\ eqv b c) -> eqv a c\n}.\n\nDefinition equivalence_class {A} (E : Equivalence A) (p : A) : set A := {a : A|eqv p a}.\n\nLemma in_equivalence_class : forall A (e : Equivalence A) (p : A), equivalence_class e p p.\nintros.\nunfold equivalence_class.\napply equiv_reflexive.\nSave.\n\nDefinition quotient {A} (e : Equivalence A) : set (set A) :=\n  {sa : set A| exists a1, (sa = equivalence_class e a1)}.\n\nLemma quotient_disjoint : forall A (e : Equivalence A), all p1 : quotient e, all p2 : quotient e,\n  (undisjoint p1 p2 -> p1 = p2).\nfirstorder.\nrewrite H.\nrewrite H0.\napply member_ext.\nrewrite H in H1.\nrewrite H0 in H2.\nfirstorder.\napply (equiv_transitive x0 x x2).\nsplit.\napply (equiv_transitive x0 x1 x).\nsplit.\napply H2.\napply equiv_symmetric.\napply H1.\napply H3.\napply (equiv_transitive x x1 x2).\nsplit.\napply H1.\napply (equiv_transitive x1 x0 x2).\nsplit.\napply equiv_symmetric.\napply H2.\napply H3.\nSave.\n\nLemma quotient_Union : forall A (e : Equivalence A), is_full (Union (quotient e)).\nintros.\nunfold Union.\nunfold quotient.\nunfold is_full.\nintros.\nexists (equivalence_class e x).\nsplit.\nexists x.\ntrivial.\nunfold equivalence_class.\napply equiv_reflexive.\nSave.\n\nLemma quotient_no_empty : forall A (e : Equivalence A) (s : set A), quotient e s -> not_empty s.\nunfold quotient.\nunfold not_empty.\nintros.\ndestruct H.\nexists x.\nrewrite H.\napply in_equivalence_class.\nSave.\n\nRequire Import Ashley.SetFunction.\n\nDefinition quotient_type {A:Type} (e: Equivalence A) : Type :=  set_type (quotient e).\n\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/Equivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7843643740559085}}
{"text": "(* week-03_binary-trees.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 29 Aug 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\nInductive binary_tree : Type :=\n| Leaf : nat -> binary_tree\n| Node : binary_tree -> binary_tree -> binary_tree.\n\nDefinition test_number_of_leaves (candidate: binary_tree -> nat) :=\n  (candidate (Leaf 1) =n= 1)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) =n= 3)\n  (* etc. *)\n  .\n\nFixpoint number_of_leaves (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    1\n  | Node t1 t2 =>\n    (number_of_leaves t1) + (number_of_leaves t2)\n  end.\n\nCompute (test_number_of_leaves number_of_leaves).\n\nLemma unfold_number_of_leaves_Leaf :\n  forall n : nat,\n    number_of_leaves (Leaf n) =\n    1.\nProof.\n  unfold_tactic number_of_leaves.\nQed.\n\nLemma unfold_number_of_leaves_Node :\n  forall t1 t2 : binary_tree,\n    number_of_leaves (Node t1 t2) =\n    (number_of_leaves t1) + (number_of_leaves t2).\nProof.\n  unfold_tactic number_of_leaves.\nQed.\n\nFixpoint number_of_nodes (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    0\n  | Node t1 t2 =>\n    S ((number_of_nodes t1) + (number_of_nodes t2))\n  end.\n\nLemma unfold_number_of_nodes_Leaf :\n  forall n : nat,\n    number_of_nodes (Leaf n) =\n    0.\nProof.\n  unfold_tactic number_of_nodes.\nQed.\n\nLemma unfold_number_of_nodes_Node :\n  forall t1 t2 : binary_tree,\n    number_of_nodes (Node t1 t2) =\n    S ((number_of_nodes t1) + (number_of_nodes t2)).\nProof.\n  unfold_tactic number_of_nodes.\nQed.\n\nTheorem on_the_relative_number_of_leaves_and_nodes_in_a_binary_tree :\n  forall t : binary_tree,\n    number_of_leaves t = S (number_of_nodes t).\nProof.\n  intro t.\n  induction t as [ n | t1 IH_t1 t2 IH_t2]. \n\n  Check(unfold_number_of_leaves_Leaf n).\n  rewrite -> (unfold_number_of_leaves_Leaf n).\n  Check(unfold_number_of_nodes_Leaf n).\n  rewrite -> (unfold_number_of_nodes_Leaf n).\n  reflexivity.\n\n  Check (unfold_number_of_leaves_Node t1 t2).\n  rewrite -> (unfold_number_of_leaves_Node t1 t2).\n  Check (unfold_number_of_nodes_Node t1 t2).\n  rewrite -> (unfold_number_of_nodes_Node t1 t2).\n  rewrite -> IH_t1.\n  rewrite -> IH_t2. \n  Search (S _ + S _ = S (S (_ + _))).\n  Search (S _ + S _ = S _ ).\n  Check (plus_Sn_m (number_of_nodes t1) (S (number_of_nodes t2))).\n  rewrite -> (plus_Sn_m (number_of_nodes t1) (S (number_of_nodes t2))).\n  Search (_ + S _ = S _).\n  rewrite -> (Nat.add_succ_r (number_of_nodes t1) (number_of_nodes t2)).\n  reflexivity.\n\n\n  (* ********** *)\n\n(* end of week-03_binary-trees.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-03_binary-trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7843643691891955}}
{"text": "Require Import ZArith.\nRequire Import Equivalence.\nRequire Import Morphisms.\n\nModule ZFunc.\n\nLocal Open Scope Z.\n\nDefinition add {A: Type} (f g: A -> Z): A -> Z :=\n  fun a => f a + g a.\n\nDefinition sub {A: Type} (f g: A -> Z): A -> Z :=\n  fun a => f a - g a.\n\nDefinition mul {A: Type} (f g: A -> Z): A -> Z :=\n  fun a => f a * g a.\n\nDefinition test_eq {A: Type} (f g: A -> Z): A -> Prop :=\n  fun a => f a = g a.\n\nDefinition test_le {A: Type} (f g: A -> Z): A -> Prop :=\n  fun a => f a <= g a.\n\nDefinition equiv {A: Type} (f g: A -> Z): Prop :=\n  forall a, f a = g a.\n\nDefinition le {A: Type} (f g: A -> Z): Prop :=\n  forall a, f a <= g a.\n\nEnd ZFunc.\n\n\nDeclare Scope func_scop.\nDelimit Scope func_scope with Func.\n\nNotation \"f + g\" := (ZFunc.add f g): func_scope.\nNotation \"f - g\" := (ZFunc.sub f g): func_scope.\nNotation \"f * g\" := (ZFunc.mul f g): func_scope.\n\nLemma Func_equiv_refl: forall A, Reflexive (@ZFunc.equiv A).\nProof.\n  intros.\n  unfold Reflexive.\n  unfold ZFunc.equiv.\n  intros.\n  reflexivity.\nQed.\n\nLemma Func_equiv_sym: forall A, Symmetric (@ZFunc.equiv A).\nProof.\n  intros.\n  unfold Symmetric.\n  unfold ZFunc.equiv.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma Func_equiv_trans: forall A, Transitive (@ZFunc.equiv A).\nProof.\n  intros.\n  unfold Transitive.\n  unfold ZFunc.equiv.\n  intros.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\nLemma Func_add_equiv: forall A,\n  Proper (@ZFunc.equiv A ==> @ZFunc.equiv A ==> @ZFunc.equiv A) ZFunc.add.\nProof.\n  intros.\n  unfold Proper, respectful.\n  intros f1 f2 ? g1 g2 ?.\n  unfold ZFunc.equiv in H.\n  unfold ZFunc.equiv in H0.\n  unfold ZFunc.equiv.\n  intros.\n  unfold ZFunc.add.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\nLemma Func_sub_equiv: forall A,\n  Proper (@ZFunc.equiv A ==> @ZFunc.equiv A ==> @ZFunc.equiv A) ZFunc.sub.\nProof.\n  intros.\n  unfold Proper, respectful.\n  intros f1 f2 ? g1 g2 ?.\n  unfold ZFunc.equiv in H.\n  unfold ZFunc.equiv in H0.\n  unfold ZFunc.equiv.\n  intros.\n  unfold ZFunc.sub.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\nLemma Func_mul_equiv: forall A,\n  Proper (@ZFunc.equiv A ==> @ZFunc.equiv A ==> @ZFunc.equiv A) ZFunc.mul.\nProof.\n  intros.\n  unfold Proper, respectful.\n  intros f1 f2 ? g1 g2 ?.\n  unfold ZFunc.equiv in H.\n  unfold ZFunc.equiv in H0.\n  unfold ZFunc.equiv.\n  intros.\n  unfold ZFunc.mul.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\nExisting Instances Func_equiv_refl\n                   Func_equiv_sym\n                   Func_equiv_trans\n                   Func_add_equiv\n                   Func_sub_equiv\n                   Func_mul_equiv.\n\n", "meta": {"author": "sjxer723", "repo": "monorepo", "sha": "65c347dfd9c4cdacc4b0d3d39e55c72603ef5633", "save_path": "github-repos/coq/sjxer723-monorepo", "path": "github-repos/coq/sjxer723-monorepo/monorepo-65c347dfd9c4cdacc4b0d3d39e55c72603ef5633/compilerverification/vcompframework/ZFuncDomain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7843502035947946}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\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\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** **** Exercise: 1 star, standard (ev_double)  *)\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  intros n. induction n as [| n' IHn']. (* we proceed by induction *)\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS. apply IHn'. (* use ev_SS and the hypothesis *)\nQed.\n\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  intros n H.\n  inversion H. (*apply inversion twice *)\n  inversion H1.\n  apply H3.\nQed.\n\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  intros H.\n  inversion H.\n  inversion H1.\n  inversion H3. (* we do inversion until we get to something that is not true\nand finish like when we discriminate *)\nQed.\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(** [] *)\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'). simpl. 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  intros m n o.\n  intros H1 H2.\n  induction H2.\n  - apply H1.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n.\n  induction n. (* a simple induction and the definition of le. *)\n  - apply le_n.\n  - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m.\n  intros H.\n  induction H. (* induction on the hypothesis *)\n  - apply le_n. \n  - apply le_S. apply IHle. (*just apply the premises*)\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m.\n  intros H.\n  inversion H. (* classical move *)\n  - apply le_n.\n  - apply le_trans with (n := S n). (* use transitivity from above *)\n    + apply le_S. apply le_n. (* obviously n <= S n *)\n    + apply H1.\nQed. \n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b.\n  induction a as [| a' IH]. (*classical inductive step *)\n  - simpl. apply O_le_n. (* trivial *)\n  - simpl. apply n_le_m__Sn_le_Sm. apply IH. (*use the previosly proven theorem *) \nQed.\n\nLemma n_leq_Sn: forall n,\n  n <= S n.\nProof.\n  intros n.\n  apply le_S. apply le_n.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\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  intros n1 n2 m.\n  intros H.\n  induction H.\n  - split.     \n    (*both cases are trivial using the previous functions *)\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. (* we need commutativity *)\n  - split.\n    + destruct IHle. (* divide the condition *)\n      (* After that, both the cases become easy using transitivity! *)\n      apply le_trans with (n := m).\n      * apply H0.\n      * apply n_leq_Sn.\n    + destruct IHle.\n      apply le_trans with (n := m).\n      * apply H1.\n      * apply n_leq_Sn.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros n m.\n  unfold lt.\n  intros H.\n  apply le_trans with (n := m).\n  - apply H.\n  - apply n_leq_Sn.\nQed.\n\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\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intros n. (* introducing m didn't turn out to be successful *)\n  induction n as [| n IHn]. (* classical induction *)\n  - simpl. intros m H. apply O_le_n. (* trivial *)\n  - induction m as [| m IHm]. (* another induction *)\n    + simpl. intros H. discriminate H. (*trivial *)\n    + intros H. \n      apply n_le_m__Sn_le_Sm. (* we need to modify the goal to use IHn *) \n      apply IHn.\n      simpl in H. (*trivial end*)\n      apply H.\nQed.  \n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\nProof. \n  intros m. (* same as earlier, we don't introduce n immediately; we use the hint given *)\n  induction m as [|m'].\n  - intros n H.\n    inversion H. (* H holds, and the goal is almost equivalent *)\n    + simpl. reflexivity.\n    + simpl. reflexivity. (*both cases are trivial *)\n  - intros n H.\n    destruct n as [|n']. (* instead of induction, we try destruct *)\n    + inversion H. (* we have a contradiction and inversion nicely settles that for us*)\n    + simpl. apply IHm'. (*we can use the inductive hypothesis *)\n      apply Sn_le_Sm__n_le_m. apply H. (* classical finish *)\nQed.\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  intros n m o.\n  intros H1 H2.\n  apply leb_correct. (* we want to apply the previous theorem *)\n  (* we can show that n <= m <= o *)\n  apply le_trans with (n := m).\n  - apply leb_complete in H1. (* trivial cases, we use the previous theorem *)\n    apply H1.\n  - apply leb_complete in H2.\n    apply H2.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  intros n m.\n  split. (* we had already proven both the directions *)\n  - apply leb_complete.\n  - apply leb_correct.\nQed.\n\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: *)\n(*Definition 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  | c1: forall l: list nat, subseq [] l\n  | c2: forall l1 l2: list nat, forall h: nat, subseq l1 l2 -> subseq l1 (h::l2)\n  | c3: forall l1 l2: list nat, forall h: nat, subseq l1 l2 -> subseq (h::l1) (h::l2)\n  (*empty list is a subsequence of anything *)\n  (*if l1 is a subsequence of l2, l1 is a subsequence of (h::l2). *)\n  (*if l1 is a subsequence of l2, (h::l1) is a subsequence of (h::l2). *)\n  \n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  intros l.\n  induction l as [| h t IH].\n  - apply c1.\n  - apply c3. apply IH.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  intros H.\n  induction H.  (*induction on l1 didn't turn out to be successful so I tried on H *)\n  - apply c1.\n  - simpl. (* in order to apply assoc *) apply c2. apply IHsubseq.\n  - simpl. (* same as before *) apply c3. apply IHsubseq.\n  (* In fact, 2nd and 3rd case are almost the same *)\nQed.\n\nLemma subseq_of_empty: forall l : list nat,\nsubseq l [] -> l = [].\nProof.\n  intros l H. \n  induction l. (*classical move *)\n  - reflexivity. (* trivial *)\n  - inversion H. (* does the job for us *)\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n\n  intros l1 l2 l3 H1 H2.\n  generalize dependent l1.\n  induction H2. (* induction on H1 failed to work so I tried H2 *)\n  - intros.\n    apply subseq_of_empty in H1. rewrite H1. apply c1.\n  - intros. apply c2. apply IHsubseq. apply H1.\n  - intros. \n(* at this point we want to use H1 because it involves most of the same variables as the goal *)\n    inversion H1.\n    + apply c1. (* trivial *)\n    + apply c2. apply IHsubseq. apply H3. (*using the hypothesis and finishing*)\n    + apply c3. apply IHsubseq. apply H3. (*almost the same as previous case *)\nQed.\n\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\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n\n  (* FILL IN HERE *) Admitted.\n\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\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  intros T s.\n  unfold not. (* unfold the not *)\n  intros H. (*introduce hypothesis and apply inversion *)\n  inversion H.\nQed.\n\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros.\n  destruct H as [H1 | H2].\n  - apply MUnionL. apply H1. (* if s matches re1, it will match the union (from left) *)\n  - apply MUnionR. apply H2. (* if s matches re2, it will match the union (from right) *)\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\nCompute fold plus [1;2;3;4] 0. (* 1 + (2 + (3 + (4 + 0))) *)\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  intros.\n  induction ss as [| h t IH].\n  - simpl. apply MStar0.\n  - simpl. apply MStarApp.\n    + apply H with (s := h). (* we see that we can apply H with (s := h). *)\n      left. reflexivity. (* we need to prove that h is either equal to h or h is in t. Trivial *)\n    + apply IH. intros s H1. apply H. simpl. right. apply H1.\n      (* applying the induction hypothesis is the first step *)\n      (* after that, we introduce a list and a hypothesis and use the definition of In *)\n      (* the ending is trivial *)\nQed. \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\nCompute napp 4 [1;2;3].\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  - simpl. omega.\n  - simpl.  \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\nCompute filter (fun x => 2 =? x) [1;2;3;4].\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  intros.\n  destruct H. (* H can be P or ~P *)\n  - split. (* we have an iff claim *)\n    + intros H1. reflexivity. (* trivial to prove *)\n    + intros H1. apply H. (*trivial *)\n  - split.\n    + intros H1. unfold not in H. destruct H. apply H1. (* we have a clear contradiction *)\n      (* unfold just let's prove the claim using it *)\n    + intros H1. discriminate H1.\nQed.\n\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\nCompute count 4 [1;2;4;5;6;4].\n\nTheorem eqbP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros n l.\n  induction l as [| h t IH]. (* we proceed by induction *)\n  - simpl. (*trivial case*)\n    intros H. unfold not. intros H1. apply H1. \n  - simpl. destruct eqbP with (n := n) (m := h). (* destruct =? *)\n    + intros H1. discriminate H1. (* clearly 1 + sth != 0 *)\n    + intros H1. unfold not. intros H2. destruct H2. (* \"preprocessing\" *)\n      * apply H. symmetry. apply H0. (* trivial *)\n      * simpl in H1. apply IH. apply H1. apply H0. (* easy ending*)\nQed.\n\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  | nostutter_empty: nostutter [] (* empty list doesnt' stutter *)\n  | nostutter_one (x : X): nostutter [x] (* a list with one element doesn't stutter *)\n  | nostutter_all (x : X) (y : X) (l : list X):\n       x <> y -> nostutter (y :: l) -> nostutter (x :: y :: l).\n  (* if x != y and l doesn't stutter with y, then l won't stutter with [x;y].*)\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\nProof. repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_2:  nostutter (@nil nat).\nProof. repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_3:  nostutter [5].\nProof. repeat constructor; apply eqb_false; 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 H1. reflexivity.\nQed.\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": "ndanevski1", "repo": "Coq-Logical-Foundations", "sha": "a27eeed307f06aa91535c39c1a9fc1180311f4d6", "save_path": "github-repos/coq/ndanevski1-Coq-Logical-Foundations", "path": "github-repos/coq/ndanevski1-Coq-Logical-Foundations/Coq-Logical-Foundations-a27eeed307f06aa91535c39c1a9fc1180311f4d6/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.7843431247944254}}
{"text": "(*************************************)\n(*************************************)\n(****                             ****)\n(****   Encoding proofs as data   ****)\n(****                             ****)\n(*************************************)\n(*************************************)\n\n(*\n  In this lesson, we're going to redefine some things from the standard library\n  to explain their definitions. We're also going to rebind some notations to\n  our definitions, so we silence the relevant warning with this:\n*)\n\n#[local] Set Warnings \"-notation-overridden\".\n\n(* One of our proofs will use `Nat.mul_assoc` from this module: *)\n\nRequire Import Coq.Arith.PeanoNat.\n\n(*\n  Consider a mathematical statement, i.e., a *proposition*, that you'd like to\n  prove. An example of a proposition is that addition of natural numbers is\n  commutative. In Coq, we'd represent that proposition as a type:\n\n  ```\n  forall x y, x + y = y + x\n  ```\n\n  This type might seem strange at first. You already know about `forall` and\n  `+`, but we haven't seen `=` yet. Fear not! In this lesson, we'll see how\n  this notion of equality and other logical constructs like \"and\" and \"or\" can\n  be defined as type families in Coq.\n\n  How then can we prove a proposition like that? In Coq, we prove a proposition\n  by constructing an element of the corresponding type. So a proof corresponds\n  to a program, and the proposition it proves corresponds to the type of that\n  program. This idea is called *propositions as types*.\n\n  It'll be useful to define a proposition which is trivially true. We'll call\n  this proposition `True`, but don't mistake it for a `bool`! As explained\n  above, propositions like `True` correspond to types.\n*)\n\nInductive True : Prop :=\n| I : True.\n\n(*\n  So `True` is a proposition, and `I` is its proof. This is a bit abstract, but\n  it'll become more clear once we define a few other logical concepts.\n\n  Note that we put `True` in a universe called `Prop` instead of `Set`. In\n  general, propositions will live in `Prop`. This is an easy way to distinguish\n  proofs from programs, and it'll allow Coq to erase all the proofs when\n  extracting the code to another programming language. See Lesson 5 for details\n  about universes and Lesson 6 for details about program extraction.\n\n  Along the same lines as `True`, it'll also be useful to have a proposition\n  which is trivially false:\n*)\n\nInductive False : Prop := .\n\n(*\n  Note that `False` has no constructors and therefore no proofs!\n\n  One of the most familiar logical concepts is *conjunction*, also known as\n  \"and\". To prove \"A and B\", we need to provide a proof of \"A\" and a proof of\n  \"B\". We can define this in Coq as follows:\n*)\n\nInductive and (A B : Prop) : Prop :=\n| conj : A -> B -> and A B.\n\nArguments conj {_} {_} _ _.\n\n(*\n  The following specifies that the notation `A /\\ B` will be used as shorthand\n  for `and A B`. The `type_scope` notation scope indicates that this notation\n  only applies in contexts where a type is expected.\n*)\n\nNotation \"A /\\ B\" := (and A B) : type_scope.\n\n(* You can look up a notation with `Locate`. *)\n\nLocate \"/\\\". (* `Notation \"A /\\ B\" := (and A B) : type_scope` *)\n\n(* Let's write a proof! *)\n\nDefinition trueAndTrue1 : True /\\ True := conj I I.\n\n(*\n  Writing proofs by hand can be extremely tedious in practice. Coq has a\n  scripting language called *Ltac* to help us construct proofs. We can use Ltac\n  in *proof mode*. Below is the same proof as above, but written in Ltac using\n  proof mode.\n\n  To write proofs using proof mode, it's essential that you're using an IDE\n  that supports Coq, such as CoqIDE or Visual Studio Code with the VsCoq\n  plugin.\n\n  We use `Theorem` when we want to give a name to the proof (e.g., to use it in\n  a later proof) and `Goal` if the proof doesn't need a name.\n*)\n\nTheorem trueAndTrue2 : True /\\ True.\nProof.\n  (*\n    Use `split` to prove each half of a conjunction individually. Equivalently,\n    we could use `apply conj`.\n  *)\n  split.\n\n  (* Use `apply` to prove the goal via some known fact. *)\n  - apply I.\n\n  (* Déjà vu! *)\n  - apply I.\nQed.\n\nPrint trueAndTrue2. (* `conj I I` *)\n\n(*\n  The proof above had two subgoals, and both were solved by `apply I`. In\n  situations like that, we can use the `;` *tactical* to reduce duplication:\n*)\n\nTheorem trueAndTrue3 : True /\\ True.\nProof.\n  split; apply I.\nQed.\n\nPrint trueAndTrue3. (* `conj I I` *)\n\n(* Let's see what happens when we try to prove `True` *and* `False`. *)\n\nGoal True /\\ False.\nProof.\n  split.\n  - apply I.\n  - (* We're stuck here! *)\nAbort.\n\n(*\n  We don't need to define *implication*, since \"A implies B\" is just `A -> B`.\n  In other words, a proof of \"A implies B\" is a function which transforms a\n  proof of \"A\" into a proof of \"B\".\n*)\n\nDefinition modusPonens (A B : Prop) : (A -> B) -> A -> B :=\n  fun H1 H2 => H1 H2.\n\nGoal forall A B : Prop, (A -> B) -> A -> B.\nProof.\n  intros.\n  apply H.\n  apply H0.\nQed.\n\nDefinition conjunctionSymmetric A B : A /\\ B -> B /\\ A :=\n  fun H1 =>\n    match H1 with\n    | conj H2 H3 => conj H3 H2\n    end.\n\nGoal forall A B, A /\\ B -> B /\\ A.\nProof.\n  (* `intros` moves the premises of the goal into the context. *)\n  intros.\n\n  (*\n    `destruct` does pattern matching. We can `destruct` a proof of `A /\\ B` to\n    get access to the proofs of `A` and `B`.\n  *)\n  destruct H.\n\n  (* The rest is familiar. *)\n  split.\n  - apply H0.\n  - apply H.\nQed.\n\nDefinition explosion (A : Prop) : False -> A :=\n  fun H =>\n    match H with\n    (* No cases to worry about! *)\n    end.\n\nCheck explosion. (* `forall A : Prop, False -> A` *)\n\nGoal forall A : Prop, False -> A.\nProof.\n  (* You know the drill. *)\n  intros.\n\n  (* We can `destruct` a proof of `False` to prove anything! *)\n  destruct H.\nQed.\n\n(*\n  To prove the *equivalence* \"A if and only if B\", we have to prove \"A\" and \"B\"\n  imply each other.\n*)\n\nDefinition iff (A B : Prop) := (A -> B) /\\ (B -> A).\n\nNotation \"A <-> B\" := (iff A B) : type_scope.\n\nDefinition AIffA A : A <-> A :=\n  conj (fun H => H) (fun H => H).\n\nGoal forall A, A <-> A.\nProof.\n  intros.\n  unfold iff. (* `unfold` replaces a name with its definition. *)\n  split; intros; apply H.\nQed.\n\n(*\n  To prove the *disjunction* \"A or B\", we must provide either a proof of \"A\" or\n  a proof of \"B\".\n*)\n\nInductive or (A B : Prop) : Prop :=\n| orIntroL : A -> or A B\n| orIntroR : B -> or A B.\n\nArguments orIntroL {_} {_} _.\nArguments orIntroR {_} {_} _.\n\nNotation \"A \\/ B\" := (or A B) : type_scope.\n\nDefinition disjunctionSymmetric A B : (A \\/ B) -> (B \\/ A) :=\n  fun H1 =>\n    match H1 with\n    | orIntroL H2 => orIntroR H2\n    | orIntroR H2 => orIntroL H2\n    end.\n\nGoal forall A B, (A \\/ B) -> (B \\/ A).\nProof.\n  intros.\n  destruct H. (* `destruct` does case analysis on a disjunctive hypothesis. *)\n  - right. (* Equivalent to `apply orIntroR.` *)\n    apply H.\n  - left. (* Equivalent to `apply orIntroL.` *)\n    apply H.\nQed.\n\n(* In Coq, the *negation* \"not A\" is defined as \"A implies False\". *)\n\nDefinition not (A : Prop) := A -> False.\n\nNotation \"~ A\" := (not A) : type_scope.\n\nDefinition notFalse : ~False := fun H => H.\n\nGoal ~False.\nProof.\n  unfold not.\n  intros.\n  apply H.\nQed.\n\n(*\n  In Lesson 2, we learned that Coq has a built-in notion of equality which is\n  used for type checking: two expressions are considered equal if they compute\n  to syntatically identical expressions. This is definitional equality.\n\n  Thus, `0 + n` is definitionally equal to `n`, because `+` pattern matches on\n  the `0` and returns `n` in that case. However, `n + 0` is not definitionally\n  equal to `n`. How unfortunate!\n\n  We can define a more flexible version of equality as an inductive family.\n  This kind of equality isn't as convenient to work with, since the type\n  checker can't use it automatically by doing computation. However, it allows\n  us to *prove* that `n + 0 = n`, and then we can use such a proof to freely\n  substitute one side for the other. This notion of equality which requires\n  proof is called *propositional equality*:\n*)\n\nInductive eq {A} (x : A) : A -> Prop :=\n| eq_refl : eq x x.\n\nNotation \"x = y\" := (eq x y) : type_scope.\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nDefinition onePlusOneEqualsTwo : 1 + 1 = 2 := eq_refl 2.\n\nGoal 1 + 1 = 2.\nProof.\n  reflexivity. (* Equivalent to `apply eq_refl.` *)\nQed.\n\nDefinition eqSymmetric A (x y : A) : x = y -> y = x :=\n  fun H =>\n    match H in _ = z return z = x with\n    | eq_refl _ => eq_refl x\n    end.\n\nGoal forall A (x y : A), x = y -> y = x.\nProof.\n  intros.\n  rewrite H. (* Replace `x` with `y` in the goal. *)\n  reflexivity.\nQed.\n\nGoal forall A (x y : A), x = y -> y = x.\nProof.\n  intros.\n  rewrite <- H. (* Replace `y` with `x` in the goal. *)\n  reflexivity.\nQed.\n\nGoal forall A (x y : A), x = y -> y = x.\nProof.\n  intros.\n  symmetry. (* Turn `y = x` into `x = y` in the goal. *)\n  apply H.\nQed.\n\nGoal forall A (x y : A), x = y -> y = x.\nProof.\n  intros.\n  symmetry in H. (* Turn `x = y` into `y = x` in hypothesis `H`. *)\n  apply H.\nQed.\n\nDefinition eqTransitive A (x y z : A) : x = y -> y = z -> x = z :=\n  fun H1 H2 =>\n    match H2 in _ = v return x = v with\n    | eq_refl _ => H1\n    end.\n\nGoal forall A (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros.\n  rewrite H.\n  rewrite H0.\n  reflexivity.\nQed.\n\nGoal forall A (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros.\n  rewrite <- H0.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nGoal forall A (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros.\n  rewrite H0 in H. (* Replace `y` with `z` in hypothesis `H`. *)\n  apply H.\nQed.\n\nGoal forall A (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros.\n  rewrite <- H in H0. (* Replace `y` with `x` in hypothesis `H0`. *)\n  apply H0.\nQed.\n\n(*\n  *Universal quantification* corresponds to the built-in `forall` syntax. Thus,\n  we don't need to define it explicitly.\n*)\n\nDefinition negbInvolution b :=\n  match b return negb (negb b) = b with\n  | true => eq_refl true\n  | false => eq_refl false\n  end.\n\nCheck negbInvolution. (* `forall b : bool, negb (negb b) = b` *)\n\nGoal forall b, negb (negb b) = b.\nProof.\n  intros.\n  destruct b; reflexivity.\nQed.\n\nDefinition weird f :\n  (forall x, f (f x) = 1 + x) ->\n  forall y, f (f (f (f y))) = 2 + y\n:=\n  fun H1 y =>\n    match H1 (1 + y) in _ = z return f (f (f (f y))) = z with\n    | eq_refl _ =>\n      match H1 y in _ = z return f (f (f (f y))) = f (f z) with\n      | eq_refl _ => eq_refl (f (f (f (f y))))\n      end\n    end.\n\nGoal\n  forall f,\n  (forall x, f (f x) = 1 + x) ->\n  forall y, f (f (f (f y))) = 2 + y.\nProof.\n  intros.\n  rewrite H.\n  rewrite H.\n  reflexivity.\nQed.\n\n(* *Existential quantification* can be defined as follows: *)\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n  ex_intro : forall x : A, P x -> ex P.\n\nArguments ex_intro {_} {_} _ _.\n\n(*\n  The notation for existentials is somewhat tricky to specify. If you're\n  curious about the details, consult the Coq reference manual.\n*)\n\nNotation \"'exists' x .. y , p\" := (ex (fun x => .. (ex (fun y => p)) ..))\n  (at level 200, x binder, right associativity) : type_scope.\n\nDefinition halfOf6Exists : exists x, 2 * x = 6 :=\n  ex_intro 3 (eq_refl 6).\n\nGoal exists x, 2 * x = 6.\nProof.\n  exists 3. (* Equivalent to `apply ex_intro with (x := 3).` *)\n  reflexivity.\nQed.\n\nDefinition divisibleBy4ImpliesEven x :\n  (exists y, 4 * y = x) ->\n  (exists z, 2 * z = x)\n:=\n  fun H1 =>\n    match H1 with\n    | ex_intro y H2 =>\n      ex_intro\n        (2 * y)\n        match eq_sym (Nat.mul_assoc 2 2 y) in Logic.eq _ z return z = x with\n        | Logic.eq_refl _ => H2\n        end\n    end.\n\nGoal forall x, (exists y, 4 * y = x) -> (exists z, 2 * z = x).\nProof.\n  intros.\n  destruct H. (* What is `y`? *)\n  exists (2 * x0).\n  rewrite Nat.mul_assoc.\n  apply H.\nQed.\n\n(*************)\n(* Exercises *)\n(*************)\n\n(*\n  1. Prove `forall (A B C : Prop), (A -> B) -> (A -> C) -> A -> B /\\ C` both\n     manually and using proof mode.\n  2. Prove `forall (A B : Prop), (A /\\ B) -> (A \\/ B)` both manually and using\n     proof mode.\n  3. Prove `forall A : Prop, ~(A /\\ ~A)` both manually and using proof mode.\n  4. Prove `forall A : Prop, ~~~A -> ~A` both manually and using proof mode.\n  5. Prove `forall x, x = 0 \\/ exists y, S y = x` both manually and using proof\n     mode.\n*)\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/Tutorial/Lesson3_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.7843019988293505}}
{"text": "Require Import Coq.Unicode.Utf8.\n\n(* The set of the group. *)\nParameter G : Set.\n\n(* The binary operator. *)\nParameter f : G → G → G.\n\n(* For readability, we use infix · to stand for the binary operator. *)\nInfix \"·\" := f (at level 50, left associativity).\n\n(* The group identity. *)\nParameter e : G.\n\n(* The inverse operator. *)\nParameter i : G → G.\n\n(* Add a more familiar form of the inverse operator. *)\nNotation \"a ⁻¹\" := (i a) (at level 20, left associativity).\n\n(* The operator [·] is also right-associative. *)\nAxiom associativity : ∀ a b c, a·b·c = a·(b·c).\n\n(* [e] is the right-identity for all elements [a] *)\nAxiom right_identity : ∀ a, a·e = a.\n\n(* [a⁻¹] is the right-inverse of [a]. *)\nAxiom right_inverse : ∀ a, a·a⁻¹ = e.\n\nProposition right_multiply_both_sides :\n  ∀ a b c, a = b → a·c = b·c.\nProof.\n  intros a b c.\n  intros a_is_b.\n  rewrite a_is_b.\n  reflexivity.\nQed.\n\nNotation \"'multiply' d 'on' 'the' 'right' 'by' c\" := (right_multiply_both_sides _ _ c d) (at level 100).\n\nProposition right_cancel_left_side :\n  ∀ a b c, a·c = b → a = b·c⁻¹.\nProof.\n  intros a b c.\n  intros to_cancel.\n  set (cancelled := multiply to_cancel on the right by c⁻¹).\n  rewrite associativity in cancelled.\n  rewrite right_inverse in cancelled.\n  rewrite right_identity in cancelled.\n  exact cancelled.\nQed.\n\nNotation \"'cancel' 'the' 'left-hand' 'side' 'of' d 'on' 'the' 'right' 'by' c\" := (right_cancel_left_side _ _ c d) (at level 100).\n\nProposition right_cancel_both_sides :\n  ∀ a b c, a·c = b·c → a = b.\nProof.\n  intros a b c.\n  intros to_cancel.\n  set (cancelled := cancel the left-hand side of to_cancel on the right by c).\n  rewrite associativity in cancelled.\n  rewrite right_inverse in cancelled.\n  rewrite right_identity in cancelled.\n  exact cancelled.\nQed.\n\nNotation \"'cancel' d 'on' 'the' 'right' 'by' c\" := (right_cancel_both_sides _ _ c d) (at level 100).\n\nCorollary right_cancelling :\n  ∀ a b c, a = b ↔ a·c = b·c.\nProof.\n  intros a b c.\n  refine (conj _ _).\n    (* → *)\n    exact (right_multiply_both_sides a b c).\n    (* ← *)\n    exact (right_cancel_both_sides a b c).\nQed.\n\nLemma more_right_cancelling :\n  ∀ a b c LHS RHS,\n    a·c = LHS\n    → b·c = RHS\n    → a = b\n    → LHS = RHS.\nProof.\n  intros a b c LHS RHS.\n  intros ac_is_LHS bc_is_RHS a_is_b.\n  rewrite a_is_b in ac_is_LHS.\n  rewrite ac_is_LHS in bc_is_RHS.\n  exact bc_is_RHS.\nQed.\n\n(* The identity [e] is unique. *)\nTheorem unique_identity : ∀ a, a·a = a → a = e.\nProof.\n  intros a.\n  intros aa_is_a.\n  set (cancelled := cancel the left-hand side of aa_is_a on the right by a).\n  rewrite right_inverse in cancelled.\n  exact cancelled.\nQed.\n\nProposition left_multiply_both_sides :\n  ∀ a b c, a = b → c·a = c·b.\nProof.\n  intros a b c.\n  intros a_is_b.\n  rewrite a_is_b.\n  reflexivity.\nQed.\n\nNotation \"'multiply' d 'on' 'the' 'left' 'by' c\" := (left_multiply_both_sides _ _ c d) (at level 100).\n\n(* [a⁻¹] is also the left-inverse of [a]. *)\nTheorem left_inverse : ∀ a, a⁻¹·a = e.\nProof.\n  intros a.\n  refine (unique_identity (a⁻¹·a) _).\n    rewrite <- associativity.\n    refine (multiply _ on the right by a).\n      rewrite associativity.\n      rewrite right_inverse.\n      rewrite right_identity.\n      reflexivity.\nQed.\n\n(* [e] is also the left-identity. *)\nTheorem left_identity : ∀ a, e·a = a.\nProof.\n  intros a.\n  refine (cancel _ on the right by a⁻¹).\n    rewrite associativity.\n    rewrite right_inverse.\n    rewrite right_identity.\n    reflexivity.\nQed.\n\n(* The inverse anti-distributes over multiplication. *)\nTheorem inverse_anti_distribution : ∀ a b, (a·b)⁻¹ = b⁻¹·a⁻¹.\nProof.\n  intros a b.\n  refine (cancel _ on the right by a·b).\n    rewrite left_inverse.\n    rewrite <- associativity.\n    refine (cancel _ on the right by b⁻¹).\n      rewrite associativity.\n      rewrite right_inverse.\n      rewrite associativity.\n      rewrite right_identity.\n      rewrite associativity.\n      rewrite left_inverse.\n      rewrite right_identity.\n      rewrite left_identity.\n      reflexivity.\nQed.\n\n(* The inverse of the inverse is the original element, or inversion is an involution. *)\nTheorem inverse_involution : ∀ a, (a⁻¹)⁻¹ = a.\nProof.\n  intros a.\n  refine (cancel _ on the right by a⁻¹).\n    rewrite left_inverse.\n    rewrite right_inverse.\n    reflexivity.\nQed.\n\n(* The identity element is self-inverse. *)\nTheorem identity_inverse : e⁻¹ = e.\nProof.\n  refine (cancel _ on the right by e).\n    rewrite left_inverse.\n    rewrite right_identity.\n    reflexivity.\nQed.\n", "meta": {"author": "Echogene", "repo": "Oilar", "sha": "61383eee23d3b798e5dcb128dfd9fe5452f324ad", "save_path": "github-repos/coq/Echogene-Oilar", "path": "github-repos/coq/Echogene-Oilar/Oilar-61383eee23d3b798e5dcb128dfd9fe5452f324ad/Playground/Groups/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.7842655207341497}}
{"text": "Require Export Permutation.\nRequire Import Recdef.\nRequire List.\n\nImport List.ListNotations.\nOpen Scope list.\n\nSection Sorting.\n  Context {A:Type}.\n  Variable lt: A -> A -> bool.\n  Infix \"<?\" := lt (at level 20).\n\n  Fixpoint insert (x: A) (xs: list A) : list A :=\n    match xs with\n    | nil => [x]\n    | x'::xs' => if x <? x'\n                 then x::x'::xs'\n                 else x'::insert x xs'\n    end.\n\n  Hint Constructors Permutation : core.\n\n  Theorem inserted_permutation : forall x xs,\n      Permutation (x::xs) (insert x xs).\n  Proof.\n    induction xs; simpl; eauto.\n    destruct (x <? a); eauto.\n  Qed.\n\n  Fixpoint insert_sort (xs: list A) (acc: list A) : list A :=\n    match xs with\n      | nil => acc\n      | x::xs => insert_sort xs (insert x acc)\n    end.\n\n  Definition sort xs := insert_sort xs [].\n\n  Theorem insert_sort_permutation : forall xs acc,\n      Permutation (xs++acc) (insert_sort xs acc).\n  Proof.\n    induction xs; intros; simpl.\n    - auto.\n    - etransitivity; [ | eauto ].\n      pose proof (inserted_permutation a acc).\n      transitivity (xs ++ a :: acc).\n      apply Permutation_cons_app; auto.\n      apply Permutation_app; auto.\n  Qed.\n\n  Theorem sort_permutation : forall xs,\n      Permutation xs (sort xs).\n  Proof.\n    unfold sort.\n    intros.\n    replace xs with (xs ++ []) at 1.\n    apply insert_sort_permutation.\n    rewrite List.app_nil_r; auto.\n  Qed.\n\nEnd Sorting.\n\nRequire Import PeanoNat.\n\nDefinition sortBy {A} (key: A -> option nat) (xs: list A) : list A :=\n  sort (fun x y => Nat.leb (match key x with\n                            | Some n => S n\n                            | None => 0\n                            end)\n                           (match key y with\n                            | Some n => S n\n                            | None => 0\n                            end)) xs.\n\nTheorem sortBy_permutation : forall A key (xs: list A),\n    Permutation xs (sortBy key xs).\nProof.\n  unfold sortBy; intros.\n  apply sort_permutation.\nQed.\n", "meta": {"author": "tchajed", "repo": "coq-sep-logic", "sha": "d79864de2e6908c474a8b04f61be19fa4e2ab390", "save_path": "github-repos/coq/tchajed-coq-sep-logic", "path": "github-repos/coq/tchajed-coq-sep-logic/coq-sep-logic-d79864de2e6908c474a8b04f61be19fa4e2ab390/src/Reification/Sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.7841685471153593}}
{"text": "Inductive nat: Type :=\n    | O\n    | S (n: nat).\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 pred (n: nat) : nat :=\n    match n with\n    | O => O\n    | S n' => n'\n    end.\n\nCheck (S (S (S O))).\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 oodb (n: nat) : bool := negb (evenb n).\n\n(* Module Nat1. *)\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 (S (S O)) (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 fact (n: nat) : nat :=\n    match n with\n    | O => S O\n    | S n' => mult n (fact n')\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\nCompute (fact (S (S (S O)))).\n\nNotation \"x + y\" := (plus x y)\n    (at level 50, left associativity).\n\nNotation \"x * y\" := (plus x y)\n    (at level 40, left associativity).\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 with\n    | O => true\n    | S n' => match m with\n              | O => false\n              | S m' => leb n' m'\n              end\n    end.\n\nNotation \"x =? y\" := (eqb x y) \n    (at level 70).\nNotation \"x <=? y\" := (leb x y) \n    (at level 70).\n\n\n\nTheorem plus_O_n: forall n : nat, O + n = n.\nProof.\n    intros n. simpl. reflexivity.\nQed.\n\nTheorem plus_1_n: forall n : nat, (S O) + n = S n.\nProof.\n    intros n. simpl. reflexivity.\nQed.\n\nTheorem plus_id: forall n m: nat, n = m -> n + n = m + m.\nProof.\n    intros n m.\n    intros H.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem plus_id_exe: 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 K.\n    rewrite -> H.\n    rewrite -> K.\n    reflexivity.\nQed.\n\nTheorem mult_0_plus: forall n m : nat,\n    (O + n) * m = n * m.\nProof.\n    intros n m.\n    rewrite -> plus_O_n.\n    reflexivity.\nQed.\n\nTheorem mult_1_plus: forall n m : nat,\n    m = S n ->\n    m * ((S O) + n) = m * m.\nProof.\n    intros n m.\n    intros H.\n    rewrite -> plus_1_n.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem plus_1_eq_0 : forall n : nat,\n    (n + (S O)) =? O = false.\nProof.\n    intros n.\n    destruct n as [| n'] eqn: E.\n    - reflexivity.\n    - reflexivity.\nQed.\n\nTheorem negneg: forall b: bool,\n    negb (negb b) = b.\nProof.\n    intros b.\n    destruct b eqn: E.\n    - reflexivity.\n    - reflexivity.\nQed.\n\nDefinition andb (b1: bool) (b2: bool) : bool :=\n    match b1 with\n    | true => b2\n    | false => false\n    end.\n\nTheorem andbcom: forall b c,\n    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(* Theorem andb_exch: forall b c d,\n    andb (andb b c) d = andb b (andb c d).\nProof.\n    intros [] [] [].\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\n    - reflexivity.\nQed. *)\n\nTheorem andtrue: forall b c:bool, \n    (andb b c = true) -> (c = true).\nProof.\n    intros b c.\n    intro H.\n    destruct c eqn: Ec.\n        - reflexivity.\n        - rewrite <- H.\n            destruct b eqn: Eb.\n            + reflexivity.\n            + reflexivity.\nQed.\n\nTheorem id_f_app2: \n    forall (f: bool -> bool),\n    (forall (x: bool), f x = x) ->\n        forall (b: bool), f (f b) = b.\nProof.\n    intros f x.\n    intro b.\n    destruct b eqn: Eb.\n        - rewrite <- x.\n          rewrite <- x.\n          reflexivity.\n        - rewrite <- x.\n          rewrite <- x.\n          reflexivity.\nQed.\n\nDefinition orb (b1: bool) (b2: bool) : bool :=\n    match b1 with\n    | true => true\n    | false => b2\n    end.\n\nTheorem andb_eq_orb: forall (b c: bool),\n    (andb b c = orb b c) -> b = c.\nProof.\n    destruct b.\n    - destruct c.\n      reflexivity.\n      intro H.\n      inversion H.\n    - destruct c.\n      intro H.\n      inversion H.\n      reflexivity.\nQed.\n", "meta": {"author": "Meowcolm024", "repo": "sf", "sha": "8ec734274600d60b0b7e905bb3d861779031bee8", "save_path": "github-repos/coq/Meowcolm024-sf", "path": "github-repos/coq/Meowcolm024-sf/sf-8ec734274600d60b0b7e905bb3d861779031bee8/lf/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7840534713791746}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nAdd LoadPath \"/Users/Josh/Downloads/software foundations/lf/\".\nSet Warnings \"-notation-overridden,-parsing\".\nRequire 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 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. induction n as [|n' IHn'].\n  - simpl. apply ev_0.\n  - simpl. apply ev_SS, IHn'. Qed.\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 (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\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\nTheorem even5_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 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'). 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.\n  intros n m Hn Hm.\n  induction Hn as [|n' Hn' IHn'].\n  - simpl. apply Hm.\n  - simpl. apply ev_SS. apply IHn'.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (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\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 *) Admitted.\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.\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  leb 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  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(** **** 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.\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, optional (reg_exp_of_list)  *)\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)  *)\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.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\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-10-09 14:36:24 -0400 (Mon, 09 Oct 2017) $ *)\n", "meta": {"author": "jtscuba", "repo": "LogicalFoundations", "sha": "345d6f856fbbbe4fcee5bc7cbe32f58755ca52ed", "save_path": "github-repos/coq/jtscuba-LogicalFoundations", "path": "github-repos/coq/jtscuba-LogicalFoundations/LogicalFoundations-345d6f856fbbbe4fcee5bc7cbe32f58755ca52ed/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.7839987778485872}}
{"text": "Require Import FunctionalExtensionality.\n\nDefinition Seq{A:Type} := nat -> A.\n\n\nDefinition sin{A : Type}(a : A)(q: Seq(A:=A)) := exists i, a = q i.\n\nLemma sin_nth{A:Type}(q: Seq(A:=A)): forall n,  sin (q n) q.\nProof.\nintro n.\nnow exists n.\nQed.\n\nDefinition increasing {A: Type} (R: A -> A -> Prop)(q : Seq) : Prop  :=\n  forall n,  R (q n) (q (S n)).\n\n\nDefinition strictly_increasing{A : Type}(R: A -> A -> Prop)(q : Seq(A := A)) :=\n  increasing R q /\\\nforall n,  ~R (q (S n)) (q n).\n\n\nLemma increasing_snth{A : Type}\n      (R : A -> A -> Prop)\n      (RRefl : forall a,  R a a)\n      (Rtrans : forall a b c,  R a b -> R b c -> R a c)\n  : forall (q: Seq (A := A)),\n    increasing R q  -> forall (i j : nat),  i <= j -> R (q i) (q j).\nProof.\nintros q Hr i j Hle.\ninduction Hle.\n*\n  apply RRefl.\n*\n  specialize (Hr m).\n  eapply Rtrans  ; eauto.\nQed.\n\n\nDefinition lub{A: Type} (R : A -> A-> Prop) (lub_val: A) (q : Seq(A:=A)) :=\n  (forall a, sin a q -> R a lub_val) /\\\n  (forall lub_val',  (forall a, sin a q -> R a lub_val')  -> R lub_val lub_val').\n", "meta": {"author": "hidden-author", "repo": "ecoop22-coq-code", "sha": "e21dac0441f2478c0dd07a9d3a043b91ab0c7061", "save_path": "github-repos/coq/hidden-author-ecoop22-coq-code", "path": "github-repos/coq/hidden-author-ecoop22-coq-code/ecoop22-coq-code-e21dac0441f2478c0dd07a9d3a043b91ab0c7061/first_method/streams/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8333245911726381, "lm_q1q2_score": 0.7839832304135883}}
{"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\nFixpoint rotate (rotate_arg0 : Nat) (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. rewrite <- append_assoc. rewrite IHx. rewrite <- append_assoc. reflexivity.\n- intros. simpl. rewrite lem3. 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/goal21.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7839196606626168}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\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\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.\n  intro.\n  reflexivity.\nQed.\n\nTheorem n_plus_O : forall n : nat, plus n O = n.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nCheck nat_ind.\n\nTheorem S_inj : forall n m : nat, S n = S m -> n = m.\n  injection 1.\n  trivial.\nQed.\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 : forall ls1 ls2 : nat_list,\n    nlength (napp ls1 ls2) = 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 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).\n  induction n1;\n    crush.\nQed.\n\nTheorem nsize_nsplice : forall tr1 tr2 : nat_btree,\n    nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1).\n  induction tr1;\n    crush.\n  rewrite plus_assoc.\n  reflexivity.\nQed.\n\n", "meta": {"author": "ytakano", "repo": "cpdt", "sha": "04c8ffb185fe02b6ed4ee9e15f8a724c05d28c20", "save_path": "github-repos/coq/ytakano-cpdt", "path": "github-repos/coq/ytakano-cpdt/cpdt-04c8ffb185fe02b6ed4ee9e15f8a724c05d28c20/src/chap3-3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088002, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7839196512685939}}
{"text": "Section Ejercicio3.\n\nDefinition Value := bool.\n\nInductive BoolExpr : Set :=\n    bbool : bool -> BoolExpr\n  | band : BoolExpr -> BoolExpr -> BoolExpr\n  | bnot : BoolExpr -> BoolExpr.\n\n\nInductive BEval : BoolExpr -> Value -> Prop :=\n   ebool : forall b : bool, BEval (bbool b) (b : Value)\n | eandl : forall e1 e2 : BoolExpr, BEval e1 false -> BEval (band e1 e2) false\n | eandr : forall e1 e2 : BoolExpr, BEval e2 false -> BEval (band e1 e2) false\n | eandrl : forall e1 e2 : BoolExpr, BEval e1 true -> BEval e2 true -> BEval (band e1 e2) true\n | enott : forall e : BoolExpr, BEval e true -> BEval (bnot e) false\n | enotf : forall e : BoolExpr, BEval e false -> BEval (bnot e) true.\n\nFixpoint beval1 (e : BoolExpr) : Value :=\n  match e with\n    bbool b => b\n  | band e1 e2 => match beval1 e1, beval1 e2 with\n                    true, true => true\n                  | _, _ => false\n                  end\n  | bnot e1 => if beval1 e1\n              then false\n              else true\n  end.\n\nFixpoint beval2 (e : BoolExpr) : Value :=\n  match e with\n    bbool b => b\n  | band e1 e2 => match beval2 e1 with\n                    false => false\n                  | _ => beval2 e2\n                  end\n  | bnot e1 => if beval2 e1\n              then false\n              else true\n  end.\n\n(*1*)\nLemma beval1C : forall e : BoolExpr, {b : Value | BEval e b}.\nProof.\nintro.\nexists (beval1 e).\ninduction e.\n- constructor.\n- simpl.\n  destruct (beval1 e1).\n  destruct (beval1 e2).\n  + constructor; assumption.\n  + apply eandr; assumption.\n  + constructor; assumption.\n- simpl.\n  destruct (beval1 e); constructor; assumption.\nQed.\n\nLemma beval2C : forall e : BoolExpr, {b : Value | BEval e b}.\nProof.\nintro.\nexists (beval2 e).\ninduction e.\n- constructor.\n- simpl.\n  destruct (beval2 e1).\n  destruct (beval2 e2).\n  + constructor; assumption.\n  + apply eandr; assumption.\n  + constructor; assumption.\n- simpl.\n  destruct (beval2 e); constructor; assumption.\nQed.\n\n(*2*)\nHint Constructors BEval.\nLemma beval1CBis : forall e : BoolExpr, {b : Value | BEval e b}.\nProof.\nintro.\nexists (beval1 e).\ninduction e.\n- auto.\n- simpl.\n  destruct (beval1 e1); auto.\n  destruct (beval1 e2); auto.\n- simpl.\n  destruct (beval1 e); auto.\nQed.\n\nLemma beval2CBis : forall e : BoolExpr, {b : Value | BEval e b}.\nProof.\nintro.\nexists (beval2 e).\ninduction e.\n- auto.\n- simpl.\n  destruct (beval2 e1); auto.\n  destruct (beval2 e2); auto.\n- simpl.\n  destruct (beval2 e); auto.\nQed.\nEnd Ejercicio3.\n\nExtraction Language Haskell.\nExtraction \"/Users/flor.rovere/Desktop/beval1CBis_function\" beval1CBis.\n\nExtraction Language Haskell.\nExtraction \"/Users/flor.rovere/Desktop/beval2CBis_function\" beval2CBis.\n\nExtract Inductive bool => \"Bool\" [\"true\" \"false\"].\nExtraction Language Haskell.\nExtraction \"/Users/flor.rovere/Desktop/beval1CBis_function2\" beval1CBis.\n\nExtraction Language Haskell.\nExtraction \"/Users/flor.rovere/Desktop/beval2CBis_function2\" beval2CBis.\n\nSection Ejercicio5.\n(*1*)\nInductive Le : nat -> nat -> Prop :=\n    Le0 : forall n, Le 0 n\n  | LeS : forall n m, Le n m -> Le (S n) (S m).\n\nInductive Gt : nat -> nat -> Prop :=\n    Gt0 : forall n, Gt (S n) 0\n  | GtS : forall n m, Gt n m -> Gt (S n) (S m).\n\nHint Constructors Le.\nHint Constructors Gt.\n\n(*2*)\nFunction leBool (n m : nat) : bool :=\n  match n, m with\n    0, _ => true\n  | S n1, 0 => false\n  | S n1, S m1 => leBool n1 m1\n  end.\n\nLemma Le_Gt_dec : forall n m : nat, {(Le n m)} + {(Gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m).\n- left; auto.\n- right; auto.\n- elim IHb; intros; [left | right]; auto.\nQed.\n\n(*3*)\nRequire Import Omega.\nLemma le_gt_dec : forall n m : nat, {(le n m)} + {(gt n m)}.\nProof.\nintros.\nfunctional induction (leBool n m).\n- left; omega.\n- right; omega.\n- elim IHb; intros; [left | right]; omega.\nQed.\nEnd Ejercicio5.\n\nSection Ejercicio6.\nRequire Import Omega.\nRequire Import DecBool.\nRequire Import Compare_dec.\nRequire Import Plus.\nRequire Import Mult.\n\nDefinition spec_res_nat_div_mod (a b : nat) (qr : nat * nat) :=\n  match qr with\n    (q, r) => (a = b * q + r) /\\ r < b\n  end.\n\nDefinition nat_div_mod :\n  forall a b : nat, not (b = 0) -> {qr : nat * nat | spec_res_nat_div_mod a b qr}.\nProof.\nintros a b hip.\nunfold spec_res_nat_div_mod.\ninduction a.\n- exists (0,0).\n  omega.\n- elim IHa; intros.\n  destruct x.\n  case (lt_dec n0 (b-1)); intros.\n  + exists (n, n0+1).\n    omega.\n  + exists (n + 1, 0).\n    split.\n    * { elim p; intros.\n        assert (n0 = b-1).\n        - omega.\n        - rewrite -> H1 in H.\n          rewrite H.\n          rewrite -> mult_plus_distr_l.\n          omega.\n      }\n    * omega.\nQed.\nEnd Ejercicio6.\n\nSection Ejercicio7.\nInductive tree (A : Set) : Set :=\n    leaf : tree A\n  | node : A -> tree A -> tree A -> tree A.\n\nInductive tree_sub (A : Set) (t : tree A) : tree A -> Prop :=\n    tree_sub1 : forall (t1 : tree A) (x : A), tree_sub A t (node A x t t1)\n  | tree_sub2 : forall (t1 : tree A) (x : A), tree_sub A t (node A x t1 t).\n\nTheorem well_founded_tree_sub : forall A : Set, well_founded (tree_sub A).\nProof.\nintro.\nunfold well_founded; intro t.\ninduction t; apply Acc_intro; intros; inversion H; auto.\nQed.\nEnd Ejercicio7.\n\nSection Ejercicio8.\n(*1*)\nFunction size (b : BoolExpr) : nat :=\n  match b with\n    bbool _ => 0\n  | band l r => 1 + (size l) + (size r)\n  | bnot b => 1 + (size b)\n  end.\n\nDefinition elt (e1 e2 : BoolExpr) := size e1 < size e2.\n\n(*2*)\nRequire Import Wf_nat.\nRequire Import Inverse_Image.\n\nTheorem well_founded_elr : well_founded elt.\nProof.\napply (wf_inverse_image BoolExpr nat lt size).\napply lt_wf.\nQed.\nEnd Ejercicio8.", "meta": {"author": "flor-rovere", "repo": "CFPTT", "sha": "afc808dd39600469217e65322e8112ebc0bc228d", "save_path": "github-repos/coq/flor-rovere-CFPTT", "path": "github-repos/coq/flor-rovere-CFPTT/CFPTT-afc808dd39600469217e65322e8112ebc0bc228d/Práctico6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.7838582659825983}}
{"text": "Require Import Ring.\nRequire Import ZArith.\nRequire Import Init.Datatypes.\n\nOpen Scope Z_scope.\n\nDefinition G : Type := Z * Z.\n\nDefinition G0: G := (0, 0).\nDefinition G1: G := (1, 0).\n\nDefinition Gadd (g1 g2 : G) : G := (fst g1 + fst g2, snd g1 + snd g2).\nDefinition Gsub (g1 g2 : G) : G := (fst g1 - fst g2, snd g1 - snd g2).\nDefinition Gmul (g1 g2 : G) : G := (fst g1 * fst g2 - snd g1 * snd g2, fst g1 * snd g2 + snd g1 * fst g2).\nDefinition Gopp (g : G) : G := (- fst g, - snd g).\n\nLemma Gadd_0_l: forall (g: G),\n  Gadd G0 g = g.\nProof.\n  intros. destruct g. reflexivity.\nQed.\n\nLemma Gadd_comm: forall (g1 g2: G),\n  Gadd g1 g2 = Gadd g2 g1.\nProof.\n  intros. destruct g1. destruct g2. unfold Gadd. simpl.\n  rewrite Zplus_comm. rewrite Zplus_comm with (z0) (z2).\n  reflexivity.\nQed. \n\nLemma Gadd_assoc: forall g1 g2 g3: G,\n  Gadd g1 (Gadd g2 g3) = Gadd (Gadd g1 g2) g3.\nProof.\n  intros. destruct g1. destruct g2. destruct g3.\n  unfold Gadd. simpl. rewrite Zplus_assoc. \n  rewrite Zplus_assoc with (z0) (z2) (z4).\n  reflexivity.\nQed. \n\nLemma Gmul_1_l: forall g : G, \n  Gmul G1 g = g.\nProof.\n  intros. unfold Gmul. unfold G1. destruct g. \nAdmitted.\n\nLemma Gmul_comm: forall g1 g2 : G, \n  Gmul g1 g2 = Gmul g2 g1.\nProof.\n  intros. unfold Gmul. destruct g1. destruct g2.\n  simpl. rewrite Zmult_comm. \n  rewrite Zmult_comm with (z0) (z2).\n  rewrite Zplus_comm with (z * z2) (z0 * z1).\n  rewrite Zmult_comm with (z0) (z1).\n  rewrite Zmult_comm with (z) (z2).\n  reflexivity.\nQed.\n\nLemma Gmul_assoc: forall g1 g2 g3 : G, \n  ( Gmul g1 (Gmul g2 g3) ) = ( Gmul (Gmul g1 g2) g3 ).\nProof.\n  Admitted.\n\nLemma Gdistr_l: forall g1 g2 g3: G, \n  Gmul (Gadd g1 g2) g3 = Gadd (Gmul g1 g3) (Gmul g2 g3).\nProof.\n  Admitted.\n\nLemma Gopp_def : forall g : G,\n  Gadd g (Gopp g) = G0.\nProof.\n  intros. unfold Gadd. unfold Gopp. destruct g. \n  simpl. rewrite Z.add_opp_diag_r. rewrite Z.add_opp_diag_r.\n  reflexivity.\nQed.\n\nLemma R_Ring_Theory : ring_theory G0 G1 Gadd Gmul Gsub Gopp eq.\nProof.\n  constructor. \n  - apply Gadd_0_l.\n  - apply Gadd_comm.\n  - intros; rewrite Gadd_assoc; easy.\n  - apply Gmul_1_l.\n  - apply Gmul_comm.\n  - intros; rewrite Gmul_assoc; easy.\n  - apply Gdistr_l.\n  - reflexivity.\n  - apply Gopp_def.\nDefined.\nAdd Ring RRing : R_Ring_Theory.\n\nDeclare Scope G_scope.\nBind Scope G_scope with G.\nOpen Scope G_scope.\n\nInfix \"+\" := Gadd : G_scope.\nNotation \"- x\" := (Gopp x) : G_scope.\nInfix \"-\" := Gsub : G_scope.\nInfix \"*\" := Gmul : G_scope.\n\nDefinition ZtoG (z : Z) : G := (z, 0).\nCoercion ZtoG : Z >-> G.\n\nTheorem ring_exercise: forall (g1 g2 : G),\n  (g1 + g2) * (g1 + g2) = g1 * g1 + (2, 0) * g1 * g2 + g2 * g2.\nProof.\n  intros. ring_simplify. 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/Ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7838505328999237}}
{"text": "Require Import Ensembles.\n\n\nClass Totalorder (S : Set) (LT : S -> S -> Prop) :=\n{ antisym : forall a b, LT a b -> LT b a -> a = b\n; trans : forall a b c, LT a b -> LT b c -> LT a c\n; connex : forall a b, LT a b /\\ LT b a\n}.\n\nDefinition UpperBound {A} {LT} {ord : Totalorder A LT} (E : Ensemble A) (b: A) : Prop\n  := forall a, In _ E a -> LT a b.\n\nDefinition LeastUpperBound {A} {LT} {ord : Totalorder A LT} (E : Ensemble A) (b: A) : Prop\n  := UpperBound E b /\\ (forall c, b = c /\\ UpperBound E c -> LT b c).\n\nDefinition UpperBounded {A} {LT} {ord : Totalorder A LT} (E : Ensemble A): Prop\n  := exists b, UpperBound E b.\n\nDefinition UpperBoundProperty A LT {ord : Totalorder A LT} : Prop\n  := forall E : Ensemble A, UpperBounded E -> exists b, LeastUpperBound E b.\n\nDefinition LowerBound {A} {LT} {ord : Totalorder A LT} (E : Ensemble A) (b: A) : Prop\n  := forall a, In _ E a -> LT b a.\n\nDefinition GreatestLowerBound {A} {LT} {ord : Totalorder A LT} (E : Ensemble A) (b: A)\n  := LowerBound E b /\\ (forall c, b = c /\\ LowerBound E c -> LT c b).\n\nDefinition LowerBounded {A} {LT} {ord : Totalorder A LT} (E : Ensemble A): Prop\n  := exists b, LowerBound E b.\n\nDefinition LowerBoundProperty A LT {ord : Totalorder A LT} : Prop\n  := forall E : Ensemble A, LowerBounded E -> exists b, GreatestLowerBound E b.\n", "meta": {"author": "IronCretin", "repo": "real-analysis-proofs", "sha": "f7b45403a8f6042cac6ded2b1e9e4d24c688bab4", "save_path": "github-repos/coq/IronCretin-real-analysis-proofs", "path": "github-repos/coq/IronCretin-real-analysis-proofs/real-analysis-proofs-f7b45403a8f6042cac6ded2b1e9e4d24c688bab4/Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7838335656641132}}
{"text": "Require Export Iron.Language.SystemF2Effect.Type.Exp.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.WfT.\nRequire Import Coq.Bool.Bool.\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", "meta": {"author": "DonaldKellett", "repo": "iron-lambda", "sha": "0ce17223c4ff2c65549ead3f9905f60adfd6a40a", "save_path": "github-repos/coq/DonaldKellett-iron-lambda", "path": "github-repos/coq/DonaldKellett-iron-lambda/iron-lambda-0ce17223c4ff2c65549ead3f9905f60adfd6a40a/done/Iron/Language/SystemF2Effect/Type/Relation/FreeT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7837871629557165}}
{"text": "Require Import Unicode.Utf8.\nRequire Import Game.Mynat.Definition.\nRequire Import Game.Mynat.Mul.\n\nFixpoint pow (a n : mynat) : mynat :=\nmatch n with\n| 0 => 1\n| succ n' => pow a n' * a\nend.\n\nNotation \"a ^ n\" := (pow a n).\n\nLemma pow_zero (a : mynat) : a ^ (0 : mynat) = 1 .\nProof.\n  reflexivity.\nQed.\n\nLemma pow_succ (a n : mynat) : a ^ (succ n) = a ^ n * a .\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "uncomputable", "repo": "natural-number-game", "sha": "602e06e352f1accb13ef1a1a23f40c19d10c5444", "save_path": "github-repos/coq/uncomputable-natural-number-game", "path": "github-repos/coq/uncomputable-natural-number-game/natural-number-game-602e06e352f1accb13ef1a1a23f40c19d10c5444/Game/Mynat/Pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275046683696, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.783772375551117}}
{"text": "(** Gustavo M. Bonassa e Victor K. Neitzel *)\n\nFrom LF Require Export Poly.\n\n(** * Métodos Formais - Lista de Exercícios 2 *)\n\n\n(** Informalmente podemos dizer que o seguinte teorema estabelece a \n    comutatividade da função [fold] em relação a concatenação ([++]), \n    prove este teorema: *)\n \nTheorem app_comm_fold :forall {X Y} (f: X->Y->Y) l1 l2 b,\n  fold f (l1 ++ l2) b = fold f l1 (fold f l2 b).\nProof.\n  intros X Y a l1 l2 H.\n  induction l1 as [|x HL].\n  - simpl. reflexivity.\n  - simpl. rewrite IHHL. reflexivity.\nQed.\n\n(*intros a b c d e f.\n  destruct d.\n  - simpl. reflexivity.\n  - simpl. *)\n\n(** Como visto no módulo [Poly.v], muitas funções sobre listas podem ser \n    implementadas usando a função [fold], por exemplo, a função \n    que retorna o número de elementos de uma listas pode ser implementada \n    como: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\n(** Prove que [fold_length] retorna ao número de elementos de uma lista.\n    Para facilitar essa prova demostre o lema [fold_length_head]. Dica:\n    as vezes a tática [reflexivty] aplica uma simplificação mais agressiva \n    que a tática [simpl], isso seŕá util na prova desse lema. *) \n\nLemma fold_length_head : forall X (h : X) (t : list X),\n  fold_length (h::t) = S (fold_length t).\nProof. reflexivity. Qed.\n\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros Y l.\n  unfold fold_length. \n  induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(** Também é possível definir a função [map] por meio da função [fold],\n    faça essa definição: *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\nfold (fun x xs => f x :: xs) l [].\n\nExample test_fold_map : fold_map (mult 2) [1; 2; 3] = [2; 4; 6].\nProof. reflexivity. Qed.\n\n(** Prove que [fold_map] tem um comportamento identico a [map], defina lemas \n    auxiliares se necessário: *)\n\nTheorem fold_map_correct : forall X Y (f: X -> Y) (l: list X),\n  fold_map f l = map f l.\nProof.\n  induction l. unfold fold_map. reflexivity.\n  unfold fold_map. \n  simpl. unfold fold_map in IHl. \n  rewrite IHl.\n  reflexivity.\nQed.\n\n(** Podemos imaginar que a função [fold] coloca uma operação binária entre\n    cada elemento de uma lista, por exemplo, [fold plus [1; 2; 3] 0] é igual \n    (1+(2+(3+0))). Da forma que foi declarada a função [fold] a operação \n    binária é executada da direita para esquerda. Declare uma função [foldl]\n    que aplique a operação da esquerda para direita: *)\n\nFixpoint foldl {X Y: Type} (f: Y->X->Y) (b: Y) (l: list X) : Y :=\nmatch l with\n  | nil => b\n  | h :: t => f (foldl f b t) h\n  end.\n\n(** Exemplo: [foldl minus 10 [1; 2; 3]] igual (((10-1)-2)-3). *)\n\nExample test_foldl : foldl minus 10 [1; 2; 3] = 4.\nProof. reflexivity. Qed.\n\n\n\n\n", "meta": {"author": "gustavobonassa", "repo": "Coq", "sha": "e2657c97272e56ff2b5bcd4a53b78eeb93fc7e82", "save_path": "github-repos/coq/gustavobonassa-Coq", "path": "github-repos/coq/gustavobonassa-Coq/Coq-e2657c97272e56ff2b5bcd4a53b78eeb93fc7e82/ListaExer2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.7837225818724392}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Examples for other tactics provided by TLC                              *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics.\n\n\n(* ********************************************************************** *)\n(** * How to do recursion/induction on terms with list of subterms *)\n\nModule SubtermIndDemos.\n\nRequire Import LibLogic LibList.\n\n(** Definition of trees with list of subtrees *)\n\nInductive tree : Type := \n  | leaf : nat -> tree\n  | node : list tree -> tree.\n\n(** Example of a primitive-recursive function on trees \n    using an inlined fixed point -- not recommended *)\n\nFixpoint tree_incr' (t:tree) :=\n  match t with\n  | leaf n => leaf (S n)\n  | node ts => \n     node ((fix aux ts := match ts with\n            | nil => nil\n            | t::ts' => tree_incr' t :: aux ts'\n            end) ts)\n  end.\n\n(** Same example but using the map function on lists \n    -- recommended\n    -- this works only because List.map has exactly\n    the same form as the local [fix] used above. \n    -- if you wanted to use LibList.map instead of \n    List.map, it would not work; you would have to\n    either use the optimal fixed point (see LibFixDemos)\n    or you would have to exploit [List.map = LibList.map] *)\n\nFixpoint tree_incr (t:tree) :=\n  match t with\n  | leaf n => leaf (S n)\n  | node ts => node (List.map tree_incr ts)\n  end.\n\n(** Another example -- recommended *)\n\nFixpoint tree_map (f:nat->nat) (t:tree) :=\n  match t with\n  | leaf n => leaf (f n)\n  | node ts => node (List.map (tree_map f) ts)\n  end.\n\n(** Another example using List.fold -- recommended *)\n\nFixpoint tree_sum (t:tree) :=\n  match t with\n  | leaf n => n\n  | node ts => List.fold_left (fun acc t => acc + tree_sum t) ts 0\n  end.\n\n(** Proof of the recursion principle *)\n\nSection Tree_induct.\n(* Note: some hypotheses are given directly by [Check tree_ind] *)\nVariables\n(P : tree -> Prop)\n(Q : list tree -> Prop) \n(P1 : forall n, P (leaf n)) \n(P2 : forall ts, Q ts -> P (node ts)) \n(Q1 : Q nil)\n(Q2 : forall t ts, P t -> Q ts -> Q (t::ts)).\n\nFixpoint tree_induct_gen (t : tree) : P t :=\n  match t as x return P x with\n  | leaf n => P1 n\n  | node ts => P2\n      ((fix tree_list_induct (ts:list tree) : Q ts :=\n      match ts as x return Q x with \n      | nil   => Q1\n      | t::ts' => Q2 (tree_induct_gen t) (tree_list_induct ts')\n      end) ts)\n  end.\n\nEnd Tree_induct.\n\n(** Example of a direct inductive proof -- not recommended *)\n\nLemma tree_map_pred_succ_1 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof.\n  intros. pattern t. match goal with |- ?F _ => sets P: F end.\n  eapply tree_induct_gen with (Q := Forall P); subst P; simpl; intros.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    inverts H. fequals~.\n  constructors.\n  constructors~. \nQed.  \n\n(** Proof of the induction principle with Forall *)\n\nLemma tree_induct_forall : forall (P : tree -> Prop),\n  (forall n : nat, P (leaf n)) ->\n  (forall ts : list tree, Forall P ts -> P (node ts)) ->\n  forall t : tree, P t.\nProof.\n  introv Hl Hn. eapply tree_induct_gen with (Q := Forall P); intros.\n  auto. auto. constructors~. constructors~.\nQed.\n\n(** Example of an inductive proof with Forall \n    -- recommended *)\n\nLemma tree_map_pred_succ_2 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof.\n  intros. induction t using tree_induct_forall; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    auto.\n    inverts H. fequals~.\nQed.\n\n(** Proof of the induction principle with Mem *)\n\nLemma tree_induct_mem : forall (P : tree -> Prop),\n  (forall n : nat, P (leaf n)) ->\n  (forall ts : list tree, \n    (forall t, Mem t ts -> P t) -> P (node ts)) ->\n  forall t : tree, P t.\nProof.\n  introv Hl Hn. eapply tree_induct_gen with (Q := fun ts =>\n    forall t, Mem t ts -> P t); intros.\n  auto. auto. inverts H. inverts~ H1. \nQed.\n\nHint Constructors Mem.\n\n(** Example of an inductive proof with Mem  \n    -- usually not as good as the one with [Forall] *)\n\nLemma tree_map_pred_succ_3 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof.\n  intros. induction t using tree_induct_mem; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    fequals.\n      apply H. constructor.\n      apply IHts. introv M. apply H. auto.\nQed.\n\n(** Definition of the relation \"immediate subtree of\" *)\n\nRequire Import LibRelation LibWf.\n\nInductive subtree : binary tree :=\n  | subtree_intro : forall t ts, \n     Mem t ts -> subtree t (node ts). \n  (* there is typically more than one case here *)\n\nHint Constructors subtree.\n\n(** Proof of well-foundedness of the subtree relation *)\n\nLemma subtree_wf : wf subtree.\nProof.\n  intros t. induction t using tree_induct_mem;\n  constructor; introv K; inversions~ K.\nQed.\n\n(** Example of a proof on the well-founded subtree order\n    -- usually a bit longer, so not recommended *)\n\nLemma tree_map_pred_succ_4 : forall t,\n  tree_map pred (tree_map S t) = t.\nProof.\n  intros. induction_wf IH: subtree_wf t.\n  destruct t as [|ts]; simpl.\n  fequals.\n  fequals. induction ts; simpl.\n    fequals.\n    fequals.\n      applys IH. auto.\n      applys IHts. introv M. inverts M.\n       auto. (* apply IH. constructors. constructors. *)\nQed.\n\nEnd SubtermIndDemos.\n\n\n(* ********************************************************************** *)\n(** * Tactics exported by LibVar *)\n\nModule LibVarDemos.\nRequire Import LibList LibLN.\nSection LibVarDemo.\nImplicit Types x y : var.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo for notin *)\n\nLemma test_notin_solve_1 : forall x E F G,\n  x \\notin E \\u F -> x \\notin G -> x \\notin (E \\u G).\nProof. \n  intros. dup. \n  notin_simpl. notin_solve. notin_solve.\n  notin_solve.\nQed.\n\nLemma test_notin_solve_2 : forall x y E F G,\n  x \\notin E \\u \\{y} \\u F -> x \\notin G ->\n  x \\notin \\{y} /\\ y \\notin \\{x}.\nProof.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_solve_3 : forall x y,\n  x <> y -> x \\notin \\{y} /\\ y \\notin \\{x}.\nProof.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_solve_4 : forall x y,\n  x \\notin \\{y} -> x <> y /\\ y <> x.\nProof.\n  split. notin_solve. notin_solve.\nQed.\n\nLemma test_notin_false_1 : forall x y E F G,\n  x \\notin (E \\u \\{x} \\u F) -> y \\notin G.\nProof. \n  intros. dup 3.\n    false. notin_false.\n    notin_false.\n    notin_false.\nQed.\n\nLemma test_notin_false_2 : forall x y : var,\n  x <> x -> y = x.\nProof. \n  intros. notin_false.\nQed.\n\nLemma test_neq_solve : forall x y E F,\n  x \\notin (E \\u \\{y} \\u F) -> y \\notin E ->\n  y <> x /\\ x <> y.\nProof.\n  split. notin_solve. notin_solve.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo for fresh *)\n\nLemma test_fresh_solve_1 : forall xs L1 L2 n,\n  fresh (L1 \\u L2) n xs -> fresh L1 n xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_2 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh L2 n xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_3 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh \\{} n xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_4 : forall xs L1 L2 n,\n fresh (L1 \\u L2) n xs -> fresh L1 (length xs) xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_5 : forall xs L1 n m,\n  m = n ->\n  fresh L1 m xs -> \n  fresh L1 n xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_6 : forall xs L1 L2 n m,\n  m = n ->\n  fresh (L1 \\u L2) n xs -> \n  fresh L1 m xs.\nProof. \n  intros. fresh_solve.\nQed.\n\nLemma test_fresh_solve_7 : forall xs L1 L2 n m,\n  n = m ->\n  fresh (L1 \\u L2) n xs -> \n  fresh L1 m xs.\nProof. \n  intros. fresh_solve.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of automation of [notin] *)\n\n(* LibVar exports the following hints:\n     Hint Extern 1 (_ \\notin _) => notin_solve.\n     Hint Extern 1 (_ <> _ :> var) => notin_solve.\n     Hint Extern 1 ((_ \\notin _) /\\ _) => splits. *)\n\nLemma test_notin_by_auto : forall x E F G,\n  x \\notin E \\u F -> x \\notin G -> x \\notin (E \\u G).\nProof. auto. Qed.\n\nLemma test_neq_by_auto : forall x y E,\n  x \\notin E \\u \\{y} -> y <> x.\nProof. auto. Qed.\n\nLemma test_notin_false_by_hand : forall x,\n  ~ x \\notin \\{x}.\nProof. intros_all. notin_false. Qed.\n\nHint Extern 1 (~ _ \\notin _) => intros_all; notin_false.\n\nLemma test_notin_false_by_auto : forall x,\n  ~ x \\notin \\{x}.\nProof. intros_all. notin_false. Qed.\n\n(* Comment: using the following hint is a bad idea because it will\n            lead to very inefficient proof scripts.\n   Hint Extern 1 (False) => notin_false. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Demo of pick_fresh_gen *)\n\nParameter trm : Type.\nParameter fv : trm -> vars.\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 : trm => fv x) in\n  constr:(A \\u B \\u C).\n\nLtac pick_fresh Y :=\n  let L := gather_vars in (pick_fresh_gen L Y).\n\nLemma test_pick_fresh :\n  forall (x y z : var) (L1 L2 L3 : vars) (t1 t2 : trm), True.\nProof.\n  intros. pick_fresh a.\nAdmitted.\n\nEnd LibVarDemo.\nEnd LibVarDemos.\n\n\n\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/LibOtherDemos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.9136765292901317, "lm_q1q2_score": 0.783722575136905}}
{"text": "(**\nTanay Gavankar\ntgavanka\n15-414 F12\n*)\n\n(****************Homework 3************Due: 3pm Oct. 3rd*****************************************************)\n(*****To prove some of the following theorems, you may need to first prove some lemmas.***************************)\n(*****You are welcome to use whatever is proved in the class in Basics.v and Lists.v *****************************)\n(*****For this homework, automatic tactics of Coq (auto, tauto, trivial, intuition, omega, etc.) are not allowed.*)\n\n(***********************************************************************)\n(***** Submit solutions in a single coq file via email to the TAs ******)\n(***********************************************************************)\n\n\n\n\n\n\n\n\n(******************************* question 1*******************************************************8 points*)\n(** Prove [andb_true_elim2], marking cases (and subcases) when\n    you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\nintros.\ndestruct c.\n(* Case c = true *)\nreflexivity.\n(* Case c = false *)\nrewrite <- H.\ndestruct b.\n(* Case b = true *)\nreflexivity.\n(* Case b = false *)\nreflexivity.\nQed.\n\n(******************************* question 2*******************************************************16 points*)\n\n(*a*)\nTheorem plus_assoc : forall n m p : nat,\nn + (m + p) = (n + m) + p.\nProof.\nintros.\ninduction n.\nreflexivity.\nsimpl.\nrewrite -> IHn.\nreflexivity.\nQed.\n\n(*b*)\nTheorem plus_distr : forall n m: nat, S (n + m) = n + (S m).\nProof.\nintros.\ninduction n.\ninduction m.\nsimpl.\nreflexivity.\nrewrite <- IHm.\nsimpl.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\n(*c*)\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\nintros.\ninduction n.\ninduction m.\nreflexivity.\nsimpl.\nrewrite <- IHm.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHn.\napply plus_distr.\nQed.\n(** [] *)\n\n(*d*)\n(** Translate your solution for [plus_comm] into an informal proof. *)\n\n(** Theorem: Addition is commutative.\n             forall n m : nat, n + m = m + n\n \n    Proof: \n    Induct on n and m.\n\n      n = 0, m = 0\n      0 + 0 = 0 + 0\n      0 = 0\n      True\n\n      n = 0\n      IH: 0 + m = m + 0\n      P(k+1) => 1 + m = 1 + (m+0)\n         By IH: 1 + m = 1 + (0+m)\n                1 + m = 1 + m\n                True\n\n      IH: n + m = m + n\n      P(k+1) => (1+n) + m = m + (1+n)\n                1 + (n + m) = m + (1+n)\n                By IH: 1 + (m + n) = m + (1+n)\n                By distr: 1 + m + n = 1 + m + n\n                True\n[]\n*)\n\n\n(******************************* question 3*******************************************************8 points*)\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. \nintros. \ninduction n.\nreflexivity.\nsimpl.\nrewrite -> IHn.\nrewrite <- plus_distr.\nreflexivity.\nQed.\n\n\n(******************************* question 4*******************************************************8 points*)\n\n(** Use [assert] to help prove this theorem.  You shouldn't need to use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.\nintros.\nrewrite -> plus_assoc.\nrewrite -> plus_assoc.\nassert (H1: n + m = m + n).\napply plus_comm.\nrewrite <- H1.\nreflexivity.\nQed.\n\n(******************************* question 5*******************************************************10 points*)\n\nLemma mult_zero : forall n : nat, n * 0 = 0.\nProof.\nintros.\ninduction n.\nreflexivity.\nsimpl.\nrewrite -> IHn.\nreflexivity.\nQed.\n\nLemma mult_iden : forall n m : nat, n + n * m = n * S m.\nProof.\nintros.\ninduction n.\ninduction m.\nreflexivity.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nrewrite -> plus_assoc.\nrewrite -> plus_assoc.\nassert (H: n + m = m + n).\nrewrite -> plus_comm.\nreflexivity.\nrewrite -> H.\nreflexivity.\nQed.\n\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\nintros.\ninduction m.\nsimpl.\nrewrite -> mult_zero.\nreflexivity.\ninduction n.\nsimpl.\nrewrite -> mult_zero.\nreflexivity.\nsimpl.\nrewrite -> IHm.\nsimpl.\nrewrite -> plus_swap.\nrewrite -> mult_iden.\nreflexivity.\nQed.\n\n\n(******************************* question 6*******************************************************10 points*)\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\nintros.\ninduction n.\ninduction m.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHn.\nrewrite -> plus_assoc.\nreflexivity.\nQed.\n\n(***** Some definitions/notations for lists, as we saw in class *****)\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) ..).\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\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\n\n\n\n\n\n\n(******************************* question 7*******************************************************12 points*)\n\n(*a*) (* 2 points *)\nTheorem app_nil_end : forall l : natlist, \n  l ++ [] = l.   \nProof.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHl.\nreflexivity.\nQed.\n\nLemma snoc_rev : forall (l:natlist) (n:nat), rev(snoc l n) = n::rev(l).\nProof.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHl.\nsimpl.\nreflexivity.\nQed.\n\n(*b*) (* 10 points *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> snoc_rev.\nrewrite -> IHl.\nreflexivity.\nQed.\n\n\n\n\n(******************************* question 8*******************************************************16 points*)\n\n(*a*) (* 4 points *)\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\nintros.\ninduction l.\nreflexivity.\nsimpl.\nrewrite <- IHl.\nreflexivity.\nQed.\n\nLemma distr_snoc : forall (l1 l2 : natlist) (n:nat), snoc (l1 ++ l2) n = l1 ++ snoc l2 n.\nintros.\ninduction l1.\ninduction l2.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHl1.\nreflexivity.\nQed.\n\n\n(*b*) (* 12 points *)\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\nintros.\ninduction l1.\ninduction l2.\nsimpl.\nreflexivity.\nsimpl.\nrewrite app_nil_end.\nreflexivity.\nsimpl.\nrewrite -> IHl1.\nrewrite -> distr_snoc.\nreflexivity.\nQed.\n\n\n(***** Some definitions on bags, as we saw in class *****)\n\nDefinition bag := natlist.\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\nRequire Import Arith.\n\nFixpoint count (v:nat) (s:bag) : nat := \n  match s with\n    nil => 0\n  | h :: t => if (beq_nat h v) then S (count v t)\n                               else count v t\n  end.\n\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    nil => nil\n  | h::t => if (beq_nat v h)\n             then t\n             else h::(remove_one v t)\n  end.\n\n\n\n\n\n\n(******************************* question 9*******************************************************12 points*)\n\n(*a*) (* 2 points *)\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\nintros.\ninduction s.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\n\n\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    simpl.  reflexivity.\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\n(*b*) (* 10 points *)\nTheorem remove_decreases_count: forall (s : bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\nintros.\ninduction s.\nsimpl.\nreflexivity.\ndestruct n.\nsimpl.\nrewrite -> ble_n_Sn.\nreflexivity.\nsimpl.\nrewrite IHs.\nreflexivity.\nQed.\n\n\n\n(******************************* BONUS QUESTION*******************************************************10 points*)\n\nTheorem rev_inj : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\nintros.\nrewrite <- (rev_involutive l2).\nrewrite <- (rev_involutive l1).\nrewrite <- H.\nreflexivity.\nQed.", "meta": {"author": "tgavankar", "repo": "15414hw3", "sha": "84047757cbdb8a52d4bdeeac2daf9e558c54ff05", "save_path": "github-repos/coq/tgavankar-15414hw3", "path": "github-repos/coq/tgavankar-15414hw3/15414hw3-84047757cbdb8a52d4bdeeac2daf9e558c54ff05/hw3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8757869932689565, "lm_q1q2_score": 0.7836449785838135}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export indprop.\nRequire Import Coq.omega.Omega.\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\nInductive next_nat (n : nat) : nat -> Prop :=\n           nn : next_nat n (S n).\n\nCheck next_nat : relation nat.\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. \nQed.\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\nunfold not.\nunfold partial_function.\nintros.\nassert (0 = 1) as Nonsense.\n {\n    apply H with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n.\n } \n  inversion Nonsense. \nQed.\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\nTheorem le_reflexive :\n  reflexive le.\nProof.\nunfold reflexive.\nintros.\napply le_n.\nQed.\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.\nunfold transitive.\nintros.\ninduction H0.\nassumption.\napply le_S. \napply IHle.\nassumption.\nQed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\nunfold transitive.\nunfold lt.\nintros.\napply le_S in H.\napply le_trans with \n(a := (S a)) (b := (S b)) (c := c).\nassumption. assumption.\nQed.\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\nunfold lt. unfold transitive.\nintros n m o Hnm Hmo.\ninduction Hmo as [| m' Hm'o].\nAdmitted.\n\nTheorem le_Sn_le : forall n m, \nS n <= m -> n <= m.\nProof.\nintros.\napply le_trans with (S n).\n- apply le_S. apply le_n.\n- assumption.\nQed.\n\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\nintros.\ninversion H.\n- apply le_n.\n- apply le_Sn_le in H2.\nassumption.\nQed.\n\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\ninduction n.\n- intros H.\ninversion H.\n- unfold not in IHn.\nintros H. apply le_S_n in H.\napply IHn in H.\nassumption.\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.\nunfold not.\nunfold symmetric.\nintros.\nassert (1<=0) as A.\n- apply H. apply le_S. apply le_n.\n- inversion A.\nQed.\n\nDefinition antisymmetric \n{X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\nLemma Sn_eq_n : forall n m,\n n =  m -> S n = S m.\nProof.\nAdmitted.\n\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\nintros a b.\ngeneralize dependent a.\ninduction b.\n- intros. inversion H.\nreflexivity.\n- intros a. intros H H1.\ndestruct a.\n+ inversion H1.\n+ apply le_S_n in H1.\napply le_S_n in H.\napply Sn_eq_n.\napply IHb.\nassumption. assumption.\nQed.\n\nLemma le_lt: forall n m,\nn <= m -> n < S m.\nProof.\nAdmitted.\n\nLemma lt_le : forall n m,\nn < S m -> n <= m.\nProof.\nAdmitted.\n\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof.\nintros n m p Hnm Hmp1.\n  unfold lt in Hnm.\n  assert (S n <= S p).\n  apply le_trans with m.\n  assumption.\n  assumption.\n  apply le_S_n.\n  assumption.\nQed.\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(** order is patial order **)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\nsplit.\n- unfold reflexive. intros. apply le_n.\n- split.\n  +  unfold antisymmetric. intros.\n     apply le_antisymmetric.\n     assumption. assumption.\n  +  apply le_trans.\nQed.\n\nInductive clos_refl_trans \n{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.\nsplit.\n- intros. induction H.\n + apply rt_refl.\n + apply rt_trans with m.\n   apply IHle. apply rt_step. apply nn.\n- intros. induction H. \n + inversion H. apply le_S. apply le_n.\n + apply le_n.\n + apply le_trans with y.\n   assumption. assumption.\nQed.\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\nLemma rsc_R : forall (X:Type) \n(R:relation X) (x y : X),\n       R x y -> clos_refl_trans_1n R x y.\nProof.\nintros.\napply rt1n_trans with y.\nassumption.\napply rt1n_refl.\nQed.\n\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.\nintros X R x y z.\nreplace (clos_refl_trans_1n R y z -> clos_refl_trans_1n R x z)\nwith (R x y).\nintros.\nAdmitted.\n\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.\nAdmitted.\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/rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7836424710538294}}
{"text": "Require Import Omega.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Bool.Bool.\nLocal Open Scope Z_scope.\n\n(** ** An omega that works for [N]\n\nThis is mostly to work around https://github.com/coq/coq/issues/6602.\n\n*)\n\nLtac Nomega := rewrite ?N.pred_sub in *; zify; omega.\n\n\n(** ** Utility lemmas about [Z], [N] and bits.\n\nSome of these certainly could live in the standard library.\n\n*)\n\n\n(** *** The [nonneg] tactic *)\n\n\n(**\nWe very often have to resolve non-negativity constraints, so we build\na tactic library for that.\n*)\n\nLemma pos_nonneg: forall p, (0 <= N.pos p)%N. \nProof.\n  compute; congruence.\nQed.\n\nLemma pos_pos: forall p, (0 < N.pos p)%N. \nProof.\n  compute; congruence.\nQed.\n\nLemma succ_nonneg: forall n, 0 <= n -> 0 <= Z.succ n.\nProof. intros. omega. Qed.\n\n\nLemma ones_nonneg: forall n, 0 <= n -> 0 <= Z.ones n.\nProof.\n  intros.\n  unfold Z.ones.\n  rewrite -> Z.shiftl_mul_pow2 by assumption.\n  rewrite Z.mul_1_l.\n  rewrite <- Z.lt_le_pred.\n  apply Z.pow_pos_nonneg; auto.\n  omega.\nQed.\n\nLemma log2_ones: forall n, 0 < n -> Z.log2 (Z.ones n) = Z.pred n.\n  intros.\n  unfold Z.ones.\n  rewrite -> Z.shiftl_mul_pow2 by omega.\n  rewrite Z.mul_1_l.\n  apply Z.log2_pred_pow2.\n  assumption.\nQed.\n\nCreate HintDb nonneg.\nHint Immediate N2Z.is_nonneg : nonneg.\nHint Immediate pos_nonneg : nonneg.\nHint Resolve N.le_0_l : nonneg.\nHint Resolve Z.log2_nonneg : nonneg.\nHint Resolve ones_nonneg : nonneg.\nHint Resolve succ_nonneg : nonneg.\nHint Resolve <- Z.shiftl_nonneg : nonneg.\nHint Resolve <- Z.shiftr_nonneg : nonneg.\nHint Resolve <- Z.land_nonneg : nonneg.\nHint Resolve Z.pow_nonneg : nonneg.\nHint Extern 1 (0 <= Z.succ (Z.pred (Z.of_N _))) => rewrite Z.succ_pred : nonneg.\nHint Resolve <- Z.lxor_nonneg : nonneg.\nHint Extern 0 => omega : nonneg.\n\nLtac nonneg := solve [auto with nonneg].\n\nLemma N_gt_0_neq:\n  forall n, (n <> 0 <-> 0 < n)%N.\nProof.\n  intros.\n  destruct n; intuition.\n  * inversion H.\n  * apply pos_pos.\n  * inversion H0.\nQed.\n\n(** *** Lemmas about [N] and [Z], especially related to bits *)\n\nLemma N_lt_pow2_testbits:\n  forall n p, (n < 2^p)%N <-> (forall j, (p <= j)%N -> N.testbit n j = false).\nProof.\n  intros.\n  etransitivity.\n  * symmetry. apply N.div_small_iff.\n    apply N.pow_nonzero; congruence.\n  * rewrite <- N.shiftr_div_pow2.\n    rewrite <- N.bits_inj_iff.\n    split; intros H j.\n    + intro.\n      specialize (H (j - p)%N).\n      rewrite N.shiftr_spec, N.bits_0 in * by nonneg.\n      rewrite N.sub_add in H by assumption.\n      assumption.\n    + rewrite N.shiftr_spec, N.bits_0 by nonneg.\n      apply H.\n      change (0 + p <= j + p)%N.\n      apply N.add_le_mono_r.\n      nonneg.\nQed.\n\n(* exists for Z, but not for N? *)\nLemma N_pow_pos_nonneg: forall a b : N, (0 < a -> 0 < a ^ b)%N.\nProof.\n  intros.\n  apply N.peano_ind with (n := b); intros.\n  * simpl. reflexivity.\n  * rewrite N.pow_succ_r; [|apply N.le_0_l].\n    eapply N.lt_le_trans. apply H0.\n    replace (a ^ n)%N  with (1 * a^n)%N at 1 by (apply N.mul_1_l).\n    apply N.mul_le_mono_pos_r; auto.\n    rewrite <- N.le_succ_l in H.\n    apply H.\nQed.\n\nLemma ones_spec:\n  forall n m : Z, 0 <= n -> Z.testbit (Z.ones n) m = (0 <=? m) && (m <? n).\nProof.\n  intros.\n  destruct (Z.leb_spec 0 m), (Z.ltb_spec m n);\n    simpl; try apply not_true_is_false;\n    rewrite Z.ones_spec_iff; omega.\nQed.\n\nLemma lor_ones_ones: forall b1 b2, 0 <= b1 -> 0 <= b2 ->\n  Z.lor (Z.ones b1) (Z.ones b2) = Z.ones (Z.max b1 b2).\nProof.\n  intros.\n  apply Z.bits_inj'. intros z?.\n  rewrite -> Z.lor_spec.\n  repeat rewrite -> ones_spec by (try rewrite Z.max_le_iff; auto).\n  destruct (Z.leb_spec 0 z), (Z.ltb_spec z b1), (Z.ltb_spec z b2), (Z.ltb_spec z (Z.max b1 b2)),  (Zmax_spec b1 b2); intuition; simpl; try omega.\nQed. \n\n\nLemma to_N_log2: forall i, Z.to_N (Z.log2 i) = N.log2 (Z.to_N i).\nProof.\n  intros.\n  destruct i; try reflexivity.\n  destruct p; try reflexivity.\nQed.\n\nLemma of_N_log2: forall n, Z.of_N (N.log2 n) = Z.log2 (Z.of_N n).\nProof.\n  intros.\n  destruct n; try reflexivity.\n  destruct p; try reflexivity.\nQed.\n\n(* This is a stronger version than what’s in the standard library *)\nLemma log2_le_lin': forall a : N, (* (0 <= a)%N -> *) (N.log2 a <= a)%N.\nProof. intros.\n  destruct a.\n  reflexivity.\n  apply N.log2_le_lin.\n  nonneg.\nQed.\n\nLemma N_land_pow2_testbit:\n  forall n i, negb (N.land (2 ^ i) n =? 0)%N = N.testbit n i.\nProof.\n  intros.\n  destruct (N.testbit n i) eqn:Htb.\n  * rewrite negb_true_iff.\n    rewrite N.eqb_neq.\n    contradict Htb.\n    assert (N.testbit (N.land (2^i)%N n) i = false)\n     by (rewrite Htb; apply N.bits_0).\n    rewrite N.land_spec in H. rewrite N.pow2_bits_true in H.\n    simpl in H. congruence.\n  * rewrite negb_false_iff.\n    rewrite N.eqb_eq.\n    apply N.bits_inj.\n    intro j.\n    rewrite N.land_spec.\n    rewrite N.pow2_bits_eqb.\n    destruct (N.eqb_spec i j); subst; intuition.\nQed.\n\nLemma land_pow2_eq:\n  forall i b, 0 <= b -> (Z.land i (2 ^ b) =? 0) = (negb (Z.testbit i b)).\nProof.\n  intros ?? Hnonneg.\n  destruct (Z.testbit i b) eqn:Htb; simpl.\n  * rewrite Z.eqb_neq.\n    contradict Htb.\n    assert (Z.testbit (Z.land i (2^b)) b = false)\n     by (rewrite Htb; apply Z.bits_0).\n    rewrite Z.land_spec in H. rewrite Z.pow2_bits_true in H.\n    rewrite andb_true_r in H.\n    simpl in H. congruence.\n    nonneg.\n  * rewrite Z.eqb_eq.\n    apply Z.bits_inj'.\n    intros j ?.\n    rewrite  Z.bits_0.\n    rewrite Z.land_spec.\n    rewrite Z.pow2_bits_eqb.\n    destruct (Z.eqb_spec b j).\n    + subst. rewrite Htb. reflexivity.\n    + rewrite andb_false_r.  reflexivity.\n    + nonneg.\nQed.\n\nLemma N_land_pow2_eq:\n  forall i b, (N.land i (2 ^ b) =? 0)%N = negb (N.testbit i b).\nProof.\n  intros ??.\n  destruct (N.testbit i b) eqn:Htb; simpl.\n  * rewrite N.eqb_neq.\n    contradict Htb.\n    assert (N.testbit (N.land i (2^b)) b = false)\n     by (rewrite Htb; apply N.bits_0).\n    rewrite N.land_spec in H. rewrite N.pow2_bits_true in H.\n    rewrite andb_true_r in H.\n    simpl in H. congruence.\n  * rewrite N.eqb_eq.\n    apply N.bits_inj.\n    intros j.\n    rewrite N.bits_0.\n    rewrite N.land_spec.\n    rewrite N.pow2_bits_eqb.\n    destruct (N.eqb_spec b j).\n    + subst. rewrite Htb. reflexivity.\n    + rewrite andb_false_r.  reflexivity.\nQed.\n\nLemma shiftr_eq_ldiff :\nforall n m b,\n    0 <= b ->\n    Z.ldiff n (Z.ones b) = Z.ldiff m (Z.ones b) ->\n    Z.shiftr n b = Z.shiftr m b.\nProof.\n  intros.\n    * apply Z.bits_inj'.\n      intros i ?.\n      rewrite -> !Z.shiftr_spec by assumption.\n      apply Z.bits_inj_iff in H0.\n      specialize (H0 (i + b)).\n      rewrite -> !Z.ldiff_spec in H0.\n      rewrite -> !Z.ones_spec_high in H0.\n      simpl in *.\n      rewrite -> ! andb_true_r in H0.\n      assumption.\n      omega.\nQed.\n\nLemma Z_shiftl_inj:\n  forall x y n,\n    0 <= n ->\n    Z.shiftl x n = Z.shiftl y n <-> x = y.\nProof.\n  intros; split; intro.\n  * apply Z.bits_inj'.\n    intros i ?.\n    apply Z.bits_inj_iff in H0.\n    specialize (H0 (i + n)).\n    do 2 rewrite -> Z.shiftl_spec in H0 by omega.\n    replace (i + n - n) with i in H0 by omega.\n    assumption.\n  * apply Z.bits_inj'.\n    intros i ?.\n    apply Z.bits_inj_iff in H0.\n    specialize (H0 (i - n)).\n    do 2 rewrite -> Z.shiftl_spec by omega.\n    assumption.\nQed.\n\nLemma N_shiftl_inj:\n  forall x y n,\n    N.shiftl x n = N.shiftl y n <-> x = y.\nProof.\n  intros; split; intro.\n  * apply N.bits_inj.\n    intros i.\n    apply N.bits_inj_iff in H.\n    specialize (H (i + n)%N).\n    do 2 rewrite -> N.shiftl_spec_alt in H by omega.\n    assumption.\n  * subst. reflexivity.\nQed.\n\nLemma land_shiftl_ones:\n  forall i n, 0 <= n -> Z.land (Z.shiftl i n) (Z.ones n) = 0.\nProof.\n  intros.\n  apply Z.bits_inj'.\n  intros j ?.\n  rewrite Z.land_spec.\n  rewrite -> Z.shiftl_spec by nonneg.\n  rewrite Z.bits_0. rewrite andb_false_iff.\n  destruct (Z.ltb_spec j n).\n  * left. apply Z.testbit_neg_r. omega.\n  * right. apply Z.ones_spec_high. omega.\nQed.\n\nLemma N_land_shiftl_ones:\n  forall i n, N.land (N.shiftl i n) (N.ones n) = 0%N.\nProof.\n  intros.\n  apply N.bits_inj.\n  intros j.\n  rewrite N.land_spec.\n  rewrite N.bits_0. rewrite andb_false_iff.\n  destruct (N.ltb_spec j n).\n  * left. rewrite -> N.shiftl_spec_low by assumption. reflexivity.\n  * right. apply N.ones_spec_high. assumption.\nQed.\n\nLemma N_shiftl_spec_eq:\n  forall n i j,\n  N.testbit (N.shiftl n i) j =\n    (if j <? i then false else N.testbit n (j - i))%N.\nProof.\n  intros.\n  destruct (N.ltb_spec j i).\n  * apply N.shiftl_spec_low; assumption.\n  * apply N.shiftl_spec_high'; assumption.\nQed.\n\nLemma Z_shiftl_add:\n  forall x y i,\n  (0 <= i) ->\n  Z.shiftl (x + y) i = Z.shiftl x i + Z.shiftl y i.\nProof.\n  intros.\n  rewrite !Z.shiftl_mul_pow2 by assumption.\n  rewrite Z.mul_add_distr_r.\n  reflexivity.\nQed.\n\nLemma N_shiftl_add:\n  forall x y i,\n  N.shiftl (x + y)%N i = (N.shiftl x i + N.shiftl y i)%N.\nProof.\n  intros.\n  rewrite !N.shiftl_mul_pow2 by assumption.\n  rewrite N.mul_add_distr_r.\n  reflexivity.\nQed.\n\nLemma testbit_1:\n  forall i, Z.testbit 1 i = (i =? 0).\nProof.\n  intros.\n  replace 1 with (2^0) by reflexivity.\n  rewrite -> Z.pow2_bits_eqb by reflexivity.\n  apply Z.eqb_sym.\nQed.\n\nLemma N_testbit_1:\n  forall i, N.testbit 1 i = (i =? 0)%N.\nProof.\n  intros.\n  replace 1%N with (2^0)%N by reflexivity.\n  rewrite -> N.pow2_bits_eqb by reflexivity.\n  apply N.eqb_sym.\nQed.\n\n(* This lemma shows that the way the code gets the upper bits above a one-bit-mask\n  is correct *)\nLemma mask_to_upper_bits:\nforall b, \n  0 <= b ->\n  (Z.lxor (Z.lnot (Z.pred (2 ^ b))) (2 ^ b)) =\n  Z.lnot (Z.ones (Z.succ b)).\nProof.\n  intros.\n  rewrite <- Z.ones_equiv.\n  rewrite <- Z.lnot_lxor_l.\n  apply Z.bits_inj_iff'. intros j?.\n  rewrite -> Z.lnot_spec by nonneg.\n  rewrite -> Z.lnot_spec by nonneg.\n  rewrite -> Z.lxor_spec.\n  rewrite -> ones_spec by nonneg.\n  rewrite -> ones_spec by nonneg.\n  rewrite -> Z.pow2_bits_eqb by nonneg.\n  destruct (Z.leb_spec 0 j), (Z.ltb_spec j b), (Z.ltb_spec j (Z.succ b)), (Z.eqb_spec b j);\n    simpl; try congruence; omega.\nQed.\n\n\nLemma of_N_shiftl:\n  forall n i, Z.of_N (N.shiftl n i) = Z.shiftl (Z.of_N n) (Z.of_N i).\nProof.\n  intros.\n  apply Z.bits_inj_iff'; intros j?.\n  replace j with (Z.of_N (Z.to_N j))\n    by (rewrite -> Z2N.id by assumption; reflexivity).\n  rewrite N2Z.inj_testbit.\n  destruct (N.leb_spec i (Z.to_N j)).\n  * rewrite -> N.shiftl_spec_high' by assumption.\n    rewrite -> Z.shiftl_spec by nonneg.\n    rewrite <- N2Z.inj_sub by assumption.\n    rewrite N2Z.inj_testbit.\n    reflexivity.\n  * rewrite -> N.shiftl_spec_low by assumption.\n    rewrite -> Z.shiftl_spec_low by Nomega.\n    reflexivity.\nQed.\n\nLemma Z_eq_shiftr_land_ones:\n  forall i1 i2 b,\n  (i1 =? i2) = (Z.shiftr i1 b =? Z.shiftr i2 b) && (Z.land i1 (Z.ones b) =? Z.land i2 (Z.ones b)).\nProof.\n  intros.\n  match goal with [ |- ?b1 = ?b2 ] => destruct b1 eqn:?, b2 eqn:? end; try congruence.\n  * contradict Heqb1.\n    rewrite not_false_iff_true.\n    rewrite andb_true_iff.\n    repeat rewrite -> Z.eqb_eq in *; subst.\n    auto.\n  * contradict Heqb0.\n    rewrite not_false_iff_true.\n    rewrite -> andb_true_iff in Heqb1.\n    destruct Heqb1.\n    repeat rewrite -> Z.eqb_eq in *; subst.\n    apply Z.bits_inj_iff'. intros j ?.\n    destruct (Z.ltb_spec j b).\n    + apply Z.bits_inj_iff in H0.\n      specialize (H0 j).\n      repeat rewrite -> Z.land_spec in H0.\n      rewrite -> Z.ones_spec_low in H0.\n      do 2 rewrite andb_true_r in H0.\n      assumption.\n      omega.\n    + apply Z.bits_inj_iff in H.\n      specialize (H (j - b)).\n      do 2 rewrite -> Z.shiftr_spec in H by omega.\n      replace (j - b + b) with j in H by omega.\n      assumption.\nQed.\n\n\nLemma N_eq_shiftr_land_ones:\n  forall i1 i2 b,\n  (i1 =? i2)%N = (N.shiftr i1 b =? N.shiftr i2 b)%N && (N.land i1 (N.ones b) =? N.land i2 (N.ones b))%N.\nProof.\n  intros.\n  match goal with [ |- ?b1 = ?b2 ] => destruct b1 eqn:?, b2 eqn:? end; try congruence.\n  * contradict Heqb1.\n    rewrite not_false_iff_true.\n    rewrite andb_true_iff.\n    repeat rewrite -> N.eqb_eq in *; subst.\n    auto.\n  * contradict Heqb0.\n    rewrite not_false_iff_true.\n    rewrite -> andb_true_iff in Heqb1.\n    destruct Heqb1.\n    repeat rewrite -> N.eqb_eq in *; subst.\n    apply N.bits_inj_iff. intros j.\n    destruct (N.ltb_spec j b).\n    + apply N.bits_inj_iff in H0.\n      specialize (H0 j).\n      repeat rewrite -> N.land_spec in H0.\n      rewrite -> N.ones_spec_low in H0 by assumption.\n      do 2 rewrite andb_true_r in H0.\n      assumption.\n    + apply N.bits_inj_iff in H.\n      specialize (H (j - b)%N).\n      do 2 rewrite -> N.shiftr_spec in H by Nomega.\n      replace (j - b + b)%N with j in H by Nomega.\n      assumption.\nQed.\n\nLemma Pos_1_testbit_succ:\n  forall p i,\n  Pos.testbit p~1 (N.succ i) = Pos.testbit p i.\nProof.\n  induction i.\n  * reflexivity.\n  * simpl. rewrite Pos.pred_N_succ. reflexivity.\nQed.\n\n\nLemma Pos_0_testbit_succ:\n  forall p i,\n  Pos.testbit p~0 (N.succ i) = Pos.testbit p i.\nProof.\n  induction i.\n  * reflexivity.\n  * simpl. rewrite Pos.pred_N_succ. reflexivity.\nQed.\n\nLemma N_bits_impl_le:\n  forall a b,\n  (forall i, N.testbit a i = true -> N.testbit b i = true) ->\n  (a <= b)%N.\nProof.\n  intros.\n  induction a; try apply N.le_0_l.\n  destruct b.\n  * exfalso.\n    refine (Pbit_faithful_0 p _).\n    intro j.\n    specialize (H (N.of_nat j)).\n    rewrite N.bits_0 in H.\n    simpl in H; rewrite Ptestbit_Pbit in H. \n    destruct (Pos.testbit_nat p j) eqn:?; intuition.\n  * simpl in *.\n    change (Pos.le p p0).\n    revert p0 H.\n    induction p; intros p0 H.\n    - destruct p0 eqn:?.\n      + change (p <= p1)%positive.\n        apply IHp. intro i.\n        specialize (H (N.succ i)).\n        rewrite !Pos_1_testbit_succ in H.\n        assumption.\n      + exfalso.\n        specialize (H 0%N).\n        simpl in H. intuition congruence.\n      + exfalso.\n        refine (Pbit_faithful_0 p _).\n        intro j.\n        specialize (H (N.succ (N.of_nat j))).\n        rewrite <- Nat2N.inj_succ in H at 2.\n        rewrite Pos_1_testbit_succ, Ptestbit_Pbit in H. \n        destruct (Pos.testbit_nat p j) eqn:?; intuition.\n    - destruct p0 eqn:?.\n      + transitivity (p1~0)%positive.\n        ** change (p <= p1)%positive.\n          apply IHp. intro i.\n          specialize (H (N.succ i)).\n          rewrite Pos_0_testbit_succ, Pos_1_testbit_succ in H.\n          assumption.\n        ** zify. omega.\n      + change (p <= p1)%positive.\n        apply IHp. intro i.\n        specialize (H (N.succ i)).\n        rewrite !Pos_0_testbit_succ in H.\n        assumption.\n      + exfalso.\n        refine (Pbit_faithful_0 p _).\n        intro j.\n        specialize (H (N.succ (N.of_nat j))).\n        rewrite <- Nat2N.inj_succ in H at 2.\n        rewrite Pos_0_testbit_succ, Ptestbit_Pbit in H. \n        destruct (Pos.testbit_nat p j) eqn:?; intuition.\n     - apply Pos.le_1_l.\nQed.\n\n\nLemma clearbit_le:\n  forall a i,\n  (N.clearbit a i <= a)%N.\nProof.\n  intros.\n  apply N_bits_impl_le; intros j H.\n  rewrite N.clearbit_eqb in H.\n  rewrite andb_true_iff in *.\n  intuition.\nQed.\n\nLemma clearbit_lt:\n  forall a i,\n  N.testbit a i = true ->\n  (N.clearbit a i < a)%N.\nProof.\n  intros.\n  apply N.le_neq; split.\n  * apply clearbit_le.\n  * intro.\n    apply N.bits_inj_iff in H0. specialize (H0 i).\n    rewrite N.clearbit_eqb in H0.\n    rewrite N.eqb_refl in H0.\n    simpl negb in H0.\n    rewrite andb_false_r in H0.\n    congruence.\nQed.\n\nLemma ldiff_le:\n  forall a b,\n  (N.ldiff a b <= a)%N.\nProof.\n  intros.\n  apply N_bits_impl_le; intros i H.\n  rewrite N.ldiff_spec in *.\n  rewrite andb_true_iff in *.\n  intuition.\nQed.\n\nLemma ldiff_lt:\n  forall a b i,\n  N.testbit a i = true ->\n  N.testbit b i = true ->\n  (N.ldiff a b < a)%N.\nProof.\n  intros.\n  apply N.le_neq; split.\n  * apply ldiff_le.\n  * intro.\n    apply N.bits_inj_iff in H1. specialize (H1 i).\n    rewrite N.ldiff_spec in H1.\n    rewrite H, H0 in H1.\n    inversion H1.\nQed.\n\nLemma ldiff_pow2_lt:\n  forall a i,\n  N.testbit a i = true ->\n  (N.ldiff a (2^i) < a)%N.\nProof.\n  intros.\n  apply ldiff_lt with (i := i); auto.\n  apply N.pow2_bits_true.\nQed.\n\nLemma clearbit_log2_mod:\n  forall bm,\n  (0 < bm)%N ->\n  N.clearbit bm (N.log2 bm)%N = (bm mod (2 ^ N.log2 bm))%N.\nProof.\n  intros.\n  apply N.bits_inj. intro i.\n  rewrite N.clearbit_eqb.\n  destruct (N.eqb_spec (N.log2 bm) i); simpl negb; [|destruct (N.ltb_spec i (N.log2 bm))].\n  * rewrite N.mod_pow2_bits_high by Nomega.\n    simpl negb.\n    apply andb_false_r.\n  * rewrite N.mod_pow2_bits_low by assumption.\n    apply andb_true_r.\n  * rewrite N.mod_pow2_bits_high by assumption.\n    rewrite N.bits_above_log2 by Nomega.\n    apply andb_true_r.\nQed.\n\nLemma clearbit_pow2_0:\n  forall n, (N.clearbit (2 ^ n) n = 0)%N.\nProof.\n  intros.\n  rewrite N.clearbit_spec'.\n  apply N.ldiff_diag.\nQed.\n\nLemma clearbit_clearbit_comm:\n  forall a i j, N.clearbit (N.clearbit a i) j =  N.clearbit (N.clearbit a j) i.\nProof.\n  intros.\n  rewrite !N.clearbit_spec'.\n  rewrite !N.ldiff_ldiff_l.\n  rewrite N.lor_comm at 1.\n  reflexivity.\nQed.\n\n(** ** Most significant differing bit\n\nOnly properly defined if both arguments are non-negative.\n*)\n\nDefinition msDiffBit : N -> N -> N :=\n  fun n m => (N.log2 (N.lxor n m) + 1)%N.\n\nLemma msDiffBit_sym: forall p1 p2,\n  msDiffBit p1 p2 = msDiffBit p2 p1.\nProof.\n  intros.\n  unfold msDiffBit.\n  rewrite N.lxor_comm.\n  reflexivity.\nQed.\n\n\nSection msDiffBit.\n  Variable p1 p2 : N.\n  Variable (Hne : p1 <> p2).\n  \n  Local Lemma lxor_pos: (0 < N.lxor p1 p2)%N.\n  Proof.\n    assert (0 <= N.lxor p1 p2)%N by nonneg.\n    enough (N.lxor p1 p2 <> 0)%N by Nomega.\n    rewrite N.lxor_eq_0_iff.\n    assumption.\n  Qed.\n  \n  Lemma msDiffBit_Different:\n        N.testbit p1 (msDiffBit p1 p2 - 1)\n     <> N.testbit p2 (msDiffBit p1 p2 - 1).\n  Proof.\n    match goal with [ |- N.testbit ?x ?b <> N.testbit ?y ?b] =>\n      enough (xorb (N.testbit x b) (N.testbit y b) = true)\n      by (destruct (N.testbit x b), (N.testbit y b); simpl in *; congruence) end.\n    rewrite <- N.lxor_spec.\n    unfold msDiffBit.\n    rewrite N.add_sub.\n    apply N.bit_log2.\n    rewrite N.lxor_eq_0_iff.\n    assumption.\n  Qed.\n\n  Lemma msDiffBit_Same:\n    forall j, (msDiffBit p1 p2 <= j)%N ->\n    N.testbit p1 j = N.testbit p2 j.\n  Proof.\n    intros.\n    match goal with [ |- N.testbit ?x ?b = N.testbit ?y ?b] =>\n      enough (xorb (N.testbit x b) (N.testbit y b) = false)\n      by (destruct (N.testbit x b), (N.testbit y b); simpl in *; congruence) end.\n    rewrite <- N.lxor_spec.\n    unfold msDiffBit in H.\n    apply N.bits_above_log2.\n    Nomega.\n  Qed.\n\n  Lemma msDiffBit_shiftr_same:\n        N.shiftr p1 (msDiffBit p1 p2)\n     =  N.shiftr p2 (msDiffBit p1 p2).\n  Proof.\n    apply N.bits_inj_iff. intros j.\n    rewrite -> !N.shiftr_spec by nonneg.\n    apply msDiffBit_Same.\n    Nomega.\n  Qed.\nEnd msDiffBit.\n\nLemma msDiffBit_less:\n  forall z1 z2 b,\n    z1 <> z2 ->\n    N.shiftr z1 b = N.shiftr z2 b ->\n    (msDiffBit z1 z2 <= b)%N.\nProof.\n  intros.\n  unfold msDiffBit.\n  enough (N.log2 (N.lxor z1 z2) < b)%N\n    by (apply N2Z.inj_le; Nomega).\n  rewrite <- N.lxor_eq_0_iff in H0.\n  rewrite <- N.shiftr_lxor in H0.\n  apply N.shiftr_eq_0_iff in H0.\n  rewrite -> N.lxor_eq_0_iff in H0.\n  intuition.\nQed.\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/BitUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.783612826139303}}
{"text": "(* Exercise coq_tree_03 *)\n\n(* Let us start with the definitions from the previous \n   exercises *)\n\nInductive nat_tree : Set :=\n  | leaf : nat_tree\n  | node : nat_tree -> nat -> nat_tree -> nat_tree.\n\nFixpoint mirror (T : nat_tree) : nat_tree :=\n  match T with \n  | leaf => leaf\n  | node l n r => node (mirror r) n (mirror l)\n  end.\n\n(* Now let us prove that taking mirror image of a tree\n   twice returs the original tree. *)\n    \nLemma mirror_double : forall T, mirror (mirror T) = T.\nProof.\nintros.\ninduction T.\n* simpl; reflexivity.\n* simpl.\n  rewrite IHT1.\n  rewrite IHT2.\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_tree_03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7836069928434732}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Program.Tactics.\nRequire Import Coq.Program.Wf.\nRequire Import Omega.\n\nImport ListNotations.\n\nInductive sorted : list nat -> Prop :=\n| SortedEmpty : sorted [ ]\n| SortedSingleton : forall n, sorted [n]\n| SortedInd : forall n m l,\n    n <= m -> sorted (m :: l) -> sorted (n :: m :: l).\n\nModule HeapSort.\n\n  Inductive bintree : Type :=\n  | Leaf : nat -> bintree\n  | Left : nat -> bintree -> bintree\n  | Right : nat -> bintree -> bintree\n  | Fork : nat -> bintree -> bintree -> bintree.\n\n  Fixpoint height (t:bintree) : nat :=\n    match t with\n    | Leaf _ => 0\n    | Left _ c1 => S (height c1)\n    | Right _ c2 => S (height c2)\n    | Fork _ c1 c2 => S (Nat.max (height c1) (height c2))\n    end.\n\n  Fixpoint vertices (t:bintree) : nat :=\n    match t with\n    | Leaf _ => 1\n    | Left _ c1 => S (vertices c1)\n    | Right _ c2 => S (vertices c2)\n    | Fork _ c1 c2 => (vertices c1) + (vertices c2) + 1\n    end.\n\n  Definition root (t:bintree) : nat :=\n    match t with\n    | Leaf n => n\n    | Left n _ => n\n    | Right n _ => n\n    | Fork n _ _ => n\n    end.\n\n  Inductive perfect : bintree -> Prop :=\n  | PerfectSingleton : forall n,\n      perfect (Leaf n)\n  | PerfectInd : forall n t1 t2,\n      perfect t1 ->\n      perfect t2 ->\n      height t1 = height t2 ->\n      perfect (Fork n t1 t2).\n\n  Lemma sum_pos : forall a b,\n      a > 0 -> a + b > 0.\n  Proof.\n    intros a b. omega.\n  Qed.\n\n  Lemma product_pos : forall a b,\n      a > 0 -> b > 0 -> a * b > 0.\n  Proof.\n    intros a b Ha. induction b as [| b' IHb' ].\n    - intros Hb. inversion Hb.\n    - intros Hb. replace (a * S b') with (a + a * b').\n      apply sum_pos. assumption.\n      (* a * S b' = a + a * b' *) rewrite <- mult_n_Sm. omega.\n  Qed.\n\n  Lemma pow_pos : forall a n,\n      a > 0 -> a ^ n > 0.\n  Proof.\n    intros a n H. induction n as [| n' IHn' ].\n    - simpl. omega.\n    - simpl. remember (a ^ n') as k. apply product_pos.\n      assumption. assumption.\n  Qed.\n\n  Proposition vertices_of_perfect_bintree : forall t,\n      perfect t ->\n      vertices t = (Nat.pow 2 (height t + 1)) - 1.\n  Proof.\n    intros t E. induction E.\n    - (* PerfectSingleton *)\n      reflexivity.\n    - (* PerfectInd *)\n      simpl. replace (height t2) with (height t1).\n      rewrite max_l. replace (vertices t2) with (vertices t1).\n      rewrite IHE1.\n      assert (Lem: 2 ^ (height t1 + 1) > 0).\n      { apply pow_pos. omega. }\n      remember (2 ^ (height t1 + 1)) as k. omega.\n      (* vertices t1 = vertices t2 *)\n      rewrite IHE1. rewrite IHE2. rewrite H. reflexivity.\n      (* height t1 <= height t2 *) omega.\n  Qed.\n\n  Fixpoint perfb (t:bintree) : bool :=\n    match t with\n    | Leaf _ => true\n    | Left _ _ => false\n    | Right _ _ => false\n    | Fork _ t1 t2 =>\n      (height t1 =? height t2) && perfb t1 && perfb t2\n    end.\n\n  Proposition perfb_true_iff : forall t,\n      perfect t <-> perfb t = true.\n  Proof.\n    intros t. split.\n    - (* -> *)\n      intros E. induction E.\n      + (* t = Leaf n *)\n        reflexivity.\n      + (* t = Inner n t1 t2 *)\n        simpl. rewrite H. rewrite IHE1. rewrite IHE2.\n        replace (height t2 =? height t2) with true. reflexivity.\n        (* goal: height t2 =? height t2 *) apply beq_nat_refl.\n    - (* <- *)\n      induction t as [n | n t1 | n t2 | n t1 IHt1 t2 IHt2].\n      + intros. apply PerfectSingleton.\n      + (* contradiction *) intros contra. inversion contra.\n      + (* contradiciton *) intros contra. inversion contra.\n      + intros H. simpl in H.\n        apply andb_prop in H. destruct H as [H Ht2].\n        apply andb_prop in H. destruct H as [Hheight Ht1].\n        apply PerfectInd.\n        * apply IHt1. apply Ht1.\n        * apply IHt2. apply Ht2.\n        * apply beq_nat_true_iff. apply Hheight.\n  Qed.\n\n  Inductive complete : bintree -> Prop :=\n  | CompleteSingleton : forall n,\n      complete (Leaf n)\n  | CompleteLeft : forall n m,\n      complete (Left n (Leaf m))\n  | CompleteA : forall n t1 t2,\n      height t1 = height t2 + 1 ->\n      complete t1 ->\n      perfect t2 ->\n      complete (Fork n t1 t2)\n  | CompleteB : forall n t1 t2,\n      height t1 = height t2 ->\n      perfect t1 ->\n      complete t2 ->\n      complete (Fork n t1 t2).\n\n  Proposition perfect_imp_complete : forall t,\n      perfect t -> complete t.\n  Proof.\n    intros t E. induction E.\n    - (* PerfectSingleton *)\n      apply CompleteSingleton.\n    - (* PerfectInd *)\n      apply CompleteB; assumption.\n  Qed.\n\n  Inductive sat_heap_prop : bintree -> Prop :=\n  | SatHPSingle : forall n,\n      sat_heap_prop (Leaf n)\n  | SatHPLeft : forall n t1,\n      sat_heap_prop t1 ->\n      root t1 <= n ->\n      sat_heap_prop (Left n t1)\n  | SatHPRight : forall n t2,\n      sat_heap_prop t2 ->\n      root t2 <= n ->\n      sat_heap_prop (Right n t2)\n  | SatHPFork : forall n t1 t2,\n      sat_heap_prop t1 ->\n      sat_heap_prop t2 ->\n      root t1 <= n ->\n      root t2 <= n ->\n      sat_heap_prop (Fork n t1 t2).\n\n  Fixpoint max_vertex (t:bintree) : nat :=\n    match t with\n    | Leaf n => n\n    | Left n t1 =>\n      Nat.max n (max_vertex t1)\n    | Right n t2 =>\n      Nat.max n (max_vertex t2)\n    | Fork n t1 t2 =>\n      Nat.max n (Nat.max (max_vertex t1) (max_vertex t2))\n    end.\n\n  Lemma max_upper : forall a b m,\n      a <= m -> b <= m -> Nat.max a b <= m.\n  Proof.\n    intros a b m Ea. generalize dependent b.\n    induction Ea.\n    - (* a = m *)\n      intros b Eb. induction Eb.\n      + (* b = a *)\n        replace (Nat.max b b) with b. apply le_n.\n        (* goal: b = Nat.max b b *)\n        symmetry. apply max_l. apply le_n.\n      + (* b <= m - 1 *)\n        replace (Nat.max (S m) b) with (S m). apply le_n.\n        (* goal: S m = Nat.max (S m) b *)\n        symmetry. apply max_l. apply le_S. apply Eb.\n    - (* a <= m - 1 *)\n      intros b Eb. inversion Eb.\n      + replace (Nat.max a (S m)) with (S m). apply le_n.\n        (* goal : S m = Nat.max a (S m) *)\n        symmetry. apply max_r. apply le_S. apply Ea.\n      + subst. apply le_S. apply IHEa. assumption.\n  Qed.\n\n  Proposition heap_prop_max : forall t,\n      sat_heap_prop t -> max_vertex t = root t.\n  Proof.\n    intros t E. induction E.\n    - (* SatHPSingle *)\n      reflexivity.\n    - (* SatHPLeft *)\n      simpl. apply max_l. rewrite IHE. assumption.\n    - (* SatHPRight *)\n      simpl. apply max_l. rewrite IHE. assumption.\n    - (* SatHPInd *)\n      simpl. apply max_l. rewrite IHE1. rewrite IHE2.\n      apply max_upper; assumption.\n  Qed.\n\n  Definition heap (t:bintree) : Prop :=\n    complete t /\\ sat_heap_prop t.\n  (** A binary tree is called binary heap if and only if it satisfies\n      the shape property (completeness) and the heap property. *)\n\nEnd HeapSort.\n\nModule QuickSort.\n\n  Check filter.\n\n  Lemma filter_lt : forall (A:Type) pred (l:list A),\n      length (filter pred l) <= length (filter pred l).\n  Proof.\n    intros. induction l as [| x l' IHl'].\n    - simpl. omega.\n    - simpl. destruct (pred x).\n      + simpl. apply le_n_S. assumption.\n      + constructor.\n  Qed.\n\n  Lemma lt_def : forall n m,\n      S n <= m <-> n < m.\n  Proof.\n    intros n m. omega.\n  Qed.\n\n  Program Fixpoint qsort (l:list nat) {measure (length l)}\n    : list nat :=\n    match l with\n    | [] => []\n    | x :: xs =>\n      let lt : list nat := filter (fun n:nat => Nat.ltb n x) xs in\n      let ge : list nat := filter (fun n:nat => Nat.leb x n) xs in\n      (qsort lt) ++ [x] ++ (qsort ge)\n    end.\n  Next Obligation.\n    induction xs as [| x' xs' IHxs'].\n    - (* xs = [ ] *)\n      simpl. omega.\n    - (* xs = x' :: xs' *)\n      simpl. destruct (x' <? x) eqn:Hbool.\n      + simpl. apply lt_n_S. replace (S (length xs')) with (length (x::xs')).\n        apply IHxs'. intros l Hl. apply xs'.\n        simpl. omega.\n      + constructor. apply lt_def. apply IHxs'.\n        intros l H. apply xs'.\n  Qed.\n  Next Obligation.\n    induction xs as [| x' xs' IHxs'].\n    - simpl. omega.\n    - simpl. destruct (x <=? x') eqn:Hbool.\n      + simpl. apply lt_n_S. replace (S (length xs')) with (length (x::xs')).\n        apply IHxs'. intros l Hl. apply xs'.\n        reflexivity.\n      + apply le_S. replace (S (length xs')) with (length (x::xs')).\n        apply lt_def. apply IHxs'. intros l Hl. apply xs'.\n        reflexivity.\n  Qed.\n\n  Example qsort_example :\n    qsort [3; 1; 4; 1; 5; 9; 2] = [1; 1; 2; 3; 4; 5; 9].\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma qsort_length : forall l,\n      length (qsort l) = length l.\n  Proof.\n  Abort.\n\n  Lemma qsort_two_head : forall l'' l n m,\n      qsort l = n :: m :: l'' -> n <= m.\n  Proof.\n    intros l''. induction l'' as [| k l'3 IHl'3]; intros l n m.\n    - intros Hqsort.\n      + unfold qsort in Hqsort. simpl in Hqsort.\n  Abort.\n\n  Theorem qsort_is_sort : forall l,\n      sorted (qsort l).\n  Proof.\n    intros l1. remember (qsort l1) as l.\n    generalize dependent l1.\n    induction l as [| n l' IHl'].\n    (* l = [] *) intros. apply SortedEmpty.\n    induction l' as [| m l'' IHl''].\n    - (* l = [n] *)\n      intros. apply SortedSingleton.\n    - (* l = n :: m :: l'' *)\n      intros l1 Hl1.\n      apply SortedInd.\n      unfold qsort in Hl1.\n      simpl in Hl1.\n  Abort.\n\nEnd QuickSort.\n", "meta": {"author": "1995hnagamin", "repo": "proof", "sha": "10dd0b6a46dd25e890059915a35b6d6156cc658b", "save_path": "github-repos/coq/1995hnagamin-proof", "path": "github-repos/coq/1995hnagamin-proof/proof-10dd0b6a46dd25e890059915a35b6d6156cc658b/2018/qsort/QuickSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7835996422548006}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq.\nFrom mathcomp Require Import fintype tuple finfun bigop.\nRequire Import Reals Fourier.\nRequire Import ssrR Reals_ext Rbigop logb ln_facts proba divergence.\n\n(** * Entropy of a distribution *)\n\nReserved Notation \"'`H'\" (at level 5).\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection entropy_definition.\n\nVariable A : finType.\nVariable P : dist A.\n\nDefinition entropy := - \\rsum_(a in A) P a * log (P a).\nLocal Notation \"'`H'\" := (entropy).\n\nLemma entropy_ge0 : 0 <= `H.\nProof.\nrewrite /entropy big_endo ?oppR0 //; last by move=> *; rewrite oppRD.\nrewrite (_ : \\rsum_(_ in _) _ = \\rsum_(i in A | predT A) - (P i * log (P i))); last first.\n  apply eq_bigl => i /=; by rewrite inE.\napply rsumr_ge0 => i _.\ncase/boolP : (P i == 0) => [/eqP ->|Hi].\n  (* NB: this step in a standard textbook would be handled as a\n     consequence of lim x->0 x log x = 0 *)\n  rewrite mul0R oppR0; exact/leRR.\nrewrite mulRC -mulNR.\napply mulR_ge0; last exact: dist_ge0.\napply oppR_ge0.\nrewrite /log -(Log_1 2).\napply Log_increasing_le => //; last exact: dist_max.\napply/ltRP; rewrite lt0R Hi; exact/leRP/dist_ge0.\nQed.\n\nHypothesis P_pos : forall b, 0 < P b.\n\nLemma entropy_pos_P_pos : 0 <= `H.\nProof.\nrewrite /entropy big_endo ?oppR0 //; last by move=> *; rewrite oppRD.\nrewrite (_ : \\rsum_(_ in _) _ = \\rsum_(i in A | predT A) - (P i * log (P i))).\n  apply rsumr_ge0 => i _.\n  rewrite mulRC -mulNR.\n  apply mulR_ge0; last exact: dist_ge0.\n  apply oppR_ge0.\n  rewrite /log -(Log_1 2).\n  apply Log_increasing_le => //; by [by apply P_pos | exact: dist_max].\napply eq_bigl => i /=; by rewrite inE.\nQed.\n\nEnd entropy_definition.\n\nNotation \"'`H'\" := (entropy) : entropy_scope.\n\nLocal Open Scope entropy_scope.\nLocal Open Scope proba_scope.\n\nLemma entropy_Ex {A} (P : dist A) : `H P = `E (--log P).\nProof.\nrewrite /entropy /mlog_rv ExE /= (big_morph _ morph_Ropp oppR0).\napply eq_bigr => a _; by rewrite mulRC -mulNR.\nQed.\n\nLemma xlnx_entropy {A} (P : dist A) :\n  `H P = / ln 2 * - \\rsum_(a : A) xlnx (P a).\nProof.\nrewrite /entropy mulRN; f_equal.\nrewrite (big_morph _ (morph_mulRDr _) (mulR0 _)).\napply eq_bigr => a _ ;rewrite /log /Rdiv mulRA mulRC; f_equal.\nrewrite /xlnx; case : ifP => // /ltRP Hcase.\nhave : P a = 0; last by move=> ->; rewrite mul0R.\ncase (Rle_lt_or_eq_dec 0 (P a)) => //; exact: dist_ge0.\nQed.\n\nLemma entropy_uniform {A : finType} n (HA : #|A| = n.+1) :\n  `H (Uniform.d HA) = log (INR #|A|).\nProof.\nrewrite /entropy /Uniform.d /Uniform.f /=.\nrewrite big_const iter_addR div1R mulRA mulRV; last by rewrite INR_eq0' HA.\nrewrite mul1R /log LogV ?oppRK //; by rewrite HA; apply/ltR0n.\nQed.\n\nLocal Open Scope reals_ext_scope.\n\nLemma entropy_max {A : finType} (P : dist A) : `H P <= log (INR #|A|).\nProof.\nhave [n HA] : exists n, #|A| = n.+1.\n  exists (#|A|.-1); rewrite prednK //; by apply (dist_domain_not_empty P).\nhave : P << (Uniform.d HA) by apply dom_by_uniform.\nmove/leq0div => H.\nrewrite /div in H.\nsuff Htmp : 0 <= - `H P + log (INR #|A|) by fourier.\napply/(leR_trans H)/Req_le.\ntransitivity (\\rsum_(a|a \\in A) P a * log (P a) + \\rsum_(a|a \\in A) P a * - log ((Uniform.d HA) a)).\n  rewrite -big_split /=.\n  apply eq_bigr => a _; by rewrite mulRDr.\nrewrite /= /Uniform.f /= div1R -[in X in _ + X = _]big_distrl /= pmf1 mul1R.\nrewrite /entropy oppRK /log LogV ?oppRK // HA; 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/entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7834920386036044}}
{"text": "(***************************)\n(* sumbool と it then else *)\n(***************************)\n\n(** 帰納型のチュートリアル **)\n(** A Tutorial on [Co-]Inductive Types in Coq **)\n(* 2.7 Logical connectives. *)\n\n(* {A} + {B} は sumbool A B の意味である。 *)\nLocate \"{ _ } + { _ }\".                     (* sumbool A B : type_scope *)\nPrint sumbool.\nCheck sumbool.\nCheck sumbool_ind.\nCheck sumbool_rec.\nCheck left.                                 (* forall A B : Prop, A -> {A} + {B} *)\nCheck right.                                (* forall A B : Prop, B -> {A} + {B} *)\n\nRequire Import Arith.\n(* これらを独自に定義したい。 *)\nCheck le_lt_dec.                            (* forall n m : nat, {n <= m} + {m < n} *)\nPrint le_lt_dec.\nCheck eq_nat_dec.                           (* forall n m : nat, {n = m} + {n <> m} *)\nPrint eq_nat_dec.\n\nEval compute in eq_nat_dec 1 1.             (* 真：left _ *)\nEval compute in eq_nat_dec 0 1.             (* 偽：right _ *)\n\nEval compute in le_lt_dec 0 1.              (* 真：left _ *)\nEval compute in le_lt_dec 1 0.              (* 偽：right _ *)\n\n(* match または if-then-else による定義 *)\nDefinition max (n p : nat) :=\n  match le_lt_dec n p with\n  | left _ => p\n  | right _ => n\n  end.\nPrint max.                                  (* if le_lt_dec n p then p else n *)\nCheck max.                                  (* nat -> nat -> nat *)\nEval compute in max 1 2.                    (* 2 *)\n\n(* これは、if-then-elseに変換される。 *)\nDefinition max' (n p : nat) :=\n  if le_lt_dec n p then p else n.\nEval compute in max' 1 2.                   (* 2 *)\n\n(* OCaml に変換すると、これは match である *)\nExtraction max.\n\n(* coqにおける、it-then-else と match の関係 *)\nEval compute in (if le_lt_dec 1 2 then 2 else 1). (* 2 *)\nEval compute in (match le_lt_dec 1 2 with left _ => 2 | right _ => 1 end). (* 2 *)\n\n(* case による振り分け *)\nTheorem le_max : forall n p, n <= p -> max n p = p.\n  intros n p H.\n  unfold max.\n  (* Goal : (if le_lt_dec n p then p else n) = p *)\n  case (le_lt_dec n p).\n    \n  (* Goal : n <= p -> p = p *)\n  reflexivity.                              (* 「->」が前についていても、問題ない *)\n\n  (* Goal : p < n -> n = p *)\n  intros l.\n  absurd (p < p).\n  eauto with arith.\n  eauto with arith.\nQed.\n\n(* この場合の case は、\n  コンストラクタの apply には置き換えられない。\n  see. coq_case.v  *)\n\nRequire Import Bool.Sumbool.\n\n(* boolを返すeq関数を定義する。 *)\nDefinition eq_bool (n p : nat) : bool :=\n  proj1_sig (bool_of_sumbool (eq_nat_dec n p)).\n\nEval compute in eq_bool 1 1.                (* 真：left _ *)\nEval compute in eq_bool 0 1.                (* 偽：right _ *)\n\n(* boolを返すle関数を定義する。 *)\nDefinition le_bool (n p : nat) : bool :=\n  proj1_sig (bool_of_sumbool (le_lt_dec n p)).\n\nEval compute in le_bool 0 1.                (* 真：left _ *)\nEval compute in le_bool 1 0.                (* 偽：right _ *)\n\nTheorem le_max' : forall n p, le_bool n p = true -> max n p = p.\n(* これを証明したい。 *)\nAdmitted.\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_sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7834920241844857}}
{"text": "Require Import Setoid Arith List Omega Coq.Program.Tactics LibTactics tactics.\nRequire Import Coq.Program.Equality.\n\n(* Set Implicit Arguments. *)\n\nModule Type Lattice.\n\nParameter T : Set.\nParameter join: T -> T -> T.\nParameter meet: T -> T -> T.\nParameter flowsto : T -> T -> Prop.\nParameter bot: T.\n  \nNotation \"X ⊑ Y\" := (flowsto X Y) (at level 70, no associativity).\nNotation \"X ⊔ Y\" := (join X Y) (at level 40, left associativity).\n\nAxiom meet_symmetry: forall a b   : T,  meet a b = meet b a.\nAxiom join_symmetry: forall a b   : T,  join a b = join b a.\nAxiom join_assoc   : forall a b c : T,  join a (join b c) = join (join a b) c.\nAxiom meet_assoc   : forall a b c : T,  meet a (meet b c) = meet (meet a b) c.\nAxiom meet_distrib : forall a b   : T,  meet a (join a b) = a.\nAxiom join_distrib : forall a b   : T,  join a (meet a b) = a.\nAxiom flowsto_dec  : forall a b   : T,  { a ⊑ b } + { not (a ⊑ b) }.\nAxiom join_flowsto : forall a b   : T,  join a b = b <-> flowsto a b.\nAxiom T_dec        : forall a b   : T,  { a = b} + { a <> b }.\nAxiom join_bot_left: forall a     : T, join bot a = a.\nAxiom join_bot_right: forall a    : T, join a bot = a.\n\n\nHint Resolve meet_symmetry join_symmetry join_assoc meet_assoc meet_distrib join_distrib\nflowsto_dec join_flowsto T_dec join_bot_left join_bot_right.\n\nEnd Lattice.\n\nModule LatticeProperties (L: Lattice).\nImport L.\n\nLemma idem_join:\n    forall a : T,\n      join a a = a.\nProof.\n  intros.\n  eauto.\n  rewrite <- (meet_distrib a a) at 2.\n  eauto.\nQed.\nLocal Hint Resolve idem_join.\n  \nLemma idem_meet:\n    forall a : T,\n      meet a a = a.\nProof.\n  intros.\n  rewrite <- (join_distrib a a) at 2.\n  eauto.\nQed.\nLocal Hint Resolve idem_meet.\n\nLemma flowsto_refl: forall a, flowsto a a.\nProof.\n  intro.\n  apply join_flowsto.\n  eauto.\nQed.\nLocal Hint Resolve flowsto_refl.\n\nLemma flowsto_trans: \n  forall a b c,\n    flowsto  a b ->\n    flowsto  b c ->\n    flowsto  a c.\nProof.\n  intros.\n  apply join_flowsto.\n  apply join_flowsto in H.\n  apply join_flowsto in H0.\n  rewrite <- H0.\n  replace  (join a(join b c)) with (join (join a b) c) by eauto.\n  rewrite -> H.\n  eauto.\nQed.\n\nHint Extern 1 (?a ⊑ ?c) =>\nmatch goal with\n| [H: a ⊑ ?b |- _] => apply (flowsto_trans a b c)\n| [H: ?b ⊑ c |- _] => apply (flowsto_trans a b c)\nend.\n  \nLemma anti_sym:\n  forall a b : T,\n    a ⊑ b ->\n    b ⊑ a ->\n    a = b.\nProof.\n  intros a b H1 H2.\n  apply join_flowsto in H1.\n  apply join_flowsto in H2.\n  replace (join b a) with (join a b) in * by eauto.\n  congruence.\nQed.\nLocal Hint Resolve anti_sym.\n\nLemma flowsto_not:\n  forall ℓ₁ ℓ₂ ℓ₃,\n    ℓ₁ ⊑ ℓ₂ ->\n    not (ℓ₁ ⊑ ℓ₃) ->\n    not (ℓ₂ ⊑ ℓ₃).\nProof.\n  intros ℓ₁ ℓ₂ ℓ₃ H1 H2.\n  intro H_absurd.\n  contradiction (flowsto_trans _ _ _ H1 H_absurd).\nQed.\nHint Resolve flowsto_not.\n\nLemma flowsto_join:\n  forall a b,\n    a ⊑ join a b.\nProof.\n  intros.\n  apply join_flowsto.\n  rewrite -> join_assoc.\n  rewrite -> idem_join.\n  reflexivity.\nQed.\n  \nLemma join_flowsto_implies_flowsto:\n  forall ℓ₁ ℓ₂ ℓ₃,\n    join ℓ₁ ℓ₂ ⊑ ℓ₃ -> ℓ₁ ⊑ ℓ₃ /\\ ℓ₂ ⊑ ℓ₃.\nProof.\n  intros.\n  assert (ℓ₁ ⊑ join ℓ₁ ℓ₂) by apply flowsto_join.\n  assert (ℓ₂ ⊑ join ℓ₁ ℓ₂) by (rewrite -> join_symmetry; apply flowsto_join).\n  split; eapply flowsto_trans; eauto.\nQed.\n\nLtac destruct_join_flowsto :=\n  match goal with\n    [H: join ?a ?b ⊑ ?c |- _] => destruct (join_flowsto_implies_flowsto a b c H); clear H\n  end.\n\nLemma not_flowsto_implies_not_join_flowsto:\n  forall a b c,\n    ~ a ⊑ c ->\n    ~ b ⊑ c ->\n    ~ join a b ⊑ c.\nProof.\n  intros.\n  intro.\n  rewrite <- join_flowsto in *.\n  rewrite <- H1 in *.\n  rewrite -> join_flowsto in *.\n  rewrite <- join_assoc in *.\n  contradiction H.\n  eapply flowsto_join.\nQed.\n\nLemma implies_join_flowsto:\n  forall a b c,\n    a ⊑ c ->\n    b ⊑ c ->\n    a ⊔ b ⊑ c.\nProof.\n  intros.\n  rewrite <- join_flowsto.\n  eapply join_flowsto in H.\n  eapply join_flowsto in H0.\n  rewrite <- join_assoc.\n  rewrite -> H0.\n  assumption.\nQed.\nHint Resolve implies_join_flowsto.\n\nEnd LatticeProperties.\n\nModule ProductLattice (A B : Lattice) <: Lattice.\n  Definition T := prod A.T B.T.  \n\n  Definition meet (x y : T) :=\n    match x, y with\n      (a1, b1), (a2, b2) => (A.meet a1 a2, B.meet b1 b2)\n    end.\n\n  Definition join (x y : T) :=\n    match x, y with\n      (a1, b1), (a2, b2) => (A.join a1 a2, B.join b1 b2)\n    end.\n  \n  Definition flowsto (a b : T) := join a b = b.\n  Local Hint Unfold flowsto.\n  \n  Lemma meet_symmetry: forall a b : T, meet a b = meet b a.\n  Proof.\n    intros.\n    unfolds.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    rewrite -> A.meet_symmetry.\n    rewrite -> B.meet_symmetry.\n    reflexivity.\n  Qed.\n\n  Lemma join_symmetry: forall a b : T, join a b = join b a.\n  Proof.\n    intros.\n    unfolds.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    rewrite -> A.join_symmetry.\n    rewrite -> B.join_symmetry.\n    reflexivity.\n  Qed.\n\n  Lemma join_assoc: forall a b c : T, join a (join b c) = join (join a b) c.\n  Proof.\n    intros.\n    unfold join.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    destruct c as [a3 b3].\n    rewrite -> A.join_assoc.\n    rewrite -> B.join_assoc.\n    reflexivity.\n  Qed.\n\n  Lemma meet_assoc: forall a b c : T, meet a (meet b c) = meet (meet a b) c.\n  Proof.\n    intros.\n    unfold meet.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    destruct c as [a3 b3].\n    rewrite -> A.meet_assoc.\n    rewrite -> B.meet_assoc.\n    reflexivity.\n  Qed.\n\n  Lemma meet_distrib: forall a b : T, meet a (join a b) = a.\n  Proof.\n    intros.\n    unfold meet, join.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    rewrite -> A.meet_distrib.\n    rewrite -> B.meet_distrib.\n    reflexivity.    \n  Qed.\n  Hint Resolve meet_distrib.\n  \n  Lemma join_distrib: forall a b : T, join a (meet a b) = a.\n  Proof.\n    intros.\n    unfold meet, join.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    rewrite -> A.join_distrib.\n    rewrite -> B.join_distrib.\n    reflexivity. \n  Qed.\n  Hint Resolve join_distrib.\n  \n  Notation \"X ⊑ Y\" := (flowsto X Y) (at level 70, no associativity).\n  Notation \"X ⊔ Y\" := (join X Y) (at level 40, left associativity).\n\n  Lemma join_flowsto: forall a b: T,\n      join a b = b <-> flowsto a b.\n  Proof.\n    split*.\n  Qed.\n\n  Lemma flowsto_pointwise_proj1:\n    forall (a1 a2 : A.T)\n      (b1 b2 : B.T),\n      flowsto (a1, b1) (a2, b2) ->\n      A.flowsto a1 a2.\n  Proof.\n    intros.\n    rewrite <- A.join_flowsto.\n    rewrite <- join_flowsto in *.\n    injects.\n    assumption.\n  Qed.\n  Hint Resolve flowsto_pointwise_proj1.\n\n  Lemma flowsto_pointwise_proj2:\n    forall (a1 a2 : A.T)\n      (b1 b2 : B.T),\n      flowsto (a1, b1) (a2, b2) ->\n      B.flowsto b1 b2.\n  Proof.\n    intros.\n    rewrite <- B.join_flowsto.\n    rewrite <- join_flowsto in *.\n    injects.\n    assumption.\n  Qed.\n  Hint Resolve flowsto_pointwise_proj2.      \n\n  Lemma join_is_pairwise:\n    forall (a1 a2 : A.T)\n      (b1 b2 : B.T),\n      join (a1, b1) (a2, b2) =\n      (A.join a1 a2, B.join b1 b2).\n  Proof.\n    intros.\n    unfolds.\n    reflexivity.\n  Qed.\n\n  Lemma flowsto_dec: forall a b : T,\n      {a ⊑ b} + {not (a ⊑ b)}.\n  Proof.\n    intros a b.\n    destruct a as [a1 b1].\n    destruct b as [a2 b2].\n    destruct (A.flowsto_dec a1 a2); destruct (B.flowsto_dec b1 b2).\n    - left.\n      rewrite <- join_flowsto.\n      rewrite <- A.join_flowsto in * |-.\n      rewrite <- B.join_flowsto in * |-.\n      unfolds.\n      rewrite -> f.\n      rewrite -> f0.\n      reflexivity.\n    - right.\n      intro.\n      rewrite <- join_flowsto in *.\n      contradict n.\n      rewrite <- B.join_flowsto.\n      unfolds in H.\n      injects.\n      assumption.\n    - right.\n      intro.\n      rewrite <- join_flowsto in *.\n      contradict n.\n      rewrite <- A.join_flowsto.\n      unfolds in H.\n      injects.\n      assumption.\n    - right.\n      intro.\n      rewrite <- join_flowsto in *.\n      unfolds in H.\n      injects.\n      contradict n.\n      rewrite <- A.join_flowsto.\n      assumption.\n  Defined.\n\nLemma T_dec: forall a b : T, {a = b} + {a <> b}.\nProof.\n  intros.\n  destruct a as [a1 b1].\n  destruct b as [a2 b2].\n  destruct (A.T_dec a1 a2); destruct (B.T_dec b1 b2); subst.\n  - left.\n    reflexivity.\n  - right.\n    intro; injects.\n    eauto.\n  - right.\n    intro; injects.\n    eauto.\n  - right.\n    intro; injects.\n    eauto.\nQed.\n\nDefinition bot := (A.bot, B.bot).\n\nLemma join_bot_left:\n  forall a,\n    join bot a = a.\nProof.\n  intros.\n  destruct a as [a b].\n  unfolds.\n  unfold bot.\n  rewrite -> A.join_bot_left.\n  rewrite -> B.join_bot_left.\n  reflexivity.\nQed.\nHint Resolve join_bot_left.\n\nLemma join_bot_right:\n  forall a,\n    join a bot = a.\nProof.\n  intros.\n  destruct a as [a b].\n  unfolds.\n  unfold bot.\n  rewrite -> A.join_bot_right.\n  rewrite -> B.join_bot_right.\n  reflexivity.\nQed.\nHint Resolve join_bot_right.\n\nLemma implies_flowsto:\n  forall a1 a2 b1 b2,\n    A.flowsto a1 a2 ->\n    B.flowsto b1 b2 ->\n    flowsto (a1, b1) (a2, b2).\nProof.\n  intros.\n  unfolds.\n  rewrite -> join_is_pairwise.\n  rewrite <- A.join_flowsto in *.\n  rewrite <- B.join_flowsto in *.\n  congruence.\nQed.\nHint Resolve implies_flowsto.\n  \nEnd ProductLattice.\n\nModule LH <: Lattice.\n\nInductive LH :=\n| L: LH\n| H: LH.\n\nDefinition T := LH.\n\nDefinition meet (a b : LH) :=\n  match a with\n    | L => L\n    | H => b\n  end.\n\nDefinition join (a b : LH) :=\n  match a with\n  | L => b\n  | H => H\n  end.\n\n\nLemma meet_symmetry: forall a b : LH, meet a b = meet b a.\nProof.\n  intros.\n  unfold meet.\n  case a; case b; auto.\nQed.\n\nLemma join_symmetry :forall a b : LH, join a b = join b a.\nProof.\n  intros; unfold join. case a; case b; auto.\nQed.\n\nLemma join_assoc: forall a b c :LH , join a (join b c) = join ( join a b) c.\nProof.\n  intros.\n  unfold join.\n  case a; case b; case c; auto.\nQed.\n\nLemma meet_assoc: forall a b c: LH, meet a (meet b c) = meet (meet a b) c.\nProof.\n  intros.\n  unfold join.\n  case a; case b; case c; auto.\nQed.\n\nLemma meet_distrib: forall a b : LH, meet a (join a b) = a.\nProof.\n  intros; case a; case b; auto.\nQed.\n\nLemma join_distrib: forall a b : LH, join a (meet a b) = a.\nProof.\n  intros; case a; case b; auto.\nQed.\n\nDefinition flowsto a b := join a b = b.\nLocal Hint Unfold flowsto.\n  \nNotation \"X ⊑ Y\" := (flowsto X Y) (at level 70, no associativity).\nNotation \"X ⊔ Y\" := (join X Y) (at level 20, left associativity).\n\nLemma flowsto_dec: forall a b : T,\n    {a ⊑ b} + {not (a ⊑ b)}.\nProof.\n  intros a b.\n  destruct a; destruct b.\n  - left; eauto.\n  - left; eauto.\n  - right. unfold not; intros. inversion H0.\n  - left; eauto.\nDefined.  \n\nLemma T_dec: forall a b : LH, {a = b } + {a <> b}.\nProof.\n  intros.\n  destruct a; destruct b; eauto; right; congruence.\nQed.\n\nLemma join_flowsto: forall a b: LH,\n  join a b = b <-> flowsto a b.\nProof.\n  split.\n  - eauto.\n  - intros.\n    eauto.\nQed.\n\nDefinition bot := L.\n\nLemma join_bot_left:\n  forall a,\n    join bot a = a.\nProof.\n  reflexivity.\nQed.\nHint Resolve join_bot_left.\n\nLemma join_bot_right:\n  forall a,\n    join a bot = a.\nProof.\n  intros.\n  destruct a; reflexivity.\nQed.\nHint Resolve join_bot_right.\n\nEnd LH.", "meta": {"author": "MathiasVP", "repo": "ni-formal-gc", "sha": "07899c51af76b237d382dc825904fc9158cd905d", "save_path": "github-repos/coq/MathiasVP-ni-formal-gc", "path": "github-repos/coq/MathiasVP-ni-formal-gc/ni-formal-gc-07899c51af76b237d382dc825904fc9158cd905d/mlattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7833929265680761}}
{"text": "(* BEGIN FIX *)\nFixpoint 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(* END FIX *)\n match t with\n  | Leaf => 0\n  | Node2 t1 t2 => 1 + (max (height t1) (height t2))\n  | Node3 t1 t2 t3 => 1 + max (max (height t1) (height t2)) (height t3)\nend.\n\n(* BEGIN FIX *)\nExample height_test_1 : height exTree1 = 2.\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nExample height_test_2 : height exTree2 = 4.\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nLemma max_0 (m : nat) : max m 0 = m.\n(* END FIX *)\nsimpl.\ninduction m as [|m H].\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nLemma height_Leaf (t : Tree) : height (Node2 t Leaf) = height (Node2 Leaf t).\n(* END FIX *)\nsimpl.\nrewrite -> max_0.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nLemma max_comm : forall (m n : nat),  max m n = max n m.\n(* END FIX *)\ninduction m as[|m' H].\nintros.\nrewrite -> max_0.\nsimpl.\nreflexivity.\nintros.\nsimpl.\ninduction n as [|n' H2].\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> H.\nreflexivity.\nQed.", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/03/hf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7833657676357738}}
{"text": "(*This contains both natlists and bags implementation*)\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\n  Notation \"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).\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.\n\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\n\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\n\nFixpoint nonzeros (k:natlist) : natlist :=\n  match k with\n  | nil => nil\n  | 0 :: l => nonzeros(l)\n  | h :: l => [h] ++ nonzeros(l)\n  end.\n\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nFixpoint oddmembers (k:natlist) : natlist :=\n  match k with\n  | nil => nil\n  | h :: l =>\n    match evenb(h) with\n    |true => oddmembers (l)\n    |false => [h] ++ oddmembers (l)\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 :=\nlength(oddmembers(l)).\n\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\n\nDefinition bag := natlist.\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\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | m :: s' =>\n    match beq_nat (v) (m) with\n    | true => 1 + count (v) (s')\n    | false  => count (v) (s')\n    end\n  end.\n\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\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 := sum s [v].\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\n\nDefinition member (v:nat) (s:bag) : bool :=\nmatch beq_nat (count (v) (s)) (0) with\n|true => false\n|false => 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 :=\nmatch s with\n| nil => nil\n| x :: n =>\n  match beq_nat (x) (v) with\n  | true => n\n  | false => x :: remove_one (v) (n)\n  end\nend.\n\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\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 :=\nmatch s with\n| nil => nil\n| x :: n =>\n  match beq_nat (x) (v) with\n  | true => remove_all (v) (n)\n  | false => x :: remove_all (v) (n)\n  end\nend.\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\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => true\n  | x :: n =>\n    match member (x) (s2) with\n    |true => subset (n) (remove_one x 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\nTheorem bag_theorem : forall x:nat, count(x)(add (x) ([])) = 1.\nProof.\nintros x.\nsimpl. induction x as [|IHx].\n- reflexivity.\n- simpl. rewrite -> IHIHx. 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. 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. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\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.\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  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m.\ninduction n as [| n' IHn'].\n- reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\nintros n m.\ninduction m as [| m' IHm'].\n- simpl. induction n as [| n' IHn'].\n+ reflexivity.\n+ simpl. rewrite -> IHn'. reflexivity.\n- simpl. rewrite <- IHm'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\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", "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/chapter3/natList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7833657664972496}}
{"text": "Require Import Arith.\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n  intros.\n  apply plus_lt_compat_r.\n  exact 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  exact H.\nQed.\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\n  intros.\n  exists 1.\n  simpl.\n  exact 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. (* existsに対してdestructできることを覚えておこう *)\n  apply (H x).\n  exact H0.\nQed.\n\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nProof.\n  intros m n.\n  rewrite mult_comm.\n  reflexivity.\nQed.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  apply plus_permute_2_in_4.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\n  intros.\n  rewrite mult_plus_distr_l.\n  rewrite mult_plus_distr_r.\n  rewrite mult_plus_distr_r.\n  simpl.\n  rewrite <- plus_n_O.\n  rewrite mult_plus_distr_r.\n  rewrite (plus_comm (n * m) (m * m)).\n  rewrite plus_permute_2_in_4.\n  rewrite (mult_comm m n).\n  reflexivity.\nQed.\n\nModule Task10.\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\n(* 自力じゃできなかった... *)\n(* 群論のサイト見た *)\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  intro x.\n  rewrite <- (one_unit_l (x * / x)).\n  rewrite <- (inv_l (/ x)) at 1.\n  rewrite <- (mult_assoc (/ / x) (/ x) (x * / x)).\n  rewrite (mult_assoc (/ x) x (/ x)).\n  rewrite (inv_l x).\n  rewrite one_unit_l.\n  rewrite inv_l.\n  reflexivity.\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 x).\n  rewrite one_unit_l.\n  reflexivity.\nQed.\n\nEnd Task10.\n", "meta": {"author": "sakabar", "repo": "CoqExercise", "sha": "f1138c25b4bc2b27edb9827b1712150ae3995b30", "save_path": "github-repos/coq/sakabar-CoqExercise", "path": "github-repos/coq/sakabar-CoqExercise/CoqExercise-f1138c25b4bc2b27edb9827b1712150ae3995b30/ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7833657590933224}}
{"text": "\n\n\n\n\n(* ------   In this file we formalize the concept of sorting in a list.  We consider lists\n   of elements (on an arbitrary type A) with a boolean comparison operator (lr: A-> A-> bool).\n   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. \n\n   Following are the concepts formalized in this file: \n\n   Sorted l      <==> 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         ==> 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 Lia.\n\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  (* ------------- 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 H H0. constructor. auto. intros x H1. destruct H1. subst x. auto.\n         eapply Htrans with (y:=b). eauto. inversion H0. eauto. } Qed.\n\n\n  Lemma Sorted_elim1 (a:A) (b:A) (l: list A): (Sorted (a::b::l)) -> (a <=r b).\n  Proof. intro H. inversion H.  eapply H3. auto.  Qed.\n  Lemma Sorted_elim4 (a:A) (l:list A): Sorted (a::l) ->(forall x, In x l -> a <=r x).\n  Proof. intro H. inversion H. auto. 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. intro H. inversion H. intros. destruct H4. subst x.  eauto. eauto. Qed.\n  Lemma Sorted_elim3 (a:A) (l:list A): (Sorted (a::l)) -> Sorted l.\n  Proof. intro H. inversion H;auto. Qed.\n  Lemma Sorted_subset (a1 a2:A) (l1 l2: list A) (Htrans: transitive lr)(Hrefl: reflexive lr):\n  Sorted (a1::l1) -> Sorted (a2::l2) -> (a1::l1) [<=] (a2::l2) -> In a2 (a1::l1)\n  -> (a1 <=r a2)/\\a2 <=r a1.\n  Proof. intros. eapply Sorted_elim2 with (a:=a1)(x:=a2) in H. assert (In a1 (a2::l2)).\n  apply H1. auto. eapply Sorted_elim2 with (a:=a2)(x:=a1) in H3. auto. auto. auto.\n  auto. auto. Qed.\n\n  Lemma Sorted_single : forall a:A, (Sorted (a::nil)).\n  Proof. constructor. constructor. intros;simpl;contradiction. Qed.\n  \n  Lemma last_in_Sorted (a d:A)(l:list A)(Htrans: transitive lr)(Hrefl: reflexive lr): \n   Sorted l -> In a l -> lr a (last l d).\n  Proof. { revert a. \n         induction l as [|b1 l']. \n         { intros a H H0. simpl in H0. auto. }\n         { intros a0 H H0. \n           destruct H0.\n           { subst b1.\n           case l' as [|b2 l''] eqn: H1.\n           { simpl. auto. }\n           { replace (last (a0 :: b2 :: l'') d) with (last (b2 :: l'') d). \n             assert (H2: b2 <=r (last (b2 :: l'') d)). \n             { apply IHl'. eapply Sorted_elim3. exact H. auto. }\n             assert (H3: a0 <=r b2). \n             { eapply Sorted_elim1. exact H. }\n             eauto. \n             simpl. destruct l'';auto. } }\n            { case l' as [|b2 l''] eqn: H1.\n             { destruct H0. }\n             { replace (last (b1 :: b2 :: l'') d) with (last (b2 :: l'') d). \n             apply IHl'. eapply Sorted_elim3. exact H. auto. \n             simpl. destruct l'';auto. } } } } Qed.\n\n\n  Hint Resolve Sorted_elim1 Sorted_elim2 Sorted_elim3 Sorted_elim4\n       Sorted_single Sorted_intro last_in_Sorted : 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. simpl in H. contradiction. simpl.\n           destruct ( a <=r a0). destruct H. subst x. all: auto.  destruct H. subst x; auto.\n          apply IHl in H as H1;auto.  } Qed.\n         \n  Lemma putin_intro1 (a:A) (l: list A): In a (putin a l).\n  Proof. { induction l. simpl. tauto. simpl. destruct ( a <=r a0). all: auto.  } Qed.\n\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. simpl in H. simpl. destruct H. left. auto. auto.\n           simpl in H. destruct ( a <=r a0).   destruct H. auto. auto. destruct H.\n           right;subst x;auto. apply IHl in H as H2. destruct H2. auto. right. auto.  } Qed.\n   \n(*  Definition comparable (lr: A->A-> bool) := forall x y, lr x y =false-> lr y x.*)\nDefinition comparable (lr: A->A-> bool) := forall x y, lr x y =true \\/ lr y x = true.\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. revert a.  induction l.\n         { intros a1 H.  simpl. apply Sorted_single. }\n           simpl. intros a1 H.  destruct ( a1 <=r a) eqn:H0.\n         {  auto.  }\n         { unfold comparable in H_comp. specialize (H_comp a1 a). \n           destruct H_comp. { rewrite H1 in H0. inversion H0. } { constructor. eauto. \n           intros x H2. apply putin_elim in H2 as H3. destruct H3.\n           subst x;auto. eauto. } } } 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 x H. induction l. eauto. simpl. destruct H. subst x.\n         apply putin_intro1. eauto using putin_intro. } Qed.\n\n  Lemma sort_elim (l: list A): forall x, In x (sort l) -> In x l.\n  Proof. { intros x H. induction l. simpl in H. contradiction.\n         simpl in H. apply putin_elim in H. destruct H. subst x;eauto. eauto. } Qed.\n\n  Lemma sort_correct (H_trans: transitive lr)(H_comp: comparable lr):\n    forall(l: list A), Sorted (sort l).\n  Proof. induction l. simpl. constructor. simpl. eauto using putin_correct. Qed.\n\n  Hint Resolve sort_elim sort_intro sort_correct: core.\n  \n  Lemma sort_equal (l: list A): Equal l (sort l).\n  Proof. split;intro; eauto. Qed.\n\n   Lemma sort_equal1 (l: list A): Equal (sort l) l.\n  Proof. split;intro; eauto. Qed.\n\n  Lemma sort_same_size (l: list A): |sort l| = |l|.\n  Proof. { induction l.\n         { simpl;auto. }\n         { simpl. replace (|putin a (sort l)|) with (S(|sort l|)).\n           rewrite IHl. auto. symmetry. apply putin_card. } } Qed.\n\n  Lemma Sorted_equal (l l': list A): Equal l l' -> Equal l (sort l').\n  Proof. intro. cut (Equal l' (sort l')). eauto.  apply sort_equal. Qed.\n  Lemma Sorted_equal1(l l': list A): Equal l l' -> Equal (sort l) l'.\n  Proof. intro. cut (Equal l (sort l)). eauto. apply sort_equal. Qed.\n\n  Lemma nodup_sort (l: list A): NoDup l -> NoDup (sort l).\n  Proof. { induction l. eauto.\n         {  simpl. intro H.  cut (NoDup (a::sort l)). eauto.\n            constructor.\n            { intro H1. absurd (In a l). inversion H; auto. eapply  sort_equal;auto. }\n            eauto. } } Qed.\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  Lemma sort_equal_nodup (l: list A)(Href: reflexive lr)(Hanti: antisymmetric lr):\n    Sorted l-> NoDup l-> sort l = l.\n  Proof. { induction l. auto. intros. simpl. rewrite IHl.\n           eauto. eauto. case l eqn:Hl. simpl. auto. intros. simpl.\n           destruct (a <=r a0) eqn:Ha. f_equal.\n           apply Sorted_elim2 with (x:=a0) in H.\n           assert(a=a0). apply Hanti. apply /andP.\n           split. auto. rewrite H in Ha.\n           auto. subst. assert(~In a0 ((a0 :: l0))).\n           eauto. assert(In a0 (a0 :: l0)). auto.\n           unfold not in H1. apply H1 in H2. \n           elim H2. apply Href. auto. } Qed. \n           \n\nEnd Sorting. \n\n\nHint Resolve Sorted_elim1 Sorted_elim2 Sorted_elim3 Sorted_elim4\n     Sorted_single Sorted_intro last_in_Sorted : core.\nHint Resolve putin_intro putin_intro1 putin_elim putin_correct nodup_putin : core.\nHint Resolve sort_elim sort_intro sort_correct sort_same_size : core.\nHint Resolve sort_equal sort_equal1 Sorted_equal Sorted_equal1 nodup_sort: core.\nHint Resolve empty_equal_nil_l head_equal_l: core.\nHint Immediate sort_equal_nodup: core.\n\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": "suneel-sarswat", "repo": "dsam", "sha": "81ed4b1c2c07db12de7e9db78fa6538ad31e01de", "save_path": "github-repos/coq/suneel-sarswat-dsam", "path": "github-repos/coq/suneel-sarswat-dsam/dsam-81ed4b1c2c07db12de7e9db78fa6538ad31e01de/DecSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8596637541053282, "lm_q1q2_score": 0.7833081743202799}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without\u0002locality\".\nFrom Foundations Require Export Logic.\nFrom Coq Require Import Lia.\n\nFixpoint div2 (n : nat) :=\n  match n with \n  | O => O\n  | 1 => O\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\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\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_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\n  | rt_trans (x y z : X) :\n      clos_refl_trans R x y ->\n      clos_refl_trans R y z ->\n      clos_refl_trans R x z\n  | rt_refl (x : X) : clos_refl_trans R x x.\n\nInductive clos_sym_refl_trans {X : Type} (R : X -> X -> Prop) : X -> X -> Prop :=\n  | srt_step (x y : X) : R x y -> clos_sym_refl_trans R x y\n  | srt_trans (x y z : X) :\n      clos_sym_refl_trans R x y ->\n      clos_sym_refl_trans R y z ->\n      clos_sym_refl_trans R x z\n  | srt_refl (x : X) : clos_sym_refl_trans R x x\n  | srt_sym (x y : X) : \n      clos_sym_refl_trans R x y ->\n      clos_sym_refl_trans R y x.\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.", "meta": {"author": "Sterling1111", "repo": "Coq_Projects", "sha": "f8b4d3cf81dfb7144e9939288d37d0299d37ab5d", "save_path": "github-repos/coq/Sterling1111-Coq_Projects", "path": "github-repos/coq/Sterling1111-Coq_Projects/Coq_Projects-f8b4d3cf81dfb7144e9939288d37d0299d37ab5d/Foundations/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7833081689707573}}
{"text": "\n(** In this file, we define matrices and prove many basic facts from linear algebra *)\n\nRequire Import Psatz. \nRequire Import String.\nRequire Import Program.\nRequire Import List.\nRequire Export Summation. \n\n\n\n(* TODO: Use matrix equality everywhere, declare equivalence relation *)\n(* TODO: Make all nat arguments to matrix lemmas implicit *)\n\n\n(** * Matrix definitions and infrastructure **)\n\nDeclare Scope genmatrix_scope.\nDelimit Scope genmatrix_scope with GM.\nOpen Scope genmatrix_scope.\n\n\n\nSection LinAlgOverCommRing.\n  Variables (F : Type).   (* F for ring, too bad R is taken :( *)\n  Variable (R0 : Monoid F).\n  Variable (R1 : Group F).\n  Variable (R2 : Comm_Group F).\n  Variable (R3 : Ring F).\n  Variable (R4 : Comm_Ring F).\n\n(* TODO: make this better (although it already works well despite being naive) *)\nLtac dumb_lRa := repeat (repeat rewrite Gmult_plus_distr_l;\n                         repeat rewrite Gmult_plus_distr_r;\n                         repeat rewrite Gmult_assoc;\n                         repeat rewrite Gmult_1_l;\n                         repeat rewrite Gmult_1_r; \n                         repeat rewrite Gmult_0_l;\n                         repeat rewrite Gmult_0_r;\n                         repeat rewrite Gplus_assoc;\n                         repeat rewrite Gplus_0_l;\n                         repeat rewrite Gplus_0_r; try easy).\n\n\n\nLemma F_ring_theory : ring_theory 0%G 1%G Gplus Gmult Gminus Gopp eq.\nProof. apply (@G_ring_theory F _ _ _ _ R4). Qed.\n\nAdd Ring F_ring_ring : F_ring_theory.\n\n\n \n\nLocal Open Scope nat_scope.\nLocal Open Scope group_scope.\n\n\n\nDefinition GenMatrix (m n : nat) := nat -> nat -> F.\n\nDefinition WF_GenMatrix {m n: nat} (A : GenMatrix m n) : Prop := \n  forall x y, x >= m \\/ y >= n -> A x y = 0. \n\nNotation Vector n := (GenMatrix n 1).\n\nNotation Square n := (GenMatrix n n).\n\n(** Equality via functional extensionality *)\nLtac prep_genmatrix_equality :=\n  let x := fresh \"x\" in \n  let y := fresh \"y\" in \n  apply functional_extensionality; intros x;\n  apply functional_extensionality; intros y.\n\n(** Matrix equivalence *)\n\nDefinition genmat_equiv {m n : nat} (A B : GenMatrix m n) : Prop := \n  forall i j, i < m -> j < n -> A i j = B i j.\n\nInfix \"==\" := genmat_equiv (at level 70) : genmatrix_scope.\n\nLemma genmat_equiv_refl : forall m n (A : GenMatrix m n), genmat_equiv A A.\nProof. unfold genmat_equiv; reflexivity. Qed.\n\nLemma genmat_equiv_eq : forall {m n : nat} (A B : GenMatrix m n),\n  WF_GenMatrix A -> \n  WF_GenMatrix B -> \n  A == B ->\n  A = B.\nProof.\n  intros m n A' B' WFA WFB Eq.\n  prep_genmatrix_equality.\n  unfold genmat_equiv in Eq.\n  bdestruct (x <? m).\n  bdestruct (y <? n).\n  + apply Eq; easy.\n  + rewrite WFA, WFB; trivial; right; try lia.\n  + rewrite WFA, WFB; trivial; left; try lia.\nQed.\n\n(** Printing *)\n\nParameter print_F : F -> string.\nFixpoint print_row {m n} i j (A : GenMatrix m n) : string :=\n  match j with\n  | 0   => \"\\n\"\n  | S j' => print_F (A i j') ++ \", \" ++ print_row i j' A\n  end.\nFixpoint print_rows {m n} i j (A : GenMatrix m n) : string :=\n  match i with\n  | 0   => \"\"\n  | S i' => print_row i' n A ++ print_rows i' n A\n  end.\nDefinition print_genmatrix {m n} (A : GenMatrix m n) : string :=\n  print_rows m n A.\n\n(** 2D list representation *)\n    \nDefinition list2D_to_genmatrix (l : list (list F)) : \n  GenMatrix (length l) (length (hd [] l)) :=\n  (fun x y => nth y (nth x l []) 0).\n\nLemma WF_list2D_to_genmatrix : forall m n li, \n    length li = m ->\n    (forall li', In li' li -> length li' = n)  ->\n    @WF_GenMatrix m n (list2D_to_genmatrix li).\nProof.\n  intros m n li L f x y [l | r].\n  - unfold list2D_to_genmatrix. \n    rewrite (nth_overflow _ []).\n    destruct y; easy.\n    rewrite L. apply l.\n  - unfold list2D_to_genmatrix. \n    rewrite (nth_overflow _ 0).\n    easy.\n    destruct (nth_in_or_default x li []) as [IN | DEF].\n    apply f in IN.\n    rewrite IN. apply r.\n    rewrite DEF.\n    simpl; lia.\nQed.\n\n(** Example *)\nDefinition M23 : GenMatrix 2 3 :=\n  fun x y => \n  match (x, y) with\n  | (0, 0) => 1\n  | (0, 1) => 1+1\n  | (0, 2) => 1+1+1\n  | (1, 0) => 1+1+1+1\n  | (1, 1) => 1+1+1+1+1\n  | (1, 2) => 1+1+1+1+1+1\n  | _ => 0\n  end.\n\nDefinition M23' : GenMatrix 2 3 := \n  list2D_to_genmatrix  \n  ([ [1; 1+1; 1+1+1];\n    [1+1+1+1; 1+1+1+1+1; 1+1+1+1+1+1] ]).\n\nLemma M23eq : M23 = M23'.\nProof.\n  unfold M23'.\n  compute.\n  prep_genmatrix_equality.\n  do 4 (try destruct x; try destruct y; simpl; trivial).\nQed.\n\n\n(** * Operands and operations **)\n\n\nDefinition Zero {m n : nat} : GenMatrix m n := fun x y => 0.\n\nDefinition I (n : nat) : Square n := \n  (fun x y => if (x =? y) && (x <? n) then 1 else 0).\n\n(* Optional coercion to scalar (should be limited to 1 × 1 matrices):\nDefinition to_scalar (m n : nat) (A: GenMatrix m n) : C := A 0 0.\nCoercion to_scalar : GenMatrix >-> C.\n*)\n\n(* This isn't used, but is interesting *)\nDefinition I__inf := fun x y => if x =? y then 1 else 0.\nNotation \"I∞\" := I__inf : genmatrix_scope.\n\n\n\n(*TODO: the placement of G's is horribly inconsistent... can probably be fixed since\n eventually Matrix n m will be something more specific like CMatrix n m *)\nDefinition trace {n : nat} (A : Square n) := \n  big_sum (fun x => A x x) n.\n\nDefinition scale {m n : nat} (r : F) (A : GenMatrix m n) : GenMatrix m n := \n  fun x y => (r * A x y).\n\nDefinition dot {n : nat} (A : Vector n) (B : Vector n) : F :=\n  big_sum (fun x => A x 0  * B x 0) n.\n\nDefinition GMplus {m n : nat} (A B : GenMatrix m n) : GenMatrix m n :=\n  fun x y => (A x y + B x y).\n\nDefinition GMopp {m n : nat} (A : GenMatrix m n) : GenMatrix m n :=\n  scale (Gopp 1) A.\n\nDefinition GMminus {m n : nat} (A B : GenMatrix m n) : GenMatrix m n :=\n  GMplus A (GMopp B).\n\nDefinition GMmult {m n o : nat} (A : GenMatrix m n) (B : GenMatrix n o) : GenMatrix m o := \n  fun x z => big_sum (fun y => A x y * B y z) n.\n\n\n(* Only well-defined when o and p are non-zero *)\nDefinition Gkron {m n o p : nat} (A : GenMatrix m n) (B : GenMatrix o p) : \n  GenMatrix (m*o) (n*p) :=\n  fun x y => Gmult (A (x / o)%nat (y / p)%nat) (B (x mod o) (y mod p)).\n\nDefinition direct_sum {m n o p : nat} (A : GenMatrix m n) (B : GenMatrix o p) :\n  GenMatrix (m+o) (n+p) :=\n  fun x y =>  if (x <? m) || (y <? n) then A x y else B (x - m)%nat (y - n)%nat.\n\nDefinition transpose {m n} (A : GenMatrix m n) : GenMatrix n m := \n  fun x y => A y x.\n\n(* NB: no adjoint! \nDefinition adjoint {m n} (A : GenMatrix m n) : GenMatrix n m := \n  fun x y => (A y x)^*.\n*)\n\n\n(* no adjoint! so these are defined in terms of transpose. good for R, but is this correct? *)\nDefinition inner_product {n} (u v : Vector n) : F := \n  GMmult (transpose u) (v) 0 0.\n\nDefinition outer_product {n} (u v : Vector n) : Square n := \n  GMmult u (transpose v).\n\n(** Kronecker of n copies of A *)\nFixpoint kron_n n {m1 m2} (A : GenMatrix m1 m2) : GenMatrix (m1^n) (m2^n) :=\n  match n with\n  | 0    => I 1\n  | S n' => Gkron (kron_n n' A) A\n  end.\n\n(** Kronecker product of a list *)\nFixpoint big_kron {m n} (As : list (GenMatrix m n)) : \n  GenMatrix (m^(length As)) (n^(length As)) := \n  match As with\n  | [] => I 1\n  | A :: As' => Gkron A (big_kron As')\n  end.\n\n(** Product of n copies of A, basically GMpow *)\nFixpoint GMmult_n {m} (A : Square m) p : Square m :=\n  match p with\n  | 0    => I m\n  | S p' => GMmult A (GMmult_n A p')\n  end.\n\n(** Direct sum of n copies of A *)\nFixpoint direct_sum_n n {m1 m2} (A : GenMatrix m1 m2) : GenMatrix (n*m1) (n*m2) :=\n  match n with\n  | 0    => @Zero 0 0\n  | S n' => direct_sum A (direct_sum_n n' A)\n  end.\n\n\n\n\n(** Notations *) \nInfix \"∘\" := dot (at level 40, left associativity) : genmatrix_scope.\nInfix \".+\" := GMplus (at level 50, left associativity) : genmatrix_scope.\nInfix \".*\" := scale (at level 40, left associativity) : genmatrix_scope.\nInfix \"×\" := GMmult (at level 40, left associativity) : genmatrix_scope.\nInfix \"⊗\" := Gkron (at level 40, left associativity) : genmatrix_scope.\nInfix \".⊕\" := direct_sum (at level 20) : genmatrix_scope. (* should have different level and assoc *)\nInfix \"≡\" := genmat_equiv (at level 70) : genmatrix_scope.\nNotation \"A ⊤\" := (transpose A) (at level 0) : genmatrix_scope. \n(* Notation \"A †\" := (adjoint A) (at level 0) : genmatrix_scope. *)\nNotation Σ := (@big_sum F R0).  (* we intoduce Σ notation here *)\nNotation \"n ⨂ A\" := (kron_n n A) (at level 30, no associativity) : genmatrix_scope.\nNotation \"⨂ A\" := (big_kron A) (at level 60): genmatrix_scope.\nNotation \"p ⨉ A\" := (GMmult_n A p) (at level 30, no associativity) : genmatrix_scope.\nNotation \"⟨ u , v ⟩\" := (inner_product u v) (at level 0) : genmatrix_scope. \n\n\nHint Unfold Zero I trace dot GMplus GMopp scale GMmult Gkron genmat_equiv transpose : U_db.\n\n\nLtac destruct_m_1 :=\n  match goal with\n  | [ |- context[match ?x with \n                 | 0   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  end.\nLtac destruct_m_eq := repeat (destruct_m_1; simpl).\n\n\nLtac lgma := \n  autounfold with U_db;\n  prep_genmatrix_equality;\n  destruct_m_eq; \n  (* lca. *)  (* !!! everything is destroyed without lca for rings *)\n  ring.\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;\n  let i := fresh \"i\" in \n  let j := fresh \"j\" in \n  let Hi := fresh \"Hi\" in \n  let Hj := fresh \"Hj\" in \n  intros i j Hi Hj; try solve_end;\n  repeat (destruct i as [|i]; simpl; [|apply Nat.succ_lt_mono in Hi]; try solve_end); clear Hi;\n  repeat (destruct j as [|j]; simpl; [|apply Nat.succ_lt_mono in Hj]; try solve_end); clear Hj.\n\nLtac lgma' :=\n  apply genmat_equiv_eq;\n  repeat match goal with\n  | [ |- WF_GenMatrix (?A) ]  => auto with wf_db (* (try show_wf) *)\n  | [ |- genmat_equiv (?A) (?B) ] => by_cell; try ring (* try lca  *)             \n  end.\n\n\n\n\n(** * Showing that M is a vector space *)\n\nProgram Instance GM_is_monoid : forall n m, Monoid (GenMatrix n m) := \n  { Gzero := @Zero n m\n  ; Gplus := GMplus\n  }.\nSolve All Obligations with program_simpl; prep_genmatrix_equality; \n  autounfold with U_db; ring. \n\n\n\nProgram Instance GM_is_group : forall n m, Group (GenMatrix n m) :=\n  { Gopp := GMopp }.\nSolve All Obligations with program_simpl; prep_genmatrix_equality; \n  autounfold with U_db; try ring.  \n\nProgram Instance M_is_comm_group : forall n m, Comm_Group (GenMatrix n m).\nSolve All Obligations with program_simpl; prep_genmatrix_equality; \n  autounfold with U_db; ring.\n\n\nProgram Instance M_is_module_space : forall n m, Module_Space (GenMatrix n m) F :=\n  { Vscale := scale }.\nSolve All Obligations with program_simpl; prep_genmatrix_equality; \n  autounfold with U_db; ring. \n\n\n\n\n\n(* lemmas which are useful for simplifying proofs involving matrix operations *)\nLemma kron_simplify : forall (n m o p : nat) (a b : GenMatrix n m) (c d : GenMatrix o p), \n    a = b -> c = d -> (a ⊗ c)%GM = (b ⊗ d)%GM.\nProof. intros; subst; easy. \nQed.\n\nLemma n_kron_simplify : forall (n m : nat) (a b : GenMatrix n m) (n m : nat), \n    a = b -> n = m -> n ⨂ a = m ⨂ b.\nProof. intros; subst; easy. \nQed.\n\nLemma Mtranspose_simplify : forall (n m : nat) (a b : GenMatrix n m), \n    a = b -> a⊤ = b⊤.\nProof. intros; subst; easy. \nQed.\n\n(*\nLemma Madjoint_simplify : forall (n m : nat) (a b : GenMatrix n m), \n    a = b -> a† = b†.\nProof. intros; subst; easy. \nQed.\n*)\n\nLemma Mmult_simplify : forall (n m o : nat) (a b : GenMatrix n m) (c d : GenMatrix m o), \n    a = b -> c = d -> a × c = b × d.\nProof. intros; subst; easy. \nQed.\n\nLemma Mmult_n_simplify : forall (n : nat) (a b : Square n) (c d : nat), \n    a = b -> c = d -> c ⨉ a = d ⨉ b.\nProof. intros; subst; easy. \nQed.\n\nLemma dot_simplify : forall (n : nat) (a b c d: Vector n), \n    a = b -> c = d -> a ∘ c = b ∘ c.\nProof. intros; subst; easy. \nQed.\n\nLemma Mplus_simplify : forall (n m: nat) (a b : GenMatrix n m) (c d : GenMatrix n m), \n    a = b -> c = d -> a .+ c = b .+ d.\nProof. intros; subst; easy. \nQed.\n\nLemma Mscale_simplify : forall (n m: nat) (a b : GenMatrix n m) (c d : F), \n    a = b -> c = d -> c .* a = d .* b.\nProof. intros; subst; easy. \nQed.\n\n\n\n(** * Proofs about well-formedness **)\n\n\n\nLemma WF_GenMatrix_dim_change : forall (m n m' n' : nat) (A : GenMatrix m n),\n  m = m' ->\n  n = n' ->\n  @WF_GenMatrix m n A ->\n  @WF_GenMatrix m' n' A.\nProof. intros. subst. easy. Qed.\n\nLemma WF_Zero : forall m n : nat, WF_GenMatrix (@Zero m n).\nProof. intros m n. unfold WF_GenMatrix. reflexivity. Qed.\n\nLemma WF_I : forall n : nat, WF_GenMatrix (I n). \nProof. \n  unfold WF_GenMatrix, I. intros n x y H. simpl.\n  destruct H; bdestruct (x =? y); bdestruct (x <? n); trivial; lia.\nQed.\n\nLemma WF_I1 : WF_GenMatrix (I 1). Proof. apply WF_I. Qed.\n\nLemma WF_scale : forall {m n : nat} (r : F) (A : GenMatrix m n), \n  WF_GenMatrix A -> WF_GenMatrix (scale r A).\nProof.\n  unfold WF_GenMatrix, scale.\n  intros m n r A H x y H0. simpl.\n  rewrite H; trivial.\n  rewrite Gmult_0_r.\n  reflexivity.\nQed.\n\nLemma WF_plus : forall {m n} (A B : GenMatrix m n), \n  WF_GenMatrix A -> WF_GenMatrix B -> WF_GenMatrix (A .+ B).\nProof.\n  unfold WF_GenMatrix, GMplus.\n  intros m n A B H H0 x y H1. simpl.\n  rewrite H, H0; trivial.\n  rewrite Gplus_0_l.\n  reflexivity.\nQed.\n\nLemma WF_mult : forall {m n o : nat} (A : GenMatrix m n) (B : GenMatrix n o), \n  WF_GenMatrix A -> WF_GenMatrix B -> WF_GenMatrix (A × B).\nProof. \n  unfold WF_GenMatrix, GMmult.\n  intros m n o A B H H0 x y D. \n  apply (@big_sum_0 F R0).\n  destruct D; intros z.\n  + rewrite H; [rewrite Gmult_0_l; easy | auto].\n  + rewrite H0; [rewrite Gmult_0_r; easy | auto].\nQed.\n\nLemma WF_kron : forall {m n o p q r : nat} (A : GenMatrix m n) (B : GenMatrix o p), \n                  q = (m * o)%nat -> r = (n * p)%nat -> \n                  WF_GenMatrix A -> WF_GenMatrix B -> @WF_GenMatrix q r (A ⊗ B).\nProof.\n  unfold WF_GenMatrix, Gkron.\n  intros m n o p q r A B Nn No H H0 x y H1. subst.\n  bdestruct (o =? 0). rewrite H0; [rewrite Gmult_0_r; easy|lia]. \n  bdestruct (p =? 0). rewrite H0; [rewrite Gmult_0_r; easy|lia]. \n  rewrite H.\n  rewrite Gmult_0_l; reflexivity.\n  destruct H1.\n  unfold ge in *.\n  left. \n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\n  right.\n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\nQed. \n\nLemma WF_direct_sum : forall {m n o p q r : nat} (A : GenMatrix m n) (B : GenMatrix o p), \n                  q = (m + o)%nat -> r = (n + p)%nat -> \n                  WF_GenMatrix A -> WF_GenMatrix B -> @WF_GenMatrix q r (A .⊕ B).\nProof. \n  unfold WF_GenMatrix, direct_sum. \n  intros; subst.\n  destruct H3; bdestruct_all; simpl; try apply H1; try apply H2. \n  all : try lia.\nQed.\n\nLemma WF_transpose : forall {m n : nat} (A : GenMatrix m n), \n                     WF_GenMatrix A -> WF_GenMatrix A⊤. \nProof. unfold WF_GenMatrix, transpose. intros m n A H x y H0. apply H. \n       destruct H0; auto. Qed.\n\n(*\nLemma WF_adjoint : forall {m n : nat} (A : GenMatrix m n), \n      WF_GenMatrix A -> WF_GenMatrix A†. \nProof. unfold WF_GenMatrix, adjoint, Cconj. intros m n A H x y H0. simpl. \nrewrite H. lca. lia. Qed.\n*)\n\nLemma WF_outer_product : forall {n} (u v : Vector n),\n    WF_GenMatrix u ->\n    WF_GenMatrix v ->\n    WF_GenMatrix (outer_product u v).\nProof. intros. apply WF_mult; [|apply WF_transpose]; assumption. Qed.\n\nLemma WF_kron_n : forall n {m1 m2} (A : GenMatrix m1 m2),\n   WF_GenMatrix A ->  WF_GenMatrix (kron_n n A).\nProof.\n  intros.\n  induction n; simpl.\n  - apply WF_I.\n  - apply WF_kron; try lia; assumption. \nQed.\n\nLemma WF_big_kron : forall n m (l : list (GenMatrix m n)) (A : GenMatrix m n), \n                        (forall i, WF_GenMatrix (nth i l A)) ->\n                         WF_GenMatrix (⨂ l). \nProof.                         \n  intros n m l A H.\n  induction l.\n  - simpl. apply WF_I.\n  - simpl. apply WF_kron; trivial. apply (H O).\n    apply IHl. intros i. apply (H (S i)).\nQed.\n\n(* alternate version that uses In instead of nth *)\nLemma WF_big_kron' : forall n m (l : list (GenMatrix m n)), \n                        (forall A, In A l -> WF_GenMatrix A) ->\n                         WF_GenMatrix (⨂ l). \nProof.                         \n  intros n m l H. \n  induction l.\n  - simpl. apply WF_I.\n  - simpl. apply WF_kron; trivial. apply H; left; easy. \n    apply IHl. intros A' H0. apply H; right; easy.\nQed.\n\nLemma WF_GMmult_n : forall n {m} (A : Square m),\n   WF_GenMatrix A -> WF_GenMatrix (GMmult_n A n).\nProof.\n  intros.\n  induction n; simpl.\n  - apply WF_I.\n  - apply WF_mult; assumption. \nQed.\n\nLemma WF_direct_sum_n : forall n {m1 m2} (A : GenMatrix m1 m2),\n   WF_GenMatrix A -> WF_GenMatrix (direct_sum_n n A).\nProof.\n  intros.\n  induction n; simpl.\n  - apply WF_Zero.\n  - apply WF_direct_sum; try lia; assumption. \nQed.\n\n\nLemma WF_Msum : forall d1 d2 n (f : nat -> GenMatrix d1 d2), \n  (forall i, (i < n)%nat -> WF_GenMatrix (f i)) -> \n  WF_GenMatrix (big_sum f n).\nProof.\n  intros. \n  apply big_sum_prop_distr; intros. \n  apply WF_plus; auto.\n  apply WF_Zero.\n  auto. \nQed.\n\n\n\nLocal Close Scope nat_scope.\n\n\n(** * Tactics for showing well-formedness *)\n\n\nLocal Open Scope nat.\nLocal Open Scope G.\n\n(* Much less awful *)\nLtac show_wf := \n  unfold WF_GenMatrix;\n  let x := fresh \"x\" in\n  let y := fresh \"y\" in\n  let H := fresh \"H\" in\n  intros x y [H | H];\n  apply le_plus_minus' in H; rewrite H;\n  cbv;\n  destruct_m_eq;\n  try ring.\n\n\n(* Create HintDb wf_db. *)\nHint Resolve WF_Zero WF_I WF_I1 WF_mult WF_plus WF_scale WF_transpose\n     WF_outer_product WF_big_kron WF_kron_n WF_kron \n     WF_GMmult_n (* WF_Msum *) : wf_db.\nHint Extern 2 (_ = _) => unify_pows_two : wf_db.\n\n\n\n(* Utility tactics *)\nLtac has_hyp P :=\n  match goal with\n    | [ _ : P |- _ ] => idtac\n  end.\n\nLtac no_hyp P :=\n  match goal with\n    | [ _ : P |- _ ] => fail 1\n    | _             => idtac\n  end.\n\n(* staggered, because it seems to speed things up (it shouldn't) *)\nLtac auto_wf :=\n  try match goal with\n      |- WF_GenMatrix _ => auto with wf_db;\n                      auto 10 with wf_db;\n                      auto 20 with wf_db;\n                      auto 40 with wf_db;\n                      auto 80 with wf_db;\n                      auto 160 with wf_db\n      end.\n\n(* Puts all well-formedness conditions for M into the context *)\nLtac collate_wf' M :=\n  match M with\n  (* already in context *)\n  | ?A        => has_hyp (WF_GenMatrix A)\n  (* recursive case *)\n  | ?op ?A ?B => collate_wf' A;\n                collate_wf' B;\n                assert (WF_GenMatrix (op A B)) by auto with wf_db\n  (* base case *)\n  | ?A =>        assert (WF_GenMatrix A) by auto with wf_db\n  (* not a matrix *)\n  | _         => idtac\n  end.\n  \n(* Aggregates well-formedness conditions for context *)\nLtac collate_wf :=\n  match goal with\n  | |- ?A = ?B      => collate_wf' A; collate_wf' B\n  | |- ?A == ?B     => collate_wf' A; collate_wf' B\n  | |- WF_GenMatrix ?A => collate_wf' A\n  | |- context[?A]  => collate_wf' A \n  end.\n\nLtac solve_wf := collate_wf; easy. \n\n(** * Basic matrix lemmas *)\n\nLemma WF0_Zero_l :forall (n : nat) (A : GenMatrix 0%nat n), WF_GenMatrix A -> A = Zero.\nProof.\n  intros n A WFA.\n  prep_genmatrix_equality.\n  rewrite WFA.\n  reflexivity.\n  lia.\nQed.\n\nLemma WF0_Zero_r :forall (n : nat) (A : GenMatrix n 0%nat), WF_GenMatrix A -> A = Zero.\nProof.\n  intros n A WFA.\n  prep_genmatrix_equality.\n  rewrite WFA.\n  reflexivity.\n  lia.\nQed.\n\nLemma WF0_Zero :forall (A : GenMatrix 0%nat 0%nat), WF_GenMatrix A -> A = Zero.\nProof.\n  apply WF0_Zero_l.\nQed.\n\nLemma I0_Zero : I 0 = Zero.\nProof.\n  apply WF0_Zero.\n  apply WF_I.\nQed.\n\nLemma trace_plus_dist : forall (n : nat) (A B : Square n), \n    trace (A .+ B) = (trace A + trace B). \nProof. \n  intros.\n  unfold trace, GMplus.\n  rewrite (@big_sum_plus F _ _ R2). \n  easy.  \nQed.\n\nLemma trace_mult_dist : forall n p (A : Square n), trace (p .* A) = (p * trace A). \nProof.\n  intros.\n  unfold trace, scale.\n  rewrite (@big_sum_mult_l F _ _ _ R3). \n  easy.\nQed.\n\nLemma GMplus_0_l : forall (m n : nat) (A : GenMatrix m n), Zero .+ A = A.\nProof. intros. lgma. Qed.\n\nLemma GMplus_0_r : forall (m n : nat) (A : GenMatrix m n), A .+ Zero = A.\nProof. intros. lgma. Qed.\n    \nLemma GMmult_0_l : forall (m n o : nat) (A : GenMatrix n o), @Zero m n × A = Zero.\nProof.\n  intros m n o A. \n  unfold GMmult, Zero.\n  prep_genmatrix_equality.\n  apply (@big_sum_0 F R0).  \n  intros.\n  ring.\nQed.\n\nLemma GMmult_0_r : forall (m n o : nat) (A : GenMatrix m n), A × @Zero n o = Zero.\nProof.\n  intros m n o A. \n  unfold Zero, GMmult.\n  prep_genmatrix_equality.\n  apply (@big_sum_0 F R0). \n  intros.\n  ring. \nQed.\n\n(* using <= because our form big_sum is exclusive. *)\nLemma GMmult_1_l_gen: forall (m n : nat) (A : GenMatrix m n) (x z k : nat), \n  (k <= m)%nat ->\n  ((k <= x)%nat -> big_sum (fun y : nat => I m x y * A y z) k = 0) /\\\n  ((k > x)%nat -> big_sum (fun y : nat => I m x y * A y z) k = A x z).\nProof.  \n  intros m n A x z k B.\n  induction k.\n  * simpl. split. reflexivity. lia.\n  * destruct IHk as [IHl IHr]. lia.  \n    split.\n    + intros leSkx.\n      simpl.\n      unfold I.\n      bdestruct (x =? k); try lia. \n      simpl; dumb_lRa.\n      apply IHl.\n      lia.\n    + intros gtSkx.\n      simpl in *.\n      unfold I in *.\n      bdestruct (x =? k); bdestruct (x <? m); subst; try lia.\n      rewrite IHl by lia; simpl; ring.\n      rewrite IHr by lia; simpl; ring.\nQed.\n\nLemma GMmult_1_l_mat_eq : forall (m n : nat) (A : GenMatrix m n), I m × A == A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold GMmult.\n  edestruct (@GMmult_1_l_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  unfold get.\n  apply Hr.\n  simpl in *.\n  lia.\nQed.  \n\nLemma GMmult_1_l: forall (m n : nat) (A : GenMatrix m n), \n  WF_GenMatrix A -> I m × A = A.\nProof.\n  intros m n A H.\n  apply genmat_equiv_eq; trivial.\n  auto with wf_db.\n  apply GMmult_1_l_mat_eq.\nQed.\n\nLemma GMmult_1_r_gen: forall (m n : nat) (A : GenMatrix m n) (x z k : nat), \n  (k <= n)%nat ->\n  ((k <= z)%nat -> big_sum (fun y : nat => A x y * (I n) y z) k = 0) /\\\n  ((k > z)%nat -> big_sum (fun y : nat => A x y * (I n) y z) k = A x z).\nProof.  \n  intros m n A x z k B.\n  induction k.\n  simpl. split. reflexivity. lia.\n  destruct IHk as [IHl IHr].\n  lia.\n  split.\n  + intros leSkz.\n    simpl in *.\n    unfold I.\n    bdestruct (k =? z); try lia.\n    simpl; dumb_lRa.\n    apply IHl; lia.\n  + intros gtSkz.\n    simpl in *.\n    unfold I in *.\n    bdestruct (k =? z); subst.\n    - bdestruct (z <? n); try lia.\n      rewrite IHl by lia; simpl; ring.\n    - rewrite IHr by lia; simpl; ring.\nQed.\n\nLemma GMmult_1_r_mat_eq : forall (m n : nat) (A : GenMatrix m n), A × I n ≡ A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold GMmult.\n  edestruct (@GMmult_1_r_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  unfold get; simpl.\n  apply Hr.\n  lia.\nQed.  \n\nLemma GMmult_1_r: forall (m n : nat) (A : GenMatrix m n), \n  WF_GenMatrix A -> A × I n = A.\nProof.\n  intros m n A H.\n  apply genmat_equiv_eq; trivial.\n  auto with wf_db.\n  apply GMmult_1_r_mat_eq.\nQed.\n\n(* Cool facts about I∞, not used in the development *) \nLemma GMmult_inf_l : forall(m n : nat) (A : GenMatrix m n),\n  WF_GenMatrix A -> I∞ × A = A.\nProof. \n  intros m n A H.\n  prep_genmatrix_equality.\n  unfold GMmult.\n  edestruct (@GMmult_1_l_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  bdestruct (m <=? x).\n  rewrite H by auto.\n  apply (@big_sum_0_bounded F R0). \n  intros z L. \n  unfold I__inf, I.\n  bdestruct (x =? z). lia. ring. \n  unfold I__inf, I in *.\n  erewrite big_sum_eq.\n  apply Hr.\n  assumption.\n  bdestruct (x <? m); [|lia]. \n  apply functional_extensionality. intros. rewrite andb_true_r. reflexivity.\nQed.\n\nLemma GMmult_inf_r : forall(m n : nat) (A : GenMatrix m n),\n  WF_GenMatrix A -> A × I∞ = A.\nProof. \n  intros m n A H.\n  prep_genmatrix_equality.\n  unfold GMmult.\n  edestruct (@GMmult_1_r_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  bdestruct (n <=? y).\n  rewrite H by auto.\n  apply (@big_sum_0_bounded F R0). \n  intros z L. \n  unfold I__inf, I.\n  bdestruct (z =? y). lia. ring. \n  unfold I__inf, I in *.\n  erewrite big_sum_eq.\n  apply Hr.\n  assumption.\n  apply functional_extensionality. intros z. \n  bdestruct (z =? y); bdestruct (z <? n); simpl; dumb_lRa; lia. \nQed.\n\nLemma kron_0_l : forall (m n o p : nat) (A : GenMatrix o p), \n  @Zero m n ⊗ A = Zero.\nProof.\n  intros m n o p A.\n  prep_genmatrix_equality.\n  unfold Zero, Gkron.\n  rewrite Gmult_0_l.\n  reflexivity.\nQed.\n\nLemma kron_0_r : forall (m n o p : nat) (A : GenMatrix m n), \n   A ⊗ @Zero o p = Zero.\nProof.\n  intros m n o p A.\n  prep_genmatrix_equality.\n  unfold Zero, Gkron.\n  rewrite Gmult_0_r.\n  reflexivity.\nQed.\n\nLemma kron_1_r : forall (m n : nat) (A : GenMatrix m n), A ⊗ I 1 = A.\nProof.\n  intros m n A.\n  prep_genmatrix_equality.\n  unfold I, Gkron.\n  rewrite 2 Nat.div_1_r.\n  rewrite 2 Nat.mod_1_r.\n  simpl.\n  ring. \nQed.\n\n(* This side is more limited *)\nLemma kron_1_l : forall (m n : nat) (A : GenMatrix m n), \n  WF_GenMatrix A -> I 1 ⊗ A = A.\nProof.\n  intros m n A WF.\n  prep_genmatrix_equality.\n  unfold I, Gkron.\n  bdestruct (m =? 0). rewrite 2 WF by lia. ring. \n  bdestruct (n =? 0). rewrite 2 WF by lia. ring. \n  bdestruct (x / m <? 1); rename H1 into Eq1.\n  bdestruct (x / m =? y / n); rename H1 into Eq2; simpl.\n  + assert (x / m = 0)%nat by lia. clear Eq1. rename H1 into Eq1.\n    rewrite Eq1 in Eq2.     \n    symmetry in Eq2.\n    rewrite Nat.div_small_iff in Eq2 by lia.\n    rewrite Nat.div_small_iff in Eq1 by lia.\n    rewrite 2 Nat.mod_small; trivial.\n    ring. \n  + assert (x / m = 0)%nat by lia. clear Eq1.\n    rewrite H1 in Eq2. clear H1.\n    assert (y / n <> 0)%nat by lia. clear Eq2.\n    rewrite Nat.div_small_iff in H1 by lia.\n    rewrite Gmult_0_l.\n    destruct WF with (x := x) (y := y). lia.\n    reflexivity.\n  + rewrite andb_false_r.\n    assert (x / m <> 0)%nat by lia. clear Eq1.\n    rewrite Nat.div_small_iff in H1 by lia.\n    rewrite Gmult_0_l.\n    destruct WF with (x := x) (y := y). lia.\n    reflexivity.\nQed.\n\nTheorem transpose_involutive : forall (m n : nat) (A : GenMatrix m n), (A⊤)⊤ = A.\nProof. reflexivity. Qed.\n\n(*\nTheorem adjoint_involutive : forall (m n : nat) (A : GenMatrix m n), A†† = A.\nProof. intros. lma. Qed.  \n*)\n\nLemma id_transpose_eq : forall n, (I n)⊤ = (I n).\nProof.\n  intros n. unfold transpose, I.\n  prep_genmatrix_equality.\n  bdestruct (y =? x); bdestruct (x =? y); bdestruct (y <? n); bdestruct (x <? n);\n    trivial; lia.\nQed.\n\nLemma zero_transpose_eq : forall m n, (@Zero m n)⊤ = @Zero m n.\nProof. reflexivity. Qed.\n\n\n(*\nLemma id_adjoint_eq : forall n, (I n)† = (I n).\nProof.\n  intros n.\n  unfold adjoint, I.\n  prep_genmatrix_equality.\n  bdestruct (y =? x); bdestruct (x =? y); bdestruct (y <? n); bdestruct (x <? n);\n    try lia; lca.\nQed.\n*)\n(*\nLemma zero_adjoint_eq : forall m n, (@Zero m n)† = @Zero n m.\nProof. unfold adjoint, Zero. rewrite Cconj_0. reflexivity. Qed.\n*)\n\nTheorem GMplus_comm : forall (m n : nat) (A B : GenMatrix m n), A .+ B = B .+ A.\nProof.\n  unfold GMplus. \n  intros m n A B.\n  prep_genmatrix_equality.\n  apply Gplus_comm.\nQed.\n\nTheorem GMplus_assoc : forall (m n : nat) (A B C : GenMatrix m n), A .+ B .+ C = A .+ (B .+ C).\nProof.\n  unfold GMplus. \n  intros m n A B C.\n  prep_genmatrix_equality.\n  rewrite Gplus_assoc.\n  reflexivity.\nQed.\n\n\nTheorem GMmult_assoc : forall {m n o p : nat} (A : GenMatrix m n) (B : GenMatrix n o) \n  (C: GenMatrix o p), A × B × C = A × (B × C).\nProof.\n  intros m n o p A B C.\n  unfold GMmult.\n  prep_genmatrix_equality.\n  replace (fun y0 : nat => Σ (fun y1 : nat => A x y1 * B y1 y0) n * C y0 y) with \n    (fun y0 : nat => Σ (fun y1 : nat => A x y1 * B y1 y0 * C y0 y) n).\n  replace (fun y0 : nat => A x y0 * Σ (fun y1 : nat => B y0 y1 * C y1 y) o) with\n    (fun y0 : nat => Σ (fun y1 : nat => A x y0 * (B y0 y1 * C y1 y)) o).\n  rewrite big_sum_swap_order.\n  do 2 (apply big_sum_eq_bounded; intros; dumb_lRa).  \n  all : apply functional_extensionality; intros.  \n  rewrite big_sum_mult_l; easy.\n  rewrite big_sum_mult_r; easy.\nQed.\n\n\nLemma GMmult_plus_distr_l : forall (m n o : nat) (A : GenMatrix m n) (B C : GenMatrix n o), \n                           A × (B .+ C) = A × B .+ A × C.\nProof. \n  intros m n o A B C.\n  unfold GMplus, GMmult.\n  prep_genmatrix_equality.\n  rewrite <- (@big_sum_plus F _ _ R2).\n  apply big_sum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Gmult_plus_distr_l. \n  reflexivity.\nQed.\n\nLemma GMmult_plus_distr_r : forall (m n o : nat) (A B : GenMatrix m n) (C : GenMatrix n o), \n                           (A .+ B) × C = A × C .+ B × C.\nProof. \n  intros m n o A B C.\n  unfold GMplus, GMmult.\n  prep_genmatrix_equality.\n  rewrite <- (@big_sum_plus F _ _ R2).\n  apply big_sum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Gmult_plus_distr_r. \n  reflexivity.\nQed.\n\nLemma kron_plus_distr_l : forall (m n o p : nat) (A : GenMatrix m n) (B C : GenMatrix o p), \n                           A ⊗ (B .+ C) = A ⊗ B .+ A ⊗ C.\nProof. \n  intros m n o p A B C.\n  unfold GMplus, Gkron.\n  prep_genmatrix_equality.\n  rewrite Gmult_plus_distr_l.\n  easy.\nQed.\n\nLemma kron_plus_distr_r : forall (m n o p : nat) (A B : GenMatrix m n) (C : GenMatrix o p), \n                           (A .+ B) ⊗ C = A ⊗ C .+ B ⊗ C.\nProof. \n  intros m n o p A B C.\n  unfold GMplus, Gkron.\n  prep_genmatrix_equality.\n  rewrite Gmult_plus_distr_r. \n  reflexivity.\nQed.\n\nLemma Mscale_0_l : forall (m n : nat) (A : GenMatrix m n), 0 .* A = Zero.\nProof.\n  intros m n A.\n  prep_genmatrix_equality.\n  unfold Zero, scale.\n  rewrite Gmult_0_l.\n  reflexivity.\nQed.\n\nLemma Mscale_0_r : forall (m n : nat) (c : F), c .* @Zero m n = Zero.\nProof.\n  intros m n c.\n  prep_genmatrix_equality.\n  unfold Zero, scale.\n  rewrite Gmult_0_r.\n  reflexivity.\nQed.\n\nLemma Mscale_1_l : forall (m n : nat) (A : GenMatrix m n), 1 .* A = A.\nProof.\n  intros m n A.\n  prep_genmatrix_equality.\n  unfold scale.\n  rewrite Gmult_1_l.\n  reflexivity.\nQed.\n\nLemma Mscale_1_r : forall (n : nat) (c : F),\n    c .* I n = fun x y => if (x =? y) && (x <? n) then c else 0.\nProof.\n  intros n c.\n  prep_genmatrix_equality.\n  unfold scale, I.\n  destruct ((x =? y) && (x <? n)).\n  rewrite Gmult_1_r; reflexivity.\n  rewrite Gmult_0_r; reflexivity.\nQed.\n\nLemma Mscale_assoc : forall (m n : nat) (x y : F) (A : GenMatrix m n),\n  x .* (y .* A) = (x * y) .* A.\nProof.\n  intros. unfold scale. prep_genmatrix_equality.\n  rewrite Gmult_assoc; reflexivity.\nQed.\n\n(* TODO: make this work when c is not a zero divisor \nLemma Mscale_div : forall {n m} (c : F) (A B : GenMatrix n m),\n  c <> C0 -> c .* A = c .* B -> A = B.\nProof. intros. \n       rewrite <- Mscale_1_l. rewrite <- (Mscale_1_l n m A).\n       rewrite <- (Ginv_l c).\n       rewrite <- Mscale_assoc.\n       rewrite H0. \n       lma.\n       apply H.\nQed.\n*)\n\n\nLemma Mscale_plus_distr_l : forall (m n : nat) (x y : F) (A : GenMatrix m n),\n  (x + y) .* A = x .* A .+ y .* A.\nProof.\n  intros. unfold GMplus, scale. prep_genmatrix_equality. apply Gmult_plus_distr_r.\nQed.\n\nLemma Mscale_plus_distr_r : forall (m n : nat) (x : F) (A B : GenMatrix m n),\n  x .* (A .+ B) = x .* A .+ x .* B.\nProof.\n  intros. unfold GMplus, scale. prep_genmatrix_equality. apply Gmult_plus_distr_l.\nQed.\n\nLemma Mscale_mult_dist_l : forall (m n o : nat) (x : F) (A : GenMatrix m n) (B : GenMatrix n o), \n    ((x .* A) × B) = x .* (A × B).\nProof.\n  intros m n o x A B.\n  unfold scale, GMmult.\n  prep_genmatrix_equality.\n  rewrite (@big_sum_mult_l F _ _ _ R3). \n  apply big_sum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Gmult_assoc.\n  reflexivity.\nQed.\n\nLemma Mscale_mult_dist_r : forall (m n o : nat) (x : F) (A : GenMatrix m n) (B : GenMatrix n o),\n    (A × (x .* B)) = x .* (A × B).\nProof.\n  intros m n o x A B.\n  unfold scale, GMmult.\n  prep_genmatrix_equality.\n  rewrite (@big_sum_mult_l F _ _ _ R3). \n  apply big_sum_eq.\n  apply functional_extensionality. intros z.\n  repeat rewrite Gmult_assoc.\n  rewrite (Gmult_comm _ x).\n  reflexivity.\nQed.\n\nLemma Mscale_kron_dist_l : forall (m n o p : nat) (x : F) (A : GenMatrix m n) (B : GenMatrix o p), \n    ((x .* A) ⊗ B) = x .* (A ⊗ B).\nProof.\n  intros m n o p x A B.\n  unfold scale, Gkron.\n  prep_genmatrix_equality.\n  rewrite Gmult_assoc.\n  reflexivity.\nQed.\n\nLemma Mscale_kron_dist_r : forall (m n o p : nat) (x : F) (A : GenMatrix m n) (B : GenMatrix o p), \n    (A ⊗ (x .* B)) = x .* (A ⊗ B).\nProof.\n  intros m n o p x A B.\n  unfold scale, Gkron.\n  prep_genmatrix_equality.\n  rewrite Gmult_assoc.  \n  rewrite (Gmult_comm (A _ _) x).\n  rewrite Gmult_assoc.  \n  reflexivity.\nQed.\n\nLemma Mscale_trans : forall (m n : nat) (x : F) (A : GenMatrix m n),\n    (x .* A)⊤ = x .* A⊤.\nProof. reflexivity. Qed.\n\n(*\nLemma Mscale_adj : forall (m n : nat) (x : F) (A : GenMatrix m n),\n    (x .* A)† = x^* .* A†.\nProof.\n  intros m n x A.\n  unfold scale, adjoint.\n  prep_genmatrix_equality.\n  rewrite Cconj_mult_distr.          \n  reflexivity.\nQed.\n*)\n\nLemma GMplus_transpose : forall (m n : nat) (A : GenMatrix m n) (B : GenMatrix m n),\n  (A .+ B)⊤ = A⊤ .+ B⊤.\nProof. reflexivity. Qed.\n\nLemma GMmult_transpose : forall (m n o : nat) (A : GenMatrix m n) (B : GenMatrix n o),\n      (A × B)⊤ = B⊤ × A⊤.\nProof.\n  intros m n o A B.\n  unfold GMmult, transpose.\n  prep_genmatrix_equality.\n  apply big_sum_eq.  \n  apply functional_extensionality. intros z.\n  rewrite Gmult_comm.\n  reflexivity.\nQed.\n\nLemma kron_transpose : forall {m n o p : nat} (A : GenMatrix m n) (B : GenMatrix o p ),\n  (A ⊗ B)⊤ = A⊤ ⊗ B⊤.\nProof. reflexivity. Qed.\n\n(*\nLemma GMplus_adjoint : forall (m n : nat) (A : GenMatrix m n) (B : GenMatrix m n),\n  (A .+ B)† = A† .+ B†.\nProof.  \n  intros m n A B.\n  unfold GMplus, adjoint.\n  prep_genmatrix_equality.\n  rewrite Cconj_plus_distr.\n  reflexivity.\nQed.\nLemma GMmult_adjoint : forall {m n o : nat} (A : GenMatrix m n) (B : GenMatrix n o),\n      (A × B)† = B† × A†.\nProof.\n  intros m n o A B.\n  unfold GMmult, adjoint.\n  prep_genmatrix_equality.\n  rewrite (@big_sum_func_distr C C _ C_is_group _ C_is_group). (* not great *) \n  apply big_sum_eq.  \n  apply functional_extensionality. intros z.\n  rewrite Cconj_mult_distr.\n  rewrite Cmult_comm.\n  reflexivity.\n  intros; lca. \nQed.\nLemma kron_adjoint : forall {m n o p : nat} (A : GenMatrix m n) (B : GenMatrix o p),\n  (A ⊗ B)† = A† ⊗ B†.\nProof. \n  intros. unfold adjoint, kron. \n  prep_genmatrix_equality.\n  rewrite Cconj_mult_distr.\n  reflexivity.\nQed.\n*)\n\n\nLemma id_kron : forall (m n : nat),  I m ⊗ I n = I (m * n).\nProof.\n  intros.\n  unfold I, Gkron.\n  prep_genmatrix_equality.\n  bdestruct (x =? y); rename H into Eq; subst.\n  + repeat rewrite Nat.eqb_refl; simpl.\n    destruct n.\n    - simpl.\n      rewrite Nat.mul_0_r.\n      bdestruct (y <? 0); try lia.\n      ring. \n    - bdestruct (y mod S n <? S n). \n      2: specialize (Nat.mod_upper_bound y (S n)); intros; lia. \n      rewrite Gmult_1_r.\n      destruct (y / S n <? m) eqn:L1, (y <? m * S n) eqn:L2; trivial.\n      * apply Nat.ltb_lt in L1. \n        apply Nat.ltb_nlt in L2. \n        contradict L2. \n        clear H.\n        (* Why doesn't this lemma exist??? *)\n        destruct m.\n        lia.\n        apply Nat.div_small_iff. \n        simpl. apply Nat.neq_succ_0. (* `lia` will solve in 8.11+ *)\n        apply Nat.div_small in L1.\n        rewrite Nat.div_div in L1; try lia.\n        rewrite Nat.mul_comm.\n        assumption.\n      * apply Nat.ltb_nlt in L1. \n        apply Nat.ltb_lt in L2. \n        contradict L1. \n        apply Nat.div_lt_upper_bound. lia.\n        rewrite Nat.mul_comm.\n        assumption.\n  + simpl.\n    bdestruct (x / n =? y / n); simpl; dumb_lRa.\n    bdestruct (x mod n =? y mod n); simpl; dumb_lRa.\n    destruct n; simpl; dumb_lRa.   \n    contradict Eq.\n    rewrite (Nat.div_mod x (S n)) by lia.\n    rewrite (Nat.div_mod y (S n)) by lia.\n    rewrite H, H0; reflexivity.\nQed.\n\n\nLocal Open Scope nat_scope.\n\nLemma div_mod : forall (x y z : nat), (x / y) mod z = (x mod (y * z)) / y.\nProof.\n  intros. bdestruct (y =? 0). subst. simpl.\n  bdestruct (z =? 0). subst. easy.\n  apply Nat.mod_0_l. easy.\n  bdestruct (z =? 0). subst. rewrite Nat.mul_0_r. simpl.\n  try rewrite Nat.div_0_l; easy.\n  pattern x at 1. rewrite (Nat.div_mod x (y * z)) by nia.\n  replace (y * z * (x / (y * z))) with ((z * (x / (y * z))) * y) by lia.\n  rewrite Nat.div_add_l with (b := y) by easy.\n  replace (z * (x / (y * z)) + x mod (y * z) / y) with\n      (x mod (y * z) / y + (x / (y * z)) * z) by lia.\n  rewrite Nat.mod_add by easy.\n  apply Nat.mod_small.\n  apply Nat.div_lt_upper_bound. easy. apply Nat.mod_upper_bound. nia.\nQed.\n\nLemma sub_mul_mod :\n  forall x y z,\n    y * z <= x ->\n    (x - y * z) mod z = x mod z.\nProof.\n  intros. bdestruct (z =? 0). subst. simpl. lia.\n  specialize (Nat.sub_add (y * z) x H) as G.\n  rewrite Nat.add_comm in G.\n  remember (x - (y * z)) as r.\n  rewrite <- G. rewrite <- Nat.add_mod_idemp_l by easy. rewrite Nat.mod_mul by easy.\n  easy.\nQed.\n\nLemma mod_product : forall x y z, y <> 0 -> x mod (y * z) mod z = x mod z.\nProof.\n  intros x y z H. bdestruct (z =? 0). subst.\n  simpl. try rewrite Nat.mul_0_r. reflexivity.\n  pattern x at 2. rewrite Nat.mod_eq with (b := y * z) by nia.\n  replace (y * z * (x / (y * z))) with (y * (x / (y * z)) * z) by lia.\n  rewrite sub_mul_mod. easy.\n  replace (y * (x / (y * z)) * z) with (y * z * (x / (y * z))) by lia.\n  apply Nat.mul_div_le. nia.\nQed.\n\nLemma kron_assoc_mat_equiv : forall {m n p q r s : nat}\n  (A : GenMatrix m n) (B : GenMatrix p q) (C : GenMatrix r s),\n  (A ⊗ B ⊗ C) == A ⊗ (B ⊗ C).                                \nProof.\n  intros. intros i j Hi Hj.\n  remember (A ⊗ B ⊗ C) as LHS.\n  unfold Gkron.  \n  rewrite (Nat.mul_comm p r) at 1 2.\n  rewrite (Nat.mul_comm q s) at 1 2.\n  assert (m * p * r <> 0) by lia.\n  assert (n * q * s <> 0) by lia.\n  apply Nat.neq_mul_0 in H as [Hmp Hr].\n  apply Nat.neq_mul_0 in Hmp as [Hm Hp].\n  apply Nat.neq_mul_0 in H0 as [Hnq Hs].\n  apply Nat.neq_mul_0 in Hnq as [Hn Hq].\n  rewrite <- 2 Nat.div_div by assumption.\n  rewrite <- 2 div_mod.\n  rewrite 2 mod_product by assumption.\n  rewrite Gmult_assoc.\n  subst.\n  reflexivity.\nQed.  \n\nLemma kron_assoc : forall {m n p q r s : nat}\n  (A : GenMatrix m n) (B : GenMatrix p q) (C : GenMatrix r s),\n  WF_GenMatrix A -> WF_GenMatrix B -> WF_GenMatrix C ->\n  (A ⊗ B ⊗ C) = A ⊗ (B ⊗ C).                                \nProof.\n  intros.\n  apply genmat_equiv_eq; auto with wf_db.\n  apply WF_kron; auto with wf_db; lia.\n  apply kron_assoc_mat_equiv.\nQed.  \n\nLemma kron_mixed_product : forall {m n o p q r : nat} (A : GenMatrix m n) (B : GenMatrix p q ) \n  (C : GenMatrix n o) (D : GenMatrix q r), (A ⊗ B) × (C ⊗ D) = (A × C) ⊗ (B × D).\nProof.\n  intros m n o p q r A B C D.\n  unfold Gkron, GMmult.\n  prep_genmatrix_equality.\n  destruct q.\n  + simpl.\n    rewrite Nat.mul_0_r.\n    simpl.\n    rewrite Gmult_0_r.\n    reflexivity. \n  + rewrite (@big_sum_product F _ _ _ R3).\n    apply big_sum_eq.\n    apply functional_extensionality.\n    intros; ring. \n    lia.\nQed.\n\n(* Arguments kron_mixed_product [m n o p q r]. *)\n\n(* A more explicit version, for when typechecking fails *)\nLemma kron_mixed_product' : forall (m n n' o p q q' r mp nq or: nat)\n    (A : GenMatrix m n) (B : GenMatrix p q) (C : GenMatrix n' o) (D : GenMatrix q' r),\n    n = n' -> q = q' ->    \n    mp = m * p -> nq = n * q -> or = o * r ->\n  (@GMmult mp nq or (@Gkron m n p q A B) (@Gkron n' o q' r C D)) =\n  (@Gkron m o p r (@GMmult m n o A C) (@GMmult p q r B D)).\nProof. intros. subst. apply kron_mixed_product. Qed.\n\n\nLemma direct_sum_assoc : forall {m n p q r s : nat}\n  (A : GenMatrix m n) (B : GenMatrix p q) (C : GenMatrix r s),\n  (A .⊕ B .⊕ C) = A .⊕ (B .⊕ C).\nProof. intros. \n       unfold direct_sum. \n       prep_genmatrix_equality.\n       bdestruct_all; simpl; auto.\n       repeat (apply f_equal_gen; try lia); easy. \nQed.\n       \nLemma outer_product_eq : forall m (φ ψ : GenMatrix m 1),\n φ = ψ -> outer_product φ φ = outer_product ψ ψ.\nProof. congruence. Qed.\n\nLemma outer_product_kron : forall m n (φ : GenMatrix m 1) (ψ : GenMatrix n 1), \n    outer_product φ φ ⊗ outer_product ψ ψ = outer_product (φ ⊗ ψ) (φ ⊗ ψ).\nProof. \n  intros. unfold outer_product. \n  specialize (kron_transpose φ ψ) as KT. \n  simpl in *. rewrite KT.\n  specialize (kron_mixed_product φ ψ (φ⊤) (ψ⊤)) as KM. \n  simpl in *. rewrite KM.\n  reflexivity.\nQed.\n\n\n\nLemma big_kron_app : forall {n m} (l1 l2 : list (GenMatrix n m)),\n  (forall i, WF_GenMatrix (nth i l1 (@Zero n m))) ->\n  (forall i, WF_GenMatrix (nth i l2 (@Zero n m))) ->\n  ⨂ (l1 ++ l2) = (⨂ l1) ⊗ (⨂ l2).\nProof. induction l1.\n       - intros. simpl. rewrite (kron_1_l _ _ (⨂ l2)); try easy.\n         apply (WF_big_kron _ _ _ (@Zero n m)); easy.\n       - intros. simpl. rewrite IHl1. \n         rewrite kron_assoc.\n         do 2 (rewrite <- Nat.pow_add_r).\n         rewrite app_length.\n         reflexivity.\n         assert (H' := H 0); simpl in H'; easy.\n         all : try apply (WF_big_kron _ _ _ (@Zero n m)); try easy. \n         all : intros. \n         all : assert (H' := H (S i)); simpl in H'; easy.\nQed.\n\nLemma kron_n_assoc :\n  forall n {m1 m2} (A : GenMatrix m1 m2), WF_GenMatrix A -> (S n) ⨂ A = A ⊗ (n ⨂ A).\nProof.\n  intros. induction n.\n  - simpl. \n    rewrite kron_1_r. \n    rewrite kron_1_l; try assumption.\n    reflexivity.\n  - simpl.\n    replace (m1 * (m1 ^ n)) with ((m1 ^ n) * m1) by apply Nat.mul_comm.\n    replace (m2 * (m2 ^ n)) with ((m2 ^ n) * m2) by apply Nat.mul_comm.\n    rewrite <- kron_assoc; auto with wf_db.\n    rewrite <- IHn.\n    reflexivity.\nQed.\n\n(*\nLemma kron_n_adjoint : forall n {m1 m2} (A : GenMatrix m1 m2),\n  WF_GenMatrix A -> (n ⨂ A)† = n ⨂ A†.\nProof.\n  intros. induction n.\n  - simpl. apply id_adjoint_eq.\n  - simpl.\n    replace (m1 * (m1 ^ n)) with ((m1 ^ n) * m1) by apply Nat.mul_comm.\n    replace (m2 * (m2 ^ n)) with ((m2 ^ n) * m2) by apply Nat.mul_comm.\n    rewrite kron_adjoint, IHn.\n    reflexivity.\nQed. *)\n\nLemma kron_n_transpose : forall (m n o : nat) (A : GenMatrix m n),\n  (o ⨂ A)⊤ = o ⨂ (A⊤). \nProof. \n  induction o; intros.\n  - apply id_transpose_eq.\n  - simpl; rewrite <- IHo; rewrite <- kron_transpose; reflexivity. \nQed.\n\n(* TODO: make Gpow *) (*\nLemma Mscale_kron_n_distr_r : forall {m1 m2} n α (A : GenMatrix m1 m2),\n  n ⨂ (α .* A) = (α ^ n)%G .* (n ⨂ A).\nProof.\n  intros.\n  induction n; simpl.\n  rewrite Mscale_1_l. reflexivity.\n  rewrite IHn. \n  rewrite Mscale_kron_dist_r, Mscale_kron_dist_l. \n  rewrite Mscale_assoc.\n  reflexivity.\nQed.\n *)\n\n\nLemma kron_n_mult : forall {m1 m2 m3} n (A : GenMatrix m1 m2) (B : GenMatrix m2 m3),\n  n ⨂ A × n ⨂ B = n ⨂ (A × B).\nProof.\n  intros.\n  induction n; simpl.\n  rewrite GMmult_1_l. reflexivity.\n  apply WF_I.\n  replace (m1 * m1 ^ n) with (m1 ^ n * m1) by apply Nat.mul_comm.\n  replace (m2 * m2 ^ n) with (m2 ^ n * m2) by apply Nat.mul_comm.\n  replace (m3 * m3 ^ n) with (m3 ^ n * m3) by apply Nat.mul_comm.\n  rewrite kron_mixed_product.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma kron_n_I : forall n, n ⨂ I 2 = I (2 ^ n).\nProof.\n  intros.\n  induction n; simpl.\n  reflexivity.\n  rewrite IHn. \n  rewrite id_kron.\n  apply f_equal.\n  lia.\nQed.\n\nLemma GMmult_n_kron_distr_l : forall {m n} i (A : Square m) (B : Square n),\n  i ⨉ (A ⊗ B) = (i ⨉ A) ⊗ (i ⨉ B).\nProof.\n  intros m n i A B.\n  induction i; simpl.\n  rewrite id_kron; reflexivity.\n  rewrite IHi.\n  rewrite kron_mixed_product.\n  reflexivity.\nQed.\n\nLemma GMmult_n_1_l : forall {n} (A : Square n),\n  WF_GenMatrix A ->\n  1 ⨉ A = A.\nProof. intros n A WF. simpl. rewrite GMmult_1_r; auto. Qed.\n\n\nLemma GMmult_n_1_r : forall n i,\n  i ⨉ (I n) = I n.\nProof.\n  intros n i.\n  induction i; simpl.\n  reflexivity.\n  rewrite IHi.  \n  rewrite GMmult_1_l; auto with wf_db.\nQed.\n\n\nLemma GMmult_n_add : forall {n} (A : Square n) (a b : nat),\n  WF_GenMatrix A ->\n  ((a + b) ⨉ A) = (a ⨉ A) × (b ⨉ A).\nProof. intros. \n       induction a; simpl.\n       - rewrite GMmult_1_l; auto with wf_db.\n       - rewrite IHa, GMmult_assoc; easy.\nQed.\n\nLemma GMmult_n_mult_r : forall {n} (A : Square n) (a b : nat),\n  WF_GenMatrix A ->\n  b ⨉ (a ⨉ A) = ((a*b) ⨉ A).\nProof. intros. \n       induction b; simpl.\n       - replace (a * 0) with 0 by lia; easy. \n       - replace (a * S b) with (a + a * b) by lia.\n         rewrite GMmult_n_add, <- IHb; auto.\nQed.\n\n  \n(*\nLemma GMmult_n_eigenvector : forall {n} (A : Square n) (ψ : Vector n) λ i,\n  WF_GenMatrix ψ -> A × ψ = λ .* ψ ->\n  i ⨉ A × ψ = (λ ^ i) .* ψ.\nProof.\n  intros n A ψ λ i WF H.\n  induction i; simpl.\n  rewrite GMmult_1_l; auto.\n  rewrite Mscale_1_l; auto.\n  rewrite GMmult_assoc.\n  rewrite IHi.\n  rewrite Mscale_mult_dist_r.\n  rewrite H.\n  rewrite Mscale_assoc.\n  rewrite Cmult_comm.\n  reflexivity.\nQed.\n*)\n\n\n\n\n\n\n(** * Summation lemmas specific to matrices **)\n\n(* due to dimension problems, we did not prove that GenMatrix m n is a ring with respect to either\n   multiplication or kron. Thus all of these need to be proven *)\nLemma kron_Msum_distr_l : \n  forall {d1 d2 d3 d4} n (f : nat -> GenMatrix d1 d2) (A : GenMatrix d3 d4),\n  A ⊗ big_sum f n = big_sum (fun i => A ⊗ f i) n.\nProof.\n  intros.\n  induction n; simpl. lgma.\n  rewrite kron_plus_distr_l, IHn. reflexivity.\nQed.\n\nLemma kron_Msum_distr_r : \n  forall {d1 d2 d3 d4} n (f : nat -> GenMatrix d1 d2) (A : GenMatrix d3 d4),\n  big_sum f n ⊗ A = big_sum (fun i => f i ⊗ A) n.\nProof.\n  intros.\n  induction n; simpl. lgma.\n  rewrite kron_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma GMmult_Msum_distr_l : forall {d1 d2 m} n (f : nat -> GenMatrix d1 d2) (A : GenMatrix m d1),\n  A × big_sum f n = big_sum (fun i => A × f i) n.\nProof.\n  intros.\n  induction n; simpl. \n  rewrite GMmult_0_r. reflexivity.\n  rewrite GMmult_plus_distr_l, IHn. reflexivity.\nQed.\n\nLemma GMmult_Msum_distr_r : forall {d1 d2 m} n (f : nat -> GenMatrix d1 d2) (A : GenMatrix d2 m),\n  big_sum f n × A = big_sum (fun i => f i × A) n.\nProof.\n  intros.\n  induction n; simpl. \n  rewrite GMmult_0_l. reflexivity.\n  rewrite GMmult_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma Mscale_Msum_distr_r : forall {d1 d2} n (c : F) (f : nat -> GenMatrix d1 d2),\n  big_sum (fun i => c .* (f i)) n = c .* big_sum f n.\nProof.\n  intros d1 d2 n c f.\n  induction n; simpl. lgma.\n  rewrite Mscale_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma Mscale_Msum_distr_l : forall {d1 d2} n (f : nat -> F) (A : GenMatrix d1 d2),\n  big_sum (fun i => (f i) .* A) n = big_sum f n .* A.\nProof.\n  intros d1 d2 n f A.\n  induction n; simpl. lgma.\n  rewrite Mscale_plus_distr_l, IHn. reflexivity.\nQed.\n\n(* TODO: add NtoG in Summation.v *)\n(*\nLemma Msum_constant : forall {d1 d2} n (A : GenMatrix d1 d2),  big_sum (fun _ => A) n = INR n .* A.\nProof.\n  intros. \n  induction n.\n  simpl. lma.\n  simpl big_sum.\n  rewrite IHn.\n  replace (S n) with (n + 1)%nat by lia. \n  rewrite plus_INR; simpl. \n  rewrite RtoC_plus. \n  rewrite Mscale_plus_distr_l.\n  lma.\nQed.\n*)\n\n\n(*\nLemma Msum_adjoint : forall {d1 d2} n (f : nat -> GenMatrix d1 d2),\n  (big_sum f n)† = big_sum (fun i => (f i)†) n.\nProof.\n  intros.\n  induction n; simpl.\n  lma.\n  rewrite GMplus_adjoint, IHn.  \n  reflexivity.\nQed.\n*)\n\n\nLemma Msum_Fsum : forall {d1 d2} n (f : nat -> GenMatrix d1 d2) i j,\n  (big_sum f n) i j = big_sum (fun x => (f x) i j) n.\nProof.\n  intros. \n  induction n; simpl.\n  reflexivity.\n  unfold GMplus.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma Msum_plus : forall n {d1 d2} (f g : nat -> GenMatrix d1 d2), \n    big_sum (fun x => f x .+ g x) n = big_sum f n .+ big_sum g n.\nProof.\n  clear.\n  intros.\n  induction n; simpl.\n  lgma.\n  rewrite IHn. lgma.\nQed.\n\n\n\n\n(** * Defining matrix altering/col operations *)\n\n(*TODO: sometimes its n m and other times its m n, should be consistant *)\nDefinition get_col {n m} (i : nat) (S : GenMatrix n m) : Vector n :=\n  fun x y => (if (y =? 0) then S x i else 0%G).   \n\nDefinition get_row {n m} (i : nat) (S : GenMatrix n m) : GenMatrix 1 m :=\n  fun x y => (if (x =? 0) then S i y else 0%G).  \n\nDefinition reduce_row {n m} (A : GenMatrix (S n) m) (row : nat) : GenMatrix n m :=\n  fun x y => if x <? row\n             then A x y\n             else A (1 + x) y.\n\nDefinition reduce_col {n m} (A : GenMatrix n (S m)) (col : nat) : GenMatrix n m :=\n  fun x y => if y <? col\n             then A x y\n             else A x (1 + y).\n\n(* more specific form for vectors *)\nDefinition reduce_vecn {n} (v : Vector (S n)) : Vector n :=\n  fun x y => if x <? n\n             then v x y\n             else v (1 + x) y.\n\n(* More specific form for squares *)\nDefinition reduce {n} (A : Square (S n)) (row col : nat) : Square n :=\n  fun x y => (if x <? row \n              then (if y <? col \n                    then A x y\n                    else A x (1+y))\n              else (if y <? col \n                    then A (1+x) y\n                    else A (1+x) (1+y))).\n\nDefinition col_append {n m} (T : GenMatrix n m) (v : Vector n) : GenMatrix n (S m) :=\n  fun i j => if (j =? m) then v i 0 else T i j.\n\nDefinition row_append {n m} (T : GenMatrix n m) (v : GenMatrix 1 m) : GenMatrix (S n) m :=\n  fun i j => if (i =? n) then v 0 j else T i j.\n\n(* more general than col_append *)\nDefinition smash {n m1 m2} (T1 : GenMatrix n m1) (T2 : GenMatrix n m2) : GenMatrix n (m1 + m2) :=\n  fun i j => if j <? m1 then T1 i j else T2 i (j - m1).\n\n(* TDOO: these are more general than col/row_append, may want to remove xx_append *)\nDefinition col_wedge {n m} (T : GenMatrix n m) (v : Vector n) (spot : nat) : GenMatrix n (S m) :=\n  fun i j => if j <? spot \n             then T i j\n             else if j =? spot\n                  then v i 0\n                  else T i (j-1).\n\nDefinition row_wedge {n m} (T : GenMatrix n m) (v : GenMatrix 1 m) (spot : nat) : GenMatrix (S n) m :=\n  fun i j => if i <? spot \n             then T i j\n             else if i =? spot\n                  then v 0 j\n                  else T (i-1) j.\n\nDefinition col_swap {n m : nat} (S : GenMatrix n m) (x y : nat) : GenMatrix n m := \n  fun i j => if (j =? x) \n             then S i y\n             else if (j =? y) \n                  then S i x\n                  else S i j.\n\nDefinition row_swap {n m : nat} (S : GenMatrix n m) (x y : nat) : GenMatrix n m := \n  fun i j => if (i =? x) \n             then S y j\n             else if (i =? y) \n                  then S x j\n                  else S i j.\n\nDefinition col_scale {n m : nat} (S : GenMatrix n m) (col : nat) (a : F) : GenMatrix n m := \n  fun i j => if (j =? col) \n             then (a * S i j)%G\n             else S i j.\n\nDefinition row_scale {n m : nat} (S : GenMatrix n m) (row : nat) (a : F) : GenMatrix n m := \n  fun i j => if (i =? row) \n             then (a * S i j)%G\n             else S i j.\n\n(* adding one column to another *)\nDefinition col_add {n m : nat} (S : GenMatrix n m) (col to_add : nat) (a : F) : GenMatrix n m := \n  fun i j => if (j =? col) \n             then (S i j + a * S i to_add)%G\n             else S i j.\n\n(* adding one row to another *)\nDefinition row_add {n m : nat} (S : GenMatrix n m) (row to_add : nat) (a : F) : GenMatrix n m := \n  fun i j => if (i =? row) \n             then (S i j + a * S to_add j)%G\n             else S i j.\n\n(* generalizing col_add *)\nDefinition gen_new_vec (n m : nat) (S : GenMatrix n m) (as' : Vector m) : Vector n :=\n  big_sum (fun i => (as' i 0) .* (get_col i S)) m.\n\nDefinition gen_new_row (n m : nat) (S : GenMatrix n m) (as' : GenMatrix 1 n) : GenMatrix 1 m :=\n  big_sum (fun i => (as' 0 i) .* (get_row i S)) n.\n\n(* adds all columns to single column *)\nDefinition col_add_many {n m} (col : nat) (as' : Vector m) (S : GenMatrix n m) : GenMatrix n m :=\n  fun i j => if (j =? col) \n             then (S i j + (gen_new_vec n m S as') i 0)%G\n             else S i j.\n\nDefinition row_add_many {n m} (row : nat) (as' : GenMatrix 1 n) (S : GenMatrix n m) : GenMatrix n m :=\n  fun i j => if (i =? row) \n             then (S i j + (gen_new_row n m S as') 0 j)%G\n             else S i j.\n\n(* adds single column to each other column *)\nDefinition col_add_each {n m} (col : nat) (as' : GenMatrix 1 m) (S : GenMatrix n m) : GenMatrix n m := \n  S .+ ((get_col col S) × as').\n\nDefinition row_add_each {n m} (row : nat) (as' : Vector n) (S : GenMatrix n m) : GenMatrix n m := \n  S .+ (as' × get_row row S).\n\nDefinition make_col_zero {n m} (col : nat) (S : GenMatrix n m) : GenMatrix n m :=\n  fun i j => if (j =? col) \n             then 0%G\n             else S i j.\n\nDefinition make_row_zero {n m} (row : nat) (S : GenMatrix n m) : GenMatrix n m :=\n  fun i j => if (i =? row) \n             then 0%G\n             else S i j.\n\nDefinition make_WF {n m} (S : GenMatrix n m) : GenMatrix n m :=\n  fun i j => if (i <? n) && (j <? m) then S i j else 0%G.\n\n(** proving lemmas about these new functions *)\n\nLemma WF_get_col : forall {n m} (i : nat) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix (get_col i S). \nProof. unfold WF_GenMatrix, get_col in *.\n       intros.\n       bdestruct (y =? 0); try lia; try easy.\n       apply H.\n       destruct H0. \n       left; easy.\n       lia. \nQed.\n\nLemma WF_get_row : forall {n m} (i : nat) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix (get_row i S). \nProof. unfold WF_GenMatrix, get_row in *.\n       intros.\n       bdestruct (x =? 0); try lia; try easy.\n       apply H.\n       destruct H0. \n       lia. \n       right; easy.\nQed.\n\nLemma WF_reduce_row : forall {n m} (row : nat) (A : GenMatrix (S n) m),\n  row < (S n) -> WF_GenMatrix A -> WF_GenMatrix (reduce_row A row).\nProof. unfold WF_GenMatrix, reduce_row. intros. \n       bdestruct (x <? row). \n       - destruct H1 as [H1 | H1].\n         + assert (nibzo : forall (a b c : nat), a < b -> b < c -> 1 + a < c).\n           { lia. }\n           apply (nibzo x row (S n)) in H2.\n           simpl in H2. lia. apply H.\n         + apply H0; auto.\n       - apply H0. destruct H1. \n         + left. simpl. lia.\n         + right. apply H1. \nQed.\n\nLemma WF_reduce_col : forall {n m} (col : nat) (A : GenMatrix n (S m)),\n  col < (S m) -> WF_GenMatrix A -> WF_GenMatrix (reduce_col A col).\nProof. unfold WF_GenMatrix, reduce_col. intros. \n       bdestruct (y <? col). \n       - destruct H1 as [H1 | H1].   \n         + apply H0; auto. \n         + assert (nibzo : forall (a b c : nat), a < b -> b < c -> 1 + a < c).\n           { lia. }\n           apply (nibzo y col (S m)) in H2.\n           simpl in H2. lia. apply H.\n       - apply H0. destruct H1.\n         + left. apply H1. \n         + right. simpl. lia. \nQed.\n\nLemma rvn_is_rr_n : forall {n : nat} (v : Vector (S n)),\n  reduce_vecn v = reduce_row v n.\nProof. intros.\n       prep_genmatrix_equality.\n       unfold reduce_row, reduce_vecn.\n       easy.\nQed.\n\nLemma WF_reduce_vecn : forall {n} (v : Vector (S n)),\n  n <> 0 -> WF_GenMatrix v -> WF_GenMatrix (reduce_vecn v).\nProof. intros.\n       rewrite rvn_is_rr_n.\n       apply WF_reduce_row; try lia; try easy. \nQed.\n\nLemma reduce_is_redrow_redcol : forall {n} (A : Square (S n)) (row col : nat),\n  reduce A row col = reduce_col (reduce_row A row) col.\nProof. intros. \n       prep_genmatrix_equality.\n       unfold reduce, reduce_col, reduce_row.\n       bdestruct (x <? row); bdestruct (y <? col); try easy.\nQed. \n\nLemma reduce_is_redcol_redrow : forall {n} (A : Square (S n)) (row col : nat),\n  reduce A row col = reduce_row (reduce_col A col) row.\nProof. intros. \n       prep_genmatrix_equality.\n       unfold reduce, reduce_col, reduce_row.\n       bdestruct (x <? row); bdestruct (y <? col); try easy.\nQed. \n\nLemma WF_reduce : forall {n} (A : Square (S n)) (row col : nat),\n  row < S n -> col < S n -> WF_GenMatrix A -> WF_GenMatrix (reduce A row col).\nProof. intros.\n       rewrite reduce_is_redrow_redcol.\n       apply WF_reduce_col; try easy.\n       apply WF_reduce_row; try easy.\nQed.\n\nLemma WF_col_swap : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  x < m -> y < m -> WF_GenMatrix S -> WF_GenMatrix (col_swap S x y).\nProof. unfold WF_GenMatrix, col_swap in *.\n       intros. \n       bdestruct (y0 =? x); bdestruct (y0 =? y); destruct H2; try lia. \n       all : apply H1; try (left; apply H2).\n       auto.\nQed.\n\nLemma WF_row_swap : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  x < n -> y < n -> WF_GenMatrix S -> WF_GenMatrix (row_swap S x y).\nProof. unfold WF_GenMatrix, row_swap in *.\n       intros. \n       bdestruct (x0 =? x); bdestruct (x0 =? y); destruct H2; try lia. \n       all : apply H1; try (right; apply H2).\n       auto.\nQed.\n\nLemma WF_col_scale : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  WF_GenMatrix S -> WF_GenMatrix (col_scale S x a).\nProof. unfold WF_GenMatrix, col_scale in *.\n       intros. \n       apply H in H0.\n       rewrite H0.\n       rewrite Gmult_0_r.\n       bdestruct (y =? x); easy.\nQed.\n\nLemma WF_row_scale : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  WF_GenMatrix S -> WF_GenMatrix (row_scale S x a).\nProof. unfold WF_GenMatrix, row_scale in *.\n       intros. \n       apply H in H0.\n       rewrite H0.\n       rewrite Gmult_0_r.\n       bdestruct (x0 =? x); easy.\nQed.\n\nLemma WF_col_add : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  x < m -> WF_GenMatrix S -> WF_GenMatrix (col_add S x y a).\nProof. unfold WF_GenMatrix, col_add in *.\n       intros.\n       bdestruct (y0 =? x); destruct H1; try lia. \n       do 2 (rewrite H0; auto). ring. \n       all : apply H0; auto.\nQed.\n\nLemma WF_row_add : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  x < n -> WF_GenMatrix S -> WF_GenMatrix (row_add S x y a).\nProof. unfold WF_GenMatrix, row_add in *.\n       intros.\n       bdestruct (x0 =? x); destruct H1; try lia. \n       do 2 (rewrite H0; auto). ring. \n       all : apply H0; auto.\nQed.\n\nLemma WF_gen_new_vec : forall {n m} (S : GenMatrix n m) (as' : Vector m),\n  WF_GenMatrix S -> WF_GenMatrix (gen_new_vec n m S as').\nProof. intros.\n       unfold gen_new_vec.\n       apply WF_Msum; intros. \n       apply WF_scale. \n       apply WF_get_col.\n       easy.\nQed.\n\nLemma WF_gen_new_row : forall {n m} (S : GenMatrix n m) (as' : GenMatrix 1 n),\n  WF_GenMatrix S -> WF_GenMatrix (gen_new_row n m S as').\nProof. intros.\n       unfold gen_new_row.\n       apply WF_Msum; intros. \n       apply WF_scale. \n       apply WF_get_row.\n       easy.\nQed.\n\nLemma WF_col_add_many : forall {n m} (col : nat) (as' : Vector m) (S : GenMatrix n m),\n  col < m -> WF_GenMatrix S -> WF_GenMatrix (col_add_many col as' S).\nProof. unfold WF_GenMatrix, col_add_many.\n       intros. \n       bdestruct (y =? col).\n       assert (H4 := (WF_gen_new_vec S as')).\n       rewrite H4, H0; try easy.\n       ring. destruct H2; lia. \n       rewrite H0; easy.\nQed.\n\nLemma WF_row_add_many : forall {n m} (row : nat) (as' : GenMatrix 1 n) (S : GenMatrix n m),\n  row < n -> WF_GenMatrix S -> WF_GenMatrix (row_add_many row as' S).\nProof. unfold WF_GenMatrix, row_add_many.\n       intros. \n       bdestruct (x =? row).\n       assert (H4 := (WF_gen_new_row S as')).\n       rewrite H4, H0; try easy.\n       ring. destruct H2; lia. \n       rewrite H0; easy.\nQed.\n\nLemma WF_col_append : forall {n m} (T : GenMatrix n m) (v : Vector n),\n  WF_GenMatrix T -> WF_GenMatrix v -> WF_GenMatrix (col_append T v).\nProof. unfold WF_GenMatrix in *.\n       intros; destruct H1 as [H1 | H1]. \n       - unfold col_append.\n         rewrite H, H0; try lia. \n         bdestruct (y =? m); easy. \n       - unfold col_append.\n         bdestruct (y =? m); try lia. \n         apply H; lia. \nQed.\n\nLemma WF_row_append : forall {n m} (T : GenMatrix n m) (v : GenMatrix 1 m),\n  WF_GenMatrix T -> WF_GenMatrix v -> WF_GenMatrix (row_append T v).\nProof. unfold WF_GenMatrix in *.\n       intros; destruct H1 as [H1 | H1]. \n       - unfold row_append.\n         bdestruct (x =? n); try lia. \n         apply H; lia. \n       - unfold row_append.\n         rewrite H, H0; try lia. \n         bdestruct (x =? n); easy. \nQed.\n\nLemma WF_col_wedge : forall {n m} (T : GenMatrix n m) (v : Vector n) (spot : nat),\n  spot <= m -> WF_GenMatrix T -> WF_GenMatrix v -> WF_GenMatrix (col_wedge T v spot).\nProof. unfold WF_GenMatrix in *.\n       intros; destruct H2 as [H2 | H2]. \n       - unfold col_wedge.\n         rewrite H0, H1; try lia. \n         rewrite H0; try lia. \n         bdestruct (y <? spot); bdestruct (y =? spot); easy. \n       - unfold col_wedge.\n         bdestruct (y <? spot); bdestruct (y =? spot); try lia. \n         rewrite H0; try lia. \n         easy.  \nQed.\n\nLemma WF_row_wedge : forall {n m} (T : GenMatrix n m) (v : GenMatrix 1 m) (spot : nat),\n  spot <= n -> WF_GenMatrix T -> WF_GenMatrix v -> WF_GenMatrix (row_wedge T v spot).\nProof. unfold WF_GenMatrix in *.\n       intros; destruct H2 as [H2 | H2]. \n       - unfold row_wedge.\n         bdestruct (x <? spot); bdestruct (x =? spot); try lia. \n         rewrite H0; try lia. \n         easy.  \n       - unfold row_wedge.\n         rewrite H0, H1; try lia. \n         rewrite H0; try lia. \n         bdestruct (x <? spot); bdestruct (x =? spot); easy. \nQed.\n\nLemma WF_smash : forall {n m1 m2} (T1 : GenMatrix n m1) (T2 : GenMatrix n m2),\n  WF_GenMatrix T1 -> WF_GenMatrix T2 -> WF_GenMatrix (smash T1 T2).\nProof. unfold WF_GenMatrix, smash in *.\n       intros. \n       bdestruct (y <? m1).\n       - apply H; lia. \n       - apply H0; lia.\nQed.\n\nLemma WF_col_add_each : forall {n m} (col : nat) (as' : GenMatrix 1 m) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix as' -> WF_GenMatrix (col_add_each col as' S).\nProof. intros.\n       unfold col_add_each.\n       apply WF_plus; try easy;\n       apply WF_mult; try easy;\n       apply WF_get_col; easy.\nQed.\n\nLemma WF_row_add_each : forall {n m} (row : nat) (as' : Vector n) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix as' -> WF_GenMatrix (row_add_each row as' S).\nProof. intros.\n       unfold row_add_each.\n       apply WF_plus; try easy;\n       apply WF_mult; try easy;\n       apply WF_get_row; easy.\nQed.\n\nLemma WF_make_col_zero : forall {n m} (col : nat) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix (make_col_zero col S).\nProof. unfold make_col_zero, WF_GenMatrix.\n       intros. \n       rewrite H; try easy.\n       bdestruct (y =? col); easy.\nQed.\n\nLemma WF_make_row_zero : forall {n m} (row : nat) (S : GenMatrix n m),\n  WF_GenMatrix S -> WF_GenMatrix (make_row_zero row S).\nProof. unfold make_row_zero, WF_GenMatrix.\n       intros. \n       rewrite H; try easy.\n       bdestruct (x =? row); easy.\nQed.\n\nLemma WF_make_WF : forall {n m} (S : GenMatrix n m), WF_GenMatrix (make_WF S).\nProof. intros. \n       unfold WF_GenMatrix, make_WF; intros. \n       destruct H as [H | H].\n       bdestruct (x <? n); try lia; easy. \n       bdestruct (y <? m); bdestruct (x <? n); try lia; easy.\nQed.\n\nHint Resolve WF_get_col WF_get_row WF_reduce_row WF_reduce_col WF_reduce_vecn WF_reduce : wf_db.\nHint Resolve WF_col_swap WF_row_swap WF_col_scale WF_row_scale WF_col_add WF_row_add  : wf_db.\nHint Resolve WF_gen_new_vec WF_gen_new_row WF_col_add_many WF_row_add_many : wf_db.\nHint Resolve WF_col_append WF_row_append WF_row_wedge WF_col_wedge WF_smash : wf_db.\nHint Resolve WF_col_add_each WF_row_add_each WF_make_col_zero WF_make_row_zero WF_make_WF : wf_db.\nHint Extern 1 (Nat.lt _ _) => lia : wf_db.\n\nLemma get_col_reduce_col : forall {n m} (i col : nat) (A : GenMatrix n (S m)),\n  i < col -> get_col i (reduce_col A col) = get_col i A.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold get_col, reduce_col.\n       bdestruct (i <? col); try lia; easy.\nQed.\n\nLemma get_col_conv : forall {n m} (x y : nat) (S : GenMatrix n m),\n  (get_col y S) x 0 = S x y.\nProof. intros. unfold get_col.\n       easy.\nQed.\n\nLemma get_col_mult : forall {n} (i : nat) (A B : Square n),\n  A × (get_col i B) = get_col i (A × B).\nProof. intros. unfold get_col, GMmult.\n       prep_genmatrix_equality.\n       bdestruct (y =? 0).\n       - reflexivity.\n       - apply (@big_sum_0 F R0). intros.\n         apply Gmult_0_r.\nQed.\n\nLemma det_by_get_col : forall {n} (A B : Square n),\n  (forall i, get_col i A = get_col i B) -> A = B.\nProof. intros. prep_genmatrix_equality.\n       rewrite <- get_col_conv.\n       rewrite <- (get_col_conv _ _ B).\n       rewrite H.\n       reflexivity.\nQed.\n\nLemma col_scale_reduce_col_same : forall {n m} (T : GenMatrix n (S m)) (y col : nat) (a : F),\n  y = col -> reduce_col (col_scale T col a) y = reduce_col T y.\nProof. intros.\n       prep_genmatrix_equality. \n       unfold reduce_col, col_scale. \n       bdestruct (y0 <? y); bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\nLemma col_swap_reduce_before : forall {n : nat} (T : Square (S n)) (row col c1 c2 : nat),\n  col < (S c1) -> col < (S c2) ->\n  reduce (col_swap T (S c1) (S c2)) row col = col_swap (reduce T row col) c1 c2.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce, col_swap.\n       bdestruct (c1 <? col); bdestruct (c2 <? col); try lia. \n       simpl. \n       bdestruct (x <? row); bdestruct (y <? col); bdestruct (y =? c1);\n         bdestruct (y =? S c1); bdestruct (y =? c2); bdestruct (y =? S c2); try lia; try easy. \nQed.\n\nLemma col_scale_reduce_before : forall {n : nat} (T : Square (S n)) (x y col : nat) (a : F),\n  y < col -> reduce (col_scale T col a) x y = col_scale (reduce T x y) (col - 1) a.\nProof. intros. \n       prep_genmatrix_equality. \n       destruct col; try lia. \n       rewrite Sn_minus_1. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y); bdestruct (y0 =? S col);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? S col); try lia; easy. \nQed.\n\nLemma col_scale_reduce_same : forall {n : nat} (T : Square (S n)) (x y col : nat) (a : F),\n  y = col -> reduce (col_scale T col a) x y = reduce T x y.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\nLemma col_scale_reduce_after : forall {n : nat} (T : Square (S n)) (x y col : nat) (a : F),\n  y > col -> reduce (col_scale T col a) x y = col_scale (reduce T x y) col a.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\nLemma mcz_reduce_col_same : forall {n m} (T : GenMatrix n (S m)) (col : nat),\n  reduce_col (make_col_zero col T) col = reduce_col T col.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce_col, make_col_zero. \n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; easy. \nQed.\n\nLemma mrz_reduce_row_same : forall {n m} (T : GenMatrix (S n) m) (row : nat),\n  reduce_row (make_row_zero row T) row = reduce_row T row.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce_row, make_row_zero. \n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; easy. \nQed.\n\nLemma col_add_many_reduce_col_same : forall {n m} (T : GenMatrix n (S m)) (v : Vector (S m))\n                                            (col : nat),\n  reduce_col (col_add_many col v T) col = reduce_col T col.\nProof. intros. \n       unfold reduce_col, col_add_many.\n       prep_genmatrix_equality. \n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; easy. \nQed.\n\nLemma row_add_many_reduce_row_same : forall {n m} (T : GenMatrix (S n) m) (v : GenMatrix 1 (S n))\n                                            (row : nat),\n  reduce_row (row_add_many row v T) row = reduce_row T row.\nProof. intros. \n       unfold reduce_row, row_add_many.\n       prep_genmatrix_equality. \n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; easy. \nQed.\n\nLemma col_wedge_reduce_col_same : forall {n m} (T : GenMatrix n m) (v : Vector m)\n                                         (col : nat),\n  reduce_col (col_wedge T v col) col = T.\nProof. intros.\n       prep_genmatrix_equality.\n       unfold reduce_col, col_wedge.\n       assert (p : (1 + y - 1) = y). lia.\n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; try easy. \n       all : rewrite p; easy.\nQed.\n\nLemma row_wedge_reduce_row_same : forall {n m} (T : GenMatrix n m) (v : GenMatrix 1 n)\n                                         (row : nat),\n  reduce_row (row_wedge T v row) row = T.\nProof. intros.\n       prep_genmatrix_equality.\n       unfold reduce_row, row_wedge.\n       assert (p : (1 + x - 1) = x). lia.\n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; try easy. \n       all : rewrite p; easy.\nQed.\n\nLemma col_add_many_reduce_row : forall {n m} (T : GenMatrix (S n) m) (v : Vector m) (col row : nat),\n  col_add_many col v (reduce_row T row) = reduce_row (col_add_many col v T) row.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_add_many, reduce_row, gen_new_vec, scale, get_col. \n       bdestruct (y =? col); try lia; try easy. \n       bdestruct (x <? row); try lia. \n       apply f_equal_gen; auto.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       bdestruct (x <? row); try lia; easy.\n       apply f_equal_gen; auto.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       bdestruct (x <? row); try lia; easy.\nQed.\n\nLemma col_swap_same : forall {n m : nat} (S : GenMatrix n m) (x : nat),\n  col_swap S x x = S.\nProof. intros. \n       unfold col_swap. \n       prep_genmatrix_equality. \n       bdestruct (y =? x); try easy.\n       rewrite H; easy.\nQed. \n\nLemma row_swap_same : forall {n m : nat} (S : GenMatrix n m) (x : nat),\n  row_swap S x x = S.\nProof. intros. \n       unfold row_swap. \n       prep_genmatrix_equality. \n       bdestruct (x0 =? x); try easy.\n       rewrite H; easy.\nQed. \n\nLemma col_swap_diff_order : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  col_swap S x y = col_swap S y x.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_swap.\n       bdestruct (y0 =? x); bdestruct (y0 =? y); try easy.\n       rewrite <- H, <- H0; easy.\nQed.\n\nLemma row_swap_diff_order : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  row_swap S x y = row_swap S y x.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_swap.\n       bdestruct (x0 =? x); bdestruct (x0 =? y); try easy.\n       rewrite <- H, <- H0; easy.\nQed.\n\nLemma col_swap_inv : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  S = col_swap (col_swap S x y) x y.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_swap.\n       bdestruct (y0 =? x); bdestruct (y0 =? y); \n         bdestruct (y =? x); bdestruct (x =? x); bdestruct (y =? y); \n         try easy. \n       all : (try rewrite H; try rewrite H0; try rewrite H1; easy).\nQed.\n\nLemma row_swap_inv : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  S = row_swap (row_swap S x y) x y.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_swap.\n       bdestruct (x0 =? x); bdestruct (x0 =? y); \n         bdestruct (y =? x); bdestruct (x =? x); bdestruct (y =? y); \n         try easy. \n       all : (try rewrite H; try rewrite H0; try rewrite H1; easy).\nQed.\n\nLemma col_swap_get_col : forall {n m : nat} (S : GenMatrix n m) (x y : nat),\n  get_col y S = get_col x (col_swap S x y).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold get_col, col_swap. \n       bdestruct (x =? x); bdestruct (x =? y); try lia; try easy.\nQed.\n\nLemma col_swap_three : forall {n m} (T : GenMatrix n m) (x y z : nat),\n  x <> z -> y <> z -> col_swap T x z = col_swap (col_swap (col_swap T x y) y z) x y.\nProof. intros.\n       bdestruct (x =? y).\n       rewrite H1, col_swap_same, col_swap_same.\n       easy. \n       prep_genmatrix_equality. \n       unfold col_swap.\n       bdestruct (y =? y); bdestruct (y =? x); bdestruct (y =? z); try lia. \n       bdestruct (x =? y); bdestruct (x =? x); bdestruct (x =? z); try lia. \n       bdestruct (z =? y); bdestruct (z =? x); try lia. \n       bdestruct (y0 =? y); bdestruct (y0 =? x); bdestruct (y0 =? z); \n         try lia; try easy.\n       rewrite H10.\n       easy.\nQed.\n\nLemma reduce_row_reduce_col : forall {n m} (A : GenMatrix (S n) (S m)) (i j : nat),\n  reduce_col (reduce_row A i) j = reduce_row (reduce_col A j) i.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce_col, reduce_row.\n       bdestruct (y <? j); bdestruct (x <? i); try lia; try easy. \nQed.\nLemma reduce_col_swap_01 : forall {n} (A : Square (S (S n))),\n  reduce_col (reduce_col (col_swap A 0 1) 0) 0 = reduce_col (reduce_col A 0) 0.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce_col, col_swap.\n       bdestruct (y <? 0); bdestruct (1 + y <? 0); try lia. \n       bdestruct (1 + (1 + y) =? 0); bdestruct (1 + (1 + y) =? 1); try lia. \n       easy. \nQed.\n\nLemma reduce_reduce_0 : forall {n} (A : Square (S (S n))) (x y : nat),\n  x <= y ->\n  (reduce (reduce A x 0) y 0) = (reduce (reduce A (S y) 0) x 0).\nProof. intros.\n       prep_genmatrix_equality.\n       unfold reduce. \n       bdestruct (y0 <? 0); bdestruct (1 + y0 <? 0); try lia. \n       bdestruct (x0 <? y); bdestruct (x0 <? S y); bdestruct (x0 <? x); \n         bdestruct (1 + x0 <? S y); bdestruct (1 + x0 <? x); \n         try lia; try easy.\nQed.     \n\nLemma col_add_split : forall {n} (A : Square (S n)) (i : nat) (c : F),\n  col_add A 0 i c = col_wedge (reduce_col A 0) (get_col 0 A .+ c.* get_col i A) 0.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_add, col_wedge, reduce_col, get_col, GMplus, scale.\n       bdestruct (y =? 0); try lia; simpl. \n       rewrite H; easy.\n       replace (S (y - 1)) with y by lia. \n       easy.\nQed.\n\nLemma col_swap_col_add_Si : forall {n} (A : Square n) (i j : nat) (c : F),\n  i <> 0 -> i <> j -> col_swap (col_add (col_swap A j 0) 0 i c) j 0 = col_add A j i c.\nProof. intros. \n       bdestruct (j =? 0).\n       - rewrite H1.\n         do 2 rewrite col_swap_same; easy.\n       - prep_genmatrix_equality. \n         unfold col_swap, col_add.\n         bdestruct (y =? j); bdestruct (j =? j); try lia; simpl. \n         destruct j; try lia. \n         bdestruct (i =? S j); bdestruct (i =? 0); try lia.  \n         rewrite H2; easy.\n         bdestruct (y =? 0); bdestruct (j =? 0); try easy. \n         rewrite H4; easy. \nQed.\n\nLemma col_swap_col_add_0 : forall {n} (A : Square n) (j : nat) (c : F),\n  j <> 0 -> col_swap (col_add (col_swap A j 0) 0 j c) j 0 = col_add A j 0 c.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_swap, col_add.\n       bdestruct (y =? j); bdestruct (j =? j); bdestruct (0 =? j); try lia; simpl. \n       rewrite H0; easy.\n       bdestruct (y =? 0); bdestruct (j =? 0); try easy. \n       rewrite H3; easy.\nQed.\n\nLemma col_swap_end_reduce_col_hit : forall {n m : nat} (T : GenMatrix n (S (S m))) (i : nat),\n  i <= m -> col_swap (reduce_col T i) m i = reduce_col (col_swap T (S m) (S i)) i.\nProof. intros.\n       prep_genmatrix_equality. \n       unfold reduce_col, col_swap. \n       bdestruct (i <? i); bdestruct (m <? i); bdestruct (y =? m); bdestruct (y =? i); \n         bdestruct (y <? i); bdestruct (1 + y =? S m); try lia; try easy. \n       bdestruct (1 + y =? S i); try lia; easy.\n       bdestruct (y =? S m); bdestruct (y =? S i); try lia; easy. \n       bdestruct (1 + y =? S i); try lia; easy.\nQed.\n\nLemma col_swap_reduce_row : forall {n m : nat} (S : GenMatrix (S n) m) (x y row : nat),\n  col_swap (reduce_row S row) x y = reduce_row (col_swap S x y) row.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_swap, reduce_row. \n       bdestruct (y0 =? x); bdestruct (x0 <? row); bdestruct (y0 =? y); try lia; easy. \nQed.\n\n\nLemma col_add_double : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  col_add S x x a = col_scale S x (1 + a)%G.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_add, col_scale. \n       bdestruct (y =? x).\n       - rewrite H; ring. \n       - easy.\nQed.\n\nLemma row_add_double : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  row_add S x x a = row_scale S x (1 + a)%G.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add, row_scale. \n       bdestruct (x0 =? x).\n       - rewrite H; ring. \n       - easy.\nQed.\n\nLemma col_add_swap : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  col_swap (col_add S x y a) x y = col_add (col_swap S x y) y x a. \nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_swap, col_add.\n       bdestruct (y0 =? x); bdestruct (y =? x);\n         bdestruct (y0 =? y); bdestruct (x =? x); try lia; easy. \nQed.\n       \nLemma row_add_swap : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  row_swap (row_add S x y a) x y = row_add (row_swap S x y) y x a. \nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_swap, row_add.\n       bdestruct_all; easy.\nQed.\n\nLemma col_add_inv : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  x <> y -> S = col_add (col_add S x y a) x y (-a).\nProof. intros. \n       prep_genmatrix_equality.\n       unfold col_add.\n       bdestruct (y0 =? x); bdestruct (y =? x); try lia. \n       ring. easy. \nQed.\n\nLemma row_add_inv : forall {n m : nat} (S : GenMatrix n m) (x y : nat) (a : F),\n  x <> y -> S = row_add (row_add S x y a) x y (-a).\nProof. intros. \n       prep_genmatrix_equality.\n       unfold row_add.\n       bdestruct (x0 =? x); bdestruct (y =? x); try lia. \n       ring. easy. \nQed.\n\nLemma genmat_equiv_make_WF : forall {n m} (T : GenMatrix n m),\n  T == make_WF T.\nProof. unfold make_WF, genmat_equiv; intros. \n       bdestruct (i <? n); bdestruct (j <? m); try lia; easy.\nQed.\n\nLemma eq_make_WF : forall {n m} (T : GenMatrix n m),\n  WF_GenMatrix T -> T = make_WF T.\nProof. intros. \n       apply genmat_equiv_eq; auto with wf_db.\n       apply genmat_equiv_make_WF.\nQed.\n\nLemma col_swap_make_WF : forall {n m} (T : GenMatrix n m) (x y : nat),\n  x < m -> y < m -> col_swap (make_WF T) x y = make_WF (col_swap T x y).\nProof. intros.\n       unfold make_WF, col_swap. \n       prep_genmatrix_equality.\n       bdestruct_all; try easy. \nQed.\n\nLemma col_scale_make_WF : forall {n m} (T : GenMatrix n m) (x : nat) (c : F),\n  col_scale (make_WF T) x c = make_WF (col_scale T x c).\nProof. intros.\n       unfold make_WF, col_scale. \n       prep_genmatrix_equality.\n       bdestruct_all; try easy; simpl; ring. \nQed.\n\nLemma col_add_make_WF : forall {n m} (T : GenMatrix n m) (x y : nat) (c : F),\n  x < m -> y < m -> col_add (make_WF T) x y c = make_WF (col_add T x y c).\nProof. intros.\n       unfold make_WF, col_add. \n       prep_genmatrix_equality.\n       bdestruct_all; try easy; simpl; ring. \nQed.\n\nLemma GMmult_make_WF : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o),\n  make_WF A × make_WF B = make_WF (A × B).\nProof. intros. \n       apply genmat_equiv_eq; auto with wf_db.\n       unfold genmat_equiv; intros. \n       unfold make_WF, GMmult.\n       bdestruct (i <? n); bdestruct (j <? o); try lia; simpl. \n       apply big_sum_eq_bounded; intros. \n       bdestruct (x <? m); try lia; easy. \nQed.\n\nLemma gen_new_vec_0 : forall {n m} (T : GenMatrix n m) (as' : Vector m),\n  as' == Zero -> gen_new_vec n m T as' = Zero.\nProof. intros.\n       unfold genmat_equiv, gen_new_vec in *.\n       prep_genmatrix_equality.\n       rewrite Msum_Fsum.\n       unfold Zero in *.\n       apply (@big_sum_0_bounded F R0); intros. \n       rewrite H; try lia. \n       rewrite Mscale_0_l.\n       easy.\nQed.\n\nLemma gen_new_row_0 : forall {n m} (T : GenMatrix n m) (as' : GenMatrix 1 n),\n  as' == Zero -> gen_new_row n m T as' = Zero.\nProof. intros.\n       unfold genmat_equiv, gen_new_row in *.\n       prep_genmatrix_equality.\n       rewrite Msum_Fsum.\n       unfold Zero in *.\n       apply (@big_sum_0_bounded F R0); intros. \n       rewrite H; try lia. \n       rewrite Mscale_0_l.\n       easy.\nQed.\n\nLemma col_add_many_0 : forall {n m} (col : nat) (T : GenMatrix n m) (as' : Vector m),\n  as' == Zero -> T = col_add_many col as' T.\nProof. intros. \n       unfold col_add_many in *.\n       prep_genmatrix_equality.\n       bdestruct (y =? col); try easy.\n       rewrite gen_new_vec_0; try easy.\n       unfold Zero; ring. \nQed.\n\nLemma row_add_many_0 : forall {n m} (row : nat) (T : GenMatrix n m) (as' : GenMatrix 1 n),\n  as' == Zero -> T = row_add_many row as' T.\nProof. intros. \n       unfold row_add_many in *.\n       prep_genmatrix_equality. \n       bdestruct (x =? row); try easy.\n       rewrite gen_new_row_0; try easy.\n       unfold Zero; ring. \nQed.\n\nLemma gen_new_vec_mat_equiv : forall {n m} (T : GenMatrix n m) (as' bs : Vector m),\n  as' == bs -> gen_new_vec n m T as' = gen_new_vec n m T bs.\nProof. unfold genmat_equiv, gen_new_vec; intros.\n       prep_genmatrix_equality.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       rewrite H; try lia. \n       easy.\nQed.\n\nLemma gen_new_row_mat_equiv : forall {n m} (T : GenMatrix n m) (as' bs : GenMatrix 1 n),\n  as' == bs -> gen_new_row n m T as' = gen_new_row n m T bs.\nProof. unfold genmat_equiv, gen_new_row; intros.\n       prep_genmatrix_equality.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       rewrite H; try lia. \n       easy.\nQed.\n\nLemma col_add_many_mat_equiv : forall {n m} (col : nat) (T : GenMatrix n m) (as' bs : Vector m),\n  as' == bs -> col_add_many col as' T = col_add_many col bs T.\nProof. intros. \n       unfold col_add_many.\n       rewrite (gen_new_vec_mat_equiv _ as' bs); easy.\nQed.\n\nLemma row_add_many_mat_equiv : forall {n m} (row : nat) (T : GenMatrix n m) (as' bs : GenMatrix 1 n),\n  as' == bs -> row_add_many row as' T = row_add_many row bs T.\nProof. intros. \n       unfold row_add_many.\n       rewrite (gen_new_row_mat_equiv _ as' bs); easy.\nQed.\n\nLemma col_add_each_0 : forall {n m} (col : nat) (T : GenMatrix n m) (v : GenMatrix 1 m),\n  v = Zero -> T = col_add_each col v T.\nProof. intros. \n       rewrite H.\n       unfold col_add_each.\n       rewrite GMmult_0_r.\n       rewrite GMplus_0_r.\n       easy. \nQed.\n\nLemma row_add_each_0 : forall {n m} (row : nat) (T : GenMatrix n m) (v : Vector n),\n  v = Zero -> T = row_add_each row v T.\nProof. intros. \n       rewrite H.\n       unfold row_add_each.\n       rewrite GMmult_0_l.\n       rewrite GMplus_0_r.\n       easy. \nQed.\n\n(* allows for induction on col_add_many *)\nLemma col_add_many_col_add : forall {n m} (col e : nat) (T : GenMatrix n m) (as' : Vector m),\n  col <> e -> e < m -> as' col 0 = 0%G ->\n  col_add_many col as' T = \n  col_add (col_add_many col (make_row_zero e as') T) col e (as' e 0).\nProof. intros. \n       unfold col_add_many, col_add, gen_new_vec.\n       prep_genmatrix_equality.\n       bdestruct (y =? col); try easy.\n       bdestruct (e =? col); try lia.\n       rewrite <- Gplus_assoc.\n       apply f_equal_gen; try easy.\n       assert (H' : m = e + (m - e)). lia. \n       rewrite H'.\n       do 2 rewrite Msum_Fsum. \n       rewrite big_sum_sum.\n       rewrite big_sum_sum.\n       rewrite <- Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded; intros.\n       unfold make_row_zero.\n       bdestruct (x0 =? e); try lia; easy. \n       destruct (m - e); try lia. \n       do 2 rewrite <- big_sum_extend_l.\n       unfold make_row_zero.\n       bdestruct (e + 0 =? e); try lia. \n       unfold scale.\n       rewrite Gmult_0_l, Gplus_0_l.\n       rewrite Gplus_comm.\n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded; intros.\n       bdestruct (e + S x0 =? e); try lia; easy.\n       unfold get_col. simpl. \n       rewrite Nat.add_0_r; easy.\nQed.\n\n(* shows that we can eliminate a column in a matrix using col_add_many *)\nLemma col_add_many_cancel : forall {n m} (T : GenMatrix n (S m)) (as' : Vector (S m)) (col : nat),\n  col < (S m) -> as' col O = 0%G ->\n  (reduce_col T col) × (reduce_row as' col) = -1%G .* (get_col col T) -> \n  (forall i : nat, (col_add_many col as' T) i col = 0%G).\nProof. intros. \n       unfold col_add_many, gen_new_vec.\n       bdestruct (col =? col); try lia. \n       rewrite Msum_Fsum. \n       assert (H' : (big_sum (fun x : nat => (as' x O .* get_col x T) i 0) (S m) = \n                     (@GMmult n m 1 (reduce_col T col) (reduce_row as' col)) i 0)%G).\n       { unfold GMmult.\n         replace (S m) with (col + (S (m - col))) by lia; rewrite big_sum_sum. \n         rewrite (le_plus_minus' col m); try lia; rewrite big_sum_sum. \n         apply f_equal_gen; try apply f_equal; auto. \n         apply big_sum_eq_bounded; intros. \n         unfold get_col, scale, reduce_col, reduce_row. \n         bdestruct (x <? col); simpl; try lia; ring.\n         rewrite <- le_plus_minus', <- big_sum_extend_l, Nat.add_0_r, H0; try lia. \n         unfold scale; rewrite Gmult_0_l, Gplus_0_l.\n         apply big_sum_eq_bounded; intros. \n         unfold get_col, scale, reduce_col, reduce_row. \n         bdestruct (col + x <? col); simpl; try lia. \n         assert (p3 : (col + S x) = (S (col + x))). lia.\n         rewrite p3. ring. }\n       rewrite H', H1.\n       unfold scale, get_col. \n       bdestruct (0 =? 0); try lia. \n       simpl; ring.\nQed.\n\nLemma col_add_many_inv : forall {n m} (S : GenMatrix n m) (col : nat) (as' : Vector m),\n  as' col O = 0%G -> S = col_add_many col (-1%G .* as') (col_add_many col as' S).\nProof. intros. \n       unfold col_add_many, gen_new_vec.\n       prep_genmatrix_equality. \n       bdestruct (y =? col); try easy.\n       rewrite <- (Gplus_0_r (S x y)).\n       rewrite <- Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto; try ring.\n       do 2 rewrite Msum_Fsum.\n       rewrite <- (@big_sum_plus F _ _ R2).\n       rewrite (@big_sum_0_bounded F R0); try ring.\n       intros. \n       unfold get_col, scale.\n       bdestruct (0 =? 0); bdestruct (x0 =? col); try lia; try ring.\n       rewrite Msum_Fsum.\n       bdestruct (0 =? 0); try lia. \n       rewrite H3, H. ring.\nQed.\n\n(* like above, allows for induction on col_add_each *)\nLemma col_add_each_col_add : forall {n m} (col e : nat) (S : GenMatrix n m) (as' : GenMatrix 1 m),\n  col <> e -> (forall x, as' x col = 0%G) ->\n              col_add_each col as' S = \n              col_add (col_add_each col (make_col_zero e as') S) e col (as' 0 e).\nProof. intros.\n       prep_genmatrix_equality.\n       unfold col_add_each, col_add, make_col_zero, GMmult, GMplus, get_col, big_sum.\n       bdestruct (y =? col); bdestruct (y =? e); bdestruct (col =? e); \n         bdestruct (e =? e); bdestruct (0 =? 0); try lia; try ring. \n       rewrite H0. \n       rewrite H2. ring.\nQed.\n\nLemma row_add_each_row_add : forall {n m} (row e : nat) (S : GenMatrix n m) (as' : Vector n),\n  row <> e -> (forall y, as' row y = 0%G) ->\n              row_add_each row as' S = \n              row_add (row_add_each row (make_row_zero e as') S) e row (as' e 0).\nProof. intros.\n       prep_genmatrix_equality.\n       unfold row_add_each, row_add, make_row_zero, GMmult, GMplus, get_row, big_sum.\n       bdestruct (x =? row); bdestruct (x =? e); bdestruct (row =? e); \n         bdestruct (e =? e); bdestruct (0 =? 0); try lia; try ring. \n       rewrite H0. \n       rewrite H2. ring.\nQed.\n\n(* must use make_col_zero here instead of just as' col 0 = 0%G, since def requires stronger hyp *)\nLemma col_add_each_inv : forall {n m} (col : nat) (as' : GenMatrix 1 m) (T : GenMatrix n m),\n  T = col_add_each col (make_col_zero col (-1%G .* as')) \n                   (col_add_each col (make_col_zero col as') T).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_add_each, make_col_zero, GMmult, GMplus, get_col, scale.\n       simpl. bdestruct (y =? col); bdestruct (col =? col); try lia; try ring. \nQed.\n\nLemma row_add_each_inv : forall {n m} (row : nat) (as' : Vector n) (T : GenMatrix n m),\n  T = row_add_each row (make_row_zero row (-1%G .* as')) \n                   (row_add_each row (make_row_zero row as') T).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add_each, make_row_zero, GMmult, GMplus, get_row, scale.\n       simpl. bdestruct (x =? row); bdestruct (row =? row); try lia; try ring. \nQed.\n\n\n(* we can show that we get from col_XXX to row_XXX via transposing *)\n(* helpful, since we can bootstrap many lemmas on cols for rows *)\nLemma get_col_transpose : forall {n m} (A : GenMatrix n m) (i : nat),\n  (get_col i A)⊤ = get_row i (A⊤).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold get_col, get_row, transpose. \n       easy.\nQed.\n\nLemma get_row_transpose : forall {n m} (A : GenMatrix n m) (i : nat),\n  (get_row i A)⊤ = get_col i (A⊤).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold get_col, get_row, transpose. \n       easy.\nQed.\n\nLemma col_swap_transpose : forall {n m} (A : GenMatrix n m) (x y : nat),\n  (col_swap A x y)⊤ = row_swap (A⊤) x y.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_swap, col_swap, transpose. \n       easy. \nQed.\n\nLemma row_swap_transpose : forall {n m} (A : GenMatrix n m) (x y : nat),\n  (row_swap A x y)⊤ = col_swap (A⊤) x y.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_swap, col_swap, transpose. \n       easy. \nQed.\n\nLemma col_scale_transpose : forall {n m} (A : GenMatrix n m) (x : nat) (a : F),\n  (col_scale A x a)⊤ = row_scale (A⊤) x a.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_scale, col_scale, transpose. \n       easy. \nQed.\n\nLemma row_scale_transpose : forall {n m} (A : GenMatrix n m) (x : nat) (a : F),\n  (row_scale A x a)⊤ = col_scale (A⊤) x a.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_scale, col_scale, transpose. \n       easy. \nQed.\n\nLemma col_add_transpose : forall {n m} (A : GenMatrix n m) (col to_add : nat) (a : F),\n  (col_add A col to_add a)⊤ = row_add (A⊤) col to_add a.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add, col_add, transpose. \n       easy. \nQed.\n\nLemma row_add_transpose : forall {n m} (A : GenMatrix n m) (row to_add : nat) (a : F),\n  (row_add A row to_add a)⊤ = col_add (A⊤) row to_add a.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add, col_add, transpose. \n       easy. \nQed.\n\nLemma col_add_many_transpose : forall {n m} (A : GenMatrix n m) (col : nat) (as' : Vector m),\n  (col_add_many col as' A)⊤ = row_add_many col (as'⊤) (A⊤).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add_many, col_add_many, transpose. \n       bdestruct (x =? col); try easy.\n       apply f_equal_gen; try apply f_equal; auto.  \n       unfold gen_new_vec, gen_new_row, get_col, get_row, scale.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       easy. \nQed.\n\nLemma row_add_many_transpose : forall {n m} (A : GenMatrix n m) (row : nat) (as' : GenMatrix 1 n),\n  (row_add_many row as' A)⊤ = col_add_many row (as'⊤) (A⊤).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_add_many, col_add_many, transpose. \n       bdestruct (y =? row); try easy. \n       apply f_equal_gen; try apply f_equal; auto. \n       unfold gen_new_vec, gen_new_row, get_col, get_row, scale.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       easy. \nQed.\n\nLemma col_add_each_transpose : forall {n m} (A : GenMatrix n m) (col : nat) (as' : GenMatrix 1 m),\n  (col_add_each col as' A)⊤ = row_add_each col (as'⊤) (A⊤).\nProof. intros. \n       unfold row_add_each, col_add_each. \n       rewrite GMplus_transpose.\n       rewrite GMmult_transpose. \n       rewrite get_col_transpose. \n       easy.\nQed.\n\nLemma row_add_each_transpose : forall {n m} (A : GenMatrix n m) (row : nat) (as' : Vector n),\n  (row_add_each row as' A)⊤ = col_add_each row (as'⊤) (A⊤).\nProof. intros. \n       unfold row_add_each, col_add_each. \n       rewrite GMplus_transpose.\n       rewrite GMmult_transpose. \n       rewrite get_row_transpose. \n       easy.\nQed.\n\n\n\n\n(** the idea is to show that col operations correspond to multiplication by special matrices. *)\n(** Thus, we show that the col ops all satisfy various multiplication rules *)\nLemma swap_preserves_mul_lt : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o) (x y : nat),\n  x < y -> x < m -> y < m -> A × B = (col_swap A x y) × (row_swap B x y).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold GMmult. \n       bdestruct (x <? m); try lia.\n       rewrite (le_plus_minus' x m); try lia.\n       do 2 rewrite big_sum_sum. \n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x1 =? x); bdestruct (x1 =? y); try lia; try easy.   \n       destruct (m - x) as [| x'] eqn:E; try lia. \n       do 2 rewrite <- big_sum_extend_l.\n       rewrite Gplus_comm.\n       rewrite (Gplus_comm (col_swap A x y x0 (x + 0)%nat * row_swap B x y (x + 0)%nat y0)%G _).\n       bdestruct ((y - x - 1) <? x'); try lia.  \n       rewrite (le_plus_minus' (y - x - 1) x'); try lia. \n       do 2 rewrite big_sum_sum.\n       do 2 rewrite <- Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x + S x1 =? x); bdestruct (x + S x1 =? y); try lia; try easy. \n       destruct (x' - (y - x - 1)) as [| x''] eqn:E1; try lia. \n       do 2 rewrite <- big_sum_extend_l.\n       rewrite Gplus_comm.\n       rewrite (Gplus_comm _ (col_swap A x y x0 (x + 0)%nat * row_swap B x y (x + 0)%nat y0)%G). \n       do 2 rewrite Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto. \n       do 2 rewrite <- plus_n_O. \n       unfold col_swap, row_swap.\n       bdestruct (x + S (y - x - 1) =? x); bdestruct (x + S (y - x - 1) =? y); \n         bdestruct (x =? x); try lia.\n       rewrite H5. ring. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x + S (y - x - 1 + S x1) =? x); \n         bdestruct (x + S (y - x - 1 + S x1) =? y); try lia; try easy.\nQed.           \n\nLemma swap_preserves_mul : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o) (x y : nat),\n  x < m -> y < m -> A × B = (col_swap A x y) × (row_swap B x y).\nProof. intros. bdestruct (x <? y).\n       - apply swap_preserves_mul_lt; easy.\n       - destruct H1.\n         + rewrite col_swap_same, row_swap_same; easy.\n         + rewrite col_swap_diff_order, row_swap_diff_order. \n           apply swap_preserves_mul_lt; lia.\nQed.\n\nLemma scale_preserves_mul : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o) (x : nat) (a : F),\n  A × (row_scale B x a) = (col_scale A x a) × B.\nProof. intros. \n       prep_genmatrix_equality. \n       unfold GMmult. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold col_scale, row_scale.\n       bdestruct (x1 =? x).\n       - rewrite Gmult_assoc.\n         ring. \n       - reflexivity. \nQed.        \n\nLemma add_preserves_mul_lt : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o) \n                                                (x y : nat) (a : F),\n   x < y -> x < m -> y < m -> A × (row_add B y x a) = (col_add A x y a) × B.\nProof. intros.  \n       prep_genmatrix_equality. \n       unfold GMmult.   \n       bdestruct (x <? m); try lia.\n       rewrite (le_plus_minus' x m); try lia.       \n       do 2 rewrite big_sum_sum.\n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x1 =? y); bdestruct (x1 =? x); try lia; easy. \n       destruct (m - x) as [| x'] eqn:E; try lia. \n       do 2 rewrite <- big_sum_extend_l.\n       rewrite Gplus_comm. \n       rewrite (Gplus_comm (col_add A x y a x0 (x + 0)%nat * B (x + 0)%nat y0)%G _).\n       bdestruct ((y - x - 1) <? x'); try lia.  \n       rewrite (le_plus_minus' (y - x - 1) x'); try lia. \n       do 2 rewrite big_sum_sum.\n       do 2 rewrite <- Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x + S x1 =? y); bdestruct (x + S x1 =? x); try lia; easy. \n       destruct (x' - (y - x - 1)) as [| x''] eqn:E1; try lia. \n       do 2 rewrite <- big_sum_extend_l.\n       rewrite Gplus_comm. \n       rewrite (Gplus_comm _ (col_add A x y a x0 (x + 0)%nat * B (x + 0)%nat y0)%G).\n       do 2 rewrite Gplus_assoc.\n     apply f_equal_gen; try apply f_equal; auto. \n       unfold row_add, col_add.\n       do 2 rewrite <- plus_n_O.\n       bdestruct (x =? y); bdestruct (x =? x); \n         bdestruct (x + S (y - x - 1) =? y); bdestruct (x + S (y - x - 1) =? x); try lia. \n       rewrite H6. ring. \n       apply big_sum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x + S (y - x - 1 + S x1) =? y); \n         bdestruct (x + S (y - x - 1 + S x1) =? x); try lia; easy. \nQed.\n\nLemma add_preserves_mul : forall {n m o} (A : GenMatrix n m) (B : GenMatrix m o) \n                                             (x y : nat) (a : F),\n   x < m -> y < m -> A × (row_add B y x a) = (col_add A x y a) × B.\nProof. intros. bdestruct (x <? y).\n       - apply add_preserves_mul_lt; easy.\n       - destruct H1.\n         + rewrite col_add_double, row_add_double. \n           apply scale_preserves_mul.\n         + rewrite (swap_preserves_mul A _ y (S m0)); try easy.\n           rewrite (swap_preserves_mul _ B (S m0) y); try easy.\n           rewrite col_add_swap.\n           rewrite row_add_swap.\n           rewrite row_swap_diff_order.\n           rewrite col_swap_diff_order.\n           apply add_preserves_mul_lt; lia. \nQed.\n\n\n(* used for the below induction where basically we may have to go from n to (n + 2) *)\n(* might want to move this somewhere else. cool technique though! Maybe coq already has something like this  *) \nDefinition skip_count (skip i : nat) : nat :=\n  if (i <? skip) then i else S i.\n\nLemma skip_count_le : forall (skip i : nat),\n  i <= skip_count skip i.\nProof. intros; unfold skip_count. \n       bdestruct (i <? skip); lia.\nQed.\n\nLemma skip_count_not_skip : forall (skip i : nat),\n  skip <> skip_count skip i. \nProof. intros; unfold skip_count. \n       bdestruct (i <? skip); try lia. \nQed.\n\nLemma skip_count_mono : forall (skip i1 i2 : nat),\n  i1 < i2 -> skip_count skip i1 < skip_count skip i2.\nProof. intros; unfold skip_count. \n       bdestruct (i1 <? skip); bdestruct (i2 <? skip); try lia. \nQed.\n\nLemma cam_ca_switch : forall {n m} (T : GenMatrix n m) (as' : Vector m) (col to_add : nat) (c : F),\n  as' col 0 = 0%G -> to_add <> col -> \n  col_add (col_add_many col as' T) col to_add c = \n  col_add_many col as' (col_add T col to_add c).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_add, col_add_many.\n       bdestruct (y =? col); try lia; try easy.\n       repeat rewrite <- Gplus_assoc.\n       apply f_equal_gen; try apply f_equal; auto. \n       bdestruct (to_add =? col); try lia.\n       rewrite Gplus_comm.\n       apply f_equal_gen; try apply f_equal; auto. \n       unfold gen_new_vec.\n       do 2 rewrite Msum_Fsum.\n       apply big_sum_eq_bounded; intros. \n       unfold get_col, scale; simpl.\n       bdestruct (x0 =? col); try ring. \n       rewrite H4, H; ring.\nQed.\n\nLemma col_add_many_preserves_mul_some : forall (n m o e col : nat) \n                                               (A : GenMatrix n m) (B : GenMatrix m o) (v : Vector m),\n  WF_GenMatrix v -> (skip_count col e) < m -> col < m -> \n  (forall i : nat, (skip_count col e) < i -> v i 0 = 0%G) -> v col 0 = 0%G ->\n  A × (row_add_each col v B) = (col_add_many col v A) × B.  \nProof. induction e as [| e].\n       - intros.\n         destruct m; try easy.\n         rewrite (col_add_many_col_add col (skip_count col 0) _ _); try easy.\n         rewrite <- (col_add_many_0 col A (make_row_zero (skip_count col 0) v)).\n         rewrite (row_add_each_row_add col (skip_count col 0) _ _); try easy.\n         rewrite <- (row_add_each_0 col B (make_row_zero (skip_count col 0) v)).\n         apply add_preserves_mul; try easy.\n         apply genmat_equiv_eq; auto with wf_db.\n         unfold genmat_equiv; intros. \n         destruct j; try lia. \n         unfold make_row_zero.\n         bdestruct (i =? skip_count col 0); try lia; try easy. \n         destruct col; destruct i; try easy.\n         rewrite H2; try easy. unfold skip_count in *. \n         bdestruct (0 <? 0); lia. \n         rewrite H2; try easy.\n         unfold skip_count in *. simpl; lia. \n         all : try apply skip_count_not_skip.\n         intros. destruct y; try easy.\n         apply H; lia. \n         unfold genmat_equiv, make_row_zero; intros. \n         destruct j; try lia. \n         bdestruct (i =? skip_count col 0); try lia; try easy. \n         destruct col; try easy.\n         destruct i; try easy.\n         rewrite H2; try easy. \n         unfold skip_count in *; simpl in *; lia. \n         rewrite H2; try easy.\n         unfold skip_count in *; simpl in *; lia. \n       - intros. \n         destruct m; try easy.\n         rewrite (col_add_many_col_add col (skip_count col (S e)) _ _); try easy.\n         rewrite (row_add_each_row_add col (skip_count col (S e)) _ _); try easy.\n         rewrite add_preserves_mul; try easy.\n         rewrite cam_ca_switch. \n         rewrite IHe; try easy; auto with wf_db.\n         assert (p : e < S e). lia. \n         apply (skip_count_mono col) in p.\n         lia. \n         intros.\n         unfold make_row_zero.\n         bdestruct (i =? skip_count col (S e)); try easy. \n         unfold skip_count in *. \n         bdestruct (e <? col); bdestruct (S e <? col); try lia. \n         all : try (apply H2; lia). \n         bdestruct (i =? col); bdestruct (S e =? col); try lia. \n         rewrite H8; apply H3.\n         apply H2. lia. \n         unfold make_row_zero.\n         bdestruct (col =? skip_count col (S e)); try easy.\n         unfold make_row_zero.\n         bdestruct (col =? skip_count col (S e)); try easy.\n         assert (H4 := skip_count_not_skip). auto.\n         all : try apply skip_count_not_skip.\n         intros. \n         destruct y; try easy.\n         apply H; lia. \nQed.\n\nLemma col_add_many_preserves_mul: forall (n m o col : nat) \n                                               (A : GenMatrix n m) (B : GenMatrix m o) (v : Vector m),\n  WF_GenMatrix v -> col < m -> v col 0 = 0%G ->\n  A × (row_add_each col v B) = (col_add_many col v A) × B.  \nProof. intros. \n       destruct m; try easy.\n       destruct m.\n       - assert (H' : v = Zero).\n         apply genmat_equiv_eq; auto with wf_db.\n         unfold genmat_equiv; intros. \n         destruct i; destruct j; destruct col; try lia; easy.\n         rewrite <- col_add_many_0, <- row_add_each_0; try easy.\n         rewrite H'; easy.\n       - apply (col_add_many_preserves_mul_some _ _ _ m col); try easy.\n         unfold skip_count.\n         bdestruct (m <? col); lia. \n         intros. \n         unfold skip_count in H2.\n         bdestruct (m <? col). \n         bdestruct (col =? (S m)); try lia. \n         bdestruct (i =? (S m)). \n         rewrite H5, <- H4. apply H1.\n         apply H; lia. \n         apply H; lia. \nQed.\n\n(* we can prove col_add_each version much more easily using transpose *)\nLemma col_add_each_preserves_mul: forall (n m o col : nat) (A : GenMatrix n m) \n                                                         (B : GenMatrix m o) (v : GenMatrix 1 m),\n  WF_GenMatrix v -> col < m -> v 0 col = 0%G ->\n  A × (row_add_many col v B) = (col_add_each col v A) × B.  \nProof. intros. \n       assert (H' : ((B⊤) × (row_add_each col (v⊤) (A⊤)))⊤ = \n                               ((col_add_many col (v⊤) (B⊤)) × (A⊤))⊤).  \n       rewrite col_add_many_preserves_mul; auto with wf_db; try easy.\n       do 2 rewrite GMmult_transpose in H'. \n       rewrite row_add_each_transpose in H'. \n       rewrite col_add_many_transpose in H'. \n       repeat rewrite transpose_involutive in H'.\n       easy. \nQed.\n\nLemma col_swap_mult_r : forall {n} (A : Square n) (x y : nat),\n  x < n -> y < n -> WF_GenMatrix A -> \n  col_swap A x y = A × (row_swap (I n) x y).\nProof. intros.\n       assert (H2 := (swap_preserves_mul A (row_swap (I n) x y) x y)).\n       rewrite <- (GMmult_1_r _ _ (col_swap A x y)); auto with wf_db.\n       rewrite H2; try easy.\n       rewrite <- (row_swap_inv (I n) x y).\n       reflexivity. \nQed.\n\nLemma col_scale_mult_r : forall {n} (A : Square n) (x : nat) (a : F),\n  WF_GenMatrix A -> \n  col_scale A x a = A × (row_scale (I n) x a).\nProof. intros. \n       rewrite scale_preserves_mul.\n       rewrite GMmult_1_r; auto with wf_db. \nQed.\n\nLemma col_add_mult_r : forall {n} (A : Square n) (x y : nat) (a : F),\n  x < n -> y < n -> WF_GenMatrix A -> \n  col_add A x y a = A × (row_add (I n) y x a).\nProof. intros. \n       rewrite add_preserves_mul; auto.\n       rewrite GMmult_1_r; auto with wf_db. \nQed.\n\nLemma col_add_many_mult_r : forall {n} (A : Square n) (v : Vector n) (col : nat),\n  WF_GenMatrix A -> WF_GenMatrix v -> col < n -> v col 0 = 0%G ->\n  col_add_many col v A = A × (row_add_each col v (I n)).\nProof. intros. \n       rewrite col_add_many_preserves_mul; try easy.\n       rewrite GMmult_1_r; auto with wf_db.\nQed.\n\nLemma col_add_each_mult_r : forall {n} (A : Square n) (v : GenMatrix 1 n) (col : nat),\n  WF_GenMatrix A -> WF_GenMatrix v -> col < n -> v 0 col = 0%G ->\n  col_add_each col v A = A × (row_add_many col v (I n)).\nProof. intros. \n       rewrite col_add_each_preserves_mul; try easy.\n       rewrite GMmult_1_r; auto with wf_db.\nQed.\n\n\n\n\n(*  TODO: figure out where to put these! \nLemma col_scale_inv : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  a <> 0%G -> S = col_scale (col_scale S x a) x (/ a).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_scale.\n       bdestruct (y =? x); try easy.\n       rewrite Gmult_assoc.\n       rewrite Cinv_l; try ring; easy. \nQed.\nLemma row_scale_inv : forall {n m : nat} (S : GenMatrix n m) (x : nat) (a : F),\n  a <> 0%G -> S = row_scale (row_scale S x a) x (/ a).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold row_scale.\n       bdestruct (x0 =? x); try easy.\n       rewrite Gmult_assoc.\n       rewrite Cinv_l; try ring; easy. \nQed.\n*)\n\n\n\n\n(* now we prove facts about the ops on (I n) *)\nLemma col_row_swap_invr_I : forall (n x y : nat), \n  x < n -> y < n -> col_swap (I n) x y = row_swap (I n) x y.\nProof. intros. \n       prep_genmatrix_equality.\n       unfold col_swap, row_swap, I.\n       bdestruct_all; try easy.\nQed.\n\nLemma col_row_scale_invr_I : forall (n x : nat) (c : F), \n  col_scale (I n) x c = row_scale (I n) x c.\nProof. intros. \n       prep_genmatrix_equality.\n       unfold col_scale, row_scale, I.\n       bdestruct_all; try easy; simpl; ring.\nQed.\n\nLemma col_row_add_invr_I : forall (n x y : nat) (c : F), \n  x < n -> y < n -> col_add (I n) x y c = row_add (I n) y x c.\nProof. intros. \n       prep_genmatrix_equality.\n       unfold col_add, row_add, I.\n       bdestruct_all; try easy; simpl; ring.\nQed.\n\nLemma row_each_col_many_invr_I : forall (n col : nat) (v : Vector n),\n  WF_GenMatrix v -> col < n -> v col 0 = 0%G ->\n  row_add_each col v (I n) = col_add_many col v (I n).  \nProof. intros. \n       rewrite <- GMmult_1_r, <- col_add_many_preserves_mul, GMmult_1_l; auto with wf_db. \nQed.\n\nLemma row_many_col_each_invr_I : forall (n col : nat) (v : GenMatrix 1 n),\n  WF_GenMatrix v -> col < n -> v 0 col = 0%G ->\n  row_add_many col v (I n) = col_add_each col v (I n).  \nProof. intros. \n       rewrite <- GMmult_1_r, <- col_add_each_preserves_mul, GMmult_1_l; auto with wf_db. \nQed.\n\nLemma reduce_append_split : forall {n m} (T : GenMatrix n (S m)), \n  WF_GenMatrix T -> T = col_append (reduce_col T m) (get_col m T).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold col_append, get_col, reduce_col.\n       bdestruct_all; subst; try easy.\n       do 2 (rewrite H; try lia); easy. \nQed.\n\nLemma smash_zero : forall {n m} (T : GenMatrix n m) (i : nat),\n  WF_GenMatrix T -> smash T (@Zero n i) = T. \nProof. intros. \n       prep_genmatrix_equality.\n       unfold smash, Zero. \n       bdestruct (y <? m); try easy.\n       rewrite H; try lia; easy.\nQed.\n\nLemma smash_assoc : forall {n m1 m2 m3}\n                           (T1 : GenMatrix n m1) (T2 : GenMatrix n m2) (T3 : GenMatrix n m3),\n  smash (smash T1 T2) T3 = smash T1 (smash T2 T3).\nProof. intros. \n       unfold smash.\n       prep_genmatrix_equality.\n       bdestruct (y <? m1 + m2); bdestruct (y <? m1); \n         bdestruct (y - m1 <? m2); try lia; try easy.\n       assert (H' : y - (m1 + m2) = y - m1 - m2).\n       lia. rewrite H'; easy.\nQed.\n\nLemma smash_append : forall {n m} (T : GenMatrix n m) (v : Vector n),\n  WF_GenMatrix T -> WF_GenMatrix v ->\n  col_append T v = smash T v.\nProof. intros. \n       unfold smash, col_append, WF_GenMatrix in *.\n       prep_genmatrix_equality. \n       bdestruct (y =? m); bdestruct (y <? m); try lia; try easy.\n       rewrite H1.\n       rewrite Nat.sub_diag; easy. \n       rewrite H0, H; try lia; try easy.\nQed.\n\nLemma smash_reduce : forall {n m1 m2} (T1 : GenMatrix n m1) (T2 : GenMatrix n (S m2)),\n  reduce_col (smash T1 T2) (m1 + m2) = smash T1 (reduce_col T2 m2).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold reduce_col, smash. \n       bdestruct (y <? m1 + m2); bdestruct (y <? m1); bdestruct (1 + y <? m1);\n         bdestruct (y - m1 <? m2); try lia; try easy.\n       assert (H' : 1 + y - m1 = 1 + (y - m1)). lia.  \n       rewrite H'; easy.\nQed.\n\nLemma split_col : forall {n m} (T : GenMatrix n (S m)), \n  T = smash (get_col 0 T) (reduce_col T 0).\nProof. intros. \n       prep_genmatrix_equality. \n       unfold smash, get_col, reduce_col.\n       bdestruct (y <? 1); bdestruct (y =? 0); bdestruct (y - 1 <? 0); try lia; try easy.\n       rewrite H0; easy. \n       destruct y; try lia. \n       simpl. assert (H' : y - 0 = y). lia. \n       rewrite H'; easy.\nQed.\n\n\n\n(** * Some more lemmas with these new concepts *)\n\n(* We can now show that matrix_equivalence is decidable *)\nLemma vec_equiv_dec : forall {n : nat} (A B : Vector n), \n    { A == B } + { ~ (A == B) }.\nProof. induction n as [| n'].\n       - left; easy.\n       - intros. destruct (IHn' (reduce_vecn A) (reduce_vecn B)).\n         + destruct (Geq_dec (A n' 0) (B n' 0)).\n           * left. \n             unfold genmat_equiv in *.\n             intros.\n             bdestruct (i =? n'); bdestruct (n' <? i); try lia. \n             rewrite H1.\n             destruct j.\n             apply e. lia.\n             apply (g i j) in H0; try lia.\n             unfold reduce_vecn in H0.\n             bdestruct (i <? n'); try lia; easy.\n           * right. unfold not. \n             intros. unfold genmat_equiv in H.\n             apply n. apply H; lia. \n         + right. \n           unfold not in *. \n           intros. apply n.\n           unfold genmat_equiv in *.\n           intros. unfold reduce_vecn.\n           bdestruct (i <? n'); try lia. \n           apply H; lia. \nQed.\n\nLemma genmat_equiv_dec : forall {n m : nat} (A B : GenMatrix n m), \n    { A == B } + { ~ (A == B) }.\nProof. induction m as [| m']. intros.  \n       - left. easy.\n       - intros. destruct (IHm' (reduce_col A m') (reduce_col B m')).\n         + destruct (vec_equiv_dec (get_col m' A) (get_col m' B)).\n           * left. \n             unfold genmat_equiv in *.\n             intros. \n             bdestruct (j =? m'); bdestruct (m' <? j); try lia.\n             ++ apply (g0 i 0) in H.\n                do 2 rewrite get_col_conv in H.\n                rewrite H1. easy. lia. \n             ++ apply (g i j) in H.\n                unfold reduce_col in H.\n                bdestruct (j <? m'); try lia; try easy.\n                lia. \n           * right. \n             unfold not, genmat_equiv in *.\n             intros. apply n0.\n             intros. \n             destruct j; try easy.\n             do 2 rewrite get_col_conv.\n             apply H; lia.\n         + right. \n           unfold not, genmat_equiv, reduce_col in *.\n           intros. apply n0. \n           intros. \n           bdestruct (j <? m'); try lia.\n           apply H; lia.            \nQed.\n\n(* we can also now prove some useful lemmas about nonzero vectors *)\nLemma last_zero_simplification : forall {n : nat} (v : Vector (S n)),\n  WF_GenMatrix v -> v n 0 = 0%G -> v = reduce_vecn v.\nProof. intros. unfold reduce_vecn.\n       prep_genmatrix_equality.\n       bdestruct (x <? n).\n       - easy.\n       - unfold WF_GenMatrix in H.\n         destruct H1.\n         + destruct y. \n           * rewrite H0, H. reflexivity.\n             left. nia. \n           * rewrite H. rewrite H. reflexivity.\n             right; nia. right; nia.\n         + rewrite H. rewrite H. reflexivity.\n           left. nia. left. nia.\nQed.\n\nLemma zero_reduce : forall {n : nat} (v : Vector (S n)) (x : nat),\n  WF_GenMatrix v -> (v = Zero <-> (reduce_row v x) = Zero /\\ v x 0 = 0%G).\nProof. intros. split.    \n       - intros. rewrite H0. split.\n         + prep_genmatrix_equality. unfold reduce_row. \n           bdestruct (x0 <? x); easy. \n         + easy.\n       - intros [H0 H1]. \n         prep_genmatrix_equality.\n         unfold Zero.\n         bdestruct (x0 =? x).\n         + rewrite H2. \n           destruct y; try easy.          \n           apply H; lia.\n         + bdestruct (x0 <? x). \n           * assert (H' : (reduce_row v x) x0 y = 0%G). \n             { rewrite H0. easy. }\n             unfold reduce_row in H'.\n             bdestruct (x0 <? x); try lia; try easy.\n           * destruct x0; try lia. \n             assert (H'' : (reduce_row v x) x0 y = 0%G). \n             { rewrite H0. easy. }\n             unfold reduce_row in H''.\n             bdestruct (x0 <? x); try lia. \n             rewrite <- H''. easy.\nQed.\n\nLemma nonzero_vec_nonzero_elem : forall {n} (v : Vector n),\n  WF_GenMatrix v -> v <> Zero -> exists x, v x 0 <> 0%G.\nProof. induction n as [| n']. \n       - intros. \n         assert (H' : v = Zero).\n         { prep_genmatrix_equality.\n           unfold Zero.\n           unfold WF_GenMatrix in H.\n           apply H.\n           left. lia. }\n         easy.\n       - intros.   \n         destruct (Geq_dec (v n' 0) 0%G). \n         + destruct (vec_equiv_dec (reduce_row v n') Zero). \n           * assert (H' := H). \n             apply (zero_reduce _ n') in H'.\n             destruct H'.\n             assert (H' : v = Zero). \n             { apply H2.\n               split. \n               apply genmat_equiv_eq; auto with wf_db.\n               easy. }\n             easy.             \n           * assert (H1 : exists x, (reduce_row v n') x 0 <> 0%G).\n             { apply IHn'; auto with wf_db.\n               unfold not in *. intros. apply n. \n               rewrite H1. easy. }\n             destruct H1. \n             exists x. \n             rewrite (last_zero_simplification v); try easy.    \n         + exists n'. \n           apply n.\nQed.\n\nLocal Close Scope nat_scope.\n\n\n\n(* some inner product lemmas *)\nLemma inner_product_scale_l : forall {n} (u v : Vector n) (c : F),\n  ⟨c .* u, v⟩ = c * ⟨u,v⟩.\nProof. intros.\n       unfold inner_product, scale, transpose, GMmult.\n       rewrite (@big_sum_mult_l F _ _ _ R3).\n       apply big_sum_eq_bounded; intros.\n       ring.\nQed.       \n\nLemma inner_product_scale_r : forall {n} (u v : Vector n) (c : F),\n  ⟨u, c .* v⟩ = c * ⟨u,v⟩.\nProof. intros.\n       unfold inner_product, scale, transpose, GMmult.\n       rewrite (@big_sum_mult_l F _ _ _ R3).\n       apply big_sum_eq_bounded; intros.\n       ring.\nQed.       \n\nLemma inner_product_plus_l : forall {n} (u v w : Vector n),\n  ⟨u .+ v, w⟩ = ⟨u, w⟩ + ⟨v, w⟩.\nProof. intros.\n       unfold inner_product, scale, transpose, GMplus, GMmult.\n       rewrite <- (@big_sum_plus F _ _ R2).\n       apply big_sum_eq_bounded; intros.\n       ring.\nQed.       \n\nLemma inner_product_plus_r : forall {n} (u v w : Vector n),\n  ⟨u, v .+ w⟩ = ⟨u, v⟩ + ⟨u, w⟩.\nProof. intros.\n       unfold inner_product, scale, transpose, GMplus, GMmult.\n       rewrite <- (@big_sum_plus F _ _ R2).\n       apply big_sum_eq_bounded; intros.\n       ring.\nQed.          \n\nLemma inner_product_big_sum_l : forall {n} (u : Vector n) (f : nat -> Vector n) (k : nat),\n  ⟨big_sum f k, u⟩ = big_sum (fun i => ⟨f i, u⟩) k.\nProof. induction k.\n       - unfold inner_product; simpl.\n         rewrite (zero_transpose_eq n 1), (GMmult_0_l 1 n); easy.\n       - simpl. \n         rewrite inner_product_plus_l, IHk.\n         reflexivity.\nQed.       \n\nLemma inner_product_big_sum_r : forall {n} (u : Vector n) (f : nat -> Vector n) (k : nat),\n  ⟨u, big_sum f k⟩ = big_sum (fun i => ⟨u, f i⟩) k.\nProof. induction k.\n       - unfold inner_product; simpl.\n         rewrite GMmult_0_r; easy.\n       - simpl. \n         rewrite inner_product_plus_r, IHk.\n         reflexivity.\nQed.       \n\nLemma inner_product_conj_sym : forall {n} (u v : Vector n),\n  ⟨u, v⟩ = ⟨v, u⟩.\nProof. intros. \n       unfold inner_product, transpose, GMmult.\n       apply big_sum_eq_bounded; intros.\n       ring.\nQed.\n\nLemma inner_product_mafe_WF_l : forall {n} (u v : Vector n),\n  ⟨u, v⟩ = ⟨make_WF u, v⟩.\nProof. intros. \n       unfold inner_product, transpose, GMmult, make_WF.\n       apply big_sum_eq_bounded; intros.\n       bdestruct_all; simpl; easy.\nQed.\n\nLemma inner_product_mafe_WF_r : forall {n} (u v : Vector n),\n  ⟨u, v⟩ = ⟨u, make_WF v⟩.\nProof. intros. \n       unfold inner_product, transpose, GMmult, make_WF.\n       apply big_sum_eq_bounded; intros.\n       bdestruct_all; simpl; easy.\nQed.\n\n\n\n(* TODO: could add norm, but need field for everything else \n(* Useful to be able to normalize vectors *)\nDefinition norm {n} (ψ : Vector n) : R :=\n  sqrt (fst ⟨ψ,ψ⟩).\nDefinition normalize {n} (ψ : Vector n) :=\n  / (norm ψ) .* ψ.\nLemma norm_scale : forall {n} c (v : Vector n), norm (c .* v) = ((Cmod c) * norm v)%R.\nProof.\n  intros n c v.\n  unfold norm, inner_product.\n  rewrite Mscale_adj.\n  rewrite Mscale_mult_dist_l, Mscale_mult_dist_r, Mscale_assoc.\n  unfold scale.\n  simpl.\n  replace (fst c * snd c + - snd c * fst c)%R with 0%R.\n  autorewrite with R_db C_db.\n  replace (fst c * fst c)%R with (fst c ^ 2)%R by lra.\n  replace (snd c * snd c)%R with (snd c ^ 2)%R by lra.\n  rewrite sqrt_mult_alt.\n  reflexivity.\n  apply Rplus_le_le_0_compat; apply pow2_ge_0.\n  lra.\nQed.\nLemma normalized_norm_1 : forall {n} (v : Vector n),\n  norm v <> 0 -> norm (normalize v) = 1.\nProof. intros. \n       unfold normalize.\n       rewrite norm_scale.  \n       rewrite Cmod_real. \n       simpl.  \n       autorewrite with R_db.\n       rewrite Rmult_comm.\n       rewrite Rinv_mult_distr; try easy. \n       rewrite <- Rmult_comm.\n       rewrite <- Rmult_assoc.\n       rewrite Rinv_r; try easy.\n       autorewrite with R_db.\n       reflexivity. \n       unfold Cinv.\n       simpl. \n       autorewrite with R_db.\n       rewrite Rinv_mult_distr; try easy. \n       rewrite <- Rmult_assoc.\n       rewrite Rinv_r; try easy.\n       autorewrite with R_db.\n       assert (H' : norm v >= 0).\n       { assert (H'' : 0 <= norm v).\n         { apply sqrt_pos. }\n         lra. }\n       destruct H' as [H0 | H0].\n       left.\n       assert (H1 : 0 < norm v). { lra. }\n       apply Rinv_0_lt_compat in H1.\n       lra. easy. \n       apply div_real.\n       easy. \nQed. \nLemma rewrite_norm : forall {d} (ψ : Vector d),\n    fst ⟨ψ,ψ⟩ = big_sum (fun i => Cmod (ψ i O) ^ 2)%R d.\nProof.\n  intros d ψ. unfold inner_product, GMmult.\n  replace (fun y : nat => (ψ† O y * ψ y O)%G) with (fun y : nat => RtoC (Cmod (ψ y O) ^ 2)).\n  apply Rsum_big_sum.\n  apply functional_extensionality. intros.\n  unfold adjoint. rewrite <- Cmod_sqr. symmetry. apply RtoC_pow.\nQed.\nLocal Open Scope nat_scope.\nLemma norm_real : forall {n} (v : Vector n), snd ⟨v,v⟩ = 0%R. \nProof. intros. unfold inner_product, GMmult, adjoint.\n       rewrite big_sum_snd_0. easy.\n       intros. rewrite Gmult_comm.\n       rewrite Gmult_conj_real.\n       reflexivity.\nQed.\nLemma inner_product_ge_0 : forall {d} (ψ : Vector d),\n  (0 <= fst ⟨ψ,ψ⟩)%R.\nProof.\n  intros.\n  unfold inner_product, GMmult, adjoint.\n  apply big_sum_ge_0.\n  intro.\n  rewrite <- Cmod_sqr.\n  simpl.\n  autorewrite with R_db.\n  apply Rmult_le_pos; apply Cmod_ge_0.\nQed.\n(* why does sqrt_pos exist? *)\nLemma norm_ge_0 : forall {d} (ψ : Vector d),\n  (0 <= norm ψ)%R.\nProof. intros.\n       unfold norm.\n       apply sqrt_positivity.\n       (* apply sqrt_pos *)\n       apply inner_product_ge_0.\nQed.\nLemma norm_squared : forall {d} (ψ : Vector d),\n  ((norm ψ) ^2)%R = fst ⟨ ψ, ψ ⟩.\nProof. intros.\n       unfold norm.\n       rewrite pow2_sqrt; auto.\n       apply inner_product_ge_0.\nQed.\n(* \"Quick\" proof of |x| = 0 iff x = 0 *)\nLemma inner_product_zero_iff_zero : forall {n} (v : Vector n),\n  WF_GenMatrix v -> (⟨v,v⟩ = 0%G <-> v = Zero). \nProof. intros. split. \n       - intros. \n         destruct (genmat_equiv_dec v Zero).\n         apply genmat_equiv_eq; try easy.\n         assert (H' : v <> Zero). \n         { unfold not; intros. \n           apply n0. rewrite H1.\n           easy. }\n         apply nonzero_vec_nonzero_elem in H'; try easy.\n         destruct H'. \n         unfold WF_GenMatrix in H.\n         bdestruct (x <? n).\n         assert (H0' := Rle_0_sqr).  \n         unfold Rsqr in H0'. \n         assert (H' : (0 < fst (inner_product v v))%R).\n         { unfold inner_product.\n           unfold GMmult. \n           apply big_sum_gt_0.\n           unfold adjoint. \n           intros.\n           rewrite <- Cmod_sqr.\n           simpl. autorewrite with R_db.\n           apply H0'. \n           exists x. split; try easy.\n           unfold adjoint. \n           rewrite <- Cmod_sqr.\n           simpl. autorewrite with R_db.\n           assert (H' : (0 <= Cmod (v x 0%nat) * Cmod (v x 0%nat))%R). \n           { apply H0'. } \n           destruct H'; try easy. \n           assert (H' := Rsqr_0_uniq).\n           unfold Rsqr in H'. \n           assert (H'' : forall a b : R, a = b -> b = a). { easy. }\n           apply H'' in H3. \n           apply H' in H3.\n           apply Cmod_gt_0 in H1.\n           rewrite H3 in H1.\n           lra. }\n         rewrite H0 in H'. \n         simpl in H'. lra. \n         assert (H' : v x O = 0%G).\n         { apply H. left; easy. }\n         rewrite H' in H1; easy. \n       - intros. \n         unfold inner_product.  \n         rewrite H0. \n         rewrite GMmult_0_r. \n         easy.\nQed.\nLemma norm_zero_iff_zero : forall {n} (v : Vector n),\n  WF_GenMatrix v -> (norm v = 0%R <-> v = Zero). \nProof. intros. split. \n       - intros. \n         unfold norm in H0.\n         apply inner_product_zero_iff_zero in H.\n         unfold inner_product in H. \n         apply sqrt_eq_0 in H0.\n         apply H. \n         apply c_proj_eq.\n         apply H0.\n         apply norm_real.\n         apply inner_product_ge_0.\n       - intros. \n         rewrite H0. \n         unfold norm, inner_product.\n         rewrite GMmult_0_r. \n         simpl. apply sqrt_0. \nQed.     \nLocal Close Scope nat_scope.\n(* We can now prove Cauchy-Schwartz for vectors with inner_product *)\nLemma CS_key_lemma : forall {n} (u v : Vector n),\n  fst ⟨ (⟨v,v⟩ .* u .+ -1 * ⟨v,u⟩ .* v), (⟨v,v⟩ .* u .+ -1 * ⟨v,u⟩ .* v) ⟩ =\n    ((fst ⟨v,v⟩) * ((fst ⟨v,v⟩)* (fst ⟨u,u⟩) - (Cmod ⟨u,v⟩)^2 ))%R.\nProof. intros. \n       replace ((fst ⟨v,v⟩) * ((fst ⟨v,v⟩)* (fst ⟨u,u⟩) - (Cmod ⟨u,v⟩)^2 ))%R with\n               (fst (⟨v,v⟩ * (⟨v,v⟩ * ⟨u,u⟩ - (Cmod ⟨u,v⟩)^2))).\n       - apply f_equal.\n         repeat rewrite inner_product_plus_l; repeat rewrite inner_product_plus_r;\n           repeat rewrite inner_product_scale_l; repeat rewrite inner_product_scale_r. \n         replace ((-1 * ⟨ v, u ⟩) ^* * (-1 * ⟨ v, u ⟩ * ⟨ v, v ⟩)) with \n           ( ⟨ v, u ⟩^* * ⟨ v, u ⟩ * ⟨ v, v ⟩ ) by ring.       \n         replace ((-1 * ⟨ v, u ⟩) ^* * (⟨ v, v ⟩ * ⟨ v, u ⟩) +\n                    ⟨ v, u ⟩ ^* * ⟨ v, u ⟩ * ⟨ v, v ⟩) with 0%G by ring.\n         rewrite (inner_product_conj_sym v u), <- (inner_product_conj_sym v v).\n         rewrite <- Gmult_assoc.   \n         replace (⟨ u, v ⟩ ^* * ⟨ u, v ⟩) with (Cmod ⟨ u, v ⟩ ^ 2) by apply Cmod_sqr.\n         ring.\n       - assert (H := norm_real v).\n         assert (H0 := norm_real u).\n         destruct ⟨ v, v ⟩; destruct ⟨ u, u ⟩.\n         rewrite Cmod_sqr.\n         replace (⟨ u, v ⟩ ^* * ⟨ u, v ⟩) with (Cmod ⟨ u, v ⟩ ^ 2,0)%R.\n         simpl in *; subst; lra.\n         apply c_proj_eq.\n         unfold Cmod. \n         rewrite pow2_sqrt. \n         simpl; lra.\n         apply Rplus_le_le_0_compat; apply pow2_ge_0.\n         rewrite Gmult_comm, Gmult_conj_real; easy. \nQed.\nLemma real_ge_0_aux : forall (a b c : R),\n  0 <= a -> 0 < b -> (a = b * c)%R ->\n  0 <= c.\nProof. intros. \n       replace c with (a * / b)%R.\n       apply Rle_mult_inv_pos; auto.\n       subst.\n       replace (b * c * / b)%R with (b * /b * c)%R by lra.\n       rewrite Rinv_r; try lra. \nQed.\nLemma Cauchy_Schwartz_ver1 : forall {n} (u v : Vector n),\n  (Cmod ⟨u,v⟩)^2 <= (fst ⟨u,u⟩) * (fst ⟨v,v⟩).\nProof. intros. \n       destruct (Req_dec (fst ⟨v,v⟩) 0).\n       - rewrite H. \n         rewrite inner_product_mafe_WF_l, inner_product_mafe_WF_r in H.\n         rewrite inner_product_mafe_WF_r.\n         assert (H' : make_WF v = Zero).\n         { apply norm_zero_iff_zero; auto with wf_db.\n           unfold norm; rewrite H.\n           apply sqrt_0. }\n         unfold inner_product.\n         rewrite H', GMmult_0_r.\n         unfold Zero.\n         rewrite Cmod_0.\n         lra.\n       - assert (H0 := CS_key_lemma u v).\n         apply real_ge_0_aux in H0.\n         lra.\n         apply inner_product_ge_0.\n         destruct (inner_product_ge_0 v); lra.\nQed.\nLemma Cauchy_Schwartz_ver2 : forall {n} (u v : Vector n),\n  (Cmod ⟨u,v⟩) <= norm u * norm v.\nProof. intros. \n       rewrite <- (sqrt_pow2 (Cmod ⟨ u, v ⟩)), <- (sqrt_pow2 (norm v)), <- (sqrt_pow2 (norm u)).\n       rewrite <- sqrt_mult.\n       apply sqrt_le_1.\n       all : try apply pow2_ge_0.\n       apply Rmult_le_pos.\n       all : try apply pow2_ge_0.\n       unfold norm.\n       rewrite pow2_sqrt, pow2_sqrt.\n       apply Cauchy_Schwartz_ver1.\n       all : try apply inner_product_ge_0; try apply norm_ge_0.\n       apply Cmod_ge_0.\nQed.\nLemma Cplx_Cauchy_vector :\n  forall n (u v : Vector n),\n    ((big_sum (fun i => Cmod (u i O) ^ 2) n) * (big_sum (fun i => Cmod (v i O) ^ 2) n) >=\n     Cmod (big_sum (fun i => ((u i O)^* * (v i O))%G) n) ^ 2)%R.\nProof. intros.\n       assert (H := Cauchy_Schwartz_ver1 u v).\n       replace (big_sum (fun i : nat => (Cmod (u i 0%nat) ^ 2)%R) n) with (fst ⟨ u, u ⟩).\n       replace (big_sum (fun i : nat => (Cmod (v i 0%nat) ^ 2)%R) n) with (fst ⟨ v, v ⟩).\n       replace (Σ (fun i : nat => (u i 0%nat) ^* * v i 0%nat) n) with (⟨ u, v ⟩).\n       lra.\n       all : unfold inner_product, adjoint, GMmult; try easy. \n       all : rewrite (@big_sum_func_distr C R _ C_is_group _ R_is_group).\n       all : try apply big_sum_eq_bounded; intros.\n       all : try rewrite <- Cmod_sqr. \n       all : try (destruct a; destruct b; simpl; easy).\n       destruct (v x 0%nat); unfold Cmod, pow, Gmult; simpl; lra. \n       destruct (u x 0%nat); unfold Cmod, pow, Gmult; simpl; lra. \nQed.\nLocal Open Scope nat_scope.\nLemma Cplx_Cauchy :\n  forall n (u v : nat -> C),\n    ((big_sum (fun i => Cmod (u i) ^ 2) n) * (big_sum (fun i => Cmod (v i) ^ 2) n) >= Cmod (big_sum (fun i => ((u i)^* * (v i))%G) n) ^ 2)%R.\nProof. intros. \n       assert (H := Cplx_Cauchy_vector n (fun i j => u i) (fun i j => v i)).\n       simpl in *.\n       easy. \nQed.       \n*)\n\n\n\n\n(** * Tactics **)\n\nLocal Close Scope nat_scope.\n\n(* Note on \"using [tactics]\": Most generated subgoals will be of the form\n   WF_GenMatrix M, where auto with wf_db will work.\n   Occasionally WF_GenMatrix M will rely on rewriting to match an assumption in the\n   context, here we recursively autorewrite (which adds time).\n   kron_1_l requires proofs of (n > 0)%nat, here we use lia. *)\n\n(* *)\n\n(* Convert a list to a vector *)\nFixpoint vec_to_list' {nmax : nat} (n : nat) (v : Vector nmax) :=\n  match n with\n  | O    => nil\n  | S n' => v (nmax - n)%nat O :: vec_to_list' n' v\n  end.\nDefinition vec_to_list {n : nat} (v : Vector n) := vec_to_list' n v.\n\nLemma vec_to_list'_length : forall m n (v : Vector n), length (vec_to_list' m v) = m.\nProof.\n  intros.\n  induction m; auto.\n  simpl. rewrite IHm.\n  reflexivity.\nQed.\n\nLemma vec_to_list_length : forall n (v : Vector n), length (vec_to_list v) = n.\nProof. intros. apply vec_to_list'_length. Qed.\n\nLemma nth_vec_to_list' : forall {m n} (v : Vector n) x,\n  (m <= n)%nat -> (x < m)%nat -> nth x (vec_to_list' m v) 0 = v (n - m + x)%nat O.\nProof.\n  intros m n v x Hm.\n  gen x.\n  induction m; intros x Hx.\n  lia.\n  simpl.\n  destruct x.\n  rewrite Nat.add_0_r.\n  reflexivity.\n  rewrite IHm by lia.\n  replace (n - S m + S x)%nat with (n - m + x)%nat by lia.\n  reflexivity.\nQed.\n\nLemma nth_vec_to_list : forall n (v : Vector n) x,\n  (x < n)%nat -> nth x (vec_to_list v) 0 = v x O.\nProof.\n  intros.\n  unfold vec_to_list.\n  rewrite nth_vec_to_list' by lia.\n  replace (n - n + x)%nat with x by lia.\n  reflexivity.\nQed.\n\n\n(** Restoring GenMatrix Dimensions *)\n\n\n(** Restoring GenMatrix dimensions *)\nLtac is_nat n := match type of n with nat => idtac end.\n\nLtac is_nat_equality :=\n  match goal with \n  | |- ?A = ?B => is_nat A\n  end.\n\nLtac unify_matrix_dims tac := \n  try reflexivity; \n  repeat (apply f_equal_gen; try reflexivity; \n          try (is_nat_equality; tac)).\n\nLtac restore_dims_rec A :=\n   match A with\n(* special cases *)\n  | ?A × I _          => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | GenMatrix ?m' ?n' => constr:(@GMmult m' n' n' A' (I n'))\n                        end\n  | I _ × ?B          => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | GenMatrix ?n' ?o' => constr:(@GMmult n' n' o' (I n')  B')\n                        end\n  | ?A × @Zero ?n ?n  => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | GenMatrix ?m' ?n' => constr:(@GMmult m' n' n' A' (@Zero n' n'))\n                        end\n  | @Zero ?n ?n × ?B  => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | GenMatrix ?n' ?o' => constr:(@GMmult n' n' o' (@Zero n' n') B')\n                        end\n  | ?A × @Zero ?n ?o  => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | GenMatrix ?m' ?n' => constr:(@GMmult m' n' o A' (@Zero n' o))\n                        end\n  | @Zero ?m ?n × ?B  => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | GenMatrix ?n' ?o' => constr:(@GMmult n' n' o' (@Zero m n') B')\n                        end\n  | ?A .+ @Zero ?m ?n => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | GenMatrix ?m' ?n' => constr:(@GMplus m' n' A' (@Zero m' n'))\n                        end\n  | @Zero ?m ?n .+ ?B => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | GenMatrix ?m' ?n' => constr:(@GMplus m' n' (@Zero m' n') B')\n                        end\n(* general cases *)\n  | ?A = ?B  => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | GenMatrix ?m' ?n' => constr:(@eq (GenMatrix m' n') A' B')\n                  end\n  | ?A × ?B   => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | GenMatrix ?m' ?n' =>\n                  match type of B' with \n                  | GenMatrix ?n'' ?o' => constr:(@GMmult m' n' o' A' B')\n                  end\n                end \n  | ?A ⊗ ?B   => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | GenMatrix ?m' ?n' =>\n                  match type of B' with \n                  | GenMatrix ?o' ?p' => constr:(@Gkron m' n' o' p' A' B')\n                  end\n                end\n  (* | ?A †      => let A' := restore_dims_rec A in \n                match type of A' with\n                | GenMatrix ?m' ?n' => constr:(@adjoint m' n' A')\n                end *)\n  | ?A .+ ?B => let A' := restore_dims_rec A in \n               let B' := restore_dims_rec B in \n               match type of A' with \n               | GenMatrix ?m' ?n' =>\n                 match type of B' with \n                 | GenMatrix ?m'' ?n'' => constr:(@GMplus m' n' A' B')\n                 end\n               end\n  | ?c .* ?A => let A' := restore_dims_rec A in \n               match type of A' with\n               | GenMatrix ?m' ?n' => constr:(@scale m' n' c A')\n               end\n  | ?n ⨂ ?A => let A' := restore_dims_rec A in\n               match type of A' with\n               | GenMatrix ?m' ?n' => constr:(@kron_n n m' n' A')\n               end\n  (* For predicates (eg. WF_GenMatrix, Mixed_State) on Matrices *)\n  | ?P ?m ?n ?A => match type of P with\n                  | nat -> nat -> GenMatrix _ _ -> Prop =>\n                    let A' := restore_dims_rec A in \n                    match type of A' with\n                    | GenMatrix ?m' ?n' => constr:(P m' n' A')\n                    end\n                  end\n  | ?P ?n ?A => match type of P with\n               | nat -> GenMatrix _ _ -> Prop =>\n                 let A' := restore_dims_rec A in \n                 match type of A' with\n                 | GenMatrix ?m' ?n' => constr:(P m' A')\n                 end\n               end\n  (* Handle functions applied to matrices *)\n  | ?f ?A    => let f' := restore_dims_rec f in \n               let A' := restore_dims_rec A in \n               constr:(f' A')\n  (* default *)\n  | ?A       => A\n   end.\n\nLtac restore_dims tac := \n  match goal with\n  | |- ?A      => let A' := restore_dims_rec A in \n                replace A with A' by unify_matrix_dims tac\n  end.\n\nTactic Notation \"restore_dims\" tactic(tac) := restore_dims tac.\n\nTactic Notation \"restore_dims\" := restore_dims (repeat rewrite Nat.pow_1_l; try ring; unify_pows_two; simpl; lia).\n\n\n(* Proofs depending on restore_dims *)\n\n\nLemma kron_n_m_split {o p} : forall n m (A : GenMatrix o p), \n  WF_GenMatrix A -> (n + m) ⨂ A = n ⨂ A ⊗ m ⨂ A.\nProof.\n  induction n.\n  - simpl. \n    intros. \n    rewrite kron_1_l; try auto with wf_db.\n  - intros.\n    simpl.\n    rewrite IHn; try auto.\n    restore_dims.\n    rewrite 2 kron_assoc; try auto with wf_db.\n    rewrite <- kron_n_assoc; try auto.\n    simpl.\n    restore_dims.\n    reflexivity.\nQed.\n\n\n(** GenMatrix Simplification *)\n\n\n(* Old: \nHint Rewrite kron_1_l kron_1_r GMmult_1_l GMmult_1_r id_kron id_adjoint_eq\n     @GMmult_adjoint GMplus_adjoint @kron_adjoint @kron_mixed_product\n     id_adjoint_eq adjoint_involutive using \n     (auto 100 with wf_db; autorewrite with M_db; auto 100 with wf_db; lia) : M_db.\n*)\n\n(* eauto will cause major choking... *)\nHint Rewrite  @kron_1_l @kron_1_r @GMmult_1_l @GMmult_1_r @Mscale_1_l \n     (* @id_adjoint_eq *) @id_transpose_eq using (auto 100 with wf_db) : M_db_light.\nHint Rewrite @kron_0_l @kron_0_r @GMmult_0_l @GMmult_0_r @GMplus_0_l @GMplus_0_r\n     @Mscale_0_l @Mscale_0_r (* @zero_adjoint_eq *) @zero_transpose_eq using (auto 100 with wf_db) : M_db_light.\n\n(* I don't like always doing restore_dims first, but otherwise sometimes leaves \n   unsolvable WF_GenMatrix goals. *)\nLtac Msimpl_light := try restore_dims; autorewrite with M_db_light.\n\nHint Rewrite (* @GMmult_adjoint @GMplus_adjoint @kron_adjoint *) @kron_mixed_product\n     (* @adjoint_involutive *)  using (auto 100 with wf_db) : M_db.\n\nLtac Msimpl := try restore_dims; autorewrite with M_db_light M_db.\n\n(** Distribute addition to the outside of matrix expressions. *)\n\nLtac distribute_plus :=\n  repeat match goal with \n  | |- context [?a × (?b .+ ?c)] => rewrite (GMmult_plus_distr_l _ _ _ a b c)\n  | |- context [(?a .+ ?b) × ?c] => rewrite (GMmult_plus_distr_r _ _ _ a b c)\n  | |- context [?a ⊗ (?b .+ ?c)] => rewrite (kron_plus_distr_l _ _ _ _ a b c)\n  | |- context [(?a .+ ?b) ⊗ ?c] => rewrite (kron_plus_distr_r _ _ _ _ a b c)\n  end.\n\n(** Distribute scaling to the outside of matrix expressions *)\n\nLtac distribute_scale := \n  repeat\n   match goal with\n   | |- context [ (?c .* ?A) × ?B   ] => rewrite (Mscale_mult_dist_l _ _ _ c A B)\n   | |- context [ ?A × (?c .* ?B)   ] => rewrite (Mscale_mult_dist_r _ _ _ c A B)\n   | |- context [ (?c .* ?A) ⊗ ?B   ] => rewrite (Mscale_kron_dist_l _ _ _ _ c A B)\n   | |- context [ ?A ⊗ (?c .* ?B)   ] => rewrite (Mscale_kron_dist_r _ _ _ _ c A B)\n   | |- context [ ?c .* (?c' .* ?A) ] => rewrite (Mscale_assoc _ _ c c' A)\n   end.\n\n\n(*\nLtac distribute_adjoint :=\n  repeat match goal with\n  | |- context [(?c .* ?A)†] => rewrite (Mscale_adj _ _ c A)\n  | |- context [(?A .+ ?B)†] => rewrite (GMplus_adjoint _ _ A B)\n  | |- context [(?A × ?B)†] => rewrite (GMmult_adjoint A B)\n  | |- context [(?A ⊗ ?B)†] => rewrite (kron_adjoint A B)\n  end.\n*)\n\n(** Tactics for solving computational matrix equalities **)\n\n\n(* Construct matrices full of evars *)\nLtac mk_evar t T := match goal with _ => evar (t : T) end.\n\nLtac evar_list n := \n  match n with \n  | O => constr:(@nil C)\n  | S ?n' => let e := fresh \"e\" in\n            let none := mk_evar e C in \n            let ls := evar_list n' in \n            constr:(e :: ls)\n            \n  end.\n\nLtac evar_list_2d m n := \n  match m with \n  | O => constr:(@nil (list C))\n  | S ?m' => let ls := evar_list n in \n            let ls2d := evar_list_2d m' n in  \n            constr:(ls :: ls2d)\n  end.\n\nLtac evar_matrix m n := let ls2d := (evar_list_2d m n) \n                        in constr:(list2D_to_genmatrix ls2d).   \n\n(* Tactic version of Nat.lt *)\nLtac tac_lt m n := \n  match n with \n  | S ?n' => match m with \n            | O => idtac\n            | S ?m' => tac_lt m' n'\n            end\n  end.\n\n(* Possible TODO: We could have the tactic below use restore_dims instead of \n   simplifying before rewriting. *)\n(* Reassociate matrices so that smallest dimensions are multiplied first:\nFor (m x n) × (n x o) × (o x p):\nIf m or o is the smallest, associate left\nIf n or p is the smallest, associate right\n(The actual time for left is (m * o * n) + (m * p * o) = mo(n+p) \n                      versus (n * p * o) + (m * p * n) = np(m+o) for right. \nWe find our heuristic to be pretty accurate, though.)\n*)\nLtac assoc_least := \n  repeat (simpl; match goal with\n  | [|- context[@GMmult ?m ?o ?p (@GMmult ?m ?n ?o ?A ?B) ?C]] => tac_lt p o; tac_lt p m; \n       let H := fresh \"H\" in \n       specialize (GMmult_assoc A B C) as H; simpl in H; rewrite H; clear H\n  | [|- context[@GMmult ?m ?o ?p (@GMmult ?m ?n ?o ?A ?B) ?C]] => tac_lt n o; tac_lt n m; \n       let H := fresh \"H\" in \n       specialize (GMmult_assoc  A B C) as H; simpl in H; rewrite H; clear H\n  | [|- context[@GMmult ?m ?n ?p ?A (@GMmult ?n ?o ?p ?B ?C)]] => tac_lt m n; tac_lt m p; \n       let H := fresh \"H\" in \n       specialize (GMmult_assoc A B C) as H; simpl in H; rewrite <- H; clear H\n  | [|- context[@GMmult ?m ?n ?p ?A (@GMmult ?n ?o ?p ?B ?C)]] => tac_lt o n; tac_lt o p; \n       let H := fresh \"H\" in \n       specialize (GMmult_assoc A B C) as H; simpl in H; rewrite <- H; clear H\n  end).\n\n\n(* Helper function for crunch_matrix *)\nLtac solve_out_of_bounds := \n  repeat match goal with \n  | [H : WF_GenMatrix ?M |- context[?M ?a ?b] ] => \n      rewrite (H a b) by (left; simpl; lia) \n  | [H : WF_GenMatrix ?M |- context[?M ?a ?b] ] => \n      rewrite (H a b) by (right; simpl; lia) \n  end;\n  autorewrite with C_db; auto.\n\n\nLemma divmod_eq : forall x y n z, \n  fst (Nat.divmod x y n z) = (n + fst (Nat.divmod x y 0 z))%nat.\nProof.\n  induction x.\n  + intros. simpl. lia.\n  + intros. simpl. \n    destruct z.\n    rewrite IHx.\n    rewrite IHx with (n:=1%nat).\n    lia.\n    rewrite IHx.\n    reflexivity.\nQed.\n\nLemma divmod_S : forall x y n z, \n  fst (Nat.divmod x y (S n) z) = (S n + fst (Nat.divmod x y 0 z))%nat.\nProof. intros. apply divmod_eq. Qed.\n\nLtac destruct_m_1' :=\n  match goal with\n  | [ |- context[match ?x with \n                 | 0%nat   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  | [ |- context[match fst (Nat.divmod ?x _ _ _) with \n                 | 0%nat   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  end.\n\nLemma divmod_0q0 : forall x q, fst (Nat.divmod x 0 q 0) = (x + q)%nat. \nProof.\n  induction x.\n  - intros. simpl. reflexivity.\n  - intros. simpl. rewrite IHx. lia.\nQed.\n\nLemma divmod_0 : forall x, fst (Nat.divmod x 0 0 0) = x. \nProof. intros. rewrite divmod_0q0. lia. Qed.\n\nLtac destruct_m_eq' := repeat \n  (progress (try destruct_m_1'; try rewrite divmod_0; try rewrite divmod_S; simpl)).\n\n(* Unify A × B with list (list (evars)) *)\n(* We convert the matrices back to functional representation for \n   unification. Simply comparing the matrices may be more efficient,\n   however. *)\n\nLtac crunch_matrix := \n                    match goal with \n                      | [|- ?G ] => idtac \"Crunching:\" G\n                      end;\n                      repeat match goal with\n                             | [ c : C |- _ ] => cbv [c]; clear c (* 'unfold' hangs *)\n                             end; \n                      simpl;\n                      unfold list2D_to_genmatrix;    \n                      autounfold with U_db;\n                      prep_genmatrix_equality;\n                      simpl;\n                      destruct_m_eq';\n                      simpl;\n                      dumb_lRa; (* basic rewrites only *) \n                      try reflexivity;\n                      try solve_out_of_bounds. \n\nLtac compound M := \n  match M with\n  | ?A × ?B  => idtac\n  | ?A .+ ?B => idtac \n  (* | ?A †     => compound A *)\n  end.\n\n(* Reduce inner matrices first *)\nLtac reduce_aux M := \n  match M with \n  | ?A .+ ?B     => compound A; reduce_aux A\n  | ?A .+ ?B     => compound B; reduce_aux B\n  | ?A × ?B      => compound A; reduce_aux A\n  | ?A × ?B      => compound B; reduce_aux B\n  | @GMmult ?m ?n ?o ?A ?B      => let M' := evar_matrix m o in\n                                 replace M with M';\n                                 [| crunch_matrix ] \n  | @GMplus ?m ?n ?A ?B         => let M' := evar_matrix m n in\n                                 replace M with M';\n                                 [| crunch_matrix ] \n  end.\n\nLtac reduce_matrix := match goal with \n                       | [ |- ?M = _] => reduce_aux M\n                       | [ |- _ = ?M] => reduce_aux M\n                       end;\n                       repeat match goal with \n                              | [ |- context[?c :: _ ]] => cbv [c]; clear c\n                              end.\n\n(* Reduces matrices anywhere they appear *)\nLtac reduce_matrices := assoc_least;\n                        match goal with \n                        | [ |- context[?M]] => reduce_aux M\n                        end;\n                        repeat match goal with \n                               | [ |- context[?c :: _ ]] => cbv [c]; clear c\n                               end.\n\n\nLtac solve_matrix := assoc_least;\n                     repeat reduce_matrix; try crunch_matrix;\n                     (* handle out-of-bounds *)\n                     unfold Nat.ltb; simpl; try rewrite andb_false_r; \n                     (* try to solve complex equalities *)\n                     ring.\n                     (* autorewrite with C_db; try ring. *)\n\n(** Gridify **)\n\n\n(** Gridify: Turns an matrix expression into a normal form with \n    plus on the outside, then tensor, then matrix multiplication.\n    Eg: ((..×..×..)⊗(..×..×..)⊗(..×..×..)) .+ ((..×..)⊗(..×..))\n*)\nLocal Open Scope nat_scope.\n\nLemma repad_lemma1_l : forall (a b d : nat),\n  a < b -> d = (b - a - 1) -> b = a + 1 + d.\nProof. intros. subst. lia. Qed. \n\nLemma repad_lemma1_r : forall (a b d : nat),\n  a < b -> d = (b - a - 1) -> b = d + 1 + a.\nProof. intros. subst. lia. Qed.\n\nLemma repad_lemma2 : forall (a b d : nat),\n  a <= b -> d = (b - a) -> b = a + d.\nProof. intros. subst. lia. Qed.\n\nLemma le_ex_diff_l : forall a b, a <= b -> exists d, b = d + a. \nProof. intros. exists (b - a). lia. Qed.\n\nLemma le_ex_diff_r : forall a b, a <= b -> exists d, b = a + d. \nProof. intros. exists (b - a). lia. Qed.  \n\nLemma lt_ex_diff_l : forall a b, a < b -> exists d, b = d + 1 + a. \nProof. intros. exists (b - a - 1). lia. Qed.\n\nLemma lt_ex_diff_r : forall a b, a < b -> exists d, b = a + 1 + d. \nProof. intros. exists (b - a - 1). lia. Qed.\n\n(* Remove _ < _ from hyps, remove _ - _  from goal *)\nLtac remember_differences :=\n  repeat match goal with\n  | H : ?a < ?b |- context[?b - ?a - 1] => \n    let d := fresh \"d\" in\n    let R := fresh \"R\" in\n    remember (b - a - 1) as d eqn:R ;\n    apply (repad_lemma1_l a b d) in H; trivial;\n    clear R;\n    try rewrite H in *;\n    try clear b H\n  | H:?a <= ?b  |- context [ ?b - ?a ] =>\n    let d := fresh \"d\" in\n    let R := fresh \"R\" in\n    remember (b - a) as d eqn:R ;\n    apply (repad_lemma2 a b d) in H; trivial;\n    clear R;\n    try rewrite H in *;\n    try clear b H\n  end.\n\n(* gets the exponents of the dimensions of the given matrix expression *)\n(* assumes all matrices are square *)\nLtac get_dimensions M :=\n  match M with\n  | ?A ⊗ ?B  => let a := get_dimensions A in\n               let b := get_dimensions B in\n               constr:(a + b)\n  | ?A .+ ?B => get_dimensions A\n  | _        => match type of M with\n               | GenMatrix 2 2 => constr:(1)\n               | GenMatrix 4 4 => constr:(2)\n               | GenMatrix (2^?a) (2^?a) => constr:(a)\n(*             | GenMatrix ?a ?b => idtac \"bad dims\";\n                                idtac M;\n                                constr:(a) *)\n               end\n  end.\n\n(* not necessary in this instance - produced hypothesis is H1 *)\n(* This is probably fragile and should be rewritten *)\n(*\nLtac hypothesize_dims :=\n  match goal with\n  | |- ?A × ?B = _ => let a := get_dimensions A in\n                    let b := get_dimensions B in\n                    assert(a = b) by lia\n  | |- _ = ?A × ?B => let a := get_dimensions A in\n                    let b := get_dimensions B in\n                    assert(a = b) by lia\n  end.\n*)\n\n(* Hopefully always grabs the outermost product. *)\nLtac hypothesize_dims :=\n  match goal with\n  | |- context[?A × ?B] => let a := get_dimensions A in\n                         let b := get_dimensions B in\n                         assert(a = b) by lia\n  end.\n\n(* Unifies an equation of the form `a + 1 + b + 1 + c = a' + 1 + b' + 1 + c'`\n   (exact symmetry isn't required) by filling in the holes *) \nLtac fill_differences :=\n  repeat match goal with \n  | R : _ < _ |- _           => let d := fresh \"d\" in\n                              destruct (lt_ex_diff_r _ _ R);\n                              clear R; subst\n  | H : _ = _ |- _           => rewrite <- Nat.add_assoc in H\n  | H : ?a + _ = ?a + _ |- _ => apply Nat.add_cancel_l in H; subst\n  | H : ?a + _ = ?b + _ |- _ => destruct (lt_eq_lt_dec a b) as [[?|?]|?]; subst\n  end; try lia.\n\nLtac repad := \n  (* remove boolean comparisons *)\n  bdestruct_all; Msimpl_light; try reflexivity;\n  (* remove minus signs *) \n  remember_differences;\n  (* put dimensions in hypothesis [will sometimes exist] *)\n  try hypothesize_dims; clear_dups;\n  (* where a < b, replace b with a + 1 + fresh *)\n  fill_differences.\n\nLtac gridify :=\n  (* remove boolean comparisons *)\n  bdestruct_all; Msimpl_light; try reflexivity;\n  (* remove minus signs *) \n  remember_differences;\n  (* put dimensions in hypothesis [will sometimes exist] *)\n  try hypothesize_dims; clear_dups;\n  (* where a < b, replace b with a + 1 + fresh *)\n  fill_differences;\n  (* distribute *)  \n  restore_dims; distribute_plus;\n  repeat rewrite Nat.pow_add_r;\n  repeat rewrite <- id_kron; simpl;\n  repeat rewrite Nat.mul_assoc;\n  restore_dims; repeat rewrite <- kron_assoc by auto_wf;\n  restore_dims; repeat rewrite kron_mixed_product;\n  (* simplify *)\n  Msimpl_light.\n\n\n(** Tactics to show implicit arguments *)\n\n\nDefinition Gkron' := @Gkron.      \nLemma kron_shadow : @Gkron = Gkron'. Proof. reflexivity. Qed.\n\nDefinition GMmult' := @GMmult.\nLemma GMmult_shadow : @GMmult = GMmult'. Proof. reflexivity. Qed.\n\nLtac show_dimensions := try rewrite kron_shadow in *; \n                        try rewrite GMmult_shadow in *.\nLtac hide_dimensions := try rewrite <- kron_shadow in *; \n                        try rewrite <- GMmult_shadow in *.\n\n\n\n\n\n\nEnd LinAlgOverCommRing.\n\n\n(* TODO: add more of these *)\n\n\n\n\n\nArguments WF_GenMatrix {F R0 m n}.\n\n\n\nArguments Zero {F R0 m n}.\nArguments I {F R0 R1 R2 R3 n}.\n\n\nArguments trace {F R0 n}.\nArguments scale {F R0 R1 R2 R3 m n}.\nArguments GMplus {F R0 m n}.\nArguments GMopp {F R0 R1 R2 R3 m n}.\nArguments GMminus {F R0 R1 R2 R3 m n}.\nArguments GMmult {F R0 R1 R2 R3 m n o}.\nArguments Gkron {F R0 R1 R2 R3 m n o p}.\nArguments transpose {F m n}.\nArguments GMmult_n {F R0 R1 R2 R3 m}.\nArguments WF_GenMatrix {F R0 m n}.\n\n\n\n\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/GenMatrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.783296442521674}}
{"text": "(******************************************************************************)\n(** * Operations on sets (unary relations) *)\n(******************************************************************************)\n\nRequire Import HahnBase.\nRequire Import Program.Basics List Arith micromega.Lia Relations Setoid Morphisms.\n\nSet Implicit Arguments.\n\nLocal Open Scope program_scope.\n\n(** Definitions of set operations *)\n(******************************************************************************)\n\nSection SetDefs.\n\n  Variables A B : Type.\n  Implicit Type f : A -> B.\n  Implicit Type s : A -> Prop.\n  Implicit Type ss : A -> B -> Prop.\n  Implicit Type d : B -> Prop.\n\n  Definition set_empty       := fun x : A => False.\n  Definition set_full        := fun x : A => True.\n  Definition set_compl s     := fun x => ~ (s x).\n  Definition set_union s s'  := fun x => s x \\/ s' x.\n  Definition set_inter s s'  := fun x => s x /\\ s' x.\n  Definition set_minus s s'  := fun x => s x /\\ ~ (s' x).\n  Definition set_subset s s' := forall x, s x -> s' x.\n  Definition set_equiv s s'  := set_subset s s' /\\ set_subset s' s.\n  Definition set_finite s    := exists findom, forall x (IN: s x), In x findom.\n  Definition set_coinfinite s:= ~ set_finite (set_compl s).\n  Definition set_collect f s := fun x => exists y, s y /\\ f y = x.\n  Definition set_map f d     := fun x => d (f x).\n  Definition set_bunion s ss := fun x => exists y, s y /\\ ss y x.\n  Definition set_disjoint s s':= forall x (IN: s x) (IN': s' x), False.\n\nEnd SetDefs.\n\nArguments set_empty {A}.\nArguments set_full {A}.\nArguments set_subset {A}.\nArguments set_equiv {A}.\n\nNotation \"P ∪₁ Q\" := (set_union P Q) (at level 50, left associativity).\nNotation \"P ∩₁ Q\" := (set_inter P Q) (at level 40, left associativity).\nNotation \"P \\₁ Q\" := (set_minus P Q) (at level 46).\nNotation \"∅\"     := (@set_empty _).\nNotation \"a ⊆₁ b\" := (set_subset a b) (at level 60).\nNotation \"a ≡₁ b\" := (set_equiv a b)  (at level 60).\nNotation \"f ↑₁ P\" := (set_collect f P) (at level 30).\nNotation \"f ↓₁ Q\" := (set_map f Q) (at level 30).\n\nNotation \"⋃₁ x ∈ s , a\" := (set_bunion s (fun x => a))\n  (at level 200, x ident, right associativity,\n   format \"'[' ⋃₁ '/ ' x  ∈  s ,  '/ ' a ']'\").\nNotation \"'⋃₁' x , a\" := (set_bunion (fun _ => True) (fun x => a))\n  (at level 200, x ident, right associativity,\n   format \"'[' ⋃₁ '/ ' x ,  '/ ' a ']'\").\nNotation \"'⋃₁' x < n , a\" := (set_bunion (fun t => t < n) (fun x => a))\n  (at level 200, x ident, right associativity,\n   format \"'[' ⋃₁ '/ ' x  <  n ,  '/ ' a ']'\").\nNotation \"'⋃₁' x <= n , a\" := (set_bunion (fun t => t <= n) (fun x => a))\n  (at level 200, x ident, right associativity,\n   format \"'[' ⋃₁ '/ ' x  <=  n ,  '/ ' a ']'\").\n\n(*\nNotation \"P ∪ Q\" := (set_union P Q) (at level 50, left associativity) : function_scope.\nNotation \"P ∩ Q\" := (set_inter P Q) (at level 40, left associativity) : function_scope.\nNotation \"P \\ Q\" := (set_minus P Q) (at level 46) : function_scope.\nNotation \"∅\"     := (@set_empty _) : function_scope.\nNotation \"a ⊆ b\" := (set_subset a b) (at level 60) : function_scope.\nNotation \"a ≡ b\" := (set_equiv a b)  (at level 60) : function_scope. *)\n\n\nGlobal Hint Unfold set_empty set_full set_compl set_union set_inter : unfolderDb.\nGlobal Hint Unfold set_minus set_subset set_equiv set_coinfinite set_finite : unfolderDb.\nGlobal Hint Unfold set_collect set_map set_bunion set_disjoint : unfolderDb.\n\n(** Basic properties of set operations *)\n(******************************************************************************)\n\nSection SetProperties.\n  Local Ltac u :=\n    repeat autounfold with unfolderDb in *;\n    ins; try solve [tauto | firstorder | split; ins; tauto].\n\n  Variables A B C : Type.\n  Implicit Type a : A.\n  Implicit Type f : A -> B.\n  Implicit Type s : A -> Prop.\n  Implicit Type d : B -> Prop.\n  Implicit Type ss : A -> B -> Prop.\n\n  (** Properties of set complement. *)\n\n  Lemma set_compl_empty : set_compl ∅ ≡₁ @set_full A.\n  Proof. u. Qed.\n\n  Lemma set_compl_full : set_compl (@set_full A) ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_compl_compl s : set_compl (set_compl s) ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_compl_union s s' :\n    set_compl (s ∪₁ s') ≡₁ set_compl s ∩₁ set_compl s'.\n  Proof. u. Qed.\n\n  Lemma set_compl_inter s s' :\n    set_compl (s ∩₁ s') ≡₁ set_compl s ∪₁ set_compl s'.\n  Proof. u. Qed.\n\n  Lemma set_compl_minus s s' :\n    set_compl (s \\₁ s') ≡₁ s' ∪₁ set_compl s.\n  Proof. u. Qed.\n\n  (** Properties of set union. *)\n\n  Lemma set_unionA s s' s'' : (s ∪₁ s') ∪₁ s'' ≡₁ s ∪₁ (s' ∪₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_unionC s s' : s ∪₁ s' ≡₁ s' ∪₁ s.\n  Proof. u. Qed.\n\n  Lemma set_unionK s : s ∪₁ s ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_union_empty_l s : ∅ ∪₁ s ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_union_empty_r s : s ∪₁ ∅ ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_union_full_l s : set_full ∪₁ s ≡₁ set_full.\n  Proof. u. Qed.\n\n  Lemma set_union_full_r s : s ∪₁ set_full ≡₁ set_full.\n  Proof. u. Qed.\n\n  Lemma set_union_inter_l s s' s'' : (s ∩₁ s') ∪₁ s'' ≡₁ (s ∪₁ s'') ∩₁ (s' ∪₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_union_inter_r s s' s'' : s ∪₁ (s' ∩₁ s'') ≡₁ (s ∪₁ s') ∩₁ (s ∪₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_union_eq_empty s s' : s ∪₁ s' ≡₁ ∅ <-> s ≡₁ ∅ /\\ s' ≡₁ ∅.\n  Proof. u. Qed.\n\n  (** Properties of set intersection. *)\n\n  Lemma set_interA s s' s'' : (s ∩₁ s') ∩₁ s'' ≡₁ s ∩₁ (s' ∩₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_interC s s' : s ∩₁ s' ≡₁ s' ∩₁ s.\n  Proof. u. Qed.\n\n  Lemma set_interK s : s ∩₁ s ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_inter_empty_l s : ∅ ∩₁ s ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_inter_empty_r s : s ∩₁ ∅ ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_inter_full_l s : set_full ∩₁ s ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_inter_full_r s : s ∩₁ set_full ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_inter_union_l s s' s'' : (s ∪₁ s') ∩₁ s'' ≡₁ (s ∩₁ s'') ∪₁ (s' ∩₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_inter_union_r s s' s'' : s ∩₁ (s' ∪₁ s'') ≡₁ (s ∩₁ s') ∪₁ (s ∩₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_inter_minus_l s s' s'' : (s \\₁ s') ∩₁ s'' ≡₁ (s ∩₁ s'') \\₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_inter_minus_r s s' s'' : s ∩₁ (s' \\₁ s'') ≡₁ (s ∩₁ s') \\₁ s''.\n  Proof. u. Qed.\n\n  (** Properties of set minus. *)\n\n  Lemma set_minusE s s' : s \\₁ s' ≡₁ s ∩₁ set_compl s'.\n  Proof. u. Qed.\n\n  Lemma set_minusK s : s \\₁ s ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_minus_inter_l s s' s'' :\n    (s ∩₁ s') \\₁ s'' ≡₁ (s \\₁ s'') ∩₁ (s' \\₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_minus_inter_r s s' s'' :\n    s \\₁ (s' ∩₁ s'') ≡₁ (s \\₁ s') ∪₁ (s \\₁ s'').\n  Proof. u; split; ins; tauto. Qed.\n\n  Lemma set_minus_union_l s s' s'' :\n    (s ∪₁ s') \\₁ s'' ≡₁ (s \\₁ s'') ∪₁ (s' \\₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_minus_union_r s s' s'' :\n    s \\₁ (s' ∪₁ s'') ≡₁ (s \\₁ s') ∩₁ (s \\₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_minus_minus_l s s' s'' :\n    s \\₁ s' \\₁ s'' ≡₁ s \\₁ (s' ∪₁ s'').\n  Proof. u. Qed.\n\n  Lemma set_minus_minus_r s s' s'' :\n    s \\₁ (s' \\₁ s'') ≡₁ (s \\₁ s') ∪₁ (s ∩₁ s'').\n  Proof. u. Qed.\n\n  (** Properties of set inclusion. *)\n\n  Lemma set_subsetE s s' : s ⊆₁ s' <-> s \\₁ s' ≡₁ ∅.\n  Proof. u; intuition; apply NNPP; firstorder. Qed.\n\n  Lemma set_subset_eq (P : A -> Prop) a (H : P a): eq a ⊆₁ P.\n  Proof. by intros x H'; subst. Qed.\n\n  Lemma set_subset_refl : reflexive _ (@set_subset A).\n  Proof. u. Qed.\n\n  Lemma set_subset_trans : transitive _ (@set_subset A).\n  Proof. u. Qed.\n\n  Lemma set_subset_empty_l s : ∅ ⊆₁ s.\n  Proof. u. Qed.\n\n  Lemma set_subset_empty_r s : s ⊆₁ ∅ <-> s ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_subset_full_l s : set_full ⊆₁ s <-> s ≡₁ set_full.\n  Proof. u. Qed.\n\n  Lemma set_subset_full_r s : s ⊆₁ set_full.\n  Proof. u. Qed.\n\n  Lemma set_subset_union_l s s' s'' : s ∪₁ s' ⊆₁ s'' <-> s ⊆₁ s'' /\\ s' ⊆₁ s''.\n  Proof. u. Qed.\n\n  Lemma set_subset_union_r1 s s' : s ⊆₁ s ∪₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_subset_union_r2 s s' : s' ⊆₁ s ∪₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_subset_union_r s s' s'' : s ⊆₁ s' \\/ s ⊆₁ s'' -> s ⊆₁ s' ∪₁ s''.\n  Proof. u. Qed.\n\n  Lemma set_subset_inter_r s s' s'' : s ⊆₁ s' ∩₁ s'' <-> s ⊆₁ s' /\\ s ⊆₁ s''.\n  Proof. u. Qed.\n\n  Lemma set_subset_compl s s' (S1: s' ⊆₁ s) : set_compl s ⊆₁ set_compl s'.\n  Proof. u. Qed.\n\n  Lemma set_subset_inter s s' (S1: s ⊆₁ s') t t' (S2: t ⊆₁ t') : s ∩₁ t ⊆₁ s' ∩₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_subset_union s s' (S1: s ⊆₁ s') t t' (S2: t ⊆₁ t') : s ∪₁ t ⊆₁ s' ∪₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_subset_minus s s' (S1: s ⊆₁ s') t t' (S2: t' ⊆₁ t) : s \\₁ t ⊆₁ s' \\₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_subset_bunion_l s ss sb (H: forall x (COND: s x), ss x ⊆₁ sb) : (⋃₁x ∈ s, ss x) ⊆₁ sb.\n  Proof. u. Qed.\n\n  Lemma set_subset_bunion_r s ss sb a (H: s a) (H': sb ⊆₁ ss a) : sb ⊆₁ ⋃₁x ∈ s, ss x.\n  Proof. u. Qed.\n\n  Lemma set_subset_bunion s s' (S: s ⊆₁ s') ss ss' (SS: forall x (COND: s x), ss x ⊆₁ ss' x) :\n    (⋃₁x ∈ s, ss x) ⊆₁ ⋃₁x ∈ s, ss' x.\n  Proof. u. Qed.\n\n  Lemma set_subset_bunion_guard s s' (S: s ⊆₁ s') ss ss' (EQ: ss = ss') :\n    (⋃₁x ∈ s, ss x) ⊆₁ (⋃₁x ∈ s', ss' x).\n  Proof. subst; u. Qed.\n\n  Lemma set_subset_collect f s s' (S: s ⊆₁ s') : f ↑₁ s ⊆₁ f ↑₁ s'.\n  Proof. u. Qed.\n\n  (** Properties of set equivalence. *)\n\n  Lemma set_equivE s s' : s ≡₁ s' <-> s ⊆₁ s' /\\ s' ⊆₁ s.\n  Proof. u; firstorder. Qed.\n\n  Lemma set_equiv_refl : reflexive _ (@set_equiv A).\n  Proof. u. Qed.\n\n  Lemma set_equiv_symm : symmetric _ (@set_equiv A).\n  Proof. u. Qed.\n\n  Lemma set_equiv_trans : transitive _ (@set_equiv A).\n  Proof. u. Qed.\n\n  Lemma set_equiv_compl s s' (S1: s ≡₁ s') : set_compl s ≡₁ set_compl s'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_inter s s' (S1: s ≡₁ s') t t' (S2: t ≡₁ t') : s ∩₁ t ≡₁ s' ∩₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_union s s' (S1: s ≡₁ s') t t' (S2: t ≡₁ t') : s ∪₁ t ≡₁ s' ∪₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_minus s s' (S1: s ≡₁ s') t t' (S2: t ≡₁ t') : s \\₁ t ≡₁ s' \\₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_bunion s s' (S: s ≡₁ s') ss ss' (SS: forall x (COND: s x), ss x ≡₁ ss' x) :\n    set_bunion s ss ≡₁ set_bunion s' ss'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_bunion_guard s s' (S: s ≡₁ s') ss ss' (EQ: ss = ss') : set_bunion s ss ≡₁ set_bunion s' ss'.\n  Proof. subst; u. Qed.\n\n  Lemma set_equiv_collect f s s' (S: s ≡₁ s') : f ↑₁ s ⊆₁ f ↑₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_subset s s' (S1: s ≡₁ s') t t' (S2: t ≡₁ t') : s ⊆₁ t <-> s' ⊆₁ t'.\n  Proof. u. Qed.\n\n  Lemma set_equiv_exp s s' (EQ: s ≡₁ s') : forall x, s x <-> s' x.\n  Proof. split; apply EQ. Qed.\n\n  (** Absorption properties. *)\n\n  Lemma set_union_absorb_l s s' (SUB: s ⊆₁ s') : s ∪₁ s' ≡₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_union_absorb_r s s' (SUB: s ⊆₁ s') : s' ∪₁ s ≡₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_inter_absorb_l s s' (SUB: s ⊆₁ s') : s' ∩₁ s ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_inter_absorb_r s s' (SUB: s ⊆₁ s') : s ∩₁ s' ≡₁ s.\n  Proof. u. Qed.\n\n  Lemma set_minus_absorb_l s s' (SUB: s ⊆₁ s') : s \\₁ s' ≡₁ ∅.\n  Proof. u. Qed.\n\n  (** Singleton sets *)\n\n  Lemma set_subset_single_l a s : eq a ⊆₁ s <-> s a.\n  Proof. u; intuition; desf. Qed.\n\n  Lemma set_subset_single_r a s :\n    s ⊆₁ eq a <-> s ≡₁ eq a \\/ s ≡₁ ∅.\n  Proof.\n    u; intuition; firstorder.\n    destruct (classic (exists b, s b)) as [M|M]; desf.\n       left; split; ins; desf; eauto.\n       specialize (H _ M); desf.\n    right; split; ins; eauto.\n  Qed.\n\n  Lemma set_subset_single_single a b :\n    eq a ⊆₁ eq b <-> a = b.\n  Proof. u; intuition; desf; eauto using eq_sym. Qed.\n\n  Lemma set_equiv_single_single a b :\n    eq a ≡₁ eq b <-> a = b.\n  Proof. u; intuition; desf; apply H; ins. Qed.\n\n  Lemma set_nonemptyE s : ~ s ≡₁ ∅ <-> exists x, s x.\n  Proof.\n    u; intuition; firstorder.\n    apply NNPP; intro; apply H0; ins; eauto.\n  Qed.\n\n  (** Big union *)\n\n  Lemma set_bunion_empty ss : set_bunion ∅ ss ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_bunion_eq a ss : set_bunion (eq a) ss ≡₁ ss a.\n  Proof. u; splits; ins; desf; eauto. Qed.\n\n  Lemma set_bunion_union_l s s' ss :\n    set_bunion (s ∪₁ s') ss ≡₁ set_bunion s ss ∪₁ set_bunion s' ss.\n  Proof. u. Qed.\n\n  Lemma set_bunion_union_r s ss ss' :\n    set_bunion s (fun x => ss x ∪₁ ss' x) ≡₁ set_bunion s ss ∪₁ set_bunion s ss'.\n  Proof. u. Qed.\n\n  Lemma set_bunion_bunion_l s ss (ss' : B -> C -> Prop) :\n    (⋃₁x ∈ (⋃₁y ∈ s, ss y), ss' x) ≡₁ ⋃₁y ∈ s, ⋃₁x ∈ ss y, ss' x.\n  Proof. u. Qed.\n\n  Lemma set_bunion_inter_compat_l s sb ss :\n    set_bunion s (fun x => sb ∩₁ ss x) ≡₁ sb ∩₁ set_bunion s ss.\n  Proof. u; split; ins; desf; eauto 8. Qed.\n\n  Lemma set_bunion_inter_compat_r s sb ss :\n    set_bunion s (fun x => ss x ∩₁ sb) ≡₁ set_bunion s ss ∩₁ sb.\n  Proof. u; split; ins; desf; eauto 8. Qed.\n\n  Lemma set_bunion_minus_compat_r s sb ss :\n    set_bunion s (fun x => ss x \\₁ sb) ≡₁ set_bunion s ss \\₁ sb.\n  Proof. u; split; ins; desf; eauto 8. Qed.\n\n  (** Collect *)\n\n  Lemma set_collect_compose (f : A -> B) (g : B -> C) s :\n    (g ∘ f) ↑₁ s ≡₁ g ↑₁ (f ↑₁ s) .\n  Proof.\n    unfold compose.\n    repeat autounfold with unfolderDb.\n    ins; splits; ins; splits; desf; eauto.\n  Qed.\n\n  Lemma set_collectE f s : f ↑₁ s ≡₁ set_bunion s (fun x => eq (f x)).\n  Proof. u. Qed.\n\n  Lemma set_collect_empty f : f ↑₁ ∅ ≡₁ ∅.\n  Proof. u. Qed.\n\n   Lemma set_collect_eq f a : f ↑₁ (eq a) ≡₁ eq (f a).\n  Proof. u; splits; ins; desf; eauto. Qed.\n\n  Lemma set_collect_union f s s' :\n    f ↑₁ (s ∪₁ s') ≡₁ f ↑₁ s ∪₁ f ↑₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_collect_inter f s s' :\n    f ↑₁ (s ∩₁ s') ⊆₁ f ↑₁ s ∩₁ f ↑₁ s'.\n  Proof. u. Qed.\n\n  Lemma set_collect_bunion f (s : C -> Prop) (ss : C -> A -> Prop) :\n    f ↑₁ (⋃₁x ∈ s, ss x) ≡₁ ⋃₁x ∈ s, f ↑₁ (ss x).\n  Proof. u. Qed.\n\n  (** Map *)\n\n  Lemma set_map_compose (f : A -> B) (g : B -> C) (d : C -> Prop) :\n    (g ∘ f) ↓₁ d ≡₁ f ↓₁ (g ↓₁ d) .\n  Proof.\n    autounfold with unfolderDb.\n    ins; splits; ins; splits; desf; eauto.\n  Qed.\n\n  Lemma set_mapE f d : f ↓₁ d ≡₁ set_bunion d (fun x y => x = f y).\n  Proof. split; u. desc. by subst y. Qed.\n\n  Lemma set_map_empty f : f ↓₁ ∅ ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_map_full f : f ↓₁ set_full ≡₁ set_full.\n  Proof. u. Qed.\n\n  Lemma set_map_union f d d' :\n    f ↓₁ (d ∪₁ d') ≡₁ f ↓₁ d ∪₁ f ↓₁ d'.\n  Proof. u. Qed.\n\n  Lemma set_map_inter f d d' :\n    f ↓₁ (d ∩₁ d') ≡₁ f ↓₁ d ∩₁ f ↓₁ d'.\n  Proof. u. Qed.\n\n  Lemma set_map_bunion f (d : C -> Prop) (dd : C -> B -> Prop) :\n    f ↓₁ (⋃₁x ∈ d, dd x) ≡₁ ⋃₁x ∈ d, f ↓₁ (dd x).\n  Proof. u. Qed.\n\n  (** Collect and Map *)\n\n  Lemma set_collect_map f d :\n    f ↑₁ (f ↓₁ d) ⊆₁ d.\n  Proof. u. desc. by subst x. Qed.\n\n  Lemma set_map_collect f s :\n    s ⊆₁ f ↓₁ (f ↑₁ s).\n  Proof. u. Qed.\n\n  (** Finite sets *)\n\n  Lemma set_finite_empty : set_finite (A:=A) ∅.\n  Proof. exists nil; ins. Qed.\n\n  Lemma set_finite_eq a : set_finite (eq a).\n  Proof. exists (a :: nil); ins; desf; eauto. Qed.\n\n  Lemma set_finite_le n : set_finite (fun t => t <= n).\n  Proof. exists (List.seq 0 (S n)); intros; apply in_seq; ins; auto with arith. Qed.\n\n  Lemma set_finite_lt n : set_finite (fun t => t < n).\n  Proof. exists (List.seq 0 n); intros; apply in_seq; ins; auto with arith. Qed.\n\n  Lemma set_finite_union s s' : set_finite (s ∪₁ s') <-> set_finite s /\\ set_finite s'.\n  Proof.\n    u; split; splits; ins; desf; eauto.\n    eexists (_ ++ _); ins; desf; eauto using in_or_app.\n  Qed.\n\n  Lemma set_finite_unionI s (F: set_finite s) s' (F': set_finite s') : set_finite (s ∪₁ s').\n  Proof.\n    u; desf; eauto; eexists (_ ++ _); ins; desf; eauto using in_or_app.\n  Qed.\n\n  Lemma set_finite_bunion s (F: set_finite s) ss :\n    set_finite (set_bunion s ss) <-> forall a (COND: s a), set_finite (ss a).\n  Proof.\n    u; split; ins; desf; eauto.\n    revert s F H; induction findom; ins.\n      by exists nil; ins; desf; eauto.\n    specialize (IHfindom (fun x => s x /\\ x <> a)); ins.\n    specialize_full IHfindom; ins; desf; eauto.\n      by apply F in IN; desf; eauto.\n    tertium_non_datur (s a) as [X|X].\n      eapply H in X; desf.\n      eexists (findom0 ++ findom1); ins; desf.\n      tertium_non_datur (y = a); desf; eauto 8 using in_or_app.\n    eexists findom0; ins; desf; apply IHfindom; eexists; splits; eauto; congruence.\n  Qed.\n\n  (** Set disjointness *)\n\n  Lemma set_disjointE s s' : set_disjoint s s' <-> s ∩₁ s' ≡₁ ∅.\n  Proof. u. Qed.\n\n  Lemma set_disjointC s s' : set_disjoint s s' <-> set_disjoint s' s.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_empty_l s : set_disjoint ∅ s.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_empty_r s : set_disjoint s ∅.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_eq_l a s : set_disjoint (eq a) s <-> ~ s a.\n  Proof. u; split; ins; desf; eauto. Qed.\n\n  Lemma set_disjoint_eq_r a s : set_disjoint s (eq a) <-> ~ s a.\n  Proof. u; split; ins; desf; eauto. Qed.\n\n  Lemma set_disjoint_eq_eq a b : set_disjoint (eq a) (eq b) <-> a <> b.\n  Proof. u; split; ins; desf; eauto. Qed.\n\n  Lemma set_disjoint_union_l s s' s'' :\n    set_disjoint (s ∪₁ s') s'' <-> set_disjoint s s'' /\\ set_disjoint s' s''.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_union_r s s' s'' :\n    set_disjoint s (s' ∪₁ s'') <-> set_disjoint s s' /\\ set_disjoint s s''.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_bunion_l s ss sr :\n    set_disjoint (set_bunion s ss) sr <-> forall x (IN: s x), set_disjoint (ss x) sr.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_bunion_r s ss sr :\n    set_disjoint sr (set_bunion s ss) <-> forall x (IN: s x), set_disjoint sr (ss x).\n  Proof. u. Qed.\n\n  Lemma set_disjoint_subset_l s s' (SUB: s ⊆₁ s') s'' :\n    set_disjoint s' s'' -> set_disjoint s s''.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_subset_r s s' (SUB: s ⊆₁ s') s'' :\n    set_disjoint s'' s' -> set_disjoint s'' s.\n  Proof. u. Qed.\n\n  Lemma set_disjoint_subset s s' (SUB: s ⊆₁ s') sr sr' (SUB': sr ⊆₁ sr') :\n    set_disjoint s' sr' -> set_disjoint s sr.\n  Proof. u. Qed.\n\n  (** Miscellaneous *)\n\n  Lemma set_le n : (fun i => i <= n) ≡₁ (fun i => i < n) ∪₁ (eq n).\n  Proof.\n    u; intuition; lia.\n  Qed.\n\n  Lemma set_lt n : (fun i => i < n) ≡₁ (fun i => i <= n) \\₁ (eq n).\n  Proof.\n    u; intuition; lia.\n  Qed.\n\nEnd SetProperties.\n\n(** Lemmas about finite subsets of [nat] *)\n\nLemma set_finite_nat_bounded s (F : set_finite s) :\n  (exists bound, forall m (M: s m), m < bound).\nProof.\n  red in F; desc.\n  exists (S (fold_right Nat.max 0 findom)); ins.\n  apply Nat.lt_succ_r.\n  apply F, in_split in M; desf.\n  clear; induction l1; ins; eauto 2 with arith.\nQed.\n\nLemma set_finite_coinfinite_nat (s: nat -> Prop) :\n  set_finite s -> set_coinfinite s.\nProof.\n  assert (LT: forall l x, In x l -> x <= fold_right Init.Nat.add 0 l).\n    induction l; ins; desf; try apply IHl in H; lia.\n  repeat autounfold with unfolderDb; red; ins; desf.\n  tertium_non_datur (s (S (fold_right plus 0 findom + fold_right plus 0 findom0))) as [X|X];\n   [apply H in X | apply H0 in X]; apply LT in X; lia.\nQed.\n\nLemma set_coinfinite_fresh (s: nat -> Prop) (COINF: set_coinfinite s) :\n  exists b, ~ s b /\\ set_coinfinite (s ∪₁ eq b).\nProof.\n  repeat autounfold with unfolderDb in *.\n  tertium_non_datur (forall b, s b).\n    by destruct COINF; exists nil; ins; desf.\n  exists n; splits; red; ins; desf.\n  apply COINF; exists (n :: findom); ins; desf; eauto.\n  specialize (H0 x); tauto.\nQed.\n\nLemma set_bunion_lt_S A n (P : nat -> A -> Prop) :\n  (⋃₁i < S n, P i) ≡₁ (⋃₁i < n, P i) ∪₁ P n.\nProof.\n  unfold set_bunion, set_equiv, set_subset, set_union;\n    split; ins; desf; eauto.\n  rewrite Nat.lt_succ_r, Nat.le_lteq in *; desf; eauto.\nQed.\n\n(** Add rewriting support. *)\n\nAdd Parametric Relation A : (A -> Prop) (set_subset (A:=A))\n  reflexivity proved by (set_subset_refl (A:=A))\n  transitivity proved by (set_subset_trans (A:=A))\n  as set_subset_rel.\n\nAdd Parametric Relation A : (A -> Prop) (set_equiv (A:=A))\n  reflexivity proved by (set_equiv_refl (A:=A))\n  symmetry proved by (set_equiv_symm (A:=A))\n  transitivity proved by (set_equiv_trans (A:=A))\n  as set_equiv_rel.\n\nInstance set_compl_Proper A : Proper (_ --> _) _ := set_subset_compl (A:=A).\nInstance set_union_Proper A : Proper (_ ==> _ ==> _) _ := set_subset_union (A:=A).\nInstance set_inter_Proper A : Proper (_ ==> _ ==> _) _ := set_subset_inter (A:=A).\nInstance set_minus_Proper A : Proper (_ ++> _ --> _) _ := set_subset_minus (A:=A).\nInstance set_bunion_Proper A B : Proper (_ ==> _ ==> _) _ := set_subset_bunion_guard (A:=A) (B:=B).\n\nInstance set_compl_Propere A : Proper (_ ==> _) _ := set_equiv_compl (A:=A).\nInstance set_union_Propere A : Proper (_ ==> _ ==> _) _ := set_equiv_union (A:=A).\nInstance set_inter_Propere A : Proper (_ ==> _ ==> _) _ := set_equiv_inter (A:=A).\nInstance set_minus_Propere A : Proper (_ ==> _ ==> _) _ := set_equiv_minus (A:=A).\nInstance set_bunion_Propere A B : Proper (_ ==> _ ==> _) _ := set_equiv_bunion_guard (A:=A) (B:=B).\nInstance set_subset_Proper A : Proper (_ ==> _ ==> _) _ := set_equiv_subset (A:=A).\n\nAdd Parametric Morphism A : (@set_finite A) with signature\n  set_subset --> Basics.impl as set_finite_mori.\nProof. red; autounfold with unfolderDb; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_finite A) with signature\n  set_equiv ==> iff as set_finite_more.\nProof. red; autounfold with unfolderDb; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_coinfinite A) with signature\n  set_subset --> Basics.impl as set_coinfinite_mori.\nProof. unfold set_coinfinite; ins; rewrite H; ins. Qed.\n\nAdd Parametric Morphism A : (@set_coinfinite A) with signature\n  set_equiv ==> iff as set_coinfinite_more.\nProof. unfold set_coinfinite; ins; rewrite H; ins. Qed.\n\nAdd Parametric Morphism A B : (@set_collect A B) with signature\n  eq ==> set_subset ==> set_subset as set_collect_mori.\nProof. autounfold with unfolderDb; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A B : (@set_collect A B) with signature\n  eq ==> set_equiv ==> set_equiv as set_collect_more.\nProof. repeat autounfold with unfolderDb; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A B : (@set_map A B) with signature\n  eq ==> set_subset ==> set_subset as set_map_mori.\nProof. repeat autounfold with unfolderDb; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A B : (@set_map A B) with signature\n  eq ==> set_equiv ==> set_equiv as set_map_more.\nProof. repeat autounfold with unfolderDb; splits; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_disjoint A) with signature\n  set_subset --> set_subset --> Basics.impl as set_disjoint_mori.\nProof. red; autounfold with unfolderDb; ins; desf; eauto. Qed.\n\nAdd Parametric Morphism A : (@set_disjoint A) with signature\n  set_equiv ==> set_equiv ==> iff as set_disjoint_more.\nProof. red; autounfold with unfolderDb; splits; ins; desf; eauto. Qed.\n\n(** Add support for automation. *)\n\nLemma set_subset_refl2 A (x: A -> Prop) :  x ⊆₁ x.\nProof. reflexivity. Qed.\n\nLemma set_equiv_refl2 A (x: A -> Prop) :  x ≡₁ x.\nProof. reflexivity. Qed.\n\nGlobal Hint Immediate set_subset_refl2 : core hahn.\nGlobal Hint Resolve set_equiv_refl2 : core hahn.\n\nHint Rewrite set_compl_empty set_compl_full set_compl_compl : hahn.\nHint Rewrite set_compl_union set_compl_inter set_compl_minus : hahn.\nHint Rewrite set_union_empty_l set_union_empty_r set_union_full_l set_union_full_r : hahn.\nHint Rewrite set_inter_empty_l set_inter_empty_r set_inter_full_l set_inter_full_r : hahn.\nHint Rewrite set_bunion_empty set_bunion_eq set_bunion_bunion_l : hahn.\nHint Rewrite set_collect_empty set_collect_eq set_collect_bunion : hahn.\nHint Rewrite set_finite_union : hahn.\nHint Rewrite set_disjoint_eq_eq set_disjoint_eq_l set_disjoint_eq_r : hahn.\n\nHint Rewrite set_inter_union_l set_inter_union_r set_union_eq_empty : hahn_full.\nHint Rewrite set_minus_union_l set_minus_union_r set_union_eq_empty : hahn_full.\nHint Rewrite set_subset_union_l set_subset_inter_r : hahn_full.\nHint Rewrite set_minusK set_interK set_unionK : hahn_full.\nHint Rewrite set_bunion_inter_compat_l set_bunion_inter_compat_r : hahn_full.\nHint Rewrite set_bunion_minus_compat_r : hahn_full.\nHint Rewrite set_bunion_union_l set_bunion_union_r : hahn_full.\nHint Rewrite set_collect_union : hahn_full.\nHint Rewrite set_disjoint_union_l set_disjoint_union_r : hahn_full.\nHint Rewrite set_disjoint_bunion_l set_disjoint_bunion_r : hahn_full.\n\nGlobal Hint Immediate set_subset_empty_l set_subset_full_r : hahn.\nGlobal Hint Immediate set_finite_empty set_finite_eq set_finite_le set_finite_lt : hahn.\nGlobal Hint Immediate set_disjoint_empty_l set_disjoint_empty_r : hahn.\n\nGlobal Hint Resolve set_subset_union_r : hahn.\nGlobal Hint Resolve set_finite_unionI set_finite_bunion : hahn.\n", "meta": {"author": "vafeiadis", "repo": "hahn", "sha": "d486f449a51c14b8e1093f14d096cc99833974d7", "save_path": "github-repos/coq/vafeiadis-hahn", "path": "github-repos/coq/vafeiadis-hahn/hahn-d486f449a51c14b8e1093f14d096cc99833974d7/HahnSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7832836197024017}}
{"text": "Require Import Bool.\nRequire Import Arith.\nRequire Import Peano.\n\n\nInductive tp : Set := \n| Nat\n| Bool\n| Prod : tp -> tp -> tp.\n\nInductive exp : tp -> Set :=\n| num : nat -> exp Nat\n| add : exp Nat -> exp Nat -> exp Nat\n| bval : bool -> exp Bool\n| and : exp Bool -> exp Bool -> exp Bool\n| isz : exp Nat -> exp Bool\n| pair : forall t1 t2, exp t1 -> exp t2 -> exp (Prod t1 t2).\n\nNotation \" '#' n \" := (num n) (at level 45) : exp_scope.\nNotation \" a1 + a2 \" := (add a1 a2) (at level 50, left associativity) : exp_scope.\nNotation \" b1 & b2 \" := (and b1 b2) (at level 40, left associativity) : exp_scope.\nNotation \" 0 ? a \" := (isz a) (at level 37, no associativity) : exp_scope.\nNotation \"[ x ; .. ; y ]\" := (add x .. (add y (num 0)) ..) : exp_scope.\n\nOpen Scope exp_scope.\n\nFixpoint interpret_tp (t:tp) : Set := \nmatch t with\n| Nat => nat\n| Bool => bool\n| Prod t1 t2 => prod (interpret_tp t1) (interpret_tp t2)\nend.\n\n\nFixpoint eval {t:tp} (e:exp t) : interpret_tp t :=\nmatch e in exp t return interpret_tp t with\n| #n => n\n| a1 + a2 => (eval a1 + eval a2)%nat\n| bval b => b\n| b1 & b2 => (eval b1 && eval b2)%bool\n| 0? a => beq_nat (eval a) 0\n| pair _ _ e1 e2 => (eval e1, eval e2)\nend.\n\nReserved Notation \" t ==> t' \" (at level 80).\n\n(* semantyka naturalna wyrazen *)\nInductive evalR : forall {t}, exp t -> interpret_tp t -> Prop :=\n| re_num : forall n, #n ==> n\n| re_add : forall a1 a2 n1 n2, \n           a1 ==> n1 -> a2 ==> n2 ->\n           a1 + a2 ==> (n1 + n2)%nat\n| re_bval : forall b, \n            bval b ==> b\n| re_and : forall b1 b2 t1 t2, \n           b1 ==> t1 -> b2 ==> t2 ->\n           b1 & b2 ==> t1 && t2\n| re_isz : forall a n, \n           a ==> n -> (0? a) ==> beq_nat n 0\n| re_pair : forall t1 t2 (a1: exp t1) (a2: exp t2) n1 n2, \n            a1 ==> n1 -> a2 ==> n2 -> \n            (pair _ _ a1 a2) ==> (n1, n2)\nwhere \" t ==> t' \" := (evalR t t').\n\n(* proste makro do wykanczania dowodow indukcyjnych *)\nLtac finish :=\nsimpl in *; try subst; try constructor; try congruence; auto.\n\n(* ta taktyka sama wyszukuje kandydatow do indukcji *)\nLtac induct_eval tac :=\nmatch goal with\n| [ H : eval ?X = _ |- _ ] => induction X; tac\n| [ H : evalR _ _ |- _ ] => induction H; tac\n| _ => fail\nend.\n\nLemma equiv :\nforall t (e:exp t) v, eval e = v <-> evalR e v.\nProof.\n(* intros t e v; split; intro H.\ninduction e; finish.\ninduction H; finish.*)\nsplit; intros; induct_eval finish.\nQed.\n\nRequire Import Coq.Program.Equality.\n\n\nLemma evalR_add : \nforall (e1 e2: exp Nat) (n1 n2:nat),\n  evalR e1 n1 -> evalR e2 n2 -> evalR (e1 + e2) ((n1 + n2)%nat).\n(* induction e1. *)\ndependent induction e1; intros; constructor; trivial.\nQed.\n\nHint Resolve evalR_add.\n\n\nLemma evalR_nat :\nforall n, evalR (#n) n.\nconstructor.\nQed.\n\nHint Immediate evalR_nat.\n\nPrint HintDb core.\n\n\nLemma guess :\nexists e1 e2: exp Nat, evalR (e1 + e2) ((2 + 3)%nat).\nProof.\ndebug eauto.\nQed.\n\nPrint guess.\n\n(**)\n\nCheck ((2+3)%nat).\n\nClose Scope exp_scope.\n\nCheck (2+3).\n\n(* przypisujemy klucz do naszego zakresu *)\nDelimit Scope exp_scope with exp.\n\n(* tak uzywamy klucza, zeby skorzystac z notacji, gdy zakres nie jest otwarty *)\n\nCheck ([#3; #4])%exp.\n\n(* Bazy twierdzen *)\n\n(* Hint Constructors *)\n\nInductive even : nat -> Prop :=\n| even0 : even 0\n| evenSS : forall n, even n -> even (S (S n)).\n\n(* dzieki temu auto bedzie widzialo konstruktory even *)\nHint Constructors even.\n\nPrint HintDb core.\n\nLemma even6 :\neven 6.\nProof. auto. Qed.\n\n(* Hint Immediate *)\n\nHypothesis n_1_m_1 : forall n m, n + 1 = m + 1 -> n = m.\n\n(* podpowiedz dla auto, o niskim koszcie *)\nHint Immediate n_1_m_1 : mydb.\n\nPrint HintDb mydb.\n\nLemma n_1_m_1_ex :\nforall n m, S (n + 1) = S (m + 1) -> n = m.\nProof.\nintros n m H; injection H; intros.\ninfo_auto with mydb.\n(* samo auto nie dziala *)\nQed.\n\n(* Hint Resolve *)\n\n(* podpowiedz dla auto *)\nHint Resolve n_1_m_1_ex : mydb.\n\nPrint HintDb mydb.\n\nLemma n_1_m_1_ex2 :\nforall n m, S (n + 1) = S (m + 1) -> n = m.\nProof.\nintros.\ninfo_auto with mydb.\nQed.\n\nCheck le_S_n.\nHint Resolve le_S_n : mydb.\n\nLemma le_S_3 : \nforall n m, S (S (S n)) <= S (S (S m)) -> n <= m.\nProof.\n(*intros; do 3 apply le_S_n; assumption.*)\ndebug auto with mydb.\nQed.\n\nPrint le_S_3.\n\nHint Resolve le_trans : mydb.\n\nPrint HintDb mydb.\n\n\nLemma le_trans2 :\nforall n m p, n<=m -> m<=p -> n<=p.\nProof.\nintros.\ndebug eauto with mydb.\n(* tak tez mozna: apply le_trans with m. *)\n(* albo tak : \neapply le_trans.\ninstantiate (1:=m).\ntrivial. trivial.\n*)\nQed.\n\n\n\nRemove Hints le_S_n: mydb.\n\nPrint HintDb mydb.\n\nHint Extern 4 =>\nmatch goal with \n| [ |- _ <= _ ] => simple apply le_S_n\n| _ => fail\nend : mydb.\n\nPrint HintDb mydb.\n\n\nLemma le_trans3 :\nforall n m p, n<=m -> m<=p -> n<=p.\nProof.\nintros.\ndebug eauto with mydb.\n(* tak tez mozna: apply le_trans with m. *)\n(* albo tak : \neapply le_trans.\ninstantiate (1:=m).\ntrivial. trivial.\n*)\nQed.\n\n\n(* Hint Rewrite *)\n\nVariable A : Set.\nVariable f : A -> A.\nHypothesis rew_f : forall x, f x = f (f x).\n\n(* podpowiedz dla autorewrite; uwaga na nieskonczone ciagi przepisywan *)\n\nHint Rewrite <- rew_f : mydb.\n\nPrint Rewrite HintDb mydb.\n\n\nLemma rew_2f :\nforall x, f (f x) = f x.\nProof.\nintros.\nautorewrite with mydb.\nreflexivity.\nQed.\n\n(* Hint Rewrite rew_f : mydb.  spowoduje zapetlenie *) \n\n(* Hint Extern *)\n\nPrint HintDb core.\n\n(* podpowiedz dla auto *)\nHint Extern 1 (_ <> _) => discriminate.\n\nPrint HintDb core.\n\nLemma true_false : \ntrue <> false.\nProof.\ninfo_auto.\nQed.\n\nHint Extern 1 => \nmatch goal with\n| [ H : S ?m = S ?n |- _ ] => injection H; intro; clear H; try subst\nend.\n\nPrint HintDb core.\n\nLemma injection_ex :\nforall n m, S (S (S n)) = S (S (S m)) -> n = m.\nProof.\ninfo_auto.\nQed.\n\n\n(* Hint Unfold *)\n\nDefinition idnat (n:nat) : Prop := n = n.\n\n(* podpowiedz dla auto, rozwija definicje w glowie celu *)\nHint Unfold idnat : mydb.\n\nPrint HintDb mydb.\n\nLemma idnat_5 :\nidnat 5.\nProof.\nauto.\ninfo_auto with mydb.\nQed.\n\n\n(* predefiniowane bazy *)\n\nLemma le_r :\nforall n m p, n <= m -> n + p <= m + p.\nProof.\ninfo_auto with arith.\nQed.\n\nPrint HintDb arith.\n\n(* pattern, omega *)\n\nRequire Import Omega.\n\nLemma mult_distr_1 :\nforall n m, n * m + m = (n + 1) * m.\nProof.\nintros n m.\n(* wybierz podterm (n+1): *)\npattern (n + 1).\n(* przepisz tylko w wybranym miejscu: *)\nrewrite plus_comm.\nsimpl.\nauto with arith.\nQed.\n\nPrint mult_distr_1.\n\nLemma five_n :\nforall n, n + n + n + n + n = 5 * n.\nProof.\nintro.\n(* wybierz 1. wystapienie n: *)\npattern n at 1.\n(* przepisz tylko w wybranym miejscu: *)\nrewrite <- mult_1_l.\nrepeat rewrite mult_distr_1.\nauto.\nQed.\n\nPrint five_n.\n\nLemma five_n_omega :\nforall n, n + n + n + n + n = 5 * n.\nProof.\nintro.\nomega.\nQed.\n\nPrint five_n_omega.\n\nFixpoint big_useless_hyp (n:nat) : Prop :=\nmatch n with\n| O => n = n\n| S m => n = n \\/ big_useless_hyp m\nend.\n\nLemma solve_omega :\nbig_useless_hyp 60 -> 1 <> 0.\nProof.\nsimpl.\nTime omega.\n(* Time auto. *)\nQed.\n\n(* programowanie w Ltac *)\n\nLtac elimcase n := \ngeneralize (refl_equal n); pattern n at -1; case n; intros.\n\n(* to samo robi istniejaca taktyka: *)\nPrint Ltac case_eq.\nPrint Ltac elimcase.\nPrint Ltac auto.\n\n\nLemma cases:\nforall (P Q : nat -> Prop) n, \n(n = 0 -> P n) -> (n > 0 -> Q n) -> P n \\/ Q n.\nProof.\nintros.\nelimcase n.\nleft; subst; intuition.\nright; subst; intuition.\nQed.\n\n\n(* taktyka rekurencyjna : \n   usun wszystkie przeslanki postaci _ = _ *)\nLtac clear_eq_hyp :=\nmatch goal with\n| [ H : _ = _ |- _ ] => clear H ; clear_eq_hyp\n| _ => idtac\nend.\n\n(* inaczej: *)\nLtac clear_eq_hyp' :=\nrepeat match goal with\n       | [ H : _ = _ |- _ ] => clear H\n       | _ => idtac\n       end.\n\nLemma clear_eq_hyp :\nforall n, 1 = 1 -> 2 = 2 -> 3 = 3 -> 4 = 4 -> 5 = 5 -> 6 = 6 -> 0 <= n.\nProof.\nintros.\nclear_eq_hyp'.\nauto with arith.\nQed.\n\n(* zamien n + m na SSSS...S n *)\n\nLtac replace_plus :=\nrepeat match goal with\n| [ |- context C [?X + S ?Y] ] => idtac C; rewrite <- plus_n_Sm\n| [ |- context [?X + 0] ] => rewrite plus_0_r\n| _ => fail\nend.\n\n(* stosuj konstruktory le do skutku *)\nLtac apply_le_c := constructor 1 || (constructor 2; apply_le_c).\n\nLemma le_n_n5 :\nforall n, n <= S (n + 4).\nProof.\nintro.\nreplace_plus.\napply_le_c. \n(* info_auto with arith. *)\nQed.\n\n\n(* sprawdz, czy nie ma juz takiej przeslanki: *)\nLtac not_in_hyps A :=\nmatch goal with\n| [ H : A |- _ ] => fail 1\n| _ => idtac\nend.\n\n(* intros bez powtorzen, \nz wylaczeniem sprawdzania powtorzen przy wprowadzaniu formul *)\nLtac new_intros :=\nmatch goal with\n| [ |- ?A -> ?B ] => not_in_hyps A; let h:=fresh \"H\" in intro h; new_intros \n| [ |- ?A -> ?B ] => let h:=fresh \"H\" in intro h; clear h; new_intros\n| [ |- forall _ : Prop, _ ] => let x:=fresh \"A\" in intro x; new_intros\n| _ => idtac\nend.  \n\nLemma intros_wo_rep :\nforall A B:Prop, (forall x:nat,x=0) -> (forall y:nat, y=0) ->\n(A -> B) -> (B -> A) -> (A -> B) -> A -> B -> B -> A -> (A -> B) -> B.  \nProof.\nnew_intros.\nassumption.\nQed.\n\n(* inversion *)\n\n(* rozwiaz cel przez n-krotna inwersje: *)\nLtac by_inversion n :=\nmatch n with\n| O => idtac \"nie udalo sie\"\n| S ?m => match goal with\n         | [ H : _ |- _ ] => solve [inversion H; try subst; idtac H; by_inversion m]\n         | _ => idtac n\n         end\nend.\n\nTactic Notation \"contradiction\" \"by\" \"inversion\" := by_inversion 1.\nTactic Notation \"contradiction\" \"by\" \"inversion\" constr(n) := by_inversion n.\n\nLemma not_even_1 :\n~ even 5.\nProof.\nintro.\ncontradiction by inversion.\ncontradiction by inversion 3.\nQed.\n \n(* taktyki jako funkcje w Ltac *)\n\nRequire Import List.\nImport ListNotations.\n\n(* oblicz dlugosc listy *)\nLtac len l :=\nmatch l with\n|  _ :: ?ls => let ln := len ls in constr:(S ln)\n| [] => O\nend.\n\n(* tak nie mozna oczywiscie:\nEval compute in len [2;3].*)\n\n(* ale tak mozna sprawdzic wynik zastosowania taktyki, ktora zwraca wartosc: *)\nGoal True.\n  let n := len [2;3;4;9] in\n    idtac n.\n  let l := auto in idtac l.\n  let l := constr:(ltac:(constructor):bool) in idtac l.\nauto.\nQed.\n\nDefinition tail {A} (l:list A) : list A :=\nmatch l with\n| [] => ltac:(auto)\n| h::t => t\nend.\n\nPrint tail.\n\n(* len + debugging info *)\n\nLtac len2 l :=\nidtac l;\nmatch l with\n|  _ :: ?ls => let ln := len2 ls in constr:(S ln)\n| [] => O\nend.\n\nGoal True.\n  let n := len2 [2;3;4;9] in\n    idtac n.\nauto.\nQed.\n\nLtac len3 l k :=\nidtac l;\nmatch l with\n|  _ :: ?ls => len3 ls ltac:(fun m => k (S m))\n| [] => k 0\nend.\n\nGoal True.\n  len3 [2;3;4;9] ltac:(fun n => pose n).\nauto.\nQed.\n\n(* generowanie zmiennych egzystencjalnych *)\n\n(* odraczanie instancjacji kwantyfikatora przez uzycie zmiennej egzystencjalnej *)\n\nLemma two_gt_one :\n(forall x, S x > x) -> 2 > 1.\nProof.\nintros.\n(* utworzenie nowej zmiennej egzystencjalnej i jej nazwy *)\nevar (y : nat).\nspecialize (H ?y).\n(* info_auto. <- tu blad: zostala zmienna niezunifikowana *)\napply H.\nQed.\n\nPrint two_gt_one.\n\n(* przyklad z Compcerta *)\n\n\n\nLemma modusponens: forall (P Q: Prop), P -> (P -> Q) -> Q.\nProof. auto. Qed.\n\nLtac exploit x :=\n   refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _ _) _)\n|| refine (modusponens _ _ (x _ _ _ _ _ _ _ _ _ _) _)\n|| refine (modusponens _ _ (x _ _ _ _) _)\n|| refine (modusponens _ _ (x _ _ _) _)\n|| refine (modusponens _ _ (x _ _) _)\n|| refine (modusponens _ _ (x _) _).\n\nLemma mp_test :\nforall A B C D E:Prop, (A -> B -> C -> D) -> E.\nintros.\nexploit H.\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/w7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7832836157872062}}
{"text": "Require Import List.\n\n(* inductive predicate expressing the fact that two lists are obtained from\neach other, by the Permute of two consecutive elements  *)\nInductive Transpose {A:Type} : list A -> list A -> Prop :=\n  | transp_pair : forall(x y:A), Transpose (x::y::nil) (y::x::nil)\n  | transp_gen  : forall (l m l1 l2 : list A), \n    Transpose l m -> Transpose (l1++l++l2) (l1++m++l2).\n\n(* one common issue with this sort of definition is that constructors of the\ninductive predicates are akin to 'axioms', and it is very easy to define the\nwrong thing, or things that are inconsistent, or incomplete etc *)\n\n(* Here is another way to go about it *)\nDefinition Transpose' {A:Type} (l: list A) (m:list A) : Prop := \n  exists (l1 l2:list A) (x y:A), \n  l = l1++(x::y::nil)++l2 /\\ m = l1++(y::x::nil)++l2.\n\n(* ideally, you want to check the equivalence between the two notions *)\nLemma Transpose_check: forall (A:Type)(l m:list A),\n  Transpose l m <-> Transpose' l m.\nProof.\n  intros A l m. split. intro H. generalize H. elim H. intros. \n  unfold Transpose'. exists nil, nil, x, y. auto.\n  clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.\n  cut (Transpose' l m). clear H0 H1. intro H.\n  unfold Transpose' in H. elim H. intro l3. clear H. intro H.\n  elim H. intro l4. clear H. intro H. \n  elim H. intro x. clear H. intro H.\n  elim H. intro y. clear H. intro H.\n  elim H. clear H. intros H0 H1.\n  unfold Transpose'.\n  exists (l1++l3), (l4++l2), x, y. rewrite H0, H1. clear H0 H1.\n  split. rewrite <- app_assoc with (l:=l1). rewrite <- app_assoc with (l:=l3).\n  rewrite <- app_assoc with (n:=l2). reflexivity. \n  rewrite <- app_assoc with (l:=l1). rewrite <- app_assoc with (l:=l3).\n  rewrite <- app_assoc with (n:=l2). reflexivity.\n  apply H1. exact H0.\n  intro H. unfold Transpose' in H. elim H. clear H. intros l1 H.\n  elim H. clear H. intros l2 H. elim H. clear H. intros x H.\n  elim H. clear H. intros y H. elim H. clear H. intros Hl Hm.\n  rewrite Hl, Hm. apply transp_gen. apply transp_pair.\nQed.\n\n(* This inductive predicate expresses the fact that two \nlists are Permutes of one another *)\nInductive Permute {A:Type} : list A -> list A -> Prop :=\n  | perm_self : forall l:list A, Permute l l\n  | perm_next : forall l l' m: list A, \n    Permute l l' -> Transpose l' m -> Permute l m. \n\n\nLemma Permute_refl : forall (A:Type) (l:list A), Permute l l.\nProof.\n  intros A l. apply perm_self.\nQed.\n\n \nLemma Transpose_sym: forall (A:Type) (l m: list A),\n  Transpose l m -> Transpose m l.\nProof.\n  intros A l m H. generalize H. elim H. clear l m H.\n  intros x y H. clear H. apply transp_pair. clear l m H.\n  intros l m l1 l2 H H' H0. clear H0. apply transp_gen.\n  apply H'. exact H.\nQed.\n\nLemma Transpose_first: forall (A:Type) (l l' m:list A),\n  Transpose l l' -> Permute l' m -> Permute l m.\nProof.\n  intros A l l' m H0 H1. generalize H0. clear H0. generalize H1 l. \n  elim H1. clear H1 l l' m. intros m. intro H. clear H. intro l.\n  intro H. apply perm_next with (l':=l). apply perm_self. exact H.\n  clear H1 l l' m. intros l l' m H0 H1 H3 H4 k H5.\n  eapply perm_next. apply H1. exact H0. exact H5. exact H3.\n  (* dont understand why normal 'apply ... with' was failing *)\nQed.\n\nLemma Permute_sym: forall (A:Type) (l m: list A),\n  Permute l m -> Permute m l.\nProof.\n  intros A l m H. generalize H. elim H. auto. clear H m l.  \n  intros l l' m H0 H1 H2 H3. apply Transpose_first with (l':=l').\n  apply Transpose_sym. exact H2. apply H1. exact H0.\nQed.\n\nLemma Permute_trans: forall (A:Type) (l m k: list A),\n  Permute l m -> Permute m k -> Permute l k.\nProof.\n  intros A l m k H. generalize H k. clear k. elim H. auto.\n  clear H l m. intros l l' m H0 H1 H2 H3 k H4.\n  apply H1. exact H0. apply Transpose_first with (l':=m).\n  exact H2. exact H4.\nQed.\n\n\nLemma Transpose_imp_eq_length: forall (A:Type)(l m:list A),\n  Transpose l m -> length l = length m.\nProof.\n  intros A l m H. generalize H. elim H.\n  clear H l m. intros. simpl. reflexivity.\n  clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.\n  rewrite app_length, app_length, app_length, app_length.\n  rewrite H1. reflexivity. exact H0.\nQed.\n\nLemma Permute_imp_eq_length: forall (A:Type)(l m:list A),\n  Permute l m -> length l = length m.\nProof.\n  intros A l m H. generalize H. elim H.\n  clear H l m. intros. reflexivity.  \n  clear H l m. intros l l' m H0 H1 H2 H3. clear H3.  \n  apply eq_trans with (y:=length l').\n  apply H1. exact H0. apply Transpose_imp_eq_length. exact H2.\nQed.\n\n\nDefinition SubSet {A:Type}(l m:list A) : Prop :=\n  forall (x:A), In x l -> In x m.\n\nDefinition EqSet {A:Type}(l m: list A) : Prop :=\n  SubSet l m /\\ SubSet m l.\n\nLemma SubSet_refl: forall (A:Type)(l:list A), SubSet l l.\nProof.\n  intros A l. unfold SubSet. intros x. tauto.\nQed.\n\nLemma SubSet_trans: forall (A: Type)(l m k: list A), \n  SubSet l m -> SubSet m k -> SubSet l k.\nProof.\n  intros A l m k H0 H1. unfold SubSet. intros x H2.\n  apply H1. apply H0. exact H2.\nQed.\n\n\nLemma Transpose_imp_SubSet: forall (A:Type)(l m:list A),\n  Transpose l m -> SubSet l m.\nProof.\n  intros A l m H. generalize H. elim H.\n  clear H l m. intros x y H0. clear H0. unfold SubSet. \n  intros z H0. simpl. simpl in H0. elim H0.\n  clear H0. intro H0. right. left. exact H0.\n  clear H0. intro H0. elim H0. clear H0. intro H0. left. exact H0.\n  apply False_ind.\n  clear H l m. intros l m l1 l2 H0 H1 H2. clear H2. unfold SubSet.\n  intros x H2. simpl. rewrite in_app_iff, in_app_iff.\n  rewrite in_app_iff, in_app_iff in H2. elim H2.\n  clear H2. intro H2. left. exact H2.\n  clear H2. intro H2. elim H2. clear H2. intro H2. right. left.\n  apply H1. exact H0. exact H2.\n  clear H2. intro H2. right. right. exact H2.\nQed.\n\nLemma Transpose_imp_EqSet: forall (A:Type)(l m:list A),\n  Transpose l m -> EqSet l m.\nProof.\n  intros A l m H. unfold EqSet. split. \n  apply Transpose_imp_SubSet. exact H.\n  apply Transpose_imp_SubSet. apply Transpose_sym. exact H.\nQed.\n\nLemma Permute_imp_SubSet: forall (A:Type)(l m: list A),\n  Permute l m -> SubSet l m.\nProof.\n  intros A l m H. generalize H. elim H.\n  clear H l m. intros. apply SubSet_refl.\n  clear H l m. intros l l' m H0 H1 H2 H3. clear H3.\n  apply SubSet_trans with (m:= l'). apply H1. exact H0.\n  apply Transpose_imp_SubSet. exact H2.\nQed.\n\n\nLemma Permute_imp_EqSet: forall (A:Type)(l m: list A),\n  Permute l m -> EqSet l m.\nProof.\n  intros A l m H. unfold EqSet. split.\n  apply Permute_imp_SubSet. exact H.\n  apply Permute_imp_SubSet. apply Permute_sym. exact H.\nQed.\n\n\nLemma Transpose_cons: forall (A:Type)(l m:list A)(a: A),\n  Transpose l m -> Transpose (a::l) (a::m).\nProof.\n intros A l m a H. \n cut (a::l = (a::nil) ++ l ++ nil).\n cut (a::m = (a::nil) ++ m ++ nil).\n intros Hm Hl. rewrite Hm, Hl. apply transp_gen. exact H.\n rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.\n rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.\nQed.\n  \n\nLemma Permute_cons: forall (A:Type)(l m: list A)(a: A),\n  Permute l m -> Permute (a::l) (a::m).\nProof.\n  intros A l m a H. generalize H. generalize a. clear a. elim H.\n  clear H l m. intros. apply perm_self.\n  clear H l m. intros l l' m H0 H1 H2 a H3.\n  apply Permute_trans with (m:=(a::l')). apply H1. exact H0.\n  apply (perm_next (a::l') (a::l') (a::m)). apply perm_self.\n  apply Transpose_cons. exact H2.\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/lib/permute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.9032942112597331, "lm_q1q2_score": 0.7831883858879812}}
{"text": "(**\nTrois objectifs dans ce TD :\n- Raisonner avec apply ... pour utiliser\n  hypothèses implicatives et/ou quantifiées universellement)\n- Utiliser des hypothèses de récurrence implicatives et/ou\n   quantifiées universellement\n- Utiliser une hypothèse indiquant une égalité entre deux \n  constructeurs différents, ce qui est \"manifestement impossible\"\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** * Partie 1 : raisonnement, tactiques refine et apply *)\n\n(** ** Rappels sur les tactiques *)\n(**\n\n- intro x\n  a le même effet que\n  refine (fun x => _)\n\n- apply f\n  a le même effet que\n  refine f, ou\n  refine (f _), ou\n  refine (f _ _), etc.\n  suivant le type de [f].\n\n  Exemple\n\n  f : T1 -> T2\n  ============\n  T2\n\n  On peut ici utiliser refine (f _), il restera à trouver\n  quelque chose de type T1.\n\n  - destruct E as [ (* Cons1 *) x | (* Cons2 *) | (* Cons3 *) y z]\n    a le même effet que\n    refine (match E with\n             | Cons1 x => _\n             | Cons2 => _\n             | Cons3 y z => _\n             end).\n\n    où E a un type inductif de constructeurs Cons1 Cons2 et Cons3\n    ayant respectivement 1, 0 et 2 arguments.\n *)\n\n(** ** Rappels sur les structures en arbre *)\n(**\n    1) on a vu des structures de données destinées à la\n    programmation (listes, etc.), et des structures de données\n    destinées au raisonnement, appelées arbres de preuve,\n    qui se manipulent de la même manière.\n\n    2) On a vu également que les types de structures de données pour\n    la programmation ont eux même un type, l'univers Set.\n *)\n\n(** ** L'univers Prop *)\n(**\n    Les arbres de preuve sont dans un univers parallèle à Set,\n    appelé Prop.\n\n    Remarque : en particulier, les égalités sont dans Prop.\n*)\n\n(*\n\nCorerction get td3\n\nFixpoint get (i:int) (s:state) :nat := \n  match s with\n  | nil => 0\n  | cons (j,v) s' => match i with\n                     | 0 => v\n                     | S i' => get i' s'\n                     end\n  end.\n\n  or \n\n  match S, i with\n  | nil, _ => 0\n  | cons (j,v) s', 0 => v\n  | cons (j,v) s', S i' => get i' s'\n  end.\n\n  get 0 Nil = 0\n  get 0 x::q = x\n  get (S i) Nil = 0\n  get (S i) x::q = get i q\n*)\nCheck (2 = 2).\n\nSection sec_ABC.\n  (** Considérons des propositions arbitraires A B C... *)\n  Variable A B C : Prop.\n  (** ... et des prédicats arbitraires P Q R sur nat *)\n  Variable P Q R : nat -> Prop.\n\n (** Preuve à faire uniquement avec refine/intro/apply *)\n (** Faire également Show Proof après les invications de\n     tactiques pour voir la preuve en train de se former. *)\n  Lemma impl_trans:\n    (A -> B) -> (B -> C) -> (A -> C).\n  Proof.\n    intros H1 H2 H3.\n    apply H2.\n    apply H1.\n    apply H3.\n  Qed.\n\n  (** Preuve à faire uniquement avec intro/apply *)\n  Lemma combi_S:   (A -> B -> C) -> (A -> B) -> A -> C.\n  Proof.\n    (* À compléter *)\n  intros H1 H2 H3.\n  apply H1.\n  apply H3.\n  apply H2.\n  apply H3.\n  Qed.\n\n  (* Preuve à faire uniquement avec intro/apply *)\n  Lemma forall_impl_trans:\n    (forall n:nat, P n -> Q n) ->\n    (forall n:nat, Q n -> R n) ->\n    (forall n:nat, P n -> R n).\n  Proof.\n    intros H1 H2 n H3.\n    apply H2.\n    apply H1.\n    apply H3.\n  Qed.\nEnd sec_ABC.\n\n\n(* -------------------------------------------------------------------------- *)\n(** * Partie 2 : équivalence entre égalité des entiers et eqnatb rendant true *)\n\n(** eqnatb renvoie true ssi ses arguments représentent le même entier naturel *)\n\nFixpoint eqnatb n1 n2 :=\n   match n1,n2 with\n  | O,O => true\n  | S n1', S n2' => eqnatb n1' n2'\n  | _,_ => false\n  end.\n\n(** ** 2.1 Le sens le plus facile (récurrence simple) *)\n\nLemma eqnatb_eq_1 : forall n, eqnatb n n = true.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - cbn[eqnatb]. apply IHn'.\nQed.\n\n\nLemma eqnatb_eq : forall n1 n2, n1 = n2 -> eqnatb n1 n2 = true.\nProof.\n  intros n1 n2 H.\n  induction H.\n  - rewrite eqnatb_eq_1. reflexivity.\nQed.\n\n  \n\n(* Facultatif : preuve directe sans utiliser eqnatb_eq_1 *)\nLemma eqnatb_eq_direct : forall n1 n2, n1 = n2 -> eqnatb n1 n2 = true.\nProof.\n  (* À compléter: utiliser clear avant induction. *)\n  (* La tactique clear [hy] retire l'hypothèse [hy] du but. *)\n  intros n1 n2 H.\n  rewrite H.\n  clear H.\n  induction n2 as [|n2' IHn2'].\n  - reflexivity.\n  - cbn[eqnatb]. apply IHn2'.\nQed.\n\n(** ** 2.2 Le sens le plus difficile (récurrence quantifiée + preuve par cas) *)\n\n(*** 2.2.1 Lemme préparatoire *)\n\n(** Nouvelle tactique :\nla tactique [change _expr_] permet de remplacer la conclusion\npar une autre propriété convertible c'est-à-dire equivalente par calcul.\n\nexemple:\n\n===========\n2 + 1 = 6\n-> change (3 = 3 * 2)\n\nCela permet de \"décalculer\" un résultat de fonction.\n *)\n\nLemma absurd: 5 = 4 -> 15 = 12.\nProof.\n  intros e.\n  (** faire apparaitre 5 et 4 dans un même contexte\n      en utilisant la tactique [change] *)\n  (* À compléter *)\n  (* change (... 5 ... = ... 4 ...). *)\n\n  (* discriminate e.*)\n\n  change(3 * 5 = 3 * 4).\n  rewrite e.\n  reflexivity.\nQed.\n(* facultatif *)\nLemma true_false_eg : true = false -> forall n1 n2 : nat, n1 = n2.\nProof.\n  intro etf. intros n1 n2.\n  (** Definir une fonction f tq [f true = n1] et [f false = n2]   *)\n  (* À compléter *)\n  (* pose (f (b:bool) := ... *)\n  pose(f (b:bool) := if b then n1 else n2).\n  change(f true = f false).\n  rewrite etf.\n  reflexivity.\n\n    (*discriminate.*)\nQed.\n\n(*** 2.2.2 Réciproque de 2.1 *)\n(** Dans l'exercice ci-dessous, il faut bien identifier la propriété de n1\n    sur laquelle porte la récurrence *)\nLemma eq_eqnatb : forall n1 n2, eqnatb n1 n2 = true -> n1 = n2.\nProof.\n  intros n1 n2 H.\n  cbn[eqnatb] in H.\n  induction n1 as [|n1' IHn1'], n2 as [|n2' IHn2'].\n  - reflexivity.\n  - discriminate.\n  - discriminate.\n  -  \nAdmitted.\n\n\n\n(** ** 2.3 Équivalence, tactique split *)\n\n(** On peut utiliser split pour prouver une équivalence\n    par décomposition en deux implications *)\n\nPrint iff.\n\nLemma eq_iff_eqnatb : forall n1 n2, eqnatb n1 n2 = true <-> n1 = n2.\nProof.\n  split.\n  - intro H.\n    induction n1, n2.\n    + reflexivity.\n    + discriminate.\n    + discriminate.\n    + \n\nAdmitted.\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/td4_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.9032942034496964, "lm_q1q2_score": 0.7831883667024157}}
{"text": "Require Import PeanoNat.\n\n(* Strong induction on Natural numbers with properties sending to Props. *)\n\nTheorem strong_induction:\nforall P : nat -> Prop,\n(forall n : nat, (forall k : nat, (k < n -> P k)) -> P n) ->\nforall n : nat, P n.\nProof.\nintros P H. assert (Lem : forall n, (forall m, m <= n -> P m)).\n{ induction n. intros.\n  - assert (E: m = 0). inversion H0.  reflexivity. rewrite E. apply H.\n    intros. exfalso. inversion H1.\n  - intros. apply H. intros. apply IHn. inversion H0.\n    * rewrite H2 in H1. apply Nat.lt_succ_r. apply H1.\n    * assert (E: k <= m). apply Nat.lt_le_incl. apply H1. \n      apply Nat.le_trans with (m:=m). apply E. apply H3. }\nintro n. apply H. intros. apply Lem with (n:=n) (m:=k).\napply Nat.lt_le_incl. apply H0.\nQed.", "meta": {"author": "ianshil", "repo": "PhD_thesis", "sha": "af4940397f0d95c1d63a196ab29a3b9f715d9f4e", "save_path": "github-repos/coq/ianshil-PhD_thesis", "path": "github-repos/coq/ianshil-PhD_thesis/PhD_thesis-af4940397f0d95c1d63a196ab29a3b9f715d9f4e/FO_Bi_Int/FO_BiInt_strong_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122720843812, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.783164615573182}}
{"text": "Require Import Nat.\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. \nQed.\n\nCheck negb.\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\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 H.\n  destruct c.\n    - reflexivity.\n    - rewrite <- H.\n  destruct b.\n    * reflexivity.\n    * reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1: forall n: nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [|n'].\n  reflexivity.\n  reflexivity.\nQed.\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 H [].\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem neg_fn_applied_twice:\n  forall (f: bool->bool),\n  (forall (x: bool), f x = negb x) -> forall (b: bool), f (f b) = b.\nProof.\n  intros f H [].\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nLemma andb_true: forall (b: bool), andb b true = b.\nProof.\n  intros [].\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma andb_false: forall (b: bool), andb b false = false.\nProof.\n  intros [].\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma orb_true: forall (b:bool), orb b true = true.\nProof.\n  intros [].\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma orb_false: forall (b: bool), orb b false = b.\nProof.\n  intros [].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem andb_eq_orb:\n  forall (b c: bool), (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  destruct c.\n  rewrite -> andb_true.\n  rewrite -> orb_true.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  rewrite -> andb_false.\n  rewrite -> orb_false.\n  intros H1.\n  rewrite -> H1.\n  reflexivity.\nQed.\n\n\nInductive bin: Type :=\n  | Z\n  | A (n: bin)\n  | B (n: bin).\n\nFixpoint incr (m:bin):bin :=\n  match m with\n  | Z => B Z\n  | A n => B n\n  | B n => A (incr n)\n  end.\n\nFixpoint bin_to_nat (m: bin): nat :=\n  match m with\n  | Z => 0\n  | A n => 2 * bin_to_nat n\n  | B n => 1 + 2 * bin_to_nat n\n  end.\n\nCompute bin_to_nat (incr (A (A (A (A (B Z)))))).\n\nExample test_bin_incr1 : (incr (B Z)) = A (B Z).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr2 : (incr (A (B Z))) = B (B Z).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr3 : (incr (B (B Z))) = A (A (B Z)).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr4 : bin_to_nat (A (B Z)) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr5 :\n        bin_to_nat (incr (B Z)) = 1 + bin_to_nat (B Z).\nProof. simpl. reflexivity. Qed.\n\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": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/Basic2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7830190310843032}}
{"text": "Require Import Utf8.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Init.Specif.\n\n\n(*Require Import Category.*)\n\n(* In order to avoid intersecting classes but still have notations,\n  I am splitting the group class *)\n\n(*Class GroupOps (A : Type) := {\n  unit : A;\n  mult : A -> A -> A;\n  inv : A -> A;\n}.*)\n\nGeneralizable Variables a b c.\n\nClass Group (A : Type) (gunit : A) (ginv : A -> A) (gmult : A -> A -> A) := {\n    multAssoc: forall a b c : A, gmult a (gmult b c) = gmult (gmult a b) c;\n    unitLeft: forall a : A, gmult gunit a = a;\n    unitRight: forall a : A, gmult a gunit = a;\n    invLeft: forall a : A, gmult (ginv a) a = gunit;\n    invRight: forall a : A, gmult a (ginv a) = gunit;\n}.\n\nDefinition unitOp {A gunit ginv gmult} {G : Group A gunit ginv gmult} := gunit.\nDefinition multOp {A gunit ginv gmult} {G : Group A gunit ginv gmult} := gmult.\nDefinition invOp {A gunit ginv gmult} {G : Group A gunit ginv gmult} := ginv.\n\nInfix \"*\" := multOp : group_scope.\nNotation \"! a\" := (invOp a) (right associativity, at level 30) : group_scope.\nNotation \"1\" := (unitOp) (at level 10): group_scope.\n\nLocal Open Scope group_scope.\n\nDefinition isInverse {A} `{Group A} (a b : A) := (a * b = 1 /\\ b * a = 1).\n\nDefinition isUnit `{Group} u := forall a, (u * a = a /\\ a * u = a).\n\nCorollary inverseUnique `{Group}: `(unique (isInverse a) (! a)).\nProof.\n  unfold unique. intros a. unfold isInverse. split.\n  - split.\n    + apply invRight.\n    + apply invLeft.\n  - intros b I. destruct I as [I1 I2]. replace (! a) with (! a * 1).\n    + rewrite <- I1. rewrite multAssoc. rewrite invLeft. apply unitLeft.\n    + apply unitRight.\nQed.\n\nCorollary unitUnique `{Group} : unique isUnit 1.\nProof.\n  unfold isUnit; split.\n  - intro a. split; [apply unitLeft | apply unitRight].\n  - intros b U. edestruct U as [U1 U2]. rewrite <- U1. apply unitRight.\nQed.\n\nCorollary inverseMult `{Group} : `(!(a * b) = !b * !a).\nProof.\n  intros a b. apply inverseUnique. unfold isInverse. split.\n  - replace (a * b * ((! b) * (! a))) with (a * (b * !b) * (!a)).\n    + rewrite invRight. rewrite (unitRight a). apply invRight.\n    + rewrite multAssoc. rewrite multAssoc. reflexivity.\n  - replace (!b * !a * (a * b)) with (!b * (!a * a) * b).\n    + rewrite invLeft. rewrite (unitRight (! b)). apply invLeft.\n    + repeat (rewrite multAssoc). reflexivity.\nQed.\n\nCorollary inverseInvolutive `{Group} : `(!!a = a).\nProof.\n  intros a. apply inverseUnique. split.\n  - apply invLeft.\n  - apply invRight.\nQed.\n\nCorollary unitInverse {A} `{Group A} : 1 = ! 1.\nProof.\n  apply unitUnique. intro a. rewrite <- (inverseInvolutive a). split.\n  - rewrite <- inverseMult. rewrite unitRight. reflexivity.\n  - rewrite <- inverseMult. rewrite unitLeft. reflexivity.\nQed.\n\nClass GroupMorphism {A B} `{Group A} `{Group B} (f : A -> B) := {\n  groupMorphism_unit : f 1 = 1;\n  groupMorphism_mult : `(f (a * b) = f a * f b);\n  (* this one does follow from the others, but it's more convenient to have it here *)\n  groupMorphism_inv : `(f (! a) = ! (f a));\n}.\n\nDefinition groupIsomorphism {A B} `{Group A} `{Group B} (f : A -> B) :=\n  (exists g : B -> A, GroupMorphism g /\\ compose f g = id /\\ compose g f = id).\n\nDefinition groupIsomorphic (A B : Type) `{G1 : Group A} `{G2 : Group B} :=\n  exists f : A -> B, groupIsomorphism f.\n\n(** GSets *)\n\nClass GSet A X `{Group A} (gSet_action : A -> X -> X) := {\n  gSet_composition : forall a b x, gSet_action a (gSet_action b x) = gSet_action (a * b) x;\n  gSet_unit : forall x, gSet_action 1 x = x;\n}.\n\nPrint GSet.\n\nArguments GSet (A X) {gunit ginv gmult} (H) (gSet_action).\n\nPrint GSet.\n\nDefinition gSetOp {A X} `{GSet A X} := gSet_action.\n\nNotation \"g '•' x\" := (gSetOp g x) (at level 61, left associativity) : group_scope.\n\nClass Equivariant {X Y} (F : X -> Y)\n    {A action1 action2} `{G : Group A} (G1 : GSet A X G action1) \n  (G2 : GSet A Y G action2) := {\n  equivariance : forall (a : A) x, F (a • x) = a • (F x);\n}.\n\nPrint Equivariant.\n\n(* G-Sets and equivariant functions form a category *)\n\nInstance EquivariantCompose {A X Y Z opX opY opZ} `{HG : Group A} \n  {G1 : GSet A X HG opX} {G2 : GSet A Y HG opY} {G3 : GSet A Z HG opZ} \n    (f : Y -> Z) (g : X -> Y)\n  (E1 : Equivariant f G2 G3) (E2 : Equivariant g G1 G2) : (Equivariant (compose f g) G1 G3).\nProof.\n  constructor. intros a x. unfold compose. rewrite (equivariance a x).\n  rewrite (equivariance a (g x)). reflexivity.\nDefined.\n\nInstance equivariantId `{G : GSet} : Equivariant (fun x => x) G G.\n  constructor. intros a x. reflexivity.\nDefined.\n\nInstance simpleGSet' A `{HG : Group A} : GSet A A HG (fun a b => a * b).\nProof.\n  constructor.\n  - apply multAssoc.\n  - apply unitLeft.\nDefined.\n\nInstance simpleGSet A `{HG : Group A} : GSet A A HG (fun a b => a * b * !a).\nProof.\n  constructor.\n  - intros a b c. rewrite inverseMult. repeat (rewrite multAssoc). reflexivity.\n  - intros a. rewrite <- unitInverse. rewrite (unitRight (1 * a)). apply unitLeft.\nDefined.\n\nInstance trivialGroup : Group Coq.Init.Datatypes.unit tt (fun u => tt) (fun u u' => tt).\nProof with auto.\n  constructor ; (try intros [])...\nDefined.\n\nPrint GroupMorphism.\n\nLemma exercise13 A `{HG : Group A} (f : A -> A) (P : GroupMorphism f)\n  (E : Equivariant f (simpleGSet A) (simpleGSet' A)): groupIsomorphic A Coq.Init.Datatypes.unit.\nProof.\n  exists (fun _ => tt). exists (fun _ => 1). split; try split.\n  - reflexivity.\n  - intros. rewrite unitRight. reflexivity.\n  - intros. apply unitInverse.\n  - extensionality a. destruct a. reflexivity.\n  - extensionality a. unfold compose.\n    replace 1 with (f a * ! (f a)). 2: { apply invRight. }\n    pose proof (@equivariance A A f A _ _ _ _ _ HG (simpleGSet A) (simpleGSet' A) E).\n    unfold gSetOp in H.\n    rewrite <- groupMorphism_inv.\n    assert( forall a : A, f (a) = a * (f a)).\n    { intros b. rewrite <- H. rewrite <- multAssoc. rewrite invRight. rewrite unitRight. reflexivity. }\n    rewrite H0. rewrite <- multAssoc. rewrite <- groupMorphism_mult. rewrite invRight.\n    replace (f gunit) with (f 1) by reflexivity. rewrite groupMorphism_unit.\n    rewrite unitRight. reflexivity.\nQed.", "meta": {"author": "mirithering", "repo": "coq", "sha": "bff4429c146a998a416f3c177b772b0fefd92d46", "save_path": "github-repos/coq/mirithering-coq", "path": "github-repos/coq/mirithering-coq/coq-bff4429c146a998a416f3c177b772b0fefd92d46/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686645, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7830127267633}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma lnot_equiv n : Z.lnot n = Z.pred (-n).\n  Proof. reflexivity. Qed.\n\n  Lemma lnot_sub1 n : Z.lnot (n-1) = -n.\n  Proof. rewrite lnot_equiv; lia. Qed.\n\n  Lemma lnot_opp x : Z.lnot (- x) = x-1.\n  Proof.\n    rewrite <-Z.lnot_involutive, lnot_sub1; 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/Lnot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7830127167184273}}
{"text": "(*********************************************************)\n(*  Formal  Proof of the Tic-Tac-Toe's Perfect Strategy  *)\n(*  Author: Shuangquan Feng                              *)\n(*  Date:   Apr 29. 2018                                 *)\n(*********************************************************)\n\n(* Tic-Tac-Toe' first player has a perfect strategy to never lose the game *)\n\nRequire Import board.\n\n(* Definition of 'safe' board state:\n   Either\n   1. Player1 wins or ties\n   2. There exists a move for player1 where either \n      a. player1 wins or ties the game\n      b. for any moves player2 can make,\n         the resulting state is incomplete(i.e. not lose)\n                and still safe for player1.\n*)\n\nInductive safe (b:board) : Prop :=\n  | win : (get_state b)=win -> safe b (* p1 wins *)\n  | tie : (get_state b)=tie -> safe b (* p1 ties *)\n  | safe_step: \n    (exists (x:step), \n      (* p1 makes one move and wins *)\n      ((valid_move b x) /\\ ((get_state (move b x))=win)) \n      \\/\n      (* p1 makes one move, forall possible moves for p2, p1 is safe *)\n      (forall (y:step), \n       (valid_round b x y)\n            ->(((get_state (move b x))=incomplete)/\\safe (move (move b x) y))))\n      ->\n      safe b.\n\n(* The main theorem we want to prove.\n   The initial empty board is safe, i.e. player1 can always win or tie *)\nTheorem tic_tac_toe_first_always_safe:   \n    safe empty_board.\n\n(* define some handy tactics to simplify the proof. *)\n\n(* player1 puts X at cell c can directly win or tie the game *)\nLtac final c := exists (st c X); left; split; simpl; split; constructor.\n\n(* player1 puts X at cell c,\n   and enumerate all valid moves of player2 *)\nLtac put c' := \n    exists (st c' X); right; intros y H; split;\n    try(reflexivity);unfold valid_round in H;\n    induction y as [c s];subst; (* c:a cell, s:X *)\n    (* separate out the props in 'valid_round' *)\n    destruct H as [H1 [H2 [H3 [H4 H5]]]]; \n    clear H1;\n    apply sym_eq_iff in H2; subst; \n    (* enumerate all the moves player2 can choose *)\n    induction c; simpl in H3; simpl; \n    (* get rid of the contradictions *)\n    try (exfalso; unfold not in H3; apply H3; constructor);\n    try (inversion H4);\n    try (inversion H5);\n    apply safe_step; clear H3 H4 H5.\n\nProof.\n  apply safe_step.\n\n  (* player1 always first put X at top left corner *)\n  put c00. \n  - put c11; try(final c22).\n    + put c20; try(final c02).\n      * final c10.\n  - put c11; try(final c22).\n    + put c12; try(final c10).\n      * put c21. put c20. put c01.\n  - put c11; try(final c22).\n    + put c20; try(final c02).\n      * put c12. put c21. put c11.\n  - put c02; try(final c01).\n    + put c21.\n      * put c12. put c22. put c20.\n      * put c10. put c22. put c20.\n      * put c12. put c22. put c10.\n      * put c10. put c20. put c21.\n  - put c11; try(final c22).\n    + put c02; try(final c20).\n      * final c01.\n  - put c01; try(final c02).\n    + put c11; try(final c21).\n      * final c22.\n  - put c11; try(final c22).\n    + put c20; try(final c10).\n      * final c02.\n  - put c02; try(final c01).\n    + put c20; try(final c11).\n      * final c10.\nQed.\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/tic-tac-toe/tic-tac-toe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7830127141533609}}
{"text": "Theorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c. induction b.\n  - (* base *)simpl. intros c_true. exact c_true.\n  - (* ih *) induction c.\n    + (* base *) simpl. intros f_t. reflexivity.\n    + (* ih *) simpl. intros f_t. exact f_t.\nQed.\n\nFixpoint beq_nat (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' => beq_nat n' m'\n            end\n  end.\n\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  induction n.\n  - (* base *) simpl. reflexivity.\n  - (* ih *) simpl. reflexivity.\nQed.\n\nCompute pred 1.\nCompute pred 0.\n\n(*\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | m => fact (pred n)\n  end.\n\nvs\n*)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | S m => fact m\n  end.\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/1_Basics/5_optionalexercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8856314753275019, "lm_q1q2_score": 0.7829330106344673}}
{"text": "(**\nA Gentle Introduction to Type Classes and Relations in Coq\nの\nChapter 2 An Introductory Example: Computing xn\nの抜萃。\n@suharahiromichi\n*)\n\n(**\n配布ファイル typeclassesTut を make したのち、\nそのディレクトリの本ファイルを置いて実行する。\nなお、typeclassesTut を make には、\ncp V8.3/Matrics.v Mat.v して、Section名をMatに修正する。\nMakefileの _CoqProject のエントリを消す。\n*)\n\n(*\nA variation of Monoid.v, using Program Fixpoint instead of Function *)\n\n(**\nこれは、typeclassesTut/Monoid_prog.v をもとにしている。\nProgram Fixpoint を使い、Contextコマンドを使っている。*)\n\nSet Implicit Arguments.\n\nRequire Import ZArith.\nRequire Import Div2.\nRequire Import Program.\n(* typeclassesTut/V8.3/Matrics.v をrenameする。Section名も。 *)\nRequire Import Mat.\n\n(** Monoid モノイド\n- carrier (台) A\n- binary, associative operation 'dot' on A\n- neutral element 1 ∈ A for 'dot'\n *)\nClass Monoid {A : Type} (dot : A -> A -> A) (one : A) : Type :=\n  {\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  }.\nPrint Monoid.                        (* 値コンストラクタの指定を省くと、Build_Monoid になる。 *)\nAbout one_left.                      (* Arguments A, dot, one, Monoid are implicit *)\n(* Class ではなく、Record の場合は、dot one は implicit ではない。 *)\nAbout one_right.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(**\nZMultは、モノイド (Z,*,1) である。\n- 台は、Z (Implicit)\n- 二項演算は、Zmult\n- 単位元は、1\n*)\n(* Compute binary_power 2 100. で使われる。 *)\nInstance ZMult : Monoid Zmult 1.\nProof.\n  split; intros; ring.\nQed.\n(* Note that we used Qed because we consider a class of sort Prop. In some cases where\ninstances must store some informative constants, ending an instance construction with\nDefined may be necessary.  *)\nCheck ZMult : Monoid Z.mul 1.\n\n(* おまけ。 *)\nInstance Mult : Monoid mult 1%nat.\nProof.\n  split; intros.\n  now rewrite mult_assoc.\n  now rewrite mult_1_l.\n  now rewrite mult_1_r.\nQed.\nCheck Mult : Monoid mult 1%nat.\n(* これがあると、Check power.  が nat -> nat -> nat になる。\nでも、Z -> nat -> Z としても使える。 *)\n\nFixpoint power {A : Type} {dot : A -> A -> A} {one : A} {M : Monoid dot one}\n         (a : A)(n : nat) :=\n  match n with\n    | 0%nat => one\n    | S p => dot a (power a p)\n  end.\nCheck power.                                (* 無意味 *)\nAbout power.\nCheck power : Z -> nat -> Z.\nCompute power 2%Z 10 : Z.\nCheck power : nat -> nat -> nat.\nCompute power 2%nat 10 : nat.\nReset power.\n\nGeneralizable Variables A dot one.\n(**\nCoq Reference Manual から\n2.7.20 Implicit generalization\n\nImplicit generalization is an automatic elaboration of a statement with free variables\ninto a closed statement where these variables are quantified explicitly. Implicit\ngeneralization is done inside binders starting with a ` and terms delimited by `{} and\n`(), always introducing maximally inserted implicit arguments for the generalized\nvariables. Inside implicit generalization delimiters, free variables in the current\ncontext are automatically quantified using a product or a lambda abstraction to generate a\nclosed term. In the following statement for example, the variables n and m are\nautamatically generalized and become explicit arguments of the lemma as we are using `():\n*)\n(* `{} は、引数を{}で囲むのときと同様に implicit argument になる。 *)\n\nFixpoint power `{Monoid A dot one} (a : A) (n : nat) := (* 「`」 でコンテキスト *)\n  match n with\n    | 0%nat => one\n    | S p => dot a (power a p)\n  end.\nCheck power.                                (* 無意味 *)\nCheck power : nat -> nat -> nat.\nCheck power : Z -> nat -> Z.\nAbout power.\n\nSection binary_power. \n  Context `{M : Monoid A dot one}.          (* コンテキスト *)\n(**\nCoq Reference Manual から\n19.4  Sections and contexts\n\nTo ease the parametrization of developments by type classes, we provide a new way to\nintroduce variables into section contexts, compatible with the implicit argument\nmechanism. The new command works similarly to the Variables vernacular (see 1.3.1), except\nit accepts any binding context as argument.\n*)  \n  Program Fixpoint binary_power_mult (acc : A) (x : A) (n : nat) {measure n} : A :=\n    (* Implicit generalization によって、\n       (A:Type) (dot:A->A->A) (one:A) (M: @Monoid A dot one)\n       が省かれている。 *)\n    (* acc * (x ** n) *) \n    let M' := M in\n    match n with\n      | 0%nat => acc\n      | _ => if  Even.even_odd_dec n\n             then\n               binary_power_mult  acc (dot x x) (div2 n)\n             else\n               binary_power_mult  (dot acc  x) (dot  x  x) (div2 n)\n    end.\n  Obligations.\n  Next Obligation.                          (* Obligation 1 *)\n    set (M' := M); apply lt_div2.\n    apply neq_0_lt in H.\n    apply H.\n    Defined.\n  Next Obligation.                          (* Obligation 2 と 3 *)\n    set (M' := M); apply lt_div2; auto with arith.\n    Defined.\n  Check binary_power_mult.                  (* A -> A -> nat -> A *)\n(*\n  証明を1行にまとめると、以下になる。Next Obligation も要らないので、注意。\n  Solve Obligations using program_simpl; set (M' := M); apply lt_div2; auto with arith.\n *)\n\n  Import WfExtensionality.\n  Lemma binary_power_mult_equation (acc x:A)(n:nat) :\n    binary_power_mult acc x n =\n    match n with\n      | 0%nat => acc\n      | _ => if Even.even_odd_dec n\n             then\n               binary_power_mult acc (dot x x) (div2 n)\n             else\n               binary_power_mult (dot acc  x) (dot  x  x) (div2 n)\n    end.\n  Proof.\n    unfold binary_power_mult at 1.\n    on_call binary_power_mult_func\n            ltac:(fun c => \n                    unfold_sub @binary_power_mult_func c;\n                    fold binary_power_mult_func).\n    simpl. destruct n; reflexivity.\n  Qed.\nCheck binary_power_mult : A -> A -> nat -> A.\nEnd binary_power.\nCheck binary_power_mult.                    (* 無意味 *)\nAbout binary_power_mult.\nCheck binary_power_mult : Z -> Z -> nat -> Z.\nCheck binary_power_mult : nat -> nat -> nat -> nat.\n\nDefinition binary_power `{Monoid A dot one} x n :=\n  binary_power_mult one x n.\n\n(************************************)\n(* First example : モノイド (Z,*,1) *)\n(************************************)\n(* ZMult をここで使う。 *)\nCompute binary_power 2 100.\n(* = 1267650600228229401496703205376 : Z *)\n\n\nGoal forall n : Z, 1 * (n * 1) = n.\nProof.\n  intro n.\n  rewrite one_left.\n  rewrite one_right.\n  trivial.\nSave XX.                                    (* Lemma XXX : ... Qed. とおなじ。 *)\n\n(***********************************)\n(* Second example : 2 x 2 Matrices *)\n(***********************************)\n(* M2 と M2_mult と Id2 と M2_eq_intros は、Mat.v で定義 *)\nSection M2_def.\n  Variables (A : Type)\n            (zero one : A) \n            (plus : A -> A -> A)            (* (plus mult minus : A->A->A) *)\n            (mult : A -> A -> A)\n            (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  Variable rth : ring_theory zero one plus mult minus sym (@eq A).\n  (* セクションの外で、M2_Monoid を使うためには、rth に値を与えないといけない。 *)\n\n  Print ring_theory.\n  (* ring タクティクで、ここで見えるring_theory のセレクタが使えるようになる。 *)\n  Add Ring Aring : rth.                     (* for ring. *)\n  \n(**\nM2_Monoidは、以下のモノイドである。\n- 台は M2 Z、Z の 2×2の行列\n- 二項演算は、 \nc00 := plus (mult (c00 m) (c00 m')) (mult (c01 m) (c10 m'));\nc01 := plus (mult (c00 m) (c01 m')) (mult (c01 m) (c11 m'));\nc10 := plus (mult (c10 m) (c00 m')) (mult (c11 m) (c10 m'));\nc11 := plus (mult (c10 m) (c01 m')) (mult (c11 m) (c11 m'))\n- 単位元は、\nc00 := one; c01 := zero; c10 := zero; c11 := one\n*)\n\n  Check @M2_mult A : (A -> A -> A) -> (A -> A -> A) -> M2 A -> M2 A -> M2 A.\n  (* (plus : A -> A -> A) (mult : A -> A -> A) *)\n  Check M2_mult plus mult : M2 A -> M2 A -> M2 A. (* dot *)\n  \n  Check @Id2 A : A -> A -> M2 A. (* (zero : A) (one : A) *)\n  Check Id2 0 1 : M2 A.                            (* one *)\n  \n  Global Instance M2_Monoid : Monoid (M2_mult plus mult) (Id2 0 1).\n  Proof.\n    split.\n    destruct x; destruct y; destruct z; simpl.\n    unfold M2_mult; apply M2_eq_intros; simpl; ring. (* rth *)\n    destruct x; simpl;\n    unfold M2_mult; apply M2_eq_intros; simpl; ring. (* rth *)\n    destruct x; simpl;\n    unfold M2_mult; apply M2_eq_intros; simpl; ring. (* rth *)\n  Qed.\n  (* セクションの外で、M2_Monoid を使うためには、rth に値を与えないといけない。 *)\n  About M2_Monoid.                                  (* Monoid ...  *)\nEnd M2_def.\n\nCheck M2_mult Z.add Z.mul : M2 Z -> M2 Z -> M2 Z. (* dot *)\nCheck Id2 0 1 : M2 Z.                             (* one *)\n(* セクションの外で、M2_Monoid を使うためには、rth に値を与えないといけない。 *)\nAbout M2_Monoid.                                  (* ring_theory ... -> Monoid ...  *)\n\n(* Zth を rth に与える。Zth は M2_defセクションの rth : ring ... に与えられる。 *)\nCheck Zth : ring_theory 0 1 Z.add Z.mul Z.sub Z.opp eq.\nPrint Zth.\nCheck M2_Monoid Zth : Monoid _ _.\nCheck M2_Monoid Zth : Monoid (M2_mult Z.add Z.mul) (Id2 0 1).\nCheck @M2_Monoid Z 0%Z 1%Z Zplus Zmult Zminus Z.opp Zth :\n  Monoid (M2_mult Z.add Z.mul) (Id2 0 1).\n(* これは、M2Z と等しい *)\n\nInstance M2Z' : Monoid (M2_mult Z.add Z.mul) (Id2 0 1) := M2_Monoid Zth.\n(* テキストの方法に記載されたのは、 *)\nInstance M2Z : Monoid _ _ := M2_Monoid Zth.\n\n(* Zthを使わずに、自力で証明する場合 *)\n(*\nInstance M2Z'' : Monoid (M2_mult Z.add Z.mul) (Id2 0 1) : Prop.\nProof.\n  split.\n  - intros x y z.                           (* M2_mult の結合則 *)\n    apply M2_eq_intros; simpl; ring.\n    \n  - intros x.                               (* M2_mult の左単位元 *)\n    Check M2_eq_intros.\n    apply M2_eq_intros; unfold M2_mult; simpl.\n    case (c00 x); [ring | reflexivity | reflexivity].\n    case (c01 x); [ring | reflexivity | reflexivity].\n    case (c10 x); [ring | reflexivity | reflexivity].\n    case (c11 x); [ring | reflexivity | reflexivity].\n\n  - intros x.                               (* M2_mult の右単位元 *)\n    apply M2_eq_intros; unfold M2_mult; simpl; ring.\nQed.\n*)\nCheck M2Z : Monoid (M2_mult Z.add Z.mul) (Id2 0 1).\nCheck ZMult : Monoid Z.mul 1.                (* 比較 *)\n\n  \n\nCompute power (Build_M2 1 1 1 0) 40.         (* M2Z をつかう。 *)\n(*\n行列の掛け算を40回繰り返す。\n[1 1]  [1 1]  [1 1] ..... [1 1]  \n[1 0]  [1 0]  [1 0]       [1 0]\nc00 := 165580141;\nc01 := 102334155;\nc10 := 102334155;\nc11 := 63245986\n*)\n\nDefinition fibonacci (n:nat) :=\n  c00 (power (Build_M2  1 1 1 0) n).\nCompute fibonacci 20.\nCompute (c00 (power (Build_M2  1 1 1 0) 20)).\n\n(** 一般的事項を証明する。 *)\n(* Generic study of power functions *)\n(** 最終的に、power と binary_power が等価なことを証明する。 *)\nSection About_power.\n\n  Require Import Arith.\n  Context `(M : Monoid A dot one ).\n\n  Ltac 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  (* \"+\" はnat のplusである。power : A -> nat -> A だから。 *)\n  \n  Lemma power_x_plus :\n    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 :\n    forall x n p, x ** n * x ** p = x ** p * x ** n. \n  Proof.\n    intros x n p; power_simpl; rewrite (plus_comm n p); trivial.\n  (* plus_comm は、nat のそれ。 *)\n  Qed.\n  \n  Lemma power_commute_with_x :\n    forall x 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 :\n    forall x n p,  (x ** n) ** p = x ** (p * n).\n  Proof.\n    induction p; simpl; [| rewrite power_x_plus; rewrite IHp]; trivial.\n  Qed.\n \n  Lemma power_S :\n    forall x n, x *  x ** n = x ** S n.\n  Proof.\n    intros; simpl; auto.\n  Qed.\n\n  Lemma sqr : forall x, x ** 2 =  x * x.\n  Proof.\n    simpl; intros; monoid_simpl; trivial.\n  Qed.\n\n  Ltac 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 :\n    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 binary_power_mult_ok :\n    forall n a x,  binary_power_mult a x n = a * x ** n.\n  Proof.\n    intro n; pattern n;apply lt_wf_ind.\n    clear n; intros n Hn; destruct n.\n    intros; simpl; monoid_simpl; trivial.\n    intros; rewrite binary_power_mult_equation. \n    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.\n  Qed.\n\n  Lemma binary_power_ok :\n    forall (x:A) (n:nat), binary_power x n = x ** n.\n  Proof.\n    intros n x; unfold binary_power; rewrite binary_power_mult_ok;\n    monoid_simpl; auto.\n  Qed.\n  About binary_power_ok.\nEnd About_power.\nAbout binary_power_ok.\n\nImplicit Arguments binary_power_ok [A dot one M].\nAbout binary_power_ok.\n\nCheck binary_power_ok 2 20.\n\nLet Mfib := Build_M2 1 1 1 0.\n\nCheck binary_power_ok Mfib 56 : binary_power Mfib 56 = power Mfib 56.\nCheck binary_power_ok (Build_M2 1 1 1 0) 40 :\n  binary_power {| c00 := 1; c01 := 1; c10 := 1; c11 := 0 |} 40 =\n  power {| c00 := 1; c01 := 1; c10 := 1; c11 := 0 |} 40.\n\nEval vm_compute in power 2 5.               (* 35 *)\n\n(** 可換モノイド、アーベルモノイド *)\n(** モノイド M に可換則を追加して得られる。 *)\nClass Abelian_Monoid `(M : Monoid ):=\n  {\n    dot_comm : forall x y, dot x y = dot y x\n  }.\nPrint Abelian_Monoid.\n\n(**\nZMult_Abelian は、\nZMultモノイド（整数積のモノイド）に可換則を追加したもの。\n *)\nInstance ZMult_Abelian : Abelian_Monoid ZMult.\nProof.\n  split. \n  exact Zmult_comm.\nQed.\n\n(**\nおまけとして (x * y)^n = x^n * y^n を証明する。\n*)\nSection Power_of_dot.\n  Context `{M : Monoid A} {AM : Abelian_Monoid M}.\n \n  Theorem power_of_mult :\n    forall n x y, power (dot x y)  n =  dot (power x n) (power y n). \n  Proof.\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.\n  Qed.\nEnd Power_of_dot.\n\nCheck power_of_mult 3 4 5.\n(* : power (4 * 5) 3 = power 4 3 * power 5 3 *)\n\nCheck power (Build_M2  1 1 1 0) 3.\nCompute power (Build_M2 1 1 1 0) 3.\nCheck power_of_mult 3 (Build_M2  1 1 1 0) (Build_M2  1 1 1 0).\n(* dot が ?204 のままなのは、なぜだろう。 *)\n\n(* END *)\n\n(* 補足 *)\n(* power が polymorphic type な関数のとき、Check の結果は一定ではない。 *)\nCheck power.                                (* この結果に惑わされてはいけない。 *)\nAbout power.                                (* こちらのほうを見る習慣をつけよう。 *)\n\n(* ZMult モノイド *)\nAbout ZMult.\nCheck power : Z -> nat -> Z.\nCompute power 2%Z 10 : Z.\nCheck @power Z Zmult 1%Z ZMult : Z -> nat -> Z.\nCompute @power Z Zmult 1%Z ZMult 2%Z 10 : Z.\n\n(* Mult モノイド *)\nAbout Mult.\nCheck power : nat -> nat -> nat.\nCompute power 2%nat 10 : nat.\nCheck @power nat mult 1%nat Mult : nat -> nat -> nat.\nCompute @power nat mult 1%nat Mult 2%nat 10 : nat.\n\n(* M2Z モノイド *)\nAbout M2Z.\nCheck power : M2 Z -> nat -> M2 Z.\nCompute power (Build_M2 1 1 1 0) 40 : M2 Z.\nCheck @power (M2 Z) (@M2_mult Z Zplus Zmult) (@Id2 Z 0 1) M2Z :\n  M2 Z -> nat -> M2 Z.\nCompute @power (M2 Z) (@M2_mult Z Zplus Zmult) (@Id2 Z 0%Z 1%Z) M2Z\n        (@Build_M2 Z 1%Z 1%Z 1%Z 0%Z) 40%nat : M2 Z.\nCompute @power (M2 Z) (M2_mult Zplus Zmult) (Id2 0 1) M2Z\n        (Build_M2 1 1 1 0) 40 : M2 Z.\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/coq_gitcrc_2_Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.7829329971800828}}
{"text": "(* week-13_fac.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\nDefinition specification_of_factorial (fac : nat -> nat) :=\n  fac 0 = 1\n  /\\\n  forall n' : nat,\n    fac (S n') = (S n') * (fac n').\n\nTheorem there_is_only_one_factorial :\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.\n  unfold specification_of_factorial.\n  intros [S_fac1_0 S_fac1_S] [S_fac2_0 S_fac2_S] n.\n  induction n as [ | n' IHn'].\n\n  rewrite -> S_fac1_0.\n  rewrite -> S_fac2_0.\n  reflexivity.\n\n  rewrite -> S_fac1_S.\n  rewrite -> S_fac2_S.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n \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  (candidate 4 =n= 24) \n  && \n  (candidate 5 =n= 120)\n  .\n\n(* ********** *)\n\n(* The factorial function in direct style: *)\n\nFixpoint fac_ds (n : nat) : nat :=\n  match n with\n    | O => 1\n    | S n' => (S n') * (fac_ds n')\n  end.\n\nCompute (test_fac fac_ds).\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fac_ds_0 :\n  fac_ds 0 = 1.\nProof.\n  unfold_tactic fac_ds.\nQed.\n\nLemma unfold_fac_ds_S :\n  forall n' : nat,\n    fac_ds (S n') = S n' * fac_ds n'.\nProof.\n  unfold_tactic fac_ds.\nQed.\n\n(* Main definition: *)\n\nDefinition fac_v1 (n : nat) : nat :=\n  fac_ds n.\n\nCompute (test_fac fac_v1).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fac_v1 :\n  forall n : nat,\n    fac_v1 n = fac_ds n.\nProof.\n  unfold_tactic fac_v1.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fac_v1_satisfies_the_specification_of_factorial :\n  specification_of_factorial fac_v1.\nProof.\n  unfold specification_of_factorial.\n  split.\n\n  rewrite -> unfold_fac_v1.\n  rewrite -> unfold_fac_ds_0.\n  reflexivity.\n\n  intro n'.\n  rewrite -> (unfold_fac_v1 (S n')).\n  rewrite -> (unfold_fac_v1  n').\n  rewrite -> unfold_fac_ds_S.\n  reflexivity.\nQed.  \n(* ********** *)\n\n(* The factorial function in continuation-passing style: *)\n\nFixpoint fac_cps (ans : Type) (n : nat) (k : nat -> ans) : ans :=\n  match n with\n    | O => k 1\n    | S n' => fac_cps ans n' (fun v => k (S n' * v))\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fac_cps_0 :\n  forall (ans : Type) (k : nat -> ans),\n    fac_cps ans 0 k = k 1.\nProof.\n  unfold_tactic fac_cps.\nQed.\n\nLemma unfold_fac_cps_S :\n  forall (ans : Type) (n' : nat) (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\n(* Lemma about resetting the continuation: *)\n\nLemma about_fac_cps :\n  forall (n : nat) (ans : Type) (k : nat -> ans),\n    fac_cps ans n k = k (fac_cps nat n (fun v => v)).\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  intros ans k.\n  rewrite ->2 unfold_fac_cps_0.\n  reflexivity.\n\n  intros ans k.\n  rewrite ->2 unfold_fac_cps_S.\n  rewrite -> IHn'.\n  rewrite -> (IHn' nat (fun v : nat => S n' * v)).\n  reflexivity.\nQed.\n\n(* Main definition: *)\n\nDefinition fac_v2 (n : nat) : nat :=\n  fac_cps nat n (fun v => v).\n\nCompute (test_fac fac_v2).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fac_v2 :\n  forall n : nat,\n    fac_v2 n = fac_cps nat n (fun v => v).\nProof.\n  unfold_tactic fac_v2.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fac_v2_fits_the_specification_of_factorial :\n  specification_of_factorial fac_v2.\nProof.\n  unfold specification_of_factorial.\n  split.\n  rewrite -> unfold_fac_v2.\n  rewrite -> unfold_fac_cps_0.\n  reflexivity.\n\n  intro n'.\n  rewrite ->2 unfold_fac_v2.\n  rewrite -> unfold_fac_cps_S.\n  rewrite -> about_fac_cps.\nreflexivity.\nQed.\n(* ********** *)\n\n(* end of week-13_fac.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_fac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7828940570767622}}
{"text": "(* ***************************************************************** *)\n(*                                                                   *)\n(* Released: 2021/03/29.                                             *)\n(* Due: 2021/04/02, 23:59:59, CST.                                   *)\n(*                                                                   *)\n(* 0. Read instructions carefully before start writing your answer.  *)\n(*                                                                   *)\n(* 1. You should not add any hypotheses in this assignment.          *)\n(*    Necessary ones have been provided for you.                     *)\n(*                                                                   *)\n(* 2. In order to check whether you have finished all tasks or not,  *)\n(*    just see whether all \"Admitted\" has been replaced.             *)\n(*                                                                   *)\n(* 3. You should submit this file (Assignment4.v) on CANVAS.         *)\n(*                                                                   *)\n(* 4. Only valid Coq files are accepted. In other words, please      *)\n(*    make sure that your file does not generate a Coq error. A      *)\n(*    way to check that is: click \"compile buffer\" for this file     *)\n(*    and see whether an \"Assignment4.vo\" file is generated.         *)\n(*                                                                   *)\n(* 5. Do not copy and paste others' answer.                          *)\n(*                                                                   *)\n(* 6. Using any theorems and/or tactics provided by Coq's standard   *)\n(*    library is allowed in this assignment, if not specified.       *)\n(*                                                                   *)\n(* 7. When you finish, answer the following question:                *)\n(*                                                                   *)\n(*      Who did you discuss with when finishing this                 *)\n(*      assignment? Your answer to this question will                *)\n(*      NOT affect your grade.                                       *)\n(*      (* FILL IN YOUR ANSWER HERE AS COMMENT *)                    *)\n(*                                                                   *)\n(* ***************************************************************** *)\n\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import PL.Imp PL.RTClosure.\nImport Abstract_Pretty_Printing.\n\n(* ################################################################# *)\n(** * Task 1: Understanding Inductive Definition *)\n\nModule Task1.\n\n(** Consider potential integer expression transformations defined by the\n    following relation [optimize]. *)\n\nInductive optimize: aexp -> aexp -> Prop :=\n| optimize_plus_0_l: forall a, optimize (APlus 0 a) a\n| optimize_plus_0_r: forall a, optimize (APlus a 0) a\n| optimize_minus_0_r: forall a, optimize (AMinus a 0) a\n| optimize_mult_1_l: forall a, optimize (AMult 1 a) a\n| optimize_mult_1_r: forall a, optimize (AMult a 1) a\n| optimize_mult_0_l: forall a, optimize (AMult 0 a) 0\n| optimize_mult_0_r: forall a, optimize (AMult a 0) 0\n| optimize_congr_APlus: forall a1 a2 a3 a4,\n    optimize a1 a2 ->\n    optimize a3 a4 ->\n    optimize (a1 + a3) (a2 + a4)\n| optimize_congr_AMinus: forall a1 a2 a3 a4,\n    optimize a1 a2 ->\n    optimize a3 a4 ->\n    optimize (a1 - a3) (a2 - a4)\n| optimize_congr_AMult: forall a1 a2 a3 a4,\n    optimize a1 a2 ->\n    optimize a3 a4 ->\n    optimize (a1 * a3) (a2 * a4)\n| optimize_refl: forall a,\n    optimize a a\n| optimize_trans: forall a1 a2 a3,\n    optimize a1 a2 ->\n    optimize a2 a3 ->\n    optimize a1 a3\n.\n\n(** We call this relation [optimize] since it represents some kind of constant\n    related optimization. You first task is to prove some of its instances. *)\n\n(** **** Exercise: 1 star, standard: (optimize_sample1) *)\n\nExample optimize_sample1: forall X Y: var,\n  optimize (X + 0 * Y) X.\nProof.\n  intros.\n  eapply optimize_trans.\n  2: apply optimize_plus_0_r.\n  apply optimize_congr_APlus.\n  + apply optimize_refl.\n  + apply optimize_mult_0_l.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard: (optimize_sample2) *)\n\nExample optimize_sample2: forall X Y: var,\n  optimize ((0 * X) * 1) 0.\nProof.\n  intros.\n  eapply optimize_trans.\n  2: apply optimize_mult_0_l.\n  apply optimize_congr_AMult.\n  + apply optimize_mult_0_l.\n  + apply optimize_refl.\nQed.\n(** [] *)\n\n(** The next task for you is to prove [optimize] sound. Hint: you may need to\n    use some properties about expression equivalence. You can use Coq's [Search]\n    command to find those we have proved. For example, you can try\n\n    [[\n         Search APlus aexp_equiv.\n    ]]\n*)\n\n(** **** Exercise: 3 stars, standard: (optimize_sound) *)\n\nTheorem optimize_sound: forall a1 a2,\n  optimize a1 a2 ->\n  aexp_equiv a1 a2.\nProof.\n  intros.\n  induction H.\n  + apply zero_plus_equiv.\n  + apply plus_zero_equiv.\n  + apply minus_zero_equiv.\n  + apply one_mult_equiv.\n  + apply mult_one_equiv.\n  + apply zero_mult_equiv.\n  + apply mult_zero_equiv.\n  + apply APlus_congr.\n    apply IHoptimize1.\n    apply IHoptimize2.\n  + apply AMinus_congr.\n    apply IHoptimize1.\n    apply IHoptimize2.\n  + apply AMult_congr.\n    apply IHoptimize1.\n    apply IHoptimize2.\n  + reflexivity.\n  + rewrite IHoptimize1.\n    rewrite IHoptimize2.\n    reflexivity.\nQed.\n(** [] *)\n\nEnd Task1.\n\n(* ################################################################# *)\n(** * Task 2: Understanding Steps *)\n\nModule Task2.\n\n(** Prove the following step relations. *)\n\n(** **** Exercise: 1 star, standard: (step_sample1) *)\n\nExample step_sample1: forall (X: var) (st: state),\n  st X = 5 ->\n  astep st ((1 + X) * 2) ((1 + 5) * 2).\nProof.\n  intros.\n  apply AS_Mult1.\n  apply AS_Plus2.\n  { apply AH_num. }\n  rewrite <- H.\n  apply AS_Id.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard: (step_sample2) *)\n\nExample step_sample2: forall (X: var) (st: state),\n  cstep (If (0 <= (1 + 5) * 2) Then X ::= X - 1 Else Skip EndIf, st)%imp\n        (If (0 <= 6 * 2) Then X ::= X - 1 Else Skip EndIf, st)%imp.\nProof.\n  intros.\n  apply CS_IfStep.\n  apply BS_Le2.\n  { apply AH_num. }\n  apply AS_Mult1.\n  apply AS_Plus.\nQed.\n(** [] *)\n\nEnd Task2.\n\n(* ################################################################# *)\n(** * Task 3: Alternative Small Step Semantics *)\n\nModule Task3.\nLocal Open Scope imp.\n\n(** Alice wrote three alternative definitions of [cstep]. Her purpose is to\n    avoid administrative steps, i.e. the step from [Skip;; c] to [c]. These\n    three definitions are [A1.cstep], [A2.cstep] and [A3.cstep] as follows.\n    Her definitions only differ from the original [cstep] definition at the\n    places of [CS_Seq]. *)\n\nModule A1.\n\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AssStep : forall st X a a',\n      astep st a a' ->\n      cstep (CAss X a, st) (CAss X a', st)\n  | CS_Ass : forall st1 st2 X n,\n      st2 X = n ->\n      (forall Y, X <> Y -> st1 Y = st2 Y) ->\n      cstep (CAss X (ANum n), st1) (Skip, st2)\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      cstep (c1, st) (c1', st') ->\n      cstep (c1 ;; c2 , st) (c1' ;; c2, st')\n  | CS_Seq : forall st c2 st' c2',\n      cstep (c2, st) (Skip ;; c2', st') ->\n      cstep (c2, st) (c2', st')   (* <- This is different. *)\n  | CS_IfStep : forall st b b' c1 c2,\n      bstep st b b' ->\n      cstep\n        (If b  Then c1 Else c2 EndIf, st)\n        (If b'  Then c1 Else c2 EndIf, st)\n  | CS_IfTrue : forall st c1 c2,\n      cstep (If BTrue Then c1 Else c2 EndIf, st) (c1, st)\n  | CS_IfFalse : forall st c1 c2,\n      cstep (If BFalse Then c1 Else c2 EndIf, st) (c2, st)\n  | CS_While : forall st b c,\n      cstep\n        (While b Do c EndWhile, st)\n        (If b Then (c;; While b Do c EndWhile) Else Skip EndIf, st).\n\nEnd A1.\n\nModule A2.\n\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AssStep : forall st X a a',\n      astep st a a' ->\n      cstep (CAss X a, st) (CAss X a', st)\n  | CS_Ass : forall st1 st2 X n,\n      st2 X = n ->\n      (forall Y, X <> Y -> st1 Y = st2 Y) ->\n      cstep (CAss X (ANum n), st1) (Skip, st2)\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      cstep (c1, st) (c1', st') ->\n      cstep (c1 ;; c2 , st) (c1' ;; c2, st')\n  | CS_Seq : forall st c2 st' c2',\n      cstep (c2, st) (c2', st') ->\n      cstep (Skip ;; c2, st) (c2', st')   (* <- This is different. *)\n  | CS_IfStep : forall st b b' c1 c2,\n      bstep st b b' ->\n      cstep\n        (If b  Then c1 Else c2 EndIf, st)\n        (If b'  Then c1 Else c2 EndIf, st)\n  | CS_IfTrue : forall st c1 c2,\n      cstep (If BTrue Then c1 Else c2 EndIf, st) (c1, st)\n  | CS_IfFalse : forall st c1 c2,\n      cstep (If BFalse Then c1 Else c2 EndIf, st) (c2, st)\n  | CS_While : forall st b c,\n      cstep\n        (While b Do c EndWhile, st)\n        (If b Then (c;; While b Do c EndWhile) Else Skip EndIf, st).\n\nEnd A2.\n\nModule A3.\n\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AssStep : forall st X a a',\n      astep st a a' ->\n      cstep (CAss X a, st) (CAss X a', st)\n  | CS_Ass : forall st1 st2 X n,\n      st2 X = n ->\n      (forall Y, X <> Y -> st1 Y = st2 Y) ->\n      cstep (CAss X (ANum n), st1) (Skip, st2)\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      cstep (c1, st) (c1', st') ->\n      cstep (c1 ;; c2 , st) (c1' ;; c2, st')\n  | CS_Seq : forall st c1 c2 st' c2',\n      remove_skip c1 = CSkip ->\n      cstep (c2, st) (c2', st') ->\n      cstep (c1 ;; c2, st) (c2', st')   (* <- This is different. *)\n  | CS_IfStep : forall st b b' c1 c2,\n      bstep st b b' ->\n      cstep\n        (If b  Then c1 Else c2 EndIf, st)\n        (If b'  Then c1 Else c2 EndIf, st)\n  | CS_IfTrue : forall st c1 c2,\n      cstep (If BTrue Then c1 Else c2 EndIf, st) (c1, st)\n  | CS_IfFalse : forall st c1 c2,\n      cstep (If BFalse Then c1 Else c2 EndIf, st) (c2, st)\n  | CS_While : forall st b c,\n      cstep\n        (While b Do c EndWhile, st)\n        (If b Then (c;; While b Do c EndWhile) Else Skip EndIf, st).\n\nEnd A3.\n\n(** But she is not sure, on what extent these [cstep] are well-defined\n    semantics. Your task is to give her an answer using the following\n    examples. *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** Which alternative semantics define a program execution process as follows?\n\n    - 1. [A1.cstep]\n\n    - 2. [A2.cstep]\n\n    - 3. [A3.cstep]\n\n    The execution process:\n\n    [[\n        Skip;; Y ::= X, st -->\n        Y ::= 1, st\n    ]]\n\n    where [st X = 1].\n\n    Remark: Your answer should be an ascending list of integers (which can be\n    an empty list, a list with singleton element, or a list with more than one\n    element, e.g. [], [1;3], [2], [1;2;3]). *)\n\nDefinition my_choice1: list Z := [2; 3].\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** Which alternative semantics define a program execution process as follows?\n\n    - 1. [A1.cstep]\n\n    - 2. [A2.cstep]\n\n    - 3. [A3.cstep]\n\n    The execution process:\n\n    [[\n        (Y ::= 1;; Skip);; X ::= 0, st -->\n        (Skip;; Skip);; X ::= 0, st' -->\n        Skip, st'' -->\n    ]]\n\n    where [st X = st' X = 1], [st' Y = st'' Y = 1] and all other variables on\n    [st], [st'], [st''] have value [0].\n\n    Remark: Your answer should be an ascending list of integers. *)\n\nDefinition my_choice2: list Z := [3].\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\n(** **** Exercise: 2 stars, standard *)\n\n(** Which alternative semantics define a program execution process as follows?\n\n    - 1. [A1.cstep]\n\n    - 2. [A2.cstep]\n\n    - 3. [A3.cstep]\n\n    The execution process:\n\n    [[\n        (Y ::= 1;; Skip);; X ::= 0, st -->\n        X ::= 0, st' -->\n        Skip, st'' -->\n    ]]\n\n    where [st X = st' X = 1], [st' Y = st'' Y = 1] and all other variables on\n    [st], [st'], [st''] have value [0].\n\n    Remark: Your answer should be an ascending list of integers. *)\n\nDefinition my_choice3: list Z := [1].\n(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *)\n(** [] *)\n\nEnd Task3.\n\n(* ################################################################# *)\n(** * Task 4: Understanding Simulation *)\n\nModule Task4.\nImport Task3.\nLocal Open Scope imp.\n\n(** In this task, you need to prove a simulation between our original small step\n    semantics [cstep] and Alice's third alternative [A3.cstep] (which is defined\n    by [A3.CS_AssStep], [A3.CS_Ass], etc.). *)\n\nInductive match_com: com -> com -> Prop :=\n| MatRefl: forall c, match_com c c\n| MatSkipSeq: forall c1_1 c1_2 c2_2,\n    remove_skip c1_1 = CSkip ->\n    match_com c1_2 c2_2 ->\n    match_com (c1_1 ;; c1_2) c2_2\n| MatSeq: forall c1_1 c1_2 c2_1,\n    match_com c1_1 c2_1 ->\n    match_com (c1_1 ;; c1_2) (c2_1 ;; c1_2).\n\nDefinition A3cstep_or_not (X Y: com * state): Prop :=\n  X = Y \\/ A3.cstep X Y.\n\n(** We provide the definition of [match_com] for you. The idea is, if\n    [match_com c1 c2], then [c1] has more [Skip] on the left than [c2]. Thus, \n    [c1]'s execution via [A3.cstep] can eliminate those left-side skip in one\n    step in the future, and simulate [c2]'s execution via [cstep], i.e.\n\n    [[\n        forall c1 c2 c2' st st',\n          match_com c1 c2 ->\n          cstep (c2, st) (c2', st') ->\n          exists c1',\n            match_com c1' c2' /\\\n            A3cstep_or_not (c1, st) (c1', st').\n    ]]\n\n    The following auxiliary lemma may be help! Prove it first. *)\n\n(** **** Exercise: 2 stars, standard *)\n\nLemma match_com_skip_spec: forall c,\n  match_com c Skip ->\n  remove_skip c = Skip.\nProof.\n  assert (forall c1 c2, match_com c1 c2 -> c2 = Skip -> remove_skip c1 = Skip).\n  2: { intros; eapply H; eauto. }\n  intros.\n  induction H; simpl.\n  + rewrite H0.\n    reflexivity.\n  + rewrite H.\n    apply IHmatch_com.\n    rewrite H0.\n    reflexivity.\n  + discriminate H0.\nQed.\n\n(** **** Exercise: 4 stars, standard, optional *)\n\n(** In order to prove the simulation property, you must be careful when choosing\n    your proof strategy. There are mainly three candidates:\n\n      - by induction over the proof of [match_com c1 c2],\n\n      - by induction over the proof of [cstep (c2, st) (c2', st')],\n\n      - by induction over the structure of [c1] (or [c2], [c2']).\n\n    Make sure to find a good one before start typing your Coq proofs.\n\n    Remark: this is an optional task, you do not lose points if you cannot solve\n    it but you will get additional points if you complete it. *)\n\nTheorem cstep_simulate_cstep: forall c1 c2 c2' st st',\n  match_com c1 c2 ->\n  cstep (c2, st) (c2', st') ->\n  exists c1',\n    match_com c1' c2' /\\ A3cstep_or_not (c1, st) (c1', st').\nProof.\n(* FILL IN HERE *) Admitted.\n  \nEnd Task4.\n\n(* 2021-03-29 18:48 *)\n", "meta": {"author": "junqi-xie-learning", "repo": "CS2603-Assignments", "sha": "1adb0494e529563eceb842cc4d4df7a6ece1eb27", "save_path": "github-repos/coq/junqi-xie-learning-CS2603-Assignments", "path": "github-repos/coq/junqi-xie-learning-CS2603-Assignments/CS2603-Assignments-1adb0494e529563eceb842cc4d4df7a6ece1eb27/Assignment4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8872045817875224, "lm_q1q2_score": 0.7828940462154125}}
{"text": "Require Import ZArith.\nRequire Import Arith.\n\nOpen Scope Z_scope.\n\nFixpoint sum_f (f:nat -> Z) (n:nat)  : Z :=\n  match n with\n  | O => f O\n  | S p => sum_f f p + f n\n  end.\n\nTheorem sum_n : forall n:nat, 2 * sum_f Z_of_nat n = \n                              Z_of_nat n * (Z_of_nat n + 1).\nProof.\n induction n as [| p IHp].\n -  reflexivity. \n -  lazy beta iota zeta delta [sum_f]; fold sum_f.\n     rewrite Zmult_plus_distr_r; rewrite IHp.\n     rewrite inj_S ; unfold Z.succ ; ring.\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/ch6_inductive_data/SRC/exo_sum_f.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509215, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7828412278125447}}
{"text": "From LF Require Export Tactics.\n\nCheck (3 = 3) : Prop.\nCheck (forall n m : nat, n + m = m + n) : Prop.\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : Prop.\nDefinition plus_claim_is_true : plus_claim.\nProof. reflexivity. Qed.\n\n(* Functions that return propositions are said to define\n   properties of their arguments. *)\nDefinition is_three (n : nat) : Prop := n = 3.\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. intros n m H. injection H as H1. apply H1. Qed.\n\n(* The equality operator `=` is a binary function that returns a Prop. *)\nCheck @eq : forall A : Type, A -> A -> Prop.\n\n(* Logical Connectives *)\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.\n       - apply HA.\n       - apply HB. Qed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof. intros n m. induction n.\n       - simpl. rewrite <- plus_n_O. reflexivity.\n       - simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity. Qed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof. intros n m H. split.\n       - induction n.\n         + reflexivity.\n         + discriminate H.\n       - induction m.\n         + reflexivity.\n         + rewrite -> plus_comm in H. discriminate H. Qed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof. intros n m H. destruct H as [Hn Hm].\n       rewrite Hn. rewrite Hm. reflexivity. Qed.\n\n(* Shortcut: *)\nLemma and_example2'' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof. intros n m [Hn Hm]. rewrite Hn. rewrite Hm. reflexivity. Qed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof. intros n m H. apply and_exercise in H.\n       destruct H as [Hn Hm]. rewrite Hn. reflexivity. Qed.\n\nLemma proj1 : forall P Q : Prop, P /\\ Q -> P.\nProof. intros P Q HPQ. destruct HPQ as [HP _]. apply HP. Qed.\n\nLemma proj2 : forall P Q : Prop, P /\\ Q -> Q.\nProof. intros P Q [_ HQ]. apply HQ. Qed.\n\nTheorem and_cummut : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof. intros P Q [HP HQ]. 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. intros P Q R [HP [HQ HR]]. split.\n       - split.\n         + apply HP.\n         + apply HQ.\n       - apply HR. Qed.\n\nLemma mult_n_0 : forall n : nat, n * 0 = 0.\nProof. intros n. induction n.\n       - reflexivity.\n       - simpl. rewrite -> IHn. reflexivity. Qed.\n\nLemma factor_is_0 :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof. intros n m [Hn |Hm].\n       - rewrite -> Hn. reflexivity.\n       - rewrite -> Hm. rewrite -> mult_n_0. reflexivity. Qed.\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof. intros A B HA. left. apply HA. Qed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof. intros [ | n'].\n       - left. reflexivity.\n       - right. reflexivity. Qed.\n\nLemma mult_is_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof. intros n m H. destruct n.\n       - left. reflexivity.\n       - right. destruct m.\n         + reflexivity.\n         + discriminate H. Qed.\n\nTheorem or_commut : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof. intros P Q H. inversion H as [HP | HQ].\n       - right. apply HP.\n       - left. apply HQ. Qed.\n", "meta": {"author": "brunoflores", "repo": "logical-foundations", "sha": "a394c40425bb7e15c746421f9b52826967174955", "save_path": "github-repos/coq/brunoflores-logical-foundations", "path": "github-repos/coq/brunoflores-logical-foundations/logical-foundations-a394c40425bb7e15c746421f9b52826967174955/theories/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8807970701552504, "lm_q1q2_score": 0.7828161465733279}}
{"text": "Lemma ind_ex1 : forall n : nat, n * 1 = n.\nintro.\nelim n.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nreflexivity.\nQed.\n\nFixpoint f (x : nat) {struct x} : nat :=\n  match x with\n  |0 => 1\n  |S x => 2 * f(x)\n  end.\nLemma ind_ex2 : f(10) = 1024.\nsimpl.\nreflexivity.\nQed.\n\nRequire Import Lists.List.\n\nOpen Scope list_scope.\nLemma ind_ex3 : forall (E : Type) (l : list E) (e : E),\n    rev(l ++ e :: nil) = e :: rev(l).\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHl.\nreflexivity.\nQed.\n\nLemma ind_ex4 : forall (E : Type) (l : list E), rev (rev l) = l.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nsimpl.\nrewrite ind_ex3.\nrewrite IHl.\nreflexivity.\nQed.\n\nRequire Import Classical.\n\nLemma auto_eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nintros.\ndecide equality.\nQed.\n\n\nLemma man_eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nintros.\ninduction m.\ninduction n.\nleft.\nreflexivity.\nintros.\ndestruct IHn.\nright.\nrewrite e.\ncongruence.\nright.\ncongruence.\ndestruct IHm.\nright.\nrewrite e.\napply n_Sn.\n\n\n\n\n\n\n\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/4types_inductifs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7828090412778589}}
{"text": "Add LoadPath \"lf/\".\nRequire Import numbers.\n\nTheorem plus_n_0: forall n : nat, n = n + 0.\n\nProof.\n  intros n.\n  induction n as [| n' IHn' ].\n    - reflexivity. (* n = 0 *)\n    - simpl.\n      rewrite <- IHn'.\n      reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem mult_0_r: forall n : nat, n * 0 = 0.\n\nProof.\n  intros.\n  induction n as [| n' IHn' ].\n    - reflexivity. (* n = 0 *)\n    - simpl.\n      rewrite -> IHn'.\n      reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem plus_n_Sm: forall n m : nat,\n  S (n + m) = n + (S m).\n\nProof.\n  intros.\n  induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem plus_comm: forall n m : nat,\n  n + m = m + n.\n\nProof.\n  intros n m.\n  induction n as [| n' IHn' ].\n  - rewrite -> plus_0_n. rewrite <- plus_n_0. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite ->  plus_n_Sm. reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem plus_assoc: forall n m p : nat,\n  n + (m + p) = (n + m) + p.\n\nProof.\n  intros.\n  induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\n  Qed.\n\n(* Exercise *)\nFixpoint double (n : nat) :=\n  match n with\n    | O => O\n    | S n' => S (S (double n'))\n  end.\n\nLemma double_plus: forall n, double n = n + n.\n\nProof.\n  intros.\n  induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\n  Qed.\n\n(* Exercise *)\nTheorem even_S: forall n : nat,\n  even (S n) = negb (even n).\n\nProof.\n  intros.\n  induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. rewrite -> negb_involutive. simpl. reflexivity.\n  Qed.\n", "meta": {"author": "qoelet", "repo": "sf-scribbles", "sha": "92bf7213eb27335de958dab621c95e4bbedb5212", "save_path": "github-repos/coq/qoelet-sf-scribbles", "path": "github-repos/coq/qoelet-sf-scribbles/sf-scribbles-92bf7213eb27335de958dab621c95e4bbedb5212/archive_/lf/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.782772614174817}}
{"text": "(** * The Stack Datatype\n \nThe Stack is the first data type defined in chapter 2 of PFDS.\n\nIts signature is defined as (in SML):\n\n<<\nsignature STACK = \nsig\n  type a Stack\n  \n  val empty       :: a Stack\n  val isEmpty     :: a Stack -> bool\n\n  val cons        :: a x a Stack -> a Stack\n  val head        :: a Stack -> a\n  val tail        :: a Stack -> a Stack\nend\n>>\n*)\n\n(** ----- *)\n\nRequire Import Bool Arith.\n\n(** ** The Implementation *)\n\n(** A stack is either empty, or it is constructed from a series of Cons.\n\n    That is, the list that would be expressed in Haskell as <<[1, 2, 3]>> would\n    be represented herein as [Cons nat 1 (Cons nat 2 (Cons nat 3 (Empty nat)))].\n *)\n\nInductive stack (T:Type) : Type :=\n  | Empty : stack T\n  | Cons : T -> stack T -> stack T.\n\n\n(** An empty stack is represented by the value Empty; therefore, an\n    implementation of isEmpty only needs to match that value.\n *)\n\nDefinition isEmpty T (s : stack T) : bool :=\n  match s with\n    | Empty => true\n    | _     => false\n  end.\n\n(** Retrieving the head of the list poses some interesting problems. The book\n    desires an exception be raised for the head of an empty list; however, a\n    formally verified program shouldn't have any erroneous conditions. There\n    is very likely a better way to express this in a definition, but this is\n    day 3 with the language. For now, an option property will suffice. This\n    returns None for an empty list, and Some value for the non-empty stack.\n *)\n\nDefinition head T (s : stack T) : option T :=\n  match s with\n    | Empty => None\n    | Cons s' _ => Some s'\n  end.\n\nDefinition tail T (s : stack T) : stack T :=\n  match s with\n    | Empty => Empty T\n    | Cons _ s' => s'\n  end.\n\n(** In order to allow cons to take a head, the value has to have the option\n    property.\n  *)\n\nDefinition cons T (x : option T) (s : stack T) : stack T :=\n  match x with\n    | None => s\n    | Some x' => Cons T x' s\n  end.\n\nFixpoint length T (s : stack T) : nat :=\n  match s with\n    | Empty => 0\n    | Cons _ s' => 1 + (length T s')\n  end.\n\n\n(** ----- *)\n(** ** Some examples *)\n\n(** *** The empty stack. *)\n\nEval simpl in Empty nat. (** <<= Empty nat : stack nat >>*)\nEval simpl in isEmpty nat (Empty nat). (** <<= true : bool >> *)\n\n(** *** A stack of length 1. *)\n\nEval simpl in Cons nat 1 (Empty nat). (** <<= Cons nat 1 (Empty nat) : stack nat >> *)\nEval simpl in isEmpty nat (Cons nat 1 (Empty nat)). (** <<= false : bool >>*)\n\n(** *** Heads or tails? *)\nDefinition list1 := Cons nat 1 (Empty nat).\nDefinition list2 := Cons nat 2 list1.\nDefinition list3 := Cons nat 2 (Cons nat 1 (Empty nat)).\n\nEval simpl in head nat list1. (** <<= Some 1 : option nat>> *)\nEval simpl in head nat list2. (** <<= Some 2 : option nat>> *)\nEval simpl in tail nat list1. (** <<= Empty nat : stack nat>> *)\nEval simpl in tail nat list2. (** <<= list1 : stack nat>> *)\nEval simpl in head nat (tail nat list2). (** <<= Some 1 : option nat>> *)\nEval simpl in length nat list2. (** <<= 2 : nat>> *)\nEval simpl in cons nat (head nat list3) (tail nat list3).\n\nEval simpl in cons nat (head nat list2) (tail nat list2).\n\n(** ----- *)\n(** ** Proving head/tail consistency.\n\n   Theorem: consing the head of a list onto the tail of a list returns the\n   original list. *)\n\nTheorem head_tail_consistency: forall t s,\n  cons t (head t s) (tail t s) = s. \nProof.\n  (** Prologue: _dramatis personae_ and split the proof into two cases: one in\n     which the stack is empty, and the other when the stack is not empty. *)\n\n  intros. induction s.\n\n  (** Case 1: the stack is empty. *)\n\n  reflexivity.\n\n  (** Case 2: the stack is not empty. *)\n\n  rewrite <- IHs.\n  reflexivity.\nQed.\n\n\n(** ** The extracted program (in OCaml) *)\n\n(*\nExtraction \"stack.ml\" stack isEmpty head tail cons length list1 list2.\nExtraction Language Haskell.\nExtraction \"stack.hs\" stack isEmpty head tail cons length list1 list2.\n *)\n\n(**\n<<\ntype bool =\n| True\n| False\n\ntype nat =\n| O\n| S of nat\n\ntype 'a option =\n| Some of 'a\n| None\n\n(** val plus : nat -> nat -> nat **)\n\nlet rec plus n m =\n  match n with\n  | O -> m\n  | S p -> S (plus p m)\n\ntype 't stack =\n| Empty\n| Cons of 't * 't stack\n\n(** val isEmpty : 'a1 stack -> bool **)\n\nlet isEmpty = function\n| Empty -> True\n| Cons (t, s0) -> False\n\n(** val head : 'a1 stack -> 'a1 option **)\n\nlet head = function\n| Empty -> None\n| Cons (s', s0) -> Some s'\n\n(** val tail : 'a1 stack -> 'a1 stack **)\n\nlet tail = function\n| Empty -> Empty\n| Cons (t, s') -> s'\n\n(** val cons : 'a1 option -> 'a1 stack -> 'a1 stack **)\n\nlet cons x s =\n  match x with\n  | Some x' -> Cons (x', s)\n  | None -> s\n\n(** val length : 'a1 stack -> nat **)\n\nlet rec length = function\n| Empty -> O\n| Cons (t, s') -> plus (S O) (length s')\n>>\n*)\n\nEval simpl in tail nat (Empty nat).\nEval simpl in head nat (Cons nat 1 (Empty nat)).", "meta": {"author": "kisom", "repo": "okasaki-coq", "sha": "bfdd42994191706a2930c9fcd2e51d091ef4e4d8", "save_path": "github-repos/coq/kisom-okasaki-coq", "path": "github-repos/coq/kisom-okasaki-coq/okasaki-coq-bfdd42994191706a2930c9fcd2e51d091ef4e4d8/stack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.782699280911179}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Bvector.\nRequire Import ZArith.\nRequire Export Zpower.\nRequire Import Omega.\n\n\n\n\nSection VALUE_OF_BOOLEAN_VECTORS.\n\n\n\nDefinition bit_value (b:bool) : Z :=\nmatch b with\n| true => 1%Z\n| false => 0%Z\nend.\n\nLemma binary_value : forall n:nat, Bvector n -> Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.binary_value\".  \nrefine (nat_rect _ _ _); intros.\nexact 0%Z.\n\ninversion H0.\nexact (bit_value h + 2 * H H2)%Z.\nDefined.\n\nLemma two_compl_value : forall n:nat, Bvector (S n) -> Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.two_compl_value\".  \nsimple induction n; intros.\ninversion H.\nexact (- bit_value h)%Z.\n\ninversion H0.\nexact (bit_value h + 2 * H H2)%Z.\nDefined.\n\nEnd VALUE_OF_BOOLEAN_VECTORS.\n\nSection ENCODING_VALUE.\n\n\n\nDefinition Zmod2 (z:Z) :=\nmatch z with\n| Z0 => 0%Z\n| Zpos p => match p with\n| xI q => Zpos q\n| xO q => Zpos q\n| xH => 0%Z\nend\n| Zneg p =>\nmatch p with\n| xI q => (Zneg q - 1)%Z\n| xO q => Zneg q\n| xH => (-1)%Z\nend\nend.\n\n\nLemma Zmod2_twice :\nforall z:Z, z = (2 * Zmod2 z + bit_value (Z.odd z))%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zmod2_twice\".  \ndestruct z; simpl.\ntrivial.\n\ndestruct p; simpl; trivial.\n\ndestruct p; simpl.\ndestruct p as [p| p| ]; simpl.\nrewrite <- (Pos.pred_double_succ p); trivial.\n\ntrivial.\n\ntrivial.\n\ntrivial.\n\ntrivial.\nQed.\n\nLemma Z_to_binary : forall n:nat, Z -> Bvector n.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_binary\".  \nsimple induction n; intros.\nexact Bnil.\n\nexact (Bcons (Z.odd H0) n0 (H (Z.div2 H0))).\nDefined.\n\nLemma Z_to_two_compl : forall n:nat, Z -> Bvector (S n).\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_two_compl\".  \nsimple induction n; intros.\nexact (Bcons (Z.odd H) 0 Bnil).\n\nexact (Bcons (Z.odd H0) (S n0) (H (Zmod2 H0))).\nDefined.\n\nEnd ENCODING_VALUE.\n\nSection Z_BRIC_A_BRAC.\n\n\n\nLemma binary_value_Sn :\nforall (n:nat) (b:bool) (bv:Bvector n),\nbinary_value (S n) ( b :: bv) =\n(bit_value b + 2 * binary_value n bv)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.binary_value_Sn\".  \nintros; auto.\nQed.\n\nLemma Z_to_binary_Sn :\nforall (n:nat) (b:bool) (z:Z),\n(z >= 0)%Z ->\nZ_to_binary (S n) (bit_value b + 2 * z) = Bcons b n (Z_to_binary n z).\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_binary_Sn\".  \ndestruct b; destruct z; simpl; auto.\nintro H; elim H; trivial.\nQed.\n\nLemma binary_value_pos :\nforall (n:nat) (bv:Bvector n), (binary_value n bv >= 0)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.binary_value_pos\".  \ninduction bv as [| a n v IHbv]; cbn.\nomega.\n\ndestruct a; destruct (binary_value n v); simpl; auto.\nauto with zarith.\nQed.\n\nLemma two_compl_value_Sn :\nforall (n:nat) (bv:Bvector (S n)) (b:bool),\ntwo_compl_value (S n) (Bcons b (S n) bv) =\n(bit_value b + 2 * two_compl_value n bv)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.two_compl_value_Sn\".  \nintros; auto.\nQed.\n\nLemma Z_to_two_compl_Sn :\nforall (n:nat) (b:bool) (z:Z),\nZ_to_two_compl (S n) (bit_value b + 2 * z) =\nBcons b (S n) (Z_to_two_compl n z).\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_two_compl_Sn\".  \ndestruct b; destruct z as [| p| p]; auto.\ndestruct p as [p| p| ]; auto.\ndestruct p as [p| p| ]; simpl; auto.\nintros; rewrite (Pos.succ_pred_double p); trivial.\nQed.\n\nLemma Z_to_binary_Sn_z :\nforall (n:nat) (z:Z),\nZ_to_binary (S n) z =\nBcons (Z.odd z) n (Z_to_binary n (Z.div2 z)).\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_binary_Sn_z\".  \nintros; auto.\nQed.\n\nLemma Z_div2_value :\nforall z:Z,\n(z >= 0)%Z -> (bit_value (Z.odd z) + 2 * Z.div2 z)%Z = z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_div2_value\".  \ndestruct z as [| p| p]; auto.\ndestruct p; auto.\nintro H; elim H; trivial.\nQed.\n\nLemma Pdiv2 : forall z:Z, (z >= 0)%Z -> (Z.div2 z >= 0)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Pdiv2\".  \ndestruct z as [| p| p].\nauto.\n\ndestruct p; auto.\nsimpl; intros; omega.\n\nintro H; elim H; trivial.\nQed.\n\nLemma Zdiv2_two_power_nat :\nforall (z:Z) (n:nat),\n(z >= 0)%Z ->\n(z < two_power_nat (S n))%Z -> (Z.div2 z < two_power_nat n)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zdiv2_two_power_nat\".  \nintros.\nenough (2 * Z.div2 z < 2 * two_power_nat n)%Z by omega.\nrewrite <- two_power_nat_S.\ndestruct (Zeven.Zeven_odd_dec z) as [Heven|Hodd]; intros.\nrewrite <- Zeven.Zeven_div2; auto.\ngeneralize (Zeven.Zodd_div2 z Hodd); omega.\nQed.\n\nLemma Z_to_two_compl_Sn_z :\nforall (n:nat) (z:Z),\nZ_to_two_compl (S n) z =\nBcons (Z.odd z) (S n) (Z_to_two_compl n (Zmod2 z)).\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_two_compl_Sn_z\".  \nintros; auto.\nQed.\n\nLemma Zeven_bit_value :\nforall z:Z, Zeven.Zeven z -> bit_value (Z.odd z) = 0%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zeven_bit_value\".  \ndestruct z; unfold bit_value; auto.\ndestruct p; tauto || (intro H; elim H).\ndestruct p; tauto || (intro H; elim H).\nQed.\n\nLemma Zodd_bit_value :\nforall z:Z, Zeven.Zodd z -> bit_value (Z.odd z) = 1%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zodd_bit_value\".  \ndestruct z; unfold bit_value; auto.\nintros; elim H.\ndestruct p; tauto || (intros; elim H).\ndestruct p; tauto || (intros; elim H).\nQed.\n\nLemma Zge_minus_two_power_nat_S :\nforall (n:nat) (z:Z),\n(z >= - two_power_nat (S n))%Z -> (Zmod2 z >= - two_power_nat n)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zge_minus_two_power_nat_S\".  \nintros n z; rewrite (two_power_nat_S n).\ngeneralize (Zmod2_twice z).\ndestruct (Zeven.Zeven_odd_dec z) as [H| H].\nrewrite (Zeven_bit_value z H); intros; omega.\n\nrewrite (Zodd_bit_value z H); intros; omega.\nQed.\n\nLemma Zlt_two_power_nat_S :\nforall (n:nat) (z:Z),\n(z < two_power_nat (S n))%Z -> (Zmod2 z < two_power_nat n)%Z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Zlt_two_power_nat_S\".  \nintros n z; rewrite (two_power_nat_S n).\ngeneralize (Zmod2_twice z).\ndestruct (Zeven.Zeven_odd_dec z) as [H| H].\nrewrite (Zeven_bit_value z H); intros; omega.\n\nrewrite (Zodd_bit_value z H); intros; omega.\nQed.\n\nEnd Z_BRIC_A_BRAC.\n\nSection COHERENT_VALUE.\n\n\n\nLemma binary_to_Z_to_binary :\nforall (n:nat) (bv:Bvector n), Z_to_binary n (binary_value n bv) = bv.\nProof. hammer_hook \"Zdigits\" \"Zdigits.binary_to_Z_to_binary\".  \ninduction bv as [| a n bv IHbv].\nauto.\n\nrewrite binary_value_Sn.\nrewrite Z_to_binary_Sn.\nrewrite IHbv; trivial.\n\napply binary_value_pos.\nQed.\n\nLemma two_compl_to_Z_to_two_compl :\nforall (n:nat) (bv:Bvector n) (b:bool),\nZ_to_two_compl n (two_compl_value n (Bcons b n bv)) = Bcons b n bv.\nProof. hammer_hook \"Zdigits\" \"Zdigits.two_compl_to_Z_to_two_compl\".  \ninduction bv as [| a n bv IHbv]; intro b.\ndestruct b; auto.\n\nrewrite two_compl_value_Sn.\nrewrite Z_to_two_compl_Sn.\nrewrite IHbv; trivial.\nQed.\n\nLemma Z_to_binary_to_Z :\nforall (n:nat) (z:Z),\n(z >= 0)%Z ->\n(z < two_power_nat n)%Z -> binary_value n (Z_to_binary n z) = z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_binary_to_Z\".  \ninduction n as [| n IHn].\nunfold two_power_nat, shift_nat; simpl; intros; omega.\n\nintros; rewrite Z_to_binary_Sn_z.\nrewrite binary_value_Sn.\nrewrite IHn.\napply Z_div2_value; auto.\n\napply Pdiv2; trivial.\n\napply Zdiv2_two_power_nat; trivial.\nQed.\n\nLemma Z_to_two_compl_to_Z :\nforall (n:nat) (z:Z),\n(z >= - two_power_nat n)%Z ->\n(z < two_power_nat n)%Z -> two_compl_value n (Z_to_two_compl n z) = z.\nProof. hammer_hook \"Zdigits\" \"Zdigits.Z_to_two_compl_to_Z\".  \ninduction n as [| n IHn].\nunfold two_power_nat, shift_nat; simpl; intros.\nassert (z = (-1)%Z \\/ z = 0%Z). omega.\nintuition; subst z; trivial.\n\nintros; rewrite Z_to_two_compl_Sn_z.\nrewrite two_compl_value_Sn.\nrewrite IHn.\ngeneralize (Zmod2_twice z); omega.\n\napply Zge_minus_two_power_nat_S; auto.\n\napply Zlt_two_power_nat_S; auto.\nQed.\n\nEnd COHERENT_VALUE.\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/ZArith/Zdigits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7826586433155305}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImplicit Type p q r : bool.\nImplicit Type m n a b c : nat.\n\n(** *** Exercise 1:\n\nProve that the equation #$$ 8y = 6x + 1 $$# has no solution.\n\n- Hint 1: take the modulo 2 of the equation.\n- Hint 2: [Search _ modn addn] and [Search _ modn muln]\n#<br/><div># *)\nLemma ex1 x y : 8 * y != 6 * x + 1.\nProof.\n(*D*)apply/negP => /eqP /(congr1 (modn^~ 2)).\n(*D*)by rewrite -modnMml mul0n -modnDml -modnMml.\n(*A*)Qed.\n\n(** #</div>#\n*** Exercise 2:\n\nThe ultimate Goal of this exercise is to find the solutions of the equation\n#$$ 2^n = a^2 + b^2,$$# where n is fixed and a and b unkwown.\n\nWe hence study the following predicate:\n#<div># *)\nDefinition sol n a b := [&& a > 0, b > 0 & 2 ^ n == a ^ 2 + b ^ 2].\n(** #</div>#\n- First prove that there are no solutions when n is 0.\n\n  - Hint: do enough cases on a and b.\n#<div># *)\nLemma sol0 a b : ~~ sol 0 a b.\n(*A*)Proof. by move: a b => [|[|[|a]]] [|[|[|b]]]. Qed.\n(** #</div>#\n- Now prove the only solution when n is 1.\n\n  - Hint: do enough cases on a and b.\n#<div># *)\nLemma sol1 a b : sol 1 a b = (a == 1) && (b == 1).\n(*A*)Proof. by move: a b => [|[|[|a]]] [|[|[|b]]]. Qed.\n(** #</div>#\n- Now prove a little lemma that will guarantee that a and b are even.\n\n  - Hint 1: first prove [(x * 2 + y) ^ 2 = y ^ 2 %[mod 4]].\n  - Hint 2: [About divn_eq] and [Search _ modn odd]\n#<div># *)\nLemma mod4Dsqr_even a b : (a ^ 2 + b ^ 2) %% 4 = 0 -> (~~ odd a) && (~~ odd b).\nProof.\n(*D*)have sqr_x2Dy_mod4 x y : (x * 2 + y) ^ 2 = y ^ 2 %[mod 4].\n(*D*)  rewrite sqrnD addnAC mulnAC [2 * _]mulnC -mulnA -[2 * 2]/4.\n(*D*)  by rewrite expnMn -[2 ^ 2]/4 -mulnDl -modnDml modnMl.\n(*D*)rewrite {1}(divn_eq a 2) {1}(divn_eq b 2) -modnDm.\n(*D*)by rewrite !sqr_x2Dy_mod4 modnDm !modn2; do 2!case: odd.\n(*A*)Qed.\n(** #</div>#\n- Deduce that if n is greater than 2 and a and b are solutions, then they are even.\n#<div># *)\nLemma sol_are_even n a b : n > 1 -> sol n a b -> (~~ odd a) && (~~ odd b).\nProof.\n(*D*)case: n => [|[|n]]// _; rewrite /sol => /and3P[_ _ /eqP eq_a2Db].\n(*D*)by rewrite mod4Dsqr_even// -eq_a2Db !expnS mulnA modnMr.\n(*A*)Qed.\n(** #</div>#\n- Prove that the solutions for n are the halves of the solutions for n + 2.\n\n  - Hint: [Search _ odd double] and [Search _ \"eq\" \"mul\"].\n\n#<div># *)\nLemma solSS n a b : sol n.+2 a b -> sol n a./2 b./2.\nProof.\n(*D*)move=> soln2ab; have [//|a_even b_even] := andP (sol_are_even _ soln2ab).\n(*D*)rewrite /sol -[a]odd_double_half -[b]odd_double_half in soln2ab.\n(*D*)rewrite (negPf a_even) (negPf b_even) ?add0n ?double_gt0 in soln2ab.\n(*D*)rewrite /sol; move: soln2ab => /and3P[-> -> /=].\n(*D*)by rewrite -(addn2 n) expnD -!muln2 !expnMn -mulnDl eqn_mul2r.\n(*A*)Qed.\n(** #</div>#\n- Prove there are no solutions for n even\n\n  - Hint: Use [sol0] and [solSS].\n#<div># *)\nLemma sol_even a b n : ~~ sol (2 * n) a b.\nProof.\n(*D*)elim: n => [|n IHn] in a b *; first exact: sol0.\n(*D*)by apply/negP; rewrite mulnS => /solSS; apply/negP.\n(*A*)Qed.\n(** #</div>#\n- Certify the only solution when n is odd.\n\n  - Hint 1: Use [sol1], [solSS] and [sol_are_even].\n  - Hint 2: Really sketch it on paper first!\n#<div># *)\nLemma sol_odd a b n : sol (2 * n + 1) a b = (a == 2 ^ n) && (b == 2 ^ n).\nProof.\n(*D*)apply/idP/idP=> [|/andP[/eqP-> /eqP->]]; last first.\n(*D*)  by rewrite /sol !expn_gt0/= expnD muln2 addnn -expnM mulnC.\n(*D*)elim: n => [|n IHn] in a b *; first by rewrite sol1.\n(*D*)rewrite mulnS !add2n !addSn => solab.\n(*D*)have [//|/negPf aNodd /negPf bNodd] := andP (sol_are_even _ solab).\n(*D*)rewrite /sol -[a]odd_double_half -[b]odd_double_half aNodd bNodd.\n(*D*)by rewrite -!muln2 !expnSr !eqn_mul2r IHn// solSS.\n(*A*)Qed.\n(** #</div>#\n*** Exercise 3:\nCertify the solutions of this problem.\n\n- Hint: Do not hesitate to take advantage of Coq's capabilities\n  for brute force case analysis\n#<div># *)\nLemma ex3 n : (n + 4 %| 3 * n + 32) = (n \\in [:: 0; 1; 6; 16]).\nProof.\n(*D*)apply/idP/idP => [Hn|]; rewrite !inE; last first.\n(*D*)  by move=> /or4P[] /eqP->.\n(*D*)have : n + 4 %| 3 * n + 32 - 3 * (n + 4) by rewrite dvdn_sub// dvdn_mull.\n(*D*)by rewrite mulnDr subnDl /= {Hn}; move: n; do 21?[case=>//].\n(*A*)Qed.\n(** #</div>#\n*** Exercise 4:\n\nCertify the result of the euclidean division of\n#$$a b^n - 1\\quad\\textrm{  by  }\\quad b ^ {n+1}$$#\n\n#<div># *)\nLemma ex4 a b n : a > 0 -> b > 0 -> n > 0 ->\n   edivn (a * b ^ n - 1) (b ^ n.+1) =\n   ((a - 1) %/ b, ((a - 1) %% b) * b ^ n + b ^ n - 1).\nProof.\n(*D*)move=> a_gt0 b_gt0 n_gt0; rewrite /divn modn_def.\n(*D*)have [q r aB1_eq r_lt] /= := edivnP (a - 1).\n(*D*)rewrite b_gt0 /= in r_lt.\n(*D*)have /(congr1 (muln^~ (b ^ n))) := aB1_eq.\n(*D*)rewrite mulnBl mulnDl mul1n.\n(*D*)move=> /(congr1 (addn^~ (b ^ n - 1))).\n(*D*)rewrite addnBA ?expn_gt0 ?b_gt0// subnK; last first.\n(*D*)  by rewrite -[X in X <= _]mul1n leq_mul2r a_gt0 orbT.\n(*D*)rewrite -mulnA -expnS -addnA => ->.\n(*D*)rewrite edivn_eq addnBA ?expn_gt0 ?b_gt0//.\n(*D*)rewrite subnS subn0 prednK ?addn_gt0 ?expn_gt0 ?b_gt0 ?orbT//.\n(*D*)rewrite -[X in _ + X]mul1n -mulnDl addn1 expnS.\n(*D*)by rewrite leq_mul2r r_lt orbT.\n(*A*)Qed.\n(** #</div>#\n*** Exercise 5:\n\nProve that the natural number interval #$$[n!+2\\ ,\\ n!+n]$$#\ncontains no prime number.\n\n- Hint: Use [Search _ prime dvdn], [Search _ factorial], ...\n\n#<div># *)\nLemma ex5 n m : n`! + 2 <= m <= n`! + n -> ~~ prime m.\nProof.\n(*D*)move=> m_in; move: (m_in); rewrite -[m](@subnKC n`!); last first.\n(*D*)  by rewrite (@leq_trans (n`! + 2)) ?leq_addr//; by case/andP: m_in.\n(*D*)set k := (_ - _); rewrite !leq_add2l => /andP[k_gt1 k_le_n].\n(*D*)apply/primePn; right; exists k.\n(*D*)  by rewrite k_gt1/= -subn_gt0 addnK fact_gt0.\n(*D*)by rewrite dvdn_add// dvdn_fact// k_le_n (leq_trans _ k_gt1).\n(*A*)Qed.\n(** #</div># *)", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/exercise6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7826586399979653}}
{"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(*                                  ex1.v                                   *)\n(****************************************************************************)\n\n\nTheorem trivial : forall A : Prop, A -> A.\nintros A H'; exact H'.\nQed.\n\nTheorem and_commutative : forall A B : Prop, A /\\ B -> B /\\ A.\nintros A B H'; split.\nelim H'; intros H'0 H'1; clear H'; exact H'1.\nelim H'; intros H'0 H'1; clear H'; exact H'0.\nQed.\n\nTheorem or_commutative : forall A B : Prop, A \\/ B -> B \\/ A.\nintros A B h; elim h; [ intro H'; clear h; try exact H' | clear h; intro H' ].\nright; assumption.\nleft; assumption.\nQed.\n\nTheorem mp : forall A B : Prop, A -> (A -> B) -> B.\nintros A B H' H'0.\napply H'0.\nexact H'.\nQed.\n\nTheorem S : forall A B C : Prop, (A -> B -> C) -> (A -> B) -> A -> C.\nintros A B C H' H'0 H'1.\napply H'.\nexact H'1.\napply H'0.\nexact H'1.\nQed.\n\nTheorem Praeclarum :\n forall x y z t : Prop, (x -> z) /\\ (y -> t) -> x /\\ y -> z /\\ t.\nintros x y z t h; elim h; intros H' H'0; clear h.\nintro h; elim h; intros H'1 H'2; clear h.\nsplit.\napply H'; assumption.\napply H'0; assumption.\nQed.\n\nTheorem resolution :\n forall (p q : Type -> Prop) (a : Type),\n p a -> (forall x : Type, p x -> q x) -> q a.\nintros p q a H' H'0.\napply H'0.\nexact H'.\nQed.\n\nTheorem Witnesses :\n forall (a b : Type) (p : Type -> Prop), p a \\/ p b -> exists x : Type, p x.\nintros a b p h; elim h; intro H'; clear h.\nexists a; assumption.\nexists b; assumption.\nQed.\n\nTheorem Simple :\n 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) ->\n forall x : A, (exists y : A, R x y) -> R x x.\nintros A R H' H'0 x h; elim h; intros y E; clear h.\napply H' with y.\nsplit; [ assumption | idtac ].\napply H'0; assumption.\nQed.\n\nTheorem not_not : forall a : Prop, a -> ~ ~ a.\nintros a H'; red in |- *; intro H'0; elim H'0; assumption.\nQed.\n\nTheorem mini_cases : forall x y : Prop, (x \\/ ~ y) /\\ y -> x.\nintros x y h; elim h; intros h0 H'; elim h0;\n [ intro H'0; clear h h0; try exact H'0 | clear h h0; intro H'0 ].\nelim H'0; try assumption.\nQed.\n\nRequire Import Classical.\n(*This theorem needs classical logic*)\n\nTheorem not_not_converse : forall a : Prop, ~ ~ a -> a.\nintros a H'.\ngeneralize (classic a); intro h; elim h;\n [ intro H'0; clear h; try exact H'0 | clear h; intro H'0 ].\nelim H'; assumption.\nQed.\n\nTheorem not_quite_classic : forall a : Prop, ~ ~ (a \\/ ~ a).\nintro a; red in |- *; intro H'; elim H'; right; red in |- *; intro H'0.\nelim H'; left; try assumption.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "cours-de-coq", "sha": "a5cf501d3e20ab88a16203abf10d05f3f240ac78", "save_path": "github-repos/coq/coq-contribs-cours-de-coq", "path": "github-repos/coq/coq-contribs-cours-de-coq/cours-de-coq-a5cf501d3e20ab88a16203abf10d05f3f240ac78/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7826586370640477}}
{"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 (k1 k2: nat), (le startI k1) /\\ (lt k1 k2) /\\ (lt k2 endI) -> (le (arr $! k1) (arr $! k2)).\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 < len1 + len2 *)\n      *[\"i\"] <- *[\"i2\"] ;;\n      \"i2\" <- \"i2\" + 1\n    _done_;;\n    \"i\" <- \"i\" + 1\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  (* an array made out of a single element is sorted ! *)\n  Axiom singletone_is_sorted: forall (arr: heap) (startI: nat),\n    is_sorted arr startI (startI + 1).\n\n  (* You can extend an array that is sorted with an element at the end\n     as long as that element is the greater or equal to the right most\n     element (the largest element in the array), and get a new sorted array *)\n  Axiom is_sorted_extend: forall (arr: heap) (startI endI x: nat),\n    is_sorted arr startI endI\n    -> arr $! (endI - 1) <= x\n    -> is_sorted (arr $+ (endI, x)) startI (endI + 1).\n\n  (* Changing elements in the heap that are outside an array will not\n     affect whether the array is sorted or not *)\n  Axiom is_sorted_remains_sorted_with_useless: \n    forall (arr: heap) (startI endI: nat) (i x: nat),\n      is_sorted arr startI endI\n      -> i >= endI\n      -> is_sorted (arr $+ (i, x)) 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/solutions1/Problem4-fixed/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.9124361551194692, "lm_q1q2_score": 0.7826586350188487}}
{"text": "(**\n有限集合の濃度の存在を証明する\n======\n2019/05/01\n\nこの文書のソースコードは以下にあります。\n\n\nhttps://github.com/suharahiromichi/coq/blob/master/pearl/ssr_ex_card.v\n\n *)\n\n(**\nOCaml 4.07.1, Coq 8.9.0, MathComp 1.9.0\n *)\n\n(**\n# 説明\n\nへんなタイトルですが、MathComp を使った定理の証明の問題です。\n\n有限集合の濃度、すなわち要素の個数は、適当な自然数に一意的に決まります。\n濃度を ``#| _ |`` で表すとすると、\n\n``∃ i : nat, #| p | = i``\n\n\nですね。これ自体は自明なのですが、MathComp で証明しようとすると、\n取り付く島もないように見えます。\n\nでも、すこし考えてみると、\nMathComp の場合、集合は有限型(finType)をドメインとするbooleanな関数で\n表されます。すなわち、``T : finType`` とすると、\n\n``p : pred T``\n\n\nなお、``pred T`` は単に ``T -> bool`` の Notation (構文糖衣) です。\n\npが、常にtrueを返す場合が全集合、常にfalseを返す場合が空集合になります。\nこのように、集合pと関数pが同一視されるので、集合pの濃度は、\n「型Tの要素のうち、関数pがtrueを返す要素の数」\nということになります。\n\nこのことから、\n型Tの要素の全体をしめす finType の enum フィールドの中身 (リスト、seq型) について、\n関数pでフィルタした結果のサイズが決まることを証明すればよいことになります。\n\n型 T から、その enum フィールドの中身を取り出すのは、次のようにします。\n\n``Finite.enum T``\n\n\n後の証明は、単にリストの要素についての帰納法です。\n\nほとんど自明であるがゆえに、\nMathCompにおける実装の裏側を知らないと解けない問題の例といえるでしょうか。\n *)\n\n(**\n# コード例\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\n\nSection Test.\n  \n  Variable T : finType.\n  Variable p : pred T.                      (* T -> bool *)\n\n  Lemma ex_card : exists (i : nat), #| p | = i.\n  Proof.\n    rewrite unlock /card /enum_mem.\n    elim: (Finite.enum T).\n    - by exists 0.\n    - move=> x s /= [i IHs].\n      case: ifP => /=.\n      + exists i.+1.\n          by rewrite IHs.\n      + by exists i.\n  Qed.\n\nEnd Test.\n\n(**\n# 最初に使った箇所\n\n単一化の証明 http://fetburner.hatenablog.com/entry/2015/12/06/224619\n\nUnify.v を MathComp への移植するときに必要になりました。移植例：\n\nhttps://github.com/suharahiromichi/coq/blob/master/unify/ssr_unify_bool_3.v\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/pearl/ssr_ex_card.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7826446872412487}}
{"text": "Require Export D.\n\n(** **** Problem #1: 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\n    Note that plus and multiplication are already defined in Coq.\n    use \"+\" for plus and \"*\" for multiplication.\n*)\n\nEval compute in 3 * 5.\nEval compute in 3+5*6.\n\nFixpoint factorial (n:nat) : nat := \n  match n with\n  | O => 1\n  | S n' => n * factorial(n')\n  end.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = 10 * 12.\nProof. reflexivity. Qed.\n", "meta": {"author": "norangLemon", "repo": "plHW", "sha": "ca142b892b3dcb25cd7a3a29c14233061bca4c84", "save_path": "github-repos/coq/norangLemon-plHW", "path": "github-repos/coq/norangLemon-plHW/plHW-ca142b892b3dcb25cd7a3a29c14233061bca4c84/01/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7825973450529129}}
{"text": "Require Import List.\nRequire Import Cpdt.CpdtTactics.\nRequire Coq.extraction.Extraction.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\nExtraction Language OCaml.\n\n(* PART 2: Programming with Dependent Types *)\n(* Chapter 6. Subset Types and Variations *)\n\nExtraction pred.\n(*\n(** val pred : nat -> nat **)\nlet pred = function\n  | O -> O\n  | S u -> u\n*)\n\n(* We might like to be sure that we never try to take the predecessor of 0.\n   We can enforce this by giving pred a stronger, dependent type.  *)\n\nLemma zgtz : 0 > 0 -> False.\n  crush.\nQed.\n\nDefinition pred_strong1 (n : nat) : n > 0 (* : proof *) -> 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(* argument n of pred strong1 can be made implicit,\n   since it can be deduced from the type of the second argument *)\nTheorem two_gt0 : 2 > 0.\n  crush.\nQed.\n\nEval compute in pred_strong1 two_gt0.\n\nLemma zero_gt0 : 0 > 0. (* absurd! *)\nAdmitted.\nEval compute in pred_strong1 zero_gt0.\n(*\n    = match zgtz zero_gt0 return nat with\n      end\n    : nat\n*)\n\n(*\n(* following example fails to type-check *)\nDefinition 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\n(* Coq's heuristics had inferred [return n > 0 -> nat] in the above example. *)\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\n(* Curry-Howard twin of ex (sig : Type, ex : Prop) *)\nPrint sig.\n(*\n  Inductive sig (A : Type) (P : A -> Prop) : Type :=\n      exist : forall x : A, P x -> { x : A | P x }\n  (Argument A is implicit)\n*)\n(* cf. *)\nPrint ex.\n(*\n  Inductive ex (A : Type) (P : A -> Prop) : Prop :=\n      ex_intro : forall x : A, P x -> exists y, P y\n  (Argument A is implicit)\n*)\n\nLocate \"{ _ : _ | _ }\".\n(*\n  Notation\n  \"{ x : A  |  P }\" := sig (fun x : A => P)\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                                 (* v \"P\" in the definition of sig *)\nEval compute in pred_strong2 (exist _ 2 two_gt0).\n                             (* ^ constructor of sig *)\n(* ... the above is the same as this: *)\nEval compute in pred_strong2 (exist (fun n => n > 0) 2 two_gt0).\nExtraction pred_strong2.\n\n(*\n  Definition proj1_sig (e:sig P) := match e with\n                                    | exist _ a b => a\n                                    end.\n\n  : function to extract the first argument of sig (the value that 'exists')\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\nEval compute in proj1_sig (exist _ 2 two_gt0). (* 2 *)\nEval compute in pred_strong3 (exist _ 2 two_gt0).\n\n(*\n  = exist (fun m : nat => 2 = S m) 1 eq_refl\n  : {m : nat | proj1_sig (exist (lt 0) 2 two_gt0) = S m}\n\n  ** eq_refl: law of 'reflexivity'\n*)\n\nExtraction pred_strong3.\n\nCheck False_rec.\n(* forall P : Set, False -> P *)\n\n(* tactic-based theorem proving\n   cf) https://softwarefoundations.cis.upenn.edu/lf-current/ProofObjects.html#lab268 *)\nDefinition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.\n  (* refine _term_ : provide _term_ as proof.\n                     _term_ should have the same type as the goal. *)\n  refine (fun n =>\n    match n with\n      | O => fun _ => False_rec _ _\n      | S n' => fun _ => exist _ n' _\n    end).\n  crush.\n  reflexivity.\nRestart.\n  destruct n as [| n']; intros.\n  - apply exist with (x:=0). inversion H.\n  - apply exist with (x:=n'). reflexivity.\nDefined. (* <- by using 'Defined', proof will remain transparent\n               (using 'Qed' instead will make the proof opaque) *)\n\nPrint pred_strong4.\nEval compute in pred_strong4 two_gt0.\n\nDefinition pred_strong4' : forall n : nat, n > 0 -> {m : nat | n = S m}.\n  (* abstract : produces shorter terms, by automatically abstracting subgoals\n                into named lemmas (???) *)\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(*\n  pred_strong4' =\n  fun n : nat =>\n  match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with\n  | 0 =>\n      fun _H : 0 > 0 =>\n      False_rec {m : nat | 0 = S m} (pred_strong4'_subproof n _H)\n  | S n' =>\n      fun _H : S n' > 0 =>\n      exist (fun m : nat => S n' = S m) n' (pred_strong4'_subproof0 n _H)\n  end\n       : forall n : nat, n > 0 -> {m : nat | n = S m}\n*)\nPrint pred_strong4'_subproof.\n(*\n  pred_strong4'_subproof = \n  fun g : 0 > 0 =>\n  Bool.diff_false_true\n    (Bool.absurd_eq_true false\n       (Bool.diff_false_true\n          (Bool.absurd_eq_true false (pred_strong4'_subproof_subproof g))))\n       : 0 > 0 -> False\n*)\nPrint pred_strong4'_subproof0.\n(*\n  pred_strong4'_subproof0 = \n  fun n' : nat => eq_refl\n       : forall n' : nat, S n' = S n'\n*)\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\n(* using Coq's new feature [Program] *)\n(* cf: https://sites.google.com/site/suharahiromichi/program-ing-coq/coq_subset *)\nObligation Tactic := crush.\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(* 6.2 Decidable Proposition Types *)\n\n(* another type in STL which captures the idea of program values *)\nPrint sumbool.\n(*\nInductive sumbool (A : Prop) (B : Prop) : Set :=\n    left : A -> {A} + {B} | right : B -> {A} + {B}\n*)\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n(* ^ The [if] form actually works when the test expression has any two-constructor\n   inductive type. *)\n\nInductive funny : Set :=\n| Foo\n| Bar.\nEval compute in (if Foo then Yes else No).\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); congruence.\n    (* congruence: http://proofcafe.org/sf/UseAuto_J.html *)\nRestart.\n  induction n.\n  - destruct m.\n    + left. reflexivity.\n    + right. congruence.\n  - induction m.\n    + right. congruence.\n    + destruct (IHn m).\n      { left. congruence. }\n      { right. congruence. }\nDefined.\n\nEval compute in eq_nat_dec 2 2.\nEval compute in eq_nat_dec 2 3.\n(* Note: Yes and No notations are hiding proofs establishing the correctness of the outputs. *)\n\nExtraction eq_nat_dec.\n(*\n(** val eq_nat_dec : nat -> nat -> sumbool **)\n\nlet rec eq_nat_dec n m =\n  match n with\n    | O -> (match m with\n              | O -> Left\n              | S n0 -> Right)\n    | S n' -> (match m with\n                 | O -> Right\n                 | S m' -> eq_nat_dec n' m')\n*)\n\n(* Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it.\n https://coq.inria.fr/refman/proof-engine/tactics.html#coq:tacn.decide-equality\n*)\nDefinition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.\n  decide equality.\nDefined.\nExtraction eq_nat_dec'.\n\n(* use \"true\" and \"false\" instead of \"Left\" and \"Right\" *)\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\nExtraction eq_nat_dec'.\n\nNotation \"x || y\" := (if x then Yes else Reduce y).\n\n(* function to decide list membership *)\nSection In_dec.\n  Variable A : Set.\n  Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}. (* ??? *)\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); crush.\n  Restart.\n    induction ls.\n    - right. intros contra. inversion contra.\n    - simpl. destruct (A_eq_dec a x).\n      + subst. left. left. reflexivity.\n      + destruct IHls.\n        { left. right. assumption. }\n        { right. intros contra. destruct contra; auto. }\n  Defined.\nEnd In_dec.\n\nEval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil).\nEval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil).\nExtraction In_dec.\n(*\n(** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)\n\nlet rec in_dec a_eq_dec x = function\n  | Nil -> false\n  | Cons (x', ls') ->\n      (match a_eq_dec x x' with\n         | true -> true\n         | false -> in_dec a_eq_dec x ls')\n*)\n\n\n(* 6.3 Partial Subset Types *)\n\n(* use 'maybe' to allow obligation-free failure *)\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\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\nEval compute in pred_strong7 2.\nEval compute in pred_strong7 0.\n\n(* How to make sure we'll allow [Unknown] only when the result is really unknown?\n   => ex. [sumor]\n*)\n\nPrint sumor.\n(*\nInductive sumor (A : Type) (B : Prop) : Type :=\n    inleft : A -> A + {B} | inright : B -> A + {B}\n\n  : sumor is either value of A or proofs of B.\n*)\nLocate \"_ + { _ }\".\n\nNotation \"!!\" := (inright _ _). (* proof *)\nNotation \"[|| x ||]\" := (inleft _ [x]). (* value *)\n(* ^ supecialized to [sumor]s whose [A] params are instantiated with regular subset types *)\n\n(* possibly failing predecessor ([sumor]-based, maximally expressive) *)\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\nEval compute in pred_strong8 2.\nEval compute in pred_strong8 0.\n\n\n(* 6.4 Monadic Notations *)\n\n(* \"bind\"-like notation *)\nNotation \"x <- e1 ; e2\" := (match e1 with\n                             | Unknown => ??\n                             | Found x _ => e2\n                           end)\n(right associativity, at level 60).\n\n(* a function to take the predecessors of two naturals at once *)\nDefinition doublePred : forall n1 n2 : nat,\n  {{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)|]); tauto.\nDefined.\n\n(* [sumor] version of the \"bind\" notation *)\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)||]); tauto.\nDefined.\n\n\n(* 6.5 A Type-Checking Example *)\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\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(* function to compare two types *)\nDefinition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.\n  decide equality.\nDefined.\n\n(* notation for \"assertion\" *)\nNotation \"e1 ;; e2\" := (if e1 then e2 else ??)\n  (right associativity, at level 60).\n\n(* every [[|e|]] expression adds a [hasType] proof obligation *)\nDefinition typeCheck : forall e : exp, {{t | hasType e t}}.\n  (* Note: {{t | hasType e t}} = maybe (fun t => hasType e t) *)\n  Hint Constructors hasType.\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); crush.\nDefined.\n\nEval simpl in typeCheck (Nat 0).\nEval simpl in typeCheck (Plus (Nat 1) (Nat 2)).\nEval simpl in typeCheck (Plus (Nat 1) (Bool false)).\nExtraction typeCheck.\n(*\n(** val typeCheck : exp -> type0 maybe **)\n\nlet rec typeCheck = function\n  | Nat n -> Found TNat\n  | Plus (e1, e2) ->\n      (match typeCheck e1 with\n         | Unknown -> Unknown\n         | Found t1 ->\n             (match typeCheck e2 with\n                | Unknown -> Unknown\n                | Found t2 ->\n                    (match eq_type_dec t1 TNat with\n                       | true ->\n                           (match eq_type_dec t2 TNat with\n                              | true -> Found TNat\n                              | false -> Unknown)\n                       | false -> Unknown)))\n  | Bool b -> Found TBool\n  | And (e1, e2) ->\n      (match typeCheck e1 with\n         | Unknown -> Unknown\n         | Found t1 ->\n             (match typeCheck e2 with\n                | Unknown -> Unknown\n                | Found t2 ->\n                    (match eq_type_dec t1 TBool with\n                       | true ->\n                           (match eq_type_dec t2 TBool with\n                              | true -> Found TBool\n                              | false -> Unknown)\n                       | false -> Unknown)))\n*)\n\nNotation \"e1 ;;; e2\" := (if e1 then e2 else !!)\n  (right associativity, at level 60).\n\n(* det = deterministic *)\nLemma hasType_det : forall e t1,\n  hasType e t1 ->\n  forall t2, hasType e t2 ->\n  t1 = t2.\nProof.\n  induction 1; inversion 1; crush.\nRestart.\n  induction e; intros.\n  - (* Nat *)  inversion H. inversion H0. reflexivity.\n  - (* Plus *) inversion H. inversion H0. reflexivity.\n  - (* Bool *) inversion H. inversion H0. reflexivity.\n  - (* And *)  inversion H. inversion H0. reflexivity.\nQed.\n\nDefinition typeCheck' : forall e : exp,\n  {t : type | hasType e t} + {forall t, ~ hasType e t}.\n  Hint Constructors hasType.\n  Hint Resolve hasType_det.\n  (* Since its statement includes [forall]-bound variables that do not appear in its conclusion,\n     only [eauto] will apply this hint. *)\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); clear F; crush' tt hasType; eauto.\n  (* We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls\n     that we never make. Such a step is usually warranted when defining a recursive function with [refine].\n     The [crush] variant [crush'] helps us by performing automatic inversion on instances of the predicates specified\n     in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *)\nRestart.\n  induction e.\n  - left. exists TNat. (* somehow worked! *) constructor.\n  - destruct IHe1 as [IHe1' | IHe1'].\n    + destruct IHe2 as [IHe2' | IHe2'].\n      { inversion IHe1' as [t1 H1]. inversion IHe2' as [t2 H2].\n        destruct t1.\n        - (* t1 = TNat *) destruct t2.\n          + (* t2 = TNat *) left. exists TNat. auto.\n          + (* t2 = TBool *) right. intros t H. inversion H; subst.\n            apply hasType_det with (t1:=TNat) in H2. inversion H2. trivial.\n        - (* t1 = TBool *) right. intros t H. inversion H; subst.\n          apply hasType_det with (t1:=TNat) in H1. inversion H1. trivial. }\n      { (* e2 is untypable *)\n         right. intros t H. inversion H; subst. apply IHe2' in H4. auto. }\n    + (* e1 is untypable *)\n      right. intros t H. inversion H; subst. apply IHe1' in H2. auto.\n  - left. exists TBool. constructor.\n  - destruct IHe1 as [IHe1' | IHe1'].\n    + destruct IHe2 as [IHe2' | IHe2'].\n      { inversion IHe1' as [t1 H1]. inversion IHe2' as [t2 H2].\n        destruct t1.\n        - (* t1 = TNat *) right. intros t H. inversion H; subst.\n          apply hasType_det with (t1:=TBool) in H1. inversion H1. trivial.\n        - (* t1 = TBool *) destruct t2.\n          + (* t2 = TNat *) right. intros t H. inversion H; subst.\n            apply hasType_det with (t1:=TBool) in H2. inversion H2. trivial.\n          + (* t2 = TBool *) left. exists TBool. auto. }\n      { (* e2 is untypable *)\n         right. intros t H. inversion H; subst. apply IHe2' in H4. auto. }\n    + (* e1 is untypable *)\n      right. intros t H. inversion H; subst. apply IHe1' in H2. auto.\nDefined.\n\nEval simpl in typeCheck' (Nat 0).\nEval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).\nEval simpl in typeCheck' (Plus (Nat 1) (Bool false)).\n(* Extraction typeCheck'. *)\n", "meta": {"author": "momohatt", "repo": "cpdt", "sha": "58ab808fbd6374b230f4123e3fa6c08fe9e93664", "save_path": "github-repos/coq/momohatt-cpdt", "path": "github-repos/coq/momohatt-cpdt/cpdt-58ab808fbd6374b230f4123e3fa6c08fe9e93664/textbook/Subset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8918110339361275, "lm_q1q2_score": 0.7825434725268149}}
{"text": "Require Import Problem PeanoNat Omega.\n\nLemma binom_n_Sn (n : nat) : binom n (S n) = 0.\nProof.\n  remember (S n) as k.\n  assert (k > n) by omega; clear Heqk.\n  revert k H.\n  induction n; simpl; intros.\n  - destruct k; omega.\n  - destruct k; [omega|].\n    rewrite IHn; [|omega].\n    rewrite IHn; omega.\nQed.\n\nLemma binom_sum_split (m n : nat) : binom_sum (S m) (S n) = binom_sum m (S n) + binom_sum m n.\nProof.\n  simpl.\n  repeat rewrite <- Nat.add_assoc.\n  apply Nat.add_cancel_l.\n  induction n.\n  * destruct m; simpl; auto.\n  * simpl.\n    repeat rewrite <- Nat.add_assoc.\n    rewrite IHn.\n    omega.\nQed.\n\nTheorem solution: task.\nProof.\n  unfold task.\n  induction n; [auto|].\n  replace (2 ^ S n) with (2 * 2^n) by (simpl; omega).\n  rewrite <- IHn; clear IHn.\n  rewrite binom_sum_split.\n  simpl.\n  rewrite binom_n_Sn.\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/031/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7825124841246007}}
{"text": "Require Import Arith.\nRequire Import List.\n\nRequire Import Omega.\n\nRequire Import listkit.\n\nParameter char : Set.\n\nDefinition leftpad c n (s : list char) :=\n  repeat c (n - length s) ++ s.\n\n(** Proving all three correctness conditions at once. *)\nLemma correctness:\n  forall c n s,\n    length (leftpad c n s) = max n (length s) /\\\n    allEq _ (take _ (n - length s) (leftpad c n s)) c /\\\n    drop _ (n - length s) (leftpad c n s) = s.\nProof.\n unfold leftpad.\n firstorder (autorewrite with list_lemmas; auto).\n    destruct (le_lt_dec n (length s)).\n     rewrite max_r; omega.\n    rewrite max_l; omega.\n   apply listall_repeat.\n  firstorder (autorewrite with list_lemmas; auto).\n firstorder (autorewrite with list_lemmas; auto).\nQed.\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/leftpad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.782512475971666}}
{"text": "(* Coq Exercise 1 / http://qnighy.github.io/coqex2014/ex1.html *)\n\nTheorem tautology : forall P : Prop, P -> P.\nProof.\n  intros P H.\n  assumption.\nQed.\n\n(*\nTheorem wrong : forall P : Prop, P.\nProof.\n  intros P.\nQed.\n*)\n\nTheorem Modus_ponens : forall P Q : Prop, P -> (P -> Q) -> Q.\nProof.\nintros P Q p pq.\napply pq. assumption.\nQed.\n\nTheorem Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P.\nProof.\nintros P Q H p.\ndestruct H as [nq pq].\napply nq. apply pq. assumption.\nQed.\n\nTheorem Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q.\nProof.\nintros P Q pq np.\ndestruct pq as [p|q].\n elim np. assumption.\nassumption.\nQed.\n\nTheorem DeMorgan1 : forall P Q : Prop, ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\nintros P Q H pq. destruct pq as [p q].\ndestruct H as [np|nq].\n apply np. assumption.\napply nq. assumption.\nQed.\n\nTheorem DeMorgan2 : forall P Q : Prop, ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\nintros P Q H pq. destruct H as [np nq].\ndestruct pq as [p|q].\n apply np. assumption.\napply nq. assumption.\nQed.\n\nTheorem DeMorgan3 : forall P Q : Prop, ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\nintros P Q H. split.\n intro p. apply H. left. assumption.\nintro q. apply H. right. assumption.\nQed.\n\nTheorem NotNot_LEM : forall P : Prop, ~ ~(P \\/ ~P).\nProof.\nintros P H. apply H.\nright. intro p. apply H. left. assumption.\nQed.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/coqex2014/coqex2014_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.782426768924849}}
{"text": "(* ************************************************************************** *)\n(* ************************************************************************** *)\n(* Pairs of Numbers *)\nModule NatList.\nInductive natprod : Type :=\n| pair (n1 n2 : nat).\nCheck (pair 3 2) : natprod.\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | pair x _ => x\n  end.\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair _ y => y\n  end.\nCompute (fst (pair 2 3)) : nat.\nNotation \"( x , y )\" := (pair x y).\nCompute (fst (2, 3)) : nat.\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.\nTheorem surjective_impairing' : forall (n m : nat),\n    (n, m) = (fst (n, m), snd (n, m)).\nProof.  reflexivity.\nQed.\nTheorem surjective_impairing : forall (p : natprod),\n    p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m].\n  reflexivity.\nQed.\n\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.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Exercise: 1 star, standard, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n    fst (swap_pair p) = snd p.\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Lists of Numbers *)\nInductive natlist : Type :=\n| nil\n| cons (n : nat) (l : natlist).\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nNotation \"x :: l\" := (cons x l)\n                       (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => []\n  | S count => n :: (repeat n count)\n  end.\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | [] => 0\n  | _ :: tl => 1 + length tl\n  end.\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | [] => l2\n  | hd :: tl => hd :: (app tl l2)\n  end.\nNotation \"x ++ y\" := (app x y)\n                       (right associativity, at level 60).\nExample test_app1 : [1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. reflexivity. Qed.\nExample test_app2 : nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3 : [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\nDefinition hd (default : nat) (l :natlist) : nat :=\n  match l with\n  | [] => default\n  | hd :: _ => hd\n  end.\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | _ :: tl => tl\n  end.\n\n(* ************************************************************************** *)\n(* Exercise: 2 stars, standard, especially useful (list_funs) *)\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | 0 :: tl => nonzeros tl\n  | hd :: tl => hd :: nonzeros tl\n  end.\nExample test_nonzeros :\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\nFixpoint is_odd (n : nat) : bool :=\n  match n with\n  | 0 => false\n  | 1 => true\n  | S (S n) => is_odd n\n  end.\nFixpoint oddmembers (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | hd :: tl =>\n    if is_odd hd then hd :: oddmembers tl\n    else oddmembers tl\n  end.\nExample test_oddmembers :\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\nDefinition countoddmembers (l : natlist) : nat :=\n  length (oddmembers l).\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 3 stars, advanced (alternate) *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | [], [] => []\n  | [], l2 => l2\n  | l1, [] => l1\n  | hd1 :: tl1, hd2 :: tl2 => hd1 :: hd2 :: (alternate tl1 tl2)\n  end.\nExample test_alternate1:\n  alternate [1;3;5] [2;4;6] = [1;2;3;4;5;6].\nProof. reflexivity. Qed.\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof. reflexivity. Qed.\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 3 stars, standard, especially useful (bag_functions) *)\nDefinition bag := natlist.\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n  | [] => 0\n  | hd :: tl =>\n    if Nat.eqb hd v then 1 + count v tl\n    else count v tl\n  end.\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.\nDefinition sum : bag -> bag -> bag := app.\nExample test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. reflexivity. Qed.\nDefinition add (v : nat) (s : bag) : bag := v :: s.\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.\nFixpoint member (v : nat) (s : bag) : bool :=\n  match s with\n  | [] => false\n  | hd :: tl =>\n    if Nat.eqb hd v then true\n    else member v tl\n  end.\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 3 stars, standard, optional (bag_more_functions) *)\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | [] => []\n  | hd :: tl =>\n    if Nat.eqb hd v then tl\n    else hd :: remove_one v tl\n  end.\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.\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | [] => []\n  | hd :: tl =>\n    if Nat.eqb hd v then remove_all v tl\n    else hd :: remove_all v tl\n  end.\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.\nFixpoint included (s1 : bag) (s2 : bag) : bool :=\n  match s1 with\n  | [] => true\n  | hd :: tl =>\n    if member hd s2 then included tl (remove_one hd s2)\n    else false\n  end.\nExample test_included1: included [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_included2: included [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* ************************************************************************** *)\n(* Exercise: 2 stars, standard, especially useful (add_inc_count) *)\nTheorem eq_n_n_true : forall n : nat,\n    Nat.eqb n n = true.\nProof.\n  intros n.\n  induction n as [|n' IHn].\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\nTheorem add_inc_count : forall (n : nat) (s : bag),\n    count n s + 1 = count n (n :: s) .\nProof.\n  intros n s.\n  induction s as [|n' s' IHs].\n  - simpl.\n    rewrite -> eq_n_n_true.\n    reflexivity.\n  - simpl.\n    rewrite -> eq_n_n_true.\n    assert (H: forall a, S a = a + 1). {\n      intros a.\n      induction a as [|a IHa].\n      - reflexivity.\n      - simpl. rewrite <- IHa. reflexivity.\n    }\n    rewrite <- H.\n    reflexivity.\nQed.\n\n(* ************************************************************************** *)\n(* Reasoning About Lists *)\n", "meta": {"author": "Ngoguey42", "repo": "software_foundations", "sha": "c797cb94aa1f6e8de6537d3a376164ab1beb6c5f", "save_path": "github-repos/coq/Ngoguey42-software_foundations", "path": "github-repos/coq/Ngoguey42-software_foundations/software_foundations-c797cb94aa1f6e8de6537d3a376164ab1beb6c5f/lf/MyLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.9005297801113612, "lm_q1q2_score": 0.7824043735261248}}
{"text": "Set Implicit Arguments.\nImport Nat.\n\n\n  Inductive le : nat -> nat -> Prop :=\n    le_n : forall n, le n n\n  | le_S : forall m n, le m n -> le m (S n).\n\n  Notation \"m <= n\" := (le m n).\n  \n  Definition le0 : forall n, 0 <= n :=\n    fix h n :=\n      match n with\n        0 => le_n 0\n      | S k => le_S (h k)\n      end.\n\n(**)\n\n\n\n  \n\n\n\n  \n  Fixpoint le0' n : 0 <= n :=\n    match n with\n      0 => le_n 0\n    | S k => le_S (le0' k)\n    end.\n\n  Lemma le0'' : forall n, 0 <= n.\n\n(**)\n  \n\n  \n\n\n  \n\n\n  Definition lt m n := le (S m) n.\n  Notation \"m < n\" := (lt m n).\n\n  Lemma lt0 : forall n, n = 0 \\/ 0 < n.\n\n(**)\n\n\n\n\n\n    \n\n\n  Theorem f_equal : forall A B (f : A -> B) x y, x = y -> f x = f y.\n  Proof.\n    intros. rewrite H. reflexivity.\n  Qed.\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/demo-le-lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8757869835428966, "lm_q1q2_score": 0.7823487550739897}}
{"text": "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\nDefinition even (n: nat): Prop :=\n    evenb n = true.\n\nInductive ev: nat -> Prop :=\n| ev_0: ev O\n| ev_SS: forall n: nat, ev n -> ev (S (S n)).\n\nFixpoint double (n: nat): nat :=\n    match n with\n    | O => O\n    | S n' => S (S (double n'))\n    end.\n\nTheorem double_even: forall n, ev (double n).\nProof.\n    intros n.\n    induction n. apply ev_0.\n    simpl. apply ev_SS. apply IHn.\nQed.\n\nTheorem ev__even: forall n, ev n -> even n.\nProof.\n    intros n E.\n    induction E as [| n' E'].\n    unfold even. reflexivity.\n    unfold even. apply IHE'.\nQed.\n\nLemma plus_helper: forall n m: nat, (S n) + m = S (n + m).\nProof.\n    intros n m.\n    induction m as [| m'].\n    reflexivity.\n    reflexivity.\nQed.\nTheorem ev_sum: forall n m,\n    ev n -> ev m -> ev (n+m).\nProof.\n    intros n m Hn Hm.\n    induction Hn.\n    apply Hm.\n    rewrite -> plus_helper. rewrite -> plus_helper. apply ev_SS. apply IHHn.\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.\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.\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (n+8).\nProof.\n    intros n B.\n    apply b_sum with (m:=8).\n    apply B. apply eight_is_beautiful.\nQed.\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    intros n B.\n    simpl.\n    apply b_sum with (n:=n) (m:=n+0).\n    apply B.\n    apply b_sum.\n    apply B. apply b_0.\nQed.\nTheorem b_times3: forall n, beautiful n -> beautiful (3*n).\nProof.\n    intros n B.\n    simpl.\n    apply b_sum with (n:=n) (m:=n+(n+0)). apply B.\n    apply b_times2. apply B.\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: forall n, gorgeous n -> gorgeous (13+n).\nProof.\n    intros n B.\n    apply g_plus3. apply g_plus5. apply g_plus5. apply B.\nQed.\n\nTheorem gorgeous_beautiful: forall n, gorgeous n -> beautiful n.\nProof. \n    intros n H.\n    induction H as [| n' | n'].\n    apply b_0.\n    apply b_sum. apply b_3. apply IHgorgeous.\n    apply b_sum. apply b_5. apply IHgorgeous.\nQed.\n\nTheorem gorgeous_sum: forall n m, gorgeous n -> gorgeous m -> gorgeous (n+m).\nProof.\n    intros n m Hn Hm.\n    induction Hn.\n    apply Hm.\n    apply g_plus3 with (n:=n+m). apply IHHn.\n    apply g_plus5 with (n:=n+m). apply IHHn.\nQed.\n\nTheorem ev_minus2: forall n, ev n -> ev (pred (pred n)).\nProof.\n    intros n E.\n    inversion E as [| n' E'].\n    apply ev_0.\n    apply E'.\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/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7822507166307748}}
{"text": "(* Exercise 62 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_062 : (forall x, ~exists y, R x y) -> (forall x, forall y, ~ R x y).\nProof.\nimp_i a1.\nall_i a.\nall_i b.\nneg_i (exists y:D, R a y) a2.\nall_e (forall x:D, ~(exists y:D, R x y)) a.\nhyp a1.\nexi_i b.\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_pred062.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7822507055570098}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nDefinition relation (X : Type) := X -> X -> Prop.\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\nPrint next_nat.\n\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function : partial_function next_nat.\nProof.\n  unfold partial_function. intros x y1 y2 H1 H2.\n  inversion H1. inversion H2. reflexivity.\nQed.\n\nPrint total_relation.\n\nTheorem le_not_a_partial_function : ~ (partial_function le).\nProof.\n  unfold partial_function. intro H.\n  assert (Nonsense: 0 = 1).\n  { apply H with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n.\n  }\n  discriminate Nonsense.\nQed.\n\nTheorem total_relation_not_partial :\n  ~(partial_function total_relation).\nProof.\n  unfold partial_function. intro H.\n  Print total_relation.\n  assert (Nonsense : 0 = 1).\n  { apply H with (x := 0).\n    - apply re_n.\n    - apply arti_sym. apply re_n.\n  }\n  discriminate Nonsense.\nQed.\n\nPrint empty_relation.\n\nTheorem empty_relation_pairtial:\n  partial_function empty_relation.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H.\nQed.\n\nDefinition reflexive {X : Type} (R : relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive : reflexive le.\nProof. unfold reflexive. 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).\n\nTheorem le_trans : transitive le.\nProof.\n  unfold transitive. intros a b c Hab Hbc.\n  induction Hbc.\n  - apply Hab.\n  - apply le_S. apply IHHbc.\nQed.\n\nTheorem le_trans' : transitive le.\nProof.\n  unfold transitive. intros a b c Hab.\n  apply le_ind.\n  - apply Hab.\n  - intros m H1 H2. apply le_S. apply H2.\nQed.\n\n\nTheorem lt_trans : transitive lt.\nProof.\n  unfold transitive. unfold lt.\n  intros a b c H. apply le_trans.\n  apply le_S. apply H.\nQed.\n\nTheorem lt_trans' : transitive lt.\nProof.\n  unfold transitive. unfold lt.\n  intros a b c H1. apply le_ind.\n  - apply le_S. apply H1.\n  - intros m H2 H3. apply le_S. apply H3.\nQed.\n\nTheorem lt_trans'' : 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. rewrite H0 in Hnm. apply Hnm.\n    + apply le_S. apply IHo'. apply H0.\nQed.\n\nTheorem lt_trans''': transitive lt.\nProof.\n  unfold transitive. intros a b c.\n  generalize dependent b.\n  generalize dependent a.\n  induction c as [|c' IH].\n  - intros. inversion H0.\n  - intros. unfold lt in *.\n    apply le_n_S. apply le_S_n in H0.\n    destruct a as [| a'] eqn:Ea.\n    + apply O_le_n.\n    + destruct b as [| b'] eqn:Eb.\n      * inversion H.\n      * apply IH with (a := a') (b := b').\n        { apply le_S_n. apply H. }\n        { apply H0. }\nQed.\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m.\n  apply (le_trans n (S n) m).\n  apply le_S. apply le_reflexive.\nQed.\n\nTheorem le_S_n : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m H. inversion H.\n  - apply le_reflexive.\n  - apply (le_trans n (S n) m).\n    + apply le_S. apply le_reflexive.\n    + apply H1.\nQed.\n\nTheorem le_Sn_n : forall n, ~(S n <= n).\nProof.\n  apply nat_ind.\n  - intro H. inversion H.\n  - intros n H. unfold not in *. intro H1. apply H.\n    apply le_S_n. apply H1.\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 : ~ (symmetric le).\nProof.\n  unfold symmetric. intro H.\n  assert (Hf : 0 <= 1 -> False).\n  { intro H'. apply H in H'. inversion H'. }\n  apply Hf. apply le_S. apply le_reflexive.\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 : antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a b H1 H2.\n  induction H2.\n  - reflexivity.\n  - apply (le_trans (S m) b m) in H1.\n    Search le. apply le_Sn_n in H1.\n    + contradiction.\n    + apply H2.\nQed.\n\nTheorem le_step : forall n m p,\n    n < m -> m <= S p -> n <= p.\nProof.\n  unfold lt. intros n m p H1 H2.\n  apply le_S_n. apply (le_trans _ m _).\n  - apply H1.\n  - apply H2.\nQed.\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\nTheorem le_order : order le.\nProof.\n  unfold order.\n  split.\n  - apply le_reflexive.\n  - split.\n    + apply le_antisymmetric.\n    + apply le_trans.\nQed.\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\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  - intro H. induction H.\n    + apply rt_refl.\n    + apply (rt_trans _ n m (S m)).\n      * apply IHle.\n      * apply rt_step. apply nn.\n  - intro H. induction H.\n    + inversion H. apply le_S. apply le_reflexive.\n    + apply le_reflexive.\n    + apply (le_trans x y z); assumption.\nQed.\n\nInductive clos_refl_trans_ln {A : Type} (R : relation A) (x : A)\n  : A -> Prop :=\n| rtln_refl : clos_refl_trans_ln R x x\n| rtln_trans (y z : A) (Hxy : R x y) (Hrest : clos_refl_trans_ln R y z) :\n    clos_refl_trans_ln R x z.\n\nLemma rsc_R : forall (X : Type) (R : relation X) (x y : X),\n    R x y -> clos_refl_trans_ln R x y.\nProof.\n  intros X R x y H. apply (rtln_trans R x y y).\n  - apply H.\n  - apply rtln_refl.\nQed.\n\nLemma rsc_trans : forall (X : Type) (R : relation X) (x y z : X),\n    clos_refl_trans_ln R x y ->\n    clos_refl_trans_ln R y z ->\n    clos_refl_trans_ln R x z.\nProof.\n  intros X R x y z H1 H2.\n  induction H1.\n  - apply H2.\n  - apply (rtln_trans R x y z).\n    + apply Hxy.\n    + apply IHclos_refl_trans_ln. apply H2.\nQed.\n\nTheorem rtc_rsc_coincide :\n  forall (X : Type) (R : relation X) (x y : X),\n    clos_refl_trans R x y <-> clos_refl_trans_ln R x y.\nProof.\n  intros X R x y. split.\n  - intro H. induction H.\n    + apply (rtln_trans R x y y).\n      * apply H.\n      * apply rtln_refl.\n    + apply rtln_refl.\n    + apply (rsc_trans X R x y z); assumption.\n  - intro H. induction H.\n    + apply rt_refl.\n    + apply (rt_trans R x y z).\n      * apply rt_step. apply Hxy.\n      * apply IHclos_refl_trans_ln.\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7822240172084793}}
{"text": "Require Import Permutation.\nRequire Import Recdef FunInd.\nRequire Import Omega.\n\nRequire List.\nImport List.ListNotations.\nOpen Scope list.\n\nSet Implicit Arguments.\n\nSection GroupEqual.\n\n  Variable A:Type.\n  Variable equal:A -> A -> bool.\n\n  Fixpoint gather_eq (x0: A) (acc: list A) (l: list A) : list A * list A :=\n    match l with\n    | [] => (acc, l)\n    | x::xs => if equal x x0 then\n                gather_eq x0 (acc ++ [x]) xs\n              else\n                let (xs, l') := gather_eq x0 acc xs in\n                (xs, x::l')\n    end.\n\n  Definition gather_eq1 (x:A) l : list A :=\n    fst (gather_eq x [] l).\n\n  Definition gather_eq2 (x:A) l : list A :=\n    snd (gather_eq x [] l).\n\n  Theorem gather_eq_lengths : forall x l acc xs l',\n      gather_eq x acc l = (xs, l') ->\n      length xs + length l' = length acc + length l.\n  Proof.\n    induction l; simpl; intros; auto.\n    inversion H; subst; auto.\n    destruct (equal a x); simpl.\n    apply IHl in H; simpl in *.\n    rewrite List.app_length in *; simpl in *.\n    omega.\n    destruct_with_eqn (gather_eq x acc l); simpl in *.\n    inversion H; subst; clear H; simpl.\n    apply IHl in Heqp.\n    omega.\n  Qed.\n\n  Lemma gather_eq12_lengths : forall (x:A) l,\n      length (gather_eq1 x l) + length (gather_eq2 x l) = length l.\n  Proof.\n    unfold gather_eq1, gather_eq2; intros.\n    destruct_with_eqn (gather_eq x [] l).\n    apply gather_eq_lengths in Heqp; simpl in *; auto.\n  Qed.\n\n  Lemma gather_eq2_smaller : forall (x:A) xs,\n      length (gather_eq2 x xs) < S (length xs).\n  Proof.\n    intros.\n    pose proof (gather_eq12_lengths x xs).\n    omega.\n  Qed.\n\n  Hint Resolve gather_eq2_smaller.\n\n  Function group_eq (l: list A) {measure length l} : list A :=\n    match l with\n    | [] => []\n    | x::xs => x::gather_eq1 x xs ++ group_eq (gather_eq2 x xs)\n    end.\n  Proof.\n    simpl; intros; subst; auto.\n  Qed.\n\n  Theorem group_eq_length : forall (l: list A),\n      length (group_eq l) = length l.\n  Proof.\n    intros.\n    remember (length l).\n    generalize dependent l.\n    induction n using lt_wf_ind; intros; subst.\n    rewrite group_eq_equation.\n    destruct l; intros; subst; simpl in *; auto.\n    rewrite List.app_length.\n    erewrite H; try reflexivity.\n    rewrite gather_eq12_lengths; auto.\n    auto.\n  Qed.\n\n  Hint Constructors Permutation.\n  Hint Resolve Permutation_sym.\n  Hint Resolve Permutation_middle.\n\n  Theorem gather_eq_permutation : forall (x:A) l acc xs l',\n      gather_eq x acc l = (xs, l') ->\n      Permutation (xs ++ l') (acc ++ l).\n  Proof.\n    induction l; simpl; intros.\n    inversion H; subst; clear H; simpl.\n    rewrite List.app_nil_r; auto.\n    destruct (equal a x).\n    apply IHl in H.\n    rewrite <- List.app_assoc in H; auto.\n    destruct_with_eqn (gather_eq x acc l).\n    inversion H; subst; clear H.\n    apply IHl in Heqp.\n    eauto.\n  Qed.\n\n  Theorem gather_eq12_permutation : forall (x:A) l,\n      Permutation (gather_eq1 x l ++ gather_eq2 x l) l.\n  Proof.\n    unfold gather_eq1, gather_eq2; intros.\n    destruct_with_eqn (gather_eq x [] l); simpl.\n    apply gather_eq_permutation in Heqp; auto.\n  Qed.\n\n  Theorem group_eq_permutation : forall (l: list A),\n      Permutation (group_eq l) l.\n  Proof.\n    intros.\n    remember (length l).\n    generalize dependent l.\n    induction n using lt_wf_ind; intros; subst.\n    rewrite group_eq_equation.\n    destruct l.\n    auto.\n    constructor.\n    transitivity (gather_eq1 a l ++ gather_eq2 a l);\n      [ | eauto using gather_eq12_permutation ].\n    eapply Permutation_app; eauto.\n    eapply H; simpl; eauto.\n  Qed.\n\nEnd GroupEqual.\n\nLtac compute_group_eq :=\n  rewrite group_eq_equation; unfold gather_eq1, gather_eq2;\n  cbn beta iota zeta delta [gather_eq fst snd].\n\nModule Examples.\n\n  Example gather_eq_ex1 :\n    gather_eq (fun x y => if PeanoNat.Nat.eq_dec x y then true else false)\n              3 [] [2;3;4;3;2;3;5] =\n    ([3;3;3], [2;4;2;5]) := eq_refl.\n\n  Example group_eq_ex1 :\n    group_eq (fun x y => if Nat.eq_dec x y then true else false)\n             [2;3;4;3;2;3;5] = [2;2;3;3;3;4;5].\n  Proof.\n    repeat (compute_group_eq; cbn [Nat.eq_dec app nat_rec nat_rect]).\n    reflexivity.\n  Qed.\n\nEnd Examples.\n", "meta": {"author": "tchajed", "repo": "ac-reasoning", "sha": "cbbca47caf60270f682ea0dfe7524621d8591dc1", "save_path": "github-repos/coq/tchajed-ac-reasoning", "path": "github-repos/coq/tchajed-ac-reasoning/ac-reasoning-cbbca47caf60270f682ea0dfe7524621d8591dc1/src/GroupEqual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.782224014623112}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Logic.\nFrom Coq Require Import Lia.\n\n(* ################################################################# *)\n(** * Inductively Defined Propositions *)\n\n(** In the [Logic] chapter, we looked at several ways of writing\n    propositions, including conjunction, disjunction, and existential\n    quantification.\n\n    In this chapter, we bring yet another new tool into the mix:\n    _inductively defined propositions_.\n\n    To begin, some examples... *)\n\n(* ================================================================= *)\n(** ** The Collatz Conjecture *)\n\n(** The _Collatz Conjecture_ is a famous open problem in number\n    theory.\n\n    Its statement is surprisingly simple.  First, we define a function\n    [f] on numbers, as follows: *)\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\n(** Next, we look at what happens when we repeatedly apply [f] to some\n    given starting number.  For example, [f 12] is [6], and [f 6] is\n    [3], so by repeatedly applying [f] we get the sequence [12, 6, 3,\n    10, 5, 16, 8, 4, 2, 1].\n\n    Similarly, if we start with [19], we get the longer sequence [19,\n    58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8,\n    4, 2, 1].\n\n    Both of these sequences eventually reach [1].  The question posed\n    by Collatz was: Does the sequence starting from _any_ natural\n    number eventually reach [1]? *)\n\n(** To formalize this question in Coq, we might try to define a\n    recursive _function_ that computes the total number of steps that\n    it takes for such a sequence to reach [1]. *)\n\nFail Fixpoint reaches_1_in (n : nat) :=\n  if n =? 1 then 0\n  else 1 + reaches_1_in (f n).\n\n(** This definition is rejected by Coq's termination checker, since\n    the argument to the recursive call, [f n], is not \"obviously\n    smaller\" than [n].\n\n    Indeed, this isn't just a silly limitation of the termination\n    checker.  Functions in Coq are required to be total, and checking\n    that this particular function is total would be equivalent to\n    settling the Collatz conjecture! *)\n\n(** Fortunately, there is another way to do it: We can express the\n    concept \"reaches [1] eventually\" as an _inductively defined\n    property_ of numbers: *)\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\n(** The details of such definitions are written will be explained\n    below; for the moment, the way to read this one is: \"The number\n    [1] reaches [1], and any number [n] reaches [1] if [f n] does.\" *)\n\n(** The Collatz conjecture then states that the sequence beginning\n    from _any_ number reaches [1]: *)\n\nConjecture collatz : forall n, reaches_1 n.\n\n(** If you succeed in proving this conjecture, you've got a bright\n    future as a number theorist.  But don't spend too long on it --\n    it's been open since 1937! *)\n\n(* ================================================================= *)\n(** ** Transitive Closure *)\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\n(** For example, a familiar binary relation on [nat] is [le], the\n    less-than-or-equal-to relation. *)\n\nModule LePlayground.\n\n(** The following definition says that there are two ways to\n    show that one number is less than or equal to another: either\n    observe that they are the same number, or, if the second has the\n    form [S m], give evidence that the first is less than or equal to\n    [m]. *)\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(** The _transitive closure_ of a relation [R] is the smallest\n    relation that contains [R] and that is transitive.  *)\n\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\n    How would you modify this definition so that it defines _reflexive\n    and_ transitive closure?  How about reflexive, symmetric, and\n    transitive closure? *)\n\nInductive clos_refl_trans {X: Type} (R: X->X->Prop) : X->X->Prop :=\n  | t_step' (x y : X) :\n      R x y ->\n      clos_refl_trans R x y\n  | t_refl (x : X) :\n      clos_refl_trans R x x\n  | t_symm (x y : X):\n      clos_refl_trans R x y ->\n      clos_refl_trans R y x\n  | t_trans' (x y z : X) :\n      clos_refl_trans R x y ->\n      clos_refl_trans R y z ->\n      clos_refl_trans R x z.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Permutations *)\n\n(** The familiar mathematical concept of _permutation_ also has an\n    elegant formulation as an inductive relation.  For simplicity,\n    let's focus on permutations of lists with exactly three\n    elements. *)\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(** This definition says:\n      - If [l2] can be obtained from [l1] by swapping the first and\n        second elements, then [l2] is a permutation of [l1].\n      - If [l2] can be obtained from [l1] by swapping the second and\n        third elements, then [l2] is a permutation of [l1].\n      - If [l2] is a permutation of [l1] and [l3] is a permutation of\n        [l2], then [l3] is a permutation of [l1]. *)\n\n(** **** Exercise: 1 star, standard, optional (perm)\n\n    According to this definition, is [[1;2;3]] a permutation of\n    [[3;2;1]]?  Is [[1;2;3]] a permutation of itself? *)\n\n(* FILL IN HERE\n\n    [] *)\n\n(* ================================================================= *)\n(** ** Evenness (yet again) *)\n\n(** We've already seen two ways of stating a proposition that a number\n    [n] is even: We can say\n\n      (1) [even n = true], or\n\n      (2) [exists k, n = double k].\n\n    A third possibility, which we'll use as a running example for the\n    rest of this chapter, is to say that [n] is even if we can\n    _establish_ its evenness from the following rules:\n\n       - The number [0] is even.\n       - If [n] is even, then [S (S n)] is even. *)\n\n(** (Defining evenness in this way may seem a bit confusing,\n    since we have already seen another perfectly good way of doing\n    it -- \"[n] is even if it is equal to the result of doubling some\n    number\". But it makes a convenient running example because it is\n    simple and compact.) *)\n\n(** To illustrate how this new definition of evenness works,\n    let's imagine using it to show that [4] is even. First, we give\n    the rules names for easy reference:\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    Now, by rule [ev_SS], it suffices to show that [2] is even. This,\n    in turn, is again guaranteed by rule [ev_SS], as long as we can\n    show that [0] is even. But this last fact follows directly from\n    the [ev_0] rule. *)\n\n(** We can translate the informal definition of evenness from above\n    into a formal [Inductive] declaration, where each \"way that a\n    number can be even\" corresponds to a separate constructor: *)\n\nInductive ev : nat -> Prop :=\n  | ev_0                       : ev 0\n  | ev_SS (n : nat) (H : ev n) : ev (S (S n)).\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 [ev]\n    appears to the _right_ of the colon on the first line, 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].  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    or equivalently:\n\n    Inductive list (X:Type) : Type :=\n      | nil                       : list X\n      | cons (x : X) (l : list X) : 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 type (i.e., [list X]).  But if we had tried to bring [nat]\n   to the left of the colon in defining [ev], 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 (H: wrong_ev n) : wrong_ev (S (S n)).\n(* ===> Error: Last occurrence of \"[wrong_ev]\" must have \"[n]\" as 1st\n        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, while in [Inductive ev : nat -> Prop := ...], the\n    unnamed [nat] argument is an index. *)\n\n(** We can think of this as defining a Coq property [ev : nat ->\n    Prop], together with \"evidence constructors\" [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))]. *)\n\n(** These evidence constructors can be thought of as \"primitive\n    evidence of evenness\", and they can be used just like proven\n    theorems.  In particular, we can use Coq's [apply] tactic with the\n    constructor names to obtain evidence for [ev] of particular\n    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 to combine several\n    constructors: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** In this way, we can also prove theorems that have hypotheses\n    involving [ev]. *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.  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  induction n.\n  - 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    _destruct_ such evidence, reasoning about how it could have been\n    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    _case analysis_ or by _induction_ on such evidence.  Let's look at a\n    few examples to see what this means in practice. *)\n\n(* ================================================================= *)\n(** ** Inversion on Evidence *)\n\n(** Suppose we are proving some fact involving a number [n], and\n    we are given [ev n] as a hypothesis.  We already know how to\n    perform case analysis on [n] using [destruct] or [induction],\n    generating separate subgoals for the case where [n = O] and the\n    case where [n = S n'] for some [n'].  But for some proofs we may\n    instead want to analyze the evidence for [ev n] _directly_.\n\n    As a tool for such proofs, we can formalize the intuitive\n    characterization that we gave above for evidence of [ev n], using\n    [destruct]. *)\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 as [ | n' E'] eqn:EE.\n  - (* E = ev_0 : ev 0 *)\n    left. reflexivity.\n  - (* E = ev_SS n' E' : ev (S (S n')) *)\n    right. exists n'. split. reflexivity. apply E'.\nQed.\n\n(** Facts like this are often called \"inversion lemmas\" because they\n    allow us to \"invert\" some given information to reason about all\n    the different ways it could have been derived.\n\n    Here, there are two ways to prove [ev n], and the inversion lemma\n    makes this explicit. *)\n\n(** We can use the inversion lemma that we proved above to help\n    structure proofs: *)\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.\n  - destruct H1 as [n' [Hnm Hev]]. injection Hnm as Heq.\n    rewrite Heq. apply Hev.\nQed.\n\n(** Note how the inversion lemma produces two subgoals, which\n    correspond to the two ways of proving [ev].  The first subgoal is\n    a contradiction that is discharged with [discriminate].  The\n    second subgoal makes use of [injection] and [rewrite].\n\n    Coq provides a handy tactic called [inversion] that factors out\n    this common pattern, saving us the trouble of explicitly stating\n    and proving an inversion lemma for every [Inductive] definition we\n    make.\n\n    Here, the [inversion] tactic can detect (1) that the first case,\n    where [n = 0], does not apply and (2) that the [n'] that appears\n    in the [ev_SS] case must be the same as [n].  It includes an\n    \"[as]\" annotation similar to [destruct], allowing us to assign\n    names rather than have Coq choose them. *)\n\nTheorem evSS_ev' : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.  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. Compare: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. apply ev_inversion in H.  destruct H as [ | [m [Hm _]]].\n  - discriminate.\n  - discriminate.\nQed.\n\nTheorem one_not_even' : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(** **** Exercise: 1 star, standard (inversion_practice)\n\n    Prove the following result using [inversion].  (For extra\n    practice, 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. inversion H as [| n0 H0 Heq0]. inversion H0 as [| n1 H1 Heq1].\n  apply H1.\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 as [| n0 H0 Heq0].\n  inversion H0 as [| n1 H1 Heq1].\n  inversion H1.\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 to analyze\n    evidence for arbitrary inductively defined propositions, not just\n    equality.  As examples, we'll use it to re-prove some theorems\n    from chapter [Tactics].  (Here we are being a bit lazy by\n    omitting the [as] clause from [inversion], thereby asking Coq to\n    choose names for the variables and hypotheses that it introduces.) *)\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. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O -> 2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\n(** Here's how [inversion] works in general.\n      - Suppose the name [H] refers to an assumption [P] in the\n        current context, where [P] has been defined by an [Inductive]\n        declaration.\n      - Then, for each of the constructors of [P], [inversion H]\n        generates a subgoal in which [H] has been replaced by the\n        specific conditions under which this constructor could have\n        been used to prove [P].\n      - Some of these subgoals will be self-contradictory; [inversion]\n        throws these away.\n      - The ones that are left represent the cases that must be proved\n        to establish the original goal.  For those, [inversion] adds\n        to the proof context all equations 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 *) unfold Even.\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 seems\n    unpromising, because (as we've noted before) the induction\n    hypothesis will talk about [n-1] (which is _not_ even!).  Thus, it\n    seems better to first try [inversion] on the evidence for [ev].\n    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 *) exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n\n    Unfortunately, the second case is harder.  We need to show [exists\n    n0, S (S n') = double n0], 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 a similar\n    one that involves a _different_ piece of evidence for [ev]: namely\n    [E'].  More formally, we could finish our proof if we could show\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 would suffice. *)\n    assert (H: (exists k', n' = double k')\n               -> (exists n0, S (S n') = double n0)).\n        { intros [k' EQ'']. exists (S k'). simpl.\n          rewrite <- EQ''. reflexivity. }\n    apply H.\n\n    (** Unfortunately, now we are stuck. To see this clearly, let's\n        move [E'] back into the goal from the hypotheses. *)\n\n    generalize dependent E'.\n\n    (** Now it is obvious that we are trying to prove another instance\n        of the same theorem we set out to prove -- only here we are\n        talking about [n'] instead of [n]. *)\nAbort.\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** If this story feels 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 hypothesis for each recursive occurrence of\n    the property in question.\n\n    To prove that a property of [n] holds for all even numbers (i.e.,\n    those for which [ev n] holds), we can use induction on [ev\n    n]. This requires us to prove two things, corresponding to the two\n    ways in which [ev n] could have been constructed. If it was\n    constructed by [ev_0], then [n=0] and the property must hold of\n    [0]. If it was constructed by [ev_SS], then the evidence of [ev n]\n    is of the form [ev_SS n' E'], where [n = S (S n')] and [E'] is\n    evidence for [ev n']. In this case, the inductive hypothesis says\n    that the property we are trying to prove holds for [n']. *)\n\n(** Let's try proving that 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    unfold Even. 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.\n    unfold Even. 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. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique across many areas -- in particular for\n    formalizing the semantics of programming languages. *)\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 En Em.\n  induction En.\n  - apply Em.\n  - simpl. apply ev_SS. apply IHEn.\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 the [Logic]\n    chapter) of applying theorems to arguments, and note that the same\n    technique works with constructors of inductively defined\n    propositions. *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros n.\n  split.\n  - intros H. 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 H. induction H.\n    + apply ev'_0.\n    + rewrite <- plus_1_l with (S n). rewrite <- plus_n_Sm. rewrite <- plus_1_l.\n      rewrite add_assoc. apply ev'_sum.\n      * apply ev'_2.\n      * apply IHev.\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 n m.\n  intros E1 E2.\n  induction E2.\n  - apply E1.\n  - simpl in E1. inversion E1 as [| sum E3 H]. apply (IHE2 E3).\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 m p Enm Enp.\n  apply ev_ev__ev with (n + n).\n  - assert (ev ((n + m) + (n + p))) as H.\n      { apply ev_sum. apply Enm. apply Enp. }\n    rewrite add_comm with n m in H.\n    rewrite <- add_assoc with m n (n + p) in H.\n    rewrite add_assoc with n n p in H.\n    rewrite add_comm with (n + n) p in H.\n    rewrite add_assoc with m p (n + n) in H.\n    rewrite add_comm with (m + p) (n + n) in H.\n    apply H.\n  - rewrite <- double_plus. 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 numbers\n    that we briefly saw above. *)\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(** (We've written the definition a bit differently this time,\n    giving explicit names to the arguments to the constructors and\n    moving them to the left of the colons.) *)\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(** **** 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\nInductive total_relation : nat -> nat -> Prop :=\n  | total_rel (n m : nat) : total_relation n m\n.\n\nTheorem total_relation_is_total : forall n m, total_relation n m.\n  Proof.\n  intros n m. apply (total_rel n m). Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation)\n\n    Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop :=\n.\n\nTheorem empty_relation_is_empty : forall n m, ~ empty_relation n m.\n  Proof.\n  intros n m H.\n  inversion H.\nQed.\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(** 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\n(** **** Exercise: 5 stars, standard, optional (le_and_lt_facts) *)\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Emn Eno.\n  induction Eno as [|o Eno IH].\n  - apply Emn.\n  - apply (le_S m o IH).\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n.\n  induction n.\n  - apply le_n.\n  - apply (le_S 0 n IHn).\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H as [|m H IH].\n  - apply le_n.\n  - apply (le_S (S n) (S m) IH).\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m H.\n  induction m.\n  - inversion H as [H0 | zero H1 H2]. apply le_n. inversion H1.\n  - inversion H as [H0 | Sm H1 H2]. apply le_n. apply (le_S n m (IHm H1)).\nQed.\n\nTheorem lt_ge_cases : forall n m,\n  n < m \\/ n >= m.\nProof.\n  intros n m.\n  destruct m.\n  - right. apply O_le_n.\n  - induction n.\n    + left. apply n_le_m__Sn_le_Sm. apply O_le_n.\n    + destruct IHn.\n      * destruct H.\n        right. apply le_n.\n        left. apply n_le_m__Sn_le_Sm. apply H.\n      * right. apply le_S. apply H.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b.\n  induction b.\n  - rewrite add_0_r. apply le_n.\n  - rewrite <- plus_n_Sm. apply (le_S a (a + b) IHb).\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  induction H.\n  - split.\n    + apply le_plus_l.\n    + rewrite add_comm. apply le_plus_l.\n  - destruct IHle as [H1 H2].\n    split.\n    + apply (le_S n1 m H1).\n    + apply (le_S n2 m H2).\nQed.\n\nTheorem add_le_cases : forall n m p q,\n  n + m <= p + q -> n <= p \\/ m <= q.\n  (** Hint: May be easiest to prove by induction on [n]. *)\nProof.\n  induction n.\n  - left. apply O_le_n.\n  - intros. destruct p.\n    + right. apply plus_le in H.\n      destruct H as [H1 H2].\n      rewrite plus_O_n in H1.\n      apply H2.\n    + simpl in H.\n      rewrite plus_n_Sm with n m in H.\n      rewrite plus_n_Sm with p q in H.\n      apply IHn in H. destruct H.\n      * left. apply n_le_m__Sn_le_Sm. apply H.\n      * right. apply Sn_le_Sm__n_le_m. apply H.\nQed.\n\nTheorem plus_le_compat_l : forall n m p,\n  n <= m ->\n  p + n <= p + m.\nProof.\n  intros n m p.\n  induction p.\n  - intros. rewrite plus_O_n. rewrite plus_O_n. apply H.\n  - intros. simpl. apply n_le_m__Sn_le_Sm. apply (IHp H).\nQed.\n\nTheorem plus_le_compat_r : forall n m p,\n  n <= m ->\n  n + p <= m + p.\nProof.\n  intros n m p H.\n  rewrite add_comm with n p.\n  rewrite add_comm with m p.\n  apply plus_le_compat_l.\n  apply H.\nQed.\n\nTheorem le_plus_trans : forall n m p,\n  n <= m ->\n  n <= m + p.\nProof.\n  intros n m p.\n  generalize dependent n.\n  generalize dependent m.\n  induction p.\n  - intros. rewrite add_comm. rewrite plus_O_n. apply H.\n  - intros. destruct H.\n    + apply le_plus_l.\n    + simpl.\n      apply IHp in H.\n      apply le_S in H. rewrite plus_n_Sm in H.\n      apply (le_S n (m + S p) H).\nQed.\n\nTheorem n_lt_m__n_le_m : forall n m,\n  n < m ->\n  n <= m.\nProof.\n  intros n m H.\n  apply le_S in H.\n  apply Sn_le_Sm__n_le_m in H.\n  apply H.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  intros n1 n2 m H.\n  inversion H as [H12 | n H12 Hm].\n  - split.\n    + apply n_le_m__Sn_le_Sm. apply le_plus_l.\n    + apply n_le_m__Sn_le_Sm. rewrite add_comm. apply le_plus_l.\n  - rewrite <- Hm in H. apply Sn_le_Sm__n_le_m in H.\n    apply plus_le in H. destruct H as [H1 H2].\n    split.\n    + apply n_le_m__Sn_le_Sm. apply H1.\n    + apply n_le_m__Sn_le_Sm. apply H2.\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 m.\n  generalize dependent m.\n  induction n.\n  - intros. apply O_le_n.\n  - intros. destruct m.\n    + discriminate.\n    + simpl in H. apply IHn in H. apply n_le_m__Sn_le_Sm. apply H.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\n  (** Hint: May be easiest to prove by induction on [m]. *)\nProof.\n  intros n m.\n  generalize dependent n.\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 n H).\nQed.\n\n(** Hint: The next two can easily be proved without using [induction]. *)\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  intros n m.\n  split.\n  - apply leb_complete.\n  - 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 n m o Hnm Hmo.\n  apply leb_complete in Hnm.\n  apply leb_complete in Hmo.\n  apply leb_correct.\n  apply le_trans with m.\n  apply Hnm. apply Hmo.\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\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(* 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  split.\n  - intros. induction H.\n    + reflexivity.\n    + simpl. f_equal. apply IHR.\n    + rewrite <- plus_n_Sm. f_equal. apply IHR.\n    + simpl in IHR.\n      apply S_injective in IHR. rewrite <- plus_n_Sm in IHR.\n      apply S_injective in IHR.\n      apply IHR.\n    + rewrite add_comm in IHR. apply IHR.\n  - intros.\n    rewrite <- H.\n    destruct H.\n    induction m.\n      + induction n. apply c1. apply c3. apply IHn.\n      + simpl. apply c2. apply IHm.\nQed.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 3 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    - (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\nInductive subseq : list nat -> list nat -> Prop :=\n  | subseq0 l : subseq [] l\n  | subseq1 x l1 l2 (H : subseq l1 l2) : subseq (x :: l1) (x :: l2)\n  | subseq2 x l1 l2 (H : subseq l1 l2) : subseq l1 (x :: l2)\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  induction l as [| x l IH].\n  - apply subseq0.\n  - apply (subseq1 x l l IH).\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H as [| x l1 l2 H IH | x l1 l2 H IH].\n  - apply subseq0.\n  - simpl. apply (subseq1 x l1 (l2 ++ l3) IH).\n  - simpl. apply (subseq2 x l1 (l2 ++ l3) IH).\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  (* Hint: be careful about what you are doing induction on and which\n     other things need to be generalized... *)\n  intros l1 l2 l3 H12 H23.\n  generalize dependent l1.\n  induction H23 as [| x l2 l3 H23 IH | x l2 l3 H23 IH].\n  - intros.\n    assert (l1 = []) as Hl1. inversion H12. reflexivity.\n    rewrite Hl1. apply subseq0.\n  - intros. inversion H12 as [| x' l1' l2' H12' | x' l1' l2' H12'].\n    + apply subseq0.\n    + apply (subseq1 x l1' l3 (IH l1' H12')).\n    + apply (subseq2 x l1 l3 (IH l1 H12')).\n  - intros. apply (subseq2 x l1 l3 (IH l1 H12)).\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (R_provability2)\n\n    Suppose we give Coq the following definition:\n\n    Inductive R : nat -> list nat -> Prop :=\n      | c1                    : R 0     []\n      | c2 n l (H: R n     l) : R (S n) (n :: l)\n      | c3 n l (H: R (S n) l) : R n     l.\n\n    Which of the following propositions are provable?\n\n    - [R 2 [1;0]]\n    - [R 1 [1;2;1;0]]\n    - [R 6 [3;2;1;0]]  *)\n\n(* FILL IN HERE\n\n    [] *)\n\n(* ################################################################# *)\n(** * A Digression on Notation *)\n\n(** There are several equivalent ways of writing inductive\n    types.  We've mostly seen this style... *)\n\nModule bin1.\nInductive bin : Type :=\n  | Z\n  | B0 (n : bin)\n  | B1 (n : bin).\nEnd bin1.\n\n(** ... which omits the result types because they are all bin. *)\n\n(** It is completely equivalent to this... *)\nModule bin2.\nInductive bin : Type :=\n  | Z : bin\n  | B0 (n : bin) : bin\n  | B1 (n : bin) : bin.\nEnd bin2.\n\n(** ... where we fill them in, and this... *)\n\nModule bin3.\nInductive bin : Type :=\n  | Z : bin\n  | B0 : bin -> bin\n  | B1 : bin -> bin.\nEnd bin3.\n\n(** ... where we put everything on the right of the colon. *)\n\n(** For inductively defined _propositions_, we need to explicitly give\n    the result type for each constructor (because they are not all the\n    same), so the first style doesn't make sense, but we can use\n    either the second or the third interchangeably. *)\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    (Technical aside: We depart slightly from standard practice in\n    that we do not require the type [T] to be finite.  This results in\n    a somewhat different theory of regular expressions, but the\n    difference is not significant for present 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\n  where \"s =~ re\" := (exp_match s re).\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  unfold not. intros. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros.\n  destruct H.\n  - apply MUnionL. apply H.\n  - apply MUnionR. apply H.\nQed.\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros T ss re H1.\n  induction ss as [| s1 ss IH].\n  - simpl. apply MStar0.\n  - simpl. apply MStarApp.\n    + apply H1. left. reflexivity.\n    + apply IH. intros s2 H2. apply H1. right. apply H2.\nQed.\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 we want to prove the following intuitive\n    result: If a regular expression [re] matches some string [s], then\n    all elements of [s] must occur as character literals somewhere in\n    [re].\n\n    To state this as a theorem, we first define a function [re_chars]\n    that 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(** The main theorem: *)\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    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  := match re with\n     | EmptySet => false\n     | EmptyStr => true\n     | Char _ => 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 _ => 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  split.\n  - intros H. destruct H as [s Hmatch].\n    induction Hmatch.\n    + reflexivity.\n    + reflexivity.\n    + simpl. rewrite IHHmatch1. rewrite IHHmatch2. reflexivity.\n    + simpl. rewrite IHHmatch. reflexivity.\n    + simpl. apply orb_true_iff. right. apply IHHmatch.\n    + reflexivity.\n    + reflexivity.\n  - intros H.\n    induction re.\n    + inversion H.\n    + exists []. apply MEmpty.\n    + exists [t]. apply MChar.\n    + simpl in H. apply andb_true_iff in H. destruct H as [H1 H2].\n      apply IHre1 in H1. destruct H1 as [s1 H1].\n      apply IHre2 in H2. destruct H2 as [s2 H2].\n      exists (s1 ++ s2). apply MApp. apply H1. apply H2.\n    + simpl in H. apply orb_true_iff in H. destruct H as [H1 | H2].\n      * apply IHre1 in H1. destruct H1 as [s1 H1].\n        exists s1. apply MUnionL. apply H1.\n      * apply IHre2 in H2. destruct H2 as [s2 H2].\n        exists s2. apply MUnionR. apply H2.\n    + exists []. apply MStar0.\nQed.\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(** Now, 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    (We can begin by generalizing [s2], since it's pretty clear that we\n    are going to have to walk over both [s1] and [s2] in parallel.) *)\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\n    from the definition of [exp_match]), we have lost a very important\n    bit of information from [H1]: the fact that [s1] matched something\n    of the form [Star re].  This means that we have to give proofs for\n    _all_ seven constructors of this definition, even though all but\n    two of them ([MStar0] and [MStarApp]) are contradictory.  We can\n    still 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\n\n      s2     =~ Char x' ->\n      x'::s2 =~ Char x'\n\n    which is clearly impossible. *)\n\n  - (* MChar. *) intros s2 H. simpl. (* Stuck... *)\nAbort.\n\n(** The problem here is that [induction] over a Prop hypothesis\n    only works properly with hypotheses that are \"completely\n    general,\" i.e., ones in which all the arguments are variables,\n    as opposed to more complex expressions like [Star re].\n\n    (In this respect, [induction] on evidence behaves more like\n    [destruct]-without-[eqn:] than like [inversion].)\n\n    A possible, but awkward, way to solve this problem is \"manually\n    generalizing\" over the problematic expressions by adding\n    explicit equality 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\n    directly, because the argument to the first hypothesis is\n    sufficiently general, which means that we can discharge most cases\n    by inverting the [re' = Star re] equality in the context.\n\n    This works, but it makes the statement of the lemma a bit ugly.\n    Fortunately, there is a better way... *)\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  intros T s re Hmatch.\n  remember (Star re) as re'.\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  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - exists []. split. reflexivity. intros s' contra. inversion contra.\n  - destruct (IH2 Heqre') as [ss' [H1 H2]].\n    injection Heqre' as Heqre'. destruct Heqre'.\n    exists (s1 :: ss'). split.\n    + simpl. rewrite <- H1. reflexivity.\n    + intros s' HIn. destruct HIn.\n      * rewrite <- H. apply Hmatch1.\n      * apply H2 in H. apply H.\nQed.\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 -- hence the name\n    [weak_pumping].)\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(** Complete the proof below. Several of the lemmas about [le] that\n    were in an optional exercise earlier in this chapter may also be\n    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  - (* MChar *)\n    intros contra. apply Sn_le_Sm__n_le_m in contra. inversion contra.\n  - (* MApp *)\n    intros H. simpl in H.\n    rewrite app_length in H.\n    apply add_le_cases in H. destruct H.\n    + apply IH1 in H.\n      destruct H as [s1' [s2' [s3' [Happ [Hne Hnapp]]]]].\n      exists s1'. exists s2'. exists (s3' ++ s2).\n      split. rewrite Happ.\n      rewrite <- app_assoc with T s1' (s2' ++ s3') s2.\n      rewrite <- app_assoc with T s2' s3' s2.\n      reflexivity.\n      split. apply Hne.\n      intros m.\n      rewrite app_assoc with T s1' (napp m s2') (s3' ++ s2).\n      rewrite app_assoc with T (s1' ++ napp m s2') s3' s2.\n      rewrite <- app_assoc with T s1' (napp m s2') s3'.\n      apply MApp. apply Hnapp. apply Hmatch2.\n    + apply IH2 in H.\n      destruct H as [s1' [s2' [s3' [Happ [Hne Hnapp]]]]].\n      exists (s1 ++ s1'). exists s2'. exists s3'.\n      split. rewrite Happ.\n      rewrite <- app_assoc with T s1 s1' (s2' ++ s3').\n      reflexivity.\n      split. apply Hne.\n      intros m.\n      rewrite <- app_assoc with T s1 s1' (napp m s2' ++ s3').\n      apply MApp. apply Hmatch1. apply Hnapp.\n  - (* MUnionL *)\n    intros H. simpl in H.\n    apply plus_le in H. destruct H as [H H'].\n    apply IH in H.\n    destruct H as [s1' [s2' [s3' [Happ [Hne Hnapp]]]]].\n    exists s1'. exists s2'. exists s3'.\n    split. apply Happ.\n    split. apply Hne.\n    intros m. apply MUnionL. apply Hnapp.\n  - (* MUnionR *)\n    intros H. simpl in H.\n    apply plus_le in H. destruct H as [H' H].\n    apply IH in H.\n    destruct H as [s1' [s2' [s3' [Happ [Hne Hnapp]]]]].\n    exists s1'. exists s2'. exists s3'.\n    split. apply Happ.\n    split. apply Hne.\n    intros m. apply MUnionR. apply Hnapp.\n  - (* MStar0 *)\n    intros H.\n    assert (Hp : (pumping_constant re) >= 1).\n    { apply pumping_constant_ge_1. }\n    inversion H as [H0|]. rewrite H0 in Hp. inversion Hp.\n  - (* MStarApp *)\n    intros H.\n    rewrite app_length in H.\n    assert (Hp : (pumping_constant re) >= 1).\n    { apply pumping_constant_ge_1. }\n    assert (Hl: (1 <= length s1 \\/ 1 <= length s2)).\n    { destruct s1. right. apply le_trans with (pumping_constant re). apply Hp. apply H. left. simpl. apply n_le_m__Sn_le_Sm. apply O_le_n. }\n    exists []. exists (s1 ++ s2). exists [].\n    split. rewrite app_nil_r. reflexivity.\n    split. destruct Hl as [Hl | Hl].\n    + destruct s1. inversion Hl. discriminate.\n    + destruct s2. inversion Hl. destruct s1. discriminate. discriminate.\n    + induction m.\n      * apply MStar0.\n      * simpl in IHm. simpl. rewrite <- app_assoc.\n        apply star_app.\n        apply (MStarApp s1 s2 re Hmatch1 Hmatch2).\n        apply IHm.\nQed.\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  - (* MChar *)\n    intros contra. apply Sn_le_Sm__n_le_m in contra. inversion contra.\n  - (* MApp *)\n    intros H.\n    assert (le_n_n: forall n : nat, ~ n < n).\n    { intros n contra. induction n. inversion contra. apply IHn. apply Sn_le_Sm__n_le_m in contra. apply contra. }\n    rewrite app_length in H. simpl in H.\n    destruct (lt_ge_cases (length s1) (pumping_constant re1)) as [H1 | H1].\n    + destruct (lt_ge_cases (length s2) (pumping_constant re2)) as [H2 | H2].\n      * apply add_le_cases in H. destruct H as [H1' | H2'].\n        ** assert (contra: pumping_constant re1 < pumping_constant re1).\n           {\n             apply le_trans with (n := S (length s1)).\n             apply n_le_m__Sn_le_Sm. apply H1'. apply H1.\n           }\n           apply le_n_n in contra. exfalso. apply contra.\n        ** assert (contra: pumping_constant re2 < pumping_constant re2).\n           {\n             apply le_trans with (n := S (length s2)).\n             apply n_le_m__Sn_le_Sm. apply H2'. apply H2.\n           }\n           apply le_n_n in contra. exfalso. apply contra.\n      * apply IH2 in H2.\n        destruct H2 as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n        exists (s1 ++ s1'). exists s2'. exists s3'.\n        split. rewrite Happ.\n        rewrite <- app_assoc with T s1 s1' (s2' ++ s3').\n        reflexivity.\n        split. apply Hne.\n        split. simpl. rewrite app_length. rewrite <- add_assoc.\n        apply le_trans with (n := length s1 + pumping_constant re2).\n        apply plus_le_compat_l. apply Hlen.\n        apply plus_le_compat_r. apply n_lt_m__n_le_m in H1. apply H1.\n        intros m.\n        rewrite <- app_assoc with T s1 s1' (napp m s2' ++ s3').\n        apply MApp. apply Hmatch1. apply Hnapp.\n    + apply IH1 in H1.\n      destruct H1 as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n      exists s1'. exists s2'. exists (s3' ++ s2).\n      split. rewrite Happ.\n      rewrite <- app_assoc with T s1' (s2' ++ s3') s2.\n      rewrite <- app_assoc with T s2' s3' s2.\n      reflexivity.\n      split. apply Hne.\n      split. simpl.\n      apply le_trans with (n := pumping_constant re1).\n      apply Hlen. apply le_plus_l.\n      intros m.\n      rewrite app_assoc with T s1' (napp m s2') (s3' ++ s2).\n      rewrite app_assoc with T (s1' ++ napp m s2') s3' s2.\n      rewrite <- app_assoc with T s1' (napp m s2') s3'.\n      apply MApp. apply Hnapp. apply Hmatch2.\n  - (* MUnionL *)\n    intros H. simpl in H.\n    apply plus_le in H. destruct H as [H H'].\n    apply IH in H.\n    destruct H as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n    exists s1'. exists s2'. exists s3'.\n    split. apply Happ.\n    split. apply Hne.\n    split. simpl. apply le_trans with (n := pumping_constant re1). apply Hlen. apply le_plus_l.\n    intros m. apply MUnionL. apply Hnapp.\n  - (* MUnionR *)\n    intros H. simpl in H.\n    apply plus_le in H. destruct H as [H' H].\n    apply IH in H.\n    destruct H as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n    exists s1'. exists s2'. exists s3'.\n    split. apply Happ.\n    split. apply Hne.\n    split. simpl. apply le_trans with (n := pumping_constant re2). apply Hlen. rewrite add_comm. apply le_plus_l.\n    intros m. apply MUnionR. apply Hnapp.\n  - (* MStar0 *)\n    intros H.\n    assert (Hp : (pumping_constant re) >= 1).\n    { apply pumping_constant_ge_1. }\n    inversion H as [H0|]. rewrite H0 in Hp. inversion Hp.\n  - (* MStarApp *)\n    intros H.\n    rewrite app_length in H.\n    assert (Hp : (pumping_constant re) >= 1).\n    { apply pumping_constant_ge_1. }\n    assert (Hl: (1 <= length s1 \\/ 1 <= length s2)).\n    { destruct s1. right. apply le_trans with (pumping_constant re). apply Hp. apply H. left. simpl. apply n_le_m__Sn_le_Sm. apply O_le_n. }\n    destruct s1 as [| x s11].\n    + destruct (lt_ge_cases (length s2) (pumping_constant (Star re))) as [H2 | H2].\n      * exists []. exists s2. exists [].\n        split. rewrite app_nil_r. reflexivity.\n        split. destruct Hl as [Hl | Hl].\n        ** inversion Hl.\n        ** destruct s2. inversion Hl. discriminate.\n        ** split. apply n_lt_m__n_le_m in H2. apply H2.\n        induction m. apply MStar0. simpl. rewrite <- app_assoc. apply star_app. apply Hmatch2. apply IHm.\n      * apply IH2 in H2.\n        destruct H2 as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n        exists s1'. exists s2'. exists s3'.\n        split. rewrite Happ. reflexivity.\n        split. apply Hne.\n        split. apply Hlen.\n        apply Hnapp.\n    + remember (x :: s11) as s1.\n      destruct (lt_ge_cases (length s1) (pumping_constant re)) as [H1 | H1].\n      * exists []. exists s1. exists s2.\n        split. reflexivity.\n        split. rewrite Heqs1. discriminate.\n        split. apply n_lt_m__n_le_m in H1. apply H1.\n        intros m. simpl. apply napp_star. apply Hmatch1. apply Hmatch2.\n      * apply IH1 in H1.\n        destruct H1 as [s1' [s2' [s3' [Happ [Hne [Hlen Hnapp]]]]]].\n        exists s1'. exists s2'. exists (s3' ++ s2).\n        split. rewrite Happ. simpl.\n        rewrite <- app_assoc with (m := s2' ++ s3').\n        rewrite <- app_assoc with (m := s3').\n        reflexivity.\n        split. apply Hne.\n        split. apply Hlen.\n        intros m. rewrite app_assoc. rewrite app_assoc. apply MStarApp.\n        rewrite <- app_assoc. apply Hnapp. apply Hmatch2.\nQed.\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 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 sort of reasoning by defining an inductive\n    proposition that yields a better case-analysis principle for [n =?\n    m].  Instead of generating the assumption [(n =? m) = true], which\n    usually requires some massaging before we can use it, this\n    principle gives us right away the assumption we really need: [n =\n    m].\n\n    Following the terminology introduced in [Logic], we call this\n    the \"reflection principle for equality on numbers,\" and we say\n    that the boolean [n =? m] is _reflected in_ the proposition [n =\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].  It states that the property [P]\n    _reflects_ (intuitively, is equivalent to) the boolean [b]: that\n    is, [P] holds if and only if [b = true].\n\n    To see this, notice that, by definition, the only way we can\n    produce evidence for [reflect P true] is by showing [P] and then\n    using the [ReflectT] constructor.  If we invert this statement,\n    this means that we can extract evidence for [P] from a proof of\n    [reflect P true].\n\n    Similarly, the only way to show [reflect P false] is by tagging\n    evidence for [~ P] with the [ReflectF] constructor. *)\n\n(** To put this observation to work, we first prove 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 eqn:Eb.\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  intros P b r. destruct r as [HP | HnP].\n  - split. reflexivity. intros. apply HP.\n  - split.\n    + intros HP. exfalso. apply (HnP HP).\n    + discriminate.\nQed.\n(** [] *)\n\n(** We can think of [reflect] as a kind of variant of the usual \"if\n    and only if\" connective; the advantage of [reflect] is that, by\n    destructing a hypothesis or lemma of the form [reflect P b], we\n    can perform case analysis on [b] while _at the same time_\n    generating appropriate hypothesis in the two branches ([P] in the\n    first subgoal and [~ P] in the second). *)\n\n(** Let's use [reflect] to produce a smoother proof of\n    [filter_not_empty_In].\n\n    We begin by recasting the [eqb_eq] lemma in terms of [reflect]: *)\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(** The proof of [filter_not_empty_In] now goes as follows.  Notice\n    how the calls to [destruct] and [rewrite] in the earlier proof of\n    this theorem are combined here into a single call to\n    [destruct]. *)\n\n(** (To see this clearly, execute 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  intros n l Hcount. induction l as [| m l' IHl'].\n  - intros contra. inversion contra.\n  - simpl in Hcount. destruct (eqbP n m).\n    + inversion Hcount.\n    + intros contra. destruct contra as [Heq | HIn].\n      * symmetry in Heq. apply (H Heq).\n      * apply (IHl' Hcount HIn).\nQed.\n(** [] *)\n\n(** This small example shows reflection giving 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    This use of [reflect] was popularized by _SSReflect_, a Coq\n    library that has been used to formalize important results in\n    mathematics, including the 4-color theorem and the Feit-Thompson\n    theorem.  The name SSReflect stands for _small-scale reflection_,\n    i.e., the pervasive use of reflection to simplify small proof\n    steps by turning them into 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.\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]] has two occurrences of the element [1] but\n    does not 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  | nostutter0 : nostutter []\n  | nostutter1 x : nostutter [x]\n  | nostutter2 x y l (P: x <> y) (H: nostutter (y :: l)) : nostutter (x :: y :: l)\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].\nProof.\n  apply nostutter2. discriminate.\n  apply nostutter2. discriminate.\n  apply nostutter2. discriminate.\n  apply nostutter2. discriminate.\n  apply nostutter2. discriminate.\n  apply nostutter1.\nQed.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\nProof. apply nostutter0. Qed.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\nProof. apply nostutter1. Qed.\n(* \n  Proof. repeat constructor; auto. Qed.\n*)\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\nProof.\n  intros contra1.\n  inversion contra1 as [| |x1 y1 l1 _ contra2].\n  inversion contra2 as [| |x2 y2 l2 contra _].\n  apply contra. reflexivity.\nQed.\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    First define what it means for one list to be a merge of two\n    others.  Do this with an inductive relation, not a [Fixpoint].  *)\n\nInductive merge {X:Type} : list X -> list X -> list X -> Prop :=\n  | mergel0 l : merge l [] l\n  | merger0 l : merge [] l l\n  | mergel1 x l l1 l2 (H: merge l1 l2 l) : merge (x :: l1) l2 (x :: l)\n  | merger1 x l l1 l2 (H: merge l1 l2 l) : merge l1 (x :: l2) (x :: l)\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 X test l l1 l2 H H1 H2.\n  induction H as [| |x l l1 l2 _ IHm|x l l1 l2 _ IHm].\n  - induction l.\n    + reflexivity.\n    + destruct H1 as [Htest H1]. simpl. rewrite Htest. rewrite (IHl H1). reflexivity.\n  - induction l.\n    + reflexivity.\n    + destruct H2 as [Htest H2]. simpl. rewrite Htest. apply (IHl H2).\n  - destruct H1 as [Htest H1]. simpl. rewrite Htest. rewrite (IHm H1 H2). reflexivity.\n  - destruct H2 as [Htest H2]. simpl. rewrite Htest. rewrite (IHm H1 H2). reflexivity.\nQed.\n\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\nTheorem subs_filter : forall (test: nat->bool) (l1 l2 : list nat),\n  subseq l1 l2 ->\n  All (fun n => test n = true) l1 ->\n  length l1 <= length (filter test l2).\nProof.\n  intros test l1 l2 H H1.\n  induction H as [| x l1 l2 H IH | x l1 l2 H IH].\n  - apply O_le_n.\n  - destruct H1 as [Htest H1]. simpl. rewrite Htest. simpl. apply n_le_m__Sn_le_Sm. apply (IH H1).\n  - simpl. destruct (test x).\n    + simpl. apply le_S. apply (IH H1).\n    + apply (IH H1).\nQed.\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\nInductive pal {X:Type} : list X -> Prop :=\n  | pal0 : pal []\n  | pal1 x : pal [x]\n  | pal2 x l (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 X l.\n  induction l.\n  - apply pal0.\n  - simpl. rewrite app_assoc. apply pal2. apply IHl.\nQed.\n\nTheorem pal_rev : forall (X:Type) (l: list X) , pal l -> l = rev l.\nProof.\n  intros X l H.\n  induction H as [| | x l _ IH].\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite <- IH. rewrite <- app_assoc. reflexivity.\nQed.\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\nTheorem palindrome_converse: forall {X: Type} (l: list X),\n    l = rev l -> pal l.\nProof.\n  intros X.\n  assert (rev_length: forall (l: list X), length (rev l) = length l).\n  {\n    intros l. induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite -> app_length.\n      simpl. rewrite -> IHl'. rewrite add_comm.\n      reflexivity.\n  }\n  assert (lemma: forall (n: nat) (l: list X), length l <= n -> l = rev l -> pal l).\n  {\n    induction n.\n    - intros l Hn _. destruct l. apply pal0. inversion Hn.\n    - destruct l.\n      + intros _ _. apply pal0.\n      + intros Hlen Hrev. destruct (rev l) as [| x' l'] eqn:H'.\n        * destruct l. apply pal1. apply f_equal with (f:=rev) in H'. rewrite rev_involutive in H'. discriminate.\n        * simpl in Hrev. rewrite H' in Hrev. rewrite Hrev. injection Hrev as H0 H. destruct H0. apply pal2.\n          apply f_equal with (f:=rev) in H. rewrite rev_app_distr in H. simpl in H. rewrite H' in H. injection H as H.\n          apply f_equal with (f:=length) in H'. simpl in H'.\n          simpl in Hlen. apply Sn_le_Sm__n_le_m in Hlen.\n          rewrite rev_length in H'.\n          assert (Hlen': length l' <= n).\n          { apply Sn_le_Sm__n_le_m. rewrite <- H'. apply le_S. apply Hlen. }\n          apply (IHn l' Hlen' H).\n  }\n  intros l.\n  apply (lemma (length l) l). apply le_n.\nQed.\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\nInductive disjoint {X : Type} : list X -> list X -> Prop :=\n  | disjoint0 l : disjoint [] l\n  | disjoint1 x l1 l2 (P: ~ In x l2) (H: disjoint l1 l2) : disjoint (x :: l1) l2\n.\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\nInductive NoDup {X : Type} : list X -> Prop :=\n  | NoDup0 : NoDup []\n  | NoDup1 x l (P: ~ In x l) (H: NoDup l) : NoDup (x :: l)\n.\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\n\nTheorem disjoint_NoDup_app : forall (X:Type) (l1:list X) (l2:list X), NoDup l1 -> NoDup l2 -> disjoint l1 l2 -> NoDup (l1 ++ l2).\nProof.\n  intros X l1 l2 H1 H2 H.\n\n  induction H as [| x l1 l2 P2 Hd].\n  - apply H2.\n  - simpl. apply NoDup1.\n    + intros contra. apply In_app_iff in contra. destruct contra as [contra | contra].\n      * inversion H1 as [| x1 l1' P1]. apply (P1 contra).\n      * apply (P2 contra).\n    + inversion H1 as [| x1 l1' P1 H1']. apply (IHHd H1' H2).\nQed.\n\nTheorem NoDup_app : forall (X:Type) (l1:list X) (l2:list X), NoDup (l1 ++ l2) -> NoDup l1 /\\ NoDup l2.\nProof.\n  intros.\n  split.\n  - induction l1. apply NoDup0. apply NoDup1.\n    + intros contra. inversion H. apply P. apply In_app_iff. left. apply contra.\n    + inversion H. apply (IHl1 H1).\n  - induction l1.\n    + apply H.\n    + inversion H. apply (IHl1 H1).\nQed.\n\nTheorem NoDup_app_disjoint : forall (X:Type) (l1:list X) (l2:list X), NoDup (l1 ++ l2) -> disjoint l1 l2.\nProof.\n  intros X l1 l2 H.\n  induction l1.\n  - apply disjoint0.\n  - apply disjoint1.\n    + inversion H. intros contra. apply P. apply In_app_iff. right. apply contra.\n    + inversion H. apply (IHl1 H1).\nQed.\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 and useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  intros.\n  induction l.\n  - inversion H.\n  - inversion H.\n    + exists []. exists l. rewrite H0. reflexivity.\n    + apply IHl in H0. destruct H0 as [l1 [l2 H0]].\n      exists (x0 :: l1). exists l2. rewrite H0. 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  | repeats1 x l (P: In x l): repeats (x :: l)\n  | repeats2 x l (H: repeats l): repeats (x :: l)\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. *)\nTheorem pigeonhole_principle: excluded_middle ->\n  forall (X:Type) (l1  l2:list X),\n  (forall x, In x l1 -> In x l2) ->\n  length l2 < length l1 ->\n  repeats l1.\nProof.\n  intros EM X l1. induction l1 as [|x l1' IHl1'].\n  - intros. inversion H0.\n  - intros. destruct (EM (In x l1')) as [HIn | HnIn].\n    + apply repeats1. apply HIn.\n    + apply repeats2.\n      destruct (in_split X x l2) as [l0 [l2' H3]].\n      { apply H. simpl. left. reflexivity. }\n      apply IHl1' with (l0 ++ l2').\n      * intros. apply In_app_iff. assert (In x0 l2). apply H. right. apply H1.\n        rewrite H3 in H2. apply In_app_iff in H2. destruct H2. left. apply H2.\n        right. destruct H2. rewrite H2 in HnIn. exfalso. apply HnIn. apply H1. apply H2.\n      * apply f_equal with (f:=length) in H3. rewrite app_length in H3. rewrite add_comm in H3. simpl in H3. rewrite app_length. rewrite add_comm. rewrite H3 in H0. simpl in H0. apply Sn_le_Sm__n_le_m in H0. apply H0.\nQed.\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 automatically.\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 implement 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  intros.\n  split.\n  - intros. inversion H.\n    destruct s1.\n    + left. split. apply H3. apply H4.\n    + right. inversion H1 as [H1']. destruct H1'. exists s1. exists s2. split. reflexivity. split. apply H3. apply H4.\n  - intros.\n    destruct H as [[H1 H2] | [s1 [s2 [H1 [H2 H3]]]]].\n    + assert (silly: a :: s = [] ++ a :: s). reflexivity. rewrite silly. apply MApp. apply H1. apply H2.\n    + rewrite H1. assert (silly: a :: s1 ++ s2 = (a :: s1) ++ s2). reflexivity. rewrite silly. apply MApp. apply H2. apply H3.\nQed.\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  split.\n  - remember (a :: s) as s'. remember (Star re) as re'.\n    intros H. induction H as [| | | | | | s1 s2 re' H1 _ H2 IH].\n    + discriminate.\n    + discriminate.\n    + discriminate.\n    + discriminate.\n    + discriminate.\n    + discriminate.\n    + destruct s1.\n      * apply (IH Heqs' Heqre').\n      * injection Heqre' as Heqre'. destruct Heqre'.\n        injection Heqs' as Heqs' Happ. destruct Heqs'.\n        exists s1. exists s2.\n        split. rewrite Happ. reflexivity.\n        split. apply H1. apply H2.\n  - intros H. destruct H as [s1 [s2 [H1 [H2 H3]]]].\n    rewrite H1.\n    assert (silly: a :: s1 ++ s2 = (a :: s1) ++ s2). reflexivity. rewrite silly.\n    apply (MStarApp (a :: s1) s2 re H2 H3).\nQed.\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  := match re with\n     | EmptySet => false\n     | EmptyStr => true\n     | Char _ => false\n     | App re1 re2 => (match_eps re1) && (match_eps re2)\n     | Union re1 re2 => (match_eps re1) || (match_eps re2)\n     | Star _ => true\n  end.\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  intros re.\n  induction re.\n  - apply ReflectF. intros contra. inversion contra.\n  - apply ReflectT. apply MEmpty.\n  - apply ReflectF. intros contra. inversion contra.\n  - simpl. inversion IHre1 as [H1 Hb1 | H1 Hb1].\n    + inversion IHre2 as [H2 Hb2 | H2 Hb2].\n      * apply ReflectT. apply (MApp [] re1 [] re2 H1 H2).\n      * apply ReflectF.\n        intros contra. inversion contra as [| | s1 re1' s2 re2' H1' H2'| | | |].\n        destruct s2. apply (H2 H2'). destruct s1. discriminate. discriminate.\n    + apply ReflectF.\n      intros contra. inversion contra as [| | s1 re1' s2 re2' H1' H2'| | | |].\n      destruct s1. apply (H1 H1'). discriminate.\n  - simpl. inversion IHre1 as [H1 Hb1 | H1 HB1].\n    + apply ReflectT. apply (MUnionL [] re1 re2 H1).\n    + inversion IHre2 as [H2 Hb2 | H2 Hb2].\n      * apply ReflectT. apply (MUnionR re1 [] re2 H2).\n      * apply ReflectF.\n        intros contra. inversion contra as [| | | s1 re1' re2' H1' | re1' s1 re2' H2' | |].\n        ** apply (H1 H1').\n        ** apply (H2 H2').\n  - apply ReflectT. apply MStar0.\nQed.\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  := match re with\n     | EmptySet => EmptySet\n     | EmptyStr => EmptySet\n     | Char x => if eqb x a then EmptyStr else EmptySet\n     | App re1 re2 => if match_eps re1 then Union (derive a re2) (App (derive a re1) re2) else App (derive a re1) re2\n     | Union re1 re2 => Union (derive a re1) (derive a re2)\n     | Star re => App (derive a re) (Star re)\n     end.\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  reflexivity. Qed.\n\n(** \"c\" =~ Char c: *)\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof.\n  reflexivity. Qed.\n\n(** \"c\" =~ Char d: *)\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof.\n  reflexivity. Qed.\n\n(** \"c\" =~ App (Char c) EmptyStr: *)\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof.\n  reflexivity. Qed.\n\n(** \"c\" =~ App EmptyStr (Char c): *)\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof.\n  reflexivity. Qed.\n\n(** \"c\" =~ Star c: *)\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof.\n  reflexivity. Qed.\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  reflexivity. Qed.\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  reflexivity. Qed.\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  intros a re s.\n  split.\n  - generalize dependent s. induction re.\n    + intros s H. apply null_matches_none in H. destruct H.\n    + intros s H. apply empty_nomatch_ne in H. destruct H.\n    + intros s H. simpl. destruct (eqb_spec t a) as [HEq | HnEq].\n      * destruct HEq. apply char_eps_suffix in H. rewrite H. apply MEmpty.\n      * assert (HnEq': a <> t). { intros contra. apply HnEq. rewrite contra. reflexivity. }\n        apply (char_nomatch_char t a s HnEq') in H. destruct H.\n    + intros s H. simpl. destruct (match_eps_refl re1) as [_ | Hnm].\n      * apply app_ne in H. destruct H as [[H1 H2] | [s1 [s2 [H [H1 H2]]]]].\n        ** apply MUnionL. apply (IHre2 s H2).\n        ** apply MUnionR. rewrite H. apply MApp. apply (IHre1 s1 H1). apply H2.\n      * apply app_ne in H. destruct H as [[H1 H2] | [s1 [s2 [H [H1 H2]]]]].\n        ** exfalso. apply Hnm. apply H1.\n        ** rewrite H. apply MApp. apply (IHre1 s1 H1). apply H2.\n    + intros s H. simpl. apply union_disj in H. destruct H as [Hl | Hr].\n      * apply MUnionL. apply (IHre1 s Hl).\n      * apply MUnionR. apply (IHre2 s Hr).\n    + intros s H. simpl. apply star_ne in H. destruct H as [s1 [s2 [H [H1 H2]]]].\n      rewrite H. apply MApp. apply (IHre s1 H1). apply H2.\n  - generalize dependent s. induction re.\n    + intros s H. apply null_matches_none in H. destruct H.\n    + intros s H. apply null_matches_none in H. destruct H.\n    + intros s H. simpl in H. destruct (eqb_spec t a) as [HEq | HnEq].\n      * destruct HEq. apply empty_matches_eps in H. rewrite H. apply MChar.\n      * assert (HnEq': a <> t). { intros contra. apply HnEq. rewrite contra. reflexivity. }\n        apply (char_nomatch_char t a s HnEq'). apply null_matches_none in H. apply H.\n    + intros s H. simpl in H. apply app_ne.\n      * destruct (match_eps_refl re1) as [Hm | Hnm].\n        ** apply union_disj in H. destruct H as [Hl | Hr].\n           *** left. split. apply Hm. apply (IHre2 s Hl).\n           *** right. apply app_exists in Hr. destruct Hr as [s1 [s2 [H [H1 H2]]]].\n               exists s1. exists s2. split. rewrite H. reflexivity. split. apply (IHre1 s1 H1). apply H2.\n        ** right. apply app_exists in H. destruct H as [s1 [s2 [H [H1 H2]]]].\n           exists s1. exists s2. split. rewrite H. reflexivity. split. apply (IHre1 s1 H1). apply H2.\n    + intros s H. simpl in H. apply union_disj in H. destruct H as [Hl | Hr].\n      * apply MUnionL. apply (IHre1 s Hl).\n      * apply MUnionR. apply (IHre2 s Hr).\n    + intros s H. apply star_ne.\n      simpl in H. apply app_exists in H. destruct H as [s1 [s2 [H [H1 H2]]]].\n      exists s1. exists s2. split. rewrite H. reflexivity. split. apply (IHre s1 H1). apply H2.\nQed.\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  := match s with\n     | (a :: s) => regex_match s (derive a re)\n     | [] => match_eps re\n     end.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (regex_match_correct)\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_match_correct : matches_regex regex_match.\nProof.\n  intros s.\n  induction s as [|a s].\n  - intros re. simpl. destruct (match_eps_refl re). apply ReflectT. apply H. apply ReflectF. apply H.\n  - intros re. simpl. destruct (IHs (derive a re)) as [Htrue | Hfalse].\n    + apply ReflectT. apply (derive_corr a re s). apply Htrue.\n    + apply ReflectF. intros contra. apply Hfalse. apply (derive_corr a re s). apply contra.\nQed.\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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7821807019211858}}
{"text": "(* Exercise 29 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_029 : (forall y, (exists x, (P y -> Q x)) -> (P y -> exists x, Q x)).\nProof.\nall_i a.\nimp_i a1.\nimp_i a2.\nexi_e (exists x:D, P a -> Q x) b a3.\nhyp a1.\nexi_i b.\nimp_e (P a).\nhyp a3.\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_pred029.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951142221377825, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7820187959973505}}
{"text": "Require Import SetoidClass SetoidCat Monoid Algebra.SetoidCat.NatUtils.\n\n\nSection NatMonoid.\n\n  Open Scope nat_scope.\n\n  Lemma nat_plus_associativity : forall a b c, a + b + c = a + (b + c).\n  Proof.\n    intros. induction a. reflexivity.\n    simpl. congruence.\n  Qed.\n\n  Instance nat_Monoid : @Monoid nat natS.\n  Proof.\n    exists (0) (plusS).\n    intros. reflexivity.\n    intros. rewrite plus_n_O. reflexivity.\n    intros. apply nat_plus_associativity.\n  Defined.\n\nEnd NatMonoid.\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/Monoid/NatUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422241476942, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7820187941306508}}
{"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.\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": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/number/Parity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.7819974898251754}}
{"text": "Require Import Omega.\nRequire Import prelims.\nRequire Import repeater.\nRequire Import increasing_expanding.\nRequire Import inverse.\nRequire Import countdown.\n\n(*\n===================================================================================\n*************** SECTION 6: INVERSE HYPEROPS, DIVISION, LOG AND LOG* ***************\n===================================================================================\n *)\n\n(* \n * We use countdown to implement an inverse tower for the Hyperoperation.\n * Interestingly, the 2nd, 3rd and 4th levels of this tower correspond to \n * divcision, logc base b and log* base b, which are not defined in the \n * Coq Standard Library. \n *\n * Our definitions, which use countdown, offer enough versatility and \n * flexibility to substantiate easy and direct proof for a vast range \n * of facts about these functions.\n *)\n\n\n(* ****** INVERSE-HYPEROP TOWER ****** *)\n\nFixpoint inv_hyperop a n b :=\n  match n with\n  | 0 => b - 1\n  | S n' =>\n    countdown_to (inv_hyperop a n') (hyperop_init a n') b\n  end.\n\n(* Handy results to transform goals involving inv_hyperop *)\nTheorem inv_hyperop_recursion :\n  forall n a,\n    inv_hyperop a (S n) = countdown_to (inv_hyperop a n) (hyperop_init a n).\nProof. trivial. Qed.\n\n(* Several results about first few levels of inv_hyperop.\n   Used to prove correctness of divcision and logc later on. *)\n\nTheorem inv_hyperop_0_contract_strict :\n  forall a k, contract_strict_above k (inv_hyperop a 0).\nProof. intro a. split; intro n; simpl; omega. Qed.\n\nTheorem inv_hyperop_1 :\n  forall a b, inv_hyperop a 1 b = b - a.\nProof.\n  intros a b. rewrite inv_hyperop_recursion. remember (b - a) as m.\n  generalize dependent b. induction m.\n  - intros b Hb. apply countdown_recursion.\n    1: apply inv_hyperop_0_contract_strict.\n       unfold hyperop_init; omega.\n  - intros b Hb. remember (m + a) as n. rewrite <- (IHm n) by omega.\n    replace n with (inv_hyperop a 0 b)\n        by (simpl; unfold hyperop_init; omega).\n    apply countdown_recursion.\n    1: apply inv_hyperop_0_contract_strict.\n    unfold hyperop_init; omega.\nQed.\n\nCorollary inv_hyperop_1_repeat :\n  forall a k m, repeat (inv_hyperop a 1) k m = m - k * a.\nProof.\n  intros a k m. induction k; [simpl; omega|].\n  remember (inv_hyperop a 1) as f. simpl.\n  rewrite IHk, Heqf, inv_hyperop_1; omega.\nQed.\n\n(* \n * Main theorem of this section. \n * Establishes the correctness of the inverse hyperoperations' \n * definition given in inv_hyperop.v \n *)\nTheorem inv_hyperop_correct :\n  forall a n, 2 <= a -> upp_inv_rel (inv_hyperop a n) (hyperop a n).\nProof.\n  intros a n Ha.\n  assert (forall m, repeatable_from (hyperop_init a m) (hyperop a m)).\n  { induction m.\n    1: rewrite repeatable_simpl; split; simpl;\n      try split; try intros u v; omega.\n    destruct m; try destruct m.\n    1, 3: try replace (hyperop a (S (S (S m)))) with\n            (repeater_from (hyperop a (S (S m)))\n               (hyperop_init a (S (S m)))) by trivial;\n      apply repeater_repeatable; simpl; try omega; assumption.\n    rewrite repeatable_simpl. split; [|simpl; omega].\n    intros u v. repeat rewrite hyperop_2. intros.\n    apply (mult_lt_compat_r _ _ _ H). omega.\n  }\n  induction n.\n  1: simpl. intros u v. omega.\n  destruct (H n) as [_ Hn].\n  apply countdown_repeater_upp_inverse; assumption.\nQed.\n\n(* ****** DIVISION AND LOGARITHM ********************************* *)\n\n(* Computes ceiling of b / a *)\nDefinition divc a b := inv_hyperop a 2 b.\n\nTheorem divc_correct :\n  forall a b m, 1 <= a -> divc a b <= m <-> b <= m * a.\nProof.\n  intros a b m Ha. destruct a; [omega|].\n  unfold divc. rewrite inv_hyperop_recursion.\n  rewrite countdown_repeat\n      by (split; intro n; rewrite inv_hyperop_1; omega).\n  rewrite inv_hyperop_1_repeat. unfold hyperop_init. omega.\nQed.\n\n(* Computes ceiling of logc_a(b) *)\nDefinition logc a b := inv_hyperop a 3 b.\n\nTheorem logc_correct :\n  forall a b m, 2 <= a -> logc a b <= m <-> b <= a ^ m.\nProof.\n  intros a b m Ha.\n  unfold logc. rewrite <- hyperop_3.\n  apply inv_hyperop_correct; trivial.\nQed.\n\n(* Computes log*_a(b).\n   Its correctness has already been established in inv_hyperop_correct *)\nDefinition logstar a b := inv_hyperop a 4 b.", "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/applications.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8558511451289038, "lm_q1q2_score": 0.7819711008527664}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(** Elements *)\n\nDefinition elements {A} (f : _ -> A) n :=\n  let l := iota 0 n.+1 in zip l (map f l).\n\n(** Triangular number *)\nDefinition delta n := (n.+1 * n)./2.\n\nCompute elements delta 10.\n\n(** Hints : halfD half_bit_double *)\nLemma deltaS n : delta n.+1 = delta n + n.+1.\nAdmitted.\n\n(** Hints   big_ord_recr big_ord_recl big_ord0 *)\nLemma deltaE n : delta n = \\sum_(i < n.+1) i.\nAdmitted.\n\n(* Hints half_leq *)\nLemma leq_delta m n : m <= n -> delta m <= delta n.\nAdmitted.\n\n(** Hints sqrnD *)\nLemma delta_square n : (8 * delta n).+1 = n.*2.+1 ^ 2.\nAdmitted.\n\n(**  Triangular root *)\nDefinition troot n := \n let l := iota 0 n.+2 in\n (find (fun x => n < delta x) l).-1.\n\nCompute elements troot 10.\n\nLemma troot_gt0 n : 0 < n -> 0 < troot n.\nAdmitted.\n\n(** Hints before_find find_size size_iota nth_iota *)\nLemma leq_delta_root m : delta (troot m) <= m.\nAdmitted.\n\n(** Hints hasP mem_iota half_bit_double half_leq nth_find nth_iota *)\nLemma ltn_delta_root m : m < delta (troot m).+1.\nAdmitted.\n\nLemma leq_root_delta m n : (n <= troot m) = (delta n <= m).\nAdmitted.\n\nLemma leq_troot m n : m <= n -> troot m <= troot n.\nAdmitted.\n\nLemma trootE m n : (troot m == n) = (delta n <= m < delta n.+1).\nAdmitted.\n\nLemma troot_deltaK n : troot (delta n) = n.\nAdmitted.\n\n(**  The modulo for triangular numbers *)\nDefinition tmod n := n - delta (troot n).\n\nLemma tmod_delta n : tmod (delta n) = 0.\nAdmitted.\n\nLemma tmodE n : n = delta (troot n) + tmod n.\nAdmitted.\n\nLemma leq_tmod_troot n : tmod n <= troot n.\nAdmitted.\n\nLemma ltn_troot m n : troot m < troot n -> m < n.\nAdmitted.\n\nLemma leq_tmod m n : troot m = troot n -> (tmod m <= tmod n) = (m <= n).\nAdmitted.\n\nLemma leq_troot_mod m n : \n   m <= n = \n   ((troot m < troot n) || ((troot m == troot n) && (tmod m <= tmod n))).\nAdmitted.\n\n(** Fermat Numbers *)\n\nDefinition fermat n := (2 ^ (2 ^ n)).+1.\n\nCompute elements (prime \\o fermat) 4.\n\n(** Hints : subn_sqr subnBA odd_double_half *)\nLemma dvd_exp_odd a k :  0 < a -> odd k -> a.+1 %| (a ^ k).+1.\nAdmitted.\n\n(** Hints: logn_gt0 mem_primes dvdn2 *)\nLemma odd_log_eq0 n : 0 < n -> logn 2 n = 0 -> odd n.\nAdmitted.\n\n(** Hints pfactor_dvdnn logn_div pfactorK *)\nLemma odd_div_log n : 0 < n -> odd (n %/ 2 ^ logn 2 n).\nAdmitted.\n\n(** Hints divnK pfactor_dvdnn prime_nt_dvdP prime_nt_dvdP *)\nLemma prime_2expS m : 0 < m -> prime (2 ^ m).+1 -> m = 2 ^ logn 2 m.\nAdmitted.\n\n(** Hints odd_exp neq_ltn expn_gt0 *)\nLemma odd_fermat n : odd (fermat n).\nAdmitted.\n\n(** Hint subn_sqr *)\nLemma dvdn_exp2m1 a k : a.+1 %| (a ^ (2 ^ k.+1)).-1.\nAdmitted.\n\nLemma fermat_gt1 n : 1 < fermat n.\nAdmitted.\n\n(** Hints subnK expnD expnM *)\nLemma dvdn_fermat m n : m < n -> fermat m %| (fermat n).-2.\nAdmitted.\n\n(** Hints gcdnMDl coprimen2 *)\nLemma coprime_fermat m n : m < n -> coprime (fermat m) (fermat n).\nAdmitted.\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/exercise4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7819050694471689}}
{"text": "Module prop.\n\n  Inductive isB : nat -> Prop :=\n  | b_0 : isB 0\n  | b_3 : isB 3\n  | b_5 : isB 5\n  | b_sum : forall n m:nat, isB n -> isB m -> isB (n+m).\n\n\n  Lemma three_isB : isB 3.\n  Proof.\n    apply b_3.\n  Qed.\n\n  Lemma five_isB : isB 5.\n  Proof.\n    apply b_5.\n  Qed.\n\n\n  Theorem eight_isB : isB 8.\n  Proof.\n    apply b_sum with (n:=3) (m:=5).\n    apply b_3. apply b_5.\n  Qed.\n\n  Theorem beautiful_plus_eight: forall n, isB n -> isB (8+n).\n  Proof.\n    intros n H.\n    apply b_sum.\n    apply eight_isB.\n    apply H.\n  Qed.\n\n  Theorem b_timesm: forall n m: nat, isB n -> isB (m*n).\n  Proof.\n    intros n m H.\n    induction m.\n    simpl. apply b_0.\n    simpl.\n    apply b_sum.\n    apply H.\n    apply IHm.\n  Qed.\n\n  Inductive gor : nat -> Prop :=\n  | g_0 : gor 0\n  | g_3: forall n, gor n -> gor (3+n)\n  | g_5: forall n, gor n -> gor (5+n).\n\n  Lemma gb : forall n, gor n -> isB n.\n  Proof.  \n    intros n H.\n    induction H.\n    apply b_0. apply b_sum. apply b_3. apply IHgor.\n    apply b_sum. apply b_5. apply IHgor.\n  Qed.\n  \n  Lemma gs : forall n m:nat, gor n -> gor m -> gor (n+m).\n  Proof.\n    intros n m H H0.\n    induction H.\n    apply H0.\n    apply g_3. apply IHgor.\n    apply g_5. apply IHgor.\n  Qed.    \n  \n  Theorem bg: forall n:nat, isB n -> gor n.\n  Proof.\n    intros n H.\n    induction H.\n    apply g_0. apply g_3. apply g_0. apply g_5. apply g_0.\n    apply gs. apply IHisB1. apply IHisB2.\n  Qed.        \n  \n  Theorem andb : forall n m, isB n -> isB m -> isB n /\\ isB m.\n  Proof.\n    intros n m H H0.\n    apply conj. apply H. apply H0. (* We can just use auto here! *)\n  Qed.\n\n  (* This theorem cannot be proven in Coq. I think! *)\n  Theorem impor: forall P Q: Prop, P -> Q -> ~ P \\/ Q.\n    intros P Q H.\n    apply or_intror with (A:=Q) in H.\n    apply or_comm in H.\n    admit.\n  Qed.\n  \n  \nEnd prop.\n", "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/prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7818602839412034}}
{"text": "(* Listes *)\n\nInductive liste : Type :=\n| nil : liste\n| C : nat -> liste -> liste.\n\n\n(* Question 13 *)\n(* Définition de la fonction longueur *)\nFixpoint longueur (l: liste ) : nat :=\n  match l with\n  | nil => 0\n  | C a l => 1 + longueur l \n  end.\n\n(* Question 14 *)\n(* Définition de la fonction concat *)\n\nFixpoint concat (l r: liste ) : liste  :=\n  match l with\n  | nil => r\n  | C a l => C a (concat l r) \n  end.\n\nCompute  (concat  (C 2 nil) (C 3 nil)).\n\n(* Question 15 *)\n\nTheorem long (l m : liste) : longueur(concat l m) = longueur l + longueur m.\nProof.\ninduction l.\nreflexivity.\nsimpl.\nrewrite IHl.\nreflexivity.\nQed.\n\n(* Question 16 *)\n(* Définition de la fonction ajoutqueue *)\nFixpoint ajoutqueue (a:nat) (l:liste ) : liste  :=\n  match l with\n  | nil => C a nil\n  | C a l => C a (ajoutqueue a l) \n  end.\n\n(* Question 17 *)\nTheorem lgajout (x : nat) (l : liste) : longueur(ajoutqueue x l) = 1 + longueur l.\nProof.\nAdmitted.\n\n\n\n\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/listes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7818425441187054}}
{"text": "From mathcomp\n  Require Import ssreflect ssrnat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Logic.\n\nLemma contrap : forall A B : Prop, (A -> B) -> (~B -> ~A).\nProof.\nrewrite /not.\nmove => A0 B0 AtoB notB.\nby move /AtoB.\nQed.\n\nVariables A B C : Prop.\n\nLemma AndOrDistL : (A /\\ C) \\/ (B /\\ C) <-> (A \\/ B) /\\ C.\nProof.\nrewrite /iff.\napply: conj.\n-case.\n +case=> AisTrue CisTrue.\n  by apply: conj; [apply: or_introl | ].\n +case=> BisTrue CisTrue.\n  by apply: conj; [apply: or_intror | ].\n-case=> AorBisTrue CisTrue.\n case: AorBisTrue => [AisTrue | BisTrue].\n +by apply: or_introl.\n +by apply: or_intror.\nQed.\n\nLemma JDM (T : Type) (P : T -> Prop) :\n  ~(exists (x : T), P x) <-> forall x, ~(P x).\nProof.\napply: conj => Hyp.\n-move=> x0 HPx0.\n apply: Hyp.\n by apply: (ex_intro P x0).\n-by case.\nQed.\n\nHypothesis ExMidLaw : forall P : Prop, P \\/ ~P.\n\nLemma notnotEq (P : Prop) : ~ ~ P -> P.\nProof.\nmove=> HnotnotP.\n-case: (ExMidLaw (~ P)).\n +by move /HnotnotP.\n +by case: (ExMidLaw P).\nQed.\n\nEnd Logic.\n", "meta": {"author": "ishioka0222", "repo": "theorem-proving-in-coq", "sha": "a67e7e5cfa837cefa776c0ec76f26152e80a6c39", "save_path": "github-repos/coq/ishioka0222-theorem-proving-in-coq", "path": "github-repos/coq/ishioka0222-theorem-proving-in-coq/theorem-proving-in-coq-a67e7e5cfa837cefa776c0ec76f26152e80a6c39/src/萩原学, アフェルト・レナルド (2018) Coq_SSReflect_MathCompによる定理証明/chap2-5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7817707764329092}}
{"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(** ** Euclidian division and Bezout's identity *)\n\nRequire Import List Arith Omega Permutation.\n\nRequire Import utils_tac utils_list.\n\nSet Implicit Arguments.\n\nSection Euclid.\n\n  Definition euclid n d : d <> 0 -> { q : nat & { r | n = q*d+r /\\ r < d } }.\n  Proof.\n    intros Hd.\n    induction on n as IHn with measure n.\n    destruct (le_lt_dec d n) as [ H | H ].\n    + destruct (IHn (n-d)) as (q & r & H1 & H2).\n      * omega.\n      * exists (S q), r; split; auto; simpl; omega.\n    + exists 0, n; split; auto; simpl; omega.\n  Qed.\n\nEnd Euclid.\n\nDefinition arem n d q j := j <= d /\\ (n = 2*q*d+j \\/ q <> 0 /\\ n = 2*q*d-j).\n\nFact division_by_even n d : d <> 0 -> { q : nat & { j | arem n d q j } }.\nProof.\n  intros Hd.\n  destruct (@euclid n (2*d)) as (q & r & H1 & H2); try omega.\n  destruct (le_lt_dec r d) as [ Hr | Hr ].\n  + exists q, r; split; auto; left.\n    rewrite H1; ring.\n  + exists (S q), (2*d-r); split; try omega; right.\n    split; try omega.\n    rewrite H1.\n    replace (2*(S q)*d) with (q*(2*d) + 2 * d) by ring.\n    omega.\nQed.\n\nFact own_multiple x p : x = p*x -> x = 0 \\/ p = 1.\nProof.\n  destruct x as [ | x ].\n  + left; trivial.\n  + right.\n    destruct p as [ | [ | p ] ].\n    - simpl in H; discriminate.\n    - trivial.\n    - exfalso; revert H.\n      do 2 (rewrite mult_comm; simpl).\n      generalize (p*x); intros; omega.\nQed.\n\nFact mult_is_one p q : p*q = 1 -> p = 1 /\\ q = 1.\nProof.\n  destruct p as [ | [ | p ] ].\n  + simpl; discriminate.\n  + simpl; omega.\n  + rewrite mult_comm.\n    destruct q as [ | [ | q ] ].\n    - simpl; discriminate.\n    - simpl; omega.\n    - simpl; discriminate.\nQed.\n\nDefinition divides n k := exists p, k = p*n.\n\nSection divides.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Fact divides_refl x : x div x.\n  Proof. exists 1; simpl; omega. Qed.\n\n  Fact divides_anti x y : x div y -> y div x -> x = y.\n  Proof.\n    intros (p & H1) (q & H2).\n    rewrite H1, mult_assoc in H2.\n    apply own_multiple in H2.\n    destruct H2 as [ H2 | H2 ].\n    + subst; rewrite mult_comm; auto.\n    + apply mult_is_one in H2; destruct H2; subst; omega.\n  Qed.\n\n  Fact divides_trans x y z : x div y -> y div z -> x div z.\n  Proof.\n    intros (p & H1) (q & H2).\n    exists (q*p); rewrite <- mult_assoc, <- H1; auto.\n  Qed.\n\n  Fact divides_0 p : p div 0.\n  Proof. exists 0; auto. Qed.\n\n  Fact divides_0_inv p : 0 div p -> p = 0.\n  Proof. intros (?&?); subst; rewrite Nat.mul_0_r; auto. Qed.\n\n  Fact divides_1 p : 1 div p.\n  Proof. exists p; rewrite mult_comm; simpl; auto. Qed.\n\n  Fact divides_1_inv p : p div 1 -> p = 1.\n  Proof.\n    intros (q & Hq).\n    apply mult_is_one with q; auto.\n  Qed.\n\n  Fact divides_2_inv p : p div 2 -> p = 1 \\/ p = 2.\n  Proof.\n    intros ([ | k ] & Hk); try discriminate.\n    destruct p as [ | [ | [|] ] ]; try omega.\n    rewrite mult_comm in Hk; simpl in Hk.\n    contradict Hk; generalize (n*S k); intros; omega.\n  Qed.\n\n  Fact divides_mult p q k : p div q -> p div k*q.\n  Proof.\n    intros (r & ?); subst.\n    exists (k*r); rewrite mult_assoc; auto.\n  Qed.\n\n  Fact divides_mult_r p q k : p div q -> p div q*k.\n  Proof.\n    rewrite mult_comm; apply divides_mult; auto.\n  Qed.\n\n  Fact divides_mult_compat a b c d : a div b -> c div d -> a*c div b*d.\n  Proof. \n    intros (u & ?) (v & ?); exists (u*v); subst.\n    repeat rewrite mult_assoc; f_equal.\n    repeat rewrite <- mult_assoc; f_equal.\n    apply mult_comm.\n  Qed.\n\n  Fact divides_minus p q1 q2 : p div q1 -> p div q2 -> p div q1 - q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 - s2).\n    rewrite Nat.mul_sub_distr_r; omega.\n  Qed.\n\n  Fact divides_plus p q1 q2 : p div q1 -> p div q2 -> p div q1+q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 + s2).\n    rewrite Nat.mul_add_distr_r; omega.\n  Qed.\n\n  Fact divides_plus_inv p q1 q2 : p div q1 -> p div q1+q2 -> p div q2.\n  Proof.\n     intros H1 H2.\n     replace q2 with (q1+q2-q1) by omega.\n     apply divides_minus; auto.\n  Qed.\n\n  Fact divides_le p q : q <> 0 -> p div q -> p <= q.\n  Proof.\n    intros H (k & Hk); subst.\n    destruct k.\n    + destruct H; auto.\n    + simpl; generalize (k*p); intros; omega.\n  Qed. \n\n  Fact divides_mult_inv k p q : k <> 0 -> k*p div k*q -> p div q.\n  Proof.\n    intros H (n & Hn); exists n.\n    apply Nat.mul_cancel_r with (1 := H).\n    rewrite mult_comm, Hn; ring.\n  Qed.\n\n  Lemma divides_fact m p : 1 < p <= m -> p div fact m.\n  Proof.\n    intros (H1 & H2); induction H2.\n    + destruct p; cbn. omega. unfold divides. exists (fact p). ring.\n    + cbn. eauto using divides_plus, divides_mult.\n  Qed.\n\n  Lemma divides_mult_inv_l p q r : p * q div r -> p div r /\\ q div r.\n  Proof.\n    intros []; split; subst.\n    - exists (x * q); ring.\n    - exists (x * p); ring.\n  Qed.\n\nEnd divides.\n\nSection gcd_lcm.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve divides_0 divides_refl divides_mult divides_1.\n\n  Definition is_gcd p q r := r div p /\\ r div q /\\ forall k, k div p -> k div q -> k div r.\n  Definition is_lcm p q r := p div r /\\ q div r /\\ forall k, p div k -> q div k -> r div k.\n\n  Fact is_gcd_sym p q r : is_gcd p q r -> is_gcd q p r.\n  Proof. intros (? & ? & ?); repeat split; auto. Qed.\n\n  Fact is_gcd_0l p : is_gcd 0 p p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_0r p : is_gcd p 0 p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1l p : is_gcd 1 p 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1r p : is_gcd p 1 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_modulus p q k r : p div k -> k <= q -> is_gcd p q r -> is_gcd p (q-k) r.\n  Proof.\n    intros (n & Hn) Hq (H1 & H2 & H3); subst.\n    split; auto.\n    split.\n    + apply divides_minus; auto.\n    + intros k H4 H5.\n      apply H3; auto.\n      replace q with (q - n*p + n*p) by omega.\n      apply divides_plus; auto.\n  Qed.\n\n  Fact is_gcd_minus p q r : p <= q -> is_gcd p q r -> is_gcd p (q-p) r.\n  Proof. intros H1; apply is_gcd_modulus; auto. Qed.\n\n  Hint Resolve divides_plus.\n\n  Fact is_gcd_moduplus p q k r : p div k -> is_gcd p q r -> is_gcd p (q+k) r.\n  Proof.\n    intros (n & Hn) (H1 & H2 & H3); subst.\n    repeat (split; auto).\n    intros k H4 H5.\n    apply H3; auto.\n    rewrite plus_comm in H5.\n    apply divides_plus_inv with (2 := H5); auto. \n  Qed.\n\n  Fact is_gcd_plus p q r : is_gcd p q r -> is_gcd p (q+p) r.\n  Proof. apply is_gcd_moduplus; auto. Qed.\n\n  Fact is_gcd_mult p q r n : is_gcd p (n*p+q) r <-> is_gcd p q r.\n  Proof.\n    split.\n    + replace q with ((n*p+q)-n*p) at 2 by omega.\n      apply is_gcd_modulus; auto; omega.\n    + rewrite plus_comm; apply is_gcd_moduplus; auto.\n  Qed.\n\n  Fact is_gcd_div p q : p div q -> is_gcd p q p.\n  Proof. intros (?&?); subst; split; auto. Qed.\n\n  Fact is_gcd_refl p : is_gcd p p p.\n  Proof. split; auto. Qed.\n\n  Fact is_gcd_fun p q r1 r2 : is_gcd p q r1 -> is_gcd p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\n  Fact is_lcm_0l p : is_lcm 0 p 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_0r p : is_lcm p 0 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_sym p q r : is_lcm p q r -> is_lcm q p r.\n  Proof. intros (?&?&?); repeat split; auto. Qed.\n\n  Fact is_lcm_fun p q r1 r2 : is_lcm p q r1 -> is_lcm p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\nEnd gcd_lcm.\n\nSection bezout.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve is_gcd_0l is_gcd_0r is_lcm_0l is_lcm_0r divides_refl divides_mult divides_0 is_gcd_minus.\n\n  Section bezout_rel_prime.\n\n    Let bezout_rec p q : 0 < p < q -> is_gcd p q 1 -> exists a b, a*p+b*q = 1+p*q /\\ a <= q /\\ b <= p.\n    Proof.\n      revert p.\n      induction on q as IHq with measure q; intros p (Hp & Hq) H.\n      destruct (@euclid q p) as (n & r & H1 & H2); try omega.\n      destruct (eq_nat_dec r 0) as [ Hr | Hr ].\n      { subst r; rewrite plus_comm in H1; simpl in H1.\n        assert (is_gcd p q p) as H3.\n        { apply is_gcd_div; subst; auto. }\n        rewrite (is_gcd_fun H3 H) in *.\n        exists 1, 1; simpl; omega. }\n      destruct (IHq _ Hq r) as (a & b & H3 & H4 & H5); try omega.\n      { replace r with (q-n*p) by omega.\n        apply is_gcd_sym, is_gcd_modulus; auto; omega. }\n      exists (b+n*p-n*a), a.\n      split; [ | split ]; auto.\n      + rewrite H1, Nat.mul_sub_distr_r, (mult_comm _ p).\n        do 3 rewrite Nat.mul_add_distr_l.\n        rewrite (plus_comm _ (p*r)), (plus_assoc 1), (mult_comm p r), <- H3.\n        rewrite (mult_comm n a), (mult_comm p b), mult_assoc, mult_assoc.\n        assert (a*n*p <= p*n*p) as H6.\n        { repeat (apply mult_le_compat; auto). }\n        revert H6; generalize (b*p) (a*r) (a*n*p) (p*n*p); intros; omega.\n      + rewrite H1; generalize (n*p) (n*a); intros; omega.\n    Qed.\n\n    Lemma bezout_nc p q : is_gcd p q 1 -> exists a b, a*p+b*q = 1+p*q.\n    Proof.\n      intros H.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0l _) H); exists 0, 1; auto. }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0r _) H); exists 1, 0; auto. }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct bezout_rec with (2 := H)\n          as (a & b & H2 & _); try omega.\n        exists a, b; auto.\n      + subst; rewrite (is_gcd_fun (is_gcd_refl _) H); exists 1, 1; auto.\n      + destruct bezout_rec with (2 := is_gcd_sym H)\n          as (a & b & H2 & _); try omega.\n        exists b, a; rewrite (mult_comm p q); omega.\n    Qed.\n\n    Hint Resolve divides_1.\n\n    Lemma bezout_sc p q a b m : a*p+b*q = 1 + m -> p div m \\/ q div m -> is_gcd p q 1.\n    Proof.\n      intros H1 H2; do 2 (split; auto).\n      intros k H4 H5.\n      apply divides_plus_inv with m.\n      +  destruct H2 as [ H2 | H2 ];\n         apply divides_trans with (2 := H2); auto.\n      + rewrite plus_comm, <- H1.\n        apply divides_plus; auto.\n    Qed.\n\n  End bezout_rel_prime.\n\n  (* We need the simple form of Bezout above to show this *)\n\n  Fact is_rel_prime_div p q k : is_gcd p q 1 -> p div q*k -> p div k.\n  Proof.\n    intros H1 (u & H2); subst.\n    destruct bezout_nc with (1 := H1) as (a & b & H3).\n    replace k with (k*(1+p*q) - k*p*q).\n    + apply divides_minus.\n      - rewrite <- H3, Nat.mul_add_distr_l.\n        apply divides_plus.\n        * rewrite mult_assoc; auto.\n        * rewrite (mult_comm b), mult_assoc, (mult_comm k), H2.\n          rewrite mult_comm, mult_assoc; auto.\n      - rewrite mult_comm, mult_assoc; auto.\n    + rewrite Nat.mul_add_distr_l, mult_assoc.\n      generalize (k*p*q); intros; omega.\n  Qed.\n\n  Fact is_rel_prime_div_r p q k : is_gcd p q 1 -> p div k*q -> p div k.\n  Proof. rewrite mult_comm; apply is_rel_prime_div. Qed.\n\n  Fact is_rel_prime_lcm p q : is_gcd p q 1 -> is_lcm p q (p*q).\n  Proof.\n    intros H.\n    repeat (split; auto).\n    rewrite mult_comm; auto.\n    intros k (u & ?) (v & ?); subst.\n    rewrite (mult_comm u).\n    apply divides_mult_compat; auto.\n    apply is_gcd_sym in H.\n    apply is_rel_prime_div with (1 := H) (k := u).\n    rewrite mult_comm, H1; auto.\n  Qed.\n\n  Hint Resolve divides_1 divides_mult_compat is_gcd_refl.\n\n  Fact is_gcd_0 p q : is_gcd p q 0 -> p = 0 /\\ q = 0.\n  Proof.\n    intros ((a & Ha) & (b & Hb) & H).\n    subst; do 2 rewrite mult_0_r; auto.\n  Qed.\n\n  Fact is_gcd_rel_prime p q g : is_gcd p q g -> exists a b, p = a*g /\\ q = b*g /\\ is_gcd a b 1.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    * intros H; subst.\n      apply is_gcd_0 in H; destruct H; subst.\n      exists 1, 1 ; simpl; auto.\n    * intros ((a & Ha) & (b & Hb) & H).\n      exists a, b; repeat (split; auto).\n      intros k H1 H2.\n      destruct (H (k*g)) as (d & Hd); subst.\n      + do 2 rewrite (mult_comm _ g); auto.\n      + do 2 rewrite (mult_comm _ g); auto.\n      + rewrite mult_assoc in Hd.\n        replace g with (1*g) in Hd at 1 by (simpl; omega).\n        apply Nat.mul_cancel_r in Hd; auto.\n        symmetry in Hd.\n        apply mult_is_one in Hd.\n        destruct Hd; subst; auto.\n  Qed.\n\n  Fact is_lcm_mult p q l k : is_lcm p q l -> is_lcm (k*p) (k*q) (k*l).\n  Proof.\n    intros (H1 & H2 & H3); repeat (split; auto).\n    intros r (a & Ha) (b & Hb).\n    destruct (eq_nat_dec k 0) as [ Hk | Hk ].\n    + subst; simpl; auto.\n    + assert (a*p = b*q) as H4.\n      { rewrite <- Nat.mul_cancel_r with (1 := Hk).\n        do 2 rewrite <- mult_assoc, (mult_comm _ k).\n        rewrite <- Hb; auto. }\n      rewrite Ha, mult_assoc, (mult_comm _ k), <- mult_assoc.\n      apply divides_mult_compat; auto.\n      apply H3; auto.\n      rewrite H4; auto.\n  Qed.\n\n  Theorem is_gcd_lcm_mult p q g l : is_gcd p q g -> is_lcm p q l -> p*q = g*l.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ]; intros H1.\n    * subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl; auto.\n    * destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H2).\n      intros H3. \n      rewrite Hu, Hv, (mult_comm u), <- mult_assoc; f_equal.\n      rewrite (mult_comm u), (mult_comm v), <- mult_assoc, (mult_comm v).\n      apply is_lcm_fun with (2 := H3).\n      subst; rewrite (mult_comm u), (mult_comm v).\n      apply is_lcm_mult, is_rel_prime_lcm; auto.\n  Qed.\n\n  Theorem is_gcd_mult_lcm p q g l : g <> 0 -> is_gcd p q g -> g*l = p*q -> is_lcm p q l.\n  Proof.\n    intros H0 H1 H2.\n    destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H3).\n    rewrite Hu, Hv, (mult_comm u), (mult_comm v).\n    replace l with (g*(u*v)).\n    + apply is_lcm_mult, is_rel_prime_lcm; auto.\n    + rewrite <- Nat.mul_cancel_r with (1 := H0).\n      rewrite (mult_comm l), H2, Hu, Hv,\n              (mult_comm u g), mult_assoc, mult_assoc; auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-p) = g \n           B) lcm p (q-p) = l-u*p *)\n\n  Lemma is_lcm_minus p q g l u : p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-p) (l-u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite mult_0_r, Nat.sub_0_r; auto.\n    + intros H1 H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_minus; auto.\n      * do 2 rewrite Nat.mul_sub_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite mult_assoc, (mult_comm g); auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-k*p) = g \n           B) lcm p (q-p) = l-k*u*p *)\n\n  Lemma is_lcm_modulus k p q g l u : k*p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-k*p) (l-k*u*p).\n  Proof.\n    rewrite <- mult_assoc.\n    intros H1 H2 H3 H4. revert H1.\n    induction k as [ | k IHk ]; intros H1.\n    + simpl; do 2 rewrite Nat.sub_0_r; auto.\n    + replace (q - S k*p) with (q -k*p -p) by (simpl; omega).\n      replace (l - S k*(u*p)) with (l - k*(u*p) - u*p).\n      - apply is_lcm_minus with (g := g); auto.\n        * simpl in H1; omega.\n        * apply is_gcd_modulus; auto.\n          simpl in H1; omega.\n        * apply IHk; simpl in H1; omega.\n      - simpl; generalize (u*p) (k*(u*p)); intros; omega.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q+p) = g \n           B) lcm p (q+p) = l+u*p *)\n\n  Lemma is_lcm_plus p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+p) (l+u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite mult_0_r, Nat.add_0_r; auto.\n    + intros H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_plus; auto.\n      * do 2 rewrite Nat.mul_add_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite mult_assoc, (mult_comm g); auto.\n  Qed.\n\n  Lemma is_lcm_moduplus k p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+k*p) (l+k*u*p).\n  Proof.\n    rewrite <- mult_assoc.\n    intros H2 H3 H4.\n    induction k as [ | k IHk ].\n    + simpl; do 2 rewrite Nat.add_0_r; auto.\n    + replace (q + S k*p) with (q +k*p +p) by (simpl; omega).\n      replace (l + S k*(u*p)) with (l + k*(u*p) + u*p) by (simpl; omega).\n      apply is_lcm_plus with (g := g); auto.\n      apply is_gcd_moduplus; auto.\n  Qed.\n\n  Section bezout_generalized.\n\n    Let bezout_rec p q : 0 < p < q \n                      -> { a : nat \n                       & { b : nat \n                       & { g : nat\n                       & { l : nat \n                       & { u : nat\n                       & { v : nat\n                         | a*p+b*q = g + l\n                        /\\ is_gcd p q g\n                        /\\ is_lcm p q l\n                        /\\ p = u*g\n                        /\\ q = v*g\n                        /\\ a <= v\n                        /\\ b <= u } } } } } }.\n    Proof.\n      revert p; induction q as [ q IHq ] using (@measure_rect _ (fun n => n)); intros p (Hp & Hq).\n      destruct (@euclid q p) as (k & r & H1 & H2); try omega.\n      destruct (eq_nat_dec r 0) as [ Hr | Hr ].\n      + exists 1, 1, p, (k*p), 1, k.\n        rewrite plus_comm in H1; simpl in H1.\n        subst; repeat split; simpl; auto.\n        destruct k; omega.\n      + destruct (IHq _ Hq r) as (a & b & g & l & u & v & H3 & H4 & H5 & H6 & H7 & H8 & H9); try omega.\n        exists (b+k*v-k*a), a, g, (l+k*v*p), v, (k*v+u).\n        apply is_gcd_sym in H4.\n        apply is_lcm_sym in H5.\n        rewrite plus_comm in H1.\n        assert (g <> 0) as Hg.\n        { intro; subst g; apply is_gcd_0, proj1 in H4; omega. }\n        split.\n        { rewrite H1, plus_assoc, Nat.mul_add_distr_l, <- H3.\n          rewrite Nat.mul_sub_distr_r, Nat.mul_add_distr_r.\n          rewrite mult_assoc, (mult_comm a k).\n          assert (k*a*p <= k*v*p) as G.\n          { repeat (apply mult_le_compat; auto). }\n          revert G; generalize (b*p) (a*r) (k*a*p) (k*v*p); intros; omega. }\n        split.\n        { rewrite H1; apply is_gcd_moduplus; auto. }\n        split.\n        { rewrite H1; apply is_lcm_moduplus with g; auto. }\n        split; auto.\n        split.\n        { rewrite H1, H6, H7, Nat.mul_add_distr_r, mult_assoc; omega. }\n        split; auto.\n        { rewrite (plus_comm _ u), <- Nat.add_sub_assoc.\n          +  apply plus_le_compat; auto. \n             generalize (k*v) (k*a); intros; omega.\n          + apply mult_le_compat; auto. }\n    Qed.\n  \n    Hint Resolve is_gcd_sym is_lcm_sym.\n\n    Definition bezout_generalized p q : { a : nat \n                                      & { b : nat \n                                      & { g : nat\n                                      & { l : nat \n                                        | a*p+b*q = g + l\n                                       /\\ is_gcd p q g\n                                       /\\ is_lcm p q l } } } }.\n    Proof.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; exists 0, 1, q, 0; repeat (split; auto). }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; exists 1, 0, p, 0; repeat (split; auto). }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct (@bezout_rec p q)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try omega.\n        exists a, b, g, l; auto.\n      + subst q; exists 1, 1, p, p.\n        repeat split; auto; omega.\n      + destruct (@bezout_rec q p)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try omega.\n        exists b, a, g, l; repeat (split; auto); omega.\n    Qed.\n\n  End bezout_generalized.\n\n  Section gcd_lcm.\n\n    Let gcd_full p q : sig (is_gcd p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & g & _ & _ & ? & _).\n      exists g; auto.\n    Qed.\n\n    Definition gcd p q := proj1_sig (gcd_full p q).\n    Fact gcd_spec p q : is_gcd p q (gcd p q).\n    Proof. apply (proj2_sig _). Qed.\n\n    Let lcm_full p q : sig (is_lcm p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & _ & l & _ & _ & ?).\n      exists l; auto.\n    Qed.\n\n    Definition lcm p q := proj1_sig (lcm_full p q).\n    Fact lcm_spec p q : is_lcm p q (lcm p q).\n    Proof. apply (proj2_sig _). Qed.\n\n  End gcd_lcm.\n     \nEnd bezout.\n\nRequire Import Extraction.\nExtraction Inline measure_rect.\n\nCheck bezout_generalized.\nPrint Assumptions bezout_generalized.\n\nSection division.\n\n  Fact div_full q p : { n : nat & { r | q = n*p+r /\\ (p <> 0 -> r < p) } }.\n  Proof.\n    case_eq p.\n    + intro; exists 0, q; subst; split; auto; intros []; auto.\n    + intros k H; destruct (@euclid q p) as (n & r & H1 & H2); try omega.\n      exists n, r; rewrite <- H; split; auto.\n  Qed.\n\n  Definition div q p := projT1 (div_full q p).\n  Definition rem q p := proj1_sig (projT2 (div_full q p)).\n\n  Fact div_rem_spec1 q p : q = div q p * p + rem q p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact div_rem_spec2 q p : p <> 0 -> rem q p < p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact rem_0 q : rem q 0 = q.\n  Proof.\n    generalize (div_rem_spec1 q 0).\n    rewrite mult_comm; auto.\n  Qed.\n\n  Fact div_rem_uniq p n1 r1 n2 r2 : \n        p <> 0 -> n1*p + r1 = n2*p + r2 -> r1 < p -> r2 < p -> n1 = n2 /\\ r1 = r2.\n  Proof.\n    intros H1 H2 H3 H4.\n    assert (n1 = n2) as E.\n    destruct (lt_eq_lt_dec n1 n2) as [ [ H | ] | H ]; auto.\n    + replace n2 with (n2-n1 + n1) in H2 by omega.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n2-n1)*p) as H5.\n      { apply mult_le_compat; omega. }\n      simpl in H5; omega.\n    + replace n1 with (n1-n2 + n2) in H2 by omega.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n1-n2)*p) as H5.\n      { apply mult_le_compat; omega. }\n      simpl in H5; omega.\n    + subst; omega.\n  Qed.\n\n  Fact div_prop q p n r : q = n*p+r -> r < p -> div q p = n.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p _ (rem q p) n r); auto.\n    + omega.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; omega.\n  Qed.\n\n  Fact rem_prop q p n r : q = n*p+r -> r < p -> rem q p = r.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p (div q p) _ n r); auto.\n    + omega.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; omega.\n  Qed.\n\n  Fact rem_idem q p : q < p -> rem q p = q.\n  Proof. apply rem_prop with 0; auto. Qed.\n\n  Fact is_gcd_rem p n a : is_gcd p n a <-> is_gcd p (rem n p) a.\n  Proof.\n    rewrite (div_rem_spec1 n p) at 1; apply is_gcd_mult.\n  Qed.\n\n  Fact rem_erase q n p r : q = n*p+r -> rem q p = rem r p.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ | Hp ]; subst.\n    + rewrite mult_comm, rem_0, rem_0; auto.\n    + destruct (div_full r p) as (m & r' & H1 & H2).\n      specialize (H2 Hp).\n      rewrite rem_prop with r p m r'; auto.\n      intros; apply rem_prop with (n+m); auto.\n      rewrite Nat.mul_add_distr_r; omega.\n  Qed.\n\n  Fact divides_div q p : divides p q -> q = div q p * p.\n  Proof.\n    intros (k & Hk).\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + subst; do 2 (rewrite mult_comm; simpl); auto.\n    + rewrite (@div_prop q p k 0); omega.\n  Qed.\n\n  Fact divides_rem_eq q p : divides p q <-> rem q p = 0.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    * subst; rewrite rem_0; split.\n      + apply divides_0_inv.\n      + intros; subst; apply divides_0.\n    * split.\n      + intros (n & Hn).\n        apply rem_prop with n; omega.\n      + intros H.\n        generalize (div_rem_spec1 q p).\n        exists (div q p); omega.\n  Qed.\n\n  Fact rem_of_0 p : rem 0 p = 0.\n  Proof.\n    destruct p.\n    + apply rem_0.\n    + apply rem_prop with 0; omega.\n  Qed.\n\n  Hint Resolve divides_0_inv.\n\n  Fact divides_dec q p : { k | q = k*p } + { ~ divides p q }.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + destruct (eq_nat_dec q 0) as [ Hq | Hq ].\n      * left; subst; exists 1; auto.\n      * right; contradict Hq; subst; auto.\n    + destruct (@euclid q p Hp) as (n & [ | r ] & H1 & H2).\n      * left; exists n; subst; rewrite plus_comm; auto.\n      * right; intros (m & Hm).\n        rewrite <- Nat.add_0_r in Hm.\n        rewrite Hm in H1.\n        destruct (div_rem_uniq _ _ Hp H1); omega.\n  Qed.\n\nEnd division.\n\nSection rem.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Fact rem_plus_rem a b : rem (a+rem b p) p = rem (a+b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite plus_assoc.\n    symmetry; apply rem_erase with (div (b) p); ring.\n  Qed.\n\n  Fact rem_mult_rem a b : rem (a*rem b p) p = rem (a*b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite Nat.mul_add_distr_l, mult_assoc.\n    symmetry; apply rem_erase with (a*div b p); auto.\n  Qed.\n\n  Fact rem_diag : rem p p = 0.\n  Proof. apply rem_prop with 1; omega. Qed.\n\n  Fact rem_lt a : a < p -> rem a p = a.\n  Proof. apply rem_prop with 0; omega. Qed.\n\n  Fact rem_plus a b : rem (a+b) p = rem (rem a p + rem b p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite (div_rem_spec1 b p) at 1.\n    apply rem_erase with (div a p + div b p).\n    ring.\n  Qed.\n\n  Fact rem_scal k a : rem (k*a) p = rem (k*rem a p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite Nat.mul_add_distr_l.\n    apply rem_erase with (k*div a p).  \n    ring.\n  Qed.\n\n  Fact rem_plus_div a b : divides p b -> rem a p = rem (a+b) p.\n  Proof. \n    intros (n & Hn); subst.\n    rewrite <- rem_plus_rem.\n    f_equal.  \n    rewrite <- rem_mult_rem, rem_diag, Nat.mul_0_r, rem_of_0; omega.\n  Qed.\n\n  Fact div_eq_0 n : n < p -> div n p = 0.\n  Proof. intros; apply div_prop with n; omega. Qed.\n\n  Fact div_of_0 : div 0 p = 0.\n  Proof. apply div_eq_0; omega. Qed.\n\n  Fact div_ge_1 n : p <= n -> 1 <= div n p.\n  Proof.\n    intros H2.\n    rewrite (div_rem_spec1 n p) in H2.\n    generalize (div_rem_spec2 n Hp); intros H3.\n    destruct (div n p); omega.\n  Qed.\n\nEnd rem.\n\nFact div_by_p_lt p n : 2 <= p -> n <> 0 -> div n p < n.\nProof.\n  intros H1 H2.\n  rewrite (div_rem_spec1 n p) at 2.\n  replace p with (2+(p-2)) at 3 by omega.\n  rewrite Nat.mul_add_distr_l.\n  generalize (div n p*(p-2)); intros x.\n  destruct (le_lt_dec p n) as [ Hp | Hp ].\n  + apply div_ge_1 in Hp; omega.\n  + rewrite rem_lt; omega.\nQed.\n\nSection rem_2.\n\n  Fact rem_2_is_0_or_1 x : rem x 2 = 0 \\/ rem x 2 = 1.\n  Proof. generalize (rem x 2) (@div_rem_spec2 x 2); intros; omega. Qed.\n\n  Fact rem_2_mult x y : rem (x*y) 2 = 1 <-> rem x 2 = 1 /\\ rem y 2 = 1.\n  Proof. \n    generalize (rem_2_is_0_or_1 x) (rem_2_is_0_or_1 y).\n    do 2 rewrite <- rem_mult_rem, mult_comm.\n    intros [ H1 | H1 ] [ H2 | H2 ]; rewrite H1, H2; simpl; rewrite rem_lt; omega.\n  Qed.\n\n  Fact rem_2_fix_0 : rem 0 2 = 0.\n  Proof. apply rem_lt; omega. Qed.\n\n  Fact rem_2_fix_1 n : rem (2*n) 2 = 0.\n  Proof. apply divides_rem_eq; exists n; ring. Qed.\n\n  Fact rem_2_fix_2 n : rem (1+2*n) 2 = 1.\n  Proof.\n    rewrite <- rem_plus_rem,rem_2_fix_1, rem_lt; omega.\n  Qed.\n\n  Fact rem_2_lt n : rem n 2 < 2.\n  Proof. apply div_rem_spec2; omega. Qed.\n\n  Fact div_2_fix_0 : div 0 2 = 0.\n  Proof. apply div_of_0; omega. Qed.\n\n  Fact div_2_fix_1 n : div (2*n) 2 = n.\n  Proof. apply div_prop with 0; omega. Qed.\n\n  Fact div_2_fix_2 n : div (1+2*n) 2 = n.\n  Proof. apply div_prop with 1; omega. Qed.\n\n  Fact euclid_2_div n : n = rem n 2 + 2*div n 2 /\\ (rem n 2 = 0 \\/ rem n 2 = 1).\n  Proof.\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; omega.\n  Qed.\n\n  Fact euclid_2 n : exists q, n = 2*q \\/ n = 1+2*q.\n  Proof. \n    exists (div n 2).\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; omega.\n  Qed.\n\nEnd rem_2.\n\nLocal Hint Resolve divides_mult divides_mult_r divides_refl.\n\nTheorem CRT u v a b : u <> 0 -> v <> 0 -> is_gcd u v 1 -> exists w, rem w u = rem a u /\\ rem w v = rem b v /\\ 2 < w.\nProof.\n  intros Hu Hv H.\n  destruct bezout_nc with (1 := H) as (x & y & H1).\n  assert (rem (x*u) v = rem 1 v) as H2.\n  { rewrite rem_plus_div with (a := 1) (b := u*v); auto.\n    rewrite <- H1; apply rem_plus_div; auto. }\n  assert (rem (y*v) u = rem 1 u) as H3.\n  { rewrite rem_plus_div with (a := 1) (b := u*v); auto.\n    rewrite <- H1, plus_comm.\n    apply rem_plus_div; auto. }\n  exists (3*(u*v)+a*(y*v)+b*(x*u)).\n  split; [ | split ].\n  + rewrite <- rem_plus_rem, (mult_assoc b).\n    rewrite rem_scal with (k := b*x), rem_diag; auto.\n    rewrite Nat.mul_0_r, rem_of_0, Nat.add_0_r.\n    rewrite <- rem_plus_rem, rem_scal, H3, <- rem_scal, Nat.mul_1_r.\n    rewrite rem_plus_rem, plus_comm.\n    symmetry; apply rem_plus_div; auto.\n  + rewrite <- plus_assoc, (plus_comm (a*_)), plus_assoc.\n    rewrite <- rem_plus_rem, (mult_assoc a).\n    rewrite rem_scal with (k := a*y), rem_diag; auto.\n    rewrite Nat.mul_0_r, rem_of_0, Nat.add_0_r.\n    rewrite <- rem_plus_rem, rem_scal, H2, <- rem_scal, Nat.mul_1_r.\n    rewrite rem_plus_rem, plus_comm.\n    symmetry; apply rem_plus_div; auto.\n  + apply lt_le_trans with (3*1); try omega.\n    do 2 apply le_trans with (2 := le_plus_l _ _).\n    apply mult_le_compat_l.\n    assert (u*v <> 0) as H4.\n    { intros G; apply mult_is_O in G; omega. }\n    revert H4; generalize (u*v); intros; omega.\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/coq-library-undecidability/Shared/Libs/DLW/Utils/gcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7817599881114788}}
{"text": "Section Lab3Task1.\nVariable D : Set.\nTheorem Lab3Task1a : forall A B : D -> Prop,\n(forall x, A x -> B x) -> ((forall x, A x) -> (forall x, B x)).\nProof.\n(* to be completed *)\nintros.\napply H.\napply H0.\nQed.\n\n\nTheorem Lab3Task1b : forall A B : D -> Prop,\n(forall x, A x -> B x) -> ((exists x, A x) -> (exists x, B x)).\nProof.\n(* to be completed *)\nintros.\ndestruct H0.\napply H in H0.\nexists x.\nassumption.\nQed.\n\n\nVariable d:D. (* D is not empty *)\nTheorem Lab3Task1c : forall A B : D -> Prop,\n(forall x, A x -> B x) -> ((forall x, A x) -> (exists x, B x)).\nProof.\nintros.\nexists d.\napply H.\napply H0.\nQed.\n\nSection Lab3Task2.\nRequire Import Arith.\n\nFixpoint sumOdd (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n => (sumOdd n) + (2*n + 1)\nend.\nTheorem sumOdds : forall n : nat, sumOdd n = n*n.\n\nProof.\ninduction n.\nreflexivity. \nchange (sumOdd(S n)) with (sumOdd(n) + (2*n +1)).\nring_simplify.\nrewrite IHn.\nreflexivity.\nQed.\n\n\nRequire Import Arith.\nSection Task3.\nFixpoint sum2 (n : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n => (sum2 n) + (n+1)*(n+2)\nend.\nTheorem sum2formula : forall n : nat, 3 * (sum2 n) = n*(n+1)*(n+2).\n\nProof.\n\ninduction n.\nring_simplify.\nreflexivity.\nchange (sum2 (S n)) with ((sum2 n) + ( n+1)*(n+2)).\nring_simplify.\nrewrite IHn.\nring_simplify.\nreflexivity.\nQed.\n\nSection Task4.\nFixpoint sum3 (n : nat) : nat :=\nmatch n with\n| 0 => n\n| S n => (sum3 n) + ((n+1)*(n+1))\nend.\nTheorem squareSumFormula : forall n : nat, 6 * (sum3 n) = n*(n+1)*(2*n+1).\n\ninduction n.\nring_simplify.\nreflexivity.\n\nchange (sum3(S n)) with ((sum3 n) + ((n+1)*(n+1))).\nring_simplify.\nrewrite IHn.\nring_simplify.\nreflexivity.\nQed.\n\n\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/lab3/lab3_task1_task4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7817599845213493}}
{"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(** * ordinal: finite ordinals, sets of finite ordinals *)\n\nRequire Import List.\nRequire Import common comparisons.\n\n\nSet Implicit Arguments.\n\n(** * Boolean strict order on natural numbers *)\n\nFixpoint ltb i j := \n  match i,j with\n    | O,S _ => true\n    | _,O   => false\n    | S i, S j => ltb i j\n  end.\nNotation \"i < j\" := (ltb i j = true).\nNotation \"i <= j\" := (ltb j i = false).\n\nLemma ltb_plus_l i m n: i<m -> i<m+n.\nProof. revert i; induction m; destruct i; simpl; auto; discriminate. Qed.\n\nLemma ltb_plus_r i m n: i<n -> m+i<m+n.\nProof. revert i; induction m; destruct i; simpl; auto; discriminate. Qed.\n\nLemma leb_plus_r i n: n <= n+i.\nProof. induction n; simpl. now destruct i. assumption. Qed.\n\nLemma ltb_minus n m i: i<n+m -> n <= i -> i-n < m.\nProof. revert n. induction i; destruct n; simpl; auto. discriminate. Qed.\n\nLemma lt_n_1 a: a<1 -> a=0.\nProof. destruct a as [|[|?]]; trivial; discriminate. Qed.\n\nDefinition lt_ge_dec i n: {i<n}+{n<=i}.\nProof. case_eq (ltb i n). now left. now right. Defined.\n\n(** * Additional induction schemes for natural numbers *)\n\nLemma ltb_ind (P: nat -> nat -> Prop)\n  (H0: forall n, P (S n) 0)\n  (HS: forall n i, P n i -> P (S n) (S i)): \n  forall n i, i<n -> P n i.\nProof. \n  induction n; intros i Hi. destruct i; discriminate. \n  destruct i. apply H0. now apply HS, IHn.\nQed.\n\nLemma nat_ind_2: forall P: nat -> Prop, \n  P 0 -> P 1 -> (forall n, P n -> P ((S (S n)))) -> forall n, P n.\nProof.\n  intros P H0 H1 HSS.\n  assert (G: forall m, P m /\\ P (S m)).\n   induction m. split; assumption. \n   destruct IHm as [IHm IHSm].\n   split. assumption. apply (HSS m), IHm.\n  intro n. destruct (G n). assumption. \nQed.\n\n\n(** * Ordinals *)\n(** we use a record rather than a dependent inductive in order to\n   - get slightly more efficient computations\n   - get simpler proofs\n   using a Boolean strict order also simplifies proofs w.r.t. using the lt\n   predicate from the standard library *)\nRecord ord n := Ord {nat_of_ord:> nat; ord_lt: nat_of_ord<n}.\nArguments Ord [_] i _: rename.\n\n(** zero and successor *)\nDefinition ord0 {n}: ord (S n) := @Ord (S n) 0 eq_refl.\nDefinition ordS {n} (i: ord n): ord (S n) := @Ord (S n) (S i) (ord_lt i).\n\n(** ** ordinals as a [cmpType] *)\n(** we just compare the underlying natural numbers *)\nDefinition eqb_ord {n} (i j: ord n) := eqb_nat i j.\n\nLemma eq_ord n (i j: ord n): @eq nat i j -> i=j. \nProof. destruct i; destruct j; simpl; intro. subst. f_equal. apply UIP_cmp. Qed.\n\nLemma eqb_ord_spec n (i j: ord n): reflect (i=j) (eqb_ord i j).\nProof.\n  unfold eqb_ord. case eqb_spec; intro E; constructor.\n  apply eq_ord, E. congruence.\nQed.\n\nDefinition ord_compare {n} (i j: ord n) := nat_compare i j. \nLemma ord_compare_spec n (i j: ord n): compare_spec (i=j) (ord_compare i j).\nProof. \n  unfold ord_compare.\n  case cmp_spec; constructor; try apply eq_ord; congruence. \nQed.\n\nCanonical Structure cmp_ord n := mk_cmp _ (@eqb_ord_spec n) _ (@ord_compare_spec n).\n\n(** ** basic properties  *)\n\n(** [ord 0] is empty *)\nLemma ord_0_empty: ord 0 -> False.\nProof. intros [[|?]]; discriminate. Qed.\n\n(** [ord 1] has only one element: 0 *)\nLemma ord0_unique: forall i: ord 1, i=ord0.\nProof. \n  intros [[|i] Hi]; apply eq_ord. reflexivity.\n  destruct i; discriminate. \nQed. \n\n(** induction scheme for ordinals *)\nLemma ord_ind' (P: forall n, ord n -> Prop) \n  (H0: forall n, P (S n) ord0)\n  (HS: forall n i, P n i -> P (S n) (ordS i)): \n  forall n i, P n i.\nProof. \n  induction n. intro i. elim (ord_0_empty i).\n  destruct i as [[|i] Hi].\n   replace (Ord 0 Hi) with (@ord0 n) by now apply eq_ord. apply H0. \n   replace (Ord (S i) Hi) with (ordS (@Ord n i Hi)) by now apply eq_ord. apply HS, IHn. \nQed.\n\n(** ** sequence of all ordinals below [n]  *)\nFixpoint seq n: list (ord n) := \n  match n with \n    | 0 => nil\n    | S n => cons ord0 (map ordS (seq n))\n  end.\n\n(** completeness of the above sequence *)\nLemma in_seq: forall {n} (i: ord n), In i (seq n).\nProof. \n  induction i using ord_ind'. now left.\n  right. rewrite in_map_iff. eauto. \nQed.\n\n\n(** ** shifting ans splitting ordinals *)\n\n(** shifting *)\nDefinition lshift {m n} (i: ord m): ord (m+n) := Ord i (ltb_plus_l _ _ _ (ord_lt i)).\nDefinition rshift {m n} (i: ord n): ord (m+n) := Ord (m+i) (ltb_plus_r _ _ _ (ord_lt i)).\n\n(** spliting the sequence of all ordinals *)\nLemma seq_cut n m: seq (n+m) = map lshift (seq n) ++ map rshift (seq m).\nProof. \n  induction n; simpl.\n   rewrite <-(map_id (seq m)) at 1. apply map_ext. \n   intros [i Hi]. apply eq_ord. reflexivity.\n   rewrite IHn, map_app. f_equal. apply eq_ord. reflexivity. \n   rewrite 3map_map. f_equal; apply map_ext; intros [i Hi]; apply eq_ord; reflexivity.\nQed.\n\n(** splitting an ordinal *)\nDefinition split {n m} (i: ord (n+m)): ord n + ord m :=\n  match lt_ge_dec i n with\n    | left Hi => inl _ (Ord _ Hi)\n    | right Hj => inr _ (Ord _ (ltb_minus _ _ _ (ord_lt i) Hj))\n  end.\n  \nInductive split_case n m (i: ord (n+m)): ord n + ord m -> Set :=\n  | split_l: forall j: ord n, i=lshift j -> split_case i (inl j)\n  | split_r: forall j: ord m, i=rshift j -> split_case i (inr j).\n\nLemma split_spec n m (i: ord (n+m)): split_case i (split i).\nProof. \n  unfold split. case lt_ge_dec; constructor; apply eq_ord; simpl. reflexivity. \n  destruct i as [j Hj]. simpl in *. revert n m e Hj.\n  induction j; destruct n; simpl; auto. discriminate.\n  intros. f_equal. eapply IHj; eassumption.\nQed.\n\n(** basic properties of split and shifting *)\nLemma split_lshift n m i: @split n m (lshift i) = inl i.\nProof. \n  case split_spec; intros j E. \n  f_equal. apply eq_ord. injection E. congruence. \n  exfalso. injection E. clear E. destruct i as [i Hi]. \n  simpl. intros ->. rewrite leb_plus_r in Hi. discriminate.\nQed.\n\nLemma split_rshift n m i: @split n m (rshift i) = inr i.\nProof. \n  case split_spec; intros j E. \n  exfalso. injection E. clear E. destruct j as [j Hj]. simpl. intros <-. \n   rewrite leb_plus_r in Hj. discriminate. \n  f_equal. apply eq_ord. symmetry. injection E. apply Plus.plus_reg_l.\nQed.\n\nLemma eqb_ord_lrshift n m i j: eqb_ord (@lshift n m i) (@rshift n m j) = false.\nProof. \n  destruct i as [i Hi]; destruct j as [j Hj]. unfold eqb_ord. simpl.\n  case eqb_spec; trivial. intro E. rewrite E in Hi. rewrite leb_plus_r in Hi. discriminate. \nQed.\n\nLemma eqb_ord_rlshift n m i j: eqb_ord (@rshift n m i) (@lshift n m j) = false.\nProof. rewrite eqb_sym. apply eqb_ord_lrshift. Qed.\n\nLemma eqb_ord_rrshift n m i j: eqb_ord (@rshift n m i) (@rshift n m j) = eqb_ord i j.\nProof. \n  destruct i as [i Hi]; destruct j as [j Hj]. unfold eqb_ord. simpl.\n  do 2 case eqb_spec; trivial. intros E E'. elim E. eapply Plus.plus_reg_l, E'. \n  congruence. \nQed.\n\nLemma split_ord0 m: @split 1 m ord0 = inl ord0. \nProof. reflexivity. Qed. \n\nLemma split_ordS m i: @split 1 m (ordS i) = inr i. \nProof.\n  case split_spec; intros j Hj.\n   rewrite (ord0_unique j) in Hj. discriminate. \n  destruct i; destruct j. injection Hj. intros <-. f_equal. now apply eq_ord. \nQed.\n\n\n\n(** * Finite sets of ordinals as ordinals *)\n\n(** we encode a finite subset of [ord n] as an element of [ord (2^n)], \n   using the coding of the characteristic function of the set as a \n   bitvector of length n \n\n   since we need to compute a little bit with these encoded sets, we\n   first define the bijection on natural numbers, before encapsulating\n   into ordinals. *)\nModule set.\n\n(** ** on natural numbers *)\n\n(** [xO' i = 2*i], [xI' i = 2*i+1] *)\nFixpoint xO' i := match i with 0 => 0 | S i => S (S (xO' i)) end.\nFixpoint xI' i := match i with 0 => 1 | S i => S (S (xI' i)) end.\n\n(** from characteristic functions to natural numbers: accumulate bits\n   until a given length [(n)] is reached *)\nFixpoint of_fun' n (f: nat -> bool): nat :=\n  match n with\n    | 0 => 0\n    | S n => if f 0\n      then xI' (of_fun' n (fun i => f (S i)))\n      else xO' (of_fun' n (fun i => f (S i)))\n  end.\n\n(** [od x] returns the pair [(o,y)] s.t. [x = 2*y+o]  *)\nFixpoint od x := \n  match x with \n    | O => (false,O) \n    | S O => (true,O)\n    | S (S x) => let (o,x) := od x in (o,S x)\n  end.\n\n(** testing membership: read the [i]th bit, using [od] *)\n(** this function is presented in such a strange way to get efficiency: \n    the partial application [mem' n x] reduces to the pattern matching function \n    that precisely corresponds to the membership function of [x]. For instance, \n    [mem' 4 {1,2}] reduces to \n    [fun i => match i with 0 | 3 => false | 1 | 2 => true | _ => assert_false end] *)\nFixpoint mem' n x := \n  match n with \n    | 0 => fun i => assert_false false\n    | S n => \n      let (o,x) := od x in \n      let f := mem' n x in \n      fun i => match i with O => o | S i => f i end\n  end.\n\n(** correctness of [mem'] and [of_fun'] *)\nLemma od_xO i: od (xO' i) = (false,i).\nProof. induction i; simpl. reflexivity. now rewrite IHi. Qed.\n\nLemma od_xI i: od (xI' i) = (true,i).\nProof. induction i; simpl. reflexivity. now rewrite IHi. Qed.\n\nLemma mem_of_fun' n: forall f i, i<n -> mem' n (of_fun' n f) i = f i.\nProof.\n  induction n; intros f i Hi; simpl. destruct i; discriminate.\n  case_eq (f 0); intro H. \n   rewrite od_xI. destruct i. congruence. now rewrite IHn.\n   rewrite od_xO. destruct i. congruence. now rewrite IHn.\nQed.\n\n(** ** encapsulation into ordinals *)\n\n(** bounds about the various operations *)\nLemma xO_bound: forall n i, i<n -> xO' i < double n.\nProof. now apply ltb_ind. Qed.\n\nLemma xI_bound: forall n i, i<n -> xI' i < double n.\nProof. now apply ltb_ind. Qed.\n\nLemma of_fun_bound: forall n f, of_fun' n f < pow2 n.\nProof.\n  induction n; intro f. reflexivity. \n  simpl. case f.\n   now apply xI_bound. \n   now apply xO_bound. \nQed.\n\nLemma od_bound a: forall n, a < double n -> snd (od a) < n.\nProof.\n  induction a using nat_ind_2; intros n Hn; simpl.\n   destruct n; simpl. discriminate. reflexivity.\n   destruct n; simpl. discriminate. reflexivity. \n  revert IHa. case od; simpl. intros o a' IH. \n  destruct n. discriminate. apply IH, Hn. \nQed.\n\n(** extending a Boolean function on ordinals into a function on natural numbers *)\nDefinition app' n (f: ord n -> bool) (i: nat) :=\n  match lt_ge_dec i n with\n    | left H => f (Ord i H)\n    | _ => false\n  end.\n\n(** encapsulation of the various operations into ordinals *)\nDefinition xO n (i: ord n): ord (double n) := Ord (xO' i) (xO_bound _ _ (ord_lt i)).\nDefinition xI n (i: ord n): ord (double n) := Ord (xI' i) (xI_bound _ _ (ord_lt i)).\nDefinition mem n (x: ord (pow2 n)) (i: ord n) := mem' n x i.\nDefinition of_fun n (f: ord n -> bool): ord (pow2 n) := Ord (of_fun' n (app' f)) (of_fun_bound _ _). \n(** retraction from [ord n -> bool] into [ord (pow2 n)] *)\nLemma mem_of_fun n (f: ord n -> bool) i: mem (of_fun f) i = f i.\nProof.\n  unfold mem, of_fun. simpl. rewrite mem_of_fun' by apply ord_lt.\n  unfold app'. case lt_ge_dec. intros. f_equal. now apply eq_ord. \n  rewrite (ord_lt i). discriminate.  \nQed.\n\n(** injectivity of the [od] function *)\nLemma od_inj a b: od a = od b -> a = b. \nProof.\n  revert b. induction a using nat_ind_2; intros [|[|b]]; simpl; \n   trivial; (try (case od; discriminate)); (try discriminate). \n  intro. f_equal. f_equal. apply IHa. revert H. \n  case od. case od. congruence.\nQed.\n\n(** extensionality on natural numbers *)\nLemma ext' n: forall a b, \n  a<pow2 n -> b<pow2 n -> (forall i, i<n -> mem' n a i = mem' n b i) ->\n  a = b. \nProof.\n  induction n; simpl; intros a b Ha Hb H. \n   rewrite lt_n_1 by assumption. now apply lt_n_1.\n   apply od_inj. revert H. generalize (od_bound _ _ Ha), (od_bound _ _ Hb).\n   case od. intros oa a' Ha'. \n   case od. intros ob b' Hb'. \n   intro H. f_equal. \n    apply (H 0 eq_refl). \n    apply IHn; trivial. intros i Hi. apply (H (S i) Hi). \nQed.\n\n(** extensionality on ordinals (i.e., with [mem_of_fun], mem/of_fun form a bijection) *)\nLemma ext n (a b: ord (pow2 n)): (forall i, mem a i = mem b i) -> a = b. \nProof.\n  intro H. apply eq_ord. eapply ext'. apply ord_lt. apply ord_lt.\n  intros i Hi. apply (H (Ord i Hi)). \nQed.\n\n(** ** additional lemmas *)\n\nLemma xO_0 n: xO (@ord0 n) = @ord0 (S (double n)).\nProof. now apply eq_ord. Qed.\nLemma xO_S n (i: ord n): xO (ordS i) = ordS (ordS (xO i)).\nProof. now apply eq_ord. Qed.\nLemma xI_0 n: xI (@ord0 n) = ordS (@ord0 (double n)). \nProof. now apply eq_ord. Qed.\nLemma xI_S n (i: ord n): xI (ordS i) = ordS (ordS (xI i)).\nProof. now apply eq_ord. Qed.\n\nLemma mem_xO_0 n (f: ord (pow2 n)): @mem (S n) (xO f) ord0 = false.\nProof. unfold mem. simpl. now rewrite od_xO. Qed.\nLemma mem_xO_S n (f: ord (pow2 n)) i: @mem (S n) (xO f) (ordS i) = mem f i.\nProof. unfold mem. simpl. now rewrite od_xO. Qed.\nLemma mem_xI_0 n (f: ord (pow2 n)): @mem (S n) (xI f) ord0 = true.\nProof. unfold mem. simpl. now rewrite od_xI. Qed.\nLemma mem_xI_S n (f: ord (pow2 n)) i: @mem (S n) (xI f) (ordS i) = mem f i.\nProof. unfold mem. simpl. now rewrite od_xI. Qed.\n\nEnd set.\n\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/ordinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8615382183188421, "lm_q1q2_score": 0.7816841503314332}}
{"text": "Require Export Arith.EqNat. \n\nInductive natlist : Type :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition new_bob (a:bool)(b:bool):bool := if a then b else false.\n\nFixpoint beq_natlist (l : natlist) (m : natlist) : bool :=\nmatch l,m with\n|[] , [] => true\n| _ , [] => false\n|[] , _ => false\n|h :: t , h'::t' =>  new_bob (beq_nat h h') (beq_natlist t t')\nend.\n\nCheck new_bob.\n\nEval compute in (beq_natlist [1;2;3] [4;5;6]).\nEval compute in (beq_natlist [1;1;1] [1;1;1]).\n\n\n(*SearchAbout beq_nat.*)\n\n\nTheorem beq_nat_refl : forall n: nat, true = beq_nat n n.\nProof.\nintros.\ninduction n. \nsimpl. reflexivity.\nsimpl. rewrite IHn.\nsimpl. reflexivity.\nQed.\n\n\nTheorem beq_natlist_refl : forall l:natlist, true = beq_natlist l l.\nProof.\nsimpl. \ninduction l.\nsimpl. reflexivity.\nsimpl. rewrite <- IHl.\nsimpl. rewrite <- beq_nat_refl.\nsimpl. reflexivity.\nQed.\n\n\nEval compute in (beq_natlist_refl [1;2;3]).\n\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/11_beq_natlist_refl/beq_natlist_refl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7815808886121173}}
{"text": "\n\n\n(* -------------------------Description--------------------------------------\n\n   This file contains formalization of sorting for a list of elements of ordType\n  \n max_in l d        ==> returns the maximum in list l (returns d if l is nil)\n min_in l d        ==> returns the minimum in list l (returns d if l is nil) \n Sorted l         <==> l is sorted according to <=b relation\n put_in a l        ==> put a in correct place in a sorted list l\n sort_i l          ==> sort the list l in increasing order w.r.t <=b comp operator\n\n \n\n--------------------------------------------------------------------------- *)\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs OrdType.\nRequire Export Omega.\n\n\n\nSet Implicit Arguments.\n\nSection ListSorting.\n  Context { A: ordType }.\n\n  (*-----------max_in and min_in functions on lists with ordType elements ---------------  *)\n  \n   Fixpoint max_in (l: list A)(d: A): A:=\n    match l with\n    |nil => d\n    |a::l' => max_of a (max_in l' a)\n    end.\n   \n   Lemma max_spec (l:list A)(d:A)(a:A): In a l -> (a <b (max_in l d) \\/ a = (max_in l d)).\n   Proof. { generalize d. induction l.\n          { intros d0 H. inversion H. }\n          { intros d0 H. simpl.\n            assert (H1: a = a0 \\/ In a l). auto. \n            destruct H1. subst a. eauto. \n            assert (H1: a<b max_in l a0 \\/ a = max_in l a0). eauto.\n            destruct H1. left. apply @max_of_spec4. auto.  rewrite <- H1. eauto. } } Qed.\n  Lemma max_in_elim (a:A) (l:list A) (d:A) : In (max_in (a::l) d) (a::l).\n     Proof. { revert a. revert d. induction l.\n            { simpl. intros; left. eauto. }\n            { intros d a0. replace (max_in (a0 :: a :: l) d) with (max_of a0 (max_in (a::l) a0)).\n              unfold max_of. match_up a0 (max_in (a::l) a0); eauto.\n              simpl;auto. } } Qed.\n     \n Hint Resolve max_spec max_in_elim: core.\n\n     \n   Fixpoint min_in (l: list A)(d: A): A:=\n    match l with\n    |nil => d\n    |a::l' => min_of a (min_in l' a)\n    end.\n\n   Lemma min_spec (l:list A)(d:A)(a:A): In a l -> ((min_in l d) <b a \\/ (min_in l d)= a).\n   Proof. { generalize d. induction l.\n          { intros d0 H. inversion H. }\n          { intros d0 H. simpl.\n            assert (H1: a = a0 \\/ In a l). auto. \n            destruct H1. subst a. eauto. \n            assert (H1: min_in l a0 <b a \\/ min_in l a0 = a). eauto.\n            destruct H1. left.  auto. rewrite H1. auto. } } Qed.\n\n   Lemma min_in_elim (a:A) (l:list A) (d:A): In (min_in (a::l) d) (a::l).\n   Proof.  { revert a. revert d. induction l.\n            { simpl. intros; left. eauto. }\n            { intros d a0. replace (min_in (a0 :: a :: l) d) with (min_of a0 (min_in (a::l) a0)).\n              unfold min_of. match_up a0 (min_in (a::l) a0); eauto.\n              simpl;auto. } } Qed.\n   \n   Hint Resolve min_spec min_in_elim: core.\n\n   (* ------------- sorting a list of elements with ordType------------------------------*)\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 <=b x))) -> Sorted (a::l).\n\n  Lemma Sorted_elim1 (a:A) (b:A) (l: list A): (Sorted (a::b::l)) -> (a <=b b).\n  Proof. intro H. inversion H.  eapply H3. eauto. Qed.\n\n   Lemma Sorted_elim2 (a:A) (l:list A):\n    Sorted (a::l) ->(forall x, In x (a::l) -> a <=b x).\n  Proof. intro H. inversion H. intros. destruct H4. subst x. all: auto. Qed.\n  \n  Lemma Sorted_elim2a (a:A) (d:A) (l:list A): (Sorted (a::l)) -> a = (min_in (a::l) d). \n  Proof. {\n    intro H. inversion H.\n    assert (H4: In (min_in (a::l) d) (a::l)). eauto.\n    destruct H4. auto.\n    apply H3 in H4 as H5. assert (H6: (min_in (a::l) d) <=b a).\n    Check min_spec. apply /orP.\n    cut (min_in (a :: l) d <b a \\/ min_in (a :: l) d = a).\n    intro H6; destruct H6. left;auto. right; apply /eqP;auto.\n    apply min_spec. eauto.\n    move /orP in H5; move /orP in H6.\n    destruct H5; destruct H6. absurd (min_in (a :: l) d <b a);eauto.\n    move /eqP in H6. auto. all: apply /eqP; eauto using H5.  } Qed.\n\n  Lemma Sorted_elim3 (a:A) (l:list A): (Sorted (a::l)) -> Sorted l.\n  Proof. intro H. inversion H;auto. Qed.\n  \n  Lemma Sorted_elim4 (a:A) (l:list A): Sorted (a::l) ->(forall x, In x l -> a <=b x).\n  Proof. intro H. inversion H. auto. Qed.\n\n  Lemma Sorted_single (a:A) : (Sorted (a::nil)).\n  Proof. constructor. constructor. intros;simpl;contradiction. Qed.\n\n  Hint Resolve Sorted_elim1 Sorted_elim2 Sorted_elim2a Sorted_elim3 Sorted_elim4: core.\n  Hint Resolve Sorted_single: core.\n\n     \n  Fixpoint put_in (a: A) (l: list A) : list A:=\n    match l with\n    |nil=> a::nil\n    |b::l1 => match comp a b with\n             |Lt => a::l\n             |Eq => a::l\n             |Gt => b::(put_in a l1)\n                    end\n    end.\n\n  Lemma put_in_intro (a:A) (l: list A): forall x, In x l -> In x (put_in a l).\n  Proof. { intros x H. induction l. simpl in H. contradiction. simpl. match_up a a0.\n          destruct H. subst x. (eauto).\n         eauto. eauto. destruct H. subst x;\n         eauto. apply IHl in H as H1;eauto. } Qed.\n         \n  Lemma put_in_intro1 (a:A) (l: list A): In a (put_in a l).\n  Proof. { induction l. simpl. tauto. simpl. destruct (on_comp a a0). eauto.\n         eauto. eauto. } Qed.\n\n  Lemma put_in_elim (a:A) (l: list A): forall x, In x (put_in a l) -> (x=a)\\/(In x l).\n  Proof. { intros x H. induction l. simpl in H. simpl. destruct H. left. auto. auto.\n         simpl in H. match_up a a0.   destruct H. auto. auto. auto.\n         destruct H. right;subst x ;auto. apply IHl in H as H2.\n         destruct H2. auto. right. auto. } Qed.\n\n  Lemma put_in_correct : forall (a:A) (l: list A), Sorted l -> Sorted (put_in a l).\n  Proof. { intros a l. revert a. revert l. induction l.\n         { intros a1 H.  simpl. apply Sorted_single. }\n         simpl. intros a1 H.  destruct (on_comp a1 a).\n         subst a1.\n         { constructor. auto. inversion H. intros x H4. destruct H4. subst x.\n           apply /orP. right. apply /eqP;auto. auto. }\n         { constructor. auto.  intros x H2. destruct H2. subst x.\n           apply /orP. left. auto. inversion H. apply H5 in H1 as H6.\n           move /orP in H6. apply /orP.\n           destruct H6. left;auto. left. move /eqP in H6. subst x. auto. }\n         { assert (H1: Sorted l). eapply Sorted_elim3. eauto.\n           eapply IHl  with (a:=a1) in H1 as H2. constructor. auto. intros x H3.\n           apply put_in_elim in H3.  destruct  H3. subst x. apply /orP.  auto.\n           eapply Sorted_elim4 in H as Ha. eauto. auto. } } Qed.\n\n  Hint Resolve put_in_intro put_in_intro1 put_in_elim put_in_correct: core.\n           \n  Fixpoint sort_i (l: list A): list A:=\n    match l with\n    |nil => nil\n    |a::l1 => put_in a (sort_i l1)\n    end.\n  \n  \n  Lemma sort_i_intro (l: list A): forall x, In x l -> In x (sort_i l).\n  Proof. { intros x H. induction l. eauto. simpl. destruct H. subst x.\n         apply put_in_intro1. auto using put_in_intro. } Qed.\n\n  Lemma sort_i_elim (l: list A): forall x, In x (sort_i l) -> In x l.\n  Proof. { intros x H. induction l. simpl in H. contradiction.\n         simpl in H. apply put_in_elim in H. destruct H. subst x;eauto.\n         eauto. } Qed.\n\n  Lemma sort_i_is_correct (l: list A): Sorted (sort_i l).\n  Proof. induction l. simpl. constructor. simpl. auto using put_in_correct. Qed.\n\n  Hint Resolve sort_i_intro sort_i_elim sort_i_is_correct: core.\n  \n\nEnd ListSorting.\n\n\n\nHint Resolve max_spec max_in_elim: core. \nHint Resolve min_spec min_in_elim: core.\n\nHint Resolve Sorted_elim1 Sorted_elim2 Sorted_elim2a Sorted_elim3 Sorted_elim4: core.\nHint Resolve Sorted_single: core.\n\nHint Resolve put_in_intro put_in_intro1 put_in_elim put_in_correct: core.\nHint Resolve sort_i_intro sort_i_elim sort_i_is_correct: core.\n\n\n \n (* Definition l := 12::42::12::11::20::0::3::30::20::0::nil.\n Eval compute in (sort_i l).  *)", "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/SortOrdType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7815808832302357}}
{"text": "Require Export D.\n\nTheorem  plus_n_O : forall n : nat, n = n + 0.\nProof.\n  intros n. induction n.\n  - reflexivity.\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.\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 m. induction n.\n  - rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite -> IHn. rewrite -> plus_n_Sm. 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/02/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7815583320731674}}
{"text": "Require Import Nat Arith.\n\nInductive Tree : Type := node : nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nFixpoint tsize (tsize_arg0 : Tree) : nat\n           := match tsize_arg0 with\n              | leaf => 0\n              | node x l r => plus 1 (plus (tsize l) (tsize r))\n              end.\n\nTheorem theorem0 : forall (x : Tree), ge (tsize x) 0.\nProof.\n   intros.\n   induction x.\n   - simpl. apply le_O_n.\n   - simpl. auto.\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/tree_size.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7815583305802452}}
{"text": "(* Data and Functions\n\nThe proofs of these claims were always the same:\nuse simpl to simplify both sides of the equation,\nthen use reflexivity to check that both sides contain identical values.\n*)\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.\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1, b2 with\n  | true, true => false\n  | _, _ => true\nend.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\n\nExample test_nandb1: (nandb true false) = true.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_nandb2: (nandb false false) = true.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_nandb3: (nandb false true) = true.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_nandb4: (nandb true true) = false.\nProof.\nsimpl. reflexivity.\nQed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1, b2, b3 with\n  | true, true, true => true\n  | _, _, _ => false\nend.\n\nExample test_andb31: (andb3 true true true) = true.\nsimpl. reflexivity.\nQed.\n\nExample test_andb32: (andb3 false true true) = false.\nsimpl. reflexivity.\nQed.\n\nExample test_andb33: (andb3 true false true) = false.\nsimpl. reflexivity.\nQed.\n\nExample test_andb34: (andb3 true true false) = false.\nsimpl. reflexivity.\nQed.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\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\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 plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\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(*  factorial(0)  =  1\n       factorial(n)  =  n * factorial(n-1)     (if n>0) *)\n\nFixpoint factorial (n:nat) : nat :=\nmatch n with\n| O => S O\n| S p => mult n (factorial p)\nend.\n\n\nCompute (factorial 5).\n\nExample test_factorial1: (factorial 3) = 6.\nsimpl. reflexivity.\nQed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nsimpl. reflexivity.\nQed.\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\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\nFixpoint ltb (n m : nat) : bool :=\n  (leb n m) && (negb (eqb n m)).\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nsimpl. reflexivity.\nQed.\n\nExample test_ltb2: (ltb 2 4) = true.\nsimpl. reflexivity.\nQed.\n\nExample test_ltb3: (ltb 4 2) = false.\nsimpl. reflexivity.\nQed.\n\n(* Proof by Simplification *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.\nQed.\n\n(* Proof by Rewriting *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\nProof.\nintros n m H.\nrewrite H.\nreflexivity.\nQed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\nintros n m H.\nsimpl.\nrewrite <- H.\nreflexivity.\nQed.\n\n(* Proof by Case Analysis \n\nThe destruct generates two subgoals, which we must then prove, separately, in order to get Coq to accept the theorem.\nThe annotation \"as [| n']\" is called an intro pattern.\n*)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E. (* The eqn:E annotation tells destruct to give the name E to this equation.*)\n  - reflexivity.\n  - reflexivity. Qed.\n\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\nintros b c H.\ndestruct c eqn: E.\n- reflexivity.\n- rewrite <- H.\n  + destruct b eqn: E2. reflexivity. reflexivity.\nQed.\n\nTheorem andb_true_elim3 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c.\n  destruct b.\n  - destruct c.\n    + reflexivity.\n    + simpl. intros. assumption.\n  - destruct c.\n    + simpl. intros. reflexivity.\n    + simpl. intros H. assumption.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [|n'] eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\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.\nintros f H b.\ndestruct b.\n- rewrite H. rewrite H. reflexivity.\n- rewrite H. rewrite H. reflexivity.\nQed.\n\n\n(* Prove the following theorem.\n(Hint: This one can be a bit tricky, depending on how you approach it.\nYou will probably need both destruct and rewrite,\nbut destructing everything in sight is not the best way. *)\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.\n- simpl. intro. rewrite H. reflexivity.\n- simpl. intro. rewrite H. reflexivity.\nQed.\n\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (m:bin) : bin :=\nmatch m with\n| Z => B Z\n| B z => A (B z)\n| A n => A (A n)\nend.\n\n\nFixpoint bin_to_nat (m:bin): nat :=\nmatch m with\n| Z => O\n| B z => S (bin_to_nat z)\n| A n => S (bin_to_nat n)\nend.\n\n\n\nDefinition bar: nat := 1.\n\n\n\n", "meta": {"author": "NotBad4U", "repo": "software-foundations-vol1", "sha": "6bc676582dfedbbae664240f1443359fbb496131", "save_path": "github-repos/coq/NotBad4U-software-foundations-vol1", "path": "github-repos/coq/NotBad4U-software-foundations-vol1/software-foundations-vol1-6bc676582dfedbbae664240f1443359fbb496131/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.9032942112597332, "lm_q1q2_score": 0.7815519146519833}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import EqNat.\nRequire Import Arith.\n\nLemma beq_nat_comm : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros.\n  case_eq (beq_nat n m); intros Hbeq.\n    rewrite (beq_nat_true n m Hbeq).\n    apply beq_nat_refl.\n\n    case_eq (beq_nat m n); intros Hbeq2.\n      rewrite (beq_nat_true m n Hbeq2) in Hbeq.\n      rewrite <- beq_nat_refl in Hbeq.\n      discriminate.\n\n      reflexivity.\nQed.\n\nLemma bi_contrapos : forall A B: Prop, (A <-> B) -> (~A <-> ~B).\nProof.\n  intros A B; intros A_B.\n  unfold iff; apply conj.\n    intros not_A; intros pf_B.\n    apply not_A.\n    apply A_B; exact pf_B.\n\n    intros not_B; intros pf_A.\n    apply not_B.\n    apply A_B; exact pf_A.\nQed. \n\nLemma bi_conj : forall A B C D: Prop, ((A <-> C) /\\ (B <-> D)) -> ((A /\\ B) <-> (C /\\ D)).\nProof.\n  intros A B C D.\n  intros H.\n  destruct H as [A_C B_D].\n  unfold iff; apply conj.\n    intros AandB.\n    destruct AandB as [pf_A pf_B].\n    apply conj.\n      apply A_C; exact pf_A.\n\n      apply B_D; exact pf_B.\n    intros CandD.\n    destruct CandD as [pf_C pf_D].\n    apply conj.\n      apply A_C; exact pf_C.\n\n      apply B_D; exact pf_D.\nQed.\n\nLemma True_conj : forall (A B : Prop), (A <-> (True /\\ B)) <-> (A <-> B).\nProof.\n  intros.\n  split.\n    intros.\n    split.\n      intros.\n      destruct H as [H1 H2].\n      pose proof (H1 H0).\n      apply H.\n\n      intros.\n      apply H.\n      apply conj.\n        exact I.\n\n        exact H0.\n\n    intros.\n    split.\n      intros.\n      apply conj.\n        exact I.\n\n        apply H; exact H0.\n\n      intros.\n      apply H; apply H0.\nQed.\n\n\n(* ------------ *)\n\nLemma arith_minus_exp : forall (i n m : nat),\n  n - (m + i) = n - m - i.\nProof.\n  induction i.\n    intros.\n    rewrite <- plus_n_O.\n    rewrite Nat.sub_0_r.\n    reflexivity.\n\n    intros n m.\n    rewrite <- plus_n_Sm.\n    rewrite Nat.add_comm.\n    rewrite plus_n_Sm.\n    rewrite Nat.add_comm.\n    rewrite IHi.\n(* Search S plus.\n    rewrite one_suc. \nSearch plus \"comm\".\n    rewrite arith_plus_comm with (a := i). *)\n    rewrite <- Nat.sub_add_distr.\n    rewrite plus_Sn_m. rewrite plus_n_Sm.\n    rewrite Nat.sub_add_distr. reflexivity.\nQed.\n\nLemma leb_plus_r : forall (i n m : nat),\n  Nat.leb i n = true -> Nat.leb i (n + m) = true.\nProof.\n  intros i' n' m.\n  generalize n' i'.\n  induction m; intros n i H.\n    rewrite plus_0_r.\n    exact H.\n\n    specialize (IHm (n + 1) i).\n    rewrite <- Nat.add_1_r.\n    rewrite Nat.add_comm with (n := m).\n    rewrite <- plus_assoc_reverse.\n    apply IHm.\n    rewrite Nat.add_1_r.\n    apply leb_correct. apply le_S.\n    apply leb_complete. assumption.\nQed.\n\nLemma leb_minus_pre : forall (n m : nat),\n  Nat.leb n m = true -> Nat.leb (n-1) (m-1) = true.\nProof.\n  intros n m Hleb.\n  induction n.\n    induction m.\n      simpl; reflexivity.\n\n      simpl in *; reflexivity.\n\n    induction m.\n      simpl in *; discriminate.\n\n      simpl in *. \n      do 2 rewrite Nat.sub_0_r.\n      assumption.\nQed.\n\nLemma leb_minus : forall (i n m : nat),\n  Nat.leb n m = true -> Nat.leb (n-i) (m-i) = true.\nProof.\n  induction i.\n    intros.\n    do 2 rewrite Nat.sub_0_r; assumption.\n\n    intros n m Hleb.\n    rewrite <- Nat.add_1_r.\n    rewrite Nat.add_comm.\n    do 2 rewrite arith_minus_exp.\n    apply IHi.\n    apply leb_minus_pre.\n    assumption.\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_AiML/Coq code/my_arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172604, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7815519071632211}}
{"text": "(* week_37a_sum.v *)\n(* dIFP 2014-2015, Q1, Week 37 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* The goal of this file is to study the sum function:\n     sum f n = f 0 + f 1 + ... + f n\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nRequire Import unfold_tactic.\n\n(* ********** *)\n\n(* The canonical unfold lemmas\n   associated to plus and mult,\n   which are predefined:\n*)\n\nLemma unfold_plus_bc :\n  forall y : nat,\n    0 + y = y.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall x' y : nat,\n    (S x') + y = S (x' + y).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\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\n(* ********** *)\n\nNotation \"A === B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_tests_for_sum (sum : (nat -> nat) -> nat -> nat) :=\n  (sum (fun n => 0) 0 === 0)\n  &&\n  (sum (fun n => 0) 1 === 0 + 0)\n  &&\n  (sum (fun n => 0) 2 === 0 + 0 + 0)\n  &&\n  (sum (fun n => 1) 0 === 1)\n  &&\n  (sum (fun n => 1) 1 === 1 + 1)\n  &&\n  (sum (fun n => 1) 2 === 1 + 1 + 1)\n  &&\n  (sum (fun n => n) 0 === 0)\n  &&\n  (sum (fun n => n) 1 === 0 + 1)\n  &&\n  (sum (fun n => n) 2 === 0 + 1 + 2)\n  &&\n  (sum (fun n => n * n) 0 === 0 * 0)\n  &&\n  (sum (fun n => n * n) 1 === 0 * 0 + 1 * 1)\n  &&\n  (sum (fun n => n * n) 2 === 0 * 0 + 1 * 1 + 2 * 2)\n  &&\n  (sum (fun n => n * n) 3 === 0 * 0 + 1 * 1 + 2 * 2 + 3 * 3)\n  &&\n  (sum S 0 === 1)\n  &&\n  (sum S 1 === 1 + 2)\n  &&\n  (sum S 2 === 1 + 2 + 3)\n  .\n\n(* Exercise: add some more tests to this unit test. *)\n\n(* ********** *)\n\nDefinition specification_of_sum (sum : (nat -> nat) -> nat -> nat) :=\n  forall f : nat -> nat,\n    sum f 0 = f 0\n    /\\\n    forall n' : nat,\n      sum f (S n') = sum f n' + f (S n').\n\n(* ********** *)\n\nTheorem there_is_only_one_sum :\n  forall sum1 sum2 : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum1 ->\n    specification_of_sum sum2 ->\n    forall (f : nat -> nat)\n           (n : nat),\n      sum1 f n = sum2 f n.\nProof.\n  intros sum1 sum2.\n  intros S_sum1 S_sum2.\n  intros f n.\n  induction n as [ | n' IHn' ].\n    unfold specification_of_sum in S_sum1.\n    unfold specification_of_sum in S_sum2.\n    destruct (S_sum1 f) as [ H_sum1_bc H_sum1_ic].\n    destruct (S_sum2 f) as [ H_sum2_bc H_sum2_ic].\n    clear S_sum1.\n    clear S_sum2.\n    rewrite -> H_sum2_bc.\n    apply H_sum1_bc.\n\n  unfold specification_of_sum in S_sum1.\n  unfold specification_of_sum in S_sum2.\n  destruct (S_sum1 f) as [ H_sum1_bc H_sum1_ic].\n  destruct (S_sum2 f) as [ H_sum2_bc H_sum2_ic].\n  clear S_sum1.\n  clear S_sum2.\n  rewrite -> (H_sum1_ic n').\n  rewrite -> (H_sum2_ic n').\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Misc. instances of the sum function: *)\n\nLemma about_sum_0 :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall n : nat,\n      sum (fun i => 0) n = 0.\nProof.\n  intros sum S_sum n.\n  induction n as [ | n' IHn' ].\n    unfold specification_of_sum in S_sum.\n    destruct (S_sum (fun _ : nat => 0)) as [ H_sum_bc H_sum_ic ].\n    clear S_sum.\n    apply H_sum_bc.\n  unfold specification_of_sum in S_sum.\n  destruct (S_sum (fun _ : nat => 0)) as [ H_sum_bc H_sum_ic ].\n  clear S_sum.\n  rewrite -> (H_sum_ic n').\n  rewrite -> (plus_0_r (sum (fun _ : nat => 0) n')).\n  apply IHn'.\nQed.\n\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\nLemma plus_1_l :\n  forall n : nat,\n    1 + n = S n.\nProof.\n  intro n.\n  rewrite -> (unfold_plus_ic 0 n).\n  rewrite -> (unfold_plus_bc n).\n  reflexivity.\nQed.\n\nLemma plus_1_r :\n  forall n : nat,\n    n + 1 = S n.\nProof.\n  intro n.\n  rewrite -> (plus_comm n 1).\n  apply (plus_1_l n).\nQed.\n\nLemma about_sum_1 :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall n : nat,\n      sum (fun i => 1) n = S n.\nProof.\n  intros sum S_sum n.\n  induction n as [ | n' IHn'].\n    unfold specification_of_sum in S_sum.\n    destruct (S_sum (fun _ : nat => 1)) as [H_sum_bc H_sum_ic].\n    clear S_sum.\n    apply H_sum_bc.\n  unfold specification_of_sum in S_sum.\n  destruct (S_sum (fun _ : nat => 1)) as [_ H_sum_ic].\n  clear S_sum.\n  rewrite -> (H_sum_ic n').\n  rewrite -> IHn'.\n  rewrite -> (plus_Sn_m n' 1).\n  rewrite -> (plus_1_r n').\n  reflexivity.\nQed.\n\n(* Replace \"Abort.\" with a proof. *)\n\n(* ***** *)\n\nLemma about_sum_identity :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall n : nat,\n      2 * sum (fun i => i) n = n * S n.\nProof.\n  intros sum S_sum n.\n  induction n as [ | n' IHn'].\n    unfold specification_of_sum in S_sum.\n    destruct (S_sum (fun i : nat => i)) as [H_sum_bc _].\n    clear S_sum.\n    rewrite -> H_sum_bc.\n    rewrite -> (mult_0_r 2).\n    rewrite -> (mult_0_l 1).\n    reflexivity.\n  unfold specification_of_sum in S_sum.\n  destruct (S_sum (fun i : nat => i)) as [_ H_sum_ic].\n  clear S_sum.\n  rewrite -> (H_sum_ic n').\n  Check mult_plus_distr_l.\n  rewrite -> (mult_plus_distr_l 2 (sum (fun i : nat => i) n') (S n')).\n  rewrite -> IHn'.\n  Check mult_plus_distr_r.\n  rewrite <- (mult_plus_distr_r n' 2 (S n')).\n  Check plus_comm.\n  rewrite -> (plus_comm n' 2).\n  rewrite -> (unfold_plus_ic 1 n').\n  rewrite -> (unfold_plus_ic 0 n').\n  rewrite -> (plus_0_l n').\n  Check mult_comm.\n  rewrite -> (mult_comm (S (S n')) (S n')).\n  reflexivity.\nQed.\n\n(* ***** *)\n\nLemma about_sum_even_numbers :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall n : nat,\n      sum (fun i => 2 * i) n = n * S n.\nProof.\n  intros sum S_sum n.\n  induction n as [ | n' IHn'].\n    unfold specification_of_sum in S_sum.\n    destruct (S_sum (fun i => 2 * i)) as [H_sum_bc _].\n    rewrite -> H_sum_bc.\n    rewrite -> (mult_0_r 2).\n    rewrite -> (mult_0_l 1).\n    reflexivity.\n  unfold specification_of_sum in S_sum.\n  destruct (S_sum (fun i => 2 * i)) as [_ H_sum_ic].\n  clear S_sum.\n  rewrite -> (H_sum_ic n').\n  rewrite -> IHn'.\n  Check mult_plus_distr_r.\n  rewrite <- (mult_plus_distr_r n' 2 (S n')).\n  rewrite -> (plus_comm n' 2).\n  rewrite -> (unfold_plus_ic 1 n').\n  rewrite -> (unfold_plus_ic 0 n').\n  rewrite -> (unfold_plus_bc n').\n  rewrite -> (mult_comm (S (S n')) (S n')).\n  reflexivity.\nQed.\n\n(* ***** *)\n\nLemma a_humble_little_lemma :\n  forall a b c : nat,\n    a + b + b + c = a + 2 * b + c.\nProof.\n  intros a b c.\n  rewrite -> (unfold_mult_ic 1 b).\n  rewrite -> (unfold_mult_ic 0 b).\n  rewrite -> (unfold_mult_bc b).\n  rewrite -> plus_0_r.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\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  rewrite -> (mult_plus_distr_r x y (x + y)).\n  rewrite -> (mult_plus_distr_l x x y).\n  rewrite -> (mult_plus_distr_l y x y).\n  rewrite -> plus_assoc.\n  rewrite <- (mult_assoc 2 x y).\n  rewrite (unfold_mult_ic 1 (x * y)).\n  rewrite (unfold_mult_ic 0 (x * y)).\n  rewrite (unfold_mult_bc (x * y)).\n  rewrite -> (plus_0_r (x * y)).\n  rewrite -> plus_assoc.\n  rewrite -> (mult_comm y x).\n  reflexivity.\n\n  Restart.\n\n  intros x y.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> plus_assoc.\n  rewrite -> unfold_mult_ic.\n  rewrite -> unfold_mult_ic.\n  rewrite -> unfold_mult_bc.\n  rewrite -> plus_assoc.\n  rewrite -> plus_0_r.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> plus_assoc.\n  rewrite -> (mult_comm x y).\n  reflexivity.\nQed.\n\nLemma about_sum_odd_numbers :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall n : nat,\n      sum (fun i => S (2 * i)) n = S n * S n.\nProof.\n  intros sum S_sum n.\n  induction n as [ | n' IHn'].\n    unfold specification_of_sum in S_sum.\n    destruct (S_sum (fun i : nat => S (2 * i))) as [H_sum_bc _].\n    clear S_sum.\n    rewrite -> (H_sum_bc).\n    rewrite -> (mult_0_r 2).\n    rewrite -> (mult_1_r 1).\n    reflexivity.\n  unfold specification_of_sum in S_sum.\n  destruct (S_sum (fun i : nat => S (2 * i))) as [_ H_sum_ic].\n  clear S_sum.\n  rewrite -> (H_sum_ic n').\n  rewrite -> IHn'.\n  rewrite -> (unfold_mult_ic 1 (S n')).\n  rewrite -> (unfold_mult_ic 0 (S n')).\n  rewrite -> (unfold_mult_bc (S n')).\n  rewrite -> (plus_0_r (S n')).\n  rewrite <- (plus_Sn_m (S n') (S n')).\n  rewrite -> (mult_succ_l (S n') (S (S n'))).\n  rewrite -> (mult_succ_r (S n') (S n')).\n  rewrite -> (plus_comm (S (S n')) (S n')).\n  rewrite plus_assoc.\n  reflexivity.\nQed.\n\n(* ***** *)\n\n(* From the June exam of dProgSprog 2012-2013: *)\n\nLemma factor_sum_on_the_left :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall (h : nat -> nat)\n           (c k : nat),\n      sum (fun x => c * h x) k = c * sum (fun x => h x) k.\nProof.\n  intros sum S_sum h c k.\nAbort.\n\n\n(* Replace \"Abort.\" with a proof. *)\n\nLemma factor_sum_on_the_right :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall (h : nat -> nat)\n           (c k : nat),\n      sum (fun x => h x * c) k = (sum (fun x => h x) k) * c.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\nTheorem June_exam :\n  forall sum : (nat -> nat) -> nat -> nat,\n    specification_of_sum sum ->\n    forall (f g : nat -> nat)\n           (m n : nat),\n      sum (fun i => sum (fun j => f i * g j) n) m =\n      (sum (fun i => f i) m) * (sum (fun j => g j) n).\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* Food for thought:\n   is the following specification of sum\n   equivalent to the one above?\n*)\n\nDefinition alt_specification_of_sum (sum : (nat -> nat) -> nat -> nat) :=\n  (forall f : nat -> nat,\n    sum f 0 = f 0)\n  /\\\n  (forall (f : nat -> nat)\n          (n' : nat),\n     sum f (S n') = sum f n' + f (S n')).\n\n(* ********** *)\n\n(* A first implementation: *)\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\nLemma unfold_sum_ds_bc :\n  forall f : nat -> nat,\n    sum_ds f 0 = f 0.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic sum_ds.\nQed.\n\nLemma unfold_sum_ds_ic :\n  forall (f : nat -> nat)\n         (n' : nat),\n    sum_ds f (S n') = sum_ds f n' + f (S n').\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic sum_ds.\nQed.\n\nDefinition sum_v0 (f : nat -> nat) (n : nat) : nat :=\n  sum_ds f n.\n\nCompute unit_tests_for_sum sum_v0.\n\nTheorem sum_v0_satisfies_the_specification_of_sum :\n  specification_of_sum sum_v0.\nProof.\n  unfold specification_of_sum.\n  unfold sum_v0.\n  intro f.\n  split.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* A second implementation: *)\n\nFixpoint sum_ds' (f : nat -> nat) (n : nat) : nat :=\n  match n with\n  | 0 => f 0\n  | S n' => f n + sum_ds' f n'\n  end.\n\nDefinition sum_v1 (f : nat -> nat) (n : nat) : nat :=\n  sum_ds' f n.\n\nCompute unit_tests_for_sum sum_v1.\n\nTheorem sum_v1_satisfies_the_specification_of_sum :\n  specification_of_sum sum_v1.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(*\n   Prove the equivalence of sum_v0 and sum_v1.\n*)\n\nTheorem sum_v0_and_sum_v1_are_functionally_equal :\n  forall (f : nat -> nat)\n         (n : nat),\n    sum_v0 f n = sum_v1 f n.\nProof.\nAbort.\n(* Replace \"Abort.\" with a proof. *)\n\n(* ********** *)\n\n(* A third implementation: *)\n\nFixpoint sum_acc (f : nat -> nat) (n a : nat) : nat :=\n  match n with\n  | 0 => f 0 + a\n  | S n' => sum_acc f n' (a + f n)\n  end.\n\nDefinition sum_v2 (f : nat -> nat) (n : nat) : nat :=\n  sum_acc f n 0.\n\n(* Does this implementation fit the specification of sum? *)\n\n(* ********** *)\n\n(* A fourth implementation: *)\n\nFixpoint sum_acc' (f : nat -> nat) (n a : nat) : nat :=\n  match n with\n  | 0 => f 0 + a\n  | S n' => sum_acc f n' (f n + a)\n  end.\n\nDefinition sum_v3 (f : nat -> nat) (n : nat) : nat :=\n  sum_acc' f n 0.\n\n(* Does this implementation fit the specification of sum? *)\n\n(* ********** *)\n\n(* end of week_37a_sum.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w37/week_37a_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8705972633721707, "lm_q1q2_score": 0.7815310717992094}}
{"text": "Require Import Arith List Omega.\n\n(** * Skew Binary Numbers, and application to Fast-Access Lists *)\n\n(** Pierre Letouzey, (c) 2016. Version 1.0 9/2/2015 *)\n\n(** This file is compatible with Coq 8.4 or 8.5. *)\n\n(** Source: Okasaki's book \"Purely Functional Data Structures\". *)\n\n(* Nota: all comments except this one are in CoqDoc syntax,\n   hence the leading **, and the first [  ] around all Coq elements. *)\n\n\n(** ** Misc Coq setup *)\n\n(** Notations [[]] for [nil] and [[a;b;c]] for [a::b::nil] : *)\nImport ListNotations.\n\n(** Some compatibility between Coq 8.4 and Coq 8.5 : *)\nRequire Import NPeano.\nInfix \"=?\" := Nat.eqb.\nSet Asymmetric Patterns.\n\n(** Some customizations of the [auto] tactic : *)\nHint Extern 10 (@eq nat _ _) => omega.\nHint Extern 10 (_ <= _) => omega.\nHint Extern 10 (_ < _) => omega.\n\n(** A short alias for the [inversion] tactic : *)\nLtac inv := inversion 1; subst; simpl; auto.\nLtac ind n := induction n;subst;simpl in *;auto.\n\n\n(** ** PART I : Skew Binary Numbers *)\n\n(** *** Definition of decompositions *)\n\n(** [ones n] is the natural number with [n] times the digit 1,\n    that is [2^n - 1]. Using a direct recursive definition helps\n    in some proofs below. *)\nFixpoint ones n :=\n match n with\n | 0 => 0\n | S n => 2 * ones n + 1\n end.\n\n(** Some properties of [ones] *)\n\n\nLemma pow_minus_1 n:\n  2^n - 1 + 1 = 2^n.\nProof.\n  ind n.\nQed.\n  \nLemma ones_pow n : ones n = 2^n-1.\nProof.\n  ind n.\n  rewrite <- !plus_n_O.\n  rewrite IHn.\n  rewrite <- plus_assoc.\n  rewrite pow_minus_1.\n  omega.\nQed.\n\nLemma ones_pos n : 0 < n -> 0 < ones n.\nProof.\n  inv.\nQed.\n  \n\nLemma ones_le_mono :forall n m,  n <= m -> ones n <= ones m.\nProof.\n  intros.\n  induction H.\n  auto.\n  simpl. auto.\nQed.  \n  \n  \nLemma ones_lt_mono n m : n < m -> ones n < ones m.\nProof.\n  intros.\n  induction H;simpl;rewrite <- plus_n_O;omega.\nQed.\n  \n(** [sum_ones [a;b;...]] is the sum [(2^a-1)+(2^b-1)+...].\n    If [n] is the obtained numbers, we say that the list\n    [[a;b;...]] is a skew binary decomposition of [n]. *)\nFixpoint sum_ones l :=\n  match l with\n  | nil => 0\n  | n :: l' => ones n + sum_ones l'\n  end.\n\n(** Some properties of [sum_ones] *)\n\nLemma sum_ones_app l l' :\n sum_ones (l++l') = sum_ones l + sum_ones l'.\nProof.\n  ind l.\nQed.\n\nLemma sum_ones_rev l :\n  sum_ones (rev l) = sum_ones l.\nProof.\n  ind l.\n  rewrite sum_ones_app.\n  simpl.\n  auto.\nQed.\n\n(** *** Canonical decompositons *)\n\n(** Not all decompositions of [n] are interesting. For instance,\n    the decomposition [1;1;...;1] always exists, but is quite\n    boring. And a [0] in arev l ++ [a] decomposition doesn't add anything.\n    We'll now consider the canonical decompositions of the form\n    [[a;b;c;d;...]] with [0<a<=b<c<d<...] :\n    all factors in these decompositions are strictly positive, and\n    only the smallest factor may be repeated (at most twice),\n    all the other factors appear only once.\n    This is expressed by the [Skew] predicate below. It uses\n    the [Incr] predicate that expresses that a list is strictly\n    increasing. *)\n\nInductive Incr : list nat -> Prop :=\n | IncrNil : Incr []\n | IncrOne n : Incr [n]\n | IncrCons n m l : n < m -> Incr (m::l) -> Incr (n :: m :: l).\n\nCheck Incr.\n\nInductive Skew : list nat -> Prop :=\n | SkewNil : Skew []\n | SkewOne n : 0 < n -> Skew [n]\n | SkewCons n m l : 0 < n <= m -> Incr (m :: l) -> Skew (n::m::l).\n\nHint Constructors Skew Incr.\n\nLemma skew_examples : Skew [2;2;5;7] /\\ Skew [1;2;3].\nProof.\n auto.\nQed.\n  \n(** Some properties of the [Skew] and [Incr] predicates *)\n\n\nLemma Incr_Skew m l : Incr (m::l) -> 0 < m -> Skew (m::l).\nProof.\n  inv.\nQed.\n\nLemma Skew_inv n l : Skew (n::l) -> Skew l.\nProof.\n  inv.\n  apply Incr_Skew;auto.\nQed.\n\n\n(** The main result is now that any natural number admits one\n    and only one canonical skew binary decomposition. *)\n\n\n(** *** Existence *)\n\n(** For the \"exist\" part of the statement, we can even build\n    the decomposition of [n+1] explicitely out of the\n    decomposition of [n]. *)\n\n(** Nota: the syntax [n =? m] is a boolean equality test [Nat.eqb].\n    For reasoning about it, you can do a [case Nat.eqb_spec] when\n    your goal contains a [=?]. *)\n\nDefinition next l :=\n  match l with\n  | n::m::l' => if n =? m then (S n) :: l' else 1::l\n  | _ => 1::l\n  end.\n\nLemma next_sum l : sum_ones (next l) = S (sum_ones l).\nProof.\n  ind l.\n  destruct l;simpl;auto.\n  case Nat.eqb_spec.\n  intros;simpl;rewrite <- !plus_n_O;rewrite e;auto.\n  intros;simpl;auto.\nQed.  \n\n\nLemma gg m n :m < n -> S m <= n.\nProof.\n  omega.\nQed.\n\nLemma gz m n l0:  Incr (m :: n :: l0) -> m < n.\nProof.\n  inv.\nQed.\n\nLemma next_skew l : Skew l -> Skew (next l).\nProof.\n  inv.\n  case Nat.eqb_spec;auto.\n  intros;subst.\n  destruct l0;simpl;auto.\n  apply SkewCons.\n  split;simpl;auto.\n  apply gz in H1;auto.\n  inversion H1;auto.\nQed.\n\n\n (** analyse de l0 et regarder ce qui en sort pour en déduir la fin*)\n\n (** So the decomposition of [n] is obtained by repeating\n    [n] times the [next] function. *)\n\nFixpoint iter_next n :=\n match n with\n | 0 => nil\n | S n => next (iter_next n)\n end.\n\nLemma iter_next_sum n : sum_ones (iter_next n) = n.\nProof.\n  induction n;simpl;auto.\n  rewrite next_sum.\n  auto.\nQed.  \n  \n\nLemma iter_next_skew n : Skew (iter_next n).\nProof.\n  induction n;simpl;auto.\n  apply next_skew;auto.\nQed.\n\n\n(** Hence the existence statement: *)\n\nLemma decomp_exists : forall n, exists l, sum_ones l = n /\\ Skew l.\nProof.\n  intros.\n  exists (iter_next n).\n  split.\n  rewrite iter_next_sum.\n  auto.\n  apply iter_next_skew.\nQed.\n\nLemma decomp_exists' : forall n, exists l, Skew l -> sum_ones l = n.\nProof.\n  intros.\n  exists (iter_next n).\n  intros.\n  rewrite iter_next_sum.\n  auto.\nQed.\n\n\n\n(** *** Reversed canonical decomposition *)\n\n(** For the unicity of the decomposition, we have to study the\n    largest factor. For that, it is quite easier to consider\n    a decomposition sorted in decreasing order : the largest\n    factor will come first in the list.\n    The [Weks] predicate is equivalent to [Skew] on the mirror\n    list. Its definition is standalone, but we'll also need\n    later a [Decr] predicate stating that a list is strictly\n    decreasing. *)\n\nInductive Weks : list nat -> Prop :=\n | WeksNil : Weks []\n | WeksOne n : 0 < n -> Weks [n]\n | WeksTwo n : 0 < n -> Weks [n;n]\n | WeksCons n m l : m < n -> Weks (m::l) -> Weks (n::m::l).\n\nInductive Decr : list nat -> Prop :=\n | DecrNil : Decr []\n | DecrOne n : Decr [n]\n | DecrCons n m l : m < n -> Decr (m :: l) -> Decr (n :: m :: l).\n\nHint Constructors Weks Decr.\n\n(** Let's now prove equivalences between [Skew] and [Weks]. *)\n\nLemma Incr_last l n m :\n  Incr (l++[n]) -> n < m -> Incr (l++[n;m]).\nProof.\n  ind l.\n  intros.\n  destruct l;simpl in *;auto;inversion H;auto.\nQed.\n\n\nLemma Decr_last l n m :\n  Decr (l++[n]) -> m < n -> Decr (l++[n;m]).\nProof.\n  ind l.\n  intros.\n  destruct l;simpl;auto;inversion H;auto.\nQed.\n\n\nLemma Incr_Decr l : Incr l -> Decr (rev l).\nProof.\n  ind l;intros.\n  destruct l;simpl;auto.\n  rewrite <- app_assoc;simpl.\n  inversion H;apply IHl in H4.\n  apply Decr_last;auto.\nQed.\n\n\n(** Un lemme pas si facile *)\nLemma Skew_last l n m :\n  Skew (l++[n]) -> n < m -> Skew (l++[n;m]).\nProof.\n  ind l;intros.\n  apply SkewCons;auto.\n  split;inversion H;auto.\n  destruct l;simpl in *;auto.\n  inversion H;auto.\n  inversion H;apply SkewCons;auto.\n  apply (Incr_last (n0 :: l) n m) in H5;simpl in *;auto.\nQed.\n\n\nLemma tt a l : Decr (a :: l) ->  Decr (l).\nProof.\n  inv.\nQed.\n\n\nLemma Weks_last l n m :\n Decr (l++[n]) -> 0 < m <= n -> Weks (l++[n;m]).\nProof.\n  ind l.\n  intros.\n  case H0.\n  intros;case H2;auto.\n  intros;simpl;auto.\n  destruct l;simpl in *;auto;inversion H;auto.\nQed.\n\n\nLemma Incr_inf_last  n0 n a:  Incr ([n0; n; a])  -> n < a.\nProof.\n  inv;inversion H4;auto.\nQed.\n\n\nLemma Incr_App_inf_last l n0 n a:  Incr (l ++ [n0; n; a])  -> n < a.\nProof.\n  induction l;simpl.\n  intros;inversion H;inversion H4;auto.\n  intros;simpl in *;auto.\n  apply IHl.\n  inversion H;auto.\nQed.\n\n\nLemma Incr_inv a l : Incr (a :: l) ->  Incr l.\nProof.\n  inv.\nQed.\n\nLemma  Incr_inv_app l n0 n a : Incr (l ++ [n0; n; a]) ->  Incr (l ++ [n0; n]).\nProof.  \n  induction l;simpl;auto.\n  intros.\n  apply IncrCons;auto.\n  inversion H;auto.\n  destruct l;simpl in *;auto.\n  intros;inversion H.\n  apply IncrCons;auto.\n\n  intros.\n  apply IncrCons.\n  inversion H;auto.\n  apply Incr_inv in H.\n  apply IHl.\n  auto.\nQed.\n  \nLemma Skew_app_inf_last l n0 n a:  Skew (l ++ [n0; n; a])  -> n < a.\nProof.\n  induction l.\n  inv.\n  inversion H4;auto.\n  intros.\n  apply IHl.\n  inversion H.\n  auto.\n  apply Incr_Skew in H3.\n  auto.\n  omega.\nQed.\n\n\nLemma Weks_Skew1 l : Weks l -> Skew (rev l).\nProof.\n  induction l;simpl in *;auto.\n  inv.\n  rewrite <- app_assoc;simpl in *.\n  apply Skew_last;auto.\nQed.  \n\n\nLemma  Skew_inv_last l n0 n a : Skew (l ++ [n0;n;a]) -> Skew (l++[n0;n]).\nProof.\n  induction l;simpl;auto.\n  intros;inversion H;auto.\n  intros.\n  destruct l;simpl in *;auto.\n  apply SkewCons;inversion H;auto.\n  apply IncrCons;inversion H4;auto.\n  constructor;inversion H;auto.\n  inversion H.\n  apply Incr_inv in H9.\n  apply Incr_inv_app in H9.\n  destruct l;simpl in *;auto.\n  apply IncrCons.\n  inversion H9;auto.\n  inversion H4;auto.\n  apply IncrCons;auto.\n  inversion H9;auto.\n  apply IncrCons.\n  inversion H4;auto.\n  auto.\nQed.  \n\nLemma list_empty_no l (a : nat) :\n  [] <> l ++ [a].\nProof.\n  induction l;simpl;auto.\n  discriminate.\n  intros.\n  discriminate.\nQed.  \n\nLemma list_empty_no2 l (a0 a1 : nat) :\n  [] = l ++ [a0 ; a1] -> False.\nProof.\n  induction l;simpl;auto.\n  discriminate.\n  intros.\n  discriminate.\nQed.  \n\nLemma list_empty_no3 l (n0 a0 a1 : nat) :\n  [n0] = l ++ [a0 ; a1] -> False.\nProof.\n  induction l;simpl;auto.\n  discriminate.\n  intros.\n  destruct l;simpl in *;auto.\n  discriminate.\n  discriminate.\nQed. \n\nLemma Weks_Skew2 l : Skew (rev l) -> Weks l.\nProof.\n  ind l.\n  intros.\n  destruct l;simpl in *;auto.\n  inversion H;auto.\n  destruct l;simpl in *;auto.\n  inversion H;auto.\n  case H2.\n  intros.\n  case H6;auto.\n  rewrite <- !app_assoc in *;simpl in *.\n  apply WeksCons.\n  apply Skew_app_inf_last in H;auto.\n  apply Skew_inv_last in H;auto.\nQed.\n \n\nLemma Weks_Skew l : Skew (rev l) <-> Weks l.\nProof.\n  split.\n  apply  Weks_Skew2.\n  apply  Weks_Skew1.\nQed.\n  (** *** Unicity *)\n\nLemma Weks_pos n l : Weks (n::l) -> 0 < n.\nProof.\n  inv.\nQed.\nLemma Weks_inv n l : Weks (n::l) ->  Weks (l).\nProof.\n  inv.\nQed.  \n(** The key property : a canonical decomposition with [n] as\n    largest factor cannot exceed [ones (S n)].\n    Hence two decompositions with the same sum will have the\n    same largest factors. *)\nLemma deb a n l: (ones a + sum_ones l) < ones n + 1  <-> ones n + (ones a + sum_ones l) < ones n + ones n + 1 .\nProof.\n  omega.\nQed.\n\nLemma tr1 a n : ones a + ones a  <= ones n + ones n + 1 -> \n                ones a + ones a + 1 <= ones n + ones n + 1 + 1.\nProof.\n  omega.\nQed.\n\n  \nLemma uui a n :\n  ones (S a) <= ones (S n) -> ones a + ones a  <= ones n + ones n + 1.\nProof.\n  simpl in *.\n  rewrite !Nat.add_0_r.\n  \n  omega.\nQed.\n\n  \nLemma aux a b c:\n  a < b -> c + a < c + b.\nProof.\n  omega.\nQed.\n\nLemma aux2 n m:\n  n <= m -> n + 1 <= m + 1.\nProof.\n  omega.\nQed.\n  \nLemma sum_ones_bound n l : \n  Weks (n::l) -> sum_ones (n::l) < ones (S n).\nProof.\n  revert n.\n  induction l.\n  intros;simpl;auto.\n  inv.\n  rewrite <- !plus_n_O.\n  rewrite <- plus_assoc.\n  apply aux.  \n  apply lt_le_trans with (ones (S a)).\n  apply IHl;auto.\n  induction n;simpl;auto.\n  rewrite <- !plus_n_O in *.\n  apply ones_le_mono in H2.\n  apply aux2.\n  simpl in *.\n  rewrite <- !plus_n_O in *.\n  omega.\nQed.\n\n\nLemma ones_pos_inv m :\n  0 < ones m -> 0 < m.\nProof.\n  induction m;auto.\nQed.\n  \nLemma ones_lt_mono_inv n m : ones n < ones m -> n < m .\nProof.\n  intros.\n  destruct (le_lt_dec m n);auto.\n  apply ones_le_mono in l;auto.\nQed.\n\n\nLemma  sum_equal a l l' :\n  sum_ones (a :: l) = sum_ones (a :: l') -> sum_ones l = sum_ones l'.\nProof.\n  inv.\nQed.  \n\n  \nLemma decomp_unique_weks l l' : Weks l -> Weks l' ->\n sum_ones l = sum_ones l' -> l = l'.\nProof.\n  revert l'.\n  ind l;intros.\n  destruct l';simpl in *;auto.\n  inversion H0;subst;simpl in *;auto.\n  apply ones_lt_mono in H3;simpl in H3;omega.\n  apply ones_lt_mono in H3;simpl in H3;omega.\n  apply ones_lt_mono in H4;simpl in H4;omega.\n  destruct l';simpl in *;auto.\n  inversion H;subst;simpl in *;auto.\n  apply ones_lt_mono in H3;simpl in H3;omega.\n  apply ones_lt_mono in H3;simpl in H3;omega.\n  apply ones_lt_mono in H4;simpl in H4;omega.\n  assert (a < S n).\n  apply ones_lt_mono_inv.\n  apply le_lt_trans with (ones n + sum_ones l').\n  omega.\n  apply sum_ones_bound;auto.\n  assert (n < S a).\n  apply ones_lt_mono_inv.\n  apply le_lt_trans with (ones a + sum_ones l).\n  omega.\n  apply sum_ones_bound;auto.\n  assert (a = n) by omega.\n  subst.\n  f_equal.\n  apply IHl.\n  apply Weks_inv in H;auto.\n  apply Weks_inv in H0;auto.\n  omega.\nQed.\n\n\nLemma rev_equal (l:list nat) (l':list nat) : l = l' -> (rev l) = (rev l').\nProof.\n  inv.\nQed.\n \nLemma decomp_unique l l' : Skew l -> Skew  l' ->\n sum_ones l = sum_ones l' -> l = l'.\nProof.\n  intros.\n  rewrite <- (rev_involutive l) in *.\n  rewrite <- (rev_involutive l') in *.\n  apply Weks_Skew in H.\n  apply Weks_Skew in H0.\n  rewrite (sum_ones_rev (rev l)) in H1.\n  rewrite (sum_ones_rev (rev l')) in H1.\n  f_equal.\n  apply decomp_unique_weks;auto.\nQed.\n  \n  \n\n   \nLemma decomp_unique' l n :\n  Skew l -> n = sum_ones l -> l = iter_next n.\nProof.\n  intros.\n  symmetry in H0.\n  rewrite <- iter_next_sum in H0.\n  apply decomp_unique;auto.\n  apply iter_next_skew.\nQed.\n\n\n\n\n(** *** Decomposition of predecessor *)\n\n(** In the same spirit as [next], we could actually build\n    the decomposition of [n-1] out of the decomposition of [n].\n    Note that this function is meant to be used on canonical\n    decomposition, [prev (0::l)] isn't supposed to occur, we can\n    answer anything in this case, here [nil]. *)\n\nDefinition prev l :=\n  match l with\n  | 1::l => l\n  | (S n)::l => n::n::l\n  | _ => nil\n  end.\n\n\nLemma prev_sum l : Skew l ->\n sum_ones (prev l) = pred (sum_ones l).\nProof.\n  induction l;simpl;subst;auto.\n  case a;simpl;auto.\n  inv.\n  intros.\n  case n;simpl;auto.\nQed.  \n\n\nLemma prev_skew l : Skew l -> Skew (prev l).\nProof.\n  induction l;simpl;auto.\n  destruct a;simpl;auto.\n  inv.\n  destruct a;simpl;auto.\n  destruct a;simpl;auto.\n  apply Skew_inv in H;auto.\nQed.\n\n(** And thanks to the unicity, we could easily prove results\n    about the composition of [prev] and [next]. *)\n\nLemma prev_next l : Skew l -> prev (next l) = l.\nProof.\n  inv.\n  case Nat.eqb_spec;simpl;auto.\n  case n;intros.\n  omega.\n  rewrite !e;auto.\nQed.\n  \n  \nLemma next_prev l : Skew l -> l<>nil -> next (prev l) = l.\nProof.\n  inv.\n  intros.\n  destruct H0;auto.\n  intros l.\n  destruct n.\n  intros;omega.\n  destruct n.\n  intros;simpl;auto.\n  auto.\n  simpl.\n  case Nat.eqb_spec;auto.\n  intros.\n  omega.\n  destruct n.\n  omega.\n  destruct n.\n  intros;simpl.\n  destruct l0;auto.\n  case Nat.eqb_spec.\n  intros.\n  rewrite e in *.\n  (** impossible cas l est ordonée donc par définition on utiliste \nle constructeur de Incr pour obtenir une contradiction *)\n  inversion H1.\n  omega.\n  auto.\n  simpl.\n  case Nat.eqb_spec.\n  auto.\n  intros;omega.\nQed.\n  \n(** ** PART II : Some complements about Coq arithmetic and lists *)\n\n(** *** An exact subtraction\n\n   No rounding at zero with this one, but rather an output\n   in [option nat]. Later, to prove things involving [sub_option],\n   simply do a [case sub_option_spec]. *)\n\nFixpoint sub_option n m :=\n  match n, m with\n  | _, 0 => Some n\n  | 0, _ => None\n  | S n, S m => sub_option n m\n  end.\n\nInductive SubOptionSpec (n m : nat) : option nat -> Prop :=\n | SubLe p : n = m + p -> SubOptionSpec n m (Some p)\n | SubLt : n < m -> SubOptionSpec n m None.\nHint Constructors SubOptionSpec.\n\n\nLemma ltsub n m : n < m -> sub_option n m = None.\nProof.\n  revert m.\n  ind n;intros.\n  case H;auto.\n  destruct m;simpl in *;auto.\n  omega.\nQed.\n\n\nLemma subSome p :sub_option p 0 = Some p.\nProof.\n  ind p.\nQed.\nLemma subSome0 m : sub_option m m = Some 0.\n  ind m.\nQed.  \n\n\n                 \nLemma gesub n p m : n = m + p -> sub_option n m = (Some p).\nProof.\n  revert p m.\n  ind n;destruct m;simpl in *;auto.\n  intros;omega.\nQed.\n\nLemma ltadd m n:   m < n -> exists p, n = m + p.\nProof.\n  intros.\n  ind H.\n  exists 1;auto.\n  destruct IHle.\n  exists (S x);omega.\nQed.\n\nLemma sub_option_spec n m : SubOptionSpec n m (sub_option n m).\nProof.\n  revert m. ind n; destruct m; auto.\n  destruct (IHn m); auto.\nQed.\n\n(** *** Injectivity of list concatenation *)\n\nLemma eq_length0_empty {A} (l : list A):\n  0 = length l -> [] = l.\nProof.\n  destruct l;auto.\n  discriminate.\nQed.\n  \nLemma app_inv {A} (u u' v v' : list A) :\n length u = length u' ->u ++ v = u' ++ v' -> u = u' /\\ v = v'.\nProof.\n  revert u u' v v'.\n  induction u; destruct u'; simpl; intros;auto.    \n  discriminate;auto.\n  discriminate;auto.\n  inversion H0.\n  inversion H.\n  edestruct IHu;eauto.\n  subst; auto.\nQed.\n\n(** *** Access to the n-th element of a list\n\n   This is a cleaner version of List.nth_error. *)\n\nFixpoint list_nth {A} (l:list A) i : option A :=\n  match i,l with\n    | 0,   x::_ => Some x\n    | S j, _::l => list_nth l j\n    | _, _ => None\n  end.\n\nLemma list_nth_app_l {A} (l l':list A)(n:nat) : n < length l ->\n  list_nth (l++l') n = list_nth l n.\nProof.\n  revert l l' n.\n  ind l;intros.\n  omega.\n  destruct n;simpl;auto.\nQed.\n\nLemma list_nth_app_r {A} (l l':list A)(n:nat) :\n  list_nth (l++l') (length l + n) = list_nth l' n.\nProof.\n  revert l l' n.\n  ind l.\nQed.\n\n\n\n(** ** PART III: Skew Lists *)\n\nSection SkewList.\nParameter A:Type.\n\n(** Skewlists are list of trees of elements.\n    We want here to store [2^d-1] elements per tree of depth [d],\n    so we put data at the nodes and not at the leaves.\n    The value at the root node is the head of the skewlist, then\n    comes the values in the left sub-tree, then the right sub-tree. *)\n\n(** Perfect binary trees parametrized by their depth. *)\n\nInductive tree : nat -> Type :=\n | Leaf : tree 0\n | Node : forall {d}, A -> tree d -> tree d -> tree (S d).\n\n(** A [dtree] is a pair of a depth and a tree of this depth. *)\n\nInductive dtree := Tree : forall {d}, tree d -> dtree.\n\n(** The type of skewlists *)\n\nDefinition skewlist := list dtree.\n\n(** The number of elements in a skewlist *)\n\nDefinition depth (t:dtree) := let (d,_) := t in d.\nDefinition skew_length l := sum_ones (map depth l).\n\n(** The invariant we impose on skewlists to keep a nice complexity: *)\n\nDefinition SkewList l := Skew (map depth l).\n\nHint Unfold SkewList.\n\n(** The empty skewlist *)\n\nDefinition empty : skewlist := nil.\n\nLemma empty_invariant : SkewList empty.\nProof.\n  auto.\nQed.\n\n(** *** Conversion from skewlist to regular list *)\n\nFixpoint tree_to_list {d} (t:tree d) :=\n  match t with\n  | Leaf => nil\n  | Node _ a tl tr => a :: tree_to_list tl ++ tree_to_list tr\n  end.\n\nFixpoint to_list l :=\n  match l with\n  | nil => nil\n  | Tree _ t :: l => tree_to_list t ++ to_list l\n  end.\n\n\n(** *** Properties of length and size of trees and skewlists *)\n\nFixpoint size {d} (t:tree d) :=\n  match t with\n  | Leaf => 0\n  | Node _ a tl tr => 1 + size tl + size tr\n  end.\n\nLemma size_ones n (t : tree n) : size t = ones n.\nProof.\n  ind t.\nQed.\n\nLemma length_tree_to_list d (t:tree d) :\n length (tree_to_list t) = size t.\nProof.\n  ind t;auto.\n  rewrite app_length;auto.\nQed.  \n\n\nLemma length_to_list l :\n length (to_list l) = skew_length l.\nProof.\n  ind l.\n  destruct a;simpl;auto.\n  rewrite app_length;rewrite IHl.\n  unfold skew_length;simpl;f_equal.\n  rewrite length_tree_to_list;rewrite size_ones;auto.\nQed.\n  \n(** *** A adhoc induction principle on two trees of same depth *)\n\n(** When you have two trees [(t1 t2 : tree n)], you cannot simply\n    do [induction t1; destruct t2], Coq will most certainly\n    complain about issues with dependent types. In this case,\n    you will have to use the [tree_ind2] principle defined below.\n    The details of how these things are built aren't important,\n    just check the type of the obtained [tree_ind2] and compare\n    it to the one of the automatically generated [tree_ind].\n    NB: this part is inspired by P. Boutillier's Vector library.\n*)\n\nDefinition case0 (t : tree 0) :\n  forall (P : tree 0 -> Prop), P Leaf -> P t :=\n  match t with\n  | Leaf => fun P H => H\n  | _ => tt\n  end.\n\nDefinition caseS {n} (t : tree (S n)) :\n  forall (P : tree (S n) -> Prop),\n  (forall x t1 t2, P (Node x t1 t2)) -> P t :=\n  match t with\n  | Node _ x t1 t2 => fun P H => H x t1 t2\n  | _ => tt\n  end.\n\nDefinition tree_ind2 (P : forall {n}, tree n -> tree n -> Prop)\n  (base : P Leaf Leaf)\n  (rec : forall {n x tl1 tr1 y tl2 tr2},\n    P tl1 tl2 -> P tr1 tr2 ->\n    P (Node x tl1 tr1) (Node y tl2 tr2)) :=\n  fix loop {n} (t1 : tree n) : forall t2 : tree n, P t1 t2 :=\n  match t1 with\n  | Leaf => fun t2 => case0 t2 _ base\n  | Node _ x1 tl1 tr1 => fun t2 =>\n    caseS t2 (P (Node x1 tl1 tr1))\n     (fun x2 tl2 tr2 => rec (loop tl1 tl2) (loop tr1 tr2))\n  end.\nCheck tree_ind2.\n\n(** *** Unicity of the skewlist representation *)\n\nLemma tree_unique n (t t' : tree n) :\n tree_to_list t = tree_to_list t' -> t = t'.\nProof.\n  induction n,t,t' using tree_ind2;auto.\n  simpl.\n  inv.\n  apply app_inv in H2.\n  destruct H2.\n  apply IHt'1 in H0.\n  apply IHt'2 in H1.\n  rewrite H0.\n  rewrite H1.\n  auto.\n  (** thanks to the unicity *)\n  rewrite !length_tree_to_list.\n  rewrite !size_ones.\n  auto.\nQed.\n\nLemma length_tolist l l':\n  to_list l = to_list l' -> length (to_list l) = length (to_list l').\nProof.\n  inv.\nQed.\n\nLemma equalsum  n l : S (ones (S n) + sum_ones (l)) =  S (sum_ones (S n ::l)).\nProof.\n  auto.\nQed.\n\n\nLemma sum_ones_bound_inv n l :\n  Skew (n::l) ->  S (sum_ones (S n::l)) > ones (S n).\nProof.\n  ind n.\nQed.\n\n\nLemma prof n (t t' : tree n) : t = t' -> Tree t = Tree t' .\nProof.\n  inv.\nQed.\n  \nLemma skewlist_unique l l' : SkewList l -> SkewList l' ->\n to_list l = to_list l' -> l = l'.\nProof.\n  revert l'. \n  unfold SkewList.\n  induction l;destruct l';auto.\n  intros.\n  inversion H0;subst;simpl;auto;destruct d;destruct t;simpl in *.\n  omega.\n  discriminate.\n  omega.\n  discriminate.\n  intros.\n  inversion H;subst;simpl;destruct a;destruct d;destruct t;\n  auto;simpl in *;try solve [omega | discriminate].\n  intros.\n  assert ( (to_list (a::l)) = (to_list (d::l')) );auto.\n  apply length_tolist in H1.\n  simpl in *.\n  destruct a;destruct d.\n  \n  rewrite !app_length in H1.\n  rewrite !length_to_list in H1.\n  unfold skew_length in H1.\n  rewrite !length_tree_to_list in H1.\n  rewrite !size_ones in  H1.\n  simpl in *.\n\n  apply (decomp_unique (d0 :: map depth l) (d :: map depth l') H H0) in H1.\n\n  inversion H1;subst;simpl;auto.\n  assert (Tree t=Tree t0).\n  apply prof.\n  simpl in *.\n  apply app_inv in H2.\n  destruct H2.\n \n  apply (tree_unique d (t) (t0) );auto.\n\n  rewrite !length_tree_to_list.\n  rewrite !size_ones.\n  auto.\n  f_equal.\n  auto.\n  apply IHl.\n  apply Skew_inv in H;auto.\n  apply Skew_inv in H0;auto.\n  \n  simpl in *.\n  apply app_inv in H2.\n  destruct H2.\n  auto.\n  rewrite !length_tree_to_list.\n  rewrite !size_ones.\n  auto.\nQed.\n\n  \n(** *** Coercion from [tree d] to [tree d'] when [d=d']. *)\n\nDefinition coerc {d d'} : tree d -> d = d' -> tree d'.\nProof.\n destruct 2.\n trivial.\nDefined.\n\nLemma coerc_to_list d d' (t:tree d) (e : d = d') :\n tree_to_list (coerc t e) = tree_to_list t.\nProof.\n now destruct e.\nQed.\n\n(** *** cons *)\n\n(** Insert an element into a skewlist.\n    Constant cost (when ignoring the cost of comparison). *)\n\nDefinition leaf := Tree Leaf.\n\nDefinition singleton x := Tree (Node x Leaf Leaf).\n\nDefinition cons x l :=\n  match l with\n  | Tree d1 t1 :: Tree d2 t2 :: l' =>\n    match eq_nat_dec d1 d2 with\n    | left E => Tree (Node x (coerc t1 E) t2) :: l'\n    | right _ => singleton x :: l\n    end\n  | _ => singleton x :: l\n  end.\n\nLemma cons_next x l : map depth (cons x l) = next (map depth l).\nProof.\n  ind l.\n  destruct a;simpl;auto.\n  destruct l;simpl;auto.\n  destruct d0;simpl;auto.\n  case (eq_nat_dec d d0);simpl in *;auto.\n  case (Nat.eqb_spec).\n  intros;subst;auto.\n  intros;omega;auto.\n  case (Nat.eqb_spec).\n  intros;omega.\n  auto.\nQed.\n\n\n  \nLemma cons_invariant x l : SkewList l -> SkewList (cons x l).\nProof.\n  unfold SkewList.\n  rewrite cons_next.\n  apply next_skew.\nQed.\n  \n  \nLemma cons_to_list x l : to_list (cons x l) = x :: to_list l.\nProof.\n  ind l.\n  destruct a;destruct l;simpl;auto.\n  destruct d0;simpl;auto.\n  case (eq_nat_dec d d0);auto.\n  intros;simpl.\n  rewrite coerc_to_list.\n  rewrite app_assoc;auto.\nQed.\n\n(** *** Conversion from a regular list to a skewlist\n\n    We simply iterate [cons]. The cost is hence linear. *)\n\nDefinition from_list (l:list A) : skewlist := List.fold_right cons nil l.\n\nLemma cons_from_list x l : from_list (x::l) = cons x (from_list l).\n  unfold from_list;simpl;auto.\nQed.\n\nLemma from_list_invariant l : SkewList (from_list l).\n  unfold SkewList.\n  ind l.\n  rewrite cons_next.\n  apply next_skew;auto.\nQed.\n  \nLemma to_from l : to_list (from_list l) = l.\nProof.\n  induction l;simpl;auto.\n  rewrite cons_to_list.\n  f_equal;auto.\nQed.\n\n\n    \nLemma unique_from_to l : SkewList l -> l = from_list (to_list l).\nProof.\n  intros.\n  apply skewlist_unique;simpl;auto.\n  apply from_list_invariant.\n  rewrite to_from;auto.\nQed.\n  \n\n\n\n(** *** Decons : head element and rest of a skewlist, if any\n\n    Constant cost. *)\n\nDefinition decons l :=\n match l with\n | Tree _ (Node 0 x _ _) :: l' => Some (x,l')\n | Tree _ (Node _ x tl tr) :: l' =>\n   Some (x, Tree tl :: Tree tr :: l')\n | _ => None\n end.\n\nLemma decons_prev l x l':\n decons l = Some (x,l') -> map depth l' = prev (map depth l).\nProof.\n  ind l;intros.\n  discriminate.\n  destruct a;simpl;auto.\n  destruct t;simpl;auto.\n  discriminate.\n  destruct d;injection H;intros;subst;auto.\nQed.\n  \n\nLemma decons_invariant x l l' :\n SkewList l -> decons l = Some (x,l') -> SkewList l'.\nProof.\n  intros.\n  apply decons_prev in H0.\n  unfold SkewList;rewrite H0.\n  apply prev_skew.\n  unfold SkewList in H;auto.\nQed.\n\n  \nLemma decons_none l : SkewList l -> (decons l = None <-> l = nil).\nProof.\n  intros;split;intros.\n  ind l.\n  destruct a;simpl;auto.\n  destruct t;simpl;auto.\n  unfold SkewList in *;simpl in *.\n  inversion H;omega.\n  destruct d;discriminate.\n  subst;auto.\nQed.\n\nLemma triv n (t1 t2 : tree n) : n=0 -> \n  tree_to_list t1 ++ tree_to_list t2 = [].\nProof.\n  induction n,t1,t2 using tree_ind2;auto.\n  simpl.\n  intros;omega.\nQed.\n  \nLemma decons_to_list x l l' :\n decons l = Some (x,l') -> to_list l = x :: to_list l'.\nProof.\n  ind l;intros.\n  discriminate.\n  destruct a;simpl;auto.\n  destruct t;simpl;auto.\n  discriminate.\n  destruct d;simpl;auto.\n  injection H;intros;subst.\n  f_equal;simpl in *.\n  rewrite triv;simpl;auto.\n  injection H;intros;subst.\n  f_equal;simpl in *.\n  rewrite app_assoc;reflexivity.\nQed.\n  \nLemma decons_cons x l : SkewList l -> decons (cons x l) = Some (x,l).\nProof.\n  intros;unfold SkewList in *.\n  ind l.\n  destruct a;simpl;auto.\n  destruct l;simpl;auto.\n  destruct d0;simpl;auto.\n  case (eq_nat_dec d d0);simpl in *.\n  inversion H;intros;subst.\n  case H2.\n  destruct d0;simpl;auto.\n  intros;omega.\n  intros;reflexivity.\nQed.\n \n  \nLemma cons_decons x l l' :\n SkewList l -> decons l = Some (x,l') -> cons x l' = l.\nProof.\n  intros;auto.\n  assert (SkewList l);auto.\n  assert (decons l = Some (x, l'));auto.\n  apply decons_invariant in H0;auto.\n  apply decons_to_list in H2.\n  rewrite <- cons_to_list in H2.\n  apply skewlist_unique;auto.\n  apply cons_invariant;auto.\nQed.\n\n(** *** Access to the n-th element of a skew list *)\n\n(** n-th element of the tree t *)\n\nFixpoint nth_tree {d} (t : tree d) n :=\n  match t with\n  | Leaf => None\n  | Node d x tl tr =>\n    match n with\n    | O => Some x\n    | S n' =>\n      match sub_option n' (ones d) with\n      | None => nth_tree tl n'\n      | Some n'' => nth_tree tr n''\n      end\n    end\n  end.\n\n(** n-th element of a skewlist l. *)\n\nFixpoint nth l n :=\n  match l with\n  | nil => None\n  | Tree d t :: l =>\n    match sub_option n (ones d) with\n    | None => nth_tree t n\n    | Some n' => nth l n'\n    end\n  end.\n\nLemma nth_tree_ok d (t : tree d) n :\n  nth_tree t n = list_nth (tree_to_list t) n.\nProof.\n  revert n.\n  ind t.\n  destruct n;simpl;auto.\n  destruct n;simpl;auto.\n  destruct (sub_option_spec n (ones d));subst.\n  rewrite (IHt2 p).\n  rewrite <- (size_ones d t1).\n  rewrite <- length_tree_to_list.\n  rewrite list_nth_app_r;auto.\n  rewrite list_nth_app_l;auto.\n  rewrite <- (size_ones d t1) in H.\n  rewrite <- length_tree_to_list in H;auto.\nQed.\n\n    \nLemma nth_ok l n : nth l n = list_nth (to_list l) n.\nProof.\n  revert n.\n  induction l.\n  destruct n;simpl;auto.\n  destruct a.\n  destruct t.\n  simpl.\n  intros.\n  case (sub_option_spec).\n  intros.\n  simpl in H.\n  rewrite H.\n  apply IHl.\n  omega.\n  simpl nth.\n  intros.\n  case (sub_option_spec).\n  intros.\n  assert (ones d + (ones d + 0) + 1 > 0).\n  auto.\n  case (zerop n) .\n  destruct n.\n  intros.\n  omega.\n  intros.\n  omega.\n  destruct n.\n  intros.\n  omega.\n  simpl.\n  rewrite <- plus_n_O in *.\n  intros.\n  rewrite <- (size_ones d t1) in H at 1.\n  rewrite <- (size_ones d t2) in H at 1.\n  rewrite <- length_tree_to_list in *.\n  rewrite <- length_tree_to_list in *.\n  assert (n =  length (tree_to_list t1) + length (tree_to_list t2)  + p) by omega.\n  rewrite <- app_length in H1.\n  rewrite H1.\n  rewrite list_nth_app_r.\n  auto.\n  intros.\n  destruct n.  \n  simpl.\n  auto.\n  case (sub_option_spec).\n  simpl.\n  rewrite list_nth_app_l.\n  intros.\n  rewrite <- (size_ones d t1) in *.\n  rewrite <- length_tree_to_list in *.\n  rewrite H0.\n  intros.\n  rewrite list_nth_app_r.\n  apply nth_tree_ok.\n  rewrite <- (size_ones d t1) in H at 1.\n  rewrite <- (size_ones d t2) in H at 1.\n  rewrite <- length_tree_to_list in *.\n  rewrite <- length_tree_to_list in *.\n  rewrite <- plus_n_O in *.\n  assert (n <  length (tree_to_list t1) + length (tree_to_list t2)  ) by omega.\n  rewrite <- app_length in H0.\n  auto.\n  intros.\n  simpl.\n  rewrite list_nth_app_l.\n  intros.\n  rewrite <- (size_ones d t1) in H at 1.\n  rewrite <- (size_ones d t2) in H at 1.\n  rewrite <- plus_n_O in *.\n  rewrite <- length_tree_to_list in H .\n  assert ( n < length (tree_to_list t1) + size t2 ) by omega.\n  rewrite list_nth_app_l.\n  apply nth_tree_ok.\n  rewrite <- (size_ones d t1) in H0 at 1.\n  rewrite <- length_tree_to_list in H0 .\n  auto.\n  rewrite <- (size_ones d t1) in H at 1.\n  rewrite <- (size_ones d t2) in H at 1.\n  rewrite <- plus_n_O in *.\n  rewrite <- !length_tree_to_list in H .\n  assert ( n < length (tree_to_list t1) +  length (tree_to_list t2) ) by omega.\n  rewrite <- app_length in H1.\n  auto.\nQed.\n\n\n(** In the \"real life\", all the arithmetical operations on the\n  sizes will be done on machine integers, and hence have a\n  constant cost (for instance [ones n = (1 << n) - 1]).\n  In this situation, [cons] and [decons] have really a constant\n  cost and [nth] has a logarithmic cost with respect to the\n  number of elements in the skew list.\n\n  In Coq, things are not so nice, since on [nat] all arithmetic\n  operations are at least linear. We could at least define\n  a notion of distance of elements in the skew list, and show\n  that this distance is at most logarithmic. (TODO)\n*)\n\n\n(** Possible extensions :\n  - a [set_nth] function, such that [set_nth l n x] creates a copy\n    of the skewlist [l] where the n-th element is now replaced by [x].\n\n  - a [drop] function, such that [drop k l] is the skewlist [l]\n    with its first [k] elements removed. This could be done by\n    repeating [k] times the [decons] function, but with a direct\n    definition we could obtain a better complexity (logarithmic\n    in the size of [l], when ignoring arithmetic ops).\n*)\n\nEnd SkewList.\n", "meta": {"author": "uzenat", "repo": "skewlist", "sha": "6318e7a717d2b479b09875792d7727c6d71bc090", "save_path": "github-repos/coq/uzenat-skewlist", "path": "github-repos/coq/uzenat-skewlist/skewlist-6318e7a717d2b479b09875792d7727c6d71bc090/Skew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7815310709233738}}
{"text": "Set Implicit Arguments.\nRequire Import List.\n\nPrint List. (* ooops this prints the whole module *)\nPrint list.\n(*\nInductive list (A : Type) : Type :=\n  | nil : list A \n  | cons : A -> list A -> list A\n*)\n\nCheck list_ind.\n(*\n\nforall (A : Type) (P : list A -> Prop),\n  P nil -> (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n  forall l : list A, P l\n*)\n\nDefinition first_two (A:Type)(l:list A): list A :=\n  match l with\n    | nil         => l\n    | cons a nil  => l\n    | a::b::ls    => a::b::nil\n  end.\n\nEval compute in first_two (2::3::4::5::nil).\nEval compute in first_two (2::7::nil).\nEval compute in first_two (6::nil).\nEval compute in first_two nil(A:=nat).\n\nFixpoint take (A:Type)(n:nat)(l:list A): list A :=\n  match n with\n    | 0         => nil\n    | S p       =>\n      match l with\n        | nil   => nil\n        | l::ls => l::take p ls\n      end\n  end.\n\nEval compute in take 3 (0::1::2::3::4::5::6::nil).\nEval compute in take 10 (0::1::2::3::4::5::6::nil).\nEval compute in take 2 (0::1::2::3::4::5::6::nil).\nEval compute in take 1 (0::1::2::3::4::5::6::nil).\nEval compute in take 0 (0::1::2::3::4::5::6::nil).\n\nFixpoint map (A:Type)(B:Type)(f:A->B)(l:list A): list B :=\n  match l with\n    | nil     => nil\n    | l::ls   => (f l)::map f ls\n  end.\n\nEval compute in map (fun x => 2*x) (0::1::2::3::4::5::6::nil).\n\nFixpoint foldl (A:Type)(B:Type)(op : B -> A -> B)(init : B)(xs: list A) : B :=\n  match xs with\n    | nil     => init\n    | (y::ys) => foldl op (op init y) ys\n  end.\n\nDefinition  sum : list nat -> nat := foldl plus 0.\n\nEval compute in sum (0::1::2::3::4::5::6::nil).\n\nFixpoint n_to_1 (n:nat) : list nat :=\n  match n with \n    | 0       => nil\n    | S p     => (S p)::n_to_1 p\n  end.\n\nEval compute in n_to_1 10.\n\nDefinition reverse (A:Type) : list A -> list A := foldl (fun rs r => r::rs) nil.\n\nEval compute in reverse (0::1::2::3::4::5::6::nil).\n\nDefinition rangefrom1 (n:nat) : list nat := reverse (n_to_1 n).\n\nEval compute in rangefrom1 0.\nEval compute in rangefrom1 10.\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/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8976952866333484, "lm_q1q2_score": 0.7815310583781014}}
{"text": "Require Export Coq.Logic.Classical.\nRequire Export Coq.Sets.Constructive_sets.\nRequire Export Coq.Sets.Ensembles.\nRequire Export Coq.Sets.Finite_sets.\nRequire Export Coq.Sets.Finite_sets_facts.\nRequire Export Coq.Sets.Powerset.\nRequire Export Coq.Setoids.Setoid.\nSection Matroids.\n  Parameter U : Type.\n  Parameter E : Ensemble U.      \n  (* A1: E is a finite set over universe U *)\n  Parameter finite : Finite U E.\n\n  (* I1: The empty set is independent *)\n  Definition I1 (I : Ensemble (Ensemble U)) :=\n    I (Empty_set U).\n    (* I2: Subsets of independent sets are independent *)\n  Definition I2 (I : Ensemble (Ensemble U)) :=\n    forall (A B : (Ensemble U)),\n      I B /\\ (Included U A B) -> I A.\n  (* I3: If |A| < |B|, A can be extended to a larger independent set by adding an element from B *)\n  Definition I3 (I : Ensemble (Ensemble U)) := \n    forall (A B : (Ensemble U)),\n    forall (m n : nat),\n      (cardinal U A m ) /\\\n      (cardinal U B n) /\\\n      m < n ->\n        exists x : U, B x /\\ I (Add U A x).\n  \n  Record Matroid : Type := {\n    I : Ensemble (Ensemble U);\n    M_I1 : I1 I;\n    M_I2 : I2 I;\n    M_I3 : I3 I\n  }.\n\n  Definition Circuits (M : Matroid) : Ensemble (Ensemble U) :=\n    (fun S : Ensemble U =>\n       (~ I M S) /\\\n       (forall T : Ensemble U,\n          Strict_Included U T S -> I M T)).\n\n  (* C1: The empty set is not a circuit *)\n  Definition C1 : Ensemble (Ensemble U) -> Prop :=\n    (fun C => ~ C (Empty_set U)).\n  (* C2: No distinct circuits are subsets *)\n  Definition C2 : Ensemble (Ensemble U) -> Prop :=\n    (fun C => \n       forall (A B : Ensemble U),\n         (C A) /\\\n         (C B) /\\\n         Included U A B ->\n           Same_set U A B).\n  (* C3: Merging distinct circuits and removing a common element gives a superset of a circuit *)\n  Definition C3 : Ensemble (Ensemble U) -> Prop :=\n    (fun C =>\n       forall (A B : Ensemble U),\n       forall (e : U),\n         (C A) /\\\n         (C B) /\\\n         (~ Same_set U A B) /\\\n         (In U (Intersection U A B) e) ->\n         exists C3 : Ensemble U,\n           (C C3) /\\\n           Included U C3 (Setminus U (Union U A B) (Singleton U e))).\n  Lemma Circuits_Satisfy_C1 : forall M : Matroid, C1 (Circuits M).\n  Proof.\n    unfold C1.\n    intros.\n    intro.\n    unfold Circuits in H.\n    destruct H.\n    contradict H.\n    apply M_I1.\n  Qed.\n  Lemma Circuits_Satisfy_C2 : forall M : Matroid, C2 (Circuits M).\n  Proof.\n    unfold C2.\n    intros.\n    destruct H as [A_circ [B_circ A_sub_B]].\n    assert (G: A = B \\/ A <> B). apply classic.\n    destruct G.\n    apply (Extension U); assumption.\n    unfold Circuits in A_circ.\n    unfold Circuits in B_circ.\n    unfold Strict_Included in A_circ.\n    unfold Strict_Included in B_circ.\n    destruct A_circ as [A_not_I A_prop_subs_I].\n    destruct B_circ as [B_not_I B_prop_subs_I].\n    assert (G: Included U A B /\\ A <> B -> I M A).\n    apply B_prop_subs_I.\n    contradict A_not_I.\n    auto.\n  Qed.\n  Lemma Sets_Included_In_Themselves :\n    forall A : Ensemble U,\n      Included U A A.\n  Proof.\n    intros.\n    assert (A = A). tauto.\n    apply Extension in H.\n    unfold Same_set in H.\n    destruct H.\n    assumption.\n  Qed.\n\n  Definition Base (M : Matroid) (S : Ensemble U) :=\n    I M S /\\ forall T : Ensemble U, Strict_Included U S T -> ~ I M S.\n  Theorem Bases_Have_Equal_Size (M : Matroid) (A B : Ensemble U) :\n    (Base M A) /\\\n    (Base M B) ->\n    forall (m n : nat),\n      (cardinal U A m) <-> (cardinal U A n).\n  Proof.\n    admit.\n  Qed.\n  Definition Maximal (S : Ensemble U) (P : Ensemble U -> Prop) :=\n    forall (V : Ensemble U),\n      Strict_Included U S V -> ~ P V.\n  Definition Maximal_included (P : Ensemble U -> Prop) (E : Ensemble U) (S : Ensemble U) :=\n    P S /\\ Included U S E.\n  Lemma Empty_set_can_be_extended_to_a_maximal_set (P : Ensemble U -> Prop) :\n    P (Empty_set U) ->\n    forall E : Ensemble U,\n      Finite U E -> exists T : Ensemble U, Maximal T (Maximal_included P E).\n  Proof.\n(*    assert (E = Empty_set U \\/ E <> Empty_set U). apply classic. *)\n    intro.\n    apply Generalized_induction_on_finite_sets.\n    intros.\n(*    set (prop (S : Ensemble U) := P S /\\ Included U S E).*)\n    set (prop (T : Ensemble U) := Maximal T (Maximal_included P X)).\n    set (term := exists T : Ensemble U, prop T).\n    assert (term \\/ ~ term). apply classic.\n    destruct H2.\n    assumption.\n    unfold term in H2.\n    assert (forall T : Ensemble U, ~ prop T). firstorder. clear H2.\n(*    unfold prop in H3.\n    unfold Maximal in H3.\n    unfold Maximal_included in H3.\n    unfold Maximal in H1.*)\n    unfold prop. unfold Maximal. unfold Maximal_included.\n    assert (prop (Empty_set U)).\n    firstorder.\n    assert (~ prop (Empty_set U)).\n    apply H3.\n    contradiction.\n  Qed.\n  Lemma Sets_Include_A_Maximal_Independent_Set (M : Matroid) (S : Ensemble U) :\n    exists T : Ensemble U,\n      Included U T S /\\\n      I M T /\\\n  Proof.\n    intros.\n    apply Generalized_induction_on_finite_sets.\n    intros.\n    destruct (H0 (Empty_set (Ensemble U))).\n    firstorder using M_I1.\n    assert (X (Empty_set U)).\n    apply M_I1.\n    Print ex.\n    destruct (H0 X).\n    \n   Qed.\n  Lemma Independent_iff_No_Circuit_Included (M : Matroid) (S : Ensemble U) :\n    (I M S) <-> forall T : Ensemble U,\n                  Included U T S ->\n                    ~ (Circuits M T).\n  Proof.\n    split.\n    (* -> *)\n    intro.\n    unfold Circuits.\n    intros.\n    contradict H.\n    destruct H as [G H].\n    assert (T = S \\/ T <> S). apply classic.\n    destruct H1.\n    rewrite H1 in G. assumption.\n    firstorder using M_I2.\n    (* <- *)\n    intro.\n    unfold Circuits in H.\n    set (term :=  ~ (~ I M S /\\ (forall T0 : Ensemble U, Strict_Included U T0 S -> I M T0))).\n    assert term. unfold term. apply (H S). apply Sets_Included_In_Themselves.\n    unfold term in H0.\n    apply not_and_or in H0.\n    destruct H0.\n    apply NNPP in H0. assumption.\n    apply not_all_ex_not in H0.\n    destruct H0.\n    assert (Strict_Included U x S). apply not_imply_elim with (I M x). assumption.\n    assert (~ I M x). apply not_imply_elim2 with (Strict_Included U x S). assumption.\n    assert term. unfold term. apply (H S). apply Sets_Included_In_Themselves.\n    unfold term in H3. apply not_and_or in H3. destruct H3.\n    apply NNPP in H3. assumption.\n    \n    contradict H0.\n    intro.\n    destruct (H S). \n    destruct (H S). \n    assert \n    contradict H.\n    \n    apply not_and_or in H.\n    destruct H.\n    apply NNPP; assumption.\n    apply not_all_ex_not in H.\n    destruct H.\n    \n    assert (I M S \\/ (forall T : Ensemble U, Strict_Included U T S -> I M T)).\n    left; assumption.\n    apply not_and_or in H0.\n  Qed.\n  Lemma Circuits_Satisfy_C3 : forall M : Matroid, C3 (Circuits M).\n  Proof.\n    unfold C3.\n    intros.\n    (* target should contain a circuit *)\n    set (target := Setminus U (Union U A B) (Singleton U e)).\n    destruct H as [A_circ [B_circ [A_neq_B e_in_intersect]]].\n    apply NNPP.\n    intro.\n    \n    assert (G: forall C3 : Ensemble U,\n                 ~(Circuits M C3 /\\\n                   Included U C3 target)).\n    apply not_ex_all_not. apply H. clear H.\n    assert (I M target).\n    assert (H: ~ (Circuits M target /\\ Included U target target)).\n    apply G.\n    apply not_and_or in H.\n    destruct H.\n    unfold Circuits in H.\n    \n\n    apply Sets_Included_In_Themselves.\n    unfold Included.\n    \n    assert (H: forall C3 : Ensemble U,\n                 (~ Circuits M C3) \\/\n                 (Included U C3 (Setminus U (Union U A B) (Singleton U e)))).\n    intro. apply not_or_and.\n    destruct (G A).\n    split.\n    assumption.\n\n    contradict A_neq_B.\n    \n    let g := (exists (O : Ensemble U),\n               (Circuits M O) /\\\n               (Included U O (Setminus U (Union U A B) (Singleton U e))))\n    in assert (G: g \\/ ~g). apply classic.\n\n    contradict.\n   Theorem Circuits_Satisfy_C_Axioms : forall M : Matroid,\n    let cs := Circuits M\n    in (C1 cs /\\ C2 cs /\\ C3 cs).\n\n  Proof.\n    intro.\n    intro.\n    split.\n    (* C2 *)\n    split.\n    unfold C2.\n    intros.\n    destruct H.\n    destruct H0.\n    unfold Same_set.\n    split.\n    assumption.\n    assert \n  Qed.\n  Record Matroid_Circuit : Type := {\n    C : Ensemble (Ensemble U);\n    M_C1 : C1 C;\n    M_C2 : C2 C;\n    M_C3 : C3 C\n}.\n\n", "meta": {"author": "MichaelBurge", "repo": "matroids", "sha": "a9e42e2f93af300caf408ad9b25712431a2f79fe", "save_path": "github-repos/coq/MichaelBurge-matroids", "path": "github-repos/coq/MichaelBurge-matroids/matroids-a9e42e2f93af300caf408ad9b25712431a2f79fe/Matroids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7814666149770003}}
{"text": "Require Import ZArith.\nRequire Import Omega.\n\nOpen Scope Z_scope.\n\nTheorem omega_example1: \n  forall x y z t:Z, x<=y<=z /\\ z<=t<=x -> x = t.\nProof.\n  intros x y z t H. omega. (* omega is for Z, use fourier for R *)\nQed.\n\nDefinition square (z:Z) := z*z.\n\n(* omega needs linear goals and context *)\n(* but getting away with it here *)\nTheorem omega_example2:\n  forall x y:Z, \n  0 <= square x -> 3*square x <= 2*y -> square x <= y.\nProof.\n  intros x y H H'. omega.\nQed.\n\nTheorem omega_example3:\n  forall x y:Z,\n  0 <= x*x ->  3*(x*x) <= 2*y -> x*x <= y.\nProof.\n  intros x y H H'. omega.\nQed.\n\n(* omega cannot convert this into linear problem *)\n(* it needs to apply associativity of mult which it *)\n(* is not programmed to do *)\n\nTheorem omega_example4:\n  forall x y:Z,\n  0 <= x*x -> (3*x)*x <= 2*y -> x*x <= y.\nProof.\n  intros x y H H'. (* omega failing here *)\nAbort.\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/omega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7814310934726253}}
{"text": "Require Import List.\nRequire Import BinPos.\nRequire Import Bool.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Sumbool.\nRequire Import Basics.\nRequire Import sflib.\nRequire Import Omega.\nRequire Import Sorting.Permutation.\nRequire Import Lia.\n\n(* Some helpful lemmas regarding List *)\n\n(* If List.length l = 1, l = h::nil. *)\nLemma list_len1:\n  forall {X:Type} (l:list X)\n         (H:List.length l = 1),\n    exists h, l = h::nil.\nProof.\n  intros.\n  destruct l.\n  - simpl in H. inversion H.\n  - destruct l.\n    + eexists. reflexivity.\n    + simpl in H. inversion H.\nQed.\n\n(* If List.length l = 2, l = h1::h2::nil. *)\nLemma list_len2:\n  forall {X:Type} (l:list X)\n         (H:List.length l = 2),\n    exists h1 h2, l = h1::h2::nil.\nProof.\n  intros.\n  destruct l.\n  - simpl in H. inversion H.\n  - destruct l.\n    + simpl in H. inversion H.\n    + destruct l.\n      * eexists. eexists. reflexivity.\n      * simpl in H. inversion H.\nQed.\n\nLemma firstn_app_decompose {X:Type}:\n  forall (l l1 l2:list X) n\n         (HL:l = l1 ++ l2)\n         (HLEN:List.length l1 = n),\n    firstn n l = l1.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent n.\n  induction l1.\n  - simpl. intros. rewrite <- HLEN. reflexivity.\n  - simpl. intros.\n    destruct n.\n    + inversion HLEN.\n    + inversion HLEN.\n      destruct l.\n      inversion HL.\n      inversion HL.\n      simpl. rewrite H0. rewrite IHl1. reflexivity.\n      congruence. reflexivity.\nQed.\n\nLemma firstn_In {X:Type}:\n  forall (l:list X) n x l'\n         (HF:List.firstn n l = l')\n         (HIN:List.In x l'),\n    List.In x l.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent l'.\n  induction n.\n  { intros. simpl in HF. inv HF. inv HIN. }\n  { simpl. intros.\n    destruct l. inv HF. inv HIN.\n    destruct l'; try congruence.\n    inv HF. inv HIN. left. ss.\n    right. eapply IHn. eassumption. ss.\n  }\nQed.\n\nLemma skipn_In {X:Type}:\n  forall (l:list X) n x l'\n         (HF:List.skipn n l = l')\n         (HIN:List.In x l'),\n    List.In x l.\nProof.\n  intros.\n  generalize dependent l'.\n  generalize dependent l.\n  induction n.\n  { intros. simpl in HF. congruence. }\n  { simpl. intros.\n    destruct l. congruence.\n    eapply IHn in HF. right. ss. ss.\n  }\nQed.\n\nLemma skipn_length {X:Type}:\n  forall n (l:list X),\n    List.length (List.skipn n l) = (List.length l) - n.\nProof.\n  intro.\n  induction n.\n  { simpl. intros. omega. }\n  { intros.\n    destruct l.\n    simpl. omega.\n    simpl. rewrite IHn. reflexivity.\n  }\nQed.    \n\nLemma skipn_app_decompose {X:Type}:\n  forall (l l1 l2:list X) n\n         (HL:l = l1 ++ l2)\n         (HLEN:List.length l1 = n),\n    skipn n l = l2.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent n.\n  induction l1.\n  - simpl. intros. rewrite HL. rewrite <- HLEN. reflexivity.\n  - simpl. intros.\n    destruct n.\n    + inversion HLEN.\n    + inversion HLEN.\n      destruct l.\n      inversion HL.\n      inversion HL.\n      simpl. rewrite H0. rewrite IHl1. reflexivity.\n      congruence. reflexivity.\nQed.\n\nLemma skipn_all {X:Type}:\n  forall (l:list X) n\n         (HLEN:List.length l <= n),\n    skipn n l = nil.\nProof.\n  intros.\n  generalize dependent n.\n  induction l.\n  - simpl. intros. destruct n; reflexivity.\n  - simpl. intros.\n    destruct n.\n    + inversion HLEN.\n    + simpl. apply IHl.\n      apply le_S_n. assumption.\nQed.\n\nLemma app_decompose {X:Type} (n:nat):\n  forall (l:list X)\n         (HLEN:n <= List.length l),\n    exists l1 l2, (l = l1 ++ l2 /\\ List.length l1 = n).\nProof.\n  intros.\n  generalize dependent n.\n  induction l.\n  - simpl. intros. inversion HLEN.\n    exists nil. exists nil. split; reflexivity.\n  - simpl. intros.\n    destruct n.\n    + exists nil. exists (a::l). split; reflexivity.\n    + apply le_S_n in HLEN.\n      apply IHl in HLEN.\n      destruct HLEN. destruct H.\n      destruct H.\n      exists (a::x). exists x0.\n      rewrite H. split. reflexivity. simpl. congruence.\nQed.\n\nLemma firstn_firstn_skipn {X:Type}:\n  forall n1 n2 (l:list X),\n    firstn n1 l ++ firstn n2 (skipn n1 l) = firstn (n1+n2) l.\nProof.\n  intros.\n  assert (HD := app_decompose n1 l).\n  assert (HDEC := Compare_dec.le_gt_dec n1 (List.length l)).\n  destruct HDEC as [HDEC | HDEC].\n  - apply HD in HDEC.\n    destruct HDEC as [l1 [l2 [HDEC1 HDEC2]]].\n    rewrite firstn_app_decompose with (l0 := l) (l3 := l1) (l4 := l2).\n    rewrite <- HDEC2.\n    rewrite HDEC1.\n    rewrite firstn_app_2.\n    rewrite skipn_app_decompose with (l3 := l1) (l4 := l2).\n    reflexivity. reflexivity. reflexivity. congruence. congruence.\n  - assert (length l <= n1).\n    { apply Gt.gt_le_S in HDEC.\n      apply PeanoNat.Nat.le_trans with (m := S (length l)).\n      auto. assumption. }\n    rewrite firstn_all2.\n    rewrite firstn_all2 with (n:= n1+n2).\n    rewrite skipn_all. rewrite firstn_nil.\n    rewrite app_nil_r. reflexivity.\n    assumption.\n    apply Gt.gt_le_S in HDEC.\n    apply PeanoNat.Nat.le_trans with (m := n1).\n    apply PeanoNat.Nat.le_trans with (m := S (length l)).\n    auto. assumption. apply PeanoNat.Nat.le_add_r.\n    assumption.\nQed.\n\n\n(* If the result of List.combine is nil, and\n   their length is the same. input is both nil *)\nLemma combine_length_nil:\n  forall {X Y:Type} (l1: list X) (l2:list Y)\n         (HLEN:List.length l1 = List.length l2)\n         (HNIL:List.combine l1 l2 = nil),\n    l1 = nil /\\ l2 = nil.\nProof.\n  intros.\n  destruct l1; destruct l2.\n  - split; reflexivity.\n  - simpl in HLEN. inversion HLEN.\n  - simpl in HLEN. inversion HLEN.\n  - simpl in HNIL. inversion HNIL.\nQed.\n\nLemma combine_length_some:\n  forall {X Y:Type} (l1: list X) (l2:list Y) a t\n         (HLEN:List.length l1 = List.length l2)\n         (HSOME:List.combine l1 l2 = a::t),\n    l1 = (a.(fst))::((List.split t).(fst))  /\\\n    l2 = (a.(snd))::((List.split t).(snd)).\nProof.\n  intros.\n  assert (split (combine l1 l2) = (l1, l2)).\n  { apply combine_split. assumption. }\n  destruct l1; destruct l2.\n  - simpl in HSOME; inversion HSOME. \n  - simpl in HLEN; inversion HLEN.\n  - simpl in HLEN; inversion HLEN.\n  - simpl in HSOME.\n    inversion HSOME.\n    simpl in H.\n    remember (split (combine l1 l2)) as q.\n    destruct q.\n    inversion H.\n    simpl.\n    split; reflexivity.\nQed.\n\n(* l = combine (fst (split l), snd (split l)). *)\nLemma combine_fst_snd_split:\n  forall {X Y:Type} (l:list (X*Y)),\n    l = List.combine (fst (List.split l)) (snd (List.split l)).\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - destruct a.\n    remember (split l) as p.\n    simpl.\n    rewrite <- Heqp.\n    destruct p.\n    simpl. rewrite IHl.\n    reflexivity.\nQed.\n\nLemma combine_map_In:\n  forall {X Y:Type} (ly:list Y) (f:Y -> X) (x:X) (y:Y) (lx:list X)\n         (HX:x = f y)\n         (HLX:lx = List.map f ly)\n         (HIN:List.In y ly),\n  List.In (x, y) (List.combine lx ly).\nProof.\n  induction ly.\n  - intros. simpl in HIN. inversion HIN.\n  - simpl. intros.\n    destruct lx; inversion HLX.\n    simpl.\n    rewrite HX.\n    destruct HIN.\n    + left. congruence.\n    + right. apply IHly with (f := f).\n      reflexivity. reflexivity. assumption.\nQed.\n\nLemma map_In:\n  forall {X Y:Type} (l:list X) (f:X -> Y) (y:Y) x\n         (HIN:List.In x l)\n         (HY:y = f x),\n    List.In y (List.map f l).\nProof.\n  induction l.\n  intros. inv HIN.\n  intros. simpl in HIN.\n  destruct HIN. simpl. left.  congruence.\n  simpl. right. eapply IHl. eassumption. assumption.\nQed.\n\nLemma In_pair_split_snd {X Y:Type}:\n  forall (x:X) (y:Y) l (HIN:List.In (x, y) l),\n    List.In y (snd (List.split l)).\nProof.\n  induction l. eauto. intros.\n  simpl in *. destruct HIN.\n  { rewrite H. destruct (List.split l).\n    simpl. left. reflexivity. }\n  { destruct a. apply IHl in H. destruct (List.split l).\n    simpl. right. eauto. }\nQed.\nLemma In_split2 {X:Type}:\n  forall x1 x2 (HDIFF:x1 <> x2) (l:list X)\n         (HIN1:List.In x1 l)\n         (HIN2:List.In x2 l),\n    exists l1 l2 l3, l = l1++x1::l2++x2::l3 \\/\n                     l = l1++x2::l2++x1::l3.\nProof.\n  intros.\n  apply List.in_split in HIN1.\n  destruct HIN1 as [l1 [l2 HIN1]].\n  rewrite HIN1 in HIN2.\n  apply List.in_app_or in HIN2.\n  destruct HIN2.\n  { apply List.in_split in H.\n    destruct H as [l3 [l4 H]].\n    rewrite H in HIN1.\n    exists l3, l4, l2.\n    right. rewrite <- List.app_assoc in HIN1.\n    rewrite <- List.app_comm_cons in HIN1.\n    assumption. }\n  { simpl in H.\n    destruct H. congruence.\n    apply List.in_split in H.\n    destruct H as [l3 [l4 H]].\n    rewrite H in HIN1.\n    exists l1, l3, l4.\n    left. assumption.\n  }\nQed.\n\nLemma In_swap {X:Type}:\n  forall (n m x:X) l\n         (HIN:List.In x (n::m::l)),\n    List.In x (m::n::l).\nProof.\n  intros.\n  inv HIN. right. left. ss.\n  inv H. left. ss.\n  right. right. ss.\nQed.\n\n(* Filtered list is shorter than the original list. *)\nLemma filter_length:\n  forall {X:Type} (l:list X) f,\n    List.length (List.filter f l) <= List.length l.\nProof.\n  intros.\n  induction l.\n  - simpl. auto.\n  - simpl.\n    destruct (f a).\n    + simpl.\n      apply Le.le_n_S.\n      assumption.\n    + apply le_S.\n      assumption.\nQed.\n\nLemma filter_true {X:Type}:\n  forall (l : list X),\n    List.filter (fun (x:X) => true) l = l.\nProof.\n  induction l.\n  { reflexivity. }\n  { simpl. rewrite IHl. reflexivity. }\nQed.\n\nLemma filter_reorder {X:Type}:\n  forall f1 f2 (l:list X),\n    List.filter f1 (List.filter f2 l) =\n    List.filter f2 (List.filter f1 l).\nProof.\n  induction l. reflexivity.\n  simpl. des_ifs; simpl; des_ifs; congruence.\nQed.\n\nLemma filter_map_combine {X Y:Type}:\n  forall (l1 l2:list X) (l3 l4:list Y) (ff:X -> bool) (fm:X -> Y)\n         (HFILTER:l2 = List.filter ff l1)\n         (HMAP1:l3 = List.map fm l1)\n         (HMAP2:l4 = List.map fm l2),\n    List.combine l4 l2 = List.filter (fun itm => ff itm.(snd)) (List.combine l3 l1).\nProof.\n  induction l1.\n  { simpl. intros. subst l2. subst l3. simpl in HMAP2.\n    subst l4. reflexivity. }\n  { simpl. intros.\n    destruct (ff a) eqn:HCOND.\n    { destruct l2. inv HFILTER.\n      simpl in HMAP2.\n      destruct l3; destruct l4; try ss.\n      inv HFILTER. inv HMAP1. inv HMAP2.\n      rewrite HCOND.\n      erewrite IHl1; reflexivity.\n    }\n    { destruct l3; ss.\n      inv HMAP1. rewrite HCOND.\n      erewrite IHl1; reflexivity.\n    }\n  }\nQed.\n\nLemma split_filter_combine_map2_snd {X Y:Type}:\n  forall (l2 l4:list Y) (l1 l3:list X) (f:(X * Y) -> bool) (g:Y -> X)\n         (HS: (l3, l4) = List.split (List.filter f (List.combine l1 l2)))\n         (HMAP: l1 = List.map g l2),\n    l4 = List.filter (fun x => f (g x, x)) l2.\nProof.\n  induction l2.\n  { simpl in *. intros. subst l1. simpl in HS. congruence. }\n  { simpl in *.\n    intros.\n    destruct l1; try congruence.\n    simpl in HS.\n    inv HMAP.\n    destruct (f (g a, a)) eqn:HCOND.\n    { simpl in HS.\n      remember (List.split (List.filter f (List.combine (List.map g l2) l2))) as hs.\n      destruct hs.\n      inv HS.\n      erewrite <- IHl2. reflexivity.  eassumption. reflexivity.\n    }\n    { simpl in HS.\n      eapply IHl2 in HS.\n      eassumption.\n      reflexivity.\n    }\n  }\nQed.\n\nLemma app_equal {X:Type}:\n  forall (l1' l2' l1 l2:list X) (x x':X)\n         (HNOTIN1:~List.In x' l1)\n         (HNOTIN1':~List.In x l1')\n         (HEQ:l1' ++ x' :: l2' = l1 ++ x :: l2),\n    l1 = l1' /\\ l2 = l2' /\\ x' = x.\nProof.\n  intros.\n  generalize dependent l1'.\n  induction l1.\n  - intros. simpl in HEQ.\n    destruct l1'. simpl in HEQ.\n    inversion HEQ. split. reflexivity. split; congruence.\n    simpl in HEQ. inversion HEQ. rewrite H0 in HNOTIN1'.\n    exfalso. apply HNOTIN1'. constructor.\n    reflexivity.\n  - simpl. intros.\n    destruct l1'.\n    + simpl in HEQ. inversion HEQ. rewrite H0 in HNOTIN1.\n      exfalso. apply HNOTIN1. constructor. reflexivity.\n    + simpl in HEQ.\n      inversion HEQ. rewrite H0 in *. clear H0.\n      assert (l1 = l1' /\\ l2 = l2' /\\ x' = x).\n      { apply IHl1. simpl in HNOTIN1.\n        apply Decidable.not_or in HNOTIN1. destruct HNOTIN1. assumption.\n        simpl in HNOTIN1'. apply Decidable.not_or in HNOTIN1'.\n        destruct HNOTIN1'. assumption.\n        assumption. }\n      destruct H. destruct H0.\n      split. congruence. split; congruence.\nQed.\n\n(* the result of List.filter satisfies forallb. *)\nLemma filter_forallb: forall {X:Type} (l:list X) f,\n    List.forallb f (List.filter f l) = true.\nProof.\n  intros.\n  induction l. reflexivity. simpl.\n  destruct (f a) eqn:H. simpl. rewrite H. rewrite IHl. auto.\n  assumption.\nQed.\n\nLemma filter_app {X:Type}:\n  forall (l1 l2:list X) (f:X -> bool),\n    List.filter f (l1++l2) = (List.filter f l1) ++ (List.filter f l2).\nProof.\n  intros.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. destruct (f a). rewrite IHl1. reflexivity.\n    assumption.\nQed.\n\nLemma forallb_map:\n  forall {X Y:Type} (l: list X) (l':list Y)\n         (f:X -> Y) (g:Y -> bool) (h:X -> bool) b\n         (HMAP:l' = List.map f l)\n         (HFORALLB:forallb g l' = b)\n         (HEQ:forall x, (compose g f) x = h x),\n    forallb h l = b.\nProof.\n  intros.\n  generalize dependent l'.\n  induction l.\n  - simpl. intros. rewrite HMAP in *. simpl in HFORALLB. congruence.\n  - simpl. intros. rewrite HMAP in HFORALLB.\n    simpl in HFORALLB.\n    destruct l'. inversion HMAP.\n    inversion HMAP.\n    unfold compose in *.\n    destruct (g (f a)) eqn:HGF.\n    + simpl. erewrite IHl. rewrite <- HEQ. rewrite HGF. reflexivity. eassumption.\n      simpl in HFORALLB. rewrite H1. assumption.\n    + simpl in HFORALLB. simpl. rewrite <- HEQ. rewrite HGF. simpl. assumption.\nQed.\n\nLemma Forall2_samelist {X:Type}:\n  forall (l:list X) (f:X -> X -> Prop)\n         (HF:forall X, f X X),\n    List.Forall2 f l l.\nProof.\n  induction l.\n  { intros. constructor. }\n  { intros.\n    constructor. apply HF. eapply IHl.\n    assumption.\n  }\nQed.\n\nLemma Forall2_implies {X Y:Type}:\n  forall (l1:list X) (l2:list Y) (f g:X -> Y -> Prop)\n         (HFORALL2:List.Forall2 f l1 l2)\n         (HIMPLIES:forall x y, f x y -> g x y),\n    List.Forall2 g l1 l2.\nProof.\n  intros.\n  induction HFORALL2.\n  { constructor. }\n  { constructor. apply HIMPLIES. assumption.\n    assumption. }\nQed.\n\nLemma Forall2_trans {X:Type}:\n  forall (l1 l2 l3:list X)\n         (f:X -> X -> Prop)\n         (HTRANS:forall x y z, f x y -> f y z -> f x z)\n         (HFORALL1:List.Forall2 f l1 l2)\n         (HFORALL2:List.Forall2 f l2 l3),\n    List.Forall2 f l1 l3.\nProof.\n  intros.\n  generalize dependent l3.\n  induction HFORALL1.\n  { intros. destruct l3. constructor.\n    inv HFORALL2. }\n  { intros. destruct l3. inv HFORALL2.\n    inv HFORALL2.\n    constructor. eapply HTRANS. eassumption. ss.\n    eapply IHHFORALL1. assumption.\n  }\nQed.\n\nLemma Forall_app {X:Type}:\n  forall (l1 l2:list X) (f:X -> Prop)\n         (HF:Forall f (l1++l2)),\n    Forall f l1 /\\ Forall f l2.\nProof.\n  intros.\n  induction l1.\n  simpl in HF. split. ss. ss.\n  simpl in HF. inv HF. split. constructor. ss.\n  apply IHl1 in H2. inv H2. ss.\n  apply IHl1 in H2. inv H2. ss.\nQed.\n\nLemma Forall_app2 {X:Type}:\n  forall (l1 l2:list X) (f:X -> Prop)\n         (HF1:Forall f l1)\n         (HF2:Forall f l2),\n    Forall f (l1 ++ l2).\nProof.\n  intros.\n  induction l1.\n  simpl. ss.\n  inv HF1. apply IHl1 in H2. simpl. constructor.\n  ss. ss.\nQed.\n\nLemma Forall_and {X:Type}:\n  forall (l:list X) (f g:X -> Prop)\n         (HF:List.Forall f l)\n         (HG:List.Forall g l),\n    List.Forall (fun x => f x /\\ g x) l.\nProof.\n  intros.\n  induction l.\n  { constructor. }\n  { inv HF. inv HG.\n    constructor. split; ss. eapply IHl; eauto.\n  }\nQed.\n\nLemma Forall_repeat {X:Type}:\n  forall x n (f:X -> Prop)\n         (HF:f x),\n    Forall f (List.repeat x n).\nProof.\n  intros.\n  induction n.\n  simpl. ss.\n  simpl. constructor. ss. ss.\nQed.\n\nLemma forallb_In {X:Type}:\n  forall (l:list X) (f:X -> bool) i\n         (HFORALLB:List.forallb f l = true)\n         (HIN:List.In i l),\n    f i = true.\nProof.\n  intros.\n  rewrite List.forallb_forall in HFORALLB.\n  apply HFORALLB in HIN.\n  assumption.\nQed.\n\nLemma forallb_Permutation {X:Type}:\n  forall (l1 l2:list X) (HPERM:Permutation l1 l2) f,\n    List.forallb f l1 =  List.forallb f l2.\nProof.\n  intros.\n  induction HPERM.\n  { reflexivity. }\n  { simpl. rewrite IHHPERM. reflexivity. }\n  { simpl.\n    rewrite andb_assoc.\n    rewrite andb_assoc.\n    rewrite andb_comm with (b1 := f y). reflexivity. }\n  { congruence. }\nQed.\n\nLemma forallb_implies:\n  forall {X:Type} (l:list X) (f g:X -> bool)\n         (HIMP:forall x, f x = true -> g x = true)\n         (HFORALLB:List.forallb f l = true),\n    List.forallb g l = true.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. simpl in HFORALLB.\n    rewrite andb_true_iff in *.\n    destruct HFORALLB.\n    split. apply HIMP. assumption. apply IHl. assumption.\nQed.\n\nLemma concat_Permutation {X:Type}:\n  forall (l1 l2:list (list X))\n         (HFORALL:List.Forall2 (fun x y => Permutation x y) l1 l2),\n    Permutation (List.concat l1) (List.concat l2).\nProof.\n  intros.\n  generalize dependent l2.\n  induction l1.\n  { intros. inv HFORALL. eauto. }\n  { simpl. intros.\n    destruct l2. inv HFORALL.\n    inv HFORALL. simpl.\n    apply Permutation_app. assumption.\n    apply IHl1. assumption.\n  }\nQed.\n\nLemma split_map_fst:\n  forall {X Y Z:Type} (l:list (X * Y)) (f:X * Y -> Z) (g:X -> Z)\n         (HEQ:forall x y, f (x, y) = g x),\n    List.map f l = List.map g (fst (split l)).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl. destruct a.\n  remember (split l) as p.\n  destruct p.\n  simpl in *.\n  rewrite HEQ. congruence.\nQed.\n\nLemma split_map_snd:\n  forall {X Y Z:Type} (l:list (X * Y)) (f:X * Y -> Z) (g:Y -> Z)\n         (HEQ:forall x y, f (x, y) = g y),\n    List.map f l = List.map g (snd (split l)).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl. destruct a.\n  remember (split l) as p.\n  destruct p.\n  simpl in *.\n  rewrite HEQ. congruence.\nQed.\n\nLemma map_fst_split {X Y:Type}:\n  forall (l:list (X * Y)),\n    List.map fst l = (List.split l).(fst).\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. destruct a.\n    remember (split l) as p.\n    destruct p. simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma existsb_rev:\n  forall {X:Type} (f:X -> bool) (l:list X),\n    List.existsb f (List.rev l) = List.existsb f l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl in *.\n    rewrite existsb_app.\n    simpl.\n    rewrite orb_comm.\n    rewrite orb_comm with (b1 := f a).\n    simpl.\n    rewrite IHl. reflexivity.\nQed.\n\n(* Why do I need this? *)\nLemma list_eq:\n  forall {X:Type} (a b:X) (c d:list X)\n    (HEQ:a = b)\n    (HEQ2:c = d),\n    a::c = b::d.\nProof.\n  intros.\n  rewrite HEQ.\n  rewrite HEQ2.\n  reflexivity.\nQed.\n\n(* If map f b = a,\n   and p = split (filter g (combine a b)),\n   map f p.snd = p.fst. *)\nLemma split_filter_combine_map:\n  forall {X Y:Type} (a:list X) (b:list Y) p f g\n         (HMAP:List.map f b = a)\n         (HP:p = List.split (List.filter g (List.combine a b))),\n    List.map f p.(snd) = p.(fst).\nProof.\n  intros.\n  remember (combine a b) as ab.\n  generalize dependent a.\n  generalize dependent b.\n  generalize dependent p.\n  induction ab as [| abh abt].\n  - intros. simpl in HP. rewrite HP. reflexivity.\n  - intros.\n    destruct (split (filter g abt)) as [abtl abtr] eqn:HS.\n    simpl in HP.\n    destruct a as [| ah at'].\n    { simpl in Heqab. inversion Heqab. }\n    destruct b as [| bh bt].\n    { simpl in Heqab. inversion Heqab. }\n    destruct (g abh).\n    + destruct abh as [abhl abhr].\n      simpl in Heqab.\n      inversion Heqab.\n      rewrite H0 in *. clear H0.\n      rewrite H1 in *. clear H1. clear Heqab.\n      simpl in HP.\n      rewrite HS in HP.\n      rewrite HP.\n      simpl.\n      simpl in HMAP.\n      inversion HMAP.\n      rewrite H0 in *. clear H0.\n      rewrite H1 in *. clear HMAP.\n      apply list_eq. reflexivity.\n      assert (abtr = snd (split (filter g abt))).\n      { rewrite HS. reflexivity. }\n      assert (abtl = fst (split (filter g abt))).\n      { rewrite HS. reflexivity. }\n      rewrite H. rewrite H0.\n      eapply IHabt.\n      * assumption.\n      * apply H1.\n      * assumption.\n    + apply IHabt with (b := bt) (a := at').\n      * rewrite HP. assumption.\n      * simpl in HMAP.\n        inversion HMAP. reflexivity.\n      * simpl in Heqab.\n        inversion Heqab.\n        reflexivity.\nQed.\n\nLemma In_map:\n  forall {X Y:Type} (l:list X) (f:X -> Y) (y:Y)\n         (HIN:List.In y (List.map f l)),\n    exists (x:X), f x = y /\\ List.In x l.\nProof.\n  induction l.\n  intros. simpl in HIN. inversion HIN.\n  intros.\n  simpl in HIN.\n  destruct HIN.\n  - eexists. split. eassumption. constructor. reflexivity.\n  - apply IHl in H.\n    destruct H as [xH H].\n    destruct H as [H1 H2].\n    eexists.\n    split. eassumption. simpl. right. assumption.\nQed.\n\nLemma In_notIn_neq {X:Type}:\n  forall (l:list X) (x1 x2:X)\n         (HNOTIN:~List.In x1 l)\n         (HIN:List.In x2 l),\n    x1 <> x2.\nProof.\n  intros.\n  intros HEQ.\n  apply HNOTIN.\n  congruence.\nQed.\n\nLemma last_cons {X:Type}:\n  forall (l:list X) h h' h'',\n    List.last (l ++ (h::nil)) h'' = List.last (h'::l ++ (h::nil)) h''.\nProof.\n  intros.\n  generalize dependent h'.\n  induction l.\n  - simpl. reflexivity.\n  - intros. simpl. reflexivity.\nQed.\n\nLemma last_element {X:Type}:\n  forall (l:list X) h1 h3 h2\n         (HLAST:List.last (l ++ (h1::nil)) h3 = h2),\n    h1 = h2.\nProof.\n  intros.\n  induction l.\n  - simpl in HLAST. congruence.\n  - simpl.\n    replace ((a::l)++h1::nil) with (a::l++h1::nil) in HLAST.\n    rewrite <- last_cons in HLAST.\n    apply IHl. assumption.\n    reflexivity.\nQed.\n\nLemma last_head {X:Type}:\n  forall (l:list X) (HLEN:List.length l > 0) x\n         (HLAST: List.last l x = x),\n    List.hd x (List.rev l) = x.\nProof.\n  intros.\n  generalize dependent HLEN.\n  generalize dependent HLAST.\n  apply rev_ind with (l := l).\n  - intros. simpl in HLEN. inversion HLEN.\n  - intros.\n    assert (x0 = x).\n    { eapply last_element. eapply HLAST. }\n    rewrite H0 in *.\n    rewrite rev_unit.\n    reflexivity.\nQed.\n\nLemma list_segmentize8_l {X:Type}:\n  forall (bs:list X),\n    exists b1 b2, bs = b1 ++ b2 /\\\n                  Nat.modulo (List.length b2) 8 = 0 /\\\n                  List.length b1 < 8.\nProof.\n  intros.\n  induction bs.\n  - exists nil. eexists nil.\n    split. reflexivity. split. reflexivity. simpl. omega.\n  - inversion IHbs as [b1 [b2 IH]].\n    destruct IH as [H1 [H2 H3]].\n    destruct b1 as [ | h1 b1].\n    { eexists (a::nil). eexists b2. \n      split. rewrite H1. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h2 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h3 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::h2::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h4 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::h2::h3::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h5 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::h2::h3::h4::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h6 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::h2::h3::h4::h5::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    destruct b1 as [ | h7 b1].\n    { simpl in H1.\n      rewrite H1.\n      eexists (a::h1::h2::h3::h4::h5::h6::nil). eexists b2.\n      split. reflexivity.\n      split. assumption.\n      simpl. omega. }\n    simpl in H1.\n    rewrite H1.\n    eexists nil.\n    eexists (a::h1::h2::h3::h4::h5::h6::h7::b1 ++ b2).\n    split. reflexivity.\n    split.\n    assert (a :: h1 :: h2 :: h3 :: h4 :: h5 :: h6 :: h7 :: b1 ++ b2 =\n            (a :: h1 :: h2 :: h3 :: h4 :: h5 :: h6 :: h7 :: b1) ++ b2).\n    { reflexivity. }\n    rewrite H.\n    rewrite app_length.\n    replace (length (a :: h1 :: h2 :: h3 :: h4 :: h5 :: h6 :: h7 :: b1)) with\n            (8 + length b1).\n    simpl in H3.\n    destruct b1.\n    + rewrite <- Nat.add_mod_idemp_l.\n      simpl.\n      apply H2.\n      omega.\n    + simpl in H3.\n      omega.\n    + simpl. reflexivity.\n    + simpl. omega.\nQed.\n\nLemma list_segmentize8_r {X:Type}:\n  forall (bs:list X),\n    exists b1 b2, bs = b1 ++ b2 /\\\n                  Nat.modulo (List.length b1) 8 = 0 /\\\n                  List.length b2 < 8.\nProof.\n  intros.\n  assert (exists b1' b2', (rev bs) = b1' ++ b2' /\\\n                          Nat.modulo (List.length b2') 8 = 0 /\\\n                          List.length b1' < 8).\n  { eapply list_segmentize8_l. }\n  destruct H as [b1' H].\n  destruct H as [b2' H].\n  destruct H as [H1 [H2 H3]].\n  rewrite <- rev_involutive with (l := b1') in H1.\n  rewrite <- rev_involutive with (l := b2') in H1.\n  rewrite <- rev_app_distr in H1.\n  assert (bs = rev b2' ++ rev b1').\n  { rewrite <- rev_involutive with (l := bs).\n    rewrite H1.\n    rewrite rev_involutive.\n    reflexivity. }\n  exists (rev b2').\n  exists (rev b1').\n  split.\n  - assumption.\n  - split.\n    rewrite rev_length. assumption.\n    rewrite rev_length. assumption.\nQed.\n\nLemma list_split8_l {X:Type}:\n  forall (bs:list X) n\n         (HLEN:n = List.length bs)\n         (HLEN2:Nat.modulo n 8 = 0)\n         (HNEQ:n <> 0),\n    exists b1 b2, bs = b1 ++ b2 /\\\n                  List.length b1 = 8 /\\\n                  Nat.modulo (List.length b2) 8 = 0.\nProof.\n  intros.\n  destruct bs as [| h1 bs].\n  { simpl in HLEN. omega. }\n  destruct bs as [| h2 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h3 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h4 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h5 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h6 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h7 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n  destruct bs as [| h8 bs].\n  { simpl in HLEN. rewrite HLEN in HLEN2. inversion HLEN2. }\n exists (h1::h2::h3::h4::h5::h6::h7::h8::nil).\n  exists bs.\n  split. reflexivity.\n  split. reflexivity.\n  assert (length (h1 :: h2 :: h3 :: h4 :: h5 :: h6 :: h7 :: h8 :: bs) =\n          8 + length bs).\n  { reflexivity. }\n  rewrite H in HLEN.\n  rewrite HLEN in HLEN2.\n  rewrite <- Nat.add_mod_idemp_l in HLEN2.\n  simpl in HLEN2.\n  simpl.\n  assumption.\n  omega.\nQed.\n\n\n\n(*******************************************\n      Boolean version of List.incl\n *******************************************)\n\nDefinition list_inclb {X:Type}\n           {eq_dec: forall x y : X, {x = y}+{x <> y}}\n           (l1 l2: list X): bool :=\n  List.forallb (fun x =>\n                  List.existsb (fun y =>\n                     match (eq_dec x y) with\n                     | left _ => true\n                     | right _ => false\n                     end) l2) l1.\n\nLemma list_inclb_refl {X:Type} {eq_dec:forall x y:X, {x = y}+{x<>y}}:\n  forall (l:list X), @list_inclb X eq_dec l l = true.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl.\n    destruct (eq_dec a a).\n    + unfold list_inclb.\n      simpl.\n      unfold list_inclb in IHl.\n      rewrite forallb_forall in *.\n      rewrite <- Forall_forall in *.\n      apply Forall_impl with (P :=\n        (fun x : X => existsb\n                        (fun y : X => if eq_dec x y then true else false) l = true)).\n      * intros.\n        rewrite H. rewrite orb_true_r. reflexivity.\n      * assumption.\n    + exfalso. auto.\nQed.\n\nLemma list_inclb_trans_existsb {X:Type} {eq_dec:forall x y:X, {x = y}+{x<>y}}:\n  forall l1 l2 a\n    (HEX:List.existsb (fun y => if eq_dec a y then true else false) l1 = true)\n    (HINC:@list_inclb X eq_dec l1 l2 = true),\n  List.existsb (fun y => if eq_dec a y then true else false) l2 = true.\nProof.\n  intros.\n  generalize dependent l2.\n  induction l1.\n  { intros. inv HEX. }\n  { intros. simpl in HEX.\n    simpl in HINC.\n    rewrite andb_true_iff in HINC.\n    destruct HINC.\n    destruct (eq_dec a a0) eqn:HEQ.\n    { subst a. assumption. }\n    { eapply IHl1. assumption. assumption. }\n  }\nQed.\n\nLemma list_inclb_trans {X:Type} {eq_dec:forall x y:X, {x = y}+{x<>y}}:\n  forall (l1 l2 l3:list X)\n         (H1:@list_inclb X eq_dec l1 l2 = true)\n         (H1:@list_inclb X eq_dec l2 l3 = true),\n    @list_inclb X eq_dec l1 l3 = true.\nProof.\n  intros.\n  generalize dependent l3.\n  generalize dependent l2.\n  induction l1.\n  { intros.\n    destruct l2. assumption.\n    reflexivity. }\n  { intros.\n    simpl in H1.\n    rewrite andb_true_iff in H1. destruct H1.\n    simpl.\n    exploit IHl1. eapply H1. eapply H0. intros HH.\n    rewrite HH.\n    rewrite andb_true_r.\n    eapply list_inclb_trans_existsb. eassumption. assumption.\n  }\nQed.\n\n\n(*******************************************\n      Numbering each element of a list.\n *******************************************)\n\nFixpoint _number_list {X:Type} (l:list X) (i:nat): list (nat * X) :=\n  match l with\n  | nil => nil\n  | h::t => (i, h)::(_number_list t (i+1))\n  end.\n\nDefinition number_list {X:Type} (l:list X): list (nat * X) :=\n  _number_list l 0.\n\nLemma _number_list_len {X:Type}:\n  forall (l:list X) i1 i2,\n    List.length (_number_list l i1) = List.length (_number_list l i2).\nProof.\n  induction l.\n  intros. reflexivity.\n  intros. simpl. erewrite IHl. reflexivity.\nQed.\n\nLemma number_list_len {X:Type}:\n  forall (l:list X) l'\n    (HEQ:l' = number_list l),\n    List.length l = List.length l'.\nProof.\n  induction l.\n  - intros. unfold number_list in HEQ. simpl in HEQ. rewrite HEQ. reflexivity.\n  - intros. unfold number_list in HEQ. simpl in HEQ.\n    rewrite HEQ. simpl.\n    rewrite _number_list_len with (i2 := 0).\n    rewrite <- IHl. reflexivity.\n    unfold number_list. reflexivity.\nQed.\n\nLemma _number_list_append {X:Type}:\n  forall (l:list X) (h:X) i n\n         (HLEN:n = List.length l),\n    (_number_list l i) ++ ((n + i, h)::nil) = (_number_list (l ++ (h::nil)) i).\nProof.\n  induction l.\n  - intros. simpl. rewrite HLEN. reflexivity.\n  - simpl. intros.\n    destruct n. inversion HLEN.\n    inversion HLEN. rewrite <- H0. rewrite <- IHl with (n := n).\n    rewrite Nat.add_comm with (n := i) (m := 1). simpl.\n    rewrite Nat.add_succ_r.\n    reflexivity.\n    assumption.\nQed.\n\nLemma _number_list_nth_fst {X:Type}:\n  forall (l:list X) n def i,\n    fst (List.nth n (_number_list l i) (n + i, def)) = n + i.\nProof.\n  induction l.\n  - intros. simpl. destruct n. reflexivity. reflexivity.\n  - intros. simpl. destruct n. reflexivity.\n    simpl.\n    rewrite <- Nat.add_succ_r with (n := n) (m := i).\n    rewrite Nat.add_comm with (n := i) (m := 1).\n    simpl.\n    rewrite IHl with (n := n) (def := def) (i := S i).\n    reflexivity.\nQed.\n\nLemma _number_list_nth_snd {X:Type}:\n  forall (l:list X) n m def i,\n    snd (List.nth n (_number_list l i) (m, def)) = List.nth n l def.\nProof.\n  induction l.\n  - intros. simpl. destruct n; reflexivity.\n  - simpl. destruct n. intros. reflexivity.\n    intros. simpl.\n    rewrite IHl. reflexivity.\nQed.\n\nTheorem list_number_nth {X:Type}:\n  forall (l:list X) n def,\n    List.nth n (number_list l) (n, def) = (n, List.nth n l def).\nProof.\n  intros.\n  remember (List.nth n (number_list l) (n, def)) as res.\n  destruct res.\n  assert (n0 = fst (nth n (number_list l) (n, def))).\n  { rewrite <- Heqres. reflexivity. }\n  assert (x = snd (nth n (number_list l) (n, def))).\n  { rewrite <- Heqres. reflexivity. }\n  unfold number_list in H, H0.\n  replace (n, def) with (n+0, def) in H, H0.\n  rewrite _number_list_nth_fst in H.\n  rewrite _number_list_nth_snd in H0.\n  rewrite Nat.add_0_r in H.\n  rewrite H, H0. reflexivity.\n  rewrite Nat.add_0_r. reflexivity.\nQed.\n\n\n(**************************************************\n   Checking all two adjacent elements in a list.\n **************************************************)\n\nFixpoint forall_adj {X:Type} (f:X -> X -> bool) (l:list X) :=\n  match l with\n  | nil => true\n  | h::t =>\n    match t with\n    | nil => true\n    | h2::t' => (f h h2) && (forall_adj f t)\n    end                     \n  end.\n\n\n(*******************************************\n      Subsequence of a list.\n *******************************************)\n\nInductive lsubseq {X:Type}: list X -> list X -> Prop :=\n| ss_nil: forall (l:list X), lsubseq l nil\n| ss_cons: forall (x:X) (l1 l2:list X) (H:lsubseq l1 l2),\n    lsubseq (x::l1) (x::l2)\n| ss_elon: forall (x:X) (l1 l2:list X) (H:lsubseq l1 l2),\n    lsubseq (x::l1) l2.\n\nLemma lsubseq_refl: forall {X:Type} (l:list X), lsubseq l l.\nProof.\n  intros.\n  induction l. constructor. constructor. assumption.\nQed.\n\nLemma lsubseq_inv:\n  forall {X:Type} (l1 l2:list X) (x:X)\n         (H:lsubseq l1 (x::l2)),\n    lsubseq l1 l2.\nProof.\n  intros.\n  induction l1.\n  - inversion H.\n  - inversion H.\n    + apply ss_elon. assumption.\n    + apply ss_elon. apply IHl1.\n      assumption.\nQed.\n\nLemma lsubseq_trans:\n  forall {X:Type} (l1 l2 l3:list X)\n         (H1:lsubseq l1 l2)\n         (H2:lsubseq l2 l3),\n    lsubseq l1 l3.\nProof.\n  intros.\n  generalize dependent l3.\n  induction H1 as [| x l1' l2' | x l1' l2'].\n  - intros. inversion H2. constructor.\n  - intros.\n    inversion H2 as [| y l2'' l3' | y l2'' l3'].\n    + constructor.\n    + constructor. apply IHlsubseq. assumption.\n    + apply ss_elon.\n      apply IHlsubseq.\n      assumption.\n  - intros.\n    apply ss_elon.\n    apply IHlsubseq.\n    assumption.\nQed.    \n\nLemma lsubseq_append: forall {X:Type} (l1 l2 l3 l4:list X)\n                             (H1:lsubseq l1 l2)\n                             (H2:lsubseq l3 l4),\n    lsubseq (l1++l3) (l2++l4).\nProof.\n  intros.\n  induction H1.\n  - simpl.\n    induction l. assumption.\n    simpl. constructor. assumption.\n  - simpl. constructor. assumption.\n  - simpl. constructor. assumption.\nQed.\n\nLemma lsubseq_append2: forall {X:Type} (l0 l1 l2:list X)\n                             (H1:lsubseq l1 l2),\n    lsubseq (l0++l1) (l2).\nProof.\n  intros.\n  induction l0.\n  - simpl. assumption.\n  - simpl. constructor. assumption.\nQed.\n\nLemma lsubseq_In:\n  forall {X:Type} (l l':list X) (x:X)\n         (HIN:List.In x l')\n         (HLSS:lsubseq l l'),\n    List.In x l.\nProof.\n  intros.\n  induction HLSS.\n  - simpl in HIN. inversion HIN.\n  - simpl in HIN.\n    destruct HIN.\n    + rewrite H. simpl. auto.\n    + simpl. right. apply IHHLSS. assumption.\n  - simpl. right. apply IHHLSS. assumption.\nQed.\n\nLemma lsubseq_In2 {X:Type}:\n  forall (l:list X) (a:X),\n    lsubseq l [a] <->  List.In a l.\nProof.\n  intros.\n  split.\n  {\n    intros HLSS.\n    remember ([a]) as l'.\n    generalize dependent a.\n    induction HLSS.\n    { intros. congruence. }\n    { intros. inv Heql'. simpl. left. reflexivity. }\n    { intros. simpl. right. apply IHHLSS. assumption. }\n  }\n  { intros.\n    induction l.\n    inv H. simpl in H. inv H. constructor. constructor.\n    constructor. apply IHl. assumption.\n  }\nQed.\n\nLemma lsubseq_combine_map {X Y:Type}:\n  forall (l11 l21:list X) (l12 l22:list Y) f\n         (HLEN1:List.length l11 = List.length l12)\n         (HLEN2:List.length l21 = List.length l22)\n         (HLSS:lsubseq (List.combine l11 l12) (List.combine l21 l22))\n         (HMAP:List.map f l12 = l11),\n    List.map f l22 = l21.\nProof.\n  intros.\n  remember (List.combine l11 l12) as l'1.\n  remember (List.combine l21 l22) as l'2.\n  generalize dependent l11.\n  generalize dependent l12.\n  generalize dependent l21.\n  generalize dependent l22.\n  induction HLSS.\n  { intros. destruct l21; destruct l22; simpl in *; try congruence. }\n  { intros.\n    destruct l21; destruct l22; simpl in *; try congruence.\n    destruct l11; destruct l12; simpl in *; try congruence.\n    inversion Heql'2. subst x.\n    inversion Heql'1. subst x0. subst y.\n    inversion HMAP. subst x1.\n    erewrite IHHLSS; try eassumption. reflexivity.\n    congruence. congruence.\n  }\n  { intros.\n    destruct l11; destruct l12; simpl in *; try congruence.\n    inversion Heql'1. subst x. inversion HLEN1.\n    erewrite IHHLSS. reflexivity.\n    congruence. assumption. eapply H0. assumption.\n    inversion HMAP. reflexivity.\n  }\nQed.\n\nLemma lsubseq_concat {X:Type}:\n  forall (l1 l2:list (list X))\n         (HLSS:lsubseq l1 l2),\n    lsubseq (List.concat l1) (List.concat l2).\nProof.\n  intros.\n  induction HLSS.\n  { simpl. constructor. }\n  { simpl. apply lsubseq_append. apply lsubseq_refl. ss. }\n  { simpl. apply lsubseq_append2. ss. }\nQed.\n\nLemma lsubseq_concat_In {X:Type}:\n  forall (ls:list (list X)) (l2:list X)\n         (HIN:List.In l2 ls),\n    lsubseq (List.concat ls) l2.\nProof.\n  intros.\n  generalize dependent l2.\n  induction ls.\n  { intros. inv HIN. }\n  { intros.\n    simpl in HIN.\n    inv HIN.\n    { simpl.\n      rewrite app_nil_end with (l := l2) at 2.\n      apply lsubseq_append.\n      apply lsubseq_refl. constructor. }\n    { simpl. apply lsubseq_append2.\n      eauto. }\n  }\nQed.\n\n(* Lemma: if length if output is larger than input,\n   lsubseq does not hold. *)\nLemma lsubseq_exceed:\n  forall {X:Type} (l l':list X)\n         (HLEN:List.length l' > List.length l),\n    ~ lsubseq l l'.\nProof.\n  intros.\n  intros H.\n  induction H.\n  - simpl in HLEN.\n    destruct (length l).\n    inversion HLEN. inversion HLEN.\n  - simpl in HLEN.\n    apply Gt.gt_S_n in HLEN.\n    apply IHlsubseq. assumption.\n  - simpl in HLEN.\n    apply IHlsubseq.\n    apply Gt.gt_trans with (m := S (length l1)).\n    assumption.\n    constructor.\nQed.\n\n(* Lemma: if length of input is same as output,\n   the input equals the output. *)\nLemma lsubseq_full:\n  forall {X:Type} (l l':list X)\n         (H:lsubseq l l')\n         (HLEN:List.length l = List.length l'),\n    l = l'.\nProof.\n  intros X l.\n  induction l.\n  - intros.\n    simpl in HLEN. symmetry in HLEN. rewrite length_zero_iff_nil in HLEN.\n    congruence.\n  - intros.\n    destruct l'.\n    simpl in HLEN. inversion HLEN.\n    simpl in HLEN. inversion HLEN.\n    inversion H.\n    + rewrite IHl with (l' := l').\n      reflexivity.\n      assumption.\n      assumption.\n    + exfalso.\n      eapply lsubseq_exceed.\n      assert (length (x::l') > length l').\n      { simpl. constructor. }\n      apply H5.\n      rewrite IHl with (l' := l') in H4.\n      assumption.\n      eapply lsubseq_inv. eassumption.\n      assumption.\nQed.\n\nLemma lsubseq_filter: forall {X:Type} (l:list X) f,\n    lsubseq l (List.filter f l).\nProof.\n  intros.\n  induction l. constructor. simpl.\n  destruct (f a) eqn:H. constructor. assumption.\n  constructor. assumption.\nQed.\n\nLemma lsubseq_filter2 {X:Type}:\n  forall (l1 l2 l3 l4 : list X) (f:X -> bool)\n         (HLSS:lsubseq l1 l2)\n         (HF1:l3 = List.filter f l1)\n         (HF1:l4 = List.filter f l2),\n    lsubseq l3 l4.\nProof.\n  intros.\n  generalize dependent l3.\n  generalize dependent l4.\n  induction HLSS.\n  { intros. simpl in HF0. inv HF0. constructor. }\n  { intros.\n    simpl in *.\n    destruct (f x) eqn:HCOND.\n    { inv HF0.\n      constructor. eapply IHHLSS; try reflexivity.\n    }\n    { eapply IHHLSS; try eassumption. }\n  }\n  { intros.\n    simpl in *.\n    destruct (f x) eqn:HCOND.\n    { inv HF1. constructor. eapply IHHLSS; try reflexivity. }\n    { eapply IHHLSS; try eassumption. }\n  }\nQed.\n\nLemma lsubseq_filter3 {X:Type}:\n  forall (l1 l2 l3 : list X) (f:X -> bool)\n         (HLSS:lsubseq l1 l2)\n         (HF1:l3 = List.filter f l2),\n    lsubseq l1 l3.\nProof.\n  intros.\n  generalize dependent l3.\n  induction HLSS.\n  { intros. simpl in HF1. inv HF1. constructor. }\n  { intros.\n    simpl in *.\n    destruct (f x) eqn:HCOND.\n    { inv HF1.\n      constructor. eapply IHHLSS; try reflexivity.\n    }\n    { constructor.\n      eapply IHHLSS; try eassumption. }\n  }\n  { intros.\n    simpl in *.\n    destruct (f x) eqn:HCOND.\n    { inv HF1. constructor. eapply IHHLSS; try reflexivity. }\n    { constructor. eapply IHHLSS; try eassumption. }\n  }\nQed.\n\nLemma lsubseq_combine:\n  forall {X Y:Type} (a1 a2:list X) (b1 b2:list Y)\n         (HLEN1:List.length a1 = List.length b1)\n         (HLEN2:List.length a2 = List.length b2)\n         (HSS:lsubseq (List.combine a1 b1) (List.combine a2 b2)),\n    lsubseq a1 a2 /\\ lsubseq b1 b2.\nProof.\n  intros.\n  remember (combine a1 b1) as c1.\n  remember (combine a2 b2) as c2.\n  generalize dependent a1.\n  generalize dependent a2.\n  generalize dependent b1.\n  generalize dependent b2.\n  induction HSS.\n  - intros.\n    assert (a2 = nil /\\ b2 = nil).\n    { apply combine_length_nil.\n      assumption. congruence. }\n    destruct H. rewrite H in *. rewrite H0 in *.\n    split; constructor.\n  - intros.\n    symmetry in Heqc1, Heqc2.\n    assert (H1 := combine_length_some a1 b1 x l1 HLEN1 Heqc1).\n    assert (H2 := combine_length_some a2 b2 x l2 HLEN2 Heqc2).\n    destruct H1 as [H11 H12].\n    destruct H2 as [H21 H22].\n    rewrite H11, H12, H21, H22.\n    assert (HH:lsubseq (fst (split l1)) (fst (split l2)) /\\\n               lsubseq (snd (split l1)) (snd (split l2)) ->\n               lsubseq (fst x :: fst (split l1)) (fst x :: fst (split l2)) /\\\n               lsubseq (snd x :: snd (split l1)) (snd x :: snd (split l2))).\n    { intros.\n      destruct H.\n      split; constructor; assumption.\n    }\n    apply HH. clear HH.\n    apply IHHSS.\n    + rewrite H21 in HLEN2. rewrite H22 in HLEN2.\n      simpl in HLEN2. apply Nat.succ_inj. assumption.\n    + rewrite H21, H22 in Heqc2.\n      simpl in Heqc2. inversion Heqc2. rewrite H1. congruence.\n    + rewrite H11 in HLEN1. rewrite H12 in HLEN1.\n      simpl in HLEN1. congruence.\n    + rewrite H11, H12 in Heqc1.\n      simpl in Heqc1. inversion Heqc1. rewrite H1. congruence.\n  - intros.\n    symmetry in Heqc1.\n    assert (H1 := combine_length_some a1 b1 x l1 HLEN1 Heqc1).\n    assert (HH:lsubseq (fst (split l1)) a2 /\\\n               lsubseq (snd (split l1)) b2 ->\n               lsubseq (fst x :: fst (split l1)) a2 /\\\n               lsubseq (snd x :: snd (split l1)) b2).\n    { intros.\n      destruct H.\n      split; constructor; assumption.\n    }\n    destruct H1 as [H11 H12].\n    rewrite H11, H12.\n    apply HH. clear HH.\n    apply IHHSS.\n    + assumption.\n    + congruence.\n    + rewrite H11, H12 in HLEN1.\n      simpl in HLEN1. apply Nat.succ_inj. assumption.\n    + apply combine_fst_snd_split.\nQed.\n\nLemma lsubseq_len:\n  forall {X:Type} (l l':list X)\n         (HLSS:lsubseq l l'),\n    List.length l' <= List.length l.\nProof.\n  intros.\n  induction HLSS.\n  - simpl.\n    apply Nat.le_0_l.\n  - simpl.\n    apply le_n_S. assumption.\n  - simpl. constructor. assumption.\nQed.\n\nLemma lsubseq_split_snd:\n  forall {X Y:Type} (l1 l2:list (X * Y))\n         (HLSS:lsubseq l1 l2),\n    lsubseq (snd (List.split l1)) (snd (List.split l2)).\nProof.\n  intros.\n  induction HLSS.\n  - simpl. constructor.\n  - simpl. destruct x.\n    remember (split l1) as tmp.\n    destruct tmp as [a1 b1].\n    remember (split l2) as tmp.\n    destruct tmp as [a2 b2].\n    simpl in IHHLSS.\n    simpl. constructor. assumption.\n  - simpl. destruct x.\n    remember (split l1) as tmp.\n    destruct tmp as [a1 b1].\n    simpl in *. constructor. assumption.\nQed.\n\nLemma lsubseq_forallb: forall {X:Type} (l l':list X) f\n                             (H:List.forallb f l = true)\n                             (HLSS:lsubseq l l'),\n    List.forallb f l' = true.\nProof.\n  intros.\n  induction HLSS.\n  - constructor.\n  - simpl in *.\n    rewrite andb_true_iff in *.\n    destruct H.\n    split. assumption. apply IHHLSS. assumption.\n  - simpl in H. rewrite andb_true_iff in H.\n    destruct H. apply IHHLSS. assumption.\nQed.\n\nLemma lsubseq_split_len2 {X:Type}:\n  forall (l:list X) (x1 x2:X)\n         (HLSS:lsubseq l (x1::x2::nil)),\n    exists l1 l2 l3,\n      l = l1 ++ x1 :: l2 ++ x2 :: l3.\nProof.\n  intros.\n  induction l.\n  { inv HLSS. }\n  { inv HLSS.\n    { eapply lsubseq_In in H0.\n      2: constructor; ss.\n      eapply List.in_split in H0.\n      inv H0. inv H.\n      exists [].\n      exists x.\n      exists x0.\n      simpl. ss.\n    }\n    { apply IHl in H2.\n      inv H2. inv H. inv H0.\n      exists (a::x).\n      eexists.\n      eexists.\n      simpl. ss.\n    }\n  }\nQed.\n\nLemma lsubseq_NotIn {X:Type}:\n  forall (l l':list X) a\n         (HLSS:lsubseq l l')\n         (HNIN:~List.In a l),\n    ~List.In a l'.\nProof.\n  intros. intros H.\n  apply HNIN.\n  eapply lsubseq_In. eassumption. assumption.\nQed.\n\nLemma lsubseq_NoDup {X:Type}:\n  forall (l l':list X)\n         (HLSS:lsubseq l l')\n         (HNDP:NoDup l),\n    NoDup l'.\nProof.\n  intros.\n  induction HLSS.\n  - constructor.\n  - inversion HNDP.\n    apply IHHLSS in H2.\n    apply NoDup_cons.\n    eapply lsubseq_NotIn.\n    eassumption.\n    assumption. assumption.\n  - inversion HNDP.\n    apply IHHLSS. assumption.\nQed.\n\nLemma lsubseq_map {X Y:Type}:\n  forall (l l':list X) (lm lm':list Y) (f:X -> Y)\n         (HLSS:lsubseq l l')\n         (HLM:lm = List.map f l)\n         (HLM':lm' = List.map f l'),\n    lsubseq lm lm'.\nProof.\n  intros.\n  generalize dependent lm.\n  generalize dependent lm'.\n  induction HLSS.\n  - intros. simpl in HLM'. rewrite HLM'.\n    constructor.\n  - intros. destruct lm. inversion HLM.\n    destruct lm'. inversion HLM'.\n    simpl in HLM. inversion HLM.\n    simpl in HLM'. inversion HLM'.\n    constructor.\n    apply IHHLSS.\n    reflexivity. reflexivity.\n  - intros. destruct lm. inversion HLM.\n    simpl in HLM. inversion HLM.\n    constructor.\n    apply IHHLSS.\n    assumption. reflexivity.\nQed.\n\nLemma notIn_filter_nat:\n  forall (l:list nat) (key:nat)\n         (HNOTIN:~List.In key l),\n   filter (fun x => x =? key) l = nil.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl in HNOTIN.\n    apply Decidable.not_or in HNOTIN.\n    destruct HNOTIN.\n    apply IHl in H0.\n    simpl. rewrite H0.\n    destruct (a =? key) eqn:HD.\n    + apply beq_nat_true in HD. omega.\n    + reflexivity.\nQed.\n\n(*******************************************\n   Finding a value by key (which is nat)\n   & Updateing a value with key\n *******************************************)\n\nDefinition list_find_key {X:Type} (l:list (nat * X)) (key:nat)\n:list (nat * X) :=\n  List.filter (fun x => fst x =? key) l.\n\nDefinition list_set {X:Type} (l:list (nat * X)) (key:nat) (v:X)\n:list (nat * X) :=\n  List.map (fun x => if fst x =? key then (key, v) else x) l.\n\nDefinition list_keys {X:Type} (l:list (nat * X))\n:list nat :=\n  List.map fst l.\n\nLemma list_keys_In {X:Type}:\n  forall (l:list (nat * X)) key val\n         (HIN:List.In (key, val) l),\n    List.In key (list_keys l).\nProof.\n  intros.\n  generalize dependent key.\n  generalize dependent val.\n  induction l.\n  - intros. inversion HIN.\n  - intros. inversion HIN. rewrite H.\n    simpl. left. reflexivity.\n    simpl. right. eapply IHl. eassumption.\nQed.\n\nLemma list_keys_app {X:Type}:\n  forall (l1 l2:list (nat*X)),\n    list_keys (l1++l2) = (list_keys l1) ++ list_keys l2.\nProof.\n  intros.\n  induction l1.\n  { reflexivity. }\n  { simpl. congruence. }\nQed.\n\nLemma list_keys_NoDup {X:Type}:\n  forall (l:list (nat * X)) (HNODUP:List.NoDup (list_keys l)),\n    List.NoDup l.\nProof.\n  intros.\n  induction l.\n  { constructor. }\n  { simpl in HNODUP. destruct a. inv HNODUP.\n    apply IHl in H2. constructor.\n    intros H0. apply H1. eapply list_keys_In. eassumption.\n    assumption. }\nQed.\n\nLemma list_find_key_In_none {X:Type}:\n  forall (l:list (nat * X)) blkid x\n    (HEMPTY: list_find_key l blkid = [])\n    (HIN:List.In x l),\n    x.(fst) <> blkid.\nProof.\n  intros.\n  induction l.\n  { inv HIN. }\n  { inv HIN.\n    { simpl in HEMPTY.\n      destruct (fst x =? blkid) eqn:HE.\n      { inv HEMPTY. }\n      { rewrite PeanoNat.Nat.eqb_neq in HE. congruence. }\n    }\n    { simpl in HEMPTY.\n      destruct (fst a =? blkid) eqn:HA; try congruence.\n      apply IHl in HEMPTY. assumption. assumption. }\n  }\nQed.\n\nLemma list_find_key_NoDup_In2 {X:Type}:\n  forall (l:list (nat * X)) key v1 v2\n         (HIN:List.In (key, v1) l)\n         (HIN:List.In (key, v2) l)\n         (HNODUP:List.NoDup (list_keys l)),\n    v1 = v2.\nProof.\n  intros.\n  induction l.\n  { inv HIN. }\n  { destruct a.\n    inv HIN.\n    { inv HIN0.\n      { congruence. }\n      { inv H. inv HNODUP.\n        exfalso. apply H2. eapply list_keys_In. eassumption. }\n    }\n    { inv HIN0.\n      { inv H0. inv HNODUP.\n        exfalso. apply H2. eapply list_keys_In. eassumption. }\n      { inv HNODUP.\n        eapply IHl; try eassumption.\n      }\n    }\n  }\nQed.\n\nLemma decompose_by_key {X:Type}:\n  forall (l:list (nat * X)) key\n         (HNODUP:NoDup (list_keys l))\n         (HIN:List.In key (list_keys l)),\n    exists l1 l2 v, l = l1 ++ (key, v)::l2 /\\\n                    ~List.In key (list_keys l1) /\\\n                    ~List.In key (list_keys l2).\nProof.\n  intros.\n  induction l.\n  - inversion HIN.\n  - destruct a as [newkey newval].\n    simpl in HNODUP.\n    simpl in HIN.\n    destruct HIN as [HIN | HIN].\n    + exists nil.\n      exists l.\n      exists newval.\n      simpl.\n      split. congruence.\n      split. intros HH; inversion HH.\n      inversion HNODUP. rewrite HIN in H1. assumption.\n    + inversion HNODUP.\n      apply IHl in H2.\n      destruct H2 as [l1 [l2 [v0 [HH1 [HH2 HH]]]]].\n      exists ((newkey, newval)::l1).\n      exists l2.\n      exists v0.\n      rewrite HH1.\n      split. reflexivity.\n      split. simpl.\n      intros H'. destruct H' as [H' | H'].\n      rewrite H' in H1. apply H1 in HIN. omega.\n      apply HH2 in H'. omega.\n      assumption.\n      assumption.\nQed.\n\nLemma list_set_keys_eq {X:Type}:\n  forall (l l':list (nat * X)) key x\n         (HMAP:l' = list_set l key x),\n    list_keys l' = list_keys l.\nProof.\n  intros.\n  generalize dependent l'.\n  induction l.\n  - simpl. intros. rewrite HMAP. reflexivity.\n  - simpl. intros.\n    destruct (fst a =? key) eqn:Heq.\n    + destruct l'. inversion HMAP.\n      inversion HMAP.\n      rewrite Nat.eqb_eq in Heq.\n      rewrite Heq. simpl. erewrite IHl. reflexivity. reflexivity.\n    + destruct l'. inversion HMAP.\n      inversion HMAP. simpl. erewrite IHl. reflexivity. reflexivity.\nQed.\n\nLemma list_find_key_set_diffkey {X:Type}:\n  forall (l:list (nat * X)) k k' v\n    (HDIFFKEY:k <> k'),\n    list_find_key (list_set l k' v) k = list_find_key l k.\nProof.\n  intros.\n  unfold list_find_key.\n  unfold list_set.\n  induction l.\n  { reflexivity. }\n  { simpl.\n    rewrite <- IHl.\n    destruct a.\n    simpl.\n    des_ifs.\n    { simpl in *. rewrite PeanoNat.Nat.eqb_eq in *. congruence. }\n    { simpl in *. rewrite PeanoNat.Nat.eqb_eq in *.\n      rewrite PeanoNat.Nat.eqb_neq in *. congruence. }\n    { simpl in *. rewrite PeanoNat.Nat.eqb_eq in *.\n      rewrite PeanoNat.Nat.eqb_neq in *. omega. }\n    { simpl in *. rewrite PeanoNat.Nat.eqb_eq in *.\n      rewrite PeanoNat.Nat.eqb_neq in *. omega. }\n    { simpl in *. rewrite PeanoNat.Nat.eqb_eq in *.\n      rewrite PeanoNat.Nat.eqb_neq in *. omega. }\n  }\nQed.\n\nLemma list_find_key_set_none {X:Type}:\n  forall (m:list (nat * X)) k v\n         (HNO:list_find_key m k = nil),\n    list_find_key (list_set m k v) k = nil.\nProof.\n  intros.\n  unfold list_find_key in *.\n  unfold list_set in *.\n  induction m.\n  { reflexivity. }\n  { simpl in HNO.\n    destruct (fst a =? k) eqn:HK; des_ifs.\n    apply IHm in HNO.\n    simpl. rewrite HK. rewrite HK. assumption.\n  }\nQed.\n\nLemma list_find_key_set_none2:\n  forall (X : Type) (m : list (nat * X)) (k k' : nat) (v : X),\n  list_find_key m k = [] -> list_find_key (list_set m k' v) k = [].\nProof.\n  intros.\n  induction m.\n  { reflexivity. }\n  { simpl.\n    simpl in H. des_ifs. simpl in Heq. rewrite Nat.eqb_eq in *. subst. rewrite Nat.eqb_refl in Heq1. ss.\n    apply IHm. ss.\n    eauto.\n  }\nQed.\n\nLemma list_set_eq {X:Type}:\n  forall (l:list (nat * X)) (key:nat) (val:X)\n         (HIN:List.In (key, val) l)\n         (HNODUP:List.NoDup (List.map fst l)),\n  list_set l key val = l.\nProof.\n  intros.\n  unfold list_set.\n  generalize dependent key.\n  generalize dependent val.\n  induction l.\n  - simpl. intros. inversion HIN.\n  - simpl. intros.\n    simpl in HNODUP.\n    inversion HNODUP.\n    destruct HIN as [HIN | HIN].\n    + rewrite HIN in H1. simpl in H1.\n      rewrite HIN. simpl. rewrite Nat.eqb_refl.\n      assert (HNE:~ List.Exists (fun x => x = key) (map fst l)).\n      { intros HX.\n        apply H1.\n        rewrite Exists_exists in HX.\n        destruct HX as [key' HX].\n        destruct HX as [HX1 HX2].\n        rewrite HX2 in HX1. assumption. }\n      rewrite <- Forall_Exists_neg in HNE.\n      clear H2 H1 IHl HNODUP H0.\n      induction l.\n      * reflexivity.\n      * simpl in HNE.\n        inversion HNE.\n        apply IHl in H3. simpl.\n        rewrite <- Nat.eqb_neq in H2.\n        rewrite H2.\n        inversion H3.\n        rewrite H5. rewrite H5. reflexivity.\n    + assert (fst a <> key).\n      {\n        apply in_split_l in HIN.\n        simpl in HIN.\n        rewrite map_fst_split in H1.\n        eapply In_notIn_neq.\n        eassumption. assumption.\n      }\n      rewrite <- Nat.eqb_neq in H3.\n      rewrite H3.\n      rewrite IHl. reflexivity. assumption. assumption.\nQed.\n\nLemma list_set_NoDup_key {X:Type}:\n  forall (l l':list (nat * X)) key v\n         (HNODUP:NoDup (list_keys l))\n         (HSET:l' = list_set l key v),\n    NoDup (list_keys l').\nProof.\n  intros.\n  erewrite list_set_keys_eq.\n  eassumption. eassumption.\nQed.\n\nLemma list_set_In {X:Type}:\n  forall (l l':list (nat * X)) key v\n         (HKEYIN:List.In key (list_keys l))\n         (HSET:l' = list_set l key v),\n    List.In (key, v) l'.\nProof.\n  intros.\n  generalize dependent l'.\n  induction l; try (inversion HKEYIN; fail).\n  intros.\n  simpl in HSET.\n  destruct (fst a =? key) eqn:HEQ.\n  - rewrite HSET. auto. simpl. auto.\n  - simpl in HKEYIN.\n    destruct HKEYIN as [HKEYIN | HKEYIN].\n    + rewrite Nat.eqb_neq in HEQ. omega.\n    + rewrite HSET. simpl. right.\n      apply IHl. assumption. reflexivity.\nQed.\n\nLemma list_set_In_key {X:Type}:\n  forall (l l':list (nat * X)) key v\n         (HNODUP:List.In key (list_keys l))\n         (HSET:l' = list_set l key v),\n    List.In key (list_keys l').\nProof.\n  intros.\n  erewrite list_set_keys_eq.\n  eassumption.\n  eassumption.\nQed.\n\nLemma list_set_notIn_key {X:Type}:\n  forall (l:list (nat * X)) key v\n         (HNODUP: ~List.In key (list_keys l)),\n    l = list_set l key v.\nProof.\n  intros.\n  induction l.\n  - intros. reflexivity.\n  - intros. simpl.\n    simpl in HNODUP.\n    destruct (fst a =? key) eqn:Heq.\n    + rewrite Nat.eqb_eq in Heq. rewrite Heq in HNODUP. omega.\n    + rewrite Nat.eqb_neq in Heq.\n      rewrite <- IHl.\n      reflexivity.\n      apply Decidable.not_or in HNODUP. destruct HNODUP. assumption.\nQed.\n\nLemma list_set_NoDup_In_unique {X:Type}:\n  forall (l:list (nat * X)) (key:nat) (x x0:X)\n         (HIN:List.In (key, x0) (list_set l key x))\n         (HNODUP:List.NoDup (list_keys l)),\n    x0 = x.\nProof.\n  intros.\n  unfold list_keys in HNODUP.\n  remember (map fst l) as l'.\n  generalize dependent l.\n  induction HNODUP.\n  - simpl. intros. destruct l; try (inversion Heql'; fail). simpl in HIN.\n    inversion HIN.\n  - intros.\n    destruct l0 as [ | h0 t0].\n    + inversion Heql'.\n    + destruct h0 as [key0 v0].\n      simpl in Heql'.\n      inversion Heql'.\n      simpl in HIN.\n      destruct HIN.\n      * destruct (key0 =? key) eqn:Hkey0.\n        inversion H0. reflexivity.\n        inversion H0. rewrite Nat.eqb_neq in Hkey0. omega.\n      * apply IHHNODUP with (l0 := t0). assumption.\n        assumption.\nQed.\n\nLemma list_keys_In_False {X:Type}:\n  forall (l:list (nat * X)) key x\n         (HNOTIN:~ In key (list_keys l))\n         (HIN:In (key, x) l),\n    False.\nProof.\n  intros.\n  induction l.\n  - inversion HIN.\n  - simpl in HIN. simpl in HNOTIN.\n    destruct HIN as [HIN | HIN].\n    rewrite HIN in HNOTIN.\n    apply HNOTIN. left. reflexivity.\n    apply Decidable.not_or in HNOTIN.\n    destruct HNOTIN.\n    apply IHl in H0. assumption. assumption.\nQed.\n\n\nLemma list_set_decompose {X:Type}:\n  forall (l l':list (nat * X)) key v\n         (HNODUP:NoDup (list_keys l))\n         (HIN:List.In key (list_keys l))\n         (HSET:l' = list_set l key v),\n    exists l1 l2 v0,\n       (l = l1 ++ (key, v0)::l2 /\\\n        l' = l1 ++ (key, v)::l2 /\\\n       ~List.In key (list_keys l1) /\\\n       ~List.In key (list_keys l2)).\nProof.\n  intros.\n  assert (NoDup (list_keys l')).\n  { eapply list_set_NoDup_key; eassumption. }\n  assert (List.In key (list_keys l')).\n  { eapply list_set_In_key; eassumption. }\n  assert (HD := decompose_by_key l key HNODUP HIN).\n  assert (HD':= decompose_by_key l' key H H0).\n  destruct HD' as [l1' [l2' [v0' [HD'1 [HD'2 HD'3]]]]].\n  destruct HD as [l1 [l2 [v0 [HD1 [HD2 HD3]]]]].\n  assert (H12: l1 = l1' /\\ l2 = l2' /\\ (key, v0') = (key, v)).\n  { rewrite HD'1, HD1 in HSET.\n    unfold list_set in HSET.\n    rewrite map_app in HSET.\n    simpl in HSET. rewrite Nat.eqb_refl in HSET.\n    assert (H11:l1 = list_set l1 key v).\n    { apply list_set_notIn_key. assumption. }\n    assert (H12:l2 = list_set l2 key v).\n    { apply list_set_notIn_key. assumption. }\n    unfold list_set in H11, H12.\n    rewrite <- H11, <- H12 in HSET.\n    apply app_equal with (x := (key, v)) (x' := (key, v0')).\n    { intros H00.\n      eapply list_keys_In_False. eapply HD2. eassumption. }\n    { intros H00.\n      eapply list_keys_In_False. eapply HD'2. eassumption. }\n    assumption.\n  }\n  destruct H12 as [H1 [H2 HITM]].\n  inversion HITM. rewrite H4 in *. clear H4 HITM.\n  exists l1', l2', v0.\n  split.\n  - congruence.\n  - split.\n    assumption.\n    split; assumption.\nQed.\n\nLemma list_find_key_NoDup {X:Type}:\n  forall (l res:list (nat * X)) (key:nat)\n         (HNODUP:NoDup (list_keys l))\n         (HRES:res = list_find_key l key),\n    List.length res < 2.\nProof.\n  intros.\n  remember (split l) as ls.\n  destruct ls as [lsk lsv].\n  unfold list_keys in HNODUP.\n  rewrite map_fst_split in HNODUP.\n  rewrite <- Heqls in HNODUP. simpl in HNODUP.\n  assert (List.map fst (List.filter (fun x => fst x =? key) l) =\n          List.filter (fun x => x =? key) lsk).\n  {\n    clear HNODUP.\n    clear HRES.\n    generalize dependent lsk.\n    generalize dependent lsv.\n    induction l.\n    - intros. simpl in Heqls. inversion Heqls.\n      reflexivity.\n    - intros. destruct a. simpl in Heqls.\n      remember (split l) as l'.\n      destruct l'.\n      inversion Heqls. destruct lsk. inversion H0.\n      destruct lsv. inversion H1.\n      simpl.\n      destruct (n =? key) eqn:HKEY.\n      + simpl. erewrite IHl. reflexivity. reflexivity.\n      + erewrite IHl. reflexivity. reflexivity.\n  }\n  unfold list_find_key in HRES.\n  rewrite <- HRES in H.\n  rewrite map_fst_split in H.\n  remember (split res) as ress.\n  destruct ress as [resk resv].\n  simpl in H.\n  rewrite <- split_length_l.\n  rewrite <- Heqress. simpl.\n  clear HRES Heqls l Heqress.\n  (* assert (NoDup resk).\n  { apply lsubseq_NoDup with (l := lsk).\n    rewrite H. apply lsubseq_filter. assumption. } *)\n  induction HNODUP as [ | lskh lsht IH].\n  - simpl in H. rewrite H. simpl. omega.\n  - simpl in H.\n    destruct (lskh =? key) eqn: Hflag.\n    + apply beq_nat_true in Hflag.\n      rewrite <- Hflag in *.\n      apply notIn_filter_nat in IH.\n      rewrite IH in H. rewrite H. simpl. omega.\n    + apply IHHNODUP. assumption.\nQed.\n\nLemma list_find_key_In {X:Type}:\n  forall (l:list (nat * X)) key val\n         (HIN:List.In (key,val) l),\n    List.In (key,val) (list_find_key l key).\nProof.\n  intros.\n  unfold list_find_key.\n  apply filter_In.\n  split. assumption. simpl. rewrite PeanoNat.Nat.eqb_refl. auto.\nQed.\n\nLemma list_set_In_not_In {X:Type}:\n  forall (l:list (nat * X)) (key key0:nat) (x x0:X)\n         (HIN:List.In (key0, x0) (list_set l key x))\n         (HNEQ:key0 <> key),\n    List.In (key0, x0) l.\nProof.\n  intros.\n  induction l.\n  - simpl in HIN. inversion HIN.\n  - simpl in HIN.\n    destruct HIN.\n    + destruct a. simpl in H.\n      destruct (n =? key) eqn:Heq.\n      inversion H. omega.\n      rewrite Nat.eqb_neq in Heq. inversion H.\n      simpl. auto.\n    + apply IHl in H. simpl. right. assumption.\nQed.\n\nLemma list_find_key_spec {X:Type}:\n  forall (l:list (nat * X)) key val\n         (HIN:List.In (key,val) l)\n         (HNODUP:List.NoDup (list_keys l)),\n    list_find_key l key = [(key, val)].\nProof.\n  intros.\n  remember (list_find_key l key) as res.\n  dup Heqres.\n  eapply list_find_key_NoDup in Heqres; try assumption.\n  assert (List.In (key, val) res).\n  { rewrite Heqres0.\n    eapply list_find_key_In.\n    assumption. }\n  destruct res. inv H.\n  destruct res. inv H. reflexivity. inv H0. simpl in Heqres.\n  omega.\nQed.\n\nLemma list_find_key_set_samekey {X:Type}:\n  forall (l : list (nat * X)) (v : X) k\n      (HNODUP:List.NoDup (list_keys l))\n      (HIN:List.In k (list_keys l)),\n    list_find_key (list_set l k v) k = [(k, v)].\nProof.\n  intros.\n  eapply list_set_In with (v0 := v) in HIN; try reflexivity.\n  erewrite <- list_set_keys_eq with (key := k) (x := v) in HNODUP; try reflexivity.\n  eapply list_find_key_spec.\n  assumption. assumption.\nQed.\n\n\n\n(*******************************************\n      Definition of range & disjointness.\n *******************************************)\n\nDefinition disjoint_range (r1 r2:nat * nat): bool :=\n  match (r1, r2) with\n  | ((b1, len1), (b2, len2)) =>\n    Nat.leb (b1 + len1) b2 || Nat.leb (b2 + len2) b1\n  end.\n\nFixpoint disjoint_ranges (rs:list (nat*nat)): bool :=\n  match rs with\n  | nil => true\n  | r::t => List.forallb (fun r2 => disjoint_range r r2) t && disjoint_ranges t\n  end.\n\nDefinition in_range (i:nat) (r:nat * nat): bool :=\n  Nat.leb r.(fst) i && Nat.leb i (r.(fst) + r.(snd)).\n\n(* Returns a list of ranges which include i. *)\nDefinition disjoint_include (rs:list (nat * nat)) (i:nat): list (nat*nat) :=\n  List.filter (in_range i) rs.\n\nDefinition disjoint_include2 {X:Type} (rs:list (nat * nat)) (data:list X) (i:nat)\n: list (nat*nat) * list X :=\n  List.split\n    (List.filter (fun x => in_range i x.(fst))\n                 (List.combine rs data)).\n\nDefinition no_empty_range (rs:list (nat * nat)): bool :=\n  List.forallb (fun t => Nat.ltb 0 t.(snd)) rs.\n\n\n\n(* Lemma: two ranges with same begin index & non-zero length overlaps. *)\nLemma disjoint_same:\n  forall b1 b2 l1 l2 (HL1:0 < l1) (HL2: 0 < l2) (HEQ:b1 = b2),\n    disjoint_range (b1, l1) (b2, l2) = false.\nProof.\n  intros.\n  unfold disjoint_range.\n  rewrite orb_false_iff.\n  repeat (rewrite Nat.leb_nle).\n  split; rewrite HEQ; apply Gt.gt_not_le; apply Nat.lt_add_pos_r; auto.\nQed.\n\n(* Same as disjoint_same, but with same end index. *)\nLemma disjoint_same2:\n  forall b1 b2 l1 l2 (HL1:0 < l1) (HL2:0 < l2) (HEQ:b1 + l1 = b2 + l2),\n    disjoint_range (b1, l1) (b2, l2) = false.\nProof.\n  intros.\n  unfold disjoint_range.\n  rewrite orb_false_iff.\n  repeat (rewrite Nat.leb_nle).\n  split.\n  - rewrite HEQ; apply Gt.gt_not_le; apply Nat.lt_add_pos_r; auto.\n  - rewrite <- HEQ; apply Gt.gt_not_le; apply Nat.lt_add_pos_r; auto.\nQed.\n\nLemma disjoint_range_sym:\n  forall r1 r2, disjoint_range r1 r2 = disjoint_range r2 r1.\nProof.\n  intros. unfold disjoint_range.\n  destruct r1. destruct r2.\n  intuition.\nQed.\n\nLemma disjoint_range_symm:\n  forall r1 r2,\n    disjoint_range r1 r2 = disjoint_range r2 r1.\nProof.\n  intros. unfold disjoint_range. destruct r1.\n  destruct r2. intuition.\nQed.\n\nLemma filter_Permutation {X:Type}:\n  forall (l1 l2:list X)\n         (HP:Permutation l1 l2) f,\n    Permutation (List.filter f l1) (List.filter f l2).\nProof.\n  intros.\n  induction HP.\n  { constructor. }\n  { simpl. destruct (f x).\n    constructor. assumption.\n    assumption. }\n  { simpl. destruct (f y); destruct (f x); try constructor; try apply Permutation_refl. }\n  { eapply Permutation_trans; eassumption. }\nQed.\n\nLemma map_Permutation {X Y:Type}:\n  forall (l1 l2:list X)\n         (HP:Permutation l1 l2) (f:X -> Y),\n    Permutation (List.map f l1) (List.map f l2).\nProof.\n  intros.\n  induction HP.\n  { constructor. }\n  { simpl. constructor. assumption. }\n  { simpl. constructor. }\n  { eapply Permutation_trans; eassumption. }\nQed.\n\nLemma Permutation_app2 {X:Type}:\n  forall (l1 l2:list X),\n    Permutation (l1 ++ l2) (l2 ++ l1).\nProof.\n  intros.\n  induction l1.\n  { simpl. rewrite List.app_nil_r. apply Permutation_refl. }\n  { simpl. apply Permutation_cons_app. assumption. }\nQed.\n\nLemma map_Permutation2 {X Y:Type}:\n  forall (l1 l2:list X) (y:Y)\n         (HPERM:Permutation l1 l2),\n    Permutation (List.map (fun x => (x, y)) l1)\n                (List.map (fun x => (x, y)) l2).\nProof.\n  intros.\n  induction HPERM.\n  { simpl. constructor. }\n  { simpl. constructor. assumption. }\n  { simpl. constructor. }\n  { eapply Permutation_trans; eassumption. }\nQed.\n\nLemma concat_map_Permutation {X Y:Type}:\n  forall (l1 l2:list X)\n         (HP:Permutation l1 l2) (f:X -> list Y),\n    Permutation (List.concat (List.map f l1))\n                (List.concat (List.map f l2)).\nProof.\n  intros.\n  induction HP.\n  { constructor. }\n  { simpl. eapply Permutation_app.\n    apply Permutation_refl. assumption. }\n  { simpl.\n    rewrite List.app_assoc.\n    rewrite List.app_assoc.\n    apply Permutation_app_tail with (tl := List.concat (List.map f l)).\n    apply Permutation_app2.\n  }\n  { eapply Permutation_trans; eassumption. }\nQed.\n\nLemma concat_Permutation2 {X:Type}:\n  forall (l1 l2:list (list X))\n         (HPERM:Permutation l1 l2),\n    Permutation (List.concat l1) (List.concat l2).\nProof.\n  intros.\n  induction HPERM.\n  { eauto. }\n  { simpl. eapply Permutation_app_head. assumption. }\n  { simpl.\n    rewrite List.app_assoc.\n    rewrite List.app_assoc.\n    eapply Permutation_app_tail with (tl := List.concat l).\n    eapply Permutation_app2. }\n  { eapply Permutation_trans; eauto. }\nQed.\n\nLemma disjoint_ranges_In:\n  forall r1 r2 rs (HDISJ:disjoint_ranges rs = true)\n         (HIN1:List.In r1 rs)\n         (HIN2:List.In r2 rs)\n         (HNEQ:r1 <> r2),\n    disjoint_range r1 r2.\nProof.\n  intros.\n  generalize dependent r1.\n  generalize dependent r2.\n  induction rs.\n  { intros. inv HIN1. }\n  { intros.\n    simpl in HIN1, HIN2.\n    inv HIN1; inv HIN2.\n    { congruence. }\n    { simpl in HDISJ.\n      rewrite andb_true_iff in HDISJ.\n      destruct HDISJ.\n      eapply forallb_In. eassumption. assumption. }\n    { simpl in HDISJ. rewrite andb_true_iff in HDISJ.\n      destruct HDISJ.\n      rewrite disjoint_range_sym.\n      eapply forallb_In. eassumption. assumption. }\n    { apply IHrs; try assumption.\n      simpl in HDISJ. rewrite andb_true_iff in HDISJ. tauto.\n    }\n  }\nQed.\n\nLemma disjoint_ranges_Permutation:\n  forall l1 l2 (HPERM:Permutation l1 l2),\n    disjoint_ranges l1 = disjoint_ranges l2.\nProof.\n  intros.\n  induction HPERM.\n  { reflexivity. }\n  { simpl. rewrite IHHPERM. erewrite forallb_Permutation.\n    reflexivity. assumption. }\n  { simpl. rewrite disjoint_range_symm.\n    rewrite andb_assoc.\n    rewrite andb_assoc.\n    rewrite <- andb_assoc with (b1 := disjoint_range x y)\n         (b2 := List.forallb (fun r2 : nat * nat => disjoint_range y r2) l)\n         (b3 := List.forallb (fun r2 : nat * nat => disjoint_range x r2) l).\n    rewrite andb_comm with\n        (b1 := List.forallb (fun r2 : nat * nat => disjoint_range y r2) l).\n    rewrite andb_assoc.\n    reflexivity.\n  }\n  { congruence. }\nQed.\n\nLemma disjoint_ranges_app_false:\n  forall (rs:list (nat * nat)) (HNNIL: rs <> nil) (HNEMP: no_empty_range rs = true),\n    disjoint_ranges (rs ++ rs) = false.\nProof.\n  intros.\n  destruct rs. congruence.\n  simpl.\n  rewrite List.forallb_app.\n  simpl.\n  simpl in HNEMP.\n  rewrite andb_true_iff in HNEMP.\n  destruct p.\n  simpl in *.\n  destruct HNEMP. rewrite PeanoNat.Nat.ltb_lt in H.\n  rewrite disjoint_same2; try omega.\n  simpl. rewrite andb_false_r. reflexivity.\nQed.\n\nLemma disjoint_ranges_app_comm:\n  forall (l1 l2:list (nat * nat)),\n    disjoint_ranges (l1 ++ l2) = disjoint_ranges (l2 ++ l1).\nProof.\n  intros.\n  eapply disjoint_ranges_Permutation.\n  apply Permutation_app2.\nQed.\n\n(* Lemma: no_empty_range still holds for appended lists *)\nLemma no_empty_range_append:\n  forall l1 l2 (H1:no_empty_range l1 = true) (H2:no_empty_range l2 = true),\n    no_empty_range (l1++l2) = true.\nProof.\n  intros.\n  induction l1.\n  - simpl. assumption.\n  - simpl in H1.\n    simpl. rewrite andb_true_iff in *.\n    destruct H1.\n    split. assumption. apply IHl1. assumption.\nQed.\n\n(* Lemma: no_empty_range holds for subsequences *)\nLemma no_empty_range_lsubseq:\n  forall l1 l2 (H1:no_empty_range l1 = true) (HLSS:lsubseq l1 l2),\n    no_empty_range l2 = true.\nProof.\n  intros.\n  induction HLSS. reflexivity.\n  simpl. simpl in H1. rewrite andb_true_iff in *.\n  destruct H1. split. assumption. apply IHHLSS. assumption.\n  apply IHHLSS. simpl in H1. rewrite andb_true_iff in *.\n  destruct H1. assumption.\nQed.\n\n(* Lemma: no_empty_range holds for concatenated lists *)\nLemma no_empty_range_concat:\n  forall (ll:list (list (nat * nat)))\n         (HALL:forall l (HIN:List.In l ll), no_empty_range l = true),\n    no_empty_range (List.concat ll) = true.\nProof.\n  intros.\n  induction ll.\n  - reflexivity.\n  - simpl. apply no_empty_range_append.\n    apply HALL. constructor. reflexivity.\n    apply IHll. intros. apply HALL.\n    simpl. right. assumption.\nQed.\n\n(* Lemma: the subsequence of disjoint ranges is also disjoint. *)\nLemma disjoint_lsubseq_disjoint:\n  forall rs rs'\n         (HDISJ:disjoint_ranges rs = true)\n         (HLSS:lsubseq rs rs'),\n    disjoint_ranges rs' = true.\nProof.\n  intros.\n  induction HLSS.\n  - constructor.\n  - simpl in *.\n    rewrite andb_true_iff in *.\n    destruct HDISJ as [HDISJ1 HDISJ2].\n    split.\n    + apply lsubseq_forallb with (l := l1).\n      assumption.\n      assumption.\n    + apply IHHLSS. assumption.\n  - simpl in HDISJ.\n    rewrite andb_true_iff in HDISJ.\n    destruct HDISJ as [_ HDISJ].\n    apply IHHLSS. assumption.\nQed.\n\nLemma disjoint_ranges_append:\n  forall l1 l2 (HDISJ:disjoint_ranges (l1 ++ l2) = true),\n    disjoint_ranges l1 = true /\\ disjoint_ranges l2 = true.\nProof.\n  intros.\n  induction l1.\n  - simpl in HDISJ.\n    split. reflexivity. assumption.\n  - simpl in HDISJ.\n    rewrite andb_true_iff in HDISJ.\n    destruct HDISJ.\n    split. simpl. rewrite andb_true_iff. split.\n    rewrite forallb_app in H.\n    rewrite andb_true_iff in H.\n    destruct H. assumption.\n    apply IHl1. assumption.\n    apply IHl1. assumption.\nQed.\n\n(* Lemma: the result of disjoint_include is subsequence of the input. *)\nLemma disjoint_include_lsubseq:\n  forall rs i, lsubseq rs (disjoint_include rs i).\nProof.\n  intros. unfold disjoint_include. apply lsubseq_filter.\nQed.\n\n(* Lemma: if lsubseq l1 l2, lsubseq (disjoint_include l1 i)\n   (disjoint_include l2 i). *)\nLemma disjoint_include_lsubseq2:\n  forall rs1 rs2 i\n         (H:lsubseq rs1 rs2),\n    lsubseq (disjoint_include rs1 i) (disjoint_include rs2 i).\nProof.\n  intros.\n  induction H.\n  - simpl. constructor.\n  - simpl.\n    destruct (in_range i x).\n    constructor. assumption.\n    assumption.\n  - simpl.\n    destruct (in_range i x).\n    constructor. assumption. assumption.\nQed.\n\n(* Lemma: (disjoint_include2 rs data i).fst = disjoint_include rs i *)\nLemma disjoint_include_include2 {X:Type} :\n  forall rs (data:list X) i\n    (HLEN:List.length rs = List.length data),\n    fst (disjoint_include2 rs data i) = disjoint_include rs i.\nProof.\n  intros.\n  unfold disjoint_include2.\n  unfold disjoint_include.\n  generalize dependent data.\n  induction rs.\n  - intros. simpl in HLEN.\n    symmetry in HLEN.\n    rewrite length_zero_iff_nil in HLEN.\n    rewrite HLEN.\n    reflexivity.\n  - intros.\n    destruct data as [ | dh dt].\n    + simpl in HLEN. inversion HLEN.\n    + simpl in HLEN. inversion HLEN.\n      simpl.\n      destruct (in_range i a) eqn:HIN.\n      * simpl.\n        rewrite <- (IHrs dt).\n        destruct (split (filter\n                           (fun x : nat * nat * X => in_range i (fst x))\n                           (combine rs dt))) eqn:H.\n        reflexivity. assumption.\n      * rewrite <- (IHrs dt).\n        reflexivity. assumption.\nQed.\n\n(* Lemma: the result of disjoint_include all satisfies in_range. *)\nLemma disjoint_include_inrange:\n  forall rs i rs'\n         (HIN:rs' = disjoint_include rs i),\n    List.forallb (in_range i) rs' = true.\nProof.\n  intros.\n  unfold disjoint_include in HIN.\n  rewrite HIN.\n  apply filter_forallb.\nQed.\n\n(* Lemma: a range that includes i is not filtered out. *)\nLemma disjoint_include_In:\n  forall rs i rs' r\n         (HDISJ:rs' = disjoint_include rs i)\n         (HIN:List.In r rs)\n         (HIN':in_range i r = true),\n    List.In r rs'.\nProof.\n  intros.\n  unfold disjoint_include in HDISJ.\n  rewrite HDISJ.\n  rewrite filter_In.\n  split; assumption.\nQed.\n\n(* Lemma: the result of disjoint_include2 is subsequence of the input. *)\nLemma disjoint_include2_lsubseq {X:Type}:\n  forall (l l': list X) rs rs' ofs\n         (HDISJ: disjoint_include2 rs l ofs = (rs', l')),\n    lsubseq (List.combine rs l) (List.combine rs' l').\nProof.\n  intros.\n  unfold disjoint_include2 in HDISJ.\n  remember (combine rs l) as lcomb.\n  generalize dependent l.\n  generalize dependent l'.\n  generalize dependent rs.\n  generalize dependent rs'.\n  induction lcomb.\n  {\n    intros.\n    simpl in HDISJ.\n    inversion HDISJ. constructor.\n  }\n  {\n    intros.\n    destruct rs as [|rsh rst];\n    destruct l as [|lh lt];\n    simpl in Heqlcomb;\n    try inversion Heqlcomb.\n    clear Heqlcomb.\n    rewrite H0 in HDISJ.\n    simpl in HDISJ.\n    destruct (in_range ofs rsh) eqn:HINR.\n    - simpl in HDISJ.\n      remember (split (filter (fun x : nat * nat * X => in_range ofs (fst x)) lcomb)) as l0.\n      destruct l0 as [rs'' l''].\n      inversion HDISJ. \n      simpl.\n      apply ss_cons.\n      rewrite <- H1.\n      eapply IHlcomb. reflexivity. eassumption.\n    - apply ss_elon.\n      rewrite <- H1.\n      eapply IHlcomb.\n      assumption. eassumption.\n  }\nQed.\n\n(* Lemma: If the inputs of two disjoint_include2 calls have subsequence relation.\n   so do their outputs. *)\nLemma disjoint_include2_lsubseq2 {X:Type}:\n  forall rs1 rs1' rs2 rs2' (data1 data1' data2 data2':list X) i\n         (HLEN1:List.length rs1 = List.length data1)\n         (HLEN2:List.length rs2 = List.length data2)\n         (H:lsubseq (List.combine rs1 data1) (List.combine rs2 data2))\n         (H1: (rs1', data1') = disjoint_include2 rs1 data1 i)\n         (H2: (rs2', data2') = disjoint_include2 rs2 data2 i),\n    lsubseq (List.combine rs1' data1') (List.combine rs2' data2').\nProof.\n  intros.\n  generalize dependent rs1'.\n  generalize dependent data1'.\n  generalize dependent rs2'.\n  generalize dependent data2'.\n  remember (combine rs1 data1) as rd1.\n  remember (combine rs2 data2) as rd2.\n  generalize dependent data1.\n  generalize dependent rs1.\n  generalize dependent data2.\n  generalize dependent rs2.\n  induction H. (* lsubseq rs1 rs2 *)\n  - intros.\n    assert (rs2 = nil /\\ data2 = nil).\n    { apply combine_length_nil. assumption. congruence. }\n    destruct H.\n    rewrite H in *. rewrite H0 in *.\n    intros.\n    unfold disjoint_include2 in H2. simpl in H2.\n    inversion H2. simpl. constructor.\n  - intros.\n    assert (rs1 = fst x :: fst (split l1) /\\\n            data1 = snd x :: snd (split l1)).\n    { apply combine_length_some.\n      assumption. congruence.\n    }\n    assert (rs2 = fst x :: fst (split l2) /\\\n            data2 = snd x :: snd (split l2)).\n    { apply combine_length_some.\n      assumption. congruence.\n    }\n    destruct H0 as [HRS1 HDATA1].\n    destruct H3 as [HRS2 HDATA2].\n    rewrite HRS1, HDATA1 in H1.\n    unfold disjoint_include2 in H1.\n    simpl in H1.\n    rewrite HRS2, HDATA2 in H2.\n    unfold disjoint_include2 in H2.\n    simpl in H2.\n    destruct (in_range i (fst x)) eqn:HINRANGE.\n    + rewrite <- combine_fst_snd_split in H1, H2.\n      remember (split (filter (fun x : nat * nat * X => in_range i (fst x)) l2)) as res2.\n      remember (split (filter (fun x : nat * nat * X => in_range i (fst x)) l1)) as res1.\n      destruct res2 as [rs2'' data2''].\n      destruct res1 as [rs1'' data1''].\n      simpl in H1, H2.\n      rewrite <- Heqres2 in H2.\n      rewrite <- Heqres1 in H1.\n      inversion H1.\n      inversion H2.\n      simpl.\n      apply ss_cons.\n      apply IHlsubseq with (rs1 := fst (split l1)) (data1 := snd (split l1))\n                           (rs2 := fst (split l2)) (data2 := snd (split l2)).\n      * rewrite HRS2 in HLEN2.\n        rewrite HDATA2 in HLEN2.\n        simpl in HLEN2.\n        apply Nat.succ_inj.\n        assumption.\n      * apply combine_fst_snd_split.\n      * rewrite HRS1 in HLEN1. rewrite HDATA1 in HLEN1.\n        simpl in HLEN1. apply Nat.succ_inj.\n        assumption.\n      * apply combine_fst_snd_split.\n      * unfold disjoint_include2.\n        rewrite <- combine_fst_snd_split.\n        assumption.\n      * unfold disjoint_include2.\n        rewrite <- combine_fst_snd_split.\n        assumption.\n    + apply IHlsubseq with (rs2 := fst (split l2)) (rs1 := fst (split l1))\n                           (data1 := snd (split l1)) (data2 := snd (split l2)).\n      * rewrite HDATA2 in HLEN2.\n        rewrite HRS2 in HLEN2.\n        simpl in HLEN2. apply Nat.succ_inj. assumption.\n      * apply combine_fst_snd_split.\n      * rewrite HDATA1 in HLEN1. rewrite HRS1 in HLEN1.\n        simpl in HLEN1. apply Nat.succ_inj. assumption.\n      * apply combine_fst_snd_split.\n      * unfold disjoint_include2. assumption.\n      * unfold disjoint_include2. assumption.\n  - intros.\n    assert (rs1 = fst x :: fst (split l1) /\\\n            data1 = snd x :: snd (split l1)).\n    { apply combine_length_some.\n      assumption. congruence.\n    }\n    destruct H0 as [HRS1 HDATA1].\n    rewrite HRS1, HDATA1 in H1.\n    unfold disjoint_include2 in H1.\n    simpl in H1.\n    destruct (in_range i (fst x)) eqn:HINRANGE.\n    + rewrite <- combine_fst_snd_split in H1.\n      remember (split (filter (fun x : nat * nat * X => in_range i (fst x)) l1)) as res1.\n      simpl in H1.\n      rewrite <- Heqres1 in H1.\n      destruct res1 as [rs1'' data1''].\n      inversion H1.\n      simpl. apply ss_elon.\n      apply IHlsubseq with (rs2 := rs2) (rs1 := fst (split l1))\n                           (data1 := snd (split l1)) (data2 := data2).\n      * assumption.\n      * assumption.\n      * rewrite split_length_l. rewrite split_length_r.\n        reflexivity.\n      * apply combine_fst_snd_split.\n      * assumption.\n      * unfold disjoint_include2.\n        rewrite <- combine_fst_snd_split.\n        assumption.\n    + apply IHlsubseq with (rs2 := rs2) (rs1 := fst (split l1))\n                           (data1 := snd (split l1)) (data2 := data2);\n        try assumption.\n      * rewrite split_length_l, split_length_r.\n        reflexivity.\n      * apply combine_fst_snd_split.\nQed.\n\n\n(* If length data = length rs,\n   the two list results of disjoint_include2 have\n   same length. *)\nLemma disjoint_include2_len {X:Type}:\n  forall rs (data:list X) i\n         (HLEN:List.length rs = List.length data),\n    List.length (fst (disjoint_include2 rs data i)) =\n    List.length (snd (disjoint_include2 rs data i)).\nProof.\n  intros.\n  unfold disjoint_include2.\n  rewrite split_length_l.\n  rewrite split_length_r.\n  reflexivity.\nQed.\n\nLemma disjoint_include2_In {X:Type}:\n  forall rs (data:list X) i res d\n         (HLEN:List.length rs = List.length data)\n         (HIN:List.In d (List.combine rs data))\n         (HIN':in_range i d.(fst) = true)\n         (HDISJ:res = disjoint_include2 rs data i),\n    List.In d (List.combine res.(fst) res.(snd)).\nProof.\n  intros.\n  unfold disjoint_include2 in HDISJ.\n  remember (filter (fun x => in_range i (fst x)) (combine rs data)) as res'.\n  assert (In d res').\n  { rewrite Heqres'.\n    rewrite filter_In.\n    split; assumption. }\n  rewrite HDISJ.\n  rewrite <- combine_fst_snd_split.\n  assumption.\nQed.\n\n(* If ranges can be mapped from data,\n   the result of disjoint_include2 can be mapped to. *)\nLemma disjoint_include2_rel {X:Type}:\n  forall rs (data:list X) i f\n         (HMAP:List.map f data = rs),\n    List.map f (snd (disjoint_include2 rs data i)) =\n    fst (disjoint_include2 rs data i).\nProof.\n  intros.\n  remember (disjoint_include2 rs data i) as dj eqn:HDJ. \n  simpl.\n  unfold disjoint_include2 in HDJ.\n  eapply split_filter_combine_map.\n  apply HMAP.\n  apply HDJ.\nQed.\n\n(* Given (rs, data) = disjoint_include2 .... , \n   length rs = length data. *)\nLemma disjoint_include2_len2 {X:Type}:\n  forall rs (data:list X) i,\n    List.length (snd (disjoint_include2 rs data i)) <=\n    List.length rs.\nProof.\n  intros.\n  unfold disjoint_include2.\n  rewrite split_length_r.\n  apply Nat.le_trans with (List.length (combine rs data)).\n  - apply filter_length.\n  - rewrite combine_length.\n    apply Nat.le_min_l.\nQed.\n\nLemma disjoint_include2_fold_left_lsubseq {X:Type}:\n  forall rs (data:list X) ofss res\n         (HRES:res =\n               List.fold_left (fun x ofs =>\n                                 disjoint_include2 (fst x) (snd x) ofs)\n                              ofss (rs, data)),\n    lsubseq (List.combine rs data) (List.combine res.(fst) res.(snd)).\nProof.\n  intros.\n  generalize dependent rs.\n  generalize dependent data.\n  generalize dependent res.\n  induction ofss.\n  - intros.\n    simpl in HRES. destruct res. inversion HRES.\n    simpl. apply lsubseq_refl.\n  - intros.\n    simpl in HRES.\n    remember (disjoint_include2 rs data a) as res'.\n    apply lsubseq_trans with (l2 := List.combine (fst res') (snd res')).\n    + apply disjoint_include2_lsubseq with (ofs := a).\n      destruct res'. rewrite <- Heqres'. reflexivity.\n    + apply IHofss.\n      destruct res'.\n      simpl.\n      assumption.\nQed.\n\nLemma disjoint_include2_fold_left_lsubseq2 {X:Type}:\n  forall rs1 rs2 (data1 data2:list X) ofss res1 res2\n         (HLEN1:List.length rs1 = List.length data1)\n         (HLEN2:List.length rs2 = List.length data2)\n         (HRES1:res1 =\n               List.fold_left (fun x ofs =>\n                                 disjoint_include2 (fst x) (snd x) ofs)\n                              ofss (rs1, data1))\n         (HRES2:res2 =\n               List.fold_left (fun x ofs =>\n                                 disjoint_include2 (fst x) (snd x) ofs)\n                              ofss (rs2, data2))\n         (HLSS:lsubseq (List.combine rs1 data1) (List.combine rs2 data2)),\n    lsubseq (List.combine res1.(fst) res1.(snd))\n            (List.combine res2.(fst) res2.(snd)).\nProof.\n  intros.\n  generalize dependent rs1.\n  generalize dependent rs2.\n  generalize dependent data1.\n  generalize dependent data2.\n  generalize dependent res1.\n  generalize dependent res2.\n  induction ofss.\n  - simpl. intros. rewrite HRES2, HRES1 in *.\n    simpl. apply HLSS.\n  - simpl. intros.\n    remember (disjoint_include2 rs1 data1 a) as res1'.\n    destruct res1' as [rs1' data1'].\n    assert(HLEN1':List.length (fst (rs1', data1')) = List.length (snd (rs1', data1'))).\n    { rewrite Heqres1'. apply disjoint_include2_len. assumption. }\n    simpl in HLEN1'.\n    remember (disjoint_include2 rs2 data2 a) as res2'.\n    destruct res2' as [rs2' data2'].\n    assert(HLEN2':List.length (fst (rs2', data2')) = List.length (snd (rs2', data2'))).\n    { rewrite Heqres2'. apply disjoint_include2_len. assumption. }\n    simpl in HLEN2'.\n\n    apply IHofss with (rs1:=rs1') (rs2:=rs2') (data1:=data1') (data2:=data2').\n    congruence.\n    assumption.\n    congruence.\n    assumption.\n    eapply disjoint_include2_lsubseq2 with (rs3 := rs1) (rs4 := rs2).\n    eassumption.\n    eassumption.\n    assumption.\n    eassumption.\n    assumption.\nQed.\n\nLemma disjoint_include2_fold_left_len {X:Type}:\n  forall rs (data:list X) ofss res\n         (HLEN:List.length rs = List.length data)\n         (HRES:res =\n               List.fold_left (fun x ofs =>\n                                 disjoint_include2 (fst x) (snd x) ofs)\n                              ofss (rs, data)),\n    List.length res.(fst) = List.length res.(snd).\nProof.\n  intros.\n  generalize dependent rs.\n  generalize dependent data.\n  generalize dependent res.\n  induction ofss.\n  - intros. simpl in HRES. destruct res. simpl. inversion HRES. congruence.\n  - intros. simpl in HRES.\n    remember (disjoint_include2 rs data a) as res'.\n    assert (List.length res'.(fst) = List.length res'.(snd)).\n    { rewrite Heqres'.\n      apply disjoint_include2_len.\n      assumption. }\n    eapply IHofss.\n    + eapply H.\n    + destruct res'. simpl. assumption.\nQed.\n\nLemma disjoint_include2_fold_left_Permutation {X:Type}:\n  forall l I I' x\n         (HL:List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs) I x\n                            = l)\n         (HPERM:Permutation I I'),\n    List.fold_left (fun (x:list (nat * nat) * list X) ofs =>\n                      disjoint_include2 (fst x) (snd x) ofs) I' x\n                            = l.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent x.\n  induction HPERM.\n  { intros. assumption. }\n  { simpl. intros. apply IHHPERM in HL. assumption. }\n  { simpl. intros.\n    assert ((disjoint_include2 (fst (disjoint_include2 (fst x0) (snd x0) y))\n            (snd (disjoint_include2 (fst x0) (snd x0) y)) x) =\n            (disjoint_include2 (fst (disjoint_include2 (fst x0) (snd x0) x))\n       (snd (disjoint_include2 (fst x0) (snd x0) x)) y)).\n    { unfold disjoint_include2.\n      rewrite <- combine_fst_snd_split.\n      rewrite <- combine_fst_snd_split.\n      rewrite filter_reorder. reflexivity. }\n    rewrite <- H. assumption. }\n  { intros.\n    apply IHHPERM1 in HL.\n    apply IHHPERM2 in HL.\n    assumption.\n  }\nQed.\n\nLemma disjoint_include2_fold_left_In {X:Type}:\n  forall I y (b:X) rs blks\n         (HLEN:List.length rs = List.length blks)\n         (HF:List.fold_left\n            (fun x ofs => disjoint_include2 (fst x) (snd x) ofs) I (rs, blks) = y)\n         (HIN:List.In b (snd y)),\n    List.In b blks.\nProof.\n  intros.\n  symmetry in HF.\n  dup HF.\n  apply disjoint_include2_fold_left_len in HF.\n  apply disjoint_include2_fold_left_lsubseq in HF0.\n  apply lsubseq_combine in HF0.\n  destruct HF0.\n  eapply lsubseq_In. eapply HIN. eassumption.\n  assumption. assumption. assumption.\nQed.\n\nLemma disjoint_include2_fold_left_reorder {X:Type}:\n  forall a I rs (blks:list X),\n    List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n              (I) (disjoint_include2 rs blks a) =\n    disjoint_include2\n      (fst (List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n                          I (rs, blks)))\n      (snd (List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n                          I (rs, blks))) a.\nProof.\n  intros.\n  assert (List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n              (I) (disjoint_include2 rs blks a) =\n          List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n              (a::I) (rs, blks)).\n  { reflexivity. }\n  rewrite H.\n  assert (disjoint_include2\n    (fst\n       (List.fold_left\n          (fun (x : list (nat * nat) * list X) (ofs : nat) =>\n           disjoint_include2 (fst x) (snd x) ofs) I (rs, blks)))\n    (snd\n       (List.fold_left\n          (fun (x : list (nat * nat) * list X) (ofs : nat) =>\n           disjoint_include2 (fst x) (snd x) ofs) I (rs, blks))) a =\n          List.fold_left (fun x ofs => disjoint_include2 (fst x) (snd x) ofs)\n              (I ++ [a]) (rs, blks)).\n  { rewrite List.fold_left_app.\n    simpl. reflexivity. }\n  rewrite H0.\n  assert (Permutation (a::I) (I++[a])).\n  { assert (Permutation I (I ++ [])).\n    { rewrite List.app_nil_r. apply Permutation_refl. }\n    eapply Permutation_cons_app in H1.\n    eassumption. }\n  eapply disjoint_include2_fold_left_Permutation.\n  reflexivity.\n  apply Permutation_sym. assumption.\nQed.\n\nLemma disjoint_include2_fold_left_rel {X:Type}:\n  forall (l1:list (nat * nat)) (l2:list X) (f:X -> (nat*nat)) res ofss\n         (HMAP:List.map f l2 = l1)\n         (HF:res = List.fold_left\n                     (fun x ofs => disjoint_include2 (fst x) (snd x) ofs) ofss\n                     (l1, l2)),\n    List.map f (snd res) = (fst res).\nProof.\n  intros.\n  generalize dependent res.\n  generalize dependent l1.\n  generalize dependent l2.\n  induction ofss.\n  { simpl. intros. rewrite HF. simpl. congruence.  }\n  { intros. simpl in HF.\n    rewrite disjoint_include2_fold_left_reorder in HF.\n    remember (List.fold_left\n               (fun (x : list (nat * nat) * list X) (ofs : nat) =>\n                disjoint_include2 (fst x) (snd x) ofs) ofss (l1, l2)) as rr.\n    exploit IHofss. eassumption.  eassumption. intros HH.\n    eapply disjoint_include2_rel in HH.\n    rewrite <- HF in HH.\n    assumption.\n  }\nQed.\n\n(* Lemma: If there are two ranges (b1, l1), (b2, l2),\n   and they include some natural number i,\n   and they are disjoint,\n   either (b1 + l1 = b2 /\\ i = b2) or (b2 + l2 = b1 /\\ i = b1). *)\nLemma inrange2_disjoint:\n  forall (b1 l1 b2 l2 i:nat)\n         (H1:in_range i (b1, l1) = true)\n         (H2:in_range i (b2, l2) = true)\n         (HDISJ:disjoint_ranges ((b1,l1)::(b2,l2)::nil) = true),\n    (b1 + l1 = b2 /\\ i = b2) \\/ (b2 + l2 = b1 /\\ i = b1).\nProof.\n  intros.\n  unfold in_range in *.\n  unfold disjoint_ranges in HDISJ.\n  simpl in HDISJ.\n  repeat (rewrite andb_true_r in HDISJ).\n  unfold disjoint_range in HDISJ.\n  rewrite andb_true_iff in *.\n  rewrite orb_true_iff in *.\n  repeat (rewrite Nat.leb_le in *).\n  simpl in *.\n  destruct HDISJ.\n  - (* Make i = b1 + l1, from b1 + l1 <= i <= b1 + l1. *)\n    assert (i = b1 + l1).\n    { apply Nat.le_antisymm. apply H1.\n      apply Nat.le_trans with (m := b2). assumption. apply H2. }\n    (* Make i = b2, from b2 <= i <= b2. *)\n    assert (i = b2).\n    { apply Nat.le_antisymm.\n      apply Nat.le_trans with (m := b1 + l1). apply H1. assumption.\n      apply H2. }\n    left. split; congruence.\n  - (* Make i = b2 + l2, from b2 + l2 <= i <= b2 + l2. *)\n    assert (i = b2 + l2).\n    { apply Nat.le_antisymm. apply H2.\n      apply Nat.le_trans with (m := b1). assumption. apply H1. }\n    assert (i = b1).\n    { apply Nat.le_antisymm.\n      apply Nat.le_trans with (m := b2 + l2). apply H2. assumption.\n      apply H1. }\n    right. split; congruence.\nQed.\n\n(* Lemma: If there are three ranges (b1, l1), (b2, l2), (b3, l3),\n   and they all include some natural number i,\n   (e.g. b1<=i<=l1, b2<=i<=l2, b3<=i<=l3),\n   and l1 != 0 && l2 != 0 && l3 != 0,\n   the three ranges cannot be disjoint. *)\nLemma inrange3_never_disjoint:\n  forall (r1 r2 r3:nat * nat) i\n         (H1:in_range i r1 = true)\n         (H2:in_range i r2 = true)\n         (H3:in_range i r3 = true)\n         (HNOEMPTY:no_empty_range (r1::r2::r3::nil) = true),\n    disjoint_ranges (r1::r2::r3::nil) = false.\nProof.\n  intros.\n  destruct r1 as [b1 l1].\n  destruct r2 as [b2 l2].\n  destruct r3 as [b3 l3].\n  (* Prettify HNOEMPTY. *)\n  simpl in HNOEMPTY.\n  rewrite andb_true_r in HNOEMPTY.\n  repeat (rewrite andb_true_iff in HNOEMPTY).\n  destruct HNOEMPTY as [HNOEMPTY1 [HNOEMPTY2 HNOEMPTY3]].\n  (* Use inrange2_disjoint! *)\n  destruct (disjoint_ranges ((b1,l1)::(b2,l2)::nil)) eqn:HDISJ12;\n  destruct (disjoint_ranges ((b1,l1)::(b3,l3)::nil)) eqn:HDISJ13.\n  - (* Okay, (b1, l1), (b2, l2) are disjoint. *)\n    assert (H12:(b1 + l1 = b2 /\\ i = b2) \\/ (b2 + l2 = b1 /\\ i = b1)).\n    { apply inrange2_disjoint; assumption. }\n    (* (b1, l1), (b3, l3) are also disjoint. *)\n    assert (H13:(b1 + l1 = b3 /\\ i = b3) \\/ (b3 + l3 = b1 /\\ i = b1)).\n    { apply inrange2_disjoint; assumption. }\n    (* Prettify *)\n    unfold in_range in *.\n    simpl in *.\n    repeat (rewrite andb_true_iff in *).\n    repeat (rewrite andb_true_r in *).\n    repeat (rewrite Nat.leb_le in *).\n    repeat (rewrite Nat.ltb_lt in *).\n    destruct H12 as [H12 | H12];\n    destruct H12 as [H12 H12'];\n    destruct H13 as [H13 | H13];\n    destruct H13 as [H13 H13'].\n    + assert (disjoint_range (b2, l2) (b3, l3) = false).\n      { apply disjoint_same. assumption. assumption. congruence. }\n      rewrite H. rewrite andb_false_r. auto.\n    + assert (disjoint_range (b1, l1) (b2, l2) = false).\n      { apply disjoint_same. assumption. assumption. congruence. }\n      rewrite H. reflexivity.\n    + assert (disjoint_range (b1, l1) (b3, l3) = false).\n      { apply disjoint_same. assumption. assumption. congruence. }\n      rewrite H. rewrite andb_false_r. auto.\n    + assert (disjoint_range (b2, l2) (b3, l3) = false).\n      { apply disjoint_same2. assumption. assumption. congruence. }\n      rewrite H. rewrite andb_false_r. auto.\n  - (* No, (b1, l1), (b3, l3) overlap. *)\n    simpl in *.\n    repeat (rewrite andb_true_r in *).\n    rewrite HDISJ13. rewrite andb_false_r. auto.\n  - (* No, (b1, l1), (b2, l2) overlap. *)\n    simpl in *.\n    repeat (rewrite andb_true_r in *).\n    rewrite HDISJ12. auto.\n  - (* (b1, l1) - (b3, l3) overlap, and (b1, l1) - (b2, l2) overlap too. *)\n    simpl in *.\n    repeat (rewrite andb_true_r in *).\n    rewrite HDISJ12. auto.\nQed.\n\n(* Theorem: If ranges are disjoint, there are at most 2 ranges\n   which have number i in-range. *)\nTheorem disjoint_includes_atmost_2:\n  forall rs i rs' (HDISJ: disjoint_ranges rs = true)\n         (HIN:rs' = disjoint_include rs i)\n         (HNOZERO:no_empty_range rs = true),\n    List.length rs' < 3.\nProof.\n  intros.\n  generalize dependent rs'.\n  induction rs.\n  - intros. simpl in HIN. rewrite HIN. simpl. auto.\n  - intros.\n    simpl in HDISJ.\n    rewrite andb_true_iff in HDISJ. \n    simpl in HNOZERO.\n    rewrite andb_true_iff in HNOZERO.\n    destruct HDISJ as [HDISJ1 HDISJ2].\n    destruct HNOZERO as [HNOZERO0 HNOZERO].\n    simpl in HIN.\n    destruct (in_range i a) eqn:HCOND.\n    + (* New element fit. *)\n      (* rs' is an updated range. *)\n      destruct rs' as [| rs'h rs't].\n      * inversion HIN.\n      * inversion HIN.\n        rewrite <- H0 in *.\n        clear H0.\n        destruct rs'h as [beg len].\n        simpl in HCOND.\n        assert (length rs't < 3).\n        {\n          apply IHrs; assumption.\n        }\n        (* rs't may be [], [(beg1,len1)], [(beg1,len1),(beg2,len2)]. *)\n        destruct rs't as [ | rs'th rs'tt].\n        { rewrite <- H1. simpl. auto. } (* [] *)\n        destruct rs'th as [beg1 len1].\n        destruct rs'tt as [ | rs'tth rs'ttt].\n        { rewrite <- H1. simpl. auto. } (* [(beg1, len1)] *)\n        destruct rs'tth as [beg2 len2].\n        destruct rs'ttt as [ | rs'ttth rs'tttt].\n        { (* [(beg1, len1), (beg2, len2)]. *)\n          (* (beg1, len1), (beg2, len2) are in rs(all ranges) as well. *)\n          assert (HDISJ0:forallb (fun r2 : nat * nat => disjoint_range (beg, len) r2)\n                          ((beg1,len1)::(beg2,len2)::nil) = true).\n          {\n            apply lsubseq_forallb with (l := rs).\n            assumption.\n            rewrite H1.\n            apply disjoint_include_lsubseq.\n          }\n          assert (HDISJ12: disjoint_ranges ((beg1, len1)::(beg2, len2)::nil) = true).\n          {\n            apply disjoint_lsubseq_disjoint with (rs := rs).\n            assumption.\n            rewrite H1.\n            apply disjoint_include_lsubseq.\n          }\n          (* Okay, we got (beg, len) (beg1, len1) disjoint,\n             (beg, len) (beg2, len2) disjoint. *)\n          simpl in HDISJ0.\n          rewrite andb_true_r in HDISJ0.\n          rewrite andb_true_iff in HDISJ0.\n          destruct HDISJ0 as [HDISJ01 HDISJ02].\n          simpl in HDISJ12.\n          repeat (rewrite andb_true_r in HDISJ12).\n          (* Make in_range predicates. *)\n          assert (HIN12: List.forallb (in_range i)\n                                      ((beg1,len1)::(beg2,len2)::nil) = true).\n          {\n            rewrite H1.\n            unfold disjoint_include.\n            apply filter_forallb.\n          }\n          simpl in HIN12.\n          repeat (rewrite andb_true_iff in HIN12).\n          destruct HIN12 as [HIN1 [HIN2 _]].\n          (* Non-zero-size range. *)\n          assert (HNOZERO12: no_empty_range ((beg1,len1)::(beg2,len2)::nil) = true).\n          {\n            unfold no_empty_range.\n            rewrite H1.\n            apply lsubseq_forallb with (l := rs).\n            apply HNOZERO. apply disjoint_include_lsubseq.\n          }\n          simpl in HNOZERO12.\n          repeat (rewrite andb_true_iff in HNOZERO12).\n          destruct HNOZERO12 as [HNOZERO1 [HNOZERO2 _]].\n          (* Now, the main theorem. *)\n          assert (HMAIN: disjoint_ranges\n                           ((beg, len)::(beg1, len1)::(beg2, len2)::nil) = false).\n          {\n            apply inrange3_never_disjoint with (i := i).\n            assumption. assumption. assumption.\n            simpl. simpl in HNOZERO0.\n            rewrite HNOZERO0. rewrite HNOZERO1. rewrite HNOZERO2.\n            reflexivity.\n          }\n          (* Make False *)\n          simpl in HMAIN.\n          rewrite HDISJ01 in HMAIN.\n          rewrite HDISJ02 in HMAIN.\n          rewrite HDISJ12 in HMAIN.\n          simpl in HMAIN.\n          inversion HMAIN.\n        }\n        { (* disjoint_include already returned more than 2 ranges.\n             This is impossible. *)\n          simpl in H.\n          exfalso.\n          apply (Lt.le_not_lt 3 (3 + length rs'tttt)).\n          repeat (apply le_n_S).\n          apply le_0_n.\n          apply H.\n        }\n   + (* No new range fit *)\n     apply IHrs.\n     assumption.\n     assumption.\n     assumption.\nQed.\n\n(* If (b1, l1) (b2, l2) are disjoint,\n   and i != b1 /\\ i != b2,\n   then i cannot belong to both ranges. *) \nLemma inrange2_false:\n  forall b1 l1 b2 l2 i\n         (HDISJ:disjoint_ranges ((b1, l1)::(b2, l2)::nil) = true)\n         (HNOTBEG:~(i = b1 \\/ i = b2)),\n    in_range i (b1,l1) && in_range i (b2, l2) = false.\nProof.\n  intros.\n  simpl in HDISJ.\n  repeat (rewrite andb_true_r in HDISJ).\n  unfold disjoint_range in HDISJ.\n  rewrite orb_true_iff in HDISJ.\n  repeat (rewrite Nat.leb_le in HDISJ).\n  remember (in_range i (b1, l1)) as v1.\n  remember (in_range i (b2, l2)) as v2.\n  unfold in_range in *.\n  simpl in *.\n  destruct v1; destruct v2; try reflexivity.\n  {\n    symmetry in Heqv1.\n    symmetry in Heqv2.\n    rewrite andb_true_iff in *.\n    repeat (rewrite Nat.leb_le in *).\n    destruct HDISJ.\n    - assert (i = b2).\n      {\n        apply Nat.le_antisymm.\n        - apply Nat.le_trans with (m := b1 + l1).\n          apply Heqv1. apply H.\n        - apply Heqv2.\n      }\n      exfalso.\n      apply HNOTBEG. right. assumption.\n    - assert (i = b1).\n      {\n        apply Nat.le_antisymm.\n        - apply Nat.le_trans with (m := b2 + l2).\n          apply Heqv2. apply H.\n        - apply Heqv1.\n      }\n      exfalso.\n      apply HNOTBEG. left. assumption.\n  }\nQed.\n\nLemma inrange2_forallb:\n  forall i r1 r2\n         (HIN:List.forallb (in_range i) (r1::r2::nil) = true),\n    in_range i r1 = true /\\ in_range i r2 = true.\nProof.\n  intros.\n  simpl in HIN.\n  rewrite andb_true_r in HIN.\n  rewrite andb_true_iff in HIN.\n  assumption.\nQed.\n\n\n\n\n(*******************************************\n             to_front function\n *******************************************)\n\nFixpoint to_front {X:Type} (l:list (nat * X)) (key:nat) :=\n  match l with\n  | [] => []\n  | h::t => if h.(fst) =? key then h::t else\n    match to_front t key with\n    | h'::t' => h'::h::t'\n    | nil => h::t\n    end\n  end.\n\nLemma to_front_spec {X:Type}:\n  forall (l l1 l2:list (nat * X)) key v\n         (HNODUP:List.NoDup (list_keys l))\n         (HSPLIT:l = l1 ++ (key, v) :: l2),\n    to_front l key = (key, v)::l1 ++ l2.\nProof.\n  intros.\n  generalize dependent HNODUP.\n  generalize dependent l.\n  induction l1.\n  { intros. simpl in HSPLIT. simpl. rewrite HSPLIT.\n    unfold to_front. simpl. rewrite PeanoNat.Nat.eqb_refl.\n    reflexivity. }\n  { intros. simpl in HSPLIT.\n    destruct l; try congruence.\n    inversion HSPLIT.\n    subst p.\n    simpl in HNODUP. inversion HNODUP.\n    subst x. subst l0. apply IHl1 in H1.\n    { simpl. destruct (fst a =? key) eqn:HKEY.\n      { rewrite PeanoNat.Nat.eqb_eq in HKEY.\n        destruct a. simpl in HKEY. subst n.\n        simpl in HNODUP.\n        inv HSPLIT.\n        rewrite list_keys_app in HNODUP.\n        simpl in HNODUP.\n        inv HNODUP.\n        exfalso.\n        apply H4.\n        apply List.in_or_app.\n        right. constructor.\n        reflexivity.\n      }\n      { rewrite PeanoNat.Nat.eqb_neq in HKEY.\n        des_ifs.\n      }\n    }\n    { assumption. }\n  }\nQed.\n\nLemma to_front_Permutation {X:Type} :\n  forall (l:list (nat * X)) key,\n    Permutation l (to_front l key).\nProof.\n  intros.\n  induction l.\n  { constructor. }\n  { simpl. destruct (fst a =? key) eqn:HKEY.\n    { apply Permutation_refl. }\n    { destruct (to_front l key) eqn:HFL.\n      { inv IHl; apply Permutation_refl. }\n      { assert (HH:Permutation (a::l) (a::p::l0)).\n        { apply perm_skip. assumption. }\n        assert (HH2:Permutation (a::p::l0) (p::a::l0)).\n        { apply perm_swap. }\n        eapply perm_trans. eassumption. assumption.\n      }\n    }\n  }\nQed.\n\n\n(*******************************************\n      Minimum/maximum value of list nat\n *******************************************)\n\nDefinition list_max (n:nat) (l:list nat): Prop :=\n  List.In n l /\\ List.Forall (fun m => m <= n) l.\n\nDefinition list_min (n:nat) (l:list nat): Prop :=\n  List.In n l /\\ List.Forall (fun m => m >= n) l.\n\nLemma list_minmax:\n  forall (l:list nat) n m\n         (HMIN:list_min n l)\n         (HMAX:list_max m l),\n    List.Forall (fun x => n <= x <= m) l.\nProof.\n  intros.\n  eapply Forall_and.\n  eapply HMIN.\n  eapply HMAX.\nQed.\n\nLemma list_min_cons:\n  forall x l y\n         (HMIN:list_min x l)\n         (HLE:x <= y),\n    list_min x (y::l).\nProof.\n  intros.\n  unfold list_min in *.\n  inv HMIN.\n  split. right. eauto.\n  rewrite List.Forall_forall in *. intros.\n  destruct H1. omega. apply H0. ss.\nQed.\n\nLemma list_min_cons2:\n  forall x l y\n         (HMIN:list_min x l)\n         (HLE:y <= x),\n    list_min y (y::l).\nProof.\n  intros.\n  unfold list_min in *.\n  inv HMIN.\n  split. left. eauto.\n  rewrite List.Forall_forall in *. intros.\n  destruct H1. omega. apply H0 in H1. omega.\nQed.\n\nLemma list_max_cons:\n  forall x l y\n         (HMAX:list_max x l)\n         (HLE:x >= y),\n    list_max x (y::l).\nProof.\n  intros.\n  unfold list_max in *.\n  inv HMAX.\n  split. right. eauto.\n  rewrite List.Forall_forall in *. intros.\n  destruct H1. omega. apply H0. ss.\nQed.\n\nLemma list_max_cons2:\n  forall x l y\n         (HMIN:list_max x l)\n         (HLE:y >= x),\n    list_max y (y::l).\nProof.\n  intros.\n  unfold list_max in *.\n  inv HMIN.\n  split. left. eauto.\n  rewrite List.Forall_forall in *. intros.\n  destruct H1. omega. apply H0 in H1. omega.\nQed.\n\nLemma list_minmax_le:\n  forall x l y\n         (HMIN:list_min x l)\n         (HMAX:list_max y l),\n    x <= y.\nProof.\n  intros.\n  unfold list_max in *.\n  unfold list_min in *.\n  rewrite List.Forall_forall in *.\n  inv HMIN. inv HMAX.\n  apply H0 in H1. omega.\nQed.\n\nLemma list_min_one:\n  forall i, list_min i [i].\nProof.\n  intros. unfold list_min. split. ss. eauto.\n  constructor. eauto. constructor.\nQed.\n\nLemma list_max_one:\n  forall i, list_max i [i].\nProof.\n  intros. unfold list_max. split. ss. eauto.\n  constructor. eauto. constructor.\nQed.\n\nLemma list_minmax_lt:\n  forall x l y a b\n         (HMIN:list_min x l)\n         (HMAX:list_max y l)\n         (HIN1:List.In a l)\n         (HIN2:List.In b l)\n         (HNEQ:a <> b),\n    x < y.\nProof.\n  intros.\n  unfold list_max in *.\n  unfold list_min in *.\n  rewrite List.Forall_forall in *.\n  inv HMIN. inv HMAX.\n  destruct (a <=? b) eqn:HLE.\n  { rewrite Nat.leb_le in HLE.\n    apply H0 in HIN1. apply H2 in HIN2. omega. }\n  { rewrite Nat.leb_gt in HLE.\n    apply H0 in HIN2. apply H2 in HIN1. omega. }\nQed.\n\nLemma list_min_Permutation:\n  forall x l  l'\n         (HMIN:list_min x l)\n         (HPERM:Permutation l l'),\n    list_min x l'.\nProof.\n  intros.\n  unfold list_min in *.\n  inv HMIN.\n  exploit Permutation_in. eassumption. eassumption. intros.\n  split. ss.\n  rewrite List.Forall_forall in *.\n  intros. eapply H0. \n  eapply Permutation_in. eapply Permutation_sym in HPERM. eassumption.\n  ss.\nQed.\n\nLemma list_max_Permutation:\n  forall x l  l'\n         (HMAX:list_max x l)\n         (HPERM:Permutation l l'),\n    list_max x l'.\nProof.\n  intros.\n  unfold list_max in *.\n  inv HMAX.\n  exploit Permutation_in. eassumption. eassumption. intros.\n  split. ss.\n  rewrite List.Forall_forall in *.\n  intros. eapply H0. \n  eapply Permutation_in. eapply Permutation_sym in HPERM. eassumption.\n  ss.\nQed.\n\nLemma list_min_exists:\n  forall i I,\n    exists i', list_min i' (i::I).\nProof.\n  intros.\n  induction I.\n  { exists i. apply list_min_one. }\n  { inv IHI.\n    destruct (a <? x) eqn:HLE.\n    { exists a. rewrite Nat.ltb_lt in HLE.\n      constructor.\n      right. left. ss.\n      inv H. inv H1. constructor. omega. constructor. ss.\n      rewrite List.Forall_forall in *. intros. apply H4 in H. omega.\n    }\n    { rewrite Nat.ltb_ge in HLE.\n      exists x. inv H. constructor. inv H0.\n      constructor. ss. right. right. ss.\n      inv H1. constructor. ss. constructor. omega.\n      ss.\n    }\n  }\nQed.\n\nLemma list_max_exists:\n  forall i I,\n    exists i', list_max i' (i::I).\nProof.\n  intros.\n  induction I.\n  { exists i. apply list_max_one. }\n  { inv IHI.\n    destruct (x <? a) eqn:HLE.\n    { exists a. rewrite Nat.ltb_lt in HLE.\n      constructor.\n      right. left. ss.\n      inv H. inv H1. constructor. omega. constructor. ss.\n      rewrite List.Forall_forall in *. intros. apply H4 in H. omega.\n    }\n    { rewrite Nat.ltb_ge in HLE.\n      exists x. inv H. constructor. inv H0.\n      constructor. ss. right. right. ss.\n      inv H1. constructor. ss. constructor. omega.\n      ss.\n    }\n  }\nQed.\n\nLemma list_max_inj_l:\n  forall n n' l\n         (H1:list_max n l)\n         (H2:list_max n' l),\n    n = n'.\nProof.\n  intros.\n  unfold list_max in *.\n  inv H1. inv H2.\n  rewrite List.Forall_forall in *.\n  apply H3 in H. apply H0 in H1. omega.\nQed.\n\nLemma list_min_inj_l:\n  forall n n' l\n         (H1:list_min n l)\n         (H2:list_min n' l),\n    n = n'.\nProof.\n  intros.\n  unfold list_min in *.\n  inv H1. inv H2.\n  rewrite List.Forall_forall in *.\n  apply H3 in H. apply H0 in H1. omega.\nQed.\n\nLemma list_min_In:\n  forall x n l\n         (HMIN:list_min x (n::l))\n         (HIN:List.In n l),\n    list_min x l.\nProof.\n  intros.\n  unfold list_min in *.\n  inv HMIN.\n  rewrite List.Forall_forall in *.\n  split. inv H. ss. ss. intros. eapply H0. right. ss.\nQed.\n\nLemma list_max_In:\n  forall x n l\n         (HMIN:list_max x (n::l))\n         (HIN:List.In n l),\n    list_max x l.\nProof.\n  intros.\n  unfold list_max in *.\n  inv HMIN.\n  rewrite List.Forall_forall in *.\n  split. inv H. ss. ss. intros. eapply H0. right. ss.\nQed.\n\nLemma list_min_swap:\n  forall n m x l\n         (HMIN:list_min x (n::m::l)),\n    list_min x (m::n::l).\nProof.\n  intros.\n  inv HMIN.\n  apply In_swap in H. split. ss.\n  rewrite List.Forall_forall in *.\n  intros. apply In_swap in H1. apply H0. ss.\nQed.\n\nLemma list_max_swap:\n  forall n m x l\n         (HMAX:list_max x (n::m::l)),\n    list_max x (m::n::l).\nProof.\n  intros.\n  inv HMAX.\n  apply In_swap in H. split. ss.\n  rewrite List.Forall_forall in *.\n  intros. apply In_swap in H1. apply H0. ss.\nQed.\n\nLemma list_min_hd:\n  forall x n l\n         (HMIN:list_min x (n :: l)),\n    x <= n.\nProof.\n  intros.\n  unfold list_min in HMIN.\n  inv HMIN.\n  inv H. ss.\n  rewrite List.Forall_forall in H0.\n  apply H0. left. ss.\nQed.\n\nLemma list_max_hd:\n  forall x n l\n         (HMAX:list_max x (n :: l)),\n    n <= x.\nProof.\n  intros.\n  unfold list_max in HMAX.\n  inv HMAX.\n  inv H. ss.\n  rewrite List.Forall_forall in H0.\n  apply H0. left. ss.\nQed.\n\n\n(*******************************************\n      Lemmas about natural numbers\n *******************************************)\n\nLemma mod_gt:\n  forall n m p (HP:p > 0), n mod p > m -> n > m.\nProof.\n  intros.\n  unfold \"mod\" in H.\n  destruct p. inv H.\n  assert (p <= p). omega.\n  apply Nat.divmod_spec with (x := n) (q := 0) in H0.\n  destruct (Nat.divmod n p 0 p).\n  simpl in *.\n  destruct H0.\n  rewrite Nat.mul_0_r in *.\n  rewrite Nat.sub_diag in *.\n  rewrite Nat.add_0_r in *.\n  rewrite Nat.add_0_r in *.\n  rewrite H0.\n  eapply Nat.lt_le_trans.\n  eapply H.\n  apply le_plus_r.\nQed.\n\nLemma mod_inj_l:\n  forall a b r,\n    a = b -> a mod r = b mod r.\nProof. intros. congruence. Qed.\n\nLemma mod_mul_eq:\n  forall a1 a2 b c (H1:b <> 0) (H2:c <> 0)\n         (HEQ:a1 mod (b * c) = a2 mod (b * c)),\n    a1 mod b = a2 mod b.\nProof.\n  intros.\n  assert (b * c <> 0).\n  { destruct b; destruct c; try congruence. simpl. intros H. congruence. }\n  assert (Ha1 := Nat.div_mod a1 (b * c) H).\n  assert (Ha2 := Nat.div_mod a2 (b * c) H).\n  rewrite HEQ in Ha1.\n  rewrite Ha2, Ha1.\n  rewrite Nat.add_mod; try omega.\n  rewrite Nat.mul_mod; try omega.\n  rewrite Nat.mul_mod with (a := b) (b := c); try congruence.\n  rewrite Nat.mod_same; try congruence.\n  rewrite Nat.mod_0_l; try omega.\n  rewrite Nat.mod_0_l; try omega. simpl.\n  rewrite Nat.add_mod; try omega.\n  rewrite Nat.mul_mod; try omega.\n  rewrite Nat.mul_mod with (a := b) (b := c); try congruence.\n  rewrite Nat.mod_same; try omega. simpl.\n  rewrite Nat.mod_0_l; try omega. simpl.\n  rewrite Nat.mod_0_l; try omega. simpl.\n  reflexivity.\nQed.  \n\nLemma double_2_pow:\n  forall n, Nat.double (2 ^ n) = 2 ^ (1 + n).\nProof.\n  intros.\n  unfold Nat.double.\n  simpl. omega.\nQed.\n\nLemma shiftl_2_nonzero:\n  forall n, Nat.shiftl 2 n <> 0.\nProof.\n  intros HH.\n  rewrite Nat.shiftl_eq_0_iff.\n  omega.\nQed.\n\nLemma shiftl_lle:\n  forall n m n'\n         (HLE:n <= n'),\n    Nat.shiftl n m <= Nat.shiftl n' m.\nProof.\n  intros.\n  induction m.\n  { ss. }\n  { simpl.\n    unfold Nat.double. lia. }\nQed.\n\nLemma shiftl_2_decompose:\n  forall n1 n2 (HPOS1: 0 < n1) (HPOS2:0 < n2) (H:n1 < n2),\n    Nat.shiftl 2 (n2 - 1) =\n    Nat.shiftl 2 (n1 - 1) * Nat.shiftl 2 (n2 - n1 - 1).\nProof.\n  intros.\n  assert (2 = Nat.shiftl 1 1). reflexivity.\n  rewrite H0.\n  repeat (rewrite Nat.shiftl_shiftl).\n  destruct n1; destruct n2; try omega.\n  simpl.\n  repeat (rewrite Nat.sub_0_r).\n  repeat (rewrite Nat.shiftl_1_l).\n  repeat (rewrite double_2_pow).\n  rewrite <- Nat.pow_add_r.\n  assert (1 + n2 = 1 + n1 + (1 + (n2 - n1 - 1))).\n  { simpl.  omega. }\n  rewrite <- H1. reflexivity.\nQed.\n\n(*** Special thanks to Youngju Song (@alxest)!! *****)\nSection ABCDD.\n\n  Variable K: nat.\n  Hypothesis NONZERO: K <> 0.\n\n  Lemma eqm_add_eqm\n        a b ctx\n        (EQM: a mod K = b mod K)\n    :\n      (a + ctx) mod K = (b + ctx) mod K\n  .\n  Proof.\n    rewrite <- Nat.add_mod_idemp_l; ss. symmetry.\n    rewrite <- Nat.add_mod_idemp_l; ss. congruence.\n  Qed.\n\n  Lemma eqm_iff\n        min\n        a b\n    :\n      <<EQM: a mod K = b mod K>> <->\n      <<EQM: exists p q, a + K * p = b + K * q /\\ min <= p /\\ min <= q>>\n  .\n  Proof.\n    split; i; des.\n    - remember (a mod K) as x.\n      symmetry in H. symmetry in Heqx.\n      destruct x; ss.\n      { rewrite Nat.mod_divides in *; ss. des.\n        exists (min + c), (min + c0).\n        esplits; try lia.\n      }\n      rewrite Nat.mod_eq in *; ss.\n      apply Nat.add_sub_eq_nz in H; ss.\n      apply Nat.add_sub_eq_nz in Heqx; ss.\n      rewrite <- H. rewrite <- Heqx.\n      exists (min + (b / K)), (min + (a / K)).\n      esplits; try lia.\n    - red.\n      destruct (le_lt_dec p q).\n      + assert(a = b + K * q - K * p) by lia.\n        rewrite <- Nat.add_sub_assoc in *; cycle 1.\n        { apply Nat.mul_le_mono_l. lia. }\n        rewrite <- Nat.mul_sub_distr_l in *.\n        rewrite H2.\n        replace (b + K * (q - p)) with ((q - p) * K + b) by lia.\n        erewrite eqm_add_eqm with (b := 0); cycle 1.\n        { rewrite Nat.mod_mul; ss. rewrite Nat.mod_0_l; ss. }\n        f_equal.\n      + assert(b = a + K * p - K * q) by lia.\n        rewrite <- Nat.add_sub_assoc in *; cycle 1.\n        { apply Nat.mul_le_mono_l. lia. }\n        rewrite <- Nat.mul_sub_distr_l in *.\n        rewrite H2.\n        replace (a + K * (p - q)) with ((p - q) * K + a) by lia.\n        erewrite eqm_add_eqm with (b := 0); cycle 1.\n        { rewrite Nat.mod_mul; ss. rewrite Nat.mod_0_l; ss. }\n        f_equal.\n  Qed.\n\n  Lemma eqm_sub_eqm\n        l0 l1 r0 r1 delta\n        (EQML: l0 mod K = (delta + l1) mod K)\n        (EQMR: r0 mod K = (delta + r1) mod K)\n        (BOUND0: r0 < K <= l0)\n        (BOUND1: r1 < K <= l1)\n    :\n      (l0 - r0) mod K = (l1 - r1) mod K\n  .\n  Proof.\n    apply (eqm_iff 0) in EQMR. des.\n    apply (eqm_iff (r0 + r1 + p + q)) in EQML. des.\n    eapply (eqm_iff 0).\n    exists (p0 - p), (q0 - q).\n    esplits; try lia.\n    assert(l0 + K * p0 - (r0 + K * p) = delta + l1 + K * q0 - (delta + r1 + K * q)) by lia.\n    rewrite Nat.sub_add_distr in *.\n    replace (l0 + K * p0 - r0 - K * p) with (l0 - r0 + K * p0 - K * p) in H by lia.\n\n    rewrite ! Nat.mul_sub_distr_l in *.\n\n    rewrite Nat.add_sub_assoc; cycle 1.\n    { apply Nat.mul_le_mono_l. lia. }\n    rewrite H.\n    rewrite ! Nat.sub_add_distr.\n    replace (delta + l1 + K * q0 - delta - r1 - K * q) with\n        (l1 + K * q0 - r1 - K * q) by lia.\n    replace (l1 + K * q0 - r1 - K * q) with\n        (l1 - r1 + K * q0 - K * q) by lia.\n    rewrite Nat.add_sub_assoc; cycle 1.\n    { apply Nat.mul_le_mono_l. lia. }\n    ss.\n  Qed.\n\n  (* a precious lemma. *)\n  Theorem addm_subm_eq\n          a y x\n    :\n      (((a + x) mod K) + K - ((a + y) mod K)) mod K =\n      ((x mod K) + K - (y mod K)) mod K\n  .\n  Proof.\n    assert(BDD0: (a + y) mod K < K).\n    { eapply Nat.mod_upper_bound; ss. }\n    assert(BDD1: y mod K < K).\n    { eapply Nat.mod_upper_bound; ss. }\n\n    eapply eqm_sub_eqm with (delta := a).\n    - rewrite Nat.add_assoc.\n      erewrite eqm_add_eqm with (a := (a + x) mod K); cycle 1.\n      { apply Nat.mod_mod; ss. }\n      replace (a + x mod K + K) with (x mod K + (a + K)) by lia.\n      erewrite eqm_add_eqm with (a := x mod K); cycle 1.\n      { apply Nat.mod_mod; ss. }\n      f_equal. lia.\n    - rewrite Nat.add_mod_idemp_r; ss.\n      rewrite Nat.mod_mod; ss.\n    - lia.\n    - lia.\n  Qed.\n\nEnd ABCDD.\n\nLemma nem_add_nem\n      K a b ctx\n      (HK:K > 0)\n      (EQM: a mod K <> b mod K)\n  :\n    (a + ctx) mod K <> (b + ctx) mod K\n.\nProof.\n  intros HH. apply EQM. clear EQM.\n(*       (((a + x) mod K) + K - ((a + y) mod K)) mod K =\n      ((x mod K) + K - (y mod K)) mod K\n*)\n  rewrite <- Nat.mod_mod in HH; try omega.\n  rewrite Nat.add_comm with (n := a) in HH.\n  rewrite Nat.add_comm with (n := b) in HH.\n  rewrite <- Nat.mod_mod with (a := (ctx + b)) in HH; try omega.\n  apply eqm_add_eqm with (ctx := K - ((ctx + 0) mod K)) in HH; try omega.\n  rewrite Nat.add_sub_assoc in HH.\n  rewrite Nat.add_sub_assoc in HH.\n  rewrite addm_subm_eq in HH; try omega.\n  rewrite addm_subm_eq in HH; try omega.\n  rewrite Nat.mod_0_l in HH; try omega.\n  rewrite Nat.sub_0_r in HH.\n  rewrite Nat.sub_0_r in HH.\n  rewrite <- Nat.mul_1_l with (n := K) in HH at 2.\n  rewrite <- Nat.mul_1_l with (n := K) in HH at 5.\n  rewrite Nat.mod_add in HH; try omega.\n  rewrite Nat.mod_add in HH; try omega.\n  rewrite Nat.mod_mod in HH; try omega.\n  rewrite Nat.mod_mod in HH; try omega.\n  assert (HH2 := Nat.mod_upper_bound (ctx + 0) K).\n  exploit HH2. omega. intros. omega.\n  assert (HH2 := Nat.mod_upper_bound (ctx + 0) K).\n  exploit HH2. omega. intros. omega.\nQed.\n\nLemma mod_add_eq:\n  forall a b c d (HD:d > 0),\n  ((a + b) mod d =? (a + c) mod d) = ((b mod d) =? (c mod d)).\nProof.\n  intros.\n  destruct (b mod d =? c mod d) eqn:HE.\n  { rewrite Nat.eqb_eq in HE.\n    apply eqm_add_eqm with (ctx := a) in HE.\n    rewrite Nat.add_comm in HE.\n    rewrite Nat.add_comm with (n := c) in HE.\n    rewrite Nat.eqb_eq. ss.\n    omega.\n  }\n  { rewrite Nat.eqb_neq in *.\n    rewrite Nat.add_comm.\n    rewrite Nat.add_comm with (m := c).\n    apply nem_add_nem. ss. ss.\n  }\nQed.\n\n\nLemma andb_inj_r:\n  forall b1 b2 b3 (H:b2 = b3),\n    b1 && b2 = b1 && b3.\nProof. intros. subst. reflexivity. Qed.\n\n", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/Common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7813494154376569}}
{"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 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(** 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 (selection_sort'_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: 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/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.9149009491921664, "lm_q1q2_score": 0.7812455814001309}}
{"text": "Require Export Tactics.\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\nTheorem plus_fact_is_true : plus_fact.\nProof. reflexivity. Qed.\n\nDefinition  is_three (n : nat) : Prop := 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. inversion H. reflexivity.\nQed.\n\nExample and_example : 3 + 4 = 7 /\\ 2*2 = 4.\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) 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  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 * 2 = 4 *) reflexivity.\nQed.\n    \nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  apply and_intro.\n  - (* n = 0 *) induction n as [| n'].\n    + reflexivity.\n    + inversion H.\n  - (* m = 0 *) induction m as [| m'].\n    + reflexivity.\n    + rewrite plus_comm in H. 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 \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  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.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n  - (* left *) apply HQ.\n  - (* right *) apply HP.\nQed.\n\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 or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - (* n = 0 *)\n    rewrite Hn. reflexivity.\n  - (* 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  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 [| n].\n  - intros m H. rewrite mult_0_l in H. left. apply H.\n  - intros [| m].\n    + right. reflexivity.\n    + intros H. inversion H.\nQed.\n\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\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\n(*Notation \"¬ x\" := (not x) : type_scope.*)\n\nCheck not.\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  apply ex_falso_quodlibet. apply H. assumption.\nQed.\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\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. 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.\nQed.\n\nTheorem double_neg : forall P : Prop,\n    P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H.\nQed.\n\nTheorem contrapositive : forall (P Q : Prop),\n    (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H H0.\n  unfold not in H0.\n  unfold not.\n  intros P'.\n  apply H0.\n  apply H.\n  apply P'.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop, ~ (P /\\ ~P).\nProof.\n  intros.\n  unfold not. intros H. destruct H.\n  apply H0. assumption.\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\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 *)\n    reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof.\n  apply I.\nQed.\n\nModule MyIff.\n\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 P Q [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. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem iff_refl : forall P : Prop,\n    P <-> P.\nProof.\n  intros P.\n  split.\n  - (* P -> P *)\n    intros H. apply H.\n  - intros H. apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n    (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  split.\n  - (* P -> R *)\n    intros H1.\n    apply H0.\n    apply H.\n    assumption.\n  - (* R -> P *)\n    intros H1.\n    apply H.\n    apply H0.\n    assumption.\nQed.\n\n    \nTheorem or_distributes_over_and : forall P Q R: Prop,\n    P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  split.\n  - (* -> *)\n    intros H. inversion H.\n    + split.\n      { left. apply H0. }\n      { left. apply H0. }\n    + split.\n      { right. apply H0. }\n      { right. apply H0. }\n  - (* <- *)\n    intros H. inversion H.\n    + destruct H1.\n      { left. apply H1. }\n      { destruct H0.\n        - left. apply H0.\n        - right. split.\n          + apply H0.\n          + apply H1. }\nQed.\n\nRequire Import Coq.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\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) -> (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.\n  intros x.\n  destruct x.\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. split.\n  - (*->*) intros H. destruct H as [X' H]. destruct H as [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' HP]. exists X'. left. apply HP.\n    + destruct HQ as [X' HQ]. exists X'. right. apply HQ.\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.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 : forall n,\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\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 A B f l y. split.\n  - (* -> *) intros H. induction l as [|x' l' IHl'].\n    + (* l = nil, contradiction *)\n      simpl in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl in H. destruct H as [H1 | H2].\n      { exists x'. split.\n        - apply H1.\n        - simpl. left. reflexivity. }\n      { apply IHl' in H2. destruct H2 as [x2 H2]. exists x2. split.\n        - apply proj1 in H2. apply H2.\n        - simpl. right. apply proj2 in H2. apply H2. }\n  - (* <- *) intros H. induction l as [| x' l' IHl'].\n    + (* l = [] *)\n      simpl in H. destruct H as [x' H]. apply proj2 in H. contradiction.\n    + (* l = x' :: l' *)\n      simpl. simpl in H. destruct H as [x'' H].\n      inversion H. destruct H1 as [H2 | H3].\n      { left. rewrite H2. apply H0. }\n      { right. apply IHl'. exists x''. split.\n        - apply H0.\n        - apply H3. }\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'. split.\n  - (* -> *)\n    intros H. induction l.\n    + simpl. simpl in H. right. apply H.\n    + simpl. simpl in H. destruct H.\n      { left. left. apply H. }\n      { apply IHl in H. apply or_assoc. right. apply H. }\n  - (* <- *)\n    intros H. induction l.\n    + simpl. simpl in H. destruct H.\n      { contradiction. }\n      { apply H. }\n    + simpl. simpl in H. apply or_assoc in H. destruct H as [H1 | [H2 | H3]].\n      { left. apply H1. }\n      { right. apply IHl. left.  apply H2.\n      } { right. apply IHl. right. apply H3. }\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 T P l. split.\n  - (* -> *) intros H. induction l.\n    + simpl. reflexivity.\n    + simpl. split.\n      { apply H. simpl. left. reflexivity. }\n      { apply IHl. intros x0 H0. apply H. simpl. right. apply H0. }\n  - (* <- *) intros H. induction l.\n    + simpl. intros x0 H0. contradiction.\n    + simpl. intros x0 H0. destruct H0 as [|H1 H2].\n      { simpl in H. apply proj1 in H. rewrite H0 in H. apply H. }\n      { simpl in H. apply proj2 in H.\n        apply IHl with x0 in H. apply H. apply H1. }\nQed.\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\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 Hodd Heven.\n  unfold combine_odd_even. destruct (oddb n) eqn: H.\n  - apply Hodd. reflexivity.\n  - apply Heven. 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 Hcomb Hodd.\n  unfold combine_odd_even in Hcomb.\n  rewrite Hodd in Hcomb. assumption.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n Hcomb Heven.\n  unfold combine_odd_even in Hcomb.\n  rewrite Heven in Hcomb. assumption.\nQed.\n\nLemma plus_comm3 :\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\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\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\nAxiom functional_extensionality :\n  forall {X Y : Type}\n         {f g : X -> Y},\n    (forall (x:X) , f x = g x) -> f = g.\n\nExample funtion_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\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\nTheorem app_nil_l : forall(X:Type), forall l:list X,\n      [] ++ l = l.\nProof.\n  reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X. apply functional_extensionality.\n  intros x. induction x as [|x' lx].\n  - simpl. unfold tr_rev. simpl. reflexivity.\n  - simpl.\n    rewrite <- IHlx. simpl tr_rev.\n    unfold tr_rev. simpl rev_append.\nAbort.\n (* rev_append lx [ ] = rev lx \n          I think this is the problem. *)\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).\n(* for any n in N there exists k s.t. k = 2n or k = 2n+1. *)\nProof.\n  intros n. induction n as [|n' IHn'].\n  - simpl. exists 0. simpl. reflexivity.\n  - destruct (evenb n') eqn: Heq.\n    + rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists n''. rewrite IHn'. reflexivity.\n    + rewrite evenb_S. rewrite Heq. simpl. destruct IHn' as [n'' IHn'].\n      exists (n'' + 1). rewrite IHn'. rewrite double_plus. rewrite double_plus.\n      rewrite plus_n_Sm. rewrite <- plus_1_l. rewrite <- plus_n_Sm.\n      rewrite <- (plus_1_l (n'' + n'')). rewrite plus_comm.\n      rewrite plus_assoc. rewrite (plus_comm 1).\n      rewrite plus_assoc. 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 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\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\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. split.\n    + rewrite andb_commutative in H. apply andb_true_elim2 in H. apply H.\n    + apply andb_true_elim2 in H. apply H.\n  - (* <- *) intros H. inversion H. rewrite H0. rewrite H1. reflexivity.\nQed.\n\n\n\nLemma orb_true_iff : forall b1 b2,\n    b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - (* -> *) intros H.\n    destruct b1.\n    + simpl. left. reflexivity.\n    + simpl. right. assumption.\n  - (* <- *) intros H.\n    destruct H as [H1 | H2].\n    + rewrite H1. simpl. reflexivity.\n    + rewrite H2. 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 x y. unfold not. split.\n  - (* -> *) intros H0 H1. apply beq_nat_true_iff in H1.\n    rewrite H1 in H0. inversion H0.\n  - (* <- *) intros H.\n    induction x as [| x'].\n    + induction y as [| y'].\n      { simpl. exfalso. apply H. reflexivity. }\n      { generalize dependent y'. reflexivity. }\n    + induction y as [| y'].\n      { simpl. reflexivity. }\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      \nFixpoint beq_list {A : Type} (beq : A -> A -> bool)\n         (l1 l2 : list A) : bool :=\n  match l1,l2 with\n  | [] , [] => true\n  | [] , _ => false\n  | _ , [] => false\n  | h1 :: t1, h2 :: t2 => (andb (beq h1 h2) (beq_list beq t1 t2))\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 l1 l2. split.\n  - (* -> *) generalize dependent l2.\n    induction l1 as [| h1 l1' IHl1].\n    + induction l2 as [| h2 l2' IHl2].\n      { simpl. reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (beq h1 h2) eqn:Heq.\n        + apply H in Heq. rewrite <- Heq.\n          assert (l1' = l2' -> h1 :: l1' = h1 :: l2') as H2.\n          { intros H3. rewrite H3. reflexivity. }\n          apply H2. apply IHl1. apply H1.\n        + inversion H1. }\n  - (* <- *) generalize dependent l2.\n    induction l1 as [| h1 l1' IHl1'].\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. reflexivity. }\n      { simpl. intros H1. inversion H1. }\n    + induction l2 as [| h2 l2' IHl2'].\n      { simpl. intros H1. inversion H1. }\n      { simpl. intros H1. destruct (beq h1 h2) eqn:Heq.\n        + apply IHl1'. apply H in Heq. rewrite Heq in H1.\n          assert (h1 :: l1' = h1 :: l2' -> l1' = l2') as H2.\n          { intros H3. inversion H1. reflexivity. }\n          apply H2. rewrite Heq. apply H1.\n        + inversion H1. apply H in H2. rewrite H2 in Heq. symmetry. apply Heq. }\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\nTheorem forallb_true_iff : forall X test (l : list X),\n    forallb test l = true <-> All (fun x => test x = true) l.\nProof.\nAbort.\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. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion 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) (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. intros P H. apply H.\n  right. intros. apply H. left. apply H0.\nQed.\n", "meta": {"author": "ihasson", "repo": "coq", "sha": "0da545a4966f48b1874183812f61f54eac7b1976", "save_path": "github-repos/coq/ihasson-coq", "path": "github-repos/coq/ihasson-coq/coq-0da545a4966f48b1874183812f61f54eac7b1976/olderversions/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8902942326713409, "lm_q1q2_score": 0.7812125174929007}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_numeric.\n\n(**\nSum properties for proving graph theorems.\n**)\n\nLemma sum_i_to_n (n : nat) :\n  2 * sum' n (fun i => i) = n * (n - 1).\nProof.\n  induction n.\n  - auto.\n  - simpl_sum.\n    set (y := sum' n (fun x => x)) in *.\n    ring_simplify.\n    ring_simplify in IHn.\n    rewrite IHn.\n    nia.\nQed.\n\nLemma sum_sum_n (n : nat) :\n  2 * sum' n (fun x => sum' x (fun y => 1)) = n * (n - 1).\nProof.\n  replace (sum' n (fun x => sum' x (fun y => 1))) with \n  (sum' n (fun x => x)).\n  - apply sum_i_to_n.\n  - apply change_sum'.\n    intros j p.\n    rewrite sum_n_krat_1.\n    + auto.\n    + auto.  (* Kaj je to?? *)\nQed.\n\nTheorem zero_is_not_succ (n k l : nat):\n    (sum' n (fun y : nat => (if Nat.eq_dec 0 (S y) then k else l))) = n * l.\nProof.\n  rewrite (same_sum' n l).\n  - auto.\n  - intros j p.\n    destruct (Nat.eq_dec 0 (S j)); omega.\nQed.\n\nTheorem end_is_not_included (n k l : nat):\n    (sum' n (fun y : nat => (if Nat.eq_dec n y then k else l))) = n * l.\nProof.\n  rewrite (same_sum' n l).\n  - auto.\n  - intros j p.\n    destruct (Nat.eq_dec n j); omega.\nQed.\n\nTheorem nat_eq_dec_reverse (n k l x : nat):\n  (sum' n (fun y : nat => (if Nat.eq_dec x y then k else l))) = \n  (sum' n (fun y : nat => (if Nat.eq_dec y x then k else l))).\nProof.\n  apply change_sum.\n  intros j p.\n  destruct (Nat.eq_dec x j); destruct (Nat.eq_dec j x); omega.\nQed.\n\nTheorem sum_succ_transformation (n k l x: nat) (p: 0 < x < 1 + n):\n  sum' n (fun y : nat => if Nat.eq_dec x (S y) then 1 else 0) = \n  sum' n (fun y : nat => if Nat.eq_dec (x - 1) y then 1 else 0).\nProof.\n  apply change_sum.\n  intros j q.\n  destruct (Nat.eq_dec x (S j)); destruct (Nat.eq_dec (x - 1) j); omega.\nQed.\n\nTheorem one_is_found (x y : nat) (p : y < x):\n  sum' x (fun x0 : nat => if Nat.eq_dec y x0 then 1 else 0) = 1.\nProof.\n  induction x.\n  - omega.\n  - rewrite sum'_S.\n    destruct (Nat.eq_dec y x).\n    + assert (sum' x (fun x0 : nat => if Nat.eq_dec y x0 then 1 else 0) =\n              sum' x (fun x0 : nat => 0)).\n      * apply change_sum.\n        intros j q.\n        destruct (Nat.eq_dec y j); auto; omega.\n      * rewrite (sum_n_krat_k x 0) in H.\n        rewrite H.\n        omega.\n    + rewrite IHx; omega.\nQed.\n\nTheorem one_is_found_general_rv (x y k l : nat) (p : y < x):\n  sum' x (fun x0 : nat => if Nat.eq_dec x0 y then k else l) = k + (x - 1) * l.\nProof.\n  induction x.\n  - omega.\n  - rewrite sum'_S.\n    destruct (Nat.eq_dec x y).\n    + assert (sum' x (fun x0 : nat => if Nat.eq_dec x0 y then k else l) =\n              sum' x (fun x0 : nat => l)).\n      * apply change_sum.\n        intros j q.\n        destruct (Nat.eq_dec j y); auto; omega.\n      * rewrite (sum_n_krat_k x l) in H.\n        rewrite H.\n        replace (S x - 1) with x; omega.\n    + rewrite IHx.\n      (* lia ne zna *)\n      (* nia pa zna ze tu*)\n      (* seveda to je nelinearna enacba :) ... ne vem zakaj sem spregledal *)\n      * nia.\n      * omega.\nQed.\n\nTheorem one_is_found_general (x y k l : nat) (p : y < x):\n  sum' x (fun x0 : nat => if Nat.eq_dec y x0 then k else l) = k + (x - 1) * l.\nProof.\n  (*\n  assert (k + (x - 1) * l = \n          sum' x (fun x0 : nat => if Nat.eq_dec x0 y then k else l)) as A.\n  - rewrite (one_is_found_general_rv); auto.\n  - rewrite A.\n    apply change_sum.\n    intros j q.\n    destruct (Nat.eq_dec y j); destruct (Nat.eq_dec j y); omega.\n  *)\n  rewrite nat_eq_dec_reverse.\n  apply one_is_found_general_rv; auto.\nQed.\n\nTheorem one_is_found_rv (x y : nat) (p : y < x):\n  sum' x (fun x0 : nat => if Nat.eq_dec x0 y then 1 else 0) = 1.\nProof.\n  rewrite (one_is_found_general_rv x y 1 0 p).\n  omega.\nQed.\n\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/numeric_extensions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913356558485, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7812024479614921}}
{"text": "Require Export induction.\nRequire Export basics.\n\nModule NatList.\n\nInductive natprod : Type :=\n  | pair (n_1 n_2 : nat).\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 (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m].\n    reflexivity.\nQed.\n\n(* Exercise 1 *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intro p.\n  destruct p as [n m].\n    reflexivity.  \nQed.\n\n(* Exercise 2 *)\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\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 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\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\n(* Exercise 3 *)\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | O :: t => nonzeros t\n  | a :: t => a :: nonzeros t\n  end.\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  | a :: t =>\n    if oddb a then\n      a :: oddmembers t\n    else\n      oddmembers t\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\n(* Exercise 4 *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, l2 => l2\n  | l1, nil => l1\n  | a :: t1, b :: t2 => a :: b :: 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\n(* Exercise 5 *)\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | a :: t =>\n    if a =? v then\n      1 + count v t\n    else\n      count v t\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. reflexivity. Qed.\n\nDefinition add : nat -> bag -> bag := cons.\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  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\n(* Exercise 6 *)\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | nil => nil\n  | a :: t =>\n     if a =? v then\n        t\n      else\n        a :: remove_one v t\n  end.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\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  | a :: t =>\n     if a =? v then\n        remove_all v t\n      else\n        a :: remove_all v t\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 (s1 : bag) (s2 : bag) : bool :=\n  match s1 with\n  | nil => true\n  | a :: t =>\n    if member a s2 then\n      subset t (remove_one a s2)\n    else\n      false\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n\n(* Exercise 7 *)\n\nLemma bag_subset_common: forall (b1 b2 : bag) (a : nat),\n  (subset b1 b2 = true) -> (subset (a :: b1) (a :: b2) = true).\nProof.\n  intros b1 b2 a H.\n  simpl. unfold member. unfold count.\n\n  assert (H2 : forall n : nat, n =? n = true). {\n    intros n. induction n as [| n' IH].\n    - reflexivity.\n    - simpl. rewrite -> IH. reflexivity.\n  }\n\n  rewrite -> (H2 a).\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem bag_self_subset: forall b : bag,\n  subset b b = true.\nProof.\n  intros b.\n  induction b as [| a t IH].\n  - reflexivity.\n  - rewrite -> (bag_subset_common t t a IH).\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. 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.\n\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  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\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. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'.\n    reflexivity.\nQed.\n\n(* Exercise 8 *)\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [| a l' IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> IH.\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 [| a l' IH].\n  - rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IH. rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. simpl. rewrite -> IH.\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  rewrite -> (app_assoc (l1 ++ l2) l3 l4).\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 [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. destruct a.\n    + reflexivity.\n    + reflexivity.\nQed.\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  | a :: l1', b :: l2' =>\n    if a =? b then eqblist l1' l2'\n    else false\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  induction l as [| a l' IH].\n  - reflexivity.\n  - simpl. rewrite -> nat_equals_self. rewrite <- IH.\n    reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall s : bag,\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s.\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  induction s as [| a s' IH].\n  - reflexivity.\n  - destruct a.\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IH. reflexivity.\nQed.\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\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42 (* arbitrary! *)\n  | a :: l' =>\n    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' =>\n    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\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: _ => Some a\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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l default.\n  destruct l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\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 : forall x, true = eqb_id x x.\nProof.\n  intro x.\n  destruct x.\n    simpl.\n    rewrite -> nat_equals_self.\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\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 :\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\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    eqb_id x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o.\n  intro H.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n", "meta": {"author": "zhengyao-lin", "repo": "sf-lf", "sha": "69d655ca5779eee56874fcf06f2b8838d16c5224", "save_path": "github-repos/coq/zhengyao-lin-sf-lf", "path": "github-repos/coq/zhengyao-lin-sf-lf/sf-lf-69d655ca5779eee56874fcf06f2b8838d16c5224/src/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.899121388082479, "lm_q1q2_score": 0.7811807278929699}}
{"text": "Require Import Arith.\n\nDefinition sum f := fix s n := match n with O => f O | S x => f n + s x end.\n\nTheorem arith_sum a b n : 2 * sum (fun i => a + i * b) n = S n * (2 * a + n * b).\nProof.\nintros a b n.\ninduction n; simpl; ring_simplify; auto.\nrewrite IHn; ring.\nQed.\n", "meta": {"author": "scottviteri", "repo": "ManipulateProofTrees", "sha": "7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7", "save_path": "github-repos/coq/scottviteri-ManipulateProofTrees", "path": "github-repos/coq/scottviteri-ManipulateProofTrees/ManipulateProofTrees-7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7/ProofSourceFiles/arith_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7810796023289555}}
{"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\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.\nExample test_length1 :\n        length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity. Qed.\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\nModule MumbleBaz.\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\nInductive baz: Type :=\n| x: baz -> baz\n| y: baz -> bool -> baz.\nEnd MumbleBaz.\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments length {X} l.\nArguments app {X} l1 l2.\nArguments rev {X} l.\nArguments snoc {X} l v.\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    | O => nil\n    | S count' => cons n (repeat n count')\n    end.\nExample test_repeat1:\n      repeat true 2 = cons true (cons true nil).\nProof. reflexivity. Qed.\n\nTheorem nil_app: forall (X: Type) (l: list X), app [] l = l.\nProof. reflexivity. Qed.\n\n(* Skipped polymorphic DS *)\n\nDefinition doit3times {X: Type} (f: X -> X) (n: X): X := f (f (f n)).\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nDefinition plus3 := plus 3.\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} (f: X * Y -> Z) (x: X) (y: Y): Z :=\n    f (x, y).\nDefinition prod_uncurry {X Y Z: Type} (f: X -> Y -> Z) (p: X * Y): Z :=\n    match p with (x, y) => f x y end.\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.\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. Admitted.\n\nFixpoint filter {X: Type} (test: X -> bool) (l: list X): list X :=\n    match l with\n    | nil => []\n    | x :: xs => if test x then x :: (filter test xs) else (filter test xs)\n    end.\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 [ [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).\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.\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n    [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ] = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l: list nat): list nat :=\n    filter (fun n => andb (evenb n) (ble_nat 7 n)) l.\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\nDefinition partition {X: Type} (test: X -> bool) (l: list X): list X * list X :=\n    pair (filter test l) (filter (fun n => negb (test n)) l).\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    | nil => []\n    | x :: xs => f x :: map f xs\n    end.\nExample test_map1: map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\nExample test_map2: map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\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\nFixpoint fold {X Y: Type} (f: X -> Y -> Y) (l: list X) (b: Y): Y :=\n    match l with\n    | nil => b\n    | x :: xs => f x (fold f xs b)\n    end.\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\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.\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'.\nDefinition fmostlytrue := override (override ftrue 1 false) 3 false.\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\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.\n    intros b.\n    reflexivity.\nQed.\n\nTheorem unfold_example: forall m n,\n    3 + n = m -> plus3 n + 1 = m + 1.\nProof.\n    intros n m H.\n    unfold plus3.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem override_neq: forall (X: Type) x1 x2 k1 k2 (f: nat -> X),\n    f k1 = x1 -> beq_nat k2 k1 = false -> (override f k2 x2) k1 = x1.\nProof.\n    intros x x1 x2 k1 k2 f H1 H2.\n    unfold override.\n    rewrite -> H2.\n    rewrite -> H1.\n    reflexivity.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8918110490322425, "lm_q1q2_score": 0.781036515750347}}
{"text": "From NAT Require Import Peanos_axioms.\nFrom NAT Require Import Tutorial_World.\nFrom NAT Require Import Addition_World.\nFrom NAT Require Import Function_World.\nFrom NAT Require Import Proposition_World.\n\nSection Advanced_Proposition_World.\n(*Now, let us consider the following proposition. Now if you said the proposition out loud you might wonder what there is to prove. After all, it states that `If P and Q then P and Q.` But this is not strickly true. Rather, we are trying to show that if we have a proof of P, and a proof of Q, that it is possible to construct a proof of P /\\ Q, and as far as Coq is concerned, it does not know our interpretation of these symbols, it only has a notion of the `legal moves` we can make on it.*)\nProposition p_and_q (P Q : Prop) (p : P)(q : Q): P /\\ Q.\nProof.\n    split.\n    exact p. exact q.\nQed.\n(*Next we wish to show that, given a proof of P and Q, that we can construct a proof of Q and P.*)\nProposition and_symm (P Q : Prop) : P /\\ Q -> Q /\\ P.\nProof.\n    intro h. \n    destruct h.\n    split.\n    exact H0. exact H.\nQed.\n(*Finally we wish to shoe that /\\ is a transitive realtion. Bonus points if you have begun to suspect that /\\ is an equivalence relation!*)\nProposition and_trans (P Q R : Prop) : (P /\\ Q) -> (Q /\\ R) -> (P /\\ R ).\nProof.\n    intros h1 h2.\n    destruct h1. destruct h2.\n    split.\n    exact H. exact H2.\nQed.\n\nProposition iff_trans (P Q R : Prop) : (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n    intros h1 h2.\n    split. intro hp.\n    apply h2. apply h1.\n    exact hp.\n    intro hr.\n    apply h1. apply h2. \n    exact hr.\nQed.\n\n\nProposition q_then_or_q ( P Q : Prop) : Q -> (P \\/ Q).\nProof.\n      intro hq.\n      right.\n      exact hq.  \nQed.\n\nProposition or_symm (P Q : Prop) : P \\/ Q -> Q \\/ P.\nProof.\n    intro hpq.\n    case hpq.\n    intro hp.\n    right. exact hp.\n    intro hq.\n    left. exact hq.\nQed.\n(*Another good problem would be to show that or is not transitive. *)\n\nProposition and_or_dist_left (P Q R : Prop) :\n(P /\\ (Q \\/ R)) <-> ((P /\\ Q) \\/ (P /\\ R)).\nProof.\n    split.\n    intro h1.\n    destruct h1 as [hp hq].\n    destruct hq.\n    left. exact (p_and_q (P)(Q)(hp)(H)). \n    right. exact (p_and_q (P)(R)(hp)(H)).\n    intro h.\n    destruct h. destruct H.\n    split. exact H. \n    left. exact H0.\n    destruct H.\n    split. exact H.\n    right. exact H0.\nQed.\n\nProposition contra (P Q : Prop) : (P /\\ ~P) -> Q.\nProof.\n    intro h.\n    destruct h as [p notp].\n    assert False.\n    exact (notp (p)).\n    exfalso. exact H.\nQed.\n\nLemma a_then_b (A B : Prop)(b : B) : A->B.\nProof.\n    intro h. exact b.\nQed.\nLemma prop_assoc (A B C : Prop) : ((A -> B) -> C) -> (A -> (B -> C)).\nProof.\n    intros h h1 h2.\n    assert (A->B). exact (a_then_b (A)(B)(h2)).\n    apply h in H. exact H.\nQed.\n\n(*Logic*)\nDefinition prop_degeneracy := forall A:Prop, A = True \\/ A = False.\n\nDefinition prop_extensionality := forall A B:Prop, (A <-> B) -> A = B.\n\nDefinition excluded_middle := forall A:Prop, A \\/ ~ A.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nLemma False_is_not_true : False <> True.\nProof.\n    intro h. rewrite h. apply True_is_true.\nQed.\n\nLemma True_then_false (h : prop_degeneracy) : (True -> False) = False.\nProof.\n    unfold prop_degeneracy in h. \n    assert ((True -> False) = True \\/ (True -> False) = False).\n    exact (h (True -> False)).\n    case H. intro hq. exfalso.\n    assert (True -> False). rewrite hq. exact True_is_true.\n    apply H0. exact True_is_true.\n    intro h1. exact h1.\nQed.\n(**)\n\nLemma not_true_is_false (h : prop_extensionality) ( hm : excluded_middle) : \n(~True) = False.\nProof.\n    unfold excluded_middle in hm. unfold prop_extensionality in h.\n    apply h. split. \n    intro hp. apply hp. exact True_is_true.\n    \n    intros hp ht. exact hp. \nQed.\n\nLemma prop_equality_right_select (A B C : Prop) :\n((A = B) = C) -> (B = C).\nProof.\nAdmitted.\n\nLemma not_false_is_true (h : prop_degeneracy) : (~False) = True.\nProof.\n    unfold prop_degeneracy in h.\n    assert (((~False) = True)= True \\/ ((~False) = True)= False). \n    exact (h((~False) = True)). \n    case H. intro h1.\n    rewrite h1. exact True_is_true.\n    intro h1. \n    assert (True = False). apply prop_equality_right_select in h1. exact h1.\n    assert (True -> False). intro ht. rewrite <-H0. exact True_is_true.\n    exfalso. rewrite <- H0. exact True_is_true.\nQed.\n\nLemma deg_ext : prop_degeneracy -> prop_extensionality.\nProof.\n    intro h. unfold prop_degeneracy in h. unfold prop_extensionality.\n    intros ha hb H. \n    assert (ha = True \\/ ha = False). exact (h(ha)).\n    assert (hb = True \\/ hb = False). exact (h(hb)).\n    destruct H0. destruct H1.\n    rewrite H0. rewrite H1. reflexivity.\n    exfalso.\n    destruct H. rewrite H0 in H. rewrite H1 in H. rewrite (True_then_false) in H.\n    exact H. exact h.\n    destruct H1.\n    destruct H. rewrite H1 in H2. rewrite H0 in H2. rewrite (True_then_false) in H2.\n    exfalso. exact H2. exact h. \n    rewrite H0. rewrite H1. reflexivity.\nQed.\n\nLemma deg_mid : prop_degeneracy -> excluded_middle.\nProof.\n    unfold prop_degeneracy. unfold excluded_middle. intros h ha.\n    assert (ha = True \\/ ha = False). exact (h(ha)).\n    destruct H. left. rewrite H. exact True_is_true.\n    right. rewrite H.\n    assert ((~ False) = True). apply not_false_is_true. exact h. \n    rewrite H0. exact True_is_true. \nQed.\n\nLemma false_implies (A : Prop): False -> A.\nProof.\n    intro h. exfalso. exact h.\nQed.\nLemma implied_truth (A : Prop) : A -> True. \nProof.\n    intro h. exact True_is_true.\nQed.\nLemma iff_true_then_True (A : Prop) (a : A): A <-> True.\nProof.\n    split.\n    intro h.  exact True_is_true. intro h. exact a. \nQed.\n\nLemma swap_not (A : Prop) (h_ext : prop_extensionality)(h_mid : excluded_middle )\n: ((~A) = True) -> (A = False).\nProof.\n    intro h. \n    unfold prop_extensionality in h_ext. \n    unfold excluded_middle in h_mid.\n    apply h_ext. \n    split. intro ha. \n    assert ((A -> False) <-> False). split. intro H. apply H. exact ha.\n    intros H1 H2. exact H1. apply H. \n    assert ((~ A )= (A -> False)). reflexivity.\n    rewrite <-H0 in H. rewrite h in H.  \n    apply H. exact True_is_true. exact ha. exact (false_implies (A)).\nQed.\n\nLemma swap_not_op (A : Prop) (h_ext : prop_extensionality)(h_mid : excluded_middle )\n: ((~A) = False) -> (A = True).\nProof.\nAdmitted.\n\nLemma mid_ext_deg : \n((prop_extensionality) /\\ (excluded_middle)) -> (prop_degeneracy).\nProof.\n    unfold prop_degeneracy. unfold prop_extensionality. unfold excluded_middle.\n    intro h. destruct h as [h_ext h_mid].\n    intro ha.\n    assert (ha \\/ ~ha). exact (h_mid (ha)). \n    destruct H. \n    assert (ha <-> True). exact (iff_true_then_True (ha)(H)).\n    apply h_ext in H0. \n    left. exact H0.\n    \n    assert (~ha <-> True). split. exact (implied_truth (~ha)).\n    intro ht. exact H.\n    apply h_ext in H0. \n    right.\n    apply (swap_not (ha)) in H0. exact H0. exact h_ext. exact h_mid.\nQed.\n\nProposition ext_mid_iff_deg : ((prop_extensionality) /\\ (excluded_middle)) <-> (prop_degeneracy).\nProof.\n    split. exact mid_ext_deg. intro h. split. apply deg_ext. exact h.\n    apply deg_mid. exact h.\nQed.\n\nProposition contradiction (h: prop_degeneracy) (P : Prop): P <-> ((~P) = False).\nProof.\n    split. intro h1. \n    unfold prop_degeneracy in h.\n    assert (P = True \\/ P = False). exact (h(P)).\n    case H. \n    intro Hp. rewrite Hp. apply not_true_is_false.   \n    apply deg_ext. exact h. apply deg_mid. exact h.\n    intro H1. exfalso. rewrite H1 in h1. exact h1.\n    intro hp.\n    assert ((~P) = True \\/ (~P) = False). exact (h (~P)).\n    case H. \n    intro Hp. exfalso. rewrite <- hp. rewrite Hp. exact True_is_true.  \n    intro Hp. apply (swap_not_op (P)) in Hp. rewrite Hp. exact True_is_true.\n    apply deg_ext. exact h. apply deg_mid. exact h.\nQed.\n\nProposition contrapostive2 (P Q : Prop) : (~Q -> ~P) -> (P -> Q).\nProof.\nAdmitted.\n\nEnd Advanced_Proposition_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/Advanced_Proposition_World.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7808380057569165}}
{"text": "Require Import Logic.Rel.R. \nRequire Import Logic.Rel.Include.\nRequire Import Logic.Rel.Properties.\n\n(* Equivalence relation generated by a given relation on Type a.                *)\nInductive Equiv (a:Type) (r:Rel a) : Rel a :=\n| EquivBase : forall (x y:a), r x y -> Equiv a r x y\n| EquivRefl : forall (x:a), Equiv a r x x\n| EquivSym  : forall (x y:a), Equiv a r x y -> Equiv a r y x\n| EquivTrans: forall (x y z:a), Equiv a r x y -> Equiv a r y z -> Equiv a r x z\n.\n\nArguments Equiv      {a}.\nArguments EquivBase  {a}.\nArguments EquivRefl  {a}.\nArguments EquivSym   {a}.\nArguments EquivTrans {a}.\n\n(* The equivalence relation generated by a given relation is reflexive.         *)\nLemma Equiv_reflexive : forall (a:Type) (r:Rel a), reflexive (Equiv r).\nProof.\n    intros a r. unfold reflexive. intros x. apply EquivRefl.\nQed.\n\n(* The equivalence relation generated by a given relation is symmetric.         *)\nLemma Equiv_symmetric : forall (a:Type) (r:Rel a), symmetric (Equiv r).\nProof.\n    intros a r. unfold symmetric. intros x y H1. apply EquivSym. assumption.\nQed.\n\n(* The equivalence relation generated by a given relation is transitive.        *)\nLemma Equiv_transitive : forall (a:Type) (r:Rel a), transitive (Equiv r).\nProof.\n    intros a r. unfold transitive. intros x y z H1 H2. \n    apply EquivTrans with y; assumption.\nQed.\n\n(* The equivalence relation generated by a given relation is an equivalence.    *)\nLemma Equiv_equivalence : forall (a:Type) (r:Rel a), equivalence (Equiv r).\nProof.\n    intros a r. unfold equivalence. split.\n    - apply Equiv_reflexive.\n    - split.\n        + apply Equiv_symmetric.\n        + apply Equiv_transitive.\nQed.\n\n(* The equivalence relation generated by a given relation contains it.          *)\nLemma Equiv_super : forall (a:Type) (r:Rel a), r <= Equiv r.\nProof.\n    intros a r. apply incl_charac. intros x y H1. apply EquivBase. assumption.\nQed.\n\n(* The equivalence relation generated by a given relation is the smallest.      *)\nLemma Equiv_smallest : forall (a:Type) (r s:Rel a),\n    equivalence s -> r <= s -> Equiv r <= s.\nProof.\n    intros a r s [H1 [H2 H3]] H4. apply incl_charac. intros x y H5.\n    induction H5 as [x y H5|x|x y H5 IH|x y z H5 H6 H7 IH].\n    - apply incl_charac_to with r; assumption.\n    - apply H1.\n    - apply H2. assumption.\n    - apply H3 with y; 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/Rel/Equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7807970240779813}}
{"text": "Inductive even : nat -> Prop :=\n  base : (even 0)\n| step : forall (n : nat), (even n) -> (even (S (S n))) .\n\n(* See Chlipala, CPDT Predicates chapter (definition of even) for example\n * similar to below.  Possibly identical.\n *)\nLemma pred_even : forall (n:nat), (even n) -> (even (pred (pred n))) .\n(* instead of doing induction over n, do induction over the structure of the\n * proof.  ie, do induction over even.\n *   in coq, we can use number to indicate anonymous terms.  In the below\n * case, induction 1 means to induct over the first even predicate.\n *)\ninduction 1 .\n  simpl . constructor .\n  simpl . exact H . (* or assumption . *)\nQed .\n(* First failed attempt\nintros. unfold pred.\nAbort .\n*)\n(* 2nd failed attempt.  inducting over n leads nowhere good\ninduction n. simpl . intro ; exact H .\nAbort .\n*)\n(*  Want to substitute n (nat) for S n ... is that allowed ? *)\n", "meta": {"author": "michael-n-kaplan", "repo": "coq", "sha": "52a834ead854cf85d6352fbe35e4beb523ee19ac", "save_path": "github-repos/coq/michael-n-kaplan-coq", "path": "github-repos/coq/michael-n-kaplan-coq/coq-52a834ead854cf85d6352fbe35e4beb523ee19ac/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7806817436069023}}
{"text": "Require Import Arith.\n\nFixpoint rplus (n p:nat) {struct p} : nat :=\n  match p with\n  | O => n\n  | S q => S (rplus n q)\n  end.\n\nEval compute in (rplus 33 17).\n\nTheorem rplus_0_p : forall p:nat, rplus 0 p = p.\nProof.\n induction p; simpl; auto.\nQed.\n\nTheorem rplus_Sn_p : forall n p:nat, rplus (S n) p = S (rplus n p).\nProof.\n induction p; simpl; auto.\nQed.\n\nTheorem plus_rplus_equiv : forall n p:nat, n + p = rplus n p.\nProof.\n induction n; simpl.\n intro p; rewrite rplus_0_p; auto.\n intro p; rewrite rplus_Sn_p; 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/structinduct/SRC/rplus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7806817272938311}}
{"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\nFixpoint mult (mult_arg0 : Nat) (mult_arg1 : Nat) : Nat\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 : Nat) (qmult_arg1 : Nat) (qmult_arg2 : Nat) : Nat\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 : Nat), 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 : Nat), 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 : Nat), 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 : Nat), 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\nTheorem theorem0 : forall (x : Nat) (y : Nat) (z : Nat), eq (plus (mult x y) z) (qmult x y z).\nProof.\n  induction x.\n  - reflexivity.\n  - intros. simpl. rewrite <- IHx. rewrite plus_assoc. rewrite (plus_commut y z). 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/goal85.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7806782153451339}}
{"text": "Require Import init.\n\nRequire Export cauchy_real_base.\n\nLemma cauchy_plus : ∀ a b : real_base, cauchy_seq (λ n, r_seq a n + r_seq b n).\nProof.\n    intros [a a_cauchy] [b b_cauchy]; cbn.\n    intros ε ε_pos.\n    pose proof (half_pos ε_pos) as ε2_pos.\n    specialize (a_cauchy _ ε2_pos) as [N1 a_cauchy].\n    specialize (b_cauchy _ ε2_pos) as [N2 b_cauchy].\n    exists (max N1 N2).\n    intros i j i_ge j_ge.\n    specialize (a_cauchy i j (trans (lmax _ _) i_ge) (trans (lmax _ _) j_ge)).\n    specialize (b_cauchy i j (trans (rmax _ _) i_ge) (trans (rmax _ _) j_ge)).\n    pose proof (lt_lrplus a_cauchy b_cauchy) as ltq.\n    rewrite plus_half in ltq.\n    apply (le_lt_trans (abs_tri _ _)) in ltq.\n    applys_eq ltq.\n    apply f_equal.\n    do 2 rewrite <- plus_assoc.\n    apply lplus.\n    rewrite neg_plus.\n    do 2 rewrite plus_assoc.\n    apply rplus.\n    apply plus_comm.\nQed.\n\nLemma cauchy_neg : ∀ a : real_base, cauchy_seq (λ n, -r_seq a n).\nProof.\n    intros [a a_cauchy] ε ε_pos; cbn.\n    specialize (a_cauchy ε ε_pos) as [N a_cauchy].\n    exists N.\n    intros i j.\n    rewrite abs_minus.\n    rewrite neg_neg, plus_comm.\n    apply a_cauchy.\nQed.\n\nNotation \"a ⊕ b\" := (make_real _ (cauchy_plus a b)) : real_scope.\nNotation \"⊖ a\" := (make_real _ (cauchy_neg a)) : real_scope.\n\nOpen Scope real_scope.\n\nLemma real_plus_wd : ∀ a b c d, a ~ b → c ~ d → a ⊕ c ~ b ⊕ d.\nProof.\n    intros [a a_cauchy] [b b_cauchy] [c c_cauchy] [d d_cauchy] ab cd ε ε_pos.\n    cbn in *.\n    pose proof (half_pos ε_pos) as ε2_pos.\n    specialize (ab _ ε2_pos) as [N1 ab].\n    specialize (cd _ ε2_pos) as [N2 cd].\n    exists (max N1 N2).\n    intros i i_ge.\n    specialize (ab i (trans (lmax N1 N2) i_ge)).\n    specialize (cd i (trans (rmax N1 N2) i_ge)).\n    pose proof (lt_lrplus ab cd) as ltq.\n    rewrite plus_half in ltq.\n    apply (le_lt_trans (abs_tri _ _)) in ltq.\n    applys_eq ltq.\n    apply f_equal.\n    do 2 rewrite <- plus_assoc.\n    apply lplus.\n    rewrite neg_plus.\n    do 2 rewrite plus_assoc.\n    apply rplus.\n    apply plus_comm.\nQed.\n\nLemma real_neg_wd : ∀ a b, a ~ b → ⊖a ~ ⊖b.\nProof.\n    intros [a a_cauchy] [b b_cauchy] ab ε ε_pos; cbn in *.\n    specialize (ab ε ε_pos) as [N ab].\n    exists N.\n    intros n.\n    rewrite abs_minus.\n    rewrite neg_neg, plus_comm.\n    apply ab.\nQed.\n\nGlobal Instance real_plus : Plus real := {\n    plus := binary_op (binary_self_wd real_plus_wd)\n}.\n\nGlobal Instance real_zero : Zero real := {\n    zero := rat_to_real 0\n}.\n\nGlobal Instance real_neg : Neg real := {\n    neg := unary_op (unary_self_wd real_neg_wd)\n}.\n\nGlobal Instance real_plus_assoc : PlusAssoc real.\nProof.\n    split.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold plus; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite plus_assoc.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_plus_comm : PlusComm real.\nProof.\n    split.\n    intros a b.\n    equiv_get_value a b.\n    unfold plus; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite (plus_comm (r_seq a i)).\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_plus_lid : PlusLid real.\nProof.\n    split.\n    intros a.\n    equiv_get_value a.\n    unfold plus, zero; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite plus_lid.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\nQed.\n\nGlobal Instance real_plus_linv : PlusLinv real.\nProof.\n    split.\n    intros a.\n    equiv_get_value a.\n    unfold plus, neg, zero; cbn.\n    unfold rat_to_real; equiv_simpl.\n    intros ε ε_pos.\n    exists 0.\n    intros i i_ge.\n    rewrite plus_linv.\n    rewrite plus_rinv.\n    rewrite <- abs_zero.\n    exact ε_pos.\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/Real/Cauchy/cauchy_real_plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7806782138052436}}
{"text": "(** * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n\t\t  #####################################################\n\t\t  ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n\t\t  #####################################################\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\tmathematical intuition: If a procedure or method has no side\n\teffects, then (ignoring efficiency) all we need to understand\n\tabout it is how it maps inputs to outputs -- that is, we can think\n\tof it as just a concrete method for computing a mathematical\n\tfunction.  This is one sense of the word \"functional\" in\n\t\"functional programming.\"  The direct connection between programs\n\tand simple mathematical objects supports both formal correctness\n\tproofs and sound informal reasoning about program behavior.\n\n\tThe other sense in which functional programming is \"functional\" is\n\tthat it emphasizes the use of functions as _first-class_ values --\n\ti.e., values that can be passed as arguments to other functions,\n\treturned as results, included in data structures, etc.  The\n\trecognition that functions can be treated as data gives rise to a\n\thost of useful and powerful programming idioms.\n\n\tOther common features of functional languages include _algebraic\n\tdata types_ and _pattern matching_, which make it easy to\n\tconstruct and manipulate rich data structures, and _polymorphic\n\ttype systems_ supporting abstraction and code reuse.  Coq offers\n\tall of these features.\n\n\tThe first half of this chapter introduces the most essential\n\telements of Coq's native functional programming language, called\n\t_Gallina_.  The second half introduces some basic _tactics_ that\n\tcan 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\tfeatures is _extremely_ small.  For example, instead of providing\n\tthe usual palette of atomic data types (booleans, integers,\n\tstrings, etc.), Coq offers a powerful mechanism for defining new\n\tdata types from scratch, with all these familiar types as\n\tinstances.\n\n\tNaturally, the Coq distribution comes with an extensive standard\n\tlibrary providing definitions of booleans, numbers, and many\n\tcommon data structures like lists and hash tables.  But there is\n\tnothing magic or primitive about these library definitions.  To\n\tillustrate this, this course we will explicitly recapitulate\n\t(almost) all the definitions we need, rather than getting them\n\tfrom the standard library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n\ta very simple example.  The following declaration tells Coq that\n\twe are defining a 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 new type is called [day], and its members are [monday],\n\t[tuesday], etc.\n\n\tHaving defined [day], we can write functions that operate on\n\tdays. *)\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 point to note is that the argument and return types of\n\tthis function are explicitly declared.  Like most functional\n\tprogramming languages, Coq can often figure out these types for\n\titself when they are not given explicitly -- i.e., it can do _type\n\tinference_ -- but we'll generally include them to make reading\n\teasier. *)\n\n(** Having defined a function, we should next check that it\n\tworks on some examples.  There are actually three different ways\n\tto do the examples in Coq.  First, we can use the command\n\t[Compute] to evaluate a compound expression involving\n\t[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\tcomputer handy, this would be an excellent moment to fire up the\n\tCoq interpreter under your favorite IDE -- either CoqIde or Proof\n\tGeneral -- and try it for yourself.  Load this file, [Basics.v],\n\tfrom the book's Coq sources, find the above example, submit it to\n\tCoq, and observe the result.) *)\n\n(** Second, we can record what we _expect_ the result to be in the\n\tform 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\tassertion (that the second weekday after [saturday] is [tuesday]),\n\tand it gives the assertion a name that can be used to refer to it\n\tlater.  Having made the assertion, we can also ask Coq to verify\n\tit like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important just now, but essentially this\n\tcan be read as \"The assertion we've just made can be proved by\n\tobserving that both sides of the equality evaluate to the same\n\tthing.\"\n\n\tThird, we can ask Coq to _extract_, from our [Definition], a\n\tprogram in another, more conventional, programming\n\tlanguage (OCaml, Scheme, or Haskell) with a high-performance\n\tcompiler.  This facility is very interesting, since it gives us a\n\tpath from proved-correct algorithms written in Gallina to\n\tefficient machine code.  (Of course, we are trusting the\n\tcorrectness of the OCaml/Haskell/Scheme compiler, and of Coq's\n\textraction facility itself, but this is still a big step forward\n\tfrom the way most software is developed today.) Indeed, this is\n\tone of the main uses for which Coq was developed.  We'll come back\n\tto this topic in later chapters. *)\n\n(* ================================================================= *)\n(** ** Homework Submission Guidelines *)\n\n(** If you are using _Software Foundations_ in a course, your\n\tinstructor may use automatic scripts to help grade your homework\n\tassignments.  In order for these scripts to work correctly (and\n\tgive you that you get full credit for your work!), please be\n\tcareful to follow these rules:\n\t  - The grading scripts work by extracting marked regions of the\n\t\t[.v] files that you submit.  It is therefore important that\n\t\tyou do not alter the \"markup\" that delimits exercises: the\n\t\tExercise header, the name of the exercise, the \"empty square\n\t\tbracket\" marker at the end, etc.  Please leave this markup\n\t\texactly as you find it.\n\t  - Do not delete exercises.  If you skip an exercise (e.g.,\n\t\tbecause it is marked \"optional,\" or because you can't solve it),\n\t\tit is OK to leave a partial proof in your [.v] file; in\n\t\tthis case, please make sure it ends with [Admitted] (not, for\n\t\texample [Abort]).\n\t  - It is fine to use additional definitions (of helper functions,\n\t\tuseful lemmas, etc.) in your solutions.  You can put these\n\t\tbetween the exercise header and the theorem you are asked to\n\t\tprove.\n\t  - If you introduce a helper lemma that you end up being unable\n\t\tto prove, hence end it with [Admitted], then make sure to also\n\t\tend the main theorem in which you use it with [Admitted], not\n\t\t[Qed].  That will help you get partial credit, in case you\n\t\tuse that main theorem to solve a later exercise.\n\n\tYou will also notice that each chapter (like [Basics.v]) is\n\taccompanied by a _test script_ ([BasicsTest.v]) that automatically\n\tcalculates points for the finished homework problems in the\n\tchapter.  These scripts are mostly for the auto-grading\n\ttools, but you may also want to use them to double-check\n\tthat your file is well formatted before handing it in.  In a\n\tterminal window, either type \"[make BasicsTest.vo]\" or do the\n\tfollowing:\n\n\t   coqc -Q . LF Basics.v\n\t   coqc -Q . LF BasicsTest.v\n\n\tSee the end of this chapter for more information about how to interpret\n\tthe output of test scripts.\n\n\tThere is no need to hand in [BasicsTest.v] itself (or [Preface.v]).\n\n\tIf your class is using the Canvas system to hand in assignments...\n\t  - If you submit multiple versions of the assignment, you may\n\t\tnotice that they are given different names.  This is fine: The\n\t\tmost recent submission is the one that will be graded.\n\t  - To hand in multiple files at the same time (if more than one\n\t\tchapter is assigned in the same week), you need to make a\n\t\tsingle submission with all the files at once using the button\n\t\t\"Add another file\" just above the comment box. *)\n\n(** The [Require Export] statement on the next line tells Coq to use\n\tthe [String] module from the standard library.  We'll use strings\n\tourselves in later chapters, but we need to [Require] it here so\n\tthat the grading scripts can use it for internal purposes. *)\nFrom Coq Require Export String.\n\n(* ================================================================= *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the standard type [bool] of\n\tbooleans, with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true\n  | false.\n\n(** Functions over booleans can be defined in the same way as\n\tabove: *)\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(** (Although we are rolling our own booleans here for the sake\n\tof building up everything from scratch, Coq does, of course,\n\tprovide a default implementation of the booleans, together with a\n\tmultitude of useful functions and lemmas.  Whenever possible,\n\twe'll name our own definitions and theorems so that they exactly\n\tcoincide with the ones in the standard library.) *)\n\n(** The last two of these illustrate Coq's syntax for\n\tmulti-argument function definitions.  The corresponding\n\tmulti-argument application syntax is illustrated by the following\n\t\"unit tests,\" which constitute a complete specification -- a truth\n\ttable -- 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 infix syntax for the\n\tboolean operations we have just defined. The [Notation] command\n\tdefines 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\tto delimit fragments of Coq code within comments; this convention,\n\talso used by the [coqdoc] documentation tool, keeps them visually\n\tseparate from the surrounding text.  In the HTML version of the\n\tfiles, these pieces of text appear in a [different font]. *)\n\n(** These examples are also an opportunity to introduce one more small\n\tfeature of Coq's programming language: conditional expressions... *)\n\nDefinition negb' (b:bool) : bool :=\n  if b then false\n  else true.\n\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\tlanguage, with one small generalization.  Since the [bool] type is\n\tnot built in, Coq actually supports conditional expressions over\n\t_any_ inductively defined type with exactly two clauses in its\n\tdefinition.  The guard is considered true if it evaluates to the\n\t\"constructor\" of the first clause of the [Inductive]\n\tdefinition (which just happens to be called [true] in this case)\n\tand false if it evaluates to the second. *)\n\n(** **** Exercise: 1 star, standard (nandb)\n\n\tThe command [Admitted] can be used as a placeholder for an\n\tincomplete proof.  We use it in exercises to indicate the parts\n\tthat we're leaving for you -- i.e., your job is to replace\n\t[Admitted]s with real proofs.\n\n\tRemove \"[Admitted.]\" and complete the definition of the following\n\tfunction; then make sure that the [Example] assertions below can\n\teach be verified by Coq.  (I.e., fill in each proof, following the\n\tmodel of the [orb] tests above, and make sure Coq accepts it.) The\n\tfunction should return [true] if either or both of its inputs are\n\t[false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool := negb (b1 && b2).  \n\nExample test_nandb1:               (nandb true false) = true.\nProof. auto. Qed.\nExample test_nandb2:               (nandb false false) = true.\nProof. auto. Qed.\nExample test_nandb3:               (nandb false true) = true.\nProof. auto. Qed.\nExample test_nandb4:               (nandb true true) = false.\nProof. auto. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (andb3)\n\n\tDo the same for the [andb3] function below. This function should\n\treturn [true] when all of its inputs are [true], and [false]\n\totherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool := b1 && b2 && b3.\n\nExample test_andb31:                 (andb3 true true true) = true.\nProof. auto. Qed.\nExample test_andb32:                 (andb3 false true true) = false.\nProof. auto. Qed.\nExample test_andb33:                 (andb3 true false true) = false.\nProof. auto. Qed.\nExample test_andb34:                 (andb3 true true false) = false.\nProof. auto. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Types *)\n\n(** Every expression in Coq has a type, describing what sort of\n\tthing it computes. The [Check] command asks Coq to print the type\n\tof an expression. *)\n\nCheck true.\n(* ===> true : bool *)\n\n(** If the expression after [Check] is followed by a colon and a type,\n\tCoq will verify that the type of the expression matches the given\n\ttype 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\t[true] and [false].  Their types are called _function types_, and\n\tthey are written with arrows. *)\n\nCheck negb\n  : bool -> bool.\n\n(** The type of [negb], written [bool -> bool] and pronounced\n\t\"[bool] arrow [bool],\" can be read, \"Given an input of type\n\t[bool], this function produces an output of type [bool].\"\n\tSimilarly, the type of [andb], written [bool -> bool -> bool], can\n\tbe read, \"Given two inputs, each of type [bool], this function\n\tproduces 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\ttypes\": their definitions explicitly enumerate a finite set of\n\telements, called _constructors_.  Here is a more interesting type\n\tdefinition, 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\tAn [Inductive] definition does two things:\n\n\t- It defines a set of new _constructors_. E.g., [red],\n\t  [primary], [true], [false], [monday], etc. are constructors.\n\n\t- It groups them into a new named type, like [bool], [rgb], or\n\t  [color].\n\n\t_Constructor expressions_ are formed by applying a constructor\n\tto zero or more other constructors or constructor expressions,\n\tobeying the declared number and types of the constructor arguments.\n\tE.g.,\n\t\t- [red]\n\t\t- [true]\n\t\t- [primary red]\n\t\t- etc.\n\tBut not\n\t\t- [red primary]\n\t\t- [true red]\n\t\t- [primary (primary red)]\n\t\t- etc.\n*)\n\n(** In particular, the definitions of [rgb] and [color] say\n\twhich constructor expressions belong to the sets [rgb] and\n\t[color]:\n\n\t- [red], [green], and [blue] belong to the set [rgb];\n\t- [black] and [white] belong to the set [color];\n\t- if [p] is a constructor expression belonging to the set [rgb],\n\t  then [primary p] (pronounced \"the constructor [primary] applied\n\t  to the argument [p]\") is a constructor expression belonging to\n\t  the set [color]; and\n\t- constructor expressions formed in these ways are the _only_ ones\n\t  belonging to the sets [rgb] and [color]. *)\n\n(** We can define functions on colors using pattern matching just as\n\twe did 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\tmatching [primary] should include either a variable (as above --\n\tnote that we can choose its name freely) or a constant of\n\tappropriate 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\t[primary] applied to any [rgb] constructor except [red].\"  (The\n\twildcard pattern [_] has the same effect as the dummy pattern\n\tvariable [p] in the definition of [monochrome].) *)\n\n(* ================================================================= *)\n(** ** Modules *)\n\n(** Coq provides a _module system_ to aid in organizing large\n\tdevelopments.  We won't need most of its features,\n\tbut one is useful: If we enclose a collection of declarations\n\tbetween [Module X] and [End X] markers, then, in the remainder of\n\tthe file after the [End], these definitions are referred to by\n\tnames like [X.foo] instead of just [foo].  We will use this\n\tfeature to limit the scope of definitions, so that we are free to\n\treuse 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\tto create a tuple type. As an example, consider representing\n\tthe four bits in a nybble (half a byte). We first define\n\ta datatype [bit] that resembles [bool] (using the\n\tconstructors [B0] and [B1] for the two possible bit values)\n\tand then define the datatype [nybble], which is essentially\n\ta 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  : nybble.\n\n(** The [bits] constructor acts as a wrapper for its contents.\n\tUnwrapping can be done by pattern-matching, as in the [all_zero]\n\tfunction which tests a nybble to see if all its bits are [B0].  We\n\tuse underscore (_) as a _wildcard pattern_ to avoid inventing\n\tvariable 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  | (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\nEnd TuplePlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\n(** We put this section in a module so that our own definition of\n\tnatural numbers does not interfere with the one from the\n\tstandard library.  In the rest of the book, we'll want to use\n\tthe standard library's. *)\n\nModule NatPlayground.\n\n(** All the types we have defined so far -- both \"enumerated\n\ttypes\" such as [day], [bool], and [bit] and tuple types such as\n\t[nybble] built from them -- are finite.  The natural numbers, on\n\tthe other hand, are an infinite set, so we'll need to use a\n\tslightly richer form of type declaration to represent them.\n\n\tThere are many representations of numbers to choose from. We are\n\tmost familiar with decimal notation (base 10), using the digits 0\n\tthrough 9, for example, to form the number 123.  You may have\n\tencountered hexadecimal notation (base 16), in which the same\n\tnumber is represented as 7B, or octal (base 8), where it is 173,\n\tor binary (base 2), where it is 1111011. Using an enumerated type\n\tto represent digits, we could use any of these as our\n\trepresentation natural numbers. Indeed, there are circumstances\n\twhere each of these choices would be useful.\n\n\tThe binary representation is valuable in computer hardware because\n\tthe digits can be represented with just two distinct voltage\n\tlevels, resulting in simple circuitry. Analogously, we wish here\n\tto choose a representation that makes _proofs_ simpler.\n\n\tIn fact, there is a representation of numbers that is even simpler\n\tthan binary, namely unary (base 1), in which only a single digit\n\tis used (as one might do to count days in prison by scratching on\n\tthe walls). To represent unary numbers with a Coq datatype, we use\n\ttwo constructors. The capital-letter [O] constructor represents\n\tzero.  When the [S] constructor is applied to the representation\n\tof the natural number n, the result is the representation of\n\tn+1, where [S] stands for \"successor\" (or \"scratch\" if one is in\n\tprison).  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\t2 by [S (S O)], and so on. *)\n\n(** Informally, the clauses of the definition can be read:\n\t  - [O] is a natural number (remember this is the letter \"[O],\"\n\t\tnot the numeral \"[0]\").\n\t  - [S] can be put in front of a natural number to yield another\n\t\tone -- 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\tof [nat] says how expressions in the set [nat] can be built:\n\n\t- the constructor expression [O] belongs to the set [nat];\n\t- if [n] is a constructor expression belonging to the set [nat],\n\t  then [S n] is also a constructor expression belonging to the set\n\t  [nat]; and\n\t- constructor expressions formed in these two ways are the only\n\t  ones belonging to the set [nat]. *)\n\n(** These conditions are the precise force of the [Inductive]\n\tdeclaration.  They imply that the constructor expression [O], the\n\tconstructor expression [S O], the constructor expression [S (S\n\tO)], the constructor expression [S (S (S O))], and so on all\n\tbelong to the set [nat], while other constructor expressions, like\n\t[true], [andb true false], [S (S false)], and [O (O (O S))] do\n\tnot.\n\n\tA critical point here is that what we've done so far is just to\n\tdefine a _representation_ of numbers: a way of writing them down.\n\tThe names [O] and [S] are arbitrary, and at this point they have\n\tno special meaning -- they are just two different marks that we\n\tcan use to write down numbers (together with a rule that says any\n\t[nat] will be written as some string of [S] marks followed by an\n\t[O]).  If we like, we can write essentially the same definition\n\tthis way: *)\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\tcompute. *)\n\n(** We can do this by writing functions that pattern match on\n\trepresentations of natural numbers just as we did above with\n\tbooleans and days -- for example, here is the predecessor\n\tfunction: *)\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\tfor some [n'], then return [n'].\"  *)\n\n(** The following [End] command closes the current module, so\n\t[nat] will refer back to the type from the standard library. *)\n\nEnd NatPlayground.\n\n(** Because natural numbers are such a pervasive form of data,\n\tCoq provides a tiny bit of built-in magic for parsing and printing\n\tthem: ordinary decimal numerals can be used as an alternative to\n\tthe \"unary\" notation defined by the constructors [S] and [O].  Coq\n\tprints 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 functions\n\tsuch 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\tnumber.  However, there is a fundamental difference between [S]\n\tand the other two: functions like [pred] and [minustwo] are\n\tdefined by giving _computation rules_ -- e.g., the definition of\n\t[pred] says that [pred 2] can be simplified to [1] -- while the\n\tdefinition of [S] has no such behavior attached.  Although it is\n\t_like_ a function in the sense that it can be applied to an\n\targument, it does not _do_ anything at all!  It is just a way of\n\twriting down numbers.\n\n\t(Think about standard decimal numerals: the numeral [1] is not a\n\tcomputation; it's a piece of data.  When we write [111] to mean\n\tthe number one hundred and eleven, we are using [1], three times,\n\tto write down a concrete representation of a number.)\n\n\tNow let's go on and define some more functions over numbers.\n\n\tFor most interesting computations involving numbers, simple\n\tpattern matching is not enough: we also need recursion.  For\n\texample, to check that a number [n] is even, we may need to\n\trecursively check whether [n-2] is even.  Such functions are\n\tintroduced 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 n') => even n'\n  end.\n\n(** We could define [odd] by a similar [Fixpoint] declaration, but\n\there 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\t[simpl] actually has no effect on the goal -- all of the work is\n\tdone by [reflexivity].  We'll discuss why that is shortly.)\n\n\tNaturally, we can also define multi-argument functions by\n\trecursion.  *)\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(* ===> 5 : nat *)\n\n(** The steps of simplification that Coq performs can be\n\tvisualized as follows: *)\n\n(*      [plus 3 2]\n   i.e. [plus (S (S (S O))) (S (S O))]\n\t==> [S (plus (S (S O)) (S (S O)))]\n\t\t  by the second clause of the [match]\n\t==> [S (S (plus (S O) (S (S O))))]\n\t\t  by the second clause of the [match]\n\t==> [S (S (S (plus O (S (S O)))))]\n\t\t  by the second clause of the [match]\n\t==> [S (S (S (S (S O))))]\n\t\t  by the first clause of the [match]\n   i.e. [5]  *)\n\n(** As a notational convenience, if two or more arguments have\n\tthe same type, they can be written together.  In the following\n\tdefinition, [(n m : nat)] means just the same as if we had written\n\t[(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\tbetween 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\tRecall the standard mathematical factorial function:\n\n\t   factorial(0)  =  1\n\t   factorial(n)  =  n * factorial(n-1)     (if n>0)\n\n\tTranslate this into Coq. *)\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n\t| O => S O\n\t| S n' => n * factorial n'\n  end.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. auto. Qed.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\nProof. auto. Qed.\n(** [] *)\n\n(** Again, we can make numerical expressions easier to read and write\n\tby introducing notations for addition, multiplication, and\n\tsubtraction. *)\n\nNotation \"x + y\" := (plus x y)\n\t\t\t\t\t   (at level 50, left associativity)\n\t\t\t\t\t   : nat_scope.\nNotation \"x - y\" := (minus x y)\n\t\t\t\t\t   (at level 50, left associativity)\n\t\t\t\t\t   : nat_scope.\nNotation \"x * y\" := (mult x y)\n\t\t\t\t\t   (at level 40, left associativity)\n\t\t\t\t\t   : nat_scope.\n\nCheck ((0 + 1) + 1) : nat.\n\n(** (The [level], [associativity], and [nat_scope] annotations\n\tcontrol how these notations are treated by Coq's parser.  The\n\tdetails are not important for present purposes, but interested\n\treaders can refer to the \"More on Notation\" section at the end of\n\tthis chapter.)\n\n\tNote that these declarations do not change the definitions we've\n\talready made: they are simply instructions to the Coq parser to\n\taccept [x + y] in place of [plus x y] and, conversely, to the Coq\n\tpretty-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\tmean it: even equality testing is a user-defined operation!\n\tHere is a function [eqb], which tests natural numbers for\n\t[eq]uality, yielding a [b]oolean.  Note the use of nested\n\t[match]es (we could also have used a simultaneous match, as we did\n\tin [minus].) *)\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n\t\t | O => true\n\t\t | S m' => false\n\t\t end\n  | S n' => match m with\n\t\t\t| O => false\n\t\t\t| S m' => eqb n' m'\n\t\t\tend\n  end.\n\n(** Similarly, the [leb] function tests whether its first argument is\n\tless 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\t  match m with\n\t  | O => false\n\t  | S m' => leb n' m'\n\t  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\tthem 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\t[=?].  We'll have much more to say about the differences and\n\tsimilarities between them later. For now, the main thing to notice\n\tis that [x = y] is a logical _claim_ -- a \"proposition\" -- that we\n\tcan try to prove, while [x =? y] is an _expression_ whose\n\tvalue (either [true] or [false]) we can compute. *)\n\n(** **** Exercise: 1 star, standard (ltb)\n\n\tThe [ltb] function tests natural numbers for [l]ess-[t]han,\n\tyielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n\tthis one, define it in terms of a previously defined\n\tfunction.  (It can be done with just one previously defined\n\tfunction, but you can use two if you want.) *)\n\nDefinition ltb (n m : nat) : bool := andb (negb (n =? m)) (leb n m).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1:             (ltb 2 2) = false.\nProof. auto. Qed.\nExample test_ltb2:             (ltb 2 4) = true.\nProof. auto. Qed.\nExample test_ltb3:             (ltb 4 2) = false.\nProof. auto. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n\tturn to stating and proving properties of their behavior.\n\tActually, we've already started doing this: each [Example] in the\n\tprevious sections makes a precise claim about the behavior of some\n\tfunction on some particular inputs.  The proofs of these claims\n\twere always the same: use [simpl] to simplify both sides of the\n\tequation, then use [reflexivity] to check that both sides contain\n\tidentical values.\n\n\tThe same sort of \"proof by simplification\" can be used to prove\n\tmore interesting properties as well.  For example, the fact that\n\t[0] is a \"neutral element\" for [+] on the left can be proved just\n\tby observing that [0 + n] reduces to [n] no matter what [n] is -- a\n\tfact 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\tthe [.v] file in your IDE than it does in the HTML rendition in\n\tyour browser. In [.v] files, we write the universal quantifier\n\t[forall] using the reserved identifier \"forall.\"  When the [.v]\n\tfiles are converted to HTML, this gets transformed into the\n\tstandard upside-down-A symbol.)\n\n\tThis is a good place to mention that [reflexivity] is a bit more\n\tpowerful than we have acknowledged. In the examples we have seen,\n\tthe calls to [simpl] were actually not needed, because\n\t[reflexivity] can perform some simplification automatically when\n\tchecking that two sides are equal; [simpl] was just added so that\n\twe could see the intermediate state -- after simplification but\n\tbefore finishing the proof.  Here is a shorter proof of the\n\ttheorem: *)\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\tsomewhat _more_ simplification than [simpl] does -- for example,\n\tit tries \"unfolding\" defined terms, replacing them with their\n\tright-hand sides.  The reason for this difference is that, if\n\treflexivity succeeds, the whole goal is finished and we don't need\n\tto look at whatever expanded expressions [reflexivity] has created\n\tby all this simplification and unfolding; by contrast, [simpl] is\n\tused in situations where we may have to read and understand the\n\tnew goal that it creates, so we would not want it blindly\n\texpanding definitions and leaving the goal in a messy state.\n\n\tThe form of the theorem we just stated and its proof are almost\n\texactly the same as the simpler examples we saw earlier; there are\n\tjust a few differences.\n\n\tFirst, we've used the keyword [Theorem] instead of [Example].\n\tThis difference is mostly a matter of style; the keywords\n\t[Example] and [Theorem] (and a few others, including [Lemma],\n\t[Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n\tSecond, we've added the quantifier [forall n:nat], so that our\n\ttheorem talks about _all_ natural numbers [n].  Informally, to\n\tprove theorems of this form, we generally start by saying \"Suppose\n\t[n] is some number...\"  Formally, this is achieved in the proof by\n\t[intros n], which moves [n] from the quantifier in the goal to a\n\t_context_ of current assumptions. Note that we could have used\n\tanother identifier instead of [n] in the [intros] clause, (though\n\tof 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\t_tactics_.  A tactic is a command that is used between [Proof] and\n\t[Qed] to guide the process of checking some claim we are making.\n\tWe will see several more tactics in the rest of this chapter and\n\tmany 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\tpronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n\tcontext and the goal change.  You may want to add calls to [simpl]\n\tbefore [reflexivity] to see the simplifications that Coq performs\n\ton 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\tones 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\tit talks about a more specialized property that only holds when\n\t[n = m].  The arrow symbol is pronounced \"implies.\"\n\n\tAs before, we need to be able to reason by assuming we are given such\n\tnumbers [n] and [m].  We also need to assume the hypothesis\n\t[n = m]. The [intros] tactic will serve to move all three of these\n\tfrom the goal into assumptions in the current context.\n\n\tSince [n] and [m] are arbitrary numbers, we can't just use\n\tsimplification to prove this theorem.  Instead, we prove it by\n\tobserving that, if we are assuming [n = m], then we can replace\n\t[n] with [m] in the goal statement and obtain an equality with the\n\tsame expression on both sides.  The tactic that tells Coq to\n\tperform 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\tvariables [n] and [m] into the context.  The second moves the\n\thypothesis [n = m] into the context and gives it the name [H].\n\tThe third tells Coq to rewrite the current goal ([n + n = m + m])\n\tby replacing the left side of the equality hypothesis [H] with the\n\tright side.\n\n\t(The arrow symbol in the [rewrite] has nothing to do with\n\timplication: it tells Coq to apply the rewrite from left to right.\n\tIn fact, you can omit the arrow, and Coq will default to rewriting\n\tin this direction.  To rewrite from right to left, you can use\n\t[rewrite <-].  Try making this change in the above proof and see\n\twhat difference it makes.) *)\n\n(** **** Exercise: 1 star, standard (plus_id_exercise)\n\n\tRemove \"[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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The [Admitted] command tells Coq that we want to skip trying\n\tto prove this theorem and just accept it as a given.  This can be\n\tuseful for developing longer proofs, since we can state subsidiary\n\tlemmas that we believe will be useful for making some larger\n\targument, use [Admitted] to accept them on faith for the moment,\n\tand continue working on the main argument until we are sure it\n\tmakes sense; then we can go back and fill in the proofs we\n\tskipped.  Be careful, though: every time you say [Admitted] you\n\tare leaving a door open for total nonsense to enter Coq's nice,\n\trigorous, formally checked world! *)\n\n(** The [Check] command can also be used to examine the statements of\n\tpreviously declared lemmas and theorems.  The two examples below\n\tare lemmas about multiplication that are proved in the standard\n\tlibrary.  (We will see how to prove them ourselves in the next\n\tchapter.) *)\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\tinstead of a hypothesis from the context. If the statement of the\n\tpreviously proved theorem involves quantified variables, as in the\n\texample below, Coq tries to instantiate them by matching with the\n\tcurrent 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\n(** **** Exercise: 1 star, standard (mult_n_1)\n\n\tUse those two lemmas about multiplication that we just checked to\n\tprove the following theorem.  Hint: recall that [1] is [S O]. *)\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n\tcalculation and rewriting: In general, unknown, hypothetical\n\tvalues (arbitrary numbers, booleans, lists, etc.) can block\n\tsimplification.  For example, if we try to prove the following\n\tfact using the [simpl] tactic as above, we get stuck.  (We then\n\tuse 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\tand [+] begin by performing a [match] on their first argument.\n\tBut here, the first argument to [+] is the unknown number [n] and\n\tthe argument to [eqb] is the compound expression [n + 1]; neither\n\tcan be simplified.\n\n\tTo make progress, we need to consider the possible forms of [n]\n\tseparately.  If [n] is [O], then we can calculate the final result\n\tof [(n + 1) =? 0] and check that it is, indeed, [false].  And if\n\t[n = S n'] for some [n'], then, although we don't know exactly\n\twhat number [n + 1] represents, we can calculate that, at least,\n\tit will begin with one [S], and this is enough to calculate that,\n\tagain, [(n + 1) =? 0] will yield [false].\n\n\tThe tactic that tells Coq to consider, separately, the cases where\n\t[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\tprove, separately, in order to get Coq to accept the theorem.\n\n\tThe annotation \"[as [| n']]\" is called an _intro pattern_.  It\n\ttells Coq what variable names to introduce in each subgoal.  In\n\tgeneral, what goes between the square brackets is a _list of\n\tlists_ of names, separated by [|].  In this case, the first\n\tcomponent is empty, since the [O] constructor is nullary (it\n\tdoesn't have any arguments).  The second component gives a single\n\tname, [n'], since [S] is a unary constructor.\n\n\tIn each subgoal, Coq remembers the assumption about [n] that is\n\trelevant for this subgoal -- either [n = 0] or [n = S n'] for some\n\tn'.  The [eqn:E] annotation tells [destruct] to give the name [E]\n\tto this equation.  Leaving off the [eqn:E] annotation causes Coq\n\tto elide these assumptions in the subgoals.  This slightly\n\tstreamlines proofs where the assumptions are not explicitly used,\n\tbut it is better practice to keep them for the sake of\n\tdocumentation, as they can help keep you oriented when working\n\twith the subgoals.\n\n\tThe [-] signs on the second and third lines are called _bullets_,\n\tand they mark the parts of the proof that correspond to the two\n\tgenerated subgoals.  The part of the proof script that comes after\n\ta bullet is the entire proof for the corresponding subgoal.  In\n\tthis example, each of the subgoals is easily proved by a single\n\tuse of [reflexivity], which itself performs some simplification --\n\te.g., the second one simplifies [(S n' + 1) =? 0] to [false] by\n\tfirst rewriting [(S n' + 1)] to [S (n' + 1)], then unfolding\n\t[eqb], and then simplifying the [match].\n\n\tMarking cases with bullets is optional: if bullets are not\n\tpresent, Coq simply asks you to prove each subgoal in sequence,\n\tone at a time. But it is a good idea to use bullets.  For one\n\tthing, they make the structure of a proof apparent, improving\n\treadability. Also, bullets instruct Coq to ensure that a subgoal\n\tis complete before trying to verify the next one, preventing\n\tproofs for different subgoals from getting mixed up. These issues\n\tbecome especially important in large developments, where fragile\n\tproofs lead to long debugging sessions.\n\n\tThere are no hard and fast rules for how proofs should be\n\tformatted in Coq -- e.g., where lines should be broken and how\n\tsections of the proof should be indented to indicate their nested\n\tstructure.  However, if the places where multiple subgoals are\n\tgenerated are marked with explicit bullets at the beginning of\n\tlines, then the proof will be readable almost no matter what\n\tchoices are made about other aspects of layout.\n\n\tThis is also a good place to mention one other piece of somewhat\n\tobvious advice about line lengths.  Beginning Coq users sometimes\n\ttend to the extremes, either writing each tactic on its own line\n\tor writing entire proofs on a single line.  Good style lies\n\tsomewhere in the middle.  One reasonable guideline is to limit\n\tyourself to 80-character lines.\n\n\tThe [destruct] tactic can be used with any inductively defined\n\tdatatype.  For example, we use it next to prove that boolean\n\tnegation is involutive -- i.e., that negation is its own\n\tinverse. *)\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\tnone of the subcases of the [destruct] need to bind any variables,\n\tso there is no need to specify any names.  In fact, we can omit\n\tthe [as] clause from _any_ [destruct] and Coq will fill in\n\tvariable names automatically.  This is generally considered bad\n\tstyle, since Coq often makes confusing choices of names when left\n\tto its own devices.\n\n\tIt is sometimes useful to invoke [destruct] inside a subgoal,\n\tgenerating yet more proof obligations. In this case, we use\n\tdifferent kinds of bullets to mark goals on different \"levels.\"\n\tFor 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\t+ reflexivity.\n\t+ reflexivity.\n  - destruct c eqn:Ec.\n\t+ reflexivity.\n\t+ reflexivity.\nQed.\n\n(** Each pair of calls to [reflexivity] corresponds to the\n\tsubgoals that were generated after the execution of the [destruct c]\n\tline right above it. *)\n\n(** Besides [-] and [+], we can use [*] (asterisk) or any repetition\n\tof a bullet symbol (e.g. [--] or [***]) as a bullet.  We can also\n\tenclose 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\t{ reflexivity. }\n\t{ reflexivity. } }\n  { destruct c eqn:Ec.\n\t{ reflexivity. }\n\t{ reflexivity. } }\nQed.\n\n(** Since curly braces mark both the beginning and the end of a proof,\n\tthey can be used for multiple subgoal levels, as this example\n\tshows. Furthermore, curly braces allow us to reuse the same bullet\n\tshapes at multiple levels in a proof. The choice of braces,\n\tbullets, or a combination of the two is purely a matter of\n\ttaste. *)\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\t{ destruct d eqn:Ed.\n\t  - reflexivity.\n\t  - reflexivity. }\n\t{ destruct d eqn:Ed.\n\t  - reflexivity.\n\t  - reflexivity. }\n  - destruct c eqn:Ec.\n\t{ destruct d eqn:Ed.\n\t  - reflexivity.\n\t  - reflexivity. }\n\t{ destruct d eqn:Ed.\n\t  - reflexivity.\n\t  - reflexivity. }\nQed.\n\n(** **** Exercise: 2 stars, standard (andb_true_elim2)\n\n\tProve the following claim, marking cases (and subcases) with\n\tbullets when you use [destruct]. Hint: delay introducing the\n\thypothesis until after you have an opportunity to simplify it. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n\tintros b c.\n\tdestruct b eqn:Eb.\n\t- intros H.\n\t  simpl in H.\n\t  rewrite H.\n\t  reflexivity.\n\t- simpl.\n\t\tintros.\n\t\tdestruct c eqn:Ec.\n\t\t+ reflexivity.\n\t\t+ destruct H.\n\t\t\treflexivity.  \nQed.\n(** [] *)\n\n(** Before closing the chapter, let's mention one final\n\tconvenience.  As you may have noticed, many proofs perform case\n\tanalysis on a variable right after introducing it:\n\n\t   intros x y. destruct y as [|y] eqn:E.\n\n\tThis pattern is so common that Coq provides a shorthand for it: we\n\tcan perform case analysis on a variable when introducing it by\n\tusing an intro pattern instead of a variable name. For instance,\n\there is a shorter proof of the [plus_1_neq_0] theorem\n\tabove.  (You'll also note one downside of this shorthand: we lose\n\tthe equation recording the assumption we are making in each\n\tsubgoal, 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\twrite [[]] to get the case analysis. *)\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: 1 star, standard (zero_nbeq_plus_1) *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n\trest of the book, except possibly other Optional sections.  On a\n\tfirst reading, you might want to skim these sections so that you\n\tknow what's there for future reference.)\n\n\tRecall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus x y)\n\t\t\t\t\t   (at level 50, left associativity)\n\t\t\t\t\t   : nat_scope.\nNotation \"x * y\" := (mult x y)\n\t\t\t\t\t   (at level 40, left associativity)\n\t\t\t\t\t   : nat_scope.\n\n(** For each notation symbol in Coq, we can specify its _precedence\n\tlevel_ and its _associativity_.  The precedence level [n] is\n\tspecified by writing [at level n]; this helps Coq parse compound\n\texpressions.  The associativity setting helps to disambiguate\n\texpressions containing multiple occurrences of the same\n\tsymbol. For example, the parameters specified above for [+] and\n\t[*] say that the expression [1+2*3*4] is shorthand for\n\t[(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n\t_left_, _right_, or _no_ associativity.  We will see more examples\n\tof this later, e.g., in the [Lists]\n\tchapter.\n\n\tEach notation symbol is also associated with a _notation scope_.\n\tCoq tries to guess what scope is meant from context, so when it\n\tsees [S(O*O)] it guesses [nat_scope], but when it sees the product\n\ttype [bool*bool] (which we'll see in later chapters) it guesses\n\t[type_scope].  Occasionally, it is necessary to help it out with\n\tpercent-notation by writing [(x*y)%nat], and sometimes in what Coq\n\tprints it will use [%nat] to indicate what scope a notation is in.\n\n\tNotation scopes also apply to numeral notation ([3], [4], [5], [42],\n\tetc.), so you may sometimes see [0%nat], which means [O] (the\n\tnatural number [0] that we're using in this chapter), or [0%Z],\n\twhich means the integer zero (which comes from a different part of\n\tthe standard library).\n\n\tPro tip: Coq's notation mechanism is not especially powerful.\n\tDon'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\t\"decreasing on 1st argument.\"  What this means is that we are\n\tperforming a _structural recursion_ over the argument [n] -- i.e.,\n\tthat we make recursive calls only on strictly smaller values of\n\t[n].  This implies that all calls to [plus'] will eventually\n\tterminate.  Coq demands that some argument of _every_ [Fixpoint]\n\tdefinition is \"decreasing.\"\n\n\tThis requirement is a fundamental feature of Coq's design: In\n\tparticular, it guarantees that every function that can be defined\n\tin Coq will terminate on all inputs.  However, because Coq's\n\t\"decreasing analysis\" is not very sophisticated, it is sometimes\n\tnecessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, standard, optional (decreasing)\n\n\tTo get a concrete sense of this, find a way to write a sensible\n\t[Fixpoint] definition (of a simple function on numbers, say) that\n\t_does_ terminate on all inputs, but that Coq will reject because\n\tof this restriction.  (If you choose to turn in this optional\n\texercise as part of a homework assignment, make sure you comment\n\tout your solution so that it doesn't cause Coq to reject the whole\n\tfile!) *)\n\n(* FILL IN HERE\n\n\t[] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 1 star, standard (identity_fn_applied_twice)\n\n\tUse the tactics you have learned so far to prove the following\n\ttheorem 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  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (negation_fn_applied_twice)\n\n\tNow state and prove a theorem [negation_fn_applied_twice] similar\n\tto the previous one but where the second hypothesis says that the\n\tfunction [f] has the property that [f x = negb x]. *)\n\n(* FILL IN HERE *)\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\t[] *)\n\n(** **** Exercise: 3 stars, standard, optional (andb_eq_orb)\n\n\tProve the following theorem.  (Hint: This one can be a bit tricky,\n\tdepending on how you approach it.  You will probably need both\n\t[destruct] and [rewrite], but destructing everything in sight is\n\tnot 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, standard (binary)\n\n\tWe can generalize our unary representation of natural numbers to\n\tthe more efficient binary representation by treating a binary\n\tnumber as a sequence of constructors [B0] and [B1] (representing 0s\n\tand 1s), terminated by a [Z]. For comparison, in the unary\n\trepresentation, a number is a sequence of [S] constructors terminated\n\tby an [O].\n\n\tFor example:\n\n\t\tdecimal               binary                          unary\n\t\t   0                       Z                              O\n\t\t   1                    B1 Z                            S O\n\t\t   2                B0 (B1 Z)                        S (S O)\n\t\t   3                B1 (B1 Z)                     S (S (S O))\n\t\t   4            B0 (B0 (B1 Z))                 S (S (S (S O)))\n\t\t   5            B1 (B0 (B1 Z))              S (S (S (S (S O))))\n\t\t   6            B0 (B1 (B1 Z))           S (S (S (S (S (S O)))))\n\t\t   7            B1 (B1 (B1 Z))        S (S (S (S (S (S (S O))))))\n\t\t   8        B0 (B0 (B0 (B1 Z)))    S (S (S (S (S (S (S (S O)))))))\n\n\tNote that the low-order bit is on the left and the high-order bit\n\tis on the right -- the opposite of the way binary numbers are\n\tusually 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\tfor binary numbers, and a function [bin_to_nat] to convert\n\tbinary 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(** The following \"unit tests\" of your increment and binary-to-unary\n\tfunctions should pass after you have defined those functions correctly.\n\tOf course, unit tests don't fully demonstrate the correctness of\n\tyour functions!  We'll return to that thought at the end of the\n\tnext chapter. *)\n\nExample test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\n(* FILL IN HERE *) Admitted.\n\nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\n(* FILL IN HERE *) Admitted.\n\nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\n(* FILL IN HERE *) Admitted.\n\nExample test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\n(* FILL IN HERE *) Admitted.\n\nExample test_bin_incr5 :\n\t\tbin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\n(* FILL IN HERE *) Admitted.\n\nExample test_bin_incr6 :\n\t\tbin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Testing Your Solutions *)\n\n(** Each SF chapter comes with a test file containing scripts that\n\tcheck whether you have solved the required exercises. If you're\n\tusing SF as part of a course, your instructors will likely be\n\trunning these test files to autograde your solutions. You can also\n\tuse these test files, if you like, to make sure you haven't missed\n\tanything.\n\n\tImportant: This step is _optional_: if you've completed all the\n\tnon-optional exercises and Coq accepts your answers, this already\n\tshows that you are in good shape.\n\n\tThe test file for this chapter is [BasicsTest.v]. To run it, make\n\tsure you have saved [Basics.v] to disk.  Then do this:\n\n\t   coqc -Q . LF Basics.v\n\t   coqc -Q . LF BasicsTest.v\n\n\tIf you accidentally deleted an exercise or changed its name, then\n\t[make BasicsTest.vo] will fail with an error that tells you the\n\tname of the missing exercise.  Otherwise, you will get a lot of\n\tuseful output:\n\n\t- First will be all the output produced by [Basics.v] itself.  At\n\t  the end of that you will see [COQC BasicsTest.v].\n\n\t- Second, for each required exercise, there is a report that tells\n\t  you its point value (the number of stars or some fraction\n\t  thereof if there are multiple parts to the exercise), whether\n\t  its type is ok, and what assumptions it relies upon.\n\n\t  If the _type_ is not [ok], it means you proved the wrong thing:\n\t  most likely, you accidentally modified the theorem statement\n\t  while you were proving it.  The autograder won't give you any\n\t  points for that, so make sure to correct the theorem.\n\n\t  The _assumptions_ are any unproved theorems which your solution\n\t  relies upon.  \"Closed under the global context\" is a fancy way\n\t  of saying \"none\": you have solved the exercise. (Hooray!)  On\n\t  the other hand, a list of axioms means you haven't fully solved\n\t  the exercise. (But see below regarding \"Allowed Axioms.\") If the\n\t  exercise name itself is in the list, that means you haven't\n\t  solved it; probably you have [Admitted] it.\n\n\t- Third, you will see the maximum number of points in standard and\n\t  advanced versions of the assignment.  That number is based on\n\t  the number of stars in the non-optional exercises.\n\n\t- Fourth, you will see a list of \"Allowed Axioms\".  These are\n\t  unproved theorems that your solution is permitted to depend\n\t  upon.  You'll probably see something about\n\t  [functional_extensionality] for this chapter; we'll cover what\n\t  that means in a later chapter.\n\n\t- Finally, you will see a summary of whether you have solved each\n\t  exercise.  Note that summary does not include the critical\n\t  information of whether the type is ok (that is, whether you\n\t  accidentally changed the theorem statement): you have to look\n\t  above for that information.\n\n\tExercises that are manually graded will also show up in the\n\toutput.  But since they have to be graded by a human, the test\n\tscript won't be able to tell you much about them.  *)\n\n(* 2021-08-11 15:08 *)\n", "meta": {"author": "MiguelANunes", "repo": "MFO", "sha": "07b8a8b9ad9e3891499985db59b17dcce7c15dbe", "save_path": "github-repos/coq/MiguelANunes-MFO", "path": "github-repos/coq/MiguelANunes-MFO/MFO-07b8a8b9ad9e3891499985db59b17dcce7c15dbe/SoftwareFoundations/lf/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7805672347424663}}
{"text": "Require Import ZArith.\nRequire Import Omega.\nRequire Import List.\nRequire Import FunctionalExtensionality.\n\nImport ListNotations.\n\nRequire Import seqi.\nRequire Import listutils.\n\nOpen Scope Z_scope.\n\nFixpoint rollingSumH (n : Z) (lst : list Z) : list Z :=\n  match lst with\n  | nil => [n]\n  | (x::xs) => n :: rollingSumH (x+n) xs\n  end.\n\nDefinition rollingSum (input : list Z): list Z :=\n  rollingSumH 0 input.\n\nLemma rollingSumH_n : forall l n,\n  rollingSumH n l = map (fun x => x + n) (rollingSumH 0 l).\nProof.\ninduction l;intros;simpl in *;auto.\nf_equal.\nrewrite IHl.\nrewrite  Z.add_0_r.\nrewrite (IHl a).\nrewrite map_map.\nf_equal.\napply functional_extensionality.\nintros.\nomega.\nQed.\n\nExample ex_rollingSum_summ :\n  let l := [3;-5;8;3;9] in\n  rollingSum l = map (fun i => sum (firstn i l)) (seq 0 (length l+1)).\nProof.\nunfold rollingSum.\nsimpl.\nauto.\nQed.\n\nExample ex_rollingSumH_summ :\n  let l := [3;-5;8;3;9] in\n  let a := 7 in\n  rollingSumH a l = map (fun i => sum (firstn i l) + a) (seq 0 (length l + 1)).\nProof.\nsimpl.\nauto.\nQed.\n\n\nLemma rollingSumH_summ : forall a (l : list Z),\n   rollingSumH a l = map (fun i => sum (firstn i l) + a) (seq 0 (length l + 1)).\nProof.\nintros.\ngeneralize dependent a.\ninduction l;intros;auto.\nsimpl rollingSumH.\nrewrite IHl.\nsimpl. f_equal.\nrewrite <- seq_shift.\nrewrite map_map.\napply map_eq.\nintros.\napply in_seq in H.\nsimpl.\nomega.\nQed.\n\nLemma rollingSum_summ : forall l,\n  rollingSum l = map (fun i => sum (firstn i l)) (seq 0 (length l + 1)).\nProof.\nintros.\nunfold rollingSum.\nrewrite rollingSumH_summ.\napply map_eq;intros. omega.\nQed.\n\n(* Close Scope Z_scope. *)", "meta": {"author": "bartavelle", "repo": "fulcrum-coq", "sha": "3f7293d538ef58cff88ebdae5c6a759b77610a52", "save_path": "github-repos/coq/bartavelle-fulcrum-coq", "path": "github-repos/coq/bartavelle-fulcrum-coq/fulcrum-coq-3f7293d538ef58cff88ebdae5c6a759b77610a52/rollingsum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7805448458866328}}
{"text": "Require Import ZArith.\nOpen Scope Z_scope.\n\n\nInductive Z_btree : Set :=\n  Z_leaf : Z_btree | \n  Z_bnode : Z -> Z_btree -> Z_btree -> Z_btree.\n\n\nInductive Z_fbtree : Set :=\n | Z_fleaf : Z_fbtree \n | Z_fnode : Z  -> (bool -> Z_fbtree) -> Z_fbtree.\n\n\nDefinition Zf_mknode (z : Z) (t1 t2 : Z_fbtree) : Z_fbtree :=\n   Z_fnode z (fun b => if b then t1 else t2).\n\nDefinition fleft_son  (t:Z_fbtree) : Z_fbtree :=\n match t with \n | Z_fleaf => Z_fleaf\n | Z_fnode a f => f true\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 f1 (t:Z_btree) : Z_fbtree :=\n  match t with\n  | Z_leaf => Z_fleaf\n  | Z_bnode z t1 t2 => Zf_mknode z (f1 t1) (f1 t2)\n  end.\n\n\nFixpoint f2 (t:Z_fbtree) : Z_btree :=\n  match t with\n  | Z_fleaf => Z_leaf\n  | Z_fnode z f => Z_bnode z (f2 (f true)) (f2 (f false))\n  end.\n\n\nTheorem f2_f1 : forall t: Z_btree, f2 (f1 t) = t.\nProof.\n induction t; simpl; auto.\n rewrite IHt1; rewrite IHt2; trivial.\nQed.\n\nSection Extensionnality.\n Hypothesis extensionality : forall (A B:Set) (f g: A -> B),\n                             (forall a, f a = g a)-> f =g.\n\n Theorem f1_f2 :  forall t: Z_fbtree, f1 (f2 t) = t.\n Proof.\n  induction t; simpl; auto.\n  do 2 rewrite H.\n  unfold Zf_mknode.\n  rewrite <- (extensionality _ _ \n                (fun b:bool =>  if b then z0 true else z0 false)\n                z0). \n  trivial.\n  destruct a; simpl; trivial.\n Qed.\nEnd Extensionnality.\n\nCheck f1_f2.\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/structinduct/SRC/tree_bij.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7804892112649005}}
{"text": "Require Import Axioms.\nRequire Import Types.\n\n(* This file contains the definition of an Abelian Monoid, \n   and then, an axiomatic definition of a Key-Value Set, as an Abelian Monoid, with more\n   axioms and properties.\n   The Key-Value Set uses generic types for its keys and values, so in order to use it,\n   you must plug-in the module types of type ModuleType (see Types.v). *)\n\nModule Type AbelianMonoid.\n\n  (* Type of Abelian Monoid *)\n  Parameter T : Type.\n\n  (* Constructors *)\n  Parameter null : T.\n  Parameter mult : T -> T -> T.\n\n  (* Notations *)\n  Notation \"s1 'o' s2\" := (mult s1 s2) (at level 20, left associativity).\n\n  (* Decision *)\n  Parameter decide_empty : forall (s : T), { s = null }+{ s <> null }.\n\n  (* Axioms of Monoid *)\n  Parameter assoc : forall m1 m2 m3, (m1 o m2) o m3 = m1 o (m2 o m3).\n  \n  Parameter id_l : forall m, null o m = m.\n  Parameter id_r : forall m, m o null = m.\n\n  (* The Axiom of Commutativity *)\n  Parameter commut : forall m1 m2, m1 o m2 = m2 o m1.\n\n  Lemma equal_commut : forall (m1 m2 : T), m1 = m2 -> m2 = m1.\n  Proof.\n    intros. rewrite -> H. reflexivity.\n  Qed.\n\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\nEnd AbelianMonoid.\n\nModule Type KeyValueSet ( M : AbelianMonoid ) ( KM : Types.ModuleType ) ( VM : Types.ModuleType ).\n\n  (* The Type *)\n  Definition T : Type := M.T.\n\n  Definition K : Type := KM.T.\n  Definition V : Type := VM.T.\n\n  (* Constructors *)\n  Parameter append : T -> K -> V -> T.\n  \n  Definition empty := M.null.\n\n  Notation \"'[' k v ']'\" := (append empty k v) (at level 15).\n\n  Parameter alloc : T -> K.\n\n  (* Decision *)  \n  Parameter decide_append : forall (s : T), \n      s <> empty -> \n      exists s' k v, s = append s' k v.\n\n  Parameter decide_append_empty : forall s' k v, empty = append s' k v -> False.\n\n  Lemma empty_union : forall s1 s2, M.mult s1 s2 = empty -> s1 = empty /\\ s2 = empty.\n  Proof. Admitted.\n\n  Proposition decide_append_iff : forall (s : T),\n      s <> empty <->\n      exists s' k v, s = append s' k v.\n  Proof.\n    split.\n    - apply decide_append.\n    - intros. inversion H; subst. inversion H0; subst. inversion H1; subst.\n      unfold not. intros H'. eapply decide_append_empty. rewrite <- H'. reflexivity.\n  Qed.\n      \n  (* Relation between Append and Concat *)\n  Notation \"s1 'o' s2\" := (M.mult s1 s2) (at level 20, left associativity).\n\n  Parameter append_concat : forall s1 s2 s' k v, \n      s2 = append s' k v -> \n      s1 o s2 = append (s1 o s') k v.\n\n  Proposition append_to_concat : forall s' k v, \n      append s' k v = s' o (append empty k v).\n  Proof.\n    intros. erewrite -> append_concat with (s' := empty) (k := k) (v := v); try reflexivity.\n    rewrite -> M.id_r. reflexivity.\n  Qed.\n\n  Proposition append_commut : forall s k v k' v',\n      append (append s k v) k' v' = append (append s k' v') k v.\n  Proof.\n    intros. rewrite -> append_to_concat. rewrite -> append_to_concat.\n    rewrite <- M.id_r with (m := s o (append empty k v) o (append empty k' v')).\n    rewrite -> M.exchange. rewrite -> M.id_r. repeat rewrite <- append_to_concat.\n    reflexivity.\n  Qed.\n\n  (* Remove *)\n  Parameter remove : T -> K -> T.\n\n  Parameter remove_append : forall s k v, remove (append s k v) k = s.\n\n  (* Membership *)\n  Inductive contains : T -> K -> V -> Prop :=\n  | contains_append : forall s s' k v, s = append s' k v -> contains s k v\n  | contains_append_set : forall s' k v k' v', k <> k' -> contains s' k' v' -> contains (append s' k v) k' v'.\n\n  Proposition empty_contains : forall k v, contains empty k v -> False.\n  Proof.\n    intros. inversion H; subst.\n    - apply decide_append_empty in H0. apply H0.\n    - assert (H' : empty = append s' k0 v0). { rewrite <- H0. reflexivity. }\n      apply decide_append_empty in H'. apply H'.\n  Qed.\n\n  (* Key Membership *)\n  Inductive contains_key : T -> K -> Prop :=\n  | contains_key_append : forall s s' k v, s = append s' k v -> contains_key s k\n  | contains_key_append_set : forall s' k v k', k <> k' -> \n    contains_key s' k' -> contains_key (append s' k v) k'.\n\n  Proposition empty_contains_key : forall k, contains_key empty k -> False.\n  Proof.\n    intros. inversion H.\n    - apply decide_append_empty in H0. apply H0.\n    - apply M.equal_commut in H0. apply decide_append_empty in H0. apply H0.\n  Qed.\n\n  Parameter remove_not_contained : forall s k, \n    ~ contains_key s k -> remove s k = s.\n\n  Lemma contains_exists : forall (S S' : M.T) k v,\n    contains S k v ->\n    exists S', S = append S' k v.\n  Proof.\n    intros. induction H.\n    - exists s'. subst. reflexivity.\n    - inversion IHcontains as [s'']. subst s'. exists (append s'' k v). apply append_commut.\n  Qed.\n\n  Proposition remove_empty : forall k, remove empty k = empty.\n  Proof.\n    intros. apply remove_not_contained. unfold not. intros. \n    eapply empty_contains_key. apply H.\n  Qed.\n\n  Parameter decide_cross_append : forall s s' k k' v v',\n    append s k' v' = append s' k v ->\n    (k = k' /\\ v = v' /\\ s = s') \\/ (k <> k' /\\ contains s k v /\\ contains s' k' v').\n\n  Parameter contains_contains_key : forall S k, \n    (exists v, contains S k v) <-> contains_key S k.\n\n  Lemma contains_set_append_law : forall s k v k' v',\n    contains (append s k' v') k v ->\n    (k = k' /\\ v = v') \\/ contains s k v.\n  Proof.\n    intros. remember H as H'. clear HeqH'. inversion H; subst.\n    - apply decide_cross_append in H0. inversion H0 as [H1 | H1].\n      + inversion H1. inversion H3. left. split; try apply H2; try apply H4.\n      + inversion H1. right. inversion H3. apply H4.\n    - remember H0 as H0'. clear HeqH0'. apply decide_cross_append in H0. inversion H0.\n      + right. inversion H3 as [H3' H3'']. inversion H3'' as [H3''' H3'''']. \n        subst k0 v0 s'. apply H2.\n      + assert (exclusi : {(k = k' /\\ v = v')} + {~(k = k' /\\ v = v')}).\n        { apply principium_tertii_exclusi with (P := (k = k' /\\ v = v')). }\n        admit.\n  Qed.\n\n  (* No Duplications *)\n  Parameter unique_append : forall s' k v, contains s' k v -> append s' k v = s'.\n\n  Lemma contains_unique : forall s' k v v', \n      contains s' k v -> contains s' k v' -> v = v'.\n  Proof.\n  Admitted.\n\n  (* Theorems *)\n  Proposition factor : forall s1 s2 k v k' v',\n      (append (append s1 k v) k' v') o s2 = s1 o (append empty k v) o (append empty k' v') o s2.\n  Proof.\n    intros. rewrite -> append_to_concat. rewrite -> append_to_concat. reflexivity.\n  Qed.\n\n  Lemma exchange : forall s1 s2 k v k' v',\n      (append (append s1 k v) k' v') o s2 = (append (append s1 k' v') k v) o s2.\n  Proof.\n    intros. repeat rewrite -> factor. apply M.exchange.\n  Qed.\n\nEnd KeyValueSet.\n\nModule Test ( M : AbelianMonoid ) ( m_nat : Types.ModuleNat ) ( kvs : KeyValueSet M m_nat m_nat ).\n  Import kvs.\n  \n  Definition test_set : kvs.T := append (append empty 1 2) 2 3.\n\n  Example test_set_contains : contains test_set 1 2.\n  Proof.\n    compute. apply contains_append_set. \n    - auto.\n    - eapply contains_append. reflexivity.\n  Qed.\n\nEnd Test.\n", "meta": {"author": "aerabi", "repo": "llc", "sha": "66193df6fbc0aee0b1111720399ab6efc60d2ac5", "save_path": "github-repos/coq/aerabi-llc", "path": "github-repos/coq/aerabi-llc/llc-66193df6fbc0aee0b1111720399ab6efc60d2ac5/Legacy/SetCtx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7804826786765714}}
{"text": "Require Import List.\nRequire Import ZArith.\nImport ListNotations.\nRequire Import Bool.\nOpen Scope Z_scope.\n\n\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 ->\n        sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\nHint Resolve sorted0 sorted1 sorted2 : sort.\n\n\nFixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => O\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\nPrint nb_occ.\n\nDefinition equiv (l l':list Z) := \n    forall z:Z, nb_occ z l = nb_occ z l'.\n\nLemma equiv_refl : forall l:list Z, equiv l l.\nProof.\n unfold equiv. trivial.\nQed.\n\nLemma equiv_sym : forall l l':list Z, equiv l l' -> equiv l' l.\nProof.\n  unfold equiv. \n  intros l l' H. symmetry. apply H.\nQed.\n\nLemma equiv_trans :\n forall l l' l'':list Z, equiv l l' -> \n                         equiv l' l'' -> \n                         equiv l l''.\nProof.\n intros l l' l'' H H0 z.\n eapply trans_eq; eauto.\nQed.\n\nLemma equiv_cons :\n forall (z:Z) (l l':list Z), equiv l l' -> \n                             equiv (z :: l) (z :: l').\nProof.\n intros z l l' H z'. \n simpl; case (Z_eq_dec z' z); auto. \nQed.\n\nLemma equiv_perm :\n forall (a b:Z) (l l':list Z),\n   equiv l l' -> \n   equiv (a :: b :: l) (b :: a :: l').\nProof.\n intros a b l l' H z; simpl.\n case (Z_eq_dec z a); case (Z_eq_dec z b); \n  simpl; case (H z); auto.\nQed.\n\nHint Resolve equiv_cons equiv_refl equiv_perm : sort.\n\n\nFixpoint bubble (z:Z) (l:list Z) : 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 :: (bubble a l')\n      | right _ => a :: (bubble z l')\n      end\n  end.\n\n\nEval compute in bubble 5 [7;0;1;2;3;6].\n\nLemma bubble_equiv : forall (l:list Z) (x:Z), \n                  equiv (x :: l) (bubble x l).\nProof.\n induction l as [|a l0 H] ; auto with sort.\n intros x. simpl. case (Z_le_gt_dec x a).\n   intros. auto with sort.\n intro; apply equiv_trans with (a :: x :: l0);\n   auto with sort.\nQed.\n\n\nLemma sorted_subs: forall (l:list Z) (x:Z) (z:Z), sorted (x::l) -> (z<=x)-> sorted (z::l).\nProof.\n  intros. induction l. auto with sort. apply sorted2. rewrite H0. \n  inversion H. apply H3. inversion H. apply H5.\nQed.\n\nLemma sorted_elim_fst: forall (l:list Z) (a:Z), sorted (a::l) -> sorted l.\nProof.\n  intros. induction l. auto with sort. inversion H. apply H4.\nQed.\n\nLemma sorted_elim_snd : forall (l:list Z) (a b:Z), sorted (a::b::l) -> sorted (a::l).\nProof.\n  intros. induction l. auto with sort. inversion H.\n  apply sorted_subs with (a0::l) b a in H4. apply H4. apply H2.\nQed.\n\nLemma sorted_add: forall (l : list Z) (x a: Z), sorted (a::l) -> x<=a -> sorted (x::a::l).\nProof.\n  auto with sort.\nQed.\n\n(*Lemma my7: forall (x: Z), x = x.\nProof.\n  intros. auto.\nQed.*)\n\nLemma nb_occ_nil: forall  (l : list Z), (forall (a : Z),  nb_occ a l = 0%nat) -> l = [].\nProof.\n  induction l. simpl. auto.  \n  intro. assert (H0:=H a). simpl in H0. case (Z.eq_dec a a) in H0.\n  symmetry in H0. Check O_S. apply O_S in H0. contradiction. intuition. (*assert (HH:= eq_refl a). contradiction. *)\nQed.\n\nLemma equiv_nil: forall (l : list Z), equiv l [] -> l = [].\n  induction l. auto. intro.\n  unfold equiv. apply nb_occ_nil in H. apply H. \nQed.\n\nLemma equiv_elim: forall (l l' :list Z) (z: Z), equiv (z::l) (z::l') -> equiv l l'.\nProof.\n  unfold equiv. intros l l' z H z0.\n  assert (H1:= H z0). simpl in H1. case (Z.eq_dec z0 z) in H1. apply eq_add_S in H1. auto. auto.\nQed.\n\nLemma equiv_add: forall (l l' :list Z) (z: Z), equiv l l' -> equiv (z::l) (z::l').\nProof.\n  unfold equiv. intros l l' z H z0.\n  assert (H1:= H z0). simpl. case (Z.eq_dec z0 z). intros. apply eq_S. auto. auto.\nQed.\n\n\nLemma equiv_cons1: forall (l:list Z) (a:Z), equiv (a::l) [a] -> (a::l) = [a].\nProof.\n  induction l. intros. auto. \n  intros. assert (H1:=IHl a0). \n  unfold equiv in H. assert (H2:= H a). simpl in H2. case (Z.eq_dec a a0) in H2. case (Z.eq_dec a a) in H2. symmetry in H2.\n  \n  apply eq_add_S in H2. apply O_S in H2. contradiction.\n  intuition. (*assert (HH:= eq_refl a). (**???*) contradiction. *)\n  case (Z.eq_dec a a) in H2. symmetry in H2. apply O_S in H2. contradiction. intuition. (* assert (HH:= eq_refl a). (**???**) contradiction. *)\nQed.\n\nLemma equiv_cons2: forall  (a b:Z) (l:list Z), equiv (a::l) [b] -> ((a = b) /\\ ((a::l) = [a])).\nProof.\n  intros a b. case (Z.eq_dec a b). intros. split. auto. apply equiv_cons1. symmetry in e. rewrite e in H. auto.\n  intros. unfold equiv in H. assert (H1:= H a).\n  simpl in H1. case (Z.eq_dec a a) in H1. case (Z.eq_dec a b) in H1. contradiction. \n    symmetry in H1. apply O_S in H1. contradiction. intuition. (*assert (HH:= eq_refl a). contradiction.*)\nQed.\n\nDefinition minimum (m:Z) (l:list Z) := \n    forall z:Z, (nb_occ z l > 0)%nat -> m <= z.\n\nEval compute in minimum 5 [1;2;3].\n\n(*Lemma help1: forall (x: nat), (x > x)%nat -> False.\nProof.\n  intros. assert (H1:=eq_refl x). inversion H. intuition. intuition. \nQed.*)\n\nLemma sorted_min: forall (l:list Z) (m:Z), sorted (m::l) -> minimum m l.\nProof.\n  induction l. intros. unfold minimum. intros. simpl in H0. intuition. (*assert(H2:=help1 0). apply H2 in H0. contradiction.*)\n  intros. assert (H0:= IHl m). assert(H4:=H). apply sorted_elim_snd in H. apply H0 in H. case (Z_le_gt_dec m a).\n  intros. unfold minimum. intros. unfold minimum in H. assert (H2:=H z). simpl in H1. case (Z.eq_dec z a) in H1.\n  symmetry in e. rewrite e in l0. auto. apply H2. apply H1.\n  intros. inversion H4. contradiction.\nQed.\n\n(*Lemma help2: forall (x:nat), (S x > 0)%nat.\nProof.\n  intros. induction x. auto. auto.\nQed.*)\n\nLemma min_sorted: forall (l:list Z) (m:Z), sorted l -> minimum m l -> sorted (m::l).\nProof.\n  induction l. auto with sort.\n  intros. case (Z_le_gt_dec m a). intros. apply sorted_add with l m a in H. apply H. auto. \n  intros. assert(H4:=H0). unfold minimum in H0. assert(H1:=H0 a). simpl in H1. case (Z.eq_dec a a) in H1. \n  intuition. intuition.\n  (*assert (H2:=help2 (nb_occ a l)). apply H1 in H2. contradiction. assert (H2:= eq_refl a). contradiction.*)\nQed.\n\nLemma min_eq: forall (l l':list Z) (m:Z), equiv l l' -> minimum m l -> minimum m l'.\nProof.\n  intros. unfold minimum. intros. unfold minimum in H0. apply H0. unfold equiv in H. assert (H2:=H z).\n  rewrite H2. apply H1.\nQed.\n\nLemma minimum_cons: forall (l:list Z) (a x:Z), minimum a l -> a <= x -> minimum a (x::l).\nProof.\n  unfold minimum. intros. simpl in H1. case (Z.eq_dec z x) in H1. symmetry in e. rewrite e in H0. apply H0.\n  assert (H2:=H z). apply H2 in H1. apply H1.\nQed.\n\n(*Lemma help3: forall (a x: Z), x > a -> a <= x.\nProof.\n  intros. intuition.\nQed.*)\n\nLemma bubble_sorted :\n forall (l:list Z) (x:Z), sorted l -> sorted (bubble x l).\nProof.\ninduction l. simpl; auto with sort.\nintros. simpl. assert (H1 := H). case (Z_le_gt_dec x a). intro.\napply sorted_elim_fst in H. apply IHl with a in H. apply sorted_add with l x a in H1.\napply sorted_min in H1. apply min_sorted. apply H. Check bubble_equiv. assert (H2:= bubble_equiv l a). \napply min_eq with (a :: l) . apply H2. apply H1. apply l0.\nintros. apply sorted_elim_fst in H. apply IHl with x in H. apply min_sorted. apply H. \nassert (H2:=bubble_equiv l x). apply min_eq with (x::l). apply H2. apply minimum_cons. apply sorted_min in H1.\napply H1. intuition. (*apply my16. apply g.*)\nQed.\n\n\nDefinition Z_sort :\n  forall l:list Z, {l' : list Z | equiv l l' /\\ sorted l'}.\n induction l as [| a l IHl]. \n exists (nil (A:=Z)); split; auto with sort.\n case IHl; intros l' [H0 H1].\n exists (bubble a l'). split.\n apply equiv_trans with (a :: l'). auto with sort.\n apply bubble_equiv.\n apply bubble_sorted; auto.\nDefined.\n\n\n\nExtraction Language Haskell.\nExtraction \"/Users/User/Documents/IndependentWork/InsertionSort/certified_sorting/bubble_sort.hs\" bubble Z_sort.\n\n\n\n\n\n", "meta": {"author": "AlexandraOlegovna", "repo": "certified_sorting", "sha": "7395d83a0802335c984e3c750d64e642d3daf217", "save_path": "github-repos/coq/AlexandraOlegovna-certified_sorting", "path": "github-repos/coq/AlexandraOlegovna-certified_sorting/certified_sorting-7395d83a0802335c984e3c750d64e642d3daf217/bubble_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7804821519781094}}
{"text": "(**\n* PSet2b: Induction in Coq (240 points)\n*)\n\nRequire Import List Arith.\n\n(**********************************************************************)\n\n(* Exercise: app_assoc coq [10 points].\n   In Coq, the list append operator is written [++]. Complete the following\n   proof by induction, which shows that application is associative.\n   Hint:  the solution is in the lecture slides. *)\n\nTheorem app_assoc : forall (A:Type) (l1 l2 l3 : list A),\n  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n  intros A l1 l2 l3.\n  induction l1 as [ | h t IH].\n  (* FILL IN, and change [Abort] to [Qed]. *)\nAbort.\n\n(**********************************************************************)\n\n(* Exercise: app_assoc math [20 points].\n\nProve that the OCaml [@] operator is also associative.  Your answer should\nbe a mathematical proof, not a Coq proof.  We have supplied part of the\nproof for you.\n\nTheorem:  for all lists lst1, lst2, and lst3,\n  lst1 @ (lst2 @ lst3) = (lst1 @ lst2) @ lst3.\n\nProof:  by induction on lst1.\nThe property being proved is:\nP(l) = FILL IN\n\nCase:  lst1 = []\nShow:  FILL IN\n\nCase: lst1 = h::t\nIH:  FILL IN\nShow:  FILL IN\n\nQED\n\n*)\n\n(**********************************************************************)\n\n(* Exercise: rev_append math [30 points].\n\nProve the following theorem, which shows how list reversal distributes\nover list append.\n\nTheorem: for all lists lst1 and lst2,\n  rev (lst1 @ lst2) = rev lst2 @ rev lst1.\n\nRecall that [rev] is defined as follows:\n<<\nlet rec rev = function\n  | [] -> []\n  | h::t -> rev t @ [h]\n>>\n\nYour answer should be a mathematical proof, not a Coq proof. In the inductive\ncase, you will need the lemma proved above saying that append is associative. In\nthe base case, you will need this lemma:\n\nLemma:  for all lists lst, lst @ [] = lst.\nProof:  given in lecture.\n\nHere, again, is the theorem you should prove:\n\nTheorem: for all lists lst1 and lst2,\n  rev (lst1 @ lst2) = rev lst2 @ rev lst1.\n\nProof:  FILL IN\n\n*)\n\n(**********************************************************************)\n\n(* Exercise: rev_append coq [30 points].\n\nNow prove the same theorem as the previous exercise, but in Coq.\nThe Coq list reversal function [rev] is defined in the standard\nlibrary for you.  Use the mathematical proof you gave above\nas a guide.  For the base case, you will need the lemma [app_nil]\nthat we proved in lecture; we've inserted the code for it below.\nYou can use that lemma in your own proof with the [rewrite] tactic.\n*)\n\nLemma app_nil : forall (A:Type) (lst : list A),\n  lst ++ nil = lst.\nProof.\n  intros A lst.\n  induction lst as [ | h t IH].\n  - trivial.\n  - simpl. rewrite -> IH. trivial.\nQed.\n\nTheorem rev_append : forall (A:Type) (lst1 lst2 : list A),\n  rev (lst1 ++ lst2) = rev lst2 ++ rev lst1.\nProof.\n  (* FILL IN, and change [Abort] to [Qed] *)\nAbort.\n\n(**********************************************************************)\n\n(* Exercise: rev involutive [30 points].\n\nProve that [rev] is _involutive_, meaning that it is its own inverse. That is,\n[rev (rev lst) = lst].\n\nHint:  for the inductive case, there is a lemma that has already been proved in\nthis lab that you will find very helpful.  Part of this exercise is figuring out\nwhich lemmma that is.\n*)\n\nTheorem rev_involutive : forall (A:Type) (lst : list A),\n  rev (rev lst) = lst.\nProof.\n  (* FILL IN, and change [Abort] to [Qed] *)\nAbort.\n\n(**********************************************************************)\n\n(* Exercise: app_length [Optional].\nProve the following theorem in Coq.\n*)\n\n(*\nTheorem app_length : forall (A:Type) (l1 l2 : list A),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  (* FILL IN, and change [Abort] to [Qed] *)\nAbort.\n*)\n\n(**********************************************************************)\n\n(* Exercise: rev_length [Optional].\nProve the following theorem in Coq.\n\nHint: previous exercise(s) as lemma, and the [ring] tactic.\n*)\n\n(*\nTheorem app_rev : forall (A:Type) (lst : list A),\n  length (rev lst) = length lst.\nProof.\n  (* FILL IN, and change [Abort] to [Qed] *)\nAbort.\n*)\n\n(**********************************************************************)\n\n(* INDUCTION ON BINARY TREES *)\n\n(* Here is a Coq type for binary trees: *)\nInductive tree (A : Type) : Type :=\n  | Leaf : tree A\n  | Node : tree A -> A -> tree A -> tree A.\n\n(* The following commands cause the [A] argument to\n   be implicit to the [Leaf] and [Node] constructors. *)\n   Arguments Leaf [A].\n   Arguments Node [A] _ _ _.\n\n(* The equivalent OCaml type would be:\n<<\ntype 'a tree =\n  | Leaf\n  | Node of 'a tree * 'a * 'a tree\n>>\n*)\n\n(* The _reflection_ operation swaps the left and right\n   subtrees at every node. *)\nFixpoint reflect {A : Type} (t : tree A) :=\n  match t with\n  | Leaf => Leaf\n  | Node l v r => Node (reflect r) v (reflect l)\n  end.\n\n(* The equivalent OCaml function would be:\n<<\nlet rec reflect = function\n  | Leaf -> Leaf\n  | Node (l,v,r) -> Node (reflect r, v, reflect l)\n>>\n*)\n\n(* A proof by induction on a binary tree has the following structure:\n\nTheorem:  For all binary trees t, P(t).\n\nProof: by induction on t.\n\nCase: t = Leaf\nShow: P(Leaf)\n\nCase: t = Node(l,v,r)\nIH1:  P(l)\nIH2:  P(r)\nShow:  P(Node(l,v,r))\n\nQED\n\nNote that we get _two_ inductive hypotheses in the inductive\ncase, one for each subtree.\n*)\n\n(**********************************************************************)\n\n(* Exercise: tree_ind [20 points].\nExplain the output of the following command in your own words, relating it to\nthe proof structure given above for induction on binary trees.\nHint: read the notes on induction principles.\n*)\n\nCheck tree_ind.\n\n(**********************************************************************)\n\n(* Exercise: reflect_involutive math [30 points].\nProve the following theorem mathematically (not in Coq).\n\nTheorem:  for all trees t, reflect (reflect t) = t\n\nProof: by induction on t.\nP(t) = reflect (reflect t) = t\n\nCase: t = Leaf\nShow: FILL IN\n\nCase: t = Node(l,v,r)\nIH1: P(l) = reflect(reflect l) = l\nIH2: P(r) = reflect(reflect r) = r\nShow: FILL IN\n\nQED\n*)\n\n(**********************************************************************)\n\n(* Exercise: reflect_involutive coq [30 points].\nState and prove a theorem in Coq that shows reflect is involutive.\nUse your mathematical proof from the previous exercise as a guide.\n\nHint: the [induction] tactic expects the arguments for the inductive\ncase in the following order:  the left subtree, the IH for the left subtree,\nthe value at the node, the right subtree, and the IH for the right subtree.\n*)\n\n(*\nUNCOMMENT AND COMPLETE\nTheorem reflect_involutive : ...\n*)\n\n(**********************************************************************)\n\n(* Exercise: height [40 points].\n\n1. Write a Coq function [height] that computes the height of a binary tree.\nRecall that the height of a leaf is 0, and the height of a node is 1 more than\nthe maximum of the heights of its two subtrees.  The standard library does\ncontain a [max] function that will be helpful.\n\n2. Prove that [reflect] preserves the height of a tree.  Hint: [Nat.max_comm].\n\n3. Write a Coq function [perfect : nat -> tree nat], such that\n[perfect h] constructs the perfect binary tree of height [h], and\nthe value at the root is [1], and if the value at a node is [v],\nthen the values of its left and right subnodes are [2*v] and [2*v+1].\nFor example, [perfect 3] is\n<<\nNode (Node (Node Leaf 4 Leaf) \n           2 \n           (Node Leaf 5 Leaf)) \n     1\n     (Node (Node Leaf 6 Leaf) \n           3 \n           (Node Leaf 7 Leaf))\n>>\n\n4. Prove that the height of [perfect h] is in fact [h].  Hint 1: induct\non [h].  Hint 2: don't introduce all the variables. Hint 3:\n[Nat.max_idempotent].\n*)\n", "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/assignments/pset2b/pset2b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7804821426805878}}
{"text": "Require Import List.\n\nPrint list.\n\nCheck list_ind.\n\nDefinition tl {A:Type} (l: list A) : list A :=\nmatch l with\n| nil => nil\n| a::l' => l'\nend.\nCompute tl (3::5::8::nil).\n\n(**\nFixpoint app {A:Type} (l l' : list A) : list A :=\nmatch l with \n| nil => l'\n| a:: m => a :: (app m l')\nend.\n*)\n\n\n\nCompute (1::2::3::nil) ++ (5::6::nil).\n\nLemma app_assoc {A:Type} :\n forall l l' l'' : list A, (l ++ l') ++ l'' = l ++ (l' ++ l'').\nProof.\n  induction l.\n  - simpl. intros;reflexivity.\n  - simpl. intros.  rewrite IHl.\n    reflexivity.\nQed.\n\nFixpoint In {A:Type} (x:A)(l : list A) : Prop  :=\nmatch l with\n| nil => False\n| y :: l' => x = y \\/ In x l'\nend.\n\nInductive mem {A:Type} (x:A) : list A -> Prop  :=\n| mem_hd : forall l', mem x (x::l')\n| mem_tl : forall y l', mem x l' -> mem x (y::l').\n\nFixpoint memb  {A:Type} (eqb : A -> A -> bool) (x:A) (l : list A) :=\nmatch l with\n| nil => false\n| y :: l' => if eqb x y then true else memb eqb x l'\nend.\n\n\nLemma mem_In : forall A (x:A) l, mem x l -> In x l.\nProof.\n  intros A x l H.\n  induction H.\n  - simpl.\n    left;trivial.\n  -  simpl.\n    right;assumption.\nQed.\n\nLemma In_mem : forall A (x:A) l, In x l -> mem x l.\nProof.\n  induction l.\n  - intro H.\n    inversion H.  \n  -  intro H; inversion H.\n     + subst x; constructor.\n     + constructor. \n      apply IHl; assumption.\nQed. \n\nLemma memb_In {A:Type}(eqb: A -> A -> bool)\n      : forall (x:A) l, memb eqb x l = true -> In x l.\nProof.\n induction l.\n - simpl.\n   discriminate.\n - simpl.\n   intro H; case_eq (eqb x a).\n   + Abort.\n\nDefinition correct_eq {A:Type}(eqb : A -> A -> bool) :=\n forall x y : A, eqb x y = true <-> x = y.\n \nLemma memb_In {A:Type}(eqb: A -> A -> bool)(Ok : correct_eq eqb) \n      : forall (x:A) l, memb eqb x l = true -> In x l.\nProof.\n induction l.\n - simpl.\n   discriminate.\n - simpl.\n   intro H; case_eq (eqb x a).\n   + rewrite (Ok x a).\n     auto.\n   +  intro H0;rewrite H0 in H.  \n      auto.\nQed.\n\nLemma In_memb {A:Type}(eqb: A -> A -> bool)(Ok : correct_eq eqb) \n      : forall (x:A) l, In x l -> memb eqb x l = true.\nProof.\n induction l.\n - simpl.\n  contradiction.\n - simpl. intro H.\n   destruct H.\n   rewrite <- (Ok x a) in H.\n   now rewrite H.\n   rewrite IHl.\n   now  destruct (eqb x a).   \n   assumption.\nQed.\n\n", "meta": {"author": "jordane51", "repo": "MTOCPLCOQ", "sha": "586564bf0ff303582e6a429b6eb42dd167ae73f6", "save_path": "github-repos/coq/jordane51-MTOCPLCOQ", "path": "github-repos/coq/jordane51-MTOCPLCOQ/MTOCPLCOQ-586564bf0ff303582e6a429b6eb42dd167ae73f6/OnLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.90192067455231, "lm_q1q2_score": 0.7803634944656613}}
{"text": "(* This file should be tested by loaded from `field_examples_check.v` and     *)\n(* `field_examples_no_check.v`. To edit this file, uncomment `Require         *)\n(* Import`s below: *)\n(* From mathcomp Require Import all_ssreflect ssralg ssrnum ssrint rat. *)\n(* From mathcomp Require Import ring. *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory.\n\nLocal Open Scope ring_scope.\n\n(* Examples from the Coq Reference Manual, but for an instance of MathComp's\n   (abstract) field. *)\n\nGoal forall (F : fieldType) (x : F), x != 0 -> (1 - 1 / x) * x - x + 1 = 0.\nProof. by move=> F x x_neq0; field. Qed.\n\nGoal forall (F F' : fieldType) (f : {rmorphism F -> F'}) (x : F),\n    f x != 0 -> f ((1 - 1 / x) * x - x + 1) = 0.\nProof. by move=> F F' f x x_neq0; field. Qed.\n\nGoal forall (F : fieldType) (x y : F), y != 0 -> y = x -> x / y = 1.\nProof. by move=> F x y y_neq0 y_eq_x; field: y_eq_x. Qed.\n\nGoal forall (F : fieldType) (x y : F), y != 0 -> y = 1 -> x = 1 -> x / y = 1.\nProof. by move=> F x y y_neq0 y_eq1 xeq1; field: y_eq1 xeq1. Qed.\n\n(* Using the _%:R embedding from nat to F *)\n\nGoal forall (F : fieldType) (n : nat),\n    n%:R != 0 :> F -> (2 * n)%:R / n%:R = 2%:R :> F.\nProof. by move=> F n n_neq0; field. Qed.\n\n(* For a numFieldType, non-nullity conditions such as 2%:R != 0 should not be *)\n(* generated.                                                                 *)\nGoal forall (F : numFieldType) (x : F), (x / 2%:R) * 2%:R = x.\nProof. by move=> F x; field. Qed.\n\nGoal forall (F : numFieldType) (n : nat),\n  n != 1%N -> ((n ^ 2)%:R - 1) / (n%:R - 1) = (n%:R + 1) :> F.\nProof. by move=> F n n_neq0; field; rewrite subr_eq0 pnatr_eq1. Qed.\n\nGoal forall (F : numFieldType) (n : nat),\n  n != 1%N -> (2%:R - (2 * n)%:R) / (1 - n%:R) = 2%:R :> F.\nProof. by move=> F n n_neq0; field; rewrite subr_eq0 eq_sym pnatr_eq1. Qed.\n", "meta": {"author": "math-comp", "repo": "algebra-tactics", "sha": "edc8e5e59b49b02089fcb0bd5217e03100ea9e12", "save_path": "github-repos/coq/math-comp-algebra-tactics", "path": "github-repos/coq/math-comp-algebra-tactics/algebra-tactics-edc8e5e59b49b02089fcb0bd5217e03100ea9e12/examples/field_examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7803634907609769}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export ZArithRing.\n\n(** Example of use of the conversion rule \n*)\nTheorem conv_example : forall n:nat, 7*5 < n -> 6*6 <= n.\nProof.\n intros; assumption.\nQed.\n\nTheorem imp_trans : forall P Q R:Prop, (P->Q)->(Q->R)->P->R.\nProof.\n  intros P Q R H H0 p.\n  apply H0; apply H; assumption.\nQed.\n\n(** Tests :\n\nPrint imp_trans.\n\nCheck (imp_trans _ _ _ (le_S 0 1)(le_S 0 2)).\n\n*)\n\nDefinition neutral_left (A:Type)(op:A->A->A)(e:A) : Prop :=\n  forall x:A, op e x = x.\n\nLemma one_neutral_left : neutral_left Z Zmult 1%Z.\nProof.\n intro z; ring. \nQed.\n\nLemma le_i_SSi : forall i:nat, i <= S (S i).\nProof.\n intro i.\n do 2 apply le_S; apply le_n.\nQed.\n\nLemma all_imp_dist   : \n forall (A:Type)(P Q:A->Prop), \n         (forall x:A, P x -> Q x)->\n         (forall y:A, P y)-> \n          forall z:A, Q z.\nProof.\n intros A P Q H H0 z.\n apply H; apply H0; assumption.\nQed.\n\n\nLemma mult_le_compat_r : forall m n p:nat, le n p -> le (n * m) (p * m).\nProof.\n intros m n p H; rewrite (mult_comm n m); rewrite (mult_comm p m).\n apply mult_le_compat_l; trivial.\nQed.\n\n\nLemma le_mult_mult :\n   forall a b c d:nat, a <= c -> b <= d -> a * b <= c * d.\nProof.\n intros a b c d H H0.  \n apply le_trans with (m := c  *b).\n - apply mult_le_compat_r; assumption.\n - apply mult_le_compat_l; assumption.\nQed.\n\n\n(** using eapply ...\n*)\n\nLemma le_mult_mult' : \n forall a b c d:nat, a <= c -> b <= d -> a*b <= c*d.\nProof.\n intros a b c d H H0.  \n eapply le_trans.\n - eapply mult_le_compat_l.\n   eexact H0.\n -  now apply mult_le_compat_r.\nQed.   \n\nLemma le_O_mult : forall n p:nat, 0 * n <= 0 * p.\nProof.\n intros n p; apply le_n.\nQed.\n\nLemma lt_8_9 : 8 < 9.\nProof.\n unfold lt; apply le_n.\nQed.\n\n(** Tests :\n\nSearchPattern (_ + _ <= _)%Z.\n\nSearchPattern (?X1 * _ <= ?X1 * _)%Z. \n\n*)\n\nLemma lt_S : forall n p:nat, n < p -> n < S p.\nProof.\n intros n p H.\n unfold lt; apply le_S; trivial.\nQed.\n\nOpen Scope Z_scope.\n\nDefinition Zsquare_diff (x y:Z):= x * x - y * y.\n\nTheorem unfold_example :\n forall x y:Z,\n   x*x = y*y ->\n   Zsquare_diff x y * Zsquare_diff (x+y)(x*y) = 0.\nProof.\n intros x y Heq.\n unfold Zsquare_diff at 1.\n rewrite Heq; ring. \nQed.\n\nSection ex_falso_quodlibet.\n Hypothesis ff : False.\n \n Lemma ex1 : 220 = 284.\n Proof.\n   apply False_ind.\n   exact ff.\n Qed.\n\n Lemma ex2 : 220 = 284.\n Proof.\n  destruct ff.\n Qed.\n\nEnd ex_falso_quodlibet.\n\nTheorem absurd : forall P Q:Prop, P -> ~P -> Q.\nProof.\n intros P Q p H.\n elim H.\n assumption.\nQed.\n\nTheorem double_neg_i : forall P:Prop, P->~~P.\nProof.\n intros P p H.\n apply H; assumption.\nQed.\n\nTheorem modus_ponens :forall P Q:Prop, P->(P->Q)->Q.\nProof.\n auto.\nQed.\n\n\nTheorem double_neg_i' : forall P:Prop, P -> ~ ~ P.\nProof.\n intro P; exact (modus_ponens P False).\nQed.\n\nTheorem contrap :forall A B:Prop, (A->B) -> ~B -> ~A.\nProof.\n intros A B; unfold not.\n apply imp_trans.\nQed.  \n\nTheorem disj4_3' : forall P Q R S:Prop, R -> P \\/ Q \\/ R \\/ S.\nProof.\n  right; right; left; assumption.\nQed.\n\nLemma and_commutes : forall A B:Prop, A /\\ B -> B /\\ A.\nProof.\n intros A B H; destruct H.\n split; assumption.\nQed.\n\nLemma or_commutes : forall A B:Prop, A\\/B->B\\/A.\nProof.\n intros A B H; destruct H as [H | H]; auto.\nQed.\n\nLemma ex_imp_ex :\n forall (A:Type)(P Q:A->Prop), (ex P)->(forall x:A, P x -> Q x)->(ex Q).\nProof.\n intros A P Q H H0; destruct H as [a Ha].\n exists a; apply H0; assumption.\nQed.\n\n\nLemma L36 : 6 * 6 =9 * 4.\nProof. reflexivity. Qed.\n\nLemma diff_of_squares : forall a b:Z, ((a + b) * (a - b) = a * a - b * b)%Z.\nProof.\n intros; ring.\nQed.\n\nTheorem eq_sym' : forall (A:Type)(a b:A), a = b -> b = a.\nProof.\n intros A a b e; rewrite e; reflexivity.\nQed.\n\nLemma Zmult_distr_1 : forall n x:Z, n * x + x = ( n + 1) * x.\nProof.\n intros n x ; rewrite Zmult_plus_distr_l.\n now rewrite  Zmult_1_l.\nQed.\n\nLemma regroup : forall x:Z, x + x + x + x + x = 5 * x.\nProof.\n intro x; pattern x at 1.\n rewrite <- Zmult_1_l.\n repeat rewrite Zmult_distr_1.\n reflexivity.\nQed.\n\n\nOpen Scope nat_scope. \n\nTheorem le_lt_S_eq : forall n p:nat, n <= p -> p < S n -> n = p.\nProof.\n intros; omega.\nQed.\n\nLemma conditional_rewrite_example : forall n:nat,\n   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.\nProof.\n intros n  H H0.\n rewrite <- (le_lt_S_eq 2 n).\n - reflexivity.  \n -  apply  plus_le_reg_l with (p := 6). \n    rewrite plus_comm in H; auto with arith.\n - apply   plus_lt_reg_l with (p:= 3); auto with arith.\nQed.\n\n(** A shorter proof ...\n*)\n\nLemma conditional_rewrite_example' : forall n:nat,\n   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.\nProof.\n intros n  H H0.\n assert (n = 2) by omega.\n now subst n.\nQed.\n\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 H; rewrite H; auto. \nQed. \n\nDefinition my_True : Prop \n:= forall P:Prop, P -> P.\n\nDefinition my_False : Prop\n:= forall P:Prop, P.\n\nTheorem my_I : my_True.\nProof.\n intros P p; assumption.\nQed.\n\n\nTheorem my_False_ind : forall P:Prop, my_False->P.\nProof.\n intros P F; apply F.\nQed.\n\nDefinition my_not (P:Prop) : Prop := P->my_False.\n\nSection leibniz.\n\n Variable A : Type.\n \n Definition leibniz (a b:A) : Prop := \n forall P:A -> Prop, P a -> P b.\n\nRequire Import Relations.\n\nTheorem leibniz_sym : symmetric A leibniz.\nProof.\n intros x y H Q; apply H; trivial.\nQed.\n\nEnd leibniz.\n\nDefinition my_and (P Q:Prop) := \n  forall R:Prop, (P->Q->R)->R.\n\nDefinition my_or (P Q:Prop) := \n  forall R:Prop, (P->R)->(Q->R)->R.\n\nDefinition my_ex (A:Type)(P:A->Prop) :=\n  forall R:Prop, (forall x:A, P x -> R)->R.\n\nDefinition my_le (n p:nat) :=\n  forall P:nat -> Prop, P n ->(forall q:nat, P q -> P (S q))-> P p.\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/chap5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.9019206804839998, "lm_q1q2_score": 0.7803634901945955}}
{"text": "Require Import Coq.Unicode.Utf8_core.\n\nTheorem slb_plus_0_n: ∀ n : nat, 0 + n = n.\nProof.\n intros n.\n reflexivity.\nQed.\n\nTheorem slb_plus_1_l : ∀ n : nat, 1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\n(* _reflexivity_ is a proofing _tactic_ *)\n(*  reflexivity =>\n    This tactic applies to a goal that has the form t=u. It checks that t and u are convertible and then solves the goal. It is equivalent to apply refl_equal.*)", "meta": {"author": "ArtifactCabinet", "repo": "workbench-coq", "sha": "baee13a074cc1a42414f03ec81bee6f5ebd11ce0", "save_path": "github-repos/coq/ArtifactCabinet-workbench-coq", "path": "github-repos/coq/ArtifactCabinet-workbench-coq/workbench-coq-baee13a074cc1a42414f03ec81bee6f5ebd11ce0/p005_proof_simpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7802740062847567}}
{"text": "Require Export stlc.Maps.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nInductive type :=\n| tvar : string -> type\n| tarr : type -> type -> type.\n\nInductive term :=\n| var : string -> term\n| app : term -> term -> term\n| lam : string -> type -> term -> term .\n\n(* Exercise 2.1 *)\n\nDefinition X_Y_X (X:string) (Y:string) : type := \n  tarr (tvar X) (tarr (tvar Y) (tvar X)).\n\nDefinition XX_XX (X:string) : type := \n  tarr (tarr (tvar X) (tvar X)) (tarr (tvar X) (tvar X)).\n\n(* Exercise 2.2 *)\n\nDefinition lxly_x (X:string) (Y:string) : term :=\n  lam \"x\" (tvar X) (lam \"y\" (tvar Y) (var \"x\")).\n\nDefinition lflx_ffx (X:string) : term :=\n  lam \"f\" (tarr (tvar X) (tvar X)) \n      (lam  \"x\" (tvar X) \n            (app  (var \"f\") \n                  (app  (var \"f\") \n                        (var \"x\")))).\n\nDefinition ctx := partial_map type.\n\n(* Exercise 2.3 *)\n\nInductive typed : ctx -> term -> type -> Prop :=\n  | var_typed : forall E x A, \n    E x = Some A -> \n    typed E (var x) A\n\n  | app_typed : forall E M N A B,\n    typed E M (tarr A B) ->\n    typed E N A ->\n    typed E (app M N) B\n\n  | lam_typed : forall E x M A B,\n    typed (E & { x --> Some A}) M B ->\n    typed E (lam x A M) (tarr A B).\n\n(* Exercise 2.4 *)\n\nLemma test : typed  empty\n                    (lxly_x \"X\" \"Y\") \n                    (X_Y_X \"X\" \"Y\").\nProof.\nunfold lxly_x. unfold X_Y_X.\napply lam_typed. \napply lam_typed. \napply var_typed.\nreflexivity.\nQed.\n\nFixpoint beq_type (A:type) (B:type) :=\n  match A, B with\n  | tvar a, tvar b =>\n      beq_string a b\n  | tarr A1 A2, tarr B1 B2 =>\n      beq_type A1 B1 && beq_type A2 B2\n  | _,_ =>\n      false\nend.\n\nLemma beq_type_eq : forall A B,\nbeq_type A B = true -> A = B.\nProof.\nintros A.\ninduction A; intros B Hbeq; \ndestruct B; inversion Hbeq.\n- apply beq_string_true_iff in Hbeq. \n  rewrite Hbeq. reflexivity.\n- apply andb_prop in H0. \n  destruct H0 as [Hbeq1 Hbeq2].\n  apply IHA1 in Hbeq1.\n  apply IHA2 in Hbeq2.\n  rewrite Hbeq1. rewrite Hbeq2.\n  reflexivity.\nQed.\n\nLemma beq_type_refl : forall (A: type),\nbeq_type A A = true.\nProof.\ninduction A.\n+ simpl. rewrite <- beq_string_refl. reflexivity.\n+ simpl. rewrite IHA1. rewrite IHA2. reflexivity.\nQed.\n\nFixpoint beq_term (M: term) (N: term) :=\n  match M, N with\n  | var m, var n => \n      beq_string m n\n  | app M1 M2, app N1 N2 => \n      beq_term M1 N1 && beq_term M2 N2\n  | lam x A m, lam y B n => \n      beq_string x y && beq_type A B && beq_term m n\n  | _,_ => false\n  end.\n\n(* Exercise 2.5 *)\n\nFixpoint typecheck (E : ctx) (t : term) : option type :=\n  match t with\n  | var x => E x\n  | app M N => \n    match (typecheck E M), (typecheck E N) with\n    | Some (tarr A B), Some C => \n        if beq_type A C then Some B \n                        else None\n    | _,_ => None\n    end\n  | lam x A M => \n    match (typecheck (E&{x-->Some A}) M) with\n    | Some B => Some (tarr A B)\n    | _      => None\n    end\n  end.\n\n(* Exercise 2.6 *)\n\n(* \nThe typing judgement [typed] will tell us for a given\ncontext, term and type whether the term is of that type.\nThe type checker [typecheck] will tell us for a given\ncontext and term what the type is (or it will return\nnothing if there is no type).\n *)\n\n(* Exercise 2.7 *)\n\nExample pos_typecheck_1 : \ntypecheck empty (lxly_x \"X\" \"Y\") = Some (X_Y_X \"X\" \"Y\").\nProof. reflexivity. Qed.\n\nExample pos_typecheck_2 : \ntypecheck empty (lflx_ffx \"X\") = Some (XX_XX \"X\").\nProof. reflexivity. Qed.\n\nDefinition lx_xx (X: string) := \n  lam \"x\" (tvar X) (app (var \"x\") (var \"x\")).\n\nExample neg_typecheck_1 : \ntypecheck empty (lx_xx \"X\") = None.\nProof. reflexivity. Qed.\n\nDefinition lflx_xf (X: string) :=\n  lam \"f\" (tarr (tvar X) (tvar X)) \n      (lam \"x\" (tvar X) \n           (app (var \"x\") (var \"f\")) ).\n\nExample neg_typecheck_2 :\ntypecheck empty (lflx_xf \"X\") = None.\nProof. reflexivity. Qed.\n\n(* Exercise 2.8 *)\n\nLemma typecheck_complete : forall E t A,\n  typed E t A ->\n  typecheck 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_type_refl.\n  reflexivity.\n- simpl.\n  rewrite IHtyped. reflexivity.\nQed.\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\nLemma typecheck_sound : forall E t A,\n  typecheck E t = Some A ->\n  typed E t A.\nProof.\nintros E t.\ninduction t; intros B Htc. inversion Htc.\n- apply var_typed. apply H0.\n- simpl typecheck in Htc. simpl (typecheck E t1) in Htc.\n\nunfold typecheck in Htc.\nremember (typecheck E t1) as TO1.\n  remember (typecheck E t2) as TO2.\n  destruct TO1 as [T1|].\n  + destruct T1 as [|TA TB].\n    *\n  +\n  destruct TO2 as [T2|]; try solve_by_invert.\n  destruct (beq_type T11 T2) eqn: Heqb;\n  try solve_by_invert.\n\n  apply beq_type_eq in Heqb.\n  apply app_typed; subst..\n-\n  \n\ndestruct (typecheck E t1) as [T1|].\n  destruct T1 as [|TA TB].\n  + apply (Some (tvar s) = Some (tvar s)) in IHt1.\n  + destruct (typecheck E t2) as [T2|].\n  destruct (beq_type TA T2) eqn: Heqa.\n  * apply beq_type_eq in Heqa.\n    rewrite <- Heqa in IHt2.\n    {destruct (beq_type TB B) eqn: Heqb.\n    - apply beq_type_eq in Heqb.\n      rewrite Heqb in IHt1.\n      apply app_typed with (A := TA).\n      apply IHt1. reflexivity.\n      apply IHt2. reflexivity.\n    - Search solve_by_invert.\nSearch \"iff\".\n    }\n    apply app_typed (A := TA) (B := TB).\n  *\n  assert (Some T1 = Some T1) as HtypT1.\n  reflexivity.\n  apply IHt1 in HtypT1.\n  destruct T1 as [|TA TB].\n  + admit.\n  + apply app_typed \n    with (E := E) (M := t1) (N := t2) \n    (A := TA) (B := B).\n    * \n  + inversion app.\n\nAdmitted.\n\n(*\nFixpoint typecheck (E : ctx) (t : term) : option type :=\n  match t with\n  | var x => E x\n  | app M N => \n    match (typecheck E M), (typecheck E N) with\n    | Some (tarr A B), Some C => \n        if beq_type A C then Some B \n                        else None\n    | _,_ => None\n    end\n  | lam x A M => \n    match (typecheck (E&{x-->Some A}) M) with\n    | Some B => Some (tarr A B)\n    | _      => None\n    end\n  end.\n\nInductive typed : ctx -> term -> type -> Prop :=\n  | var_typed : forall E x A, \n    E x = Some A -> \n    typed E (var x) A\n  | app_typed : forall E M N A B,\n    typed E M (tarr A B) ->\n    typed E N A ->\n    typed E (app M N) B\n  | lam_typed : forall E x M A B,\n    typed (E & { x --> Some A}) M B ->\n    typed E (lam x A M) (tarr A B).\n\nInductive type :=\n| tvar : string -> type\n| tarr : type -> type -> type.\n\nInductive term :=\n| var : string -> term\n| app : term -> term -> term\n| lam : string -> type -> term -> term .\n\n  \n    inversion IHt1. with (A := T1).\n try solve by inversion;\n    destruct T1 as [|T11 T12]; try solve by inversion.\n\napply app_typed.\neval typecheck in Htc.\napply app_typed with (A := typecheck E t1).\n- eval typecheck in IHt1.\n\napply app_typed with (A := . destruct typed. destruct typecheck in IHt1.\n  \n- remember (typecheck E t1) as TO1.\n  remember (typecheck E t2) as TO2.\n  destruct TO1 as [T1|]; try solve by inversion;\n  destruct T1 as [|T11 T12]; try solve by inversion.\n destruct typecheck in IHt1. inversion IHt1.\n+ inversion IHt1.\n\n-\n    \n\n\n\n-d apply H in IHt1.\n\n induction typecheck.\n destruct app in H. simpl H. rewrite H in IHt1.\n- apply H in IHt1. simpl typecheck in H.\n- apply app_typed.\nast\nLemma typecheck_sound : forall E t A,\n  typecheck E t = Some A ->\n  typed E t A.\nProof with eauto.\nintros E t.\ninduction t; intros B Htc. inversion Htc.\n- apply var_typed. apply H0.\n- remember (typecheck E t1) as TO1.\n  remember (typecheck E t2) as TO2.\n  destruct TO1 as [T1|].\n  assert (Some T1 = Some T1) as HtypT1.\n  reflexivity.\n  apply IHt1 in HtypT1.\n  destruct T1 as [|TA TB].\n  + admit.\n  + apply app_typed \n    with (E := E) (M := t1) (N := t2) \n    (A := TA) (B := B).\n    * \n  + inversion app.\n\nAdmitted.\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/SimplyTypedLambdaCalculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7802739915505598}}
{"text": "Inductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint len (l : lst) : nat :=\n  match l with\n  | Nil => 0\n  | Cons x y => 1 + len y\n  end.\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 rev (l : lst) : lst :=\n  match l with\n  | Nil => Nil\n  | Cons x y => append (rev y) (Cons x Nil)\n  end.\n\nLemma len_append : forall x y : lst, len (append x y) = len x + len y.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem len_rev : forall x : lst, len (rev x) = len x.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl.\n    rewrite len_append.\n    rewrite IHx.\n    simpl.\n    rewrite <- plus_n_Sm.\n    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/list_rev_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.780200037113954}}
{"text": "Require Import Arith.\nImport Nat.\n\n\nLoad hoare.\n\n\n  (* From \"Formal Reasoning About Programs\"\n\n     factorial(n) {\n        a = 1;\n        while (n > 0) {\n           a = a * n;\n           n = n - 1;\n        }\n        return a; \n     }\n  *)\n\n  Definition gt01 n m := if gt_dec n m then 1 else 0.\n\n  Notation \"[ e1 `*` e2 ]\" := (expr_op e1 mul e2).\n  Notation \"[ e1 `-` e2 ]\" := (expr_op e1 sub e2).\n  Notation \"[ e1 `>` e2 ]\" := (expr_op e1 gt01 e2).\n\n  Definition factorial_cmd :=\n    seq (assign a (expr_num 1))\n        (while [expr_var n `>` expr_num 0]\n               (seq (assign a [expr_var a `*` expr_var n])\n                    (assign n [expr_var n `-` expr_num 1]))).\n\n\n\n  Module MainProof.\n\n    Definition c := seq (assign a  [expr_var a `*` expr_var n])\n                        (assign n [expr_var n `-` expr_num 1]).\n    \n    Definition linv n0 s := s a * fact (s n) = fact n0.\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\n    Lemma factorial_inv n0 : hoare (fun s => linv n0 s /\\ s n > 0)\n                                   c\n                                   (linv n0).\n\n\n\n\n\n\n\n\n\n\n      \n    Lemma factorial_correct n0 : hoare (fun s => s n = n0)\n                                       factorial_cmd\n                                       (fun s => s a = fact n0).\n\n\n\n\n\n\n\n\n\n        \n  End MainProof.\n\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/demo-hoare-factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7799834302998675}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nArguments nil {X}.\nArguments cons {X}.\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 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\nTheorem app_nil_r : forall (X:Type), forall l:list X, l ++ [] = l.\nProof.\n  intros x l.\n  induction l.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite IHl. reflexivity.\nQed.\n\nSearch (_ = _ + 0).\n\nLemma app_length : forall (X:Type) (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros x l1 l2.\n  induction l1.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite <- IHl1. 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/3_poly_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.779983057521869}}
{"text": "(*|\n############################################\nCoq: Associativity of relational composition\n############################################\n\n:Link: https://stackoverflow.com/q/70377028\n|*)\n\n(*|\nQuestion\n********\n\nI am working on verifying a system based on relation algebra. I found\nD. Pous's relation algebra library popular among the Coq society.\n\nhttps://github.com/damien-pous/relation-algebra\n\nOn this page, binary relation ``hrel`` is defined together with its\nrelational composition ``hrel_dot``.\n\nhttp://perso.ens-lyon.fr/damien.pous/ra/html/RelationAlgebra.rel.html\n\nIn this library, a binary relation is defined as\n|*)\n\nUniverse U.\nDefinition hrel (n m : Type@{U}) := n -> m -> Prop.\n\n(*|\nAnd the relational composition of two binary relations is defined as\n|*)\n\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(*| I believe that the relational composition is associative, i.e. |*)\n\nLemma dot_assoc :\n  forall m n p q (x : hrel m n) (y : hrel n p) (z : hrel p q),\n    hrel_dot m p q (hrel_dot m n p x y) z = hrel_dot m n q x (hrel_dot n p q y z).\n\n(*|\nI got to the place where I think the LHS and RHS of the expressions\nare equivalent, but I have no clues about the next steps.\n|*)\n\n  intros. (* .none *) unfold hrel_dot. (* .none *)\n  Show. (* .unfold .messages *)\n\n(*|\nI don't know how to reason about the nested ``exists2``, although the\nresults seem straightforward by exchanging the variables ``k`` and\n``k0``.\n\n----\n\n**A (Ana Borges):** I'm not sure you can prove the *equality* of those\ntwo expressions, at least not without proof irrelevance. If you\nrewrite your goal as a logical equivalence things should be easier.\n|*)\n\n(*|\nAnswer\n******\n\nAs Ana pointed out, it is not possible to prove this equality without\nassuming extra axioms. One possibility is to use functional and\npropositional extensionality:\n|*)\n\nReset Initial. (* .none *)\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\n\nUniverse U.\nDefinition hrel (n m : Type@{U}) := n -> m -> Prop.\n\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\nLemma dot_assoc :\n  forall m n p q (x : hrel m n) (y : hrel n p) (z : hrel p q),\n    hrel_dot m p q (hrel_dot m n p x y) z = hrel_dot m n q x (hrel_dot n p q y z).\nProof.\n  intros m n p q x y z.\n  apply functional_extensionality. intros a.\n  apply functional_extensionality. intros b.\n  apply propositional_extensionality.\n  unfold hrel_dot; split.\n  - intros [c [d ? ?] ?]. eauto.\n  - intros [c ? [d ? ?]]. eauto.\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/coq-associativity-of-relational-composition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7799417043078433}}
{"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 Definition next_weekday (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n(******************************* Booleans **************************************)\n\n(**These are defined in Coq.Init.Datatypes **)\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(* Negate a boolean by pattern matching on the data constructor *)\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n(* Given two bools, and a, and a b, compute their conjunction  *)\nDefinition andb (a:bool) (b:bool) : bool :=\n  match a with\n  | true => b\n  | false => false\n  end.\n\n(* Given two bools, compute thier disjunction *)\n(* in haskell this type is Bool -> Bool -> Bool *)\nDefinition orb (a:bool) (b:bool) : bool :=\n  match a with\n  | true => true\n  | false => b\n  end.\n\n(* Some tests *)\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(* Is notation a macro or a function? *)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\n(* test the new notation *)\n(* NOT LEGAL: Example test_&&: *)\nExample test_and: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* Some exercises *)\n\n(* Why doesn't this work? *)\n(* Notation \"¬ x\" := (negb x). *)\n\n(* Definition nandb (a:bool) (b:bool) : bool = ¬(a && b) *)\nDefinition nandb (a:bool) (b:bool) : bool := (negb (andb a b)).\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 2 *)\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\n(******************************* Function Types ********************************)\n(* Check is :t in ghci *)\nCheck negb.\n(* negb *)\n(*      : 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 => true\n  | primary p => false (*Notice that c is being unboxed to a primary p*)\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(*Why not this? *)\n(* Definition isred (c:color) : bool := *)\n(*   match c with *)\n(*   | primary red => true *)\n(*   | _ => false *)\n(*   end. *)\n\n(******************************* Numbers ***************************************)\n\nModule NatPlayground.\n\n(* Peano Axioms *)\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(* Remember these are just representations, the meaning is in the semantics *)\n(* deep embedding ayy-o *)\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 m => m\n  end.\n\nEnd NatPlayground.\n\nCheck (S (S (S (S O)))).\n(* 4 *)\n(*      : nat *)\n\nDefinition minustwo (n:nat) : nat :=\n  match n with\n  | O => O             (* zero minus two is zero in set nat *)\n  | S O => O           (* one minus two is zero in set nat*)\n  | S (S b) => b       (* any other number minus two is that number minus two *)\nend.\n\nCompute (minustwo 1729).\n\n(* Check out these types *)\nCheck S.             (* nat -> nat*)\nCheck pred.          (* nat -> nat*)\nCheck minustwo.      (* nat -> nat*)\n\n(* The data constructor S has the same type as these functions that operate on\nnat. But these are fundamentally different, the functions have computation rules\nattached to them. The constructor S is just a way to write down numbers, it is\ndata! *)\n\n(* We use fixpoint for recursive functions. We pattern match on numbers. If zero\nthen true, if one then false, if greater than one, then minus two and recur. If\nit is even you'll get to 0, if not you'll get to one. *)\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S b) => evenb b\n  end.\n\n(* oddb is just negation composed with evenb. Wouldn't this look nice with\nfunction composition and eta reduction *)\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\n(* addition, we check the first argument for zero, if it is zero we return the\nsecond arg. If not zero, then we take an S from the first argument and build a\nrecursive bunch of S's. so (plus 2 1) turns into (S (S (plus 0 1))) = 3 *)\nFixpoint plus (n:nat) (m:nat) : nat :=\n  match n with\n  | O => m\n  | S newN => S (plus newN m)\n  end.\n\n(* check the plus function *)\nCompute (plus 3 2).\n\n(* This is the simplification that happens for plus *)\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(* multiplication we just add the second parameter, the number of times of the\nfirst *)\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S newN => plus m (mult newN m)\n  end.\n\n(* The lack of a comma between (a b : nat) and the require comma in the match\npattern bothers me *)\nFixpoint minus (a b : nat) : nat :=\n  match a,b with\n  | O,_ => O\n  | S _, O => a\n  | S newA, S newB => minus newA newB\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(********************************* Exercises ***********************************)\n(* factorial function. I wonder if it has the same memory issues as haskell? It\nshouldn't*)\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S newN => mult n (factorial newN)\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.\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 leb (a b : nat) : bool :=\n  match a with\n  | O => true\n  | S newA => match b with\n             | O => false\n             | S newB => leb newA newB\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 2 less than *)\nDefinition blt_nat (a b : nat) : bool := negb (beq_nat a b) && leb a b.\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(****************************** Simplification *********************************)\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\n(* reflexivity can perform simple reduction, so simpl. is not actuall required*)\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 = O.\nProof.\n  intros n. reflexivity. Qed.\n\n(****************************** Rewriting **************************************)\nTheorem plus_id_example : forall n m :nat,\n    n = m -> n + n = m + m.\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(****************************** Exercises **************************************)\nTheorem plus_id_exercise : forall n m o : nat,\n    n = m -> m = o -> n + m = m + o.\nProof.\n  (* introduce all the varibles *)\n  intros n m o.\n  (* introduce all both hypotheses *)\n  intros H I.\n  (* rewrite the left side with hypothesis H *)\n  rewrite -> H.\n  (* rewrite the right side with hypothesis I *)\n  rewrite <- I.\n  (* Oh look both sides equate yay! *)\n  reflexivity. Qed.\n\n(* We can rewrite using these proven theorems *)\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.  (* Like this! *)\n  reflexivity. Qed.\n\nTheorem mult_S_1 : forall n m : nat,\n    m = S n -> m * (1 + n) = m * m.\nProof.\n  (* introduce our variables *)\n  intros n m.\n  (* introduce the hypothesis given by implication *)\n  intros H.\n  (* looks like we can rewrite the left side for equivalence *)\n  rewrite -> H.\n  (* and we can  *)\n  reflexivity. Qed.\n\n(****************************** Case **************************************)\n(* Theorem plus_1_neq_0_firsttry : forall n : nat, *)\n(*   beq_nat (n + 1) 0 = false. *)\n(* Proof. *)\n(*   intros n. *)\n(*   simpl. (* does nothing! *) *)\n(* Abort. *)\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\n Theorem 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 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'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(****************************** Exercises **************************************)\n(* There must be a cleaner way to write this than the direct case enum *)\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + intros H.\n      rewrite <- H.\n      simpl.\n      reflexivity.\n - destruct c.\n   + reflexivity.\n   + intros H.\n     rewrite <- H.\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  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(* Fixpoint plus' (n : nat) (m : nat) : nat := *)\n(*   match n, m with *)\n(*   | O, O => O *)\n(*   | S n' , O => S (plus' n' O) *)\n(*   | O, S m' => S (plus' O m') *)\n(*   | S n', S m' => S (plus' n' m') *)\n(*   end. *)\n\n\n(****************************** More Exercises *********************************)\nTheorem identity_fn_applied_twice :\n  forall (f : bool -> bool), (forall (x : bool), f x = x) -> forall (b : bool), f (f b) = b.\nProof.\n  intros f H b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice :\n  forall (f : bool -> bool), (forall (x : bool), f x = negb x) -> forall (b : bool), f (f b) = b.\nProof.\n  intros f H [].\n  - rewrite -> H.\n    rewrite -> H.\n    simpl. reflexivity.\n  - rewrite ->  H.\n    rewrite -> H.\n    simpl. reflexivity.\nQed.\n\nLemma  eq_commutative : forall (a b : bool), (a = b -> b = a).\n  Proof.\n    intros [] [].\n    - reflexivity.\n    - intros H. rewrite -> H. reflexivity.\n    - intros H. rewrite -> H. reflexivity.\n    - reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool), (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\n(* a *)\nInductive bin : Type :=\n| OO : bin\n| S' : bin -> bin\n| SS : bin -> bin.\n\n(* b *)\n\n(* Fixpoint mult (n m : nat) : nat := *)\n(*   match n with *)\n(*   | O => O *)\n(*   | S newN => plus m (mult newN m) *)\n(*   end. *)\nFixpoint incr (a : bin) : bin := S' a.\n\nFixpoint bin_to_nat (a : bin) : nat :=\n  match a with\n  | OO => O\n  | S' a' => S (bin_to_nat a')\n  | SS a' => 2 * (bin_to_nat a')\n  end.\n\n(* unary counting can still work *)\nExample test1: bin_to_nat (S' (S' (S' (S' OO)))) = 4.\nProof. simpl. reflexivity. Qed.\n\n(* or we can do 2^2 * 1 *)\nExample test2: bin_to_nat (SS (SS (S' OO))) = 4.\nProof. simpl. reflexivity. Qed.\n\n(* just checking that 2^10 = 1024 *)\nExample test3: bin_to_nat (SS (SS (SS (SS (SS (SS (SS (SS (SS (SS (S' OO))))))))))) = 1024.\nProof. simpl. 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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7798928003313456}}
{"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 nat.\n  author    : ZhengPu Shi\n  date      : 2021.05\n*)\n\nRequire Export Nat Arith Lia.\n\n\n(* ######################################################################### *)\n(** * More properties for nat *)\n\n(** a natural number must be odd or even *)\nLemma nat_split : forall (n : nat), exists (x : nat),\n  n = 2 * x \\/ n = 2 * x + 1.\nProof.\n  induction n.\n  - exists 0. auto.\n  - destruct IHn. destruct H.\n    + exists x. right. subst. lia.\n    + exists (x+1). left. subst. lia.\nQed.\n\n(** Two step induction principle for natural number *)\nTheorem nat_ind2 : forall (P : nat -> Prop),\n  (P 0) -> (P 1) -> (forall n, P n -> P (S (S n))) -> (forall n, P n).\nProof.\n  intros. destruct (nat_split n). destruct H2; subst; induction x; auto.\n  - replace (2 * S x) with (S (S (2 * x))); [apply H1; auto | lia].\n  - replace (2 * S x + 1) with (S (S (2 * x + 1))); [apply H1; auto | lia].\nQed.\n\n(** Connect induction principle between nat and list *)\nLemma ind_nat_list {A} : forall (P : list A -> Prop) ,\n  (forall n l, length l = n -> P l) -> (forall l, P l).\nProof.\n  intros. apply (H (length l)). auto.\nQed.\n\n\n\n(* ######################################################################### *)\n(** * Extension for nat from (Verified Quantum Computing). *)\n\n  (* https://www.cs.umd.edu/~rrand/vqc/index.html *)\n  \n  (*******************************)\n  (* Automation *)\n  (*******************************)\n\n  Lemma double_mult : forall (n : nat), (n + n = 2 * n).\n  Proof. intros. lia. Qed.\n  \n  \nRequire Export Arith Lia Lra.\nRequire Import Setoid. (* R ==> R', Morphisms.respectful R R' *)\n  Lemma pow_two_succ_l : forall x, 2^x * 2 = 2 ^ (x + 1).\n  Proof. intros. rewrite Nat.mul_comm. rewrite <- Nat.pow_succ_r'. intuition. Qed.\n  \n  Lemma pow_two_succ_r : forall x, 2 * 2^x = 2 ^ (x + 1).\n  Proof. intros. rewrite <- Nat.pow_succ_r'. intuition. Qed.\n  \n  Lemma double_pow : forall (n : nat), 2^n + 2^n = 2^(n+1). \n  Proof. intros. rewrite double_mult. rewrite pow_two_succ_r. reflexivity. Qed.\n  \n  Lemma pow_components : forall (a b m n : nat), a = b -> m = n -> a^m = b^n.\n  Proof. intuition. Qed.\n\n  Ltac unify_pows_two :=\n    repeat match goal with\n    (* NB: this first thing is potentially a bad idea, do not do with 2^1 *)\n    | [ |- context[ 4%nat ]]                  => replace 4%nat with (2^2)%nat \n                                                 by reflexivity\n    | [ |- context[ (0 + ?a)%nat]]            => rewrite Nat.add_0_l \n    | [ |- context[ (?a + 0)%nat]]            => rewrite Nat.add_0_r \n    | [ |- context[ (1 * ?a)%nat]]            => rewrite Nat.mul_1_l \n    | [ |- context[ (?a * 1)%nat]]            => rewrite Nat.mul_1_r \n    | [ |- context[ (2 * 2^?x)%nat]]          => rewrite <- Nat.pow_succ_r'\n    | [ |- context[ (2^?x * 2)%nat]]          => rewrite pow_two_succ_l\n    | [ |- context[ (2^?x + 2^?x)%nat]]       => rewrite double_pow \n    | [ |- context[ (2^?x * 2^?y)%nat]]       => rewrite <- Nat.pow_add_r \n    | [ |- context[ (?a + (?b + ?c))%nat ]]   => rewrite Nat.add_assoc \n    | [ |- (2^?x = 2^?y)%nat ]                => apply pow_components; try lia \n    end.\n\n  (** Restoring Matrix dimensions *)\n  Ltac is_nat_equality :=\n    match goal with \n    | |- ?A = ?B => match type of A with\n                  | nat => idtac\n                  end\n    end.\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/CoqExt/NatExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7798787539788046}}
{"text": "(* Definitions that are used by ott-generated output (when using non-expanded lists) *)\n\nRequire Import Bool.\nRequire Import List.\nSet Implicit Arguments.\n\n\n\nSection list_predicates.\nVariable (A : Set). (* should be Type in coq >= V8.1 *)\n\n(* Test whether a predicate [p] holds for every element of a list [l]. *)\nDefinition forall_list (p:A->bool) (l:list A) :=\n  fold_left (fun b (z:A) => b && p z) l true.\n\n(* Test whether a predicate [p] holds for some element of a list [l]. *)\nDefinition exists_list (p:A->bool) (l:list A) :=\n  fold_left (fun b (z:A) => b || p z) l false.\n\n(* Assert that a property holds for every element of a list *)\nInductive Forall_list (P:A->Prop) : list A -> Prop :=\n  | Forall_nil : Forall_list P nil\n  | Forall_cons :\n    forall x l, P x -> Forall_list P l -> Forall_list P (x::l).\n(* Assert that a property holds for some element of a list *)\nInductive Exists_list (P:A->Prop) : list A -> Prop :=\n  | Exists_head : forall x l, P x -> Exists_list P (x::l)\n  | Exists_tail : forall x l, Exists_list P l -> Exists_list P (x::l).\n\nEnd list_predicates.\nHint Constructors Forall_list Exists_list.\n\n\n\nSection list_mem.\n(* Functions about membership in a list, with equality between a list\n   element and a potential member being decided by [eq_dec]. *)\nVariable (A : Set). (* should be Type in coq >= V8.1 *)\nVariable (eq_dec : forall (a b:A), {a=b} + {a<>b}).\n\n(* Test whether [x] appears in [l]. *)\nFixpoint list_mem (x:A) (l:list A) {struct l} : bool :=\n  match l with\n  | nil => false\n  | cons h t => if eq_dec h x then true else list_mem x t\nend.\n\n(* Remove any element of [l1] that is present in [l2]. *)\nFixpoint list_minus (l1 l2:list A) {struct l1} : list A :=\n  match l1 with\n  | nil => nil\n  | cons h t =>\n    if (list_mem h l2) then list_minus t l2 else cons h (list_minus t l2)\nend.\nEnd list_mem.\n\n\n\nSection Flat_map_definition.\nVariables (A B : Set). (* should be Type in coq >= V8.1 *)\nVariable (f : A -> list B).\n(* This definition is almost the same as the one in the standard library of\n   Coq V8.0 or V8.1. The difference is that this version has the shape\n    fun A B f => (fix flat_map l := _)\n   while the standard library has\n    fun A B => (fix flat_map f l := _)\n   Our version has the advantage of making recursive definitions such as\n    fix foo x := match x with ... | List xs => flat_map foo xs end\n   well-founded.\n *)\nFixpoint flat_map (l:list A) {struct l} : list B :=\n  match l with\n    | nil => nil\n    | cons x t => (f x) ++ (flat_map t)\n  end.\nEnd Flat_map_definition.\n\n\n\n(* Provide helper lemmas for {{coq-equality}} homs. *)\nRequire Export ott_list_eq_dec.\n", "meta": {"author": "vellvm", "repo": "vellvm-legacy", "sha": "e4c22d795974ba7c768c18b74fa098b0be2f86f7", "save_path": "github-repos/coq/vellvm-vellvm-legacy", "path": "github-repos/coq/vellvm-vellvm-legacy/vellvm-legacy-e4c22d795974ba7c768c18b74fa098b0be2f86f7/src/Vellvm/ott/ott_list_core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.8774767922879692, "lm_q1q2_score": 0.7798652229878222}}
{"text": "(** Comments in Coq are as in Ocaml and SML:  they start with a left-paren \n   and asterisk, and are closed with an asterisk and right-paren. *)\n\nRequire Import Arith.\n\n(** [Require Import Arith.] is a top-level command that tells Coq to import\n   the definitions from the [Arith] library (arithmetic) and to make the\n   definitions available at the top-level.  All top-level commands end\n   with a period.\n*)\n\n\nDefinition four : nat := 4.\n\n(** A top-level definition begins with the keyword [Definition], followed\n   by an identifier (in this case [four]) that we want to use, a colon,\n   a type, [:=], and then an expression followed by a period.  \n   Here the type of the number [4] is [nat] which stands for natural number.  *)\n\nDefinition four' := 2 + 2.\n(** You can leave off the type information and Coq can often infer it.  \n   But it can't always infer types, and it's good documentation to put\n   the types on complicated definitions. *)\n\nEval compute in four'.\n\nEval compute in four + four'.\n(** [Eval compute in <exp>.] lets you evaluate an expression to see the \n   resulting value and type. *)\n\nCheck four'.\n(** [Check <exp>] lets you check the type of an expression. *)\n\nPrint four'.\n(** [Print <identifier>] lets you see the definition of the identifier. *)\n\nDefinition four'' := (6 - 4) * 2.\n\nCheck four''.\nEval compute in four''.\nPrint four''.\n\nDefinition inc (x:nat) : nat := x + 1.\n(** To define a function, we just make a parameterized definition.*)\n\nCheck inc.\nEval compute in inc.\nEval compute in inc four.\n\nDefinition inc' x := x + 1.\n(** As in Ocaml, we can leave off the types and Coq can usually infer them,\n   but not always. *)\n\nCheck inc'.\nPrint inc'.\nEval compute in inc' four.\n\nDefinition inc'' := fun (x:nat) => x + 1.\n(** Parameterized definitions are just short-hand for a regular definition\n   using a lambda expression. *)\n\nCheck inc''.\nEval compute in inc'' four.\n\n\nDefinition add1 x y := x + y.\nDefinition add2 (x:nat) (y:nat) := x + y.\nDefinition add3 (x y:nat) := x + y.\n(** When the types are the same, we can group parameters as in [add']. *)\nDefinition add4 := fun x => fun y => x + y.\n(** Multiple parameters are just iterated lambdas. *)\n\nCheck add1.\nCheck add2.\nCheck add3.\nCheck add4.\nEval compute in add1 5 4.\nEval compute in add2 5 4.\n\nDefinition inc''' := add1 1.\nEval compute in inc'''.\nEval compute in inc''' 4.\n\nInductive bool : Type := \n| true \n| false.\n(** An inductive definition is just like an Ocaml datatype definition,\n   though the syntax is a little different.  Here, we are defining\n   a new [Type] called [bool] with constructors [true] and [false].\n   Unlike Ocaml, we can (and generally need to) provide the type of \n   each data constructor, hence both [true] and [false] are defined\n   as constructors that immediately return a [bool].  \n\n   Notice that when we evaluate this definition, Coq says that not\n   only is [bool] defined, but also [bool_rect], [bool_ind], and \n   [bool_rec].  We'll discuss those later on when we start talking\n   about proving things.\n*)\nCheck true.\nCheck false.\nPrint bool.\n\nDefinition negb (b:bool) : bool := \n  match b with \n    | true => false\n    | false => true \n  end.\n(** The definition above shows how we use pattern-matching to tear apart\n   an inductive type, in this case a [bool].  The syntax is similar to \n   Ocaml except that we use \"=>\" for the guard instead of \"->\" and we\n   have to put an \"end\" to terminate the \"match\". *)\n\nCheck negb.\nEval compute in negb true.\nEval compute in negb false.\n\nDefinition andb (b1 b2:bool) : bool := \n  match b1 with \n    | true => b2\n    | false => false\n  end.\n\nEval compute in andb true false.\nEval compute in andb true true.\n\nDefinition orb b1 b2 := \n  match b1 with\n    | true => true\n    | _ => b2\n  end.\n\nEval compute in orb true false.\nEval compute in orb true true.\n\n(** The [Arith] module defines this [nat] type already.  It is a way to\n   represent the natural numbers, with a base case of zero, \"0\" and \n   successor constructor [S]. Notice that the type of [S] declares\n   it to take a [nat] as an argument, before returning a [nat]. \n\nInductive nat : Type := \n  | O : nat\n  | S : nat -> nat.\n\ntype nat = O | S of nat\n*)\n\nPrint nat.\n\n(** \n   A digression:\n\n   In informal math, we tend to think of a \"type\" as a set of\n   objects.  For instance, we think of [nat] as the set of\n   objects {0,1,2,3,...}.  But we can also form sets out of\n   sets.  For instance, we can have {nat,bool,string}.  Technically,\n   to avoid circularities, [nat] is considered a \"small\" set,\n   and {nat,bool,string} is considered a \"large\" set, sometimes\n   called a class.  Stratifying our sets is necessary to avoid\n   constructions such as S = { s : set | s is not contained in s }\n   (Russell's paradox.)  \n\n   In Coq, the identifier [Set] refers to a universe of \n   types, including {nat,bool,string,...}.  So in some sense, \n   the identifier [Set] names a class of types.  We sometimes\n   say that [Set] is the type of the collection \n   {nat,bool,string,...}. When we build \n   certain kinds of new types out of elements of [Set], then we \n   have to move up to a new universe.  Internally, that universe\n   is called Type_1.  (Actually, [Set] is represented as Type_0\n   internally.)  And if we build certain types out of Type_1,\n   we have to move up to Type_2.  So Coq has an infinite hierarchy\n   Set a.k.a. Type_0, Type_1, Type_2, ...   \n\n   Now figuring out where in this hierarchy a definition should go\n   isn't that hard, and in fact, Coq automagically infers this\n   for you.  When you write [Type], you are really writing [Type_x]\n   and Coq is later solving for [x] to make sure your definitions\n   don't contain a circularity.  In fact, with the exception of\n   [Set] and one more very special universe, [Prop], you can't\n   even explicitly say at what level you want a given definition.\n   \n   For now, we can just ignore this and use [Type] everywhere.\n*)\nCheck O.\nCheck 0.   (** the numeral 0 is just notation for the constructor O *)\nEval compute in 0.\nEval compute in 3.\nCheck S.\nCheck S 0. (** 1,2,3 are short-hand for (S O), (S (S O)) and (S (S (S O))). *)\nCheck S (S (S 0)).\n\nDefinition is_zero (n:nat) : bool := \n  match n with \n    | 0 => true\n    | S _ => false\n  end.\n\nFixpoint add'' (n m:nat) : nat := \n  match m with \n    | 0 => n\n    | S m' => S (add'' n m')\n  end.\n(** We construct recursive functions by using the keyword \"Fixpoint\". *)\n\nEval compute in add'' 4 3.\nPrint add''.\n\nDefinition add5 :=\n  fix local_add (n m:nat) : nat := \n  match n with \n    | 0 => m\n    | S n' => S (local_add n' m)\n  end.\n(** Alternatively, we can use a \"fix\" expression which builds a recursive\n   functions, similar to the way \"fun\" builds a non-recursive function.\n*)\n\nEval compute in add5 4 3.\nPrint add5.\n\n(** Pairs *)\nDefinition p1 : nat * nat := (3,4).  (** pair of nats *)\nDefinition p2 : nat * bool := (3, true).  (** nat and bool *)\nDefinition p3 : nat * bool * nat := (3,true,2).\n\nEval compute in add3 (fst p1) (snd p1).  \n(** [fst] extracts the first component of a pair, and [snd]\n   extracts the second component. *)\n\nEval compute in fst p3.\nEval compute in snd p3.\n\nPrint pair.\nEval compute in match p1 with \n                  | pair x y => x + y\n                end.\nLocate \"_ * _\".\n\n(** Notice that [(3,true,2)] is really short-hand for [((3,true),2)]. \n   and [nat * bool * nat] is short for [(nat * bool) * nat]. *)\n\n(** Options *)\nDefinition opt1 : option nat := None.\nDefinition opt2 : option nat := Some 4.\n(** An [option t] is either [None] or [Some] applied to a value of type [t]. \n   Notice that unlike Ocaml, we write [option nat] instead of [nat option].\n*)\nPrint option.\n\nFixpoint subtract (m n:nat) : option nat := \n  match m, n with \n    | _, 0 => Some m\n    | 0, S _ => None\n    | S m', S n' => subtract m' n'\n  end.\nEval compute in subtract 5 2.\nEval compute in subtract 2 5.\n\nDefinition subt (m n:nat) : nat := \n  match subtract m n with \n    | None => 0\n    | Some i => i\n  end.\nEval compute in subt 5 2.\nEval compute in subt 2 5.\n\n(** Sums *)\nLocate \"_ + _\".\nPrint sum.\n\nDefinition s1 : nat + bool := inl 3.\nDefinition s2 : nat + bool := inr true.\n\nPrint s1.\n\n(** We build something of type [t1 + t2] by using either [inl] or \n   [inr].  It's important to provide Coq enough type information\n   that it can figure out what the other type is. *)\n\nDefinition add_nat_or_bool (s1 s2: nat + bool) : nat + bool := \n  match s1, s2 with \n    | inl n1, inl n2 => inl (n1 + n2)\n    | inr b1, inr b2 => inr (orb b1 b2)\n    | _, _ => inr false\n  end.\n\n(** Lists *)\nRequire Import List.\nPrint list.\nDefinition l1 : list nat := nil.\nDefinition l2 : list nat := 3::2::1::nil.\nDefinition l3 : list bool := true::false::nil.\nDefinition l4 : list (nat + bool) := (inl 3)::(inr true)::nil.\n\nFixpoint append (l1 l2:list nat) : list nat := \n  match l1 with \n    | nil => l2\n    | h::t => h::(append t l2)\n  end.\n\nEval compute in append l2 l2.\n\nFixpoint add_list (l1 l2:list nat) : option (list nat) := \n  match l1, l2 with \n    | nil, nil => Some nil\n    | n1::l1, n2::l2 => \n      match add_list l1 l2 with\n        | None => None\n        | Some l => Some ((n1+n2)::l)\n      end\n    | _, _ => None\n  end.\n\nEval compute in add_list l2 l2.\nEval compute in add_list l2 (1::nil).\n(** Polymorphism *)\n\nFixpoint generic_append (A:Type) (l1 l2: list A) : list A := \n  match l1 with \n    | nil => l2\n    | h::t => h::(generic_append A t l2)\n  end.\n(** Unlike Ocaml, we make type parameters explicit in Coq.  Here, \n   we've defined a generic append function, which abstracts over\n   a type [A].  Notice that the types of the arguments [l1] and\n   [l2] depend upon [A], as does the result type.  Notice also\n  that when we call this function, we must provide an actual\n  type for the instantiation of [A].\n*)\n\nEval compute in generic_append bool l3 l3.\nEval compute in generic_append nat l1 l2.\nEval compute in generic_append _ l3 l3.\nEval compute in generic_append _ nil nil.\n(** Coq can usually figure out what the types are, and we can\n   leave out the type by just putting an underscore there \n   instead.  But there are cases where it can't figure it\n   out (e.g., generic_append _ nil nil).\n*)\n\nFixpoint generic_append' {A:Type} (l1 l2:list A) : list A := \n  match l1 with \n    | nil => l2\n    | h::t => h::(generic_append' t l2)\n  end.\n(** The curly braces tell Coq to make an argument implicit.  That\n   means it's up to Coq to fill in the argument for you.  Notice\n   that in the recursive call, we didn't have to specify the type. *)\n\nEval compute in generic_append' l1 l1.\nEval compute in generic_append' l2 l2.\nEval compute in generic_append' nil nil.\nEval compute in generic_append _ nil nil.\n\n(** This won't work though:\nDefinition foo := generic_append' nil nil.\n   We can fix it by either giving enough information in the context\n   or by using \"@\" to override the implicit arguments:\n*)\nDefinition foo : list nat := generic_append' nil nil.\nDefinition foo1 := @generic_append' nat nil nil.\n\n\n(** Assignment *)\n(** Problem0 *)\nFixpoint length {A:Type} (l:list A): nat :=\n  match l with \n    | nil => 0\n    | h::t => 1+ (length t)\n  end.\n\nEval compute in length (3::2::1::nil).\nEval compute in length (generic_append' l2 l2).\n\n(** Problem1  Write a function rev that reverses a list.\n rev : forall {A:Type}, list A -> list A *)\n\nFixpoint rev {A:Type} (l : list A) : list A :=\n  match l with \n    | nil => nil\n    | h ::t => generic_append' (rev t) (h::nil)\n   end.\n\nSearchAbout (list _ ->list _ ->list _).\nLocate app.\n\nEval compute in rev l2.\nEval compute in rev (generic_append' l2 l2).\nEval compute in rev (5::4::3::2::1::nil).\n\n(** Problem 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, ith 2 (1::2::3::4::nil)\n should return Some 3, whereas ith 4 (1::2::3::4::nil) \n should return None.*)\n\nFixpoint ith {A:Type} (n:nat) (l:list A): option A :=\n  match l, n with \n    |nil, _ => None\n    |h ::t, 0 => Some h\n    |h::t, S n' => ith n' t\n  end.\n\nEval compute in ith 2 nil.\nEval compute in ith 4 (1::2::3::4::nil).\nEval compute in ith 0 (1::2::3::4::nil).\nEval compute in ith 2 (1::2::3::4::nil).\n\n(** Problem 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} (f1: A->B) (f2: B->C) : A-> C :=\n  fun (a: A) => f2 (f1 a).\n\nCheck comp.\n\nEval compute in comp length add5.\nEval compute in comp length add5 (3::2::1::nil).\nEval compute in comp length add5 (3::2::1::nil) 10.\n\n(** Problem4:  Write a function sum that adds up all of the nats \nin a list. sum : list nat -> nat  \n*)\n\nFixpoint sum (l:list nat): nat :=\n  match l with \n    | nil => 0\n    | h ::t => h + (sum t)\nend .\n\nEval compute in sum l1.\nEval compute in sum l2.\n\n(** Problem5: Write a function map that maps a function\n over the elements in a list, producing a new list.\n map : forall {A B:Type}, (A -> B) -> list A -> list B\n*)\n\nFixpoint map {A B:Type} (f : A-> B) (l:list A): list B :=\n  match l with \n    | nil => nil\n    | h::t => f (h) :: (map f t)\nend.\n\nEval compute in map is_zero (0::1::2::3::0::0::nil).\n\n(** Problem6: Write a generic \"fold-right\" for a list such that,\n for instance. 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*)\n\nFixpoint fold {A B:Type} (f: A -> B -> B) (b: B) (l : list A) : B :=\n  match l with \n    | nil => b \n    | h::t => fold f (f h b) t\n  end.\n\nEval compute in fold (fun x y => x + y) 0 (1::2::3::nil).\nEval compute in fold (fun x y => x + y) 10 (1::2::3::nil).\n\n(** Problem7:  Write a function add_pairs that takes a list of pairs of \n nats and returns the list of the corresponding sums.\n For instance, add_pairs ((1,2)::(3,4)::nil) should \n return 3::7::nil. add_pairs : list (nat * nat) -> list nat\n*)\n\nFixpoint add_pairs (l : list (nat * nat)): list nat :=\n  match l with \n    | nil => nil\n    | (a,b)::t => (a+b)::(add_pairs t)\n  end.\n\nEval compute in add_pairs ((1,2)::(3,4)::nil).\n\n(** Problem8: 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]. Implicit Arguments Node [A].\n*)\n\nInductive tree (A:Type) : Type := \n| Leaf : tree A\n| Node : tree A -> A -> tree A -> tree A.\n\nPrint tree.\n\n(** Write a function which flattens the tree into a list. \nFor instance, flatten on the tree:\n3 / \\ 1 7 / \\ / \\ o o o o\nshould yield 1::3::7::nil. flatten : forall {A:Type}, tree A -> list A\n*)\n\n(** Problem 10. \nInductive order : Type := \n| Less \n| Equal\n| Greater.\n\n10. Write a function which when given two numbers n and m, \nreturns Less if n < m, Equal if n = m, and otherwise returns Greater.\n nat_cmp : nat -> nat -> order\n\n*)\n\nInductive order : Type := \n| Less \n| Equal\n| Greater.\n\nFixpoint nat_cmp (n m: nat) : order :=\n  match n, m with \n    | 0, 0 => Equal\n    | 0, S m' => Less\n    | S n', 0 => Greater\n    | S n', S m' => nat_cmp n' m'\nend.\n\nEval compute in nat_cmp 0 0.\nEval compute in nat_cmp 4 0.\nEval compute in nat_cmp 5 9.\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/lecture1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.7798652117466394}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Strings.String.\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'*)\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  emulLC : nat -> e_exp -> e_exp |\n  emulRC : e_exp -> nat -> e_exp |\n  edivC : e_exp -> nat -> e_exp\n.\nPrint e_exp.\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 \"n '*l' e\" := (emulLC n e) (at level 21, right associativity).\nNotation \"e '*r' n\" := (emulRC e n) (at level 21, right associativity).\nLocate \"*\".\nCheck 4 *l (enumC 5 '+ enumC 6).\n\nNotation \"e1 '/ n\" := (edivC e1 n) (at level 21, right associativity).\nCheck (enumC 4)'/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 *l (5 '+ 2).\nCheck (5 '+ 4) *r 8.\nCheck x '- 3.\nCheck 5 '+ 4 *r 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 *)\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 : string -> nat) : 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  | emulLC n e' => n * (eval_e_exp e' st)\n  | emulRC e' n => (eval_e_exp e' st) * n\n  | edivC e' n => (eval_e_exp e' st) / n\n  end.\n\n\nFixpoint eval_P_exp (P : P_exp) (st : string -> nat) : 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\nDefinition idle : Evt := nil.\nCheck idle.\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 }\" := (evtC a1 :: .. :: an :: nil).\nNotation \"P ? a\" := (tstC P a) (at level 47).\nNotation \"P1 ; P2\" := (seqC P1 P2) (at level 48).\nNotation \"P1 'U' P2\" := (choC P1 P2) (at level 49).\nNotation \"P **\" := (loopC P) (at level 46).\n\nLocate \"**\".\nCheck x ':= 4 :: nil.\nCheck evtC (x ':= 4 :: nil).\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\n\n(* ================== CDL Formula ======================== *)\n(* Clock relation in formula *)\nInductive rel := \n  rRelC : CRel -> rel |\n  rConjC : list CRel -> rel\n.\nPrint rel.\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  EmulC : E_exp -> E_exp -> E_exp |\n  (* unecessary expression *)\n  EminusC : E_exp -> E_exp -> E_exp\n.\nPrint E_exp. \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\n\n\n\n\n(* ====================================================== Definition of Sequent =========================== *)\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\nDefinition Gamma := list CDL_exp.\nDefinition Delta := list CDL_exp.\n\nDefinition SequentL := Gamma -> CDL_exp -> Delta. \nDefinition SequentR := Gamma -> CDL_exp -> Delta.\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\n\n\n\n(* ===================================================== CDL Calculus ======================================*)\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-191216.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7797862425695098}}
{"text": "Require Import ZArith.\nRequire Import Omega.\nRequire Import List.\nRequire Import FunctionalExtensionality.\n\nImport ListNotations.\n\nRequire Import listutils.\nRequire Import rollingsum.\nRequire Import seqi.\n\nDefinition fv (l : list Z) (i : nat) : Z :=\n  Z.abs(sum (firstn i l) - sum (skipn i l)).\n\nOpen Scope Z_scope.\n\n\nDefinition fulcrumRS (input : list Z) : list Z :=\n  let sl := rollingSum input in\n  let sr := rev (rollingSum (rev input)) in\n  map (fun p => Z.abs (fst p - snd p)) (combine sl sr)\n.\n\nDefinition fulcrum (input : list Z) : option (nat * Z) :=\n  minIndex_b (fulcrumRS input).\n\nExample ex_fulcrumRS :\n  let input := [5;-2;8;10;2;5] in\n  fulcrumRS input = map (fun i => fv input i) (seqi (length input)).\nProof.\nintros.\nunfold fv.\nunfold fulcrumRS.\nsimpl.\nauto.\nQed.\n\nTheorem fulcrumRS_correct : forall input,\n  input <> nil ->\n  fulcrumRS input = map (fun i => fv input i) (seqi (length input)).\nProof.\nintros. unfold fv.\nunfold fulcrumRS.\nrepeat (rewrite rollingSum_summ).\nunfold seqi.\nrewrite rev_length.\nrewrite <- map_rev.\nrewrite rev_seq.\nrewrite map_map.\nrewrite combine_map.\nrewrite map_map.\napply map_eq.\nintros.\napply in_seq in H0.\nsimpl.\nreplace (length input + 1 - x - 1)%nat with (length input - x)%nat by omega.\ndestruct (Nat.eq_dec x 0).\n* subst. simpl.\n  rewrite Nat.sub_0_r.\n  rewrite <- rev_length.\n  rewrite firstn_all.\n  rewrite <- sum_rev.\n  auto.\n* assert(L: (length input > 0)%nat). { destruct input. contradiction. simpl. omega. }\n  rewrite firstn_skipn_rev with (x := (length input - x)%nat).\n  rewrite rev_involutive.\n  rewrite <- sum_rev.\n  rewrite rev_length.\n  replace (length input - (length input - x))%nat with x by omega.\n  auto.\n\n  rewrite rev_length. omega.\nQed.\n\nTheorem fulcrum_correct : forall l i v j,\n   (j < length l)%nat -> fulcrum l = Some (i, v) -> fv l j >= fv l i.\nProof.\nintros.\nunfold fulcrum in H0.\nrewrite fulcrumRS_correct in H0.\napply minIndex_b_map_seq in H0.\ndestruct H0.\napply H1.\nomega.\ndestruct l. inversion H.\nintro contra.\ninversion contra.\nQed.\n", "meta": {"author": "bartavelle", "repo": "fulcrum-coq", "sha": "3f7293d538ef58cff88ebdae5c6a759b77610a52", "save_path": "github-repos/coq/bartavelle-fulcrum-coq", "path": "github-repos/coq/bartavelle-fulcrum-coq/fulcrum-coq-3f7293d538ef58cff88ebdae5c6a759b77610a52/fulcrum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7797862321682674}}
{"text": "Definition 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\n\nLemma excluded_middle_peirce : excluded_middle->peirce.\nProof.\n unfold peirce; intros H P Q H0.\n case (H P).\n trivial.\n intro H1; apply H0; intro H2; absurd P; auto.\nQed.\n\nLemma peirce_classic : peirce->classic.\nProof.\n unfold classic; intros H P H0.\n apply (H P False).\n intro H1.\n case H0.\n assumption. \nQed.\n\nLemma classic_excluded_middle: classic->excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H.\n unfold not at 1; intro H0.\n absurd P.\n intro H1; apply H0; auto.\n apply H; intro H1; apply H0; auto.\nQed.\n\n\nLemma excluded_middle_implies_to_or :  excluded_middle -> implies_to_or.\nProof.\n unfold implies_to_or; intros H P Q H0.\n case (H P); intro H1.\n right; auto.\n left; trivial.\nQed.\n\nLemma implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n case (H P P); auto. \nQed.\n\nLemma classic_de_morgan_not_and_not : classic -> \n                                      de_morgan_not_and_not.\nProof.\n unfold de_morgan_not_and_not; intros H P Q H0.\n apply H.\n intro H1.\n apply H0.\n split;intro;apply H1; auto.\nQed.\n\nLemma de_morgan_not_and_not_excluded_middle : de_morgan_not_and_not ->\n                                              excluded_middle.\nProof.\n unfold excluded_middle; intros H P.\n apply H; intro H1; elim H1; auto.\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/everyday/SRC/class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7797152514466116}}
{"text": "Set Implicit Arguments.\nRequire Import Arith.\n\n\n\n  Definition divides a b := exists k, a * k = b.\n  Notation \"( a | b )\" := (divides a b).\n\n  Lemma divides_refl : forall n, (n | n).\n  Proof.\n    exists 1. firstorder.\n  Qed.\n\n  Section Gcd.\n\n    Definition state : Set := nat * nat.    (*  (a, b)  *)\n  \n    Inductive step : state -> state -> Prop :=\n      step_a : forall a b, a > b -> step (a, b) (a - b, b)\n    | step_b : forall a b, a < b -> step (a, b) (a, b - a).\n\n\n    Lemma div_inv a b a' b' : step (a, b) (a', b') ->\n                              forall z, (z | a) /\\ (z | b) <-> (z | a') /\\ (z | b').\n\n    \n    Definition is_gcd (a b z : nat) :=\n      (z | a) /\\ (z | b) /\\ forall z', (z' | a) -> (z' | b) -> (z' | z).  \n\n\n    Lemma gcd_inv a b a' b' : step (a, b) (a', b') ->\n                              forall z, is_gcd a b z <-> is_gcd a' b' z.\n\n\n\n\n\n\n  End Gcd.\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/gcd-transition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7797152447815089}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(* elim tactic *)\n\nGoal forall n : nat, n + n = 2 * n.\nShow Proof.\nelim.\nShow Proof.\ndone.\nmove=> n IH.\nring.\nQed.\n\nCheck Wf_nat.lt_wf_ind.\n\n(* SSReflect idiom for strong induction *)\n\nLemma mylt_wf_ind : forall (n : nat) (P : nat -> Prop),\n  (forall n0 : nat, (forall m : nat, (m < n0) -> P m) -> P n0) ->\n  P n.\nProof.\nmove=> n.\nmove: (leqnn n).\nmove: {-2}n.\nmove: n.\nelim.\n  case=> //.\n  move=> _ P.\n  apply.\n  done.\nmove=> n IH m mn P HP.\nmove: (HP).\napply => k km.\napply IH => //.\nrewrite -ltnS.\nby apply: leq_trans mn.\nQed.\n\n(* rewrite tactic *)\n\nGoal forall n : nat, n = 0 -> forall m : nat, m + n = m.\nmove=> n n0 m.\nrewrite n0.\nrewrite addn0.\ndone.\nQed.\n\nGoal forall n : nat, n = 0 -> forall m : nat, n + m = n.\nmove=> n n0 m.\nrewrite n0.\n(* rewrite both occurrences *) \nUndo.\nrewrite {1}n0.\n(* rewrite only the first occurrence *)\nUndo.\nrewrite {2}n0. \n(* rewrite only the second occurrence *)\nUndo.\nrewrite {-2}n0.\n(* rewrite all the occurrences except the second one *)\nUndo.\nAbort.                                      (* o.k. *)\n(* NB: this is the same occurrence switch <occ-switch> as we used in the proof of strong induction *)\n\n\n(* the following two example are taken from the ssreflect manual *)\n\nGoal forall x y : nat,\n  (forall t u, t + u = u + t) ->\n  x + y = y + x.\nmove=> x y H.\n(* rewrite H. changes the lhs, what if I want to change the rhs? *)\n(* <rstep> =def= [<r-prefix>]<r-item> \n   <r-prefix> =def= ... [ [<r-pattern>] ]\n   <r-pattern> =def= <term> | ...\n*)\nFail rewrite {2}H.\nrewrite H.                                  (* x + y が書き換えられる。 *)\nUndo.\nrewrite [y + _]H.                           (* y + x が書き換えられる。 *)\ndone.\nQed.\n\nGoal forall x y : nat,\n  (forall t u, t + u * 0 = t) ->\n  x + y * 4 + 2 * 0 = x + 2 * 0.\nProof.\nmove=> x y H.\nFail rewrite [x + _]H.\n(* rewrite does not try to recover from a pattern-match failure *)\nrewrite [x + 2 * _]H.\nAbort.                                      (* ok. *)\n\n(* contextual pattern *)\nGoal forall (a b c : nat),\n  (a + b) + (2 * (b + c)) = 0.\nmove=> a b c.\n(* commute b and c *)\nFail rewrite {2}addnC.\nrewrite [b + _]addnC.         (* b + c が対象 *)\nrewrite [in 2 * _]addnC.      (* 2 * (c + b) の中のどっかが対象 *)\nrewrite [in X in _ + X]addnC. (* (a + b) + 2 * (b + c) の中の 2 * (b + c) の中のどこがが対象 *)\nAbort.                        (* ok. *)\n\n(* the same as above but detailed, naming conventions to be explained later *)\nGoal forall n : nat, n + n = 2 * n.\nelim.\n  rewrite addn0.\n  rewrite muln0.\n  done.\nmove=> n IH.\nrewrite mulnS.\nrewrite -IH.\nrewrite -addSnnS.\nrewrite addnCA.\nrewrite -addn2.\nrewrite addnA.\ndone.\nQed.\n(* ringを使う。 *)\nGoal forall n : nat, n + n = 2 * n.\n  by elim=> [|n IH]; ring.\nQed.\n\n(* structured scripts *)\n\nLemma undup_filter {A : eqType} (P : pred A) (s : seq A) :\n  undup (filter P s) = filter P (undup s).\nProof.\nelim: s => // h t IH /=.\ncase: ifP => /= [Ph | Ph].\n- case: ifP => [Hh | Hh].\n  + have ->// : h \\in t.\n      move: Hh; by rewrite mem_filter => /andP [].\n  + have : h \\in t = false.\n      apply: contraFF Hh; by rewrite mem_filter Ph.\n    move=> -> /=; by rewrite Ph IH.\n- case: ifP => // ht.\n  by rewrite IH /= Ph.\nQed.\n\nFixpoint flat {A : eqType} (l : seq (seq A)) : seq A :=\n  if l is h :: t then h ++ flat t else [::].\n\n(* Structure the following script *)\nLemma exo10 {A : eqType} (s : seq (seq A)) a :\n  reflect (exists2 s', s' \\in s & a \\in s') (a \\in flat s).\nProof.\nAbort.\n\n(* equation generation *)\n\nGoal forall s1 s2 : seq nat, rev (s1 ++ s2) = rev s2 ++ rev s1.\nmove=> s1.\nmove H : (size s1) => n.\nmove: n s1 H.\nelim.\n  case => //.\n  rewrite /=.\n  move=> _ s2.\n  by rewrite cats0.\nmove=> n IH.\ncase=> // h t.\ncase=> tn.\nmove=> s2.\nrewrite /=.\nrewrite rev_cons.\nrewrite IH //.\nrewrite rcons_cat.\nby rewrite rev_cons.\nQed.\n\n(* from the ssreflect manual *)\n\nGoal forall a b : nat,\n  a <> b.\nmove=> a b.\ncase H : a => [|n].\nShow 2.\nAbort.                                      (* ok. *)\n\n(* congr tactic *)\n\nGoal forall a b c a' b' c', a + b + c = a' + b' + c'.\nmove=> a b c a' b' c'.\ncongr (_ + _ + _).\nAbort.                                      (* |- a = a', |- b = b',  |- c = c' *)\n\n(* Search command *)\n\nSearch (_ < _)%N.\nSearch (_ < _ = _)%N.\n\nSearch _ (_ <= _)%N.\nSearch _ (_ <= _)%N \"-\"%N.\nSearch _ (_ <= _)%N \"-\"%N addn.\nSearch _ (_ <= _)%N \"-\"%N addn \"add\".\nSearch _ (_ <= _)%N \"-\"%N addn \"add\" in ssrnat.\n\n(* commutativity of addition? *)\nSearch (_ + _ = _ + _)%N.\nSearch _ \"commutative\".\nSearch _ commutative.\nSearch _ addn \"C\" in ssrnat.\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/tactics_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8902942210281198, "lm_q1q2_score": 0.7797081032884722}}
{"text": "From MyCoq.Lib Require Export Nat.\n\n\nInductive list (X : Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\nArguments nil {X}.\nArguments cons {X} _ _.\n\n\nFixpoint repeat {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | O => nil\n  | S count' => cons x (repeat x count')\n  end.\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)\nend.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => O\n  | cons _ l' => S (length l')\n  end.\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\nTheorem app_nil_r: forall (X : Type), forall l : list X,\n  l ++ [] = l.\nProof.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl.\n    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  induction l as [| x l'].\n  - reflexivity.\n  - simpl.\n    intros m n.\n    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  induction l1 as [| n1 l1'].\n  - reflexivity.\n  - simpl.\n    intros l2.\n    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  induction l1 as [| n1 l1'].\n  - simpl.\n    intros l2.\n    rewrite app_nil_r.\n    reflexivity.\n  - simpl.\n    intros l2.\n    rewrite IHl1'.\n    rewrite app_assoc.\n    reflexivity.\nQed. \n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl.\n    rewrite rev_app_distr.\n    simpl.\n    rewrite IHl'.\n    reflexivity.\nQed.\n\n\nInductive prod (X Y : Type) : Type :=\n  | pair (x : X) (y : Y).\nArguments pair {X} {Y} _ _.\n\n\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\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\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\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n  match l with\n  | nil => (nil, nil)\n  | x :: y => match x with\n              | (m, n) => match split y with\n                              | (l1, l2) => (m :: l1, n :: l2)\n                              end\n              end\n  end.\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  | x :: y => if n =? O\n              then Some x\n              else nth_error y (pred n)\n  end.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | x :: y => Some x\n  end.\n\n\nFixpoint filter {X : Type} (test: X -> bool) (l : list X) : (list X) :=\n  match l with\n  | [] => []\n  | x :: y => if test x\n              then x :: filter test y\n              else filter test y\n  end.\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\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  induction l1 as [| n1 l1'].\n  - reflexivity.\n  - simpl.\n    intros l2.\n    rewrite -> IHl1'.\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  induction l as [| n l'].\n  - reflexivity.\n  - simpl.\n    rewrite map_app.\n    simpl.\n    rewrite <- IHl'.\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 :: y => (f x) ++ flat_map f y\n  end.\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\nFixpoint fold {X Y: Type} (f : X -> Y -> Y) (l : list X) (b : Y) : Y :=\n  match l with\n  (* 需要一个起始元素 *)\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l O.\n\nTheorem fold_length_correct: forall X (l : list X),\n  fold_length l = length l.\nProof.\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 x y => (f x) :: y) l [].\n\nTheorem fold_map_correct: forall (X Y : Type) (f : X -> Y) (l : list X),\n  fold_map f l = map f l.\nProof.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    (* reflexivity 化简力度比 simpl 更强 *)\n    reflexivity.\nQed.\n\n\nDefinition prod_curry {X Y Z : Type} (f : X * Y -> Z) (x : X) (y : Y) : Z :=\n  f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type} (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  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.\n  intros f.\n  intros [x y].\n  reflexivity.\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/Lib/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8902942246666266, "lm_q1q2_score": 0.779708089156919}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Strings.Ascii.\n\n(* Returns the comparison of two ASCII characters. *)\nDefinition compare_ascii (a b : ascii) : comparison  :=\n  N.compare (N_of_ascii a) (N_of_ascii b).\n\n(* Prove that the compare_ascii function implies the equality of two ASCII \n * characters. *)\nTheorem compare_ascii_implies_equality : forall (a b : ascii),\n  (compare_ascii a b) = Eq -> a = b.\nProof.\n  intros.\n  rewrite <- ascii_N_embedding with (a := a).\n  rewrite <- ascii_N_embedding with (a := b).\n  f_equal.\n  now apply N.compare_eq_iff.\nQed.\n\n(* Prove that comparing an ASCII character to itself gives Eq. *)\nLemma compare_ascii_reflexive : forall (a : ascii),\n  compare_ascii a a = Eq.\nProof.\n  intro x.\n  unfold compare_ascii.\n  now apply N.compare_eq_iff.\nQed.\n\n(** Prove that compare_ascii is symmetric when the result is Eq. *)\nLemma compare_ascii_eq_symmetric : forall (a b : ascii),\n    compare_ascii a b = Eq -> compare_ascii b a = Eq.\nProof.\n  intros.\n  rewrite compare_ascii_implies_equality with (a := a) (b := b).\n  + rewrite compare_ascii_reflexive.\n    reflexivity.\n  + rewrite H.\n    reflexivity.\nQed.\n\n(** Prove that compare_ascii is asymmetric when the result is not Eq. **)\nLemma compare_ascii_lt_gt_asymmetric : forall (a b : ascii),\n    (compare_ascii a b) = Lt <-> (compare_ascii b a) = Gt.\nProof.\n  split.\n  + unfold compare_ascii.\n    intros.\n    apply N.compare_gt_iff in H.\n    rewrite H.\n    reflexivity.\n  + unfold compare_ascii.\n    intros.\n    apply N.compare_gt_iff in H.\n    rewrite H.\n    reflexivity.\nQed.\n\n(** Prove that compare_ascii is transitive when the result is Eq. *)\nLemma compare_ascii_eq_transitive : forall (a b c : ascii),\n    compare_ascii a b = Eq /\\ compare_ascii b c = Eq -> compare_ascii a c = Eq.\nProof.\n  intros.\n  rewrite compare_ascii_implies_equality with (a := a) (b := b). (* Intuition? *)\n  + decompose [and] H.\n    rewrite H1.\n    reflexivity.\n  + decompose [and] H.\n    rewrite H0.\n    reflexivity.\nQed.\n\n(* Boolean equality for ASCII characters. *)\nDefinition beq_ascii (a b : ascii) : bool :=\n  match compare_ascii a b with\n    | Eq => true\n    | _ => false\n  end.\n\n(* Prove boolean equality for ASCII characters is reflexive. *)\nLemma beq_ascii_reflexive : forall (a : ascii),\n  beq_ascii a a = true.\nProof.\n  intros.\n  unfold beq_ascii.\n  rewrite -> compare_ascii_reflexive.\n  reflexivity.\nQed.\n\n(* Prove that beq_ascii is symmetric. *)\nTheorem beq_ascii_symmetric : forall (a b : ascii),\n    beq_ascii a b = beq_ascii b a.\nProof.\n  intros.\n  unfold beq_ascii.\n  case_eq (compare_ascii a b).\n  + intros.\n    apply compare_ascii_eq_symmetric in H.\n    rewrite H.\n    reflexivity.\n  + intros.\n    apply compare_ascii_lt_gt_asymmetric in H.\n    rewrite H.\n    reflexivity.\n  + intros.\n    apply compare_ascii_lt_gt_asymmetric in H.\n    rewrite H.\n    reflexivity.\nQed.\n\n(** Prove that (beq_ascii a b) is true if and only if a = b. *)\nLemma beq_ascii_iff_equality : forall (a b : ascii),\n    beq_ascii a b = true <-> a = b.\nProof.\n  split.\n  unfold beq_ascii.\n  case_eq (compare_ascii a b).\n  + intros.\n    apply compare_ascii_implies_equality with (a := a) (b := b) in H.\n    rewrite H.\n    reflexivity.\n  + intros.\n    contradict H0.\n    intuition.\n  + intros.\n    contradict H0.\n    intuition.\n  + intros.\n    rewrite H.\n    rewrite beq_ascii_reflexive.\n    reflexivity.\nQed.\n\n(** Prove that beq_ascii is transitive. *)\nTheorem beq_ascii_transitive : forall (a b c : ascii),\n    beq_ascii a b = true /\\ beq_ascii b c = true -> beq_ascii a c = true.\nProof.\n  intros.\n  rewrite beq_ascii_iff_equality in H.\n  rewrite beq_ascii_iff_equality in H.\n  elim H. (* Elim will split the conjunction in H then introduce the hypotheses to the goal. *)\n  intros.\n  (* decompose [and] H. *) (* This tactic can also be used to decompose the conjunction in H directly. *)\n  rewrite H0.\n  rewrite H1.\n  rewrite beq_ascii_reflexive.\n  reflexivity.\nQed.\n\n(* Boolean less than for ASCII characters. *)\nDefinition blt_ascii (a b : ascii) : bool :=\n  match compare_ascii a b with\n    | Lt => true\n    | _ => false\n  end.\n\n(** Prove that boolean less than for ASCII characters is antireflexive. *)\nTheorem blt_ascii_antireflexive : forall (a : ascii),\n  blt_ascii a a = false.\nProof.\n  intros.\n  unfold blt_ascii.\n  rewrite compare_ascii_reflexive.\n  reflexivity.\nQed.\n\n(** Prove that boolean less than for ASCII characters is asymmetric. *)\nTheorem blt_ascii_asymmetric : forall (a b : ascii),\n    blt_ascii a b = true -> blt_ascii b a = false.\nProof.\n  intros a b.\n  unfold blt_ascii.\n  case_eq (compare_ascii a b).\n  + intros.\n    contradict H0. (* Contradiction, if blt_ascii a b = true then compare_ascii a b <> Eq. *)\n    intuition.\n  + intros.\n    rewrite compare_ascii_lt_gt_asymmetric in H.\n    rewrite H.\n    reflexivity.\n  + intros.\n    contradict H0. (* Contradiction, if blt_ascii a b = true then compare_ascii a b <> Gt. *)\n    intuition.\nQed.\n\n(* TODO: blt_ascii_transitive *)\n\n(* Boolean less than or equal to for ASCII characters. *)\nDefinition bleq_ascii (a b : ascii) : bool :=\n  orb (blt_ascii a b) (beq_ascii a b).\n\n(* Prove that boolean less than or equal to for ASCII characters is reflexive. *)\nTheorem bleq_ascii_reflexive : forall (a : ascii),\n    bleq_ascii a a = true.\nProof.\n  intros.\n  unfold bleq_ascii.\n  rewrite beq_ascii_reflexive.\n  intuition. (* We end up with a disjunction with true = true, solved by intuition. *)\nQed.\n\n(* Boolean greater than for ASCII characters. *)\nDefinition bgt_ascii (a b : ascii) : bool :=\n  match compare_ascii a b with\n    | Gt => true\n    | _ => false\n  end.\n\n(** Prove that boolean greater than for ASCII characters is antireflexive. *)\nTheorem bgt_ascii_antireflexive : forall (a : ascii),\n    bgt_ascii a a = false.\nProof.\n  intros.\n  unfold bgt_ascii.\n  rewrite compare_ascii_reflexive.\n  reflexivity.\nQed.\n\n(** Prove that boolean greater than for ASCII characters is asymmetric. *)\nTheorem bgt_ascii_asymmetric : forall (a b : ascii),\n    bgt_ascii a b = true -> bgt_ascii b a = false.\nProof.\n  intros a b.\n  unfold bgt_ascii.\n  case_eq (compare_ascii a b).\n  + intros.\n    contradict H0.\n    intuition.\n  + intros.\n    contradict H0.\n    intuition.\n  + intros.\n    rewrite <- compare_ascii_lt_gt_asymmetric in H.\n    rewrite H.\n    reflexivity.\nQed.\n\n(* TODO: bgt_ascii_transitive *)\n\n(* Boolean greater than or equal to for ASCII characters. *)\nDefinition bgeq_ascii (a b : ascii) : bool :=\n  orb (bgt_ascii a b) (beq_ascii a b).\n\n(** Prove that boolean greater than or equal to for ASCII characters is reflexive. *)\nTheorem bgeq_ascii_reflexive : forall (a : ascii),\n    bgeq_ascii a a = true.\nProof.\n  intros.\n  unfold bgeq_ascii.\n  rewrite beq_ascii_reflexive.\n  intuition.\nQed.\n\n(* TODO: bgeq_ascii_antisymmetric *)\n\n(* TODO: bgeq_ascii_transitive *)\n\n(* Boolean equality for option ASCII characters. *)\nDefinition beq_option_ascii (a b : option ascii) : bool :=\n  match a, b with\n    | None, None => true\n    | Some a', Some b' => beq_ascii a' b'\n    | _, _ => false\n  end.\n\n(* TODO: Proofs for beq_option_ascii. *)\n\n(* Equality notations module for ASCII characters. *)\nModule AsciiEqualityNotations.\n  \n  (* Boolean equality operator. *)\n  Notation \"a ==_a b\" := (beq_ascii a b) (at level 30).\n\n  (* Boolean equality operator (including option). *)\n  Notation \"a ?==_a b\" := (beq_option_ascii a b) (at level 30).\n\n  (* Boolean less than operator. *)\n  Notation \"a <_a b\" := (blt_ascii a b) (at level 30).\n\n  (* Boolean less than or equal to operator. *)\n  Notation \"a <=_a b\" := (bleq_ascii a b) (at level 30).\n\n  (* Boolean greater than operator. *)\n  Notation \"a >_a b\" := (bgt_ascii a b) (at level 30).\n\n  (* Boolean greater than or equal to operator. *)\n  Notation \"a >=_a b\" := (bgeq_ascii a b) (at level 30).\n\nEnd AsciiEqualityNotations.\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/Ascii/Equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.779616397196901}}
{"text": "Inductive nat_tree : Set :=\n| NNode' : nat -> list nat_tree -> nat_tree.\nSection All.\n  Variable T : Set.\n  Variable P : T -> Prop.\n\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\nSection nat_tree_ind'.\n  Variable P : nat_tree -> Prop.\n\n  Hypothesis NNode'_case : forall (n : nat) (ls : list nat_tree),\n    All nat_tree P ls -> P (NNode' n ls).\n\n  Fixpoint 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 nat_tree 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) ls)\n    end.\nEnd nat_tree_ind'.\n\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 h t => plus h (sum t)\n  end.\n\n(*Now we can define a size function over our trees.*)\n\nFixpoint ntsize (tr : nat_tree) : nat :=\n  match tr with\n    | NNode' _ trs => S (sum (map _ _ ntsize trs))\n  end.\n\n(* Notice that Coq was smart enough to expand the definition of map\n to verify that we are using proper nested recursion, even through \na use of a higher-order function.*)\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 trs) => NNode' n (cons (ntsplice tr tr2) trs)\n  end.\n\n(*We have defined another arbitrary notion of tree splicing,\n similar to before, and we can prove an analogous theorem about\n its relationship with tree size. We start with a useful lemma about addition.*)\n\n\nAdd LoadPath \"/home/user/Downloads/cpdt/\".\nRequire Import Cpdt.CpdtTactics. (*!!! HOW TO src*)\n(**)\nLemma plus_S : forall n1 n2 : nat,\n  plus n1 (S n2) = S (plus n1 n2).\n  induction n1; crush.\nQed.\n\n(*Now we begin the proof of the theorem, adding the lemma plus_S as a hint.*)\n\nTheorem ntsize_ntsplice : forall tr1 tr2 : nat_tree, ntsize (ntsplice tr1 tr2)\n  = plus (ntsize tr2) (ntsize tr1).\n  Hint Rewrite plus_S.\n(*\nWe know that the standard induction principle is insufficient for the task, so we need to provide a using clause for the induction tactic to specify our alternate principle.\n*)\n  induction tr1 using nat_tree_ind'; crush.\n(*\nOne subgoal remains:\n  n : nat\n  ls : list nat_tree\n  H : All\n        (fun tr1 : nat_tree =>\n         forall tr2 : nat_tree,\n         ntsize (ntsplice tr1 tr2) = plus (ntsize tr2) (ntsize tr1)) ls\n  tr2 : nat_tree\n  ============================\n   ntsize\n     match ls with\n     | Nil => NNode' n (Cons tr2 Nil)\n     | Cons tr trs => NNode' n (Cons (ntsplice tr tr2) trs)\n     end = S (plus (ntsize tr2) (sum (map ntsize ls)))\n \nAfter a few moments of squinting at this goal, it becomes apparent that we need to do a case analysis on the structure of ls. The rest is routine.\n*)\n  destruct ls; crush.\n(*\nWe can go further in automating the proof by exploiting the hint mechanism.\n*)\n  Restart.\n\n  Hint Extern 1 (ntsize (match ?LS with nil => _ | cons _ _ => _ end) = _) =>\n    destruct LS; crush.\n  induction tr1 using nat_tree_ind'; crush.\nDefined.\nQed.\n", "meta": {"author": "georgydunaev", "repo": "TRASH", "sha": "36b24517b8c51817e1b8eb39df945d30c287162b", "save_path": "github-repos/coq/georgydunaev-TRASH", "path": "github-repos/coq/georgydunaev-TRASH/TRASH-36b24517b8c51817e1b8eb39df945d30c287162b/SHEN/nat_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642806, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7795117506646781}}
{"text": "Require Export Basics.\n\nTheorem plus_n_0 : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'. reflexivity. Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\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. Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity. Qed.\n\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_0. 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.\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 <- plus_n_Sm. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'.\n    rewrite -> negb_involutive.\n    simpl. 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. Qed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. reflexivity. Qed.\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n' IHn']. reflexivity.\n  simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_assoc'' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. destruct n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_Sm.\n    assert (H: n + m = m + n).\n    { rewrite -> plus_comm. reflexivity. }\n    rewrite -> plus_assoc'. rewrite -> H.\n    rewrite -> plus_assoc'. reflexivity.\nQed.\n\nTheorem mult_n_Sm : forall n m : nat,\n  n * S m = n * m + n.\nProof.\n  intros n m. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    rewrite -> plus_n_Sm.\n    rewrite <- plus_assoc'.\n    reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n. induction n as [|n' IHn'].\n  - simpl. rewrite -> mult_0_r. reflexivity.\n  - destruct m.\n    + simpl. rewrite -> mult_0_r. reflexivity.\n    + simpl. rewrite <- IHn'. simpl.\n      rewrite -> plus_swap.\n      rewrite -> mult_n_Sm.\n      assert (H: m * n' + m = m + m * n').\n      { rewrite -> plus_comm. reflexivity. }\n      rewrite -> H. reflexivity.\nQed.\n\nTheorem leb_refl : forall n : nat,\n  true = leb n n.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n : nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros b. destruct b.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\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.\n  induction p as [|p' IHn'].\n  - simpl. rewrite -> H. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n : nat,\n  beq_nat (S n) 0 = false.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\nTheorem mult_1_l : forall n : nat, 1 * n = n.\nProof.\n  intros n. simpl. rewrite <- plus_n_0.\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. destruct b.\n  - simpl. destruct c.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. 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 n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl. 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' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'.\n    rewrite -> mult_plus_distr_r.\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 plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. destruct n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- plus_n_Sm.\n    rewrite -> plus_assoc'.\n    rewrite -> plus_assoc'.\n    replace (n + m) with (m + n).\n    + reflexivity.\n    + rewrite -> plus_comm. reflexivity.\nQed.", "meta": {"author": "binaks", "repo": "funtp", "sha": "b196c7da3aecea3ff6afcc5902560dbc0afb5bad", "save_path": "github-repos/coq/binaks-funtp", "path": "github-repos/coq/binaks-funtp/funtp-b196c7da3aecea3ff6afcc5902560dbc0afb5bad/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7794524355688135}}
{"text": "From Coq Require Import Arith ZArith Psatz Bool String List Program.Equality.\nRequire Import Sequences Lemmas.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope list_scope.\n\n(** * 1. The source language: IMP *)\n\n(** ** 1.1 Arithmetic expressions *)\n\nDefinition ident := string.\n\n(** The abstract syntax: an arithmetic expression is either... *)\n\nInductive aexp : Type :=\n  | CONST (n: Z)                       (**r a constant, or *)\n  | VAR (x: ident)                    (**r a variable, or *)\n  | PLUS (a1: aexp) (a2: aexp)         (**r a sum of two expressions, or *)\n  | MINUS (a1: aexp) (a2: aexp).       (**r a difference of two expressions *)\n\n(** The denotational semantics: an evaluation function that computes\n  the integer value denoted by an expression.  It is parameterized by\n  a store [s] that associates values to variables. *)\n\nDefinition store : Type := ident -> Z.\n\nFixpoint aeval (s: store) (a: aexp) : Z :=\n  match a with\n  | CONST n => n\n  | VAR x => s x\n  | PLUS a1 a2 => aeval s a1 + aeval s a2\n  | MINUS a1 a2 => aeval s a1 - aeval s a2\n  end.\n\n(** Such evaluation functions / denotational semantics have many uses.\n    First, we can use [aeval] to evaluate a given expression in a given store. *)\n\nCompute (aeval (fun x => 2) (PLUS (VAR \"x\") (MINUS (VAR \"x\") (CONST 1)))).\n\n(** Result is: [ = 3 : Z ]. *)\n\n(** We can also do partial evaluation with respect to an unknown store *)\n\nEval cbn in (fun s => aeval s (PLUS (VAR \"x\") (MINUS (CONST 10) (CONST 1)))).\n\n(** Result is: [ = fun s : store => s \"x\" + 9 ]. *)\n\n(** We can prove properties of a given expression. *)\n\nLemma aeval_xplus1:\n  forall s x, aeval s (PLUS (VAR x) (CONST 1)) > aeval s (VAR x).\nProof.\n  intros. cbn. lia.\nQed.\n\n(** Finally, we can prove \"meta-properties\" that hold for all expressions.\n  For example: the value of an expression depends only on the values of its\n  free variables.\n\n  Free variables are defined by this recursive predicate:\n*)\n\nFixpoint free_in_aexp (x: ident) (a: aexp) : Prop :=\n  match a with\n  | CONST n => False\n  | VAR y => y = x\n  | PLUS a1 a2 | MINUS a1 a2 => free_in_aexp x a1 \\/ free_in_aexp x a2\n  end.\n\nTheorem aeval_free:\n  forall s1 s2 a,\n  (forall x, free_in_aexp x a -> s1 x = s2 x) ->\n  aeval s1 a = aeval s2 a.\nProof.\n  induction a; cbn; intros SAMEFREE.\n- (* Case a = CONST n *)\n  auto.\n- (* Case a = VAR x *)\n  apply SAMEFREE. auto.\n- (* Case a = PLUS a1 a2 *)\n  rewrite IHa1, IHa2. auto. auto. auto.\n- (* Case a = MINUS a1 a2 *)\n  rewrite IHa1, IHa2; auto.\nQed.\n\n(** *** Exercise (1 star, recommended). *)\n(** Add support for multiplication in arithmetic expressions.\n  Modify the [aexp] type and the [aeval] function accordingly. *)\n\n(** *** Exercise (2 stars, recommended). *)\n(** Add support for division and for detecting arithmetic overflow.\n  With this extension, the evaluation of an expression can produce an\n  error: integer division by zero or result that exceeds the range\n  [[min_int, max_int]].  You can either change the type of the\n  function [aeval] to\n<<\n  aeval: store -> aexp -> option Z\n>>\n  with [None] meaning \"error\" and [Some n] meaning \"success with\n  result n\".  Alternatively, you can define the semantics as a\n  relation instead of a function:\n<<\n  Inductive aeval_rel: store -> aexp -> Z -> Prop := ...\n>>\n  Some definitions you can use:\n*)\n\nDefinition min_int := - (2 ^ 63).\nDefinition max_int := 2 ^ 63 - 1.\nDefinition check_for_overflow (n: Z): option Z :=\n  if n <? min_int then None else if n >? max_int then None else Some n.\n\n(** ** 1.3 Boolean expressions *)\n\n(** The IMP language has conditional statements (if/then/else) and\n  loops.  They are controlled by expressions that evaluate to Boolean\n  values.  Here is the abstract syntax of Boolean expressions. *)\n\nInductive bexp : Type :=\n  | TRUE                              (**r always true *)\n  | FALSE                             (**r always false *)\n  | EQUAL (a1: aexp) (a2: aexp)       (**r whether [a1 = a2] *)\n  | LESSEQUAL (a1: aexp) (a2: aexp)   (**r whether [a1 <= a2] *)\n  | NOT (b1: bexp)                    (**r Boolean negation *)\n  | AND (b1: bexp) (b2: bexp).        (**r Boolean conjunction *)\n\n(** Just like arithmetic expressions evaluate to integers,\n  Boolean expressions evaluate to Boolean values [true] or [false]. *)\n\nFixpoint beval (s: store) (b: bexp) : bool :=\n  match b with\n  | TRUE => true\n  | FALSE => false\n  | EQUAL a1 a2 => aeval s a1 =? aeval s a2\n  | LESSEQUAL a1 a2 => aeval s a1 <=? aeval s a2\n  | NOT b1 => negb (beval s b1)\n  | AND b1 b2 => beval s b1 && beval s b2\n  end.\n\n(** There are many useful derived forms. *)\n\nDefinition NOTEQUAL (a1 a2: aexp) : bexp := NOT (EQUAL a1 a2).\n\nDefinition GREATEREQUAL (a1 a2: aexp) : bexp := LESSEQUAL a2 a1.\n\nDefinition GREATER (a1 a2: aexp) : bexp := NOT (LESSEQUAL a1 a2).\n\nDefinition LESS (a1 a2: aexp) : bexp := GREATER a2 a1.\n\nDefinition OR (b1 b2: bexp) : bexp := NOT (AND (NOT b1) (NOT b2)).\n\n(** *** Exercise (1 star, recommended) *)\n(** Show the expected semantics for the [OR] derived form: *)\n\nLemma beval_OR:\n  forall s b1 b2, beval s (OR b1 b2) = beval s b1 || beval s b2.\nProof.\n  (* Hint: do \"SearchAbout negb\" to see the available lemmas about Boolean negation. *)\n  (* Hint: or just do a case analysis on [beval s b1] and [beval s b2], there are\n     only 4 cases to consider. *)\n  intros; cbn.\n  remember (beval s b1) as b1'.\n  remember (beval s b2) as b2'.\n  (* TODO: any clever bool automations? *)\n  destruct b1'; destruct b2'; reflexivity.\nQed.\n\n(** ** 1.4 Commands *)\n\n(** To complete the definition of the IMP language, here is the\n  abstract syntax of commands, also known as statements. *)\n\nInductive com: Type :=\n  | SKIP                                     (**r do nothing *)\n  | ASSIGN (x: ident) (a: aexp)              (**r assignment: [v := a] *)\n  | SEQ (c1: com) (c2: com)                  (**r sequence: [c1; c2] *)\n  | IFTHENELSE (b: bexp) (c1: com) (c2: com) (**r conditional: [if b then c1 else c2] *)\n  | WHILE (b: bexp) (c1: com).               (**r loop: [while b do c1 done] *)\n\n(** We can write [c1 ;; c2] instead of [SEQ c1 c2], it is easier on the eyes. *)\n\nInfix \";;\" := SEQ (at level 80, right associativity).\n\n(** Here is an IMP program that performs Euclidean division by\n  repeated subtraction.  At the end of the program, \"q\" contains\n  the quotient of \"a\" by \"b\", and \"r\" contains the remainder.\n  In pseudocode:\n<<\n       r := a; q := 0;\n       while b <= r do r := r - b; q := q + 1 done\n>>\n  In abstract syntax:\n*)\n\nDefinition Euclidean_division :=\n  ASSIGN \"r\" (VAR \"a\") ;;\n  ASSIGN \"q\" (CONST 0) ;;\n  WHILE (LESSEQUAL (VAR \"b\") (VAR \"r\"))\n    (ASSIGN \"r\" (MINUS (VAR \"r\") (VAR \"b\")) ;;\n     ASSIGN \"q\" (PLUS (VAR \"q\") (CONST 1))).\n\n(** A useful operation over stores:\n    [update x v s] is the store that maps [x] to [v] and is equal to [s] for\n    all variables other than [x]. *)\n\nDefinition update (x: ident) (v: Z) (s: store) : store :=\n  fun y => if string_dec x y then v else s y.\n\n(** A naive approach to giving semantics to commands is to write an\n  evaluation function [cexec s c] that runs the command [c] in initial\n  store [s] and returns the final store when [c] terminates. *)\n\nFail Fixpoint cexec (s: store) (c: com) : store :=\n  match c with\n  | SKIP => s\n  | ASSIGN x a => update x (aeval s a) s\n  | SEQ c1 c2 => let s' := cexec s c1 in cexec s' c2\n  | IFTHENELSE b c1 c2 => if beval s b then cexec s c1 else cexec s c2\n  | WHILE b c1 =>\n      if beval s b\n      then (let s' := cexec s c1 in cexec s' (WHILE b c1))\n      else s\n  end.\n\n(** The definition above is rejected by Coq, and rightly so, because\n  all Coq functions must terminate, yet the [WHILE] case may not\n  terminate.  Consider for example the infinite loop [WHILE TRUE\n  SKIP].\n\n  Worse, IMP is Turing-complete, since it has unbounded iteration\n  ([WHILE]) plus arbitrary-precision integers.  Hence, there is no\n  computable function [cexec s c] that would return [Some s'] if [c]\n  terminates with store [s'], and [None] if [c] does not terminate.\n\n  However, instead of computable functions, we can use a relation\n  [cexec s c s'] that holds iff command [c], started in state [s],\n  terminates with state [s'].  This relation can easily be defined as\n  a Coq inductive predicate:\n*)\n\nInductive cexec: store -> com -> store -> Prop :=\n  | cexec_skip: forall s,\n      cexec s SKIP s\n  | cexec_assign: forall s x a,\n      cexec s (ASSIGN x a) (update x (aeval s a) s)\n  | cexec_seq: forall c1 c2 s s' s'',\n      cexec s c1 s' -> cexec s' c2 s'' ->\n      cexec s (SEQ c1 c2) s''\n  | cexec_ifthenelse: forall b c1 c2 s s',\n      cexec s (if beval s b then c1 else c2) s' ->\n      cexec s (IFTHENELSE b c1 c2) s'\n  | cexec_while_done: forall b c s,\n      beval s b = false ->\n      cexec s (WHILE b c) s\n  | cexec_while_loop: forall b c s s' s'',\n      beval s b = true -> cexec s c s' -> cexec s' (WHILE b c) s'' ->\n      cexec s (WHILE b c) s''.\n\n(** This style of semantics is known as natural semantics or big-step\n  operational semantics.  The predicate [cexec s c s'] holds iff there\n  exists a finite derivation of this conclusion, using the axioms and\n  inference rules above.  The structure of the derivation represents\n  the computations performed by [c] in a tree-like manner.  The\n  finiteness of the derivation guarantees that only terminating\n  executions satisfy [cexec].  Indeed, [WHILE TRUE SKIP] does not\n  satisfy [cexec]: *)\n\nLemma cexec_infinite_loop:\n  forall s, ~ exists s', cexec s (WHILE TRUE SKIP) s'.\nProof.\n  assert (A: forall s c s', cexec s c s' -> c = WHILE TRUE SKIP -> False).\n  { induction 1; intros EQ; inversion EQ.\n  - subst b c. cbn in H. discriminate.\n  - subst b c. apply IHcexec2. auto.\n  }\n  intros s (s' & EXEC). apply A with (s := s) (c := WHILE TRUE SKIP) (s' := s'); auto.\nQed.\n\n(** Our naive idea of an execution function for commands was not\n  completely off.  We can define an approximation of such a function\n  by bounding a priori the recursion depth, using a [fuel] parameter\n  of type [nat].  When the fuel drops to 0, [None] is returned,\n  meaning that the final store could not be computed. *)\n\nFixpoint cexec_bounded (fuel: nat) (s: store) (c: com) : option store :=\n  match fuel with\n  | O => None\n  | S fuel' =>\n      match c with\n      | SKIP => Some s\n      | ASSIGN x a => Some (update x (aeval s a) s)\n      | SEQ c1 c2 =>\n          match cexec_bounded fuel' s c1 with\n          | None  => None\n          | Some s' => cexec_bounded fuel' s' c2\n          end\n      | IFTHENELSE b c1 c2 =>\n          if beval s b then cexec_bounded fuel' s c1 else cexec_bounded fuel' s c2\n      | WHILE b c1 =>\n          if beval s b then\n            match cexec_bounded fuel' s c1 with\n            | None  => None\n            | Some s' => cexec_bounded fuel' s' (WHILE b c1)\n            end\n          else Some s\n      end\n  end.\n\n(** This bounded execution function is great for testing programs.\n    For example, let's compute the quotient and the remainder of 14 by\n    3 using the Euclidean division program above. *)\n\nEval compute in\n  (let s := update \"a\" 14 (update \"b\" 3 (fun _ => 0)) in\n   match cexec_bounded 100 s Euclidean_division with\n   | None => None\n   | Some s' => Some (s' \"q\", s' \"r\")\n   end).\n\n(** *** Exercise (3 stars, optional) *)\n(** Relate the [cexec] relation with the [cexec_bounded] function by\n  proving the following two lemmas. *)\n\nLemma cexec_bounded_sound:\n  forall fuel s c s', cexec_bounded fuel s c = Some s' -> cexec s c s'.\nProof.\n  induction fuel as [ | fuel].\n  - intros. simpl in H. inversion H.\n  - destruct c; simpl; intros;\n      try (inversion H; subst; constructor; clear H1).\n    + destruct (cexec_bounded fuel s c1) eqn:H'; try inversion H.\n      pose proof (IHfuel _ _ _ H').\n      pose proof (IHfuel _ _ _ H).\n      eapply cexec_seq; eassumption.\n    + destruct (beval s b);\n      apply IHfuel; assumption.\n    + destruct (beval s b) eqn:Hsb.\n      destruct (cexec_bounded fuel s c) eqn:H';\n        try inversion H.\n      pose proof (IHfuel _ _ _ H').\n      pose proof (IHfuel _ _ _ H).\n      econstructor; eassumption.\n      inversion H; subst; constructor; assumption.\nQed.\n\nLemma cexec_bounded_complete:\n  forall s c s', cexec s c s' ->\n  exists fuel1, forall fuel, (fuel >= fuel1)%nat -> cexec_bounded fuel s c = Some s'.\nProof.\n  induction 1.\n  - (* SKIP *)\n    exists 1%nat; intros.\n    destruct fuel; try inversion H.\n    constructor. reflexivity.\n  - (* ASSIGN *)\n    exists 1%nat; intros.\n    destruct fuel; try inversion H.\n    constructor. reflexivity.\n  - (* SEQ *)\n    destruct IHcexec1 as [fuel1 IHc1exec];\n      assert (Hc1exec := IHc1exec fuel1 (ge_refl fuel1));\n    destruct IHcexec2 as [fuel2 IHc2exec];\n      assert (Hc2exec := IHc2exec fuel2 (ge_refl fuel2)).\n      (* actually should be precisely  max(fuel1, fuel2)  *)\n    exists (1 + fuel1 + fuel2)%nat; intros fuel Hfuel.\n    destruct (ge_diff Hfuel) as [k Hk]; clear Hfuel; subst fuel.\n    simpl.\n    remember (fuel1 + fuel2 + k)%nat as fuel_big.\n    assert (Hc1execBig: cexec_bounded fuel_big s c1 = Some s') by\n      (apply IHc1exec; lia).\n    assert (Hc2execBig: cexec_bounded fuel_big s' c2 = Some s'') by\n      (apply IHc2exec; lia).\n    destruct (cexec_bounded fuel_big s c1) eqn:Hc1;\n      try inversion Hc1execBig.\n    destruct (cexec_bounded fuel_big s' c2) eqn:Hc2;\n      try inversion Hc2execBig.\n    subst; reflexivity.\n  - (* IFTHENELSE *)\n    destruct IHcexec as [fuel IHcexec].\n    exists (S fuel).\n    intros fuel' Hfuel'; destruct (ge_diff Hfuel') as [k Hk]; clear Hfuel'; subst fuel'.\n    simpl.\n    destruct (beval s b) eqn:Hb;\n      apply IHcexec; lia.\n  - (* WHILEDONE *) exists 1%nat.\n    intros fuel' Hfuel'; destruct (ge_diff Hfuel') as [k Hk]; clear Hfuel'; subst fuel'.\n    simpl.\n    rewrite H; reflexivity.\n  - (* WHILELOOP *)\n    destruct IHcexec1 as [fuel1 IHc1exec];\n      assert (Hc1exec := IHc1exec fuel1 (ge_refl fuel1));\n    destruct IHcexec2 as [fuel2 IHc2exec];\n      assert (Hc2exec := IHc2exec fuel2 (ge_refl fuel2)).\n    exists (1 + fuel1 + fuel2)%nat.\n    intros fuel' Hfuel'; destruct (ge_diff Hfuel') as [k Hk]; clear Hfuel'; subst fuel'.\n    simpl.\n    rewrite H.\n    remember (fuel1 + fuel2 + k)%nat as fuel_big.\n    remember c as c1; remember (WHILE b c1) as c2.\n    assert (Hc1execBig: cexec_bounded fuel_big s c1 = Some s') by\n      (apply IHc1exec; lia).\n    assert (Hc2execBig: cexec_bounded fuel_big s' c2 = Some s'') by\n      (apply IHc2exec; lia).\n    destruct (cexec_bounded fuel_big s c1) eqn:Hc1;\n      try inversion Hc1execBig.\n    destruct (cexec_bounded fuel_big s' c2) eqn:Hc2;\n      try inversion Hc2execBig.\n    subst; reflexivity.\nQed.\n\n(** * 6. Small-step semantics for IMP *)\n\n(** * 6.1 Reduction semantics *)\n\n(** In small-step style, the semantics is presented as a one-step\n  reduction relation [ red (c, s) (c', s') ], meaning that the command\n  [c], executed in initial state [s], performs one elementary step of\n  computation.  [s'] is the updated state after this step.  [c'] is\n  the residual command, capturing all the computations that remain to\n  be done.  *)\n\nInductive red: com * store -> com * store -> Prop :=\n  | red_assign: forall x a s,\n      red (ASSIGN x a, s) (SKIP, update x (aeval s a) s)\n  | red_seq_done: forall c s,\n      red (SEQ SKIP c, s) (c, s)\n  | red_seq_step: forall c1 c s1 c2 s2,\n      red (c1, s1) (c2, s2) ->\n      red (SEQ c1 c, s1) (SEQ c2 c, s2)\n  | red_ifthenelse: forall b c1 c2 s,\n      red (IFTHENELSE b c1 c2, s) ((if beval s b then c1 else c2), s)\n  | red_while_done: forall b c s,\n      beval s b = false ->\n      red (WHILE b c, s) (SKIP, s)\n  | red_while_loop: forall b c s,\n      beval s b = true ->\n      red (WHILE b c, s) (SEQ c (WHILE b c), s).\n\n(** *** Exercise (2 stars, recommended) *)\n(** Show that Imp programs cannot go wrong.  Hint: first prove the following\n  \"progress\" result for non-[SKIP] commands. *)\n\nLemma red_progress:\n  forall c s, c = SKIP \\/ exists c', exists s', red (c, s) (c', s').\nProof.\n  induction c; intros;\n    (* SKIP *)\n    (try (left; reflexivity) || right);\n    (* ASSIGN *)\n    (* IFTHENELSE *)\n    try (eexists; eexists; constructor; fail).\n  - (* SEQ *)\n    destruct c1;\n      (* SEQ_DONE *)\n      try (\n        eexists; eexists; constructor;\n        fail);\n      (* SEQ_STEP *)\n      try (\n        specialize (IHc1 s); destruct IHc1 as [ IHc1 | IHc1 ]; try inversion IHc1;\n        destruct IHc1 as [c1Next [sNext Hc1]];\n        eexists; exists sNext; econstructor; eassumption;\n        exists (c1Next ;; c2); exists sNext;\n        apply red_seq_step; assumption;\n        fail).\n  - (* WHILE *)\n    destruct (beval s b) eqn:Hb;\n      eexists; eexists;\n      [ apply red_while_loop | apply red_while_done ];\n      assumption.\nQed.\n\nDefinition goes_wrong (c: com) (s: store) : Prop :=\n  exists c', exists s',\n  star red (c, s) (c', s') /\\ irred red (c', s') /\\ c' <> SKIP.\n\nLemma not_goes_wrong:\n  forall c s, ~(goes_wrong c s).\nProof.\n  intros c s (c' & s' & STAR & IRRED & NOTSKIP).\n  pose proof (red_progress c' s').\n  inversion H; intuition; clear H1 NOTSKIP.\n  destruct H0 as [c'C [s'C Hred]].\n  specialize (IRRED (c'C, s'C)).\n  intuition.\nQed.\n\n(** Sequences of reductions can go under a sequence context, generalizing\n  rule [red_seq_step]. *)\n\nLemma red_seq_steps:\n  forall c2 s c s' c',\n  star red (c, s) (c', s') -> star red ((c;;c2), s) ((c';;c2), s').\nProof.\n  intros. dependent induction H.\n- apply star_refl.\n- destruct b as [c1 st1].\n  apply star_step with (c1;;c2, st1). apply red_seq_step. auto. auto.\nQed.\n\n(** We now recall the equivalence result between\n- termination according to the big-step semantics\n- existence of a finite sequence of reductions to [SKIP]\n  according to the small-step semantics.\n\nWe start with the implication big-step ==> small-step, which is\na straightforward induction on the big-step evaluation derivation. *)\n\nTheorem cexec_to_reds:\n  forall s c s', cexec s c s' -> star red (c, s) (SKIP, s').\nProof.\n  induction 1.\n- (* SKIP *)\n  apply star_refl.\n- (* ASSIGN *)\n  apply star_one. apply red_assign.\n- (* SEQ *)\n  eapply star_trans. apply red_seq_steps. apply IHcexec1.\n  eapply star_step.  apply red_seq_done.  apply IHcexec2.\n- (* IFTHENELSE *)\n  eapply star_step. apply red_ifthenelse. auto.\n- (* WHILE stop *)\n  apply star_one. apply red_while_done. auto.\n- (* WHILE loop *)\n  eapply star_step. apply red_while_loop. auto.\n  eapply star_trans. apply red_seq_steps. apply IHcexec1.\n  eapply star_step. apply red_seq_done. apply IHcexec2.\nQed.\n\n(** The reverse implication, from small-step to big-step, is more subtle.\nThe key lemma is the following, showing that one step of reduction\nfollowed by a big-step evaluation to a final state can be collapsed\ninto a single big-step evaluation to that final state. *)\n\nLemma red_append_cexec:\n  forall c1 s1 c2 s2, red (c1, s1) (c2, s2) ->\n  forall s', cexec s2 c2 s' -> cexec s1 c1 s'.\nProof.\n  intros until s2; intros STEP. dependent induction STEP; intros.\n- (* red_assign *)\n  inversion H; subst. apply cexec_assign.\n- (* red_seq_done *)\n  apply cexec_seq with s2. apply cexec_skip. auto.\n- (* red seq step *)\n  inversion H; subst. apply cexec_seq with s'0.\n  eapply IHSTEP; eauto.\n  auto.\n- (* red_ifthenelse *)\n  apply cexec_ifthenelse. auto.\n- (* red_while_done *)\n  inversion H0; subst. apply cexec_while_done. auto.\n- (* red while loop *)\n  inversion H0; subst. apply cexec_while_loop with s'0; auto.\nQed.\n\n(** As a consequence, a term that reduces to [SKIP] evaluates in big-step\n  with the same final state. *)\n\nTheorem reds_to_cexec:\n  forall s c s',\n  star red (c, s) (SKIP, s') -> cexec s c s'.\nProof.\n  intros. dependent induction H.\n- apply cexec_skip.\n- destruct b as [c1 s1]. apply red_append_cexec with c1 s1; auto.\nQed.\n\n(** ** 6.2 Transition semantics with continuations *)\n\n(** We now introduce an alternate form of small-step semantics\n  where the command to be executed is explicitly decomposed into:\n- a sub-command under focus, where computation takes place;\n- a continuation (or context) describing the position of this sub-command\n  in the whole command, or, equivalently, describing the parts of the\n  whole command that remain to be reduced once the sub-command is done.\n\nAs a consequence, the small-step semantics is presented as a\ntransition relation between triples (subcommand-under-focus,\ncontinuation, state).  Previously, we had transitions between pairs\n(whole-command, state).\n\nThe syntax of continuations is as follows:\n*)\n\nInductive cont : Type :=\n  | Kstop\n  | Kseq (c: com) (k: cont)\n  | Kwhile (b: bexp) (c: com) (k: cont).\n\n(** Intuitive meaning of these constructors:\n- [Kstop] means that, after the sub-command under focus terminates,\n  nothing remains to be done, and execution can stop.  In other words,\n  the sub-command under focus is the whole command.\n- [Kseq c k] means that, after the sub-command terminates, we still need\n  to execute command [c] in sequence, then continue as described by [k].\n- [Kwhile b c k] means that, after the sub-command terminates, we still need\n  to execute a loop [WHILE b DO c END], then continue as described by [k].\n*)\n\n(** Another way to forge intuitions about continuations is to ponder the following\n  [apply_cont k c] function, which takes a sub-command [c] under focus\n  and a continuation [k], and rebuilds the whole command.  It simply\n  puts [c] in lefmost position in a nest of sequences as described by [k].\n*)\n\nFixpoint apply_cont (k: cont) (c: com) : com :=\n  match k with\n  | Kstop => c\n  | Kseq c1 k1 => apply_cont k1 (SEQ c c1)\n  | Kwhile b1 c1 k1 => apply_cont k1 (SEQ c (WHILE b1 c1))\n  end.\n\n(** Transitions between (subcommand-under-focus, continuation, state)\n  triples perform conceptually different kinds of actions:\n- Computation: evaluate an arithmetic expression or boolean expression\n  and modify the triple according to the result of the evaluation.\n- Focusing: replace the sub-command by a sub-sub-command that is to be\n  evaluated next, possibly enriching the continuation as a consequence.\n- Resumption: when the sub-command is [SKIP] and therefore fully executed,\n  look at the head of the continuation to see what to do next.\n\nHere are the transition rules, classified by the kinds of actions they implement.\n*)\n\nInductive step: com * cont * store -> com * cont * store -> Prop :=\n\n  | step_assign: forall x a k s,              (**r computation for assignments *)\n      step (ASSIGN x a, k, s) (SKIP, k, update x (aeval s a) s)\n\n  | step_seq: forall c1 c2 s k,               (**r focusing for sequence *)\n      step (SEQ c1 c2, k, s) (c1, Kseq c2 k, s)\n\n  | step_ifthenelse: forall b c1 c2 k s,      (**r computation for conditionals *)\n      step (IFTHENELSE b c1 c2, k, s) ((if beval s b then c1 else c2), k, s)\n\n  | step_while_done: forall b c k s,          (**r computation for loops *)\n      beval s b = false ->\n      step (WHILE b c, k, s) (SKIP, k, s)\n\n  | step_while_true: forall b c k s,          (**r computation and focusSKIing for loops *)\n      beval s b = true ->\n      step (WHILE b c, k, s) (c, Kwhile b c k, s)\n\n  | step_skip_seq: forall c k s,              (**r resumption *)\n      step (SKIP, Kseq c k, s) (c, k, s)\n\n  | step_skip_while: forall b c k s,          (**r resumption *)\n      step (SKIP, Kwhile b c k, s) (WHILE b c, k, s).\n\n\n(** *** Extensions to other control structures *)\n\n(** A remarkable feature of continuation semantics is that they extend very easily\n  to other control structures besides \"if-then-else\" and \"while\" loops.\n  Consider for instance the \"break\" construct of C, C++ and Java, which\n  immediately terminates the nearest enclosing \"while\" loop.  Assume we\n  extend the type of commands with a [BREAK] constructor.  Then, all we need\n  to give \"break\" a semantics is to add two resumption rules:\n<<\n  | step_break_seq: forall c k s,\n      step (BREAK, Kseq c k, s) (BREAK, k, s)\n  | step_break_while: forall b c k s,\n      step (BREAK, Kwhile b c k, s) (SKIP, k, s)\n>>\n  The first rule says that a [BREAK] statement \"floats up\" pending sequences,\n  skipping over the computations they contain.  Eventually, a [Kwhile]\n  continuation is encountered, meaning that the [BREAK] found its enclosing\n  loop.  Then, the second rule discards the [Kwhile] continuation and\n  turns the [BREAK] into a [SKIP], effectively terminating the loop.\n  That's all there is to it!\n**)\n\n(** *** Exercise (2 stars, recommended) *)\n(** Besides \"break\", C, C++ and Java also have a \"continue\" statement\n  that terminates the current iteration of the enclosing loop,\n  then resumes the loop at its next iteration (instead of stopping\n  the loop like \"break\" does). Give the transition rules\n  for the \"continue\" statement. *)\n(**\n<<\n  | step_continue_seq: forall c k s,\n      step (CONTINUE, Kseq c k, s) (CONTINUE, k, s)\n  | step_continue_while_done: forall b c k s,\n      beval s b = false ->\n      step (CONTINUE, Kwhile b c k, s) (SKIP, k, s)\n  | step_continue_while_true: forall b c k s,\n      beval s b = true ->\n      step (CONTINUE, Kwhile b c k, s) (c, Kwhile b c k, s)\n*)\n\n(** *** Exercise (3 stars, optional) *)\n(** In Java, loops as well as \"break\" and \"continue\" statements carry\n  an optional label.  \"break\" without a label exits out of the immediately\n  enclosing loop, but \"break lbl\" exits out of the first enclosing loop\n  that carries the label \"lbl\".  Similarly for \"continue\".\n  Give the transition rules for \"break lbl\" and \"continue lbl\". *)\n\n(** *** Relating the continuation semantics and the big-step semantics *)\n\n(** *** Exercise (2 stars, optional) *)\n(** Show that a big-step execution give rise to a sequence of steps to [SKIP].\n  You can adapt the proof of theorem [cexec_to_reds] with minor changes. *)\n\nTheorem cexec_to_steps:\n  forall s c s', cexec s c s' -> forall k, star step (c, k, s) (SKIP, k, s').\nProof.\n  induction 1; intros k.\n  - (* SKIP *)\n    constructor.\n  - (* ASGN *)\n    repeat econstructor.\n  - (* SEQ *)\n    econstructor. apply step_seq.\n    eapply star_trans. apply IHcexec1.\n    econstructor. apply step_skip_seq.\n    apply IHcexec2.\n  - (* IFTHENELSE *)\n    econstructor. apply step_ifthenelse.\n    apply IHcexec.\n  - (* WHILE FALSE *)\n    econstructor. apply step_while_done; try assumption.\n    econstructor.\n  - (* WHILE TRUE *)\n    econstructor. apply step_while_true; try assumption.\n    eapply star_trans. apply IHcexec1.\n    econstructor. apply step_skip_while.\n    apply IHcexec2.\nQed.\n\n(** *** Exercise (3 stars, optional) *)\n(** Show the converse result: a sequence of steps to [(SKIP, Kstop)] corresponds\n  to a big-step execution.  You need a lemma similar to [red_append_cexec],\n  but also a notion of big-step execution of a continuation. *)\n\nLtac easy_head :=\n    eapply cexec_seq;\n      try (eassumption; fail);\n      try (econstructor; eassumption; fail).\n\nLtac inv_Hcexec := repeat match goal with\n                    | H: cexec _ (_;; _) _ |- _ => inv H\n                    | H: cexec _ SKIP _ |- _ => inv H\n                    end.\n\nLemma cexec_head_skip_noop: forall s c s',\n  cexec s c s' <-> cexec s (SKIP;; c) s'.\nProof.\n  split; intros.\n  - easy_head.\n  - inv_Hcexec. assumption.\nQed.\n\nLemma cexec_tail_skip_noop: forall s c s',\n  cexec s c s' <-> cexec s (c;; SKIP) s'.\nProof.\n  split; intros.\n  - easy_head.\n  - inv_Hcexec. assumption.\nQed.\n\nLtac strip_cexec_skip := match goal with\n                    | |- cexec _ (SKIP;; _) _ => rewrite <- cexec_head_skip_noop\n                    | |- cexec _ (_;; SKIP) _ => rewrite <- cexec_tail_skip_noop\n                    end.\n\nLemma apply_cont_seq: forall k c1 c2 s s',\n  cexec s (SEQ c1 (apply_cont k c2)) s' <-> cexec s (apply_cont k (SEQ c1 c2)) s'.\nProof with easy_head.\n  induction k; split; intros; simpl in *;\n    try auto;\n    try (\n      inv_Hcexec;\n      rewrite <- IHk in *;\n      inv_Hcexec; easy_head);\n    try (\n      rewrite <- IHk in *;\n      inv_Hcexec; easy_head;\n      rewrite <- IHk in *; easy_head).\nQed.\n\nLemma apply_cont_done: forall k c s s',\n  cexec s (SEQ c (apply_cont k SKIP)) s' <-> cexec s (apply_cont k c) s'.\nProof with repeat easy_head.\n  induction k; split; intros; simpl in *.\n  (* Kstop *)\n  - inv_Hcexec...\n    assumption.\n  - strip_cexec_skip.\n    assumption.\n  (* Kseq *)\n  - inv_Hcexec...\n    rewrite <- IHk in *.\n    inv_Hcexec...\n  - rewrite <- IHk in *.\n    inv_Hcexec...\n    rewrite <- IHk in *.\n    inv_Hcexec...\n  (* Kwhile *)\n  - inv_Hcexec...\n    rewrite <- IHk in *.\n    inv_Hcexec...\n  - rewrite <- IHk in *.\n    inv_Hcexec...\n    rewrite <- IHk in *.\n    inv_Hcexec...\nQed.\n\nInductive Wrapper {P: Prop} := mkWrap: P -> @Wrapper P.\nLemma deWrap: forall P, @Wrapper P -> P.\nintros. inv H. assumption. Qed.\n\nLtac destruct_Hexec :=\n  repeat match goal with\n  | H: cexec _ (apply_cont _ (_;; _)) _ |- _=>\n      rewrite <- apply_cont_seq in H; inv H\n  | H: cexec _ (apply_cont _ SKIP) _ |- _=>\n      pose proof (mkWrap H); clear H\n  | H: cexec _ (apply_cont _ _) _ |- _ =>\n      rewrite <- apply_cont_done in H; inv H\n  end;\n  repeat match goal with\n  | H: @Wrapper _ |- _ =>\n      apply deWrap in H\n  end.\n\nLtac destruct_solve_goal :=\n  repeat match goal with\n  | |- cexec _ (apply_cont _ (_;; _)) _ =>\n      rewrite <- apply_cont_seq; easy_head\n  | |- cexec _ (apply_cont _ _) _ =>\n      rewrite <- apply_cont_done; easy_head\n  end.\n\nLemma step_append_cexec:\n  forall c1 k1 s1 c2 k2 s2, step (c1, k1, s1) (c2, k2, s2) ->\n  forall s', cexec s2 (apply_cont k2 c2) s' ->\n  cexec s1 (apply_cont k1 c1) s'.\nProof with repeat easy_head.\n  intros until s2; intros Hstep.\n  dependent induction Hstep;\n    intros; simpl in *;\n    destruct_Hexec;\n    destruct_solve_goal.\nQed.\n\nTheorem steps_to_cexec:\n  forall c s s' k, star step (c, k, s) (SKIP, Kstop, s') -> cexec s (apply_cont k c) s'.\nProof.\n  intros. dependent induction H.\n  - apply cexec_skip.\n  - destruct b as [[c1 k1] s1]. apply step_append_cexec with c1 k1 s1; auto.\nQed.\n\n\n\nSection UNUSED.\nInductive stepexec: store -> cont -> store -> Prop :=\n  | stepexec_stop: forall s,\n      stepexec s Kstop s\n\n  | stepexec_seq_skip: forall s s' k,\n      stepexec s k s' ->\n      stepexec s (Kseq SKIP k) s'\n  | stepexec_seq_assign: forall s x a s' k,\n      stepexec (update x (aeval s a) s) k s' ->\n      stepexec s (Kseq (ASSIGN x a) k) s'\n  | stepexec_seq_seq: forall s c1 c2 s' k,\n      stepexec s (Kseq c1 (Kseq c2 k)) s' ->\n      stepexec s (Kseq (SEQ c1 c2) k) s'\n  | stepexec_seq_ifthenelse: forall s b c1 c2 s' k,\n      stepexec s (Kseq (if (beval s b) then c1 else c2) k) s' ->\n      stepexec s (Kseq (IFTHENELSE b c1 c2) k) s'\n  | stepexec_seq_while: forall s b c s' k,\n      stepexec s (Kwhile b c k) s' ->\n      stepexec s (Kseq (WHILE b c) k) s'\n\n  | stepexec_while_done: forall s b c s' k,\n      beval s b = false ->\n      stepexec s k s' ->\n      stepexec s (Kwhile b c k) s'\n  | stepexec_while_loop: forall s b c s' k,\n      beval s b = true ->\n      stepexec s (Kseq c (Kwhile b c k)) s' ->\n      stepexec s (Kwhile b c k) s'.\n\nLemma stepexec_to_cexec: forall s s' k,\n  stepexec s k s' -> cexec s (apply_cont k SKIP) s'.\nProof.\n  intros *. intros Hstepexec. dependent induction Hstepexec.\n  - (* Kstop *)\n    simpl in *. apply cexec_skip.\n  - (* Kseq SKIP k *)\n    simpl in *. rewrite <- apply_cont_seq.\n    eapply cexec_seq. econstructor.\n    assumption.\n  - (* Kseq ASSIGN k *)\n    simpl in *. rewrite <- apply_cont_seq.\n    eapply cexec_seq. econstructor.\n    rewrite <- apply_cont_done.\n    eapply cexec_seq. econstructor. assumption.\n  - (* Kseq SEQ k *)\n    simpl in *.\n    rewrite <- apply_cont_seq in IHHstepexec.\n    inv IHHstepexec. inv H2. inv H3.\n    rewrite <- apply_cont_seq.\n    eapply cexec_seq. econstructor.\n    rewrite <- apply_cont_seq.\n    eapply cexec_seq. eassumption. assumption.\n  - (* Kseq IFTHENELSE k *)\n    simpl in *.\n    rewrite <- apply_cont_seq in IHHstepexec.\n    inv IHHstepexec. inv H2.\n    rewrite <- apply_cont_seq.\n      eapply cexec_seq. econstructor.\n    rewrite <- apply_cont_done.\n    rewrite <- apply_cont_done in H4.\n    inv H4.\n      eapply cexec_seq. econstructor.\n      eassumption.\n      assumption.\n  - (* Kseq WHILE k *)\n    simpl in *. assumption.\n  - (* KWhile false c k *)\n    simpl in *.\n    rewrite <- apply_cont_seq.\n    eapply cexec_seq. econstructor.\n    rewrite <- apply_cont_done.\n    eapply cexec_seq. econstructor; assumption.\n    assumption.\n  - (* KWhile true c k *)\n    (*remember (Kwhile b c k) as kw.*)\n    simpl in *.\n    rewrite <- apply_cont_seq in IHHstepexec.\n    inv IHHstepexec. inv H3. inv H4.\n    rewrite <- apply_cont_done in H5.\n    inv H5.\n    rewrite <- apply_cont_seq.\n    eapply cexec_seq. econstructor.\n    rewrite <- apply_cont_done.\n    eapply cexec_seq. eapply cexec_while_loop.\n    eassumption. eassumption. eassumption. eassumption.\nQed.\nEnd UNUSED.\n", "meta": {"author": "Hoblovski", "repo": "compilerverif", "sha": "7f2fefb761afbcd610ef2ebe04c9a9e5e36f31de", "save_path": "github-repos/coq/Hoblovski-compilerverif", "path": "github-repos/coq/Hoblovski-compilerverif/compilerverif-7f2fefb761afbcd610ef2ebe04c9a9e5e36f31de/IMP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009468718408, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7794524269304558}}
{"text": "Theorem ex21: forall a b : Prop,\n               (a /\\ b) <-> (b /\\ a).\nProof.\n  split. intro. elim H. intros.\n  split. assumption. assumption.\n  intro. elim H. intros. split. \n  assumption. assumption.\nQed.\n\nTheorem ex22: forall a b : Prop,\n               (a \\/ b) <-> (b \\/ a).\nProof.\n  split. intro. elim H. intro. right. assumption.\n  intro. left. assumption. intro. elim H. intro.\n  right. assumption. intro. left. assumption.\nQed.\n\nTheorem ex23: forall a b : Prop,\n               (a <-> b) <-> (b <-> a).\nProof.\n  split. intro. elim H. intros. split.\n  assumption. assumption.\n  intro. elim H. intros. split.\n  assumption. 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/Commutativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7794524261993292}}
{"text": "Require Export Tree_Inf  RelationClasses.\n\nSet Implicit Arguments.\n\nSection LTree_bisimilar_def.\nVariable A:Type.\n\n(* An extensional equality on (LTree A) *)\n\nCoInductive LTree_bisimilar :  LTree A -> LTree A -> Prop :=\n  LTree_bisimilar_leaf : LTree_bisimilar LLeaf LLeaf\n| LTree_bisimilar_bin : forall (a:A) (t1 t'1 t2 t'2 : LTree A),\n                LTree_bisimilar t1 t'1 ->\n                LTree_bisimilar t2 t'2 ->\n                LTree_bisimilar (LBin a t1 t2) (LBin a t'1 t'2).\n\nInstance LTree_bisimilar_refl : Reflexive  LTree_bisimilar.\nProof.\n cofix H; intro a; case a ; constructor; auto.\nQed.\n\nInstance LTree_bisimilar_sym : Symmetric LTree_bisimilar.\nProof.\n cofix H.\n intros x y; case x; case y.\n  - left.\n  -  inversion_clear 1.\n  -  inversion_clear 1.\n  -  inversion_clear 1;  now right. \nQed.\n\nInstance  LTree_bisimilar_trans : Transitive  LTree_bisimilar.\nProof.\n cofix H; intros x y z ; case x; case y.\n - inversion 2; constructor.\n - inversion 1.\n - inversion 1.\n -  inversion_clear 1.\n     case z; inversion_clear 1;  right; now eapply H; eauto.\nQed.\n\nGlobal Instance  bisimilar_equiv : Equivalence LTree_bisimilar.\nProof.\n split;[apply LTree_bisimilar_refl |\n        apply LTree_bisimilar_sym  |\n        apply LTree_bisimilar_trans].\nQed.\n\n Theorem LTree_bisimilar_label : \n   forall (p:path) (t t': LTree A),\n          LTree_bisimilar t t' ->\n          LTree_label t p = LTree_label t' p.\n Proof.\n  simple induction p.\n  intros t t'; case t, t'.\n  - reflexivity.\n  -  inversion_clear 1.\n  -  inversion_clear 1.\n  -  inversion_clear 1; simpl; auto.\n  -  intros a l;case a; intros H t t'; case t, t'.\n    + reflexivity.\n    +  inversion_clear 1.\n    +  inversion_clear 1.\n    +  inversion_clear 1; cbn; repeat  rewrite LTree_label_rw0; auto.\n    +  repeat  rewrite LTree_label_rw1; auto.\n    +  inversion_clear 1.\n    +  inversion_clear 1.\n    +  inversion_clear 1; repeat  rewrite LTree_label_rw1; auto.\n Qed.\n\n\n Theorem label_LTree_bisimilar :  forall t t': LTree A, \n                          (forall p:path, LTree_label t p = LTree_label t' p)->\n                          LTree_bisimilar t t'.\n Proof.\n  cofix.\n  intros t t'; case t; case t'.\n  - left.\n  - intros a l l0 H; discriminate (H nil). \n  - intros a l l0 H; discriminate (H nil). \n  - intros a l l0 a0 t1 t2 H.\n   assert (e : a = a0) by\n        (generalize (H nil); injection 1; congruence).\n   subst a0;  constructor;  apply label_LTree_bisimilar; intro p.\n   +  generalize (H (cons d0 p));repeat rewrite LTree_label_rw0; auto.\n   +  generalize (H (cons d1 p)); repeat rewrite LTree_label_rw1; auto.\n Qed.\n\nEnd LTree_bisimilar_def.\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/LTree_bisimilar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7793834565676893}}
{"text": "Require Arith.\n\n\nInductive F: Set :=\n   | one : F (* 1 *)\n   | n : F -> F (* 1 + f *)\n   | d : F -> F (* 1 / (1 + (1 / f)) *)\n.\n\nFixpoint  fraction (f : F) : nat * nat :=\n  match f with\n  | one => (1,1)\n  | n f' => let (a, b) := fraction f' in (a + b, b)\n  | d f' => let (a, b) := fraction f' in (a, a + b)\n end.\n\n\n\n(** Test:\nCompute  fraction (d (d (n (d (d one))))).    \n\n= (4, 11) : nat*nat\n\n*)\n\n\n(****************************************************************************\n\n bonus proof (for readers of chapter 8) :\n   Let us admit that a/b is irreducible if\n   there exists u, v in Z such that au+bv=1.\n   Then fraction f is irreducible for every f\n\n*****************************************************************************)\n\nRequire Import ZArith.\n\nOpen Scope Z_scope.\nInductive bezout (a b:nat): Prop :=\n mk_bezout :  forall u v : Z,\n              (lt 0 a) -> \n              (lt 0 b) ->\n              (Z_of_nat a) * u +  (Z_of_nat b) * v = 1  ->\n               bezout a b.\n\nLemma b_one : bezout 1 1.\nProof. \n  split with 1 0 ; auto.\nQed.\n\nLemma b_n : forall a b : nat, bezout a b -> bezout (a + b)%nat b.\nProof.\n intros a b H; case H.\n intros u v H0 HA e.\n split with u (v-u).\n -  auto with arith.\n -  auto.\n -  rewrite inj_plus; now  ring_simplify.\nQed.\n \nLemma b_d : forall a b : nat, bezout a b -> bezout a (a + b)%nat.\nProof.\n intros a b H; case H.\n intros u v H0 HA e.\n split with  (u-v) v.\n -  auto.\n - auto with zarith.\n - rewrite inj_plus;  ring_simplify;\n   now  rewrite (Zmult_comm v (Z_of_nat b)).\nQed.\n\nHint Resolve b_one b_d b_n.\n\nInductive simplified : nat*nat -> Prop :=\n  mk_simpl : forall a b : nat, bezout a b -> simplified (a, b).\n\nLemma fractionsimplified  : forall f : F, \n                              simplified (fraction f).\nProof.\n simple induction f ; simpl.\n -  split ; auto.\n -  intro f0; case (fraction f0).  \n    inversion_clear  1;split; auto.\n -  intro f0; case (fraction f0).  \n     inversion_clear  1; split; auto.\nQed.\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/exo_frac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7793704090385191}}
{"text": "Check (fun x : nat => x).\nCheck (fun x : True => x).\nCheck I.\nCheck (fun _ : False => I).\nCheck (fun x : False => x).\nInductive unit : Set := | tt.\nCheck unit.\nCheck tt.\nTheorem unit_singleton : forall x : unit, x = tt.\nProof. induction x. auto. Qed.\nCheck unit_ind.\nInductive test : Set := t1 | t2.\nCheck test_ind.\nInductive Empty_set : Set := .\nTheorem the_sky_is_falling : forall x : Empty_set, 2+2=5.\nProof. intros. inversion x. Qed.\nTheorem false_ : forall P Q : Prop, P -> ~P -> Q.\nProof. intros. destruct H0. apply H. Qed.\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_app : forall ls1 ls2:nat_list, nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2).\nProof. induction ls1; auto. intros.\n  simpl. f_equal. auto. Qed.\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 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 a b c, a+b+c=a+(b+c).\nProof. induction a; auto. intros. repeat rewrite plus_Sn_m. auto. Qed.\n\nTheorem nsize_nsplice : forall tr1 tr2:nat_btree, nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1).\nProof. induction tr1; auto. intros. simpl. erewrite IHtr1_1. rewrite plus_assoc. reflexivity. Qed.\nCheck nat_btree_ind.\nPrint nsize_nsplice.\n\nInductive list (T:Set) : Set :=\n| Nil:list T\n| Cons:T->list T->list T.\n\nImplicit Arguments Nil [T].\n\nFixpoint length (T:Set) (ls:list T) :nat:=\n  match ls with\n  | Nil => O\n  | Cons _ _ ls' => S (length T ls')\n  end.\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\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\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\n\nTheorem elength_eapp : forall el1 el2:even_list,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).", "meta": {"author": "Yumeri", "repo": "coq", "sha": "615d40c73a9b4d7e96568d16d04bb661d5b869f6", "save_path": "github-repos/coq/Yumeri-coq", "path": "github-repos/coq/Yumeri-coq/coq-615d40c73a9b4d7e96568d16d04bb661d5b869f6/cpdt/2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7792761205893043}}
{"text": "Definition and_bool (b1 b2 : bool) : bool :=\n  match b1 , b2 with\n    | true ,  b2 => b2\n    | false , b2 => false\n  end.\n\nLemma and_true_left : \n  forall b, and_bool true b = b.\nProof.\n  induction b; auto.\nQed.\n\nLemma and_false_left : \n  forall b, and_bool false b = false.\nProof.\n  auto.\nQed.\n\nLemma and_com : \n  forall b b', and_bool b b' = and_bool b' b.\nProof.\n  induction b; induction b'; auto.\nQed.\n\nLemma and_assocc : \n  forall b1 b2 b3, and_bool b1 (and_bool b2 b3) = and_bool (and_bool b1 b2) b3.\nProof.\n  induction b1; induction b2; induction b3; auto.\nQed.\n\nLemma zero_identity_add_right : \n  forall n, n + 0 = n.\nProof.\n  induction n; simpl; try (rewrite IHn);reflexivity.\nQed.\n\nLemma add_inc : \n  forall m n, S (m + n) = m + S n.\nProof.\n  induction m; intro n; simpl; try (rewrite IHm); reflexivity.\nQed.\n\nLemma add_commut : \n  forall n m, n + m = m + n.\nProof.\n  induction n; intro m; simpl; \n  repeat ((rewrite IHn) || (apply add_inc)); \n  try (rewrite zero_identity_add_right); reflexivity.\nQed.\n\nLemma add_associative : \n  forall n m p, n + (m + p) = (n + m) + p.\nProof.\n  induction n; intros m p; simpl; try (rewrite IHn); reflexivity.\nQed.\n\nLemma one_identity_times_right : \n  forall n, n * 1 = n.\nProof.\n  induction n; simpl; try rewrite IHn; reflexivity.\nQed.\n\nLemma one_identity_times_left : \n  forall n, 1 * n = n.\nProof.\n  induction n; simpl; \n  try rewrite IHn; \n  try rewrite zero_identity_add_right; \n  reflexivity.\nQed.\n\nLemma add_mult_1 : \n  forall n m p, (n + m) * p = n * p + m * p.\nProof.\n  induction n; intros m p; simpl; \n  try rewrite IHn; \n  try apply add_associative; \n  auto.\nQed.\n\nLemma times_associative : \n  forall n m p, (n * m) * p = n * (m * p).\nProof.\n  induction n; intros m p; simpl;\n  try rewrite <- IHn; \n  try apply add_mult_1; \n  reflexivity.\nQed.\n\nLemma add_1 : \n  forall n m p, n + (m + p) = m + (n + p).\nProof.\n  induction n; simpl; intros m p;\n  try rewrite IHn;\n  try apply add_inc;\n  auto.\nQed.\n\nLemma times_1 : \n  forall n m, n + n * m = n * S m.\nProof.\n  induction n; simpl; intro m; \n  try rewrite <- IHn;\n  try rewrite <- add_1; auto.\nQed.\n\nLemma times_commut : \n  forall n m, n * m = m * n.\nProof.\n  induction n; intros m; simpl; \n  try rewrite IHn; \n  try apply times_1;\n  auto.\nQed.\n\nFixpoint not_bool (b : bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nLemma not_not_b :\n  forall b, not_bool (not_bool b) = b.\nProof.\n  intro b ;destruct b;auto.\nQed.\n\nFixpoint even_bool (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S n => not_bool (even_bool n)\n  end.\n\nLemma even_add_n :\n  forall n, even_bool (n + n) = true.\nProof.\n  induction n;\n  simpl;\n  try rewrite add_commut; \n  simpl;\n  try rewrite IHn;\n  auto.\nQed.\n\nFixpoint odd_bool (n : nat) : bool :=\n  match n with\n    | 0 => false\n    | S n => not_bool (odd_bool n)\n  end.\n\nLemma odd_add_n_n :\n  forall n, odd_bool (n + n) = false.\nProof.\n  induction n; simpl; auto;\n  try rewrite add_commut; simpl;\n  try rewrite IHn; auto.\nQed.\n\nLemma odd_add_n :\n  forall n, odd_bool (n + S n) = true.\nProof.\n  induction n;\n  simpl;\n  try rewrite add_commut;\n  simpl;\n  try rewrite odd_add_n_n;\n  auto.\nQed.\n\nLemma even_SS : \n  forall n, even_bool n = even_bool (S (S n)).\nProof.\n  induction n; simpl; \n  try rewrite not_not_b; auto.\nQed.\n\nLemma odd_SS :\n  forall n, odd_bool n = odd_bool (S (S n)).\nProof.\n  induction n; simpl; \n  try rewrite not_not_b; auto.\nQed.\n\nLemma even_bool_S:\n  forall n, even_bool n = not_bool (even_bool (S n)).\nProof.\n  induction n; simpl;\n  try rewrite not_not_b; auto.\nQed.\n\nRequire Import List.\n\nLemma repeat_length {A : Type} : \n  forall (n : nat)(x : A), length (repeat x n) = n.\nProof.\n  induction n; intros x; simpl; \n  try rewrite IHn;\n  reflexivity.\nQed.\n\nLemma app_nil_right {A : Type} : \n  forall (xs : list A), xs ++ nil = xs.\nProof.\n  induction xs; simpl;\n  try rewrite IHxs;\n  reflexivity.\nQed.\n\nLemma app_assoc {A : Type} : \n  forall (xs ys zs : list A), xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\nProof.\n  induction xs; intros ys zs; simpl;\n  try rewrite IHxs;\n  reflexivity.\nQed.\n\nLemma map_app {A B : Type}{f : A -> B}\n  : forall xs ys, map f (xs ++ ys) = map f xs ++ map f ys.\nProof.\n  induction xs; intros; simpl;\n  try rewrite IHxs;\n  reflexivity.\nQed.\n\nLemma reverse_app {A : Type}\n  : forall (xs ys : list A), rev (xs ++ ys) = rev ys ++ rev xs.\nProof.\n  induction xs; intros; simpl;\n  try rewrite app_nil_right;\n  try rewrite IHxs;\n  try rewrite app_assoc;\n  reflexivity.\nQed.\n\nLemma reverse_inv {A : Type}\n  : forall (xs : list A), rev (rev xs) = xs.\nProof.\n  induction xs; simpl;\n  try rewrite reverse_app;\n  simpl;\n  try rewrite IHxs;\n  auto.\nQed.\n\nInductive even : nat -> Prop :=\n| ev_zero : even 0\n| ev_ss   : forall n, even n -> even (S (S n)).\n\nDefinition double (n : nat) := 2 * n.\n\nLemma double_2 :\n  forall n, double n = n + n.\nProof.\n  unfold double;\n  induction n;\n  simpl;\n  try rewrite zero_identity_add_right;\n  auto.\nQed.\n\nLemma double_even : \n  forall n, even (double n).\nProof.\n  unfold double; induction n; simpl; \n  try rewrite IHn; \n  try apply ev_zero;\n  try rewrite zero_identity_add_right;\n  try rewrite add_commut;\n  simpl;\n  try rewrite <- double_2;\n  unfold double;\n  try apply ev_ss;\n  auto.\nQed.\n\nLemma le_refl : \n  forall n, n <= n.\nProof.\n  apply le_n.\nQed.\n\nLemma le_cong_S : \n  forall n m, n <= m -> S n <= S m.\nProof.\n  intros;\n  induction H;\n  try apply le_refl;\n  try apply le_S;\n  auto.\nQed.\n\nLemma le_S_cong : \n  forall n m, S n <= S m -> n <= m.\nProof.\n  intros;\n  induction m;\n  inversion H;\n  try apply le_refl;\n  try inversion H1;\n  auto.\nQed.\n\nLemma le_trans : \n  forall n m p, n <= m -> m <= p -> n <= p.\nProof.\n  induction n; intros; try rewrite H; auto.\nQed.\n\nLemma le_zero_antisym_left :\n  forall n, 0 <= n -> n <= 0 -> 0 = n.\nProof.\n  induction n; intros; auto.\n  inversion H0.\nQed.\n\nLemma le_antisym : \n  forall n m, n <= m -> m <= n -> n = m.\nProof.\n  induction n; intros; \n  try apply le_zero_antisym_left;\n  inversion H;\n  subst; auto; subst;\n  apply f_equal;\n  apply IHn;\n  apply le_S_cong;\n  auto.\nQed.\n\nImport ListNotations.\n\nInductive Sorted : list nat -> Prop :=\n  | sorted_nil : Sorted []\n  | sorted_cons1 a : Sorted [a]\n  | sorted_consn a b l : Sorted (b :: l) -> a <= b -> Sorted (a :: b :: l) .\n\nExample test_sorted1 : Sorted [].\n  Proof.\n    apply sorted_nil.\n  Qed.\n\nExample test_sorted2 : Sorted [10].\n  Proof.\n    apply sorted_cons1.\n  Qed.\n\nExample test_sorted3 : Sorted [1 ; 3 ; 5 ].\nProof.\n  repeat ((apply sorted_consn)||(apply sorted_cons1)||(apply le_n)||(apply le_S)).\nQed.\n\nReserved Notation \"x '<<=' y\" (at level 40, no associativity).\n\nInductive le_alt : nat -> nat -> Prop :=\n| le_alt_zero : forall n, 0 <<= n\n| le_alt_succ : forall n m, n <<= m -> S n <<= S m\nwhere \"x '<<=' y\" := (le_alt x y).\n\nLemma le_alt_refl : \n  forall n, n <<= n.\nProof.\n  induction n; \n  try apply le_alt_zero;\n  try apply le_alt_succ;\n  try apply IHn.\nQed.\n\nLemma le_alt_trans\n  : forall n m p, n <<= m -> m <<= p -> n <<= p.\nProof.\n  induction n; intros; try apply le_alt_zero;\n  inversion H0;\n  subst;\n  inversion H;\n  subst;\n  apply le_alt_succ;\n  apply (IHn n0 m0);\n  inversion H;\n  auto.\nQed.\n\nLemma le_alt_antisym : \n  forall n m, n <<= m -> m <<= n -> n = m.\nProof.\n  induction n; intros.\n  inversion H0; auto.\n  inversion H;\n  subst;\n  apply f_equal;\n  apply (IHn m0);\n  inversion H0;\n  auto.\nQed.\n\nLemma le_zero :\n  forall n, 0 <= n.\nProof.\n  induction n ; constructor ; try assumption.\nQed.\n\nLemma le_alt_equiv_le : \n  forall n m, n <<= m <-> n <= m.\nProof.\n  induction n ; intros ; split ; intros; try apply le_zero; try constructor;\n  destruct m;\n  inversion H;\n  subst;\n  try apply le_alt_refl;\n  try apply le_cong_S;\n  try apply IHn in H2;\n  try apply le_S_cong in H;\n  try apply IHn in H;\n  try constructor;\n  auto.\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", "meta": {"author": "Baumgratz", "repo": "Coq_Learning", "sha": "c78730a96bf744496cb7bd16e2edf9da61ab4eba", "save_path": "github-repos/coq/Baumgratz-Coq_Learning", "path": "github-repos/coq/Baumgratz-Coq_Learning/Coq_Learning-c78730a96bf744496cb7bd16e2edf9da61ab4eba/tipoIndAuto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7791600649564822}}
{"text": "(** * pair: encoding pairs of ordinals as ordinals *)\n(** more precisely, [ord n * ord m] into [ord (n*m)] *)\n\nRequire Import Psatz PeanoNat Compare_dec Euclid.\nRequire Import ordinal.\n\nSet Asymmetric Patterns.\nSet Implicit Arguments.\nLocal Open Scope ltb_scope.\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. lia. trivial. \n   split. discriminate. inversion 1. \n   rewrite IHx. lia. \nQed.\n\n(** auxiliary lemma *)\nLemma mk_lt n m x y: x<n -> y<m -> y*n+x < n*m. \nProof. setoid_rewrite ltb_lt. nia. Qed.\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). lia. 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. abstract nia.\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 Nat.mul_comm, (Nat.mul_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 behave 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  nia. 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  nia. 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": "damien-pous", "repo": "relation-algebra", "sha": "13b99896782e449c7ca3910e48e18427517c8135", "save_path": "github-repos/coq/damien-pous-relation-algebra", "path": "github-repos/coq/damien-pous-relation-algebra/relation-algebra-13b99896782e449c7ca3910e48e18427517c8135/theories/pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7791600448386231}}
{"text": "Require Import Lia.\nRequire Import List.\n\n(** * Basic lemmas and functions *)\n\n(** ** Empty lists and membership*)\nDefinition isNil {A : Type} (l : list A) : Prop :=\n  match l with\n  | nil => True\n  | _ => False\n  end.\n\nProposition isNil_no_member\n            {A : Type}\n            (l : list A)\n            (Hl : isNil l)\n            (x : A)\n  : ~(In x l).\nProof.\n  induction l ; cbn in *.\n  - exact (fun z => z).\n  - contradiction.\nQed.\n  \n(** ** Lemma about addition *)\nProposition plus_ge\n            {n1 n2 m1 m2 : nat}\n            (p : n1 >= n2)\n            (q : m1 >= m2)\n  : n1 + m1 >= n2 + m2.\nProof.\n  lia.\nQed.\n\nProposition mult_ge\n            {k n m : nat}\n            (p : n >= m)\n  : k * n >= k * m.\nProof.\n  nia.\nQed.\n\n(** ** Basics functions *)\n\nArguments id {_} _/.\n\nDefinition comp\n           {X Y Z : Type}\n           (g : Y -> Z)\n           (f : X -> Y)\n           (x : X)\n  : Z\n  := g(f x).\n\nNotation \"g 'o' f\" := (comp g f) (at level 40, left associativity).\nArguments comp {_ _ _} _ _ _/.\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/Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.779140876393123}}
{"text": "Module Play.\n\n  Inductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\n  Fixpoint plus (a b : nat) :=\n    match a, b with\n      | O, n => n\n      | (S m) , n => plus m (S n)\n    end.\n\n  Theorem plus_O_n : forall n : nat, plus O n = n.\n  Proof.\n    intros n.\n    reflexivity.\n  Qed.\n  Theorem plus_n_O : forall n : nat, plus n O = n.\n  Proof.\n    intros n.\n    simpl.\n  Abort.\n  Theorem plus_1_l : forall n : nat, plus (S O) n = S n.\n  Proof.\n    intros n.\n    simpl.\n    reflexivity.\n  Qed.\n  Theorem plus_id_example : forall n m :nat,\n                              n = m ->\n                              plus n n = plus m m.\n  Proof.\n    intros m n.\n    intros H.\n    rewrite -> H.\n    reflexivity.\n  Qed.\n  Theorem plus_id_exercise :\n    forall n m o : nat,\n      n = m -> m = o -> plus n m = plus m o.\n  Proof.                               \n    intros n m o.                                              \n    intros H1.\n    intros H2.\n    rewrite -> H1.\n    rewrite <- H2.\n    reflexivity.\n  Qed.\n\n  Fixpoint mult (n m : nat) : nat :=\n    match n, m with\n      | O, _ => O\n      | (S n'), m => plus m (mult n' m)\n    end.\n  Theorem mult_O_plus :\n    forall n m : nat,\n      (mult (plus O n) m) = mult n m.\n  Proof.\n    intros n m.\n    rewrite <- plus_O_n.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem mult_S_1 :\n    forall n m : nat,\n      m = S n ->\n      mult m (plus (S O) n) = mult m m.\n  Proof.\n    intros n m.\n    intros H1.\n    simpl.\n    rewrite <- H1.\n    reflexivity.\n  Qed.\n\n  Inductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n  Fixpoint beq_nat (a b : nat) : bool :=\n    match a, b with\n      | O, O => true\n      | O, S n => false\n      | S n , O => false\n      | S n , S m => beq_nat n m\n    end.\n\n  Theorem plus_1_neq_0_firsttry :\n    forall n : nat,\n      beq_nat (plus n (S O)) O = false.\n  Proof.\n    intros n.\n    destruct n as [| n' ].\n    reflexivity.\n\n    simpl.\n    \n  Abort.\n\n  Theorem plus_exch:\n    forall n m,\n      plus n (S m) = plus (S n) m.\n\n  Proof.\n    intros n m.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem plus_1_neq_0_firsttry :\n    forall n : nat,\n      beq_nat (plus n (S O)) O = false.\n\n  Proof.\n    intros n.\n    rewrite -> plus_exch.\n    destruct n as [O | n'].\n    reflexivity.\n  Abort.\n\n  Theorem identif_fn_applied_twice :\n    forall (f : bool -> bool),\n      (forall (x : bool), f x = x) ->\n      forall (b : bool), f (f b) = b.\n  Proof.\n    intros f.\n    intros x.\n    intros b.\n    rewrite -> x.\n    rewrite -> x.\n    reflexivity.\n  Qed.\n\n  Theorem pl0:\n    forall (x : nat),\n      plus (S O) x = S x.\n  Proof.\n    reflexivity.\n  Qed.\n (*   Theorem pl00:\n      forall (m n :nat),\n       S m = S n -> m = n.\n    Proof.\n      intros m n.\n      intros H.\n      induction m as [| m'].\n      reflexivity.*)\n      Theorem pl1:\n    forall (n: nat),\n    forall (a b : nat),\n      plus n (plus a b) = plus (plus n a) b.\n    intros n.\n    induction n as [| n'].\n    reflexivity.\n    simpl.\n    rewrite <- IHn'.\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/08192016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.779112166026637}}
{"text": "Require Import ZArith.\nRequire Import Znumtheory.\nRequire Import Unicode.Utf8.\nOpen Scope Z_scope.\n\nFixpoint sumdigits n (f : nat -> Z) :=\n  match n with\n  | O => f O\n  | S n => f (S n) + sumdigits n f\n  end.\n\nFixpoint number n (f : nat -> Z) :=\n  match n with\n  | O => f O\n  | S n => f (S n) + 10 * number n f\n  end.\n\nTheorem div3 : ∀ n d,\n  (number n d) mod 3 = (sumdigits n d) mod 3.\nProof.\n  intros n d; induction n.\n    auto.\n    \n    change ((d (S n) + 10 * number n d) mod 3 = (d (S n) + sumdigits n d) mod 3).\n    rewrite Zplus_mod, Zmult_mod, IHn.\n    remember (sumdigits n d) as SU.\n    replace (10 mod 3) with 1 by trivial.\n    rewrite Zmult_1_l, Zmod_mod.\n    rewrite <- Zplus_mod.\n    reflexivity.\nQed.\n\nTheorem div9 : ∀ n d,\n  (number n d) mod 9 = (sumdigits n d) mod 9.\nProof.\n  intros n d; induction n.\n    auto.\n\n    change ((d (S n) + 10 * number n d) mod 9 = (d (S n) + sumdigits n d) mod 9).\n    rewrite Zplus_mod, Zmult_mod, IHn.\n    remember (sumdigits n d) as SU.\n    replace (10 mod 9) with 1 by trivial.\n    rewrite Zmult_1_l, Zmod_mod.\n    rewrite <- Zplus_mod.\n    reflexivity.\nQed.\n\n\n", "meta": {"author": "Whu-Lambda", "repo": "Lambda-Cube", "sha": "6845929d9f816a350e65b33078657b14ae940693", "save_path": "github-repos/coq/Whu-Lambda-Lambda-Cube", "path": "github-repos/coq/Whu-Lambda-Lambda-Cube/Lambda-Cube-6845929d9f816a350e65b33078657b14ae940693/Coq_ex/Coq_proof/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7791121545597492}}
{"text": "(** * 6.887 Formal Reasoning About Programs, Spring 2016 - Pset 0 *)\n\nRequire Import Frap.\n\n(* Authors: Peng Wang (wangpeng@csail.mit.edu), Adam Chlipala (adamc@csail.mit.edu) *)\n\n(* This lightweight pset is meant to force you to get started installing Coq\n * and finding bugs in our homework-submission system!  *ahem*  We meant\n * \"learning to use our homework-submission system.\" ;-) *)\n\n(* The Coq standard library contains a definition of a type of lists, a common\n * concept in functional programming.  More mainstream languages might call such\n * a thing an \"immutable, singly linked list.\"\n *\n * Here's the type definition, which is effectively included automatically,\n * by default, in any Coq file.\n * <<\n     Inductive list A :=\n       nil\n     | cons (hd : A) (tl : list A).\n   >>\n *\n * [A] is a type parameter.  (Note that, following Coq's code-documentation\n * conventions, we put square brackets around bits of code within comments,\n * and we use double-angle brackets to set off larger code excerpts.)\n * This list type is a lot like the syntax-tree types we saw in class;\n * the only new wrinkle is the polymorphic type parameter [A], which is\n * related to *generics* in OO languages.\n *\n * We can also define some useful operations on lists.\n * A basic one is length.\n * <<\n    Fixpoint length {A} (xs : list A) : nat :=\n      match xs with\n        | nil => 0\n        | cons _ xs' => 1 + length xs'\n      end.\n   >>\n * Note the use of the natural-number type [nat].\n * The curly braces in type argument [{A}] tell Coq to infer this type argument\n * when [length] is called, which by the way is the default behavior for all\n * type arguments in Haskell and OCaml.\n * Another function is concatenation of lists, defined using an infix operator\n * [::] for [cons].\n * <<\n    Fixpoint app {A} (l : list A) (m : list A) : list A :=\n      match l with\n       | nil => m\n       | a :: l1 => a :: app l1 m\n      end.\n   >>\n * Finally, we'll also work with list reversal, using [++] as an infix operator\n * for [app].\n * <<\n    Fixpoint rev {A} (l : list A) : list A :=\n      match l with\n        | nil => nil\n        | x :: l' => rev l' ++ (x :: nil)\n      end.\n   >>\n *)\n\n(* Here's an example proof with lists, using a list shorthand notation. *)\nTheorem an_important_theorem : length [1; 2; 3] = 3.\nProof.\n  simplify.\n  equality.\nQed.\n\n\n(* OK, enough warmup.  Your job is to define a module implementing the following\n * signature.  We ask you to implement a file Pset0.v, such that it can\n * be checked against this signature by successfully processing a third\n * file with a command like so:\n * <<\n    Require Pset0Sig Pset0.\n\n    Module M : Pset0Sig.S := Pset0.\n   >>\n * You'll need to build your module first.  Here's the UNIX-style approach\n * that we'll use for grading: Put this file Pset0Sig.v, your solution\n * Pset0.v, and an additional file Pset0Check.v in some directory.\n * The last file should include the two lines of code quoted above.\n * Then create a _CoqProject file in the same directory, containing:\n * <<\n-R ../../frap Frap\nPset0Sig.v\nPset0.v\nPset0Check.v\n   >>\n * Replace the `../../frap' with the path to the unpacked book source.\n * Then create a Makefile with this content:\n * <<\ncoq: Makefile.coq\n\t$(MAKE) -f Makefile.coq\n\nMakefile.coq: Makefile _CoqProject\n\tcoq_makefile -f _CoqProject -o Makefile.coq\n   >>\n * If your Coq installation is set up properly, simply running `make' should\n * now be enough to build everything and check that it works.\n * Note also that you will need to run `make coq' in the directory of the book\n * library code, *before* starting to work on your solution, which needs\n * to import compiled library code from the book.\n*)\n\n(* Finally, here's the actual signature to implement. *)\nModule Type S.\n  Axiom another_important_theorem : length [1; 2; 3] = 1 + length [4; 5].\n\n  Axiom length_concat : forall A (xs ys : list A), length (xs ++ ys) = length xs + length ys.\n  (* Hint: want induction for this one! *)\n\n  Axiom length_rev : forall A (xs : list A), length xs = length (rev xs).\n  (* Hint: appeal to [length_concat] somewhere! *)\nEnd S.\n\n(* Example template for the Pset0.v file you will create:\n * <<\nRequire Import Frap.\n\nTheorem another_important_theorem : length [1; 2; 3] = 1 + length [4; 5].\nProof.\n  ...\nQed.\n\nTheorem length_concat : forall A (xs ys : list A), length (xs ++ ys) = length xs + length ys.\nProof.\n  ...\nQed.\n\nTheorem length_rev : forall A (xs : list A), length xs = length (rev xs).\nProof.\n  ...\nQed.\n   >> *)\n", "meta": {"author": "wangpengmit", "repo": "6887psets", "sha": "36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d", "save_path": "github-repos/coq/wangpengmit-6887psets", "path": "github-repos/coq/wangpengmit-6887psets/6887psets-36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d/pset0/Pset0Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8947894639983208, "lm_q1q2_score": 0.7790012721701789}}
{"text": "(** * Lists: Working with Structured Data *)\n\nRequire Export Induction.\n\nModule NatList.\n\n(* ###################################################### *)\n(** * Pairs of Numbers *)\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 (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n(** **** 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. Qed.\n\n(** * Lists of Numbers *)\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) ..).\n\n(** *** Repeat *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(** *** Length *)\n\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** *** Append *)\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 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\n(** **** Exercise: 2 stars (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | 0 :: t => nonzeros t\n    | h :: t => h :: nonzeros t\n  end.\n\nExample test_nonzeros:            nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t =>  match oddb h with\n                   | true  => h :: oddmembers t\n                   | false => oddmembers t\n                 end\n  end.\n\nExample test_oddmembers:            oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  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(** **** Exercise: 3 stars, advanced (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n    | nil => l2\n    | h :: s => match l2 with\n                  | nil => l1\n                  | x :: xs => h :: x :: alternate s xs\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(** ** Bags via Lists *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars (bag_functions) *)\n(** Complete the following definitions for the functions\n    [count], [sum], [add], and [member] for bags. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n    | nil => 0\n    | x :: xs => match (beq_nat x v) with\n                  | true  => S (count v xs)\n                  | false => count v xs\n                 end\n  end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\nProof. reflexivity. Qed.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\nProof. reflexivity. Qed.\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n    all the elements of [a] and of [b].  (Mathematicians usually\n    define [union] on multisets a little bit differently, which\n    is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := app.\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  match s with\n    | nil => [v]\n    | x :: xs => v :: s\n  end.\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  ble_nat 1 (count v s).\n\nExample test_member1:             member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2:             member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n    | nil => nil\n    | x :: xs => match beq_nat v x with\n                   | true  => xs\n                   | false => x :: remove_one v xs\n                 end\nend.\n\nExample test_remove_one1:         count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2:         count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one3:         count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. 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  match s with\n    | nil => nil\n    | x :: xs => match beq_nat v x with\n                   | true  => remove_all v xs\n                   | false => x :: remove_all v xs\n                 end\nend.\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 member x s2 with\n                   | true  => subset xs (remove_one x s2)\n                   | false => false\n                 end\n  end.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (bag_theorem) *)\n(** Write down an interesting theorem about bags involving the\n    functions [count] and [add], and prove it.  Note that, since this\n    problem is somewhat open-ended, it's possible that you may come up\n    with a theorem which is true, but whose proof requires techniques\n    you haven't learned yet.  Feel free to ask for help if you get\n    stuck! *)\n(* TODO *)\n(* Fact a_great_theorem : forall a b : nat, forall s : bag, *)\n(*   beq_nat a b = true -> count b (add a s) = 1 + count b s. *)\n(* Proof. Abort. *)\n(** [] *)\n\n(** * Reasoning About Lists *)\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  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    reflexivity.  Qed.\n\n(** ** Micro-Sermon *)\n\n(** ** Induction on Lists *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** *** Informal version *)\n\n(** *** Another example *)\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(** *** Reversing a list *)\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\n(** *** Proofs about reverse *)\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\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| x xs].\n  Case \"l = []\". reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHxs. reflexivity. Qed.\n\nTheorem rev_snoc : forall (v : nat) (l : natlist),\n  rev (snoc l v) = v :: rev l.\nProof.\n  intros v l. induction l as [| x xs].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHxs. reflexivity. Qed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| x xs].\n  Case \"l = []\". reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> rev_snoc. rewrite -> IHxs. reflexivity. Qed.\n\n(* ref: https://github.com/etosch/software_foundations/blob/master/lesson3_Lists.v *)\n\n(** There is a short solution to the next exercise.  If you find\n    yourself getting tangled up, step back and try to look for a\n    simpler way. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  replace ((l1 ++ l2) ++ l3) with (l1 ++ l2 ++ l3).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc. reflexivity.\n  Case \"replace\".\n    rewrite -> app_assoc. reflexivity. Qed.\n\nTheorem snoc_append : forall (l : natlist) (n : nat),\n  snoc l n = l ++ [n].\nProof.\n  intros l n. induction l as [| x xs].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> IHxs. reflexivity. Qed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2. induction l1 as [| x xs].\n  Case \"l1 = []\".\n    simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHxs.\n    rewrite -> snoc_append. rewrite -> snoc_append.\n    rewrite -> app_assoc. reflexivity. Qed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_nil : forall l : natlist,\n  nonzeros [] = [].\nProof.\n  reflexivity. Qed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| x xs].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l1 = cons\".\n    destruct x as [| x'].\n    SCase \"x = 0\".\n      simpl. rewrite -> IHxs. reflexivity.\n    SCase \"x > 0\".\n      simpl. rewrite -> IHxs. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n    | nil => match l2 with\n               | nil => true\n               | _   => false\n             end\n    | h :: t => match l2 with\n               | nil => false\n               | h2 :: t2 => match beq_nat h h2 with\n                               | false => false\n                               | true  => beq_natlist t t2\n                             end\n                end\n  end.\n\nExample test_beq_natlist1 :   (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nLemma beq_n_n : forall n : nat,\n  beq_nat n n = true.\nProof.\n  intros. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n > 0\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l : natlist,\n  true = beq_natlist l l.\nProof.\n  intro l. induction l as [| x xs].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> beq_n_n.\n    rewrite <- IHxs. reflexivity.\nQed.\n\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars (list_design) *)\n(** Design exercise:\n     - Write down a non-trivial theorem involving [cons]\n       ([::]), [snoc], and [app] ([++]).\n     - Prove it. *)\n\n(* TODO *)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_proofs) *)\n(** Here are a couple of little theorems to prove about your\n    definitions about bags earlier in the file. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  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 \"s = []\".\n    reflexivity.\n  Case \"s = cons\".\n    destruct h as [| h']. simpl.\n    SCase \"h = 0\".\n      rewrite -> ble_n_Sn. reflexivity.\n    SCase \"h > 0\".\n    simpl. rewrite -> IHt. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem about bags involving the\n    functions [count] and [sum], and prove it.*)\n\n(* TODO *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\nTheorem rev_injective: forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  rewrite <- rev_involutive.\n  rewrite <- H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\n(** * Options *)\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 O with\n               | true => Some a\n               | false => index (pred n) l'\n               end\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\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n   have to pass a default element for the [nil] case.  *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n    | nil => None\n    | h :: t => Some h\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  intros l d. destruct l as [| h t].\n  reflexivity.\n  reflexivity.\nQed.\n\n(** * Dictionaries *)\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) : natoption :=\n  match d with\n  | empty         => None\n  | record k v d' => if (beq_nat key k)\n                       then (Some v)\n                       else (find key d')\n  end.\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros d k v.\n  simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),\n  beq_nat m n = false -> find m d = find m (insert n o d).\nProof.\n  intros d m n o H.\n  simpl. rewrite -> H. reflexivity.\nQed.\n\nEnd Dictionary.\n\nEnd NatList.\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_Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8947894717137996, "lm_q1q2_score": 0.7790012608619343}}
{"text": "Set Implicit Arguments.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Lists.List.\nRequire Import Coq.omega.Omega.\n\nSection Defs.\n  Variable A:Type.\n\n  (** [MapsTo] is the last index of [x]. *)\n\n  Inductive MapsTo (x:A) : nat -> list A -> Prop :=\n  | maps_to_eq:\n    forall l,\n    MapsTo x (length l) (x::l)\n  | maps_to_cons:\n    forall l y n,\n    x <> y ->\n    MapsTo x n l ->\n    MapsTo x n (y :: l).\n\n  (** [IndexOf] assigns an element to an index with respect to a given list. *)\n\n  Inductive IndexOf (x:A) : nat -> list A -> Prop :=\n  | index_of_eq:\n    forall l,\n    IndexOf x (length l) (x :: l)\n  | index_of_cons:\n    forall y n l,\n    IndexOf x n l ->\n    IndexOf x n (y :: l).\n\n  (** Checks if a number is an index of the given list,\n      which is defined whenever there is an element [x] with an\n      index of [n]. *)\n\n  Inductive Index (n:nat) (l:list A) : Prop :=\n  | index_def:\n    forall x,\n    IndexOf x n l ->\n    Index n l.\n\n  Lemma index_of_to_in:\n    forall x n l,\n    IndexOf x n l ->\n    In x l.\n  Proof.\n    intros.\n    induction l. {\n      inversion H.\n    }\n    inversion H; subst.\n    - auto using in_eq.\n    - auto using in_cons.\n  Qed.\n\n  Lemma index_of_fun_1:\n    forall l x n n',\n    NoDup l ->\n    IndexOf x n l ->\n    IndexOf x n' l ->\n    n' = n.\n  Proof.\n    intros.\n    induction l. {\n      inversion H0.\n    }\n    inversion H; subst; clear H.\n    inversion H0; subst; clear H0.\n    - inversion H1; subst; clear H1.\n      + trivial.\n      + contradiction H4; eauto using index_of_to_in.\n    - inversion H1; subst; clear H1.\n      + contradiction H4; eauto using index_of_to_in.\n      + eauto.\n  Qed.\n\n  Lemma index_of_lt:\n    forall x n l,\n    IndexOf x n l ->\n    n < length l.\n  Proof.\n    intros.\n    induction l. {\n      inversion H.\n    }\n    inversion H; subst.\n    - auto.\n    - simpl.\n      assert (n < length l) by eauto.\n      eauto.\n  Qed.\n\n  Lemma index_cons:\n    forall n l x,\n    Index n l ->\n    Index n (x::l).\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    eauto using index_def, index_of_cons.\n  Qed.\n\n  Lemma lt_to_index:\n    forall n l,\n    n < length l ->\n    Index n l.\n  Proof.\n    induction l; intros; simpl in *. {\n      inversion H.\n    }\n    inversion H; subst; clear H.\n    - eauto using index_def, index_of_eq.\n    - auto using index_cons with *.\n  Qed.\n\n  Lemma index_lt:\n    forall n l,\n    Index n l ->\n    n < length l.\n  Proof.\n    intros.\n    inversion H.\n    eauto using index_of_lt.\n  Qed.\n\n  Lemma index_iff_length:\n    forall n l,\n    Index n l <-> n < length l.\n  Proof.\n    split; auto using index_lt, lt_to_index.\n  Qed.\n\n  Lemma in_to_index_of:\n    forall l x,\n    In x l ->\n    exists n, n < length l /\\ IndexOf x n l.\n  Proof.\n    induction l; intros. {\n      inversion H.\n    }\n    destruct H.\n    - subst.\n      exists (length l).\n      simpl.\n      eauto using index_of_eq.\n    - apply IHl in H.\n      destruct H as (n, (?,?)).\n      exists n.\n      simpl.\n      eauto using index_of_cons.\n  Qed.\n\n  Lemma index_of_bij:\n    forall l x x' n,\n    NoDup l ->\n    IndexOf x n l ->\n    IndexOf x' n l ->\n    x' = x.\n  Proof.\n    intros.\n    induction l. {\n      inversion H0.\n    }\n    inversion H; clear H; subst.\n    inversion H0; subst; clear H0.\n    - inversion H1; subst; clear H1.\n      + trivial.\n      + assert (length l < length l). {\n          eauto using index_of_lt.\n        }\n        omega.\n    - inversion H1; subst; clear H1.\n      + assert (length l < length l). {\n          eauto using index_of_lt.\n        }\n        omega.\n      + eauto.\n  Qed.\n\n  Lemma index_of_neq:\n    forall l x y n n',\n    NoDup l ->\n    IndexOf x n l ->\n    IndexOf y n' l ->\n    n <> n' ->\n    x <> y.\n  Proof.\n    intros.\n    induction l. {\n      inversion H0.\n    }\n    inversion H; clear H; subst.\n    inversion H0; subst; clear H0.\n    - inversion H1; subst; clear H1.\n      + omega.\n      + unfold not; intros; subst.\n        contradiction H5.\n        eauto using index_of_to_in.\n    - inversion H1; subst; clear H1.\n      + unfold not; intros; subst.\n        contradiction H5.\n        eauto using index_of_to_in.\n      + eauto.\n  Qed.\n\n  Inductive Lt (l:list A) (x:A) (y:A) : Prop :=\n  | lt_def:\n    forall xn yn,\n    IndexOf x xn l ->\n    IndexOf y yn l ->\n    xn < yn ->\n    Lt l x y.\n\n  Definition Gt (l:list A) (x:A) (y:A) : Prop := Lt l y x.\n\n  Lemma lt_trans (l:list A) (N:NoDup l):\n    forall x y z,\n    Lt l x y ->\n    Lt l y z ->\n    Lt l x z.\n  Proof.\n    intros.\n    inversion H; clear H.\n    inversion H0; clear H0.\n    rename yn0 into zn.\n    assert (xn0 = yn) by\n    eauto using index_of_fun_1; subst.\n    apply lt_def with (xn:=xn) (yn:=zn); auto.\n    omega.\n  Qed.\n\n  Lemma gt_trans (l:list A) (N:NoDup l):\n    forall x y z,\n    Gt l x y ->\n    Gt l y z ->\n    Gt l x z.\n  Proof.\n    unfold Gt; intros.\n    eauto using lt_trans.\n  Qed.\n\n  Lemma lt_irrefl (l:list A) (N:NoDup l):\n    forall x,\n    ~ Lt l x x.\n  Proof.\n    intros.\n    intuition.\n    inversion H.\n    assert (xn=yn) by eauto using index_of_fun_1.\n    intuition.\n  Qed.\n\n  Lemma gt_irrefl (l:list A) (N:NoDup l):\n    forall x,\n    ~ Gt l x x.\n  Proof.\n    unfold Gt; intros.\n    eauto using lt_irrefl.\n  Qed.\n\n  Lemma lt_neq (l:list A) (N:NoDup l):\n    forall x y,\n    Lt l x y ->\n    x <> y.\n  Proof.\n    intros.\n    inversion H; clear H.\n    assert (xn <> yn) by omega.\n    eauto using index_of_neq.\n  Qed.\n\n  Lemma gt_neq (l:list A) (N:NoDup l):\n    forall x y,\n    Gt l x y ->\n    x <> y.\n  Proof.\n    unfold Gt; intros.\n    apply lt_neq in H; auto.\n  Qed.\n\n  Lemma lt_absurd_nil:\n    forall x y,\n    ~ Lt nil x y.\n  Proof.\n    intuition.\n    destruct H.\n    inversion H.\n  Qed.\n\n  Lemma lt_cons:\n    forall z l x y,\n    Lt l x y ->\n    Lt (z :: l) x y.\n  Proof.\n    intros.\n    inversion H.\n    eauto using lt_def, index_of_cons.\n  Qed.\n\nEnd Defs.\n\n\nSection MapsTo.\n  Variable A:Type.\n\n  Lemma maps_to_inv_eq:\n    forall (x:A) n vs,\n    MapsTo x n (x :: vs) ->\n    n = length vs.\n  Proof.\n    intros.\n    inversion H; subst; auto.\n    contradiction H3; trivial.\n  Qed.\n\n  Lemma maps_to_neq:\n    forall (x:A) y vs n,\n    x <> y ->\n    MapsTo y n (x :: vs) ->\n    MapsTo y n vs.\n  Proof.\n    intros.\n    inversion H0.\n    - subst; contradiction H; trivial.\n    - assumption.\n  Qed.\n\n  Lemma maps_to_fun_2:\n    forall vs (x:A) n n',\n    MapsTo x n vs ->\n    MapsTo x n' vs ->\n    n' = n.\n  Proof.\n    induction vs; intros. {\n      inversion H.\n    }\n    inversion H; subst; clear H;\n    inversion H0; subst; clear H0; auto.\n    - contradiction H3; trivial.\n    - contradiction H4; trivial.\n    - eauto.\n  Qed.\n\n  Lemma maps_to_to_index_of:\n    forall (x:A) nx vs,\n    MapsTo x nx vs ->\n    IndexOf x nx vs.\n  Proof.\n    intros.\n    induction H. {\n      auto using index_of_eq.\n    }\n    auto using index_of_cons.\n  Qed.\n\n  Lemma maps_to_lt:\n    forall (x:A) n vs,\n    MapsTo x n vs ->\n    n < length vs.\n  Proof.\n    induction vs; intros. {\n      inversion H.\n    }\n    inversion H; subst. {\n      auto.\n    }\n    apply IHvs in H4.\n    simpl.\n    auto.\n  Qed.\n\n  Lemma maps_to_absurd_length:\n    forall (x:A) vs,\n    ~ MapsTo x (length vs) vs.\n  Proof.\n    intros.\n    unfold not; intros.\n    apply maps_to_lt in H.\n    apply Lt.lt_irrefl in H.\n    assumption.\n  Qed.\n\n  Lemma index_of_absurd_length:\n    forall (x:A) vs,\n    ~ IndexOf x (length vs) vs.\n  Proof.\n    intuition.\n    apply index_of_lt in H.\n    omega.\n  Qed.\n\n  Lemma index_absurd_length:\n    forall (vs:list A),\n    ~ Index (length vs) vs.\n  Proof.\n    intuition.\n    inversion H.\n    apply index_of_absurd_length in H0.\n    contradiction.\n  Qed.\n\n  Lemma maps_to_absurd_cons:\n    forall (x:A) y n vs,\n    MapsTo x n vs ->\n    ~ (MapsTo y n (y :: vs)).\n  Proof.\n    intros.\n    unfold not; intros.\n    assert (n = length vs) by eauto using maps_to_inv_eq; subst.\n    apply maps_to_absurd_length in H.\n    contradiction.\n  Qed.\n\n  Lemma maps_to_inv_key:\n    forall (x:A) y l,\n    MapsTo y (length l) (x :: l) ->\n    y = x.\n  Proof.\n    intros.\n    inversion H; subst. {\n      trivial.\n    }\n    apply maps_to_absurd_length in H4; contradiction.\n  Qed.\n\n  Lemma index_of_inv_key:\n    forall (x:A) y l,\n    IndexOf y (length l) (x :: l) ->\n    y = x.\n  Proof.\n    intros.\n    inversion H; subst. {\n      trivial.\n    }\n    apply index_of_absurd_length in H2; contradiction.\n  Qed.\n\n  Lemma index_of_fun_2:\n    forall l (x:A) y n,\n    IndexOf x n l ->\n    IndexOf y n l ->\n    y = x.\n  Proof.\n    induction l; intros. {\n      inversion H.\n    }\n    inversion H; subst; clear H. {\n      inversion H0; subst; clear H0. {\n        trivial.\n      }\n      apply index_of_absurd_length in H2; contradiction.\n    }\n    inversion H0; subst; clear H0. {\n      apply index_of_absurd_length in H3; contradiction.\n    }\n    eauto.\n  Qed.\n\n  Lemma maps_to_fun_1:\n    forall (x:A) y n vs,\n    MapsTo x n vs ->\n    MapsTo y n vs ->\n    y = x.\n  Proof.\n    intros.\n    induction H. {\n      eauto using maps_to_inv_key.\n    }\n    inversion H0; subst. {\n      apply maps_to_absurd_length in H1.\n      contradiction.\n    }\n    auto.\n  Qed.\n\n  Lemma maps_to_to_in:\n    forall (x:A) n vs,\n    MapsTo x n vs ->\n    List.In x vs.\n  Proof.\n    intros.\n    induction H. {\n      auto using List.in_eq.\n    }\n    auto using List.in_cons.\n  Qed.\n\n  Lemma index_eq:\n    forall (x:A) vs,\n    Index (length vs) (x::vs).\n  Proof.\n    intros.\n    eauto using index_def, index_of_eq.\n  Qed.\n\n  Lemma maps_to_to_index:\n    forall (x:A) n vs,\n    MapsTo x n vs ->\n    Index n vs.\n  Proof.\n    intros.\n    eauto using index_def, maps_to_to_index_of.\n  Qed.\n\n  Section MapsToDec.\n    Variable eq_dec: forall (x y:A), { x = y } + { x <> y }.\n\n    Lemma in_to_maps_to:\n      forall (x:A) vs,\n      List.In x vs ->\n      exists n, MapsTo x n vs.\n    Proof.\n      induction vs; intros. {\n        inversion H.\n      }\n      destruct H. {\n        subst.\n        eauto using maps_to_eq.\n      }\n      destruct (eq_dec x a). {\n        subst.\n        eauto using maps_to_eq.\n      }\n      apply IHvs in H.\n      destruct H.\n      eauto using maps_to_cons.\n    Qed.\n\n    Fixpoint lookup x l :=\n    match l with\n    | nil => None\n    | y :: l => if eq_dec x y then Some (length l) else lookup x l\n    end.\n\n    Lemma lookup_some:\n      forall xs x n,\n      lookup x xs = Some n ->\n      MapsTo x n xs.\n    Proof.\n      induction xs; intros. {\n        inversion H.\n      }\n      simpl in *.\n      destruct (eq_dec x a). {\n        inversion H; subst.\n        auto using maps_to_eq.\n      }\n      auto using maps_to_cons.\n    Qed.\n\n    Lemma lookup_none:\n      forall xs x,\n      lookup x xs = None ->\n      ~ List.In x xs.\n    Proof.\n      induction xs; intros; simpl in *; auto.\n      destruct (eq_dec x a).\n      - inversion H.\n      - unfold not; intros.\n        apply IHxs in H.\n        destruct H0.\n        * contradiction n; auto.\n        * contradiction.\n    Qed.\n\n    Lemma maps_to_to_lookup:\n      forall x n xs,\n      MapsTo x n xs ->\n      lookup x xs = Some n.\n    Proof.\n      induction xs; intros. {\n        inversion H.\n      }\n      simpl.\n      destruct (eq_dec x a). {\n        subst.\n        apply maps_to_inv_eq in H; subst.\n        trivial.\n      }\n      apply maps_to_neq in H; auto.\n    Qed.\n\n    Lemma not_in_lookup_none:\n      forall xs x,\n      ~ List.In x xs ->\n      lookup x xs = None.\n    Proof.\n      induction xs; intros. {\n        auto.\n      }\n      simpl.\n      destruct (eq_dec x a). {\n        subst.\n        contradiction H; auto using in_eq.\n      }\n      apply IHxs.\n      unfold not; intros N.\n      contradiction H; auto using in_cons.\n    Qed.\n\n    Fixpoint index_of n (l:list A) : option A :=\n    match l with\n    | nil => None\n    | x :: l => if eq_nat_dec n (length l) then Some x else index_of n l\n    end.\n\n    Lemma index_of_some:\n      forall n l x,\n      index_of n l = Some x ->\n      IndexOf (A:=A) x n l.\n    Proof.\n      induction l; intros. {\n        simpl in *.\n        inversion H.\n      }\n      simpl in *.\n      destruct (eq_nat_dec n (length l)). {\n        inversion H; subst.\n        auto using index_of_eq.\n      }\n      auto using index_of_cons.\n    Qed.\n\n    Lemma index_of_prop:\n      forall l n x,\n      IndexOf (A:=A) x n l ->\n      index_of n l = Some x.\n    Proof.\n      induction l; intros. {\n        inversion H.\n      }\n      inversion H; subst; clear H. {\n        simpl.\n        destruct (eq_nat_dec (length l) (length l)). {\n          trivial.\n        }\n        intuition.\n      }\n      simpl.\n      destruct (eq_nat_dec n (length l)). {\n        subst.\n        apply index_of_absurd_length in H2.\n        contradiction.\n      }\n      auto.\n    Qed.\n\n  End MapsToDec.\nEnd MapsTo.", "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/Bijection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7789482319834248}}
{"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 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. rewrite plus_succ. rewrite IHx. reflexivity.\n   - rewrite plus_zero. reflexivity.\nQed.\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": "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/goal85.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7789482248116647}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia Coq.micromega.Lia.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Z.bitblast.\nRequire Import coqutil.Z.prove_Zeq_bitwise.\nRequire Import coqutil.Byte.\nRequire coqutil.Datatypes.List.\n\nLocal Open Scope Z_scope.\n\nSection LittleEndian.\n  Fixpoint le_combine(l: list byte): Z :=\n    match l with\n    | nil => 0\n    | cons h t => Z.lor (byte.unsigned h) (Z.shiftl (le_combine t) 8)\n    end.\n\n  Fixpoint le_split (n : nat) (w : Z) : list byte :=\n    match n with\n    | O => nil\n    | S n => cons (byte.of_Z w) (le_split n (Z.shiftr w 8))\n    end.\n\n  Lemma le_combine_split (n : nat) (z : Z) :\n    le_combine (le_split n z) = z mod 2 ^ (Z.of_nat n * 8).\n  Proof.\n    revert z; induction n; cbn [le_split le_combine]; intros.\n    { rewrite Z.mod_1_r; trivial. }\n    { erewrite IHn, byte.unsigned_of_Z, Nat2Z.inj_succ, Z.mul_succ_l by blia.\n      unfold byte.wrap; rewrite <-! Z.land_ones by blia; prove_Zeq_bitwise. }\n  Qed.\n  Notation le_combine_le_split := le_combine_split.\n\n  Lemma length_le_split: forall n z,\n      length (le_split n z) = n.\n  Proof. induction n; cbn [length le_split]; auto. Qed.\n\n  Lemma split_le_combine bs :\n    le_split (List.length bs) (le_combine bs) = bs.\n  Proof.\n    induction bs; cbn [le_split le_combine List.length]; trivial.\n    f_equal.\n    { eapply byte.unsigned_inj.\n      rewrite byte.unsigned_of_Z, <-byte.wrap_unsigned; cbv [byte.wrap].\n      Z.bitblast; cbn; subst.\n      rewrite (Z.testbit_neg_r _ (i-8)) by blia.\n      Z.bitblast_core. }\n    { rewrite <-IHbs.\n      rewrite length_le_split.\n      rewrite le_combine_split.\n      f_equal.\n      rewrite <-byte.wrap_unsigned; cbv [byte.wrap].\n      Z.bitblast; subst; cbn.\n      rewrite <-IHbs.\n      rewrite le_combine_split.\n      Z.bitblast_core. }\n  Qed.\n  Notation le_split_le_combine := split_le_combine.\n\n  Lemma le_combine_inj: forall (b1 b2: list byte),\n      length b1 = length b2 ->\n      LittleEndian.le_combine b1 = LittleEndian.le_combine b2 ->\n      b1 = b2.\n  Proof.\n    intros.\n    apply (f_equal (le_split (length b1))) in H0.\n    rewrite H in H0 at 2.\n    do 2 rewrite split_le_combine in H0.\n    exact H0.\n  Qed.\n\n  Lemma le_combine_1: forall b, le_combine (cons b nil) = byte.unsigned b.\n  Proof.\n    intros. change (le_combine (b :: nil) )with (Z.lor (byte.unsigned b) 0).\n    apply Z.lor_0_r.\n  Qed.\n\n  Lemma hd_error_le_split n z (H : n <> 0%nat) :\n    List.hd_error (le_split n z) = Some (byte.of_Z z).\n  Proof. destruct n; trivial; contradiction. Qed.\n\n  Local Coercion Z.of_nat : nat >-> Z.\n  Lemma skipn_le_split' n m : forall z,\n    List.skipn n (le_split (n+m) z) = le_split m (Z.shiftr z (8*n)).\n  Proof.\n    induction n; intros. { rewrite Z.shiftr_0_r; trivial. }\n    cbn [Nat.add List.skipn le_split].\n    rewrite IHn, Z.shiftr_shiftr; repeat (blia || f_equal).\n  Qed.\n\n  Lemma skipn_le_split n m z (H: (n <= m)%nat) :\n    List.skipn n (le_split m z) = le_split (m-n) (Z.shiftr z (8*n)).\n  Proof.\n    replace m with (n+(m-n))%nat by blia.\n    rewrite skipn_le_split'; f_equal; blia.\n  Qed.\n\n  Lemma nth_error_le_split i n z (H: (i < n)%nat) :\n    List.nth_error (le_split n z) i = Some (byte.of_Z (Z.shiftr z (8*i))).\n  Proof.\n    rewrite List.nth_error_as_skipn, skipn_le_split, hd_error_le_split by blia; trivial.\n  Qed.\n\n  Lemma nth_default_le_split i n z (H: (i < n)%nat) d :\n    List.nth_default d (le_split n z) i = byte.of_Z (Z.shiftr z (8*i)).\n  Proof. cbv [List.nth_default]; rewrite nth_error_le_split; trivial. Qed.\n\n  Lemma le_combine_firstn n : forall bs,\n    le_combine (List.firstn n bs) = le_combine bs mod 2^(8*n).\n  Proof.\n    induction n. { setoid_rewrite Z.mod_1_r; trivial. }\n    intros [|bs b]; cbn [le_combine List.firstn].\n    { rewrite Z.mod_0_l; trivial. eapply Z.pow_nonzero; blia. }\n    rewrite <-byte.wrap_unsigned; cbv [byte.wrap].\n    rewrite IHn, <-!Z.land_ones by blia.\n    prove_Zeq_bitwise.\n  Qed.\n\n  Lemma le_combine_nil : le_combine nil = 0. Proof. exact eq_refl. Qed.\n\n  Lemma le_combine_bound t:\n      0 <= le_combine t < 2 ^ (8 * List.length t).\n  Proof.\n    rewrite <-(List.firstn_all t), le_combine_firstn, List.firstn_all.\n    eapply Z.mod_pos_bound, Z.pow_pos_nonneg; blia.\n  Qed.\n\n  Lemma le_combine_app bs1 bs2:\n    le_combine (bs1 ++ bs2) =\n      Z.lor (le_combine bs1) (Z.shiftl (le_combine bs2) (Z.of_nat (List.length bs1) * 8)).\n  Proof.\n    induction bs1; cbn -[Z.shiftl Z.of_nat Z.mul]; intros.\n    - rewrite Z.mul_0_l, Z.shiftl_0_r; reflexivity.\n    - rewrite IHbs1, Z.shiftl_lor, Z.shiftl_shiftl, !Z.lor_assoc by lia.\n      f_equal; f_equal; lia.\n  Qed.\n\n  Lemma le_combine_0 n:\n    le_combine (List.repeat Byte.x00 n) = 0.\n  Proof. induction n; simpl; intros; rewrite ?IHn; reflexivity. Qed.\n\n  Lemma le_combine_app_0 bs n:\n    le_combine (bs ++ List.repeat Byte.x00 n) = le_combine bs.\n  Proof.\n    rewrite le_combine_app; simpl; rewrite le_combine_0.\n    rewrite Z.shiftl_0_l, Z.lor_0_r.\n    reflexivity.\n  Qed.\n\n  Import List.ListNotations. Open Scope list_scope.\n\n  Lemma le_combine_snoc_0 bs:\n    le_combine (bs ++ [Byte.x00]) = le_combine bs.\n  Proof. apply le_combine_app_0 with (n := 1%nat). Qed.\n\n  Lemma le_split_mod z n:\n    le_split n z = le_split n (z mod 2 ^ (Z.of_nat n * 8)).\n  Proof.\n    apply le_combine_inj.\n    - rewrite !length_le_split; reflexivity.\n    - rewrite !le_combine_split.\n      coqutil.Z.PushPullMod.Z.push_pull_mod; reflexivity.\n  Qed.\n\n  Lemma split_le_combine' bs n:\n    List.length bs = n ->\n    le_split n (le_combine bs) = bs.\n  Proof. intros <-; apply split_le_combine. Qed.\n\n  Lemma le_combine_chunk_split n z:\n    (0 < n)%nat ->\n    List.map le_combine (List.chunk n (le_split n z)) =\n      [z mod 2 ^ (Z.of_nat n * 8)].\n  Proof.\n    intros; rewrite List.chunk_small by (rewrite length_le_split; lia).\n    simpl; rewrite le_combine_split; reflexivity.\n  Qed.\nEnd LittleEndian.\n\nArguments le_combine: simpl never.\nArguments le_split: simpl never.\n", "meta": {"author": "mit-plv", "repo": "coqutil", "sha": "48eeef16cc9aa3a057d4a76207b88b34fd397e24", "save_path": "github-repos/coq/mit-plv-coqutil", "path": "github-repos/coq/mit-plv-coqutil/coqutil-48eeef16cc9aa3a057d4a76207b88b34fd397e24/src/coqutil/Word/LittleEndianList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7788823057499464}}
{"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_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\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\nLemma Nat_beq_refl : forall (n : natural), eqb n n = true.\nProof.\n   intros.\n   induction n.\n   - assumption.\n   - reflexivity.\n   \nQed.\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   - intros. destruct y.\n   + discriminate.\n   + reflexivity.\nQed.\n\nLemma less_not_refl : forall (n : natural), less n n = false.\nProof.\n   intros.\n   induction n.\n   - simpl. assumption.\n   - reflexivity.\n   \nQed.\n              \nTheorem theorem0 : forall (x : natural) (y : lst), eq (count (insort y x) x) (Succ (count y x)).\nProof.\n   intros.\n  induction y.\n  - simpl. destruct (eqb x n) eqn:?.\n    + destruct (less x n) eqn:?.\n      * apply Nat_beq_eq in Heqb. rewrite Heqb in Heqb0. rewrite less_not_refl in Heqb0. discriminate.\n      * simpl. rewrite Heqb. rewrite IHy. reflexivity.\n    + destruct (less x n) eqn:?.\n      * simpl. rewrite Nat_beq_refl. rewrite Heqb. reflexivity.\n      * simpl. rewrite Heqb. assumption.\n      - simpl. rewrite Nat_beq_refl. 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/goal70.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7787449539148401}}
{"text": "Require Export Basics.\n\nCompute (evenb 2).\n\nTheorem plus_O_firstry: forall n:nat, n = n + O.\nProof.\n  intros n.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem minus_diag: forall n:nat, minus n n = 0.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_0_r: forall n:nat, n * 0 = 0.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m:nat, S (n + m) = n + S m.\nProof.\n  induction n as [|n' IHn'].\n  - simpl. reflexivity.\n  - simpl.\n    intros m.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_comm: forall n m:nat, n + m = m + n.\nProof.\n  induction n as [|n' IHn'].\n  - induction m as [|m IHm'].\n    * reflexivity.\n    * simpl.\n      rewrite <- IHm'.\n      simpl.\n      reflexivity.\n  - intros m.\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\nQed.\n\nTheorem plus_assoc: forall n m p:nat, n + (m + p) = (n + m) + p.\nProof.\n  induction n as [|n' IHn'].\n  - intros m p.\n    simpl.\n    reflexivity.\n  - intros m p.\n    simpl.\n    rewrite -> IHn'.\n    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\nNotation \"x + y\" := (plus x y) (at level 50, left associativity) :nat.\n\nNotation \"x * y\" := (mult x y) (at level 40, left associativity) :nat.\n\nLemma double_plus: forall n:nat, double n = n + n.\nProof.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\nQed.\n\n\n\nTheorem evenb_S: forall n: nat, evenb (S n) = negb (evenb n).\nProof.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - rewrite -> IHn'.\n    rewrite -> negb_involutive.\n    simpl.\n    reflexivity.\nQed.\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  - reflexivity.\n  - rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem plus_rearrange: forall n m p q: nat, (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (n + m = m + n) as H.\n  - rewrite plus_comm.\n    reflexivity.\n  - rewrite H.\n    reflexivity.\nQed.\n\nTheorem plus_swap: 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  assert (n + m = m + n) as H.\n  - rewrite -> plus_comm.\n    reflexivity.\n  - rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem mult_n_Sm: forall n m: nat, n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_swap.\n    reflexivity.\nQed.\n\nTheorem mult_comm: forall m n: nat, m * n = n * m.\nProof.\n  induction m as [|m' IHm'].\n  - intros n.\n    rewrite -> mult_0_r.\n    reflexivity.\n  - intros n.\n    simpl.\n    rewrite -> IHm'.\n    rewrite -> mult_n_Sm.\n    reflexivity.\nQed.\n\nTheorem leb_refl: forall n:nat, true = leb n n.\nProof.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem zero_nbeq_S: forall n: nat, beq_nat O (S n) = false.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem andb_false_r: forall b:bool, 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.\n  induction p as [|p' IHp'].\n  - simpl.\n    rewrite <- H.\n    reflexivity.\n  - simpl.\n    rewrite <- IHp'.\n    reflexivity.\nQed.\n\nTheorem S_nbeq_0: forall n:nat, beq_nat (S n) 0 = false.\nProof.\n  intros [].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\nTheorem mult_1_l: forall n:nat, 1 * n = n.\nProof.\n  intros n.\n  simpl.\n  rewrite <- plus_n_O.\n  reflexivity.\nQed.\n\nTheorem all3_spec: forall b c:bool,\n    orb (andb b c) (orb (negb b) (negb c)) = true.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem mult_plus_distr_r: forall n m p: nat,\n    (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> plus_assoc.\n    reflexivity.\nQed.\n\nTheorem mult_assoc: forall n m p: nat,\n    n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    rewrite -> mult_plus_distr_r.\n    reflexivity.\nQed.\n\nTheorem beq_nat_relf: forall n: nat,\n    true = beq_nat n n.\nProof.\n  induction n as [|n' IHn'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_swap': forall n m p: nat,\n    n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  replace (n + m) with (m + n).\n  - reflexivity.\n  - rewrite -> plus_comm.\n    reflexivity.\nQed.\n\nInductive bin: Type :=\n| Z : bin\n| T : bin -> bin\n| TP : bin -> bin.\n\nFixpoint incr(b: bin): bin :=\n  match b with\n  | Z => TP Z\n  | T n => TP n\n  | TP n => T (incr n)\n  end.\n\nFixpoint bin_to_nat(b: bin): nat :=\n  match b with\n  | Z => O\n  | T n => mult (bin_to_nat n) (S (S O))\n  | TP n => S (mult (bin_to_nat n) (S (S O)))\n  end.\n\nExample test_bin_incr1: bin_to_nat (incr Z) = 1.\nProof.\n  reflexivity.\nQed.\n\nExample test_bin_incr2: bin_to_nat (incr (T Z)) = 1.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_bin_incr3: bin_to_nat (incr (TP Z)) = 2.\nProof.\n  reflexivity.\nQed.\n\nExample test_bin_incr4: bin_to_nat (incr (T (T Z))) = 1.\nProof.\n  reflexivity.\nQed.\n\nExample test_bin_incr5: bin_to_nat (incr (TP (TP Z))) = 4.\nProof.\n  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.\n  induction b as [|b IHb |c IHc].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHc.\n    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_to_bin_to_nat: forall n: nat,\n    bin_to_nat (nat_to_bin n) = n.\nProof.\n  intros n.\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\nCompute (nat_to_bin 1).\nCompute (nat_to_bin 2).\nCompute (nat_to_bin 3).\nCompute (nat_to_bin 4).\nCompute (nat_to_bin 5).\nCompute (nat_to_bin 6).\n\nTheorem inverse_normalize: forall b: bin,\n    nat_to_bin (bin_to_nat b) = b.\nProof.\n  intros b.\n  induction b as [|b' IHb' |b' IHb'].\n  - simpl.\n    reflexivity.\n  - simpl.\nAdmitted.\n\n", "meta": {"author": "liuxueyang", "repo": "software-foundations-solutions", "sha": "0b460f106236ffa9c39f6492484426b04286f627", "save_path": "github-repos/coq/liuxueyang-software-foundations-solutions", "path": "github-repos/coq/liuxueyang-software-foundations-solutions/software-foundations-solutions-0b460f106236ffa9c39f6492484426b04286f627/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7787449522421074}}
{"text": "Require Import List.\n\nDefinition eq_dec (A:Type) :=\n  forall x y:A, {x = y} + {x <> y}.\n\nLemma nat_dec : eq_dec nat.\nProof.\n  unfold eq_dec. intros x. elim x.\n  clear x. intro y. elim y.\n  clear y. auto.\n  clear y. intros. right. auto.\n  clear x. intros n IH m. elim m.\n  clear m. intros. right. auto.\n  clear m. intros m H. clear H.\n  elim (IH m).\n  intro H. rewrite H. left. reflexivity.\n  intro H. right. intro H'. apply H. injection H'. auto.\nQed.\n\n\n\n\n(* returns the number of occurences of n in l *)\nFixpoint count (l:list nat)(n: nat) :nat :=\n  match l with\n    | nil     =>  0\n    | (m::l') =>  match nat_dec n m with\n                    | left  _ => S (count l' n)\n                    | right _ => count l' n\n                  end\n  end.\n\n\nEval compute in (count (1::2::1::3::nil) 1).\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/sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7787384582152282}}
{"text": "From LF Require Export exercise1.\nFrom LF Require Export exercise2.\nFrom LF Require Export exercise3.\nFrom LF Require Export exercise4.\n\nTheorem eq_is_eq : forall (X : Type) (n m : X),\n  n = m ->\n  n = m.\nProof.\n  intros X n m eq. apply eq.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex) *)\n(* Complete the following proof using only intros and apply. *)\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 H1 H2 H3.\n  apply H2. apply H1. apply H3.\nQed.\n\n(** **** Exercise: 2 stars, standard (apply_exercise1) *)\n(* You can use apply with previously defined theorems, not just hypotheses in the context. Use Search to find a previously-defined theorem about rev from Lists. Use that theorem as part of your (relatively short) solution to this exercise.\nYou do not need induction. *)\nTheorem rev_exercise1 : forall (l l' : list nat),\n  l = rev l' ->\n  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. rewrite -> eq2.\n  reflexivity.\nQed.\n\nFixpoint minustwo (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | 1 => 0\n  | S (S n') => minustwo n'\n  end.\n\n(** **** Exercise: 3 stars, standard, optional (trans_eq_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 H1 H2.\n  transitivity m. apply H2. apply H1.\nQed.\n\nTheorem nat_injective: forall (n m : nat),\n\tS n = S m ->\n\tn = m.\nProof.\n\tintros n m H.\n\tinjection H as Hnm. apply Hnm.\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. injection H as H1 H2.\n  assert(H': z :: l = y :: l).\n    {\n      transitivity j. symmetry. apply H0. symmetry. apply H2.\n    }\n  rewrite H1.\n  injection H'. apply eq_is_eq.\nQed.\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.\nTheorem eq_implies_succ_equal : forall (n m : nat),\n  n = m -> S n = S m.\nProof. intros n m H. apply f_equal. apply H. Qed.\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  intros. induction l as [| n l H'].\n  - simpl. discriminate H.\n  - simpl. apply H'. discriminate.\nQed.\n\nTheorem double_injective: forall n m : nat,\n\tdouble n = double m ->\n\tn = m.\nProof.\n  intros n. induction n as [| n' H].\n  - simpl. intros m eq. destruct m.\n    + reflexivity.\n    + discriminate eq.\n  - intros m eq. destruct m as [| m'].\n    + discriminate.\n    + apply f_equal. apply H.\n      simpl in eq. injection eq as goal.\n      apply goal.\nQed.\n\n(** **** Exercise: 2 stars, standard (eqb_true) *)\nTheorem eqb_true : forall n m,\n  n =? m = true -> n = m.\nProof.\n  intros m. induction m as [| m' H].\n  - intros n H'. destruct n.\n    + reflexivity.\n    + discriminate.\n  - intros n H'. destruct n.\n    + discriminate.\n    + simpl in H'. apply f_equal. apply H. apply H'.\nQed.\n\n\n(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective) *)\n(* In addition to being careful about how you use intros, practice using \"in\"\nvariants in this proof. (Hint: use plus_n_Sm.) *)\nTheorem plus_n_n_injective : forall n m,\n  n + n = m + m ->\n  n = m.\nProof.\n  intros. rewrite <- double_plus in H. rewrite <- double_plus in H.\n  apply double_injective. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, especially useful (gen_dep_practice) *)\n(* Prove this by induction on l. *)\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 [| n' l' IHl].\n  - intros. reflexivity.\n  - intros. destruct n.\n    + discriminate.\n    + simpl. apply IHl. simpl in H. injection H. apply eq_is_eq.\nQed.\n\nDefinition square n : nat := 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 mul_comm.\n      rewrite <- mult_assoc.\n      reflexivity.\n    }\n  rewrite H. reflexivity.\nQed.\n\n(* In fact, this is injection. *)\nLemma pair_eq : forall X Y (x1 x2: X) (y1 y2 : Y),\n  (x1, y1) = (x2, y2) ->\n  x1 = x2 /\\ y1 = y2.\nProof.\n  intros. injection H as H1 H2.\n  split.\n  - apply H1.\n  - apply H2.\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 [| n l' IHl].\n  - intros. simpl in H. apply pair_eq in H.\n    destruct H. rewrite <- H. rewrite <- H0. reflexivity.\n  - destruct n as [n1 n2]. simpl. destruct (split l').\n    + simpl. intros l1 l2 H.\n      apply pair_eq in H. destruct H. rewrite <- H. rewrite <- H0.\n      assert(H' : combine x y = l').\n      {\n        apply IHl. reflexivity.\n      }\n      rewrite <- H'. 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\n  Theorem sillyfun1_odd_FAILED : forall (n : nat),\n  sillyfun1 n = true ->\n  odd n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn: Heqn3.\n  - apply eqb_true in Heqn3. rewrite Heqn3. reflexivity.\n  - destruct (n =? 5) eqn : Heqn5.\n    + apply eqb_true in Heqn5. rewrite Heqn5. reflexivity.\n    + discriminate eq.\nQed.\n\n(** **** Exercise: 2 stars, standard (destruct_eqn_practice) *)\nTheorem bool_fn_applied_thrice : forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros. destruct b.\n  - destruct (f true) eqn: H1.\n    + rewrite H1. apply H1.\n    + destruct (f false) eqn: H2.\n      * apply H1.\n      * apply H2.\n  - destruct (f false) eqn: H1.\n    +  destruct (f true) eqn : H2.\n      * apply H2.\n      * apply H1.\n    + rewrite H1. apply H1.\nQed.\n\n(** **** Exercise: 3 stars, standard (eqb_sym) *)\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\n  intros n. induction n as [| n' H].\n  - intros m. destruct m.\n    * reflexivity.\n    * reflexivity.\n  - intros m. destruct m.\n    * reflexivity.\n    * simpl. apply H.\nQed.\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  intros. apply eqb_true in H. apply eqb_true in H0.\n  rewrite H. rewrite <- H0. apply eqb_refl.\nQed.\n\n\n(** **** Exercise: 3 stars, advanced (split_combine) *)\n(* We proved, in an exercise above, that combine is the inverse of split. Complete the definition of split_combine_statement below with a property that\nstates that split is the inverse of combine. Then, prove that the property\nholds. *)\n(* Hint: Take a look at the definition of combine in Poly. Your property will\nneed to account for the behavior of combine in its base cases, which possibly\ndrop some list elements. *)\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. induction l1 as [| n l1' H].\n  - intros. simpl. destruct l2.\n    + reflexivity.\n    + inversion H.\n  - intros. destruct l2.\n    + simpl. inversion H0.\n    + inversion H0. apply H in H2. simpl. rewrite H2. simpl. reflexivity.\nQed.\n\n(*Sometimes you have a hypothesis that can't be true unless other things\nare also true. We can use inversion to discover other necessary\nconditions for a hypothesis to be true.*)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\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. induction l as [|n l' IHl].\n  - intros H. simpl in H. discriminate.\n  - intros H. simpl in H. destruct (test n) eqn: H'.\n    + inversion H. rewrite H1 in H'. apply H'.\n    + inversion H. apply IHl. apply H.\nQed.\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/exercise5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.90192067257508, "lm_q1q2_score": 0.7787107352225853}}
{"text": "Require Import List.\nRequire Import Arith.\n\nFixpoint nth_option {A:Type}(n:nat)(l:list A) \n  : option A :=\n  match n, l with\n  | O, cons a _ =>  Some a\n  | S p, cons  _ tl => nth_option  p tl\n  | _, nil => None\n  end.\n\nLemma nth_length {A : Type} : \n  forall (n:nat)(l:list A), nth_option  n l = None <->\n                                   length l <= n.\nProof.\n induction n as [| p IHp].\n -  destruct l; simpl; split; auto.\n   +  discriminate 1.\n   +  inversion 1.\n -  intro l; destruct l as [ | a l'].\n   +   split;simpl; auto with arith.\n   +   simpl;  rewrite (IHp l');  split;  auto with arith.  \nQed.\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/nth_length.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7786667783032438}}
{"text": "Require Import ZArith.\nRequire Import List.\n\nInductive bop : Set :=\n| Add : bop\n| Sub : bop\n| Mul : bop.\n\nDefinition arg := nat.\n\nDefinition mkArg (name : nat) : arg := name.\nDefinition argName (a : arg) : nat := a.\n\nInductive aexp : Set :=\n| ArgExp : arg -> aexp\n| Binop : bop -> aexp -> aexp -> aexp.\n\nOpen Scope Z_scope.\n\nDefinition arithState := arg -> Z.\n\nFixpoint aEval (e : aexp) (s : arithState) : Z :=\n  match e with\n    | Binop Add l r => (aEval l s) + (aEval r s)\n    | Binop Sub l r => (aEval l s) - (aEval r s)\n    | Binop Mul l r => (aEval l s) * (aEval r s)\n    | ArgExp a => s a\n  end.\n\nDefinition stackReg := nat.\n\nDefinition stackRegName (sreg : stackReg) : nat := sreg.\nDefinition eq_stackReg (sr1 sr2 : stackReg) : bool :=\n  beq_nat (stackRegName sr1) (stackRegName sr2).\n\nDefinition mkStackReg (n : nat) : stackReg := n.\n\nInductive stackBOP : Set :=\n| StackAdd : stackBOP\n| StackSub : stackBOP\n| StackMul : stackBOP.\n\nInductive stackInstr : Set :=\n| Push : stackReg -> stackInstr\n| Pop : stackReg -> stackInstr\n| StackBinop : stackBOP -> stackReg -> stackReg -> stackInstr\n| Ret : stackReg -> stackInstr.\n\nDefinition stackRegVals := stackReg -> Z.\nDefinition stack := list Z.\n\nInductive stackState : Set :=\n| StackState : stackRegVals -> stack -> stackState.\n\nDefinition arithStateToStackRegVals (arithS : arithState) : stackRegVals :=\n  fun sreg => arithS (argName (stackRegName sreg)).\n\nDefinition freshStackState (arithS : arithState) : stackState :=\n  StackState (arithStateToStackRegVals arithS) nil.\n\nCheck arithStateToStackRegVals.\n\nDefinition stackProgram := list stackInstr.\n\nDefinition pushStk (r : stackReg) (ss : stackState) : stackState :=\n  match ss with\n    | StackState srVals stk => StackState srVals ((srVals r) :: stk)\n  end.\n\nDefinition popStk (r : stackReg) (ss : stackState) : option stackState :=\n  match ss with\n    | StackState srVals (v :: stk) =>\n      Some (StackState (fun x => if eq_stackReg x r then v else srVals x) stk)\n    | StackState srVals nil =>\n      None\n  end.\n\nFixpoint spEval (sp : stackProgram) (ss : stackState) : option Z :=\n  match sp, ss with\n    | nil, _ => None\n    | (Push r :: sp'), ss =>\n      spEval sp' (pushStk r ss)\n    | (Pop r :: sp'), ss =>\n      match popStk r ss with\n        | Some newSS => spEval sp' newSS\n        | None => None\n      end\n    | (StackBinop b r0 r1 :: sp'), (StackState srVals stk) =>\n      spEval sp' (StackState srVals stk)\n    | Ret r :: sp', (StackState srVals stk) => Some (srVals r)\n  end.\n\nDefinition sr0 := mkStackReg 0.\nDefinition sr1 := mkStackReg 1.\n\nFixpoint arithToStackInstrs (e : aexp) : list stackInstr :=\n  match e with\n    | ArgExp a => Push (mkStackReg (argName a)) :: nil\n    | Binop Add l r =>\n      (arithToStackInstrs l) ++ (arithToStackInstrs r) ++ (Pop sr0 :: Pop sr1 :: StackBinop StackAdd sr0 sr1 :: nil)\n    | Binop Sub l r =>\n      (arithToStackInstrs l) ++ (arithToStackInstrs r) ++ (Pop sr0 :: Pop sr1 :: StackBinop StackSub sr0 sr1 :: nil)\n    | Binop Mul l r =>\n      (arithToStackInstrs l) ++ (arithToStackInstrs r) ++ (Pop sr0 :: Pop sr1 :: StackBinop StackMul sr0 sr1 :: nil)\n  end.\n  \nFixpoint compileArithToStack (e : aexp) : stackProgram :=\n  (arithToStackInstrs e) ++ (Pop sr0 :: Ret sr0 :: nil).\n\nTheorem pushStk_implies_not_empty :\n  forall (r : stackReg) (ss : stackState),\n    exists (srv : stackRegVals) (s : stack),\n      pushStk r ss = StackState srv ((srv r) :: s).\nProof.\n  intros; destruct ss; repeat eapply ex_intro. cbv delta.\n  cbv beta. cbv iota. reflexivity.\nQed.\n\nTheorem compileArithToStack_correct :\n  forall (e : aexp) (ars : arithState),\n           Some (aEval e ars) = spEval (compileArithToStack e) (freshStackState ars).\nProof.\n  intros; induction e.\n\n  simpl. unfold arithStateToStackRegVals.\n  unfold argName. unfold mkStackReg. unfold stackRegName. reflexivity.\n\n  simpl; destruct b.", "meta": {"author": "dillonhuff", "repo": "CertArith", "sha": "606388777cee1435b6aa354f89c3af371d3a1864", "save_path": "github-repos/coq/dillonhuff-CertArith", "path": "github-repos/coq/dillonhuff-CertArith/CertArith-606388777cee1435b6aa354f89c3af371d3a1864/ArithExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7786667648818527}}
{"text": "(*\n  NOTE: This proof depends on plus_commutes and plus_associates\n  defined in PlusCommutes.v and PlusAssociates.v\n*)\n\n(*\n  Add the load path containing the two theorems -\n  feel free to edit the load path accordingly\n*)\nAdd LoadPath \"/path/to/lemmas_and_theorems\".\n\n(* Require the two theorems mentioned above *)\nRequire Export PlusCommutes.\nRequire Export PlusAssociates.\n\n(* A useful lemma for the proof below *)\nLemma plus_p_right : forall n m p : nat, n = m -> n + p = m + p.\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n(*\n  Multiplication of natural numbers distributes\n  over addition to the left, i.e. a(b + c) = ab + ac\n*)\nTheorem left_distributive : forall n m p : nat, n * (m + p) = n * m + n * p.\nProof.\n  intros.\n  induction n as [| n' IHn].\n    reflexivity.\n\n    simpl.\n    rewrite IHn.\n    symmetry.\n    rewrite plus_associates.\n    rewrite plus_commutes.\n    symmetry.\n    rewrite plus_associates.\n    rewrite plus_commutes.\n    rewrite <- plus_associates.\n    symmetry.\n    rewrite <- plus_associates.\n    apply plus_p_right.\n    apply plus_p_right.\n    apply plus_commutes.\nQed.\n", "meta": {"author": "DonaldKellett", "repo": "coq-proofs", "sha": "d6852ba3ec39848b4e3a78f6df63ec517c14a7d7", "save_path": "github-repos/coq/DonaldKellett-coq-proofs", "path": "github-repos/coq/DonaldKellett-coq-proofs/coq-proofs-d6852ba3ec39848b4e3a78f6df63ec517c14a7d7/nat/LeftDistributive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7786544637732981}}
{"text": "Require Import List.\nRequire Import Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nCheck (fun x : nat => x).\nCheck (fun x : True => x).\nCheck I.\nCheck (fun _ : False => I).\nCheck (fun x : False => x).\n\nInductive unit : Set :=\n  | tt.\nCheck unit.\nCheck tt.\nTheorem unit_singleton : forall x : unit, x = tt.\n  induction x.\n  reflexivity.\nQed.\nCheck unit_ind.\nInductive Empty_set : Set := .\n\nTheorem the_sky_is_falling : forall x : Empty_set, 2 + 2 = 5.\n  destruct 1.\nQed.\n\nCheck Empty_set_ind.\n\nDefinition e2u (e : Empty_set) : unit := match e with end.\n\nInductive bool : Set :=\n| true\n| false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n    | true => false\n    | false => 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.\n  destruct b.\n  reflexivity.\nRestart.\n  destruct b; reflexivity.\nQed.\n\nTheorem negb_ineq : forall b : bool, negb b <> b.\n  destruct b; discriminate.\nQed.\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\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.\n  intro; reflexivity.\nQed.\n\nTheorem n_plus_O : forall n : nat, plus n O = n.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nRestart.\n  induction n; crush.\nQed.\n\nCheck nat_ind.\n\nTheorem S_inj : forall n m : nat, S n = S m -> n = m.\n  injection 1; trivial. \nRestart.\n  injection 1; congruence.\nQed.\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 : 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 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).\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)\n  = plus (nsize tr2) (nsize tr1).\n  induction tr1; crush.\nQed.\n\nCheck nat_btree_ind.\n\nInductive mylist (T : Set) : Set :=\n| Nil : mylist T\n| Cons : T -> mylist T -> mylist T.\n\nCheck mylist.\n\nFixpoint length T (ls : mylist T) : nat :=\n  match ls with\n    | Nil => O\n    | Cons _ ls' => S (length ls')\n  end.\n\nFixpoint app T (ls1 ls2 : mylist T) : mylist 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 : mylist T), length (app ls1 ls2)\n  = plus (length ls1) (length ls2).\n  induction ls1; crush.\nQed.\n\nLocate mylist.\nLocate app.\n\nReset mylist. (*After this stat, mylist is invisible afterwards*)\n\nLocate mylist.\n\nSection mylistx. \n  Variable T : Set.\n\n  Inductive mylist : Set :=\n  | Nil : mylist\n  | Cons : T -> mylist -> mylist.\n\n  Fixpoint length (ls : mylist) : nat :=\n    match ls with\n      | Nil => O\n      | Cons _ ls' => S (length ls')\n    end.\n\n  Fixpoint app (ls1 ls2 : mylist) : mylist :=\n    match ls1 with\n      | Nil => ls2\n      | Cons x ls1' => Cons x (app ls1' ls2)\n    end.\n\n  Theorem length_app : forall ls1 ls2 : mylist, length (app ls1 ls2)\n    = plus (length ls1) (length ls2).\n    induction ls1; crush.\n  Qed.\nEnd mylistx.\n\nArguments Nil {T}.\nPrint mylist. \nCheck length.\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\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.\nCheck even_list_ind.\n\nScheme even_list_mut := Induction for even_list Sort Prop\nwith odd_list_mut := Induction for odd_list Sort Prop.\n\nCheck even_list_mut.\nTheorem n_plus_O' : forall n : nat, plus n O = n.\n  apply nat_ind.\nUndo. Check nat_ind.\n  apply (nat_ind (fun n => plus n O = n)); crush.\nQed.\n\nTheorem elength_eapp : forall el1 el2 : even_list,\n  elength (eapp el1 el2) = plus (elength el1) (elength el2).\n  Check even_list_mut.\n  apply (even_list_mut\n    (fun el1 : even_list => forall el2 : even_list,\n      elength (eapp el1 el2) = plus (elength el1) (elength el2))\n    (fun ol : odd_list => forall el : even_list,\n      olength (oapp ol el) = plus (olength ol) (elength el))); crush.\nQed.\n\nInductive pformula : Set :=\n| Truth : pformula\n| Falsehood : pformula\n| Conjunction : pformula -> pformula -> pformula.\n\nDefinition prod' := prod.\n\nFixpoint pformulaDenote (f : pformula) : Prop :=\n  match f with\n    | Truth => True\n    | Falsehood => False\n    | Conjunction f1 f2 => pformulaDenote f1 /\\ pformulaDenote f2\n  end.\n(* haoyang *)\nInductive formula : Set :=\n| Eq : nat -> nat -> formula\n| And : formula -> formula -> formula\n| Forall : (nat -> formula) -> formula.\n\nExample forall_refl : formula := Forall (fun x => Eq x x).\n\nFixpoint formulaDenote (f : formula) : Prop :=\n  match f with\n    | Eq n1 n2 => n1 = n2\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 n1 n2 => Eq n2 n1\n    | And f1 f2 => And (swapper f2) (swapper f1)\n    | Forall f' => Forall (fun n => swapper (f' n))\n  end.\n\nTheorem swapper_preserves_truth : forall f, formulaDenote f -> formulaDenote (swapper f).\n  induction f; crush.\nQed.\n\nCheck formula_ind.\n\nInductive term : Set := App | Abs.\nReset term.\nDefinition uhoh := O.\n\nPrint nat_ind.\nCheck nat_rect.\nPrint nat_rec.\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\nPrint plus_recursive.\nPrint nat_rec.\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.\n  reflexivity.\nQed.\n\nPrint nat_rect.\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\nSection nat_ind'.\n  Variable P : nat -> Prop.\n  Hypothesis O_case : P O.\n  Hypothesis S_case : forall n : nat, P n -> P (S n).\n\n  Fixpoint nat_ind' (n : nat) : P n :=\n    match n with\n      | O => O_case\n      | S n' => S_case (nat_ind' n')\n    end.\nEnd nat_ind'.\n\nPrint even_list_mut.\nSection even_list_mut'.\n\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'.\n\nSection formula_ind'.\n  Variable P : formula -> Prop.\n  Hypothesis Eq_case : forall n1 n2 : nat, P (Eq n1 n2).\n  Hypothesis And_case : forall f1 f2 : formula,\n    P f1 -> P f2 -> P (And f1 f2).\n  Hypothesis Forall_case : forall f : nat -> formula,\n    (forall n : nat, P (f n)) -> P (Forall f).\n\n  Fixpoint formula_ind' (f : formula) : P f :=\n    match f with\n      | Eq n1 n2 => Eq_case n1 n2\n      | And f1 f2 => And_case (formula_ind' f1) (formula_ind' f2)\n      | Forall f' => Forall_case f' (fun n => formula_ind' (f' n))\n    end.\nEnd formula_ind'.\n\nInductive nat_tree : Set :=\n| NNode' : nat -> mylist nat_tree -> nat_tree.\n\nCheck Forall.\n\nCheck nat_tree_ind.\n\nSection All.\n  Variable T : Set.\n  Variable P : T -> Prop.\n\n  Fixpoint All (ls : mylist T) : Prop :=\n    match ls with\n      | Nil => True\n      | Cons h t => P h /\\ All t\n    end.\nEnd All.\n\nPrint True.\nLocate \"/\\\".\n\nPrint and.\nSection nat_tree_ind'.\n  Variable P : nat_tree -> Prop.\n\n  Hypothesis NNode'_case : forall (n : nat) (ls : mylist nat_tree),\n    All P ls -> P (NNode' n ls).\n\n  Definition list_nat_tree_ind := O.\n\n  Fixpoint 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 : mylist 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) ls)\n    end.\n\nEnd nat_tree_ind'.\n\nSection map.\n  Variables T T' : Set.\n  Variable F : T -> T'.\n\n  Fixpoint map (ls : mylist T) : mylist 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 : mylist nat) : nat :=\n  match ls with\n    | Nil => O\n    | Cons h t => plus h (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 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 trs) => NNode' n (Cons (ntsplice tr tr2) trs)\n  end.\n\nLemma plus_S : forall n1 n2 : nat,\n  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)\n  = plus (ntsize tr2) (ntsize tr1).\n  induction tr1 using nat_tree_ind'; crush.\n  destruct ls; crush.\nRestart.\n  Hint Extern 1 (ntsize (match ?LS with Nil => _ | Cons _ _ => _ end) = _) =>\n    destruct LS; crush.\n  induction tr1 using nat_tree_ind'; crush.\nQed.\n\nPrint red.\nLocate red.\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(* begin thide *)\n  intros n m H.\n  change (pred (S n) = pred (S m)).\n  rewrite H.\n  reflexivity.\nQed.\n", "meta": {"author": "haoyang9804", "repo": "CPDT", "sha": "ab053fe3c88ab66a6a514ddbfdbbec6744d34e7d", "save_path": "github-repos/coq/haoyang9804-CPDT", "path": "github-repos/coq/haoyang9804-CPDT/CPDT-ab053fe3c88ab66a6a514ddbfdbbec6744d34e7d/src/InductiveTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.877476785879798, "lm_q1q2_score": 0.7785014379296622}}
{"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 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. *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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, recommendedM (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  (* 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, advancedM (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  (* 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\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n   (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 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 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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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 : Type} (P : T -> Prop) (l : list T) : Prop\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 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\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. *)\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** We've seen two different ways of encoding logical facts in Coq:\n    with _booleans_ (of type [bool]), and with _propositions_ (of type\n    [Prop]).\n\n    For instance, to claim that a number [n] is even, we can say\n    either\n       - (1) that [evenb n] returns [true], or\n       - (2) that there exists some [k] such that [n = double k].\n             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  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* FILL IN HERE *) Admitted.\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, while 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  (* FILL IN HERE *) Admitted.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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(* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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\n(* FILL IN HERE *)\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7783633980957237}}
{"text": "\n\n\n\n(* ------------------ Descriptions--------------------------------------------------\n\n In this file we define the concept of Stable Set, Cliq and Coloring for an undirected\n graph.  We also define boolean functions to check these properties. We connect these \n properties with boolean functions using reflection lemmas.\n \n Predicate              Boolean function       Joining Lemma\n Stable G I             stable G I             stableP\n Max_I_in G I           max_I_in G I           max_I_inP\n Cliq G K               cliq G K               cliqP\n Max_K_in G K           max_K_in G K           max_K_inP\n Coloring_of G f        coloring_of G f        coloring_ofP\n\n\n (Max_I_in G I) declares that I is a maximum size stable set in G. \n (Max_K_in G I) declares that K is a maximum size cliq in G. \n\n Definition Stable_in (G: dG)(I: list A):= I [<=] G /\\ IsOrd I /\\ Stable G I.\n Definition Cliq_in (G: dG)(K: list A):Prop := K [<=] G /\\ IsOrd K /\\ Cliq G K.\n\n Definition i_num (G: dG)(n:nat):= exists I, Max_I_in G I /\\ |I|=n.\n Definition cliq_num (G: dG)(n:nat):= exists K, Max_K_in G K /\\ |K|=n.\n\n Definition clrs_of (f:A->nat) (l:list A): list nat:= (img f l).\n Definition chrom_num (G: dG) (n: nat):= \n                              exists f, Best_coloring_of G f /\\ | clrs_of f G | = n.\n\n We also define the notion of a perfect graph as follows:\n \n Definition Nice (G: dG): Prop:= forall n, cliq_num G n -> chrom_num G n.\n Definition Perfect (G: dG): Prop:= forall G1, Ind_subgraph G1 G -> Nice G1.\n \n---------------------------------------------------------------------------------------*)\n\n\nRequire Export DecUG.\n\nSet Implicit Arguments.\n\nSection MoreOnDecidableGraphs.\n\n  Context { A: ordType }.\n\n  \n  (*------------  Stable set and independence number in a graph G ------------*)\n  Definition Stable (G: dG)(I: list A): Prop:=\n    (forall x y, In x I-> In y I -> edg G x y = false).\n  Definition stable (G: dG)(I: list A):=\n    (forall_xyb (fun x y => edg G x y == false) I).\n\n  Definition Stable_in (G: dG)(I: list A):= I [<=] G /\\ IsOrd I /\\ Stable G I.\n\n  Lemma Stable_elim (G:dG)(I: list A)(x y:A): Stable G I -> In x I-> In y I-> edg G x y = false.\n  Proof. { intros H Hx Hy.  unfold Stable in H. specialize (H x y Hx Hy) as H'. auto. } Qed.\n  Lemma Stable_in_elim (G:dG)(I: list A): Stable_in G I -> Stable G I.\n  Proof. intro H; apply H. Qed.\n  Lemma Stable_in_elim1 (G: dG)(I: list A): Stable_in G I -> I [<=] G.\n  Proof. intro H; apply H. Qed.\n  Lemma Stable_in_elim2 (G:dG)(I: list A): Stable_in G I -> IsOrd I.\n  Proof. intro H; apply H. Qed.\n  \n  Lemma stableP (G: dG)(I: list A): reflect (Stable G I) (stable G I).\n  Proof. { apply reflect_intro. split;unfold stable; unfold Stable.\n         {  intro H.  apply /forall_xyP; intros; apply /eqP; auto. }\n         {  intro H. move /forall_xyP in H. intros x y H1 H2; apply /eqP; auto. } } Qed.\n  Lemma nil_is_stable (G: dG): stable G nil.\n  Proof. unfold stable. apply /forall_xyP. auto. Qed.\n\n  \n  Hint Resolve Stable_in_elim Stable_in_elim1 Stable_in_elim2: core.\n  Hint Resolve stableP nil_is_stable: core.\n  \n  Definition Max_I_in (G: dG)(I: list A):= Max_sub_in G I (fun I => stable G I).\n  Definition max_I_in (G: dG)(I: list A):= max_sub_in G I (fun I => stable G I).\n\n  Lemma max_I_inP (G: dG)(I:list A): reflect (Max_I_in G I)(max_I_in G I).\n  Proof. apply max_sub_inP; auto. Qed.\n\n  Lemma exists_Max_I_in (G: dG): exists I, Max_I_in G I.\n  Proof. { specialize (exists_largest_in G (fun I=> stable G I)).\n         intro H.\n         assert (Ha: exists X : list A, In X (pw G) /\\ (fun I : list A => stable G I) X).\n         { exists nil. split; auto. }\n         apply H in Ha as Hb. destruct Hb as [I0 Hb]. exists I0.\n         unfold Max_I_in; unfold Max_sub_in;destruct Hb as [Hb Hc]; destruct Hc as [Hc Hd].\n         split.\n         {  auto. }\n         split.\n         { eauto. }\n         split.\n         { auto. }\n         { intros. apply Hd. auto. auto. } } Qed.\n  \n  Definition i_num (G:dG)(n:nat):= exists I, Max_I_in G I /\\ |I|=n.\n  Lemma i_num_of (G: dG): exists n, i_num G n.\n  Proof. { specialize (exists_Max_I_in G) as HI. destruct HI as [I H].\n           exists (|I|). unfold i_num. exists I. split; auto.  } Qed.\n  \n  (* Use of above lemma can be:  destruct (i_num_of G) as [n H]. *)\n  \n \n  Lemma Max_I_in_elim1 (G: dG)(I: list A): Max_I_in G I -> Stable G I.\n  Proof. intro H. apply /stableP. apply H.  Qed.\n  Lemma Max_I_in_elim2 (G: dG)(I: list A): Max_I_in G I -> Stable_in G I.\n  Proof. intro H. unfold Stable_in. split. eauto.  split. eauto. apply /stableP. apply H.  Qed.\n  \n  Lemma Max_I_in_elim3 (G: dG)(I X: list A):\n    Max_I_in G I ->  IsOrd X -> X [<=] G-> Stable G X -> |X| <= |I|.\n  Proof. { intros H H1 H2 H3. destruct H as [Ha H]; destruct H as [Hb H].\n           apply H; auto. apply /stableP;auto.  } Qed.\n\n  Lemma Max_I_in_elim (G: dG)(I X: list A):\n    Max_I_in G I ->  Stable_in G X -> |X| <= |I|.\n  Proof. intros H H1. eapply Max_I_in_elim3 with (G:=G). all:auto. eauto. Qed.\n  \n  Lemma Max_I_in_intro (G: dG)( I: list A):\n    Stable_in G I -> (forall I', Stable_in G I' -> |I'| <= |I|) -> Max_I_in G I.\n  Proof. { intros H H1. unfold Max_I_in. unfold Max_sub_in.\n         split. auto. split. apply H. split. apply /stableP. apply H.\n         intros I' H2 H3. apply H1. split. auto. split. eauto.\n         apply /stableP;auto. } Qed.\n\n   Hint Resolve max_I_inP exists_Max_I_in Max_I_in_elim1 Max_I_in_elim2 : core.\n  \n  Lemma i_num_same (G: dG)(n m:nat): i_num G n -> i_num G m -> n=m.\n  Proof. {  intros Hn Hm.\n           destruct Hn as [I1 Hn]. destruct Hm as [I2 Hm].\n           cut (n<=m /\\ m<=n). omega.\n           destruct Hn as [Hn1 Hn2]. destruct Hm as [Hm1 Hm2].\n           unfold Max_I_in in Hn1.  unfold Max_I_in in Hm1.\n           split; subst n; subst m; eapply Max_I_in_elim3;eauto. } Qed.\n\n  Hint Resolve i_num_same : core.\n\n  Lemma Stable_in_HG (H G:dG)(I: list A): Ind_subgraph H G-> Stable_in H I-> Stable_in G I.\n  Proof. { unfold Stable_in. intros h0 h1. unfold Ind_subgraph in h0.\n         destruct h0 as [h0 h]. destruct h1 as [h2 h1]. destruct h1 as [h3 h1].\n         repeat try (split;auto). unfold Stable. intros x y h4 h5.\n         replace (edg G x y) with (edg H x y). apply h1;auto. auto. } Qed.\n  \n  Lemma i_num_HG (H G: dG)(m n:nat): Ind_subgraph H G-> i_num H m -> i_num G n-> m<=n.\n  Proof. { intro h. unfold i_num. intros h1 h2.\n         destruct h1 as [I h1]. destruct h1 as [h1 hm].\n         destruct h2 as [Ig h2]. destruct h2 as [h2 hn].\n         assert (h3: Stable_in G I).\n         { cut (Stable_in H I). eauto using Stable_in_HG. auto. }\n         subst n. subst m.  eapply Max_I_in_elim; eauto. } Qed.\n   \n  Hint Immediate Stable_in_HG i_num_HG:core.\n    \n  (*-----  Cliq and the Cliq number for a given graph G ----------------------*)\n  \n  Definition Cliq (G:dG)(K: list A):Prop := (forall x y, In x K-> In y K -> x=y \\/ edg G x y).\n  Definition cliq (G:dG)(K: list A):bool:= forall_xyb (fun x y=> (x==y) || edg G x y) K.\n\n  Definition Cliq_in (G:dG)(K: list A):Prop := K [<=] G /\\ IsOrd K /\\ Cliq G K.\n\n  Lemma Cliq_elim (G:dG)(K: list A)(x y:A): Cliq G K -> In x K-> In y K-> x<>y -> edg G x y.\n  Proof. { intros H Hx Hy H1.  unfold Cliq in H. specialize (H x y Hx Hy) as H'.\n           destruct H'. contradiction. auto. } Qed.\n  Lemma Cliq_in_elim (G:dG)(K: list A): Cliq_in G K -> Cliq G K.\n  Proof. intro H; apply H. Qed.\n  Lemma Cliq_in_elim1 (G:dG)(K: list A): Cliq_in G K -> K [<=] G.\n  Proof. intro H; apply H. Qed.\n  Lemma Cliq_in_elim2 (G:dG)(K: list A): Cliq_in G K -> IsOrd K.\n  Proof. intro H; apply H. Qed.\n\n  Lemma cliqP (G: dG)(K: list A): reflect (Cliq G K) (cliq G K).\n  Proof. { apply reflect_intro. split;unfold cliq; unfold Cliq.\n           {  intro H. apply /forall_xyP.  intros x y H0 H1. apply /orP.\n              specialize (H x y H0 H1) as H2. destruct H2; auto. }\n           {  intro H. move /forall_xyP in H. intros x  y H0 H1.\n              specialize (H x y H0 H1) as H2. move /orP in H2. destruct H2; auto. } } Qed.\n  \n   Lemma nil_is_cliq (G: dG): cliq G nil.\n   Proof. unfold cliq. apply /forall_xyP. auto. Qed.\n\n   Hint Resolve Cliq_in_elim Cliq_in_elim1 Cliq_in_elim2: core.\n   Hint Resolve Cliq_elim cliqP nil_is_cliq: core.\n\n  Definition Max_K_in (G: dG)(K: list A):= Max_sub_in G K (fun K => cliq G K).\n  Definition max_K_in (G: dG)(K: list A):= max_sub_in G K (fun K => cliq G K).\n\n  Lemma max_K_inP (G: dG)(K:list A): reflect (Max_K_in G K)(max_K_in G K).\n  Proof. apply max_sub_inP; auto. Qed.\n\n  Lemma exists_Max_K_in (G: dG): exists K, Max_K_in G K.\n  Proof. { specialize (exists_largest_in G (fun K=> cliq G K)).\n         intro H.\n         assert (Ha: exists X : list A, In X (pw G) /\\ (fun K : list A => cliq G K) X).\n         { exists nil. split; auto. }\n         apply H in Ha as Hb. destruct Hb as [K0 Hb]. exists K0.\n         unfold Max_K_in; unfold Max_sub_in;destruct Hb as [Hb Hc]; destruct Hc as [Hc Hd].\n         split.\n         {  auto. }\n         split.\n         { eauto. }\n         split.\n         { auto. }\n         { intros. apply Hd. auto. auto. } } Qed.\n\n\n  Definition cliq_num (G:dG)(n:nat):= exists K, Max_K_in G K /\\ |K|=n.\n  \n  Lemma cliq_num_of (G: dG): exists n, cliq_num G n.\n  Proof. { specialize (exists_Max_K_in G) as HK. destruct HK as [K H].\n           exists (|K|). unfold cliq_num. exists K. split;auto.  } Qed.\n  \n  (* Use of above lemma can be :  destruct (cliq_num_of G) as [n H]. *)\n  \n  Lemma Max_K_in_elim1 (G: dG)(K: list A): Max_K_in G K -> Cliq G K.\n  Proof. intro H. apply /cliqP. apply H.  Qed.\n  Lemma Max_K_in_elim2 (G: dG)(K: list A): Max_K_in G K -> Cliq_in G K.\n  Proof. intro H. unfold Cliq_in. split. eauto.  split. eauto. apply /cliqP. apply H.  Qed.\n  Lemma Max_K_in_elim3 (G: dG)(K X: list A):\n    Max_K_in G K ->  IsOrd X -> X [<=] G-> Cliq G X -> |X| <= |K|.\n  Proof. { intros H H1 H2 H3. destruct H as [Ha H]; destruct H as [Hb H].\n           apply H; auto. apply /cliqP;auto. } Qed.\n  \n  Lemma Max_K_in_elim (G: dG)(K X: list A):\n    Max_K_in G K ->  Cliq_in G X -> |X| <= |K|.\n  Proof. intros H H1. eapply Max_K_in_elim3 with (G:=G). all:auto. eauto. Qed.\n  \n  Lemma Max_K_in_intro (G: dG)( K: list A):\n    Cliq_in G K -> (forall K', Cliq_in G K' -> |K'| <= |K|) -> Max_K_in G K.\n  Proof. { intros H H1. unfold Max_K_in. unfold Max_sub_in.\n         split. auto. split. apply H. split. apply /cliqP. apply H.\n         intros K' H2 H3. apply H1. split. auto. split. eauto.\n         apply /cliqP;auto. } Qed.\n  \n  \n\n  Hint Resolve max_K_inP exists_Max_K_in Max_K_in_elim1 Max_K_in_elim2 : core.\n  \n  Lemma cliq_num_same (G: dG)(n m:nat): cliq_num G n -> cliq_num G m -> n=m.\n  Proof.  {  intros Hn Hm.\n           destruct Hn as [K1 Hn]. destruct Hm as [K2 Hm].\n           cut (n<=m /\\ m<=n). omega.\n           destruct Hn as [Hn1 Hn2]. destruct Hm as [Hm1 Hm2].\n           unfold Max_K_in in Hn1.  unfold Max_K_in in Hm1.\n           split; subst n; subst m; eapply Max_K_in_elim3;eauto. } Qed.\n\n  Hint Resolve cliq_num_same:core.\n\n  Lemma Cliq_in_HG (H G:dG)(K: list A): Ind_subgraph H G-> Cliq_in H K-> Cliq_in G K.\n  Proof. { unfold Cliq_in. intros h0 h1. unfold Ind_subgraph in h0.\n         destruct h0 as [h0 h]. destruct h1 as [h2 h1]. destruct h1 as [h3 h1].\n         repeat try (split;auto). unfold Cliq. intros x y h4 h5.\n         replace (edg G x y) with (edg H x y). apply h1;auto. auto. } Qed.\n  Lemma cliq_num_HG (H G: dG)(m n:nat): Ind_subgraph H G-> cliq_num H m -> cliq_num G n-> m<=n.\n  Proof. { intro h. unfold cliq_num. intros h1 h2.\n         destruct h1 as [I h1]. destruct h1 as [h1 hm].\n         destruct h2 as [Ig h2]. destruct h2 as [h2 hn].\n         assert (h3: Cliq_in G I).\n         { cut (Cliq_in H I). eauto using Cliq_in_HG. auto. }\n         subst n. subst m.  eapply Max_K_in_elim; eauto. } Qed.\n   \n  Hint Immediate Cliq_in_HG cliq_num_HG:core.\n \n   \n   (*------ Concepts of Coloring and the chromatic number of a graph G ------------------*)\n  Definition Coloring_of (G: dG)(f: A-> nat): Prop:=\n    forall x y, In x G-> In y G -> edg G x y -> f x <> f y.\n  \n  Definition coloring_of (G: dG)(f: A-> nat):bool:=\n    forall_xyb (fun x y => negb (edg G x y)|| negb (f x == f y)) G.\n  Lemma coloring_ofP (G: dG)(f: A->nat): reflect (Coloring_of G f)(coloring_of G f).\n  Proof. { apply reflect_intro. unfold coloring_of;unfold Coloring_of.\n         split.\n         { intro H; apply /forall_xyP; intros x y Hx Hy; apply /impP.\n           intro H1; apply /negP; move /eqP; apply H;auto. }\n         { move /forall_xyP. intro H. intros x y Hx Hy.\n           specialize (H x y Hx Hy) as H1; move /impP in H1; intro H2.\n           apply H1 in H2 as H3; move /negP in H3; move /eqP; auto. } } Qed.\n        \n  Lemma exists_coloring (G: dG): exists f, Coloring_of G f.\n  Proof. { exists ( fun x => idx x G).  unfold Coloring_of.\n         intros x y Hx Hy HE. apply diff_index. all: auto.\n         eapply no_self_edg;eauto. } Qed.\n\n   \n  Definition clrs_of (f:A->nat) (l:list A): list nat:= (img f l).\n   \n   Definition Best_coloring_of (G: dG) (f:A->nat): Prop :=\n     Coloring_of G f /\\ (forall f1, Coloring_of G f1 -> | clrs_of f G | <= | clrs_of f1 G|).\n   \n   Definition chrom_num (G: dG) (n: nat):= exists f, Best_coloring_of G f /\\ | clrs_of f G | = n.\n\n   Lemma best_clrs_same_size (G: dG)(f1 f2: A->nat):\n     Best_coloring_of G f1 -> Best_coloring_of G f2 -> |clrs_of f1 G|=|clrs_of f2 G|.\n   Proof.  { intros h1 h2. destruct h1 as [h1a h1];destruct h2 as [h2a h2].\n           cut((| clrs_of f1 G |) <= (| clrs_of f2 G |)).\n           cut ((| clrs_of f2 G |) <= (| clrs_of f1 G |)). omega. all: eauto. } Qed.\n   Lemma chrom_num_same (G:dG)(n m:nat): chrom_num G n-> chrom_num G m -> n=m.\n   Proof. { intros h1 h2. destruct h1 as [f1 h1]. destruct h1 as [h1a h1].\n          destruct h2 as [f2 h2]. destruct h2 as [h2a h2]. subst m;subst n.\n          apply best_clrs_same_size;auto. } Qed. \n\n   Lemma clrs_of_inc (K1: list A)(K2: list A)(f:A-> nat):\n     K1 [<=] K2 -> (clrs_of f K1) [<=] (clrs_of f K2).\n   Proof.  unfold clrs_of; auto. Qed.\n   Lemma clrs_of_inc1 (K1: list A)(K2: list A)(f: A->nat):\n     K1 [<=] K2 -> |(clrs_of f K1)| <= |(clrs_of f K2)|.\n   Proof. unfold clrs_of; auto. Qed.\n   \n   Hint Resolve chrom_num_same clrs_of_inc clrs_of_inc1: core.\n\n   Lemma coloring_of_HG (H G: dG)(f: A-> nat): Ind_subgraph H G-> Coloring_of G f-> Coloring_of H f.\n   Proof. { unfold Coloring_of. intros h0 h1. unfold Ind_subgraph in h0.\n            destruct h0 as [h0 h]. intros x y h2 h3 h4.\n            apply h1. all: try auto. replace (edg G x y) with (edg H x y); auto. } Qed.\n   Lemma chrom_num_HG (H G: dG)(m n: nat): Ind_subgraph H G-> chrom_num H m-> chrom_num G n-> m<=n.\n   Proof. { intro h. unfold chrom_num. intros h1 h2.\n           destruct h1 as [fh h1]. destruct h1 as [h1 hm].\n           destruct h2 as [fg h2]. destruct h2 as [h2 hn].\n           assert (h3: Coloring_of H fg).\n           { cut (Coloring_of G fg). eauto using coloring_of_HG. apply h2.  }\n           subst n. subst m.\n           cut ( (| clrs_of fh H |) <= (| clrs_of fg H |)).\n           cut ( (| clrs_of fg H |) <= (| clrs_of fg G |)). omega.\n           cut (H [<=] G). auto. apply h.  apply h1; auto. } Qed.\n\n   Hint Immediate coloring_of_HG chrom_num_HG: core.\n   \n   (*----- Think about the proof of existence of a best coloring----------------------------*)\n\n   \n   (*-------- Concepts of nice graph and  perfect graphs -------------------------------- *)\n   Definition Nice (G: dG): Prop:= forall n, cliq_num G n -> chrom_num G n.\n   Definition Perfect (G: dG): Prop:= forall G1, Ind_subgraph G1 G -> Nice G1.\n      \n   Lemma perfect_is_nice (G: dG): Perfect G -> Nice G.\n   Proof.  unfold Perfect. intros H; apply H. auto.  Qed.\n\n   Hint Resolve perfect_is_nice: core.\n\n   Lemma perfect_sub_perfect (G H: dG): Perfect G-> Ind_subgraph H G-> Perfect H.\n   Proof. unfold Perfect. intros. cut (Ind_subgraph G1 G). auto. eauto. Qed.\n   \n    \n   (*---------  More colors needed than the largest cliq size --------------------------*)\n\n   Lemma clrs_on_a_cliq  (G: dG)(K: list A)(f: A->nat):\n     Cliq_in G K-> Coloring_of G f -> |K| = |clrs_of f K|.\n   Proof. { intros H H1.\n            unfold clrs_of. match_up (|K|) (| img f K|).\n            { auto. }\n            { cut (| img f K| <= |K|).\n              move /ltP in H0. intro H2. omega. auto. }\n            { move /ltP in H0.\n              assert (H2: ~ one_one_on K f).\n              { cut(NoDup K). eauto. unfold Cliq_in in H.\n                cut (IsOrd K). auto. apply H. }\n              unfold one_one_on in H2. unfold Coloring_of in H1.\n              absurd (forall x y : A, In x K -> In y K -> x <> y -> f x <> f y).\n              apply H2. intros x y Hx Hy Hxy. \n              destruct H as [Ha H]. destruct H as [Hb H].\n              apply H1;auto.  eapply Cliq_elim;eauto. } }  Qed.\n   \n   Lemma more_clrs_than_cliq_size (G: dG)(K: list A)(f: A->nat):\n     Cliq_in G K-> Coloring_of G f -> |K| <= |clrs_of f G|.\n   Proof. { intros H H1.\n          assert (H2: | K | = |clrs_of f K|).\n          { unfold clrs_of. match_up (|K|) (| img f K|).\n            { auto. }\n            { cut (| img f K| <= |K|).\n              move /ltP in H0. intro H2. omega. auto. }\n            { move /ltP in H0.\n              assert (H2: ~ one_one_on K f).\n              { cut(NoDup K). eauto. unfold Cliq_in in H.\n                cut (IsOrd K). auto. apply H. }\n              unfold one_one_on in H2. unfold Coloring_of in H1.\n              absurd (forall x y : A, In x K -> In y K -> x <> y -> f x <> f y).\n              apply H2. intros x y Hx Hy Hxy. \n              destruct H as [Ha H]. destruct H as [Hb H].\n              apply H1;auto.  eapply Cliq_elim;eauto. } }    \n          cut (|clrs_of f K| <= | clrs_of f G|). omega. \n          destruct H as [H H']. auto. } Qed.\n   \n   Lemma more_clrs_than_cliq_num (G: dG)(n:nat)(f: A->nat):\n     cliq_num G n-> Coloring_of G f -> n <= |clrs_of f G|.\n   Proof. { intros H H1. destruct H as [K H]. destruct H as [Ha H].\n          assert (H2: Cliq_in G K); auto. subst n.\n          apply more_clrs_than_cliq_size;auto. } Qed.\n\n   (*---------Some other properties of graph --------------------------*)\n\n   Lemma nice_intro (G: dG)(n:nat):\n     cliq_num G n -> (exists f, Coloring_of G f /\\ |clrs_of f G|= n)-> Nice G.\n   Proof. { intros H H1 m H2. assert (Hnm: n=m); eauto; subst m. clear H2.\n          destruct H1 as [f H1].\n          unfold chrom_num. exists f.\n          destruct H1 as [H1 HR]. split. \n          { unfold Best_coloring_of. split.\n            { auto. }\n            rewrite HR. intro f1. apply more_clrs_than_cliq_num;auto. }\n          { auto. } } Qed.\n            \n   Hint Immediate perfect_sub_perfect more_clrs_than_cliq_size more_clrs_than_cliq_num: core.\n   Hint Immediate nice_intro: core.\n   \nEnd MoreOnDecidableGraphs.\n\n\n\n\n Hint Resolve Stable_in_elim Stable_in_elim1 Stable_in_elim2: core.\n Hint Resolve stableP nil_is_stable: core.\n Hint Resolve max_I_inP exists_Max_I_in Max_I_in_elim1 Max_I_in_elim2 : core.\n Hint Resolve i_num_same:core.\n Hint Immediate Stable_in_HG i_num_HG:core.\n\n Hint Resolve Cliq_in_elim Cliq_in_elim1 Cliq_in_elim2: core.\n Hint Resolve  Cliq_elim cliqP nil_is_cliq: core.\n Hint Resolve max_K_inP exists_Max_K_in  Max_K_in_elim1 Max_K_in_elim2: core.\n Hint Resolve cliq_num_same:core.\n Hint Immediate Cliq_in_HG cliq_num_HG:core.\n \n Hint Resolve chrom_num_same clrs_of_inc clrs_of_inc1: core.\n Hint Immediate coloring_of_HG chrom_num_HG: core.\n \n Hint Resolve perfect_is_nice: core.\n Hint Immediate perfect_sub_perfect more_clrs_than_cliq_size more_clrs_than_cliq_num: core.\n Hint Resolve clrs_on_a_cliq: core.\n Hint Immediate nice_intro: 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/MoreDecUG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.7783633823120182}}
{"text": "Require Import Coq.Arith.Div2.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import N_Z_nat_conversions.\nRequire Export Lia Nlia.\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; lia.\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  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 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.\nQed.\n\nTheorem pow2_N : forall n, Npow2 n = N.of_nat (pow2 n).\nProof.\n  intro n.\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 = \n    ltac:(match eval hnf in (1 mod 0) with | 0 => exact 0 | _ => exact 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. cbn 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": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/rupicola/bedrock2/deps/kami/Kami/Lib/NatLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417881, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7782634816003812}}
{"text": "From sorting Require Export Utils.\nFrom sorting Require Export Sorted.\n\n\n(** * Definition  *)\n\nFixpoint select (x : nat) (l : list nat) : nat * list nat :=\n  match 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')\n  end.\n\nFixpoint selsort (l : list nat) (n : nat) {struct n} :=\n  match 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\n  end.\n\nDefinition selection_sort (l : list nat) :=\n  selsort l (length l).\n\n\n(** * Correctness goal  *)\n\nDefinition selection_sort_correct : Prop :=\n  is_a_sorting_algorithm selection_sort.\n\n\n(** * Permutations *)\n\nLemma select_perm:\n  forall (x : nat) (l : list nat),\n    let (y, r) := select x l in Permutation (x :: l) (y :: r).\nProof.\n  intros x l; revert x.\n  induction l; intros; simpl in *. {\n    apply Permutation_refl.\n  } {\n    unfold select.\n    bdestruct (x <=? a); fold select. {\n      specialize (IHl x).\n      destruct (select x l) eqn:Seq.\n      apply perm_trans with (a :: n :: l0). {\n        apply Permutation_sym.\n        apply perm_trans with (a :: x :: l). {\n          now apply perm_skip.\n        } {\n          apply perm_swap.\n        }\n      } {\n        apply perm_swap.\n      }\n    } {\n      specialize (IHl a).\n      destruct (select a l) eqn:Seq.\n      apply perm_trans with (x :: n :: l0). {\n        now apply perm_skip.\n      } {\n        apply perm_swap.\n      }\n    }\n  }\nQed.\n\nLemma selsort_perm:\n  forall (n : nat) (l : list nat), length l = n -> Permutation l (selsort l n).\nProof.\n  induction n. {\n    intros.\n    destruct l. {\n      apply perm_nil.\n    } {\n      inversion H.\n    }\n  } {\n    intros.\n    destruct l. {\n      intros.\n      inversion H.\n    } {\n      simpl.\n      destruct (select n0 l) eqn:Seq.\n      apply perm_trans with (n1 :: l0). {\n        assert (let (y, r) := select n0 l in Permutation (n0 :: l) (y :: r)). {\n          apply (select_perm n0 l).\n        }\n        destruct (select n0 l).\n        inv Seq.\n        apply H0.\n      } {\n        apply perm_skip.\n        apply IHn.\n        assert (length (n0::l) = (length (n1::l0))). {\n          apply Permutation_length.\n          assert (let (y, r) := select n0 l in Permutation (n0 :: l) (y :: r)). {\n            apply (select_perm n0 l).\n          }\n          destruct (select n0 l).\n          inv Seq.\n          apply H0.\n        }\n        inv H0.\n        inv H.\n        reflexivity.\n      }\n    }\n  }\nQed.\n\nTheorem selection_sort_perm:\n  forall (l : list nat), Permutation l (selection_sort l).\nProof.\n  unfold selection_sort.\n  intros.\n  apply selsort_perm.\n  reflexivity.\nQed.\n\n\n(** * [select] selects the smallest element of a list *)\n\nLemma select_smallest_aux:\n  forall (x : nat) (al : list nat) (y : nat) (bl : list nat),\n    Forall (fun z => y <= z) bl ->\n    select x al = (y,bl) ->\n    y <= x.\nProof.\n  intros.\n  pose (select_perm x al).\n  rewrite H0 in y0.\n  apply (Permutation_in x) in y0. {\n    destruct y0. {\n      omega.\n    } {\n      rewrite Forall_forall in H.\n      apply H.\n      apply H1.\n    }\n  } {\n    apply in_eq.\n  }\nQed.\n\nTheorem select_smallest:\n  forall (x : nat) (al : list nat) (y : nat) (bl : list nat),\n    select x al = (y,bl) ->\n    Forall (fun z => y <= z) bl.\nProof.\n  intros x al.\n  revert x.\n  induction al; intros; simpl in *. {\n    inv H.\n    easy.\n  } {\n    bdestruct (x <=? a). {\n      destruct select eqn:Seq.\n      inv H.\n      apply Forall_cons. {\n        apply (le_trans y x a). {\n          apply (select_smallest_aux x al y l). {\n            apply (IHal x y l).\n            easy.\n          } {\n            easy.\n          }\n        } {\n          easy.\n        }\n      } {\n        apply (IHal x y l).\n        easy.\n      }\n    } {\n      destruct (select a al) eqn:?H.\n      inv H.\n      apply Forall_cons. {\n        assert (y <= a). {\n          apply (select_smallest_aux a al y l). {\n            apply (IHal a y l).\n            apply H1.\n          } {\n            apply H1.\n          }\n        }\n        omega.\n      } {\n        apply (IHal a y l).\n        easy.\n      }\n    }\n  }\nQed.\n\n\n(** * A list applied with selection sort is sorted **)\n\nLemma selection_sort_sorted_aux:\n  forall (y : nat) (bl : list nat),\n   sorted (selsort bl (length bl)) ->\n   Forall (fun z : nat => y <= z) bl ->\n   sorted (y :: selsort bl (length bl)).\nProof.\n  induction bl. {\n    simpl.\n    intros.\n    apply sorted_1.\n  } {\n    intros.\n    simpl in *.\n    destruct select eqn:Seq.\n    apply sorted_cons. {\n      rewrite Forall_forall in H0.\n      apply H0.\n      apply Permutation_in with (n :: l). {\n        pose (select_perm a bl).\n        rewrite Seq in y0.\n        apply Permutation_sym.\n        apply y0.\n      } {\n        apply in_eq.\n      }\n    } {\n      apply H.\n    }\n  }\nQed.\n\nTheorem selection_sort_sorted:\n  forall (al : list nat), sorted (selection_sort al).\nProof.\n  intros.\n  unfold selection_sort.\n  remember (length al) as n.\n  generalize dependent al.\n  induction n. {\n    intros.\n    simpl.\n    destruct al. {\n      apply sorted_nil.\n    } {\n      apply sorted_nil.\n    }\n  } {\n    intros.\n    destruct al. {\n      apply sorted_nil.\n    } {\n      unfold selsort.\n      fold selsort.\n      destruct (select n0 al) eqn:Seq.\n      pose (select_perm n0 al).\n      rewrite Seq in y.\n      apply Permutation_length in y.\n      rewrite <- Heqn in y.\n      inversion y.\n      apply (selection_sort_sorted_aux n1 l). {\n        rewrite <- H0.\n        apply IHn.\n        apply H0.\n      } {\n        apply (select_smallest n0 al n1 l).\n        apply Seq.\n      }\n    }\n  }\nQed.\n\n\n(** * Wrapping up **)\n\nTheorem selection_sort_is_correct:\n  selection_sort_correct.\nProof.\n  split.\n  apply selection_sort_perm.\n  apply selection_sort_sorted.\nQed.\n", "meta": {"author": "joseoliveirajr", "repo": "sorting", "sha": "a55ab8f6270d71b21df2175a871997ba3876812f", "save_path": "github-repos/coq/joseoliveirajr-sorting", "path": "github-repos/coq/joseoliveirajr-sorting/sorting-a55ab8f6270d71b21df2175a871997ba3876812f/SelectionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7782224804929514}}
{"text": "Section LPPO_1.\nVariable D: Set.\nVariable c d e :D.\nVariable P Q T: D-> Prop.\n(*1*)\nTheorem pred_008 : ~(forall x, P x) -> ~ forall x, P x /\\ Q x.\nProof.\nintros.\nintro.\napply H.\nintro.\ndestruct H.\nintro x0.\napply H0.\nQed.\n(*2*)\nTheorem pred_013 : (exists x, P x \\/ Q x) -> (forall x, ~Q x) -> exists x, P x.\nProof.\nintro.\ndestruct H.\nexists x.\ndestruct H.\nassumption.\napply H0 in H.\ncontradiction.\nQed.\n(*3*)\nTheorem pred_025 : ~(forall x, P x /\\ Q x) /\\ (forall x, P x) -> ~forall x, Q x.\nProof.\nintros.\nintro.\ndestruct H.\napply H.\nintro.\nsplit.\napply H1.\napply H0.\nQed.\n(*4*)\nTheorem pred_035 : (forall y, Q y -> ~exists x, P x) /\\ (forall x, P x) -> forall y, ~Q y.\nProof.\nintro.\ndestruct H.\nintros.\nintro.\napply H in H1.\napply H1.\nexists y.\napply H0.\nQed.\n(*5*)\nTheorem pred_067 : (forall x, ~P x) -> ~exists x, P x.\nProof.\nintros.\nintro.\ndestruct H0.\napply H in H0.\nassumption.\nQed.\nEnd LPPO_1.\nSection LPPO_2.\nVariable A : Set.\nVariables (P Q : A -> Prop)\n(R : A -> A -> Prop).\n(*6*)\nLemma forall_imp_dist : (forall x:A, P x -> Q x) ->\n(forall x:A, P x) ->\nforall x: A, Q x.\nProof.\nintros.\napply H.\napply H0.\nQed.\n(*7*)\nLemma forall_perm : (forall x y:A, R x y) -> forall y x, R x y.\nProof.\nintros.\napply H.\nQed.\n(*8*)\nLemma forall_delta : (forall x y:A, R x y) -> forall x, R x x.\nProof.\nintros.\napply H.\nQed.\n(*9*)\nLemma exists_or_dist : (exists x: A, P x \\/ Q x) <->\n(exists x, P x) \\/ (exists x , Q x).\nProof.\nsplit.\nintros.\ndestruct H.\ndestruct H.\nleft.\nexists x.\nassumption.\nright.\nexists x.\nassumption.\nintros.\ndestruct H.\ndestruct H.\nexists x.\nleft.\nassumption.\ndestruct H.\nexists x.\nright.\nassumption.\nQed.\n(*10*)\nLemma exists_imp_dist : (exists x: A, P x -> Q x) ->\n(forall x:A, P x) ->\nexists x:A, Q x.\nProof.\nintros.\ndestruct H.\nexists x.\napply H.\napply H0.\nQed.\n(*11*)\nLemma not_empty_forall_exists : forall a:A,\n(forall x:A, P x) ->\nexists x:A, P x.\nProof.\nintros.\nexists a.\napply H.\nQed.\n(*12*)\nLemma not_ex_forall_not : ~(exists x:A, P x) <-> forall x:A, ~P x.\nProof.\nsplit.\nintros.\nintro.\napply H.\nexists x.\nassumption.\nintros.\nintro.\ndestruct H0.\napply H in H0.\nassumption.\nQed.\nEnd LPPO_2.\n", "meta": {"author": "antoyneGG", "repo": "My-coq-files", "sha": "92c2b986d5108c395b34d002e387df8dc9903984", "save_path": "github-repos/coq/antoyneGG-My-coq-files", "path": "github-repos/coq/antoyneGG-My-coq-files/My-coq-files-92c2b986d5108c395b34d002e387df8dc9903984/Taller_6_FabianAntoyne_GarciaGallego.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7782224769504102}}
{"text": "Set Implicit Arguments.\n\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\n\nInductive nat' : Set := O' | S'(_:nat').  (* alternative syntax *)\n\n\nInductive even : nat -> Prop :=\n  | even_O  : even O\n  | even_SS : forall n:nat, even n -> even (S (S n)).\n\nInductive list (A:Set) : Set :=\n  | nil : list A\n  | cons: A -> list A -> list A.\n \nInductive list' (A:Set) : Set := nil' | cons'(_:A)(_:list' A).\n\n(* Variant is like Inductive but no recursive definitionof types *)\n\nInductive sum (A B: Set) : Set := left : A -> sum A B | right : B -> sum A B.\n\nInductive tree (A B:Set) : Set :=\n  | node : A -> forest A B -> tree A B\n  with forest (A B:Set) : Set :=\n    | leaf    : B -> forest A B\n    | cons''  : tree A B -> forest A B -> forest A B.\n\nCoInductive stream (A:Set): Set :=\n  | seq : A -> stream A -> stream A.\n\nDefinition head {A:Set}(x:stream A) : A := let (a,s):=x in a.\nDefinition tail {A:Set}(x:stream A) : stream A := let (a,s):=x in s.\n\nCoInductive Eq {A:Set} : stream A -> stream A -> Prop := \n  eq: forall s1 s2: stream A, \n    head s1 = head s2 -> Eq (tail s1) (tail s2) -> Eq s1 s2.\n\n\nFixpoint add(n m:nat) (* {struct n} *): nat := \n  match n with\n    | O   => m\n    | S p => S (add p m)\n  end.\n\nFixpoint add'(n m:nat) : nat :=\n  match m with\n    | O   => n\n    | S p => S (add' n p)\n  end.\n\nFixpoint nat_match\n  {C:Set} (f0:C) (fS: nat -> C -> C) (n:nat) : C :=\n    match n with\n      | O     => f0\n      | S p   => fS p (nat_match f0 fS p)\n    end.\n\nFixpoint mod2 (n:nat) : nat :=\n  match n with\n    | O   => O\n    | S p => match p with\n              | O   => S O   \n              | S q => mod2 q\n            end\n  end.\n\nEval compute in mod2 (S (S (S (S O)))).\nEval compute in mod2 (S (S (S (S (S O))))).\n\nFixpoint even' (n : nat) : Prop :=\n  match n with\n    | O   => True\n    | S p => odd' p\n  end\n  with odd'(n : nat) : Prop :=\n    match n with\n      | O   => False\n      | S p => even' p\n    end.\n\nEval compute in even' (S (S (S (S O)))).\nEval compute in odd' (S (S (S (S O)))).\nEval compute in even' (S (S (S (S (S O))))).\nEval compute in odd' (S (S (S (S (S O))))).\n\nCoFixpoint from (n : nat) : stream nat :=\n  seq n (from (S n)).\n\nDefinition integers := from O.\n\nFixpoint sub (n:nat) : stream nat :=\n  match n with\n    | O   => integers\n    | S p => tail (sub p)\n  end.\n\nDefinition id (n:nat) : nat := head (sub n).\n\nEval compute in id O.\nEval compute in id (S O).\nEval compute in id( S (S O)).\n\nLemma same : forall n:nat, id n = n.\nProof.\n  intro n. elim n.\n    clear n. unfold id. simpl. reflexivity.\n    clear n. intros n IH. unfold id. unfold id in IH.\n    unfold sub. fold sub.  \nAbort.\n\nEval compute in from O.\nEval compute in head (from O).\nEval compute in tail (from O).\n\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/inductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7782224692785424}}
{"text": "Require Import SetoidClass.\nRequire groups.\n\nModule Make(Import M: groups.T).\n\nClass ring (F: Set) (s: Setoid F) (op1 op2: F -> F -> F) (zero one: F) (inv1: F -> F)\n                     (g1: @group F s op1 zero inv1) :=\n{\n  r_assoc     : forall {a b c}, op2 (op2 a b) c == op2 a (op2 b c);\n  r_identity  : forall {a}, op2 one a == a;\n  r_inverser  : forall a: F, op1 (inv1 a) a == zero;\n  r_idsdiffer : ~ one == zero;\n  r_comm      : forall {a b}, op1 a b == op1 b a;\n  r_distrib   : forall {a b c}, (op2 a (op1 b c)) == op1 (op2 a b) (op2 a c)\n}.\nCheck ring.\n\nRequire Import Psatz.\nRequire Import Nsatz.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nDefinition zmult (n m: Z):= n * m.\nDefinition zid2 := 1%Z.\n\nProgram Instance Zeq_setoid : Setoid Z :=\n  { equiv := eq ; setoid_equiv := eq_equivalence }.\n\n(** < Z, +, *, 0, 1, ^{-1+} > as a ring instance **)\nProgram Instance ring_integers: (@ring Z (Zeq_setoid) _ zmult _ zid2 _ group_integers).\nObligation 1. unfold zmult. rewrite Zmult_assoc. reflexivity. Qed.\nNext Obligation. destruct a; reflexivity. Qed.\nNext Obligation. unfold zadd, zinv, zid. omega. Qed.\nNext Obligation. unfold zadd. omega. Qed.\nNext Obligation. unfold zadd, zmult. apply Zmult_plus_distr_r. Qed.\nCheck ring_integers.\n\nRequire Import Psatz.\nRequire Import Nsatz.\nRequire Import QArith.\nOpen Scope Q_scope.\n\nDefinition qmult (n m: Q) := n * m.\nDefinition qid2 := 1.\n\n(** < Q, +, *, 0, 1, ^{-1+} > as a ring instance **)\nProgram Instance ring_rationals: `(@ring Q (Qeq_setoid) _ qmult _ qid2 _ group_rationals).\nObligation 1. unfold qmult. symmetry. apply Qmult_assoc. Qed. \nNext Obligation. unfold qmult, qid2. apply Qmult_1_l. Qed.\nNext Obligation. unfold qadd, qinv, qid. rewrite Qplus_comm, Qplus_opp_r. reflexivity. Qed. \nNext Obligation. unfold qadd. apply Qplus_comm. Qed.\nNext Obligation. unfold qadd, qmult. apply Qmult_plus_distr_r. Qed.\nCheck ring_rationals.\n\nRequire Import ZArith_base.\nRequire Import Rdefinitions.\nRequire Import Coq.Reals.Raxioms.\nLocal Open Scope R_scope.\n\nDefinition rmult (n m: R) := n * m.\nDefinition rid2 := 1.\n\n(** < R, +, *, 0, 1, ^{-1+} > as a ring instance **)\nProgram Instance ring_reals: `(@ring R _ _ rmult _ rid2 _ group_reals).\nObligation 1. unfold rmult. apply Rmult_assoc. Qed.\nNext Obligation. unfold rmult, rid2. apply Rmult_1_l. Qed.\nNext Obligation. unfold radd, rinv, rid. rewrite Rplus_comm, Rplus_opp_r. reflexivity. Qed. \nNext Obligation. unfold rid, rid2. apply R1_neq_R0. Qed.\nNext Obligation. unfold radd. apply Rplus_comm. Qed.\nNext Obligation. unfold radd, rmult. apply  Rmult_plus_distr_l. Qed.\nCheck ring_reals.\n\nEnd Make.", "meta": {"author": "ekiciburak", "repo": "algebraic-groups-rings-fields", "sha": "3f260eaf6f5069b594c8ad2e5fd0c38e972c50c1", "save_path": "github-repos/coq/ekiciburak-algebraic-groups-rings-fields", "path": "github-repos/coq/ekiciburak-algebraic-groups-rings-fields/algebraic-groups-rings-fields-3f260eaf6f5069b594c8ad2e5fd0c38e972c50c1/src/rings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7782215855503584}}
{"text": "Require Import ZArith.\nRequire Import Bool.\nOpen Scope Z_scope.\n\nInductive Z_fbtree : Set :=\n | Z_fleaf : Z_fbtree \n | Z_fnode : Z  -> (bool -> Z_fbtree) -> Z_fbtree.\n\n\nFixpoint fzero_present (t:Z_fbtree) : bool :=\n match t with\n  | Z_fleaf => false\n  | Z_fnode v f => match v with 0 => true\n                              | _ => orb (fzero_present (f true))\n                                         (fzero_present (f false))\n                   end\n end.\n\n", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Tsinghua Coq Summer School/booksite83-export/structinduct/SRC/fzero_present.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9518632316144275, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.778219085110628}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Unset Printing Notations. *)\n\n(** Use SSReflect tactics.\n    DO NOT use automation like [tauto], [intuition], [firstorder], etc.,\n    except for [by], [done], [exact] tactic(al)s. *)\n\n\n(** * Exercise *)\n\nLemma demorgan (A B : Prop) : ~ (A \\/ B) -> (~ A /\\ ~ B).\nRestart.\nmove => nab.\nmove : conj.\napply.\n- move => a.\n  apply : nab.\n  apply : or_introl.\n  exact a.\nmove => b.\napply : nab.\napply : or_intror.\nexact b.\nQed.\n\nLemma nlem (A : Prop):\n  ~ (A \\/ ~ A) -> A.\nRestart.\nmove => noana.\nmove : (demorgan noana).\ncase.\nmove => na nna.\napply : False_ind.\nexact (nna na).\nQed.\n\n(** Hint: you might want to use a separate lemma here to make progress.\nOr, use the `have` tactic: `have: statement` creates a new subgoal and asks\nyou to prove the statement. This is like a local lemma. *)\n\n\n(** * Exercise *)\n\nLemma weak_Peirce (A B : Prop) :\n  ((((A -> B) -> A) -> A) -> B) -> B.\nRestart.\nmove => f.\napply : (f).\nmove => g.\napply : (g).\nmove => a.\napply : (f).\nmove => h.\nexact a.\nQed.\n\n(** * Exercise *)\n\n(* Prove that having a general fixed-point combinator in Coq would be incosistent *)\n\nDefinition FIX := forall A : Type, (A -> A) -> A.\n\nLemma fix_inconsistent :\n  FIX -> False.\nRestart.\nmove => f.\nmove : (@f False).\napply.\nexact id.\nQed.\n\nSection Boolean.\n(** * Exercise *)\n\n\nLemma negbNE b : ~~ ~~ b -> b.\nRestart.\nrewrite /negb.\nmove : b.\ncase.\n- exact id.\n- exact id.\nQed.\n\n(** * Exercise *)\n\nLemma negbK : involutive negb.\nRestart.\nrewrite /involutive /negb /cancel.\ncase.\n-  by [].\nby [].\nQed.\n\n\n(** * Exercise *)\n\nLemma negb_inj : injective negb.\nRestart.\nrewrite /injective /negb.\ncase.\n- case.\n  - by [].\n  - by [].\ncase.\n  - by [].\n  - by [].\nQed.\n\nEnd Boolean.\n\n\n(** * Exercise *)\n\nFixpoint triple (n : nat) : nat :=\n  if n is n'.+1 then (triple n').+3\n  else n.\n\nLemma triple_mul3 n :\n  triple n = 3 * n.\nRestart.\nelim : n.\n- exact erefl.\nmove => n ih /=.\nrewrite mulnS /=.\nrewrite /addn /addn_rec /Nat.add.\nexact (congr1 (fun x => S (S (S x))) ih).\nQed.\n\n(** Hints:\n- use the /= action to simplify your goal: e.g. move=> /=.\n- use `Search (<pattern>)` to find a useful lemma about multiplication\n*)\n\n(** * Exercise\nProve by it induction: you may re-use the addnS and addSn lemmas only *)\n\nLemma plus_two_inj (n m : nat) : S (S n) = S (S m) -> eq n m.\nRestart.\ncase.\nexact.\nQed.\n\nLemma zz_plus (n : nat) : O = addn n n -> eq O n.\nRestart.\ncase : n.\n- exact.\nexact.\nQed.\n\nLemma plus_zz (n : nat) : addn n n = O -> eq n O.\nRestart.\ncase : n.\n- exact.\nexact.\nQed.\n\nLemma two_is_double_one (n : nat) : S (S O) = addn n n -> eq (S O) n.\nRestart.\nelim : n.\n- exact.\nmove => n ih.\nrewrite (addSn n (S n)).\nrewrite (addnS n n).\nmove => h.\nmove : (plus_two_inj h).\nmove => h2.\nmove : (zz_plus h2).\nmove => h3.\nexact (congr1 S h3).\nQed.\n\nLemma double_inj m n :\n  m + m = n + n -> m = n.\nRestart.\nmove : n m.\nelim.\n- apply : plus_zz.\nmove => n h1.\ncase.\n- apply : zz_plus.\nmove => k.\nrewrite (addSn k (S k)).\nrewrite (addnS k k).\nrewrite (addSn n (S n)).\nrewrite (addnS n n).\nmove => h2.\nmove : (plus_two_inj h2).\nmove => h3.\nmove : (h1 k h3).\napply : (congr1 S).\nQed.\n\n(* This is a harder exercise than the previous ones but\n   the tactics you already know are sufficient *)\n\n(** * Optional exercise\n    [negb \\o odd] means \"even\".\n    The expression here says, informally,\n    the sum of two numbers is even if the summands have the same \"evenness\",\n    or, equivalently, \"even\" is a morphism from [nat] to [bool] with respect\n    to addition and equivalence correspondingly.\n    Hint: [Unset Printing Notations.] and [rewrite /definition] are your friends :)\n *)\n\nLemma s_flips_odd (n : nat) : odd (S n) = negb (odd n).\nRestart.\nelim : n.\n- exact.\nexact.\nQed.\n\nLemma rneutral_z (n : nat) : addn n O = n.\nelim : n.\n- exact.\nmove => n ih.\nrewrite (addSn n O).\nexact (congr1 S ih).\nQed.\n\nLemma rneutral_true (b : bool) : (Equality.op (Equality.class bool_eqType) b true) = b.\nRestart.\ncase : b.\n- exact.\nexact.\nQed.\n   \nCheck s_flips_odd.\nCheck rneutral_z.\nCheck rneutral_true.\n\nLemma even_add :\n  {morph (negb \\o odd) : x y / x + y >-> x == y}.\nRestart.\nrewrite /morphism_2 /eq_op /(comp negb odd).\nelim.\n- exact.\nmove => n ih.\ncase.\n- rewrite (addSn n O).\n  rewrite (rneutral_z n).\n  rewrite (s_flips_odd n).\n  rewrite /(negb (odd O)).\n  rewrite /(odd O).\n  rewrite (rneutral_true (negb (negb (odd n)))).\n  exact.\nhave h1 : forall (a b : bool), (Equality.op (Equality.class bool_eqType) (negb a) b) = negb (Equality.op (Equality.class bool_eqType) a b).\ncase.\n- exact.\ncase.\n- exact.\nexact.\nmove => k.\nrewrite (s_flips_odd n).\nrewrite (h1 (negb (odd n)) (negb (odd (S k)))).\nrewrite /(addSn n (S k)).\nexact (congr1 negb (ih (S k))).\nQed.\n\n(** * Optional exercise *)\n\nDefinition LEM (Q : Prop) := or Q (not Q).\nDefinition DNE (Q : Prop) := not (not Q) -> Q.\n\nLemma LEM_implies_DNE : forall Q : Prop, (LEM Q) -> (DNE Q).\nRestart.\nrewrite /LEM /DNE.\nmove => q.\ncase.\n- exact.\nmove => nq nnq.\napply : (False_ind q (nnq nq)).\nQed.\n\nLemma nn_LEM : forall Q, not (not (LEM Q)).\n\nRestart.\nrewrite /LEM.\nmove => q.\nmove => h1.\nmove : (nlem h1).\nmove => vq.\nmove : (h1 (or_introl vq)).\nexact.\nQed.\n\nLemma DNE_implies_LEM : (forall Q, DNE Q) -> (forall P, LEM P).\nRestart.\nmove => dne.\nmove => p.\napply : (dne).\nmove => h1.\nmove : (nn_LEM h1).\nexact.\nQed.\n\nReset DNE_iff_nppp.\n\nLemma DNE_iff_nppp :\n  (forall P, ~ ~ P -> P) <-> (forall P, (~ P -> P) -> P).\nRestart.\nsplit.\n- move => h1.\n  move => p.\n  move : (DNE_implies_LEM h1).\n  move => h2.\n  move : (h2 p).\n  case.\n  - exact.\n  move => np.\n  move => h3.\n  exact (h3 np).\nmove => h1 p.\napply : LEM_implies_DNE.\napply : (h1).\nmove => h2.\nmove : (nn_LEM h2).\nexact.\nQed.\n\n(** * Optional exercise *)\n\nLemma leq_add1l p m n :\n  m <= n -> m <= p + n.\nRestart.\nmove : (leq0n p).\napply : leq_add.\nQed.\n\n(** Hint: this lemmas does not require induction, just look for a couple lemmas *)\n\n\n(* ================================================ *)\n\n(*\nMore fun with functions, OPTIONAL\n*)\n\nSection PropertiesOfFunctions.\n\nLemma comp_assoc (a b c d: Type) (f : c -> d) (g : b -> c) (h : a -> b) : (f \\o g) \\o h =1 f \\o (g \\o h).\nRestart.\ndone.\nQed.\n\nLemma comp_sym (a b : Type) (f g : a -> b) : f =1 g -> g =1 f.\nRestart.\nrewrite /eqfun.\nmove => fg.\nmove => x.\nmove : (fg x).\nexact.\nQed.\n\nLemma comp_assoc_both\n      (a b c d : Type)\n      (g1 g2 : c -> d) (f : b -> c) (h1 h2 : a -> b)\n  : (g1 \\o f) \\o h1 =1 (g2 \\o f) \\o h2\n    -> g1 \\o (f \\o h1) =1 g2 \\o (f \\o h2).\nProof.\n  move => k1.\n  move : (comp_assoc g1 f h1) (comp_assoc g2 f h2).\n  move => //.\nQed.\n\nLemma comp_assoc_both_r\n      (a b c d : Type)\n      (g1 g2 : c -> d) (f : b -> c) (h1 h2 : a ->b) :\n  g1 \\o (f \\o h1) =1 g2 \\o (f \\o h2) -> (g1 \\o f) \\o h1 =1 (g2 \\o f) \\o h2.\nProof.\n  done.\nQed.\n\nSection SurjectiveEpic.\n\nContext {A B : Type}.\n\n(* https://en.wikipedia.org/wiki/Surjective_function *)\n(** Note: This definition is too strong in Coq's setting, see [epic_surj] below *)\n\nDefinition surjective (f : A -> B) :=\n  exists g : B -> A, f \\o g =1 id.\n\n(** This is a category-theoretical counterpart of surjectivity:\n    https://en.wikipedia.org/wiki/Epimorphism *)\n\nDefinition epic (f : A -> B) :=\n  forall C (g1 g2 : B -> C), g1 \\o f =1 g2 \\o f -> g1 =1 g2.\n\n(** * Optional exercise *)\n\nLemma surj_epic f : surjective f -> epic f.\nRestart.\nrewrite /surjective /epic.\ncase.\nmove => x.\nmove => h1.\nmove => c.\nmove => g1 g2.\nmove => eg12f.\nhave xx : (x =1 x).\nexact.\nmove : (eq_comp eg12f xx).\nmove : (comp_assoc g1 f x).\nmove => h2 h3.\nmove : (comp_assoc g2 f x).\nmove => h4.\nmove : (comp_sym h2).\nmove => h5.\nmove : (ftrans h5 h3).\nmove => h6.\nmove : (ftrans h6 h4).\nhave gg1 : g1 =1 g1.\nexact.\nhave gg2 : g2 =1 g2.\nexact.\nmove : (eq_comp gg1 h1) (eq_comp gg2 h1).\nmove => s1 s2.\nmove => s3.\nmove : (ftrans (comp_sym s1) s3).\nmove => s4.\nmove : (ftrans s4 s2).\nexact.\nQed.\n\n(** * Optional exercise *)\n\nLemma epic_surj f : epic f -> surjective f.\n  (** Why is this not provable? *)\nAbort.\n\nEnd SurjectiveEpic.\n\nSection EpicProperties.\n\nContext {A B C : Type}.\n\n(** * Optional exercise *)\n\nLemma epic_comp (f : B -> C) (g : A -> B) :\n  epic f -> epic g -> epic (f \\o g).\nRestart.\nrewrite /epic.\nmove => epic_f epic_g D g1 g2.\nset ef := epic_f D.\nset eg := epic_g D.\nmove => h1.\nset h2 := ftrans (comp_assoc g1 f g) h1.\nset h3 := (ftrans h2 (comp_sym (comp_assoc g2 f g))).\nset h4 := (eg (g1 \\o f) (g2 \\o f) h3).\nexact (ef g1 g2 h4).\nQed.\n\n(** * Optional exercise *)\n\nLemma comp_epicl (f : B -> C) (g : A -> B) :\n  epic (f \\o g) -> epic f.\nRestart.\nrewrite /epic.\nmove => epic_fg.\nmove => D g1 g2.\nmove => h1.\nhave gg : g =1 g.\nexact.\nset efg := epic_fg D g1 g2.\nset h2 := (comp_assoc_both (eq_comp h1 gg)).\nexact (efg h2).\nQed.\n\n(** * Optional exercise *)\n\nLemma retraction_epic (f : B -> A) (g : A -> B) :\n  (f \\o g =1 id) -> epic f.\nRestart.\nrewrite /epic.\nmove => h1 D g1 g2 h2.\nhave gg : g =1 g.\nexact.\nset h3 := comp_assoc_both (eq_comp h2 gg).\nhave g1g1 : g1 =1 g1.\nexact.\nhave g2g2 : g2 =1 g2.\nexact.\nhave g1fg : g1 \\o (f \\o g) =1 g1.\nmove : (eq_comp g1g1 h1).\nexact.\nhave g2fg : g2 \\o (f \\o g) =1 g2.\nmove : (eq_comp g2g2 h1).\nexact.\nexact (ftrans (comp_sym g1fg) (ftrans h3 g2fg)).\nQed.\n\nEnd EpicProperties.\n\n(** The following section treats some properties of injective functions:\n    https://en.wikipedia.org/wiki/Injective_function *)\n\nSection InjectiveMonic.\n\nContext {A B C : Type}.\n\n(** This is a category-theoretical counterpart of injectivity:\n    https://en.wikipedia.org/wiki/Monomorphism *)\n\nDefinition monic (f : B -> C) :=\n  forall A (g1 g2 : A -> B), f \\o g1 =1 f \\o g2 -> g1 =1 g2.\n\n(** * Optional exercise *)\n\nLemma inj_monic f : injective f -> monic f.\nRestart.\nrewrite /injective /monic /comp /eqfun.\nmove => h1 D.\nmove => g1 g2.\nmove => h2.\nmove => x.\nexact (h1 (g1 x) (g2 x) (h2 x)).\nQed.\n\n(** * Optional exercise *)\n\nLemma monic_inj f : monic f -> injective f.\nRestart.\nrewrite /injective /monic /comp /eqfun.\nmove => h1.\nmove => x1 x2.\nset lx1 : unit -> B := fun _ => x1.\nset lx2 : unit -> B := fun _ => x2.\nset h2 := h1 unit lx1 lx2.\nmove => h3.\nhave h4 : forall x : unit, f (lx1 x) = f (lx2 x).\ncase.\nrewrite /lx1 /lx2.\nexact h3.\nmove : (h2 h4).\napply.\nexact tt.\nQed.\n\nEnd InjectiveMonic.\n\nSection MonicProperties.\n\nContext {A B C : Type}.\n\n(** * Optional exercise *)\n\nLemma monic_comp (f : B -> C) (g : A -> B) :\n  monic f -> monic g -> monic (f \\o g).\nRestart.\nrewrite /monic.\nmove => h1 h2.\nmove => D.\nmove => g1 g2.\nmove => h3.\nset h4 := ftrans (comp_sym (comp_assoc f g g1)) h3.\nset h5 := ftrans h4 (comp_assoc f g g2).\nexact (h2 D g1 g2 (h1 D (g \\o g1) (g \\o g2) h5)).\nQed.\n\n\n(** * Optional exercise *)\nLemma comp_monicr (f : B -> C) (g : A -> B) :\n  monic (f \\o g) -> monic g.\nProof.\n  rewrite /monic.\n  have ff : f =1 f.\n  by exact.\n  move => h1 D g1 g2 h2.\n  set h3 := (eq_comp ff h2).\n  set h4 := (@comp_assoc_both_r _ _ _ _ f f g g1 g2 h3).\n  exact (h1 D g1 g2 h4).\nQed.\n          \n(** * Optional exercise *)\nLemma section_monic (f : B -> A) (g : A -> B) :\n  (g \\o f =1 id) -> monic f.\nProof.\n  rewrite /monic.\n  move => h1.\n  move => D.\n  move => g1 g2.\n  have gg : g =1 g.\n    by done.\n  move => h2.\n  move : (comp_assoc_both_r (eq_comp gg h2)).\n  have gfg1 : (g \\o f) \\o g1 =1 g1.\n    - have ig1 :id \\o g1 =1 g1.\n        by done.\n        have g1g1 : g1 =1 g1.\n        by done.\n        have p1 : (g \\o f) \\o g1 =1 id \\o g1.\n        exact (eq_comp h1 g1g1).\n        by done.\n   have gfg2 : (g \\o f) \\o g2 =1 g2.\n    - have ig2 :id \\o g2 =1 g2.\n        by done.\n        have g2g2 : g2 =1 g2.\n        by done.\n        have p1 : (g \\o f) \\o g2 =1 id \\o g2.\n        exact (eq_comp h1 g2g2).\n          by done.\nmove => h3.\nmove : (ftrans (comp_sym gfg1) (ftrans h3 gfg2)).\ndone.\nQed.\n       \nEnd MonicProperties.\n\nEnd PropertiesOfFunctions.\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/hw05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8918110461567922, "lm_q1q2_score": 0.7779690248239051}}
{"text": "Set Implicit Arguments.\nRequire Import List.\n\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\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\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\nLemma ex1 : SubList (5::3::nil)  (5::7::3::4::nil).\nProof.\n  constructor.\n  constructor.\n  constructor.\n  constructor.\nQed.\n\nLemma ex1b : forall (A:Type) (l:list A), SubList l l.\nProof.\n  intros.\n  induction l.\n  - constructor.\n  - constructor.\n    assumption.\nQed.\n\nLemma ex1c : forall (A B:Type) (f:A->B) (l1 l2:list A), SubList l1 l2 -> SubList (map f l1) (map f l2).\nProof.\n  intros.\n  induction H.\n  - constructor.\n  - simpl.\n    constructor.\n    assumption.\n  - simpl.\n    constructor.\n    assumption.\nQed.\n\nLemma ex1d : forall (A:Type) (x:A) (l : list A), In x l -> exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  intros.\n  induction H.\n  exists nil. exists xs. simpl. reflexivity.\n  destruct IHIn as [I1 H1]. destruct H1 as [I2 H1]. exists (x0::I1). exists I2.  rewrite <-app_comm_cons.\n  rewrite H1. reflexivity.\nQed.\n\nFixpoint drop (A:Type) (n:nat) (l : list A)  : list A :=  \n  match n with\n  | 0 => l (* Caso seja drop 0, o resultado é a lista *)\n  | S n' => drop n' (tl l) (* Caso seja outro valor, retira-se 1 ao valor e faz-se sobre a cauda *)\n  end.\n\nLemma ex2a : drop 2 (5::7::3::4::nil) = 3::4::nil.\nProof.\n  constructor.\nQed.\n\nLemma ex2b : forall (A:Type) (n:nat) (l:list A), SubList (drop n l) l.\nProof.\n  intros H n.\n  induction n.\n  - induction l.\n    * constructor.\n    * constructor.\n      apply IHl.\n  - induction l.\n    * simpl.\n      apply IHn.\n    * constructor.\n      simpl.\n      apply IHn.\nQed.\n\nInductive Sorted : list nat -> Prop := \n  | sorted0 : Sorted nil  (* Caso vazio *)\n  | sorted1 : forall a:nat, Sorted (a :: nil) (* Ultimo elemento da lista *) \n  | sorted2 : forall (a1 a2:nat) (l:list nat), a1 <= a2 -> Sorted (a2 :: l) -> Sorted (a1 :: a2 :: l). (* Caso geral *)\n\nLemma ex3a : forall (x y:nat) (l:list nat), x<=y -> (Sorted (y::l)) -> Sorted (x::l).\nProof.\n  intros.\n  induction l.\n  - constructor.\n  - constructor.\n    + rewrite H. inversion H0. exact H3. \n    + inversion H0. exact H5.\n    \nQed.\n\nLemma sorted2 : forall (x y:nat) (l:list nat), Sorted(x::y::l) -> x<=y. (* Auxiliar para o caso em que temos 2 valores da lista no Sorted*)\nProof.\n  intros.\n  inversion H.\n  assumption.\nQed.\n\nLemma sortedAux: forall (x y:nat) (l:list nat), x<=y -> Sorted(x::y::l) -> Sorted(x::l). (* Mais uma auxiliar para o caso em que temos 2 valores da lista*)\nProof.\n  intros.\n  inversion H0.\n  generalize H5.\n  generalize H3.\n  apply ex3a.\nQed.\n\nLemma ex3b : forall (x y:nat) (l:list nat), (In y l) /\\ (Sorted (x::l)) -> x <= y.\nProof.\n  intros.\n  induction H.\n  induction H.\n  - generalize H0. apply sorted2.\n  - inversion H0. \n    apply IHIn. \n    generalize H0. \n    apply sortedAux. \n    assumption. \nQed.\n\nLemma ex4a : forall (A:Type) (l:list A), Prefix l l.\nProof.\n  intros.\n  induction l.\n  - constructor.\n  - constructor.\n    assumption.\nQed.\n\nLemma concatenate_extra : forall (A:Type) (l1 l2:list A), Prefix l1 l2 -> exists l3:list A, l2 = l1 ++ l3. \nProof.\n  intros.\n  induction H.\n  - exists l. \n    rewrite app_nil_l.\n    trivial.\n  - destruct IHPrefix.\n    exists x0. \n    rewrite H0. \n    apply app_comm_cons.\nQed.\n\nLemma concatenate_prefix : forall (A:Type) (l1 l2:list A), Prefix l1 (l1++l2).\nProof.\n  intros.\n  induction l1.\n  - simpl. constructor.\n  - simpl. constructor. exact IHl1.\nQed.\n\nLemma ex4_b : forall (A:Type) (l1 l2 l3:list A), Prefix l1 l2 /\\ Prefix l2 l3 -> Prefix l1 l3.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  apply concatenate_extra in H1.\n  destruct H1.\n  apply concatenate_extra in H2.\n  destruct H2.\n  rewrite  H0.\n  rewrite  H.\n  assert(((l1++x)++x0)=(l1++(x++x0))). \n  - apply app_assoc_reverse. \n  - rewrite H1.\n    apply concatenate_prefix.\nQed.\n\nLemma concatenate_aux : forall (A:Type) (x:A) (l1 l2:list A), l1 = l2 -> x::l1 = x::l2.\nProof.\n  intros.\n  rewrite H.\n  trivial.\nQed.\n\nLemma ex4c : forall (A:Type) (l1 l2:list A), Prefix l1 l2 /\\ Prefix l2 l1 -> l1 = l2.\nProof.\n  intros.\n  destruct H.\n  induction H.\n  - inversion H0. trivial.\n  - apply concatenate_aux.\n    apply IHPrefix.\n    inversion H0.\n    exact H2.\nQed.", "meta": {"author": "HugoOSFaria", "repo": "Formal-Verification", "sha": "3ac482504bacfbdb2db1f1be2697843abefa74af", "save_path": "github-repos/coq/HugoOSFaria-Formal-Verification", "path": "github-repos/coq/HugoOSFaria-Formal-Verification/Formal-Verification-3ac482504bacfbdb2db1f1be2697843abefa74af/Coq_TPC2/tpc2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7779690188547715}}
{"text": "Module Sqrt.\n\nRequire Import Compare_dec.\nRequire Import Arith.Mult.\nRequire Import Arith.Plus.\nRequire Import Omega.\n\n\n(** \n  *   Definition of sqrt.\n  *)\n\n(** Note: natural numbers in Coq are represented as lists:\n  0 = O;  1 = S O;  2 = S (S O);  5 = S (S (S (S (S O)))).\n  Infix operators can have a prefix form:\n  a <= b <=> le a b;\n  a < b <=> lt a b;\n  a > b <=> lt a b;\n  this operators return truth. They are not computable. \n  A computable analog of 'le' is 'leb'. It returns boolean:\n  leb: nat -> nat -> bool.\n  It can be used as a condition in an if-statement\n*)\n  \n\n(** ** auxilary function - emulating iteration with tail recursion.\n   guess monotonically decreasing on each call while its square > n \n   function is guaranteed to terminate. (proven automatically due \n   to the form of the function (destructive recursion) \n\n  Construction \"match n with A x y z => ... | B a b c => ... end\"\n  performs destruction of its argument n by all possible constructors.\n  \n *)\nFixpoint guess_sqrt (n guess: nat): nat :=\n  match n with \n      | O => O\n      | S x => match guess with\n                 | O => O\n                 | S prv =>\n                   if (leb (guess * guess) n) then guess else guess_sqrt n prv\n               end\n  end.\n\n(** ** wrapper interface function \n\n  *)\nFunction sqrt (n: nat) := guess_sqrt n n.\n\n(** \n  *   Testing of the defined function. \n\n  *)\n\nEval compute in (sqrt 10).\n\n(** \n                                                                     \n  * Correctness proof: $sqrt(n)^2 <= n < (sqrt(n)+1)^2 $\n                                                                     \n   The main theorem is proven last.                                  \n\n  *)\n\n(** ** A boolean can either be equal to true, or false.\n   this lemma helps consider cases in analysis of an if-expression \n\n  *)\nLemma true_or_false: forall a : bool, a=true \\/ a=false.\nintro.\ninduction a.\ntauto.\ntauto.\nQed.\n\n\n(** *** guess_sqrt is 0 if the first argument is 0 \n\n  *)\nLemma guess_0_is_0: forall m: nat, guess_sqrt 0 m = 0.\nProof.\ninduction m.\nsimpl.\nauto.\nunfold guess_sqrt.\nauto.\nQed.\n\nLemma guess_le: forall n g:nat, (guess_sqrt n g)*(guess_sqrt n g) <= n.\nProof.\nintros.\ndestruct n.\n- rewrite guess_0_is_0.\n  auto.\n- induction g.\n  + unfold guess_sqrt.\n    omega.\n  + unfold guess_sqrt.\n    fold guess_sqrt.\n    pose proof true_or_false.\n    specialize H with (leb (S g*S g) (S n)).\n    decompose sum H.\n    * rewrite H0.\n      apply leb_complete in H0.\n      assumption.\n    * rewrite H0.\n      apply leb_complete_conv in H0.\n      apply IHg.\nQed.\n\nLemma guess_gt: forall n g: nat, (n < S g * S g) ->\n                                 n < (S (guess_sqrt n g))*(S (guess_sqrt n g)).\nProof.\n  intros.\n  destruct n.\n  - rewrite guess_0_is_0.\n    auto.\n  - induction g.\n    auto.\n    unfold guess_sqrt; fold guess_sqrt.\n    pose proof true_or_false.\n    specialize H0 with (leb (S g*S g) (S n)).\n    decompose sum H0.\n    + rewrite H1.\n      assumption.\n    + rewrite H1.\n      apply leb_complete_conv in H1.\n      apply IHg.\n      apply H1.\nQed.\n\n(** *** The holy grail: complete correctness proof, combining together two\n   parts, proven before. \n\n  *)\nTheorem true_sqrt: forall n :nat, le ((sqrt n)*(sqrt n)) n /\\ lt n (S (sqrt n) * S (sqrt n)).\nunfold sqrt.\nintros.\nsplit.\n- apply guess_le.\n- apply guess_gt.\n  simpl.\n  apply le_lt_n_Sm.\n  apply le_plus_l.\nQed.\n\n(** *** So far, it is formally proven (modulo Coq core), that:\n1) sqrt n terminates for any natural n and 2) x = sqrt n satisfies specification : $(sqrt\\ n)^{2} <= n < (1+sqrt\\ n)^{2}$\n  *)\nEnd Sqrt.", "meta": {"author": "dgendill", "repo": "Coq-Learning", "sha": "39318afc5530a318e07c2f4cfbed3c02c7f29e1c", "save_path": "github-repos/coq/dgendill-Coq-Learning", "path": "github-repos/coq/dgendill-Coq-Learning/Coq-Learning-39318afc5530a318e07c2f4cfbed3c02c7f29e1c/Sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7779414648537682}}
{"text": "(**\nObjectif de ce suppport de TD :\ninitiation aux relations ou prédicats définis inductivement,\npour préparer la définition des sémantiques relationnelles.\n*)\n\n(* Les exercices sont faciles, progressifs, et sont prévus\n   pour une durée d'environ 1/2h).\n*)\n\n(* ------------------------------------------------------------ *)\n(** * Relations ou prédicats définis inductivement *)\n\n(** ** Prédicats à 1 argument sur un type énuméré  *)\n\n(** Commençons par un prédicat très simple qui indique comment\n    sélectionner quelques valeurs dans un type énuméré. *)\n\n\nInductive coul : Set :=\n| violet : coul\n| indigo : coul\n| bleu : coul\n| vert : coul\n| jaune : coul\n| orange : coul\n| rouge : coul\n.\n\n(** Rappel : on ne peut PAS définir un autre type qui partage des\n    constructeurs avec un type déjà défini. *)\nFail Inductive coulfeu : Set :=\n| vert : coulfeu\n| orange : coulfeu\n| rouge : coulfeu\n.\n\nDefinition ATTENTION_QUESTION_EN_COMMENTAIRE_1 : bool.\nProof.\n  \n(**\nPourquoi interdire à un constructeur d'être dans des types inductifs différents ?\n *)\n(* Répondre ici\nPour ne pas créer d'ambiguïté en utilisant le constructeur concerné\n *)\nAdmitted.\n\n(** Mais on peut définir un prédicat sur coul qui est démontrable\n    pour vert orange et rouge (et seulement pour ces derniers). *)\n\nInductive estCoulfeu : coul -> Prop :=\n| Fver : estCoulfeu vert\n| Fora : estCoulfeu orange\n| Frou : estCoulfeu rouge\n.\n\n(** Par exemple on peut démontrer que vert satisfait ce prédicat. *)\nExample exemple_feu_vert : estCoulfeu vert.\nProof.\n  apply Fver.\nQed.\n\n(** Certains feux de circulation ne présentent que les deux couleurs\n    vert et rouge. *)\n\nInductive feu2couls : coul -> Prop :=\n| F2ver : feu2couls vert\n| F2rou : feu2couls rouge\n.\n\n(** On veut démontrer que le second prédicat implique le premier. *)\n\nLemma feu2couls_estCoulfeu : forall c, feu2couls c -> estCoulfeu c.\nProof.\n  intro c.\n  (** On essaie d'abord un raisonnement par cas sur [c].*)\n  destruct c.\n  (** Beaucoup de cas inutiles (et qui requièrent une technique spéciale).\n      Donc on essaye une meilleure stratégie. *)\n  Undo 1.\n  (** Introduction de l'hypothèse sur [c]. *)\n  intro f2c.\n  (** Il suffit de raisonner par cas sur les deux façons\n      dont [f2c] peut être construite *)\n  refine (match f2c with F2ver => _ | F2rou => _ end).\n  clear.\n  (** Même chose en utilisant la tactique destruct sur l'HYPOTHÈSE [f2c] *)\n  Undo 2.\n  destruct f2c as [ (*F2ver*) | (*F2rou*) ].\n  - apply Fver.\n  - refine Frou.\nQed.\n\n(** Exercice *)\n\n(** Sur le modèle du prédicat estCoulfeu, définir un autre prédicat nommé boivr,\n    qui sélectionne les couleurs bleu, orange, indigo, vert et rouge. *)\n\n(* Inductive boivr à compléter *)\n\nInductive boivr : coul -> Prop :=\n|Fble : boivr bleu\n|Foran : boivr orange\n|Findi : boivr indigo\n|Fvert : boivr vert\n|Froug : boivr rouge\n.\n\n(** Démontrer ensuite : *)\n\nLemma estCoulfeu_boivr : forall c, estCoulfeu c -> boivr c.\nProof.\n  (** compléter *)\n  intro c.\n  intro ecf.\n  destruct ecf as [(*Fver*) | (*Fora*) | (*Frou*)].\n  -apply Fvert.\n  -apply Foran.\n  -refine Froug.\nQed.\n\n(** ** Relations à 2 arguments sur un type énuméré *)\n\n(** Les relations inductives permettent de représenter des fonction partielles\n    i.e., qui ne sont pas définies partout. Voici un exemple où coulsuiv\n    est définie pour vert, orange et rouge, mais pas pour les autres couleurs\n    prévues dans coul. *)\n\nInductive coulsuiv : coul -> coul -> Prop :=\n| CSv : coulsuiv vert orange\n| CSo : coulsuiv orange rouge\n| CSr : coulsuiv rouge vert\n.\n\n(** Exercice (même technique qu'auparavant) *)\n\nLemma coulsuiv_estCoulfeu : forall c1 c2, coulsuiv c1 c2 -> estCoulfeu c1.\nProof.\n  (** compléter *)\n  intros a b c.\n  destruct c as [(*Fver*) | (*Fora*) | (*Frou*)].\n  - apply Fver.\n  - apply Fora.\n  - apply Frou. \nQed.\n\n(** ** Prédicat even sur nat *)\n\n(** De même que les types inductifs de données peuvent être récursifs,\n    par exemple nat ou aexp, les prédicats inductifs peuvent être\n    récursifs. C'est le cas de even, présenté au CM4. *)\n\nInductive even : nat -> Prop :=\n| E0 : even 0\n| E2 : forall n, even n -> even (S (S n))\n.\n\n(** Exercice : démontrer que 6 est pair. *)\n\nExample ev10 : even 10.\nProof.\n  refine (E2 8 _).\n  apply (E2 6).\n  apply E2.\n  (** compléter *)\n  apply E2.\n  apply E2.\n  apply E0.\nQed.\n\nPrint ev10.\n\nDefinition ATTENTION_QUESTION_EN_COMMENTAIRE_2 : bool.\n(** Exercice :\n    - quel est le type et la signification de E2 4 ?\n    - quel est le type et la signification de E2 5 ?\n*)\n(* Répondre ici\nE2 4: Prop. C'est une soustraction de 2 depuis 6\nE2 5: Prop. C'est une soustraction de 2 depuis 7\n *)\nAdmitted.\n\n\n(** Entiers atteignables en ajoutant des 2 ou des 7 en partant de 0. *)\nInductive p2p7 : nat -> Prop :=\n| PP0 : p2p7 0\n| PP2 : forall n, p2p7 n -> p2p7 (2 + n)\n| PP7 : forall n, p2p7 n -> p2p7 (7 + n)\n.\n\n(** Exercice : démontrer de 3 façons que 11 est atteignable par p2p7. *)\nExample p2p7_11_methode1 : p2p7 11.\nProof.\n  (** Compléter ici *)\n  refine (PP7 4 _).\n  apply PP2.\n  apply PP2.\n  apply PP0.\nQed.\n\nExample p2p7_11_methode2 : p2p7 11.\nProof.\n  (** Compléter ici *)\n  refine (PP2 9 _).\n  apply PP7.\n  apply PP2.\n  apply PP0.\nQed.\n\nExample p2p7_11_methode23 : p2p7 11.\nProof.\n  (** Compléter ici *)\n  refine (PP2 9 _).\n  apply PP2.\n  apply PP7.\n  apply PP0.\nQed.\n\nPrint p2p7_11_methode2.\n\n(** Démontrer que tout entier pair satisfait p2p7. *)\n\nTheorem even_p2p7 : forall n, even n -> p2p7 n.\nProof.\n  intros n en.\n  (** Comme il y a une infinité d'entiers pairs, une preuve par cas\n      ne suffit pas. On procède par récurrence structurelle sur les\n      façons de démontrer [even n], autrement les formes possibles\n      d'arbres de preuve pour [en].\n      On a deux cas, celui où [en] est [E0], et celui où [en]\n      est de la forme [E2 n' en'], avec [en' : even n'] ;\n      dans ce dernier cas, on a droit à une hypothèse de récurrence\n      sur en', assurant que [n'] satisfait p2p7.\n  *)\n  induction en as [ (*E0*) | (*E2*) n' evn' Hrec_evn'].\n  - apply PP0.\n  - (** Facultatif : mise sous une forme clairement adaptée à p2p7 *)\n    change (p2p7 (2 + n')).\n    (** Utilisation du constructeur approprié de p2p7 *)\n    apply PP2.\n    (** Utilisation de l'hypothèse de récurrence *)\n    apply Hrec_evn'.\nQed.\n\n(** Il est instructif de démontrer le même théorème par une\n    fonction récursive. *)\n\nFixpoint fct_even_p2p7 n (en : even n) : p2p7 n :=\n  match en with\n  | E0 => PP0\n  | E2 n' evn' => PP2 n' (fct_even_p2p7 n' evn')\n  end.\n\n(** On peut transformer un arbre de preuve de [even 4]\n    en un arbre de preuve de [p2p7 4] *)\nCompute fct_even_p2p7 4 (E2 2 (E2 0 E0)).\n\n(** La somme de deux entiers pairs est paire *)\nLemma even_plus : forall n m, even n -> even m -> even (n + m).\nProof.\n  intros n m evn evm.\n  (** Compléter par récurrence structurelle sur evn *)\n  induction evn as [ (*E0*) | (*E2*) n' evn' Hrec_evn'].\n  -refine (evm).\n  - change(even (S (S (n'+m)))).  apply E2.\n    apply Hrec_evn'.\n  \nQed.\n\n(** Exercice facultatif :\n    en donner une preuve sous forme de fonction. *)\n\nFixpoint fct_even_plus n m (evn : even n) (evm : even m) : even (n + m).\n  (** A compléter *)\nAdmitted.\n\n(* Les multiples de 4 sont pairs *)\nInductive mul4 : nat -> Prop :=\n| M4_0 : mul4 0\n| M4_4 : forall n, mul4 n -> mul4 (S (S (S (S n))))\n.\n\nLemma mul4_even : forall n, mul4 n -> even n.\nProof.\n  intros n m4n.\n  (** Terminer par récurrence structurelle sur [m4n] *)\n  induction m4n as [(*M4_0*) | (*M4_4*)].\n  - apply (E0).\n  - apply E2.\n    apply E2.\n    apply IHm4n.\nQed.\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/TD5_firstPart/TD05_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8991213732152423, "lm_q1q2_score": 0.7779414558914474}}
{"text": "Theorem identity : forall A B : Prop, A -> B -> A.\nProof.\n    intros.\n    exact H.\nQed.\n\nTheorem forward_small : forall A B : Prop, A -> (A -> B) -> B.\nProof.\n    intros A B.\n    intros poA atob.\n    pose (poB := atob poA).\n    exact poB.\nQed.\n\nTheorem backward_small : forall A B : Prop, A -> (A -> B) -> B.\nProof.\n    intros A B.\n    intros poA atob.\n    refine (atob _).\n    exact poA.\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 a ab abc.\n    refine (abc _ _).\n    exact a.\n    refine (ab _).\n    exact a.\nQed.\n\nInductive Or (A B : Prop) : Prop :=\n    | inlS : A -> Or A B\n    | inrS : B -> Or A B.\n\nInductive And (A B : Prop) : Prop :=\n    | conjS : A -> B -> And A B.\n\nNotation \"A || B\" := (Or A B) : my_scope.\nNotation \"A && B\" := (And A B) : my_scope.\n\nOpen Scope my_scope.\n\nTheorem or_commutes : forall A B, 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 (inrS _ _ _).\n    exact proof_of_A.\n    intros proof_of_B.\n    refine (inlS _ _ _).\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    case A_and_B.\n    intros proof_of_A proof_of_B.\n    refine (conjS _ _ _ _).\n    exact proof_of_B.\n    exact proof_of_A.\nQed.\n", "meta": {"author": "AVBelyy", "repo": "HoTT-ITMO", "sha": "af4012c27569f4576f85403a5fa8cd3063dd59de", "save_path": "github-repos/coq/AVBelyy-HoTT-ITMO", "path": "github-repos/coq/AVBelyy-HoTT-ITMO/HoTT-ITMO-af4012c27569f4576f85403a5fa8cd3063dd59de/coq-intro/playings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7778508474459097}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import PartSum.\nLocal Open Scope R_scope.\n\nDefinition C (n p:nat) : R :=\nINR (fact n) / (INR (fact p) * INR (fact (n - p))).\n\nLemma pascal_step1 : forall n i:nat, (i <= n)%nat -> C n i = C n (n - i).\nProof. hammer_hook \"Binomial\" \"Binomial.pascal_step1\".  \nintros; unfold C; replace (n - (n - i))%nat with i.\nrewrite Rmult_comm.\nreflexivity.\napply plus_minus; rewrite plus_comm; apply le_plus_minus; assumption.\nQed.\n\nLemma pascal_step2 :\nforall n i:nat,\n(i <= n)%nat -> C (S n) i = INR (S n) / INR (S n - i) * C n i.\nProof. hammer_hook \"Binomial\" \"Binomial.pascal_step2\".  \nintros; unfold C; replace (S n - i)%nat with (S (n - i)).\ncut (forall n:nat, fact (S n) = (S n * fact n)%nat).\nintro; repeat rewrite H0.\nunfold Rdiv; repeat rewrite mult_INR; repeat rewrite Rinv_mult_distr.\nring.\napply INR_fact_neq_0.\napply INR_fact_neq_0.\napply not_O_INR; discriminate.\napply INR_fact_neq_0.\napply INR_fact_neq_0.\napply prod_neq_R0.\napply not_O_INR; discriminate.\napply INR_fact_neq_0.\nintro; reflexivity.\napply minus_Sn_m; assumption.\nQed.\n\nLemma pascal_step3 :\nforall n i:nat, (i < n)%nat -> C n (S i) = INR (n - i) / INR (S i) * C n i.\nProof. hammer_hook \"Binomial\" \"Binomial.pascal_step3\".  \nintros; unfold C.\ncut (forall n:nat, fact (S n) = (S n * fact n)%nat).\nintro.\ncut ((n - i)%nat = S (n - S i)).\nintro.\npattern (n - i)%nat at 2; rewrite H1.\nrepeat rewrite H0; unfold Rdiv; repeat rewrite mult_INR;\nrepeat rewrite Rinv_mult_distr.\nrewrite <- H1; rewrite (Rmult_comm (/ INR (n - i)));\nrepeat rewrite Rmult_assoc; rewrite (Rmult_comm (INR (n - i)));\nrepeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym.\nring.\napply not_O_INR; apply minus_neq_O; assumption.\napply not_O_INR; discriminate.\napply INR_fact_neq_0.\napply INR_fact_neq_0.\napply prod_neq_R0; [ apply not_O_INR; discriminate | apply INR_fact_neq_0 ].\napply not_O_INR; discriminate.\napply INR_fact_neq_0.\napply prod_neq_R0; [ apply not_O_INR; discriminate | apply INR_fact_neq_0 ].\napply INR_fact_neq_0.\nrewrite minus_Sn_m.\nsimpl; reflexivity.\napply lt_le_S; assumption.\nintro; reflexivity.\nQed.\n\n\nLemma pascal :\nforall n i:nat, (i < n)%nat -> C n i + C n (S i) = C (S n) (S i).\nProof. hammer_hook \"Binomial\" \"Binomial.pascal\".  \nintros.\nrewrite pascal_step3; [ idtac | assumption ].\nreplace (C n i + INR (n - i) / INR (S i) * C n i) with\n(C n i * (1 + INR (n - i) / INR (S i))); [ idtac | ring ].\nreplace (1 + INR (n - i) / INR (S i)) with (INR (S n) / INR (S i)).\nrewrite pascal_step1.\nrewrite Rmult_comm; replace (S i) with (S n - (n - i))%nat.\nrewrite <- pascal_step2.\napply pascal_step1.\napply le_trans with n.\napply le_minusni_n.\napply lt_le_weak; assumption.\napply le_n_Sn.\napply le_minusni_n.\napply lt_le_weak; assumption.\nrewrite <- minus_Sn_m.\ncut ((n - (n - i))%nat = i).\nintro; rewrite H0; reflexivity.\nsymmetry ; apply plus_minus.\nrewrite plus_comm; rewrite le_plus_minus_r.\nreflexivity.\napply lt_le_weak; assumption.\napply le_minusni_n; apply lt_le_weak; assumption.\napply lt_le_weak; assumption.\nunfold Rdiv.\nrepeat rewrite S_INR.\nrewrite minus_INR.\ncut (INR i + 1 <> 0).\nintro.\napply Rmult_eq_reg_l with (INR i + 1); [ idtac | assumption ].\nrewrite Rmult_plus_distr_l.\nrewrite Rmult_1_r.\ndo 2 rewrite (Rmult_comm (INR i + 1)).\nrepeat rewrite Rmult_assoc.\nrewrite <- Rinv_l_sym; [ idtac | assumption ].\nring.\nrewrite <- S_INR.\napply not_O_INR; discriminate.\napply lt_le_weak; assumption.\nQed.\n\n\n\nLemma binomial :\nforall (x y:R) (n:nat),\n(x + y) ^ n = sum_f_R0 (fun i:nat => C n i * x ^ i * y ^ (n - i)) n.\nProof. hammer_hook \"Binomial\" \"Binomial.binomial\".  \nintros; induction  n as [| n Hrecn].\nunfold C; simpl; unfold Rdiv;\nrepeat rewrite Rmult_1_r; rewrite Rinv_1; ring.\npattern (S n) at 1; replace (S n) with (n + 1)%nat; [ idtac | ring ].\nrewrite pow_add; rewrite Hrecn.\nreplace ((x + y) ^ 1) with (x + y); [ idtac | simpl; ring ].\nrewrite tech5.\ncut (forall p:nat, C p p = 1).\ncut (forall p:nat, C p 0 = 1).\nintros; rewrite H0; rewrite <- minus_n_n; rewrite Rmult_1_l.\nreplace (y ^ 0) with 1; [ rewrite Rmult_1_r | simpl; reflexivity ].\ninduction  n as [| n Hrecn0].\nsimpl; do 2 rewrite H; ring.\n\nset (N := S n).\nrewrite Rmult_plus_distr_l.\nreplace (sum_f_R0 (fun i:nat => C N i * x ^ i * y ^ (N - i)) N * x) with\n(sum_f_R0 (fun i:nat => C N i * x ^ S i * y ^ (N - i)) N).\nreplace (sum_f_R0 (fun i:nat => C N i * x ^ i * y ^ (N - i)) N * y) with\n(sum_f_R0 (fun i:nat => C N i * x ^ i * y ^ (S N - i)) N).\nrewrite (decomp_sum (fun i:nat => C (S N) i * x ^ i * y ^ (S N - i)) N).\nrewrite H; replace (x ^ 0) with 1; [ idtac | reflexivity ].\ndo 2 rewrite Rmult_1_l.\nreplace (S N - 0)%nat with (S N); [ idtac | reflexivity ].\nset (An := fun i:nat => C N i * x ^ S i * y ^ (N - i)).\nset (Bn := fun i:nat => C N (S i) * x ^ S i * y ^ (N - i)).\nreplace (pred N) with n.\nreplace (sum_f_R0 (fun i:nat => C (S N) (S i) * x ^ S i * y ^ (S N - S i)) n)\nwith (sum_f_R0 (fun i:nat => An i + Bn i) n).\nrewrite plus_sum.\nreplace (x ^ S N) with (An (S n)).\nrewrite (Rplus_comm (sum_f_R0 An n)).\nrepeat rewrite Rplus_assoc.\nrewrite <- tech5.\nfold N.\nset (Cn := fun i:nat => C N i * x ^ i * y ^ (S N - i)).\ncut (forall i:nat, (i < N)%nat -> Cn (S i) = Bn i).\nintro; replace (sum_f_R0 Bn n) with (sum_f_R0 (fun i:nat => Cn (S i)) n).\nreplace (y ^ S N) with (Cn 0%nat).\nrewrite <- Rplus_assoc; rewrite (decomp_sum Cn N).\nreplace (pred N) with n.\nring.\nunfold N; simpl; reflexivity.\nunfold N; apply lt_O_Sn.\nunfold Cn; rewrite H; simpl; ring.\napply sum_eq.\nintros; apply H1.\nunfold N; apply le_lt_trans with n; [ assumption | apply lt_n_Sn ].\nreflexivity.\nunfold An; fold N; rewrite <- minus_n_n; rewrite H0;\nsimpl; ring.\napply sum_eq.\nintros; unfold An, Bn.\nchange (S N - S i)%nat with (N - i)%nat.\nrewrite <- pascal;\n[ ring\n| apply le_lt_trans with n; [ assumption | unfold N; apply lt_n_Sn ] ].\nunfold N; reflexivity.\nunfold N; apply lt_O_Sn.\nrewrite <- (Rmult_comm y); rewrite scal_sum; apply sum_eq.\nintros; replace (S N - i)%nat with (S (N - i)).\nreplace (S (N - i)) with (N - i + 1)%nat; [ idtac | ring ].\nrewrite pow_add; replace (y ^ 1) with y; [ idtac | simpl; ring ];\nring.\napply minus_Sn_m; assumption.\nrewrite <- (Rmult_comm x); rewrite scal_sum; apply sum_eq.\nintros; replace (S i) with (i + 1)%nat; [ idtac | ring ]; rewrite pow_add;\nreplace (x ^ 1) with x; [ idtac | simpl; ring ];\nring.\nintro; unfold C.\nreplace (INR (fact 0)) with 1; [ idtac | reflexivity ].\nreplace (p - 0)%nat with p; [ idtac | apply minus_n_O ].\nrewrite Rmult_1_l; unfold Rdiv; rewrite <- Rinv_r_sym;\n[ reflexivity | apply INR_fact_neq_0 ].\nintro; unfold C.\nreplace (p - p)%nat with 0%nat; [ idtac | apply minus_n_n ].\nreplace (INR (fact 0)) with 1; [ idtac | reflexivity ].\nrewrite Rmult_1_r; unfold Rdiv; rewrite <- Rinv_r_sym;\n[ reflexivity | apply INR_fact_neq_0 ].\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/Binomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7778430800029211}}
{"text": "Require Import ZArith.\nRequire Import Arith.\n\nOpen Scope Z_scope.\n\nFixpoint sum_f (f:nat -> Z) (n:nat)  : Z :=\n  match n with\n  | O => f O\n  | S p => sum_f f p + f n\n  end.\n\nTheorem sum_n : forall n:nat, 2 * sum_f Z_of_nat n = \n                              Z_of_nat n * (Z_of_nat n + 1).\nProof.\n induction n as [| p IHp].\n -  reflexivity. \n -  lazy beta iota zeta delta [sum_f]; fold sum_f.\n     rewrite Zmult_plus_distr_r; rewrite IHp.\n     rewrite inj_S ; unfold Zsucc ; ring.\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/exo_sum_f.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811581728097, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7777421289022822}}
{"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_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\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (rev (qreva x y)) (append (rev y) x).\nProof.\n  induction x.\n  - intros. simpl. rewrite append_nil. 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/goal77.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7776952812043737}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Some basic functions *)\n\nDefinition const {A B} (a : A) :=\n  fun _ : B => a.\n\nDefinition flip {A B C} (f : A -> B -> C) : B -> A -> C :=\n  fun b a => f a b.\n\nArguments const {A B} a _ /.\nArguments flip {A B C} f b a /.\n\n\n(* move to logic_exercises *)\nSection IntLogic.\n\nVariables A B C D : Prop.\n\nLemma axiomK :\n  A -> B -> A.\nProof. exact: const. Qed.\n\n\n(* note: flip is more general *)\nLemma contraposition :\n  (A -> ~ B) -> (B -> ~ A).\nProof. exact: flip. Qed.\n\n\nLemma p_imp_np_iff_np : (A -> ~A)  <->  ~A.\nProof.\n(* a step-by-step solution *)\nsplit.\n- rewrite /not. move=> a_na. move=> a. exact: (a_na a a).\nmove=> na _. exact: na.\n\nRestart.\n(* a more idiomatic solution *)\nby split=> // a_na a; apply: a_na.\n(**\nExplanation: the proof of the last branch of the step-by-step proof\nis trivial, so it can be handled with [//].\nThis leaves us with just the first subgoal.\n[move=> a_na. move=> a.] can be merged into [move=> a_na a.]\nwhich itself can be melded into the preceeding [split] tactic.\n\nThe [tac1; tac2] construction allows us to apply [tac2] tactic\nto all the subgoals we are left with after applying [tac1] tactic.\n *)\nQed.\n\n\n(* We can generalize the previous lemma into *)\nLemma p_p_q_iff_p_q :\n  (A -> A -> B)  <->  (A -> B).\nProof. by split=> // a_na a; apply: a_na. Qed.\n\n\nLemma p_is_not_equal_not_p :\n  ~ (A <-> ~ A).\nProof.\n(** The \"defective\" form of [move] tactic brings the goal to\n    the head normal form (hnf).\n    Defective here means \"not combined with anything else\".\n *)\nmove.\n(** Amounts to \"unfold all definitions\" in this case.\n    The goal after applying [compute] tactic can be\n    easier to understand, but this really depends on\n    how much experience you have with unfolding those\n    definitions mentally.\n *)\ncompute.\n(** Now that we have conjunction as the top of the goal stack,\n    we can have access to the individual conjuncts.\n *)\ncase. move=> aaf af_a.\n(** Parentheses around a hypothesis let us reuse it later,\n    had we omitted those, we would have it erased from the context.\n *)\napply: (aaf).\n- apply: af_a. move=> a. exact: (aaf a a).\napply: af_a. move=> a. exact: (aaf a a).   (* duplication! *)\n\nRestart.\n\n(** A refactored version of the above proof *)\ncase=> aaf af_a.\n(** We use [have ident : statement by tactic] form to prove [A] beforehand\n    and call it [a] in the context.\n  *)\nhave a: A by apply: af_a=> a; apply: aaf.\nby apply: aaf.\nQed.\n\n\nLemma not_not_lem :\n  ~ ~ (A \\/ ~ A).\nProof.\nmove=> not_lem.\napply: (not_lem).\nright.\nmove=> a.\napply: not_lem.\nleft.\nexact: a.\n\nRestart.\n\n(** a shorter version *)\nmove=> not_lem; apply: (not_lem); right=> a.\nby apply: not_lem; left.\nQed.\n\nLemma constructiveDNE :\n  ~ ~ ~ A  ->  ~ A.\nProof.\nmove=> nnna.\nmove=> a.\napply: nnna.\nmove=> na.\napply: na.\nexact: a.\n\nRestart.\n\n(** A shorter version *)\nby move=> nnna a; apply: nnna.\nQed.\n\nEnd IntLogic.\n\n\n\n\n(* Boolean logic (decidable fragment enjoys classical laws) *)\n\nSection BooleanLogic.\n\nLemma LEM_decidable a :\n  a || ~~ a.\nProof.\nby case: a.\n(** the rest of the proof is by computation *)\nQed.\n\nLemma disj_implb a b :\n  a || (a ==> b).\nProof.\nby case: a.\n(** Here we only need to case analyse on [a].\n    Make sure you understand why.\n    (Hint: look at the definitions and see if knowing the form\n           of [b] is really needed here)\n *)\nQed.\n\nLemma iff_is_if_and_only_if a b :\n  (a ==> b) && (b ==> a) = (a == b).\nProof. by case: a; case: b. Qed.\n\nLemma implb_trans : transitive implb.\nProof.\nrewrite /transitive. move=> b a c. case: a.\n- move=> /=. (* simplify goal *)\n  (* The head of the goal is an (implicit) equation [b = true].\n     How to check it? *)\n  move->.  (* rewrite with the head of the goal stack *)\n  move=> /=.\n  by [].\nby [].\n\nRestart.\n\n(** A more idiomatic version *)\nby move=> b [] c //= ->.\n\n(** Explanation:\n\n[by move=> b [] c //= ->]\n             ^    ^\n             |    |\n             |    solve trivial goals (//) and simplify (/=) combined\n             |\n             inplace case analysis ([case: a])\n*)\nQed.\n\nLemma triple_compb (f : bool -> bool) :\n  f \\o f \\o f =1 f.\nProof.\nby case=> /=; case Et: (f true); case Ef: (f false); rewrite ?Ef ?Et.\nQed.\n\n\n\n(* negb \\o odd means \"even\" *)\nLemma even_add :\n  {morph (negb \\o odd) : x y / x + y >-> x == y}.\nProof.\nmove=> x y /=.\nby rewrite odd_add negb_add eqb_negLR negbK.\nQed.\n\nEnd BooleanLogic.\n\n\n(* some properties of functional composition *)\n\nSection eq_comp.\nVariables A B C D : Type.\n\nLemma compA (f : A -> B) (g : B -> C) (h : C -> D) :\n  h \\o g \\o f = h \\o (g \\o f).\nProof. by []. Qed.\n\nLemma eq_compl (f g : A -> B) (h : B -> C) :\n  f =1 g -> h \\o f =1 h \\o g.\nProof. by move=> eq_fg; apply: eq_comp. Qed.\n\nLemma eq_compr (f g : B -> C) (h : A -> B) :\n  f =1 g -> f \\o h =1 g \\o h.\nProof. by move=> eq_fg; apply: eq_comp. Qed.\n\nLemma eq_idl (g1 g2 : A -> B) (f : B -> B) :\n  f =1 id -> f \\o g1 =1 f \\o g2 -> g1 =1 g2.\nProof.\nmove=> f_id g12f a.\nmove: (g12f a). move=> /=.\nrewrite f_id. rewrite f_id.\ndone.\n\nRestart.\n\n(* idiomatic solution *)\nby move=> f_id g12f a; move: (g12f a)=> /=; rewrite !f_id.\nQed.\n\nLemma eq_idr (f1 f2 : A -> B) (g : A -> A) :\n  g =1 id -> f1 \\o g =1 f2 \\o g -> f1 =1 f2.\nProof.\nby move=> g_id f12g a; move: (f12g a)=> /=; rewrite g_id.\nQed.\n\nEnd eq_comp.\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/seminars/seminar02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7776952680694128}}
{"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 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\nEval simpl in compile (Binop Plus (Const 2) (Const 2)).\n\nEval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nEval simpl in progDenote (compile (Const 42)) nil.\n\nEval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.\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).\n\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 compile.\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  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.\nAbort.\n\nLemma compile_correct' : 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,\n    progDenote (compile e) nil = 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\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 2)) (TNConst 7)).\n\nEval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\nDefinition tstack : Set := 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\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 =>\n    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 _) (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 2)) (TNConst 7)) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\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).\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", "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/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7776416692449405}}
{"text": "(*|\n############################################################\nCoq theorem proving: Simple fraction law in peano arithmetic\n############################################################\n\n:Link: https://stackoverflow.com/q/59120093\n|*)\n\n(*|\nQuestion\n********\n\nI am learning coq and am trying to prove equalities in peano\narithmetic.\n\nI got stuck on a simple fraction law.\n\nWe know that ``(n + m) / 2 = n / 2 + m / 2`` from primary school. In\npeano arithmetic this does only hold if n and m are even (because then\ndivision produces correct results).\n|*)\n\nRequire Import Arith Even.\n\nCompute (3 / 2) + (5 / 2). (*3*)\nCompute (3 + 5) / 2. (*4*)\n\n(*| So we define: |*)\n\nTheorem fraction_addition: forall n m: nat ,\n    even n -> even m ->  Nat.div2 n + Nat.div2 m = Nat.div2 (n + m).\n\n(*|\nFrom my understanding this is a correct and provable theorem. I tried\nan inductive proof, e.g.\n|*)\n\n  intros n m en em. induction n.\n  - reflexivity.\n  - (* .unfold *)\nAbort. (* .none *)\n\n(*|\nSo I don't find a way to apply the induction hypothesis.\n\nAfter long research of the standard library and documentation, i don't\nfind an answer.\n|*)\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nYou need to strengthen your induction hypothesis in cases like this.\nOne way of doing this is by proving an induction principle like this\none:\n|*)\n\nFrom Coq Require Import Arith Even.\nLemma nat_ind2 (P : nat -> Prop) :\n  P 0 -> P 1 -> (forall n, P n -> P (S n) -> P (S (S n))) ->\n  forall n, P n.\nProof.\n  now intros P0 P1 IH n; enough (H : P n /\\ P (S n)); [|induction n]; intuition.\nQed.\n\n(*| ``nat_ind2`` can be used as follows: |*)\n\nTheorem fraction_addition n m :\n  even n -> even m -> Nat.div2 n + Nat.div2 m = Nat.div2 (n + m).\nProof.\n  induction n using nat_ind2.\n  (* here goes the rest of the proof *)\nAdmitted.\n\n(*|\nAnswer (larsr)\n**************\n\nYou can also prove your theorem without induction if you are ok with\nusing the standard library.\n\nIf you use ``Even m`` in your hypothesis (which says ``exists n, m =\n2*m``) then you can use simple algebraic rewrites with lemmas from the\nstandard library.\n|*)\n\nRequire Import PeanoNat.\nImport Nat.\n\nGoal forall n m, Even n -> Even m -> n / 2 + m / 2 = (n + m) / 2.\n  inversion 1; inversion 1.\n  subst.\n  rewrite <- mul_add_distr_l.\n  rewrite ?(mul_comm 2).\n  rewrite ?(div_mul); auto.\nQed.\n\n(*|\nThe question mark just means \"rewrite as many (zero or more) times as\npossible\".\n\n``inversion 1`` does inversion on the first inductive hypothesis in\nthe goal, in this case first ``Even n`` and then ``Even m``. It gives\nus ``n = 2 * x`` and ``m = 2 * x0`` in the context, which we then\nsubstitute.\n\nAlso note ``even_spec: forall n : nat, even n = true <-> Even n``, so\nyou can use ``even`` if you prefer that, just rewrite with\n``even_spec`` first...\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/coq-theorem-proving-simple-fraction-law-in-peano-arithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7774170527224938}}
{"text": "(**\nコンピュータの数学 2.6 離散系および連続系の微積分学（和差分学)\n======\n\n自然数での下降階乗冪と上昇階乗冪の和分差分の計算 ffact, rfact\n\n2022_08_28 @suharahiromichi\n*)\nFrom mathcomp Require Import all_ssreflect.\nFrom common Require Import ssrsumop ssromega.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n(**\n# 和分差分学の定義と補題\n *)\nSection FINCAL.\n(**\n## 短調増加\n*)\n  Definition monotone a := forall (x : nat), a x <= a x.+1.\n\n(**\n## 差分 difference \n\n````\ndiff b = diff (fun x => b x) = Δb x / Δx = a x\n```\nを求める。連続系とのアナロジーでは、b は a の原始関数となる。\n*)\n  Definition diff b := fun x => b x.+1 - b x. (* = a *)\n\n(**\n### 差分の公式\n *)\n  Lemma diff_split a b (x : nat) :\n    monotone a -> monotone b ->\n    diff a x + diff b x = diff (fun x => a x + b x) x.\n  Proof.\n    move=> Ha Hb.\n    rewrite /diff.\n    rewrite addnBA; last done.\n    rewrite subnDA.\n    rewrite addnBAC; last done.\n    done.\n  Qed.\n\n  Lemma diff_distr c b (x : nat) :\n    c * diff b x = diff (fun x => c * b x) x.\n  Proof.\n    rewrite /diff.\n    by rewrite mulnBr.\n  Qed.\n\n(**\n## 和分 summation\n\n### 和分の定義\n\n```Σb(x)δx = Σ(n1 <= k < n2) b(x)```\n *)\n  Definition summ b n1 n2 := \\sum_(n1 <= x < n2)(b x).\n\n(**\n### 差分と和分の関係\n*) \n(**\n差分・和分の基本公式 : 微積分の基本公式のアナロジー (by mh)\n\nΣ a を計算することは a n = b n+1 - b n となる数列 b が既知であれば, \nb の差を求めることである。\n\n積分計算とのアナロジーで b を a の原始関数と言ってもよいでしょう ...\n```\nF'(x) = f(x) のとき ∫ f(x)dx = F(x_max) - F(x_min)\n```\n\n総和の場合は、(``diff b = a``)\n```\nb n+1 - b n = a n のとき Σa = b n+1 - b 0\n```\n*)\n  Lemma summ_diff' b m : b 0 = 0 ->\n                         (forall n, b n <= b n.+1) ->\n                         summ (diff b) 0 m = b m.\n  Proof.\n    move=> Hf0 Hfn.\n    rewrite /summ /diff.\n    elim: m.\n    - rewrite sum_nil'.\n      by rewrite Hf0.\n    - move=> n IHn.\n      rewrite sum_last; last done.\n      rewrite IHn.\n      by rewrite subnKC.\n  Qed.\n  \n(**\n一般に成立するはずの関係\n*) \n  Lemma summ_diff b n1 n2 : n1 <= n2 -> summ (diff b) n1 n2 = b n2 - b n1.\n  Proof.\n    rewrite /summ /diff.\n  Admitted.                                 (* 不使用 *)\n\n(**\n### 和分の公式\n *)\n  Lemma summ_nil a n :  summ a n n = 0.\n  Proof.\n    rewrite /summ.\n    by rewrite sum_nil.\n  Qed.\n  \n  Lemma summ_split a b n1 n2 :\n    n1 <= n2 ->\n    summ a n1 n2 + summ b n1 n2 = summ (fun x => a x + b x) n1 n2.\n  Proof.\n    rewrite leq_eqVlt => /orP [Heq | Hlt].\n    - move/eqP in Heq.                      (* n1 = n2 の場合 *)\n      rewrite -Heq.\n      by rewrite 3!summ_nil.\n    - rewrite /summ.                        (* n1 < n2 の場合 *)\n      by apply: sum_split.\n  Qed.\n\n  Lemma summ_distr c a n1 n2 :\n    n1 <= n2 -> c * summ a n1 n2 = summ (fun x => c * a x) n1 n2.\n  Proof.\n    rewrite leq_eqVlt => /orP [Heq | Hlt].\n    - move/eqP in Heq.                      (* n1 = n2 の場合 *)\n      rewrite -Heq.\n      by rewrite 2!summ_nil muln0.\n    - by rewrite /summ sum_distrr.\n  Qed.\n\n(**\n## 一般化した関数拡張の公理\n\n関数の部分だけを取り出して関数拡張する場合、Standard Coq の\nfunctional_extensionality を使うのではだめで、\n引数xが m≦x である条件を追加する必要がある。\n*)\n(*  \n  Axiom functional_extensionality_ge_m : \n    forall (m : nat) (f g : nat -> nat),\n      (forall x : nat, m <= x -> f x = g x) -> f = g.\n*)\n  Axiom functional_extensionality' : \n    forall (A B : Type) (P : A -> Prop) (a b : A -> B),\n      (forall (x : A), P x -> a x = b x) -> a = b.\n  Check fun (m : nat) => @functional_extensionality' nat nat (leq m).\n\nEnd FINCAL.\n  \n(**\n# 下降階乗冪 ffact, falling_factorial\n *)\nSection FFACT.\n(**\n## 補題\n *)\n  Check ffactn0 : forall n : nat, n ^_ 0 = 1.\n  Check ffactn1 : forall n : nat, n ^_ 1 = n.\n  Check ffact0n : forall m : nat, 0 ^_ m = (m == 0).\n  Lemma  ffact0n' m : 0 < m ->  0 ^_ m = 0.\n  Proof. by case: m. Qed.\n  \n(**\nx^_m が x に対して単調に増加することの証明\n\n``monotone (falling_factorial^~ m)`` という記法は使わないことにします。\n*)\n  Lemma ffact_monotone m : monotone (fun x => x ^_ m).\n  Proof.\n    move=> x.\n    case: m => // m.                        (* m = 0 の場合を片付ける。 *)\n    rewrite ffactSS ffactnSr.               (* m ≧ 1 の場合 *)\n    rewrite mulnC leq_mul2r.\n    apply/orP/or_intror.\n    by ssromega.\n  Qed.\n  \n(**\n## 下降階乗冪の差分\n\n```Δx^_(m + 1) / Δx = (m + 1) * x^_m```\n*)  \n  Lemma diff_ffactE' (m : nat) (x : nat) :\n    m <= x -> diff (fun x => x^_m.+1) x = m.+1 * x^_m.\n  Proof.\n    move=> Hmx.\n(*\ndiff (falling_factorial^~ m.+1) x = m.+1 * x ^_ m\n*)\n    rewrite /diff.\n    rewrite ffactSS ffactnSr [x^_m * (x - m)]mulnC.\n    rewrite mulnBl mulSnr.\n    rewrite subnBA; last by rewrite leq_mul.\n    rewrite -[x * x^_m + x^_m + m * x^_m]addnA.\n    rewrite -{2}[x * x^_m]addn0 subnDl subn0.\n    rewrite -mulSn.\n    done.\n  Qed.\n(**\n``->`` の右のxを抽象して ``=1`` のかたちにすると、\n``m <= x``の条件が無視されるため、あとで適用したときに証明が進まなくなる。\n*)\n  \n(**\nより直感的かかたち：\n\n```Δx^_m / Δx = m * x^_(m - 1)```\n*)  \n  Lemma diff_ffactE (m : nat) (x : nat) :\n    0 < m -> m <= x -> diff (fun x => x^_m) x = m * x^_m.-1.\n  (*                         b                  a *)\n  Proof.\n    case: m => //=.\n    move=> m H0m Hmx.\n    rewrite diff_ffactE' //.\n    by ssromega.\n  Qed.\n  \n(**\n## 下降階乗冪の和分\n\n下降階乗冪の和分（0から）\nx*)\n  Lemma summ_ffactE' (m : nat) (n : nat) :\n    1 <= m -> m <= n -> summ (fun x => m * x^_m.-1) 0 n = n^_m.\n  (*                          a *)\n  Proof.\n    move=> Hm.                         (* 0^^1 = 1 を回避するため。 *)\n    move=> Hmn.\n    rewrite -[RHS](@summ_diff' (fun x => x^_m)) //.\n    (*                          b *)\n    - congr (summ _ 0 n).\n      apply: (@functional_extensionality' _ _ (leq m)) => x Hmx.\n      by rewrite diff_ffactE.\n    - by apply: ffact0n'.\n    - move=> x.\n      by apply: ffact_monotone.\n  Qed.\n(**\nbigopの関数部分をcongrで取り出し、一般化した関数拡張の公理を使用して証明する。\n*)\n  \n(**\n下降階乗冪の和分（任意のaから）\n*)  \n  Lemma summ_ffactE (m : nat) (n1 n2 : nat) :\n    n1 <= n2 -> m < n1 -> summ (fun x => x * x^_m) n1 n2 = n2^_m.+1.\n  Proof.\n  Admitted.                                 (* 不使用 *)\n\nEnd FFACT.\n\n(**\n# 上昇階乗冪 rfact, rising_factorial\n\n定義およびrfactについての証明は hm 氏による。\n *)\nSection RFACT.\n  Fixpoint rfact_rec n m := if m is m'.+1 then (n + m') * rfact_rec n m' else 1.\n(*\n  Fixpoint rfact_rec' n m := if m is m'.+1 then n * rfact_rec' n.+1 m' else 1.\n*)\n  Definition rising_factorial := nosimpl rfact_rec.\n  \n  Notation \"n ^^ m\" := (rising_factorial n m)\n                         (at level 30, right associativity).\n\n  Lemma rfactn0 n : n ^^ 0 = 1. Proof. by []. Qed.\n  \n  Lemma rfactn1 n : n ^^ 1 = n.\n  Proof.\n    rewrite /rising_factorial //=.\n    rewrite addn0.\n    by rewrite muln1.\n  Qed.\n  \n  Lemma rfactnSr n m : n ^^ m.+1 = n^^m * (n + m).\n  Proof.\n    case: m => [|m] //=.\n    - have -> : n ^^ 0 = 1 by [].\n      rewrite addn0.\n      rewrite rfactn1.\n      by rewrite mul1n.\n    - have -> : n ^^ m.+2 = (n + m.+1) * n ^^ m.+1 by [].\n      by rewrite mulnC.\n  Qed.\n  \n  Lemma rfactnS n m : n ^^ m.+1 = n * n.+1 ^^ m.\n  Proof.\n    elim: m => [|m IHm].\n    - rewrite rfactn1.\n      have -> : n.+1 ^^ 0 = 1 by [].\n      by rewrite muln1.\n    - have -> : n ^^ m.+2 = (n + m.+1) * n ^^ m.+1 by [].\n      rewrite IHm.\n      rewrite rfactnSr.\n      have -> : n + m.+1 = (n+m+1) by ssromega.\n      have -> : n.+1 + m = (n+m+1) by ssromega.\n      ring.\n  Qed.  \n  \n  Lemma rfactSS n m : n.+1 ^^ m.+1 = n.+1 ^^ m * (n + m.+1).\n  Proof.\n    rewrite rfactnSr.\n    by rewrite addSnnS.\n  Qed.\n  \n  Lemma rfact0n m : 0 ^^ m = (m == 0).\n  Proof.\n    case: m => //= m.\n    by rewrite rfactnS mul0n.    \n  Qed.\n  \n  Lemma rfact0n' m : 0 < m -> 0 ^^ m = 0.\n  Proof.\n    case: m => //= m Hm.\n    by rewrite rfactnS mul0n.\n  Qed.\n  \n(**\nx^^m が x に対して単調に増加することの証明\n*)\n  Lemma rfact_monotone m : monotone (fun x => x ^^ m).\n  Proof.\n    move=> x.\n    case: m => // m.                        (* m = 0 の場合を片付ける。 *)\n    rewrite rfactSS rfactnS.                (* m ≧ 1 の場合 *)\n(*\n``x ^_ m * (x - m) <= x.+1 * x ^_ m``\n*)\n    rewrite mulnDr mulnC.\n    by rewrite leq_addr.\n  Qed.\n  \n(**\n## 上昇階乗冪の差分\n\n```Δx^^(m + 1) / Δx = (m + 1) * (x + 1)^^m```\n*)  \n  Lemma diff_rfactE' (m : nat) (x : nat) :\n    m <= x -> diff (fun x => x^^m.+1) x = m.+1 * x.+1^^m.\n  Proof.\n    move=> Hmx.\n    rewrite /diff.\n    rewrite rfactSS rfactnS.\n    rewrite [x.+1 ^^ m * (x + m.+1)]mulnC.\n    rewrite mulnDl addnC -addnBA //=.\n    by rewrite subnn addn0.\n  Qed.\n  \n(**\nより直感的かかたち：\n\n```Δx^^m / Δx = m * (x + 1)^^(m - 1)```\n*)  \n  Lemma diff_rfactE (m : nat) (x : nat) :\n    0 < m -> m <= x -> diff (fun x => x^^m) x = m * x.+1^^m.-1.\n  (*                         b                  a *)\n  Proof.\n    case: m => //=.\n    move=> m H0m Hmx.\n    rewrite diff_rfactE' //.\n    by ssromega.\n  Qed.\n  \n(**\n## 上昇階乗冪の和分\n\n上昇階乗冪の和分（0から）\n*)\n  Lemma summ_rfactE' (m : nat) (n : nat) :\n    1 <= m -> m <= n -> summ (fun x => m * x.+1^^m.-1) 0 n = n^^m.\n  (*                          a *)\n  Proof.\n    move=> Hm.                         (* 0^^1 = 1 を回避するため。 *)\n    move=> Hmn.\n    Check (@summ_diff' (fun x => x^^m)).\n    rewrite -[RHS](@summ_diff' (fun x => x^^m)) //.\n    (*                          b *)\n    - congr (summ _ 0 n).\n      apply: (@functional_extensionality' _ _ (leq m)) => x Hmx.\n      by rewrite diff_rfactE.\n    - by apply: rfact0n'.\n    - move=> x.\n      by apply: rfact_monotone.\n  Qed.\n  \n(**\n上昇階乗冪の和分（任意のaから）\n*)  \n  Lemma summ_rfactE (m : nat) (n1 n2 : nat) :\n    n1 <= n2 -> m < n1 -> summ (fun x => x * x^^m) n1 n2 = n2^^m.+1.\n  Proof.\n  Admitted.                                 (* 不使用 *)\n  \nEnd RFACT.\n\nSection OPTION.\n(**\n# 補足\n\n## 特殊なかたち；\n\n```Δx/Δx = 1```\n*)  \n  Check @diff_ffactE' 0\n    : forall x : nat, 0 <= x -> diff (fun x => x^_1) x = 1 * x^_0.\n\n  Lemma diff_idE (x : nat) : diff id x = 1.\n  Proof.\n    rewrite -[RHS](ffactn0 x) -[RHS]mul1n.\n    rewrite -(@diff_ffactE' 0 x); last done.\n    rewrite /falling_factorial /ffact_rec.\n    rewrite /diff.\n    by ssromega.\n  Qed.\n  \n  Notation \"n ^^ m\" := (rising_factorial n m)\n                         (at level 30, right associativity).\n\n  Check @diff_rfactE' 0\n    : forall x : nat, 0 <= x -> diff (fun x => x^^1) x = 1 * x^^0.\n\n  Lemma diff_idE' (x : nat) : diff id x = 1.\n  Proof.\n    rewrite -[RHS](rfactn0 x) -[RHS]mul1n.\n    rewrite -(@diff_rfactE' 0 x); last done.\n    rewrite /rising_factorial /rfact_rec.\n    rewrite /diff.\n    by ssromega.\n  Qed.\n  \n(**\ndiff_ffactE' に対応する版\n*)\n  Lemma summ_ffactE'' (m : nat) (n : nat) :\n    1 <= m -> m <= n -> summ (fun x => m.+1 * x^_m) 0 n = n^_m.+1.\n  Proof.\n    move=> Hm.                         (* 0^_1 = 1 を回避するため。 *)\n    move=> Hmn.\n    rewrite -[RHS](@summ_diff' (fun x => x^_m.+1)) //.\n    - congr (summ _ 0 n).\n      apply: (@functional_extensionality' _ _ (leq m)) => x Hmx.\n      by rewrite diff_ffactE'.\n    - move=> x.\n      by apply: ffact_monotone.\n  Qed.\n\n(**\ndiff_rfactE' に対応する版\n*)\n  Lemma summ_rfactE'' (m : nat) (n : nat) :\n    1 <= m -> m <= n -> summ (fun x => m.+1 * x.+1^^m) 0 n = n^^m.+1.\n  Proof.\n    move=> Hm.                         (* 0^^1 = 1 を回避するため。 *)\n    move=> Hmn.\n    Check (@summ_diff' (fun x => x^^m)).\n    rewrite -[RHS](@summ_diff' (fun x => x^^m.+1)) //.\n    - congr (summ _ 0 n).\n      apply: (@functional_extensionality' _ _ (leq m)) => x Hmx.\n      by rewrite diff_rfactE'.\n    - by apply: rfact0n'.\n    - move=> x.\n      by apply: rfact_monotone.\n  Qed.\n  \nEnd OPTION.\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/gkp/gkp_2_6_fincal_ffact_rfact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7774067509494099}}
{"text": "Require Import msl.Extensionality.\n\n(* https://en.wikipedia.org/wiki/Lattice_(order) *)\n\nClass Lattice (A: Type) := mkLattice {\n  top : A;\n  bot : A;\n  glb : A -> A -> A;\n  lub : A -> A -> A;\n  glb_top_r : forall (a: A), glb a top = a;\n  lub_bot_r : forall (a: A), lub a bot = a;\n  glb_commut : forall (a b: A), glb a b = glb b a;\n  lub_commut : forall (a b: A), lub a b = lub b a;\n  glb_assoc : forall (a b c: A), glb a (glb b c) = glb (glb a b) c;\n  lub_assoc : forall (a b c: A), lub a (lub b c) = lub (lub a b) c;\n  glb_absorb : forall (a b: A), glb a (lub a b) = a;\n  lub_absorb : forall (a b: A), lub a (glb a b) = a;\n}.\n\nSection LatticeFacts.\n\nContext {A: Type}.\nContext {LA: Lattice A}.\n\nLemma glb_idempotent: forall (a: A), glb a a = a.\nProof.\n  intros. transitivity (glb a (lub a (glb a a))).\n  - f_equal. symmetry. apply lub_absorb.\n  - f_equal. apply glb_absorb.\nQed.\n\nLemma lub_idempotent: forall (a: A), lub a a = a.\nProof.\n  intros. transitivity (lub a (glb a (lub a a))).\n  - f_equal. symmetry. apply glb_absorb.\n  - f_equal. apply lub_absorb.\nQed.\n\nLemma glb_top_l: forall (a: A), glb top a = a.\nProof. intro. rewrite glb_commut. apply glb_top_r. Qed.\n\nLemma lub_bot_l: forall (a: A), lub bot a = a.\nProof. intro. rewrite lub_commut. apply lub_bot_r. Qed.\n\nLemma glb_bot_l: forall (a: A), glb bot a = bot.\nProof.\n  intro. transitivity (glb bot (lub bot a)).\n  - f_equal. symmetry. apply lub_bot_l.\n  - apply glb_absorb.\nQed.\n\nLemma lub_top_l: forall (a: A), lub top a = top.\nProof.\n  intro. transitivity (lub top (glb top a)).\n  - f_equal. symmetry. apply glb_top_l.\n  - apply lub_absorb.\nQed.\n\nLemma lub_top_r: forall (a: A), lub a top = top.\nProof. intro. rewrite lub_commut. apply lub_top_l. Qed.\n\nLemma glb_bot_r : forall (a: A), glb a bot = bot.\nProof. intro. rewrite glb_commut. apply glb_bot_l. Qed. \n\n(* \"lattice-lessthan-or-equal\" *)\nDefinition lle(a b: A): Prop := b = lub a b.\n\nLemma double_lle_eq: forall (a b: A), lle a b -> lle b a -> a = b.\nProof.\n  intros a b Le1 Le2. unfold lle in *. rewrite Le1. rewrite lub_commut. apply Le2.\nQed.\n\nLemma lle_lub_l: forall (a b: A), lle a (lub a b).\nProof.\n  intros. unfold lle. rewrite lub_assoc. rewrite lub_idempotent. reflexivity.\nQed.\n\nLemma lle_lub_r: forall (a b: A), lle b (lub a b).\nProof.\n  intros. unfold lle. rewrite lub_commut. rewrite lub_assoc. rewrite lub_idempotent. reflexivity.\nQed.\n\nLemma lle_bot_inv: forall (a: A), lle a bot -> a = bot.\nProof. intros. unfold lle in *. rewrite H. symmetry. apply lub_bot_r. Qed.\n\nLemma lub_bot_inv: forall (a b: A), lub a b = bot -> a = bot /\\ b = bot.\nProof.\n  intros.\n  pose proof (lle_lub_l a b) as C. rewrite H in C. apply lle_bot_inv in C.\n  pose proof (lle_lub_r a b) as D. rewrite H in D. apply lle_bot_inv in D.\n  apply (conj C D).\nQed.\n\nLemma lle_top: forall (a: A), lle a top.\nProof. intro. unfold lle. symmetry. apply lub_top_r. Qed.\n\nLemma lle_refl: forall (a: A), lle a a.\nProof. intro. unfold lle. symmetry. apply lub_idempotent. Qed.\n\nEnd LatticeFacts.\n\n\nInductive label : Set := Lo | Hi.\n\nInstance LoHi : Lattice label := {|\n  top := Hi;\n  bot := Lo;\n  glb := fun l1 l2 => match l1 with\n         | Hi => l2\n         | Lo => Lo\n         end;\n  lub := fun l1 l2 => match l1 with\n         | Lo => l2\n         | Hi => Hi\n         end\n|}.\n- intro a. destruct a; reflexivity.\n- intro a. destruct a; reflexivity.\n- intros a b. destruct a; destruct b; reflexivity.\n- intros a b. destruct a; destruct b; reflexivity.\n- intros a b c. destruct a; destruct b; destruct c; reflexivity.\n- intros a b c. destruct a; destruct b; destruct c; reflexivity.\n- intros a b. destruct a; destruct b; reflexivity.\n- intros a b. destruct a; destruct b; reflexivity.\nDefined.\n\nInstance LiftLattice {T A: Type} (LA: Lattice A): Lattice (T -> A) := {|\n  top := fun (x: T) => (@top A LA);\n  bot := fun (x: T) => (@bot A LA);\n  glb := fun (a b: T -> A) => (fun (x: T) => @glb A LA (a x) (b x));\n  lub := fun (a b: T -> A) => (fun (x: T) => @lub A LA (a x) (b x));\n|}.\n- intro. extensionality. apply glb_top_r.\n- intro. extensionality. apply lub_bot_r.\n- intros. extensionality. apply glb_commut.\n- intros. extensionality. apply lub_commut.\n- intros. extensionality. apply glb_assoc.\n- intros. extensionality. apply lub_assoc.\n- intros. extensionality. apply glb_absorb.\n- intros. extensionality. apply lub_absorb.\nDefined.\n\n(* Now we have lub and glb available for any number of lifting levels:\n\nCheck (glb (fun (i: nat) => Hi) (fun (i: nat) => Lo)).\nCheck (glb (fun (x: nat) (i: nat*nat) => Hi) (fun (x: nat) (i: nat*nat) => Lo)).\nEval simpl in (lub (fun (x: nat) (i: nat*nat) => Hi) (fun (x: nat) (i: nat*nat) => Lo)).\nEval simpl in (lub (fun (x: nat) (i: nat*nat) => Lo) (fun (x: nat) (i: nat*nat) => Lo)).\n\nIncluding all the lemmas!\n*)\n\nSection LiftLatticeFacts.\n\nContext {T: Type}.\nContext {A: Type}.\nContext {LA: Lattice A}.\n\nLemma lle_pointwise: forall (f1 f2: T -> A), lle f1 f2 <-> forall (x: T), lle (f1 x) (f2 x).\nProof.\n  split.\n  - intros. unfold lle in *. pose proof (equal_f H) as C. apply C.\n  - intro. unfold lle in *. extensionality. apply H.\nQed.\n\nEnd LiftLatticeFacts.\n\n(* Basically just a lattice on A, but with an additional element \"None\" sitting on top\n   of the whole lattice.\n   We chose to put \"None\" at the top because it means absence of classification information,\n   in which case we have to assume that it is classified as Hi, which is top. *)\nInstance OptionLattice {A: Type} (LA: Lattice A): Lattice (option A) := {|\n  top := (@None A);\n  bot := Some (@bot A LA);\n  glb := fun (oa ob: option A) => match oa, ob with\n         | None  , None   => None\n         | Some a, None   => Some a\n         | None  , Some b => Some b\n         | Some a, Some b => Some (@glb A LA a b)\n         end;\n  lub := fun (oa ob: option A) => match oa, ob with\n         | Some a, Some b => Some (@lub A LA a b)\n         | _, _ => None\n         end;\n|}.\n- intro a. destruct a; reflexivity.\n- intro a. destruct a; try reflexivity. f_equal. apply lub_bot_r.\n- intros a b. destruct a; destruct b; try reflexivity. f_equal. apply glb_commut.\n- intros a b. destruct a; destruct b; try reflexivity. f_equal. apply lub_commut.\n- intros a b c. destruct a; destruct b; destruct c; try reflexivity. f_equal. apply glb_assoc.\n- intros a b c. destruct a; destruct b; destruct c; try reflexivity. f_equal. apply lub_assoc.\n- intros a b. destruct a; destruct b; try reflexivity. f_equal. apply glb_absorb.\n- intros a b. destruct a; destruct b; try reflexivity; f_equal.\n  + apply lub_absorb.\n  + apply lub_idempotent.\nDefined.\n", "meta": {"author": "samuelgruetter", "repo": "vst-ifc", "sha": "3c7a526d07cf69ae6c57c399c3bc5eb885375039", "save_path": "github-repos/coq/samuelgruetter-vst-ifc", "path": "github-repos/coq/samuelgruetter-vst-ifc/vst-ifc-3c7a526d07cf69ae6c57c399c3bc5eb885375039/ifc/lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7773525424480099}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export ZArithRing.\nRequire Import Relations.\n\n\n(** Example of use of the conversion rule \n*)\nTheorem conv_example : forall n:nat, 7*5 < n -> 6*6 <= n.\nProof.\n intros; assumption.\nQed.\n\nTheorem imp_trans : forall P Q R:Prop, (P->Q)->(Q->R)->P->R.\nProof.\n  intros P Q R H H0 p.\n  apply H0; apply H; assumption.\nQed.\n\n(** Tests :\n\nPrint imp_trans.\n\nCheck (imp_trans _ _ _ (le_S 0 1)(le_S 0 2)).\n\n*)\n\nDefinition neutral_left (A:Type)(op:A->A->A)(e:A) : Prop :=\n  forall x:A, op e x = x.\n\nLemma one_neutral_left : neutral_left Z Zmult 1%Z.\nProof.\n intro z; ring. \nQed.\n\nLemma le_i_SSi : forall i:nat, i <= S (S i).\nProof.\n intro i.\n do 2 apply le_S; apply le_n.\nQed.\n\nLemma all_imp_dist   : \n forall (A:Type)(P Q:A->Prop), \n         (forall x:A, P x -> Q x)->\n         (forall y:A, P y)-> \n          forall z:A, Q z.\nProof.\n intros A P Q H H0 z.\n apply H; apply H0; assumption.\nQed.\n\n\nLemma mult_le_compat_r : forall m n p:nat, le n p -> le (n * m) (p * m).\nProof.\n intros m n p H; rewrite (mult_comm n m); rewrite (mult_comm p m).\n apply mult_le_compat_l; trivial.\nQed.\n\n\nLemma le_mult_mult :\n   forall a b c d:nat, a <= c -> b <= d -> a * b <= c * d.\nProof.\n intros a b c d H H0.  \n apply le_trans with (m := c  *b).\n - apply mult_le_compat_r; assumption.\n - apply mult_le_compat_l; assumption.\nQed.\n\n\n(** using eapply ...\n*)\n\nLemma le_mult_mult' : \n forall a b c d:nat, a <= c -> b <= d -> a*b <= c*d.\nProof.\n intros a b c d H H0.  \n eapply le_trans.\n - eapply mult_le_compat_l.\n   eexact H0.\n -  now apply mult_le_compat_r.\nQed.   \n\nLemma le_O_mult : forall n p:nat, 0 * n <= 0 * p.\nProof.\n intros n p; apply le_n.\nQed.\n\nLemma lt_8_9 : 8 < 9.\nProof.\n unfold lt; apply le_n.\nQed.\n\n(** Tests :\n\nSearchPattern (_ + _ <= _)%Z.\n\nSearchPattern (?X1 * _ <= ?X1 * _)%Z. \n\n*)\n\nLemma lt_S : forall n p:nat, n < p -> n < S p.\nProof.\n intros n p H.\n unfold lt; apply le_S; trivial.\nQed.\n\nOpen Scope Z_scope.\n\nDefinition Zsquare_diff (x y:Z):= x * x - y * y.\n\nTheorem unfold_example :\n forall x y:Z,\n   x*x = y*y ->\n   Zsquare_diff x y * Zsquare_diff (x+y)(x*y) = 0.\nProof.\n intros x y Heq.\n unfold Zsquare_diff at 1.\n rewrite Heq; ring. \nQed.\n\nSection ex_falso_quodlibet.\n Hypothesis ff : False.\n \n Lemma ex1 : 220 = 284.\n Proof.\n   apply False_ind.\n   exact ff.\n Qed.\n\n Lemma ex2 : 220 = 284.\n Proof.\n  destruct ff.\n Qed.\n\nEnd ex_falso_quodlibet.\n\nTheorem absurd : forall P Q:Prop, P -> ~P -> Q.\nProof.\n intros P Q p H.\n elim H.\n assumption.\nQed.\n\nTheorem double_neg_i : forall P:Prop, P->~~P.\nProof.\n intros P p H.\n apply H; assumption.\nQed.\n\nTheorem modus_ponens :forall P Q:Prop, P->(P->Q)->Q.\nProof.\n auto.\nQed.\n\n\nTheorem double_neg_i' : forall P:Prop, P -> ~ ~ P.\nProof.\n intro P; exact (modus_ponens P False).\nQed.\n\nTheorem contrap :forall A B:Prop, (A->B) -> ~B -> ~A.\nProof.\n intros A B; unfold not.\n apply imp_trans.\nQed.  \n\nTheorem disj4_3' : forall P Q R S:Prop, R -> P \\/ Q \\/ R \\/ S.\nProof.\n  right; right; left; assumption.\nQed.\n\nLemma and_commutes : forall A B:Prop, A /\\ B -> B /\\ A.\nProof.\n intros A B H; destruct H.\n split; assumption.\nQed.\n\nLemma or_commutes : forall A B:Prop, A\\/B->B\\/A.\nProof.\n intros A B H; destruct H as [H | H]; auto.\nQed.\n\nLemma ex_imp_ex :\n forall (A:Type)(P Q:A->Prop), (ex P)->(forall x:A, P x -> Q x)->(ex Q).\nProof.\n intros A P Q H H0; destruct H as [a Ha].\n exists a; apply H0; assumption.\nQed.\n\n\nLemma L36 : 6 * 6 =9 * 4.\nProof. reflexivity. Qed.\n\nLemma diff_of_squares : forall a b:Z, ((a + b) * (a - b) = a * a - b * b)%Z.\nProof.\n intros; ring.\nQed.\n\nTheorem eq_sym' : forall (A:Type)(a b:A), a = b -> b = a.\nProof.\n intros A a b e; rewrite e; reflexivity.\nQed.\n\nLemma Zmult_distr_1 : forall n x:Z, n * x + x = ( n + 1) * x.\nProof.\n intros n x ; rewrite Zmult_plus_distr_l.\n now rewrite  Zmult_1_l.\nQed.\n\nLemma regroup : forall x:Z, x + x + x + x + x = 5 * x.\nProof.\n intro x; pattern x at 1.\n rewrite <- Zmult_1_l.\n repeat rewrite Zmult_distr_1.\n reflexivity.\nQed.\n\n\nOpen Scope nat_scope. \n\nTheorem le_lt_S_eq : forall n p:nat, n <= p -> p < S n -> n = p.\nProof.\n intros; omega.\nQed.\n\nLemma conditional_rewrite_example : forall n:nat,\n   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.\nProof.\n intros n  H H0.\n rewrite <- (le_lt_S_eq 2 n).\n - reflexivity.  \n -  apply  plus_le_reg_l with (p := 6). \n    rewrite plus_comm in H; auto with arith.\n - apply   plus_lt_reg_l with (p:= 3); auto with arith.\nQed.\n\n(** A shorter proof ...\n*)\n\nLemma conditional_rewrite_example' : forall n:nat,\n   8 < n + 6 ->  3 + n < 6 -> n * n = n + n.\nProof.\n intros n  H H0.\n assert (n = 2) by omega.\n now subst n.\nQed.\n\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 H; rewrite H; auto. \nQed. \n\nDefinition my_True : Prop \n:= forall P:Prop, P -> P.\n\nDefinition my_False : Prop\n:= forall P:Prop, P.\n\nTheorem my_I : my_True.\nProof.\n intros P p; assumption.\nQed.\n\n\nTheorem my_False_ind : forall P:Prop, my_False->P.\nProof.\n intros P F; apply F.\nQed.\n\nDefinition my_not (P:Prop) : Prop := P->my_False.\n\nSection leibniz.\n\n Variable A : Type.\n \n Definition leibniz (a b:A) : Prop := \n forall P:A -> Prop, P a -> P b.\n\n\nTheorem leibniz_sym : symmetric A leibniz.\nProof.\n intros x y H Q; apply H; trivial.\nQed.\n\nEnd leibniz.\n\nDefinition my_and (P Q:Prop) := \n  forall R:Prop, (P->Q->R)->R.\n\nDefinition my_or (P Q:Prop) := \n  forall R:Prop, (P->R)->(Q->R)->R.\n\nDefinition my_ex (A:Type)(P:A->Prop) :=\n  forall R:Prop, (forall x:A, P x -> R)->R.\n\nDefinition my_le (n p:nat) :=\n  forall P:nat -> Prop, P n ->(forall q:nat, P q -> P (S q))-> P p.\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/ch5_everydays_logic/SRC/chap5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8824278556326344, "lm_q1q2_score": 0.7772398795286762}}
{"text": "Require Export stlc.Maps.\n\nInductive type : Type := \n  | tvar : string -> type\n  | tarr : type -> type -> type\n  | tprod : type -> type -> type.\n\nInductive term : Type :=\n  | var : string -> term\n  | app : term -> term -> term\n  | lam : string -> type -> term -> term\n  | prod : term -> term -> term\n  | fst : term -> term\n  | snd : term -> term.\n\nDefinition ctx := partial_map type.\n\n(* Exercise 2.1 *)\n\nDefinition X_Y_X (X:string) (Y:string) : type := \n  tarr (tvar X) (tarr (tvar Y) (tvar X)).\n\nDefinition XX_XX (X:string) : type := \n  tarr (tarr (tvar X) (tvar X)) (tarr (tvar X) (tvar X)).\n\n(* Exercise 2.2 *)\n\nDefinition lxly_x (X:string) (Y:string) : term :=\n  lam \"x\" (tvar X) (lam \"y\" (tvar Y) (var \"x\")).\n\nDefinition lflx_ffx (X:string) : term :=\n  lam \"f\" (tarr (tvar X) (tvar X)) \n      (lam  \"x\" (tvar X) \n            (app  (var \"f\") \n                  (app  (var \"f\") \n                        (var \"x\")))).\n\n(* Exercise 2.3 *)\n\nInductive typed : ctx -> term -> type -> Prop :=\n  | var_typed : forall E x A,\n      E x = Some A ->\n      typed E (var x) A\n  | app_typed : forall A B E M N,\n      typed E M (tarr A B) ->\n      typed E N A -> \n      typed E (app M N) B\n  | lam_typed : forall E x A B M,\n      typed (update E x A) M B -> \n      typed E (lam x A M) (tarr A B)\n  | prod_typed : forall E t s T S,\n      typed E t T ->\n      typed E s S ->\n      typed E (prod t s) (tprod T S)\n  | fst_typed : forall E p T S,\n      typed E p (tprod T S) ->\n      typed E (fst p) T\n  | snd_typed : forall E p T S,\n      typed E p (tprod T S) ->\n      typed E (snd p) S.\n\n(* Exercise 2.4 *)\n\nLemma test : typed  empty\n                    (lxly_x \"X\" \"Y\") \n                    (X_Y_X \"X\" \"Y\").\nProof.\n  unfold lxly_x. unfold X_Y_X.\n  apply lam_typed. \n  apply lam_typed. \n  apply var_typed.\n  reflexivity.\nQed.\n\n(* Exercise 2.5 *)\n\n(*  To build a typechecker, we first need to define \n    a helper function for type equality and prove that\n    it actually defines equality. *)\nFixpoint beq_type (A B:type) : bool :=\n  match A,B with\n  | tvar a, tvar b => beq_string a b\n  | tarr A1 B1, tarr A2 B2 =>\n      andb (beq_type A1 A2) (beq_type B1 B2)\n  | tprod T1 S1, tprod T2 S2 => \n      andb (beq_type T1 T2) (beq_type S1 S2)\n  | _,_ => \n      false\n  end.\n\nLemma beq_type_refl : forall A,\n  beq_type A A = true.\nProof.\n  intros A1. induction A1; simpl.\n  apply beq_string_true_iff. reflexivity.\n  rewrite IHA1_1. rewrite IHA1_2. reflexivity.\n  rewrite IHA1_1. rewrite IHA1_2. reflexivity. Qed.\n\nLemma beq_type_eq : forall A B,\n  beq_type A B = true -> A = B.\nProof.\n  intros A. induction A; intros A Hbeq; destruct A; 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 IHA1 in Hbeq1. apply IHA2 in Hbeq2. subst... reflexivity.\n  - apply andb_prop in H0. inversion H0 as [Hbeq1 Hbeq2].\n    apply IHA1 in Hbeq1. apply IHA2 in Hbeq2. subst... reflexivity.\nQed.\n\nFixpoint typecheck (E:ctx) (t:term) : option type :=\n  match t with\n  | var x => \n      E x\n  | app M N => \n      match typecheck E M, typecheck E N with\n      | Some (tarr A B),Some A1 =>\n          if beq_type A A1 then Some B else None\n      | _,_ => None\n      end\n  | lam x A M => \n      match typecheck (update E x A) M with\n      | Some B => Some (tarr A B)\n      | _ => None\n      end\n  | prod s t => \n      match typecheck E s, typecheck E t with\n      | Some A, Some B => Some (tprod A B)\n      | _,_ => None\n      end\n  | fst p => \n      match typecheck E p with\n      | Some (tprod A B) => Some A\n      | _ => None\n      end\n  | snd p => \n      match typecheck E p with\n      | Some (tprod A B) => Some B\n      | _ => None\n      end\n  end.\n\n(* Exercise 2.6 *)\n\n(* \nThe typing judgement [typed] will tell us for a given\ncontext, term and type whether the term is of that type.\nThe type checker [typecheck] will tell us for a given\ncontext and term what the type is (or it will return\nnothing if there is no type).\n *)\n\n(* Exercise 2.7 *)\n\nExample pos_typecheck_1 : \n  typecheck empty (lxly_x \"X\" \"Y\") = Some (X_Y_X \"X\" \"Y\").\nProof. reflexivity. Qed.\n\nExample pos_typecheck_2 : \ntypecheck empty (lflx_ffx \"X\") = Some (XX_XX \"X\").\nProof. reflexivity. Qed.\n\nDefinition lx_xx (X: string) := \n  lam \"x\" (tvar X) (app (var \"x\") (var \"x\")).\n\nExample neg_typecheck_1 : \ntypecheck empty (lx_xx \"X\") = None.\nProof. reflexivity. Qed.\n\nDefinition lflx_xf (X: string) :=\n  lam \"f\" (tarr (tvar X) (tvar X)) \n      (lam \"x\" (tvar X) \n           (app (var \"x\") (var \"f\")) ).\n\nExample neg_typecheck_2 :\ntypecheck empty (lflx_xf \"X\") = None.\nProof. reflexivity. Qed.\n\n(* Exercise 2.8 *)\n\nLemma typecheck_complete : forall E t A,\n  typed E t A ->\n  typecheck E t = Some A.\nProof.\n  intros E t A H.\n  induction H.\n  - apply H.\n  - simpl.\n    rewrite IHtyped1. rewrite IHtyped2.\n    rewrite beq_type_refl.\n    reflexivity.\n  - simpl.\n    rewrite IHtyped. reflexivity.\n  - simpl.\n    rewrite IHtyped1. rewrite IHtyped2.\n    reflexivity.\n  - simpl.\n    rewrite IHtyped. reflexivity.\n  - simpl.\n    rewrite IHtyped. reflexivity.\nQed.\n\nLemma typecheck_sound : forall E t A,\n  typecheck E t = Some A -> typed E t A.\nProof.\n  intros E t. generalize dependent E.\n  induction t; intros E T Htc; inversion Htc.\n  - apply var_typed. apply H0.\n  - remember (typecheck E t1) as TO1.\n    remember (typecheck E t2) as TO2.\n    destruct TO1 as [A|]; inversion H0;\n    destruct A as [|A1 A2|T1 S1]; inversion H0.\n    destruct TO2 as [B|]; inversion H0.\n    remember (beq_type A1 B) as b.\n    destruct b; inversion H0.\n    symmetry in Heqb. apply beq_type_eq in Heqb.\n    inversion H0; subst... \n    apply app_typed with (A := B) (B := 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 (update E s t) as G'.\n    remember (typecheck G' t0) as TO2.\n    destruct TO2; inversion H0.\n    inversion H0. apply lam_typed. rewrite <- HeqG'.\n    apply IHt. rewrite HeqTO2. reflexivity. \n  - remember (typecheck E t1) as TO1.\n    remember (typecheck E t2) as TO2.\n    destruct TO1; inversion H0.\n    destruct TO2; inversion H0.\n    apply prod_typed.\n    symmetry in HeqTO1. apply IHt1 in HeqTO1.\n    apply HeqTO1.\n    symmetry in HeqTO2. apply IHt2 in HeqTO2.\n    apply HeqTO2.\n  - remember (typecheck E t) as TO1.\n    destruct TO1; inversion H0.\n    destruct t0; inversion H0.\n    symmetry in HeqTO1.\n    apply IHt in HeqTO1.\n    rewrite -> H2 in HeqTO1.\n    apply fst_typed with (S := t0_2).\n    apply HeqTO1.\n  - remember (typecheck E t) as TO1.\n    destruct TO1; inversion H0.\n    destruct t0; inversion H0.\n    symmetry in HeqTO1.\n    apply IHt in HeqTO1.\n    rewrite -> H2 in HeqTO1.\n    apply snd_typed with (T := t0_1).\n    apply HeqTO1.\nQed.\n\n(*\nInductive typed : ctx -> term -> type -> Prop :=\n  | var_typed : forall E x A,\n      E x = Some A ->\n      typed E (var x) A\n  | app_typed : forall A B E M N,\n      typed E M (tarr A B) ->\n      typed E N A -> \n      typed E (app M N) B\n  | lam_typed : forall E x A B M,\n      typed (update E x A) M B -> \n      typed E (lam x A M) (tarr A B)\n  | prod_typed : forall E t s T S,\n      typed E t T ->\n      typed E s S ->\n      typed E (prod t s) (tprod T S)\n  | fst_typed : forall E p T S,\n      typed E p (tprod T S) ->\n      typed E (fst p) T\n  | snd_typed : forall E p T S,\n      typed E p (tprod T S) ->\n      typed E (snd p) S.\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/STLC3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7771291686067264}}
{"text": "Require Import Nat.\nRequire Import Arith.\n\n(* Função Somatório *)\nFixpoint somat (n:nat) : nat :=\n match n with\n  | 0 => 0\n  | S m => n + (somat m)\nend.\n\n\n\n(*\n  Search (( _ + _) * (_ + _)).\n\n  A + B = B + A\n\n  (S n) + (plus (S n) m = (plus (S n) + m + (S n)\n*)\n\n\nLemma dois_div :\n  forall (n m:nat), (n + (div2 m)) = (div2 (n + (n + m))).\nProof.\nintros.\ninduction n.\n\n(* Caso Base *)\n - simpl.\n   reflexivity.\n\n(* Caso indutivo *)\n - simpl. (* tira 1 da divisão *)\n   rewrite (Nat.add_comm n (S (n + m))). (* coloca sucessor na direita para poder retornar à divisão *)\n   simpl.\n   rewrite IHn. (* rescrever n + div2 m *)\n   rewrite (Nat.add_comm n (n  + m)). (* alterar a ordem para reflexividade *)\n   reflexivity.\nQed.\n\nLemma somat_aux :\nforall (n:nat), (plus n (somat n)) = (div2 (plus n (plus n (plus n (mult n n))))).\nProof.\ninduction n.\n\n(* Caso Base *)\n - simpl.\n   reflexivity.\n\n(* Caso Indutivo *)\n - simpl. (* tira 1 da divisão *)\n    + rewrite <- (Nat.add_comm (S (n + S (n + S (n + n * S n)))) n). (* Remover os sucessores de dentro da divisão *)\n      rewrite <- (Nat.add_comm (S (n + S (n + n * S n))) n).\n      rewrite <- (Nat.add_comm (S (n + n * S n)) n).\n      rewrite <- (Nat.add_comm (n * S n) n).\n      rewrite <- (Nat.mul_comm (S n) n).\n      simpl. (* Volta a por a divisão e retira os S *)\n\n    * rewrite -> IHn. (* O que queremos igualar *)\n      rewrite <- (Nat.add_comm (S (div2 (n + (n + (n + n * n))))) n). (* Troca para por o n dentro do S *)\n      simpl.\n      rewrite <- (Nat.add_comm  n (div2 (n + (n + (n + n * n))))). (* Troca para usar o dois div*)\n      rewrite -> (dois_div n (n + (n + (n + n * n)))).\n      rewrite <- (Nat.add_comm  (n + (n + (n + (n + n * n)))) n). (* Trocas para deixar ambos os termos iguais *)\n      rewrite <- (Nat.add_comm  (n + (n + (n + n * n))) n).\n      rewrite <- (Nat.add_comm  (n + n * n) n).\n      rewrite <- (Nat.add_comm  (n + n * n + n) n).\n      reflexivity.\nQed.\n\nLemma somat_correct: forall (n:nat), (somat n) = (div2 (mult n (S n))).\nProof.\n(* Caso Base *)\nintro.\ninduction n.\n - simpl.\n   reflexivity.\n\n(* Caso Indutivo *)\n - simpl.\n    + rewrite <- (Nat.mul_comm (S (S n)) n).\n      rewrite <- (Nat.add_comm (S (S n) * n) n).\n      simpl.\n\n    * rewrite -> (somat_aux n).\n      rewrite <- (Nat.add_comm (n + n * n) n).\n      rewrite <- (Nat.add_comm (n + n * n + n) n).\n      reflexivity.\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/ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7770498852340256}}
{"text": "(** * 2018 Functional Programming Homework1 *)\n\n(* \n    10152160137\n    陈弈君\n*)\n\n(* ################################################################# *)\n\n(* 1. Prove the following properties.*)\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_Sn : forall n m : nat, (1 + n) * m = m + n * m.\n\nProof.\n  intros n m. simpl. reflexivity. Qed.\n\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S p => mult base (exp base p)\n  end.\n\nTheorem exp_1_l: forall n : nat, exp n 1 = n * 1.\n\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem exp_Sn : forall n m : nat, exp n (1+m) = n * (exp n  m).\nProof.\n  intros n m. simpl. reflexivity. Qed.\n\n\n(* 2. Define the geb function that tests whether its first argument is greater than or equal to its second argument, yielding a boolean. *)\n\nFixpoint geb(n1 n2 : nat) : bool :=\n  match n2 with\n  | 0 => true\n  | S n2' => \n    match n1 with\n    | 0 => false\n    | S n1' => geb n1' n2'\n    end\n  end.\n\nExample test_geb1 : (geb 4 4) = true.\n\nProof. simpl. reflexivity. Qed.\n\nExample test_geb2 : (geb 4 6) = false.\n\nProof. simpl. reflexivity. Qed.\n\nExample test_geb3 : (geb 7 5) = true.\n\nProof. simpl. reflexivity. Qed.\n\n\nTheorem plus_3O_n : forall n : nat, 0 + 0 + 0 + n = n.\n\nProof. intros n. simpl. reflexivity. Qed.\n", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/homework1_10152160137.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.777039130851865}}
{"text": "Add LoadPath \"/Users/danielle/projects/software-foundations/chapter02/\".\n\nRequire Import basics.\n\nDefinition blt_nat (n m : nat) : bool := \n  negb (ble_nat m n).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\n", "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/chapter02/exercise03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7770380402449973}}
{"text": "(*\nVerificación Formal - 2020-II\nArchivo de definiciones - Arreglos flexibles usando árboles de Braun\n\nImportación de los archivos de definiciones y propiedades de BN\n*)\nFrom TAREA3 Require Import Defs_BN.\nFrom TAREA3 Require Import Props_BN.\n\n\n(*\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n                Inicio del Fragmento de código visto en clase.\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n*)\n\n\n(*\nDefinition of binary trees and some of their properties\n*)\nParameter (A:Type)\n          (eq_dec_A: forall (x y:A),{x=y}+{x<>y})\n          (undefA : A).\n\n\n(*\nBinary trees defined here\n*)\nInductive BTree : Type :=\n  | E : BTree   \n  | N : A -> BTree  -> BTree  -> BTree.\n\n\nCheck BTree_ind.\n\n\n(*\nÁrbol indefinido\n*)\nParameter (undefBTree : BTree).\n\n\n(*\nsize on binary trees defined next\n*)\nFixpoint bsize (t:BTree): BN :=\nmatch t with\n  | E => Z\n  | N x s t =>  sucBN ((bsize s) ⊞ (bsize t))\nend.\n\nCheck bsize.\n\n\n(*\nBalance condition on Braun trees\n*)\nInductive bbal : BTree -> Prop:=\n  | bbalE : bbal E \n  | bbalN : forall (a: A) (s t: BTree),\n            bbal s -> bbal t -> (bsize t) ≤BN (bsize s) ->\n            (bsize s) ≤BN (sucBN (bsize t)) ->\n            bbal (N a s t).\n\n\nCheck bbal_ind.\n\n\nParameter (allBal: forall (t:BTree), bbal t).\n\n\n(*\nConsulta del elemento b-simo\n*)\nFixpoint lookup_bn (t:BTree) (b: BN) : A :=\nmatch t,b with\n  | E, b => undefA\n  | N x s t,Z => x \n  | N x s t, U a => lookup_bn s a   (* U a = 2a+1 *)\n  | N x s t, D a => lookup_bn t a   (* D a = 2a + 2 *) \nend.\n\n\n(*\nActualización del elemento b-simo\n*)\nFixpoint update (t:BTree) (b: BN) (x : A) : BTree :=\nmatch t,b with\n  | E, b => undefBTree\n  | N y s t, Z =>  N x s t\n  | N y s t, U a => N y (update s a x) t\n  | N y s t, D a => N y s (update t a x)\nend.\n\n\n(*\nInserción de un elento al inicio del arreglo\n*)\nFixpoint le (x:A) (t:BTree) : BTree :=\nmatch t with\n  | E => N x E E\n  | N y s t => N x (le y t) s\nend.\n\n\n(*\nInserción de un elento al final del arreglo\n*)\nFixpoint he (x:A) (t:BTree) : BTree  :=\nmatch t with\n  | E => N x E E\n  | N y l r => match bsize t with\n                | Z => undefBTree \n                | U b => N y (he x l) r\n                | D b => N y l (he x r)\n              end\nend.\n\n\n(*\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n                   Fin del fragmento de código visto en clase.\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n*)\n\n\n(*\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n                Inicio del fragmento de código implementado.\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n*)\n\n\n(*\nEliminación del primer elemento en el arreglo\n*)\nFixpoint lr (t:BTree) : BTree  :=\nmatch t with\n  | E => undefBTree\n  | N y l r => match l with\n                | E => E\n                | N x _ _ => N x r (lr l)\n               end\nend.\n\n\n(*\nEliminación del últiom elemento en el arreglo\n*)\nFixpoint hr (t:BTree) : BTree  :=\nmatch t with\n  | E => undefBTree\n  | N y E _ => E\n  | N y l r => match bsize t with\n                | U b => N y l (hr r)\n                | D b => N y (hr l) r\n                | Z => undefBTree \n               end\nend.\n\n", "meta": {"author": "cigarcial", "repo": "VF2020II", "sha": "3a283400575564770e47f54e7f7cc66f996da0f1", "save_path": "github-repos/coq/cigarcial-VF2020II", "path": "github-repos/coq/cigarcial-VF2020II/VF2020II-3a283400575564770e47f54e7f7cc66f996da0f1/Tarea3/Defs_BT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597459, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7770374509291695}}
{"text": "Require Import Ordinal.\n\n(* 一些比较弱的著名记号，主要从大数入门.pdf中选取 *)\n\n(* 阶乘 *)\nFixpoint fac(n:nat) :=\nmatch n with\n| O => 1\n| S n' => n*(fac n')\nend.\n\nCompute (List fac 5).\n\n\n(* 乘方 *)\nFixpoint pow(a b:nat) :=\nmatch b with\n| O => 1\n| S b' => a*(pow a b')\nend.\n\nCompute (List (pow 2) 5).\nCompute (List (pow 3) 5).\n\n\n(* 阿克曼函数 *)\nFixpoint Ack(m:nat):nat->nat :=\nmatch m with\n| O => S\n| S m' => fun n=>iter (Ack m') n (Ack m' 1)\nend.\n\nCompute (List (Ack 0) 4).\nCompute (List (Ack 1) 4).\nCompute (List (Ack 2) 4).\nCompute (List (Ack 3) 4).\nCompute (List (Ack 4) 0).\n\n\n(* 高德纳箭头 *)\nFixpoint arrow(a n b:nat) :=\nmatch n with\n| O => O\n| S O => pow a b\n| S n' => iter (arrow a n') (b-1) a\nend.\n\nCompute (List (arrow 2 1) 4).\nCompute (List (arrow 2 2) 4).\n\n\n(* 葛立恒数 *)\nFixpoint G(n:nat) :=\nmatch n with\n| O => 4\n| S n' => arrow (G n') 3 3\nend.\n\nDefinition G64 := G 64.\n\n\n(* 康威链 *)\n(**\n  a,b = a^b\n  X,1,Y = X\n  X,a+1,b+1 = X,(X,a,b+1),b\n  大写字母表示自然数构成的序列，小写字母表示自然数\n**)\n\n(* 可以从 F0=X 和 F1(a)=X,a 构造 chain_suc(F0,F1,a,b)=X,a,b *)\nFixpoint chain_suc(F0:nat)(F1:nat->nat)(a b:nat):nat :=\nmatch a,b with\n| 1,_ => F0\n| _,1 => F1 a\n| (S a'),(S b') => iter (fun x=>chain_suc F0 F1 x b') a' F0\n| _,_ => O\nend.\n\n(* 根据 F0=X、F1(a)=X,a、ls=Y 递归计算 X,a,Y *)\nFixpoint chain' (F0:nat)(F1:nat->nat)(ls:list nat):nat :=\nmatch ls with\n| nil => F0\n| cons a b =>\n  match b with\n  | nil => F1 a\n  | _ => chain' (F1 a) (chain_suc F0 F1 a) b\n  end\nend.\n\n(* 计算康威链 *)\nDefinition chain(ls:list nat) :=\nmatch ls with\n| nil => 1\n| cons a bs => chain' a (pow a) bs\nend.\n\nCompute (chain (17::nil)).\nCompute (chain (2::3::nil)).\nCompute (chain (3::2::nil)).\nCompute (chain (2::3::2::nil)).\nCompute (arrow 2 2 3).\n\n(* 将a重复b次的列表 *)\nFixpoint repeat_list(a b:nat): list nat :=\nmatch b with\n| O => nil\n| S b' => cons a (repeat_list a b')\nend.\n\n(* 康威链的下标扩展 *)\nFixpoint chain_ex(n:nat)(ls:list nat):nat :=\nmatch ls with\n| nil => 1\n| cons a bs =>\n  match n with\n  | 0 => O\n  | 1 => chain' a (pow a) bs\n  | S n' => chain' a (fun b=>chain_ex n' (repeat_list a (S b))) bs\n  end\nend.\n\nGoal chain_ex 1 = chain.\nsplit.\nQed.\n", "meta": {"author": "ccz181078", "repo": "googology", "sha": "1bbd8b93d44d00d145dc237a20a00b2df8a8b86a", "save_path": "github-repos/coq/ccz181078-googology", "path": "github-repos/coq/ccz181078-googology/googology-1bbd8b93d44d00d145dc237a20a00b2df8a8b86a/Simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7770317595942057}}
{"text": "Require Import ZArith.\nRequire Import VCF.Sem.\nRequire Import VCF.ZFuncDomain.\nRequire Import VCF.SetsDomain.\nRequire Import VCF.BinRelDomain.\nRequire Import VCF.KnasterTarski.\nRequire Import VCF.WhileLang.\n\nDefinition state := var -> Z.\nDefinition constant_func {A: Type} (c: Z): A -> Z := fun _ => c.\nDefinition query_var (X: var): state -> Z := fun st => st X.\n\nFixpoint aeval (a : aexp) : state -> Z :=\n  match a with\n  | ANum n => constant_func n\n  | AId X => query_var X\n  | APlus a1 a2 => (aeval a1 + aeval a2)%Func\n  | AMinus a1 a2  => (aeval a1 - aeval a2)%Func\n  | AMult a1 a2 => (aeval a1 * aeval a2)%Func\n  end.\n\nFixpoint beval (b : bexp) : state -> Prop :=\n  match b with\n  | BTrue       => Sets.full\n  | BFalse      => Sets.empty\n  | BEq a1 a2   => ZFunc.test_eq (aeval a1) (aeval a2)\n  | BLe a1 a2   => ZFunc.test_le (aeval a1) (aeval a2)\n  | BNot b1     => Sets.complement (beval b1)\n  | BAnd b1 b2  => Sets.intersect (beval b1 ) (beval b2)\n  end.\n\nDefinition if_sem\n  (cond: state -> Prop)\n  (then_branch else_branch: state -> state -> Prop)\n  : state -> state -> Prop\n:=\n  Sets.union\n    (Rel.concat (Rel.test cond) then_branch)\n    (Rel.concat (Rel.test (Sets.complement cond)) else_branch).\n\nDefinition loop_sem_CL:\n  @CompleteLattice_Setoid\n    (state -> state -> Prop)\n    Sets.included\n    Sets.equiv\n    Sets.omega_union\n:= SETS_included_CL.\n\nLocal Existing Instance loop_sem_CL.\n\nDefinition loop_sem (cond: state -> Prop) (loop_body: state -> state -> Prop):\n  state -> state -> Prop :=\n  KT_fix_l\n    (fun sem =>\n       Sets.union\n         (Rel.concat\n           (Rel.test cond)\n           (Rel.concat loop_body sem))\n         (Rel.test (Sets.complement cond))).\n\nLemma loop_sem_recur:\n  forall cond loop_body,\n    Sets.equiv\n      (loop_sem cond loop_body)\n      (Sets.union\n         (Rel.concat\n           (Rel.test cond)\n           (Rel.concat loop_body (loop_sem cond loop_body)))\n         (Rel.test (Sets.complement cond))).\nProof.\n  intros.\n  unfold loop_sem.\n  match goal with\n  | |- Sets.equiv (KT_fix_l ?F) _ =>\n    pose proof KnasterTarski_fixpoint_theorem_l F as H; apply H; clear H\n  end.\n  hnf; intros.\n  solve_mono BinRel_solve_mono.\nQed.\n\nFixpoint ceval (c: com): state -> state -> Prop :=\n  match c with\n  | CSkip => Rel.id\n  | CAss X E =>\n      fun st1 st2 =>\n        st2 X = aeval E st1 /\\\n        forall Y, X <> Y -> st1 Y = st2 Y\n  | CSeq c1 c2 => Rel.concat (ceval c1) (ceval c2)\n  | CIf b c1 c2 => if_sem (beval b) (ceval c1) (ceval c2)\n  | CWhile b c => loop_sem (beval b) (ceval c)\n  end.\n\n\n", "meta": {"author": "sjxer723", "repo": "monorepo", "sha": "65c347dfd9c4cdacc4b0d3d39e55c72603ef5633", "save_path": "github-repos/coq/sjxer723-monorepo", "path": "github-repos/coq/sjxer723-monorepo/monorepo-65c347dfd9c4cdacc4b0d3d39e55c72603ef5633/compilerverification/vcompframework/WhileLang_RelSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109749090952, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7770317592044856}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\n\nRequire Import Hapsl.Bool.Bool.\nRequire Import Hapsl.Ascii.Equality.\n\nImport AsciiEqualityNotations.\n\n(* Calculates the Hamming distance between two strings. *)\nFixpoint hamming_distance (a b : string) : option nat :=\n  match a, b with\n    | EmptyString, EmptyString => Some 0\n    | String ca a', String cb b' =>\n      match hamming_distance a' b' with\n        | None => None\n        | Some n => Some ((nat_of_bool (negb (ca ==_a cb))) + n)\n      end\n    | _, _ => None\n  end.\n\n(* TODO: Prove lemma - Hamming distance is undefined for strings with differing \n   lengths. *)\nLemma hamming_distance_undefined_for_different_lengths : forall (a b : string),\n  length a <> length b <-> hamming_distance a b = None.\nProof.\n  Admitted.\n  \n\n(* TODO: Prove lemma - Hamming distance is defined for strings with the same \n   length. *)\nLemma hamming_distance_defined_for_same_length : forall (a b : string),\n  length a = length b -> hamming_distance a b <> None.\nProof.\n  Admitted.\n\n(* Hamming distance is 0 for identical strings. *)\nLemma hamming_distance_zero_for_identical : forall (s: string),\n  hamming_distance s s = Some 0.\nProof.\n  induction s.\n    - auto.\n    - unfold hamming_distance.\n      rewrite beq_ascii_reflexive.\n      simpl.\n      fold hamming_distance.\n      rewrite IHs.\n      reflexivity.\nQed.\n\n(* TODO: Prove lemma - Hamming distance is at most string length. *)\nLemma hamming_distance_at_most_string_length : forall (a b : string),\n  True.\n  (* TODO: Option nat conversion. *)\n  (* length a = length b -> hamming_distance a b <= length a. *)\nProof.\n  Admitted.\n\n(* The Levenshtein indicator function that will return 0 if the character at \n   each given position is each given string is equal, otherwise returns 1. *)\nDefinition indicator (a b : string) (i j : nat) : nat :=\n  nat_of_bool (negb ((get (i - 1) a) ?==_a (get (j - 1) b))).\n\n(* The Levenshtein distance function. Returns the number of insertions, \n   deletions and substitutions required to go from one string to another. *)\nFixpoint levenshtein (a b : string) (i j n : nat) : nat :=\n  match i, j, n with\n    | O, _, _ | _, O, _ | _, _, O => max i j\n    | S i', S j', S n' => min \n      ((levenshtein a b i' j n') + 1)\n      (min \n        ((levenshtein a b i j' n') + 1)\n        ((levenshtein a b i' j' n') + (indicator a b i j)))\n  end.\n\n(* Calculates the Levenshtein distance between two strings. *)\nDefinition levenshtein_distance (a b : string) : nat :=\n  let i := length a in\n    let j := length b in\n      let n := max i j in\n        levenshtein a b i j n.\n\n(* Returns the length difference between two strings. *)\nFixpoint string_length_diff (a b : string) : nat :=\n  match a, b with\n    | EmptyString, EmptyString => 0\n    | _, EmptyString => length a\n    | EmptyString, _ => length b\n    | String ca a', String cb b' => string_length_diff a' b'\n  end.\n\n(* TODO: Prove lemma - It is always at least the difference of the sizes of the \n   two strings. *)\nLemma levenshtein_distance_at_least_length_diff : forall (a b : string),    \n  levenshtein_distance a b >= string_length_diff a b.\nProof.\n  Admitted.\n\n(* TODO: Prove lemma - It is zero if and only if the strings are equal. *)\nLemma levenshtein_distance_zero_for_equal_strings : forall (a b : string),\n  a = b <-> levenshtein_distance a b = 0.\nProof.\n  Admitted.\n\n(* TODO: Prove lemma - If the strings are the same size, the Hamming distance is\n   an upper bound on the Levenshtein distance. *)\nLemma levenshtein_distance_same_length_leq_hamming : forall (a b : string),\n  True.\n  (* TODO: Option nat conversion. *)\n  (* length a = length b -> levenshtein_distance a b <= hamming_distance a b. *)\nProof.\n  Admitted.\n\n(* TODO: Prove lemma - It is at most the length of the longer string. *)\nLemma levenshtein_distance_leq_longer_string_length : forall (a b : string),\n  levenshtein_distance a b <= max (length a) (length b).\nProof.\n  Admitted.\n\n(* TODO: Prove lemma - The Levenshtein distance between two strings is no \n   greater than the sum of their Levenshtein distances from a third string \n   (triangle inequality). *)\nLemma levenshtein_distance_triangle_inequality : forall (a b c : string),\n  levenshtein_distance a b <= (levenshtein_distance a c) \n    + (levenshtein_distance b c).\nProof.\n  Admitted.\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/Distance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7769470173117151}}
{"text": "Module Note.\n\n  (* Syntax: *)\n\n  Inductive Exp : Type :=\n  | T\n  | F\n  | And (b1 : Exp) (b2 : Exp)       \n  | If  (b : Exp)  (b1 : Exp) (b2 : Exp).\n\n  Notation \"b1 /*\\ b2\" := (And b1 b2) (at level 50, left associativity).\n\n  Definition exp1 : Exp := T.\n  Definition exp2 : Exp := T /*\\ F.\n  Definition exp3 : Exp := If exp2 (T /*\\ T) F.  \n\n  (* An indexed data type (b is the index): \n      isVal T \n      isVal F\n  *)\n  Inductive isVal : Exp -> Prop :=\n  | valT : isVal T\n  | valF : isVal F.\n\n  (* Parameterized Data Type (b is the parameter): *)\n  Inductive isVal' (b : Exp) : Prop :=\n  | valT' : b = T -> isVal' b\n  | valF' : b = F -> isVal' b.\n\n  (* Evaluation: Single and Multi *)\n\n  Fixpoint eval (b : Exp) : Exp :=\n    match b with\n    | T => T\n    | F => F\n    | T /*\\ T => T (* AndT  *)\n    | F /*\\ T => F (* AndF1 *)\n    | T /*\\ F => F (* AndF2 *)\n    | F /*\\ F => F (* AndF  *)\n    | b1 /*\\ b2 =>\n      match (eval b1) with\n      | T => eval b2\n      | F => F\n      | _ => b1 /*\\ b2\n      end\n    | If b b1 b2 =>\n      match eval b with\n      | T => eval b1\n      | F => eval b2\n      | _ => If b b1 b2\n      end       \n    end.\n\n  Lemma isval_to_val : forall (b : Exp),\n      isVal b -> b = T \\/ b = F.\n  Proof.\n    intros.\n    destruct H.\n    left.\n    trivial.\n    right.\n    trivial.\n  Qed. \n\n  Lemma eval_T : forall (b : Exp),\n   eval b = T ->\n     (b = T)\n  \\/ (exists (b1 b2 : Exp), b = b1 /*\\ b2)\n  \\/ (exists (b1 b2 b3 : Exp), b = If b1 b2 b3).\n  Proof.\n    intros.\n    destruct b.  \n    - left. trivial.\n    - left. trivial.\n    - right. left. exists b1. exists b2. trivial.\n    - right. right. exists b1. exists b2. exists b3. trivial.\n  Qed.\n  \n  Lemma eval_and : forall (b1 b2 : Exp),\n        (eval b1 = T \\/ eval b1 = F) ->\n        (eval b2 = T \\/ eval b1 = F) ->\n        (eval (b1 /*\\ b2) = T \\/ eval (b1 /*\\ b2) = F).\n  Proof.\n    intros.\n    destruct H.\n    - destruct H0.\n      left.\n      simpl.\n      rewrite H.\n      rewrite H0.\n      destruct (eval_T b1).\n      * apply H.\n      * rewrite H1. destruct (eval_T b2).\n      + apply H0.\n      + rewrite H2. trivial.\n      +  destruct H2.\n         { destruct H2. destruct H2. rewrite H2. trivial. }\n         { destruct H2. destruct H2. destruct H2. rewrite H2. trivial. }\n      *  \n           \n  Lemma eval_to_val : forall (b : Exp), isVal (eval b).\n  Proof. \n    intro b.\n    induction b.\n    apply valT.\n    apply valF.\n    \n    (* isVal (eval b1) -> eval b1 = T \\/ eval b1 = F\n    * isVal (eval b2) -> eval b2 = T \\/ eval b1 = F \n    * ---------------------------------------------\n    * eval (b1 /*\\ b2) = T \\/ eval (b1 /*\\ b2) = F  *)\n    \n\n  Compute (eval (If (T /*\\ T) (F /*\\ T) T)).\n\nEnd Note.\n", "meta": {"author": "AU-PL", "repo": "lectures", "sha": "237c66db33fe2297cde3db4edb4f4096252a8720", "save_path": "github-repos/coq/AU-PL-lectures", "path": "github-repos/coq/AU-PL-lectures/lectures-237c66db33fe2297cde3db4edb4f4096252a8720/04-14-2021.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7768314195304531}}
{"text": "Require Import Relation.\nRequire Import Ordering.\n\n(* operations *)\n\nTheorem n_plus_identity : forall (n : nat),\n  n + 0 = n.\nProof.\ninduction n.\n- reflexivity.\n- simpl. rewrite IHn. reflexivity.\nQed. \n\nTheorem n_plus_one : forall (n : nat),\n  n + 1 = S n.\nProof.\ninduction n.\n- reflexivity.\n- simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_plus_n_Sm : forall (n m : nat),\n  n + S m = S (n + m).\nProof.\nintros.\ninduction n. \n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_plus_comm : forall (n m : nat),\n  n + m = m + n.\nProof.\nintros.\ninduction n.\n  - intros. rewrite n_plus_identity. reflexivity.\n  - simpl. rewrite IHn. rewrite n_plus_n_Sm. reflexivity.\nQed.\n\nTheorem n_plus_assoc : forall (n m k : nat),\n  n + (m + k) = (n + m) + k.\nProof.\nintros.\ninduction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_plus_cancel : forall (n m k: nat),\n  n + k = m + k <-> n = m.\nProof.\nintros. unfold iff. apply conj.\n- induction k.\n  + rewrite n_plus_identity. rewrite n_plus_identity. intros. apply H.\n  + intros. rewrite n_plus_n_Sm in H. rewrite n_plus_n_Sm in H. \n    inversion H. apply IHk. apply H1.\n- intros. rewrite H. reflexivity.\nQed.\n\nTheorem n_mul_identity : forall n : nat,\n  n * 1 = n.\nProof.\ninduction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_mul_zero : forall n : nat,\n  n * 0 = 0.\nProof.\ninduction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_mul_right : forall (n m : nat),\n  n * S m = n * m + n.\nProof.\nintros.\ninduction n.\n  - reflexivity.\n  - simpl. rewrite IHn. rewrite n_plus_n_Sm. rewrite n_plus_assoc. reflexivity.\nQed.\n\nTheorem n_mul_comm : forall (n m : nat),\n  n * m = m * n.\nProof.\nintros.\ninduction n.\n  - rewrite n_mul_zero. reflexivity.\n  - simpl. rewrite IHn. rewrite n_mul_right. rewrite n_plus_comm. reflexivity.\nQed.\n\nTheorem n_distributive : forall (n m k : nat),\n  n * (m + k) = n * m + n * k.\nProof.\nintros.\ninduction n.\n  - reflexivity.\n  - simpl. \nassert (H : (k + n * (m + k)) = n * m + (k + n * k)).\nrewrite IHn. rewrite n_plus_assoc. rewrite n_plus_comm with (n:=k). rewrite n_plus_assoc. reflexivity.\nrewrite <- n_plus_assoc. rewrite H. rewrite n_plus_assoc. reflexivity.\nQed.\n\nTheorem n_right_distributive : forall (n m k : nat),\n  (n + m) * k = n * k + m * k.\nProof.\nintros. rewrite n_mul_comm. rewrite n_mul_comm with (n:=n). rewrite n_mul_comm with (n:=m).\napply n_distributive.\nQed.\n\nTheorem n_mul_assoc : forall (n m k : nat),\n  n * (m * k) = (n * m) * k.\nProof.\nintros.\ninduction n.\n  - reflexivity.\n  - simpl. rewrite IHn. rewrite n_mul_comm with (n:=m+n*m). rewrite n_distributive. rewrite n_mul_comm.\nassert (H : (n*m*k = k*(n*m))).\nrewrite n_mul_comm with (m:=n*m). reflexivity.\nrewrite H. reflexivity.\nQed.\n\n(* inequalities *)\n\nDefinition n_le : Relation nat nat :=\nfun p => match p with\n  | (n, m) => n <= m\nend.\n\nDefinition n_lt : Relation nat nat :=\nfun p => match p with\n  | (n, m) => n < m\nend.\n\nDefinition n_ge : Relation nat nat :=\nfun p => match p with\n  | (n, m) => m <= n\nend.\n\nDefinition n_gt : Relation nat nat :=\nfun p => match p with\n  | (n, m) => m < n\nend.\n\nTheorem n_le_0_n : forall (n : nat),\n  0 <= n.\nProof.\ninduction n.\n- apply le_n.\n- apply le_S. apply IHn.\nQed.\n\nTheorem n_le_reflexive : forall (n : nat),\n  n <= n.\nProof.\nintros. apply le_n.\nQed.\n\nTheorem n_le_n_S_m : forall (n m : nat),\n  n <= S m <-> n <= m \\/ n = S m.\nProof.\nunfold iff. intros. apply conj.\n- intros. inversion H. \n  + apply or_intror. reflexivity.\n  + apply or_introl. apply H1.\n- intros. inversion H. \n  + apply le_S. apply H0.\n  + rewrite H0. apply le_n.\nQed.\n\nTheorem n_le_transitive : forall (n m k : nat),\n  n <= m -> m <= k -> n <= k.\nProof.\ninduction k.\n- intros nm m0. inversion m0 as [meq0|]. rewrite meq0 in nm. apply nm.\n- intros nm mSk. inversion mSk as [meqSk | m0  mk].\n  + rewrite meqSk in nm. apply nm.\n  + apply le_S. apply IHk. apply nm. apply mk.\nQed.\n\nTheorem n_le_Sn_n_false : forall (n : nat),\n  not (S n <= n).\nProof.\ninduction n.\n- intros H. inversion H.\n- intros H. inversion H.\n  + apply IHn. rewrite H1. apply le_n.\n  + apply IHn. apply n_le_transitive with (m:= S (S n)).\n    apply le_S. apply le_n. apply H1.\nQed.\n\nTheorem n_le_Sn_Sm : forall (n m : nat),\n  S n <= S m <-> n <= m.\nProof.\nunfold iff. intros. apply conj.\n- intros. inversion H.\n  + apply le_n.\n  + apply n_le_transitive with (m:=S n)(k := m).\n    apply le_S. apply le_n. apply H1.\n- intros. induction m.\n  + inversion H. apply le_n.\n  + inversion H. \n    * apply le_n.\n    * apply IHm in H1. apply n_le_transitive with (m:=S m).\n      apply H1. apply le_S. apply le_n.\nQed.\n\nTheorem n_le_antisymmetric : forall (n m : nat),\n  n <= m -> m <= n -> n = m.\nProof.\nintros n m nm mn. inversion nm.\n+ reflexivity.\n+ assert (contra : S m0 <= m0).\n  { rewrite <- H0 in mn. apply n_le_transitive with (m:=n). apply mn. apply H. }\n  apply n_le_Sn_n_false in contra. contradiction.\nQed.\n\nTheorem n_le_total_ordering : forall (n m : nat),\n  n <= m \\/ m <= n.\nProof.\nintros. induction m.\n- right. apply n_le_0_n.\n- destruct IHm.\n  + left. apply le_S. apply H.\n  + inversion H.\n    * left. apply le_S. apply le_n.\n    * right. apply n_le_Sn_Sm. apply H0.\nQed.\n\nTheorem n_le_total_partial_ordering : total_partial_ordering n_le.\nProof.\nunfold total_partial_ordering. apply conj.\n- unfold partial_ordering. apply conj.\n  + unfold reflexive. apply n_le_reflexive.\n  + apply conj.\n    * unfold antisymmetric. apply n_le_antisymmetric.\n    * unfold transitive. apply n_le_transitive.\n- apply n_le_total_ordering.\nQed.\n\nTheorem n_lt_is_strict_n_le : n_lt = partial_to_strict n_le.\nProof.\napply Relation_eq. intros. unfold iff. apply conj.\n- intros. apply conj.\n  + apply n_le_Sn_Sm. apply n_le_transitive with (m:=b).\n    apply H. apply le_S. apply le_n.\n  + intros eq. rewrite eq in H. apply n_le_Sn_n_false in H. contradiction.\n- intros. destruct H as [leab neq].\n  inversion leab.\n  + contradiction.\n  + apply n_le_Sn_Sm. apply H.\nQed.\n\nTheorem n_le_is_partial_n_lt : n_le = strict_to_partial n_lt.\nProof.\nrewrite n_lt_is_strict_n_le. apply eq_sym. \napply partial_to_strict_to_partial_identity.\napply n_le_total_partial_ordering.\nQed.\n\nTheorem n_lt_total_strict_ordering : total_strict_ordering n_lt.\nProof.\nrewrite n_lt_is_strict_n_le.\napply partial_to_strict_preserves_totality.\napply n_le_total_partial_ordering.\nQed.\n\nTheorem n_le_plus : forall (n m k : nat),\n  n <= m <-> n + k <= m + k.\nProof.\nunfold iff. intros. apply conj.\n- intros. induction k.\n  + rewrite n_plus_identity. rewrite n_plus_identity. apply H.\n  + rewrite n_plus_n_Sm. rewrite n_plus_n_Sm.\n    apply n_le_Sn_Sm. apply IHk.\n- intros. induction k.\n  + rewrite n_plus_identity in H. rewrite n_plus_identity in H. apply H.\n  + rewrite n_plus_n_Sm in H. rewrite n_plus_n_Sm in H.\n    apply -> n_le_Sn_Sm in H. apply IHk. apply H.\nQed.\n\nTheorem n_le_mul : forall (n m k : nat),\n  n <= m -> n * k <= m * k.\nProof.\nintros. induction k.\n- rewrite n_mul_zero. rewrite n_mul_zero. apply le_n.\n- rewrite n_mul_comm. rewrite n_mul_comm with (n:=m).\n  simpl. rewrite n_mul_comm. rewrite n_mul_comm with (m:=m).\n  apply n_le_transitive with (m:=n+m*k).\n  + rewrite n_plus_comm. rewrite n_plus_comm with (n:=n).\n    apply n_le_plus. apply IHk.\n  + apply n_le_plus. apply H.\nQed. \n\nTheorem n_le_sum : forall (n m k l : nat),\n  n <= m -> k <= l -> n + k <= m + l.\nProof.\nintros n m k l nm kl. apply n_le_transitive with (m:=m+k).\n- apply n_le_plus. apply nm.\n- rewrite n_plus_comm. rewrite n_plus_comm with (n:=m).\n  apply n_le_plus. apply kl.\nQed.\n\nTheorem n_lt_plus : forall (n m k : nat),\n  n < m <-> n + k < m + k.\nProof.\nintros. unfold lt.\nrewrite n_plus_comm. rewrite <- n_plus_n_Sm. rewrite n_plus_comm.\napply n_le_plus.\nQed.\n\nTheorem n_lt_mul : forall (n m k : nat),\n  n < m -> 0 < k -> n * k < m * k.\nProof.\nintros n m k nm kpos. apply n_le_mul with (k:=k) in nm.\nsimpl in nm. rewrite n_plus_comm in nm. apply n_le_transitive with (m:=n*k+k).\n- rewrite <- n_plus_one. rewrite n_plus_comm. rewrite n_plus_comm with (m:=k).\n  apply n_le_plus. apply kpos.\n- apply nm.\nQed.\n\nTheorem n_le_lt_sum : forall (n m k l : nat),\n  n < m -> k <= l -> n + k < m + l.\nProof.\nintros n m k l nm kl.\nrewrite n_plus_comm. unfold lt. rewrite <- n_plus_n_Sm. rewrite n_plus_comm.\napply n_le_sum. apply nm. apply kl.\nQed.\n\nTheorem n_lt_sum : forall (n m k l : nat),\n  n < m -> k < l -> n + k < m + l.\nProof.\nintros n m k l nm kl. apply n_le_lt_sum. apply nm. apply le_S in kl. apply n_le_Sn_Sm. apply kl.\nQed.\n\nTheorem n_lt_lemma1 : forall (n m k l : nat),\n  n < m -> k < l -> n * l + m * k < n * k + m * l.\nProof.\nintros n m k l nm kl. induction l.\n- inversion kl.\n- rewrite <- n_plus_one. rewrite n_distributive. rewrite n_distributive.\n  rewrite n_mul_identity. rewrite n_mul_identity.\n  inversion kl.\n  + rewrite n_plus_comm with (m:=m). rewrite n_plus_assoc. apply n_lt_plus.\n    rewrite n_plus_comm. rewrite n_plus_comm with (m:=m). apply n_lt_plus.\n    apply nm.\n  + rewrite <- n_plus_assoc. rewrite n_plus_comm with (n:=n).\n    rewrite n_plus_assoc. rewrite n_plus_assoc.\n    apply n_lt_sum. apply IHl. apply H0. apply nm.\nQed.", "meta": {"author": "yskim5892", "repo": "Coq_math", "sha": "4b88322f1d40f154c05db2b523e419b28e544159", "save_path": "github-repos/coq/yskim5892-Coq_math", "path": "github-repos/coq/yskim5892-Coq_math/Coq_math-4b88322f1d40f154c05db2b523e419b28e544159/NatProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7768314100018622}}
{"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\nFixpoint append(m n :natlist) : natlist :=\nmatch m with\n|[] => n\n|a :: b => a::(append b n)\nend.\n\nFixpoint snoc(m:natlist)(n:nat) :natlist:=\nmatch m with\n|[] => [n]\n|a::b => a:: (snoc b n)\nend.\n\nNotation \"x ++ y\" := (append x y)(at level 60, right associativity).\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.", "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_Backup/appendList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.776778011179757}}
{"text": "Require Import Coq.omega.Omega.\nInductive seq : Type :=\n| empty : seq\n| pair  : nat -> seq -> seq.\n(* lexicographical ordering less than or equal <= *)\nFixpoint lessOrEq (s t: seq) : Prop :=\nmatch s with\n| empty     => True\n| pair a s1 => match t  with\n| empty     => False\n| pair b t1 =>  (a < b) \\/\n((a = b) /\\ (lessOrEq s1 t1))\nend\nend.\nLemma test1 : not (lessOrEq (pair 4 (pair 3 empty))\n(pair 3 empty)).\nProof.\n\nintro.\ndestruct H.\nomega.\ndestruct H.\ncontradiction.\n\nQed.\nLemma test2 : lessOrEq (pair 4 (pair 3 empty))\n(pair 4 (pair 3 (pair 2 empty))).\nProof.\n\nsimpl.\nintuition.\n\nQed.", "meta": {"author": "Toskah", "repo": "Coq", "sha": "956df87bfc60f2ae32b80851978d211f60768de0", "save_path": "github-repos/coq/Toskah-Coq", "path": "github-repos/coq/Toskah-Coq/Coq-956df87bfc60f2ae32b80851978d211f60768de0/lab8/task2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809826, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7767514001155599}}
{"text": "Require Import ch1.Simplification.\n\nTheorem plus_id_example : forall n m : nat,\n    n = m -> n + n = m + m.\n\nProof.\n    intros n m.     (* \"for some n <- Nat, m <- Nat\" *)\n    intros H.       (* \"such that n = m \" *)\n    rewrite -> H.   (* Rewrite the goal using the hypothesis *)\n    reflexivity. Qed.\n\n(* Exercise *)\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 H1 H2.\n    rewrite -> H1.\n    rewrite -> H2.\n    reflexivity. Qed.\n\nTheorem mult_0_plus : forall n m : nat,\n    (0 + n) * m = n * m.\n\nProof.\n    intros n m.\n    rewrite -> plus_O_n.\n    reflexivity. Qed.\n\n(* Exercise *)\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    reflexivity. Qed.\n", "meta": {"author": "domdere", "repo": "software-foundations-coq", "sha": "4405da60315b7ad929fc9be0b263952f30766cca", "save_path": "github-repos/coq/domdere-software-foundations-coq", "path": "github-repos/coq/domdere-software-foundations-coq/software-foundations-coq-4405da60315b7ad929fc9be0b263952f30766cca/src/ch1/Rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7767513992489915}}
{"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_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\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. 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", "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/goal82.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8723473862936943, "lm_q1q2_score": 0.7766458437291529}}
{"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.\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.\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/Divide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7766160517617884}}
{"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\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  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 := \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\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.\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\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O   , _    => O\n  | S _ , O    => n\n  | S n', S m' => minus n' m'\n  end.\n\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 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.\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 := 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. 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, 0 + n = n.\nProof.\n  intros n.\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\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H.\n  intros K.\n  rewrite -> H.\n  rewrite -> K.\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 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.\nQed.\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\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 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.\n  destruct b as [t0|f0] eqn:Eb.\n  - destruct c as [t|f] eqn:Ec.\n    + simpl.\n      reflexivity.\n    + simpl.\n      intros H.\n      rewrite -> H.\n      reflexivity.\n  - destruct c as [t|f] eqn:Ec.\n    + simpl.\n      reflexivity.\n    + simpl.\n      intros H.\n      rewrite -> H.\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\nFrom Coq Require Export String. \n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] [].\n  intros H.\n  + reflexivity. \n  + simpl. intros. rewrite -> H. reflexivity.\n  + simpl. intros. rewrite -> H. reflexivity. \n  + simpl. intros. 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 incr1: (incr Z) = B Z.\nProof. simpl. reflexivity. Qed.\n\nExample incr2: (incr (incr Z)) = A (B Z).\nProof. simpl. reflexivity. Qed.\n\nExample incr3: (incr (incr (incr Z))) = B (B Z).\nProof. simpl. reflexivity. Qed.\n\nExample incr4: (incr (incr (incr (incr Z)))) = A (A (B Z)).\nProof. simpl. reflexivity. Qed.\n\nExample incr5: (incr (incr (incr (incr (incr Z))))) = B (A (B Z)).\nProof. simpl. reflexivity. Qed.\n\nExample incr6: (incr (incr (incr (incr (incr (incr Z)))))) = A (B (B Z)).\nProof. simpl. reflexivity. Qed.\n\nExample incr9: (incr (incr (incr (incr (incr (incr (incr (incr (incr (incr (incr Z))))))))))) = A (B (B (B Z))).\nProof. simpl.  Abort.\n\nFixpoint bin_to_nat (m:bin) :=\n  match m with\n  | Z => 0\n  | A n => 2 * bin_to_nat n\n  | B n => S (2 * bin_to_nat n)\n  end.\n\n", "meta": {"author": "s3141p", "repo": "software-foundations", "sha": "a6eee47da487495fff2bba8b3ff7b5e330efe18e", "save_path": "github-repos/coq/s3141p-software-foundations", "path": "github-repos/coq/s3141p-software-foundations/software-foundations-a6eee47da487495fff2bba8b3ff7b5e330efe18e/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7765987142469363}}
{"text": "Require Import List.\nImport ListNotations.\n\n(* Check the type of list *)\nCheck list.\n(* It is a constructor:\n   list : Type -> Type\n   that maps the type of elements in the list to the list type. *)\n\nDefinition is_empty (A : Type) (lst : list A) :=\n  match lst with\n  | nil => true\n  | cons _ _ => false\n  end.\n\n(* or *)\n\nDefinition is_empty2 (A : Type) (lst : list A) :=\n  match lst with\n  | [] => true\n  | _::_ => false\n  end.\n\nCompute is_empty nat [1].\nCompute is_empty nat [].\n\nTheorem empty_is_empty : forall A : Type, forall lst : list A,\n      length lst = 0 -> is_empty A lst = true.\nProof.\n  intros A lst H.\n  (* lst has two possible values: nil and cons.\n     Both subgoals assume H, that is, length lst = 0.\n     The first subgoal has H true, because length nil = 0.\n          is_empty A [] = true, so this subgoal is proved\n          with trivial.\n     The second subgoal has H false. Because H is false, we\n         use discriminate. Again, discriminate lets us prove\n         anything when one of our assumptions is false. *)\n  destruct lst.\n    trivial.\n    discriminate.\nQed.\n\n", "meta": {"author": "andrewyatesg", "repo": "CoqExcercises", "sha": "4b36cd7d2a8445df63689b6dbbfe8b0b5f783510", "save_path": "github-repos/coq/andrewyatesg-CoqExcercises", "path": "github-repos/coq/andrewyatesg-CoqExcercises/CoqExcercises-4b36cd7d2a8445df63689b6dbbfe8b0b5f783510/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7765292932726541}}
{"text": "From Coq Require Import List Arith.\n\nLocal Open Scope list_scope.\n\nLemma skipn_skipn {A} (l: list A) (n m: nat):\n  skipn n (skipn m l) = skipn (n + m) l.\nProof.\nrevert n l.\ninduction m, l; intros; try repeat rewrite skipn_nil; try easy.\n{ cbn. now rewrite Nat.add_0_r. }\nreplace (n + S m) with (S (n + m)) by auto with arith.\nrepeat rewrite skipn_cons.\napply IHm.\nQed.\n\nLemma nth_hd_skipn {A} (l: list A) (n: nat):\n  nth_error l n = hd_error (skipn n l).\nProof.\nrevert l. induction n, l; try easy.\ncbn. apply IHn.\nQed.\n\nFixpoint list_eqb {A} (eqb: A -> A -> bool) (l l': list A)\n: bool\n:= match l with\n   | nil => match l' with\n            | nil => true\n            | _ => false\n            end\n   | h :: t => match l' with\n               | nil => false\n               | h' :: t' => if eqb h h'\n                               then list_eqb eqb t t'\n                               else false\n               end\n   end.\n\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/Lib2/List2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7765292843206467}}
{"text": "Require Export Basics.\n\nTheorem plus_n_0 : forall n : nat, n = n+0.\nProof.\n  intro n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\nminus n n = 0.\n  Proof.\n    intro. induction n. \n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn. reflexivity.\n  Qed.\n\nTheorem mult_0_r : forall n : nat,\nn * 0 = 0.\nProof.\n  intros. induction n; simpl.\n  - reflexivity.\n  -  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. } { simpl. rewrite -> IHn'. reflexivity. }\nQed.\n\nTheorem plus_comm : forall n m : nat, \n n + m = m + n.\nProof.\n  intros. induction n; simpl.\n  - rewrite <- plus_n_0. reflexivity.\n  - rewrite -> IHn. apply plus_n_Sm.\nQed.\n\nTheorem plus_assoc : forall n m o : nat, \n (n + m) + o = n + (m + o).\nProof.\n  intros. induction n; simpl.\n  - reflexivity.\n  - rewrite -> IHn. reflexivity.\nQed.\n\nFixpoint double (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' => (plus 2 (double n'))\n  end.\n\nCompute (double 6).\n\nLemma double_plus : forall n, double n = n+n.\nProof.\n  intro. induction n; simpl.\n  - reflexivity.\n  - rewrite -> IHn. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof. \n  intro. 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 m.\n  assert (H : 0 + n = n). { reflexivity. }\n  rewrite -> H. 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  {rewrite <- plus_comm. reflexivity. }\n  rewrite <- H. reflexivity.\nQed.\n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7765242045950168}}
{"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.\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; lia. 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; lia);right; lia.\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); lia.\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); lia.\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", "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/interval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7765241983968585}}
{"text": "(* Solution for exercieses in Tsinghua Coq Summber School.\n  Exercise for leture 3: Proofs in Proposition Logic and Predicate Logic by Pierre Castéran. *)\n\n(** 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 should be proved several times :\n   first using only elementary tactics :\n   intro[s], apply, assumption\n   split, left, right, destruct.\n   exists, rewrite\n   assert (only if you don't find another solution)\n\n\n   Then, use tactic composition, auto, tauto, firstorder.\n\n\nNotice that, if you want to keep all solutions, you may use various\nidentifiers like in the given example : imp_dist, imp_dist' share\nthe same statement, with different interactive proofs.\n*)\n\nSection Minimal_propositioal_logic.\n\nVariables P Q R S : Prop.\n\nLemma imp_dist : (P -> Q -> R) -> (P -> Q) -> P -> R.\nProof.\n  intros H H0 p.\n  apply H.\n  assumption.\n  apply H0.\n  assumption.\nQed.\n\nLemma imp_dist' : (P -> Q -> R) -> (P -> Q) -> P -> R.\nProof.\n  intros H H0 p;apply H.\n  assumption.\n  apply H0;assumption.\nQed.\n\nLemma id_P : P -> P.\nProof.\n  intro H.\n  assumption.\nQed.\n\nLemma id_P' : P -> P.\nProof.\n  intros h1.\n  apply h1.\nQed.\n\nLemma id_PP : (P -> P) -> P -> P.\nProof.\n  intros h1 h2.\n  apply h2.\nQed.\n\nLemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros h1 h2 h3.\n  apply h2; apply h1; apply h3.\nQed.\n\nLemma imp_perm : (P -> Q -> R) -> Q -> P -> R.\nProof.\n  intros h1 h2 h3.\n  apply h1; [apply h3 | apply h2].\nQed.\n\nLemma ignore_Q : (P -> R) -> P -> Q -> R.\nProof.\n  intros h1 h2 h3.\n  apply h1; apply h2.\nQed.\n\nLemma delta_imp : (P -> P -> Q) -> P -> Q.\nProof.\n  intros h1 h2.\n  apply h1; [apply h2 | apply h2].\nQed.\n\nLemma delta_impR : (P -> Q) -> P -> P -> Q.\nProof.\n  intros h1 h2 h3.\n  apply h1; apply h2.\nQed.\n\nLemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\nProof.\n  intros h1 h2 h3 h4.\n  apply h3.\n  apply h1; apply h4.\n  apply h2; apply h4.\nQed.\n\nLemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\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.\n\nEnd Minimal_propositioal_logic.\n\n(** Same exercise as the previous one, with full intuitionistic propositional\n   logic\n\n   You may use the tactics intro[s], apply, assumption, destruct,\n                           left, right, split and try to use tactic composition *)\n\nSection propositional_logic.\n\nVariables P Q R S T : Prop.\n\nLemma and_assoc : P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intro h1.\n  split; [split | idtac]; apply h1.\nQed.\n\nLemma and_imp_dist : (P -> Q) /\\ (R -> S) -> P /\\ R -> Q /\\ S.\nProof.\n  intros h1 h2.\n  elim h1.\n  intros h3 h4.\n  split; [apply h3 | apply h4]; apply h2.\nQed.\n\nLemma not_contrad :  ~(P /\\ ~P).\nProof.\n  intros h1.\n  elim h1.\n  intros h2 h3.\n  apply h3; apply h2.\nQed.\n\nLemma or_and_not : (P \\/ Q) /\\ ~P -> Q.\nProof.\n  intros h1.\n  elim h1.\n  intros h2 h3.\n  elim h2;\n    [ intros h4; elim h3; apply h4\n    | trivial\n    ].\nQed.\n\nLemma not_not_exm : ~ ~ (P \\/ ~ P).\nProof.\n  intros h1.\n  elim h1; right; intro h2.\n  elim h1; left; apply h2.\nQed.\n\nLemma de_morgan_1 : ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  intros h1.\n  split; intros h2; elim h1; [left | right]; assumption.\nQed.\n\nLemma de_morgan_2 : ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\n  intros h1 h2.\n  elim h2; (* \"unfold not in h1;\" *) apply h1.\nQed.\n\nLemma de_morgan_3 : ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\n  intros h1 h2.\n  elim h2.\n  intros h3 h4.\n  elim h1;\n    [ intros h5; apply h5\n    | intros h6; apply h6\n    ];\n    assumption.\nQed.\n\nEnd propositional_logic.\n\nSection First_Order_Logic.\n\nVariable A : Set.\nVariables\n  (P Q : A -> Prop)\n  (R : A -> A -> Prop).\n\n\nLemma forall_imp_dist : (\n  forall x : A, P x -> Q x) -> (\n    forall x : A, P x) ->\n      forall x : A, Q x.\nProof.\n  intros h1 h2 x.\n  apply h1; apply h2.\nQed.\n\nLemma forall_perm : (\n  forall x y : A, R x y) ->\n    forall y x, R x y.\nProof.\n  intros h1 y x.\n  apply h1.\nQed.\n\nLemma forall_delta : (\n  forall x y : A, R x y) ->\n    forall x, R x x.\nProof.\n  intros h1 x.\n  apply h1.\nQed.\n\nLemma exists_or_dist : (\n  exists x : A, P x \\/ Q x) <-> (\n    exists x, P x) \\/ (\n      exists x, Q x).\nProof.\n  split.\n\n  intros h1; elim h1.\n  intros x h2; elim h2;\n    intros;\n      [ left\n      | right\n      ];\n    exists x; assumption.\n\n  intros h1; elim h1;\n    intros h2; elim h2;\n    intros x h3;\n    exists x;\n      [ left\n      | right\n      ];\n    assumption.\nQed.\n\nLemma exists_imp_dist : (\n  exists x : A, P x -> Q x) -> (\n    forall x : A, P x) ->\n      exists x:A, Q x.\nProof.\n  intros h1 h2.\n  elim h1.\n  intros x h3.\n  exists x.\n  apply h3; apply h2.\nQed.\n\nLemma not_empty_forall_exists :\n  forall a : A, (\n    forall x : A, P x) ->\n      exists x : A, P x.\nProof.\n  intros a h1.\n  exists a.\n  apply h1.\nQed.\n\nLemma not_ex_forall_not : ~ (\n  exists x : A, P x) <->\n    forall x : A, ~ P x.\nProof.\n  split.\n\n  intros h1 x h2.\n  elim h1.\n  exists x.\n  apply h2.\n\n  intros h1 h2.\n  elim h2.\n  intros x.\n  apply h1.\nQed.\n\nLemma singleton_forall_eq : (\n  exists x : A,\n    forall y : A, x = y) ->\n      forall z t : A, z = t.\nProof.\n  intros h1 z t.\n  elim h1.\n  intros x h2.\n  rewrite <- (h2 t).\n  apply eq_sym. (* rewrite goal using the symmetry of equal relation. *)\n  rewrite <- (h2 z).\n  reflexivity.\nQed.\n\nPrint singleton_forall_eq.\n\nSection S1.\n\nVariables  (f g : A -> A).\n\nHypothesis f_g_perm :\n  forall x : A, f (g x) = g (f x).\nHypothesis g_idempotent :\n  forall x : A, g (g x) = g x.\nHypothesis f_idempotent :\n  forall x : A, f (f x) = f x.\n\nLemma L :\n  forall z, g (f (g (f (g (f z))))) = f (g z).\nProof.\n  intros z.\n  rewrite f_g_perm.\n  rewrite g_idempotent.\n  rewrite f_idempotent.\n  rewrite f_g_perm.\n  rewrite g_idempotent.\n  rewrite f_idempotent.\n  rewrite f_g_perm.\n  trivial.\nQed.\n\nLemma L':  (\n  forall x : A, ~ x = f x) -> ~ (\n    exists y : A, True).\nProof.\n  intros h1 h2.\n  (* introduce a variable \"x\" into hypotheses. *)\n  elim h2.\n  intros x h3.\n  apply (h1 (f x)).\n  rewrite f_idempotent.\n  trivial.\nQed.\n\nEnd S1.\n", "meta": {"author": "sighingnow", "repo": "amazing-coq", "sha": "70acce0bac267f76f696b0f0a35865622b6a0ee8", "save_path": "github-repos/coq/sighingnow-amazing-coq", "path": "github-repos/coq/sighingnow-amazing-coq/amazing-coq-70acce0bac267f76f696b0f0a35865622b6a0ee8/tsinghua-coq-summer-school/solutions/exercises_3_work.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.9073122132152183, "lm_q1q2_score": 0.7765241883298715}}
{"text": "Require Import QArith. \nRequire Import Reals.\nRequire Import Psatz.\nRequire Import QArith.Qminmax.\nRequire Lra.\n\n\nStructure Open_Interval := {\nlower_bound:Q;\nupper_bound:Q;\nopennes : lower_bound < upper_bound}.\n\nDefinition open_membership ( x :Q )( I : Open_Interval) :=\nx < upper_bound I /\\ x > lower_bound I.\n\nDefinition open_waybelow ( I J :Open_Interval) :=\nlower_bound J < lower_bound I /\\ upper_bound I < upper_bound J.\n\nLemma member_transivity : forall x :Q , forall I J : Open_Interval,\nopen_waybelow I J -> open_membership x I -> open_membership x J.\nProof.\nintros.\ndestruct I as [lower upper prop].\ndestruct J as [lower' upper' prop'].\nunfold open_waybelow, open_membership.\nsimpl in *.\ndestruct H as [A1 A2].\nsplit.\napply (Qlt_trans x upper upper').\napply H0.\napply A2.\napply (Qlt_trans lower' lower x).\napply A1.\napply H0.\nQed.\n\nDefinition open_separated (I J : Open_Interval):=\nupper_bound I <= lower_bound J \\/ upper_bound J <= lower_bound I.\n\nDefinition totally_open_separated (I J : Open_Interval):=\nupper_bound I < lower_bound J \\/ upper_bound J < lower_bound I.\n\nLemma separation_expansion: forall I J : Open_Interval , \ntotally_open_separated I J ->\n exists I' J' , totally_open_separated I' J' \n-> open_waybelow I I' -> open_waybelow J J'.\nProof.\nintros.\ndestruct I as [lower_I upper_I prop_I].\ndestruct J as [lower_J upper_J prop_J].\ndestruct H as [A1| A2].\nsimpl in *.\nassert (I'_prop: ((3#1)*(lower_I)-(lower_J)+(upper_I))*(1#3)<\n((2#1)*(upper_I ) + (lower_J) ) * (1#3)).\nlra.\nexists{|lower_bound:=((3#1)*(lower_I)-(lower_J)+(upper_I))*(1#3);upper_bound :=\n((2#1)*(upper_I ) + (lower_J) ) * (1#3); opennes :=I'_prop|}.\nassert(J'_prop: ((2#1)*lower_J + upper_I)*(1#3) < ((3#1)*upper_J + lower_J \n- upper_I)*(1#3)).\nlra.\nexists{|lower_bound:=((2#1)*lower_J + upper_I)*(1#3) ; upper_bound := ((3#1)*upper_J + lower_J \n- upper_I)*(1#3); opennes :=J'_prop |}.\nunfold totally_open_separated.\nsimpl in *.\nunfold open_waybelow.\nsimpl in *.\nlra.\nsimpl in *.\nassert (J'_prop: ((3#1)*(lower_J)-(lower_I)+(upper_J))*(1#3)<\n((2#1)*(upper_J ) + (lower_I) ) * (1#3)).\nlra.\nexists{|lower_bound:=((3#1)*(lower_J)-(lower_I)+(upper_J))*(1#3);upper_bound :=\n((2#1)*(upper_J ) + (lower_I) ) * (1#3); opennes :=J'_prop|}.\nassert(I'_prop: ((2#1)*lower_I + upper_J)*(1#3) < ((3#1)*upper_I + lower_I \n- upper_J)*(1#3)).\nlra.\nexists{|lower_bound:=((2#1)*lower_I + upper_J)*(1#3) ; upper_bound := ((3#1)*upper_I + lower_I \n- upper_J)*(1#3); opennes :=I'_prop |}.\nunfold totally_open_separated.\nsimpl in *.\nunfold open_waybelow.\nsimpl in *.\nlra.\nQed.\n\n(*Check upper_bound.*)\n", "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/Geometry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7763028848857512}}
{"text": "Add LoadPath \"C:/Coq/cpdt/src\".\nRequire Export CpdtTactics.\nRequire Bool Arith List.\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\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 (cons n s)\n  | iBinop b =>\n    match s with\n      | cons arg1 (cons arg2 s') => Some (cons ((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  | cons 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 => cons (iConst n) nil\n  | Binop b e1 e2 => app (app (compile e2)  (compile e1) ) (cons (iBinop b) nil)\n  end.\n\n\nEval simpl in compile (Binop Plus (Const 2) (Const 2)).\nEval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))) nil.\n\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/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705932, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.776210612469386}}
{"text": "Module Bycicles1.\n\n(* ((Booleans)) *)\n\n(* Exercise: 1 star (nandb) *)\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.\n  Proof. reflexivity. Qed.\n\nExample test_nandb2: (nandb false false) = true.\n  Proof. reflexivity. Qed.\n\nExample test_nandb3: (nandb false true) = true.\n  Proof. reflexivity. Qed.\n\nExample test_nandb4: (nandb true true) = false.\n  Proof. reflexivity. Qed.\n\n(* END nandb. *)\n\n(* Exercise: 1 star (andb3) *)\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.\n  Proof. reflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\n  Proof. reflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\n  Proof. reflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\n  Proof. reflexivity. Qed.\n\n(* END andb3. *)\n\n(* ((Numbers)) *)\n\nEnd Bycicles1.\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n    | O => O\n    | S O => O\n    | S (S n') => n'\n  end.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\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\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => S O\n    | S p => (S p) * (factorial p)\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\n  Proof. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\n  Proof. reflexivity. Qed.\n\n(* END factorial. *)\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\n(* Exercise: 2 stars (blt_nat) *)\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.\n  Proof. reflexivity. Qed.\n\nExample test_blt_nat2: (blt_nat 2 4) = true.\n  Proof. reflexivity. Qed.\n\nExample test_blt_nat3: (blt_nat 4 2) = false.\n  Proof. reflexivity. Qed.\n\n(* END blt_nat. *)\n\n(* ((Proof by Rewriting)) *)\n\n(* Exercise: 1 star (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 NM MO.\n  rewrite -> NM.\n  rewrite -> MO.\n  reflexivity.\nQed.\n\n(* END plus_id_exercise. *)\n\n(* Excercise: 2 stars (mult_S_1) *)\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* END mult_S_1. *)\n\n(* ((Proof by Case Analysis)) *)\n\n(* Exercise: 1 star (zero_nbeq_plus_1) *)\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n.\n  reflexivity.\n  reflexivity.\nQed.\n\n(* END zero_nbeq_plus_1. *)\n\n(* ((More Exercises)) *)\n\n(* Exercise: 2 stars (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 H b.\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 f H b.\n  rewrite -> H.\n  rewrite -> H.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\n(* END boolean_functions. *)\n\n(* Exercise: 2 stars (andb_eq_orb) *)\n\nLemma andb_true_b:\n  forall b : bool, andb true b = b.\nProof.\n  intros b.\n  reflexivity. \nQed.\n\nLemma orb_false_b:\n  forall b : bool, orb false b = b.\nProof.\n  intros b.\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 H.\n  destruct b.\n  rewrite <- andb_true_b.\n  rewrite -> H.\n  reflexivity.\n  rewrite <- orb_false_b.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(* END andb_eq_orb. *)\n\n(* Exercise: 3 stars (binary) *)\n\nInductive bin : Type :=\n  | bO : bin\n  | bD : bin -> bin\n  | bT : bin -> bin.\n\nFixpoint incr (b : bin) : bin :=\n  match b with\n    | bO   => bT bO\n    | bD p => bT p\n    | bT p => bD (incr p)\n  end.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | bO   => O\n    | bD p => bin_to_nat p + bin_to_nat p\n    | bT p => S (bin_to_nat p + bin_to_nat p)\n  end.\n\nExample test_bin_incr1: bin_to_nat bO = 0.\n  Proof. reflexivity. Qed.\n\nExample test_bin_incr2: bin_to_nat (incr (incr (incr bO))) = 3.\n  Proof. reflexivity. Qed.\n\nExample test_bin_incr3: bin_to_nat (incr (incr (incr (incr (incr bO))))) = 5.\n  Proof. reflexivity. Qed.\n\nExample test_bin_incr4: bin_to_nat (incr (bT (bD (bT bO)))) = 6.\n  Proof. reflexivity. Qed.\n\nExample test_bin_incr5: bin_to_nat (incr (bD (bT (bT (bT bO))))) = 15.\n  Proof. reflexivity. Qed.\n\n(* END binary. *)\n\n(* ((Fixpoint and Structural Recursion (Advanced))) *)\n\n(* Exercise: 2 stars, optional (decreasing) *)\n\n(*\n\nFixpoint fall_apart (n : nat) : nat :=\n  match n with\n    | O    => fall_apart (S O)\n    | S O  => fall_apart (S (S O))\n    | S (S O) => O\n    | S p  => fall_apart p\n  end.\n\n*)\n\n(* END decreasing. *)\n\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8688267813328976, "lm_q1q2_score": 0.776131140932218}}
{"text": "(**\n初心に戻ってリストのappendとreverseを解き直してみる。\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import Program.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection List.\n  \n  Variable A : Type.\n  \n  (* append 命題 *)\n  Inductive append : seq A -> seq A -> seq A -> Prop :=\n  | app_nil (b : seq A) : append [::] b b\n  | app_cons (h : A) (a b c : seq A) : append a b c -> append (h :: a) b (h :: c).\n  Hint Constructors append.\n  \n  (* append 関数 *)\n  Fixpoint app (a b : seq A) : seq A :=\n    match a with\n    | [::] => b\n    | h :: a => h :: app a b\n    end.\n  \n  (* 命題と関数の同値の証明 *)\n  Lemma appapp : forall (a b c : seq A), append a b c <-> app  a b = c.\n  Proof.\n    split.\n    - elim=> b'' //= a' b' c' H IH.\n        by rewrite IH.\n    - elim: a b c => //=.\n      + by move=> b c ->.\n      + move=> n' a' IH b' c' <-.\n        apply: app_cons.\n          by apply: IH.\n  Qed.\n  \n  (* Program コマンドで定義する。 *)\n  Program Fixpoint app' (a b : seq A) : {c | append a b c} :=\n    match a with\n    | [::] => b\n    | h :: a => h :: app' a b\n    end.\n  (* Obligation なし *)\n  \n  (* ******************************* *)\n  (* うしろに append する (snoc) の例 *)\n  (* ******************************* *)\n  \n  (* reverse1 命題 *)\n  Inductive reverse1 : seq A -> seq A -> Prop :=\n  | rev_nil : reverse1 [::] [::]\n  | rev_cons (h : A) (a b c : seq A) :\n      reverse1 a b -> append b [:: h] c -> reverse1 (h :: a) c.\n  Hint Constructors reverse1.\n  \n  (* rev1 関数 *)  \n  Fixpoint rev1 (a : seq A) : seq A :=\n    match a with\n    | [::] => [::]\n    | h :: a => app (rev1 a) [:: h]\n    end.\n\n  (* 命題と関数の同値の証明 *)  \n  Lemma revrev1l (a b : seq A) : reverse1 a b <-> rev1 a = b.\n  Proof.\n    split.\n    - elim=> //= n a' b' c' H1 H2 H3.\n      apply/appapp.\n        by rewrite H2.\n  - elim: a b => [b' H | n a IH c H].\n    + by rewrite -H.\n    + apply: rev_cons.\n      * by apply: IH.\n      * by apply/appapp.\n  Qed.\n  \n  (* ************* *)\n  (* 末尾再帰 の例 *)\n  (* ************* *)\n  \n  (* reverse2 命題 *)\n  Inductive reverse2 : seq A -> seq A -> seq A -> Prop :=\n  | rev2_nil (b : seq A) : reverse2 [::] b b\n  | rev2_cons (h : A) (a b c : seq A) :\n      reverse2 a (h :: b) c -> reverse2 (h :: a) b c.\n  Hint Constructors reverse2.\n  \n  (* rev2 関数 *)  \n  Fixpoint rev2 (a b : seq A) : seq A :=\n    match a with\n    | [::] => b\n    | h :: a => rev2 a (h :: b)\n    end.\n  \n  (* 命題と関数の同値の証明 *)\n  Lemma revrev2 (a b c : seq A) : reverse2 a b c <-> rev2 a b = c.\n  Proof.\n    split.\n    - by elim=> //=.\n    - elim: a b c => [b c | h a IH b c H].\n      + rewrite /rev2 => <-.\n          by apply: rev2_nil.\n      + apply: rev2_cons.\n          by apply: IH.\n  Qed.\n\n  (* Program コマンドを使用する。 *)\n  \n  Program Fixpoint rev2' (a b : seq A) : {c : seq A | reverse2 a b c} :=\n    match a with\n    | [::] => b\n    | h :: a => rev2' a (h :: b)\n    end.\n  (* Obligation なし *)\n\nEnd List.\n  \nGoal reverse2 [:: 1;2;3] [::] [:: 3;2;1].\nProof.\n  apply: rev2_cons.\n  apply: rev2_cons.\n  apply: rev2_cons.\n  apply: rev2_nil.\nQed.\n\nCompute rev2 [:: 1;2;3] [::].               (* [:: 3;2;1] *)\n\nCompute proj1_sig (rev2' [:: 1;2;3] [::]).  (* [:: 3;2;1] *)\n\n\n(**\n   依存型Vectorの定義：\n   https://www.math.nagoya-u.ac.jp/~garrigue/lecture/2011_AW/coq7.pdf\n *)\nSection Vector.\n\n  Variable A : Set.\n  \n  (* 依存型Vectorの定義 *)\n  Inductive vector : nat -> Set :=\n  | Vnil : vector 0\n  | Vcons : forall n, A -> vector n -> vector n.+1.\n  \n  Check Vnil : vector 0.\n  Check fun (h : A) => Vcons h Vnil : vector 1.\n  \n  (* vappend命題 *) \n  Inductive vappend : forall (n m : nat),\n      vector n -> vector m -> vector (n + m) -> Prop :=\n  | vapp_nil : forall (n : nat) (b : vector n), vappend Vnil b b\n  | vapp_cons : forall (h : A) (n m : nat)\n                       (a : vector n) (b : vector m) (c : vector (n + m)),\n      vappend a b c -> vappend (Vcons h a) b (Vcons h c).\n  Hint Constructors vappend.\n\n  (* vappend関数 *)\n  Fixpoint vapp (n m : nat) (a : vector n) (b : vector m) : vector (n + m) :=\n    match a with\n    | Vnil => b\n    | Vcons n h t => Vcons h (vapp t b)\n  end.\n  \n  (* 命題と関数の同値の証明 *)\n  Lemma vappapp (n m : nat) (a : vector n) (b : vector m) (c : vector (n + m)) :\n    vappend a b c <-> vapp a b = c.\n  Proof.\n    split.\n    - elim=> //= h n' m' a' b' c' H1 H2.\n        by subst.\n    - elim: a b c => //= [b c H | n' m' a IHa b c H]; subst.\n      + done.\n      + apply: vapp_cons.\n          by apply: IHa.\n  Qed.\n  \n  (* Program コマンドで定義する。 *)\n  Program Fixpoint vapp' (n m : nat) (a : vector n) (b : vector m)\n    : {c | vappend a b c} :=\n  match a with\n  | Vnil => b\n  | Vcons n h t => Vcons h (vapp' t b)\n  end.\n\n  (* reverse の命題はうまく定義できない。 *)\n  Fail Inductive vreverse : forall (n m : nat),\n      vector nat n -> vector nat m -> vector nat (n + m) -> Prop :=\n  | vrev_nil : forall (n : nat) (b : vector nat n), vreverse (Vnil nat) b b\n  | vrev_cons : forall (h : nat) (n m : nat)\n                       (a : vector nat n) (b : vector nat m) (c : vector nat (n + m).+1),\n    vreverse a (Vcons h b) c -> vreverse (Vcons h a) b c.\n  Fail Hint Constructors vreverse.\n  \n  Fail Inductive vreverse : forall (n : nat), vector nat n -> vector nat n -> Prop :=\n  | vrev_nil : vreverse (Vnil nat) (Vnil nat)\n  | vrev_cons (h : nat) (n : nat) (a b : vector nat n) (c : vector nat n.+1) :\n      vreverse a b -> vappend b (Vcons h (Vnil nat)) c -> vreverse (Vcons h a) c.\n  \n  Fail Fixpoint vrev (n : nat) (a : vector nat n) : vector nat n :=\n  match a with\n  | Vnil => Vnil nat\n  | Vcons n h t => vapp (vrev a) (Vcons h (Vnil nat))\n  end.\n  \n  (* vreverse関数 *)\n  Program Fixpoint vrev (n m : nat) (a : vector n) (b : vector m)\n    : (vector (n + m)) :=\n  match a with\n  | Vnil => b\n  | Vcons n h t => vrev t (Vcons h b)\n  end.\n  Next Obligation.\n  Proof.\n      by rewrite addSnnS.\n  Defined.\n\nEnd Vector.\n\nCheck Vnil nat : vector nat 0.\nCheck Vcons 100 (Vnil nat).\n\nDefinition data1 := Vcons 1 (Vcons 2 (Vnil nat)).\nDefinition data2 := Vcons 3 (Vcons 4 (Vnil nat)).\nDefinition data12 := Vcons 1 (Vcons 2 (Vcons 3 (Vcons 4 (Vnil nat)))).\n\nGoal vappend data1 data2 data12.\nProof.\n  apply: vapp_cons.\n  apply: vapp_cons.\n  apply: vapp_nil.\nQed.\n\nCompute vapp data1 data2. (* = Vcons 1 (Vcons 2 (Vcons 3 (Vcons 4 (Vnil nat)))) *)\nCompute proj1_sig (vapp' data1 data2).\n(* (* = Vcons 1 (Vcons 2 (Vcons 3 (Vcons 4 (Vnil nat)))) *) *)\n\nCompute vrev data1 (Vnil nat).              (* XXX *)\n\nRequire Import Extraction.\nExtraction vapp.\n(** val vapp : nat -> nat -> 'a1 vector -> 'a1 vector -> 'a1 vector **)\n(*\nlet rec vapp _ m a b =\n  match a with\n  | Vnil -> b\n  | Vcons (n, h, t) -> Vcons ((addn n m), h, (vapp n m t b))\n *)\n\nExtraction vrev.\n(** val vrev : nat -> nat -> 'a1 vector -> 'a1 vector -> 'a1 vector **)\n(* \nlet rec vrev _ m a b =\n  match a with\n  | Vnil -> b\n  | Vcons (n, h, t) -> vrev n (S m) t (Vcons (m, h, b))\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/ssr_reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7759852489876305}}
{"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(* ** Euclidian division and Bezout's identity *)\n\nRequire Import List Arith Lia Permutation Extraction.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list.\n\nSet Implicit Arguments.\n\nSection Euclid.\n\n  (* Simultaneous comparison and difference *)\n\n  Fixpoint cmp_sub x y : { z | z+y = x } + { x < y }.\n  Proof.\n    refine (match y as y' return { z | z+y' = x } + { x < y' } with\n      | 0    => inleft (exist _ x _)\n      | S y' => match x as x' return { z | z+_ = x' } + { x' < _ } with\n        | 0    => inright _\n        | S x' => match cmp_sub x' y' with\n          | inleft (exist _ z Hz) => inleft (exist _ z _)\n          | inright H => inright _\n        end\n      end\n    end); abstract lia.\n  Defined.  \n\n  Definition euclid n d : d <> 0 -> { q : nat & { r | n = q*d+r /\\ r < d } }.\n  Proof.\n    intros Hd; induction on n as euclid with measure n.\n    refine (match cmp_sub n d with\n      | inleft (exist _ z Hz) => \n      match euclid z _ with\n        | existT _ q (exist _ r Hr) => existT _ (S q) (exist _ r _) \n      end\n      | inright H      => existT _ 0 (exist _ n _)\n    end); abstract (simpl; lia).\n  Defined.\n\nEnd Euclid.\n\nDefinition arem n d q j := j <= d /\\ (n = 2*q*d+j \\/ q <> 0 /\\ n = 2*q*d-j).\n\nFact division_by_even n d : d <> 0 -> { q : nat & { j | arem n d q j } }.\nProof.\n  intros Hd.\n  destruct (@euclid n (2*d)) as (q & r & H1 & H2); try lia.\n  destruct (le_lt_dec r d) as [ Hr | Hr ].\n  + exists q, r; split; auto; left.\n    rewrite H1; ring.\n  + exists (S q), (2*d-r); split; lia.\nQed.\n\nFact own_multiple x p : x = p*x -> x = 0 \\/ p = 1.\nProof.\n  destruct x as [ | x ].\n  + left; trivial.\n  + right.\n    destruct p as [ | [ | p ] ].\n    - simpl in H; discriminate.\n    - trivial.\n    - exfalso; revert H.\n      do 2 (rewrite mult_comm; simpl).\n      generalize (p*x); intros; lia.\nQed.\n\nFact mult_is_one p q : p*q = 1 -> p = 1 /\\ q = 1.\nProof.\n  destruct p as [ | [ | p ] ].\n  + simpl; discriminate.\n  + simpl; lia.\n  + rewrite mult_comm.\n    destruct q as [ | [ | q ] ].\n    - simpl; discriminate.\n    - simpl; lia.\n    - simpl; discriminate.\nQed.\n\nDefinition divides n k := exists p, k = p*n.\n\nSection divides.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Fact divides_refl x : x div x.\n  Proof. exists 1; simpl; lia. Qed.\n\n  Fact divides_anti x y : x div y -> y div x -> x = y.\n  Proof.\n    intros (p & H1) (q & H2).\n    rewrite H1, mult_assoc in H2.\n    apply own_multiple in H2.\n    destruct H2 as [ H2 | H2 ].\n    + subst; rewrite mult_comm; auto.\n    + apply mult_is_one in H2; destruct H2; subst; lia.\n  Qed.\n\n  Fact divides_trans x y z : x div y -> y div z -> x div z.\n  Proof.\n    intros (p & H1) (q & H2).\n    exists (q*p); rewrite <- mult_assoc, <- H1; auto.\n  Qed.\n\n  Fact divides_0 p : p div 0.\n  Proof. exists 0; auto. Qed.\n\n  Fact divides_0_inv p : 0 div p -> p = 0.\n  Proof. intros (?&?); subst; rewrite Nat.mul_0_r; auto. Qed.\n\n  Fact divides_1 p : 1 div p.\n  Proof. exists p; rewrite mult_comm; simpl; auto. Qed.\n\n  Fact divides_1_inv p : p div 1 -> p = 1.\n  Proof.\n    intros (q & Hq).\n    apply mult_is_one with q; auto.\n  Qed.\n\n  Fact divides_2_inv p : p div 2 -> p = 1 \\/ p = 2.\n  Proof.\n    intros ([ | k ] & Hk); try discriminate.\n    destruct p as [ | [ | [|] ] ]; lia.\n  Qed.\n\n  Fact divides_mult p q k : p div q -> p div k*q.\n  Proof.\n    intros (r & ?); subst.\n    exists (k*r); rewrite mult_assoc; auto.\n  Qed.\n\n  Fact divides_mult_r p q k : p div q -> p div q*k.\n  Proof.\n    rewrite mult_comm; apply divides_mult; auto.\n  Qed.\n\n  Fact divides_mult_compat a b c d : a div b -> c div d -> a*c div b*d.\n  Proof. \n    intros (u & ?) (v & ?); exists (u*v); subst.\n    repeat rewrite mult_assoc; f_equal.\n    repeat rewrite <- mult_assoc; f_equal.\n    apply mult_comm.\n  Qed.\n\n  Fact divides_minus p q1 q2 : p div q1 -> p div q2 -> p div q1 - q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 - s2).\n    rewrite Nat.mul_sub_distr_r; lia.\n  Qed.\n\n  Fact divides_plus p q1 q2 : p div q1 -> p div q2 -> p div q1+q2.\n  Proof.\n    intros (s1 & H1) (s2 & H2).\n    exists (s1 + s2).\n    rewrite Nat.mul_add_distr_r; lia.\n  Qed.\n\n  Fact divides_plus_inv p q1 q2 : p div q1 -> p div q1+q2 -> p div q2.\n  Proof.\n     intros H1 H2.\n     replace q2 with (q1+q2-q1) by lia.\n     apply divides_minus; auto.\n  Qed.\n\n  Fact divides_le p q : q <> 0 -> p div q -> p <= q.\n  Proof.\n    intros ? ([] & ?); subst; lia.\n  Qed. \n\n  Fact divides_mult_inv k p q : k <> 0 -> k*p div k*q -> p div q.\n  Proof.\n    intros H (n & Hn); exists n.\n    apply Nat.mul_cancel_r with (1 := H).\n    rewrite mult_comm, Hn; ring.\n  Qed.\n\n  Lemma divides_fact m p : 1 < p <= m -> p div fact m.\n  Proof.\n    intros (H1 & H2); induction H2.\n    + destruct p; cbn. lia. unfold divides. exists (fact p). ring.\n    + cbn. eauto using divides_plus, divides_mult.\n  Qed.\n\n  Lemma divides_mult_inv_l p q r : p * q div r -> p div r /\\ q div r.\n  Proof.\n    intros []; split; subst.\n    - exists (x * q); ring.\n    - exists (x * p); ring.\n  Qed.\n\nEnd divides.\n\nSection gcd_lcm.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve divides_0 divides_refl divides_mult divides_1 : core.\n\n  Definition is_gcd p q r := r div p /\\ r div q /\\ forall k, k div p -> k div q -> k div r.\n  Definition is_lcm p q r := p div r /\\ q div r /\\ forall k, p div k -> q div k -> r div k.\n\n  Fact is_gcd_sym p q r : is_gcd p q r -> is_gcd q p r.\n  Proof. intros (? & ? & ?); repeat split; auto. Qed.\n\n  Fact is_gcd_0l p : is_gcd 0 p p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_0r p : is_gcd p 0 p.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1l p : is_gcd 1 p 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_1r p : is_gcd p 1 1.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_gcd_modulus p q k r : p div k -> k <= q -> is_gcd p q r -> is_gcd p (q-k) r.\n  Proof.\n    intros (n & Hn) Hq (H1 & H2 & H3); subst.\n    split; auto.\n    split.\n    + apply divides_minus; auto.\n    + intros k H4 H5.\n      apply H3; auto.\n      replace q with (q - n*p + n*p) by lia.\n      apply divides_plus; auto.\n  Qed.\n\n  Fact is_gcd_minus p q r : p <= q -> is_gcd p q r -> is_gcd p (q-p) r.\n  Proof. intros H1; apply is_gcd_modulus; auto. Qed.\n\n  Hint Resolve divides_plus : core.\n\n  Fact is_gcd_moduplus p q k r : p div k -> is_gcd p q r -> is_gcd p (q+k) r.\n  Proof.\n    intros (n & Hn) (H1 & H2 & H3); subst.\n    repeat (split; auto).\n    intros k H4 H5.\n    apply H3; auto.\n    rewrite plus_comm in H5.\n    apply divides_plus_inv with (2 := H5); auto. \n  Qed.\n\n  Fact is_gcd_plus p q r : is_gcd p q r -> is_gcd p (q+p) r.\n  Proof. apply is_gcd_moduplus; auto. Qed.\n\n  Fact is_gcd_mult p q r n : is_gcd p (n*p+q) r <-> is_gcd p q r.\n  Proof.\n    split.\n    + replace q with ((n*p+q)-n*p) at 2 by lia.\n      apply is_gcd_modulus; auto; lia.\n    + rewrite plus_comm; apply is_gcd_moduplus; auto.\n  Qed.\n\n  Fact is_gcd_div p q : p div q -> is_gcd p q p.\n  Proof. intros (?&?); subst; split; auto. Qed.\n\n  Fact is_gcd_refl p : is_gcd p p p.\n  Proof. split; auto. Qed.\n\n  Fact is_gcd_fun p q r1 r2 : is_gcd p q r1 -> is_gcd p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\n  Fact is_lcm_0l p : is_lcm 0 p 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_0r p : is_lcm p 0 0.\n  Proof. repeat split; auto. Qed.\n\n  Fact is_lcm_sym p q r : is_lcm p q r -> is_lcm q p r.\n  Proof. intros (?&?&?); repeat split; auto. Qed.\n\n  Fact is_lcm_fun p q r1 r2 : is_lcm p q r1 -> is_lcm p q r2 -> r1 = r2.\n  Proof. intros (?&?&?) (?&?&?); apply divides_anti; auto. Qed.\n\nEnd gcd_lcm.\n\nSection bezout.\n\n  Infix \"div\" := divides (at level 70, no associativity).\n\n  Hint Resolve is_gcd_0l is_gcd_0r is_lcm_0l is_lcm_0r divides_refl divides_mult divides_0 is_gcd_minus : core.\n\n  Section bezout_rel_prime.\n \n    (* A Bezout procedure with better extraction *)\n\n    Definition bezout_rel_prime_lt p q : \n            0 < p < q \n         -> is_gcd p q 1 \n         -> { a : nat & { b | a*p+b*q = 1+p*q \n                           /\\ a <= q \n                           /\\ b <= p } }.\n    Proof.\n      induction on p q as bezout with measure q; intros (Hp & Hq) H.\n      refine (match @euclid q p _ with\n        | existT _ n (exist _ r H0) => \n        match eq_nat_dec r 0 with\n          | left Hr => existT _ 1 (exist _ 1 _)\n          | right Hr => match @bezout r p Hq _ _ with\n            | existT _ a (exist _ b G0) => \n               existT _ (b+n*p-n*a) (exist _ a _)\n          end\n        end \n      end); try lia.\n      + destruct H0 as (H1 & H2).\n        subst r; rewrite plus_comm in H1; simpl in H1.\n        assert (is_gcd p q p) as H3.\n        { apply is_gcd_div; subst; auto. }\n        rewrite (is_gcd_fun H3 H) in *.\n        simpl; lia.\n      + replace r with (q-n*p) by lia.\n        apply is_gcd_sym, is_gcd_modulus; auto; lia.\n      + destruct H0 as (H1 & H2).\n        destruct G0 as (H3 & H4 & H5).\n        split; [ | split ]; auto.\n        * rewrite H1, Nat.mul_sub_distr_r, (mult_comm _ p).\n          do 3 rewrite Nat.mul_add_distr_l.\n          rewrite (plus_comm _ (p*r)), (plus_assoc 1), (mult_comm p r), <- H3.\n          rewrite (mult_comm n a), (mult_comm p b), mult_assoc, mult_assoc.\n          assert (a*n*p <= p*n*p) as H6.\n          { repeat (apply mult_le_compat; auto). }\n          revert H6; generalize (b*p) (a*r) (a*n*p) (p*n*p); intros; lia.\n        * rewrite H1; generalize (n*p) (n*a); intros; lia.\n    Defined.\n\n    Definition bezout_rel_prime p q : is_gcd p q 1 -> { a : nat & { b | a*p+b*q = 1+p*q } }.\n    Proof.\n      intros H.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0l _) H); exists 0, 1; auto. }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; rewrite (is_gcd_fun (is_gcd_0r _) H); exists 1, 0; auto. }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct bezout_rel_prime_lt with (2 := H)\n          as (a & b & H2 & _); try lia.\n        exists a, b; auto.\n      + subst; rewrite (is_gcd_fun (is_gcd_refl _) H); exists 1, 1; auto.\n      + destruct bezout_rel_prime_lt with (2 := is_gcd_sym H)\n          as (a & b & H2 & _); try lia.\n        exists b, a; rewrite (mult_comm p q); lia.\n    Defined.\n\n    Lemma bezout_nc p q : is_gcd p q 1 -> exists a b, a*p+b*q = 1+p*q.\n    Proof.\n      intros H.\n      destruct bezout_rel_prime with (1 := H) as (a & b & ?).\n      exists a, b; auto.\n    Qed.\n\n    Hint Resolve divides_1 : core.\n\n    Lemma bezout_sc p q a b m : a*p+b*q = 1 + m -> p div m \\/ q div m -> is_gcd p q 1.\n    Proof.\n      intros H1 H2; do 2 (split; auto).\n      intros k H4 H5.\n      apply divides_plus_inv with m.\n      +  destruct H2 as [ H2 | H2 ];\n         apply divides_trans with (2 := H2); auto.\n      + rewrite plus_comm, <- H1.\n        apply divides_plus; auto.\n    Qed.\n\n  End bezout_rel_prime.\n\n  (* We need the simple form of Bezout above to show this *)\n\n  Fact is_rel_prime_div p q k : is_gcd p q 1 -> p div q*k -> p div k.\n  Proof.\n    intros H1 (u & H2); subst.\n    destruct bezout_nc with (1 := H1) as (a & b & H3).\n    replace k with (k*(1+p*q) - k*p*q).\n    + apply divides_minus.\n      - rewrite <- H3, Nat.mul_add_distr_l.\n        apply divides_plus.\n        * rewrite mult_assoc; auto.\n        * rewrite (mult_comm b), mult_assoc, (mult_comm k), H2.\n          rewrite mult_comm, mult_assoc; auto.\n      - rewrite mult_comm, mult_assoc; auto.\n    + rewrite Nat.mul_add_distr_l, mult_assoc.\n      generalize (k*p*q); intros; lia.\n  Qed.\n\n  Fact is_rel_prime_div_r p q k : is_gcd p q 1 -> p div k*q -> p div k.\n  Proof. rewrite mult_comm; apply is_rel_prime_div. Qed.\n\n  Fact divides_is_gcd a b c : divides a b -> is_gcd b c 1 -> is_gcd a c 1.\n  Proof.\n    intros H1 H2; msplit 2; try apply divides_1.\n    intros k H3 H4.\n    apply H2; auto.\n    apply divides_trans with a; auto.\n  Qed.\n\n  Fact is_rel_prime_lcm p q : is_gcd p q 1 -> is_lcm p q (p*q).\n  Proof.\n    intros H.\n    repeat (split; auto).\n    rewrite mult_comm; auto.\n    intros k (u & ?) (v & ?); subst.\n    rewrite (mult_comm u).\n    apply divides_mult_compat; auto.\n    apply is_gcd_sym in H.\n    apply is_rel_prime_div with (1 := H) (k := u).\n    rewrite mult_comm, H1; auto.\n  Qed.\n\n  Hint Resolve divides_1 divides_mult_compat is_gcd_refl : core.\n\n  Fact is_gcd_0 p q : is_gcd p q 0 -> p = 0 /\\ q = 0.\n  Proof.\n    intros ((a & Ha) & (b & Hb) & H).\n    subst; do 2 rewrite mult_0_r; auto.\n  Qed.\n\n  Fact is_gcd_rel_prime p q g : is_gcd p q g -> exists a b, p = a*g /\\ q = b*g /\\ is_gcd a b 1.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    * intros H; subst.\n      apply is_gcd_0 in H; destruct H; subst.\n      exists 1, 1 ; simpl; auto.\n    * intros ((a & Ha) & (b & Hb) & H).\n      exists a, b; repeat (split; auto).\n      intros k H1 H2.\n      destruct (H (k*g)) as (d & Hd); subst.\n      + do 2 rewrite (mult_comm _ g); auto.\n      + do 2 rewrite (mult_comm _ g); auto.\n      + rewrite mult_assoc in Hd.\n        replace g with (1*g) in Hd at 1 by (simpl; lia).\n        apply Nat.mul_cancel_r in Hd; auto.\n        symmetry in Hd.\n        apply mult_is_one in Hd.\n        destruct Hd; subst; auto.\n  Qed.\n\n  Fact is_lcm_mult p q l k : is_lcm p q l -> is_lcm (k*p) (k*q) (k*l).\n  Proof.\n    intros (H1 & H2 & H3); repeat (split; auto).\n    intros r (a & Ha) (b & Hb).\n    destruct (eq_nat_dec k 0) as [ Hk | Hk ].\n    + subst; simpl; auto.\n    + assert (a*p = b*q) as H4.\n      { rewrite <- Nat.mul_cancel_r with (1 := Hk).\n        do 2 rewrite <- mult_assoc, (mult_comm _ k).\n        rewrite <- Hb; auto. }\n      rewrite Ha, mult_assoc, (mult_comm _ k), <- mult_assoc.\n      apply divides_mult_compat; auto.\n      apply H3; auto.\n      rewrite H4; auto.\n  Qed.\n\n  Theorem is_gcd_lcm_mult p q g l : is_gcd p q g -> is_lcm p q l -> p*q = g*l.\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ]; intros H1.\n    * subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl; auto.\n    * destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H2).\n      intros H3. \n      rewrite Hu, Hv, (mult_comm u), <- mult_assoc; f_equal.\n      rewrite (mult_comm u), (mult_comm v), <- mult_assoc, (mult_comm v).\n      apply is_lcm_fun with (2 := H3).\n      subst; rewrite (mult_comm u), (mult_comm v).\n      apply is_lcm_mult, is_rel_prime_lcm; auto.\n  Qed.\n\n  Theorem is_gcd_mult_lcm p q g l : g <> 0 -> is_gcd p q g -> g*l = p*q -> is_lcm p q l.\n  Proof.\n    intros H0 H1 H2.\n    destruct is_gcd_rel_prime with (1 := H1)\n        as (u & v & Hu & Hv & H3).\n    rewrite Hu, Hv, (mult_comm u), (mult_comm v).\n    replace l with (g*(u*v)).\n    + apply is_lcm_mult, is_rel_prime_lcm; auto.\n    + rewrite <- Nat.mul_cancel_r with (1 := H0).\n      rewrite (mult_comm l), H2, Hu, Hv,\n              (mult_comm u g), mult_assoc, mult_assoc; auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-p) = g \n           B) lcm p (q-p) = l-u*p *)\n\n  Lemma is_lcm_minus p q g l u : p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-p) (l-u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite mult_0_r, Nat.sub_0_r; auto.\n    + intros H1 H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_minus; auto.\n      * do 2 rewrite Nat.mul_sub_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite mult_assoc, (mult_comm g); auto.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q-k*p) = g \n           B) lcm p (q-p) = l-k*u*p *)\n\n  Lemma is_lcm_modulus k p q g l u : k*p <= q -> p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q-k*p) (l-k*u*p).\n  Proof.\n    rewrite <- mult_assoc.\n    intros H1 H2 H3 H4. revert H1.\n    induction k as [ | k IHk ]; intros H1.\n    + simpl; do 2 rewrite Nat.sub_0_r; auto.\n    + replace (q - S k*p) with (q -k*p -p) by (simpl; lia).\n      replace (l - S k*(u*p)) with (l - k*(u*p) - u*p).\n      - apply is_lcm_minus with (g := g); auto.\n        * simpl in H1; lia.\n        * apply is_gcd_modulus; auto.\n          simpl in H1; lia.\n        * apply IHk; simpl in H1; lia.\n      - simpl; generalize (u*p) (k*(u*p)); intros; lia.\n  Qed.\n\n  (*  if   1) p <= q \n           2) p = u*g \n           3) gcd p q = g \n           4) lcm p q = l  \n      then A) gcd p (q+p) = g \n           B) lcm p (q+p) = l+u*p *)\n\n  Lemma is_lcm_plus p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+p) (l+u*p).\n  Proof.\n    destruct (eq_nat_dec g 0) as [ H0 | H0 ].\n    + intros _ H1 H2.\n      subst; apply is_gcd_0 in H1.\n      destruct H1; subst; simpl.\n      rewrite mult_0_r, Nat.add_0_r; auto.\n    + intros H2 H3 H4.\n      apply is_gcd_mult_lcm with (1 := H0).\n      * apply is_gcd_plus; auto.\n      * do 2 rewrite Nat.mul_add_distr_l.\n        rewrite <- (is_gcd_lcm_mult H3 H4).\n        f_equal.\n        rewrite H2 at 2.\n        rewrite mult_assoc, (mult_comm g); auto.\n  Qed.\n\n  Lemma is_lcm_moduplus k p q g l u : p = u*g -> is_gcd p q g -> is_lcm p q l -> is_lcm p (q+k*p) (l+k*u*p).\n  Proof.\n    rewrite <- mult_assoc.\n    intros H2 H3 H4.\n    induction k as [ | k IHk ].\n    + simpl; do 2 rewrite Nat.add_0_r; auto.\n    + replace (q + S k*p) with (q +k*p +p) by (simpl; lia).\n      replace (l + S k*(u*p)) with (l + k*(u*p) + u*p) by (simpl; lia).\n      apply is_lcm_plus with (g := g); auto.\n      apply is_gcd_moduplus; auto.\n  Qed.\n\n  Section bezout_generalized.\n\n    (* TODO, write this FULLY specified Bezout with a better extraction, following bezout_rel_prime above *)\n\n    Definition bezout_generalized_lt p q : \n                         0 < p < q \n                      -> { a : nat \n                       & { b : nat \n                       & { g : nat\n                       & { l : nat \n                       & { u : nat\n                       & { v : nat\n                         | a*p+b*q = g + l\n                        /\\ is_gcd p q g\n                        /\\ is_lcm p q l\n                        /\\ p = u*g\n                        /\\ q = v*g\n                        /\\ a <= v\n                        /\\ b <= u } } } } } }.\n    Proof.\n      induction on p q as IH with measure q; intros (Hp & Hq).\n      destruct (@euclid q p) as (k & r & H1 & H2); try lia.\n      destruct (eq_nat_dec r 0) as [ Hr | Hr ].\n      + exists 1, 1, p, (k*p), 1, k.\n        rewrite plus_comm in H1; simpl in H1.\n        subst; repeat split; simpl; auto.\n        destruct k; lia.\n      + destruct (IH r _ Hq) as (a & b & g & l & u & v & H3 & H4 & H5 & H6 & H7 & H8 & H9); try lia.\n        exists (b+k*v-k*a), a, g, (l+k*v*p), v, (k*v+u).\n        apply is_gcd_sym in H4.\n        apply is_lcm_sym in H5.\n        rewrite plus_comm in H1.\n        assert (g <> 0) as Hg.\n        { intro; subst g; apply is_gcd_0, proj1 in H4; lia. }\n        split.\n        { rewrite H1, plus_assoc, Nat.mul_add_distr_l, <- H3.\n          rewrite Nat.mul_sub_distr_r, Nat.mul_add_distr_r.\n          rewrite mult_assoc, (mult_comm a k).\n          assert (k*a*p <= k*v*p) as G.\n          { repeat (apply mult_le_compat; auto). }\n          revert G; generalize (b*p) (a*r) (k*a*p) (k*v*p); intros; lia. }\n        split.\n        { rewrite H1; apply is_gcd_moduplus; auto. }\n        split.\n        { rewrite H1; apply is_lcm_moduplus with g; auto. }\n        split; auto.\n        split.\n        { rewrite H1, H6, H7, Nat.mul_add_distr_r, mult_assoc; lia. }\n        split; auto.\n        { rewrite (plus_comm _ u), <- Nat.add_sub_assoc.\n          +  apply plus_le_compat; auto. \n             generalize (k*v) (k*a); intros; lia.\n          + apply mult_le_compat; auto. }\n    Defined.\n  \n    Hint Resolve is_gcd_sym is_lcm_sym : core.\n\n    Definition bezout_generalized p q : { a : nat \n                                      & { b : nat \n                                      & { g : nat\n                                      & { l : nat \n                                        | a*p+b*q = g + l\n                                       /\\ is_gcd p q g\n                                       /\\ is_lcm p q l } } } }.\n    Proof.\n      destruct (eq_nat_dec p 0) as [ | Hp ].\n      { subst; exists 0, 1, q, 0; repeat (split; auto). }\n      destruct (eq_nat_dec q 0) as [ | Hq ].\n      { subst; exists 1, 0, p, 0; repeat (split; auto). }\n      destruct (lt_eq_lt_dec p q) as [ [ H1 | H1 ] | H1 ].\n      + destruct (@bezout_generalized_lt p q)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.\n        exists a, b, g, l; auto.\n      + subst q; exists 1, 1, p, p.\n        repeat split; auto; lia.\n      + destruct (@bezout_generalized_lt q p)\n          as (a & b & g & l & _ & _ & ? & ? & ? & _); try lia.\n        exists b, a, g, l; repeat (split; auto); lia.\n    Qed.\n\n  End bezout_generalized.\n\n  Section gcd_lcm.\n\n    Let gcd_full p q : sig (is_gcd p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & g & _ & _ & ? & _).\n      exists g; auto.\n    Qed.\n\n    Definition gcd p q := proj1_sig (gcd_full p q).\n    Fact gcd_spec p q : is_gcd p q (gcd p q).\n    Proof. apply (proj2_sig _). Qed.\n\n    Let lcm_full p q : sig (is_lcm p q).\n    Proof.\n      destruct (bezout_generalized p q) as (_ & _ & _ & l & _ & _ & ?).\n      exists l; auto.\n    Qed.\n\n    Definition lcm p q := proj1_sig (lcm_full p q).\n    Fact lcm_spec p q : is_lcm p q (lcm p q).\n    Proof. apply (proj2_sig _). Qed.\n\n  End gcd_lcm.\n     \nEnd bezout.\n\nSection division.\n\n  Fact div_full q p : { n : nat & { r | q = n*p+r /\\ (p <> 0 -> r < p) } }.\n  Proof.\n    case_eq p.\n    + intro; exists 0, q; subst; split; auto; intros []; auto.\n    + intros k H; destruct (@euclid q p) as (n & r & H1 & H2); try lia.\n      exists n, r; rewrite <- H; split; auto.\n  Qed.\n\n  Definition div q p := projT1 (div_full q p).\n  Definition rem q p := proj1_sig (projT2 (div_full q p)).\n\n  Fact div_rem_spec1 q p : q = div q p * p + rem q p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact div_rem_spec2 q p : p <> 0 -> rem q p < p.\n  Proof. apply (proj2_sig (projT2 (div_full q p))). Qed.\n\n  Fact rem_0 q : rem q 0 = q.\n  Proof.\n    generalize (div_rem_spec1 q 0).\n    rewrite mult_comm; auto.\n  Qed.\n\n  Fact div_rem_uniq p n1 r1 n2 r2 : \n        p <> 0 -> n1*p + r1 = n2*p + r2 -> r1 < p -> r2 < p -> n1 = n2 /\\ r1 = r2.\n  Proof.\n    intros H1 H2 H3 H4.\n    assert (n1 = n2) as E.\n    destruct (lt_eq_lt_dec n1 n2) as [ [ H | ] | H ]; auto.\n    + replace n2 with (n2-n1 + n1) in H2 by lia.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n2-n1)*p) as H5.\n      { apply mult_le_compat; lia. }\n      simpl in H5; lia.\n    + replace n1 with (n1-n2 + n2) in H2 by lia.\n      rewrite Nat.mul_add_distr_r in H2.\n      assert (1*p <= (n1-n2)*p) as H5.\n      { apply mult_le_compat; lia. }\n      simpl in H5; lia.\n    + subst; lia.\n  Qed.\n\n  Fact div_prop q p n r : q = n*p+r -> r < p -> div q p = n.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p _ (rem q p) n r); auto.\n    + lia.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; lia.\n  Qed.\n\n  Fact rem_prop q p n r : q = n*p+r -> r < p -> rem q p = r.\n  Proof.\n    intros H1 H2.\n    apply (@div_rem_uniq p (div q p) _ n r); auto.\n    + lia.\n    + rewrite <- H1; symmetry; apply div_rem_spec1.\n    + apply div_rem_spec2; lia.\n  Qed.\n\n  Fact rem_idem q p : q < p -> rem q p = q.\n  Proof. apply rem_prop with 0; auto. Qed.\n\n  Fact rem_rem x m : rem (rem x m) m = rem x m.\n  Proof.\n    destruct (eq_nat_dec m 0).\n    + subst; rewrite !rem_0; auto.\n    + apply rem_idem, div_rem_spec2; auto.\n  Qed.\n\n  Fact is_gcd_rem p n a : is_gcd p n a <-> is_gcd p (rem n p) a.\n  Proof.\n    rewrite (div_rem_spec1 n p) at 1; apply is_gcd_mult.\n  Qed.\n\n  Fact rem_erase q n p r : q = n*p+r -> rem q p = rem r p.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ | Hp ]; subst.\n    + rewrite mult_comm, rem_0, rem_0; auto.\n    + destruct (div_full r p) as (m & r' & H1 & H2).\n      specialize (H2 Hp).\n      rewrite rem_prop with r p m r'; auto.\n      intros; apply rem_prop with (n+m); auto.\n      rewrite Nat.mul_add_distr_r; lia.\n  Qed.\n\n  Fact divides_div q p : divides p q -> q = div q p * p.\n  Proof.\n    intros (k & Hk).\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + subst; do 2 (rewrite mult_comm; simpl); auto.\n    + rewrite (@div_prop q p k 0); lia.\n  Qed.\n\n  Fact divides_rem_eq q p : divides p q <-> rem q p = 0.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    * subst; rewrite rem_0; split.\n      + apply divides_0_inv.\n      + intros; subst; apply divides_0.\n    * split.\n      + intros (n & Hn).\n        apply rem_prop with n; lia.\n      + intros H.\n        generalize (div_rem_spec1 q p).\n        exists (div q p); lia.\n  Qed.\n\n  Fact rem_of_0 p : rem 0 p = 0.\n  Proof.\n    destruct p.\n    + apply rem_0.\n    + apply rem_prop with 0; lia.\n  Qed.\n\n  Hint Resolve divides_0_inv : core.\n\n  Fact divides_dec q p : { k | q = k*p } + { ~ divides p q }.\n  Proof.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    + destruct (eq_nat_dec q 0) as [ Hq | Hq ].\n      * left; subst; exists 1; auto.\n      * right; contradict Hq; subst; auto.\n    + destruct (@euclid q p Hp) as (n & [ | r ] & H1 & H2).\n      * left; exists n; subst; rewrite plus_comm; auto.\n      * right; intros (m & Hm).\n        rewrite <- Nat.add_0_r in Hm.\n        rewrite Hm in H1.\n        destruct (div_rem_uniq _ _ Hp H1); lia.\n  Qed.\n\nEnd division.\n\nSection rem.\n\n  Variable (p : nat) (Hp : p <> 0).\n\n  Fact rem_plus_rem a b : rem (a+rem b p) p = rem (a+b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite plus_assoc.\n    symmetry; apply rem_erase with (div (b) p); ring.\n  Qed.\n\n  Fact rem_mult_rem a b : rem (a*rem b p) p = rem (a*b) p.\n  Proof.\n    rewrite (div_rem_spec1 b p) at 2.\n    rewrite Nat.mul_add_distr_l, mult_assoc.\n    symmetry; apply rem_erase with (a*div b p); auto.\n  Qed.\n\n  Fact rem_diag : rem p p = 0.\n  Proof. apply rem_prop with 1; lia. Qed.\n\n  Fact rem_lt a : a < p -> rem a p = a.\n  Proof. apply rem_prop with 0; lia. Qed.\n\n  Fact rem_plus a b : rem (a+b) p = rem (rem a p + rem b p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite (div_rem_spec1 b p) at 1.\n    apply rem_erase with (div a p + div b p).\n    ring.\n  Qed.\n\n  Fact rem_scal k a : rem (k*a) p = rem (k*rem a p) p.\n  Proof.\n    rewrite (div_rem_spec1 a p) at 1.\n    rewrite Nat.mul_add_distr_l.\n    apply rem_erase with (k*div a p).  \n    ring.\n  Qed.\n\n  Fact rem_plus_div a b : divides p b -> rem a p = rem (a+b) p.\n  Proof. \n    intros (n & Hn); subst.\n    rewrite <- rem_plus_rem.\n    f_equal.  \n    rewrite <- rem_mult_rem, rem_diag, Nat.mul_0_r, rem_of_0; lia.\n  Qed.\n\n  Fact div_eq_0 n : n < p -> div n p = 0.\n  Proof. intros; apply div_prop with n; lia. Qed.\n\n  Fact div_of_0 : div 0 p = 0.\n  Proof. apply div_eq_0; lia. Qed.\n\n  Fact div_ge_1 n : p <= n -> 1 <= div n p.\n  Proof.\n    intros H2.\n    rewrite (div_rem_spec1 n p) in H2.\n    generalize (div_rem_spec2 n Hp); intros H3.\n    destruct (div n p); lia.\n  Qed.\n\nEnd rem.\n\nFact divides_rem_rem p q a : divides p q -> rem (rem a q) p = rem a p.\nProof.\n  destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n  { intros (k & ->); subst; rewrite mult_0_r.\n    repeat rewrite rem_0; auto. }\n  intros H.\n  generalize (div_rem_spec1 a q); intros H1.\n  destruct H as (k & ->).\n  rewrite H1 at 2.\n  rewrite plus_comm.\n  apply rem_plus_div; auto.\n  do 2 apply divides_mult.\n  apply divides_refl.\nQed.\n \nFact divides_rem_congr p q a b : divides p q -> rem a q = rem b q -> rem a p = rem b p.\nProof.\n  intros H1 H2.\n  rewrite <- (divides_rem_rem a H1),\n          <- (divides_rem_rem b H1).\n  f_equal; auto.\nQed.\n\nFact div_by_p_lt p n : 2 <= p -> n <> 0 -> div n p < n.\nProof.\n  intros H1 H2.\n  rewrite (div_rem_spec1 n p) at 2.\n  replace p with (2+(p-2)) at 3 by lia.\n  rewrite Nat.mul_add_distr_l.\n  generalize (div n p*(p-2)); intros x.\n  destruct (le_lt_dec p n) as [ Hp | Hp ].\n  + apply div_ge_1 in Hp; lia.\n  + rewrite rem_lt; lia.\nQed.\n\nSection rem_2.\n\n  Fact rem_2_is_0_or_1 x : rem x 2 = 0 \\/ rem x 2 = 1.\n  Proof. generalize (rem x 2) (@div_rem_spec2 x 2); intros; lia. Qed.\n\n  Fact rem_2_mult x y : rem (x*y) 2 = 1 <-> rem x 2 = 1 /\\ rem y 2 = 1.\n  Proof. \n    generalize (rem_2_is_0_or_1 x) (rem_2_is_0_or_1 y).\n    do 2 rewrite <- rem_mult_rem, mult_comm.\n    intros [ H1 | H1 ] [ H2 | H2 ]; rewrite H1, H2; simpl; rewrite rem_lt; lia.\n  Qed.\n\n  Fact rem_2_fix_0 : rem 0 2 = 0.\n  Proof. apply rem_lt; lia. Qed.\n\n  Fact rem_2_fix_1 n : rem (2*n) 2 = 0.\n  Proof. apply divides_rem_eq; exists n; ring. Qed.\n\n  Fact rem_2_fix_2 n : rem (1+2*n) 2 = 1.\n  Proof.\n    rewrite <- rem_plus_rem,rem_2_fix_1, rem_lt; lia.\n  Qed.\n\n  Fact rem_2_lt n : rem n 2 < 2.\n  Proof. apply div_rem_spec2; lia. Qed.\n\n  Fact div_2_fix_0 : div 0 2 = 0.\n  Proof. apply div_of_0; lia. Qed.\n\n  Fact div_2_fix_1 n : div (2*n) 2 = n.\n  Proof. apply div_prop with 0; lia. Qed.\n\n  Fact div_2_fix_2 n : div (1+2*n) 2 = n.\n  Proof. apply div_prop with 1; lia. Qed.\n\n  Fact euclid_2_div n : n = rem n 2 + 2*div n 2 /\\ (rem n 2 = 0 \\/ rem n 2 = 1).\n  Proof.\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.\n  Qed.\n\n  Fact euclid_2 n : exists q, n = 2*q \\/ n = 1+2*q.\n  Proof. \n    exists (div n 2).\n    generalize (div_rem_spec1 n 2) (@div_rem_spec2 n 2); intros; lia.\n  Qed.\n\nEnd rem_2.\n\nLocal Hint Resolve divides_mult divides_mult_r divides_refl : core.\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/gcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7758905000125161}}
{"text": "Inductive bin : Type :=\n  | Z \n  | B0 (n : bin)\n  | B1 (n : bin).\n\nDefinition double_bin (b:bin) : bin :=\n    match b with \n    | Z => Z\n    | n => B0 n\n    end.\n\n\nFixpoint incr (m : bin) : bin :=\n    match m with \n    | Z => B1 Z \n    | B0 n => B1 n  \n    | B1 n => B0 (incr n)\n    end. \n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with \n  | Z => O \n  | B0 n => 2 * bin_to_nat n \n  | B1 n => 1 + 2 * bin_to_nat n \n  end. \n\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with \n  | O => Z \n  | S n' => incr (nat_to_bin n')\n  end. \n\nFixpoint normalize (b:bin) : bin :=\n    match b with \n    | Z => Z \n    | B0 Z => Z \n    | B0 n => B0(normalize(n))\n    | B1 n => B1(normalize(n))\n    end.\n\n Lemma double_incr_bin : forall b,\n    double_bin (incr b) = incr (incr (double_bin b)).\nProof.\n  intros b. induction b as [| b' | b'].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  Qed. \n\nLemma n_plus_0_eq_n : forall n : nat, \n  n + 0 = n. \nProof. \n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\n  Qed. \n\nLemma l8r : forall b : bin, \n  bin_to_nat b + bin_to_nat b = 2 * bin_to_nat b.\nProof.\n    intros b. simpl. rewrite -> n_plus_0_eq_n. reflexivity.\n    Qed.\n\nLemma l9r : forall b : bin, \n    bin_to_nat(B0 b) = 2 * bin_to_nat b. \nProof. \n    intros b. reflexivity.\n    Qed.\n\nLemma add_assoc : forall n m p : nat, \n    n + (m + p) = (n + m) + p. \nProof. Admitted.\n\nLemma l12r : forall b : bin, \n  nat_to_bin(2 * bin_to_nat b) = double_bin(nat_to_bin(bin_to_nat b)).\nProof.\n  intros b. induction b as [| b' | b'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> n_plus_0_eq_n. rewrite -> n_plus_0_eq_n. rewrite -> l8r. rewrite <- l9r. rewrite -> l8r.\n\nLemma kk : forall b : bin, \n    nat_to_bin (bin_to_nat (B0 b)) = double_bin(nat_to_bin (bin_to_nat b)).\nProof. \n    intros b. induction b as [| b' | b'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> n_plus_0_eq_n. rewrite -> n_plus_0_eq_n. rewrite -> l8r. rewrite <- l9r. rewrite -> IHb'. rewrite -> l8r. rewrite ->  l9r.\n\n(* Lemma jj : forall b : bin, \n    normalize(B0 b) = normalize(double_bin(normalize(b))).\nProof. \n  intros b. induction b as [| b' | b'].\n  - reflexivity.\n  -  *)\n\n(* Lemma l10r : forall b : bin, \n    double_bin(normalize b) = normalize(double_bin b).\nProof. \n  intros b. induction b as [| b' | b'].\n  - reflexivity.\n  - *)\n\n(* Lemma l11r : forall b : bin, \n    normalize(normalize b) = normalize b. \nProof. \n  intros b. induction b as [| b' | b'].\n  - simpl. reflexivity.\n  -  *)\n\n\n\nLemma l13r : forall b : bin, \n  incr(double_bin (b)) = B1 b.\nProof.\n  intros b. induction b as [| b' | b'].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nTheorem bin_nat_bin : forall b, \n    nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n    intros b. induction b as [| b' | b'].\n    - reflexivity.\n    - rewrite -> kk. rewrite -> IHb'. rewrite -> jj. \n    rewrite -> l10r. rewrite -> l11r. reflexivity.\n    - simpl. rewrite -> n_plus_0_eq_n. rewrite -> l8r. rewrite <- IHb'.\n    rewrite -> l12r. rewrite -> IHb'. rewrite -> l13r. reflexivity. \n    Qed.\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/induction/exercises/bin_nat_bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7758804084789752}}
{"text": "Section ExerciseOne.\n\nLemma Ex1A : forall a b c : Prop, (a \\/ b) \\/ c -> a \\/ (b \\/ c).\nProof.\nintros a b c H.\ndestruct H as [HO | H3].\ndestruct HO as [H1 | H2].\n  left.\n  exact H1.\n  right.\n  left.\n  exact H2.\n  right.\n  right.\n  exact H3. \nQed.\n\nLemma Ex1B : forall a b c : Prop, (b -> c) -> a \\/ b -> a \\/ c.\nintros a b c H1 H2.\ndestruct H2 as [H3 | H4].\n  left.\n  exact H3. \n  right.\n  apply H1.\n  exact H4. \nQed.\n\nLemma Ex1C : forall a b c : Prop, (a /\\ b) /\\ c -> a /\\ (b /\\ c). \nintros a b c H. \ndestruct H as [HO H3].\ndestruct HO as [H1 H2].\n  split.\n    exact H1.\n    split.\n      exact H2. \n      exact H3. \nQed.\n\nLemma Ex1D : forall a b c : Prop, a \\/ (b \\/ c) -> (a \\/ b) \\/ (a \\/ c).\nintros a b c H.\ndestruct H as [HO | H3].\n  left.\n  left.\n  exact HO.\n  destruct H3 as [H1 | H2].\n    left.\n    right.\n    exact H1.\n    right.\n    right.\n    exact H2.\nQed.\n\nLemma Ex1E : forall a b c : Prop, (a /\\ b) \\/ (a /\\ c) <-> a /\\ (b \\/ c).\nintros a b c.\nsplit.\n  (* left to right *)\n  intros H.\n  split.\n    destruct H as [H1 | H2].\n    destruct H1 as [H3 H4].\n    exact H3.\n    destruct H2 as [H5 H6].\n    exact H5.\n  destruct H as [H1 | H2].\n  destruct H1 as [H3 H4].\n  left.\n  exact H4.\n  destruct H2 as [H5 H6].\n  right.\n  exact H6.\n  (* right to left *)\n  intros H. \n  destruct H as [H1 H2]. \n  destruct H2 as [H3 | H4].\n  left.\n  split.\n  exact H1.\n  exact H3.\n  right.\n  split.\n  exact H1.\n  exact H4.\nQed.\n\nLemma Ex1F : forall a b c : Prop, (a \\/ b) /\\ (a \\/ c) <-> a \\/ (b /\\ c).\nProof.\nintros a b c.\nsplit.\n  (* left to right *)\n  intros H.\n  destruct H as [H1 H2].\n  destruct H1 as [H3 | H4].\n  left; exact H3.\n  destruct H2 as [H5 | H6].\n  left; exact H5.\n  right.\n  split.\n    exact H4.\n    exact H6.\n  (* right to left *)\n  intro H.\n  split; destruct H as [H1 | H2].\n    left; exact H1.\n    destruct H2 as [H3 H4].\n    right; exact H3.\n    left; exact H1.\n    destruct H2 as [H3 H4].\n    right; 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/p1ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7758408210720699}}
{"text": "Require Import FSets MapFunction.\nRequire Import Arith EqNat Euclid ArithRing ZArith.\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\n(** First, let's define powers of 2 and binomial function \n    for later expressing the cardinal of powersets. *)\n\nFixpoint two_power (n:nat) : nat := match n with \n | O => 1\n | S n => 2 * (two_power n)\n end.\n\nFixpoint binomial n k { struct n } := match n, k with \n  | _, O => 1\n  | O, _ => 0 \n  | S n', S k' => binomial n' k' + binomial n' k\n end. \n\nFixpoint fact n := match n with \n  | O => 1 \n  | S n' => n * (fact n') \n end.\n\nLemma binomial_0 : forall n k, k>n -> binomial n k = 0.\nProof.\ninduction n; destruct k; simpl; auto.\ninversion 1.\ninversion 1.\nintros.\ndo 2 (rewrite IHn; auto with arith).\nQed.\n\nLemma binomial_rec : forall n k, k<=n -> \n (binomial n k)*(fact k * fact (n-k)) = fact n.\nProof.\ninduction n; destruct k.\nsimpl; auto.\ninversion 1.\nsimpl; intros; ring.\nintros.\nchange (fact (S n)) with ((1+n)*(fact n)).\nchange (fact (S k)) with ((1+k)*(fact k)).\nsimpl (S n - S k).\nsimpl binomial.\ninversion_clear H.\nrewrite (@binomial_0 n (S n)); auto.\npattern (fact n) at 2; rewrite <- (IHn n); auto; ring.\ncut ((binomial n k)*(fact k*fact (n-k))*(1+k) + \n     (binomial n (S k))*(fact (S k)*fact (n-S k))*(n-k) = \n     (1+n)*fact n).\nintros H; rewrite <- H.\nreplace (n-k) with (S (n-S k)) by omega.\nsimpl; ring.\nrewrite (IHn k); auto with arith.\nrewrite (IHn (S k)); auto with arith.\ncut (((1+k)+(n-k))*(fact n) = (1+n)*(fact n)).\nintro H; rewrite <- H; ring.\nreplace (1+k+(n-k)) with (1+n) by omega; auto.\nQed.\n\nLemma fact_pos : forall k, fact k > 0.\nProof.\n induction k; simpl; auto with arith.\nQed.\n\nLemma binomial_den_pos : forall n k, fact k * fact (n-k) > 0.\nProof.\n intros; generalize (fact_pos k) (fact_pos (n-k)).\n unfold gt; intros.\n change 0 with (0*(fact (n-k))).\n apply mult_lt_compat_r; auto with arith.\nQed.\n\nDefinition binomial' n k := \n let (q,_) := quotient (fact k * fact (n-k)) (binomial_den_pos n k) (fact n)\n in q.\n\nLemma binomial_alt : forall n k, k<=n -> \n binomial n k = binomial' n k.\nProof.\nintros.\nunfold binomial'.\ndestruct quotient as (q,(r,(H1,H2))).\nassert (H3:=binomial_rec H).\nassert (H4:=binomial_den_pos n k).\nset (D:=fact k * fact (n-k)) in *.\nassert (r = fact n - q * D) by omega.\nrewrite <- H3 in H0.\nassert (r = (binomial n k - q)*D) by (rewrite H0;auto with arith).\nrewrite H5 in H2; unfold gt in H2.\ncase_eq (binomial n k - q); intros.\nrewrite H6 in *; simpl in *.\nrewrite H5 in *; simpl in *.\nrewrite plus_comm in H1; simpl in H1.\nrewrite H1 in H3.\nassert (0 = q*D - binomial n k*D) by (rewrite H3; auto with arith).\nassert (0 = (q - binomial n k)*D) by (rewrite H7; auto with arith).\ncase_eq (q - binomial n k); intros.\nomega.\nassert (0 * D < S n0 * D).\n apply mult_lt_compat_r; auto with arith.\nrewrite <- H9 in H10; rewrite <- H8 in H10; simpl in H10; inversion H10.\nassert (1 * D <= S n0 * D).\n apply mult_le_compat; auto with arith.\nrewrite <- H6 in H7.\nsimpl in H7; rewrite plus_comm in H7; simpl in H7.\nomega.\nQed.\n\n\nModule PowerSet (M:S).\n\n(* M is our base sets structure. *)\n(* MM is a \"sets of sets\" structure: *)\nModule MM := FSetList.Make M.\n(* Adding a map function to MM... *)\nModule MM' := MapFunction.MapFunction MM.\n(* Properties functors *)\nModule P := FSetProperties.Properties M.\nModule P' := FSetProperties.OrdProperties M.\nModule F := P.FM.\nModule PEP := FSetEqProperties.EqProperties MM.\nModule PP := PEP.MP.\nModule FF := PP.FM.\nModule ME := OrderedTypeFacts M.E.\n\nInfix \"[=]\" := M.Equal (at level 70, no associativity).\nInfix \"[==]\" := MM.Equal (at level 70, no associativity).\n\n(** Computing the set of all subsets of a particular set [s] *)\n\nDefinition powerset s := \n  M.fold \n   (fun (x:M.elt)(ss:MM.t) => MM.union ss (MM'.map (M.add x) ss)) \n   s \n   (MM.singleton M.empty).\n\n(** Proofs about powerset *)\n\nLemma map_add : forall s s' x, MM.In s' (MM'.map (M.add x) s)\n <-> M.In x s' /\\ (MM.In s' s \\/ MM.In (M.remove x s') s).\nProof.\nintros.\nrewrite MM'.map_In by (intros; rewrite H; reflexivity).\nunfold M.eq in *.\nsplit; [intros (b & IN & EQ) | intros (IN,[OR1|OR2]) ].\nassert (M.In x s') by (rewrite <- EQ; auto with set).\nsplit; auto.\ndestruct (P.In_dec x b); [left|right]; \n apply MM.In_1 with (2:=IN); P.Dec.fsetdec.\n (* sans le P.Dec.fsetdec : \n     rewrite <- IN; red; intro a; F.set_iff; intuition.\n     eauto with set. ----> anomaly *)\n\nexists s'; split; auto; P.Dec.fsetdec.\nexists (M.remove x s'); split; auto; P.Dec.fsetdec.\nQed.\n\nLemma compat_op_pow :\n compat_op M.E.eq MM.Equal\n  (fun x0 ss => MM.union ss (MM'.map (M.add x0) ss)).\nProof.\nrepeat red; intros; FF.set_iff.\ndo 2 rewrite map_add; rewrite H; rewrite H0; intuition.\nQed.\nHint Resolve compat_op_pow : set.\n\nLemma singleton_empty : forall s, MM.In s (MM.singleton M.empty) <-> M.Empty s.\nProof.\nintros.\nrewrite FF.singleton_iff; split; unfold M.eq; auto with set.\nQed.\n\nLemma powerset_base : forall s, M.Empty s -> powerset s [==] MM.singleton M.empty.\nProof.\nintros; unfold powerset.\nrewrite (@P.fold_1 s MM.t MM.Equal FF.Equal_ST); auto with set.\nQed.\n\nLemma powerset_step : forall s1 s2 x, P'.Above x s1 -> P.Add x s1 s2 -> \n powerset s2 [==] MM.union (powerset s1) (MM'.map (M.add x) (powerset s1)). \nProof.\nintros; unfold powerset.\nrewrite (@P'.fold_3 s1 s2 x MM.t MM.Equal FF.Equal_ST); auto with set.\nQed.\n\nLemma powerset_is_powerset: \n forall s s', MM.In s' (powerset s) <-> M.Subset s' s.\nProof.\ninduction s using P'.set_induction_max; intros.\n\nrewrite (powerset_base H).\nrewrite singleton_empty; firstorder.\n\nrewrite (powerset_step H H0).\nFF.set_iff.\nrewrite map_add.\ndo 2 rewrite IHs1; clear IHs1.\nsplit; [intros [U|[U [V|V]]]|intros U].\nfirstorder.\nfirstorder.\nred; intro a; generalize (H a)(H0 a); F.set_iff; destruct (F.eq_dec a x); intuition.\n(*eauto with set. (* Anomaly: uncaught exception Failure \"Cannot print a global reference\". *)*)\napply H6; apply V; auto with set.\ndestruct (P.In_dec x s'); [right|left].\nsplit; auto.\nright.\nred; intro a; generalize (U a)(H0 a); F.set_iff; intuition.\nred; intro a; generalize (U a)(H0 a); intuition.\nelim n; rewrite H4; auto.\nQed.\n\nLemma powerset_cardinal: \n forall s, MM.cardinal (powerset s) = two_power (M.cardinal s).\nProof.\ninduction s using P'.set_induction_max; intros.\n\nrewrite (powerset_base H).\nrewrite PP.singleton_cardinal.\nrewrite P.cardinal_1; simpl; auto.\n\nrewrite (powerset_step H H0).\nrewrite PP.union_cardinal.\nrewrite MM'.map_cardinal.\nrewrite IHs1.\nrewrite (@P.cardinal_2 s1 s2 x); auto.\nsimpl; auto.\nred; intros.\nelim (@M.E.lt_not_eq x x); auto.\nintros; rewrite H1; reflexivity.\nintros u v; do 2 rewrite powerset_is_powerset.\nred; red; intros.\ngeneralize (H3 a) (H1 a) (H2 a); F.set_iff; clear H3 H1 H2.\nintuition; elim (@M.E.lt_not_eq a x); auto.\nintros u (A,B).\nrewrite powerset_is_powerset in A.\nrewrite map_add in B; destruct B as (B,_).\nelim (@M.E.lt_not_eq x x); auto.\nQed.\n\n(** Computing the set of all subsets of cardinal k for a particular set [s] *)\n\nDefinition powerset_k s k := \n MM.filter (fun s => beq_nat (M.cardinal s) k) (powerset s).\n\n\n(** Proofs about powerset_k *)\n\nLemma powerset_k_is_powerset_k : forall k s s', \n MM.In s' (powerset_k s k) <-> M.Subset s' s /\\ M.cardinal s' = k.\nProof.\nunfold powerset_k; intros.\nrewrite FF.filter_iff by (red; intros; f_equal; auto).\nrewrite powerset_is_powerset. \nintuition.\napply beq_nat_eq; auto.\nsubst; symmetry; apply beq_nat_refl.\nQed.\n\nLemma powerset_k_cardinal : forall s k, \n MM.cardinal (powerset_k s k) = binomial (M.cardinal s) k.\nProof.\nassert (forall k, compat_bool M.Equal (fun s0 => beq_nat (M.cardinal s0) k)).\n red; intros; f_equal; auto.\ninduction s using P'.set_induction_max; unfold powerset_k; intros.\n\nrewrite P.cardinal_1; auto.\ndestruct k.\nrewrite <- (@PP.Equal_cardinal (MM.singleton M.empty)).\n apply PP.singleton_cardinal.\n red; intros.\n rewrite FF.filter_iff; auto.\n rewrite powerset_base; auto.\n rewrite singleton_empty.\n intuition.\n rewrite P.cardinal_1; auto.\nrewrite <- (@PP.Equal_cardinal MM.empty).\n apply PP.cardinal_1; auto.\n red; intros.\n rewrite FF.empty_iff; rewrite FF.filter_iff; auto.\n rewrite powerset_base; auto.\n rewrite singleton_empty.\n intuition.\n rewrite (P.cardinal_1 H2) in H3; simpl in H3; discriminate.\n\nassert (H2 := powerset_step H0 H1).\nrewrite (FF.filter_equal (H k) H2).\nrewrite PEP.filter_union; auto.\nrewrite PP.union_cardinal; auto.\nunfold powerset_k in IHs1.\nrewrite IHs1.\nrewrite MM'.map_filter by (auto; intros; rewrite H3; reflexivity).\nrewrite MM'.map_cardinal. \ndestruct k.\nrewrite PP.cardinal_1.\ndestruct (M.cardinal s1); destruct (M.cardinal s2); auto.\nred; intro a; rewrite FF.filter_iff.\nred; destruct 1.\ncase_eq (M.cardinal (M.add x a)); intros.\nelim (@P.cardinal_inv_1 _ H5 x); F.set_iff; auto.\nrewrite H5 in H4; simpl in H4; inversion H4.\nrepeat red; intros; f_equal; rewrite H3; auto.\nassert (MM.filter (fun x0 => beq_nat (M.cardinal (M.add x x0)) (S k)) (powerset s1)\n   [==] MM.filter (fun x0 => beq_nat (M.cardinal x0) k) (powerset s1)).\nred; intros.\nrewrite FF.filter_iff by (repeat red; intros; f_equal; rewrite H3; auto).\nrewrite FF.filter_iff by (repeat red; intros; f_equal; rewrite H3; auto).\nrewrite powerset_is_powerset.\nintuition.\nassert (~M.In x a).\n red; intros; elim (@ME.lt_antirefl x); auto.\nrewrite P.add_cardinal_2 in H5; simpl in H5; auto.\nassert (~M.In x a).\n red; intros. elim (@ME.lt_antirefl x); auto.\nrewrite P.add_cardinal_2; simpl; auto.\nrewrite H3.\nrewrite IHs1.\nrewrite (@P.cardinal_2 s1 s2 x); auto.\nsimpl; auto with arith.\nred; intros; elim (@ME.lt_antirefl x); auto. \n\nintros; rewrite H3; reflexivity.\n\nintros.\nrewrite FF.filter_iff in H3.\ndestruct H3.\nrewrite FF.filter_iff in H4.\ndestruct H4.\nrewrite powerset_is_powerset in H3.\nrewrite powerset_is_powerset in H4.\nassert (~M.In x x0).\n red; intros; elim (@ME.lt_antirefl x); auto.\nassert (~M.In x y).\n red; intros; elim (@ME.lt_antirefl x); auto.\nred; red; intros.\ngeneralize (H5 a); clear H5; do 2 rewrite F.add_iff.\nintuition.\nelim H8; apply M.In_1 with a; auto.\nelim H8; apply M.In_1 with a; auto.\nelim H9; apply M.In_1 with a; auto.\nelim H9; apply M.In_1 with a; auto.\nrepeat red; intros; f_equal; rewrite H7; auto.\nrepeat red; intros; f_equal; rewrite H6; auto.\n\nintros.\nrewrite !FF.filter_iff by (red; intros; subst; auto).\nrewrite map_add.\nrewrite !powerset_is_powerset.\nintros ((A,_),((B,_),_)).\nelim (@ME.lt_antirefl x); auto.\nQed.\n\n(** A more \"direct\" definition *)\n\nDefinition powerset_k' s := \n  M.fold \n  (fun (x:M.elt)(ff:nat->MM.t)(k:nat) => match k with \n    | O => ff 0\n    | S k' => MM.union (ff k) (MM'.map (M.add x) (ff k'))\n   end) \n  s \n  (fun k => if k then MM.singleton M.empty else MM.empty).\n\nLemma powerset_k'_is_powerset_k : \n forall s s' k, MM.In s' (powerset_k' s k) <-> M.Subset s' s /\\ M.cardinal s' = k.\nProof.\nassert (ST : Setoid_Theory _ (fun g h => forall k:nat, g k [==] h k)).\n constructor; red; auto with set.\n intros; apply PP.equal_trans with (y k); auto with set.\n\ninduction s using P'.set_induction_max; intros.\n\nintros; unfold powerset_k'.\nassert (T:=P.fold_1 ST (s:=s)).\nsimpl in T; rewrite T; clear T; auto.\n\ndestruct k.\nrewrite singleton_empty.\nintuition idtac.\nfirstorder.\nintuition.\nintuition.\nrewrite FF.empty_iff.\nintuition.\nrewrite P.cardinal_1 in H2; try discriminate; firstorder.\n\nintros; unfold powerset_k'.\nassert (T:=P'.fold_3 ST (s:=s1) (s':=s2) (x:=x)).\nsimpl in T; rewrite T; clear T; auto.\n\nchange (MM.In s' (match k with \n         | O => powerset_k' s1 0\n         | S k' => MM.union (powerset_k' s1 k) (MM'.map (M.add x) (powerset_k' s1 k'))\n         end) <-> M.Subset s' s2 /\\ M.cardinal s' = k).\ndestruct k.\nrewrite IHs1.\nintuition idtac.\nred; intros.\nelim (P.cardinal_inv_1 H3 H1).\nred; intros.\nelim (P.cardinal_inv_1 H3 H1).\nFF.set_iff.\nrewrite map_add.\ndo 3 rewrite IHs1; clear IHs1.\nsplit; destruct 1.\ndestruct H1; split; auto.\napply P.subset_trans with s1; auto; red; intros; rewrite (H0 a); auto.\ndestruct H1.\ndestruct H2; intuition idtac.\nfirstorder.\nelim (@M.E.lt_not_eq x x); auto.\nred; intro a; generalize (H3 a)(H0 a); F.set_iff; destruct (F.eq_dec a x); intuition.\nrewrite <- H4.\nsymmetry; apply P.remove_cardinal_1; auto.\ndestruct (P.In_dec x s').\nright.\n split; auto.\n right; split.\n red; intro a; generalize (H1 a)(H0 a); F.set_iff; intuition.\n generalize (P.remove_cardinal_1 i); auto.\n rewrite H2; inversion 1; auto.\nleft.\n split; auto.\n red; intro a; generalize (H1 a)(H0 a); intuition.\n elim n; rewrite H6; auto.\n\nunfold compat_op, Proper, respectful; intros.\ndestruct k0; auto.\nred; intros; FF.set_iff.\nrewrite !map_add, !H2, H1; split; auto.\nQed.\n\nLemma powerset_k_alt : \n forall s k, powerset_k' s k [==] powerset_k s k.\nProof.\nred; intros.\nrewrite powerset_k'_is_powerset_k. \nrewrite powerset_k_is_powerset_k.\nsplit; auto.\nQed.\n\nEnd PowerSet.\n\n(** An example: *)\n\nOpen Scope positive_scope.\n\nModule P := FSetList.Make Positive_as_OT.\nModule PS := PowerSet P.\nModule PP := PS.MM.\n\n(* The set containing numbers 1..n *)\nFixpoint interval (n:nat) {struct n} : P.t := match n with \n | O => P.empty\n | S n => P.add (P_of_succ_nat n) (interval n)\n end.\n\nEval vm_compute in P.elements (interval 10).\n\nDefinition powerset_5 := PS.powerset (interval 5).\n\nEval vm_compute in map P.elements (PP.elements powerset_5).\n\nDefinition subsets_size2_in5 := PS.powerset_k' (interval 5) 2. \n\nEval vm_compute in map P.elements (PP.elements subsets_size2_in5).\n\n\n\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/PowerSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7758145397176025}}
{"text": "(* sem0.v *)\n\n(**** Expressions ****)\n\n(* Integer expressions *)\n\nRequire Export ZArith.\nOpen Scope Z.\n\nInductive expr : Set :=\n| Cte : Z -> expr\n| Plus : expr -> expr -> expr\n| Moins : expr -> expr -> expr\n| Mult : expr -> expr -> expr\n| Div : expr -> expr -> expr.\n\nInductive eval : expr -> Z -> Prop :=\n| ECte : forall c : Z , eval (Cte c) c\n| EPlus : forall (e1 e2 : expr ) (v1 v2 v : Z),\n  eval e1 v1 -> eval e2 v2 -> v = v1 + v2 -> eval (Plus e1 e2) v\n| EMoins : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval e1 v1 -> eval e2 v2 -> v = v1 - v2 -> eval (Moins e1 e2) v\n| EMult : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval e1 v1 -> eval e2 v2 -> v = v1 * v2 -> eval (Mult e1 e2) v\n| EDiv : forall (e1 e2 : expr) (v1 v2 v : Z),\n  eval e1 v1 -> eval e2 v2 -> v = v1 / v2 -> eval (Div e1 e2) v.\n\nLemma eval0 : eval (Plus (Cte 1) (Cte 1)) 2.\nProof.\n  eapply EPlus.\n  apply ECte.\n  apply ECte.\n  auto.\nQed.\n\nLemma eval1 : eval (Mult (Plus (Cte 4) (Cte 2)) (Moins (Cte 9) (Cte 2))) 42.\nProof.\n  eapply EMult.\n  eapply EPlus.\n  apply ECte.\n  apply ECte.\n  auto.\n  eapply EMoins.\n  apply ECte.\n  apply ECte.\n  auto.\n  auto.\nSave.\n\nLtac apply_eval :=\n  repeat\n    eapply EPlus || eapply EMoins || eapply EMult || eapply EDiv ||\n    apply ECte || auto.\n\nLemma eval0b : eval (Plus (Cte 1) (Cte 1)) 2.\nProof.\n  apply_eval.\nSave.\n\nLemma eval1b :\n  eval (Mult (Plus (Cte 4) (Cte 2)) (Moins (Cte 9) (Cte 2))) 42.\nProof.\n  apply_eval.\nSave.\n\nFixpoint f_eval (e : expr) : Z :=\n  match e with\n  | Cte c => c\n  | Plus e1 e2 =>\n    let v1 := f_eval e1 in\n    let v2 := f_eval e2 in\n    v1 + v2\n  | Moins e1 e2 =>\n    let v1 := f_eval e1 in\n    let v2 := f_eval e2 in\n    v1 - v2\n  | Mult e1 e2 =>\n    let v1 := f_eval e1 in\n    let v2 := f_eval e2 in\n    v1 * v2\n  | Div e1 e2 =>\n    let v1 := f_eval e1 in\n    let v2 := f_eval e2 in\n    v1 / v2\n  end.\n\nLemma eval0t : f_eval (Plus (Cte 1) (Cte 1)) = 2.\nProof.\n  simpl; reflexivity.\nSave.\n\nLemma eval1t :\n  f_eval (Mult (Plus (Cte 4) (Cte 2)) (Moins (Cte 9) (Cte 2))) = 42.\nProof.\n  simpl; reflexivity.\nSave.\n\nFunctional Scheme f_eval_ind := Induction for f_eval Sort Prop.\n\nTheorem f_eval_sound :\n  forall (e : expr) (v : Z), (f_eval e) = v -> eval e v.\nProof.\n  intro; functional induction (f_eval e) using f_eval_ind; intros.\n  rewrite H; apply ECte.\n  apply EPlus with (v1 := (f_eval e1)) (v2 := (f_eval e2));\n    [ apply (IHz (f_eval e1)); auto | apply (IHz0 (f_eval e2)); auto | auto ].\n  apply EMoins with (v1 := (f_eval e1)) (v2 := (f_eval e2));\n    [ apply (IHz (f_eval e1)); auto | apply (IHz0 (f_eval e2)); auto | auto ].\n  apply EMult with (v1 := (f_eval e1)) (v2 := (f_eval e2));\n    [ apply (IHz (f_eval e1)); auto | apply (IHz0 (f_eval e2)); auto | auto ].\n  apply EDiv with (v1 := (f_eval e1)) (v2 := (f_eval e2));\n    [ apply (IHz (f_eval e1)); auto | apply (IHz0 (f_eval e2)); auto | auto ].\nSave.\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/sem0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7758145265785412}}
{"text": "(* -- DISCLAIMER: definitions in this file remain to be renamed, \n      e.g. mmin and mmax. *)\n\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Minimum/Maximum w.r.t. an order relation                                *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibReflect LibOperation\n  LibRelation LibOrder LibEpsilon.\nGeneralizable Variables A.\n\n(* This module offers the functions [mmin] and [mmax] which produce\n   the minimum and maximum elements of a non-empty, bounded set. *)\n\n\n(**************************************************************************)\n(* * Lower bound and minimum*)\n\n(* [lower_bound le P x] means that [x] is a lower bound for the\n   set [P] with respect to the ordering [le]. *)\n\nDefinition lower_bound A (le:binary A) (P:A->Prop) (x:A) :=\n  forall y, P y -> le x y.\n\n(* [min_element le P x] means that [x] is a minimal element of\n   [P], i.e., it is both a member of [P] and a lower bound for\n   [P]. *)\n\nDefinition min_element A (le:binary A) (P:A->Prop) (x:A) :=\n  P x /\\ lower_bound le P x.\n\n(* [mmin le P] is a minimal element of [P] with respect to [le],\n   when such an element exists. *)\n\nDefinition mmin `{Inhab A} (le:binary A) (P:A->Prop) :=\n  epsilon (min_element le P).\n\n\n(**************************************************************************)\n(* * Upper bound and maximum *)\n\n(* [upper_bound le P x] means that [x] is a lower bound for the\n   set [P] with respect to the ordering [le]. *)\n\nDefinition upper_bound A (le:binary A) (P:A->Prop) (x:A) :=\n  forall y, P y -> le y x.\n\n(* [max_element le P x] means that [x] is a maximal element of\n   [P], i.e., it is both a member of [P] and a lower bound for\n   [P]. *)\n\nDefinition max_element A (le:binary A) (P:A->Prop) (x:A) :=\n  P x /\\ upper_bound le P x.\n\n(* [mmax le P] is a minimal element of [P] with respect to [le],\n   when such an element exists. *)\n\nDefinition mmax `{Inhab A} (le:binary A) (P:A->Prop) :=\n  epsilon (max_element le P).\n\n\n(**************************************************************************)\n(* * Least upper bound and greatest lower bound *)\n\n(* [lub le P x] means that [x] is a least upper bound\n   for the set [P] with respect to the ordering [le]. *)\n\nDefinition lub A (le:binary A) (P:A->Prop) (x:A) :=\n  min_element le (upper_bound le P) x.\n\n(* [glb le P x] means that [x] is a greatest lower bound\n   for the set [P] with respect to the ordering [le]. *)\n\nDefinition glb A (le:binary A) (P:A->Prop) (x:A) :=\n  max_element le (lower_bound le P) x.\n\n\n(**************************************************************************)\n(* * Connexion between lower and bounds *)\n\nLemma upper_bound_inverse : forall A (le:binary A),\n  upper_bound le = lower_bound (inverse le).\nProof using.\n  extens. intros P x. unfolds lower_bound, upper_bound. iff*.\nQed.\n\nLemma max_element_inverse : forall A (le:binary A) (P:A->Prop) (x:A),\n  max_element le P x = min_element (inverse le) P x.\nProof using.\n  extens. unfold max_element, min_element. rewrite* upper_bound_inverse.\nQed.\n\nLemma mmax_inverse : forall `{Inhab A} (le:binary A) (P:A->Prop),\n  mmax le P = mmin (inverse le) P.\nProof using.\n  intros. applys epsilon_eq. intros x. rewrite* max_element_inverse.\nQed.\n\n\n(**************************************************************************)\n(* * Elimination roperties *)\n\n(* [bounded_has_minimal le] means that, at type [A], it is\n   the case that every non-empty set that admits a lower\n   bound has a minimal element. *)\n\nDefinition bounded_has_minimal A (le:binary A) :=\n  (* Recall that [ex P] means that [P] has an inhabitant; i.e.,\n     it is equivalent to [exists x, P x]. *)\n  forall P,\n  ex P ->\n  ex (lower_bound le P) ->\n  ex (min_element le P).\n\n\n(* If the set [P] is non-empty and admits a lower bound, and if the type\n   [A] is such that every such set has a minimal element, then [P] has a\n   minimal element, and this element is [mmin le P]. *)\n\nLemma mmin_spec : forall `{Inhab A} (le:binary A) (P:A->Prop) m,\n  m = mmin le P ->\n  ex P ->\n  ex (lower_bound le P) ->\n  bounded_has_minimal le ->\n  min_element le P m.\nProof using.\n  intros. subst. unfold mmin. epsilon* m.\nQed.\n\n\n\n(**************************************************************************)\n(* * Application to [nat] *)\n\nFrom TLC Require Import LibNat.\n\n(* The type [nat] enjoys this property. *)\n\nLemma increment_lower_bound_nat : forall (P : nat->Prop) x,\n  lower_bound le P x ->\n  ~ P x ->\n  lower_bound le P (x + 1)%nat.\nProof using.\n  introv hlo ?. intros y ?.\n  destruct (eq_nat_dec x y).\n    { subst. tauto. }\n    { forwards: hlo; eauto. nat_math. }\nQed.\n\nLemma bounded_has_minimal_nat :\n  @bounded_has_minimal nat le.\nProof using.\n  (* Assume a set [P], such that [y] is an inhabitant of [P]\n     and [x] is a lower bound for [P]. *)\n  intros P [ y ? ].\n  (* We reason by induction on the difference [y + 1 - x].\n     Reasoning with [y - x] would work too, but this choice\n     is more elegant, as it makes the base case a contradiction,\n     and avoids a little duplication. *)\n  cut (\n    forall (k x : nat), (y + 1 - x)%nat = k ->\n    lower_bound le P x ->\n    exists z, min_element le P z\n  ). { intros ? [ x ? ]. eauto. }\n  induction k; introv ? hlo.\n  (* Base. *)\n  (* Our hypotheses imply that [x] must be less than or equal to\n     [y]. Because in this case the difference [y + 1 - x] is zero,\n     this leads to a contradiction. *)\n  { false. forwards: hlo; eauto. nat_math. }\n  (* Step. *)\n  (* Eeither [P x] holds, or it does not. If it does, then [x]\n     is the desired minimal element. If it does not, this implies\n     that [x + 1] is a lower bound for [P], and the induction\n     hypothesis can be used. *)\n  destruct (prop_inv (P x)).\n    { exists x. split; eauto. }\n    { eapply (IHk (x + 1)%nat). nat_math. eauto using increment_lower_bound_nat. }\nQed.\n\nHint Resolve bounded_has_minimal_nat : bounded_has_minimal.\n\n(* Furthermore, at type [nat], every set admits a lower bound. *)\n\nLemma admits_lower_bound_nat : forall (P : nat->Prop),\n  ex (lower_bound le P).\nProof using.\n  exists 0%nat. unfold lower_bound. nat_math.\nQed.\n\nHint Resolve admits_lower_bound_nat : admits_lower_bound.\n\n(* At type [nat], every non-empty set that admits an upper bound\n   has a maximal element. *)\n\nLemma bounded_has_maximal_nat :\n  @bounded_has_minimal nat (inverse le).\nProof using.\n  (* Assume a set [P], such that [y] is an inhabitant of [P]\n     and [x] is an upper bound for [P]. *)\n  intros P [ y ? ] [ x h ].\n  assert (y <= x).\n    { forwards: h. eauto. eauto. }\n  (* We apply our previous result to the image of [P] through\n     the function that maps [i] to [x - i]. (We note that this\n     function is its own inverse.) This yields a minimal\n     element [z] of this image. Thus, [x - z] is the desired\n     maximal element of [P]. *)\n  assert (self_inverse: forall i, i <= x -> (x - (x - i))%nat = i).\n    intros. nat_math.\n  forwards [ z [ ? hz ]]: (@bounded_has_minimal_nat (fun i => P (x - i)%nat)).\n    { exists (x - y)%nat. rewrite self_inverse by eauto. eauto. }\n    { eauto using admits_lower_bound_nat. }\n  exists (x - z)%nat.\n  clear dependent y.\n  split; [ assumption | ].\n  intros y ?.\n  assert (y <= x).\n    { forwards: h. eauto. eauto. }\n  forwards: hz (x - y)%nat.\n    { rewrite self_inverse by eauto. eauto. }\n  unfold inverse. nat_math.\nQed.\n\nHint Resolve bounded_has_maximal_nat : bounded_has_minimal.\n\nLemma mmin_spec_nat:\n  forall (P:nat->Prop) m,\n  m = mmin le P ->\n  ex P ->\n  P m /\\ (forall x, P x -> m <= x).\nProof using.\n  introv E Q. applys (@mmin_spec _ _ _ P m E Q).\n  applys admits_lower_bound_nat.\n  applys bounded_has_minimal_nat.\nQed.\n\n\n(**************************************************************************)\n(* * Typeclasses *)\n\n(* [MMin P] is [mmin le P], in a context where the desired\n   ordering can be inferred. *)\n\nDefinition MMin `{Inhab A} `{Le A} := mmin le.\n\n(* [MMax P] is [mmax le P], in a context where the desired\n   ordering can be inferred. *)\n\nDefinition MMax `{Inhab A} `{Le A} := mmax le.\n\n\n\n\n", "meta": {"author": "tilk", "repo": "tlc", "sha": "9a07c989dfc12aba4c5fb02107761c8d7e281996", "save_path": "github-repos/coq/tilk-tlc", "path": "github-repos/coq/tilk-tlc/tlc-9a07c989dfc12aba4c5fb02107761c8d7e281996/src/LibMin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7758065123631386}}
{"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 monday).\n\n(** assertion *)\nExample test_next_weekday :\n  (next_weekday (next_weekday monday)) = tuesday. Admitted.\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 addb (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\nExample test_orb1 : (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2 : (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3 : (orb false 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\nCheck true.\n\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 red => true\n  | primary _ => false  \n  end.\n\n\nCompute (monochrome (primary red)).\n\nModule test_nat.\nInductive nat : Type :=\n  | O : nat\n  | S : nat->nat.\n\nDefinition pred (x : nat) : nat :=\n  match x with\n  |O => O\n  |S x' => x'\n  end.\nEnd test_nat.\n\nCompute (S (S (S O))).\nCheck (S (S(S(S(S O))))).\n\nFixpoint evenb (x:nat) : bool :=\n  match x with\n  | O => true\n  | S n => negb (evenb n)\n  end.\nDefinition oddb (x:nat):bool := negb (evenb x).\n\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb2: oddb 100 = false.\nProof. simpl. reflexivity. Qed.\n\nModule Nat_playground2.\nFixpoint plus (n:nat) (m:nat) : nat :=\n  match n with\n  | 0 => m\n  | S n' => S (plus n' m)\n  end.\n\nCompute (plus 2 3).\n\n\nFixpoint mult (n m:nat):nat :=\n  match n with\n  | 0 => 0\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  | (0, _) => 0\n  | (n, 0) => n\n  | (S n', S m') => minus n' m'\n  end.\nEnd Nat_playground2.\n\nFixpoint exp (base power:nat) : nat :=\n  match power with\n  |0 => 1\n  |S p' =>mult base (exp base p')\n  end.\n\n\nNotation \"x + y\" := (plus x y).\n\nFixpoint beq_nat (x y:nat):bool :=\n  match x with\n  | 0 => match y with\n         | 0 => true\n         | _ => false\n         end\n  | S x' => match y with\n         | 0 => false\n         | S y' => beq_nat x' y'\n         end\n  end.\n\nFixpoint leb (x y:nat) : bool :=\n  match x with\n  | 0 => true\n  | S x' => match y with\n            | 0 => false\n            | S y' => leb x' y'\n            end\n  end.\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\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_1_l : forall n:nat, (1 + n) = S n.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem mult_O_n : forall n:nat, 0 * n = 0.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_id_example : forall n m:nat, \n  n = m -> n+n = m+m.\nProof.\n  intros n m.\n  intros H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\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\n   rewrite -> plus_1_l.\n   rewrite -> H.\n(*   rewrite -> H. *) \n(*   rewrite plus_1_l. *) \n\n  simpl.\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  - simpl. 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 add_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", "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/try.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8824278556326344, "lm_q1q2_score": 0.7757835884573602}}
{"text": "(** * Tutoriel 1 - Prouver avec Coq : Logique propositionnelle *)\n\nRequire Import Bool.\n\n(** ** I. Un premier exemple *)\n\n(** Souvenez-vous de cet exposé sur Coq (et sur K) !\n    Je vous avais expliqué cette preuve : *)\n\nLemma andb_prop : forall b1 b2,\n  andb b1 b2 = true -> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2 H.\n  (* introduit les hypothèses *)\n  split. (* sépare le but en deux sous-buts *)\n  - destruct b1. (* raisonnement par cas *)\n    + reflexivity. (* true = true *)\n    + simpl in H. exact H. (* ce que l'on veut montrer est une hypothèse *)\n  - destruct b2. (* raisonnement par cas *)\n    + reflexivity. (* true = true *)\n    + destruct b1.  (* raisonnement par cas *)\n      * simpl in H. exact H. (* ce que l'on veut montrer est une hypothèse *)\n      * simpl in H. exact H. (* ce que l'on veut montrer est une hypothèse *)\nQed.\n\n(** Cette preuve montre l'utilisation de plusieurs tactiques que nous\n    allons expliquer plus précisément au fur et à mesure des feuilles\n    d'exercices.\n\n    Notez déjà l'utilisation massive des bullets [+] afin d'identifier\n    les points de branchement dans une preuve.\n    Les autres bullets possibles sont [*], [-], [**], [+++], etc.\n    Si une bullet est utilisée pour un sous-but, cette même bullet doit être\n    utilisée pour tous les autres sous-buts du même niveau.\n    Il est également possible d'utiliser les accolades pour délimiter un but. *)\n\n(** Dans cette feuille d'exercices, nous nous intéressons uniquement à des \n    énoncés exprimables dans la logique propositionnelle.\n    Vous n'avez donc besoin que des tactiques suivantes :\n     - intro / intros : introduction de l'implication ->\n     - apply H : pour utiliser un énoncé, une hypothèse\n     - exact H / assumption : la règle nommée \"axiome\"\n     - left et right : pour l'introduction de la disjonction \\/\n     - split : pour l'introduction de la conjonction /\\\n     - destruct H : pour l'élimination de la conjonction /\\, la disjonction \\/,\n                    de [False]\n     - unfold d in H : pour dérouler une définition [d] dans une hypothèse [H].\n*)\n\n(** Dans Coq, le type des propositions est [Prop].\n    Nous déclarons trois objets arbitraires de ce type. *)\n\nVariable P : Prop.\nVariable Q : Prop.\nVariable R : Prop.\n\n(** La requête [Check] peut être utilisée pour vérifier que les expressions ont\n    un sens, mais aussi de voir leur type.\n    Les requêtes suivantes montrent les notations Coq pour la disjonction (\\/),\n    la conjonction (/\\) et l'implication (->). *)\n\nCheck True.\nCheck P \\/ Q.\nCheck False /\\ P.\nCheck P -> Q -> R.\n\n(** ** II. Commutativité de la conjonction.\n\n    Ici, nous déclarons un objectif sans nom, et nous le prouvons.\n    Une preuve est une succession de tactiques, chaque tactique réduisant le\n    premier sous-but à une nouvelle liste (éventuellement vide) de sous-buts. *)\n\nGoal P /\\ Q -> Q /\\ P.\nProof.\n  intro H.\n  destruct H.\n  split.\n   + exact H0.\n   + exact H.\nQed.\n\n(** ** III. Commutativité de la disjonction. *)\n\nGoal P \\/ Q -> Q \\/ P.\nProof.\n  intro H.\n  destruct H.\n   + right. exact H.\n   + left.  exact H.\nQed.\n\n(** ** IV. Distributivité *)\n\n(** *** Exercice 1 - A vous de jouer ! *)\n\nGoal P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\nProof.\n  intro H.\n  destruct H.\n  destruct H0.\n  +left. split. exact H. exact H0.\n  +right. split. exact H. exact H0.\nQed.\n\nGoal (P /\\ Q) \\/ (P /\\ R) -> P /\\ (Q \\/ R).\nProof.\n intro H. destruct H.\n  +split. destruct H. exact H. destruct H. left. exact H0.\n  +split. destruct H. exact H. destruct H. right. exact H0.\nQed.\n\n(** ** V. Une forme de commutativité pour l'implication.\n\n    A noter ici :\n      - l'associativité de l'implication\n      - la variante [intros] de [intro]. *)\n\nGoal (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros H HQ HP.\n  apply H.\n   + exact HP.\n   + exact HQ.\nQed.\n\n(** ** VI. Hypothèses multiples\n\n    Prouvez l'équivalence suivante, en gardant à l'esprit que\n    [P <-> Q] est une notation pour [(P -> Q) /\\ (Q -> P)].\n    Vous pouvez le vérifier en utilisant la tactique [unfold iff]. *)\n\n(** *** Exercice 2 - A vous de jouer ! *)\n\nGoal (P -> Q -> R) <-> (P /\\ Q -> R).\nProof.\n  split. \n  +intros H HQ. apply H. destruct HQ. exact H0. destruct HQ. exact H1.\n  +intros H HP HQ. apply H. split. exact HP. exact HQ.\nQed.\n\n(** Note : En Coq, on écrit généralement [P -> Q -> R] plutôt que [P /\\ Q -> R],\n    puisque la première forme est plus facile à travailler en utilisant les\n    tactiques fournies. *)\n\n(** ** VII. Négation\n\n    La négation [~ P] est une notation pour [P -> False]. *)\n\nGoal P -> ~ ~ P.\nProof.\n  intros H Hn.\n  unfold not in Hn.\n  apply Hn.\n  exact H.\nQed.\n\n(** *** Exercice 3 - A vous de jouer ! *)\n\nGoal (~P /\\ ~Q) -> ~(P \\/ Q).\nProof.\nintros H Hn. destruct H. unfold not in H. unfold not in H0. destruct Hn. \n  +apply H. exact H1.\n  +apply H0. exact H1.\nQed.\n\nLemma not_or : forall (P Q : Prop), ~(P \\/ Q) -> (~P /\\ ~Q).\nProof.\n  intros P Q H. split.\n    + unfold not in H. intro Hn. destruct H. left. exact Hn.\n    + unfold not in H. intro Hn. destruct H. right. exact Hn.\nQed.\n\nGoal (~P \\/ ~Q) -> ~(P /\\ Q).\nProof.\nintros H Hn. destruct H.\n  + unfold not in H. destruct Hn. apply H. exact H0.\n  + unfold not in H. destruct Hn. apply H. exact H1.\nQed.\n\n(** *** Exercice 4 - Avec le modus ponens *)\n\n(** Note : Les quantifications [forall P : Prop] sont\n           des quantifications d'ordre supérieur.\n           Nous quittons donc la logique propositionnelle. *)\n\nLemma modus_ponens : forall P Q : Prop, P -> (P -> Q) -> Q.\nProof.\nintros P Q H0 H1. apply H1. exact H0.\nQed.\n\n\n(** Démontrer à nouveau l'énoncé suivant, mais cette fois en utilisant\n    [modus_ponens]. *)\nLemma impl_not : forall P : Prop, P -> ~ ~ P.\nProof.\nintro P. unfold not. apply modus_ponens.\nQed.\n\n(** Démontrer l'énoncé suivant à partir de [impl_not]. *)\nLemma P_notP_contradiction : forall P : Prop, ~ (P /\\ ~ P).\nProof.\nintro P. unfold not. intro Hn. destruct Hn. apply H0. exact H.\nQed.\n\nLemma not_and : forall P Q : Prop, P \\/ Q -> ~(~ P /\\ ~Q).\nProof.\nintros P Q. intro H. unfold not. intro Hn. destruct Hn. destruct H.\n  + apply H0. exact H.\n  + apply H1. exact H.\nQed.\n\n(** ** VIII.  Raisonnement classique\n\n    Coq implémente une logique constructive.\n    Cela veut dire que la logique interne de Coq n'a pas l'axiome du tiers exclu,\n    ou un équivalent. Il n'est également pas possible de prouver le tiers exclu.\n    Nous verrons les conséquences de ce choix plus tard. *)\n\n(** *** Exercice 5 - Tiers exclu avec Coq *)\n\n(** Pour le raisonnement classique, il faut donc déclarer un axiome.\n    Note : [RAA] signifie pour Reductio Ad Absurdum.\n\n    Ces objectifs de preuve sont un peu plus difficiles. *)\n\nAxiom RAA : forall A:Prop, ~~A -> A.\n\nGoal ~(P /\\ Q) -> (~P \\/ ~Q).\nProof.\nintro H. apply RAA. intro Hn. apply not_or in Hn. destruct Hn. apply RAA in H0. apply RAA in H1. \napply H. split. exact H0. exact H1.\nQed.\n\n(** [LEM] pour Law of Excluded Middle. *)\nLemma LEM : P \\/ ~P.\nProof.\napply RAA. intro H. apply not_or in H. apply H. destruct H. exact H.\nQed.\n\n\nGoal (P -> Q) \\/ (Q -> P).\nProof.\napply RAA. intro H. apply not_or in H. destruct H. \napply H. intro P. apply RAA. intro nQ. \napply H0. intro Q. apply RAA. intro nP. apply nP. exact P.\nQed.\n\n(** Merci à David Baelde et Catherine Dubois. *)\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/TD1_A_prouver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.7757239602844131}}
{"text": "Require Import magma.\nRequire Import ZArith.\nRequire Import Coq.Arith.Mult.\n\nGeneralizable Variables A o.\n\nClass semigroup (A : Type) `{M : magma A o} : Prop := {\n  dot_assoc : forall x y z,\n                o x (o y z) = o (o x y) z\n}.\n\nInstance list_concat_semigroup {A : Type} : semigroup (list A).\nProof.\n  split.\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  rewrite IHx.\n  reflexivity.\nQed.\n\nInstance nat_mult_semigroup : semigroup nat.\nProof.\n  split.\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  rewrite IHx.\n  rewrite mult_plus_distr_r.\n  reflexivity.\nQed.\n\nInstance z_add_semigroup : semigroup Z.\nProof.\n  split.\n  apply Zplus_assoc.\nQed.", "meta": {"author": "relrod", "repo": "coq-playground", "sha": "b6e5538ef9fce09a4169169c78a5bc2da5951e8a", "save_path": "github-repos/coq/relrod-coq-playground", "path": "github-repos/coq/relrod-coq-playground/coq-playground-b6e5538ef9fce09a4169169c78a5bc2da5951e8a/random/semigroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7756453263485065}}
{"text": "Require Import Expression.\nRequire Import Util.\n(**\nDefinition. The set [K] of lambda-kinds is defined\ninductively as follows:\n\n- [kappa] is in [K]\n- If [x] is a variable and [A] is in [E] (i.e.,\n  [A] is a lambda-expression) and [B] is in [K],\n  then [KLam x:A.B] is in [K].\n*)\nInductive kind : Type :=\n | kappa : kind                (* kind constant *)\n | KLam : exp -> kind -> kind. (* lambda kind *)\n\n(**\nTheorem. If [k] is a Lambda-Kind, then either\n[k = kappa] or [k = KLam t k'] where [t] is some [exp]\nand [k'] is another Lambda-Kind.\n\n(As a consequence, it makes sense to talk about the\n\"length\" of a [kind] by counting the number of [KLam]\nconstants that appear.)\n*)\nTheorem canonical_form_of_kinds :\n forall k : kind, k = kappa \\/ (exists (t : exp) (k' : kind), k = KLam t k').\nProof.\n  intuition.\n  induction k.\n  (* Case: k = kappa *)\n  - left. reflexivity.\n  (* Case: k = KLam e k *)\n  - right. eauto .\nQed.", "meta": {"author": "pqnelson", "repo": "ltlc", "sha": "9b322ccb617ccd3ecee8438f4b7d3ec62e20c26b", "save_path": "github-repos/coq/pqnelson-ltlc", "path": "github-repos/coq/pqnelson-ltlc/ltlc-9b322ccb617ccd3ecee8438f4b7d3ec62e20c26b/src/Kind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7756101281996347}}
{"text": "Require Import Coq.Arith.Lt.\n\nInductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint len (l : lst) : nat :=\n    match l with\n    | Nil => 0\n    | Cons x y => 1 + len y\n    end.\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 rev (l1 : lst) : lst :=\n    match l1 with\n    | Nil => Nil\n    | Cons x y => append (rev y) (Cons x Nil)\n    end.\n\nTheorem consLT : forall l1 n, (len l1) < (len (Cons n l1)).\nProof.\n  intros.\n  simpl. apply lt_n_Sn.\nQed.\n\nTheorem appendLT : forall l1 l2 n, (len l1) < (len (append l1 (Cons n l2))).\nProof.\n    intros. induction l1.\n    - simpl. apply lt_0_Sn.\n    - simpl. apply lt_n_S. assumption.\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/inequalities/list_lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7755444227361782}}
{"text": "(** %\\chapter{Functional Programming in Coq} *)\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\nFrom mathcomp\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\nFrom mathcomp\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_plus'' n m := nat_rec (fun _ => nat) m (fun n' m' => m'.+1) n.\n\nEval compute in my_plus'' 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 => \n match n' return P n' -> _ with\n | 0 => fun _ => 1\n | n1.+1 => fun m => my_plus m (n'.+1) \n end 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   | n''.+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\nFrom mathcomp Require 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\nArguments 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\nFrom mathcomp Require 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(**\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\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(**\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\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\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\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\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\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\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", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/lectures/FunProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7754853512461772}}
{"text": "(** * Indu\\u00e7\\u00e3o em Coq *)\n\nAdd LoadPath \"/Users/marcosmonteiro/desktop/coq\".\nRequire Export aula04_provas.\n\n(* ############################################### *)\n(** * Prova por indu\\u00e7\\u00e3o *)\n\n(** Nem sempre \\u00e9 poss\\u00edvel provar somente por:\n    - simplifica\\u00e7\\u00e3o\n    - reescrita\n    - an\\u00e1lise de casos *)\n\n(** Na aula passada, vimos o seguinte teorema *)\n\nPrint plus_O_n.\n\n(** E se quisermos provar n + 0 = n? *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0 .\nProof.\n  intros n.\n  simpl. (* n\\u00e3o simplifica nada *)\n  try reflexivity.\n(** [reflexivity] n\\u00e3o funciona, pois [n]\n    em [n + 0] \\u00e9 um n\\u00famero arbitr\\u00e1rio e\n    n\\u00e3o caso padr\\u00e3o com o [+] *)\n  Print NatPlayground2.plus.\nAbort.\n\n(** An\\u00e1lise de casos tamb\\u00e9m n\\u00e3o ajuda. *)\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    simpl. reflexivity. (* quando [n] \\u00e9 0, funciona *)\n  - (* n = S n' *)\n    simpl.       (* aqui [n] \\u00e9 [S n'],\n                  outro n\\u00famero arbitr\\u00e1rio *)\nAbort.\n\n(** Chamadas sucessivas a [destruct n']\n    tamb\\u00e9m n\\u00e3o ajudaria. Precisamos de indu\\u00e7\\u00e3o. *)\n\nTheorem plus_n_O : forall n:nat, n = n + 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. (* n = 0 *)    reflexivity.\n  - (* n = S n' *) simpl. rewrite <- IHn'.\n                   reflexivity.\nQed.\n\n(** Outro exemplo. *)\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n(** Nota: [induction] move automaticamente\n    vari\\u00e1veis quantificadas para o contexto. *)\n\n(** **** Exercise: (basic_induction)  *)\n(** Prove os seguintes teoremas. Ser\\u00e1 necess\\u00e1rio\n    buscar por resultados previamente provados. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n.\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.\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.\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n\n\n(* ############################################### *)\n(** * Provas aninhadas *)\n\n(** \\u00c9 possivel/aconselh\\u00e1vel quebrar provas maiores\n    em subprovas. Isto pode ser feito a partir de\n    [Lemma], como tamb\\u00e9m a partir de \"sub-teoremas\". *)\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  {\n    simpl. reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(** Outro exemplo: veja que a t\\u00e1tica [rewrite]\n    n\\u00e3o \\u00e9 muito \"inteligente\" sobre onde aplicar\n    a reescrita no objetivo. *)\n\nTheorem plus_rearrange_firsttry :\n  forall n m p q : nat,\n    (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q. Print plus_comm.\n  (* S\\u00f3 queremos trocar (n + m) por (m + n). *)\n  rewrite -> plus_comm.\n  (* Mas  reescrita n\\u00e3o faz o que queremos. *)\nAbort.\n\n(** Veja a pr\\u00f3xima prova. *)\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\n(** Mas tamb\\u00e9m funcionaria s\\u00f3 instanciando\n    [n] e [m], deixando [p] e [q] ligados. *)\nTheorem plus_rearrange' : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m.\n  rewrite -> plus_comm. reflexivity.\nQed.\n\n(** Contudo, a ordem das quantifica\\u00e7\\u00f5es\n    pode vir a ser um problema. *)\n\nTheorem plus_rearrange'' : forall n p q m : 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\n(* ############################################### *)\n(** * Mais exerc\\u00edcios *)\n\n(** **** Exercise: (mult_comm)  *)\n(** Use [assert] para ajudar na prova. N\\u00e3o \\u00e9\n    necess\\u00e1rio usar indu\\u00e7\\u00e3o. *)\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.\n  assert (H: n + m = m + n).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H. reflexivity.\nQed.\n\n(** Agora, prove comutatividade da multiplica\\u00e7\\u00e3o.\n    Talvez seja necess\\u00e1rio provar um teorema auxiliar.\n    O teorema [plus_swap] ser\\u00e1 \\u00fatil. *)\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n. induction m.\n  - simpl. rewrite <- mult_n_O. reflexivity.\n  - rewrite <- mult_n_Sm. simpl. rewrite plus_comm.\n  assert (H: m * n = n * m).\n  { rewrite IHm. reflexivity. }\n  rewrite IHm. reflexivity.\nQed.\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Induction\n  https://softwarefoundations.cis.upenn.edu/lf-current/Induction.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/aula05_inducao.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.7754582835845584}}
{"text": "Parameter A : Prop.\nParameter E : Set.\nParameters x y : E.\nParameters P Q : E -> Prop.\n\n(*Exercie 1*)\n\n(*Q1*)\n\nGoal (forall x : E, (P x) -> (Q x)) -> ((exists y : E, (P y)) -> (exists z : E, (Q z))).\nProof.\n  intros.\n  elim H0.\n  intros.\n  exists x0.\n  apply H.\n  assumption.\nQed.\n\n(*Q2*)\n\nOpen Scope type_scope.\nSection axioms.\nParameter o : Set.\nVariables x y : Set.\n\nAxiom Zero : x + o = x.\nAxiom Sym : x + y = y + x.\n\nEnd axioms. (*Insère les pour tout ds tt les axiomes*)\n\nGoal forall x : Set, o + (x + o) = x.\nProof.\n    intros.\n    rewrite Sym.\n    rewrite Zero.\n    rewrite Zero.\n    reflexivity.\nQed.\n\n(*Exercie 2*)\n\nRequire Import Arith.\nRequire Import Lia.\nRequire Export List.\nOpen Scope list_scope.\nImport ListNotations.\n\n(*Question 1*)\nInductive is_even : nat -> Prop :=\n| is_even_O : is_even 0\n| is_even_pair : forall n : nat, is_even n -> is_even (S (S n)).\n\nInductive even_deer_list : list nat -> Prop :=\n| even_deer_nil :  even_deer_list nil\n| even_deer_one : forall a, is_even a -> even_deer_list [a] \n| even_deer_many : forall a b l, is_even a -> is_even b -> a>=b -> even_deer_list (b::l) -> even_deer_list (a::(b::l)).\n\nGoal even_deer_list [0].\nProof.\n    apply even_deer_one.\n    apply is_even_O.\nQed.\n\nGoal even_deer_list[4;2;0].\nProof.\n    apply even_deer_many.\n    apply is_even_pair.\n    apply is_even_pair.\n    apply is_even_O.\n    apply is_even_pair.\n    apply is_even_O.\n    lia.\n    apply even_deer_many.\n    apply is_even_pair.\n    apply is_even_O.\n    apply is_even_O.\n    lia.\n    apply even_deer_one.\n    apply is_even_O.\nQed.", "meta": {"author": "RomainGallerne", "repo": "VerificationCoq", "sha": "6522181bb71e4c28e2bf4668177e642f70a7a238", "save_path": "github-repos/coq/RomainGallerne-VerificationCoq", "path": "github-repos/coq/RomainGallerne-VerificationCoq/VerificationCoq-6522181bb71e4c28e2bf4668177e642f70a7a238/Anciens Exams/examen2022-session1/Exo1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7754582815454079}}
{"text": "(* Mathematical Logic retake\n   computer exercises\n\nYour Name:\n\nYour Neptun code:\n\nIt is enough to solve any THREE exercises.\n\n*)\n\n\nRequire Import Classical.\n\nParameters P Q R S E U W: Prop.\n\nSection exercise1a.\nHypothesis pr1: P /\\ (Q /\\ R).\nHypothesis pr2: (S /\\ E) /\\ U.\nHypothesis pr3: E -> W.\nGoal (Q /\\ P) /\\ W.\n\n(*Write your solution here.*)\n\nAbort. (*You can replace Abort with Qed\n         when finished with the proof.*)\nEnd exercise1a.\n\nSection exercise1b.\nHypothesis pr1: Q.\nHypothesis pr2: Q->P \\/ R.\nHypothesis pr3: R->S.\nGoal P\\/S.\n\n(*Write your solution here.*)\n\nAbort.\nEnd exercise1b.\n\n\nSection exercise1c.\nHypothesis pr1: S->P.\nHypothesis pr2: Q -> E.\nGoal (P->Q) -> (S->E).\n\n(*Write your solution here.*)\n\nAbort.\nEnd exercise1c.\n\n\nSection exercise1d.\n\nHypothesis pr1: (P \\/ ~S) <-> (R /\\ S ).\nHypothesis pr2: R->S.\nGoal R -> P.\n\n(*Write your solution here.*)\n\nAbort.\nEnd exercise1d.\n\n", "meta": {"author": "bodri5", "repo": "logic22", "sha": "b627d281715c0b947b48d91fc61d01e238720e00", "save_path": "github-repos/coq/bodri5-logic22", "path": "github-repos/coq/bodri5-logic22/logic22-b627d281715c0b947b48d91fc61d01e238720e00/coqideRetake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7754561664365259}}
{"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  f_equal.\n  rewrite mult_succ_r.\n  rewrite plus_assoc.\n  rewrite IHn.\n  ring.\n\nQed.", "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_11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7754478522876779}}
{"text": "Require Import Arith List Permutation Omega.\nRequire Import SortSpec.\n\nRequire Import Tactics.Crush.\nRequire Import Tactics.PermutationSolver.\nRequire Import Tactics.Tactics.\n\nModule SelectSort <: Sorting.\n\n(** Formalizing and proving selection sort based on dependent type\n    and generic recursion. *)\n\n(** The original idea is presented by Andrew Appel in OPLSS14, but his\n    implementation was a little hacky, since the [selsort_aux] function only\n    takes two parameters [l] and [n], but uses the assumption that\n    [length l] = [n]. So I enhance his implementation by using dependent\n    type and generic recursion, where we \"encode\" the proof of the\n    equality in program. *)\n\n(* The proof outline is very similar to quicksort. *)\n\nLemma Forall_Permutation :\n  forall A (l l' : list A) P, Forall P l -> Permutation l l' -> Forall P l'.\nProof.\n  intros. apply Forall_forall.\n  intros. apply Permutation_sym in H0.\n  eapply Permutation_in in H0; eauto.\n  rewrite Forall_forall in H.\n  apply H. apply H0.\nQed.\n\nDefinition AllLe (x : nat) (l : list nat) : Prop := Forall (fun y => x <= y) l.\n\nDefinition lengthOrder (l1 l2 : list nat) :=\n  length l1 < length l2.\n\nLemma lengthOrder_wf' :\n  forall len l, length l <= len -> Acc lengthOrder l.\nProof.\n  unfold lengthOrder; induction len; intros; constructor; intros.\n  + destruct l; crush.\n  + apply IHlen; crush.\nQed.\n\n(** [lengthOrder] is well-founded relation. *)\nTheorem lengthOrder_wf : well_founded lengthOrder.\nProof.\n  Hint Constructors Acc.\n  unfold lengthOrder; intro; eapply lengthOrder_wf'; eauto.\nQed.\n\nFixpoint select (i : nat) (l : list nat) : nat * list nat :=\n  match l with\n  | nil => (i, nil)\n  | h :: t => if 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')\n  end.\n\nLemma select_spec :\n  forall l x h t,\n    select x l = (h, t) -> AllLe h (x :: l) /\\ Permutation (x :: l) (h :: t).\nProof.\n  intro l; induction l; crush.\n  - constructor; auto.\n  - bdestruct (x <? a); crush.\n    destruct (select x l) eqn:Hs; apply IHl in Hs; inversion H; crush.\n    inversion H1; subst; repeat constructor; crush.\n    destruct (select a l) eqn:Hs; apply IHl in Hs; inversion H; crush.\n    inversion H1; subst; repeat constructor; crush.\n  - bdestruct (x <? a); crush.\n    destruct (select x l) eqn:Hs; apply IHl in Hs; inversion H; crush.\n    permutation_solver.\n    destruct (select a l) eqn:Hs; apply IHl in Hs; inversion H; crush.\n    permutation_solver.\nQed.\n\nLemma select_spec' :\n  forall l x h t,\n    select x l = (h, t) -> AllLe h t /\\ Permutation (x :: l) (h :: t).\nProof.\n  intros; pose proof (select_spec l x h t H); crush.\n  unfold AllLe in *.\n  assert (Forall (fun y : nat => h <= y) (h :: t)).\n  { eapply Forall_Permutation; eauto. }\n  inversion H0; auto.\nQed.\n\nLemma select_len :\n  forall l x h t,\n    select x l = (h, t) -> length t = length l.\nProof.\n  intros; pose proof (select_spec l x h t H); crush.\n  apply Permutation_length in H2; crush.\nQed.\n\n(* Use the idea of \"convey pattern\" mentioned by Adam Chlipala in\n   http://coq-club.inria.narkive.com/Jz4riTaq/equations-from-match-case-unifiers-under-refine-tactic *)\nDefinition selsort : list nat -> list nat.\n  refine (Fix lengthOrder_wf (fun _ => list nat)\n    (fun (l : list nat) =>\n      match l return (forall l' : list nat, lengthOrder l' l -> list nat) -> list nat with\n      | nil => fun H => nil\n      | h :: t =>\n          fun (selsort : forall l' : list nat, lengthOrder l' (h :: t) -> list nat) =>\n            fst (select h t) :: selsort (snd (select h t)) _\n      end\n\t  )\n\t); unfold lengthOrder; destruct (select h t) eqn:H; pose proof (select_len t h n l0 H); crush.\nDefined.\n\nTheorem selsort_eq : forall l,\n  selsort l =\n    match l with\n    | nil => nil\n    | h :: t => fst (select h t) :: selsort (snd (select h t))\n    end.\nProof.\n  intros; destruct l;\n  apply (Fix_eq lengthOrder_wf (fun _ => list nat)); auto; intros;\n  destruct x; simpl; repeat f_equal; auto.\nQed.\n\nDefinition sort := selsort.\n\nExample selsort_pi :\n  sort [3; 1; 4; 1; 5; 9; 2; 6; 5; 3; 5] = [1; 1; 2; 3; 3; 4; 5; 5; 5; 6; 9].\nProof.\n  repeat (rewrite selsort_eq; simpl).\n  reflexivity.\nQed.\n\nTheorem sort_algorithm : forall (l : list nat),\n  Sorted (sort l) /\\ Permutation l (sort l).\nProof.\n  unfold sort.\n  intros.\n  apply (well_founded_ind lengthOrder_wf\n    (fun l => Sorted (selsort l) /\\ Permutation l (selsort l))\n  ).\n  intros; rewrite selsort_eq; destruct x; auto.\n  destruct (select n x) eqn:Heq; simpl.\n  pose proof (select_len x n n0 l0 Heq).\n  assert (Hl: lengthOrder l0 (n :: x)). { unfold lengthOrder; crush. }\n  pose proof (H l0 Hl).\n  apply select_spec' in Heq; crush.\n  assert (AllLe n0 (selsort l0)). { eapply Forall_Permutation; eauto. }\n  destruct (selsort l0); auto.\n  constructor; inversion H1; crush.\nQed.\n\nEnd SelectSort.\n", "meta": {"author": "foreverbell", "repo": "verified", "sha": "44bba8f17b8070de304e14bc6fe1580e6890cd43", "save_path": "github-repos/coq/foreverbell-verified", "path": "github-repos/coq/foreverbell-verified/verified-44bba8f17b8070de304e14bc6fe1580e6890cd43/sorting-algorithms/SelectionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7753924284365243}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype seq bigop.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nTheorem sommation n : 2 * sumn (iota 1 n) = n * (n + 1).\nProof.\n  elim: n => [//= | n IHn].\n  (* rewrite -{1 3}[n.+1]addn1. *)\n  rewrite -(addn1 n) iota_add /= sumn_cat !mulnDr IHn /= mulnC -!addnA.\n  congr (_ + _).\n  by rewrite muln0 !muln1 /= !add0n addn0 [RHS]addnA [RHS]addnC [n + 1]addnC.\nQed.\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/somme.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7753737549916995}}
{"text": "From LF Require Export Basics.\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\nProof.\nintros n.\ninduction n as [| n' IHn'].\n- reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\nintros n.\ninduction n as [| n' IHn'].\n- reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\nintros n.\ninduction n as [| n' IHn'].\n- reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\nintros n m.\ninduction n as [| n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\nintros n m.\ninduction n as [| n' IHn'].\n- rewrite <- plus_n_O_firsttry. simpl. reflexivity.\n- rewrite <- plus_n_Sm. rewrite <- IHn'. simpl. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\nintros n m p.\ninduction n as [| n IHn'].\n- simpl. reflexivity.\n- simpl. \nrewrite -> plus_n_Sm.\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.\nintros n m p.\ninduction n as [| n IHn'].\n- simpl. reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n. \n  induction n as [| n IHn']. \n  - simpl. rewrite -> mult_0_r. reflexivity.\n  - induction m as [| m IHm'].\n  -- simpl. rewrite -> mult_0_r. reflexivity. \n  -- simpl. rewrite <- IHn'. ", "meta": {"author": "vrthra", "repo": "coq-practices", "sha": "e5a24171d2c42c57e7aee8a35aa3c6501e359a09", "save_path": "github-repos/coq/vrthra-coq-practices", "path": "github-repos/coq/vrthra-coq-practices/coq-practices-e5a24171d2c42c57e7aee8a35aa3c6501e359a09/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7753450242235383}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Logic.\n\nLemma contrap : forall (A B:Prop),\n  (A -> B) -> (~B -> ~A).\nProof.\n  rewrite /not. (*定義を紐解く*)\n  move=> A B AtoB notB.\n  by move /AtoB.\nQed.\n\n(*B に apply (A->B) をすると A になる*)\n(*A->C に move /(A->B) をすると B->C になる*)\n\nVariables A B C : Prop.\n\nLemma AndOrDistL : (A /\\ C) \\/ (B /\\ C) <-> (A \\/ B) /\\ C.\nProof.\n  rewrite /iff.\n  apply: conj.\n  -case.\n   +case=> AisTrue CisTrue. (*case. move=> _ _*)\n    by apply: conj; [apply: or_introl |]. (*apply conj. apply or_introl. by []*)\n    case=> BisTrue CisTrue.\n    by apply: conj; [apply: or_intror |].\n  -case=> AorBisTrue CisTrue.\n  (*move: AorBisTrue. case. move=> AisTrue. apply or_introl. by [].\n  move=> BisTrue. apply or_intror. by [].*)\n   case: AorBisTrue => [AisTrue | BisTrue].\n   +by apply: or_introl.\n   +by apply: or_intror.\nQed.\n\nInductive ex' (A:Type) (P:A -> Prop) : Prop :=\n  ex_intro' : forall x:A, (P x -> ex' (A:=A) P).\nCheck ex_intro'.\n\nLemma JDM (T:Type) (P:T->Prop):\n  ~(exists (x:T), P x) <-> forall x, ~(P x).\nProof.\n  apply: conj => Hyp. (*apply:conj. move=> Hyp.*)\n  -move=> x0 HPx0.\n  apply: Hyp.\n  (*Print ex.*)\n  by apply: (ex_intro P x0).\n  by case.\nQed.\n\nHypothesis ExMidLaw : forall P : Prop, P \\/ ~P.\n\nLemma notnotEq (P : Prop): ~~P -> P.\nProof.\n  move=> HnotnotP.\n  move: (ExMidLaw (~P)).\n  case.\n  move=> /HnotnotP.\n  by [].\n  move: (ExMidLaw P).\n  case. move=> H1 H2. apply H1.\n  move=> H1.\n  apply HnotnotP in H1.\n  inversion H1.\nQed.\n  \n\nSearch (_ /\\ _).\nFrom mathcomp Require Import ssrnat.\nSearch _ (_ + _ = _).\n\nLocate and_comm.\nLocate conj.\nLocate \"+\".\nLocate \"^\".\nLocate \"/\\\".\n\nSection AxiomTest.\n\nVariables Q : Prop.\nAxiom a_axiom : Q.\nHypothesis a_hypo : Q.\n\nEnd AxiomTest.\n\nCheck a_axiom.\n(*Check AxiomTest.a_hypo.*)\nEnd Logic.\n\nRecord magma : Type := Magma {\n  carrier : Type ;\n  operator : carrier -> carrier -> carrier\n}.\n\nCheck magma.\nCheck Magma.\n\nDefinition prop_and_magma := Magma and.\nPrint prop_and_magma.\nDefinition nat_plus_magma := Magma plus.\nPrint nat_plus_magma.\n\nCheck (operator).\nLemma PropMagmaFalse (x y:carrier prop_and_magma) : \n  (operator x False) -> y.\n\n  Abort.\n\nRecord semigroup : Type := Semigroup {\n  scarrier : magma ;\n  assoc : forall a b c : carrier scarrier,\n    operator a (operator b c)\n    = operator (operator a b) c\n}.\n\nCheck addnA. Check addn.\nLocate \"+\".\nTheorem plus_comm : forall (a b c : carrier nat_plus_magma),\n  (operator a (operator b c))=operator (operator a b) c.\nProof.\n  apply addnA.\nQed.\n\nCanonical nat_plus_magma.\nDefinition nat_plus_semigroup := Semigroup\n  addnA.\n\n(* Definition nat_plus_semigroup := Semigroup\n  plus_comm. *)\n\nNotation \"a ^ b\" := (operator a b).\nCanonical nat_plus_semigroup.\nLemma natPlusExample1 (x y z : carrier nat_plus_magma) : \n  x ^ (y ^ z) = (x ^ y) ^ z.\nProof. by rewrite assoc. Qed.\n\nFrom mathcomp Require Import ssrbool.\n\nCheck addbb. Check ssrfun.self_inverse.\nPrint addbb.\nLocate \"==>\".\n\nFrom mathcomp Require Import eqtype.\n\nPrint eqType.\nAbout eqType.\nLocate \".+4\".\nEval simpl in (muln 3 4).\nCompute (muln 3 4).\nCheck ex_minn.\nCheck pred nat.\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/ssrf03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.775197824067204}}
{"text": "Require Import MyTactics.\nRequire Import LCSyntax.\nRequire Import LCValues.\nRequire Import LCReduction.\nRequire Import STLCDefinition.\n\n(*|\n---------------------------\nRenamings of term variables\n---------------------------\n|*)\n\n(*|\n\nThe typing judgement is preserved by a renaming `xi` that maps\nterm variables to term variables. Note that `xi` need not be\ninjective.\n\n|*)\n\nLemma jt_te_renaming:\n  forall Gamma t U,\n  jt Gamma t U ->\n  forall Gamma' xi,\n  Gamma = xi >>> Gamma' ->\n  jt Gamma' t.[ren xi] U.\nProof.\n  dup 2.\n  {\n    (* A detailed proof, where every case is dealt with explicitly: *)\n    induction 1; intros; subst.\n    (* JTVar *)\n    { asimpl. econstructor. eauto. }\n    (* JTLam *)\n    { asimpl. econstructor. eapply IHjt. autosubst. }\n    (* JTApp *)\n    { asimpl. econstructor. eauto. eauto. }\n    { asimpl. econstructor. }\n    { asimpl. econstructor. eauto. }\n    { asimpl. econstructor. eauto. eauto.\n      eapply IHjt3. autosubst. }\n  }\n  (* A shorter script, where all cases are dealt with uniformly: *)\n  induction 1; intros; subst; asimpl;\n  econstructor; eauto with autosubst.\nQed.\n\n(*|\n\nAs a corollary, `jt` is preserved by the renaming `(+1)`.\n\n|*)\n\nLemma jt_te_renaming_0:\n  forall Gamma t T U,\n  jt Gamma t U ->\n  jt (T .: Gamma) (lift 1 t) U.\nProof.\n  intros. eapply jt_te_renaming. eauto. autosubst.\nQed.\n\n(*|\n-----------------------------------------\nSubstitutions of terms for term variables\n-----------------------------------------\n|*)\n\n(*|\n\nThe typing judgement is extended to substitutions of terms for term\nvariables.\n\nWith respect to a type environment `Gamma`, a substitution `sigma` has\ntype `Delta` if and only if, for every variable `x`, the term `sigma\nx` has type `Delta x`.\n\nThis auxiliary judgement encourages us to think of terms of *total*\nsubstitutions, where *every* variable is replaced by a term. This\nconcept turns out to be easier to understand and manipulate,\nespecially during proofs by induction. Of course one always later\nconsider the special case of a substitution that seems to affect just\none variable, say variable 0. (In reality, such a substitution affects\nall variables, as the variables other than 0 are renumbered.)\n\n|*)\n\nDefinition js Gamma sigma Delta :=\n  forall x : var,\n  jt Gamma (sigma x) (Delta x).\n\n(*|\n\nThe following are basic lemmas about `js`.\n\nThe identity substitution has type `Gamma` in environment `Gamma`.\n\n|*)\n\nLemma js_ids:\n  forall Gamma,\n  js Gamma ids Gamma.\nProof.\n  unfold js. eauto with jt.\nQed.\n\n(*|\n\nThe typing judgement `js` behaves like an infinite list of typing judgements\n`jt`. So, one can prepend one more `jt` judgement in front of it.\n\n|*)\n\nLemma js_cons:\n  forall Gamma t sigma T Delta,\n  jt Gamma t T ->\n  js Gamma sigma Delta ->\n  js Gamma (t .: sigma) (T .: Delta).\nProof.\n  intros. intros [|x]; asimpl; eauto.\nQed.\n\n(*|\n\nThe typing judgement `js` is preserved by the introduction of a new term\nvariable. That is, a typing judgement `js` can be pushed under a\nlambda-abstraction.\n\n|*)\n\nLemma js_up:\n  forall Gamma sigma Delta T,\n  js Gamma sigma Delta ->\n  js (T .: Gamma) (up sigma) (T .: Delta).\nProof.\n  intros. eapply js_cons.\n  { eauto with jt. }\n  { intro x. asimpl. eauto using jt_te_renaming_0. }\nQed.\n\n(*|\n\nThe typing judgement is preserved by a well-typed substitution `sigma`\nof (all) term variables to terms.\n\n|*)\n\nLemma jt_te_substitution:\n  forall Delta t U,\n  jt Delta t U ->\n  forall Gamma sigma,\n  js Gamma sigma Delta ->\n  jt Gamma t.[sigma] U.\nProof.\n  (* A short script, where all cases are dealt with in the same way: *)\n  induction 1; intros; subst; asimpl; eauto using js_up with jt.\n  * econstructor; eauto.\n    - eauto using js_up, IHjt3. \nQed.\n\n(*|\n\nAs a corollary, the typing judgement is preserved by a well-typed\nsubstitution of one term for one variable, namely variable 0.\n\nThis property is exploited in the proof of subject reduction, in the\ncase of beta-reduction.\n\n|*)\n\nLemma jt_te_substitution_0:\n  forall Gamma t1 t2 T U,\n  jt (T .: Gamma) t1 U ->\n  jt Gamma t2 T ->\n  jt Gamma t1.[t2/] U.\nProof.\n(*\n  (* One can do the proof step by step as follows: *)\n  intros. eapply jt_te_substitution.\n  { eauto. }\n  { eapply js_cons.\n    { eauto. }\n    { eapply js_ids. } }\n  (* Of course one can also let Coq find the proof by itself: *)\n  Restart.*) eauto using jt_te_substitution, js_ids, js_cons.\nQed.\n", "meta": {"author": "CatalaLang", "repo": "catala-formalization", "sha": "30edf137f1e250a61b46ab1aef03273d9d33b8a0", "save_path": "github-repos/coq/CatalaLang-catala-formalization", "path": "github-repos/coq/CatalaLang-catala-formalization/catala-formalization-30edf137f1e250a61b46ab1aef03273d9d33b8a0/theories/lcalc/STLCLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7751443740330214}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq. \n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\n\n(* ########################################################### *)\n(** * Propositions *)\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\n\n(** In Coq, the type of things that can (potentially) \n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated \n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P]. \n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.  \nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat \n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.\n*)     \n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining Propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?  \n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other datatype.\n\n    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.  \n\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\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(** 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(** ** \"Introducing\" Conjuctions *)\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  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\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\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\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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  (* 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\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 (Logical \"or\") *)\n\n(** ** Implementing 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(** *** *)\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\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 (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] (advanced) *)\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_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  (* FILL IN HERE *) Admitted.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\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\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(** *** *)\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(* #################################################### *)\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\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\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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (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, 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(** *** Constructive logic *)\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     from evidence for [P]. *) \n  Abort.\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\n(* FILL IN HERE *)\n(** [] *)\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), ~ ~ (P \\/ ~ P).  \nProof.\n  (* FILL IN HERE *) Admitted.\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\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.9230391680088872, "lm_q1q2_score": 0.7751073428689855}}
{"text": "\nLoad ch1_ref.\n\n(* Chapter 1 Exercises *)\nSection Chapter_1_Exercises.\n  (* 1.1. Define Function Composition\n          and show associativity *)\n  Definition fc {A B C} (g : B -> C) (f : A -> B) : A -> C\n    := (* fill in here... *) .\n  Lemma fc_assoc {A B C D : Type}\n    (* fill in full theorem statement here... *)\n  .\n  Proof. trivial. Qed. (* the proof should be trivial *)\n\n\n  (* 1.2 Derive pair_recursion from fst/snd projections\n         and    sigma_recursion from proj1/proj2 *)\n  Definition pair_recursion_alt {A B}\n             (C : Type)\n             (g : A -> B -> C)\n             (p : prod A B)\n    : C\n    := (* fill in here... *) .\n  Definition sigma_recursion_alt {A B}\n             (C : Type)\n             (g : forall x : A, B x -> C)\n             (p : exists x : A, B x )\n    : C\n    := (* fill in here... *) .\n\n  (* 1.3 Derive pair_induction from fst/snd projedtions\n         and    sigma_induction from proj1/proj2 *)\n  Print uniq_prod. (* recall this lemma *)\n  (* use the lemma, but not induction on pairs *)\n  Definition pair_induction {A B}\n             (C : (prod A B) -> Type)\n             (g : forall (x:A) (y:B), (C (pair x y)))\n             (x : prod A B)\n    : C x\n    := (* fill in here... *) .\n  (* here's a similar lemma to use.\n     use it, but not induction on dependent pairs *)\n  Lemma uniq_sigma {A B}\n        (x : exists a:A, B a)\n    : { x.1 ; x.2 } = x.\n  Proof. destruct x. trivial. Qed.\n  Definition sigma_induction {A B}\n             (C : (sigma x : A, B x) -> Type)\n             (g : forall (a : A) (b : B a), C {a;b})\n             (p : sigma x : A, B x )\n    : C p\n    := (* fill in here... *) .\n\n\n  (* 1.4 Derive nat recursion from iteration *)\n  Fixpoint iter (C:Type) (c0:C) (cs:C->C) (n:nat) : C\n    := match n with\n       | O   => c0\n       | S n => cs (iter C c0 cs n)\n       end.\n  Definition nat_recursion_iter (C:Type) :\n    C -> (nat -> C -> C) -> nat -> C\n    := (* fill in here... *) .\n  Lemma Def_Eq_nat_recursion {C:Type} {c0 cs} (n:nat)\n    : (nat_recursion_iter C c0 cs O = c0) *\n      (nat_recursion_iter C c0 cs (S n)\n       =\n       cs n (nat_recursion_iter C c0 cs n)).\n  Proof. \n    (* fill in here... *)\n    (* Hint: I had to use 'assert' to claim a sub-lemma *)\n    (* Hint: you can use the 'pose' tactic to name a subexpression *)\n    (* Hint: the tactics 'fold' and 'unfold' help manage\n             named expressions *)\n  Qed.\n\n  \n  (* 1.5 Bool Sum *)\n  Definition BSum (A B : UU) :=\n    exists x:bool, bool_rect (fun y : bool => UU) A B x.\n  Definition Binl {A B} (a:A) : BSum A B := {true ; a}.\n  Definition Binr {A B} (b:B) : BSum A B := {false ; b}.\n  Definition BSum_induction {A B}\n             (C : BSum A B -> UU)\n             (f : forall a:A, C (Binl a))\n             (g : forall b:B, C (Binr b))\n             (x : BSum A B)\n    : C x\n    := (* fill in here... *) (* use sig_rect *) .\n  Lemma DefEq_BSum_induction {A B} {C f g} :\n    (forall a:A, BSum_induction C f g (Binl a) = f a) *\n    (forall b:B, BSum_induction C f g (Binr b) = g b).\n  Proof. split; trivial. Qed. (* should verify trivially *)\n\n\n  (* 1.6 Bool Prod *)\n  Definition BProd (A B : UU) :=\n    forall x:bool, bool_rect (fun x:bool => UU) A B x.\n  Definition Bpair {A B} (a : A) (b : B) : BProd A B :=\n    fun x:bool => match x with\n      | false => a\n      | true  => b\n    end.\n  Axiom funext :\n    forall (A : Type) (B : A -> Type)\n           (f g : forall x:A, B x),\n    (forall x : A, (f x) = (g x)) -> f = g.\n  Definition Bfst {A B} (x : BProd A B) : A := x true.\n  Definition Bsnd {A B} (x : BProd A B) : B := x false.\n  Definition uniq_BProd {A B} {x : BProd A B}\n    : Bpair (Bfst x) (Bsnd x) = x\n    := (* fill in here... *) .\n  Definition BProd_induction {A B}\n             (C : BProd A B -> Type)\n             (f : forall (a:A) (b:B), C (Bpair a b))\n             (x : BProd A B)\n    : C x\n    := (* fill in here... *) .\n  (* I skipped over this one *)\n  (*Lemma DefEq_BProd_induction {A B} {C g} :\n    forall (a:A) (b:B),\n      BProd_induction C g (Bpair a b) = g a b.*)\n\n  (* 1.7 Alternative Path Induction *)\n    (* skipping *)\n\n  (* 1.8 Multiplication and Exponentiation of nat;\n         (nat, +, 0, *, 1) is a semi-ring *)\n    (* define using nat_recursion *)\n  Definition times (x y : nat) : nat :=\n    (* fill in here... *) .\n  Definition exp   (x y : nat) : nat :=\n    (* fill in here... *) .\n\n  Definition is_a_semiring (A : Type) :=\n    exists\n      (plus        : A -> A -> A)\n      (zero        : A)\n      (times       : A -> A -> A)\n      (one         : A)\n      (* fill in properties here... *)\n      (plus_assoc  : (*...*) )\n      \n    , unit.\n\n  (* this tactic helps name properties in the proof *)\n  Ltac show_exists nm := match goal with\n                         | |- exists (_ : ?T), _ =>\n                           assert T as nm; [ | exists nm]\n                         end.\n\n  Theorem nat_is_a_semiring :\n    is_a_semiring nat.\n  Proof. (* fill in here... *)\n    unfold is_a_semiring.\n    exists plus.\n    exists 0.\n    exists times.\n    exists 1.\n    show_exists plus_assoc.\n  Defined.\n\n  (* 1.9 Define the type family Fin *)\n    (* unsure how to do this *)\n\n\n  (* 1.11 Triple not is constructively just not *)\n  Definition intro_double_not {A:Prop} : A -> ~~A :=\n    (* fill in here... *) .\n  Definition triple_not {A:Prop} : ~~~A -> ~A :=\n    (* fill in here... *) .\n\n  (* 1.12 More Simple Logic Problems as Types *)\n  Definition if_a_then_if_b_then_a {A B}\n    : A -> (B -> A)\n    := (* fill in here... *) .\n  Definition if_not_a_or_not_b_then_not_a_and_b {A B}\n    : ((~A) + (~B))%type -> ~(A * B)%type\n    := (* fill in here... *) .\n\n  (* 1.13 Not Not Excluded Middle *)\n  Definition not_not_excluded_middle {P} :\n    ~~(P + ~P)%type\n    := (* fill in here... *) .\n\n  (* 1.14 *)\n    (* skipping for now; no formal work? *)\n\n  (* 1.15 indiscernability from path induction *)\n    (* see inline earlier *)\n\n  (* 1.16 commutativity of addition of natural numbers *)\n  Lemma nat_commutativity :\n    forall i j : nat, i+j = j+i.\n  Proof. (* fill in here... *)\n  Qed.\nEnd Chapter_1_Exercises.\n\n\n", "meta": {"author": "gilbo", "repo": "hott_reading_group", "sha": "7b78e75c49120aee0ebaa82d504fc7fb895a1965", "save_path": "github-repos/coq/gilbo-hott_reading_group", "path": "github-repos/coq/gilbo-hott_reading_group/hott_reading_group-7b78e75c49120aee0ebaa82d504fc7fb895a1965/ch1_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7751073396845666}}
{"text": "Require Import Bool Arith Coq.Arith.Div2 List.\nRequire Import BellantoniCook.Lib.\n\nNotation bs := (list bool).\n\nDefinition unary (v : bs) := forallb id v.\n\n(** * Boolean interpretation of bitstrings *)\n\nDefinition bs2bool (v:bs) : bool := hd false v.\n\nDefinition bool2bs (b:bool) : bs :=\n  if b then true::nil else nil.\n\nLemma bs_nat2bool_true : forall v,\n  bs2bool v = true -> length v <> 0.\nProof.\n intro v; case v; simpl; auto; intros; discriminate.\nQed.\n\nLemma bs_nat2bool_true_conv : forall v,\n  unary v = true ->\n  length v <> 0 -> bs2bool v = true.\nProof.\n intro v; case v; simpl; intros.\n elim H0; trivial.\n rewrite andb_true_iff in H.\n decompose [and] H; destruct b; trivial.\nQed.\n\nLemma bs_nat2bool_false v :\n  unary v = true ->\n  bs2bool v = false -> length v = 0.\nProof.\n destruct v; simpl; trivial; intros.\n rewrite andb_true_iff in H.\n decompose [and] H; destruct b; discriminate.\nQed.\n\nLemma bs_nat2bool_false_conv v :\n  length v = 0 ->\n  bs2bool v = false.\nProof.\n destruct v; simpl; trivial; intros.\n discriminate.\nQed.\n\n(** * Binary interpretation of bitstrings *)\n\nFixpoint bs2nat (v:bs) : nat :=\n  match v with\n  | nil => 0\n  | false :: v' => 2 * bs2nat v'\n  | true  :: v' => S (2 * bs2nat v')\n  end.\n\nFixpoint succ_bs (v : bs) : bs :=\n  match v with\n    | nil => [true]\n    | false :: v' => true :: v'\n    | true :: v' => false :: succ_bs v'\n  end.\n\nLemma succ_bs_correct v : bs2nat (succ_bs v) = bs2nat v + 1.\nProof.\n induction v; simpl; trivial; case a; simpl; ring [IHv].\nQed.\n\nFixpoint nat2bs (n:nat) : bs :=\n  match n with\n  | 0 => nil\n  | S n' => succ_bs (nat2bs n')\n  end.\n\nLemma bs2nat_nil :\n  bs2nat nil = 0.\nProof. trivial. Qed.\n\nLemma bs2nat_false v :\n  bs2nat (false :: v) = 2 * bs2nat v.\nProof. trivial. Qed.\n\nLemma bs2nat_true v :\n  bs2nat (true :: v) = 1 + 2 * bs2nat v.\nProof. trivial. Qed.\n\nLemma bs2nat_tl : forall v, bs2nat (tl v) = div2 (bs2nat v).\nProof.\n destruct v; simpl; [ trivial | ].\n replace (bs2nat v + (bs2nat v + 0)) with (2 * bs2nat v) by omega.\n case b;[ rewrite div2_double_plus_one | rewrite div2_double]; trivial.\nQed.\n\nLemma bs2nat_nat2bs : forall n, bs2nat (nat2bs n) = n.\nProof.\n induction n as [ | n' IHn]; simpl; auto.\n rewrite succ_bs_correct; ring [IHn].\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/Bitstring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7750625843108148}}
{"text": "(** Calculation of the simple arithmetic language. *)\n\nRequire Import List.\nRequire Import Tactics.\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| PUSH : nat -> Code -> Code\n| ADD : Code -> Code\n| HALT : Code.\n\nFixpoint comp' (x : Expr) (c : Code) : Code :=\n  match x with\n    | Val n => PUSH n c\n    | Add x1 x2 => comp' x1 (comp' x2 (ADD c))\n  end.\n\nDefinition comp (x : Expr) : Code := comp' x HALT.\n\n(** * Virtual Machine *)\n\nDefinition Stack : Set := list nat.\n\nDefinition Conf : Set := prod Code  Stack.\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive VM : Conf -> Conf -> Prop :=\n| vm_push n c s : (PUSH n c , s) ==> (c , n :: s)\n| vm_add c s m n : (ADD c, m :: n :: s) ==> (c, (n + m) :: s)\nwhere \"x ==> y\" := (VM x y).\n\n(** * Calculation *)\n\n(** Boilerplate to import calculation tactics *)\n\nModule VM <: Preorder.\nDefinition Conf := Conf.\nDefinition VM := VM.\nEnd VM.\nModule VMCalc := Calculation VM.\nImport VMCalc.\n\n(** Specification of the compiler *)\n\nTheorem spec x c s : (comp' x c, s) =>> (c , eval x :: s).\n\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  generalize dependent s.\n  induction x;intros.\n\n(** Calculation of the compiler *)\n\n(** - [x = Val n]: *)\n\n  begin\n  (c, n :: s).\n  <== { apply vm_push }\n  (PUSH n c, s).\n  [].\n\n(** - [x = Add x1 x2]: *)\n\n  begin\n  (c, eval x1 + eval x2 :: s).\n  <== { apply vm_add}\n  (ADD c, eval x2 :: eval x1 :: s).\n  <<= { apply IHx2}\n  (comp' x2 (ADD c), eval x1 :: s).\n  <<= { apply IHx1}\n  (comp' x1 (comp' x2 (ADD c)), s).\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 s C : (comp x, s) =>>! C -> C = (HALT , eval x :: s).\nProof.\n  intros.\n  pose (spec x 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'. intro Contra. destruct Contra.\n  inversion H0.\nQed.", "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/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.774975993548977}}
{"text": "(* The addition of the natural numbers is associative *)\nTheorem plus_associates : forall n m p : nat, (n + m) + p = n + (m + p).\nProof.\n  intros n m p.\n  induction n as [| n' IHn].\n    reflexivity.\n\n    simpl.\n    rewrite IHn.\n    reflexivity.\nQed.", "meta": {"author": "DonaldKellett", "repo": "coq-proofs", "sha": "d6852ba3ec39848b4e3a78f6df63ec517c14a7d7", "save_path": "github-repos/coq/DonaldKellett-coq-proofs", "path": "github-repos/coq/DonaldKellett-coq-proofs/coq-proofs-d6852ba3ec39848b4e3a78f6df63ec517c14a7d7/nat/PlusAssociates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7749227601413234}}
{"text": "Structure Group : Type := const_kozos\n{\nA :> Set;\n\nop : A -> A -> A ;\ninv : A -> A ;\nz : A ;\n\nop_assoc : forall a b c, op a (op b c) = op (op a b) c;\nop_z : forall a, op a z = a /\\ op z a = a ;\nop_inverse : forall a, op a (inv a) = z /\\ op (inv a) a = z\n}.\n\nInductive Z6 : Set :=\n|z0 : Z6\n|z1 : Z6\n|z2 : Z6\n|z3 : Z6\n|z4 : Z6\n|z5 : Z6.\n\nDefinition Z6_succ (x:Z6) : Z6 :=\nmatch x with\n| z0 => z1\n| z1 => z2\n| z2 => z3\n| z3 => z4\n| z4 => z5\n| z5 => z0\nend.\n\nDefinition Z6_add (x : Z6) (y : Z6) : Z6 :=\nmatch x with\n|z0 => y\n|z1 => Z6_succ y\n|z2 => Z6_succ (Z6_succ y)\n|z3 => Z6_succ (Z6_succ (Z6_succ y))\n|z4 => Z6_succ (Z6_succ (Z6_succ (Z6_succ y)))\n|z5 => Z6_succ (Z6_succ (Z6_succ (Z6_succ (Z6_succ y))))\nend.\n\nDefinition Z6_inv (x:Z6) : Z6 :=\nmatch x with\n| z0 => z0\n| z1 => z5\n| z2 => z4\n| z3 => z3\n| z4 => z2\n| z5 => z1\nend.\n\n\nTheorem Z6_group : Group.\nProof.\n  apply (const_kozos Z6 Z6_add Z6_inv z0).\n  induction a,b,c ; auto.\n  induction a; auto.\n  induction a; auto.\n  Show Proof.\nDefined.\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/maritsm/group6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7748861292802253}}
{"text": "Require Export P01.\n\n\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\nPrint c_nat.\n\nDefinition c_succ (n : c_nat) : c_nat  :=\n  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\nExample c_succ_1 : c_succ c_zero = c_one.\nProof. reflexivity. Qed.\n\nExample c_succ_2 : c_succ c_one = c_two.\nProof. reflexivity. Qed.\n\nExample c_succ_3 : c_succ c_two = c_three.\nProof. reflexivity. Qed.\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/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7747682339175769}}
{"text": "Theorem DeMorgan1 : forall P Q : Prop, ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\n  intros.\n  intro.\n  destruct H as [ H1 | H2 ].\n  absurd P.\n  assumption.\n  apply H0.\n  absurd Q.\n  assumption.\n  apply H0.\nQed.\n\nTheorem DeMorgan2 : forall P Q : Prop, ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\n  intros.\n  intro.\n  destruct H0 as [ H1 | H2 ].\n  absurd P.\n  apply H.\n  assumption.\n  absurd Q.\n  apply H.\n  assumption.\nQed.\n\nTheorem DeMorgan3 : forall P Q : Prop, ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  intros.\n  split.\n  intro.\n  absurd (P \\/ Q).\n  assumption.\n  left.\n  assumption.\n  intro.\n  absurd (P \\/ Q).\n  assumption.\n  right.\n  assumption.\nQed.\n", "meta": {"author": "s4ichi", "repo": "coq_exercise", "sha": "4fed65c6fffe1e433c6ca67a1e992444fc275b2b", "save_path": "github-repos/coq/s4ichi-coq_exercise", "path": "github-repos/coq/s4ichi-coq_exercise/coq_exercise-4fed65c6fffe1e433c6ca67a1e992444fc275b2b/ex1/4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7747654831492061}}
{"text": "Require Import Arith.\nRequire Import NatMisc.\nRequire Import DecidableEquivalences.\nRequire Import Fin.\nRequire Import Vector.\nRequire Import FinVectorMisc.\nImport VectorNotations.\nRequire Import SigmaMisc.\nRequire Import NotationsMisc.\nRequire Import DPF.\nFrom Equations Require Import Equations.\nSet Equations Transparent.\nUnset Equations WithK.\n\n(** Equivalence relations on {0,1,...,n-1} **)\n\n(* To build a type of all equivalence relations on {0,1,...,n-1}, just\n   describe the process of putting elements into their classes one by one:\n\n   - start with an empty list of classes\n   - assuming {0,1,...,n-1} have been put into classes already, either\n     + the element n is not related to any of the lower elements,\n       thus forming a new class, or\n     + n belongs to one of the existing classes.\n\n   This translates into an inductive type family indexed by the number\n   of elements and the number of classes: *)\n\nInductive ER : nat -> nat -> Type :=\n  | EREmpty             :                      ER O O\n  | ERNew   {n c : nat} :            ER n c -> ER (S n) (S c)\n  | ERPut   {n c : nat} : Fin.t c -> ER n c -> ER (S n) c.\n\nNotation \"#\"        :=  EREmpty.\nNotation \"'+>' e\"   := (ERNew e)   (at level 70).\nNotation \"x '>>' e\" := (ERPut x e) (at level 69, right associativity).\n\n(* Notes\n   - unfortunately, [+>] and [>>]  cannot be used in patterns\n     of \"Equations\", this seems to be a limitation of the library itself\n   - Formerly, to be consistent with the explanation above, we interpreted\n     the largest or last element in Fin.t (S n) as the \"new\" element to be\n     placed into a class. As a consequence, instead of matching against F1 and\n     FS, we had to match against \"last\" and \"previous\", which became incon-\n     venient. So now, in [ERNew e] and [ERPut t e], we interpret e as an \n     equivalence on {FS F1, ...} and F1 as the \"new\" element to be put into\n     a new class or in class t, respectively.\n*)\n\n(* the type of all equivalence relations on {0,...,n-1} becomes: *)\nDefinition EqR (n : nat) : Type := { c : nat & ER n c }.\n\n(* the embedding of [ER n c] into [EqR n] *)\nDefinition erEqr {n c : nat} (e : ER n c) : EqR n := {| c ; e |}.\n\n(* since we have [EqDec] for [nat] and [Fin.t], [EqDec] for [ER] is derivable *)\nDerive EqDec for ER.\n\n(* and thus we also have UIP *)\nEquations uipER {n c : nat} {e1 : ER n c} (eq : e1 = e1) : eq = eq_refl :=\n  uipER eq_refl := eq_refl.\n\n(* derive wellfounded subterm relation for wf recursion *)\nDerive Signature Subterm for ER.\n\n\n(** special equivalence relations **)\n\n(* the identity relation *)\nEquations idER {n : nat} : ER n n :=\n  idER {n:=O}     := #;\n  idER {n:=(S m)} := +> idER.\n\nDefinition idEqr {n : nat} : EqR n := {| n ; idER |}.\n\n(* the all relation *)\nEquations allER {n : nat} : ER (S n) 1 :=\n  allER {n:=O}     := +> # ;\n  allER {n:=(S m)} := F1 >> allER.\n\nEquations allEqr {n : nat} : EqR n := \n  allEqr {n:=0}     := {| 0 ; # |};\n  allEqr {n:=(S _)} := {| 1 ; allER  |}.\n\n\n(** elementary properties of [ER] **)\n\n(* any element of [ER 0 0] is equal to EREmpty *)\nEquations er00Empty (e : ER 0 0) : e = # :=\n  er00Empty # := eq_refl.\n\nHint Rewrite @er00Empty : eqr.\n\n(* if [ER n c] is inhabited, then [c <= n] *)\nEquations erCLeN {n c : nat} (e : ER n c) : c <= n :=\n  erCLeN  #          := @le_n 0;\n  erCLeN (ERNew e)   := leNS (erCLeN e);\n  erCLeN (ERPut t e) := le_S _ _ (erCLeN e).\n\n(* [idER n] is the only element of [ER n n] *)\nEquations ernnIdER {n : nat} (e : ER n n) : e = idER :=\n  ernnIdER {n:=0}      #          := eq_refl;\n  ernnIdER {n:=(S _)} (ERNew e)   := f_equal ERNew (ernnIdER e);\n  ernnIdER {n:=(S _)} (ERPut t e) := False_rect _ (nleSuccDiagL _ (erCLeN e)).\n\nHint Rewrite @ernnIdER : eqr.\n\n(* any equivalence relation with only one class is [allER] *)\nEquations ern1AllER {n : nat} (e : ER (S n) 1) : e = allER :=\n  ern1AllER {n:=0}     (ERNew #)           :=  eq_refl;\n  ern1AllER {n:=(S _)} (ERNew (ERPut t _)) :=! t;\n  ern1AllER {n:=(S _)} (ERPut F1 e)        :=  f_equal (ERPut F1) (ern1AllER e).\n\nHint Rewrite @ern1AllER : eqr.\n\n(** elementary properties of [EqR] **)\n\n(* the only element in [EqR] 0 is [idEqr] ( which is [{| 0 ; # |}]) *)\nEquations eqr0Id (e : EqR 0) : e = idEqr :=\n  eqr0Id {| 0 ; # |} := eq_refl.\n\nHint Rewrite @eqr0Id : eqr.\n\n(** [erMap] **)\n\n(* [erMap e] is the Vector of length [n], with the [e]-class of the [i]th\n   element of [Fin.t n] at the [i]th position. I.e., it is the tabulation\n   of the map sending an element to its equivalence class. *)\nEquations erMap {n c : nat} (e : ER n c) : Vector.t (Fin.t c) n :=\n  erMap  #          := [];\n  erMap (ERNew e)   := F1 :: (map FS (erMap e));\n  erMap (ERPut t e) := t  ::         (erMap e).\n\nNotation \"e '@v' t\" := (Vector.nth (erMap e) t)\n                       (at level 61, right associativity).\n\nHint Rewrite @nthMapLemma : eqr.\nObligation Tactic := repeat (simp eqr || program_simpl).\n\n\n(* computation lemmata for [@v] *)\n\nEquations erMapNewF1 {n c : nat} (e : ER n c) :\n                     (+> e) @v F1 = F1 :=\n  erMapNewF1 _ := _.\nHint Rewrite @erMapNewF1 : eqr.\n\nEquations erMapNewFS {n c : nat} (e : ER n c) (y : Fin.t n) :\n                     (ERNew e) @v (FS y) = FS (e @v y) :=\n  erMapNewFS _ _ := _.\nHint Rewrite @erMapNewFS : eqr.\n\nEquations erMapPutF1 {n c : nat} (e : ER n c) (t : Fin.t c) :\n                     (t >> e) @v F1 = t :=\n  erMapPutF1 _ _ := _.\nHint Rewrite @erMapPutF1 : eqr.\n\nEquations erMapPutFS {n c : nat} (e : ER n c) (t : Fin.t c) (y : Fin.t n) :\n                     (t >> e) @v (FS y) = (e @v y) :=\n  erMapPutFS _ _ _ := _.\nHint Rewrite @erMapPutFS : eqr.\n\n(** properties of [@v] **)\n\n(* erMap of idER is the identity *)\nEquations(noind) idERId {n : nat} (x : Fin.t n) : idER @v x = x :=\n  idERId  F1     := _;\n  idERId (FS x)  with (idERId x) := { | IH := _}.\nNext Obligation. congruence. Defined.\nHint Rewrite @idERId : eqr.\n\n(** erSection **)\n\n(* [erSection e] maps each class to its largest representative\n   (w.r.t. the order F1 < (FS F1) < ... *)\nEquations erSection {n c : nat} (e : ER n c) : Vector.t (Fin.t n) c :=\n  erSection  #          := [];\n  erSection (ERNew e)   := F1 :: (map FS (erSection e));\n  erSection (ERPut _ e) :=       (map FS (erSection e)).\n\nNotation \"e '@^' cl\" := (Vector.nth (erSection e) cl)\n                        (at level 61, right associativity).\n\n(* computation lemmata for [@^] *)\n\nEquations erSectionNewF1 {n c : nat} (e : ER n c) :\n                         (+>e) @^ F1 = F1 :=\n  erSectionNewF1 _ := _.\nHint Rewrite @erSectionNewF1 : eqr.\n\nEquations erSectionNewFS {n c : nat} (e : ER n c) (y : Fin.t c) :\n                         (+>e) @^ (FS y) = FS (e @^ y) :=\n  erSectionNewFS _ _ := _.\nHint Rewrite @erSectionNewFS : eqr.\n\nEquations erSectionPut {n c : nat} (e : ER n c) (t x : Fin.t c) :\n                       (t >> e) @^ x = FS (e @^ x) :=\n  erSectionPut _ _ _ := _.\nHint Rewrite @erSectionPut   : eqr.\n\n\n(* [erSection e] is a section of [erMap e] *)\nLemma erSectionIsSection {n c : nat} (e : ER n c) (y : Fin.t c) :\n                          e @v e @^ y = y.\nProof. induction e; dependent destruction y; simp eqr; congruence.\nDefined.\nHint Rewrite @erSectionIsSection : eqr.\n\n(* thus it is injective *)\n(* we write this as an iff so that simp eqr can use it for rewrites ... *)\n\nLemma erSectionIsInjective {n c : nat} (e : ER n c) (y1 y2 : Fin.t c) :\n                           e @^ y1 = e @^ y2 <-> y1 = y2.\nProof.\n  split; intro eq.\n  + pose (f_equal (fun y => e @v y) eq) as eq'; simpl in eq'; simp eqr in eq'.\n  + congruence.\nDefined.\nHint Rewrite @erSectionIsInjective : eqr.\n\n(* idER @^ also acts the identity. *)\nEquations(noind) idERSId {n : nat} (x : Fin.t n) : idER @^ x = x :=\n  idERSId  F1     := _;\n  idERSId (FS x)  with (idERSId x) := { | IH := _}.\nNext Obligation. congruence. Defined.\nHint Rewrite @idERSId : eqr.\n\n(** [erClassMax] **)\n\n(* [erMap e] followed by [erSection e] maps an element to the largest element\n   in its equivalence class *)\nDefinition erClassMax {n c : nat} (e : ER n c) :\n                       Vector.t (Fin.t n) n :=\n  Vector.map (fun x => e @^ x) (erMap e).\nNotation \"e '@>' x\" := (Vector.nth (erClassMax e) x) \n                       (at level 61, right associativity).\n\n(* [e @>] is [e @v] followed by [e @^] *)\nEquations erClassMaxExpand {n c : nat} (e : ER n c) (x : Fin.t n) :\n                           e @> x = e @^ e @v x :=\n  erClassMaxExpand _ _ := _.\nHint Rewrite @erClassMaxExpand : eqr.\n\n(* [e @>] is idempotent *)\nLemma erClassMaxIsIdempotent {n c : nat} (e : ER n c) (x : Fin.t n) :\n                              e @> e @> x = e @> x.\nProof. simp eqr. Defined.\nHint Rewrite @erClassMaxIsIdempotent : eqr.\n\n(* computation lemmata for [@>] *)\n\nEquations erClassMaxNewF1 {n c : nat} (e : ER n c) :\n                          (+>e) @> F1 = F1 :=\n  erClassMaxNewF1 _ := _.\nHint Rewrite @erClassMaxNewF1 : eqr.\n\nEquations erClassMaxNewFS {n c : nat} (e : ER n c) (y : Fin.t n) :\n                          (+>e) @> (FS y) = FS ( e @> y ) :=\n  erClassMaxNewFS _ _ := _.\nHint Rewrite @erClassMaxNewFS : eqr.\n\nEquations erClassMaxPutF1 {n c : nat} (e : ER n c) (t : Fin.t c) :\n                          (t >> e) @> F1 = FS (e @^ t) :=\n  erClassMaxPutF1 _ _ := _.\nHint Rewrite @erClassMaxPutF1 : eqr.\n\nEquations erClassMaxPutFS {n c : nat} (e : ER n c) (t : Fin.t c) (x : Fin.t n) :\n                          (t >> e) @> (FS x) = FS (e @> x) :=\n  erClassMaxPutFS _ _ _ := _.\nHint Rewrite @erClassMaxPutFS : eqr.\n\n\n(** [eqrClassMax] **)\n\n(* the result type of [erClassMax e] is not dependent on c, so we can define *)\nDefinition eqrClassMax {n : nat} (e : EqR n) :\n                        Vector.t (Fin.t n) n :=\n  erClassMax (e.2).\nNotation \"e '@@' x\" := (Vector.nth (eqrClassMax e) x)\n                       (at level 61, right associativity).\n\n(* trivial computation lemma for [@@] *)\nEquations eqrClassMaxCompute {n c : nat} (e : ER n c) (x : Fin.t n) :\n                             {| c ; e |} @@ x = e @> x :=\n  eqrClassMaxCompute _ _ := _.\nHint Rewrite @eqrClassMaxCompute : eqr.\n\n(* [e @@] is idempotent *)\nEquations eqrClassMaxIsIdempotent {n : nat} (e : EqR n) (x : Fin.t n) :\n                                  e @@ e @@ x = e @@ x :=\n  eqrClassMaxIsIdempotent _ _ := _.\nHint Rewrite @eqrClassMaxIsIdempotent : eqr.\n\n(* Restrict equivalence on [n+1] elements to the first [n] elements\n   Just take the constructor argument of the 2nd component and repack it.\n   Needed only to shorten statements. *)\n\nEquations eqrShrink {n : nat} (e : EqR (S n)) : EqR n :=\n  eqrShrink {|_ ;   +> e |} := {|_ ; e |};\n  eqrShrink {|_ ; _ >> e |} := {|_ ; e |}.\n\n(* on the higher elements, [eqrShrink e] does \"essentially the same\" as [e] *)\n\nLemma eqrShrinkClassMax {n : nat} (e : EqR (S n)) (x : Fin.t n) :\n                        FS ((eqrShrink e) @@ x) = e @@ (FS x).\nProof.\n  destruct e as [k e]; dependent induction e; repeat (program_simpl || simp eqr).\nDefined.\nHint Rewrite @eqrShrinkClassMax : eqr.\n\n(* lift the constructors of ER to Eqr *)\n\nEquations eqrNew {n : nat} (e : EqR n) : EqR (S n) :=\n  eqrNew {|_; e |} := {|_; +> e |}.\n\nEquations eqrPut {n : nat} (e : EqR n) (x : Fin.t e.1) : EqR (S n) :=\n  eqrPut {|_; e |} x := {|_; x >> e |}.\n\n(* useful in cases with [n : nat] and [x : Fin.t n] among the hypotheses *)\nLtac handleFinCase0 n := try (destruct n; [> apply Fin.case0; trivial | idtac]).\n\n(* computation rules for @@ *)\n\nEquations eqrMapNewF1 {n : nat} (e : EqR n) :\n                      (eqrNew e) @@ F1 = F1 :=\n  eqrMapNewF1 e := _.\nNext Obligation. dependent destruction e; simp eqr. Defined.\nHint Rewrite @eqrMapNewF1 : eqr.\n\nEquations eqrMapNewFS {n : nat} (e : EqR n) (y : Fin.t n) :\n                      (eqrNew e) @@ (FS y) = FS (e @@ y) :=\n  eqrMapNewFS e y := _.\nNext Obligation. handleFinCase0 n. destruct e; simp eqr. Defined.\nHint Rewrite @eqrMapNewFS : eqr.\n\nLemma eqrNewShrink {n : nat} (e : EqR n) : eqrShrink (eqrNew e) = e.\nProof. destruct e; program_simpl. Defined.\nHint Rewrite @eqrNewShrink : eqr.\n\nLemma eqrPutShrink {n : nat} (e : EqR n) (x : Fin.t e.1) : \n                   eqrShrink (eqrPut e x) = e.\nProof. destruct e; program_simpl. Defined.\nHint Rewrite @eqrNewShrink : eqr.\n\n\n\n(* insert here eqrShrink and computation rules using it...\n   also [idEqr @@] = identity function  *)\n\n\n\n\n(** the decidable equivalence relation on [Fin.t n] defined by [e : EqR n] *)\n\n(* The relation on [Fin.t n] defined by [e : EqR] is just the kernel of\n   [eqrClassMax], i.e. the pullback of equality along [eqrClassMax].\n   It is a decidable equivalence on [Fin.t n], as equality has this property\n   and pullback preserves it.  *)\n\nDefinition eqrToDecEq {n : nat} (e : EqR n) :\n                       DecidableEquivalence (Fin.t n) :=\n  pullbackDecidableEquivalence (fun x => e @@ x) eqFinDecidableEquivalence.\nNotation \"x '~(' e ')~' y\" := (relationOfDecidableEquivalence (eqrToDecEq e) x y)\n                              (at level 62).\n\n(* needed to shorten proofs *)\n\nLemma eqrToDecEqCompute {n : nat} (e : EqR n) (x y : Fin.t n) : \n                        x ~(e)~ y  <-> e @@ x = e @@ y.\nProof. unfold eqrToDecEq; simpl; unfold pullbackRelation; reflexivity.\nDefined.\nHint Rewrite @eqrToDecEqCompute : eqr.\n\n(** composition **)\n\n(* this operation is called composition since it corresponds to the\n   composition of classMaps (see below). It is NOT what one usually \n   calls the composition of relations, namely x ~(r ○ s)~ y  <=> \n   ∃ z. x ~(r)~ z ∧ z ~(s)~ y  *)\n\nEquations erCompose {n c d: nat} (e1 : ER n c) (e2 : ER c d) : ER n d :=\n  erCompose  #             #            :=  #;\n  erCompose (ERNew e1)    (ERNew e2)    :=            +> (erCompose e1 e2);\n  erCompose (ERNew e1)    (ERPut t2 e2) :=         t2 >> (erCompose e1 e2);\n  erCompose (ERPut t1 e1)  e2           := (e2 @v t1) >> (erCompose e1 e2).\nNotation  \"e1 '**' e2\" := (@erCompose _ _ _ e1 e2)\n                          (at level 60, right associativity).\n\n\n(** properties of [erCompose] **)\n\n(* [idER] is left unit for [**] *)\nEquations idERLeft1 {n c : nat} (e : ER n c) : idER ** e = e :=\n  idERLeft1   #          := eq_refl;\n  idERLeft1  (ERNew e)   := f_equal  ERNew    (idERLeft1 e);\n  idERLeft1  (ERPut t e) := f_equal (ERPut t) (idERLeft1 e).\nHint Rewrite @idERLeft1 : eqr.\n\n(* [idER] is right unit for [**] *)\nEquations idERRight1 {n c : nat} (e : ER n c) : e ** idER = e :=\nidERRight1  #          :=  eq_refl;\nidERRight1 (ERNew e)   := (f_equal ERNew (idERRight1 e));\nidERRight1 (ERPut t e) :=\n  (t >> e) ** idER\n     ={ erCompose_equation_4 _ _ _ _ _ _ }=\n  (idER @@ t) >> (e ** idER)\n     ={ f_equal (fun s => s >> (e ** idER)) (idERId t) }=\n  t >> (e ** idER)\n     ={ f_equal (ERPut t) (idERRight1 e ) }=\n  (t >> e) QED.\nHint Rewrite @idERRight1 : eqr.\n\n\n(* postcomposing with [allER] maps to [allER] *)\nDefinition allERRight {n d : nat} (e : ER (S n) (S d)) : e ** allER = allER.\nProof. apply ern1AllER. Defined.\nHint Rewrite @allERRight : eqr.\n\n\nEquations(noind) erMapCompose {n m l : nat} (e1 : ER n m) (e2 : ER m l) \n                              (x : Fin.t n) :\n                              (e1 ** e2) @v x = e2 @v (e1 @v x) :=\n  erMapCompose {n:=0}      #            #             x          :=! x;\n  erMapCompose {n:=(S _)} (ERNew e1)   (ERNew e2)     F1         := eq_refl;\n  erMapCompose {n:=(S _)} (ERNew e1)   (ERNew e2)    (FS y)\n                             with erMapCompose e1 e2 y := { | IH := _};\n  erMapCompose {n:=(S _)} (ERNew e1)   (ERPut t2 e2)  F1         := _;\n  erMapCompose {n:=(S _)} (ERNew e1)   (ERPut t2 e2) (FS y)\n                             with erMapCompose e1 e2 y := { | IH := _};\n  erMapCompose {n:=(S _)} (ERPut t1 e1) e2            F1         := _;\n  erMapCompose {n:=(S _)} (ERPut t1 e1) e2           (FS y)\n                             with erMapCompose e1 e2 y := { | IH := _}.\n(* above typechecks, but takes between 2 and 3 minutes on 1.9GHz I3 *)\nHint Rewrite @erMapCompose : eqr.\n\n\n(* [erSection] of [e1 ** e2] is composition of [erSection]s.\n   Note the order! Typechecks, but takes 1 to 2 minutes on 1.9GHz I3... *)\nEquations(noind) erSectionCompose {n m l : nat} (e1 : ER n m) (e2 : ER m l)\n                                  (x : Fin.t l) :\n                                  (e1 ** e2) @^ x = e1 @^ (e2 @^ x) :=\n  erSectionCompose {n:=0}      #           #            x     :=! x;\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERNew e2)    F1    := eq_refl;\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERNew e2)   (FS y)\n                                with erSectionCompose e1 e2 y := { | IH := _ };\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERPut _ e2)  x\n                                with erSectionCompose e1 e2 x := { | IH := _ };\n  erSectionCompose {n:=(S _)} (ERPut _ e1) e2           x\n                                with erSectionCompose e1 e2 x := { | IH := _ }.\nHint Rewrite @erSectionCompose : eqr.\n\n(* giving explicit right hand sides doesn't help to speed things up ...\nEquations(noind) erSectionCompose {n m l : nat} (e1 : ER n m) (e2 : ER m l)\n                                  (x : Fin.t l) :\n                                  (e1 ** e2) @^ x = e1 @^ (e2 @^ x) :=\n  erSectionCompose {n:=0}      #           #            x     :=! x;\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERNew e2)    F1    := eq_refl;\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERNew e2)   (FS y)\n                                with erSectionCompose e1 e2 y := {\n     | IH := (+>e1 ** +>e2) @^ (FS y)\n             ={ f_equal (fun e => e @^ (FS y))\n                        (erCompose_equation_2 _ _ _ e1 e2) }=\n             (+> (e1 ** e2)) @^ (FS y)\n             ={ erSectionNewFS (e1 ** e2) y }=\n             FS ((e1 ** e2) @^ y)\n             ={ f_equal FS IH }=\n             FS (e1 @^ (e2 @^ y))\n             ={ eq_sym (erSectionNewFS e1 (e2 @^ y)) }=\n             (+>e1) @^ (FS (e2 @^ y))\n             ={ f_equal (fun x => (+>e1) @^ x)\n                        (eq_sym (erSectionNewFS e2 y)) }=\n             (+>e1) @^ (+>e2) @^ (FS y) QED                      };\n  erSectionCompose {n:=(S _)} (ERNew e1)  (ERPut t e2)  x\n                                with erSectionCompose e1 e2 x := {\n     | IH := (+>e1 ** t>>e2) @^ x\n             ={ f_equal (fun e => e @^ x)\n                        (erCompose_equation_3 _ _ _ e1 t e2) }=\n             (t >> (e1 ** e2)) @^ x\n             ={ erSectionPut (e1 ** e2) t x }=\n             FS ((e1 ** e2) @^ x)\n             ={ f_equal FS IH }=\n             FS (e1 @^ (e2 @^ x))\n             ={ eq_sym (erSectionNewFS e1 (e2 @^ x)) }=\n             (+>e1) @^ (FS (e2 @^ x))\n             ={ f_equal (fun x => (+>e1) @^ x)\n                        (eq_sym (erSectionPut e2 t x)) }=\n             (+>e1) @^ (t>>e2) @^ x  QED                         };\n  erSectionCompose {n:=(S _)} (ERPut t e1) e2           x\n                                with erSectionCompose e1 e2 x := {\n     | IH := (t>>e1 ** e2) @^ x\n             ={ f_equal (fun e => e @^ x)\n                        (erCompose_equation_4 _ _ _ t e1 e2) }=\n             ((e2 @v t) >> (e1 ** e2)) @^ x\n             ={ erSectionPut (e1 ** e2) (e2 @v t) x }=\n             FS ((e1 ** e2) @^ x)\n             ={ f_equal FS IH }=\n             FS (e1 @^ (e2 @^ x))\n             ={ eq_sym (erSectionPut e1 t (e2 @^ x)) }=\n             (t>>e1) @^ e2 @^ x  QED                             }.\n*)\n\n\n(* [**] is associative *)\n\nLemma erComposeAssociative {n m l k : nat}\n                           (e1 : ER n m) (e2 : ER m l) (e3 : ER l k) :\n                           (e1 ** e2) ** e3 = e1 ** e2 ** e3.\nProof.\n  funelim (e1 ** e2).\n  - funelim (# ** e3); reflexivity.\n  - funelim ((+> (e ** e0)) ** e3); simp eqr; rewrite H1; trivial.\n  - repeat (simp eqr || program_simpl || intuition || rewrite H).\n  - repeat (simp eqr || program_simpl || intuition || rewrite H).\nDefined.\n\n(** containment **)\n\n(* [f] is contained in [e]\n   <=> any equivalence class of [f] is contained in an equivalence class of [e],\n   <=> the classes of [e] are unions of certain classes of [f],\n   <=> there is an equivalence [d] on the set of classes of [f] s.t. the union \n       of all classes of [f] in a class of [d] is a class of e ( ;-) ),\n   <=> there exists [d] such that  [f ** d = e]  *)\n\nDefinition erContains {n m l : nat} (f: ER n m) (e: ER n l) : Type :=\n                      { d : ER m l & f ** d = e }.\nNotation \"f '[='  e\" := (erContains f e) (at level 50).\n\nDefinition eqrContains {n : nat} (f e : EqR n) : Type := f.2 [= e.2.\nNotation \"e 'C='  f\" := (eqrContains e f) (at level 50).\n\n(** properties of [[=] and [C=] **)\n\n(* [[=] is Reflexive and Transitive *)\nDefinition erContainsReflexive {n m : nat} (e : ER n m) : \n                               e [= e :=\n  {| idER ; (idERRight1 e) |}.\n\nDefinition erContainsTransitive {n c1 c2 c3 : nat} (e1 : ER n c1) \n                                (e2 : ER n c2) (e3 : ER n c3) :\n                                (e1 [= e2) -> (e2 [= e3) -> (e1 [= e3).\nProof.\n  intros [d1 eq1] [d2 eq2].\n  exists (d1 ** d2).\n  rewrite <- erComposeAssociative.\n  program_simpl.\nDefined.\n\n(* [C=]  is a partial order i.e. reflexive, transitive and antisymmetric *)\nDefinition eqrContainsReflexive {n : nat} (e : EqR n) :\n                                 e C= e := erContainsReflexive e.2.\n\nDefinition eqrContainsTransitive {n : nat} (e1 e2 e3 : EqR n) :\n                                 (e1 C= e2) -> (e2 C= e3) -> (e1 C= e3).\nProof. apply erContainsTransitive. Defined.\n\nLemma eqrContainsAntiSymmetric {n : nat} (e1 e2 : EqR n) :\n                               (e1 C= e2) -> (e2 C= e1) -> e1 = e2.\nProof.\n  destruct e1 as [c1 e1]; destruct e2 as [c2 e2].\n  intros [d1 eq1] [d2 eq2]; simpl in *.\n  destruct (leAntiSymmetric _ _ (conj (erCLeN d2) (erCLeN d1))).\n  rewrite (ernnIdER d1) in eq1.\n  simp eqr in eq1; program_simpl.\nDefined.\n\n(* [idEqr] is minimal for [C=] *)\nEquations idEqrMin {n : nat} (e : EqR n) : idEqr C= e :=\n  idEqrMin {|_; e |} := {| e; idERLeft1 e |}.\n\n(* [allEqr] is maximal for [C=] *)\nEquations allEqrMax {n : nat} (e : EqR n) : e C= allEqr :=\n  allEqrMax {n:=0}     {| 0 ; # |}      := eqrContainsReflexive _;\n  allEqrMax {n:=(S _)} {| 0 ; t >> _ |} :=! t;\n  allEqrMax {n:=(S _)} {|(S _); e |}    := {| allER ; allERRight e |}.\n\n\n(** [eqrToDecEq] preserves and reflects containment **)\n\n(* rewrite to expand definition of [c=] ... just to shorten proofs *)\nLemma eqrToDecEqContainsRewrite {n : nat} (e f : EqR n) :\n                  (eqrToDecEq e) c= (eqrToDecEq f) <->\n                  (forall x y : Fin.t n, e @@ x = e @@ y -> f @@ x = f @@ y).\nProof.\n  unfold \"c=\", Relations_1.contains, eqrToDecEq, pullbackDecidableEquivalence,\n         pullbackRelation; reflexivity.\nDefined.\n\nHint Rewrite @eqrToDecEqContainsRewrite :eqr .\n\n(* containment is preserved by [eqrToDecEq] *)\nLemma eqrToDecEqPreservesContains {n : nat} (e f : EqR n) (p : e C= f) :\n                                  (eqrToDecEq e) c= (eqrToDecEq f).\nProof.\n  destruct e as [c e], f as [d f], p as [g eq]; simpl in *; simp eqr.\n  intros x y; simp eqr; intro.\n  repeat rewrite <- eq; simp eqr; program_simpl.\nDefined.\n\n(* to show that [eqrToDec] also reflects containment, we first show that\n   [(eqrToDecEq e) c= (eqrToDecEq f)]  is equivalent to have\n   [(e @@ x) ~(f)~ x]  for any [x]  *)\n\nDefinition eqrMaxMapCondition {n : nat} (e f : EqR n) : Prop :=\n  forall (x : Fin.t n), (e @@ x) ~(f)~ x.\n\nLemma eqrMaxMapConditionIffEqrToDecEqContains\n                  {n : nat} (e f : EqR n) :\n                  eqrMaxMapCondition e f <-> (eqrToDecEq e) c= (eqrToDecEq f).\nProof.\n  destruct e as [k e], f as [l f]; split; simp eqr.\n  + congruence.\n  + unfold eqrMaxMapCondition; intros ec x.\n    apply ec.\n    apply eqrClassMaxIsIdempotent.\nDefined.\n\n(* If [e C= f], [eqrMaxMapCondition e f] holds *)\nLemma eqrContainsToEqrMaxMapCondition\n                          {n : nat} (e f : EqR n) (cont: e C= f) :\n                          eqrMaxMapCondition e f.\nProof.\n  intro x; handleFinCase0 n.\n  simp eqr.\n  destruct e as [c1 e], f as [c3 f], cont as [c eq]; simpl in *.\n  rewrite <- eq.\n  simp eqr.\nDefined.\n\n(* that [eqrMaxMapCondition e f] implies [e C= f] is a little more difficult *)\n\nLemma eqrShrinkPreservesEqrMaxMapCondition\n                        {n : nat} (e f : EqR (S n))\n                        (emms : eqrMaxMapCondition e f) :\n                        eqrMaxMapCondition (eqrShrink e) (eqrShrink f).\nProof.\n  unfold eqrMaxMapCondition, eqrToDecEq in *; simpl in *;\n  unfold pullbackRelation in *.\n  intro x.\n  apply FS_inj.\n  repeat rewrite eqrShrinkClassMax.\n  apply emms.\nDefined.\n\n(* [eqrShrink] preserves containment *)\n\nEquations eqrShrinkPreservesContains {n : nat} (e f : EqR (S n)) (p : e C= f) :\n                                     (eqrShrink e) C= (eqrShrink f) :=\n  eqrShrinkPreservesContains {|_;+>_|}  {|_;+>_ |} {|+>d ;eq|} := {|d;sigmaNat2 _|};\n  eqrShrinkPreservesContains {|_;+>_|}  {|_;+>_ |} {|_>>_;eq|} :=! eq;\n  eqrShrinkPreservesContains {|_;+>_|}  {|_;t>>_|} {|+>_ ;eq|} :=! eq;\n  eqrShrinkPreservesContains {|_;+>_|}  {|_;t>>_|} {|_>>d;eq|} := {|d;sigmaNat2 _|};\n  eqrShrinkPreservesContains {|_;_>>_|} {|_;+>_ |} {|_   ;eq|} :=! eq;\n  eqrShrinkPreservesContains {|_;_>>_|} {|_;_>>_|} {|d   ;eq|} := {|d;sigmaNat2 _|}.\n\n(* to prove [e C= f], it is enough to have containment of the shrinks and\n   [eqrMaxMapCondition e f F1]  *)\n\nObligation Tactic := idtac.\n\nEquations(noind) eqrBuildContains {n : nat} (e f :  EqR (S n))\n                           (shrinkCond : (eqrShrink e) C= (eqrShrink f))\n                           (f1Cond     : f @@ e @@ F1 = f @@ F1) :\n                            e C= f :=\n  eqrBuildContains {|_; +>e   |} {|_; +>f   |} {|c; eq |} _   := {|+>c   ;_|};\n  eqrBuildContains {|_; +>e   |} {|_; t2>>f |} {|c; eq |} _   := {|t2>>c ;_|};\n  eqrBuildContains {|_; t1>>e |} {|_; +>f   |} shrinkC    f1C :=! f1C;\n  eqrBuildContains {|_; t1>>e |} {|_; t2>>f |} {|c; eq |} f1C := {|c ;_|}.\nNext Obligation.\n  repeat (program_simpl || simp eqr).\nDefined.\nNext Obligation.\n  repeat (program_simpl || simp eqr).\nDefined.\nNext Obligation.\n  intros.\n  handleFinCase0 wildcard1.\n  handleFinCase0 wildcard4.\n  simp eqr in *; simpl in *.\n  apply FS_inj in f1C.\n  rewrite <- eq in f1C.\n  simp eqr in f1C.\n  program_simpl.\nDefined.\nNext Obligation.\n  intros.\n  handleFinCase0 c0.\n  simp eqr in f1Cond.\n  inversion f1Cond.\nDefined.\nNext Obligation.\n  intros.\n  handleFinCase0 c0.\n  apply False_rect.\n  simp eqr in f1Cond.\n  inversion f1Cond.\nDefined.\n\n\n(* thus, [erqMaxMapCondition e f] implies [e C= f] *)\nLemma eqrContainsFromEqrMaxMapCondition {n : nat} (e f : EqR n)\n                                        (emmc : eqrMaxMapCondition e f) :\n                                         e C= f.\nProof.\n  induction n.\n  - rewrite (eqr0Id e). apply idEqrMin.\n  - apply eqrBuildContains.\n    + apply IHn.\n      apply eqrShrinkPreservesEqrMaxMapCondition.\n      exact emmc.\n    + apply emmc.\nDefined.\n\n(* and we have that [eqrToDecEq] reflects containment *)\n\nLemma eqrToDecEqReflectsContains {n : nat} (e f : EqR n)\n                                 (etdeContains : (eqrToDecEq e) c= (eqrToDecEq f)) :\n                                 e C= f.\nProof.\n  apply eqrContainsFromEqrMaxMapCondition.\n  rewrite eqrMaxMapConditionIffEqrToDecEqContains.\n  exact etdeContains.\nDefined.\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/EqR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7747654738092294}}
{"text": "Require Import VectorStates.\n\n(** Facts about permutations and matrices that implement them. *)\n\nLocal Open Scope nat_scope.\n\n(** * Permutations on (0,...,n-1) *)\nDefinition permutation (n : nat) (f : nat -> nat) :=\n  exists g, forall x, x < n -> (f x < n /\\ g x < n /\\ g (f x) = x /\\ f (g x) = x).\n\nLemma permutation_is_injective : forall n f,\n  permutation n f -> \n  forall x y, x < n -> y < n -> f x = f y -> x = y.\nProof.\n  intros n f [g Hbij] x y Hx Hy H.\n  destruct (Hbij x Hx) as [_ [_ [H0 _]]].\n  destruct (Hbij y Hy) as [_ [_ [H1 _]]].\n  rewrite <- H0. \n  rewrite <- H1.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma permutation_compose : forall n f g,\n  permutation n f ->\n  permutation n g ->\n  permutation n (f ∘ g)%prg.\nProof.\n  intros n f g [finv Hfbij] [ginv Hgbij].\n  exists (ginv ∘ finv)%prg.\n  unfold compose.\n  intros x Hx.\n  destruct (Hgbij x) as [? [_ [? _]]]; auto.\n  destruct (Hfbij (g x)) as [? [_ [Hinv1 _]]]; auto.\n  destruct (Hfbij x) as [_ [? [_ ?]]]; auto.\n  destruct (Hgbij (finv x)) as [_ [? [_ Hinv2]]]; auto.\n  repeat split; auto.\n  rewrite Hinv1. \n  assumption.\n  rewrite Hinv2. \n  assumption.\nQed.\n\nLemma fswap_at_boundary_permutation : forall n f x,\n  permutation (S n) f ->\n  (x < S n)%nat -> f x = n ->\n  permutation n (fswap f x n).\nProof.\n  intros n f x Hf Hx Hfx.\n  assert (Hneq: forall x0, x0 < S n -> x0 <> x -> f x0 <> n).\n  { intros x0 Hx0 Hneq contra.\n    rewrite <- Hfx in contra.\n    eapply permutation_is_injective in contra.\n    contradiction.\n    apply Hf.\n    assumption.\n    assumption. }  \n\n  destruct Hf as [g Hg].\n  exists (compose (fswap (fun x : nat => x) x n) g).\n  intros x0 Hx0.\n  unfold fswap, compose.\n  bdestructΩ (x0 =? n).\n  repeat split.\n  - bdestruct (x0 =? x).\n    subst x0.\n    assert (f n <> n).\n    apply Hneq; lia.\n    destruct (Hg n) as [? _]; lia.\n    assert (f x0 <> n).\n    apply Hneq; lia.\n    destruct (Hg x0) as [? _]; lia.\n  - assert (g x0 <> x).\n    intro contra. \n    rewrite <- contra in Hfx.\n    destruct (Hg x0) as [_ [_ [_ ?]]]; lia.\n    bdestruct_all.\n    lia.\n    destruct (Hg x0) as [_ [? _]]; lia.\n  - bdestruct (x0 =? x).\n    subst x0.\n    destruct (Hg n) as [_ [_ [H1 _]]]; try lia.\n    rewrite H1.\n    bdestruct_all; trivial.\n    destruct (Hg x0) as [_ [_ [H1 _]]]; try lia.\n    rewrite H1.\n    bdestruct_all; trivial.\n  - assert (g x0 <> x).\n    intro contra. \n    rewrite <- contra in Hfx.\n    destruct (Hg x0) as [_ [_ [_ ?]]]; lia.\n    bdestructΩ (g x0 =? x).\n    bdestruct (g x0 =? n).\n    bdestructΩ (x =? x).\n    destruct (Hg x0) as [_ [_ [_ ?]]]; try lia.\n    rewrite <- H2.\n    assumption.\n    bdestruct_all.\n    destruct (Hg x0) as [_ [_ [_ ?]]]; lia.\nQed.\n  \n(** vsum terms can be arbitrarily reordered *)\nLemma vsum_reorder : forall {d} n (v : nat -> Vector d) f,\n  permutation n f ->\n  big_sum v n = big_sum (fun i => v (f i)) n.\nProof.\n  intros.\n  generalize dependent f.\n  induction n.\n  reflexivity.\n  intros f [g Hg].\n  destruct (Hg n) as [_ [H1 [_ H2]]]; try lia.\n  rewrite (vsum_eq_up_to_fswap _ f _ (g n) n) by auto.\n  repeat rewrite <- big_sum_extend_r.\n  rewrite fswap_simpl2.\n  rewrite H2.\n  specialize (IHn (fswap f (g n) n)).\n  rewrite <- IHn.\n  reflexivity.\n  apply fswap_at_boundary_permutation; auto.\n  exists g. auto.\nQed.\n\n(** * Permutation matrices *)\n\nDefinition perm_mat n (p : nat -> nat) : Square n :=\n  (fun x y => if (x =? p y) && (x <? n) && (y <? n) then C1 else C0).\n\nLemma perm_mat_WF : forall n p, WF_Matrix (perm_mat n p).\nProof.\n  intros n p.\n  unfold WF_Matrix, perm_mat. \n  intros x y [H | H].\n  bdestruct (x =? p y); bdestruct (x <? n); bdestruct (y <? n); trivial; lia.\n  bdestruct (x =? p y); bdestruct (x <? n); bdestruct (y <? n); trivial; lia.\nQed. \n#[export] Hint Resolve perm_mat_WF : wf_db.\n\nLemma perm_mat_unitary : forall n p, \n  permutation n p -> WF_Unitary (perm_mat n p).\nProof.\n  intros n p [pinv Hp].\n  split.\n  apply perm_mat_WF.\n  unfold Mmult, adjoint, perm_mat, I.\n  prep_matrix_equality.\n  destruct ((x =? y) && (x <? n)) eqn:H.\n  apply andb_prop in H as [H1 H2].\n  apply Nat.eqb_eq in H1.\n  apply Nat.ltb_lt in H2.\n  subst.\n  apply big_sum_unique.\n  exists (p y).\n  destruct (Hp y) as [? _]; auto.\n  split; auto.\n  split.\n  bdestruct_all; simpl; lca.\n  intros.  \n  bdestruct_all; simpl; lca.\n  apply (@big_sum_0 C C_is_monoid).\n  intros z.\n  bdestruct_all; simpl; try lca.\n  subst.\n  rewrite andb_true_r in H.\n  apply beq_nat_false in H.\n  assert (pinv (p x) = pinv (p y)) by auto.\n  destruct (Hp x) as [_ [_ [H5 _]]]; auto.\n  destruct (Hp y) as [_ [_ [H6 _]]]; auto.\n  contradict H.\n  rewrite <- H5, <- H6.\n  assumption.\nQed.\n\nLemma perm_mat_Mmult : forall n f g,\n  permutation n g ->\n  perm_mat n f × perm_mat n g = perm_mat n (f ∘ g)%prg.\nProof.\n  intros n f g [ginv Hgbij].\n  unfold perm_mat, Mmult, compose.\n  prep_matrix_equality.\n  destruct ((x =? f (g y)) && (x <? n) && (y <? n)) eqn:H.\n  apply andb_prop in H as [H H3].\n  apply andb_prop in H as [H1 H2].\n  apply Nat.eqb_eq in H1.\n  apply Nat.ltb_lt in H2.\n  apply Nat.ltb_lt in H3.\n  subst.\n  apply big_sum_unique.\n  exists (g y).\n  destruct (Hgbij y) as [? _]; auto.\n  split; auto.\n  split.\n  bdestruct_all; simpl; lca.\n  intros.\n  bdestruct_all; simpl; lca.\n  apply (@big_sum_0 C C_is_monoid).\n  intros z.\n  bdestruct_all; simpl; try lca.\n  subst.\n  rewrite 2 andb_true_r in H.\n  apply beq_nat_false in H.\n  contradiction.\nQed.\n\nLemma perm_mat_I : forall n f,\n  (forall x, x < n -> f x = x) ->\n  perm_mat n f = I n.\nProof.\n  intros n f Hinv.\n  unfold perm_mat, I.\n  prep_matrix_equality.\n  bdestruct_all; simpl; try lca.\n  rewrite Hinv in H1 by assumption.\n  contradiction.\n  rewrite Hinv in H1 by assumption.\n  contradiction.\nQed.\n\n(** Given a permutation p over n qubits, construct a permutation over 2^n indices. *)\nDefinition qubit_perm_to_nat_perm n (p : nat -> nat) :=\n  fun x:nat => funbool_to_nat n ((nat_to_funbool n x) ∘ p)%prg.\n\nLemma qubit_perm_to_nat_perm_bij : forall n p,\n  permutation n p -> permutation (2^n) (qubit_perm_to_nat_perm n p).\nProof.\n  intros n p [pinv Hp].\n  unfold qubit_perm_to_nat_perm.\n  exists (fun x => funbool_to_nat n ((nat_to_funbool n x) ∘ pinv)%prg).\n  intros x Hx.\n  repeat split.\n  apply funbool_to_nat_bound.\n  apply funbool_to_nat_bound.\n  unfold compose.\n  erewrite funbool_to_nat_eq.\n  2: { intros y Hy. \n       rewrite funbool_to_nat_inverse. \n       destruct (Hp y) as [_ [_ [_ H]]].\n       assumption.\n       rewrite H.\n       reflexivity.\n       destruct (Hp y) as [_ [? _]]; auto. }\n  rewrite nat_to_funbool_inverse; auto.\n  unfold compose.\n  erewrite funbool_to_nat_eq.\n  2: { intros y Hy. \n       rewrite funbool_to_nat_inverse. \n       destruct (Hp y) as [_ [_ [H _]]].\n       assumption.\n       rewrite H.\n       reflexivity.\n       destruct (Hp y) as [? _]; auto. }\n  rewrite nat_to_funbool_inverse; auto.\nQed.  \n\n(** Transform a (0,...,n-1) permutation into a 2^n by 2^n matrix. *)\nDefinition perm_to_matrix n p :=\n  perm_mat (2 ^ n) (qubit_perm_to_nat_perm n p).\n \nLemma perm_to_matrix_permutes_qubits : forall n p f, \n  permutation n p ->\n  perm_to_matrix n p × f_to_vec n f = f_to_vec n (fun x => f (p x)).\nProof.\n  intros n p f [pinv Hp].\n  rewrite 2 basis_f_to_vec.\n  unfold perm_to_matrix, perm_mat, qubit_perm_to_nat_perm.\n  unfold basis_vector, Mmult, compose.\n  prep_matrix_equality.\n  destruct ((x =? funbool_to_nat n (fun x0 : nat => f (p x0))) && (y =? 0)) eqn:H.\n  apply andb_prop in H as [H1 H2].\n  rewrite Nat.eqb_eq in H1.\n  rewrite Nat.eqb_eq in H2.\n  apply big_sum_unique.\n  exists (funbool_to_nat n f).\n  split.\n  apply funbool_to_nat_bound.\n  split.\n  erewrite funbool_to_nat_eq.\n  2: { intros. rewrite funbool_to_nat_inverse. reflexivity.\n  destruct (Hp x0) as [? _]; auto. }\n  specialize (funbool_to_nat_bound n f) as ?.\n  specialize (funbool_to_nat_bound n (fun x0 : nat => f (p x0))) as ?.\n  bdestruct_all; lca.\n  intros z Hz H3.\n  bdestructΩ (z =? funbool_to_nat n f).\n  lca.\n  apply (@big_sum_0 C C_is_monoid).\n  intros z.\n  bdestruct_all; simpl; try lca.\n  rewrite andb_true_r in H.\n  apply beq_nat_false in H.\n  subst z.\n  erewrite funbool_to_nat_eq in H2.\n  2: { intros. rewrite funbool_to_nat_inverse. reflexivity.\n  destruct (Hp x0) as [? _]; auto. }\n  contradiction.\nQed.\n\nLemma perm_to_matrix_unitary : forall n p, \n  permutation n p ->\n  WF_Unitary (perm_to_matrix n p).\nProof.\n  intros.\n  apply perm_mat_unitary.\n  apply qubit_perm_to_nat_perm_bij.\n  assumption.\nQed.\n\nLemma qubit_perm_to_nat_perm_compose : forall n f g,\n  permutation n f ->\n  (qubit_perm_to_nat_perm n f ∘ qubit_perm_to_nat_perm n g = \n    qubit_perm_to_nat_perm n (g ∘ f))%prg.\nProof.\n  intros n f g [finv Hbij].\n  unfold qubit_perm_to_nat_perm, compose.\n  apply functional_extensionality.\n  intro x.\n  apply funbool_to_nat_eq.\n  intros y Hy.\n  rewrite funbool_to_nat_inverse.\n  reflexivity.\n  destruct (Hbij y) as [? _]; auto.\nQed.\n\nLemma perm_to_matrix_Mmult : forall n f g,\n  permutation n f ->\n  permutation n g ->\n  perm_to_matrix n f × perm_to_matrix n g = perm_to_matrix n (g ∘ f)%prg.\nProof.\n  intros. \n  unfold perm_to_matrix.\n  rewrite perm_mat_Mmult.\n  rewrite qubit_perm_to_nat_perm_compose by assumption.\n  reflexivity.\n  apply qubit_perm_to_nat_perm_bij.\n  assumption.\nQed.\n\nLemma perm_to_matrix_I : forall n f,\n  permutation n f ->\n  (forall x, x < n -> f x = x) ->\n  perm_to_matrix n f = I (2 ^ n).\nProof.\n  intros n f g Hbij. \n  unfold perm_to_matrix.\n  apply perm_mat_I.\n  intros x Hx.\n  unfold qubit_perm_to_nat_perm, compose. \n  erewrite funbool_to_nat_eq.\n  2: { intros y Hy. rewrite Hbij by assumption. reflexivity. }\n  apply nat_to_funbool_inverse.\n  assumption.\nQed.\n\nLemma perm_to_matrix_WF : forall n p, WF_Matrix (perm_to_matrix n p).\nProof. intros. apply perm_mat_WF. Qed. \n#[export] Hint Resolve perm_to_matrix_WF : wf_db.\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/Permutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7747654712155065}}
{"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 : Lst), eq (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\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/goal72.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7745564099691433}}
{"text": "(* Exercise 23 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\n\nTheorem exercise_023 : \n  ((exists x : D, P x) -> (forall x : D, Q x)) \n-> \n  (forall y : D, P y -> Q y).\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/Taak11/Taak11_pred023.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810451666346, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7745545701799459}}
{"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. \n    intros H0 H1. \n    rewrite -> H0, H1.\n    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/basics/exercises/plus_id_exercise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522862, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7745545587615046}}
{"text": "(** Prove that Stdlib's function Min is primitive recursive *)\n(** this is a variant of the exercise MinPR *)\n\n\nFrom hydras Require Import  primRec extEqualNat.\nFrom Coq Require Import ArithRing Lia Compare_dec.\n\n(** Define an n-ary if-then-else *)\n\nFixpoint naryIf (n:nat) :\n  naryRel n -> naryFunc n -> naryFunc n -> naryFunc n\n  :=\n    match n return (naryRel n -> naryFunc n -> naryFunc n -> naryFunc n) with\n      0 => (fun b x y =>  if b then x else y)\n    | S m => fun (p': naryRel (S m)) (g h: naryFunc (S m)) =>\n               fun x => naryIf m (p' x) (g x) (h x)\n    end.\n\nLemma If2IsPR (p: naryRel 2)(f g : naryFunc 2):\n  isPRrel 2 p -> isPR 2 f -> isPR 2 g ->\n  isPR 2 (naryIf 2 p f g).\nProof.\n  unfold naryIf; cbn.\n  intros [x Hx] [y Hy] [z Hz].\n  assert (H: isPR 2  (fun a b => charFunction 2 p a b * f a b +\n                                 (1- charFunction 2 p a b) * g a b)).\n  {\n    apply   compose2_2IsPR.\n    - apply compose2_2IsPR.\n      + exists x; auto.\n      + exists y; auto.\n      + apply multIsPR.\n    - apply   compose2_2IsPR.\n      +  apply compose2_2IsPR.\n         *   apply filter01IsPR.\n             apply const1_NIsPR.\n         *  exists x; auto.\n         *  apply minusIsPR.\n      +  exists z; auto.\n      +  apply multIsPR.\n    -   apply plusIsPR.\n  }\n  destruct H as [t Ht]; exists t;  eapply extEqualTrans.\n  -   apply Ht.\n  -  intros a b; case_eq (p a b).\n     + intro H0; unfold charFunction.\n       rewrite H0.\n       replace (1 - 1) with 0; ring_simplify; reflexivity.\n     +  intro H1; unfold charFunction; rewrite H1; cbn; lia. \nQed. \n\nSection Proof_of_MinIsPR.\n\n  Let minPR : naryFunc 2 :=\n    naryIf 2 leBool\n           (fun x _ => x)\n           (fun _ y => y).\n\n  Lemma minPR_correct : extEqual 2 minPR PeanoNat.Nat.min.\n  Proof.\n    intros a b; unfold minPR, naryIf, leBool.\n    destruct  (le_lt_dec a b).\n    -    rewrite PeanoNat.Nat.min_l; auto; reflexivity. \n    - rewrite PeanoNat.Nat.min_r; auto with arith; reflexivity. \n  Qed.\n\n  Lemma minPR_PR : isPR 2 minPR.\n  Proof.\n    unfold minPR;apply If2IsPR.\n   -  apply leIsPR.\n   -  apply pi1_2IsPR.\n   -  apply pi2_2IsPR. \n  Qed.\n\n  Lemma minIsPR : isPR 2 min.\n  Proof.\n    destruct minPR_PR as [f Hf].\n    exists f; eapply extEqualTrans with (1:= Hf). \n    apply minPR_correct.\n  Qed.\n\n\nEnd Proof_of_MinIsPR.\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/MinPR2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.7745312060767948}}
{"text": "(* ***** examples: intuitionistic logic ***** *)\n\n(* The logical connectives for true, false, conjunction,\ndisjunction are defined by means of inductive predicates.\nRoughly the constructors correspond to the introduction\nrules, and the induction principle corresponds to the\nelimination rules. *)\n\nPrint True.\n(* True_ind states that P holds if we can prove True from it *)\nCheck True_ind.\n\nPrint False.\n(* False_ind gives the elimination rule for False:\nany P follows from False *)\nCheck False_ind.\n\nParameters A B C : Prop.\nLemma about_false: False -> A.\n\nProof.\nintro x.\nelim x.\n(* alternative:\nelimtype False.\nassumption.      *)\n(* alternative:\napply False_ind.\nassumption.      *)\nQed.\n\nPrint and.\nCheck and_ind.\n\nLemma about_intro_and : A -> B -> A /\\ B.\n\nProof.\nintro x.\nintro y.\nsplit.\nassumption.\nassumption.\n(* alternative:\napply conj.\nassumption.\nassumption.      *)\nQed.\n\nLemma about_elim_and : A /\\ B -> C -> A.\n(* elim or apply and_ind *)\n\nProof.\nintros x y.\napply and_ind with A B.\nintros.\nassumption.\nassumption.\nQed.\n\n\n(* ***** examples: even ***** *)\n\n(* an inductive definition of even *)\nInductive even : nat -> Prop :=\n| evenO : even O\n| evenSS : forall n:nat , even n -> even (S (S n)).\n\nCheck evenO.\nCheck (even O).\nCheck (even 1).\nCheck (evenSS O evenO).\nCheck (even 2).\nCheck (evenSS 2 (evenSS O evenO)).\nCheck (even 4).\n\n(* example *)\nTheorem evenzero : (even O).\n\nProof.\napply evenO.\nQed.\n\n(* example *)\nTheorem evenss : forall n:nat , (even n) -> (even (S (S n))).\n\nProof.\nexact evenSS.\nQed.\n\n(*\nalternative proof:\nintro n.\nintro H.\napply evenSS.\nexact H.\nQed.\n*)\n\n\n(* ***** examples: le ***** *)\n\nInductive le (n:nat) : nat -> Prop :=\n| le_n : le n n\n| le_S : forall m:nat , le n m -> le n (S m).\n\nCheck (le O O).\nCheck (le_n O).\nCheck (le_n O).\nCheck (le_S O O (le_n O)).\nDefinition zero_smaller_than_one := (le_S O O (le_n O)).\nCheck zero_smaller_than_one.\nCheck (le_n 7).\n\n(* examples: sorted *)\n\n(* an inductive type for finite lists of natural numbers *)\nInductive natlist : Set :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\n(* an inductive predicate sorted *)\nInductive sorted : natlist -> Prop :=\n| sorted0 : sorted nil\n| sorted1 : forall n:nat , sorted (cons n nil)\n| sorted2 : forall n h:nat , forall t:natlist ,\n            le n h -> sorted (cons h t) -> sorted (cons n (cons h t)).\n\nCheck (sorted1 1).\nDefinition list_one_sorted := (sorted1 1).\nCheck list_one_sorted.\nCheck (sorted2 O 1 nil zero_smaller_than_one list_one_sorted).\nDefinition list_zero_one_sorted := (sorted2 O 1 nil zero_smaller_than_one list_one_sorted).\nCheck list_zero_one_sorted.\n\n\n\n\n(* ***** examples: inversion ***** *)\nParameter P : nat -> Prop.\nParameter Q : nat -> nat -> Prop.\nParameter R : natlist -> Prop.\n\nLemma one : forall n : nat, even n -> P n.\n\nProof.\nintros n H.\ninversion H.\nAbort.\n\nLemma two : forall n m : nat, le n m -> Q n m.\n\nintros n m H.\ninversion H.\nAbort.\n\nLemma three : forall l : natlist, sorted l -> R l.\n\nProof.\nintros l H.\ninversion H.\nAbort.\n\n\n\n(* *************** now the exercises start ********** *)\n(* *************** we use definition given above **** *)\n\n(* exercise 1 *)\nTheorem even2 : (even 2 ).\nProof.\n(*! proof *)\n\nQed.\n\n(* a few checks *)\nCheck evenO.\nCheck evenzero.\nPrint evenzero.\nCheck evenSS.\nCheck even2.\nPrint even2.\n\n(* exercise 2\n   use inversion *)\nTheorem noteven1 : ~(even 1).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 3\n   you may want to use an earlier proved result *)\nTheorem even4 : even 4.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 4 *)\nTheorem noteven3 : ~(even 3).\nProof.\n(*! proof *)\n\nQed.\n\n(* an inductive definition of even and odd *)\nInductive ev : nat -> Prop :=\n| evO : ev O\n| evS : forall n:nat , odd n -> ev (S n)\nwith odd : nat -> Prop :=\n| oddS : forall n:nat , ev n -> odd (S n).\n\n(* example *)\nTheorem evzero : ev O.\nProof.\nexact evO.\nQed.\n\n(* example *)\nTheorem odd1 : odd 1.\nProof.\nexact (oddS O evzero).\nQed.\n\n(* exercise 5 *)\nTheorem ev2 : ev 2.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 6 *)\nTheorem notodd2 : ~ odd 2.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 7\n   use induction *)\nTheorem evorodd : forall n:nat, ev n \\/ odd n.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 8 *)\nTheorem zero_and_zero : le O O.\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 9 *)\nTheorem zero_and_one  : le 0 1.\nProof.\n(*! proof *)\n\nQed.\n\n(* some checks *)\nPrint zero_and_one.\nCheck zero_and_one.\n\n(* exercise 10 *)\nTheorem one_and_zero : ~ (le 1 0).\nProof.\n(*! proof *)\n\nQed.\n\n\n(* exercise 11 *)\nTheorem sortednil : sorted nil.\nProof.\n(*! proof *)\n\nQed.\n\n\n(* exercise 12 *)\nTheorem sortedone : sorted (cons 0 nil).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 13 *)\nTheorem sorted_one_two_three :\n  sorted (cons 1 (cons 2 (cons 3 nil))).\nProof.\n(*! proof *)\n\nQed.\n\n(* exercise 14 *)\nTheorem sorted_tail :\n  forall (n : nat) (l : natlist),\n  sorted (cons n l) ->\n  sorted l.\nProof.\n(*! proof *)\n\nQed.\n\n(* given for exercise 15\n   without_last n k l holds if\n   n is the last element of k\n   and\n   l is k without the last element *)\nInductive without_last (n:nat) : natlist -> natlist -> Prop :=\n| without_last_one :\n  without_last n (cons n nil) nil\n| without_last_more :\n    forall m:nat, forall l k : natlist,\n    without_last n k l -> without_last n (cons m k) (cons m l).\n\n(* exercise 15 *)\n(* define a predicate palindrome : natlist -> Prop\n   that holds exactly if the input list is equal to its reverse.\n   use three clauses: for the empty list, for a list of one\n   element, for a list of two or more elements *)\n\nInductive palindrome : natlist -> Prop := (*! term *)\n  .\n\n\n", "meta": {"author": "danalvi", "repo": "imc010-type-theory-coq", "sha": "13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8", "save_path": "github-repos/coq/danalvi-imc010-type-theory-coq", "path": "github-repos/coq/danalvi-imc010-type-theory-coq/imc010-type-theory-coq-13f80ccb19be0b0c93ab2da1f8f4b5c521b9b2f8/ex5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7744764783282283}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Sorting algorithms *)\n\n(** ** Insertion sort *)\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 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\n    insert x (sort s')\n  else [::].\n\n\n(** Now we'd like to prove [sort] correct.\n    But what does mean for a sorting algorithm\n    to be correct?\n\nIt could have been a requirement that the output\nof the algorithm is _sorted_.\nLet's give this notation a precise meaning.\nWe call the corresponding predicate [sorted']\nbecause we will later refine the definition into\nsomething more general that helps us a lot with\ninductive proofs.\n*)\n\n(** This fails because [x2 :: s'] is not a\n    structural subterm of [s] *)\nFail Fixpoint sorted' s : bool :=\n  if s is x1 :: x2 :: s' then\n    leT x1 x2 && (sorted' (x2 :: s'))\n  else true.\n\nFixpoint sorted' s : bool :=\n  if s is x1 :: ((x2 :: s') as tail) then\n    leT x1 x2 && (sorted' tail)\n  else true.\n\n(** The obvious definition we came up with is not\n    very easy to work with.\n    We would see it later when trying to prove\n    that [insert] function preserves sortedness. *)\n\n\n(** So instead we are going to use Mathcomp's\n    [sorted] predicate, which is based on the notion\n    of [path]. *)\nPrint sorted.\n(**\nsorted =\nfun (T : eqType) (leT : rel T) (s : seq T) =>\nif s is x :: s' then path leT x s'\nelse true\n: forall T : Type, rel T -> seq T -> bool\n*)\n\nPrint path.\n(**\npath =\nfun (T : Type) (e : rel T) =>\nfix path (x : T) (p : seq T) {struct p} : bool :=\n  if p is (y :: p') then e x y && path y p'\n  else true\n: forall T : Type, rel T -> T -> seq T -> bool\n*)\n\n(** With the modified definition the helper lemma\n    is much easier to prove (exercise): *)\nLemma sorted_cons e s :\n  sorted leT (e :: s) -> sorted leT s.\nAdmitted.\n\n\n\n\n\n(**\nIt's easy to see that requiring just sortedness\nof the output list is a rather weak specification --\na function always returning an empty list would\nalso be correct\n\nHence, our next observation --\nthe function should NOT forget about elements of\nthe input list:\n\n  forall x : T, x \\in s -> x \\in (sort s)\n\nA little thinking reveals this is a pretty weak spec:\na function may (in principle) add extra elements\nto the output, so we need to disallow that:\n\n  forall x : T, x \\in s = x \\in (sort s)\n\nRemark:\n  Since our implementations are going to be\n  parametric (generic), the only way the extra\n  elements may occur in the output list is by\n  repeating some elements of the input list,\n  so the above tweak of the spec does not\n  actually buy us anything.\n\nThe current version of the spec is still not strong\nenough: it does not take into account possible\nduplicates in the input list, e.g. the following is\ntrue, while this is not what we meant -- let's assume\ns = [:: 0; 0; 0] and that (sort s) = [:: 0; 0],\nthen the spec above still holds:\n  forall x, x \\in [:: 0; 0; 0] = x \\in [:: 0; 0]\n\nWhat we actually care about is to keep the elements\ntogether with their repective number of occurences.\n\n  forall x : T,\n    count (pred1 x) s = count (pred1 x) (sort s)\n\nQuestion: what goes wrong if we add a precondition\nthat all the elements we count must come from the\ninput list?\n\n  forall x : T,\n    x \\in s ->\n    count (pred1 x) s = count (pred1 x) (sort s)\n\n\nYou may have recognized the proposition\n  forall x : T,\n    count (pred1 x) s = count (pred1 x) (sort s)\n\nas expressing the notion of _permutation_.\n *)\n\n\n(**\nThere is one more concern w.r.t. the spec we came up\nwith so far -- it's non-computable as it requires us\nto compute [count]-expressions over a possibly\ninfinite type [T].\nIntuitively we know that for any two lists we can\ncompute if one is a permutation of the other if we\nhave equality over the type of elements.\n\nMathcomp introduces a computable notion of\nequivalence up to permutation: [perm_eq] defined\nas follows:\n*)\n\nPrint perm_eq.\n(**\nperm_eq =\nfun (T : eqType) (s1 s2 : seq T) =>\n  all\n    [pred x | (count_mem x) s1 == (count_mem x) s2]\n    (s1 ++ s2)\n\nis equivalent to\n\n  all\n    [pred x | (count_mem x) s1 == (count_mem x) s2]\n    s1\n  &&\n  all\n    [pred x | (count_mem x) s1 == (count_mem x) s2]\n    s2\n\n: forall T : eqType, seq T -> seq T -> bool\n\nwhere\nNotation count_mem x := (count (pred1 x))\n*)\n\n\n(**\nMoreover, any two lists [s1] and [s2] that are\na permutation of each other, give us the following\nproperty which is universal for _any_ predicate [p]:\n  forall p : pred T,\n    count p s1 = count p s2,\nexpressed as a [reflect]-predicate:\n*)\nAbout permP.\n(**\npermP :\n   forall (T : eqType) (s1 s2 : seq T),\n   reflect (count^~ s1 =1 count^~ s2)\n           (perm_eq s1 s2)\n*)\n\n\n(**\nAlternatively, the notion of permutation may be\nexpressed as a binary _inductive_ predicate:\n *)\nSection InductivePermutations.\nVariable A : Type.\n\nInductive perm : seq A -> seq A -> Prop :=\n| permutation_nil : perm [::] [::]\n| permutation_skip a v1 v2 of\n    perm v1 v2 : perm (a :: v1) (a :: v2)\n| permutation_swap a b v1 v2 of\n    perm v1 v2 : perm [:: a, b & v1] [:: b, a & v2]\n| permutation_trans v1 v2 v3 of\n    perm v1 v2 & perm v2 v3 : perm v1 v3.\n\n\nInductive le : nat -> nat -> Prop :=\n| leO n : le 0 n\n| leS m n : le m n -> le m.+1 n.+1.\n\nDefinition le_3_4 : le 3 4 :=\n  leS (leS (leS (leO _))).\n\nInductive le' : nat -> nat -> Prop :=\n| le_refl n : le' n n\n| leSr m n : le' m n -> le' m n.+1.\n\nDefinition le_3_4' : le' 3 4 :=\n  leSr (le_refl _).\n\n(**\nThe pros of this definition:\n- it can be used to work in a more general setting\n  where we don't have decidable equality;\n- we can do induction on the proofs of two lists\n  being a permutation of each other.\n\nThe cons is, of course, it does not compute.\n *)\n\nLemma pperm_sym v1 v2 :\n  perm v1 v2 <-> perm v2 v1.\nProof.\nsuff {v1 v2} L : forall v1 v2,\n  perm v1 v2 -> perm v2 v1 by split; apply: L.\nmove=> v1 v2; elim=> [*|*|*|].\n- exact: permutation_nil.\n- exact: permutation_skip.\n- exact: permutation_swap.\nmove=> ??? _ P21 _ P32.\nby apply: permutation_trans P32 P21.\n(* Restart. *)\n(* suff {v1 v2} L : forall v1 v2, *)\n(*   perm v1 v2 -> perm v2 v1 by split; apply: L. *)\n(* elim. *)\n(* Undo 3. *)\nQed.\n\n(** Exercise: try proving [pperm_sym]\n    by induction a list.\n *)\nEnd InductivePermutations.\n\n\n(** * Upshot:\nOur final notion of correctness of sorting algorithms\ncan be expressed semi-formally as follows\n  sorted (sort s)  /\\  perm_eq s (sort s)\n*)\n\n\n\n\n(** Let's try proving these properties for the\n    insertion sort algorithm we implemented *)\n\n(** * The output is sorted *)\n\n\n(* Local Notation sorted := (sorted leT). *)\n\nLemma sort_sorted s :\n  sorted leT (sort s).\nProof.\nelim: s=> [//| x s IHs /=].\n(** We need the fact that [insert] preserves\n    sortedness. Let's prove it as a standalone lemma\n *)\nAbort.\n\nLemma insert_sorted e s :\n  sorted leT s ->\n  sorted leT (insert e s).\nProof.\nelim: s=> [//| x1 s IHs].\nmove=> /=.\nmove=> path_x1_s.\ncase: ifP=> [e_le_x1 | e_gt_x1].\n- by rewrite /= e_le_x1 path_x1_s.\n(** Notice that we lack one essential fact about\n    [leT] -- totality *)\nAbort.\n\nHypothesis leT_total : total leT.\nPrint total.\n(**\ntotal =\nfun (T : Type) (R : rel T) =>\n  forall x y : T, R x y || R y x\n*)\n\nLemma insert_sorted e s :\n  sorted leT s ->\n  sorted leT (insert e s).\nProof.\nelim: s=> [//| x1 s IHs].\nmove=> /= path_x1_s.\ncase: ifP=> [e_le_x1 | e_gt_x1].\n- by rewrite /= e_le_x1 path_x1_s.\nhave:= leT_total e x1.\nrewrite {}e_gt_x1.\nmove=> /= x1_le_e.\nmove: path_x1_s=> {}/path_sorted/IHs.\ncase: s=> [|x2 s]; first by rewrite /= x1_le_e.\nmove=> /=.\ncase: ifP.\n- move=> /=.\n  move=>-> /= ->.\n  by rewrite x1_le_e.\n  (** We are moving in circles here, let's step back\n      and generalize the problem. *)\nAbort.\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\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\n\n(** exercise *)\nLemma sort_sorted s :\n  sorted leT (sort s).\nProof.\nAdmitted.\n\nEnd InsertionSort.\n\nArguments sort {T} _ _.\nArguments insert {T} _ _ _.\n\n\n\n\nSection SortIsPermutation.\n\nVariable T : eqType.\nVariables leT : rel T.\n\n(** a helper lemma (exercise) *)\nLemma count_insert p e s :\n  count p (insert leT e s) = p e + count p s.\nAdmitted.\n\nAbout perm_eql.\n(**\nNotation perm_eql s1 s2 :=\n  (perm_eq s1 =1 perm_eq s2).\n *)\n\nPrint perm_eq.\n(**\nperm_eq =\nfun (T : eqType) (s1 s2 : seq T) =>\nall [pred x | count_mem x s1 == count_mem x s2]\n    (s1 ++ s2)\n     : forall T : eqType, seq T -> seq T -> bool\n*)\n\n\nLemma perm_sort s : perm_eql (sort leT s) s.\nProof.\n  (* Search _ perm_eq. *)\n  Search _ (perm_eq ?s1 =1 perm_eq ?s2).\napply/permPl/permP.\nelim: s=> //= x s IHs.\nmove=> p.\nby rewrite count_insert IHs.\nQed.\n\n(** This is why we state [perm_sort] lemma\n    using [perm_eql] -- it can be used as\n    an equation like so\n *)\nLemma mem_sort s : sort leT s =i s.\nProof. by apply: perm_mem; rewrite perm_sort. Qed.\n\nLemma sort_uniq s : uniq (sort leT s) = uniq s.\nProof. by apply: perm_uniq; rewrite perm_sort. Qed.\n\nEnd SortIsPermutation.\n\n\n\nSection SortProperties.\n\nVariable T : eqType.\nVariables leT : rel T.\n\nLemma sorted_sort s :\n  sorted leT s -> sort leT s = s.\nProof.\nelim: s=> // x1 s IHs S.\nmove: (S)=> {}/sorted_cons/IHs /= ->.\nmove: S=> /=.\ncase: s=> //= x2 s.\nby case/andP=> ->.\nQed.\n\n(** Insertion sort is stable (exercise) *)\nSection Stability.\n\nVariable leT' : rel T.\nImplicit Types s : seq T.\n\n(** Hint: you are free to assume e.g.\n          [transitivity] of [leT] / [leT'] should\n          you need that. E.g.\nHypothesis leT_tr : transitive leT.\n *)\n\nLemma sort_stable s :\n  sorted leT' s ->\n  sorted\n    [rel x y | leT x y && (leT y x ==> leT' x y)]\n    (sort leT s).\nProof.\nAdmitted.\nEnd Stability.\n\nEnd SortProperties.\n\nEnd Insertion.\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/lecture10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8807970779778825, "lm_q1q2_score": 0.7743499123030384}}
{"text": "Require Import list.\nRequire Import nat.\nRequire Import bool.\n\n\nTheorem silly1 : forall (n m o p:nat),\n    n = m -> [n,o] = [n,p] -> [n,o] = [m,p].\nProof.\n    intros n m o p H1 H2. rewrite <- H1. exact H2.\nQed.\n\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.\n    intros n m o p H1 H2. apply H2. exact H1.\nQed.\n\n\nTheorem silly_ex : (forall n:nat, evenb n = true -> oddb (S n) = true) ->\n    evenb 3 = true -> oddb 4 = true.\nProof. intros H1 H2. apply H1. exact H2. Qed.\n\n\nTheorem silly3 : forall n:nat,\n    true = eqb n 5 -> eqb (S (S n)) 7 = true.\nProof.\n    intros n H. simpl. symmetry. exact H.\nQed.\n\n(*\nSearchAbout rev.\n*)\n\nTheorem rev_ex1 : forall (a:Type) (l k:list a),\n    l = rev k -> k = rev l.\nProof.\n    intros a l k H. assert (rev l = rev (rev k)) as H'. { rewrite H. reflexivity. }\n    rewrite rev_involutive in H'. symmetry. exact H'.\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. rewrite H1, H2. reflexivity.\nQed.\n\nTheorem trans_eq : forall (a:Type) (x y z:a),\n    x = y -> y = z -> x = z.\nProof.\n    intros a x y z H1 H2. rewrite H1, H2. 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. intros a b c d e f. apply trans_eq. Qed.\n\nDefinition minustwo (n:nat) : nat :=\n    match n with\n    | 0         => 0\n    | S 0       => 0\n    | S (S p)   => p\n    end.\n\n \nExample trans_eq_ex : forall (n m p q:nat),\n    m = (minustwo p) ->\n    (n + q) = m ->\n    (n + q) = (minustwo p).\nProof.\n    intros n m p q H1 H2. apply trans_eq with (y:= m).\n    exact H2. exact H1.\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/sf/apply.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.7743498970398103}}
{"text": "Definition negb b :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb b1 b2 :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb b1 b2 :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nDefinition nandb b1 b2 :=\n  match b1 with\n  | true => negb b2\n  | false => true\n  end.\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\nDefinition andb3 b1 b2 b3 :=\n  match b1 with\n  | true => andb b2 b3\n  | false => false\n  end.\n\nCheck true.\nCheck andb.\nCheck andb3.\n\nDefinition minustwo n :=\n  match n with\n  | O | S O => O\n  | S (S n') => n'\n  end.\n\nEval simpl in minustwo 4.\n\nCheck S.\nCheck O.\nCheck pred.\n\nFixpoint evenb n :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb n := negb (evenb 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\nCheck plus.\nCheck mult.\nCheck minus.\n\nFixpoint exp base power :=\n  match power with\n  | O => S O\n  | S p' => mult base (exp base p')\n  end.\n\nExample test_exp1: exp 2 3 = 8.\nProof. reflexivity. Qed.\n\nFixpoint factorial n :=\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. reflexivity. Qed.\nExample test_factorial2: factorial 5 = mult 10 12.\nProof. reflexivity. Qed.\n\nNotation \"x + y\" := (plus 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\" := (minus x y) (at level 50, left associativity): nat_scope.\n\nEval simpl in 0 - 1 + 2.\n\nFixpoint beq_nat n m :=\n  match n, m with\n  | O, O => true\n  | O, _ | _, O => false\n  | S n', S m' => beq_nat n' m'\n  end.\n\nFixpoint ble_nat n m :=\n  match n, m with\n  | O, _ => true\n  | _, O => false\n  | S n', S m' => ble_nat n' m'\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\nTheorem plus_O_n: forall n, 0 + n = n.\nProof.\n  intro n.\n  reflexivity.\nQed.\n\nTheorem plus_1_l: forall n, 1 + n = S n.\nProof.\n  intro n.\n  reflexivity.\nQed.\n\nTheorem mult_0_l: forall n, 0 * n = 0.\nProof.\n  intro n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_id_example:\n  forall n m, n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intro H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise:\n  forall n m o, n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intro h1.\n  intro h2.\n  rewrite -> h1.\n  rewrite -> h2.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus:\n  forall n m, (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_1:\n  forall n m,\n    m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intro H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry:\n  forall n, beq_nat (n + 1) 0 = false.\nProof.\n  intro n.\n  simpl.\nAbort.\n\nTheorem plus_1_neq_0:\n  forall n, beq_nat (n + 1) 0 = false.\nProof.\n  intro n.\n  destruct n as [|n'].\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem negb_involutive:\n  forall b, negb (negb b) = b.\nProof.\n  intro b.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1:\n  forall n, beq_nat 0 (n + 1) = false.\nProof.\n  intro n.\n  destruct n.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem identity_fn_applied_twice:\n  forall f, (forall x, f x = x) -> forall (b: bool), f (f b) = b.\nProof.\n  intro f.\n  intro H.\n  intro b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem negation_fn_applied_twice:\n  forall f, (forall x, f x = negb x) -> forall (b: bool), f (f b) = b.\nProof.\n  intro f.\n  intro H.\n  intro b.\n  rewrite -> H.\n  rewrite -> H.\n  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\nTheorem orb_true_eq_true:\n  forall b, orb b true = true.\nProof.\n  intro b.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem andb_eq_orb:\n  forall b c, (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  intro H.\n  destruct c.\n  destruct b.\n  reflexivity.\n\nTheorem and_f_t_f: andb false true = false.\nProof. reflexivity. Qed.\n\n  rewrite <- and_f_t_f.\n  rewrite -> H.\n  reflexivity.\n  destruct b.\n\nTheorem and_t_f_f: andb true false = false.\nProof. reflexivity. Qed.\n\n  rewrite <- and_t_f_f.\n  rewrite -> H.\n  reflexivity.\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\nEval simpl in toNat (TPlus (T (TPlus Z))).\n\nExample nine_toNat_plus_eq: S (toNat (TPlus (T (T (TPlus Z))))) = toNat (incr (TPlus (T (T (TPlus Z))))).\nProof. reflexivity. Qed.\n\nFixpoint plus' n m :=\n  match n with\n  | O => m\n  | S n' => S (plus' n' m)\n  end.\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": "davidgrenier", "repo": "SoftwareFoundation", "sha": "4e34d1ac87c4136ea2468048dee306ba5180eb82", "save_path": "github-repos/coq/davidgrenier-SoftwareFoundation", "path": "github-repos/coq/davidgrenier-SoftwareFoundation/SoftwareFoundation-4e34d1ac87c4136ea2468048dee306ba5180eb82/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7743498957214889}}
{"text": "Require Export Coq.Lists.List\n        Coq.Sorting.Permutation\n        CoqRecon.Util.Base Coq.micromega.Lia\n        Coq.Arith.Compare_dec.\nExport ListNotations.\n\nSection Uniques.\n  Context {A : Set}.\n  Context {HEA: EqDec A eq}.\n\n  Fixpoint remove (a : A) (l : list A) : list A :=\n    match l with\n    | []    => []\n    | h :: l => (if h == a then [] else [h]) ++ remove a l\n    end.\n\n  Lemma remove_correct : forall l a, ~ In a (remove a l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a H; simpl in *; auto.\n    dispatch_eqdec; firstorder.\n  Qed.\n\n  Lemma remove_not_in : forall l a,\n      ~ In a l -> remove a l = l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a H; simpl in *; auto.\n    apply Decidable.not_or in H as (Hha & Hal).\n    dispatch_eqdec.\n    apply IHl in Hal. rewrite Hal. reflexivity.\n  Qed.\n\n  Lemma remove_sound : forall l a x,\n      In a (remove x l) -> In a l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a x Hal; simpl in *; auto.\n    dispatch_eqdec; firstorder.\n  Qed.\n\n  Lemma remove_complete : forall l a x,\n      x <> a -> In a l -> In a (remove x l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a x Hax Hal; simpl in *; auto.\n    dispatch_eqdec; destruct Hal; intuition.\n  Qed.\n\n  Fixpoint uniques (l : list A) : list A :=\n    match l with\n    | []    => []\n    | a :: l => a :: remove a (uniques l)\n    end.\n  \n  Lemma uniques_sound : forall l a,\n      In a (uniques l) -> In a l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a Hal; simpl in *; auto.\n    destruct Hal as [Hha | Hal]; eauto using remove_sound.\n  Qed.\n\n  Lemma uniques_complete : forall l a,\n      In a l -> In a (uniques l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a Hal; simpl in *; auto.\n    eqdec h a; auto.\n    destruct Hal; try contradiction.\n    eauto using remove_complete.\n  Qed.\n\n  Local Hint Constructors NoDup : core.\n  Local Hint Resolve remove_sound : core.\n\n  Lemma remove_nodup : forall l,\n      NoDup l -> forall a, NoDup (remove a l).\n  Proof.\n    intros l H; induction H; intros a; simpl; auto.\n    dispatch_eqdec; eauto.\n  Qed.\n\n  Local Hint Resolve remove_correct : core.\n  Local Hint Resolve remove_nodup : core.\n  \n  Lemma uniques_nodup : forall l,\n      NoDup (uniques l).\n  Proof.\n    intro l; induction l as [| a l IHl]; simpl; auto.\n  Qed.\n\n  Local Hint Resolve remove_not_in : core.\n  \n  Lemma NoDup_uniques_idem : forall l,\n      NoDup l -> uniques l = l.\n  Proof.\n    intros l Hnd;\n      induction Hnd as [| a l Hal Hl IHl];\n      simpl; f_equal; rewrite IHl; auto.\n  Qed.\n\n  Local Hint Resolve uniques_sound : core.\n  Local Hint Resolve uniques_complete : core.\n\n  Lemma uniques_iff : forall a l,\n      In a (uniques l) <-> In a l.\n  Proof.\n    intuition.\n  Qed.\n\n  Lemma remove_length : forall l a,\n      length (remove a l) <= length l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; auto.\n    rewrite app_length.\n    specialize IHl with a. dispatch_eqdec; lia.\n  Qed.\n\n  Lemma uniques_length : forall l,\n      length (uniques l) <= length l.\n  Proof.\n    intro l; induction l as [| a l IHl]; simpl in *; auto.\n    pose proof remove_length (uniques l) a. lia.\n  Qed.\n\n  Lemma remove_idempotent : forall l a,\n      remove a (remove a l) = remove a l.\n  Proof.\n    intros l a.\n    rewrite remove_not_in with (l := remove a l) by auto.\n    reflexivity.\n  Qed.\n\n  Lemma remove_comm : forall l a x,\n      remove a (remove x l) = remove x (remove a l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros a x; simpl; auto; repeat dispatch_eqdec;\n        auto; rewrite IHl; reflexivity.\n  Qed.\n  \n  Lemma remove_uniques_comm : forall l a,\n      remove a (uniques l) = uniques (remove a l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; try dispatch_eqdec; auto.\n    - rewrite remove_idempotent; auto.\n    - rewrite remove_comm. rewrite IHl.\n      reflexivity.\n  Qed.\n\n  Lemma uniques_idempotent : forall l,\n      uniques (uniques l) = uniques l.\n  Proof.\n    intro l; induction l as [| a l IHl]; simpl; auto.\n    repeat rewrite <- remove_uniques_comm.\n    rewrite remove_idempotent. rewrite IHl.\n    reflexivity.\n  Qed.\n\n  Lemma remove_app : forall l r a,\n      remove a (l ++ r) = remove a l ++ remove a r.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intros r a; simpl; try dispatch_eqdec;\n        try rewrite IHl; auto.\n  Qed.\n  \n  Lemma uniques_app : forall l r,\n      uniques (l ++ r) = uniques (uniques l ++ uniques r).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro r; simpl.\n    - rewrite uniques_idempotent. reflexivity.\n    - f_equal. rewrite IHl.\n      repeat rewrite remove_uniques_comm.\n      repeat rewrite remove_app.\n      rewrite <- remove_uniques_comm.\n      rewrite remove_idempotent. reflexivity.\n  Qed.\n\n  Lemma remove_rev : forall l a,\n      rev (remove a l) = remove a (rev l).\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; auto.\n    repeat rewrite remove_app; simpl.\n    rewrite rev_app_distr.\n    rewrite IHl. f_equal.\n    dispatch_eqdec; reflexivity.\n  Qed.\n  \n  Lemma uniques_app2 : forall l r,\n      uniques (l ++ r) = uniques l ++ fold_right remove (uniques r) l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro r; simpl; auto.\n    f_equal. rewrite IHl.\n    rewrite remove_app. reflexivity.\n  Qed.\n\n  Lemma uniques_repeat : forall n a,\n      uniques (repeat a n) =\n      match n with\n      | O   => []\n      | S _ => [a]\n      end.\n  Proof.\n    intro n; induction n as [| n IHn];\n      intro a; simpl; auto.\n    rewrite IHn.\n    destruct n; simpl; try dispatch_eqdec; auto.\n  Qed.\n\n  Fixpoint count (a : A) (l : list A) : nat :=\n    match l with\n    | []    => 0\n    | h :: l => (if h == a then 1 else 0) + count a l\n    end.\n\n  Lemma count_app : forall l r a,\n      count a (l ++ r) = count a l + count a r.\n  Proof.\n    intro l; induction l as [| h l IHl]; intros r a; simpl; auto.\n    rewrite IHl. rewrite PeanoNat.Nat.add_assoc. reflexivity.\n  Qed.\n  \n  Lemma count_remove : forall l a, count a (remove a l) = 0.\n  Proof.\n    intro l; induction l as [| h l IHl]; intro a; simpl;\n      repeat dispatch_eqdec; try rewrite IHl; auto.\n  Qed.\n\n  Lemma count_remove_le : forall l a x,\n      count a (remove x l) <= count a l.\n  Proof.\n    intro l; induction l as [| h l IHl]; intros a x; simpl; try lia.\n    specialize IHl with (a := a) (x := x).\n    repeat dispatch_eqdec; try lia.\n  Qed.\n\n  Lemma count_uniques : forall l a,\n      count a (uniques l) <= 1.\n  Proof.\n    intro l; induction l as [| h l IHl]; intro a; simpl; auto.\n    specialize IHl with a. dispatch_eqdec.\n    - rewrite count_remove. lia.\n    - pose proof count_remove_le (uniques l) a h as Hle. lia.\n  Qed.\n\n  Lemma count_in : forall l a,\n      In a l <-> count a l > 0.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; split; intros H;\n        try dispatch_eqdec; try firstorder lia.\n  Qed.\n\n  Corollary count_uniques_in : forall a l,\n      In a l -> count a (uniques l) = 1.\n  Proof.\n    intros a l Hal.\n    rewrite <- uniques_iff in Hal.\n    rewrite count_in in Hal.\n    pose proof count_uniques l a. lia.\n  Qed.\n  \n  Lemma count_not_in : forall l a,\n      ~ In a l <-> count a l = 0.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; split; intros H;\n        try dispatch_eqdec; try firstorder lia.\n  Qed.\n\n  Lemma count_length_le : forall l a,\n      count a l <= length l.\n  Proof.\n    intro l; induction l as [| h l IHl];\n      intro a; simpl; try lia.\n    specialize IHl with a.\n    dispatch_eqdec; lia.\n  Qed.\n  \n  Lemma count_remove_length : forall l a,\n      length (remove a l) = length l - count a l.\n  Proof.\n    intro l; induction l as [| h l IHl]; intro a; simpl;\n      repeat dispatch_eqdec; auto.\n    destruct (count a l) as [| n] eqn:Hcnt.\n    - rewrite <- count_not_in in Hcnt.\n      rewrite remove_not_in by assumption. reflexivity.\n    - rewrite IHl. rewrite Hcnt.\n      pose proof count_length_le l a as HCL. lia.\n  Qed.\n    \n  Lemma count_repeat : forall n a,\n      count a (repeat a n) = n.\n  Proof.\n    intro n; induction n as [| n IHn]; intro a; simpl;\n      try dispatch_eqdec; try rewrite IHn; auto.\n  Qed.\n\n  Local Hint Constructors Permutation : core.\n\n  Lemma remove_perm : forall l l',\n      Permutation l l' -> forall a, Permutation (remove a l) (remove a l').\n  Proof.\n    intros l l' H; induction H; intro a; simpl;\n      repeat dispatch_eqdec; eauto.\n  Qed.\n\n  Local Hint Resolve remove_perm : core.\n  \n  Lemma uniques_perm : forall l l',\n      Permutation l l' -> Permutation (uniques l) (uniques l').\n  Proof.\n    intros l l' H; induction H; simpl; eauto 3.\n    rewrite remove_comm. repeat dispatch_eqdec; auto.\n  Qed.\n\n  Lemma In_split_repeat_perm : forall l (a : A),\n      In a l -> exists n l',\n        ~ In a l' /\\ Permutation l (repeat a (S n) ++ l').\n  Proof.\n    intro l; induction l as [| h t IHt];\n      intros a Hal; simpl in *; try contradiction.\n    destruct (In_dec HEA a t) as [Hat | Hat]; eqdec h a;\n      destruct Hal as [Hha' | Hat']; subst; simpl;\n        try contradiction.\n    - apply IHt in Hat as (n & l' & Hl' & HP).\n      exists (S n). exists l'. simpl; intuition.\n    - apply IHt in Hat as (n & l' & Hl' & HP).\n      exists (S n). exists l'. simpl; intuition.\n    - apply IHt in Hat as (n & l' & Hl' & HP).\n      exists n. exists (h :: l'). simpl; intuition.\n      rewrite app_comm_cons in *.\n      auto using Permutation_cons_app.\n    - exists 0. exists t. simpl; intuition.\n  Qed.\n\n  Lemma length_uniques_app_le : forall l r,\n      length (uniques l) <= length (uniques (l ++ r)).\n  Proof.\n    intros l r.\n    rewrite uniques_app2.\n    rewrite app_length. lia.\n  Qed.\n\n  Lemma uniques_Forall : forall P l,\n      Forall P (uniques l) <-> Forall P l.\n  Proof.\n    intros P l; repeat rewrite Forall_forall; intuition.\n  Qed.\n\n  Lemma uniques_nil : forall l,\n      uniques l = [] <-> l = [].\n  Proof.\n    intro l; split; intros H; simpl in *; subst; auto.\n    destruct l; simpl in *; auto; try discriminate.\n  Qed.\nEnd Uniques.\n\nSection Inside.\n  Context {A : Set}.\n  \n  Inductive inside (a : A) : list A -> Prop :=\n  | inside_cons_hd t :\n      inside a (a :: t)\n  | inside_cons_tl h t :\n      h <> a ->\n      inside a t ->\n      inside a (h :: t).\n\n  Lemma inside_sound : forall a l, inside a l -> In a l.\n  Proof.\n    intros a l H; induction H; intuition.\n  Qed.\n    \n  Lemma inside_split_first : forall a l,\n      inside a l -> exists l1 l2, l = l1 ++ a :: l2 /\\ ~ inside a l1.\n  Proof.\n    intros a l H; induction H.\n    - exists [], t. split; auto.\n      intros H; inv H.\n    - destruct IHinside as (l1 & l2 & Ht & Hl1); subst.\n      exists (h :: l1), l2. split; auto.\n      intros Hin; inv Hin; contradiction.\n  Qed.\n\n  Hypothesis Hexm_eq : forall a1 a2 : A, a1 = a2 \\/ a1 <> a2.\n\n  Local Hint Constructors inside : core.\n\n  Lemma inside_complete : forall l a, In a l -> inside a l.\n  Proof.\n    intro l; induction l as [| h t IHt];\n      intros a Hal; simpl in *; try contradiction.\n    destruct (Hexm_eq h a) as [Hha | Hha];\n      firstorder subst; auto.\n  Qed.\n\n  Local Hint Resolve inside_sound : core.\n  Local Hint Resolve inside_complete : core.\n\n  Lemma inside_in_iff : forall a l,\n      inside a l <-> In a l.\n  Proof.\n    intuition.\n  Qed.\n\n  Lemma inside_in_not_iff : forall a l,\n      ~ inside a l <-> ~ In a l.\n  Proof.\n    intuition.\n  Qed.\n  \n  Lemma in_split_first : forall (a : A) l,\n      In a l -> exists l1 l2, l = l1 ++ a :: l2 /\\ ~ In a l1.\n  Proof.\n    intros a l HIn.\n    apply inside_complete in HIn.\n    apply inside_split_first in HIn\n      as (l1 & l2 & Hl & Hl1); subst.\n    exists l1, l2; auto.\n  Qed.\nEnd Inside.\n\nFixpoint flipper {A B : Set} (C : list (A * B)) : list (B * A) :=\n  match C with\n  | []         => []\n  | (l, r) :: C => (r, l) :: flipper C\n  end.\n\nLemma flipper_involutive : forall (A B : Set) (C : list (A * B)),\n    flipper (flipper C) = C.\nProof.\n  intros A B C; induction C as [| [l r] C IHC]; simpl; f_equal; auto.\nQed.\n\nLemma flipper_nil : forall (A B : Set) (C : list (A * B)),\n    flipper C = [] -> C = [].\nProof.\n  intros A B C HC.\n  destruct C as [| [? ?] ?];\n    simpl in *; try discriminate; reflexivity.\nQed.\n\nLemma in_flipper : forall (A B : Set) l (a : A) (b : B),\n    In (a, b) l -> In (b, a) (flipper l).\nProof.\n  intros A B l; induction l as [| [u v] l IHl];\n    intros a b Hin; simpl in *; auto.\n  destruct Hin as [Hab | Hab]; try inv Hab; auto.\nQed.\n\nSection PairLists.\n  Context {U V : Set}.\n\n  Lemma combine_map_fst : forall (us : list U) (vs : list V),\n      map fst (combine us vs) = firstn (min (length us) (length vs)) us.\n  Proof.\n    intro us; induction us as [| u us IHus];\n      intros [| v vs]; simpl; f_equal; auto.\n  Qed.\n\n  Lemma combine_map_snd : forall (vs : list V) (us : list U),\n      map snd (combine us vs) = firstn (min (length us) (length vs)) vs.\n  Proof.\n    intro vs; induction vs as [| v vs IHvs];\n    intros [| u us]; simpl; f_equal; auto.\n  Qed.\n\n  Lemma split_map : forall (l : list (U * V)),\n      split l = (map fst l, map snd l).\n  Proof.\n    intro l; induction l as [| [u v] t IHt]; simpl; auto.\n    destruct (split t) as [us vs] eqn:Hsplit; simpl; inv IHt; auto.\n  Qed.\n\n  Lemma combine_map : forall (l : list (U * V)),\n      combine (map fst l) (map snd l) = l.\n  Proof.\n    intros l.\n    pose proof split_combine l as H.\n    destruct (split l) as [us vs] eqn:Hsplit.\n    rewrite split_map in Hsplit.\n    injection Hsplit as Hus Hvs.\n    rewrite Hus, Hvs; assumption.\n  Qed.\n  \n  Hint Rewrite map_length : core.\n  Local Hint Resolve combine_map : core.\n           \n  Lemma combine_ex : forall (l : list (U * V)),\n      exists us vs, l = combine us vs /\\ length us = length vs.\n  Proof.\n    intro l. exists (map fst l). exists (map snd l).\n    autorewrite with core; auto.\n  Qed.\n\n  Lemma flipper_combine : forall (us : list U) (vs : list V),\n      flipper (combine us vs) = combine vs us.\n  Proof.\n    intro us; induction us as [| u us IHus];\n      intros [| v vs]; simpl; f_equal; auto.\n  Qed.\n\n  Local Hint Constructors NoDup : core.\n  \n  Lemma NoDup_combine : forall (us : list U),\n      NoDup us ->\n      forall (vs : list V),\n        NoDup (combine us vs).\n  Proof.\n    intros us Hndu; induction Hndu;\n      intros [| v vs]; simpl; auto.\n    assert (~ In (x, v) (combine l vs)).\n    { intros Hin.\n      apply in_combine_l in Hin as ?; contradiction. }\n    auto.\n  Qed.\n\n  Lemma NoDup_pair_eq_r : forall us,\n      NoDup us ->\n      forall vs (u : U) (v1 v2 : V),\n        In (u,v1) (combine us vs) ->\n        In (u,v2) (combine us vs) ->\n        v1 = v2.\n  Proof.\n    intros us Hnd; induction Hnd;\n      intros [| v vs] u v1 v2 Hv1 Hv2;\n      simpl in *; try contradiction.\n    destruct Hv1 as [Hv1 | Hv1];\n      destruct Hv2 as [Hv2 | Hv2]; subst;\n        try inv Hv1; try inv Hv2; eauto;\n          try apply in_combine_l in Hv2;\n          try apply in_combine_l in Hv1; contradiction.\n  Qed.\n\n  Lemma NoDup_pair_eq_l : forall vs,\n      NoDup vs ->\n      forall us (u1 u2 : U) (v : V),\n        In (u1,v) (combine us vs) ->\n        In (u2,v) (combine us vs) ->\n        u1 = u2.\n  Proof.\n    intros vs Hnd; induction Hnd;\n      intros [| u us] u1 u2 v Hin1 Hin2;\n      simpl in *; try contradiction.\n    destruct Hin1 as [Hu1 | Hin1];\n      destruct Hin2 as [Hu2 | Hin2];\n      try inv Hu1; try inv Hu2; eauto;\n        try apply in_combine_r in Hin2;\n        try apply in_combine_r in Hin1; contradiction.\n  Qed.\n\n  Lemma in_combine_nth_error : forall us vs (u : U) (v : V),\n      In (u,v) (combine us vs) ->\n      exists n, nth_error us n = Some u /\\ nth_error vs n = Some v.\n  Proof.\n    intro us; induction us as [| hu us IHus];\n      intros [| hv vs] u v Hin; simpl in *;\n        try contradiction.\n    destruct Hin as [Hin | Hin]; try inv Hin.\n    - exists 0; auto.\n    - apply IHus in Hin as (n & Hus & Hvs).\n      exists (S n); auto.\n  Qed.\n\n  Lemma nth_error_combine_some : forall n us vs (u : U) (v : V),\n      nth_error us n = Some u ->\n      nth_error vs n = Some v ->\n      nth_error (combine us vs) n = Some (u, v).\n  Proof.\n    intro n; induction n as [| n IHn];\n      intros [| hu us] [| hv vs] u v Hu Hv;\n      simpl in *; inv Hu; inv Hv; auto.\n  Qed.\n  \n  Local Hint Resolve nth_error_combine_some : core.\n\n  Lemma in_combine_index : forall n us vs (u : U) (v : V),\n      nth_error us n = Some u ->\n      nth_error vs n = Some v ->\n      In (u,v) (combine us vs).\n  Proof.\n    intros n us vs u v Hu Hv.\n    eauto using nth_error_In.\n  Qed.\n\n  Context {HEU : EqDec U eq} {HEV : EqDec V eq}.\n  \n  Lemma not_in_combine : forall us vs (u : U) (v : V),\n      ~ In (u,v) (combine us vs) ->\n      ~ In u us /\\ ~ In v vs \\/\n      In u us   /\\ ~ In v vs \\/\n      ~ In u us /\\   In v vs \\/\n      exists m n, m <> n /\\ nth_error us m = Some u /\\ nth_error vs n = Some v.\n  Proof.\n    intros us vs u v Hin.\n    pose proof in_dec HEU u us as [Huus | Huus];\n      pose proof in_dec HEV v vs as [Hvvs | Hvvs]; auto.\n    apply In_nth_error in Huus, Hvvs.\n    destruct Huus as [p Hus]; destruct Hvvs as [q Hvs].\n    repeat right. exists p, q; intuition; subst.\n    apply Hin. apply nth_error_In with q; auto.\n  Qed.\nEnd PairLists.\n\nLemma nodup_triple_eq_r : forall {U V W : Set} us,\n    NoDup us ->\n    forall (u : U) (v : V) (w1 w2 : W) vs ws,\n      NoDup vs ->\n      In (u,v) (combine us vs) ->\n      In (u,w1) (combine us ws) ->\n      In (v,w2) (combine vs ws) -> w1 = w2.\nProof.\n  intros U V W us Hndus;\n    induction Hndus as [| hu us Hninu Hndus IHus];\n    intros u v w1 w2 vs [| w ws] Hndvs Huv Huw Hvw;\n    inversion Hndvs as [Hvsnil | hv tvs Hninhv Hndtvs]; subst;\n      simpl in *; try contradiction.\n  destruct Huv as [Huv | Huv];\n    destruct Huw as [Huw | Huw];\n    destruct Hvw as [Hvw | Hvw];\n    try inv Huv; try inv Huw; try inv Hvw; eauto;\n      try apply in_combine_l in Hvw;\n      try apply in_combine_l in Huw;\n      try apply in_combine_l in Huv as Hu';\n      try apply in_combine_r in Huv as Hv';\n      contradiction.\nQed.\n\nLemma flipper_combine_map_fst : forall {U V : Set} (us : list U) (vs : list V),\n    map fst (flipper (combine us vs)) =\n    firstn (min (length us) (length vs)) vs.\nProof.\n  intros U V us vs.\n  rewrite flipper_combine.\n  rewrite combine_map_fst.\n  f_equal. lia.\nQed.\n\nLemma flipper_combine_map_snd : forall {U V : Set} (us : list U) (vs : list V),\n    map snd (flipper (combine us vs)) =\n    firstn (min (length us) (length vs)) us.\nProof.\n  intros U V us vs.\n  rewrite flipper_combine.\n  rewrite combine_map_snd.\n  f_equal; lia.\nQed.\n\nLemma combine_map_l :\n  forall {U V W : Set} (f : U -> W) (us : list U) (vs : list V),\n    combine (map f us) vs = map (fun '(u,v) => (f u,v)) (combine us vs).\nProof.\n  intros U V W f us; induction us as [| u us IHus];\n    intros [| v vs]; simpl; f_equal; auto.\nQed.\n\nLemma combine_map_r :\n  forall {U V W : Set} (f : V -> W) (us : list U) (vs : list V),\n    combine us (map f vs) = map (fun '(u,v) => (u,f v)) (combine us vs).\nProof.\n  intros U V W f us; induction us as [| u us IHus];\n    intros [| v vs]; simpl; f_equal; auto.\nQed.\n\nLemma in_combine_flip :\n  forall {U V : Set} us vs (u : U) (v : V),\n    In (u,v) (combine us vs) -> In (v,u) (combine vs us).\nProof.\n  intros U V us; induction us as [| hu us IHus];\n    intros [| hv vs] u v Hin; simpl in *;\n      try contradiction.\n  destruct Hin as [Huv | Hin]; try inv Huv; auto.\nQed.\n\nLemma nodup_nth_error : forall (A : Set) l,\n    NoDup l ->\n    forall m n (a : A),\n      nth_error l m = Some a ->\n      nth_error l n = Some a -> m = n.\nProof.\n  intros A l Hnd; induction Hnd;\n    intros [| m] [| n] h Hm Hn; simpl in *;\n      try discriminate; auto.\n  - inv Hm; apply nth_error_In in Hn; contradiction.\n  - inv Hn; apply nth_error_In in Hm; contradiction.\n  - f_equal; eauto.\nQed.\n\n(** My contribution to the standard library. *)\nSection CuttingMap.\n  Context {A B : Set}.\n  Variable (f : A -> B).\n  \n  Lemma firstn_map : forall n l,\n      firstn n (map f l) = map f (firstn n l).\n  Proof.\n    intro n; induction n as [| n IHn];\n      intros [| a l]; simpl in *; f_equal; auto.\n  Qed.\n\n  Lemma skipn_map : forall n l,\n      skipn n (map f l) = map f (skipn n l).\n  Proof.\n    intro n; induction n as [| n IHn];\n      intros [| a l]; simpl in *; f_equal; auto.\n  Qed.\nEnd CuttingMap.\n\nSection FilterMap.\n  Context {A B : Set}.\n\n  Section FM.\n    Variable (f : A -> option B).\n\n    Fixpoint filtermap (l : list A) : list B :=\n      match l with\n      | []    => []\n      | a :: l => match f a with\n                | Some b => [b]\n                | None   => []\n                end ++ filtermap l\n      end.\n\n    Lemma filtermap_app : forall l1 l2,\n        filtermap (l1 ++ l2) = filtermap l1 ++ filtermap l2.\n    Proof.\n      intro l1; induction l1 as [| a l1 IHl1]; intro l2; simpl; auto.\n      rewrite <- app_assoc, <- IHl1; f_equal.\n    Qed.\n\n    Lemma filtermap_fold_right : forall l,\n        filtermap l =\n        fold_right\n          (fun a acc =>\n             match f a with\n             | Some b => [b]\n             | None   => []\n             end ++ acc) [] l.\n    Proof.\n      intro l; induction l as [| a l IHl]; simpl; auto.\n    Qed.\n\n    Lemma in_filtermap : forall l a b,\n        f a = Some b -> In a l -> In b (filtermap l).\n    Proof.\n      intro l; induction l as [| h l IHl];\n        intros a b Hfab Hin; simpl in *;\n          try contradiction.\n      rewrite in_app_iff.\n      destruct Hin as [? | Hin]; subst;\n        try rewrite Hfab; simpl; firstorder.\n    Qed.\n\n    Fixpoint separate (l : list A) : list A * list B :=\n      match l with\n      | []    => ([], [])\n      | a :: l =>\n        let (la,lb) := separate l in\n        match f a with\n        | Some b => (la, b :: lb)\n        | None   => (a :: la, lb)\n        end\n      end.\n\n    Lemma separate_filtermap : forall l,\n        snd (separate l) = filtermap l.\n    Proof.\n      intro l; induction l as [| a l IHl]; simpl; auto.\n      destruct (separate l) as [us vs] eqn:Huvs;\n        destruct (f a) as [b |] eqn:Hfabeq;\n        simpl in *; f_equal; auto.\n    Qed.\n\n    Lemma in_snd_separate : forall l a b,\n        f a = Some b -> In a l -> In b (snd (separate l)).\n    Proof.\n      intros l a b.\n      rewrite separate_filtermap.\n      eauto using in_filtermap.\n    Qed.\n\n    Lemma in_fst_separate : forall l a,\n        f a = None -> In a l -> In a (fst (separate l)).\n    Proof.\n      intro l; induction l as [| h l IHl];\n        intros a Hfa Hin; simpl in *; try contradiction.\n      specialize IHl with a.\n      destruct (separate l) as [la lb] eqn:Hsep.\n      destruct (f h) as [b |] eqn:Hfh;\n        destruct Hin as [? | Hin]; subst; simpl in *; intuition.\n      rewrite Hfa in Hfh; discriminate.\n    Qed.\n\n    Lemma in_fst_separate_in_orig : forall l a,\n        In a (fst (separate l)) -> In a l.\n    Proof.\n      intro l; induction l as [| h l IHl];\n        intros a Hin; simpl in *; auto.\n      destruct (separate l) as [la lb] eqn:Hsep; simpl in *.\n      destruct (f h) as [b |] eqn:Hfhb; simpl in *;\n        intuition.\n    Qed.\n\n    Lemma not_in_fst_separate : forall l a b,\n        f a = Some b -> In a l -> ~ In a (fst (separate l)).\n    Proof.\n      intro l; induction l as [| h l IHl];\n        intros a b Hfab Hal Hafsl; simpl in *; auto.\n      destruct (separate l) as [la lb] eqn:Hsep.\n      destruct (f h) as [bh |] eqn:Hfhb; simpl in *;\n        destruct Hal as [? | Hal]; subst.\n      - rewrite Hfab in Hfhb; inv Hfhb.\n        assert (Hal: In a l).\n        { replace la with (fst (separate l)) in Hafsl.\n          - auto using in_fst_separate_in_orig.\n          - rewrite Hsep; reflexivity. }\n        firstorder.\n      - firstorder.\n      - rewrite Hfab in Hfhb; discriminate.\n      - destruct Hafsl as [? | Hala]; subst; firstorder.\n        rewrite Hfab in Hfhb; discriminate.\n    Qed.\n\n    Lemma separate_app : forall l1 l2,\n        separate (l1 ++ l2) =\n        let (us1, bs1) := separate l1 in\n        let (us2, bs2) := separate l2 in\n        (us1 ++ us2, bs1 ++ bs2).\n    Proof.\n      intro l1; induction l1 as [| a l1 IHl1]; intro l2; simpl.\n      - destruct (separate l2); auto.\n      - specialize IHl1 with l2;\n          destruct (separate (l1 ++ l2)) as [us bs] eqn:Heql;\n          destruct (separate l1) as [us1 bs1] eqn:Heql1;\n          destruct (separate l2) as [us2 bs2] eqn:Heql2;\n          inv IHl1; destruct (f a) as [b |] eqn:Heqfab;\n            simpl in *; repeat f_equal.\n    Qed.\n  End FM.\nEnd FilterMap.\n", "meta": {"author": "rudynicolop", "repo": "Type-Reconstruction", "sha": "c2455ced75254a40846d6b28992761480f277ab8", "save_path": "github-repos/coq/rudynicolop-Type-Reconstruction", "path": "github-repos/coq/rudynicolop-Type-Reconstruction/Type-Reconstruction-c2455ced75254a40846d6b28992761480f277ab8/vtr/coq/lib/Util/ListLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.7743099875332448}}
{"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\nFixpoint nonZeros(n:natlist) : natlist :=\nmatch n with\n| [] => []\n| x :: xs => match x with\n    | 0 => nonZeros(xs)\n    | _ => x :: nonZeros(xs)\n    end\nend.\n\nTheorem distr_rev : 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\nLemma nonZerosLemma : forall l1 l2 : natlist, nonZeros (l1 ++ l2 ) = (nonZeros l1 ) ++ (nonZeros l2 ).\nProof.\nintros l1 l2.\ninduction l1.\nsimpl. reflexivity.\nsimpl. \ndestruct n.\nsimpl. rewrite IHl1.\nreflexivity.\nsimpl. rewrite IHl1.\nreflexivity.\nQed.\n\n\n\nEval compute in( nonZeros [0;1;2;0;0;4;5;0]).\nEval compute in( nonZerosLemma [0;1;2;0;0;4;5;0] [0;1;2;0]).\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/6_nonzeros_app/nonZerosLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7743099690981843}}
{"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.\nRequire Import Permutation.\nRequire Import Arith.\n\nRequire Omega.\n\nRequire Import list_aux.\nRequire Import list_perm.\n\nSet Implicit Arguments.\n\n(* list product *)\n\nSection list_prod.\n\n  Variables (A B C : Type) (f : A -> B -> C).\n\n  (* list_prod [a1;...;an] [b1;...;bm] = [f a1 b1; f a2 b1;...;f an b1;f a1 b2;...;f an b2;...;f a1 bm;...;f an bm] *)\n\n  Definition list_prod ll mm := flat_map (fun y => map (fun x => f x y) ll) mm.\n\n  Fact list_prod_spec ll mm : forall c, In c (list_prod ll mm) <-> exists a b, In a ll /\\ In b mm /\\ c = f a b.\n  Proof.\n    intros c; split; unfold list_prod;\n    rewrite in_flat_map.\n    intros (b & H1 & H2).\n    rewrite in_map_iff in H2.\n    destruct H2 as (a & H2 & H3).\n    exists a, b; auto.\n    intros (a & b & H1 & H2 & H3).\n    exists b; split; auto.\n    rewrite in_map_iff.\n    exists a; auto.\n  Qed.\n\n  Fact list_prod_length ll mm : length (list_prod ll mm) = length ll * length mm.\n  Proof.\n    rewrite mult_comm; induction mm; simpl; auto.\n    rewrite app_length, map_length; f_equal; auto.\n  Qed.   \n  \n  Fact list_prod_nil ll mm : list_prod ll mm = nil -> ll = nil \\/ mm = nil.\n  Proof.\n    intros H.\n    apply f_equal with (f := @length _) in H.\n    rewrite list_prod_length in H; simpl in H.\n    destruct ll; auto.\n    destruct mm; auto.\n    simpl in H; discriminate H.\n  Qed.\n\n  Fact list_prod_nil_left mm : list_prod nil mm = nil.\n  Proof.\n    induction mm; simpl; f_equal; auto.\n  Qed.\n\n  Fact list_prod_nil_right ll : list_prod ll nil = nil.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Fact list_prod_sg_right ll x : list_prod ll (x::nil) = map (fun a => f a x) ll.\n  Proof.\n    symmetry; apply app_nil_end.\n  Qed.\n\n  Fact list_prod_app_left ll mm nn : list_prod (ll++mm) nn ~p list_prod ll nn ++ list_prod mm nn.\n  Proof.\n    induction nn as [ | x nn IH ]; simpl.\n    apply perm_nil.\n    rewrite map_app, app_ass, app_ass.\n    apply Permutation_app; auto.\n    apply Permutation_trans with (1 := Permutation_app_head _ IH).\n    do 2 rewrite <- app_ass.\n    apply Permutation_app; auto.\n    apply Permutation_app_comm.\n  Qed.\n\n  Fact list_prod_app_right ll mm nn : list_prod ll (mm++nn) ~p list_prod ll mm ++ list_prod ll nn.\n  Proof.\n    unfold list_prod; rewrite flat_map_app; apply Permutation_refl.\n  Qed.\n  \n  Fact list_prod_cons_left a ll mm : list_prod (a::ll) mm ~p list_prod (a::nil) mm ++ list_prod ll mm.\n  Proof.\n    apply (list_prod_app_left (a::nil)).\n  Qed.\n\n  Fact list_prod_cons_right ll a mm : list_prod ll (a::mm) ~p list_prod ll (a::nil) ++ list_prod ll mm.\n  Proof.\n    apply (list_prod_app_right _ (a::nil)).\n  Qed.\n  \n  Let list_prod_perm_left ll mm nn : ll ~p mm -> list_prod ll nn ~p list_prod mm nn.\n  Proof.\n    intros; apply flat_map_perm.\n    intros; apply Permutation_map; assumption.\n  Qed.\n  \n  Let list_prod_perm_right nn ll mm : ll ~p mm -> list_prod nn ll ~p list_prod nn mm.\n  Proof.\n    induction 1 as [ | | | l1 l2 l3 _ IH1 ]; simpl.\n    apply perm_nil.\n    apply Permutation_app; auto.\n    do 2 rewrite app_assoc.\n    apply Permutation_app.\n    apply Permutation_app_comm.\n    apply Permutation_refl.\n    apply Permutation_trans with (1 := IH1); auto.\n  Qed.\n\n  (* list_prod is congruent under permutations *)\n\n  Fact list_prod_perm l1 l2 m1 m2 : l1 ~p l2 -> m1 ~p m2 -> list_prod l1 m1 ~p list_prod l2 m2.\n  Proof.\n    intros H1 H2.\n    apply Permutation_trans with (1 := list_prod_perm_left _ H1).\n    apply list_prod_perm_right; auto.\n  Qed.\n\nEnd list_prod.\n\nFact list_prod_map A A' B B' C (p : A' -> B' -> C) (f : A -> A') (g : B -> B') l m : \n     list_prod (fun a b => p (f a) (g b)) l m = list_prod p (map f l) (map g m).\nProof.\n  induction m; simpl; f_equal; auto.\n  rewrite map_map; auto.\nQed.\n  \nFact map_list_prod A B C C' (p : A -> B -> C) (f : C -> C') l m : map f (list_prod p l m) = list_prod (fun a b => f (p a b)) l m.\nProof.\n  induction m; simpl; f_equal; auto.\n  rewrite map_app.\n  f_equal; auto.\n  rewrite map_map; 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_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.7743099668420715}}
{"text": "\nDefinition relation T := T -> T -> Prop.\n\nDefinition reflexive {T} (R: relation T) := forall t: T, R t t.\nDefinition transitive {T} (R: relation T) := forall s t u: T, R s t -> R t u -> R s u.\n\n(* R1 is subset of R2 *)\nDefinition rel_subset {T} (R1 R2: relation T) :=\n  forall a b, R1 a b -> R2 a b.\n\nDefinition closure {T} (R Rc: relation T) (P: relation T -> Prop) : Prop :=\n  rel_subset R Rc ->\n  (forall Rc', (rel_subset R Rc') -> P Rc' -> (rel_subset Rc Rc')).\n\nDefinition rel_union {T} (R1 R2: relation T) : relation T :=\n  fun a b => R1 a b \\/ R2 a b.\n\nDefinition eq_rel {T} : relation T := (fun a b => a = b).\n\nDefinition reflexive_closure {T} (R: relation T) : relation T :=\n  rel_union eq_rel R.\n\n(* ex 2.2.6 *)\nLemma reflexive_closure_proof :\n  forall T R, @closure T R (@reflexive_closure T R) reflexive.\nProof.\n  intros.\n  unfold closure, reflexive_closure, reflexive, rel_subset, rel_union, eq_rel, relation in *.\n  intros.\n  destruct H2.\n  - subst. auto.\n  - auto.\nQed.\n\nFixpoint transitive_closure' {T} (R: relation T) (n : nat) : relation T :=\n  match n with\n  | 0 => R\n  | S n => let Rn := transitive_closure' R n\n          in rel_union Rn (fun a b => exists c, Rn a c /\\ Rn c b)\n  end.\n\nDefinition transitive_closure {T} (R: relation T) : relation T :=\n  fun a b => exists n, transitive_closure' R n a b.\n\n(* ex 2.2.7 *)\nLemma transitive_closure_proof :\n  forall T R, @closure T R (@transitive_closure T R) transitive.\nProof.\n  intros.\n  unfold closure, transitive_closure, transitive, rel_subset, rel_union, eq_rel, relation in *.\n  intros.\n  destruct H2 as [n ?].\n  generalize dependent a.\n  generalize dependent b.\n  induction n; intros.\n  - auto.\n  - simpl in H2.\n    unfold closure, transitive_closure, transitive, rel_subset, rel_union, eq_rel, relation in *.\n    destruct H2.\n    + auto.\n    + destruct H2. destruct H2.\n      eauto.\nQed.\n\nDefinition preserves {T} (R: relation T) (P: T -> Prop) :=\n  forall t t', P t -> R t t' -> P t'.\n\n(* ex 2.2.8 *)\nLemma preserves_reflexive_closure :\n  forall {T} (R : relation T) (P: T -> Prop),\n    preserves R P -> preserves (reflexive_closure R) P.\nProof.\n  intros.\n  unfold preserves, reflexive_closure, rel_union, eq_rel in *.\n  intros.\n  destruct H1; subst; eauto.\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/set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.7743099584742004}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq.\nFrom ssrintro Require Import intro.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Programmers rely on testing to ensure that their code behaves as expected,\n    but this is often too weak to catch errors -- as Dijkstra used to put it,\n    \"testing shows the presence, not the absence of bugs\".  In this chapter, we\n    will start to use Coq to write precise specifications about programs and\n    formally verify that they are valid.\n\n\n    * Proof by Simplification\n\n    Consider the following (very simple) verification task: we would like to\n    ensure that the expression [is_empty Leaf] evaluates to [true].  We can\n    state this claim in Coq with the [Lemma] command. *)\n\nLemma is_empty_leaf : is_empty Leaf = true.\n\n(** This command tells Coq that we want to prove a statement called\n    [is_empty_leaf] asserting that [is_empty Leaf] is equal to [true].  We can\n    see now that Coq's interface changed a bit, displaying our claim in a\n    separate window.  Our goal is to convince Coq that this claim holds.  The\n    [Proof] command marks the beginning of our proof.  (It is not needed,\n    strictly speaking, but it is considered good style to include it.) *)\n\nProof.\n\n(** To write proofs, we use special commands called _tactics_.  Each tactic\n    transforms the goal a little bit, applying inference steps that (hopefully)\n    bring us towards a state where our claim becomes obvious enough to Coq.  Coq\n    checks that each argument is sound according to the rules of its logic and\n    rejects any invalid proofs.\n\n    Our first tactic is [rewrite /=], which attempts to simplify the current\n    goal by roughly expanding definitions and performing trivial computation\n    steps.  Recall that we defined [is_empty_left] with a [match] expression\n    that returned [true] whenever applied to [Leaf]; thus, it makes sense to try\n    to replace [is_empty_leaf Leaf] with [true]. *)\n\nrewrite /=.\n\n(** We can see that the previous goal became [true = true].  This statement is\n    obvious enough for Coq to accept without further help.  To complete the\n    proof, we use the [done] tactic: *)\n\ndone.\n\n(** Coq now tells us that there are no more subgoals, which means that there is\n    nothing else left to prove.  We conclude our proof with the [Qed] command,\n    records [is_empty_left] as a true statement.  We can convince ourselves that\n    Coq believes in our claim by issuing the [Check] command. *)\n\nQed.\n\nCheck is_empty_leaf.\n\n(** This first example property may seem a bit disappointing, given that we\n    could have checked it by simply asking Coq to evaluate [is_empty Leaf] for\n    us.  In that sense, we have not gained anything compared to a conventional\n    testing infrastructure.  For a slightly more interesting example, let us\n    prove something about the behavior of _infinitely many programs_: *)\n\nLemma is_empty_node t1 n t2 : is_empty (Node t1 n t2) = false.\nProof. rewrite /=. done. Qed.\n\n(** To better understand how simplification is performed, consider the following\n    function and properties. *)\n\nDefinition singleton n := Node Leaf n Leaf.\n\nLemma tsize1 n : tsize (singleton n) = 1.\nProof.\n\n(** Writing [rewrite -[x]/(y)] instructs Coq to replace all occurrences of [x]\n    by [y] in the current goal, provided that both expressions are equivalent\n    according to the computation rules of Coq's logic. In the line below, Coq\n    understands that both terms are equal because the second is exactly what we\n    gave for the definition of [singleton]. *)\n\nrewrite -[singleton n]/(Node Leaf n Leaf).\n\n(** Here, we can see that [rewrite] is a more general tactic that takes many\n    possible actions as arguments, which have slightly different effects.\n\n    We can perform a similar exercise for [tsize], and replace the call to it by\n    its definition. *)\n\nrewrite -[tsize _]/(match Node Leaf n Leaf with\n                    | Leaf => 0\n                    | Node t1 _ t2 => tsize t1 + 1 + tsize t2\n                    end).\n\n(** Notice that we didn't specify the argument that was given to [tsize], and\n    just said [_] instead. Coq can often understand these incomplete patterns\n    from the context where they are used.\n\n    Simplifying the [match] expression is easy: since Coq knows the first\n    constructor used in the discriminee, it knows which branch to take. Here, we\n    use the [LHS] (short for _left-hand side_) pattern instead of writing the\n    entire term. *)\n\nrewrite -[LHS]/(tsize Leaf + 1 + tsize Leaf).\n\n(** Similar simplification steps show that [tsize Leaf] evaluates to [0]. *)\n\nrewrite -[tsize Leaf]/(0).\n\n(** At this point, we can conclude. *)\n\ndone.\nQed.\n\n(** Calling [done] after a tactic is so common that ssreflect offers special\n    syntax for it: if [t] is a tactic, then [by t] tries to execute [t] and to\n    conclude the proof afterwards by calling [done]. If the proof cannot be\n    complete, Coq raises an error. *)\n\nLemma tsize1' (n : nat) : tsize (singleton n) = 1.\nProof. by rewrite /=. Qed.\n\n(** As a matter of fact, the above proof is so simple that we don't even need to\n    tell Coq to simplify the goal; [done] alone suffices. Alternatively, we can\n    also write [by []] (that is, [by] with an \"empty\" first tactic) as a synonym\n    for [done]: *)\n\nLemma tsize1'' (n : nat) : tsize (singleton n) = 1.\nProof. done. Qed.\n\nLemma tsize1''' (n : nat) : tsize (singleton n) = 1.\nProof. by []. Qed.\n\n(** Before we move on to more interesting proofs, it is worth leaving a small\n    note on naming conventions: ssreflect tries to follow very consistent naming\n    conventions for its lemmas, which we will try to emulate here. The [1]\n    suffix on [tsize1], for instance, signals that this lemma relates [tsize] to\n    something of size [1]; in this case, a singleton tree. We will point to\n    other naming conventions as we progress.\n\n\n    * Using sections\n\n    Coq provides another mechanism for alleviating the burden of annotations:\n    _sections_. Sections allow us to declare certain parameters as being common\n    to all definitions and lemmas enclosed within it. Inside the section, these\n    parameters don't have to be redeclared and applied; when the section is\n    closed, on the other hand, all parameters become explicit.\n\n    Sections are opened with the [Section] keyword. Each section must be given a\n    name (in this case, [Ex]). *)\n\nSection Ex.\n\n(** Once we are inside a section, we can use the [Variable] command to declare a\n    parameter that will be shared by all definitions in the section. *)\n\nVariable T : Type.\n\n(** We can also associate variable names to certain types. After the following\n    command, Coq assumes that [x] has type [nat], unless otherwise\n    specified. This has the same effect for variables with \"similar\" names, such\n    as [x0] and [x']. *)\n\nImplicit Type x : nat.\n\n(** We can now write statements such as this one: *)\n\nLemma tsize1'''' n : tsize (singleton n) = 1.\nProof. by []. Qed.\n\n(** Notice that [x] had to be declared in the statement of the lemma, but that\n    we didn't have to supply its type. [T], on the other hand, didn't have to be\n    declared again.\n\n    If we check the lemma we just proved, we see that [T] is \"fixed\" (that is,\n    not universally quantified): *)\n\nCheck tsize1''''.\n\n(** Once we close the [Ex] section, we see that [T] becomes explicitly\n    quantified: *)\n\nEnd Ex.\n\nCheck tsize1''''.\n\n(** We will enclose some of the remaining material in a section with some\n    variable declarations and implicit types, to make our lives easier. *)\n\nSection Basic.\n\nVariable T : Type.\n\nImplicit Type (t : tree) (x : T).\n\n(** * Proof by case analysis\n\n    Often, simplification is not enough to complete a proof. For instance,\n    suppose that we have the following function [troot] which computes the\n    element stored in the root of a tree (notice that an empty tree has 0 at its\n    root by convention): *)\n\nDefinition troot t : nat :=\n  match t with\n  | Leaf => 0\n  | Node _ n _ => n\n  end.\n\n(** Clearly, the [tmirror] function defined above does not change the root of\n    the tree it is applied to. Let's try to convince Coq of this fact: *)\n\nLemma troot_tmirror t : troot (tmirror t) = troot t.\nProof.\n\n(** We can try to simplify the goal, but Coq won't be able to make any\n    progress. We can also try to use [done], to see if Coq accepts this fact on\n    its own, but it raises an error instead: *)\n\nrewrite /=. (* Nothing happens... *)\n(* done. *) (* Cannot finish the proof. *)\n\n(** The reason why simplification worked on the previous example, but cannot\n    make any progress here, is that Coq knew exactly what shape the result of\n    [singleton] has, because its definition started with a [Node]\n    constructor. In the current lemma, however, we are trying to prove something\n    about an _arbitrary_ tree [t], without any further information about what\n    [t] is. What we need is a way to consider all possible forms that [t] can\n    have, which we can accomplish with the [case] tactic: *)\n\ncase: t.\n\n(** The [case: t] call instructs Coq to do a proof by cases. The proof state now\n    shows that we need to complete two subgoals: one where [t] is replaced by\n    [Leaf], and another one where it is replaced by a tree that starts with the\n    [Node] constructor. We can proceed by proving each of the subgoals in\n    sequence. Following the ssreflect convention, we indent the proof of the\n    first subgoal by two spaces. Its proof follows by simplification. *)\n\n  rewrite /=.\n  by [].\n\n(** The second subgoal looks a little bit different: besides not mentioning [t]\n    anymore, our goal now contains additional universally quantified variables,\n    the arguments to the [Node] constructor. We can introduce these variables,\n    bringing them from the goal into the context by using the [move] tactic: *)\n\nmove=> t1 n t2.\n\n(** Each name given after the [=>] operator is used to name one universally\n    quantified variable present in the goal. We can now simplify our goal as\n    before and conclude. *)\n\nrewrite /=.\nby [].\nQed.\n\n(** Ssreflect allows us to combine some of these steps into a single tactic. For\n    instance, we can use [case] to name all constructor arguments and perform a\n    simplification automatically, like this: *)\n\nLemma troot_tmirror' t : troot (tmirror t) = troot t.\nProof.\ncase: t => [|t1 n t2] /=.\n\n(** The pattern enclosed by square brackets in the above tactic names the\n    arguments resulting from each constructor of [tree]. In the general case,\n    each group of variables separated by [|] corresponds to one\n    constructor. Since the [Leaf] constructor doesn't take any arguments, its\n    corresponding part in the pattern doesn't contain any variables.\n\n    The [/=] symbol tells Coq to attempt to simplify the goal _after_ doing case\n    analysis on [t]. We can see that the resulting goals can be solved\n    immediately: *)\n\n  by [].\nby [].\nQed.\n\n(** As a matter of fact, we didn't even have to name the constructor arguments,\n    since the [done] tactic is smart enough to do this by itself. *)\n\nLemma troot_tmirror'' t : troot (tmirror t) = troot t.\nProof. by case: t. Qed.\n\n(** Of course, in many cases we _do_ have to perform non-trivial reasoning steps\n    after calling [case]. We will encounter many examples of such proofs as we\n    make progress.\n\n\n    * Proof by rewriting\n\n    So far, we have done simple proofs showing that certain equations between\n    two expressions hold. We can also use these equations in other proofs to\n    show more results. This process is known as _rewriting_.\n\n    The [rewrite] tactic can be used not only with the [/=] symbol, which\n    performs simplification by computation, but also with any previously proved\n    equation. As a simple example, we can try to prove the following variant of\n    [troot_tmirror]: *)\n\nLemma troot_tmirror2 t : troot (tmirror (tmirror t)) = troot t.\nProof.\n\n(** This result is simple enough that a single call to [case] would suffice to\n    solve it, as in [troot_tmirror]. However, we can take a slightly different\n    approach, using [troot_tmirror] instead to rewrite on the left-hand side of\n    the equation. *)\n\nrewrite troot_tmirror.\nrewrite troot_tmirror.\nby [].\nQed.\n\n(** As we can see, each call to [rewrite] instantiated the [troot_tmirror]\n    lemma with a different tree value, successively removing calls to\n    [tmirror]. In the first rewrite, the tree value was instantiated to [tmirror\n    t], while in the second one, it was instantiated with [t] itself. Coq\n    performs unification to find out how to instantiate each lemma given to\n    [rewrite], but we can also explicitly instantiate our lemma by passing the\n    value we want to use as an argument to the theorem. This is useful when\n    there are multiple possible instantiations and Coq doesn't choose the one we\n    want by itself. *)\n\nLemma troot_tmirror2' t : troot (tmirror (tmirror t)) = troot t.\nProof.\nrewrite (troot_tmirror (tmirror t)).\nrewrite (troot_tmirror t).\nby [].\nQed.\n\n(** It is also possible to perform several rewrite steps at once: *)\n\nLemma troot_tmirror2'' t : troot (tmirror (tmirror t)) = troot t.\nProof. by rewrite troot_tmirror troot_tmirror. Qed.\n\n(** Alternatively, we can use the [!] flag to rewrite with a lemma as many times\n    as possible: *)\n\nLemma troot_tmirror2''' t : troot (tmirror (tmirror t)) = troot t.\nProof. by rewrite !troot_tmirror. Qed.\n\n(** Finally, we can prefix a lemma with a minus sign [-] to indicate that we\n    want to rewrite in the opposite direction: *)\n\nLemma troot_tmirror2'''' t : troot (tmirror (tmirror t)) = troot t.\nProof.\n\n(* Replace [troot t] by [troot (tmirror t)] *)\nrewrite -(troot_tmirror t).\n\n(* Replace [troot (tmirror t)] by [troot (tmirror (tmirror t))] *)\nrewrite -(troot_tmirror (tmirror t)).\n\nby [].\nQed.\n\n(** * Proof by induction\n\n    Coq is not smart enough to come up with its own inductive proofs. These are\n    done with the [elim] tactic.\n\n    At its simplest form, [elim] is just a more powerful version of [case] that\n    generates induction hypothesis for structurally smaller terms. Here's an\n    example. Suppose that we wanted to show that [tmirror] is its own\n    inverse. *)\n\nLemma tmirrorK t : tmirror (tmirror t) = t.\nProof.\n\n(** The [K] suffix in the name of this lemma stands for \"cancellation\", and is a\n    convention used by ssreflect to name similar results.\n\n    As with [case], when we call [elim: t], we get to provide names for the\n    arguments of each constructor. The difference is that every recursive\n    argument also generates an induction hypothesis, saying that the result we\n    are trying to prove is valid for that argument. Thus, in the tactic below,\n    [IH1] and [IH2] stand for the induction hypotheses that correspond to [t1]\n    and [t2]. Notice that we use the [/=] flag to simplify both subgoals. *)\n\nelim: t => [|t1 IH1 x t2 IH2] /=.\n\n(** The first subgoal corresponds to the [t = Leaf] case, and can be solved by\n    Coq automatically. *)\n\n  by [].\n\n(** When attacking the second subgoal, where [t] has the form [Node c t1 x t2],\n    we can see that our context looks a bit different. Besides the usual\n    arguments, it also contains the induction hypotheses [IH1] and [IH2], which\n    state that [tmirror (tmirror t1) = t1] and [tmirror (tmirror t2) = t2]. To\n    conclude this subgoal, we can rewrite with these hypotheses, as if they were\n    normal lemmas: *)\n\nrewrite IH1 IH2.\n\n(** Now, both sides of the equation are equal, and Coq accepts our proof. *)\n\nby [].\nQed.\n\n(** Ssreflect provides nice syntax for simplifying this proof. Since many cases\n    in a proof follow directly by simplification, we can use the [//] flag with\n    [elim] to tell Coq to try to close all goals it can with the [done]\n    tactic. *)\n\nLemma tmirrorK' t : tmirror (tmirror t) = t.\nProof.\nelim: t => [|t1 IH1 x t2 IH2] // /=.\nby rewrite IH1 IH2.\nQed.\n\n(** Both [//] and [/=] can be combined in a single flag, [//=]. *)\n\nLemma tmirrorK'' t : tmirror (tmirror t) = t.\nProof.\nelim: t => [|t1 IH1 x t2 IH2] //=.\nby rewrite IH1 IH2.\nQed.\n\n(** We can further condense this proof by performing some of the rewriting steps\n    directly after calling [elim]. When [->] is given as a name for a\n    hypothesis, this tells Coq to try to rewrite with that hypothesis. This\n    leads to the following proof: *)\n\nLemma tmirrorK''' t : tmirror (tmirror t) = t.\nProof. by elim: t => [|/= t1 -> x t2 ->]. Qed.\n\n(** Notice that, before rewriting with the induction hypotheses in the [Node]\n    branch, we perform a simplification step with [/=], so that Coq can find the\n    terms [tmirror (tmirror t1)] and [tmirror (tmirror t2)] in the goal.\n\n\n    * Propositions are first-class values\n\n    One interesting aspect of Coq's theory is that propositions are first-class\n    values that can be manipulated according to the same rules that are used for\n    other objects of the language. In particular, since Coq is a _typed_\n    language, all propositions have a type: [Prop]. For instance: *)\n\nCheck 1 = 1.\n\n(** Note that being a syntatically well-formed proposition does not imply that\n    this proposition is true. Hence, [0 = 1] also has type [Prop], even though\n    it corresponds to a false claim. *)\n\nCheck 0 = 1.\n(** Coq comes with a rich language for writing propositions. So far, we have\n    encountered the equality operator [=], and universal quantification\n    [forall], but there are many more. We will introduce more of them as we go\n    along.\n\n    We can define functions that return propositions, allowing us to develop\n    convenient abbreviations for common patterns.\n\n    As an example, we can define a function [cancel] that takes in two functions\n    [f] and [g] as arguments, and states that [g] is the left inverse of\n    [f]. Since [cancel] is already provided by ssreflect, we restate the\n    definition here with a different name, to avoid clashes. *)\n\nDefinition cancel' (S R : Type) (f : S -> R) (g : R -> S) : Prop :=\n  forall x : S, g (f x) = x.\n\n(** Notice that the [S] and [R] types are explicitly given as arguments to\n    [cancel]. However, because of the \"implicit arguments\" option we enabled at\n    the beginning of the file, we don't have to provide them most of the\n    time. For instance: *)\n\nLemma tmirrorK'''' : cancel tmirror tmirror.\nProof.\n\n(** To understand what's going on, it is sometimes useful to unfold the\n    definition of [cancel]. Simplification by default does not perform this kind\n    of unfolding, because it would create bigger and harder-to-understand proof\n    contexts. To unfold a term [foo], we use the [/foo] rewrite flag. For\n    instance (even though it won't affect the rest of the proof): *)\n\nrewrite /cancel.\n\n(** Since [cancel] has an explicitly quantified variable [x] in its definition,\n    we need to bring it into the context, much like we did after doing case\n    analysis. Of course, we can give [x] any name we like: *)\n\nmove=> t.\nby elim: t => [|/= t1 -> x t2 ->].\nQed.\n\n(** In situations like this, where we want our tactic to act on the first\n    quantified value on the goal, we can just call that tactic directly, without\n    having to introduce that value directly. In other words, tactics such as\n    [case] and [elim] always act implicitly on the first universally quantified\n    value in our goal, in stack-like fashion. *)\n\nLemma tmirrorK''''' : involutive tmirror.\nProof. by elim=> [|/= t1 -> x t2 ->]. Qed.\n\n(** Notice that we have used [involutive tmirror] instead of [tcancel tmirror\n    tmirror]. [involutive foo] is defined exactly as [cancel foo foo].\n\n    The reason we wrote [: t] on previous calls to [elim] is simple: the [:] is\n    actually a tactic operator, whose effect is to put some variables in the\n    context back in the goal. In this sense, it is the inverse of the [=>]\n    introduction operator. For instance: *)\n\nLemma tmirrorK'''''' : involutive tmirror.\nProof.\nmove=> t.\nmove: t.\nAbort.\n\n(** * Using previous results\n\n    Coq and ssreflect come with many definitions and lemmas about them. In order\n    to make effective use of Coq, it is important to know how to reuse this\n    infrastructure. Here is a simple example. Suppose that we wanted to prove\n    that mirroring a tree does not change its size. *)\n\nLemma tsize_tmirror t : tsize (tmirror t) = tsize t.\nProof.\n\n(** We could try to prove this by induction: *)\n\nelim: t => [|/= t1 -> x t2 ->] //.\n\n(** Here, we see that Coq was able to discharge the base case by itself, with\n    [//]. However, it was not able to get rid of the second one. Indeed, we can\n    see that the order of the summands on both sides is different:\n\n    [tsize t2 + 1 + tsize t1 = tsize t1 + 1 + tsize t2]\n\n    Unfortunately, ssreflect's [done] tactic does not perform this kind of\n    arithmetic reasoning by itself, and we must find previous results that will\n    allow us to show that these two terms are equal. Coq comes with a\n    [SearchAbout] command that can be used for looking up lemmas that mention\n    certain definitions. In this case, we want to be able to argue about\n    commutativity and associativity of [+]. As it turns out, ssreflect already\n    these notions for us: *)\n\nPrint commutative. (* [C-c C-a C-p] in Proof General *)\nPrint associative.\n\n(** We can then try to use [SearchAbout] to find lemmas that may help us\n    here. *)\n\nSearchAbout \"+\" commutative. (* [C-c C-a C-a] in Proof General *)\nSearchAbout \"+\" associative.\n\n(** Running these commands shows us that there are two lemmas, [addnC] and\n    [addnA], that we can use. You will notice that both lemmas mention a\n    function [addn] instead of the [+] operator. Coq comes with a notation\n    mechanism for changing the syntax of certain constructs. Thus, natural\n    number addition is actually defined as a function [addn], and only later we\n    issue a [Notation] command for using the nice infix syntax. Notice also that\n    we had to enclose [+] in quotes so that Coq can understand that we are\n    referring to a notation as opposed to a normal identifier. We will not\n    discuss the details of the [Notation] command right now, though, as it is a\n    bit complicated to explain. *)\n\nby rewrite addnC (addnC _ 1) addnA.\nQed.\n\n(** * Hypothetical statements\n\n    So far, we have seen how to prove facts that are always true. In many cases,\n    however, we are interested in facts that are only valid when certain\n    hypotheses hold. In Coq, we can express such hypothetical statements with\n    the implication operator [->]. For example: *)\n\nLemma tmirror_leaf t : tmirror t = Leaf -> t = Leaf.\n\n(** Each formula preceeding an arrow is a hypothesis that needs to be met for\n    the conclusion of the statement (the formula after [->]) to hold. In this\n    case, the lemma says that if the result of [tmirror t] is [Leaf], then [t]\n    itself must be equal to [Leaf].\n\n    We can use the [=>] operator to name hypotheses that appear in the goal and\n    bring them into the context. This allows us to use a hypothesis like we used\n    previous lemmas or induction hypotheses: *)\n\nProof.\nmove=> e.\n\n(** We can use [tmirrorK] to replace [t] by [tmirror (tmirror t)]. *)\n\nrewrite -(tmirrorK t).\n\n(** Thanks to our hypothesis, we can now bring the goal to a more palatable\n    form. *)\n\nrewrite e.\n\n(** Since [tmirror Leaf] is equal to [Leaf] by simplification, Coq can conclude\n    directly. *)\n\nby [].\nQed.\n\n(** This shows how to prove hypothetical results. It is also possible to use\n    hypothetical results to prove other statements; this in turn requires that\n    we prove separately each hypothesis in that statement. *)\n\nLemma tmirror_leaf2 t : tmirror (tmirror t) = Leaf -> t = Leaf.\nProof.\nmove=> e.\n\n(** Since the [tmirror_leaf] lemma used below has a hypothesis, the rewrite\n    below generates two subgoals: [Leaf = Leaf] and [tmirror t = Leaf]. The\n    first one is trivial, and can be discharged directly with [//]. Notice*)\n\nrewrite (@tmirror_leaf t) //.\n\n(** Alternatively, if the goal matches exactly the conclusion of a lemma or\n    hypothesis in the context, we can use the [apply] tactic. Once again, if the\n    result we apply has any hypotheses, we will have to solve them as separate\n    subgoals. *)\n\napply: tmirror_leaf.\nby [].\n\n(** In this case, choosing between [rewrite] and [apply] was (almost) just a\n    matter of style. It is important to notice, however, that both tactics are\n    usually not interchangeable. [rewrite] only works with statements whose\n    conclusions are equalities, and performs a small modification on the\n    goal. [apply], on the other hand, works with goals that involve _arbitrary_\n    logical constructs, not just equalities. It will be more useful once we\n    learn more about Coq's logic.\n\n    Besides using lemmas as functions to specify the value of universally\n    quantified variables, we can use function application syntax to supply\n    hypotheses. We can use this feature to prove the previous theorem with a\n    single call to [apply]. *)\n\nRestart.\nmove=> e.\nby apply: (tmirror_leaf (tmirror_leaf e)).\n\n(** Instead of using [by apply], we can also use [exact]. There are subtle\n    differences between the two, but for now we can think of [exact] as a\n    shorter version of [by apply]. *)\n\nRestart.\nmove=> e.\nexact: (tmirror_leaf (tmirror_leaf e)).\nQed.\n\n(** * Forward reasoning tactics\n\n    Coq's primary style of interaction is backwards: we progressively simplify\n    the goal, until it reaches a state where it can be solved trivially. Often,\n    it is more convenient to reason _forward_ instead: progressively deduce more\n    and more complex facts from the hypotheses that we have, until some of them\n    can apply directly to the goal.\n\n    In ssreflect, the two primary forward-reasoning tactics are [have] and\n    [suffices]. When we write [have e: P], Coq adds a new intermediate subgoal\n    where it asks for a proof of [P]. Once we complete the proof, it resumes the\n    original subgoal, enriching the context with a new hypotheses [e : P]. We\n    can use [have] to write an alternative proof of [tmirror_leaf2]: *)\n\nLemma tmirror_leaf2' t : tmirror (tmirror t) = Leaf -> t = Leaf.\nProof.\nmove=> e.\nhave e': tmirror t = Leaf.\n  by apply: tmirror_leaf.\nby apply: (tmirror_leaf e').\n\n(** It is important to notice that the [:] symbol used in [have] is unrelated to\n    the use of [:] in tactics such as [apply], [move] and [case]: in [have], its\n    purpose is to state the intermediate result we want to prove, while in the\n    other tactics we have seen it moves variables and hypotheses from the\n    context into the goal.\n\n    If the intermediate proof used with [have] is short, we can condense it into\n    a single tactic, using the [by] keyword. *)\n\nRestart.\nmove=> e.\nhave e': tmirror t = Leaf by apply: tmirror_leaf.\nby apply: (tmirror_leaf e').\n\n(** The [suffices] tactic is similar to [have]. Its main difference is that it\n    reverses the order of the generated subgoals: the first subgoal is augmented\n    with the new fact, while the second one asks of the proof of that auxiliary\n    fact. Compare: *)\n\nRestart.\nmove=> e.\nsuffices e': tmirror t = Leaf.\n  by apply: (tmirror_leaf e').\nby apply: tmirror_leaf.\n\n(** We are also allowed to merge the proof of the first subgoal into the call to\n    [suffices]: *)\n\nRestart.\nmove=> e.\nsuffices e': tmirror t = Leaf by apply: (tmirror_leaf e').\nby apply: tmirror_leaf.\nQed.\n\n(** The [suffices] tactic is useful when the proof of the auxiliary statement is\n    more complicated than the part that uses it. Its name is meant to mimic the\n    usual pattern seen in mathematical proofs: \"To show A, it suffices to show\n    B, because [short argument follows]. Let's then prove B.\" *)\n\nEnd Basic.\n\n(** Before discussing more interesting operations on trees, it is worth having a\n    tour of some of the basic types and operations provided by Coq and\n    ssreflect.\n\n\n    * Booleans\n\n    Coq defines [bool] as an inductive data type with two constructors: [true]\n    and [false]. In that sense, it is equivalent to the definition of the\n    [color] type above. *)\n\nPrint bool.\n\n(** We can perform case analysis on a boolean with the familiar if-then-else\n    syntax: *)\n\nCompute if true then 1 else 2.\n\n(** This form is just a shorthand to an explicit [match]: *)\n\nCompute match true with true => 1 | false => 2 end.\n\n(** Many standard boolean operations are already defined for us. We write [&&],\n    [||] and [~~] for the \"and\", \"or\", and \"not\" functions. *)\n\nCheck true && true.\nCheck (true || ~~ false).\n\n(** The [case] tactic can be used to do a proof by cases on members of any\n    inductively defined type, including [bool]. *)\n\nLemma andbF' b : b && false = false.\nProof.\n\n(** Coq cannot solve this goal by itself because [&&] is defined by case\n    analysis on its first argument: *)\n\nPrint andb.\n\n(** If we do case on [b], on the other hand, the goal becomes trivial. We can\n    see that [b] is replaced by [true] and [false] on each generated subgoal: *)\n\ncase: b.\n  by [].\nby [].\nQed.\n\n(** Ssreflect provides an [andbF] lemma whose statement is similar to the one\n    above. The name [andbF] means that the lemma talks about what happens when\n    we compute the [and] of an arbitrary boolean [b] and [false] ([F]). (Can you\n    guess what [andFb] states? What about [andbT]?).\n\n\n    * Natural numbers\n\n    We have already seen some definitions involving natural numbers. Unlike\n    other languages, where numeric types are often primitive, [nat] in Coq is\n    just another inductive data type. It is defined as the type having one\n    constructor [O], representing zero, and one constructor [S : nat -> nat],\n    which represents the successor of a number. *)\n\nPrint nat.\n\n(** Coq allows us to write elements of [nat] with conventional arabic\n    notation. This feature is just for making programming with [nat] more\n    convenient: internally, natural numbers are still represented with [S] and\n    [O]. *)\n\nCheck 2.\nCheck S (S O).\n\n(** Additionally, ssreflect uses [n.+1] as special syntax for [S n]: *)\n\nCheck 0.+1.+1.\n\n(** We can also use [n.+2], [n.+3] and [n.+4]. *)\n\nCheck 0.+2.\n\n(** For instance, here's how we can define a function for computing the\n    Fibonacci numbers: *)\n\nFixpoint fib_aux n acc1 acc2 :=\n  if n is n'.+1 then fib_aux n' acc2 (acc1 + acc2)\n  else acc2.\n\nDefinition fib n := fib_aux n 0 1.\n\nCompute fib 8.\n\n(** This definition also uses a different syntax for doing pattern matching. [if\n    e is p then e1 else e2] is just a synonym for [match e with p => e1 | _ =>\n    e2]. If it is not obvious for you that this function defines the Fibonacci\n    numbers, check the exercise at the end of the chapter.\n\n    We can subtract two numbers by using the [subn] function, written as the\n    familiar infix operator [-]. It is worth noting that, because [nat] doesn't\n    contain negative values, subtraction on [nat] is _truncated_: if [n] is less\n    than [m], then [n - m = 0]. *)\n\nCompute 2 - 4.\n\n(** We can test whether a number is less than other with the [<=] operator: *)\n\nCompute 2 <= 4.\nCompute 4 <= 2.\n\n(** We can also write [n < m], which is just special syntax for [n.+1 <= m]. *)\n\nCheck (2 + 3).+1 <= 5.\n\n(** When used with a [nat], the [case] tactic behaves similarly to [tree] or\n    [bool]: it generates subgoals corresponding to the [O] and [S]\n    constructors. The [elim] tactic also works with members of [nat], generating\n    an induction hypothesis for the [S] case. Here is a proof of the [addnA]\n    lemma we have used above. *)\n\nLemma addnA' : associative addn.\nProof.\nmove=> n m p.\nelim: n => [|n IH] //=.\nrewrite addSn IH.\nby [].\nQed.\n\n(** * Sequences\n\n    Like other functional programming languages, ssreflect provides a data type\n    [seq] of finite sequences, or lists. To use it, you must import the\n    [Ssreflect.seq] library. This type is parameterized over the type of\n    elements contained in the sequence; hence, elements of [seq nat] are\n    sequences of natural numbers, while elements of [seq bool] are sequences of\n    booleans.\n\n    As in other languages, the [seq] type is generated by two constructors:\n    [nil], which denotes an empty sequence, and [cons], which adds an element at\n    the beginning of some other sequence. For those, Ssreflect provides the\n    notations [[::]] and [::]. For example, the sequence consisting of the\n    natural numbers [1], [2], and [3] is written as follows: *)\n\nCheck 1 :: 2 :: 3 :: [::].\n\n(** Notice that Coq prints the above expression in a slightly different form. In\n    ssreflect, we can refer to a literal sequence [e1 :: .. :: en :: [::]] using\n    the notation [[:: e1; .. ; en]]: *)\n\nCheck [:: 1; 2; 3].\n\n(** The [++] operator concatenates two sequences. *)\n\nCheck [:: true; false] ++ [:: true].\n\n(** The [seq] library defines many common operations on sequences for us. The\n    familiar [map] function applies some function [f] to all elements of a\n    sequence [s]. Here, the [fun n => e] expression is Coq's syntax for an an\n    _anonymous function_ that takes [n] as an argument and produces [e] as its\n    result. *)\n\nCheck map (fun n => [:: n]) [:: 1; 2; 3].\n\n(** Ssreflect has support for a limited form of _list comprehension_ syntax,\n    similar to Haskell's. We can see that the above expression is printed\n    slightly different by Coq when we execute [Check]: *)\n\nCheck [seq [:: n] | n <- [:: 1; 2; 3]].\n\n(** Unfortunately, Coq's notation mechanism is not powerful enough to define a\n    flexible, generic equivalent of the list comprehension syntax. Thus,\n    ssreflect defines special syntax for only a handful of expressions involving\n    sequences. You can read more about them in the documentation of the [seq]\n    library.\n\n    Since [seq] is generated by [nil] and [cons], doing case analysis or\n    induction on a sequence will generate two cases: one for [nil] and one for\n    [cons]. For example: *)\n\nLemma catA' T : associative (@cat T).\nProof.\nmove=> s1 s2 s3.\nelim: s1 => [|x s1 IH] /=.\n  by []. (* [nil] case *)\nby rewrite IH. (* [cons] case *)\nQed.\n\n(** (Can you make the above proof shorter?)\n\n    Finally, ssreflect provides an operator [\\in] for testing whether an element\n    occurs in a sequence. *)\n\nCheck 1 \\in [:: 1; 2; 3].\n\n(** The [\\in] operator is actually defined not just for sequences, but for any\n    type supporting a \"membership test\" operation. In the case of sequences, we\n    can only test for membership of elements of some [eqType], which is a Coq\n    type equipped with a boolean operation for testing equality. We will come\n    back to [eqType] in more detail later; for now, you only need to know that\n    ssreflect defines such operations for many basic types, including [nat],\n    [seq], among others.\n\n\n    * Reasoning about constructors\n\n    Intuitively, there are two properties that we expect to hold of data\n    constructors. The first one is that constructors are _disjoint_: if we\n    construct two values using different constructors, the two values must be\n    different. The second one is that constructors are _injective_: whenever two\n    expressions involving the same constructor are equal, we can conclude that\n    the arguments given to the constructors are equal. These principles are\n    validated by Coq's logic, and are useful for proving many results; we\n    discuss a few examples here to show how they work.\n\n    Suppose we wanted to prove the following result: *)\n\nLemma eq_map_nil T S (f : T -> S) s :\n  [seq f x | x <- s] = [::] ->\n  s = [::].\n\n(** We can argue by case analysis. Since [seq] is generated by [nil] and [cons],\n    [s] can have to forms: [[::]] and [x :: s'], for some values [x] and\n    [s']. *)\n\nProof.\ncase: s=> [|x s'] /=.\n\n(** We can see that the first case was reduced to [[::] = [::] -> [::] =\n    [::]]. Since the conclusion is trivial, [done] suffices: *)\n\n  by [].\n\n(** The second case is more interesting: our goal wants us to conclude\n    that [x :: s' = [::]], which is clearly false. However, the\n    hypothesis in our goal now equates two expressions that start with\n    different constructors:\n\n    [f x :: [seq f x' | x' <- s'] = [::]]\n\n    This hypothesis is now absurd, which means that this case can actually never\n    occur. The [done] tactic can detect this situation and remove the case from\n    further consideration, allowing us to conclude. In logic jargon, this is a\n    particular instance of the _principle of explosion_, which states that a\n    contradiction entails anything. *)\n\nby [].\nQed.\n\n(** (Can you make this proof shorter?)\n\n    The second principle, injectivity, is not handled by [done] by\n    default. Instead, ssreflect provides an introduction form for decomposing an\n    equality between expressions with constructors in terms of the arguments\n    that appear in it. Here is a simple example: *)\n\nLemma inj_ex T (x1 x2 y1 y2 : T) :\n  [:: x1; y1] = [:: x2; y2] -> x1 = x2.\n\n(** We have seen that we can use the [=>] tactic operator to name hypotheses and\n    bring them into the context. If instead of giving it a single name, we give\n    a _list_ of names enclosed in brackets [[]], Coq will enumerate all\n    equations between arguments that it can infer from that fact, from left to\n    right, and name them according to the given list. Thus, the call *)\n\nProof.\nmove=> [ex ey].\n\n(** converts the [[:: x1; y1] = [:: x2; y2]] hypothesis into two equations [ex]\n    and [ey], asserting [x1 = x2] and [y1 = y2]. The syntax tries to mimic the\n    one for case-analysis patterns on purpose. On a data value, the pattern has\n    the effect of enumerating all constructors that could have been used to\n    produce that value. On an equality, the pattern enumerates all equalities\n    that must hold for that one to be valid.\n\n    At this point, we can conclude by rewriting with [e1], or by using\n    [done] directly: *)\n\nby [].\nQed.\n\n(** (Can you make this proof shorter?)\n\n\n    * Using booleans as propositions\n\n    We often want to state facts as an equality between booleans. For instance,\n    here's is how we might say that the number [1] occurs in the sequence [[::\n    1; 2; 3]]: *)\n\nLemma bool_prop_ex1 : (1 \\in [:: 1; 2; 3]) = true.\n\n(** Since the [\\in] operator is defined by a function that computes a boolean,\n    Coq can attest that this claim is valid by computation. *)\n\nProof. by []. Qed.\n\n(** This pattern is so common that ssreflect provides a shorthand for it:\n    whenever an expression [e] of type [bool] is used in a context that expects\n    an expression of type [Prop], [e] is implicitly converted to [Prop] by\n    mapping it to [e = true]. *)\n\nLemma bool_prop_ex2 : 1 \\in [:: 1; 2; 3].\n\n(** This is an instance of a generic feature of Coq called _implicit coercions_,\n    which allows certain functions to be implicitly inserted in an expression to\n    convert from one type to another. We can have a better sense of what is\n    going on by telling Coq to show all coercions that are applied: *)\n\nSet Printing Coercions.\n\n(** We can see that the goal we were trying to prove is actually [is_true (1 \\in\n    [:: 1; 2; 3])], where [is_true b] is defined as [b = true]. *)\n\nUnset Printing Coercions.\n\n(** Coq treats [is_true b] as if it were an equality. For instance, it can solve\n    trivial goals involving [is_true] with [done]. *)\n\nProof. by []. Qed.\n\n(** It can also rewrite with hypotheses of the form [is_true b], which\n    has the effect of replacing [b] by [true]. For instance, we can\n    prove the following fact about the boolean \"and\" operator [&&]: *)\n\nLemma bool_prop_ex3 (b c : bool) : b -> b && c = c.\nProof. by move=> ->. Qed.\n\n(** Since different constructors are disjoint, we know that [false] cannot occur\n    in a hypothesis, because that is synonym with [false = true]. The [done]\n    tactic can detect this and similar hypotheses in our context and discharge\n    the current goal automatically. Consider the following result: *)\n\nLemma bool_prop_ex4 n : n <= 0 -> n = 0.\nProof.\n\n(** To put the goal in a shape that can be simplified, we can perform case\n    analysis on [n]: *)\n\ncase: n => [|n] /=.\n\n(** In the first subgoal, we have to prove [0 = 0], which is trivial: *)\n\n  by [].\n\n(** In the second one, we are left with a contradictory hypothesis, stating that\n    [n < 0] (recall that [n < 0] is just notation for [n.+1 <= 0]). We can\n    rewrite with [ltn0] lemma from [ssrnat] to replace that hypothesis by\n    [false], allowing us to conclude.. *)\n\nrewrite ltn0.\nby [].\n\n(** As a matter of fact, we don't even need to call [rewrite], because [n < 0]\n    can be \"forced\" to simplify to [false]: *)\n\nRestart.\nby case: n.\nQed.\n\n(** We may also use a boolean to state that a certain proposition is not\n    valid. For instance: *)\n\nLemma bool_prop_ex5 : (4 < 2) = false.\nProof. by []. Qed.\n\n(** However, because of how the coercion from [bool] to [Prop] is defined,\n    ssreflect prefers statements of the form [~~ b = true]: *)\n\nLemma bool_prop_ex6 : ~~ (4 < 2).\nProof. by []. Qed.\n\n(** * Generalizing the induction hypothesis *)\n\nModule Rev.\n\nSection Rev.\n\nVariable T : Type.\n\nImplicit Type s : seq T.\n\nFixpoint rev s :=\n  match s with\n  | [::] => [::]\n  | x :: s => rev s ++ [:: x]\n  end.\n\nFixpoint tr_rev_aux s acc :=\n  match s with\n  | [::] => acc\n  | x :: s => tr_rev_aux s (x :: acc)\n  end.\n\nDefinition tr_rev s := tr_rev_aux s [::].\n\nLemma tr_revE s : tr_rev s = rev s.\nProof.\nrewrite /tr_rev -[RHS]cats0.\nelim: s [::] => [|x s IH] //= acc.\nby rewrite IH -catA.\nQed.\n\nEnd Rev.\n\nEnd Rev.\n\n(** * Specifying and verifying a tree operation\n\n    We can use sequences to specify and verify our first interesting tree\n    operation: a [tmember] function, that tests whether some element [x] occurs\n    on a tree [t], assuming that [t] is a binary search tree -- that is, that\n    any element on a node is greater than those on its left subtree and smaller\n    than those on its right subtree.\n\n    It would be possible to program [tmember] for any type of elements with a\n    comparison operator. However, we will begin with something simpler, and\n    define [tmember] only for trees of natural numbers, taking advantage of the\n    usual comparison operator [<] defined in the [ssrnat] library. Notice that\n    our definition uses [if] expressions, which are defined in the obvious way\n    in terms of [match]. *)\n\nFixpoint tmember (x : nat) (t : tree) : bool :=\n  match t with\n  | Leaf => false\n  | Node t1 x' t2 =>\n    if x < x' then tmember x t1\n    else if x' < x then tmember x t2\n    else true\n  end.\n\n(** We will state the specification of [tmember] in terms of a [telems]\n    function, which lists all elements that appear in the tree from left to\n    right. *)\n\nFixpoint telems (t : tree) : seq nat :=\n  match t with\n  | Leaf => [::]\n  | Node t1 x t2 => telems t1 ++ x :: telems t2\n  end.\n\n(** In order to fully specify the behavior of [tmember], we would have to reason\n    about the search-tree invariant. Before getting there, however, we start\n    with something simpler: showing that if [tmember x t] is true, then [x] must\n    occur in [telems t]. *)\n\nLemma tmember_sound x t : tmember x t -> x \\in telems t.\nProof.\n\n(** It seems a good idea to try to prove this result by induction. *)\n\nelim: t => [|t1 IH1 x' t2 IH2] /=.\n\n(** In the first case ([t = Leaf]), we have to prove that [x] occurs in the\n    empty sequence (that is, [telems Leaf]), assuming that [tmember x Leaf] is\n    true. While [x] cannot occur in an empty sequence, we can remark that\n    [tmember x Leaf] is [false] by definition. This means that we never have to\n    consider this case because it can never occur. The [done] tactic can detect\n    this and remove this case from consideration for us.  *)\n\n  by [].\n\n(** The second case is more interesting, as we have to consider all possible\n    outcomes of comparing [x'] and [x]. The [case] variant below can be used to\n    perform case analysis on a value while generating an equation for that\n    case. For reasons that soon will become apparent, we will need these\n    additional equations later. *)\n\ncase e1: (x < x').\n\n(** In the first generated subgoal, we have an additional hypothesis [e1]\n    stating [(x < x') = true], and the original compliated premise has been\n    simplified to [tmember x t1]. *)\n\n  rewrite mem_cat => e.\n  by rewrite (IH1 e).\n\ncase e2: (x' < x).\n\n  rewrite mem_cat /= inE.\n\nAdmitted.\n\n(** * Exercises: *)\n\nLemma negbK' : involutive negb.\nProof. Admitted.\n\nLemma eq_add_0L n m : n + m = 0 -> n = 0.\nProof. Admitted.\n\nLemma eq_add_0R n m : n + m = 0 -> m = 0.\nProof. Admitted.\n\n(** Hint: The [drop_size_cat] lemma might come in handy. *)\nLemma cat_fact T (s : seq T) : s ++ s = s -> s = [::].\nProof. Admitted.\n\n(** Hint: What is the value of [fib_aux n (x1 + x2) (y1 + y2)]? *)\nLemma fib2 n : fib n.+2 = fib n.+1 + fib n.\nProof. Admitted.\n", "meta": {"author": "arthuraa", "repo": "ssr-intro", "sha": "42f991b6619534f882afa0aad0708627d0a58844", "save_path": "github-repos/coq/arthuraa-ssr-intro", "path": "github-repos/coq/arthuraa-ssr-intro/ssr-intro-42f991b6619534f882afa0aad0708627d0a58844/proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.9046505254608136, "lm_q1q2_score": 0.7742461831678934}}
{"text": "(* NEXT: ===> Extensionality                                                    *)\n\nRequire Import Logic.Set.Set.\nRequire Import Logic.Set.Elem.\n\nDeclare Scope Set_Equal_scope.\n\n(* There is one other crucially important relation on 'set' which we have not   *)\n(* yet defined, namely that of equality. It is tempting to define equality      *)\n(* simply as 'double inclusion'. However, if we assume that equality is not     *)\n(* part of a core set theoretic language, but is instead defined in terms of    *)\n(* core primitives, the definition we choose should make it obvious that if P   *)\n(* is a predicate on sets expressed in the core language, then if two sets x y  *)\n(* are deemed equal, the statement P x should be equivalent to the statement    *)\n(* P y. For example, if x and y are deemed equal, the statements x :: z and     *)\n(* and y :: z should be equivalent for all z. A definition of equality in terms *)\n(* of 'double inclusion' would fail to make such equivalence obvious. As we     *)\n(* shall see in the 'Extensionality' module, the definition of equality we      *)\n(* adopt below is in fact equivalent to 'double inclusion'. However, the point  *)\n(* is 'double inclusion' is not the right definition: if x and y are deemed     *)\n(* equal, we don't simply want the equivalence 'z :: x <-> z :: y' to hold for  *)\n(* all z, we also want the equivalence 'x :: z <-> y :: z'. For any predicate P *)\n(* expressed in terms of :: and logical connectives, these two equivalences     *)\n(* should ensure that P x <-> P y when x == y (this would need to be formalized *)\n(* and proven). In short, for two sets to be equal, we need more than them      *)\n(* having identical elements, we also need them to belong to the same sets.     *)\nDefinition equal (x y:set) : Prop :=\n    (forall (z:set), z :: x <-> z :: y) \n /\\ (forall (z:set), x :: z <-> y :: z). \n\nNotation \"x == y\" := (equal x y) (at level 90) : Set_Equal_scope.\n\nOpen Scope Set_Equal_scope.\n\n(* Our equality relation is reflexive.                                          *)\nLemma equalRefl : forall (x:set), x == x.\nProof.\n    intros x. split; intros z; split; intros H; assumption.\nQed.\n\n(* Our equality relation is symmetric.                                          *)\nLemma equalSym : forall (x y:set), x == y -> y == x.\nProof.\n    intros x y [H1 H2]. split; intros z; split; intros H.\n    - apply H1. assumption.\n    - apply H1. assumption.\n    - apply H2. assumption.\n    - apply H2. assumption.\nQed.\n\n(* Our equality relation is transitive                                          *)\nLemma equalTrans : forall (x y z:set), x == y -> y == z -> x == z.\nProof.\n    intros x y z [H1 H2] [H3 H4]. split; intro t; split; intros H.\n    - apply H3, H1. assumption.\n    - apply H1, H3. assumption.\n    - apply H4, H2. assumption.\n    - apply H2, H4. assumption.\nQed.\n\n(* These immediate consequences of equality are sometimes useful in proofs      *)\nLemma elemCompatL : forall (x y z:set), x == y -> x :: z -> y :: z.\nProof.\n    intros x y z [H1 H2] H. apply H2. assumption.\nQed.\n\nLemma elemCompatR : forall (x y z:set), x == y -> z :: x -> z :: y.\nProof.\n    intros x y z [H1 H2] H. apply H1. assumption.\nQed.\n\nLemma elemCompatLR : forall(x x' y y':set), \n    x == x' -> y == y' -> x :: y -> x' :: y'.\nProof.\n    intros x x' y y' Hx Hy H. apply elemCompatL with x.\n    - assumption.\n    - apply elemCompatR with y; assumption.\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/Set/Equal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8757869932689565, "lm_q1q2_score": 0.7742300937893625}}
{"text": "Module Stack.\n\nInductive Stack :=\n  | empty\n  | Push (e : nat) (s : Stack).\n\nCompute empty : Stack.\n\nCompute Push 1 empty : Stack.\n\nCompute Push 2 (Push 1 empty) : Stack.\n\nDefinition s1 : Stack := \n  Push 2 (Push 1 empty).\n\nCompute Push 3 s1 : Stack.\n\n(* Stack Pairs: (e,r) *)\nInductive stackpair : Type :=\n  | pair (n : nat) (s : Stack).\n\nDefinition fst (p : stackpair) : nat :=\n   match p with\n   | pair n _ => n\n   end.\n\nDefinition snd (p : stackpair) : Stack :=\n    match p with\n    | pair _ s => s\n    end.\n\n(*\n* Inductive MaybeStackpair : Type :=\n*  | Nothing\n*  | Just (p : stackpair).\n*)\nInductive Maybe (a : Type) : Type :=\n  | Nothing\n  | Just (x : a).\n\nCheck Nothing.\n\nDefinition MaybeStackpair : Type := Maybe stackpair .\n\n(* How to pop the stack? \n * \n * | 3 |      Push 3 (\n * | 2 |           Push 2 (\n * | 1 | ===>        Push 1         \n * | e |                    empty))\n *)\nDefinition pop (s : Stack) : Maybe stackpair :=\n  match s with\n  | empty => @Nothing stackpair\n  | Push e s' => Just stackpair (pair e s')\n  end.\n\nDefinition peek (s : Stack) : Maybe nat := \n  match pop s with\n  | Nothing _ => @Nothing  nat\n  | Just _ (pair e _) => Just nat e\n  end.\n\nCompute pop s1 : stackpair.\nCompute peek s1 : nat.\n\n", "meta": {"author": "AU-PL", "repo": "lectures", "sha": "237c66db33fe2297cde3db4edb4f4096252a8720", "save_path": "github-repos/coq/AU-PL-lectures", "path": "github-repos/coq/AU-PL-lectures/lectures-237c66db33fe2297cde3db4edb4f4096252a8720/01-20-2021/note.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7741786654579833}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(***************************************************************************)\n(* File: useful.v                                                          *)\n(* auteur: alex@sysal.ibp.fr                                               *)\n(* date: 19/10/95                                                          *)\n(***************************************************************************)\nRequire Import nothing.\n\n(***************************************************************************)\n(* Many useful lemmas                                                      *)\n(***************************************************************************)\n\n(***************************************************************************)\n(* Distributivity and factorisation of /\\ and \\/                           *)\n(***************************************************************************)\nLemma lem_and_fact :\n forall P0 P1 P2 : Prop, (P0 \\/ P1) /\\ P2 -> P0 /\\ P2 \\/ P1 /\\ P2.\n(* Proof of lem_and_fact                                                   *)\nintros; tauto.\nQed.\n(* End of proof of lem_and_fact                                            *)\n\nLemma lem_and_dist :\n forall P0 P1 P2 : Prop, P0 /\\ P2 \\/ P1 /\\ P2 -> (P0 \\/ P1) /\\ P2.\n(* Proof of lem_and_dist                                                   *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_and_dist                                            *)\n\nLemma lem_or_fact :\n forall P0 P1 P2 : Prop, P0 /\\ P1 \\/ P2 -> (P0 \\/ P2) /\\ (P1 \\/ P2).\n(* Proof of lem_or_fact                                                    *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_or_fact                                             *)\n\nLemma lem_or_dist :\n forall P0 P1 P2 : Prop, (P0 \\/ P2) /\\ (P1 \\/ P2) -> P0 /\\ P1 \\/ P2.\n(* Proof of lem_or_dist                                                    *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_or_dist                                             *)\n\n(***************************************************************************)\n(* Rewriting                                                               *)\n(***************************************************************************)\nLemma lem_or_and_conv_l :\n forall a b c d : Prop,\n a /\\ b \\/ c /\\ d -> (a \\/ c) /\\ (b \\/ c) /\\ (a \\/ d) /\\ (b \\/ d).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_or_and_conv_r :\n forall a b c d : Prop,\n (a \\/ c) /\\ (b \\/ c) /\\ (a \\/ d) /\\ (b \\/ d) -> a /\\ b \\/ c /\\ d.\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_and_rew_r :\n forall P Q1 Q2 : Prop, (Q1 <-> Q2) -> (P /\\ Q1 <-> P /\\ Q2).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_and_rew_l :\n forall P Q1 Q2 : Prop, (Q1 <-> Q2) -> (Q1 /\\ P <-> Q2 /\\ P).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_and_assoc_l : forall a b c : Prop, (a /\\ b) /\\ c <-> a /\\ b /\\ c.\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\n(* Note : le /\\ est associatif a droite en CoQ don pas de lemme symmetrique*)\n\nLemma lem_or_rew_l :\n forall P Q1 Q2 : Prop, (Q1 <-> Q2) -> (Q1 \\/ P <-> Q2 \\/ P).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_or_rew_r :\n forall P Q1 Q2 : Prop, (Q1 <-> Q2) -> (P \\/ Q1 <-> P \\/ Q2).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_or_assoc_l : forall a b c : Prop, (a \\/ b) \\/ c <-> a \\/ b \\/ c.\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\n(* Note : le \\/ est associatif a droite en CoQ don pas de lemme symmetrique*)\n\nLemma lem_and_rew_lr :\n forall al bl ar br : Prop,\n (al <-> ar) -> (bl <-> br) -> (al /\\ bl <-> ar /\\ br).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\nLemma lem_or_rew_lr :\n forall al bl ar br : Prop,\n (al <-> ar) -> (bl <-> br) -> (al \\/ bl <-> ar \\/ br).\n(* Proof                                                                   *)\nintros; tauto.\nQed.\n(* End of proof                                                            *)\n\n(***************************************************************************)\n(* Symmetry properties                                                     *)\n(***************************************************************************)\nLemma lem_iff_sym : forall a b : Prop, (a <-> b) -> (b <-> a).\n(* Proof of lem_iff_sym                                                    *)\nintros; tauto.\nQed.\n(* End of proof of lem_iff_sym                                             *)\n\nLemma lem_or_sym : forall a b : Prop, a \\/ b -> b \\/ a.\n(* Proof of lem_or_sym                                                     *)\nintros.\nelim H; clear H; intros.\nright; assumption.\n\nleft; assumption.\n\nQed.\n(* End of proof of lem_or_sym                                              *)\n\nLemma lem_and_sym : forall a b : Prop, a /\\ b -> b /\\ a.\n(* Proof of lem_and_sym                                                    *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_and_sym                                             *)\n\n(***************************************************************************)\n(* Contraction and expansion                                               *)\n(***************************************************************************)\nLemma lem_or_expand : forall a : Prop, a -> a \\/ a.\n(* Proof of lem_or_expand                                                  *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_or_expand                                           *)\n\nLemma lem_and_expand : forall a : Prop, a -> a /\\ a.\n(* Proof of lem_and_expand                                                 *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_and_expand                                          *)\n\nLemma lem_or_contract : forall a : Prop, a \\/ a -> a.\n(* Proof of lem_or_contract                                                *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_or_contract                                         *)\n\nLemma lem_and_contract : forall a : Prop, a /\\ a -> a.\n(* Proof of lem_and_contract                                               *)\nintros; tauto.\n\nQed.\n(* End of proof of lem_and_contract                                        *)\n\n(***************************************************************************)\n(* Existenciel et unicite                                                  *)\n(***************************************************************************)\nDefinition exUniq (A : Set) (P : A -> Prop) :=\n  exists x : A, P x /\\ (forall y : A, P y -> x = y).\n\nNotation ExU := (exUniq _) (only parsing).\n\n(***************************************************************************)\n(*                     Next : any file you want                            *)\n(***************************************************************************)", "meta": {"author": "coq-contribs", "repo": "zf", "sha": "cf33d92b69865af97d93946337f291cffc1e8a9e", "save_path": "github-repos/coq/coq-contribs-zf", "path": "github-repos/coq/coq-contribs-zf/zf-cf33d92b69865af97d93946337f291cffc1e8a9e/src/useful.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7741690819731042}}
{"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\nFrom Coq Require Import Arith Euclid Compare Lia.\nFrom Coqtail Require Export Nle Nk_ind.\nOpen Scope nat_scope.\n\n(** * Definitions *)\n(** Definition of divisibility *)\nInductive Ndivide a b : Prop :=\n| Ndivide_intro : forall q, b = q * a -> Ndivide a b.\n\n(** Definition of a quotient *)\nInductive Nquotient a b : nat -> Prop :=\n| Nquotient_intro : forall q, b = q * a -> Nquotient a b q.\n\n(** Definition of modulus/remainder *)\nInductive Nmod a b : nat -> Prop :=\n| Nmod_intro : forall q r, b = q * a + r -> r < a -> Nmod a b r.\n\n(** Notation *)\nNotation \"( a | b )\" := (Ndivide a b) (at level 0) : nat_scope.\n\n(** Definition of coprimality *)\nDefinition Nrel_prime p q := forall n, (n | p) -> (n | q) -> n = 1.\n\n(** Definition of primality *)\nDefinition Nprime p := 1<p /\\ (forall n, 1 < n < p -> ~ (n | p)).\n\n(* begin hide *)\nLemma Nprime_intro : forall p, 1 < p -> (forall n, 1 < n < p -> ~(n | p)) -> Nprime p.\nintros.\nsplit; auto.\nQed.\n(* end hide *)\n\n(** * Basic results on prime numbers *)\n(** [0] is not prime *)\nLemma Nnot_prime_0 : ~(Nprime 0).\nProof.\nunfold Nprime.\nintro.\ndestruct H.\napply le_Sn_O in H.\nexact H.\nQed.\n\n(** [1] is not prime *)\nLemma Nnot_prime_1 : ~(Nprime 1).\nProof.\nunfold Nprime.\nintro.\ndestruct H.\napply lt_irrefl in H.\nexact H.\nQed.\n\n(** A prime number is greater than or equal to [2] *)\nLemma Nprime_ge_2 : forall (p:nat), Nprime p -> 2<=p.\nProof.\nintros.\ndestruct p.\napply Nnot_prime_0 in H.\ncontradiction.\ndestruct p.\napply Nnot_prime_1 in H.\ncontradiction.\nunfold Nprime in H.\ndestruct H.\nauto with arith.\nQed.\n\n(** A composed number is not prime *)\nLemma Ncomposed_not_prime : forall n m, 1 < n -> 1 < m -> ~(Nprime (n * m)).\nProof.\nintros.\nintro.\ndestruct H1.\napply H2 with n.\nsplit.\nauto with arith.\nreplace n with (n*1).\ndestruct n.\napply le_Sn_O in H.\ncontradiction.\nrewrite <- mult_assoc.\napply mult_S_lt_compat_l.\nrewrite mult_1_l.\ntrivial.\nauto with arith.\nexists m.\nring.\nQed.\n\n(** * Basic properties of divisibility *)\n(** Compatibility with addition *)\nLemma Ndiv_plus_compat : forall p a b, (p | a) -> (p | b) -> (p | a + b).\nProof.\nintros.\ndestruct H.\ndestruct H0.\napply Ndivide_intro with (q+q0).\nrewrite H. rewrite H0.\nring.\nQed.\n\n(** Product divisiblity weakening *)\nLemma Nab_div_c : forall a b c, (a * b | c) -> (a | c).\nProof.\nintros.\ndestruct H.\napply Ndivide_intro with (q*b).\nrewrite H.\nring.\nQed.\n\n(** A divisor is usually nonzero *)\nLemma Ndiv_non_0 : forall a b, (a | b) -> 1 <= b -> 1 <= a.\nProof.\nintros.\ndestruct a.\ndestruct H.\nrewrite mult_0_r in H.\nrewrite H in H0.\nexact H0.\nauto with arith.\nQed.\n\n(** Any number divides [0] *)\nLemma Ndiv_0 : forall a, (a | 0).\nintros.\napply Ndivide_intro with 0.\nring.\nQed.\n\n(** [1] divides any number *)\nLemma Ndiv_1 : forall a, (1 | a).\nintros.\napply Ndivide_intro with a.\nring.\nQed.\n\n(** Not divisor implies nonzero *)\nLemma Nnon_div_non_zero : forall a b, ~( a | b) -> b > 0.\nintros.\ndestruct b.\ndestruct H.\napply Ndiv_0.\nauto with arith.\nQed.\n\n(** [n] divides [n] *)\nLemma Ndiv_n_n : forall n, (n|n).\nProof.\nintro.\napply Ndivide_intro with 1.\nring.\nQed.\n\n(** * Basic properties of quotient *)\n(** Quotient implies divisibility *)\nLemma Nquotient_div : forall a b q, Nquotient a b q -> (a | b).\nProof.\nintros.\ndestruct H.\napply Ndivide_intro with q.\nauto.\nQed.\n\n(** Compatibility with order *)\nLemma Nquotient_le_compat : forall a b c q p, \n  Nquotient a b q -> Nquotient a c p -> 1 <= b <= c -> q <= p.\nProof.\nintros.\nassert (1<=a).\napply Ndiv_non_0 with b.\napply Nquotient_div with q.\nexact H.\ndestruct H1.\nexact H1.\nassert (exists a',a=S a').\ndestruct a.\napply le_Sn_O in H2.\ncontradiction.\nexists a.\nreflexivity.\ndestruct H3.\ndestruct H.\ndestruct H0.\ndestruct H1.\nrewrite H in H4.\nrewrite H0 in H4.\nrewrite H3 in H4.\napply mult_S_le_reg_l with x.\nassert (S x*q=q*S x).\nring.\nassert (S x*q0=q0*S x).\nring.\nrewrite H5.\nrewrite H6.\nexact H4.\nQed.\n\n(** * Properties of divisibility *)\n\n(** Transitivity *)\nLemma Ndiv_trans : forall a b c, (a | b) -> (b | c) -> (a | c).\nProof.\nintros.\ndestruct H.\ndestruct H0.\nexists (q*q0).\nrewrite H0.\nrewrite H.\nring.\nQed.\n\n(** Simplification of addition *)\nLemma Ndiv_plus_simpl : forall a b c, (a | b + c) -> (a | b) -> (a | c).\nProof.\nintros.\ndestruct b.\ndestruct H.\napply Ndivide_intro with q.\nauto with arith.\n\ndestruct H.\ndestruct H0.\napply Ndivide_intro with (q-q0).\nassert (q0<=q).\napply Nquotient_le_compat with a (S b) (S b+c).\napply Nquotient_intro. exact H0.\napply Nquotient_intro. exact H.\nsplit.\nauto with arith.\nauto with arith.\napply Nle_plus in H1.\ndestruct H1.\nrewrite H1.\nassert (q0+x-q0=x).\napply minus_plus.\nrewrite H2.\nrewrite H1 in H.\nrewrite H0 in H.\nrewrite mult_plus_distr_r in H.\nrewrite plus_comm in H.\napply plus_reg_l with (q0*a).\nrewrite plus_comm.\nrewrite H.\nauto with arith.\nQed.\n\n(** Right implification of subtraction *)\nLemma Ndiv_minus_simpl_r : forall a b c, b >= c -> (a | b - c) -> (a | c) -> (a | b).\nProof.\nintros.\napply Nle_plus in H.\ndestruct H.\nrewrite H in * |- *.\nrewrite minus_plus in H0.\napply Ndiv_plus_compat; auto.\nQed.\n\n(** Left implification of subtraction *)\nLemma Ndiv_minus_simpl_l : forall a b c, b >= c -> (a | b - c) -> (a | b) -> (a | c).\nProof.\nintros.\napply Nle_plus in H.\ndestruct H.\nrewrite H in * |- *.\nrewrite minus_plus in H0.\nrewrite plus_comm in H1.\napply Ndiv_plus_simpl with x; auto.\nQed.\n\n(** Weak compatibility with multiplication *)\nLemma Ndiv_mult_compat : forall a b q, (a | b) -> (a | b * q).\nProof.\nintros.\ndestruct H.\napply Ndivide_intro with (q0*q).\nrewrite H.\nring.\nQed.\n\n(** Strong compatibility with multiplication *)\nLemma Ndiv_strong_mult_compat : forall a b q, (a|b) -> (a * q | b * q).\nProof.\nintros.\ndestruct H.\napply Ndivide_intro with (q0).\nrewrite H.\nring.\nQed.\n\n(* begin hide *)\nLemma toto : forall a b q, S q * a = S q * b -> a = b.\n  induction a.\n  intros.\n  rewrite mult_0_r in H.\n  symmetry in H.\n  apply mult_is_O in H.\n  destruct H.\n  discriminate H.\n  auto.\n  intros.\n  destruct b.\n  rewrite mult_0_r in H.\n  discriminate H.\n  assert (a=b).\n  rewrite mult_succ_r in H.\n  rewrite mult_succ_r in H.\n  assert (S q  + S q * a= S q + S q * b).\n  rewrite plus_comm.\n  rewrite H.\n  ring.\n  apply plus_reg_l in H0.\n  apply IHa with q.\n  auto.\n  rewrite H0.\n  auto.\nQed.\n(* end hide *)\n\n(** Simplification of common factor *)\nLemma Ndiv_mult_simpl : forall a b q, q <> 0 -> (a * q | b * q) -> (a | b).\nProof.\nintros.\ndestruct H0.\ndestruct q.\ncontradiction H.\nreflexivity.\nrewrite mult_assoc in H0.\nassert (S q*b=S q*(q0*a)).\nrewrite mult_comm.\nrewrite H0.\nring.\nassert (b=q0*a).\napply toto with q.\nrewrite mult_comm.\nrewrite H0.\nring.\napply Ndivide_intro with q0.\nauto.\nQed.\n\n(** Divisibility implies order *)\nLemma Ndiv_le : forall n p, 0 < p -> (n | p) -> n <= p.\nProof.\nintros.\ndestruct H0.\ndestruct p.\napply lt_irrefl in H. contradiction.\ndestruct n.\nauto with arith.\ndestruct q.\nsimpl in H0.\ndiscriminate H0.\nreplace (S n) with (1*S n).\nrewrite H0.\napply mult_le_compat.\nauto with arith.\nauto with arith.\nrewrite mult_1_l.\ntrivial.\nQed.\n\n(** Dividable by [0] implies zero *)\nLemma Ndiv_0_n : forall n, (0 | n) -> n = 0.\nProof.\ndestruct n.\ntrivial.\nintro.\ndestruct H.\nrewrite mult_0_r in H.\ndiscriminate H.\nQed.\n\n(** * Properties of coprimes *)\n\n(** [n] and [n] are usually not coprime *)\nLemma Nnon_rel_prime_n_n : forall n, n <> 1 -> ~(Nrel_prime n n).\nProof.\nintro.\nintro.\nintro.\nunfold Nrel_prime in H0.\nassert (n=1).\napply H0.\napply Ndiv_n_n.\napply Ndiv_n_n.\ncontradiction.\nQed.\n\n(** Compatibility with modulus *)\nTheorem Nrel_prime_mod : forall a b r, Nrel_prime a b -> Nmod a b r -> Nrel_prime a r.\nProof.\nintros.\ndestruct H0.\nunfold Nrel_prime in H.\nunfold Nrel_prime.\nintros.\nassert (n|b).\nrewrite H0.\napply Ndiv_plus_compat.\nrewrite mult_comm.\napply Ndiv_mult_compat.\nauto.\nauto.\napply H.\nauto.\nauto.\nQed.\n\n(** Symmetry *)\nLemma Nrel_prime_sym : forall a b, Nrel_prime a b -> Nrel_prime b a.\nProof.\nintros.\nintro.\nintros.\napply H.\nauto.\nauto.\nQed.\n\n(** Weakening from primality to coprimality *)\nLemma Nprime_le_rel_prime : forall n p, Nprime p -> 0 < n < p -> Nrel_prime n p.\nProof.\nintros.\ndestruct H0.\ndestruct H.\nintro.\nintros.\nassert (0<n0).\napply Ndiv_non_0 with n.\nauto.\nauto with arith.\nassert (n0<p).\napply le_trans with (S n).\napply le_n_S.\napply Ndiv_le.\nauto with arith.\ntrivial.\nauto.\ndestruct n0.\napply Ndiv_0_n in H3.\nrewrite H3 in H0.\ninversion H0.\ndestruct n0.\ntrivial.\napply H2 in H4.\ncontradiction.\nsplit.\nauto with arith.\nauto.\nQed.\n\n(** A coprime of [0] is [1] *)\nLemma Nrel_prime_0 : forall n, Nrel_prime n 0 -> n = 1.\nProof.\nintros.\napply H.\napply Ndiv_n_n.\napply Ndiv_0.\nQed.\n\n(** Any number is coprime with [1] *)\nLemma Nrel_prime_1 : forall n, Nrel_prime n 1.\nProof.\nintros.\nintro.\nintros.\ndestruct n0.\ndestruct H0.\nrewrite mult_0_r in H0. auto.\napply Ndiv_le in H0.\ndestruct n0.\nauto.\ninversion H0.\ninversion H2.\nauto.\nQed.\n\n(** * Gauss theorem *)\nTheorem Ngauss : forall a b c, (a | b * c) -> Nrel_prime a b -> (a | c).\nProof.\napply (nat_strong_ind (fun a =>  forall b c, (a|b*c) -> Nrel_prime a b -> (a|c))).\nintros.\ndestruct H.\nrewrite mult_0_r in H.\napply mult_is_O in H.\ndestruct H.\nrewrite H in H0.\napply Nnon_rel_prime_n_n in H0.\ncontradiction.\nauto with arith.\nrewrite H.\napply Ndiv_0.\n\nintros.\ndestruct n.\napply Ndiv_1.\n\ndestruct H0.\nassert (diveucl b (S (S n))).\napply eucl_dev.\nauto with arith.\ndestruct H2.\nassert (diveucl c (S(S n))).\napply eucl_dev.\nauto with arith.\ndestruct H2.\nrewrite e in H0.\nrewrite e0 in H0.\nrewrite mult_plus_distr_l in H0.\nrewrite mult_plus_distr_r in H0.\nrewrite mult_plus_distr_r in H0.\nassert (S (S n)|r*r0).\napply Ndiv_plus_simpl with (q0 *S( S n) * r0).\napply Ndiv_plus_simpl with (r * (q1 * S(S n))).\napply Ndiv_plus_simpl with (q0 * S(S n) * (q1 * S(S n))).\napply Ndivide_intro with q.\nrewrite <- H0.\nring.\napply Ndivide_intro with (q0*S(S n)*q1).\nring.\napply Ndivide_intro with (r*q1).\nring.\napply Ndivide_intro with (r0*q0).\nring.\ndestruct H2.\nassert (Nrel_prime (S(S n)) r).\napply Nrel_prime_mod with b.\nauto.\napply Nmod_intro with q0.\nauto.\nauto.\nassert (r|q2).\napply H with (S(S n)).\nauto with arith.\napply Ndivide_intro with r0.\nrewrite mult_comm.\nrewrite <- H2.\nring.\napply Nrel_prime_sym.\nauto.\nassert (S(S n)*r | r*r0).\nrewrite H2.\nrewrite mult_comm.\napply Ndiv_strong_mult_compat.\nauto.\nassert (S(S n)|r0).\napply Ndiv_mult_simpl with r.\ndestruct r.\nrewrite plus_0_r in e.\nassert (S(S n)|b).\napply Ndivide_intro with q0.\nauto.\nassert (S(S n)=1).\napply H1.\napply Ndiv_n_n.\nauto.\ndiscriminate H7.\nauto with arith.\ndestruct H5.\napply Ndivide_intro with q3.\nrewrite mult_comm.\nrewrite H5.\nring.\nrewrite e0.\napply Ndiv_plus_compat.\nrewrite mult_comm.\napply Ndiv_mult_compat.\napply Ndiv_n_n.\nauto.\nQed.\n\n(** * Decidability of divisibility *)\n\n(** Algorithm to compute a remainder modulus a number *)\nFixpoint Ndiv_mod_algo (n m:nat) {struct m} : nat :=\nmatch n with\n| 0 => 0\n| S n' =>\n  match m with\n  | 0 => 0\n  | S m' =>\n    let tmp:=S (Ndiv_mod_algo n m') in\n    match beq_nat n tmp with\n    | true => 0\n    | false => tmp\n    end\n  end\nend.\n\n(** Algorithm to decide divisibility *)\nDefinition Ndiv_algo (n m:nat) : bool :=\n  beq_nat (Ndiv_mod_algo n m) 0.\n\n  (* begin hide *)\n  Lemma eq_nat_correct : forall n m, n<>m -> false=beq_nat n m.\n  Proof.\n  intros n.\n  induction n.\n  destruct m.\n  intros.\n  contradiction H. reflexivity.\n  intros.\n  compute. reflexivity.\n  induction m.\n  compute. reflexivity.\n  simpl.\n  intros.\n  apply IHn.\n  auto with arith.\n  Qed.\n(* end hide *)\n(** [m] mod [n] equals [m] if [n] is greater than [m] *)\nLemma Ndiv_mod_l0 : forall n m, m < n -> Ndiv_mod_algo n m = m.\nProof.\ninduction m.\nintros. destruct n. inversion H. compute. trivial.\nintros.\ndestruct n.\ninversion H.\nsimpl.\nreplace (Ndiv_mod_algo (S n) m) with m.\nreplace (beq_nat n m) with false.\nreflexivity.\napply eq_nat_correct.\nintro.\nrewrite H0 in H.\napply lt_irrefl in H. contradiction.\nsymmetry.\napply IHm.\nauto with arith.\nQed.\n\n(** Simplification of addition *)\nLemma Ndiv_mod_l1 : forall n m, n > 0 -> Ndiv_mod_algo n (m + n) = Ndiv_mod_algo n m.\nProof.\nintros n m. pattern m. apply nat_strong_ind.\nintros. simpl.\ninduction n.\nreflexivity.\nsimpl.\nreplace (Ndiv_mod_algo (S n) n) with n.\nreplace (beq_nat n n) with true.\nreflexivity. apply beq_nat_refl.\nsymmetry.\napply Ndiv_mod_l0.\nauto with arith.\nintros.\ninduction n.\nsimpl. reflexivity.\nsimpl.\nreplace (Ndiv_mod_algo (S n) (n0+S n)) with (Ndiv_mod_algo (S n) n0); auto.\nsymmetry.\napply H.\nauto with arith.\nauto with arith.\nQed.\n\n(** Correctness of divisibility algorithm *)\nTheorem Ndiv_algo_correct : forall n m, n > 0 -> (n | m) -> Ndiv_algo n m=true.\nProof.\ndestruct n.\nintros.\ninversion H.\nintro. pattern m.\napply nat_strong_ind.\nintros.\ncompute. trivial.\nintros.\nunfold Ndiv_algo.\ndestruct H1.\ndestruct q.\nsimpl in H1.\ninversion H1.\nrewrite mult_succ_l in H1.\nrewrite H1.\nrewrite Ndiv_mod_l1.\napply H.\napply le_trans with (q*S n+n).\nauto with arith.\nrewrite plus_comm in H1.\nsimpl in H1.\napply eq_add_S in H1.\nrewrite H1.\nrewrite plus_comm.\nauto with arith.\nauto with arith.\nexists q.\nauto.\nauto.\nQed.\n\n(* The remainder is a remainder (strong condition) *)\nLemma Ndiv_mod_algo_rem : forall n m r, n > 0 -> Ndiv_mod_algo n m = r -> r < n.\nProof.\ninduction m.\nintros.\ndestruct n. inversion H. compute in H0. rewrite <- H0. auto with arith.\nintros.\ndestruct n. inversion H.\nsimpl in H0.\nassert (Ndiv_mod_algo (S n) m<(S n)).\napply IHm. auto with arith. auto.\napply le_le_S_eq in H1.\ndestruct H1.\napply le_S_n in H1.\napply le_lt_n_Sm in H1.\napply lt_S_n in H1.\ndestruct (beq_nat n (Ndiv_mod_algo (S n) m)).\nrewrite <- H0. auto with arith.\nrewrite <- H0.\napply lt_n_S. auto.\napply eq_add_S in H1.\nrewrite H1 in H0.\nrewrite <- beq_nat_refl in H0.\nrewrite <- H0.\nauto with arith.\nQed.\n\n(* The remainder is lower than or equal to number itself *)\nLemma Ndiv_mod_algo_rem2 : forall n m r, n > 0 -> Ndiv_mod_algo n m = r -> r <= m.\nProof.\ninduction m.\nintros.\ndestruct n; compute in H0; rewrite <- H0; auto with arith.\nintros.\nsimpl in H0.\ndestruct n. inversion H.\ndestruct (beq_nat (S n) (S (Ndiv_mod_algo (S n) m))).\nrewrite <- H0. auto with arith.\ndestruct r.\ninversion H0.\napply eq_add_S in H0.\napply le_n_S.\napply IHm.\nauto.\nauto.\nQed.\n\n(** Completeness of modulus algorithm *)\nTheorem Ndiv_mod_algo_complete : forall n m r, n > 0 -> Ndiv_mod_algo n m = r ->\n(n | m - r).\nProof.\ndestruct n.\n+ intros; inversion H.\n+ intro m; pattern m; apply nat_strong_ind.\n  - intros; compute in H0; rewrite <- H0.\n    simpl; apply Ndiv_0.\n  - intros; simpl in H1; case (lt_eq_lt_dec (S n) n0).\n    intros; destruct s.\n\n{ assert (exists d, n0=S n+d) by (apply Nle_plus; auto with arith).\n  destruct H2; rewrite H2 in H1.\n  assert (Ndiv_mod_algo (S n) (S n+x)=Ndiv_mod_algo (S n) (x+S n)) by (rewrite plus_comm; auto).\nrewrite H3 in H1.\nclear H3.\nrewrite Ndiv_mod_l1 in H1.\nrewrite H2.\nreplace (S (S n+x)) with (S n+S x) by auto with arith.\nreplace (S n+S x-r) with (S n+(S x-r)).\n2: {\napply plus_minus.\nreplace (r+(S n+(S x-r))) with (S n+r+(S x-r)).\n2: {\nrewrite plus_assoc.\nnow auto with arith.\n}\nassert (S x=r+(S x-r)).\nsymmetry.\napply le_plus_minus_r.\ndestruct (beq_nat n (Ndiv_mod_algo (S n) x)).\nrewrite <- H1. auto with arith.\ndestruct r. inversion H1.\napply eq_add_S in H1.\napply le_n_S.\napply Ndiv_mod_algo_rem2 with (S n).\nauto with arith.\nauto.\nrewrite H3.\nrewrite plus_assoc.\nrewrite minus_plus.\nauto.\n}\napply Ndiv_plus_compat.\napply Ndiv_n_n.\napply H.\nrewrite plus_Snm_nSm in H2.\napply le_trans with (S x+n).\nauto with arith.\nrewrite plus_comm.\nrewrite <- H2.\nauto with arith.\nauto with arith.\nauto.\nauto with arith. }\n\n\n    {\n    rewrite <- e in H1.\n    replace (Ndiv_mod_algo (S n) (S n)) with (Ndiv_mod_algo (S n) (0+S n)) in H1.\n    rewrite Ndiv_mod_l1 in H1.\n    simpl in H1; destruct n.\n    { simpl in H1; rewrite <- H1; rewrite <- e; simpl; exists 2; ring. }\n    { simpl in H1; rewrite <- H1; rewrite e; simpl; rewrite <- minus_n_O; apply Ndiv_n_n. }\n    { auto with arith. }\n    { simpl. auto. }\n    }\n\n    {\n    intro;\n    replace (Ndiv_mod_algo (S n) n0) with n0 in H1.\n    apply le_le_S_eq in l.\n    destruct l.\n    assert (n<>n0).\n    intro. rewrite H3 in H2. apply lt_irrefl in H2. auto.\n    apply eq_nat_correct in H3.\n    rewrite <- H3 in H1.\n    rewrite <- H1.\n    rewrite <- minus_diag_reverse.\n    apply Ndiv_0.\n    apply eq_add_S in H2.\n    rewrite H2 in H1.\n    rewrite <- beq_nat_refl in H1.\n    rewrite <- H1.\n    rewrite <- minus_n_O.\n    rewrite H2.\n    apply Ndiv_n_n.\n    symmetry.\n    apply Ndiv_mod_l0.\n    auto. }\nQed.\n\n(** Completeness of the divisibility algorith *)\nTheorem Ndiv_algo_complete : forall n m, n>0 -> Ndiv_algo n m=true -> (n | m).\nProof.\nintros.\nunfold Ndiv_algo in H0.\nsymmetry in H0.\napply beq_nat_eq in H0.\nreplace m with (m-0).\napply Ndiv_mod_algo_complete.\nauto.\nauto.\nauto with arith.\nQed.\n\n(** * Greatest strict divisor *)\n(** Algorithm to compute the greatest divisor lower than a number *)\nFixpoint Ngreatest_div_le (n:nat) (p:nat) {struct n}: nat :=\nmatch n with\n| 0 | 1 => 1\n| S n => \n    if Ndiv_algo (S n) p then (S n)\n    else Ngreatest_div_le n p\nend.\n\n(** Algorithm to compute the greatest strict divisor of a number *)\nDefinition Ngreatest_div (p:nat) : nat :=\n  Ngreatest_div_le (pred p) p.\n\n(** The greatest divisor is a divisor *)\nLemma Ngreatest_div_le_div : forall p n, p>1 -> (Ngreatest_div_le n p | p).\nProof.\ninduction n.\nintros.\ncompute. apply Ndiv_1.\nintros.\nsimpl.\ndestruct n. apply Ndiv_1.\nassert(Ndiv_algo (S(S n)) p=true -> (S(S n)|p)).\nintros. apply Ndiv_algo_complete. auto with arith. auto.\ndestruct (Ndiv_algo (S(S n)) p).\napply H0. auto.\nauto.\nQed.\n\n(** The greatest strict divisor is a divisor *)\nTheorem Ngreatest_div_div : forall p, p > 1 -> (Ngreatest_div p | p).\nProof.\nintros.\napply Ngreatest_div_le_div.\nauto.\nQed.\n\n(** The greatest divisor lower than a number is a lower than that number *)\nTheorem Ngreatest_div_le_le : forall n p, n > 0 -> Ngreatest_div_le n p <= n.\nProof.\nintros.\ninduction n.\ninversion H.\nsimpl.\ndestruct n.\nauto.\ndestruct (Ndiv_algo (S (S n)) p).\nauto.\neapply le_trans.\neapply IHn. auto with arith.\nauto with arith.\nQed.\n\n(** The greatest divisor is a monotonous function *)\nTheorem Ngreatest_div_le_monotone : forall n n' p,\n  n <= n' -> Ngreatest_div_le n p <= Ngreatest_div_le n' p.\nProof.\nintros.\ninduction H.\nauto.\neapply le_trans.\neexact IHle.\nassert (Ndiv_algo (S m) p=true -> Ngreatest_div_le (S m) p=S m).\nintros.\nsimpl.\ndestruct m. auto.\nrewrite H0. auto.\nassert (Ndiv_algo (S m) p=false -> Ngreatest_div_le (S m) p=Ngreatest_div_le m p).\nintros.\nsimpl.\ndestruct m. compute. auto.\nrewrite H1. auto.\ndestruct (Ndiv_algo (S m) p).\nrewrite H0.\ndestruct m. compute. auto.\neapply le_trans.\neapply Ngreatest_div_le_le. auto with arith.\nauto with arith. auto.\nrewrite H1. auto. auto.\nQed.\n\n(** The greatest divisor is a the greatest divisor *)\nTheorem Ngreatest_div_le_greatest : forall n p q, \n  p>1 -> q>=1 -> q<p -> q<=n -> (q | p) -> q <= Ngreatest_div_le n p.\nProof.\nintros.\nreplace q with (Ngreatest_div_le q p).\napply Ngreatest_div_le_monotone. auto.\ndestruct q.\ninversion H0.\nsimpl.\ndestruct q.\nauto.\napply Ndiv_algo_correct in H3.\nrewrite H3. auto. auto with arith.\nQed.\n\n(** The greatest strict divisor is a the greatest strict divisor *)\nTheorem Ngreatest_div_greatest : forall p q, \n  p>1 -> q>=1 -> q<p -> (q | p) -> q <= Ngreatest_div p.\nProof.\nintros.\napply Ngreatest_div_le_greatest; auto.\ndestruct p. inversion H.\nsimpl. auto with arith.\nQed.\n\n(** The greatest strict divisor is strict *)\nTheorem Ngreatest_div_lt_p : forall n, n > 1 -> Ngreatest_div n < n.\nProof.\nintros.\ndestruct n.\ninversion H.\ndestruct n.\ninversion H. inversion H1.\nunfold lt.\napply le_n_S.\nunfold Ngreatest_div.\nreplace (pred(S(S n))) with (S n).\napply Ngreatest_div_le_le.\nauto with arith.\nauto with arith.\nQed.\n\n(** The greatest strict divisor is nonzero *)\nTheorem Ngreatest_div_le_1 : forall n, Ngreatest_div n>=1.\nProof.\nintros.\ndestruct n.\ncompute. auto.\ndestruct n. compute. auto.\napply Ngreatest_div_greatest.\nauto with arith.\nauto.\nauto with arith.\napply Ndiv_1.\nQed.\n\n(** * Decidability of primality with greatest strict divisor *)\n(** Implication of greatest strict divisor on primality *)\nTheorem Ngreatest_div_1_prime : forall p, p > 1 -> Ngreatest_div p = 1 -> Nprime p.\nProof.\nintro.\ndestruct p.\nintros. inversion H.\ndestruct p.\nintros. inversion H. inversion H2.\n\nintros.\nsplit.\nauto.\nintros.\nintro.\napply Ngreatest_div_greatest in H2.\nrewrite H0 in H2.\ndestruct H1.\nassert(1<1).\neapply le_trans.\neapply H1. auto.\ninversion H4. inversion H6.\nauto with arith.\ndestruct H1.\nauto with arith.\ndestruct H1.\nauto with arith.\nQed.\n\n(** Implication of primality greatest divisor *)\nTheorem Nprime_greatest_div_le_1 : forall n p, n<p -> Nprime p -> Ngreatest_div_le n p=1.\nProof.\ninduction n.\nintros.\ncompute. auto.\nintros.\nsimpl.\ndestruct n.\nauto.\nassert(~(Ndiv_algo (S (S n)) p=true)).\nintro.\ndestruct H0.\napply H2 with (S(S n)).\nsplit.\nauto with arith. auto.\napply Ndiv_algo_complete.\nauto with arith. auto.\ndestruct (Ndiv_algo (S (S n)) p).\ncontradiction H1. auto.\napply IHn.\nauto with arith.\nauto.\nQed.\n\n(** Implication of primality greatest strict divisor *)\nTheorem Nprime_greatest_div_1 : forall p, Nprime p -> Ngreatest_div p=1.\nProof.\nintros.\napply Nprime_greatest_div_le_1.\ndestruct H.\ninversion H;\nauto with arith. auto.\nQed.\n\n(** * Lowest strict divisor *)\n(** Algorithm to compute the lowest divisor greater than a number *)\nFixpoint Nleast_div_ge (n p:nat) {struct n} : nat :=\nmatch n with\n| 0 => p\n| S n =>\n    if Ndiv_algo (p-S n) p then p-S n\n    else Nleast_div_ge n p\nend.\n\n(** Algorithm to compute lowest strict divisor *)\nDefinition Nleast_div p := Nleast_div_ge (p-2) p.\n\n(** Lowest divisor is a divisor *)\nLemma Nleast_div_ge_div : forall p n, p>1 -> n < p -> (Nleast_div_ge n p | p).\nProof.\ninduction n.\nintros.\ncompute. apply Ndiv_n_n.\nintros.\nsimpl.\nassert (Ndiv_algo (p-S n) p=true -> (p-S n|p)).\napply Ndiv_algo_complete.\nunfold gt.\napply (minus_le_compat_r (S (S n)) p (S n)) in H0.\nrewrite <- minus_Sn_m in H0.\nrewrite <- minus_n_n in H0.\neapply le_trans.\neapply H0. auto. auto.\ndestruct (Ndiv_algo (p-S n) p).\napply H1. auto.\napply IHn. auto.\nauto with arith.\nQed.\n\n(** Lowest divisor is usually greater than [1] *)\nTheorem Nleast_div_ge_gt_1 : forall n p, p > 1 -> S n < p -> 1 < Nleast_div_ge n p.\nProof.\ninduction n.\nintros.\ncompute. auto.\nintros.\nsimpl.\ndestruct (Ndiv_algo (p-S n) p).\napply (minus_le_compat_r (S(S(S n))) p (S n)) in H0.\nrewrite <- minus_Sn_m in H0.\nrewrite <- minus_Sn_m in H0.\nrewrite <- minus_n_n in H0.\nauto. auto. auto.\napply IHn.\nauto. auto with arith.\nQed.\n\n(** Lowest strict divisor is greater than [1] *)\nTheorem Nleast_div_gt_1 : forall p, p > 1 -> 1 < Nleast_div p.\nProof.\nintros.\napply Nleast_div_ge_gt_1.\nauto.\nunfold lt.\nassert(p>=2).\nauto with arith.\napply Nle_plus in H0.\ndestruct H0.\nrewrite H0.\nrewrite minus_plus.\nauto with arith.\nQed.\n\n(** Lowest strict divisor is a divisor *)\nTheorem Nleast_div_div : forall p, p>1 -> (Nleast_div p | p).\nProof.\nintros.\napply Nleast_div_ge_div.\nauto.\nauto with arith.\nQed.\n\n(** Lowest divisor greater than a number is greater than that number *)\nTheorem Nleast_div_ge_ge : forall n p, n < p -> Nleast_div_ge n p >= p - n.\nProof.\ninduction n.\nintros.\nsimpl.\nrewrite <- minus_n_O.\nauto.\nintros.\nsimpl.\ndestruct (Ndiv_algo (p-S n) p).\nauto.\nunfold ge.\napply le_trans with (p-n).\napply minus_le_compat_l.\nauto.\napply IHn. auto with arith.\nQed.\n\n(** Lowest divisor is a monotonous function *)\nTheorem Nleast_div_ge_monotone : forall n n' p,\n  n <= n' -> n' < p -> Nleast_div_ge n p >= Nleast_div_ge n' p.\nProof.\nintros.\ninduction H.\nauto.\nsimpl.\ndestruct (Ndiv_algo (p-S m) p).\napply le_trans with (p-m).\napply minus_le_compat_l.\nauto.\napply le_trans with (p-n).\napply minus_le_compat_l.\nauto.\napply Nleast_div_ge_ge.\napply le_trans with (S m).\nauto with arith.\nauto with arith.\napply IHle.\nauto with arith.\nQed.\n\n(** Lowest divisor is lowest divisor *)\nTheorem Nleast_div_ge_least : forall n p q, \n  p > 1 -> q >= 1 -> q < p -> n < p -> q >= p-n -> (q | p) -> Nleast_div_ge n p <= q.\nProof.\nintros.\nreplace q with (Nleast_div_ge (p-q) p).\napply Nleast_div_ge_monotone.\nunfold ge in H3.\ndestruct (le_dec n p).\napply (plus_le_compat_l (p-n) q n) in H3.\nrewrite le_plus_minus_r  in H3.\napply (minus_le_compat_r p (n+q) q) in H3.\nrewrite plus_comm in H3.\nrewrite minus_plus in H3.\nauto.\nauto.\napply le_trans with p.\napply le_minus.\nauto.\nauto.\n\ndestruct H1.\nrewrite <- minus_Sn_m.\nrewrite <- minus_n_n.\nsimpl. rewrite <- minus_n_O.\napply Ndiv_algo_correct in H4.\nrewrite H4. auto. auto. auto.\n\nrewrite <- minus_Sn_m.\nsimpl.\napply Ndiv_algo_correct in H4.\nassert(q<=m).\nauto with arith.\napply Nle_plus in H5.\ndestruct H5.\nrewrite H5.\nrewrite minus_plus.\nrewrite plus_comm.\nrewrite minus_plus.\nrewrite H5 in H4.\nrewrite plus_comm.\nrewrite H4.\nauto. auto. auto with arith.\nQed.\n\n(** Lowest strict divisor is lowest divisor *)\nTheorem Nleast_div_least : forall p q, \n  p > 1 -> q > 1 -> q < p -> (q | p) -> Nleast_div p <= q.\nProof.\nintros.\napply Nleast_div_ge_least.\nauto. auto with arith. auto. auto with arith.\napply Nle_plus in H.\ndestruct H.\nrewrite H.\nrewrite minus_plus.\nrewrite plus_comm.\nrewrite minus_plus.\nauto.\nauto.\nQed.\n\n(** * Decidability of primality with lowest strict divisor *)\n(** Implication of lowest strict divisor on primality *)\nTheorem Nleast_div_p_prime : forall p, p > 1 -> Nleast_div p = p -> Nprime p.\nProof.\nintros.\ndestruct p.\ninversion H.\nsplit.\nauto.\nintros.\ndestruct H1.\nintro.\napply Nleast_div_least in H3.\nrewrite H0 in H3.\nassert(n<n).\napply le_trans with (S p).\nauto. auto.\napply lt_irrefl in H4. auto.\nauto.\nauto.\nauto.\nQed.\n\n(** Implication of primality on lowest divisor *)\nTheorem Nprime_least_div_ge_p : forall n p, S n < p -> Nprime p -> Nleast_div_ge n p = p.\n(* fixme: cette preuve est foireuse *)\ninduction n.\nintros.\ncompute. auto.\nintros.\ndestruct H0.\napply le_le_S_eq in H.\ndestruct H.\nsimpl.\nassert(~(p-S n|p)).\napply H1.\nsplit.\napply (minus_le_compat_r (S(S(S(S n)))) p (S n)) in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_n_n in H.\nauto with arith.\nauto.\nauto.\nauto with arith.\napply lt_minus.\napply le_trans with (S(S(S n))).\nauto with arith. auto.\nauto with arith.\nauto with arith.\nassert (~Ndiv_algo (p-S n) p=true).\nintro.\napply H1 with (p-S n).\nsplit.\napply (minus_le_compat_r (S(S(S(S n)))) p (S n)) in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_n_n in H.\nauto with arith.\nauto.\nauto.\nauto.\napply lt_minus.\napply le_trans with (S(S(S(S n)))).\nauto. auto. auto with arith.\napply Ndiv_algo_complete.\nunfold gt.\napply (minus_le_compat_r (S(S(S(S n)))) p (S n)) in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_Sn_m in H.\nrewrite <- minus_n_n in H.\napply le_trans with 3. auto. auto. auto. auto. auto. auto. auto with arith.\n\ndestruct (Ndiv_algo (p-S n) p).\ncontradiction H3. auto.\napply IHn.\napply le_trans with (S(S(S(S n)))).\nauto. auto.\nsplit. auto. auto.\n\ndestruct p. inversion H.\ndestruct p. inversion H.\ndestruct p. inversion H.\ndo 3 apply eq_add_S in H.\nrewrite H.\nunfold Nleast_div_ge.\nrewrite <- minus_Sn_m.\nrewrite <- minus_Sn_m.\nrewrite <- minus_n_n.\nassert(~(Ndiv_algo 2 (S(S(S p)))=true)).\nintro.\napply H1 with 2.\nsplit. auto. auto with arith.\napply Ndiv_algo_complete. auto. auto.\ndestruct (Ndiv_algo 2 (S(S(S p)))).\ncontradiction H2. auto.\nfold Nleast_div_ge.\nrewrite <- H.\napply IHn.\nauto.\nsplit. auto with arith.\nrewrite H.\nauto.\nauto.\nauto.\nQed. \n\n(** Implication of primality on lowest strict divisor *)\nTheorem Nprime_least_div_p : forall p, Nprime p -> Nleast_div p = p.\nProof.\nintros.\napply Nprime_least_div_ge_p.\ndestruct p.\napply Nnot_prime_0 in H. contradiction.\ndestruct p.\napply Nnot_prime_1 in H. contradiction.\nrewrite minus_Sn_m.\napply le_trans with (S (S p)).\napply lt_n_S.\nauto with arith. auto. auto with arith.\nauto.\nQed.\n\n(** Lowest strict divisor is prime *)\nTheorem Nleast_div_prime : forall p, p>1 -> Nprime (Nleast_div p).\nProof.\nintros.\nsplit.\napply Nleast_div_gt_1.\nauto.\nintros.\nintro.\ndestruct H0.\nassert((n|p)).\napply Ndiv_trans with (Nleast_div p).\nauto.\napply Nleast_div_div.\nauto with arith.\napply Nleast_div_least in H3.\napply lt_irrefl with (Nleast_div p).\napply le_trans with (S n).\nauto with arith.\nauto.\nauto with arith.\nauto.\napply le_trans with (Nleast_div p).\nauto.\napply Ndiv_le.\ndestruct p. inversion H.\nauto with arith.\napply Nleast_div_div.\nauto with arith.\nQed.\n\n(** Lowest strict divisor is greater than [1] *)\nTheorem Nleast_div_ge_2 : forall n, n > 1 -> Nleast_div n >= 2.\nProof.\nintros.\nassert(Nprime (Nleast_div n)).\napply Nleast_div_prime.\nauto.\nassert(0<=Nleast_div n).\nauto with arith.\napply le_le_S_eq in H1.\ndestruct H1.\napply le_le_S_eq in H1.\ndestruct H1.\nauto.\nrewrite <- H1 in H0.\napply Nnot_prime_1 in H0. contradiction.\nrewrite <- H1 in H0.\napply Nnot_prime_0 in H0. contradiction.\nQed.\n\n(** Implication of lowest strict divisor on not primality *)\nTheorem Nleast_div_lt_p_not_prime : forall n, n > 2 -> (Nleast_div n) < n -> ~(Nprime n).\nProof.\nintros.\nintro.\nassert((Nleast_div n|n)).\napply Nleast_div_div.\nauto with arith.\ndestruct H2.\ndestruct q.\nrewrite mult_0_l in H2.\nrewrite H2 in H.\ninversion H.\ndestruct q.\nrewrite mult_1_l in H2.\nrewrite <- H2 in H0.\napply lt_irrefl in H0.\nauto.\napply (Ncomposed_not_prime (S(S q)) (Nleast_div n)).\nauto with arith.\napply Nleast_div_gt_1.\nauto with arith.\nrewrite H2 in H1. auto.\nQed.\n\n(** Every number has a prime divisor *)\nTheorem Nhas_prime_divisor : forall n, n > 1 -> exists p, Nprime p /\\ (p | n).\nProof.\nintros.\nexists (Nleast_div n).\nsplit.\napply Nleast_div_prime.\nauto.\napply Nleast_div_div.\nauto with arith.\nQed.\n\n(** * Gauss theorem (prime formulation) *)\nTheorem Ngauss_prime : forall a b c, (a | b * c) -> Nprime a -> (a | c) \\/ (a | b).\nProof.\nintros.\ndestruct a.\napply Nnot_prime_0 in H0. contradiction.\n\nassert(Ndiv_algo (S(a)) b=true -> ((S(a))|b)).\nintro. apply Ndiv_algo_complete. auto.\nauto with arith. auto.\nassert(Ndiv_algo (S a) b=false -> Nrel_prime (S a) b).\nintro.\nassert(~(S a|b)).\nintro.\napply Ndiv_algo_correct in H3. rewrite H3 in H2. inversion H2.\nauto with arith.\nintro.\nintros.\ndestruct n.\ndestruct H4. rewrite mult_0_r in H4. inversion H4.\ndestruct n.\nauto.\ndestruct H0.\napply H6 in H4.\ncontradiction.\nsplit.\nauto with arith.\napply Ndiv_le in H4.\napply le_le_S_eq in H4.\ndestruct H4.\nauto.\nrewrite H4 in H5.\napply H3 in H5.\ncontradiction.\nauto with arith.\ndestruct (Ndiv_algo (S a) b).\nright.\napply H1.\nauto.\nleft.\napply Ngauss with b.\napply H.\napply H2.\nauto.\nQed.\n\n(** * Compatibility of coprimality with multiplication *)\nTheorem Nrel_prime_mult_compat : forall p n m,\n  Nrel_prime p n -> Nrel_prime p m -> Nrel_prime p (n * m).\nProof.\nintros.\nintro.\nintros.\ndestruct n0.\ndestruct H1.\nrewrite mult_0_r in H1.\nrewrite H1 in H.\ndestruct H2.\nrewrite mult_0_r in H2.\napply mult_is_O in H2.\ndestruct H2.\nrewrite H2 in H.\napply H.\napply Ndiv_n_n.\napply Ndiv_n_n.\nrewrite H1 in H0.\nrewrite H2 in H0.\napply H0.\napply Ndiv_n_n.\napply Ndiv_n_n.\ndestruct n0.\nauto.\n\nassert(exists pn0, Nprime pn0 /\\ (pn0|(S(S n0)))).\napply Nhas_prime_divisor.\nauto with arith.\ndestruct H3.\ndestruct H3.\nassert((x|n*m)).\neapply Ndiv_trans.\neapply H4.\napply H2.\napply Ngauss_prime in H5.\nassert(x=1).\ndestruct H5.\napply H0.\neapply Ndiv_trans. eapply H4. apply H1.\napply H5.\napply H.\neapply Ndiv_trans. eapply H4. apply H1.\napply H5.\nrewrite H6 in H3.\napply Nnot_prime_1 in H3.\ncontradiction.\nauto.\nQed.\n\n(** * Primality results *)\n(** Not prime implies composed *)\nTheorem Nnot_prime_composed : forall n, \n  n > 2 -> ~(Nprime n) -> exists p, exists q, p > 1 /\\ q > 1 /\\ n = p * q.\nProof.\nintros.\nexists(Nleast_div n).\nassert(Nleast_div n|n).\napply Nleast_div_div.\nauto with arith.\ndestruct H1.\nexists q.\nsplit.\napply Nleast_div_gt_1. auto with arith.\nsplit.\ndestruct q.\nrewrite mult_0_l in H1.\nrewrite H1 in H.\ninversion H.\ndestruct q.\nrewrite mult_1_l in H1.\nsymmetry in H1.\napply Nleast_div_p_prime in H1.\napply H0 in H1. contradiction.\nauto with arith.\nauto with arith.\nrewrite mult_comm. auto.\nQed.\n\n(** A number if either prime or not prime *)\nTheorem Nprime_or_not_prime : forall n, (Nprime n) \\/ (~(Nprime n)).\nProof.\nintros.\ndestruct n.\nright. apply Nnot_prime_0.\ndestruct n.\nright. apply Nnot_prime_1.\ndestruct n.\nleft.\napply Nprime_intro.\nauto with arith.\nintros.\ndestruct H.\ninversion H.\nrewrite H1 in H0.\napply lt_irrefl in H0. contradiction.\nrewrite <- H2 in H0.\nassert(2<2).\napply le_trans with (S m).\nauto with arith. auto with arith.\napply lt_irrefl in H3. contradiction.\nassert(beq_nat (Nleast_div (S(S(S n)))) (S(S(S n)))=true -> Nprime (S(S(S n)))).\nintros.\napply Nleast_div_p_prime.\nauto with arith.\napply beq_nat_true.\nauto.\nassert(beq_nat (Nleast_div (S(S(S n)))) (S(S(S n)))=false -> ~Nprime (S(S(S n)))).\nintros.\nassert(Nleast_div (S(S(S n)))<>(S(S(S n)))).\napply beq_nat_false.\nauto.\napply not_eq in H1.\ndestruct H1.\napply Nleast_div_lt_p_not_prime.\nauto with arith.\nauto.\nassert(Nleast_div (S(S(S n)))<=S(S(S n))).\napply Ndiv_le.\nauto with arith.\napply Nleast_div_div.\nauto with arith.\nassert(S(S(S n))<S(S(S n))).\neapply le_trans.\neapply H1.\napply H2.\napply lt_irrefl in H3.\nintro. auto.\n\ndestruct (beq_nat (Nleast_div (S (S (S n)))) (S (S (S n)))).\nleft. auto.\nright. auto.\nQed.\n\n(** A number is either prime or composed *)\nTheorem Nprime_or_composed : forall n, \n  n > 2 -> (Nprime n) \\/ (exists p, exists q, p > 1 /\\ q > 1 /\\ n=p * q).\nProof.\nintros.\nassert(Nprime n \\/ ~Nprime n).\napply Nprime_or_not_prime.\ndestruct H0.\nleft. auto.\nright.\napply Nnot_prime_composed.\nauto. auto.\nQed.\n\n(** * Relation between lowest strict divisor and greatest strict divisor *)\nTheorem Ngreatest_least_div_relation : forall n, n > 2 -> (Ngreatest_div n) * (Nleast_div n)=n.\nProof.\nintros.\nassert(Nprime n \\/ ~Nprime n).\napply Nprime_or_not_prime.\ndestruct H0.\nreplace (Ngreatest_div n) with 1.\nreplace (Nleast_div n) with n.\nring.\nsymmetry.\napply Nprime_least_div_p. auto.\nsymmetry.\napply Nprime_greatest_div_1. auto.\n\nassert(Q:~Nprime n).\nauto. clear H0.\nassert((Ngreatest_div n)*(Nleast_div n)<=n).\nassert((Ngreatest_div n)|n).\napply Ngreatest_div_div. auto with arith.\ndestruct H0.\nassert(q|n).\nexists (Ngreatest_div n).\nrewrite mult_comm. auto.\napply Nleast_div_least in H1.\nrewrite H0 at 3.\nrewrite mult_comm.\napply mult_le_compat_r.\nauto.\nauto with arith.\ndestruct q.\nrewrite mult_0_l in H0. rewrite H0 in H. inversion H.\ndestruct q.\nrewrite mult_1_l in H0.\nassert(Ngreatest_div n<n).\napply Ngreatest_div_lt_p.\nauto with arith.\nrewrite <- H0 in H2 at 1.\napply lt_irrefl in H2.\ncontradiction.\nauto with arith.\nassert(q<=n).\napply Ndiv_le; auto. destruct n. inversion H. auto with arith.\napply le_le_S_eq in H2.\ndestruct H2.\nauto.\nrewrite H2 in H0.\ndestruct n.\ninversion H.\nassert(1<=Ngreatest_div (S n)).\napply Ngreatest_div_le_1.\napply le_le_S_eq in H3.\ndestruct H3.\nreplace q with (q*1).\nrewrite H0.\nrewrite H2.\napply mult_S_lt_compat_l.\nauto. ring.\nsymmetry in H3.\napply Ngreatest_div_1_prime in H3.\napply Q in H3. contradiction.\nauto with arith.\n\nassert((Ngreatest_div n)*(Nleast_div n)>=n).\nassert((Nleast_div n)|n).\napply Nleast_div_div. auto with arith.\ndestruct H1.\nassert(q|n).\nexists (Nleast_div n).\nrewrite mult_comm. auto.\napply Ngreatest_div_greatest in H2.\nunfold ge.\nrewrite H1 at 1.\napply mult_le_compat_r.\nauto.\nauto with arith.\ndestruct q.\nrewrite mult_0_l in H1.\nrewrite H1 in H. inversion H.\nauto with arith.\napply Ndiv_le in H2.\napply le_le_S_eq in H2.\ndestruct H2.\nauto.\nrewrite H2 in H1.\nassert(Nleast_div n>=2).\napply Nleast_div_ge_2.\ndestruct n. inversion H.\nauto with arith.\nreplace q with (q*1).\nrewrite H1.\nrewrite H2.\ndestruct n.\ninversion H.\napply mult_S_lt_compat_l.\nauto. ring.\ndestruct n.\ninversion H.\nauto with arith.\n\napply le_antisym; auto.\nQed.\n\nLemma div_mod a b : a <> 0 -> (a | b) <-> b mod a = 0.\nProof.\n  intros az; split.\n  - intros (k, ->). apply Nat.mod_mul, az.\n  - intros e. exists (b / a).\n    etransitivity. apply (Nat.div_mod _ a), az.\n    lia.\nQed.\n\nLemma eqmod_div m a b : m <> 0 -> a <= b -> a mod m = b mod m <-> (m | b - a).\nProof.\n  intros mz l; split.\n  - intros e. exists ((b / m) - (a / m)).\n    rewrite Nat.mul_comm, Nat.mul_sub_distr_l.\n    rewrite (Nat.div_mod a m mz) at 1.\n    rewrite (Nat.div_mod b m mz) at 1.\n    lia.\n  - intros (k, e).\n    assert (b = a + k * m) by lia.\n    assert (b mod m = (a + k * m) mod m) as -> by congruence.\n    rewrite Nat.mod_add; auto.\nQed.\n\nLemma Nrel_prime_eqmod m a b :\n  m <> 0 ->\n  a mod m = b mod m ->\n  Nrel_prime m a ->\n  Nrel_prime m b.\nProof.\n  intros mz ab ma x xm xb.\n  apply (ma x xm); clear ma.\n  destruct (le_lt_dec a b) as [le|lt].\n  - rewrite eqmod_div in ab; auto.\n    destruct xb as (k & ->).\n    destruct xm as (l & ->).\n    destruct ab as (m & em).\n    exists (k - m * l).\n    replace ((k - m * l) * x) with (k * x - m * (l * x)). lia.\n    rewrite Nat.mul_sub_distr_r. lia.\n  - symmetry in ab.\n    rewrite eqmod_div in ab; auto. 2:lia.\n    destruct xb as (k & ->).\n    destruct xm as (l & ->).\n    destruct ab as (m & em).\n    exists (m * l + k).\n    replace ((m * l + k) * x) with (k * x + m * (l * x)). lia.\n    rewrite Nat.mul_add_distr_r. lia.\nQed.\n\nLemma Ndivide_eqmod m a b :\n  m <> 0 ->\n  a mod m = b mod m ->\n  (m | a) <-> (m | b).\nProof.\n  intros mz ab.\n  rewrite 2 div_mod; auto.\n  split; lia.\nQed.\n\nLemma Nrel_prime_prime (a p : nat) :\n  Nprime p ->\n  Nrel_prime a p <-> ~ (p | a).\nProof.\n  intros Pp.\n  pose proof Nprime_ge_2 _ Pp as p2.\n  split; intros ap.\n  - intros pa.\n    specialize (ap p pa (Ndiv_n_n _)).\n    lia.\n  - apply Nrel_prime_sym.\n    eapply Nrel_prime_eqmod with (a mod p).\n    lia.\n    now rewrite Nat.mod_mod; lia.\n    apply Nrel_prime_sym, Nprime_le_rel_prime; auto.\n    split.\n    + rewrite (Ndivide_eqmod _ _ (a mod p)) in ap.\n      2: lia.\n      2: now rewrite Nat.mod_mod; lia.\n      enough (0 <> a mod p) by lia.\n      intros e. apply ap. rewrite <-e.\n      apply Ndiv_0.\n    + apply Nat.mod_upper_bound. lia.\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/Arith/Ndiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7741528156749331}}
{"text": "Require Export List.\nAdd LoadPath \"../../lnt/tense-logic-in-Coq\".\nRequire Import Strong_induction.\nSet Implicit Arguments.\nExport ListNotations.\n\nDelimit Scope My_scope with M.\nOpen Scope My_scope.\n\n(**Defintions**)\n\n(*Definitaion of Propositional Variables*)\nParameter PropVars : Set.\nHypothesis Varseq_dec : forall x y:PropVars, {x = y} + {x <> y}.\n\n(*Definition of Propositional Formulas*)\nInductive PropF : Set :=\n | Var : PropVars -> PropF\n | Bot : PropF\n | Imp : PropF -> PropF -> PropF\n.\n\nNotation \"# P\" := (Var P) (at level 1) : My_scope.\nNotation \"A → B\" := (Imp A B) (at level 16, right associativity) : My_scope.\nNotation \"⊥\" := Bot (at level 0)  : My_scope.\n\n(* Defined connectives *)\nNotation \"¬ A\" := (A → ⊥) (at level 1)  : My_scope.\nNotation \"A ∧ B\" := ((A → (B → ⊥)) → ⊥) (at level 15, right associativity) : My_scope.\nNotation \"A ∨ B\" := ((A → ⊥) → B) (at level 15, right associativity) : My_scope.\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 => (negb (TrueQ v B)) || (TrueQ v C)\nend.\n\n(* Prove that the defined connectives are correct *)\n\nLemma def_neg_correct (A: PropF) :\n  forall v, TrueQ v (¬ A) = negb (TrueQ v A).\nProof. intros. destruct A.\n       simpl. rewrite Bool.orb_false_r. trivial.\n       simpl. trivial.\n       simpl. rewrite Bool.orb_false_r. trivial.\nQed.\n\nLemma def_or_correct (A B: PropF) :\n  forall v, TrueQ v (A ∨ B) = orb (TrueQ v A) (TrueQ v B).\nProof. intros. simpl. repeat rewrite Bool.orb_false_r.\n       rewrite Bool.negb_involutive.\n       trivial.\nQed.\n\nLemma def_and_correct (A B: PropF) :\n  forall v, TrueQ v (A ∧ B) = andb (TrueQ v A) (TrueQ v B).\nProof. intros. simpl. repeat rewrite Bool.orb_false_r.\n       repeat rewrite Bool.negb_orb.\n       repeat rewrite Bool.negb_involutive.\n       reflexivity.\nQed.\n\nFixpoint  weight p :=\n    match p with\n      | # q' => 0\n      | Bot => 0\n      | p' → q' => S (max (weight p') (weight q'))\n      end.\n\n(*Gentzen's Sequent Calculus*)\n\nReserved Notation \"Γ |- Δ >> n\" (at level 80).\nInductive LK : nat -> list PropF -> list PropF -> Prop :=\n| LKId  : forall A Γ Δ, In (Var A) Δ -> In (Var A) Γ -> LK 0 Γ Δ\n| LKBot : forall Γ Δ,   In ⊥ Γ  -> LK 0 Γ Δ\n| LKImpL : forall n m A B Γ1 Γ2 Δ,\n              LK n (Γ1++B::Γ2) Δ -> LK m (Γ1++Γ2) (A::Δ)\n           -> LK (S (max n m)) (Γ1++A→B::Γ2) Δ\n| LKImpR : forall n A B Γ Δ1 Δ2,\n              LK n (A::Γ) (Δ1++B::Δ2)\n           -> LK (S n) Γ (Δ1++A→B::Δ2)\nwhere \"Γ |- Δ >> n\" := (LK (n) (Γ) (Δ)) : My_scope.\n\n(**Auxiliary Lemmas**)\n\nLemma in_elt : forall (A : Type) (a : A) L1 L2, In a (L1 ++ a :: L2).\nProof.\nintros.\napply in_app_iff.\nright.\nsimpl.\nleft.\nreflexivity.\nQed.\n\nLemma cons_eq_app: forall (A : Type) (x y z : list A) (a : A),\n  a :: x = y ++ z -> y = [] /\\ z = a :: x \\/\n                         exists (y' : list A), y = a :: y' /\\ x = y' ++ z.\nProof.\nintros.\ndestruct y.\n simpl in H. subst. tauto.\n simpl in H. injection H. intros. right. subst. exists y. tauto.\nQed.\n\nLemma app_eq_app: forall (A : Type) (w x y z : list A),\n  w ++ x = y ++ z -> exists (m : list A),\n    w = y ++ m /\\ z = m ++ x \\/ y = w ++ m /\\ x = m ++ z.\nProof.\n intro. intro.\n induction w.\n    simpl. intros. exists y. rewrite H. tauto.\n\n    intros. simpl in H.\n    apply cons_eq_app in H.\n    destruct H.  destruct H. rewrite H. simpl.\n    exists (a :: w). rewrite H0. simpl. tauto.\n    destruct H. destruct H.\n    apply IHw in H0. destruct H0. destruct H0. destruct H0.\n    rewrite H.  rewrite H0.  rewrite H1.  simpl.\n    exists x1. tauto.\n    destruct H0. rewrite H.  rewrite H0.  rewrite H1.  simpl.\n    exists x1. tauto.\nQed.\n\nLemma cons_single_app: forall T (A : T) L, A :: L = [A] ++ L.\nProof.\nreflexivity.\nQed.\n\nLemma in_app_comm : forall (A : Type) (a : A) (X Y : list A), In a (X ++ Y) <-> In a (Y ++ X).\nProof.\nintros.\ninduction X.\n\nrewrite app_nil_r.\nrewrite app_nil_l.\nreflexivity.\n\nrewrite! in_app_iff.\nfirstorder.\nQed.\n\nLemma in_cons_comm : forall (A : Type) (a b c: A) (X Y : list A), In a (X ++ b :: c :: Y) <-> In a (X ++ c :: b :: Y).\nProof.\nintros.\nrewrite! in_app_iff.\nsimpl.\nfirstorder.\nQed.\n\nLemma in_list_eq : forall {A : Type} {l1 l2 l3 : list A} {a : A}, (l1 ++ a :: l2) = l3 -> In a l3.\nProof.\nintros.\nrewrite <- H.\napply in_app_iff.\nright.\napply in_eq.\nQed.\n\nLemma le_trans: forall a b c, a <= b -> b <= c -> a <= c.\nProof.\nintros.\nrewrite H.\nassumption.\nQed.\n\nLemma in_app_add: forall (A : Type) (a : A) (L1 L2 : list A), In a L1 -> In a (L1 ++ L2).\nProof.\nintros.\ninduction L2.\n\nrewrite app_nil_r.\nassumption.\n\nrewrite cons_single_app.\napply in_app_comm.\nsimpl.\nright.\napply in_app_comm.\nassumption.\nQed.\n\nLemma imp_not_var: forall A B C L1 L2, In (# A) (L1 ++ Imp B C :: L2) -> In (# A) (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma imp_not_bot: forall B C L1 L2, In Bot (L1 ++ Imp B C :: L2) -> In Bot (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma in_double: forall (A : Type) (a : A) B L1 L2 L3, In a (L1 ++ B :: L2 ++ B :: L3) -> In a (L1 ++ B :: L2 ++ L3) .\nProof.\nintros.\nrewrite in_app_iff in H.\nsimpl in H.\nrewrite or_comm in H.\nrewrite or_assoc in H.\ndestruct H.\n\nsubst.\nfirstorder.\n\nrewrite in_app_comm in H.\nrewrite <- app_comm_cons in H.\nsimpl in H.\nrewrite in_app_comm in H.\nrewrite or_comm in H.\nrewrite in_app_iff.\nassumption.\nQed.\n\n(*Sanity Check that Γ1,A,Γ2 |- Δ1,A,Δ2 is Deriavable *)\n\nLemma Id_extension : forall A Γ Δ, In A Δ -> In A Γ -> exists n, weight A <= n /\\ Γ |- Δ >> n.\nProof.\nintros A.\ninduction A.\n\n(*PropVar*)\nintros.\nexists 0.\nsplit.\napply le_n.\napply (LKId p _ _ H H0).\n\n(*Bot*)\nintros.\nexists 0.\nsplit.\napply le_n.\napply (LKBot _ _ H0).\n\n(*Imp*)\nintros.\nsimpl.\napply in_split in H.\ndestruct H as [l1 [l2 Z1]].\napply in_split in H0.\ndestruct H0 as [l3 [l4 Z2]].\nsubst.\ndestruct (IHA1 (A1 :: l3 ++ l4) (A1 :: l1 ++ A2 :: l2) (in_eq A1 _) (in_eq A1 _)) as [a [I1 I2]].\ndestruct (IHA2 ((A1 :: l3) ++ A2 :: l4) (l1 ++ A2 :: l2) (in_elt A2 _ _) (in_elt A2 _ _)) as [b [I3 I4]].\npose (LKImpL _ _ _ I4 I2) as I5.\nexists (S (S (max b a))).\nsplit.\n\nrewrite PeanoNat.Nat.max_comm.\napply (le_n_S _ _ (le_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ I3 I1))).\n\napply (LKImpR _ _ _ I5).\nQed.\n\n(*Proof of Other Structural Inferences*)\n\nLemma exchange_R:\n  forall n Γ E F Δ1 Δ2 (D: LK n Γ (Δ1 ++ E :: F :: Δ2)), LK n Γ (Δ1 ++ F :: E :: Δ2).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\napply in_cons_comm in Suc.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_comm_cons in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LKImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqA) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I1).\n\ndestruct l.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\napply (LKImpR _ _ _ I1).\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in I.\nrewrite <- !app_comm_cons in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\nrewrite (cons_single_app F _).\nrewrite (cons_single_app F _) in I1.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in I.\nrewrite app_assoc in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\nrewrite app_assoc_reverse in *.\napply (LKImpR _ _ _ I1).\nQed.\n\nLemma exchange_L:\n  forall n E F Γ1 Γ2 Δ (D: LK n (Γ1 ++ E :: F :: Γ2) Δ), LK n (Γ1 ++ F :: E :: Γ2) Δ.\nProof.\nintro n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\napply in_cons_comm in Ant.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply in_cons_comm in Fal.\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L1 R).\n\ninversion Z2 as [[Z3 Z4]].\ndestruct l.\n\ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\napply (LKImpL _ _ _ L1 R).\n \ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L1 R).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite app_assoc_reverse in *.\napply (LKImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\napply (LKImpR _ _ _ I1).\nQed.\n\n(*Strengthening Exchange from Single Elements to Lists*)\n(*----------------------------------------------------*)\n\nLemma move_R_R: forall n Γ A Δ3 Δ2 Δ1,\n                LK n Γ (Δ1 ++ A :: Δ2 ++ Δ3) ->\n                LK n Γ (Δ1 ++ Δ2 ++ A :: Δ3).\nProof.\nintros n Γ A Δ3 Δ2.\ninduction Δ2.\n\nintros.\nassumption.\n\nintros.\nrewrite cons_single_app. \nrewrite app_assoc_reverse.\nrewrite app_assoc.\napply IHΔ2.\nrewrite app_assoc_reverse.\napply exchange_R. \nassumption.\nQed.\n\nLemma swap_R:\n  forall n Γ Δ2 Δ3 Δ1 Δ4,\n    LK n Γ (Δ1 ++ Δ2 ++ Δ3 ++ Δ4) ->\n    LK n Γ (Δ1 ++ Δ3 ++ Δ2 ++ Δ4).\nProof.\nintros n Γ Δ2 Δ3.\ninduction Δ2.\n\nintros.\nassumption.\n\nintros.\napply move_R_R.\nrewrite cons_single_app.\nrewrite app_assoc.\nrewrite cons_single_app in H.\nrewrite app_assoc_reverse in H.\nrewrite app_assoc in H.\napply (IHΔ2 _ _ H).\nQed.\n\nLemma move_R_L:\n  forall n Δ A Γ3 Γ2 Γ1,\n    LK n (Γ1 ++ A :: Γ2 ++ Γ3) Δ ->\n    LK n (Γ1 ++ Γ2 ++ A :: Γ3) Δ.\nProof.\nintros n Δ A Γ3 Γ2.\ninduction Γ2.\n\nintros.\nassumption.\n\n\nintros.\nrewrite cons_single_app.\nrewrite app_assoc_reverse.\nrewrite app_assoc.\napply IHΓ2.\nrewrite app_assoc_reverse.\napply exchange_L.\nassumption.\nQed.\n\nLemma swap_L:\n  forall n Δ Γ2 Γ3 Γ1 Γ4,\n    LK n (Γ1 ++ Γ2 ++ Γ3 ++ Γ4) Δ->\n    LK n (Γ1 ++ Γ3 ++ Γ2 ++ Γ4) Δ.\nProof.\nintros n Δ Γ2 Γ3.\ninduction Γ2.\n\nintros.\nassumption.\nintros.\n\napply move_R_L.\nrewrite cons_single_app in H.\nrewrite app_assoc_reverse in H.\nrewrite app_assoc in H.\n\nrewrite cons_single_app.\nrewrite app_assoc.\napply (IHΓ2 (Γ1 ++ [a]) Γ4 H).\nQed.\n\n(*-----------------------------------------*)\n(*Return to Proofs of Structural Inferneces*)\n\nLemma weakening_R:\n  forall n Γ Δ1 Δ2 (D: LK n Γ (Δ1 ++ Δ2)),\n    forall W, (LK n Γ (Δ1 ++ W ++ Δ2)).\nProof.\nintro n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\nrewrite in_app_comm in Suc.\napply (in_app_add _ _ W) in Suc.\nrewrite app_assoc_reverse in Suc.\nrewrite in_app_comm in Suc.\nrewrite app_assoc_reverse in Suc.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\nrewrite app_comm_cons in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\napply (LKImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite <- app_nil_r.\nrewrite! app_assoc_reverse.\napply swap_R.\nrewrite app_assoc.\nrewrite <- EqA.\nrewrite app_assoc_reverse.\nrewrite <- app_nil_r in I.\npose (H _ (le_n _) _ _ _ I W) as I1.\nrewrite! app_assoc_reverse in I1.\napply (LKImpR _ _ _ I1).\nQed.\n\nLemma weakening_L:\n    forall n Γ1 Γ2 Δ (D: LK n (Γ1 ++ Γ2) Δ),\n      forall W, LK n (Γ1 ++ W ++ Γ2) Δ.\nProof.\nintro n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\nrewrite in_app_comm in Ant.\napply (in_app_add _ _ W) in Ant.\nrewrite app_assoc_reverse in Ant.\nrewrite in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\nrewrite in_app_comm in Fal.\napply (in_app_add _ _ W) in Fal.\nrewrite app_assoc_reverse in Fal.\nrewrite in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite! app_assoc in *.\napply (LKImpL _ _ _ L1 R1).\n\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite app_assoc_reverse.\napply swap_L.\nrewrite <- Z2.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ I W) as I1.\napply (LKImpR _ _ _ I1).\nQed.\n\n(* Implication left derives one sequent from two previously derived sequents\n   so inversion is split into two lemmas, one for each of the sequents    *)\n\nLemma inv_ImpL1 :\n  forall n E F Γ1 Γ2 Δ (D: LK n (Γ1 ++ E→F :: Γ2) Δ),\n    (exists m, m <= n /\\ LK m (Γ1 ++ Γ2) (E::Δ)).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\napply imp_not_var in Ant.\npose (in_app_add _ Δ [E] Suc) as Suc1.\napply in_app_comm in Suc1.\napply (LKId _ _ _ Suc1 Ant).\n\n(*Bot*)\napply imp_not_bot in Fal.\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists b.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_r _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\npose (exchange_R _ _ [] _ R2) as R3.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L2 R3).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists b.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_r _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\npose (exchange_R _ _ [] _ R2) as R3.\nrewrite app_assoc_reverse in *.\napply (LKImpL _ _ _ L2 R3).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite app_comm_cons in *.\napply (LKImpR _ _ _ I2).\nQed.\n\nLemma inv_ImpL2:\n  forall n E F Γ1 Γ2 Δ (D: LK n (Γ1 ++ (E→F) :: Γ2) Δ),\n    (exists m, m <= n /\\ LK m (Γ1 ++ F :: Γ2) Δ).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\napply imp_not_var in Ant.\napply in_app_comm in Ant.\napply (in_app_add _ _ [F] ) in Ant.\nrewrite app_assoc_reverse in Ant.\napply in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply imp_not_bot in Fal.\napply in_app_comm in Fal.\napply (in_app_add _ _ [F] ) in Fal.\nrewrite app_assoc_reverse in Fal.\napply in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_assoc_reverse in *.\napply (LKImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LKImpR _ _ _  I2).\nQed.\n\nLemma inv_ImpR:\n  forall n E F Δ1 Δ2 Γ (D : LK n Γ (Δ1++E→F::Δ2)),\n   (exists m, m <= n /\\ LK m (E::Γ) (Δ1++F::Δ2)).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsubst.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ID*)\napply imp_not_var in Suc.\napply in_app_comm in Suc.\napply (in_app_add _ _ [F] ) in Suc.\nrewrite app_assoc_reverse in Suc.\napply in_app_comm in Suc.\nrewrite app_assoc_reverse in Suc.\napply (in_app_add _ _ [E]) in Ant.\nrewrite in_app_comm in Ant.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (in_app_add Bot Γ [E]) in Fal.\napply in_app_comm in Fal.\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_comm_cons in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_comm_cons in L2.\napply (LKImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqA) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite <- (app_nil_l (E :: A :: Γ)) in I2.\napply exchange_L in I2.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in I.\nrewrite app_assoc in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite <- (app_nil_l (E :: A :: Γ)) in I2.\napply exchange_L in I2.\nrewrite app_assoc_reverse in *.\napply (LKImpR _ _ _ I2).\nQed.\n\nTheorem contraction:\n  forall n X,\n    (forall Γ1 Γ2 Γ3 Δ (D : (Γ1 ++ X :: Γ2 ++ X :: Γ3) |- Δ >> n),\n       exists m, m <= n /\\ LK m (Γ1 ++ X :: Γ2 ++ Γ3 ) Δ) /\\\n    (forall Δ1 Δ2 Δ3 Γ (D : Γ |- Δ1 ++ X :: Δ2 ++ X :: Δ3 >> n),\n       exists m, m <= n /\\ LK m Γ (Δ1 ++ X :: Δ2 ++ Δ3)).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsplit.\n\n(*Left*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\nsubst.\napply in_double in Ant.\napply (LKId A _ _ Suc Ant).\n\n(*Bot*)\nsubst.\napply in_double in Fal.\napply (LKBot _ _ Fal).\n\n(*Right*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\napply in_double in Suc.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive*)\nintros.\nsplit.\n\n(*Left*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ImpL2 _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in L2.\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) B) as [X1 _].\ndestruct (X1 _ _ _ _ L2) as [d [L3 L4]].\nrewrite app_assoc in R.\ndestruct (inv_ImpL1 _ _ _ _ R) as [e [R1 R2]].\nrewrite app_assoc_reverse in R2.\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) A) as [_ Y2].\ndestruct (Y2 [] [] _ _ R2) as [f [R3 R4]].\nexists (S (Nat.max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\napply (LKImpL _ _ _ L4 R4).\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ A → B :: ΓB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 | Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) p) as [X1 _].\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite app_assoc_reverse in L.\ndestruct (X1 _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) p) as [Y1 _].\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite app_assoc_reverse in R.\ndestruct (Y1 _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite app_assoc in *.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L2 R2).\n\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (inv_ImpL2 _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) B) as [X1 _].\ndestruct (X1 _ _ _ _ L2) as [d [L3 L4]].\nrewrite app_assoc_reverse in R.\ndestruct (inv_ImpL1 _ _ _ _ R) as [e [R1 R2]].\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) A) as [_ Y2].\ndestruct (Y2 [] [] _ _ R2) as [f [R3 R4]].\nexists (S (Nat.max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L4.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L4 R4).\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z1]].\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) p) as [X1 _].\nrewrite app_comm_cons in L.\nrewrite (app_assoc (p :: l)) in L.\ndestruct (X1 _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\nrewrite <- app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) p) as [Y1 _].\ndestruct (Y1 _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite app_assoc_reverse in *.\nrewrite app_assoc in *.\napply (LKImpL _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ImpL2 _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ ((le_trans L1 (PeanoNat.Nat.le_max_l _ _))) B) as [X1 _].\nrewrite app_assoc_reverse in L2.\ndestruct (X1 _ _ _ _ L2) as [d [L3 L4]].\nrewrite app_assoc in R.\ndestruct (inv_ImpL1 _ _ _ _ R) as [e [R1 R2]].\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) A) as [_ Y2].\ndestruct (Y2 [] [] _ _ R2) as [f [R3 R4]].\nexists (S (Nat.max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\nrewrite app_assoc_reverse in R4.\napply (LKImpL _ _ _ L4 R4).\n\ninversion Z2.\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) X) as [X1 _].\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (X1 _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) X) as [Y1 _].\nrewrite app_assoc in R.\ndestruct (Y1 _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_assoc_reverse in L2.\nrewrite app_assoc_reverse in R2.\nrewrite app_assoc_reverse.\napply (LKImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\ndestruct (H _ (le_n _) X) as [X1 _].\nrewrite app_comm_cons in I.\ndestruct (X1 _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LKImpR _ _ _ I2).\n\n(*Right*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) X) as [_ X2].\ndestruct (X2 _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) X) as [_ Y2].\nrewrite app_comm_cons in R.\ndestruct (Y2 _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LKImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqA) as [l [[Z1 Z2] | [Z1 Z2]]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in I.\nrewrite app_assoc in I.\ndestruct (inv_ImpR _ _ _ _ I) as [b [I1 I2]].\ndestruct (H _ I1 A) as [X1 _].\ndestruct (X1 [] [] _ _ I2) as [c [I3 I4]].\ndestruct (H _ (le_trans I3 I1) B) as [_ Y2].\nrewrite app_assoc_reverse in I4.\ndestruct (Y2 _ _ _ _ I4) as [d [I5 I6]].\nexists (S d).\nsplit.\n\napply (le_n_S _ _ (le_trans I5 (le_trans I3 I1))).\n\napply (LKImpR _ _ _ I6).\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ A → B :: ΔB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 |Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z6]].\nsubst.\nrewrite app_assoc_reverse in I.\nrewrite <- app_comm_cons in I.\nrewrite app_assoc_reverse in I.\ndestruct (H _ (le_n _) p) as [_ X2].\ndestruct (X2 _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite cons_single_app.\napply swap_R.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_R in I2.\nrewrite app_comm_cons in I2.\nrewrite! app_assoc in *.\napply (LKImpR _ _ _ I2).\n\nsubst.\nrewrite app_assoc_reverse in I.\ndestruct (inv_ImpR _ _ _ _ I) as [b [I1 I2]].\ndestruct (H _ I1 A) as [X1 _].\ndestruct (X1 [] [] _ _ I2) as [c [I3 I4]].\ndestruct (H _ (le_trans I3 I1) B) as [_ Y2].\ndestruct (Y2 _ _ _ _ I4) as [d [I5 I6]].\nexists (S d).\nsplit.\n\napply (le_n_S _ _ (le_trans I5 (le_trans I3 I1))).\n\nrewrite cons_single_app.\napply swap_R.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_R in I6.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I6).\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\ndestruct (H _ (le_n _) p) as [_ X2].\nrewrite app_assoc_reverse in I.\nrewrite app_comm_cons in I.\nrewrite <- app_comm_cons in I.\nrewrite app_assoc in I.\ndestruct (X2 _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite cons_single_app.\napply swap_R.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_R in I2.\nrewrite app_assoc_reverse in I2.\nrewrite app_assoc in *.\napply (LKImpR _ _ _ I2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in I.\nrewrite app_assoc in I.\ndestruct (inv_ImpR _ _ _ _ I) as [b [I1 I2]].\ndestruct (H _ I1 A) as [X1 _].\ndestruct (X1 [] [] _ _ I2) as [c [I3 I4]].\ndestruct (H _ (le_trans I3 I1) B) as [_ Y2].\nrewrite app_assoc_reverse in I4.\ndestruct (Y2 _ _ _ _ I4) as [d [I5 I6]].\nexists (S d).\nsplit.\n\napply (le_n_S _ _ (le_trans I5 (le_trans I3 I1))).\n\napply (LKImpR _ _ _ I6).\n\ninversion Z2.\nsubst.\ndestruct (H _ (le_n _) X) as [_ X2].\nrewrite app_comm_cons in I.\nrewrite app_assoc in I.\ndestruct (X2 _ _ _ _ I) as [b [ I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\nrewrite app_assoc_reverse in I2.\nrewrite app_assoc_reverse.\napply (LKImpR _ _ _ I2).\nQed.\n\n(*Case Bashing Belonging in Multiple Lists with Known First Value*)\n(*Used for Id Case in Cut When Avoiding Contraction*)\n\nLemma cut_gax:\n  forall (A A0 A1 : PropF) (L1 L2 : list PropF),\n       In A0 L1 -> In A0 ([A] ++ L2)\n    -> In A1 L2 -> In A1 ([A] ++ L1)\n    -> In A0 L1 /\\ In A0 L2 \\/ In A1 L1 /\\ In A1 L2.\nProof.\nintros.\ndestruct H0.\n\ndestruct H2.\n\nsubst.\nfirstorder.\n\nfirstorder.\n\nfirstorder.\nQed.\n\n\nTheorem cut_elimination_no_contraction:\n  forall A n m Γ Δ (D : LK n Γ ([A] ++ Δ)) (D1 : LK m ([A] ++ Γ) Δ),\n    exists k, Γ |- Δ >> k.\nProof.\nintros A.\ninduction A.\n\n(*PropVar*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros m.\ninduction m using strong_induction.\n\n(*Base Case m : n = 0*)\nintros.\nsubst.\nexists 0.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\nsubst.\ninversion D1 as [ DA DΓT DΔT DSuc DAnt DHeight DEqS DEqA | DΓT DΔT DFal DEqS DEqA | Da Db DA DB DΓA DΓB DΔT DL DR DHeight DEqS DEqA | Da DA DB DΓT DΔA DΔB DI DHeight DEqS DEqA].\n\n\n(*Id : Id*)\ndestruct (cut_gax Ant Suc DSuc DAnt) as [[Ant1 Suc1] | [Ant1 Suc1]].\n\napply (LKId _ _ _ Suc1 Ant1).\n\napply (LKId _ _ _ Suc1 Ant1).\n\n(*Id : Bot*)\ndestruct Suc as [Suc | Suc].\n\ndestruct DFal as [DFal | DFal].\n\ndiscriminate.\n\napply (LKBot _ _ DFal).\n\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive m : n = 0*)\nintros.\nsubst.\ninversion D1 as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct ΓA.\n\ninversion EqS.\n\ninversion EqS.\nsubst.\ndestruct (inv_ImpL2 _ _ _ _ D) as [c [L1 L2]].\ninversion L1.\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ L2 L) as [c L3].\ndestruct (inv_ImpL1 _ _ _ _ D) as [d [R1 R2]].\ninversion R1.\nsubst.\nrewrite cons_single_app in R2.\nrewrite <- app_nil_l in R2.\napply swap_R in R2.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ R2 R) as [d R3].\nexists (S (max c d)).\napply (LKImpL _ _ _ L3 R3).\n\n(*ImpR*)\nsubst.\nrewrite app_assoc in D.\ndestruct (inv_ImpR _ _ _ _ D) as [b [I1 I2]].\ninversion I1.\nsubst.\nrewrite cons_single_app in I.\nrewrite <- (app_nil_l ( [A] ++ [# p] ++ Γ)) in I.\napply swap_L in I.\ndestruct (H _ (le_n _) _ _ I2 I) as [c I3].\nexists (S c).\napply (LKImpR _ _ _ I3).\n\n(*Inductive n*)\nintros.\nsubst.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL2 _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\ndestruct (inv_ImpL1 _ _ _ _ D1) as [e [R1 R2]].\nrewrite cons_single_app in R.\nrewrite <- app_nil_l in R.\napply swap_R in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max d f)).\napply (LKImpL _ _ _ L3 R3).\n\n(*ImpR*)\ndestruct ΔA.\n\ninversion EqA.\n\ninversion EqA.\nsubst.\ndestruct (inv_ImpR _ _ _ _ D1) as [b [I1 I2]].\nrewrite cons_single_app in I2.\nrewrite <- (app_nil_l ( [A] ++ [# p] ++ Γ)) in I2.\napply swap_L in I2.\ndestruct (H _ (le_n _) _ _ _ I I2) as [c I3].\nexists (S c).\napply (LKImpR _ _ _ I3).\n\n(*Bot*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\nsubst.\nexists 0.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\ndestruct Suc as [Suc | Suc].\n\ninversion Suc.\n\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive n*)\nintros.\nsubst.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL2 _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\ndestruct (inv_ImpL1 _ _ _ _ D1) as [e [R1 R2]].\nrewrite <- app_nil_l in R.\napply exchange_R in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max d f)).\napply (LKImpL _ _ _ L3 R3).\n\n(*ImpR*)\ndestruct ΔA.\n\ninversion EqA.\n\ninversion EqA.\nsubst.\ndestruct (inv_ImpR _ _ _ _ D1) as [b [I1 I2]].\nrewrite <- (app_nil_l ( A :: [Bot] ++ Γ)) in I2.\napply exchange_L in I2.\ndestruct (H _ (le_n _) _ _ _ I I2) as [c I3].\nexists (S c).\napply (LKImpR _ _ _ I3).\n\n(*Imp*)\nintros.\nsubst.\ndestruct (inv_ImpR _ _ [] _ D) as [a [I1 I2]].\ndestruct (inv_ImpL1 _ _ [] _ D1) as [b [I3 I4]].\nrewrite cons_single_app in I4.\npose (weakening_R _ _ I4 [A2]) as I5.\ndestruct (IHA1  _ _ _ _ I5 I2) as [c I6].\ndestruct (inv_ImpL2 _ _ [] _ D1) as [d [I7 I8]].\ndestruct (IHA2 _ _ _ _ I6 I8) as [e I9].\nexists e.\nassumption.\nQed.\n\nTheorem cut_elimination_with_contraction:\n  forall A n m Γ Δ (D : LK n Γ ([A] ++ Δ)) (D1 : LK m ([A] ++ Γ) Δ),\n    exists k, Γ |- Δ >> k.\nProof.\nintros A.\ninduction A.\n\n(*PropVar*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\ndestruct Suc as [Suc | Suc].\n\nsubst.\nrewrite <- Suc in Ant.\ndestruct (in_split _ _ Ant) as [l1 [l2 Z1]].\nsubst.\ndestruct (contraction m #p) as [X1 _].\ndestruct (X1 [] _ _ _ D1) as [a [I1 I2]].\napply move_R_L in I2.\nexists a.\nassumption.\n\nexists 0.\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\nexists 0.\napply (LKBot _ _ Fal).\n\n(*Inductive n*)\nintros.\nsubst.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL2 _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\ndestruct (inv_ImpL1 _ _ _ _ D1) as [e [R1 R2]].\nrewrite cons_single_app in R.\nrewrite <- app_nil_l in R.\napply swap_R in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max d f)).\napply (LKImpL _ _ _ L3 R3).\n\n(*ImpR*)\ndestruct ΔA.\n\ninversion EqA.\n\ninversion EqA.\nsubst.\ndestruct (inv_ImpR _ _ _ _ D1) as [b [I1 I2]].\nrewrite cons_single_app in I2.\nrewrite <- (app_nil_l ( [A] ++ [# p] ++ Γ)) in I2.\napply swap_L in I2.\ndestruct (H _ (le_n _) _ _ _ I I2) as [c I3].\nexists (S c).\napply (LKImpR _ _ _ I3).\n\n(*Bot*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\nsubst.\nexists 0.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*Id*)\ndestruct Suc as [Suc | Suc].\n\ninversion Suc.\n\napply (LKId _ _ _ Suc Ant).\n\n(*Bot*)\napply (LKBot _ _ Fal).\n\n(*Inductive n*)\nintros.\nsubst.\ninversion D as [ A ΓT ΔT Suc Ant Height EqS EqA | ΓT ΔT Fal EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT ΔA ΔB I Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL2 _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\ndestruct (inv_ImpL1 _ _ _ _ D1) as [e [R1 R2]].\nrewrite <- app_nil_l in R.\napply exchange_R in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max d f)).\napply (LKImpL _ _ _ L3 R3).\n\n(*ImpR*)\ndestruct ΔA.\n\ninversion EqA.\n\ninversion EqA.\nsubst.\ndestruct (inv_ImpR _ _ _ _ D1) as [b [I1 I2]].\nrewrite <- (app_nil_l ( A :: [Bot] ++ Γ)) in I2.\napply exchange_L in I2.\ndestruct (H _ (le_n _) _ _ _ I I2) as [c I3].\nexists (S c).\napply (LKImpR _ _ _ I3).\n\n(*Imp*)\nintros.\nsubst.\ndestruct (inv_ImpR _ _ [] _ D) as [a [I1 I2]].\ndestruct (inv_ImpL1 _ _ [] _ D1) as [b [I3 I4]].\nrewrite cons_single_app in I4.\npose (weakening_R _ _ I4 [A2]) as I5.\ndestruct (IHA1  _ _ _ _ I5 I2) as [c I6].\ndestruct (inv_ImpL2 _ _ [] _ D1) as [d [I7 I8]].\ndestruct (IHA2 _ _ _ _ I6 I8) as [e I9].\nexists e.\nassumption.\nQed.", "meta": {"author": "aarondroidbryce", "repo": "LK_Formalisation_Coq", "sha": "17714aa86f76355ba2f93336b869f2ca05457b05", "save_path": "github-repos/coq/aarondroidbryce-LK_Formalisation_Coq", "path": "github-repos/coq/aarondroidbryce-LK_Formalisation_Coq/LK_Formalisation_Coq-17714aa86f76355ba2f93336b869f2ca05457b05/Aaron_LK_cut_elim_no_bound_shorten_new_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.774152807171249}}
{"text": "(************ bools ************)\nModule Nats.\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\nFixpoint plus (a b : nat) :=\n  match a with\n  | O => b\n  | S n' => S(plus n' b)\n  end.\n\nFixpoint minus (a b : nat) :=\n  match a,b with\n  | O, _ => O\n  | _, O => a\n  | S a',S b' => minus a' b'\n  end.\n\nFixpoint mult (a b : nat) :=\n  match b with\n  | O => O\n  | S O => a\n  | S b' => plus a (mult a b')\n  end.\n\nFixpoint exp (a b : nat) :=\n  match b with\n  | O => S O\n  | S O => a\n  | S b' => mult a (exp a b')\n  end.\n\nFixpoint fact (n : nat) :=\n  match n with\n  | O => O\n  | S O => S O\n  | S n' => mult n (fact n')\n  end.\n\nFixpoint isEven (n : nat) :=\n  match n with\n  | O => true\n  | S O => false\n  | S(S n') => isEven n'\n  end.\n\nDefinition isOdd (n : nat) := negb (isEven n).\n\n\nFixpoint eq (a b : nat) :=\n  match a with\n  | O => match b with\n       | O => true\n       | _ => false\n       end\n  | S a' => match b with\n       | O => false\n       | S (b') => eq a' b'\n       end\n  end.\n\nFixpoint isLessOrEqual (a b : nat) :=\n  eq (minus a b) O. \nFixpoint isLess (a b : nat) :=\n  negb (isLessOrEqual b a).\n\nCompute Nats.plus(S (S (S (S O)))) (S(S(O))).\nCompute Nats.minus(S (S (S (S O)))) (S(S(O))).\nCompute Nats.mult(S (S (S (S O)))) (S(S(O))).\nCompute Nats.exp(S (S (S (S O)))) (S(S(O))).\nCompute Nats.fact(S (S (S (S O)))).\nCompute isEven (Nats.plus(S (S (S (S O)))) (S(S(O)))).\nCompute isOdd (Nats.plus(S (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\" := (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.\nNotation \"x =? y\" := (eq x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (isLessOrEqual x y) (at level 70) : nat_scope.\nNotation \"x <? y\" := (isLess x y) (at level 70) : nat_scope.\n\nCompute ((S(S O)) * (plus (S O) (S O)) =? S(S(S(S(O))))).\nCompute (S(S O)) <=? (S(S(S(S(O))))).\nCompute (S(S O)) <=? (S(S(O))).\nCompute (S(S O)) <? (S(S(O))).\nCompute (S(S O)) <? (S(S(S(O)))).\n\nCompute S(O) + S(S(S(O))).\n\n\n\nCheck S.\nCheck pred.\nCheck Nats.plus.\n\nEnd Nats.\n\nTheorem neutral : forall n:nat, O + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem xPlusx : forall n m:nat, n = m -> n + n = m + m.\nProof. intros n m H. rewrite -> H. reflexivity. Qed.\n\nTheorem plusId : forall n m o : nat, n = m -> m = o -> n + m = m + o.\nintros n m o H H'. rewrite -> H. rewrite <- H'. reflexivity. Qed.\n\nTheorem multZeroPlus : forall n m : nat, (O + n) * m = n * m.\nProof. intros n m. rewrite neutral. reflexivity. Qed.\n\nTheorem multS1 : forall n m : nat,\n  m = S n -> m * (S n) = m * m.\nProof. intros n m H. rewrite H. reflexivity. Qed.\n\nTheorem succZero : forall n : nat, (eq (S n) O) = False.\nProof. intros n. destruct n as [|n'] eqn:E.\n  - Abort.\n\nTheorem negNeg: forall b : bool, negb(negb b) = b.\nProof. intros b. destruct b eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity. \nQed.\n\nTheorem andCommutative : forall a b : bool, andb a b = andb a b.\nProof. intros a b. destruct a eqn:E.\n -destruct b.\n    +reflexivity.\n    +reflexivity.\n -destruct b.\n    +reflexivity.\n    +reflexivity. \nQed.\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(* NEXT: More on Notation (Optional) and exercise https://softwarefoundations.cis.upenn.edu/lf-current/Basics.html *)\n\nTheorem andTrueElim: forall b c : bool, \n                     andb b c %bool = true -> c = true.\nProof. intros [] [].\n  -simpl. reflexivity.\n  -intros []. simpl. reflexivity.\n  -simpl. reflexivity.\n  -intros []. 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. intros f x b. rewrite x. rewrite x. reflexivity. Qed.\n\nTheorem andb_eq_orb :\n  forall(b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof. intros b c. destruct b.\n  -simpl. destruct c. reflexivity. easy.\n  -simpl. destruct c. easy. easy.\n\nInductive bin : Type :=\n | Z\n | O (n : bin)\n | I (n : bin).\n\nFixpoint allOne(m:bin) : bool :=\n  match m with\n  | Z => true\n  | I m' => allOne m'\n  | O m' => false\n  end.\n\n\n(* TODO fix incr of binary representation *)\nFixpoint incr(m:bin) : bin :=\n  match m with\n  | Z   => Z\n  | O m' => if allOne m' then I (incr m') else O (incr m')\n  | I m' => if allOne m' then I (incr(m')) else I (incr m')\n  end.\n\nCompute incr (O Z).\nCompute incr (I Z).\nCompute incr (I (O Z)).\nCompute incr (I (I Z)).", "meta": {"author": "marcomaida", "repo": "coqplayground", "sha": "bde3f0511230cd68a6ca1e0445ed7f5d613ce24b", "save_path": "github-repos/coq/marcomaida-coqplayground", "path": "github-repos/coq/marcomaida-coqplayground/coqplayground-bde3f0511230cd68a6ca1e0445ed7f5d613ce24b/nats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7740995589941132}}
{"text": "Require Import\n  Coq.NArith.NArith MathClasses.implementations.peano_naturals MathClasses.theory.naturals\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.naturals MathClasses.interfaces.orders\n  MathClasses.interfaces.additional_operations.  \n\n(* canonical names for relations/operations/constants: *)\n#[global]\nInstance N_equiv : Equiv N := eq.\n#[global]\nInstance N_0 : Zero N := 0%N.\n#[global]\nInstance N_1 : One N := 1%N.\n#[global]\nInstance N_plus : Plus N := Nplus.\n#[global]\nInstance N_mult : Mult N := Nmult.\n\n(* properties: *)\n#[global]\nInstance: SemiRing N.\nProof.\n  repeat (split; try apply _); repeat intro.\n         now apply Nplus_assoc.\n        now apply Nplus_0_r.\n       now apply Nplus_comm.\n      now apply Nmult_assoc.\n     now apply Nmult_1_l.\n    now apply Nmult_1_r.\n   now apply Nmult_comm.\n  now apply Nmult_plus_distr_l.\nQed.\n\n#[global]\nInstance: ∀ x y : N, Decision (x = y) := N.eq_dec.\n\n#[global]\nInstance inject_nat_N: Cast nat N := N_of_nat.\n#[global]\nInstance inject_N_nat: Cast N nat := nat_of_N.\n\n#[global]\nInstance: SemiRing_Morphism nat_of_N.\nProof.\n  repeat (split; try apply _); repeat intro.\n   now apply nat_of_Nplus.\n  now apply nat_of_Nmult.\nQed.\n\n#[global]\nInstance: Inverse nat_of_N := N_of_nat.\n\n#[global]\nInstance: Surjective nat_of_N.\nProof. constructor. intros x y E. rewrite <- E. now apply nat_of_N_of_nat. now apply _. Qed.\n\n#[global]\nInstance: Injective nat_of_N.\nProof. constructor. exact nat_of_N_inj. apply _. Qed.\n\n#[global]\nInstance: Bijective nat_of_N := {}.\n\n#[global]\nInstance: Inverse N_of_nat := nat_of_N.\n\n#[global]\nInstance: Bijective N_of_nat.\nProof. apply jections.flip_bijection. Qed.\n\n#[global]\nInstance: SemiRing_Morphism N_of_nat.\nProof. change (SemiRing_Morphism (nat_of_N⁻¹)). split; apply _. Qed.\n\n#[global]\nInstance: NaturalsToSemiRing N := retract_is_nat_to_sr N_of_nat.\n#[global]\nInstance: Naturals N := retract_is_nat N_of_nat.\n\n(* order *)\n#[global]\nInstance N_le: Le N := N.le.\n#[global]\nInstance N_lt: Lt N := N.lt.\n\n#[global]\nInstance: FullPseudoSemiRingOrder N_le N_lt.\nProof.\n  assert (PartialOrder N_le).\n   repeat (split; try apply _). exact N.le_antisymm.\n  assert (SemiRingOrder N_le).\n   split; try apply _.\n     intros x y E. exists (Nminus y x).\n     symmetry. rewrite commutativity. now apply N.sub_add.\n    repeat (split; try apply _); intros.\n     now apply N.add_le_mono_l.\n    eapply N.add_le_mono_l. eassumption.\n   intros. now apply Nle_0.\n  assert (TotalRelation N_le).\n   intros x y. now apply N.le_ge_cases.\n  rapply semirings.dec_full_pseudo_srorder.\n  split.\n   intro. now apply N.le_neq.\n  intros [E1 E2]. now apply N.Private_Tac.le_neq_lt.\nQed.\n\n#[global]\nProgram Instance: ∀ x y: N, Decision (x ≤ y) := λ y x,\n  match N.compare y x with\n  | Gt => right _\n  | _ => left _\n  end.\nNext Obligation. now apply not_symmetry. Qed.\n\n#[global]\nInstance N_cut_minus: CutMinus N := Nminus.\n#[global]\nInstance: CutMinusSpec N _.\nProof.\n  split; try apply _.\n   intros. now apply N.sub_add.\n  intros. now apply Nminus_N0_Nle.\nQed.\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/implementations/stdlib_binary_naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8267117855317473, "lm_q1q2_score": 0.7740378532779163}}
{"text": "(* 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.\n\tShow Proof.\nQed.\n\nDefinition sym (A:Type) (x y:A) (e:x=y) : y=x :=\n\t@eq_ind A x (fun a => a=x) eq_refl y e\n.\n\nCheck eq_ind.\nCheck sym.\n\n\nDefinition trans (A:Type) (x y z:A) (e1: x=y) (e2 : y=z) : x=z :=\n\t@eq_ind A y (fun a => x = a) e1 z e2\n.\n\nCheck trans.\n\n\nDefinition cong (A B:Type) (f: A -> B) (x y :A) (e: x=y) : f x = f y :=\n\t@eq_ind A x (fun a => f x = f a) eq_refl y e\n.\nCheck cong.\n\nCheck eq_rect.\n\nDefinition congd (A :Type) (B:A->Type) (f: forall x:A,B x) (x y :A) (e: x=y) : \t\t(@eq_rect A x B (f x) y e ) = f y\n.\nProof.\n\tdestruct e.\n\tcompute.\n\treflexivity.\nQed.\n\nCheck Prop.\nCheck Type.\nCheck Prop -> Prop.\nCheck forall (P:Prop), P.\nCheck forall (P:Type), P.\n\nDefinition t := Type.\nCheck t.\n\nFail Check (forall (P:t), P) : t. \nDefinition p := Prop.\nCheck (forall (P:p), P) : p.\n\nDefinition conj (A B : Prop) := forall Q:Prop, (A->B->Q)->Q.\n\nDefinition conj_i (A B : Prop) (h1 : A) (h2 : B) : conj A B :=\n\tfun Q f => f h1 h2\n.\n\n\nCheck conj_i.\n\n(*exam 2017*)\n\nDefinition t1 : { x : nat | x = 3 } := \n\t exist _ 3 eq_refl\n.\n\nEval compute in eq_sym.\n\nDefinition eq_sym {A : Type} (x y : A) (e : x = y) : y = x :=\nmatch e in _ = _ return _ with\n| eq_refl => eq_refl\nend.\n\n\nCheck True.\nCheck unit.\n\nCheck True_ind.\nCheck unit_ind.\n\nCheck and.\nCheck prod.\n\nCheck and_ind.\nCheck prod_ind.\n\nCheck sig.\nCheck ex.\n\nCheck sig_ind.\nCheck ex_ind.\n\nExample nth : forall A (l : list A),\n{n : nat | n < length l} -> A.\nAdmitted.\n\n(*exam*)\n\nInductive tree : Type := \n|L : nat -> tree \n|N : nat -> tree -> tree -> tree.\n\nFixpoint mult (t:tree) : nat :=\nmatch t with \n|L n => n\n|N n ln rn => \n\tn * (mult ln) * (mult rn) \nend.\n\nEval compute in (mult (N 2 (L 3) (L 2))).\n\nFixpoint in0 (t:tree) : Prop :=\nmatch t with\n|L 0 => True\n|L _ => False\n|N 0 _ _ => True\n|N _ ln rn => (in0 ln) \\/ (in0 rn)\nend.\n\nEval compute in (in0 (N 2 (L 3) (L 2))).\nEval compute in (in0 (N 2 (L 3) (L 0))).\n\nInductive inO : tree -> Prop :=\n| inO_L : inO (L O)\n| inO_N l r : inO (N O l r)\n| inO_N_l n l r : inO l -> inO (N n l r)\n| inO_N_r n l r : inO r -> inO (N n l r).\n\nEval compute in (in0 (N 2 (L 3) (N 6 (L 0) (L 1)))).\nEval compute in (inO (N 2 (L 3) (N 6 (L 0) (L 1)))).\nEval compute in (inO (N 2 (L 3) (N 6 (L 2) (L 1)))).\n\n\n\nDefinition unit {A} : A -> option A := Some.\nDefinition bind {A B} (m : option A) (f : A -> option B) : option B :=\nmatch m with\n| Some x => f x\n| None => None\nend.\nDefinition raise {A} : option A := None.\n\n\nFixpoint mult0 (t : tree) : option nat :=\nmatch t with\n| L 0 => raise\n| L n => unit n\n| N 0 l r => raise\n| N n l r =>\n\tbind (mult0 l) (fun l' => \n\tbind (mult0 r) (fun r' => \n\t\tunit (n * l'* r')\n\t))\nend.\n\nEval compute in (mult (N 2 (L 3) (L 2))).\nEval compute in (mult0 (N 2 (L 3) (L 2))).\nEval compute in (mult0 (N 2 (L 3) (L 0))).\n\nDefinition M (A : Type) :=\n  forall (C : Type), (A -> C) -> C -> C \n.\n\nDefinition unit' {A} (a:A) : M A :=\n\tfun _ f _ => f a \n.\n\nCheck unit'.\n\nDefinition raise' {A} (a:A) : M A :=\n\tfun _ _ x => x \n.\n\nDefinition bind' {A B}  ( ma : M A) (f : A -> M B) : M B :=\n\tfun c sk fk => ma c (fun a => f a c sk fk) fk\n.\n\nCheck bind'.\n\nDefinition catch {A}  (e1 : M A) (e2 : A) : A := \n\te1 A (fun a => a) e2 \n.\n\n(***)\n\nParameter epsilon : forall (A:Type), A -> (A -> Prop) -> A.\nAxiom epsilon_spec :\nforall (A:Type) (a:A), forall P, (exists x, P x) -> P (epsilon A a P).\n\n\nFixpoint power2 (n:nat) : nat :=\n\tmatch n with \n\t| 0 => 1\n\t| S n => 2 * power2 n \n\tend.\n\nEval compute in (power2 3).\n\nDefinition log2 (n:nat) : nat :=\n\tepsilon nat n (fun x => n=power2 x) .\n\nEval compute in (log2 8).\n\nDefinition epsilon_bool_subset (P : bool -> Prop) :\n(exists x : bool, P x) -> { x : bool | P x }.\nAdmitted.\n\n\n(***)\n\nInductive comparaison : Set :=\n|Eq : comparaison\n|Lt : comparaison\n|Gt : comparaison.\n\nStructure dec_order :=\n{\n\tord_car : Type;\n\tord_rel : ord_car -> ord_car -> Prop;\n\tord_compare : forall x y, ;\n\tord_rel_compare : ord_car -> ord_car -> Prop;\n\tord_irrefl : forall x, not (ord_rel x x)\n}.\n\nEval ord_compare x y ", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/TP5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.7739506086082215}}
{"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 m n o p H1 H2.\n rewrite <- H1. apply H2.\nQed.\n\nTheorem silly2 : forall ( n m o p : nat ) , \n    n = m -> ( forall ( q r : nat ) , q = r -> [ q ; o ] = [ r ; p ] ) ->\n    [ n ; o ] = [ m ; p ].\nProof.\n intros n m o p H1 H2. \n apply H2. apply H1.\nQed.\n(* Not able to write this proof using rewrite. I stuck with second hypothesis\nforall ( q r : nat ) , q = r -> [ q ; o ] = [ r ; p ] *)\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 H1 H2.\n apply H2. apply H1.\nQed.\n\nTheorem silly_ex : \n  ( forall n, evenb n = true -> oddb ( S n ) = true ) ->\n  evenb 3 = true -> oddb 4 = true.\nProof.\n intros H1 H2. apply H1. apply H2.\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. simpl.\nAbort.\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. symmetry. apply H.\nQed.\n\nTheorem rev_exercise1 : forall ( l l' : list nat ), \n  l = rev l' -> \n  l' = rev l.\nProof.\n intros l l' H. symmetry. rewrite -> H. \n SearchAbout ( rev ( rev _ ) = _ ).\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 e d f H1 H2.\n rewrite -> H1. apply H2.\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 H1 H2.\n rewrite -> H1. apply H2.\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 with ( m := [ c ; d ]). apply H1.  apply H2.\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 apply trans_eq with ( m := m ). apply H2. apply H1.\nQed.\n\n\nTheorem eq_add_S : forall ( n m : nat ) ,\n  S n = S m -> n = m.\nProof.\n intros n m H. inversion H. reflexivity.\nQed.\n\n(* See inversion is propogating the things into goal also *)\n\nTheorem silly4 : forall ( n m : nat ) , \n [ n ] = [ m ] ->\n n = m.\nProof.\n intros n m H. inversion H. reflexivity.\nQed.\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n intros n m o H. inversion H.\n 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 X x y z l j H1 H2. inversion H2. reflexivity.\nQed.\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n intros n H. inversion H.\nQed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n intros n m H. inversion H.\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 H1 H2. inversion H1.\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 H. rewrite -> H.  reflexivity.\nQed.\n\nTheorem beq_nat_0_1 : forall n , \n  beq_nat 0 n = true -> n = 0.\nProof.\n  intros n H. destruct n as [ | n' ].\n  Case \"n = O\".\n   reflexivity.\n  Case \"n = S n'\".\n   inversion H.\nQed.\n\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n intros n H. destruct n as [ | n' ].\n Case \"n = O\".\n  reflexivity.\n Case \"n = S n'\".\n  inversion H.\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.\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 H1 H2. symmetry in H2. apply H1 in H2. symmetry. apply H2.\nQed.\n\nTheorem plus_n_Sm : forall ( n m : nat ),\n   n + S m = S ( n + m ).\nProof.\n  intros n m. induction n as [ | n' ].\n  Case \"n = O\".\n    simpl. reflexivity.\n  Case \"n = S n'\".\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 Case \"n = O\".\n   intros m H. induction  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. induction m as [ | m' ].\n    SCase \"m = O\".\n     inversion H.\n    SCase \"m = S m'\".\n       simpl in H. inversion H.  rewrite plus_n_Sm in H1.\n       rewrite plus_n_Sm in H1. inversion H1. apply IHn' in H2.\n       rewrite -> H2. reflexivity.\nQed.\n\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\".\n   simpl. intros H. destruct m as [ | m'].\n   SCase \"m = O\".\n     reflexivity.\n   SCase \"m = S m'\".\n     simpl in H. inversion H.\n  Case \"n = S n'\".\n     intros H. destruct m as [ | m']. \n     SCase \"m = O\".\n       inversion H.\n     SCase \"m = S m'\".\n       apply f_equal.\nAbort.\n\nTheorem double_injective : forall (  n m : nat ), \n double m = double n -> m = n.\nProof. \n  intros n. induction n as [ | n' ].\n  Case \"n = O\".\n    simpl. intros m. destruct m as [ | m' ].\n    SCase \"m = O\".\n      simpl. reflexivity.\n    SCase \"m = S m'\".\n      simpl. intros H. inversion H.\n  Case \"n = S n'\".\n     simpl. intros m. destruct m as [ | m' ].\n     SCase \"m = O\".\n        simpl. intros H. inversion H.\n     SCase \"m = S m'\".\n       simpl. intros H. inversion H. apply IHn' in H1.\n       apply f_equal. apply H1.\nQed.\n\nTheorem beq_nat_true : forall ( n m : nat ) , \n   beq_nat n m = true -> n = m.\nProof.\n intros n. induction n as [ | n' ].\n Case \"n = O\".\n   intros m. destruct m as [ | m' ].\n   SCase \"m = O\".\n       simpl. reflexivity.\n   SCase \"m = S m'\".\n       simpl. intros H. inversion H.\n  Case \"n = S n'\".\n   intros m. destruct m as [ | m' ].\n   SCase \"m = O\".\n     simpl. intros H. inversion H.\n   SCase \"m = S m'\".\n     simpl. intros H. apply IHn' in H.\n     apply f_equal. apply H.\nQed.\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\".\n     simpl. intros H. destruct n as [ | n' ].\n     SCase \"n = O\".\n      reflexivity.\n     SCase \"n = S n'\".\n      simpl in H. inversion H.\n  Case \"m = S m'\".\n     simpl. intros H. destruct n as [ | n' ].\n     SCase \"n = O\".\n      simpl in H. inversion H.\n     SCase \"n = S n'\".\n        simpl in H. inversion H. \n(* Watch carefull that our induction hypothesis is not going to help us.\n    SCase := \"n = S n'\" : String.string\n  Case := \"m = S m'\" : String.string\n  n' : nat\n  m' : nat\n  IHm' : double (S n') = double m' -> S n' = m'\n  H : S (S (double n')) = S (S (double m'))\n  H1 : double n' = double m'\n  ============================\n   S n' = S m'\n*)\nAbort.\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. generalize dependent n.\n  induction m as [ | m' ].\n  Case \"m = O\".\n    simpl. intros n. destruct n as [ | n' ].\n    SCase \"n = O\".\n      reflexivity.\n    SCase \"n = S n'\".\n      simpl. intros H. inversion H.\n  Case \"n = S n'\".\n    simpl. intros n. destruct n as [ | n'].\n    SCase \"n = O\".\n      simpl. intros H. inversion H.\n    SCase \"n = S n'\".\n      simpl. intros H. inversion H. apply IHm' in H1.\n      apply f_equal. apply H1.\nQed.\n\nTheorem length_snoc' : forall ( X : Type ) ( v : X ) ( 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 = nil\".\n   simpl. intros n H. rewrite -> H. reflexivity.\n Case \"l = cons v' l'\".\n   intros n H. simpl. destruct n as [ | n' ].\n   SCase \"n = O\".\n     inversion H.\n   SCase \"n = S n'\".\n     apply f_equal. apply IHl'. inversion H. reflexivity.\nQed.\n\n(* solved using forward reasoning *)\n\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 H. induction l as [ | v' l'].\n  Case \"l = nil\".\n    simpl. simpl in H. rewrite H. reflexivity.\n  Case \"l = Cons v' l'\".\n    simpl. apply f_equal.\nAbort.\n\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. generalize dependent n.\n  induction l as [ | v' l' ].\n  Case \"l = nil\".\n   simpl. intros n. destruct n as [ | n' ].\n   SCase \"n = O\".\n     reflexivity.\n   SCase \"n = S n'\".\n     intros H. inversion H.\n  Case \"l = Cons v' l'\".\n    intros n. destruct n as [ | n' ].\n    SCase \"n = O\".\n      simpl. intros H. inversion H.\n    SCase \"n = S n'\".\n      simpl. intros H. inversion H. rewrite -> H1.\n      apply IHl' in H1. apply H1.\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. generalize dependent n. induction l as [ | v' l' ].\n   Case \"l = nil\".\n     simpl. intros n H. rewrite -> H. reflexivity.\n   Case \"l = Cons v' l'\".\n     simpl. intros n. destruct n as [ | n' ].\n     SCase \"n = O\".\n       intros H. inversion H.\n     SCase \"n = S n'\".\n       intros H. inversion H. rewrite -> H1. apply IHl' in H1. \n       apply f_equal. apply H1.\nQed.\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. induction l1 as [ | v1' l1' ].\n  Case \"l1 = nil\".\n   simpl. intros n. destruct n as [ | n' ].\n   SCase \"n = O\".\n     intros H. inversion H.\n   SCase \"n = S n'\".\n     intros H. inversion H. reflexivity.\n  Case \"l1 = Cons v1' l1'\".\n    simpl. intros n. destruct n as [ | n' ].\n    SCase \"n = O\".\n      intros H. inversion H.\n    SCase \"n = S n'\".\n      intros H. inversion H. rewrite -> H1. apply IHl1' in H1. \n      apply f_equal. apply H1.\nQed.\n\nLemma length_twice : forall ( X : Type ) ( l1 l2 : list X ) ( v : X ),\n     length ( l1 ++ v :: l2 ) = S ( length ( l1 ++ l2 ) ).\nProof.\n  intros X l1 l2 v. induction l1 as [ | v1' l1'].\n  Case \"l1 = nil\". \n    simpl. reflexivity.\n  Case \"l1 = Cons v1' l1'\". \n     simpl. rewrite IHl1'. reflexivity.\nQed.\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. induction n as [ | n' ].\n  Case \"n = O\".\n     intros l H. destruct l as [ | v' l' ].\n     SCase \"l = nil\".\n        simpl. reflexivity.\n     SCase \"l = Cons v' l'\".\n        simpl. inversion H.\n  Case \"n = S n'\".\n     intros l. destruct l as [ | v' l'].\n     SCase \"l = nil\".\n      simpl. intros H. inversion H.\n     SCase \"l = Cons v' l'\".\n      simpl. intros H. apply f_equal. rewrite plus_n_Sm.\n      rewrite length_twice. apply f_equal. inversion H. apply IHn' in H1.\n      inversion H. rewrite H2. apply H1.\nQed.\n\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 H1 H2 H3 H4 m. induction m as [ | m' ].\n  Case \"m = O\".\n     intros n. induction  n as [ | n' ].\n     SCase \"n = O\".\n       apply H1. apply H3. apply IHn'.\n  Case \"m = S m'\".\n     intros n.  induction n as [ | n'].\n     SCase \"n = O\".\n       apply H2. apply IHm'. apply H4. apply IHm'.\nQed.\n\n(* Finally follow the type *)\n\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\".\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 : 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 ( 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\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 [ | v' l' ]. \n  Case \"l = nil\".\n   intros l1 l2. simpl. intros H. inversion H. simpl. reflexivity.\n  Case \"l = Cons v' l'\".\n    destruct v'. \nAbort.\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 : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n   intros n. unfold sillyfun1.\n   destruct ( beq_nat n 3 ). \n   Case \"beq_nat n 3 = true\".\n     intros H.\n(* We don't have enough information to proceed the calculation *)\nAbort.\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n   intros n H. unfold sillyfun1 in H.\n   destruct ( beq_nat n 3 ) eqn : Heqn3.\n   Case \"beq_nat n 3 = true\".\n     apply beq_nat_true in Heqn3. rewrite -> Heqn3. reflexivity.\n   Case \"beq_nat n 3 = false\".\n      destruct ( beq_nat n 5 ) eqn : Heqn5.\n      SCase \"beq_nat n 5 = true\".\n         apply beq_nat_true in Heqn5. rewrite -> Heqn5. reflexivity.\n      SCase \"beq_nat n 5 = false\".\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 f b.  apply f_equal. destruct ( f ( f b ) ) eqn : feqn.\n  Case \"f ( f b ) = true\".\n     destruct b.\n     SCase \"b = true\".\n       reflexivity.\n     SCase \"b = false\".\nAbort.\n\nTheorem override_same : forall (X:Type) x1 k1 k2 (f : nat -> X),\n  f k1 = x1 ->\n  (override f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f H. unfold override.\n  destruct ( beq_nat k1 k2 ) eqn : Heqn.\n  Case \"beq_nat k1 k2 = true\".\n   rewrite <- H. apply f_equal. apply beq_nat_true in Heqn.\n   apply Heqn.\n  Case \"beq_nat k1 k2 = false\".\n    apply f_equal. reflexivity.\nQed.\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 = O\".\n    intros m. destruct m as [ | m' ].\n    SCase \"m = O\".\n      reflexivity.\n    SCase \"m = S m'\".\n      simpl. reflexivity.\n  Case \"n = S n'\".\n    intros m. destruct m as [ | m' ].\n    SCase \"m = O\".\n      simpl. reflexivity.\n    SCase \"m = S m'\".\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 m p H1 H2.\n  apply beq_nat_true in H1. apply beq_nat_true in H2. \n   rewrite -> H1. rewrite <- H2. SearchAbout ( beq_nat ).\n   symmetry. apply beq_nat_refl.\nQed.\n\n(*\n\nExercise: 3 stars, advanced (split_combine)\nWe have just proven that for all lists of pairs, combine is the inverse of split. \nHow would you formalize the statement that split is the inverse of combine?\nComplete the definition of split_combine_statement below with a property that \nstates that split is the inverse of combine. Then, prove that the property holds. \n(Be sure to leave your induction hypothesis general by not doing intros on more \nthings than necessary. Hint: what property do you need of l1 and l2 for split \ncombine 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\n*)\n\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 H. unfold override.\n destruct ( beq_nat k1 k3 ) eqn : Heqn1.\n Case \"beq_nat k1 k3 = true\".\n   destruct ( beq_nat k2 k3 ) eqn : Heqn2.\n   SCase \"beq_nat k2 k3 = true\".\n    apply beq_nat_true in Heqn1. apply beq_nat_true in Heqn2.\n    rewrite Heqn1 in H. rewrite Heqn2 in H. \n    assert ( Htrue: beq_nat k3 k3 = true ).\n        symmetry. apply beq_nat_refl.\n    rewrite Htrue in H. inversion H.\n   SCase \"beq_nat k2 k3 = false\".\n       reflexivity.\n Case \"beq_nat k1 k3 = false\".\n       reflexivity.\nQed.\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. induction l as [ | v' l' ].\n Case \"l = nil\".\n  simpl. intros lf H. inversion H.\n Case \"l = Cons v' l'\".\n  intros lf. destruct lf as [ | vf' lf'].\n  SCase \"lf' = nil\".\n   simpl. intros H. destruct ( test v' ) eqn : Htest.\n   SSCase \"test v' = true\".\n     inversion H. rewrite H1 in Htest. apply Htest.\n   SSCase \"test v' = false\".\n     apply IHl' in H. apply H.\n  SCase \"lf' = Cons vf' lf'\".\n   simpl. intros H. destruct ( test v' ) eqn : Htest.\n   SSCase \"test v' = true\".\n    inversion H. rewrite H1 in Htest. apply Htest.\n   SSCase \"test v' = false\".\n    apply IHl' in H. apply H.\nQed.\n\nFixpoint forallb { X : Type } ( f : X -> bool ) ( l : list X ) : bool :=\n  match l with\n  | nil => true\n  | h :: t => andb ( f h ) ( forallb f t )\n  end.\n\nEval compute in forallb oddb [1;3;5;7;9] = true.\nEval compute in forallb negb [false;false] = true.\nEval compute in forallb evenb [0;2;4;5] = false.\nEval compute in forallb (beq_nat 5) [] = true.\n\nFixpoint existsb { X : Type } ( f : X -> bool ) ( l : list X ) : bool :=\n  match l with\n  | nil => false\n  | h :: t => orb ( f h ) ( existsb f t )\n  end.\n\nEval compute in existsb (beq_nat 5) [0;2;3;6] = false.\nEval compute in existsb (andb true) [true;true;false] = true.\nEval compute in existsb oddb [1;0;0;0;0;3] = true.\nEval compute in existsb evenb [] = false.\n\n(*\n\nNext, define a nonrecursive version of existsb — call it existsb' — using forallb \nand negb.\nProve that existsb' and existsb have the same behavior.\n\n*)\n\n\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.7739505853959127}}
{"text": "Set Implicit Arguments.\nRequire Import ZArith.\n\nPrint positive.\n(*\nInductive positive : Set :=\nxI : positive -> positive | xO : positive -> positive | xH : positive\n*)\n\nPrint Z.\n(*\nInductive Z : Set :=  Z0 : Z | Zpos : positive -> Z | Zneg : positive -> Z\n*)\n\nCheck positive_ind.\n(*\nforall P : positive -> Prop,\n  (forall p : positive, P p -> P (p~1)%positive) ->\n  (forall p : positive, P p -> P (p~0)%positive) ->\n   P 1%positive -> forall p : positive, P p\n*)\n\nFixpoint Psucc (x:positive) : positive :=\n  match x with\n    | xI x' => xO (Psucc x') \n    | xO x' => xI x'\n    | xH    => 2%positive\n  end.\n\nEval compute in Psucc (234%positive).\nEval compute in Psucc (63%positive).\n\n(*\nOpen Scope positive_scope.\n*)\n\nEval compute in xO (xO (xO (xI (xO (xI (xI (xI (xI xH)))))))).\nEval compute in (1~1~1~1~1~0~1~0~0~0)%positive. (* 1000 *)\nEval compute in (1~1~0~0~1)%positive.           (* 25 *)\nEval compute in (1~0~0~0~0~0~0~0~0~0)%positive. (* 512 *)\n\nDefinition pos_even_bool (n:positive) : bool :=\n  match n with\n    | xO p      => true\n    | xI p      => false\n    | xH        => false\n  end.\n\nEval compute in pos_even_bool 1%positive.\nEval compute in pos_even_bool 2.\nEval compute in pos_even_bool 3%positive.\n\nDefinition pos_to_int (n:positive): Z := Zpos n.\n\nDefinition pos_div2 (n:positive) : Z :=\n  match n with\n    | xO p      => Zpos p\n    | xI p      => Zpos p\n    | xH        => Z0\n  end.\n\nEval compute in pos_div2 127%positive.\n\nDefinition pos_div4 (n:positive) : Z :=\n  match n with \n    | xO (xO p) => Zpos p\n    | xI (xO p) => Zpos p\n    | xO (xI p) => Zpos p\n    | xI (xI p) => Zpos p\n    | other     => Z0\n  end.\n\nEval compute in pos_div4 1%positive.\nEval compute in pos_div4 2%positive.\nEval compute in pos_div4 3%positive.\nEval compute in pos_div4 4%positive.\nEval compute in pos_div4 5%positive.\nEval compute in pos_div4 6%positive.\nEval compute in pos_div4 7%positive.\nEval compute in pos_div4 8%positive.\n\nVariable pos_mult : positive -> positive -> positive.\n\nDefinition new_Z_mult (n m : Z) : Z :=\n  match (n, m) with \n    | (Z0, _ )          => 0%Z\n    | (_ , Z0)          => 0%Z\n    | (Zpos x, Zpos y)  => Zpos (pos_mult x y)\n    | (Zpos x, Zneg y)  => Zneg (pos_mult x y)\n    | (Zneg x, Zpos y)  => Zneg (pos_mult x y)\n    | (Zneg x, Zneg y)  => Zpos (pos_mult x y)\n  end.\n\nInductive prop : Set :=\n  | And : prop -> prop -> prop\n  | Or  : prop -> prop -> prop\n  | Not : prop -> prop\n  | Imp : prop -> prop -> prop\n  | Top : prop\n  | Bot : prop.\n\n(* any positive rational can be obtained by a unique sequence\nof application of N and D below, starting from 1 *)\n\nInductive pos_ratio : Set :=\n  | One : pos_ratio\n  | N   : pos_ratio -> pos_ratio  (* x -> 1 + x *)\n  | D   : pos_ratio -> pos_ratio. (* x -> 1/(1 + 1/x) *)\n\n\nFixpoint power (z:Z)(n:nat) : Z :=\n  match n with\n    | 0         => 1%Z\n    | S p       => (z * power z p)%Z\n  end.\n\nEval compute in power 2 20.\n\nFixpoint discrete_log (p: positive) : nat :=\n  match p with\n    | xH        =>  0\n    | xO p'     => S (discrete_log p')\n    | xI p'     => S (discrete_log p')\n  end.\n\nEval compute in discrete_log 1024.\nEval compute in discrete_log 2048.\n\nFixpoint toPair (r :pos_ratio) : positive*positive :=\n  (match r with\n    | One         => (1,1)\n    | N x         => let p := toPair x in (snd p + fst p, snd p)\n    | D x         => let p := toPair x in (fst p, fst p + snd p)\n  end)%positive.\n\nEval compute in toPair (N (D (N (N (N (D (D (N One)))))))).\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/positive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7739115164256698}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nRequire Export Logic.\n\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. induction n as [|n IH]. apply ev_0.\n  apply ev_SS. apply IH. Qed.\n\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. intros n H. inversion H as [|n' E'].\n  inversion E' as [|n'' E'']. apply E''. Qed.\n\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. intros H. inversion H as [|n E].\n inversion E as [|n' E']. inversion E'. Qed.\n   \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\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'). 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. intros n m Hn Hm. induction Hn as [|n' E IH].\n  apply Hm.\n  apply ev_SS. apply IH. Qed.\n  \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. intros n. split. \n  - intros ev_nm. induction ev_nm.\n    apply ev_0. \n    apply ev_SS. apply ev_0.\n    apply ev_sum. apply IHev_nm1. apply IHev_nm2.\n  - intros ev_n. induction ev_n.\n    apply ev'_0.\n    apply (ev'_sum 2 n). apply ev'_2. apply IHev_n. Qed.\n\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. intros n m ev_nm ev_n. induction ev_n. \n  - apply ev_nm.\n  - apply IHev_n. inversion ev_nm. apply H0. Qed.\n\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. intros n m p ev_nm ev_np. apply (ev_ev__ev (double n) (m+p)).\n  rewrite double_plus. rewrite <- plus_assoc. rewrite (plus_swap n m p).\n  rewrite plus_assoc. apply ev'_ev. apply ev'_sum.\n    apply ev'_ev. apply ev_nm.\n    apply ev'_ev. apply ev_np. \n  apply ev_double. Qed.\n\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\nInductive total_relation : nat -> nat -> Prop :=\n  | te : forall n m, total_relation n m.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop :=.\n\n\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. intros m n o le_mn le_no. induction le_no as [|o']. \n  - apply le_mn.\n  - apply le_S. apply IHle_no.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof. induction n. apply le_n. apply le_S. apply IHn. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. intros n m le. induction le.\n  apply le_n. apply le_S. apply IHle. Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. intros n m le. inversion le.\n  apply le_n. apply le_trans with (n:=(S n)). \n  apply le_S. apply le_n. apply H0. Qed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. intros a b. induction a as [|a IH].\n  - apply O_le_n. \n  - apply n_le_m__Sn_le_Sm. apply IH. Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n  unfold lt. intros n1 n2 m H. split.\n  - apply le_trans with (n:= S (n1) + n2).\n    apply le_plus_l. apply H.\n  - apply le_trans with (n:= S (n2) + n1).\n    apply le_plus_l. rewrite plus_comm in H. apply H. Qed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof. intros n m H. apply le_S. apply H. Qed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof. induction n as [|n IH].\n  - intros m H. apply O_le_n.\n  - intros m. destruct m. \n    intros H. inversion H.\n    intros H. apply n_le_m__Sn_le_Sm. apply IH. apply H. Qed.\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. intros n m. generalize dependent n. induction m as [|m IH].\n  - intros n H. inversion H. reflexivity. \n  - intros n H. destruct n. \n    + reflexivity. \n    + apply IH. apply Sn_le_Sm__n_le_m. apply H. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof. intros n m. split. apply leb_complete. apply leb_correct. Qed. \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. intros n m o. rewrite leb_iff, leb_iff, leb_iff.\n  apply le_trans. Qed.\n\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[R 1 1 2]\n\n(forall a b c, R a b c <-> a + b = c) holds even we drop c4, c5.\n \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  plus.\n  \nTheorem R_equiv_fR : forall m n o, R m n o <-> m + n = o.\nProof. intros m n o. split. \n  - intros H. induction H. \n    + reflexivity.\n    + rewrite <- IHR. reflexivity.\n    + rewrite <- plus_n_Sm, IHR. reflexivity.\n    + rewrite <- plus_n_Sm in IHR. inversion IHR. reflexivity.\n    + rewrite plus_comm. apply IHR.\n  - generalize dependent m. \n    generalize dependent n.\n    induction o. \n      + intros n m H. apply and_exercise in H.\n        inversion H. inversion H0. inversion H1. apply c1.\n      + intros n [|m]. \n          simpl.  intros H. rewrite H.\n          assert (H2: forall k, R 0 k k).\n          { induction k. apply c1. apply c3. apply IHk. }\n          apply H2.\n        \n          intros H. apply c2. apply IHo. inversion H. \n          reflexivity. Qed.\n\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\nInductive subseq: list nat -> list nat -> Prop :=\n  | sq_empty : forall l, subseq [] l\n  | sq_1 : forall h l1 l2, subseq l1 l2 -> subseq l1 (h::l2)\n  | sq_2 : forall h l1 l2, subseq l1 l2 -> subseq (h::l1) (h::l2).\n(*\nTheorem subseq_refl : forall l,\n  subseq l l.\nProof. induction l as [|h l IH]. \n  - apply sq_empty.\n  - apply sq_2. apply IH. Qed.\n\nTheorem subseq_app : forall l1 l2 l3,\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof. intros l1 l2 l3 sq. induction sq.\n  apply sq_empty.\n  apply sq_1. apply IHsq.\n  apply sq_2. apply IHsq. Qed.\n\nTheorem sss : forall x y z, \n      subseq (x++y) z -> subseq y z.\n      Proof. intros x y z. generalize dependent y. \ngeneralize dependent z.  induction x as [|h x IH].\n       intros z y sq. apply sq.\n       intros z y sq. apply IH. \n       inversion sq.\n       inversion sq. Abort.\n\nLemma head_sub : forall h t l, l = h :: t ->\n  subseq t l.\nProof. intros h t l H. rewrite H. apply sq_1. \n  apply subseq_refl. Qed. \n\nTheorem subsh : forall h y z a b,\n  subseq (h::y) z -> z = a ++ (h :: b).\nProof. Admitted.\n\nTheorem subseq_trans : forall l1 l2 l3, \n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof. intros l1 l2 l3 sq.\n  generalize dependent l3.\n  induction sq. \n  - intros H H2. apply sq_empty.\n  - intros l3 H. apply IHsq. \n      Abort.\n\nTheorem subseq_trans2 : forall l1 l2 l3, \n  subseq l2 l3 -> subseq l1 l2 -> subseq l1 l3.\nProof. intros l1 l2 l3 sq23. induction sq23.\n  *)\n\n\n \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    - [R 2 [1;0]]\n    - [R 1 [1;2;1;0]]\n*)\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 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(** 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\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. intros T s H. inversion H. Qed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof. intros T s re1 re2 [H|H]. \n  apply MUnionL. apply H. \n  apply MUnionR. apply H. \nQed.\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof. intros T ss re H. induction ss as [|h ss IH].\n  apply MStar0.\n  apply (MStarApp h (fold app ss []) re).\n  - apply H. left. reflexivity.\n  - apply IH. intros s H2. apply H. right. apply H2. Qed. \n\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\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. intros T s1. induction s1 as [|h s1 IH].\n  - intros s2. split. \n    + destruct s2.\n      intros H. reflexivity.\n      { simpl. intros H. inversion H. inversion H3. rewrite <- H5 in H0.\n        inversion H0. }\n    + intros H. rewrite <- H. apply MEmpty.\n  - intros s2. split.\n    + destruct s2. \n      simpl. intros H. inversion H.\n      { simpl. intros H. inversion H. inversion H3. \n        rewrite <- H5 in H0. inversion H0. apply f_equal.\n        apply IH. rewrite <- H9. apply H4. }\n    + destruct s2. \n      intros H. inversion H.\n      intros H. inversion H.\n      rewrite <- H2. \n        apply (MApp [t] _ s1 _). apply MChar. apply IH. reflexivity. Qed.\n    \n\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  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char t => true\n  | App X Y => (re_not_empty X) && (re_not_empty Y)\n  | Union X Y => (re_not_empty X) || (re_not_empty Y)\n  | Star X => 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. intros T re. split.\n  + intros [e E]. induction E.\n    - reflexivity.\n    - reflexivity.\n    - simpl. rewrite IHE1. apply IHE2.\n    - simpl. rewrite IHE. reflexivity.\n    - simpl. rewrite orb_true_iff. right. apply IHE.\n    - reflexivity.\n    - reflexivity.\n  + intros H. induction re.\n    - inversion H.\n    - exists []. apply MEmpty.\n    - exists [t]. apply MChar.\n    - simpl in H. rewrite andb_true_iff in H. destruct H as [H1 H2].\n      apply IHre1 in H1. apply IHre2 in H2. \n      destruct H1 as [s1 S1]. destruct H2 as [s2 S2].\n      exists (s1++s2). apply MApp.\n        apply S1. \n        apply S2.\n    - simpl in H. rewrite orb_true_iff in H. destruct H as [H|H].\n      apply IHre1 in H. destruct H as [s S]. \n      exists s. apply MUnionL. apply S.\n      apply IHre2 in H. destruct H as [s S].\n      exists s. apply MUnionR. apply S.\n    - exists []. apply MStar0. Qed.\n\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. intros T s re H. remember (Star re) as rex eqn:Heq. \n  induction H. \n  - inversion Heq.\n  - inversion Heq.\n  - inversion Heq.\n  - inversion Heq.\n  - inversion Heq.\n  - exists []. split. \n    + reflexivity.\n    + intros s' contra. inversion contra.\n  - inversion Heq. apply IHexp_match2 in Heq. destruct Heq as [ss [He1 He2]].\n    exists (s1 :: ss).\n    split.\n    + simpl. rewrite He1. reflexivity.\n    + intros s. simpl. intros [Hx|Hx].\n      * rewrite <- Hx, <- H2. apply H.\n      * apply He2. apply Hx.\nQed.\n\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 pump_lemma : forall T (s:list T) re m, \n  s =~ re ->\n  napp m s =~ Star re.\nProof. intros T s re m. induction m as [|m].\n  intros H. simpl. apply MStar0.\n  intros H. simpl. apply MStarApp.\n  apply H. apply IHm. apply H. Qed.\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  - simpl. omega.\n  - simpl. rewrite app_length.\n    intros H. \n    assert (Ha: forall a b c d,\n      (a + b) <= (c + d) -> (a <= c) \\/ (b <= d)).\n      intros a b c d. omega.\n    apply Ha in H. destruct H as [H|H].\n    * apply IH1 in H. destruct H as [s11 [s12 [s13 [H1 [H2 H3]]]]].\n      exists s11, s12, (s13 ++ s2). split.\n      + rewrite H1. rewrite <- (app_assoc T s11 (s12 ++ s13)).\n        rewrite <- app_assoc. reflexivity.\n      + split. apply H2.\n        intros m. rewrite app_assoc, \n          app_assoc, <- (app_assoc T _ _ s13). apply MApp.\n        apply H3. \n        apply Hmatch2.\n    * apply IH2 in H. destruct H as [s21 [s22 [s23 [H1 [H2 H3]]]]].\n      exists (s1++s21), s22, s23. split.\n      + rewrite H1. rewrite app_assoc. reflexivity.\n      + split. apply H2. \n        intros n. rewrite <- app_assoc. apply MApp.\n        apply Hmatch1.\n        apply H3. \n  - intros H. simpl in H.\n    assert (H2: pumping_constant re1 <= length s1).\n      {apply le_trans with (m:=(pumping_constant re1 + pumping_constant re2)).\n       apply le_plus_l. apply H. }\n    apply IH in H2. destruct H2 as [s2 [s3 [s4 [Ha [Hb Hc]]]]].\n    exists s2, s3, s4. split. apply Ha. split. apply Hb. \n    intros m. apply MUnionL. apply Hc.\n  - intros H. simpl in H. \n    assert (H2: pumping_constant re2 <= length s2).\n      {apply le_trans with (m:=(pumping_constant re1 + pumping_constant re2)).\n       rewrite plus_comm. apply le_plus_l. apply H. }\n    apply IH in H2. destruct H2 as [s1 [s3 [s4 [Ha [Hb Hc]]]]].\n    exists s1, s3, s4. split. apply Ha. split. apply Hb. \n    intros m. apply MUnionR. apply Hc.\n  - intros H. inversion H.\n  - destruct s2. \n    * intros H. exists [], s1, [].\n      rewrite app_nil_r in *. split. reflexivity.\n      split. \n      + intros Hx.\n        rewrite Hx in H. inversion H.\n      + simpl. intros m. rewrite app_nil_r.\n        apply pump_lemma. apply Hmatch1.\n    * assert (H: pumping_constant (Star re) <= length (t :: s2)).\n        { apply n_le_m__Sn_le_Sm. apply O_le_n. }\n      apply IH2 in H. \n      destruct H as [s21 [s22 [s23 [Ha [Hb Hc]]]]].\n      intros H'. exists (s1++s21), s22, s23.\n      rewrite Ha. rewrite <- (app_assoc T (s1)). split. reflexivity.\n      split. apply Hb. intros m. rewrite <- (app_assoc T (s1)).\n      apply MStarApp. apply Hmatch1. apply Hc. Qed.\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. intros P b H. destruct b. \n  - split. intros p. reflexivity.\n    intros _. inversion H. apply H0.\n  - split. intros p. inversion H. exfalso. apply H0. apply p.\n    intros contra. inversion contra. Qed.\n\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. intros n l H. induction l as [|h l IH].\n  - intros contra. inversion contra. \n  - intros H1. simpl in *. destruct (beq_natP n h).\n    + inversion H.\n    + destruct H1 as [H1|H1].\n      * apply H0. symmetry. apply H1.\n      * apply IH. apply H. apply H1.\nQed.     \n\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  | nos_nil : nostutter []\n  | nos_one : forall x, nostutter [x]\n  | nos_cons : forall x h l, \n      nostutter (h :: l) -> (x <> h) -> (nostutter (x :: h :: l)).\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\n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n\nExample test_nostutter_2:  nostutter (@nil nat).\n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n\nExample test_nostutter_3:  nostutter [5].\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n  Proof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction H5; 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\nInductive merge {X:Type} : list X -> list X -> list X -> Prop :=\n  | merge_0 : merge [] [] []\n  | mergeL : forall l1 l2 l h, merge l1 l2 l -> merge (h::l1) l2 (h::l)\n  | mergeR : forall l1 l2 l h, merge l1 l2 l -> merge l1 (h::l2) (h::l).\n\nTheorem merge_theorem : forall X (test:X->bool) l l1 l2,\n  merge l1 l2 l ->\n  (forall x, In x l1 -> test x = true) -> \n  (forall x, In x l2 -> test x = false) -> \n  filter test l = l1.\nProof. intros X test l l1 l2 Hind. \n  induction Hind as [|l1 l2 l h H IH| l1 l2 l h H IH].\n  - reflexivity.\n  - simpl. intros H2. \n    assert (Ha: forall x : X, In x l1 -> test x = true).\n    { intros x HIn. apply (H2 x (or_intror HIn)). }\n    assert (Hb: test h = true).\n    { apply H2. left. reflexivity. }\n    rewrite Hb. intros H3.\n    apply f_equal.\n    apply IH. apply Ha. apply H3. \n  - simpl. intros H2 H3.\n    assert (Ha: forall x : X, In x l2 -> test x = false).\n    { intros x HIn. apply H3. right. apply HIn. }\n    assert (Hb: test h = false).\n    { apply (H3 h (or_introl eq_refl)). }\n    rewrite Hb. \n    apply IH. apply H2. apply Ha. Qed.\n\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\nInductive subseqX {X:Type}: list X -> list X -> Prop :=\n  | sqx_empty : forall l, subseqX [] l\n  | sqx_1 : forall h l1 l2, subseqX l1 l2 -> subseqX l1 (h::l2)\n  | sqx_2 : forall h l1 l2, subseqX l1 l2 -> subseqX (h::l1) (h::l2).\n\nTheorem filter_challenge_2 : forall X (test:X->bool) l ls,\n  subseqX ls l ->\n  (forall x, In x ls -> test x = true) ->\n  length ls <= length (filter test l).\nProof. intros X test l ls HInd.\n  induction HInd as [l|h ls l H IH|h ls l H IH].\n  - intros H. apply O_le_n.\n  - intros Ha. apply IH in Ha. \n    apply le_trans with (n:=(length (filter test l))).\n    apply Ha. simpl. destruct (test h). apply le_S. apply le_n.\n    reflexivity.\n  - intros H1.\n    assert (Ha: forall x : X, In x ls -> test x = true).\n    { intros x HIn. apply H1. right. apply HIn. }\n    assert (Hb: test h = true).\n    {apply H1. left. reflexivity. }\n    simpl. rewrite Hb. apply n_le_m__Sn_le_Sm. apply IH. apply Ha. Qed.    \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\nInductive pal {X:Type}: list X -> Prop :=\n  | pal_0 : pal []\n  | pal_1 : forall x, pal [x]\n  | pal_2 : forall x l, pal l -> pal (x :: l ++ [x]).\n\nTheorem pal_app_rev: forall X  (l:list X), pal (l ++ rev l).\nProof. intros X l. induction l as [|x l IH].\n  - constructor.\n  - simpl. rewrite app_assoc. constructor. apply IH. Qed.\n\nTheorem pal_rev : forall X (l:list X), pal l -> l = rev l.\nProof. intros X l p. induction p as [|x IH|x l H IH].\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr, <- IH. reflexivity. Qed.\n\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\nLemma list_represent : forall X (l:list X),\n  l = [] \\/ (exists x, l = [x]) \\/ (exists x l' y, l = (x :: l' ++ [y])).\nProof. intros X. induction l as [|h l IH].\n  - left. reflexivity. \n  - destruct IH as [H | [[x H] | [x [l' [y H]]]]].\n    + right. left. exists h. rewrite H. reflexivity.\n    + right. right. exists h, [], x. rewrite H. reflexivity.\n    + right. right. exists h, (x :: l'), y. rewrite H. reflexivity. Qed.\n\nTheorem palindrome_converse_n : forall X  n (l:list X), length l <= n -> \nl = rev l -> pal l.\nProof. intros X. induction n as [|n].\n  intros l Hlength. destruct l. \n    intros _. constructor.\n    inversion Hlength.\n  intros l Hlength Hrev.\n  destruct (list_represent X l) as [H | [[x H] | [x [l' [y H]]]]].\n  - inversion H. constructor. \n  - inversion H. constructor. \n  - rewrite H in Hrev. simpl in Hrev. rewrite rev_app_distr in Hrev. \n    inversion Hrev. rewrite <- H1 in H. rewrite H. \n    apply (f_equal _ _ rev _ _) in H2. \n    rewrite rev_app_distr, rev_app_distr in H2.\n    rewrite rev_involutive in H2. inversion H2. rewrite H3. \n    rewrite H in Hlength.\n    simpl in Hlength. rewrite app_length, plus_comm in Hlength. \n    apply le_S, Sn_le_Sm__n_le_m, Sn_le_Sm__n_le_m in Hlength.\n    constructor. apply IHn. apply Hlength. symmetry. apply H3.\nQed. \n\nTheorem palindrome_converse : forall X (l:list X), l = rev l -> pal l.\nProof. intros X l. apply (palindrome_converse_n X (length l)). \n  constructor. Qed.\n\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\nInductive disjoint {X:Type} : list X -> list X -> Prop :=\n  | dis_nilL : forall l, disjoint [] l\n  | dis_nilR : forall l, disjoint l []\n  | dis_consL: forall l1 l2 x, disjoint l1 l2 -> ~ In x l2 -> disjoint (x::l1) l2  \n  | dis_consR: forall l1 l2 x, disjoint l1 l2 -> ~ In x l1 -> disjoint l1 (x::l2).\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\nInductive NoDup {X:Type} : list X -> Prop :=\n  | nd_nil : NoDup []\n  | nd_cons : forall l x, ~ In x l -> NoDup l -> NoDup (x::l). \n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\n\nLemma not_in_append1 : forall X x (l1 l2 : list X),\n  ~ In x (l1++l2) -> ~ In x l1.\nProof. intros X x l1 l2 H H2. rewrite In_app_iff in H.\n  apply H. left. apply H2. Qed.\n\nLemma not_in_append2 : forall X x (l1 l2 : list X),\n  ~ In x (l1++l2) -> ~ In x l2.\nProof. intros X x l1 l2 H H2. rewrite In_app_iff in H.\n  apply H. right. apply H2. Qed.\n\nLemma in_app : forall X x (l1 l2 : list X),\n  ~ In x l1 -> ~ In x l2 -> ~ In x (l1++l2).\nProof. intros X x l1 l2 H1 H2 H.\n  rewrite In_app_iff in H. destruct H as [H|H].\n  - apply H1. apply H.\n  - apply H2. apply H. Qed.\n\nLemma not_in_comm : forall X x (l1 l2 : list X),\n  ~ In x (l1++l2) -> ~ In x (l2++l1).\nProof. intros X x l1 l2 H. apply in_app.\n  - apply not_in_append2 with l1. apply H.\n  - apply not_in_append1 with l2. apply H. Qed.\n\nLemma nodup_insert : forall X x (l1 l2 : list X),\n  NoDup (l1 ++ l2) -> ~ In x (l1++l2) -> NoDup (l1++(x::l2)).\nProof. intros X x l1 l2 Hnd HnIn. induction l1 as [|h l1 IH].\n - constructor. apply HnIn. apply Hnd.\n - assert (H: x <> h).\n   { intros Hx.  apply HnIn. left. symmetry. apply Hx. }\n   inversion Hnd.\n   constructor. \n   + apply in_app. \n     * apply not_in_append1 with l2. apply H2.\n     * intros [Hx|Hx]. apply H. apply Hx. \n       apply H2. rewrite In_app_iff. right. apply Hx.\n   + apply IH. \n     * apply H3.\n     * intros Hx. apply HnIn.\n       right. apply Hx. Qed.\n   \nLemma nodup_comm : forall X (l1 l2 : list X),\n  NoDup (l1++l2) -> NoDup (l2++l1).\nProof. intros X l1 l2 H. induction l1 as [|h l1 IH].\n - rewrite app_nil_r.\n   apply H.\n - inversion H. apply nodup_insert. apply IH, H3.\n   apply not_in_comm. apply H2. Qed.\n\nTheorem nodup_disjoint : forall X (l1 l2: list X),\n  NoDup (l1++l2) -> disjoint l1 l2.\nProof. intros X l1 l2 H. induction l1 as [|h l1 IH].\n  - constructor. \n  - inversion H. constructor. apply IH. apply H3.\n    apply not_in_append2 with l1. apply H2. Qed.\n\nTheorem disjoint_of_nodups : forall X (l1 l2: list X),\n  NoDup l1 -> NoDup l2 -> disjoint l1 l2 -> NoDup (l1++l2).\nProof. intros X l1 l2 Hl1 Hl2 Hdj. induction Hdj.\n  - apply Hl2.\n  - rewrite app_nil_r. apply Hl1.  \n  - inversion Hl1. constructor. \n    + apply in_app. apply H2. apply H. \n    + apply IHHdj. apply H3. apply Hl2.\n  - inversion Hl2. apply nodup_insert. \n    + apply IHHdj. apply Hl1. apply H3.\n    + apply in_app.  apply H. apply H2. Qed.\n\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. intros X x l HIn. induction l as [|h l IH].\n  - inversion HIn.\n  - destruct HIn as [HIn|HIn]. \n    * exists [], l. inversion HIn. reflexivity.\n    * apply IH in HIn. destruct HIn as [l1 [l2 E]].\n      exists (h::l1), l2. rewrite E. reflexivity. Qed.\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_in : forall l x, In x l -> repeats (x::l)\n | rp_rp : forall l x, repeats l -> repeats (x::l).\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\nFixpoint natlists (n:nat) : list nat :=\n  match n with\n  | O => []\n  | S n => (S n) :: natlists n\n  end.\n\nInductive natl : list nat -> Prop :=\n  | nl_0 : natl [] \n  | nl_1 : natl [1]\n  | nl_n : forall n l, natl (n :: l) -> natl ((S n)::n :: l).\n\nDefinition inj {A B: Type} (f:A->B) :=\n  forall (x y:A), f x = f y -> x = y.\n(* \nFixpoint delete_one {X:Type} (x:X) (l:list X) (em : excluded_middle) : list X :=\n  match l with\n  | [] => []\n  | h :: t => match (em (h=x)) with\n              | or_introl _ => l\n              | or_intror _ => h :: (delete_one x t em)\n              end\n  end.\n\nLemma aux_pigeon: forall (X:Type) (l1  l2:list X) h,\n(~ In h l1)\n (forall x, In x l1 -> In x l2) -> \n   l2 = (delete_one h l2).\nProof. Qed.*)\n\n\nLemma in_comm: forall X x (l1 l2:list X),\n  In x (l1 ++ l2) -> In x (l2 ++ l1). \nProof. intros X x l1 l2 H. rewrite In_app_iff in *.\n  destruct H as [H|H].\n  - right. apply H.\n  - left. apply H.\nQed.\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 [|h l1 IH].\n   - intros l2 em H1 H2. inversion H2.\n   - intros l2 em H1 H2. destruct (em (In h l1)).\n     + constructor. apply H.\n     + apply rp_rp. \n       assert (H': In h l2).\n       { apply H1. left. reflexivity. }\n       apply in_split in H'. destruct H' as [l21 [l22 Hl2]].\n       apply IH with (l2:=l22++l21).\n       * apply em.\n       * intros x HH. \n         assert (Ha:In x (h::l22 ++ l21)).\n         { replace (h :: l22 ++ l21) with ((h :: l22) ++ l21).\n           apply in_comm. rewrite <- Hl2. apply H1. \n           right. apply HH. \n           reflexivity. }\n         destruct Ha as [Ha|Ha].\n           exfalso. apply H. inversion Ha. apply HH.\n           apply Ha.\n        * rewrite Hl2 in H2.\n          rewrite app_length, plus_comm in H2. \n          simpl in H2. apply Sn_le_Sm__n_le_m in H2. rewrite app_length.\n          apply H2.\nQed.\n          \n\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 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 represeneted\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\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. inversion 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, optional (app_ne)  *)\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. intros a s re0 re1. split. \n  - intros H. inversion H. destruct s1 as [|h s1].\n    * left. split.\n      + apply H3.\n      + apply H4.\n    * right. exists s1, s2. inversion H0. split.\n      + reflexivity.\n      + split. rewrite H6 in *. apply H3. apply H4. \n  - intros [[H1 H2]|H].\n    + replace (a :: s) with ([] ++ (a :: s)). \n      * constructor. \n         apply H1.\n         apply H2.\n      * reflexivity.\n    + destruct H as [s0 [s1 [H1 [H2 H3]]]].\n      rewrite H1. \n      replace (a :: s0 ++ s1) with ((a :: s0) ++ s1).\n      * constructor.\n          apply H2. \n          apply H3. \n      * reflexivity. Qed.\n\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 H2.\n  - intros [ H | H ].\n    + apply MUnionL. apply H.\n    + apply MUnionR. apply H. \nQed.\n\n(** **** Exercise: 3 stars, optional (star_ne)  *)\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 not_empty_star: forall (s:string), \n  (s =~ Star EmptyStr) -> s = [].\nProof. intros s H2. remember (Star EmptyStr) as x eqn:H.\n  induction H2.\n  - reflexivity.\n  - inversion H.\n  - inversion H.\n  - inversion H.\n  - inversion H.\n  - reflexivity.\n  - inversion H. rewrite H1 in *. inversion H2_. \n    rewrite IHexp_match2. reflexivity. reflexivity. Qed.  \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. intros a s re. split.\n  - intros H. remember (Star re) as re'. remember (a::s) as s'.\n    induction H .\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqs'.\n    + destruct s1 as [|h s1]. \n      * inversion Heqre'. rewrite H2 in *. \n        apply IHexp_match2 in Heqre'.\n        destruct Heqre' as [s0 [s1 [Ha [Hb Hc]]]].\n        exists s0, s1. split. \n          apply Ha. split.\n          apply Hb.\n          apply Hc.\n        apply Heqs'.\n      * inversion Heqs'. rewrite H2 in *.\n        inversion Heqre'. rewrite H4 in *.\n        exists s1, s2. split.\n          reflexivity. split.\n          apply H.\n          apply H0.\n  - intros [s0 [s1 [H [H1 H2]]]]. \n    rewrite H. apply (MStarApp (a :: s0)).\n    apply H1. apply H2. Qed.\n\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, optional (match_eps)  *)\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  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char _ => false\n  | App x y => andb (match_eps x) (match_eps y)\n  | Union x y => orb (match_eps x) (match_eps y)\n  | Star _ => true\n  end.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (match_eps_refl)  *)\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. intros re. apply iff_reflect. split.\n  - intros H. remember [] as s.\n    induction H.\n    + reflexivity.\n    + inversion Heqs.\n    + simpl.\n      destruct s1, s2.\n      * rewrite IHexp_match1, IHexp_match2. reflexivity.\n      reflexivity. reflexivity.\n      * inversion Heqs.\n      * inversion Heqs.\n      * inversion Heqs.\n    + simpl. rewrite IHexp_match. reflexivity. apply Heqs.\n    + simpl. rewrite orb_true_iff. right. apply IHexp_match.\n      apply Heqs.\n    + reflexivity.\n    + reflexivity.\n  - intros H. induction re.\n    + inversion H.\n    + constructor.\n    + inversion H.\n    + apply andb_true_iff in H. destruct H as [H1 H2]. apply (MApp []). \n      * apply IHre1. apply H1.\n      * apply IHre2. apply H2.\n    + apply orb_true_iff in H. destruct H as [H | H].\n      * apply MUnionL. apply IHre1. apply H.\n      * apply MUnionR. apply IHre2. apply H.\n    + constructor.\nQed.\n \n\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\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, optional (derive)  *)\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. *)\n\nCheck forall A B, A + B.\n\nPrint ascii_dec.\n\nCheck @left.\n\nFixpoint derive (a : ascii) (re : @reg_exp ascii) : @reg_exp ascii :=\n  match re with\n  | EmptySet => EmptySet\n  | EmptyStr => EmptySet\n  | Char x => if ascii_dec a x then EmptyStr else EmptySet\n  | App A B => if (match_eps A) then Union (derive a B) (App (derive a A) B)  \n               else App (derive a A) B\n  | Union A B => Union (derive a A) (derive a B)\n  | Star A => App (derive a A) (Star A)\n  end.\n  \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. reflexivity. Qed.\n\n(** \"c\" =~ Char c: *)\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof. reflexivity. Qed.\n\n(** \"c\" =~ Char d: *)\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof. reflexivity. Qed.\n\n(** \"c\" =~ App (Char c) EmptyStr: *)\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof. reflexivity. Qed.\n\n(** \"c\" =~ App EmptyStr (Char c): *)\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof. reflexivity. Qed.\n\n(** \"c\" =~ Star c: *)\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof. reflexivity. Qed.\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. reflexivity. Qed.\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. reflexivity. Qed.\n\n(** **** Exercise: 4 stars, optional (derive_corr)  *)\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]. *)\n\n\nLemma derive_corr : derives derive.\nProof. intros a re s. split.\n* remember (a :: s) as s'.\n  intros H. generalize dependent s. induction H.\n  - intros s Heqs'. inversion Heqs'.\n  - intros s Heqs'. simpl. destruct (ascii_dec a x).\n    + inversion Heqs'. constructor.\n    + inversion Heqs'. exfalso. apply n. symmetry. apply H0.\n  - intros s Heqs'. simpl. destruct (match_eps re1) eqn: Heps.\n    + destruct s1. \n        apply MUnionL. apply IHexp_match2. apply Heqs'.\n        inversion Heqs'. apply MUnionR. constructor.\n        apply IHexp_match1. inversion H2. reflexivity.\n        apply H0.\n    + destruct s1. \n        destruct (match_eps_refl re1). \n        inversion Heps. exfalso. apply H1. apply H.\n        inversion Heqs'. constructor. apply IHexp_match1.\n        inversion H2. reflexivity. apply H0.\n   - intros s H'. apply MUnionL. apply IHexp_match.\n     apply H'.\n   - intros s H'. apply MUnionR. apply IHexp_match.\n     apply H'.\n   - intros s contra. inversion contra.\n   - intros s H'.\n     simpl. destruct s1.\n     + simpl in H'. apply IHexp_match2. apply H'.\n     + inversion H'. constructor. \n         apply IHexp_match1. inversion H2.\n         reflexivity.\n         apply H0.\n* generalize dependent s. induction re.\n  - intros s H. rewrite null_matches_none in H. inversion H.\n  - intros s H. simpl in H. rewrite null_matches_none in H. inversion H.\n  - intros s H. simpl in H. destruct (ascii_dec a t).\n    + rewrite empty_matches_eps in H. rewrite H. inversion e. constructor.\n    + rewrite null_matches_none in H. inversion H.\n  - intros s H. simpl in H. destruct (match_eps re1) eqn: He.\n    + rewrite union_disj in H. destruct H as [H|H].\n      destruct (match_eps_refl re1).\n        replace (a :: s) with ([]++(a :: s)).\n        constructor. \n          apply H0.\n          apply IHre2. apply H.\n        reflexivity.\n        inversion He.\n      rewrite app_exists in H. destruct H as [s0 [s1 [H [H1 H2]]]]. \n      apply IHre1 in H1. \n      apply app_exists. exists (a :: s0), s1.\n      split. rewrite H. reflexivity.\n      split. apply H1. apply H2.\n    + rewrite app_exists in H.\n      destruct H as [s0 [s1 [H [H1 H2]]]]. apply IHre1 in H1.\n      rewrite app_exists. exists (a :: s0), s1.\n      split. rewrite H. reflexivity.\n      split. apply H1. apply H2.\n  - intros s H. simpl in H. rewrite union_disj in *.\n    destruct H as [H|H]. \n      left. apply IHre1. apply H.\n      right. apply IHre2. apply H.\n  - intros s H. simpl in H. rewrite app_exists, star_ne in *.\n    destruct H as [s0 [s1 [H [H1 H2]]]].\n    exists s0, s1. \n    split. \n      + apply H.\n      + split. \n        apply IHre. apply H1. \n        apply H2.\nQed.  \n    \n\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\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, optional (regex_match)  *)\n(** Complete the definition of [regex_match] so that it matches\n    regexes. *)\n\nFixpoint regex_match (s : string) (re : @reg_exp ascii) : bool :=\n  match s with\n  | [] => match_eps re\n  | h :: t => regex_match t (derive h re)\n  end.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (regex_refl)  *)\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. *)\n\nTheorem regex_refl : matches_regex regex_match.\nProof. intros s. induction s as [|h s IH].\n  - intros re. simpl. destruct (match_eps_refl re). \n    + constructor. apply H.\n    + constructor. apply H.\n  - intros re. simpl. destruct (derive_corr h re s).\n    destruct (IH (derive h re)).\n      constructor. apply H0. apply H1.\n      constructor. intros contra. apply H1. apply H. apply contra. Qed.\n\n", "meta": {"author": "kolya-vasiliev", "repo": "logical-foundations-2018", "sha": "1486b6748963514bc281672a93d408ac830ae0d0", "save_path": "github-repos/coq/kolya-vasiliev-logical-foundations-2018", "path": "github-repos/coq/kolya-vasiliev-logical-foundations-2018/logical-foundations-2018-1486b6748963514bc281672a93d408ac830ae0d0/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7738159192606561}}
{"text": "Require Import Arith Arith.Even Arith.Div2 Omega.\nRequire Import Coq.Logic.JMeq Coq.Program.Wf.\nRequire Import Program.Syntax List.\nRequire Import Braun.common.util.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Coq.Wellfounded.Lexicographic_Product.\n\nSet Implicit Arguments.\n\n(* fl_log(n) = floor(log_2(n+1)) *)\nProgram Fixpoint fl_log n {wf lt n} : nat :=\n  match n with\n    | 0 => 0\n    | S n' => S (fl_log (div2 n'))\n  end.\n\n(* cl_log(n) = ceiling(log_2(n+1)) *)\n(* which is the same as Racket's 'integer-length' *)\nProgram Fixpoint cl_log n {wf lt n} : nat :=\n  match n with\n    | 0 => 0\n    | S n' => S (cl_log (div2 n))\n  end.\n\nExample fl_log_ex :\n  map fl_log\n      [0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15]\n  = [0;1;1;2;2;2;2;3;3;3;3; 3; 3; 3; 3; 4].\nProof.\n  compute; reflexivity.\nQed.\n\nExample cl_log_ex :\n  map cl_log\n      [0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15]\n  = [0;1;2;2;3;3;3;3;4;4;4; 4; 4; 4; 4; 4].\nProof.\n  compute; reflexivity.\nQed.\n\nLemma fl_log_div2' : \n  forall n,\n    fl_log (S n) = S (fl_log (div2 n)).\nProof.\n  intros.\n  apply (Fix_eq _ lt lt_wf (fun _ => nat)).\n  intuition.\n  destruct x; [ reflexivity | repeat f_equal].\nQed.\nHint Rewrite fl_log_div2'.\n\nLemma fl_log_div2'' :  forall n, div2 (n + 1) < S n.\nProof.\n  intros n.\n  replace (n+1) with (S n);[|omega].\n  auto.\nQed.\nHint Resolve fl_log_div2''.\n\nLemma cl_log_zero :\n  cl_log 0 = 0.\nProof.\n  apply (Fix_eq _ lt lt_wf (fun _ => nat)).\n  intuition.\n  destruct x; [ reflexivity | repeat f_equal].\nQed.\nHint Rewrite cl_log_zero.\n\nLemma cl_log_div2' : \n  forall n, \n    cl_log (S n) = S (cl_log (div2 (S n))).\nProof.\n  intros.\n  apply (Fix_eq _ lt lt_wf (fun _ => nat)).\n  intuition.\n  destruct x; [ reflexivity | repeat f_equal].\nQed.\nHint Rewrite cl_log_div2'.\n\nLemma fl_log_zero :\n  fl_log 0 = 0.\nProof.\n  apply (Fix_eq _ lt lt_wf (fun _ => nat)).\n  intuition.\n  destruct x; [ reflexivity | repeat f_equal].\nQed.\nHint Rewrite fl_log_zero.\n\nLemma fl_log_div2 : \n  forall n, \n    fl_log (div2 n) + 1 = fl_log (S n).\nProof.\n  intros n.\n  rewrite fl_log_div2'.\n  intuition.\nQed.\nHint Rewrite fl_log_div2.\n\nLemma fl_log_odd :\n  forall n : nat,\n    fl_log (n + n + 1) = (fl_log n) + 1.\nProof.\n  intro n.\n  rewrite plus_comm; simpl.\n  rewrite fl_log_div2'.\n  rewrite double_div2.\n  rewrite plus_comm; simpl; reflexivity.\nQed.\nHint Rewrite fl_log_odd.\n\nLemma fl_log_even :\n  forall n : nat,\n    fl_log ((n + 1) + (n + 1)) = (fl_log n) + 1.\nProof.\n  intro n.\n  replace (n + 1 + (n + 1)) with (S (S (n + n))) ; [|omega].\n  rewrite fl_log_div2'.\n  rewrite div2_with_odd_argument.\n  rewrite plus_comm; simpl; reflexivity.\nQed.\nHint Rewrite fl_log_even.\n\nLemma cl_log_odd :\n  forall n,\n    cl_log(n+n+1) = cl_log n + 1.\nProof.\n  intros.\n  rewrite plus_comm; simpl.\n  rewrite cl_log_div2'.\n  rewrite div2_with_odd_argument.\n  rewrite plus_comm; simpl; reflexivity.\nQed.\nHint Rewrite cl_log_odd.\n\nLemma cl_log_even :\n  forall n,  \n    cl_log (n+1) + 1 = cl_log (n + 1 + n + 1).\nProof.\n  intros.\n  replace (n + 1 + n + 1) with (S (S (n+n))); [|omega].\n  rewrite cl_log_div2'.\n  replace (S (S (n+n))) with ((n+1)+(n+1)); [|omega].\n  rewrite double_div2.\n  rewrite plus_comm; simpl; reflexivity.\nQed.\nHint Rewrite cl_log_even.\n\nLemma braun_invariant_implies_fl_log_property :\n  forall s_size t_size,\n    t_size <= s_size <= t_size + 1 ->\n    fl_log t_size + 1 = fl_log (s_size + t_size + 1).\nProof.\n  intros.\n  assert (s_size = t_size \\/ s_size = t_size + 1) as TwoCases;\n    [ omega | ].\n\n  inversion TwoCases; subst; clear.\n\n  rewrite fl_log_odd.\n  reflexivity.\n\n  replace (t_size + 1 + t_size + 1) with ((t_size+1) + (t_size+1)); [| omega].\n  rewrite fl_log_even.\n  reflexivity.\nQed.\nHint Rewrite braun_invariant_implies_fl_log_property.\n\nLemma braun_invariant_implies_cl_log_property:\n  forall s1_size t1_size,\n    t1_size <= s1_size <= t1_size + 1 ->\n    cl_log s1_size + 1 = cl_log (s1_size + t1_size + 1).\nProof.\n  intros.\n  assert (s1_size = t1_size \\/ s1_size = t1_size+1) as TWOCASES; [omega|].\n  inversion TWOCASES; clear TWOCASES; subst s1_size.\n\n  replace (cl_log (t1_size + t1_size+1)) with (cl_log (S (t1_size + t1_size))).\n\n  replace (cl_log (S (t1_size + t1_size)))\n  with (S (cl_log (div2 (S (t1_size + t1_size))))) ; [|rewrite cl_log_div2';reflexivity].\n\n  replace (div2 (S (t1_size+t1_size))) with t1_size;\n    [| rewrite (div2_with_odd_input t1_size); reflexivity].\n\n  omega.\n\n  replace (t1_size + t1_size+1) with (S (t1_size+t1_size)).\n  reflexivity.\n\n  omega.\n\n  replace (t1_size + 1 + t1_size + 1) with (S (S (t1_size+t1_size))); [|omega].\n  rewrite cl_log_div2'.\n\n  replace (S (S (t1_size+t1_size))) with ((S t1_size)+(S t1_size)); [|omega].\n  rewrite double_div2.\n  rewrite plus_comm.\n  simpl.\n  rewrite plus_comm.\n  reflexivity.\nQed.\nHint Rewrite braun_invariant_implies_cl_log_property.\n\nLemma fl_log_cl_log_relationship :\n  forall n,\n    S (fl_log n) = cl_log (S n).\nProof.\n  apply (well_founded_ind\n           lt_wf\n           (fun n => S (fl_log n) = cl_log (S n))).\n  intros.\n  destruct x.\n  compute; reflexivity.\n  rewrite fl_log_div2'.\n  rewrite cl_log_div2'.\n  rewrite (H (div2 x)); auto.\nQed.\nHint Rewrite fl_log_cl_log_relationship.\n\nLemma div2_le:\n  forall n,\n    div2 n <= n.\nProof.\n  induction n as [|n].\n  simpl. auto.\n\n  apply Nat.div2_decr.\n  auto.\nQed.\n\nLemma ind_0_div2 :\n  forall P:nat -> Prop,\n    P 0 -> (forall n, P (div2 n) -> P (S n)) -> forall n, P n.\nProof.\n  intros P P0 I.\n  apply (well_founded_ind lt_wf P).\n  intros n IH.\n  destruct n as [|n].\n  auto.\n  apply I.\n  apply IH.\n  unfold lt.\n  apply le_n_S.\n  apply div2_le.\nQed.\n\nLemma fl_log_decr:\n  forall x,\n    fl_log x <= x.\nProof.\n  apply ind_0_div2.\n  \n  rewrite fl_log_zero.\n  auto.\n\n  intros n.\n  rewrite <- fl_log_div2.\n  intros LE.\n  rewrite plus_comm. simpl.\n  apply le_n_S.\n  eapply le_trans.\n  apply LE.\n  apply div2_le.\nQed.\n\nLemma fl_log_monotone:\n  forall x y,\n    x <= y ->\n    fl_log x <= fl_log y.\nProof.\n  apply (ind_0_div2 (fun x => forall y : nat, x <= y -> fl_log x <= fl_log y)).\n\n  intros y LE. \n  rewrite fl_log_zero.\n  apply le_0_n.\n\n  intros n IH y LE.\n  rewrite <- fl_log_div2.\n  destruct y as [|y].\n  omega.\n  assert (n <= y) as LE'; try omega.\n  clear LE.\n  rewrite <- fl_log_div2.\n  rewrite plus_comm. simpl.\n  rewrite plus_comm. simpl.\n  apply le_n_S.\n  apply IH.\n  apply div2_monotone.\n  auto.\nQed.\n\nLemma cl_log_monotone:\n  forall x y,\n    x <= y ->\n    cl_log x <= cl_log y.\nProof.\n  intros [|n] y LE.\n  \n  rewrite cl_log_zero.\n  apply le_0_n.\n\n  rewrite <- fl_log_cl_log_relationship.\n  destruct y as [|y].\n  omega.\n  rewrite <- fl_log_cl_log_relationship.\n  assert (n <= y) as LE'; try omega.\n  apply le_n_S.\n  apply fl_log_monotone.\n  auto.\nQed.\n\nLemma S_cl_log_doubles : \n  forall n, S (cl_log (S n)) = cl_log (S n + S n).\nProof.\n  intros.\n  rewrite <- (double_div2 (S n)) at 1.\n  replace (S n + S n) with (S (n+S n)) at 1;[|omega].\n  rewrite <- cl_log_div2'.\n  replace (S (n+S n)) with (S n + S n);omega.\nQed.\n\nLemma cl_log_product : forall n m, cl_log (n*m) <= 2*cl_log n + 2*cl_log m.\nProof.\n  intros.\n  apply (lt_wf_double_ind (fun n m => cl_log (n*m) <= 2*cl_log n + 2*cl_log m)).\n  clear.\n  intros.\n  destruct n.\n  rewrite mult_0_l.\n  rewrite cl_log_zero.\n  omega.\n  destruct m.\n  rewrite mult_0_r.\n  rewrite cl_log_zero.\n  omega.\n  destruct (even_odd_dec n).\n  destruct (even_odd_dec m).\n  destruct n. rewrite mult_1_l. omega.\n  destruct m. rewrite mult_1_r. omega.\n  apply (le_trans (cl_log (S (S n) * S (S m)))\n                  (cl_log (div2 (S (S n)) * div2 (S (S m))) + 4)).\n  replace (div2 (S (S n))) with (div2 (S n));[|apply even_div2; auto].\n  replace (div2 (S (S m))) with (div2 (S m));[|apply even_div2; auto].\n  rewrite <- even_div_product; auto.\n  replace ((S n) * div2 (S m)) with (div2 (S m) * (S n));[|rewrite mult_comm;auto].\n  rewrite <- even_div_product; auto.\n  destruct n.\n  inversion e.\n  inversion H2.\n  destruct m.\n  inversion e0.\n  inversion H2.\n  replace (S (S n)) with (n+2) at 2;[|omega].\n  replace (S (S m)) with (m+2) at 2;[|omega].\n  rewrite mult_plus_distr_r;\n    repeat (rewrite mult_plus_distr_l);\n    rewrite plus_assoc.\n  replace (m * n + m * 2 + 2 * n + 2 * 2)\n  with (S (S (S (S (m * n + m * 2 + 2 * n)))));[|omega].\n  unfold div2 at 2; fold div2.\n  replace (cl_log (div2 (S (S (div2 (m * n + m * 2 + 2 * n))))) + 4)\n  with (S (S (S (S (cl_log (div2 (S (S (div2 (m * n + m * 2 + 2 * n))))))))));[|omega].\n  rewrite <- cl_log_div2'.\n  replace (S (S (div2 (m * n + m * 2 + 2 * n))))\n  with (div2 (S (S (S (S (m * n + m * 2 + 2 * n))))));[|unfold div2;auto].\n  rewrite <- cl_log_div2'.\n  rewrite S_cl_log_doubles.\n  replace (S (S (S (S (m * n + m * 2 + 2 * n)))) +\n           S (S (S (S (m * n + m * 2 + 2 * n)))))\n  with (S ((S (S (S (m * n + m * 2 + 2 * n)))) +\n           S (S (S (S (m * n + m * 2 + 2 * n))))));[|omega].\n  rewrite S_cl_log_doubles.\n  apply cl_log_monotone.\n  replace (S (S (S n))) with (n+3);[|omega].\n  replace (S (S (S m))) with (m+3);[|omega].\n  rewrite mult_plus_distr_r;\n    repeat (rewrite mult_plus_distr_l);\n    rewrite plus_assoc.\n  rewrite mult_comm at 1.\n  remember (m*n) as l.\n  omega.\n  repeat rewrite cl_log_div2'.\n  replace ( 2 * S (cl_log (div2 (S (S n)))) + 2 * S (cl_log (div2 (S (S m)))))\n  with ( 2 * (cl_log (div2 (S (S n)))) + 2 * (cl_log (div2 (S (S m)))) + 4);[|omega].\n  apply plus_le_compat; auto.\n  replace (S n) with (n + 1); try omega.\n  replace (S m) with (m + 1); try omega.\n  assert (((n+1)*(m+1)) = (n*m + m + n + 1)); try omega.\n  rewrite mult_plus_distr_r.\n  rewrite mult_plus_distr_l.\n  rewrite mult_plus_distr_l.\n  omega.\n  rewrite H1.\n  replace (n*m+m+n+1) with (S(n*m+m+n));[|omega].\n  rewrite cl_log_div2'.\n  replace (S(n*m+m+n)) with (n*m+m+n+1);[|omega].\n  rewrite <- H1.\n  rewrite mult_comm.\n  rewrite even_div_product;[|apply odd_even_plus; auto; repeat constructor].\n  apply (le_trans (S (cl_log (div2 (m + 1) * (n + 1))))\n                  (2*cl_log(div2(m+1)) + 2*cl_log(n+1) + 1)).\n  replace (S (cl_log (div2 (m + 1) * (n + 1))))\n  with (cl_log (div2 (m + 1) * (n + 1)) +1);[|omega].\n  apply plus_le_compat;auto.\n  rewrite mult_comm.\n  replace ( 2 * cl_log (div2 (m + 1)) + 2 * cl_log (n + 1))\n  with  (2 * cl_log (n + 1) + 2 * cl_log (div2 (m + 1)));[|apply plus_comm].\n  replace (n+1) with (S n); [auto|omega].\n  replace (m+1) with (S m);[auto|omega].\n  replace (cl_log (S m)) with (S (cl_log (div2 (S m))));[|\n                                                        apply eq_sym;\n                                                          apply cl_log_div2']; omega.\n   replace (S n) with (n + 1); try omega.\n  replace (S m) with (m + 1); try omega.\n  assert (((n+1)*(m+1)) = (n*m + m + n + 1)); try omega.\n  rewrite mult_plus_distr_r.\n  rewrite mult_plus_distr_l.\n  omega.\n  rewrite H1.\n  replace (n*m+m+n+1) with (S(n*m+m+n));[|omega].\n  rewrite cl_log_div2'.\n  replace (S(n*m+m+n)) with (n*m+m+n+1);[|omega].\n  rewrite <- H1.\n  rewrite even_div_product;[|apply odd_even_plus; auto; repeat constructor].\n  apply (le_trans (S (cl_log (div2 (n + 1) * (m + 1))))\n                  (2*cl_log(div2(n+1)) + 2*cl_log(m+1) + 1)).\n  replace  (S (cl_log ((div2 (n+1)) * (m+1)))) with  (cl_log ((div2 (n+1)) * (m+1)) + 1).\n  apply plus_le_compat; auto.\n  omega.\n  replace (n+1) with (S n);[|omega].\n  rewrite cl_log_div2'.\n  omega.\nQed.\n\nLemma cl_log_square_four :\n  forall n, cl_log (n * n) <= 4 * cl_log n.\nProof.\n  intros.\n  eapply le_trans.\n  apply cl_log_product.\n  omega.\nQed.\n\nDefinition monotone (f : nat -> nat) := forall n m, n<=m -> f n <= f m.\n\nTheorem log_prod_time :\n  forall (n k:nat) (f g : nat -> nat),\n    monotone g ->\n    f 0 = k /\\ (forall n, f (S n) = f (div2 (S n)) + g (S n)) ->\n    f n <= (cl_log n)*(g n) + k.\nProof.\n  intros n k f g Mono_g H.\n  destruct H.\n  apply (well_founded_ind\n           lt_wf\n           (fun n =>  f n <= cl_log n * g n + k)).\n  clear n.\n  intros n IH.\n  destruct n.\n  rewrite H.\n  rewrite cl_log_zero. omega.\n  rewrite H0.\n  rewrite cl_log_div2'.\n  replace (S (cl_log (div2 (S n)))) with ((cl_log (div2 (S n)))+1);[|omega].\n  rewrite mult_plus_distr_r.\n  rewrite mult_1_l.\n  rewrite <- plus_assoc.\n  replace (g (S n) + k) with (k + g (S n));[|omega].\n  rewrite plus_assoc.\n  apply plus_le_compat; auto.\n  eapply le_trans.\n  apply IH.\n  apply lt_div2. omega.\n  apply plus_le_compat; auto.\n  apply mult_le_compat.\n  auto.\n  apply Mono_g.\n  assert (div2 (S n) < S n).\n  auto. omega.\nQed.\n\nTheorem log_prod_time2 :\n  forall (n m k:nat) (f g : nat -> nat -> nat),\n    (forall m, monotone (fun n => g n m)) ->\n    (forall m, f 0 m = k) /\\ (forall n m, f (S n) m = f (div2 (S n)) m + g (S n) m) ->\n    f n m <= (cl_log n)*(g n m) + k.\nProof.\n  intros n m k f g Mono_g H.\n  destruct H.\n  apply (well_founded_ind\n           lt_wf\n           (fun n => forall m, f n m <= (cl_log n)*(g n m) + k)).\n  clear n m.\n  intros n IH.\n  intros m.\n  destruct n.\n  rewrite H.\n  rewrite cl_log_zero. omega.\n  rewrite H0.\n  rewrite cl_log_div2'.\n  replace (S (cl_log (div2 (S n)))) with ((cl_log (div2 (S n)))+1);[|omega].\n  rewrite mult_plus_distr_r.\n  rewrite mult_1_l.\n  rewrite <- plus_assoc.\n  replace (g (S n) m + k) with (k + g (S n) m);[|omega].\n  rewrite plus_assoc.\n  apply plus_le_compat; auto.\n  eapply le_trans.\n  apply IH.\n  apply lt_div2. omega.\n  apply plus_le_compat; auto.\n  apply mult_le_compat.\n  auto.\n  apply Mono_g.\n  assert (div2 (S n) < S n).\n  auto. omega.\nQed.\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/log.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7737164474153233}}
{"text": "(** * Multiset:  Insertion Sort With Multisets *)\n\n(** We have seen how to specify algorithms on \"collections\", such as\n    sorting algorithms, using permutations.  Instead of using\n    permutations, another way to specify these algorithms is to use\n    multisets.  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.  One simple\n    representation of a multiset is a function from values to [nat]. *)\n\nRequire Import Coq.Strings.String.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Sort.\nRequire Export FunctionalExtensionality.\n\n(** In this chapter we will be using natural numbers for two different\n    purposes: the values in the lists that we sort, and the\n    multiplicity (number of times occurring) of those values.  To keep\n    things straight, we'll use the [value] type for values, and [nat]\n    for multiplicities. *)\n\nDefinition value := nat.\n\nDefinition multiset := value -> nat.\n\n(** Just like sets, multisets have operators for [union], for the\n    [empty] multiset, and the multiset with just a single element. *)\n\nDefinition empty : multiset :=\n   fun x => 0.\n\nDefinition union (a b : multiset) : multiset :=\n   fun x => a x + b x.\n\nDefinition singleton (v: value) : multiset :=\n   fun x => if x =? v then 1 else 0.\n\n(** **** Exercise: 1 star (union_assoc)  *)\n(** Since multisets are represented as functions, to prove that one\n    multiset equals another we must use the axiom of functional\n    extensionality. *)\n\nLemma union_assoc: forall a b c : multiset, (* assoc stands for \"associative\" *)\n   union a (union b c) = union (union a b) c.\nProof.\n  intros. unfold union.\n  extensionality x. apply plus_assoc. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (union_comm)  *)\nLemma union_comm: forall a b : multiset,  (* comm stands for \"commutative\" *)\n   union a b = union b a.\nProof.\n  intros. unfold union.\n  extensionality x. apply plus_comm. Qed.\n\n(** [] *)\n\n(** Remark on efficiency:  These multisets aren't very efficient.  If\n  you wrote programs with them, the programs would run slowly. However,\n  we're using them for _specifications_, not for _programs_.  Our\n  multisets built with [union] and [singleton] will never really\n  _execute_ on any large-scale inputs; they're only used in the proof\n  of correctness of algorithms such as [sort].  Therefore, their\n  inefficiency is not a problem. *)\n\n(** Contents of a list, as a multiset: *)\n\nFixpoint contents (al: list value) : multiset :=\n  match al with\n  | a :: bl => union (singleton a) (contents bl)\n  | nil => empty\n  end.\n\n(** Recall the insertion-sort program from [Sort.v].  Note that it\n    handles lists with repeated elements just fine. *)\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. simpl. reflexivity. Qed.\n\nExample sort_pi_same_contents:\n    contents ([3;1;4;1;5;9;2;6;5;3;5]) = contents [1;1;2;3;3;4;5;5;5;6;9].\nProof. \nextensionality x. simpl.\ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \ndestruct x; try reflexivity. \n  (* Why does this work? Try it step by step, without [do 10] *)\nQed.\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, contents al = contents (f al) /\\ sorted (f al).\n\n(** **** Exercise: 3 stars (insert_contents)  *)\n(** First, prove the auxiliary lemma [insert_contents], which will be\n    useful for proving [sort_contents] below.  Your proof will be by\n    induction.  You do not need to use [extensionality]. *)\n\nLemma insert_contents: forall x l, contents (x::l) = contents (insert x l).\nProof. induction l. \n  - reflexivity.\n  - simpl in *. \n    bdestruct (x <=? a).\n    + reflexivity.\n    + rewrite union_assoc. rewrite (union_comm (singleton x)).\n      rewrite <- union_assoc. rewrite IHl.\n      reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (sort_contents)  *)\n(** Now prove that sort preserves contents. *)\n\nTheorem sort_contents: forall l, contents l = contents (sort l).\nProof. induction l. \n  - reflexivity.\n  - simpl. rewrite <- insert_contents.\n    rewrite IHl. reflexivity.\nQed.\n\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem insertion_sort_correct:\n  is_a_sorting_algorithm' sort.\nProof.\nsplit. apply sort_contents. apply sort_sorted.\nQed.\n\n(** **** Exercise: 1 star (permutations_vs_multiset)  *)\n(** Compare your proofs of [insert_perm, sort_perm] with your proofs\n    of [insert_contents, sort_contents].  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 (prod 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 <-> contents al = contents bl.] *)\n\n(** **** Exercise: 3 stars (perm_contents)  *)\n(** The forward direction is easy, by induction on the evidence for\n    [Permutation]: *)\n\nLemma perm_contents:\n  forall al bl : list nat,\n   Permutation al bl -> contents al = contents bl.\nProof. intros. induction H.\n  - reflexivity.\n  - simpl. rewrite IHPermutation.\n    reflexivity.\n  - simpl. rewrite union_assoc. rewrite (union_comm (singleton y)).\n    rewrite <- union_assoc. reflexivity.\n  - rewrite IHPermutation1, IHPermutation2. reflexivity.\nQed.\n(** [] *)\n\n(** The other direction,\n    [contents al = contents bl -> Permutation al bl],\n    is surprisingly difficult.  (Or maybe there's an easy way\n    that I didn't find.) *)\n\nFixpoint list_delete (al: list value) (v: value) :=\n  match al with\n  | x::bl => if x =? v then bl else x :: list_delete bl v\n  | nil => nil\n  end.\n\nDefinition multiset_delete (m: multiset) (v: value) :=\n   fun x => if x =? v then pred(m x) else m x.\n\n(** **** Exercise: 3 stars (delete_contents)  *)\nLemma delete_contents:\n  forall v al,\n   contents (list_delete al v) = multiset_delete (contents al) v.\nProof.\n  intros.\n  extensionality x.\n  induction al.\n  simpl. unfold empty, multiset_delete.\n  bdestruct (x =? v); auto.\n  simpl.\n  bdestruct (a =? v).\n  unfold multiset_delete, singleton, union. rewrite <- H.\n  bdestruct (x =? a); reflexivity.\n  simpl. unfold singleton, union.\n  rewrite IHal. unfold multiset_delete. \n  bdestruct (x =? a).\n  replace (x =? v) with false.\n  reflexivity.\n  symmetry. rewrite Nat.eqb_neq. omega.\n  reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (contents_perm_aux)  *)\nLemma contents_perm_aux:\n forall v b, empty = union (singleton v) b -> False.\nProof. intros. \n  assert (empty v = union (singleton v) b v) by \n    (rewrite H; reflexivity).\n  unfold empty, union, singleton in H0. \n  rewrite Nat.eqb_refl in H0. inversion H0.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (contents_in)  *)\nLemma contents_in:\n  forall (a: value) (bl: list value) , contents bl a > 0 -> In a bl.\nProof. intros. induction bl. \n  - unfold contents, empty in H. \n    inversion H.\n  - unfold In. unfold contents, union, singleton in H.\n    bdestruct (a =? a0). left. auto.\n    right. apply IHbl. apply H.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (in_perm_delete)  *)\nLemma in_perm_delete:\n  forall a bl,\n  In a bl -> Permutation (a :: list_delete bl a) bl.\nProof. intros. induction bl.\n  - inversion H.\n  - simpl. bdestruct (a0 =? a). \n    * subst. apply Permutation_refl.\n    * apply perm_trans with (a0 :: a :: list_delete bl a).\n      apply perm_swap. apply perm_skip. apply IHbl.\n      destruct H. omega. assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars (contents_perm)  *)\nLemma contents_perm:\n forall al bl, contents al = contents bl -> Permutation al bl.\nProof.\n  induction al; destruct bl; intro.\n  auto.\n  simpl in H.\n  contradiction (contents_perm_aux _ _ H).\n  simpl in H. symmetry in H.\n  contradiction (contents_perm_aux _ _ H).\n  specialize (IHal (list_delete (v :: bl) a)).\n  (** From this point on, you don't need induction.\n    Use the lemmas [perm_trans], [delete_contents],\n     [in_perm_delete], [contents_in].   At _certain points_\n     you'll need to unfold the definitions of\n     [multiset_delete], [union], [singleton]. *)\n\n  apply perm_trans with (a :: list_delete (v :: bl) a).\n  - apply perm_skip. apply IHal.\n    rewrite delete_contents.\n    rewrite <- H. rewrite <- delete_contents. apply perm_contents.\n    simpl. rewrite Nat.eqb_refl. apply Permutation_refl.\n\n  - apply in_perm_delete. apply contents_in.\n    rewrite <- H. unfold contents, union, singleton. \n    rewrite Nat.eqb_refl. omega.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * The Main Theorem: Equivalence of Multisets and Permutations *)\nTheorem same_contents_iff_perm:\n  forall al bl, contents al = contents bl <-> Permutation al bl.\nProof.\n  intros. split. apply contents_perm. apply perm_contents.\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 same_contents_iff_perm; auto.\nQed.\n", "meta": {"author": "kolya-vasiliev", "repo": "verified-functional-algorithms-2019", "sha": "56fa7ddc0a37b82346ef3636b5af7908abdc75d8", "save_path": "github-repos/coq/kolya-vasiliev-verified-functional-algorithms-2019", "path": "github-repos/coq/kolya-vasiliev-verified-functional-algorithms-2019/verified-functional-algorithms-2019-56fa7ddc0a37b82346ef3636b5af7908abdc75d8/Multiset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7736387860534479}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\n\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H: even n) : even (S (S n))\n.\n\nCheck ev_SS.\nTheorem ev_4 : even 4.\nProof.\n  apply (ev_SS 2).\n  apply (ev_SS 0).\n  apply ev_0.\nQed.\n\nTheorem ev_4' : even 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\nTheorem ev_plus_4:\n  forall n:nat, even n -> even (4 + n).\nProof.\n  intros n H.\n  exact (ev_SS (2 + n) (ev_SS n H)).\nQed.\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 Hn.\n  destruct Hn as [|n' H'].\n  - left. reflexivity.\n  - right. exists n'. split. reflexivity. exact H'.\nQed.\n\nTheorem ev_minus2 : forall n,\n  even n -> even (pred (pred n)).\nProof.\n  intros n Hn.\n  destruct Hn as [|n' H'].\n  - simpl. exact ev_0.\n  - simpl. exact H'.\nQed.\n\nTheorem evSS_ev : forall n,\n  even (S (S n)) -> even n.\nProof.\n  intros n Hn.\n  apply ev_inversion in Hn.\n  destruct Hn as [H' | H'].\n  - discriminate H'.\n  - destruct H' as [n' [Hl Hr]].\n    injection Hl as Hl'.\n    rewrite <- Hl' in Hr.\n    exact Hr.\nQed.\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  exact E'.\nQed.\n\nTheorem one_not_even : ~ even 1.\nProof.\n  unfold \"~\".\n  intros H.\n  inversion H.\nQed.\n", "meta": {"author": "wierton", "repo": "SoftwareFoundationSolutions", "sha": "e8d2c92ff78997af2cb67c5d06cd13ed6afd9e37", "save_path": "github-repos/coq/wierton-SoftwareFoundationSolutions", "path": "github-repos/coq/wierton-SoftwareFoundationSolutions/SoftwareFoundationSolutions-e8d2c92ff78997af2cb67c5d06cd13ed6afd9e37/LF/IndPropLearn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7736362664882679}}
{"text": "\nRequire Import 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 => or (eq 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\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/goal36.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7735071011676444}}
{"text": "\nTheorem Ex011 (A B : Prop) : (A /\\ ~A) -> B.\nProof.  \n  intro.\n  destruct H.\n  exfalso.\n  apply H0.\n  exact H.\nQed.\n\nTheorem Ex011_2 (A B : Prop) : (A /\\ ~A) -> B.\nProof.\n  intro.\n  destruct H.\n  contradiction.\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/Ex011.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182322, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.773507096388303}}
{"text": "Theorem induc4 : forall P: nat-> Prop,\n                 P 0 -> P 1 -> P 2 -> P 3 ->\n                 (forall p, P p -> P (S (S (S (S p))))) ->\n                 forall n, P n.\nProof.\n intros P H0 H1 H2 H3 H.\n cut (forall n, (P n /\\ P (S n) /\\ P (S (S n)) /\\ P (S (S (S n))))).\n intros H4 n; case (H4 n); auto.\n induction n.\n repeat split; auto.\n intuition.  \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/progav/SRC/quadruple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7733438961818777}}
{"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 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. lfind.  rewrite IHx.  reflexivity. \nAdmitted.\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. rewrite mult_assoc. rewrite (mult_commut x y). 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_goal84_plus_commut_64_plus_succ/goal84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938536, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7732002295031436}}
{"text": "Require Import ZArith.\nRequire Import Reals.\nFrom Flocq Require Import Raux Defs Float_prop Operations.\nRequire Import Gappa_definitions.\n\nLemma float2_zero :\n  forall e : Z, Float2 0 e = 0%R :>R.\nProof.\nintro e.\napply F2R_0.\nQed.\n\nDefinition Fopp2 (x : float2) :=\n  Float2 (- Fnum x) (Fexp x).\n\nLemma Fopp2_correct :\n  forall x : float2,\n  Fopp2 x = (- x)%R :>R.\nProof.\nintros x.\nunfold float2R, Fopp2. simpl.\napply F2R_Zopp.\nQed.\n\nDefinition Fmult2 (x y : float2) :=\n  Float2 (Fnum x * Fnum y) (Fexp x + Fexp y).\n\nDefinition Fmult2_correct :\n  forall x y : float2,\n  Fmult2 x y = (x * y)%R :>R.\nProof.\nintros (mx, ex) (my, ey).\nexact (F2R_mult (Float radix2 mx ex) (Float radix2 my ey)).\nQed.\n\nDefinition shl (m : Z) (d : positive) :=\n match m with\n | Z0 => Z0\n | Zpos p => Zpos (shift_pos d p)\n | Zneg p => Zneg (shift_pos d p)\n end.\n\nLemma float2_shl_correct :\n  forall m e : Z, forall d : positive,\n  Float2 (shl m d) (e - Zpos d) = Float2 m e :>R.\nProof.\nintros m e d.\nreplace (shl m d) with (m * Zpower_pos 2 d)%Z.\nunfold float2R.\nrewrite (F2R_change_exp _ (e - Zpos d) _ e).\nsimpl.\nnow replace (e - (e - Zpos d))%Z with (Zpos d) by ring.\ngeneralize (Zgt_pos_0 d).\nomega.\nrewrite Zmult_comm.\ndestruct m as [|m|m] ; simpl.\napply Zmult_0_r.\nnow rewrite shift_pos_correct.\nchange (Zneg (shift_pos d m)) with (- Zpos (shift_pos d m))%Z.\nrewrite shift_pos_correct.\nnow rewrite Zopp_mult_distr_r.\nQed.\n\nDefinition Fshift2 (x y : float2) :=\n match (Fexp x - Fexp y)%Z with\n | Zpos p => (shl (Fnum x) p, Fnum y, Fexp y)\n | Zneg p => (Fnum x, shl (Fnum y) p, Fexp x)\n | Z0 => (Fnum x, Fnum y, Fexp x)\n end.\n\nLemma Fshift2_correct :\n  forall x y : float2,\n  match Fshift2 x y with\n  | (mx, my, e) => Float2 mx e = x :>R /\\ Float2 my e = y :>R\n  end.\nProof.\nintros (mx, ex) (my, ey).\nunfold Fshift2. simpl.\nassert (ex = ex - ey + ey)%Z by ring.\npattern ex at - 1 ; rewrite H.\ndestruct (ex - ey)%Z as [|d|d] ; repeat split.\nrewrite <- (float2_shl_correct mx _ d).\nnow ring_simplify (Zpos d + ey - Zpos d)%Z.\nrewrite Zplus_comm.\napply float2_shl_correct.\nQed.\n\nDefinition Fplus2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, e) => Float2 (mx + my) e\n end.\n\nLemma Fplus2_correct :\n  forall x y : float2,\n  Fplus2 x y = (x + y)%R :>R.\nProof.\nintros x y.\nunfold Fplus2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite plus_IZR.\napply Rmult_plus_distr_r.\nQed.\n\nDefinition Fminus2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, e) => Float2 (mx - my) e\n end.\n\nLemma Fminus2_correct :\n  forall x y : float2,\n  Fminus2 x y = (x - y)%R :>R.\nProof.\nintros x y.\nunfold Fminus2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite minus_IZR.\napply Rmult_minus_distr_r.\nQed.\n\nDefinition Fcomp2 (x y : float2) :=\n match Fshift2 x y with\n | (mx, my, _) => (mx ?= my)%Z\n end.\n\nLemma Fcomp2_correct :\n  forall x y : float2,\n  Fcomp2 x y = Rcompare x y.\nProof.\nintros x y.\nunfold Fcomp2.\ngeneralize (Fshift2_correct x y).\ndestruct (Fshift2 x y) as ((mx, my), e).\nintros (Hx, Hy).\nrewrite <- Hx, <- Hy.\nunfold float2R, F2R. simpl.\nrewrite Rcompare_mult_r.\nnow rewrite Rcompare_IZR.\napply bpow_gt_0.\nQed.\n\nDefinition Feq2 (x y : float2) :=\n match Fcomp2 x y with\n | Eq => true\n | _ => false\n end.\n\nLemma Feq2_correct :\n  forall x y : float2,\n  Feq2 x y = true -> x = y :>R.\nProof.\nintros x y Hb.\napply Rcompare_Eq_inv.\nrewrite <- Fcomp2_correct.\nrevert Hb.\nunfold Feq2.\nnow case Fcomp2.\nQed.\n\nDefinition Flt2 (x y : float2) :=\n match Fcomp2 x y with\n | Lt => true\n | _ => false\n end.\n\nLemma Flt2_correct :\n  forall x y : float2,\n  Flt2 x y = true -> (x < y)%R.\nProof.\nintros x y Hb.\napply Rcompare_Lt_inv.\nrewrite <- Fcomp2_correct.\nrevert Hb.\nunfold Flt2.\nnow case Fcomp2.\nQed.\n\nDefinition Fle2 (x y : float2) :=\n match Fcomp2 x y with\n | Gt => false\n | _ => true\n end.\n\nLemma Fle2_correct :\n  forall x y : float2,\n  Fle2 x y = true -> (x <= y)%R.\nProof.\nintros x y Hb.\napply Rcompare_not_Gt_inv.\nrewrite <- Fcomp2_correct.\nintros H.\nunfold Fle2 in Hb.\nnow rewrite H in Hb.\nQed.\n\nInductive Fle2_prop (x y : float2) : bool -> Prop :=\n  | Fle2_true : (x <= y)%R -> Fle2_prop x y true\n  | Fle2_false : (y < x)%R -> Fle2_prop x y false.\n\nLemma Fle2_spec :\n  forall x y, Fle2_prop x y (Fle2 x y).\nProof.\nintros x y.\ncase_eq (Fle2 x y) ; intros H.\napply Fle2_true.\napply Fle2_correct.\nexact H.\ngeneralize H. clear H.\nunfold Fle2.\ncase_eq (Fcomp2 x y) ; try (intros ; discriminate).\nintros H _.\napply Fle2_false.\napply Rcompare_Gt_inv.\nnow rewrite <- Fcomp2_correct.\nQed.\n\nDefinition Fis0 (x : float2) :=\n match (Fnum x) with\n   Z0 => true\n | _ => false\n end.\n\nLemma Fis0_correct :\n forall x : float2,\n Fis0 x = true -> x = 0%R :>R.\nintros x.\nunfold Fis0.\ninduction x.\ninduction Fnum ; intro H0 ; try discriminate.\napply float2_zero.\nQed.\n\nDefinition Fpos (x : float2) :=\n match (Fnum x) with\n   Zpos _ => true\n | _ => false\n end.\n\nLemma Fpos_correct :\n  forall x : float2,\n  Fpos x = true -> (0 < x)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_gt_0. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fneg (x : float2) :=\n match (Fnum x) with\n   Zneg _ => true\n | _ => false\n end.\n\nLemma Fneg_correct :\n  forall x : float2,\n  Fneg x = true -> (x < 0)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_lt_0. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fpos0 (x : float2) :=\n match (Fnum x) with\n   Zneg _ => false\n | _ => true\n end.\n\nLemma Fpos0_correct :\n  forall x : float2,\n  Fpos0 x = true -> (0 <= x)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_ge_0. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Fneg0 (x : float2) :=\n match (Fnum x) with\n   Zpos _ => false\n | _ => true\n end.\n\nLemma Fneg0_correct :\n  forall x : float2,\n  Fneg0 x = true -> (x <= 0)%R.\nProof.\nintros (m, e) H.\nunfold float2R.\napply F2R_le_0. simpl.\nrevert H.\nunfold Fpos. simpl.\nnow case m.\nQed.\n\nDefinition Flt2_m1 f :=\n  Flt2 (Float2 (-1) 0) f.\n\nLemma Flt2_m1_correct :\n  forall f,\n  Flt2_m1 f = true ->\n  (-1 < f)%R.\nProof.\nintros f Hb.\ngeneralize (Flt2_correct _ _ Hb).\nunfold float2R, F2R. simpl.\nnow rewrite Rmult_1_r.\nQed.\n\nDefinition Fle2_m1 f :=\n  Fle2 (Float2 (-1) 0) f.\n\nLemma Fle2_m1_correct :\n  forall f,\n  Fle2_m1 f = true ->\n  (-1 <= f)%R.\nProof.\nintros f Hb.\ngeneralize (Fle2_correct _ _ Hb).\nunfold float2R, F2R. simpl.\nnow rewrite Rmult_1_r.\nQed.\n", "meta": {"author": "MSoegtropIMC", "repo": "gappa-coq", "sha": "d6f5177181c35f07ff50bd5c173ee13528e06576", "save_path": "github-repos/coq/MSoegtropIMC-gappa-coq", "path": "github-repos/coq/MSoegtropIMC-gappa-coq/gappa-coq-d6f5177181c35f07ff50bd5c173ee13528e06576/src/Gappa_dyadic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7732002279049419}}
{"text": "Require Export TopologicalSpaces.\nRequire Export DirectedSets.\nRequire Export InteriorsClosures.\nRequire Export Continuity.\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\nImplicit Arguments net_limit [[I] [X]].\nImplicit Arguments net_cluster_point [[I] [X]].\nImplicit Arguments net_limit_is_cluster_point [[I] [X]].\nImplicit Arguments net_limit_in_closure [[I] [X]].\nImplicit Arguments 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": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Nets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660956376158, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7731694022843589}}
{"text": "Require Export SfLib.\n\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. reflexivity. Qed.\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) e2 => optimize_0plus e2\n  | APlus e1 e2 =>\n    APlus (optimize_0plus e1) (optimize_0plus e2)\n  | AMinus e1 e2 =>\n    AMinus (optimize_0plus e1) (optimize_0plus e2)\n  | AMult e1 e2 =>\n    AMult (optimize_0plus e1) (optimize_0plus e2)\n  end.\n\nExample 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).\nProof. reflexivity. Qed.\n\nTheorem optimize_0plus_sound : forall e,\n    aeval (optimize_0plus e) = aeval e.\nProof.\n  intros e. induction e.\n  Case \"ANum\". reflexivity.\n  Case \"APlus\". destruct e1.\n    SCase \"e1 = ANum n\". destruct n.\n      SSCase \"n = 0\". simpl. apply IHe2.\n      SSCase \"n <> 0\". simpl. rewrite IHe2. reflexivity.\n    SCase \"e1 = APlus e1_1 e1_2\".\n      simpl. simpl in IHe1. rewrite IHe1.\n      rewrite IHe2. reflexivity.\n    SCase \"e1 = AMinus e1_1 e1_2\".\n      simpl. simpl in IHe1. rewrite IHe1.\n      rewrite IHe2. reflexivity.\n    SCase \"e1 = AMult e1_1 e1_2\".\n      simpl. simpl in IHe1. rewrite IHe1.\n      rewrite IHe2. reflexivity.\n  Case \"AMinus\".\n    simpl. rewrite IHe1. rewrite IHe2. reflexivity.\n  Case \"AMult\".\n    simpl. rewrite IHe1. rewrite IHe2. reflexivity.\nQed.\n\nLemma foo : forall n, ble_nat 0 n = true.\nProof.\n  intros.\n  destruct n.\n    Case \"n=0\". simpl. reflexivity.\n    Case \"n=Sn\". simpl. reflexivity.\nQed.\n\nLemma foo' : forall n, ble_nat 0 n = true.\nProof.\n  intros.\n  destruct n;\n    simpl;\n    reflexivity.\nQed.\n\nTheorem optimize_0plus_sound' : forall e,\n    aeval (optimize_0plus e) = aeval e.\nProof.\n  intros e.\n  induction e;\n    try (simpl; rewrite IHe1; rewrite IHe2; reflexivity).\n  Case \"ANum\". reflexivity.\n  Case \"APlus\".\n    destruct e1;\n      try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n    SCase \"e1 = ANum n\".\n      destruct n;\n        simpl; rewrite IHe2; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound'' : forall e,\n    aeval (optimize_0plus e) = aeval e.\nProof.\n  intros e.\n  induction e;\n    try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);\n    try reflexivity.\n  Case \"APlus\".\n    destruct e1; try (simpl; simpl in IHe1; rewrite IHe1;\n                     rewrite IHe2; reflexivity).\n    SCase \"e1 = ANum n\".\n      destruct n; simpl; rewrite IHe2; reflexivity.\nQed.\n\nTactic Notation \"simpl_and_try\" tactic(c) :=\n  simpl;\n  try c.\n\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ANum\" | Case_aux c \"APlus\" |\n    Case_aux c \"AMinus\" | Case_aux c \"AMult\" ].\n\nTheorem optimize_0plus_sound''' : forall e,\n    aeval (optimize_0plus e) = aeval e.\nProof.\n  intros e.\n  aexp_cases (induction e) Case;\n    try (simpl; rewrite IHe1; rewrite IHe2; reflexivity);\n    try reflexivity.\n  Case \"APlus\".\n    aexp_cases (destruct e1) SCase;\n      try (simpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; reflexivity).\n    SCase \"ANum\". destruct n;\n      simpl; rewrite IHe2; reflexivity.\nQed.\n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\" |\n    Case_aux c \"BEq\"   | Case_aux c \"BLe\" |\n    Case_aux c \"BNot\"  | Case_aux c \"BAnd\" ].\n\nFixpoint optimize_0plus_b (e:bexp) : bexp :=\n  match e with\n  | BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)\n  | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n  | _ => e\n  end.\n\nExample optimize_0plus_b_test1:\n  optimize_0plus_b (BEq (APlus (ANum 0) (ANum 2))\n                   (ANum 2))\n  = (BEq (ANum 2) (ANum 2)).\nProof. reflexivity. Qed.\n\nTheorem optimize_0plus_b_sound : forall e,\n    beval (optimize_0plus_b e) = beval e.\nProof.\n  intros e.\n  bexp_cases (induction e) Case;\n    try (simpl; rewrite optimize_0plus_sound;\n         rewrite optimize_0plus_sound; reflexivity);\n    try reflexivity.\nQed.\n\nModule aevalR_first_try.\n\nInductive aevalR : aexp -> nat -> Prop :=\n| E_ANum : forall (n:nat),\n    aevalR (ANum n) n\n| E_APlus : forall (e1 e2 : aexp) (n1 n2 : nat),\n    aevalR e1 n1 ->\n    aevalR e2 n2 ->\n    aevalR (APlus e1 e2) (n1 + n2)\n| E_AMinus : forall (e1 e2 : aexp) (n1 n2 : nat),\n    aevalR e1 n1 ->\n    aevalR e2 n2 ->\n    aevalR (AMinus e1 e2) (n1 - n2)\n| E_AMult : forall (e1 e2 : aexp) (n1 n2 : nat),\n    aevalR e1 n1 ->\n    aevalR e2 n2 ->\n    aevalR (AMult e1 e2) (n1 * n2).\n\nNotation \"e '||' n\" := (aevalR e n) : type_scope.\n\nEnd aevalR_first_try.\n\nReserved Notation \"e '||' n\" (at level 50, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n| E_ANum : forall (n:nat),\n    (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)\nwhere \"e '||' n\" := (aevalR e n) : type_scope.\n\nTactic Notation \"aevalR_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"E_ANum\"   | Case_aux c \"E_APlus\" |\n    Case_aux c \"E_AMinus\" | Case_aux c \"E_AMult\" ].\n\nTheorem aeval_iff_aevalR : forall a n,\n    (a || n) <-> aeval a = n.\nProof.\n  split.\n  Case \"->\".\n    intros H.\n    aevalR_cases (induction H) SCase; simpl.\n    SCase \"E_ANum\".\n      reflexivity.\n    SCase \"E_APlus\".\n      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    SCase \"E_AMinus\".\n      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    SCase \"E_AMult\".\n      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n  Case \"<-\".\n    generalize dependent n.\n    aexp_cases (induction a) SCase;\n      simpl; intros; subst.\n    SCase \"ANum\".\n      apply E_ANum.\n    SCase \"APlus\".\n      apply E_APlus.\n      apply IHa1. reflexivity.\n      apply IHa2. reflexivity.\n    SCase \"AMinus\".\n      apply E_AMinus.\n      apply IHa1. reflexivity.\n      apply IHa2. reflexivity.\n    SCase \"AMult\".\n      apply E_AMult.\n      apply IHa1. reflexivity.\n      apply IHa2. reflexivity.\nQed.\n\nTheorem aeval_iff_aevalR' : forall a n,\n    (a || n) <-> aeval a = n.\nProof.\n  split.\n  Case \"->\".\n    intros H; induction H; subst; reflexivity.\n  Case \"<-\".\n    generalize dependent n.\n    induction a; simpl; intros; subst; constructor;\n      try apply IHa1; try apply IHa2; reflexivity.\nQed.\n\nReserved Notation \"e '||' n\" (at level 50, left associativity).\n\nInductive bevalR : bexp -> bool -> Prop :=\n| E_BTrue :\n    BTrue || true\n| E_BFalse :\n    BFalse || false\n| E_BEq : forall (e1 e2 : aexp) (n1 n2 : nat),\n    aevalR e1 n1 ->\n    aevalR e2 n2 ->\n    (BEq e1 e2) || (beq_nat n1 n2)\n| E_BLe : forall (e1 e2 : aexp) (n1 n2 : nat),\n    aevalR e1 n1 ->\n    aevalR e2 n2 ->\n    (BLe e1 e2) || (ble_nat n1 n2)\n| E_BNot : forall (e : bexp) (b : bool),\n    e || b ->\n    (BNot e) || (negb b)\n| E_BAnd : forall (e1 e2 : bexp) (b1 b2 : bool),\n    e1 || b1 ->\n    e2 || b2 ->\n    (BAnd e1 e2) || (andb b1 b2)\nwhere \"e '||' n\" := (bevalR e n) : type_scope.\n\nTactic Notation \"bevalR_cases\" tactic(first) ident(c) :=\n  first;\n  [Case_aux c \"E_BTrue\" | Case_aux c \"E_BFalse\" |\n   Case_aux c \"E_BEq\"   | Case_aux c \"E_BLe\" |\n   Case_aux c \"E_BNot\"  | Case_aux c \"E_BAnd\" ].\n\nTheorem beval_iff_bevalR : forall e b,\n    (e || b) <-> beval e = b.\nProof.\n  split.\n  Case \"->\".\n    intros H; induction H; simpl;\n      try (apply aeval_iff_aevalR in H;\n           apply aeval_iff_aevalR in H0);\n      subst; reflexivity.\n  Case \"<-\".\n    generalize dependent b.\n    induction e; simpl; intros; subst; constructor;\n    try apply aeval_iff_aevalR;\n    try apply IHe;\n    try apply IHe1;\n    try apply IHe2;\n    reflexivity.\nQed.\n\nEnd AExp.\n\nModule Id.\n\nInductive id : Type :=\n| Id : nat -> id.\n\nDefinition beq_id X1 X2 :=\n  match (X1, X2) with\n    (Id n1, Id n2) => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall X,\n    true = beq_id X X.\nProof.\n  intros. destruct X.\n  apply beq_nat_refl.\nQed.\n\nTheorem beq_id_eq : forall i1 i2,\n    true = beq_id i1 i2 -> i1 = i2.\nProof.\n  intros. destruct i1 as [n]. destruct i2 as [m].\n  unfold beq_id in H. apply beq_nat_eq in H.\n  subst. reflexivity.\nQed.\n\nTheorem beq_id_false_not_eq : forall i1 i2,\n    beq_id i1 i2 = false -> i1 <> i2.\nProof.\n  intros. destruct i1 as [n]. destruct i2 as [m].\n  unfold beq_id in H. apply beq_nat_false in H.\n  (*ここからSfLiを見てしまいました*)\n  intros C. apply H. inversion C. reflexivity.\nQed.\n\nTheorem not_eq_beq_id_false : forall i1 i2,\n    i1 <> i2 -> beq_id i1 i2 = false.\nProof.\n  intros. destruct i1 as [n]. destruct i2 as [m].\n  (*ここからSfLibの中を見てしまいました*)\n  assert (n <> m).\n  Case \"Proof of assertion\".\n    intros G. apply H. subst. reflexivity.\n    apply not_eq_beq_false. apply H0.\nQed.\n\nTheorem beq_id_sym : forall i1 i2,\n    beq_id i1 i2 = beq_id i2 i1.\nProof.\n  intros. destruct i1 as [n]. destruct i2 as [m].\n  unfold beq_id. apply beq_nat_sym.\nQed.\n\nEnd Id.\n\nDefinition state := id -> nat.\n\nDefinition empty_state : state :=\n  fun _ => 0.\n\nDefinition update (st:state) (X:id) (n:nat) : state :=\n  fun X' => if beq_id X X' then n else st X'.\n\nTheorem update_eq : forall n X st,\n    (update st X n) X = n.\nProof.\n  intros. unfold update.\n  rewrite <- beq_id_refl. reflexivity.\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. unfold update. rewrite H. reflexivity.\nQed.\n\nTheorem update_example : forall (n:nat),\n    (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  intros. unfold update. simpl. unfold empty_state. 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. unfold update.\n  destruct (beq_id k2 k1) as []eqn:?.\n  (* 上の代わりに下記のtacticでもおｋ\n  case_eq (beq_id k2 k1).\n   *)\n  Case \"beq_id k2 k1 = true\". reflexivity.\n  Case \"beq_id k2 k1 = false\". reflexivity.\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. unfold update.\n  destruct (beq_id k1 k2) as []eqn:?.\n  Case \"beq_id k1 k2 = true\".\n    apply eq_sym in Heqb.\n    apply beq_id_eq in Heqb.\n    rewrite <- H. rewrite Heqb. reflexivity.\n  Case \"beq_id k1 k2 = false\".\n    reflexivity.\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. unfold update.\n  case_eq (beq_id k1 k3); intros.\n  Case \"beq_id k1 k3 = true\".\n    apply eq_sym in H0. apply beq_id_eq in H0.\n    subst. rewrite H. reflexivity.\n  Case \"beq_id k1 k3 = false\".\n    reflexivity.\nQed.\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\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ANum\" | Case_aux c \"AId\" | Case_aux c \"APlus\"\n  | Case_aux c \"AMinus\" | Case_aux c \"AMult\" ].\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\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\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\" | Case_aux c \"BEq\"\n  | Case_aux c \"BLe\" | Case_aux c \"BNot\" | Case_aux c \"BAnd\" ].\n\nFixpoint aeval (st : state) (e : aexp) : nat :=\n  match e with\n  | ANum n => n\n  | AId X => st X\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\nExample aexp1 :\n  aeval (update empty_state X 5)\n        (APlus (ANum 3) (AMult (AId X) (ANum 2)))\n  = 13.\nProof. reflexivity.\nQed.\n\nExample bexp1 :\n  beval (update empty_state X 5)\n        (BAnd BTrue (BNot (BLe (AId X) (ANum 4))))\n  = true.\nProof. reflexivity.\nQed.\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\nTactic Notation \"com_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"SKIP\" | Case_aux c \"::=\" | Case_aux c \";\"\n  | Case_aux c \"IFB\" | Case_aux c \"WHILE\" ].\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' e1 'THEN' e2 'ELSE' e3 'FI'\" :=\n  (CIf e1 e2 e3) (at level 80, right associativity).\n\nDefinition fact_in_coq : com :=\n  Z ::= AId X;\n  Y ::= ANum 1;\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n        Y ::= AMult (AId Y) (AId Z);\n        Z ::= AMinus (AId Z) (ANum 1)\n  END.\n\nDefinition plus2 : com :=\n  X ::= (APlus (AId X) (ANum 2)).\n\nDefinition XtimesYinZ : com :=\n  Z ::= (AMult (AId X) (AId Y)).\n\nDefinition subtract_slowly_body : com :=\n  Z ::= AMinus (AId Z) (ANum 1);\n  X ::= AMinus (AId X) (ANum 1).\n\nDefinition subtract_slowly : com :=\n  WHILE BNot (BEq (AId X) (ANum 0)) DO\n    subtract_slowly_body\n  END.\n\nDefinition subtract_3_from_5_slowly : com :=\n  X ::= ANum 3;\n  Z ::= ANum 5;\n  subtract_slowly.\n\nDefinition loop : com :=\n  WHILE BTrue DO\n        SKIP\n  END.\n\nDefinition fact_body : com :=\n  Y ::= AMult (AId Y) (AId Z) ;\n  Z ::= AMinus (AId Z) (ANum 1).\n\nDefinition fact_loop : com :=\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n    fact_body\n  END.\n\nDefinition fact_com : com :=\n  Z ::= AId X ;\n  Y ::= ANum 1 ;\n  fact_loop.\n\nFixpoint ceval_step1 (st : state) (c : com) : state :=\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_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 =>\n    st\nend.\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_step1 st' c2\n    | IFB b THEN c1 ELSE c2 FI =>\n      if (beval st b)\n      then ceval_step2 st c1 i'\n      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\nend.\n\nFixpoint ceval_step3 (st : state) (c : com) (i : nat) : 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)\n      then ceval_step3 st c1 i'\n      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\nend.\n\nNotation \"'LETOPT' x <== e1 'IN' e2\" :=\n  (match e1 with\n   | Some x => e2\n   | None => None\n   end)\n    (right associativity, at level 60).\n\nFixpoint ceval_step (st : state) (c : com) (i : nat) : 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      LETOPT st' <== ceval_step st c1 i' IN\n             ceval_step st' c2 i'\n    | IFB b THEN c1 ELSE c2 FI =>\n      if (beval st b)\n      then ceval_step st c1 i'\n      else ceval_step st c2 i'\n    | WHILE b1 DO c1 END =>\n      if (beval st b1)\n      then LETOPT st' <== ceval_step st c1 i' IN\n                  ceval_step st' c i'\n      else Some st\n    end\nend.\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  Y ::= ANum 0;\n  WHILE (BLe (ANum 1) (AId X)) DO\n        Y ::= APlus (AId Y) (AId X);\n        X ::= AMinus (AId X) (ANum 1)\n  END.\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\nReserved Notation \"c1 '/' st '||' st'\" (at level 40, st at level 39).\n\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''\nwhere \"c1 '/' st '||' st'\" := (ceval c1 st st').\n\nTactic Notation \"ceval_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"E_Skip\" | Case_aux c \"E_Ass\" | Case_aux c \"E_Seq\"\n  | Case_aux c \"E_IfTrue\" | Case_aux c \"E_IfFalse\" | Case_aux c \"E_WhileEnd\" | Case_aux c \"E_WhileLoop\" ].\n\nExample ceval_example1:\n  (X ::= ANum 2;\n  IFB BLe (AId X) (ANum 1) THEN\n    Y ::= ANum 3\n  ELSE\n    Z ::= ANum 4\n  FI)\n    / empty_state\n    || (update (update empty_state X 2) Z 4).\nProof.\n  apply E_Seq with (update empty_state X 2).\n  Case \"assignment command\".\n    apply E_Ass. reflexivity.\n  Case \"if command\".\n    apply E_IfFalse.\n    reflexivity.\n    apply E_Ass. reflexivity.\nQed.\n\nExample ceval_example2:\n  (X ::= ANum 0; Y ::= ANum 1; Z ::= ANum 2) / empty_state ||\n  (update (update (update empty_state X 0) Y 1) Z 2).\nProof.\n  apply E_Seq with (update empty_state X 0).\n  apply E_Ass. reflexivity.\n  apply E_Seq with (update (update empty_state X 0) Y 1).\n  apply E_Ass. reflexivity.\n  apply E_Ass. reflexivity.\nQed.\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 c st st' H.\n  inversion H as [i E].\n  clear H.\n  generalize dependent st'.\n  generalize dependent st.\n  generalize dependent c.\n  induction i as [| i'].\n  Case \"i = 0 -- contradictory\".\n    intros c st st' H. inversion H.\n  Case \"i = S i'\".\n    intros c st st' H.\n    com_cases (destruct c) SCase;\n      simpl in H; inversion H; subst; clear H.\n    SCase \"SKIP\". apply E_Skip.\n    SCase \"::=\". apply E_Ass. reflexivity.\n    SCase \";\".\n      remember (ceval_step st c1 i') as r1. destruct r1.\n      SSCase \"Evaluation of r1 terminates normally\".\n        apply E_Seq with s.\n          apply IHi'. rewrite Heqr1. reflexivity.\n          apply IHi'. simpl in H1. assumption.\n      SSCase \"Otherwise -- contradiction\".\n        inversion H1.\n    SCase \"IFB\".\n      remember (beval st b) as r. destruct r.\n      SSCase \"r = true\".\n        apply E_IfTrue. rewrite Heqr. reflexivity.\n        apply IHi'. assumption.\n      SSCase \"r = false\".\n        apply E_IfFalse. rewrite Heqr. reflexivity.\n        apply IHi'. assumption.\n    SCase \"WHILE\". remember (beval st b) as r. destruct r.\n      SSCase \"r = true\".\n        remember (ceval_step st c i') as r1. destruct r1.\n        SSSCase \"r1 = Some s\".\n          apply E_WhileLoop with s. rewrite Heqr. reflexivity.\n          apply IHi'. rewrite Heqr1. reflexivity.\n          apply IHi'. simpl in H1. assumption.\n        SSSCase \"r1 = None\".\n          inversion H1.\n      SSCase \"r = false\".\n        inversion H1.\n        apply E_WhileEnd.\n        rewrite Heqr. subst. reflexivity.\nQed.\n\nTheorem ceval_step_more : forall i1 i2 st st' c,\n    i1 <= i2 ->\n    ceval_step st c i1 = Some st' ->\n    ceval_step st c i2 = Some st'.\nProof.\n  induction i1 as [| i1']; intros i2 st st' c Hle Hceval.\n  Case \"i1 = 0\".\n    inversion Hceval.\n  Case \"i1 = S i1'\".\n    destruct i2 as [| i2']. inversion Hle.\n    assert (Hle': i1' <= i2') by omega.\n    com_cases (destruct c) SCase.\n    SCase \"SKIP\".\n      simpl in Hceval. inversion Hceval.\n      reflexivity.\n    SCase \"::=\".\n      simpl in Hceval. inversion Hceval.\n      reflexivity.\n    SCase \";\".\n      simpl in Hceval. simpl.\n      remember (ceval_step st c1 i1') as st1'o.\n      destruct st1'o.\n      SSCase \"st1'o = Some\".\n        symmetry in Heqst1'o.\n        apply (IHi1' i2') in Heqst1'o; try assumption.\n        rewrite Heqst1'o.\n        apply (IHi1' i2') in Hceval; try assumption.\n      SSCase \"st1'o = None\".\n        inversion Hceval.\n    SCase \"IFB\".\n      simpl in Hceval. simpl.\n      remember (beval st b) as bval.\n      destruct bval; apply (IHi1' i2') in Hceval; assumption.\n    SCase \"WHILE\".\n      simpl in Hceval. simpl.\n      destruct (beval st b); try assumption.\n      remember (ceval_step st c i1') as st1'o.\n      destruct st1'o.\n      SSCase \"st1'o = Some\".\n        symmetry in Heqst1'o.\n        apply (IHi1' i2') in Heqst1'o; try assumption.\n        rewrite -> Heqst1'o. simpl. simpl in Hceval.\n        apply (IHi1' i2') in Hceval; try assumption.\n      SSCase \"st1'o = None\".\n        simpl in Hceval. inversion Hceval.\nQed.\n\nTheorem ceval__ceval_step : forall c st st',\n    c / st || st' ->\n    exists i, ceval_step st c i = Some st'.\nProof.\n  intros c st st' Hce.\n  ceval_cases (induction Hce) Case.\n  Case \"E_Skip\". exists 1. reflexivity.\n  Case \"E_Ass\". exists 1. simpl. rewrite H. reflexivity.\n  Case \"E_Seq\". destruct IHHce1. destruct IHHce2.\n    exists (1 + x + x0). simpl.\n    remember (ceval_step st c1 (x + x0)) as r.\n    destruct r.\n    SCase \"r = Some\".\n      apply ceval_step_more with (i2 := (x + x0)) in H.\n      rewrite H in Heqr. inversion Heqr.\n      apply ceval_step_more with (i1 := x0). omega.\n      assumption. omega.\n    SCase \"r = None\".\n      apply ceval_step_more with (i2 := (x + x0)) in H.\n      rewrite H in Heqr. inversion Heqr. omega.\n  Case \"E_IfTrue\". destruct IHHce.\n    exists (1 + x). simpl. rewrite H. apply H0.\n  Case \"E_IfFalse\". destruct IHHce.\n    exists (1 + x). simpl. rewrite H. apply H0.\n  Case \"E_WhileEnd\". exists 1. simpl. rewrite H. reflexivity.\n  Case \"E_WhileLoop\". destruct IHHce1. destruct IHHce2.\n    exists (1 + x + x0). simpl. rewrite H.\n    remember (ceval_step st c1 (x + x0)) as r.\n    destruct r.\n    SCase \"r = Some\".\n      apply ceval_step_more with (i2 := x + x0) in H0.\n      rewrite H0 in Heqr. inversion Heqr.\n      apply ceval_step_more with (i2 := x + x0) in H1.\n      assumption. omega. omega.\n    SCase \"r = None\".\n      apply ceval_step_more with (i2 := x + x0) in H0.\n      rewrite H0 in Heqr. inversion Heqr. omega.\nQed.\n\nTheorem ceval_and_ceval_step_coincide : forall c st st',\n    c / st || st'\n    <-> exists i, ceval_step st c i = Some st'.\nProof.\n  intros c st st'.\n  split. apply ceval__ceval_step. apply ceval_step__ceval.\nQed.\n\nTheorem ceval_deterministic : forall c st st1 st2,\n    c / st || st1 ->\n    c / st || st2 ->\n    st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  ceval_cases (induction E1) Case;\n    intros st2 E2; inversion E2; subst.\n  Case \"E_Skip\". reflexivity.\n  Case \"E_Ass\". reflexivity.\n  Case \"E_Seq\".\n    assert (st' = st'0) as EQ1.\n    SCase \"Proof of assertion\". apply IHE1_1; assumption.\n    subst st'0.\n    apply IHE1_2. assumption.\n  Case \"E_IfTrue\".\n    SCase \"b1 evaluates to true\".\n      apply IHE1. assumption.\n    SCase \"b1 evaluates to false (contradiction)\".\n      rewrite H in H5. inversion H5.\n  Case \"E_IfFalse\".\n    SCase \"b1 evaluates to true (contradiction)\".\n      rewrite H in H5. inversion H5.\n    SCase \"b1 evaluates to false\".\n      apply IHE1. assumption.\n  Case \"E_WhileEnd\".\n    SCase \"b1 evaluates to true\".\n      reflexivity.\n    SCase \"b1 evaluates to false (contradiction)\".\n      rewrite H in H2. inversion H2.\n  Case \"E_WhileLoop\".\n    SCase \"b1 evaluates to true (contradiction)\".\n      rewrite H in H4. inversion H4.\n    SCase \"b1 evaluates to false\".\n      assert (st' = st'0) as EQ1.\n      SSCase \"Proof of assertion\". apply IHE1_1; assumption.\n      subst st'0.\n      apply IHE1_2. assumption.\nQed.\n\nTheorem ceval_deterministic' : forall c st st1 st2,\n    c / st || st1 ->\n    c / st || st2 ->\n    st1 = st2.\nProof.\n  intros c st st1 st2 He1 He2.\n  apply ceval__ceval_step in He1.\n  apply ceval__ceval_step in He2.\n  inversion He1 as [i1 E1].\n  inversion He2 as [i2 E2].\n  apply ceval_step_more with (i2 := i1 + i2) in E1.\n  apply ceval_step_more with (i2 := i1 + i2) in E2.\n  rewrite E1 in E2. inversion E2. reflexivity.\n  omega. omega.\nQed.\n\nTheorem plus2_spec : forall st n st',\n    st X = n ->\n    plus2 / st || st' ->\n    st' X = n + 2.\nProof.\n  intros st n st' HX Heval.\n  inversion Heval. subst.\n  apply update_eq.\nQed.\n\nTheorem XtimesYinZ_spec : forall st st' n m,\n    st X = n ->\n    st Y = m ->\n    XtimesYinZ / st || st' ->\n    st' Z = n * m.\nProof.\n  intros st st' n m HX HY Heval.\n  inversion Heval. subst.\n  apply update_eq.\nQed.\n\nTheorem loop_never_stops : forall st st',\n    ~(loop / st || st').\nProof.\n  intros st st' contra. unfold loop in contra.\n  remember (WHILE BTrue DO SKIP END) as loopdef.\n  induction contra; inversion Heqloopdef.\n    Case \"E_WhileEnd\".\n      rewrite H1 in H. simpl in H. inversion H.\n    Case \"E_WhileLoop\". contradiction.\nQed.\n\nFixpoint no_whiles (c : com) : bool :=\n  match c with\n  | SKIP => true\n  | _ ::= _ => true\n  | c1 ; c2 => andb (no_whiles c1) (no_whiles c2)\n  | IFB _ THEN ct ELSE cf FI => andb (no_whiles ct) (no_whiles cf)\n  | WHILE _ DO _ END => false\n  end.\n\n(*\nInductive no_whilesR: com -> Prop :=\n| NW_Skip : no_whilesR SKIP\n| NW_Ass : forall l a,\n    no_whilesR (l ::= a)\n| NW_Seq : forall c1 c2,\n    no_whilesR c1 ->\n    no_whilesR c2 ->\n    no_whilesR (c1 ; c2)\n| NW_If : forall c1 c2 b,\n    no_whilesR c1 ->\n    no_whilesR c2 ->\n    no_whilesR (IFB b THEN c1 ELSE c2 FI)\n.\n\nTheorem no_whiles_eqv : forall c,\n    no_whiles c = true <-> no_whilesR c.\nProof.\n  intros. split.\n  Case \"->\". intro.\n    com_cases (induction c) SCase; try (constructor).\n    SCase \";\".\n      simpl in H. apply IHc1. rewrite <- H.\n*)", "meta": {"author": "MountainSeal", "repo": "coq_study", "sha": "8f5c27fa4f5ed0775d60c96210d60a5ece100327", "save_path": "github-repos/coq/MountainSeal-coq_study", "path": "github-repos/coq/MountainSeal-coq_study/coq_study-8f5c27fa4f5ed0775d60c96210d60a5ece100327/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7731560288938202}}
{"text": "(* Exercise coq_nat_09 *)\n\n(* Now, let us prove that multiplication is commutative *)\n\n(* For this we may need to use some properties of addition and multiplication  \n   that we proved before. *)\nRequire Import Arith.\nCheck mult_0_r.\nCheck plus_comm.\nCheck plus_assoc.\n\n(* ... and a following auxiliary lemma *)\n\nLemma mult_succ : forall m n, n + n * m = n * S m.\nProof.\nintros.\ninduction n.\nsimpl; reflexivity.\nsimpl.\nrewrite <- IHn.\nrewrite Nat.add_comm.\nrewrite Nat.add_assoc.\nrewrite Nat.add_comm with (n := m+n*m).\nrewrite Nat.add_assoc.\nrewrite Nat.add_comm with (n := n).\nreflexivity.\nQed.\n\nLemma mult_comm : forall m n, m * n = n * m.\n\nProof.\nintros.\ninduction m.\nrewrite Nat.mul_0_r.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHm.\nrewrite mult_succ.\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_nat_09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7731524316198839}}
{"text": "Inductive 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  | B x => A (incr x)\n  | A x => B x         \n  end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  | Z => O\n  | B Z => 1\n  | B x => 1 + 2 * (bin_to_nat x)\n  | A x => 2 * (bin_to_nat x)\n  end.\n\nTheorem test: forall code: bin, bin_to_nat(incr(code)) = 1 + bin_to_nat(code).\nProof.\nintros n.\ninduction n as [|n'1 IHn1|n'2 IHn2].\n- simpl. reflexivity.\n- destruct n'1; repeat auto.\n- destruct n'2.\n  * reflexivity.\n  * destruct n'2; repeat (simpl; auto).\n  * simpl.\n    simpl in IHn2.\n    rewrite -> IHn2.\n    destruct n'2; repeat (simpl; auto).\nQed.\n\n\n\n", "meta": {"author": "dk14", "repo": "proofs", "sha": "cabcaf641a79597dd5b11d12bef6bd4f88b07dc5", "save_path": "github-repos/coq/dk14-proofs", "path": "github-repos/coq/dk14-proofs/proofs-cabcaf641a79597dd5b11d12bef6bd4f88b07dc5/binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7731004196389175}}
{"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\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 (append (rev x) (rev y))) (append y x).\nProof.\n  induction x.\n  - intros. simpl. rewrite rev_rev. rewrite append_nil. reflexivity.\n  - intros. simpl. rewrite rev_append. simpl. rewrite (eq_refl : cons n nil = rev (cons n nil)). rewrite IHx. rewrite rev_rev. 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/goal80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7730853773071665}}
{"text": "Require Import Nat.\nRequire Import Arith.\n\n\n(*\n  The \"Tm\" type and the previously defined typing relation.\n*)\n\nInductive Tm : Set :=\n  | num (n : nat)\n  | plus (t t' : Tm)\n  | isZero (t : Tm)\n  | true\n  | false\n  | ifThenElse (t t' t'' : Tm)\n.\n\n\nNotation \"t + t'\" := (plus t t') : term_scope.\nNotation\n  \"'If' t 'then' t' 'else' t''\" :=\n  (ifThenElse t t' t'')\n  (at level 100)\n  : term_scope\n.\n\n(* Delimit Scope term_scope with term. *)\n(* Bind Scope term_scope with Tm. *)\nOpen Scope term_scope.\n\n(* Compute (plus (num 1) (num 2)). *)\nCompute (num 1 + num (2 + 3)).\nCompute (2 + 4)%nat.\n\n(* The set of Ty and the inductive typing relation. *)\n\nInductive Ty : Set := Nat | Bool.\n\nInductive TypeJudgement : Tm -> Ty -> Prop :=\n  | TJ_num {n : nat} : (num n) :: Nat\n  | TJ_plus {t t' : Tm} (j : t :: Nat) (j' : t' :: Nat) : (t + t') :: Nat\n  | TJ_isZero {t : Tm} (j : t :: Nat) : (isZero t) :: Bool\n  | TJ_true : true :: Bool\n  | TJ_false : false :: Bool\n\n  | TJ_ifThenElse\n    {t t' t'' : Tm} {A : Ty}\n    (j : t :: Bool) (j' : t' :: A) (j'' : t'' :: A)\n    : (If t then t' else t'') :: A\n\nwhere \"tm :: ty\" := (TypeJudgement tm ty) : term_scope.\n\n\n(*\n  2.3. OperĂĄciĂłs szemantika\n*)\n\n(* val : 2.9. - 2.11. *)\n\nReserved Notation \"t 'val'\" (at level 1).\n\nInductive ValueJudgement : Tm -> Prop :=\n  | VJ_num {n : nat} : (num n) val\n  | VJ_true : true val\n  | VJ_false : false val\nwhere\n  \"t 'val'\" :=\n  (ValueJudgement t)\n  : term_scope.\n\n\n(*\n  Transition judgements.\n*)\n\nReserved Notation \"t |-> t'\" (at level 100).\n\n(* One Step Transition : 2.14. - 2.22. *)\n\nInductive OneStepTransitionJudgement : Tm -> Tm -> Prop :=\n  | OSTJ_sum {n1 n2 n : nat} :\n    ((n1 + n2)%nat = n) ->\n    num n1 + num n2 |-> num n\n\n  | OSTJ_isZero_true :\n    (isZero (num 0)) |-> true\n\n  | OSTJ_isZero_false {n : nat} :\n    (n > 0) ->\n    isZero (num n) |-> false\n\n  | OSTJ_ifThenElse_true {t t' : Tm} :\n    If true then t else t' |-> t\n\n  | OSTJ_ifThenElse_false {t t' : Tm} :\n    If false then t else t' |-> t'\n\n  | OSTJ_plus_left {t1 t1' t2 : Tm} :\n    (t1 |-> t1') ->\n    t1 + t2 |-> t1' + t2\n\n  | OSTJ_plus_right {t1 t2 t2' : Tm} :\n    t1 val -> (t2 |-> t2') ->\n    t1 + t2 |-> t1 + t2'\n\n  | OSTJ_isZero {t t' : Tm} :\n    (t |-> t') ->\n    isZero t |-> isZero t'\n\n  | OSTJ_ifThenElse {t t' t1 t2 : Tm} :\n    (t |-> t') ->\n    If t then t1 else t2 |-> If t' then t1 else t2\nwhere\n  \"t |-> t'\" :=\n  (OneStepTransitionJudgement t t')\n  : term_scope.\n\n\n(* Any Step Transition : 2.12. - 2.13. *)\n\nReserved Notation \"t |->* t'\" (at level 100).\n\nInductive AnyStepTransitionJudgement : Tm -> Tm -> Prop :=\n  | ASTJ_refl {t : Tm} :\n    t |->* t\n  | ASTJ_trans {t t'' : Tm} (t' : Tm) : \n    (t |-> t') -> (t' |->* t'') ->\n    t |->* t''\nwhere \"t |->* t'\" := (AnyStepTransitionJudgement t t') : term_scope.\n\n\nLemma p :\n  (num 1 + num 2) + (num 3 + num 4) |-> num 3 + (num 3 + num 4)\n.\nProof.\n  apply OSTJ_plus_left.\n  apply OSTJ_sum.\n  simpl. reflexivity.\nQed.\n\nLemma q :\n  num 3 + (num 3 + num 4) |-> num 3 + num 7\n.\nProof.\n  apply OSTJ_plus_right.\n  - apply VJ_num.\n  - apply OSTJ_sum.\n    simpl. reflexivity.\nQed.\n\nLemma r :\n  num 3 + num 7 |-> num 10\n.\nProof.\n  apply OSTJ_sum.\n  simpl. reflexivity.\nQed.\n\nLemma TransitionTest1 :\n  (num 1 + num 2) + (num 3 + num 4) |->* num 10\n.\nProof.\n  refine (ASTJ_trans _ p _).\n  - refine (ASTJ_trans _ q _).\n    + refine (ASTJ_trans _ r _).\n      * exact ASTJ_refl.\nQed.\n\n\nLemma TransitionTest2 :\n  If isZero (num 1 + num 2) then num 1 else (num 3 + num 1) |->* num 4\n.\nProof.\n  eapply ASTJ_trans.\n  {\n    eapply OSTJ_ifThenElse.\n    eapply OSTJ_isZero.\n    eapply OSTJ_sum; reflexivity.\n  }\n\n  eapply ASTJ_trans.\n  {\n    eapply OSTJ_ifThenElse.\n    eapply OSTJ_isZero_false.\n    eapply gt_Sn_O.\n  }\n\n  eapply ASTJ_trans.\n  {\n    eapply OSTJ_ifThenElse_false.\n  }\n\n  eapply ASTJ_trans.\n  {\n    eapply OSTJ_sum; reflexivity.\n  }\n\n  eapply ASTJ_refl.\nQed.\n\n(* Proof.\n  refine (ASTJ_trans _ _ _).\n  - refine (OSTJ_ifThenElse _).\n    + refine (OSTJ_isZero _).\n      * refine (OSTJ_sum _).\n        -- simpl. reflexivity.\n  - refine (ASTJ_trans _ _ _).\n    + refine (OSTJ_ifThenElse _).\n      * refine (OSTJ_isZero_false _).\n        -- auto.\n    + refine (ASTJ_trans _ _ _).\n      * refine (OSTJ_ifThenElse_false).\n      * refine (ASTJ_trans _ _ _).\n        -- refine (OSTJ_sum _).\n           simpl. reflexivity.\n        -- exact ASTJ_refl.\nQed. *)\n\nLtac transition_solver :=\n  repeat (\n    (eapply ASTJ_refl)\n    ||\n    (eapply ASTJ_trans; repeat (\n      (eapply OSTJ_sum; reflexivity) ||\n      (eapply OSTJ_plus_right; (only 1: eapply VJ_num)) ||\n      (eapply OSTJ_plus_left) ||\n      (eapply OSTJ_isZero_true) ||\n      (eapply OSTJ_isZero_false; eapply gt_Sn_O) ||\n      (eapply OSTJ_isZero) ||\n      (eapply OSTJ_ifThenElse_true) ||\n      (eapply OSTJ_ifThenElse_false) ||\n      (eapply OSTJ_ifThenElse)\n    ))\n  )\n.\n\n(*\n  2.19. Lemma.\n  No transition from val.\n*)\n\nLemma no_val_transition :\n  forall t t' : Tm, ~ ((t val) /\\ (t |-> t'))\n.\nProof.\n  unfold not. intros. inversion H.\n  induction H1; inversion H0.\nQed.\n\n\n(*\n  2.20. Lemma.\n  Determinism.\n*)\n\nLemma determinism {t t'} :\n  (t |-> t') -> (forall t'' : Tm, (t |-> t'') -> (t' = t''))\n.\nProof.\n  intros H.\n  induction H.\n\n  (* sum *)\n  - intros. inversion H0.\n    + rewrite <- H. rewrite <- H4. reflexivity.\n    + inversion H4.\n    + inversion H5.\n\n  (* isZero_true *)\n  - intros. inversion H.\n    + reflexivity.\n    + inversion H1.\n    + inversion H1.\n\n  (* isZero_false *)\n  - intros. inversion H0.\n    + rewrite <- H2 in H. inversion H.\n    + reflexivity.\n    + inversion H2.\n\n  (* ifThenElse_true *)\n  - intros. inversion H.\n    + reflexivity.\n    + inversion H4.\n\n  (* ifThenElse_false *)\n  - intros. inversion H.\n    + reflexivity.\n    + inversion H4.\n\n  (* plus_left *)\n  - intros. inversion H0.\n    + rewrite <- H1 in *. inversion H.\n    + pose (ir := IHOneStepTransitionJudgement t1'0 H4).\n      rewrite ir. reflexivity.\n    + pose (nvt := no_val_transition t1 t1').\n      unfold not in nvt.\n      pose (f := nvt (conj H3 H)). inversion f.\n\n  (* plus_right *)\n  - intros. inversion H1.\n    + rewrite <- H4 in *. inversion H0.\n    + pose (nvt := no_val_transition t1 t1').\n      unfold not in nvt.\n      pose (f := nvt (conj H H5)). inversion f.\n    + pose (ir := IHOneStepTransitionJudgement t2'0 H6).\n      rewrite ir. reflexivity.\n\n  (* isZero *)\n  - intros. inversion H0.\n    + rewrite <- H2 in *. inversion H.\n    + rewrite <- H1 in *. inversion H.\n    + pose (ir := IHOneStepTransitionJudgement t'0 H2).\n      rewrite ir. reflexivity.\n\n  (* ifThenElse *)\n  - intros. inversion H0.\n    + rewrite <- H2 in *. inversion H.\n    + rewrite <- H2 in *. inversion H.\n    + pose (ir := IHOneStepTransitionJudgement t'0 H5).\n      rewrite ir. reflexivity.\nQed.\n\n(*\n  2.29. Lemma\n*)\nLemma progress_helper_Nat {t : Tm} :\n  (t :: Nat) -> (t val) -> (exists n : nat, t = num n)\n.\nProof.\n  intros. inversion H0.\n  + refine (ex_intro _ _ _). reflexivity.\n  + rewrite <- H1 in *. inversion H.\n  + rewrite <- H1 in *. inversion H.\nQed.\n\nLemma progress_helper_Bool {t : Tm} :\n  (t :: Bool) -> (t val) -> (t = true \\/ t = false).\nProof.\n  intros.\n  inversion H0.\n  + subst. inversion H.\n  + left. trivial.\n  + right. trivial.\nQed.\n\nTheorem progress {t : Tm} {A : Ty} :\n  (t :: A) -> t val \\/ (exists t' : Tm, t |-> t').\nProof.\n  intros. induction H.\n  + left. apply VJ_num.\n  + right. destruct IHTypeJudgement1; destruct IHTypeJudgement2.\n    - pose (lhs := progress_helper_Nat H H1).\n      pose (rhs := progress_helper_Nat H0 H2).\n      inversion lhs. inversion rhs. subst.\n      eapply (ex_intro ). eapply OSTJ_sum. trivial.\n    - pose (lhs := progress_helper_Nat H H1).\n      inversion lhs. subst.\n      inversion H2. \n      (* all used variables must be in the context before applying ex_intro *)\n      eapply ex_intro. eapply OSTJ_plus_right.\n      * exact H1.\n      * exact H3.\n     - pose (rhs := progress_helper_Nat H0 H2).\n       inversion rhs. subst.\n       inversion H1.\n       eapply ex_intro.\n       eapply OSTJ_plus_left. exact H3.\n     - inversion H1. inversion H2.\n       eapply ex_intro. eapply OSTJ_plus_left. exact H3.\n  \n  (* isZero *)\n  + right. destruct IHTypeJudgement.\n    - pose (lem := progress_helper_Nat H H0). \n      inversion lem. subst. \n      destruct x; eapply ex_intro.\n      * eapply OSTJ_isZero_true.\n      * eapply OSTJ_isZero_false. apply gt_Sn_O.\n    - inversion H0. eapply ex_intro. eapply OSTJ_isZero. exact H1.\n  \n  (* true *)  \n  + left. apply VJ_true.\n  \n  (* false *)  \n  + left. apply VJ_false.\n  \n  (* IfThenElse *)\n  + destruct IHTypeJudgement1.\n    - right. pose (lem := progress_helper_Bool H H2).\n      destruct lem; subst.\n      * eapply ex_intro. eapply OSTJ_ifThenElse_true.\n      * eapply ex_intro. eapply OSTJ_ifThenElse_false.\n    - right. inversion H2. eapply ex_intro. eapply OSTJ_ifThenElse. exact H3.\nQed.\n\nTheorem type_preservation {t t' : Tm} :\n  (t |-> t') -> (forall A : Ty, (t :: A) -> (t' :: A)).\nProof.\n  intros H. induction H; intros.\n  (* num *)\n  + inversion H0. subst. apply TJ_num.\n  (* true *)\n  + inversion H. subst. apply TJ_true.\n  (* false *)\n  + inversion H0. apply TJ_false.\n  (* IfThenElse *)\n  + inversion H. subst. exact j'.\n  + inversion H. subst. exact j''.\n  (* Plus *)\n  + inversion H0. subst. eapply TJ_plus.\n    - apply IHOneStepTransitionJudgement. exact j.\n    - exact j'.\n  + inversion H1. subst. apply TJ_plus.\n    - exact j.\n    - apply IHOneStepTransitionJudgement. exact j'.\n  (* isZero *)\n  + inversion H0. subst. apply TJ_isZero.\n    apply IHOneStepTransitionJudgement. exact j.\n  (* IfThenElse condition rewrite *)\n  + inversion H0. subst. apply TJ_ifThenElse.\n    - apply IHOneStepTransitionJudgement. exact j.\n    - exact j'.\n    - exact j''.\nQed.\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Anabra", "repo": "type-systems", "sha": "36565e1bc477f6d47f726c22b90e909c189c4fb5", "save_path": "github-repos/coq/Anabra-type-systems", "path": "github-repos/coq/Anabra-type-systems/type-systems-36565e1bc477f6d47f726c22b90e909c189c4fb5/type_presenvation_and_progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7730144025253999}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Coq.Logic.Classical.\nRequire Import Coq.Logic.Decidable. (* Introducing decidable *)\n\nSection Logic_Theories.\n  Lemma or_dist_and: forall (A B C:Prop), A \\/ (B /\\ C) <-> (A \\/ B) /\\ (A \\/ C).\n  Proof.\n    rewrite /iff.\n    split.\n    case.\n    move => HA.\n    split.\n    left.\n    apply HA.\n    left.\n    apply HA.\n    case.\n    move => HB HC.\n    split; right.\n    apply HB.\n    apply HC.\n    case.\n    move => HAB HAC.\n    inversion HAB.\n    left.\n    apply H.\n    inversion HAC.\n    left.\n    apply H0.\n    right.\n    split.\n    apply H.\n    apply H0.\n  Qed.\n\n  Lemma and_dist_or: forall (A B C:Prop), A /\\ (B \\/ C) <-> (A /\\ B) \\/ (A /\\ C).\n  Proof.\n    rewrite /iff.\n    split.\n    case => HA.\n    case => HB.\n    left.\n    split; done.\n    right.\n    split; done.\n    case.\n    case => HA HB.\n    split.\n    done.\n    left.\n    done.\n    case => HA HC.\n    split.\n    done.\n    right.\n    done.\n  Qed.\n\n  Lemma or_imply_to_imply_and:\n    forall (A B C:Prop), (A \\/ B -> C) -> ((A -> C) /\\ (B -> C)).\n  Proof.\n    move => A B C H.\n    split; move => H0; apply H.\n    left.\n    apply H0.\n    right.\n    apply H0.\n  Qed.\n\n  Lemma or_not_l_iff_3: forall (A B C:Prop), (A -> False) \\/ (B -> False) \\/ C <-> (A /\\ B -> C).\n  Proof.\n    move => A B C.\n    rewrite /iff.\n    split => H.\n    case.\n    move => HA.\n    apply or_not_l_iff_2.\n    apply classic.\n    move: HA.\n    apply or_not_l_iff_2.\n    apply classic.\n    apply H.\n    apply or_not_l_iff_2.\n    apply classic.\n    move => HA.\n    apply or_not_l_iff_2.\n    apply classic.\n    move => HB.\n    apply H.\n    split.\n    apply HA.\n    apply HB.\n  Qed.\n\n  Lemma imply_and_to_or_imply: forall (A B C:Prop), (A -> B /\\ C) -> (A -> B) /\\ (A -> C).\n  Proof.\n    move => A B C H.\n    split; apply H.\n  Qed.\n\nEnd Logic_Theories.\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/set_theory/logic_theories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7729420569638772}}
{"text": "From Coq Require Import \n  PeanoNat Lia Eqdep_dec Arith.\n\n\nSection Fin. \n\n  Inductive Fin : nat -> Type :=\n  | Fz {n : nat} : Fin (S n)\n  | Fs {n : nat} : Fin n -> Fin (S n).\n\n\n  Fact uip_nat {n : nat} (e : n = n) : e = eq_refl.\n  Proof. apply UIP_dec, eq_nat_dec. Qed.\n  \n\n  Lemma fin_ind : \n    forall (n : nat) (P : Fin (S n) -> Type), \n    P Fz -> (forall (f : Fin n), P (Fs f)) ->\n    forall fw : Fin (S n), P fw.\n  Proof.\n    intros ? ? Hfz Hfs.\n    refine (\n      fix Fn fw :=\n      match fw as fw' in Fin (S np)\n        return\n          forall (pf : np = n), \n            fw = (eq_rect np (fun wp => Fin (S wp)) fw' n pf) -> \n            P (eq_rect np (fun wp => Fin (S wp)) fw' n pf)\n      with \n      | Fz => fun Heq Hf => _ \n      | Fs _ => fun Heq Hf => _ \n      end eq_refl eq_refl).\n    + subst.\n      exact Hfz.\n    + subst.\n      apply Hfs.\n  Qed.\n\n  (* \n    Show Proof. \n    Print EqdepFacts.internal_eq_rew_r_dep.\n  *)\n\n  Fixpoint nat_to_fin (n : nat) : Fin (S n) :=\n    match n with\n    | 0 => Fz \n    | S n' => Fs (nat_to_fin n')\n  end.\n\n\n\n  Fixpoint fin_to_nat {n : nat} (f : Fin n) : nat :=\n    match f with \n    | Fz => 0 \n    | Fs t => S (fin_to_nat t)\n    end.\n  \n\n\n  Lemma nat_to_fin_and_fin_to_nat_inv : \n    forall (n : nat), fin_to_nat (nat_to_fin n) = n.\n  Proof.\n    refine (\n      fix Fn n :=\n        match n with \n        | 0 => eq_refl \n        | S n' => _ \n        end).\n      simpl; rewrite Fn.\n      exact eq_refl.\n  Defined.\n\n\n  Lemma fin_inv_0 (f : Fin 0) : False.\n  Proof.\n    refine (match f with end).\n  Defined.\n  \n \n  Lemma fin_inv_S {n : nat} (f : Fin (S n)) :\n    (f = Fz) + {t | f = Fs t}.\n  Proof.\n    refine (match f with\n      | Fz => _ \n      | Fs s => _ \n      end);\n      [left | right; exists s]; \n      exact eq_refl.\n  Defined.\n  \n\n\n  Lemma cast_fin : forall {n : nat} (f : Fin (S n)), \n    Fin (S (fin_to_nat f)).\n  Proof.\n    refine (fix Fn n :=\n      match n as n' return n = n' -> _ with\n      | 0 => fun Hn f => _ \n      | S n' => fun Hn f => _\n      end eq_refl);\n    subst.\n    + \n      pose proof (fin_inv_S f) as [Ha | (t & Hb)].\n      subst; simpl.\n      exact Fz.\n      pose proof (fin_inv_0 t) as Hf; \n      refine (match Hf with end).\n    + \n      pose proof (fin_inv_S f) as [Ha | (t & Hb)].\n      subst; simpl.\n      exact Fz.\n      pose proof (Fn _ t) as Ft.\n      subst; simpl.\n      exact (Fs Ft).\n  Defined.\n   \n\n  Lemma fin_to_nat_and_nat_to_fin_inv : \n    forall (n : nat) (f : Fin (S n)), \n      nat_to_fin (fin_to_nat f) = @cast_fin _ f.\n  Proof.\n    refine (fix Fn n :=\n      match n as n' return n = n' -> _ with\n      | 0 => fun Hn f => _ \n      | S n' => fun Hn f => _\n      end eq_refl);\n    subst.\n    + \n      pose proof (fin_inv_S f) as [Ha | (t & Hb)].\n      subst; simpl.\n      exact eq_refl.\n      pose proof (fin_inv_0 t) as Hf; \n      refine (match Hf with end).\n    + \n      pose proof (fin_inv_S f) as [Ha | (t & Hb)].\n      subst; simpl.\n      exact eq_refl.\n      pose proof (Fn _ t) as Ft.\n      subst; simpl.\n      rewrite Ft.\n      reflexivity.\n  Defined.\n\n\n\n\n  Lemma FS_inj : \n    forall {n} (x y : Fin n), Fs x = Fs y ->  x = y.\n  Proof.\n    intros ? ? ? Heq.\n    refine\n      match \n        Heq in _ = a \n        return \n        match \n          a as a' in Fin n \n          return \n            match n with \n            | 0 => Prop \n            | S n' => Fin n' -> Prop\n            end \n        with\n        | Fz => fun _ => True \n        | Fs y => fun x' => x' = y\n        end x\n    with\n    | eq_refl => eq_refl \n    end.\n  Defined.\n  \n\n\n\n  Lemma fin_to_nat_lt :\n    forall {n : nat} (f : Fin n), \n    fin_to_nat f < n.\n  Proof.\n    induction n.\n    + intros f.\n      pose proof (fin_inv_0 f) as Hf;\n      refine (match Hf with end).\n    + intros f. \n      pose proof (fin_inv_S f) as [H | (t & H)].\n      subst; simpl.\n      apply Nat.lt_0_succ.\n      subst; simpl.\n      apply Lt.lt_n_S,\n      IHn.\n  Defined.\n\n    \n  (** of_nat p n returns the p{^ th} element of \n      fin n if p < n, othewise a proof that n <= p else *)\n  Definition of_nat : forall (p n : nat), \n    (Fin n) + {m | p = n + m}.\n  Proof.\n    intros p n.\n    revert n p.\n    refine (fix Fn n := \n      match n as n' return n' = n -> \n        forall pt, (Fin n') + {m | pt = n' + m}  with\n      | 0 => fun He p => inr (exist _ p eq_refl)\n      | S n' => fun He p => \n        match p as p' return p = p' -> _ with \n        | 0 => fun Hp => inl Fz\n        | S p' => fun Hp => match Fn n' p' with \n          | inl t => inl (Fs t) \n          | inr (exist _ m e) => inr (exist _ m _)\n          end \n        end eq_refl\n      end eq_refl).\n      rewrite e.\n      reflexivity.\n  Defined.\n\n\n  Definition of_nat_lt : forall {p n : nat}, p < n -> Fin n.\n  Proof.\n    intros ? ?.\n    revert n p.\n    refine \n      (fix Fn n :=\n        match n as n' \n          return n = n' -> \n            forall p, p < n' -> Fin n'\n        with\n        | 0 => fun Hn p Hp => False_rect _ (PeanoNat.Nat.nlt_0_r p Hp)\n        | S n' => fun Hn p => \n            match p as p' \n              return p = p' -> p' < S n' -> Fin (S n') \n            with \n            | 0 => fun Hp Hsp => @Fz _  \n            | S p' => fun Hp Hsp => \n              @Fs _ (Fn n' p' (proj2 (Nat.succ_lt_mono _ _ ) Hsp)) \n            end eq_refl \n        end eq_refl).\n  Defined.\n\n\n\n  \n\n  Fact le_inv n m (H : n <= m) :\n      (exists e : m = n, eq_rect _ _ H _ e = le_n n)\n    \\/ (exists m' (e : m = S m') (H' : n <= m'), \n      eq_rect _ _ H _ e = le_S _ _ H').\n  Proof.\n    revert m H.\n    intros ? [ | m H ].\n    + left. now exists eq_refl.\n    + right. now exists m, eq_refl, H.\n  Qed.\n \n  \n  \n  Lemma le_unique : forall (m n : nat)\n    (p q : m <= n), p = q.\n  Proof.\n    intros ?. \n    refine(fix Fn n p {struct p} :=\n      match p as p' in (_ <= np)\n        return n = np -> forall (q : m <= np), \n          p' = q  \n      with \n      | le_n _ => fun Heq q => \n        match q as q' in (_ <= nq)\n          return forall (pf : nq = m),\n            le_n m = (eq_rect _ _ q' _ pf)\n        with\n        | le_n _ => fun pf => _ \n        | le_S _ nt Hnt => fun pf => _ \n        end  eq_refl\n      | le_S _ nt Hnt => fun Heq q => \n        match q as q' in (_ <= S np)\n          return \n            forall (pf : np = nt),\n              le_S _ nt Hnt =  \n              eq_rect np (fun w => m <= S w) q' nt pf  \n        with \n        | le_n _ => _ \n        | le_S _ nw Hnw => fun pf => _ \n        end eq_refl\n      end eq_refl).\n    + rewrite (uip_nat pf).\n      exact eq_refl.\n    + abstract nia.\n    + clear Fn.\n      destruct m.\n      ++ exact idProp.\n      ++ abstract nia.\n    + subst; simpl.\n      f_equal.\n      apply Fn.\n  Qed.\n  \n\n\n  \n  Lemma le_pair_induction:\n    forall (n : nat)\n    (P : forall m : nat, n <= m -> n <= m -> Prop),\n    P n (le_n n) (le_n n) ->\n    (forall (m : nat) (Ha Hb : n <= m), P m Ha Hb ->\n      P (S m) (le_S n m Ha) (le_S n m Hb)) ->\n    forall (mt : nat) (Hna Hnb : n <= mt), P mt Hna Hnb.\n  Proof.\n    intros ? ? Pa Pb.\n    refine(\n      fix Fn mt Hna {struct Hna} :=\n      match Hna as Hna' in (_ <= mtp) \n        return \n          mt = mtp -> \n          forall Hnb, P mtp Hna' Hnb\n      with \n      | le_n _ => fun _ Hnb => \n        match Hnb as Hnb' in (_ <= nt) \n          return \n            forall (pf : nt = n),\n            P n (le_n n) (eq_rect nt _ Hnb' n pf)\n        with \n        | le_n _ =>  fun pf => _ \n        | le_S _ nt Hnt => fun pf => _  \n        end eq_refl\n      | le_S _ nt Hnt => fun Heq Hnb => \n        match Hnb as Hnb' in (_ <= S np)\n          return \n            forall (pf : np = nt),\n            P (S nt) (le_S n nt Hnt) \n              (eq_rect np (fun w => n <= S w) Hnb' nt pf)\n        with\n        | le_n _ => _ \n        | le_S _ nw Hnw => fun pf => _ \n        end eq_refl\n      end eq_refl).\n    + rewrite (uip_nat pf).\n      exact Pa.\n    + abstract nia.\n    + clear Fn.\n      destruct n. \n      ++ exact idProp.\n      ++ abstract nia.  \n    + subst.\n      apply Pb, Fn.\n  Qed.\n\n  Lemma le_unique_using_ind : \n    forall {m n : nat}\n    (p q : m <= n), p = q.\n  Proof.\n    intros ? ? ? ?.\n    apply (le_pair_induction m\n      (fun \n        (n : nat) \n        (a : m <= n) \n        (b : m <= n) => a = b)).\n    + exact eq_refl.\n    + intros ? ? ? He;\n      subst; reflexivity.\n  Qed.\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/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7729177378167266}}
{"text": "Require Export Poly_J.\n\nCheck (2 + 2 = 4).\nCheck (ble_nat 3 2 = false).\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\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.\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.\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 d1 d2 d3 ok b0 b1.\n  apply okd_before with (d2 := d2).\n  apply okd_before with (d2 := d3).\n  apply ok.\n  apply b1.\n  apply b0. Qed.\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 \"0\". reflexivity.\n  Case \"S n\". intros n H. simpl. apply eq_remove_S. apply H. Qed.\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.\nCheck natlist1_ind.\n\nInductive ExSet : Type :=\n| con1 : bool -> ExSet\n| con2 : nat -> ExSet -> ExSet.\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(*\n  tree_ind :\n    forall (X : Type) (P : tree X -> Prop),\n      (forall x : X, P (leaf X x)) ->\n      (forall t : tree X, P t -> forall t0 : tree X, P t0 -> P (node X t t0)) ->\n      forall t : tree X, P t\n *)\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   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\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) -> nat -> 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.\nCheck foo'_ind.\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 f1 : foo' X, P f1\n *)\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\n    unfold P_m0r. simpl. intros n' IHn'.\n    apply IHn'.  Qed.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\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\nTheorem ev_plus4' : forall n,\n  ev n -> ev (4 + n).\nProof.\n  simpl.\n  intros n Hev.\n  apply ev_SS. apply ev_SS. apply Hev. Qed.\n\nDefinition ev_plus4 : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) (Hev : ev n) => ev_SS (S (S n)) (ev_SS n Hev).\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". simpl. apply ev_0.\n  Case \"n = S n'\".\n    simpl. apply ev_SS. apply IHn'. Qed.\n\nDefinition double_even' : forall n, ev (double n) :=\n  nat_ind\n    (fun (n : nat) => ev (double n))\n    ev_0\n    (fun (n' : nat) (IHn' : ev (double n')) => ev_SS (double n') IHn').\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\". simpl.\n  apply ev_0.\n  Case \"E = ev_SS\". simpl. apply E'. Qed.\n\nDefinition ev_minus2' : forall (n : nat), ev n -> ev (pred (pred n)) :=\n  ev_ind\n    (fun (n' : nat) => ev (pred (pred n')))\n    ev_0\n    (fun (n'' : nat) (E' : ev n'') =>  (fun (E'' : ev (pred (pred n''))) => E')).\n\nTheorem ev_minus2'' : forall n,\n    ev n -> ev (pred (pred n)).\nProof.\n  intros n E. destruct n as [| n'].\n  Case \"n = 0\". simpl. apply E.\n  Case \"n = S n'\". inversion E. simpl. apply H0. 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\". reflexivity.\n  Case \"E = ev_SS n' E'\".\n    unfold even. apply IHE'. Qed.\n\nTheorem ev_even_n : forall n,\n    ev n -> even n.\nProof.\n  intros n E. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    inversion E. unfold even.\n  Admitted.\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros n m En Em. induction En as [| n' En'].\n  Case \"En = ev_0\".\n    simpl. apply Em.\n  Case \"En = ev_SS n' En'\".\n    simpl. apply ev_SS. apply IHEn'. Qed.\n\nDefinition ev_sum' : forall n m, ev n -> ev m -> ev (n + m) :=\n  fun (n m : nat) (En : ev n) (Em : ev m) =>\n    (ev_ind\n      (fun (n' : nat) => ev (n' + m))\n      Em\n      (fun (n' : nat) (En' : ev n') (Enm : ev (n' + m)) => ev_SS (n' + m) Enm))\n      n En.\n\nTheorem SSev_ev_firsttry : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n\nAdmitted.\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\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. inversion E' as [| n'' E'']. apply E''. Qed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros E. inversion E. inversion H0. inversion H2. Qed.\n\nTheorem ev_minus2''': 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'. Qed.\n\nTheorem ev_ev_even : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m Enm E.\n  generalize dependent Enm.\n  generalize dependent m.\n  induction E as [| n' E'].\n  Case \"ev n = ev_0\".\n    intros m Enm. apply Enm.\n  Case \"ev n = ev_SS n' E'\".\n    simpl. intros m Em. inversion Em as [| nm Em'].\n    apply IHE'. apply Em'. Qed.\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 Enm Enp.\n  apply (ev_ev_even (n + n) (m + p)).\n  rewrite <- (plus_assoc' n n (m + p)).\n  rewrite -> (plus_assoc' n m p).\n  rewrite -> (plus_comm (n + m) p).\n  rewrite -> (plus_assoc' n p (n + m)).\n  apply (ev_sum (n + p) (n + m)).\n  apply Enp.\n  apply Enm.\n  rewrite <- double_plus.\n  apply double_even. Qed.\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 assert\". reflexivity.\n  rewrite -> H12.\n  apply MyProp2.\n  assert (8 = 4 + 4) as H8.\n    Case \"Proof of assert\". reflexivity.\n  rewrite -> H8.\n  apply MyProp2.\n  apply MyProp1. Qed.\n\nTheorem MyProp_0 : MyProp 0.\nProof.\n  apply MyProp3.\n  simpl.\n  apply MyProp3.\n  simpl.\n  apply MyProp1. Qed.\n\nTheorem MyProp_plustwo : forall n:nat, MyProp n -> MyProp (S (S n)).\nProof.\n  intros n E.\n  induction E.\n  Case \"E = MyProp1\".\n    assert (6 = 4 + 2) as H6.\n      SCase \"Proof of assert\". reflexivity.\n    rewrite -> H6.\n    apply MyProp2.\n    apply MyProp3.\n    simpl.\n    apply MyProp1.\n  Case \"E = MyProp2\".\n    apply MyProp2. apply IHE.\n  Case \"E = MyProp3\".\n    apply E. Qed.\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 M.\n  induction M.\n    Case \"M = MyProp1\". apply ev_SS. apply ev_SS. apply ev_0.\n    Case \"M = MyProp2\". apply ev_SS. apply ev_SS. apply IHM.\n    Case \"M = MyProp2\". apply SSev_even. apply IHM. Qed.\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 MyProp_ind.\n\nTheorem ev_MyProp' : forall n:nat,\n  MyProp n -> ev n.\nProof.\n  apply MyProp_ind.\n  Case \"MyProp1\". apply ev_SS. apply ev_SS. apply ev_0.\n  Case \"MyProp2\". intros n E IHE. apply ev_SS. apply ev_SS. apply IHE.\n  Case \"MyProp3\". intros n E IHE. apply SSev_even. apply IHE. Qed.\n\nDefinition MyProp_ev' : forall n:nat, ev n -> MyProp n :=\n  ev_ind (fun (n : nat) => MyProp n)\n         MyProp_0\n         (fun (n' : nat) (E' : ev n') (M' : MyProp n') => MyProp_plustwo n' M').\n\nDefinition ev_MyProp'' : forall n : nat, MyProp n -> ev n :=\n  MyProp_ind\n    (fun (n' : nat) => ev n')\n    (ev_SS _ (ev_SS _ ev_0))\n    (fun (n' : nat) (M : MyProp n') (E : ev n') => ev_SS _ (ev_SS _ E))\n    (fun (n' : nat) (M : MyProp (2 + n')) (E : ev (2 + n')) => SSev_even n' E).\n\nModule P.\n  Inductive 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).\nEnd P.\n\nInductive pal {X : Type} : list X -> Prop :=\n| pal_rev (l : list X) : l = rev l -> pal l.\n\nTheorem pal_append_rev : forall (X : Type) (l : list X),\n    pal (l ++ rev l).\nProof.\n  intros X l.\n  apply pal_rev.\n  induction l as [| x l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = x :: l'\".\n    simpl.\n    rewrite <- snoc_with_append.\n    rewrite -> rev_snoc.\n    rewrite <- IHl'.\n    simpl. reflexivity. Qed.\n\nTheorem pal_id_rev : forall (X : Type) (l : list X),\n    pal l -> l = rev l.\nProof.\n  intros X l P.\n  induction P. apply H. Qed.\n\nTheorem id_rev_pal : forall (X : Type) (l : list X),\n    l = rev l -> pal l.\nProof.\n  intros X l eq. apply pal_rev. apply eq. Qed.\n\nInductive subseq : list nat -> list nat -> Prop :=\n| subseq_0 : forall (l : list nat), subseq [] l\n| subseq_tail : forall (x : nat) (l xs : list nat), subseq l xs -> subseq (x :: l) (x :: xs)\n| subseq_all : forall (x : nat) ( l xs : list nat), subseq l xs -> subseq l (x :: xs).\n\nTheorem subseq_refl : forall l : list nat, subseq l l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\". apply subseq_0.\n  Case \"l = n :: l'\".\n    apply subseq_tail. apply IHl'. Qed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n    subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros l1 l2 l3 s.\n  induction s.\n  apply subseq_0.\n  simpl. apply subseq_tail. apply IHs.\n  simpl. apply subseq_all. apply IHs. Qed.\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.\n  generalize dependent l2.\n  generalize dependent l1.\n  induction l3 as [| n3 l3'].\n  Case \"l3 = []\".\n    intros l1 l2 s1 s2. inversion s2.\n    rewrite <- H in s1. inversion s1. apply subseq_0.\n  Case \"l3 = n3 :: l3'\".\n    intros l1 l2 s1 s2. inversion s2.\n      SCase \"subseq_0\".\n        rewrite <- H in s1. inversion s1. apply subseq_0.\n      SCase \"subseq_tail\".\n        subst n3 l2 l3'. inversion s1.\n        SSCase \"subseq_0\".\n          apply subseq_0.\n        SSCase \"subseq_tail\".\n          subst x l l1. apply subseq_tail.\n          apply (IHl3' l0 xs0).\n          apply H2.\n          apply H1.\n        SSCase \"subseq_all\".\n          subst l x l1. apply subseq_all. apply (IHl3' l0 xs0).\n          apply H2.\n          apply H1.\n      SCase \"subseq_all\".\n        subst l3' n3 l2. apply subseq_all. apply (IHl3' l1 l).\n        apply s1.\n        apply H1. Qed.\n", "meta": {"author": "wat-aro", "repo": "SF", "sha": "8200fe72b8eb412fbd622a368cab478b575d1f34", "save_path": "github-repos/coq/wat-aro-SF", "path": "github-repos/coq/wat-aro-SF/SF-8200fe72b8eb412fbd622a368cab478b575d1f34/Prop_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.772912827997068}}
{"text": "(* Computation of nth root (code from Yves.Bertot@inria.fr)                   *)\nFrom mathcomp Require Import all_ssreflect.\n\n(******************************************************************************)\n(*                                                                            *)\n(*   rootn n i      ==  computes the integer n^th root of i                   *)\n(*   is_rootn n i   ==  check if i is of n^th root of a number                *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFixpoint rootn_rec k r n :=\n  if r == 0 then 0 else\n  if n is n1.+1 then\n  let v := (rootn_rec k (r %/ (2 ^ k)) n1).*2 in\n  if v.+1 ^ k <= r then v.+1 else v\n  else 0.\n\nDefinition rootn k n :=\n  if k == 0 then 0 else rootn_rec k n n.\n\nLemma rootn_rec_bound k r n : \n  0 < k -> r <= n -> (rootn_rec k r n) ^ k  <= r < (rootn_rec k r n ).+1 ^ k.\nProof.\ncase: k => // k _.\nhave F : 1 < 2 ^ k.+1 by rewrite -{1}[1](exp1n k.+1) ltn_exp2r.\nelim: n r => [[] //=|n IH [|[|r]] rLn /=]; rewrite ?(exp0n, exp1n) //.\n  rewrite divn_small //=.\n  have -> : rootn_rec k.+1 0 n = 0 by case: (n).\n  by rewrite exp1n /= exp1n.\nset x := _ %/ _; set u := rootn_rec _ _ _.\nhave /IH : x <= n.\n  apply: leq_trans (rLn : _ < n).\n  have /mulnK H : 0 < 2 ^ k.+1 by rewrite expn_gt0.\n  rewrite -[r.+1]H leq_div2r //.\n  by rewrite -{1}[r.+1]muln1 ltn_mul2l.\nrewrite -/u => /andP[uLx xLu].  \ncase: (leqP (u.*2.+1 ^ k.+1 ) r.+2) => ->; rewrite !(andbT, andTb).\n  rewrite -doubleS -muln2 expnMn.\n  rewrite (divn_eq r.+2 (2 ^ k.+1)) -/x.\n  apply: leq_trans (_ : x.+1 * 2 ^ k.+1 <= _).\n    by rewrite mulSn addnC ltn_add2r // ltn_mod ?expn_gt0.\n  by rewrite leq_mul2r // expn_eq0.\nrewrite -muln2 expnMn (divn_eq r.+2 (2 ^ k.+1)) -/x.\napply: leq_trans (leq_addr _ _).\nby rewrite leq_mul2r // expn_eq0.\nQed.\n\nLemma root0n i : rootn 0 i = 0.\nProof. by rewrite /rootn eqxx. Qed.\n\nLemma rootn_bound n i : 0 < n -> rootn n i ^ n <= i < (rootn n i).+1 ^ n.\nProof. by case: n => // n  _; apply: rootn_rec_bound. Qed.\n\nLemma rootn0 n : rootn n 0 = 0.\nProof. by case: n. Qed.\n\nDefinition is_rootn n i := (i == rootn n i ^ n).\n\nLemma is_rootnE n i : is_rootn n i = (i == rootn n i ^ n).\nProof. by []. Qed.\n\nLemma leq_rootn n x y : 0 < n -> x <= y -> rootn n x <= rootn n y.\nProof.\nmove=> n_gt0 xLy.\nrewrite -ltnS -(ltn_exp2r _ _ n_gt0).\nhave /andP[rLx _] := rootn_bound x n_gt0.\nhave /andP[_ yLr] := rootn_bound y n_gt0.\nby apply: leq_ltn_trans rLx (leq_ltn_trans _ yLr).\nQed.\n\nLemma rootnE n x y :\n  0 < n -> y ^ n <= x < y.+1 ^ n -> rootn n x = y.\nProof.\nmove=> n_gt0 /andP[ynLx xLySn].\nhave /andP[rLx xLrS] := rootn_bound x n_gt0.\napply/eqP; rewrite eqn_leq.\nrewrite -ltnS -(ltn_exp2r _ _ n_gt0) (leq_ltn_trans rLx) //.\nby rewrite -ltnS -(ltn_exp2r _ _ n_gt0) (leq_ltn_trans ynLx).\nQed.\n\nLemma expnK n x : 0 < n -> rootn n (x ^ n) = x.\nProof.\nby move=> n_gt0; apply: rootnE; rewrite // leqnn ltn_exp2r ?ltnSn.\nQed.\n\nLemma rootn_leq n x y :\n  0 < n -> x ^ n <= y -> x <= rootn n y.\nProof. by move=> n_gt0 xnLy; rewrite -(expnK x n_gt0) leq_rootn. Qed.\n\nLemma rootn_ltn n x y :\n  0 < n -> x < y.+1 ^ n -> rootn n x <= y.\nProof.\nmove=> n_gt0; rewrite ltnNge [in X in _ -> X]leqNgt.\napply: contra => yLrx.\nhave /andP[rLx _] := rootn_bound x n_gt0.\nby apply: leq_trans rLx; rewrite leq_exp2r.\nQed.\n\nDefinition sqrtn := rootn 2.\n\nLemma sqrtn_bound n : (sqrtn n) ^ 2 <= n < ((sqrtn n).+1) ^ 2.\nProof. by apply: rootn_bound. Qed.\n\nLemma sqrtnE n x : x ^ 2 <= n < x.+1^2 -> sqrtn n = x.\nProof. by apply: rootnE. Qed.\n\nLemma leq_sqrtn m n : m <= n -> sqrtn m <= sqrtn n.\nProof. by apply: leq_rootn. Qed.\n\nLemma sqrnK n : sqrtn (n ^ 2) = n.\nProof. by apply: expnK. Qed.\n\nLemma sqrtn_gt0 n : (0 < sqrtn n) = (0 < n).\nProof.\nby case: n => [|n]; rewrite // -[1%N]/(sqrtn 1) // leq_sqrtn.\nQed.\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/rootn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8652240756264639, "lm_q1q2_score": 0.7729128051017994}}
{"text": "Require Export P01.\n\n(** **** Problem #2: 2 stars (blt_nat) *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Use [Fixpoint] to define it. **)\n\nFixpoint blt_nat(n m : nat) : bool :=\n  match n with\n  | O => match m with\n       | O => false\n       | S m' => true\n        end\n  | S n' => match m with\n          | O => false\n          | S m' => blt_nat n' m'\n          end\nend.\n\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n", "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/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.7728990346468205}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(*** [reflect] predicate *)\n\nSection MotivationalExample.\n\nVariable T : Type.\n\nVariable p : pred T.\nPrint pred.\nCheck p : T -> bool.\n\nLemma all_filter (s : seq T) :\n  all p s -> filter p s = s.\nProof.\n\n(* Notation \"[ 'seq' x <- s | C ]\" := (filter (fun x => C) s) *)\n\nPrint filter.\nPrint all.\n\nelim: s => //= x s IHs.\n\nrewrite /is_true.\nmove=> /andP.\n(* Set Printing Coercions. *)\nrewrite /is_true.\nmove=> [].\nmove=> ->.\nmove/IHs.\nmove=>->.\ndone.\n\nRestart.\n\nby elim: s => //= x s IHs /andP[-> /IHs->].\nQed.\n\nEnd MotivationalExample.\n\n\n(** How does [andP] from above work? *)\n\nAbout andP.\n\nPrint reflect.\nPrint Bool.reflect.\n\n(**\n    Inductive reflect (P : Prop) : bool -> Set :=\n    | ReflectT : P -> reflect P true\n    | ReflectF : ~ P -> reflect P false\n *)\n\nSearch _ reflect.\n\n(** First, let us show that [P] if and only if [b = true]\n    as two separate lemmas\n  *)\n\nLemma introT_my (P : Prop) (b : bool) :\n  reflect P b -> P -> b.\nProof.\nSet Printing Coercions.\nrewrite /is_true.\nUnset Printing Coercions.\ncase.\n- move=> _ _. done.\nmove=> np. move/np. case.\nQed.\n\nLemma elimT_my (P : Prop) (b : bool) :\n  reflect P b -> b -> P.\nProof.\ncase.\n- move=> p _. exact: p.\nmove=> _. done.\nQed.\n\n  (* reflect P b -> (b <-> P). *)\n\n(** Essentially, a [reflect] predicate connects\n    a _decidable_ proposition to its decision procedure.\n *)\nLemma reflect_lem P b :\n  reflect P b -> P \\/ ~ P.\nProof.\nby case=> H; [left | right].\nQed.\n\n(** Lets look at some standard [reflect] predicates *)\n\nLemma andP_my (b c : bool) :\n  reflect (b /\\ c) (b && c).\nProof.\nby case: b; case: c; constructor=> //; case.\nQed.\n\n\nLemma orP_my (b c : bool) :\n  reflect (b \\/ c) (b || c).\nProof. (* exercise *) Admitted.\n\nLemma nandP_my b c : reflect (~~ b \\/ ~~ c) (~~ (b && c)).\nProof. by case: b; case: c; constructor; auto; case. Qed.\n\n\n\n(** * Using reflection views in intro patterns *)\n\nLemma special_support_for_reflect_predicates b c :\n  b && c -> b /\\ c.\nProof.\nmove/andP.\nShow Proof.\n\n(**\nSSReflect implicitly inserts the so-called view hints to\nfacilitate boolean reflection. In this case it's [elimTF] view hint.\n\nHere is the syntax to do that (see ssrbool.v file):\nHint View for move/ elimTF|3 elimNTF|3 elimTFn|3 introT|2 introTn|2 introN|2.\n\nThe optional natural number is the number of implicit arguments\nto be considered for the declared hint view lemma.\n\nThe ssrbool.v module already declares a numbers of view hints,\nso adding new ones should be justified. For instance, one might need to do it\nif one defines a new logical connective.\n *)\n\n(* Set Printing All. *)\n(* Show Proof. *)\n\nAbout introTF.\nAbout elimTF.\nAbout elimF.\n\nRestart.\n\nmove=> Hb.\nCheck @elimTF (b /\\ c) (b && c) true (@andP b c) Hb.\nmove: Hb.\nmove/(@elimTF (b /\\ c) (b && c) true (@andP b c)).\n\nexact: id.\nQed.\n\n\n(** Reflection views generally work in both directions *)\nLemma special_support_for_reflect_predicates' (b c : bool) :\n  b /\\ c -> b && c.\nProof.\nmove/andP.\nShow Proof.\nAbout introT.  (** [introT] view hint gets implicitly inserted *)\nexact: id.\nQed.\n\n\n\n(** * Switching views at the goal *)\n\nLemma special_support_for_reflect_predicates'' (b c : bool) :\n  b /\\ c -> b && c.\nProof.\nmove=> ab.\napply/andP.  (** [apply/] syntax *)\nShow Proof.  (** [introTF] view hint gets inserted *)\nAbout introTF.\ndone.\nQed.\n\n\n\n(** Specification for [eqn] -- decision procedure for equality on [nat]s *)\nLemma eqnP_my (n m : nat) : reflect (n = m) (eqn n m).\nProof.\nelim: n m=> [|n IHn] [|m]; try constructor=> //.\n\nmove=> /=.\n\n(** Need to convert a [reflect]-based propositions into biimplications *)\nSearch reflect -seq -\"or\" -\"and\" -\"mem\" -negb -minn.\n\nCheck iffP (IHn m).\n(**\nHow the conclusion of [iffP (IHn m)] matches with the goal:\n\n                                         reflect (n.+1 = m.+1) (eqn n m)\n       (n = m -> ?Q) -> (?Q -> n = m) -> reflect ?Q            (eqn n m)\n\nCoq infers [?Q] existential variable to be [n.+1 = m.+1]\n*)\nby apply: (iffP (IHn _)) => [-> | /succn_inj].\n\nRestart.\n\napply: (iffP idP).   (** [idP] -- the trivial reflection view *)\n- by elim: n m => [|n IHn] [|m] //= /IHn->.\n- move=> ->. by elim: m.\nQed.\n\n\nLemma silly_example_iffP_andP (b c : bool) :\n  reflect (b /\\ c) (b && c).\nProof.\napply: (iffP idP).\nUndo.\nCheck (iffP andP).\napply: (iffP andP).\ndone.\ndone.\nQed.\n\n\n(** A better example of using [iffP] with a non-[idP] argument *)\nLemma nseqP (T : eqType) n (x y : T) :\n  reflect (y = x /\\ n > 0) (y \\in nseq n x).\nProof.\nrewrite mem_nseq andbC.\n(* apply: (iffP idP); move/andP. *)\napply: (iffP andP).\n(* reflect (x = y) (x == y) *)\ncase. move/eqP. move=>->. done.\ncase=>->. done.\n\nRestart.\n\nby rewrite mem_nseq andbC; apply: (iffP andP) => -[/eqP].\nQed.\n\n\n\n(** * Rewriting with [reflect] predicates *)\n\n\nAbout maxn_idPl.\n\nLemma leq_max m n1 n2 :\n  (m <= maxn n1 n2) = (m <= n1) || (m <= n2).\nProof.\n(* move: (leq_total n2 n1). *)\n(* case. *)\n(* rewrite /is_true. *)\n(* Print eq. *)\n(* Set Printing All. *)\n(*   move/orP. case=> [le_n21 | le_n12]. *)\ncase/orP: (leq_total n2 n1) => [le_n21 | le_n12].\n\nCheck (@maxn_idPl n1 n2).\nrewrite (@maxn_idPl n1 n2 le_n21).\n\n(** Why does this work?\n    [maxn_idPl] is _not_ a function but behaves like one here *)\n\nCheck (maxn_idPl le_n21).  (** OK, this is an ordinary equation,\n                               no wonder [rewrite] works. *)\n\nSet Printing Coercions.\nCheck (maxn_idPl le_n21).   (** [elimT] get implicitly inserted *)\nUnset Printing Coercions.\n\nAbout elimT.\n\n(** [elimT] is a coercion from [reflect] to [Funclass],\n    This means it gets inserted when one uses a reflect view as a function.\n  *)\n\n(** Essentially we invoke the following tactic: *)\n\nUndo.\nrewrite (elimT maxn_idPl le_n21).\nAbort.\n\n\n(** * An example of a specification for a [seq] function *)\n\n(** [all] specification *)\nAbout allP.\n(**\n    forall (T : eqType) (a : pred T) (s : seq T),\n    reflect {in s, forall x : T, a x} (all a s)\n*)\n\n(** Check out some other specs in the [seq] module! *)\nSearch _ reflect in seq.\n\n\n\n\n(*** Specs as rewrite rules *)\n\nExample for_ltngtP m n :\n  (m <= n) && (n <= m) ->\n  (m == n) || (m > n) || (m + n == 0).\nProof.\nby case: ltngtP.\n\nRestart.\n\ncase: ltngtP.\ndone.\ndone.\nmove=>/=.\nAbort.\n\n\nModule Trichotomy.\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(** One more example *)\nLemma maxnC : commutative maxn.\nProof. by move=> m n; rewrite /maxn; case: ltngtP. Qed.\n\nEnd Trichotomy.\n\n\n\n\n\n\n(*** Coercions summary *)\n\n\n(** * [is_true] coercion *)\n\n(** We have already been using [is_true] coercion regularly.\n    It's defined in ssrbool.v as follows:\n\n    Coercion is_true : bool >-> Sortclass.\n *)\n\n(** E.g. [is_true] makes the following typecheck *)\nCheck (erefl true) : true.\n\n\n\n(** * [elimT] coercion *)\n\n(**  Allow the direct application of a reflection lemma\n     to a boolean assertion.\n\n    Coercion elimT : reflect >-> Funclass.\n *)\n\nSection ElimT_Example.\n\nVariables b c : bool.\nHypothesis H : b || c.\n\nCheck orP H.\nSet Printing Coercions.\nCheck orP H.\nUnset Printing Coercions.\n\nEnd ElimT_Example.\n\n\n\n(** * [nat_of_bool] coercion *)\n\nAbout nat_of_bool.\n\nAbout leq_b1.\nAbout mulnb.\n\nAbout count_nseq.\n\n(** You can learn more using the following search query: *)\nSearch _ nat_of_bool.\n\n\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/lecture05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8807970873650403, "lm_q1q2_score": 0.7728789958222885}}
{"text": "Require Export Basics.\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.\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\nEval simpl in (fst (3,4)).\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 : 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.\n  intros p. destruct p as (n,m). simpl. reflexivity. Qed.\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\nDefinition l_123' := 1 :: (2 :: (3 :: nil)).\nDefinition l_123'' := 1 :: 2 :: 3 :: nil.\nDefinition l_123''' := [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_tail:            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 => if beq_nat h O then nonzeros t else h :: (nonzeros t)\n  end.\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t =>\n    match (oddb h) with\n    | true  => h :: (oddmembers t)\n    | false => oddmembers t\n    end\n  end.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. reflexivity. Qed.\n\nFixpoint 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\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\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, nil => nil\n  | nil, _   => l2\n  | _  , nil => l1\n  | h1 :: t1, h2 :: t2 =>\n    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.\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  => 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. simpl. reflexivity. Qed.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition sum : bag -> bag -> bag := app.\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.\n\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match (count v s) with\n  | O   => false\n  | S _ => true\n  end.\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint 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 => 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. simpl. reflexivity. Qed.\nExample test_remove_one2: count 5 (remove_one 5 [2,1,4,1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_one4: count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t =>\n    match (beq_nat v h) with\n    | true  => remove_all v t\n    | false => h :: (remove_all v t)\n    end\n  end.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all2:          count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all3:          count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_remove_all4:          count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1, s2 with\n  | nil, nil  => true\n  | _,   nil  => false\n  | nil, _    => true\n  | h1::t1, _::t2 =>\n    match (count h1 s2) with\n    | O   => false\n    | S _ => subset t1 (remove_one h1 s2)\n    end\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 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 (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = cons n l'\".\n    simpl. reflexivity.\n  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    simpl. reflexivity.\n  Case \"l1 = n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\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 = l1'\".\n    simpl. reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. 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\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 l.\n  induction l as [| n' l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = cons n' l'\".\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n    length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n :: l'\".\n    simpl. rewrite -> length_snoc. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_nil_end : forall l : natlist,\n    l ++ [] = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n :: l'\".\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_snoc : forall l : natlist, forall n : nat,\n          rev (snoc l n) = n :: rev l.\nProof.\n  intros l n. induction l as [| n' l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n' :: l'\".\n    simpl. rewrite -> IHl'. simpl. reflexivity.\nQed.\n  \nTheorem rev_involutive : forall l : natlist,\n    rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n :: l'\".\n    simpl. rewrite -> rev_snoc. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem snoc_rev : forall l1 l2 : natlist, forall n : nat,\n          snoc (l1 ++ rev l2) n = l1 ++ snoc (rev l2) n.\nProof.\n  intros l1 l2 n. induction l1 as [|n' l1'].\n  Case \"l1 = nil\".\n    simpl. reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n    rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. rewrite -> IHl1'.\n    rewrite -> snoc_rev. 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  induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    simpl. rewrite -> app_ass. reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. rewrite <- app_ass. rewrite <- app_ass. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n    snoc l n = l ++ [n].\nProof.\n  intros l n.\n  induction l as [| n' l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n' l'\".\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_nil : forall l : natlist,\n    l ++ [] = l.\nProof.\n  intros l. induction l as [|n l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = n :: l'\".\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(*わかりません(絶望)*)\n(*三章でif文のdestructを知って使ったらこれだよ☆*)\n(*恐らくnonzerosの実装に問題があるためこのようにせざるを得ないのだと思います*)\nLemma nonzeros_length : forall l1 l2 : natlist,\n    nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1'].\n  Case \"l1 = []\". reflexivity.\n  Case \"l1 = n :: l1'\".\n    simpl. destruct (beq_nat n 0).\n    SCase \"beq_nat n 0 = true\". rewrite -> IHl1'. reflexivity.\n    SCase \"beq_nat n 0 = false\".\n      rewrite -> IHl1'. simpl. reflexivity.\nQed.\n\nEnd NatList.", "meta": {"author": "MountainSeal", "repo": "coq_study", "sha": "8f5c27fa4f5ed0775d60c96210d60a5ece100327", "save_path": "github-repos/coq/MountainSeal-coq_study", "path": "github-repos/coq/MountainSeal-coq_study/coq_study-8f5c27fa4f5ed0775d60c96210d60a5ece100327/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8807970795424087, "lm_q1q2_score": 0.7728789917802602}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nFixpoint bgcdn (k m n : nat) := \n  if m == 0 then n else\n  if m == 1 then 1 else\n  if n == 0 then m else\n  if n == 1 then 1 else\n  if k is k1.+1 then\n    if odd m then \n      if odd n then\n        let m1 := maxn m n in\n        let n1 := minn m n in\n        bgcdn k1 (m1 - n1)./2 n1\n      else bgcdn k1 m n./2\n    else \n      if odd n then bgcdn k1 m./2 n\n      else (bgcdn k1 m./2 n./2).*2    \n  else 1.\n\nLemma bgcdnC k m n : bgcdn k m n = bgcdn k n m.\nProof.\nelim: k m n => [|k IH] [|[|m]] [|[|n]] //=.\ncase: odd; case: odd => //=.\n  by rewrite maxnC minnC.\nby rewrite IH.\nQed.\n\nLemma bgcdnE k1 k2 m n : \n  m < 2 ^ k1 -> n < 2 ^ k2 -> bgcdn (k1 + k2) m n = gcdn m n.\nProof.\nelim: {k1 k2}_.+1 {-2}k1 {-2} k2 (ltnSn (k1 + k2)) m n =>\n         // k IH [|k1] [|k2] Hk // [|[|m]] [|[|n]] //= Hm Hn.\n- by rewrite gcd1n.\n- by rewrite gcdn1.\nmove: (odd_double_half m) (odd_double_half n).\nhave [Om|Em] := boolP (odd _); have [On|En] := boolP (odd _);\n     rewrite ?add0n ?add1n => //= mE nE.\n- rewrite /maxn /minn; case: leqP => [nLm|mLn].\n    have mDnE :  m.+2 - n.+2 = (m.+2 - n.+2)./2.*2.\n      by rewrite -{1}(odd_double_half (_ - _)) oddB //= Om On.\n    rewrite IH //.\n      rewrite  -{2}[m.+2](subnK nLm) [RHS]gcdnC [RHS]gcdnDr [RHS]gcdnC.\n      rewrite {2}mDnE -muln2 [LHS]gcdnC [RHS]gcdnC Gauss_gcdl //.\n      by rewrite /coprime -gcdn_modl modn2 /= On gcd1n.\n    rewrite -ltn_double -mDnE -mul2n -expnS (leq_trans _ Hm) //.\n    by rewrite (leq_trans _ (_ : m.+2 < _)) // ltnS leq_subr.\n  have m1Ln : m.+1 < n.+2 by apply: leq_trans mLn.\n  have nDmE :  n.+2 - m.+2 = (n.+2 - m.+2)./2.*2.\n    by rewrite -{1}(odd_double_half (_ - _)) oddB //= Om On.\n  rewrite [(_ + _)%Nrec]addnC addSnnS IH //; last first.\n  - rewrite -ltn_double -nDmE -mul2n -expnS (leq_trans _ Hn) //.\n    by rewrite (leq_trans _ (_ : n.+2 < _)) // ltnS leq_subr.\n  - by rewrite addnC addSnnS.\n  rewrite  -{2}[n.+2](subnK m1Ln) gcdnDr.\n  rewrite {2}nDmE -muln2 Gauss_gcdl 1?gcdnC //.\n  by rewrite /coprime -gcdn_modl modn2 /= Om gcd1n.\n- rewrite -[(_ + _)%Nrec]addSnnS IH //; last 2 first.\n  - by rewrite addSnnS.\n  - rewrite -nE expnS mul2n in Hn.\n    by rewrite (ltn_double _.+1) in Hn.\n  rewrite -{2}nE -doubleS -muln2 Gauss_gcdl //.\n  by rewrite /coprime -gcdn_modl modn2 /= Om gcd1n.\n- rewrite IH //; last first.\n    rewrite -mE expnS mul2n in Hm.\n    by rewrite (ltn_double _.+1) in Hm.\n  rewrite -{2}mE.\n  rewrite -doubleS -muln2 [LHS]gcdnC [RHS]gcdnC Gauss_gcdl //.\n  by rewrite /coprime -gcdn_modl modn2 /= On gcd1n.\nrewrite IH //; last 2 first.\n- by rewrite -mE -doubleS expnS mul2n ltn_double in Hm.\n- rewrite -nE -doubleS expnS mul2n ltn_double in Hn.\n  by rewrite (leq_trans Hn) // leq_exp2l.\nrewrite -{2}mE -{2}nE -!doubleS -!muln2.\nby rewrite  muln_gcdl.\nQed.", "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/bgcdn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7727865501536421}}
{"text": "Require Export Reals.\nRequire Export TopologicalSpaces.\nRequire Export NeighborhoodBases.\nRequire Import RationalsInReals.\nRequire Export EnsemblesSpec.\n\nOpen Scope R_scope.\n\nSection metric.\n\nVariable X:Type.\nVariable d:X->X->R.\n\nRecord metric : Prop := {\n  metric_nonneg: forall x y:X, d x y >= 0;\n  metric_sym: forall x y:X, d x y = d y x;\n  triangle_inequality: forall x y z:X, d x z <= d x y + d y z;\n  metric_zero: forall x:X, d x x = 0;\n  metric_strict: forall x y:X, d x y = 0 -> x = y\n}.\n\nEnd metric.\n\nImplicit Arguments metric [[X]].\n\nSection metric_topology.\n\nVariable X:Type.\nVariable d:X->X->R.\nHypothesis d_is_metric: metric d.\n\nDefinition open_ball (x0:X) (r:R) : Ensemble X :=\n  [ x:X | d x0 x < r ].\n\nInductive metric_topology_neighborhood_basis (x:X) : Family X :=\n  | intro_open_ball: forall r:R, r > 0 ->\n    In (metric_topology_neighborhood_basis x) (open_ball x r).\n\nDefinition MetricTopology : TopologicalSpace.\nrefine (Build_TopologicalSpace_from_open_neighborhood_bases\n  X metric_topology_neighborhood_basis _ _ _ _).\n\nintros.\ndestruct H as [r1].\ndestruct H0 as [r2].\nexists (open_ball x (Rmin r1 r2)); split.\nconstructor.\napply Rmin_Rgt_r; split; trivial.\nred; intros.\ndestruct H1.\nconstructor; constructor.\napply Rlt_le_trans with (Rmin r1 r2); trivial.\napply Rmin_l.\napply Rlt_le_trans with (Rmin r1 r2); trivial.\napply Rmin_r.\n\nintros.\ndestruct H.\nconstructor.\nrewrite metric_zero; trivial.\n\nintro.\nexists (open_ball x 1).\nconstructor.\nauto with *.\n\nintros.\ndestruct H.\ndestruct H0.\nexists (open_ball y (r - d x y)); split.\nconstructor.\napply Rgt_minus; trivial.\nred; intros z ?.\ndestruct H1.\nconstructor.\napply Rle_lt_trans with (d x y + d y z).\napply triangle_inequality; trivial.\nassert (d x y + d y z < d x y + (r - d x y)).\nauto with *.\nring_simplify in H2.\nassumption.\nDefined.\n\nEnd metric_topology.\n\nImplicit Arguments metric_topology_neighborhood_basis [[X]].\nImplicit Arguments MetricTopology [[X]].\n\nDefinition metrizes (X:TopologicalSpace)\n  (d:point_set X -> point_set X -> R) : Prop :=\n  forall x:point_set X, open_neighborhood_basis\n             (metric_topology_neighborhood_basis d x) x.\n\nInductive metrizable (X:TopologicalSpace) : Prop :=\n  | intro_metrizable: forall d:point_set X -> point_set X -> R,\n    metric d -> metrizes X d ->\n    metrizable X.\n\nLemma MetricTopology_metrizable: forall (X:Type) (d:X->X->R)\n  (d_metric: metric d),\n  metrizes (MetricTopology d d_metric) d.\nProof.\nintros.\nred.\nintros.\napply Build_TopologicalSpace_from_open_neighborhood_bases_basis.\nQed.\n\nRequire Export Nets.\n\nLemma metric_space_net_limit: forall (X:TopologicalSpace)\n  (d:point_set X -> point_set X -> R), metrizes X d ->\n  forall (I:DirectedSet) (x:Net I X) (x0:point_set X),\n  (forall eps:R, eps > 0 -> for large i:DS_set I, d x0 (x i) < eps) ->\n  net_limit x x0.\nProof.\nintros.\nred; intros.\ndestruct (H x0).\ndestruct (open_neighborhood_basis_cond U) as [V []].\nsplit; trivial.\ndestruct H3.\napply eventually_impl_base with (2:=H0 r H3).\nintros.\napply H4.\nconstructor; trivial.\nQed.\n\nLemma metric_space_net_limit_converse: forall (X:TopologicalSpace)\n  (d:point_set X -> point_set X -> R), metrizes X d ->\n  forall (I:DirectedSet) (x:Net I X) (x0:point_set X),\n    net_limit x x0 -> forall eps:R, eps > 0 ->\n                         for large i:DS_set I, d x0 (x i) < eps.\nProof.\nintros.\npose (U:=open_ball _ d x0 eps).\nassert (open_neighborhood U x0).\napply H.\nconstructor; trivial.\ndestruct H2.\ndestruct (H0 U) as [i]; trivial.\nexists i; intros.\napply H4; trivial.\nQed.\n\nLemma metric_space_net_cluster_point: forall (X:TopologicalSpace)\n  (d:point_set X -> point_set X -> R), metrizes X d ->\n  forall (I:DirectedSet) (x:Net I X) (x0:point_set X),\n  (forall eps:R, eps > 0 ->\n     exists arbitrarily large i:DS_set I, d x0 (x i) < eps) ->\n  net_cluster_point x x0.\nProof.\nintros.\nred; intros.\ndestruct (H x0).\ndestruct (open_neighborhood_basis_cond U) as\n  [? [[]]].\nsplit; trivial.\nred; intros.\ndestruct (H0 r H3 i) as [j []].\nexists j; split; trivial.\napply H4.\nconstructor; trivial.\nQed.\n\nLemma metric_space_net_cluster_point_converse: forall (X:TopologicalSpace)\n  (d:point_set X -> point_set X -> R), metrizes X d ->\n  forall (I:DirectedSet) (x:Net I X) (x0:point_set X),\n    net_cluster_point x x0 -> forall eps:R, eps > 0 ->\n                exists arbitrarily large i:DS_set I, d x0 (x i) < eps.\nProof.\nintros.\npose (U:=open_ball _ d x0 eps).\nassert (open_neighborhood U x0).\napply H.\nconstructor; trivial.\ndestruct H2.\npose proof (H0 U H2 H3).\nred; intros.\ndestruct (H4 i) as [j []].\nexists j.\nsplit; trivial.\ndestruct H6; trivial.\nQed.\n\nRequire Export Continuity.\n\nLemma metric_space_fun_continuity_converse: forall (X Y:TopologicalSpace)\n  (f:point_set X->point_set Y) (x:point_set X)\n  (dX:point_set X -> point_set X -> R)\n  (dY:point_set Y -> point_set Y -> R),\n  metrizes X dX -> metrizes Y dY ->\n  continuous_at f x -> forall eps:R, eps > 0 ->\n                         exists delta:R, delta > 0 /\\\n                         forall x':point_set X, dX x x' < delta ->\n                                        dY (f x) (f x') < eps.\nProof.\nintros.\ndestruct (H x).\ndestruct (H0 (f x)).\nassert (neighborhood (open_ball _ dY (f x) eps) (f x)).\napply open_neighborhood_is_neighborhood.\napply open_neighborhood_basis_elements0.\nconstructor; trivial.\napply H1 in H3.\ndestruct H3 as [U].\ndestruct H3.\ndestruct (open_neighborhood_basis_cond U H3) as [V].\ndestruct H5.\ndestruct H5 as [delta].\nexists delta.\nsplit; trivial.\nintros.\nassert (In (inverse_image f (open_ball _ dY (f x) eps)) x').\napply H4.\napply H6.\nconstructor.\ntrivial.\ndestruct H8.\ndestruct H8.\ntrivial.\nQed.\n\nLemma metric_space_fun_continuity: forall (X Y:TopologicalSpace)\n  (f:point_set X->point_set Y) (x:point_set X)\n  (dX:point_set X -> point_set X -> R)\n  (dY:point_set Y -> point_set Y -> R),\n  metrizes X dX -> metrizes Y dY ->\n  (forall eps:R, eps > 0 -> exists delta:R, delta > 0 /\\\n                         forall x':point_set X, dX x x' < delta ->\n                                        dY (f x) (f x') < eps) ->\n  continuous_at f x.\nProof.\nintros.\ndestruct (H x).\ndestruct (H0 (f x)).\nred; intros.\ndestruct H2 as [V'].\ndestruct H2.\ndestruct (open_neighborhood_basis_cond0 V' H2).\ndestruct H4.\ndestruct H4 as [eps].\ndestruct (H1 eps H4) as [delta []].\nexists (open_ball _ dX x delta).\nsplit.\napply open_neighborhood_basis_elements.\nconstructor; trivial.\nintros x' ?.\ndestruct H8.\nconstructor.\napply H3.\napply H5.\nconstructor.\napply H7; trivial.\nQed.\n\nRequire Export CountabilityAxioms.\n\nLemma metrizable_impl_first_countable: forall X:TopologicalSpace,\n  metrizable X -> first_countable X.\nProof.\nintros.\ndestruct H.\nred; intros.\nexists (Im [n:nat | (n>0)%nat]\n           (fun n:nat => open_ball _ d x (/ (INR n)))).\nsplit.\napply open_neighborhood_basis_is_neighborhood_basis.\nconstructor.\nintros.\ndestruct H1 as [n ? V].\ndestruct H1.\napply H0.\nrewrite H2; constructor.\nauto with *.\n\nintros.\ndestruct (H0 x).\ndestruct (open_neighborhood_basis_cond U) as [V [[eps] ?]]; trivial.\ndestruct (inverses_of_nats_approach_0 eps H2) as [n [? ?]].\nexists (open_ball _ d x (/ (INR n))); split.\nexists n; trivial.\nconstructor; trivial.\nred; intros y ?.\napply H3.\ndestruct H6.\nconstructor.\napply Rlt_trans with (/ INR n); trivial.\n\napply countable_img.\napply countable_type_ensemble.\nexists (fun n:nat => n).\nred; intros; trivial.\nQed.\n\nLemma metrizable_separable_impl_second_countable:\n  forall X:TopologicalSpace, metrizable X -> separable X ->\n    second_countable X.\nProof.\nintros.\ndestruct H.\ndestruct H0.\nexists (Im [p:(Q*(point_set X))%type |\n            let (r,x):=p in (r>0)%Q /\\ In S x]\n  (fun p:(Q*(point_set X))%type =>\n      let (r,x):=p in open_ball _ d x (Q2R r))).\nconstructor.\nintros.\ndestruct H3.\ndestruct H3.\ndestruct x as [r x].\ndestruct H3.\ndestruct (H1 x).\ndestruct (open_neighborhood_basis_elements y).\nrewrite H4.\nconstructor; trivial.\nassert (Q2R 0 = 0).\nunfold Q2R.\nsimpl.\nring.\nrewrite <- H6.\napply Qlt_Rlt; trivial.\nassumption.\n\nintros.\ndestruct (H1 x).\ndestruct (open_neighborhood_basis_cond U) as [V [[r]]].\nsplit; trivial.\n\ndestruct (dense_meets_every_nonempty_open _ _ H2\n  (open_ball _ d x (r/2))).\ndestruct (open_neighborhood_basis_elements\n  (open_ball _ d x (r/2))).\nconstructor; trivial.\napply Rmult_lt_0_compat; auto with real.\ndestruct (open_neighborhood_basis_elements\n  (open_ball (point_set X) d x (r/2))).\nconstructor; trivial.\napply Rmult_lt_0_compat; auto with real.\nassumption.\nexists x.\nconstructor.\nrewrite metric_zero.\napply Rmult_lt_0_compat; auto with real.\ntrivial.\n\ndestruct H7.\ndestruct H8.\n\ndestruct (rationals_dense_in_reals (d x x0) (r - d x x0)) as [r'].\nassert (d x x0 + d x x0 < r/2 + r/2).\nauto with *.\nassert (r/2 + r/2 = r).\nfield.\nrewrite H10 in H9; clear H10.\nassert ((d x x0 + d x x0) - d x x0 < r - d x x0).\nunfold Rminus.\nauto with *.\nring_simplify in H10.\nring_simplify.\nassumption.\n\nexists (open_ball _ d x0 (Q2R r')); repeat split.\nexists ( (r', x0) ); auto.\nconstructor; split; trivial.\nassert (Q2R r' > 0).\napply Rgt_ge_trans with (d x x0).\napply H9.\napply metric_nonneg; trivial.\napply Rlt_Qlt.\nunfold Q2R at 1.\nsimpl.\nring_simplify.\nassumption.\n\nred; intros y ?.\ndestruct H10.\napply H6.\nconstructor.\napply Rle_lt_trans with (d x x0 + d x0 y).\napply triangle_inequality; trivial.\napply Rlt_trans with (d x x0 + Q2R r').\nauto with *.\ndestruct H9.\nassert (d x x0 + Q2R r' < d x x0 + (r - d x x0)).\nauto with *.\nring_simplify in H12.\nassumption.\ndestruct H9.\nrewrite metric_sym; trivial.\n\napply countable_img.\ndestruct H0 as [h].\n\ndestruct (Q_countable).\ndestruct countable_nat_product as [g].\n\nred.\n\nmatch goal with |- CountableT ?T =>\nexists (fun x:T =>\n  match x with\n  | exist (r, x0) (intro_characteristic_sat (conj r_pos i)) =>\n    g (h (exist _ x0 i), f r)\n  end)\nend.\nred; intros.\ndestruct x1 as [[r1 x1] [[pos_r1 i1]]].\ndestruct x2 as [[r2 x2] [[pos_r2 i2]]].\nRequire Import Proj1SigInjective.\napply subset_eq_compatT.\napply H4 in H5.\nf_equal.\ninjection H5; intros.\napply H3; trivial.\ninjection H5; intros.\napply H0 in H7.\ninjection H7; trivial.\nQed.\n\nLemma metrizable_Lindelof_impl_second_countable:\n  forall X:TopologicalSpace, metrizable X -> Lindelof X ->\n    second_countable X.\nProof.\nintros.\ndestruct H.\nRequire Import ClassicalChoice.\ndestruct (choice (fun (n:{n:nat | (n > 0)%nat}) (S:Family (point_set X)) =>\n  Included S (Im Full_set (fun x:point_set X =>\n                            open_ball _ d x (/ (INR (proj1_sig n)))))\n  /\\ Countable S /\\ FamilyUnion S = Full_set))\nas [choice_fun].\ndestruct x as [n].\napply H0.\nintros.\ndestruct H2 as [x ? U].\ndestruct (H1 x).\nOpaque In. apply open_neighborhood_basis_elements. Transparent In.\nrewrite H3; constructor.\nsimpl.\nauto with *.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nsimpl.\nexists (open_ball _ d x (/ INR n)).\nexists x; trivial.\nconstructor.\nrewrite metric_zero; auto with *.\n\nexists (IndexedUnion choice_fun).\nconstructor.\nintros.\ndestruct H3 as [n V].\ndestruct (H2 n) as [? [? ?]].\napply H4 in H3.\ndestruct H3 as [x ? V].\ndestruct (H1 x).\nOpaque In. apply open_neighborhood_basis_elements. Transparent In.\nrewrite H7; constructor.\ndestruct n as [n g].\nsimpl.\nauto with *.\n\nintros.\ndestruct (H1 x).\ndestruct (open_neighborhood_basis_cond U) as [V [? ?]].\nsplit; trivial.\ninversion H5.\ndestruct (inverses_of_nats_approach_0 (r/2)) as [n [? ?]].\napply Rmult_lt_0_compat; auto with *.\npose (nsig := exist (fun n:nat => (n>0)%nat) n H9).\ndestruct (H2 nsig) as [? [? ?]].\nassert (In (FamilyUnion (choice_fun nsig)) x).\nrewrite H13; constructor.\ndestruct H14 as [W].\npose proof (H11 _ H14).\ndestruct H16 as [y ? W].\nrewrite H17 in H15; destruct H15.\nexists W; repeat split.\nexists nsig; trivial.\nassert (Included W V); auto with *.\nrewrite H17; rewrite <- H8.\nred; intros z ?.\ndestruct H18.\nconstructor.\napply Rle_lt_trans with (d x y + d y z).\napply triangle_inequality; trivial.\nrewrite (metric_sym _ d H x y).\napply Rlt_trans with (/ INR (proj1_sig nsig) + / INR (proj1_sig nsig)).\nauto with *.\nsimpl.\nassert (r = r/2 + r/2).\nfield.\nrewrite H19; clear H19.\nauto with *.\nrewrite H17; constructor.\nassumption.\n\napply countable_union.\napply countable_type_ensemble.\nexists (fun n:nat => n).\nred; intros; trivial.\nintro.\ndestruct (H2 a) as [? [? ?]]; trivial.\nQed.\n\nSection dist_to_set.\n\nVariable X:Type.\nVariable d:X->X->R.\nHypothesis d_is_metric: metric d.\nVariable S:Ensemble X.\nHypothesis S_nonempty: Inhabited S.\n\nRequire Export SupInf.\n\nDefinition dist_to_set (x:X) : R.\nrefine (proj1_sig (inf (Im S (d x)) _ _)).\nexists 0.\nred; intros.\ndestruct H.\nrewrite H0; apply metric_nonneg; trivial.\ndestruct S_nonempty.\nexists (d x x0); exists x0; trivial.\nDefined.\n\nLemma dist_to_set_triangle_inequality: forall (x y:X),\n  dist_to_set y <= dist_to_set x + d x y.\nProof.\nintros.\nunfold dist_to_set at 1; destruct inf as [dSy [? ?]].\nsimpl.\nunfold dist_to_set at 1; destruct inf as [dSx].\nsimpl.\nclear r.\napply lt_plus_epsilon_le.\nintros.\ndestruct (glb_approx _ _ _ i0 H) as [dxz [[z]]].\nrewrite H1 in H2; clear y0 H1.\ndestruct H2.\napply Rle_lt_trans with (d y z).\nassert (d y z >= dSy); auto with *.\napply i.\nexists z; trivial.\napply Rle_lt_trans with (d y x + d x z).\napply triangle_inequality; trivial.\nrewrite (metric_sym _ _ d_is_metric y x).\nreplace (dSx + d x y + eps) with (d x y + (dSx + eps)).\nauto with *.\nring.\nQed.\n\nEnd dist_to_set.\n\nImplicit Arguments dist_to_set [[X]].\nImplicit Arguments dist_to_set_triangle_inequality [[X]].\n\nSection dist_to_set_and_topology.\n\nVariable X:TopologicalSpace.\nVariable d:point_set X -> point_set X -> R.\nHypothesis d_is_metric: metric d.\nHypothesis d_metrizes_X: metrizes X d.\nVariable S:Ensemble (point_set X).\nHypothesis S_nonempty: Inhabited S.\n\nLemma dist_to_set_zero_impl_closure: forall x:point_set X,\n  dist_to_set d d_is_metric S S_nonempty x = 0 -> In (closure S) x.\nProof.\nintros.\napply NNPP; intro.\ndestruct (d_metrizes_X x).\ndestruct (open_neighborhood_basis_cond (Complement (closure S))) as [V [? ?]].\nsplit; trivial.\napply closure_closed.\ndestruct H1 as [r].\nunfold dist_to_set in H.\ndestruct inf in H.\nsimpl in H.\nrewrite H in i; clear x0 H.\ndestruct i.\nassert (is_lower_bound (Im S (d x)) r).\nred; intros y ?.\ndestruct H4 as [y].\nrewrite H5; clear y0 H5.\ndestruct (total_order_T (d x y) r) as [[?|?]|?]; auto with *.\nassert (In (open_ball _ d x r) y).\nconstructor; trivial.\napply H2 in H5.\ncontradiction H5.\napply closure_inflationary; trivial.\napply H3 in H4.\nassert (0 < 0).\napply Rlt_le_trans with r; trivial.\nrevert H5; apply Rlt_irrefl.\nQed.\n\nLemma closure_impl_dist_to_set_zero: forall x:point_set X,\n  In (closure S) x -> dist_to_set d d_is_metric S S_nonempty x = 0.\nProof.\nintros.\nunfold dist_to_set; destruct inf.\ndestruct i.\nsimpl.\napply Rle_antisym.\napply lt_plus_epsilon_le.\nintros.\nring_simplify.\nassert (exists y:point_set X, In S y /\\ d x y < eps).\napply NNPP; intro.\npose proof (not_ex_all_not _ _ H1).\nclear H1.\nsimpl in H2.\nassert (In (interior (Complement S)) x).\nexists (open_ball _ d x eps).\nred; split.\ndestruct (d_metrizes_X x).\ndestruct (open_neighborhood_basis_elements (open_ball _ d x eps)).\nconstructor; trivial.\nsplit.\nassumption.\n\nred; intros y ?.\ndestruct H4.\nred; red; intro.\ncontradiction (H2 y).\nsplit; trivial.\n\nconstructor.\nrewrite metric_zero; trivial.\n\nrewrite interior_complement in H1.\ncontradiction H1; trivial.\n\ndestruct H1 as [y [? ?]].\napply Rle_lt_trans with (d x y); trivial.\nassert (d x y >= x0).\napply i.\nexists y; trivial.\nauto with *.\n\napply r.\nred; intros.\ndestruct H0.\nrewrite H1; apply metric_nonneg; trivial.\nQed.\n\nVariable T:Ensemble (point_set X).\nHypothesis T_nonempty: Inhabited T.\n\nLemma closer_to_S_than_T_open: open\n  [x:point_set X | dist_to_set d d_is_metric S S_nonempty x <\n                   dist_to_set d d_is_metric T T_nonempty x].\nProof.\nmatch goal with |- open ?U => assert (interior U = U) end.\napply Extensionality_Ensembles; split.\napply interior_deflationary.\nred; intros.\ndestruct H.\nmatch type of H with ?d1 < ?d2 => pose (eps := d2 - d1) end.\nmatch goal with |- In (interior ?U) x =>\n  assert (Included (open_ball _ d x (eps/2)) (interior U)) end.\napply interior_maximal.\ndestruct (d_metrizes_X x).\ndestruct (open_neighborhood_basis_elements\n  (open_ball _ d x (eps/2))).\nconstructor.\nassert (eps > 0).\napply Rgt_minus; auto with *.\napply Rmult_gt_0_compat; auto with *.\nassumption.\nred; intros.\ndestruct H0.\nconstructor.\napply Rle_lt_trans with\n  (dist_to_set d d_is_metric S S_nonempty x +\n   d x x0).\napply dist_to_set_triangle_inequality.\napply Rlt_le_trans with\n  (dist_to_set d d_is_metric T T_nonempty x - d x x0).\napply Rminus_lt.\nring_simplify.\nassert (2 * d x x0 < eps).\nreplace eps with (2 * (eps / 2)).\nauto with *.\nfield.\nmatch goal with |- ?LHS < 0 => replace LHS with (2 * d x x0 - eps) end.\napply Rlt_minus; trivial.\nunfold eps; ring.\n\nassert (dist_to_set d d_is_metric T T_nonempty x <=\n        dist_to_set d d_is_metric T T_nonempty x0 + d x x0).\nrewrite (metric_sym _ d d_is_metric x x0).\napply dist_to_set_triangle_inequality.\napply Rminus_le.\napply Rle_minus in H1.\nmatch type of H1 with ?A <= 0 =>\n  match goal with |- ?B <= 0 =>\n    replace B with A end end.\nassumption.\nring.\n\napply H0.\nconstructor.\nrewrite metric_zero.\napply Rmult_gt_0_compat; auto with *.\napply Rgt_minus; trivial.\ntrivial.\n\nrewrite <- H; apply interior_open.\nQed.\n\nEnd dist_to_set_and_topology.\n\nRequire Export SeparatednessAxioms.\n\nLemma metrizable_impl_normal_sep: forall X:TopologicalSpace,\n  metrizable X -> normal_sep X.\nProof.\nintros.\ndestruct H.\nsplit.\nred; intros.\nassert (closure (Singleton x) = Singleton x).\napply Extensionality_Ensembles; split.\nred; intros.\nassert (x0 = x).\napply metric_strict with d; trivial.\napply NNPP; intro.\nassert (d x0 x > 0).\ndestruct (total_order_T (d x0 x) 0) as [[?|?]|?]; trivial.\nassert (0 < 0).\napply Rle_lt_trans with (d x0 x); trivial.\nassert (d x0 x >= 0); auto with *.\napply metric_nonneg; trivial.\ncontradict H3; apply Rlt_irrefl.\ncontradiction H2.\n\nassert (In (interior (Complement (Singleton x))) x0).\nexists (open_ball _ d x0 (d x0 x)).\nsplit.\ndestruct (H0 x0).\ndestruct (open_neighborhood_basis_elements\n  (open_ball (point_set X) d x0 (d x0 x))).\nconstructor; trivial.\nsplit.\nassumption.\nred; intros.\nintro.\ndestruct H7.\ndestruct H6.\nrevert H6; apply Rlt_irrefl.\nconstructor.\nrewrite metric_zero; trivial.\n\nrewrite interior_complement in H4.\ncontradiction H4.\n\nrewrite H2; constructor.\n\napply closure_inflationary.\n\nrewrite <- H1; apply closure_closed.\n\nintros.\nRequire Import DecidableDec.\ncase (classic_dec (Inhabited F)); intro.\ncase (classic_dec (Inhabited G)); intro.\n\npose (U := [ x:point_set X | dist_to_set d H F i x <\n                             dist_to_set d H G i0 x ]).\npose (V := [ x:point_set X | dist_to_set d H G i0 x <\n                             dist_to_set d H F i x ]).\nexists U; exists V; repeat split.\napply closer_to_S_than_T_open; trivial.\napply closer_to_S_than_T_open; trivial.\nreplace (dist_to_set d H F i x) with 0.\ndestruct (total_order_T 0 (dist_to_set d H G i0 x)) as [[?|?]|?]; trivial.\nsymmetry in e.\napply dist_to_set_zero_impl_closure in e.\nrewrite closure_fixes_closed in e; trivial.\nassert (In Empty_set x).\nrewrite <- H3; constructor; trivial.\ndestruct H5.\ntrivial.\n\nassert (0 < 0).\napply Rle_lt_trans with (dist_to_set d H G i0 x); auto with sets.\nunfold dist_to_set; destruct inf.\nsimpl.\napply i1.\nred; intros.\ndestruct H5.\nrewrite H6; apply metric_nonneg; trivial.\ncontradict H5; apply Rlt_irrefl.\n\nunfold dist_to_set; destruct inf.\nsimpl.\napply Rle_antisym.\napply i1.\nred; intros.\ndestruct H5.\nrewrite H6; apply metric_nonneg; trivial.\ndestruct i1.\nassert (0 >= x0); auto with *.\napply H5.\nexists x; trivial.\nsymmetry; apply metric_zero; trivial.\n\nreplace (dist_to_set d H G i0 x) with 0.\ndestruct (total_order_T 0 (dist_to_set d H F i x)) as [[?|?]|?]; trivial.\nsymmetry in e.\napply dist_to_set_zero_impl_closure in e.\nrewrite closure_fixes_closed in e; trivial.\nassert (In Empty_set x).\nrewrite <- H3; constructor; trivial.\ndestruct H5.\ntrivial.\n\nassert (0 < 0).\napply Rle_lt_trans with (dist_to_set d H F i x); auto with *.\nunfold dist_to_set; destruct inf.\nsimpl.\napply i1.\nred; intros.\ndestruct H5.\nrewrite H6; apply metric_nonneg; trivial.\ncontradict H5; apply Rlt_irrefl.\n\nsymmetry.\napply closure_impl_dist_to_set_zero; trivial.\napply closure_inflationary; trivial.\n\napply Extensionality_Ensembles; split; auto with sets.\nred; intros.\ndestruct H4.\ndestruct H4.\ndestruct H5.\ncontradict H5.\nauto with *.\n\nexists Full_set; exists Empty_set; repeat split; auto with topology.\nred; intros.\ncontradiction n.\nexists x; trivial.\n\nauto with sets.\n\nexists Empty_set; exists Full_set; repeat split; auto with topology.\nred; intros.\ncontradiction n.\nexists x; trivial.\nauto with sets.\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/MetricSpaces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7727865343804282}}
{"text": " (** * IndProp: Inductively Defined Propositions *)\n\nRequire Export Arith.\nRequire Export Induction.\nRequire Export Logic.\n\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 new definition of evenness works, let's use\n    its rules to show that [4] is even. By rule [ev_SS], it suffices\n    to show that [2] is even. This, in turn, is again guaranteed by\n    rule [ev_SS], as long as we can show that [0] is even. But this\n    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\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\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 theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Such \"constructor\n    theorems\" have the same status as proven theorems.  In particular,\n    we can use Coq's [apply] tactic with the rule names to prove [ev]\n    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.\n  intros. induction n.\n  + simpl. apply ev_0.\n  + simpl. apply ev_SS. assumption.\n\nQed.\n\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(** ** Inversion on Evidence *)\n\n(** Subtracting two from an even number yields another even number.\n    We can easily prove this claim with the techniques that we've\n    already seen, provided that we phrase it in the right way.  If we\n    state it in terms of [evenb], for instance, we can proceed by a\n    simple case analysis on [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(** We can state the same claim in terms of [ev], but this quickly\n    leads us to an obstacle: Since [ev] is defined inductively --\n    rather than as a function -- Coq doesn't know how to simplify a\n    goal involving [ev n] after case analysis on [n].  As a\n    consequence, the same proof strategy fails: *)\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; we're stuck! *) simpl.\nAbort.\n\n(** The solution is to perform case analysis on the evidence that [ev\n    n] _directly_. By the definition of [ev], there are two cases to\n    consider:\n\n    - If that 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, that 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(** We can invoke this kind of argument in Coq using the [inversion]\n    tactic.  Besides allowing us to reason about equalities involving\n    constructors, [inversion] provides a case-analysis principle for\n    inductively defined propositions.  When used in this way, its\n    syntax is similar to [destruct]: We pass it a list of identifiers\n    separated by [|] characters to name the arguments to each of the\n    possible constructors.  For instance: *)\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(** Note that, in this particular case, it is also possible to replace\n    [inversion] by [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 (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E. inversion E as [|n' E'].\n  inversion E' as [|n'' E'']. apply E''.\nQed.\n\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  simpl.  intros. exfalso.\n  inversion H.  inversion H1. inversion H3.\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(* ####################################################### *)\n(** ** Induction on Evidence *)\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], we already know that those are equivalent to\n    each other). To show that all three coincide, we just need the\n    following lemma: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\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').\n      reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\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\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       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 when studying the semantics of programming\n    languages, where many properties of interest are defined\n    inductively.  The following exercises provide simple examples of\n    this technique, to help you familiarize yourself with it. *)\n\n\n\n(** **** Exercise: 2 stars (ev_sum)  *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros. induction H.\n  + simpl.  assumption.\n  + simpl.  apply ev_SS. assumption.\nQed.\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\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\n    the old one. *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros. split.\n  + intros. induction H.\n   - apply ev_0.\n   - apply ev_SS.  apply ev_0.\n   - apply ev_sum. assumption. assumption.\n  +  intros. induction H.\n   - apply ev'_0.\n   - rewrite plus1_S_equiv. rewrite plus1_S_equiv. rewrite <- plus_assoc.\n     simpl.  apply ev'_sum. assumption. apply ev'_2.\nQed.\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  intros.  induction H0.\n  + rewrite <- plus_O_n. assumption.\n  + apply IHev. rewrite plus_Sn_m in H.  simpl in H.\n    apply evSS_ev. assumption.\nQed.\n\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  intros. assert (F: ev ((n+m)+(n+p))). apply ev_sum.  assumption. assumption.\n  assert (G: (n+m) +(n+p) = (n+n)+(m+p)).  rewrite <- (plus_assoc  n m).\n  rewrite (plus_assoc m n p). rewrite (plus_comm m n). rewrite <- plus_assoc.  rewrite <- plus_assoc.\n  reflexivity.\n  assert (ev (n+n)). rewrite  <- double_plus. apply ev_double.\n  apply (ev_ev__ev (n+n) (m+p)).  rewrite <- G. assumption.  assumption.\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 LeModule.\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** 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  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) -> 2 + 2 = 5.\nProof.\n  intros H. inversion H. inversion H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : 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, 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| tr : forall n m: nat, total_relation n m.\n\nExample tr_1: total_relation 7 2.\nProof. apply tr. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop :=.\n\nExample er_1: empty_relation 5 5 -> False.\nProof.\n  intros. inversion H. Qed.\n\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.\n  intros.\n  induction o.\n  + inversion H0. rewrite <- H1. assumption.\n  + inversion H0.\n    - rewrite <- H1. assumption.\n    - apply le_S. apply IHo. assumption.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n.\n  + apply le_n.\n  + apply le_S. 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 m.\n  + inversion H. apply le_n.\n  + inversion H. apply le_n. apply IHm in H1. apply le_S in H1.\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  induction m.\n  + inversion H.\n    - apply le_n.\n    - inversion H1.\n  + inversion H.\n    - apply le_n.\n    - apply le_S. apply IHm. assumption.\nQed.\n\n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros.\n  induction b.\n  + rewrite <- plus_n_O. apply le_n.\n  + rewrite <- plus_n_Sm.  apply le_S. assumption.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt.\n  intros. split.\n  + induction n2.\n    - rewrite  plus_n_O with (n:= n1). assumption.\n    - apply IHn2. rewrite <- plus_n_Sm in H.  inversion H.\n      * apply le_S. apply le_n.\n      * rewrite H1. apply le_S in H. apply Sn_le_Sm__n_le_m in H. assumption.\n  + induction n1.\n    - rewrite  plus_n_O with (n:= n2). rewrite plus_comm. assumption.\n    - apply IHn1. rewrite plus_comm in H. rewrite plus_comm.  rewrite <- plus_n_Sm in H.  inversion H.\n      * apply le_S. apply le_n.\n      * rewrite H1. apply le_S in H. apply Sn_le_Sm__n_le_m in H. assumption.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros.\n  unfold lt. induction m.\n  - inversion H.\n  - inversion H.\n    + apply le_S. apply le_n.\n    + apply le_S in H1. apply le_S in H1. assumption.\nQed.      \n\nTheorem leb_complete : forall n m,\n  leb 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  leb n m = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\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  intros.\n(* FILL IN HERE *) Admitted.\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_provability2)  *)\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 *)\nExample r_1_1_2: R  1 1 2.\nProof.\n  apply c5. apply c3. apply c5. apply c3. apply c1.\nQed.\n\nExample r_2_2_6 : R 2 2 6.\nProof.\n  apply c3. apply c2. apply c2. apply c5. apply c2. Admitted.\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  fun  (m n: nat) => m+n.\n\nLemma R_O_n_n: forall n, R 0 n n.\nProof.\n  intros. induction n.\n  + apply c1.\n  + apply c3. assumption.\nQed.\n\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n  intros. split.\n  + intros. unfold fR. induction H.\n    - reflexivity.\n    - simpl. rewrite IHR. reflexivity.\n    - rewrite plus_comm. simpl.  rewrite plus_comm.  rewrite IHR. reflexivity.\n    - rewrite <- plus_n_Sm in IHR. rewrite  plus_Sn_m in IHR. inversion IHR. reflexivity.\n    - rewrite plus_comm. assumption.\n  + intros. unfold fR in H.  induction H.\n    induction m.\n    - rewrite plus_O_n. apply R_O_n_n.\n    - simpl. apply c2. assumption.\nQed.\n\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_provability)  *)\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 of evenness that we had\n    already seen, and does not seem to offer any concrete benefit over\n    them.  To give a better sense of the power of inductive\n    definitions, we now show how to use them to model a classic\n    concept in computer science: _regular expressions_.\n\n    Regular expressions are a simple language for describing strings,\n    defined as elements of the following inductive type.  (The names\n    of the constructors should become clear once we explain their\n    meaning below.)  *)\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(** Note that this definition is _polymorphic_: Regular expressions in\n    [reg_exp T] describe strings with characters drawn from [T] --\n    that is, lists of elements of [T].  (We depart slightly from\n    standard practice in that we do not require the type [T] to be\n    finite.  This results in a somewhat different theory of regular\n    expressions, but the difference is not significant for our\n    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].  (As a special case, the sequence of\n      strings may be empty, so [Star re] always matches the empty\n      string [[]] no matter what [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 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    \n              exp_match s2 (Union re1 re2)\n| MStar0 : forall re, exp_match [] (Star re)\n| MStarApp : forall s1 s2 re,\n\n\n    \n               exp_match s1 re ->\n               exp_match s2 (Star re) ->\n               exp_match (s1 ++ s2) (Star re).\n\n(** Once again, for readability, we can also display this definition\n    using inference-rule notation.  At the same time, let's introduce\n    a more 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\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\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Furthermore, 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 to help write 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.\n  intros. unfold not. intros. inversion H.\nQed.   \n  \n  \n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros. destruct H.\n  +  apply MUnionL.  assumption.\n  +  apply MUnionR. assumption.\nQed. \n\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros. induction ss.\n  + simpl. apply MStar0.\n  + simpl. apply MStarApp.\n  - apply H. simpl. left. reflexivity.\n  - apply IHss. intros. apply H. simpl. right. assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars (reg_exp_of_list)  *)\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.  For\n    example, suppose that we wanted to prove the following intuitive\n    result: If a regular expression [re] matches some string [s], then\n    all elements of [s] must occur somewhere in [re].  To state this\n    theorem, we first define a function [re_chars] that lists all\n    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 [\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  (* 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} (re : reg_exp T) : bool :=\n  (* FILL IN HERE *) admit.\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(** ** 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 net effect of this will be\n    to lose information (much as [destruct] can do), and leave you\n    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 the\n    recursive cases. (Try it!). So we need induction. Here is a naive\n    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 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 of them 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... *)\n\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].  In this respect it\n    behaves more like [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 T),\n  s1 =~ re' ->\n  re' = Star 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.  Calling\n    [remember e as x] causes Coq to (1) replace all occurrences of the\n    expression [e] by the variable [x], and (2) add an equation [x =\n    e] to the context.  Here's how we can use it to show the above\n    result: *)\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(** 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(** In the interesting cases (those that correspond to [Star]), we can\n    proceed as usual.  Note that the induction hypothesis [IH2] on the\n    [MStarApp] case mentions an additional premise [Star re'' = Star\n    re'], which results from the equality generated by [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(** **** Exercise: 4 stars (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(* ############################################################ *)\n(** **** Exercise: 5 stars, advanced (pumping)  *)\n(** One of the first interesting theorems in the theory of regular\n    expressions is the so-called _pumping lemma_, which states,\n    informally, that any sufficiently long string [s] matching a\n    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\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  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ####################################################### *)\n(** * Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].\n    Unfortunately, performing this conversion by hand 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\n    apply 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], which is what we need to\n    complete this case.\n\n    We can streamline this proof by defining an inductive proposition\n    that yields a better case-analysis principle for [beq_nat n\n    m].  Instead of generating an equation such as [beq_nat n m =\n    true], which is not directly useful, this principle gives us right\n    away the assumption we need: [n = m].  We'll actually define\n    something a bit more general, which can be used with arbitrary\n    properties (and not just equalities): *)\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]: [P]\n    holds if and only if [b = true].  To see this, notice that, by\n    definition, the only way we can produce evidence that [reflect P\n    true] holds is by showing that [P] is true and using the\n    [ReflectT] constructor.  If we invert this statement, this means\n    that it should be possible to extract evidence for [P] from a\n    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  intros P [] H.\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    To use [reflect] to produce a better proof of\n    [filter_not_empty_In], we begin by recasting the\n    [beq_nat_iff_true] lemma into a more convenient form in terms of\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(** 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].  (To see this clearly, look at the two\n    proofs of [filter_not_empty_In] in your Coq browser and observe\n    the differences in proof state at the beginning of the first case\n    of the [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(** Although this technique arguably gives us only a small gain\n    in convenience for this particular proof, using [reflect]\n    consistently often leads to shorter and clearer proofs. We'll see\n    many more examples where [reflect] comes in handy in later\n    chapters.\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: 4 stars, recommended (palindromes)  *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n\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\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\n(* FILL IN HERE *)\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, advanced (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: 3 stars, recommended (nostutter)  *)\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.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\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 (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: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "perng", "repo": "proof", "sha": "bf181860d43bffdc67f7cd52269518f5fcaf27f1", "save_path": "github-repos/coq/perng-proof", "path": "github-repos/coq/perng-proof/proof-bf181860d43bffdc67f7cd52269518f5fcaf27f1/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.772578304038021}}
{"text": "(** Algoritmo de Ordenação por Inserção em listas *)\n\nFrom Coq Require Import List Arith.\nOpen Scope nat_scope.\n\n(** * Definição de ordenação *)\n\nInductive ordenada: list nat -> Prop :=\n| lista_vazia: ordenada nil\n| lista_unit: forall x, ordenada (x :: nil)\n| lista_mult: forall x y l, x <= y -> ordenada (y :: l) -> ordenada (x :: y :: l).\n\n(** * Definição da função de inserção *)\n\nFixpoint insere (n:nat) (l: list nat) :=\n  match l with\n  | nil => n :: nil\n  | h :: tl => if n <=? h then (n :: l)\n             else (h :: (insere n tl)) \n                      end.\n\n(** * Definição da função principal do algoritmo. *)\n\n Fixpoint ord_insercao l :=\n  match l with\n    | nil => nil\n    | h :: tl => insere h (ord_insercao tl)\n  end.\n\n(** A função [insert] preserva a ordenação. *)\n\nLemma insere_preserva_ordem: forall l x, ordenada l -> ordenada (insere x l). \nProof.\n  induction l. (*indução sempre tem dois passos: base e passo*)\n    - intro x. (*seja x um natural qualquer*)\n      intro Hnil.\n      simpl.\n      apply lista_unit.\n    - intros x H.\n      simpl.\n      destruct (x <=? a) eqn:Hle.\n      -- apply lista_mult.\n         --- apply leb_complete.\n             assumption.\n         --- exact H.\n      -- apply leb_complete_conv in Hle.\n         case_eq l.\n         --- intro Hnil.\n             simpl.\n             apply lista_mult.\n             ---- apply Nat.lt_le_incl.\n                  exact Hle.\n             ---- apply lista_unit.\n         --- intros n l' Hl'.\n             subst.\n             simpl in *.\n             inversion H; subst.\n             destruct (x<=?n) eqn: Hle'.\n             ---- apply lista_mult.\n             ----- apply Nat.lt_le_incl.\n                   assumption.\n             ----- apply (IHl x) in H4.\n                   rewrite Hle' in H4.\n                  assumption.\n            ---- apply lista_mult.\n                 ----- assumption.\n                 ----- apply (IHl x) in H4.\n                       rewrite Hle' in H4.\n                       assumption.\nQed.\n\n\n(** O algoritmo ord_insercao ordena. *)\n\nLemma ord_insercao_ordena: forall l, ordenada (ord_insercao l).\nProof.\n  induction l.\n  - simpl.\n    apply lista_vazia.\n  - simpl.\n    case_eq l.\n    -- intro Hnil.\n       simpl.\n       apply lista_unit.\n    -- intros n l' Hl'.\n       subst.\n       simpl in *. (* travei *)\nAdmitted.\n  \n(** * Permutação *)\n\nInductive perm: list nat -> list nat -> Prop :=\n| perm_refl: forall l, perm l l\n| perm_hd: forall x l l', perm l l' -> perm (x::l) (x::l')\n| perm_swap: forall x y l l', perm l l' -> perm (x::y::l) (y::x::l')\n| perm_trans: forall l l' l'', perm l l' -> perm l' l'' -> perm l l''.\n\nLemma ord_insercao_perm: forall l, perm l (ord_insercao l).\nProof.\n(* Substitua esta linha pela sua prova. Provas completas terminam com Qed. *)  Admitted.\n\n\nTheorem correcao_ord_insercao: forall l, ordenada (ord_insercao l) /\\ perm l (ord_insercao l).\nProof.\n  Admitted.\n  \n(** Extração de código certificado *)\n\nRequire Extraction.\n\nRecursive Extraction ord_insercao.\nExtraction \"ord_insercao.ml\" ord_insercao.", "meta": {"author": "alineavila", "repo": "analise-algoritmos", "sha": "ef54f5212de3ed31dca309786fa733168ef109a5", "save_path": "github-repos/coq/alineavila-analise-algoritmos", "path": "github-repos/coq/alineavila-analise-algoritmos/analise-algoritmos-ef54f5212de3ed31dca309786fa733168ef109a5/proof_insertion_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7725783034262982}}
{"text": "From mathcomp Require Import all_ssreflect.\n(** -------------------------------------------- *)\n\n(** #<div class='slide vfill'>#  \n** Lesson 3 (of 4)\n\n - Finite types\n\n#</div># *)\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide vfill'>#  \n** Objective of this course\n\nUnderstand the benefits and usage of finite types.\n\n - formation principle\n - A special case: ordinals\n - New tools : finite functions and finite set theory\n - Moving even closer to classical logic : choice and extensionality\n#</div># *)\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide vfill'># \n** Formation principle\n\nFor a finite type, you can enumerate the elements\n\nThe enumeration is a simple piece of data (based on sequences)\n - The enumeration gives some computation principle\n - Elements of a finite type can be indexed\n\n#</div># *)\n\n(** -------------------------------------------- *)\n  \n(** #<div class='slide'># \n** The simplest finite types: ordinal numbers\n\nInitial segments of natural numbers\n- Building blocks or yardsticks for other finite types\n- Usable as plain integers, thanks to coercions\n*)\n\nAbout Ordinal.\n\nExample two_in_I_4 :=  Ordinal (isT : 2 < 4).\n\nFail Example five_in_I_4 : Ordinal (isT : 5 < 4).\n\n(* For ordinal types that contain at least one elements, there\nis an optimistic injection from nat. *)\n\nCheck inord.\n\n(* Beware of hidden coercions when reading these statements. *)\n\nCheck inordK.\n\nCheck inord_val.\n\nExample inord_val_3_4 : inord 2 = two_in_I_4 :> 'I_4.\nProof.\nrewrite -[X in inord X]/(nat_of_ord two_in_I_4).\nrewrite inord_val. by [].\nQed.\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'>#  \n** Finite type constructions\n\nIn the rest of this talk I will use the following pattern to\n    verify that I have a finite type.\n*)\nCheck [finType of 'I_4].\n\nFail Check [finType of nat].\n(** New finite types can be built from existing ones\n - ordinal types are the usual examples of basic finite types\n - unit (with one element)\n - bool (with two elements)\n - cartesian product\n - disjoint sum\n - subtype\n - function type\n*)\nCheck [finType of 'I_4 * 'I_3].\n\nDefinition twin_primes_lt100 :=\n {x : 'I_100 * 'I_100 | prime (fst x) &&\n                      prime (snd x) && (snd x == (fst x) + 2 :> nat)}.\n\nCheck [finType of twin_primes_lt100].\n\nDefinition lesser_twin_100 :=\n {x : nat | prime x && prime (x + 2) && (x < 100)}.\n\nFail Check [finType of lesser_twin_100].\n(* solution to make lesser_twin_100 a finite type at the end. *)\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># \n** Building a finite type from scratch\n\nAn example: building an enumerated type, show that is\n   finite\n\nExhibit an injection into another finite type.\n*)\nModule LessonSandBox1.\n\nInductive card_point : predArgType := W | E | N | S.\n\nDefinition cp2o d : 'I_4 :=\n  match d with\n    W => inord 0 | E => inord 1 | N => inord 2 | S => inord 3\n  end.\n\nDefinition o2cp (n : 'I_4) :=\n  match val n with\n    0 => Some W | 1 => Some E | 2 => Some N | 3 => Some S | _ => None\n  end.\n\nLemma cp_can : pcancel cp2o o2cp.\nProof.\ncase.\nrewrite /o2cp. rewrite /=. rewrite inordK. by []. by [].\nby rewrite /o2cp /= inordK.\nby rewrite /o2cp /= inordK.\nby rewrite /o2cp /= inordK.\nQed.\n\n(** #<div class='slide'># \n\nThe lemma cp_can means that there is an injection from card_point into\n a known finite type\n\nA succession of helper theorem to add qualities\n - equality is decidable [eqType]\n - there is a canonical way to choose witnesses [choiceType]\n - the elements can be enumerated [countType]\n - the type [card_point] is finite.\n#</div>#\n*)\n\nCanonical cp_eqType := EqType card_point (PcanEqMixin cp_can).\nCanonical card_point_choiceType :=\n    ChoiceType card_point (PcanChoiceMixin cp_can).\nCanonical cp_countType :=\n    CountType card_point (PcanCountMixin cp_can).\nCanonical card_point_finType := FinType card_point (PcanFinMixin cp_can).\n\nCheck [finType of card_point].\n\nEnd LessonSandBox1.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># \n** Tools about finiteness\n\nMore classical logic\n - Quantifications of decidable predicates become decidable.\n - Need to use special notations\n*)\n\n  \nCheck [forall x : 'I_4, x < 2] && [exists x :'I_4, 4 < x].\n\nCheck [forall x : {x : 'I_100 | prime x}, 1 < val x].\n\nCheck xchoose.\n\nSearch xchoose.\n\n(** #</div class='slide'># *)\n(** Proofs about quantified statements. *)\n\nExample logical_proof : ~~([forall x : 'I_4, x < 2] &&\n         [exists x : 'I_4, 4 < x]).\nProof.\nSearch _ (~~ (_ && _)).\nrewrite negb_and. rewrite negb_forall. apply/orP; left.\napply/existsP. exists (Ordinal (isT : 2 < 4)).\nby [].  (* let's think a little. *)\nQed.\n\nExample logical_proof1 : ~~[exists x: 'I_4, 4 < x].\nProof.\nrewrite negb_exists. apply/forallP. rewrite /=.\nmove => [[ | [ | [ | [ | a]]]] px] => /=.\nby []. by []. by []. by [].\nFail rewrite {px}; by [].\nby [].\nQed.\n(** #</div># *)\n\n(** --------------------------------------------\n#<div class='slide'>#\n** Finite functions\n\nFunction whose domain is a finite type\n\n  - A finite type when the type for values is finite\n  - A special notation for functions from ordinals\n*)\nModule LessonSandbox2.\n\nParameter T : finType.\nParameters x y : T.\n\nCheck [ffun z : T => z = y].\nCheck [ffun z : T => z == y].\nCheck [finType of {ffun T -> bool}].\nCheck [ffun i : 'I_2 => if val i == 0 then x else y].\nCheck [ffun i : 'I_2 => if i == ord0 then x else y] : T ^ 2.\n\nLemma finfun_proof : [ffun i : 'I_2 => if i == ord0 then x else y]\n          (Ordinal (isT : 1 < 2)) = y.\nProof.\nrewrite /=.  rewrite ffunE. rewrite /=. by [].\nQed.\n\nLemma finfun_proof2 : [ffun i : 'I_2 => if i == ord0 then x else y] =\n  [ffun i : 'I_2 => if val i == 1 then y else x].\nProof.\napply/ffunP.\nmove => z. rewrite !ffunE /=.\ncase: z => [[ | [ | z']] pz].\n    rewrite /=. by [].\n  rewrite /=. by [].\nrewrite /=. by [].\nQed.\n\n(** #</div># *)\n\n(** --------------------------------------------\n#<div class='slide'>#\n\n** Set theory over finite types\n - obviously finite sets over a finite type are finite\n - obviously the type of these sets is finite \n*)\nCheck [finType of {set T}].\nParameter A : {set T}.\nCheck #|A|.\nCheck #|[set: T]|.\nLocate \"#| _ |\".\nCheck x \\in A.\nCheck [set x].\nCheck [set x; y].\n\nLemma set_proof : (#|[set x; y]| == 2) = (x != y).\nProof.\nSearch card in finset.\nrewrite cardsU1.\nrewrite cards1 addnC addSn add0n.\nrewrite in_set1.\nrewrite eqSS.\nrewrite eqb1.\nby [].\nQed.\n\n(** #</div># *)\n(** --------------------------------------------\n#<div class='slide'>#\n** Finite types and big operators\n - Big operators are the natural tool to compute repeatedly over\n   all elements of a finite type\n - Elements are picked in the fixed order given by the enumeration. *)\nParameter f : T -> nat.\nCheck \\sum_(i : T) f i.\nCheck big_ord_recr.\nCheck big_ord_recl.\nCheck bigD1.\nCheck big_setID.\n(** #</div># *)\n(** --------------------------------------------\n#<div class='slide'>#\n** Finite graphs\n\nFinite graphs are build on a finite type of nodes\n\nThree approaches\n  - Use a function to list all targets of edges\n  - The graph of a relation\n  - The graph of a function\n*)\nDefinition mg := [:: (0,1); (1,0); (1,2); (3,3)].\nDefinition mgr : rel 'I_4 :=\n   fun x y : 'I_4 => (val x, val y) \\in mg.\nCheck rgraph mgr.\nCheck dfs_path (rgraph mgr) [::] ord0.\nLemma graph_proof : dfs_path (rgraph mgr) [::] ord0 (Ordinal (isT : 2 < 4)).\nSearch dfs_path.\nSearch _ (grel (rgraph _)).\nhave pp : path (grel (rgraph mgr)) ord0 [:: Ordinal (isT : 1 < 4); Ordinal (isT : 2 < 4)].\n  rewrite /=. rewrite andbT; apply/andP; split. \n    rewrite mem_enum. by [].\n  rewrite mem_enum. by [].\napply: (DfsPath pp).\n  by [].\nrewrite disjoint_sym.\napply: disjoint0.\nQed.\n\nParameters (z : T) (g : T -> seq T).\nHypothesis xny : x != y.\nHypothesis xnz : x != z.\nHypothesis ynz : y != z.\nHypothesis g_xyz :\n  (g x == [::y]) && (g y == [:: x; z]).\n  \nLemma graph_proof2 : dfs_path g [::] x z.\nProof.\nhave pp: path (grel g) x [::y;z].\n  rewrite /= andbT.\n  move/andP: g_xyz => [/eqP -> /eqP ->].\n  rewrite !inE. rewrite !eqxx. rewrite orbT. by [].\napply (DfsPath pp).\n  rewrite /=. by [].\nrewrite disjoint_sym. rewrite disjoint0.\nby [].\nQed.\n\n(** --------------------------------------------\n#<div class='slide'>#\n** Exercises\n\nExercises taken from #<a href=\"http://www-sop.inria.fr/manifestations/MapSpringSchool/program.html\">Map Spring School</a># (thanks to L. Rideau)\n \n*)\nLemma inj_card_le (I J : finType) (f : I -> J) : injective f -> #|I| <= #|J|.\n\nLemma ord1 : forall i : 'I_1, i = ord0.\n\nLemma adds : forall (a b : T) (E : {set T}), \n    a != b -> a \\notin E -> b \\notin E ->\n    #| a |:  (b |: E)| = #|E| + 2.\n\n(** State and prove the following statements\n\n - E union F = (E minus F) union (F minus E) union (E inter F)\n*)\n(** #</div>#\n*)\n\n(** --------------------------------------------\n#<div class='slide'># \n** Promised proof for lesser_twin_100 *)\nDefinition lesser_twin_100_in_ord (x : lesser_twin_100) : 'I_100.\ncase : x => x /andP [_ px]; exact (Ordinal px).\nDefined.\n\nLemma build_andb (a b : bool) : a -> b -> a && b.\nby move => -> ->. Qed.\n\nDefinition lesser_twin_from_ord (x : 'I_100) : option lesser_twin_100 :=\n  match x with\n  | Ordinal x px => \n     match Sumbool.sumbool_of_bool (prime x && prime (x + 2)) with\n     | left h => Some (exist _ x (build_andb _ _ h px))\n     | right h => None\n     end\n  end.\n\nLemma Pcan100 : pcancel lesser_twin_100_in_ord lesser_twin_from_ord.\nProof. case => x p /=.\ncase: (elimTF andP p) => p1 p2.\nrewrite /lesser_twin_from_ord.\ncase: (Sumbool.sumbool_of_bool (prime x && prime (x + 2))).\n  by move => a; congr Some; apply: val_inj => /=.\nby rewrite p1.\nQed.\n\n(** #</div># \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# *)\n", "meta": {"author": "gares", "repo": "MathCompWS", "sha": "f06e05bea3694857ce22fc9671efd3971b195d4c", "save_path": "github-repos/coq/gares-MathCompWS", "path": "github-repos/coq/gares-MathCompWS/MathCompWS-f06e05bea3694857ce22fc9671efd3971b195d4c/lesson3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.772553727288452}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscreteType\n        Finite.FinType\n        Finite.Constructions.Vector\n        Tactics.Tactics.\n\nImport ListNotations.\n\n\nLemma Cardinality_gt_zero (A : finType) (x : A) : Cardinality A > 0.\nProof.\n  pose proof (element_In x).\n  unfold Cardinality.\n  destruct (elem A) ; crush.\nQed.\n\nLemma Cardinality_card_eq (A : finType)\n  : card (elem A) = Cardinality A.\nProof.\n  apply dup_free_card ; auto.\n  apply dup_free_elem.\nQed.\n\nLemma card_upper_bound (A : finType) (xs : list A): card xs <= Cardinality A.\nProof.\n  rewrite <- Cardinality_card_eq.\n  apply card_le ; auto.\nQed.  \n\nLemma injective_dupfree\n      (A B : finType)\n      (xs : list A)\n      (f : A -> B)\n  : injective f -> dup_free (get_image f).\nProof.\n  intro inj. unfold injective in inj.\n  unfold get_image. apply dup_free_map.\n  -\n    firstorder.\n  -\n    apply dup_free_elem.\nQed.\n\nLemma dup_free_length\n      (A : finType)\n      (xs : list A)\n  : dup_free xs -> |xs| <= Cardinality A.\nProof.\n  unfold Cardinality.  intros D.\n  rewrite <- (dup_free_card _ D). rewrite <- (dup_free_card _ (dup_free_elem A)).\n  apply card_le ; auto.\nQed.\n\nTheorem pidgeon_hole_inj\n        (A B : finType)\n        (f : A -> B)\n        (inj : injective f)\n  : Cardinality A <= Cardinality B.\nProof.\n  rewrite <- (get_image_length f).\n  apply dup_free_length.\n  apply (injective_dupfree (elem A) inj).\nQed.\n\nLemma surj_sub\n      (A B : finType)\n      (f : A -> B)\n      (surj : surjective f)\n  : elem B <<= get_image f.\nProof.\n  intros y E.\n  specialize (surj y).\n  destruct surj as [x H].\n  subst y.\n  apply get_image_in.\nQed.\n\n\nLemma card_length_leq\n      (A : discType)\n      (xs : list A) : card xs <= length xs.\nProof.\n  induction xs ; repeat (crush ; dec).\nQed.\n\nTheorem pidgeon_hole_surj\n        (A B : finType)\n        (f : A -> B)\n        (surj : surjective f)\n  : Cardinality A >= Cardinality B.\nProof.\n  rewrite <- (get_image_length f).\n  rewrite <- Cardinality_card_eq.\n  pose proof (card_le (surj_sub surj)) as H.\n  pose proof (card_length_leq (get_image f)) as H'. omega.\nQed.\n\nLemma eq_iff (x y: nat) : x >= y /\\ x <= y -> x = y.\nProof.\n  omega.\nQed.\n\nCorollary pidgeon_hole_bij\n          (A B : finType)\n          (f : A -> B)\n          (bij : bijective f)\n  : Cardinality A = Cardinality B.\nProof.\n  destruct bij as [inj surj]. apply eq_iff. split.\n  -\n    now eapply pidgeon_hole_surj.\n  -\n    eapply pidgeon_hole_inj; eauto.\nQed.    \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/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7725537178526803}}
{"text": "(** * Imp: Simple Imperative Programs *)\n\n(** \"One man's code is another man's data.\"\n    (Alan Perlis) *)\n\n(** In this chapter, we take a more serious look at how to use Coq to\n    study other things.  Our case study is a _simple imperative\n    programming language_ called Imp, embodying a tiny core fragment\n    of conventional mainstream languages such as C and Java.  Here is\n    a familiar mathematical function written in Imp.\n\n       Z := X;\n       Y := 1;\n       while ~(Z = 0) do\n         Y := Y * Z;\n         Z := Z - 1\n       end\n*)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom 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 Import Maps.\n\n(* ################################################################# *)\n(** * Arithmetic and Boolean Expressions *)\n\n(** We'll present Imp in three parts: first a core language of\n    _arithmetic and boolean expressions_, then an extension of these\n    expressions with _variables_, and finally a language of _commands_\n    including assignment, conditions, sequencing, and loops. *)\n\n(* ================================================================= *)\n(** ** Syntax *)\n\nModule AExp.\n\n(** These two definitions specify the _abstract syntax_ of\n    arithmetic and boolean expressions. *)\n\n(* We want to define four kinds of arithmetic expressions:\n    + Natural Numbers\n    + Additions\n    + Subtractions\n    + Multiplications *)\n\nInductive aexp : Type :=\n  | ANum (n:nat)\n  | APlus (a:aexp) (b:aexp)\n  | AMinus (a:aexp) (b:aexp)\n  | AMult (a:aexp) (b:aexp).\n\n(* 1+2*3 --> concrete syntax *)\n(* APlus (ANum 1) (AMult (ANum 2) (ANum 3)) --> Abstract syntax*)  \n\n(* Boolean expressions:\n    + Booleans - true and false\n    + Equalities and inequalities of arithmetic expressions\n    + Negation and Conjunction*)\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a:aexp) (b:aexp) (* a =b*)\n  | BLe (a:aexp) (b:aexp) (* a <= b *)\n  | BNot (a:bexp)\n  | BAnd (a:bexp) (b:bexp). \n\n(** AST of [\"1 + 2 * 3\"] is\n      APlus (ANum 1) (AMult (ANum 2) (ANum 3)).\n*)\n\n\n\n\n\n\n(** For comparison, here's a conventional BNF (Backus-Naur Form)\n    grammar defining the same abstract syntax:\n\n    a := nat\n        | a + a\n        | a - a\n        | a * a\n\n    b := true\n        | false\n        | a = a\n        | a <= a\n        | ~ b\n        | b && b\n*)\n\n\n(* ================================================================= *)\n(** ** Evaluation *)\n\n(** _Evaluating_ an arithmetic expression produces a number. *)\n\nFixpoint aeval (a : aexp) : nat := \n  match a with\n  | ANum n => n\n  | APlus a b => (aeval a) + (aeval b)\n  | AMinus a b => (aeval a) - (aeval b)\n  | AMult a b => (aeval a) * (aeval b)\n  end.\n\n(* 2+2 --> 4*)\nExample test_aeval1:\n  aeval (APlus (ANum 2) (ANum 2)) = 4.\nProof. reflexivity. Qed.\n\n(** Similarly, evaluating a boolean expression yields a boolean. *)\n\nFixpoint beval (b : bexp) : bool := \n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a b => Nat.eqb (aeval a) (aeval b)\n  | BLe a b => Nat.leb (aeval a) (aeval b)\n  | BNot a => negb (beval a)\n  | BAnd a b => andb (beval a) (beval b)\n  end.\n\n(* ================================================================= *)\n(** ** Optimization *)\n\nFixpoint optimize_0plus (a:aexp) : aexp :=\n  match a with\n  | ANum n => ANum n\n  | APlus (ANum 0) e2 => optimize_0plus e2\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\n(** 2 + 0 + 0 + 1 = 2 + 1 *)\n\nExample 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).\nProof. simpl. reflexivity. Qed.\n\nTheorem optimize_0plus_sound: forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a. induction a.\n  - (* ANum *) reflexivity.\n  - (* APlus *) destruct a1 eqn:Ea1.\n    + (* a1 = ANum n *) destruct n eqn:En.\n      * (* n = 0 *)  simpl. apply IHa2.\n      * (* n <> 0 *) simpl. rewrite IHa2. reflexivity.\n    + (* a1 = APlus a1_1 a1_2 *)\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n    + (* a1 = AMinus a1_1 a1_2 *)\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n    + (* a1 = AMult a1_1 a1_2 *)\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n  - (* AMinus *)\n    simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - (* AMult *)\n    simpl. rewrite IHa1. rewrite IHa2. reflexivity.  \nQed.\n\n(* ################################################################# *)\n(** * Evaluation as a Relation *)\n\n(** We have presented [aeval] and [beval] as functions defined by\n    [Fixpoint]s.  Another way to think about evaluation -- one that we\n    will see is often more flexible -- is as a _relation_ between\n    expressions and their values.  This leads naturally to [Inductive]\n    definitions like the following one for arithmetic expressions... *)\n\n(** For example, [==>] is the smallest relation closed under these\n    rules:\n\n                             -----------                               (E_ANum)\n                             ANum n ==> n\n\n                               e1 ==> n1\n                               e2 ==> n2\n                         --------------------                         (E_APlus)\n                         APlus e1 e2 ==> n1+n2\n\n                               e1 ==> n1\n                               e2 ==> n2\n                        ---------------------                        (E_AMinus)\n                        AMinus e1 e2 ==> n1-n2\n\n                               e1 ==> n1\n                               e2 ==> n2\n                         --------------------                         (E_AMult)\n                         AMult e1 e2 ==> n1*n2\n*)\n\nModule aevalR_first_try.\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) :\n      aevalR (ANum n) n\n  | E_APlus: forall (e1 e2 : aexp) (n1 n2 : nat),\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (AMinus e1 e2) (n1 - n2)\n  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (AMult e1 e2) (n1 * n2).\n\n(** It will be convenient to have an infix notation for\n    [aevalR].  We'll write [e ==> n] to mean that arithmetic expression\n    [e] evaluates to value [n]. *)\n\nNotation \"e '==>' n\"\n         := (aevalR e n)\n            (at level 90, left associativity)\n         : type_scope.\n\nEnd aevalR_first_try.\n\nReserved Notation \"e '==>' n\" (at level 90, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) :\n      (ANum n) ==> n\n  | E_APlus (e1 e2 : aexp) (n1 n2 : nat) :\n      (e1 ==> n1) -> (e2 ==> n2) -> (APlus e1 e2)  ==> (n1 + n2)\n  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :\n      (e1 ==> n1) -> (e2 ==> n2) -> (AMinus e1 e2) ==> (n1 - n2)\n  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :\n      (e1 ==> n1) -> (e2 ==> n2) -> (AMult e1 e2)  ==> (n1 * n2)\n\n  where \"e '==>' n\" := (aevalR e n) : type_scope.\n\n\n(* ================================================================= *)\n(** ** Equivalence of the Definitions *)\n\n(** It is straightforward to prove that the relational and functional\n    definitions of evaluation agree: *)\n\nTheorem aeval_iff_aevalR : forall a n,\n  (a ==> n) <-> aeval a = n.\nProof.\n  split.\n  {\n    intros H. induction H.\n    + simpl. reflexivity.\n    + simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    + simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    + simpl. rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.    \n  }\n  {\n    generalize dependent n. induction a.\n    + simpl. intros. subst. apply E_ANum.\n    + simpl. intros. subst. apply E_APlus.\n      - apply IHa1. reflexivity.\n      - apply IHa2. reflexivity.\n    + simpl. intros. subst. apply E_AMinus.\n      - apply IHa1. reflexivity.\n      - apply IHa2. reflexivity.\n    + simpl. intros. subst. apply E_AMult.\n    - apply IHa1. reflexivity.\n    - apply IHa2. reflexivity.      \n  }\nQed.\n\nTheorem aeval_iff_aevalR' : forall a n,\n  (a ==> n) <-> aeval a = n.\nProof.\n  split.\n  {\n    intros H. induction H; simpl; try rewrite IHaevalR1; try rewrite IHaevalR2; reflexivity.\n  }\n  {\n    generalize dependent n. induction a; simpl; intros; subst; constructor;\n    try apply IHa1; try apply IHa2; reflexivity.\n  }\nQed.\n\n\n(* ================================================================= *)\n(** ** Computational vs. Relational Definitions *)\n\nModule aevalR_division.\n\n(** For example, suppose that we wanted to extend the arithmetic\n    operations with division: *)\n\nInductive 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).         (* <--- NEW *)\n\n(** Extending the definition of [aeval] to handle this new\n    operation would not be straightforward (what should we return as\n    the result of [ADiv (ANum 5) (ANum 0)]?).  But extending [aevalR]\n    is very easy. *)\n\nReserved Notation \"e '==>' n\"\n                  (at level 90, left associativity).\n\nInductive 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) -> (APlus a1 a2) ==> (n1 + n2)\n  | E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) -> (AMinus a1 a2) ==> (n1 - n2)\n  | E_AMult (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) -> (AMult a1 a2) ==> (n1 * n2)\n  | E_ADiv (a1 a2 : aexp) (n1 n2 n3 : nat) :          (* <----- NEW *)\n      \n\nwhere \"a '==>' n\" := (aevalR a n) : type_scope.\n\n(** Notice that the evaluation relation has now become _partial_:\n    There are some inputs for which it simply does not specify an\n    output. *)\n\nEnd aevalR_division.\n\nModule aevalR_extended.", "meta": {"author": "csci5535", "repo": "csci5535.github.io", "sha": "591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d", "save_path": "github-repos/coq/csci5535-csci5535.github.io", "path": "github-repos/coq/csci5535-csci5535.github.io/csci5535.github.io-591108aa7b2c74a2a53f55cc80ad47ff7dd0f26d/coq/MyImp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7725537096090567}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom VFA Require Import Perm.\n\nFixpoint insert (i:nat) (l: list nat) :=\nmatch l with\n| nil => i::nil\n| h::t => if i <=? h then i::h::t else h :: insert i t\nend.\n\nFixpoint sort (l: list nat) : list nat :=\nmatch 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]\n= [1;1;2;3;3;4;5;5;5;6;9].\nProof. hammer_hook \"Sort\" \"Sort.sort_pi\". simpl. reflexivity. Qed.\n\n\n\nEval compute in insert 7 [1; 3; 4; 8; 12; 14; 18].\n\n\n\n\n\n\n\n\n\nInductive sorted: list nat -> Prop :=\n| sorted_nil:\nsorted nil\n| sorted_1: forall x,\nsorted (x::nil)\n| sorted_cons: forall x y l,\nx <= y -> sorted (y::l) -> sorted (x::y::l).\n\n\n\nDefinition sorted' (al: list nat) :=\nforall i j, i < j < length al -> nth i al 0 <= nth j al 0.\n\n\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) :=\nforall al, Permutation al (f al) /\\ sorted (f al).\n\n\n\n\n\n\n\n\nSearch Permutation.\n\nLemma insert_perm: forall x l, Permutation (x::l) (insert x l).\nProof. hammer_hook \"Sort\" \"Sort.insert_perm\".\nAdmitted.\n\n\n\n\n\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof. hammer_hook \"Sort\" \"Sort.sort_perm\".\nAdmitted.\n\n\n\n\n\nLemma insert_sorted:\nforall a l, sorted l -> sorted (insert a l).\nProof. hammer_hook \"Sort\" \"Sort.insert_sorted\".\nAdmitted.\n\n\n\n\n\nTheorem sort_sorted: forall l, sorted (sort l).\nProof. hammer_hook \"Sort\" \"Sort.sort_sorted\".\nAdmitted.\n\n\n\n\nTheorem insertion_sort_correct:\nis_a_sorting_algorithm sort.\nProof. hammer_hook \"Sort\" \"Sort.insertion_sort_correct\".\nsplit. apply sort_perm. apply sort_sorted.\nQed.\n\n\n\n\n\n\n\nLemma sorted_sorted': forall al, sorted al -> sorted' al.\n\n\n\nAdmitted.\n\n\n\nLemma sorted'_sorted: forall al, sorted' al -> sorted al.\n\n\n\nProof. hammer_hook \"Sort\" \"Sort.sorted'_sorted\".\nAdmitted.\n\n\n\n\n\n\n\n\nLemma Forall_nth:\nforall {A: Type} (P: A -> Prop) d (al: list A),\nForall P al <-> (forall i,  i < length al -> P (nth i al d)).\nProof. hammer_hook \"Sort\" \"Sort.Forall_nth\".\nAdmitted.\n\n\n\n\nLemma insert_sorted':\nforall a l, sorted' l -> sorted' (insert a l).\nAdmitted.\n\n\n\nTheorem sort_sorted': forall l, sorted' (sort l).\nAdmitted.\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/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7725537080364281}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\n\n(*\n *\n * the BNF grammar for this simple language:\n *\n *  <exp> ::= \n *         |  <X>\n *         |  <exp> + <exp>\n *         |  <exp> * <exp>\n *         |  <exp> < <exp>\n *         |  <integer contant>\n *         |  (<exp>)\n *\n *  <cmd> ::= \n *         |  skip\n *         |  <X> = <exp>\n *         |  ifNZ <exp> { <cmd> } else { <cmd> }\n *         |  whileNZ <exp> { <cmd> }\n *         |  <cmd>; <cmd>\n *\n *)\n\nDefinition name := string.\n\n(* Abstract syntax of arithmetic expressions *)\nInductive exp : Type :=\n  Var : name -> exp\n| Add : exp  -> exp -> exp\n| Dec : exp  -> exp\n| Mul : exp  -> exp -> exp\n| Lt  : exp  -> exp -> exp\n| Lit : nat    -> exp.\n\nDefinition arith : exp := Mul (Lit 3) (Add (Lit 4) (Lit 5)).\n\n(* Abstract syntax of commands *)\nInductive cmd : Type :=\n  Skip    : cmd\n| Assn    : name -> exp -> cmd\n| IfNZ    : exp  -> cmd -> cmd -> cmd\n| WhileNZ : exp  -> cmd -> cmd\n| Seq     : cmd  -> cmd -> cmd.\n\nDefinition X := String \"X\" EmptyString.\nDefinition ANS := String \"A\" (String \"N\" (String \"S\" EmptyString)).\n\nDefinition factorial : cmd :=\n  let x := \"X\"%string in\n  let ans := \"ANS\"%string in\n  Seq (Assn x (Lit 6))\n      (Seq (Assn ans (Lit 1))\n           (WhileNZ (Var x)\n                    (Seq (Assn ans (Mul (Var ans) (Var x)))\n                         (Assn x (Dec (Var x)))))).\n      \n(* Interpreter *)\n\nDefinition state := name -> nat.\nDefinition init_state := fun x : name => 0.\n\nFixpoint beq_string (s1 s2 : string) : bool :=\n  match s1, s2 with\n    | EmptyString, EmptyString => true\n    | EmptyString, String _ _  => false\n    | String _ _, EmptyString  => false\n    | String h1 t1, String h2 t2 =>\n      if beq_nat (nat_of_ascii h1) (nat_of_ascii h2)\n      then beq_string t1 t2\n      else false\n  end.\n\nNotation \"x == y\" := (beq_string x y) (at level 60).\n\nDefinition update (s : state) (x : name) (v : nat) :=\n  fun (y : name) => if x == y then v else s y.\n\nFixpoint bl_nat (n m : nat) : bool :=\n  match n, m with\n    | O, O       => false\n    | O, S _     => true\n    | S _, O     => false\n    | S n1, S m1 => bl_nat n1 m1\n  end.\n\nFixpoint neq_nat (n m : nat) : bool :=\n  match n, m with\n    | O, O       => false\n    | O, S _     => true\n    | S _, O     => true\n    | S n1, S m1 => neq_nat n1 m1\n  end.\n\nFixpoint interpret_exp (s : state) (e : exp) : nat :=\n  match e with\n    | Var x     => s x\n    | Add e1 e2 => (interpret_exp s e1) + (interpret_exp s e2)\n    | Dec e     => (interpret_exp s e) - 1\n    | Mul e1 e2 => (interpret_exp s e1) * (interpret_exp s e2)\n    | Lt  e1 e2 => if (bl_nat (interpret_exp s e1) (interpret_exp s e2)) then 1 else 0\n    | Lit i     => i\n  end.\n\nFixpoint interpret_cmd (s : state) (c : cmd) (i : nat) : state :=\n  match i with\n    | O    => s\n    | S i' => \n      match c with\n        | Skip         => s\n        | Assn x e     => update s x (interpret_exp s e)\n        | IfNZ e c1 c2 =>\n          if (neq_nat (interpret_exp s e) 0) then interpret_cmd s c1 i' else interpret_cmd s c2 i'\n        | WhileNZ e c  =>\n          interpret_cmd s (IfNZ e (Seq c (WhileNZ e c)) Skip) i'\n        | Seq c1 c2    =>\n          let s1 := interpret_cmd s c1 i' in\n          interpret_cmd s1 c2 i'\n      end\n  end.\n\nCompute (interpret_cmd init_state factorial 1000) \"ANS\"%string = 720.\n\nCompute (interpret_cmd init_state (Seq (Assn \"X\"%string (Lit 6)) (Assn \"X\"%string (Dec (Var \"X\"%string)))) 10) \"X\"%string = 5.\n\nCompute \"123\"%string == \"122\"%string = false.\n", "meta": {"author": "zjhmale", "repo": "MFCS", "sha": "e82b0e2425b4988ce8dfc558901ae2e76e1b23f1", "save_path": "github-repos/coq/zjhmale-MFCS", "path": "github-repos/coq/zjhmale-MFCS/MFCS-e82b0e2425b4988ce8dfc558901ae2e76e1b23f1/simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7724926299142872}}
{"text": "Theorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  (* use assert instead of rewriting lemma plus_O_n *)\n  assert (H : 0 + n = n).\n  {\n    reflexivity.\n  }\n  rewrite -> H.\n  reflexivity.\nQed.\n\nAxiom plus_comm : forall m n : nat, m + n = n + m.\n\nTheorem plus_rearrange_firsttry : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  (* We just need to swap (n + m) for (m + n)... seems\n     like plus_comm should do the trick! *)\n  rewrite <- plus_comm.\n  (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\nTheorem plus_rearrange_mytry : 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 n should do the trick! *)\n  rewrite <- (plus_comm n).\n  reflexivity.\nQed.\n\nTheorem plus_rearrange_their_try : 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 : m + n = n + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite -> H.\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/2_Induction/2_proofs_within_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7724926278601802}}
{"text": "Inductive SNat : nat -> Type :=\n| SZ : SNat 0\n| SS : forall (n:nat), SNat n -> SNat (S n)\n.\n\nArguments SS {n}.\n\nFixpoint inj (n:nat) : SNat n :=\n    match n with\n    | 0     => SZ\n    | S n   => SS (inj n)\n    end.\n\n\nDefinition f n : SNat n := inj n.\n\nDefinition g : forall (n:nat), SNat n := fun n => inj 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/Definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7724754976901625}}
{"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\nRequire Export IndProp.\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  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\nTheorem total_relation_not_partial : ~ (partial_function total_relation).\nProof. unfold partial_function. intros H.\n  assert (0 = 1) as Nonsense. {\n    apply H with (x := 0).\n    - apply te.\n    - apply te. }\n  inversion Nonsense. Qed.\n\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. *)\nTheorem empty_relation_partial : partial_function empty_relation.\nProof. unfold partial_function. intros x y1 y2 H. inversion H. Qed.\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' IH].\n  - constructor. apply Hnm. \n  - constructor. apply IHIH. Qed.\n\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 H1 H2.\n  induction o as [| o'].\n  - inversion H2.\n  - apply le_trans with (b:=(S m)). \n    + constructor. apply H1.\n    + apply H2.\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, optional (le_S_n)  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof. intros n m H. inversion H.\n  - constructor.\n  - apply le_trans with (S n).\n    + constructor. constructor.\n    + apply H1.\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    writing an informal proof without doing the formal proof first.\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. intros n H. induction n as [|n IH].\n  - inversion H.\n  - apply IH. apply le_S_n. apply H. Qed.\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, optional (le_not_symmetric)  *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof. unfold symmetric. intros H. \n  assert (1 <= 0) as Nonsense.\n    apply H. constructor. constructor.\n  inversion Nonsense. Qed.  \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\nCheck le_ind.\n(** **** Exercise: 2 stars, optional (le_antisymmetric)  *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof. intros n m H1 H2. \n  inversion H1.\n  - reflexivity.\n  - apply n_le_m__Sn_le_Sm in H. rewrite H0 in H. \n    exfalso. apply (le_Sn_n n). apply le_trans with m.\n    apply H. apply H2. Qed.\n  \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. intros. apply le_S_n. apply le_trans with m.\n  apply H. apply H0. Qed.\n\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. intros. induction H as [|x y'].\n  - apply H0. \n  - apply rt1n_trans with y'. \n    + apply H.\n    + apply IHclos_refl_trans_1n. apply H0. Qed.\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. intros X R x y. split.\n  - intros H. induction H.\n    + apply rsc_R. apply H.\n    + constructor.\n    + apply rsc_trans with y. \n      * apply IHclos_refl_trans1.\n      * apply IHclos_refl_trans2.\n  - intros H. induction H. \n    + apply rt_refl.\n    + apply rt_trans with y. \n      * constructor. apply H.\n      * apply IHclos_refl_trans_1n.\nQed.\n    \n\n(** [] *)\n\n", "meta": {"author": "kolya-vasiliev", "repo": "logical-foundations-2018", "sha": "1486b6748963514bc281672a93d408ac830ae0d0", "save_path": "github-repos/coq/kolya-vasiliev-logical-foundations-2018", "path": "github-repos/coq/kolya-vasiliev-logical-foundations-2018/logical-foundations-2018-1486b6748963514bc281672a93d408ac830ae0d0/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.7723978928307088}}
{"text": "Require Import Datatypes.\nFrom MyCoq.Lib Require Export Bool.\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\n\nFixpoint N (n : Datatypes.nat) : nat :=\n  match n with\n  | 0 => O\n  | Datatypes.S m => S (N m)\n  end.\n\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\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 :=\n  negb (evenb n).\n\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 ltb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n          | O => false\n          | _ => true\n          end\n  | S n' => match m with\n            | O => false\n            | S m' => ltb 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\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 minus (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | _, O => n\n  | S n', S m' => minus n' m'\n  end.\n\nFixpoint mult (n m : nat) : nat :=\n  match n, m with\n  | O, _ => O\n  | S n', m => plus m (mult n' m)\n  end.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S power' => mult base (exp base power')\n  end.\n\n\nNotation \"x =? y\" := (eqb x y) (at level 70, no associativity).\n\nNotation \"x <? y\" := (ltb x y) (at level 70, no associativity).\n\nNotation \"x <=? y\" := (leb x y) (at level 70, no associativity).\n\n\nNotation \"x + y\" := (plus x y) (at level 50, left associativity).\n\nNotation \"x - y\" := (minus x y) (at level 50, left associativity).\n\nNotation \"x * y\" := (mult x y) (at level 40, left associativity).\n\n\nTheorem plus_O_n: forall n : nat,\n  O + n = n.\nProof.\n  reflexivity.\nQed.\n\nTheorem plus_n_O: forall n : nat,\n  n + O = n.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_n_Sm: forall n m : nat,\n  n + S m = S (n + m) .\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  (* + 的定义 *)\n  - simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\n(* 加法交换律 *)\nTheorem plus_comm: forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - rewrite plus_O_n.\n    rewrite plus_n_O.\n    reflexivity.\n  - simpl.\n    rewrite plus_n_Sm.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\n(* 加法结合律 *)\nTheorem plus_assoc: forall a b c : nat,\n  a + b + c = a + (b + c).\nProof.\n  intros a b c.\n  induction a as [| a' IHa'].\n  - reflexivity.\n  (* 两次应用 + 的定义 *)\n  - simpl.\n    rewrite IHa'.\n    reflexivity.\nQed.\n\nTheorem mult_O_n: forall n : nat,\n  O * n = O.\nProof.\n  reflexivity.\nQed.\n\nTheorem mult_n_O: forall n : nat,\n  n * O = O.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_n_Sm: forall n m : nat,\n  n * m + n = n * S m.\nProof.\n  intros n m.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  (* * 的定义以及 + 的定义 *)\n  - simpl.\n    rewrite <- IHn'.\n    rewrite -> plus_n_Sm.\n    rewrite <- plus_assoc.\n    reflexivity.\nQed.\n\n(* 乘法交换律 *)\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros n m.\n  induction m as [| m' IHm'].\n  - rewrite mult_n_O.\n    reflexivity.\n  - rewrite <- mult_n_Sm.\n    simpl.\n    rewrite IHm'.\n    rewrite plus_comm.\n    reflexivity.\nQed.\n\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (n : bin) : bin :=\n  match n with\n  | Z => B Z\n  | A n' => B n'\n  | B n' => A (incr n')\n  end.\n\nFixpoint bin_to_nat (n : bin) : nat :=\n  match n with\n  | Z => O\n  | A n' => (N 2) * (bin_to_nat n')\n  | B n' => (N 1) + (N 2) * (bin_to_nat n')\n  end.\n\nFixpoint nat_to_bin (n : nat) : bin :=\n  match n with\n  | O => Z\n  | S n' => incr (nat_to_bin n')\n  end.\n\n\nTheorem self_eq: forall n : nat,\n  n =? n = true.\nProof.\n  induction n as [| n'].\n  - reflexivity.\n  - simpl.\n    rewrite IHn'.\n    reflexivity.\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\nFixpoint double (n : nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\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 IHn'].\n  - induction p as [| p IHp'].\n    + reflexivity.\n    + reflexivity.\n  - simpl.\n    assert (H: p + n * p + m * p = p + (n * p + m * p)).\n    {\n      rewrite -> plus_assoc.\n      reflexivity.\n    }\n    rewrite -> H.\n    rewrite <- IHn'.\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' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> mult_plus_distr_r.\n    rewrite IHn'.\n    reflexivity.\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/Lib/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7722089029789198}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\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 Lia.\nFrom Coq Require Export Lists.List.\nExport ListNotations.\nFrom Coq Require Export Permutation.\n\n\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]  = [1;1;2;3;3;4;5;5;5;6;9].\nProof. simpl. reflexivity. Qed.\n\n\n\nInductive sorted : list nat -> Prop :=\n| sorted_nil  : sorted []\n| sorted_1    : forall x, sorted [x]\n| sorted_cons : forall x y l,\n    x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nDefinition sorted'' (al : list nat) := forall i j,\n    i < j < length al ->\n    nth i al 0 <= nth j al 0.\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\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) := forall al,\n    Permutation al (f al) /\\ sorted (f al).\n\n\n\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\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.\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.\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\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\nLtac bdestruct X :=\n  let H := fresh     in\n  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\n\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l S. \n  induction S; simpl.\n  - constructor.\n  - bdestruct (a <=? x).\n    + apply sorted_cons.\n        assumption.\n        constructor.\n    + apply sorted_cons.\n        lia.\n        constructor.\n  - bdestruct (x >=? a).\n    + apply sorted_cons; try lia.\n      apply sorted_cons; try lia.\n      assumption.\n    + simpl in IHS.\n      bdestruct (y >=? a).\n      * apply sorted_cons; try lia.\n        assumption.\n      * apply sorted_cons; try lia.\n        assumption.\nQed.\n\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n  intro l.\n  induction l; simpl.\n  - constructor.\n  - apply insert_sorted.\n    assumption.\nQed.\n\nPrint Permutation.\nSearch Permutation.\n\nLemma insert_perm: forall x l,\n    Permutation (x :: l) (insert x l).\nProof.\n  intros x l.\n  induction l; simpl.\n  - constructor. constructor.\n  - bdestruct (a >=? x).\n    + apply Permutation_refl.\n    + apply perm_trans with (a :: x :: l).\n      * apply perm_swap.\n      * constructor.\n        assumption.\nQed.\n\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.\n  intro l.\n  induction l; simpl.\n  - constructor.\n  - apply perm_trans with (a :: sort l).\n    + constructor. assumption.\n    + apply insert_perm.\nQed.\n\nTheorem insertion_sort_correct:\n    is_a_sorting_algorithm sort.\nProof.\n  split.\n  - apply sort_perm.\n  - apply sort_sorted.\nQed.\n\n\n\nLemma less_than_all_sorted: forall x y l,\n  x <= y -> sorted' (y :: l) -> \n  forall i iv, nth_error (y :: l) i = Some iv -> x <= iv.\nProof.\n  intros x y l Hxy Hsorted.\n  unfold sorted' in Hsorted.\n  intro i.\n  induction i.\n  - simpl. intros iv H'. injection H' as H'.\n    subst. assumption.\n  - simpl. intros iv H'.\n    assert (y <= iv). {\n      apply (Hsorted 0 (S i) y iv).\n      + lia.\n      + reflexivity.\n      + simpl. apply H'.\n    }\n    lia.\nQed.\n\nLemma sorted_sorted': forall al, sorted al -> sorted' al.\nProof.\n  intros al.\n  induction al; simpl; intro Hsorted.\n  - intros i j iv jv Hind H1 H2.\n    destruct i; simpl in H1; discriminate H1.\n  - inversion Hsorted; subst.\n    + intros i j iv jv Hind H1 H2.\n      destruct i; inversion Hind; subst.\n      -- discriminate H2.\n      -- simpl in H2.\n         destruct m; simpl in H2; discriminate H2.\n      -- discriminate H2.\n      -- simpl in H2.\n         destruct m; simpl in H2; discriminate H2.\n    + intros i j iv jv Hind H1' H2'.\n      destruct i; destruct j.\n      * lia.\n      * apply IHal in H2. clear IHal.\n        simpl in H1', H2'.\n        injection H1' as H1'; subst.\n        induction j.\n        -- simpl in H2'. injection H2' as H2'; subst.\n           assumption.\n        -- apply (less_than_all_sorted _ _ _ H1 H2  (S j) jv H2').\n      * lia.\n      * simpl in H1', H2'.\n        apply (IHal H2 i j iv jv).\n        -- lia.\n        -- apply H1'.\n        -- apply H2'.\nQed.\n\nLemma sorted_tail: \n  forall a l, sorted' (a :: l) -> sorted' l.\nProof.\n  intros a l H i j iv jv Hilj Hiv Hjv.\n  apply (H (S i) (S j) iv jv).\n  - lia.\n  - simpl. apply Hiv.\n  - simpl. apply Hjv.\nQed.\n\nLemma sorted'_sorted : forall al, sorted' al -> sorted al.\nProof.\n  intro al.\n  induction al.\n  - intro H. constructor.\n  - intro H.\n    destruct al as [ | alh alt].\n    + constructor.\n    + apply sorted_cons.\n      * unfold sorted' in H.\n        apply (H 0 1).\n          lia.\n          reflexivity.\n          reflexivity.\n      * apply IHal.\n        apply sorted_tail with a.\n        apply H.\nQed.\n\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  intro l.\n  induction l; simpl; intros a' i iv H.\n  - destruct i; try (destruct i; discriminate H).\n    simpl in H. injection H as H.\n    left.\n    assumption.\n  - bdestruct (a >=? a').\n    + destruct i.\n      * simpl in H. injection H as H.\n        left.\n        assumption.\n      * simpl in H.\n        right. exists i. apply H.\n    + destruct i.\n      * simpl in H. injection H as H. subst.\n        right.\n        exists 0. reflexivity.\n      * simpl in H.\n        assert (G: a' = iv \\/ (exists i' : nat, nth_error l i' = Some iv)). {\n          eapply IHl.\n          apply H.\n        }\n        destruct G as [Gl | [gi Gr]].\n        -- left. assumption.\n        -- right. exists (S gi). simpl. assumption.\nQed.\n\nLemma less_than_all_sorted': forall x y l,\n  x < y -> sorted' (y :: l) -> \n  forall i iv, nth_error (y :: l) i = Some iv -> x < iv.\nProof.\n  intros x y l Hxy Hsorted.\n  unfold sorted' in Hsorted.\n  intro i.\n  induction i.\n  - simpl. intros iv H'. injection H' as H'.\n    subst. assumption.\n  - simpl. intros iv H'.\n    assert (y <= iv). {\n      apply (Hsorted 0 (S i) y iv).\n      + lia.\n      + reflexivity.\n      + simpl. apply H'.\n    }\n    lia.\nQed.\n\nLemma remove_second_in_sorted: forall v v' l, sorted' (v :: v' :: l) -> sorted' (v :: l).\nProof.\n  intros v v' l Hsorted i j vi vj Lij Hi Hj.\n  destruct i; destruct j.\n  - lia.\n  - simpl in *.\n    injection Hi as Hi; subst.\n    apply (Hsorted 0 (S (S j)) vi vj).\n    + lia.\n    + reflexivity.\n    + simpl. apply Hj.\n  - lia.\n  - simpl in *.\n    apply (Hsorted (S (S i)) (S (S j)) vi vj).\n    + lia.\n    + simpl. apply Hi.\n    + simpl. apply Hj.\nQed.\n\nLemma less_than_insert_to_tail: forall l v a,\n  sorted' (v :: l) -> \n  a > v -> \n  forall i v', nth_error (insert a l) i = Some v' -> (v <= v').\nProof.\n  intro l.\n  induction l; simpl; intros v a' Hsorted La'v i v' H.\n  - destruct i; simpl in H.\n    + injection H as H; subst. lia.\n    + destruct i; discriminate H.\n  - bdestruct (a >=? a').\n    + destruct i; simpl in H.\n      * injection H as H; subst. lia.\n      * apply (less_than_all_sorted v a l) with i.\n        -- lia.\n        -- apply sorted_tail with v. apply Hsorted.\n        -- apply H.\n    + destruct i; simpl in H.\n      * injection H as H; subst.\n        apply (Hsorted 0 1 v v').\n        -- lia.\n        -- reflexivity.\n        -- reflexivity.\n      * apply (IHl v a') with i.\n        -- apply (remove_second_in_sorted _ _ _ Hsorted).\n        -- assumption.\n        -- apply H.\nQed.\n\nLemma insert_sorted':\n  forall a l, sorted' l -> sorted' (insert a l).\nProof.\n  intros a l H.\n  induction l.\n  - simpl.\n    unfold sorted'.\n    intros i j iv jv Lij Hiv Hvj.\n    destruct i; destruct j.\n    + lia.\n    + simpl in *. destruct j; discriminate Hvj.\n    + lia.\n    + simpl in *. destruct j; discriminate Hvj.\n  - simpl.\n    bdestruct (a0 >=? a).\n    + unfold sorted'.\n      intros i j iv jv Lij Hiv Hvj.\n      destruct i; destruct j; try lia.\n      * simpl in *.\n        injection Hiv as Hiv; subst.\n        apply (less_than_all_sorted iv a0 l H0 H j).\n        assumption.\n      * simpl in *.\n        apply (H i j iv jv).\n        -- lia.\n        -- apply Hiv.\n        -- apply Hvj.\n    + intros i j iv jv Lij Hiv Hvj.\n      destruct i; destruct j; try lia.\n      * simpl in *.\n        injection Hiv as Hiv; subst.\n        apply (less_than_insert_to_tail _ _ _ H H0 j jv Hvj).\n      * simpl in *.\n        apply sorted_tail in H.\n        apply IHl in H.\n        apply (H i j iv jv).\n        -- lia.\n        -- apply Hiv.\n        -- apply Hvj.\nQed.\n\nLtac inv H := inversion H; clear H; subst.\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", "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/vol3_vfa/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.868826769445233, "lm_q1q2_score": 0.7721774364860109}}
{"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(*                               Lib_Mult.v                                 *)\n(****************************************************************************)\n\nRequire Export Lib_Plus.\n\nLemma plus_mult : forall n : nat, n + n = 2 * n.\nintros n; simpl in |- *; elim plus_n_O; auto with arith.\nQed.\nHint Resolve plus_mult.\n\n\nLemma lt_mult_lt_O : forall n m : nat, 0 < n * m -> 0 < m -> 0 < n.\nsimple induction n; auto with arith.\nQed.\n\n\nLemma le_mult_cst : forall x y a : nat, x <= y -> a * x <= a * y.\nauto with arith.\nQed.\n\n\n\nLemma le_mult_csts : forall a b c d : nat, a <= b -> c <= d -> a * c <= b * d.\nintros.\napply le_trans with (a * d).\napply le_mult_cst; assumption.\nelim mult_comm; elim mult_comm with d b.\napply le_mult_cst; assumption.\nQed.\nHint Resolve le_mult_csts.\n\n\n\nLemma lt_mult_n_Sn : forall n m : nat, 0 < m -> n * m < S n * m.\nsimple induction n; simple induction m; auto with arith.\nintros; simpl in |- *.\nelim plus_n_O; auto with arith.\nintro.\nelim mult_n_O; elim mult_n_O; auto with arith.\nintros; simpl in |- *; apply lt_n_S; auto with arith.\nQed.\nHint Resolve lt_mult_n_Sn.\n\n\n\nLemma lt_mult_cst : forall x y a : nat, x < y -> 0 < a -> a * x < a * y.\nintros.\nelim H.\nelim mult_comm; elim mult_comm with (S x) a.\napply lt_mult_n_Sn; assumption.\nintros.\napply lt_trans with (a * m).\nassumption.\nelim mult_comm; elim mult_comm with (S m) a.\napply lt_mult_n_Sn; assumption. \nQed.\nHint Resolve lt_mult_cst.\n\n\n\nLemma lt_mult_csts : forall a b c d : nat, a < b -> c < d -> a * c < b * d.\nintros.\napply le_lt_trans with (a * d).\napply le_mult_cst.\napply lt_le_weak; assumption.\nelim mult_comm; elim mult_comm with d b.\napply lt_mult_cst.\nassumption.\napply lt_O with c; auto with arith.\nQed.\nHint Resolve lt_mult_csts.\n\n\n\nLemma pred_mult : forall n m : nat, 0 < n -> n * m = pred n * m + m.\nintros.\nelim H; simpl in |- *; auto with arith.\nQed.\nHint Resolve pred_mult.\n\n\n\nLemma le_lt_plus_mult :\n forall n m p n' p' : nat, n <= n' -> p < p' -> n * m + p < n' * m + p'.\nintros; apply le_lt_plus; auto with arith.\nQed.\n\n\n\nLemma le_mult_l : forall n m : nat, 0 < m -> n <= m * n.\nintros.\nrewrite (S_pred m 0); trivial with arith.\nsimpl in |- *; auto with arith.\nQed.\nHint Resolve le_mult_l.\n\n\n\nLemma le_mult_r : forall n m : nat, 0 < m -> n <= n * m.\nintros n m; elim (mult_comm m n); auto with arith.\nQed.\nHint Resolve le_mult_r.\n\n\n\nLemma lt_mult : forall n m : nat, 1 < m -> 0 < n -> n < n * m.\nintros.\npattern n at 1 in |- *.\nelim mult_1_r.\napply lt_mult_cst; auto with arith.\nQed.\nHint Resolve lt_mult.\n\n\n\nLemma lt_SO_mult : forall n m : nat, 1 < n -> 0 < m -> 1 < n * m.\nintros.\napply lt_le_trans with (1 * n).\nauto with arith.\nsimpl in |- *.\nelim plus_n_O.\napply le_mult_r; auto with arith.\nQed.\n\n\n\nLemma plus_m_mult_n_m : forall n m : nat, m + n * m = S n * m.\nsimple induction n; simple induction m; simpl in |- *; auto with arith.\nQed.\n\n\n\nLemma y_eq_multxy : forall x y : nat, x = 1 \\/ y = 0 -> y = x * y.\nintros x y H; elim H; clear H; intros H; rewrite H; simpl in |- *;\n auto with arith.\nQed.\n\n\n\nLemma mult_plus_distr_left : forall n m p : nat, p * (n + m) = p * n + p * m.\nintros; elim mult_comm.\nelim (mult_comm n p).\nelim (mult_comm m p).\nauto with arith.\nQed.\nHint Resolve mult_plus_distr_left.\n\n\n\nLemma mult_minus_distr_left : forall n m p : nat, p * (n - m) = p * n - p * m.\nintros.\nrewrite (mult_comm p (n - m)); rewrite (mult_comm p n);\n rewrite (mult_comm p m); auto with arith.\nQed.\nHint Resolve mult_minus_distr_left.\n\n\n\nLemma mult_eq_zero : forall a b : nat, a * b = 0 -> a = 0 \\/ b = 0.\nintros a b; elim a.\nauto with arith.\nintros n H_rec H.\nright.\nelim (plus_eq_zero (n * b) b); auto with arith.\nsimpl in H; elim plus_comm.\nauto with arith.\nQed. \nHint Resolve mult_eq_zero.\n\n\n\nLemma lt_mult_S_S : forall n m : nat, 0 < S n * S m.\nsimple induction n; simpl in |- *; auto with arith.\nQed.\nHint Resolve lt_mult_S_S.\n\n\n\nLemma mult_S_O : forall n m : nat, 0 = S n * m -> 0 = m.\nintros n m H.\nelim (mult_eq_zero (S n) m); auto with arith.\nintro; absurd (S n = 0); auto with arith.\nQed.\n\n\n\nLemma mult_reg_l : forall a b p : nat, p * a = p * b -> p = 0 \\/ a = b.\nintros a b p; generalize b; generalize a; clear a b.\nsimple induction a.\nreplace (p * 0) with 0.\nintros.\ncut (p = 0 \\/ b = 0).\nintro.\nelim H0; auto with arith.\ncut (p * b = 0).\nelim (mult_eq_zero p b); auto with arith.\nauto with arith.\napply mult_n_O.\nintros n H_rec.\nsimple induction b.\nreplace (p * 0) with 0.\nintro.\napply (mult_eq_zero p (S n) H).\napply mult_n_O.\nintros m H.\nreplace (p * S n) with (p * n + p).\nreplace (p * S m) with (p * m + p).\n2: apply mult_n_Sm.\n2: apply mult_n_Sm.\nclear a; clear b.\nintro.\nelim (H_rec m); auto with arith.\napply (fun a b : nat => plus_reg_l a b p).\nelim (plus_comm (p * n) p).\nelim (plus_comm (p * m) p); trivial with arith.\nQed.\nHint Resolve mult_reg_l.\n\n\n\n\nLemma mult_reg_l_bis : forall a b p : nat, 0 < p -> p * a = p * b -> a = b.\nintros a b p H H1.\nelim (mult_reg_l a b p); auto with arith.\nintro; absurd (p = 0); auto with arith.\nQed.\nHint Immediate mult_reg_l_bis.\n\n\n\nLemma mult_eq_zero_bis : forall a b : nat, 0 < a -> a * b = 0 -> b = 0.\nintros a b pos H.\nelim (mult_eq_zero a b H); auto with arith.\nintro h.\nabsurd (a = 0); auto with arith.\nQed. \nHint Immediate mult_eq_zero_bis.\n\n\n\nLemma lt_nm_mult : forall n m : nat, 0 < n -> 0 < m -> 0 < n * m.\nintros n m H1 H2.\nelim H1; elim H2; simpl in |- *; auto with arith.\nQed.\nHint Resolve lt_nm_mult.\n \n\n\nLemma same_quotient_order :\n forall b q q' r r' : nat, r < b -> q < q' -> q * b + r < q' * b + r'.\nintros.\napply lt_le_trans with (q * b + b).\napply plus_lt_compat_l.\ntry trivial with arith.\npattern b at 2 in |- *.\nreplace b with (1 * b).\nelim mult_plus_distr_r.\napply le_trans with (q' * b).\nelim (mult_comm b (q + 1)); elim (mult_comm b q').\napply le_mult_cst.\nreplace (q + 1) with (S q).\nauto with arith.\nelim plus_comm; simpl in |- *; auto with arith.\nauto with arith.\nsimpl in |- *; auto with arith. \nQed.\nHint Resolve same_quotient_order.\n\n(************************************************************************)\n", "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/Libraries/Lib_Arithmetic/Lib_Mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7721548135583217}}
{"text": "Require Import String Arith List Lia.\nImport ListNotations.\n\n(* \nFirst, we will define name as we did in the lecture notes.\n*)\nDefinition var := string.\n\n(* \nThen we need to define the labels for the in and out. \n*)\nInductive label :=\n    | In (name: var)\n    | Out (name: var)\n.\n\n(* \nAnd we need to define actions including the internal action, Tau.\n *)\nInductive action :=\n    | Label (l: label)\n    | Tau\n.\n\nDefinition complement (a: action) : action :=\n    match a with\n    | Label (In n) => Label (Out n)\n    | Label (Out n) => Label (In n)\n    | Tau => Tau\nend.\n\nDefinition action_eq (a b: action) : bool :=\n    match a with \n    | Label (In n) => match b with\n                        | Label (In m) => eqb n m\n                        | _ => false\n                        end\n    | Label (Out n) => match b with\n                        | Label (Out m) => eqb n m\n                        | _ => false\n                        end\n    | Tau => match b with \n                | Tau => true\n                | _ => false\n                end\nend.\n\n    \n(* \nWe can now define all of our proess expressions as we did in the lecture notes.\n *)\nInductive expr :=\n    | Skip \n    | Const (v: var) (e: expr)\n    | Action (a: action) (e: expr)\n    | Sum (e1 e1: expr)\n    | Comp (e1 e2: expr)\n    | Rest (e: expr) (a: action)\n    | Relab (e: expr) (from to: label)\n.\n\n(* \nNow, let's define our labelling transition step semantics.\n *)\nInductive expr_step: expr -> action -> expr -> Prop :=\n    (* The name of the constant can step to the same place that the expression can step *)\n    | expr_step_const               : forall (v: var) (e1 e2: expr) (a: action),\n                                        expr_step e1 a e2 ->\n                                        expr_step (Const v e1) a e2\n\n    (* The action describes the step that can be taken *)\n    | expr_step_act                 : forall (e: expr) (a: action),\n                                        expr_step (Action a e) a e\n\n    (* If the left side of a sum can take a step, then the entire expression can take a step there *)\n    | expr_step_sum_left            : forall (e1 e1' e2: expr) (a: action),\n                                        expr_step e1 a e1' ->\n                                        expr_step (Sum e1 e2) a e1'\n\n    (* If the right side of a sum can take a step, then the entire expression can take a step there *)\n    | expr_step_sum_right           : forall (e1 e2 e2': expr) (a: action),\n                                        expr_step e2 a e2' ->\n                                        expr_step (Sum e1 e2) a e2'\n    \n    \n    (* If the left side of a composition can take a step, then the entire expression can take a step there where the left side is modified *)                                \n    | expr_step_comp_left           : forall (e1 e1' e2: expr) (a: action),\n                                        expr_step e1 a e1' ->\n                                        expr_step (Comp e1 e2) a e1'\n    \n    (* If the right side of a composition can take a step, then the entire expression can take a step there where the right side is modified *)                                \n    | expr_step_comp_right          : forall (e1 e2 e2': expr) (a: action),\n                                        expr_step e2 a e2' ->\n                                        expr_step (Comp e1 e2) a e2'   \n    \n    (* If the actions are internal to the composition, we can step to the next composite expression with tau *)\n    | expr_step_comp_internal       : forall (e1 e1' e2 e2': expr) (a: action),\n                                        expr_step e1 a e1' ->\n                                        expr_step e2 (complement a) e2' ->\n                                        expr_step (Comp e1 e2) Tau (Comp e1' e2')\n\n    (* The step is preserved as long as the label being restricted isn't the being restricted *)\n    | expr_step_res                 : forall (e1 e2: expr) (a b: action),\n                                        (action_eq Tau b) = false ->\n                                        (action_eq a b) = false -> \n                                        (action_eq (complement a) b) = false ->\n                                        expr_step e1 a e2 ->\n                                        expr_step (Rest e1 b) a (Rest e2 b)\n\n    (* If you can step between two expressions, then you can step to the relabeling of that action taking into account the relabelling of the state it can step to *)\n    | expr_step_rel                 : forall (e1 e2: expr) (a b: label),\n                                        expr_step e1 (Label a) e2 ->\n                                        expr_step (Relab e1 a b) (Label b) (Relab e2 a b)\n    .\n\n(* \nLet's work through the example we did in the lecture notes.\n*)\nExample class_example:\n    forall (e f: expr) (a b: label),\n        expr_step (Rest (Comp (Sum (Action (Label a) e) (Action (Label b) Skip)) (Action (complement (Label a)) f)) (Label a)) Tau (Rest (Comp e f) (Label a)).\nProof.\n    intros.\n    eapply expr_step_res.\n    - auto. \n    - auto.\n    - auto.\n    - eapply expr_step_comp_internal.\n        + eapply expr_step_sum_left.\n            * apply expr_step_act.\n        + apply expr_step_act.\nQed.\n(* \nIt was exactly like the proof in the lecture notes!\n*)", "meta": {"author": "hannahkamundson", "repo": "process-calculus-lecture", "sha": "af45a445435bc8a3a2369c732f36be22e7912aa9", "save_path": "github-repos/coq/hannahkamundson-process-calculus-lecture", "path": "github-repos/coq/hannahkamundson-process-calculus-lecture/process-calculus-lecture-af45a445435bc8a3a2369c732f36be22e7912aa9/lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7721254138226087}}
{"text": "Ltac unfold_tactic name := intros; unfold name; (* fold name; *) reflexivity.\n\nRequire Import Arith Bool.\n\n\nDefinition specification_of_ackermann_peter_function (ack : nat -> nat -> nat):=\n  (forall n : nat,\n      ack 0 n = S n)\n  /\\\n  (forall m : nat,\n      ack (S m) 0 = ack m 1)\n  /\\\n  (forall m n : nat,\n      ack (S m) (S n) = ack m (ack (S m) n)).\n\n\nDefinition specification_of_ackermann_peter_function' (ack : nat -> nat -> nat):=\n  forall m n : nat,\n    (ack 0 n = S n)\n    /\\\n    (ack (S m) 0 = ack m 1)\n    /\\\n    (ack (S m) (S n) = ack m (ack (S m) n)).\n\n\nProposition extensionality_of_the_specification_of_the_ackermann_peter_function :\n  forall f g : nat -> nat -> nat,\n    specification_of_ackermann_peter_function f ->\n    specification_of_ackermann_peter_function g ->\n    forall m n : nat,\n      f m n = g m n.\nProof.\n  intros f g.\n  unfold specification_of_ackermann_peter_function.\n  intros [S_f_0_l [S_f_0_r S_f_SS]] [S_g_0_l [S_g_0_r S_g_SS]].\n\n  intro m.\n  induction m as [ | m' IHm'].\n\n  intro n.\n  rewrite -> S_f_0_l.\n  rewrite -> S_g_0_l.\n  reflexivity.\n\n  intro n.\n  induction n as [ | n' IHn'].\n  rewrite -> S_f_0_r.\n  rewrite -> S_g_0_r.\n  rewrite -> IHm'.\n  reflexivity.\n  \n  rewrite -> S_f_SS.\n  rewrite -> S_g_SS.\n\n  rewrite -> IHn'.\n  rewrite -> IHm'.\n  reflexivity.\nQed.\n  \nProposition equivalence_of_the_two_specifications: \n  forall f : nat -> nat -> nat,\n    specification_of_ackermann_peter_function f\n    <->\n    specification_of_ackermann_peter_function' f.\nProof. \n  intro f.\n  unfold specification_of_ackermann_peter_function.\n  unfold specification_of_ackermann_peter_function'.\n\n  split.\n  intros [S_f_0_l [S_f_0_r S_f_SS]].\n\n  intros n m.\n  split.\n  rewrite -> S_f_0_l.\n  reflexivity.\n  split.\n  rewrite -> S_f_0_r.\n  reflexivity.\n  rewrite -> S_f_SS.\n  reflexivity.\n\n  intros S_f_all.\n  split.\n  intro n.\n  Check (S_f_all 0 n).\n  apply (S_f_all 0 n).\n\n  split.\n  intro m.\n  apply (S_f_all m 0).\n\n  intros m n.\n  apply (S_f_all m n).\nQed.  \n\nFixpoint primitive_iteration (T : Type) (s : T -> T) (z : T) (i : nat) : T :=\n  match i with\n  | 0 =>\n    z\n  | S i' =>\n    s (primitive_iteration T s z i')\n  end.\n\nLemma unfold_primitive_iteration_0 :\n  forall (T : Type) (s : T -> T) (z : T),\n    primitive_iteration T s z 0 = z.\nProof.\n  unfold_tactic primitive_iteration.\nQed.\n\nLemma unfold_primitive_iteration_S :\n  forall (T : Type) (s : T -> T) (z : T) (n' : nat),\n    primitive_iteration T s z (S n') =\n    s (primitive_iteration T s z n').\nProof.\n  unfold_tactic primitive_iteration.\nQed.\n\nDefinition ack_orig (m : nat) :=\n  primitive_iteration\n    (nat -> nat)\n    (fun f n => primitive_iteration nat f (f 1) n)\n    S\n    m.\n\nProposition ack_orig_satisfies_the_specification_of_the_ackermann_peter_function :\n  specification_of_ackermann_peter_function ack_orig.\nProof.\n  unfold specification_of_ackermann_peter_function.\n  unfold ack_orig.\n  split.\n\n  intro n.\n  unfold primitive_iteration.\n  reflexivity.\n\n  split.\n  intro m.\n  Check (unfold_primitive_iteration_0 (nat -> nat) ).\n  \n\n\nAbort.\n\nFixpoint ack (m : nat) :=\n  match m with\n  | O =>\n    S\n  | S m' =>\n    fix ack_local (n : nat) :=\n    match n with\n    | O =>\n      ack m' 1\n    | S n' =>\n      ack m' (ack_local n')\n    end\n  end.\n\nLemma unfold_ack_0 :\n  ack 0 = S.\nProof.\n  unfold_tactic ack.\nQed.\n\nLemma unfold_ack_S :\n  forall m' : nat,\n    ack (S m') =\n    fix ack_local (n : nat) :=\n    match n with\n    | O =>\n      ack m' 1\n    | S n' =>\n      ack m' (ack_local n')\n    end.\nProof.\n  unfold_tactic ack.\nQed. \nLemma unfold_ack_S_0 :\n  forall m' : nat,\n    ack (S m') 0 = ack m' 1.\nProof.\n  unfold_tactic ack.\nQed.\n\nLemma unfold_ack_S_S :\n  forall m' n': nat,\n    ack (S m') (S n') = ack m' (ack (S m') n').\nProof.\n  unfold_tactic ack.\nQed.\n\nProposition ack_satisfies_the_specification_of_the_ackermann_peter_function:\n  specification_of_ackermann_peter_function ack.\nProof.\nAbort.\n\nTheorem an_inequality_about_the_ackermann_peter_function:\n  forall ack : nat -> nat -> nat,\n    specification_of_ackermann_peter_function ack ->\n    forall m n : nat,\n      n < ack m n.\nProof.\n  unfold specification_of_ackermann_peter_function.\n  intros ack [S_ack_0_l [S_ack_0_r S_ack_SS]].\n\n  intro m.\n  induction m as [ | m' IHm'].\n  intro n.\n  rewrite -> S_ack_0_l.\n  Search (_ < S _).\n  apply Nat.lt_succ_diag_r.\n\n  induction n as [ | n' IHn'].\n  rewrite -> S_ack_0_r.\n  Search (S _ < _).\n  (*Nat.lt_succ_l: forall n m : nat, S n < m -> n < m*)\n  apply (Nat.lt_succ_l 0 (ack m' 1) (IHm' 1)).\n\n  Check (lt_trans).\n  (*Nat.lt_trans\n     : forall n m p : nat, n < m -> m < p -> n < p*)", "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_week10_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7721052874560862}}
{"text": "Module Basic.\n\nInductive num : Type :=\n    | Zero : num\n    | Succ : num -> num . \n   \nInductive bool : Type := \n    | True : bool\n    | False : bool .\n\nDefinition pred ( n : num ) : num := \n    match n with\n      | Zero => Zero\n      | Succ n' => n\n    end.\n\nEval compute in (pred Zero).\nEval compute in (pred (Succ Zero)).\n\nDefinition iszero (n : num ) : bool := \n     match n with\n      | Zero => True\n      | Succ _ => False\n     end.\n\nEval compute in (iszero Zero).\nEval compute in (iszero (Succ Zero)).\n\nFixpoint sum ( n : num ) ( m : num ) : num := \n     match m with\n       | Zero => n\n       | Succ n' => Succ (sum n n')\n     end.\n\nEval compute in (sum Zero (Succ Zero)).\nEval compute in (sum (Succ Zero) (Succ Zero)).\n\nFixpoint product ( n : num ) ( m : num ) : num := \n      match m with \n       | Zero => Zero\n       | Succ n' => sum n (product n n')\n      end.\n\nEval compute in (product (Succ (Succ Zero)) (Succ (Succ Zero))).\n\nFixpoint less ( n : num ) ( m : num ) : bool := \n      match n, m with\n        | Zero, Zero => False\n        | Zero, Succ n' => True\n        | Succ n', Zero => False\n        | Succ n', Succ m' => less n' m'\n      end.\n\nEval compute in (less Zero (Succ Zero)).\n\nEval compute in (less (Succ Zero) Zero).\n\n\nFixpoint eq ( n : num ) ( m : num ) : bool := \n      match n, m with\n        | Zero, Zero => True\n        | Zero, Succ m' => False\n        | Succ n', Zero => False\n        | Succ n', Succ m' => eq n' m'\n      end.\n\nEval compute in (eq Zero Zero).\n\nDefinition or ( a : bool ) ( b : bool ) : bool := \n       match a with\n         | True => True\n         | False => b\n       end.\n\nEval compute in (or False True).\nEval compute in (or True False).\n\nDefinition and ( a : bool ) (b : bool) : bool := \n       match a with\n         | True => b\n         | False => False\n       end.\n\nEval compute in (and False False).\nEval compute in (and True True).\n\nDefinition lesseq ( n : num ) ( m : num ) : bool := \n      or (less n m) (eq n m) .    \n\nEval compute in (lesseq Zero Zero).\n\nDefinition not ( a : bool ) : bool := \n      match a with \n        | True => False\n        | False => True\n      end.\n\nDefinition greater ( n : num ) ( m : num ) : bool := \n     not (lesseq n m).\n\nDefinition greatereq (n : num)  (m : num) : bool := \n     not (less n m).\n\n\nFixpoint subtract (n : num) (m : num) : num := \n     match n, m with\n       | Zero, _ => Zero\n       |  _ , Zero => n\n       | Succ n' , Succ m' => subtract n' m'\n     end.\n\nFixpoint factorial (n : num) := \n      match n with \n       | Zero => Succ Zero\n       | Succ n' => product n (factorial n')\n      end.\n\nEval compute in (factorial (Succ (Succ (Succ Zero)))).\n\n\n\nTheorem add_commutative : forall a b : nat , a + b = b + a.\nProof. admit. Qed.\n\nTheorem multi_commutative : forall a b : nat, a * b = b * a.\nProof. admit. Qed.\n\nTheorem add_identity : forall a : num, sum a Zero = a.\nProof. intros. reflexivity. Qed.\n\nTheorem multi_identity : forall a : num, product a (Succ Zero) = a.\nProof. intros. reflexivity. Qed.\n\nExample factorial_example : factorial (Succ Zero) = Succ Zero.\nProof. reflexivity. Qed.\n\nTheorem theorem1 : forall a b c : nat, a = b -> b = c -> a + b = b +c .\nProof.  intros.  rewrite -> H. rewrite -> H0. reflexivity. Qed.\n\nTheorem theorem2 : forall a b : nat, a = b + 1 -> a * ( b + 1 ) = a * a.\nProof. intros. rewrite <- H. reflexivity. Qed.\n\nTheorem theorem3 : forall a b : nat, a = b + 1 -> a * ( 1 + b ) = a * a.\nProof. intros. rewrite -> H. rewrite add_commutative. reflexivity. Qed.\n\nEnd Basic.\n", "meta": {"author": "mukeshtiwari", "repo": "abhidivmuk", "sha": "23d577d239522f4dfe373ff09e795bf3f5655ed3", "save_path": "github-repos/coq/mukeshtiwari-abhidivmuk", "path": "github-repos/coq/mukeshtiwari-abhidivmuk/abhidivmuk-23d577d239522f4dfe373ff09e795bf3f5655ed3/code/sf/div/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7721052745009849}}
{"text": "\n(* Level 0 data *)\n(* name the `exact` tactic *)\n(* tactics apply *)\n(* available false *)\n(* Level prologue *)\n(*\nClassically, you can think of a proposition to be a statement\nthat is True or False. In Homotopy Type Theory, this definition\nis a bit more subtle, but instead of `Type`s we may use\n`Prop`s. You can think of types `P : Prop` as propositions, and\nelements `p : P` as proofs for the proposition `P`. In this case,\nfunctions `P -> Q` become like implications, where we wish to produce\na proof of the proposition `Q` from a proof `p : P` of \nthe proposition `P`. \n\nRemember our `exact` tactic. It works the same here as in the previous\nworld, so the proof of this lemma may seem familiar. If you forgot how\nyou proved this statement for `Type`s in Function World, feel free\nto go back and look at your proof there!\n*)\nExample level0 (P Q : Prop) (p : P) (h : P -> Q) : Q.\nProof.\n    exact (h p).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name the `intro` tactic *)\n(* tactics apply *)\n(* available false *)\n(* Level 1 prologue *)\n(*\nLet's prove an implication. Like I said in the previous level,\nthey are kind of like functions, except on `Prop`ositions instead of\n`Type`s. In the below lemma,\ntyping `intro p` will kind of be like saying \"assume `P` holds\".\nIt then remains to present some element of type `P`. But we have a proof\nof `P`, namely `p`, which we introduced before. It should be enough to then\ntype `exact p`.\n\nTry it out below!\n*)\nLemma imp_self (P : Prop) : P -> P.\nProof.\n    intro p.\n    exact p.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 2 data *)\n(* name the `specialize` tactic *)\n(* tactics apply *)\n(* available false *)\n(* Level 2 prologue *)\n(*\nLike in function world, we can still use the `specialize` tactic\nto make it easier to later `exact _` something of the right type.\nIndeed, here we could type \n```\nexact (l(j(h(p))))\n```\nbut you should try to use the `specialize` tactic to practice!\nRemember, it should look something like\n```\nspecialize (h p) as q.\n```\n*)\nLemma maze (P Q R S T U: Prop)\n    (p : P)\n    (h : P -> Q)\n    (i : Q -> R)\n    (j : Q -> T)\n    (k : S -> T)\n    (l : T -> U)\n    : U.\nProof.\n    remember (h p) as q.\n    remember (j q : T) as t.\n    (* what does eremember do vs remember? *)\n    eremember (l(t)) as u.\n    exact u.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 data *)\n(* name the `apply` tactic *)\n(* tactics apply *)\n(* available false *)\n(* Level 3 prologue *)\n(*\nOur hypotheses kind of became a mess on the previous level, so \nwe should try it again, but then using `apply`. Again, like in \nFunction world, this allows us to \"reason backwards\". Try\nto `apply` the right functions to turn our goal into `P`,\nso we can `exact p.` to finish it off.\n*)\nLemma maze2 (P Q R S T U: Prop)\n    (p : P)\n    (h : P -> Q)\n    (i : Q -> R)\n    (j : Q -> T)\n    (k : S -> T)\n    (l : T -> U)\n    : U.\nProof.\n    apply l.\n    apply j, h.\n    exact p.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 4 data *)\n(* name `P -> (Q -> P)` *)\n(* tactics apply *)\n(* available false *)\n(* Level 4 prologue *)\n(*\nWe want to show that `P -> (Q -> P)` where `P` and `Q` are propositions.\nThink about our rule of thumb regarding functions/implications\nand the `intro` tactic, and take a good look at our hypothesis\nto see what we can `exact` or `apply` here. \n\nRemember you can also use the `intros` tactic to repeatedly \nintroduce hypotheses?\n*)\nExample level4 (P Q : Prop) : P -> (Q -> P).\nProof.\n    intros p q.\n    exact p.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 5 data *)\n(* name `(P -> (Q -> R)) -> ((P -> Q) -> (P -> R))` *)\n(* tactics apply *)\n(* available false *)\n(* Level 5 prologue *)\n(*\nYou can solve this level completely with `intro`, `apply` and `exact`.\nHowever, it may happen that `apply`ing a function of type `P -> Q -> R`\nproduces two subgoals. If you're proving it this way, remember to use\ndashes (these: `-`) to specifiy that you're working in a subgoal!\n*)\nExample level5 (P Q R : Prop) : (P -> (Q -> R)) -> ((P -> Q) -> (P -> R)).\nProof.\n    intros j f p.\n    apply j.\n    - exact p.\n    - exact (f p).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 6 data *)\n(* name `(P -> Q) -> ((Q -> R) -> (P -> R))` *)\n(* tactics apply *)\n(* available false *)\n(* Level 6 prologue *)\n(*\nIn Function World, this level did not really mean much, but\nthinking of `->` as implication, this level really shows\nthe transitivity of implications!\n*)\nLemma imp_trans (P Q R : Type) : (P -> Q) -> ((Q -> R) -> (P -> R)).\nProof.\n    intros f g h.\n    apply g, f.\n    exact h.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\nLemma not_iff_impl_false (P : Prop) : ~ P <-> (P -> False).\nProof.\n    unfold not.\n    split.\n    - trivial.\n    - trivial.\nQed.\n\nRequire Setoid.\n\n(* Level 7 data *)\n(* name `(P -> Q) -> (~Q -> ~P)` *)\n(* tactics unfold *)\n(* available false *)\n(* Level 7 prologue *)\n(*\nThere is a `False` `Prop`osition, with no proofs (kind of \nlike the empty type, with no inhabitants). We can use this\nto define \"negation\" of a proposition (i.e. `~Q`). In reality,\nwe have that `~Q` is the same as `Q -> False`. \n\nI have added a lemma \n```\n#Lemma not_iff_impl_false (P : Prop) : ~ P <-> (P -> False).\n```\nfor you to use in this level. Use it to \n```\nrepeat rewrite not_iff_impl_false.\n```\nin this level to get rid of the `~`.\n\nLater on, it might be easier to use Coq's own way of doing\nthis, by writing\n```unfold not```\nwhich basically `unfold`s the definition of `not` \n(the `~` operator). \n\nTry either of these ways in the proof below!\n*)\nLemma contrapositive (P Q : Prop) : (P -> Q) -> (~Q -> ~P).\nProof.\n    (* requires Setoid *)\n    repeat rewrite not_iff_impl_false.\n    intros f g p.\n    exact (g (f p)).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 8 data *)\n(* name a big maze *)\n(* tactics unfold *)\n(* available false *)\n(* Level 8 prologue *)\n(*\nTry to solve the maze below using the tactics you have\nlearnt in Proposition World and Function World!\n*)\nExample level8 (A B C D E F G H I J K L : Prop)\n    (f1 : A -> B) (f2 : B -> E) (f3 : E -> D) (f4 : D -> A) (f5 : E -> F)\n    (f6 : F -> C) (f7 : B -> C) (f8 : F -> G) (f9 : G -> J) (f10 : I -> J)\n    (f11 : J -> I) (f12 : I -> H) (f13 : E -> H) (f14 : H -> K) (f15 : I -> L)\n: A -> L.\nProof.\n    intro a.\n    now apply f15, f11, f9, f8, f5, f2, f1.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n\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/Proposition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7721052730499849}}
{"text": "Require Import\n  Coq.NArith.NArith MathClasses.implementations.peano_naturals MathClasses.theory.naturals\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.naturals MathClasses.interfaces.orders\n  MathClasses.interfaces.additional_operations.  \n\n(* canonical names for relations/operations/constants: *)\nInstance N_equiv : Equiv N := eq.\nInstance N_0 : Zero N := 0%N.\nInstance N_1 : One N := 1%N.\nInstance N_plus : Plus N := Nplus.\nInstance N_mult : Mult N := Nmult.\n\n(* properties: *)\nInstance: SemiRing N.\nProof.\n  repeat (split; try apply _); repeat intro.\n         now apply Nplus_assoc.\n        now apply Nplus_0_r.\n       now apply Nplus_comm.\n      now apply Nmult_assoc.\n     now apply Nmult_1_l.\n    now apply Nmult_1_r.\n   now apply Nmult_comm.\n  now apply Nmult_plus_distr_l.\nQed.\n\nInstance: ∀ x y : N, Decision (x = y) := N_eq_dec.\n\nInstance inject_nat_N: Cast nat N := N_of_nat.\nInstance inject_N_nat: Cast N nat := nat_of_N.\n\nInstance: SemiRing_Morphism nat_of_N.\nProof.\n  repeat (split; try apply _); repeat intro.\n   now apply nat_of_Nplus.\n  now apply nat_of_Nmult.\nQed.\n\nInstance: Inverse nat_of_N := N_of_nat.\n\nInstance: Surjective nat_of_N.\nProof. constructor. intros x y E. rewrite <- E. now apply nat_of_N_of_nat. now apply _. Qed.\n\nInstance: Injective nat_of_N.\nProof. constructor. exact nat_of_N_inj. apply _. Qed.\n\nInstance: Bijective nat_of_N := {}.\n\nInstance: Inverse N_of_nat := nat_of_N.\n\nInstance: Bijective N_of_nat.\nProof. apply jections.flip_bijection. Qed.\n\nInstance: SemiRing_Morphism N_of_nat.\nProof. change (SemiRing_Morphism (nat_of_N⁻¹)). split; apply _. Qed.\n\nInstance: NaturalsToSemiRing N := retract_is_nat_to_sr N_of_nat.\nInstance: Naturals N := retract_is_nat N_of_nat.\n\n(* order *)\nInstance N_le: Le N := Nle.\nInstance N_lt: Lt N := Nlt.\n\nInstance: FullPseudoSemiRingOrder N_le N_lt.\nProof.\n  assert (PartialOrder N_le).\n   repeat (split; try apply _). exact N.le_antisymm.\n  assert (SemiRingOrder N_le).\n   split; try apply _.\n     intros x y E. exists (Nminus y x).\n     symmetry. rewrite commutativity. now apply N.sub_add.\n    repeat (split; try apply _); intros.\n     now apply N.add_le_mono_l.\n    eapply N.add_le_mono_l. eassumption.\n   intros. now apply Nle_0.\n  assert (TotalRelation N_le).\n   intros x y. now apply N.le_ge_cases.\n  rapply semirings.dec_full_pseudo_srorder.\n  split.\n   intro. now apply N.le_neq.\n  intros [E1 E2]. now apply N.Private_Tac.le_neq_lt.\nQed.\n\nProgram Instance: ∀ x y: N, Decision (x ≤ y) := λ y x,\n  match Ncompare y x with\n  | Gt => right _\n  | _ => left _\n  end.\nNext Obligation. now apply not_symmetry. Qed.\n\nInstance N_cut_minus: CutMinus N := Nminus.\nInstance: CutMinusSpec N _.\nProof.\n  split; try apply _.\n   intros. now apply N.sub_add.\n  intros. now apply Nminus_N0_Nle.\nQed.\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/stdlib_binary_naturals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7721052673715683}}
{"text": "Require Import Vector Arith Bool List Nat.\n\n(** Remove the following axiom when you've finished all the exercises. This\naxoim provides a value of any type to allow the file to compile and incomplete\nexpressions to be used.\n *)\nAxiom fill_me : forall {X : Type}, X.\n\n(** Definitions used in the exercises **)\n\nDefinition leq : nat -> nat -> Prop :=\n  fun m n => exists k, k + m = n.\n\nDefinition Even : nat -> Prop :=\n  fun n => exists k, n = 2 * k.\n\nDefinition Odd : nat -> Prop :=\n  fun n => exists k, n = 2 * k + 1.\n\n(** Exercise 2.1\nProve that filtering a list results in a list with length less than or equal to the length of the original list.\n *)\n\nTheorem length_filter_list : forall A (l : list A) (p : A -> bool), leq (length (filter p l)) (length l).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.2\nProve that less-than-or-equal is transitive.\n *)\nTheorem leq_transitive : forall a b c, leq a b -> leq b c -> leq a c.\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.3\nProve that less-than-or-equal to is anti-symmetric.\n *)\n\nTheorem leq_antisymmetry : forall a b: nat, leq a b -> leq b a -> a = b.\nProof.\n  exact fill_me.\nQed.\n\n(** Hint: The following lemmas may be useful *)\n\nLemma inj_plus : forall k a: nat, k + a = a -> k = 0.\nProof.\n  exact fill_me.\nQed.\n\nLemma sum_to_zero : forall n m, n + m = 0 -> m = 0.\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.4\nProve for all numbers a and b that either a is less-than-or-equal to b or\n      b is less than equal to a.\n *)\nTheorem either_a_leq_b_or_b_leq_a : forall a b, leq a b \\/ leq b a.\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.5\nProve that the sum of two even numbers is even.\n *)\n\nTheorem sum_of_two_evens_is_even : forall n m, Even n -> Even m -> Even (n + m).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.6\nProve that the sum of two odd numbers is even.\n *)\n\nTheorem sum_of_two_odds_is_even : forall n m, Odd n -> Odd m -> Even (n + m).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.7\nProve that either n or its succesor is even.\n *)\n\nTheorem either_n_or_succ_n_is_even : forall n, Even n \\/ Even (S n).\nProof.\n  exact fill_me.\nQed.\n\n(** Exercise 2.8\nProve that all numbers are either even or odd.\n *)\n\nTheorem even_or_odd : forall n, Even n \\/ Odd n.\nProof.\n  exact fill_me.\nQed.\n", "meta": {"author": "paulcadman", "repo": "certified-programming", "sha": "0ad19c922948c1c05e19f7805a9a54f1f9903df5", "save_path": "github-repos/coq/paulcadman-certified-programming", "path": "github-repos/coq/paulcadman-certified-programming/certified-programming-0ad19c922948c1c05e19f7805a9a54f1f9903df5/src/exercises/little-typer-02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7719169277343678}}
{"text": "Require Import List.\nRequire Import Coq.Logic.Decidable.\nImport ListNotations.\n\nRequire Import CpdtTactics.\n\nRequire Import Equality.\n\n\nLocal Hint Unfold decidable.\nHint Constructors or.\n\n\nDefinition splits_into {A : Type} (l l1 l2 : list A) : Prop :=\n  l = l1 ++ l2.\n\n\nDefinition is_prefix_of {A : Type} (p s : list A) : Prop :=\n  exists s', splits_into s p s'.\n\n\n(**\n * We give an inductive definition of being a prefix since proofs\n * work better with those. However, [is_prefix_of] is more straigtforward,\n * and probably easier to work with.\n *)\nInductive IsPrefix {A : Type} : list A -> list A -> Prop :=\n  | prefix_nil : forall l, IsPrefix [] l\n  | prefix_cons : forall a p l, IsPrefix p l -> IsPrefix (a :: p) (a :: l).\n\n\nHint Unfold is_prefix_of splits_into.\nLocal Hint Constructors IsPrefix.\n\n\nLemma splits_into_cons {A : Type} :\n  forall (a : A) l l1 l2, splits_into (a :: l) l1 l2 ->\n    (exists l1', l1 = a :: l1') \\/ (l1 = [] /\\ exists l2', l2 = a :: l2').\nProof.\n  intros a l l1 l2 H.\n  destruct l1.\n  - right; split; auto.\n    destruct l2; try solve [inversion H].\n    inversion H; subst.\n    exists l2; auto.\n  - left.\n    inversion H; subst.\n    exists l1; auto.\nQed.\n\n\n(**\n * Let's show that the two definitions of prefix are equivalent.\n *)\nLemma is_prefix_of_iff_IsPrefix {A : Type} :\n  forall p s, @is_prefix_of A p s <-> IsPrefix p s.\nProof.\n  intros p s; split; revert s.\n  - induction p; intros s H.\n    + auto.\n    + inversion H as [s' Heq]; clear H.\n      unfold splits_into in Heq. subst.\n      simpl; constructor.\n      apply IHp; clear IHp.\n      exists s'; auto.\n  - induction p; intros s H.\n    + exists s; auto.\n    + inversion H; subst; clear H.\n      destruct (IHp l H3) as [l' Heq]; clear H3 IHp.\n      exists l'. crush.\nQed.\n\n\nTheorem IsPrefix_decidable {A : Type} :\n  eq_decidable A -> forall p s, decidable (@IsPrefix A p s).\nProof.\n  Ltac impossible :=\n    solve [right; intro HContra; inversion HContra; contradiction].\n\n  intros eq_dec p.\n  induction p; intros s.\n  - crush.\n  - destruct s; try impossible.\n    destruct (eq_dec a a0); destruct (IHp s); subst; try impossible; crush.\nQed.\n\n\nLemma IsPrefix_app {A : Type} :\n  forall e p s, @IsPrefix A p s <-> IsPrefix (e ++ p) (e ++ s).\nProof.\n  intros e p s; split; intro H.\n  - induction e; crush.\n  - induction e.\n    + apply H.\n    + apply IHe; clear IHe.\n      inversion H; auto.\nQed.\n\n\nLemma mutual_prefix_implies_eq {A : Type} :\n  forall (p1 p2 : list A),\n    is_prefix_of p1 p2 ->\n    is_prefix_of p2 p1 ->\n    p1 = p2.\nProof.\n  intros p1 p2 Hprefix1 Hprefix2.\n  destruct Hprefix1 as [p2' Heq_p2].\n  destruct Hprefix2 as [p1' Heq_p1].\n  unfold splits_into in *. subst p2.\n  rename Heq_p1 into H.\n  rewrite <- app_nil_r in H at 1.\n  rewrite <- app_assoc in H.\n  apply app_inv_head in H.\n  symmetry in H.\n  apply app_eq_nil in H.\n  destruct H; subst.\n  rewrite app_nil_r.\n  reflexivity.\nQed.\n\n\nDefinition partitions_into {A : Type} (l : list A) (ls : list (list A)) :=\n  l = concat ls.\n\nHint Unfold partitions_into.\n\n\nLemma empty_list_partitions_into_empty_lists {A : Type} :\n  forall (ps : list (list A)),\n    partitions_into [] ps -> Forall (fun p => p = []) ps.\nProof.\n  Hint Constructors Forall.\n  induction ps as [ | p ps]; intro H; auto.\n  destruct p as [ | a p].\n  + crush.\n  + inversion H.\nQed.\n\n\n(* TODO\nTheorem empty_partitions_are_irrelevant {A : Type} :\n  forall (l : list A) (ps : list (list A)),\n    partitions_into l ps <-> partitions_into l (filter (fun p => p <> []) ps).\n*)\n\n\nLemma partitions_are_prefixes {A : Type} :\n  forall (p l : list A) (ps : list (list A)),\n    partitions_into l (p :: ps) -> is_prefix_of p l.\nProof.\n  intros p l ps H.\n  unfold partitions_into in H.\n  exists (concat ps).\n  auto.\nQed.\n\n\n(**\n * We say that there is a break between [l1] and [l2] according to\n * [ps] (which is meant to be a partitioning of [l1 ++ l2]) if [ps]\n * can be split into two pieces, one partitioning [l1] and the other\n * partitioning [l2].\n *)\nDefinition break_between {A : Type} (l1 l2 : list A) (ps : list (list A)) :=\n  exists (ps1 ps2 : list (list A)),\n    splits_into ps ps1 ps2 /\\\n    partitions_into l1 ps1 /\\\n    partitions_into l2 ps2.\n\n\nLemma break_between_implies_partition {A : Type} :\n  forall (l1 l2 : list A) (ps : list (list A)),\n    break_between l1 l2 ps -> partitions_into (l1 ++ l2) ps.\nProof.\n  intros l1 l2 ps H.\n  inversion H as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n  unfold partitions_into in *.\n  subst l1 l2.\n  rewrite Hsplit.\n  rewrite concat_app.\n  reflexivity.\nQed.\n\n\nLemma break_between_cons {A : Type} :\n  forall (a l1 l2 : list A) (ps : list (list A)),\n    break_between l1 l2 ps <-> break_between (a ++ l1) l2 (a :: ps).\nProof.\n  intros a l1 l2 ps; split; intro H.\n  - inversion_clear H as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n    exists (a :: ps1); exists ps2.\n    crush.\n  - inversion_clear H as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n    apply splits_into_cons in Hsplit as Hbreak.\n    destruct Hbreak as [H | [Heq H]].\n    + destruct H as [ps1' H]; subst.\n      exists ps1', ps2; repeat split; auto.\n      * inversion Hsplit; auto.\n      * unfold partitions_into in Heqps1; simpl in Heqps1.\n        apply app_inv_head in Heqps1.\n        auto.\n    + subst.\n      apply app_eq_nil in Heqps1; destruct Heqps1; subst.\n      inversion_clear H as [ps2' Heqps2']; subst.\n      inversion Hsplit; subst.\n      exists [], ps2'; crush.\nQed.\n\n\nLemma break_between_nil_cons {A : Type} :\n  forall (a l2 : list A) (ps : list (list A)),\n    break_between [] l2 ps <-> break_between [] (a ++ l2) (a :: ps).\nProof.\n  intros a l2 ps; split; intro H.\n  - inversion_clear H as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n    exists []; exists (a :: ps1 ++ ps2); crush.\n    unfold partitions_into in *; simpl.\n    rewrite concat_app.\n    rewrite <- Heqps1.\n    rewrite app_nil_l.\n    reflexivity.\n  - inversion_clear H as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n    apply splits_into_cons in Hsplit as Hbreak.\n    destruct Hbreak as [H | [Heq H]]; subst.\n    + destruct a.\n      * destruct H as [ps1' Hbreak_ps1]; subst.\n        inversion Hsplit.\n        exists ps1', ps2; crush.\n      * destruct H as [ps1' Hbreak_ps1]; subst.\n        inversion Heqps1.\n    + destruct H as [ps2' Hsplit_ps2]; subst.\n      inversion_clear Hsplit; subst.\n      exists [], ps2'; crush.\n      unfold partitions_into in *; simpl in Heqps2.\n      apply app_inv_head in Heqps2.\n      assumption.\nQed.\n\n\n(**\n * We can decide if there is a break between two list chunks.\n *)\nTheorem break_between_decidable {A : Type} :\n  eq_decidable A ->\n    forall (l1 l2 : list A) (ps : list (list A)),\n      decidable (break_between l1 l2 ps).\nProof.\n  Ltac impossible_break :=\n    solve [ \n      right;\n      intro HContra;\n      inversion HContra as [ps1 [ps2 [Hsplit [Hp1 Hp2]]]];\n      inversion Hsplit as [Heq];\n      symmetry in Heq;\n      apply app_eq_nil in Heq; destruct Heq; subst;\n      try (solve [inversion Hp1]);\n      try (solve [inversion Hp2])\n    ].\n\n  intro eq_dec.\n  intros l1 l2 ps; revert l1 l2.\n  induction ps; intros l1 l2.\n  - destruct l1; destruct l2; try impossible_break.\n    + left; exists []; exists []; crush.\n  - destruct (IsPrefix_decidable eq_dec a l1) as [Hprefix1 | Hprefix1].\n    + apply is_prefix_of_iff_IsPrefix in Hprefix1.\n      inversion_clear Hprefix1 as [l1' Heql1]; unfold splits_into in Heql1; subst.\n      apply (decidable_equivalent (break_between_cons a l1' l2 ps)).\n      apply IHps.\n    + destruct l1 as [ | x l1'].\n      -- destruct (IsPrefix_decidable eq_dec a l2) as [Hprefix2 | Hprefix2].\n         ++ apply is_prefix_of_iff_IsPrefix in Hprefix2.\n            inversion_clear Hprefix2 as [l2' Heql2].\n            unfold splits_into in Heql2; subst.\n            apply (decidable_equivalent (break_between_nil_cons a l2' ps)).\n            apply IHps.\n         ++ right; intro HContra.\n            inversion_clear HContra as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n            apply splits_into_cons in Hsplit as Hbreak.\n            destruct Hbreak as [H | [Heq H]]; subst.\n            * apply Hprefix1.\n              apply is_prefix_of_iff_IsPrefix.\n              destruct H as [ps1' Hbreak_ps1]; subst.\n              apply partitions_are_prefixes in Heqps1.\n              assumption.\n            * apply Hprefix2.\n              apply is_prefix_of_iff_IsPrefix.\n              destruct H as [ps12' Hbreak_ps2]; subst.\n              apply partitions_are_prefixes in Heqps2.\n              assumption.\n      -- right; intro HContra.\n         inversion_clear HContra as [ps1 [ps2 [Hsplit [Heqps1 Heqps2]]]].\n         apply splits_into_cons in Hsplit as Hbreak.\n         destruct Hbreak as [H | [Heq H]]; subst.\n         * destruct H as [ps1' Hbreak_ps1]; subst.\n           apply Hprefix1.\n           apply is_prefix_of_iff_IsPrefix.\n           apply partitions_are_prefixes in Heqps1.\n           assumption.\n         * inversion Heqps1.\nQed.\n\n\nLemma empty_partition_only_breaks_empty_list {A : Type} :\n  forall (s1 s2 : list A),\n    break_between s1 s2 [] -> s1 = [] /\\ s2 = [].\nProof.\n  intros s1 s2 Hbreak.\n  inversion Hbreak as [ps1 [ps2 [Hsplit [Heq_ps1 Heq_ps2]]]].\n  unfold splits_into in Hsplit.\n  symmetry in Hsplit; apply app_eq_nil in Hsplit as [Hnil_ps1 Hnil_ps2]; subst.\n  crush.\nQed.\n\n\nLemma concat_app_prefix {A : Type} :\n  forall (l1 l23 l12 l3 : list (list A)),\n    l1 ++ l23 = l12 ++ l3 ->\n    Forall (fun p => p <> []) l1 ->\n    is_prefix_of (concat l1) (concat l12) ->\n    is_prefix_of l1 l12.\nProof.\n  induction l1 as [ | p l1]; intros l23 l12 l3 Heq Hneq_l1 Hprefix.\n  - exists l12; auto.\n  - destruct l12 as [ | p' l12].\n    + destruct Hprefix as [Hl2' Heq_l2'].\n      unfold splits_into in Heq_l2'; symmetry in Heq_l2'.\n      apply app_eq_nil in Heq_l2' as [Hempty_l1 _].\n      simpl in Hempty_l1.\n      apply app_eq_nil in Hempty_l1 as [Hempty_p _].\n      apply Forall_inv in Hneq_l1.\n      contradiction.\n    + inversion Heq; subst.\n\n      apply is_prefix_of_iff_IsPrefix in Hprefix.\n      simpl in Hprefix.\n      apply IsPrefix_app in Hprefix.\n      apply is_prefix_of_iff_IsPrefix in Hprefix.\n      inversion_clear Hneq_l1.\n      specialize (IHl1 l23 l12 l3 H1 H0 Hprefix).\n\n      apply is_prefix_of_iff_IsPrefix.\n      apply is_prefix_of_iff_IsPrefix in IHl1.\n      apply IsPrefix_app with (e := [p']) in IHl1.\n      assumption.\nQed.\n\n\nLemma concat_app_eq {A : Type} :\n  forall (l1 l2 l1' l2' : list (list A)),\n    l1 ++ l2 = l1' ++ l2' ->\n    Forall (fun p => p <> []) l1 ->\n    Forall (fun p => p <> []) l1' ->\n    concat l1 = concat l1' ->\n    l1 = l1'.\nProof.\n  intros l1 l2 l1' l2' Heq Hno_empty_l1 Hno_empty_l1' Hconcat.\n  assert (is_prefix_of l1 l1').\n  + apply (concat_app_prefix l1 l2 l1' l2'); auto.\n    - exists []; crush.\n  + inversion H as [l1'' Heq_l1''].\n    unfold splits_into in Heq_l1''; subst.\n    replace l1'' with ([] : list (list A)).\n    - symmetry; apply app_nil_r.\n    - rewrite concat_app in Hconcat.\n      rewrite <- app_nil_r in Hconcat at 1.\n      apply app_inv_head in Hconcat.\n      apply empty_list_partitions_into_empty_lists in Hconcat.\n      destruct l1''; auto.\n      exfalso.\n      apply Forall_app in Hno_empty_l1'.\n      destruct Hno_empty_l1' as [_ Hno_empty_l1''].\n      apply Forall_inv in Hno_empty_l1''.\n      apply Forall_inv in Hconcat.\n      contradiction.\nQed.\n\nTheorem break_of_break {A : Type} :\n  forall (l1 l2 l3 : list A) (ps : list (list A)),\n    Forall (fun p => p <> []) ps -> (* TODO: remove this requirement *)\n    break_between (l1 ++ l2) l3 ps ->\n    break_between l1 (l2 ++ l3) ps ->\n    exists p1 p2 p3,\n      ps = p1 ++ p2 ++ p3 /\\\n      partitions_into l1 p1 /\\\n      partitions_into l2 p2 /\\\n      partitions_into l3 p3.\nProof.\n  intros l1 l2 l3 ps Hno_empty Hbreak23 Hbreak12.\n  inversion_clear Hbreak23 as [p12 [p3 [Hsplit23 [Heq_p12 Heq_p3]]]].\n  inversion_clear Hbreak12 as [p1 [p23 [Hsplit12 [Heq_p1 Heq_p23]]]].\n  assert (Hprefix_l1 : is_prefix_of p1 p12).\n  + apply (concat_app_prefix p1 p23 p12 p3).\n    - crush.\n    - unfold splits_into in Hsplit12; subst.\n      apply Forall_app in Hno_empty.\n      apply Hno_empty.\n    - exists l2; crush.\n  + inversion Hprefix_l1 as [p2 Heq_p2].\n    exists p1, p2, p3; repeat split.\n    - unfold splits_into in *; crush.\n    - assumption.\n    - unfold partitions_into in *; subst.\n      unfold splits_into in Heq_p2; subst.\n      rewrite concat_app in Heq_p12.\n      apply app_inv_head in Heq_p12.\n      assumption.\n    - assumption.\nQed.\n\n\nLemma break_between_cons_prefix {A : Type} :\n  forall (l1 l2 p : list A) (ps : list (list A)),\n    l1 <> [] ->\n    break_between l1 l2 (p :: ps) ->\n    is_prefix_of p l1.\nAdmitted.\n\n\nLocal Lemma break_between_obvious {A : Type} :\n  forall (p : list A) (ps : list (list A)),\n    break_between p (concat ps) (p :: ps).\nProof.\n  intros p ps.\n  exists [p], ps; repeat split; auto.\n  unfold partitions_into; simpl.\n  rewrite app_nil_r.\n  reflexivity.\nQed.\n\n\n(**\n * Two partitionings are the same if and only if they\n * induce the same breaks (modulo empty partitions). This\n * gives us a nice way to characterize partitions.\n *)\nLemma breaks_eq_implies_partitions_eq {A : Type} :\n  forall (ps1 ps2 : list (list A)),\n  Forall (fun p => p <> []) ps1 ->\n  Forall (fun p => p <> []) ps2 ->\n  (forall (s1 s2 : list A),\n     break_between s1 s2 ps1 <-> break_between s1 s2 ps2) ->\n  ps1 = ps2.\nProof.\n  induction ps1 as [ | p1 ps1]; intros ps2 Hno_empty_ps1 Hno_empty_ps2 Hsame_breaks.\n  - destruct ps2 as [ | p2 ps2].\n    + reflexivity.\n    + inversion_clear Hno_empty_ps2.\n      contradict H.\n      apply (empty_partition_only_breaks_empty_list p2 (concat ps2)).\n      apply Hsame_breaks.\n      exists [p2], ps2; crush.\n      unfold partitions_into; simpl.\n      rewrite app_nil_r.\n      reflexivity.\n\n  - destruct ps2 as [| p2 ps2].\n    + inversion_clear Hno_empty_ps1.\n      contradict H.\n      apply (empty_partition_only_breaks_empty_list p1 (concat ps1)).\n      apply Hsame_breaks.\n      apply break_between_obvious.\n    + replace p2 with p1 in *.\n      * replace ps2 with ps1; auto.\n        apply IHps1.\n        -- inversion_clear Hno_empty_ps1; assumption.\n        -- inversion_clear Hno_empty_ps2; assumption.\n        -- intros s1 s2; split; intro H;\n             apply break_between_cons with (a := p1);\n             apply Hsame_breaks;\n             apply break_between_cons;\n             assumption.\n      * apply mutual_prefix_implies_eq.\n        -- apply break_between_cons_prefix with (l2 := concat ps2) (ps := ps1).\n           ** inversion Hno_empty_ps2; assumption.\n           ** apply Hsame_breaks.\n              apply break_between_obvious.\n        -- apply break_between_cons_prefix with (l2 := concat ps1) (ps := ps2).\n           ** inversion Hno_empty_ps1; assumption.\n           ** apply Hsame_breaks.\n              apply break_between_obvious.\nQed.\n\n\n(* TODO: this might be useful *)\n(*\nLemma non_empty_breaks_are_unique {A : Type} :\n  forall (s1 s2 : list A) (ps : list (list A)) (cs1 cs2 cs1' cs2' : list (list A)),\n    Forall (fun p => p <> []) ps ->\n    splits_into ps cs1 cs2 ->\n    partitions_into s1 cs1 ->\n    partitions_into s2 cs2 ->\n    splits_into ps cs1' cs2' ->\n    partitions_into s1 cs1' ->\n    partitions_into s2 cs2' ->\n    cs1 = cs1' /\\ cs2 = cs2'.\nProof.\n  intros s1 s2 ps cs1 cs2 cs1' cs2' Hno_empty Hsplit Hp_cs1 Hp_cs2 Hsplit' Hp_cs1' Hp_cs2'.\n  assert (cs1 = cs1').\n  - induction cs1 as [_ | p cs1]; destruct cs1' as [_ | p' cs1']; auto.\n    + unfold partitions_into in Hp_cs1; subst.\n      simpl in Hp_cs1'.\n      apply empty_list_partitions_into_empty_lists in Hp_cs1' as HContra.\n      apply Forall_inv in HContra.\n      contradict HContra.\n      unfold splits_into in Hsplit'; subst.\n      apply Forall_inv in Hno_empty.\n      assumption.\n    + unfold partitions_into in Hp_cs1'; subst.\n      simpl in Hp_cs1.\n      apply empty_list_partitions_into_empty_lists in Hp_cs1 as HContra.\n      apply Forall_inv in HContra.\n      contradict HContra.\n      unfold splits_into in Hsplit; subst.\n      apply Forall_inv in Hno_empty.\n      assumption.\n    + admit.\n\n  - subst cs1; split; auto.\n    unfold splits_into in *.\n    rewrite Hsplit' in Hsplit.\n    apply app_inv_head in Hsplit.\n    symmetry; assumption.\nAdmitted.\n   \n*)\n\n(* TODO: generalize breaks to multiple breaks.\n\n(**\n * Given two partitionings [c, g], we say that [g] is more _granular_\n * than [c] (or [g] is a sub partition of [c]) if every \"break\" in [c]\n * also exists in [g].\n *)\nInductive IsSubPartition {A : Type} : list (list A) -> list (list A) -> Prop :=\n  | sub_partition_nil : IsSubPartition [] []\n  | sub_partition_empty : forall c g, IsSubPartition c g -> IsSubPartition c ([] :: g)\n  | sub_partition_head : forall c g, forall hc hg rg,\n    splits_into hg hc rg -> IsSubPartition c (rg :: g) -> IsSubPartition (hc :: c) (hg :: g).\n\n\nTheorem IsSubPartition_decidable {A : Type} :\n  forall c g, decidable (@IsSubPartition A c g).\nAdmitted.\n\n\nLemma partition_split_decidable {A : Type} :\n  forall (l1 l2 : list A) (ps : list (list A)),\n    decidable (\n      exists (ps1 ps2 : list (list A)),\n        splits_into ps ps1 ps2 /\\\n        partitions_into l1 ps1 /\\\n        partitions_into l2 ps2).\nProof.\n  intros l1 l2 ps.\n  destruct (IsSubPartition_decidable [l1; l2] ps).\n*)", "meta": {"author": "cacay", "repo": "grapheme-clusters", "sha": "c709072bc26ea0c81a5d30b858557071329f0bfa", "save_path": "github-repos/coq/cacay-grapheme-clusters", "path": "github-repos/coq/cacay-grapheme-clusters/grapheme-clusters-c709072bc26ea0c81a5d30b858557071329f0bfa/coq-src/Partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7719169155748037}}
{"text": "Require Import Arith List.\nRequire Import Recdef.\n\nFixpoint select_min (x: nat) (l: list nat) : nat * list nat :=\n  match l with\n  | nil => (x,l)\n  | h :: tl => if (le_lt_dec x h) then\n                 let (m,l') := select_min x tl in\n                 (m, h::l')\n                   else \n                     let (m,l') := select_min h tl in\n                     (m, x::l')\n  end.\n\nCompute (select_min 2 (1::nil)).\nCompute (select_min 2 (1::2::3::0::1::nil)).\n\nLemma select_min_length: forall l l' x y, select_min x l = (y, l') -> length l = length l'.\nProof.\n  induction l.\n  - simpl.\n    intros l x y H.\n    inversion H; subst.\n    reflexivity.\n  - intros l' x y.\n    assert (H: select_min x l = (y, l') -> length l = length l').\n        {\n          apply IHl.\n          }\n        generalize dependent y.\n        generalize dependent x.\n        induction l'.\n    + intros x y IH H.\n      simpl in H.\n      destruct (le_lt_dec x a).\n      * destruct (select_min x l).\n        inversion H.\n      * destruct (select_min a l).\n        inversion H.\n    + intros x y IH H.\n      simpl in H. \n      destruct (le_lt_dec x a).\n      * simpl. apply f_equal.\n        apply IHl with x y.\n        destruct (select_min x l).\n        inversion H; subst.\n        reflexivity.\n      * simpl. apply f_equal.\n        apply IHl with a y.\n        destruct (select_min a l).\n        inversion H; subst.\n        reflexivity.\nQed.\n\nFunction select (l: list nat) {measure length} : list nat :=\n  match l with\n  | nil => l\n  | h :: tl =>\n    let (m,l') := select_min h tl in\n    (m :: (select l'))\n  end.\nProof.\n  intros.\n  apply select_min_length in teq0.\n  rewrite <- teq0.\n  simpl.\n  apply lt_n_Sn.\nQed.\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\nLemma ordenada_sub: forall l n, ordenada (n :: l) -> ordenada l.\nProof.\n  induction l.\n  - intros n H.\n    apply lista_vazia.\n  - intros n' Hcons.\n    inversion Hcons. subst.\n    assumption.\nQed.\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 equiv_trans: forall l l' l'', equiv l l' -> equiv l' l'' -> equiv l l''.\nProof.\n  intros l l' l'' H H'.\n  unfold equiv in *.\n  intro n.\n  apply eq_trans with (num_oc n l').\n  apply H.\n  apply H'.\nQed.\n\nLemma equiv_cons: forall l l' a, equiv l l' -> equiv (a::l) (a::l').\nProof.\n  intros l l' n H.\n  unfold equiv in *.\n  intros n'.\n  simpl.\n  destruct (Nat.eq_dec n' n).\n  - apply f_equal.\n    apply H.\n  - apply H.\nQed.\n\nLemma equiv_cons_comm: forall l l' x z, equiv l l' -> equiv (z :: x :: l) (x :: z :: l').\nProof.\n  intros l l' x z H.\n  unfold equiv in *.\n  intro n. simpl.\n  destruct (Nat.eq_dec n z).\n  - destruct (Nat.eq_dec n x).\n    + apply f_equal. apply f_equal.\n      apply H.\n    + apply f_equal.\n      apply H.\n  - destruct (Nat.eq_dec n x).\n    + apply f_equal.\n      apply H.\n    + apply H.\nQed.\n\nLemma equiv_cons_cons: forall l l' x y z, equiv (x :: l) (y :: l') -> equiv (x :: z :: l) (y :: z :: l').\nProof.\n  intros l l' x y z H.\n  assert (H': equiv (z :: x :: l) (z :: y :: l')).\n  {\n    apply equiv_cons; assumption.\n  }\n  apply equiv_trans with (z :: x :: l).\n  - apply equiv_cons_comm.\n    unfold equiv; reflexivity.\n  - apply equiv_trans with (z :: y :: l').\n    + assumption.\n    + apply equiv_cons_comm.\n      unfold equiv; reflexivity.\nQed.\n\nLemma select_min_cons_le: forall l l' x y a, select_min x (a::l) = (y,a::l') -> x <= a -> select_min x l = (y,l').\nProof.\n  intros l l' x y a H H'.\n  simpl in H.\n  destruct (le_lt_dec x a).\n  - destruct (select_min x l).\n    inversion H; subst.\n    reflexivity.\n  - destruct (select_min a l).\n    apply le_not_lt in H'.\n    contradiction.\nQed.\n\nLemma select_min_cons_lt: forall l l' x y a, select_min x (a::l) = (y,x::l') -> a < x -> select_min a l = (y,l').\nProof.\n  intros l l' x y a H H'.\n  simpl in H.\n  destruct (le_lt_dec x a).\n  - destruct (select_min x l).\n    apply le_not_lt in l0.\n    contradiction.\n  - destruct (select_min a l).\n    inversion H; subst.\n    reflexivity.\nQed.\n\nLemma select_min_equiv: forall l l' x y, select_min x l = (y, l') -> equiv (x::l) (y::l').\nProof.\n  induction l.\n  - intros l x y H.\n    simpl in H.\n    inversion H; subst.\n    unfold equiv; reflexivity.\n  - intros l' x y. case l'.\n    + simpl. intro H.\n      destruct (le_lt_dec x a).\n      * destruct (select_min x l).\n        inversion H.\n      * destruct (select_min a l).\n        inversion H.\n    + intros n l'' H.\n      assert (H' := H).\n      simpl in H.\n      destruct (le_lt_dec x a).\n      * destruct (select_min x l).\n        inversion H; subst.\n        apply equiv_cons_cons.\n        clear H.\n        apply IHl.\n        apply select_min_cons_le in H'.\n        ** assumption.\n        ** assumption.        \n      * destruct (select_min a l).\n        inversion H; subst.\n        apply equiv_trans with (a :: n :: l).\n        ** apply equiv_cons_comm.\n           unfold equiv; reflexivity.\n        ** apply equiv_cons_cons.        \n           apply IHl.\n           apply select_min_cons_lt with n; assumption.\nQed.\n\nTheorem selectionSort_equiv: forall l, equiv l (select l).\nProof.\n  intro l.\n  functional induction (select l).\n  - unfold equiv.\n    reflexivity.\n  - unfold equiv in *.\n    intro n.\n    simpl.\n    destruct (Nat.eq_dec n h).\n    + destruct (Nat.eq_dec n m).\n      * apply f_equal.\n        apply select_min_equiv in e0.\n        subst.\n        unfold equiv in e0.\n        apply eq_trans with (num_oc m l').\n        assert (H: num_oc m (m :: tl) = num_oc m (m :: l')).\n        {\n          apply e0.\n        }\n        simpl in H.\n        destruct (Nat.eq_dec m m).\n        ** inversion H; subst.\n           reflexivity.\n        ** apply False_ind.\n           apply n; reflexivity.\n        ** apply IHl0.\n      * apply select_min_equiv in e0.\n        unfold equiv in e0.\n        assert (H: num_oc n (h :: tl) = num_oc n (m :: l')).\n        { apply e0. }\n        clear e0.\n        simpl in H.\n        subst.\n        destruct (Nat.eq_dec h h).\n        ** destruct (Nat.eq_dec h m).\n           *** contradiction.\n           *** rewrite H.\n               apply IHl0.\n        ** destruct (Nat.eq_dec h m).\n           *** contradiction.\n           *** apply False_ind.\n               apply n; reflexivity.\n    + destruct (Nat.eq_dec n m).\n      * subst.\n        apply select_min_equiv in e0.\n        unfold equiv in e0.\n        assert (H := e0 m).\n        simpl in H.\n        destruct (Nat.eq_dec m h).\n        ** destruct (Nat.eq_dec m m).\n           *** contradiction.\n           *** apply False_ind.\n               apply n; reflexivity.\n        ** destruct (Nat.eq_dec m m).\n           *** rewrite H.\n               apply f_equal.\n               apply IHl0.\n           *** apply False_ind.\n               apply n1; reflexivity.\n      * apply select_min_equiv in e0.\n        unfold equiv in e0.\n        assert (H := e0 n).\n        simpl in H.\n        destruct (Nat.eq_dec n h).\n        ** contradiction.\n        ** destruct (Nat.eq_dec n m).\n           *** contradiction.\n           *** rewrite H.\n               apply IHl0.\nQed.\n\nLemma select_min_leq': forall h l m l', select_min h l = (m, l') -> m <= h.\nAdmitted.\n\nLemma select_min_smallest: forall x l y l', select_min x l = (y, l') -> Forall (fun z => y <= z) l'.\nProof.\n  intros x l. generalize dependent x.\n  induction l.\n  - intros x y l' H.\n    simpl in H.\n    inversion H; subst.\n    apply Forall_nil.\n  - intros x y l' H.\n    simpl in H.\n    destruct (le_lt_dec x a).\n    + destruct (select_min x l) eqn: H'.\n      inversion H; subst. clear H.\n      assert (H := H').\n      apply select_min_leq' in H'.\n      apply Forall_cons.\n      * apply le_trans with x; assumption.\n      * apply IHl with x; assumption.\n    + destruct (select_min a l) eqn: H'.\n      inversion H; subst. clear H.\n      assert (H := H').\n      apply select_min_leq' in H'.\n      apply Forall_cons.\n      * apply Nat.lt_le_incl in l0.\n        apply le_trans with a; assumption.\n      * apply Nat.lt_le_incl in l0.\n        apply IHl with a; assumption.\nQed.\n\nLemma select_min_leq: forall h1 l1 m1 m2 h2 l2 l3, select_min h1 l1 = (m1, h2 :: l2) -> select_min h2 l2 = (m2, l3) -> m1 <= m2.\nProof.\n  intros h1 l1. generalize dependent h1.\n  induction l1.\n  - intros h1 m1 m2 h2 l2 l3 H.\n    inversion H; subst.\n  - intros h1 m1 m2 h2 l2 l3 H1 H2.\n    apply IHl1 with h1 h2 l2 l3.\n    + assert (H: select_min h1 l1 = (m1, h2 :: l2) -> select_min h2 l2 = (m2, l3) -> m1 <= m2).\n    {\n      apply IHl1.\n    }\n      simpl in H1.\n      destruct (le_lt_dec h1 a).\n      * destruct (select_min h1 l1).\n        admit.\n      * admit.\n    + assumption.\nAdmitted.\n\nLemma smallest_equiv:\n  forall l y l', equiv l l' -> Forall (fun z => y <= z) l -> Forall (fun z => y <= z) l'.\nProof.\n  intros l y l'; revert l y.\n  induction l' using list_lenght_ind.\n  - admit.\n  - intros l y Heq H'.\n    assert (Hlength: length l = length l').\n    { apply equiv_length; assumption. }\n    generalize dependent l'.\n    intro l'. case l'.\n    + intros IH Heq Hlen.\n      apply Forall_nil.\n    + intros n l'' IH Heq Hlen.\n      apply Forall_cons.\n      * admit.\n      * apply IH with l''.\n        ** simpl. auto.\n        ** unfold equiv; reflexivity.\n        ** admit.\nAdmitted.\n\nLemma select_min_cons: forall h h' a m l l', h <= a -> select_min h (a :: l) = (m, a :: h' :: l') -> select_min h l = (m, h' :: l').\n\nLemma select_min_min: forall l2 h1 l1 m1 m2 h2 l3, select_min h1 l1 = (m1, h2 :: l2) -> select_min h2 l2 = (m2, l3) -> m1 <= m2.\nProof.\nAdmitted.\n\nTheorem selectionSort_sorts: forall l, ordenada (select l).\nProof.\n  intro l. functional induction (select l).\n  - apply lista_vazia.\n  - generalize dependent l'.\n    intro l'.\n    case l'.\n    + intros H H1.\n      rewrite select_equation.\n      apply lista_1.\n    + intros h' tl' Hl Hord.\n      rewrite select_equation in *.\n      destruct (select_min h' tl') as [m' l''] eqn: H.\n      apply lista_nv.\n      assert (H': m <= m').\n      (* { apply select_min_min with tl' h tl h' l''; assumption. } *)\n      { apply select_min_min with tl' h tl h' l''; assumption. }\n      * assumption.\n      * inversion 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/selectionSort20172_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7719116939379752}}
{"text": "(** Inductive datatypes were not part of the original calculus of\n    constructions. The only native logical connective is product\n    ([forall]) but it can be used to define other connectives. *)\n\n(** The first two definitions are fairly useless but illustrate the\n    logical interpretation of the product construct. *)\nDefinition implies (P Q : Prop) := P -> Q.\n\nDefinition univ_quantification (T : Type) (P : T -> Prop) := forall (x : T), P x.\n\n(** _Conjunction_ *)\nDefinition and (P Q : Prop) := forall (R : Prop), (P -> Q -> R) -> R.\n(** This can be understood as \"any proposition [R] that requires a\n    function of type [P -> Q -> R] to be is the type of proofs of [P] and\n    [Q]\". *)\n\n(** _Disjunction_ *)\nDefinition or (P Q : Prop) := forall (R : Prop), (P -> R) -> (Q -> R) -> R.\n\n(** _Negation_ *)\nDefinition not (P : Prop) := forall (Q : Prop), P -> Q.\n\n(** _Existential quantification_ *)\nDefinition ex (T : Type) (P : T -> Prop) := forall (Q : Prop), (forall (t : T), P t -> Q) -> Q.\n\n(** Prove the following lemmas, first with a proof script, then by\n    writing a proof term directly. *)\n\n(** To make it easier to write proof terms, you can write terms with\n    placeholders (underscore) such as [fun (x : T) => _]. If the\n    content of the placeholder can be inferred because of type\n    dependencies, Coq will do so automagically. Otherwise, you get an\n    error message which indicates the expected type of the\n    placeholder. *)\n\n(* Quantify over P and Q here to avoid a lot clutter in the examples. *)\nSection Examples.\n\nVariables P Q : Prop.\n\n(** _Example_ *)\nTheorem or_comm : or P Q -> or Q P.\nProof.\n  unfold or; intros.\n  apply H.\n  - exact H1.\n  - exact H0.\nQed.\n\nDefinition or_comm' : or P Q -> or Q P :=\n  fun (H : or P Q) (R : Prop) (H0 : Q -> R) (H1 : P -> R) => H R H1 H0.\n\nTheorem and_comm : and P Q -> and Q P.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition and_comm' : and P Q -> and Q P\n  (* write a proof term here *)\n. Admitted.\n\nTheorem and_proj_l : and P Q -> P.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition and_proj_l' : and P Q -> P\n  (* write a proof term here *)\n. Admitted.\n\nTheorem absurd : P -> not P -> Q.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition absurd' : P -> not P -> Q\n  (* write a proof term here *)\n. Admitted.\n\nTheorem modus_ponens : and (or (not P) Q) P -> Q.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition modus_ponens' : and (or (not P) Q) P -> Q\n  (* write a proof term here *)\n. Admitted.\n\nEnd Examples.\n\n(** Provide a non-inductive definition of the type of equivalent\n    propositions, without relying on a previously defined proposition\n    (such as [and]). *)\nDefinition iff (P Q : Prop) : Prop := False.\n\nSection ExamplesIff.\n\nVariables A B C T : Prop.\nVariable P : T -> Prop.\n\nTheorem iff_refl : iff A A.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition iff_refl' : iff A A\n  (* write a proof term here *)\n. Admitted.\n\nTheorem iff_sym : (iff A B) -> (iff B A).\n  (* write a proof script here *)\nAdmitted.\n\nDefinition iff_sym' : (iff A B) -> (iff B A)\n  (* write a proof term here *)\n. Admitted.\n\nTheorem iff_trans : (iff A B) -> (iff B C) -> (iff A C).\n  (* write a proof script here *)\nAdmitted.\n\nDefinition iff_trans' : (iff A B) -> (iff B C) -> (iff A C)\n  (* write a proof term here *)\n. Admitted.\n\nTheorem all_not_ex :\n    iff (forall (x : T), not (P x)) (not (ex T P)).\nProof.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition all_not_ex' :\n    iff (forall (x : T), not (P x)) (not (ex T P))\n  (* write a proof term here *)\n. Admitted.\n\nEnd ExamplesIff.\n\n(** Try to give a non-inductive definition of the type of false\n    propositions. *)\nDefinition false : Prop := True.\n\nSection ExamplesFalse.\n\nVariables P : Prop.\n\n(** Hint for the definition: The principle of explosion [forall P,\n    false -> P] can be seen as defining falsehood. *)\nTheorem ex_falso : false -> P.\n  (* write a proof script here *)\nAdmitted.\n\nDefinition ex_falso' : false -> P\n  (* write a proof term here *)\n. Admitted.\n\nTheorem not_alternative_def : iff (P -> false) (not P).\n  (* write a proof script here *)\nAdmitted.\n\nDefinition not_alternative_def' : iff (P -> false) (not P)\n  (* write a proof term here *)\n. Admitted.\n\nEnd ExamplesFalse.\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/3/Ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7719098539082021}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nImplicit Type P Q R : Prop.\n\n(** *** Exercise 0:\n    - Define not. In type theory negation is defined in terms\n      of [False].\n*)\n\nDefinition not P := \n.\n\n(** *** Exercise 1:\n    - Prove the negation of the excluded middle.\n*)\nLemma ex0 P : not (P /\\ not P).\nProof.\nQed.\n\n(** *** Exercise 2:\n    - Declare iff (the constructor being called [iff_intro]).\n    - Define iff1 of the given type\n*)\nInductive iff P Q :=\n.\n\nDefinition iff1 P Q : iff P Q -> P -> Q :=\n\n(** *** Exercise 3:\n    - Declare xor: two constructors, both have two arguments\n    - Prove the following lemmas\n*)\n\nInductive xor P Q : Prop :=\n.\n\nLemma xorC P Q : iff (xor P Q) (xor Q P).\nProof.\nQed.\n\n\nLemma xor1 P Q : (xor P Q) -> not Q -> P.\nProof.\nQed.\n\nLemma xor2 P Q Z : (xor P Q) -> (xor Q Z) -> iff P Z.\nProof.\nQed.\n\n(** *** Exercise 4:\n    - Declare exists2\n    - Prove a lemma ex1 -> ex2 T\n*)\n\nInductive ex2 T (P Q : pred T) : Prop :=\n.\n\nLemma ex2T T (P : pred T) : (exists x, P x) -> (ex2 T P P).\nProof.\nQed.\n\n(** *** Exercise 5:\n    - Write the induction principle for lists\n*)\nDefinition induction_seq A (P : seq A -> Prop) :\n  P nil -> (forall a l, P l -> P (a :: l)) -> forall l, P l :=\n.\n\n\n(** *** Exercise 6:\n    - remeber [=> /view] to prove the following lemma\n    - the two relevant views are [prime_gt1] and [dvdn_leq]\n    - Note: [=> /view] combines well with [->] (lesson 3)\n    - Hint: the proof can be a one liner [by move=> ....]\n    - Recall: the notation \"_ < _ <= _\" hides a conjunction\n*)\nAbout prime_gt1.\nAbout dvdn_leq.\n\nLemma ex_view p : prime p -> p %| 7 -> 1 < p <= 7.\nProof.\nQed.\n\n(** *** Exercise 7:\n    - Define the indexed data type of Cherry tree:\n      + the index is a bool and must be truee iff the tree is completely\n        flourished\n      + leaves can be either Flower or Bud\n      + the third constructor is called Node and has two sub trees\n*)\nInductive cherryt : bool -> Type :=\n\nCheck Node _ Flower Flower : cherryt true.\nCheck Node _ Bud Bud       : cherryt false.\nFail Check Node _ Flower Bud.\n\n\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/exercise4_todo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7719098516519163}}
{"text": "Require Import ZArith Zwf.\nRequire Import ZArith.Znumtheory.\nRequire Import Psatz.\nSet Implicit Arguments.\nOpen Scope Z.\n\nLemma rel_prime_factor_exclusive : forall a b c, a <> 0 -> b <> 0 -> rel_prime a b -> 1 < c -> (c | a) -> ~(c | b).\nProof.\n  intros a b c Ha Hb Hrp Hc Hdiv.\n  destruct Hdiv as [a' ->].\n  intros [b' ->].\n  rewrite <- Zgcd_1_rel_prime in Hrp.\n  rewrite Z.gcd_mul_mono_r_nonneg in Hrp; auto with *.\n  rewrite Z.mul_comm in Hrp.\n  destruct (Z.mul_eq_1 _ _ Hrp); subst; auto with *.\nQed.\n\nLemma root_divide : forall n k, 1 <= k -> (n | n ^ k).\nProof.\n  intros.\n  replace k with (1 + (k - 1)); auto with *.\n  rewrite Z.pow_add_r; auto with *.\n  cbn.\n  auto with *.\nQed.\nHint Resolve root_divide.\n\nLemma factor_prod : forall a b c d, (a | b) -> (c | d) -> (a * c | b * d).\nProof.\n  intros a b c d [b' -> ] [d' ->].\n  exists (b' * d').\n  lia.\nQed.\n\nLemma not_prime_divide_prime :\n  forall n, 1 < n -> ~prime n -> exists p, 1 < p < n /\\ (p | n) /\\ prime p.\nProof.\n  intro n.\n  induction n using (well_founded_ind (Zwf_well_founded 0)).\n  intros Hlt (m & Hrange & Hdiv)%not_prime_divide; auto.\n  destruct (prime_dec m) as [Hp | Hnp]; eauto.\n  destruct (H m) as (p & Hp); auto with *.\n  - unfold Zwf.\n    auto with *.\n  - exists p.\n    intuition.\n    eauto using Z.divide_trans.\nQed.\n\nInductive Factors : Z -> Prop :=\n| factors_1 : Factors 1\n| factors_prod : forall p m, prime p -> Factors m -> Factors (m * p).\nHint Constructors Factors.\n\nLemma pos_factors : forall n, 1 <= n -> Factors n.\nProof.\n  induction n using (well_founded_ind (Zwf_well_founded 0)).\n  intro Hn.\n  destruct (Zle_lt_or_eq _ _ Hn) as [Hgt | <-]; auto.\n  destruct (prime_dec n) as [Hp | Hnp].\n  - rewrite <- Z.mul_1_l.\n    auto.\n  - apply not_prime_divide_prime in Hnp; auto.\n    destruct Hnp as (p & Hrange & [n' ->] & Hp).\n    apply factors_prod; auto.\n    assert (1 <= n') as Hn'; try nia.\n    apply H; auto.\n    unfold Zwf.\n    nia.\nQed.\n\nLemma factors_pos : forall n, Factors n -> 1 <= n.\nProof.\n  intros.\n  induction H; auto with *.\n  destruct H.\n  apply Z.le_trans with m; auto.\n  rewrite <- Z.le_mul_diag_r; auto with *.\nQed.\nHint Resolve factors_pos.\n\n\nLemma divide_sq_prime : forall p b, prime p -> 1 <= b -> (p ^ 2 | b ^ 2) -> (p | b).\nProof.\n  intros p b Hp Hb Hdiv.\n  assert (p | b ^ 2) as Hdiv'. {\n    apply Z.divide_trans with (p ^ 2); auto with *.\n  }\n  clear Hdiv.\n  rewrite Z.pow_2_r in Hdiv'.\n  apply prime_mult in Hdiv'; tauto.\nQed.\n\n\nLemma divide_sq_inv : forall a b, 1 <= a -> 1 <= b -> (a ^ 2 | b ^ 2) -> (a | b).\nProof.\n  intros a b Ha Hb.\n  revert b Hb.\n  induction (pos_factors Ha); auto with *.\n  intros b Hb Hdiv.\n  destruct (@divide_sq_prime p b) as [k ->]; auto with *.\n  - apply Z.divide_trans with ((m * p) ^ 2); auto.\n    rewrite Z.pow_mul_l.\n    auto with *.\n  - apply Z.mul_divide_mono_r.\n    apply IHf; auto with *.\n    + destruct H.\n      nia.\n    + repeat rewrite Z.pow_mul_l in Hdiv.\n      eapply Z.mul_divide_cancel_r; eauto with *.\n      intros He%Z.pow_eq_0; subst; auto with *.\nQed.\n\nDefinition Square n := exists m, n = m ^ 2.\nLemma Square_pow_2 : forall n, Square (n ^ 2).\nProof.\n  intros.\n  exists n.\n  reflexivity.\nQed.\nHint Resolve Square_pow_2.\n\nLemma Square_square : forall n, Square (n * n).\nProof.\n  intros.\n  exists n.\n  lia.\nQed.\nHint Resolve Square_square.\n\nLemma Square_nonneg_root : forall n, Square n -> exists m, 0 <= m /\\ n = m ^ 2.\nProof.\n  intros n [m ->].\n  destruct (Z.lt_ge_cases m 0); eauto.\n  exists (- m).\n  split; auto with *.\n  lia.\nQed.\n\nLemma Square_product : forall n m, Square n -> Square m -> Square (n * m).\nProof.\n  intros n m [n' ->] [m' ->].\n  exists (n' * m').\n  lia.\nQed.\n\nLemma Square_product_inv_r : forall n m, 0 <> n -> Square (n * m) -> Square n -> Square m.\nProof.\n  intros n m Hnzn (k & Hnnegk & Hk)%Square_nonneg_root (n' & Hnnegn' & ->)%Square_nonneg_root.\n  destruct (Z.eq_dec m 0) as [| Hnzm];subst;[exists 0; lia|].\n  assert ((n' | k)) as [k' ->]. {\n    apply divide_sq_inv; try nia.\n    rewrite <- Hk.\n    auto with *.\n  }\n  exists k'.\n  rewrite <- Z.mul_cancel_r with (p := n' ^ 2); auto.\n  lia.\nQed.\n\nLemma Square_product_inv_l : forall n m, 0 <> m -> Square (n * m) -> Square m -> Square n.\nProof.\n  intros.\n  rewrite Z.mul_comm in *.\n  eapply Square_product_inv_r; eauto.\nQed.\n\nLemma prime_mult_sq_aux : forall p n m, prime p -> ~(p | m) -> (p ^ 2 | n * m) -> (p ^ 2 | n).\nProof.\n  intros p.\n  intros n m Hp Hnd [k Hk].\n  assert (p | n * m) as Hdivpnm. {\n    rewrite Hk.\n    auto with *.\n  }\n  apply prime_mult in Hdivpnm; auto.\n  destruct Hdivpnm as [[n' ->]|]; try contradiction.\n  assert (p | n' * m) as Hdivpn'm. {\n    destruct Hp.\n    replace (n' * m) with (k * p); auto with *.\n    nia.\n  }\n  apply prime_mult in Hdivpn'm; auto.\n  destruct Hdivpn'm as [[n'' ->]|]; try contradiction.\n  auto with *.\n  exists n''.\n  lia.\nQed.\n\nLemma prime_mult_sq : forall p n m, prime p -> rel_prime n m -> (p ^ 2 | n * m) -> (p ^ 2 | n) \\/ (p ^ 2 | m).\nProof.\n  intros p n m Hp Hrp Hdiv.\n  destruct (Z.eq_dec 0 m); subst; auto with *.\n  destruct (Z.eq_dec 0 n); subst; auto with *.\n  \n  assert (p | n * m) as [Hpn | Hpm]%prime_mult; auto with *.\n  - apply Z.divide_trans with (p ^ 2); auto with *.\n  - left.\n    apply prime_mult_sq_aux with m; auto.\n    apply rel_prime_factor_exclusive with n; auto with *.\n    now destruct Hp.\n  - right.\n    rewrite Z.mul_comm in Hdiv.\n    apply rel_prime_sym in Hrp.\n    apply prime_mult_sq_aux with n; auto.\n    apply rel_prime_factor_exclusive with m; auto with *.\n    now destruct Hp.\nQed.\n\nLemma rel_prime_square_l : forall n m,\n    1 <= n -> 1 <= m ->\n    rel_prime n m -> Square (n * m) -> Square n.\nProof.\n  intros n m Hposn Hposm Hrp (k & Hposk & Hk)%Square_nonneg_root.\n  \n  assert (1 <= k) as Hposk'; try nia.\n  clear Hposk.\n  revert Hk.\n  revert n Hposn m Hposm Hrp.\n  induction (pos_factors Hposk') as [| p k Hp].\n  - exists 1.\n    nia.\n  - intros n Hposn m Hpsm Hrp Hsq.\n    pose proof Hp as [Hppos _].\n    assert (p ^ 2 | n * m) as Hdivppnm. {\n      rewrite Hsq.\n      rewrite Z.pow_mul_l.\n      auto with *.\n    }\n    apply prime_mult_sq in Hdivppnm; auto with *.\n    destruct Hdivppnm as [[n' ->] | [m' ->]].\n    + apply Square_product; auto.\n      apply IHf with (m := m); auto with *.\n      * cut (0 <= n'); try nia.\n        apply Zmult_le_0_reg_r with (n := p * p); auto with *.\n        lia.\n      * eapply rel_prime_div; eauto with *.\n      * rewrite <- Z.sub_move_0_r.\n        apply Zmult_integral_l with (p ^ 2); try lia.\n        intros x%Z.pow_eq_0; auto with *.\n    + apply IHf with (m := m'); auto with *.\n      * cut (0 <= m'); try nia.\n        apply Zmult_le_0_reg_r with (n := p * p); auto with *.\n        lia.\n      * apply rel_prime_sym.\n        apply rel_prime_sym in Hrp.\n        eapply rel_prime_div; eauto with *.\n      * rewrite <- Z.sub_move_0_r.\n        apply Zmult_integral_l with (p ^ 2). try lia.\n        intros x%Z.pow_eq_0; auto with *.\n        lia.\nQed.\n\nLemma rel_prime_square_r : forall n m,\n    1 <= n -> 1 <= m ->\n    rel_prime n m -> Square (n * m) -> Square m.\nProof.\n  intros.\n  apply rel_prime_square_l with (m := n); auto.\n  - now apply rel_prime_sym.\n  - now rewrite Z.mul_comm.\nQed.\n\n\nTheorem P1 : forall n,\n    0 < n -> Z.gcd (n ^ 2 + 1) (5 * n ^ 2 + 9) = if Z.even n then 1 else 2.\nProof.\n  intros n Hpos.\n  replace (Z.gcd _ _ ) with (Z.gcd (n * n + 1) 4).\n  - rewrite Z.gcd_comm.\n    destruct (Z.Even_or_Odd n) as [He | Ho].\n    + rewrite (proj2 (Z.even_spec _) He).\n      destruct He as [m ->].\n      replace (2 * m * (2 * m) + 1) with (1 + m ^ 2 * 4); try lia.\n      now rewrite  Z.gcd_add_mult_diag_r.\n    + rewrite <- Z.negb_odd.\n      rewrite (proj2 (Z.odd_spec _) Ho).\n      simpl negb.\n      destruct Ho as [m ->].\n      replace (_ + _) with (2 * (1 + (m * m +  m) * 2)); try lia.\n      replace 4 with (2 * 2); auto.\n      rewrite Z.gcd_mul_mono_l.\n      now rewrite Z.gcd_add_mult_diag_r.\n  - rewrite <- (@Z.gcd_add_mult_diag_r _ 4 5).\n    f_equal; lia.\nQed.\n\nTheorem P2 : forall n, 0 < n -> ~Square ((n ^ 2 + 1) * (5 * n ^ 2 + 9)).\nProof.\n  intros n Hposn.\n  assert (1 <= n ^ 2 + 1) as Hp1; try nia.\n  assert (1 <= 5 * n ^ 2 + 9) as Hp2; auto with *.\n    \n  pose proof (P1 Hposn) as Hrp.\n  destruct (Z.Even_or_Odd n) as [He | Ho].\n  - rewrite <- Z.even_spec in He.\n    rewrite He in *.\n    rewrite Zgcd_1_rel_prime in Hrp.\n    intro Hsq.\n    pose proof (rel_prime_square_l Hp1 Hp2 Hrp Hsq) as (m & Hnnnegm & Hm)%Square_nonneg_root.\n    destruct (Z.le_gt_cases m n); nia.\n  - destruct Ho as [m ->].\n    replace (Z.even (2 * m + 1)) with (Z.even (1 + 2 * m)) in Hrp;try solve [f_equal; lia].\n    rewrite Z.even_add_mul_2 in Hrp.\n    remember (2 * m ^ 2 + 2 * m + 1) as X.\n    replace ((2 * m + 1) ^ 2 + 1) with (X * 2) in *; try lia.\n    remember (10 * m * (m + 1) + 7) as Y.\n    replace (5 * (2 * m + 1) ^ 2 + 9) with (Y * 2) in *; try lia.\n    rewrite Z.gcd_mul_mono_r_nonneg, Z.mul_id_l, Zgcd_1_rel_prime in Hrp; auto with *.\n    intro Hsq.\n    absurd (Square Y).\n    + intro HsqY.\n      cut (Y mod 4 = 3 /\\ Y mod 4 = 1); auto with *.\n      split.\n      * rewrite HeqY.\n        rewrite Z.add_mod; try discriminate.\n        rewrite <- Z.mul_assoc.\n        assert (2 | m * (m + 1)) as [m' Heqm']. {\n          destruct (Z.Even_or_Odd m) as [[m' ->] | [m' ->]].\n          - exists (m' * (2 * m' + 1)). lia.\n          - exists ((2 * m' + 1) * (m' + 1)). lia.\n        }\n        replace (10 * (m * (m + 1))) with (5 * m' * 4); try lia.\n        rewrite Z.mod_mul; auto with *.\n      * apply Square_nonneg_root in HsqY.\n        destruct HsqY as (Y' & HnnegY' & ->).\n        destruct (Z.Even_or_Odd Y') as [[Y'' ->] | [Y'' ->]]; try lia.\n        replace (_ ^ 2) with (1 + (Y'' ^ 2 + Y'') * 4); try lia.\n        rewrite Z.mod_add; auto with *.\n    + apply rel_prime_square_r with X; auto with *.\n      apply Square_product_inv_l with 4; auto with *.\n      * apply (eq_ind _ _ Hsq).\n        lia.\n      * now exists 2.\nQed.\n", "meta": {"author": "kazkob", "repo": "ut_entrance_exam_math", "sha": "ec3ea65d5232b2dff4572e85b84cdc04805ce5d8", "save_path": "github-repos/coq/kazkob-ut_entrance_exam_math", "path": "github-repos/coq/kazkob-ut_entrance_exam_math/ut_entrance_exam_math-ec3ea65d5232b2dff4572e85b84cdc04805ce5d8/2019_sci_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7718684649690555}}
{"text": "Require Import Arith.\n\n\n(* AVOIR SON COURS SOUS LES YEUX *)\n(* AVOIR SON COURS SOUS LES YEUX *)\n(* AVOIR SON COURS SOUS LES YEUX *)\n(* AVOIR SON COURS SOUS LES YEUX *)\n(* AVOIR SON COURS SOUS LES YEUX *)\n\n\n(**********************************************************************)\n(* Un prédicat particulier : =                                        *)\n(**********************************************************************)\n(* Un prédicat = est déjà défini en Coq. On peut considérer qu'il s'agit de la plus petite relation réflexive *)\n(* C'est un inductif avec une seule règle de construction : pour tout x on construit  x=x. *)\n(* La règle d'introduction de = est \"reflexivity\". *)\n\nLemma egalite : 4=4.\nProof.\nreflexivity.\nQed.\n\n(* Lorsqu'on a une ÉGALITÉ x = y dans une hypothèse, disons Heq, on peut remplacer\n- dans le but\n  + tous les x libres par des y avec\n    rewrite -> Heq.\n  + tous les y libres par des x avec\n    rewrite <- Heq.\n- dans une hypothèse, disons H,\n  + tous les x libres par des y avec\n    rewrite -> Heq in H.\n  + tous les y libres par des x avec\n    rewrite <- Heq in H.\n *)\n\nLemma ex_rewrite (x : nat)  : 1 + (x + 3) = 6 -> 1 + (x + 3) = 1 + x + 3  -> 1 + (1 + x + 3) = 1 + 6.\nProof.\nintro.\nintro.\nrewrite <- H.\nrewrite -> H0.\nreflexivity.\nQed.\n\n(* En Coq des CONSTRUCTEURS DIFFÉRENTS donnent des TERMES DIFFÉRENTS.  *)\n(* Si en hypothèse on trouve le prédicat d'égalité avec deux membres différents alors on peut achever la preuve directement avec\n\"discriminate\". *)\nLemma hyp_egal_diff : 3=4 -> False.\nProof.\n(* cette formule vient de l'introduction de la flèche *)\nintro Habs.\n(* on voit que l'hypothèse Habs est une égalité avec deux constructeurs différents, on finit la preuve directement avec \"discriminate\". *)\ndiscriminate.\nQed.\n\n\n(**********************************************************************)\n(* STRUCTURE DE BASE DES LISTES (FINIES) D'ENTIERS                    *)\n(**********************************************************************)\n\n\n(*On rappelle que les objets de type nat sont définis inductivement de façon similaire à \nInductive entiers : Set :=\n  | O : entiers\n  | S : entiers -> entiers.\n*)\n\nPrint nat.\n\n(* On dispose donc d'un principe d'induction nat_ind, construit à peu près comme vu en cours *)\nCheck nat_ind.\n(* Si on omet le \"forall P\" qui n'est PAS du premier ordre, on se retrouve bien avec deux branches :\n   - une branche qui demande de prouver sur le cas de base des nat, c'est-à-dire 0\n   - une branche qui demande de prouver sur un nat construit par S à partir d'un nat sur lequel on sait déjà prouevr la propriété\n   On peut en déduire la propriété sur tout nat obtenu par 0 et S. *)\n\n\n\n(* EN COQ : l'application de la tactique \"induction\" sur un nom\n   d'entier produira donc DEUX sous-buts (il y a bien 2 règles de\n   construction des entiers...) :\n  - Le sous-but correspondant au cas de bas O, \n  - Le sous-but correspondant au cas inductif où l'hypothèse d'induction apparaît\n    dans le contexte.\n\nCOMME ON SAIT que ça va mettre deux nouvelles choses dans la branche de droite et rien de nouveau dans celle de gauche on peut même nommer directement :\n   induction \"n\" as [ | \"m\" \"Hyp_Ind_m\"].\noù n est dans le cas de droite l'entier S m avec comme hypothèse d'induction que la propriété est vraie pour m (hypothèse nommée ici Hyp_Ind_m).  \n *)\n\n\n(* On définit les listes de nat *)\nInductive nlist : Set :=\n| nnil : nlist                  \n| ncons : nat -> nlist -> nlist. \n\n(* ... avec des notations confortables *)\nInfix \"::\" := ncons.\nNotation \"[]\" := nnil.\n\n(* Vous avez vu la génération des principes d'induction ? *)\nCheck nlist_ind.\n(* C'est tout à fait similaire au cas des nat.\n   Si on omet le \"forall P\" qui n'est PAS du premier ordre, on se retrouve bien avec deux branches :\n   - une branche qui demande de prouver sur le cas de base des listes\n   - une branche qui demande de prouver sur une liste construite par :: à partir d'une liste sur laquelle on sait déjà prouevr la propriété\n   On peut en déduire la propriété sur toute liste obtenue par [] et ::. *)\n\n\n\n\n\n(******************************************************************************)\n(* FONCTIONS NON-RECRUSIVES SUR LES TYPES INDUCTIFS                           *)\n(******************************************************************************)\n\n(* Si on n'a pas besoin d'hypothèse d'induction, il est en général suffisant de faire une étude par cas, \n   c'est-à-dire un destruct de l'objet étudié *)\n\nInductive Alphabet : Type :=\n| a : Alphabet\n| b : Alphabet.\n\n(* Prouvez les correction et complétude de la fonction comp_alphabet de votre TP de LIFLF, c'est-à-dire qu'elle retourne true si et seulement si ses deux paramètres sont égaux\n  - on procède par cas sur les deux paramètres\n  - on peut être amené à faire des calculs (avec simpl dans le but ou simpl in toto dans l'hypothèse toto. *)\nDefinition comp_alphabet (x : Alphabet) (y : Alphabet) : bool := (* mettez votre code ici *)\nmatch (x, y) with\n| (a,a) => true\n| (b, b) => true\n| _ => false\nend.\n\n\nTheorem comp_alphabet_ssi (x : Alphabet) (y : Alphabet) : (comp_alphabet x y = true -> x = y) /\\ (x = y -> comp_alphabet x y = true).\nProof.\nsplit.\n-intro h0.\ninduction x as [a | b].\ninduction y as [a | b].\nreflexivity.\ndiscriminate.\ninduction y as [a | b].\ndiscriminate.\nreflexivity.\n-intro h0.\ninduction x as [a | b].\ninduction y as [a | b].\nreflexivity.\ndiscriminate.\ninduction y as [a | b].\ndiscriminate.\nreflexivity.\nQed.\n\n\n\n(* On rappelle la fonction de comparaison sur les option nat codée en LIFLF *)\nDefinition comp_option_nat (x 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\n(* EN COQ : si on a une hypothèse H : forall x, P(x) on peut la\n spécialiser en une nouvelle hypothèse pour une certaine valeur de x,\n disons n. Pour celà on invoque \"pose (H n) as nouveauH\".  On crée\n alors une nouvelle hypothèse qui s'appelle nouveauH qui est un cas\n particulier de H, celui où x vaut n : nouveauH : P(n)\n*)\n\n\n(* Montrer que (comp_option_nat x y) retourne true SEULEMENT SI x=y. \n   on utilisera le théorème\n   beq_nat_true: forall n m : nat, Nat.eqb n  m = true -> n = m \n   qu'on spécialisera aux bons paramètres \"n_fixe\", \"m_fixe\" avec \n   pose (beq_nat_true \"n_fixe\" \"m_fixe\") as \"nom_de_la_nouvelle_hypothèse\".\n   \n  ATTENTION : Nat.eqb e1 e2 s'écrit aussi e1 =? e2\n\n*)\nTheorem comp_option_nat_seulement_si (x : option nat) (y : option nat) : comp_option_nat x y = true -> x = y.\nProof.\ninduction x.\n-induction y.\n+intro h0.\npose (beq_nat_true a0 a1) as h1.\ndestruct h1.\nrewrite <- h0.\nreflexivity.\nreflexivity.\n+intro h0.\ndiscriminate.\n-induction y.\n+intro h0.\npose (beq_nat_true a0) as h1.\ndiscriminate.\n+intro h0.\nreflexivity.\nQed.\n\n\n\n(******************************************************************************)\n(* FONCTIONS RECURSIVES ET INDUCTION SUR LES ENTIER                           *)\n(******************************************************************************)\n\n(* Exercice : montrer que la fonction plus appliquée à 0 et un x quelconque retourne x. *)\n(* La définition de plus est récursive sur le paramètre de gauche, donc pas de problème ici, c'est juste un calcul (simpl) *)\nLemma plus_Z_l (x : nat) : plus 0 x = x.\nProof.\nsimpl.\nreflexivity.\nQed. \n\n(* Exercice : montrer que la fonction plus appliquée un x quelconque et 0 retourne x. *)\n(* Mmmh là il faut travailler par induction sur x... *)\n(* on utilise \"induction x as...\" qui invoque la règle nat_ind. *)\nLemma plus_Z_r (x : nat) : plus x 0 = x.\nProof.\ninduction x as [ | n].\n-reflexivity.\n-simpl.\nrewrite -> IHn.\nreflexivity.\nQed. \n\n\n\n(******************************************************************************)\n(* FONCTIONS RECURSIVES ET INDUCTION SUR LES LISTES                           *)\n(******************************************************************************)\n\n(* Exercice *)\n(* Définir \"concat\" la fonction de concaténation de deux listes l1 et l2 (par récursion sur l1) *)\nFixpoint concat (l1 l2 : nlist) : nlist := (* écrire votre code ici *)\n  match l1 with\n  | [] => l2\n  | n::l11 => n::(concat l11 l2)\n  end.\n\n(* On note ++ en notation infix pour la concatenation *)\nInfix \"++\" := concat.\n\n(* VU EN COURS : fonction de longueur des listes                              *)\nFixpoint length (l : nlist) : nat :=\n  match l with\n  | []     => 0 \n  | x :: l => S(length l) \n  end.\n\n(* Exercice : montrer que la fonction retourne 0 SEULEMENT SI la liste\n   est vide *)\nLemma length_zero_seulement_si_vide (l : nlist) : length l = 0 -> l=[].\nProof.\nintro h0.\ninduction l as [ | n l1].\n-reflexivity.\n-destruct IHl1.\n+rewrite <- h0.\ndiscriminate.\n+discriminate.\nQed.\n\n\n\n(* Exercice : montrer que la fonction appliquée à la concaténation de\ndeux listes quelconques l1 l2 retourne la somme des applications de\ncette fonction à chacune des deux listes.*)\nLemma length_of_concat (l1 : nlist) (l2 : nlist) : length (l1 ++ l2) = length l1 + length l2.\nProof.\ninduction l1 as [ | l10 H1].\n-simpl.\nreflexivity.\n-simpl.\nrewrite -> IHH1.\nreflexivity.\nQed.\n\n\n\n(* QUANTIFICATION UNIVERSELLE *)\n(* Règle d'introduction du quantificateur universel *)\n(* La tactique utilisée pour la règle d'introduction de l'universel est intro \"nom de la variable générique\". *)\n\n(* Prouver que pour tout nat x et toute liste de nat l,\nla liste vide n'est pas obtenue par l'ajout de x en tête de l. *)\nLemma nil_neq_cons : forall (x:nat), forall (l:nlist), [] = x :: l -> False.\nProof.\n  intro un_element_general.\n  intro une_liste_generale.\n  intro Habsurde.\n    (* poursuivre la preuve *)\n  discriminate.\nQed.\n\n\n\n(* Exprimer et montrer que pour tout élément x et toutes listes l1 et\nl2, ajouter x en tête de la concaténation de l1 et l2 est\nla même chose que concaténer l1 avec x en tête et l2. *)\n(* pas de difficulté, c'est juste un pas de calcul (simpl). *)\n\nLemma concat_cons : forall (x:nat), forall (l1:nlist), forall (l2:nlist), concat (x::l1) l2 = x::concat l1 l2 -> True.\nProof.\nintro x.\nintro l1.\nintro l2.\nsimpl.\nreflexivity.\nQed.\n\n(* Eprimer et montrer maintenant que pour toute liste l1, concaténer à l1 la liste vide renvoie exactement la liste l1. *)\n(* Comme on a défini concat par récursion sur le premier paramètre, il va falloir une induction... *)\nLemma concat_nil_r : forall (l1:nlist), concat l1 [] = l1 -> True.\nProof.\ninduction l1 as [ | l10 H1].\n-simpl.\nreflexivity.\n-simpl.\nreflexivity.\nQed.\n\n", "meta": {"author": "MartinLeocmach", "repo": "LIFLC", "sha": "6bc4fc692b1555dfa13e59600c3845e405a95d94", "save_path": "github-repos/coq/MartinLeocmach-LIFLC", "path": "github-repos/coq/MartinLeocmach-LIFLC/LIFLC-6bc4fc692b1555dfa13e59600c3845e405a95d94/liflc_tp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7717161110396927}}
{"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    Try to prove the following theorems using no\n    lemma and minimizing the number of applications of\n    the tactic case\n*)\n\n(** *** Exercise 1:\n*)\n\nLemma andTb p : true && p = p.\n(*D*)Proof. by []. Qed.\n\n(** *** Exercise 2:\n*)\n\nLemma andbT p : p && true = p.\n(*D*)Proof. by case: p. Qed.\n\n(** *** Exercise 3:\n*)\n\nLemma orbC p q : p || q = q || p.\n(*D*)Proof. by case: p; case: q. Qed.\n\n(** *** Exercise 4:\n*)\nGoal forall p q,    (p && q) || (   p && ~~ q) || \n                 (~~ p && q) || (~~ p && ~~ q). \n(*D*)Proof. by move=> p q; case: p; case: q. Qed.\n\n(** *** Exercise 5 :\n*)\nGoal forall p q r, (p || q) && r = r && (p || q).\n(*D*)Proof. by move=> p q r; case: (p || q); case: r. Qed.\n\nGoal forall n, n < n.+1.\nby [].\nQed.\n\n(** *** Exercise 6  :\n   - look up what [==>] \n*)\n(*D*)Locate \"==>\".\n(*D*)Print implb.\nLemma implybE p q : p ==> q = ~~ p || q.\n(*D*) Proof. by case: p. Qed.\n\n(** *** Exercise 7  :\n    Try to prove using the case tactic and alternatively\n    without using the case tactic\n*)\n\nLemma negb_imply p q : ~~ (p ==> q) = p && ~~ q.\n(*D*) (* Proof. by case: p. Qed. *)\n(*D*) Proof. by rewrite implybE negb_or negbK. Qed.\n\n\n(** *** Exercise 8  :\n    Try to prove using the case tactic and alternatively\n    without using the case tactic\n*)\nLemma Peirce p q : ((p ==> q) ==> p) ==> p.\n(*D*) (* Proof. by case: p; case: q. Qed. *)\n(*D*) Proof. by rewrite implybE negb_imply implybE orbK orNb. Qed.\n\n\n(** *** Exercise 9 :\n    - what is [(+)] ?\n    - prove this using move and rewrite\n*)\nLemma find_me p q :  ~~ p = q -> p (+) q.\n(*D*)Locate \"(+)\".\n(*D*)Search _ addb negb.\n(*D*)Proof. by move=> np_q; rewrite -np_q addbN negb_add. Qed.\n\n\n(** ***\n    maxn defines the maximum of two numbers \n*)\n\nPrint maxn.\nSearch maxn in ssrnat.\n\n(** ***\n    We define the maxinum of three number as \n    folllow  \n*)\n\nDefinition max3n a b c :=\n   if a < b then maxn b c else maxn a c.\n\n(** ***\n    Try to prove the following theorem\n    (you may use properties of maxn)\n*)\n\n\n(** *** Exercise 10\n*)\n\nLemma max3n3n a : max3n a a a = a.\n(*D*) Proof. by rewrite /max3n if_same maxnn. Qed.\n\n(** *** Exercise 11\n*)\nLemma max3E a b c : max3n a b c = maxn (maxn a b) c.\n(*D*) Proof. by rewrite /max3n /maxn; case: (a < b). Qed.\n\n(** *** Exercise 12\n*)\nLemma max3n_213 a b c : max3n a b c = max3n b a c.\n(*D*) Proof. by rewrite max3E (maxnC a) -max3E. Qed.\n\n(** *** Exercise 13\n*)\nLemma max3n_132 a b c : max3n a b c = max3n a c b.\n(*D*) Proof. by rewrite max3E -maxnA (maxnC b) maxnA -max3E. Qed.\n\n(** *** Exercise 14\n*)\nLemma max3n_231 a b c : max3n a b c = max3n b c a.\n(*D*) Proof. by rewrite max3n_213 max3n_132. Qed.\n\n(** ***\n    We define functions that test if 3 natural numbers are\n    in increasing (or decreasing) order \n*)\n\nDefinition order3n (T : Type) (r : rel T) x y z := (r x y) && (r y z).\nDefinition incr3n := order3n nat (fun x y => x <= y).\nDefinition decr3n := order3n nat (fun x y => y <= x).\n\n(** *** Exercise 15\n*)\nLemma incr3n_decr a b c : incr3n a b c = decr3n c b a.\n(*D*) Proof. by rewrite /incr3n /order3n andbC. Qed.\n\n(** *** Exercise 16\n*)\n\nLemma incr3_3n a : incr3n a a a.\n(*D*) by rewrite /incr3n /order3n leqnn. Qed.\n\n(** *** Exercise 17\n*)\n\nLemma decr3_3n a : decr3n a a a.\n(*D*) by rewrite -incr3n_decr incr3_3n. Qed.\n\n(** *** Exercise 18\n*)\n\nLemma incr3n_leq12 a b c : incr3n a b c -> a <= b.\n(*D*) by rewrite /incr3n /order3n; case: (_ <= _). Qed.\n\n(** *** Exercise 19\n*)\nLemma incr3n_leq23 a b c : incr3n a b c -> b <= c.\n(*D*) by rewrite /incr3n /order3n; case: (_ <= _). Qed.\n\n(** *** Exercise 20\n*)\nLemma incr3n_eq a b c : incr3n a b a = (a == b).\n(*D*) by rewrite /incr3n /order3n eqn_leq. Qed.\n \n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/exercise2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8976952893703477, "lm_q1q2_score": 0.7717160863648621}}
{"text": "Inductive bool : Type :=\n| false : bool  \n| true : bool.\n\nDefinition neg_b (b:bool) : bool :=\nmatch b with\n| false => true\n| true => false\nend.\n\nDefinition and_b (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n| false => false\n| true => b2\nend. \n\nDefinition or_b (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n| true => true\n| false => b2\nend.\n\nNotation \"a || b\" := (or_b a b).\nNotation \"a && b\" := (and_b a b).\nNotation \"- a\" := (neg_b a).\n\n\nCheck (false && true).\n\n    (* Equivalent à : - simpl. reflexivity. tapé 4 fois (pour chaque pair (a, b))*)\nTheorem deMorgan : forall a b, (-a || -b) = -(a && b).\nProof. \n    intros a b.\n    destruct a; destruct b; (simpl; reflexivity).\nQed.\n\n\nTheorem doubleNeg : forall n, --n = n.\nProof.\n    intro n.\n    destruct n.\n    - (*cas n = false*) trivial. (*équivalent à simpl. reflexivity. (+ d'autre trucs)*)\n    - (* cas n = true*) trivial.\nQed.\n\nTheorem existBool : exists p, p && true = true.\nProof.\n   exists true.\n   simpl. reflexivity.\nQed.\n\nTheorem idempotence : forall p, p && p = p.\nProof.\n  intro p.\n  destruct p.\n  - trivial.\n  - trivial.\nQed.", "meta": {"author": "staceb", "repo": "rebasing", "sha": "9fa227fcc169d32493c2f0440320ead8b9d8bf85", "save_path": "github-repos/coq/staceb-rebasing", "path": "github-repos/coq/staceb-rebasing/rebasing-9fa227fcc169d32493c2f0440320ead8b9d8bf85/Logical-proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7716405159737747}}
{"text": "(* Software Foundations *)\n(* Exercice 4 stars, subseq *)\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nInductive subseq: (list nat)->(list nat)-> Prop :=\n|seq_nil: forall l, subseq [] l\n|seq_1: forall n l1 l2, subseq l1 l2 -> subseq l1 (n::l2) \n|seq_2: forall n l1 l2, subseq l1 l2 -> subseq (n::l1) (n::l2).\n\n\nTheorem subseq_refl: forall l, subseq l l.\nProof.\n    intros. induction l as [|h t].\n    apply seq_nil.\n    apply seq_2. apply IHt.\nQed.\n\nTheorem subseq_append: forall l1 l2 l3, subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n    intros. induction H.\n    apply seq_nil.\n    simpl. apply seq_1. apply IHsubseq.\n    simpl. apply seq_2. apply IHsubseq.\nQed.\n\nTheorem subseq_transitive: forall l1 l2 l3, subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n    intros.\n    induction H0. \n    inversion H. apply seq_nil.\n    apply seq_1. apply IHsubseq. apply H.\nAbort.\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/subseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7716163762480814}}
{"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 aexp_ex1 : aexp := Amu (Apl (Aco 1) (Ava 2)) (Aco 3).\nDefinition aexp_ex2 : aexp := Apl (Amu (Ava 0) (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\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\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 n => n\n  | Ava i => get i s\n  | Apl a1 a2 => eval a1 s + eval a2 s\n  | Amu a1 a2 => eval a1 s * eval a2 s\n  | Amo a1 a2 => eval a1 s - eval a2 s\n  end.\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  | Aco n => Aco n\n  | Ava i => Ava (S i)\n  | Apl a1 a2 => Apl (renomme a1) (renomme a2)\n  | Amu a1 a2 => Amu (renomme a1) (renomme a2)\n  | Amo a1 a2 => Amo (renomme a1) (renomme a2)\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\nTheorem eval_renomme_decale : forall (a: aexp) (s: state),\neval a s = eval (renomme a) (decale s).\nProof.\n  intros a s.\n  induction a as [|i|a1 IH1 a2 IH2|a1 IH1 a2 IH2|a1 IH1 a2 IH2].\n  - reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IH1. rewrite IH2. reflexivity.\n  - simpl. rewrite IH1. rewrite IH2. reflexivity.\n  - simpl. rewrite IH1. rewrite IH2. reflexivity.\nQed. \n\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 : Set := \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\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\n\nFixpoint evalb (b: bexp) (s: state) : bool :=\n  match b with\n    | Btrue => true\n    | Bfalse => false\n    | Bnot b' => match evalb b' s with\n                | true => false\n                | false => true\n                end\n    | Band b1 b2 => match evalb b1 s, evalb b2 s with\n                    | true, true => true\n                    | _, _ => false\n                    end\n    | Bor b1 b2 => match evalb b1 s, evalb b2 s with\n                    | false, false => false\n                    | _, _ => true\n                    end\n    | Beq b1 b2 => match evalb b1 s , evalb b2 s with\n                    | true, true | false, false => true\n                    | _, _ => false\n                    end\n    end.\n\n\nDefinition bexp_ex1 := Bnot ( Btrue ).\nDefinition bexp_ex2 := Band ( Btrue ) ( Bfalse ).\nDefinition bexp_ex3 := Bor ( Btrue ) ( Bfalse ).\n\nExample evalb_ex1_ex1 : evalb bexp_ex1 s_ex1 = false.\nProof. reflexivity. Qed.\nExample evalb_ex2_ex1 : evalb bexp_ex2 s_ex1 = false.\nProof. reflexivity. Qed.\nExample evalb_ex3_ex1 : evalb bexp_ex3 s_ex1 = true.\nProof. reflexivity. Qed.\n\n\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/td3_bis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7715718024943997}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Lists.List.\nLocal Open Scope Z.\n\nLocal Open Scope Z_scope.\nModule Z.\n  Definition modexp_pos a p m := Pos.iter (fun z => (a * z) mod m) (1 mod m) p.\n  Definition modexp a p m\n    := match p with\n       | 0 => 1 mod m\n       | Z.neg _ => 0\n       | Z.pos p => modexp_pos a p m\n       end.\n  Lemma modexp_pos_correct a p m\n    : modexp_pos a p m = Z.pow_pos a p mod m.\n  Proof.\n    cbv [Z.pow_pos modexp_pos].\n    erewrite Pos.iter_swap_gen with (f := fun a => a mod m).\n    { reflexivity. }\n    { cbv beta; intros; now rewrite Zmult_mod_idemp_r. }\n  Qed.\n  Lemma modexp_correct a p m\n    : modexp a p m = a ^ p mod m.\n  Proof.\n    cbv [modexp Z.pow]; destruct p;\n      now rewrite ?modexp_pos_correct, ?Zmod_0_l.\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/ModExp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523027, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7714650600206008}}
{"text": "(** * ProofObjects: Working with Explicit Evidence in Coq *)\n\nRequire Export Logic.\n\n(* ##################################################### *)\n\n(**  We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types (like [nat] or [list]) and functions\n    over these types, and for _proving_ properties of these programs,\n    using inductive propositions (like [ev] or [eq]), implication, and \n    universal quantification.  So far, we have treated these mechanisms\n    as if they were quite separate, and for many purposes this is\n    a good way to think. But we have also seen hints that Coq's programming and \n    proving facilities are closely related. For example, the\n    keyword [Inductive] is used to declare both data types and \n    propositions, and [->] is used both to describe the type of\n    functions on data and logical implication. This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are almost\n    the same thing.  In this chapter we will study how this 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 evidence, \n    which can be thought of as a data structure. If the proposition\n    is an implication like [A -> B], then its proof will be an \n    evidence _transformer_: a recipe for converting evidence for\n    A into evidence for B.  So at a fundamental level, proofs are simply\n    programs that manipulate evidence.\n*)\n(**\n    Q. If evidence is data, what are propositions themselves?\n\n    A. They are types!\n\n    Look again at the formal definition of the [beautiful] property.  *)\n\nPrint beautiful. \n(* ==>\n  Inductive beautiful : nat -> Prop :=\n      b_0 : beautiful 0\n    | b_3 : beautiful 3\n    | b_5 : beautiful 5\n    | b_sum : forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m)\n*)\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(** 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(** Now let's look again at a previous proof involving [beautiful]. *)\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. Qed.\n\n(** Just as with ordinary data values and functions, we can use the [Print]\ncommand to see the _proof object_ that results from this proof script. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful = b_sum 3 5 b_3 b_5  \n     : beautiful 8  *)\n\n(** In view of this, we might wonder whether we can write such\n    an expression ourselves. Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_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   apply (b_sum 3 5 b_3 b_5).\nQed.\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(* ##################################################### *)\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   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(**\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, 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 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  (* FILL IN HERE *) Admitted.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  (* FILL IN HERE *) admit.\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 *) Admitted.\n\nDefinition nine_is_beautiful' : beautiful 9 :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Quantification, 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, beautiful n -> beautiful (3+n).\nProof.\n   intros n H.\n   apply b_sum.\n   apply b_3.\n   apply H.\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 : nat) => fun (H : beautiful n) =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n : nat, 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(** When we view the proposition being proved by [b_plus3] as a function type,\n    one aspect of it may seem a little unusual. The second argument's\n    type, [beautiful n], mentions the _value_ of the first argument, [n].\n    While such _dependent types_ are not commonly found in programming\n    languages, even functional ones like ML or Haskell, they can\n    be useful there too.  \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 name\n    to the type on the LHS of the arrow. *)                                           \n\n(** For example, consider this proposition: *)\n\nDefinition beautiful_plus3 : Prop := \n  forall n, forall (E : beautiful n), beautiful (n+3).\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    beautiful.  But the name [E] for this evidence is not used in the\n    rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name for it.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition beautiful_plus3' : Prop := \n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition beatiful_plus3'' : Prop :=\n  forall n, beautiful n -> beautiful (n+3). \n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n\n(** **** Exercise: 3 stars (b_times2) *)\n(** First prove this theorem using tactics. *)\n\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now write a corresponding proof object directly. *)\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n\n\n\n(** **** Exercise: 2 stars, optional (gorgeous_plus13_po) *) \n(** Give a proof object corresponding to the theorem [gorgeous_plus13] from Prop.v *)\n\nDefinition gorgeous_plus13_po: forall n, gorgeous n -> gorgeous (13+n):=\n   (* FILL IN HERE *) admit.\n(** [] *)\n\n\n\n\n(** It is particularly revealing to look at proof objects involving the \nlogical connectives that we defined with inductive propositions in Logic.v. *)\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(** **** Exercise: 1 star, optional (case_proof_objects) *)\n(** The [Case] tactics were commented out in the proof of\n    [and_example] to avoid cluttering the proof object.  What would\n    you guess the proof object will look like if we uncomment them?\n    Try it and see. *)\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    (* 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 easier to understand. It is still\n    a little complicated, but after performing some simple reduction\n    steps, we can see that all that is really happening is taking apart \n    a record 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        (fun H0 : Q /\\ P => H0)\n            match H with\n            | conj HP HQ => (fun (HP0 : P) (HQ0 : Q) => conj Q P HQ0 HP0) HP HQ\n            end\n      : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** After simplifying some direct application of [fun] expressions to arguments,\nwe get: *)\n\n(* ===> \n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     match H with\n     | conj HP HQ => conj Q P HQ HP\n     end \n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\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 :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n\n(** **** Exercise: 2 stars, advanced (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\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\n(** Recall that we model an existential for a property as a pair consisting of \na witness value and a proof that the witness obeys that property. \nWe can choose to construct the proof explicitly. \n\nFor 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\n(** **** Exercise: 2 stars (ex_beautiful_Sn) *)\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\n(* ##################################################### *)\n(** ** Giving Explicit Arguments to Lemmas and Hypotheses *)\n\n(** Even when we are using tactic-based proof, it can be very useful to\nunderstand the underlying functional nature of implications and quantification. \n\nFor example, it is often convenient to [apply] or [rewrite] \nusing a lemma or hypothesis with one or more quantifiers or \nassumptions already instantiated in order to direct what\nhappens.  For example: *)\n\nCheck plus_comm.\n(* ==> \n    plus_comm\n     : forall n m : nat, n + m = m + n *)\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. *) \n      (* rewrites in the first possible spot; not what we want *)\n   rewrite (plus_comm b a).  (* directs rewriting to the right spot *)\n   reflexivity.  Qed.\n\n\n(** In this case, giving just one argument would be sufficient. *)\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.  Qed.\n\n(** Arguments must be given in order, but wildcards (_)\nmay be used to skip arguments that Coq can infer.  *)\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. Qed.\n\n(** The author of a lemma can choose to declare easily inferable arguments\nto be implicit, just as with functions and constructors. \n\n  The [with] clauses we've already seen is really just a way of\n  specifying selected arguments by name rather than position:  *)\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. Qed.\n\n\n(** **** Exercise: 2 stars (trans_eq_example_redux) *)\n(** Redo the proof of the following theorem (from MoreCoq.v) using\nan [apply] of [trans_eq] but _not_ using a [with] clause. *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ##################################################### *)\n(** ** Programming with Tactics *)\n\n(** If we can build proofs with explicit terms rather than\ntactics, you may be wondering if we can build programs using\ntactics rather than explicit terms.  Sure! *)\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\nEval compute in add1 2. \n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than with\n[:=] followed by a term.  This tells Coq to enter proof scripting mode\nto build an object of type [nat -> nat].  Also, we terminate the proof\nwith [Defined] rather than [Qed]; this makes the definition _transparent_\nso that it can be used in computation like a normally-defined function.  \n\nThis feature is mainly useful for writing functions with dependent types,\nwhich we won't explore much further in this book.\nBut it does illustrate the uniformity and orthogonality of the basic ideas in Coq. *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.7714308772075877}}
{"text": "Require Import List.\nRequire Import Nat.\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(*define insert sort *) \n\nFixpoint insert (n : nat) (sorted : list nat) : list nat :=\n  match sorted with\n  | nil => n :: nil\n  | m :: t => if n <? m then n :: sorted\n                       else m :: (insert n t)\n  end.\n\nExample insert1 : insert 5 [4;6] = [4;5;6].\n Proof. reflexivity. Qed.\n\nExample insert2 : insert 7 [2;3;5;7;7;9;8] = [2;3;5;7;7;7;9;8].\n Proof. reflexivity. Qed.\n\nFixpoint insert_sort (arr : list nat) : list nat :=\n  match arr with\n  | nil => nil\n  | m :: t =>insert m (insert_sort t)\n  end. \n\nCheck insert_sort [7;5;9;8;3;7;7;2].\n\nExample test_insert_sort1 : insert_sort [7;5;9;8;3;7;7;2] = [2;3;5;7;7;7;8;9].\n Proof. reflexivity. Qed.\n\nExample test_insert_sort2 : insert_sort [] = [].\n Proof. reflexivity. Qed.\n\nExample test_insert_sort3 : insert_sort [5;4;3;2;1;0] = [0;1;2;3;4;5].\n Proof. reflexivity. Qed.\n\n(*define count func*)\n\nFixpoint count (v : nat) (l : list nat) : nat :=\n  match l with\n  | nil => O\n  | h :: t => if v =? h then S(count v t)\n                        else count v t\n  end.\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(*define is_sorted*)\n\n\nFixpoint is_sorted (arr : list nat) : bool :=\n  match arr with\n  | nil => true\n  | h :: t => match t with\n               | nil => true\n               | k :: g => if h <=? k then is_sorted t \n                                      else false\n               end\n  end.\n\nExample test_is_sorted1: is_sorted [7;5;9;8;3;7;7;2] = false.\n  Proof. reflexivity. Qed.\n\nExample test_is_sorted2: is_sorted [2;3;5;7;7;7;8;9] = true.\n  Proof. reflexivity. Qed.\n\nExample test_is_sorted3: is_sorted [] = true.\n  Proof. reflexivity. Qed.\n\n(*Proof*)\n\n(* nat lemmas *)\n\nLemma plus_1_neq_0_left : forall n : nat,\n  S n =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nLemma plus_1_neq_0_right : forall n : nat,\n  0 =? S n = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nLemma nat_is_positive_right : forall n : nat,\n  0 <? S n = true.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nLemma nat_is_positive_right2 : forall n : nat,\n  0 <=? S n = true.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nLemma nat_is_not_negative_left : forall n : nat,\n  S n <? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\n(* comparison lemmas *)\n\nLemma mon_uneq :\n   forall n m : nat, S n <? S m = true -> n <? m = true.\nProof.\nintros n m. destruct (n <? m) eqn:E; try auto.\nunfold ltb in *. remember (S n) as t. simpl.\nrewrite E. auto.\nQed.\n\nLemma eq_not_less :\n  forall n t : nat, n =? t = true -> n <? t = false.\nProof.\nintros n. induction n.\n  - intros t L. destruct t.\n     + reflexivity.\n     + rewrite plus_1_neq_0_right in L. discriminate L.\n  - intros t L. destruct t.\n     + simpl. rewrite plus_1_neq_0_left in L. discriminate L.\n     + simpl in L. apply IHn. rewrite -> L. reflexivity.\nQed.\n\nLemma eq_ref :\n  forall n : nat, n =? n = true.\nProof.\n  induction n. \n  + reflexivity. \n  + simpl. rewrite -> IHn. reflexivity. \nQed.\n\nLemma eq_or_less_ref :\n  forall n : nat, n <=? n = true.\nProof.\n  induction n. \n  + reflexivity. \n  + simpl. rewrite -> IHn. reflexivity. \nQed.\n\nLemma less_is_less_or_eq :\n  forall n m : nat, n <? m = true -> (n <=? m) = true.\nProof.\n  intros n. induction n.\n  - intros m L. destruct m.\n     + reflexivity.\n     + rewrite nat_is_positive_right2. reflexivity.\n  - intros m L. destruct m.\n     + simpl. rewrite nat_is_not_negative_left in L. discriminate L.\n     + simpl in L. apply IHn. rewrite -> mon_uneq. reflexivity.\n       rewrite -> L. reflexivity.\nQed.\n\nLemma eq_is_less_or_eq :\n  forall n m : nat, n =? m = true -> (n <=? m) = true.\nProof.\n  intros n. induction n.\n  - intros m L. destruct m.\n     + reflexivity.\n     + rewrite nat_is_positive_right2. reflexivity.\n  - intros m L. destruct m.\n     + simpl. rewrite plus_1_neq_0_left in L. discriminate L.\n     + simpl in L. apply IHn. apply L.\nQed.\n\nLemma h0:\n  forall n m, n =? m = true -> n = m.\nProof.\n  intros n.\n  induction n.\n  - intros m L. destruct m.\n    + reflexivity.\n    + rewrite plus_1_neq_0_right in L. discriminate.\n  - intros m L. destruct m.\n    + rewrite plus_1_neq_0_left in L. discriminate.\n    + simpl in L. \n      assert (H: n = m -> S n = S m). { intro. rewrite <-H. reflexivity. }\n      apply H. apply IHn. apply L.\nQed.\n\nLemma h0b:\n  forall n m, n = m -> n =? m = true.\nProof.\n  intros n m L.\n  rewrite L.\n  apply eq_ref.\nQed.\n\nLemma trans_eq:\n  forall n m k, n =? m = true /\\ k =? m = true -> n =? k = true.\nProof.\n  intros n m k [L1 L2].\n  apply h0 in L1. apply h0 in L2.\n  rewrite <- L1 in L2. symmetry in L2. apply h0b in L2. apply L2.\nQed.\n\nLemma leb_n0 : forall n, n <=? 0 = true -> n =? 0 = true.\nProof. destruct n; intro H.\napply eq_ref.\nsimpl in H. discriminate H.\nQed.\n\nLemma trans_leb:\n  forall n m k, n <=? m = true /\\ m <=? k = true -> n <=? k = true.\nProof.\nintros n m k. generalize dependent m. generalize dependent n.\ninduction k; intros n m H; destruct H as [H1 H2].\n- apply leb_n0 in H2. apply h0 in H2. rewrite H2 in H1. assumption.\n- destruct n.\n  + reflexivity.\n  + simpl. destruct m.\n    * simpl in H1. discriminate.\n    * apply IHk with (m := m). simpl in H1, H2. auto.\nQed.\n\nSearch _ le \"trans\".\n\n\nLemma l4 :\n forall n k, (n <? k = false /\\ n =? k = false) -> k <? n = true.\nProof.\nunfold ltb. induction n.\n- destruct k; simpl; intro H; destruct H; discriminate.\n- destruct k; intro H.\n  + reflexivity.\n  + apply IHn. destruct H as [H1 H2]. remember (S n) as t in H1.\n    simpl in H1, H2. rewrite Heqt in H1. rewrite H1, H2. split; reflexivity.\nQed.\n\nLemma leb_antisym : forall n m, (n <=? m) = true /\\ (m <=? n) = true\n -> (n =? m) = true.\nProof.\ninduction n, m; try reflexivity; simpl; intro H;\ndestruct H as [H1 H2]; try discriminate.\napply IHn. split; assumption.\nQed.\n\nLemma eqn_sym : forall n m, (n =? m) = (m =? n).\nProof. induction n, m; simpl; try reflexivity; apply IHn. Qed.\n\nLemma eq1:\n  forall n m, n <=? m = true /\\ n <? m = false -> n =? m = true.\n\nProof.\nintros n m H. destruct H as [H1 H2].\ndestruct (n =? m) eqn: E1; try reflexivity.\nrewrite <- H2. apply l4. split.\n- destruct (m <? n) eqn: E2; try reflexivity.\n  apply less_is_less_or_eq in E2.\n  rewrite <- E1. symmetry. apply leb_antisym.\n  split; assumption.\n- rewrite <- E1. apply eqn_sym.\nQed.\n\n\n(* sort_array lemmas *)\n\nLemma push_in_nonsorted:\n  forall l m, is_sorted (l) = false -> is_sorted(m :: l) = false.\nProof.\n  intros l n L.\n  simpl.\n  destruct l as [| t h] eqn:E1.\n  - simpl in L. discriminate.\n  -  destruct (n <=? t) eqn:E2.\n    + apply L.\n    + reflexivity.   \nQed.\n\n\nLemma sublist_of_sorted_is_sorted :\n  forall l n, is_sorted (n :: l) = true -> is_sorted l = true.\nProof.\n  intros l n L.\n  destruct (is_sorted l) as [| t h] eqn:E1.\n  - reflexivity.\n  - apply push_in_nonsorted with(m:=n) in E1. \n    rewrite E1 in L. discriminate.   \nQed.\n\nLemma l0:\n forall n m, n =? m = true -> [n] = [m].\nProof.\n  intros n m L.\n  rewrite h0 with (n:=n) (m:=m). reflexivity.\n  apply L.\nQed.\n\nLemma h1:\n forall n m, [n] = [m] -> n <=? m = true .\nProof.\n  intros n m L.\n  rewrite h0 with (n:=n) (m:=m). apply eq_or_less_ref.\n  injection L. intros K. apply h0b. apply K.\nQed.\n\nLemma h3:\n forall t n h k g, t :: n :: h = k :: g -> t =? k = true.\nProof.\n intros t n h k g L.\n injection L. intros H1 H2. apply h0b. apply H2.\nQed.\n\nLemma h4:\n  forall t n k g, t :: n = k :: g -> t =? k = true.\nProof.\n intros t n k g L.\n injection L. intros H1 H2. apply h0b. apply H2.\nQed.\n\nLemma l2 :\n  forall t n h,  n =? t = true -> insert n h = insert t h.\nProof.\n  intros t n h L.\n  simpl.\n  destruct h as [| a l] eqn:E1.\n  - simpl. apply l0. apply L.  \n  - simpl. rewrite h0 with (n:=n) (m:=t). \n    destruct (t <=? a) eqn:E2.\n    + reflexivity.\n    + reflexivity.\n    + apply L.\nQed.\n\n(* sorting proof *)\n\nTheorem invariance_of_occurrences : \n  forall l n, count n (insert n l) = S (count n l).\nProof.\n  intros l.\n  induction l as [| t h IHl].\n  - intros n. simpl.\n    rewrite eq_ref. reflexivity. \n  - intros n. simpl. destruct (n =? t) eqn:E1.\n      + rewrite eq_not_less. simpl. rewrite E1. rewrite IHl. reflexivity. \n        rewrite E1. reflexivity.\n      + destruct (n <? t) eqn:E2.\n          * simpl. rewrite eq_ref. rewrite E1. reflexivity. \n          * simpl. rewrite E1. rewrite IHl. reflexivity. \nQed.\n\nTheorem independence_of_occurrences :\n  forall l n m, n =? m = false -> count n (insert m l) = count n l.\nProof.\n  intros l.\n  induction l as [| t h IHl].\n  - intros n m L. simpl.\n    rewrite L. reflexivity. \n  - intros n m L. simpl. destruct (m =? t) eqn:E1.\n      { rewrite eq_not_less. simpl. destruct (n =? t) eqn:E2.\n          - rewrite IHl. reflexivity. \n            rewrite L. reflexivity.\n          - rewrite IHl. reflexivity.\n            rewrite L. reflexivity.\n          - rewrite E1. reflexivity. }\n      { destruct (m <? t) eqn:E3.\n          - destruct (n =? t) eqn:E4. \n              + simpl. rewrite L. rewrite E4. reflexivity.\n              + simpl. rewrite E4. rewrite L. reflexivity.\n          - destruct (n =? t) eqn:E4. \n              + simpl. rewrite E4. rewrite IHl. reflexivity.\n                rewrite L. reflexivity.\n              + simpl. rewrite E4. rewrite IHl. reflexivity.\n                rewrite L. reflexivity. } \nQed.\n\nLemma l1 :\n forall t h k g, is_sorted (t :: h) = true /\\ \n   insert t h = k :: g -> t <=? k = true.\nProof.\n  intros t h k g [L1 L2].\n  simpl in L1. destruct h.\n  - simpl in L2. \n    destruct g.\n    + apply h1. apply L2.\n    + discriminate.\n  - destruct (t <=? n) eqn:E1.\n    + simpl in L2.\n      destruct (t <? n) eqn:E2.\n      * simpl in L2. apply h3 in L2. \n        apply eq_is_less_or_eq in L2.\n        apply L2.\n      * apply h4 in L2. apply eq_is_less_or_eq. apply trans_eq with (m:=n). \n        split. apply eq1. split.\n        apply E1. apply E2. \n        apply h0 with (n:=n) (m:=k) in L2. rewrite L2. apply eq_ref.\n    + discriminate.   \nQed.\n\nLemma l3 :\n forall t h n k g, is_sorted (t :: h) = true /\\ \n   (insert n h = k :: g /\\ t <? n = true) -> t <=? k = true.\nProof.\n  intros t h n k g [L1 [L2 L3]].\n  simpl in L1. destruct h as [|x p].\n  - simpl in L2. \n    destruct g.\n    + apply h1 in L2. apply less_is_less_or_eq in L3.\n      apply trans_leb with (m:=n). split.\n      apply L3. apply L2.\n    + discriminate.\n  - destruct (t <=? x) eqn:E1.\n    + simpl in L2.\n      destruct (n <? x) eqn:E2.\n      * apply h3 in L2. \n        apply less_is_less_or_eq in L3.\n        apply h0 in L2. rewrite <-L2. apply L3.\n      * apply h4 in L2. apply h0 in L2.\n        rewrite <-L2. apply E1.\n    + discriminate.  \nQed.\n\nTheorem sorting_preservation : \n  forall l n, is_sorted l = true -> is_sorted (insert n l) = true.\nProof.\n  intros l.\n  induction l as [| t h IHl].\n  - intros n L. simpl. reflexivity.\n  - intros n L. simpl. \n    destruct (n =? t) eqn:E1.\n      + rewrite eq_not_less. simpl.\n        destruct (insert n h) as [| k g] eqn:E2.\n          * reflexivity.\n          * destruct (t <=? k) eqn:E3.\n            { rewrite <- E2. rewrite IHl. \n              reflexivity. apply sublist_of_sorted_is_sorted with (n:=t).\n              rewrite L. reflexivity. }\n            { rewrite l1 with (t:=t) (h:=h) (k:=k) (g:=g) in E3. discriminate.\n              split. apply L. \n              rewrite <- l2 with (n:=n). apply E2. \n              apply E1. } \n          * rewrite E1. reflexivity.\n      + destruct (n <? t) eqn:E4.\n          * simpl. rewrite less_is_less_or_eq with (n:=n) (m:=t).\n            destruct (h) as [| k g] eqn:E5.\n            { reflexivity. }\n            { destruct (t <=? k) eqn:E6.\n              - apply sublist_of_sorted_is_sorted with (n:=t).\n                rewrite L. reflexivity. \n              - simpl in L. rewrite E6 in L. discriminate L. }\n            {rewrite E4. reflexivity. }\n          * simpl. destruct (insert n h) as [| k g] eqn:E7.\n            { reflexivity. }\n            { destruct (t <=? k) eqn:E8.\n              - rewrite <- E7. apply IHl. \n                apply sublist_of_sorted_is_sorted with (n:=t). apply L.\n              - rewrite l3 with (t:=t) (h:=h) (n:=n) (k:=k) (g:=g) in E8. discriminate E8.\n                split. apply L. \n                split. apply E7.\n                apply l4. split. apply E4. apply E1. } \nQed.\n\nLemma sort_is_sort : forall l, is_sorted (insert_sort l) = true.\nProof.\ninduction l.\n- simpl. reflexivity.\n- simpl. apply sorting_preservation. rewrite IHl. reflexivity.\nQed.\n\n(* Check if there are any assumptions still unproved (admitted or otherwise).*)\nPrint Assumptions sort_is_sort.\n\n\n", "meta": {"author": "ilyaderkatch", "repo": "coq_project", "sha": "1a471010211749d8bc4c0230bc96e46d1f931980", "save_path": "github-repos/coq/ilyaderkatch-coq_project", "path": "github-repos/coq/ilyaderkatch-coq_project/coq_project-1a471010211749d8bc4c0230bc96e46d1f931980/coq_project_final.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8807970842359876, "lm_q1q2_score": 0.7713906343664418}}
{"text": "\n(* On introduit les variables propositionnelles avec lesquelles \n   on va travailler par la suite *)\nContext (P Q R A Z J F M S T: Prop).\n\n(**********************************************************************)\n(* Exercice 1 LA FLÈCHE  ***********************)\n(* - axiome : assumption\n   - introduction de la flèche : intro [nom qu'on donne à l'hypothèse] \n   - élimination de la flèche : apply [nom de l'hypothèse utilisée] *)\nTheorem exercice_1a: P -> (P -> Q) -> Q.\nProof.\n  intro Hp.\n  intro Hpq.\n  apply Hpq.\n  assumption.\nQed.\n\n\nTheorem exercice_1b: (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  intro Hpq.\n  intro Hqr.\n  intro Hp.\n  apply Hqr.\n  apply Hpq.\n  assumption.\nQed.\n\n(* Exercice 2 LE ET  ***********************)\n(* Une variante de la question précédente avec /\\ *)\n(* - décomposition du /\\ en hypothèse : destruct [nom de l'hypothèse avec /\\]\n*)\nTheorem exercice_2a: (P -> Q) /\\ (Q -> R) -> (P -> R).\nProof.\n  intro H.\n  intro HP.\n  destruct H as [H1 H2].\n  apply H2.\n  apply H1.\n  assumption.\nQed.\n\n(* - introduction du /\\ : split *)\n(* On obtient bien deux sous-buts *)\nTheorem exercice_2b : P -> Q -> P /\\ Q.\nProof.\n  intro Hp.\n  intro Hq.\n  split.\n  - apply Hp.\n  - apply Hq.\nQed.\n  \n(* Exercice 3 LE OU  ***********************)\n(* introduction du ou :\n   - depuis la droite : right\n   - depuis la gauche : left\n\n   decomposition du \\/ en hypothèse : destruct *)\n\nTheorem exercice_3a: (P \\/ Q) -> (Q \\/ P).\nProof.\n  intro Hpq.\n  destruct Hpq.\n  - right.\n    assumption.\n  - left.\n    assumption.\nQed.\n\n(* ---------------------------------------------------------------------*)\n\n\n(* zéro constructeur *)\nPrint False. \n(* un seul constructeur car une seule règle d'intro *)\nPrint and.\n(* deux constructeurs car deux règles d'intro*)\nPrint or.  \n\n(* destruct donne bien un sous but par constructeur *)\n(* On remarque que comme False n'a aucun constructeur : le destruct\nrésoud le but *)\nTheorem ex_falso_quodlibet : False ->  P.\nProof.\nintros H.\ndestruct H.\nQed.\n\n(** un peu difficile **)\n(* Plus généralement, la tactique exfalso remplace tout but par False. *)\n(* Si on peut déduire False des hypothèses, c'est alors gagné ! *)\n\nTheorem ex_falso_quodlibet_Q : (A -> False) -> A -> (P \\/ (Q -> Z /\\ J) -> F).\nProof.\n  intro hafalse.\n  intro ha.\n  (* ces hypothèses permettent clairement de produire False *)\n  (* on simplifie tout puisque le but ne sert plus à rien *)\n  exfalso.\n  (* et on produit False *)\n  apply hafalse.\n  assumption.\nQed.\n  \n\n(* À partir de maintenant on peut penser à nommer les hypothèses qui\napparaissent dans les destruct avec \"as\" et suivant le nombre de sous-buts *)\n(* ---------------------------------------------------------------------*)\n\n\n(* Exercice 4 PREMIÈRE MODÉLISATION  ***********************)\n(* Modéliser l'exercice de TD \"Zoé va à Paris\", prouver que Zoé va à Paris *)\n(* - introduction du /\\ : split\n*)\nTheorem zoe_va_a_paris : (A /\\ J -> Z) -> (J -> A) -> (J \\/ Z) -> Z.\nProof.\n  intro Hajz.\n  intro Hja.\n  intro Hjz.\n  destruct Hjz.  \n  - apply Hajz.\n    split.\n    + apply Hja. assumption.\n    + assumption.\n  - assumption.\nQed.\n\nTheorem zoe_va_a_paris' : (A /\\ J -> Z) /\\ (J -> A) /\\ (J \\/ Z) -> Z.\nProof.\n  intro.\n  destruct H.\n  destruct H0.\n  destruct H1.\n  - apply H.\n    split.\n    + apply H0. assumption.\n    + assumption.\n  - assumption.\nQed.\n\n(* Exercice 5 LE NOT *************************)\n\n(* - la notation not : unfold not\n   - la notation not en hypothèse : unfold not in [nom de l'hypothèse avec ~]\n*)\nTheorem exercice_5a : (~P \\/ ~Q) -> ~(P /\\ Q).\nProof.\n  intro Hnpnq.\n  unfold not in Hnpnq.\n  intro.\n  destruct Hnpnq.\n  - destruct H. apply H0. assumption.\n  - destruct H. apply H0. assumption.\nQed.\n\n(* Si on a toto et ~toto dans les hypothèses, alors le but est résolu avec \"contradiction.\" *)\n\nTheorem exercice_5b : P -> ~P -> Q.\nProof.\n  intro hp.\n  intro hnp.\n  contradiction.\nQed.\n\n(**********************************************************************)\n(* Exercice 6 LE TIERS-EXCLU *)\n\n(* On introduit la règle de tiers-exclu. *)\nContext (Tiers_exclus: forall X: Prop, X \\/ ~X).\n\n(* Pour l'utiliser, c'est-à-dire pour avoir deux sous buts, un avec toto en hypothèse, l'autre avec ~toto, on invoquera :\n   destruct (Tiers_exclus toto).\n*)\n\n\n(* Deuxième modélisation *)\n(* Modéliser l'exercice de TD \"Frodon va au Mordor\", prouver que Frodon est triste\n- Si Frodon ne va pas au Mordor, Sauron prend le pouvoir ; (~M -> S)\n- Si Sauron prend le pouvoir, Frodon est triste ; (S -> T)\n- Si Frodon va au Mordor, il ne possède pas l'anneau ; (M -> ~A)\n- Si Frodon ne possède pas l'anneau, il est triste ; (~A -> T)\n*)\nTheorem exercice_6b : (~M -> S) -> (S -> T) -> (M -> ~A) -> (~A -> T) -> T.\nProof.\nintros H1 H2 H3 H4.\n(*\nsupposons {H1 H2 H3 H4} et prouvons que T\n- soit I(M)=1 comme (M -> ~A)=1 alors I(~A)=1\n  comme I(~A)=1, comme I(~A -> T)=1 alors I(T)=1\n- soit I(M)=0 comme I(~M -> S)=1 alors I(S)=1\n  comme I(S)=1, comme I(S -> T)=1 alors I(T)=1\nDans tous les cas T est vrai Qed.\n*)\nassert (M \\/ ~M).\napply (Tiers_exclus M).\ndestruct H.\n- apply H4.\n  apply H3.\n  assumption.\n- apply H2.\n  apply H1.\n  assumption.\nQed.\n\n\n(* Quid de ~~P et P ? *)\nTheorem exercice_6c: (~~P -> P) /\\ (P -> ~~P).\n(* Pour l'un des deux sens on aura besoin du tiers-exclu et, en remarquant qu'on peut déduire False des hypothèses, de la simplification \"exfalso\". *)\nProof.\n  split.\n  intros.\n  - unfold not in H.\n    destruct(Tiers_exclus P).\n    assumption.\n    exfalso.\n    unfold not in H0.\n    apply H.\n    assumption.\n  - intros H.\n    intros H1.\n    unfold not in H1.\n    apply H1.\n    assumption.\nQed.\n\nTheorem execirce_bonus: (~~~P -> ~P).\nProof.\n  intros.\n  unfold not in H.\n  unfold not.\n  intros H1.\n  apply H.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nDefinition si_cest_vrai_cest_pas_faux := P -> ~~P.\n\nTheorem scvcpf: si_cest_vrai_cest_pas_faux /\\ (~~P -> P).\nProof.\nsplit.\n- unfold si_cest_vrai_cest_pas_faux.\n  intros H2.\n  intros H3.\n  apply H3.\n  assumption.\n- intros H. \n  assert (P \\/ ~P).\n  exact (Tiers_exclus P).\n  destruct H0.\n  * assumption.\n  * exfalso. apply H. assumption.\nQed.\n  \n\n\n\n\n\n\n\n\n\n\n\n\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/liflc/tp1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.7713101166914565}}
{"text": "Require Import set.\nRequire Import Axiom_Skolem.\nRequire Import belong.\nRequire Import subset.\nRequire Import Axiom_Power_Set.\nRequire Import Axiom_Extensionality.\n\n(* binary relation expression the fact that P(a) = b *)\nDefinition is_power_set (a b:set) : Prop :=\n  forall x:set, x:b <-> subset x a.\n\nLemma power_set_is_unique : forall a:set, forall b c:set,\n  is_power_set a b -> is_power_set a c -> b = c.\nProof.\n  intros a b c Hab Hac. apply extensionality.\n  unfold subset. intros x Hx. apply Hab in Hx. apply Hac in Hx. exact Hx.\n  unfold subset. intros x Hx. apply Hac in Hx. apply Hab in Hx. exact Hx.\nQed.\n\n(* Given a:set, the power set P(a) exists and is unique *)\n(* The Skolem axiom allows us to extract an element for it, *) \n(* as well as a proof of the fact this element is indeed P(a) *)\n\nDefinition power (a:set) : set :=\n  proj1_sig(skolem (power_set a) (power_set_is_unique a)).\n\nNotation \"'P' ( a )\" := (power a) : core_scope.\n\nProposition power_is_power: forall a:set,\n  forall x:set, x:P(a) <-> subset x a.\nProof.\n  intros a. exact (proj2_sig (skolem (power_set a) (power_set_is_unique a))).\nQed.\n\nProposition power_intro: forall a x:set,\n  subset x a -> x:P(a).\nProof.\n  intros a x H. apply power_is_power. exact H.\nQed.\n\nProposition power_elim: forall a x:set,\n  x:P(a) -> subset x a.\nProof.\n  intros a x H. apply power_is_power. 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/zf/power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7712929646312472}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\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": "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/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7712790669435114}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #2: 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\n    Note that plus and multiplication are already defined in Coq.\n    use \"+\" for plus and \"*\" for multiplication.\n*)\n\nEval compute in 3 * 5.\nEval compute in 3+5*6.\n\nFixpoint factorial (n:nat) : nat := \nmatch n with\n| O => S O\n| S n' => n * (factorial n')\nend.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = 10 * 12.\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/01/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.771279065069706}}
{"text": "Require Import PV.Syntax.\n\n(** 习题：*)\nLemma size_nonneg: forall t,\n  0 <= tree_size t.\nAdmitted. (* 请删除这一行_[Admitted]_并填入你的证明，以_[Qed]_结束。 *)\n\n(** 习题：*)\nLemma reverse_result_Node: forall t t1 k t2,\n  tree_reverse t = Node t1 k t2 ->\n  t = Node (tree_reverse t2) k (tree_reverse t1).\nAdmitted. (* 请删除这一行_[Admitted]_并填入你的证明，以_[Qed]_结束。 *)\n\n\n(** 习题：*)\n(** 下面的_[left_most]_函数与_[right_most]_函数计算了二叉树中最左侧的节点信息与\n    最右侧的节点信息。如果树为空，则返回_[default]_。*)\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(** 很显然，这两个函数应当满足：任意一棵二叉树的最右侧节点，就是将其左右翻转之后\n    最左侧节点。这个性质可以在Coq中如下描述：*)\n\nLemma left_most_reverse: forall t default,\n  left_most (tree_reverse t) default = right_most t default.\nAdmitted. (* 请删除这一行_[Admitted]_并填入你的证明，以_[Qed]_结束。 *)\n\n", "meta": {"author": "panic-coursework", "repo": "fakeverification", "sha": "9eb195fa2a94f700a564fe52a7f2cbfc31963213", "save_path": "github-repos/coq/panic-coursework-fakeverification", "path": "github-repos/coq/panic-coursework-fakeverification/fakeverification-9eb195fa2a94f700a564fe52a7f2cbfc31963213/materials/Assignment0216.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.7712758559128077}}
{"text": "Require Export Coq.Lists.List.\nRequire Export Coq.micromega.Lia.\nRequire Export Coq.Init.Nat.\nExport ListNotations.\n\n\n\n(* About the built-in \"if then else\" function *)\n\nLemma iteinv :\n  forall (A : Type) (a : bool) (b c: A)  ,\n    not (b = c)\n    -> (if a then b else c) = b\n    -> a = true.\nProof.\n  intros.\n  assert (not  (a = false)).\n  { unfold not.\n    intros.\n    assert   ((if a then b else c) = c).\n    { destruct a. discriminate H1. auto. }\n    rewrite H0 in H2.  auto. }\n  destruct a.\n  - auto.\n  - contradiction.\nQed.\n\n\n\nLemma TnF :\n  not (True = False).\nProof.\n  unfold not.\n  intros.\n  rewrite <- H.\n  auto.\nQed.\n\nLemma TFiteinv :\n  forall (a : bool) ,\n    (if a then True else False)\n    -> a = true.\nProof.\n  intros.\n  assert (H1 := TnF).\n  apply (iteinv Prop a True False).\n  - auto.\n  - destruct a.\n    + auto.\n    + contradiction.\nQed.\n\n\n\n\n\n\n(* About lists *)\n\n(* For \"T : Set\", \"P : T -> Prop\", \"ls : list T\" (N long list \"ls\")\n\"listforall P ls\" is the proposition \"(P ls1) /\\ (P ls2) /\\ ... /\\ (P lsN)\". *)\n\nSection listforall.\n\n  Context  {T : Set}.\n  Variable P : T -> Prop.\n\n  Fixpoint listforall (ls : list T) : Prop :=\n    match ls with\n    | nil => True\n    | cons h t => P h /\\ listforall t\n    end.\n\nEnd listforall.\n\n\nLemma unfold_listforall :\n  forall (T : Set) (P : T -> Prop) (t : T) (tl : list T),\n    listforall P (cons t  tl) = (P t /\\ listforall P tl).\nProof.\n  auto.\nQed.\n\n\n(* For sets \"T\" and \"T'\", function \"F : T -> T'\" and \"ls : list T\",\nmaplist T T' F ls *)\n\nSection maplist.\n\n  Context {T T' : Set}.\n  Variable F : T -> T'.\n\n  Fixpoint maplist (ls : list T) : list T' :=\n    match ls with\n    | nil => nil\n    | cons h t => cons (F h) (maplist t)\n    end.\n\nEnd maplist.\n\nLemma unfold_maplist:\n  forall (T T' : Set) (F : T -> T') (h : T) (ls : list T),\n    maplist F (h :: ls) = (F h) :: (maplist F ls).\nProof.\n  auto.\nQed.\n\n\n\n(* About Naturals *)\n\nLemma n_minus_n :\n  forall (n : nat),\n    n - n = 0.\nProof.\n  lia.\nQed.\n\n\n\n(* \"inb n m\" is defined for \"n\" and \"m\" naturals,\nand it gives \"true\" if \"n=m\" and gives \"false\" otherwise. \"=?\" is infix notation *)\n\n(* \"inb n ln\" gives \"true : bool\" if \"n\" is in the list \"ln\", while gives \"false : bool\"\nif \"n\" is not in \"ln\" *)\nFixpoint inb (n: nat) (ln: list nat) : bool :=\n    match ln with\n      | nil => false\n      | n' :: ln' => eqb n n' || inb n ln'\n    end.\n(* \"orb : bool -> bool -> bool\" is the boolean or, with \"||\" infix notation *)\n\nLemma unfold_inb:\n  forall n n' ln',\n    inb n (n' :: ln') = orb (eqb n n') (inb n ln').\nProof.\n  auto.\nQed.\n\n\n\n(* \"max n m\" is defined for \"n\" and \"m\" naturals,\nand is the maximum of the two. When they are equal, m is the output. *)\n\n(* \"listmax ln\" is the maximum of the list of naturals.\nWhen there are several instances of the maxial, it delivers the last. *)\nFixpoint listmax  (ln: list nat) : nat :=\n    match ln with\n      | nil => 0\n      | n' :: ln' => max n' (listmax ln')\n    end.\n\n\n(* This proposition is useful in rewriting the right as the left. *)\nLemma unfold_listmax:\n  forall n' ln',\n    listmax (n' :: ln') = max n' (listmax ln').\nProof.\n  auto.\nQed.\n\n\n\n(* The first \"length l1\" number of elements of\n\"l1 ++ l2\" is \"l1\" *)\nLemma firstn_app_exact :\n  forall {A : Type} (l1 l2 : list A),\n    @firstn A (length l1) (l1 ++ l2) = l1.\nProof.\n  intros.\n  rewrite firstn_app.\n  rewrite n_minus_n.\n  rewrite firstn_O.\n  rewrite firstn_all.\n  rewrite app_nil_r.\n  reflexivity.\nQed.\n\n(* The skipping \"length l1\" number of elements of\n\"l1 ++ l2\" is \"l2\" *)\nLemma skipn_app_exact :\n  forall {A : Type}  (l1 l2 : list A),\n    @skipn A (length l1) (l1 ++ l2) = l2.\nProof.\n  intros.\n  rewrite skipn_app.\n  rewrite n_minus_n.\n  rewrite skipn_O.\n  rewrite skipn_all.\n  rewrite app_nil_l.\n  reflexivity.\nQed.\n", "meta": {"author": "kmilesz", "repo": "CCSA_FOO_Verification", "sha": "bb33875f975bcb266acacec1980b13c9631c273e", "save_path": "github-repos/coq/kmilesz-CCSA_FOO_Verification", "path": "github-repos/coq/kmilesz-CCSA_FOO_Verification/CCSA_FOO_Verification-bb33875f975bcb266acacec1980b13c9631c273e/Core/A_Auxiliaries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8633916011860786, "lm_q1q2_score": 0.7712758433525886}}
{"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), so readers who are already comfortable with\n    these ideas can safely skim or skip this chapter.  However,\n    relations are also a good source of exercises for developing\n    facility with Coq's basic reasoning facilities, so it may be\n    useful to look at this material just after the [IndProp]\n    chapter. *)\n\nRequire Export IndProp.\nRequire Import Coq.omega.Omega.\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 : partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  reflexivity.  \nQed.\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 : ~ (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.   \nQed.\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [total_relation] defined in earlier is not a partial\n    function. *)\nTheorem total_relation_is_not_a_partial_function : \n  ~ (partial_function total_relation).\nProof.\n  unfold not, partial_function. intros Htr.\n  pose proof Htr 1 2 3.\n  assert (t1 : total_relation 1 2). apply tr_1. auto.\n  assert (t2 : total_relation 1 3). apply tr_1. auto.\n  pose proof H t1 t2. inversion H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [empty_relation] that we defined earlier is a\n    partial function. *)\nTheorem rempty_relation_is_partial_function : \n  partial_function empty_relation.\nProof.\n  unfold partial_function. intros x y1 y2 H1 H2. inversion H2.\nQed.\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 : reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n. \nQed.\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 : 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.\nQed.\n\nTheorem lt_trans: 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. \nQed.\n\n(** **** Exercise: 2 stars, optional  *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using [le_trans].  Do this.*)\nLemma n_le_m__n_le_Sm : forall n m, n <= m -> n <= S m.\nProof.\n  intros n m Hnm. induction Hnm. auto. auto.\nQed.\n\nTheorem lt_trans' : 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 n_le_m__n_le_Sm. apply Hnm.\n  - apply n_le_m__n_le_Sm. apply IHHm'o.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' : 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. inversion Hmo. rewrite <- H0.\n    apply Hnm. apply IHo'. apply H0.\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  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros n m. intros H. inversion H. trivial. \n  apply le_Sn_le. 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\n    Proof:\n    (* FILL IN HERE *)\n    []\n *)\n\n(** **** Exercise: 1 star, optional  *)\nTheorem le_Sn_n : forall n, ~ (S n <= n).\nProof.\n  intros n. unfold not. intros H. induction n.\n  - inversion H.\n  - apply IHn. apply le_S_n. apply H.\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  *)\nTheorem le_not_symmetric : ~ (symmetric le).\nProof.\n  unfold not, symmetric. intros.\n  assert (t : 0 <= 1) by omega.\n  pose proof H 0 1 t. inversion H0.\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 : antisymmetric le.\nProof.\n  unfold antisymmetric. intros a b Hab Hba. omega.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\nLemma le_step1 : forall n m, n < m -> S n <= m.\nProof.\n  intros n m Hnm. inversion Hnm. omega. omega.\nQed.\n\nLemma le_step2 : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m Hnm. omega.\nQed.\n\nTheorem le_step : forall n m p, n < m -> m <= S p -> n <= p.\nProof.\n  intros n m p Hnm Hmp. apply le_step1 in Hnm. apply le_step2.\n  omega.\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.\nQed.\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. induction H.\n  - apply H0.\n  - apply rt1n_trans with y. apply H. \n    apply IHclos_refl_trans_1n. apply 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, 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. split. intros H.\n  - induction H. apply rt1n_trans with y. \n    assumption. constructor. constructor.\n    apply rsc_trans with y. assumption. assumption.\n  - intros H. induction H. apply rt_refl. apply rt_trans with y.\n    apply rt_step. assumption. assumption.\nQed.\n(** [] *)\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "lambdaxymox", "repo": "software-foundations", "sha": "ab1b397316009dfd6144e1c11875a9d60d8c9a84", "save_path": "github-repos/coq/lambdaxymox-software-foundations", "path": "github-repos/coq/lambdaxymox-software-foundations/software-foundations-ab1b397316009dfd6144e1c11875a9d60d8c9a84/src/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.7712758345746363}}
{"text": "(* A category is very much like a graph. It has vertices\n   named objects and vertices named arrows. Each arrow goes\n   from an object to an object (possibly the same!). *)\nClass Cat (obj: Type) (arr: obj -> obj -> Type): Type :=\n  MkCat {\n    (* For each object, there is an arrow called `id` which\n    goes from the object to itself. *)\n    id: forall {o: obj}, arr o o;\n\n    (* Given an arrow `f` from object `a` to `b` and an arrow\n       `g` from `b` to `c`. We can compose these arrow. The\n       result is an arrow from `a` to `c`. *)\n    compose: forall {a b c: obj}, arr a b -> arr b c -> arr a c;\n\n    (* Here comes some properties of `id` and `compose` *)\n\n    (* For any arrow `f`, compose id f = f *)\n    neutralLeft:   forall {a b: obj} (f: arr a b), compose id f = f;\n\n    (* For any arrow `f`, compose f id = f  *)\n    neutralRight:  forall {a b: obj} (f: arr a b), compose f id = f;\n\n    (* For any arrows `f`, `g` and `h`,\n        composing f with g, and then the result with h\n       gives exatctly the same result as\n        composing f with the result of the composition of g and h\n\n       Which means, like string concatenation than we can commpose\n       the way we preserve the order of each element in the sequence. *)\n    associativity: forall {a b c d: obj} (f: arr a b) (g: arr b c) (h: arr c d),\n                     compose (compose f g) h = compose f (compose g h);\n  }.\n\n(* `LE n m` encode the property that `n ≤ m`\n    i.e. `n` is less or equal to `m` *)\nInductive LE : nat -> nat -> Prop :=\n    LERefl: forall {o: nat}, LE o o\n  | LENext: forall {a b: nat}, LE a b -> LE a (S b)\n.\n\n\n(* Taking naturals as objects and `LE` as arrows,\n   this actually forms a category! *)\nInstance natPoset: Cat nat LE := ???\n.", "meta": {"author": "chrilves", "repo": "big4-tutorial", "sha": "277e034f7152623a17527c4ae55acc7aa8ce1f89", "save_path": "github-repos/coq/chrilves-big4-tutorial", "path": "github-repos/coq/chrilves-big4-tutorial/big4-tutorial-277e034f7152623a17527c4ae55acc7aa8ce1f89/Coq/CatC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7712138134176373}}
{"text": "(** This first serie of  exercises asks you to prove some derived\n    inference rules *)\n\nLemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.\nProof.\n intros P.\n intro Q.\n intro H.\n intro 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\n\nLemma not_or_1 : forall P Q : Prop, ~(P \\/ Q) -> ~P.\nProof.\n intros P Q.\n unfold not.\n intro H.\n intro H0.\n apply H.\n left.\n apply H0.\nQed.\n\n \n\nLemma de_morgan_1 : forall P Q: Prop, ~ (P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n intros P Q.\n split.\n intro H.\n split.\n apply (not_or_1 P Q).\n apply H.\n intro H1.\n apply H.\n right.\n apply H1.\n intro J.\n intro J1.\n destruct J1.\n destruct J.\n destruct H0.\n apply H.\n destruct J.\n destruct H1.\n apply H.\nQed.\n\nLemma de_morgan_2 : forall P Q: Prop, ~ P \\/ ~Q  -> ~(P /\\ Q).\nProof.\n intros P Q.\n intro H.\n intro H0.\n destruct H.\n destruct H0.\n apply H.\n apply H0.\n destruct H0.\n apply H.\n apply H1.\nQed.\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 intro H.\n intro H0.\n intro H1.\n intros H2.\n intro H3.\n apply H1.\nQed.\n\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\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.\n split.\n intro H1.\n intro x0.\n unfold not.\n intros.\n destruct H1.\n exists x0.\n assumption.\n unfold not.\n apply P.\n intros.\nAdmitted.\n\n\nLemma ex_not_forall_not : forall (A: Type) (P: A -> Prop),\n                       (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\nAdmitted.\n\n\nLemma diff_sym : forall (A:Type) (a b : A), a <> b -> b <> a.\nProof.\nAdmitted.\n\n\nLemma fun_diff :  forall (A B:Type) (f : A -> B) (a b : A), \n                       f a <> f b -> a <> b.\nProof.\nAdmitted.\n\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.\nAdmitted.\n\n\nLemma Double_neg_Exm :  Double_neg -> Exm.\nProof.\n Admitted.\n\nLemma Peirce_Double_neg : Peirce -> Double_neg.\nProof.\nAdmitted.\n\nLemma Exm_Peirce : Exm -> Peirce.\nProof.\nAdmitted.\n\n\nLemma Classical_impl_Exm : Classical_impl -> Exm.\nAdmitted.\n\n\nLemma Exm_Classical_impl : Exm -> Classical_impl.\nProof.\nAdmitted.\n \n \nLemma Not_forall_not_exists_Double_neg :  Not_forall_not_exists -> Double_neg.\nProof.\nAdmitted.\n\nLemma Exm_Not_forall_not_exists: Exm -> Not_forall_not_exists.\nAdmitted.\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.\nAdmitted.\n\n Definition 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.\nAdmitted.\n\n\nLemma surjective_comp : forall U V W (f:U->V)(g : V -> W),\n                       surjective (compose g f) -> surjective g.\nProof.\nAdmitted.\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.\nAdmitted.\n\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.\nAdmitted.\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.\nAdmitted.\n\nLemma my_or_intro_l : forall P Q:Prop, P -> my_or P Q.\nProof.\nAdmitted.\n\nLemma my_or_ok : forall P Q:Prop, P \\/ Q <-> my_or P Q.\nProof.\nAdmitted.\n\nLemma my_and_ok :  forall P Q:Prop, P /\\ Q <-> my_and P Q.\nProof.\nAdmitted.\n\nLemma my_ex_ok :  forall (A:Type)(P:A->Prop),\n                   (exists x, P x) <-> (my_exists A P).\nProof.\nAdmitted.\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278533, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.771204555247711}}
{"text": "Lemma decid_egal:\n forall (n m : nat), { n = m } + { n <> m }.\ndouble induction n m;intros.\nleft.\nreflexivity.\nright.\ndiscriminate.\nright.\ndiscriminate.\nelim (H0 n0).\nintro.\nleft.\ncongruence.\nintro.\nright.\nSearchAbout (_ <> _ -> _ <> _).\napply not_eq_S.\nassumption.\nDefined.\nRecursive Extraction decid_egal.\n\n\nInductive is_fact : nat -> nat -> Prop :=\n| is_fact_O : is_fact 0 1\n| is_fact_S : forall n f : nat, is_fact n f -> is_fact (S n) ((S n)*f). \n\n\nLemma fact: \n forall (n : nat), { v : nat | is_fact n v }.\n  intro.\n  elim n.\n  exists 1.\n  apply is_fact_O.\n  \n  intros.\n  elim H.\n  intros.\n  exists ((S n0)* x).\n  apply is_fact_S.\n  assumption.\n\nOpen Scope list_scope.\nInductive is_map (f : nat -> nat) : (list nat) -> (list nat) -> Prop :=\n | is_map_nil : is_map f nil nil\n | is_map_rec : forall (l1 l2 : list nat) (a : nat),\n                 is_map f l1 l2 ->\n                 is_map f (a::l1) ((f a)::l2).\n\nLemma map :forall (f : nat -> nat)(l1 : list nat) , { l2 : list nat | is_map f l1 l2 }.\ninduction l1.\nexists nil.\napply is_map_nil.\n\nelim IHl1.\nintros.\nexists ((f a)::x).\napply is_map_rec.\napply p.\nDefined.\n\n(*\nFixpoint add (n : nat) :  nat :=\nmatch n with\n| n => (S n)\nend.\n*)\n\n\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/tp5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8723473862936943, "lm_q1q2_score": 0.7711893514818022}}
{"text": "Require Import PeanoNat Lia.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\n(* induction/recursion principle wrt. a decreasing measure f *)\n(* example: elim /(measure_rect length) : l. *)\nLemma measure_rect {X : Type} (f : X -> nat) (P : X -> Type) : \n  (forall x, (forall y, f y < f x -> P y) -> P x) -> forall (x : X), P x.\nProof.\n  exact: (well_founded_induction_type (Wf_nat.well_founded_lt_compat X f _ (fun _ _ => id)) P).\nQed.\n\nLemma iter_plus {X: Type} {f: X -> X} {x: X} {n m: nat} : \n  Nat.iter (n + m) f x = Nat.iter m f (Nat.iter n f x).\nProof. by rewrite Nat.add_comm /Nat.iter nat_rect_plus. Qed.\n\nLemma pow_3_mod_2 (n: nat) : 3 ^ n mod 2 = 1.\nProof.\n  elim: n; first by (cbv; lia).\n  move=> n IH. rewrite Nat.pow_succ_r' Nat.mul_mod ?IH; first by lia.\n  by cbv; lia.\nQed.\n\nLemma pow_5_mod_2 (n: nat) : 5 ^ n mod 2 = 1.\nProof.\n  elim: n; first by (cbv; lia).\n  move=> n IH. rewrite Nat.pow_succ_r' Nat.mul_mod ?IH; first by lia.\n  by cbv; lia.\nQed.\n\nLemma pow_2_mod_3 (n: nat) : 2 ^ n mod 3 = 1 \\/ 2 ^ n mod 3 = 2.\nProof.\n  elim: n; first by (cbv; lia).\n  move=> n IH. rewrite Nat.pow_succ_r' Nat.mul_mod; first by lia.\n  move: IH => [->|->]; cbv; by lia.\nQed.\n\nLemma pow_5_mod_3 (n: nat) : 5 ^ n mod 3 = 1 \\/ 5 ^ n mod 3 = 2.\nProof.\n  elim: n; first by (cbv; lia).\n  move=> n IH. rewrite Nat.pow_succ_r' Nat.mul_mod; first by lia.\n  move: IH => [->|->]; cbv; by lia.\nQed.\n\nLemma mod_frac_lt {n m: nat} : (S m) mod (n + 1) = 0 -> S m < (S m * (n + 2)) / (n + 1).\nProof.\n  have ->: S m * (n + 2) = S m + S m * (n + 1) by lia.\n  have := Nat.div_mod_eq (S m) (n + 1).\n  rewrite Nat.div_add; 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/CounterMachines/Util/Nat_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7711892435932424}}
{"text": "Lemma ExampleCHI: forall A B C: Prop, (A -> B -> C) -> (A -> B) -> (A -> C).\n(*intros.*)\nintros A B C X Y Z.\n\napply X.\n\nassumption.\n\napply Y.\nassumption.\nQed.\n\nPrint ExampleCHI.\n\n\n(* In natural deduction:\n\n\nG, A |- A (axiom)\n\n\nG, A |- B\n-------------------- (-> intro) \nG |- A -> B\n\n\nG |- A -> B      G |- A\n-------------------------(-> elim)\nG |- B\n\n*)\n\nSection Minimal_propositional_logic.\n Variables P Q R S : Prop.\n\nLemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\n Proof.\n intros H0 H1 H2 H3.\n apply H2.\n - apply H0.\n   assumption.\n - apply H1; assumption.\n Qed.\n\nPrint diamond.\n\nEnd Minimal_propositional_logic.\n\nPrint diamond.\n\n\nSection Minimal_first_order_logic.\n Variables (A : Set)\n   (P Q : A -> Prop)\n   (R : A -> A -> Prop).\n\nTheorem all_imp_dist :\n  (forall a:A, P a -> Q a) -> (forall a:A, P a) -> forall a:A, Q a.\n Proof.\n intros.\n apply H.\n apply H0.\n Qed.\n\nPrint all_imp_dist.\n\nTheorem all_delta : (forall a b:A, R a b) -> forall a:A, R a a.\n Proof.\n intros.\n apply H.\n Qed.\n\nEnd Minimal_first_order_logic.\n\n\nLemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.\nProof.\n intros P Q H p; apply H. \n intro H0;apply H0;assumption. \nQed.\n\nPrint P3Q.\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/mlogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7711892341604929}}
{"text": "(*** Exercício de Programação Funcional**)\n\n(** Defina um programa que compute o antecessor do antecessor de um dado número n **)\n\n(** 1 star **)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | 1 => 0\n  | S(S(n')) => n'\n end.\n\n(** Teste a função minustwo **)\n(** 1 star **)\n\nExample test_minustwo_1 : minustwo 4 = 2.\n  Proof.\n  simpl.\n  reflexivity.\n  Qed.\n\n(** 1 star **)\nExample test_minustwo_2 : minustwo 1 = 0.\n  Proof.\n  simpl.\n  reflexivity.\n  Qed.\n\n(** 1 star **)\nExample test_minustwo_3 : minustwo 0 = 0.\n  Proof.\n  simpl.\n  reflexivity.\n  Qed.\n\n(** Defina uma função que some 2 **)\n(** 1 star **)\n\nDefinition plustwo (n : nat) : nat := S(S(n)).\n\n(** Teste a função plustwo **)\n(** 1 star **)\n\nExample test_plustwo_1 : plustwo 4 = 6.\n  Proof.\n  unfold plustwo.\n  reflexivity.\n\n(** 1 star **)\nExample test_plustwo_2 : plustwo 0 = 2.\n  Proof.\n  unfold plustwo.\n  reflexivity.\n\nInductive fruta : Type :=\n  | morango : fruta\n  | uva : fruta\n  | laranja : fruta.\n\nInductive salada : Type :=\n  | salada1 : fruta -> salada\n  | salada2 : fruta -> fruta -> salada\n  | salada3 : fruta -> fruta -> fruta -> salada.\n\n(** Defina o tipo fruta (morango, uva e laranja) **)\n(** 1 star **)\n\n(** Defina o tipo salada, onde uma salada é formada pela combinação de até três frutas **)\n(** 1 star **)\n", "meta": {"author": "nobreconfrade", "repo": "reidocoq", "sha": "98fc4c357cbc38041b1e83e1a2c468aac0d6ef70", "save_path": "github-repos/coq/nobreconfrade-reidocoq", "path": "github-repos/coq/nobreconfrade-reidocoq/reidocoq-98fc4c357cbc38041b1e83e1a2c468aac0d6ef70/doit1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7711892260456256}}
{"text": "Require Import not.\n\nDefinition LEM          := forall (P:Prop), P \\/ ¬P. \nDefinition Double_Neg   := forall (P:Prop), (¬¬P) -> P.\nDefinition Peirce       := forall (P Q:Prop), ((P -> Q) -> P) -> P.\nDefinition DeMorgan     := forall (P Q:Prop), ¬(¬P /\\ ¬Q) -> P \\/ Q.\nDefinition Implies      := forall (P Q: Prop), (P -> Q) -> (¬P \\/ Q).\n\nTheorem LEM_irrefutable : forall (P:Prop), \n    ¬ ¬ (P \\/ ¬ P).\nProof.\n    intros P H. \n    assert ( ¬P ) as H'. { intro Hp. apply H. left. exact Hp. }\n    apply H. right. exact H'.\nQed.\n\n\nTheorem LEM_Double_Neg : LEM <-> Double_Neg.\nProof.\n    unfold LEM, Double_Neg. split.\n    - intros H P H'. destruct (H P) as [H1|H1].\n        + exact H1.\n        + exfalso. apply H'. exact H1.\n    - intros H P. apply H. apply LEM_irrefutable.\nQed.\n\nTheorem LEM_Peirce : LEM <-> Peirce.\nProof.\n    unfold LEM, Peirce. split.\n    - intros H P Q H'. destruct (H P) as [H1|H1].\n        + exact H1.\n        + apply H'. intros H0. exfalso. apply H1. exact H0.\n    - intros H P. apply H with (Q := False).\n        intros H'. right. intros H0. apply H'. left. exact H0.\nQed.\n\n\nTheorem LEM_DeMorgan : LEM <-> DeMorgan.\nProof.\n    unfold LEM, DeMorgan. split.\n    - intros H P Q H'. \n        assert ((P \\/ Q) \\/ ¬(P \\/Q)) as H0. { apply H. }\n        destruct H0 as [H1|H1].\n            + exact H1.\n            + exfalso. apply H'. split.\n                { intros H0. apply H1. left. exact H0. }\n                { intros H0. apply H1. right. exact H0. }\n    - intros H P. apply H. intros [H1 H2]. apply H2. exact H1.\nQed.\n\n\nTheorem LEM_Implies : LEM <-> Implies.\nProof.\n    unfold LEM, Implies. split.\n    - intros H P Q H'. destruct (H P) as [H1|H1].\n        + right. apply H'. exact H1.\n        + left. exact H1.\n    - intros H P. assert (¬P \\/ P) as H0.\n        { apply H. intros H'. exact H'. }\n        destruct H0 as [H1|H1].\n            + right. exact H1.\n            + left. exact H1.\nQed.\n\n\nTheorem restricted_LEM : forall (P:Prop) (b:bool),\n    (P <-> b = true) -> P \\/ ¬P.\nProof.\n    intros P b [H1 H2]. destruct b eqn:H.\n    - left. apply H2. reflexivity.\n    - right. intros H'. apply H1 in H'. inversion H'.\nQed.\n\nTheorem not_exists_forall : forall (a:Type) (P:a -> Prop),\n    ¬ (exists x, P x) -> forall x, ¬ P x.\nProof. intros a P H x Px. apply H. exists x. exact Px. Qed.\n\n(* we need LEM for this one *)\nTheorem not_exists_forall_strong : LEM ->\n    forall (a:Type) (P:a -> Prop), ¬ (exists x, ¬ P x) -> forall x, P x.\nProof.\n    intros H a P H' x. assert (Double_Neg) as H0. { apply LEM_Double_Neg. exact H. }\n    apply H0. set (Q := fun x => ¬ P x). apply (not_exists_forall a Q). 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/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7710471472051009}}
{"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\nNotation \"x =? y\"   := (eq x y) (at level 70).\nNotation \"x <? y\"   := (lt x y) (at level 70).\nNotation \"x <=? y\"  := (leq x y) (at level 70). \n\nSection OrderedNat.\n\n  Fixpoint nat_eq (n0 n1 : nat) : bool :=\n    match (n0, n1) with\n      | (O, O)       => true\n      | (S m0, S m1) => nat_eq m0 m1\n      | _            => false\n    end.\n  \n  Fixpoint nat_lt (n0 n1 : nat) : bool :=\n    match (n0, n1) with\n      | (O, O)   => false\n      | (O, S _) => true\n      | (S _, O) => false\n      | (S m0, S m1) => nat_lt m0 m1\n    end.\n\n  Definition nat_leq (n0 n1 : nat) : bool :=\n    nat_eq n0 n1 || nat_lt n0 n1.\n    \n  Theorem nat_eq_sym\n    : forall (t1 t2 : nat)\n    , nat_eq t1 t2 = nat_eq t2 t1.\n  Proof.\n  Admitted.\n\n  Theorem nat_lt_asym\n    : forall (t1 t2 : nat) (b : bool)\n    , (nat_lt t1 t2 = true) -> (nat_lt t2 t1 = false).\n  Proof.\n  Admitted.\n\n  Theorem nat_eq_implies_leq\n    : forall (t1 t2 : nat)\n    , nat_eq t1 t2 = true -> nat_leq t1 t2 = true.\n  Proof.\n  Admitted.\n\n  Theorem nat_lt_implies_leq\n    : forall (t1 t2 : nat)\n    , nat_lt t1 t2 = true -> nat_leq t1 t2 = true.\n  Proof.\n  Admitted.\n\n  Theorem nat_lt_not_eq\n    : forall (t1 t2 : nat)\n    , nat_lt t1 t2 = true -> nat_eq t1 t2 = false.\n  Proof.\n  Admitted.\n\n  Instance orderedNat : ordered nat :=\n    { eq              := nat_eq\n    ; lt              := nat_lt\n    ; leq             := nat_leq\n    ; eq_sym          := nat_eq_sym\n    ; lt_asym         := nat_lt_asym\n    ; eq_implies_leq  := nat_eq_implies_leq\n    ; lt_implies_leq  := nat_lt_implies_leq\n    ; lt_not_eq       := nat_lt_not_eq\n    }.\n\nEnd OrderedNat.\n\nClass set (S : Type) (A : Type) : Type :=\n  { empty  : S\n  ; insert : A -> S -> S\n  ; member : A -> S -> bool\n\n  ; empty_member\n      : forall (a : A)\n      , member a empty = false\n  ; insert_non_member\n      : forall (s : S) (a : A)\n      , member a s = false -> member a (insert a s) = true\n  ; insert_member_idenpotent\n      : forall (s : S) (a : A)\n      , member a (insert a s) = member a (insert a (insert a s))\n  }.\n\n\nSection BinarySearchTree.\n\n  Inductive tree (A : Type) : Type :=\n    | Leaf   : tree A\n    | Branch : tree A -> A -> tree A -> tree A\n    .\n  \n  (* How to represent the balanced tree property in for tree? *)\n  \n  Fixpoint tree_member {A : Type} `{ordered A} (x : A) (t : tree A) : bool :=\n    match t with\n      | Leaf _         => false\n      | Branch _ l y r =>\n          match (x <? y) with\n            | true  => tree_member x l\n            | false =>\n                match (y <? x) with\n                  | true  => tree_member x r\n                  | false => true\n                end\n          end\n    end.\n\n  Fixpoint tree_insert {A : Type} `{o : ordered A} (x : A) (t : tree A) : tree A :=\n    match t with\n      | Leaf _         => Branch A (Leaf A) x (Leaf A)\n      | Branch _ l y r =>\n          match (x <? y) with\n            | true  => Branch A (tree_insert x l) y r\n            | false =>\n                match (y <? x) with\n                  | true  => Branch A l y (tree_insert x r)\n                  | false => Branch A l y r\n                end\n          end\n    end.\n\nEnd BinarySearchTree.\n\nSection UnbalancedSet.\n\nTheorem tree_empty_member\n  : forall (A : Type) (o : ordered A) (a : A)\n  , tree_member a (Leaf A) = false.\nProof.\nAdmitted.\n\nTheorem tree_insert_member\n  : forall (A : Type) (o : ordered A) (s : tree A) (a : A)\n  , tree_member a (tree_insert a s) = true.\nProof.\nAdmitted.\n\nTheorem tree_insert_non_member\n  : forall (A : Type) (o : ordered A) (s : tree A) (a : A)\n  , tree_member a s = false -> tree_member a (tree_insert a s) = true.\nProof.\nAdmitted.\n\nTheorem tree_insert_member_idenpotent\n  : forall (A : Type) (o : ordered A) (s : tree A) (a : A)\n  , tree_member a (tree_insert a s) = tree_member a (tree_insert a (tree_insert a s)).\nProof.\nAdmitted.\n\nInstance unbalanced_set_tree {A : Type} `{o : ordered A} : set (tree A) A :=\n  { empty                     := Leaf A\n  ; insert                    := tree_insert\n  ; member                    := tree_member\n  ; empty_member              := tree_empty_member _ _\n  ; insert_non_member         := tree_insert_non_member _ _\n  ; insert_member_idenpotent  := tree_insert_member_idenpotent _ _\n  }.\n\nEnd UnbalancedSet.\n", "meta": {"author": "andorp", "repo": "LearningCoq", "sha": "5a1f7582853ec033f952a710017e5888b1edea89", "save_path": "github-repos/coq/andorp-LearningCoq", "path": "github-repos/coq/andorp-LearningCoq/LearningCoq-5a1f7582853ec033f952a710017e5888b1edea89/PurelyFunctionalDataStructures/Chapter02/Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7710471452214742}}
{"text": "Inductive day : Type :=\n| monday : day\n| tuesday : day\n| wednesday : day\n| thursday : day\n| friday : day\n| saturday : day\n| sunday : day.\n\nDefinition next_weekday(d: day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => monday\n  | saturday => monday\n  | sunday => monday\n  end.\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof.\n  simpl. 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\nExample test_orb1: (orb true false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb2: (orb false false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb3: (orb false true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb4: (orb true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample test_orb5 : false || false || true = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\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\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  match b1 with\n  | true => andb b2 b3\n  | false => false\n  end.\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\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.\n\nEnd Playground1.\n\nDefinition minustwo (n: nat) :nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\n\nFixpoint evenb (n: nat) :bool:=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n: nat): bool :=\n  negb (evenb n).\n\nExample test_oddb1: oddb 1 = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_oddb2: oddb 4 = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\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  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  Example test_mult1: (mult 3 3) = 9.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\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\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 (factorial n') (S 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\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\nTheorem plus_n_O: forall n: nat, n = n + O.\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem plus_id_example: forall n m:nat, 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 = 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\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.\nQed.\n\nTheorem mult_S_1: forall n m:nat, 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\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 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\nFixpoint blt_nat (n m: nat): bool :=\n  match n with\n  | O => match m with\n         | O => false\n         | S n' => true\n         end\n  | S n' => match m with\n            | O => false\n            | S m' => blt_nat n' m'\n            end\n  end.\n\nTheorem plus_1_neq_0_firsttry: forall n: nat, beq_nat (n + 1) 0 = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem plus_1_neq_0: forall n:nat, beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\nTheorem negb_involutive: forall b:bool, 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 andb_commutative': forall b c:bool, 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: 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  - 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, beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\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\nTheorem andb_true_elim2: forall b c: bool, andb b c = true -> c = true.\nProof.\n  intros.\n  induction b.\n  - simpl in H. apply H.\n  - inversion H.\nQed.\n\nTheorem zero_nbeq_plus_1: forall n:nat, beq_nat 0 (n + 1) = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\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\nTheorem identity_fn_applied_twice:\n  forall (f: bool -> bool), (forall (x: bool), f x = x) -> forall (b: bool), f (f b) = b.\nProof.\n  intros f.\n  intros H.\n  intros [].\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\n  - rewrite -> H.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem andb_eq_orb:\n  forall (b c: bool), (andb b c = orb b c) -> b = c.\nProof.\n  intros [] c.\n  - simpl.\n    intros H.\n    rewrite -> H.\n    reflexivity.\n  - simpl.\n    intros H.\n    rewrite -> H.\n    reflexivity.\nQed.\n", "meta": {"author": "liuxueyang", "repo": "software-foundations-solutions", "sha": "0b460f106236ffa9c39f6492484426b04286f627", "save_path": "github-repos/coq/liuxueyang-software-foundations-solutions", "path": "github-repos/coq/liuxueyang-software-foundations-solutions/software-foundations-solutions-0b460f106236ffa9c39f6492484426b04286f627/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8856314738181876, "lm_q1q2_score": 0.771028341922585}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import List.\nImport ListNotations.\n\n\nFixpoint list_max (xs : list nat) : nat :=\n    match xs with\n    | [] => 0\n    | x :: xs => max x (list_max xs)\n    end.\n\nLemma list_max_in_list : forall xs,\n    xs <> [] ->\n    In (list_max xs) xs.\ninduction xs; intros Hxs.\n- exfalso. congruence.\n- simpl. destruct (Max.max_dec a (list_max xs)) as [Hmax | Hmax].\n  + left. congruence.\n  + destruct xs as [| b xs].\n    * left. simpl. rewrite Max.max_0_r. reflexivity.\n    * right. rewrite Hmax. apply IHxs. discriminate.\nQed.\n\nLemma list_max_ge : forall xs x,\n    In x xs ->\n    x <= list_max xs.\ninduction xs; intros ? Hin.\n- inversion Hin.\n- destruct Hin as [Hin | Hin].\n  + subst a. simpl. apply Max.le_max_l.\n  + simpl. apply Nat.le_trans with (m := list_max xs).\n    * apply IHxs. exact Hin.\n    * apply Max.le_max_r.\nQed.\n\n\nPrint Init.Nat.max.\n\nFixpoint max''' (n m : nat) : nat :=\n    match n with\n    | 0 => m\n    | S n' =>\n            match m with\n            | 0 => n\n            | S m' => S (max n' m')\n            end\n    end.\n\nDefinition max'' (n m : nat) : nat :=\n    nat_rect (fun _ => nat -> nat)\n        (fun m => m)\n        (fun n' IHn m =>\n            nat_rect (fun _ => nat)\n                (S n')\n                (fun m' IHm => S (IHn m'))\n            m)\n    n m.\n\nDefinition max' (n m : nat) : nat :=\n    nat_rect (fun _ => nat -> unit -> nat)\n        (fun m dummy => m)\n        (fun n' IHn m dummy =>\n            nat_rect (fun _ => unit -> nat)\n                (fun dummy => S n')\n                (fun m' IHm dummy => S (IHn m' dummy))\n            m dummy)\n    n m tt.\n\nLemma max'_correct : forall n m, max' n m = max n m.\ninduction n; destruct m; simpl; try reflexivity.\n- rewrite <- IHn. reflexivity.\nQed.\n\nDefinition list_max' (xs : list nat) : nat :=\n    list_rect (fun _ => nat)\n        (0)\n        (fun x xs IHxs => max' x IHxs)\n    xs.\n\nLemma list_max'_correct : forall xs, list_max' xs = list_max xs.\ninduction xs; simpl; try reflexivity.\n- rewrite IHxs. apply max'_correct.\nQed.\n\n\nRequire String.\nRequire Import HList Utopia SourceLifted SourceValues CompilationUnit.\nRequire Import OeufPlugin.OeufPlugin.\n\nSet Printing All.\nOeuf Reflect list_max' As list_max_cu.\nUnset Printing All.\n\nCheck list_max_cu : compilation_unit.\n\nLemma list_max_cu_validate : hhead (genv_denote (exprs list_max_cu)) hnil = list_max'.\nreflexivity.\nQed.\n\nRequire Pretty.\n\nOeuf Eval lazy Then Write To File \"list_max.oeuf\" (Pretty.compilation_unit.print list_max_cu).\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/demos/list_max/list_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.7710283407813111}}
{"text": "\n\n(* ================================================================== *)\n(* ===================== Reasoning about lists  ===================== *)\n(* ================================================================== *)\n\nSet Implicit Arguments.\n\nRequire Import List.\nRequire Import Omega.\nImport ListNotations.\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\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\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\n\nLemma ex1_a : SubList (5::3::nil) (5::7::3::4::nil).\nProof.\n  constructor.\n  constructor.\n  constructor.  \n  constructor.\nQed.\n\n\nLemma ex1_b : forall (A:Type) (l:list A), SubList l l.\nProof.\n  intros.\n  induction l.\n  constructor.\n  constructor.\n  assumption.\nQed.\n\nLemma ex1_c : forall (A B:Type) (f:A->B) (l1 l2:list A), SubList l1 l2 -> SubList (map f l1) (map f l2).\nProof.\n  intros.\n  induction H.\n  constructor.\n  simpl.\n  constructor.\n  assumption.\n  simpl.\n  constructor.\n  assumption.\nQed.\n\nLemma ex1_d : forall (A:Type) (x:A) (l : list A), In x l -> exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  intros.\n  induction H.\n  exists nil. exists xs. simpl. reflexivity.\n  destruct IHIn as [I1 H1]. destruct H1 as [I2 H1]. exists (x0::I1). exists I2.  rewrite <-app_comm_cons.\n  rewrite H1. reflexivity.\nQed.\n\nFixpoint drop (A:Type) (n:nat) (l : list A)  : list A :=  \n  match n with               (* Dar match com n, pois a guarda para quando l é nil está definida na função tl do lists.*)\n  | 0 => l                   (* Quando n igual a 0, retorna a lista. *)\n  | S n' => drop n' (tl l)   (* Quando n maior que 0, remove-se o primeiro elemento com a função tl de lists. *)\n  end.\n\nEval compute in drop 2 (5::7::3::4::nil). (* Provar q funciona *)\n\nLemma ex2_a : drop 2 (5::7::3::4::nil) = (3::4::nil).\nProof.\n  constructor.\nQed.\n\nLemma ex2_b : forall (A:Type) (n:nat) (l:list A), SubList (drop n l) l.\nProof.\n  intros H n.\n  induction n.\n  - unfold drop. apply ex1_b.\n  - induction l.\n    + simpl. apply IHn.\n    + simpl. constructor. apply IHn.\nQed.\n\nInductive Sorted : list nat -> Prop :=\n| sort0 : Sorted nil\n| sort1 : forall a:nat, Sorted (a::nil)\n| sort2 : forall z1 z2:nat, forall l:list nat, z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l).\n\nLemma ex3_a : forall (x y:nat) (l:list nat), x<=y -> (Sorted (y::l)) -> Sorted (x::l).\nProof.\n  intros.\n  induction l.\n  - constructor.\n  - constructor.\n    + rewrite H. inversion H0. exact H3.\n    + inversion H0. exact H5.\nQed.\n\n(*---------- LEMAS AUXILIARES PARA RESOLVER O EX3_B ----------*)\nLemma sorted_min : forall (x y:nat) (l:list nat), Sorted(x::y::l) -> x <= y.\nProof.\n  intros.\n  inversion H.\n  exact H2.\nQed.\n\nLemma aux: forall (y a :nat) (l:list nat),In y (a::l)  ->  y = a \\/ In y l.\nProof.\nintros.\ninversion H. \n- left. trivial. \n- right. assumption.\nQed.\n\nLemma auxObvious: forall (x y :nat) (l:list nat), x<=y -> Sorted(x::y::l) -> Sorted(x::l).\nProof.\n  intros.\n  inversion H0.\n  generalize H5.\n  generalize H3.\n  apply ex3_a.\nQed.\n(*---------- ----- ---------- ---- -------- - ----- ----------*)\n\nLemma ex3_b : forall (x y:nat) (l:list nat), (In y l) /\\ (Sorted (x::l)) -> x <= y.\nProof.\n  intros.\n  inversion H.\n  induction l.\n  - inversion H0.\n  - apply sorted_min in H1. apply aux in H0. destruct H0.\n    + rewrite H0. exact H1.\n    + apply IHl.\n      * split.\n        { - exact H0. }\n        { - destruct H. generalize H2. generalize H1. apply auxObvious. }\n      * exact H0.\n      * destruct H. generalize H2. generalize H1. apply auxObvious.\nQed.\n\nLemma ex4_a : forall (A:Type) (l:list A), Prefix l l.\nProof.\n  intros.\n  induction l.\n  constructor.\n  constructor.\n  assumption.\nQed.\n\n(*---------- LEMAS AUXILIARES PARA RESOLVER O EX4_B ----------*)\nLemma pref_conc_def : forall (A:Type) (l1 l2:list A), Prefix l1 l2 -> exists l3, l2 = l1 ++ l3. \nProof.\n  intros.\n  induction H.\n    - exists l. simpl. trivial.\n    - destruct IHPrefix. exists x0. rewrite H0. apply app_comm_cons.\nQed.\n\nLemma pref_conc_prefix : forall (A:Type) (l1 l2:list A), Prefix l1 (l1++l2).\nProof.\n  intros.\n  induction l1.\n  - simpl. constructor.\n  - simpl. constructor. exact IHl1.\nQed.\n(*---------- ----- ---------- ---- -------- - ----- ----------*)\n\nLemma ex4_b : forall (A:Type) (l1 l2 l3:list A), Prefix l1 l2 /\\ Prefix l2 l3 -> Prefix l1 l3.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  apply pref_conc_def in H1.\n  destruct H1.\n  apply pref_conc_def in H2.\n  destruct H2.\n  rewrite  H0.\n  rewrite  H.\n  assert(((l1++x)++x0)=(l1++(x++x0))). \n    - apply app_assoc_reverse. \n    - rewrite H1. apply pref_conc_prefix.\nQed.\n\nLemma auxEqual : forall (A:Type) (x:A) (l1 l2:list A), l1 = l2 -> x::l1 = x::l2.\nProof.\n  intros.\n  induction H.\n  trivial.\nQed.\n\nLemma ex4_c : forall (A:Type) (l1 l2:list A), Prefix l1 l2 /\\ Prefix l2 l1 -> l1 = l2.\nProof.\n  intros. \n  destruct H.\n  induction H.\n  - inversion H0. trivial.\n  - apply auxEqual. apply IHPrefix. inversion H0. exact H2. \nQed.\n", "meta": {"author": "Th0l", "repo": "VF", "sha": "2c7393433656dc395fd6a3c7c79e1051f53afcf3", "save_path": "github-repos/coq/Th0l-VF", "path": "github-repos/coq/Th0l-VF/VF-2c7393433656dc395fd6a3c7c79e1051f53afcf3/TPCs/7_CoqTpc2/A81716_Coq2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7710283359756402}}
{"text": "Require Import Eqdep_dec Peano_dec Substitution JMeq. \nRequire Import Image Arith.\nRequire Export InductiveFiniteSets Arith. \n\n(**  * Definitions and proofs about co products of Finite types, etc  *)\n\nSet Implicit Arguments.\n\nSection FinSum_defs.\n\nImplicit Arguments fz [n ].\n \n\n Fixpoint fin_inl (n m : nat ) (i : Fin n) {struct i} : Fin (n + m) :=\n          match i  in Fin n return Fin (n + m) with\n          | fz _  => fz \n          | fs x k => fs (fin_inl  m  k)\n          end.\n\n Fixpoint  fin_inr (n m : nat) (i:Fin m) {struct n}: Fin (n + m) :=\n     match n return Fin (n + m) with\n        | O => i\n        | S n' => fs (fin_inr n' i)\n       end.\n\n \n  (** View for CoProducts of finite types  *)\n  Inductive FinSum (n m : nat)  : Fin (n + m) -> Type :=\n         | is_inl : forall i: Fin n ,  FinSum n m (fin_inl m  i)\n         | is_inr : forall j: Fin m, FinSum  n m  (fin_inr  n j).\n\n  Fixpoint finsplit (n m : nat) {struct n}  \n                : forall  (i : Fin (n + m)), FinSum n m i :=\n     match n as e return (forall  (i : Fin (e + m)), FinSum e m i) with\n     | O => fun i => is_inr _ i\n     | S n' => fun i =>  let f := finSN i in\n                   match f in (FinSN f0) return (FinSum (S n') m f0) with\n                   | isfz => is_inl m  (fz (n := n'))\n                   | isfs j =>  let f0 := (finsplit n' m j) in\n          match f0 in (FinSum _ _ f1) return (FinSum (S n') m (fs f1)) with\n                     | is_inl x => is_inl m (fs x)\n                     | is_inr y => is_inr (S n') y\n                     end\n                  end\n     end. \n\n(** * Results and Proofs *)\n Lemma finsplit_inl : forall (n m: nat) (i : Fin n),    \n             finsplit n m (fin_inl m i) = is_inl m   i.\n Proof.\n   intros n m; induction i; simpl; trivial. \n   rewrite IHi; reflexivity.\n Qed.\n\n Lemma finsplit_inr : forall (n m: nat) (i : Fin m),    \n        finsplit n m (fin_inr  n i) = is_inr  n  i.\n Proof.\n   induction n; simpl; trivial. \n   intros m i; rewrite (IHn m i); reflexivity.\n Qed.\n\n Lemma fin_inl_inject : forall (n m : nat) (i j : Fin n), \n       fin_inl  m i = fin_inl  m j -> i = j.\n Proof.\n   induction i; destruct j using FinSn_rect; auto. \n   intro H ; discriminate H. \n   intro H; rewrite (IHi j (fsInject  H)) ; trivial.\n   intro H; discriminate H.\n Qed.\n\nLemma fin_inr_inject : forall (n m : nat) (i j : Fin m),  \n   fin_inr n  i = fin_inr n  j -> i = j.\nProof.\n   induction n; simpl; auto.\n   apply (fun m i j H =>  (IHn m i j (fsInject H))).\nQed.\n\n Definition fincase (n m : nat)(X : Type )  (l : Fin n -> X) ( r : Fin m -> X) \n     (i : Fin ( n + m)):= \n   let f := finsplit n m i in\n   match f with\n   | is_inl i => l i\n   | is_inr j => r j\n   end.\n\n Lemma f_fincase (n m : nat) (X Y : Type) (f : X -> Y)  \n                (l : Fin n -> X) ( r : Fin m -> X) (i : Fin ( n + m)) :\n       f (fincase l r i) = fincase (fun x  => f (l x)) (fun x => f (r x)) i .\n Proof.\n  unfold fincase; intros n m X Y f l r i.\n  destruct (finsplit n m i); trivial.\n Qed.\n\n\nDefinition FinCase (n m : nat) (i : Fin (n + m)) : Fin n + Fin m :=\n   match finsplit n m i with\n   | is_inl a => inl (Fin m) a\n   | is_inr a => inr (Fin n) a\n   end.\n\nDefinition CaseFin (n m : nat) (i : Fin n + Fin m ) : Fin (n + m) :=\n  match i with\n  | inl a => fin_inl  m a\n  | inr b => fin_inr n  b\n  end.\n \nLemma FinCaseFin : forall (n m : nat)(i : Fin n + Fin m), \n    FinCase n m (CaseFin i) = i.  \nProof.\n  unfold FinCase; unfold CaseFin. \n  intros n m i; destruct i; auto.\n  rewrite (finsplit_inl m f); reflexivity.\n  rewrite (finsplit_inr n f); reflexivity.\nQed.\n\nLemma CaseFinCase : \n   forall (n m : nat)(i : Fin (n + m)), CaseFin (FinCase n m i) = i.\nProof.\n  unfold CaseFin; unfold FinCase.\n  intros n m i; destruct (finsplit n m i); trivial.\nQed.\n\nLemma FinCase_inl (n m  : nat) (i : Fin n) : \n   (FinCase n m (fin_inl  m i) )= (inl (Fin m) i).\nProof.\n  intros n m i;  unfold FinCase.\n  rewrite  finsplit_inl; trivial.\nQed.\n\nLemma FinCase_inr (n m  : nat) (i : Fin m) : \n    (FinCase n m  (fin_inr  n i) )= (inr (Fin n) i).\nProof.\n  intros n m i;\n  unfold FinCase.\n  rewrite  finsplit_inr; trivial.\nQed. \n\nLemma fincase1 (A: Type) (n m : nat)\n    (f : Fin (S n) -> A) (g : Fin m -> A)  (a : Fin (n + m)) :  \n               fincase f g (fs a) = fincase (fun i => f (fs i)) g a.\nProof.\n  unfold fincase; intros A n m f0 g0 a ; simpl. \n  destruct (finsplit n m a); trivial .\nQed. \n\nLemma finCase_eq  (n m : nat) \n     (f : Fin n -> nat) (g : Fin m -> nat)  (a : Fin (n + m)) :  \n               match  FinCase n m  a with\n               inl z => f z\n               | inr z => g z\n               end = fincase f g a.\n Proof.\n  unfold fincase; unfold FinCase.\n  intros n m f0 g0 i.\n  destruct (finsplit n m i); trivial.\n Qed.\n\n Lemma fincaseS (n m : nat) (f : Fin (S n) -> nat)\n     (g : Fin m -> nat)  (a : Fin (n + m)) :  \n               match  FinCase n m  a with\n               inl z => f (fs z)\n               | inr z => g z\n               end = \n              match FinCase (S n) m (fs a) with\n              | inl z => f z\n              | inr z => g z\n             end. \nProof.\n  intros n m f0 g0 a.\n  generalize (finCase_eq (fun x => f0 (fs x)) g0 a).\n  intro H; simpl in H.\n  rewrite H. \n  rewrite (finCase_eq f0 g0 (fs a)). \n  apply (sym_equal (fincase1 f0 g0 a)).\nQed.\n\n\nEnd FinSum_defs.\n\n\nSection reversing_inductive_finite_sets.\n (** * Top and Embed *)\n\n Implicit Arguments fz [ n].\n Fixpoint emb (n : nat) (i:Fin n) {struct i }: Fin (S n) :=\n   match i in Fin n  return Fin (S n) with\n   |  fz _  =>  fz \n   |  fs _ j => fs (emb j)\n   end. \n     \n Fixpoint tp (n:nat) : Fin (S n) :=\n    match n return Fin (S n) with\n    | O => fz \n    | S x' => fs (tp x' )\n   end.\n\n(** View on tp and emb *)\nInductive FinEmtp (n : nat) : Fin (S  n) -> Type :=\n   | isTp :  FinEmtp (tp n)\n   | isEmb : forall  (i : Fin n), FinEmtp (emb i).\n\n Fixpoint finEmtp (n : nat) : forall i : Fin (S n) ,  FinEmtp i :=\n   match n as e return (forall i : Fin (S e), FinEmtp i) with\n   | O => fun i => let f := finSN i in  \n          match f in (FinSN f0) return FinEmtp f0 with\n          | isfz => isTp 0\n          | isfs j => match (fin_0_empty j) with end\n          end\n   | S n' => fun f => let f' := finSN f in\n           match f' in (FinSN f0) return FinEmtp f0 with\n           | isfz => isEmb (fz (n := n'))\n           | isfs i => let k := finEmtp i in\n              match k in (FinEmtp  f1) return (FinEmtp  (fs f1)) with\n              | isTp => isTp (S n') \n              | isEmb i => isEmb (fs  i)\n              end\n           end\n   end.\n\n Definition FinEmTp_rect\n     : forall (n : nat) (P : Fin (S n) -> Type),\n       (forall y : Fin n, P (emb y)) -> P (tp n) -> forall x : Fin (S n), P x :=\n   fun n P H0 H1 x => match (finEmtp x) in (FinEmtp  e) return (P e) with\n                    | isTp => H1\n                    | isEmb i => (H0 i)\n                    end.\n\n  (** forgetful function using the emb _ tp view *)\n  Fixpoint foo1 n : Fin n -> nat :=\n    match n as e return Fin e -> nat with\n    | O => fun i => \n             match (fin_0_empty i) return nat with end \n    | S m => fun i => match (finEmtp i) with\n                      | isTp => m\n                      | isEmb j => foo1 j\n                      end\n    end.\n\n \n  (* tp not fz *)\n  Lemma tp_not_fz : forall n, tp (S n) <> fz (n := S n).\n  simpl. unfold not;  intros n H; inversion H.\n Qed.\n\n Lemma tp_emb (n : nat) (i : Fin n): tp n = emb i -> False.\n Proof.\n   induction i; simpl.\n   intros h; discriminate h.\n    apply (fun H => IHi (fsInject H)).\n Qed.\n\nLemma fs_emb (n : nat) (i : Fin n) : fs i = emb i -> False.\nProof.\n  induction i.\n  intro h; discriminate h.\n  simpl. apply (fun H => IHi (fsInject H)).\nQed.\n\n(* emb is injective *)\n Lemma  embInject ( n :nat) (i j: Fin n) :   emb i = emb j -> i = j .\n Proof.\n   induction i; destruct j using FinSn_rect; simpl.\n   intro h; discriminate h. trivial.\n   intro h; rewrite (IHi j (fsInject h)); trivial. \n   intro h; discriminate h.\nQed.\n\n (** Reversing the nat-indexed family, Fin  *)\n Fixpoint rv (n:nat) (i:Fin n) {struct i} : Fin n :=\n    match  i in Fin n  return Fin n with   \n    |  fz p => tp p \n    |  fs _ k => emb  (rv k)\n   end.   \n\n Lemma emb_S :  forall n: nat, forall i: Fin n, rv  (emb i) = fs (rv i).\n Proof.\n   induction  i; simpl; auto.\n   rewrite IHi;  simpl;  trivial.\n Qed.             \n        \n (** reversing Fin is involutive *)\n Theorem idem_rvFin: forall n: nat, forall i:Fin n,  rv (rv i) = i.\n Proof.\n   induction i; simpl;  auto.\n   induction n; simpl; auto.\n   rewrite IHn ; trivial.   \n   rewrite (emb_S (rv i));  rewrite IHi; reflexivity.\n Qed.\n\n Lemma fsFz (n : nat) (i : Fin n) : rv fz = rv (fs i) -> False .\n Proof.\n   intros  n i; simpl; generalize (rv i) . \n   induction f; simpl; try  (intro h; discriminate h). \n   exact (fun H => IHf f (fsInject H)).\n Qed.\n \n  (** rev in injective *)\n Lemma rvInject (n : nat) (i j : Fin n) : rv i = rv j -> i = j.\n Proof.\n    induction n. \n    abstract inversion i.\n    intros i j; destruct j using FinSn_rect . \n    destruct i using FinSn_rect.\n    intro H; elim (IHn i j (embInject (rv i) (rv  j) H)); trivial.\n    intro H; case (fsFz j H).\n    destruct i using FinSn_rect; auto.  \n    intro H; case (fsFz i (sym_equal H)).\nQed. \n \n Lemma rvdist (n: nat) (i j: Fin n): rv  i = j -> i = rv j.\n Proof.\n  intros n i j H; \n  apply (eq_subs (fun x : Fin n => x = rv (n := n) j) \n       (idem_rvFin i) (f_equal (rv (n := n)) H)).\n Qed.\n\n Lemma rvdistJM (n m : nat) (H : n = m) (i : Fin n) (j : Fin m) : \n        JMeq (rv i) j -> JMeq i (rv j).\n Proof. \n  intros n m H ; case H.\n  intros i j h; rewrite  (rvdist i (JMeq_eq h) ); trivial.\n Qed. \n\nLemma idmrv_subst: forall (n : nat) (i : Fin n) \n  (P : Fin n -> Fin n -> Type), P (rv (rv i))  (rv i) -> P i (rv i).\n Proof.\n   intros n i P; \n   rewrite (idem_rvFin i); \n   trivial.\n Qed.\n  \nDefinition rv_elim (n: nat) (i : Fin n) \n  (P : Fin n -> Fin n -> Type ) (H : forall j, P (rv j) j) : P i (rv i) :=\n   idmrv_subst i P (H (rv i)).\n\n Section Foo.\n    (** *** Redunctions *)\n  \n   Lemma foo_emb : forall n (i : Fin n), foo (emb i) = foo i.\n     induction i; simpl; auto.\n   Qed.\n\n    Lemma foo_rvtp:  forall n : nat, foo (rv (tp n)) = 0.\n      induction n; simpl ; auto.\n      rewrite <- IHn.\n      apply foo_emb.\n    Qed.\n \n    Lemma foo_tp : forall n, foo (tp n) = n.\n      induction n; simpl; auto.\n    Qed.\n\n    Lemma fooRv n (i : Fin n) : foo (rv i) = n - (foo i) - 1.\n    Proof.\n      induction i; simpl. rewrite <- (minus_n_O ).\n      apply foo_tp. rewrite foo_emb. trivial.\n    Qed.\n\n    Lemma foo_inl n m (i : Fin n) : foo (fin_inl m i) = foo i.\n    Proof.\n       induction i; simpl; auto.\n    Qed.\n\n     Lemma foo_inr n m (i : Fin m) : foo (fin_inr n i) =  n + (foo i).\n    Proof.\n      induction n; simpl; auto.\n    Qed.\n\n   Lemma foo_nm n m (i : Fin (n + m)) : foo i = \n       match finsplit  n m  i with\n       | is_inl a => foo a\n       | is_inr a => n + foo a\n       end.\n    Proof.\n      intros n m i; destruct (finsplit n m i);  \n      [rewrite (foo_inl m i); trivial |  rewrite (foo_inr n j); trivial]. \n   Qed.\n\n    \n      \n End Foo.\n\n\nSection Alternative_Reverse.\n (** * Alternative Definition of rev *) \n\n Definition S1 (n:nat) : S n = n + 1.\n Proof.\n  induction n; auto.\n  exact (eq_subs (fun x : nat => S x = S n + 1) (sym_equal IHn) \n    (refl_equal (S n + 1)) ).\n Defined.\n\n Axiom eq_unique : forall (A : Set) (a : A) (H : a = a), H = refl_equal a.\n Axiom extensionality : forall (A B: Type)  (f g: A ->  B ), \n      (forall a , f a = g a )-> f =g. \n\n Definition Rv (n : nat) : Fin n ->   Fin n.  \n  induction n.\n  intro i; try inversion i.\n  exact (fun i : Fin (S n) => \n       fincase (fun (x:  Fin n) => fs (IHn x)) (fun _ : Fin 1 => fz ) \n         (eq_subs Fin (S1 n) i) ).\n Defined.\n\nLemma Rv_fs (n : nat) (i : Fin (S n)) :\n   Rv i = fincase (fun a : Fin n => fs (Rv a)) (fun _ : Fin 1 => fz ) \n    (eq_subs Fin (S1 n)  i).\n Proof.\n    intros n i; destruct i using FinSn_rect; auto.\n Qed.\n \n Lemma F_fincase (n : nat) (i : Fin (n + 1) )(F : forall m : nat, Fin m -> \n     Fin (S m)) :\n     fincase (fun x : Fin n => F (S n) (fs (Rv x))) \n       (fun _ : Fin 1 => F (S n)  fz ) i =\n   F (S n) (fincase (fun x : Fin n => fs (Rv x)) (fun _ : Fin 1 => fz ) i).\n Proof.\n  intros n i F; unfold fincase.\n  destruct (finsplit n 1 i); trivial.\n Qed.\n\n Lemma fs_eq_subs (n m : nat) (H : n = m) (i : Fin n) :  \n      fs (eq_subs Fin H i) = eq_subs Fin (f_equal S H) (fs i).\n  Proof. \n   intros n m H; case H; trivial.\n  Qed.\n\n Lemma match_rem1 (n m : nat) (H : n = m) (H1 : S n = S m)  (i : Fin n) :\n   match H1 in ( _ = y ) return (Fin y) with \n   | refl_equal => fs i\n   end = \n   match H in ( _ = y ) return (Fin (S y)) with \n   | refl_equal => fs i\n   end .\n Proof.\n  intros n m H; case H.\n  intro H1; rewrite (eq_unique H1); trivial.\n Qed. \n\n(*Require Import Peano_dec. *)\n\n Lemma emb_Rv : forall  (n : nat) (i : Fin n), Rv (fs i) = emb (Rv i).\n Proof.\n  induction n.\n  intro i; try inversion i. \n  intro i; destruct i using FinSn_rect.\n  replace (emb (Rv (fs i))) with \n    (fincase (fun x : Fin n => fs (emb (Rv x))) (fun _ : Fin 1 => fz )\n                            (eq_subs Fin (S1 n) (fs i))).\n  rewrite  (extensionality  (fun x : Fin n => fs (emb (Rv x)))\n           (fun x : Fin n => fs (Rv (fs x))) \n           (fun a : Fin n => fs_eq (sym_eq (IHn a))) ).\n  rewrite (Rv_fs (fs (fs i))). \n  replace (eq_subs Fin (S1 (S n)) (fs (fs i))) with\n       (fs (eq_subs Fin (S1 n) (fs i))).\n  unfold fincase.\n  destruct (finsplit n 1 (eq_subs Fin (S1 n) (fs i))).\n  generalize  (finsplit_inl  1 (fs i0)).\n  intro H; simpl fin_inl in H; rewrite H; trivial.\n  destruct j using FinSn_rect.\n  inversion j. \n  Implicit Arguments fz [ ].\n  simpl; rewrite (finsplit_inr n (fz 0) ); trivial.\n  rewrite (fs_eq_subs (S1 n) ).\n   rewrite (proof_irrelevance (S (S n) = S n + 1)\n     (S1 (S n)) (f_equal S (S1 n)) ); trivial.\n  simpl Rv at 2; rewrite <- (F_fincase n (eq_subs Fin (S1 n) (fs i)) emb);  trivial.\n  simpl .\n  rewrite <- (F_fincase n (eq_subs Fin (S1 n) (fz n)) emb);  trivial.\n  rewrite   (extensionality\n (fun x : Fin n  => emb (fs  (Rv x))) (fun x : Fin n => fs (Rv (fs x)))\n (fun x : Fin n => fs_eq (sym_equal (IHn x)))\n  ).\n replace  (eq_subs Fin\n        (eq_subs (fun x : nat => S x = S (n + 1)) (sym_equal (S1 n))\n           (refl_equal (S (n + 1)))) (fs (fz n))) with (fs  (eq_subs Fin (S1 n) (fz n))).\n rewrite (fincase1 (fun x : Fin (S n) => fs (fincase (fun x0 : Fin n => fs (Rv x0))\n                    (fun _ : Fin 1 => fz n) (eq_subs Fin (S1 n) x))) \n     (fun _ : Fin 1 => fz (S n))\n          (eq_subs Fin (S1 n) (fz n))); trivial.\n replace (eq_subs (fun x : nat => S x = S (n + 1)) (sym_equal (S1 n))\n        (refl_equal (S (n + 1)))) with (S1 (S n)); auto.\n rewrite (proof_irrelevance (S (S n) = S n + 1)\n     (S1 (S n)) (f_equal S (S1 n)) ); trivial. \n rewrite  (fs_eq_subs (S1 n) (fz n)); trivial.\nQed. \n\n \n Lemma fz_eq_subs (n m : nat) (H : S n =  S m) :\n   fz m = match H in ( _ = y) return (Fin  y)  with\n         | refl_equal => fz n\n          end.\n Proof.\n   intros n m H ; injection  H. \n   intro H1; destruct  H1. \n   apply  (eq_subs (fun x : S n = S n => fz n =\n                          match x in (_ = y) return (Fin y) with\n                          | refl_equal => fz n\n                          end ) (sym_equal (eq_unique H))); trivial. \n Qed. \n\n Lemma rv_Rv : forall (n : nat) (i : Fin n), rv i = Rv i.\n Proof.\n  induction n.\n  intro i; try inversion i.\n  intro i; destruct i using FinSn_rect.\n  rewrite (emb_Rv i); rewrite <- (IHn i); trivial.\n  destruct n. \n  simpl; trivial.\n  simpl Rv.\n  replace  (eq_subs Fin\n        (eq_subs (fun x : nat => S x = S (n + 1)) (sym_equal (S1 n))\n           (refl_equal (S (n + 1)))) (fz (S n))) with\n              (eq_subs Fin (S1 (S n)) (fz (S n))); auto .\n  apply (eq_subs (fun x : Fin (S n + 1) => fs (tp n) =\n     fincase\n     (fun x : Fin (S n) =>\n      fs (fincase (fun x0 : Fin n => fs (Rv x0)) (fun _ : Fin 1 => fz n)\n          (eq_subs Fin (S1 n) x))) (fun _ : Fin 1 => fz (S n)) x ) \n                 (fz_eq_subs (S1  (S n)))).\n  unfold fincase; simpl.\n  apply  (eq_subs (fun x : Fin (S n) => fs (tp n) = fs x) (Rv_fs (fz n)) ). \n  rewrite <- (IHn (fz n)); trivial.\n Qed. \n  \n End  Alternative_Reverse.\n\nEnd reversing_inductive_finite_sets.\n(* Implicit Arguments fz [ ]. *)\n\n Section Rotate.\n(** * Rotate *)\n\n (* rotates the first position to the last , and remainig ones\n    one level up *)\n Definition rot n (i :  Fin n)  :  Fin n :=\n   match i in Fin e return Fin e with\n   | fz x => tp x\n   | fs _ j => emb j \n   end. \n\n Fixpoint rotn n : forall m, Fin m -> Fin m :=\n    match n with \n    | O => fun _ i => i\n    (* | S O => rot *)  \n    | S n' => fun m i => (rotn n' (rot i))\n    end.\n\n Definition rotn1 n m (i : Fin m)  := match le_lt_dec m n with\n                                      | left _ => rotn (n - m) i\n                                      | right _ => i\n                                      end.\n Definition rotn2 n (i : Fin n) := rotn1 n i.\n\n\nLemma rotn_Sn : forall n m (i : Fin m), rot (rotn n i) = rotn (S n) i.\n Proof. \n  induction n; simpl; auto. \n  intros. rewrite (IHn m (rot i)); simpl; trivial.\n Qed.\n\n Lemma rotn_rotn : forall n m x (i : Fin x), rotn n (rotn m i) = rotn (n+m) i.\n Proof.\n   induction n; simpl; auto.\n   intros. rewrite <- (IHn m x (rot i)); trivial.\n   rewrite (rotn_Sn m i); simpl; trivial.\n Qed.\n\n Lemma rotn_minus : forall n (i : Fin n), rotn (n - n) i = i.\n Proof.\n    intros ; rewrite  minus_diag; simpl; trivial.\n Qed.\n\n Lemma rotn_minus1 : forall n (i : Fin n), rotn (S n - n) i = rot i.\n Proof. \n   intros n i; rewrite <- (minus_Sn_m _ _ (le_n n)); simpl.\n   rewrite rotn_minus; trivial.\n Qed.\n\n Lemma rotn_nm : forall (n m : nat) (i : Fin m), rotn (n + m - n) i = rotn m i.\n Proof.\n  induction n; simpl. intros.\n  rewrite <- (minus_n_O m); trivial.\n  intros. apply (IHn m i).\n Qed.\n\n\n(*Lemma rotn_rot_swap : forall n m (i : Fin m), rot (rotn n i) = rotn n (rot i).\n Proof.\n   induction n; simpl; trivial.\n Qed. *)\n\n Lemma rot_inject : forall n (i j: Fin n), rot i = rot j -> i = j.\n   destruct i; destruct j using FinSn_rect; simpl; auto.\n   intro. destruct (tp_emb _ H). \n   intro H; rewrite (embInject _ _ H ); trivial.\n   intros H; destruct (tp_emb _ (sym_eq H)).\n Qed.\n\n Lemma rotn_inject : forall n m (i j : Fin m), rotn n i = rotn n j -> i = j.\n Proof.\n   induction n; simpl; auto.\n  intros. apply (rot_inject i j (IHn m (rot i) (rot j) H)).\n Qed.\n\n Lemma foo_rot (n : nat) (i : Fin n):\n     foo (rot i) = match i in Fin e return nat with\n             | fz m => foo (tp m)\n             | fs _ j => foo (emb j)\n             end. \n     destruct i; simpl; trivial.\n  Qed.\n\n \n Definition un_rot (n : nat) :  Fin n -> Fin n := \n   match n as e return Fin e -> Fin e with\n   | O => fun i => i\n   | S m => fun i => match finEmtp i with\n                     | isEmb i => fs i\n                     | isTp  => fz m\n                     end\n   end.\n\n Lemma un_rot_inject : forall n (i j : Fin n), un_rot i = un_rot j -> i = j.\n Proof.\n   destruct n; try intros; simpl. inversion i.\n   destruct (finEmtp i);  destruct (finEmtp j); trivial.\n   simpl in H. destruct (finEmtp (tp n));\n   destruct (finEmtp (emb i)); trivial. inversion H.\n   inversion H. rewrite (fsInject H); trivial. \n   simpl in *. \n   destruct (finEmtp (emb i)). destruct (finEmtp (tp n)); trivial.\n   destruct (finEmtp (tp n)). inversion H.  rewrite (fsInject H); trivial.\n   simpl in H. destruct (finEmtp (emb i)). destruct (finEmtp (emb i0)); trivial.\n   inversion H. destruct ( finEmtp (emb i0)). inversion H.\n   rewrite (fsInject H); trivial.\n Qed.\n\n\n (* rot in inverse  to un_rot *)\n Lemma rot_un_rot_id : forall n (i : Fin n), rot (un_rot i) = i.\n Proof.\n   destruct i; simpl.\n   destruct n; simpl; trivial.\n   destruct (finEmtp (fs i)); simpl; trivial.\n Qed.\n\n Lemma un_rot_rot_id : forall n (i : Fin n), un_rot (rot i) = i. \n Proof. \n   destruct i; simpl. \n   induction n; simpl; trivial.\n   destruct (finEmtp (tp n)); auto.\n   inversion IHn.\n   induction i; simpl; trivial.\n   destruct ( finEmtp (emb i)); simpl.\n   inversion IHi. rewrite IHi; trivial.\n Qed.\n\nEnd Rotate. \n\n\n(* Fixpoint eqFin (n :nat) (i  : Fin n): Fin n ->  bool :=\n   match i in Fin e return Fin e -> bool with\n  | fz _ => fun j => match finSN j with\n                     | isfz => true\n                     | _    => false\n                     end\n  | fs _ x => fun j => match finSN j with\n                      | isfs x1 => eqFin x x1\n                      | _ => false\n                      end\n  end.\n\n Lemma FinEq_ok : forall n (i j : Fin n), eqFin i j = true -> i = j.\n Proof.\n   induction i. destruct j using FinSn_rect;  simpl; auto. \n   intro H; discriminate H.\n   destruct j using FinSn_rect; simpl; auto.\n    intro H; rewrite (IHi _ H); trivial.\n   intro H; discriminate H.\n Qed. *)\n\n\nDefinition nofin (X: Type) (i : Fin 0) : X.\n    intros X  i; inversion  i.\n Defined. \n\nDefinition caseFin (n: nat) (X: Type) :  X ->  (Fin n -> X) -> Fin (S n) ->  X.\n   intros n X x h i.\n   destruct (finSN i) as [x | k].\n   exact x.\n   exact (h k).\nDefined.\n\nDefinition finplus_swap (n m : nat) (i : Fin (n + m)) : Fin (m + n) :=\n  match finsplit n m i with\n  | is_inl a => fin_inr  m a\n  | is_inr a => fin_inl n  a \n  end. \n\n Lemma finsplit_unique : forall n m (i : Fin (n +m)) ( x : FinSum n m i) , \n    x = finsplit n m i.\n Proof.\n    intros n m i x; destruct x.\n    exact (sym_equal (finsplit_inl m i)).\n    exact (sym_equal (finsplit_inr n j)).\n Defined.\n \n Lemma finsplit_inl_inr : forall (n m : nat) (i : Fin n) (j : Fin m), \n     fin_inl  m i = fin_inr n j -> False.\n Proof.\n    intros n m i j; induction i; simpl.\n    intro H; discriminate H.\n    exact (fun x => IHi (fsInject x)).\n Qed.  \n\nLemma fin_inlS  (n : nat) (i j: Fin n):  forall m : nat, \n       fin_inl m i = fin_inl m  j -> fin_inl  (S m) i = fin_inl (S m) j.\nProof.\n  intros n i j m; induction i; simpl; auto.  \n  destruct j using FinSn_rect ; simpl; auto.\n  intros H; discriminate H.  \n  destruct j using FinSn_rect; simpl  ; auto. \n   exact (fun a => fs_eq (IHi j (fsInject a))).\n  intro H; discriminate H.\nQed.\n\nLemma fin_inlP  (n : nat) (i j: Fin n):  \n  forall m : nat,  fin_inl  m i = fin_inl  m j ->\n        fin_inl  (pred m) i = fin_inl  (pred m) j.  \n Proof.\n  intros n i j m; induction i; simpl; auto.\n  destruct j using FinSn_rect ; simpl; auto.\n  intros H; discriminate H.  \n  destruct j using FinSn_rect; simpl  ; auto.\n  exact (fun a => fs_eq (IHi j (fsInject a))).\n  intro H; discriminate H.\n Qed.\n\nLemma fin_inrS (m : nat) (i j : Fin m) :\n   forall n : nat, fin_inr n  i = fin_inr n  j ->\n                     fin_inr (S n)  i = fin_inr (S n)  j.\nProof.\n   destruct n; simpl; exact (fun a => fs_eq a).\nQed. \n\nLemma fin_inrP (m : nat) (i j : Fin m) : \n     forall n : nat, fin_inr n  i = fin_inr n  j ->\n                  fin_inr (pred n)  i = fin_inr (pred n)  j.\n Proof.\n   destruct n; simpl; trivial.\n   exact (fun a => fsInject a).\nQed.\n \n Require Import Arith.\n\nLemma fininl_embO (n : nat) ( i : Fin n) : \n    emb (fin_inl  0 i) = fin_inl  0 (emb i).\nProof.\n   induction i; simpl ; auto.\n   exact (fs_eq IHi).\nQed.\n\nLemma fin_inl_inr  (n m : nat) (i : Fin n) (j: Fin m): \n     fin_inl  m i = fin_inr n  j  -> False.\nProof.\n  intros n m i j.\n  induction i;  simpl.\n  intro h; inversion h.\n  exact (fun x => IHi (fsInject x)).\nQed.\n\nLemma rv_fin_inlO (n : nat) (i : Fin n) : rv (fin_inl  0 i) = fin_inl 0 (rv i).\n  induction i; simpl.\n  induction n; simpl ; auto.\n  rewrite IHn; reflexivity.  \n  rewrite <- (fininl_embO (rv i)). \n  rewrite IHi; reflexivity.\n Qed.\n\nLemma emb_tpm (n : nat) : emb (tp (S n)) = fz (S (S n)) -> False .\nProof.\n simpl;  intros n H. \n discriminate H. \nQed. \n\nSection FinTimes_.\n  (** Products of finite types *)\n\n Fixpoint fpair  (n m : nat) (i : Fin n) (j : Fin m) : Fin (n * m) :=\n   match i in (Fin e) return Fin (e * m) with\n   | fz n => fin_inl (n * m) j\n   | fs _ i1 => fin_inr m (fpair i1 j)\n   end.\n\n\nInductive FinTimes (n m : nat) : Fin (n * m) -> Set :=\n  |isfpair : forall (i : Fin n) (j : Fin m), FinTimes n m (fpair  i j).\n\n\n Fixpoint fintimes (n m : nat) : forall i :  Fin (n * m), FinTimes n m i :=\n   match n as e return (forall i : Fin (e * m),  FinTimes e m i) with\n   | O => fun i => match (fin_0_empty i) return ( FinTimes 0 m i) with end\n   | S n0 => fun i => match finsplit _ _ i in (FinSum _ _ f0) \n                                    return (FinTimes (S n0) m f0) with\n             | is_inl l => isfpair (fz _) l\n             | is_inr r => match (fintimes _ _ r) in (FinTimes _ _ f1) \n                             return  (FinTimes (S n0) m (fin_inr m f1)) with\n                           | isfpair i1 j0 => isfpair (fs i1) j0 \n                           end\n             end\n   end. \n\n\n (* distritutivity of times over plus *)\n Definition dist (n m o : nat) (x : Fin (n * (m + o))) : Fin (n * m + n * o) :=\n   match fintimes n (m + o) x with\n   | isfpair i j =>\n      match finsplit m o j with\n      | is_inl i0 => fin_inl (n * o) (fpair i i0)\n      | is_inr j0 => fin_inr (n * m) (fpair i j0)\n     end\n end.\n\n\nEnd FinTimes_.\n\n\nDefinition finJmeq (n m : nat) (H : n = m) (i: Fin n) :\n   JMeq i (eq_subs (fun x : nat => Fin x) H i).\n intros n m H; case H.\n intro i; auto.\nQed. \n\n\nSection JMeq_fin_inl_or_inr.\n(** * Miscellaneous *)\nLemma fin_emb (n m : nat) (H : n = m) (i : Fin m) (J : Fin n) : \n     JMeq i J -> JMeq (emb i) (emb J).\n Proof.\n   intros n m H; elim H.\n   intros i J H0 ; elim H0; apply JMeq_refl.\n Qed.\n\n Lemma fin_inl_O : forall (n : nat) (i : Fin n), JMeq (fin_inl  0 i) i.\n Proof.\n   intro n; induction i; simpl.\n   apply  (eq_subs (fun x : nat => JMeq (fz (n + 0)) (fz x)) (sym_equal (plus_n_O n)) ).  \n   apply JMeq_refl.  \n   exact (fin_fs  (plus_n_O n) IHi).\n Qed.              \n \n Lemma match_simpl : forall (n m : nat) (i : Fin (n + m)) , \n             match\n                match\n                   match finsplit n m i with\n                   | is_inl a => inl (Fin m) a\n                   | is_inr a => inr (Fin n) a\n                   end\n                 with\n                 | inl a1 => inl (Fin m) (rv a1)\n                 | inr a1 => inr (Fin n) (rv a1)\n                 end\n               with\n               | inl b => inr (Fin m) b\n               | inr b => inl (Fin n)  b\n               end =\n             match finsplit n m  i  with\n             | is_inl a => inr (Fin m) (rv a)\n             | is_inr a => inl (Fin n) (rv a)\n             end.\n   Proof.\n       intros n m i; destruct (finsplit n m i); trivial.\n  Qed.\n\n(*  Lemma match_simpl_rv : forall (n m : nat) (i : Fin (n + m)) , \n             match\n                match\n                   match finsplit n m (rv i) with\n                   | is_inl a => inl (Fin m) a\n                   | is_inr a => inr (Fin n) a\n                   end\n                 with\n                 | inl a1 => inl (Fin m) (rv a1)\n                 | inr a1 => inr (Fin n) (rv a1)\n                 end\n               with\n               | inl b => inr (Fin m) b\n               | inr b => inl (Fin n)  b\n               end =\n             match finsplit n m  i  with\n             | is_inl a => inr (Fin m) (rv a)\n             | is_inr a => inl (Fin n) (rv a)\n             end.\n   Proof.\n       intros n m i.  rewrite (match_simpl _ _ (rv i)).\n    \n  destruct (finsplit n m i); trivial.\n  Qed. *)\n\nLemma fin_Jmeq (n m : nat) (i : Fin  m) : \n     JMeq (fs (fin_inr n   i)) (fin_inr n  (fs i)).\nProof.\n  induction n; simpl; auto.\n  intros m i;\n  apply  (fin_fs (sym_equal (plus_n_Sm n m)) (IHn m i) ).\nQed.\n\nLemma JM_rvEmb  (n m : nat) (i : Fin n) : \n    JMeq (emb (fin_inr m  i)) (fin_inr m  (emb i)).  \nProof.\n  induction m; simpl.\n  intro i; apply JMeq_refl.\n  intro i; exact (fin_fs (sym_equal (plus_Snm_nSm m n)) (IHm i)).\nQed.\n\nLemma Jmeq_fsInject (n m : nat) (i :Fin n) (j : Fin m) :\n     n = m -> JMeq (fs i) (fs j) -> JMeq i j.\nProof.\n  intros n m i j H; destruct H. \n  intro H; elim (fsInject (JMeq_eq H)) ;  trivial.\nQed.\n\nImplicit Arguments fin_inl [ ].\nImplicit Arguments fin_inr [ ].\nLemma fin_Jmeq_l (n m : nat) (i : Fin n) :\n    JMeq (fin_inl n (S m) i) (fin_inl (S n) m (fs i)) -> False.\nProof.\n  intros n m i; induction i.\n  intro H. \n  generalize (JMeq_eq (eq_subs (fun x : nat => JMeq (fz x) (fs (fz (n + m))))\n              (sym_equal (plus_Snm_nSm n m)) H )).\n  clear H; intro H; discriminate H.\n intro H; simpl in H.\n apply (IHi (Jmeq_fsInject (sym_equal (plus_Snm_nSm n m)) H) ).\nQed. \n   \nLemma JM_rvEmb1 (n m : nat) ( i : Fin n) : \n    JMeq (fin_inl n (S m) i ) (emb (fin_inl n m i)).\nProof.\n induction i.\n apply  (eq_subs (fun x : nat => JMeq (fz (n + S m)) (fz x))  (sym_equal (plus_Snm_nSm n m ))).\n apply JMeq_refl.\n apply (fin_fs (plus_Snm_nSm n m ) IHi).\nQed.\n\n\nLemma rvFin_inl (n m : nat) (i : Fin n) : \n     JMeq (rv (fin_inl n m i)) (fin_inr m n (rv i)).\nProof. \n  induction i. induction n; simpl.  \n  induction m; simpl; auto.\n  apply (fin_fs (sym_equal (S1 m)) IHm ).\n  simpl in IHn. \n  apply (trans_JMeq  (fin_fs (plus_comm m (S n)) IHn) (fin_Jmeq m (tp n))).\n  apply (trans_JMeq  (fin_emb (plus_comm m n) IHi) (JM_rvEmb m (rv i))).\nQed.\n \nLemma rvFin_inr (n m : nat) (i : Fin n) :  \n JMeq (rv (fin_inr m n i)) (fin_inl n m (rv i)).\nProof.\n  induction m; simpl.  \n  induction i; simpl.\n  apply (sym_JMeq (fin_inl_O (tp n))).\n  apply (sym_JMeq (fin_inl_O (emb (rv i)))). \n  apply (fun i => trans_JMeq (fin_emb (plus_comm  n m)  (IHm i) )\n           (sym_JMeq (JM_rvEmb1 m (rv i)))).\nQed.\n\n\nLemma inl_inr_eq (n : nat) (i j : Fin n) : \n    JMeq (fin_inr 0 n i) (fin_inl n 0 j) -> i = j.\nProof.\n  induction j; auto.\n  destruct i using FinSn_rect; simpl.\n  apply (eq_subs (fun x => JMeq (fs i) (fz x) -> fs i = fz n) \n         (sym_equal (plus_0_r n))) .\n  intro H; apply (JMeq_eq H);auto.  \n  trivial. \n  destruct i using FinSn_rect.\n  intro H; rewrite (IHj i (Jmeq_fsInject (sym_equal (plus_0_r  n)) H)); trivial.\n  apply  (eq_subs (fun x => JMeq (fz x) (fs (fin_inl n 0 j)) -> fz n = fs j)\n           (plus_0_r n)).\n  intro H; generalize (JMeq_eq H); intro h; discriminate h.\nQed.\n\nLemma finsumX (n m : nat) (i : Fin (n + m)) (j k : Fin (m + n))(g : k = (rv j))\n              (si  : FinSum n m  i) (sk :   FinSum m n k) :  JMeq i j -> \n  match si with \n  | is_inl a => inr (Fin m) (rv a)\n  | is_inr a => inl (Fin n) (rv a)\n  end\n  =\n  match sk with\n  | is_inl a => inl (Fin n) a\n  | is_inr a => inr (Fin m) a\n  end.  \n intros n m i j k g si sk H. \n destruct si; destruct sk.  \n rewrite (rvdist j (sym_equal g)) in H.\ncase (fin_inl_inr i (rv i0) (JMeq_eq (trans_JMeq H (rvFin_inl n i0)))).\nrewrite (rvdist j  (sym_equal g)) in H . \nrewrite (fin_inl_inject m i (rv j0) (JMeq_eq (trans_JMeq H (rvFin_inr m j0)))).  \nrewrite (idem_rvFin j0) ; trivial.\nrewrite (rvdist j (sym_equal g)) in H.\nrewrite  (fin_inr_inject n j0 (rv i) (JMeq_eq (trans_JMeq H (rvFin_inl n i)))).  \nrewrite (idem_rvFin i); trivial.\nrewrite (rvdist j (sym_equal g)) in H.\ncase  (fin_inl_inr (rv j1) j0 (sym_equal (JMeq_eq (trans_JMeq H (rvFin_inr m j1))))).\nQed.\n\n\n Lemma finsplit_rv_swap : forall n m (i : Fin (n + m)) (j : Fin (m + n)),\n   JMeq i j ->\n    match finsplit n m (rv i) with\n    | is_inl a => inl (Fin m) a\n    | is_inr b => inr (Fin n) b\n   end =\n   match finsplit m n j with\n   | is_inl a => inr (Fin n) (rv a)\n   | is_inr b => inl (Fin m) (rv b)\n   end.\n Proof.\n   intros n m i j H; rewrite (finsumX  (refl_equal (rv i))  (finsplit m n j) \n      (finsplit n m (rv i)) (sym_JMeq H)); trivial.\n Qed.\n   \n Implicit Arguments finsplit_rv_swap [n m].\n\n   \n\nLemma fin_inr_inr (n x y : nat) (i : Fin y) :\n  JMeq (fin_inr n (x + y) (fin_inr x y i)) (fin_inr (n + x) y i).\n Proof.\n  intros n x y i; induction n; simpl; auto.\n  apply (dp_rwt Fin (fun (a : nat) (fa : Fin a) => \n        JMeq (fs fa) (fs (fin_inr (n + x) y i)))\n       (sym_equal (plus_assoc n x y)) (sym_JMeq IHn) ); trivial.\n Qed.\n\nLemma fin_inl_inrN (n m x z y : nat) (H : m + x = z + y) (i : Fin n ) (j : Fin y) \n  :  JMeq (fin_inl n (m + x) i) (fin_inr (n + z) y j) -> False .\n Proof.\n  intros n m x z y H; rewrite H.\n  clear H; intros .\n  induction i; simpl in *.\n  generalize (JMeq_eq (eq_subs (fun x : nat => JMeq (fz x) \n       (fs (fin_inr (n + z) y j))) (plus_assoc n z y) H));\n  clear H; intro H.\n  discriminate H .\n  apply (IHi (Jmeq_fsInject (plus_assoc n z y) H )).\n Qed.\n  \n Lemma fin_inr_inrPlus  (n x y a b: nat) (H : x + y  = a + b) (i : Fin (x + y))\n  (j : Fin b) :  (JMeq i (fin_inr a b j) -> False) ->  \n     JMeq (fin_inr n (x + y) i) (fin_inr (n + a) b j) -> False.\n Proof.\n  intros n x y a b H; rewrite H.\n  clear H; intros i j H.\n  induction n; simpl in *; trivial. \n  apply (fun A => IHn (Jmeq_fsInject (plus_assoc n a b) A )).\n Qed. \n\n  Lemma finl_inl_inlx  (x z w : nat) (i : Fin x) :  \n  JMeq (fin_inl x (z + w) i) (fin_inl (x + z) w (fin_inl x z i)).\nProof.\n  intros; induction i;  simpl.\n  apply (eq_subs (fun x => JMeq (fz x) (fz (n + z + w))) (plus_assoc_reverse n z w) ); trivial.\n  apply (fin_fs  (plus_assoc_reverse n z w) IHi ).\nQed.\n\n Lemma fin_inl_JM (n m x : nat)(H : n = m ) (i : Fin n) (j : Fin m) :  \n   JMeq (fin_inl n x i)(fin_inl m x j) -> JMeq i j.\n Proof.\n  intros n m x  H; case H.\n  intros i j h; rewrite (fin_inl_inject x i j (JMeq_eq h)); trivial.\n Qed.\n\nLemma fin_inr_inlJm (x y z : nat) (i : Fin y) :\n   JMeq (fin_inr x (y + z) (fin_inl y z i)) (fin_inl (x + y) z (fin_inr x y  i)).\n Proof.\n  induction x; simpl.\n  intros; trivial.\n   intros y z i.\n  apply (fin_fs (plus_assoc_reverse x y z) (IHx y z i)).\nQed.\n\n Lemma fin_inl_inl_inr1 (x y k z w : nat) (H: y = k)  (i : Fin x ) (j : Fin k) :\n   JMeq (fin_inl (x + (y + z)) w (fin_inl x (y + z) i))\n        (fin_inl (x + k) (z + w) (fin_inr x k j)) -> False.\n  Proof. \n  intros x y k z w H; case H.\n  intros. induction x. inversion i.\n  destruct i using FinSn_rect.\n  simpl in *.\n  apply (IHx i (Jmeq_fsInject\n        (trans_equal\n        ( trans_equal (plus_assoc_reverse x (y + z) w ) \n          (sym_equal (f_equal (plus x) (plus_assoc y z w))))\n        (plus_assoc x y (z + w) )) H0)).\n   simpl in H0.\n    set (R := JMeq_eq (eq_subs (fun k : nat  => JMeq (fz k ) \n                 (fs (fin_inl (x + y) (z + w) (fin_inr x y j)))) \n       (trans_equal\n        ( trans_equal (plus_assoc_reverse x (y + z) w )\n          (sym_equal (f_equal (plus x) (plus_assoc y z w))))\n        (plus_assoc x y (z + w))) H0 )).\n  discriminate R.\n  Qed.\n\n Lemma fin_inl_inr_lr (x y k w z : nat) (H : z = k + w) (i : Fin z ) (j : Fin x) :\n   JMeq (fin_inr x (y + z ) (fin_inr y z i))\n        (fin_inl (x + (y + k)) w (fin_inl x (y + k) j)) -> False.\n Proof.\n  intros x y k w z H; try rewrite  H.   intros.\n  induction j; simpl in *.\n  set (R := JMeq_eq (eq_subs (fun p : nat =>  \n      JMeq (fs (fin_inr n (y + (k + w)) (fin_inr y (k + w) i))) (fz p))\n    ( trans_equal (plus_assoc_reverse n (y + k) w ) \n         (f_equal (plus n) (plus_assoc_reverse y k w))) H0 ));\n     discriminate R.\n  apply (IHj (Jmeq_fsInject\n         (sym_equal (trans_equal (plus_assoc_reverse n (y + k) w ) \n        (f_equal (plus n) (plus_assoc_reverse y k w))))  H0 )).\n Qed.\n\n Lemma fin_inl_inrJm (x y z : nat) (i : Fin y) :\n   JMeq (fin_inl (x + y) z (fin_inr x y i)) (fin_inr x (y + z) (fin_inl y z i)).\n Proof.\n  induction x; simpl; auto.\n   intros y z i;  apply (fin_fs (plus_assoc x y z) (IHx y z i)).\nQed.\n\nLemma fin_inrJm (x n m : nat) (H : n = m) (i : Fin n) (j : Fin m) :\n  JMeq (fin_inr x n i) (fin_inr x m j) -> JMeq i j.\nProof.\n  intros x n m H; case H.\n  intros i j h; case (fin_inr_inject x i j (JMeq_eq h)); trivial.\nQed.\n\nLemma fin_inlJm (x n m : nat) (H : n = m) (i : Fin n) (j : Fin m) :\n  JMeq (fin_inl n x i) (fin_inl m x j) -> JMeq i j.\nProof.\n  intros x n m H; case H.\n  intros i j h;  case (fin_inl_inject x i j (JMeq_eq h)); trivial.\nQed.\n\nLemma Jmeq_fin_inl_inr3 (x z k Y : nat) (H : Y = z + k) (i : Fin Y ) (j : Fin x ) :\n   JMeq (fin_inr x Y i) (fin_inl (x + z) k (fin_inl x z j)) -> False.\nProof.  \n intros x z k Y H; try rewrite H.\n intros.\n induction j; simpl in *.\n set (P := JMeq_eq (eq_subs (fun q : nat => JMeq (fs (fin_inr n (z + k) i)) (fz q))\n         (plus_assoc_reverse  n z k) H0 )); discriminate P.\n apply (IHj (Jmeq_fsInject (plus_assoc  n z k) H0 ))  .\n Qed.\n\nLemma Jmeq_fin_inr (z y x : nat) (H : y = x) (j : Fin x) (i : Fin y) :\n   JMeq (fin_inr z x j) (fin_inr z y i) -> JMeq i j.\nProof.\n intros z y x H; case H; clear H.\n intros j i H; case (fin_inr_inject z j i (JMeq_eq H) ); trivial.\nQed.\n\nLemma fin_inl_inrZ1 ( n z y A : nat) (H : A = z + y)  (i : Fin n) (j : Fin y): \n       JMeq (fin_inl n A i) (fin_inr (n + z) y j) -> False.\nProof.\n intros n z y A H; rewrite  H.\n intros; clear H. \n induction i; simpl in *.\n  set (P := JMeq_eq (eq_subs (fun a => JMeq (fz a) (fs (fin_inr (n + z) y j)) )\n              (plus_assoc n z y) H0)); discriminate P.\n  apply (IHi (Jmeq_fsInject  (plus_assoc n z y) H0 )).\nQed.\n\nEnd JMeq_fin_inl_or_inr.\n\n\nSection ZipMaps.\n\n \n Definition ziP (n m : nat) : Fin (n + m) -> Fin n + Fin m.\n    induction n. simpl.\n    exact (fun _ i => inr _ i).\n    intros m h. destruct m.\n     destruct (finsplit _ _ h).\n    exact (inl _ i). exact (inr _ j).\n    destruct (finsplit _ _ h).\n    destruct (finSN i).\n    exact (inl _ (fz _ )).\n    destruct i.\n    exact (inr _ (fz _ )). \n    destruct (IHn _ (fin_inl m (fs i))).\n    exact (inl _ (fs (fs i))). \n    exact (inr _ (fs f)).\n    destruct (finEmtp j).\n    exact (inr _ (tp _ )).\n    destruct i. \n    exact (inl _ (tp _ )).\n    destruct (IHn _ (fin_inr n i)).\n    exact (inl _ (emb f)).\n    exact (inr _ (fs (emb f))).\n Defined.\n    \n\n(* Eval compute in  ((ziP 2 3)  (fz 4)). *)\n\nEnd ZipMaps.\n\nSection Exponential.\n  (** * Exponential of Finite Types  *)\n\n  Fixpoint eXP (n m : nat) {struct n}:=\n    match n,m with\n    | O, m => 1\n    | S n', m => m  * (eXP n' m)\n    end. \n  Notation \"m -^ n\" := (eXP n m) (at level 14).\n\n Fixpoint finex (n m : nat) {struct n}: (Fin n -> Fin m) -> Fin (m -^ n) :=\n  match n as e return ((Fin e -> Fin m) -> Fin (m -^ e)) with\n  | O => fun _ => (fz 0)  \n  | S n' => fun f =>\n           fpair (f (fz n')) (finex (fun i => f (fs i)))\n  end.\n\n Inductive FunView (n m : nat)  : Fin (m -^ n) -> Set := \n   lam : forall f : Fin n -> Fin m, FunView n m (finex f).\n \n Definition funView : forall n m i, FunView n m i.\n    induction n; simpl.\n    intros n  i; destruct (finSN i).  \n    exact (lam (nofin (Fin n))).\n    destruct (fin_0_empty i).\n    intros m i.\n    destruct (fintimes m (m -^ n) i) as [p0 ff].\n    destruct (IHn m ff) as [ g ]. \n    replace (fpair p0 (finex g)) with (finex (caseFin p0 g)).\n    exact (lam (caseFin p0 g)).\n    destruct p0; simpl;\n    repeat (rewrite (extensionality g (fun i => g i) (fun a => refl_equal (g a)));\n    trivial).\n Defined.\n  \n Definition fapp : forall (n m : nat), Fin (eXP n m) -> Fin n -> Fin m :=\n    fun n m i => match  (funView n m i) with\n                 | lam f => f\n                 end.\n     \n End Exponential.  \n\n\n (* some tactice for rewriting goals with fin *)\n\n  Ltac rewriteHyp :=\n  match goal with\n    | [ H : _ |- _ ] => rewrite H; auto; [idtac]\n  end.\n\n\n \n", "meta": {"author": "rawlep", "repo": "ArithmeticAnaysisOfPolymorphicPrograms", "sha": "1e7919ade56888a7134597e25d9fb1438e24a75b", "save_path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms", "path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms/ArithmeticAnaysisOfPolymorphicPrograms-1e7919ade56888a7134597e25d9fb1438e24a75b/FiniteTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7708055847134657}}
{"text": "Require Import Coq.Classes.RelationClasses.\nRequire Import Sets.\nRequire Import Ordinal.\n\nClass Preorder {L:Set} (leq: L->L->Prop) := {\n  preorder_reflexive :> Reflexive leq;\n  preorder_transitive :> Transitive leq;\n}.\n\nClass PartialOrder {L:Set} (leq: L->L->Prop) := {\n  po_preorder  :> Preorder leq;\n  antisymmetry :>  forall {x y}, leq x y -> leq y x -> x=y;\n}.\n\n(* I define 2 kinds of complete lattices. The first kind is easier to deal with,\nas the lub and glb operations are defined as function. However, when I have to\nprove that a set forms a complete lattice, it isn't clear how to define these\noperations as functions. Therefore, in this case I prefer the second one which\nrequires only the existence of these operations. *)\n\nClass FunctionalCompleteLattice {L:Set} (leq: L->L->Prop) := {\n  fcl_po  :> PartialOrder leq;\n  lub     :  Pow L -> L;\n  glb     :  Pow L -> L;\n  fcl_lub :  forall X: Pow L, LeastUpperBound leq (Full_set L) (lub X) X;\n  fcl_glb :  forall X: Pow L, GreatestLowerBound leq (Full_set L) (glb X) X;\n}.\n\nClass CompleteLattice {L:Set} (leq: L->L->Prop) (S: Pow L) := {\n  cl_po  :> PartialOrder leq;\n  cl_lub :  forall X: Pow L, X ⊆ S -> (exists x, x ∈ S /\\ LeastUpperBound leq S x X);\n  cl_glb :  forall X: Pow L, X ⊆ S -> (exists x, x ∈ S /\\ GreatestLowerBound leq S x X);\n}.\n\nClass CompletePrelattice {L:Set} (leq: L->L->Prop) (S:Pow L) := {\n  cpl_preorder :> Preorder leq;\n  cpl_lub      :  forall X: Pow L, X ⊆ S -> (exists x, x ∈ S /\\ LeastUpperBound leq S x X);\n  cpl_glb      :  forall X: Pow L, X ⊆ S -> (exists x, x ∈ S /\\ GreatestLowerBound leq S x X);\n}.\n\nDefinition Strict {L:Set} (leq:L->L->Prop) (x y:L) := leq x y /\\ ~leq y x.\nDefinition Equiv  {L:Set} (leq:L->L->Prop) (x y:L) := leq x y /\\ leq y x.\nDefinition Approx {L:Set} (leq:Ord->L->L->Prop) (a:Ord) (x y:L) := forall b, b<a -> leq b x y.\n\nDefinition Equiv_class {L:Set} (equiv:L->L->Prop) (x:L) := fun y => equiv x y.\n\nClass LexicographicLattice {L:Set} (sqleq:L->L->Prop) (k:Ord) (sqleqa:Ord->L->L->Prop) := {\n  ll_cl            :> FunctionalCompleteLattice sqleq;\n  ll_preorders     :> forall a, a<k -> Preorder (sqleqa a);\n  k_limit          :  Limit k;\n  sqlt_determined1: forall x y, Strict sqleq x y -> exists a, a<k /\\ Strict (sqleqa a) x y;\n  sqlt_determined2: forall x y a, a<k -> Strict (sqleqa a) x y -> Strict sqleq x y;\n  property1        : forall a x y, a<k -> sqleqa a x y -> Approx (fun b => Equiv (sqleqa b)) a x y;\n  property2        : forall x y, Approx (fun b => Equiv (sqleqa b)) k x y -> x=y;\n  property3_lub    : forall x a, Equiv (sqleqa a) (lub (Equiv_class (Equiv (sqleqa a)) x)) x;\n  property3_glb    : forall x a, Equiv (sqleqa a) (glb (Equiv_class (Equiv (sqleqa a)) x)) x;\n}.\n\nLemma Unique_lub {L:Set} {leq:L->L->Prop} (X:Pow L) {x y:L}:\n  (FunctionalCompleteLattice leq) ->\n  LeastUpperBound leq (Full_set L) x X ->\n  LeastUpperBound leq (Full_set L) y X ->\n  x = y.\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  apply antisymmetry.\n  exact (H1 y (full_intro L y) H0).\n  exact (H2 x (full_intro L x) H).\nQed.\n\nLemma Empty_set_lub {L:Set} {leq:L->L->Prop} (X:Pow L) {x:L}:\n  (FunctionalCompleteLattice leq) ->\n  LeastUpperBound leq X x (Empty_set L) ->\n  forall y, y∈X -> leq x y.\nProof.\n  intros.\n  destruct H.\n  apply (H1 y H0).\n  unfold UpperBound.\n  unfold Forall_left.\n  intros.\n  induction H2.\nQed.\n\n", "meta": {"author": "giannosch", "repo": "lexicographic-fixed-point", "sha": "b4dbb02657c8498c1b9a9baaa840799e6f621bbe", "save_path": "github-repos/coq/giannosch-lexicographic-fixed-point", "path": "github-repos/coq/giannosch-lexicographic-fixed-point/lexicographic-fixed-point-b4dbb02657c8498c1b9a9baaa840799e6f621bbe/Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7707715532204328}}
{"text": "Require Import Arith Omega.\n\nReserved Notation \"x / y == z\" (at level 40).\nInductive Div: nat -> nat -> nat -> Prop :=\n | Div0:  forall y,      y <> 0   -> Div 0 y 0\n | DivSz: forall x y z, Div x y z -> Div (x+y)   y (S z)\n | DivSy: forall x y z, Div x y z -> Div (x+z)(S y)   z\nwhere \"x / y == z\" := (Div x y z).\nHint Constructors Div.\nTheorem DivSzE: forall y x z x',\n        x / y == z -> x' = (x+y) -> x' / y == S z.\nProof. intros. rewrite H0; auto. Qed.\nTheorem DivSyE: forall y x z x',\n        x / y == z -> x' = (x+z) -> x' / (S y) == z.\nProof. intros. rewrite H0; auto. Qed.\nHint Resolve DivSzE DivSyE.\nTheorem Div0': forall y,\n        0 / (S y) == 0.\nProof. intros y. apply Div0. auto. Qed.\nHint Resolve Div0'.\nTheorem Div_xx1: forall x,\n        x <> 0 -> x / x == 1.\nProof.\n intros x H.\n destruct x.\n  elim H. reflexivity.\n  eapply DivSzE. apply Div0.\n  intros C. inversion C.\n  simpl. reflexivity.\nQed.\nTheorem Div_xx1': forall x,\n        S x / S x == 1.\nProof.\n intros x.\n apply Div_xx1.\n auto.\nQed.\nHint Resolve Div_xx1 Div_xx1'.\nTheorem Div_x0z: forall x z,\n        x / 0 == z -> False.\nProof.\n intros x z C.\n generalize (refl_equal 0).\n refine (\n match C in Div x y z\n   return y = 0 -> False with\n | Div0 y' Hy' => _\n | DivSz x' y' z' HC => _\n | DivSy x' y' z' HC => _\n end); intros Hy.\n  exact (Hy' Hy).\n induction HC.\n  exact (H Hy). apply IHHC; exact Hy. inversion Hy.\n  inversion Hy.\nQed.\nHint Resolve Div_x0z.\nTheorem Div0_a: forall y z,\n        0 / y == z -> z = 0.\nProof.\n intros.\n inversion H; subst.\n  reflexivity.\n  destruct (plus_is_O _ _ H0) as [Hx0 Hy0]. subst.\n  exact (False_ind _ (Div_x0z _ _ H1)).\n destruct (plus_is_O _ _ H0) as [Hx0 Hy0]. subst.\n reflexivity.\nQed.\nHint Resolve Div0_a.\nTheorem Div_le: forall x y z,\n        x / y == z -> z <= x.\nProof.\n intros.\n destruct y. exact (False_ind _ (Div_x0z x z H)).\n induction H.\n  omega.\n  \n  destruct y0. exact (False_ind _ (Div_x0z _ _ H)).\n  rewrite plus_comm. simpl. apply le_n_S.\n  rewrite plus_comm. apply le_plus_trans. auto.\n  \n  rewrite plus_comm. apply le_plus_trans. omega.\nQed.\nHint Resolve Div_le.\nTheorem Div_xyx_a: forall x y,\n        x <> 0 -> x / y == x -> y = 1.\nProof.\n intros x y Hx H.\n destruct y.\n  exact (False_ind _ (Div_x0z x x H)).\n destruct y. reflexivity.\n apply False_ind.\n destruct x. apply Hx. reflexivity.\n clear Hx.\n inversion H.\n  rewrite plus_comm in H1. inversion H1.\n  subst. simpl in H1. clear H1.\n  rewrite plus_comm in H0. inversion H0. clear H0. subst.\n  apply Div_le in H. apply Div_le in H3.\n  omega.\n assert (x0 = 0) by omega. clear H3. subst.\n rewrite plus_0_l in H0, H2. subst.\n apply Div0_a in H2. inversion H2.\nQed.\nHint Resolve Div_xyx_a.\nTheorem S_O: forall n, S n <> 0. Proof. auto. Qed.\nHint Resolve S_O.\nTheorem Div_xyx_a': forall x y,\n        S x / y == S x -> y = 1.\nProof. eauto. Qed.\nHint Resolve Div_xyx_a'.\n\nTheorem Div_xy0_a: forall x y,\n        x / y == 0 -> x = 0.\nProof.\n intros x y H.\n inversion H; subst.\n  reflexivity.\n  rewrite plus_0_r in H.\n  subst.\n  destruct x0. reflexivity.\n  apply False_ind.\n  clear H.\n  induction y0. eauto.\n  apply IHy0. inversion H0; subst.\n  rewrite plus_0_r in H. subst.\n  rewrite plus_0_r. exact H2.\nQed.\n\nTheorem Div_x0z_a: forall x y z,\n        x / y == z -> y <> 0.\nProof.\n intros.\n destruct y.\n  eauto.\n omega.\nQed.\nHint Resolve Div_x0z_a.\n\nTheorem Div_mult: forall y n,\n        y <> 0 -> (n*y) / y == n.\nProof.\n intros.\n induction n as [|n'].\n  simpl. constructor. exact H.\n simpl. rewrite plus_comm. constructor. exact IHn'.\nQed.\nHint Resolve Div_mult.\n\nTheorem Div_mult_a: forall x y z,\n        x / y == z -> x = z*y.\nProof.\n intros.\n induction H.\n  reflexivity.\n  simpl. omega.\n  rewrite IHDiv. ring.\nQed.\nHint Resolve Div_mult_a.\n\nTheorem Div_multE: forall x y z,\n        y <> 0 -> x = (z*y) -> x / y == z.\nProof.\n intros.\n rewrite H0.\n eauto.\nQed.\nHint Resolve Div_multE.\n\nTheorem Div_xy1_a: forall x y,\n        x / y == 1 -> x = y.\nProof.\n intros x y H.\n specialize (Div_mult_a _ _ _ H). intros Hx.\n rewrite Hx. omega.\nQed. (* 想像以上に証明が短くなった！ *)\nHint Resolve Div_xy1_a.\n\nExample Div_ex1: 12 / 6 == 2.\nProof.\n eauto.\nQed.\nExample Div_ex2: ~ 12 / 5 == 2.\nProof.\n intros C.\n specialize (Div_mult_a _ _ _ C).\n intros C2. omega.\nQed.\n\nTheorem Div_inv: forall x y z w a,\n        x / y == z -> z / w == a -> x / (y*w) == a.\nProof.\n intros.\n specialize (Div_mult_a _ _ _ H).\n specialize (Div_mult_a _ _ _ H0).\n intros. subst.\n replace (a*w*y) with (a*(y*w)).\n apply Div_mult.\n destruct y. apply False_ind. eauto.\n destruct w. apply False_ind. eauto.\n simpl. auto.\n ring.\nQed.\nHint Resolve Div_inv.\n\nTheorem Div_lt: forall x y z,\n        x < y /\\ x <> 0 -> x / y == z -> False.\nProof.\n intros.\n destruct H as [Hlt Hneq].\n specialize (Div_mult_a _ _ _ H0). intros Hmult.\n clear H0. subst.\n destruct y.\n  auto.\n destruct z.\n  simpl in Hneq. omega.\n induction z as [|z'].\n  simpl in Hlt. omega.\n apply IHz'. simpl. simpl in Hlt. omega.\n simpl. auto.\nQed.\nHint Resolve Div_lt.\n\nRequire Program.\nProgram Fixpoint div_sig (x y: nat) (Hy: y <> 0) {measure x}:\n                 {n: option nat |\n                  match n with\n                  | None   => ~ exists z, x / y == z\n                  | Some z =>             x / y == z\n                  end} :=\n match y with\n | O => None\n | S y' =>\n   match x with\n   | O => Some 0\n   | S _ =>\n     match le_gt_dec x y with\n     | left Hle =>\n       match eq_nat_dec x y with\n       | left Heq => Some 1\n       | right Hneq => None\n       end\n     | right Hgt =>\n       match div_sig (x-y) y Hy with\n       | None => None\n       | Some z => Some (S z)\n       end\n     end\n   end\n end.\nNext Obligation.\nProof.\n rewrite Heq. apply Div_xx1'.\nQed.\nNext Obligation.\nProof.\n intros Cex. destruct Cex as [z Cex].\n rename wildcard' into w.\n assert (S w < S y'). omega.\n exact (Div_lt _ _ z (conj H (S_O _)) Cex).\nQed.\nNext Obligation.\nProof.\n simpl. omega.\nQed.\nNext Obligation.\nProof.\n intros Cex. destruct Cex as [z Cex].\n rename wildcard' into w.\n assert (Hltw: S w - S y' < S w).\n  omega.\n remember (proj1_sig (\n                   (div_sig (S w - S y') (S y') Hy\n                      (div_sig_func_obligation_5 (S w) (S y') Hy\n                         div_sig y' eq_refl w eq_refl Hgt Heq_anonymous))\n )) as d. destruct d.\n inversion Heq_anonymous0.\n remember (proj2_sig (\n         (div_sig (S w - S y') (S y') Hy\n            (div_sig_func_obligation_5 (S w) (S y') Hy div_sig y'\n               eq_refl w eq_refl Hgt Heq_anonymous))\n )) as d2. clear Heqd2. rewrite <- Heqd in d2. (* やっとなんか出た！ *)\n clear Heqd. clear Heq_anonymous0.\n unfold gt in Hgt. unfold lt in Hgt.\n apply d2. clear d2. clear Heq_anonymous.\n apply le_Sn_le in Hgt. rename Hgt into Hle.\n specialize (le_plus_minus _ _ Hle). intros Rpm.\n rewrite Rpm in Cex.\n specialize (Div_mult_a _ _ _ Cex). intros Hexm.\n Lemma Div_mult_minus_ex: (forall y' w z, y' <= w -> (y' + (w - y')) / y' == z -> y' + (w - y') = z * y' -> exists z', w - y' = z' * y').\n  intros y' w z Hle Cex Hexm.\n  rewrite plus_comm in Hexm.\n  destruct Cex.\n   simpl in Hexm. destruct y. apply False_ind. auto.\n    apply False_ind. omega.\n   exists z. simpl in Hexm.\n   destruct y. apply False_ind. eauto.\n   simpl. omega.\n  rewrite plus_comm in Hexm.\n  rewrite (le_plus_minus_r _ _ Hle) in Hexm.\n  destruct z.\n   rewrite mult_0_l in Hexm.\n   destruct w. apply False_ind. omega.\n   inversion Hexm.\n  exists z. simpl in Hexm. omega.\n Qed.\n specialize ( Div_mult_minus_ex (S y') (S w) z Hle Cex Hexm). intros H.\n destruct H as [z' H].\n rewrite H.\n exists z'.\n apply Div_mult. auto.\nQed. (* やったあ！ *)\nNext Obligation.\nProof.\n (* さて最後だ *)\n rename wildcard' into w.\n remember (proj2_sig (\n         (div_sig (S w - S y') (S y') Hy\n                      (div_sig_func_obligation_5 (S w) (S y') Hy\n                         div_sig y' eq_refl w eq_refl Hgt Heq_anonymous))\n )) as HDiv. clear HeqHDiv. rewrite <- Heq_anonymous0 in HDiv.\n clear Heq_anonymous0. clear Heq_anonymous. clear Hy.\n unfold gt, lt in Hgt. apply le_Sn_le in Hgt. rename Hgt into Hle.\n rewrite (le_plus_minus _ _ Hle).\n rewrite plus_comm. constructor. exact HDiv.\nQed.\n(* やったあ！ *)\nDefinition div x y (Hy:y <> 0): option nat := proj1_sig (div_sig x y Hy).\nHint Unfold div.\nTheorem div_Div: forall x y Hy z,\n        div x y Hy = Some z -> x / y == z.\nProof.\n intros.\n unfold div in H.\n specialize (proj2_sig (div_sig x y Hy)). intros p.\n simpl in p. (* 結構時間がかかる(Qed.の時にも) *)\n rewrite H in p.\n exact p.\nQed.\nHint Resolve div_Div.\nTheorem div_Div': forall x y z,\n        div x (S y) (S_O y) = Some z -> x / S y == z.\nProof.\n eauto.\nQed.\nHint Resolve div_Div'.\nLemma plus_reg_r: forall n m p,\n      n + p = m + p -> n = m.\nProof.\n intros.\n omega.\nQed.\nTheorem DivSz_a: forall x y z,\n        Div (x+y) y (S z) -> Div x y z.\nProof.\n intros.\n destruct y. apply False_ind. eauto.\n apply Div_multE. omega.\n apply Div_mult_a in H.\n rewrite mult_succ_l in H.\n apply plus_reg_r in H.\n exact H.\nQed.\nHint Resolve DivSz_a.\nTheorem DivSy_a: forall x y z,\n        y <> 0 -> Div (x+z) (S y) z -> Div x y z.\nProof.\n intros.\n destruct y. apply False_ind. eauto. clear H.\n apply Div_multE. omega.\n apply Div_mult_a in H0.\n rewrite mult_succ_r in H0.\n apply plus_reg_r in H0.\n exact H0.\nQed.\nHint Resolve DivSy_a.\nTheorem Div_xyz_xyz'_a: forall x y z z',\n        x / y == z -> x / y == z' -> z = z'.\nProof.\n intros.\n destruct y. apply False_ind. eauto.\n generalize dependent z'.\n induction H; intros.\n  apply Div0_a in H0. subst. reflexivity.\n  inversion H0; subst.\n   symmetry in H1. destruct (plus_is_O _ _  H1). subst. omega.\n   assert (x0 = x) by omega. subst. clear H1.\n   f_equal. apply IHDiv. exact H2.\n   destruct z'.\n    apply Div_xy0_a in H0. omega.\n   f_equal. apply IHDiv.\n   apply DivSz_a in H0. exact H0.\n inversion H0; subst.\n  symmetry in H1. destruct (plus_is_O _ _ H1). subst. auto.\n  apply Div_mult_a in H. subst.\n  apply Div_mult_a in H0.\n  rewrite H0 in H1.\n  clear H1. clear H2.\n  destruct y0.\n   rewrite mult_0_r in H0. rewrite mult_1_r in H0. simpl in H0.\n   inversion H0. subst. reflexivity.\n  rewrite <- mult_succ_r in H0.\n  Lemma mult_reg: (forall n m p, n * S p = m * S p -> n = m).\n   intros.\n   generalize dependent m.\n   induction n; intros.\n    induction m.\n     reflexivity.\n    simpl in H. inversion H.\n   induction m.\n    simpl in H. inversion H.\n   f_equal. apply IHn.\n   rewrite mult_succ_l in H. rewrite mult_succ_l in H.\n   apply plus_reg_r in H. exact H.\n  Qed.\n  Hint Resolve mult_reg.\n  apply mult_reg in H0. exact H0.\n apply Div_mult_a in H. subst.\n apply Div_mult_a in H0.\n rewrite <- mult_succ_r in H0.\n apply mult_reg in H0. subst.\n reflexivity.\nQed.\nHint Resolve Div_xyz_xyz'_a.\n\nTheorem div_NotDiv: forall x y Hy z,\n        div x y Hy <> Some z -> ~ x / y == z.\n intros.\n intro. apply H.\n specialize (proj2_sig (div_sig x y Hy)). intros p.\n simpl in p.\n change (proj1_sig (div_sig x y Hy)) with (div x y Hy) in p.\n destruct (div x y Hy).\n  rewrite (Div_xyz_xyz'_a _ _ _ _ H0 p). reflexivity.\n apply False_ind. apply p. eauto.\nQed.\nHint Resolve div_NotDiv.\nTheorem div_NotDiv': forall x y z,\n        div x (S y) (S_O y) <> Some z -> ~ x / S y == z.\nProof. eauto. Qed.\nHint Resolve div_NotDiv'.\n\nExample divDiv_ex1: 18 / 6 == 3.\nProof.\n apply div_Div'.\n unfold div.\n(*\n simplしたらメモリ食いつぶして帰ってこないｗｗｗｗ\n でもcbvなら大丈夫。何故？ バグか？\n*)\n cbv.\n reflexivity.\nQed.\nExample divDiv_ex2: 153 / 9 == 17.\nProof. auto. Qed.\nExample divDiv_ex3: ~ 12 / 6 == 3.\nProof.\n apply div_NotDiv'.\n cbv. intro. inversion H.\nQed.\n", "meta": {"author": "anta0", "repo": "coq", "sha": "68ecffaec1f502cb90d7049a366cdd2b9ac76a4f", "save_path": "github-repos/coq/anta0-coq", "path": "github-repos/coq/anta0-coq/coq-68ecffaec1f502cb90d7049a366cdd2b9ac76a4f/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7707194604924298}}
{"text": "Definition lem := forall p, p \\/ ~p.\nPrint lem.\n\nDefinition frobenius := forall (A: Set)(p: A->Prop)(q: Prop),\n  (forall x: A, q \\/ p x) <-> (q \\/ forall x: A, p x).\n\nTheorem lem_to_frobenius: lem -> frobenius.\nProof.\nunfold lem, frobenius.\nfirstorder.\n(*assert (G := H q).\ndestruct G.*)\ndestruct (H q).\nleft.\nassumption.\nright.\nintro.\ndestruct (H0 x).\nelim H1.\nassumption.\nassumption.\nQed.\n\n", "meta": {"author": "Igorocky", "repo": "coq-intro-bauerandrej", "sha": "bded41981a7062293a0eb85a28fc55179659cd48", "save_path": "github-repos/coq/Igorocky-coq-intro-bauerandrej", "path": "github-repos/coq/Igorocky-coq-intro-bauerandrej/coq-intro-bauerandrej-bded41981a7062293a0eb85a28fc55179659cd48/3-The-dual-Frobenius-rule-part-1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922389, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7706287028913106}}
{"text": "(* Exercise 84 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_084 : (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.\ncon_i.\nexi_i a.\ncon_e1 (Q a).\nhyp a2.\nexi_i a.\ncon_e2 (P 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_pred084.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133531922387, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7706286925502501}}
{"text": "Require Import HoTT.\n\nSection Definitions.\n\tVariable A:Set.\n\tDefinition prod A := A->A->A.\n\tDefinition associative {A} (m : prod A) :=\n\t\tforall a b c : A, m (m a b) c = m a (m b c).\n\tDefinition commutative {A} (m : prod A) :=\n\t\tforall a b : A, m a b = m b a.\n\tDefinition neutral {A} (e:A) (m:prod A) :=\n\t\tforall a:A, (m e a = a) /\\ (m a e = a).\n\tDefinition exists_inverse {A} (m:prod A) (e:A) :=\n\t\tforall a:A, exists a', m a a' = e /\\ m a' a = e.\n\t\n\tDefinition isMonoid A (m : prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m.\n\tDefinition isCommutative_Monoid A (m : prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ commutative m.\n\tDefinition isGroup A (m:prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ exists_inverse m e.\n\tDefinition isAbelian_Group A (m:prod A) (e:A) :=\n\t\tassociative m /\\ neutral e m /\\ exists_inverse m e /\\ commutative m.\nEnd Definitions.\n\nSection Nat.\n\tFixpoint add (m:nat) : nat->nat :=\n\t\tmatch m with\n\t\t\t| O => (fun n:nat => n)\n\t\t\t| S m => (fun n:nat => S (add m n) )\n\t\tend.\n\t\t\n\t\n\t(*Addition is defined recursively on the first variable.\n\tIt also decreases on second variable: *)\n\tLemma pred_second : forall m n : nat, add m (S n) = S (add m n).\n\tProof.\n\t\tintros m n.\n\t\tinduction m.\n\t\t(*Base case*) * reflexivity.\n\t\t(*Induction step*) *\n\t\t\tsimpl.\n\t\t\trewrite IHm. reflexivity.\n\tDefined.\n\t\n\tLemma addzero : forall n : nat, add n 0 = n.\n\tProof.\n\tinduction n. reflexivity. (*Base case done*)\n\t(*Induction step:*)\n\tsimpl. rewrite IHn. reflexivity.\n\tDefined.\n\n\tLemma zeroadd : forall n : nat, add 0 n = n.\n\tProof. reflexivity. Defined.\t\n\n\tLemma add_associative : forall l m n:nat, add (add l m) n = add l (add m n).\n\t\tinduction l.\n\t\t\tinduction m.\n\t\t\t\tinduction n.\n\t\t\t\t\t(*l m n = 0*) * reflexivity.\n\t\t\t\t\t(*l = m = 0, Step n*)* reflexivity.\n\t\t\t\t\t(*l = 0, Step m *)* reflexivity.\n\t\t\t\t\t(*Step l*)*\n\t\t\t\t\t\tintros m n.\n\t\t\t\t\t\tsimpl.\n\t\t\t\t\t\tapply (ap S).\n\t\t\t\t\t\tapply IHl.\n\tDefined.\n\t\n\tLemma add_commutative : forall n m:nat, add n m = add m n.\n\t\tinduction n.\n\t\t(*Base case*) *\n\t\t\tintro m.\n\t\t\trewrite addzero. reflexivity.\n\t\t(*Induction step*) *\n\t\t\tintro m.\n\t\t\tsimpl.\n\t\t\trewrite IHn.\n\t\t\tsymmetry.\n\t\t\tapply pred_second.\n\tDefined.\n\t\n\tProposition nat_comm_monoid : isCommutative_Monoid nat add O.\n\t\tunfold isCommutative_Monoid.\n\t\tsplit.\n\t\t\t(*Associativity*) *\n\t\t\t\t\tunfold associative.\n\t\t\t\t\tapply add_associative.\n\t\t\t\t* split.\n\n\t\t\t\t\tunfold neutral.\n\t\t\t\t\tintro n.\n\t\t\t\t\tsplit.\n\t\t\t\t\t\t\tapply zeroadd. apply addzero.\n\t\t\t(*Commutativity*) \n\t\t\t\tunfold commutative.\n\t\t\t\tapply add_commutative.\n\tDefined.\n\t\t\t\n\n\n\t(*Define addition by recursion on the second variable.*)\n\tFixpoint add' (m n : nat) : nat :=\n\t\tmatch n with\n\t\t|O => m\n\t\t|S n1 => S (add' m n1)\n\tend.\n\t\n\t\n\tProposition equaladditions : forall m n:nat, add m n = add' m n.\n\t\tinduction n.\n\t\t(*Base case*) * simpl. rewrite addzero. reflexivity.\n\t\t(*Induction step*) *\n\t\t\tsimpl.\n\t\t\trewrite pred_second.\n\t\t\trewrite IHn.\n\t\t\treflexivity.\n\tDefined.\n\n\t\t\t\n\t(*Slightly different proof showing that the two additions are equal (doesn't use lemmas)*)\n\tProposition equaladditions2 : forall m n:nat, add m n = add' m n.\n\t\tinduction m.\n\t\t(*Base case m*) *\n\t\t\tinduction n.\n\t\t\t\t(*Base case n*) ** reflexivity.\n\t\t\t\t(*Induction step n*) ** \n\t\t\t\t\tsimpl.\n\t\t\t\t\trewrite <- IHn. \n\t\t\t\t\treflexivity.\n\t\t(*Induction step m*) *\n \t\t\tintro n.\n\t\t\tsimpl.\n\t\t\trewrite IHm.\n\t\t\t\tinduction n.\n\t\t\t\t\t(*Base case n*) ** reflexivity.\n\t\t\t\t\t(*Induction step n*) **\n\t\t\t\t\t\tsimpl.\n\t\t\t\t\t\trewrite IHn. reflexivity.\n\tDefined.\n\nEnd Nat.\n\n\nSection Integers.\n\tInductive Z : Set :=\n\t\t|subt (n0 n1:nat) : Z\n\t.\n\t\n\tAxiom eq_Z_1 : forall m1 m2 n1 n2 : nat, \n\t\tadd m1 n2 = add n1 m2 -> subt m1 m2 = subt n1 n2.\n\t\n\tAxiom eq_Z_2 : forall m1 m2 n1 n2 : nat, \n\t\tsubt m1 m2 = subt n1 n2 -> add m1 n2 = add n1 m2.\n\t\n\tDefinition inj (n: nat) : Z := subt n O.\n\t\n\tDefinition neg (m:Z) :=\n\t\tmatch m with\n\t\t|subt m1 m2 => subt m2 m1\n\tend.\n\t\n\tDefinition add_Z (m n : Z) : Z :=\n\t\tmatch m with\n\t\t| subt m1 m2 => match n with\n\t\t\t|subt n1 n2 => subt (add m1 n1) (add m2 n2)\n\t\tend\n\tend.\n\t\n\tDefinition subt_Z (m n: Z) : Z :=\n\t\tadd_Z m (neg n).\n\t\t\n\tProposition injection : forall m n:nat, inj m = inj n -> m = n.\n\tProof.\n\t\tunfold inj.\n\t\tintros m n p.\n \t\trewrite <- (addzero m). rewrite <- (addzero n).\n\t\tapply eq_Z_2.\n\t\tassumption.\n\tDefined.\n\t\n\t(*Abelian group axioms*)\n\tLemma add_Z_associative : forall l m n : Z, \n\t\tadd_Z (add_Z l m) n = add_Z l (add_Z m n).\n\tProof.\n\t\tinduction l.\n\t\tinduction m.\n\t\tinduction n.\n\t\tunfold add_Z.\n\t\trewrite add_associative. rewrite add_associative. reflexivity.\n\tDefined.\n\t\n\tLemma add_Z_commutative : forall m n : Z,\n\t\tadd_Z m n = add_Z n m.\n\t\tinduction m.\n\t\tinduction n.\n\t\tsimpl.\n\t\trewrite (add_commutative n2 n0). rewrite (add_commutative n3 n1). reflexivity.\n\tDefined.\n\t\t\n\tDefinition O_Z := subt O O.\n\t\n\tLemma addzero_Z : forall n : Z, add_Z n O_Z = n.\n\tProof.\n\t\tinduction n.\n\t\tunfold O_Z.\n\t\tunfold add_Z.\n\t\trewrite addzero. rewrite addzero. reflexivity.\n\tDefined.\n\tLemma zeroadd_Z : forall n : Z, add_Z O_Z n = n.\n\t\tinduction n.\n\t\tunfold O_Z.\n\t\tunfold add_Z.\n\t\trewrite zeroadd. rewrite zeroadd. reflexivity.\n\tDefined.\n\t\n\tLemma inverse_neg : forall n : Z, add_Z n (neg n) = O_Z /\\ add_Z (neg n) n = O_Z.\n\tProof.\n\t\tinduction n.\n\t\tunfold neg.\n\t\tunfold add_Z.\n\t\tunfold O_Z.\n\t\tsplit.\n\t\t*apply eq_Z_1.\n\t\trewrite addzero. rewrite zeroadd. \n\t\tapply add_commutative.\n\t\t*apply eq_Z_1.\n\t\trewrite addzero. rewrite zeroadd. \n\t\tapply add_commutative.\n\tDefined.\n\t\n\tProposition Z_abelian : isAbelian_Group Z add_Z O_Z.\n\t\tunfold isAbelian_Group.\n\t\t\n\t\tsplit.\n\t\t(*Associativity*) *\n\t\t\tunfold associative. apply add_Z_associative.\n\t\t* split.\n\t\t(*Neutral element*) **\n\t\t\tunfold neutral. intro n. split.\n\t\t\t\t***apply zeroadd_Z. ***apply addzero_Z.\n\t\t** split.\n\t\t(*Exists inverse*) ***\n\t\t\tunfold exists_inverse.\n\t\t\t\tintro n.\n\t\t\t\texists (neg n). apply inverse_neg.\n\t\t(*Commutativity*) ***\n\t\t\tunfold commutative.\n\t\t\tapply add_Z_commutative.\n\tDefined.\n\t\t\t\t\n\t\n\t\n\t\t\nEnd Integers.", "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/misc/Integers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7704786861677291}}
{"text": "Inductive True1 : Prop :=\n  | tt1 : True1.\n\nInductive False1 : Prop := .\n\nInductive conj1 (A B : Prop) : Prop :=\n  | and1 : A -> B -> conj1 A B.\n\nInductive disj1 (A B : Prop) : Prop :=\n  | or1 : A -> B -> disj1 A B.\n\nInductive bool1 : Set :=\n  | true1  : bool1\n  | false1 : bool1.\n\nRequire Import Bool.\n\nDefinition  not_bool (b : bool) : bool :=\n  match b with\n    | false => true\n    | true => false\n  end.\n\nDefinition and_bool (b1 b2 : bool) : bool := \n  match b1 , b2 with\n    | true , b2  => b2\n    | false , b2 => false\n  end.\n\nDefinition or_bool (b1 b2 : bool) : bool :=\n  match b1 , b2 with\n    | true  , b2 => true\n    | false , b2 => false\n  end.\n\nDefinition xor_bool (b1 b2 : bool) : bool :=\n  match b1 , b2 with\n    | true , false => true\n    | false , true => true\n    | b1 , b2 => false\n  end.\n\nEval compute in not_bool false.\n\nEval compute in xor_bool false true.\n\nLemma not_bool_inv : forall b : bool, not_bool (not_bool b) = b.\n  Proof.\n    intro b.\n    destruct b.\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      reflexivity.\n  Qed.\n\nLemma and_true_left : forall b, and_bool true b = b.\n  Proof.\n  intro b.\n  destruct b.\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    reflexivity.\n  Qed.\n\nLemma and_false_left : forall b, and_bool false b = false.\n  Proof.\n  intro b.\n  destruct b.\n  +\n    simpl.\n    reflexivity.\n  +\n    simpl.\n    reflexivity.\n  Qed.\n\nLemma and_com : forall b b', and_bool b b' = and_bool b' b.\n  Proof.\n  intros b b'.\n  destruct b.\n  +\n    destruct b'.\n    - \n      simpl.\n      reflexivity.\n    -\n      simpl.\n      reflexivity.\n  +\n    destruct b'.\n    - \n      simpl.\n      reflexivity.\n    -\n      simpl.\n      reflexivity.\n  Qed.\n\nLemma and_assocc : forall b1 b2 b3, and_bool b1 (and_bool b2 b3) = and_bool (and_bool b1 b2) b3.\n  Proof.\n  intros b1 b2 b3.\n  destruct b1.\n  +\n    destruct b2.\n    -\n      destruct b3.\n      *\n        simpl.\n        reflexivity.\n      *\n        simpl.\n        reflexivity.\n    -\n      destruct b3.\n      *\n        simpl.\n        reflexivity.\n      *\n        simpl.\n        reflexivity.\n  +\n    destruct b2.\n    -\n      destruct b3.\n      *\n        simpl.\n        reflexivity.\n      *\n        simpl.\n        reflexivity.\n    -\n      destruct b3.\n      *\n        simpl.\n        reflexivity.\n      *\n        simpl.\n        reflexivity.\n  Qed.\n(* \nInductive nat1 : Set :=\n| O : nat1\n| S : nat1 -> nat1.\n\nFixpoint add (n m : nat) : nat :=\n  match n with\n    | O    => m\n    | S n' => S (add n' m)\n  end. *)\n(* \nEval compute in add 1 1. *)\n(* \nNotation \"n ':+:' m\" := (add n m)(at level 40, left associativity). *)\n\nLemma zero_identity_add_left : forall n, 0 + n = n.\nProof.\n    intro n.\n    simpl.\n    reflexivity.\nQed.\n\nLemma zero_identity_add_right : forall n, n + O = n.\n  Proof.\n    intro n.\n    induction n as [ | n' IHn'].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite IHn'.\n      reflexivity.\n  Qed.\n\nLemma add_inc : forall m n, S (m + n) = m + S n.\n  Proof.\n    intros m n.\n    induction m as [ | m' IHm'].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite IHm'.\n      reflexivity.\n  Qed.\n\nLemma add_commut : forall n m, n + m = m + n.\n  Proof.\n    intros n m.\n    induction n as [| n' IHn'].\n    +\n      simpl.\n      symmetry.\n      apply zero_identity_add_right.\n    +\n      simpl.\n      rewrite IHn'. (* nessa versão tem que fazer algumas correcoes*)\n      apply add_inc.\n  Qed.\n\nLemma add_associative : forall n m p, n + (m + p) = (n + m) + p.\n    Proof.\n      intros n m p.\n      induction n as [| n' IHn'].\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite IHn'.\n        reflexivity.\n    Qed.\n\n(*\nFixpoint times (n m : nat) : nat :=\n      match n with\n      | 0    => 0\n      | S n' => m + (times n' m)\n      end.\n*)\n\nLemma one_identity_times_right : forall n, n * 1 = n.\n  Proof.\n    intro n.\n    induction n as [| n' Ihn'].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite Ihn'.\n      reflexivity.\n  Qed.\n\n\nLemma one_identity_times_left : forall n, 1 * n = n.\n  Proof.\n    intro n.\n    induction n as [| n' Ihn'].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite zero_identity_add_right.\n      reflexivity.\n  Qed.\n\nLemma zero_times_left : forall n, 0 * n = 0.\n  Proof.\n    intro n.\n    simpl.\n    reflexivity.\n  Qed.\n\nLemma zero_times_right : forall n, n * 0 = 0.\n  Proof.\n    intro n.\n    induction n as [|n' Ihn'].\n    +\n      reflexivity.\n    +\n      simpl.\n      apply Ihn'.\n  Qed.\n\nLemma add_mult_1 : forall n m p, (n + m) * p = n * p + m * p.\n  Proof.\n    intro n.\n    induction n as [| n' Ihn].\n    +\n      intros m p.\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      intros m p.\n      rewrite Ihn.\n      apply add_associative.\n  Qed.\n\n\nLemma times_associative : forall n m p, (n * m) * p = n * (m * p).\n  Proof.\n    intros n.\n    induction n as  [| n' Ihn'].\n    +\n      simpl.\n      intros m p.\n      reflexivity.\n    +\n      simpl.\n      intros m p.\n      rewrite <- Ihn'.\n      apply add_mult_1.\n  Qed.\n\nLemma add_1 : forall n m p, n + (m + p) = m + (n + p).\n  Proof.\n    intro n.\n    induction n as [|n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      intros m p.\n      simpl.\n      rewrite Ihn.\n      rewrite add_inc.\n      reflexivity.\n  Qed.\n\nLemma times_1 : forall n m, n + n * m = n * S m.\n  Proof.\n    intro n.\n    induction n as [| n' Ihn].\n    +\n      simpl.\n      intro m.\n      reflexivity.\n    +\n      simpl.\n      intro m.\n      rewrite <- Ihn.\n      rewrite add_1.\n(*       assert (n' + (m + n' * m) = m + (n' + n' * m)).\n        admit. \n      rewrite H. *)\n      reflexivity.\n  Qed.\n\nLemma times_commut : forall n m, n * m = m * n.\n  Proof.\n    intros n.\n    induction n as [| n' Ihn'].\n    +\n      simpl.\n      intro m.\n      rewrite zero_times_right.\n      reflexivity.\n    +\n      simpl.\n      intro m.\n      rewrite Ihn'.\n      apply times_1.\n  Qed.\n\n\nFixpoint even_bool (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S n => not_bool (even_bool n)\n  end.\n\nLemma even_add_n : forall n, even_bool (n + n) = true.\n  Proof.\n    intro n.\n    induction n as [|n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite add_commut.\n      simpl.\n      rewrite Ihn.\n      simpl.\n      reflexivity.\n  Qed.\n\nFixpoint odd_bool (n: nat) : bool :=\n  match n with\n    | 0 => false\n    | S n => not_bool (odd_bool n)\n  end.\n\nLemma odd_add_n_n : forall n, odd_bool (n + n) = false.\n  Proof.\n    intro n.\n    induction n as [|n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite add_commut.\n      simpl.\n      rewrite Ihn.\n      simpl.\n      reflexivity.\n  Qed.\n\nLemma odd_add_n_Sn : forall n, odd_bool (n + S n) = true.\n  Proof.\n    intro n.\n    induction n as [|n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite add_commut.\n      simpl.\n      rewrite odd_add_n_n.\n      simpl.\n      reflexivity.\n  Qed.\n\nLemma even_SS : forall n, even_bool n = even_bool (S (S n)).\n  Proof.\n    intro n.\n    induction n as [| n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite not_bool_inv.\n      reflexivity.\n  Qed.\n\nLemma odd_SS : forall n, odd_bool n = odd_bool (S (S n)).\n  Proof.\n    intro n.\n    induction n as [| n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite not_bool_inv.\n      reflexivity.\n  Qed.\n\nLemma even_bool_S : forall n, even_bool n = not_bool (even_bool (S n)).\n  Proof.\n    intro n.\n    induction n as [| n' Ihn].\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite not_bool_inv.\n      reflexivity.\n  Qed.\n\nLemma length_app\n      : forall {A : Type}(xs ys : list A), length (xs ++ ys) = length xs + length ys.\n    Proof.\n      intros A xs ys.\n      induction xs as [| z zs IHzs].\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite IHzs.\n        reflexivity.\n    Qed.\n\nLemma length_app_1\n      : forall {A : Type}(xs ys : list A), length (xs ++ ys) = length xs + length ys.\n    Proof.\n      intros A xs ys.\n      induction xs as [| z zs IHzs].\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite IHzs.\n        reflexivity.\n    Qed.\n\n(*necessario para o restante dos exercicios.*)\nRequire Import List.\n\nLemma map_length {A B : Type}{f : A -> B} : forall xs, length (map f xs) = length xs.\n    Proof.\n      intros xs.\n      induction xs as [ | y ys IHys].\n      +\n        reflexivity.\n      +\n        simpl.\n        rewrite IHys.\n        reflexivity.\n    Qed.\n\n(*reverse => rev*)\nLemma reverse_length {A : Type}: forall (xs : list A), length xs = length (rev xs).\n    Proof.\n      intros xs.\n      induction xs.\n      +\n        reflexivity.\n      +\n        simpl.\n        rewrite length_app, add_commut.\n        rewrite IHxs.\n        reflexivity.\n    Qed.\n\n(*reapeat esta com seus parametro trocados.*)\nLemma repeat_length {A : Type} : forall (n : nat)(x : A), length (repeat x n) = n. \n    Proof.\n      intro n.\n      induction n.\n      +\n        simpl.\n        intro x.\n        reflexivity.\n      +\n        intro x.\n        simpl.\n        rewrite IHn.\n        reflexivity.\n    Qed.\n\n(*[] => nil - verificar depois*)\nLemma app_nil_right {A : Type} : forall (xs : list A), xs ++ nil = xs.\n    Proof.\n    intro xs.\n    induction xs.\n    +\n      simpl.\n      reflexivity.\n    +\n      simpl.\n      rewrite IHxs.\n      reflexivity.\n   Qed.\n\nLemma app_assoc {A : Type} : \n  forall (xs ys zs : list A), xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\n    Proof.\n      intros xs.\n      induction xs.\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        intros ys zs.\n        rewrite IHxs.\n        reflexivity.\n    Qed.\n\nLemma map_app {A B : Type}{f : A -> B}\n      : forall xs ys, map f (xs ++ ys) = map f xs ++ map f ys.\n    Proof.\n      intro xs.\n      induction xs.\n      +\n        simpl.\n        reflexivity.\n      +\n        intro ys.\n        simpl.\n        rewrite IHxs.\n        reflexivity.\n    Qed.\n\n(*reverse => rev*)\n\nLemma reverse_app {A : Type}\n      : forall (xs ys : list A), rev (xs ++ ys) = rev ys ++ rev xs.\n    Proof.\n      intros xs.\n      induction xs.\n      +\n        simpl.\n        intro ys.\n        rewrite app_nil_right.\n        reflexivity.\n      +\n        intro ys.\n        simpl.\n        rewrite IHxs.\n        rewrite app_assoc.\n        reflexivity.\n   Qed.\n\nLemma reverse_inv {A : Type}\n      : forall (xs : list A), rev (rev xs) = xs.\n    Proof.\n      intro xs.\n      induction xs.\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite reverse_app.\n        simpl.\n        rewrite IHxs.\n        reflexivity.\n    Qed.\n\nInductive even : nat -> Prop :=\n| ev_zero : even 0\n| ev_ss   : forall n, even n -> even (S (S n)).\n\nDefinition double (n : nat) := 2 * n.\n\nLemma double_n : \n  forall n, n + n = 2 * n.\n    Proof.\n      intro n.\n      induction n.\n      +\n        simpl.\n        reflexivity.\n      +\n        simpl.\n        rewrite zero_identity_add_right.\n        reflexivity.\n    Qed.\n\nLemma double_even : \n  forall n, even (double n).\n    Proof.\n      unfold double.\n      intro n.\n      induction n.\n      +\n        simpl.\n        apply ev_zero.\n      +\n        simpl.\n        rewrite zero_identity_add_right.\n        rewrite add_commut.\n        simpl.\n        rewrite double_n.\n        apply ev_ss.\n        apply IHn.\n    Qed.\n\nExample teste_le : 3 <= 6.\n    Proof.\n      apply le_S.\n      apply le_S.\n      apply le_S.\n      apply le_n.\n    Qed.\n\nExample teste_le_false : 2 <= 1 -> 1 + 1 = 10.\n    Proof.\n      intros H.\n      inversion H.\n      inversion H1.\n    Qed.\n\nLemma le_0_n : forall n, 0 <= n.\n    Proof.\n      intros n.\n      induction n as [| n' IHn'].\n      +\n        apply le_n.\n      +\n        apply le_S.\n        assumption.\n    Qed.\n\nLemma le_refl : forall n, n <= n.\n  Proof.\n    intro n.\n    induction n.\n    +\n      apply le_n.\n    +\n      apply le_n.\n  Qed.\n\nLemma le_cong_S : forall n m, n <= m -> S n <= S m.\n  Proof.\n    intros n m Hnm.\n    induction Hnm.\n    +\n      apply le_refl.\n    +\n      apply le_S.\n      assumption.\n  Qed.\n\n(*não entendi essa prova.*)\nLemma le_S_cong : forall n m, S n <= S m -> n <= m.\n  Proof.\n    intros n m.\n    induction m as [| m' IHm'].\n    +\n      intros Hnm.\n      inversion Hnm.\n      -\n        apply le_refl.\n      -\n        inversion H0.\n    +\n      intros Hnm.\n      inversion Hnm.\n      -\n        subst.\n        apply le_refl.\n      -\n        subst.\n        apply le_S.\n        apply IHm'.\n        assumption.\n  Qed.\n\nLemma le_n_sm :\n  forall n m, n <= m -> n <= S m.\n    Proof.\n      intro n.\n      induction n.\n      -\n        intro m.\n        intro H0m.\n        apply le_S.\n        apply H0m.\n     -\n        intro m.\n        intro Hsmn.\n        apply le_S.\n        apply Hsmn.\n    Qed.\n\nLemma le_trans : \n  forall n m p, n <= m -> m <= p -> n <= p.\n    Proof.\n      intro n.\n      induction n.\n      +\n        intros m p.\n        intro H0m.\n        intro Hmp.\n        rewrite H0m.\n        apply Hmp.\n      +\n        intros m p.\n        intro Hsnm.\n        intro Hmp.\n        rewrite Hsnm.\n        apply Hmp.\n    Qed.\n\nLemma eq_zero_right :\n  forall n, n = 0 -> 0 = n.\n    Proof.\n      intro n.\n      induction n.\n      +\n        intro H00.\n        assumption.\n      +\n        intro Hsn0.\n        inversion Hsn0.\n    Qed.\n\nLemma eq_zero_left :\n  forall n, 0 = n -> n = 0.\n    Proof.\n      intro n.\n      induction n.\n      +\n        intro H00.\n        assumption.\n      +\n        intro Hsn0.\n        inversion Hsn0.\n    Qed.\n\n\nLemma le_zero_antisym_right :\n  forall n, n <= 0 -> 0 <= n -> n = 0.\n    Proof.\n      intro n.\n      induction n.\n      +\n        intro H001.\n        intro H002.\n        apply eq_refl.\n      +\n        intro Hsn0.\n        intro H0sn.\n        inversion Hsn0.\n   Qed.\n\nLemma le_zero_antisym_left :\n  forall n, 0 <= n -> n <= 0 -> 0 = n.\n    Proof.\n      intro n.\n      induction n.\n      +\n        intro H001.\n        intro H002.\n        apply eq_refl.\n      +\n        intro H0sn.\n        intro Hsn0.\n        inversion Hsn0.\n    Qed.\n\nLemma le_s_inject : forall n m, S n <= S m -> n <= m.\n  Proof.\n    intros n m.\n    generalize dependent n.\n    induction m.\n    +\n      intros n H.\n      inversion H.\n      -\n        apply le_n.\n      -\n        inversion H1.\n    +\n      intro n.\n      intro H.\n      inversion H.\n      -\n        apply le_n.\n      -\n        apply IHm in H1.\n        apply le_S.\n        assumption.\n    Qed.\n\nLemma le_antisym : forall n m, n <= m -> m <= n -> n = m.\n  Proof.\n    intro n.\n    induction n.\n    intro m.\n    +\n      apply le_zero_antisym_left.\n    +\n      intro p.\n      intro Hsnp.\n      intro Hpsn.\n      inversion Hsnp.\n      -\n        reflexivity.\n      -\n        f_equal.\n        apply IHn.\n        *\n          rewrite <- H0 in Hsnp.\n          apply le_s_inject.\n          assumption.\n        *\n          rewrite <- H0 in Hsnp, Hpsn.\n          apply le_s_inject.\n          assumption.\n  Qed.\n\nImport ListNotations.\n\nInductive Sorted : list nat -> Prop :=\n  | sorted_nil : Sorted []\n  | sorted_cons1 a : Sorted [a]\n  | sorted_consn a b l : Sorted (b :: l) -> a <= b -> Sorted (a :: b :: l) .\n\n\nExample test_sorted1 : Sorted [].\n  Proof.\n    apply sorted_nil.\n  Qed.\n\nExample test_sorted2 : Sorted [10].\n  Proof.\n    apply sorted_cons1.\n  Qed.\n\nExample test_sorted3 : Sorted [1 ; 3 ; 5 ].\n  Proof.\n    apply sorted_consn.\n    +\n      apply sorted_consn.\n      -\n        apply sorted_cons1.\n      -\n        apply le_S.\n        apply le_S.\n        apply le_n.\n    +\n      apply le_S.\n      apply le_S.\n      apply le_n.\n  Qed.\n\nReserved Notation \"x '<<=' y\" (at level 40, no associativity).\n\nInductive le_alt : nat -> nat -> Prop :=\n| le_alt_zero : forall n, 0 <<= n\n| le_alt_succ : forall n m, n <<= m -> S n <<= S m\nwhere \"x '<<=' y\" := (le_alt x y).\n\n Lemma le_alt_refl : forall n, n <<= n.\n    Proof.\n      intro n.\n      induction n.\n      +\n        apply le_alt_zero.\n      +\n        apply le_alt_succ.\n        apply IHn.\n    Qed.\n\nLemma le_alt_trans\n      : forall n m p, n <<= m -> m <<= p -> n <<= p.\n    Proof.\n      induction n; intros m p H1 H2.\n      +\n        apply le_alt_zero.\n      +\n        inversion H2.\n        -\n          subst.\n          inversion H1.\n        -\n          subst.\n          apply le_alt_succ.\n          apply (IHn n0 m0).\n          *\n            inversion H1.\n            assumption.\n          *\n            assumption.\n    Qed.\n\nLemma le_alt_antisymm : \n  forall n m, S n <<= S m -> n <<= m.\n  Proof.\n    induction n ; intros m H.\n    +\n      apply le_alt_zero.\n    +\n      inversion H.\n      subst.\n      assumption.\n  Qed.\n\nLemma le_alt_antisym : \n  forall n m, n <<= m -> m <<= n -> n = m.\n    Proof.\n      induction n ; intros m H1 H2.\n      +\n        inversion H2.\n        apply eq_refl.\n      +\n        inversion H1.\n        subst.\n        f_equal.\n        apply (IHn m0).\n        -\n          inversion H1.\n          assumption.\n        -\n          inversion H2.\n          assumption.\n    Qed.\nLemma le_zero :\n  forall n, 0 <= n.\n    Proof.\n    induction n ; constructor ; try assumption.\n  Qed.\n\nLemma le_alt_equiv_le : \n  forall n m, n <<= m <-> n <= m.\n    Proof.\n      induction n ; intros ; split ; intros.\n      +\n        apply le_zero.\n      +\n       constructor.\n      +\n        destruct m.\n        -\n          inversion H.\n        -\n          apply le_cong_S.\n          inversion H.\n          apply IHn in H2.\n          assumption.\n      +\n        destruct m.\n        -\n          inversion H.\n        -\n          apply le_S_cong in H.\n          constructor.\n          apply IHn in H.\n          assumption.\n    Qed.", "meta": {"author": "Baumgratz", "repo": "Coq_Learning", "sha": "c78730a96bf744496cb7bd16e2edf9da61ab4eba", "save_path": "github-repos/coq/Baumgratz-Coq_Learning", "path": "github-repos/coq/Baumgratz-Coq_Learning/Coq_Learning-c78730a96bf744496cb7bd16e2edf9da61ab4eba/tiposInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7704748264258385}}
{"text": "(**************************** Exercise: 1 star  (nandb)  *********************)\n\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\n(************************** Exercise: 1 star (andb3) ***************************)\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\n\n(************************** Exercise: 1 star (factorial) ***************************)\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n\tmatch n with\n\t\t| 0 => m\n\t\t| S n' => S (plus n' m)\n\tend.\n\n\nFixpoint mult (n m : nat) : nat :=\n\tmatch n with\n\t\t| 0 => 0\n\t\t| S n' => plus m (mult n' m)\n\tend.\n\nFixpoint factorial (n:nat) : nat :=\n    match n with\n    | 0 => 1\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\n(**************************  Exercise: 1 star (blt_nat) ***************************)\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 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\n\nDefinition blt_nat (n m : nat) : bool := \n                    (andb (negb (beq_nat n m)) (leb n m)).\n\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n\n(************************** Exercise: 1 star (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 Ha.\n  intros Hb.\n  rewrite -> Ha.\n  rewrite <- Hb.\n  reflexivity. Qed.\n\n(************************** Exercise: 2 stars (mult_S_1) ***************************)\n\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intro Ha.\n  rewrite -> Ha.\n  reflexivity.\nQed.\n\n(************************** Exercise: 2 stars (andb_true_elim2) ***************************)\n\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct b.\n   - simpl in H. assumption.\n   - simpl in H.\n   congruence.\n(************************** Exercise: 1 star (zero_nbeq_plus_1) ***************************)\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\n", "meta": {"author": "deisekelley", "repo": "Master", "sha": "28f69b362488a574138b3779f2dabb76e30ad861", "save_path": "github-repos/coq/deisekelley-Master", "path": "github-repos/coq/deisekelley-Master/Master-28f69b362488a574138b3779f2dabb76e30ad861/Exercicios_Coq/cap1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7704748248146424}}
{"text": "Require Import EqNat.\nRequire Import List.\nRequire Import Peano.\n(* syntax of propositional logic, Schoening p 4, lecture notes *)\n\nInductive atomic :=\n| A : nat -> atomic. \n\nDefinition beq_atomic (a : atomic) (b : atomic) :=\n  match a, b with\n    | A n, A m => beq_nat n m\n  end.\n\nInductive formula :=\n  | Atom : atomic -> formula \n  | Negation : formula -> formula\n  | Disjunction : formula -> formula -> formula.\n\nFixpoint beq_formula (f : formula) (g : formula) :=\n  match f, g with\n    | Atom foo, Atom bar => beq_atomic foo bar\n    | Negation foo, Negation bar => beq_formula foo bar\n    | Disjunction foo boo, Disjunction far bar => andb (beq_formula foo far) (beq_formula boo bar)\n    | _, _ => false\n  end.\n\nFixpoint get_atoms (f : formula) : list atomic :=\n  match f with\n    | Atom foo => foo::nil\n    | Negation foo => get_atoms foo\n    | Disjunction foo bar => (get_atoms foo) ++ (get_atoms bar)\n  end.\n\n(* computational definition *)\n\nFixpoint subformula (F : formula) (G : formula) : bool :=\n  (* checks whether F is a subformula of G *)\n  if beq_formula F G\n  then true\n  else match G with\n         | Atom foo => false\n         | Negation foo => subformula F foo\n         | Disjunction foo bar => orb (subformula F foo) (subformula F bar)\n       end.\n\nInductive subformulaR : formula -> formula -> Prop :=\n| R_Atom : forall a b,\n             beq_atomic a b = true -> subformulaR (Atom a) (Atom b)\n| R_Negation : forall f,\n                 subformulaR f (Negation f)\n| R_Disjunction_L : forall f g,\n                      subformulaR f (Disjunction f g)\n| R_Disjunction_R : forall f g,\n                      subformulaR g (Disjunction f g).\n\nTheorem comp_rel_subformula_eq : forall F G,\n                                   subformula F G = true <-> subformulaR F G.\nProof. \n  intros. split.\n  + intros.\n    induction G.\n    simpl in H.\n    destruct (beq_formula F (Atom a)) eqn:foo.\n    destruct F.\n    generalize foo.\n    apply R_Atom.\n    inversion H.\n    apply IHG in H.    \n    generalize H. apply R_Negation.\n\nEval simpl in get_atoms (Disjunction (Negation (Atom (A 1))) (Disjunction (Atom (A 2)) (Atom (A 3)))).\nEval simpl in subformula (Atom (A 2)) (Disjunction (Negation (Atom (A 1))) (Disjunction (Atom (A 2)) (Atom (A 3)))).\n\nExample ex1: subformula (Disjunction (Atom (A 1)) (Atom (A 2))) (Disjunction (Atom (A 3)) (Disjunction (Atom (A 1)) (Atom (A 2)))) = true.\nProof.\n simpl. reflexivity.\nQed.\n\nExample ex2 : subformulaR (Disjunction (Atom (A 2)) (Atom (A 3))) (Disjunction (Atom (A 2)) (Atom (A 3))).\n\nEval simpl in subformula (Negation (Atom (A 2))) (Disjunction (Negation (Atom (A 1))) (Disjunction (Atom (A 2)) (Atom (A 3)))).\n\n(* relational definition *)\n\nDefinition assignment := list (atomic * bool).\n\nFixpoint find_assignment (a : atomic) (assignments : assignment) : option bool :=\n  match assignments with\n    | nil => None\n    | (b, truth_value)::tail => if beq_atomic a b\n                                then Some truth_value\n                                else find_assignment a tail\n  end.\n\n(* When we define the semantics of propositional logic, we do so by saying that there exists\n   some function (which we call the assignment) of the atomic formulae, which we can expand to be\n   true for all formulae built up from the atomic formulae. The function we define here in Coq\n   works from the top-down, rather than from the bottom-up. Could we think of the informal proof\n   as being like weak induction and the formal one as being like strong induction? Or this mostly \n   just the difference between using a function vs using propositions?\n*)\n\n\nFixpoint eval_formula (phi : formula) (a : assignment) : option bool :=\n  (* for now we use the option type to handle cases when the assignment isn't ... *)\n  match phi with\n    | Atom foo => find_assignment foo a\n    | Negation foo => match (eval_formula foo a) with\n                        | None => None\n                        | Some x => Some (negb x)\n                      end\n    | Disjunction foo bar => match (eval_formula foo a) with\n                               | None => None\n                               | Some x => match (eval_formula bar a) with\n                                             | None => None\n                                             | Some y => Some (orb x y)\n                                           end\n                             end\n  end.\n\nEval simpl in eval_formula (Negation (Disjunction (Atom (A 1)) (Atom (A 2)))) \n                           (((A 1), true)::((A 2), true)::nil).\nEval simpl in eval_formula (Negation (Disjunction (Atom (A 1)) (Atom (A 2)))) \n                           (((A 1), true)::((A 2), false)::nil).\nEval simpl in eval_formula (Negation (Disjunction (Atom (A 1)) (Atom (A 2)))) \n                           (((A 1), false)::((A 2), false)::nil).\n\n(* computational models *)\nDefinition suitable1 (f : formula) (a : assignment) := eval_formula f a <> None.\n\nFixpoint suitable2 (f : formula) (a : assignment) :=\n  match a with\n    | nil => True\n    | (literal, _)::tl => (In literal (get_atoms f)) /\\ (suitable2 f tl)\n  end.\n\nDefinition models (f : formula) (a : assignment) := eval_formula f a = Some true.\n\nDefinition satisfiable (f : formula) := exists a,\n                                          suitable1 f a -> eval_formula f a = Some true.\n\nDefinition unsatisfiable (f : formula) := forall a,\n                                            suitable1 f a -> eval_formula f a = Some false.\n\nDefinition valid (f : formula) := forall a,\n                                    suitable1 f a -> eval_formula f a = Some true.\n\n(* relational models *)\n\n(* Inductive suitableR : formula -> assignment -> Prop := *)\n(* | R_Atom : forall (f : formula) (atom : atomic) (a : assignment), *)\n(*              find_assignment atom a <> None -> suitableR (Atom atom) a *)\n(* | R_Negation : forall (f : formula) (atom : atomic) (a : assignment), *)\n(*                  find_assignment atom a <> None -> suitableR f a -> suitableR (Negation f) a  *)\n(* | R_Disjunction : forall (f g : formula) (atom : atomic) (a : assignment), *)\n(*                     find_assignment atom a <> None -> suitableR f a -> suitableR g a -> suitableR (Disjunction f g) a. *)\n\n(* Inductive satisfiableR : formula -> assignment -> Prop := *)\n(* | R_Atom : forall (f : formula) (atom : atomic) (a : assignment), *)\n(*              (suitableR f a) f atom a ->  *)\n\n(* Illustrate some examples *)\n\nDefinition some_assignments : assignment := ((A 1), false)::((A 2), true)::nil.\n\nExample suitable_ex : suitable1 (Negation (Atom (A 1))) some_assignments.\nProof. compute; intros H; inversion H. Qed.\n\n(* Example suitableR_ex : suitableR (Negation (Atom (A 1))) some_assignments. *)\n(* Proof.  *)\n(*   unfold some_assignments. *)\n(*   apply R_Negation with (atom:=(A 1)). *)\n(*   compute; intros; inversion H. *)\n(*   apply R_Atom. *)\n\n\nExample models_ex : models (Negation (Atom (A 1))) some_assignments.\nProof. compute; reflexivity. Qed.\n\nExample sat_ex : satisfiable (Negation (Atom (A 1))).\nProof. unfold satisfiable; exists some_assignments; compute; reflexivity. Qed.\n\n(*Notation \"'Conjunction' A B\" := (Negation (Disjunction (Negation A) (Negation B))) (at level 85, left associativity).\nCheck (Conjunction (Atom (A 1)) (Atom (A 2))). *)\n\n(* this is a candidate problem? *)\nExample unsat_ex : unsatisfiable (Negation (Disjunction (Atom (A 1)) (Negation (Atom (A 1))))).\nProof. \n  unfold unsatisfiable.\n  unfold suitable1.\n  intros.\n  simpl. simpl in H.\n  destruct (find_assignment (A 1) a).\n  destruct b; simpl; reflexivity.\n  unfold not in H.\n  assert (H1 : False -> None = Some false).\n  + intros. inversion H0.\n  + apply H1. apply H. reflexivity.\nQed.\n\nLemma empty_assignment_not_suitable : forall F,\n                                        eval_formula F nil = None -> ~ suitable1 F nil.\nProof.\n  induction F as [|F' IHF| F' IHF];\n  try (simpl; intros; unfold not; intros; compute in H0; apply H0 in H; inversion H);\n  try (intros; unfold not; unfold suitable; unfold not; intros; apply H0 in H; inversion H).\nQed.\n\n(* Schoening, p 9 : A formula F is a tautology iff ~F is unsat *)\n(* Lemma not_unsat_sat : forall F, *)\n(*                         ~ (unsatisfiable F) -> exists a, *)\n                                                 \nLemma  suitable_invariant_negation : forall F a,\n                                       suitable1 F a <-> suitable1 (Negation F) a.\nProof. \n  intros. split.\n  + induction F; unfold suitable1; 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 suitable1; 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 subformula_atomic_reverse : forall a b,\n                                    subformulaR (Atom a) (Atom b) -> beq_atomic a b = true.\nProof. \n  intros.\n  destruct (Atom a).\n  \n\n  generalize a b.\n  induction H.\n  intros.\n  \n\n\nLemma subformula_atom_subset: forall F G,\n                                subformulaR F G -> \n                                forall a,\n                                  In a (get_atoms F) -> In a (get_atoms G).\nProof.\n  intros. induction F; induction G.\n  simpl. left. simpl in H0. inversion H0.\n  rewrite <- H1.  \n\n", "meta": {"author": "etosch", "repo": "logic", "sha": "40e1f1c26bd89fed3a814d90166995cc44568ef5", "save_path": "github-repos/coq/etosch-logic", "path": "github-repos/coq/etosch-logic/logic-40e1f1c26bd89fed3a814d90166995cc44568ef5/src/prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7704492145068794}}
{"text": "Require 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_equalanglesflip : \n   forall A B C D E F, \n   CongA A B C D E F ->\n   CongA C B A F E D.\nProof.\nintros.\nassert (nCol D E F) by (conclude lemma_equalanglesNC).\nassert (CongA D E F A B C) by (conclude lemma_equalanglessymmetric).\nassert (nCol A B C) by (conclude lemma_equalanglesNC).\nassert (~ Col C B A).\n {\n intro.\n assert (Col A B C) by (forward_using lemma_collinearorder).\n contradict.\n }\nassert (CongA C B A A B C) by (conclude lemma_ABCequalsCBA).\nassert (CongA C B A D E F) by (conclude lemma_equalanglestransitive).\nassert (CongA D E F F E D) by (conclude lemma_ABCequalsCBA).\nassert (CongA C B A F E D) by (conclude lemma_equalanglestransitive).\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_equalanglesflip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7704492139180035}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun ssrnat finset fingroup fintype bigop.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nImport Prenex Implicits.\n\nSection Lagrange.\n\nOpen Scope group_scope.\n\nVariable gT: finGroupType.\nVariable G: {group gT}.\nVariable H: {group gT}.\nHypothesis HG: H \\subset G.\n\nDefinition R := [rel x y | x * y^-1 \\in H].\n\nLemma equiv_rel_R: equivalence_rel R.\nProof.\n  rewrite /equivalence_rel=> x y z /=.\n  split.\n  - by rewrite mulgV.\n  - move=> Hxy.\n    apply /idP /idP => Htest.\n    + apply groupVr in Hxy.\n      rewrite invMg invgK in Hxy.\n      move: (groupM Hxy Htest).\n      by rewrite -mulgA [X in _ * X]mulgA mulVg mul1g.\n    + move: (groupM Hxy Htest).\n      by rewrite -mulgA [X in _ * X]mulgA mulVg mul1g.\nQed.\n\nLemma myCard_rcoset (A: {set gT}):\n  A \\in rcosets H G -> #|A| = #|H|.\nProof.\n  case /rcosetsP => x xinG ->. (* -> : x=y -> P x => P y  *)\n  by apply: card_rcoset.\nQed.\n\n\nLemma coset_equiv_class (x: gT) (xinG : x \\in G):\n  H :* x = [set y in G | R x y].\nProof.\n  apply /setP => /= y. rewrite inE.\n  apply /idP /idP.\n  - case /rcosetP => z zinH -> {y}.\n    apply /andP; split.\n    + apply/ groupM; try by [].\n      move/ subsetP: HG => HG'.\n      by rewrite HG'.\n    + rewrite invMg mulgA mulgV mul1g.\n      by apply groupVr.\n  - case/ andP => yinG xyvinH.\n    apply/ rcosetP.\n    exists (y * x^-1); last first.\n    + by rewrite -mulgA mulVg mulg1.\n    + move: xyvinH.\n      by rewrite -groupV invMg invgK.\nQed.\n\nLemma rcosets_equiv_part: rcosets H G = equivalence_partition R G.\nProof.\n\nAdmitted.\n\nEnd Lagrange.\n", "meta": {"author": "MerHS", "repo": "cinqoc", "sha": "b40a32b5b598fb401eb5213170c3401ddb82fd91", "save_path": "github-repos/coq/MerHS-cinqoc", "path": "github-repos/coq/MerHS-cinqoc/cinqoc-b40a32b5b598fb401eb5213170c3401ddb82fd91/book6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8376199673867853, "lm_q1q2_score": 0.7703109488174145}}
{"text": "Inductive day : Type :=\n| monday : day\n| tuesday : day\n| wednesday : day\n| thursday : day\n| friday : day\n| saturday : day\n| sunday : day.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n    | monday => tuesday\n    | tuesday => wednesday\n    | wednesday => thursday\n    | thursday => friday\n    | friday => monday\n    | saturday => monday\n    | sunday => monday\n  end.\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\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 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. 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\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. 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_andb34: (andb3 true true false) = false.\nProof. reflexivity. Qed.\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\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\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  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  Example test_mult1: (mult 3 3) = 9.\n  Proof. reflexivity. Qed.\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.\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. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\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\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\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.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, O + n = n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_O_l : forall n : nat, 0 * n = 0.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem plus_id_example : forall n m : nat,\n                            n = m ->\n                            n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n                             n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H1.\n  intros H2.\n  rewrite -> H1.\n  rewrite -> H2.\n  reflexivity.\nQed.\n\nTheorem mult_O_plus : forall n m : nat,\n                        (O + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_S_l : 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_O : 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_l : forall n : nat,\n                             beq_nat 0 (n + 1) = false.\nProof.\n  intros 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.\n  intros H.\n  intros b.\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 f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  destruct b.\n    reflexivity.\n    reflexivity.\nQed.\n\n\nTheorem andb_true_true :\n  forall (c:bool), andb true c = true -> c = true.\nProof.\n  intros c.\n  destruct c.\n  reflexivity.\nAbort.\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    destruct c.\n      reflexivity.\n      intros H.\n      simpl in H.\n      symmetry.\n      rewrite -> H.\n      reflexivity.\n    destruct c.\n      intros H.\n      simpl in H.\n      rewrite -> H.\n      reflexivity.\n      reflexivity.\nQed.\n\nInductive bin : Type :=\n| Z : bin\n| Twice : bin -> bin\n| STwice : bin -> bin.\n\nFixpoint bin_incr (b : bin) : bin :=\n  match b with\n    | Z => STwice Z\n    | Twice b' => STwice (b')\n    | STwice b' => Twice (bin_incr b')\n  end.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | Z => O\n    | Twice b' => 2 * (bin_to_nat b')\n    | STwice b' => 2 * (bin_to_nat b') + 1\n  end.\n\nExample test_bin_incr1 : bin_incr Z = STwice Z.\nProof. reflexivity. Qed.\nExample test_bin_incr2 : bin_incr (STwice Z) = Twice (STwice Z).\nProof. reflexivity. Qed.\nExample test_bin_incr3: bin_incr (Twice (STwice Z)) = STwice (STwice Z).\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat1 : bin_to_nat Z = O.\nProof. reflexivity. Qed.\nExample test_bin_to_nat2 : bin_to_nat (STwice Z) = 1.\nProof. reflexivity. Qed.\nExample test_bin_to_nat3 : bin_to_nat (Twice (STwice Z)) = 2.\nProof. reflexivity. Qed.\nExample test_bin_to_nat4 : bin_to_nat (STwice (STwice Z)) = 3.\nProof. reflexivity. Qed.\n", "meta": {"author": "micxjo", "repo": "sf", "sha": "a3a841e52ba88baddedea691259086520d0b85bd", "save_path": "github-repos/coq/micxjo-sf", "path": "github-repos/coq/micxjo-sf/sf-a3a841e52ba88baddedea691259086520d0b85bd/src/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8902942341267435, "lm_q1q2_score": 0.7703040150399733}}
{"text": "(** \n\n  Binary strategy, according to Bergeron, Brlek et al. \n\n  Let $n>3$ be a positive number. We associate to $n$ the half of $n$.\n*)\n \n\nRequire Import Arith NArith Pow Compatibility More_on_positive Lia.\nRequire Export Strategies.\n\nOpen Scope positive_scope.\n\n(* begin snippet BinaryStrats:: no-out *)\nDefinition half (p:positive) :=\n  match p with xH => xH\n          |    xI q | xO q =>  q\n  end.\n\nDefinition two (p:positive) := 2%positive.\n\n#[ global ] Instance Binary_strat : Strategy half.\nProof.\n  split; destruct p; unfold half; try lia.\nQed.\n\n#[ global ] Instance Two_strat : Strategy two.\nProof.\n  split;unfold two; lia.\nQed.\n(* end snippet BinaryStrats *)\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/BinaryStrat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7702901979167378}}
{"text": "(** Computing least fixed points, following the Knaster-Tarski theorem. *)\n\nFrom Coq Require Import Extraction ExtrOcamlBasic.\n\nSection KNASTER_TARSKI.\n\n(** Consider a type [A] equipped with a decidable equality [eq] and a\n    transitive ordering [le]. *)\n\nVariable A: Type.\n\nVariable eq: A -> A -> Prop.\nVariable eq_dec: forall (x y: A), {eq x y} + {~eq x y}.\n\nVariable le: A -> A -> Prop.\nHypothesis le_trans: forall x y z, le x y -> le y z -> le x z.\nHypothesis eq_le: forall x y, eq x y -> le y x.\n\n(** This is the strict order induced by [le].  We assume it is well-founded:\n    all strictly ascending chains are finite. *)\n\nDefinition gt (x y: A) := le y x /\\ ~eq y x.\n\nHypothesis gt_wf: well_founded gt.\n\n(** Let [bot] be a smallest element of [A]. *)\n\nVariable bot: A.\nHypothesis bot_smallest: forall x, le bot x.\n\nSection FIXPOINT.\n\n(** Let [F] be a monotonically increasing function from [A] to [A]. *)\n\nVariable F: A -> A.\nHypothesis F_mon: forall x y, le x y -> le (F x) (F y).\n\nLemma iterate_acc:\n  forall (x: A) (acc: Acc gt x) (PRE: le x (F x)) (NEQ: ~eq x (F x)), Acc gt (F x).\nProof.\n  intros. apply Acc_inv with x; auto. split; auto.\nDefined.\n\nLemma iterate_le:\n  forall (x: A) (PRE: le x (F x)), le (F x) (F (F x)).\nProof.\n  intros. apply F_mon. apply PRE.\nQed.\n\n(** We iterate [F] starting from a pre-fixed-point [x], that is, an [x]\n    such that [le x (F x)].  This is a structural recursion over a derivation\n    of accessibility [Acc gt x] of [x], that is, over the proof that\n    all strictly increasing sequences starting from [x] are finite.\n    This guarantees that the iteration always terminates! *)\n\nFixpoint iterate (x: A) (acc: Acc gt x) (PRE: le x (F x)) {struct acc}: A :=\n  let x' := F x in\n  match eq_dec x x' with\n  | left E => x\n  | right NE => iterate x' (iterate_acc x acc PRE NE) (iterate_le x PRE)\n  end.\n\n(** The fixed point is obtained by iterating from [bot]. *)\n\nDefinition fixpoint : A := iterate bot (gt_wf bot) (bot_smallest (F bot)).\n\n(** It is solution to the fixed point equation. *)\n\nLemma fixpoint_eq: eq fixpoint (F fixpoint).\nProof.\n  assert (REC: forall x acc PRE, eq (iterate x acc PRE) (F (iterate x acc PRE))).\n  { induction x using (well_founded_induction gt_wf). intros. destruct acc; cbn.\n    destruct (eq_dec x (F x)).\n    - auto.\n    - apply H. split; auto.\n  }\n  apply REC.\nQed.\n\n(** It is the smallest post-fixed point. *)\n\nLemma fixpoint_smallest: forall z, le (F z) z -> le fixpoint z.\nProof.\n  intros z LEz.\n  assert (REC: forall x acc PRE, le x z -> le (iterate x acc PRE) z).\n  { induction x using (well_founded_induction gt_wf). intros. destruct acc; cbn.\n    destruct (eq_dec x (F x)).\n    - auto.\n    - apply H. split; auto.\n      apply le_trans with (F z). apply F_mon; auto. apply LEz.\n  }\n  apply REC. apply bot_smallest.\nQed.\n\nEnd FIXPOINT.\n\n(** If a function [F] is pointwise below another function [G],\n    the fixed point of [F] is below that of [G]. *)\n\nSection FIXPOINT_MON.\n\nVariable F: A -> A.\nHypothesis F_mon: forall x y, le x y -> le (F x) (F y).\nVariable G: A -> A.\nHypothesis G_mon: forall x y, le x y -> le (G x) (G y).\nHypothesis F_le_G: forall x, le (F x) (G x).\n\nTheorem fixpoint_mon: le (fixpoint F F_mon) (fixpoint G G_mon).\nProof.\n  apply fixpoint_smallest. \n  eapply le_trans. apply F_le_G. apply eq_le. apply fixpoint_eq.\nQed.\n\nEnd FIXPOINT_MON.\n\nEnd KNASTER_TARSKI.\n\n(** Let's ask Coq to extract OCaml executable code from the definition of\n    [fixpoint], we see that the arguments [acc] and[PRE] disappear,\n    because their only purpose is to prove termination.\n    The extracted OCaml code is exactly the code we would have written\n    by hand! *)\n\nRecursive Extraction fixpoint.\n\n(** Result:\n<<\n(** val iterate : ('a1 -> 'a1 -> bool) -> ('a1 -> 'a1) -> 'a1 -> 'a1 **)\n\nlet rec iterate eq_dec f x =\n  let x' = f x in if eq_dec x x' then x else iterate eq_dec f x'\n\n(** val fixpoint : ('a1 -> 'a1 -> bool) -> 'a1 -> ('a1 -> 'a1) -> 'a1 **)\n\nlet fixpoint eq_dec bot f =\n  iterate eq_dec f bot\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/Fixpoints.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7702901961949054}}
{"text": "Require Export Lists.\nRequire Export Basics.\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.\nCheck cons.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint length (X:Type) (l:list X) : nat :=\n  match l with\n  | nil => 0\n  | cons h t => S (length X t)\nend.\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) : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons X h (app X t l2)\nend.\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)\nend.\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\nend.\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\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)\nend.\n\nCheck app'.\nCheck app.\n\nFixpoint length' (X:Type) (l:list X) : nat :=\n  match l with\n  | nil => 0\n  | cons h t => S (length' _ t)\nend.\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 nat))).\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\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\n\n(* 暗黙の引数*)\nFixpoint length'' {X:Type} (l:list X) : nat :=\n  match l with\n  | nil => 0\n  | cons h t => S (length'' t)\nend.\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\nFixpoint repeat (X:Type) (n : X) (count : nat) : list X :=\n  match count with\n  | O => nil\n  | S count' => cons n (repeat X n count')\nend.\n\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. simpl. 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. induction s as [| v' s'].\n  Case \"s = nil\".\n    simpl. reflexivity.\n  Case \"s = v' :: s'\".\n    simpl. rewrite -> IHs'. simpl. reflexivity.\nQed.\n\nTheorem snoc_with_append :\n  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  Case \"l1 = nil\".\n    simpl. reflexivity.\n  Case \"l1 = v' l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nImplicit Arguments 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 (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) : list (X*Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\nend.\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)\nend.\n\nCheck @combine.\n\nEval simpl in (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  | h :: t =>\n    match h with\n    | (x,y) =>\n      (x :: fst (split t), y :: snd (split t))\n    end\n  end\n.\n\nExample test_split: 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\nImplicit Arguments some [[X]].\nImplicit Arguments none [[X]].\n\nFixpoint 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'\nend.\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  | h :: _ => some h\nend.\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\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nCheck plus.\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\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 (x,y) => (f x) y end.\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. intros. compute. reflexivity. Qed.\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. intros. destruct p. compute. 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\nend.\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: filter length_is_1 [[1,2], [3], [4], [5,6,7], [], [8]] = [[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': 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]] = [[3], [4], [8]].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l:list nat) : list nat :=\n  filter (fun n => andb (evenb n) (blt_nat 7 n)) 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\nDefinition partition {X:Type} (test : X -> bool) (l : list X) : list X * list X :=\n  (filter test l, filter (fun x => negb (test x)) l).\n\nFixpoint partition' {X:Type} (test : X -> bool) (l : list X) : list X * list X :=\n  match l with\n  | [] => ([], [])\n  | h :: t => let tmp := partition' test t\n              in if test h\n              then (h :: (fst tmp), snd tmp)\n              else (fst tmp, h :: (snd tmp))\nend.\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)\nend.\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] = [[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) (x : X),\n    map f (snoc l x) = snoc (map f l) (f x). \nProof.\n  intros. induction l as [| x' l']. \n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = x' :: l'\".\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. induction l as [| x l'].\n  Case \"l = nil\".\n    simpl. reflexivity.\n  Case \"l = x :: l'\".\n    simpl. rewrite -> map_snoc. rewrite -> IHl'. reflexivity.\nQed.\n\nFixpoint flat {X:Type} (ll:list (list X)): list X :=\n  match ll with\n  | [] => []\n  | l :: tl =>\n    match l with\n    | [] => flat tl\n    | _  => l ++ flat tl\n    end\n  end\n.\n\nExample test_flat1:\n  flat [[1,1,1],[5,5,5],[4,4,4]]\n  = [1, 1, 1, 5, 5, 5, 4, 4, 4].\nProof. reflexivity. Qed.\nExample test_flat2:\n  flat [[1], [], [2,3], [4,5]]\n  = [1,2,3,4,5].\nProof. reflexivity. Qed.\n\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\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\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)\nend.\n\n(*以下のfilter'およびmap'は練習問題の解答*)\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' X test t) else filter' X test t\nend.\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)\nend.\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)\nend.\n\nCheck (fold plus).\nEval simpl in (fold plus [1,2,3,4] 0).\n\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\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.\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.\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\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.\n  intro. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\". reflexivity.\nQed.\n\nTheorem unfold_example_bad : forall m n,\n    3 + n = m -> plus3 n + 1 = m + 1.\nProof.\n  intros m n H. (*Admitted.*)\n  rewrite <- H. simpl. reflexivity.\nQed.\n\nTheorem unfold_example : forall m n,\n    3 + n = m -> plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  unfold plus3.\n  rewrite -> H.\n  reflexivity.\nQed.\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. reflexivity.\nQed.\n\nTheorem override_neq : forall {X:Type} x1 x2 k1 k2 (f:nat->X),\n    f k1 = x1 -> beq_nat k2 k1 = false -> (override f k2 x2) k1 = x1.\nProof.\n  intros X x1 x2 k1 k2 f H I.\n  unfold override.\n  rewrite -> I. rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem eq_add_s : forall (n m : nat),\n    S n = S m -> n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.\nQed.\n\nTheorem silly4 : forall (n m : nat),\n    [n] = [m] -> n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.\nQed.\n\nTheorem silly5 : forall (n m o : nat),\n    [n,m] = [o,o] -> [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 X x y z l j H G.\n  inversion H. inversion G. rewrite -> H1. reflexivity.\nQed.\n\nTheorem silly6 : forall (n : nat),\n    S n = 0 -> 2 + 2 = 5.\nProof.\n  intros n H. inversion H.\nQed.\n\nTheorem silly7 : forall (n m : nat),\n    false = true -> [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 eq1 eq2.\n  inversion eq1. \nQed.\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\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 [| n'].\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.\nQed.\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. induction n as [| n'].\n    SCase \"n = 0\". simpl. reflexivity.\n    SCase \"n = S n'\". simpl. intros contra. inversion contra.\n  Case \"m = S m'\".\n    intros n. induction n as [| n'].\n    SCase \"n = 0\". simpl. intros contra. inversion contra.\n    SCase \"n = S n'\". simpl.\n      intros H. apply eq_remove_S. apply IHm'. apply H.\nQed.\n\nTheorem length_snoc' : forall (X:Type) (v:X)\n                              (l:list X) (n:nat),\n    length l = 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.\n    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.\nQed.\n\nTheorem beq_nat_0_l : forall n,\n    true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". simpl. reflexivity.\n  Case \"n = S n'\". simpl. intros contra. inversion contra.\nQed.\n\nTheorem beq_nat_0_r : forall n,\n    true = beq_nat n 0 -> 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". simpl. reflexivity.\n  Case \"n = S n'\".\n    simpl. intros contra. inversion contra.\nQed.\n\nTheorem double_injective : forall n m,\n    double n = double m -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". inversion eq.\n  Case \"n = S n'\". intros m eq. destruct m as [| m'].\n    SCase \"m = 0\". inversion eq.\n    SCase \"m = S m'\".\n      apply eq_remove_S. apply IHn'. inversion eq. 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.\nQed.\n\nTheorem silly3' : forall (n : nat),\n    (beq_nat n 5 = true ->\n    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. 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  Case \"n = 0\".\n    destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". intro H. inversion H.\n  Case \"n = S n'\".\n    destruct m as [| m'].\n    SCase \"m = 0\". intro H. inversion H.\n    SCase \"m = S m'\".\n      intro H. (*この段階でdouble_plusとdouble_injectiveを使えばとけそう*)\n      simpl in H.\n      rewrite -> plus_comm in H. simpl in H. rewrite <- double_plus in H.\n      rewrite -> plus_comm in H. simpl in H. rewrite <- double_plus in H.\n      inversion H. apply double_injective in H1.\n      rewrite -> H1. 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    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.\nQed.\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 (beq_nat k1 k2).\n  Case \"beq_nat k1 k2 = true\". reflexivity.\n  Case \"beq_nat k1 k2 = false\". reflexivity.\nQed.\n\n(*combine_splitとsplit_combineは後でゆっくりやる*)\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 : 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  destruct e3.\n  Case \"e3 = true\". apply beq_nat_eq in Heqe3.\n    rewrite -> Heqe3. reflexivity.\n  Case \"e3 = false\".\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.\nQed.\n\nTheorem override_same : forall {X:Type} x1 k1 k2 (f : nat -> X),\n    f k1 = x1 ->\n    (override f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f eq. unfold override.\n  remember (beq_nat k1 k2). destruct b.\n  Case \"b = true\". apply beq_nat_eq in Heqb.\n    rewrite <- Heqb. symmetry in eq. apply eq.\n  Case \"b = false\". 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.\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. rewrite -> eq2.\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 eq1 eq2.\n  apply trans_eq with (m:=[c,d]). apply eq1. 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. apply eq2. apply eq1.\nQed.\n\n(*これ以上は意味不明 apply withの使い方がよくわからん*)\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  intros n m p eq1 eq2.\n  apply beq_nat_eq in eq1. apply beq_nat_eq in eq2.\nAdmitted.\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  induction l as [| x l'].\n  Case \"l = []\". unfold fold_length. simpl. reflexivity.\n  Case \"l = x :: l'\". simpl. rewrite <- IHl'.\n  unfold fold_length. simpl. reflexivity.\nQed.\n\nDefinition fold_map {X Y:Type} (f:X->Y) (l:list X) : list Y :=\n  fold (fun x ys => f x :: ys) l [].\n\nExample fold_map_test1: fold_map (fun x => evenb x) [1,2,3,4] = map (fun x => evenb x) [1,2,3,4].\nProof. reflexivity. Qed.\n\nTheorem fold_map_correct : forall {X Y:Type} (f:X->Y) l,\n    fold_map f l = map f l.\nProof.\n  induction l as [| x l'].\n  Case \"l = []\". unfold fold_map. simpl. reflexivity.\n  Case \"l = x :: l'\". simpl. rewrite <- IHl'.\n    unfold fold_map. simpl. reflexivity.\nQed.\n\nModule MumbleBaz.\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\nInductive baz : Type :=\n| x : baz -> baz\n| y : baz -> bool -> baz.\n\nEnd MumbleBaz.\n\nFixpoint forallb {X:Type} (f:X->bool) (l:list X) : bool :=\n  match l with\n  | [] => true\n  | h :: t => if f h\n              then forallb f t\n              else false\n  end.\n\nFixpoint existsb {X:Type} (f:X->bool) (l:list X) : bool :=\n  match l with\n  | [] => false\n  | h :: t => if f h\n              then true\n              else existsb f t\n  end.\n\nDefinition existsb' {X:Type} (f:X->bool) (l:list X) : bool :=\n  negb (forallb (fun x => negb (f x)) l).\n\nTheorem existsb'_correct : forall {X:Type} (f:X->bool) l,\n    existsb' f l = existsb f l.\nProof.\n  intros. induction l as [| x l'].\n  Case \"l = []\". unfold existsb'. simpl. reflexivity.\n  Case \"l = x :: l'\". unfold existsb'. simpl.\n    destruct (f x).\n    SCase \"f x = true\". simpl. reflexivity.\n    SCase \"f x = false\". simpl. rewrite <- IHl'.\n      unfold existsb'. reflexivity.\nQed.", "meta": {"author": "MountainSeal", "repo": "coq_study", "sha": "8f5c27fa4f5ed0775d60c96210d60a5ece100327", "save_path": "github-repos/coq/MountainSeal-coq_study", "path": "github-repos/coq/MountainSeal-coq_study/coq_study-8f5c27fa4f5ed0775d60c96210d60a5ece100327/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.9019206857566126, "lm_q1q2_score": 0.7701615623061868}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_onray_neq_A_B :\n\tforall A B C,\n\tOnRay A B C ->\n\tneq A B.\nProof.\n\tintros A B C.\n\tintros OnRay_AB_C.\n\n\tdestruct OnRay_AB_C as (J & _ & BetS_J_A_B).\n\n\tpose proof (lemma_betweennotequal _ _ _ BetS_J_A_B) as (neq_A_B & _).\n\n\texact neq_A_B.\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_neq_A_B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7701101192775242}}
{"text": "Module 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 (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)\nend.\n\nNotation beq_nat := Nat.eqb (compat \"8.4\").\n\nNotation leb := Nat.leb (compat \"8.4\").\n\nFixpoint beval (b : bexp) : bool :=\n match b with\n | BTrue => true\n | BFalse => false\n | BEq a1 a2 => beq_nat (aeval a1) (aeval a2)\n | BLe a1 a2 => leb (aeval a1) (aeval a2)\n | BNot b1 => negb (beval b1)\n | BAnd b1 b2 => andb (beval b1) (beval b2)\nend.\n\nFixpoint optimize_0plus (a:aexp) : aexp :=\n  match a with\n  | ANum n =>\n      ANum n\n  | APlus (ANum 0) e2 =>\n      optimize_0plus e2\n  | APlus e1 e2 =>\n      APlus (optimize_0plus e1) (optimize_0plus e2)\n  | AMinus e1 e2 =>\n      AMinus (optimize_0plus e1) (optimize_0plus e2)\n  | AMult e1 e2 =>\n      AMult (optimize_0plus e1) (optimize_0plus e2)\n  end.\n\nTheorem optimize_0plus_sound: forall a, aeval (optimize_0plus a) = aeval a.\nProof.\nintros a.\ninduction a.\nsimpl.\nreflexivity.\ndestruct a1.\ndestruct n.\nsimpl.\napply IHa2.\nsimpl.\nrewrite IHa2.\nsimpl.\nreflexivity.\nsimpl.\nsimpl in IHa1.\nrewrite IHa1.\nrewrite IHa2.\nreflexivity.\nsimpl.\nsimpl in IHa1.\nrewrite IHa1.\nrewrite IHa2.\nreflexivity.\nsimpl.\nsimpl in IHa1.\nrewrite IHa1.\nrewrite IHa2.\nreflexivity.\nsimpl.\nrewrite IHa1.\nrewrite IHa2.\nreflexivity.\nsimpl.\nrewrite IHa1.\nrewrite IHa2.\nreflexivity.\nQed.\n\nTheorem silly1 : forall ae, aeval ae = aeval ae.\nProof.\ntry reflexivity.\nQed.\n\nTheorem silly2 : forall(P : Prop), P -> P.\nProof.\nintros P HP.\ntry reflexivity.\napply HP.\nQed.\n\nLemma foo : forall n, leb 0 n = true.\nProof.\nintros.\ndestruct n;\nsimpl;\nreflexivity.\nQed.\n\nTheorem optimize_0plus_sound': forall a, aeval (optimize_0plus a) = aeval a.\nProof.\nintros a.\ninduction a;\ntry (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\nreflexivity.\ndestruct a1;\ntry (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\ndestruct n;\n      simpl; rewrite IHa2; reflexivity.\nQed.\n\n(*General form of ; : T; [T1 | T2 | ... | Tn]*)\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   | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n   | BNot b1 => BNot (optimize_0plus_b b1)\n   | BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)\n  end.\n\nTheorem optimize_0plus_b_sound:\n  forall e, beval (optimize_0plus_b e) = beval e.\nProof.\nintro e.\n  induction e;\n    try reflexivity;\n    try (simpl; rewrite 2 optimize_0plus_sound; reflexivity).\n    simpl. rewrite IHe. reflexivity.\n    simpl. rewrite IHe1. rewrite IHe2. reflexivity.\nQed.\n\nRequire Import Coq.omega.Omega.\n\nModule aevalR_first_try.\n\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum : forall (n: nat),\n      aevalR (ANum n) n\n  | E_APlus : forall (e1 e2: aexp) (n1 n2: nat),\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus: forall(e1 e2: aexp) (n1 n2: nat),\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (AMinus e1 e2) (n1 - n2)\n  | E_AMult : forall (e1 e2: aexp) (n1 n2: nat),\n      aevalR e1 n1 ->\n      aevalR e2 n2 ->\n      aevalR (AMult e1 e2) (n1 * n2).\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_Logic12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7701101119700927}}
{"text": "Require Import Setoid.\n\nSet Implicit Arguments.\n\n(** * Module [Lattice]  *)\nModule Lattice.\n  (** A set is a lattice if it has a meet and a join following the standard\n     lattice equations. *)\n  Record t (A: Type) := New {\n    Meet: A -> A -> A;\n    Join: A -> A -> A;\n\n    MeetIdempotent: forall a, Meet a a = a;\n    MeetCommutative: forall a b, Meet a b = Meet b a;\n    MeetAssociative: forall a b c, Meet (Meet a b) c = Meet a (Meet b c);\n    MeetAbsorptive: forall a b, Meet a (Join a b) = a;\n\n    JoinIdempotent: forall a, Join a a = a;\n    JoinCommutative: forall a b, Join a b = Join b a;\n    JoinAssociative: forall a b c, Join (Join a b) c = Join a (Join b c);\n    JoinAbsorptive: forall a b, Join a (Meet a b) = a}.\n\n  (** Implicit parameters used for most of the developments. *)\n  Module Type Param.\n    (** The current set. *)\n    Parameter A: Type.\n\n    (** The current lattice description. *)\n    Parameter Lattice: t A.\n  End Param.\n\n  Module Instance (P: Param).\n    Import P.\n\n    Module Definitions.\n      (** Orderering relation: less or equal. *)\n      Definition Le a b := Meet Lattice a b = a.\n    End Definitions.\n    Import Definitions.\n\n    Module Notations.\n      Infix \"/*\\\" := (Meet P.Lattice)\n        (at level 40, left associativity): lattice_scope.\n      Infix \"\\*/\" := (Join P.Lattice)\n        (at level 50, left associativity): lattice_scope.\n      Infix \"<=\" := Le : lattice_scope.\n    End Notations.\n    Import Notations.\n    Local Open Scope lattice_scope.\n\n    (** ** Lemmas about lattices. *)\n    Module Facts.\n      (** *** [a <= b] is an order. *)\n      Lemma LeReflexive: forall a, a <= a.\n        apply MeetIdempotent.\n      Qed.\n\n      Lemma LeAntiSymmetric: forall a b,\n        a <= b -> b <= a -> a = b.\n        intros a b Ha Hb.\n        unfold Le in Hb.\n        rewrite MeetCommutative in Hb.\n        congruence.\n      Qed.\n\n      Lemma LeTransitive: forall a b c,\n        a <= b -> b <= c -> a <= c.\n        intros a b c Hab Hbc.\n        unfold Le in *.\n        rewrite <- Hab at 2.\n        rewrite <- Hbc.\n        rewrite <- MeetAssociative.\n        congruence.\n      Qed.\n\n      (** *** Some properties relating the ordering and the lattice operators. *)\n      Lemma MeetJoinEq: forall a b,\n        a /*\\ b = a <-> a \\*/ b = b.\n        split; intro H; rewrite <- H.\n          rewrite JoinCommutative.\n          rewrite MeetCommutative.\n          rewrite JoinAbsorptive.\n          reflexivity.\n          rewrite MeetAbsorptive.\n          reflexivity.\n      Qed.\n\n      Lemma ConsistentMeet: forall a b,\n        a <= b <-> a /*\\ b = a.\n        tauto.\n      Qed.\n\n      Lemma ConsistentJoin: forall a b,\n        a <= b <-> a \\*/ b = b.\n        intros a b.\n        rewrite <- MeetJoinEq.\n        apply ConsistentMeet.\n      Qed.\n\n      Lemma MeetLeLeft : forall a b, a /*\\ b <= a.\n        intros a b.\n        rewrite ConsistentMeet.\n        rewrite MeetCommutative.\n        rewrite <- MeetAssociative.\n        now rewrite MeetIdempotent.\n      Qed.\n\n      Lemma MeetLeRight : forall a b, a /*\\ b <= b.\n        intros a b.\n        rewrite ConsistentMeet.\n        rewrite MeetAssociative.\n        now rewrite MeetIdempotent.\n      Qed.\n\n      Lemma JoinLeLeft : forall a b, a <= a \\*/ b.\n        intros a b.\n        rewrite ConsistentJoin.\n        rewrite <- JoinAssociative.\n        now rewrite JoinIdempotent.\n      Qed.\n\n      Lemma JoinLeRight : forall a b, b <= a \\*/ b.\n        intros a b.\n        rewrite ConsistentJoin.\n        rewrite JoinCommutative.\n        rewrite JoinAssociative.\n        now rewrite JoinIdempotent.\n      Qed.\n\n      Lemma CompareToMeetRight: forall u a b,\n        u <= a -> u <= b -> u <= a /*\\ b.\n        intros u a b Ha Hb.\n        rewrite <- (proj1 (ConsistentMeet u b)); trivial.\n        rewrite <- (proj1 (ConsistentMeet u a)); trivial.\n        rewrite MeetAssociative.\n        apply MeetLeRight.\n      Qed.\n\n      Lemma CompareToMeetLeft: forall u a b,\n        a <= u \\/ b <= u -> a /*\\ b <= u.\n        intros u a b [Ha | Hb].\n          apply LeTransitive with (b := a); trivial.\n          apply MeetLeLeft.\n\n          apply LeTransitive with (b := b); trivial.\n          apply MeetLeRight.\n      Qed.\n\n      Lemma CompareToJoinLeft: forall u a b,\n        a <= u -> b <= u -> a \\*/ b <= u.\n        intros u a b Ha Hb.\n        rewrite <- (proj1 (ConsistentJoin a u)); trivial.\n        rewrite <- (proj1 (ConsistentJoin b u)); trivial.\n        rewrite <- JoinAssociative.\n        apply JoinLeLeft.\n      Qed.\n\n      Lemma CompareToJoinRight: forall u a b,\n        u <= a \\/ u <= b -> u <= a \\*/ b.\n        intros u a b [Ha | Hb].\n          apply LeTransitive with (b := a); trivial.\n          apply JoinLeLeft.\n\n          apply LeTransitive with (b := b); trivial.\n          apply JoinLeRight.\n      Qed.\n    End Facts.\n  End Instance.\nEnd Lattice.\n", "meta": {"author": "clarus", "repo": "cybele", "sha": "1843e4a181f854717b2820085089582acdc50525", "save_path": "github-repos/coq/clarus-cybele", "path": "github-repos/coq/clarus-cybele/cybele-1843e4a181f854717b2820085089582acdc50525/test-suite/Lattice/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7701101010089452}}
{"text": "From Coq Require Import Arith.\n\nTheorem injection_example_1: forall (a b c : nat),\n  a = S b -> a = S c -> b = c.\nProof.\n  intros. rewrite H0 in H. \n  injection H as H. \n  rewrite H.  \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/Injection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7700950992198893}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\n\nSet Implicit Arguments.\n\nRequire Import Lia.\n\n(*\nInductive nat : Type :=\n| O\n| S (n : nat)\n.\n*)\n\nFixpoint sum (n: nat) : nat :=\n  match n with\n  | 0 => 0\n  | S m => n + sum m\n  end.\n\nCompute sum 100.\n\n\nTheorem sum_calc: forall n: nat, 2 * sum n = n * (n+1).\nProof.\n  induction n.\n  - simpl. auto.\n  - simpl. nia.\nQed.\n\nPrint sum_calc.\n\nCheck (eq_refl: 1 + 1 = 2).\n\nTheorem one_plus_one_is_two: 1 + 1 = 2.\nProof.\n  auto.\nQed.\n\nPrint one_plus_one_is_two.\n\n\n\n(***\n    Curry-Howard Isomorphism\n ***)\n\nInductive and (P Q : Type) : Type :=\n| conj (p: P) (q: Q)\n.\n\nNotation \"A /\\ B\" := (and A B) : type_scope.\n\nInductive or (P Q : Type) : Type :=\n| or_introl (p: P)\n| or_intror (q: Q)            \n.\n\nNotation \"A \\/ B\" := (or A B) : type_scope.\n\nInductive False : Type :=\n.\n\nInductive True : Type :=\n| I  \n.\n\n\nCheck (forall P Q : Type, P /\\ Q -> P).\n\nDefinition pq_imp_p (P Q : Type) (pq: P /\\ Q) : P :=\n  match pq with\n  | conj p q => p\n  end.\n\nCheck pq_imp_p.\n\nCheck ((forall P Q, P -> P /\\ Q) -> False).\n\nDefinition p_imp_pq_absurd (f: forall P Q, P -> P /\\ Q) : False :=\n  match (@f True False (I: True)) with\n  | conj p q => q\n  end.\n\nCheck p_imp_pq_absurd.\n\n(**\n  Constructive Math vs. Classical Math\n **)\n\nDefinition EXM_imp_DNN (EXM: forall Q: Type, Q \\/ (Q -> False))\n           (P: Type) (NNP: ((P -> False) -> False)) : P\n  :=\n    match EXM P with\n    | or_introl _ Ppf => Ppf\n    | or_intror _ NPpf => match NNP NPpf with\n                          end\n    end.\n\nCheck EXM_imp_DNN.\n\n(**\n  Dependent Types\n **)\n\nInductive List (T: Type) : Type :=\n| nil\n| cons (hd: T) (tl: List T)\n.\nArguments nil {T}.\n\n(*\nList T: the set of lists of elements of T.\n\nVecN n: the set of lists of natural numbers of length n\n\nList: Type -> Type\nVecN: Nat -> Type\n*)\n\nInductive VecN : nat -> Type :=\n| vnil : VecN 0\n| vcons (hd: nat) (n: nat) (tl: VecN n) : VecN (S n)\n.\n\nCheck (vnil).\nCheck (vcons 3 (vcons 2 vnil)).\nCheck (vcons 1 (vcons 2 (vcons 3 vnil))).\n\n  (* List Nat -> Nat *)    (* forall _:List Nat, Nat *)\n\n  (*  (n:nat) -> VecN n *) (* forall n: nat, VecN n *)\n  (*  nat -> List nat *)                                   \n\n\nInductive eq: forall A: Type, A -> A -> Type :=\n| eq_refl A (x: A) : eq x x\n.\n\nNotation \"x = y\" := (eq x y) (at level 70) : type_scope.\n\nCheck (eq_refl (cons 3 nil)).\n\n(*\nFixpoint plus (x y: nat) : nat :=\n  match x with\n  | 0 => y\n  | S x0 => S (plus x0 y)         \n  end.\n *)\n\nFixpoint proof_of_false (n:nat) : nat :=\n  match n with\n  | 0 => 0  \n  | S n0 => proof_of_false n0\n  end.\n\n(*\nx^0 + x^1 + x^2 + ...  : [0,1] -> [0,1]\n\nnat -> A\n\neq_refl 2 : 2 = 2\neq_refl (1+1) : 1+1 = 1+1\n\neq_refl 2 : 2 = 2\n*)\n\nDefinition eq_rec_r: forall (A : Type) (x : A) (y : A) (EQ: x = y) (P : A -> Type), P y -> P x :=\n  fun A x y EQ => match EQ with\n                  | eq_refl z => (fun P PF => PF)\n                  end.\n\nPrint eq_rec_r.\n\nFixpoint nat_rec_r (P: nat -> Type) (BASE: P 0) (IND: forall m, P m -> P (S m)) (n: nat) : P n :=\n  match n with\n  | 0 => BASE\n  | S m => IND m (nat_rec_r P BASE IND m)\n  end.\n\nFixpoint foo (n: nat) : 1+n = n+1 :=\n  match n with\n  | 0 => eq_refl 1\n  | S n0 => eq_rec_r (foo n0) (fun z => S z = S _) (eq_refl _)\n  end.           \n\nCheck (forall n: nat, 1 + n = n + 1).\n\nDefinition eq_x_plus_Sy: forall x y, x + S y = S (x + y) :=\n  fun x y =>\n  nat_rec_r (fun x => x + S y = S (x + y))\n            (eq_refl _)\n            (fun x0 PF => eq_rec_r PF (fun z => S z = _) (eq_refl _))\n            x.\n\n(*\n  Existential Quantification\n*)\n\nInductive ex (A : Type) (P : A -> Type) : Type :=\n| ex_intro (a : A) (pf: P a) : ex P\n.\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\nDefinition even_exists: forall n, exists m, m = n + n :=\n  fun n => ex_intro _ (n+n) (eq_refl (n+n)).\n\nDefinition case_nat: forall n, n = 0 \\/ exists m, n = S m :=\n  fun n =>\n  match n with\n  | 0 => or_introl _ (eq_refl 0)\n  | S n0 => or_intror _ (ex_intro _ n0 (eq_refl (S n0)))\n  end.\n\n\n(*\nChoice (exists f: nat -> nat, P f) : nat->nat\nforall f g: nat -> nat, P f -> P g -> forall n, f n = g n.\n *)\n\n", "meta": {"author": "snu-sf-class", "repo": "pp202202", "sha": "93b2fb4e689c6b1acc2a9d577f7f949dcc2fb070", "save_path": "github-repos/coq/snu-sf-class-pp202202", "path": "github-repos/coq/snu-sf-class-pp202202/pp202202-93b2fb4e689c6b1acc2a9d577f7f949dcc2fb070/coq_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7700510402450905}}
{"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. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12). \nProof. reflexivity. Qed.\n", "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/chapter02/exercise02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7700510342798236}}
{"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 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.\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\nExample test_negb1 :\n  (negb true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_negb2 :\n  (negb false) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb (b1 b2 : bool) : bool :=\n  match b1 with\n    | true => b2\n    | false => false\n  end.\n\nExample test_andb1 :\n  (andb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb2 :\n  (andb true false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb3 :\n  (andb false true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb4 :\n  (andb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition orb (b1 b2 : bool) : bool :=\n  match b1 with\n    | true => true\n    | false => b2\n  end.\n\nExample test_orb1 :\n  (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2 :\n  (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3 :\n  (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4 :\n  (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise nandb *)\n\nDefinition nandb (b1 b2 : bool) : bool :=\n  match b1 with\n    | true => negb b2\n    | false => true\n  end.\n\nExample test_nandb1:\n  (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb2:\n  (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb3:\n  (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb4:\n  (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1 b2 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.\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 (negb true).\nCheck negb.\nCheck andb. (* : bool -> bool -> bool *)\n\nModule Playground1.\n\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.\n\nEnd Playground1.\n\nDefinition play_minustwo (n : Playground1.nat) : Playground1.nat :=\n  match n with\n    | Playground1.O => Playground1.O\n    | Playground1.S Playground1.O => Playground1.O\n    | Playground1.S (Playground1.S n') => n'\n  end.\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\nExample test_evenb1 :\n  (evenb O) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_evenb2 :\n  (evenb (S (S (S O)))) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition oddb (n : nat) : bool :=\n  negb (evenb n).\n\nExample test_oddb1 :\n  (oddb (S O)) = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2 :\n  (oddb (S (S (S (S O))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule Playground2.\n\n  Fixpoint plus (n 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 O)) (S (S (S O)))).\n\n  Example test_plus1 :\n    plus (S (S O)) (S (S (S O))) = 5.\n  Proof. simpl. reflexivity. Qed.\n\n  Example test_plus2 :\n    plus O (S (S (S O))) = 3.\n  Proof. simpl. reflexivity. Qed.\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  Example test_mult1 :\n    mult (S (S O)) (S (S (S O))) = 6.\n  Proof. simpl. reflexivity. Qed.\n\n  Example test_mult2 :\n    mult (S (S (S (S O)))) (S O) = 4.\n  Proof. simpl. reflexivity. Qed.\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  Example test_minus1 :\n    minus (S (S (S O))) (S O) = 2.\n  Proof. simpl. reflexivity. Qed.\n\n  Example test_minus2 :\n    minus (S (S (S (S O)))) (S (S (S (S (S O))))) = 0.\n  Proof. simpl. reflexivity. Qed.\n\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => S O\n    | S power' => mult base (exp base power')\n  end.\n\nExample test_exp1 :\n  exp (S O) O = 1.\nProof. simpl. reflexivity. Qed.\n\nExample test_exp2 :\n  exp (S (S (S O))) (S (S O)) = 9.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise 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 :\n  (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2 :\n  (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\nExample test_notation1 :\n  ((3 + 3) - 1) * 2 = 10.\nProof. simpl. 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\nExample test_beq_nat1 :\n  beq_nat (S (S (S O))) (S (S (S O))) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_nat2 :\n  beq_nat O (S O) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint ble_nat (n m : nat) : bool := (* less than equal *)\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 :\n  (ble_nat 2 2) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_ble_nat2 :\n  (ble_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_ble_nat3 :\n  (ble_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise blt_nat *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  andb (ble_nat n m) (negb (beq_nat n m)).\n\nExample test_blt_nat1 :\n  (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat2 :\n  (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat3:\n  (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_0_n :\n  forall n : nat, 0 + n = n.\nProof. reflexivity. Qed.\n\n(* Exercise simpl_plus *)\n\nEval simpl in (forall n:nat, n + 0 = n).\n(* = forall n : nat, n + 0 = n *)\n(* : Prop *)\n\nEval simpl in (forall n:nat, 0 + n = n).\n(* = forall n : nat, n = n *)\n(* : Prop *)\n\nTheorem plus_0_n'' :\n  forall n : nat, 0 + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l :\n  forall n : nat, 1 + n = S n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof. intros. simpl. reflexivity. Qed.\n\nTheorem plus_id_example :\n  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_example' :\n  forall n m : nat,\n    n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(* 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.\n  intros I.\n  rewrite -> H.\n  rewrite <- I.\n  reflexivity.\nQed.\n\nTheorem mult_0_plus :\n  forall n m : nat,\n    (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_0_n.\n  reflexivity.\nQed.\n\nTheorem mult_1_plus :\n  forall n m : nat,\n    (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  rewrite -> plus_1_l.\n  simpl. reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry :\n  forall n : nat,\n    beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  simpl.\n  Admitted.\n\nTheorem plus_1_neq_0 :\n  forall n : nat,\n    beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\nTheorem negb_involutive :\n  forall b : bool,\n    negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\n(* Exercise zero_nbeq_plus_1 *)\n\nTheorem zero_nbeq_plus_1 :\n  forall n : nat,\n    beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\nRequire String.\nOpen 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,\n    andb b c = true -> b = true.\n\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H.\n    simpl.\n    reflexivity.\nQed.\n\n(* Exercise andb_true_elim2 *)\n\nTheorem andb_true_elim2 :\n  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      simpl. reflexivity.\n    SCase \"b = false\".\n      simpl. reflexivity.\nQed.\n\n(* Theorem plus_0_r_firsttry : *)\n(*   forall n : nat, *)\n(*     n + 0 = n. *)\n(* Proof. *)\n(*   intros n. *)\n(*   destruct n as [| n']. *)\n(*   simpl. reflexivity. *)\n(*   simpl. *)\n(*   Admitted. *)\n\n(* Theorem plus_0_r_secondtry : *)\n(*   forall n : nat, *)\n(*     n + 0 = n. *)\n(* Proof. *)\n(*   intros n. destruct n as [| n']. *)\n(*   Case \"n = 0\". *)\n(*     reflexivity. *)\n(*   Case \"n = S n'\". *)\n(*     simpl. Admitted. *)\n\nTheorem plus_0_r :\n  forall n : nat,\n    n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n    Case \"n = S n'\".\n      simpl. rewrite -> IHn'.\n      reflexivity.\nQed.\n\n(* Exercise basic_induction. *)\n\nTheorem mult_0_r :\n  forall n : nat,\n    n * 0 = 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'.\n    reflexivity.\nQed.\n\nTheorem plus_n_Sm :\n  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. reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_comm :\n  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. rewrite -> plus_0_r.\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. 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\n(* Exercise double_plus. *)\n\nLemma double_plus :\n  forall n : nat,\n    double n = n + n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    rewrite <- plus_n_Sm.\n    reflexivity.\nQed.\n\n(* Exercise destruct_induction. *)\n\n(* destruct と induction の違いを短く説明しなさい. *)\n\n(* destruct は全ての場合を網羅することで証明できる場合に用いる. Induction は任意の数の証明などの再帰的に証明しなければ証明できない場合に用いる. *)\n\n(*** 形式的証明と非形式的証明 ***)\n\nTheorem plus_assoc' :\n  forall n m p : nat,\n    n + (m + p) = (n + m) + p.\nProof. intros n m p. induction n as [| n']. reflexivity.\n       simpl. rewrite -> IHn'. reflexivity. Qed.\n\n", "meta": {"author": "iyahoo", "repo": "Read-Software-Foundations", "sha": "70ed428cb2bf03c0c2ea9c9572ee1cdeba0a8a54", "save_path": "github-repos/coq/iyahoo-Read-Software-Foundations", "path": "github-repos/coq/iyahoo-Read-Software-Foundations/Read-Software-Foundations-70ed428cb2bf03c0c2ea9c9572ee1cdeba0a8a54/Basics_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.7700143905574461}}
{"text": "Require Import Le.\nRequire Import Nat.\nRequire Import Compare_dec.\n\nFixpoint blt_nat (n m:nat) : bool :=\n    match n with\n    | 0 => \n        match m with\n        | 0     => false\n        | S _   => true\n        end\n    | S n'  =>\n        match m with\n        | 0     => false\n        | S m'  => blt_nat n' m'\n        end\n    end.\n\nLemma nat_dec : forall (n m:nat), {n = m} + {n <> m}.\nProof.\n    induction n as [|n IH].\n    - destruct m as [|m].\n        + left. reflexivity.\n        + right. intros H. inversion H.\n    - destruct m as [|m].\n        + right. intros H. inversion H.\n        + destruct (IH m) as [H|H].\n            { left. rewrite H. reflexivity. }\n            { right. intros H'. apply H. inversion H'. reflexivity. }\nQed.\n\nLemma plus_n_n : forall (n:nat), n + n = 2*n.\nProof.\n    destruct n as [|n].\n    - reflexivity.\n    - simpl. rewrite <- plus_n_Sm, <- plus_n_Sm, <- plus_n_O. reflexivity.\nQed.\n\n\nLemma max_lub : forall (n m p:nat), n <= p -> m <= p -> max n m <= p.\nProof.\n    intros n m p H1 H2. destruct (le_dec n m) as [H|H].\n    - rewrite max_r; assumption.\n    - rewrite max_l.\n        + assumption.\n        + apply not_le in H. unfold gt in H. unfold lt in H.\n          apply le_trans with (S m). \n            { apply le_S, le_n. }\n            { 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/cpdt/Utils/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.770000395600307}}
{"text": "Require Import Classical.\nRequire Export GeoCoq.Elements.OriginalProofs.euclidean_defs.\nRequire Export GeoCoq.Elements.OriginalProofs.general_tactics.\n\nLtac remove_double_neg :=\nrepeat\n match goal with\n H: ~ ~ ?X |- _ => apply NNPP in H\nend.\n\nSection basic_lemmas.\n\nContext `{Ax:euclidean_neutral}.\n\n\nLemma Col_or_nCol : forall A B C,\n  Col A B C \\/ nCol A B C.\nProof.\nunfold nCol, Col.\nintros.\ntauto.\nQed.\n\nLemma nCol_or_Col : forall A B C,\n  nCol A B C \\/ Col A B C.\nProof.\nunfold nCol, Col.\nintros.\ntauto.\nQed.\n\nLemma eq_or_neq : forall A B,\n eq A B \\/ neq A B.\nProof.\nintros;unfold neq;tauto.\nQed.\n\nLemma neq_or_eq : forall A B,\n neq A B \\/ eq A B.\nProof.\nintros;unfold neq;tauto.\nQed.\n\nLemma Col_nCol_False : forall A B C, nCol A B C -> Col A B C -> False.\nProof.\nunfold Col, nCol;intuition.\nQed.\n\nLemma nCol_notCol :\n forall A B C, ~ Col A B C -> nCol A B C.\nProof.\nintros.\nunfold nCol, Col, neq in *.\nintuition.\nQed.\n\nLemma not_nCol_Col : forall A B C,\n  ~ nCol A B C -> Col A B C.\nProof.\nintros.\nunfold nCol, Col, neq in *.\ntauto.\nQed.\n\nLemma nCol_not_Col : forall A B C,\n  nCol A B C -> ~ Col A B C.\nProof.\nintros.\nunfold nCol, Col, neq in *.\ntauto.\nQed.\n\nEnd basic_lemmas.\n\nHint Resolve not_nCol_Col \n nCol_not_Col nCol_notCol Col_nCol_False.\n\nHint Resolve \n Col_or_nCol nCol_or_Col eq_or_neq neq_or_eq : decidability.\n\nTactic Notation \"by\" \"cases\" \"on\" constr(t) :=\n(let H := hyp_of_type t in decompose [or] H; clear H) ||\n   let C := fresh in (assert (C:t) by (auto with decidability || unfold neq in *;tauto);\n decompose [or] C;clear C).\n\nLtac remove_not_nCol :=\nrepeat\nmatch goal with\n H: ~ nCol ?A ?B ?C |- _ => apply not_nCol_Col in H\nend.\n\nLtac forward_using thm :=\n remove_not_nCol;spliter;splits;\n match goal with\n  H: ?X |- _ => apply thm in H;spliter;assumption\n end.\n\nLtac contradict := \n (solve [eauto using Col_nCol_False]) || contradiction || (unfold nCol in *;intuition).\n\nLtac conclude t :=\n spliter;\n remove_double_neg;\n solve [unfold eq in *;mysubst;assumption |\n        eauto using t |\n        eapply t;eauto |\n        eapply t;intuition |\n        apply <- t;remove_exists;eauto  |\n        unfold neq,eq in *;intuition |\n        unfold neq,eq in *;remove_double_neg;congruence |\n        apply t;tauto\n].\n\nLtac close := solve [assumption |\n                     auto |\n                     repeat (split;auto) |\n                     unfold neq, nCol in *;try assumption;tauto |\n                     remove_exists;eauto 15 \n                    ].\n\nLtac conclude_def_aux t := (remove_double_neg;\n  (progress (unfold t);  \n   solve [remove_exists;eauto 6 | \n          remove_exists;splits;eauto  |\n          remove_exists;eauto 11 |\n          one_of_disjunct |\n          intuition\n         ])) \n || \n solve [unfold t in *;spliter;assumption |\n        unfold t in *;destruct_all;assumption |\n        unfold t in *;remove_double_neg;destruct_all;remove_exists;eauto 11  ].\n\n(** Trick to have unfold working also with definitions within typeclasses,\n thank you Pierre Courtieu *)\n\nTactic Notation \"conclude_def\" reference(x) := (conclude_def_aux x).\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/GeoCoq/Elements/OriginalProofs/euclidean_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7699452972650462}}
{"text": "Require Import Arith.\n\nFixpoint plus' (n m:nat){struct m} : nat :=\n  match m with O => n | S p => S (plus' n p) \n  end.\n\n\nLemma plus'_assoc : forall n m p, plus' n (plus' m p)= plus' (plus' n m) p.\nProof.\n intros n m p ; elim p; simpl; auto. \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/progav/SRC/plus_prim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7698908998275261}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2021 - Pset 1 *)\n\n(* Welcome to 6.822!  Read through `Pset1Signature.v` before starting here. *)\n\nRequire Import Frap Pset1Signature.\n\nModule Impl.\n  (* The first part of this assignment involves the [bool] datatype,\n   * which has the following definition.\n   * <<\n       Inductive bool :=\n       | true\n       | false.\n     >>\n   * We will define logical negation and conjunction of Boolean values,\n   * and prove some properties of these definitions.\n   *)\n\n  (* Define [Neg] so that it implements Boolean negation, which flips\n   * the truth value of a Boolean value.\n   *)\n  Definition Neg (b : bool) : bool.\n  Admitted.\n\n  (* For instance, the negation of [true] should be [false].\n   * This proof should follow from reducing both sides of the equation\n   * and observing that they are identical.\n   *)\n  Theorem Neg_true : Neg true = false.\n  Proof.\n  Admitted.\n\n  (* Negation should be involutive, meaning that if we negate\n   * any Boolean value twice, we should get the original value back.\n\n   * To prove a fact like this that holds for all Booleans, it suffices\n   * to prove the fact for both [true] and [false] by using the\n   * [cases] tactic.\n   *)\n  Theorem Neg_involutive : forall b : bool, Neg (Neg b) = b.\n  Proof.\n  Admitted.\n\n  (* Define [And] so that it implements Boolean conjunction. That is,\n   * the result value should be [true] exactly when both inputs\n   * are [true].\n   *)\n  Definition And (x y : bool) : bool.\n  Admitted.\n\n  (* Here are a couple of examples of how [And] should act on\n   * concrete inputs.\n   *)\n  Theorem And_true_true : And true true = true.\n  Proof.\n  Admitted.\n\n  Theorem And_false_true : And false true = false.\n  Proof.\n  Admitted.\n\n  (* Prove that [And] is commutative, meaning that switching the order\n   * of its arguments doesn't affect the result.\n   *)\n  Theorem And_comm : forall x y : bool, And x y = And y x.\n  Proof.\n  Admitted.\n\n  (* Prove that the conjunction of a Boolean value with [true]\n   * doesn't change that value.\n   *)\n  Theorem And_true_r : forall x : bool, And x true = x.\n  Proof.\n  Admitted.\n\n  (* In the second part of this assignment, we will work with a simple language\n   * of imperative arithmetic programs that sequentially apply operations\n   * to a natural-number-valued state.\n\n   * The [Prog] datatype defines abstract syntax trees for this language.\n   *)\n\n  Print Prog.\n\n  (* Define [run] such that [run p n] gives the final state\n   * that running the program [p] should result in, when the\n   * initial state is [n].\n   *)\n  Fixpoint run (p : Prog) (initState : nat) : nat.\n  Admitted.\n\n  Theorem run_Example1 : run Done 0 = 0.\n  Proof.\n  Admitted.\n\n  Theorem run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7.\n  Proof.\n  Admitted.\n\n  Theorem run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6.\n  Proof.\n  Admitted.\n\n  (* Define [numInstructions] to compute the number of instructions\n   * in a program, not counting [Done] as an instruction.\n   *)\n  Fixpoint numInstructions (p : Prog) : nat.\n  Admitted.\n\n  Theorem numInstructions_Example :\n    numInstructions (MulThen 5 (AddThen 2 Done)) = 2.\n  Proof.\n  Admitted.\n\n  (* Define [concatProg] such that [concatProg p1 p2] is the program\n   * that first runs [p1] and then runs [p2].\n   *)\n  Fixpoint concatProg (p1 p2 : Prog) : Prog.\n  Admitted.\n\n  Theorem concatProg_Example :\n       concatProg (AddThen 1 Done) (MulThen 2 Done)\n       = AddThen 1 (MulThen 2 Done).\n  Proof.\n  Admitted.\n\n  (* Prove that the number of instructions in the concatenation of\n   * two programs is the sum of the number of instructions in each\n   * program.\n   *)\n  Theorem concatProg_numInstructions\n    : forall (p1 p2 : Prog), numInstructions (concatProg p1 p2)\n                        = numInstructions p1 + numInstructions p2.\n  Proof.\n  Admitted.\n\n  (* Prove that running the concatenation of [p1] with [p2] is\n     equivalent to running [p1] and then running [p2] on the\n     result. *)\n  Theorem concatProg_run\n    : forall (p1 p2 : Prog) (initState : nat),\n      run (concatProg p1 p2) initState =\n      run p2 (run p1 initState).\n  Proof.\n  Admitted.\n\n  (* Read this definition and understand how division by zero is handled. *)\n  Fixpoint runPortable (p : Prog) (state : nat) : bool * nat :=\n    match p with\n    | Done => (true, state)\n    | AddThen n p => runPortable p (n+state)\n    | MulThen n p => runPortable p (n*state)\n    | DivThen n p =>\n        if n ==n 0 then (false, state) else\n        runPortable p (state/n)\n    | VidThen n p =>\n        if state ==n 0 then (false, 0) else\n        runPortable p (n/state)\n    | SetToThen n p =>\n        runPortable p n\n    end.\n  Arguments Nat.div : simpl never. (* you don't need to understand this line *)\n\n  (* Here are a few examples: *)\n\n  Definition goodProgram1 := AddThen 1 (VidThen 10 Done).\n  Example runPortable_good : forall n,\n    runPortable goodProgram1 n = (true, 10/(1+n)).\n  Proof. simplify. equality. Qed.\n\n  Definition badProgram1 := AddThen 0 (VidThen 10 Done).\n  Example runPortable_bad : let n := 0 in\n    runPortable badProgram1 n = (false, 0).\n  Proof. simplify. equality. Qed.\n\n  Definition badProgram2 := AddThen 1 (DivThen 0 Done).\n  Example runPortable_bad2 : forall n,\n    runPortable badProgram2 n = (false, 1+n).\n  Proof. simplify. equality. Qed.\n\n  (* Prove that running the concatenation [p] using [runPortable]\n     coincides with using [run], as long as [runPortable] returns\n     [true] to confirm that no divison by zero occurred. *)\n  Lemma runPortable_run : forall p s0 s1,\n    runPortable p s0 = (true, s1) -> run p s0 = s1.\n  Proof.\n  Admitted.\n\n  (* The final goal of this pset is to implement [validate : Prog -> bool]\n     such that if this function returns [true], the program would not trigger\n     division by zero regardless of what state it starts out in.  [validate] is\n     allowed to return [false] for some perfectly good programs that never cause\n     division by zero, but it must recognize as good the examples given below.  In\n     jargon, [validate] is required to be sound but not complete, but \"complete\n     enough\" for the use cases defined by the examples given here: *)\n\n  Definition goodProgram2 := AddThen 0 (MulThen 10 (AddThen 0 (DivThen 1 Done))).\n  Definition goodProgram3 := AddThen 1 (MulThen 10 (AddThen 0 (VidThen 1 Done))).\n  Definition goodProgram4 := Done.\n  Definition goodProgram5 := SetToThen 0 (DivThen 1 Done).\n  Definition goodProgram6 := SetToThen 1 (VidThen 1 Done).\n  Definition goodProgram7 := AddThen 1 (DivThen 1 (DivThen 1 (VidThen 1 Done))).\n\n  (* If you already see a way to build [validate] that meets the\n   * requirements above, _and have a plan for how to prove it correct_,\n   * feel free to just code away. Our solution uses one intermediate definition\n   * and one intermediate lemma in the soundness proof -- both of which are more\n   * sophisticated than the top-level versions given here. *)\n\n  (* If a clear plan hasn't emerged in 10 minutes (or if you get stuck later),\n   * take a look at the hints for this pset on the course web site.\n   * It is not expected that this pset is doable for everyone without the hints,\n   * and some planning is required to complete the proof successfully.\n   * In particular, repeatedly trying out different combinations of tactics\n   * and ideas from hints until something sticks can go on for arbitrarily long\n   * with little insight and no success; just guessing a solution is unlikely.\n   * Thus, we encourage you to take your time to think, look at the hints when\n   * necessary, and only jump into coding when you have some idea why it should\n   * succeed. Some may call Coq a video game, but it is not a grinding contest. *)\n\n\n  Definition validate (p : Prog) : bool.\n  Admitted.\n\n  (* Start by making sure that your solution passes the following tests, and add\n   * at least one of your own tests: *)\n\n  Example validate1 : validate goodProgram1 = true. Admitted.\n  Example validate2 : validate goodProgram2 = true. Admitted.\n  Example validate3 : validate goodProgram3 = true. Admitted.\n  Example validate4 : validate goodProgram4 = true. Admitted.\n  Example validate5 : validate goodProgram5 = true. Admitted.\n  Example validate6 : validate goodProgram6 = true. Admitted.\n  Example validate7 : validate goodProgram7 = true. Admitted.\n  Example validateb1 : validate badProgram1 = false. Admitted.\n  Example validateb2 : validate badProgram2 = false. Admitted.\n\n  (* Then, add your own example of a bad program here, and check that `validate`\n   * returns `false` on it: *)\n\n  Definition badProgram3 : Prog. Admitted.\n  Example validateb3 : validate badProgram3 = false. Admitted.\n\n\n\n  (* Finally, before diving into the Coq proof, try to convince yourself that\n   * your code is correct by applying induction by hand.  Can you describe the\n   * high-level structure of the proof?  Which cases will you have to reason\n   * about?  What do the induction hypotheses look like?  Which key lemmas do\n   * you need?  Write a short (~10-20 lines) informal proof sketch before\n   * proceeding. *)\n\n  (** Proof sketch: **)\n  (* [[Fill in your proof sketch here.]] *)\n\n  (* Now you're ready to write the proof in Coq: *)\n\n  Lemma validate_sound : forall p, validate p = true ->\n    forall s, runPortable p s = (true, run p s).\n  Admitted.\n\n  (* Here is the complete list of commands used in one possible solution:\n    - Search, for example Search (_ + 0).\n    - induct, for example induct x\n    - simplify\n    - propositional\n    - equality\n    - linear_arithmetic\n    - cases, for example cases (X ==n Y)\n    - apply, for example apply H\n    - apply in, for example apply H1 in H2 or apply somelemma in H1\n    - apply with, for example apply H1 with (x:=2)\n    - apply in with, for example apply H1 with (x:=2) in H2\n    - rewrite, for example rewrite H\n    - rewrite in, for example rewrite H1 in H2 or rewrite somelemma in H1\n    - ;, for example simplify; propositional *)\nEnd Impl.\n\n(* The following line checks that your `Impl` module implements the right\n   signature.  Make sure that it works, or the auto-grader will break!\n   If there are mismatches, coq will report them (`Signature components for\n   label … do not match`): *)\nModule ImplCorrect : Pset1Signature.S := Impl.\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/pset01_ProgramAnalysis/Pset1Implementation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7698908945085002}}
{"text": "\nRequire Export ZArith  List  Arith Bool.\n\n(* \n \nInductive month : Set :=\n| January : month | February : month | March : month\n| April : month   | May : month      | June : month\n| July : month    | August : month   | September : month\n| October : month | November : month | December : month.\n\n*)\n\n(** short form \n*)\nInductive month : Set :=\n| January | February | March     | April   | May      | June \n| July    | August   | September | October | November | December.\n\n(** Tests :\n\nCheck month_ind.\n\nCheck month_rec.\n*)\n\n\nTheorem month_equal :\nforall m:month, \n m=January \\/ m=February \\/ m=March \\/ m=April \\/ m=May \\/ m=June \\/\n m=July \\/ m=August \\/  m=September \\/ m=October \\/ m=November \\/\n m=December.\nProof.  \n destruct m; auto 12. \nQed.\n\n(** explicit use of maont_ind:\n\n*)\nTheorem month_equal' :\nforall m:month, \n m=January \\/ m=February \\/ m=March \\/ m=April \\/\n m=May \\/ m=June \\/ m=July \\/ m=August \\/ \n m=September \\/ m=October \\/ m=November \\/ m=December.\nProof.  \n intro m; pattern m; apply month_ind; auto 12.\nQed.\n\nTheorem bool_equal: forall (b:bool), b = true \\/ b = false.\nProof. \n  intros. destruct b. left. reflexivity. right. reflexivity.\nQed.\n\nDefinition month_length (leap:bool)(m:month) : nat :=\n  match m with\n  | January => 31 | February => if leap then 29 else 28\n  | March => 31   | April => 30    | May => 31  | June => 30 \n  | July => 31    | August => 31   | September => 30  \n  | October => 31 | November => 30 | December => 31\n  end.\n\n\n  \nDefinition month_length' (leap:bool) :=\n  month_rec (fun m:month => nat)\n  31 (if leap then 29 else 28) 31 30 31 30 31 31 30 31 30 31.\n\n\nDefinition month_length'' (leap:bool)(m:month) :=\n match m with\n | February => if leap then 29 else 28\n | April  | June  | September | November => 30\n | _  => 31\n end.\n\n(** Tests :\n\nCompute  (fun leap => month_length leap November).\n*)\n\nExample  length_february : month_length false February = 28.\nProof. reflexivity. Qed.\n\nInductive plane : Set := point : Z->Z->plane.\nPrint plane.\nPrint plane_ind.\nPrint plane_rec.\n(* Definition with Record *)\nReset plane.\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\nPrint abscissa.\nPrint plane.\nDefinition in_diagonal (p:plane) :=\n  Z_eq_bool (abscissa p) (ordinate p).\n\nPrint plane.\nFail Print plane_ind.\n\nInductive vehicle : Set :=\n  bicycle : nat->vehicle | motorized : nat->nat->vehicle.\n\n(** \nCheck vehicle_ind.\n*)\n\nDefinition nb_wheels (v:vehicle) : nat :=\n  match v with\n  | bicycle x => 2\n  | motorized x n => n\n  end.\n\nDefinition nb_seats (v:vehicle) : nat :=\n  match v with\n  | bicycle x => x\n  | motorized x _ => x\n  end.\nPrint vehicle_ind.\nPrint vehicle_rec.\nTheorem at_least_28 :\n forall (leap:bool)(m:month), 28 <= month_length leap m.\nProof.\n intros leap m; case m; simpl; auto with arith.\n case leap; simpl; auto with arith.\nQed.\n\nDefinition next_month (m:month) :=\n  match m with\n  |  January => February  | February => March | March => April\n  | April => May         | May => June       | June => July\n  | July => August       | August => September\n  | September => October | October => November\n  | November => December | December => January\n  end.\n\nTheorem next_august_then_july :\n forall m:month, next_month m = August -> m = July.\nProof.\n intros m; case m; simpl; intros Hnext_eq;\n    (reflexivity || discriminate Hnext_eq).\nQed.\n \n\n\n(* Simulating discriminate (just for the fun) *)\n\nTheorem not_January_eq_February' : January <> February.\nProof.\n unfold not; intros H. \n change ((fun m:month =>\n          match m with | January => True | _ => False end)\n        February).\n rewrite <- H.\n trivial.\nQed.\n\n(* Using injection *)\n\nTheorem bicycle_eq_seats :\n forall x1 y1:nat, bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intros x1 y1 H.\n injection H.\n trivial.\nQed.\n\n(* Simulating injection (for the fun) *)\n\nTheorem bicycle_eq_seats' :\n forall x1 y1:nat, bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intros x1 y1 H.\n change (nb_seats (bicycle x1) = nb_seats (bicycle y1)).\n rewrite H; reflexivity.\nQed.\n\n(* haoyang: case_eq *)\n\nTheorem next_march_shorter :\n forall (leap:bool)(m1 m2:month), next_month m1 = March ->\n   month_length leap m1 <= month_length leap m2.\nProof.\nintros. case m1. Restart.\n intros leap m1 m2 H. \n \ndestruct m1. Undo. case m1. Undo. Locate case_eq. case_eq m1. Undo.\n\n case_eq m1; try  (intro H0; rewrite H0 in H; simpl in H; discriminate H).\n  case leap ; case m2 ; simpl; auto with arith.\nQed.\n\n(* A first, detailed, proof of associativity of + *)\n\nTheorem plus_assoc :\n forall x y z:nat, (x+y)+z = x+(y+z).\nProof.\n induction x as [ | x0 IHx0].\n -  simpl; reflexivity.\n - simpl; intros y z; rewrite IHx0; reflexivity.\nQed.\n\n\nFixpoint mult2 (n:nat) : nat :=\n   match n with \n   | 0 => 0\n   | S p => S (S (mult2 p))\n   end.\n\nInductive Z_btree : Set :=\n  Z_leaf : Z_btree | Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nFixpoint sum_all_values (t:Z_btree) : Z :=\n  (match t with\n   | Z_leaf => 0\n   | Z_bnode v t1 t2 =>\n       v + sum_all_values t1 + sum_all_values t2\n  end)%Z.\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 =>\n        zero_present t1 ||  zero_present t2\n   end.\n\nFixpoint add_one (x:positive) : positive :=\n  match x with\n  | xI x' => xO (add_one x')\n  | xO x' => xI x'\n  | xH => 2%positive\n  end.\n\n\nInductive Z_fbtree : Set :=\n  Z_fleaf : Z_fbtree | Z_fnode : Z ->(bool->Z_fbtree)-> Z_fbtree.\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\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\n(**\n\nCheck Z_fbtree_ind. \n*)\n\nFixpoint fsum_all_values (t:Z_fbtree) : Z :=\n (match t with\n  | Z_fleaf => 0\n  | Z_fnode v f =>\n     v + fsum_all_values (f true) + fsum_all_values (f false)\n  end )%Z .\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 (n:nat)(f : nat -> Z) : Z\n := (match n with \n       | O => 0\n       | S p => f n + sum_f p f\n     end)%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 =>\n         v + sum_f n (fun x:nat => n_sum_all_values n (f x))\n    end )%Z.\n\n\n\nDefinition mult2' : nat->nat :=\n  fix f (n:nat) : nat :=\n    match n with 0 => 0 | S p => S (S (f p)) end.\n\n\n\nFixpoint app {A:Type}(l m:list A) : list A :=\n  match l with\n  | nil => m\n  | cons a l1 => cons a (app  l1 m)\n  end.\n\nPrint cons.\n\nDefinition pred_option (n:nat) : option nat :=\n  match n with O => None | S p => Some p end.\n\nDefinition pred2_option (n:nat) : option nat :=\n  match pred_option n with\n  | None => None\n  | Some p => pred_option p\n  end.\n\nFixpoint nth_option {A:Type} (n:nat)(l:list A) : option A :=\n  match n, l with\n  | O, cons a tl => Some a\n  | S p, cons a tl => nth_option  p tl\n  | _, nil => None\n  end.\n\nFixpoint nth_option' {A:Type} (n:nat)(l:list A) {struct n} : option A :=\n  match n, l with\n  | O, cons a tl => Some a\n  | S p, cons a tl => nth_option'  p tl\n  | _, nil => None\n  end.\n\n(** Some tests: \n\nPrint fst.\n\nCheck (sum nat bool). \n\nCheck (inl bool 4).\n\nCheck (inr nat false).\n*)\n\nPrint sum.\n\nPrint fst.\n\nCheck (sum nat bool). \n\nCheck (inl bool 4).\n\nCheck (inr nat false).\n\nCheck (inl bool 4).\nCheck (inl 4).\n\n\nInductive ltree (n:nat) : Set :=\n  | lleaf : ltree n\n  | lnode : forall p:nat, p <= n -> ltree n -> ltree n -> ltree n.\n\nInductive sqrt_data (n:nat) : Set :=\n  sqrt_intro : forall x:nat, x*x <= n -> n <  S x * S x -> sqrt_data n.\n\nCompute (sqrt_data).\n\nInductive sqrt_data' (n:nat) : Set :=\n  sqrt_intro' : sqrt_data' n.\n\nCompute sqrt_intro'.\nCompute (sqrt_intro' 1).\n\nInductive htree (A:Type) : nat->Type :=\n  | hleaf : A->htree A 0\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\nCheck hleaf.\nCheck htree_ind.\n\n(**\n\nCheck htree_ind.\n\n*)\n\n\nFixpoint htree_to_btree (n:nat)(t:htree Z n){struct t} : Z_btree :=\n  match t with\n  | hleaf _ x => Z_bnode x Z_leaf Z_leaf\n  | hnode _ p v t1 t2 =>\n      Z_bnode v (htree_to_btree p t1)(htree_to_btree p t2)\n  end.\n\nFixpoint invert (A:Type)(n:nat)(t:htree A n){struct t} : htree A n :=\n  match t in htree _ x return htree A x with\n  | hleaf _ v => hleaf A v\n  | hnode _ p v t1 t2 => hnode A p v (invert A p t2)(invert A p t1)\n  end.\n\n  \n(**\n\nPrint Empty_set.\n\nCheck Empty_set_ind. \n*)\n\nInductive strange : Set :=  cs : strange->strange.\n\n\nTheorem strange_empty : forall x:strange, False.\nProof.\n intro x. induction x.\n assumption.\nQed.\n\nTheorem strange_empty' : forall x:strange, False.\nProof.\n intro x. apply strange_ind.\n - intros. assumption.\n - apply x.\nQed.\n\nTheorem nat_not_strange :  forall n:nat, False.\nProof.\n intros x. \n Print nat_ind.\n apply nat_ind.\n - admit. \n - intros; assumption.\n - apply x. \nAbort.\n\nTheorem nat_not_strange' :  forall n:nat, False.\nProof.\n intros x. \n induction x.\n - admit.\n -  \nAbort.\n\n(** attempt to prove falsehood\n\nTheorem nat_not_strange :  forall n:nat, False.\nProof.\n intros x; elim x.\nAbort.\n\n*)\n\nInductive even_line : nat->Set :=\n  | even_empty_line : even_line 0\n  | even_step_line : forall n:nat, even_line n -> even_line (S (S n)).\n\n(** Tests :\n\nCheck even_empty_line.\n\nCheck (even_step_line _ even_empty_line). \n\n\nCheck (even_step_line _ (even_step_line _ even_empty_line)). \n*)\n\n", "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/ch6_inductive_data/SRC/chap6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7698846745060194}}
{"text": "Theorem plus_1 :\n  forall (n m:nat), n + S m = S (n + m).\nProof. intros. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem plus_comm :\n  forall (n m:nat), n + m = m + n.\nProof.\n  intros n m. \n  induction n as [|n IHn].\n  - simpl. induction m; simpl; auto.\n  - simpl. rewrite plus_1.  rewrite IHn. reflexivity.\nQed.", "meta": {"author": "bennofs", "repo": "coq-mapping-database", "sha": "1efb401b7ff22d1d33363e24061b08282757dbbf", "save_path": "github-repos/coq/bennofs-coq-mapping-database", "path": "github-repos/coq/bennofs-coq-mapping-database/coq-mapping-database-1efb401b7ff22d1d33363e24061b08282757dbbf/Example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7698724156577835}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\nTheorem app_assoc_destruct : forall X (l1 l2 l3: list X),\n  (l1 ++ l2) ++ l3 = l1 ++ l2 ++ l3.\nProof.\n  intros.\n  induction l1 as [|h t IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite IHl'. reflexivity.\nQed.\n\n(* parameterized propositions *)\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.\n  injection H as H1.\n  apply H1.\nQed.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA 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  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros.\n  apply and_intro.\n  - destruct n as [|n'].\n    + reflexivity.\n    + simpl in H. discriminate H.\n  - destruct m as [|m'].\n    + reflexivity.\n    + rewrite -> plus_comm in H. simpl in H.\n      discriminate 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\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  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. \nQed.\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ. \nQed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP. \nQed.\n\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\nLemma or_example : forall n m : nat, \n  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 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\nModule MyNot.\nDefinition not (P:Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\n(* ===> Prop -> Prop *)\nNotation \"x <> y\" := (~ (x = y)).\nEnd MyNot.\n\n(*  Latin ex falso quodlibet\n  = from falsehood follows whatever you like\n  = principle of explosion. *)\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  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  unfold not.\n  intros.\n  apply H in H0.\n  destruct H0.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. \nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~ P) -> Q.\nProof.\n  intros P Q [HP HNA]. \n  unfold not in HNA.\n  apply HNA in HP. destruct HP. \nQed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~ ~ P.\nProof.\n  intros P H.\n  unfold not. intros G.\n  apply G. apply H.\nQed.\n\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\n  unfold not.\n  intros P Q H0 H1 H2. apply H0 in H2.\n  apply H1 in H2. destruct H2.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~ P).\nProof.\n  intros P.\n  unfold not.\n  intros [H0 H1].\n  apply H1 in H0.\n  apply H0.\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. reflexivity.\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\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  (* WORKED IN CLASS *)\n  intros P Q [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  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\nTheorem or_depend_on_each_left : forall P Q : Prop,\n  P -> P \\/ Q.\nProof. Admitted.\n\nTheorem or_depend_on_each_right : forall P Q : Prop,\n  Q -> P \\/ Q.\nProof. Admitted.\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 [H0 | H1].\n    { split.\n      - apply or_depend_on_each_left. apply H0.\n      - apply or_depend_on_each_left. apply H0.\n    } \n    { split.\n      - apply proj1 in H1. \n        apply or_depend_on_each_right.\n        apply H1.\n      - apply proj2 in H1. \n        apply or_depend_on_each_right.\n        apply H1.\n    }\n  }\n  {\n    intros [[H0 | H1] [H2 | H3]]. left.\n    - apply H0.\n    - apply or_depend_on_each_left. apply H0.\n    - apply or_depend_on_each_left. apply H2.\n    - apply or_depend_on_each_right. \n      apply and_intro. apply H1. apply H3.\n  }\nQed. \n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof. Admitted.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof. Admitted.\n\nLemma mult_0 : forall n m, \n  n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc : forall P Q R : Prop, \n  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  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. reflexivity.\nQed.\n\nLemma apply_iff_example : forall n m : nat, \n  n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. \n  apply mult_0. apply H.\nQed.\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 [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.\n  unfold not.\n  (* intros [x1 Hx1] is OK, too. *)\n  intros H0.\n  destruct H0 as [x1 Hx1]. \n  apply Hx1 in H. destruct H.\nQed.\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> \n    (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros. split.\n  - intros [x [H0 | H1]]. \n    + left. exists x. apply H0.\n    + right. exists x. apply H1.\n  - intros [[x0 H0] | [x1 H1]].\n    + exists x0. left. apply H0.\n    + exists x1. right. apply H1.\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.\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  - (* 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 as [|x' l' IHl'].\n    + simpl. apply ex_falso_quodlibet.\n    + simpl. intros [H0 | H1]. \n      * exists x'. split. apply H0. \n        left. reflexivity.\n      * apply IHl' in H1. destruct H1 as [x [H1 H2]].\n        exists x. split. apply H1. right. apply H2.\n  - induction l as [|x' l' IHl'].\n    + intros [x [H0 H1]]. simpl. simpl in H1.\n      apply H1.\n    + intros H. simpl in H.\n      destruct H as [x [H1 [H2 | H3]]].\n      * simpl. left. rewrite -> H2.\n        apply H1.\n      * simpl. right. apply IHl'.\n        exists x. split. apply H1. apply H3.\nQed.\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.\n  - induction l as [|x' l'' IHl''].\n    + simpl. intros H. right. apply H.\n    + simpl. intros [H0 | H1]. \n      * left. left. apply H0.\n      * apply or_assoc. right. \n        apply IHl''. apply H1.\n  - induction l as [|x' l'' IHl''].\n    + simpl. intros [H0 | H1]. \n      * apply ex_falso_quodlibet. apply H0.\n      * apply H1.\n    + simpl. intros [[H0 | H1] | H2].\n      * left. apply H0.\n      * right. apply IHl''. left. apply H1.\n      * right. apply IHl''. right. apply H2.\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) <->\n    All P l.\nProof.\n  intros. split.\n  - intros H. induction l as [|x l' IHl'].\n    + simpl. reflexivity.\n    + simpl. split.\n      * apply H. simpl. left. reflexivity.\n      * apply IHl'. intros x0 H0.\n        simpl in H. apply H. right. apply H0.\n  - intros H. induction l as [|x l' IHl'].\n    + simpl. intros x0 H0. \n      apply ex_falso_quodlibet. apply H0.\n    + simpl. simpl in H. \n      destruct H as [H0 H1].\n      intros x0 [H2 | H3].\n      * rewrite <- H2. apply H0.\n      * apply IHl'. apply H1. apply H3.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : \n   nat -> Prop :=\n  fun (n : nat) => if oddb n \n                   then Podd n \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.\n  unfold combine_odd_even.\n  destruct (oddb n) eqn:E1.\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  unfold combine_odd_even.\n  intros. 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  unfold combine_odd_even.\n  intros. rewrite H0 in H. apply H.\nQed.\n\n(* Use theorems AS Function !!! *)\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), \n    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 :\n  forall l : list nat, \n    In 42 l -> l <> [].\nProof.\n  (* WORKED IN CLASS *)\n  intros l H.\n  Fail apply in_not_nil.\nAbort.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, \n    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\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(*\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. \n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\n\nI don't know what it means yet.\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\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\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\nAxiom rev_append_aux : forall X (x : X) (l: list X),\n  rev_append l [x] = rev_append l [ ] ++ [x].\n\nLemma tr_rev_correct : forall X, \n  @tr_rev X = @rev X.\nProof. \n  intros.\n  apply functional_extensionality.\n  intros l. induction l as [|x l' IHl'].\n  - reflexivity.\n  - unfold tr_rev. simpl. \n    rewrite <- IHl'. unfold tr_rev. \n    apply rev_append_aux.\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, \n  evenb (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. rewrite plus_comm. simpl.\n    rewrite <- IHk'. reflexivity.\nQed.\n\n(* Originally in Basics.v *)\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof. Admitted.\n\nAxiom negb_axiom1 : forall (b : bool),\n  negb b = true -> b = false.\n\nAxiom negb_axiom2 : forall (b : bool),\n  negb b = false -> b = true.\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 as [|n' IHn'].\n  - simpl. exists 0. reflexivity.\n  - destruct (evenb (S n')) eqn:E1.\n    + rewrite evenb_S in E1. \n      apply negb_axiom1 in E1.\n      rewrite E1 in IHn'. \n      destruct IHn' as [k0 IHn'].\n      exists (S k0). rewrite IHn'.\n      unfold double. symmetry. simpl.\n      rewrite plus_comm. simpl. reflexivity.\n    + rewrite evenb_S in E1. \n      apply negb_axiom2 in E1.\n      rewrite E1 in IHn'. \n      destruct IHn' as [k0 IHn'].\n      rewrite IHn'. exists k0.\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 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_refl : forall n,\n  true = (n =? n).\nProof.\n  intros. induction n as [|n' H].\n  - simpl. reflexivity.\n  - simpl. apply H.\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\n(* Proof by reflection. examples *)\nExample even_1000 : exists k, 1000 = double k.\nProof. exists 500. reflexivity. Qed.\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n(* What is interesting is that, since the \n   two notions are equivalent, we can use \n   the boolean formulation to prove the \n   other one without mentioning the value \n   500 explicitly: \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\nExample not_even_1001' : \n  ~ (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  intros n m p H.\n  rewrite eqb_eq in H.\n  rewrite H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros. split.\n  - unfold andb. intros H. destruct b1.\n    + split. reflexivity. apply H.\n    + discriminate H.\n  - intros H. destruct H as [H1 H2].\n    unfold andb. rewrite H1. simpl. \n    apply H2. \nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros. split.\n  - unfold orb. intros H. destruct b1.\n    left. reflexivity. right. apply H.\n  - intros H. unfold orb. \n    destruct H as [H1 | H2].\n    + rewrite H1. simpl. reflexivity.\n    + destruct b1. reflexivity. apply H2.\nQed.\n\nTheorem eqb_false : forall n m,\n  n =? m = false -> n <> m.\nProof. Admitted.\n\n(*\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  intros. split.\n  - apply eqb_false.\n  - unfold not. intros H. \nQed.\n*)\n\nFixpoint eqb_list {A : Type} \n  (eqb : A -> A -> bool) (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | _ , [] => false\n  | [] , _ => false\n  | (h1 :: t1) , (h2 :: t2) =>\n    if (eqb h1 h2) then (eqb_list eqb t1 t2)\n      else false\n  end.\n\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. split.\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\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 as [|h t IHt].\n    simpl. reflexivity. simpl. intros H. \n    apply andb_true_iff in H.\n    destruct H as [H0 H1]. split. \n    apply H0. apply IHt. apply H1.\n  - induction l as [|h t IHt].\n    simpl. reflexivity. simpl. intros [H0 H1].\n    rewrite H0. simpl. apply IHt. apply H1. \nQed.\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\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\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. unfold not.\n  intros. \nQed.\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  intros. unfold not. intros H.\n  apply H. \nQed.\n*)\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).", "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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.7697836481731911}}
{"text": "(** ProofCafe Coq入門 #2 *)\n(** 2017/8/19 @suharahiromichi  *)\n\nSet Implicit Arguments.\n\n(* 自然数 *)\nRequire Import Arith.\n\nGoal forall x y z : nat, x * (y * z) = x * y * z.\nProof.\n  intros.\n  Search (_ * (_ * _)).\n  (* Search では Notation は見つからない。 *)\n  now rewrite mult_assoc.                   (* Notation *)\n  Undo 1.\n  now rewrite Nat.mul_assoc.\n  Undo 1.\n  ring.\nQed.\n\nGoal forall x : nat, 1 * x = x.\nProof.\n  intros.\n  now rewrite mult_1_l.                     (* Notation *)\n  Undo 1.\n  now rewrite Nat.mul_1_l.\n  Undo 1.\n  ring.\nQed.\n\nGoal forall x : nat, x * 1 = x.\nProof.\n  intros.\n  now rewrite mult_1_r.                     (* Notation *)\n  Undo 1.\n  now rewrite Nat.mul_1_r.\n  Undo 1.\n  ring.\nQed.\n\n(* 整数 *)\nRequire Import ZArith.\nOpen Scope Z.\n\n(* Scope については、以下を参照のこと。\n\n   Coq RM\n   Chapter 12  Syntax extensions and interpretation scopes\n   12.2  Interpretation scopes\n\n   https://coq.inria.fr/refman/Reference-Manual014.html\n\n   主なコマンドは、Bind Scope, Open Scope, Close Scoep.\n   省略時解釈は、core_scope, type_scope, nat_scope の順番である。\n *)\n\nGoal forall x y z : Z, x * (y * z) = x * y * z.\nProof.\n  intros.\n  now rewrite Zmult_assoc.                  (* Notation *)\n  Undo 1.\n  Search (_ * (_ * _)).                     (* Scope はSearchに影響するよう。 *)\n  now rewrite Z.mul_assoc.\n  Undo 1.\n  ring.\nQed.\n\nGoal forall x : Z, 1 * x = x.\nProof.\n  intros.\n  now rewrite Zmult_1_l.                    (* Notation *)\n  Undo 1.\n  now rewrite Z.mul_1_l.\n  Undo 1.\n  ring.\nQed.\n\nGoal forall x : Z, x * 1 = x.\nProof.\n  intros.\n  now rewrite Zmult_1_r.                    (* Notation *)\n  Undo 1.\n  now rewrite Z.mul_1_r.\n  Undo 1.\n  ring.\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/intro/2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.769783645129039}}
{"text": "Add LoadPath \"F:\\sfsol\".\nRequire Export Chap3.\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    intros m eq.\n    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\". apply IHn'.\n        inversion eq. reflexivity.\n      rewrite -> 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  generalize dependent n.\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\nTheorem plus_n_n_injective_take2 : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m.\n  destruct n.\n    reflexivity.\n    intros H. inversion H.\n  destruct n.\n    intros H. inversion H.\n    rewrite <- plus_n_Sm.\n    rewrite <- plus_n_Sm.\n    intros H. inversion H.\n    assert (n = m). apply IHm.\n    apply H1.\n    rewrite -> H0.\n    reflexivity.\n    Qed.\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  intros n X l.\n  generalize dependent n.\n  induction l.\n    intros n H.\n    destruct n.\n      reflexivity.\n      inversion H.\n    intros n H.\n    destruct n.\n      inversion H.\n      simpl.\n      inversion H.\n      apply IHl.\n      reflexivity.\n  Qed.\n\n(* index_after_last_informal yet to write *)\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.\n  destruct n.\n    reflexivity.\n    intros H. inversion H.\n  intros n H.\n  destruct n.\n    inversion H.\n    simpl in H. inversion H.\n    simpl.\n    assert (length (snoc l v) = S n).\n    apply IHl. apply H1.\n    rewrite -> H.\n    rewrite -> H0.\n    reflexivity.\n  Qed.\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 H.\n  destruct n.\n    reflexivity.\n    inversion H.\n  intros n H.\n  destruct n.\n    inversion H.\n    simpl in H. inversion H.\n    simpl.\n    assert (length (snoc l v) = S n).\n      apply IHl.\n      apply H1.\n    rewrite -> H0.\n    rewrite -> H.\n    reflexivity.\n  Qed.\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 H.\n  rewrite <- H.\n  reflexivity.\n  intros n H.\n  destruct n.\n    inversion H.\n    simpl in H.\n    inversion H.\n    simpl.\n    rewrite -> H1.\n    assert(S (length (l1 ++ l2)) = n).\n      apply IHl1.\n    apply H1.\n    rewrite -> H0.\n    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 X n l.\n  generalize dependent n.\n  induction l.\n  intros n H.\n  simpl in H.\n  rewrite <- H.\n  reflexivity.\n  intros n H.\n  destruct n.\n    inversion H.\n    simpl.\n    assert (length (l ++ x :: l) = S (n + n)).\n    inversion H.\n    assert (length (l ++ l) = n + n).\n    apply IHl. apply H1.\n    rewrite -> H1.\n    rewrite <- H0.\n    remember (length (l ++ x :: l)) as len.\n    symmetry.\n    apply app_length_cons with (x:=x).\n    symmetry.\n    apply Heqlen.\n    rewrite -> H0.\n    rewrite -> plus_n_Sm.\n    reflexivity.\n  Qed.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/Chap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.7697836443585574}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2012     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\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.\nLocal Open Scope identity_scope.\nRequire Import Logic_Type.\n\nOpen Scope nat_scope.\n\nDefinition eq_S := f_equal S.\n\nHint Resolve (f_equal S): v62.\nHint Resolve (f_equal (A:=nat)): core.\n\n(** The predecessor function *)\n\nDefinition pred (n:nat) : nat := match n with\n                                 | O => n\n                                 | S u => u\n                                 end.\n(* Hint Resolve (f_equal pred): v62. *)\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) : Type :=\n  match n with\n  | O => False\n  | S p => True\n  end.\n\n(** Zero is not the successor of a number *)\n\n(* XXX Andrej: Try to put back in, does not work with current Coq. *)\n(* Theorem O_S : forall n:nat, 0 <> S n. *)\n(* Proof. *)\n(*   discriminate. *)\n(* Qed. *)\n(* Hint Resolve O_S: core. *)\n\n(* XXX Andrej: Try to put back in, does not work with current Coq. *)\n(* Theorem n_Sn : forall n:nat, n <> S n. *)\n(* Proof. *)\n(*   induction n; auto. *)\n(* Qed. *)\n(* Hint Resolve n_Sn: core. *)\n\n(** addition *)\n\nFixpoint plus (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\n\nwhere \"n + m\" := (plus n m) : nat_scope.\n\nHint Resolve (f_equal2 plus): v62.\nHint Resolve (f_equal2 (A1:=nat) (A2:=nat)): core.\n\nLemma plus_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n; simpl; auto.\nQed.\nHint Resolve plus_n_O: core.\n\nLemma plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  auto.\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  auto.\nQed.\n\n(** Standard associated names *)\n\nNotation plus_0_r_reverse := plus_n_O (compat \"8.2\").\nNotation plus_succ_r_reverse := plus_n_Sm (compat \"8.2\").\n\n(** Multiplication *)\n\nFixpoint mult (n m:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => m + p * m\n  end\n\nwhere \"n * m\" := (mult n m) : nat_scope.\n\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 (compat \"8.2\").\nNotation mult_succ_r_reverse := mult_n_Sm (compat \"8.2\").\n\n(** Truncated subtraction: [m-n] is [0] if [n>=m] *)\n\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O, _ => n\n  | S k, O => n\n  | S k, S l => k - l\n  end\n\nwhere \"n - m\" := (minus n m) : 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 -> Type :=\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\n(** Case analysis *)\n\nTheorem nat_case :\n forall (n:nat) (P:nat -> Type), 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 -> Type,\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\nFixpoint max n m : nat :=\n  match n, m with\n    | O, _ => m\n    | S n', O => n\n    | S n', S m' => S (max n' m')\n  end.\n\nFixpoint min n m : nat :=\n  match n, m with\n    | O, _ => 0\n    | S n', O => 0\n    | S n', S m' => S (min n' m')\n  end.\n\n(* Theorem max_l : forall n m : nat, m <= n -> max n m = n. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem max_r : forall n m : nat, n <= m -> max n m = m. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem min_l : forall n m : nat, n <= m -> min n m = n. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem min_r : forall n m : nat, m <= n -> min n m = m. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(** [n]th iteration of the function [f] *)\n\nFixpoint nat_iter (n:nat) {A} (f:A->A) (x:A) : A :=\n  match n with\n    | O => x\n    | S n' => f (nat_iter n' f x)\n  end.\n\nLemma nat_iter_succ_r n {A} (f:A->A) (x:A) :\n  nat_iter (S n) f x = nat_iter n f (f x).\nProof.\n  induction n; intros; simpl; rewrite <- ?IHn; trivial.\nQed.\n\nTheorem nat_iter_plus :\n  forall (n m:nat) {A} (f:A -> A) (x:A),\n    nat_iter (n + m) f x = nat_iter n f (nat_iter m f x).\nProof.\n  induction n; intros; simpl; rewrite ?IHn; trivial.\nQed.\n\n(** Preservation of invariants : if [f : A->A] preserves the invariant [Inv],\n    then the iterates of [f] also preserve it. *)\n\nTheorem nat_iter_invariant :\n  forall (n:nat) {A} (f:A -> A) (P : A -> Type),\n    (forall x, P x -> P (f x)) ->\n    forall x, P x -> P (nat_iter n f x).\nProof.\n  induction n; simpl; trivial.\n  intros A f P Hf x Hx. apply Hf, IHn; trivial.\nQed.\n", "meta": {"author": "clarus", "repo": "coq-hoq", "sha": "7943953569f1b32169c4da625cebb018030226dd", "save_path": "github-repos/coq/clarus-coq-hoq", "path": "github-repos/coq/clarus-coq-hoq/coq-hoq-7943953569f1b32169c4da625cebb018030226dd/Init/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8723473647220786, "lm_q1q2_score": 0.769783629253426}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.PeanoNat.\n\n\n(** List Sets *)\n\n(* this would normally be kept abstract as a section variable,\n   but for testing, we make it concrete *)\nDefinition E := nat.\nDefinition eeq: forall (e1 e2: E), {e1 = e2} + {e1 <> e2} := Nat.eq_dec.\n\nDefinition set: Type -> Type := list.\n\nDefinition contains(A: set E)(e: E): Prop := List.In e A.\n\nDefinition empty_set: set E := nil.\n\nDefinition singleton_set(e: E): set E := (cons e nil).\n\nDefinition union(A B: list E): list E :=\n  fold_left (fun res a => if in_dec eeq a res then res else a :: res) A B.\n\nDefinition intersect(A B: list E): list E :=\n  fold_left (fun res a => if in_dec eeq a B then a :: res else res) A nil.\n\nDefinition diff(A B: list E): list E :=\n  fold_left (fun res b => remove eeq b res) B A.\n\n\n(** Specs of set operations in terms of \"contains\" *)\n\nConjecture empty_set_spec: forall (x: E), contains empty_set x <-> False.\n\nConjecture singleton_set_spec: forall (x y: E),\n    contains (singleton_set y) x <-> x = y.\n\nConjecture union_spec: forall (x: E) (A B: set E),\n    contains (union A B) x <-> contains A x \\/ contains B x.\n\nConjecture intersect_spec: forall (x: E) (A B: set E),\n    contains (intersect A B) x <-> contains A x /\\ contains B x.\n\nConjecture diff_spec: forall (x: E) (A B: set E),\n    contains (diff A B) x <-> contains A x /\\ ~ contains B x.\n\n\n\n(** Additional functions for sets defined in terms of the primitive ones *)\n\nDefinition add(s: set E)(e: E) := union (singleton_set e) s.\nDefinition remove_elem(s: set E)(e: E) := diff s (singleton_set e).\nDefinition subset(s1 s2: set E) := forall x, contains s1 x -> contains s2 x.\nDefinition disjoint(s1 s2: set E) := forall x, (~ contains s1 x) \\/ (~ contains s2 x).\n\n\n(** List Maps *)\n\n(* this would normally be kept abstract as a section variable,\n   but for testing, we make it concrete *)\nDefinition K: Type := nat.\nDefinition V: Type := nat.\nDefinition keq: forall (k1 k2: K), {k1 = k2} + {k1 <> k2} := Nat.eq_dec.\nDefinition veq: forall (v1 v2: V), {v1 = v2} + {v1 <> v2} := Nat.eq_dec.\n\nDefinition map(K V: Type): Type := list (K * V).\n\nDefinition empty_map: map K V := nil.\n\nDefinition get(M: map K V)(k: K): option V :=\n  match find (fun '(ki, vi) => if keq ki k then true else false) M with\n  | Some (_, v) => Some v\n  | None => None\n  end.\n\nDefinition remove(M: map K V)(k: K): map K V :=\n  filter (fun '(ki, vi) => if keq k ki then false else true) M.\n\nDefinition put(M: map K V)(k: K)(v: V): map K V := (k, v) :: (remove M k).\n\nDefinition restrict(M: map K V)(A: set K): map K V :=\n  filter (fun '(ki, vi) => if in_dec keq ki A then true else false) M.\n\nDefinition domain(M: map K V): set K := List.map fst M.\n\nDefinition domain_and_range(M: map K V): set K * set V :=\n  fold_left (fun '(d, r) '(ki, vi) =>\n               if in_dec keq ki d then (d, r) else (ki :: d, vi :: r)\n            ) M (empty_set, empty_set).\n\nDefinition range(M: map K V): set V :=\n  snd (domain_and_range M).\n\nDefinition reverse_get(M: map K V)(v: V): option K :=\n  snd (fold_left (fun '(seen_keys, res) '(ki, vi) =>\n                    if in_dec keq ki seen_keys then (seen_keys, res)\n                    else (ki :: seen_keys, if veq vi v then Some ki else res))\n                 M (empty_set, None)).\n\nDefinition intersect_map(M1 M2: map K V): map K V :=\n  filter (fun '(k1, v1) => match get M1 k1, get M2 k1 with\n                           | Some v1', Some v2 => if veq v1' v1\n                                                  then if veq v1 v2 then true else false\n                                                  else false\n                           | _, _ => false\n                           end) M1.\n\nDefinition preimage(M: map K V)(vs: set V): set K :=\n  filter (fun ki => match get M ki with\n                    | Some vi => if in_dec veq vi vs then true else false\n                    | None => false\n                    end)\n         (domain M).\n\nDefinition remove_keys(M: map K V)(ks: set K): map K V :=\n  filter (fun '(ki, vi) => if in_dec keq ki ks then false else true) M.\n\nDefinition remove_by_value(M: map K V)(v: V): map K V :=\n  remove_keys M (preimage M (singleton_set v)).\n\nDefinition remove_values(M: map K V)(vs: set V): map K V :=\n  remove_keys M (preimage M vs).\n\nDefinition update_map(M1 M2: map K V): map K V :=\n  (filter (fun '(k1, v1) =>\n             if (find (fun '(k2, v2) => if keq k1 k2 then true else false) M2)\n             then false else true) M1) ++ M2.\n\n\n(** Specs of the map functions in terms of \"get\" *)\n\nConjecture empty_is_empty: forall (k: K),\n    get empty_map k = None.\n\nConjecture get_remove_same: forall m k,\n    get (remove m k) k = None.\n\nConjecture get_remove_diff: forall m k1 k2,\n    k1 <> k2 -> get (remove m k1) k2 = get m k2.\n\nConjecture get_put_same: forall (m: map K V) (k: K) (v: V),\n    get (put m k v) k = Some v.\n\nConjecture get_put_diff: forall (m: map K V) (k1 k2: K) (v: V),\n    k1 <> k2 -> get (put m k1 v) k2 = get m k2.\n\nConjecture get_restrict_in: forall m k ks,\n    contains ks k -> get (restrict m ks) k = get m k.\n\nConjecture get_restrict_notin: forall m k ks,\n    ~ contains ks k -> get (restrict m ks) k = None.\n\nConjecture in_domain: forall m k v,\n    get m k = Some v -> contains (domain m) k.\n\nConjecture not_in_domain: forall m k,\n    get m k = None -> ~ contains (domain m) k.\n\nConjecture in_range: forall m k v,\n    get m k = Some v -> contains (range m) v.\n\nConjecture not_in_range: forall m v,\n    (forall k, get m k <> Some v) -> ~ contains (range m) v.\n\nConjecture range_spec: forall m v,\n    contains (range m) v <-> exists k, get m k = Some v.\n\nConjecture reverse_get_Some: forall m k v,\n    reverse_get m v = Some k -> get m k = Some v.\n\nConjecture reverse_get_None: forall m v,\n    reverse_get m v = None -> forall k, get m k <> Some v.\n\nConjecture intersect_map_spec: forall k v m1 m2,\n    get (intersect_map m1 m2) k = Some v <-> get m1 k = Some v /\\ get m2 k = Some v.\n\nConjecture remove_by_value_same: forall k v m,\n    get m k = Some v -> get (remove_by_value m v) k = None.\n\nConjecture remove_by_value_diff: forall k v m,\n    get m k <> Some v -> get (remove_by_value m v) k = get m k.\n\nConjecture remove_values_never_there: forall m k vs,\n    get m k = None ->\n    get (remove_values m vs) k = None.\n\nConjecture remove_values_removed: forall m k v vs,\n    get m k = Some v ->\n    contains vs v ->\n    get (remove_values m vs) k = None.\n\nConjecture remove_values_not_removed: forall m k v vs,\n    get m k = Some v ->\n    ~ contains vs v ->\n    get (remove_values m vs) k = Some v.\n\nConjecture get_update_map_l: forall m1 m2 k,\n    get m2 k = None ->\n    get (update_map m1 m2) k = get m1 k.\n\nConjecture get_update_map_r: forall m1 m2 k v,\n    get m2 k = Some v ->\n    get (update_map m1 m2) k = Some v.\n\n\n(** Additional map judgments defined in terms of the primitive ones *)\n\nDefinition extends(s1 s2: map K V) :=\n  forall x w, get s2 x = Some w -> get s1 x = Some w.\n\nDefinition only_differ(s1: map K V)(d: set K)(s2: map K V) :=\n  forall x, contains d x \\/ get s1 x = get s2 x.\n\nDefinition agree_on(s1: map K V)(d: set K)(s2: map K V) :=\n  forall x, contains d x -> get s1 x = get s2 x.\n\nDefinition undef_on(s: map K V)(ks: set K) :=\n  forall x, contains ks x -> get s x = None.\n", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/QuickChick/SetAndMapProperties/SetAndMapLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7697289448111766}}
{"text": "(* Razonamiento automatizado 2020-2\n   Loyola Cruz Luis Fernando.\n   Reyes Granados Naomi Itzel.\n   Tarea 4, Tácticas básicas y negación clásica*)\n\nVariables p q r s t x l m:Prop.\nVariables U:Type.\nVariables P Q: U -> Prop.\nVariables R : U -> U -> Prop.\nVariables a b : U.\n\n\nSection LPyLPO.\n\nTheorem DilemaC : (p -> q) -> (r -> s) -> p \\/ r -> q \\/ s. \nProof.\nintro.\nintro.\nintro.\ndestruct H1.\nleft.\napply H.\nassumption.\nright.\napply H0.\nassumption.\nQed.\n\n\nTheorem Distrib : p \\/ (q /\\ r) -> (p \\/ q) /\\ (p \\/ r).\nProof.\nintro.\nsplit.\ndestruct H.\nleft.\nassumption.\ndestruct H.\nright.\nassumption.\ndestruct H.\nleft.\nassumption.\ndestruct H.\nright.\nassumption.\nQed.\n\n\n\nTheorem Argumento1: ((x \\/ p) /\\ q -> l) /\\\n                    (m \\/ q -> s /\\ t) /\\\n                    ((s /\\ t) /\\ l -> x) /\\\n                    (p -> q) ->\n                    (m /\\ p -> x).\nProof.\nintro.\ndestruct H.\ndestruct H0.\ndestruct H1.\nintro.\ndestruct H3.\napply H1.\nsplit.\napply H0.\nleft.\nassumption.\napply H.\nsplit.\nright.\nassumption.\napply H2.\nassumption.\nQed.\n\n\nTheorem Socrates: (forall x:U, P x -> Q x) /\\ P a -> Q a.\nProof.\nintro.\ndestruct H.\napply H.\nassumption.\nQed.\n\n\nTheorem DistrExistsConj: (exists x:U, P x /\\ Q x) -> (exists x:U, P x) /\\ (exists x:U, Q x).\nProof.\nintro.\nsplit.\ndestruct H.\ndestruct H.\nexists x0.\nassumption.\ndestruct H.\ndestruct H.\nexists x0.\nassumption.\nQed.\n\n\nTheorem Argumento2: (forall y:U, P y -> Q y) -> (forall x:U, (exists y:U, P y /\\ R x y) -> exists z:U, Q z /\\ R x z).\nProof.\nintro.\nintros.\ndestruct H0.\ndestruct H0.\nexists x1.\nsplit.\napply H.\nassumption.\nassumption.\nQed.\n\n\nEnd LPyLPO.\n\n\nSection LogConst.\n\nTheorem NegImp: (p -> q) -> (p -> ~q) -> ~p.\nProof.\nheorem NegImp: (p -> q) -> (p -> ~q) -> ~p.\nProof.\nintros.\nunfold not.\nintro.\nabsurd (q).\napply H0.\nassumption.\napply H.\nassumption.\nQed.\n\nTheorem nonoTExc: ~~(p \\/ ~p).\nProof.\nunfold not.\nintro.\napply H.\nright.\nintro.\napply H.\nleft.\nassumption.\nQed.\n\nTheorem dmorganO : ~ ( p \\/ q ) <-> ~p /\\ ~q.\nProof.\nunfold iff.\nsplit.\nunfold not.\nintro.\nsplit.\nintro.\napply H.\nleft.\nassumption.\nintro.\napply H.\nright.\nassumption.\nunfold not.\nintros.\ndestruct H.\ndestruct H0.\napply H.\nassumption.\napply H1.\nassumption.\nQed.\n\nTheorem Argumento3: (forall x:U, P x -> Q x) /\\\n              (~ exists x:U, P x /\\ Q x) ->\n              ~ exists x:U, P x.\nProof.\nunfold not.\nintros.\ndestruct H.\ndestruct H0.\napply H1.\nexists x0.\nsplit.\nassumption.\napply H.\nassumption.\nQed.\n\n\nEnd LogConst.\n", "meta": {"author": "NaomiReyes", "repo": "BasicosCoq", "sha": "86173446d7b92cdf5d55ce8c2631243a02b87d25", "save_path": "github-repos/coq/NaomiReyes-BasicosCoq", "path": "github-repos/coq/NaomiReyes-BasicosCoq/BasicosCoq-86173446d7b92cdf5d55ce8c2631243a02b87d25/tarea4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7697289442117979}}
{"text": "Module Common.\n\n  Inductive list (X : Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n  (*\n  Inductive list {X : Type} : Type :=\n  | nil : list \n  | cons :  X -> list  -> list .\n*)\n\n\n  Fixpoint evenb (n:nat) : bool :=\n     match n with\n     | O => true\n     | S O => false\n     | S (S num) => evenb num\n   end.\n\n  Definition oddb (n:nat) : bool :=\n     negb (evenb 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\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 t l2)\n  end.\n\n\nFixpoint rev {X:Type} (l:(list X)) : (list X)  :=\n  match l with\n  | nil _   =>  nil  X\n  | cons _ h t => app (rev t) (cons X h (nil X))\n  end.\n\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  Notation \"x ++ y\" := (app x y)\n                         (right associativity, at level 60).\n\n  Check app [1;2] [3;4].\n\nLemma concat_append : forall X : Type, forall e : X, forall l : list X,\n   cons _ e l = [e] ++ l.\nProof.\n  intros X e l.\n  simpl.\n  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.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\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 [| l' IHl' ].\n  {\n    simpl.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite IHIHl'.\n    reflexivity.\n  }\n\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.\n  {\n    simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite IHl1.\n    simpl.\n    rewrite app_assoc.\n    reflexivity.\n  }\n\nQed.\n\n\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  induction l.\n  { reflexivity. }\n  { rewrite <- IHl.\n    rewrite concat_append.\n    rewrite rev_app_distr.\n    rewrite IHl.\n    rewrite rev_app_distr.\n    rewrite IHl.\n    simpl.\n    reflexivity.\n    }\n\n\nQed.\n\n\n(* Common numeric functions *)\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\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n   intros n m.\n   induction n as [| n' IHn' ].\n   - simpl. reflexivity.\n   - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\n\n(* Taken from chapter 2 *)\nTheorem plus_n_Sm2 : forall n m : nat,\n  S (n + m) = (S n) + m.\nProof.\n   intros n m.\n   induction n as [| n' IHn' ].\n   - simpl. reflexivity.\n   - simpl. rewrite -> IHn'. reflexivity.\nQed.\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 0) then Some a else nth_error l' (pred n)\n  end.\n\n\nFixpoint length {X : Type } (l : list X) : nat :=\n  match l with\n  | [] => 0\n  | h :: t => S (length t)\n  end.\n\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\nFixpoint split { X Y : Type } (l : list (X*Y) )\n  : (list X) * (list Y) :=\n  match l with\n  |  nil _ => (nil _, nil _)\n  |  ((x,y) :: rest) =>  match (split rest) with\n                         |  (x2,y2) => ((x::x2), (y::y2))\n                         end\n\n  end.\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)\n               else filter test t\n  end.\n\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\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\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\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\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\n\n\nEnd Common.\n  \n", "meta": {"author": "ldfallas", "repo": "sf_exercises", "sha": "a09704ebb31a6e4b563e61f01ff2b4bcb8a328af", "save_path": "github-repos/coq/ldfallas-sf_exercises", "path": "github-repos/coq/ldfallas-sf_exercises/sf_exercises-a09704ebb31a6e4b563e61f01ff2b4bcb8a328af/Common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7696421858969485}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreProp.\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\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 a 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(** 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\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. inversion H as [HP [HQ HR]]. split.\n  Case \"left\".\n    split. apply HP. apply HQ.\n  Case \"right\".\n    apply HR.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (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  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    split.\n    SCase \"left\". intros H. apply ev_0.\n    SCase \"rigth\". intros H. inversion H.\n  Case \"n = S n'\".\n    inversion IHn' as [H1 H2]. split.\n    SCase \"left\". apply H2.\n    SCase \"right\". intros H. apply ev_SS. apply H1. apply H.  Qed.\n(** [] *)\n\n\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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)\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. split.\n  Case \"->\". intros H. apply H.\n  Case \"<-\". intros H. apply H.  Qed.\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 as [HPQ HQP].\n  inversion H2 as [HQR HRQ].\n  split.\n  Case \"->\". intros H. apply HPQ in H. apply HQR in H. apply H.\n  Case \"<-\". intros H. apply HRQ in H. apply HQP in H. apply H.  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\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\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 (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. inversion H as [[H1P | H1Q] [H2P | H2R]].\n  Case \"PP\". left. apply H1P.\n  Case \"PR\". left. apply H1P.\n  Case \"QP\". left. apply H2P.\n  Case \"QR\". right. split.\n    SCase \"left\". apply H1Q.\n    SCase \"right\". apply H2R.  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 P Q R. split.\n  Case \"->\". apply or_distributes_over_and_1.\n  Case \"<-\". apply or_distributes_over_and_2.  Qed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\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_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\".\n    destruct c.\n    SCase \"c = true\". inversion H.\n    SCase \"c = false\". right. reflexivity.\n  Case \"b = fasle\".\n    left. reflexivity.  Qed.\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\".\n    left. reflexivity.\n  Case \"b = false\".\n    destruct c.\n    SCase \"c = true\". right. reflexivity.\n    SCase \"c = false\". inversion H.  Qed.\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\".\n    inversion H.\n  Case \"b = false\".\n    destruct c.\n    SCase \"c = true\". inversion H.\n    SCase \"c = false\". split. reflexivity. reflexivity.  Qed.\n(** [] *)\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\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(* #################################################### *)\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop :=\n  I : True.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to\n    higher-order [Prop]s. *)\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, 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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not. intros P Q H1 H2 H3.\n  apply H1 in H3. apply H2 in H3.\n  inversion H3.  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  unfold not. intros P H.\n  inversion H. apply H1 in H0. inversion H0.  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(* 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  Case \"ev_0\".\n    intros Hev1. inversion Hev1.\n  Case \"ev_SS\".\n    intros Hev3. inversion Hev3 as [|n' Hev1 Heqn'].\n    apply IHev in Hev1. inversion Hev1.  Qed.\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     from evidence for [P]. *)\n  Abort.\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\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\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 m H. destruct (beq_nat n m) eqn:E.\n  Case \"E = true\".\n    unfold not in H. apply ex_falso_quodlibet.\n    apply H. apply beq_nat_true. apply E.\n  Case \"E = false\".\n    reflexivity.  Qed.\n(** [] *)\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 m. destruct (beq_nat n m) eqn:E.\n  Case \"E = true\".\n    intros contra. inversion contra.\n  Case \"E = false\".\n    unfold not. intros eq1 eq2. rewrite -> eq2 in E.\n    rewrite <- beq_nat_refl in E. inversion E.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (ble_nat_false) *)\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros n m. destruct (ble_nat n m) eqn:E.\n  Case \"E = true\".\n    intros contra. inversion contra.\n  Case \"E = false\".\n    unfold not. intros eq1 eq2. apply le_ble_nat in eq2.\n    rewrite -> eq2 in E. inversion E.  Qed.\n(** [] *)\n\n\n\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P].\n\n*)\n\n\n(** Coq's [Notation] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2).\n  reflexivity.  Qed.\n\n(** Note that we have to explicitly give the witness. *)\n\n(** Or, instead of writing [apply ex_intro with (witness:=e)] all the\n    time, we can use the convenient shorthand [exists e], which means\n    the same thing. *)\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity.  Qed.\n\n(** 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(** **** 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  unfold not. intros X P H1 H2.\n  inversion H2 as [x Hx]. apply Hx. apply H1.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  intros Hem X P H x.\n  assert (Hem': P x \\/ ~ P x).\n    apply Hem.\n  inversion Hem' as [HP | HNP].\n  Case \"Hem' = P x\".\n    apply HP.\n  Case \"Hem' = ~ P x\".\n    apply ex_falso_quodlibet. apply H.\n    exists x. apply HNP.  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  Case \"->\".\n    intros H. inversion H as [x Hx].\n    inversion Hx as [HP | HQ].\n    SCase \"Hx = P x\".\n      left. exists x. apply HP.\n    SCase \"Hx = Q x\".\n      right. exists x. apply HQ.\n  Case \"<-\".\n    intros H. inversion H as [HP | HQ].\n    SCase \"H = HP\".\n      inversion HP as [x Hx]. exists x. left. apply Hx.\n    SCase \"H = HQ\".\n      inversion HQ as [x Hx]. exists x. right. apply Hx.  Qed.\n(** [] *)\n\n(* Print dist_exists_or. *)\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has (roughly)\n    the following inductive definition. *)\n\n(* (We enclose the definition in a module to avoid confusion with the\n    standard library equality, which we have used extensively\n    already.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n  refl_equal : forall x, eq x x.\n(** Standard infix notation: *)\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(** The definition of [=] is a bit subtle.  The way to think about it\n    is that, given a set [X], it defines a _family_ of propositions\n    \"[x] is equal to [y],\" indexed by pairs of values ([x] and [y])\n    from [X].  There is just one way of constructing evidence for\n    members of this family: applying the constructor [refl_equal] to a\n    type [X] and a value [x : X] yields evidence that [x] is equal to\n    [x]. *)\n\n\n(** **** Exercise: 2 stars (leibniz_equality) *)\n(** The inductive definitions of equality corresponds to _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 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. inversion H as [z H1 H2].\n  intros Py. apply Py.  Qed.\n(** [] *)\n\n(** 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 compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n*)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply refl_equal.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\nto now is essentially just short-hand for [apply refl_equal]. *)\n\nEnd MyEquality.\n\n\n(* ###################################################### *)\n(** * Evidence-carrying booleans. *)\n\n(** So far we've seen two different forms of equality predicates:\n[eq], which produces a [Prop], and\nthe type-specific forms, like [beq_nat], that produce [boolean]\nvalues.  The former are more convenient to reason about, but\nwe've relied on the latter to let us use equality tests\nin _computations_.  While it is straightforward to write lemmas\n(e.g. [beq_nat_true] and [beq_nat_false]) that connect the two forms,\nusing these lemmas quickly gets tedious.\n\nIt turns out that we can get the benefits of both forms at once\nby using a construct called [sumbool]. *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\nNotation \"{ A } + { B }\" :=  (sumbool A B) : type_scope.\n\n(** Think of [sumbool] as being like the [boolean] type, but instead\nof its values being just [true] and [false], they carry _evidence_\nof truth or falsity. This means that when we [destruct] them, we\nare left with the relevant evidence as a hypothesis -- just as with [or].\n(In fact, the definition of [sumbool] is almost the same as for [or].\nThe only difference is that values of [sumbool] are declared to be in\n[Set] rather than in [Prop]; this is a technical distinction\nthat allows us to compute with them.) *)\n\n(** Here's how we can define a [sumbool] for equality on [nat]s *)\n\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      left. reflexivity.\n    SCase \"m = S m'\".\n      right. intros contra. inversion contra.\n  Case \"n = S n'\".\n    intros m.\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      right. intros contra. inversion contra.\n    SCase \"m = S m'\".\n      destruct IHn' with (m := m') as [eq | neq].\n      left. apply f_equal.  apply eq.\n      right. intros Heq. inversion Heq as [Heq']. apply neq. apply Heq'.\nDefined.\n\n(** Read as a theorem, this says that equality on [nat]s is decidable:\nthat is, given two [nat] values, we can always produce either\nevidence that they are equal or evidence that they are not.\nRead computationally, [eq_nat_dec] takes two [nat] values and returns\na [sumbool] constructed with [left] if they are equal and [right]\nif they are not; this result can be tested with a [match] or, better,\nwith an [if-then-else], just like a regular [boolean].\n(Notice that we ended this proof with [Defined] rather than [Qed].\nThe only difference this makes is that the proof becomes _transparent_,\nmeaning that its definition is available when Coq tries to do reductions,\nwhich is important for the computational interpretation.)\n\nHere's a simple example illustrating the advantages of the [sumbool] form. *)\n\nDefinition override' {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if eq_nat_dec k k' then x else f k'.\n\nTheorem override_same' : forall (X:Type) x1 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f. intros Hx1.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).   (* observe what appears as a hypothesis *)\n  Case \"k1 = k2\".\n    rewrite <- e. \n    symmetry. apply Hx1.\n  Case \"k1 <> k2\".\n    reflexivity.  Qed.\n\n(** Compare this to the more laborious proof (in MoreCoq.v) for the\n   version of [override] defined using [beq_nat], where we had to\n   use the auxiliary lemma [beq_nat_true] to convert a fact about booleans\n   to a Prop. *)\n\n\n(** **** Exercise: 1 star (override_shadow') *)\nTheorem override_shadow' : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  (override' (override' f k1 x2) k1 x1) k2 = (override' f k1 x1) k2.\nProof.\n  intros x x1 x2 k1 k2 f. unfold override'.\n  destruct (eq_nat_dec k1 k2).\n  Case \"k1 = k2\". reflexivity.\n  Case \"k1 <> k2\". reflexivity.  Qed.\n(** [] *)\n\n(* ####################################################### *)\n(** ** Inversion, Again (Advanced) *)\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(** **** Exercise: 1 star, optional (dist_and_or_eq_implies_and) *)\nLemma dist_and_or_eq_implies_and : forall P Q R,\n       P /\\ (Q \\/ R) /\\ Q = R -> P/\\Q.\nProof.\n  intros P Q R H.\n  inversion H as [HP H'].\n  inversion H' as [HQR H''].\n  inversion HQR as [HQ | HR].\n  Case \"HQR = Q\".\n    split. apply HP. apply HQ.\n  Case \"HQR = R\".\n    split. apply HP. rewrite -> H''. apply HR.  Qed.\n(** [] *)\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  | all_nil : all X P nil\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 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\nTheorem forallb_correct : forall X f l,\n  all X (fun x => f x = true) l <-> forallb f l = true.\nProof.\n  intros X f l. split.\n  Case \"->\".\n    intros H. induction H as [| x xs HP H' Hl].\n    SCase \"H = []\".\n      reflexivity.\n    SCase \"H = x :: xs\".\n      simpl. rewrite -> HP. rewrite -> Hl. reflexivity.\n  Case \"<-\".\n    intros H. induction l as [| x xs].\n    SCase \"l = []\".\n      apply all_nil.\n    SCase \"l = x :: xs\".\n      simpl in H. apply all_cons.\n      SSCase \"P x\".\n        apply andb_true_elim1 in H. apply H.\n      SSCase \"all X P l\".\n        apply IHxs. apply andb_true_elim2 in H. apply H.  Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example,\n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\nInductive merge {X : Type} : list X -> list X -> list X -> Prop :=\n  | m_nil : forall (l : list X), merge [] [] []\n  | m_1 : forall x xs ys l, merge xs ys l -> merge (x :: xs) ys (x :: l)\n  | m_2 : forall y xs ys l, merge xs ys l -> merge xs (y :: ys) (y :: l).\n\nTheorem filter_correct : forall X (l l1 l2: list X) (test : X -> bool),\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.\n  intros X l. induction l as [| z l'].\n  Case \"l = []\".\n    intros l1 l2 test H H1 H2.\n    inversion H. reflexivity.\n  Case \"l = z :: l'\".\n    intros l1 l2 test H.\n    inversion H.\n    SCase \"m_1\".\n      intros Hall1 Hall2. inversion Hall1.\n      SSCase \"all_cons\".\n        simpl. rewrite -> H7. apply f_equal.\n        apply IHl' with (l2:=l2).\n          apply H3. apply H8. apply Hall2.\n    SCase \"m_2\".\n      intros Hall1 Hall2. inversion Hall2.\n      SSCase \"all_cons\".\n        simpl. rewrite -> H7.\n        apply IHl' with (l2:=ys).\n          apply H3. apply Hall1. apply H8.  Qed.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\nInductive subseq {X : Type} : list X -> list X -> Prop :=\n  | s_nil : forall l, subseq nil l\n  | s_1 : forall x l1 l2, subseq l1 l2 -> subseq (x :: l1) (x :: l2)\n  | s_2 : forall x l1 l2, subseq l1 l2 -> subseq l1 (x :: l2).\n\nTheorem filter_challenge_2 : forall X (l k: list X) (test : X -> bool),\n  subseq k l -> all X (fun x => test x = true) k -> subseq k (filter test l).\nProof.\n  intros X l. induction l as [| x l'].\n  Case \"l = []\".\n    intros k test H Hall. simpl. apply H.\n  Case \"l = x :: l'\".\n    intros k test H.\n    inversion H.\n    SCase \"s_nil\".\n      intros Hall. apply s_nil.\n    SCase \"s_1\".\n      intros Hall. simpl. inversion Hall. rewrite -> H6.\n      apply s_1. apply IHl'. apply H2. apply H7.\n    SCase \"s_2\".\n      intros Hall. simpl. destruct (test x).\n      SSCase \"test x = true\".\n        apply s_2. apply IHl'. apply H2. apply Hall.\n      SSCase \"test x = false\".\n        apply IHl'. apply H2. apply Hall.  Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l].\n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall (X:Type) (xs ys : list X) (x:X),\n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  intros X xs ys x H.\n  induction xs as [| x' xs'].\n  Case \"xs = []\".\n    right. apply H.\n  Case \"xs = x' :: xs'\".\n    inversion H.\n    SCase \"ai_here\".\n      left. apply ai_here.\n    SCase \"ai_later\".\n      apply IHxs' in H1. inversion H1.\n      SSCase \"left\".\n        left. apply ai_later. apply H3.\n      SSCase \"right\".\n        right. apply H3.  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 X xs ys x H. induction xs as [| x' xs'].\n  Case \"xs = []\".\n    inversion H as [Hleft | Hright].\n    SCase \"left\". inversion Hleft.\n    SCase \"right\". apply Hright.\n  Case \"xs = x' :: xs'\".\n    inversion H as [Hleft| Hright].\n    SCase \"left\".\n      inversion Hleft.\n      SSCase \"ai_here\".\n        apply ai_here.\n      SSCase \"ai_later\".\n        simpl. apply ai_later. apply IHxs'. left. apply H1.\n    SCase \"right\".\n      simpl. apply ai_later. apply IHxs'. right. apply Hright.  Qed.\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\nInductive disjoint {X : Type}: list X -> list X -> Prop :=\n  | dj_nil: forall l, disjoint [] l\n  | dj_cons: forall x l1 l2, ~ appears_in x l2 -> disjoint l1 l2 -> disjoint (x :: l1) 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\nInductive no_repeats {X : Type} : 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\nTheorem nr_disjoint : forall X (l1 l2: list X),\n  no_repeats (l1 ++ l2) -> disjoint l1 l2.\nProof.\n  intros. induction l1 as [| x xs].\n  Case \"l1 = []\".\n    apply dj_nil.\n  Case \"l1 = x :: xs\".\n    apply dj_cons.\n      unfold not. intros. inversion H. apply H3. apply app_appears_in. right. apply H0.\n      apply IHxs. inversion H. apply H3.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n  | ns_nil : nostutter []\n  | ns_singl : forall x, nostutter [x]\n  | ns_cons : forall x y l, x <> y -> nostutter (y :: l) -> nostutter (x :: y :: 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_nat_false; auto. Qed.\n\nExample test_nostutter_2:  nostutter [].\nProof. repeat constructor; apply beq_nat_false; auto. Qed.\n\nExample test_nostutter_3:  nostutter [5].\nProof. repeat constructor; apply beq_nat_false; 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 H1; auto. Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some\n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2. induction l1 as [| x xs].\n  Case \"l1 = []\".\n    reflexivity.\n  Case \"l2 = x :: xs\".\n    simpl. apply f_equal. apply IHxs.  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. induction H.\n  Case \"ai_here\".\n    exists []. exists l. reflexivity.\n  Case \"ai_later\".\n    inversion IHappears_in as [ms H1]. exists (b :: ms).\n    inversion H1 as [ns H2]. exists ns.\n    simpl. rewrite H2. reflexivity.  Qed.\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  | rep_here: forall x xs, appears_in x xs -> repeats (x :: xs)\n  | rep_later: forall x xs, repeats xs -> repeats (x :: xs).\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(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "tymmym", "repo": "software-foundations", "sha": "940149ef3e1e5ae7640497ba392a4e3667dd0412", "save_path": "github-repos/coq/tymmym-software-foundations", "path": "github-repos/coq/tymmym-software-foundations/software-foundations-940149ef3e1e5ae7640497ba392a4e3667dd0412/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7696201884765969}}
{"text": "(* Binary representation of the positive integers. *)\n\nInductive pos: Set :=\n  | bI: pos\n  | b0: pos -> pos\n  | b1: pos -> pos.\n\n(* For illustration, we can interpret these as naturals. *)\n\nFixpoint nat_of (p: pos): nat :=\n  match p with\n    | (* Initial one bit. *)\n      bI => 1\n    | (* Shift left plus zero. *)\n      b0 p => 2 * nat_of p\n    | (* Shift left plus one. *)\n      b1 p => S (2 * nat_of p)\n  end.\n\n(* In this interpretation, we read bits right-to-left. *)\n\nExample eg_11: nat_of (b1 (b1 (b0 bI))) = 11. simpl. reflexivity. Qed.\nExample eg_12: nat_of (b0 (b0 (b1 bI))) = 12. simpl. reflexivity. Qed.\nExample eg_13: nat_of (b1 (b0 (b1 bI))) = 13. simpl. reflexivity. Qed.\n\n(* A successor function consistent with this interpretation. *)\n\nFixpoint succ (p: pos): pos :=\n  match p with\n    | (* Carry the one. *)\n      bI => b0 bI\n    | (* Increment the least-significant bit. *)\n      b0 q => b1 q\n    | (* Carry the one. *)\n      b1 q => b0 (succ q)\n  end.\n\n(* Challenge: prove a nat-like induction principle for `pos`. *)\n(* This is a bit tricky, so I've given you a head start. *)\n\nDefinition pos_succ_rect:\n  forall (p: pos) (P: pos -> Type) (I: P bI) (S: forall p, P p -> P (succ p)), P p.\nProof.\n  induction p; intros P I S.\n  - (* Base case bI *)\n    assumption.\n  - (* Inductive case b0 *)\n    (* Note: when we apply IHp, we implicitly instantiate its P\n         with `fun p => P (b0 p)`! *)\n    apply IHp.\n    + (* Prove the first assumption of IHp, which corresponds to I,\n           but with the specialised P. *)\n      (* Look at the next sub-case for some hints. *)\n      admit.\n    + (* Prove the second assumption of IHp, which corresponds to S,\n           but with the specialised P. *)\n      intros q H.\n      (* The `change` tactic replaces the current goal with another,\n           provided it has the same normal form. *)\n      (* Here, `P (succ (succ (b0 q)))` could be simplified\n           to `P (b0 (succ q))`, so this `change` is allowed. *)\n      change (P (succ (succ (b0 q)))).\n      (* We use the S we were given to prove IHp's S, but since we\n           have lifted IHp's P over b0, we need to apply S twice! *)\n      apply S. apply S. apply H.\n  - (* Inductive case b1 *)\n    (* Should be somewhat similar to the b0 case! *)\n    admit.\nDefined.\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/L01-pos-induct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7696201884765967}}
{"text": "Inductive even : nat -> Prop :=\n|EvenO : even 0\n|EvenSS : forall n : nat, even n -> even(S(S n)).\n\n\nTheorem even_0 : even 0.\nProof.\napply EvenO.\nQed.\n\nTheorem even_4 : even 4.\nProof.\napply EvenSS.\napply EvenSS.\napply EvenO.\nQed.\n\nTheorem even_4_1 : even 4.\nProof.\nconstructor. constructor. constructor.\nQed.\n\n(*\nHint Resolve EvenO.\nHint Resolve EvenSS.\n*)\n\nHint Constructors even.\n\nTheorem even_4_2 : even 4.\nProof.\nauto.\nQed.\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/Auto/Auto1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7695940821664246}}
{"text": "(**\nフィボナッチ数列の加法定理\n========================\n\n@suharahiromichi\n\n2020/07/01\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import ssromega.\nRequire Import Recdef.                      (* Function *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n# はじめに\n\nフィボナッチ ffibonacci 数列には、加法定理 addition theorem\n(加法法則 addition law) が成り立ちます。 $ 1 \\le m$ のとき、\n\n$$ F_{n + m} = F_m F_{n+1} + F_{m-1} F_n $$\n\nフィボナッチ数列の定義は、だれでも知っている単純なものですが、\n1個前と2個前の項を参照する、という意味で、帰納法としては複雑なかたちをしています。\n\nそこで、Coqの「特定の再帰関数に専用の帰納法」のための\nコマンド ``functional induction`` を使って解いてみましょう。\n\nこのファイルは、以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_add_law.v\n\n\nまた、\n\nhttps://github.com/suharahiromichi/coq/blob/master/common/ssromega.v\n\n\nも必要です。\n *)\n\nSection Fib_2.\n\n(**\n# fibonacci 関数の定義\n\n``functional induction`` を使うためには、\n関数を``Fixpoint``ではなく、``Function``で定義する必要があります。\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(**\n``Function``コマンドをで定義すると、``functional induction``を行うための``fib_ind``が定義されます。\n *)\n  Check fib_ind\n    : forall P : nat -> nat -> Prop,\n      (forall m : nat, m = 0 -> P 0 0) ->\n      (forall m : nat, m = 1 -> P 1 1) ->\n      (forall m k : nat,\n          m = k.+2 -> P k (fib k) -> P k.+1 (fib k.+1) -> P k.+2 (fib k + fib k.+1)) ->\n      forall m : nat, P m (fib m).\n\n\n(**  \n簡単にいうと、命題 P(m, F_m) に対して、次の帰納法で証明することができます。\n\n- 命題が、P(0, F_0) で成り立つ場合を証明する。F_0 = 0 なので P(0, 0)\n- 命題が、P(1, F_1) で成り立つ場合を証明する。F_1 = 1 なので P(1, 1)\n- 命題が、P(k, F_k) と P(m=k+1, F_k+1) で成り立つと仮定して、P(m=k+2, F_k + F_k+1)\nで成り立つこと証明する。\n- 以上から、命題は、任意の P(m, F_m) で成り立つ。\n\nつまり、フィボナッチ数列の定義そのものですね。\n*)  \n  \n(**\nまた、関数の展開をするための``fib_equation``が定義されます。\n *)\n  Check fib_equation\n    : forall n : nat,\n      fib n = match n with\n              | 0 => 0\n              | 1 => 1\n              | (m.+1 as pn).+1 => fib m + fib pn\n              end.\n\n\n(**  \n``Function`` で関数を定義すると、\n関数を展開するunfoldタクティクが、事実上、使用不能になるため、\n代わりに ``rewrite fib_equation`` による書き換えを可能にするためのものです。\nなお、今回は使用しません。\n*)  \n\n(**\n# 補題\n\n定義から導かれる、簡単な補題を証明しておきます。\n*)  \n  Lemma fib_n n : fib n.+2 = fib n + fib n.+1.\n  Proof.\n    done.\n  Qed.\n\n(**\n# フィボナッチ数列の加法定理\n\n最初にCoqで扱い易い、引き算の無いかたちで証明します。\nこの場合 n、m とも任意の自然数でよいです。\n\n$$ F_{n + m + 1} = F_{m + 1} F_{n+1} + F_m F_n $$\n *)\n  Lemma fib_addition' n m :\n    fib (n + m.+1) = fib m.+1 * fib n.+1 + fib m * fib n.\n  Proof.\n(**\nF_m に対する帰納法をおおこなう。mだけの帰納法ではない。\n*)\n    functional induction (fib m).\n\n(**\n- P(m=0, F_0) を証明する。\n*)\n    - rewrite addn1.\n      rewrite [fib 1]/= mul1n mul0n addn0.\n      done.\n      \n(**\n- P(m=1, F_1) を証明する。\n*)\n    - rewrite addn2.\n      rewrite [fib 2]/= add0n 2!mul1n.\n      rewrite addnC -fib_n.\n      done.\n      \n(**\n- IHn0 : P(m=m, F_m) で成り立つ。\n- IHn1 : P(m=m+1, F_m+1) で成り立つ。\n- Goal : P(m=m+2, F_m + F_m+1) で成り立つことを証明する。\n\n前節での説明上の k が、ここでは m になっています。\n*)\n    - rewrite fib_n 2!mulnDl.\n      \n      (* F_(n + m.+1) の項をまとめて置き換える *)\n      rewrite ?addnA [_ + fib m * fib n]addnC. (* この項を先頭に。 *)\n      rewrite ?addnA [_ + fib m.+1 * fib n.+1]addnC ?addnA. (* この項を先頭に。 *)\n      rewrite -IHn0.\n       \n      (* F_(n + m.+2) の項をまとめて置き換える *)\n      rewrite ?addnA [_ + fib m.+1 * fib n]addnC. (* この項を先頭に。 *)\n      rewrite ?addnA [_ + fib m.+2 * fib n.+1]addnC ?addnA. (* この項を先頭に。 *)\n      rewrite -IHn1.\n      \n      have -> : n + m.+3 = (m + n).+3 by ssromega.\n      have -> : n + m.+2 = (m + n).+2 by ssromega.\n      have -> : n + m.+1 = (m + n).+1 by ssromega.\n      rewrite fib_n.\n      rewrite [fib (m + n).+2 + fib (m + n).+1]addnC.\n      done.\n  Qed.\n\n(**\n最後に、$1 \\le m$ の条件のもとで、定理を証明します。\n\n$$ F_{n + m} = F_m F_{n+1} + F_{m-1} F_n $$\n*)  \n  Lemma fib_addition n m :\n    1 <= m -> fib (n + m) = fib m * fib n.+1 + fib m.-1 * fib n.\n  Proof.\n    move=> H.\n    have H' := fib_addition' n m.-1.\n      by rewrite prednK in H'.\n  Qed.\n\n(**\n``n - 1 + 1 = n`` をいうためには、``0 < n`` の条件が必要です。\nこれは、n が自然数の0のとき、``0 - 1 = 0`` となるためです。\n*)\n\n  Check prednK : forall n : nat, 0 < n -> n.-1.+1 = n.\n\nEnd Fib_2.\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_add_law.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7695640360164712}}
{"text": "Require Import vcfloat.VCFloat.\nRequire Import List.\nRequire Import common op_defs list_lemmas float_acc_lems.\nRequire Import FunctionalExtensionality.\n\nRequire Import Reals.\nOpen Scope R.\n\nImport ListNotations.\n\nSection DotProd.\nContext {NAN : Nans} {t : type}.\n\n(* Standard floating-point dot-product *)\nDefinition dotprod (v1 v2: list (ftype t)) : ftype t :=\n  fold_left (fun s x12 => BPLUS (BMULT (fst x12) (snd x12)) s) \n                (List.combine v1 v2) (Zconst t 0).\n\nInductive dot_prod_rel : \n            list (ftype t * ftype t) -> ftype t -> Prop :=\n| dot_prod_rel_nil  : dot_prod_rel  nil (Zconst t 0)\n| dot_prod_rel_cons : forall l (xy : ftype t * ftype t) s,\n    dot_prod_rel  l s ->\n    dot_prod_rel  (xy::l) (BPLUS (BMULT  (fst xy) (snd xy)) s).\n\nLemma dot_prod_rel_fold_right :\nforall (v1 v2: list (ftype t)), \n    dot_prod_rel (rev (List.combine v1 v2)) (dotprod v1 v2).\nProof.\nintros v1 v2. \n unfold dotprod; rewrite <- fold_left_rev_right. \ninduction (rev (List.combine v1 v2)).\n{ simpl; auto. apply dot_prod_rel_nil. }\nsimpl. apply dot_prod_rel_cons. auto.\nQed.\n\nEnd DotProd.\n\nSection FMADotProd.\nContext {NAN : Nans} {t : type}.\n\n(* FMA dot-product *)\nDefinition fma_dotprod (v1 v2: list (ftype t)) : ftype t :=\n  fold_left (fun s x12 => BFMA (fst x12) (snd x12) s) \n                (List.combine v1 v2) (Zconst t 0).\n\nInductive fma_dot_prod_rel : \n            list (ftype t * ftype t) -> ftype t -> Prop :=\n| fma_dot_prod_rel_nil  : fma_dot_prod_rel nil (Zconst t 0)\n| fma_dot_prod_rel_cons : forall l (xy : ftype t * ftype t) s,\n    fma_dot_prod_rel  l s ->\n    fma_dot_prod_rel  (xy::l) (BFMA (fst xy) (snd xy) s).\n\n\nLemma fma_dot_prod_rel_fold_right  :\nforall (v1 v2: list (ftype t)), \n    fma_dot_prod_rel (rev (List.combine v1 v2)) (fma_dotprod v1 v2).\nProof.\nintros v1 v2. \n unfold fma_dotprod; rewrite <- fold_left_rev_right. \ninduction (rev (List.combine v1 v2)).\n{ simpl; auto. apply fma_dot_prod_rel_nil. }\nsimpl. apply fma_dot_prod_rel_cons. auto.\nQed.\n\nEnd FMADotProd.\n\nSection RealDotProd.\n\n(* Dot-product over the reals *)\nDefinition dotprodR l1 l2 : R := \n  fold_left Rplus (map (uncurry Rmult) (List.combine l1 l2)) 0%R.\n\nInductive R_dot_prod_rel : \n            list (R * R) -> R -> Prop :=\n| R_dot_prod_rel_nil  : R_dot_prod_rel  nil 0%R\n| R_dot_prod_rel_cons : forall l xy s,\n    R_dot_prod_rel  l s ->\n    R_dot_prod_rel  (xy::l)  (fst xy * snd xy + s).\n\nLemma R_dot_prod_rel_eq :\n  forall l a b \n  (Ha: R_dot_prod_rel l a)\n  (Hb: R_dot_prod_rel l b), a = b.\nProof.\ninduction l.\n{ intros; inversion Ha; inversion Hb; auto. }\nintros; inversion Ha; inversion Hb; subst; f_equal. \napply IHl; auto.\nQed.\n\nDefinition Rabsp p : R * R := (Rabs (fst p), Rabs (snd p)).\n\nDefinition FR2 {t: type} (x12: ftype t * ftype t) := (FT2R (fst x12), FT2R (snd x12)).\n\nLemma FT2R_FR2 t : \n  (forall a a0 : ftype t, (FT2R a, FT2R a0) = FR2 (a, a0)) .\nProof. intros. unfold FR2; simpl; auto. Qed.\n\nDefinition sum_fold: list R -> R := fold_right Rplus 0%R.\n\nLemma dotprodR_nil_l u:\ndotprodR nil u = 0%R. \nProof. simpl; auto. Qed.\n\nLemma dotprodR_nil_r u:\ndotprodR u nil = 0%R. \nProof. unfold dotprodR; rewrite combine_nil; simpl; auto. Qed.\n\nLemma sum_rev l:\nsum_fold l = sum_fold (rev l).\nProof.\nunfold sum_fold. \nrewrite fold_left_rev_right.\nreplace (fun x y : R => y + x) with Rplus\n by (do 2 (apply FunctionalExtensionality.functional_extensionality; intro); lra).\ninduction l; simpl; auto.\nrewrite IHl.\nrewrite <- fold_left_Rplus_0; f_equal; nra.\nQed.\n\nLemma dotprodR_rel :\nforall (v1 v2: list R) , \n    R_dot_prod_rel ((List.combine v1 v2)) (dotprodR v1 v2).\nProof.\nintros; unfold dotprodR;\ninduction (((combine v1 v2))).\n{ simpl. apply R_dot_prod_rel_nil. }\ndestruct a; simpl. \nunfold dotprodR. simpl.\nrewrite fold_left_Rplus_Rplus.\napply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma dotprodR_rev : forall (v1 v2: list R) , \n  length v1 = length v2 -> \n  dotprodR v1 (rev v2) = dotprodR (rev v1) v2.\nProof.\nintros; unfold dotprodR.\nreplace (combine v1 (rev v2)) with\n  (rev (combine (rev v1) v2)).\nrewrite <- fold_left_rev_right.\nreplace (fun x y : R => y + x) with Rplus\n by (do 2 (apply functional_extensionality; intro); lra).\nsymmetry.\ninduction (combine (rev v1) v2).\nsimpl; auto.\nmatch goal with |- context [?A = ?B] =>\nset (y:= B)\nend. \nsimpl. subst y.\nrewrite fold_left_Rplus_Rplus.\nrewrite IHl.\nrewrite !map_rev, !rev_involutive.\nsimpl; auto.\nrewrite <- combine_rev, rev_involutive; auto.\nrewrite rev_length; auto.\nQed.\n\nLemma R_dot_prod_rel_fold_right t :\nforall (v1 v2: list (ftype t)) , \n   let prods := map (uncurry Rmult) (map FR2 (List.combine v1 v2)) in\n    R_dot_prod_rel (rev (map FR2 (List.combine v1 v2))) (sum_fold prods).\nProof.\nintros. subst prods. rewrite sum_rev. rewrite <- !map_rev.\ninduction (map FR2 (rev (combine v1 v2))).\n{ simpl. apply R_dot_prod_rel_nil. }\ndestruct a; simpl. apply R_dot_prod_rel_cons; auto.\nQed.\n\n\nLemma R_dot_prod_rel_fold_right_Rabs t :\nforall (v1 v2: list (ftype t)) , \n   let prods := map (uncurry Rmult) (map Rabsp (map FR2 (List.combine v1 v2))) in\n    R_dot_prod_rel (rev (map Rabsp (map FR2 (List.combine v1 v2)))) (sum_fold prods).\nProof.\nintros. subst prods. rewrite sum_rev. rewrite <- !map_rev.\ninduction (map Rabsp (map FR2 (rev (combine v1 v2)))).\n{ simpl. apply R_dot_prod_rel_nil. }\ndestruct a; simpl. apply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma R_dot_prod_rel_single rs a:\nR_dot_prod_rel [a] rs -> rs = (fst a * snd a).\nProof.\nintros.\ninversion H.\ninversion H3; subst; nra.\nQed.\n\nLemma R_dot_prod_rel_single' a:\nR_dot_prod_rel [a] (fst a * snd a).\nProof.\nreplace (fst a * snd a) with (fst a * snd a + 0) by nra.\napply R_dot_prod_rel_cons; apply R_dot_prod_rel_nil.\nQed.\n\nLemma R_dot_prod_rel_Rabs_eq :\nforall l s,\nR_dot_prod_rel (map Rabsp l) s -> Rabs s = s.\nProof.\ninduction  l.\n{ intros.\ninversion H.\nrewrite Rabs_R0.\nnra. }\nintros.\ninversion H; subst; clear H.\nunfold Rabsp. destruct a; simpl.\nreplace (Rabs(Rabs r * Rabs r0 + s0)) with \n  (Rabs r * Rabs r0 + s0); try nra.\nsymmetry.\nrewrite Rabs_pos_eq; try nra.\napply Rplus_le_le_0_compat.\napply Rmult_le_pos;\napply Rabs_pos.\nrewrite <- IHl; try apply Rabs_pos; auto.\nQed.\n\nLemma dot_prod_sum_rel_R_Rabs :\nforall l s1 s2,\nR_dot_prod_rel l s1 -> R_dot_prod_rel (map Rabsp l) s2 -> Rabs s1 <= Rabs s2.\nProof.\ninduction l.\n{ intros.\ninversion H.\ninversion H0.\nnra. }\nintros.\ninversion H; subst; clear H.\ninversion H0; subst; clear H0.\nunfold Rabsp; destruct a; simpl.\neapply Rle_trans; [\napply Rabs_triang |].\nreplace (Rabs (Rabs r * Rabs r0 + s0)) with \n  (Rabs r * Rabs r0 + s0).\neapply Rplus_le_compat; try nra.\nrewrite Rabs_mult; nra.\nrewrite <- (R_dot_prod_rel_Rabs_eq l); auto.\nsymmetry.\nrewrite Rabs_pos_eq; try nra.\napply Rplus_le_le_0_compat.\napply Rmult_le_pos;\napply Rabs_pos.\nrewrite <- (R_dot_prod_rel_Rabs_eq l); auto.\napply Rabs_pos.\nQed.\n\nLemma dot_prod_combine_map_Rmult a u v r:\nlength u = length v ->\nR_dot_prod_rel (combine u v) r -> \nR_dot_prod_rel (combine (map (Rmult a) u) v) (a * r). \nProof. revert u r. induction v.\n{ intros. rewrite !combine_nil in *.  \n  inversion H0; subst; rewrite Rmult_0_r; apply R_dot_prod_rel_nil. }\ndestruct u.\n  { intros; pose proof Nat.neq_0_succ (length v); try contradiction. }\n  intros.   inversion H0. assert (Hlen: length u = length v) by (simpl in H; lia).\n  specialize (IHv u s Hlen H4).\n  simpl. replace (a * (r * a0 + s)) with \n    (a * r * a0 + a * s) by nra. apply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma dotprod_rel_R_exists {NAN: Nans}:\n  forall (t : type) (l : list (ftype t * ftype t)) (fp : ftype t)\n  (Hfp : dot_prod_rel l fp),\n  exists rp, R_dot_prod_rel (map FR2 l) rp.\nProof.\nintros ?. induction l.\n{ simpl; exists 0. apply R_dot_prod_rel_nil. }\nintros. inversion Hfp; subst. \ndestruct (IHl s H2) as (rs & Hrs); clear IHl.\nexists (FT2R (fst a) * FT2R (snd a) + rs); simpl. \napply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma dotprod_rel_R_exists_fma {NAN: Nans}:\n  forall (t : type) (l : list (ftype t * ftype t)) (fp : ftype t)\n  (Hfp : fma_dot_prod_rel l fp),\n  exists rp, R_dot_prod_rel (map FR2 l) rp.\nProof.\nintros ?. induction l.\n{ simpl; exists 0. apply R_dot_prod_rel_nil. }\nintros. inversion Hfp; subst. \ndestruct (IHl s H2) as (rs & Hrs); clear IHl.\nexists (FT2R (fst a) * FT2R (snd a) + rs); simpl. \napply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma sum_rel_R_abs_exists_fma {NAN: Nans}:\n  forall (t : type) (l : list (ftype t * ftype t)) (fp : ftype t)\n  (Hfp : fma_dot_prod_rel l fp),\n  exists rp, R_dot_prod_rel (map Rabsp (map FR2 l)) rp.\nProof.\nintros ?. induction l.\n{ simpl; exists 0. apply R_dot_prod_rel_nil. }\nintros. inversion Hfp; subst. \ndestruct (IHl s H2) as (rs & Hrs); clear IHl.\nexists (Rabs (FT2R (fst a)) * Rabs (FT2R (snd a)) + rs); simpl. \napply R_dot_prod_rel_cons; auto.\nQed.\n\nLemma dotprodR_rel_bound'  :\n  forall (t : type) (l : list (ftype t * ftype t)) (rp a: R)\n  (Ha : 0 <= a)\n  (Hrp : R_dot_prod_rel (map FR2 l) rp)\n  (Hin : forall x, In x l -> Rabs (FT2R (fst x)) <= sqrt a /\\ Rabs (FT2R (snd x)) <= sqrt a),\n  Rabs rp <= INR (length l) * a.\nProof.\ninduction l; intros.\n{ inversion Hrp; subst; simpl; rewrite Rabs_R0; nra. }\n  inversion Hrp; subst. \n  eapply Rle_trans; [apply Rabs_triang|].\n  eapply Rle_trans; [apply Rplus_le_compat | ].\n  rewrite Rabs_mult; apply Rmult_le_compat; try apply Rabs_pos.\n  apply Hin; simpl; auto.\n  apply Hin; simpl; auto.\n  apply IHl; auto; [ apply Ha| intros; apply Hin; simpl; auto].\n  rewrite sqrt_def; auto. apply Req_le;\n  replace (length (a::l)) with ( S(length l)) by auto. \n  rewrite S_INR; nra.\nQed.\n\nLemma dotprodR_rel_bound''  :\n  forall (t : type) (l : list (ftype t * ftype t)) (rs_abs a: R)\n  (Ha : 0 <= a)\n  (Hrp : R_dot_prod_rel (map Rabsp (map FR2 l)) rs_abs)\n  (Hin : forall x, In x l -> Rabs (FT2R (fst x)) <= sqrt a /\\ Rabs (FT2R (snd x)) <= sqrt a),\n  rs_abs <= INR (length l) * a.\nProof.\ninduction l; intros.\n{ inversion Hrp; subst; simpl; nra. }\n  inversion Hrp; subst. \n  eapply Rle_trans; [ apply Rplus_le_compat | ].\n  apply Rmult_le_compat; \n  [ destruct a; simpl; apply Rabs_pos | destruct a; simpl; apply Rabs_pos | | ].\n  apply Hin; simpl; auto.\n  apply Hin; simpl; auto.\n  apply IHl; auto; [ apply Ha| intros; apply Hin; simpl; auto].\n  rewrite sqrt_def; auto. apply Req_le;\n  replace (length (a::l)) with ( S(length l)) by auto. \n  rewrite S_INR; nra.\nQed.\n\n\nEnd RealDotProd.\n\n\nSection NonZeroDP.\nContext {NAN: Nans} {t : type}.\n\nVariables (v1 v2 : list (ftype t)).\nHypothesis (Hlen : length v1 = length v2).\n\nNotation v1R := (map FT2R v1).\n\nLemma dot_prod_rel_nnzR :\nforall \n(fp : ftype t)\n(Hfp : dot_prod_rel (combine v1 v2) fp)\n(Hfin: Binary.is_finite (fprec t) (femax t) fp = true),\nnnzR v1R = 0%nat -> FT2R fp = 0.\nProof.\nintros.\npose proof nnz_lemma _ _ v1R _ H.\nrevert H0 H Hfp Hlen Hfin. revert v2 fp.\ninduction v1; intros.\nsimpl in *; inversion Hfp; auto.\ndestruct v2; try discriminate; auto.\ninversion Hfp; subst.\nunfold fst, snd.\nassert (Hin: forall x : R, In x (map FT2R l) -> x = 0).\n{ intros. apply H0; simpl; auto. }\nassert (Hlen1:  length l = length l0) by (simpl; auto).\nassert (HFIN: Binary.is_finite (fprec t) (femax t) s = true).\n{ simpl in Hfin. destruct (BMULT a f); destruct s;\n  destruct s0; try discriminate; simpl in *; auto; \n  destruct s; try discriminate; auto.\n}\npose proof nnz_is_zero_cons _ (FT2R a) (map FT2R l) _ _ H as H1.\nspecialize (IHl l0 s Hin H1 H4 Hlen1 HFIN).\ndestruct (@BPLUS_accurate' t NAN (BMULT a f) s Hfin)\n  as (d & _ & Hacc).\nrewrite Hacc; clear Hacc.\nrewrite IHl.\nassert (HFIN2: Binary.is_finite (fprec t) (femax t) (BMULT a f) = true).\n{ simpl in Hfin. destruct (BMULT a f); destruct s; try discriminate; auto. } \nassert (Ha: FT2R a = 0).\napply H0; simpl; auto.\npose proof Bmult_0R _ _ HFIN2 Ha as H2; destruct H2; rewrite H2;\nsimpl; nra.\nQed.\n\nLemma fma_dot_prod_rel_nnzR :\nforall \n(fp : ftype t)\n(Hfp : fma_dot_prod_rel (combine v1 v2) fp)\n(Hfin: Binary.is_finite (fprec t) (femax t) fp = true),\nnnzR v1R = 0%nat -> FT2R fp = 0.\nProof.\nintros.\npose proof nnz_lemma _ _ v1R _ H.\nrevert H0 H Hfp Hlen Hfin. revert v2 fp.\ninduction v1; intros.\nsimpl in *; inversion Hfp; auto.\ndestruct v2; try discriminate; auto.\ninversion Hfp; subst.\nunfold fst, snd.\nassert (Hin: forall x : R, In x (map FT2R l) -> x = 0).\n{ intros. apply H0; simpl; auto. }\nassert (Hlen1:  length l = length l0) by (simpl; auto).\nassert (HFIN: Binary.is_finite (fprec t) (femax t) s = true).\n{ simpl in Hfin. destruct a; destruct f; destruct s;\n  destruct s0; destruct s1; destruct s; try discriminate; simpl in *; auto; \n  try discriminate; auto. }\npose proof nnz_is_zero_cons _ (FT2R a) (map FT2R l) _ _ H as H1.\nspecialize (IHl l0 s Hin H1 H4 Hlen1 HFIN).\nassert (Ha: FT2R a = 0).\napply H0; simpl; auto.\nrewrite (Bfma_mult_0R a f s  Hfin Ha).\nrewrite IHl; auto.\nQed.\n\n\nLemma R_dot_prod_rel_nnzR :\nforall \n(rp : R)\n(Hrp  : R_dot_prod_rel (map FR2 (combine v1 v2)) rp),\nnnzR v1R = 0%nat -> rp = 0.\nProof.\nintros ? ? H.\npose proof nnz_lemma _ _ v1R _ H.\nrevert H0 H Hrp  Hlen. revert v2 rp.\ninduction v1; intros.\nsimpl in *; inversion Hrp; auto.\ndestruct v2; try discriminate; auto.\ninversion Hrp; subst.\nunfold FR2, fst, snd.\nassert (Hin: forall x : R, In x (map FT2R l) -> x = 0).\n{ intros. apply H0; simpl; auto. }\nassert (Hlen1:  length l = length l0) by (simpl; auto).\npose proof nnz_is_zero_cons _ (FT2R a) (map FT2R l) _ _ H as H1.\nspecialize (IHl l0 s Hin H1 H4 Hlen1).\nrewrite IHl.\nspecialize (H0 (FT2R a)).\nrewrite H0; [|simpl;auto]; nra.\nQed.\n\n\nLemma R_dot_prod_rel_nnzR_abs :\nforall \n(rp_abs : R) \n(Hra : R_dot_prod_rel (map Rabsp (map FR2 (combine v1 v2))) rp_abs),\nnnzR v1R = 0%nat -> rp_abs = 0.\nProof.\nintros ? ? H.\npose proof nnz_lemma _ _ v1R  _ H.\nrevert H0 H Hra  Hlen. revert v2 rp_abs .\ninduction v1; intros.\nsimpl in *. inversion Hra. auto.\ndestruct v2; try discriminate; auto.\ninversion Hra; subst.\nunfold FR2, Rabsp, fst, snd.\nassert (Hin: forall x : R, In x (map FT2R l) -> x = 0).\n{ intros. apply H0; simpl; auto. }\nassert (Hlen1:  length l = length l0) by (simpl; auto).\npose proof nnz_is_zero_cons _ (FT2R a) (map FT2R l) _ _ H as H2.\nspecialize (IHl l0 s Hin H2 H4 Hlen1). \nrewrite IHl.\npose proof in_map Rabs (map FT2R (a::l)).\nspecialize (H0  (FT2R a)).\nrewrite H0; [|simpl;auto]. rewrite Rabs_R0. nra.\nQed.\n\n\nEnd NonZeroDP.", "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/dotprod_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7695640230920356}}
{"text": "Require Omega.   \nRequire Export Bool.\nRequire Export List.\nExport ListNotations.\nRequire Export Arith.\nRequire Export Arith.EqNat.\n\nTheorem ex_falso_quodlibet : forall (P:Set),\n  False -> P.\nProof.  intros P contra.\n  inversion contra.  \nQed.\n\nInductive minimal_in_list : nat -> list nat -> Prop :=\n  mil_Base : forall n, minimal_in_list n [n]\n| mil_Head : forall n m tl, n <= m -> minimal_in_list m tl -> minimal_in_list n (n::tl)\n| mil_Tail : forall n m tl, m <  n -> minimal_in_list m tl -> minimal_in_list m (n::tl).\n\n(*\nProgram Fixpoint minimal1 (l : list nat) (_ : length l > 0) : { n | minimal_in_list n l} :=\n  match l with  \n    [h] => h\n  | h::tl => let m := minimal1 tl _ in if leb h m then h else m\n  | _ => 0\n  end.\n\nObligation 1. apply mil_Base. Qed.\nObligation 2. remember (H0 h). destruct tl. apply ex_falso_quodlibet. apply n. reflexivity.\n                simpl. omega. Defined.\nObligation 3. admit. Defined.\nObligation 4. admit. Defined.\n*)\n\n(*Extraction \"minimal1.ml\" minimal1.*)\n\nLtac by_contradiction := try (simpl in *; omega; match goal with H:_ |- _ => inversion H end).\n\nHint Constructors minimal_in_list.\nTheorem minimal : \n  forall (l : list nat), length l > 0 -> { n | minimal_in_list n l}.\nProof. \n  intros. induction l. by_contradiction.\n    destruct l eqn: L. \n      exists a. auto. (*apply mil_Base.*)\n      assert (A: length (n::l0) > 0). simpl in *. omega.     \n      apply IHl in A. inversion A.\n      remember (le_gt_dec a x) as A1.\n      inversion A1. exists a. eauto. (*apply mil_Head with x; assumption.*)\n                    exists x. eauto. (*apply mil_Tail; assumption. *)\nDefined.\n\nExtraction Language Ocaml.\n\nExtraction \"minimal.ml\" minimal.\n\nPrint minimal.\nInductive list_sorted : list nat -> Prop :=\n  ls_Nil  : list_sorted []\n| ls_One  : forall n, list_sorted [n]\n| ls_Cons : forall n m tl, \n    list_sorted tl -> minimal_in_list m tl -> n <= m -> list_sorted (n::tl).\n\nInductive list_insert : nat -> list nat -> list nat -> Prop :=\n  li_Head : forall n tl, list_insert n tl (n::tl)\n| li_Tail : forall n m tl tl', list_insert n tl tl' -> list_insert n (m::tl) (m::tl').\n\nInductive list_permutation : list nat -> list nat -> Prop :=\n  lp_Nil  : list_permutation [] []\n| lp_Cons : forall n l l' m, \n   list_permutation l' l -> list_insert n l' m -> list_permutation m (n::l).\n\nLemma minimal_in_sorted : forall n l,\n  list_sorted (n::l) -> minimal_in_list n (n::l).\nProof. \n  intros. destruct l. \n    apply mil_Base.\n    inversion H. apply mil_Head with m; assumption.\nQed.\n\nLemma minimal_in_inserted : forall l' n m l,\n  minimal_in_list m l -> list_insert n l l' -> \n  (m <= n /\\ minimal_in_list m l') \\/ (n < m /\\ minimal_in_list n l').\nProof.\n  intro l'. induction l'. intros. inversion H0.\n    intros. \n      remember (le_lt_dec m n) as A. clear HeqA. inversion A.\n        clear A. left. split. assumption.\n          inversion H0. rewrite <- H6. rewrite <- H5. \n          apply le_lt_eq_dec in H1. inversion H1. apply mil_Tail. assumption. assumption.\n            rewrite <- H4. apply mil_Head with m. omega. assumption.\n          rewrite <- H4 in H. inversion H. rewrite <- H10 in H5. \n            inversion H5. rewrite <- H9. rewrite <- H2. rewrite <- H9. \n              apply mil_Head with n. assumption. apply mil_Base.\n          remember (le_lt_dec m1 n) as A. clear HeqA. inversion A.\n          apply (IHl' n m1 tl) in H11. inversion H11. inversion H13.\n            rewrite <- H2. apply mil_Head with m1. omega. assumption.\n            inversion H13. rewrite <- H2. apply mil_Head with n. omega. assumption. \n              assumption.\n          apply (IHl' n m1 tl) in H11. inversion H11. inversion H13.\n            rewrite <- H2. apply mil_Head with m1. omega. assumption.\n            inversion H13. rewrite <- H2. apply mil_Head with n. omega. assumption. \n              assumption.\n          apply (IHl' n m tl) in H11. inversion H11. inversion H12. rewrite <- H2.\n            apply mil_Tail. assumption. assumption. inversion H12. \n              apply lt_not_le in H13. apply ex_falso_quodlibet. apply H13. assumption.\n              assumption.\n        clear A. right. split. assumption.\n          inversion H0. rewrite <- H6. rewrite <- H5. apply mil_Head with m. omega. \n             assumption.\n          rewrite <- H4 in H. inversion H. rewrite <- H10 in H5. inversion H5.\n             apply mil_Tail. omega. apply mil_Base. \n          remember (le_lt_dec n m1) as A. clear HeqA. inversion A.\n          apply (IHl' n m1 tl) in H11. inversion H11. inversion H13.\n             assert (HA: a < a). omega. remember (lt_irrefl a). \n             apply ex_falso_quodlibet. apply n2. assumption.\n             inversion H13. apply mil_Tail. omega. assumption. assumption.\n          apply (IHl' n m1 tl) in H11. inversion H11. inversion H13.\n             assert (HA: a < a). omega. remember (lt_irrefl a).\n             apply ex_falso_quodlibet. apply n2. assumption. \n             inversion H13. apply mil_Tail. omega. assumption. assumption.\n          apply (IHl' n m tl) in H11. inversion H11. inversion H12.\n             apply lt_not_le in H1. apply ex_falso_quodlibet. apply H1. assumption.\n             inversion H12. apply mil_Tail. omega. assumption. assumption.\nQed.\n\nLemma minimal_in_inserted_preserve : forall l' n m l,\n  minimal_in_list m l -> m <= n -> list_insert n l l' -> minimal_in_list m l'.\nProof. \n  intros. apply (minimal_in_inserted l' n m l) in H. \n   inversion H. inversion H2. assumption. inversion H2. apply lt_not_le in H3. \n     apply ex_falso_quodlibet. apply H3. assumption. assumption.\nQed.\n\nLemma minimal_in_inserted_swap : forall n m l l',\n  minimal_in_list m l -> n < m -> list_insert n l l' -> minimal_in_list n l'.\nProof.\n  intros. apply (minimal_in_inserted l' n m l) in H. \n    inversion H. inversion H2. apply lt_not_le in H0. apply ex_falso_quodlibet. apply H0.\n      assumption. inversion H2. assumption. assumption.\nQed.\n\nLemma insert_sorted_exists : \n  forall l n, list_sorted l -> {l' | list_insert n l l' & list_sorted l'}.\nProof.\n  intros. induction l. \n    exists [n]. apply li_Head. apply ls_One.\n    remember (le_gt_dec n a) as A. \n    inversion A. \n      exists (n::a::l). \n        apply li_Head. \n        apply (ls_Cons n a (a::l)). assumption. \n        apply minimal_in_sorted. assumption. assumption.\n    assert (L: list_sorted l). inversion H. apply ls_Nil. assumption.\n    apply IHl in L. inversion L.\n      exists (a::x). apply li_Tail. assumption. \n        inversion H. rewrite <- H5 in H1. inversion H1.\n          apply ls_Cons with n. apply ls_One. apply mil_Base. omega.\n          remember (le_gt_dec m n) as A1.\n          inversion A1.\n            assert (M: minimal_in_list m x). \n              apply (minimal_in_inserted_preserve x n m l); assumption.\n            apply ls_Cons with m; assumption.\n            assert (M: minimal_in_list n x). \n              apply (minimal_in_inserted_swap n m l x); assumption.\n            apply ls_Cons with n; try assumption; omega.\nQed.\n\nTheorem list_sort_exists : forall l, { l' | list_permutation l' l & list_sorted l'}.\nProof.\n  intros. induction l.\n    exists []. apply lp_Nil. apply ls_Nil.\n    inversion IHl. \n      apply (insert_sorted_exists x a) in H0. inversion H0.\n      exists x0. \n        apply lp_Cons with x; assumption. assumption.\nQed.\n\nInductive lists_merged : list nat -> list nat -> list nat -> Prop :=\n  lm_LeftNil  : forall l, lists_merged [] l l\n| lm_RightNil : forall l, lists_merged l [] l\n| lm_Le       : forall m n l l' l'', m < n -> lists_merged l (n::l') l'' -> \n                                              lists_merged (m::l) (n::l') (m::l'')\n| lm_Gt       : forall m n l l' l'', n <= m -> lists_merged (m::l) l' l'' ->\n                                               lists_merged (m::l) (n::l') (n::l'').\n\nLemma merge_sorted_exists : forall l l', \n  list_sorted l -> list_sorted l' -> {l'' | lists_merged l l' l'' & list_sorted l''}.\nProof. admit. Qed.\n(*\n  intros l. induction l'.\n    intros. exists l. apply lm_RightNil. assumption.\n    intros. destruct l eqn: L. \n      exists (a::l'). apply lm_LeftNil. assumption.\n      remember (le_gt_dec a n) as A. clear HeqA. inversion A.\n         apply IHl' in H. inversion H. exists (a::x). apply lm_Gt. assumption. assumption.\n*)\nDefinition sort (l : list nat) : list nat := \n  match list_sort_exists l with exist2 r _ _ => r end.\n            \nExtraction Language Ocaml.\n\nSet Extraction AccessOpaque.\n\nExtraction \"sort.ml\" sort.\n        \nTheorem pred_exists : forall n, n > 0 -> {m | S m = n}.\nProof.\n  intros. destruct n. omega. \n  exists n. reflexivity.\nQed.\n\nDefinition pred (n : nat) : n > 0 -> nat := fun ev =>\n  proj1_sig (pred_exists n ev).\n\nExtraction \"pred.ml\" pred.\n\nInductive id : Type :=\n  Id : nat -> id.\n\nTheorem eq_id_dec : forall id1 id2 : id, {id1 = id2} + {id1 <> id2}.\nProof.\n   intros id1 id2.\n   destruct id1 as [n1]. destruct id2 as [n2].\n   destruct (eq_nat_dec n1 n2) as [Heq | Hneq].\n     left. rewrite Heq. reflexivity.\n     right. intros contra. inversion contra. apply Hneq. apply H0.\nDefined. \n\n(** The following lemmas will be useful for rewriting terms involving [eq_id_dec]. *)\n\nLemma eq_id : forall (T:Type) x (p q:T), \n              (if eq_id_dec x x then p else q) = p. \nProof.\n  intros. \n  destruct (eq_id_dec x x). \n    reflexivity.\n    apply ex_falso_quodlibet; apply n; reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (neq_id) *)\nLemma neq_id : forall (T:Type) x y (p q:T), x <> y -> \n               (if eq_id_dec x y then p else q) = q. \nProof.\n intros.\n destruct (eq_id_dec x y). contradiction. reflexivity.\nQed.\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\nDefinition state := id -> nat.\n\nDefinition empty_state : state :=\n  fun _ => 0.\n\nDefinition update (st : state) (x : id) (n : nat) : state :=\n  fun x' => if eq_id_dec x x' then n else st x'.\n\n(** For proofs involving states, we'll need several simple properties\n    of [update]. *)\n\n(** **** Exercise: 1 star (update_eq) *)\nTheorem update_eq : forall n x st,\n  (update st x n) x = n.\nProof.\n  intros. unfold update. apply eq_id.\nQed.\n\n(** **** Exercise: 1 star (update_neq) *)\nTheorem update_neq : forall x2 x1 n st,\n  x2 <> x1 ->                        \n  (update st x2 n) x1 = (st x1).\nProof.\n  intros. unfold update. apply neq_id. assumption.\nQed.\n\n(** **** Exercise: 1 star (update_example) *)\n(** Before starting to play with tactics, make sure you understand\n    exactly what the theorem is saying! *)\n\nTheorem update_example : forall (n:nat),\n  (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  intros. unfold update. simpl. unfold empty_state. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (update_shadow) *)\nTheorem update_shadow : forall n1 n2 x1 x2 (st : state),\n   (update  (update st x2 n1) x2 n2) x1 = (update st x2 n2) x1.\nProof.\n  intros. unfold update. destruct (eq_id_dec x2 x1) eqn:D.\n    reflexivity.\n    reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (update_same) *)\nTheorem update_same : forall n1 x1 x2 (st : state),\n  st x1 = n1 ->\n  (update st x1 n1) x2 = st x2.\nProof.\n  intros. unfold update. destruct (eq_id_dec x1 x2). rewrite <- e. symmetry. assumption.\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars (update_permute) *)\nTheorem update_permute : forall n1 n2 x1 x2 x3 st,\n  x2 <> x1 -> \n  (update (update st x2 n1) x1 n2) x3 = (update (update st x1 n2) x2 n1) x3.\nProof.\n  intros. unfold update. \n  destruct (eq_id_dec x1 x3) eqn: D1. rewrite e in H. \n    destruct (eq_id_dec x2 x3) eqn: D2. contradiction. reflexivity.\n    reflexivity.\nQed.  \n\nFixpoint aeval (st : state) (a : aexp) : nat :=\n  match a with\n  | ANum n => n\n  | AId x => st x                                       \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\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)\n                 : list nat :=\nmatch prog with\n| [] => stack\n| (SPush n)::prog' => s_execute st (n :: stack) prog'\n| (SLoad i)::prog' => s_execute st (st i :: stack) prog'\n| op::prog' =>\n   match stack with\n   | y::x::stack' => \n      s_execute \n        st\n        (((match op with \n           | SPlus => plus \n           | SMinus => minus \n           | SMult => mult \n           | _ => plus \n           end) x y)::stack')\n        prog'\n   | _ => s_execute st stack prog'\n   end\nend.\n\nLemma s_execute_composition : forall p st s s' s'' p', \n  s_execute st s p  = s' -> s_execute st s' p' = s'' -> s_execute st s (p ++ p') = s''.\nProof. admit. Qed.\n\nHint Resolve s_execute_composition.\n\nTheorem compiler_exists : \n  forall (e : aexp), {p : list sinstr | forall st s, s_execute st s p = (aeval st e)::s}.\nProof.\n  intros. induction e.\n    exists [SPush n]. eauto.\n    exists [SLoad i]. eauto.\n    inversion IHe1. inversion IHe2. exists (x ++ x0 ++ [SPlus]). eauto. \n    inversion IHe1. inversion IHe2. exists (x ++ x0 ++ [SMinus]). eauto. \n    inversion IHe1. inversion IHe2. exists (x ++ x0 ++ [SMult]). eauto.\nQed.\n\nDefinition compile (e : aexp) :=\n  proj1_sig (compiler_exists e).\n\nExtraction \"compile.ml\" compile.\n\nInductive snoc : nat -> list nat -> list nat -> Prop :=\n  snoc_Nil  : forall n, snoc n [] [n]\n| snoc_Cons : forall n m l l', snoc n l l' -> snoc n (m::l) (m::l').\n\nTheorem snoc_exists : forall n l, {l' | snoc n l l'}.\nProof.\n  intros. induction l.\n  exists [n]. apply snoc_Nil.\n  inversion IHl. exists (a::x). apply snoc_Cons. assumption.\nQed.\n\nInductive reverse : list nat -> list nat -> Prop :=\n  reverse_Nil  : reverse [] []\n| reverse_Cons : forall n l l' l'', reverse l l' -> snoc n l' l'' -> reverse (n::l) l''.\n\nTheorem reverse_exists : forall l, {l' | reverse l l'}.\nProof.\n  intros. induction l.\n    exists []. apply reverse_Nil.\n    inversion IHl. assert (S: {m | snoc a x m}). apply snoc_exists. \n      inversion S. exists x0. apply reverse_Cons with x. assumption. assumption.\nQed.\n\nDefinition rev l := proj1_sig (reverse_exists l).\n\nExtraction \"rev.ml\" rev.\n\nInductive counted (X : Set) : nat -> Set := count : forall n, X -> counted X n.\n\nDefinition ret  (X : Set) (x : X) : counted X 0 := count X 0 x.\n\nDefinition bind (X Y : Set) {n m : nat} : counted X n -> (X -> counted Y m) -> counted Y (m+n) :=\n  fun c f => \n    match c with count n x => \n      match f x with count m y => count Y (m+n) y end\n    end.\n\nDefinition increment (X : Set) {n : nat} : counted X n -> counted X (S n) := fun c =>\n  match c with count n x => count X (S n) x end.\n\nNotation \"A >>= B\" := (bind A B) (at level 90, right associativity).\n\nDefinition zero_counted := ret nat 80.\n\nPrint zero_counted.\n\nDefinition one_counted := increment nat zero_counted.\n\nPrint one_counted.\n\nFixpoint csum (n m : nat) : counted nat n := \n  match n with\n  | 0    => ret nat m\n  | S n' => increment nat (csum n' m)\n  end.\n\nDefinition clength (X : Type) (l : list X) : counted nat (length l).\n  destruct l; simpl; constructor; constructor.\nDefined.\n\nExtraction \"clength.ml\" clength.\n\n\n\n\n  \n  ", "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/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7695140580328778}}
{"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 : ...) :\n  (A -> B) \\/ (B -> A).\nAdmitted.\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.\nAdmitted.\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.\nAdmitted.\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.\nAdmitted.\n(**\n\nNow, some algebra.\n\n*)\nFrom mathcomp Require Import all_algebra.\nFrom mathcomp Require Import algC.\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.\nAdmitted.\n\nLemma gaussNormM : {morph gaussNorm : x y / x * y}.\nAdmitted.\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 admit.\nhave V2real : (2%:R^-1 : algC) \\is Num.real by admit.\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  admit.\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  admit.\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 *)\nadmit.\nAdmitted.\n\nEnd GaussIntegers.\nEnd AlgebraicHierarchy.\n\nSection Polynomials.\n\nOpen Scope ring_scope.\nImport GRing.Theory Num.Theory.\n\nVariable n : nat.\nVariables na nb: nat.\nHypothesis nbne0: nb != 0%N.\n\nDefinition a:rat := (Posz na)%:~R.\nDefinition b:rat :=(Posz nb)%:~R.\n\nDefinition pi := a / b.\n\nDefinition f :{poly rat} := (n`!)%:R^-1 *: ('X^n * (a%:P -  b*:'X)^+n).\n\nDefinition F :{poly rat} := \\sum_(i:'I_n.+1) (-1)^i *: f^`(2*i).\n\n\nAxiom derive_f_0_int: forall i, f^`(i).[0] \\is a Qint.\n\n\n(** Prove that F at 0 is a Qint.  Hint: relevant lemmas\nare exprnP hornerE horner_sum and the rpred* family *)\nLemma F0_int : F.[0] \\is a Qint.\nProof.\nAdmitted.\n\nAxiom pf_sym:  f \\Po (pi%:P -'X) = f.\n\n(** Prove this equation by induction on [i].\nHint: relevant lemmas are scale* mulr* addr* expr* oppr* in ssralg,\nderivnS derivZ deriv_comp derivE in poly *)\nLemma  derivn_fpix: forall i , (f^`(i)\\Po(pi%:P -'X))= (-1)^+i *: f^`(i).\nProof.\nAdmitted.\n\n(** Prove that F at pi is a Qint.\nHint: relevant lemmas are horner_comp sqrr_sign mulnC scale1r *)\nLemma FPi_int : F.[pi] \\is a Qint.\nProof.\nAdmitted.\n\nEnd Polynomials.\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 admit.\n  have /eqP rkvDrku : (\\rank v + \\rank u)%N == n.\n    by rewrite eqn_leq; admit.\n  have sub_v_ku : (v <= kermx u)%MS by admit.\n  have /eqmxP/eqmx_sym eq_vu: (v == kermx u)%MS.\n    rewrite -(geq_leqif (mxrank_leqif_eq _)) //.\n    admit.\n  rewrite submx1 sub1mx -col_leq_rank mxdirectEgeq /=.\n  (* use adds_eqmx to lift eq_vu to a sum *)\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  (* finish using hypothesis *)\n  admit.\nmove=> /andP [/eqmxP kuDu_eq1 kvDu_direct].\npose v := proj_mx (kermx u) u; exists v.\n  admit.\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  admit.\nAdmitted.\n\nEnd LinearAlgebra.\n\n", "meta": {"author": "gares", "repo": "CWS16", "sha": "608148973a715994ebbedb0a48724f2755c7bc89", "save_path": "github-repos/coq/gares-CWS16", "path": "github-repos/coq/gares-CWS16/CWS16-608148973a715994ebbedb0a48724f2755c7bc89/exam-todo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8688267745399465, "lm_q1q2_score": 0.7694603394511803}}
{"text": "Require Import ZArith.\n\n(* A temporal frame T=⟨T,≺⟩ defines the flow of time over \nwhich the meanings of the tense operators are to be defined.\nNote that, so far, no conditions like transitivity or irreflexivity on the \"precedence\"relation ≺ are imposed.*)\nParameter TemporalFrame: Set.\n\n(* Logic of the future *)\nInductive LTTerm :=\n| Atom: TemporalFrame -> LTTerm\n| And: LTTerm -> LTTerm -> LTTerm\n| Not: LTTerm -> LTTerm\n| Globally: LTTerm -> LTTerm\n| Future: LTTerm -> LTTerm\n| Next: LTTerm -> LTTerm.\n\nDefinition Or a b := Not(And(Not a)(Not b)).\nDefinition Impl a b := Or (Not a) (b).\nDefinition Equiv a b := And (Impl a b) (Impl b a).\n\n\n(*\n  Hence □ and ◇ form a dual pair of operators.\n  ◇p (future p) is equivalent to ¬□¬p (\"not always not-p\")\n*)\n(*Definition Future p := Not (Globally (Not p)).*)\n\n(*\nA temporal model for a set of atomic propositions PROP is a triple M=⟨T,≺,V⟩,\nwhere ⟨T,≺⟩ is a temporal frame and V is a valuation assigning to every p∈PROP a set of time instants\nV(p)⊆T at which p is declared true.\n\nEquivalently, an interpretation of PROP in T is a mapping I : T × PROP → {true, false}\nwhich assigns a truth value to each atomic proposition at each time instant in the temporal frame.\nThe truth of a formula of TL at a given time instant t\nin a given temporal model M is defined inductively as follows:\nM=⟨T,≺,V⟩\nM,t ⊨p iff t∈V(p), for p ∈ PROP;\nM,t ⊨¬ψ iff it is not the case that M,t⊨ψ;\nM,t ⊨φ ∧ ψ iff M,t ⊨ φ and M,t ⊨ ψ;\nM,t ⊨φ ∨ ψ iff M,t ⊨ φ or M,t ⊨ ψ;\nM,t ⊨Gφ iff M,t'⊨φ for all time instants t' such that t≺t';\nM,t ⊨Xφ iff M,succ(t) ⊨ φ;\nM,t ⊨Fϕ iff M,h,t′⊨ϕ for some t' ∈ h such that t≺t'.\n*)\n\nFixpoint eval (F :LTTerm) (t :nat) (valuation : TemporalFrame -> Prop) {struct F} : Prop :=\nmatch F with\n| Atom p => valuation p\n| And a b => (eval a t valuation) /\\ (eval b t valuation)\n| Not p => not (eval p t valuation)\n| Globally p => (forall t' , t' >= t -> (eval p t' valuation))\n| Future p => (exists t' , t' >= t /\\ (eval p t' valuation))\n| Next p => (eval p (t + 1) valuation)\nend.\n\n(*\n  Since ¬□¬p can be expressed by its dual ◇p, the Future evaluation \n  can be expressed thanks to the Globally and the Not evaluation. \n  This is illustrated by the following transformations and inductions:\n     \n  eval (Future p) t evaluation   \n  ⟺ not (eval (Globally (Not p)) t evaluation)                  [Equivalence]\n  ⟺ not (forall t',  t'>=t -> (eval (Not p) t' valuation))      [Induction]\n  ⟺ exists t', not(t'>=t -> (eval (Not p) t' valuation))        [Forall-Not]\n  ⟺ exists t', not(not(t'>=t) \\/ (eval (Not p) t' valuation))   [Equivalence]\n  ⟺ exists t', t'>=t /\\ not(eval (Not p) t' valuation)          [Not distribution]\n  ⟺ exists t', t'>=t /\\ not(not(eval p t' valuation))           [Induction]\n  ⟺ exists t', t'>=t /\\ eval p t' valuation                     [DoubleNot*]\n\n  * This is possible since not works on boolean which relies on the law of excluded middle.\n*)                \n\n\n(* Transitivity on order relation of TL ◇◇p → ◇p *)\nTheorem future_trans: forall p t valuation, (eval (Future (Future p)) t valuation) -> (eval (Future p) t valuation).\nProof.\nsimpl;intros.\ninversion H.\ndestruct H0.\ninversion H1.\ndestruct H2.\nexists x0.\nsplit.\nomega.\napply H3.\nQed.\n\n\n(* Transitivity on order relation of TL ◇p → ◇◇p *)\nTheorem future_trans2: forall p t valuation, (eval (Future p) t valuation) -> (eval (Future (Future p)) t valuation).\nProof.\nsimpl;intros.\ninversion H.\ndestruct H0.\nexists x.\nintros; split.\napply H0.\nexists x.\nintros; split.\nauto.\napply H1.\nQed.\n\n\n(* Transitivity on order relation of TL □□p → □p *)\nTheorem globally_trans: forall p t valuation, (eval (Globally (Globally p)) t valuation) -> (eval (Globally p) t valuation).\nProof.\n  simpl.\n  intros p t val H.\n  apply H.\n  omega.\nQed.\n\n\n(* Transitivity on order relation of TL □p → □□p *)\nTheorem globally_trans2: forall p t valuation, (eval (Globally p) t valuation) -> (eval (Globally (Globally p)) t valuation).\nProof.\n  intros p t val H.\n  simpl.\n  intros.\n  apply H.\n  omega.\nQed.\n\n(* Distributivity on next ◯(p ∨ q) → ◯p ∨ ◯q *)\nTheorem next_distributivity_1: forall p q t valuation, (eval (Next (Or p q)) t valuation) -> (eval (Or (Next p) (Next q)) t valuation).\nProof.\nsimpl.\nintros p q t val H.\nassumption.\nQed.\n\n(* Distributivity on next ◯p ∨ ◯q → ◯(p ∨ q) *)\nTheorem next_distributivity_2: forall p q t valuation, (eval (Or (Next p) (Next q)) t valuation) -> (eval (Next (Or p q)) t valuation).\nProof.\nsimpl.\nintros.\nassumption.\nQed.\n\n(* Distributivity on next ◯(p ∨ q) ≡ ◯p ∨ ◯q *)\nTheorem next_distributivity: forall p q t valuation, (eval (Next (Or p q)) t valuation) <-> (eval (Or (Next p) (Next q)) t valuation).\nProof.\nsimpl.\nintros.\nsplit.\napply next_distributivity_1.\napply next_distributivity_2.\nQed.\n\n(* Distributivity on globally □(p ∧ q) → □p ∧ □q *)\nTheorem distributivity_globally_1: forall p q t valuation, (eval (Globally (And p q)) t valuation) -> (eval (And (Globally p) (Globally q)) t valuation).\nProof.\nsimpl.\nintros p q t val H.\nsplit.\nintros.\napply H.\napply H0.\nintros.\napply H.\napply H0.\nQed.\n\n(* Distributivity on globally □p ∧ □q → □(p ∧ q) *)\nTheorem distributivity_globally_2: forall p q t valuation, (eval (And (Globally p) (Globally q)) t valuation) -> (eval (Globally (And p q)) t valuation).\nProof.\nsimpl.\nsplit.\nintros.\napply H.\napply H0.\nintros.\napply H.\napply H0.\nQed.\n\n(* Distributivity on globally □(p ∧ q) ≡ □p ∧ □q *)\nTheorem distributivity_globally: forall p q t valuation,  (eval (Globally (And p q)) t valuation) <-> (eval (And (Globally p) (Globally q)) t valuation).\nProof.\nintros.\nsplit.\napply distributivity_globally_1.\napply distributivity_globally_2.\nQed.\n\n\n(* equiv globally *)\n\n(* □p → ¬◇¬p *)\nTheorem dual_nnpp_1: forall p t valuation, (eval (Globally p) t valuation) -> not (eval (Future (Not p)) t valuation).\nProof.\nsimpl.\nintros p t valuation H H0.\ninversion H0.\ndestruct H1.\napply H2.\napply H.\nassumption.\nQed.\n\n(* ¬◇¬p → □p *)\nTheorem dual_nnpp_2: forall p t valuation, not (eval (Future (Not p)) t valuation) -> (eval (Globally p) t valuation).\nProof.\nadmit.\nAdmitted.\n\n(* NNPP □p ≡ ¬◇¬p *)\nTheorem nnpp: forall p t valuation, (eval (Globally p) t valuation) <-> not (eval (Future (Not p)) t valuation).\nProof.\nadmit.\nAdmitted.\n\n(* equiv future *)\n\n(* ◇p → ¬□¬p *)\nTheorem dual_future_1: forall p t valuation, (eval (Future p) t valuation) -> not (eval (Globally (Not p)) t valuation).\nProof.\nadmit.\nAdmitted.\n\n(* ¬□¬p → ◇p *)\nTheorem dual_future_2: forall p t valuation, not (eval (Globally (Not p)) t valuation) -> (eval (Future p) t valuation).\nProof.\nadmit.\nAdmitted.\n\n(* ◇p ≡ ¬□¬p *)\nTheorem dual_future: forall p t valuation, (eval (Future p) t valuation) = not (eval (Globally (Not p)) t valuation).\nProof.\nadmit.\nAdmitted.\n\n(* leads □p → ◇p *)\nTheorem leads: forall p t valuation, (eval (Globally p) t valuation) -> (eval (Future p) t valuation).\nProof.\nadmit.\nAdmitted.\n", "meta": {"author": "NotBad4U", "repo": "coqlang_temporal_logic", "sha": "22247107f90852540a055393e867d6a303d20515", "save_path": "github-repos/coq/NotBad4U-coqlang_temporal_logic", "path": "github-repos/coq/NotBad4U-coqlang_temporal_logic/coqlang_temporal_logic-22247107f90852540a055393e867d6a303d20515/temporal_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7693715151287259}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import IndProp.\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\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros. simpl.\n  apply ev_SS. 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'' (n : nat) (H : ev n) : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\n(* Programming with Tactics *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n.\nShow Proof.\nDefined.\n\nPrint add1.\nCompute add1 2.\n\nTheorem add1' : forall n : nat, nat.\nProof.\n  intros.\n  Show Proof.\n  apply S.\n  Show Proof.\n  apply n.\n  Show Proof.\nQed.\n\n(* Logical Connectives as Inductive Types *)\n\nModule Props.\n\n(* Conjunction *)\n\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. 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\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 *)\n\nDefinition conj_fact : forall P Q R,\n  P /\\ Q -> Q /\\ R -> P /\\ R.\nintros P Q R [HP HQ] [HQ' HR].\napply conj.\napply HP. apply HR.\nDefined.\n\n(* Disjunction *)\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(* Exercise *)\n\nDefinition or_com : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun (P: Prop) => fun (Q : Prop) =>\n    fun (PQ : P \\/ Q) => match PQ with\n      | or_introl P => or_intror P\n      | or_intror Q => or_introl Q\n      end.\n\n(* Existential Quantification *)\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\n(* Exercise *)\nCheck ev_SS 0 ev_0.\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  ex_intro (fun n => ev (S n)) (S 0) (ev_SS 0 ev_0).\n\n(* True and False *)\n\nInductive True : Prop :=\n  | I : True.\nInductive False : Prop :=.\n\nEnd Props.\n\n(* Equality *)\n\nModule MyEquality.\n\nInductive eq {X : Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(* Exercises *)\n\nLemma leibniz_equality: forall (X: Type) (x y: X),\n  eq x y -> forall P: X -> Prop, P x -> P y.\nProof.\n  intros. destruct H. apply H0.\nQed.\n\n(* The reflexivity tactic that we have used to prove \n   equalities up to now is essentially just short-hand \n   for apply eq_refl. *)\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), []++[x] = x::[] :=\n  fun (X : Type) (x : X) => eq_refl [x].\n\n(* Inversion, Again *)\n\n(* In general, the inversion tactic\n   takes a hypothesis H whose type P is inductively defined, and,\n   for each constructor C in P's definition,\n     1. generates a new subgoal in which we assume H was built with C,\n     2. adds the arguments of C to the context of the subgoal as extra hypotheses,\n     3. matches the conclusion of C against the current goal and calculates a se\n        of equalities that must hold in order for C to be applicable,\n     4. adds these equalities to the context\n     5. if the equalities are not satisfiable, immediately solves the subgoal.\n*)\n\nEnd MyEquality.\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/ProofObject.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7693715023772654}}
{"text": "Require Import XR_Rabs.\nRequire Import XR_Rsqr.\nRequire Import XR_Rle_antisym.\nRequire Import XR_Rsqr_le_abs_0.\n\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_eq_abs_0 : forall x y:R, Rsqr x = Rsqr y -> Rabs x = Rabs y.\nProof.\n  intros x y h.\n  apply Rle_antisym.\n  {\n    apply Rsqr_le_abs_0.\n    right.\n    exact h.\n  }\n  {\n    apply Rsqr_le_abs_0.\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_0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7693046133160204}}
{"text": "Theorem ex54_16: forall a1 a2 a3 b c : Prop,\n                 (a1 -> b) -> (a2 -> b) -> (a3 -> b) -> \n                 (a1 \\/ a2 \\/ a3) -> b.\nProof.\n  intros. elim H2. intro. apply (H H3).\n  intro. elim H3. intro. apply (H0 H4).\n  intro. apply (H1 H4).\nQed.\n\nTheorem ex54_17: forall a1 a2 a3 b1 b2 b3: Prop,\n                 (a1 -> b1) -> (a2 -> b2) -> (a3 -> b3) ->\n                 (a1 \\/ a2 \\/ a3) -> (b1 \\/ b2 \\/ b3).\nProof.\n  intros. elim H2. intro. left. apply (H H3).\n  intro. elim H3. intro. right. left. apply (H0 H4).\n  intro. right. right. apply (H1 H4).\nQed.\n\nTheorem ex54_18: forall a b1 b2 b3 : Prop,\n                 (a -> b1) -> (a -> b2) -> (a -> b3) -> \n                 (~b1 \\/ ~b2 \\/ ~b3) -> ~a.\nProof.\n  intros. intro. elim H2. intro. apply H4.\n  apply (H H3). intro. elim H4. intro.\n  apply H5. apply (H0 H3). intro.\n  apply H5. apply (H1 H3).\nQed.\n\nTheorem ex54_19: forall a1 a2 a3 b1 b2 b3 : Prop,\n                 (a1 -> b1) -> (a2 -> b2) -> (a3 -> b3) -> \n                 (~b1 \\/ ~b2 \\/ ~b3) -> (~a1 \\/ ~a2 \\/ ~a3).\nProof.\n  intros. elim H2. intro. left. intro.\n  apply H3. apply (H H4).\n  intro. elim H3. intro. right. left. intro.\n  apply H4. apply (H0 H5).\n  intro. right. right. intro. apply H4.\n  apply (H1 H5).\nQed.\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/ConstDestTrilemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7692883680769733}}
{"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 day_inc (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\nCompute (day_inc monday).\nCompute (day_inc (day_inc sunday)).\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | friday => monday\n  | saturday => monday\n  | _ => day_inc d\n  end.\n\n\n\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nExample test_negb_1:\n  (negb true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_negb_2:\n  (negb false) = true.\nProof. simpl. reflexivity. Qed.\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.\n\nExample test_orb2: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nExample test_andb1: (andb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb2: (andb true false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb3: (andb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb4: false || true = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true =>\n        match b2 with\n        | true => false\n        | false => true\n        end\n  | false => true\n  end.\n  \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  | true => andb b2 b3\n  | false => false\n  end.\n  \nExample test_andb3_1: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb3_2: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb3_3: (andb3 false false false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb3_4: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\n\nCheck (negb true).\n\nCheck negb.\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\n  end.\n\nExample monochrome_1: monochrome white = true.\nProof. simpl. reflexivity. Qed.\n\nExample monochrome_2: monochrome (primary red) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition isred (c : color) : bool :=\n  match c with\n  | primary red => true\n  | _ => false\n  end.\n\nExample isred_1: isred (primary blue) = false.\nProof. simpl. reflexivity. Qed.\n\nExample isred_2: isred (primary red) = true.\nProof. simpl. reflexivity. Qed.\n\nExample isred_3: isred white = false.\nProof. simpl. reflexivity. Qed.\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 (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\nExample minustwo_1: minustwo 4 = 2.\nProof. simpl. reflexivity. Qed.\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 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\nExample plus_1: plus 1 3 = 4.\nProof. simpl. reflexivity. Qed.\n\nExample plus_2: plus 4 5 = 9.\nProof. simpl. reflexivity. Qed.\n\nExample plus_3: plus 134 2 = 136.\nProof. simpl. 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\nExample mult_1: mult 3 4 = 12.\nProof. simpl. reflexivity. Qed.\n\nExample mult_2: mult 2 8 = 16.\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\nExample minus_1: minus 3 2 = 1.\nProof. simpl. reflexivity. Qed.\n\nExample minus_2: minus 3 5 = 0.\nProof. simpl. reflexivity. Qed.\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\nExample exp_1: exp 2 4 = 16.\nProof. simpl. reflexivity. Qed.\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => mult n (factorial n')\n  end.\n\nExample test_factorial_1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial_2: (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\n  end.\n\nExample test_beq_nat_1: beq_nat 2 3 = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_beq_nat_2: beq_nat 3 3 = true.\nProof. simpl. reflexivity. Qed.\n\n\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_leb_1: leb 2 3 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_leb_2: leb 3 3 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_leb_3: leb 4 3 = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition blt_nat (n m : nat) : bool :=\n  andb (leb n m) (negb (beq_nat n m)).\n  \nExample test_blt_nat_1: blt_nat 2 2 = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat_2: blt_nat 2 4 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat_3: blt_nat 4 2 = false.\nProof. simpl. reflexivity. Qed.\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.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + m = m + m.\nProof. \n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity. \nQed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\n\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 as [| 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\n\nTheorem plus_1_neq_0' : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\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 [] [].\n  - intros H. reflexivity.\n  - intros H. rewrite <- H. reflexivity.\n  - intros H. reflexivity.\n  - intros H. rewrite <- H. reflexivity. \nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nNotation \"x + y\" := (plus 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\nFixpoint plus' (n : nat) (m : nat) : nat :=\n  match m with\n  | O => n\n  | S m' => S (plus' n m')\n  end.\n\nTheorem identity_fn_applied_twice : \n  forall (f : bool -> bool), \n  (forall (x : bool), f x = x) -> \n  forall (b : bool), f (f b) = b.\nProof.\n  intros H f.\n  intros [].\n  - rewrite -> f. rewrite -> f. reflexivity.\n  - rewrite -> f. rewrite -> f. 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 H f.\n  intros [].\n  - rewrite -> f. rewrite -> f. reflexivity.\n  - rewrite -> f. rewrite -> f. reflexivity.\nQed.\n\n\nTheorem andb_eq_orb:\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros b c. destruct b as [| b']. \n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\nInductive bin : Type :=\n  | Zero : bin\n  | Twice : bin -> bin\n  | Twice_plus_1 : bin -> bin.\n\nCheck Zero. (** 0 **)\nCheck Twice_plus_1 Zero. (** 1 **)\nCheck Twice (Twice_plus_1 Zero). (** 2 **)\nCheck Twice_plus_1 (Twice_plus_1 Zero). (** 3 **)\nCheck Twice (Twice (Twice_plus_1 Zero)). (** 4 **)\nCheck Twice_plus_1 (Twice (Twice_plus_1 Zero)). (** 5 **)\nCheck Twice (Twice_plus_1 (Twice_plus_1 Zero)). (** 6 **)\nCheck Twice_plus_1 (Twice_plus_1 (Twice_plus_1 Zero)). (** 7 **)\n\nFixpoint incr (n : bin) : bin :=\n  match n with\n  | Zero => Twice_plus_1 Zero\n  | Twice n' => Twice_plus_1 n'\n  | Twice_plus_1 n' => Twice (incr n')\n  end.\n\nExample test_bin_incr1: incr (Zero) = Twice_plus_1 Zero.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr2: incr (incr Zero) = Twice (Twice_plus_1 Zero).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr3: incr (Twice_plus_1 (Twice_plus_1 Zero)) = Twice (Twice (Twice_plus_1 Zero)).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr4: incr (incr (incr (incr Zero))) = Twice (Twice (Twice_plus_1 Zero)).\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr5: incr (incr (incr (incr (incr (incr Zero))))) = Twice (Twice_plus_1 (Twice_plus_1 Zero)).\nProof. simpl. reflexivity. Qed.\n\nFixpoint bin_to_nat (n : bin) : nat :=\n  match n with\n  | Zero => 0\n  | Twice n' => mult 2 (bin_to_nat n')\n  | Twice_plus_1 n' => plus 1 (mult 2 (bin_to_nat n'))\n  end.\n\nExample test_bin_to_nat_1: bin_to_nat (Twice (Twice_plus_1 Zero)) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_to_nat_2: bin_to_nat (Twice (Twice (Twice_plus_1 Zero))) = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_to_nat_incr1: bin_to_nat (incr (incr (incr (incr Zero)))) = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_to_nat_incr2: bin_to_nat (incr (incr (incr (incr (incr (incr (incr Zero))))))) = 7.\nProof. simpl. reflexivity. Qed.\n\n\n\n\n\n\n\n\n", "meta": {"author": "prashantpawar", "repo": "logical-foundations", "sha": "8c2126869f2104e2fe38249e3b86de080ea12d2f", "save_path": "github-repos/coq/prashantpawar-logical-foundations", "path": "github-repos/coq/prashantpawar-logical-foundations/logical-foundations-8c2126869f2104e2fe38249e3b86de080ea12d2f/Basics_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7692381103064099}}
{"text": "(** * Exponentiation   in a Monoid \n\nIn this section, we give two polymorphic functions for computing\n $x^n$: the  naive (%\\emph{i.e.}% linear) one and the aforementionned \nbinary method, that takes less than $2\\times \\log_2(n)$ multiplications.\n\n Both functions require an instance of [EMonoid]. Their code use the \n multiplication of the monoid, and sometimes  its  unity. \n  Correctness proofs require the \"axioms\" of monoid structure.\n *)\n\n\n\nSet Implicit Arguments.\n\nRequire Export ZArith  Div2.\nRequire Export Recdef.\nRequire Import Relations Morphisms.\n\nRequire Import Monoid_def.\nRequire Import Arith Lia.\n\nOpen Scope M_scope.\n\n\n(** ** Two functions for computing powers \n\n The  module defines two functions for exponentiation on any [Emonoid] \n  on carrier $A$.\n \n  - The function [power] has type [A -> nat -> A]; it is linear with respect to \n    the exponent. Its simplicity and the fact that the exponent has type [nat] \n    make it adequate for being the reference for any other definition, and for \n    easily proving laws like $x^{n+p}=x^n \\times x^p$.\n    %\\footnote{Cite : Refinement for free!}%\n\n - The function [Pos_bpow] has type [A -> positive -> A] and is logarithmic\n   with respect to its exponent. This function should be used for effective\n   computations. Its variant [N_bpow] allows the exponent to be $0$.\n\n*)\n\n(** *** The \"naive\" reference function *)\nGeneralizable Variables  A E_op E_one E_eq.\n\n\n(* begin snippet powerDef *)\nFixpoint power `{M: @EMonoid A  E_op E_one E_eq}\n         (x:A)(n:nat) :=\n  match n with 0%nat => E_one\n             | S p =>   x *  x ^ p\n  end\nwhere \"x ^ n\" := (power x n) : M_scope.\n(* end snippet powerDef *)\n\n(* begin snippet powerEqns:: no-out *)\n\nLemma power_eq1  `{M: @EMonoid A  E_op E_one E_eq}(x:A) :\n  x ^ 0 = E_one.\nProof. reflexivity. Qed.\n\n\nLemma power_eq2  `{M: @EMonoid A  E_op E_one E_eq}(x:A) (n:nat) :\n x ^ (S n)  = x * x ^ n.\nProof. reflexivity. Qed.\n\nLemma power_eq3  `{M: @EMonoid A  E_op E_one E_eq}(x:A) :\n x ^ 1 == x.\nProof. cbn;  rewrite Eone_right; reflexivity. Qed.\n(* end snippet powerEqns *)\n\n(** *** The binary exponentiation function (exponents in  [positive])  *)\n\n  (**  *** \n\nThe auxiliary function below computes  $acc \\times x ^p$, where\nthe \"accumulator\" [acc] is intented to be an already computed power of [x]:\n\n*) \n\n(* begin snippet binaryPowerMult *)\nFixpoint binary_power_mult  `{M: @EMonoid A E_op E_one E_eq} \n         (x a:A)(p:positive) : A \n  :=\n  match p with\n    | xH =>  a * x\n    | xO q => binary_power_mult (x * x) a q\n    | xI q =>  binary_power_mult  (x * x) (a * x) q\n  end.\n(* end snippet binaryPowerMult *)\n\n (** *** \n\nThe  following function decomposes the exponent [p]\n  into $2 ^ k \\times q$ , then calls [binary_power_mult]\n   with $x^{2^k}$ and $q$.\n\n*)\n\n(* begin snippet PosBpow *)\nFixpoint Pos_bpow  `{M: @EMonoid A E_op E_one E_eq}\n         (x:A)(p:positive) :=\n match p with\n  | xH => x\n  | xO q => Pos_bpow  (x * x) q\n  | xI q => binary_power_mult  (x * x) x q\nend.\n(* end snippet PosBpow *)\n\n(** ***\n  It is straightforward to adapt [Pos_bpow]\n for accepting exponents of type [N] :\n*)\n\n(* begin snippet NBpow *)\nDefinition N_bpow  `{M: @EMonoid A E_op E_one E_eq} x (n:N) := \n  match n with \n  | 0%N => E_one\n  | Npos p => Pos_bpow x p\n  end.\n\nInfix \"^b\" := N_bpow (at level 30, right associativity) : M_scope.\n(* end snippet NBpow *)\n\n(** ** Properties of the power function \n\n Taking [power] as a reference, it remains to prove two kinds of properties\n  - Mathematical properties of exponentiation, _i.e_ the function [power],\n\n  - proving  correctness of functions [Pos_bpow] and [N_bpow]\n\nFirst, let us consider some [Emonoid] and define some useful notations and tactics:\n*)\n\n(* begin snippet MGiven *)\nSection M_given.\n  \n  Variables (A:Type) (E_one:A) .\n  Context (E_op : Mult_op A) (E_eq : Equiv A)\n          (M:EMonoid  E_op E_one E_eq).\n(* end snippet MGiven *)\n\n#[global] Instance Eop_proper : Proper (equiv ==> equiv ==> equiv) E_op.\nProof.\n  apply  Eop_proper.\nQed.\n\n(* begin snippet monoidRw *)\nLtac monoid_rw :=\n    rewrite Eone_left  ||\n    rewrite Eone_right  || \n    rewrite Eop_assoc.\n\nLtac monoid_simpl := repeat monoid_rw.\n(* end snippet monoidRw *)\n\n(* *** Properties of the classical exponentiation  *)\n\n(* begin snippet powerProper:: no-out *)\n#[global] Instance power_proper :\n  Proper (equiv ==> eq ==> equiv) power.\n(* end snippet powerProper *)\nProof.\n  intros x y Hxy n p Hnp;  subst p; induction n.\n  - reflexivity.\n  - cbn; now rewrite IHn, Hxy.\nQed.\n\n(* begin snippet powerOfPlus:: no-out *)\nLemma power_of_plus :\n  forall x n p, x ^ (n + p) ==  x ^ n *  x ^ p.\n(* end snippet powerOfPlus *)\nProof.\n  induction n; cbn; intro.\n  - monoid_simpl; reflexivity.\n  - rewrite IHn.\n    monoid_simpl; reflexivity.\nQed.\n\n(* begin snippet powerSimpl *)\nLtac power_simpl := repeat (monoid_rw || rewrite <- power_of_plus).\n(* end snippet powerSimpl *)\n\n(* begin snippet powerCommute:: no-out *)\nLemma power_commute x n p: \n  x ^ n * x ^ p ==  x ^ p * x ^ n. \nProof.\n power_simpl; now rewrite (Nat.add_comm n p).\nQed.\n\nLemma power_commute_with_x x n:\n  x * x ^ n == x ^ n * x.\nProof.\n  induction n; cbn.\n  - now monoid_simpl.\n  - rewrite IHn at 1; now monoid_simpl.\nQed.\n\nLemma power_of_power x n p:\n  (x ^ n) ^ p == x ^ (p * n).\nProof.\n  induction p; cbn.\n  - reflexivity.\n  - rewrite IHp; now power_simpl. \nQed.\n(* end snippet powerCommute *)\n\n\nLemma power_of_power_comm x n p : (x ^ n) ^ p == (x ^ p) ^ n.\nProof.\n  repeat rewrite power_of_power.\n  now rewrite Nat.mul_comm.\nQed.\n\n(* begin snippet sqrEqn:: no-out *)\nLemma sqr_eqn : forall x, x ^ 2 ==  x * x.\n(* end snippet sqrEqn *)\nProof.\n  intros; cbn;  now monoid_simpl.\nQed.\n\n\nLtac factorize := repeat (\n                rewrite <- power_commute_with_x ||\n                rewrite  <- power_of_plus  ||\n                rewrite <- sqr_eqn ||\n                rewrite <- power_eq2 ||\n                rewrite power_of_power).\n\n(* begin snippet powerOfSquare:: no-out *)\nLemma power_of_square x n : (x * x) ^ n ==  x ^ n * x ^ n.\nProof.\n  induction n; cbn; monoid_simpl.\n  - reflexivity.\n  - rewrite IHn; now factorize.\nQed.\n(* end snippet powerOfSquare *)\n\n(** ** Correctness of the binary algorithm \n\nCorrectness of the \"concrete\" functions [Pos_bpow] and [N_bpow]\nwith respect to the more abstract function [power] is expressed \nby  extensional equalities, taking into account the conversion between \nvarious representations of natural numbers.\n\n*)\n\n\n(* begin snippet binaryPowerMultOk:: no-out *)\nLemma binary_power_mult_ok :\n  forall p a x,   binary_power_mult  x a p  ==  a * x ^ Pos.to_nat p.\nProof.\n  induction p as [q IHq | q IHq|].\n  (* ... *)\n(* end snippet binaryPowerMultOk *)  \n  - (* 2 * q + 1 *)\n    intros; cbn.\n    rewrite Pos2Nat.inj_xI, IHq.\n    rewrite power_eq2, Eop_assoc.\n    rewrite <- power_of_power, sqr_eqn, power_of_square; reflexivity.\n  - (* 2 * q *)\n    intros; cbn.\n    rewrite Pos2Nat.inj_xO, IHq.\n    rewrite <- power_of_power, sqr_eqn, power_of_square; reflexivity.\n  - (* 1 *)\n    intros; cbn.\n    simpl (x ^ Pos.to_nat 1).\n    now monoid_rw.\nQed.\n\n(* begin snippet PosBpowOk:: no-out *)\nLemma Pos_bpow_ok : \n  forall p x, Pos_bpow x p == x ^ Pos.to_nat p.\n(* end snippet PosBpowOk *)\nProof.\n  induction p; cbn; intros.\n  - rewrite binary_power_mult_ok, Pos2Nat.inj_xI.\n    factorize.\n    apply power_proper; [reflexivity | lia].\n  - rewrite IHp, Pos2Nat.inj_xO.\n    factorize.\n    apply power_proper; [reflexivity | lia].\n  - simpl.\n    now monoid_rw.\nQed.\n\n#[global] Instance Pos_bpow_proper :\n  Proper  (equiv ==> eq ==> equiv) Pos_bpow.\nProof.\n  intros x y Hxy n p Hnp. subst n. revert  x y Hxy.\n  induction p; cbn; intros; trivial.\n  - repeat rewrite binary_power_mult_ok.  \n    factorize.\n    apply power_proper; auto.\n  - apply IHp. now apply Eop_proper.\nQed.\n\n(* begin snippet NBpowOk:: no-out *)\nLemma N_bpow_ok : \n  forall n x, x ^b n == x ^ N.to_nat n.\n(* end snippet NBpowOk *)\nProof.\n  destruct n.\n  - (* 0 *) reflexivity.\n  - apply Pos_bpow_ok.\nQed.\n\n(* begin snippet NBpowOkR:: no-out *)\nLemma N_bpow_ok_R : \n  forall n x, x ^b  (N.of_nat n) == x ^ n.\n(* end snippet NBpowOkR *)\nProof.\n  intros; rewrite N_bpow_ok; now rewrite Nnat.Nat2N.id.\nQed.\n\n(* begin snippet PosBpowOkR:: no-out *)\nLemma Pos_bpow_ok_R : \n  forall p x, p <> 0 ->\n              Pos_bpow x (Pos.of_nat p) == x ^ p.\n(* end snippet PosBpowOkR *)\nProof.\n  intros; rewrite Pos_bpow_ok; now rewrite Nat2Pos.id.\nQed.\n\n(* begin snippet NBpowCommute:: no-out *)\nLemma N_bpow_commute : forall x n p,  \n                        x ^b n *  x ^b p ==  \n                        x ^b p *  x ^b n.\nProof.\n  intros x n p; repeat rewrite N_bpow_ok;\n    apply power_commute.\nQed.\n(* end snippet NBpowCommute *)\n\nLemma Pos_bpow_of_plus : forall x n p, Pos_bpow x  (n + p)%positive ==\n                                       Pos_bpow x  n *  Pos_bpow x  p.\nProof.\n  intros; repeat rewrite Pos_bpow_ok.\n  rewrite Pos2Nat.inj_add.\n  now rewrite power_of_plus.\nQed.\n\nLemma Pos_bpow_of_bpow : forall (x:A) n p,\n    Pos_bpow (Pos_bpow x n) p == Pos_bpow x (p * n)%positive.\nProof.\n  intros; repeat rewrite Pos_bpow_ok.\n  rewrite Pos2Nat.inj_mul.\n  now rewrite power_of_power.\nQed.\n\n\n\n(** ** Remark\n\nIf we normalize exponentiation functions with a given exponent, we notice\nthat the obtained functions do not execute the same computations, but it is\nhard to visualize why the binary method is more efficient than the naive one.\n\n\n*)\n\n(* begin snippet bpow17 *)\nEval simpl in fun (x:A) => x ^b 17.\n(* end snippet bpow17 *)\n\n(* begin snippet naivePow17 *)\nEval simpl in  fun x => x ^ 17.\n(* end snippet naivePow17 *)\n\n(* begin snippet pow17LetIn *)\n\nDefinition pow_17  (x:A) :=\n  let x2 := x * x in\n  let x4 := x2 * x2 in\n  let x8 := x4 * x4 in\n  let x16 := x8 * x8 in\n  x16 * x.\n\n(* end snippet pow17LetIn *)\n\n(* begin snippet evalPow17LetIn *)\nEval cbv  zeta beta delta [pow_17]  in  pow_17.\n(* end snippet evalPow17LetIn *)\n\n(**\n = fun x : A =>\n       x * x * (x * x) * (x * x * (x * x)) *\n       (x * x * (x * x) * (x * x * (x * x))) * x\n     : A -> A\n*)\n\n\n(**\nIn order to compare the real computations needed to raise some $x$ to its $n$-th\npower, we need to make more explicit how intermediate values are used during \nsome computation. \nThis is described in the module %\\texttt{Chains}% (see %\\vref{chains-section}%).\n\n*)\n\n(** ** Properties of Abelian Monoids \n \n Some equalities hold in the restricted context of abelian (a.k.a. commutative)\n monoids. \n*)\n\nSection Power_of_op.\n Context  {AM:Abelian_EMonoid M}.\n \nTheorem power_of_mult :\n   forall n x y,  (x * y)  ^ n ==  x ^ n *  y ^ n. \nProof.\n induction n;simpl.\n -  intros;rewrite Eone_left;auto.\n    reflexivity.\n-  intros; rewrite IHn; repeat rewrite Eop_assoc.\n    rewrite <- (Eop_assoc  x y (power x n)); rewrite (Eop_comm y (power x n)).\n    repeat rewrite Eop_assoc;reflexivity. \nQed.\n\nEnd Power_of_op.\n\n\n\nEnd M_given.\n\nInfix \"^\" := power : M_scope.\n\n\n   \nLtac monoid_simpl M := generalize (Eop_proper M); intro; \n  repeat ( rewrite (Eone_left ) || \n    rewrite (Eone_right  ) || \n    rewrite (Eop_assoc )).\n\n  Ltac power_simpl M := generalize (Eop_proper M); intro; \n  repeat ( rewrite Eone_left  ||  rewrite Eone_right ||  rewrite Eop_assoc \n     || rewrite power_of_plus).\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/Pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.7692180683464777}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreProp. \n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\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  (* SOLUTION: *)\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(* SOLUTION: *)\n  split.\n    Case \"left\". split.\n      SCase \"left\". apply HP.\n      SCase \"right\". apply HQ.\n    Case \"right\". apply HR.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (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  (* SOLUTION: *)\n  intros n. induction n as [| n' ].\n  Case \"n = O\". simpl. split.\n    SCase \"left conjunct\". intros eq. apply ev_0.\n    SCase \"right conjunct\". intros eq. inversion eq.\n  Case \"n = S n'\". split. \n    SCase \"left conjunct\". intros eq. inversion IHn' as [Hn HSn].\n      apply HSn. apply eq.\n    SCase \"right conjunct\". intros eq. inversion IHn' as [Hn HSn].\n      apply ev_SS. unfold even in eq. simpl in eq. apply Hn. apply eq. Qed. \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  (* SOLUTION: *)\n  fun P Q R HPQ HQR =>\n    match (HPQ,HQR) with\n    | (conj HP _, conj _ HR) => conj P R HP HR\n    end.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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  (* SOLUTION: *)\n  intros P. split.\n    Case \"->\". intros H. apply H.\n    Case \"<-\". intros H. apply H.  Qed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* SOLUTION: *)\n  intros P Q R H G.\n  inversion H as [HAB HBA].\n  inversion G as [HBC HCB].\n  split.\n    Case \"->\". intros HP. apply HBC. apply HAB. apply HP.\n    Case \"<-\". intros HR. apply HBA. apply HCB. apply HR.  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, advanced (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  (* SOLUTION: *)\n  fun n => conj _ _ (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\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(* SOLUTION: *)\nDefinition or_commut'' : forall P Q, P \\/ Q -> Q \\/ P :=\n    fun (P Q : Prop) (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\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  (* SOLUTION: *)\n  intros P Q R. intros H.\n  inversion H as [[HAl | HQ] [HAr | HR]].\n    Case \"left,left\". left. apply HAl.\n    Case \"left,right\". left. apply HAl.\n    Case \"right,left\". left. apply HAr.\n    Case \"right,right\". right. split. apply HQ. apply HR. 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  (* SOLUTION: *)\n  intros P Q R. split.\n    Case \"->\". apply or_distributes_over_and_1.\n    Case \"<-\". apply or_distributes_over_and_2.  Qed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\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, optional (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  (* SOLUTION: *)\n  intros b c H.\n  destruct b.\n  Case \"b=true\".\n    destruct c.\n    SCase \"c=true\".\n      simpl in H. inversion H.\n    SCase \"c=false\".\n      right. reflexivity.\n  Case \"b=false\".\n    left. reflexivity.  Qed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* SOLUTION: *)\n  intros b c H.\n  destruct b.\n  Case \"b=true\".\n    left. reflexivity.\n  Case \"b=false\".    \n    destruct c.\n    SCase \"c=true\".\n      right. reflexivity.\n    SCase \"c=false\".\n      simpl in H. inversion H.  Qed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* SOLUTION: *)\n  intros b c H.\n  destruct b.\n  Case \"b=true\".\n    inversion H.\n    split. reflexivity.\n  Case \"b=false\".\n    destruct c.\n    SCase \"c=true\".\n      inversion H.\n    SCase \"c=false\".\n      reflexivity.  Qed.\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\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\n(* SOLUTION: *)\nInductive True : Prop :=\n I : True.\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, 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(* SOLUTION: *) Let a proposition [P] be given, and suppose we have\n   evidence for [P].  We must show [~~P] -- i.e., [~P -> False], so\n   suppose [~P] as well.  Then we have both [P] and [~P], a\n   contradiction, so [~~P] holds.\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* SOLUTION: *)\n  intros P Q H HNotB HP.\n  apply HNotB.  apply H. apply HP.  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  (* SOLUTION: *)\n  intros P H. inversion H as [HP HNA]. apply HNA. apply HP.  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(* SOLUTION: *)\n(* _Proof_: Suppose, for some [P], that [(P /\\ ~P)] holds.  Recall\n  that [~P] is defined as [P -> False].  Given [P] and [P -> False],\n  we can prove [False], so [(P /\\ ~P) -> False], i.e., [~(P /\\ ~P)].\n*)\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  (* SOLUTION: *)\n    Case \"ev_0\". intros H. inversion H.\n    Case \"ev_SS\". intros G. inversion G as [| n' HevSn Heqn'].\n      apply IHev. apply HevSn.  Qed.\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     from evidence for [P]. *) \n  Admitted.\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\n(* SOLUTION: *)\nLemma ito__em :\n  implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros Hito P.\n  apply or_commut.\n  apply Hito.\n  intros HP. apply HP.\nQed.\n\nLemma em__ito :\n  excluded_middle -> implies_to_or.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros Hem P Q H.\n  assert (P \\/ ~P) by apply Hem.\n  inversion H0 as [HP | HNP].\n    Case \"P\". right. apply H. apply HP.\n    Case \"~P\". left. apply HNP.\nQed.\n\nLemma em__demorgan :\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle, de_morgan_not_and_not.\n  intros Hem P Q H.\n  assert (P \\/ ~P) by apply Hem.\n  inversion H0 as [HP | HNP].\n    Case \"P\".\n      left. apply HP.\n    Case \"~P\".\n      assert (Q \\/ ~Q) by apply Hem.\n      inversion H1 as [HQ | HNQ].\n      SCase \"Q\".\n        right. apply HQ.\n      SCase \"~Q\".\n        apply ex_falso_quodlibet. apply H.\n        split. apply HNP. apply HNQ.\nQed.\n\nLemma demorgan__em :\n  de_morgan_not_and_not -> excluded_middle.\nProof.\n  unfold de_morgan_not_and_not, excluded_middle.\n  intros Hdm P.\n  apply Hdm.\n  unfold not. intros Hcontra.\n  inversion Hcontra as [HNP HNNP].\n  apply HNNP. apply HNP.\nQed.\n\nLemma em__classic :\n  excluded_middle -> classic.\nProof.\n  unfold excluded_middle, classic, not.\n  intros Hem P.\n  assert (P \\/ (P -> False)) by apply Hem.\n  inversion H as [HP | HNP].\n    Case \"P\". intros H'. apply HP.\n    Case \"~P\". intros H'. apply H' in HNP. inversion HNP.\nQed.\n\nLemma classic__demorgan :\n  classic -> de_morgan_not_and_not.\nProof.\n  unfold classic, de_morgan_not_and_not, not.\n  intros Hc P Q H.\n  apply Hc.\n  intros H2.\n  apply H.\n  split.\n    Case \"left conjunct\". intros HP. apply H2. left. apply HP.\n    Case \"right conjunct\". intros HQ. apply H2. right. apply HQ.\nQed.\n\n(** The above suffices (along with [demorgan__em]), but we can also\n    prove it directly this way *)\n\nLemma classic__em :\n  classic -> excluded_middle.\nProof.\n  unfold classic, excluded_middle, not.\n  intros Hc P.\n  apply Hc.\n  intros H.\n  apply H.\n  right.\n    intros HP. apply H.\n    left. apply HP.\nQed.\n  \nLemma em__peirce : \n  excluded_middle -> peirce.\nProof.\n  unfold excluded_middle, peirce.\n  intros Hem P Q H.\n  assert (P \\/ ~P) by apply Hem.\n  inversion H0 as [HP | HNP].\n    Case \"P\". apply HP.\n    Case \"~P\". \n      assert ((P -> Q) \\/ ~(P -> Q)) by apply Hem.\n      inversion H1 as [HPQ | HNPQ].\n      SCase \"P->Q\". apply H. apply HPQ.\n      SCase \"~(P->Q)\". assert (P -> Q) as HPQ.\n        intros HP.\n        apply ex_falso_quodlibet. \n        apply HNP. apply HP.\n      apply H. apply HPQ.\nQed.\n\nLemma peirce__em :\n  peirce -> excluded_middle.\nProof.\n  unfold peirce, excluded_middle, not.\n  intros Hp P. \n  apply Hp with False.\n  right.\n    intros HP. apply H.\n    left. apply HP.\nQed. \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\n\n\n(** **** Exercise: 2 stars (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof. \n  (* SOLUTION: *)\n  intros n n' H. unfold not in H. \n   remember (beq_nat n n') as e. destruct e. \n   Case \"e = true (contradictory)\". \n     apply ex_falso_quodlibet. apply H. \n     apply beq_nat_eq in Heqe. apply Heqe. \n   Case \"e = false\". \n    reflexivity.  Qed.\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  (* SOLUTION: *) \n  intros n m H Heq.\n  rewrite <- Heq in H. \n  rewrite <- beq_nat_refl in H.\n  inversion H. Qed.\n  (** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P]. \n\n    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] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2). \n  reflexivity.  Qed.\n\n(** Note, 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) = 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(* SOLUTION: *)\n(* There is some number whose successor is beautiful. *)\n\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n(* SOLUTION: *)\n  ex_intro nat (fun n => beautiful (S n)) 2 b_3.\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  (* SOLUTION: *)\n  intros X P H G. inversion G as [x Hx]. \n  apply Hx. apply H.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  (* SOLUTION: *)\n  intros EM X P H x.\n  assert (P x \\/ ~ P x) as H1 by apply EM.\n  inversion H1 as [HPx | HNPx].\n  Case \"P x\".\n    apply HPx.\n  Case \"~P x\".\n    apply ex_falso_quodlibet. \n    apply H.\n    apply ex_intro with (witness:=x).\n    apply HNPx.\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   (* SOLUTION: *)\n  intros X P Q. split.\n  Case \"->\". intros H. inversion H as [x Hx].\n    inversion Hx as [HP | HQ].\n    SCase \"P x\". left. exists x. apply HP.\n    SCase \"Q x\". right. exists x. apply HQ.\n  Case \"<-\". intros H. inversion H as [HPx | HQx]. \n    SCase \"exists x, P x\". inversion HPx as [x Hx]. exists x. \n      left. apply Hx.\n    SCase \"exists x, Q x\". inversion HQx as [x Hx]. exists x. \n      right. apply Hx.  Qed.\n(** [] *)\n\n(* Print dist_exists_or. *)\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has (roughly)\n    the following inductive definition. *)\n\n(* (We enclose the definition in a module to avoid confusion with the\n    standard library equality, which we have used extensively\n    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: *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) \n                    : type_scope.\n\n(** The definition of [=] is a bit subtle.  The way to think about it\n    is that, given a set [X], it defines a _family_ of propositions\n    \"[x] is equal to [y],\" indexed by pairs of values ([x] and [y])\n    from [X].  There is just one way of constructing evidence for\n    members of this family: applying the constructor [refl_equal] to a\n    type [X] and a value [x : X] yields evidence that [x] is equal to\n    [x]. *)\n\n(** **** Exercise: 2 stars (leibniz_equality) *)\n(** The inductive definitions of equality corresponds to _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 leibniz_equality : forall (X : Type) (x y: X), \n x = y -> forall P : X -> Prop, P x -> P y.\nProof.\n(* SOLUTION: *)\nintros X x y H.\ninduction H.\nintros P H. apply H.\nQed.\n(** [] *)\n\n(** 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(* ####################################################### *)\n(** ** Inversion, Again (Advanced) *)\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(** **** Exercise: 1 star, optional (dist_and_or_eq_implies_and) *)  \nLemma dist_and_or_eq_implies_and : forall P Q R,\nP /\\ (Q \\/ R) /\\ Q = R -> P/\\Q.\nProof.\n(* SOLUTION: *)\nintros P Q R H.\ninversion H. inversion H1.\nsplit. \nCase \"left\". \napply H0. \nCase \"right\".\ninversion H2. \nSCase \"left\". apply H4. \nSCase \"right\".\ninversion H3. (* rewrite H3. *)\napply H4.\nQed.\n(** [] *)\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, the built-in logic is even smaller than it appears, since\n    [->] and [forall] are actually the _same_ primitive!\n\n    The [->] notation is actually just a shorthand for a degenerate\n    use of [forall]. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := \n  forall n, forall (E : beautiful n), beautiful (n+3).\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    beautiful.  But the name [E] for this evidence is not used in the\n    rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name for it.  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(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n(** We've seen an inductive definition of one fundamental relation:\n    equality.  Another useful one is the \"less than or equal to\"\n    relation on numbers: *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [~(2 <= 1)].) *)\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 H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n(* SOLUTION: *)\nInductive total_relation : nat -> nat -> Prop :=\n  tot : forall n m : nat, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* SOLUTION: *)\nInductive empty_relation : nat -> nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* SOLUTION: *)\n   - The first proposition is provable and the second is not.\n     The proof term for the first is:\n       (c3 _ _ _ (c2 _ _ _ c1)).\n   - Dropping [c5] would not change the set of provable\n     propositions.  [c4] and [c1] don't interact with [c5], since\n     they're already symmetric in [m] and [n]; [c2] followed by\n     [c5] is equivalent to [c3], and vice versa.\n\n   - Dropping [c4] would not change the set of provable\n     propositions.  [c4] is equivalent to undoing an application\n     of [c2] and an application of [c3].\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(* SOLUTION: *)\nTheorem R_plus: forall m n o, R m n o <-> m + n = o.\nProof.\n  intros m n o. split.\n  Case \"->\". intros H. induction H.\n    SCase \"c1\". reflexivity.\n    SCase \"c2\". simpl. rewrite IHR. reflexivity.\n    SCase \"c3\". rewrite <- plus_n_Sm. rewrite IHR. reflexivity.\n    SCase \"c4\". simpl in IHR. rewrite <- plus_n_Sm in IHR.\n      inversion IHR. reflexivity.\n    SCase \"c5\". rewrite plus_comm. apply IHR.\n  Case \"<-\". generalize dependent n. generalize dependent m. \n    induction o as [|o']. \n    SCase \"o = 0\". \n      intros m n H.\n      destruct m as [|m'].\n      SSCase \"m = 0\". \n        simpl in H. rewrite -> H. apply c1.\n      SSCase \"m = S m'\".\n        inversion H.\n    SCase \"o = S o'\".\n      intros m n H. destruct m as [|m'].\n      SSCase \"m = 0\".\n        simpl in H. rewrite -> H. apply c3. apply IHo'. \n        reflexivity.\n      SSCase \"m = S m'\".\n        apply c2. apply IHo'. inversion H. reflexivity.\nQed.\n\n(** [] *)\n\nEnd R.\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  (* SOLUTION: *)\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\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(* SOLUTION: *)\nTheorem forallb_spec : forall X test l, \n   forallb test l = true <-> all X (fun x => test x = true) l.\nProof.\n  intros X test.\n  split.\n  Case \"-> direction\". induction l as [|x l'].\n    SCase \"l = []\". simpl. intros. apply all_nil.\n    SCase \"l = x::l'\". simpl. \n      intros H. apply andb_true__and in H. inversion H as [H1 H2].\n      apply all_cons. apply H1. apply IHl'. apply H2.\n  Case \"<- direction\". induction l as [|x l'].\n    SCase \"l = []\". simpl. reflexivity.\n    SCase \"l = x::l'\". simpl.\n      intros H. inversion H.\n      apply and__andb_true. split.\n        apply H2.\n        apply IHl'. apply H3.\nQed. \n\n(* This theorem exactly captures the input-output behaviour of [allb]. However, \n   it does not say anything about the running time. *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example, \n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\n(* SOLUTION: *)\nInductive merge {X:Type} : list X -> list X -> list X -> Prop :=\n  | merge_empty : \n      merge [] [] [] \n  | merge_left : forall l1 l2 l3 x, \n      merge l1 l2 l3 -> \n      merge (x::l1) l2 (x::l3)\n  | merge_right : forall l1 l2 l3 x, \n      merge l1 l2 l3 -> \n      merge l1 (x::l2) (x::l3).  \n\nTheorem filter_good : forall {X : Type}, \n                      forall (test : X->bool), \n                      forall (l1 l2 l3 : list X),\n  forallb test l1 = true ->\n  forallb (fun x => negb (test x)) l2 = true ->\n  merge l1 l2 l3 ->\n  filter test l3 = l1.\nProof.\n  intros X test l1 l2 l3 HT HF HM.\n  induction HM.  \n  Case \"merge_empty\". reflexivity.\n  Case \"merge_left\". unfold filter.\n    remember (test x) as testx. destruct testx.\n    SCase \"test x = true\". unfold filter in IHHM. rewrite -> IHHM. reflexivity.\n      unfold forallb in HT. rewrite <- Heqtestx in HT. apply HT. apply HF.\n    SCase \"test x = false\". unfold forallb in HT. rewrite <- Heqtestx in HT.\n      inversion HT.\n  Case \"merge_right\". unfold filter.\n    remember (test x) as testx. destruct testx.\n    SCase \"test x = true\". unfold forallb in HF. rewrite <- Heqtestx in HF.\n      inversion HF.  \n    SCase \"test x = false\". \n      unfold filter in IHHM. rewrite -> IHHM. reflexivity.\n      apply HT. unfold forallb in HF. rewrite <- Heqtestx in HF. apply HF. \nQed.\n\n(* An alternate solution: *)\nLemma cons_eq : forall X (x:X) l1 l2, l1 = l2 -> x::l1 = x::l2.\nProof. intros. rewrite -> H. reflexivity. Qed.\n\nLemma negb_true : forall b, negb b = true -> b = false.\nProof. intros b eq. destruct b; [inversion eq | reflexivity]. Qed.\n\nTheorem filter_spec : forall (X:Type) (test:X->bool) (l l1 l2:list X),\n merge l1 l2 l ->\n forallb test l1 = true ->\n forallb (fun x => negb (test x)) l2 = true ->\n l1 = filter test l.\nProof.\n intros X test l1 l2 l3 HM. induction HM.\n Case \"merge_empty\". intros HT HF. simpl. reflexivity.\n Case \"merge_left\". intros HT HF. simpl. simpl in HT.\n   apply andb_true__and in HT. inversion HT as [HX HL1].\n   rewrite -> HX. apply cons_eq. apply IHHM. apply HL1. apply HF.\n Case \"merge_right\". intros HT HF. simpl. simpl in HF.\n   apply andb_true__and in HF. inversion HF as [HX HL2].\n   apply negb_true in HX. rewrite -> HX. apply IHHM. apply HT. apply HL2.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* SOLUTION: *)\n(** We reproduce the definition of subseq here, with a different name\n    so it doesn't conflict. *)\nInductive subseq' {X:Type} : list X -> list X -> Prop :=\n  | sub_nil  : forall l, subseq' [] l\n  | sub_take : forall x l1 l2, subseq' l1 l2 -> subseq' (x :: l1) (x :: l2)\n  | sub_skip : forall x l1 l2, subseq' l1 l2 -> subseq' l1 (x :: l2).\n\n(** A few lemmas about subseq. *)\nLemma subseq_drop_l : forall (X:Type) (x:X) (l1 l2 : list X),\n  subseq' (x :: l1) l2 -> subseq' l1 l2.\nProof.\n  intros X x l1 l2 Hsub.\n  induction l2 as [|x' l2'].\n  Case \"l2 = []\". inversion Hsub.\n  Case \"l2 = x' :: l2'\".\n    inversion Hsub.\n    SCase \"sub_take\". apply sub_skip. apply H0.\n    SCase \"sub_skip\". apply sub_skip. apply IHl2'. apply H1.\nQed.\n\nLemma subseq_drop : forall (X:Type) (x:X) (l1 l2 : list X),\n  subseq' (x :: l1) (x :: l2) -> subseq' l1 l2.\nProof.\n  intros X x l1 l2 Hsub.\n  inversion Hsub.\n    apply H0.\n    apply subseq_drop_l with x. apply H1.\nQed.\n\n(** Now for some silly lemmas about [<=], which we need since we\n    redefined [<=] ourselves. Of course, these are all in the Coq\n    standard library. *)\n\nLemma le_0_n : forall n, 0 <= n.\nProof.\n  induction n as [|n']. \n    apply le_n. \n    apply le_S. apply IHn'.\nQed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H1 H2. induction H2.\n    apply H1.\n    apply le_S. apply IHle.\nQed.\n\nLemma 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\nLemma le_S_n : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m H. inversion H.\n  Case \"m = n\". apply le_n.\n  Case \"S n <= m\". apply le_Sn_le. apply H1.\nQed.\n\nLemma le_n_S : forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m H. induction H.\n    apply le_n.\n    apply le_S. apply IHle.\nQed.\n\nLemma Sn_le_n : forall n, ~ (S n <= n).\nProof.\n  unfold not. induction n as [|n'].\n  Case \"n = 0\". intros contra. inversion contra.\n  Case \"n = S n'\". intros H. apply IHn'.\n  apply le_S_n. apply H.\nQed.\n\n(** A list is _maximal_ with property [P] if it has the property, and\n    every other list with the property is at most as long as it is. *)\n\nDefinition maximal {X:Type} (lmax : list X) (P : list X -> Prop) := P\nlmax /\\ forall l', P l' -> length l' <= length lmax.\n\n(** A \"good subsequence\" for a given list [l] and a [test] is a\n    subsequence of [l] all of whose members evaluate to [true] under\n    the [test]. *)\n\nDefinition good_subseq {X:Type} (test : X -> bool) (l lsub : list X) :=\n  subseq' lsub l /\\ forallb test lsub = true.\n\n(** Good subsequences can be extended with good elements. *)\n\nLemma good_subseq_extend : forall (X:Type) (test : X -> bool) \n                                  (l lsub : list X) (x : X),\n  good_subseq test l lsub -> \n  test x = true -> \n  good_subseq test (x::l) (x::lsub).\nProof.\n  intros X test l lsub x [Hsub Hall] Hx. split.\n  Case \"subseq\". apply sub_take. apply Hsub.\n  Case \"all\". simpl. rewrite Hx. apply Hall.\nQed.\n\n(** If [lmax] is a maximal good subsequence of [x :: l] and [x] is not good,\n    then [lmax] is also a maximal good subsequence of [l]. *)\n\nLemma maximal_strengthening : forall (X:Type) (x:X) \n                                     (lmax l : list X) \n                                     (test : X -> bool),\n  maximal lmax (good_subseq test (x::l)) ->\n  test x = false ->\n  maximal lmax (good_subseq test l).\nProof.\n  intros X x lmax l test [[Hsub Hall] Hlen] Hx.\n  split. split.\n  Case \"subseq\".\n    inversion Hsub.\n    SCase \"sub_nil\". apply sub_nil.\n    SCase \"sub_take\". rewrite H in H0.\n      rewrite <- H0 in Hall. simpl in Hall. rewrite Hx in Hall. inversion Hall.\n    SCase \"sub_skip\". apply H1.\n  Case \"all\". apply Hall.\n  Case \"len\". intros l' [Hsub' Hall']. apply Hlen. split.\n    SCase \"subseq\". apply sub_skip. apply Hsub'.\n    SCase \"all\". apply Hall'.\nQed.\n\n(** Some easy lemmas about filter: its result is a good subsequence of\n    the original list. *)\n\nLemma filter_subseq : forall (X:Type) (l : list X) (test : X -> bool),\n  subseq' (filter test l) l.\nProof.\n  intros X l test. induction l as [|x l'].\n  Case \"l = []\". apply sub_nil.\n  Case \"l = x :: l'\". simpl. destruct (test x).\n    SCase \"test x = true\". apply sub_take. apply IHl'.\n    SCase \"test x = false\". apply sub_skip. apply IHl'.\nQed.\n\nLemma filter_all : forall (X:Type) (l : list X) (test : X -> bool),\n  forallb test (filter test l) = true.\nProof.\n  intros X l test. induction l as [|x l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = x :: l'\". simpl. \n    remember (test x) as tx. destruct tx.\n    SCase \"test x = true\". simpl. rewrite <- Heqtx. apply IHl'.\n    SCase \"test x = false\". apply IHl'.\nQed.\n\n(** And now for the main theorem: [lsub] is a maximal good subsequence\n    of [l] if and only if [filter test l = lsub]. *)\n\nTheorem filter_spec2 : forall (X:Type) (l lsub:list X) (test : X -> bool),\n  maximal lsub (good_subseq test l) <-> filter test l = lsub.\nProof. \n  split.\n  Case \"->\". \n    generalize dependent lsub.\n    induction l as [|x l'].\n    SCase \"l = []\". \n      (* lsub = [] since lsub is a subseq of l. *)\n      intros lsub [[Hsub _] _].\n      inversion Hsub. reflexivity.\n    SCase \"l = x :: l'\".\n      intros lsub H. simpl.\n      remember (test x) as tx. destruct tx.\n      SSCase \"test x = true\".\n        destruct H as [[Hsub Hall] Hlen].\n        (* in this case, lsub must begin with x, since otherwise it\n           wouldn't be maximal. *)\n        destruct lsub as [|x' lsub'].\n        SSSCase \"lsub = []\". (* impossible: contradicts maximality of lsub *)\n          assert (length [x] <= length ([] : list X)) as contra.\n          SSSSCase \"proof of assertion\".\n            apply Hlen. split. \n              apply sub_take. apply sub_nil.\n              simpl. rewrite <- Heqtx. reflexivity.\n          inversion contra.\n        SSSCase \"lsub = x' :: lsub'\".\n          assert (x = x'). (* because of maximality again *)\n          SSSSCase \"proof of assertion\".\n            inversion Hsub. \n            SSSSSCase \"sub_take\". reflexivity.\n            SSSSSCase \"sub_skip\". (* contradiction, since x :: x' :: lsub' \n                                     would be longer *)\n              assert (length (x :: x' :: lsub') <= length (x' :: lsub')).\n              SSSSSSCase \"proof of assertion\".\n                apply Hlen. split.\n                  apply sub_take. apply H1.\n                  simpl. rewrite <- Heqtx. simpl. simpl in Hall.\n                  apply Hall.\n              simpl in H3. apply Sn_le_n in H3. inversion H3.\n          rewrite H.\n          rewrite -> (IHl' lsub'). reflexivity.\n          split. split. rewrite H in Hsub. apply subseq_drop with x'. apply Hsub.\n            simpl in Hall. apply andb_true_elim2 in Hall. apply Hall.\n            intros l0 Hgood0. rewrite <- H in Hlen. simpl in Hlen.\n            apply le_S_n. \n            apply (Hlen (x :: l0)). apply good_subseq_extend. apply Hgood0.\n            symmetry. apply Heqtx.\n      SSCase \"test x = false\".\n        apply IHl'. \n        apply maximal_strengthening with x. apply H.\n        symmetry. apply Heqtx.\n  Case \"<-\". intros Hfilter.\n    split. split.\n    SCase \"subseq\". rewrite <- Hfilter. apply filter_subseq.\n    SCase \"all\". rewrite <- Hfilter. apply filter_all.\n    SCase \"len\". generalize dependent lsub. induction l as [|x l2].\n      SSCase \"l = []\". intros lsub _ l' [Hsub _]. inversion Hsub. apply le_0_n.\n      SSCase \"l = x :: l2\". intros lsub Hfilter l' [Hsub Hall].\n        simpl in Hfilter.\n        remember (test x) as tx. destruct tx.\n        SSSCase \"test x = true\".\n          rewrite <- Hfilter. inversion Hsub.\n          SSSSCase \"sub_nil\". apply le_0_n.\n          SSSSCase \"sub_take\". simpl. apply le_n_S.\n            apply IHl2. reflexivity. split. apply H1. rewrite <- H0 in Hall.\n              simpl in Hall. apply andb_true_elim2 in Hall. apply Hall.\n          SSSSCase \"sub_skip\". simpl. apply le_S.\n            apply IHl2. reflexivity. split. apply H1. apply Hall.\n        SSSCase \"test x = false\".\n          apply IHl2. apply Hfilter. split. \n          inversion Hsub. apply sub_nil. rewrite <- H0 in Hall. rewrite H in Hall.\n            simpl in Hall. rewrite <- Heqtx in Hall. inversion Hall.\n            apply H1.\n          apply Hall.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l]. \n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall {X:Type} (xs ys : list X) (x:X), \n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  (* SOLUTION: *)\n  intros X xs ys x. \n  Case \"->\".\n    induction xs as [|x' xs']. \n    SCase \"xs = nil\".\n      intros AI. \n      simpl in AI. right. apply AI. \n    SCase \"xs = x'::xs'\".\n      intros AI.\n      simpl in AI.  inversion AI as [l | b l]. \n      SSCase \"ai_here\".\n        left. apply ai_here.\n      SSCase \"ai_later\".    \n         assert (AI' : appears_in x xs' \\/ appears_in x ys). \n            apply IHxs'.  apply H0. \n         destruct AI'. \n         SSSCase \"left\".\n           left.  apply ai_later.  apply H2. \n         SSSCase \"right\".\n           right.  apply H2.  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  (* SOLUTION: *)\n  intros X xs ys x. \n    induction xs as [|x' xs']. \n    SCase \"xs = nil\".\n      intros [AI1 | AI2].\n        SSCase \"left\".\n          inversion AI1.\n        SSCase \"right\".\n          apply AI2.\n    SCase \"xs = x'::xs'\".\n      intros [AI1 | AI2]. \n        SSCase \"left\". \n           inversion AI1. \n           SSSCase \"ai_here\". \n             apply ai_here.\n           SSSCase \"ai_later\". \n             simpl. apply ai_later. apply IHxs'. left. apply H0. \n        SSCase \"right\". \n          simpl.  apply ai_later.  apply IHxs'. right. apply AI2.  Qed.\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(* SOLUTION: *)\nDefinition disjoint {X:Type} (l1 l2: list X) :=\n  forall (x:X), appears_in x l1 -> ~ appears_in x 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(* SOLUTION: *)\nInductive no_repeats {X:Type} : list X -> Prop :=\n  | nr_nil : no_repeats nil\n  | nr_cons : forall a l, \n              no_repeats l ->\n              ~ (appears_in a l) ->\n              no_repeats (a::l).\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\n(* SOLUTION: *)\n(* Here are some possible answers: *)\n  \nLemma no_repeats_append : forall {X:Type} (l1 l2: list X),\n   no_repeats l1 -> no_repeats l2 -> disjoint l1 l2 -> no_repeats (l1 ++ l2).\nProof.\n  intros X l1. induction l1 as [| x l1']. \n  Case \"l1 = nil\".\n    intros l2 NR1 NR2 D.  simpl. apply NR2. \n  Case \"l1 = x:l1'\".\n    intros l2 NR1 NR2 D. simpl.\n    apply nr_cons.  apply IHl1'. inversion NR1 as [| ? ? NRl1' NA]. \n    apply NRl1'. apply NR2. \n    unfold disjoint. intros x0 AI.  apply D. apply ai_later.  apply AI.\n    intro contra.  apply appears_in_app in contra.  inversion contra. \n    inversion NR1 as [| ? ? NRl1' NA]. apply NA. apply H. \n    unfold disjoint in D.  apply D with x.  \n    apply ai_here.\n    apply H. \nQed.\n\nLemma no_repeats_disjoint : forall {X:Type} (l1 l2: list X), \n                            no_repeats (l1++l2) -> disjoint l1 l2.\nProof.\n   unfold disjoint.\n   induction l1 as [|x l1']. \n     intros l2 NR x AI.  inversion AI. \n     intros l2 NR x0 AI.  simpl in NR. inversion NR. inversion AI.  \n       intro contra. apply H2. \n          apply app_appears_in.  right. apply contra. \n       apply IHl1'.  apply H1. apply H4.\nQed.\n\n(* We can also show the following results about [no_repeats] and [++]\n   by themeselves *)\nLemma no_repeats_left : forall {X:Type} (l1 l2: list X),\n                        no_repeats (l1++l2) -> no_repeats l1.\nProof.\n   induction l1 as [|x l1'].  \n       intros l2 NR. apply nr_nil.\n       intros l2 NR. inversion NR. apply nr_cons. apply (IHl1' l2).  apply H1.\n       intro contra. apply H2. apply app_appears_in.  left. apply contra. \nQed.\n       \n\nLemma no_repeats_right: forall {X:Type} (l1 l2: list X),\n                        no_repeats (l1++l2) -> no_repeats l2.\nProof.\n   induction l1 as [|x l1'].\n     intros l2 NR. simpl in NR.  apply NR. \n     intros l2 NR. inversion NR. apply IHl1'.  apply H1. \nQed.\n\n(* This theorem combines the various lemmas to give a complete\n   characterization *)\nTheorem no_repeats_disjoint_app : forall {X:Type} (l1 l2: list X),\n  no_repeats (l1++l2) <->\n  (no_repeats l1 /\\ no_repeats l2 /\\ disjoint l1 l2).\nProof.\n  intros X l1 l2. \n  split.\n  Case \"->\".\n    intro NR. split.\n      apply no_repeats_left with l2. apply NR.\n      split.\n        apply no_repeats_right with l1. apply NR.\n        apply no_repeats_disjoint. apply NR.\n  Case \"<-\".\n    intros [NR1 [NR2 DISJ]]. \n    apply no_repeats_append. apply NR1. apply NR2.  apply DISJ. \nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* SOLUTION: *)\n  induction n as [| n'].\n  Case \"n = 0\".\n    apply le_n.\n  Case \"n = S n'\".\n    apply le_S. apply IHn'.  Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  (* SOLUTION: *)\n  intros n m H. induction H.\n    apply le_n.\n    apply le_S. apply IHle.  Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m. \n  (* SOLUTION: *)\n   intros n H. \n     destruct n. \n       apply le_n.\n       inversion H.  inversion H1. \n   intros n H. \n     inversion H; subst. \n       apply le_n. \n       apply le_S.  apply IHm.  assumption.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  (* SOLUTION: *)\n  intros a b. induction a.\n    apply O_le_n.\n    apply n_le_m__Sn_le_Sm in IHa. assumption.  Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n (* SOLUTION: *)\n  intros. induction H; unfold lt.\n  split. \n    apply n_le_m__Sn_le_Sm. apply le_plus_l.\n    rewrite plus_comm. apply n_le_m__Sn_le_Sm. apply le_plus_l. \n  inversion IHle as [Hn1m Hn2m].\n    unfold lt in Hn1m, Hn2m.\n    apply le_S in Hn1m. apply le_S in Hn2m.\n    split. apply Hn1m. apply Hn2m.  Qed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* SOLUTION: *)\n  unfold lt. intros. apply le_S. assumption. Qed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  (* SOLUTION: *)\n  intros n.\n  induction n as [| n']. \n  Case \"n = 0\". intros m H.\n    apply O_le_n.\n  Case \"n = S n'\". intros m H.\n    simpl in H. destruct m as [| m'].\n    SCase \"m = 0\".\n      inversion H.\n    SCase \"m = S m'\".\n      apply IHn' in H.\n      apply n_le_m__Sn_le_Sm.\n      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  (* SOLUTION: *)\n  intros n. induction n as [| n'].\n  Case \"n = 0\". intros m H.\n    simpl in H. inversion H.\n  Case \"n = S n'\". intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      reflexivity.\n    SCase \"m = S m'\".\n      simpl. apply IHn'. simpl in H. assumption.  Qed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  (* SOLUTION: *)\n  intros.\n  unfold not. intro Hle. induction Hle.\n    Case \"le_n\".\n      rewrite <- ble_nat_refl in H.  inversion H.\n    Case \"le_S\".\n      apply IHHle.\n      apply ble_nat_n_Sn_false. assumption.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n (* SOLUTION: *)\n | nostutter0: nostutter nil\n | nostutter1: forall n, nostutter (n::nil)\n | nostutter2: forall a b r, a<>b -> nostutter(b::r) -> nostutter (a::b::r)\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(* SOLUTION: *)\n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_2:  nostutter [].\n(* SOLUTION: *)\n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_3:  nostutter [5].\n(* SOLUTION: *)\n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_4:      not (nostutter [3,1,1,4]).\n(* SOLUTION: *)\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, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some \n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall {X:Type} (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2. \nProof. \n  (* SOLUTION: *)\n  intros X l1. induction l1 as [|x l1'].\n  Case \"l1 = nil\". reflexivity.\n  Case \"l1 = x::l1'\". intros l2.  simpl. rewrite -> IHl1'. reflexivity. 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  (* SOLUTION: *)\n  induction l as [|x' l']; intros AI. \n  Case \"l = nil\". inversion AI. \n  Case \"l = x'::l'\". inversion AI.  \n    SCase \"x = x'\". exists []. exists l'. reflexivity.\n    SCase \"appears_in x l'\". destruct (IHl' H0) as [l1' [l2' EQ]].\n       exists (x'::l1'). exists l2'. rewrite -> EQ.  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  (* SOLUTION: *)\n  | rep_here : forall a l, appears_in a l -> repeats (a::l)\n  | rep_later : forall a l, repeats l -> repeats (a::l)\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  (* SOLUTION: *)\n    intros l2 EM INC NR.  simpl in NR. inversion NR. \n    intros l2 EM INC NR. \n    destruct (EM (appears_in x l1)). \n      left. assumption.\n      right. destruct (appears_in_app_split x l2) as [l2a [l2b EQ]]. \n        apply INC. left.\n        apply (IHl1 (l2a ++ l2b) EM). \n         intros x0 AI.  \n          assert (x0 <> x).  intro. subst. apply H. apply AI. \n          assert (appears_in x0 l2).  apply INC. right. assumption.\n          rewrite EQ in H1. apply appears_in_app in H1. apply app_appears_in. \n            inversion H1. \n              left. assumption.\n              inversion H2; subst. \n                 apply ex_falso_quodlibet.  apply H0. reflexivity. \n                 right.  assumption.\n         assert (length l2 = S(length (l2a ++ l2b))).\n            rewrite EQ.  \n            rewrite app_length. rewrite app_length. rewrite plus_comm. \n            simpl. rewrite plus_comm. reflexivity.\n        rewrite H0 in NR. simpl in NR. \n        apply Sn_le_Sm__n_le_m.  apply NR.  Qed. \n(** [] *)\n\n(* $Date: 2013-02-10 18:08:54 -0500 (Dom, 10 Feb 2013) $ *)\n\n", "meta": {"author": "ysyshtc", "repo": "cis500", "sha": "c538fd552b09cbcf4a972fc3474d48d0c246e30d", "save_path": "github-repos/coq/ysyshtc-cis500", "path": "github-repos/coq/ysyshtc-cis500/cis500-c538fd552b09cbcf4a972fc3474d48d0c246e30d/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7691912489284752}}
{"text": "Require Export Coq.Unicode.Utf8.\nRequire Import Omega.\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]; omega.\nQed.\n\nLemma lt_inv_plus {n m} : n < m → exists r, m = n + S r.\nProof.\n  induction 1.\n  - exists 0; omega.\n  - destruct IHle as [r ?]; subst.\n    exists (S r); omega.\nQed.\n\nLemma le_inv_plus {n m} : n ≤ m → exists r, m = n + r.\nProof.\n  induction 1.\n  - exists 0; omega.\n  - destruct IHle as [r ?]; subst.\n    exists (S r); omega.\nQed.\n\n", "meta": {"author": "dominiquedevriese", "repo": "facomp-stlc-coq", "sha": "77043e68813d3a7ed8926802191638f063de1544", "save_path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq", "path": "github-repos/coq/dominiquedevriese-facomp-stlc-coq/facomp-stlc-coq-77043e68813d3a7ed8926802191638f063de1544/Common/Common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7691912305553092}}
{"text": "Require Import ZArith.\nRequire Import String.\nRequire Import Basics.\nRequire Import Program.Combinators.\n\nRequire Import Algae.Group.\nRequire Import Algae.Monoid.\nRequire Import Algae.Semigroup.\n\n(* And here we play with the machinery because it's fun! *)\n\n(* This is useless since N can't form a group. *)\nInstance magma_nat : Magma nat plus.\nProof. reflexivity. Qed.\n\nInstance semigroup_nat : Semigroup magma_nat.\nProof.\n  split.\n  intros.\n  apply Plus.plus_assoc.\nQed.\n\nInstance monoid_nat : Monoid semigroup_nat 0.\nProof.\n  split.\n  intros.\n  apply Plus.plus_0_l.\n  apply Plus.plus_0_r.\nQed.\n\nRequire Export Ascii.\nOpen Scope string_scope.\n\n\n(* This is useless for us too - The free monoid over strings + string concat. *)\n(* I couldn't find a built-in exported theorem for associativity of append. *)\nInstance magma_str_concat : Magma string append.\nProof. reflexivity. Qed.\n\nLemma string_assoc :\n  (forall a x y, (String a x) <+> y = String a (x <+> y)).\nProof. reflexivity. Qed.\n\nInstance semigroup_str_concat : Semigroup magma_str_concat.\nProof.\n  split.\n  intros.\n  induction x.\n  reflexivity.\n  rewrite string_assoc.\n  rewrite IHx.\n  reflexivity.\nQed.\n\nInstance monoid_str_concat : Monoid semigroup_str_concat EmptyString.\nProof.\n  split.\n  intros.\n  trivial.\n  intros.\n  induction x.\n  trivial.\n  rewrite string_assoc.\n  rewrite IHx.\n  reflexivity.\nQed.\n\n\n(* Functions form a monoid under composition. *)\nVariable A : Type.\nInstance magma_functions  : Magma (A -> A) compose.\nProof. reflexivity. Qed.\n\nInstance semigroup_functions : Semigroup magma_functions.\nProof.\n  split.\n  reflexivity.\nQed.\n\nDefinition id x : A := x.\n\nInstance monoid_functions : Monoid semigroup_functions id.\nProof.\n  split.\n  intros.\n  reflexivity.\n  reflexivity.\nQed.\n\n(* They only form a group if they are all isomorphisms in the respective *)\n(* category (bijections in Set). So we can't say much here. *)\n\n\nInstance magma_ints_add : Magma Z Z.add.\nProof. reflexivity. Qed.\n\nInstance semigroup_ints_add : Semigroup magma_ints_add.\nProof.\n  split.\n  intros.\n  rewrite Z.add_assoc.\n  reflexivity.\nQed.\n\nInstance monoid_ints_add : Monoid semigroup_ints_add Z0.\nProof.\n  split.\n  apply Z.add_0_l.\n  apply Z.add_0_r.\nQed.\n\nInstance group_ints_add : Group monoid_ints_add Z.opp.\nProof.\n  split.\n  intros.\n  rewrite Z.add_comm.\n  rewrite Z.add_opp_diag_r.\n  reflexivity.\n  intros.\n  rewrite Z.add_comm.\n  rewrite Z.add_opp_diag_l.\n  reflexivity.\nQed.\n\nRequire Export Ascii.\nOpen Scope string_scope.\nEval compute in \"aa\" <+> \"bb\".", "meta": {"author": "relrod", "repo": "coq-playground", "sha": "b6e5538ef9fce09a4169169c78a5bc2da5951e8a", "save_path": "github-repos/coq/relrod-coq-playground", "path": "github-repos/coq/relrod-coq-playground/coq-playground-b6e5538ef9fce09a4169169c78a5bc2da5951e8a/algebra/Instances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7690475908214114}}
{"text": "From Coq Require Import Reals.\nFrom Coq Require Import QArith.\nRequire Import Field.\n \nOpen Scope R_scope.\n\nDefinition C : Type := R * R.\n\nDefinition RtoC (r : R) : C := (r, 0).\nCoercion RtoC : R >-> C.\n\nDeclare Scope C_scope.\nBind Scope C_scope with C.\nOpen Scope C_scope.\n\nNotation i := (0,1).\nNotation \"0\" := (RtoC 0) : C_scope.\nNotation \"1\" := (RtoC 1) : C_scope.\n\nDefinition Cadd (c1 c2 : C) : C := (fst c1 + fst c2, snd c1 + snd c2).\nDefinition Csub (c1 c2 : C) : C := (fst c1 - fst c2, snd c1 - snd c2).\nDefinition Cmul (c1 c2 : C) : C := (fst c1 * fst c2 - snd c1 * snd c2, fst c1 * snd c2 + snd c1 * fst c2).\nDefinition Copp (c : C) : C := (- fst c, - snd c).\nDefinition Cinv (c : C) : C := \n  ( fst c / (fst c * fst c + snd c * snd c), - snd c / (fst c * fst c + snd c * snd c) ).\nDefinition Cdiv (c1 c2 : C) : C := Cmul c1 (Cinv c2).\n\nLemma c_proj_eq : forall (c1 c2 : C),\n  fst c1 = fst c2 -> snd c1 = snd c2 -> c1 = c2.\nProof. \n  intros. destruct c1, c2. simpl in *. subst. reflexivity. \nQed.\n\nLemma Cadd_0_l: forall (c: C),\n  Cadd 0 c = c.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cadd_comm: forall (c1 c2: C),\n  Cadd c1 c2 = Cadd c2 c1.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cadd_assoc: forall c1 c2 c3: C,\n  Cadd c1 (Cadd c2 c3) = Cadd (Cadd c1 c2) c3.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cmul_1_l: forall c : C, \n  Cmul 1 c = c.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cmul_comm: forall c1 c2 : C, \n  Cmul c1 c2 = Cmul c2 c1.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cmul_assoc: forall c1 c2 c3 : C, \n  ( Cmul c1 (Cmul c2 c3) ) = ( Cmul (Cmul c1 c2) c3 ).\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Cdistr_l: forall c1 c2 c3: C, \n  Cmul (Cadd c1 c2) c3 = Cadd (Cmul c1 c3) (Cmul c2 c3).\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma Copp_def : forall c : C,\n  Cadd c (Copp c) = 0.\nProof.\n  intros. apply c_proj_eq; simpl; ring.\nQed.\n\nLemma C1_neq_C0 : 1 <> 0. \nProof. \nAdmitted.\n\nLemma Cinv_l : forall c: C, \n  c <> 0 -> Cmul (Cinv c) c = 1.\nProof.\n  Admitted.\n\nLemma C_Field_Theory : @field_theory C 0 1 Cadd Cmul Csub Copp Cdiv Cinv eq.\nProof.\n  constructor. constructor.\n  - apply Cadd_0_l.\n  - apply Cadd_comm.\n  - apply Cadd_assoc.\n  - apply Cmul_1_l.\n  - apply Cmul_comm.\n  - apply Cmul_assoc.\n  - apply Cdistr_l.\n  - reflexivity.\n  - apply Copp_def.\n  - apply C1_neq_C0.\n  - reflexivity.\n  - apply Cinv_l.\nDefined.\nAdd Field CField : C_Field_Theory.", "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/Field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7690475898624132}}
{"text": "(*\nVerificación Formal - 2020-II\nArchivo de definiciones - Números por paridad\n*)\n\n\n(*\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n                Inicio del Fragmento de código visto en clase.\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n*)\n\n\n(*\nDefinición inductiva para los números por paridad\n*)\nInductive BN :=\n  | Z : BN\n  | U : BN -> BN\n  | D : BN -> BN.\n\n\nCheck BN_ind.\nCheck BN_rec.\nCheck BN_rect.\n\n\n(* \nFunctió sucesor\n*)\nFixpoint sucBN (b:BN) : BN :=\nmatch 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*)  \nend.\n\n\n(*\nSe asume la existencia de un elemento indefinido en BN\n*)\nParameter (undefBN: BN). \n\n\nFixpoint predBN (b:BN): BN :=\nmatch b with\n  | Z => undefBN\n  | U Z => Z\n  | U x => D (predBN x)\n  | D x => U x\nend.\n\n\n(*\nFunciones para convertir entre BN y nat\n*)\nFixpoint toN (b:BN) : nat :=\nmatch b with \n  | Z => 0\n  | U x => 2*(toN x) + 1\n  | D x => 2*(toN x) + 2\nend.\n\n\nFixpoint toBN (n: nat) : BN :=\nmatch n with\n  | 0 => Z\n  | S x => sucBN (toBN x)\nend.\n\n\nEval compute in (toN (predBN (toBN 47))).\nEval compute in toN(D(U(U Z))).\nEval compute in toN(sucBN(D(U(U Z)))).\nEval compute in toBN 16.\n\n\n(*\nDefinición de la suma para BN\n*)\nFixpoint plusBN (a b : BN) : BN :=\nmatch 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))                \nend.\nNotation \"a ⊞ b\" := (plusBN a b) (at level 60).\n\n\n(*\nDefinición del orden estricto para BN\n*)\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\n(*\nDefinición del orden suave para BN\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.\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).\nNotation \"a ≤BN b\" := (lteqBN a b) (at level 70).\n\n\n(*\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n                   Fin del fragmento de código visto en clase.\n------------------------------------####------------------------------------\n------------------------------------####------------------------------------\n*)\n\n", "meta": {"author": "cigarcial", "repo": "VF2020II", "sha": "3a283400575564770e47f54e7f7cc66f996da0f1", "save_path": "github-repos/coq/cigarcial-VF2020II", "path": "github-repos/coq/cigarcial-VF2020II/VF2020II-3a283400575564770e47f54e7f7cc66f996da0f1/Tarea3/Defs_BN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7690317442215661}}
{"text": "(** * Logic: Logic in Coq *)\n\n(** Zhaoguo Wang **)\n\nRequire Export MoreProp. \n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\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.\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(** 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  split.\n  Case \"P\". apply HP.\n  Case \"Q\". apply HQ.\n  Case \"R\". apply HR.\nQed.\n\n(** **** Exercise: 2 stars (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  induction n as [ | n' ].\n  split.\n\n  Case \"n = O\".\n  intro H.\n  apply ev_0.\n\n  Case \"n = 1\".\n  intro H.\n  inversion H.\n\n  Case \"n = S n'\".\n  split.\n\n  SCase \"Left\".\n  intro H.\n  destruct IHn' as [ Hn' HSn' ].\n  apply HSn' in H.\n  apply H.\n\n  SCase \"Right\".\n  intro H.\n  destruct IHn' as [ Hn' HSn' ].\n  apply ev_SS in Hn'.\n  apply Hn'.\n  inversion H as [ H' ].\n  apply H'.\nQed.\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 (H1:(P /\\ Q)) ( H2:( Q /\\ R))\n=> conj P R  (proj1 P Q H1) (proj2 Q R H2).\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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  Case \"->\". intro H_P. apply H_P.\n  Case \"<-\". intro H_P. apply H_P.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R H_P_iff_Q H_Q_iff_R.\n  inversion H_P_iff_Q as [ H_P__Q H_Q__P ].\n  inversion H_Q_iff_R as [ H_Q__R H_R__Q ].\n  split.\n\n  Case \"->\".\n  intro H_P.\n  apply H_Q__R.\n  apply H_P__Q.\n  apply H_P.\n\n  Case \"<-\".\n  intro H_R.\n  apply H_Q__P.\n  apply H_R__Q.\n  apply H_R.\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, advanced (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 :=\nfun n => conj (beautiful n -> gorgeous n) (gorgeous n -> beautiful n) \n(beautiful__gorgeous n) (gorgeous__beautiful 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\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'' : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun P Q H =>\n  match H with\n    | or_introl EP => or_intror Q P EP\n    | or_intror EQ => or_introl Q P EQ\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\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.\n  intro H.\n  inversion H as [[HP | HQ] [HP' | HR]].\n  left. Case \"left\". apply HP.\n  left. Case \"left\". apply HP.\n  left. Case \"left\". apply HP'.\n  right. Case \"left\". split.\n  SCase \"left\". apply HQ.\n  SCase \"right\". 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  apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\nQed.\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\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, optional (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  intros b c.\n  destruct b.\n  Case \"b = true\".\n  destruct c.\n  SCase \"c = true\".\n  intro H.\n  inversion H.\n  SCase \"c = false\".\n  intro H.\n  right.\n  reflexivity.\n  Case \"b = false\".\n  intro H.\n  left.\n  reflexivity.\nQed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c.\n  destruct b.\n  Case \"b = true\".\n  intro H.\n  left.\n  reflexivity.\n  Case \"b = false\".\n  intro H.\n  right.\n  rewrite <- H.\n  unfold orb.\n  reflexivity.\nQed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros b c.\n  destruct b.\n  Case \"b = true\".\n  intro H.\n  inversion H.\n  Case \"b = false\".\n  intro H.\n  split.\n  reflexivity.\n  rewrite <- H.\n  unfold orb.\n  reflexivity.\nQed.\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\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := T : True.\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, 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(* FILL IN HERE *)\n   [Introduce P and H; unfold the definition\nof not to a nested expression. Then we can get G and apply G to the original proposition\n. Lastly, apply the hypothesis to prove it ]\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H_P__Q.\n  unfold not.\n  intros H_not_Q H_P.\n  apply H_not_Q.\n  apply H_P__Q.\n  apply H_P.\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.\n  unfold not.\n  intros [ HP H_not_P ].\n  apply H_not_P.\n  apply HP.\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(* Introduct P first and then unfold not using its definition. Then \nintroduct hypotheises HP and H_not_P. Apply both sequentially to get proof*)\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  \n  Case \"~ ev 1\".\n  intro contra.\n  inversion contra.\n  Case \"~ ev (S (S (S n)))\".\n  intro H_SSSn.\n  apply IHev.\n  inversion H_SSSn.\n  apply H1.\nQed.\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     from evidence for [P]. *) \n  Admitted.\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\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\n\n(** **** Exercise: 2 stars (not_eq_beq_false) *)\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  intros H.\n  simpl.\n  reflexivity.\n  destruct n'.\n  intros H.\n  simpl.\n  reflexivity.\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(** **** 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  induction n.\n  destruct m.\n  intros H.\n  inversion H.\n  simpl.\n  intros H.\n  unfold not.\n  intros H2.\n  inversion H2.\n  destruct m.\n  simpl.\n  intros H1.\n  unfold not.\n  intros H2.\n  inversion H2.\n  simpl.\n  intros H.\n  apply IHn in H.\n  unfold not in H.\n  unfold not.\n  intros H2.\n  inversion H2.\n  apply H.\n  rewrite H1.\n  reflexivity.\nQed.\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can express it with the following\n    definition: *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\n(** That is, [ex] is a family of propositions indexed by a type [X]\n    and a property [P] over [X].  In order to give evidence for the\n    assertion \"there exists an [x] for which the property [P] holds\"\n    we must actually name a _witness_ -- a specific value [x] -- and\n    then give evidence for [P x], i.e., evidence that [x] has the\n    property [P]. \n\n    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] facility can be used to introduce more\n    familiar notation for writing existentially quantified\n    propositions, exactly parallel to the built-in syntax for\n    universally quantified propositions.  Instead of writing [ex nat\n    ev] to express the proposition that there exists some number that\n    is even, for example, we can write [exists x:nat, ev x].  (It is\n    not necessary to understand exactly how the [Notation] definition\n    works.) *)\n\nNotation \"'exists' x , p\" := (ex _ (fun x => p))\n  (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" := (ex _ (fun x:X => p))\n  (at level 200, x ident, right associativity) : type_scope.\n\n(** We can use the usual set of tactics for\n    manipulating existentials.  For example, to prove an\n    existential, we can [apply] the constructor [ex_intro].  Since the\n    premise of [ex_intro] involves a variable ([witness]) that does\n    not appear in its conclusion, we need to explicitly give its value\n    when we use [apply]. *)\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2). \n  reflexivity.  Qed.\n\n(** Note, 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) = 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(* For natural number, (fun n => beautiful (S n) holds  *)\n\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\nex_intro _ (fun n => beautiful (S n)) 2 b_3.\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 H.\n  unfold not.\n  intros H1.\n  inversion H1.\n  apply H0. apply H.\nQed.\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** (The other direction of this theorem requires the classical \"law\n    of the excluded middle\".) *)\n\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (dist_exists_or) *)\n(** Prove that existential quantification distributes over\n    disjunction. *)\n\nTheorem dist_exists_or : forall (X:Type) (P Q : X -> Prop),\n  (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  intros X P Q.\n  unfold iff.\n  split.\n  intros H.\n  inversion H.\n  inversion H0.\n  left.\n  exists witness.\n  apply H1.\n\n  right.\n  exists witness.\n  apply H1.\n\n  intros H.\n  inversion H.\n  inversion H0.\n  exists witness.\n  left.\n  apply H1.\n\n  inversion H0.\n  exists witness.\n  right.\n  apply H1.\nQed.\n(* Print dist_exists_or. *)\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has (roughly)\n    the following inductive definition. *)\n\n(* (We enclose the definition in a module to avoid confusion with the\n    standard library equality, which we have used extensively\n    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: *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) \n                    : type_scope.\n\n(** The definition of [=] is a bit subtle.  The way to think about it\n    is that, given a set [X], it defines a _family_ of propositions\n    \"[x] is equal to [y],\" indexed by pairs of values ([x] and [y])\n    from [X].  There is just one way of constructing evidence for\n    members of this family: applying the constructor [refl_equal] to a\n    type [X] and a value [x : X] yields evidence that [x] is equal to\n    [x]. *)\n\n(** **** Exercise: 2 stars (leibniz_equality) *)\n(** The inductive definitions of equality corresponds to _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 leibniz_equality : forall (X : Type) (x y: X), \n x = y -> forall P : X -> Prop, P x -> P y.\nProof.\nintros X x y H P.\ninversion H.\ntrivial.\nQed.\n\n(** 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(* ####################################################### *)\n(** ** Inversion, Again (Advanced) *)\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(** **** Exercise: 1 star, optional (dist_and_or_eq_implies_and) *)  \nLemma dist_and_or_eq_implies_and : forall P Q R,\nP /\\ (Q \\/ R) /\\ Q = R -> P/\\Q.\nProof.\n intros P Q R H.\n  inversion H.\n  split.\n  apply H0.\n  inversion H1.\n  inversion H2.\n  apply H4.\n  rewrite H3.\n  apply H4.\nQed.\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, the built-in logic is even smaller than it appears, since\n    [->] and [forall] are actually the _same_ primitive!\n\n    The [->] notation is actually just a shorthand for a degenerate\n    use of [forall]. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := \n  forall n, forall (E : beautiful n), beautiful (n+3).\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    beautiful.  But the name [E] for this evidence is not used in the\n    rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name for it.  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(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ####################################################### *)\n(** * Relations *)\n\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.  \n\n(** We've seen an inductive definition of one fundamental relation:\n    equality.  Another useful one is the \"less than or equal to\"\n    relation on numbers: *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [~(2 <= 1)].) *)\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 H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nInductive next_even (n:nat) : nat -> Prop :=\n  | ne_1 : ev (S n) -> next_even n (S n)\n  | ne_2 : ev (S (S n)) -> next_even n (S (S n)).\n\n(** **** Exercise: 2 stars (total_relation) *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n\ttotal_relation1 : forall (n m:nat), total_relation n m.\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation : nat -> nat -> Prop := \nempty_relation1 : forall n m : nat, False -> empty_relation n m.\n\n(** **** Exercise: 3 stars (R_provability) *)\nModule R.\n(** We can define three-place relations, four-place relations,\n    etc., in just the same way as binary relations.  For example,\n    consider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n   | c1 : R 0 0 0 \n   | c2 : forall m n o, R m n o -> R (S m) n (S o)\n   | c3 : forall m n o, R m n o -> R m (S n) (S o)\n   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n   | c5 : forall m n o, R m n o -> R n m o.\n\n(** - Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - If we dropped constructor [c5] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n  \n    - If we dropped constructor [c4] from the definition of [R],\n      would the set of provable propositions change?  Briefly (1\n      sentence) explain your answer.\n\n(* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** 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(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | [] => true\n    | x :: l' => andb (test x) (forallb test l')\n  end.\n\n(** Using the property [all], write down a specification for [forallb],\n    and prove that it satisfies the specification. Try to make your \n    specification as precise as possible.\n\n    Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (filter_challenge) *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example, \n    [1,4,6,2,3]\n    is an in-order merge of\n    [1,6,2]\n    and\n    [4,3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (no_repeats) *)\n(** The following inductively defined proposition... *)\n\nInductive appears_in {X:Type} (a:X) : list X -> Prop :=\n  | ai_here : forall l, appears_in a (a::l)\n  | ai_later : forall b l, appears_in a l -> appears_in a (b::l).\n\n(** ...gives us a precise way of saying that a value [a] appears at\n    least once as a member of a list [l]. \n\n    Here's a pair of warm-ups about [appears_in].\n*)\n\nLemma appears_in_app : forall {X:Type} (xs ys : list X) (x:X), \n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma app_appears_in : forall {X:Type} (xs ys : list X) (x:X), \n     appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now use [appears_in] to define a proposition [disjoint X l1 l2],\n    which should be provable exactly when [l1] and [l2] are\n    lists (with elements of type X) that have no elements in common. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [appears_in] to define an inductive proposition\n    [no_repeats X l], which should be provable exactly when [l] is a\n    list (with elements of type [X]) where every member is different\n    from every other.  For example, [no_repeats nat [1,2,3,4]] and\n    [no_repeats bool []] should be provable, while [no_repeats nat\n    [1,2,1]] and [no_repeats bool [true,true]] should not be.  *)\n\n(* FILL IN HERE *)\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n as [| n'] ; \n  apply le_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 m.\n  destruct n as [| n'].\n  Case \"n = 0\".\n  induction m as [| m'].\n  SCase \"m = 0\".\n  intros H. apply le_n.\n  SCase \"m = S m'\".\n  intros H.\n  apply le_S.\n  apply IHm'.\n  apply O_le_n.\n  Case \"n = S n'\".\n  induction m as [| m'].\n  intros H.\n  SCase \"m = 0\".\n  inversion H.\n  SCase \"m = S m'\".\n  intros H.\n  inversion H ; subst.\n  apply le_n. apply le_S.\n  apply IHm'. apply H1.\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. \n    destruct n as [| n']. \n    SCase \"n = 0\".\n     intros H. apply le_n.\n    SCase \"n = S n'\".\n     intros H. inversion H. inversion H1.\n  Case \"m = S m'\".\n    intros n H.      \n    inversion H ; subst.\n    apply le_n.\n    apply le_S. apply IHm.\n    assumption.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  intros a.\n  induction a as [| a'].\n  Case \"a = 0\".\n    simpl.\n    apply O_le_n.\n  Case \"a = S a'\".\n    simpl. intros b.\n    apply n_le_m__Sn_le_Sm.\n    apply IHa'.\nQed.\n\n\nRemark O_lt_Sn : forall n, 0 < S n.\nProof.\n  intros n.\n  unfold lt. apply n_le_m__Sn_le_Sm.\n  apply O_le_n.\nQed.\n\n\nRemark Sn_le_m__n_le_m : forall n m, S n <= m -> n <= m.\nProof.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros m. intros H. apply O_le_n.\n  Case \"n = S n'\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      inversion H.  \n    SCase \"m = S m'\".\n      apply Sn_le_Sm__n_le_m in H.\n      apply IHn' in H.\n      apply n_le_m__Sn_le_Sm.\n      assumption.\nQed.\n\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n   induction n1 as [| n1'].\n  Case \"n1 = 0\".\n    intros n2 m H.\n    simpl in *.\n    split. \n    destruct m as [| m'].\n    SCase \"m = 0\".\n      inversion H.\n    SCase \"m = S m'\".\n      apply O_lt_Sn.\n    assumption.\n  Case \"n1 = S n1'\".\n    intros n2 m H.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      inversion H.\n    SCase \"m = S m'\".\n      split.\n      apply Sn_le_Sm__n_le_m in H.\n      unfold lt in *.\n      apply n_le_m__Sn_le_Sm.\n      simpl in H.\n      apply IHn1' in H.\n      inversion H.\n      assumption.\n      destruct n2 as [| n2'].\n      SSCase \"n2 = 0\".\n        apply n_le_m__Sn_le_Sm.\n        apply O_le_n.\n      SSCase \"n2 = S n2'\".\n        apply n_le_m__Sn_le_Sm.\n        rewrite <- plus_n_Sm in H.\n        apply Sn_le_Sm__n_le_m in H.\n        simpl in H.\n        apply Sn_le_m__n_le_m in H.\n        apply IHn1' in H.\n        inversion H.\n        unfold lt in H1 ; assumption.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros m H.\n    unfold lt.\n    apply n_le_m__Sn_le_Sm.\n    apply O_le_n.\n  Case \"n = S n'\".\n    intros m H.\n    unfold lt in H.\n    apply Sn_le_m__n_le_m in H.\n    apply n_le_m__Sn_le_Sm.\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\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 m.\n  generalize dependent n.\n  induction m as [| m'].\n  Case \"m = 0\".\n    intros n H. \n    destruct n as [| n'].\n    SCase \"n = 0\".\n      simpl. discriminate.      \n    SCase \"n = S n'\".\n      reflexivity.\n  Case \"n = S n'\".\n    intros n.\n    destruct n as [| n'].\n    SCase \"n = 0\".\n      simpl. trivial.\n    SCase \"n = S n'\".\n      simpl.\n      intros H.\n      apply IHm' in H.\n      assumption.\nQed.\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 m.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      intros H. inversion H.    \n    SCase \"m = S m'\".\n      simpl.\n      intros H. inversion H.\n  Case \"n = S n'\". \n    intros m.\n    destruct m as [| m'].\n    SCase \"m = 0\".\n      simpl.\n      intros H contra. clear H.\n      inversion contra.\n    SCase \"m = S m'\". \n      simpl.\n      intros H. apply IHn' in H.\n      intros H1.\n      apply Sn_le_Sm__n_le_m in H1.\n      contradiction.\nQed.\n\n(** **** Exercise: 3 stars (nostutter) *)\n(** Formulating inductive definitions of predicates is an important\n    skill you'll need in this course.  Try to solve this exercise\n    without any help at all (except from your study group partner, if\n    you have one).\n\n    We say that a list of numbers \"stutters\" if it repeats the same\n    number consecutively.  The predicate \"[nostutter mylist]\" means\n    that [mylist] does not stutter.  Formulate an inductive definition\n    for [nostutter].  (This is different from the [no_repeats]\n    predicate in the exercise above; the sequence [1,4,1] repeats but\n    does not stutter.) *)\n\nInductive nostutter:  list nat -> Prop :=\n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but you are free\n    to change the proof if the given one doesn't work for you.\n    Your definition might be different from mine and still correct,\n    in which case the examples might need a different proof.\n   \n    The suggested proofs for the examples (in comments) use a number\n    of tactics we haven't talked about, to try to make them robust\n    with respect to different possible ways of defining [nostutter].\n    You should be able to just uncomment and use them as-is, but if\n    you prefer you can also prove each example with more basic\n    tactics.  *)\n\nExample test_nostutter_1:      nostutter [3,1,4,1,5,6].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_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, advanced (pigeonhole principle) *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some \n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n\n(** First a pair of useful lemmas (we already proved these for lists\n    of naturals, but not for arbitrary lists). *)\n\nLemma app_length : forall {X:Type} (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2. \nProof. \n  (* FILL IN HERE *) Admitted.\n\nLemma appears_in_app_split : forall {X:Type} (x:X) (l:list X),\n  appears_in x l -> \n  exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now define a predicate [repeats] (analogous to [no_repeats] in the\n   exercise above), such that [repeats X l] asserts that [l] contains\n   at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* FILL IN HERE *)\n.\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n   represents a list of pigeonhole labels, and list [l1] represents 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(* $Date: 2013-02-10 18:08:54 -0500 (Sun, 10 Feb 2013) $ *)\n\n", "meta": {"author": "randywse", "repo": "541", "sha": "eae3a7e9f16ee8cbaa6f7a79682b318360d057bf", "save_path": "github-repos/coq/randywse-541", "path": "github-repos/coq/randywse-541/541-eae3a7e9f16ee8cbaa6f7a79682b318360d057bf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.769031739590502}}
{"text": "Inductive list (A: Type): Type  :=\n |nil: list A\n |cons: A -> list A -> list A\n.\n\n(*Inductive bool: Set :=\n| true\n| false\n.\n\nInductive nat: Set :=\n| O: nat\n| S: nat -> nat\n.\n\n\nDefinition n0 := O.\nDefinition n1 := (S O).\nDefinition n1' := (S n0).\nDefinition n2 := (S n1).\n\nFixpoint plus (n1 n2: nat): nat :=\nmatch n1 with\n  |O => n2\n  |S n1' => S (plus n1' n2)\nend.\n\n Fixpoint length (A: Type) (l: list A): nat :=\nmatch l with\n  |nil => O\n  |cons h t => S (length A  t)\nend.\n\nDefinition l0: list nat := nil nat.\nDefinition l1: list nat := cons nat (S O) (nil nat).\nDefinition l2:= cons nat (S (S O)) (cons nat (S O) (nil nat)).\nDefinition l2' := cons nat (S (S O)) l1.\n\nCompute length nat l2.\n*)\n\nArguments nil {A}.\nArguments cons {A} _ _.\n\nDefinition l0':= cons 1 nil.\n(* 0 - 1 are recognized in Coq libraries *)\nCheck l0'.\n\nDefinition l1':= cons false nil.\nCheck l1'.\n\nDefinition l2'' := @nil bool.\n(* Turns off implicit typing *)\n\n\nNotation \"h :: t\" := (cons h t)(at level 60, right associativity).\n\nDefinition l6 := 5::4::3::2::1::0::nil.\n\nFixpoint length {A: Type} (l: list A): nat :=\n  match l with\n    |nil => 0\n    |h :: t => S (length t)\nend.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nDefinition l8 := [5;4;3;2;1;0].\n\nFixpoint append {A: Type} (l1 l2: list A): list A:=\n  match l1 with\n  |nil => l2\n  |h :: t => h::(append t l2)\nend.\n\nFixpoint snoc {A: Type} (h: A) (t: list A): list A :=\n  match t with\n    |nil => [h]\n    |h'::t'' => append t [h] \nend.\n\n\n(*Fixpoint reverse {A: Type} {l: list A}: list A :=\n  match l with\n    |nil => nil\n    |h :: t => append snoc h (rev t) \n  end.\n\nCompute @rev nat [].\n*)\n\nFixpoint reverse {A: Type} (l: list A): list A :=\n  match l with\n    |nil => nil\n    |h :: t => append (reverse t) [h] \n  end.\n\n", "meta": {"author": "audreygchoi", "repo": "CS4240", "sha": "d1725c20af5428ada7b719b16bf83484d3b9d87e", "save_path": "github-repos/coq/audreygchoi-CS4240", "path": "github-repos/coq/audreygchoi-CS4240/CS4240-d1725c20af5428ada7b719b16bf83484d3b9d87e/9.18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8887587979121384, "lm_q1q2_score": 0.7689755186444999}}
{"text": "(** * 6.887 Formal Reasoning About Programs - Lab 2\n    * Transition Systems and Invariants, including modeling dynamic thread creation *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n\n(* Authors: Adam Chlipala (adamc@csail.mit.edu), Peng Wang (wangpeng@csail.mit.edu) *)\n\n(* Examples based on ideas introduced in TransitionSystem.v, from the book source.\n * Key definitions about invariants are imported from the Frap library. *)\n\n\n(** * A simple transition-system example: list search *)\n\n(* Consider a transition system equivalent to this program, which checks whether\n * a number appears in a list:\n   lsearch(needle, haystack) {\n     while (haystack != null) {\n       if (haystack.data == needle) {\n         return true;\n       } else {\n         haystack = haystack.next;\n       }\n     }\n     return false;\n   } *)\n\n(* Here's a suitable state type. *)\nInductive lsearch_state :=\n| AnswerIs (answer : bool)\n  (* The function has returned, with this answer. *)\n| Searching (remaining : list nat).\n  (* We are right before a loop iteration, with this value of \"haystack\". *)\n\n(* Initial states: searching the full input list. *)\nInductive lsearch_init (haystack : list nat) : lsearch_state -> Prop :=\n| LsearchInit : lsearch_init haystack (Searching haystack).\n\n(* Steps, each corresponding to one loop iteration. *)\nInductive lsearch_step (needle : nat) : lsearch_state -> lsearch_state -> Prop :=\n| LsearchNotFound :\n  lsearch_step needle (Searching nil) (AnswerIs false)\n| LsearchFound : forall ls,\n  lsearch_step needle (Searching (needle :: ls)) (AnswerIs true)\n| LsearchKeepLooking : forall x ls,\n  x <> needle\n  -> lsearch_step needle (Searching (x :: ls)) (Searching ls).\n\n(* Putting it together into a full system, parameterized on the two function\n * parameters. *)\nDefinition lsearch_sys (needle : nat) (haystack : list nat) := {|\n  Initial := lsearch_init haystack;\n  Step := lsearch_step needle\n|}.\n\n(* A basic invariant capturing the final correctness condition. *)\nDefinition lsearch_correct (needle : nat) (haystack : list nat) (st : lsearch_state) :=\n  match st with\n  | AnswerIs b => b = true <-> In needle haystack\n  | _ => True\n  end.\n(* Note the use of infix operator [<->] for \"if and only if.\"\n * The [propositional] tactic knows what to do with it!\n * Also see the definition of [In], a predicate we use for list membership. *)\nPrint In.\n\n(* CHALLENGE #1: Prove that the system meets its spec. *)\nTheorem lsearch_ok : forall needle haystack,\n  invariantFor (lsearch_sys needle haystack) (lsearch_correct needle haystack).\nProof.\nAdmitted.\n\n(* Hint: You will almost certainly want to define and use a stronger\n * invariant! *)\n\n\n(** * Transition systems for dynamic thread creation *)\n\n(* Let's define a general way of building transition systems that allow dynamic\n * thread creation.  We will work with step relations returning values in this\n * type, capturing whether to spawn a new thread. *)\nInductive thread_step_outcome shared private :=\n| Basic (sh : shared) (pr : private)\n  (* Meaning: shared state is mutated to [sh] and private state to [pr]. *)\n| Spawn (sh : shared) (state_of_new_thread my_own_next_state : private).\n  (* Meaning: shared state to [sh] and private state to [my_own_next_state].\n   * Additionally, spawn a new thread whose private state is\n   * [state_of_new_thread]. *)\n\n(* Now system states can include arbitrarily many threads. *)\nRecord threads_state shared private := {\n  Shared : shared;\n  (* State shared across all threads *)\n  Private : list private\n  (* Private states of all threads that have been spawned *)\n}.\n\n(* Initial states of multithreaded programs, based on given initial values of\n * shared and private state.  We start with exactly one thread, which has that\n * private state. *)\nInductive threads_init shared private (sh0 : shared) (pr0 : private)\n  : threads_state shared private -> Prop :=\n| ThreadsInit : threads_init sh0 pr0 {| Shared := sh0; Private := [pr0] |}.\n\n(* CHALLENGE #2: Fill in this definition of a step relation.\n * To get more of a sense for the definitions, it may be helpful to look first\n * at the example system just below.\n * Another hint: you probably want to write rules that pick threads out of lists\n * and then build new modified lists.  A useful pattern for that picking is as\n * follows:\n *   [forall ts1 t ts2, threads_step step (... (ts1 ++ t :: ts2) ...)\n *                                        (... (ts1 ++ t' :: ts2) ...)]\n * That is, we quantify over all threads before and after a given thread [t],\n * in the list of active threads.  Recall that [++] is list concatenation,\n * while [::] is the operator to add a new element to the front of a list.\n *)\nInductive threads_step shared private\n          (step : shared -> private -> thread_step_outcome shared private -> Prop)\n  : threads_state shared private -> threads_state shared private -> Prop :=\n| ThisIsWrong : forall sh pr sh' pr',\n    threads_step step {| Shared := sh; Private := pr |}\n                      {| Shared := sh'; Private := pr' |}.\n\n(* Package it all together into a system. *)\nDefinition threads_sys shared private (sh0 : shared) (pr0 : private)\n           (step : shared -> private -> thread_step_outcome shared private -> Prop)\n  : trsys (threads_state shared private) := {|\n  Initial := threads_init sh0 pr0;\n  Step := threads_step step\n|}.\n\n(* Now our example of a thread-spawning program.  It is for checking whether a\n * number occurs in a binary tree, based on this type definition. *)\nInductive tree :=\n| Leaf (n : nat)\n| Branch (tr1 tr2 : tree).\n\n(* Here is what it means for a number to be in the tree. *)\nFixpoint InTree (n : nat) (tr : tree) : Prop :=\n  match tr with\n  | Leaf n' => n = n'\n  | Branch tr1 tr2 => InTree n tr1 \\/ InTree n tr2\n  end.\n\n(* The pseudocode of our algorithm, where we write \"spawn(c)\" for running\n * command \"c\" in a new thread:\n\n   bool found = false;\n\n   treesearch(needle, haystack) {\n     switch (haystack) {\n       case Leaf n:\n         if (n == needle) {\n           found = true;\n         }\n         return;\n       case Branch tr1 tr2:\n         spawn(treesearch(needle, tr1));\n         treesearch(needle, tr2);\n     }\n   }\n\n * If global variable \"found\" is ever set to \"true\", then we know the number\n * has been found in the tree.\n*)\n\n(* We only need to model the following two private program states. *)\nInductive treesearch_thread :=\n| SearchTree (tr : tree)\n  (* Just beginning a call to the function, searching the given tree *)\n| Done.\n  (* Finished a call to the function *)\n\n(* Step relation, crucially using the [Spawn] outcome in the last rule *)\nInductive treesearch_step (needle : nat) : bool\n  -> treesearch_thread\n  -> thread_step_outcome bool treesearch_thread\n  -> Prop :=\n| TsLeafMatch : forall b,\n  treesearch_step needle b (SearchTree (Leaf needle)) (Basic true Done)\n| TsLeafNoMatch : forall b n,\n  n <> needle\n  -> treesearch_step needle b (SearchTree (Leaf n)) (Basic b Done)\n| TsBranch : forall b tr1 tr2,\n  treesearch_step needle b (SearchTree (Branch tr1 tr2))\n                  (Spawn b (SearchTree tr1) (SearchTree tr2)).\n\nDefinition treesearch_sys (needle : nat) (haystack : tree) :=\n  threads_sys false (SearchTree haystack) (treesearch_step needle).\n\n(* Next, we use a helper function to define an overall correctness condition. *)\nFixpoint allDone (ls : list treesearch_thread) : Prop :=\n  match ls with\n  | nil => True\n  | th :: ls' => th = Done /\\ allDone ls'\n  end.\n\nDefinition treesearch_correct (needle : nat) (haystack : tree)\n           (st : threads_state bool treesearch_thread) :=\n  allDone st.(Private)\n  -> (InTree needle haystack <-> st.(Shared) = true).\n\n(* CHALLENGE #3: Prove that the system meets its spec. *)\nTheorem treesearch_ok : forall needle haystack,\n  invariantFor (treesearch_sys needle haystack) (treesearch_correct needle haystack).\nProof.\nAdmitted.\n\n(* Hint: you probably want to define another helper function or two, similar to\n * [allDone], to use in your strengthened invariant. *)\n\n(* Some suggested tactics:\n * [left] or [right]: prove a disjunction (using [\\/]) by choosing to prove the\n *   left or right disjunct, respectively.\n * [first_order]: simplify with rules of first-order logic.\n *   WARNING: Sometimes this one goes off the rails and runs effectively\n *   forever!\n * [rewrite H1 in H2]: use [H1] to make a rewrite as usual, but within\n *   hypothesis [H2], rather than in the conclusion formula.\n * [apply H1 in H2]: forward-reasoning version of [apply], for when [H1] proves\n *   an implication from [H2].  The effect is to replace [H2] with the\n *   conclusion of the implication.\n * [unfold X in *]: like [unfold X] but applies to the whole goal, not just the\n *   conclusion.\n * [exfalso]: switch to proving [False], from any conclusion.  That is, we\n *   switch into a proof by contradiction. *)\n", "meta": {"author": "wangpengmit", "repo": "6887psets", "sha": "36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d", "save_path": "github-repos/coq/wangpengmit-6887psets", "path": "github-repos/coq/wangpengmit-6887psets/6887psets-36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d/Lab2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7689755045494063}}
{"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 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 substraction: 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(*   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, 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 abreviate 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 a 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\nImplicit Arguments eqnP [x y].\nPrenex Implicits eqnP.\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 substraction, 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] [|n]; try exact (IHm n). 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.\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.\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] [|n] //; exact: IHm n. 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.\n\nLemma eqn_leq m n : (m == n) = (m <= n <= m).\nProof. elim: m n => [|m IHm] [|n] //; exact: IHm n. 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. elim: m n => [|m IHm] [|n] //; exact: IHm n. 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] //; exact: IHn m p. Qed.\n\nLemma leq_ltn_trans n m p : m <= n -> n < p -> m < p.\nProof. move=> Hmn; exact: leq_trans. Qed.\n\nLemma ltnW m n : m < n -> m <= n.\nProof. exact: leq_trans. Qed.\nHint Resolve ltnW.\n\nLemma leqW m n : m <= n -> m <= n.+1.\nProof. by move=> le_mn; exact: ltnW. Qed.\n\nLemma ltn_trans n m p : m < n -> n < p -> m < p.\nProof. by move=> lt_mn /ltnW; exact: leq_trans. Qed.\n\nLemma leq_total m n : (m <= n) || (m >= n).\nProof. by rewrite -implyNb -ltnNge; apply/implyP; exact: 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.\nImplicit Arguments 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; exact: IHn.\nQed.\n\nLemma ltP m n : reflect (m < n)%coq_nat (m < n).\nProof. exact leP. Qed.\nImplicit Arguments 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\nCoInductive 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\nCoInductive 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\nCoInductive 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\nCoInductive compare_nat m n : 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 m n : compare_nat 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(* 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; exact: leq_add2l. Qed.\n\nLemma leq_add2r p m n : (m + p <= n + p) = (m <= n).\nProof. by rewrite -!(addnC p); exact: 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=> -> //; exact: leq_addr. Qed.\n\nLemma ltn_addl m n p : m < n -> m < p + n.\nProof. by move/leq_trans=> -> //; exact: 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] //; exact: 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; exact: 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 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 <-; exact: (@leq_sub2r p.+1). Qed.\n\nLemma ltn_sub2l p m n : m < p -> m < n -> p - n < p - m.\nProof. by move/subnSK <-; exact: 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 => // [_|->] //; 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; 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  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 => // -> /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 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 <-; exact: 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.\nImplicit Arguments 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.\nImplicit Arguments 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.\nImplicit Arguments 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.\nImplicit Arguments 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.\nImplicit Arguments 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.\nImplicit Arguments 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; exact: 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 lt_im; rewrite (odd_sub (ltnW lt_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. elim: m n => [|m IHm] [|n] //; exact: IHm n. 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=> //; exact: 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.\nmove=> le1 le2; case: posnP => [n12_0 | ].\n  rewrite n12_0; move/eqP: n12_0 {le1 le2}le1.1 le2.1; rewrite muln_eq0.\n  by case/orP=> /eqP->; case: m1 m2 => [|m1] [|m2] // _ _; \n    rewrite ?muln0; exact/leqif_refl.\nrewrite muln_gt0 => /andP[n1_gt0 n2_gt0].\nhave [m2_0 | m2_gt0] := posnP m2.\n  apply/leqifP; rewrite -le2 andbC eq_sym eqn_leq leqNgt m2_0 muln0.\n  by rewrite muln_gt0 n1_gt0 n2_gt0.\nhave mono_n1 := leq_pmul2l n1_gt0; have mono_m2 := leq_pmul2r m2_gt0.\nrewrite -(mono_leqif mono_m2) in le1; rewrite -(mono_leqif mono_n1) in le2.\nexact: leqif_trans le1 le2.\nQed.\n\nLemma nat_Cauchy m n : 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n).\nProof.\nwlog 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\nNotation Local oddn := odd.\nFixpoint odd n := 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 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 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 bin_nat_eqMixin := EqMixin eq_binP.\nCanonical 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 :=\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 : Psucc 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. case: b1 b2 => [|p] [|q] //=; exact: 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.\ncase: b => [|p] /=; first exact: expn0.\nby elim: p => //= 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. 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/v8.4/theories/ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7689738812451687}}
{"text": "Require 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 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\nFixpoint mem (mem_arg0 : natural) (mem_arg1 : lst) : bool\n           := match mem_arg0, mem_arg1 with\n              | x, Nil => false\n              | x, Cons y z => orb (eqb x y) (mem x z)\n              end.\n\nDefinition lst_mem := mem.\n\nFixpoint lst_intersection (lst_intersection_arg0 : lst) (lst_intersection_arg1 : lst) : lst\n           := match lst_intersection_arg0, lst_intersection_arg1 with\n              | Nil, x => Nil\n              | Cons n x, y => if lst_mem n y then Cons n (lst_intersection x y) else lst_intersection x 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   - intros. destruct y.\n   + discriminate.\n   + reflexivity.\nQed.\n\n\nTheorem theorem0 : forall (x : natural) (y : lst) (z : lst), and (eq (lst_mem x y) true) (eq (lst_mem x z) true) -> eq (lst_mem x (lst_intersection y z)) true.\nProof.\n   intros.\n   destruct H.\n   induction y.   \n   - simpl in H. apply Bool.orb_prop in H. destruct H.\n     + simpl. destruct (lst_mem n z) eqn:?.\n       * simpl. rewrite H. reflexivity.\n       * rewrite (Nat_beq_eq x n H) in H0. rewrite H0 in Heqb. discriminate.\n     + apply IHy in H. simpl. destruct (lst_mem n z) eqn:?.\n       * simpl. rewrite H. apply Bool.orb_true_r.\n       * assumption.\n   - discriminate.   \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/goal44.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7689268798109462}}
{"text": "(* Simple inductive types: lists *)\nInductive list :=\n  nil\n| cons : nat -> list -> list.\n\nCheck (cons 3 (cons 2 nil)).\n\n(* mutual inductive types: even/odd lists *)\n\nInductive even_list :=\n  enil\n| econs : nat -> odd_list -> even_list\nwith odd_list :=\n  ocons : nat -> even_list -> odd_list.\n\nCheck (ocons 2 enil).\nCheck (econs 3 (ocons 2 enil)).\n\n(* indexed inductive types: vectors (fixed-size lists) *)\n\nInductive vector : nat -> Type :=\n  vnil : vector 0\n| vcons : forall n, nat -> vector n -> vector (1 + n).\n\n(* inductive-inductive type : contextes and types *)\nInductive context : Type :=\n  nilc : context\n| extc : forall (Γ : context), type Γ -> context (* Γ, A *)\nwith type : context -> Type :=\n  N : forall Γ, type Γ (* Γ ⊢ ℕ *) .\n    (* with term : forall (Γ : context), type Γ -> Type := .. *)\n\n(* Transport hell example:\n   rev_append vector1 vector2 = rev vector1 ++ vector2 *)\nFixpoint rev_append (n : nat) (v1 : vector n) (m : nat) (v2 : vector m) { struct v1 } : vector (n + m).\n  (* refine\n  (\n  match v1 with\n    vnil => v2\n  | vcons n' hd tl => rev_append n' tl (1 + m) (vcons _ hd v2) \n    end). *)\n  refine\n  (\n  match v1 with\n    vnil => v2\n  | vcons n' hd tl => _ (* rev_append n' tl (1 + m) (vcons _ hd v2) *)\n    end).\n  (* \n  refine ( rev_append n' tl (1 + m) (vcons _ hd v2) ).\n*)\n  Check ( rev_append n' tl (1 + m) (vcons _ hd v2) ).\n  Require Import Nat.\n  Search Nat.add.\n  Check (eq_rect_r vector ( rev_append n' tl (1 + m) (vcons _ hd v2) )\n      (plus_n_Sm n' m)  ).\n  exact (eq_rect_r vector ( rev_append n' tl (1 + m) (vcons _ hd v2) )\n      (plus_n_Sm n' m)  ).\n  Abort.\n\nFixpoint rev_append (n : nat) (v1 : vector n) (m : nat) (v2 : vector m) { struct v1 } : vector (n + m) :=\n  match v1 with\n    vnil => v2\n  | vcons n' hd tl =>\n    eq_rect_r vector ( rev_append n' tl (1 + m) (vcons _ hd v2) )\n      (plus_n_Sm n' m)  \n    end. \n\n(* other example : lib.agda in omegatt *)\n", "meta": {"author": "amblafont", "repo": "slides", "sha": "93b877426c7e87d8f1f6a9a3438042a1542627c4", "save_path": "github-repos/coq/amblafont-slides", "path": "github-repos/coq/amblafont-slides/slides-93b877426c7e87d8f1f6a9a3438042a1542627c4/inductifinductif/examples_cheat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7687758523173713}}
{"text": "Require Import Coq.ZArith.ZArith Coq.omega.Omega 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; omega);\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; omega.\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 omega.\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 omega end.\n    repeat match goal with |- context[?x * -1] => replace (x * -1) with (-x) by omega 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 omega;\n      try rewrite (Z.sgn_neg b) by omega;\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 omega\n                   | match goal with\n                     | [ |- context[-1 * ?x] ]\n                       => replace (-1 * x) with (-x) by omega\n                     | [ |- context[?x * -1] ]\n                       => replace (x * -1) with (-x) by omega\n                     | [ |- context[-?x - ?y] ]\n                       => replace (-x - y) with (-(x + y)) by omega\n                     | [ |- context[-?x + - ?y] ]\n                       => replace (-x + - y) with (-(x + y)) by omega\n                     | [ |- context[(?a + ?b + ?c) / ?b] ]\n                       => replace (a + b + c) with (((a + c) + b * 1)) by lia; rewrite Z.div_add' by omega\n                     | [ |- context[(?a + ?b - ?c) / ?b] ]\n                       => replace (a + b - c) with (((a - c) + b * 1)) by lia; rewrite Z.div_add' by omega\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": "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/Quot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7687722432356534}}
{"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\nRequire Import ZArith.\nRequire Import Reals.\n\n\nLemma Zabs_mult : forall z1 z2 : Z, Z.abs (z1 * z2) = (Z.abs z1 * Z.abs z2)%Z.\n\nProof.\nintros.\ncase z1.\nsimpl in |- *.\nauto.\ncase z2.\nsimpl in |- *; auto.\nsimpl in |- *; auto.\nsimpl in |- *; auto.\nsimpl in |- *.\nintros.\ncase z2.\nauto with real. \nauto with real. \nauto with real.\nQed.\n\nHint Resolve Zabs_mult: real.\n\n\nLemma Zabs_O : forall z : Z, Z.abs z = 0%Z -> z = 0%Z.\n\nProof.\nintro z.\ncase z; simpl in |- *; auto.\nintros.\ninversion H.\nQed.\n\n\nHint Resolve Zabs_O: real.\n\n\nLemma Zabs_lt_0 : forall z : Z, z <> 0%Z -> (Z.abs z > 0)%Z.\n\nProof.\nintro.\nunfold Z.abs in |- *.\ncase z.\nintuition.\nauto with zarith.\nauto with zarith.\nQed.\n\nHint Resolve Zabs_lt_0: zarith.\n\n\nLemma Zabs_not_eq : forall z : Z, (Z.abs z > 0)%Z -> z <> 0%Z.\nProof.\nintro.\nunfold Z.abs in |- *.\ncase z; intro.\ninversion H.\nauto with zarith.\nintro.\nintuition.\ninversion H0.\nQed.\n\nHint Resolve Zabs_not_eq: zarith.\n\n\nLemma Zabs_01 :\n forall x a : Z, (0 <= a)%Z -> (x <= a)%Z -> (a < Z.abs x)%Z -> (x < 0)%Z.\nProof.\nintros x a H.\nunfold Z.abs in |- *.\ncase x; intros.\nomega.\nomega.\nred in |- *.\nauto with zarith.\nQed.\n\nHint Resolve Zabs_01: zarith.", "meta": {"author": "coq-community", "repo": "exact-real-arithmetic", "sha": "43bf40b6bfa71a1d1a2b17219c46c4081705c7fa", "save_path": "github-repos/coq/coq-community-exact-real-arithmetic", "path": "github-repos/coq/coq-community-exact-real-arithmetic/exact-real-arithmetic-43bf40b6bfa71a1d1a2b17219c46c4081705c7fa/Zabs_complements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8633916170039421, "lm_q1q2_score": 0.7686725715007721}}
{"text": "(* week_40b_fib.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\nLemma plus_1_l :\n  forall n : nat,\n    1 + n = S n.\nProof.\n  intro n.\n  rewrite -> plus_Sn_m.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\n\nNotation \"A =n= B\" := (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 unit_test_for_the_fibonacci_function (candidate: nat -> nat) :=\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  (candidate 9 =n= 34)\n  .\n\n(* A specification: *)\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(* 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\n(*\nCompute map fib_ds (0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: nil).\n     = 0 :: 1 :: 1 :: 2 :: 3 :: 5 :: 8 :: 13 :: nil\n     : list nat\n*)\n\n(* Associated unfold lemmas: *)\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 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\n(* Main definition: *)\n\nDefinition fib_v0 (n : nat) : nat :=\n  fib_ds n.\n\nCompute unit_test_for_the_fibonacci_function fib_v0.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_ds_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_ds.\nProof.\n  unfold specification_of_fibonacci.\n  split.\n\n    apply unfold_fib_ds_base_case_0.\n\n  split.\n\n    apply unfold_fib_ds_base_case_1.\n\n  intro n''.\n  apply unfold_fib_ds_induction_case.\nQed.\n\nTheorem fib_v0_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v0.\nProof.\n  unfold fib_v0.\n  exact fib_ds_satisfies_the_specification_of_fibonacci.\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_base_case_0 :\n  forall (ans : Type) (k : nat -> ans),\n    fib_cps ans 0 k = k 0.\nProof.\n  unfold_tactic fib_cps.\nQed.\n\nLemma unfold_fib_cps_base_case_1 :\n  forall (ans : Type) (k : nat -> ans),\n    fib_cps ans 1 k = k 1.\nProof.\n  unfold_tactic fib_cps.\nQed.\n\nLemma unfold_fib_cps_induction_case :\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'' IHSn''] using nat_ind2.\n\n  intros ans k.\n  rewrite -> unfold_fib_cps_base_case_0.\n  rewrite -> unfold_fib_cps_base_case_0.\n  reflexivity.\n\n  intros ans k.\n  rewrite -> unfold_fib_cps_base_case_1.\n  rewrite -> unfold_fib_cps_base_case_1.\n  reflexivity.\n\n  intros ans k.\n  rewrite -> unfold_fib_cps_induction_case.\n  rewrite -> unfold_fib_cps_induction_case.\n  rewrite -> IHSn''.\n  rewrite -> IHn''.\n  rewrite -> (IHSn'' nat (fun v1 => fib_cps nat n'' (fun v2 => v1 + v2))).\n  rewrite -> (IHn'' nat (fun v2 => fib_cps nat (S n'') (fun v => v) + v2)).\n  reflexivity.\nQed.\n      \n(* Main definition: *)\n\nDefinition fib_v1 (n : nat) : nat :=\n  fib_cps nat n (fun v => v).\n\nCompute unit_test_for_the_fibonacci_function fib_v1.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v1_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v1.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v1.\n  split.\n\n    rewrite -> unfold_fib_cps_base_case_0.\n    reflexivity.\n\n  split.\n\n    rewrite -> unfold_fib_cps_base_case_1.\n    reflexivity.\n\n  intro n''.\n  rewrite -> unfold_fib_cps_induction_case.\n  rewrite -> about_fib_cps.\n  rewrite -> about_fib_cps.\n  reflexivity.\nQed.\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_base_case :\n  forall a1 a0 : nat,\n    fib_acc 0 a1 a0 = a0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\nLemma unfold_fib_acc_induction_case :\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_v2 (n : nat) : nat :=\n  fib_acc n 1 0.\n\nCompute unit_test_for_the_fibonacci_function fib_v2.\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.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [_ [_ H_fib_ic]].\n  intro j.\n  induction j as [ | j' IHj'].\n\n  intro i.\n  rewrite -> unfold_fib_acc_base_case.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  intro i.\n  rewrite -> unfold_fib_acc_induction_case.\n  rewrite <- (H_fib_ic i).\n  rewrite -> (IHj' (S i)).\n  rewrite -> plus_Snm_nSm.\n  reflexivity.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v2_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v2.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v2.\n  split.\n\n    apply unfold_fib_acc_base_case.\n\n  split.\n\n    rewrite -> unfold_fib_acc_induction_case.\n    apply unfold_fib_acc_base_case.\n\n  intro n''.\n\n  rewrite <- unfold_fib_ds_base_case_1.\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci (S (S n'')) 0).\n  rewrite -> plus_0_r.\n\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci (S n'') 0).\n  rewrite -> plus_0_r.\n\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci n'').  \n  rewrite -> plus_0_r.\n\n  apply unfold_fib_ds_induction_case.\nQed.\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_base_case :\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_induction_case :\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_v3 (n : nat) : nat :=\n  fib_acc_cps nat n 1 0 (fun a => a).\n\nCompute unit_test_for_the_fibonacci_function fib_v3.\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.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [_ [_ H_fib_ic]].\n  intros ans j.\n  induction j as [ | j' IHj'].\n\n  intros i k.\n  rewrite -> unfold_fib_acc_cps_base_case.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  intros i k.\n  rewrite -> unfold_fib_acc_cps_induction_case.\n  rewrite <- (H_fib_ic i).\n  rewrite -> (IHj' (S i) k).\n  rewrite -> plus_Snm_nSm.\n  reflexivity.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v3_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v3.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v3.\n  split.\n\n    apply unfold_fib_acc_cps_base_case.\n\n  split.\n\n    rewrite -> unfold_fib_acc_cps_induction_case.\n    rewrite -> plus_0_r.\n    rewrite -> unfold_fib_acc_cps_base_case.\n    reflexivity.\n\n  intro n''.\n\n  rewrite <- unfold_fib_ds_base_case_1.\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S (S n'')) 0).\n  rewrite -> plus_0_r.\n\n  rewrite <- unfold_fib_ds_base_case_1.\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S n'') 0).\n  rewrite -> plus_0_r.\n\n  rewrite <- unfold_fib_ds_base_case_1.\n  rewrite <- unfold_fib_ds_base_case_0 at 2.\n  rewrite -> (about_fib_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat n'' 0).  \n  rewrite -> plus_0_r.\n\n  apply unfold_fib_ds_induction_case.\nQed.\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_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 (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_v4 (n : nat) : nat :=\n  let (a1, a0) := fib_co_acc n\n  in a0.\n\nCompute unit_test_for_the_fibonacci_function fib_v4.\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.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [H_fib_bc_0 [H_fib_bc_1 H_fib_ic]].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  rewrite -> unfold_fib_co_acc_base_case.\n  rewrite -> H_fib_bc_1.\n  rewrite -> H_fib_bc_0.\n  reflexivity.\n\n  rewrite -> unfold_fib_co_acc_induction_case.\n  rewrite -> IHn'.\n  rewrite <- (H_fib_ic n').\n  reflexivity.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v4_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v4.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v4.\n  split.\n\n    rewrite -> unfold_fib_co_acc_base_case.\n    reflexivity.\n\n  split.\n\n    rewrite -> unfold_fib_co_acc_induction_case.\n    rewrite -> unfold_fib_co_acc_base_case.\n    reflexivity.\n\n  intro n''.\n  rewrite -> (about_fib_co_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci (S n'')).\n  rewrite -> (about_fib_co_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci n'').\n  case n'' as [ | n'''].\n\n  rewrite <- unfold_fib_ds_base_case_0 at 3.\n  apply (unfold_fib_ds_induction_case 0).\n\n  rewrite -> (about_fib_co_acc fib_ds fib_ds_satisfies_the_specification_of_fibonacci (S (S (S n''')))).\n  apply (unfold_fib_ds_induction_case (S n''')).\nQed.\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_base_case :\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_induction_case :\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_v5 (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 unit_test_for_the_fibonacci_function fib_v5.\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.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [H_fib_bc_0 [H_fib_bc_1 H_fib_ic]].\n  intros ans n.\n  induction n as [ | n' IHn'].\n\n  intro k.\n  rewrite -> unfold_fib_co_acc_cps_base_case.\n  rewrite -> H_fib_bc_1.\n  rewrite -> H_fib_bc_0.\n  reflexivity.\n\n  intro k.\n  rewrite -> unfold_fib_co_acc_cps_induction_case.\n  rewrite -> IHn'.\n  rewrite <- (H_fib_ic n').\n  reflexivity.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v5_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v5.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v5.\n  split.\n\n    rewrite -> unfold_fib_co_acc_cps_base_case.\n    reflexivity.\n\n  split.\n\n    rewrite -> unfold_fib_co_acc_cps_induction_case.\n    rewrite -> unfold_fib_co_acc_cps_base_case.\n    reflexivity.\n\n  intro n''.\n  rewrite -> (about_fib_co_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S n'') _).\n  rewrite -> (about_fib_co_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat n'' _).\n  rewrite <- (unfold_fib_ds_induction_case n'').\n  exact (about_fib_co_acc_cps fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S (S n'')) (fun p : nat * nat => let (a1, a0) := p in a0)).\nQed.\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'_base_case :\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'_induction_case :\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_v6 (n : nat) : nat :=\n  fib_co_acc_cps' nat\n                  n\n                  (fun a1 a0 =>\n                     a0).\n\nCompute unit_test_for_the_fibonacci_function fib_v6.\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.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [H_fib_bc_0 [H_fib_bc_1 H_fib_ic]].\n  intros ans n.\n  induction n as [ | n' IHn'].\n\n  intro k.\n  rewrite -> unfold_fib_co_acc_cps'_base_case.\n  rewrite -> H_fib_bc_1.\n  rewrite -> H_fib_bc_0.\n  reflexivity.\n\n  intro k.\n  rewrite -> unfold_fib_co_acc_cps'_induction_case.\n  rewrite -> IHn'.\n  rewrite <- (H_fib_ic n').\n  reflexivity.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v6_satisfies_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v6.\nProof.\n  unfold specification_of_fibonacci.\n  unfold fib_v6.\n  split.\n\n    rewrite -> unfold_fib_co_acc_cps'_base_case.\n    reflexivity.\n\n  split.\n\n    rewrite -> unfold_fib_co_acc_cps'_induction_case.\n    rewrite -> unfold_fib_co_acc_cps'_base_case.\n    reflexivity.\n\n  intro n''.\n  rewrite -> (about_fib_co_acc_cps' fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S n'') _).\n  rewrite -> (about_fib_co_acc_cps' fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat n'' _).\n  rewrite <- (unfold_fib_ds_induction_case n'').\n  exact (about_fib_co_acc_cps' fib_ds fib_ds_satisfies_the_specification_of_fibonacci nat (S (S n'')) (fun a1 a0 : nat => a0)).\nQed.\n\n(* ********** *)\n\n(* end of week_40c_fib.v *)", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w40/week_40b_fib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8902942166619118, "lm_q1q2_score": 0.7686725695918976}}
{"text": "(** * The Z property implies Confluence\n\n  An ARS, say $(A,R)$, is defined as a pair composed of a set $A$ and\n  binary relation over this set $R:A\\times A$. Let $a,b\\in A$. We\n  write $a\\to_R b$ (or $R\\ a\\ b$ in Coq) to denote that $(a,b)\\in R$,\n  and we say that $a$ $R$-reduces to $b$ in one step. The reflexive\n  transitive closure of a relation [R], written as $\\tto_R$, is\n  defined by the following inference rules: %\\begin{mathpar}\n  \\inferrule*[Right={$(refl)$}]{~}{a \\tto_R a} \\and\n  \\inferrule*[Right={$(rtrans)$}]{a\\to_R b \\and b \\tto_R c}{a \\tto_R\n  c} \\end{mathpar}% %\\noindent% where $a,b$ and $c$ are universally\n  quantified variables as one makes explicit in the corresponding Coq\n  definition: *)\n(* begin hide *)\nDefinition Rel (A:Type) := A -> A -> Prop.\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\n(**\nLemma transit' {A:Type} (R: Rel A):\n  forall t u v, trans R t u -> R u v -> trans R t v.\nProof.\n  intros t u v H1 H2. induction H1.\n  - apply transit with b. \n    + assumption.\n    + apply singl.\n      assumption.\n  - apply IHtrans in H2.\n    apply transit with b; assumption.\nQed.\n\nLemma trans_composition' {A} (R: Rel A):\n  forall t v, trans R t v -> (R t v \\/ exists u, trans R t u /\\ R u v).\nProof.\n intros t v H.\n induction H.\n - left; assumption.\n - right.\n   destruct IHtrans.\n   + exists b.\n     split.\n     * apply singl.\n       assumption.\n     * assumption.\n   + destruct H1.\n     exists x.\n     split.\n     * apply transit with b.\n       ** assumption.\n       ** apply H1.\n     * apply H1.\nQed. *)\n(* end hide *)\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\n(** The rules named ([refl]) and ([rtrans]) are called _constructors_\nin the Coq definition. The first constructor, namely [refl], states\nthe reflexivity axiom for $\\tto_R$, while [rtrans] extends the\nreflexive transitive closure of [R], if one has at least a one-step\nreduction. As a first example, let's have a look at the proof of\ntransitivity of $\\tto_R$:\n\n%\\begin{lemma} Let $\\to_R$ be a binary relation over a set $A$. For\nall $t, u, v \\in A$, if $t \\tto_R u$ and $u \\tto_R v$ then $t \\tto_R\nv$.  \\end{lemma}%\n\n Despite its simplicity, the proof of this lemma will help us explain\nthe way in which we will relate English annotations with the proof\nsteps. Coq proofs are written between the reserved words [Proof] and\n[Qed] (lines 1 and 9), and each proof command finishes with a\ndot. Proofs can be structured with bullets (- in the first level, + in\nthe second level, * in the third level, ** in the fourth level, and so\non). The corresponding informal proof proceed as follows: The\ncorresponding lemma in Coq, named [refltrans_composition], is stated\nas follows: *)\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. (** %\\comm{Let $t,u,v$ be elements of $A$.}% *)\n  \n  intros H1 H2. (** %\\comm{Let $H1$ (respectively, $H2$) be the hipothesis that $t \\tto_R   u$ (respectively, $u \\tto_R v$).}% *)\n  \n  induction H1. (** %\\comm{The proof procceds by induction on the\n    hipothesis $H1$. Therefore there is one case for each constructor\n    of the reflexive transitive closure of $R$. The structure of the\n    proof context determines the shape of the induction hypothesis,\n    and this fact will be essential to understand the inductive proof\n    of the next theorem.}% *)\n  \n  - assumption. (** %\\comm{For the base case, which corresponds to the rule $refl$, $t$ and $u$ are the same element and hence the goal coincides with the hipothesis $H2$.}% *)\n    \n  - apply rtrans with b. (** %\\comm{For the inductive case, $t \\tto_R\n    u$ is build from $t \\to_R b$ and $b \\tto_R u$, for some $b$, and\n    as induction hipothesis one has that $b \\tto_R v$. Therefore, one\n    can prove that $t \\tto_R v$ by applying the rule ($rtrans$) with\n    $b$ as the intermediary term:\n\n\\begin{mathpar} \\inferrule*[Right={$(rtrans)$}]{t\\to_R b \\and b \\tto_R\n  v}{t \\tto_R v} \\end{mathpar}\n\n We have then two subproofs:}% *)\n    \n    + assumption. (** %\\comm{The proof that $t\\to_R b$ is one of the hipothesis, and we are done.}% *)\n      \n    + apply IHrefltrans; assumption.  (** %\\comm{The proof that\n$b\\tto_R v$ is obtained from the induction hipothesis, and this proof\ncan be better visualized by the corresponding deduction tree:\n\n\\begin{mathpar}\n\\inferrule*[Right={$MP$}]{\n\\inferrule*[Right={$IH$}]{~}{b\\tto_R u \\to b\\tto_R v} \\and\n\\inferrule*[Right={H2}]{~}{b\\tto_R u}}{b\\tto_R v}\n\\end{mathpar} }% *)\n      \nQed. \n(* begin hide *)\n(**\n<<\n1. Proof.  \n2.  intros t u v.  \n3.  intros H1 H2.  \n4.  induction H1.\n5.  - assumption.  \n6.  - apply rtrans with b.  \n7.  + assumption.  \n8.  + apply IHrefltrans; assumption.  \n9. Qed. \n>>\n\nThis work is not a Coq tutorial, but our idea is that it should\nalso be readable for those unfamiliar with the Coq proof Assistant. In\naddition, this paper is built directly from a Coq proof script, which\nmeans that we are forced to present the ideas and the results in a\nmore organized and systematic way that is not necessarily the more\npedagogical one. *)\n\n(** %{\\bf Proof}.%\n\n    Let $t, u, v \\in A$, i.e. they are elements of type [A], or\n    elements of the set [A] (line 2). Call [H1] (resp. [H2]) the\n    hypothesis that $t \\tto_R u$ (resp. $u\\tto_R v$) (line 3). The\n    proof proceeds by induction on the hypothesis [H1] (line 4),\n    i.e. by induction on $t \\tto_R u$. The structure of the proof\n    context determines the shape of the induction hypothesis, and this\n    fact will be essential to understand the inductive proof of the\n    next theorem. As shown in Figure %\\ref{fig:trans}%, [H1] and [H2]\n    are the only hypothesis (the other lines are just declaration of\n    variables), therefore the induction hypothesis subsumes [H2].\n\n      %\\begin{figure}[h] \\centering\n        \\includegraphics[scale=0.6]{fig1.png} \\caption{Transitivity of\n        $\\tto_R$}\\label{fig:trans} \\end{figure}%\n\n    The first case is when $t \\tto_R u$ is generated by the\n    constructor [refl], which is an axiom and hence we are done (line\n    5).  The second case, i.e. the recursive case is more interesting\n    because $t \\tto_R u$ is now generated by [rtrans] (line 6). This\n    means that there exists an element, say $b$, such that $t \\to_R b$\n    and $b \\tto_R u$. Therefore, in order to prove that $t \\tto_R u$,\n    we can apply the rule [rtrans] taking [b] as the intermediary\n    term. The proof of the recursive case can be better visualized by\n    the corresponding deduction tree: %{\\scriptsize \\begin{mathpar}\n    \\inferrule*[Right=MP]{\\inferrule*[Right=MP]{\\inferrule*[Right={\n    $rtrans$}]{~}{\\inferrule*[Right={$(\\forall_e)$}]{\\forall x\\ y\\ z,\n    x\\to_R y \\to y\\tto_R z \\to x\\tto_R z}{t\\to_R b \\to b\\tto_R u \\to\n    t\\tto_R u}} \\and \\inferrule*[Right={H}]{~}{t\\to_R b}}{ b\\tto_R u\n    \\to t\\tto_R u} \\and \\inferrule*[Right=MP]{\\inferrule*[Right={\n    $IH$}]{~}{u\\tto_R v \\to b\\tto_R u} \\and\n    \\inferrule*[Right={H2}]{~}{u\\tto_R v}}{b\\tto_R u}}{t\\tto_R u}\n    \\end{mathpar}}%\n\n    Each branch of the above tree corresponds to a new goal in the Coq\n    proof. Therefore, we have two subcases (or subgoals) to prove: In\n    this subgoal we need to prove that $t \\to_R b$, which we have as\n    hypothesis (line 7). In the second subgoal (line 8), we need to\n    prove that $b \\tto_R u$. To do so, we apply the induction\n    hypothesis [IHrefltrans]: $u \\tto_R v \\to b \\tto_R u$, where\n    $u\\tto_R v$ is the hypothesis [H2]. $\\hfill\\Box$ *)\n(* end hide *)\n\n(** This example is interesting because it shows how Coq works, how\neach command line (also known as tactics or tacticals depending on its\nstructure) corresponds, in general, to several steps of natural\ndeduction rules. *)\n\n(* begin hide *)\nLemma refltrans_composition2 {A} (R: Rel A): forall t u v, refltrans R t u -> R u v -> refltrans R t v.\nProof.\n  intros t u v H1 H2. induction H1.\n  - apply rtrans with v.\n    + assumption.\n    + apply refl.\n  - apply IHrefltrans in H2.\n    apply rtrans with b; assumption.\nQed.\n\nLemma trans_to_refltrans {A:Type} (R: Rel A): forall a b, trans R a b -> refltrans R a b.\nProof.\n  intros a b Htrans.\n  induction Htrans.\n  - apply rtrans with b.\n    + assumption.\n    + apply refl.\n  - apply rtrans with b; assumption.\nQed.    \n(* end hide *)\n\n(** The reflexive transitive closure of a relation is used to define\n    the notion of confluence: no matter how the reduction is done, the\n    result will always be the same. In other words, every divergence\n    is joinable as stated by the following diagram:\n\n    $\\centerline{\\xymatrix{ & a \\ar@{->>}[dl] \\ar@{->>}[dr] & \\\\ b\n    \\ar@{.>>}[dr] & & c \\ar@{.>>}[dl] \\\\ & d & }}$\n\n\n    Formally, this means that if an expression $a$ can be reduced in\n    two different ways to the expressions $b$ and $c$, then there\n    exists an expression $d$ such that both $b$ and $c$ reduce to\n    $d$. The existential quantification is expressed by the dotted\n    lines in the diagram. This notion is defined in the Coq system as\n    follows: *)\n\nDefinition Confl {A:Type} (R: Rel A) := forall a b c, (refltrans R) a b -> (refltrans R) a c -> (exists d, (refltrans R) b d /\\ (refltrans R) c d).\n\n(** In %\\cite{dehornoy2008z}%, V. van Oostrom gives a sufficient\n    condition for an ARS to be confluent, known as the _Z Property_:\n\n    %\\begin{definition} Let $(A,\\to_R)$ be an ARS. Then $(A,\\to_R)$\n      has the Z property, if there exists a map $f:A \\to A$ such that\n      the following diagram holds:\n    \n      \\[ \\xymatrix{ a \\ar[r]_R & b \\ar@{.>>}[dl]^R\\\\ f(a)\n      \\ar@{.>>}[r]_R & f(b) \\\\ } \\] \\end{definition}%\n\nThe corresponding Coq definition is given as: *)\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\n(** Alternatively, for a given function [f], one can say that [f] satisfies the Z property, or that [f] is Z, if the above conditions hold for [f]: *)\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\n(** The first contribution of this work is a constructive proof of the\n    fact that the Z property implies confluence. Our proof uses nested\n    induction, and hence it differs from the one in %\\cite{kes09}%\n    (that follows %\\cite{dehornoy2008z}%) and the one in %\\cite{zproperty}% \n    in the sense that it does not rely on analyzing whether \n    a term is in normal form or not, avoiding necessity of \n    the law of the excluded middle . As a result, we have \n    an elegant inductive proof of the fact that if a binary relation\n    has the Z property then it is confluent. In addition, we\n    formalized this proof in the Coq proof assistant. In\n    %\\cite{zproperty}%, B. Felgenhauer et.al. formalized in Isabelle/HOL \n    the Z property and its relation to confluence. \n    In what follows, we present the theorem\n    and its proof interleaving Coq code and the corresponding\n    comments. *)\n\nTheorem Z_prop_implies_Confl {A:Type}: forall R: Rel A, Z_prop R -> Confl R.\nProof.\n  intros R HZ_prop. (** %\\comm{Let $R$ be a relation over $A$ that satisfies\n    the Z property, which will be denoted by $HZ\\_prop$ for future\n    reference.}% *)\n\n  unfold Z_prop, Confl in *. (** %\\comm{Unfolding both definitions of\n  $Z\\_prop$ and $Confl$, we get the following proof context:\n\n     \\includegraphics[scale=0.5]{fig3.png} }% *)\n\n  intros a b c Hrefl1 Hrefl2. (** %\\comm{Let $a, b$ and $c$ be elements of\n     the set $A$, $Hrefl1$ the hypothesis that $a \\tto_R b$, and\n     $Hrefl2$ the hypothesis that $a\\tto_R c$. We need to prove that\n     there exists $d$ such that $b\\tto_R d$ and $c\\tto_R d$.}% *)\n  \n  destruct HZ_prop as [g HZ_prop]. (** %\\comm{We know from the hypothesis\n     $HZ\\_prop$ that there exists a mapping $f$ that is Z. Let's call\n     $g$ this mapping, and we get following proof context:\n\n      %\\includegraphics[scale=0.6]{fig4.png}%\n\n      The proof proceeds by nested induction, firstly on the length of\n      the reduction from $a$ to $b$, and then on the length of the\n      reduction from $a$ to $c$.}% *)\n  \n  generalize dependent c. (** %\\comm{Before the first induction,\n      i.e. induction on $Hrefl1$, the element $c$ needs to be\n      generalized so that it can be afterwards instantiated with any\n      reduct of $a$.}% *)\n  \n  induction Hrefl1. (** %\\comm{The induction on $Hrefl1$ corresponds to\n       induction on the reflexive transitive closure of the relation\n       $R$, and since $refltrans$ has two rules, the goal splits in\n       two subgoals, one for each possible way of constructing $a\n       \\tto_R b$.}% *)\n  \n  - intros c Hrefl2. (** %\\comm{In the first case, we have that $b = a$ since\n    we are in the reflexive case. This means that we have to prove\n    that there exists $d$, such that $a \\tto_R d$ and $c \\tto_R d$.}% *)\n    \n    exists c; split. (** %\\comm{Taking $d$ as $c$, the proof is simplified to $a\n    \\tto_R c$ and $c \\tto_R c$.}% *)\n\n    + assumption. (** %\\comm{The first component is exactly the hypothesis\n        $Hrefl2$ and }% *) \n\n    + apply refl. (** %\\comm{$c \\tto_R c$ corresponds to an application of\n        the $refl$ axiom.}% *)\n\n        (** The interesting part of the proof is then given by the\n        inductive case, i.e. when $a\\tto_R b$ is generated by the rule\n        [(rtrans)]. In this case, the reduction from [a] to [b] is\n        done in at least one step, therefore there must exists an\n        element $a'$ such that the following diagram holds.\n\n        % \\[\\xymatrix{ & & a \\ar@{->}[dl] \\ar@{->>}[dr] & \\\\ & a'\n        \\ar@{->>}[dl] & & c \\ar@{.>>}[ddll] \\\\ b \\ar@{.>>}[dr] & & &\n        \\\\ & d & & }\\] % \n\n        (* The corresponding proof context is as follows:\n\n        %\\includegraphics[scale=0.6]{fig5.png}% *)\n\n        The induction hypothesis states that every divergence from\n        $a'$ that reduces to $b$ from one side converges: [IHHrefl1]\n        : $\\forall c_0 : A, a'\\tto_R c_0 \\to (\\exists d : A, b\\tto_R d\n        \\land c_0\\tto_R d$). Now, we'd like apply induction on the\n        hypothesis [Hrefl2] (a\\tto_R c), but the current proof context has the\n        hypothesis [H]: $a\\to_R a'$ ([a] reduces to [a'] in one step),\n        and hence it is the sole hypothesis depending on [a] in the\n        current proof context. If we were to apply induction on [Hrefl2] now, \n        the generated induction hypothesis [IHrefl2] would assume that there is \n        a term $a''$ such that $a \\to_R a'' \\tto_R c$ and would require that \n        $a'' \\to_R a'$, which is generally false. In order to circumvent \n        this problem, we need to discard the hypothesis [H] from our proof \n        context, and replace it by another relevant information derived from \n        the Z property as shown in what follows. *)\n\n  - intros c0 Hrefl2. (** %\\comm{Let $c_0$ be a reduct of $a$, and $Hrefl2$\n    be the hypothesis $a \\tto_R c_0$. So the reduction $a\\tto_R c$ in\n    the above diagram is now $a\\tto_R c_0$ due to a renaming of\n    variables automatically done by the Coq system. In addition, the\n    reduction $a \\to_R a' \\tto_R b$ is now $a\\to_R b \\tto_R c$, as\n    shown below:\n\n    \\includegraphics[scale=0.5]{fig5-1.png}\n\n    Before applying induction to $Hrefl2$: $a \\tto_R c_0$, we will derive \n    $b\\tto_R (g\\ a)$ and $a\\tto_R (g\\ a)$ from the proof context so we can\n    discard the hypothesis $H$: $a\\to_R$.}% *)\n\n    assert (Hbga: refltrans R b (g a)).\n    { apply HZ_prop; assumption.  } (** %\\comm{We call $Hbga$ the reduction\n    $b\\tto_R (g\\ a)$ that is directly obtained from the Z property.}% *)\n\n    assert (Haga: refltrans R a (g a)).\n    { apply rtrans with b; assumption.  } (** %\\comm{Call $Haga$ the\n        reduction $a\\tto_R (g\\ a)$, and prove it using the\n        transitivity of $\\tto_R$, since $a \\to_R b$ and $b \\tto_R (g\\\n        a)$. Diagrammatically, we change from the situation on the\n        top to the bottomone on the right:\n\n        \\xymatrix{ & & a \\ar@{->>}[ddrr]_R \\ar@{->}[dl]^R & & \\\\ & b\n        \\ar@{->>}[dl]^R & & & \\\\ c \\ar@{.>>}[ddrr]_R & & & & c_0\n        \\ar@{.>>}[ddll]^R \\\\ & & & & \\\\ & & d & & } \n\n        \\xymatrix{ & & a \\ar@{->>}[ddrr]_R \\ar@{->>}[dd]_R & & \\\\ & b\n        \\ar@{->>}[dl]^R \\ar@{->>}[dr]_R & & & \\\\ c \\ar@{.>>}[ddrr]_R &\n        & (g \\; a) & & c_0 \\ar@{.>>}[ddll]^R \\\\ & & & & \\\\ & & d & &} }% *) \n\n    clear H. generalize dependent b. (** %\\comm{At this point we can remove\n      the hypothesis $H$ from the context, and generalize $b$. Doing so, \n      we generalize $IHHrefl1$, which, in conjunction with the hypotheses \n      that depend on a (namely, $Hrefl2$, $Hbga$, and $Haga$), will form \n      the four necessary conditions for use of the second inductive \n      hypothesis, $IHHrefl2$.}% *)\n\n    induction Hrefl2. (** %\\comm{Now we are ready to start the induction on\n    the reduction $a\\tto_R c_0$, and we have two subgoals.}% *)\n    \n    + intros b Hrefl1 IHHrefl1 Hbga. (** %\\comm{The first subgoal corresponds\n        to the reflexive case that is closed by the induction\n        hypothesis $IHHrefl1$:\n\n        \\[\\xymatrix{ & & a \\ar@{->>}[dd]^{H2} & & \\\\ & b\n        \\ar@{->>}[dl]_{Hrefl1} \\ar@{->>}[dr]^{H1} & & & \\\\ c\n        \\ar@{.>>}[dr] & IHHrefl1 & (g \\; a) \\ar@{.>>}[dl] & & \\\\ & d &\n        &&}\\] }% *)\n      \n      assert (IHHrefl1_ga := IHHrefl1 (g a));\n        \n        apply IHHrefl1_ga in Hbga. (** %\\comm{In order to apply $IHHrefl1$, we instantiate $c_0$ with $(g\\\n      a)$.}% *)\n      \n      destruct Hbga. (** %\\comm{Therefore, there exists an element, say $x$,\n      such that both $c\\tto_R x$ and $(g\\ a) \\tto_R x$.}% *)\n      \n      exists x; split. (** %\\comm{We then take $x$ to show that $c\\tto_R x$ and $a\n      \\tto_R x$.}% *)\n      \n      * apply H. (** %\\comm{Note that $c\\tto_R x$ is already an hypothesis,\n        and we are done.}% *)\n        \n      * apply refltrans_composition with (g a);\n\n        [assumption | apply H]. (**\n      %\\comm{The proof of $a \\tto_R x$ is done by the transitivity of\n      $\\tto_R$ taking $(g\\ a)$ as the intermediate step.}% *)\n           \n    + intros b0 Hrefl1 IHHrefl1 Hb0ga. (** %\\comm{The second subgoal corresponds\n        to the case in which $a\\tto_R c_0$ is generated by the rule\n        $(rtrans)$. Therefore, there exists a term $b$ such that\n        $a\\to_R b$ and $b \\tto_R c_0$. The corresponding proof context\n        after introducing the universally quantified variable $b0$,\n        the hypothesis $Hrefl1$ and the induction hypothesis\n        $IHHrefl1$ generated by the first outer induction and the fact\n        that $b0 \\tto_R (g\\ a)$ is given by:\n\n        \\includegraphics[scale=0.48]{fig7.png} }% *)\n\n      apply IHHrefl2 with b0. (** %\\comm{The second goal, i.e. the inductive case is \n      the consequent on $IHHrefl2$, so we can apply $IHHrefl2$ to prove it. Doing so, \n      we must prove the antecedent of $IHHrefl2$, which consists of four separate \n      hypotheses that we must prove. Those hypotheses are as follows:}% *)\n      \n      * apply refltrans_composition with (g a);\n          \n        apply HZ_prop; assumption. (** %\\comm{1. $b \\tto_R (g\\ b)$: This is proved by the transitivity of the\n      reflexive transitive closure of $R$ using the\n      hypothesis (H: $a\\to_R b$) and $HZ\\_prop$: $\\forall a\\\n      b: a \\to_R b \\to (b \\tto_R (g\\ a) \\land (g\\ a) \\tto_R (g\\ b))$.}% *)\n        \n      * assumption. (** %\\comm{2. $b0 \\tto_R c$: This is exactly the\n          hypothesis $Hrefl1$.}% *)\n\n      * assumption. (** %\\comm{3. $\\forall c0: b0 \\tto_R c0 \\to (\\exists d:\n            c \\tto_R d \\land c0 \\tto_R d)$: This is exactly the\n            induction hypothesis $IHHrefl1$.}% *)\n\n      * apply refltrans_composition with (g a);\n        [ assumption | apply HZ_prop; assumption]. (** %\\comm{4. $b0 \\tto_R (g\\ b)$: This is proved by the transitivity of\n      the reflexive transitive closure of $R$ using the\n      hypothesis $H'$: $b0 \\tto_R (g\\ a)$ and the fact that\n      $(g\\ a) \\tto_R (g\\ b)$ that is obtained from the fact that\n      $R$ satisfies the Z property (hypothesis\n      $HZ\\_prop$).}% *)\n        \nQed.\n\n(* Another proof \n\nLemma refltrans_f_is_Z_refltrans {A:Type}: forall (R: Rel A) a b f, f_is_Z R f -> (refltrans R) a b -> (refltrans R) (f a) (f b).\nProof.\n  intros R a b f H Hab.\n  unfold f_is_Z in H.\n  induction Hab.\n  - apply refl.\n  - apply H in H0.\n    destruct H0 as [H1 H2].\n    apply refltrans_composition with (f b); assumption.\nQed.\n\nLemma refltrans_f_is_Z {A:Type}: forall (R: Rel A) a f, f_is_Z R f -> (refltrans R) a (f a).\nProof.\n  intros R a f H.\n  unfold f_is_Z in H.\nAdmitted.\n\n  Theorem Z_prop_implies_Confl2 {A:Type}: forall R: Rel A, Z_prop R -> Confl R.\n  Proof.\n    intros R H.\n    unfold Z_prop in H.\n    destruct H as [g H].\n    unfold Confl.\n    intros a b c H1 H2.\n    generalize dependent c.\n    induction H1.\n    - intros c H1.\n      exists c; split.\n      + assumption.\n      + apply refl.\n    - intros c0 H2.\n      apply H in H0.\n      destruct H0 as [Hga Hgb].\n      assert (refltrans R (g a) (g c0)).\n      {\n        apply  refltrans_f_is_Z_refltrans.\n        - assumption.\n        - assumption.\n      }\n      assert (refltrans R c0 (g c0)).\n      {\n        apply refltrans_f_is_Z; assumption.\n      }\n      assert (refltrans R b (g c0)).\n      {\n        apply refltrans_composition with (g a); assumption.\n      }\n      apply IHrefltrans in H4.\n      destruct H4 as [d [H4 H5]].\n      exists d; split.\n      +  assumption.\n      + apply refltrans_composition with (g c0); assumption.     \nQed. *)\n      \n(** An alternative proof that Z implies confluence is possible via the\n    notion of semiconfluence, which is equivalent to confluence, as\n    done in %\\cite{zproperty}%. Unlike the proof in %\\cite{zproperty}% and \n    similarly to our previous proof, our proof of the Theorem that \n    Z implies semiconfluence is constructive, but we\n    will not explain it here due to lack of space; any\n    interested reader can find it in the Coq file in our GitHub\n    repository. *)\n  \nDefinition SemiConfl {A:Type} (R: Rel A) := forall a b c, R a b -> (refltrans R) a c -> (exists d, (refltrans R) b d /\\ (refltrans R) c d).\n\nTheorem Z_prop_implies_SemiConfl {A:Type}: forall R: Rel A, Z_prop R -> SemiConfl R.\n(* begin hide *)\nProof.\n  intros R HZ_prop.\n  unfold Z_prop in HZ_prop.\n  unfold SemiConfl.\n  destruct HZ_prop.\n  intros a b c Hrefl Hrefl'.\n  assert (Haxa: refltrans R a (x a)).\n  { apply rtrans with b.  - assumption.  - apply H.  assumption.  }\n  apply H in Hrefl.\n  destruct Hrefl.\n  clear H1.\n  generalize dependent b.\n  induction Hrefl'.\n  - intros.\n    exists (x a).\n    split; assumption.\n  - intros.\n    destruct IHHrefl' with b0.\n    + apply refltrans_composition with (x a); apply H; assumption.\n    + apply refltrans_composition with (x b).\n      * apply refltrans_composition with (x a).\n        ** assumption.\n        ** apply H.\n           assumption.\n      * apply refl.\n    + exists x0.\n      assumption.\nQed.\n(* end hide *)\n\nTheorem Semi_equiv_Confl {A: Type}: forall R: Rel A, Confl R <-> SemiConfl R.\n(* begin hide *)\nProof.\n  unfold Confl.\n  unfold SemiConfl.\n  intro R.\n  split.\n  - intros.\n    apply H with a.\n    + apply rtrans with b.\n      * assumption.\n      * apply refl.\n    + assumption.\n  - intros.\n    generalize dependent c.\n    induction H0.\n    + intros.\n      exists c.\n      split.\n      * assumption.\n      * apply refl.\n    + intros.\n      specialize (H a).\n      specialize (H b).\n      specialize (H c0).\n      apply H in H0.\n      * destruct H0.\n        destruct H0.\n        apply IHrefltrans in H0.\n        destruct H0.\n        destruct H0.\n        exists x0.\n        split.\n        ** assumption.\n        ** apply refltrans_composition with x; assumption.\n      * assumption.\nQed.\n(* end hide *)\n\nCorollary Zprop_implies_Confl_via_SemiConfl {A:Type}: forall R: Rel A, Z_prop R -> Confl R.\nProof. intros R HZ_prop. apply Semi_equiv_Confl. generalize dependent HZ_prop.\n       apply Z_prop_implies_SemiConfl. Qed.\n\n(** * An extension of the Z property: Compositional Z\n\n    In this section we present a formalization of an extension of the\n    Z property with compositional functions, known as _Compositional\n    Z_, as presented in %\\cite{Nakazawa-Fujita2016}%. The\n    compositional Z is an interesting property because it allows a\n    kind of modular approach to the Z property in such a way that the\n    reduction relation can be split into two parts. More precisely,\n    given an ARS $(A,\\to_R)$, one must be able to decompose the\n    relation $\\to_R$ into two parts, say $\\to_1$ and $\\to_2$ such that\n    $\\to_R = \\to_1\\cup \\to_2$. This kind of decomposition can be done\n    in several interesting situations such as the $\\lambda$-calculus\n    with $\\beta\\eta$-reduction%\\cite{Ba84}%, extensions of the\n    $\\lambda$-calculus with explicit substitutions%\\cite{accl91}%, the\n    $\\lambda\\mu$-calculus%\\cite{Parigot92}%, etc. But before\n    presenting the full definition of the Compositional Z, we need\n    to define the _weak Z property_:\n\n    %\\begin{figure}[h] \\centering \\[ \\xymatrix{ a \\ar[r]_R & b\n        \\ar@{.>>}[dl]^x\\\\ f(a) \\ar@{.>>}[r]_x & f(b) \\\\ } \\]\n        \\caption{The weak Z property}\\label{fig:weakZ} \\end{figure}%\n    \n    %\\begin{definition} Let $(A,\\to_R)$ be an ARS and $\\to_R'$ a\n     relation on $A$. A mapping $f$ satisfies the {\\it weak Z\n     property} for $\\to_R$ by $\\to_R'$ if $a\\to_R b$ implies $b \\tto_R'\n     f(a)$ and $f(a) \\tto_R' f(b)$ (cf. Figure\n     \\ref{fig:weakZ}). Therefore, a mapping $f$ satisfies the Z\n     property for $\\to_R$ if it satisfies the weak Z property by\n     itself.  \\end{definition}%\n\n    When $f$ satisfies the weak Z property, we also say that $f$ is\n    weakly Z, and the corresponding definition in Coq is given as\n    follows: *)\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\n(** The compositional Z is an extension of the Z property for\ncompositional functions, where composition is defined as usual: *)\n\nDefinition comp {A} (f1 f2: A -> A) := fun x:A => f1 (f2 x).\nNotation \"f1 # f2\" := (comp f1 f2) (at level 40).\n\n(** %\\noindent% and the disjoint union is inductively defined as: *)\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\n(* begin hide *)\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(* end hide *)\n\n(** We are now ready to present the definition of the compositional Z:\n\n    %\\begin{theorem}\\cite{Nakazawa-Fujita2016}\\label{thm:zcomp} Let\n     $(A,\\to_R)$ be an ARS such that $\\to_R = \\to_1 \\cup \\to_2$. If\n     there exists mappings $f_1,f_2: A \\to A$ such that\n     \\begin{enumerate} \\item $f_1$ is Z for $\\to_1$ \\item $a \\to_1 b$\n     implies $f_2(a) \\tto f_2(b)$ \\item $a \\tto f_2(a)$ holds for any\n     $a\\in Im(f_1)$ \\item $f_2 \\circ f_1$ is weakly Z for $\\to_2$ by\n     $\\to_R$ \\end{enumerate} then $f_2 \\circ f_1$ is Z for\n     $(A,\\to_R)$, and hence $(A,\\to_R)$ is confluent.  \\end{theorem}%\n\n    We define the predicate [Z_comp] that corresponds to the premises\n    of Theorem %\\ref{thm:zcomp}%, i.e. to the conjunction of items\n    (i), (ii), (iii) and (iv) in addition to the fact that $\\to_R =\n    \\to_1 \\cup \\to_2$, where $\\to_1$ (resp. $\\to_2$) is written as\n    [R1] (resp. [R2]): *)\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 a) (f2 b)) /\\ (forall a b, b = f1 a -> (refltrans R) b (f2 b)) /\\ (f_is_weak_Z R2 R (f2 # f1)).\n\n(* begin hide *)\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(* end hide *)\n\n(** As stated by Theorem %\\ref{thm:zcomp}%, the compositional Z gives\n    a sufficient condition for compositional functions to be Z. In\n    other words, compositional Z implies Z, which is justified by the\n    diagrams of Figure %\\ref{fig:zcomp}%.\n \n    %\\begin{figure}[h]\\begin{tabular}{l@{\\hskip 3cm}l} $\\xymatrix{ a\n    \\ar@{->}[rr]^1 && b \\ar@{.>>}[dll]_1\\\\ f_1(a)\\ar@{.>>}[d]\n    \\ar@{.>>}[rr]^1 && f_1(b) \\\\ f_2(f_1(a)) \\ar@{.>>}[rr] &&\n    f_2(f_1(b)) }$ & $\\xymatrix{ a \\ar@{->}[rr]^2 && b\n    \\ar@{.>>}[ddll]\\\\ & & \\\\ f_2(f_1(a)) \\ar@{.>>}[rr] && f_2(f_1(b))\n    }$ \\end{tabular}\\caption{Compositional Z implies\n    Z}\\label{fig:zcomp}\\end{figure}%\n  \n    In what follows, we present our commented Coq proof of this fact:\n    *)\n\nLemma refltrans_union_equiv {A}: forall (R R1 R2 : Rel A) (x y : A), R x y <-> (R1 !_! R2) x y -> forall x y : A, refltrans (R1 !_! R2) x y -> refltrans R x y.\nProof.  \nAdmitted.\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 b (f1 a).\n        ** apply Hunion.\n        ** apply Hb.\n      * apply H3 with a; reflexivity. \n    + apply H1 in H.  destruct H as [Hb Hf].\n      clear Hb.  unfold comp. \n      induction Hf. \n      * apply refl. \n      * apply refltrans_composition with (f2 b0). \n        ** apply H2; assumption. \n        ** apply IHHf. \n  - apply H4; assumption. \nQed.\n\n(** Now we can use the proofs of the theorems [Z_comp_implies_Z_prop]\nand [Z_prop_implies_Confl] to conclude that compositional Z is a\nsufficient condition for confluence. *)\n\nCorollary Z_comp_is_Confl {A}: forall (R: Rel A), Z_comp R -> Confl R.\nProof.\n  intros R H.\n  apply Z_comp_implies_Z_prop in H.\n  apply Z_prop_implies_Confl; assumption.\nQed.\n\n(** Rewriting Systems with equations is another interesting and\n    non-trivial topic %\\cite{winkler89,terese03}%. The confluence of\n    rewriting systems with an equivalence relation can also be proved\n    by a variant of the compositional Z, known as Z property\n    modulo%~\\cite{AK12b}%.\n\n    %\\begin{theorem}\\label{cor:zcomp} Let\n     $(A,\\to_R)$ be an ARS such that $\\to_R = \\to_1 \\cup \\to_2$. If\n     there exist mappings $f_1,f_2: A \\to A$ such that\n     \\begin{enumerate} \\item $a \\to_1 b$ implies $f_1(a) = f_1(b)$\n     \\item $a \\tto_1 f_1(a), for all a$ \\item $a \\tto_R f_2(a)$ holds\n     for any $a\\in Im(f_1)$ \\item $f_2 \\circ f_1$ is weakly Z for\n     $\\to_2$ by $\\to_R$ \\end{enumerate} then $f_2 \\circ f_1$ is Z for\n     $(A,\\to_R)$, and hence $(A,\\to_R)$ is confluent. \\end{theorem}%\n\n    We define the predicate [Z_comp_eq] corresponding to the\n    hypothesis of Theorem %\\ref{cor:zcomp}%, and then we prove\n    directly that if [Z_comp_eq] holds for a relation [R] then [Zprop\n    R] also holds. This approach differs from\n    %\\cite{Nakazawa-Fujita2016}% that proves Theorem\n    %\\ref{cor:zcomp}%, which is a Corollary in %\\cite{Nakazawa-Fujita2016}%, \n    directly from Theorem %\\ref{thm:zcomp}% *)\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        \nLemma Z_comp_eq_implies_Z_prop {A:Type}: forall (R : Rel A), Z_comp_eq R -> Z_prop R.\nProof.\n  intros R Heq.  unfold Z_comp_eq in Heq. (** %\\comm{Let $R$ be a relation\n  and suppose that $R$ satisfies the predicate $Z\\_comp\\_eq$.}% *)\n  \n  destruct Heq as [R1 [R2 [f1 [f2 [Hunion [H1 [H2 [H3 H4]]]]]]]]. (**\n  %\\comm{Call $Hi$ the $i$th hypothesis as in \\ref{cor:zcomp}.}% *)\n  \n  unfold Z_prop.  exists (f2 # f1). (** %\\comm{From the definition of the\n  predicate $Z\\_prop$, we need to find a map, say $f$ that is Z. Let\n  $(f_2 \\circ f_1)$ be such map.}%  *)\n  \n  intros a b Hab. (** %\\comm{In order to prove that $(f_2 \\circ f_1)$ is Z,\n  let $a$ and $b$ be arbitrary elements of type $A$, and $Hab$ be the\n  hypothesis that $a \\to_{R} b$.}% *)\n  Admitted.\n(*  \n  inversion Hunion; subst; clear H.  inversion Hab; subst; clear Hab. (**\n  %\\comm{Since $a$ $R$-reduces in one step to $b$ and $R$ is the union of the\n  relations $R1$ and $R2$ then we consider two cases:}% *)\n  \n  - unfold comp; split. (** %\\comm{The first case is when $a \\to_{R1}\n    b$. This is equivalent to say that $f_2 \\circ f_1$ is weak Z for\n    $R1$ by $R1 \\cup R2$.}% *)\n    \n    + apply refltrans_composition with (f1 b). (** %\\comm{Therefore, we first\n    prove that $b \\tto_{(R1\\cup R2)} (f_2 (f_1\\ a))$, which can be\n    reduced to $b \\tto_{(R1\\cup R2)} (f_1\\ b)$ and $(f_1\\ b)\n    \\tto_{(R1\\cup R2)} (f_2 (f_1\\ a))$ by the transitivity of\n    $refltrans$.}% *)\n      \n      * apply refltrans_union.  apply H2. (** %\\comm{From hypothesis $H2$, we\n        know that $a \\tto_{R1} (f_1\\ a)$ for all $a$, and hence\n        $a\\tto_{(R1\\cup R2)} (f_1\\ a)$ and we conclude.}% *)\n        \n      * apply H1 in H.  rewrite H.  apply H3 with b; reflexivity. (**\n        %\\comm{The proof that $(f_1\\ b)\\tto_{(R1\\cup R2)} (f_2 (f_1\\ a))$ is\n        exactly the hypothesis $H3$.}% *)\n\n    + apply H1 in H.  rewrite H.  apply refl. (** %\\comm{The proof that $(f_2\n    (f_1\\ a)) \\tto_{(R1\\cup R2)} (f_2 (f_1\\ b))$ is done using the\n    reflexivity of $refltrans$ because $(f_2 (f_1\\ a)) = (f_2 (f_1\\\n    b))$ by hypothesis $H1$.}% *)\n      \n  - apply H4; assumption. (** %\\comm{When $a \\to_{R2} b$ then we are done by\n    hypothesis $H4$.}% *)\n\nQed.\n*)\n", "meta": {"author": "flaviodemoura", "repo": "lx_confl", "sha": "a4ef454f9b5e0d6e71abbd965be9a2e4a72458ea", "save_path": "github-repos/coq/flaviodemoura-lx_confl", "path": "github-repos/coq/flaviodemoura-lx_confl/lx_confl-a4ef454f9b5e0d6e71abbd965be9a2e4a72458ea/ZtoConfl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7686725633449862}}
{"text": "Require Export Utils Basics.\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.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n                            andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    simpl in H.\n    rewrite -> H.\n    reflexivity.\n  Case \"b = false\".\n    destruct c.\n    SCase \"c = true\".\n      reflexivity.\n    SCase \"c = false\".\n      simpl in H.\n      rewrite -> H.\n      reflexivity.\nQed.\n\nTheorem plus_O_r : forall n : nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S h'\". simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat,\n                       minus n n = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". simpl. reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_O_r : forall n : nat,\n                     n * 0 = 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 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\". reflexivity.\n  Case \"n = S 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'].\n  Case \"n = 0\". simpl. rewrite <- plus_n_O. reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'. 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\". simpl. reflexivity.\n  Case \"n = S 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'].\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'. rewrite -> plus_n_Sm.\n    reflexivity.\nQed.\n\nTheorem mult_O_plus' : forall n m : nat,\n                         (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: O + 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  rewrite -> plus_assoc.\n  assert (H: n + m = m + n). rewrite -> plus_comm. reflexivity.\n  rewrite -> H. rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nTheorem mult_plus : forall m n : nat,\n                      n * S m = n + n * m.\nProof.\n  intros m n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'. rewrite -> plus_swap.\n  reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n                      m * n = n * m.\nProof.\n  intros m n. induction n as [| n'].\n  Case \"n = 0\". rewrite -> mult_O_r. reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> mult_plus. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem evenb_n__oddb_Sn : forall n : nat,\n                             evenb n = negb (evenb (S n)).\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    assert (H: evenb (S (S n')) = evenb n'). reflexivity.\n    rewrite -> H. rewrite -> IHn'. rewrite -> negb_involutive.\n    reflexivity.\nQed.\n\nTheorem ble_nat_refl : forall n : nat,\n                         true = ble_nat n n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\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. reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n                         andb b false = false.\nProof.\n  intros b. destruct b; reflexivity.\nQed.\n\nLemma plus_O_l : forall n : nat,\n                   0 + n = n.\nProof.\n  reflexivity.\nQed.\n\nTheorem plus_ble_compat_l :\n  forall n m p : nat,\n    ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n  intros n m p H. induction p as [| p']; simpl.\n  Case \"p = 0\". rewrite -> H. reflexivity.\n  Case \"p = S p'\". rewrite -> IHp'. reflexivity.\nQed.\n\nTheorem S_nbeq_O : forall n : nat,\n                     beq_nat (S n) 0 = false.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_1_l : forall n : nat, 1 * n = n.\nProof.\n  intros n. simpl. rewrite -> plus_O_r. reflexivity.\nQed.\n\nTheorem all3_spec :\n  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; destruct c; 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 n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'. 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. induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'. rewrite -> mult_plus_distr_r.\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'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n                       n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  replace (n + m) with (m + n).\n  rewrite -> plus_assoc.\n  reflexivity.\n\n  Case \"n + m = m + n\".\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\nTheorem bin_to_nat_pres_incr :\n  forall b : bin,\n    bin_to_nat (bin_incr b) = (bin_to_nat b) + 1.\nProof.\n  intros b. induction b as [| b'| b''].\n  Case \"b = Z\". reflexivity.\n  Case \"b = Twice b'\". reflexivity.\n  Case \"b = STwice b''\".\n    simpl.\n    rewrite -> IHb''.\n    repeat rewrite -> plus_O_r.\n    rewrite -> plus_swap.\n    repeat rewrite -> plus_assoc.\n    reflexivity.\nQed.\n\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with\n    | O => Z\n    | S n' => bin_incr (nat_to_bin n')\n  end.\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'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IHn'.\n    rewrite -> plus_comm.\n    reflexivity.\nQed.\n\nFixpoint normalize (b:bin) : bin :=\n  match b with\n    | Z => Z\n    | Twice b' => nat_to_bin (bin_to_nat b)\n    | STwice b' => nat_to_bin (bin_to_nat b)\n  end.\n\nTheorem bin_to_nat_to_bin :\n  forall b : bin, nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  intros b. destruct b as [| b'| b'']; reflexivity.\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/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7686725617802581}}
{"text": "(** -> を含む証明 *)\nModule Section4.\n\nSection imp_sample.\nVariables P Q R:Prop.\nTheorem imp_sample : (P -> (Q -> R)) -> (P -> Q) -> P -> R.\nProof.\n  (* 最初は intro(s) してゴールの -> を無くす *)\n  intros pqr pq p.\n  (* ゴールの R を得られそうなのは pqr *)\n  apply pqr.\n    (* ゴール = P. そのままの仮定があれば assumption *)\n    assumption.\n    (* ゴール = Q. pq を使えば Q が得られそう *)\n    apply pq.  assumption.\nQed.\n\n(** 4.2 /\\ を含む証明 *)\nTheorem and_assoc : (P/\\Q)/\\R -> P/\\(Q/\\R).\nProof.\n  intro pqr.\n  (* (P/\\Q)/\\R を分解する *)\n  destruct pqr as [[p q] r].\n  (* ゴールの P/\\(Q/\\R) を P と Q/\\R に分解 *)\n  split.\n    (* ゴール P *)\n    assumption.\n    (* ゴール Q /\\ R。 split. assumption. assumption. でも OK *)\n    split; assumption.\nQed.\n\n(** 4.3 \\/ を含む証明 *)\nTheorem or_assoc : (P\\/Q)\\/R -> P\\/(Q\\/R).\nProof.\n  intro pqr.\n  (* (P\\/Q)\\/R を分解する *)\n  destruct pqr as [[p|q]|r].\n    (* 仮定 p:P *)\n    left. assumption.\n    (* 仮定 q:Q *)\n    right. left. assumption.\n    (* 仮定 r:R *)\n    right; right.  assumption.\nQed.\n\n(** 4.4 ~を含む証明 *)\nPrint False.\n\nTheorem neg_sample : ~(P /\\ ~P).\nProof.\n  (* ~で始まるゴールは intro *)\n  intro.\n  destruct H as [p np].\n  (* ゴールが False なら ~で始まる仮定を elim *)\n  elim np.\n  assumption.\nQed.\n\nEnd imp_sample.\n(** 課題４：命題論理の証明 *)\n(* 証明せよ *)\nSection Ex4.\nVariable A B C D:Prop. \nTheorem ex4_1 : (A -> C) /\\ (B -> D) /\\ A /\\ B -> C /\\ D. \nProof.\n(* Proof *)\nQed.\n\nTheorem ex4_2 : ~~~A -> ~A. \nProof.\n(* Proof *)\nQed.\n\nTheorem ex4_3 : (A -> B) -> ~B -> ~A. \nProof.\n(* Proof *)\nQed.\n\nTheorem ex4_4 : ((((A -> B) -> A) -> A) -> B) -> B. \nProof.\n(* Proof *)\nQed.\n\nTheorem ex4_5 : ~~(A\\/~A).\nProof.\n(* Proof *)\nQed.\n\nEnd Ex4.\nEnd Section4.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120202/tutorial3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7684827574300752}}
{"text": "\n\n(* ================================================================== *)\n(* =============== Reasoning about lists and naturals =============== *)\n(* ================================================================== *)\n\nRequire Import List.\n\nSet Implicit Arguments.\n\nPrint list.\nPrint app.\n\nLocate \"::\".\nLocate \"++\".\n\n\n(* three similar proofs by induction using different tactics *)\n\nTheorem app_l_nil : forall (A:Set) (l:list A), app l nil = l.\nProof.\n  intros A l.\n  pattern l. (* pattern performs a beta-expansion *)\nCheck list_ind.\n  apply list_ind.\n  - reflexivity.\n  - intros a l0 IH. simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem app_l_nil' : forall (A:Set) (l:list A), app l nil = l.\nProof.\n  intros A l.\n  elim l.\n  - reflexivity.\n  - intros a l0 IH; simpl; rewrite IH; reflexivity.\nQed.\n\nTheorem app_l_nil'' : forall (A:Set) (l:list A), app l nil = l.\nProof.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\n\nPrint nat.\nPrint length.\n\n\n(* \n Exercise: prove that the length of the append of two lists is equal \n           to the sum of the length of each list \n*)\n\nLemma sum_length : forall (A:Prop)(l1 l2:list A), length(app l1 l2) = length(l1) + length(l2).\nProof.\n  intros a l1 l2. \n  induction l1.\n  - reflexivity.\n  - simpl. SearchPattern (S _ = S _).\n    apply eq_S.\n    assumption.\nQed.\n\n\n    \nFixpoint snoc (A:Type) (a:A) (l:list A) {struct l} : list A :=\n    match l with\n      | nil => a::nil\n      | x::xs => x::(snoc a xs)\n    end.\n\n\nLemma snoc_len : forall (A:Set) (a:A) (l:list A),\n                            length (snoc a l) =  1 + (length l).\nProof.\n  intros.\n  induction l.          (* proof by induction on l *)\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\n(* Exercise: *)\nLemma snoc_app : forall (A:Set) (a:A) (l:list A), snoc a l = l ++ (a::nil).\nProof.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity. \nQed.\n\n(* A predicate defined recursively as a function *)\n\nFixpoint In (A:Set) (a:A) (l:list A) {struct l} : Prop :=\n    match l with\n      | nil => False\n      |  x :: xs => x = a \\/ In a xs\n    end.\n\n\nLemma in_app : forall (A:Set) (l1 l2:list A) (a:A), \n                           In a (app l1 l2) -> In a l1 \\/ In a l2.\nProof.\n  intros.\n  generalize H.  (* generalize – reintroduces an hypothesis into the goal *)\n  clear H.       (* clear – removes an hypothesis from the environment *)\n  induction l1.\n  - simpl. intro H. right. assumption. \n  - intros.  simpl in H. destruct H as [H|H].\n    + rewrite H. left. simpl. left. reflexivity.\n    +  destruct (IHl1 H).  (* apply IHl1 in H. destruct H. *)\n      * left. simpl. right; assumption.\n      * right; assumption.\nQed.\n\n\n\nPrint rev.\n\n\n\nLemma rev_rev_l : forall (A:Set) (l:list A), rev (rev l) = l.\nProof.\n  induction l.\n  - reflexivity.\n  - simpl.\n(* This auxiliary lemma would help...\nLemma rev_aux : forall (A:Set) (l: list A) (a:A), rev (l ++ (a :: nil)) = a :: (rev l).\nYou can prove it before this lemma or you can use the tactic assert as follows.\n*)\n    assert (rev_aux : forall (A:Set) (l: list A) (a:A), rev (l ++ (a :: nil)) = a :: (rev l)).\n    + induction l0.\n      * reflexivity.\n      * intro. simpl. rewrite IHl0.\n        simpl. reflexivity.\n    + rewrite rev_aux.\n      rewrite IHl. reflexivity.\nQed.\n\n\n\n\nPrint nat.\n\n(* A predicate on natural numbers defined as an inductive type *)\n\nInductive Even : nat -> Prop :=\n| Even_base : Even 0\n| Even_step : forall n, Even n -> Even (S (S n)).\n\n(*\n\n-- --------------- (Even_base)\n     Even 0\n\n      Even n\n--------------------- (Even_step)\n   Even (S (S n))\n\n*)\n\n\nLemma not_1_even : ~(Even 3).\nProof.\n  red.\n  intros.\n  inversion H. inversion H1.\n(* inversion_clear H. inversion H0.  *)\nQed.\n\n\n\nProposition sum_even : forall n m:nat, Even n -> Even m -> Even (n+m).\nProof.\n  intros.\n  induction H.               (* proof by induction on the predicate (Even n) *)\n  - simpl. assumption.\n  - simpl. apply Even_step.  (* constructor whould work here also *)\n    assumption.\nQed.\n\n\nLemma  s_n_even : forall n:nat, Even n -> ~ Even (1+n).\nProof.\n  intros n H. simpl.\n  induction H. \n  - intro. inversion H.\n  - intro. inversion_clear H0. contradiction.\nQed.\n\n\nLemma double_even : forall n:nat, Even (2*n).\nProof.\n  intros. simpl. elim n.\n  - simpl. constructor.  (* apply Even_base. *)\n  - intros. simpl.\n    cut (forall x y:nat, x+(S y) = S (x+y)).   (* similar to assert *)\n    + intros. rewrite H0. constructor. assumption.\n    + clear H. intros. induction x.\n      * reflexivity.\n      * simpl. rewrite IHx. reflexivity.\nQed.\n\n(*\n Exercise: rewrite the prove of the previous lemma without using the cut tactic.\n Hint: use the command SearchPattern or SearchRewrite to find out a useful lemma in the database.\n*)\n\nLemma double_even' : forall n:nat, Even (2*n).\nProof.\n  intros.\n  simpl.\n  induction n.\n  - simpl. constructor.\n  - simpl. \n    rewrite PeanoNat.Nat.add_0_r. \n    rewrite PeanoNat.Nat.add_succ_r. \n    constructor.\n    rewrite PeanoNat.Nat.add_assoc in IHn.\n    rewrite PeanoNat.Nat.add_0_r in IHn.\n    assumption.\n  Qed.  \n\n\n(*\n Exercise: define the \"Odd\" predicate and prove that for every n, (Even n)->(Odd (S n)).\n*)\n\nInductive Odd : nat -> Prop :=\n| Odd_base : Odd 1\n| Odd_step : forall n, Odd n -> Odd (S (S n)).\n\nLemma even_odd : forall n:nat, (Even n)->(Odd (S n)).\nProof.\n  intros.\n  elim H.\n    - constructor.\n    - intros.\n      constructor.\n      assumption.\nQed.\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\nLemma last_nil : forall (A:Type) (x:A), ~(Last x nil).\nProof.\n  intros. intro. inversion H.\nQed.\n\n\n(* The prove of  ~(Last x nil)  without using the inversion tactic. *)\n\nLemma last_nil_aux : forall (A:Type) (l: list A) (x:A), Last x l -> l=nil -> False.\nProof.\n  intros A l x H. elim H.\n  - intro H0. discriminate H0.\n  - intros. discriminate H2.\nQed.\n\nTheorem last_nil' : forall (A:Type) (x:A), ~(Last x nil).\nProof.\n  intros. intro.\n  apply last_nil_aux with A nil x.\n  - assumption.\n  - reflexivity.\nQed.\n\n\n\n(* Exercise: \n*)\nLemma rev_last : forall (A:Type) (x:A) (l: list A), (Last x (rev (x::l))).\n(* An auxiliary lemma can be useful! *)\nProof.\n  intros.\n  simpl.\n  induction l.\n  - constructor.\n  - Search rev.  \n    constructor.\nQed.\n\n", "meta": {"author": "melpereira7", "repo": "VF_2122", "sha": "cbac6daa9e4640a095cfadc06ad5fa5722d4bbfd", "save_path": "github-repos/coq/melpereira7-VF_2122", "path": "github-repos/coq/melpereira7-VF_2122/VF_2122-cbac6daa9e4640a095cfadc06ad5fa5722d4bbfd/Exercícios/Coq/lesson2b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7684827559883265}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\n\nSet 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 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  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    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) : 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 interesting point becomes apparent: The second\n    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 the recent flurry of activity in the\n    functional programming 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\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(** * 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 HPQ HQR =>\n    match HPQ, HQR with\n    | conj HP _, conj _ HR => conj HP HR\n    end.\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  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(** ** 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(** **** 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  intros X x y Heq P HPx. destruct Heq. apply HPx.\nQed.\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 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]).  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:Type) (x:X), []++[x] = x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [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\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-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\n\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/revisit/lf/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.7684827446478382}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\nLocal Open Scope R_scope.\n\n(*\nExample taken from:\nMarc Daumas and Guillaume Melquiond and César Muñoz,\nGuaranteed Proofs Using Interval Arithmetic.\nIn IEEE ARITH 17, pages 188-195, 2005.\n*)\n\nDefinition a := 6378137.\nDefinition f := 1000000000/298257223563.\nDefinition umf2 := (1 - f)².\nDefinition max := 715/512.\nDefinition rp phi := a / sqrt (1 + umf2 * (tan phi)²).\nDefinition arp phi :=\n  let x := max² - phi² in\n  4439091/4 + x * (9023647/4 + x * (\n    13868737/64 + x * (13233647/2048 + x * (\n      -1898597/16384 + x * (-6661427/131072))))).\n\nGoal forall phi, 0 <= phi <= max ->\n  Rabs ((rp phi - arp phi) / rp phi) <= 23/16777216.\nProof.\nunfold rp, arp, umf2, a, f, max.\nintros phi Hphi.\n(*\nTime interval with (i_bisect_diff phi). (* 38 s *)\n*)\nTime interval with (i_bisect_taylor phi 5). (* 4.4 s *)\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-20140610.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502203, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7684592579510865}}
{"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 ZArithRing.\nRequire Import ZArith_base.\nRequire Export Omega.\nRequire Import Wf_nat.\nOpen Local Scope Z_scope.\n\n\n(**********************************************************************)\n(** About parity *)\n\nLemma two_or_two_plus_one :\n  forall n:Z, {y : Z | n = 2 * y} + {y : Z | n = 2 * y + 1}.\nProof.\n  intro x; destruct x.\n  left; split with 0; reflexivity.\n\n  destruct p.\n  right; split with (Zpos p); reflexivity.\n\n  left; split with (Zpos p); reflexivity.\n\n  right; split with 0; reflexivity.\n\n  destruct p.\n  right; split with (Zneg (1 + p)).\n  rewrite BinInt.Zneg_xI.\n  rewrite BinInt.Zneg_plus_distr.\n  omega.\n\n  left; split with (Zneg p); reflexivity.\n\n  right; split with (-1); reflexivity.\nQed.\n\n(**********************************************************************)\n(** The biggest power of 2 that is stricly less than [a]\n\n    Easy to compute: replace all \"1\" of the binary representation by\n    \"0\", except the first \"1\" (or the first one :-) *)\n\nFixpoint floor_pos (a:positive) : positive :=\n  match a with\n    | xH => 1%positive\n    | xO a' => xO (floor_pos a')\n    | xI b' => xO (floor_pos b')\n  end.\n\nDefinition floor (a:positive) := Zpos (floor_pos a).\n\nLemma floor_gt0 : forall p:positive, floor p > 0.\nProof.\n  intro.\n  compute in |- *.\n  trivial.\nQed.\n\nLemma floor_ok : forall p:positive, floor p <= Zpos p < 2 * floor p.\nProof.\n  unfold floor in |- *.\n  intro a; induction a as [p| p| ].\n\n  simpl in |- *.\n  repeat rewrite BinInt.Zpos_xI.\n  rewrite (BinInt.Zpos_xO (xO (floor_pos p))).\n  rewrite (BinInt.Zpos_xO (floor_pos p)).\n  omega.\n\n  simpl in |- *.\n  repeat rewrite BinInt.Zpos_xI.\n  rewrite (BinInt.Zpos_xO (xO (floor_pos p))).\n  rewrite (BinInt.Zpos_xO (floor_pos p)).\n  rewrite (BinInt.Zpos_xO p).\n  omega.\n\n  simpl in |- *; omega.\nQed.\n\n(**********************************************************************)\n(** Two more induction principles over [Z]. *)\n\nTheorem Z_lt_abs_rec :\n  forall P:Z -> Set,\n    (forall n:Z, (forall m:Z, Zabs m < Zabs n -> P m) -> P n) ->\n    forall n:Z, P n.\nProof.\n  intros P HP p.\n  set (Q := fun z => 0 <= z -> P z * P (- z)) in *.\n  cut (Q (Zabs p)); [ intros | apply (Z_lt_rec Q); auto with zarith ].\n  elim (Zabs_dec p); intro eq; rewrite eq; elim H; auto with zarith.\n  unfold Q in |- *; clear Q; intros.\n  apply pair; apply HP.\n  rewrite Zabs_eq; auto; intros.\n  elim (H (Zabs m)); intros; auto with zarith.\n  elim (Zabs_dec m); intro eq; rewrite eq; trivial.\n  rewrite Zabs_non_eq; auto with zarith.\n  rewrite Zopp_involutive; intros.\n  elim (H (Zabs m)); intros; auto with zarith.\n  elim (Zabs_dec m); intro eq; rewrite eq; trivial.\nQed.\n\nTheorem Z_lt_abs_induction :\n  forall P:Z -> Prop,\n    (forall n:Z, (forall m:Z, Zabs m < Zabs n -> P m) -> P n) ->\n    forall n:Z, P n.\nProof.\n  intros P HP p.\n  set (Q := fun z => 0 <= z -> P z /\\ P (- z)) in *.\n  cut (Q (Zabs p)); [ intros | apply (Z_lt_induction Q); auto with zarith ].\n  elim (Zabs_dec p); intro eq; rewrite eq; elim H; auto with zarith.\n  unfold Q in |- *; clear Q; intros.\n  split; apply HP.\n  rewrite Zabs_eq; auto; intros.\n  elim (H (Zabs m)); intros; auto with zarith.\n  elim (Zabs_dec m); intro eq; rewrite eq; trivial.\n  rewrite Zabs_non_eq; auto with zarith.\n  rewrite Zopp_involutive; intros.\n  elim (H (Zabs m)); intros; auto with zarith.\n  elim (Zabs_dec m); intro eq; rewrite eq; trivial.\nQed.\n\n(** To do case analysis over the sign of [z] *)\n\nLemma Zcase_sign :\n  forall (n:Z) (P:Prop), (n = 0 -> P) -> (n > 0 -> P) -> (n < 0 -> P) -> P.\nProof.\n  intros x P Hzero Hpos Hneg.\n  induction  x as [| p| p].\n  apply Hzero; trivial.\n  apply Hpos; apply Zorder.Zgt_pos_0.\n  apply Hneg; apply Zorder.Zlt_neg_0.\nQed.\n\nLemma sqr_pos : forall n:Z, n * n >= 0.\nProof.\n  intro x.\n  apply (Zcase_sign x (x * x >= 0)).\n  intros H; rewrite H; omega.\n  intros H; replace 0 with (0 * 0).\n  apply Zmult_ge_compat; omega.\n  omega.\n  intros H; replace 0 with (0 * 0).\n  replace (x * x) with (- x * - x).\n  apply Zmult_ge_compat; omega.\n  ring.\n  omega.\nQed.\n\n(**********************************************************************)\n(** A list length in Z, tail recursive.  *)\n\nRequire Import List.\n\nFixpoint Zlength_aux (acc:Z) (A:Type) (l:list A) : Z :=\n  match l with\n    | nil => acc\n    | _ :: l => Zlength_aux (Zsucc acc) A l\n  end.\n\nDefinition Zlength := Zlength_aux 0.\nImplicit Arguments Zlength [A].\n\nSection Zlength_properties.\n\n  Variable A : Type.\n\n  Implicit Type l : list A.\n\n  Lemma Zlength_correct : forall l, Zlength l = Z_of_nat (length l).\n  Proof.\n    assert (forall l (acc:Z), Zlength_aux acc A l = acc + Z_of_nat (length l)).\n    simple induction l.\n    simpl in |- *; auto with zarith.\n    intros; simpl (length (a :: l0)) in |- *; rewrite Znat.inj_S.\n    simpl in |- *; rewrite H; auto with zarith.\n    unfold Zlength in |- *; intros; rewrite H; auto.\n  Qed.\n\n  Lemma Zlength_nil : Zlength (A:=A) nil = 0.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma Zlength_cons : forall (x:A) l, Zlength (x :: l) = Zsucc (Zlength l).\n  Proof.\n    intros; do 2 rewrite Zlength_correct.\n    simpl (length (x :: l)) in |- *; rewrite Znat.inj_S; auto.\n  Qed.\n\n  Lemma Zlength_nil_inv : forall l, Zlength l = 0 -> l = nil.\n  Proof.\n    intro l; rewrite Zlength_correct.\n    case l; auto.\n    intros x l'; simpl (length (x :: l')) in |- *.\n    rewrite Znat.inj_S.\n    intros; exfalso; generalize (Zle_0_nat (length l')); omega.\n  Qed.\n\nEnd Zlength_properties.\n\nImplicit Arguments Zlength_correct [A].\nImplicit Arguments Zlength_cons [A].\nImplicit Arguments Zlength_nil_inv [A].\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/Zcomplements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7684421843841691}}
{"text": "Require Import init.\n\nRequire Import nat.\nRequire Import set.\n\nDeclare Scope int_scope.\nDelimit Scope int_scope with int.\n\n(* begin hide *)\nSection IntEquiv.\n(* end hide *)\nLet int_eq (a b : nat * nat) := fst a + snd b = fst b + snd a.\n(* begin hide *)\nLocal Infix \"~\" := int_eq.\n\nLemma int_eq_reflexive : ∀ a, a ~ a.\nProof.\n    intros [a1 a2].\n    unfold int_eq; cbn.\n    reflexivity.\nQed.\nInstance int_eq_reflexive_class : Reflexive _ := {\n    refl := int_eq_reflexive\n}.\n\nLemma int_eq_symmetric : ∀ a b, a ~ b → b ~ a.\nProof.\n    intros [a1 a2] [b1 b2] ab.\n    unfold int_eq in *; cbn in *.\n    symmetry.\n    exact ab.\nQed.\nInstance int_eq_symmetric_class : Symmetric _ := {\n    sym := int_eq_symmetric\n}.\n\nLemma int_eq_transitive : ∀ a b c, a ~ b → b ~ c → a ~ c.\nProof.\n    intros [a1 a2] [b1 b2] [c1 c2] ab bc.\n    unfold int_eq in *; cbn in *.\n    pose proof (lrplus ab bc) as eq; clear ab bc.\n    plus_cancel_left b1 in eq.\n    plus_cancel_left b2 in eq.\n    rewrite eq.\n    apply plus_comm.\nQed.\nInstance int_eq_transitive_class : Transitive _ := {\n    trans := int_eq_transitive\n}.\n\nEnd IntEquiv.\n(* end hide *)\n\nDefinition int_equiv := make_equiv _\n    int_eq_reflexive_class int_eq_symmetric_class int_eq_transitive_class.\nNotation \"a ~ b\" := (eq_equal int_equiv a b) : int_scope.\n\nNotation \"'int'\" := (equiv_type int_equiv).\n\nDefinition nat_to_int a := to_equiv int_equiv (a, zero).\n\nTheorem nat_to_int_eq : ∀ a b, nat_to_int a = nat_to_int b → a = b.\nProof.\n    intros a b eq.\n    unfold nat_to_int in eq.\n    rewrite equiv_eq in eq; cbn in eq.\n    do 2 rewrite plus_rid in eq.\n    exact eq.\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/Int/int_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7683938401910831}}
{"text": "Section Ejercicio1.\n\nInductive list (X:Set) : Set :=\n  nil : list X\n  | cons : X -> list X -> list X.\n\nDefinition nilnat: list nat := nil nat.\nDefinition consnat: nat -> list nat -> list nat:= cons nat.\n\nCheck(list nat).\nCheck(consnat 0 nilnat).\n\nInductive arbol (X:Set): Set :=\n  empty : arbol X\n  | branch : X -> arbol X -> arbol X -> arbol X.\n\nInductive bintree (X:Set) :=\n  Empty : bintree X\n  | Branch : X -> bintree X -> bintree X -> bintree X.\n\nVariable f : Set -> Set.\n\nInductive array (X:Set) : nat -> Set :=\n  emptyarr : array X 0\n  | consarr : forall n: nat,\n    X -> array  X n ->  array X  (n + 1).\n\nInductive matrix (X:Set) : nat -> nat -> Set :=\n  one_col : forall n: nat, array X n -> matrix X n 1 \n  | consm : forall n m: nat,\n    matrix X n m -> array X n -> matrix X n (m+1).\n\n\nInductive leq : nat -> nat -> Prop :=\n  le0 : forall n:nat, leq 0 n\n  | leS : forall n m:nat, leq n m -> leq (S n) (S m).\n\n\n(**\nFixpoint leq (n : nat) (m : nat) : bool := match n, m with\n                                           | 0, _ => true\n                                           | _, 0 => false\n                                           | (S s), (S t) => leq s t\n                                           end.\n\nEval compute in (leq 1 2).\n**)\n\n\nInductive eq_list (X:Set) : list X -> list X -> Prop :=\n  eq_list_nil : eq_list X (nil X) (nil X)\n  | eq_list_cons : forall (l1 l2 : list X) (x1 x2 : X),\n    x1 = x2 -> eq_list X (cons X x1 l1) (cons X x2 l2).\n\nInductive sorted (X:Set) (f:X->X->Prop) : list X -> Prop :=\n  sorted_nil : sorted X f (nil X)\n  | sorted_singleton : forall x:X, sorted X f (cons X x (nil X))\n  | sorted_cons : forall (l : list X) (x1 x2 : X),\n    f x1 x2 -> sorted X f (cons X x2 l) ->\n      sorted X f (cons X x1 (cons X x2 l)).\n\nInductive mirror (X:Set) : bintree X -> bintree X -> Prop :=\n  mirror_empty : mirror X (Empty X) (Empty X)\n  | mirror_branch : forall (t11 t12 t21 t22 : bintree X) (x1 x2 : X),\n    mirror X t11 t22 -> mirror X t12 t21 ->\n      x1 = x2 -> mirror X (Branch X x1 t11 t12) (Branch X x2 t21 t22).\n\nInductive isomorfo (X:Set) : arbol X -> arbol X -> Prop :=\n  isomorfo_empty : isomorfo X (empty X) (empty X)\n  | isomorfo_branch : forall (t11 t12 t21 t22 : arbol X) (x1 x2 : X),\n    isomorfo X t11 t21 -> isomorfo X t12 t22 ->\n      isomorfo X (branch X x1 t11 t12) (branch X x2 t21 t22).\n\n(**\ndata Tree a b = Empty | Leaf a | Branch b (Tree a b) (Tree a b)\n**)\n\nInductive GenTree'' (A B : Set) : Set :=\n  nodeGT'' : A -> GenForest'' A B -> GenTree'' A B\nwith\n  GenForest'' (A B : Set) : Set :=\n    leafGF'' : B -> GenForest'' A B\n    | consGF'' : GenTree'' A B -> GenForest'' A B -> GenForest'' A B.\n\nInductive GenTree (A B : Set) : Set :=\n  leafGT : B -> GenTree A B\n  | nodeGT : A -> GenForest A B -> GenTree A B\nwith\n  GenForest (A B : Set) : Set :=\n    leafGF : GenTree A B -> GenForest A B\n    | consGF : GenTree A B -> GenForest A B -> GenForest A B.\n\nDefinition tree_1 : GenTree nat bool :=\n  nodeGT nat bool 1 (leafGF nat bool (leafGT nat bool true)).\n\nCheck (consGF nat bool tree_1 (leafGF nat bool (leafGT nat bool false))).\nCheck (leafGT nat bool true).\n\nDefinition tree'_1 := leafGT nat bool true.\n\nCheck (nodeGT nat bool 1 (leafGF nat bool tree'_1)).\n\nInductive GenTree' (A B : Set) : Set :=\n  leafGT' : GenForest' A B -> GenTree' A B\n  | nodeGT' : B -> GenForest' A B -> GenTree' A B\nwith\n  GenForest' (A B : Set) : Set :=\n    leafGF' : A -> GenForest' A B\n    | consGF' : GenTree' A B -> GenForest' A B -> GenForest' A B.\n\nCheck (leafGT' nat bool\n  (leafGF' nat bool 1)).\n\nEnd Ejercicio1.\n\nSection Ejercicio2.\n\n(* Apartado 1 *)\n\nDefinition Or : bool -> bool -> bool :=\n  fun b1 b2 =>\n    match b1, b2 with\n      true, _ => true\n      | _, true => true\n      | _, _ => false\n    end.\n\nEval compute in (Or true false).\n\nDefinition And : bool -> bool -> bool :=\n  fun b1 b2 =>\n    match b1, b2 with\n      true, _ => b2\n      | false, _ => false\n    end.\n\nEval compute in (And true false).\nEval compute in (And false true).\n\nDefinition Not : bool -> bool :=\n  fun b =>\n    match b with\n      true => false\n      | _ => true\n    end.\n\nEval compute in (Not true).\n\nDefinition Xor : bool -> bool -> bool :=\n  fun b1 b2 =>\n    match b1, b2 with\n      true, true => false\n      | false, false => false\n      | _, _ => true\n    end.\n\n(* Apartado 2 *)\n\nDefinition is_nil (A : Set) : list A -> bool :=\n  fun xs =>\n    match xs with\n      nil => true\n      | _ => false\n    end.\n\nEval simpl in (is_nil nat (nil nat)).\nEval simpl in (is_nil nat (cons nat 1 (nil nat))).\n\nEnd Ejercicio2.\n\nSection Ejercicio3.\n\n(* Apartado 1 *)\nFixpoint sum (n m : nat) : nat :=\n    match n with\n      0 => m\n      | (S k) => S (sum k m)\n    end.\n\n(* Apartado 2 *)\nFixpoint prod (n m : nat) : nat :=\n    match n with\n      0 => 0\n      | (S k) => sum (prod k m) m\n    end.\n\nEval simpl in (prod 1000 0).\nEval simpl in (forall n: nat, prod n 0 = 0).\n\n(* Apartado 3 *)\nFixpoint pot (n m : nat) {struct m} : nat :=\n  match m with\n    0 => 1\n    | S k => prod n (pot n k)\n  end.\n\nEval simpl in (pot 9 3).\n\n(* Apartado 4 *)\nFixpoint leBool (n m : nat) : bool :=\n  match n, m with\n    0, _ => true\n    | S k, 0 => false\n    | S k1, S k2 => leBool k1 k2\n  end.\n\nEval simpl in (leBool 44 331).\n\nEnd Ejercicio3.\n\nSection Ejercicio4.\n\nCheck nil.\n\n(* Apartado 1 *)\nFixpoint length (A:Set) (xs:list A): nat :=\n  match xs with\n    nil => 0\n    | cons y ys => sum 1 (length A ys)\n  end.\n\nEval simpl in (length bool (cons bool true (nil bool))).\n\n(* Apartado 2 *)\nFixpoint append (A:Set) (xs:list A) (ys:list A): list A :=\n  match xs, ys with\n    nil, _ => ys\n    | cons z zs, _ => cons A z (append A zs ys)\n  end.\n\nEval simpl in (append nat (cons nat 3 (cons nat 1 (nil nat)))\n  (cons nat 2 (nil nat))).\n\nDefinition singleton (A:Set) (a:A) : list A := cons A a (nil A).\n\n(* Apartado 3 *)\nFixpoint reverse (A:Set) (xs:list A) : list A :=\n  match xs with\n    nil => nil A\n    | cons z zs => append A (reverse A zs) (cons A z (nil A))\n  end.\n\nEval compute in (reverse nat (cons nat 1 (cons nat 2 (nil nat)))).\n\n(* Apartado 4 *)\nFixpoint filter (A:Set) (f:A->bool) (xs:list A) : list A :=\n  match xs with\n    nil => nil A\n    | cons y ys => if f y then cons A y (filter A f ys) else filter A f ys\n  end.\n\nEval compute in\n(\nfilter nat\n  (fun x => leBool 2 x)\n  (cons nat 0 (cons nat 12 (cons nat 33 (nil nat))))\n).\n\n(* Apartado 5 *)\nFixpoint map (A B:Set) (f:A -> B) (xs:list A) : list B :=\n  match xs with\n    nil => nil B\n    | cons y ys => cons B (f y) (map A B f ys)\n  end.\n\nEval compute in (map nat nat (fun x => x + 1) (cons nat 1 (nil nat))).\n\n(* Apartado 6 *)\nFixpoint exists_ (A:Set) (p:A -> bool) (xs:list A) : bool :=\n  match xs with\n    nil => false\n    | cons y ys => if p y then true else exists_ A p ys\n  end.\n\nEval compute in\n(\nexists_ nat\n  (fun x => leBool 4 x)\n  (cons nat 0 (cons nat 5 (cons nat 1 (cons nat 12 (nil nat)))))\n).\n\nEnd Ejercicio4.\n\nSection Ejercicio5.\n\n(* Apartado 1 *)\nFixpoint inverse (X : Set) (b : bintree X) : bintree X :=\n  match b with\n    Empty => Empty X\n    | (Branch e l r) => Branch X e (inverse X r) (inverse X l)\n  end.\n\nEval compute in (inverse nat (Branch nat 1 (Empty nat)\n  (Branch nat 2 (Empty nat) (Empty nat)))).\nEval compute in\n(\n  mirror nat\n    (inverse nat (Branch nat 1 (Empty nat)\n      (Branch nat 2 (Empty nat) (Empty nat))))\n    (Branch nat 1 (Empty nat) (Branch nat 2 (Empty nat) (Empty nat)))\n).\n\n(* Apartado 2 *)\n\n(*\nInductive GenTree (A B : Set) : Set :=\n  leafGT : B -> GenTree A B\n  | nodeGT : A -> GenForest A B -> GenTree A B\nwith\n  GenForest (A B : Set) : Set :=\n    leafGF : GenTree A B -> GenForest A B\n    | consGF : GenTree A B -> GenForest A B -> GenForest A B.\n*)\n\n(*Fixpoint nodes (X Y : Set) (gt : GenTree X Y) : bool :=\n*)  \n\nEnd Ejercicio5.\n\nSection Ejercicio6.\n\nDefinition listN := list nat.\n\nFixpoint nat_eq (n:nat) (m:nat) : bool :=\n  match n, m with\n    0, 0 => true\n    | S k1, S k2 => nat_eq k1 k2\n    | _, _ => false\n  end.\n\n(* 6.1 *)\nFixpoint member (n:nat) (xs:listN) : bool :=\n  match xs with\n    nil => false\n    | cons m ys => Or (nat_eq m n) (member n ys)\n  end.\n\nEval compute in (member 2 (cons nat 2 (cons nat 2 (nil nat)))).\n\n(* 6.2 *)\nFixpoint delete (xs:listN) (n:nat) : listN :=\n  match xs with\n    nil => nil nat\n    | cons m ys => if nat_eq m n then\n  delete ys n else cons nat m (delete ys n)\n  end.\n\nEval compute in (delete\n  (cons nat 2 (cons nat 2 (cons nat 80 (nil nat)))) 8).\n\n(* 6.3 *)\nFixpoint insert (x:nat) (xs:listN) {struct xs} : listN :=\n  match xs with\n    nil => cons nat x (nil nat)\n    | cons y ys =>\n    match leBool x y with\n      true => cons nat x (cons nat y ys)\n      | _  => cons nat y (insert x ys)\n    end\n  end.\n\nFixpoint insert_sort (xs:listN) : listN :=\n  match xs with\n    nil => nil nat\n    | cons y ys => insert y (insert_sort ys)\n  end.\n\nEval compute in\n(\n  insert_sort\n    (\n      (cons nat 45\n      (cons nat 0\n      (cons nat 93\n      (cons nat 12\n      (nil nat)\n      ))))\n    )\n).\n\n(* Generalizaciones *)\n\nEnd Ejercicio6.\n\nSection Ejercicio7.\n\n(* 7.1 *)\nInductive Exp (A:Set) : Set :=\n  atom : A -> Exp A\n  | Sum : Exp A -> Exp A -> Exp A\n  | Mul : Exp A -> Exp A -> Exp A\n  | Minus : Exp A -> Exp A.\n\n(* 7.2 *)\nFixpoint InterpretNat (ne : Exp nat) : nat :=\n  match ne with\n    atom n => n\n    | Sum n1 n2 => (InterpretNat n1) + (InterpretNat n2)\n    | Mul n1 n2 => (InterpretNat n1) * (InterpretNat n2)\n    | Minus n => InterpretNat n\n  end.\n\n(* 7.3 *)\nFixpoint InterpretBool (be : Exp bool) : bool :=\n  match be with\n    atom b => b\n    | Sum b1 b2 => Or (InterpretBool b1) (InterpretBool b2)\n    | Mul b1 b2 => And (InterpretBool b1) (InterpretBool b2)\n    | Minus b => Not (InterpretBool b)\n  end.\n\nEnd Ejercicio7.\n\nSection Ejercicio8.\n\n(* 8.1 *)\nTheorem andAsoc : forall p q r: bool,\n  And (And p q) r = And p (And q r).\nProof.\n  destruct p; reflexivity.\nQed.\n\nTheorem orAsoc : forall p q r: bool,\n  Or (Or p q) r = Or p (Or q r).\nProof.\n  destruct p;\n  destruct q;\n  destruct r;\n  reflexivity.\nQed.\n\nTheorem andConmut : forall p q : bool, And p q = And q p.\nProof.\n  destruct p;\n  destruct q;\n  reflexivity.\nQed.\n\nTheorem orConmut : forall p q : bool, Or p q = Or q p.\nProof.\n  destruct p;\n  destruct q;\n  reflexivity.\nQed.\n\n(* 8.2 *)\nLemma LAnd : forall a b : bool, (And a b = true) <->\n  (a = true /\\ b = true).\nProof.\n  destruct a;\n  destruct b;\n  compute;\n  split;\n  intro;\n  [split | | split |destruct H as [_ H] |split\n  |destruct H as [H _] |split |destruct H as [H _] ];\n  trivial.\nQed.\n\n(* 8.3 *)\nLemma LOr1 : forall a b : bool, Or a b = false <->\n  a = false /\\ b = false.\nProof.\n  destruct a;\n  destruct b;\n  compute;\n  split;\n  intro;\n  [split |destruct H as [_ H] | split |destruct H as [H _]\n  |split |destruct H as [_ H] | split |split ];\n  trivial.\nQed.\n\n(* 8.4 *)\nLemma LOr2 : forall a b : bool, Or a b = true\n  <-> a = true \\/ b = true.\nProof.\n  destruct a;\n  destruct b;\n  compute;\n  split;\n  intro;\n  [right | | left |\n  |right | | right | elim H; intros];\n  trivial.\nQed.\n\n(* 8.5 *)\nLemma LXor : forall a b : bool, Xor a b = true <-> a <> b.\nProof.\n  intuition.\n  destruct a; rewrite <- H0 in H; discriminate.\n  destruct a; destruct b; compute;\n    [elim H | | | elim H]; trivial.\nQed.\n\n(* 8.6 *)\nLemma LNot : forall b : bool, Not (Not b) = b.\nProof.\n  destruct b; trivial.\nQed.\n\nEnd Ejercicio8.\n\nSection Ejercicio9.\n\nLemma SumO : forall n : nat, sum n 0 = n.\nProof.\n  apply nat_ind; [ | intros; simpl; rewrite H ]; trivial.\nQed.\n\nLemma SumS : forall n m : nat, sum n (S m) = sum (S n) m.\nProof.\n  intro.\n  elim n; simpl; [ | intros; rewrite -> H]; trivial.\nQed.\n\nLemma SumConm : forall n m : nat, sum n m = sum m n.\nProof.\n  intro.\n  elim n; simpl; [ | intros; rewrite -> H]; trivial.\nQed.\n\nLemma SumAsoc : forall n m p : nat, sum n (sum m p) = sum (sum n m) p.\nProof.\n  intro.\n  elim n; simpl; [ | intros; rewrite -> H ]; trivial.\nQed.\n\nCheck prod.\n\nLemma Prod0 : forall m : nat, prod m 0 = 0.\nProof.\n  induction m;\n  [ | simpl; rewrite IHm ]; trivial.\nQed.\n\nLemma ProdS : forall n m : nat,\n  prod n (S m) = sum (prod n m) n.\nProof.\n  intros.\n  induction n.\n    trivial.\n\n    simpl.\n    rewrite IHn.\n    rewrite SumConm.\n    rewrite SumAsoc.\n    simpl.\n    rewrite SumConm.\n    rewrite SumAsoc.\n    rewrite SumConm.\n    rewrite (SumConm n m).\n    rewrite SumAsoc.\n    trivial.\nQed.\n\nLemma ProdConm : forall n m : nat, prod n m = prod m n.\nProof.\n  intros.\n  induction n;\n  [ symmetry; apply Prod0\n  |\n    rewrite ProdS;\n    simpl;\n    rewrite IHn;\n    trivial ].\nQed.\n\nLemma ProdDistr : forall n m p : nat,\n  prod n (sum m p) = sum (prod n m) (prod n p).\nProof.\n  intros.\n  induction n;\n  [ |\n    simpl;\n    rewrite IHn;\n    rewrite SumAsoc;\n    rewrite SumAsoc;\n    rewrite <- (SumAsoc (prod n m) m (prod n p));\n    rewrite (SumConm m (prod n p));\n    rewrite <- (SumAsoc (prod n m) (prod n p) m)\n  ]; trivial.\nQed.\n\nLemma ProdAsoc : forall n m p : nat, prod n (prod m p) = \nprod (prod n m) p.\nProof.\n  intros.\n  induction n;\n  [ |\n    simpl;\n    rewrite IHn;\n    rewrite (ProdConm (sum (prod n m) m) p);\n    rewrite ProdDistr;\n    rewrite ProdConm;\n    rewrite (ProdConm m p)\n  ]; trivial.\nQed.\n\nEnd Ejercicio9.\n\nSection Ejercicio10.\n\nLemma L1 : forall (A : Set) (l : list A), append A l (nil\n A) = l.\nProof.\n  intros.\n  induction l;\n  [ | simpl; rewrite IHl ]; trivial.\nQed.\n\nLemma L2 : forall (A : Set) (l : list A) (a : A), ~(cons \nA a l) = nil A.\nProof.\n  unfold not.\n  intros.\n  discriminate H.\nQed.\n\nLemma L3 : forall (A : Set) (l m : list A) (a : A), \ncons A a (append A l m) = append A (cons A a l) m.\nProof.\n  intros.\n  induction l; [ | simpl ]; trivial.\nQed.\n\nLemma L4 : forall (A : Set) (l m : list A), \nlength A (append A l m) = sum (length A l) (length \nA m).\nProof.\n  intros.\n  induction l;\n  [ | simpl; rewrite IHl]; trivial.\nQed.\n\nLemma L5 : forall (A : Set) (l : list A),\n  length A (reverse A l) = length A l.\nProof.\n  intros.\n  induction l;\n  [ trivial\n  | simpl;\n    rewrite <- IHl;\n    rewrite L4;\n    simpl;\n    apply SumConm\n  ].\nQed.\n\n(* Lema auxiliar, asociatividad del append *)\nLemma AppendAsoc : forall (A : Set) (l m n : list A),\n  append A (append A l m) n = append A l (append A m n).\nProof.\n  intros.\n  induction l;\n  [ | simpl; rewrite IHl ]; trivial.\nQed.\n\nLemma L6 : forall (A : Set) (l m : list A),\n reverse A (append A l m) = append A (reverse A m) (reverse A l).\nProof.\n  intros.\n  induction l; simpl;\n  [ rewrite L1\n    |\n    rewrite IHl;\n    rewrite AppendAsoc\n  ]; trivial.\nQed.\n\nEnd Ejercicio10.\n\nSection Ejercicio11.\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;\n  [ | simpl; rewrite IHl ]; trivial.\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;\n  [ |\n    simpl;\n    rewrite IHl;\n    case (P x)\n  ]; trivial.\nQed.\n\nLemma L9 : 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;\n  [ |\n    simpl;\n    rewrite IHl\n  ]; trivial.\nQed.\n\nLemma L10 : forall (A : Set) (l : list A),\nreverse A (reverse A l) = l.\nProof.\n  intros.\n  induction l;\n  [ | simpl; rewrite L6; rewrite IHl ]; trivial.\nQed.\n\nEnd Ejercicio11.\n\nSection Ejercicio12.\n\nFixpoint filterMap (A B : Set) (P : B -> bool) (f : A -> B)\n  (l : list A) {struct l} : list B :=\n    match l with\n    | nil => nil B\n    | cons a l1 =>\n      match P (f a) with\n      | true => cons B (f a) (filterMap A B P f l1)\n      | false => filterMap A B P f l1\n      end\n    end.\n\nLemma FusionFilterMap :\n  forall (A B : Set) (P : B -> bool) (f : A -> B) (l : list A), \n    filter B P (map A B f l) = filterMap A B P f l.\nProof.\n  intros.\n  induction l;\n  [ | simpl; case (P (f x)); rewrite IHl ]; trivial.\nQed.\n\nEnd Ejercicio12.\n\nSection Ejercicio18.\n \nVariable A : Set. \nInductive Tree_ : Set := \n  | nullT : Tree_ \n  | consT : A -> Tree_ -> Tree_ -> Tree_.\n\n(* 18.1 *)\nInductive isSubTree: Tree_ -> Tree_ -> Prop :=\n  | isSubTree0 : forall t: Tree_, isSubTree t t\n  | isSubTree1 : forall (t1 t2 t3: Tree_) (x: A),\n    isSubTree t1 t2 -> isSubTree t1 (consT x t2 t3)\n  | isSubTree2 : forall (t1 t2 t3: Tree_) (x: A),\n    isSubTree t1 t3 -> isSubTree t1 (consT x t2 t3).\n\n(* 18.2 *)\nLemma isSubTreeReflex : forall t: Tree_,\n  isSubTree t t.\nProof.\n  apply isSubTree0.\nQed.\n\n(* 18.3 *)\nLemma isSubTreeTrans : forall t1 t2 t3: Tree_,\n  isSubTree t1 t2 /\\ isSubTree t2 t3 -> isSubTree t1 t3.\nProof.\n  intros.\n  destruct H.\n  induction H0;\n  [ |\n    apply isSubTree1;\n    apply IHisSubTree\n    |\n    apply isSubTree2;\n    apply IHisSubTree\n  ]; trivial.\nQed.\n\nEnd Ejercicio18.\n\nSection Ejercicio19.\n\n(* 19.1 *)\nVariable A: Set.\n\nInductive ACom: nat -> Set :=\n  | leafACom: A -> ACom 0\n  | consACom: forall n: nat, A -> ACom n -> ACom n -> ACom (S n).\n\nVariable a: A.\n\nCheck (leafACom a).\n\n(* 19.2 *)\nFixpoint h (n: nat) (t: ACom n): nat :=\n    match t with\n      leafACom _ => 1\n      | consACom n0 x t1 t2 => h n0 t1 + h n0 t2\n    end.\n\nEval simpl in (h 0 (leafACom a)).\n\n(* 19.3 *)\n\nParameter poten: nat -> nat -> nat.\n\nAxiom potO : forall n : nat, poten (S n) 0 = 1.  \n(*  n0 = 1 ∀ n>0  *) \nAxiom potS : forall m: nat, poten 2 (S m) = sum (poten 2 m) (poten 2 m). \n(*  2m+1 = 2m + 2m  *)\n\nLemma e193: forall (n: nat) (t: ACom n),\n  h n t = poten 2 n.\nProof.\n  intros.\n  induction t;\n  [ rewrite potO\n    |\n    simpl;\n    rewrite (potS n)\n  ]; auto.\nQed.\n\nEnd Ejercicio19.\n\nSection Ejercicio20.\n\nDefinition max: nat -> nat -> nat :=\n  fun n m =>\n    if leBool m n then n else m.\n\n(* 20.1 *)\nInductive AB (A: Set): nat -> Set :=\n  | emptyAB: AB A 0\n  | branchAB: forall n k: nat,\n  A -> AB A n -> AB A k -> AB A (S (max n k)).\n\n(* 20.2 *)\nFixpoint camino (A: Set) (n: nat) (t: AB A n): list A :=\n  match t with\n    emptyAB => nil A\n    | branchAB n1 n2 x t1 t2 =>\n      if leBool n2 n1\n      then cons A x (camino A n1 t1)\n      else cons A x (camino A n2 t2)\n  end.\n\n(* Prueba de ejemplo *)\nDefinition e := emptyAB nat.\nDefinition t1 := branchAB nat 0 0 1 e e.\nDefinition t2 := branchAB nat 1 1 2 t1 t1.\nDefinition t3 := branchAB nat 1 2 3 t1 t2.\nDefinition t4 := branchAB nat 1 0 4 t1 e.\nDefinition t5 := branchAB nat 1 2 5 t1 t4.\nDefinition t6 := branchAB nat 3 3 6 t3 t5.\n\nEval simpl in (camino nat 0 e).\nEval simpl in (camino nat 3 t5).\nEval simpl in (camino nat 4 t6).\n\n(* 20.3 *)\nLemma e203 (A: Set): forall (n: nat) (t: AB A n),\n  length A (camino A n t) = n.\nProof.\n  intros.\n  induction t; simpl;\n  [ |\n    unfold max;\n    case (leBool k n);\n    simpl;\n      [ rewrite IHt1 | rewrite IHt2 ]\n   ]; trivial.\nQed.\n\nEnd Ejercicio20.\n\nSection Ejercicio16.\n\nInductive posfijo (A: Set): list A -> list A -> Prop :=\n  posfijoE : forall l: list A, posfijo A l l\n  | posfijoL : forall (l1 l2: list A) (x: A),\n    posfijo A l1 l2 -> posfijo A l1 (cons A x l2).\n\n(* 16.2 *)\nLemma e162a (A : Set) : forall l1 l2 l3 : list A,\n  l2 = append A l3 l1 -> posfijo A l1 l2.\nProof.\n  intros.\n  rewrite H.\n  clear H.\n  induction l3;\n  simpl;\n  [ apply posfijoE\n    |\n    apply posfijoL;\n    trivial\n  ].\nQed.\n\n(* 16.3 *)\nFixpoint ultimo (A: Set) (xs: list A) {struct xs}: list A :=\n  match xs with\n    nil => nil A\n    | cons y nil => xs\n    | cons y ys => ultimo A ys\n  end.\n\nEval simpl in (ultimo nat (cons nat 1 (cons nat 2 (cons nat 3 (nil nat))))).\n\n(* 16.4 *)\nLemma e164 (A: Set):\n  forall l: list A, posfijo A (ultimo A l) l.\nProof.\n  intro.\n  induction l;\n  simpl;\n  [ apply posfijoE\n    |\n    destruct l;\n      [ apply posfijoE\n        |\n        apply posfijoL\n      ];\n      trivial\n   ].\nQed.\n\nLemma e162b (A: Set): forall l1 l2: list A,\n  posfijo A l1 l2 -> (exists l3: list A, l2 = append A l3 l1).\nProof.\n  intros.\n  induction H;\n  [ exists (nil A)\n    |\n    elim IHposfijo;\n    intros;\n    exists (cons A x x0);\n    rewrite H0\n   ]; simpl; trivial.\nQed.\n\nEnd Ejercicio16.\n\nSection Ejercicio15.\n\nInductive Tree (A: Set): Set :=\n  leafTree: A -> Tree A\n  | branchTree: Tree A -> Tree A -> Tree A.\n\n(* 15.1 *)\nFixpoint mapTree (A B: Set) (t: Tree A) (f: A -> B): Tree B :=\n  match t with\n    leafTree x => leafTree B (f x)\n    | branchTree t1 t2 =>\n      branchTree B (mapTree A B t1 f) (mapTree A B t2 f)\n  end.\n\n(* 15.2 *)\nFixpoint numLeaves (A: Set) (t: Tree A): nat :=\n  match t with\n    leafTree x => 1\n    | branchTree t1 t2 =>\n      (numLeaves A t1) + (numLeaves A t2)\n  end.\n\n(* 15.3 *)\nLemma e153 (A B: Set):\n  forall (t: Tree A) (f: A -> B),\n    numLeaves B (mapTree A B t f) = numLeaves A t.\nProof.\n  intros.\n  induction t;\n  simpl;\n  [ |\n    rewrite IHt1;\n    rewrite IHt2\n  ]; trivial.\nQed.\n\n(* 15.4 *)\nFixpoint hojas (A: Set) (t: Tree A): list A :=\n  match t with\n    leafTree x => cons A x (nil A)\n    | branchTree t1 t2 =>\n      append A (hojas A t1) (hojas A t2)\n  end.\n\nLemma e154 (A: Set):\n  forall (t: Tree A), length A (hojas A t) = numLeaves A t.\nProof.\n  intro.\n  induction t;\n  simpl;\n  [ trivial\n    |\n    rewrite L4;\n    rewrite IHt1;\n    rewrite IHt2\n  ]; trivial.\nQed.\n\nEnd Ejercicio15.", "meta": {"author": "nicodelpiano", "repo": "coq", "sha": "06344cda6995cdd9c5d44c52880b49a7ec280ebd", "save_path": "github-repos/coq/nicodelpiano-coq", "path": "github-repos/coq/nicodelpiano-coq/coq-06344cda6995cdd9c5d44c52880b49a7ec280ebd/TP4/practica4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7683610224024409}}
{"text": "Require Import Modal.\nRequire Import occ_in_phi.\nRequire Import Bool.\nRequire Import my_arith__my_leb_nat.\n\n\nFixpoint is_pos (phi : Modal) (i : nat) : bool :=\n  if occ_in_phi phi i then \n  match phi with\n  | atom p => EqNat.beq_nat 1 i\n  | mneg psi => eqb false (is_pos psi i)\n  | mconj psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then is_pos psi1 i\n                          else is_pos psi2 (i-(length (pv_in psi1)))\n  | mdisj psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then is_pos psi1 i\n                          else is_pos psi2 (i-(length (pv_in psi1)))\n  | mimpl psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then eqb false (is_pos psi1 i)\n                          else is_pos psi2 (i-(length (pv_in psi1)))\n  | box psi => is_pos psi i\n  | diam psi => is_pos psi i\n  end\n  else false.\n\nLemma is_pos_defn_mconj : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mconj phi1 phi2) i =\n  if occ_in_phi (mconj phi1 phi2) i \n     then if Nat.leb i (length (pv_in phi1)) \n             then is_pos phi1 i\n             else is_pos phi2 (i-(length (pv_in phi1)))\n     else false.\nProof.\n  intros; simpl; reflexivity.\nQed.\n\nLemma is_pos_defn_mdisj : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mdisj phi1 phi2) i =\n  if occ_in_phi (mdisj phi1 phi2) i \n     then if Nat.leb i (length (pv_in phi1)) \n             then is_pos phi1 i\n             else is_pos phi2 (i-(length (pv_in phi1)))\n     else false.\nProof.\n  intros; simpl; reflexivity.\nQed.\n\nLemma is_pos_defn_mimpl : forall (phi1 phi2 : Modal) (i : nat),\n  is_pos (mimpl phi1 phi2) i =\n  if occ_in_phi (mimpl phi1 phi2) i \n     then if Nat.leb i (length (pv_in phi1)) \n             then eqb false (is_pos phi1 i)\n             else is_pos phi2 (i-(length (pv_in phi1)))\n     else false.\nProof.\n  intros; simpl; reflexivity.\nQed.\n\n\n(* ----------------------------------------------------------------- *)\n(* is_neg *)\n\n\nFixpoint is_neg (phi : Modal) (i : nat) : bool :=\n  if occ_in_phi phi i then \n  match phi with\n  | atom p => false\n  | mneg psi => eqb false (is_neg psi i)\n  | mconj psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then is_neg psi1 i\n                          else is_neg psi2 (i-(length (pv_in psi1)))\n  | mdisj psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then is_neg psi1 i\n                          else is_neg psi2 (i-(length (pv_in psi1)))\n  | mimpl psi1 psi2 => if Nat.leb i (length (pv_in psi1)) then eqb false (is_neg psi1 i)\n                          else is_neg psi2 (i-(length (pv_in psi1)))\n  | box psi => is_neg psi i\n  | diam psi => is_neg psi i\n  end\n  else false.\n", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq_AiML/Coq code/is_pos_neg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7683510182976093}}
{"text": "Require Import Arith List Permutation Extraction.\nRequire Import SortSpec.\n\nRequire Import Tactics.Crush.\nRequire Import Tactics.Tactics.\n\nModule InsertSort <: Sorting.\n\n(** Body of insert sort. Sort the rest list, and insert the head\n    element into the sorted rest list. *)\nFixpoint insert (x : nat) (l : list nat) : list nat :=\n  match l with\n  | nil => x :: nil\n  | y :: l' => if x <=? y\n                 then x :: y :: l'\n                 else y :: insert x l'\n  end.\n\nFixpoint insertsort (l : list nat) : list nat :=\n  match l with\n  | nil => nil\n  | x :: l' => insert x (insertsort l')\n  end.\n\nDefinition sort := insertsort.\n\nExample insertsort_pi :\n  sort [3; 1; 4; 1; 5; 9; 2; 6; 5; 3; 5] = [1; 1; 2; 3; 3; 4; 5; 5; 5; 6; 9].\nProof.\n  simpl; reflexivity.\nQed.\n\n(** [insert] keeps a sorted list still sorted. *)\nLemma insert_keeps_sorted :\n  forall l x, Sorted l -> Sorted (insert x l).\nProof.\n  intros l.\n  induction l; crush.\n  bdestruct (x <=? a); crush.\n  pose proof (IHl x).\n  inversion H; destruct l; crush.\n  bdestruct (x <=? n); crush.\nQed.\n\n(** [insert] keeps a permutation still a permutation. *)\nLemma insert_keeps_permutation :\n  forall l l' x, Permutation l l' -> Permutation (x :: l) (insert x l').\nProof.\n  intros l l'.\n  generalize dependent l.\n  induction l'; crush.\n  bdestruct (x <=? a); crush.\n  pose proof (IHl' l' x (Permutation_refl l')).\n  apply perm_trans with (l' := (a :: x :: l')); auto.\n  apply perm_swap.\nQed.\n\nTheorem sort_algorithm : forall (l : list nat),\n  Sorted (sort l) /\\ Permutation l (sort l).\nProof.\n  unfold sort.\n  intros; induction l; split; crush.\n  - apply insert_keeps_sorted; auto.\n  - apply insert_keeps_permutation; auto.\nQed.\n\nEnd InsertSort.\n\nExtraction InsertSort.insert.\nExtraction InsertSort.insertsort.\n", "meta": {"author": "foreverbell", "repo": "verified", "sha": "44bba8f17b8070de304e14bc6fe1580e6890cd43", "save_path": "github-repos/coq/foreverbell-verified", "path": "github-repos/coq/foreverbell-verified/verified-44bba8f17b8070de304e14bc6fe1580e6890cd43/sorting-algorithms/InsertSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7683510145102955}}
{"text": "Require Export Coq.Strings.String.\nRequire Export Coq.Bool.Bool.\nRequire Export Coq.Arith.EqNat.\nRequire Export List.\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(* Here I have formalized the basic definitions of model theory in Coq and proved some basic theorems \nI have followed this text: http://www.math.toronto.edu/weiss/model_theory.pdf. *)\n\n(******************************************************************************************)\n(* Args *)\n(******************************************************************************************)\n\n(* Argument tuples are lists parameterized by length. These types are passed to functions\nand relations. Specifically an n-place function will take an n-tuple args as its parameter\nand an m-place relation will take an m-typle args as its parameter.*)\n\n(* Inductive type idea and notation taken from\n http://www.cs.cornell.edu/courses/cs6115/2017fa/notes/lecture8.html *)\nInductive args (T : Type) : nat -> Type :=\n| nilA : args T 0\n| consA : forall n, T -> args T n -> args T (S n).\nLocal Notation \"[| |]\" := (@nilA _).\nLocal Notation \"[| x |]\" := (@consA _ 1 x nilA).\nLocal Notation \"[| x ; .. ; y |]\" := (@consA _ _ x (.. (@consA _ _ y (@nilA _)) ..)).\n\n(******************************************************************************************)\n(* Symbols *)\n(******************************************************************************************)\n\n(* In model theory there are symbols for variables, functions, constants, and relations, along with\nall the usual logic connectives and quantifiers, which we will see later in the formula section. *)\n\nInductive var : Type :=\n(* The nat is the variable identifier. *)\n| Var : nat -> var. \nInductive func : Type :=\n(* The first nat is the function identifier and the second nat is the function arity. *)\n| Func : nat -> nat -> func. \nInductive const : Type :=\n(* The first nat is the constant identifier. *)\n| Const : nat -> const.\nInductive rel : Type :=\n(* The first nat is the relation identifier and the second nat is the relation arity. *)\n| Rel : nat -> nat -> rel.\n\n(******************************************************************************************)\n(* Terms *)\n(******************************************************************************************)\n\n(* Terms in model theory are variables, constants, or n-place functions which take n arguments, \nall of which are also terms. *)\n\n(* Does the arity of the function f match arity? *)\nDefinition arity_match_func (f : func) (arity : nat) := match f with\n| Func _ ar => arity = ar\nend.\n\nInductive term : Type :=\n(* Wraps a variable symbol. *)\n| VarT   : var -> term\n(* Wraps a constant symbol. *)\n| ConstT : const -> term\n(* Function terms consist of a symbol, an arity, a term argument tuple of that arity, \nand a proof that the symbol arity matches the specified arity. *)\n| FuncT  : forall (f : func) (arity : nat) (arg : args term arity), \n            (arity_match_func f arity) -> term.\n\nModule func_inst_example.\nDefinition v0 := VarT (Var 0).\nDefinition myArgs := [| v0; v0 |].\nDefinition myFuncSym := Func 0 2.\nDefinition myProof : (arity_match_func myFuncSym 2). Proof. reflexivity. Qed. \nDefinition myFunc := FuncT myFuncSym 2 myArgs myProof.\nEnd func_inst_example.\n\n(******************************************************************************************)\n(* Formulas *)\n(******************************************************************************************)\n\n(* Formulas in model theory are relations (including the special equals relation, which is a \npart of any language), as well as the usual logical connectives applied to formulas. Note that\nEquals and Relates formulas are known as atomic formulas. *)\n\nDefinition arity_match_rel (r : rel) (arity : nat) := match r with\n| Rel _ ar => arity = ar\nend.\n\nInductive formula : Type :=\n(* Equals formulas takes in two formulas and always as the usual interpretation of equality. *) \n| Equals  : term -> term -> formula\n(* Relates formulas consist of a symbol, an arity, a term argument tuple of that arity\nand a proof that the symbol arity matches the specified arity. *)\n| Relates : forall (r : rel) (arity : nat) (arg : args term arity), \n            (arity_match_rel r arity) -> formula\n(* Usual logical Not. *)\n| Not     : formula -> formula\n(* Usual logical Or. *)\n| Or      : formula -> formula -> formula\n(* Usual predicate calculus quantification. *)\n| Forall  : var -> formula -> formula.\n\n(* Derived formulas *)\nDefinition And (phi psi : formula) := Not (Or (Not phi) (Not psi)).\nDefinition Impl (phi psi : formula) := Or (Not phi) psi.\nDefinition Iff (phi psi : formula) := And (Impl phi psi) (Impl psi phi).\nDefinition Exists (v : var) (phi : formula) := Not (Forall v (Not phi)).\n\n(******************************************************************************************)\n(* Subformulas *)\n(******************************************************************************************)\n\n(* Here we define the notion of a subformula of a formula. *)\nInductive subformula : formula -> formula -> Prop :=\n| SubIden   (psi phi : formula) : psi = phi -> subformula psi phi\n(* If psi is the same as phi, psi is a subformula of phi. *)\n| SubNot    (psi phi : formula) : subformula (Not psi) phi -> subformula psi phi\n(* If Not psi is a subformula of phi, psi is a subformula of phi. *)\n| SubOrL    (theta psi phi : formula) : subformula (Or theta psi) phi -> subformula theta phi\n(* If Or theta psi is a subformula of phi, theta is a subformula of phi. *)\n| SubOrR    (theta psi phi : formula) : subformula (Or theta psi) phi -> subformula psi phi\n(* If Or theta psi is a subformula of phi, psi is a subformula of phi. *)\n| SubForall (v : var) (psi phi : formula) : subformula (Forall v psi) phi -> subformula psi phi.\n(* If Forall v psi is a subformula of phi, psi is a subformula of phi. *)\n\n(* Below are proofs about subformulas for derived formulas. *)\n\n(* If And theta psi is a subformula of phi, theta is a subformula of phi. *)\nTheorem SubAndL : forall (theta psi phi : formula), \n  subformula (And theta psi) phi -> subformula theta phi.\nProof.\n  intros.\n  unfold And in H.\n  apply SubNot in H.\n  apply SubOrL in H.\n  apply SubNot in H.\n  assumption.\nQed.\n\n(* If And theta psi is a subformula of phi, psi is a subformula of phi. *)\nTheorem SubAndR : forall (theta psi phi : formula),\n  subformula (And theta psi) phi -> subformula psi phi.\nProof.\n  intros.\n  unfold And in H.\n  apply SubNot in H.\n  apply SubOrR in H.\n  apply SubNot in H.\n  assumption.\nQed.\n\n(* If Impl theta psi is a subformula of phi, theta is a subformula of phi. *)\nTheorem SubImplL : forall (theta psi phi : formula),\n  subformula (Impl theta psi) phi -> subformula theta phi.\nProof.\n  intros.\n  unfold Impl in H.\n  apply SubOrL in H.\n  apply SubNot in H.\n  assumption.\nQed.\n\n(* If Impl theta psi is a subformula of phi, psi is a subformula of phi. *)\nTheorem SubImplR : forall (theta psi phi : formula),\n  subformula (Impl theta psi) phi -> subformula psi phi.\nProof.\n  intros.\n  unfold Impl in H.\n  apply SubOrR in H.\n  assumption.\nQed.\n\n(* If Iff theta psi is a subformula of phi, theta is a subformula of phi. *)\nTheorem SubIffL : forall (theta psi phi : formula),\n  subformula (Iff theta psi) phi -> subformula theta phi.\nProof.\n  intros.\n  unfold Iff in H.\n  apply SubAndL in H.\n  apply SubImplL in H.\n  assumption.\nQed.\n\n(* If Iff theta psi is a subformula of phi, psi is a subformula of phi. *)\nTheorem SubIffR : forall (theta psi phi : formula),\n  subformula (Iff theta psi) phi -> subformula psi phi.\nProof.\n  intros.\n  unfold Iff in H.\n  apply SubAndL in H.\n  apply SubImplR in H.\n  assumption.\nQed.\n\n(* If Exists v psi is a subformula of phi, psi is a subformula of phi. *)\nTheorem SubExists : forall (v : var) (psi phi : formula),\n  subformula (Exists v psi) phi -> subformula psi phi.\nProof.\n  intros.\n  unfold Exists in H.\n  apply SubNot in H.\n  apply SubForall in H.\n  apply SubNot in H.\n  assumption.\nQed.\n\n(******************************************************************************************)\n(* Util functions for var/const/func/rel lists *)\n(******************************************************************************************)\n\nDefinition eq_var (v1 : var) (v2 : var) := match v1, v2 with\n| Var v1', Var v2' => beq_nat v1' v2'\nend.\n\nFixpoint contains_var (l : list var) (v : var) := match l with \n| [] => false\n| h::t => eq_var v h || contains_var t v\nend.\n\nFixpoint remove_var (l : list var) (v : var) := match l with\n| [] => []\n| h::t => if eq_var v h then remove_var t v else h::(remove_var t v)\nend.\n\nDefinition eq_const (c1 : const) (c2 : const) := match c1, c2 with\n| Const c1', Const c2' => beq_nat c1' c2'\nend.\n\nFixpoint contains_const (l : list const) (c : const) := match l with\n| [] => false\n| h::t => eq_const c h || contains_const t c\nend.\n\nDefinition eq_func (f1 : func) (f2 : func) := match f1, f2 with\n| Func f1' _, Func f2' _ => beq_nat f1' f2'\nend.\n\nFixpoint contains_func (l : list func) (f : func) := match l with\n| [] => false\n| h::t => eq_func f h || contains_func t f\nend.\n\nDefinition eq_rel (r1 : rel) (r2 : rel) := match r1, r2 with\n| Rel r1' _, Rel r2' _ => beq_nat r1' r2'\nend.\n\nFixpoint contains_rel (l : list rel) (r : rel) := match l with\n| [] => false\n| h::t => eq_rel r h || contains_rel t r\nend.\n\n(******************************************************************************************)\n(* Free variables *)\n(******************************************************************************************)\n\n(* Given a formula, a variable is in the set of that formula's free variables if and only if\nit appears outside the syntatic scope of a quantifier at least once in that formula. *)\n\n(* Helper type that represents function arguments as a list rather than an args. \nThis is so we can use the useful list functions rather than deal with cumbersome arg terms. *)\nInductive termList : Type :=\n| VarTList   : var -> termList\n| ConstTList : const -> termList\n| FuncTList  : func -> (list termList ) -> termList.\n\n(* Converts a term to a termList. *)\nFixpoint term_to_termlist (t : term) := \n\nlet _args_to_list := (fix _args_to_list (n : nat) (a : args term n) := match a with\n| nilA _ => []\n| consA _ n' h t  => (term_to_termlist h)::(_args_to_list n' t)\nend) in\n\nmatch t with\n| VarT v        => VarTList v\n| ConstT c      => ConstTList c\n| FuncT f n a _ => FuncTList f (_args_to_list n a) \nend.\n\n(* Returns a list of all the variables mentioned in the termList. *)\nFixpoint term_vars_helper (t : termList) := match t with\n| VarTList v    => v::[]\n| ConstTList c  => []\n| FuncTList f l => fold_left (fun acc x => acc++(term_vars_helper x)) l []\nend.\n\n(* Returns a list of all the variables mentioned in the term. *)\nDefinition term_vars (t : term) := term_vars_helper (term_to_termlist t).\n\n(* Converts an args term n into a list term. *)\nFixpoint args_to_list (n : nat) (a : args term n) := match a with\n| nilA _ => []\n| consA _ n' h t' => (term_to_termlist h)::(args_to_list n' t')\nend.\n\nModule term_vars_example.\nTheorem am : arity_match_func (Func 1 2) 2. Proof. reflexivity. Qed.\nDefinition t  := FuncT (Func 1 2) 2 [|VarT (Var 1); VarT (Var 1)|] am.\nDefinition tv := term_vars t.\nTheorem thm : contains_var tv (Var 1) = true. Proof. reflexivity. Qed.\nEnd term_vars_example.\n\n(* Returns the free variables of phi. *)\nFixpoint free_vars (phi : formula) := match phi with \n| Equals t1 t2      => (term_vars t1)++(term_vars t2)\n| Relates r n a _   => fold_left (fun a x => a++(term_vars_helper x)) (args_to_list n a) []\n| Not psi           => free_vars psi\n| Or theta psi      => (free_vars theta)++(free_vars psi)\n| Forall v psi      => remove_var (free_vars psi) v\nend.\n\nModule free_vars_example.\nDefinition v1   := VarT (Var 1).\nDefinition v2   := VarT (Var 2).\nTheorem am : arity_match_func (Func 1 1) 1. Proof. reflexivity. Qed.\nDefinition t    := FuncT (Func 1 1) 1 [|v1|] am.\nDefinition phi  := Or (Equals v2 v2) (Forall (Var 1) (Equals t t)).\nDefinition fv   := free_vars phi.\nTheorem thm1 : contains_var fv (Var 1) = false. Proof. reflexivity. Qed.\nTheorem thm2 : contains_var fv (Var 2) = true. Proof. reflexivity. Qed.\nEnd free_vars_example.\n\n(******************************************************************************************)\n(* Substitution *)\n(******************************************************************************************)\n\n(* Given a formula phi, a variable v, and a term t, define substitution to be syntactic replacement\nof all free occurrences of v with t in phi. *)\n\n(* Term substitution. Substitutes all occurrences of v with t in t_orig. *)\nFixpoint subst_term (t_orig : term) (v : var) (t : term) := \nlet subst_term_args := (fix subst_term_args (n : nat) (a : args term n) := match a with\n| nilA _ => nilA _ \n| consA _ n' h t' => consA _ n' (subst_term h v t) (subst_term_args n' t')\nend) in\n\nmatch t_orig with\n| VarT v    => t\n| ConstT c  => ConstT c\n| FuncT f n a p => FuncT f n (subst_term_args n a) p\nend.\n\nFixpoint subst_helper (phi: formula) (v : var) (t : term) (free : list var) := \nlet subst_term_args := (fix subst_term_args (n : nat) (a : args term n) := match a with\n| nilA _ => nilA _\n| consA _ n' h t' => consA  _ n' (subst_term h v t) (subst_term_args n' t')\nend) in\n\nmatch phi with\n| Equals t1 t2    =>  if (contains_var free v) then \n                        Equals (subst_term t1 v t) (subst_term t2 v t) \n                      else \n                        Equals t1 t2\n| Relates r n a p =>  if (contains_var free v) then \n                        Relates r n (subst_term_args n a) p\n                      else \n                        Relates r n a p\n| Not psi         =>  Not (subst_helper psi v t free)\n| Or theta psi    =>  Or (subst_helper theta v t free) (subst_helper psi v t free)\n| Forall v' psi   => Forall v' (subst_helper psi v t (remove_var free v'))\nend.\n\n(* Formula substitution. Substitutes all free occurrences of v with t in phi. *)\nDefinition subst (phi: formula) (v : var) (t : term) := subst_helper phi v t (free_vars phi).\n\nModule subst_example.\nDefinition v1       := Var 1.\nDefinition v1T      := VarT v1.\nDefinition v2T      := VarT (Var 2).\nDefinition cT       := ConstT (Const 1).\nTheorem am : arity_match_rel (Rel 1 2) 2. Proof. reflexivity. Qed.\nDefinition phi      := Or (Equals v1T v1T) (Forall v1 (Relates (Rel 1 2) 2 [|v1T; v2T|] am)).\nDefinition phi_sub  := subst phi v1 cT.\nDefinition expected := Or (Equals cT cT) (Forall v1 (Relates (Rel 1 2) 2 [|v1T; v2T|] am)).\nTheorem thm1 : phi_sub = expected. Proof. reflexivity. Qed.\nEnd subst_example.\n\n(******************************************************************************************)\n(* Languages *)\n(******************************************************************************************)\n\n(* A language in model theory is defined as a set of constant, relation, and function symbols.*)\nInductive lang : Type :=\n| Lang : list const -> list rel -> list func -> lang.\nDefinition lang_const (l : lang) := match l with\n| Lang c r f => c\nend.\nDefinition lang_rel (l : lang) := match l with\n| Lang c r f => r\nend.\nDefinition lang_func (l : lang) := match l with\n| Lang c r f => f\nend.\n\n(* A term is valid with respect to a language if it only mentions symbols from that language. *)\nFixpoint valid_term (language : lang) (t : term) := \nlet valid_term_args := (fix valid_term_args (n : nat) (a : args term n) := match a with\n| nilA _ => true\n| consA _ n' h t => (valid_term language h) && (valid_term_args n' t)\nend) in\n\nmatch t with\n| VarT _        => true\n| ConstT c      => contains_const (lang_const language) c\n| FuncT f n a _ => contains_func (lang_func language) f && (valid_term_args n a)\nend.\n\n(* A formula is valid with respect to a language if it only mentions symbols from that language. *)\nFixpoint valid_formula (language : lang) (phi : formula) := \nlet valid_term_args := (fix valid_term_args (n : nat) (a : args term n) := match a with\n| nilA _ => true\n| consA _ n' h t => (valid_term language h) && (valid_term_args n' t)\nend) in\n\nmatch phi with\n| Equals t1 t2  => (valid_term language t1) && (valid_term language t2)\n| Relates r n a _ => contains_rel (lang_rel language) r && (valid_term_args n a)\n| Not psi       => valid_formula language psi\n| Or psi theta  => (valid_formula language psi) && (valid_formula language theta)\n| Forall _ psi  => valid_formula language psi\nend.\n\nModule valid_formula_example.\nDefinition c1 := ConstT (Const 1).\nDefinition c2 := ConstT (Const 2).\nDefinition c3 := ConstT (Const 3).\nDefinition v1 := Var 1.\nDefinition r1 := (Rel 1 2).\nTheorem am : arity_match_rel r1 2. Proof. reflexivity. Qed.\nDefinition phi := Or (Equals c1 c2) (Forall v1 (Relates r1 2 [|VarT v1; c3|] am)).\nDefinition l := Lang [Const 1; Const 2; Const 3]  [Rel 1 2] [].\nTheorem thm1 : (valid_formula l phi) = true. Proof. reflexivity. Qed.\nDefinition l' := Lang [Const 1; Const 2] [Rel 1 2] [].\nTheorem thm2: (valid_formula l' phi) = false. Proof. reflexivity. Qed.\nEnd valid_formula_example.\n\n(******************************************************************************************)\n(* Models *)\n(******************************************************************************************)\n\n(* Given a language L, a model is a tuple (A, I) where A is a set (called the universe of the model)\nand I is an interpretation function for the constant, function, and relation symbols for L. \nIf a symbol F is an n-place function symbol, then I(F) is an n-place function\nsymbol on A. If a symbol R is an m-place relation symbol, then I(R) is an m-place relation\nsymbol on A. If a symbol C is a constant symbol, then I(C) is an element of A. Note that constants\ncan be viewed as a degenerate case of functions, namely a function that takes 0 arguments.*)\n\n(* Note that it isn't strictly necesary to tie interpretation functions to a language, since\ninterpretation functions for constants/functions/relations can simply map all symbols \nnot in a given language to a single value. For example, if a language has constants\n{Const 1, Const 2}, an interpretation function can map Const 1 to v1, Const 2 to v2, \nand all other constants to v1. Similar reasoning applies to functions and relations. *)\n\n(* The constant portion of the symbol interpretation function maps each constant symbol to an element of A. *)\nInductive constInterp (A : Type) : Type :=\n| ConstInterp : (const -> A) -> constInterp A.\n\n(* The function portion of the symbol interpretation function maps each n-place function symbol \nto a n-place function on A. *)\nInductive funcInterp (A : Type) : Type :=\n| FuncInterp : (func -> (list A) -> A) -> funcInterp A.\n\n(* The relation portion of the symbol interpretation function maps each m-place relation symbol\nto an m-place relation on A. *)\nInductive relInterp (A : Type) : Type :=\n| RelInterp : (rel -> (list A) -> Prop) -> relInterp A.\n\n(* The symbol interpretation function is a composite of the constant, function, and relation\nsymbol interpretation functions. *)\nInductive interpretation (A : Type) : Type :=\n| Interpretation : (constInterp A) -> (funcInterp A) -> (relInterp A) -> interpretation A.\n\n(* A model is a composite of a language and an interpretation function. *)\nInductive model (A : Type) : Type := \n| Model : lang -> (interpretation A) -> model A.\n\nModule model_example.\nDefinition zero := Const 0.\nDefinition plus := Func 0 2.\nDefinition times := Func 1 2.\nDefinition simpleLang := Lang [zero] [] [plus].\nDefinition cInterp (c : const) := if eq_const c zero then 0 else 0.\nFixpoint fInterp (f : func) (args : list nat) :=\n  if (eq_func f plus) then \n    match args with \n    | [] => 0\n    | h::t => h + (fInterp f t)\n    end\n  else\n    match args with\n    | [] => 0\n    | h::t => h * (fInterp f t)\n    end\n.\nDefinition rInterp (r : rel) (args : list nat) := True.\nDefinition interp := \n  Interpretation nat (ConstInterp nat cInterp) (FuncInterp nat fInterp) (RelInterp nat rInterp).\nDefinition myModel := Model nat simpleLang interp.\nEnd model_example.\n", "meta": {"author": "heavyairship", "repo": "model-theory", "sha": "581fa9de38f4306915fcc583df184f09480b7618", "save_path": "github-repos/coq/heavyairship-model-theory", "path": "github-repos/coq/heavyairship-model-theory/model-theory-581fa9de38f4306915fcc583df184f09480b7618/ModelTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7683510126166384}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nRequire Import Poly_complements.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nSection Poly_exec.\nVariable R : ringType.\nImplicit Type p : {poly R}.\n\nLemma Poly_cons (a: R) K:\n\tPoly (a :: K) = cons_poly a (Poly K).\nProof. done. Qed.\n\nDefinition lopp_poly : seq R -> seq R := map -%R.\n\nLemma lopp_poly_spec l : Poly (lopp_poly l) = - Poly l.\nProof.\nelim: l => [|a l IH]; rewrite /= ?rm0 //.\nby rewrite !cons_poly_def IH opprD polyCN mulNr.\nQed.\n\nDefinition lscal_poly (a : R) := map (fun i => a * i).\n\nLemma lscal_poly_spec a l : Poly (lscal_poly a l) = a *: Poly l.\nProof.\nelim: l => [|b l IH]; rewrite /= ?rm0 //.\nby rewrite !cons_poly_def IH scalerDr scalerAl polyCM mul_polyC.\nQed.\n\n(* l1 + l2 *)\nFixpoint ladd_poly (l1 l2 : seq R) :=\n if l1 is a :: l3 then\n   if l2 is b :: l5 then a + b :: ladd_poly l3 l5\n   else l1\n else l2.\n\nLemma ladd_poly_spec l1 l2 : Poly (ladd_poly l1 l2) = Poly l1 + Poly l2.\nProof.\nelim: l1 l2 => [l2| a l1 IH [|b l2]]; rewrite /= ?rm0 //.\nrewrite !cons_poly_def IH  polyCD mulrDl.\nby rewrite -addrA [Poly l2 * _ + _]addrCA addrA.\nQed.\n\n(* l1 - l2 *)\nFixpoint lsub_poly (l1 l2 : seq R) :=\n if l1 is a :: l3 then\n   if l2 is b :: l5 then a - b :: lsub_poly l3 l5\n   else l1\n else lopp_poly l2.\n\nLemma lsub_poly_spec l1 l2 : Poly (lsub_poly l1 l2) = Poly l1 - Poly l2.\nProof.\nelim: l1 l2 => [l2| a l1 IH [|b l2]]; rewrite /= ?rm0 //.\n  by rewrite lopp_poly_spec.\nrewrite !cons_poly_def IH  polyCB mulrBl.\nby rewrite -addrA [-_ + _]addrCA opprD !addrA.\nQed.\nEnd Poly_exec.\n", "meta": {"author": "FlorianSteinberg", "repo": "Cheby", "sha": "2b082ee667336fa6872d00085270c7656becf2bd", "save_path": "github-repos/coq/FlorianSteinberg-Cheby", "path": "github-repos/coq/FlorianSteinberg-Cheby/Cheby-2b082ee667336fa6872d00085270c7656becf2bd/Poly_exec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7683461873718683}}
{"text": "Require Import ZArith.\nRequire Import QArith.\nLoad funs.\n\nOpen Scope Q_scope.\n\nDefinition same_cardinality (A B : Type) :=\n  exists f : A -> B, exists g : B -> A,\n    (forall b : B, f (g b) = b) /\\ (forall a : A, g (f a) = a).\n\nDefinition is_denumerable A := same_cardinality A nat.\n\nLemma same_card_is_two_injectives : forall A B : Type,\n (exists f : A -> B, injective f) ->\n (exists g : B -> A, injective g) -> same_cardinality A B.\n\nTheorem Q_is_at_most_denumerable: exists f : Q -> nat, injective f.\nProof.\nQed.\n\nTheorem Q_is_denumbrable: is_denumbrable Q.\nProof.\n\tdestruct Q_is_at_most_denumerable as [f injf].\nQed.\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/q_denumbrable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7683435211456283}}
{"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 category\n\n*)\n\nRequire Export Misc.Unicode.\nRequire Export Theory.Notations.\nRequire Export Theory.SetoidType.\n\nGeneralizable All Variables.\n\n(*------------------------------------------------------------------------------\n  -- ＣＡＴＥＧＯＲＹ  ＤＥＦＩＮＩＴＩＯＮ\n  ----------------------------------------------------------------------------*)\n(** ** Category definition **)\n\nStructure Category : Type := mkCategory\n{ Obj            :>  Type\n; Hom            :   Obj → Obj → Setoid where \"A ⇒ B\" := (Hom A B)\n; id             :   ∀ {A}, A ⇒ A\n; compose        :   ∀ {A B C}, [ B ⇒ C ⟶ A ⇒ B ⟶ A ⇒ C ] where \"g ∘ f\" := (compose g f)\n; left_id        :   ∀ {A B} {f : A ⇒ B}, id ∘ f ≈ f\n; right_id       :   ∀ {A B} {f : A ⇒ B}, f ∘ id ≈ f\n; compose_assoc  :   ∀ {A B C D} {f : A ⇒ B} {g : B ⇒ C} {h : C ⇒ D}, h ∘ g ∘ f ≈ h ∘ (g ∘ f) }.\n\nArguments mkCategory  {_ _ _ _} _ _ _.\nArguments Hom         {_} _ _.\nArguments id          {_} {_}.\nArguments compose     {_} {_ _ _}.\n\nNotation \"_⇒_\"  := Hom (only parsing).\nInfix \"⇒\"       := Hom.\n\nNotation \"_∘_\"  := compose (only parsing).\nInfix \"∘\"       := compose.\n\nNotation \"'id[' X ]\"     := (id (A := X)) (only parsing).\nNotation \"T '-id'\"       := (id (c := T)) (at level 0, only parsing).\nNotation \"T '-id[' X ]\"  := (id (c := T) (A := X)) (at level 0, only parsing).\n\nNotation \"'Category.make' ⦃ 'Hom' ≔ Hom ; 'id' ≔ id ; 'compose' ≔ compose ⦄\" :=\n  (@mkCategory _ Hom id compose _ _ _) (only parsing).\n\n(** ** Opposite category **)\n\nProgram Definition op_cat (𝒞 : Category) : Category :=\n  Category.make ⦃ Hom ≔ λ (A B : 𝒞) ∙ B ⇒ A\n                ; id  ≔ λ _ ∙ id\n                ; compose ≔ λ _ _ _ ∙ λ g f ↦₂ f ∘ g ⦄.\nNext Obligation. solve_proper. Qed.\nNext Obligation. now rewrite right_id. Qed.\nNext Obligation. now rewrite left_id. Qed.\nNext Obligation. now rewrite compose_assoc. Qed.\n\nNotation \"𝒞 '^op'\" := (op_cat 𝒞) (at level 3, no associativity, format \"𝒞 '^op'\").\n\n(** ** Product of categories **)\n\nLocal Notation π₁ := fst.\nLocal Notation π₂ := snd.\n\nProgram Definition prod_cat (𝒞 𝒟 : Category) : Category :=\n  Category.make ⦃ Hom ≔ λ (A B : 𝒞 ⟨×⟩ 𝒟) ∙ Setoid.make ⦃ Carrier ≔ (π₁ A ⇒ π₁ B) ⟨×⟩ (π₂ A ⇒ π₂ B)\n                                                        ; Equiv ≔ λ f g ∙ π₁ f ≈ π₁ g ∧ π₂ f ≈ π₂ g ⦄\n                ; id  ≔ λ A ∙ (𝒞-id , 𝒟-id)\n                ; compose ≔ λ A B C ∙ λ g f ↦₂ (π₁ g ∘ π₁ f , π₂ g ∘ π₂ f) ⦄.\nNext Obligation.\n  constructor.\n  - intros [f₁ f₂]; split; reflexivity.\n  - intros [f₁ f₂] [g₁ g₂] [eq_f₁g₁ eq_f₂g₂]; split; now symmetry.\n  - intros [f₁ f₂] [g₁ g₂] [h₁ h₂] [? ?] [? ?]; split; etransitivity; eauto.\nQed.\nNext Obligation.\n  intros [? ?] [? ?] [? ?] [? ?] [? ?] [? ?]; split; now apply cong.\nQed.\nNext Obligation.\n  split; now rewrite left_id.\nQed.\nNext Obligation.\n  split; now rewrite right_id.\nQed.\nNext Obligation.\n  split; now rewrite compose_assoc.\nQed.\n\nNotation \"A '𝘅' B\" := (prod_cat A B) (at level 20, left associativity).\nNotation \"'_𝘅_'\" := prod_cat (only parsing).\n", "meta": {"author": "rs-", "repo": "Triangles", "sha": "57f10cb6c627c331b2c6e7b344a34ae50838cc67", "save_path": "github-repos/coq/rs--Triangles", "path": "github-repos/coq/rs--Triangles/Triangles-57f10cb6c627c331b2c6e7b344a34ae50838cc67/Theory/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7682935479855675}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\n\nFixpoint div2 (n:nat):nat:=\n  match n with 0 => 0 | 1 => 0 | S (S p) => S (div2 p) end.\n\nFixpoint div3 (n:nat):nat:=\n  match n with\n    0 => 0\n  | 1 => 0 \n  | 2 => 0\n  | S (S (S p)) => S (div3 p) end.\n\nFixpoint rem2 (n:nat):nat:=\n  match n with 0 => 0 | 1 => 1 | S (S p) => rem2 p end.\n\nTheorem div2_ind :\n  forall P: nat -> Prop,\n    P 0 -> P 1 ->\n    (forall n, P 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 div3_ind :\n  forall P : nat -> Prop,\n    P 0 -> P 1 -> P 2 ->\n    (forall n, P n -> P (S (S (S n)))) ->\n    forall n, P n.\nProof.\n intros P H0 H1 H2 Hstep n.\n assert (P n/\\P(S n)/\\P(S (S n))).\n elim n; intuition.\n intuition.\nQed.\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\nFixpoint fib2 (n:nat) : nat*nat :=\n  match n with\n    0 => (1, 1)\n  | S p => \n    let (v1, v2) := fib2 p in (v2, v1 + v2)\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 div3_le : forall n, div3 n <= n.\nProof.\n intro n; elim n using div3_ind; simpl; auto with arith.\nQed.\n\nTheorem div2_rem2_eq : forall n, 2 * div2 n + rem2 n = n.\nProof.\n intros n; elim n using div2_ind; try (simpl; auto with arith; fail).\n intros p IHp; pattern p at 3; rewrite <- IHp.\n simpl;ring.\nQed.\n\nTheorem fib_fib2_equiv : forall n, fib n = (fst (fib2 n)).\nProof.\n intros n; elim n using fib_ind; try(simpl;auto with arith;fail).\n intros p IHp IHSp.\n replace (fib (S (S p))) with (fib p + fib (S p)).\n rewrite IHp; rewrite IHSp.\n simpl.\n case (fib2 p); auto.\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/div3tofib_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7682935357414042}}
{"text": "Require Import Nat Arith List.\nImport ListNotations.\n\n(*****************************************************************************************)\n(******************************** { Définitions de base } ********************************)\n(*****************************************************************************************)\n\n(** une case du plateau *)\nRecord coord := mkCoord { x : nat; y : nat }.\n\n(** liste de cases *)\nDefinition plateau := list coord.\n\n(** une case est soit blanche soit noire *)\nInductive couleur := Blanc | Noir.\n\n(** négatif *)\nDefinition neg_couleur c :=\n  match c with\n  | Blanc => Noir\n  | Noir => Blanc\n  end.\n\n(**\n  un domino se pose peut être identifié par :\n  - une case\n  - le sens dans lequel il est posé\n  exemple : Hauteur {0;0} occupe les cases {0;0} et {0;1}\n *)\nInductive domino :=\n  | Hauteur : coord -> domino\n  | Largeur : coord -> domino.\n\n(** case a droite de [c] *)\nDefinition droite  (c : coord) := {| x := c.(x) + 1; y := c.(y) |}.\n\n(** case en dessous de [c] *)\nDefinition dessous (c : coord) := {| x := c.(x)    ; y := c.(y) + 1 |}.\n\n(** pair des cases occupées par un domino *)\nDefinition case_prise (d:domino) : coord * coord :=\n  match d with\n  | Hauteur c => (c, dessous c)\n  | Largeur c => (c, droite c)\n  end.\n\n(** une case est blanche si la somme de ses coordonnées est paire *)\nDefinition case_blanche (c : coord) : Prop := Nat.Even (c.(x) + c.(y)).\n\n(** une case est noire si la somme de ses coordonnées est paire *)\nDefinition case_noire (c : coord) : Prop := Nat.Odd (c.(x) + c.(y)).\n\n(** condiction pour que la case [c] soit de couleur [cc] *)\nDefinition couleur_case (cc : couleur) (c : coord) : Prop :=\n  match cc with\n  | Blanc => Nat.Even (c.(x) + c.(y))\n  | Noir  => Nat.Odd  (c.(x) + c.(y))\n  end.\n\n(** calcul le nombre de case de couleur [Blanc] sur un plateau [p] *)\nFixpoint card_bl (p : plateau) :=\n  match p with\n  | [] => 0\n  | c :: t =>\n      if even (c.(x) + c.(y))\n      then 1 + card_bl t\n      else card_bl t\n  end.\n\n(** calcul le nombre de case de couleur [Noir] sur un plateau [p] *)\nFixpoint card_no (p : plateau) :=\n  match p with\n  | [] => 0\n  | c :: t =>\n      if odd (c.(x) + c.(y))\n      then 1 + card_no t\n      else card_no t\n  end.\n\n(** calcul le nombre de case de couleur [c] sur un plateau [p] *)\nDefinition card (c : couleur) (p : plateau) :=\n  match c with\n  | Blanc => card_bl p\n  | Noir  => card_no p\n  end.\n\n(** Fabrique une ligne d'un plateau\n    exemple : mk_line n m = [ { 1; m } .. { n; m } ] *)\nFixpoint mk_line (n m:nat) : list coord :=\n  match n with\n  | 0 => []\n  | S n => {| x := n; y := m |} :: (mk_line n m)\n  end.\n\n(** construction d'un plateau « classique »\n    forme de carré [n] * [n]\n    exemple :\n     mk_plateau n := { {1; 1} ; ... ; {1; n} ; ... ; {n; 1} ; { n; n } } *)\nFixpoint mk_plateau (n:nat) :=\n  match n with\n  | 0 => []\n  | S n =>\n      (mk_line 8 n) ++ (mk_plateau n)\n  end.\n\n\n(** Plateau du problème original est un plateau d'échecs donc : 8x8 *)\nDefinition plateau_base : plateau := mk_plateau 8.\n\n(* Eval compute in mk_plateau 8. *)\n\n(** l'égalité entre coordonnées est décidable *)\nLemma eq_coord : forall a b : coord, {a = b} + {a <> b}.\nProof.\n  decide equality; decide equality.\nDefined.\n\nLemma eq_rw {P}:\n  forall a (x y : P), (if eq_coord a a then x else y) = x.\nProof.\n  intros a y0 x0.\n  case (eq_coord a a).\n  intro eq.\n  - trivial.\n  - contradiction.\nQed.\n\nLemma eq_rw2 {P}:\n  forall a b (x y : P), a <> b -> (if eq_coord a b then x else y) = y.\nProof.\n  intros a b x0 y0 H.\n  case (eq_coord a b).\n  - contradiction.\n  - trivial.\nQed.\n\n(** l'égalité entre dominos est décidable *)\nLemma eq_domino : forall a b : domino, {a = b} + {a <> b}.\nProof.\n  intros a b.\n  destruct a, b.\n  - case (eq_coord c c0); intro e.\n    + rewrite e. left. trivial.\n    + decide equality; apply eq_coord.\n  - right. discriminate.\n  - right. discriminate.\n  - case (eq_coord c c0); intro e.\n    + rewrite e. left. trivial.\n    + decide equality; apply eq_coord.\nDefined.\n\n(** notation à la \\setminus *)\nInfix \"\\\" := (fun a b => List.remove eq_coord b a) (at level 31, left associativity).\n\n(** Plateau du problème : échiquier classique sans 1 pair de coins opposés *)\nDefinition plateau_coupe := plateau_base \\ {| x := 7; y := 7|} \\ {| x := 0; y := 0|}.\n\n(* Eval compute in plateau_coupe. *)\n\n(** poser un domino [d] :\n      retirer les deux cases prisent par [d] dans la liste des cases du plateau *)\nDefinition pose_domino (d : domino) (p : plateau) : plateau :=\n  p \\ fst (case_prise d) \\ snd (case_prise d).\n\nInfix \"//\" := pose_domino (at level 29, right associativity).\n\n(** itérations consécutives de la fonction précédante *)\nDefinition pose_dominos (dl : list domino) (p_init : plateau) : plateau :=\n  fold_left (fun (p : plateau) (d : domino) => d // p) dl p_init.\n\n(** hyp : si l'on a un [p'] tq [p' = pose_domino d p]\n          alors c'est que les cases prisent par le domino\n          étaient présentes dans [p] *)\n\nHypothesis rm_iff_mem : forall p p' d, p' = d // p ->\n  (In (fst (case_prise d)) p /\\ In (snd (case_prise d)) p).\n\nDefinition mk_domino_H (x y : nat) := Hauteur {| x := x ; y := y |}.\nDefinition mk_domino_L (x y : nat) := Largeur {| x := x ; y := y |}.\n\n(* Eval compute in pose_domino (mk_domino_H 4 4) plateau_coupe. *)\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/Domino.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7682734130876949}}
{"text": "Require Export Relations Classes.EquivDec.\nFrom FloatCohorts Require Import Arith Tactics.\n\nOpen Scope Z.\n\n(* simple binary float: no zero, no special values *)\nRecord float_pair : Set := FPair { FPnum : positive; FPexp : Z}.\n\nDefinition fp_equiv_def : relation float_pair :=\n  fun fp1 fp2 =>\n    let '(m1, e1) := (FPnum fp1, FPexp fp1) in\n    let '(m2, e2) := (FPnum fp2, FPexp fp2) in\n    or\n      ((e2 <= e1) /\\ (Z.pos m2 = (Z.pos m1) * 2 ^ (e1 - e2)))\n      ((e1 <= e2) /\\ (Z.pos m1 = (Z.pos m2) * 2 ^ (e2 - e1))).\n\nInstance fp_equiv : Equivalence fp_equiv_def.\nProof.\n  unfold fp_equiv_def.\n  constructor.\n  -\n    constructor.\n    split.\n    reflexivity.\n    rewrite Z.sub_diag, Z.pow_0_r, Z.mul_1_r.\n    reflexivity.\n  -\n    unfold Symmetric; intros.\n    destruct H; auto.\n  -\n    intros fp1 fp2 fp3 EQ12 EQ23.\n    destruct fp1 as [mp1 e1], fp2 as [mp2 e2], fp3 as [mp3 e3].\n    unfold FPnum, FPexp in *.\n    remember (Z.pos mp1) as m1; clear Heqm1 mp1.\n    remember (Z.pos mp2) as m2; clear Heqm2 mp2.\n    remember (Z.pos mp3) as m3; clear Heqm3 mp3.\n    destruct EQ12 as [EQ12 | EQ12], EQ23 as [EQ23 | EQ23].\n    all: destruct EQ12 as [E12 M12], EQ23 as [E23 M23]; subst.\n    + left; split; [lia |].\n      rewrite <-Z.mul_assoc.\n      rewrite <-Z.pow_add_r; try lia.\n      replace (e1 - e2 + (e2 - e3)) with (e1 - e3) by lia.\n      reflexivity.\n    + destruct (Z.eq_dec e1 e3); subst.\n      * (* e1 = e3 *)\n        apply Z.mul_reg_r in M23.\n        subst; left; split; [lia |].\n        rewrite Z.sub_diag; lia.\n        pose proof (Z.pow_pos_nonneg 2 (e3 - e2)).\n        lia.\n      * destruct (Z_lt_le_dec e1 e3).\n        -- (* e1 < e3 *)\n          assert (E123 : e2 <= e1 < e3) by lia; clear E12 E23 n l.\n          right; split; [lia |].\n          apply f_equal with (f := fun x => Z.div x (2 ^ (e1 - e2))) in M23.\n\n          rewrite Z_div_mult in M23;\n            [| generalize (Z.pow_pos_nonneg 2 (e1 - e2)); lia].\n          subst.\n          rewrite Z.divide_div_mul_exact;\n            [| apply Z.pow_nonzero; lia | apply Zpow_divide; lia].\n          replace (e3 - e2) with ((e3 - e1) + (e1 - e2)) by lia.\n          rewrite Z.pow_add_r by lia.\n          rewrite Z.div_mul by (apply Z.pow_nonzero; lia).\n          reflexivity.\n        -- (* e3 < e1 *)\n          assert (E123: e2 <= e3 < e1) by lia; clear E12 E23 n l.\n          left; split; [lia |].\n          apply f_equal with (f := fun x => Z.div x (2 ^ (e3 - e2))) in M23.\n          rewrite Z_div_mult in M23;\n            [| generalize (Z.pow_pos_nonneg 2 (e3 - e2)); lia].\n          subst.\n          rewrite Z.divide_div_mul_exact;\n            [| apply Z.pow_nonzero; lia | apply Zpow_divide; lia].\n          replace (e1 - e2) with ((e1 - e3) + (e3 - e2)) by lia.\n          rewrite Z.pow_add_r by lia.\n          rewrite Z.div_mul by (apply Z.pow_nonzero; lia).\n          reflexivity.\n    + destruct (Z.eq_dec e1 e3); subst.\n      * (* e1 = e3 *)\n        left; split; [lia |].\n        rewrite Z.sub_diag; lia.\n      * destruct (Z_lt_le_dec e1 e3).\n        -- (* e1 < e3 *)\n          assert (E123 : e1 < e3 <= e2) by lia; clear E12 E23 n l.\n          right; split; [lia |].\n          rewrite <-Z.mul_assoc.\n          rewrite <-Z.pow_add_r by lia.\n          replace (e2 - e3 + (e3 - e1)) with (e2 - e1) by lia.\n          reflexivity.\n        -- (* e3 < e1 *)\n          assert (H: e3 < e1 <= e2) by lia; clear E12 E23 n l.\n          left; split; [lia |].\n          rewrite <-Z.mul_assoc.\n          rewrite <-Z.pow_add_r by lia.\n          replace (e2 - e1 + (e1 - e3)) with (e2 - e3) by lia.\n          reflexivity.\n    + right; split; [lia |].\n      rewrite <-Z.mul_assoc.\n      rewrite <-Z.pow_add_r; try lia.\n      replace (e3 - e2 + (e2 - e1)) with (e3 - e1) by lia.\n      reflexivity.\nQed.\n\nInstance fp_equiv_dec : DecidableEquivalence fp_equiv.\nProof.\n  unfold DecidableEquivalence, Decidable.decidable.\n  intros fp1 fp2.\n  unfold equiv, fp_equiv_def.\n  destruct fp1 as [mp1 e1], fp2 as [mp2 e2].\n  unfold FPnum, FPexp in *.\n  destruct (Z_le_dec e1 e2),\n           (Z_le_dec e2 e1),\n           (Z.eq_dec (Z.pos mp2) (Z.pos mp1 * 2 ^ (e1 - e2))),\n           (Z.eq_dec (Z.pos mp1) (Z.pos mp2 * 2 ^ (e2 - e1))).\n  all: auto.\n  all: right.\n  all: intros C.\n  all: destruct C; destruct H.\n  all: auto.\nQed.\n\nDefinition digits_m (fp : float_pair) : positive :=\n  Pos.size (FPnum fp).\n\nLemma exponent_unique (fp1 fp2 : float_pair) :\n  FPexp fp1 = FPexp fp2 ->\n  fp1 === fp2 ->\n  fp1 = fp2.\nProof.\n  destruct fp1 as [m1 e1], fp2 as [m2 e2].\n  cbn.\n  intros H E.\n  subst.\n  rewrite Z.sub_diag in *.\n  cbn in *.\n  repeat rewrite Pos.mul_1_r in *.\n  destruct E as [[H1 H2] | [H1 H2]].\n  all: inversion H2; subst; reflexivity.\nQed.\n\nLemma digits_m_unique (fp1 fp2 : float_pair) :\n  digits_m fp1 = digits_m fp2 ->\n  fp1 === fp2 ->\n  fp1 = fp2.\nProof.\n  intros.\n  destruct (Z.eq_dec (FPexp fp1) (FPexp fp2)) as [| NE];\n    [apply exponent_unique; assumption |].\n  destruct fp1 as [m1 e1], fp2 as [m2 e2].\n  cbn in *.\n  destruct H0 as [[E M] | [E M]].\n  -\n    remember (e1 - e2) as ed.\n    destruct ed; try lia.\n    replace e1 with (e2 + Z.pos p) in * by lia.\n    clear Heqed E NE.\n\n    break_match; inversion M; clear M.\n    rewrite <-Pos2Z.inj_pow in Heqz.\n    inversion Heqz; clear Heqz.\n    rewrite <-H2 in H1.\n    rewrite H1 in H.\n    rewrite pos_size_mul_pow_two in H.\n    lia.\n  -\n    remember (e2 - e1) as ed.\n    destruct ed; try lia.\n    replace e2 with (e1 + Z.pos p) in * by lia.\n    clear Heqed E NE.\n    \n    break_match; inversion M; clear M.\n    rewrite <-Pos2Z.inj_pow in Heqz.\n    inversion Heqz; clear Heqz.\n    rewrite <-H2 in H1.\n    rewrite H1 in H.\n    rewrite pos_size_mul_pow_two in H.\n    lia.\nQed.\n\nLemma equiv_neq_m (fp1 fp2 : float_pair) :\n  fp1 === fp2 ->\n  (FPnum fp1 < FPnum fp2)%positive ->\n  FPexp fp1 > FPexp fp2.\nProof.\n  intros.\n  destruct fp1 as (m1, e1), fp2 as (m2, e2).\n  cbn in *.\n  destruct H as [[E M] | [E M]].\n  -\n    break_match; inversion M.\n    destruct (e1 - e2) eqn:A; lia.\n  -\n    exfalso.\n    break_match; try lia.\n    inversion M.\n    rewrite H1 in H0.\n    clear - H0.\n    induction p; lia.\nQed.\n\nLemma equiv_neq_e (fp1 fp2 : float_pair) :\n  fp1 === fp2 ->\n  FPexp fp1 < FPexp fp2 ->\n  (FPnum fp1 > FPnum fp2)%positive.\nProof.\n  intros.\n  destruct fp1 as (m1, e1), fp2 as (m2, e2).\n  cbn in *.\n  destruct H as [[E M] | [E M]].\n  -\n    break_match; inversion M.\n    destruct (e1 - e2) eqn:A; lia.\n  -\n    break_match; inversion M.\n    enough (1 < 2 ^ (e2 - e1)) by nia.\n    destruct (e2 - e1) eqn:A; try lia.\n    clear.\n    rename p0 into p.\n    rewrite <-(Z.pow_1_l (Z.pos p)) by lia.\n    apply Z.pow_lt_mono_l; lia.\nQed.\n\nLemma equiv_neq_m_digits (fp1 fp2 : float_pair) :\n  fp1 === fp2 ->\n  (digits_m fp1 < digits_m fp2)%positive ->\n  FPexp fp1 > FPexp fp2.\nProof.\n  intros.\n  apply pos_size_monotone_inv in H0.\n  apply equiv_neq_m; assumption.\nQed.\n\nLemma equiv_neq_e_digits (fp1 fp2 : float_pair) :\n  fp1 === fp2 ->\n  FPexp fp1 < FPexp fp2 ->\n  (digits_m fp1 > digits_m fp2)%positive.\nProof.\n  intros.\n  destruct (Pos.eq_dec (digits_m fp1) (digits_m fp2))\n    as [EQ | NEQ].\n  -\n    exfalso.\n    apply digits_m_unique in EQ; [| assumption].\n    subst.\n    lia.\n  -\n    apply equiv_neq_e in H0; [| assumption].\n    apply Pos.gt_lt, Pos.lt_le_incl in H0.\n    apply pos_size_monotone in H0.\n    unfold digits_m in *.\n    lia.\nQed.\n", "meta": {"author": "zoickx", "repo": "float-cohorts", "sha": "524fe9ba2a992961c142eec6d2fd74e3869af4ce", "save_path": "github-repos/coq/zoickx-float-cohorts", "path": "github-repos/coq/zoickx-float-cohorts/float-cohorts-524fe9ba2a992961c142eec6d2fd74e3869af4ce/FloatPair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7682734110255354}}
{"text": "Require Import Arith.\nRequire Import Lia.\nFrom recross Require Import util regexp.\n\nFixpoint pumping_constant (re : regexp) : nat :=\n  match re with\n  | Void | Nil | Class [] => 1\n  | Char _ | Class _ => 2\n  | Star re => pumping_constant re\n  | Cat re1 re2 | Alt re1 re2 | And re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  end.\n\nLemma pumping_constant_ge_1 : forall re,\n  pumping_constant re >= 1.\nProof.\n  induction re; cbn; try destruct cs; intuition. Qed.\n\nLemma pumping_constant_ne_0 : forall re,\n  pumping_constant re <> 0.\nProof.\n  intros.\n  assert (pumping_constant re >= 1) by apply pumping_constant_ge_1.\n  lia. Qed.\n\nFixpoint napp {T} (l : list T) (n : nat) : list T :=\n  match n with\n  | S n' => l ++ napp l n'\n  | 0 => []\n  end.\n\nLemma napp_plus : forall T (l : list T) n m,\n  napp l (n + m) = napp l n ++ napp l m.\nProof.\n  induction n; cbn; intros.\n  - reflexivity.\n  - now rewrite IHn, app_assoc. Qed.\n\nLemma Star_napp : forall re n s1 s2,\n  s1 =~ re ->\n  s2 =~ Star re ->\n  napp s1 n ++ s2 =~ Star re.\nProof.\n  induction n; cbn; intros.\n  - assumption.\n  - rewrite <- app_assoc. now apply MStarApp, IHn. Qed.\n\nLemma add_le : forall n m p,\n  n + m <= p -> n <= p /\\ m <= p.\nProof. lia. Qed.\n\nLemma pumping : forall re 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 n, s1 ++ napp s2 n ++ s3 =~ re.\nProof.\n  intros re s H Hlen. induction H; cbn in *.\n  - invert Hlen.\n  - invert Hlen. invert H0.\n  - destruct cs.\n    + invert H.\n    + invert Hlen. invert H1.\n  - invert Hlen. apply pumping_constant_ne_0 in H0 as [].\n  - rewrite app_length in Hlen.\n    destruct (le_lt_dec (pumping_constant re) (length s1)) as [Hlen1 | Hlen1].\n    + apply IHre_match1 in Hlen1 as [s11 [s12 [s13 [? [? []]]]]]. subst.\n      exists s11, s12, (s13 ++ s2). repeat split.\n      * now rewrite <- (app_assoc s11 _ _), <- app_assoc.\n      * assumption.\n      * assumption.\n      * intros. rewrite (app_assoc _ _ s2), app_assoc. now apply MStarApp.\n    + destruct (Nat.eq_dec (length s1) 0) as [Heq | Heq].\n      * apply length_zero_iff_nil in Heq. subst. apply IHre_match2, Hlen.\n      * exists [], s1, s2. repeat split.\n        -- intro. destruct s1. now apply Heq. discriminate.\n        -- cbn. lia.\n        -- intros. now apply Star_napp.\n  - rewrite app_length in Hlen.\n    apply Nat.add_le_cases in Hlen as [Hlen1 | Hlen2].\n    + apply IHre_match1 in Hlen1 as [s11 [s12 [s13 [? [? []]]]]]. subst.\n      exists s11, s12, (s13 ++ s2). repeat split.\n      * now rewrite <- app_assoc, <- app_assoc.\n      * assumption.\n      * lia.\n      * intros. rewrite (app_assoc _ _ s2), app_assoc. now apply MCat.\n    + destruct (le_lt_dec (pumping_constant re1) (length s1)) as [Hlen1 | Hlen1].\n      * apply IHre_match1 in Hlen1 as [s11 [s12 [s13 [? [? []]]]]]. subst.\n        exists s11, s12, (s13 ++ s2). repeat split.\n        -- now repeat rewrite <- app_assoc.\n        -- assumption.\n        -- lia.\n        -- intros. rewrite (app_assoc _ _ s2), app_assoc. apply MCat.\n          ++ apply H4.\n          ++ assumption.\n      * apply IHre_match2 in Hlen2 as [s21 [s22 [s23 [? [? []]]]]]. subst.\n        exists (s1 ++ s21), s22, s23. repeat split.\n        -- now rewrite app_assoc.\n        -- assumption.\n        -- rewrite app_length. lia.\n        -- intros. rewrite <- app_assoc. now apply MCat.\n  - apply add_le in Hlen as [Hlen1 _].\n    apply IHre_match in Hlen1 as [s11 [s12 [s13 [? [? []]]]]]. subst.\n    exists s11, s12, s13. repeat split.\n    + assumption.\n    + lia.\n    + intros. now apply MAltL.\n  - apply add_le in Hlen as [_ Hlen2].\n    apply IHre_match in Hlen2 as [s21 [s22 [s23 [? [? []]]]]]. subst.\n    exists s21, s22, s23. repeat split.\n    + assumption.\n    + lia.\n    + intros. now apply MAltR.\n  - apply add_le in Hlen as [Hlen1 Hlen2].\n    apply IHre_match1 in Hlen1 as [s11 [s12 [s13 [? [? []]]]]].\n    apply IHre_match2 in Hlen2 as [s21 [s22 [s23 [? [? []]]]]].\n    exists s11, s12, s13. repeat split.\n    + assumption.\n    + assumption.\n    + lia.\n    + intros. apply MAnd. apply H4. admit.\nAdmitted.\n", "meta": {"author": "thaliaarchi", "repo": "recross-coq", "sha": "ad3b5adf270e0dc052238831e45b0d57515e1d94", "save_path": "github-repos/coq/thaliaarchi-recross-coq", "path": "github-repos/coq/thaliaarchi-recross-coq/recross-coq-ad3b5adf270e0dc052238831e45b0d57515e1d94/theories/regexp_pumping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7682601435152471}}
{"text": "(* This File contains the proof of Dilworth's Thm. We just combine the \n   Thms DilworthA and DilworthB from the File Finitedilworth_AB.v to prove\n   the statement of Dilworth's theorem. \n   Dilworth's decomposition theorem is the central result in our formalization. \n   It states that in any poset, the maximum size of an antichain is equal to \n   the minimum number of chains in any chain cover. In other words, if c(P) \n   represents the size of a smallest chain cover of P, then width(P)=c(P). \n   \n   We prove the following formal statement,\n\n  Theorem Dilworth: forall (P: FPO U), Dilworth_statement P.\n\n  where Dilworth_statement is defined as, \n\n  Definition Dilworth_statement:= fun (P: FPO U)=> forall (m n: nat), \n      (Is_width P m) -> (exists cover: Ensemble (Ensemble U), \n      (Is_a_smallest_chain_cover P cover) /\\ (cardinal _ cover n)) -> m=n.\n\n *)\n\nRequire Export PigeonHole.\nRequire Export BasicFacts.\nRequire Import FiniteDilworth_AB.\n\n\n\nSection Dilworth.\n \n  \n  Variable U: Type.\n\n\n\nInductive Is_width (P: FPO U) (n: nat) :Prop :=\n     W_cond: (exists la: Ensemble U, Is_largest_antichain_in P la /\\ cardinal _ la n) -> (Is_width P n).\n\n\n Definition Dilworth_statement:=  fun (P: FPO U)=>\n     forall (m n: nat), (Is_width P m) ->\n    (exists cover: Ensemble (Ensemble U), (Is_a_smallest_chain_cover P cover)/\\ (cardinal _ cover n)) ->\n    m=n.\n\n\n \n   Theorem Dilworth: forall (P: FPO U), Dilworth_statement P.\n\n   Proof. { intro P. unfold Dilworth_statement. intros m n. intros.\n            destruct H. destruct H as [la H]. destruct H0 as [cover H0].\n            \n            (* We prove that there is a chain cover of size m using DilworthB *)\n            assert (H1:  (exists (cv: Ensemble (Ensemble U)), Is_a_chain_cover P cv /\\\n                                                      cardinal _ cv m)).\n            { apply (DilworthB _ P ).  exists la.  auto. }\n            (* Hence n<= m, since n is the size of smallest chain cover *)\n            assert (H2: n<= m ).\n            { destruct H1 as [cv H1].\n             destruct H0 as [H_cover H0].\n             destruct H_cover . \n             apply H3 with ( cover0:= cv) ( sn:= n) (n:= m). tauto.\n            }\n            (* We prove n>=m or ~ (n<m) using DilworthA *)\n             assert (H3: n>= m).\n              { apply nat_P1. apply ( DilworthA _ P) with (cv:= cover) (a:= la).\n                apply H0.  apply H. tauto.  tauto. } \n           (* Hemce combining H2 and H3 we have m=n  *)\n           auto with arith.  }\n  Qed.\n            \n \n \n  \nEnd Dilworth.\n\n\n", "meta": {"author": "Abhishek-TIFR", "repo": "Dilworth-Hall-Erdos-Theorems", "sha": "74c0cde97967149b7f44b775fabdc7d909760ebd", "save_path": "github-repos/coq/Abhishek-TIFR-Dilworth-Hall-Erdos-Theorems", "path": "github-repos/coq/Abhishek-TIFR-Dilworth-Hall-Erdos-Theorems/Dilworth-Hall-Erdos-Theorems-74c0cde97967149b7f44b775fabdc7d909760ebd/FiniteDilworth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7682601420888404}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\n\nLocal Open Scope morphism_scope.\n\nSection Equalizer.\n  Context {C : Category} {a b : Obj} (f g : a –≻ b).\n\n  (** given two parallel arrows f,g : a -> b, their equalizer is an object e\n      together with an arrow eq : e -> a such that f ∘ eq = g ∘ eq such that\n      for any other object z and eqz : z -> a that we have f ∘ eqz = g ∘ eqz,\n      there is a unique arrow h : z -> e that makes the following diagram\n      commute:\n\n#\n<pre>\n\n          eqz\n/—————————————————\\     f\n|                 ↓  ———————>\nz ———–> e ——————> a          b\n   ∃!h      eq       ———–——–>\n                        g\n</pre>\n#\n *)\n\n  Local Open Scope morphism_scope.\n  \n  Record Equalizer : Type :=\n    {\n      equalizer : C;\n\n      equalizer_morph : equalizer –≻ a;\n\n      equalizer_morph_com : f ∘ equalizer_morph = g ∘ equalizer_morph;\n\n      equalizer_morph_ex (e' : Obj) (eqm : e' –≻ a) :\n        f ∘ eqm = g ∘ eqm → e' –≻ equalizer;\n\n      equalizer_morph_ex_com (e' : Obj) (eqm : e' –≻ a)\n                             (eqmc : f ∘ eqm = g ∘ eqm)\n      : equalizer_morph ∘ (equalizer_morph_ex e' eqm eqmc) = eqm;\n\n      equalizer_morph_unique (e' : Obj) (eqm : e' –≻ a)\n                             (com : f ∘ eqm = g ∘ eqm) (u u' : e' –≻ equalizer)\n      : equalizer_morph ∘ u = eqm → equalizer_morph ∘ u' = eqm → u = u'\n    }.\n\n  Coercion equalizer : Equalizer >-> Obj.\n  \n  (** Equalizers are unique up to isomorphism. *)\n  Theorem Equalizer_iso (e1 e2 : Equalizer) : (e1 ≃ e2)%isomorphism.\n  Proof.\n    apply (Build_Isomorphism _ _ _ (equalizer_morph_ex e2 _ (equalizer_morph e1)\n                                                       (equalizer_morph_com e1))\n                             ((equalizer_morph_ex e1 _ (equalizer_morph e2)\n                                                  (equalizer_morph_com e2))));\n    eapply equalizer_morph_unique; [| | simpl_ids; trivial| | |simpl_ids;\n                                      trivial]; try apply equalizer_morph_com;\n    rewrite <- assoc; repeat rewrite equalizer_morph_ex_com; auto.\n  Qed.\n\nEnd Equalizer.\n\nArguments equalizer_morph {_ _ _ _ _} _.\nArguments equalizer_morph_com {_ _ _ _ _} _.\nArguments equalizer_morph_ex {_ _ _ _ _} _ {_ _} _.\nArguments equalizer_morph_ex_com {_ _ _ _ _} _ {_ _} _.\nArguments equalizer_morph_unique {_ _ _ _ _} _ {_ _ _} _ _ _ _.\n\nArguments Equalizer _ {_ _} _ _, {_ _ _} _ _.\n\nDefinition Has_Equalizers (C : Category) : Type :=\n  ∀ (a b : C) (f g : a –≻ b), Equalizer f g.\n\nExisting Class Has_Equalizers.\n\n(** CoEqualizer is the dual of equalzier *)\nDefinition CoEqualizer {C : Category} := @Equalizer (C^op).\n\nArguments CoEqualizer _ {_ _} _ _, {_ _ _} _ _.\n\nDefinition Has_CoEqualizers (C : Category) : Type := Has_Equalizers (C^op).\n\nExisting Class Has_CoEqualizers.", "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/Equalizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7682601418479965}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_8_2.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral_ruler_compass}.\n\nLemma lemma_squareflip : \n   forall A B C D, \n   SQ A B C D ->\n   SQ B A D C.\nProof.\nintros.\nassert ((Cong A B C D /\\ Cong A B B C /\\ Cong A B D A /\\ Per D A B /\\ Per A B C /\\ Per B C D /\\ Per C D A)) by (conclude_def SQ ).\nassert (Cong B A D C) by (forward_using lemma_congruenceflip).\nassert (Cong B A A D) by (forward_using lemma_congruenceflip).\nassert (Cong B A C B) by (forward_using lemma_congruenceflip).\nassert (Per C B A) by (conclude lemma_8_2).\nassert (Per B A D) by (conclude lemma_8_2).\nassert (Per A D C) by (conclude lemma_8_2).\nassert (Per D C B) by (conclude lemma_8_2).\nassert (SQ B A D C) by (conclude_def SQ ).\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_squareflip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947455, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7682495472220261}}
{"text": "Lemma Identity :\n  forall A : Prop,\n    A -> A.\nProof.\n  intro A.\n  intro H_A.\n  apply H_A.\nQed.\n\n(* ASSUMPTIONS\n   ==========\n     GOAL\n*)\n\nLemma Identity' : \n  forall B : Prop,\n    B -> B.\nProof.\n  intro B.\n  intro H_B.\n  apply H_B.\nQed.\n\nLemma Identity'' : \n  forall C : Prop,\n    C -> C.\nProof.\n  intro C.\n  intro H_C.\n  apply H_C.\nQed.\n\n\n(* Freedom to choose names *)\nLemma Identity''' : \n  forall Z : Prop,\n    Z -> Z.\nProof.\n  intro Simon.\n  intro Hypothesis_about_Simon.\n  apply Hypothesis_about_Simon.\nQed.\n\nTheorem foobar : \n  forall A B : Prop,\n    A -> (B -> A).\nProof.\n  intro A.\n  intro B.\n  intro H_A.\n  intro H_B.\n  apply H_A.\nQed.\n\nRequire Import Arith.\n\nLemma comm_a : \n  forall a b c : nat,\n    (a + b) + c = c + (b + a).\nProof.\n  intros a b c.\n  rewrite -> (plus_comm a b). (* From the left *)\n  rewrite -> (plus_comm (b + a) c).\n  reflexivity.\n\n  Restart.\n\n  intros a b c.\n  rewrite -> (plus_comm (a + b) c).\n  rewrite -> (plus_comm a b).\n  reflexivity.\n\n  (* It can obviously be done in any way and from any direction *)\n\nQed.\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_35_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.882427857178614, "lm_q1q2_score": 0.7682392938780092}}
{"text": "Inductive day : Type :=\n  | lundi : day\n  | mardi : day\n  | mercredi : day\n  | jeudi : day\n  | vendredi : day\n  | samedi : day\n  | dimanche : day.\n\nDefinition next_day (d : day) : day := \n  match d with\n  | lundi => mardi\n  | mardi => mercredi\n  | mercredi => jeudi\n  | jeudi => vendredi\n  | vendredi => samedi\n  | samedi => dimanche\n  | dimanche => lundi\n  end.\n\nEval compute in (next_day vendredi).\nEval compute in (next_day (next_day samedi)).\n\nExample test_next_day:\n  next_day (next_day dimanche) = mardi.\n\nProof.\n  simpl. (* optional 'cause reflexivity seems to perform simpl automatically*)\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\nExample test_negb1 : negb true = false.\nProof. \n  reflexivity.\nQed.\n\nExample test_negb2 : negb false = true.\nProof. \n  reflexivity.\nQed.\n\nDefinition andb (a : bool) (b : bool) : bool :=\n  match a with\n  | true => b\n  | false => false\n  end.\n\nExample test_andb1 : andb false false = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb2 : andb true false = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb3 : andb false true = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb4 : andb true true = true.\nProof.\n  reflexivity.\nQed.\n\nDefinition orb (a : bool) (b : bool) : bool :=\n  match a with\n  | true => true\n  | false => b\n  end.\n\nExample test_orb1 : orb false false = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_orb2 : orb true false = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_orb3 : orb true false = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_ordb4 : orb true true = true.\nProof.\n  reflexivity.\nQed.\n\n(* Exercises *)\n\n(* nandb *)\nDefinition nandb (a : bool) (b : bool) : bool :=\n  negb (andb a b).\n\nExample test_nandb1: nandb true false = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_nandb2: nandb false false = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_nandb3: nandb false true = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_nandb4: nandb true true = false.\nProof.\n  reflexivity.\nQed.\n\n(* andb3 *)\n\nDefinition andb3 (a : bool) (b : bool) (c : bool) : bool :=\n  andb (andb a b) c.\n\nExample test_andb31: andb3 true true true = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb32: andb3 false true true = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb33: andb3 true false true = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb34: andb3 true true false = false.\nProof.\n  reflexivity.\nQed.\n\n(* Numbers *)\n\nModule MyNat.\n\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.\n\nEnd MyNat.\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 compute 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\nModule Playground1.\n\n  Fixpoint my_plus (a b : nat) : nat :=\n    match b with\n    | O => a\n    | S n => plus (S a) n\n    end.\n\n  (* from sf *)\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  Example test_plus510: plus 5 10 = 15.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Eval compute in (plus 3 2).\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  Example test_mult1: (mult 3 3) = 9.\n  Proof. reflexivity. Qed.\n\n  (* Exercises *)\n\n  Fixpoint factorial (n : nat) : nat :=\n    match n with\n    | O => S O\n    | S n' => mult n (factorial n')\n    end.\n\n  Example test_fact0 : factorial O = S O.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example test_fact3 : factorial 3 = 6.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example test_fact4 : factorial 4 = 4 * factorial 3.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Example test_fact5 : factorial 5 = mult 10 12.\n  Proof.\n    reflexivity.\n  Qed.\n\nEnd Playground1.\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\nDefinition blt_nat (n m : nat) : bool :=\n  ble_nat n (m - 1).\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\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n.\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\nTheorem plus_id_example : forall n m : nat,\n  n = m -> n + n = m + m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n(* Exercises *)\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_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\nFixpoint beq_nat (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | S _, O\n  | O, S _ => false\n  | S n', S m' => beq_nat n' m'\n  end.\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 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.\n  destruct n as [| n' ].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem identify_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall x : bool,\n  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\nTheorem neg_fn_applied_twice :\n  forall (f : bool -> bool),\n  (forall x : bool,\n  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  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\n(* mmh works but seems bad *)\nTheorem andb_eq_orb :\n  forall b c : bool,\n  andb b c = orb b c -> b = c.\nProof.\n  intros b.\n  intros c.\n  destruct b.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\nQed.\n", "meta": {"author": "eyyub", "repo": "coq-playground", "sha": "9c3e3c372e6f5ae0fe882e5e35ceee035f351fd4", "save_path": "github-repos/coq/eyyub-coq-playground", "path": "github-repos/coq/eyyub-coq-playground/coq-playground-9c3e3c372e6f5ae0fe882e5e35ceee035f351fd4/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.7682392833730701}}
{"text": "(**\n<<\n  This file contains parition function of quicksort as an exampl \n  that tries to use [fold_left_right_tup] from [FoldLib]. \n\n\n  [1] Bird, Richard. Introduction to Functional Programming using \n                 Haskell (2nd ed.). Prentice Hall. Harlow, England.\n                 1998. \n>>\n*)\n\n  Require Import Recdef.\n  Require Import homo.MyLib.\n  \n\n  (** ** Partitioning \n\n   *)\n\n  (** *** [partition_lt]\n\n      We use [partition] from the List library of Coq to \n      defined [partition_lt]. \n   *)\n  \n  Functional Scheme partition_ind := Induction for partition Sort Prop.\n  Definition f_part (p: nat) := fun x => Nat.ltb x p.\n\n  Definition partition_lt (p: nat) (l: list nat) := partition (f_part p) l.  \n  Functional Scheme partition_lt_ind := Induction for partition_lt Sort Prop.\n\n\n  (** *** [partition_wont_expand]\n  *)\n\n  Lemma partition_wont_expand: \n    forall l p m_lt m_ge, \n      (m_lt, m_ge) = partition_lt p l -> \n      length m_lt <= length l /\\ length m_ge <= length l.\n  Proof. \n    intros l p. \n    functional induction (partition (f_part p) l); intros * P.\n    - injection P; intros; subst; auto.\n    - unfold partition_lt in P.\n      simpl in P.\n      rewrite e0 in P.\n      rewrite e1 in P.\n      injection P; intros; subst. \n      simpl.\n      symmetry in e0.\n      apply IHp0 in e0.\n      intuition.\n    - unfold partition_lt in P.\n      simpl in P.\n      rewrite e0 in P.\n      rewrite e1 in P.\n      injection P; intros; subst. \n      simpl.\n      symmetry in e0.\n      apply IHp0 in e0.\n      intuition.\n  Qed. \n\n  (** *** [partition_lt_idempotent]\n   *)\n\n  Lemma partition_lt_idempotent: \n    forall l p m_lt m_ge, \n      (m_lt, m_ge) = partition_lt p l -> \n      (m_lt, []) = partition_lt p m_lt.\n  Proof. \n    intros l p.\n    functional induction (partition (f_part p) l); intros * P.\n    - injection P; intros; \n      now subst m_lt m_ge. \n    - unfold partition_lt in P.\n      simpl in P.\n      rewrite e0 in P.\n      rewrite e1 in P.\n      symmetry in e0.\n      apply IHp0 in e0.\n      injection P; intros; \n      subst m_lt m_ge. \n      simpl.\n      rewrite <- e0.\n      rewrite e1.\n      reflexivity.\n    - \n      simpl in P.\n      unfold partition_lt in P.\n      rewrite e0 in P.\n      rewrite e1 in P.\n      injection P; intros; \n      subst m_lt m_ge. \n      symmetry in e0.\n      apply IHp0 in e0.\n      apply e0.\n  Qed. \n\n\n  (** *** [partition__lt]\n   *)\n\n  Lemma partition__lt: \n    forall l p m_lt m_ge k, \n      (m_lt, m_ge) = partition_lt p l ->\n      In k m_lt -> \n      k < p.\n  Proof. \n    induction l as [| y ys] ; intros * P IN. \n    - inversion P; subst.\n      apply in_nil in IN; inversion IN.\n    - unfold partition_lt in P.\n      simpl in P.\n      name_term tpl (partition (f_part p) ys) Py. \n      destruct tpl as [lo hi].\n      rewrite <- Py in P.\n      unfold f_part in P.\n      remember (Nat.ltb y p) as r.\n      destruct r. \n      + \n        injection P; intros T1 T2.\n        inversion T1; clear T1.\n        subst. \n        symmetry in Heqr.\n        apply Nat.ltb_lt in Heqr.\n        destruct IN.\n        * now subst k.\n        * apply IHys with (m_lt:=lo) (m_ge:=hi); auto.\n      + injection P; intros; \n        subst lo.\n        apply IHys with (m_lt:=m_lt) (m_ge:=hi); auto.\n  Qed. \n  \n\n  \n  Lemma partition__le: \n    forall l p m_lt m_ge k, \n      (m_lt, m_ge) = partition_lt p l ->\n      In k m_ge -> \n      p <= k.\n  Proof. \n    induction l as [| y ys] ; intros * P IN. \n    - inversion P; subst.\n      apply in_nil in IN; inversion IN.\n    - unfold partition_lt in P.\n      simpl in P.\n      name_term tpl (partition (f_part p) ys) Py. \n      destruct tpl as [lo hi].\n      rewrite <- Py in P.\n      unfold f_part in P.\n      remember (Nat.ltb y p) as r.\n      destruct r. \n      + injection P; intros T1 T2.\n        subst hi; apply IHys with (k:=k) in Py; auto.\n      + symmetry in Heqr.\n        apply Nat.ltb_ge in Heqr.\n        injection P; intros T1 T2. \n        subst. \n        destruct IN.\n        * now subst k.\n        * apply IHys with (m_lt:=lo) (m_ge:=hi); auto.\n  Qed. \n\n  Require Import Sorting.Sorted Sorting.Permutation.\n  Definition join_parted (p:nat) (m_lt m_ge: list nat) :=\n    m_lt ++ [p] ++ m_ge.\n\n  Lemma partition_join_parted_permute: \n    forall m p m_lt m_ge, \n      (m_lt, m_ge) = partition_lt p m ->\n      Permutation (p::m) (m_lt++[p]++m_ge). \n  Proof. \n    intros * P.\n    apply Permutation_cons_app. \n    revert P.\n    revert m_ge m_lt p. \n    induction m as [| x xs]; intros * P. \n    - simpl in P. \n      injection P; intros; \n      subst.\n      apply perm_nil.\n    - simpl in P.\n      unfold partition_lt in P.\n      name_term tpl (partition (f_part p) xs) Tpl.\n      rewrite <- Tpl in P. \n      unfold f_part in P.\n      destruct tpl as [lo hi]. \n      remember (Nat.ltb x p) as r. \n      destruct r; injection P; intros; \n        subst m_lt m_ge. \n      + apply IHxs in Tpl. \n        simpl. \n        apply perm_skip. \n        apply Tpl. \n      + apply Permutation_cons_app. \n        apply IHxs in Tpl; auto. \n  Qed. \n  \n  \n  Definition partition_one (l: list nat) (p: nat) :=\n    (fix f (l: list nat) (z: list nat * list nat) :=\n       match l with \n         | [] => z \n         | x::xs => match z with\n                      | (lo, hi) => if Nat.ltb x p\n                                    then f xs (lo ++ [x], hi)\n                                    else f xs (lo, hi ++ [x])\n                    end\n       end)\n      l ([],[]). \n\n\n\n  Lemma f_fact_7:\n    forall {S1 S2 A B C D E F: Type}\n           (f: S1 -> S2 -> A -> B -> C -> D -> E -> F)\n           (bb:bool) s1 s2 f1 f2 f4 f5 pp1 pp2,\n      f s1 s2 f1 f2\n        (if bb then pp1 else pp2)\n        f4 f5\n      = \n      if bb then\n        f s1 s2 f1 f2 pp1 f4 f5\n      else\n        f s1 s2 f1 f2 pp2 f4 f5        \n  .\n  Proof.\n    intros. \n    now destruct bb.\n  Qed.    \n\n  \n\n\n  \n  \n  (** ** Quicksort\n\n   *)\n\n  (** *** [qsort]\n \n  *)\n \n Function qsort (m: list nat) {measure length m}:=\n    match m with\n      | [] => []\n      | x::xs => let (m_lt, m_ge) := partition_lt x xs in\n                 (qsort m_lt) ++ [x] ++ (qsort m_ge)\n    end. \n  Proof. \n    -\n      intros * M * P.\n      symmetry in P.\n      apply partition_wont_expand in P.\n      simpl.\n      intuition.\n    - intros * M * P.\n      symmetry in P.\n      apply partition_wont_expand in P.\n      simpl.\n      intuition.\n   Qed.       \n\n\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/QSort/QSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8705972566572503, "lm_q1q2_score": 0.7682392797331904}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Logic.\nRequire Export Basics.\nRequire Export List.\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: *)\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  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.  Qed.\n\n\n(** **** Exercise: 1 star (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros n. simpl. \n  rewrite double_plus.\n  induction n.\n  - simpl. apply ev_0.\n  - simpl. rewrite <- plus_n_Sm. apply ev_SS. apply IHn.\nQed.\n\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.\n  intros n E.\n  inversion E as [| n' E'].\n  inversion E' as [| n'' E''].\n  apply E''.\nQed.\n\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.\n  intros E. simpl. inversion E. inversion H0. inversion H2.\nQed.\n\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'). 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.\n  intros n m H1 H2.\n  induction H1 as [|n' H1' IH1].\n    - simpl. apply H2.\n    - simpl. apply ev_SS. apply IH1.\nQed.\n  \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.) *)\nRequire Import Basics.\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\nintros n. split.\n  - intros H1. induction H1 as [| |n' H1' IH1].\n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum. \n      { apply IHIH1. }\n      { apply IHev'1. }\n  - intros H1. induction H1 as [|n' H1' IH1].\n    + apply ev'_0.\n    + assert (H3: S (S n') = 2 + n').\n      { induction n'.\n        - simpl. reflexivity.\n        - simpl. reflexivity. }\n      rewrite H3. apply ev'_sum.\n       { apply ev'_2. }\n        { apply IH1. }\nQed. \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  intros n m H1 H2.\n  induction H2.\n  - simpl in H1. apply H1.\n  - apply IHev. inversion H1. apply H0.\nQed.\n\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 plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. rewrite <- plus_n_O. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: plus_comm *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite plus_comm.\n  rewrite <- plus_assoc.\n  assert (p + n = n + p).\n  { rewrite <- plus_comm. reflexivity. }\n  rewrite <- H. simpl.  reflexivity. Qed.\n\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n\n  intros n m p H1 H2.\n  apply (ev_sum (n + m) (n + p)) in H1 as H1'. \n  (* - rewrite plus_assoc <- in H1'. rewrite <- plus_assoc in H1'. *)\n  (* FILL IN HERE *) Admitted.\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.\n  intros m n o H1 H2.\n  induction H2.\n  - apply H1.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n.\n  - apply le_n.\n  - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed. \n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m H.\n  inversion H.\n  - apply le_n.\n  - apply (le_trans n (S n) m).\n    + apply le_S. apply le_n.\n    + apply H1.\nQed. \n\nTheorem plus_n_Sm_v2 : forall n m : nat,\n  S (n + m) = (S n) + m.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - (* n = 0 *)\n    simpl. reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n(* GRADE_THEOREM 0.5: plus_n_Sm *)\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros.\n  induction a.\n  - simpl. apply O_le_n.\n  - apply (n_le_m__Sn_le_Sm a (a + b)) in IHa. rewrite plus_n_Sm_v2 in IHa. apply IHa.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n  intros.\n  split.\n  - rewrite plus_n_Sm_v2 in H. apply (le_trans (S n1) (S n1 + n2) m).\n    + apply (le_plus_l (S n1) n2).\n    + apply H.\n  - rewrite plus_n_Sm in H. apply (le_trans (S n2) (n1 + ( S n2)) m).\n    + rewrite plus_comm. apply (le_plus_l (S n2) n1).\n    + apply H.\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\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\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  intros n.\n  induction n.\n  - intros m H. apply O_le_n.\n  - intros m H. induction m.\n    + inversion H.\n    + inversion H. apply n_le_m__Sn_le_Sm. apply IHn. apply 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  intros n m H. generalize dependent n. induction m.\n\nAdmitted.\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  intros n m o H1 H2.\n  apply leb_correct. \n  apply leb_complete in H1. \n  apply leb_complete in H2.\n  apply (le_trans n m). \n  apply H1.\n  apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  split.\n  - apply leb_complete.\n  - apply leb_correct.\nQed.\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.\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, 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(* ================================================================= *)\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 represeneted\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\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. inversion 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, optional (app_ne)  *)\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 H2.\n  - intros [ H | H ].\n    + apply MUnionL. apply H.\n    + apply MUnionR. apply H. \nQed.\n\n(** **** Exercise: 3 stars, optional (star_ne)  *)\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, optional (match_eps)  *)\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, optional (match_eps_refl)  *)\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\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, optional (derive)  *)\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, optional (derive_corr)  *)\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\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, optional (regex_match)  *)\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, optional (regex_refl)  *)\n(** Finally, prove that [regex_match] in fact matches regexes.\n\n    Hint: if your definition of [regex_match] applies [match_eps] to\n    regex [re], then a natural proof applies [match_eps_refl] to [re]\n    and destructs the result to generate cases in which you may assume\n    that [re] does or does not match the empty string.\n\n    Hint: if your definition of [regex_match] applies [derive] to\n    character [x] and regex [re], then a natural proof applies\n    [derive_corr] to [x] and [re] to prove that [x :: s =~ re] given\n    [s =~ derive x re], and vice versa. *)\nTheorem regex_refl : matches_regex regex_match.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n", "meta": {"author": "dandougherty", "repo": "mqpCoq2018", "sha": "bc8018a301e4ad2a8ea88b1381715b4e2084bdcd", "save_path": "github-repos/coq/dandougherty-mqpCoq2018", "path": "github-repos/coq/dandougherty-mqpCoq2018/mqpCoq2018-bc8018a301e4ad2a8ea88b1381715b4e2084bdcd/Spiros_Chapters/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8705972549785201, "lm_q1q2_score": 0.7682392782518321}}
{"text": "Require Import Arith.\nRequire Import \"unfold_tactic\".\n\n\nFixpoint trav (P : nat -> Prop) \n         (b : P 0) \n         (f : forall k, P k -> P (S k)) \n         (n : nat) :=\n  match n return P n with\n    | 0 => b\n    | S n' => f n' (trav P b f n')\n  end.\nCheck trav.\n\nCheck Prop.\n\nDefinition specification_of_foo (foo : nat -> nat) :=\n  forall n : nat,\n    foo (2 * n) = n.\n\nTheorem there_is_only_one_foo :\n  forall f g : nat -> nat,\n    specification_of_foo f ->\n    specification_of_foo g ->\n    forall x : nat,\n      f (x) = g (x).\nProof.\n  intros f g.\n  unfold specification_of_foo.\n  intros Hf Hg.\n  intro x.\n  rewrite -> Hf.\n  rewrite -> Hg.\n  reflexivity.\nQed.\n\nLemma unfold_add_v1_bc :\n  forall j : nat,\n    plus 0 j = j.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_add_v1_ic :\n  forall i' j : nat,\n    plus (S i') j = S (plus i' j).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic plus.\nQed.\n\n\n(*\nLemma unfold_add_v2_ic :\n  forall i' j : nat,\n    plus (S i') j = plus i' (S j).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  intros i' j.\n  rewrite -> (unfold_add_v1_ic i' j).\n  rewrite -> (plus_comm i' (S j)).\n  rewrite -> (unfold_add_v1_ic j i').\n  rewrite -> (plus_comm j i').\n  reflexivity.\nQed.\n*)\n\n\n(* A useful lemma: *)\n(*\nProposition add_v2_ic_right :\n  forall i j : nat,\n    plus i (S j) = S (plus i j).\nProof.\n\n  intro i.\n  induction i as [ | i' IHi'].\n\n  intro j.\n  rewrite -> unfold_add_v1_bc.\n  rewrite -> unfold_add_v1_bc.\n  reflexivity.\n\n  intro j.\n  rewrite -> unfold_add_v2_ic.\n  rewrite -> unfold_add_v2_ic.\n  rewrite -> (IHi' (S j)).\n  reflexivity.\nQed.\n*)\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  rewrite -> (unfold_add_v1_ic).\n  rewrite -> (plus_0_l (S n')).\n  reflexivity.\nQed.\n\n\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 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\nDefinition fac_co_help (x : nat) : nat * nat :=\n  (x, fac x).\n\nCompute(fac_co_help 3).\n\nLemma negb_negb_b_equals_b : \n  forall b : bool,\n    negb (negb b) = b.\nProof.\n  intro b.\n  case b.\n  unfold negb.\n  reflexivity.\n  unfold negb.\n  reflexivity.\nQed.\n\n\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/practise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7681121515409307}}
{"text": "Require Import ZArith.\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){struct t} : bool :=\n   match t with\n   | Z_leaf => false\n   | Z_bnode z1  t1 t2 => if Zeq_bool z z1\n                          then  true\n                          else  if value_present z t1 \n                                then true \n                                else value_present z t2\n   end.\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/structinduct/SRC/value_present.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7680940523834127}}
{"text": "Require Export Basics.\nRequire Export TacticUtil.\n\nTheorem andb_true_elim1 : forall b c : bool, andb b c = true -> b = true.\nProof. intros b c H; destruct b.\nCase \"b = true\".  reflexivity.\nCase \"b = false\". rewrite <- H; reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool, andb b c = true -> c = true.\nProof. intros b c H; destruct c.\nCase \"c = true\".  reflexivity.\nCase \"c = false\". destruct b; rewrite <- H; reflexivity.\nQed.\n\nTheorem plus_0_r : forall n : nat, n + 0 = n.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; reflexivity.\nQed.\n\nTheorem minus_diag : forall n : nat, minus n n = 0.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; apply IHn'.\nQed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; apply IHn'.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat, S (n + m) = n + (S m).\nProof. intros n m; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof. intros n m; induction n as [| n'].\nCase \"n = 0\".    rewrite plus_0_r; reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; rewrite plus_n_Sm; reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat, n + (m + p) = (n + m) + p.\nProof. intros n m p; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S 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, double n = n + n.\nProof. intros n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; rewrite plus_n_Sm; reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat, (0 + n) * m = n * m.\nProof. intros n m; assert (0 + n = n) as H.\nCase \"H: 0 + n = n\". reflexivity.\nrewrite H; reflexivity.\nQed.\n\nTheorem plus_rearrange : forall n m p q : nat, (n + m) + (p + q) = (m + n) + (p + q).\nProof. intros n m p q; assert (n + m = m + n) as H.\nCase \"H: n + m = m + n\". apply plus_comm.\nrewrite H; reflexivity.\nQed.\n\nTheorem plus_swap : forall n m p : nat, n + (m + p) = m + (n + p).\nProof. intros n m p; assert (n + m = m + n) as H.\nCase \"H: n + m = m + n\". apply plus_comm.\nrewrite plus_assoc; rewrite plus_assoc; rewrite H; reflexivity.\nQed.\n\nTheorem mult_iden_r : forall n : nat, n * 1 = n.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; reflexivity.\nQed.\n\nLemma mult_S_r : forall n m : nat, n * S m = n + n * m.\nProof. intros n m; induction n as [| n']. \nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl. rewrite plus_swap; rewrite IHn'; reflexivity.\nQed.\n\nTheorem mult_comm : forall n m : nat, n * m = m * n.\nProof. intros m n; induction n as [| n'].\nCase \"n = 0\".    simpl; apply mult_0_r.\nCase \"n = S n'\". simpl; rewrite mult_S_r; rewrite IHn'; reflexivity.\nQed.\n\nLemma evenb_SS : forall n : nat, evenb (S (S n)) = evenb n.\nProof. reflexivity.\nQed.\n\nTheorem evenb_n__oddb_Sn : forall n : nat, evenb n = negb (evenb (S n)).\nProof. intros n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". rewrite evenb_SS; rewrite IHn'; rewrite negb_involutive; reflexivity.\nQed.\n\nTheorem ble_nat_refl : forall n : nat, ble_nat n n = true.\nProof. intros n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; exact IHn'.\nQed.\n\nTheorem zero_nbeq_S : forall n : nat, beq_nat O (S n) = false.\nProof. reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool, andb b false = false.\nProof. destruct b; reflexivity. Qed.\n\nTheorem plus_ble_compat_l :\n  forall n m p : nat, ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof. intros n m p H; induction p as [| p'].\nCase \"p = 0\".    simpl; exact H.\nCase \"p = S p'\". simpl; exact IHp'.\nQed.\n\nTheorem S_nbeq_0 : forall n : nat, beq_nat (S n) 0 = false.\nProof. reflexivity. Qed.\n\nTheorem mult_iden_l : forall n : nat, 1 * n = n.\nProof. intro n; simpl; rewrite plus_0_r; reflexivity.\nQed.\n\nTheorem all3_spec : forall b c : bool, orb (andb b c) (orb (negb b) (negb c)) = true.\nProof. intros b c; destruct b; destruct c; reflexivity.\nQed.\n\nTheorem mult_plus_dist_r : forall n m p : nat, (n + m) * p = n * p + m * p.\nProof. intros n m p; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite IHn'; apply plus_assoc; reflexivity.\nQed.\n\nTheorem mult_assoc : forall n m p : nat, n * (m * p) = (n * m) * p.\nProof. intros n m p; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl. rewrite mult_plus_dist_r. rewrite IHn'; reflexivity.\nQed.\n\nTheorem beq_nat_refl : forall n : nat, true = beq_nat n n.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; exact IHn'.\nQed.\n\nTheorem plus_swap' : forall n m p : nat, n + (m + p) = m + (n + p).\nProof. intros n m p; repeat rewrite plus_assoc; replace (n + m) with (m + n). reflexivity.\nCase \"hypothesis from replace\". apply plus_comm.\nQed.\n\nTheorem bin_to_nat_past_S : forall n : bin, bin_to_nat (bin_S n) = S (bin_to_nat n).\nProof. intro n; induction n as [| n' | n'].\nCase \"n = ZZ\".    reflexivity.\nCase \"n = EE n'\". reflexivity.\nCase \"n = OO n'\". simpl; repeat rewrite plus_0_r; repeat rewrite IHn';\n  rewrite plus_n_Sm; reflexivity.\nQed.\n\nTheorem nat_to_bin_past_S : forall n : nat, nat_to_bin (S n) = bin_S (nat_to_bin n).\nProof. reflexivity. Qed.\n\nTheorem nat_bin_nat_roundtrip : forall n : nat, bin_to_nat (nat_to_bin n) = n.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; rewrite bin_to_nat_past_S; rewrite IHn'; reflexivity.\nQed.\n\n(* Used in normalize; double its argument, collapsing duplicate EE around ZZ. *)\nDefinition normal_double (n : bin) : bin :=\n  match n with\n    | ZZ    => ZZ\n    | EE n' => EE n\n    | OO n' => EE n\n  end.\n\nTheorem normal_double_correct :\n  forall n : bin, bin_to_nat (normal_double n) = bin_to_nat n + bin_to_nat n.\nProof. intro n; destruct n as [| n' | n'].\nCase \"n = ZZ\".    reflexivity.\nCase \"n = EE n'\". simpl; repeat rewrite plus_0_r; reflexivity.\nCase \"n = OO n'\". simpl; repeat rewrite plus_0_r; reflexivity.\nQed.\n\n(* Yield a unique representation of n, removing the redundancy that comes from shifting\n * zero left over and over (that is, EE (EE (EE ... ZZ))). *)\nFixpoint normalize (n : bin) : bin :=\n  match n with\n    | ZZ    => ZZ\n    | EE n' => normal_double (normalize n')\n    | OO n' => OO (normalize n')\n  end.\n\nTheorem normalize_correct : forall n : bin, bin_to_nat (normalize n) = bin_to_nat n.\nProof. intro n; induction n as [| n' | n'].\nCase \"n = ZZ\".    reflexivity.\nCase \"n = EE n'\". simpl; rewrite normal_double_correct; rewrite IHn'; rewrite plus_0_r;\n                  reflexivity.\nCase \"n = OO n'\". simpl; rewrite IHn'; reflexivity.\nQed.\n\nLemma normal_double_bin_S :\n  forall n : bin, normal_double (bin_S n) = bin_S (bin_S (normal_double n)).\nProof. intro n; induction n as [| n' | n']; reflexivity.\nQed.\n\nLemma nat_bin_normal_double :\n  forall n : nat, nat_to_bin (n + n) = normal_double (nat_to_bin n).\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". rewrite <- plus_n_Sm; simpl; rewrite IHn'; rewrite normal_double_bin_S;\n                 reflexivity.\nQed.\n\nLemma nat_bin_double_S : forall n : nat, nat_to_bin (S n + S n) = EE (nat_to_bin (S n)).\nProof. intro n; induction n as [| n'].\nCase \"n = 0\". reflexivity.\nCase \"n = S n'\". replace (S (S n') + S (S n')) with (S (S (S n' + S n'))).\n  rewrite nat_to_bin_past_S; rewrite nat_to_bin_past_S; rewrite nat_to_bin_past_S;\n  rewrite IHn'; reflexivity.\n  SCase \"Proof of replace assertion\".\n  rewrite plus_n_Sm; reflexivity.\nQed.\n\nTheorem bin_nat_bin_normalized : forall n : bin, nat_to_bin (bin_to_nat n) = normalize n.\nProof. intro n; induction n as [| n' | n'].\nCase \"n = ZZ\".    reflexivity.\nCase \"n = EE n'\". simpl; rewrite plus_0_r; rewrite <- IHn'; rewrite nat_bin_normal_double;\n                  reflexivity.\nCase \"n = OO n'\". simpl; rewrite plus_0_r; rewrite <- IHn'; simpl.\n  cut (forall m : nat, bin_S (nat_to_bin (m + m)) = OO (nat_to_bin m)).\n  intro H; apply H.\n  SCase \"Proof of assertion\". intro m; destruct m as [| m'].\n    SSCase \"m = 0\". reflexivity.\n    SSCase \"m = S m'\". rewrite nat_bin_double_S; reflexivity.\nQed.\n\nDefinition even_bin (n : bin) : bool :=\n  match n with\n    | ZZ   => true\n    | EE _ => true\n    | OO _ => false\nend.\n\nTheorem even_bin_SS : forall n : bin, even_bin (bin_S (bin_S n)) = even_bin n.\nProof. intro n; induction n as [| n' | n']; reflexivity. Qed.\n\nTheorem induction_by_2 :\n  forall (P : forall n : nat, Prop),\n    P 0 -> P 1 -> (forall n : nat, P n -> P (S (S n))) -> forall n : nat, P n.\nProof. intros P P0 P1 IHP; cut (forall m : nat, P m /\\ P (S m)).\nCase \"Proof from strengthened conclusion\". intro H; apply H.\nCase \"Proof of strengthened conclusion\". intro m; induction m as [| m'].\nSCase \"m = 0\". split; [exact P0 | exact P1].\nSCase \"m = S m'\". split; [| apply IHP]; apply IHm'.\nQed.\n\nTheorem even_bin_correct_even : forall n : nat, even_bin (nat_to_bin n) = evenb n.\nProof. apply induction_by_2.\nCase \"n = 0\". reflexivity.\nCase \"n = 1\". reflexivity.\nCase \"n = S (S n)\". intros n IHn; repeat rewrite nat_to_bin_past_S;\n                    rewrite evenb_SS; rewrite even_bin_SS; apply IHn.\nQed.\n", "meta": {"author": "ystael", "repo": "sf", "sha": "fc304885bf687301521a0b3673743ec840986be4", "save_path": "github-repos/coq/ystael-sf", "path": "github-repos/coq/ystael-sf/sf-fc304885bf687301521a0b3673743ec840986be4/coq/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.7680769935703118}}
{"text": "Set Warnings \"-notation-overridden-parsing\".\nAdd LoadPath \"/Users/lubis/Documents/study/software_foundations\".\nRequire Export Tactics.\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\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_inj: injective S.\nProof.\n  unfold injective. intros n m H.\n  inversion H. reflexivity.\nQed.\n\nCheck @eq.\n\nExample and_example: 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma and_intro:\n  forall A B: Prop, \n  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\n(* Page 115 Exercise *)\n\nExample and_exercise:\n  forall n m: nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m eq. apply and_intro.\n  - induction n as [| n' IHn'].\n    + reflexivity.\n    + discriminate.\n  - induction m as [| m' IHm'].\n    + reflexivity.\n    + rewrite plus_comm in eq. inversion eq.\nQed.\n\nExample and_exercise':\n  forall n m: nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m eq. apply and_intro.\n  - destruct n as [| n'].\n    + reflexivity.\n    + discriminate.\n  - destruct m as [| m'].\n    + reflexivity.\n    + rewrite plus_comm in eq. discriminate.\nQed.\n\n(* Exercise Ends *)\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 [HA HB].\n  rewrite HA. rewrite HB.\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. rewrite Hm. reflexivity.\nQed.\n\nLemma proj1:\n  forall P Q: Prop, P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.\nQed.\n\n(* Page 117 Exercise *)\n\nLemma proj2:\n  forall P Q: Prop, P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ.\nQed.\n\n(* Exercise Ends *)\n\nTheorem and_commut:\n  forall P Q: Prop, P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split. \n  - apply HQ.\n  - apply HP.\nQed.\n\n(* Page 118 Exercise *) \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(* Exercise Ends *)\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  intros n. destruct n as [| n'].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(* Page 118 Exercise *)\n\nLemma mult_eq_0:\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m eq.\n  destruct n as [| n'].\n  - left. reflexivity.\n  - right. destruct m as [| m'].\n    + reflexivity.\n    + discriminate.\nQed.\n\nTheorem or_commut:\n  forall P Q: Prop, P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q [HP | HQ].\n  - right. apply HP.\n  - left. apply HQ.\nQed.\n\n(* Exercise Ends *)\n\nModule MyNot.\n\nDefinition not (P: Prop) :=  P -> False.\n\nNotation \"~ x\" := (not x): type_scope.\n\nEnd MyNot.\n\n(* Page 119 Exercise *)\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  ~ P -> (forall Q:Prop, P -> Q).\nProof.\n  intros P NP. unfold not in NP.\n  intros Q. intros HP. apply NP in HP.\n  destruct HP.\nQed.\n\n(* Exercise Ends *)\n\nTheorem zero_not_one: 0 <> 1.\nProof.\n  unfold not. intros contra.\n  discriminate.\nQed.\n\nTheorem not_False:\n  ~ False.\nProof.\n  unfold not. intros H. destruct H.\nQed.\n\nTheorem contradiction_implies_anything:\n  forall P Q: Prop, (P /\\ ~ P) -> Q.\nProof.\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.\nQed.\n\nTheorem double_neg: forall P: Prop,\n  P -> ~(~ P).\nProof.\n  intros P H. unfold not. intros G.\n  apply G. apply H.\nQed.\n\n(* Page 120~ Exercise *)\n\nTheorem contrapositive: forall P Q: Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q HA HNQ.\n  unfold not in HNQ. unfold not.\n  intros H. apply HA in H. apply HNQ in H.\n  destruct H.\nQed.\n\nTheorem not_both_true_and_false:\n  forall P: Prop, ~ (P /\\ ~P).\nProof.\n  intros P. unfold not.\n  intros [HP HN].\n  apply HN in HP.\n  destruct HP.\nQed.\n\n(* Exercise Ends *)\n\nTheorem not_true_is_false:\n  forall b: bool, b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b.\n  - unfold not in H. exfalso. apply H. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem not_true_is_false':\n  forall b: bool, b <> true -> b = false.\nProof.\n  intros b H. destruct b.\n  - unfold not in H. apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - reflexivity.\nQed.\n\nLemma True_is_true: True.\nProof.\n  apply I.\nQed.\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) : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym:\n  forall P Q: Prop, (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q.  intros [HPQ HQP].\n  split.\n  - apply HQP.\n  - apply HPQ.\nQed.\n\nLemma not_true_iff_false:\n  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\n(* Page 122 Exercise *)\n\nTheorem iff_refl:\n  forall P: Prop, P <-> P.\nProof.\n  intros P. split.\n  - intros H. apply H.\n  - intros H. apply H.\nQed.\n\nTheorem iff_trans:\n  forall P Q R: Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R. intros H1 H2.\n  destruct H1. destruct H2. split.\n  - intros H3. apply H1. apply H. apply H3.\n  - intros H3. apply H0. 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  - intros [HP | HQR].\n    + split.\n      * left. apply HP.\n      * left. apply HP.\n    + destruct HQR. split.\n      * right. apply H.\n      * right. apply H0.\n  - intros [HPQ HPR].\n    destruct HPQ.\n    + left. apply H.\n    + destruct HPR.\n      * left. apply H0.\n      * right. split. apply H. apply H0.\nQed.\n\n(* Exercise Ends *)\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_0: forall n m,\n  n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc: forall P Q R: Prop,\n  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\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) -> (exists o, n = 2 + o).\nProof.\n  intros n. intros [m Hm]. exists (2 + m).\n  apply Hm.\nQed.\n\n(* Page 124 Exercise *)\n\nTheorem dist_not_exists:\n  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. intros H'.\n  destruct H' as [x E]. apply E. apply H.\nQed.\n\nTheorem dist_exists_or:\n  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 H. destruct H. destruct H.\n    + left. exists x. apply H.\n    + right. exists x. apply H.\n  - intros H. destruct H.\n    + destruct H. exists x. left. apply H.\n    + destruct H. exists x. right. apply H.\nQed.\n\n(* Exercise Ends *)\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] -> 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.\n  - exfalso. apply 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 A B f l x.\n  induction l as [| x' l' IHl'].\n  - simpl. intros H. apply H.\n  - simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(* Page 126~ Exercise *)\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 A B f l y. split.\n  - induction l as [| n' l' IHl'].\n    + simpl. intros HF. exfalso. apply HF.\n    + simpl. intros H. destruct H.\n      * exists n'. split.\n        { apply H. }\n        { left. reflexivity. }\n      * apply IHl' in H. destruct H.\n        exists x. destruct H. split.\n        { apply H. }\n        { right. apply H0. }\n  - induction l as [| n' l' IHl'].\n    + simpl. intros H. destruct H. \n      destruct H. apply H0.\n    + simpl. intros H. destruct H. destruct H.\n      destruct H0.\n      * rewrite H0. left. apply H.\n      * right. apply IHl'. exists x. 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 A l l' a. split.\n  - induction l as [| n t IHt].\n    + simpl. intros H. right. apply H.\n    + simpl. intros H. destruct H.\n      * left. left. apply H.\n      * apply IHt in H. destruct H.\n        { left. right. apply H. }\n        { right. apply H. }\n  - induction l as [| n t IHt].\n    + simpl. intros H. destruct H.\n      * exfalso. apply H.\n      * apply H.\n    + simpl. intros [[H | H] | H]. \n      * left. apply H.\n      * right. apply IHt. left. apply H.\n      * right. apply IHt. 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), (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P. split.\n  - induction l as [| n' l' IHl'].\n    + intros H. simpl. reflexivity.\n    + simpl. intros H. split.\n      * apply H. left. reflexivity.\n      * apply IHl'. intros x. intros H'. apply H.\n        right. apply H'.\n  - induction l as [| n' l' IHl'].\n    + simpl. intros H1. intros H2. intros H3. \n      destruct H3.\n    + simpl. intros [H1 H2].\n      intros x. intros H. destruct H.\n      * rewrite H in H1. apply H1.\n      * apply IHl'. \n        { apply H2. }\n        { apply H. }\nQed.\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\nTheorem combine_odd_even_intro:\n  forall (Podd Peven: nat -> Prop) (n: nat),\n  (oddb n = true -> Podd n) -> \n  (oddb n = false ->\n  Peven n) -> combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n. intros H1 H2.\n  unfold combine_odd_even. destruct (oddb n) eqn:En.\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 -> \n  Podd n.\nProof.\n  intros Podd Peven n. intros H1 H2.\n  unfold combine_odd_even in H1.\n  rewrite H2 in H1. apply H1.\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. intros H1 H2.\n  unfold combine_odd_even in H1. rewrite H2 in H1.\n  apply H1.\nQed.\n\n(* Exercise Ends *)\n\nCheck plus_comm.\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. 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. intros Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\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 nat 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 _ _ _ H).\nQed.\n\n\nExample lemma_application_ex:\n  forall {n: nat} {ns: list nat}, In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H) as [m [Hm _]].\nAbort.\n\nExample function_equality_ex1:\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2:\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof. Abort.\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 x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n\n(* Page 132 Exercise *)\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\n(* Exercise Ends *)\n\n\nTheorem evenb_double: forall k,\n  evenb (double k) = true.\nProof.\n  intros k. induction k as [| k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7679457071149641}}
{"text": "Require Import ZArith.\nRequire Import List.\n\n\n\n(* Arithmetic expressions with variables *)\n\nDefinition aArg := nat.\n\nDefinition mkAArg n : aArg := n.\nDefinition aArgName (a : aArg) := a.\n\nInductive aBop : Set :=\n| AAdd : aBop\n| ASub : aBop\n| AMul : aBop.\n\nInductive aExp : Set :=\n| ArgExp : aArg -> aExp\n| ABinop : aBop -> aExp -> aExp -> aExp.\n\nDefinition aMap := aArg -> Z.\n\nOpen Scope Z_scope.\n\nFixpoint aExpEval (e : aExp) (m : aMap) : Z :=\n  match e with\n    | ArgExp a => m a\n    | ABinop AAdd l r =>\n      (aExpEval l m) + (aExpEval r m)\n    | ABinop ASub l r =>\n      (aExpEval l m) - (aExpEval r m)\n    | ABinop AMul l r =>\n      (aExpEval l m) * (aExpEval r m)\n  end.\n", "meta": {"author": "dillonhuff", "repo": "CertArith3", "sha": "a21b46002df3346a024c11131095c86e8aa5666f", "save_path": "github-repos/coq/dillonhuff-CertArith3", "path": "github-repos/coq/dillonhuff-CertArith3/CertArith3-a21b46002df3346a024c11131095c86e8aa5666f/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075711974105, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7679415351647744}}
{"text": "Theorem both_and : (forall A B : Prop, A -> B -> A /\\ B).\nProof.\n  intros A B.\n  intros proof_A proof_B.\n  refine (conj _ _).\n    exact proof_A.\n    exact proof_B.\nQed.\n\nTheorem and_commutes : (forall A B : Prop, A /\\ B -> B /\\ A).\nProof.\n  intros A B.\n  intros proof_A_and_B.\n  case proof_A_and_B.\n    intros proof_A proof_B.\n    refine (conj _ _).\n      exact proof_B.\n      exact proof_A.\nQed.\n\nTheorem and_commutes_again : (forall A B : Prop, A /\\ B -> B /\\ A).\nProof.\n  intros A B.\n  intros proof_A_and_B.\n  destruct proof_A_and_B as [ proof_A proof_B ].\n  refine (conj _ _).\n    exact proof_B.\n    exact proof_A.\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/and.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7678660620521647}}
{"text": "(** CS6225 -- Pset4a (120 points) *)\n\n(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 3 *)\n\nRequire Import Frap Pset4aSig.\n\n(* Define the identity function [id], which just returns its\n * argument without modification.\n *)\nDefinition id {A : Type} (x : A) : A := x.\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 *)\nDefinition compose {A B C : Type} (g : B -> C) (f : A -> B)\n           (x : A) : C := g(f x).\n\n(* If we map the [id] function over any list, we get the\n * same list back.\n *)\nTheorem map_id : forall {A : Type} (xs : list A),\n    map id xs = xs.\nProof.\n  simplify.\n  induction xs.\n  - simplify. equality.\n  - unfold id. simplify. unfold id in IHxs. rewrite IHxs. equality.\nQed.\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 *)\nTheorem 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).\nProof.\n  simplify.\n  induction xs.\n  - simplify. equality.\n  - unfold compose. simplify. unfold compose in IHxs. rewrite IHxs. equality.\nQed.\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 *)\nTheorem map_length : forall {A B : Type} (f : A -> B) (xs : list A),\n    length (map f xs) = length xs.\nProof.\n  induction xs.\n  - simplify. equality.\n  - unfold length. simplify. unfold length in IHxs. rewrite IHxs. equality.\nQed.\n\nTheorem map_append : forall {A B : Type} (f : A -> B) (xs ys : list A),\n    map f (xs ++ ys) = map f xs ++ map f ys.\nProof.\n  induction xs.\n    - simplify. equality.\n    - unfold append. simplify. unfold append in IHxs. rewrite IHxs. equality.\nQed.\n\n\nTheorem map_rev : forall {A B : Type} (f : A -> B) (xs : list A),\n    map f (rev xs) = rev (map f xs).\nProof.\n  induction xs.\n      - simplify. equality.\n      - simpl map. simpl rev. simplify. rewrite  (map_append (f) (rev xs) ([a])). rewrite IHxs. equality.\nQed.\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 [left_fold] function that we defined\n * in lecture.\n *)\nFixpoint fold {A B : Type} (b_cons : A -> B -> B) (b_nil : B)\n         (xs : list A) : B :=\nmatch xs with\n| [] => b_nil\n| h::t => b_cons h (fold b_cons  b_nil t)\nend.\n\n(* For instance, we should have\n     fold plus 10 [1; 2; 3]\n   = 1 + (2 + (3 + 10))\n   = 16\n *)\nExample fold_example : fold plus 10 [1; 2; 3] = 16.\nProof.\n  simplify. equality.\nQed.\n\n(* Prove that [map] can actually be defined as a particular\n * sort of [fold].\n *)\n\n  \nDefinition 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.\nProof.\n  intros.\n  induction xs.\n    - simplify. equality.\n    - simpl. rewrite IHxs. simpl fold. equality.\nQed.\n   \n(* Since [fold f z] replaces [cons] with [f] and [nil] with\n * [z], [fold cons nil] should be the identity function.\n *)\nTheorem fold_id : forall {A : Type} (xs : list A),\n    fold cons nil xs = xs.\nProof.\n  simplify.\n  induction xs.\n    - simplify. equality.\n    - simpl fold. rewrite IHxs. equality. \nQed.\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\n(* We will use this lemma to prove the next theorem *)\nLemma app_nil : forall {A:Type} (lst : list A),\n  lst ++ nil = lst.\nProof.\n  intros A lst.\n  induction lst as [ | h t IH].\n  - trivial.\n  - simpl. rewrite -> IH. trivial.\nQed.\n\nTheorem 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.\nProof.\n  simplify.\n  induction xs.\n  - simplify. equality.\n  - simpl fold. rewrite IHxs. equality.\nQed.\n\n(* Using [fold], define a function that computes the\n * sum of a list of natural numbers.\n *)\nDefinition sum (lst:list nat) :nat := fold (fun (x:nat) (y:nat)=> x+y) 0 lst.\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 *)\nExample sum_example : sum [1; 2; 3] = 6.\nProof.\n  simpl. equality.\nQed.\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 *)\nDefinition all (lst:list bool) :bool := fold (fun (x:bool) (y:bool) => x && y) true lst.\n\nExample all_example : all [true; false; true] = false.\nProof.  \n   simplify. equality.\nQed.\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 *)\nTheorem sum_append : forall (xs ys : list nat),\n    sum (xs ++ ys) = sum xs + sum ys.\nProof.\n  simplify.\n  induction xs.\n    - simplify. equality.\n    - simpl sum. unfold sum. simpl fold. unfold sum in IHxs. rewrite IHxs. linear_arithmetic.\nQed.\n\nTheorem all_append : forall (xs ys : list bool),\n    all (xs ++ ys) = andb (all xs) (all ys).\nProof.\n  simplify.\n  induction xs.\n    - simplify. equality.\n    - simpl all. unfold all. simpl fold. unfold all in IHxs. rewrite IHxs. ring.\nQed.\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 in tact.\n *)\nFixpoint tree_map {A B : Type} (f : A -> B) (t : tree A)\n  : tree B := match t with\n| Leaf => Leaf\n| Node a b c => Node (tree_map f a) (f b) (tree_map f c)\nend.\n\nExample 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))).\nProof.\n  simplify. equality.\nQed.\n\n(* [tree_map_flatten] shows that [map]\n * and [tree_map] are related by the [flatten] function.\n *)\nTheorem tree_map_flatten : forall {A B : Type} (f : A -> B) (t : tree A),\n  flatten (tree_map f t) = map f (flatten t).\nProof.\n  simplify.\n  induction t.\n      - simplify. equality.\n      - simpl flatten. rewrite IHt1. rewrite IHt2. rewrite  (map_append f (flatten t1) (d::flatten t2)). simpl map. equality.\nQed.\n\n\n(* Using [fold], define a function that composes a list of functions,\n * applying the *last* function in the list *first*.\n *)\nDefinition compose_list {A : Type} (lst: list (A -> A)) (y: A) : A := fold (fun (f:A->A) (y:A) => f y) y (lst).\n\nExample compose_list_example :\n  compose_list [fun x => x + 1; fun x => x * 2; fun x => x + 2] 1 = 7.\nProof.\n  simplify. equality.\nQed.\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 *)\nTheorem compose_list_map_add_sum : forall (xs : list nat),\n    compose_list (map plus xs) 0 = sum xs.\nProof.\n  simplify.\n  induction xs.\n    - simplify. equality.\n    - unfold compose_list. simplify. unfold compose_list in IHxs. rewrite IHxs. simpl sum. equality.\nQed.\n\n\n(* Ignore the below lines: *)\n\n\n(*Lemma util: forall {A B:Type} (zs: list B) (xs: list A) (f: A->B), \n  fold (fun (x : A) (ys : list B) => f x :: ys) zs xs = zs++fold (fun (x : A) (ys : list B) => f x :: ys) [] xs. \nProof.\n  simplify.\n  induct xs.\n    - simplify. rewrite (app_nil zs). equality.\n    - simplify. induction zs.\n        ++ simplify. equality.\n        ++ simplify. \n  \n*) \n(* Lemma fold_id_util : forall {A : Type} (xs: list A) (a:A), \n  fold cons [a] xs = a::xs.\nProof.\n  simplify.\n  induct xs.\n    - simplify. equality.\n    - \n*)\n", "meta": {"author": "nvvishnu", "repo": "CS6225-Programs-and-Proofs", "sha": "6faa7d6a880b2243551086b562a292303724032e", "save_path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs", "path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs/CS6225-Programs-and-Proofs-6faa7d6a880b2243551086b562a292303724032e/pset4/Pset4a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.9032942125614059, "lm_q1q2_score": 0.767774030083993}}
{"text": "(** * Andrew Chen\n3/13/22 *)\n\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Lia.\nFrom Coq Require Import Lists.List. Import ListNotations.\nRequire Import Coq.Program.Program.\nRequire Import Relation_Definitions.\nRequire Export Coq.Classes.RelationClasses.\nRequire Export Coq.Classes.Morphisms.\nRequire Export Coq.Classes.Init.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Program.Tactics.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.ZArith.Int. (*would like to use integers, but did not\n                                 realize it was necessary until it was too late *)\n\n(*Basic group definitions and properties, showing group axioms from left axioms.*)\n\nClass Group (G : Type) : Type := \n{\n  op : G -> G -> G;\n  inv : G -> G;\n  e : G;\n\n  associativity : forall a b c, op a (op b c) = op (op a b) c;\n  leftidentity : forall a, op e a = a;\n  leftinverse : forall a, op (inv a) a = e;\n}.\n\nClass Finite (G : Type) : Type :=\n{\n  elements : list G;\n}.\n\nClass FiniteGroup (G : Type) {g : Group G} {f : Finite G} : Type := { }.\n\n(*Class FiniteGroup (G : Type) {g : Group G}: Type :=\n{\n  elements : list G;\n  (*\n  (*cardinality := length(elements);*)\n  memberfinitegroup (m : G) : Prop := In m elements <-> member m*)\n}. *)\n\nDefinition finiteorder {G : Type}{g : Group G}{f : Finite G}{f : FiniteGroup G} : nat :=\n  length(elements).\n\n(*Definition isfinitegroup (G : Type){g : Group G}{f : Finite G}{f : FiniteGroup G} : Prop :=\n  forall (g : G), In g elements. *)\n\nNotation \"x '**' y\" := (op x y) (at level 50, left associativity).\n\nDefinition idempotent {G : Type} {g : Group G} (a : G) : Prop := \n  op a a = a.\n\nDefinition identity {G : Type} {g : Group G} (a : G) : Prop :=\n  a = e.\n\nLemma leftapplication {G : Type} {g : Group G} : forall (a b c: G),\n  a = b -> c ** a = c ** b.\nProof.\n  intros. rewrite H. reflexivity.\nQed.\n\nLemma rightapplication {G : Type} {g : Group G} : forall (a b c : G), \n  a = b -> a ** c = b ** c.  \nProof.\n  intros. rewrite H. reflexivity. \nQed.\n\nTheorem rightinverse {G : Type} {g : Group G} : forall (a : G),\n  op a (inv a) = e. (*hard*)\nProof.\n  intros. rewrite <- leftidentity with (a ** inv a). \n  rewrite <- leftinverse with (a ** inv a).\n  rewrite <- associativity.\n  assert (A: a ** inv a ** (a ** inv a) = a ** (inv a ** a) ** inv a).\n  { rewrite associativity. rewrite associativity. reflexivity. }\n   rewrite A. rewrite leftinverse with a. rewrite <- associativity. \n   rewrite leftidentity. reflexivity.\nQed.\n\nTheorem rightidentity {G : Type} {g : Group G} : forall (a : G),\n  a ** e = a.\nProof.\n  intros. rewrite <- leftinverse with a.\n  rewrite associativity. rewrite rightinverse with a.\n  rewrite leftidentity. reflexivity. \nQed.\n\nLemma leftcancellation {G : Type} {g : Group G} : forall (a b c : G), \n  c ** a = c ** b -> a = b.  \nProof.\n  intros. rewrite <- leftidentity. rewrite <- leftinverse with c.\n  rewrite <- associativity. rewrite <- H. rewrite associativity.\n  rewrite leftinverse. rewrite leftidentity. reflexivity. \nQed.\n\nLemma rightcancellation {G : Type} {g : Group G} : forall (a b c : G), \n  a ** c = b ** c -> a = b.  \nProof.\n  intros. rewrite <- rightidentity. rewrite <- rightinverse with c.\n  rewrite associativity. rewrite <- H. rewrite <- associativity.\n  rewrite rightinverse. rewrite rightidentity. reflexivity. \nQed.\n\nTheorem inverse_unique {G : Type} {g : Group G}: forall (a b: G),\n  a ** b = e -> a = inv b /\\  b = inv a.\nProof.\n  intros. split.\n  * rewrite <- leftidentity. rewrite <- H.\n    rewrite <- associativity.\n    rewrite rightinverse with b. rewrite rightidentity. reflexivity.\n  * rewrite <- rightidentity. rewrite <- H.\n    rewrite associativity.\n    rewrite leftinverse with a. rewrite leftidentity. reflexivity.\nQed.\n\nLemma inverseinverse {G : Type} {g : Group G} : forall (a : G), \n  inv (inv a) = a.\nProof. \n  intros. \n  remember (leftinverse a) as H.\n  destruct HeqH. apply inverse_unique in H. destruct H.\n  symmetry. assumption.\nQed. \n\nLemma inversefunction {G : Type} {g : Group G} : forall (a b : G), \n  a = b -> inv a = inv b. \nProof.\n  intros. rewrite H; reflexivity.\nQed.\n\nLemma inverseinjective {G : Type} {g : Group G} : forall (a b : G), \n  inv a = inv b -> a = b. \nProof.\n  intros. apply inversefunction in H. repeat rewrite inverseinverse in H. assumption.\nQed. \n\nTheorem inversedistribution {G : Type} {g : Group G} : forall (a b : G), \n inv (a ** b) = inv b ** inv a.\nProof.\n  intros. rewrite <- rightcancellation with (inv (a ** b)) (inv b ** inv a) a. reflexivity.\n  rewrite <- associativity. rewrite leftinverse with a. rewrite rightidentity.\n  rewrite <- rightcancellation with (inv (a ** b) ** a) (inv b) b. reflexivity.\n  rewrite leftinverse with b. rewrite <- associativity. rewrite leftinverse with (a ** b).\n  reflexivity.\nQed.\n\nLemma einverse_ise {G : Type} {g : Group G} : forall (a : G), \n  inv e = e.\nProof. \n  intros. rewrite <- leftidentity with (inv e). rewrite rightinverse with e. reflexivity.\nQed. \n\nTheorem leftinverseisrightinverse {G : Type} {g : Group G}: forall (a b c: G),\n  a ** b = e /\\ c ** a = e -> b = c.\nProof.\n  intros. destruct H. apply leftapplication with (c ** a) e (inv c) in H0. \n  rewrite associativity in H0. rewrite leftinverse in H0. rewrite leftidentity in H0.\n  rewrite rightidentity in H0. rewrite H0 in H. apply inverse_unique in H. destruct H.\n  apply inverseinjective in H. symmetry; assumption.\nQed.\n\nTheorem inversecommutes {G : Type} {g : Group G}: forall (a b: G),\n  a ** b = e <-> b ** a = e.\nProof.\n  intros. split; intros.\n  * rewrite <- rightinverse with b. rewrite <- leftapplication with a (inv b) b. reflexivity.\n    rewrite <- leftinverse with b in H. apply rightcancellation in H. assumption.\n  * rewrite <- rightinverse with a. rewrite <- leftapplication with b (inv a) a. reflexivity.\n    rewrite <- leftinverse with a in H. apply rightcancellation in H. assumption.\nQed.\n   \nLemma leftidentity_unique {G : Type}{g : Group G}: forall (a b : G), \n  a ** b = b -> a = e.\nProof.\n  intros. rewrite <- leftidentity with b in H.\n  rewrite associativity in H. rewrite rightidentity with a in H.\n  rewrite rightcancellation with a e b. reflexivity. assumption. \nQed.\n\nLemma rightidentity_unique {G : Type}{g : Group G}: forall (a b : G), \n  a ** b = a -> b = e.\nProof.\n  intros. rewrite <- rightidentity with a in H.\n  rewrite <- associativity in H. rewrite leftidentity with b in H.\n  rewrite leftcancellation with b e a. reflexivity. assumption. \nQed.\n\nTheorem leftidentityisrightidentity {G : Type} {g : Group G}: forall (a b c: G),\n  a ** b = a /\\ c ** a = a -> b = c.\nProof.\n  intros. destruct H. rewrite <- leftidentity in H0. apply rightcancellation in H0.\n  rewrite <- rightidentity in H. apply leftcancellation in H. rewrite <- H in H0. symmetry.\n  assumption.\nQed.\n\nTheorem idempotent_is_identity {G : Type} {g : Group G} : forall (a : G), \nidempotent a <-> identity a.  \nProof.\n  intros. split; intros.\n  * inversion H. unfold identity. rewrite <- leftidentity in H0. apply rightcancellation in H0.\n    rewrite H0. apply rightidentity.\n  * inversion H. unfold idempotent. apply rightidentity.\nQed.\n\n(*Cyclic and Abelian groups *)\n\nClass AbelianGroup (G : Type) {g : Group G} : Type :=\n{\n  commutativity : forall a b, op a b = op b a\n}. \n\nDefinition iscommutative {G : Type} {g : Group G} (a b : G) : Prop := \n  a ** b = b ** a.\n\nDefinition isabelian (G : Type) {g : Group G} : Prop := \n  forall (a b: G), iscommutative a b. \n\nFixpoint opexponent {G : Type} {g : Group G}(base : G)(n : nat): G :=\n  match n with\n  | O => e \n  | S n => base ** opexponent base n \nend.\n\nClass CyclicGroup (G : Type) {g : Group G} : Type :=\n{\n  generator : exists a, forall b, exists (n : nat), opexponent a n = b\n}. \n\nDefinition iscyclic (G : Type) {g : Group G} : Prop :=\n  exists (a : G), forall (b : G), exists (n : nat), opexponent a n = b.\n\nDefinition isgenerator {G : Type} {g : Group G} (gen : G) : Prop :=\n  forall b, exists (n : nat), opexponent gen n = b.\n\nLemma opexponentaddition {G : Type}{g : Group G}: forall (a : G) (n1 n2 : nat),\n  (opexponent a n1) ** (opexponent a n2) = (opexponent a (n1 + n2)) /\\ \n  (opexponent a n2) ** (opexponent a n1) = (opexponent a (n1 + n2)).\nProof.\n  intros. split.\n  * induction n1. simpl. apply leftidentity.\n    simpl. rewrite <- associativity. \n    rewrite leftapplication with (opexponent a n1 ** opexponent a n2) (opexponent a (n1 + n2)) a.\n    reflexivity. assumption.\n  * induction n2. simpl. rewrite leftidentity. rewrite plus_0_r. reflexivity.\n    assert (A: n1 + S n2 = S n2 + n1).\n    { lia. }\n    rewrite A. simpl. rewrite <- associativity. \n    rewrite leftapplication with (opexponent a n2 ** opexponent a n1) (opexponent a (n2 + n1)) a.\n    reflexivity.\n    assert (B : n2 + n1 = n1 + n2).\n    { lia. }\n    rewrite B; assumption.\nQed.\n\nTheorem cyclicisabelian (G : Type){g : Group G}{c : CyclicGroup G} : \n  isabelian G.\nProof.\n  unfold isabelian. unfold iscommutative. intros. inversion c. destruct generator0.\n  assert (A: exists n1, opexponent x n1 = a).\n  { eapply H. }\n  assert (B: exists n1, opexponent x n1 = b).\n  { eapply H. }\n  destruct A. destruct B.\n  rewrite <- H0. rewrite <- H1.\n  assert (X: opexponent x x0 ** opexponent x x1 = opexponent x (x0+x1)).\n  {apply opexponentaddition. }\n  assert (Y : opexponent x x1 ** opexponent x x0 = opexponent x (x0+x1)).\n  {apply opexponentaddition. }\n  rewrite X. rewrite Y. reflexivity.\nQed.\n\n(*Defining Subgroups*)\n\nClass Restrict (G : Type) : Type := \n{\n  member : G -> Prop\n}.\n\nClass Subgroup (G : Type){g : Group G}{r : Restrict G} : Type :=\n{\n  closure : forall a b, member a -> member b -> member (op a b);\n  inverse : forall a, member a -> member (inv a);\n  identityinsubgroup : forall a, identity a -> member a\n}.\n\nClass FiniteSubgroup (G : Type){g : Group G}{r : Restrict G}{f : Finite G} : Type := {}.\n\nDefinition subgroupfiniteorder {G : Type}{g : Group G}{r : Restrict G}{f : Finite G}{fg : FiniteSubgroup G} : nat :=\n  length(elements).\n\nDefinition issubgroup {G : Type}{g : Group G}(r : Restrict G) : Prop :=\n  forall (a b : G), member a -> member b -> member e /\\ member (a ** b) /\\ member (inv a).\n\n(*Informally, if G is a group and a is in G, then H = { a ^ n | n \\in Z} is a subgroup of G\n  containing a. This is the smallest subgroup containing a, as subgroups must be closed \n  under operation. *)\nTheorem smallestsubgroupcontaininga {G : Type}{g : Group G}{r : Restrict G} : \n  forall (a : G), ((forall (n : nat), member (opexponent a n)) /\\ \n                  (forall (b : G), member b -> (exists (n: nat), b = opexponent a n))) \n                  -> issubgroup r.\nProof.\n  intros. unfold issubgroup. intros. split.\n  * assert (B: member (opexponent a 0)).\n    { intros. apply H. }\n    simpl in B. assumption. \n  * split; destruct H.\n    - apply H2 in H1. apply H2 in H0. destruct H1. destruct H0.\n      rewrite H0. rewrite H1.\n      assert(A : opexponent a x0 ** opexponent a x = opexponent a (x0 + x)).\n      { apply opexponentaddition. }\n      rewrite A. apply H.\n    - apply H2 in H0. destruct H0. rewrite H0. \n      (*At the point the informal proof relies on the usage of Z,\n        namely the existence of -x,\n        but here I only have the naturals in the form of nat. *)\nAdmitted.\n\nClass NormalSubgroup (G : Type){g : Group G}{r : Restrict G}{h : Subgroup G} : Type :=\n{\n  normal : forall (g n : G), member n -> member (g ** n ** (inv g))\n}.\n\nLemma onenonmemberleadstononmember{G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : forall (a b : G), \n (~(member a) /\\ member b ) \\/ (member a /\\ ~(member b)) -> ~(member (a ** b)).\n Proof.\n  intros. remember closure as A. destruct H.\n  * destruct H. unfold not. unfold not in H. intros. apply H.\n    apply inverse in H0. apply A with (a ** b) (inv b) in H0.\n    rewrite <- associativity in H0. rewrite rightinverse with b in H0. rewrite rightidentity in H0.\n    assumption. assumption.\n  * destruct H. unfold not. unfold not in H. intros. apply H0.\n    apply inverse in H. apply A with (inv a) (a ** b) in H.\n    rewrite associativity in H. rewrite leftinverse with a in H. rewrite leftidentity in H.\n    assumption. assumption.\nQed.\n\nLemma subgroupinverse {G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : forall (a : G),\n  member(inv a) <-> member a. \nProof.\n  intros. split; intros.\n  * apply inverse in H. rewrite inverseinverse with a in H. assumption.\n  * apply inverse in H; assumption. \nQed.\n\nLemma notsubgroupinverse {G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : forall (a : G),\n  ~member(inv a) <-> ~member a.\nProof.\n  intros. split; intros.\n  * unfold not. intros. unfold not in H. apply H. apply inverse in H0. assumption.\n  * unfold not. unfold not in H. intros. apply H. rewrite subgroupinverse in H0. assumption.\nQed. \n\nLemma subgroupleftmember {G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : forall (a b : G),\n  member a -> member b <-> member(a ** b).\nProof.\n  intros; split; intros.\n  * apply closure with a b in H. assumption. assumption.\n  * apply inverse in H. apply closure with (inv a) (a ** b) in H. rewrite associativity in H.\n    rewrite leftinverse in H. rewrite leftidentity in H. assumption. assumption.\nQed.\n\nLemma subgrouprightmember {G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : forall (a b : G),\n  member b -> member a <-> member(a ** b).\nProof.\n  intros; split; intros.\n  * apply closure with a b in H. assumption. assumption.\n  * apply inverse in H. apply closure with (a ** b) (inv b) in H. rewrite <- associativity in H.\n    rewrite rightinverse in H. rewrite rightidentity in H. assumption. assumption.\nQed.\n\n(*the below proof is difficult, not sure how to complete it. *)\nTheorem fundamentaltheoremofcyclicgroups {G : Type}{g : Group G}{c : CyclicGroup G}{r : Restrict G}{h : Subgroup G} :\n  exists (a : G), member a /\\ forall (h : G), member h -> exists (n : nat), h = opexponent a n.\nProof.\n  remember generator as A. destruct A. eexists. split.\n  * Abort. \n  (*exists x.  intros. destruct. split. *)\n\n(* Cosets *)\n\nClass LeftCosetRestrict (G : Type) : Type :=\n{\n  lcosetmember : G -> Prop\n}.\n\nClass RightCosetRestrict (G : Type) : Type :=\n{\n  rcosetmember : G -> Prop\n}.\n\n(*Not all cosets are groups, so we do not give it the subgroup annotation*)\nClass leftcoset {G: Type}{g : Group G}(r : Restrict G){c : LeftCosetRestrict G}(a : G):=\n{\n  inleftcoset : forall (h : G), member h ->  lcosetmember (a ** h)\n}.\n\nClass rightcoset {G: Type}{g : Group G}(r : Restrict G){c : RightCosetRestrict G}(a : G):=\n{\n  inrightcoset : forall (h : G), member h ->  rcosetmember (h ** a)\n}.\n\nDefinition leftrightcosetequalfora {G : Type}{g : Group G}{r : Restrict G}(h : Subgroup G)(a : G)\n      {l : LeftCosetRestrict G}{r : RightCosetRestrict G} : Prop := \n  forall (s : G), member s -> (lcosetmember (a ** s) <-> rcosetmember (s ** a)).\n\nDefinition leftrightcosetsequal {G : Type}{g : Group G}{r : Restrict G}(h : Subgroup G)\n{l : LeftCosetRestrict G}{r : RightCosetRestrict G} : Prop :=\n  forall (a : G), leftrightcosetequalfora h a.\n\nDefinition leftcosetrelation {G : Type}{g : Group G}{r : Restrict G}\n(a : G)(b : G) : Prop :=\n  member ((inv a) ** b).\n\nDefinition rightcosetrelation {G : Type}{g : Group G}{r : Restrict G}\n(a : G)(b : G) : Prop :=\n  member (a ** (inv b)).\n\nDefinition isequivalencerelation {G : Type}(f : G -> G -> Prop): Prop :=\n  forall (a b c : G), f a a /\\ ((f a b) <-> (f b a)) /\\ ((f a b) -> (f b c) -> (f a c)).\n\nTheorem cosetrelationisequivrelation {G : Type}{g : Group G}{r : Restrict G}{h : Subgroup G} : \n isequivalencerelation leftcosetrelation /\\ isequivalencerelation rightcosetrelation.\nProof.\n  unfold isequivalencerelation. split; split.\n  * unfold leftcosetrelation. rewrite leftinverse. apply identityinsubgroup. reflexivity.\n  * split.\n    - split; unfold leftcosetrelation; intros; apply inverse in H;\n      rewrite inversedistribution in H; rewrite inverseinverse in H;\n      assumption.\n    - unfold leftcosetrelation; repeat intros. \n      apply closure with (inv a ** b) (inv b ** c) in H.\n      repeat rewrite <- associativity in H.\n      assert (A: b ** (inv b ** c) = (b ** inv b) ** c).\n      { rewrite <- associativity. reflexivity. }\n        rewrite A in H. rewrite rightinverse in H.\n        rewrite leftidentity in H. assumption.\n        assumption.\n  * unfold rightcosetrelation. rewrite rightinverse. apply identityinsubgroup. reflexivity.\n  *  split.\n    - split; unfold rightcosetrelation; intros; apply inverse in H;\n      rewrite inversedistribution in H; rewrite inverseinverse in H;\n      assumption.\n    - unfold rightcosetrelation; repeat intros. \n      apply closure with (a ** inv b) (b ** inv c) in H.\n      repeat rewrite <- associativity in H.\n      assert (A: inv b ** (b ** inv c) = (inv b ** b) ** inv c).\n      { rewrite <- associativity. reflexivity. }\n        rewrite A in H. rewrite leftinverse in H.\n        rewrite leftidentity in H. assumption.\n        assumption.\nQed.\n\nClass LeftCosetEquivalenceClass {G: Type}{g : Group G}{r : Restrict G}{c : LeftCosetRestrict G}(a : G):=\n{\n  inleftcosetequivalenceclass (b : G) : leftcosetrelation a b\n}.\n\nClass RightCosetEquivalenceClass {G: Type}{g : Group G}{r : Restrict G}{c : RightCosetRestrict G}(a : G):=\n{\n  inrightcosetequivalenceclass (b : G) : rightcosetrelation a b\n}.\n\nClass LeftCosets (G: Type){g : Group G}{r : Restrict G}{c : LeftCosetRestrict G}:=\n{\n  aleftcoset (a : G) : LeftCosetEquivalenceClass a\n}.\n\nClass FiniteLeftCosets (G: Type){g : Group G}{r : Restrict G}{c : LeftCosetRestrict G}{f : Finite G} : Type := {}.\n\nDefinition leftcosetsfinitecardinality {G : Type}{g : Group G}{r : Restrict G}{c : LeftCosetRestrict G}{f : Finite G}\n{flc : FiniteLeftCosets G} : nat :=\n  length(elements).\n\nClass RightCosets (G: Type){g : Group G}{r : Restrict G}{c : RightCosetRestrict G}:=\n{\n  arightcoset (a : G) : RightCosetEquivalenceClass a\n}.\n\nClass FiniteRightCosets (G: Type){g : Group G}{r : Restrict G}{c : RightCosetRestrict G}{f : Finite G} : Type := {}.\n\nDefinition rightcosetsfinitecardinality {G : Type}{g : Group G}{r : Restrict G}{c : RightCosetRestrict G}{f : Finite G}\n{frc : FiniteRightCosets G} : nat :=\n  length(elements).\n\nDefinition isbijective {A : Type}{B : Type}(f : A -> B) :=\n  (forall (b1 b2 : B)(a1 a2 : A), b1 = f a1 -> b2 = f a2 -> b1 = b2 -> a1 = a2) \n  /\\ (forall (b : B), exists (a : A), f a = b).\n\n(* The (a : G) is the representative of the coset aH, while h is intended to be any element\n    of the subgroup. The proof of Lagrange's theorem uses the bijectivity of this function to \n    show that for any coset aH, aH has the same number of elements as H.*)\nDefinition lagrangemapping {G : Type}{g : Group G}{r : Restrict G} \n{s : Subgroup G}{f: Finite G}{fg : FiniteGroup G}{sf : FiniteSubgroup G}(a : G) : G -> G := fun h => a ** h.\n    \nTheorem partoflagrange {G : Type}{g : Group G}{r : Restrict G} \n{s : Subgroup G}{f: Finite G}{fg : FiniteGroup G}{sf : FiniteSubgroup G}\n(a : G): isbijective (lagrangemapping a).\nProof.\n  unfold isbijective. unfold lagrangemapping. split; intros.\n  * rewrite H1 in H. rewrite H0 in H. apply leftcancellation in H.\n    symmetry. assumption.\n  * exists (inv a ** b). rewrite associativity. rewrite rightinverse.\n    rewrite leftidentity. reflexivity.\nQed.\n\n(*The above theorem is intended to show that \"Every coset of a subgroup of H\n  of a group G has the same number of elements as H\", a statement which once established,\n  Lagrange's theorem follows almost immediately from,\n  as shown in Theorem 10.10 in Fraleigh,\n  \"A First Course in Abstract Algebra\". However, my implementation has a couple of issues,\n  namely that my Lagrange mapping goes from G -> G and does not reflect the fact that\n  the mapping should go H -> G in the informal proof. Additionally, I have been unsuccessful\n  in thinking of a way to count the number of items in a left coset equivalence class,\n  and I also haven't shown a way to count the number of left coset equivalence classes.\n  From the above theorem, when stated correctly, Lagrange's theorem is a direct result\n  of the fact that the order of the group must be equal to the number of cosets times the number of \n  items in each coset - the above theorem proving that the number of items in each coset\n  must be the same as the number of items in the subgroup H from which the cosets are generated from,\n  gives the result of Lagrange's theorem: the order of H divides the order of G.\n  *)\n\nTheorem Lagrange {G : Type}{g : Group G}{r : Restrict G} \n{s : Subgroup G}{f: Finite G}{fg : FiniteGroup G}{sf : FiniteSubgroup G}\n: exists (n : nat), n * subgroupfiniteorder = finiteorder.\nProof.\nAbort.\n\n(*Factor/Quotient Groups: Expansion *)\n(*Class QuotientGroup (G : Type){g : Group G}{r : Restrict G}{h : Subgroup G}{n : NormalSubgroup G} : Type :=\n{\n\n}\n*)\n\n", "meta": {"author": "achen1210", "repo": "lagrangestheoremcoq", "sha": "f5b408a48e295244aa818ee4eebc622c3327b527", "save_path": "github-repos/coq/achen1210-lagrangestheoremcoq", "path": "github-repos/coq/achen1210-lagrangestheoremcoq/lagrangestheoremcoq-f5b408a48e295244aa818ee4eebc622c3327b527/LagrangesTheorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7677712077965323}}
{"text": "\n\nRequire Import NArith Ring Monoid_instances Euclidean_Chains Pow\n        Strategies Dichotomy BinaryStrat.\nImport Addition_Chains. \nOpen Scope N_scope.\n\n\n(* begin snippet FibDef *)\nFixpoint fib (n:nat) : N :=\n  match n with\n    0%nat | 1%nat => 1\n  | (S ((S p) as q)) => fib p + fib q\n  end.\n\n\nCompute fib 20.\n(* end snippet FibDef *)\n\nLemma fib_ind (P:nat->Prop) :\n  P 0%nat -> P 1%nat -> (forall n, P n -> P (S n) -> P(S (S n))) ->\n  forall n, P n.\nProof.\nintros H0 H1 HS n; assert (P n /\\ P (S n)).\n{ induction n.\n  - split;auto.\n  - destruct IHn; split; auto.\n}\n tauto.\nQed.\n\nLemma fib_SSn : forall (n:nat) , fib (S (S n)) = (fib n + fib (S n)).\nProof.\n  intro n; pattern n; apply fib_ind; try reflexivity.\nQed.\n\n\n(** Yves' encoding *)\n\n(* begin snippet mul2Def *)\nDefinition mul2 (p q : N * N) :=\n  match p, q with\n    (a, b),(c,d) => (a*c + a*d + b*c, a*c + b*d)\n  end.\n(* end snippet mul2Def *)\n\nLemma neutral_l p : mul2 (0,1) p = p.\n  unfold mul2. destruct p; f_equal; ring.\nQed.\n\nLemma neutral_r p : mul2 p (0,1)  = p.\n  unfold mul2.  destruct p; f_equal; ring.\nQed.\n\n(* begin snippet mul2Monoid  *)\n#[ global ] Instance Mul2 : Monoid  mul2 (0,1).\n(* end snippet mul2Monoid  *)\n\nProof.\n  split.\n  destruct x,y,z; unfold mul2;  cbn; f_equal; ring.\n  intro x; now rewrite neutral_l.\n  intro  x; now rewrite neutral_r.\nQed.\n\n(* begin snippet nextFib:: no-out *)\nLemma next_fib (n:nat) : mul2 (1,0) (fib (S n), fib n) =\n                         (fib (S (S n)), fib (S n)).\n(* end snippet nextFib *)\nProof.\n  unfold mul2; f_equal; ring_simplify.\n  -  rewrite fib_SSn. ring.\n  - reflexivity.\nQed.\n\n(* begin snippet fibMul2Def *)\nDefinition fib_mul2 n := let (a,b) := power (M:=Mul2) (1,0) n\n                         in (a+b).\n\nCompute fib_mul2 20.\n(* end snippet fibMul2Def *)\n\n(* begin snippet fibMul2OK0:: no-out *)\nLemma fib_mul2_OK_0 (n:nat) :\n  power (M:=Mul2) (1,0) (S (S n)) =\n  (fib (S n), fib n).\nProof.\n  induction n.\n  (* ... *)\n  (* end snippet fibMul2OK0 *)\n  - reflexivity. \n  - now rewrite power_eq2, IHn, next_fib.\nQed.\n\n(* begin snippet fibMul2OK:: no-out *)\nLemma fib_mul2_OK n : fib n = fib_mul2 n.\n(* end snippet fibMul2OK *)\nProof.\n unfold fib_mul2; pattern n;apply fib_ind; try reflexivity.\n - intros; rewrite fib_mul2_OK_0; now rewrite fib_SSn, N.add_comm.\nQed.\n\n(* begin snippet TimeFibMul2 *)\nTime Compute fib_mul2 87.\n(* end snippet TimeFibMul2 *)\n\n(* begin snippet fibPos *)\nDefinition fib_pos n :=\n  let (a,b) := Pos_bpow (M:= Mul2) (1,0) n in\n  (a+b).\n\nCompute fib_pos xH.\nCompute fib_pos 10%positive. \n\nTime Compute fib_pos 153%positive.\n(* end snippet fibPos *)\n\nLocate chain_apply.\nAbout chain_apply.\n\n(* begin snippet fibEuclDemo *)\nDefinition fib_eucl gamma `{Hgamma: Strategy gamma} n :=\n  let c := make_chain gamma  n\n  in let r := chain_apply c (M:=Mul2) (1,0) in\n       fst r + snd r.\n\nTime Compute fib_eucl dicho  153.\nTime Compute fib_eucl two  153.\nTime Compute fib_eucl half 153.\n(* end snippet fibEuclDemo *)\n\n\n(*  68330027629092351019822533679447\n     : N \nFinished transaction in 0.002 secs (0.002u,0.s) (successful)\n*)\n\nRequire Import AM.\nDefinition fib_with_chain c :=\n  match chain_apply c  Mul2 (1,0) with\n    Some ((a,b), nil) => Some (a+b) | _ => None end.\n\nDefinition c153 := chain_gen dicho (gen_F 153%positive).\n\nCompute c153.\n\n(*\n  = (PUSH :: SQR :: SQR :: SQR :: MUL :: PUSH :: \n     SQR :: SQR :: SQR :: SQR :: MUL :: nil)%list\n     : code\n\n*)\n(* number of multiplications and squares *)\n\nCompute mults_squares c153.\n\n\nCompute fib_with_chain c153 .\n\n(*\n = Some 68330027629092351019822533679447\n     : option N\n*)\n\nCompute mults_squares (chain_gen dicho (gen_F 30000%positive)).\n\n(*   = (6%nat, 13%nat)\n     : nat * nat  *)\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/Fib2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7675339218220686}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\nRequire Extraction.\n\n(** Arithmetic Expression Over Natural Numbers **)\n\n(* Source Language *)\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 =>\n    (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\n(* Target Language *)\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr\n.\n\nDefinition prog := list instr.\n\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' =>\n      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\n(* Translation *)\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n => iConst n :: nil\n  | Binop b e1 e2 =>\n    compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in compile (Binop Plus (Const 2) (Const 3)).\n\n(* Translation Correctness *)\n\nLemma compile_correct' : forall e p s, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  intros.\n  rewrite (app_nil_end (compile e)).\n  rewrite compile_correct'.\n  reflexivity.\nQed.\n\n(** Typed Expressions **)\n\n(* Source Language *)\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 =>\n    (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TBinop TTimes (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. (* %type as an instruction to Coq's extensible parser *)\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 (* destruct multi-level tuple *)\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(* 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\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(* This could work *)\n(*\nDefinition tcompile := \n  fix tcompile (t : type) (e : texp t) (ts : tstack) {struct e} : tprog ts (t :: ts) :=\n    match e in (texp t) return (tprog ts (t :: ts)) with\n    | TNConst n => TCons (TiNConst ts n) (TNil (Nat :: ts))\n    | TBConst b => TCons (TiBConst ts b) (TNil (Bool :: ts))\n    | TBinop t1 t2 t0 b e1 e2 =>\n      tconcat (tcompile t2 e2 ts)\n              (tconcat (tcompile t1 e1 (t2 :: ts)) (TCons (TiBinop ts b) (TNil (t0 :: ts))))\n    end.\n*)\n\n(* TODO: this doesn't work -- dependent pattern matching *)\n(*\nFixpoint tcompile (t : type) (e : texp t) (ts : tstack) {struct e} : tprog ts (t :: ts) :=\n  match e in (texp t) return (tprog ts (t :: ts)) with\n  | TNConst n => TCons (TiNConst ts n) (TNil (Nat :: ts))\n  | TBConst b => TCons (TiBConst _ b) (TNil _)\n  | TBinop arg1 arg2 res b e1 e2 =>\n    tconcat (tcompile arg2 e2 ts)\n            (tconcat (tcompile arg1 e1 (arg2 :: ts))\n                     (TCons (TiBinop ts b) (TNil (res :: ts))))\n  end.\n *)\n\nEval simpl in tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.\n\n(* Translation correctness *)\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 = tprogDenote p' (tprogDenote p s).\nProof.\n  induction p; crush.\nQed.\n\nHint Rewrite tconcat_correct.\n\n(* Strengthed induction hypothesis *)\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  crush.\nQed.\n\nExtraction tcompile.\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/my_cpdt/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798115, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7673517084326914}}
{"text": "(*\n * Divisibility rules.\n * E.g., an integer is divisible by 9 iff the sum of its digits are.\n *)\n\nFrom Coq Require Import\n  ZArith.\nFrom FunProofs.Lib Require Import\n  Series\n  Util\n  ZipMap.\n\nOpen Scope Z.\nImport ZSum ZAltSum.\n\nDefinition Z_of_digits (ds : list Z) : Z :=\n  sum (zipMap Z.mul ds (rev (tens (length ds)))).\n\nLemma Z_of_digits_mod ds m (n := Z_of_digits ds) :\n  m <> 0 ->\n  n mod m = sum (zipMap\n    (fun x y => (x * y) mod m)\n    (map (fun x => x mod m) ds)\n    (map (fun y => y mod m) (rev (tens (length ds))))) mod m.\nProof.\n  intros; subst n.\n  rewrite <- zipMap_split.\n  unfold Z_of_digits, zipMap.\n  rewrite sum_mod, map_map by easy.\n  erewrite map_ext with (g := fun xy => _); auto.\n  intros; rewrite Z.mul_mod by easy; eauto.\nQed.\n\nSection Div9.\n  Lemma sum_digs_9_congr ds (n := Z_of_digits ds) : n mod 9 = (sum ds) mod 9.\n  Proof.\n    subst n; rewrite Z_of_digits_mod by easy.\n    unfold tens; rewrite map_rev, (geom_mod _ 1), geom_one, map_repeat, rev_repeat\n      by easy.\n    rewrite zipMap_repeat_r, map_map by (now rewrite map_length).\n    erewrite map_ext with (g := fun x => _).\n    2: now intros; rewrite Z.mul_1_r, Z.mod_mod.\n    symmetry; now apply sum_mod.\n  Qed.\n\n  Corollary divisibility_9 ds (n := Z_of_digits ds) : (9 | n) <-> (9 | sum ds).\n  Proof. subst n; now rewrite <- !Z.mod_divide, sum_digs_9_congr. Qed.\nEnd Div9.\n\nSection Div3.\n  Corollary sum_digs_3_congr ds (n := Z_of_digits ds) : n mod 3 = (sum ds) mod 3.\n  Proof.\n    apply mod_mul_congr with (m := 3); try easy.\n    apply sum_digs_9_congr.\n  Qed.\n\n  Corollary divisibility_3 ds (n := Z_of_digits ds) : (3 | n) <-> (3 | sum ds).\n  Proof. subst n; now rewrite <- !Z.mod_divide, sum_digs_3_congr. Qed.\nEnd Div3.\n\nSection Div11.\n  Lemma altsum_digs_11_congr ds (n := Z_of_digits ds) :\n    n mod 11 = (altsum (rev ds)) mod 11.\n  Proof.\n    subst n; rewrite Z_of_digits_mod by easy.\n    rewrite <- sum_rev, zipMap_rev, <- !map_rev, rev_involutive.\n    2: unfold tens; now rewrite !map_length, rev_length, geom_length.\n    unfold tens; rewrite map_rev, (geom_mod _ (-1)), geom_none by easy.\n    rewrite <- map_rev, <- zipMap_split.\n    erewrite map_ext with (g := fun xy => _).\n    2: intros; rewrite <- Z.mul_mod by easy; eauto.\n    unfold altsum; rewrite (sum_mod (altmap _ _)) by easy.\n    unfold ZSumOps.Tmodulo, ZAltSumOps.Topp, ZSumOps.T in *.\n    do 2 f_equal.\n    apply list_eq_pointwise; intros.\n    assert (n < length ds \\/ n >= length ds)%nat as [|] by lia.\n    - match goal with\n      | |- nth_error (map _ ?x) n = nth_error (map _ ?y) n =>\n        assert (exists a b, nth_error x n = Some a /\\ nth_error y n = Some b)\n          as (? & ? & Hnth & Hnth')\n      end.\n      { match goal with\n        | |- exists _ _, ?x = _ /\\ ?y = _ => assert (x <> None /\\ y <> None)\n        end.\n        { split; apply nth_error_Some;\n            rewrite ?combine_length, altmap_length, rev_length, ?repeat_length; lia.\n        }\n        now destruct (nth_error _ _), (nth_error _); eauto.\n      }\n      erewrite !map_nth_error; eauto.\n      rewrite Hnth'; f_equal.\n      apply combine_nth_error in Hnth as (Hnth1 & Hnth2).\n      2: rewrite altmap_length, rev_length, repeat_length; auto.\n      assert (Hrep: nth_error (repeat 1 (length ds)) n = Some 1)\n        by (rewrite repeat_nth; auto).\n      apply altmap_nth_error with (f := Z.opp) in Hrep.\n      apply altmap_nth_error with (f := Z.opp) in Hnth1.\n      assert (Nat.Even n -> Nat.Odd n -> False).\n      { rewrite <- Nat.even_spec, <- Nat.odd_spec.\n        unfold Nat.odd; now destruct (Nat.even _).\n      }\n      rewrite Hnth', Hnth2 in *.\n      destruct Hnth1 as [(? & ?) | (? & ?)], Hrep as [(? & ?) | (? & ?)]; intuition;\n        simplify.\n      + replace (snd _) with 1 by auto; lia.\n      + replace (snd _) with (-1) by auto; lia.\n    - match goal with\n      | |- ?x = ?y => enough (x = None /\\ y = None) as (? & ?) by congruence\n      end.\n      split; apply nth_error_None;\n        rewrite map_length, ?combine_length, altmap_length, rev_length, ?repeat_length;\n        lia.\n  Qed.\n\n  Corollary divisibility_11 ds (n := Z_of_digits ds) :\n    (11 | n) <-> (11 | altsum (rev ds)).\n  Proof. subst n; now rewrite <- !Z.mod_divide, altsum_digs_11_congr. Qed.\nEnd Div11.\n\nSection Div2.\n  Lemma last_dig_even_congr ds (n := Z_of_digits ds) : n mod 2 = (last ds 0) mod 2.\n  Proof.\n    subst n; rewrite Z_of_digits_mod by easy.\n    assert (ds = [] \\/ 0 < length ds)%nat as [|]\n      by (destruct ds; cbn; intuition lia); [subst; auto |].\n    unfold tens; rewrite map_rev, (geom_mod _ 0), geom_zero, map_cons, map_repeat\n      by easy.\n    rewrite (@app_removelast_last _ ds 0) at 1 by (now destruct ds).\n    rewrite map_app; cbn [rev]; rewrite rev_repeat, zipMap_app; auto.\n    2: now rewrite map_length, repeat_length, removelast_length.\n    rewrite zipMap_repeat_r by (now rewrite map_length, removelast_length).\n    erewrite map_map, map_ext with (g := fun x => _).\n    2: now intros; rewrite Z.mul_0_r; cbn.\n    rewrite map_const, removelast_length, sum_app0, sum_repeat; cbn.\n    now rewrite Z.mul_1_r, !Z.mod_mod.\n  Qed.\n\n  Lemma divisibility_2 ds (n := Z_of_digits ds) : (2 | n) <-> (2 | last ds 0).\n  Proof. intros; subst n; now rewrite <- !Z.mod_divide, last_dig_even_congr. Qed.\nEnd Div2.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Div9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7673517010675522}}
{"text": "(** * Rel: Properties of Relations *)\n\nRequire Export SfLib.\n\n(** This short, optional chapter develops some basic definitions and a\n    few theorems about binary relations in Coq.  The key definitions\n    are repeated where they are actually used (in the [Smallstep]\n    chapter), so readers who are already comfortable with these ideas\n    can safely skim or skip this chapter.  However, relations are also\n    a good source of exercises for developing facility with Coq's\n    basic reasoning facilities, so it may be useful to look at it just\n    after the [Logic] chapter. *)\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(** 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-than-or-equal-to\n    relation which we usually write like this [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\n(* ######################################################### *)\n(** * Basic Properties of Relations *)\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    ways of classifying relations (are they reflexive, transitive,\n    etc.), theorems that can be proved generically about classes of\n    relations, constructions that build one relation from another,\n    etc.  For example... *)\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 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 function.\n    In short: 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  { (* 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 earlier is not a partial\n    function. *)\n\nTheorem total_relation_not_a_partial_function :\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense.\n  { (* Proof of assertion *)\n    apply Hc with (x := 0).\n    - apply tot.\n    - apply tot. }\n  inversion Nonsense.   \nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [empty_relation] defined earlier is a partial\n    function. *)\n\nTheorem  empty_relation_is_a_partial_function :\n  partial_function empty_relation.\nProof.\n  unfold partial_function.\n  intros.\n  inversion H0. \nQed. \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\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 *)\n  - apply le_S. apply Hnm.\n  - apply le_trans with (a := (S n)) (b := (S m)) (c := (S m')).\n    + apply le_S.  apply Hnm.\n    + apply le_S. apply Hm'o.\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  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 8 *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold not. unfold symmetric. intros.\n  assert (1 <= 0) as Nonsense.\n  { apply H. 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 9 *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a.\n  induction a.\n  - intros. destruct b.\n    + reflexivity.\n    + inversion H0.\n  - intros. \n    inversion H.\n    + reflexivity.\n    + inversion H0.\n      * rewrite <- H2 in H3. rewrite H3. reflexivity.\n      * apply eq_S. apply IHa.\n        {\n           apply le_Sn_le. apply H1.\n        } \n        {\n           rewrite <- H2 in H0. apply le_Sn_le. rewrite H2. apply H4.\n        }\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  (* 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    - (* 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. 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\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(** 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.\n  induction H.\n  - apply H0.\n  - apply rsc_step with y. \n    * apply H.\n    *  apply IHrefl_step_closure. apply 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, 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_step with y.\n      * apply H.\n      * apply rsc_refl.\n    + apply rsc_refl.\n    + apply rsc_trans with y.\n      * apply IHclos_refl_trans1.\n      * apply 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 IHrefl_step_closure.\nQed.\n(** [] *)\n\n(** $Date: 2015-08-10 18:00:14 +0200 (Mon, 10 Aug 2015) $ *)\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7673468810840341}}
{"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 Bool List Omega.\n\nRequire Import Cpdt.CpdtTactics Cpdt.MoreSpecif.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(** %\\chapter{More Dependent Types}% *)\n\n(** Subset types and their relatives help us integrate verification with programming.  Though they reorganize the certified programmer's workflow, they tend not to have deep effects on proofs.  We write largely the same proofs as we would for classical verification, with some of the structure moved into the programs themselves.  It turns out that, when we use dependent types to their full potential, we warp the development and proving process even more than that, picking up \"free theorems\" to the extent that often a certified program is hardly more complex than its uncertified counterpart in Haskell or ML.\n\n   In particular, we have only scratched the tip of the iceberg that is Coq's inductive definition mechanism.  The inductive types we have seen so far have their counterparts in the other proof assistants that we surveyed in Chapter 1.  This chapter explores the strange new world of dependent inductive datatypes outside [Prop], a possibility that sets Coq apart from all of the competition not based on type theory. *)\n\n\n(** * Length-Indexed Lists *)\n\n(** Many introductions to dependent types start out by showing how to use them to eliminate array bounds checks%\\index{array bounds checks}%.  When the type of an array tells you how many elements it has, your compiler can detect out-of-bounds dereferences statically.  Since we are working in a pure functional language, the next best thing is length-indexed lists%\\index{length-indexed lists}%, which the following code defines. *)\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 see that, within its section, [ilist] is given type [nat -> Set].  Previously, every inductive type we have seen has either had plain [Set] as its type or has been a predicate with some type ending in [Prop].  The full generality of inductive definitions lets us integrate the expressivity of predicates directly into our normal programming.\n\n   The [nat] argument to [ilist] tells us the length of the list.  The types of [ilist]'s constructors tell us that a [Nil] list has length [O] and that a [Cons] list has length one greater than the length of its tail.  We may apply [ilist] to any natural number, even natural numbers that are only known at runtime.  It is this breaking of the%\\index{phase distinction}% _phase distinction_ that characterizes [ilist] as _dependently typed_.\n\n   In expositions of list types, we usually see the length function defined first, but here that would not be a very productive function to code.  Instead, let us implement list concatenation. *)\n\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  (** Past Coq versions signalled an error for this definition.  The code is still invalid within Coq's core language, but current Coq versions automatically add annotations to the original program, producing a valid core program.  These are the annotations on [match] discriminees that we began to study in the previous chapter.  We can rewrite [app] to give the annotations explicitly. *)\n\n(* begin thide *)\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    end.\n(* end thide *)\n\n(** Using [return] alone allowed us to express a dependency of the [match] result type on the _value_ of the discriminee.  What %\\index{Gallina terms!in}%[in] adds to our arsenal is a way of expressing a dependency on the _type_ of the discriminee.  Specifically, the [n1] in the [in] clause above is a _binding occurrence_ whose scope is the [return] clause.\n\nWe may use [in] clauses only to bind names for the arguments of an inductive type family.  That is, each [in] clause must be an inductive type family name applied to a sequence of underscores and variable names of the proper length.  The positions for _parameters_ to the type family must all be underscores.  Parameters are those arguments declared with section variables or with entries to the left of the first colon in an inductive definition.  They cannot vary depending on which constructor was used to build the discriminee, so Coq prohibits pointless matches on them.  It is those arguments defined in the type to the right of the colon that we may name with [in] clauses.\n\nOur [app] function could be typed in so-called%\\index{stratified type systems}% _stratified_ type systems, which avoid true dependency.  That is, we could consider the length indices to lists to live in a separate, compile-time-only universe from the lists themselves.  Compile-time data may be _erased_ such that we can still execute a program.  As an example where erasure would not work, consider an injection function from regular lists to length-indexed lists.  Here the run-time computation actually depends on details of the compile-time argument, if we decide that the list to inject can be considered compile-time.  More commonly, we think of lists as run-time data.  Neither case will work with %\\%naive%{}% erasure.  (It is not too important to grasp the details of this run-time/compile-time distinction, since Coq's expressive power comes from avoiding such restrictions.) *)\n\n(* EX: Implement injection from normal lists *)\n\n(* begin thide *)\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(** We can define an inverse conversion and prove that it really is an inverse. *)\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    induction ls; crush.\n  Qed.\n(* end thide *)\n\n(* EX: Implement statically checked \"car\"/\"hd\" *)\n\n(** Now let us attempt a function that is surprisingly tricky to write.  In ML, the list head function raises an exception when passed an empty list.  With length-indexed lists, we can rule out such invalid calls statically, and here is a first attempt at doing so.  We write [???] as a placeholder for a term that we do not know how to write, not for any real Coq notation like those introduced two chapters ago.\n[[\n  Definition hd n (ls : ilist (S n)) : A :=\n    match ls with\n      | Nil => ???\n      | Cons _ h _ => h\n    end.\n]]\nIt is not clear what to write for the [Nil] case, so we are stuck before we even turn our function over to the type checker.  We could try omitting the [Nil] case:\n[[\n  Definition hd n (ls : ilist (S n)) : A :=\n    match ls with\n      | Cons _ h _ => h\n    end.\n]]\n\n<<\nError: Non exhaustive pattern-matching: no clause found for pattern Nil\n>>\n\nUnlike in ML, we cannot use inexhaustive pattern matching, because there is no conception of a <<Match>> exception to be thrown.  In fact, recent versions of Coq _do_ allow this, by implicit translation to a [match] that considers all constructors; the error message above was generated by an older Coq version.  It is educational to discover for ourselves the encoding that the most recent Coq versions use.  We might try using an [in] clause somehow.\n\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\n<<\nError: The reference n was not found in the current environment\n>>\n\nIn this and other cases, we feel like we want [in] clauses with type family arguments that are not variables.  Unfortunately, Coq only supports variables in those positions.  A completely general mechanism could only be supported with a solution to the problem of higher-order unification%~\\cite{HOU}%, which is undecidable.  There _are_ useful heuristics for handling non-variable indices which are gradually making their way into Coq, but we will spend some time in this and the next few chapters on effective pattern matching on dependent types using only the primitive [match] annotations.\n\nOur final, working attempt at [hd] uses an auxiliary function and a surprising [return] annotation. *)\n\n(* begin thide *)\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  Check hd'.\n(** %\\vspace{-.15in}% [[\nhd'\n     : forall n : nat, ilist n -> match n with\n                                  | 0 => unit\n                                  | S _ => A\n                                  end\n  ]]\n  *)\n\n  Definition hd n (ls : ilist (S n)) : A := hd' ls.\n(* end thide *)\n\nEnd ilist.\n\n(** We annotate our main [match] with a type that is itself a [match].  We write that the function [hd'] returns [unit] when the list is empty and returns the carried type [A] in all other cases.  In the definition of [hd], we just call [hd'].  Because the index of [ls] is known to be nonzero, the type checker reduces the [match] in the type of [hd'] to [A]. *)\n\n\n(** * 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": "paul-kline", "repo": "protosynth", "sha": "1b66397cea554f086cf4bdc95d61bfa269da890a", "save_path": "github-repos/coq/paul-kline-protosynth", "path": "github-repos/coq/paul-kline-protosynth/protosynth-1b66397cea554f086cf4bdc95d61bfa269da890a/cpdt/src/MoreDep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8887587883361618, "lm_q1q2_score": 0.7673468748917874}}
{"text": "Require Export InductionExercises.\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.\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\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. 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. reflexivity.\nQed.\n\nTheorem swap_swap_is_p : forall (p : natprod),\n  swap_pair (swap_pair p) = p.\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl. reflexivity. Qed.\n\n", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/NatList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7673468738540016}}
{"text": "Require Import Nat Arith.\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 count (count_arg0 : Nat) (count_arg1 : Lst) : Nat\n           := match count_arg0, count_arg1 with\n              | x, nil => zero\n              | x, cons y z => if Nat_beq x y then succ (count x z) else count 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_eq : forall (x y : Nat), Nat_beq x y = true -> x = y.\nProof.\n  intros.\n  generalize dependent y.\n  induction x.\n  - intros. destruct y.\n    + reflexivity.\n    + discriminate.\n  - intros. destruct y.\n    + discriminate.\n    + simpl in H. apply IHx in H. rewrite H. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Nat) (y : Nat) (z : Lst), not (eq x y) -> eq (count x (insort y z)) (count x z).\nProof.\n  intros.\n  induction z.\n  - simpl. destruct (Nat_beq x y) eqn:?.\n    + apply Nat_beq_eq in Heqb. contradiction.\n    + reflexivity.\n  - simpl. destruct (Nat_beq x n) eqn:?.\n    + destruct (less y n) eqn:?.\n      * simpl. destruct (Nat_beq x y) eqn:?.\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 (Nat_beq x y) eqn:?.\n        -- apply Nat_beq_eq in Heqb1. contradiction.\n        -- rewrite Heqb. reflexivity.\n      * simpl. rewrite Heqb. assumption.\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/goal71.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.767245217813628}}
{"text": "Require Export SQIR.UnitaryOps.\n\nLocal Open Scope nat_scope.\nLocal Open Scope ucom_scope.\n\nFixpoint GHZ (dim n : nat) : base_ucom dim :=\n  match n with\n  | 0        => SKIP\n  | 1        => H 0\n  | S (S n'' as n') => GHZ dim n' ; CNOT n'' n'      \n  end.\n\nLocal Open Scope R_scope.\nLocal Open Scope C_scope.\n\nDefinition ghz (n : nat) : Matrix (2^n) (1^n) := (* 1^n for consistency with kron_n *)\n  match n with \n  | 0 => I 1 \n  | S n' => 1/ √2 .* (n ⨂ ∣0⟩) .+ 1/ √2 .* (n ⨂ ∣1⟩)\n  end.\n\nLemma WF_ghz : forall n : nat, WF_Matrix (ghz n).\nProof.\n  induction n; simpl; auto with wf_db. \nQed.\n\nLemma typed_GHZ : forall dim n, (0 < dim)%nat -> (n <= dim)%nat -> uc_well_typed (GHZ dim n).\nProof.\n  intros. induction n.\n  - simpl. apply uc_well_typed_ID; assumption.\n  - simpl. destruct n. \n    + apply uc_well_typed_H; assumption.\n    + apply WT_seq.\n      apply IHn; try lia.\n      apply uc_well_typed_CNOT; lia.\nQed.      \n\nTheorem GHZ_correct' : forall dim n : nat, \n  (0 < dim)%nat -> (n <= dim)%nat -> uc_eval (GHZ dim n) × dim ⨂ ∣0⟩ = ghz n ⊗ (dim - n) ⨂ ∣0⟩.\nProof.\n  intros. induction n.\n  - simpl. rewrite denote_SKIP; try assumption. \n    Msimpl. replace (dim - 0)%nat with dim by lia.\n    reflexivity.\n  - destruct dim; try lia.\n    rewrite kron_n_assoc at 1; auto with wf_db.\n    destruct n.\n    + simpl; autorewrite with eval_db.\n      bdestructΩ (0 + 1 <=? S dim). \n      Msimpl_light.\n      replace (dim - 0)%nat with dim by lia.\n      rewrite kron_mixed_product.\n      Msimpl_light.\n      apply f_equal2; try reflexivity.\n      solve_matrix.\n    + replace (uc_eval (GHZ (S dim) (S (S n)))) with (uc_eval (CNOT n (S n)) × uc_eval (GHZ (S dim) (S n))) by easy.\n      rewrite <- kron_n_assoc.\n      2: auto with wf_db.\n      rewrite Mmult_assoc.\n      setoid_rewrite IHn. \n      2: lia.\n      (* annoyingly manual *)\n      replace (S dim - S (S n))%nat with (dim - (S n))%nat by lia.\n      replace (S dim - S n)%nat with (S (dim - (S n)))%nat by lia.\n      rewrite kron_n_assoc.\n      2: auto with wf_db.\n      unfold ghz. \n      autorewrite with eval_db.\n      clear IHn.\n      bdestruct_all.\n      clear H H1 H2. \n      apply Peano.le_S_n in H0.\n      replace (S n - n - 1)%nat with O by lia.      \n      replace (S dim - (n + (1 + 0 + 1)))%nat with (dim - S n)%nat by lia.\n      simpl I.\n      repeat rewrite kron_1_r.\n      simpl kron_n.\n      replace (2 ^ S (dim - S n))%nat with (2 * 2 ^ (dim - S n))%nat by unify_pows_two.\n      replace (1 ^ S (dim - S n))%nat with (1 * 1 ^ (dim - S n))%nat by (repeat rewrite Nat.pow_1_l; lia).\n      rewrite <- (kron_assoc _ (∣0⟩)); auto with wf_db.\n      2:{ apply WF_plus; apply WF_scale; apply WF_kron; auto with wf_db;\n          rewrite !Nat.pow_1_l; reflexivity. }\n      rewrite kron_plus_distr_l.\n      rewrite (kron_plus_distr_r _ _ _ _ _ _ (∣0⟩)). \n      repeat rewrite Mscale_kron_dist_l.\n      replace (2 ^ S n)%nat with (2 ^ n * 2)%nat by unify_pows_two.\n      replace (1 ^ S n)%nat with (1 ^ n * 1)%nat by (repeat rewrite Nat.pow_1_l; lia).\n      rewrite 2 (kron_assoc _ _ (∣0⟩)) by auto with wf_db.\n      replace (2 ^ (1 + 0 + 1))%nat with (2 * 2)%nat by reflexivity. \n      replace (2 ^ n * 2 * 2)%nat with (2 ^ n * (2 * 2))%nat by lia.\n      replace (1 ^ n * 1 * 1)%nat with (1 ^ n * (1 * 1))%nat by lia.\n      replace (2 ^ S dim)%nat with (2 ^ n * (2 * 2) * 2 ^ (dim - S n))%nat.\n      2: simpl; unify_pows_two.\n      replace (2 * 2 ^ 0)%nat with 2%nat by reflexivity.\n      replace (1 ^ S dim)%nat with (1 ^ n * (1 * 1) * 1 ^ (dim - S n))%nat.\n      2: repeat rewrite Nat.pow_1_l; reflexivity.\n      rewrite kron_mixed_product.\n      rewrite Mmult_plus_distr_r.\n      repeat rewrite Mmult_plus_distr_l.\n      repeat rewrite Mscale_mult_dist_r.\n      repeat rewrite kron_mixed_product.\n      repeat rewrite (Mmult_assoc _ (_)†). \n      Qsimpl.\n      repeat rewrite <- kron_assoc by auto with wf_db.\n      rewrite Mplus_comm.\n      reflexivity.\nQed.\n\nTheorem GHZ_correct : forall n : nat, \n  (0 < n)%nat -> uc_eval (GHZ n n) × n ⨂ ∣0⟩ = ghz n.\nProof.\n  intros.\n  rewrite GHZ_correct'; try lia.\n  replace (n - n)%nat with O by lia.\n  simpl.\n  rewrite kron_1_r.\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/ghz/GHZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7672452117505412}}
{"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 eqb (n m: Nat) : 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\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 len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\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\nTheorem insort_len: forall (n: Nat) (x : Lst), len (insort n x) = succ (len x).\n  intro.\n  induction x.\n  { simpl. destruct (less n n0).\n    {\n      simpl. reflexivity.\n    }\n    {\n      simpl. rewrite IHx.\n      reflexivity.\n    }\n  }\n  {\n    simpl. reflexivity.\n  }\nQed.\n\nTheorem theorem0 : forall (x : Lst), eq (len (sort x)) (len x).\nProof.\n  induction x; simpl; try reflexivity.\n  rewrite insort_len.\n  f_equal; 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/CLAM/goal48.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7672088705721944}}
{"text": "\nRequire Import List.\nRequire Import ZArith. \nFrom mathcomp Require Import ssreflect ssrnat ssrbool eqtype seq.\n\nRequire Import tactics.\nRequire Import arith.\n\nDefinition occ (zs: seq Z) (z: Z) : nat :=\n  count (fun z'=> Z.eqb z' z) zs.\n\nEval compute in (occ ([:: 2; -43; 2; 32; 22; -43; -2; 3; -43]) (-43))%Z.\n\nLemma occ_cat:\n  forall zs1 zs2 z,\n    occ (zs1 ++ zs2) z = occ zs1 z + occ zs2 z.\nProof.\n  move=> zs1 zs2 z.\n  rewrite /occ.\n  rewrite count_cat=>//.\nQed. \n\nDefinition sorted (zs: seq Z) : Prop :=\n  forall i j, \n    0 <= i -> i < j -> j < size zs ->\n    (nth (0%Z) zs i <= nth (0%Z) zs j)%Z.\n\nLemma empty_lst_sorted: sorted [:: ].\nProof.\n  rewrite /sorted. move=> i j H_0i H_ij H_jsz.\n  simpl in H_jsz. inv H_jsz.\nQed.\n\nLemma singleton_sorted: forall (z:Z), sorted [:: z].\nProof.\n  move=> z. rewrite /sorted.\n  move=> i j H_0i H_ij H_jsz.\n  simpl in H_jsz.\n  case En: j=>[ | j0].\n  - rewrite En in H_ij. rewrite ltn0 in H_ij. inv H_ij.\n  - rewrite En in H_jsz. inv H_jsz. \nQed. \n\n(* zs1 is a continuous fragment of zs2 *)\nDefinition lst_frag (b0: Z) zs1 zs2 :=\n  forall i,\n    i < size zs1 ->\n    ((i + Z.to_nat b0 < size zs2) /\\ \n     nth (0%Z) zs1 i = nth (0%Z) zs2 (i + Z.to_nat b0)).\n\nLemma sorted_lst_frag: \n  forall b0 zs1 zs2,\n    lst_frag b0 zs1 zs2 -> sorted zs2 -> sorted zs1.\nProof.\n  move=> b0 zs1 zs2 H_lst_frag H_sorted2.\n  rewrite /lst_frag in H_lst_frag.\n  rewrite /sorted in H_sorted2.\n  rewrite /sorted.\n  move=> i j H_0i H_ij H_jsz.\n  have H_isz: i < size zs1 by apply ltn_trans with (n:=j)=>//. \n  specialize (H_lst_frag i H_isz) as H_corr1.\n  specialize (H_lst_frag j H_jsz) as H_corr2.\n  inversion H_corr1 as [H_i_b0_sz1 H_nth1]; clear H_corr1.\n  inversion H_corr2 as [H_j_b0_sz2 H_nth2]; clear H_corr2.\n  rewrite H_nth1. rewrite H_nth2.\n  apply H_sorted2.\n  apply leq_trans with (n:=i); auto.\n  apply leq_addr.\n  rewrite ltn_add2r; auto.\n  auto.\nQed.\n\nLemma sorted_concat:\n  forall zs1 zs2,\n    sorted zs1 ->\n    sorted zs2 -> \n    (nth 0 zs2 0 >= nth 0 zs1 (size zs1 - 1))%Z ->\n    sorted (zs1 ++ zs2).\nProof.\n  move=> zs1 zs2 H_sorted1 H_sorted2 H_ge.\n  case En1: zs1=> [ | z1 zs1' ].\n  - move=>//.\n  - rewrite <- En1.\n    unfold sorted in *.\n    move=> i j H_0i H_ij H_jsz.\n    have: (j < size zs1) || ~~(j < size zs1)\n      by case (j < size zs1); auto.\n    move /orP=> H_case_j.\n    inversion H_case_j as [H_j_left | H_j_right].\n    + have H_i_left: i < size zs1 \n        by apply ltn_trans with (n:=j); auto.\n      rewrite nth_cat. rewrite H_i_left.\n      rewrite nth_cat. rewrite H_j_left.\n      apply H_sorted1; auto.\n    + have H_j_r: ~~ (j < size zs1) by auto.\n      rewrite <- leqNgt in H_j_right.\n      have: (i < size zs1) || ~~(i < size zs1)\n        by case (i < size zs1); auto.\n      move /orP=> H_case_i.\n      inversion H_case_i as [H_i_left | H_i_right].\n      * 2: { (* i j both pointing into zs2 *)\n          case En: (i < size zs1).\n          rewrite En in H_i_right; inv H_i_right.\n          case En': (j < size zs1). \n          rewrite En' in H_j_r; inv H_j_r.\n          have H_lt_or_eq: size zs1 < j \\/ size zs1 = j.\n          {\n            rewrite leq_eqVlt in H_j_right.\n            move: H_j_right; move /orP=>H_or.\n            inv H_or.\n            right. move: H; move /eqP=>//. left=>//.\n          }\n          inv H_lt_or_eq.\n          rewrite nth_cat. rewrite En.\n          rewrite nth_cat. rewrite En'.\n          apply H_sorted2; auto with arith.\n          apply ltn_sub2r; auto.\n          rewrite size_cat in H_jsz.\n          rewrite <- ltn_subLR in H_jsz; auto.\n          rewrite <-H in H_ij. rewrite H_ij in En. inv En.\n        }\n      * (* i < size zs1, size zs1 <= j*)\n        rewrite nth_cat. rewrite H_i_left.\n        have: (j < size zs1)=false by apply: negPf=>//.\n        rewrite nth_cat. move->.\n        clear H_case_i; clear H_case_j.\n        have H_le1: (nth (0%Z) zs1 i <= nth (0%Z) zs1 (size zs1 - 1))%Z.\n        {\n          have H_i_le: i <= size zs1 - 1.\n          {\n            apply lt_1_le in H_i_left.\n            apply leq_sub2r with (p:=1) in H_i_left.\n            rewrite <- addnBA in H_i_left=>//.\n            rewrite sub_zero in H_i_left.\n            rewrite add_zero in H_i_left=>//.\n          }\n          rewrite leq_eqVlt in H_i_le.\n          move: H_i_le; move /orP=> H_or.\n          inv H_or. move: H; move /eqP->. apply: Z.le_refl.\n          apply H_sorted1; auto.\n          rewrite ltn_subrL.\n          apply /andP. apply: conj. auto. rewrite En1. simpl; auto.\n        }\n        have H_le2: (nth 0 zs2 0 <= nth 0 zs2 (j - size zs1))%Z.\n        {\n          rewrite leq_eqVlt in H_j_right.\n          move: H_j_right; move /orP=> H_or.\n          inv H_or.\n          move: H; move /eqP->. rewrite sub_zero. apply: Z.le_refl.\n          apply H_sorted2; auto.\n          rewrite subn_gt0=>//.\n          rewrite size_cat in H_jsz.\n          rewrite <- ltn_subLR in H_jsz; auto.\n        }\n        apply Z.le_trans with (m:= nth (0%Z) zs1 (size zs1 - 1)); auto.\n        apply Z.le_trans with (m:= nth (0%Z) zs2 0); auto.\n        auto with zarith.\nQed.         \n\nLemma sorted_tail:\n  forall z zs, sorted (z :: zs) -> sorted zs.\nProof.\n  move=> z zs H_sorted.\n  rewrite /sorted in H_sorted.\n  rewrite /sorted.\n  move=> i j H_0i H_ij H_j_sz.\n  specialize (H_sorted (i.+1) (j.+1)).\n  simpl in H_sorted.\n  apply H_sorted; auto with arith.\nQed.\n\nLemma sorted_occ_le:\n  forall zs z, sorted zs -> 0 < occ zs z -> ((nth (0%Z) zs 0) <= z)%Z.\nProof. \n  elim.\n  - move=> z H_sorted H_lt. simpl in H_lt. inv H_lt.\n  - move=> a l IH z H_sorted H_lt.\n    assert (H_sorted0:=H_sorted).\n    apply sorted_tail in H_sorted.\n    simpl in H_lt.\n    case En: (a =? z)%Z.\n    + move: En. move /Z.eqb_eq. move->. simpl. auto with zarith.\n    + simpl. \n      rewrite En in H_lt. simpl in H_lt. rewrite add_zero_l in H_lt.\n      specialize (IH z H_sorted H_lt).\n      case Enl: l=> [ | a' l'].\n      rewrite Enl in H_lt. simpl in H_lt. inv H_lt.\n      rewrite Enl in IH. simpl in IH.\n      rewrite Enl in H_sorted0. rewrite /sorted in H_sorted0.\n      specialize (H_sorted0 0 1).\n      simpl in H_sorted0.\n      apply Z.le_trans with (m:=a'); auto with zarith.\nQed.\n\nLemma occ_sorted_hd_corr:\n  forall zs zs1 zs2,\n    size zs > 0 -> \n    sorted zs ->\n    sorted zs1 ->\n    sorted zs2 ->\n    (forall z, occ zs z = occ zs1 z + occ zs2 z) ->\n    (size zs1 > 0 /\\ nth (0%Z) zs 0 = nth (0%Z) zs1 0 \\/\n     size zs2 > 0 /\\ nth (0%Z) zs 0 = nth (0%Z) zs2 0).\nProof.\n  move=> zs zs1 zs2 H_0_zs\n            H_sorted_zs H_sorted_zs1 H_sorted_zs2 H_occ.\n  have H_pos_occ: occ zs (nth (0%Z) zs 0) > 0.\n  {\n    simpl. case En: zs => [ | z zs']. rewrite En in H_0_zs.\n    simpl in H_0_zs. inv H_0_zs. simpl.\n    case En': (z =? z)%Z. auto with arith.\n    move: En'. move /Z.eqb_neq. auto with zarith.\n  }\n  specialize (H_occ (nth (0%Z) zs 0)) as H_occ'.\n  rewrite H_occ' in H_pos_occ.\n  have H_or: 0 < occ zs1 (nth 0%Z zs 0) \\/ 0 < occ zs2 (nth 0%Z zs 0).\n  {\n    case En': (occ zs1 (nth 0%Z zs 0)) => [ | n']. \n    rewrite En' in H_pos_occ. right. auto with arith.\n    left. auto with arith.\n  }\n  inversion H_or as [H_pos_occ_zs1 | H_pos_occ_zs2]; clear H_or.\n  -\n    have H_pos_occ_zs1': 0 < occ zs1 (nth 0%Z zs1 0).\n    {\n      case En: zs1 => [| z0 zs1'].\n      rewrite En in H_pos_occ_zs1. simpl in H_pos_occ_zs1. inv H_pos_occ_zs1.\n      simpl.\n      have: (z0 =? z0)%Z = true by apply Z.eqb_refl.\n      move->. auto with arith.\n    }\n    have H_le: (nth 0%Z zs 0 <= nth 0%Z zs1 0)%Z.\n    {\n      apply sorted_occ_le; auto.\n      rewrite (H_occ (nth 0%Z zs1 0)).\n      apply ltn_leq_trans with (n:=occ zs1 (nth 0%Z zs1 0)); auto.\n      apply leq_addr.\n    }\n    have H_le': (nth 0%Z zs1 0 <= nth 0%Z zs 0)%Z \n        by apply sorted_occ_le; auto.\n    left.\n    apply: conj.\n    destruct zs1. simpl in H_pos_occ_zs1. inv H_pos_occ_zs1. simpl; auto.\n    auto with zarith.\n  -\n    have H_pos_occ_zs2': 0 < occ zs2 (nth 0%Z zs2 0).\n    {\n      case En: zs2 => [| z0 zs2'].\n      rewrite En in H_pos_occ_zs2. simpl in H_pos_occ_zs2. inv H_pos_occ_zs2.\n      simpl.\n      have: (z0 =? z0)%Z = true by apply Z.eqb_refl.\n      move->. auto with arith.\n    }\n    have H_le: (nth 0%Z zs 0 <= nth 0%Z zs2 0)%Z.\n    {\n      apply sorted_occ_le; auto.\n      rewrite (H_occ (nth 0%Z zs2 0)).\n      apply ltn_leq_trans with (n:=occ zs2 (nth 0%Z zs2 0)); auto.\n      apply leq_addl.\n    }\n    have H_le': (nth 0%Z zs2 0 <= nth 0%Z zs 0)%Z \n        by apply sorted_occ_le; auto.\n    right.\n    apply: conj.\n    destruct zs2. simpl in H_pos_occ_zs2. inv H_pos_occ_zs2. simpl; auto.\n    auto with zarith.\nQed.     \n\nLemma sorted_hd_nxt:\n  forall z zs,\n    size zs > 0 -> \n    sorted (z :: zs) ->\n    (z <= (nth 0%Z zs 0))%Z.\nProof.\n  move=> z zs H_sz H_sorted. \n  specialize (H_sorted 0 1).\n  have H': nth 0%Z (z :: zs) 1 = nth 0%Z zs 0.\n  { destruct zs. inv H_sz. simpl; auto. }\n  rewrite H' in H_sorted.\n  have H'': nth 0%Z (z :: zs) 0 = z by simpl; auto.\n  rewrite H'' in H_sorted.\n  apply H_sorted; auto.\nQed.   \n  \n  \n  \n", "meta": {"author": "lixm", "repo": "ind-verify", "sha": "9846f3f254b74a31f36225d2f0454752ebae8256", "save_path": "github-repos/coq/lixm-ind-verify", "path": "github-repos/coq/lixm-ind-verify/ind-verify-9846f3f254b74a31f36225d2f0454752ebae8256/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7671144885446624}}
{"text": "Require Import ssreflect ssrbool.\n\n\nLemma negb_invol : forall b, negb (negb b) = b.\ncase.\n  simpl.\n  reflexivity.\nreflexivity.\nQed.\n\nFixpoint evenb n :=\n  match n with\n| 0 => true\n| S n => negb (evenb n)\n  end.\n\n\n\nInductive even : nat -> Prop :=\n| even0 : even 0\n| evenS : forall n, even n -> even (S (S n)).\n\nLemma e1 : forall n, even n -> evenb n.\n  move => n e.\n  induction e.\n    done.\n  simpl.\n  rewrite negb_invol.\n  assumption.\nQed.\n\nDefinition pred n :=\n  match n with\n  | S m => m\n  | 0 => 0\n  end.\n\nLemma evenb_even_aux :\n  forall n,\n    (evenb n -> even n)\n    /\\(evenb (pred n) -> even (pred n)).\n  elim => [ | [|n] [hn1 hn2]]; simpl.\n(* two remarks :\n   - we do [| n] instead of n, that is we have three cases :\n     0, (S 0), (S (S n))\n   - I write [hn1 hn2] that is I immediately cut the induction hypothesis hn1/\\h\nn2 in two (hn1 and hn2)  *)\n\n(* when n = 0 both cases are solved by even_0 *)\n  - split; move => e; apply even0.\n    \n(* n = 1 is quite easy *)\n- split.\n    done.\n  move => e; apply even0.\n\n(* the case (S (S n)) *)\n- split.\n    rewrite negb_invol.\n    move => h.\n    apply evenS.\n    simpl in hn2.\n    apply hn2.\n    assumption.\n\n  move => h.\n  apply hn1.\n  simpl.\n  assumption.\nQed.\n\n(* the lemma is just a corolary *)\nLemma evenb_even : forall n, evenb n -> even n.\nProof.\nmove => n e.\nmove: (evenb_even_aux n) => [h1 h2].\nby apply h1.\nQed.\n\nDefinition evenl n := exists p, n = p + p.\n\nLemma addnS : forall n m, n + S m = S (n+m).\nelim => [//=|n hn] m /=.\nby rewrite hn.\nQed.\n\nLemma even_l : forall n, even n -> evenb n.\nProof.\nmove => n h.\ninduction h.\n  trivial.\nsimpl.\nrewrite negb_invol.\nassumption.\nQed.\n\nLemma even_half :\n  forall n, even n -> evenl n.\nProof.\nmove => n h.\ninduction h.\n  by exists 0.\nmove: IHh => [p hp].\nexists (S p).\nby rewrite /= addnS hp.\n (* the /= just inserts a \"simpl\" in the\n    rewrite sequence *)\nQed.\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/Tutorial_5/l5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7670577623721325}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Lists.\n\nInductive list(X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nCheck list.\n\nCheck nil.\n\nCheck O.\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\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(* Exercise mumble grumble *)\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 bool (b a 5).\nCheck e bool true.\nCheck e mumble (b c 0).\nCheck c.\n\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count : list X :=\n  match count with \n  | O => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat'.\nCheck repeat.\n\nFixpoint repeat'' X x count : list X :=\n  match count with \n  | O => nil _\n  | S count' => cons X x (repeat'' _ x count')\n  end.\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  | O => 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 => O\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\nCheck @nil.\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\n(* Exercise poly exercises *)\nTheorem app_nil_r : forall (X:Type),\n  forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X.\n  intros l.\n  induction l as [| h t H].\n  - reflexivity.\n  - simpl. rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem app_assoc : forall A (l m n : list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A.\n  intros l m n.\n  induction l as [| h t H].\n  - simpl. reflexivity.\n  - simpl. rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X.\n  intros l1 l2.\n  induction l1 as [| h t H].\n  - reflexivity.\n  - simpl. rewrite -> H.\n  reflexivity.\n  Qed.\n\n(* Exercise more poly exercises *)\n\nTheorem rev_app_distr : forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X.\n  intros l1 l2.\n  induction l1 as [| h t H].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> H. rewrite <- app_assoc.\n  reflexivity.\n  Qed.\n\nTheorem rev_involutive : forall (X:Type), \n  forall (l : list X),\n  rev (rev l) = l.\nProof.\n  intros X.\n  intros l.\n  induction l as [| h t H].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n  rewrite -> H.\n  simpl.\n  reflexivity.\n  Qed.\n\nInductive prod (X Y : Type) : Type :=\n  | pair : X->Y->prod X 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.\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\n(* Exercise combine checks *)\nCheck @combine.\nCompute (combine [1;2][false;false;true;true]).\n\n(* Exercise split *)\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))\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 nth_error{X : Type}(l : list X)(n : nat)\n  : option X :=\n  match l with \n  | [] => None\n  | a :: ll => \n    if beq_nat n O\n    then Some a\n    else nth_error ll (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 hd_error poly *)\n\nDefinition hd_error{X:Type}(l:list X) : option X\n  := match l with \n  | [] => None\n  | h::_ => Some h\n  end.\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\nDefinition doit3times{X:Type}(f:X->X)(n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\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 => \n    if test h then \n    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.\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (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 oddb 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' : \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\n(* Exercise filter even gt7 *)\n\nSearch evenb.\nSearch leb.\n\nDefinition filter_even_gt7(l:list nat) : list nat\n  := \n  filter (fun l => andb (evenb l) (negb (leb l 7))) l.\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(* Exercis partition *)\nFixpoint partition{X:Type}\n          (test:X->bool)\n          (l:list X)\n      : list X * list X \n  :=\n  match l with \n  | [] => ([], [])\n  | h::t => match (test h) with \n    | true => (h::fst(partition test t), \n               snd(partition test t))\n    | false => (fst(partition test t), \n                h::snd(partition test t))\n    end\n  end.\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.\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\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(* Exercise map rev *)\n\nLemma map_distr : forall (X Y : Type)\n  (f:X->Y)(l:list X)(h:X),\n  map f (l ++ [h]) = (map f l) ++ [f h]. \nProof.\n  intros X Y. intros f l h.\n  induction l as [| hh tt H].\n  - reflexivity.\n  - simpl. rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem map_rev : forall (X Y : Type)\n    (f:X->Y)(l:list X),\n  map f (rev l) = rev (map f l).\nProof. \n  intros X Y.\n  intros f l.\n  induction l as [| h t H].\n  - simpl. reflexivity.\n  - simpl. Search rev.\n  rewrite <- H.\n  rewrite -> map_distr.\n  reflexivity.\n  Qed.\n\n(* Exercise flat map *)\nFixpoint flat_map{X Y : Type}(f:X->list Y)\n    (l:list X) : (list Y)\n  :=\n  match l with \n  | [] => []\n  | h::t => \n  (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}\n    (f:X->Y)(xo:option X) : option Y \n  :=\n  match xo with \n  | None => None\n  | Some x => Some (f x)\n  end.\n\nFixpoint fold{X Y : Type}\n  (f:X->Y->Y)(l:list X)(b:Y) : Y\n  :=\n  match l with \n  | nil => b\n  | h::t => f h (fold f t b)\n  end.\n\nCheck (fold andb).\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\n\nDefinition plus3 := plus 3.\nCheck plus3.\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(* Exercise fold length *)\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_add: forall X (h:X)(l:list X),\n  fold_length (h::l) = S (fold_length l).\nProof.\n  intros X h l. induction l as [| x l' IHl'].\n  - reflexivity.\n  - reflexivity.\n  Qed.\n\nTheorem fold_length_correct: forall X (l:list X),\n  fold_length l = length l.\nProof.\n  intros X l. induction l as [| h t IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHl'.\n  apply fold_length_add.\n  Qed.\n\n(* Exercise fold map *)\n\n(* Exercise currying *)\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  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. Check @prod_uncurry.\n\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  unfold fst.\n  unfold snd.\n  reflexivity.\n  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 X Y Z f p.\n  unfold prod_curry.\n  unfold prod_uncurry.\n  destruct p as [x y].\n  unfold fst. unfold snd.\n  reflexivity.\n  Qed.\n\n(* Exercise church numerals *)\n\nModule Church.\n\nDefinition nat := forall X:Type, (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 zero:nat :=\n  fun(X:Type)(f:X->X)(x:X) => x.\n\n\n\nEnd Church.\n\nEnd Exercises.\n\n", "meta": {"author": "rpgzysb", "repo": "SoftwareFoundation", "sha": "4f987efcec24d880908edcb4f1c1cd3926c60291", "save_path": "github-repos/coq/rpgzysb-SoftwareFoundation", "path": "github-repos/coq/rpgzysb-SoftwareFoundation/SoftwareFoundation-4f987efcec24d880908edcb4f1c1cd3926c60291/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.7670028646773763}}
{"text": "Require Import Arith.\nImport IfNotations.\n\nInductive term :=\n  | TVar (index : nat)\n  | TArrow (lhs rhs : term)\n  | TNum\n  | TBool.\n\nFixpoint term_eq (τ0 τ1 : term) : bool :=\n  match τ0, τ1 with\n  | TVar n0, TVar n1 => n0 =? n1\n  | TArrow l0 r0, TArrow l1 r1 => term_eq l0 l1 && term_eq r0 r1\n  | TNum, TNum | TBool, TBool => true\n  | _, _ => false\n  end.\n\nFixpoint occurs (τ : term) (n : nat) : bool :=\n  match τ with\n  | TVar n0 => n0 =? n\n  | TArrow l r => occurs l n || occurs r n\n  | TNum | TBool => false\n  end.\n\nDefinition substitution : Type := nat -> option term.\n\nDefinition empty : substitution := fun _ => None.\n\nDefinition insert (σ : substitution) (n : nat) (t : term) : option substitution :=\n  if occurs t n then None\n  else Some (fun n1 => if n1 =? n then Some t else σ n).\n\nFixpoint unify (τ0 τ1 : term) (σ : substitution) : option substitution :=\n  match τ0, τ1 with\n  | TVar n0, _ => insert σ n0 τ1\n  | _, TVar n1 => insert σ n1 τ0\n  | TArrow l0 r0, TArrow l1 r1 =>\n      let σ0 := unify l0 l1 σ in if σ0 is Some σ0 then\n      let σ1 := unify r0 r1 σ0 in if σ1 is Some σ1 then\n      Some σ1\n      else None else None\n  | TNum, TNum => Some σ\n  | TBool, TBool => Some σ\n  | _, _ => None\n  end.\n\nCompute unify (TVar 0) (TVar 0) empty.\nCompute unify (TVar 0) (TVar 1) empty.\nCompute unify (TVar 0) (TArrow (TVar 0) (TVar 2)) empty.\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/hm/hm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8175744784160989, "lm_q1q2_score": 0.7669862573190475}}
{"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 [even]), 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 [even] property.  *)\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(** 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 [even] declares that [ev_0 : even\n    0].  Instead of \"[ev_0] has type [even 0],\" we can say that \"[ev_0]\n    is a proof of [even 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                  even n ->\n                  even (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 [even\n    n] -- and yields evidence for the proposition [even (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [even]. *)\n\nTheorem ev_4 : even 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     : even 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(* ===> even 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 [even 2] and [even 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, even n -> even (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': even 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'' : 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\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''' : even 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) : even 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)  \n\n    Give a tactic proof and a proof object showing that [even 8]. *)\n\nTheorem ev_8 : even 8.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nDefinition ev_8' : even 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, even n -> even (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, even n ->\n    even (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, even n -> even (4 + n) :=\n  fun (n : nat) => fun (H : even 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 : 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(** 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, [even 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 : even n), even (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 (_ : even n), even (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, even n -> even (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\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 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\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 [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) : 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, optional (conj_fact)  \n\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(** ** 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, standard, optional (or_commut'')  \n\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(* ================================================================= *)\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 => even n).\n(* ===> exists n : nat, even n\n        : Prop *)\n\n(** Here's how to define an explicit proof object involving [ex]: *)\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: 2 stars, standard, optional (ex_ev_Sn)  \n\n    Complete the definition of the following proof object: *)\n\nDefinition ex_ev_Sn : ex (fun n => even (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 slight 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 members of this family:\n    applying the constructor [eq_refl] to a type [X] and a single\n    value [x : X], 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 equalities up\n    to now is essentially just shorthand 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\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: 5 stars, standard, optional (leibniz_equality__equality)  \n\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\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(* 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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7669824899247142}}
{"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.  Abort.\n\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\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  assert (n = m -> [n;o] = [m;p]).\n    rewrite (eq2 n m). reflexivity.\n    rewrite eq1. reflexivity.\n  rewrite (H eq1). reflexivity.\nQed.\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. 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 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 l l' H. rewrite H.\n  symmetry. 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\n - apply: trys to simplify first, and applies hypothesis / lemma to the goal.\n     requires exact match. might need to prove preconditions afterwards.\n - rewrite: can rewrite using a hypothesis / lemma both from left to right\n     and from right to left. it can be use to rewrite only a portion of the conclusion\n     does less thing than \"apply\".\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 n m o p eq1 eq2.\n  apply trans_eq with m. 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 i j eq1 eq2. inversion eq2. reflexivity.\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 i j eq1 eq2. inversion eq1. 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(** 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 n eq1. destruct n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S 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. destruct n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". inversion eq1.\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\". intros m eq1. simpl in eq1. rewrite eq1.\n    induction m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". rewrite <- plus_n_Sm in eq1. inversion eq1.\n  Case \"n = S n'\". intros m eq2.\n  rewrite <- plus_n_Sm in eq2.\n    destruct m as [| m'].\n    SCase \"m = 0\". simpl in eq2. inversion eq2.\n    SCase \"m = S m'\". simpl in eq2.\n      assert (S (m' + S m') = S (S (m' + m'))).\n        rewrite <- plus_n_Sm. reflexivity.\n      rewrite H in eq2. inversion eq2.\n      apply f_equal. apply IHn'.  apply H1.\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 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\". symmetry. apply beq_nat_0_l. apply H.\n  Case \"n = S n'\". intros m eq1. destruct m as [|m'].\n    SCase \"m = 0\". inversion eq1.\n    SCase \"m = S m'\". apply f_equal. apply IHn'.\n      simpl in eq1. apply eq1.\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  We want to prove: suppose m n are two natural numbers, if [beq_nat n m]\n  returns [true], then [m = n].\n\n  We will prove it by induction on n.\n\n  - Base case: n = 0.\n    Since we know that for any given natural number l, if [beq_nat 0 l = true],\n    then [l = 0]. The conclusion follows by letting [m = l], and we have [m = 0 = n].\n  - Inductive step: n = S n'\n    Assume for any given n' < n, the conclusion holds. We need to prove\n    if [beq_nat (S n') m = true] then [m = S n' = n] for any natural number m.\n\n    This can be proved by considering two cases:\n\n    - Case #1: m = 0\n\n    We know that if [beq_nat (S n') 0 = true], we must have [S n' = 0],\n    which is impossible.\n\n    - Case #2: m = S m' > 0\n\n    Since [beq_nat n m = beq_nat (S n') (S m') = true], by definition, we also have:\n    [beq_nat n' m' = true]. And the conclusion holds by applying the hypothesis,\n    which is: since [beq_nat n' m' = true], we have [n' = m'], thus [S n' = S m']\n    therefore [n = m].\n\n*)\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 n X l eq1. generalize dependent n.\n  induction l as [|x l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons x l'\". intros n eq1. simpl in eq1. destruct n.\n    SCase \"n = 0\". inversion eq1.\n    SCase \"n = S n'\". apply IHl'. inversion eq1. 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\n     We will prove it by induction on [l].\n\n     - Base case: l = nil\n\n     The conclusion follows by observing that\n     [length l = n = 0] and [index n l = None]\n\n     - Inductive step: suppose l = x :: l',\n       if [length l' = n'] then [index n' l' = None].\n\n     Since [l] has at least one element, we know\n     [length l = n > 0]. Let [n = S n'], by defintion of [length],\n     we know [length l' = n'], therefore [index n' l' = None].\n     The conclusion follows by observation that [length l = S (length (x :: l')) = n]\n     and [index (S n') (x :: l') = None].\n\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. generalize dependent n. induction l as [|x l'].\n  Case \"l = nil\". intros n eq1. simpl in eq1.\n    rewrite <- eq1. reflexivity.\n  Case \"l = cons x l'\". intros n eq1. simpl in eq1. destruct n.\n    SCase \"n = 0\". inversion eq1.\n    SCase \"n = S n'\". inversion eq1. rewrite H0. simpl.\n      apply f_equal. apply IHl'. apply H0.\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. generalize dependent n.\n  induction l1 as [|x1 l1'].\n  Case \"l1 = nil\". intros n eq1. simpl in eq1. destruct n.\n    SCase \"n = 0\". inversion eq1.\n    SCase \"n = S n'\". inversion eq1. apply f_equal. reflexivity.\n  Case \"l1 = cons x1 l1'\". intros n eq1. simpl in eq1. destruct n.\n    SCase \"n = 0\". inversion eq1.\n    SCase \"n = S n'\". apply f_equal. apply IHl1'.\n      inversion eq1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice) *)\n(** Prove this by induction on [l], without using app_length. *)\n\nLemma app_nil : forall (X : Type) (l : list X),\n  l ++ [] = l.\nProof.\n  intros X l. induction l as [|x l'].\n  Case \"l = nil\". reflexivity.\n  Case \"l = cons x l'\". simpl. rewrite IHl'. reflexivity.\nQed.\n\nLemma app_commute_under_length : forall (X : Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length (l2 ++ l1).\nProof.\n  intros X l1 l2. induction l1 as [|x l1'].\n  Case \"l1 = nil\". apply f_equal. rewrite app_nil. reflexivity.\n  Case \"l1 = cons x l1'\". simpl. rewrite IHl1'. apply app_length_cons with x.\n    reflexivity.\nQed.\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. generalize dependent n. induction l as [|x l'].\n  Case \"l = nil\". intros n eq1. simpl in eq1.\n    simpl. rewrite <- eq1. reflexivity.\n  Case \"l = cons x l'\". intros n eq1. destruct n.\n    SCase \"n = 0\". simpl in eq1. inversion eq1.\n    SCase \"n = S n'\". simpl in eq1. inversion eq1.\n      rewrite eq1. simpl. rewrite app_commute_under_length. simpl.\n      rewrite <- plus_n_Sm. apply f_equal. apply f_equal.\n      apply IHl'. apply H0.\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 x1 x2 k1 k2 f. unfold override.\n  destruct (beq_nat k1 k2).\n  Case \"beq_nat k1 k2 = true\". reflexivity.\n  Case \"beq_nat k1 k2 = false\". reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (combine_split) *)\n(** Complete the proof below *)\n\nLemma pair_fst_snd : forall (X Y : Type) (p : X * Y),\n  p = (fst p, snd p).\nProof.\n  intros X Y p. destruct p. 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.\n  intros X Y l. induction l as [|(x,y) l'].\n  Case \"l = nil\". intros l1 l2 eq1.\n    simpl in eq1. inversion eq1. reflexivity.\n  Case \"l = (x,y) :: l'\". intros l1 l2 eq1. unfold combine.\n    inversion eq1. apply f_equal. apply IHl'.\n    apply pair_fst_snd.\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. destruct (f b) eqn:Hfb.\n  Case \"f b = true\". destruct b eqn:Hb.\n    SCase \"b = true\". rewrite Hfb. apply Hfb.\n    SCase \"b = false\". destruct (f true) eqn:Hfb'.\n      SSCase \"f true = true\". apply Hfb'.\n      SSCase \"f true = false\". apply Hfb.\n  Case \"f b = false\". destruct b eqn:Hb.\n    SCase \"b = true\". destruct (f false) eqn:Hfb'.\n      SSCase \"f false = true\". apply Hfb.\n      SSCase \"f false = false\". apply Hfb'.\n    SCase \"b = false\". rewrite Hfb. apply Hfb.\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 X x1 k1 k2 f eq1. unfold override.\n  destruct (beq_nat k1 k2) eqn:Heq12.\n  Case \"beq_nat k1 k2 = true\".\n    assert (k1 = k2). apply beq_nat_true. apply Heq12.\n    rewrite <- H. symmetry. apply eq1.\n  Case \"beq_nat k1 k2 = false\". 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. induction n as [|n'].\n  Case \"n = 0\". intros m. simpl. destruct m as [|m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". reflexivity.\n  Case \"n = S n'\". intros m. simpl. destruct m as [|m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". 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   We prove it by induction on [n].\n\n   - Base case: n = 0.\n\n     - if m = 0, then beq_nat m n = true = beq_nat n m.\n     - if m > 0, then beq_nat m n = false = beq_nat n m.\n\n   - Inductive step: n = S n'.\n\n     The hypothesis is: for any natural number [m], we have:\n     [beq_nat n' m = beq_nat m n'].\n\n     - if m = 0, then [beq_nat (S n') m = false = beq_nat m (S n')].\n     - if m = S m' > 0, we need to prove\n       [beq_nat (S n') (S m') = beq_nat n' m' = beq_nat m' n' = beq_nat (S m') (S n')].\n       This follows by applying the hypothesis.\n\n    Therefore for any natural number [n] and [m], we have [beq_nat n m = beq_nat m n].\n\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans) *)\nLemma beq_nat_n_n : forall n,\n  beq_nat n n = true.\nProof.\n  intros n. induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. 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 m p Hnm Hmp.\n  assert (n = m). apply beq_nat_true. apply Hnm.\n  assert (m = p). apply beq_nat_true. apply Hmp.\n  assert (n = p). apply trans_eq with m. apply H.\n  apply H0. rewrite H1. apply beq_nat_n_n.\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 : Type) (Y : Type)\n         (l1 : list X) (l2 : list Y) (l : list (X * Y)),\n      length l1 = length l2\n   -> combine l1 l2 = l\n   -> split l = (l1,l2).\n(** [] *)\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X Y l1. induction l1 as [|x1 l1'].\n  Case \"l1 = nil\". intros l2 l eq1 eq2. destruct l2 as [|x2 l2'].\n    SCase \"l2 = nil\". simpl in eq2. rewrite <- eq2. reflexivity.\n    SCase \"l2 = x2 :: l2'\". inversion eq1.\n  Case \"l1 = x1 l1'\". intros l2 l eq1 eq2. destruct l2 as [|x2 l2'].\n    SCase \"l2 = nil\". inversion eq1.\n    SCase \"l2 = x2 l2'\". destruct l as [|(a,b) l'].\n      SSCase \"l = nil\". inversion eq2.\n      SSCase \"l = (a,b) :: l'\". inversion eq1. inversion eq2.\n      assert (split (combine l1' l2') = (l1',l2')) as IH.\n        apply IHl1'. apply H0. reflexivity.\n      simpl. rewrite IH. reflexivity.\nQed.\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 eq1.\n  unfold override. destruct (beq_nat k1 k3) eqn:H13.\n  Case \"beq_nat k1 k3 = true\".\n    assert (k1 = k3). apply beq_nat_true. apply H13.\n    rewrite <- H. rewrite eq1. reflexivity.\n  Case \"beq_nat k1 k3 = false\". 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 test x l lf.\n  generalize dependent lf. generalize dependent x.\n  induction l as [|a l'].\n  Case \"l = nil\". intros x lf eq1.\n    unfold filter in eq1. inversion eq1.\n  Case \"l = a :: l'\". destruct (test a) eqn:Htx.\n    SCase \"test a = true\".\n      intros x lf eq1. unfold filter in eq1.\n      rewrite Htx in eq1. inversion eq1.\n      rewrite <- H0. apply Htx.\n    SCase \"test a = false\". intros x lf eq1.\n      apply IHl' with lf. unfold filter in eq1.\n      rewrite Htx in eq1. apply eq1.\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*)\n\nFixpoint forallb {X : Type} (f : X -> bool) (xs : list X) : bool :=\n  match xs with\n  | [] => true\n  | h :: t => if f h then forallb f t else false\n  end.\n\nFixpoint existsb {X : Type} (f : X -> bool) (xs : list X) : bool :=\n  match xs with\n  | [] => false\n  | h :: t => if f h then true else existsb f t\n  end.\n\nDefinition existsb' {X : Type} (f : X -> bool) (xs : list X) : bool :=\n  negb (forallb (fun x => negb (f x)) xs).\n\nExample forallb_1 :\n  forallb oddb [1;2;3] = false.\nProof. reflexivity. Qed.\n\nExample forallb_2 :\n  forallb oddb [1;3;5] = true.\nProof. reflexivity. Qed.\n\nExample existsb_1 :\n  existsb oddb [2;4;6] = false.\nProof. reflexivity. Qed.\n\nExample existsb_2 :\n  existsb oddb [2;4;5] = true.\nProof. reflexivity. Qed.\n\nTheorem same_existsb_existsb' : forall (X : Type) (f : X -> bool) (xs : list X),\n  existsb f xs = existsb' f xs.\nProof.\n  intros X f xs. induction xs as [|h t].\n  Case \"xs = nil\". unfold existsb.\n    unfold existsb'. unfold forallb. reflexivity.\n  Case \"xs = h :: t\". destruct (f h) eqn:Hfh.\n    SCase \"f h = true\". unfold existsb. unfold existsb'.\n      rewrite Hfh. simpl. rewrite Hfh. reflexivity.\n    SCase \"f h = false\".\n      unfold existsb. rewrite Hfh. fold (@existsb X).\n      rewrite IHt. unfold existsb'. unfold forallb.\n      rewrite Hfh. reflexivity.\nQed.\n(** [] *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.9407897492587141, "lm_q1q2_score": 0.7669623776915833}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #3 : 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\nPrint prod_curry.\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\n|(x, y) => f x y\nend.\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\nExample test_uncurry:\n  prod_uncurry plus (3,7) = 10.\nProof. reflexivity. Qed.\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. 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. simpl. 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/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7669213789702218}}
{"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\nSet Implicit Arguments.\n\nSection Forall.\n\n  Variable (X : Type) (P : X -> Prop).\n\n  Fact Forall_cons_inv x l : Forall P (x::l) <-> P x /\\ Forall P l.\n  Proof. \n    split.\n    + inversion 1; auto.\n    + constructor; tauto.\n  Qed.\n\n  Fact Forall_app_inv l m : Forall P (l++m) <-> Forall P l /\\ Forall P m.\n  Proof.\n    induction l; simpl; try (repeat split; auto; tauto).\n    do 2 rewrite Forall_cons_inv; tauto.\n  Qed.\n\n  Let Forall_rec_1 l : Forall P l -> Forall P (rev l).\n  Proof.\n    induction 1; simpl; auto.\n    apply Forall_app_inv; simpl; auto.\n  Qed.\n\n  Fact Forall_rev l : Forall P (rev l) <-> Forall P l.\n  Proof.\n    split; auto.\n    rewrite <- (rev_involutive l) at 2.\n    apply Forall_rec_1.\n  Qed.\n\nEnd Forall.\n\nFact Forall2_lft_nil_inv X Y (R : X -> Y -> Prop) m : Forall2 R nil m -> m = nil.\nProof. inversion 1; auto. Qed.\n  \nFact Forall2_lft_cons_inv X Y (R : X -> Y -> Prop) x l m : Forall2 R (x::l) m -> exists y m', m = y::m' /\\ R x y /\\ Forall2 R l m'.\nProof. inversion 1; subst; exists y, l'; auto. Qed.\n\nTactic Notation \"inv\" \"Forall2\" \"nil\" := \n  repeat match goal with H: Forall2 _ nil ?m |- _ => apply Forall2_lft_nil_inv in H; try discriminate; subst m end.\n  \nTactic Notation \"inv\" \"Forall2\" \"in\" hyp(H) \"with\" ident(x) ident(m) := apply Forall2_lft_cons_inv in H; destruct H as (x & m & ? & ? & ?); subst.\n\nFact Forall2_fun X Y (R : X -> Y -> Prop) l : (forall x, In x l -> forall y1 y2, R x y1 -> R x y2 -> y1 = y2) \n                                            -> forall m1 m2, Forall2 R l m1 -> Forall2 R l m2 -> m1 = m2.\nProof.\n  induction l as [ | t l IHl ]; intros Hl l1 l2 H1 H2.\n  inv Forall2 nil; auto.\n  inv Forall2 in H1 with x1 m1.\n  inv Forall2 in H2 with x2 m2.\n  f_equal.\n  apply Hl with t; simpl; auto.\n  apply IHl; auto.\n  intros ? ? ? ?; apply Hl; right; auto.\nQed.\n\nFact Forall2_mono X Y (R S : X -> Y -> Prop) : (forall x y, R x y -> S x y) -> forall l m, Forall2 R l m -> Forall2 S l m.\nProof. induction 2; simpl; auto. Qed.\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/utils/list_forall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7668195320544232}}
{"text": "\nTheorem and_commutative : (forall A B :Prop,  A /\\ B -> B /\\ A).\nProof.\nintros.\nelim H.\nintros.\nsplit.\nauto.\nauto.\nQed.\n\n\nTheorem or_commutative : (forall A B : Prop, A \\/ B -> B \\/ A).\nProof.\n        intros.\n        elim H.\n        intro HA.\n        clear H. (* remove unnecessary proofs *)\n        right.\n        trivial.\n        auto.\nQed.\n\n\nSection Predicate_calculus.\n        Variable D : Set.\n        Variable R : D -> D -> Prop.\nSection R_sym_trans.\nHypothesis R_symmetric: (forall x y : D, R x y -> R y x).\nHypothesis R_transitive: (forall x y z : D, 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.\n        intros x x_Rlinked.\n        elim x_Rlinked.\n        intros y Rxy.\n        apply R_transitive with y.\n        assumption.\n        apply R_symmetric. \n        assumption.\nQed.\nEnd R_sym_trans.\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/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090975, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7667889339093177}}
{"text": "Require Import Frap Helpers.\n\nRequire Import Problem.\n\nFixpoint fact (n: nat): nat :=\n  0 (* Part 1: Implement this *)\n.\n\nTheorem fact_thm1:\n  fact 5 = 120.\nProof.\n  (* Part 1: Prove this after implementing fact *)\nAdmitted.\n\nTheorem fact_thm2: forall (n: nat),\n  n > 1 -> (exists (k: nat), fact n = 2 * k).\nProof.\n  (* Part 2: Prove this after implementing fact *)\nAdmitted.\n\nFixpoint fact_CPS (n: nat) (C: nat -> nat): nat :=\n  (* Part 3: Implement factorial using continuation passing style\n     C is the continuation *)\n  C 0.\n\nTheorem CPS_correct: forall (n: nat) (f: nat -> nat),\n fact_CPS n f = f (fact n).\nProof.\n  (* Part 3: Prove factorial using continuation passing style is correct *)\nAdmitted.\n\nTheorem fact_CPS_thm2: forall (n: nat),\n  n > 1 -> (exists (k: nat), fact_CPS n (fun R => R) = 2 * k).\nProof.\n  (* Part 4: Freeby: Prove this using CPS_correct and fact_thm2! *)\nAdmitted.", "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/Problem1/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.766778190052355}}
{"text": "Require Export \"ProofObjects\".\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 n\". intros n H. simpl. apply H.\nQed.\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 n\". simpl. intros n H. apply f_equal. assumption.\nQed.\n\nInductive yesno : Type :=\n| yes : yesno\n| no : yesno.\n\n(*\nforall P : yesno -> Prop, P yes -> P no -> forall y, P y *)\n\nInductive rgb : Type :=\n| red : rgb\n| green : rgb\n| blue : rgb.\n\n(* \nforall P : rgb -> Prop, P red -> P green -> P blue -> forall y, P y *)\nCheck rgb_ind.\n\nInductive natlist : Type :=\n| nnil : natlist\n| ncons : nat -> natlist -> natlist.\n\n(*\nforall P : natlist -> Prop, P nnil -> (forall (n : nat) (l : natlist), \nP l -> P (ncons n l)) -> forall n : natlist, P n *)\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(* \n forall P : natlist1 -> Prop, \n   P nnil1 -> (forall (n : nat) (l : natlist1), P l -> P (nsnoc1 l n)) -> \n   forall (n : natlist1), P n *)\nCheck natlist1_ind.\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/MoreInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7666576298047536}}
{"text": "(**********************************************************************\n*\n* This file contains a definition of the \"look and say\" sequence\n* https://en.wikipedia.org/wiki/Look-and-say_sequence\n*\n* Along with a proof that it contains only numbers <= 3 and is decidable.\n*\n* MIT License\n*\n* Copyright (c) 2021 Cody Roux (codyroux), see LICENSE file for details.\n*\n*\n*\n***********************************************************************)\n\n\n\nRequire Import List Arith Lia.\n\nImport ListNotations.\n\n\nPrint List.\n\nInductive LookAndSay : list nat -> list nat -> Prop :=\n(* Look at an empty list, and say \"empty list\" *)\n| LAS_nil : LookAndSay [] []\n(* See a non-empty consecutive list of k \"a\"s, and then l1, and say \"k a\"\n   and then whatever you'd have said for l1. *)\n| LAS_Cons : forall l1 l2 a k, 0 < k -> hd_error l1 <> Some a -> LookAndSay l1 l2 -> LookAndSay ((repeat a k) ++ l1) (k::a::l2)\n.\n\nHint Constructors LookAndSay.\n\n(* Seems to work *)\nGoal LookAndSay [1;1;1;2;2] [3;1;2;2].\nProof.\n  replace ([1; 1; 1; 2; 2]) with (repeat 1 3 ++ repeat 2 2 ++ []) by reflexivity.\n  apply LAS_Cons; [lia | simpl; congruence | ].\n  apply LAS_Cons; [lia | simpl; congruence | ].\n  now auto.\nQed.\n\n(* the actual sequence. We could define it recursively, but this\n   serves as well (and avoids an existential). *)\nInductive LookAndSay_n : nat -> list nat -> Prop :=\n  | LAS_n_0 : LookAndSay_n 0 [1]\n  | LAS_n_S : forall n l l', LookAndSay_n n l -> LookAndSay l l' -> LookAndSay_n (S n) l'\n.\n\n(* Suprisingly seems to be absent from std lib... *)\nLemma skipn_repeat : forall A n (a : A) k, skipn n (repeat a k) = repeat a (k - n).\nProof.\n  induction n; simpl.\n  - intros; rewrite Nat.sub_0_r; now auto.\n  - induction k; simpl; auto.\nQed.\n\n(* This is the critical trick: we need to bound both the values in the\n   list, and the length of consecutive runs of a given value. Again we do\n   this with an inductive predicate, since Coq likes these. *)\nInductive val_and_len_bounded : list nat -> Prop :=\n| val_and_len_bounded_nil : val_and_len_bounded []\n| val_and_len_bounded_cons : forall l1 l2 a k,\n    0 < k <= 3 ->\n    a <= 3 ->\n    hd_error l1 <> Some a ->\n    val_and_len_bounded l1 ->\n    l2 = repeat a k ++ l1 ->\n    val_and_len_bounded l2\n.\n\nHint Constructors val_and_len_bounded.\n\n(* This lemma is really powerful: it allows us to not reasona bout\n   list lenght, but instead deduces the critical property for smaller\n   lists from larger ones.\n\n   Otherwise we'd have to do a well-founded induction on list length,\n   which is tedious.  *)\nLemma bounded_cons : forall n l, val_and_len_bounded l -> val_and_len_bounded (skipn n l).\nProof.\n  induction n using lt_wf_ind.\n  intros l h.\n  inversion h; subst; auto.\n  - rewrite skipn_nil; auto.\n  - rewrite skipn_app.\n    rewrite repeat_length.\n    rewrite skipn_repeat.\n    destruct (Nat.le_gt_cases k n).\n    + replace (k - n) with 0 by lia; simpl.\n      apply H; [lia | now auto].\n    + replace (n - k) with 0 by lia; simpl.\n      apply val_and_len_bounded_cons with (l1 := l1) (a := a) (k := k - n); first [lia | congruence].\nQed.\n\n(* Also surprisingly absent from the stdlib... *)\nLemma skipn_len_app : forall A l1 l2, skipn(A:=A) (length l1) (l1 ++ l2) = l2.\nProof.\n  induction l1; simpl; auto.\nQed.\n\n(* Trivial from bounded_cons. *)\nLemma bounded_extensions : forall l1 l2, val_and_len_bounded (l1 ++ l2) -> val_and_len_bounded l2.\nProof.\n  intros.\n  replace l2 with (skipn (length l1) (l1 ++ l2)) by apply skipn_len_app; auto.\n  apply bounded_cons; auto.\nQed.\n\n(* This is also an important property that corresponds to an insight:\n   a given value in l1 will lead to the same value in l2, shifted by\n   one. This means that a constraint on how many times a value can\n   repeat in l1 will propagate to l2. *)\nLemma LAS_hd_second : forall l1 l2 k, LookAndSay l1 (k::l2) -> hd_error l1 = hd_error l2.\nProof.\n  intros l1 l2 k h; inversion h.\n  destruct k; simpl; [lia| now auto].\nQed.\n\n(* The main lemma. *)\nLemma LAS_bounded : forall l l', LookAndSay l l' -> val_and_len_bounded l -> val_and_len_bounded l'.\nProof.\n  intros l l' h.\n  induction h.\n  - auto.\n  - intros h'.\n    inversion h'.\n    + destruct k; [lia| simpl in *; congruence].\n    + clear H6.\n      assert (a = a0) by (destruct k; destruct k0; simpl in H5; first [lia | congruence]).\n      subst a0.\n      destruct (Nat.eq_dec k a); subst.\n      -- destruct l2.\n         ++ apply val_and_len_bounded_cons with (l1 := []) (a := a) (k := 2);\n              simpl; first [lia | congruence | constructor | idtac].\n         ++ assert (hd_error l2 <> Some a) by (erewrite <- LAS_hd_second; [exact H0| exact h]).\n            destruct (Nat.eq_dec a n); subst.\n            { apply val_and_len_bounded_cons with (l1 := l2) (a := n) (k := 3); simpl; first [lia | congruence | auto].\n              replace l2 with (skipn 1 (n::l2)) by reflexivity.\n              apply bounded_cons.\n              apply IHh.\n              eapply bounded_extensions; eauto. }\n            apply val_and_len_bounded_cons with (l1 := (n::l2)) (a := a) (k := 2); simpl; first [lia | congruence | auto].\n            apply IHh; eapply bounded_extensions; eauto.\n      -- assert (k = k0).\n         (* Ugh I can make this a lemma as well... *)\n         { revert H5 H3 H0; clear.\n           revert k0 l0 l1 a.\n           induction k; induction k0; simpl; auto.\n           - intros.\n             exfalso.\n             destruct l1; simpl in *; congruence.\n           - intros.\n             destruct l0; simpl in *; congruence.\n           - intros; f_equal; eapply IHk; inversion H5; eauto. }\n         subst.\n         apply val_and_len_bounded_cons with (l1 := (a::l2)) (a := k0) (k := 1); simpl; first [lia | congruence | auto].\n         destruct l2.\n         ++ apply val_and_len_bounded_cons with (l1 := []) (a := a) (k := 1);\n              simpl; first [lia | congruence | constructor | idtac].\n         ++ destruct (Nat.eq_dec a n0); subst.\n            {\n              assert (hd_error l2 <> Some n0) by (erewrite <- LAS_hd_second; [exact H0| exact h]).\n              apply val_and_len_bounded_cons with (l1 := l2) (a := n0) (k := 2); simpl; first [lia | congruence | auto].\n              replace l2 with (skipn 1 (n0::l2)) by reflexivity.\n              apply bounded_cons.\n              apply IHh.\n              eapply bounded_extensions; eauto. }\n            apply val_and_len_bounded_cons with (l1 := (n0::l2)) (a := a) (k := 1);\n              simpl; first [lia | congruence | constructor | idtac].\n            apply IHh; eapply bounded_extensions; eauto.\nQed.\n\n(* We need to actually show that our strengthened property is stronger! *)\nLemma bounded_In : forall l a, val_and_len_bounded l -> In a l -> a <= 3.\nProof.\n  intros l a h; revert a; induction h.\n  - intros a h; inversion h.\n  - intros b; rewrite H2.\n    intros h'.\n    generalize (in_app_or _ _ _ h').\n    intro h''; destruct h''.\n    + generalize (repeat_spec k a b H3); intros; subst; now auto.\n    + now auto.\nQed.\n\n(* And seed the recurrence. *)\nLemma bounded_init : val_and_len_bounded [1].\nProof.\n  apply val_and_len_bounded_cons with (l1 := []) (a := 1) (k := 1); simpl; first [lia | congruence | auto].\nQed.\n\n(* The main theorem follows as a pretty trivial corollary to the main lemma. *)\nTheorem LookAndSay_less_than_3 : forall n l a, LookAndSay_n n l -> In a l -> a <= 3.\nProof.\n  intros n l a h.\n  apply bounded_In.\n  induction h; [apply bounded_init |].\n  eapply LAS_bounded; eauto.\nQed.\n\n\n\n\n\n\n\n(*****************************************************************************************************)\n\n(* We also build a quick and dirty proof of decidability for\n   [LookAndSay l1 l2], i.e. from any given [l1], we can compute an\n   [l2] such that [LookAndSay l1 l2] holds.\n\n   This would be trivial in Prolog :). But in Coq it's a bit finicky,\n   because we need to consume a chunk of l1 at each step: basically\n   the whole list of contiguous equal elements (probably we could do\n   it simply 3 at a time using the above theorem, but...).\n\n   This makes Coq unhappy, because consuming some arbitrary but\n   non-zero elements of a list, before a recursive call is\n   non-structural.\n\n   We adopt the only sane approach, which is to give a natural number\n   as \"gas\", and proving that a certain number will always suffice to\n   compute the result without running out of gas.\n\n *)\n\n\n(* It turns out we can break the problem into 2 chunks: getting the\n   remaining elements of the list, and counting the prefix of\n   identical elements.\n\n   It seems to be a good pattern to break things up like this, though\n   it makes for some definition and proof duplication.  *)\nFixpoint get_prefix_tl (l : list nat) (a : nat) : list nat :=\n  match l with\n  | [] => []\n  | b::l' =>\n    if a =? b then\n      get_prefix_tl l' a\n    else l\n  end.\n\nFixpoint get_prefix_len (l : list nat) (a : nat) : nat :=\n  match l with\n  | [] => 0\n  | b::l' => if a =? b then\n               S (get_prefix_len l' a)\n             else 0\n  end.\n\n\n(* Testing functions in Coq is a surprisingly effective way of not\n   getting stuck for hours on trying to prove incorrect theorems! *)\nEval compute in (get_prefix_len [1;1;1;1;1;1;1;2;1;1] 1).\nEval compute in (get_prefix_tl [1;1;1;1;1;1;1;2;1;1] 1).\n\n\nLemma get_prefix_len_gt : forall l a, hd_error l = Some a <-> 0 < get_prefix_len l a.\nProof.\n  split.\n  - destruct l; simpl; [congruence|].\n    intros.\n    inversion H.\n    rewrite <- beq_nat_refl.\n    lia.\n  - destruct l; simpl; [lia|].\n    case_eq (a =? n).\n    + intro h; rewrite (beq_nat_true _ _ h); now auto.\n    + lia.\nQed.\n\nLemma get_prefix_len_aux : forall l a, length (get_prefix_tl l a) + (get_prefix_len l a) = length l.\nProof.\n  induction l; simpl; auto.\n  intros b.\n  destruct (b =? a); auto.\n  erewrite <- IHl; now eauto.\nQed.\n\nLemma get_prefix_aux_head : forall l a, hd_error (get_prefix_tl l a) <> Some a.\nProof.\n  induction l; simpl; [congruence|].\n  intro b; case_eq (b =? a); intro eq_a; simpl.\n  - apply IHl.\n  - assert (b <> a) by (apply beq_nat_false; now auto).\n    congruence.\nQed.\n\n(* We don't use this anywhere, but it captures the spirit. *)\nLemma get_prefix_repeat : forall l a, l = (repeat a (get_prefix_len l a)) ++ (get_prefix_tl l a).\nProof.\n  induction l; simpl; auto.\n  intros b; case_eq (b =? a); intro eq_a.\n  - assert (H : b = a) by (apply beq_nat_true; now auto).\n    rewrite H; simpl.\n    f_equal; now auto.\n  - simpl; now auto.\nQed.\n\n(* We often need finicky \"inversion like\" lemmas for inductive predicates *)\nLemma LAS_empty : forall l, LookAndSay [] l -> l = [].\nProof.\n  intros l h; inversion h; auto.\n  destruct k; simpl in *; first [lia | congruence].\nQed.\n\n(* I originally defined this as a single recursive function without\n   [get_prefix_foo], and pattern matching on the recursive call to do\n   additional work.\n\n   Proofs were not forthcoming.\n *)\nFixpoint look_and_say (gas : nat) (l : list nat) : option (list nat) :=\n  match gas with\n  | 0 => None\n  | S k =>\n    match l with\n    | [] => Some []\n    | a::l' =>\n      option_map (fun l'' => S (get_prefix_len l' a) :: a :: l'') (look_and_say k (get_prefix_tl l' a))\n    end\n  end.\n\nLemma look_and_say_gas : forall k l, length l < k -> look_and_say k l <> None.\nProof.\n  induction k; simpl.\n  - lia.\n  - intros l len.\n    destruct l.\n    + congruence.\n    + unfold option_map.\n       simpl in len.\n       assert (length (get_prefix_tl l n) <= length l).\n      -- erewrite <- (get_prefix_len_aux l) with (a := n).\n         lia.\n      -- assert (len' : length (get_prefix_tl l n) < k) by lia.\n         generalize (IHk _ len'); intro H'.\n         case_eq (look_and_say k (get_prefix_tl l n)); intros; simpl; congruence.\nQed.\n\n(* the main lemma for [get_prefix_tl] *)\nLemma get_prefix_tl_repeat : forall l a k,\n hd_error l <> Some a ->\n    get_prefix_tl (repeat a k ++ l) a = l.\n  induction k; simpl.\n  - induction l; simpl; auto.\n    intro neq.\n    assert (a <> a0) by congruence.\n    rewrite<- Nat.eqb_neq in *.\n    rewrite H; auto.\n  - rewrite<- beq_nat_refl.\n    auto.\nQed.\n\n(* the main lemma for [get_prefix_len] *)\nLemma get_prefix_len_repeat : forall l a k,\n hd_error l <> Some a ->\n get_prefix_len (repeat a k ++ l) a = k.\nProof.\n  induction k; simpl.\n  - induction l; simpl; auto.\n    intro neq.\n    assert (a <> a0) by congruence.\n    rewrite<- Nat.eqb_neq in *.\n    rewrite H; auto.\n  - rewrite<- beq_nat_refl.\n    auto.\nQed.\n\n(* The main lemma for [look_and_say], handles the non-trivial case of the theorem.*)\nLemma look_and_say_repeat : forall gas l a k,\n    0 < k ->\n    hd_error l <> Some a ->\n    look_and_say (S gas) ((repeat a k) ++ l) = option_map (fun l'' => k :: a :: l'') (look_and_say gas l).\nProof.\n  intros.\n  simpl.\n  destruct k; simpl; first [lia | congruence | idtac].\n  rewrite get_prefix_len_repeat; auto.\n  rewrite get_prefix_tl_repeat; auto.\nQed.\n\n(* This theorem could be made simpler by simply fixing [gas = length l + 1], but we'd need this as a lemma. *)\nTheorem LAS_cons : forall l l',\n    LookAndSay l l' ->\n    forall gas,\n      length l < gas ->\n      Some l' = look_and_say gas l.\nProof.\n  intros l l' las.\n  induction las.\n  - simpl; destruct gas; first [lia | auto].\n  - rewrite app_length, repeat_length.\n    intros.\n    destruct gas; [lia |].\n    rewrite look_and_say_repeat; auto.\n    erewrite <- IHlas; [eauto | lia ].\nQed.\n", "meta": {"author": "codyroux", "repo": "look-and-say", "sha": "db130fffbbf9fdebfacd34c3fc257b9f33cffbc0", "save_path": "github-repos/coq/codyroux-look-and-say", "path": "github-repos/coq/codyroux-look-and-say/look-and-say-db130fffbbf9fdebfacd34c3fc257b9f33cffbc0/look_and_say.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.7666529783508427}}
{"text": "Module Lecture10.\n\nPrint nat.\n\nTheorem t1: 2 * 2 = 4.\nProof.\n    Print \"*\".\n    simpl.\n    reflexivity.\nQed.\n\nTheorem t2: exists x, x * 2 = 4.\nProof.\n  exists 2.\n  apply t1.\nQed.\n\nPrint t2.\nPrint t1.\n\nTheorem t3: exists x y, x*y = 4.\nProof.\n  exists 2.\n  exists 2.\n  apply t1.\nQed.\n\nPrint t3.\n\nInductive bool: Type :=\n| true\n| false\n.\n\nCheck false.\nCheck (bool -> bool): Type.\nCheck (fun b: bool => b).\n\nCheck (fun b => bool).\n\nCheck (fun b => b) true.\nCheck fun (f: bool -> bool) => f true.\n\nCompute (fun b => b) 1.\n\nDefinition i := fun b: bool => b.\nCheck i.\nCompute i true.\n\nDefinition neg :=\n  fun (b: bool) =>\n    match b with\n    | true  => false\n    | false => true\n  end.\n\nCheck neg.\n\nCompute neg false.\nCompute neg true.\n\nDefinition and (a b: bool) : bool := \n  match a with \n  | false => false\n  | true  => b\nend.\n\nCompute and true true.\nCompute and true false.\n\n(*\n\nSet : Type(0)\nProp : Type(0)\n\\forall i Type(i)\n\nBHK interptertation\n exists p:A . P(p) - (a \\in A, P)\n*)\n\nPrint \"=\".\n\n(*\n  A -> Prop\n\n  (fun (x: nat) => x%2 == 0): nat -> Prop\n*)\n\nInductive eq (A : Type) (x : A) : A -> Prop :=  \n  eq_refl : eq x x\n.\n\nPrint nat.\n\nInductive nat: Type :=\n| O\n| S: nat -> nat.\n\nCheck S(S(S O)).\n\nDefinition succn := S.\n\n(*\nThere are some possible signatures of pred is possible:\n  predn: nat -> nat\n  predn: nat -> Option nat\n  predn: forall n: nat, (n <> 0) -> nat\n*)\n\nDefinition predn (n :nat) : nat :=\n  match n with \n  | S x => x\n  | O => O\nend.\n\nFixpoint addn (n m: nat) {struct n}: nat :=\n  match n with\n  | O => m\n  | S k => S (addn k m)\nend.\n\nCompute addn (S (S O)) (S (S O)).\n\nPrint list.\n\nInductive list (A : Type) : Type :=\n\t| nil : list A \n  | cons : A -> list A -> list A\n.\n\nTheorem list2: list nat.\nProof.\n  apply cons.\n  {\n    apply 1.\n  }\n  apply cons.\n  {\n    apply 2.\n  }\n  apply nil.\nQed.\n\nSet Printing All.\nCheck 5 + 5.\n", "meta": {"author": "mikevoronov", "repo": "applied-type-theory", "sha": "ee80d207d25823d862da732c9673ef38c5cfafec", "save_path": "github-repos/coq/mikevoronov-applied-type-theory", "path": "github-repos/coq/mikevoronov-applied-type-theory/applied-type-theory-ee80d207d25823d862da732c9673ef38c5cfafec/lecture-notes/att-lecture-note-10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7665534578634252}}
{"text": "Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Set :=\n  | pair : nat -> nat -> natprod.\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n    | pair x _ => x\n  end.\nDefinition snd (p : natprod) : nat :=\n  match p with\n    | pair _ 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 p : natprod, p = (fst p, snd p).\nProof. intro p; destruct p as [x y]; reflexivity. Qed.\n\nTheorem snd_fst_is_swap : forall p : natprod, (snd p, fst p) = swap_pair p.\nProof. intro p; destruct p as [x y]; reflexivity. Qed.\n\nTheorem fst_swap_is_snd : forall p : natprod, fst (swap_pair p) = snd p.\nProof. intro p; destruct p as [x y]; reflexivity. Qed.\n\nInductive natlist : Set :=\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) .. ).\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    | n :: l' => S (length l')\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n    | []       => l2\n    | n :: l1' => n :: app l1' 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: 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    | []     => default\n    | n :: _ => n\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n    | []      => []\n    | _ :: l' => l'\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    | O     :: l' => nonzeros l'\n    | (S n) :: l' => (S n) :: nonzeros l'\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    | n :: l' => match (oddb n) with\n                   | true  => n :: oddmembers l'\n                   | false => oddmembers l'\n                 end\n  end.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l : natlist) : nat :=\n  match l with\n    | []      => O\n    | n :: l' => match (oddb n) with\n                   | true  => S (countoddmembers l')\n                   | false => countoddmembers l'\n                 end\n  end.\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n    | []        => l2\n    | n1 :: l1' => match l2 with\n                     | []        => l1\n                     | n2 :: l2' => n1 :: n2 :: alternate l1' l2'\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\nDefinition bag := natlist.\n\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n    | []      => O\n    | n :: s' => match beq_nat v n with\n                   | true  => S (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. 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 := 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 := negb (beq_nat 0 (count v s)).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n    | []      => []\n    | n :: s' => match beq_nat v n with\n                   | true  => s'\n                   | false => n :: remove_one v s'\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  match s with\n    | []      => []\n    | n :: s' => match beq_nat v n with\n                   | true  => remove_all v s'\n                   | false => n :: 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. 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 s2 : bag) : bool :=\n  match s1 with\n    | []       => true\n    | n :: s1' => match ble_nat (count n s1) (count n s2) with\n                    | true  => subset s1' 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\nTheorem add_increments_count : forall (s : bag) (v : nat), count v (add v s) = S (count v s).\nProof. intros s v; simpl; rewrite <- beq_nat_refl; reflexivity. Qed.\n\nTheorem nil_app : forall l : natlist, [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l : natlist, length (tl l) = pred (length l).\nProof. intro l; destruct l as [| n l']; reflexivity. Qed.\n\nTheorem app_ass : forall l1 l2 l3 : natlist, l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof. intros l1 l2 l3; induction l1 as [| n l1'].\nCase \"l1 = []\".     reflexivity.\nCase \"l1 = n::l1'\". simpl; rewrite IHl1'; reflexivity.\nQed.\n\nTheorem app_length : forall l1 l2 : natlist, length (l1 ++ l2) = length l1 + length l2.\nProof. intros l1 l2; induction l1 as [| n l1'].\nCase \"l1 = []\".     reflexivity.\nCase \"l1 = n::l1'\". simpl; rewrite IHl1'; reflexivity.\nQed.\n\nFixpoint snoc (l : natlist) (v : nat) : natlist :=\n  match l with\n    | []      => [v]\n    | n :: l' => n :: snoc l' v\n  end.\n\nFixpoint rev (l : natlist) : natlist :=\n  match l with\n    | []      => []\n    | n :: l' => snoc (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\nTheorem length_snoc : forall (l : natlist) (v : nat), length (snoc l v) = S (length l).\nProof. intros l v; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite IHl'; reflexivity.\nQed.\n\nTheorem length_rev : forall l : natlist, length (rev l) = length l.\nProof. intro l; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite <- IHl'; rewrite length_snoc; reflexivity.\nQed.\n\nTheorem app_nil_end : forall l : natlist, l ++ [] = l.\nProof. intro l; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite IHl'; reflexivity.\nQed.\n\nLemma rev_snoc : forall (l : natlist) (v : nat), rev (snoc l v) = v :: rev l.\nProof. intros l v; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite IHl'; reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist, rev (rev l) = l.\nProof. intro l; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite rev_snoc; rewrite IHl'; reflexivity.\nQed.\n\nTheorem app_ass4 :\n  forall l1 l2 l3 l4 : natlist, l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof. intros l1 l2 l3 l4; repeat rewrite app_ass; reflexivity. Qed.\n\nTheorem snoc_append : forall (l : natlist) (v : nat), snoc l v = l ++ [v].\nProof. intros l v; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl. rewrite IHl'; reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist, rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof. intros l1 l2; induction l1 as [| n l1'].\nCase \"l1 = []\".     simpl; rewrite app_nil_end; reflexivity.\nCase \"l1 = n::l1'\". simpl; repeat rewrite snoc_append; rewrite IHl1';\n                    rewrite app_ass; reflexivity.\nQed.\n\nLemma nonzeros_app :\n  forall l1 l2 : natlist, nonzeros (l1 ++ l2) = nonzeros l1 ++ nonzeros l2.\nProof. intros l1 l2; induction l1 as [| n l1'].\nCase \"l1 = []\".     reflexivity.\nCase \"l1 = n::l1'\". destruct n as [| n']; simpl; rewrite IHl1'; reflexivity.\nQed.\n\nTheorem snoc_app_cons :\n  forall (l1 l2 : natlist) (v : nat), (snoc l1 v) ++ l2 = l1 ++ (v :: l2).\nProof. intros l1 l2 v; rewrite snoc_append; rewrite <- app_ass; reflexivity. Qed.\n\nTheorem count_member_nonzero : forall (s : bag) (v : nat), ble_nat 1 (count v (v :: s)) = true.\nProof. intros s v; simpl; rewrite <- beq_nat_refl; reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n : nat, ble_nat n (S n) = true.\nProof. intro n; induction n as [| n'].\nCase \"n = 0\".    reflexivity.\nCase \"n = S n'\". simpl; exact IHn'.\nQed.\n\n(* This actually appears somewhat more subtle if you try to replace 0 by (v : nat).\n * Instead of destructing n, you need to destruct (beq_nat v n), but there are three\n * occurrences of this in the theorem and one of them is behind the reduction of\n * count v (remove_one v s).  One needs some way to retain the case-analyzed value of\n * beq_nat v n in the context, which I don't know how to do. *)\nTheorem remove_decreases_count :\n  forall (s : bag), ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof. intro s; induction s as [| n s'].\nCase \"s = []\".    reflexivity.\nCase \"s = n::s'\". simpl; destruct n as [| n'].\n SCase \"n = 0\".    apply ble_n_Sn.\n SCase \"n = S n'\". simpl; exact IHs'.\nQed.\n\n(* To solve the problem above, use the eqn: clause of destruct which retains the case info. *)\nTheorem remove_decreases_count' :\n  forall (s : bag) (v : nat), ble_nat (count v (remove_one v s)) (count v s) = true.\nProof. intros s v; induction s as [| n s'].\nCase \"s = []\".    reflexivity.\nCase \"s = n::s'\". simpl; destruct (beq_nat v n) eqn: nH.\n SCase \"v = n\".  apply ble_n_Sn.\n SCase \"v /= n\". simpl; rewrite nH; exact IHs'.\nQed.\n\nTheorem sum_adds_count :\n  forall (v : nat) (s1 s2 : bag), count v (sum s1 s2) = count v s1 + count v s2.\nProof. intros v s1 s2; induction s1 as [| n s1'].\nCase \"s1 = []\".     reflexivity.\nCase \"s1 = n::s1'\". simpl; destruct (beq_nat v n); rewrite IHs1'; reflexivity.\nQed.\n\nTheorem rev_injective : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof. intros l1 l2 H; rewrite <- (rev_involutive l1); rewrite <- (rev_involutive l2);\n       rewrite H; reflexivity.\nQed.\n\nInductive natoption : Set :=\n| Some : nat -> natoption\n| None : natoption.\n\nFixpoint index (i : nat) (l : natlist) : natoption :=\n  match l with\n    | []    => None\n    | n::l' => match i with\n                 | O    => Some n\n                 | S i' => index i' 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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n    | Some n => n\n    | None   => d\n  end.\n\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n    | []   => None\n    | n::_ => Some n\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\nTheorem option_elim_hd :\n  forall (l : natlist) (default : nat), hd default l = option_elim default (hd_opt l).\nProof. intros l default; destruct l as [| n l']; reflexivity. Qed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n    | [],      []      => true\n    | n1::l1', n2::l2' => andb (beq_nat n1 n2) (beq_natlist l1' l2')\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.\nExample test_beq_natlist4 : beq_natlist [1;2;3] [1;2] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l : natlist, true = beq_natlist l l.\nProof. intro l; induction l as [| n l'].\nCase \"l = []\".    reflexivity.\nCase \"l = n::l'\". simpl; rewrite <- beq_nat_refl; rewrite <- IHl'; reflexivity.\nQed.\n\nModule Dictionary.\n\nInductive dictionary : Set :=\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) : 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 :\n  forall (d : dictionary) (k v : nat), find k (insert k v d) = Some v.\nProof. intros d k v; simpl; rewrite <- beq_nat_refl; reflexivity. Qed.\n\nTheorem dictionary_invariant2 :\n  forall (d : dictionary) (k k' v : nat),\n    beq_nat k k' = false -> find k d = find k (insert k' v d).\nProof. intros d k k' v Hneq; simpl; rewrite Hneq; reflexivity. Qed.\n\nEnd Dictionary.\n\nEnd NatList.\n", "meta": {"author": "ystael", "repo": "sf", "sha": "fc304885bf687301521a0b3673743ec840986be4", "save_path": "github-repos/coq/ystael-sf", "path": "github-repos/coq/ystael-sf/sf-fc304885bf687301521a0b3673743ec840986be4/coq/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.7664936917642357}}
{"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(** *** Exercise 1:\n    - use no lemma to prove the following statement\n*)\nLemma orbC p q : p || q = q || p.\n(*D*)Proof. by case: p; case: q. Qed.\n\n(** *** Exercise 2:\n   - look up what [==>] is and prove that as you like\n*)\nLemma Peirce p q : ((p ==> q) ==> p) ==> p.\n(*D*)Proof. by case: p; case: q. Qed. \n\n(** *** Exercise 3:\n    - what is [(+)] ?\n    - prove this using move and rewrite\n*)\nLemma find_me p q :  ~~ p = q -> p (+) q.\n(*D*)Locate \"(+)\".\n(*D*)Search _ addb negb.\n(*D*)Proof. by move=> np_q; rewrite -np_q addbN negb_add. Qed.\n\n(** *** Exercise 4:\n    - prove this satement by induction\n*)\nLemma iterSr A n (f : A -> A) x : iter n.+1 f x = iter n f (f x).\n(*D*)Proof. by elim: n => // n IH; rewrite /= -IH. Qed.\n\n(** *** Exercise 5:\n    - look up the definition of [iter] (note there is an accumulator varying\n      during recursion)\n    - prove the following statement by induction\n*)\nLemma iter_predn m n : iter n predn m = m - n.\nProof.\n(*D*)elim: n m => [|n IHn] m.\n(*D*)  by rewrite subn0.\n(*D*)by rewrite /= IHn subnS.\nQed.\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/exercise2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.766493686466387}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2012     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\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.\nLocal Open Scope identity_scope.\nRequire Import Logic_Type.\nRequire Coq.Init.Nat.\n\nOpen Scope nat_scope.\nLocal Notation \"0\" := O.\n\nDefinition eq_S := f_equal S.\n\nHint Resolve (f_equal S): v62.\nHint Resolve (f_equal (A:=nat)): core.\n\n(** The predecessor function *)\n\nDefinition pred (n:nat) : nat := match n with\n                                 | O => n\n                                 | S u => u\n                                 end.\n(* Hint Resolve (f_equal pred): v62. *)\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) : Type :=\n  match n with\n  | O => False\n  | S p => True\n  end.\n\n(** Zero is not the successor of a number *)\n\n(* XXX Andrej: Try to put back in, does not work with current Coq. *)\n(* Theorem O_S : forall n:nat, 0 <> S n. *)\n(* Proof. *)\n(*   discriminate. *)\n(* Qed. *)\n(* Hint Resolve O_S: core. *)\n\n(* XXX Andrej: Try to put back in, does not work with current Coq. *)\n(* Theorem n_Sn : forall n:nat, n <> S n. *)\n(* Proof. *)\n(*   induction n; auto. *)\n(* Qed. *)\n(* Hint Resolve n_Sn: core. *)\n\n(** addition *)\n\nFixpoint plus (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\n\nwhere \"n + m\" := (plus n m) : nat_scope.\n\nHint Resolve (f_equal2 plus): v62.\nHint Resolve (f_equal2 (A1:=nat) (A2:=nat)): core.\n\nLemma plus_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n; simpl; auto.\nQed.\nHint Resolve plus_n_O: core.\n\nLemma plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  auto.\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  auto.\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\nFixpoint mult (n m:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => m + p * m\n  end\n\nwhere \"n * m\" := (mult n m) : nat_scope.\n\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\nFixpoint minus (n m:nat) : nat :=\n  match n, m with\n  | O, _ => n\n  | S k, O => n\n  | S k, S l => k - l\n  end\n\nwhere \"n - m\" := (minus n m) : 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 -> Type :=\n  | le_n : le n n\n  | le_S : forall m:nat, le n m -> le n (S m).\nLocal Notation \"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\nLocal Infix \"<\" := lt : nat_scope.\n\nDefinition ge (n m:nat) := m <= n.\nHint Unfold ge: core.\n\nLocal Infix \">=\" := ge : nat_scope.\n\nDefinition gt (n m:nat) := m < n.\nHint Unfold gt: core.\n\nLocal Infix \">\" := gt : nat_scope.\n\nLocal Notation \"x <= y <= z\" := (x <= y /\\ y <= z) : nat_scope.\nLocal Notation \"x <= y < z\" := (x <= y /\\ y < z) : nat_scope.\nLocal Notation \"x < y < z\" := (x < y /\\ y < z) : nat_scope.\nLocal Notation \"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\n(** Case analysis *)\n\nTheorem nat_case :\n forall (n:nat) (P:nat -> Type), 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 -> Type,\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\nFixpoint max n m : nat :=\n  match n, m with\n    | O, _ => m\n    | S n', O => n\n    | S n', S m' => S (max n' m')\n  end.\n\nFixpoint min n m : nat :=\n  match n, m with\n    | O, _ => 0\n    | S n', O => 0\n    | S n', S m' => S (min n' m')\n  end.\n\n(* Theorem max_l : forall n m : nat, m <= n -> max n m = n. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem max_r : forall n m : nat, n <= m -> max n m = m. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem min_l : forall n m : nat, n <= m -> min n m = n. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(* Theorem min_r : forall n m : nat, m <= n -> min n m = m. *)\n(* Proof. *)\n(* induction n; destruct m; simpl; auto. inversion 1. *)\n(* intros. apply f_equal. apply IHn. apply le_S_n. trivial. *)\n(* Qed. *)\n\n(** [n]th iteration of the function [f] *)\n\nFixpoint nat_iter (n:nat) {A} (f:A->A) (x:A) : A :=\n  match n with\n    | O => x\n    | S n' => f (nat_iter n' f x)\n  end.\n\nLemma nat_iter_succ_r n {A} (f:A->A) (x:A) :\n  nat_iter (S n) f x = nat_iter n f (f x).\nProof.\n  induction n; intros; simpl; rewrite <- ?IHn; trivial.\nQed.\n\nTheorem nat_iter_plus :\n  forall (n m:nat) {A} (f:A -> A) (x:A),\n    nat_iter (n + m) f x = nat_iter n f (nat_iter m f x).\nProof.\n  induction n; intros; simpl; rewrite ?IHn; trivial.\nQed.\n\n(** Preservation of invariants : if [f : A->A] preserves the invariant [Inv],\n    then the iterates of [f] also preserve it. *)\n\nTheorem nat_iter_invariant :\n  forall (n:nat) {A} (f:A -> A) (P : A -> Type),\n    (forall x, P x -> P (f x)) ->\n    forall x, P x -> P (nat_iter n f x).\nProof.\n  induction n; simpl; trivial.\n  intros A f P Hf x Hx. apply Hf, IHn; trivial.\nQed.\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/coq/theories/Init/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7664152460167857}}
{"text": "(* ----------------------------------------------------------------- *)\n(*                     Basic algebra of Sets                         *)\n(* ----------------------------------------------------------------- *)\n\nFrom Practice Require Import Basin.Base.\nFrom Practice Require Import Basin.ElemAlg.\nFrom Practice Require Import Basin.ClassicalSets.\n\nImport List.\nImport ListNotations.\n\n\n(* Union: CommMonoid *)\nProgram Instance magma_union U: Magma _ (@Union U).\n\nProgram Instance assoc_union U: Associative _ (@Union U).\nNext Obligation. firstorder. Qed.\n\nProgram Instance comm_union U: Commutative _ (@Union U).\nNext Obligation. firstorder. Qed.\n\nProgram Instance hasid_union U: HasIdentity _ (@Union U) := { mid := EmptySet }.\nNext Obligation. firstorder. Qed.\nNext Obligation. firstorder. Qed.\n\nProgram Instance semigroup_union U: Semigroup _ (@Union U).\nProgram Instance monoid_union U: Monoid _ (@Union U).\nProgram Instance cmon_union U: CommMonoid _ (@Union U).\n\n\nProgram Instance magma_intersect U: Magma _ (@Intersect U).\n\nProgram Instance assoc_intersect U: Associative _ (@Intersect U).\nNext Obligation. firstorder. Qed.\n\nProgram Instance comm_intersect U: Commutative _ (@Intersect U).\nNext Obligation. firstorder. Qed.\n\nProgram Instance hasid_intersect U: HasIdentity _ (@Intersect U) := { mid := FullSet }.\nNext Obligation. firstorder. Qed.\nNext Obligation. firstorder. Qed.\n\nProgram Instance semigroup_intersect U: Semigroup _ (@Intersect U).\nProgram Instance monoid_intersect U: Monoid _ (@Intersect U).\nProgram Instance cmon_intersect U: CommMonoid _ (@Intersect U).\n\n\nLemma cat_unions_as_unionover: forall U (L: list (ESet U)),\n  MCat Union L == MCatOver Union id L.\nProof. move=> U L. by rewrite /MCatOver map_id. Qed.\n\nLemma cat_intersects_as_intersectover: forall U (L: list (ESet U)),\n  MCat Intersect L == MCatOver Intersect id L.\nProof. move=> U L. by rewrite /MCatOver map_id. Qed.\n\n\nLemma cat_unionover_compl: forall I U (L: list I) (F: I -> ESet U),\n  ~! (MCatOver Union F L) == MCatOver Intersect (fun i => ~! F i) L.\nProof. move=> I U L F. elim: L; firstorder. Qed.\n\nLemma cat_intersectover_compl: forall I U (L: list I) (F: I -> ESet U),\n  ~! (MCatOver Intersect F L) == MCatOver Union (fun i => ~! F i) L.\nProof. move=> I U L F. elim: L => [|a L IH]. firstorder.\n  constructor=> x. decides (x :in: F a); firstorder. Qed.\n\n\n(* Set of lists where each element is in a set *)\nDefinition ForallSet {U} (T: ESet U): ESet (list U) :=\n  mkSet (fun L => Forall (InSet T) L).\n\n(* Set of lists where at least single element is in a set *)\nDefinition ExistsSet {U} (T: ESet U): ESet (list U) :=\n  mkSet (fun L => Exists (InSet T) L).\n", "meta": {"author": "Abastro", "repo": "Coq-Practice", "sha": "2117c3e3a62ac0019ff2d7461fbd41eb561700dd", "save_path": "github-repos/coq/Abastro-Coq-Practice", "path": "github-repos/coq/Abastro-Coq-Practice/Coq-Practice-2117c3e3a62ac0019ff2d7461fbd41eb561700dd/Basin/ClSetLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.766415228242731}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\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\n(* -------------------------------- *)\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\n\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' =>\n            Some ((binopDenote b) arg1 arg2 :: s')\n        | _ =>\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(* \"Compiling e and executing it is the same as\n   pushing the value of expDonte on the stack\" *)\nLemma compile_correct' : forall e p s, \n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n    induction e; crush.\n\nTheorem compile_correct : \n    forall e, progDenote (compile e) nil = Some (expDenote e :: nil).", "meta": {"author": "nikomatsakis", "repo": "coq-a-doodle-do", "sha": "fda3c3a6acaece029b4a7ac086556c078121cee6", "save_path": "github-repos/coq/nikomatsakis-coq-a-doodle-do", "path": "github-repos/coq/nikomatsakis-coq-a-doodle-do/coq-a-doodle-do-fda3c3a6acaece029b4a7ac086556c078121cee6/cpdt-chapters/chapter2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7664152264833202}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\nFrom Coq Require Import Setoids.Setoid.\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_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n    intros. split.\n    - destruct n .\n    -- reflexivity.\n    -- discriminate.\n    - destruct m .\n    -- reflexivity.\n    -- rewrite<-plus_n_Sm in H. discriminate.\nQed.\n\nLemma 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 proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n    intros P Q [_ HQ].\n    apply HQ.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP. 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\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\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    ~P -> (forall (Q:Prop), P -> Q).\nProof.\n    intros. destruct H. apply H0. Qed.\n    \nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\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.\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 P Q H. unfold not. intros. apply H in H1. apply H0 in H1.\n    apply H1. Qed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n    intros P. unfold not. intros [HP HNA]. apply HNA in HP.\n    apply HP. Qed.\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  - (* b = false *)\n    reflexivity.\nQed.\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H. (* note implicit destruct b here *)\n  - (* b = true *)\n    unfold not in H.\n    exfalso. (* <=== *)\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\nP \\/ (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. destruct H as [HPQ HPR]. destruct HPQ.\n    -- left. apply H. \n    -- destruct HPR.\n    + left. apply H0.\n    + right. split. apply H. apply H0.\nQed.\n\nLemma mult_eq_0: forall n m, n*m =0 -> n = 0 \\/ m = 0 .\nProof.\n    intros n m H. destruct n.\n    - left. reflexivity.\n    - destruct m.\n    -- right. reflexivity.\n    -- discriminate.\nQed.\n\nLemma eq_mult_0: forall n m, n=0 \\/ m =0-> n*m=0 .\nProof.\n    intros n m [Hn|Hm].\n    - rewrite->Hn. reflexivity.\n    - rewrite->Hm. apply mult_comm.\nQed.\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 :\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\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) -> ~ (exists x, not (P x)).\nProof.\n  intros. unfold not. intros. destruct H0. apply H0 in H. 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. split.\n    - intros [x [HP|HQ]]. \n    -- left. exists x. apply HP.\n    -- right. exists x. apply HQ.\n    - intros [HP | HQ].\n    -- destruct HP as [x HP]. exists x. left. apply HP.\n    -- destruct HQ as [x HQ]. exists x. right. apply HQ.\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.\n  (* WORKED IN CLASS *)\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  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nTheorem In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) <->\n    exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\n  - induction l as [|h t IH].\n  -- intros. simpl in H. destruct H.\n  -- intros. simpl. destruct H eqn:H1.\n    + exists h. split. apply e. left. reflexivity.\n    + clear H1. apply IH in i. destruct i. exists x. destruct H0. \n      split. apply H0. right. apply H1. \n  - induction l as [|h t IH].\n  -- intros. simpl in H. destruct H. destruct H. destruct H0.\n  -- intros. simpl. destruct H. simpl in H. destruct H.  \n     destruct H0. \n      * left. rewrite->H0. apply H.\n      * right. apply IH. exists x. split. apply H. apply H0.\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  - split.\n  -- simpl. intros. right. apply H.\n  -- simpl. intros. destruct H. destruct H. apply H.\n  - split.\n  -- simpl. intros. destruct H.\n  + left. left. apply H.\n  + apply IH in H. destruct H.\n  * left. right. apply H.\n  * right. apply H.\n  -- simpl. intros. destruct H as [[H1|H2]|H3].\n  + left. apply H1. \n  + right. apply IH. left. apply H2.\n  + right. apply IH. right. apply H3.  \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)\nend.\n\nTheorem All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <->\n    All P l.\nProof.\n  intros. split. \n  - intros. induction l as [|h t IH].\n  -- simpl. reflexivity.\n  -- simpl. split.\n  + apply H. simpl. left. reflexivity.\n  + apply IH. intros. simpl in H. apply H. right. apply H0.\n  - induction l as [|h t IH]. \n  + intros. simpl in H0. destruct H0.\n  + simpl. intros. destruct H. destruct H0.\n  * rewrite<-H0. apply H.\n  * apply IH. apply H1. apply H0.\nQed.\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\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (oddb n = true -> Podd n) ->\n    (oddb n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros. unfold combine_odd_even. destruct (oddb n) eqn:IH.\n  - simpl in H. 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. unfold combine_odd_even in H. destruct (oddb n).\n  - apply H. \n  - discriminate.\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. destruct (oddb n).\n  - discriminate.\n  - apply H.\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. intro Hl.\n  rewrite Hl in H.\n  simpl in H.\n  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\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\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 rev_append_empty: forall X (l1 l2:list X), rev_append l1 l2 = rev_append l1 []++ l2.\nProof.\n  intros X l1. induction l1.\n  - intros l2. reflexivity.\n  - intros l2. simpl. destruct l2 as [|h t].\n  -- rewrite app_nil_r. reflexivity.\n  -- rewrite IHl1. replace (rev_append l1 [x]) with (rev_append l1 [] ++ [x]).\n  + rewrite<- app_assoc. reflexivity.\n  + rewrite<-IHl1. reflexivity.\nQed. \n  \nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros. apply functional_extensionality. \n  unfold tr_rev. induction x as [|h t HX].\n  - reflexivity.\n  - simpl. rewrite<-HX. apply rev_append_empty.\nQed.\n\nDefinition even x := exists n : nat, x = double n.\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof. \n  intros. induction n.\n  - reflexivity.\n  - rewrite IHn. simpl. rewrite negb_involutive. reflexivity.\nQed.\n\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n  injection H as H1. apply H1. Qed.\n\nLemma evenb_double_conv : forall n, exists k,\n  n = if evenb n then double k else S (double k).\nProof.\n  intros. induction n as [|n' IH].\n  - simpl. exists 0. reflexivity.\n  - rewrite evenb_S. destruct (evenb n').\n  -- simpl. destruct IH. exists x. rewrite H. reflexivity.\n  -- simpl. destruct IH. exists (S x). rewrite H. simpl. reflexivity.\nQed.\n\nLemma 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 even_bool_prop : forall n,\n  evenb n = true <-> even n.\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\nTheorem andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros. split.\n  - intros. destruct b1.\n  + simpl in H. rewrite H. split. reflexivity. reflexivity.\n  + simpl in H. discriminate.\n  - intros. destruct b1.\n  + destruct H. rewrite H0. reflexivity.\n  + destruct H. simpl. apply H.\nQed.\n\nTheorem orb_true_iff : forall b1 b2,\n  orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros. split.\n  - intros. destruct b1.\n  -- left. reflexivity.\n  -- simpl in H. right. apply H.\n  - intros. destruct H.\n  -- rewrite H. simpl. reflexivity.\n  -- destruct b1.\n  + reflexivity.\n  + simpl. apply H. \nQed.\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  intros. split.\n  - rewrite<- not_true_iff_false. intros. intros H'.\n  destruct H. rewrite H'. symmetry. apply eqb_refl.\n  - rewrite<- not_true_iff_false. intros. intros H'.\n  destruct H. apply eqb_true in H'. apply H'.\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  |h::t,nil=>false\n  |nil,h::t=>false\n  |h1::t1,h2::t2=>(eqb h1 h2) && (eqb_list eqb t1 t2)\nend.\n\nLemma andb_true_elim1: forall a b , (a && b) =true->a = true.\nProof.\n  intros. destruct a.\n  - reflexivity.\n  - simpl in H. apply H.\nQed.\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. split.\n  - generalize dependent l2. induction l1 as [|h t IH].\n  -- simpl. destruct l2. \n  + reflexivity. \n  + intros. discriminate.\n  -- simpl. destruct l2 as [|h' t'].\n  + intros. discriminate.\n  + intros. apply andb_true_iff in H0. destruct H0. \n    apply H in H0. rewrite H0. apply IH in H1. rewrite H1.\n    reflexivity.\n  - generalize dependent l2. induction l1 as [|h t IH].\n  -- simpl. intros. destruct l2.\n  + reflexivity.\n  + discriminate.\n  -- simpl. intros. destruct l2.\n  + discriminate.\n  + injection H0 as H0. apply H in H0. apply IH in H1.\n    rewrite H0. rewrite H1. 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\nTheorem forallb_true_iff : forall X test (l : list X),\n   forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  intros. split.\n  - intros. induction l as [|h t IH].\n  -- reflexivity.\n  -- simpl. simpl in H. apply andb_true_iff in H.\n    destruct H as [H1 H2]. split. \n  + apply H1. \n  + apply IH in H2. apply H2.\n  - intros. induction l as [|h t IH].\n  -- reflexivity.\n  -- simpl. simpl in H. destruct H as [H1 H2].\n  rewrite H1. apply IH in H2. rewrite H2. reflexivity.\nQed.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\nTheorem restricted_excluded_middle : forall P (b : bool),\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\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H.\n  apply H. right. intros. apply H. left. apply H0.\nQed.\n\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7663607457675243}}
{"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(*  ===> 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 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 *) \n    reflexivity.\n  - (* n = S n' *) \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, standard, optional (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 H. apply plus_comm. \nQed.\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\n  | no.\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, 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\n(*\n  forall P: rgb -> Prop,\n    P red ->\n    P green ->\n    P blue ->\n    forall x: rgb, P x \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(* ===> (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, standard, optional (natlist1)  \n\n    Suppose we had written the above definition a little\n   differently: *)\n\nInductive natlist1 : Type :=\n  | nnil1\n  | nsnoc1 (l : natlist1) (n : nat).\n\n(** Now what will the induction principle look like? \nnatlist1_ind:\n  forall P: natlist1 -> Prop,\n    \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\n(** **** Exercise: 1 star, standard, optional (byntree_ind)  \n\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\n | bleaf (yn : yesno)\n | nbranch (yn : yesno) (t1 t2 : byntree).\n(** [] *)\n\n\n(*\n( byntree_ind: forall P: byntree -> Prop,\n    ( P bempty ) ->\n    ( forall yn:yesno, P (blead yn) ) ->\n    ( forall yn:yesno (t1 t2:byntree), P t1 -> P t2 -> P (nbranch yn t1 t2)) ->\n    forall t:byntree, P t\n*)\n\nCheck byntree_ind.\n(** **** Exercise: 1 star, standard, optional (ex_set)  \n\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  | con1 (b:bool)\n  | cons2 (n:nat) (e: ExSet). \n\nCheck ExSet_ind.\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, 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\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n(*\n  tree_ind: \n    forall (X : Type) (P : tree X -> Prop),\n    (forall x : X, P (leaf X x)) ->\n    (forall t1 : tree X,\n      P t1 ->\n        forall t2 : tree X,\n        P t2 -> P (node X t1 t2)) ->\n          forall t : tree X, P t\n*)\n\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(* mytype X is a type \n   mytype: Type -> Type\n*)\nInductive mytype (X: Type) :=\n  | constr1 (x:X)\n  | constr2 (n:nat)\n  | constr3 (m: mytype X) (n:nat).\n\nCheck mytype_ind.\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\nInductive foo (X Y:Type) :=\n  | bar (x : X)\n  | baz (y : Y)\n  | quux (f1: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\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), P f -> P (C1 X k f)) ->\n              P (C2 X) ->\n             forall f : foo' X, P f\n*)\n\nCheck foo'_ind.\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    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, standard, optional (plus_explicit_prop)  \n\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\nCheck nat_ind.\n\nDefinition P_plus_assoc (m:nat): Prop := \n  forall n p, (m + n) + p = m + (n + p).\n\nDefinition P_plus_comm (m:nat): Prop := forall n, m + n = n + m. \n\nTheorem plus_comm_from_def: forall m, P_plus_comm m.\nProof.\n  apply nat_ind.\n  - unfold P_plus_comm.\n    apply nat_ind.\n    { reflexivity. }\n    { intros n H. simpl.\n      rewrite <- H. simpl.\n      reflexivity.\n    } \n  - unfold P_plus_comm.\n    intros n H.\n    intros n0.\n    simpl.\n    Search (_ + S _ = S (_ + _)).\n    rewrite plus_n_Sm.\n    rewrite H.\n    reflexivity.\nQed.\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 [even] are a\n    tiny bit more complicated.  As with all induction principles, we\n    want to use the induction principle on [even] to prove things by\n    inductively considering the possible shapes that something in [even]\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 [even]...\n\n      Inductive even : nat -> Prop :=\n      | ev_0 : even 0\n      | ev_SS : forall n : nat, even n -> even (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, even n -> Prop),\n         P O ev_0 ->\n         (forall (m : nat) (E : even m),\n            P m E ->\n            P (S (S m)) (ev_SS m E)) ->\n         forall (n : nat) (E : even n),\n         P n E\n\n     ... because:\n\n     - Since [even] is indexed by a number [n] (every [even] 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 [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 [even]: *)\n\nCheck even_ind.\n(* ===> ev_ind\n        : forall P : nat -> Prop,\n          P 0 ->\n          (forall n : nat, even n -> P n -> P (S (S n))) ->\n          forall n : nat,\n          even 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].  For example, we can use it to show that [even'] (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 [even]: *)\nTheorem ev_ev' : forall n, even n -> even' n.\nProof.\n  apply even_ind.\n  - (* ev_0 *)\n    apply even'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (even'_sum 2 m).\n    + apply even'_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 m (H : 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(* Wed Jan 9 12:02:46 EST 2019 *)\n", "meta": {"author": "ConDai", "repo": "LogicalFoundations", "sha": "6f348aeb84102960192e648d88899aa2e4c770c9", "save_path": "github-repos/coq/ConDai-LogicalFoundations", "path": "github-repos/coq/ConDai-LogicalFoundations/LogicalFoundations-6f348aeb84102960192e648d88899aa2e4c770c9/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.9149009468718409, "lm_q1q2_score": 0.7663392864467402}}
{"text": "(** Calculation of the simple arithmetic language. *)\n\nRequire Import Tactics.\nRequire Export Memory.\nModule Arith (mem : MemoryExt).\nImport mem.\n\n(** * Syntax *)\n\nInductive var := X | Y | Z.\n\nInductive Expr : Set :=\n| Val : nat -> Expr \n| Add : Expr -> Expr -> Expr\n| Var : var -> Expr.\n\n(** * Semantics *)\n\nDefinition env := var -> nat.\n\nFixpoint eval (e : env) (x: Expr) : nat :=\n  match x with\n    | Val n => n\n    | Add x1 x2 => eval e x1 + eval e x2\n    | Var v => e v\n  end.\n\n(** * Compiler *)\n\nInductive Code : Set :=\n| LOAD : nat -> Code -> Code\n| LDA : adr -> Code -> Code\n| ADD : adr -> Code -> Code\n| STORE : adr -> Code -> Code\n| HALT : Code.\n\nFixpoint comp' (x : Expr) (vars: var -> adr) (r : adr) (c : Code) : Code :=\n  match x with\n  | Val n => LOAD n c\n  | Add x1 x2 => comp' x1  vars r (STORE r (comp' x2 vars (next r) (ADD r c)))\n  | Var v => LDA (vars v) c\n  end.\n\nDefinition mkVars : var -> adr :=\n  fun v =>\n    match v with\n    | X => first\n    | Y => next first\n    | Z => next (next first)\n    end.\n\nDefinition firstFresh : adr := next (next (next first)).\n\nDefinition mkMem (e : env) : Mem :=\n  set (mkVars Z) (e Z) ((set (mkVars Y) (e Y) (set (mkVars X) (e X) empty))).  \n  \n  \nDefinition comp (x : Expr) : Code := comp' x mkVars firstFresh 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)\n| vm_lda c r m a : (LDA r c, m, a) ==> (c, m, get r m)\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\nLemma env_fresh (e : env) vars r m\n  (Fresh : forall v, vars v < r)\n  (Env : forall v, e v = get (vars v) m) v n:\n  e v = get (vars v) (set r n m).\nProof.\n  rewrite get_set'; auto using next_fresh.\nQed.\n  \n  \n(** Specification of the compiler *)\n\nTheorem spec x r c a m vars e\n  (Fresh : forall v, vars v < r)\n  (Env : forall v, e v = get (vars v) m):\n  isFreeFrom r m ->\n  (comp' x vars r c, m, a) =>> (c , m, eval e 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 e x1 + eval e x2).\n  = {rewrite isFreeFrom_free, get_set}\n    (c, free r (set r (eval e x1) m), get r (set r (eval e x1) m)  + eval e x2).\n  <== {apply vm_add}\n    (ADD r c, set r (eval e x1) m, eval e x2).\n  <<= {apply IHx2; auto using isFreeFrom_set, env_fresh}\n    (comp' x2 vars (next r) (ADD r c), set r (eval e x1) m, eval e x1).\n  <== {apply vm_store}\n    (STORE r (comp' x2 vars (next r) (ADD r c)), m, eval e x1).\n  <<= { apply IHx1}\n    (comp' x1 vars r (STORE r (comp' x2 vars (next r) (ADD r c))), m, a).\n  [].\n\n(** - [x = Var v]: *)\n  \n  begin\n    (c, m, e v).\n  = {rewrite Env}\n    (c, m, get (vars v) m).\n  <<= {apply vm_lda}\n    (LDA (vars v) c , m, a).  \n  [].\nQed.\n\n\nLemma mkMemEnv (e : env) (v : var) : e v = get (mkVars v) (mkMem e).\nProof.\n  destruct v;\n  unfold mkMem; simpl;\n    repeat first [rewrite get_set' by (apply next_fresh; auto) | rewrite get_set];\n    reflexivity.\nQed.\n\nLemma mkVarsFresh v : mkVars v < firstFresh.\nProof.\n  unfold firstFresh. destruct v; simpl; auto.\nQed.\n\nLemma isFreeFromFirst e : isFreeFrom firstFresh (mkMem e).\nProof.\n  unfold mkMem. simpl. eauto using isFreeFrom_first, isFreeFrom_set.\nQed. \n\nTheorem spec_top x a e:\n  (comp x, mkMem e, a) =>> (HALT , mkMem e, eval e x).\nProof.\n  apply spec.\n  - apply mkVarsFresh.\n  - apply mkMemEnv.\n  - apply isFreeFromFirst.\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 e : (comp x, mkMem e, a) =>>! C -> C = (HALT , mkMem e, eval e x).\nProof.\n  intros.\n  pose (spec_top x) as H'. unfold comp in *. pose (determ_trc determ_vm) as D.\n  unfold determ in D. eapply D. apply H. split. apply H'. 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/Vars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7662523188374707}}
{"text": "(* pair constructing *)\n\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\n(* getting first or second *)\nDefinition fst (p : natprod) : nat :=\n    match p with\n    | pair x y => x\n    end.\nDefinition snd (p : natprod) : nat :=\n    match p with\n    | pair x y => y\n    end.\n\nCompute fst(pair 1 2). (* 1 *)\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(* Note that pattern-matching on a pair (with parentheses: (x, y)) is not to be confused with the \"multiple pattern\" syntax (with no parentheses: x, y) that we have seen previously. The above examples illustrate pattern matching on a pair with elements x and y, whereas, for example, the definition of minus in Basics performs pattern matching on the values n and m: *)\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 distinction is minor, but it is worth knowing that they are not the same.  *)\n\n(* Now let's try to prove a few simple facts about pairs.\nIf we state properties of pairs in a slightly peculiar way, we can sometimes complete their 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 just reflexivity is not enough if we state the lemma in the most natural way: *)\nTheorem surjective_pairing_stuck : forall (p : natprod),\n    p = (fst p, snd p).\nProof.\n    simpl. (* Doesn't reduce anything! *) Abort.\n\n(* Instead, we need to expose the structure of p so that simpl can perform the pattern match in fst and snd. We can do this with destruct. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n    intros p. destruct p as [n m].\n    simpl. reflexivity. Qed.\n\n(* Notice that, unlike its behavior with nats, where it generates two subgoals, destruct generates just one subgoal here. That's because natprods can only be constructed in one way. *)", "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/pairs_of_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.9124361634533147, "lm_q1q2_score": 0.7662036471035245}}
{"text": "Require Export D.\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\nend.\n\nDefinition snd (p:natprod) : nat :=\n  match p with\n| pair x y => y\nend.\n\nNotation \"( x , y )\" := (pair x y).\n\nEval compute in (fst (3,5)).\n\nDefinition swap_pari (p:natprod) : natprod :=\n(snd p, fst p).\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) ..).\n\nFixpoint repeat (n count:nat) : natlist :=\n  match count with\n| O => nil\n| S c => n::(repeat n c)\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 :=\nmatch l1 with\n|[] => l2\n|hd::tl => hd::(app tl l2)\nend.\n\nDefinition hd (default:nat) (l:natlist) : nat :=\nmatch l with\n| [] => default\n| hd::tl => hd\nend.\n\nDefinition tl (l:natlist) : natlist :=\nmatch l with\n| [] => []\n| hd::tl => tl\nend.\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 :=\nmatch l with\n|[] => []\n|hd::tl => if beq_nat hd 0 then nonzeros tl\n          else hd::(nonzeros tl)\nend.\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\nmatch l with\n|[] => []\n|hd::tl => if oddb hd then hd::(oddmembers tl)\n          else oddmembers tl\nend.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\n\nFixpoint countoddmembers (l:natlist) : nat :=\nmatch l with\n|[] => O\n|hd::tl => if oddb hd then S (countoddmembers tl)\n          else countoddmembers tl\nend.\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\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\nmatch l with\n| [] => [v]\n| hd::tl => hd::(snoc tl v)\nend.\n\nFixpoint rev (l:natlist) : natlist :=\nmatch l with\n|[] => []\n|hd::tl => snoc (rev tl) hd\nend.\nExample test_rev1: rev [1;2;3] = [3;2;1].\nProof. reflexivity. Qed.\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nInductive natoption : Type :=\n|Some : nat ->natoption\n|None : natoption\n.\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\nmatch l with\n|[] => None\n|hd::tl => if beq_nat n 0 then Some hd\n          else index (pred n) tl\nend.\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\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/List_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.7660050124449537}}
{"text": "From LF Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Type := \n| pair : nat -> nat -> natprod.\n\n\nCheck (pair 3 5).\n\nDefinition fst (p : natprod) : nat := \n    match p with \n    | pair x y => x\nend.\n\nDefinition snd (p : natprod) : nat := \n    match p with \n    | pair x y => y\nend.\n\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (4,5)).\n\n\nDefinition fst' (p : natprod ) : nat :=\nmatch p with\n| (x,y) => x\nend.\nDefinition snd' (p : natprod ) : nat :=\nmatch p with\n| (x,y) => y\nend.\nDefinition swap_pair (p : natprod ) : natprod :=\nmatch p with\n| (x,y) => (y,x )\nend.\n\nTheorem surjective_pairing' : forall (n m : nat),\n(n,m) = (fst (n,m), snd (n,m)).\nProof.\nreflexivity. Qed.\n\nTheorem surjective_pairing : forall (p : natprod ),\np = (fst p, snd p).\nProof.\n    intros p.\n    destruct p as [n m]. simpl. reflexivity.\nQed.\n\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\n\nTheorem fst_swap_is_snd : forall (p : natprod ),\nfst (swap_pair p) = snd p.\nProof.\n    intros p.\n    destruct p as [n m].\n    simpl.\n    reflexivity.\nQed.\n\nInductive natlist: Type := \n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\nNotation \" x :: l \" := (cons x l).\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil)..).\n\nNotation \"[ ]\" := nil.\n\nFixpoint repeat (n count : nat) : natlist := \nmatch count with \n    | O => nil\n    | S count' => n :: (repeat n count')\nend.\n\nFixpoint length (l:natlist) : nat := \nmatch l with \n    | nil => O\n    | h :: t => S (length t)\nend.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\nmatch l1 with\n    | nil => l2\n    | h :: t => h :: (app t l2 )\nend.\n\nNotation \"x ++ y\" := (app x y).\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 :=\nmatch l with\n    | nil => default\n    | h :: t => h\nend.\nDefinition tl (l :natlist) : natlist :=\nmatch l with\n    | nil => nil\n    | h :: t => t\nend.\nExample test_hd1 : hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2 : hd 0 nil = 0.\nProof. reflexivity. Qed.\nExample test_tl : tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\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' => h :: (nonzeros t)\n                end\nend.\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l :natlist) : natlist :=\nmatch l with \n    | nil => nil\n    | h :: t => match (odd h) with\n                | false => oddmembers t\n                | true => h :: (oddmembers t)\n                end\nend.\n\n\nExample test_oddmembers:\noddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\n\nFixpoint countoddmembers (l :natlist) : nat :=\nmatch l with \n    | nil => O\n    | h :: t => match (odd h) with\n                | false => countoddmembers t\n                | true => S (countoddmembers t)\n                end\nend.\n\nExample test_countoddmembers1 :\ncountoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers2 :\ncountoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3 :\ncountoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1 with\n    | nil => l2\n    | h1 :: t1 => match l2 with \n                    | nil => h1 :: t1\n                    | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n                end\nend. \n\nExample test_alternate1 :\nalternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate2 :\nalternate [1] [4;5;6] = [1;4;5;6].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate3 :\nalternate [1;2;3] [4] = [1;4;2;3].\nProof. simpl. reflexivity. Qed.\n\nExample test_alternate4 :\nalternate [] [20;30] = [20;30].\nProof. simpl. reflexivity. Qed.\n\n\nDefinition bag := natlist.\n\nFixpoint count (v :nat) (s:bag) : nat :=\nmatch s with \n    | nil => O\n    | h :: t => match eqb v h with\n                | true => S (count v t)\n                | false => count v t\n                end\nend.\n\n\nExample test_count1 : count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_count2 : count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition sum : bag -> bag -> bag :=\napp.\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 :=\nv :: s.\n\nExample test_add1 : count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_add2 : count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v :nat) (s:bag) : bool :=\nltb 0 (count v s).\n\nExample test_member1 : member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_member2 : member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n\nFixpoint remove_one (v :nat) (s:bag) : bag :=\nmatch s with\n    | nil => nil\n    | h :: t => match eqb h v with \n                | true => t\n                | false => h :: remove_one v t\n                end\nend.\n\n\nExample test_remove_one1 :\ncount 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one2 :\ncount 5 (remove_one 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one3 :\ncount 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_one4 :\ncount 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint remove_all (v :nat) (s:bag) : bag :=\n    match s with\n    | nil => nil\n    | h :: t => match eqb h v with \n                | true => remove_all v t\n                | false => h :: remove_all v t\n                end\nend.\n\n\nExample test_remove_all1 : count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all2 : count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all3 : count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_remove_all4 : count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint subset (s1 :bag) (s2 :bag) : bool :=\nmatch s1 with \n    | nil => true\n    | h :: t => match leb (count h s1)  (count h s2) with \n                | true => subset t s2\n                | false => false\n                end\nend.\n\n\nExample test_subset1 : subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_subset2 : subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem bag_sum_nil: forall (b : bag), sum b [] = b .\nProof.\n    induction b as [|h' t' IHb'].\n    - reflexivity.\n    - simpl. rewrite IHb'. reflexivity.\nQed.\n\nTheorem leb_n_Sn: forall n : nat, leb n (S n) = true.\nProof.\n    induction n as [|n' IHn'].\n    - reflexivity.\n    - simpl. rewrite IHn'. reflexivity.\nQed.\n\n\nTheorem bag_theorem1 : forall v1 v2 : nat, forall b: bag, leb (count v1 b) (count v1 (add v2 b)) = true. \nProof.\n    intros v1 v2 b.\n    induction b as [|h t IHb'].\n    - reflexivity.\n    - simpl. destruct (eqb v1 h) as [|].\n        -- destruct (eqb v1 v2) as [|].\n            --- simpl. rewrite -> leb_n_Sn. reflexivity.\n            --- simpl. rewrite leb_refl. reflexivity.\n        -- destruct (eqb v1 v2) as [|].\n            --- simpl. rewrite -> leb_n_Sn. reflexivity.\n            --- simpl. rewrite leb_refl. reflexivity.\nQed.\n\nTheorem bag_theorem2 : forall v : nat, forall b1 b2 : bag, leb (count v b1) (count v (sum b1 b2)) = true. \nProof.\n    intros v b1 b2.\n    induction b1 as [|h1 b1 IHb1].\n    - simpl. reflexivity.\n    - simpl. destruct (eqb v h1) as [|].\n        -- simpl. rewrite IHb1. reflexivity.\n        -- rewrite IHb1. reflexivity.\nQed.\n\n(* Theorem bag_theorem3 : forall v : nat, forall b1 b2, (member v b1) && (member v b2) = true -> subset b1 b2 = true .\nProof.\n    intros v.\n    intros b1 b2.\n    destruct (member v b1) as [|].\n    - destruct (member v b2) as [|].\n        -- simpl. induction b1 as [|h1 t1 IHb1].\n            --- reflexivity.\n            --- assert(H1 : member v b2 = true). {\n                reflexivity.\n                }\nQed. *)\n\n(* \nTheorem bag_theorem3 : forall v : nat, forall b , subset b (v :: b) = true.\nProof.\n    intros v b.\n    induction b\n\nTheorem bag_theorem3 : forall b , subset b b = true.\nProof.\n    intros b.\n    induction b as [|h t IHb].\n    - reflexivity.\n    - simpl. rewrite <- eqb_refl. simpl. rewrite <- leb_refl. simpl.\n\n\n\nTheorem bag_theorem3 : forall b1 b2 : bag, subset b1 (sum b1 b2) = true.\nProof.\n    induction b1 as [|h1 t1 IHb].\n    - simpl. reflexivity.\n    - simpl. rewrite <- eqb_refl. simpl. intros b2. rewrite bag_theorem2.\n        assert(H1 : leb (count h1 t1) (count h1 (sum t1 b2)) = true). { \n            rewrite bag_theorem2. reflexivity\n        }\n        \n        rewrite -> bag_theorem2.  destruct (eqb h1 v) as [|].\n        -- simpl. rewrite leb_n_Sn.\n\n\nTheorem bag_theorem3 : forall v : nat, forall b1 b2 , subset b1 (v :: sum b1 b2) = subset b1 (sum b1 b2).\nProof.\n    intros v b1 b2.\n    induction b2 as [|h2 t2 IHb2].\n    - rewrite bag_sum_nil. rewrite reflexivity.\n    - simpl. rewrite <- eqb_refl. simpl. destruct (eqb h1 v) as [|].\n        -- rewrite -> bag_theorem2. rewrite <- leb_n_Sn.\n\nTheorem bag_theorem : forall b1 b2 : bag, subset b1 (sum b1 b2) = true.\nProof.\n    intros b1 b2.\n    induction b1 as [|h1 t1 IHb1].\n    -- simpl. reflexivity.\n    -- simpl. rewrite <- eqb_refl. simpl. rewrite bag_theorem2. simpl. *)\n\nTheorem nil_app: forall l : natlist, [] ++ l = l.\nProof.\n    reflexivity.\nQed.\n\nTheorem tl_length_pred : forall l :natlist,\npred (length l ) = length (tl l ).\nProof.\n    intros l. destruct l as [| n l' ].\n    - reflexivity.\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    - reflexivity.\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 app_length : forall l1 l2 : natlist,\nlength (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\n\nTheorem rev_length_firsttry : forall l : natlist,\nlength (rev l ) = length l.\nProof.\n    intros l.\n    induction l as [|n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite -> app_length. rewrite -> add_comm. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\nl ++ [] = l.\nProof.\n    induction l as [|n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite IHl'. reflexivity.\nQed.\n\nTheorem rev_add_n: forall l : natlist, forall n : nat, rev(l ++ [n]) = [n] ++ rev l.\nProof.\n    intros l n.\n    induction l as [|h l' IHl'].\n    - reflexivity.\n    - simpl. rewrite IHl'. reflexivity.\nQed.\n\n\n\nTheorem rev_involutive : forall l : natlist,\nrev (rev l ) = l.\nProof.\n    intros l.\n    induction l as [|n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite rev_add_n. rewrite IHl'. reflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\nl1 ++ (l2 ++ (l3 ++ l4 )) = ((l1 ++ l2 ) ++ l3 ) ++ l4.\nProof.\n    intros l1 l2 l3 l4.\n    rewrite app_assoc.\n    rewrite app_assoc.\n    reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\nnonzeros (l1 ++ l2 ) = (nonzeros l1 ) ++ (nonzeros l2 ).\nProof.\n    intros l1 l2.\n    induction l1 as [|n l1' IHl1'].\n    - reflexivity.\n    - simpl. destruct n as [|n'].\n        -- rewrite IHl1'. reflexivity.\n        -- rewrite IHl1'. simpl. reflexivity.\nQed.\n\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\nmatch l1 with\n| nil => match l2 with \n            | nil => true\n            | n2::l2' => false\n        end\n| n1::l1' => match l2 with \n            | nil => false\n            | n2::l2' => match eqb n1 n2 with\n                    | true => eqblist l1' l2'\n                    | false => false\n                    end\n            end\nend.\n\nExample test_eqblist1 :\n(eqblist nil nil = true).\nProof. reflexivity. Qed.\n\nExample test_eqblist2 :\neqblist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\neqblist [1;2;3] [1;2;4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l :natlist,\ntrue = eqblist l l.\nProof.\n    intros l.\n    induction l as [|n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite eqb_refl. rewrite IHl'. reflexivity.\nQed.\n\n\nTheorem count_member_nonzero : forall (s : bag),\nleb 1 (count 1 (1 :: s)) = true.\nProof.\n    intros s.\n    induction s as [|h t IHs'].\n    - reflexivity.\n    - simpl. reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n,\nleb n (S n) = true.\nProof.\n    intros n. induction n as [| n' IHn' ].\n    - simpl. reflexivity.\n    - simpl. rewrite IHn'. reflexivity. \nQed.\n\nTheorem remove_decreases_count: forall (s : bag),\nleb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n    induction s as [| h t IHs'].\n    - reflexivity.\n    - simpl. destruct h as [| h'].\n        -- simpl. rewrite ble_n_Sn. reflexivity.\n        -- simpl. rewrite IHs'. reflexivity.\nQed.\n\nTheorem rev_injective: forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n    intros l1 l2 H.\n    replace l1 with (rev (rev l1)).\n    replace l2 with (rev (rev l2)).\n    - rewrite H. reflexivity.\n    - rewrite rev_involutive. reflexivity.\n    - rewrite rev_involutive. reflexivity.\nQed.\n\n\nInductive natoption : Type :=\n| Some : nat -> natoption\n| None : natoption.\n\nFixpoint nth_error (l :natlist) (n:nat) : natoption :=\nmatch l with\n| nil => None\n| a :: l' => match eqb n O with\n        | true => Some a\n        | false => nth_error l' (pred n)\n        end\nend.\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 :=\nmatch o with\n| Some n' => n'\n| None => d\nend.\n\nDefinition hd_error (l : natlist) : natoption :=\nmatch l with \n| nil => None\n| n :: t => Some n\nend.\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\nTheorem option_elim_hd : forall (l :natlist) (default:nat),\nhd default l = option_elim default (hd_error l ).\nProof.\n    intros l default.\n    destruct l as [|h t].\n    - reflexivity.\n    - simpl. reflexivity.\nQed.\n\nInductive id : Type :=\n| Id : nat -> id.\n\nDefinition beq_id x1 x2 :=\nmatch x1, x2 with\n| Id n1, Id n2 => eqb n1 n2\nend.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n    intros x.\n    destruct x as [].\n    simpl. rewrite eqb_refl. reflexivity.\nQed.\n\nEnd NatList.\n\nModule PartialMap.\nImport NatList.\n\nInductive partial_map : Type :=\n| empty : partial_map\n| record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d : partial_map) (key : id) (value : nat) : partial_map :=\nrecord key value d.\n\n\nFixpoint find (key : id ) (d : partial_map) : natoption :=\nmatch d with\n| empty => None\n| record k v d' => if beq_id key k\n                    then Some v\n                    else find key d'\nend.\n\nTheorem update_eq :\nforall (d : partial_map) (k : id ) (v : nat),\nfind k (update d k v ) = Some v.\nProof.\n    intros d k v.\n    destruct d as [|id' n' d'].\n    - simpl. rewrite <- beq_id_refl. reflexivity.\n    - simpl. rewrite <- beq_id_refl. reflexivity.\nQed.\n\nTheorem update_neq :\nforall (d : partial_map) (m n : id ) (o: nat),\nbeq_id m n = false -> find m (update d n o) = find m d.\nProof.\n    intros d m n o H.\n    simpl. rewrite H. reflexivity.\nQed.\n\n(* Inductive baz : Type :=\n| Baz1 : baz -> baz\n| Baz2 : baz -> bool -> baz.\nHow many elements does the type baz have? zero *)\n\nDefinition injective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => forall x1 x2, f1 x1 = f1 x2 -> x1 = x2.\n\nDefinition surjective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => forall x1, exists x2, f1 x2 = x1.\n\nDefinition bijective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => injective f1 /\\ surjective f1.\n\nInductive baz : Type :=\n    | x : baz -> baz\n    | y : baz -> bool -> baz.\n\nTheorem baz_False : baz -> False. \nProof. \n    induction 1; \n    firstorder.\nQed.\n\nGoal exists f1 : baz -> False, bijective f1.\nProof.\nexists baz_False. unfold bijective, injective, surjective. firstorder.\nassert (H2 := baz_False x1). firstorder.\nassert (H2 := x1). firstorder.\nQed.\n\nEnd PartialMap.", "meta": {"author": "ppx123-web", "repo": "SF", "sha": "50d6508ca6dc3e7b8c7cd93ed5d7197416f50e4b", "save_path": "github-repos/coq/ppx123-web-SF", "path": "github-repos/coq/ppx123-web-SF/SF-50d6508ca6dc3e7b8c7cd93ed5d7197416f50e4b/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.7660049836337239}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition next (p: nat * nat): nat * nat :=\n  match p with \n  | (0, y) => (S y, 0)\n  | (S x, y) => (x, S y)\n  end.\n\nCompute (next (0,0)).\nCompute (next (1,0)).\nCompute (next (0, 1)).\nCompute (next (3, 3)).\n\nFixpoint decode (n: nat): nat * nat :=\n  match n with\n  | 0 => (0, 0)\n  | S n' => next (decode n')\n  end.\n\nFixpoint s (n: nat) := \n  match n with \n  | 0 => 0\n  | S n' => n + s n'\n  end.\n\nDefinition encode (p: nat * nat): nat :=\n  let (x, y) := p in s (x + y) + y.\n\n(* 7.2.1 *)\nTheorem step: forall c, encode (next c) = S (encode c).\nProof.\n  move => [x y].\n  elim x.\n    by rewrite /next /encode 2!addn0 add0n /(s y.+1) -/s addSn addnC.\n  move => n IH.\n  by rewrite /next /encode addnS addSn addnS.\nQed.\n\n(* 7.2.2 *)\nTheorem eq: forall n, encode (decode n) = n.\nProof.\n  elim => [//| n IH].\n  by rewrite /decode -/decode step IH.\nQed.\n\n(* 7.2.3 *)\nLemma enc0: forall c, encode c = 0 -> c = (0, 0).\nProof.\n  move => [x y].\n  case x; case y => //.\nQed.\n\nLemma step_enc: forall x y, next (S x, y) = (x, S y).\nProof. by []. Qed.\n\nLemma step_enc': forall x, next (0, x) = (S x, 0).\nProof. by []. Qed.\n\nTheorem eq': forall c, decode (encode c) = c.\nProof.\n  move => c.\n  (* elim: {-1}(encode c) (erefl (encode c)). *)\n  have H: (forall ec, encode c = ec -> decode ec = c) -> (decode (encode c) = c).\n    move => Hec.\n    by apply Hec.\n  apply H => {H}.\n  move => ec.\n  move: c.\n  elim: ec => [c |n IH c].\n    by move/enc0 ->.\n  rewrite /decode -/decode.\n  case: c IH => [x y] IH.\n  case x; case y => //.\n    move => n'.\n    rewrite -step_enc step => H.\n    rewrite (IH (1, n')) => //.\n    by apply (eq_add_S _ _ H).\n\n    move => n'.\n    rewrite -step_enc' step => H.\n    rewrite (IH (0, n')) => //.\n    by apply (eq_add_S _ _ H).\n\n    move => n' n''.\n    rewrite -step_enc step => H.\n    rewrite (IH (n''.+2, n')) => //.\n    by apply (eq_add_S _ _ H).\nQed.\n\n(* 7.2.4 *)\n\nSection tst.\nVariables x y: nat.\nGoal x = y -> x == y.\nProof.\n  move/eqnP. (* reflection between = and eqn *)\n  Print eqnP.\n  Search (eqn _ _ = _ == _).\n  Print erefl.\n  rewrite {1}eqnE. (* equality betweek eqn and == *)\n  by [].\nQed.\nEnd tst.", "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/ch7_cantor_pairing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7659830638262392}}
{"text": "Require Import not.\n\nLemma four_is_even : exists (n:nat), 4 = n + n.\nProof. exists 2. reflexivity. Qed.\n\n\nTheorem exsists_example2 : forall (n:nat),\n    (exists m, n = 4 + m) -> (exists p, n = 2 + p).\nProof. intros n [m H]. exists (2 + m). apply H. Qed.\n\n\nTheorem forall_exists : forall (a:Type) (P:a -> Prop),\n    (forall x, P x) -> ¬ (exists x, ¬ P x).\nProof. intros a P H [x H']. apply H'. apply H. Qed.\n\n\nTheorem exists_or : forall (a:Type) (P Q:a -> Prop),\n    (exists x, P x \\/ Q x) <-> (exists x, P x) \\/ (exists x, Q x).\nProof.\n    intros a P Q. split.\n    - intros [x [Hp|Hq]].\n        + left. exists x. exact Hp.\n        + right. exists x. exact Hq.\n    - intros [[x Hp]|[x Hq]].\n        + exists x. left. exact Hp.\n        + exists x. right. exact Hq.\nQed.\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/sf/exists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7659830542967164}}
{"text": "(* In this file, we have formalized the (correct) notion of isomorphisms in dagger categories, the so called unitary morphisms.\nNotice that this definition is different compared to (non-dagger) categories, therefore, we can not reuse is_z_isomorphism. *)\n\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.DaggerCategories.Categories.\n\nLocal Open Scope cat.\n\nSection UnitaryMorphisms.\n\n  Definition is_unitary\n             {C : category} (dag : dagger_structure C)\n             {x y : C} (f : C⟦x,y⟧)\n    : UU := is_inverse_in_precat f (dag x y f).\n\n  Lemma isaprop_is_unitary\n        {C : category} (dag : dagger_structure C)\n        {x y : C} (f : C⟦x,y⟧)\n    : isaprop (is_unitary dag f).\n  Proof.\n    apply isaprop_is_inverse_in_precat.\n  Qed.\n\n  Definition unitary {C : category} (dag : dagger_structure C)\n             (x y : C)\n    : UU\n    := ∑ f : C⟦x,y⟧, is_unitary dag f.\n\n  Definition unitary_to_mor\n             {C : category} {dag : dagger_structure C}\n             {x y : C} (u : unitary dag x y)\n    : C⟦x,y⟧ := pr1 u.\n  Coercion unitary_to_mor : unitary >-> precategory_morphisms.\n\n  Lemma isaset_unitary\n        {C : category} (dag : dagger_structure C) (x y : C)\n    : isaset (unitary dag x y).\n  Proof.\n    apply isaset_total2.\n    - apply homset_property.\n    - intro ; apply isasetaprop ; apply isaprop_is_unitary.\n  Qed.\n\n  Lemma unitary_eq\n        {C : category} {dag : dagger_structure C}\n        {x y : C}\n        (f g : unitary dag x y)\n    : pr1 f = pr1 g -> f = g.\n  Proof.\n    intro p.\n    apply (total2_paths_f p).\n    apply isaprop_is_unitary.\n  Qed.\n\n  Definition unitary_id\n             {C : category} (dag : dagger C)\n             (x : C)\n    : unitary dag x x.\n  Proof.\n    exists (identity_z_iso x).\n    abstract (apply make_is_inverse_in_precat ;\n              [ refine (id_left _ @ _) ; apply dagger_to_law_id\n              | refine (id_right _ @ _) ; apply dagger_to_law_id ]).\n  Defined.\n\n  Lemma is_unitary_comp\n             {C : category} {dag : dagger C}\n             {x y z : C}\n             {f : C⟦x,y⟧} (ff : is_unitary dag f)\n             {g : C⟦y,z⟧} (gg : is_unitary dag g)\n    : is_unitary dag (f · g).\n  Proof.\n    split.\n    - etrans.\n      { apply maponpaths, dagger_to_law_comp. }\n      etrans.\n      { apply assoc. }\n      etrans.\n      { apply maponpaths_2, assoc'. }\n      etrans.\n      { apply maponpaths_2, maponpaths, gg. }\n      etrans.\n      { apply maponpaths_2, id_right. }\n      apply ff.\n    - etrans.\n      { apply maponpaths_2, dagger_to_law_comp. }\n      etrans.\n      { apply assoc. }\n      etrans.\n      { apply maponpaths_2, assoc'. }\n      etrans.\n      { apply maponpaths_2, maponpaths, ff. }\n      etrans.\n      { apply maponpaths_2, id_right. }\n      apply gg.\n  Qed.\n\n  Definition unitary_comp\n             {C : category} {dag : dagger C}\n             {x y z : C}\n             (f : unitary dag x y)\n             (g : unitary dag y z)\n    : unitary dag x z\n    := _ ,, is_unitary_comp (pr2 f) (pr2 g).\n\n  Lemma unitary_inv_is_unitary\n             {C : category} {dag : dagger C}\n             {x y : C} {f : C⟦x,y⟧}\n             (ff : is_unitary dag f)\n    : is_unitary dag (pr1 dag x y f).\n  Proof.\n    split.\n    - refine (! dagger_to_law_comp dag y x y (pr1 dag x y f) f @ _).\n      etrans.\n      { apply maponpaths, ff. }\n      apply dagger_to_law_id.\n    - refine (! dagger_to_law_comp dag x y x f (pr1 dag x y f) @ _).\n      etrans.\n      { apply maponpaths, ff. }\n      apply dagger_to_law_id.\n  Qed.\n\n  Definition unitary_inv\n             {C : category} {dag : dagger C}\n             {x y : C}\n             (f : unitary dag x y)\n    : unitary dag y x\n    := _ ,, unitary_inv_is_unitary (pr2 f).\n\n  Lemma unitary_inv_of_unitary_inv\n        {C : category} {dag : dagger C}\n        {x y : C}\n        (f : unitary dag x y)\n    : unitary_inv (unitary_inv f) = f.\n  Proof.\n    use unitary_eq.\n    apply dagger_to_law_idemp.\n  Qed.\n\nEnd UnitaryMorphisms.\n\nSection EquationalReasoningLemmas.\n\n  Context {C : category} (dag : dagger C).\n\n  Lemma unitary_inv_to_left {a b c : C}\n        (f : C⟦ a, b ⟧) (g : C⟦b, c⟧) (h : C⟦ a, c ⟧)\n    : is_unitary dag f -> dag _ _ f · h = g → h = f · g.\n  Proof.\n    exact (λ u p, z_iso_inv_to_left _ _ _ (make_z_iso _ _ (_,,pr2 u)) _ _ p).\n  Qed.\n\n  Lemma unitary_inv_on_left {a b c : C}\n        (f : C⟦ a, b ⟧) (g : C⟦b, c⟧) (h : C⟦ a, c ⟧)\n    : is_unitary dag g -> h = f · g → f = h · dag _ _ g.\n  Proof.\n    exact (λ u p, z_iso_inv_on_left _ _ _ _ (make_z_iso _ _ (_,,pr2 u)) _ p).\n  Qed.\n\n  Lemma unitary_inv_on_right {a b c : C}\n        (f : C⟦ a, b ⟧) (g : C⟦b, c⟧) (h : C⟦ a, c ⟧)\n    : is_unitary dag f ->  h = f · g → dag _ _ f · h = g.\n  Proof.\n    exact (λ u p, z_iso_inv_on_right _ _ _ (make_z_iso _ _ (_,,pr2 u)) _ _ p).\n  Qed.\n\n  Lemma unitary_inv_to_right {a b c : C}\n        (f : C⟦ a, b ⟧) (g : C⟦b, c⟧) (h : C⟦ a, c ⟧)\n    : is_unitary dag g ->   f = h · dag _ _ g → f · g = h.\n  Proof.\n    exact (λ u p, z_iso_inv_to_right _ _ _ _ (make_z_iso _ _ (_,,pr2 u)) _ p).\n  Qed.\n\nEnd EquationalReasoningLemmas.\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/DaggerCategories/Unitary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7658065941479651}}
{"text": "(*\n  This is a test document filled with exercises from\n  https://coq.inria.fr/tutorial-nahas\n*)\n\nTheorem my_first_proof__again__again : (forall A : Prop, A -> A).\nProof.\n  intros A.\n  intros proof_of_A.\n  exact proof_of_A.\nQed.\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.\n  refine (H0 _).\n    exact H.\nQed.\n\nTheorem backward_large : (forall A B C : Prop, A -> (A -> B) -> (B -> C) -> C).\nProof.\n  intros.\n  refine (H1 _).\n  refine (H0 _).\n  exact H.\nQed.\n\nTheorem backward_huge : (forall A B C : Prop, \n                         A -> (A -> B) -> (A -> B -> C) -> C).\nProof.\n  intros.\n  refine (H1 _ _).\n    exact H.\n    refine (H0 _).\n      exact H.\nQed.\n\nTheorem forward_huge : (forall A B C : Prop, \n                        A -> (A -> B) -> (A -> B -> C) -> C).\nProof.\n  intros.\n  pose (proof_of_B := H0 H).\n  pose (proof_of_C := H1 H proof_of_B).\n  exact proof_of_C.\nQed.\n\nTheorem True_can_be_proven : True.\nProof.\n  exact I.\nQed.\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 absurd : forall A C : Prop, A -> ~A -> C.\nProof.\n  intros.\n  unfold not in H0.\n  pose (proof_of_False := H0 H).\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  (* these next two aren't actually needed!*)\n  unfold not.\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.\n  case a.\n    (*simpl.*)\n    exact I.\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    simpl.\n    intros proof_of_True.\n    exact I.\n\n    simpl.\n    intros proof_of_False.\n    case proof_of_False.\nQed.\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, 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.\n  refine (conj _ _).\n    exact H.\n    exact H0.\nQed.\n\nTheorem and_commutes : (forall A B : Prop, A /\\ B -> B /\\ A).\nProof.\n  intros A B.\n  intros proof_of_A_and_B.\n  case proof_of_A_and_B.\n   intros proof_of_A proof_of_B.\n   refine (conj _ _).\n     exact proof_of_B.\n     exact proof_of_A.\nQed.\n\nTheorem and_communtes__again : (forall A B : Prop, A /\\ B -> B /\\ A).\nProof.\n  intros.\n  destruct H as [proof_of_A proof_of_B].\n  refine (conj _ _).\n    exact proof_of_B.\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.\n    case a, b.\n      simpl.\n      exact (or_introl I).\n\n      simpl.\n      exact (or_introl I).\n\n      simpl.\n      exact (or_intror I).\n\n      simpl in H.\n      refine (or_introl _).\n      simpl.\n      case H.\n    intros.\n    case a,b.\n      exact I.\n      exact I.\n      exact I.\n      case H.\n        intros A.\n        simpl in A.\n        case A.\n\n        intros B.\n        simpl in B.\n        case B.\nQed.\n\nTheorem andb_is_and : (forall a b, \n                       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      simpl.\n      exact (conj I I).\n\n      simpl in H.\n      case H.\n\n      simpl in H.\n      case H.\n\n      simpl in H.\n      case H.\n    intros H.\n    case a, b.\n      simpl.\n      exact I.\n\n      simpl in H.\n      destruct H as [A B].\n      case B.\n\n      simpl in H.\n      destruct H as [A B].\n      case A.\n\n      simpl in H.\n      destruct H as [A B].\n      case A.\nQed.\n\n(* !a <-> !A where a : bool, A : Prop *)\nTheorem negb_is_not : (forall a, Is_true (negb a) <-> (~(Is_true a))).\nProof.\n  intros.\n  unfold iff.\n  case a.\n    (* a is true *)\n    simpl.\n    refine (conj _ _).\n      (* False -> ~True *)\n      intros.\n      unfold not.\n      case H.\n\n      (* ~True -> False *)\n      unfold not.\n      intros.\n      case H.\n      exact I.\n    (* a is false *)\n    simpl.\n    refine (conj _ _).\n      (* True -> ~False*)\n      unfold not.\n      intros.\n      case H0.\n\n      (* ~False -> True *)\n      unfold not.\n      intros.\n      exact I.\nQed.\n\nDefinition basic_predicate := (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    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.\n  case b.\n    (* b = true *)\n    refine (ex_intro _ true _).\n      simpl.\n      exact I.\n    (* b = false *)\n    refine (ex_intro _ false _).\n    simpl.\n    exact I.\nQed.\n\nTheorem thm_forall_exists__simple : (forall b, (exists a, Is_true (eqb a b))).\nProof.\n  intros.\n  refine (ex_intro _ b _).\n  exact (eqb_a_a b).\nQed.\n\nTheorem forall_exists : (forall P : Set -> Prop, \n                        (forall x, ~(P x)) -> ~(exists x, P x)).\nProof.\n  intros.\n  unfold not in H.\n  unfold not.\n  intros exists_set_px.\n  destruct exists_set_px as [exists_set exists_px].\n  pose (not_Pwitness := H exists_set exists_px).\n  case not_Pwitness.\nQed.\n\nTheorem forall_exists__book : (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.\n\nTheorem thm_eq_sym : (forall x y : Set, x = y -> y = x).\nProof.\n  intros x y.\n  intros x_y.\n  destruct x_y as [].\n  exact (eq_refl x).\nQed.\n\nTheorem them_eq_trans : (forall x y z : Set, x = y -> y = z -> x = z).\nProof.\n  intros.\n  destruct H as [].\n  destruct H0 as [].\n  exact (eq_refl x).\nQed.\n\nTheorem thm_eq_trans__again : (forall x y z: Set, x = y -> y = z -> x = z).\nProof.\n  intros.\n  rewrite H.\n  rewrite H0.\n  exact (eq_refl z).\nQed.\n\nTheorem thm_eq_trans__again2 : (forall x y z: Set, x = y -> y = z -> x = z).\nProof.\n  intros.\n  rewrite H.\n  rewrite <-H0.\n  exact (eq_refl y).\nQed.\n\nTheorem andb_sym : (forall a b, a && b = b && a).\nProof.\n  intros.\n  case a, b.\n    simpl.\n    exact (eq_refl true).\n\n    simpl.\n    exact (eq_refl false).\n\n    simpl.\n    exact (eq_refl false).\n\n    simpl.\n    exact (eq_refl false).\nQed.\n\nTheorem neq_nega: (forall a, a <> (negb a)).\nProof.\n  intros.\n  unfold not.\n  case a.\n    simpl.\n    discriminate.\n    simpl.\n    discriminate.\nQed.\n\nTheorem neq_nega__book: (forall a, a <> (negb a)).\nProof.\n  intros a.\n  unfold not.\n  case a.\n    intros a_eq_neg_a.\n    simpl in a_eq_neg_a.\n    discriminate a_eq_neg_a.\n\n    intros a_eq_neg_a.\n    simpl in a_eq_neg_a.\n    discriminate a_eq_neg_a.\nQed.\n\n(* Peano Arithmetic *)\n\nTheorem plus_2_3 : (2 + 3 = 5).\n  simpl.\n  exact (eq_refl 5).\nQed.\n\nTheorem plus_2_3_long : (S (S O)) + (S (S (S O))) = (S (S (S (S (S O))))).\nProof.\n  simpl.\n  exact (eq_refl 5).\nQed.\n\nTheorem plus_O_n : (forall n, O + n = n).\nProof.\n  intros n.\n  simpl.\n  exact (eq_refl n).\nQed.\n\nTheorem plus_n_O : (forall n, n + O = n).\nProof.\n  intros n.\n  elim n.\n    (* base case *)\n    simpl.\n    exact (eq_refl _).\n\n    (* inductive case *)\n    intros.\n    simpl.\n    rewrite H.\n    exact (eq_refl _).\nQed.\n\nTheorem plus_symmetric : (forall n m, n + m = m + n).\nProof.\n  intros.\n  elim n.\n    elim m.\n      simpl.\n      exact (eq_refl _).\n\n      intros.\n      simpl.\n      rewrite <- H.\n      simpl.\n      exact (eq_refl _).\n    intros.\n    simpl.\n    rewrite H.\n    elim m.\n      simpl.\n      exact (eq_refl _).\n\n      intros.\n      simpl.\n      rewrite H0.\n      exact (eq_refl _).\nQed.\n\nRequire Import List.\n\n(* Adding an element to a list increases its length by 1 *)\nTheorem cons_adds_one_to_length :\n    (forall A : Type,\n    (forall (x : A) (lst : list A),\n     length (x :: lst) = (S (length lst)))).\nProof.\n  intros.\n  simpl.\n  exact (eq_refl _).\nQed.\n\nDefinition hd (A : Type) (default : A) (l : list A) :=\nmatch l with\n| nil => default\n| x :: _ => x\nend.\n\n(* currying the above function with 2 parameters*)\nDefinition hd_for_nat_lists := hd nat 0.\n(* Compute hd_for_nat_lists (5 :: 4 :: nil). *)\n(* Compute hd_for_nat_lists (nil). *)\n\nTheorem correctness_of_hd :\n    (forall A : Type,\n    (forall (default : A) (x : A) (l : list A),\n    (hd A default nil) = default /\\ (hd A default (x :: l) = x))).\nProof.\n  intros.\n  simpl.\n  refine (conj _ _).\n    exact (eq_refl _).\n    exact (eq_refl _).\nQed.\n\n(* `: option A` can be inferred *)\nDefinition hd_error (A : Type) (l : list A) : option A :=\nmatch l with\n| nil => None\n| x :: _ => Some x\nend.\n(* Compute hd_error nat nil.\nCompute hd_error nat (5 :: 4 :: nil). *)\n\nTheorem correctness_of_hd_error :\n    (forall A : Type,\n    (forall (x : A) (l : list A),\n    (hd_error A nil) = None /\\ (hd_error A (x :: l)) = Some x)).\nProof.\n  intros.\n  simpl.\n  refine (conj _ _).\n    exact (eq_refl _).\n    exact (eq_refl _).\nQed.\n\n(* some crazy shit?!?! *)\n(* pass a proof that hte list is not nil *)\nDefinition hd_never_fail (A : Type) (lst : list A) (safety_proof : lst <> nil)\n  : A\n:=\n  (match lst as b return (lst = b -> A) with\n    | nil => (fun foo : lst = nil =>\n                   match (safety_proof foo) return A with\n                   end\n                )\n    | x :: _ => (fun foo : lst = x :: _ =>\n                   x\n                )\n  end) eq_refl.\n\nTheorem correctness_of_hd_never_fail :\n   (forall A:Type,\n   (forall (x : A) (rest : list A),\n   (exists safety_proof : ((x :: rest) <> nil),\n      (hd_never_fail A (x :: rest) safety_proof) = x))).\nProof.\n  intros.\n  assert (witness : ((x :: rest) <> nil)).\n    unfold not.\n    intros.\n    discriminate H.\n  refine (ex_intro _ witness _).\n    simpl.\n    exact (eq_refl _).\nQed.\n\nDefinition tl (A : Type) (l:list A) :=\n  match l with\n    | nil => nil\n    | a :: m => m\n  end.\n\nTheorem hd_tl :\n   (forall A:Type,\n   (forall (default : A) (x : A) (lst : list A),\n   (hd A default (x::lst)) :: (tl A (x::lst)) = (x :: lst))).\nProof.\n  intros.\n  simpl.\n  exact (eq_refl _).\nQed.\n\n(* exercises *)\n\nTheorem app_nil_l : (forall A : Type, (forall l : list A, nil ++ l = l)).\nProof.\n  intros.\n  simpl.\n  exact (eq_refl _).\nQed.\n\nTheorem app_nil_r : (forall A:Type, (forall l:list A, forall l:list A, l ++ nil = l)).\nProof.\n  intros.\n  simpl.\n  elim l0.\n    simpl.\n    exact (eq_refl _).\n  intros.\n  simpl.\n  rewrite H.\n  exact (eq_refl _).\nQed.\n\nTheorem app_comm_cons : forall A (x y:list A) (a:A), a :: (x ++ y) = (a :: x) ++ y.\nProof.\n  intros.\n  simpl.\n  exact (eq_refl _).\nQed.\n\nTheorem app_assoc : forall A (l m n:list A), l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  elim l.\n    simpl.\n    exact (eq_refl _).\n  intros.\n  simpl.\n  rewrite H.\n  exact (eq_refl _).\nQed.\n\nTheorem app_cons_not_nil : forall A (x y:list A) (a:A), nil <> x ++ a :: y.\nProof.\n  intros.\n  unfold not.\n  elim x.\n    simpl.\n    discriminate.\n\n    intros.\n    simpl in H0.\n    discriminate H0.\nQed.\n\n", "meta": {"author": "phase", "repo": "learning-coq", "sha": "101c800bde3eba5959994f46ae157f1e8c1a391a", "save_path": "github-repos/coq/phase-learning-coq", "path": "github-repos/coq/phase-learning-coq/learning-coq-101c800bde3eba5959994f46ae157f1e8c1a391a/tutorial-mike-nahas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7656996557269395}}
{"text": "Require Import Nat Arith Bool.\n\n\nInductive Lst : Type := nil : Lst | cons : nat -> Lst -> 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 lst_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 (beq_nat x y) (lst_mem x z)\n    end.\n\nFixpoint lst_subset (lst_subset_arg0 : Lst) (lst_subset_arg1 : Lst) : Prop\n           := match lst_subset_arg0, lst_subset_arg1 with\n              | nil, x => True\n              | cons n x, y => and (lst_subset x y) (lst_mem n y = true)\n              end.\n\nDefinition lst_eq (lst_eq_arg0 : Lst) (lst_eq_arg1 : Lst) : Prop\n           := match lst_eq_arg0, lst_eq_arg1 with\n              | x, y => and (lst_subset x y) (lst_subset y x)\n              end.\n\nFixpoint lst_union (lst_union_arg0 : Lst) (lst_union_arg1 : Lst) : Lst\n           := match lst_union_arg0, lst_union_arg1 with\n              | nil, x => x\n              | cons n x, y => if lst_mem n y then lst_union x y else cons n (lst_union x y)\n              end.\n\n      \nLemma subset_cons: forall l1 l2 n, lst_subset l1 l2 -> lst_subset l1 (cons n l2).\nProof.\n  induction l1.\n  - intros. reflexivity.\n  - intros. simpl. split.\n    * apply IHl1. inversion H. assumption.\n    * destruct (beq_nat n n0). reflexivity. simpl.\n      inversion H. assumption.\nQed.\n\nLemma beq_nat_refl: forall n, beq_nat n n = true.\nProof.\n  induction n. reflexivity. simpl. assumption.\nQed.      \n\nLemma subset_refl : forall (x : Lst), lst_subset x x.\nProof.\ninduction x. simpl. reflexivity.\nsimpl. split. \n- apply subset_cons. assumption.\n- rewrite beq_nat_refl. reflexivity.\nQed.\n\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), lst_subset x y -> lst_eq (lst_union x y) y.\nProof.\n  intros.\n  induction x.\n  - simpl. unfold lst_eq. split.\n    + apply subset_refl.\n    + apply subset_refl.\n  - simpl. simpl in H. destruct H. rewrite H0. apply IHx. assumption.\nQed.\n\n\n(* This proof uses subset_cons above -- the goal is exactly the consequent of that lemma, but we also need a hypothesis. *)\nTheorem theorem1: forall (x : Lst) (y : Lst), lst_subset x (append x y).\nProof.\n  induction x.\n  - intros. simpl. reflexivity.\n  - intros. simpl. split.\n    * apply subset_cons. apply IHx.\n    * rewrite beq_nat_refl. simpl. reflexivity.\nQed.\n\n(* This one does as well, and also reflexivity. Again, no synthesis or generalization. *)\nTheorem theorem2: forall (x : Lst) (y : Lst), lst_subset y (append x y).\nProof.\n  induction x.\n  - intros. simpl. apply subset_refl.\n  - intros. simpl. apply subset_cons. apply IHx.\nQed.\n\nLemma mem_union: forall n x y,\n  lst_mem n y = true -> \n  lst_mem n (lst_union x y) = true.\nintro. induction x.\n- intros. simpl. assumption.\n- intros. simpl. destruct (lst_mem n0 y).\n  * apply IHx. assumption.\n  * simpl. destruct (beq_nat n n0). reflexivity.\n    simpl. apply IHx. assumption.\nQed.\n\n(* Same here. *)\nTheorem theorem3: forall (x : Lst) (y : Lst), lst_subset x (lst_union x y).\nProof.\n  intros. induction x.\n  - simpl. reflexivity.\n  - simpl. split.\n    * destruct (lst_mem n y).\n      +  assumption.\n      + apply subset_cons. assumption.\n    * remember (lst_mem n y) as m.\n      destruct m.\n      -- apply mem_union. rewrite Heqm.\n         reflexivity.\n      -- simpl. rewrite beq_nat_refl. reflexivity.\nQed.", "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/inequalities/goal40.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.765699653525953}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\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 Lia.\nFrom Coq Require Export Lists.List.\nExport ListNotations.\nFrom Coq Require Export Permutation.\n\nDefinition geb (n m : nat) := m <=? n.\n(* Hint Unfold geb : core. *)\nInfix \">=?\" := geb (at level 70) : nat_scope.\nDefinition gtb (n m : nat) := m <? n.\n(* Hint Unfold gtb : core. *)\nInfix \">?\" := gtb (at level 70) : nat_scope.\n\n(* Try lia. *)\nExample lia_example :\n  forall i j k,\n    i > j -> k > i + 3 -> k > j.\nProof.\n  intros. lia.\nQed.\n\nDefinition swap(l : list nat) : list nat :=\n  match l with\n  | a :: b :: l' => if a >? b then b :: a :: l' else l\n  | _ => l\n  end.\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.\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.\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.\nLemma gtb_reflect : forall x y, reflect (x > y) (x >? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\nLemma geb_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\nExample reflect_example1: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros.\n  destruct (ltb_reflect a 5); lia.\nQed.\n\nHint Resolve ltb_reflect leb_reflect gtb_reflect geb_reflect eqb_reflect : bdestruct.\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    [ auto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n\nTheorem swap_is_idempotent : forall l,\n  swap (swap l) = swap l.\nProof.\n  intros. destruct l as [| lhs l].\n  - reflexivity.\n  - destruct l as [| rhs l].\n    + reflexivity.\n    + simpl. bdestruct (lhs >? rhs).\n      * simpl. bdestruct (rhs >? lhs). lia. trivial.\n      * simpl. bdestruct (lhs >? rhs). lia. trivial.\nQed.\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  intros.\n  simpl. rewrite app_nil_r.\n  apply perm_trans with (5 :: 6 :: (b ++ a)).\n  - apply perm_skip. apply perm_skip. apply Permutation_app_comm.\n  - apply perm_skip. apply perm_trans with (6 :: a ++ b).\n    + apply perm_skip. apply Permutation_app_comm.\n    + replace (6 :: a ++ b) with ((6 :: a) ++ b). apply Permutation_app_comm. trivial.\nQed.\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\n(* The point is, [1] != [2]. *)\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n  unfold not. intros.\n  apply Permutation_cons_inv in H. inversion H.\n  apply Permutation_length_1_inv in H0.\n  apply Permutation_sym in H1. apply Permutation_length_1_inv in H1.\n  rewrite H0 in H1. inversion H1.\nQed.\n\n(* \nNow we can prove that maybe_swap is a permutation: it reorders elements but does not add or remove any.\n*)\n\nTheorem swap_perm : forall l,\n  Permutation l (swap l).\nProof.\n  intros. destruct l.\n  - trivial.\n  - destruct l.\n    + trivial.\n    + simpl. bdestruct (n >? n0).\n      * apply perm_swap.\n      * trivial.\nQed.\n\nDefinition first_le_second (l : list nat) : Prop :=\n  match l with\n  | a :: b :: l' => a <= b\n  | _ => True\n  end.\n\nTheorem swap_correct : forall l,\n  Permutation l (swap l) /\\ first_le_second (swap l).\nProof.\n  intros. split.\n  - apply swap_perm.\n  - destruct l.\n    + reflexivity.\n    + simpl. destruct l.\n      * reflexivity.\n      * unfold first_le_second. bdestruct (n >? n0); lia.\nQed.\n\n(* Forall is Coq library's version of the All proposition defined in Logic, but defined as an inductive\nproposition rather than a fixpoint. Prove this lemma by induction. You will need to decide what to induct\non: al, bl, Permutation al bl, and Forall f al are possibilities. *)\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof.\n  intros. induction H.\n  - apply H0.\n  - apply Forall_cons. apply Forall_inv in H0.\n    apply H0. apply Forall_inv_tail in H0.\n    apply IHPermutation in H0. apply H0.\n  - apply Forall_cons. apply Forall_inv_tail in H0. apply Forall_inv in H0. apply H0.\n    apply Forall_cons. apply Forall_inv in H0. apply H0. apply Forall_inv_tail in H0. apply Forall_inv_tail in H0. apply H0.\n  - apply IHPermutation2. apply IHPermutation1. apply H0.\nQed.", "meta": {"author": "hiroki-chen", "repo": "Software-Foundations", "sha": "c60a50c490603fce3c2ecaa88976349004f7fc6f", "save_path": "github-repos/coq/hiroki-chen-Software-Foundations", "path": "github-repos/coq/hiroki-chen-Software-Foundations/Software-Foundations-c60a50c490603fce3c2ecaa88976349004f7fc6f/Vol3/exercise1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.9073122282528898, "lm_q1q2_score": 0.7656763601590514}}
{"text": "\n(* exercise 3.2 *)\n\nSection exercise_3_2.\n  Variable (P Q R : Prop).\n\n  Lemma id_P : P -> P.\n  Proof.\n    intro p.\n    assumption.\n  Qed.\n\n  Lemma id_PP : (P -> P) -> (P -> P).\n  Proof.\n    intros pp p.\n    assumption.\n  Qed.\n\n  Lemma imp_trans : (P -> Q) -> (Q -> R) -> (P -> R).\n  Proof.\n    intros pq qr p.\n    apply qr.\n    apply pq.\n    assumption.\n  Qed.\n\n  Lemma imp_perm : (P -> Q -> R) -> (Q -> P -> R).\n  Proof.\n    intros pqr q r.\n    apply pqr.\n    assumption.\n    assumption.\n  Qed.\n\n  Lemma ignore_Q : (P -> R) -> P -> Q -> R.\n  Proof.\n    intros pr p q.\n    apply pr.\n    assumption.\n  Qed.\n\n  Lemma delta_imp : (P -> P -> Q) -> P -> Q.\n  Proof.\n    intros ppq p.\n    apply ppq.\n    assumption.\n    assumption.\n  Qed.\n\n  Lemma delta_impR : (P -> Q) -> (P -> P -> Q).\n  Proof.\n    intros pq p p2.\n    apply pq.\n    assumption.\n  Qed.\n\n  Variable T : Prop.\n\n  Lemma diamond : (P -> Q) -> (Q -> R) -> (Q -> R -> T) -> P -> T.\n  Proof.\n    intros pq qr qrt p.\n    apply qrt.\n    apply pq.\n    assumption.\n    apply qr.\n    apply pq.\n    assumption.\n  Qed.\n\n  Lemma weak_pierce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n  Proof.\n    intro pqppq.\n    apply pqppq.\n    intro pqp.\n    apply pqp.\n    intro p.\n    apply pqppq.\n    intro pqp2.\n    assumption.\n  Qed.\nEnd exercise_3_2.\n\n", "meta": {"author": "mizukami234", "repo": "coqart-exercises", "sha": "ba6a2098a667c4292777fad34a77e75cda8eeaba", "save_path": "github-repos/coq/mizukami234-coqart-exercises", "path": "github-repos/coq/mizukami234-coqart-exercises/coqart-exercises-ba6a2098a667c4292777fad34a77e75cda8eeaba/section_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7656763400941136}}
{"text": "From NaturalNumbers Require Export Base Tutorial Addition \n    Multiplication Power Proposition AdvProposition AdvAddition AdvMultiplication.\n\nDefinition le (a b : mynat) := exists (c : mynat), b = a + c.\n\nInfix \"<=\" := le.\nNotation \"(<=)\" := le (only parsing).\nNotation \"( f <=)\" := (le f) (only parsing).\nNotation \"(<= f )\" := (fun g => le g f) (only parsing).\n\nFact le_iff_exists_add (a b : mynat) : a <= b <-> exists (c : mynat), b = a + c.\nProof.\n    split.\n    - trivial.\n    - trivial.\nQed.\n\n(* Level 0 data *)\n(* name `one_add_le_self` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nI have just added a new definition, that of `<=`. The statment\n`a <= b` is defined to mean\n```exists (c : mynat), b = a + c``` \nIn other words, we can find some `c : mynat` such that `b = a + c`.\n\nIf you really want, you can use the lemma I have added,\n```\n#Fact le_iff_exists_add (a b : mynat) : a <= b <-> exists (c : mynat), b = a + c.\n```\nto rewrite `<=` into the `exists` statment, but it is not really necessary,\nsince Coq knows what `<=` means, so you can just treat it as if it is written\nlike the `exists` statement already.\n\nNow how does one go about proving an `exists` statement? There is a tactic,\nalso called `exists`, that we can use. Basically, if we have to prove something\nof the form \n`exists (c : mynat), 1 + x = x + c`,\ntyping `exists 1.` substitutes `1` for `c` in the equation, and turns our goal\ninto `1 + x = x + 1`. Now you can easily use the powerful `ring` tactic to\nfinish the proof. Try it yourself below!\n*)\nLemma one_add_le_self (x : mynat) : x <= 1 + x.\nProof.\n    exists 1.\n    ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name `le_refl` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nHere is an easy one, try using the `exists` tactic with\nthe right value for `c` to solve this one!\n*)\nLemma le_refl (x : mynat) : x <= x.\nProof.\n    exists 0.\n    ring.\nQed.\n(* Level epilogue *)\n(*\nNow we have shown that `<=` is a reflexive equation. \nI can now power up our `reflexivity` tactic, by typing\n```\nRequire Import Coq.Classes.RelationClasses.\nGlobal Instance le_Reflexive : Reflexive le := le_refl.\n```\nwhich allows us to prove statements like the following a lot\neasier:\n```\n#Example refl : 0 <= 0.\n#Proof.\n#    reflexivity.\n#Qed.\n```\n*)\n(* Level end *)\n\nRequire Import Coq.Classes.RelationClasses.\n\nGlobal Instance le_Reflexive : Reflexive le := le_refl.\n\nExample refl : 0 <= 0.\nProof.\n    reflexivity.\nQed.\n\n(* Level 2 data *)\n(* name `le_succ` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nOkay, we have seen how goals with `exists` work, but what if we have\na hypothesis with an `exists` statement? Well, we can use our `destruct` \ntactic to obtain the variable that exists, and a witness for the statement\nin the `exists` statement.\n\nBasically, in this level, if we `intro h` we obtain `h : a <= b`. If we type\n```\ndestruct h as [c H].\n```\nwe obtain\n```\nc : mynat\nH : b = a + c\n```\nTry it out below.\n*)\nLemma le_succ (a b : mynat) : a <= b -> a <= S b.\nProof.\n    intro h.\n    destruct h as [c H].\n    exists (S c).\n    now rewrite H, add_succ.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 data *)\n(* name `zero_le` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nAnother easy one.\n*)\nLemma zero_le (a : mynat) : 0 <= a.\nProof.\n    exists a.\n    ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 4 data *)\n(* name `le_trans` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nAgain, this one should not be too tough.\n*)\nLemma le_trans (a b c : mynat) (hab : a <= b) (hbc : b <= c) : a <= c.\nProof.\n    destruct hab as [ca ha].\n    destruct hbc as [cb hb].\n    rewrite ha in hb.\n    exists (ca + cb).\n    rewrite hb.\n    ring.\nQed.\n(* Level epilogue *)\n(*\nWe have shown that `<=` is transitive. I can type the following\n```\n#Global Instance le_Transitive : Transitive le := le_trans.\n#Global Instance le_PreOrder : PreOrder le.\n#Proof.\n#    constructor.\n#    - exact le_Reflexive.\n#    - exact le_Transitive.\n#Qed.\n```\nto let Coq know that `<=` actually defines a preorder on `mynat`.\n*)\n(* Level end *)\n\nGlobal Instance le_Transitive : Transitive le := le_trans.\nGlobal Instance le_PreOrder : PreOrder le.\nProof.\n    constructor.\n    - exact le_Reflexive.\n    - exact le_Transitive.\nQed.\n\n(* Level 5 data *)\n(* name `le_antisymm` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nIn advanced addition world, we have shown \n```\n#Lemma eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a -> b = 0.\n```\nwhich might be useful here. Remember you can use `specialize` to create\nnew hypotheses out of ones you have, and theorems we have shown before.\nSo if we have `hd : a + (c + d) = a` and we want `h : c + d = 0`, you\ncan write \n```\nspecialize (eq_zero_of_add_right_eq_self hd) as h.\n```\nto do so.\n*)\nLemma le_antisymm (a b : mynat) (hab : a <= b) (hba : b <= a) : a = b.\nProof.\n    destruct hab as [ca ha].\n    destruct hba as [cb hb].\n    rewrite ha, add_assoc in hb.\n    symmetry in hb.\n    specialize (eq_zero_of_add_right_eq_self hb) as hcacb.\n    specialize (add_right_eq_zero hcacb) as hca.\n    rewrite hca, add_zero in ha.\n    symmetry.\n    exact ha.\nQed.\n(* Level epilogue *)\n(*\nWe have now shown that `<=` is a partial order! I typed\n```\n#Global Instance le_Antisymmetric : Antisymmetric _ _ le := le_antisymm.\n#Global Instance le_PartialOrder : PartialOrder _ le.\n#Proof.\n#    constructor.\n#    - intro h.\n#      split; now exists 0.\n#    - intro h.\n#      destruct h as [h1 h2].\n#      exact ((le_antisymm x x0) h1 h2).\n#Qed.\n```\nto let Coq know it is.\n*)\n(* Level end *)\n\n\nGlobal Instance le_Antisymmetric : Antisymmetric _ _ le := le_antisymm.\nGlobal Instance le_PartialOrder : PartialOrder _ le.\nProof.\n    constructor.\n    - intro h.\n      split; now exists 0.\n    - intro h.\n      destruct h as [h1 h2].\n      exact ((le_antisymm x x0) h1 h2).\nQed.\n\n(* Level 6 data *)\n(* name `le_zero` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nRemember the `symmetry` tactic? You can also use `symmetry`\nin hypothesis by for example writing `symmetry in h` if\n`h` is a hypothesis you have. It may come in useful in this level.\n*)\nLemma le_zero (a : mynat) (h : a <= 0) : a = 0.\nProof.\n    destruct h as [c h].\n    symmetry in h.\n    exact (add_right_eq_zero h).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 7 data *)\n(* name `succ_le_succ` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nAnother straightforward one.\n*)\nLemma succ_le_succ (a b : mynat) (h : a <= b) : S a <= S b.\nProof.\n    destruct h as [c h].\n    exists c.\n    now rewrite h, succ_add.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 8 data *)\n(* name `le_total` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nTry using `revert a` to prove this one, otherwise you\nmight get stuck!\n*)\nLemma le_total (a b : mynat) : a <= b \\/ b <= a.\nProof.\n    revert a.\n    induction b as [| ? h].\n    - intro a.\n      right. exact (zero_le a).\n    - intro a.\n      destruct a.\n      * left. exact (zero_le (S b)).\n      * specialize (h a) as h.\n        destruct h.\n        + left. now apply succ_le_succ.\n        + right. now apply succ_le_succ.\nQed.\n(* Level epilogue *)\n(* \nWe have now shown that `<=` defines a linear order. Sadly\nCoq does not have a builtin class for this.\n*)\n(* Level end *)\n\n(* Total order? *)\n\n(* Level 9 data *)\n(* name `le_succ_self` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*  \nIt is possible to write a two line proof for this level!\n*)\nLemma le_succ_self (a : mynat) : a <= S a.\nProof.\n    rewrite succ_eq_add_one.\n    now exists 1.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 10 data *)\n(* name `add_le_add_right` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nRemember to use the `intro` tactic on `forall` goals!\n*)\nLemma add_le_add_right {a b : mynat} : a <= b -> forall (t : mynat), (a + t) <= (b + t).\nProof.\n    intros h t.\n    induction t as [| ? ht].\n    - now simpl.\n    - repeat rewrite add_succ.\n      now apply succ_le_succ.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 11 data *)\n(* name `le_of_succ_le_succ` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\nLemma le_of_succ_le_succ (a b : mynat) : S a <= S b -> a <= b.\nProof.\n    intro h.\n    destruct h as [c hc].\n    rewrite succ_add in hc.\n    exists c.\n    now rewrite eq_iff_succ_eq_succ in hc.\n\n    (* now inversion hc. *)\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 12 data *)\n(* name `not_succ_le_self` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nRemember to `unfold not` to turn negations `~P` into `P -> False`.\n*)\nLemma not_succ_le_self (a : mynat) : ~(S a <= a).\nProof.\n    unfold not.\n    intro h.\n    induction a as [| ? ha].\n    - specialize (le_zero (S 0)) as h1.\n      apply (succ_ne_zero 0).\n      exact (h1 h).\n    - apply ha.\n      apply le_of_succ_le_succ.\n      exact h.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 13 data *)\n(* name `add_le_add_left` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nThese levels may seem easy, but they are the things we need\nto show that `mynat` is in fact an ordered commutative monoid.\n*)\nLemma add_le_add_left {a b : mynat} (h : a <= b) (t : mynat) : t + a <= t + b.\nProof.\n    rewrite add_comm, (add_comm t b).\n    exact (add_le_add_right h _).\nQed.\n(* Level epilogue *)\n(* Level end *)\n\nDefinition lt (a b : mynat) := (a <= b) /\\ ~(b <= a).\n\nInfix \"<\" := lt.\nNotation \"(<)\" := le (only parsing).\nNotation \"( f <)\" := (le f) (only parsing).\nNotation \"(< f )\" := (fun g => le g f) (only parsing).\n\n(* Level 14 data *)\n(* name `lt_aux_one` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nI have just introduced the definition of `<`. By definition,\n`a < b` is the same as `(a <= b) /\\ ~(b <= a)`. \nRemember to use the `destruct` tactic.\n*)\nLemma lt_aux_one (a b : mynat) : a < b -> S a <= b.\nProof.\n    intro h.\n    destruct h as [hab hnba].\n    destruct hab as [c habc].\n    destruct c.\n    - exfalso.\n      rewrite add_zero in habc.\n      apply hnba.\n      rewrite habc.\n      reflexivity.\n    - rewrite habc.\n      rewrite add_succ.\n      exists c.\n      now rewrite succ_add.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 15 data *)\n(* name `lt_aux_two` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nNow the other way.\n*)\nLemma lt_aux_two (a b : mynat) : S a <= b -> a <= b /\\ ~(b <= a).\nProof.\n    intro h.\n    split.\n    - apply (le_trans a (S a) b); trivial.\n      * exact (le_succ_self a).\n    - unfold not.\n      intro k.\n      specialize (le_trans (S a) b a) as haSab.\n      apply (not_succ_le_self a).\n      now apply haSab.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 16 data *)\n(* name `lt_iff_succ_le` *)\n(* tactics exists *)\n(* theorems le_iff_exists_add *)\n(* Level prologue *)\n(*\nAlright, we can combine the previous levels \n(`lt_aux_one` and `lt_aux_two`) into this if and only\nif statement, and then we have shown that `mynat` is an ordered\ncancellative commutative monoid.\n*)\nLemma lt_iff_succ_le (a b : mynat) : a < b <-> (S a) <= b.\nProof.\n    split.\n    - exact (lt_aux_one _ _).\n    - exact (lt_aux_two _ _).\nQed.\n(* Level epilogue *)\n(*\nThat's it for the natural numbers game! If you enjoyed, feel\nfree to leave a star on the \n<a href=\"https://github.com/DenSinH/natural-numbers-game\">source code on GitHub</a>.\n\nI hope this helped you learn a bit about Coq and proof formalization.\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/Inequality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7656763400941136}}
{"text": "(*\n  CPDTより：\n  Some more recent Coq features provide more convenient syntax for\n  defining recursive functions.  Interested readers can consult the\n  Coq manual about the commands %\\index{Function}%[Function] and\n  %\\index{Program Fixpoint}%[Program Fixpoint].\n*)\n\n(* オリジナルは、CPDTの  GeneralRec.v *)\n\nRequire Import Arith List Omega.\nRequire Import Cpdt.CpdtTactics Cpdt.Coinductive.\nRequire Import Permutation Sorted Program Recdef.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n\nSection mergeSort.\n  Variable A : Type.\n  Variable le : A -> A -> bool.\n\n  Fixpoint insert (x : A) (ls : list A) : list A :=\n    match ls with\n      | nil => x :: nil\n      | h :: ls' =>\n        if le x h\n          then x :: ls\n          else h :: insert x ls'\n    end.\n  \n  Fixpoint merge (ls1 ls2 : list A) : list A :=\n    match ls1 with\n      | nil => ls2\n      | h :: ls' => insert h (merge ls' ls2)\n    end.\n\n  Fixpoint split (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 ls' in\n          (h1 :: ls1, h2 :: ls2)\n    end.\n  \n  (* yoshihiro *)\n  Lemma split_length : forall zs xs ys,\n      split zs = (xs, ys) -> length zs = length xs + length ys.\n  Proof.\n  Admitted.\n  \n  (* yoshihiro *)\n  Function mergesort (xs : list A) {measure length xs} : list A :=\n    match xs with\n    | nil => nil\n    | x::nil => x::nil\n    | x::y::zs =>\n      match split (x::y::zs) with\n      | (xs, ys) => merge (mergesort xs) (mergesort ys)\n      end\n    end.\n  Proof.\n    - intros xs x l ys zs teq0 teq xs0 ys0 teq1.\n      Check (@split_length (x :: ys :: zs) xs0 ys0 teq1).\n      Check (@split_length _ _ _ teq1).\n      rewrite (@split_length _ _ _ teq1).\n      simpl in teq1.\n      generalize teq1.\n      case (split zs).\n      intros.\n      inversion teq2.\n      now crush.\n    - intros xs x l ys zs teq0 teq xs0 ys0 teq1.\n      rewrite (@split_length _ _ _ teq1).\n      simpl in teq1.\n      generalize teq1.\n      case (split zs).\n      intros.\n      inversion teq2.\n      now crush.\n  Defined.\n  \n  (* CPDT オリジナル *)\n  Definition lengthOrder (ls1 ls2 : list A) :=\n    length ls1 < length ls2.\n  \n  Lemma split_wf1 : forall ls, 2 <= length ls\n    -> lengthOrder (fst (split ls)) ls.\n  Admitted.\n  \n  Lemma split_wf2 : forall ls, 2 <= length ls\n    -> lengthOrder (snd (split ls)) ls.\n  Admitted.\n  \n  Lemma split_wf1' : forall ls, 2 <= length ls\n    -> length (fst (split ls)) < length ls.\n  Proof.\n    pose split_wf1 as H.\n    unfold lengthOrder in H.\n    crush.\n  Qed.\n  \n  Lemma split_wf2' : forall ls, 2 <= length ls\n    -> length (snd (split ls)) < length ls.\n  Proof.\n    pose split_wf2 as H.\n    unfold lengthOrder in H.\n    crush.\n  Qed.\n  \n  (*  Hint Resolve split_wf1 split_wf2. *)\n  Hint Resolve split_wf1' split_wf2'.\n  \n  Function mergeSort (ls : list A) {measure length ls} : list A :=\n    if le_lt_dec 2 (length ls) then\n      let lss := split ls in\n      merge (mergeSort (fst lss)) (mergeSort (snd lss))\n    else\n      ls.\n  Proof.\n    - auto.\n    - auto.\n      \n      (*\n    - pose split_wf2 as H.\n      unfold lengthOrder in H.\n      crush.\n    - pose split_wf1 as H.\n      unfold lengthOrder in H.\n      crush.\n       *)\n      \n      (*\n      rewrite (split_length' ls).\n      case (le_lt_dec 2 (length ls)); intros H.\n      + apply (split_len_1 ls) in H.\n        crush.\n      + crush.                              (* len ls < 2 で矛盾  *)\n    - intros ls le2 teq2.\n      rewrite (split_length' ls).\n      case (le_lt_dec 2 (length ls)); intros H.\n      + apply (split_len_2 ls) in H.\n        crush.\n      + crush.                              (* len ls < 2 で矛盾  *)\n*)\n  Defined.\n(*\nmergeSort_tcc is defined\nmergeSort_terminate is defined\nmergeSort_ind is defined\nmergeSort_rec is defined\nmergeSort_rect is defined\nR_mergeSort_correct is defined\nR_mergeSort_complete is defined\n*)\n\n  Check mergeSort_ind : forall P : list A -> list A -> Prop,\n       (forall (ls : list A) (_x : 2 <= length ls),\n        le_lt_dec 2 (length ls) = in_left ->\n        let lss := split ls in\n        P (fst lss) (mergeSort (fst lss)) ->\n        P (snd lss) (mergeSort (snd lss)) ->\n        P ls (merge (mergeSort (fst lss)) (mergeSort (snd lss)))) ->\n       (forall (ls : list A) (_x : length ls < 2),\n        le_lt_dec 2 (length ls) = in_right -> P ls ls) ->\n       forall ls : list A, P ls (mergeSort ls)\n\nEnd mergeSort.\n\nExtraction merge.\nExtraction split.\nExtraction mergeSort.\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_cpdt_msort_func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7655054693802122}}
{"text": "Require Import Le Lt.\n\nInductive Vec (A : Type) : nat -> Type :=\n  | Vnil : Vec A 0\n  | Vcon : forall {n : nat} (hd : A) (tl : Vec A n), Vec A (S n).\n\nArguments Vnil {A}.\nArguments Vcon [A n] hd tl.\n\nFixpoint Vget {A : Type} {n : nat} (v : Vec A n) (m : nat) (mltn : m < n) : A.\ndestruct v.\n apply False_rect ; eapply lt_n_O ; eassumption.\n destruct m.\n  exact hd.\n  eapply Vget ; [| eapply lt_S_n ] ; eassumption.\nDefined.\n\nDefinition Vec_ext {A n} (v1 v2 : Vec A n) :=\n  forall (p : nat) (pr : p < n), Vget v1 p pr = Vget v2 p pr.\n\nFixpoint Vconcat {A : Type} {m n : nat} (v1 : Vec A m) (v2 : Vec A n) : Vec A (m + n) :=\nmatch v1 in Vec _ m return Vec A (m + n) with\n  | Vnil         => v2\n  | Vcon hd tl => Vcon hd (Vconcat tl v2)\nend.\n\nFixpoint Vupdate {A : Type} {n : nat} (v : Vec A n) (m : nat) (mltn : m < n) (a : A)\n {struct v} : Vec A n.\ndestruct v.\n constructor.\n destruct m.\n  constructor ; [exact a | exact v].\n  constructor.\n   exact hd.\n   eapply (Vupdate _ _ v m (lt_S_n _ _ mltn) a).\nDefined.\n\nFixpoint Vmap {A B : Type} {n : nat} (f : A -> B) (v : Vec A n) : Vec B n :=\nmatch v in (Vec _ n0) return (Vec B n0) with\n  | Vnil         => Vnil\n  | Vcon hd tl => Vcon (f hd) (Vmap f tl)\nend.\n\nFixpoint Vmap_full {A B : Type} {n : nat} (f : forall (m : nat) (mltn : m < n), A -> B)\n  (v : Vec A n): Vec B n.\ndestruct v.\n constructor.\n constructor.\n  exact (f O (lt_0_Sn _) hd).\n  eapply Vmap_full.\n  eexact (fun  m mltn => f (S m) (lt_n_S _ _ mltn)).\n  assumption.\nDefined.\n\nFixpoint genVec_cst {A : Type} (n : nat) (a : A) : Vec A n :=\nmatch n with\n  | O    => Vnil\n  | S n' => Vcon a (genVec_cst n' a)\nend.\n\nDefinition genVec_pr (n : nat) : Vec {p |  p < n} n :=\n  Vmap_full (fun m mltn _ => exist (fun p => p < n) m mltn) (genVec_cst n O).\n\nDefinition genVec (n : nat) : Vec nat n :=\n  Vmap_full (fun m _ _ => m) (genVec_cst n O).\n\nDefinition genVec_P {A : Type} (n : nat) (P : forall m, m < n -> A) : Vec A n :=\n  Vmap_full (fun m mltn _ => P m mltn) (genVec_cst n 0).\n\n(*\nDefinition genVec2 (n : nat) : Vec nat n := genVec_P n (fun m _ => m).\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/Vec/Vec_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8723473763375644, "lm_q1q2_score": 0.7654645733568984}}
{"text": "Theorem pair_eq : forall (A B: Type)(a a': A)(b b': B),\n(a, b) = (a', b') <-> a = a' /\\ b = b'.\nProof.\nunfold iff. intros. apply conj.\n- intros. injection H. intros. apply conj. apply H1. apply H0.\n- intros. apply proj1 in H as H1. apply proj2 in H as H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\nDefinition Relation (A B : Type) : Type := (prod A B -> Prop).\n\nAxiom Relation_eq : forall {A B} (R S : Relation A B),\n(forall (a:A)(b:B), R(a, b) <-> S(a, b)) <-> R = S.\n\nDefinition dom {A B}(R : Relation A B) : (A -> Prop) := \n(fun x => (exists y:B, R(x, y))).\n\nDefinition ran {A B}(R : Relation A B) : (B -> Prop) :=\n(fun y => (exists x:A, R(x, y))).\n\nDefinition image {A B}(R : Relation A B) : ((A -> Prop) -> (B -> Prop)) :=\n(fun A_ => (fun y => (exists x:A, A_ x -> R(x, y)))).\n\nDefinition inv_image {A B}(R : Relation A B) : ((B -> Prop) -> (A -> Prop)) :=\n(fun B_ => (fun x => (exists y:B, B_ y -> R(x, y)))).\n\nDefinition inv {A B}(R : Relation A B) : Relation B A :=\n(fun p => (match p with \n  | (b,a) => R(a, b) \nend)).\n\nDefinition composition {A B C} (R : Relation A B) (S : Relation B C) : Relation A C :=\n(fun p => (match p with\n  | (a, c) => exists b, R(a, b) /\\ S(b, c)\nend)).\n\nDefinition symmetric {A} (R : Relation A A) : Prop :=\nforall (a b : A), R(a, b) -> R(b, a).\n\nDefinition antisymmetric {A} (R : Relation A A) : Prop :=\nforall (a b : A), R(a, b) -> R(b, a) -> a = b.\n\nDefinition asymmetric {A} (R: Relation A A) : Prop :=\nforall (a b : A), R(a, b) -> not (R(b, a)).\n\nDefinition transitive {A} (R: Relation A A) : Prop :=\nforall (a b c : A), R(a, b) -> R(b, c) -> R(a, c).\n\nDefinition reflexive {A} (R : Relation A A) : Prop :=\nforall (a : A), R(a, a).\n\nDefinition injective {A B} (R : Relation A B) : Prop :=\nforall (a1 a2 : A)(b : B), R(a1, b) -> R(a2, b) -> a1 = a2.\n\nDefinition functional {A B} (R : Relation A B) : Prop :=\nforall (a : A)(b1 b2 : B), R(a, b1) -> R(a, b2) -> b1 = b2.\n\nDefinition one_to_one {A B} (R : Relation A B) : Prop :=\ninjective R /\\ functional R.\n\nDefinition left_total {A B} (R : Relation A B) : Prop :=\nforall (a : A), exists (b : B), R(a, b).\n\nDefinition surjective {A B} (R : Relation A B) : Prop :=\nforall (b : B), exists (a : A), R(a, b).\n\nDefinition equiv {A} (R : Relation A A) : Prop :=\nreflexive R /\\ transitive R /\\ symmetric R.\n\n", "meta": {"author": "yskim5892", "repo": "Coq_math", "sha": "4b88322f1d40f154c05db2b523e419b28e544159", "save_path": "github-repos/coq/yskim5892-Coq_math", "path": "github-repos/coq/yskim5892-Coq_math/Coq_math-4b88322f1d40f154c05db2b523e419b28e544159/Relation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7653945040888597}}
{"text": "\nRequire Import Arith. \n\nInductive fact_domain : nat -> Prop :=\n| fact_domain_zero :\n  fact_domain 0\n| fact_domain_pos :\n  forall n : nat, fact_domain (n-1) -> fact_domain n.\n\nTheorem fact_domain_pos_true : forall n : nat, fact_domain n -> 0 <= n.\nProof. \n  intros n H. case H. auto with arith. \n  intros n' H'. case H'. auto with arith.\n  intros n'' H''. auto with arith. \nDefined.\n\nTheorem fact_domain_inv :\n  forall n : nat, fact_domain n -> 0 < n -> fact_domain (n-1).\nProof. \n  intros n H Hlt. case H. simpl. apply fact_domain_zero.\n  intros n0' H'. auto. \nDefined.\nTransparent fact_domain_inv.\n\nRequire Import Arith. \n\nPrint fact_domain_inv.\n \nFixpoint fact (n : nat) (h : fact_domain n) {struct h} : nat :=\n  match lt_eq_lt_dec n 0 with\n    | inleft hle => \n      match hle with \n        | left nlt0 => False_rec nat (lt_n_O n nlt0)\n        | right neq0 => 1\n      end\n    | inright hgt => \n      match h in (fact_domain n) return (fact_domain (n - 1)) with \n        | fact_domain_zero => fact_domain_zero\n        | fact_domain_pos _ H' => n * (fact (n-1) H')\n      end\n  end.\n\n\n      \n\n(fact_domain_inv n h hgt))\n  end.\n\n\nDefinition fact (n: nat) (h : fact_domain n) : nat.\nProof.\n  refine \n    (fix f (n : nat) (h : fact_domain n) {struct h} :=  \n      match le_gt_dec n 0 with \n        | left _ => 1 \n        | right hgt => n * (f (n-1) (fact_domain_inv n h hgt))\n      end).\n  destruct n. inversion hgt. \n  simpl. cut (n-0 = n). intros. inversion h. simpl in *. rewrite H in *.       \n  auto. auto with arith. \nDefined.\n\nRequire Import Ascii.\nRequire Import String. \n\n\nInductive Suffix (s:string) : string -> Prop :=\n| suffix_refl : Suffix s s\n| suffix_next : forall s' c, Suffix s s' -> Suffix s (String c s').\nHint Constructors Suffix.\n\nLemma Suffix_empty : forall (s:string), Suffix \"\" s.\nProof.\n  induction s ; auto ; destruct s ; auto. \nDefined.\nHint Resolve Suffix_empty.\n\nLemma Suffix_both : forall (s' s:string) c c', \n  Suffix (String c s) (String c' s') -> Suffix s s'.\nProof.\n  induction s' ;intros ; inversion H ; subst ; auto. inversion H1.\n  apply suffix_next. eapply IHs'. eauto.\nDefined.\n\nDefinition ProperSuffix (s s':string) := exists c, Suffix (String c s) s'.\nHint Unfold ProperSuffix.\n\nLemma ProperSuffix_irrefl (s :string) : ~ ProperSuffix s s.\nProof.\n  induction s. unfold not. intros. inversion H.\n  inversion H0.\n  unfold not. intros. inversion H.\n  eapply Suffix_both in H0. \n  cut (ProperSuffix s s). intros. auto.\n  eauto.\nDefined.\n\nLemma ProperSuffix_not_empty (s :string) : ~ProperSuffix s \"\".\nProof.\n  induction s. unfold  not. intros. inversion H. inversion H0.\n  unfold not. intros. inversion H. inversion H0.\nDefined.    \n\nLemma ProperSuffix_both : forall (s s':string) c c', \n  ProperSuffix (String c s) (String c' s') -> ProperSuffix s s'.\nProof. \n  destruct s; intros. inversion H ; subst ; auto. \n  apply Suffix_both in H0. unfold ProperSuffix.\n  exists c. auto.\n\n  inversion H. apply Suffix_both in H0. \n  unfold ProperSuffix. exists c. auto.\nDefined.\n\nDefinition SuffixFamily (s:string) := {s' | Suffix s' s}.\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/Recursion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7653945021380447}}
{"text": "Require Import Arith Omega.\nRequire Import List.\nRequire Import Sorted.\n\nDefinition P {A} (u v : list A) := exists x, In x u /\\ In x v.\n\nDefinition Spec (f : list nat -> list nat -> bool) := forall u v, StronglySorted (lt) u -> StronglySorted (lt) v -> if f u v then P u v else ~ P u v.\n\nDefinition Spec' (f : list nat * list nat -> bool) := forall uv, StronglySorted (lt) (fst uv) -> StronglySorted (lt) (snd uv) -> if f uv then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv).\n\nRequire Import Recdef.\n\nDefinition totallen (uv : list nat * list nat) := length (fst uv) + length (snd uv).\n\nFunction intp (uv : list nat * list nat) {measure totallen} : bool :=\n  match fst uv with\n    | nil => false\n    | x :: xs =>\n      match snd uv with\n        | nil => false\n        | y :: ys =>\n          match lt_eq_lt_dec x y with\n            | inleft (left _) (* x < y *) => intp (xs, y :: ys)\n            | inleft (right _) (* x = y *) => true\n            | inright _ (* x > y *) => intp (x :: xs, ys)\n          end\n      end\n  end.\n\nunfold totallen; intros; destruct uv; simpl in *; subst; simpl.\nomega.\n\nunfold totallen; intros; destruct uv; simpl in *; subst; simpl.\nomega.\nDefined.\n\nCheck (intp_ind (fun uv b => if b then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv))).\n\n\nLemma not_P_nil {A} (v : list A) : ~ P nil v.\nProof.\n  unfold P; intros [x [l r]].\n  inversion l.\nQed.\n\nLemma not_P_nil2 {A} (v : list A) : ~ P v nil.\nProof.\n  unfold P; intros [x [l r]].\n  inversion r.\nQed.\n\nLemma P_head {A} (v : A) (us vs : list A) : P (v :: us) (v :: vs).\nProof.\n  exists v; split; constructor; reflexivity.\nQed.\n\nLemma In_lemma (x a0 : nat) (v : list nat) :\n  StronglySorted lt (a0 :: v) ->\n  x < a0 ->\n  ~In x (a0 :: v).\nProof.\n  intros S l I.\n  inversion I; subst.\n  omega.\n  destruct v.\n  inversion H.\n  inversion S; subst.\n  destruct (Forall_forall (lt a0) (n :: v)) as [Lemma _].\n  pose (Lemma H3 x H).\n  omega.\nQed.\n\nTheorem intp_Spec : Spec' intp.\nProof.\n  unfold Spec'.\n\n  intros uv.\n\n  apply (intp_ind (fun uv b => StronglySorted lt (fst uv) -> StronglySorted lt (snd uv) -> if b then P (fst uv) (snd uv) else ~ P (fst uv) (snd uv))); simpl; intros;\n  repeat match goal with\n           | [ uv : (?a * ?b)%type |- _ ] => destruct uv\n         end; simpl in *; subst.\n  \n  apply not_P_nil.\n\n  apply not_P_nil2.\n  \n  unfold P in *.\n  destruct (intp (xs, y :: ys)).\n  Focus 1.\n  assert (StronglySorted lt xs) as H2.\n  inversion H0; assumption.\n  destruct (H H2 H1) as [x' [L R]].\n  exists x'; split.\n  right; assumption.\n  assumption.\n  Focus 1.\n  assert (StronglySorted lt xs) as H2.\n  inversion H0; assumption.\n  intro H3; apply (H H2 H1); clear H.\n  destruct H3 as [x' [L R]].\n  inversion L; subst.\n  pose (In_lemma _ _ _ H1 _x R) as f.\n  elim f.\n  exists x'; split; assumption.\n\n  unfold P in *.\n  exists y; split; constructor; reflexivity.\n  \n  unfold P in *.\n  destruct (intp (x :: xs, ys)).\n  Focus 1.\n  assert (StronglySorted lt ys) as H2.\n  inversion H1; assumption.\n  destruct (H H0 H2) as [x' [L R]].\n  exists x'; split.\n  assumption.\n  right; assumption.\n  Focus 1.\n  assert (StronglySorted lt ys) as H2.\n  inversion H1; assumption.\n  intro H3; apply (H H0 H2); clear H.\n  destruct H3 as [x' [L R]].\n  inversion R; subst.\n  pose (In_lemma _ _ _ H0 _x L) as f.\n  elim f.\n  exists x'; split; assumption.\nQed.\n\nExtraction Language Ocaml.\n\nExtraction intp.\n\n(****\n\n(** val intp : (nat list, nat list) prod -> bool **)\n\nlet rec intp uv =\n  match fst uv with\n  | Nil -> False\n  | Cons (x, xs) ->\n    (match snd uv with\n     | Nil -> False\n     | Cons (y, ys) ->\n       (match lt_eq_lt_dec x y with\n        | Inleft s ->\n          (match s with\n           | Left -> intp (Pair (xs, (Cons (y, ys))))\n           | Right -> True)\n        | Inright -> intp (Pair ((Cons (x, xs)), ys))))\n\n\n ***)\n", "meta": {"author": "orchid-hybrid", "repo": "SF", "sha": "257bf43a6d44f3980c3964fd7deca0d599fbed15", "save_path": "github-repos/coq/orchid-hybrid-SF", "path": "github-repos/coq/orchid-hybrid-SF/SF-257bf43a6d44f3980c3964fd7deca0d599fbed15/unrelated/intersectp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7653944964345213}}
{"text": "(** V tej lekciji bomo spoznali induktivne tipe.\n\n    Najbolj znan primer induktivnega tipa so naravna števila.\n    Drugi znani primeri so seznami in drevesa.\n\n    Induktivni tip [T] definiran tako, da podamo nekaj\n    _konstruktorjev_ (ki nimajo zveze s konstruktorji\n    v objektnem programiranju)\n\n      c_1 : ... -> T\n      c_2 : ... -> T\n      ...\n      c_n : ... -> T\n\n    Vsak od konstruktorjev sprejme še nič ali več argumentov\n    različnih tipov (zgoraj označeno z ...). Nekateri argumenti\n    so lahko spet tipa [T] (ali celo bolj splošni, v kar se tu ne\n    bomo spuščali), zato so induktivni tipi _rekurzivni_.\n\n    Elementi tipa [T] so vsi tisti izrazi oblike [c_i e_1 .. e_k]\n    za katere so [e_1, ..., e_k] ustrezni argumenti in je [c_i]\n    eden od konstruktorjev. Drugač povedano, elemente [T] gradimo\n    _indkutivno_, začenši s konstruktorji brez argumentov.\n\n    Na primer, naravna števila lahko definiramo takole.\n*)\n\nInductive N :=\n  | o : N\n  | s : N -> N.\n\n(** Imamo dva konstruktorja. Konstruktor [o] ne sprejme nobenega\n    parametra, torej je to _konstanta_ tipa [nat]. Konstruktor [s]\n    sprejme kot argument naravno število. Katere elemente lahko\n    zgradimo s pomočjo teh dveh konstruktorjev? *)\n\nCheck o.\nCheck s o.\nCheck s (s o).\nCheck s (s (s o)).\nCheck s (s (s (s o))).\n\n(** Res dobivamo naravna števila. Ker je tip _indkutiven_\n    \"neskončni\" izraz [s (s (s (s ...)))], v katerem se [s]\n    v nedogled ponavlja, _ni_ veljaven. Coq pozna tudi _koinduktivne_\n    tipe, ki vsebujejo tudi neskončne izraze.\n*)\n\n(** Tudi seznami so induktivni tip. Takole definiramo sezname,\n    ki imajo elemente tipa [A]:  *)\n\nInductive seznam (A : Type) :=\n  | prazen : seznam A\n  | sestavi : A -> seznam A -> seznam A.\n\n(** To definicijo preberemo takole: definirali smo\n    induktivni tip [seznam], ki je parameteriziran s\n    tipom [A]. To pomeni, da za vsak tip [A] dobimo\n    tip [seznam A]. Elementi tipa [seznam A] so:\n\n    - [prazen A] je element tipa [seznam A],\n    - [sestavi A x l] je element tipa [seznam A], pri predpostavki\n      da je [x : A] in [l : seznam A].\n\n    Tu je nekaj seznamov tipa [seznam bool]. *)\n\nCheck prazen bool. (* prazen seznam *)\nCheck sestavi bool false (sestavi bool true (prazen bool)). (* seznam [false, true] *)\n\n(* Kot vidimo, je treba vedno povedati tip [A], kar je precej\n   nepraktično. Coq-u lahko razložimo, da naj bo [A] impicitni argument\n   pri konstruktorjih [prazen] in [sestavi].\n   Tako ga bo Coq sam izračunal iz ostalih podatkov (ali se pritožil,\n   če ne bo znal. *)\n\nArguments prazen {A}.\nArguments sestavi {A} _ _.\n\n(** Sedaj lahko pišemo krajše: *)\n\nCheck @prazen bool. (* prazen seznam elementov tipa [bool]. *)\nCheck sestavi false (sestavi true prazen). (* seznam [false, true] *)\n\n(** Pri praznem seznamu smo morali še vedno pisati [bool], saj sicer\n    Coq ne more uganiti, da gre za prazen seznam elementov tipa [bool]. *)\n\n(** Coq pravzaprav že ima definirana naravna števila in sezname. *)\nPrint nat.\nPrint list.\n\n(** Za naravna števila ima Coq običajno notacijo. *)\nCheck 42.\n\n(** Za sezname uporablja enako notacijo kot OCaml. *)\nCheck @nil bool.\nCheck cons false (cons true nil). (* seznam [false, true] *)\n\n(** Namesto [cons x xs] lahko pišemo [x :: xs], če aktiviramo\n    notacijo iz [list_scope]. *)\nCheck (false :: true :: nil)%list.\nLocal Open Scope list_scope.\nCheck false :: true :: nil.\n\n(** Od sedaj naprej bomo uporabljali Coq-ova tipa [nat] in [list]. *)\n\nRequire Import Arith. (* Knjižnica izrekov o [nat]. *)\nRequire Import List.  (* Knjižnica izrekov o [list]. *)\n\n(** Funkcije na induktivnih tipih definiramo rekurzivno.\n    Rekurzivne funkcije definiramo s [Fixpoint] ali [fix].\n*)\n\nFixpoint dolzina {A : Type} (lst : list A) : nat :=\n  match lst with\n    | nil => 0\n    | _ :: lst' => S (dolzina lst')\n  end.\n\n(** Ekvivalentna defincija s [fix]. Ta je podoben kot\n    [fun], saj definira anonimno funkcijo. V spodnji\n    definiciji je [f] vezana spremenljivka. \n*)\nDefinition dolzina' {A: Type} :=\n   fix f (lst : list A) : nat :=\n     match lst with\n       | nil => 0\n       | _ :: lst' => S (f lst')\n     end.\n\n(** Primer računanja s funkcijo [dolzina]. *)\nEval compute in dolzina (2 :: 4 :: 3 :: nil).\n\n(** V standardni knjižnici je funkcija za dolžino seznama že definirana. *)\nPrint length.\n\nEval compute in length (2 :: 4 :: 3 :: nil).\n\n(** Sestavi funkcijo [range n], ki vrne seznam naravnih števil\n    [(n-1) :: (n-2) :: ... 1 :: 0 :: nil]. \n\n    [Definition] spremeni v [Fixpoint] ali pa uporabo [fix].\n*)\nDefinition range : nat -> list nat.\nAdmitted.\n\n(*\n  Fixpoint range (n : nat) :=\n    ???\n*)\n\n(** Naslednji izračun mora vrniti\n    9 :: 8 :: 7 :: 6 :: 5 :: 4 :: 3 :: 2 :: 1 :: 0 :: nil *)\nEval compute in range 10.\n\n(** Definirajmo še funkcijo za stikanje dveh seznamov. *)\nFixpoint stakni {A : Type} (lst1 : list A) (lst2 : list A) : list A :=\n  match lst1 with\n    | nil => lst2\n    | x :: lst1' => x :: (stakni lst1' lst2)\n  end.\n\nEval compute in stakni (range 5) (range 7).\n\n(* Coq ne dovoli definirati rekurzivne funkcije, ki ni povsod definirana.\n   Zato moramo vedno zagotoviti, da se rekurzivni klici izvajajo na manjših\n   argumentih. Coq sam ugotovi, kateri argument se zmanjšuje. Če tega ne\n   zna sam, mu lahko to povemo z določilom [{struct ..}]. Recimo:\n*)\n\nFixpoint stakni' {A : Type} (lst1 : list A) (lst2 : list A) {struct lst1}: list A :=\n  match lst1 with\n    | nil => lst2\n    | x :: lst1' => x :: (stakni' lst1' lst2)\n  end.\n\n(** V standardni knjižnici že imamo funkcijo [app], ki stika sezname.\n    Namesto [app x lst] lahko pišemo [x ++ lst]. *)\nPrint app.\n\nEval compute in range 5 ++ range 7.\n\n(** Naloga: definiraj funkcijo, ki obrne seznam.\n    Koda naj ustreza naslednji definiciji:\n \n    - obrnjeni prazen seznam je spet prazen seznam\n    - seznam x :: l' obrnemo tako, da obrnemo l' in ga staknemo\n      s seznamom, ki vsebuje samo x.\n\n    Nato v standardni knjižnici poišči funkcijo, ki obrača sezname.\n    Primerjaj definicijo. *)\nDefinition obrni {A : Type} (lst : list A) : list A.\nAdmitted.\n\n(* \n  Fixpoint obrni {A : Type} (lst : list A) :=\n  ???\n*)\n\n\n(** Tole mora izračunati 5 :: 4 :: 3 :: 2 :: 1 :: nil *)\nEval compute in obrni (1 :: 2 :: 3 :: 4 :: 5 :: nil).\n\n(** V standradni knjižnici poišči funkcijo za obračanje seznamov. *)\n\n(** Izreke o induktivnih tipih dokazujemo z indukcijo.\n    Vsak induktivni tip ima namreč pripadajoči princip indukcije.\n    Indukcija na naravnih številih je le poseben primer splošne indukcije.\n\n    Ko definiramo induktivni tip, Coq sam generira nekaj variant ustreznih\n    principov indukcije. S taktiko [induction] lahko uporabimo tako generirani\n    princip.\n*)\n\n(** Z indukcijo dokažimo, da je stik seznama [lst] in praznega seznama spet [lst]. *)\nLemma app_nil (A : Type) (lst : list A) : lst = lst ++ nil.\nProof.\n  (* Indukcija na lst. *)\n  induction lst.\n  - (* osnovni primer: prazen seznam *)\n    reflexivity.\n  - (* indukcijski korak: seznam oblike [a :: lst] *)\n    simpl.\n    rewrite <- IHlst.\n    reflexivity.\nQed.\n\n(** Z indukcijo pokažimo, da velja [rev (lst1 ++ lst2) = (rev lst2) ++ (rev lst1)]. *)\nLemma rev_app (A : Type) (lst1 lst2 : list A) : rev (lst1 ++ lst2) = rev lst2 ++ rev lst1.\nProof.\n  induction lst1.\n  - apply app_nil.\n  - simpl.\n    (* Menda obstaja lema, da je [app] asociativen. *)\n    SearchAbout (?x ++ ?y ++ ?z).\n    rewrite app_assoc.\n    rewrite <- IHlst1.\n    reflexivity.\nQed.\n\n(** Z indukcijo dokaži, da je dvakrat obrnjeni seznam enak prvotnemu. *)\nLemma rev_rev (A : Type) (lst : list A) : lst = rev (rev lst).\nProof.\n  admit.\nQed.\n\n(** Obravnavajmo še dvojiška drevesa. *)\nInductive tree :=\n  | empty : tree\n  | node : tree -> tree -> tree.\n\n(** Število elementov v drevesu. *)\nFixpoint size (t : tree) :=\n  match t with\n    | empty => 0\n    | node l r => S (size l + size r)\n  end.\n\n(** Globina drevesa. *)\nFixpoint depth (t : tree) :=\n  match t with\n    | empty => 0\n    | node l r => S (max (depth l) (depth r))\n  end.\n\n(** Polno drevo globine n. *)\nFixpoint complete (n : nat) : tree :=\n  match n with\n    | 0 => empty\n    | S n' => node (complete n') (complete n')\n  end.\n\nEval compute in complete 3.\nEval compute in depth (complete 5).\nEval compute in size (complete 5).\n\n(** Dokažimo, da ima [complete n] res globino [n] in da ima\n     velikost [2^n - 1]. Potenciranje se skriva v knjižnici [NPeano]. *)\n\nRequire Import NPeano.\n\n(** Vaja. *)\nLemma complete_depth (n : nat) : depth (complete n) = n.\nProof.\n  admit.\nQed.\n\n(** To naredimo skupaj na predavanjih. *)\nLemma complete_size (n : nat) : S (size (complete n)) = 2 ^ n.\nProof.\n  induction n.\n  - auto.\n  - simpl.\n    ring_simplify.\n    SearchAbout (?x * ?y + ?x).\n    rewrite <- mult_succ_r.\n    congruence.\nQed.\n\n(** Funkcija, ki zamenja levo in desno podrevo, in naredi\n    isto še v obeh podrevesih. *)    \nFixpoint flip (t : tree) :=\n  match t with\n    | empty => empty\n    | node l r => node (flip r) (flip l)\n  end.\n\n(** Če obrnemo dvakrat, dobimo isto drevo. *)\nLemma flip_idem (t : tree) : flip (flip t) = t.\nProof.\n  admit.\nQed.\n\n(** Obračanje ne spremeni velikosti. *)\nLemma flip_size (t : tree) : size t = size (flip t).\nProof.\n  admit.\nQed.\n\n(** Obrnjeno polno drevo je spet polno drevo. *)\nLemma flip_complete (n : nat) : complete n = flip (complete n).\nProof.\n  admit.\nQed.\n\n(** Pri naslednji nalogah ne potrebuješ indukcije, ker so\n    indukcijske hipoteze neuporabne. Namesto [induction t]\n    raje poskusi [destruct t] ali [destruct t as [|u1 u2]]. *)\n\n(** Edino drevo globine 0 je prazno drevo. *)\nLemma globina_0 (t : tree) : depth t = 0 -> t = empty.\nProof.\n  admit.\nQed.\n\n(** Edino drevo globine 1 je [node empty empty]. *)\nLemma globina_1 (t : tree) :\n  depth t = 1 -> t = node empty empty.\nProof.\n  admit.\nQed.\n\n(** Obstajajo tri drevesa globine 2. *)\nLemma globina_2 (t : tree) :\n  depth t = 2 ->\n  t = node (node empty empty) empty \\/\n  t = node empty (node empty empty) \\/\n  t = node (node empty empty) (node empty empty).\nProof.\n  intro H.\n  destruct t as [|t1 t2] ; try discriminate || auto.\n  admit.\nQed.\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/induktivni_tipi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7653536818941552}}
{"text": "(* BEGIN FIX *)\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (n1 n2 : nat)\n  | BGe (n1 n2 : nat)\n  | BNot (b : bexp)\n  | BOr (b1 b2 : bexp).\n\nFrom Coq Require Import Init.Nat.\n\nEval compute in 3 =? 4.\nEval compute in 3 <=? 3.\n\nFixpoint beval (b : bexp) : bool := \n(* END FIX *)\n  match b with\n    | BTrue => true\n    | BFalse => false\n    | BEq n1 n2 => n1 =? n2\n\t  | BGe n1 n2 => negb (n1 <? n2)\n\t  | BNot b => negb (beval b)\n\t  | BOr b1 b2 => orb (beval b1) (beval b2)\nend.\n\n(* BEGIN FIX *)\nExample beval_test_1 : beval (BGe 3 4) = false.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nExample beval_test_2 : beval (BGe 3 3) = true.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nExample beval_test_3 : beval (BGe 5 3) = true.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nExample beval_test_4 : beval (BOr (BGe 3 4) (BGe 3 2)) = true.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nDefinition BAnd (b1 b2 : bexp) : bexp := \n(* END FIX *)\n  BNot(BOr (BNot b1) (BNot b2))\n.\n(* BEGIN FIX *)\nExample beval_test_5 : beval (BAnd (BGe 3 4) (BGe 3 2)) = false.\n(* END FIX *)\nsimpl. reflexivity.\nQed.\n\n(* BEGIN FIX *)\nExample beval_test_6 : beval (BAnd (BGe 4 4) (BGe 3 2)) = true.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nExample beval_test_7 : beval\n  (BAnd\n    (BOr\n      (BOr\n        (BNot BTrue)\n        (BEq 3 3))\n      (BGe 5 3))\n    (BNot (BEq 3 4)))\n  = true.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nLemma bor_left_unit (b : bexp) : beval (BOr BFalse b) = beval b.\n(* END FIX *)\nsimpl. reflexivity. Qed.\n\n(* BEGIN FIX *)\nLemma lem (b : bexp)(p : beval b = true) : beval (BAnd b BTrue) = true.\n(* END FIX *)\nsimpl.\nrewrite -> p.\nsimpl.\nreflexivity.\nQed.\n", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/04/hf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7653536752890409}}
{"text": "\n\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs.\nRequire Export Sorting.\nRequire Export DecType SetReflect.\nRequire Export DecList.\n\n\n\nSet Implicit Arguments.\n\n\n\nSection MoreDecList.\n\nContext { A: eqType}.\n(*------------------ Uniform list -----------------------------------------------------*)\n\nInductive uniform : list A -> Prop:=\n| Nil_uni: uniform nil\n|Sing_uni(a:A): uniform (a::nil)\n|Ind_uni(a b:A)(l:list A): a=b -> uniform (b::l)-> uniform (a::b::l).\n\nLemma uniform_elim (a:A)(l: list A): uniform (a::l)-> (forall x, In x l -> x=a).\nProof. Admitted.\nLemma uniform_elim1 (a:A)(l: list A): uniform (a::l)-> (forall x, In x (a::l)-> x=a).\nProof. Admitted.\nLemma uniform_elim2 (a:A) (l: list A): uniform (a::l)-> uniform l.\nProof. Admitted.\nLemma uniform_intro (a:A)(l: list A): (forall x, In x l -> x=a) -> uniform (a::l).\nProof. Admitted.\n\n(* ----------------- delete_all operation ---------------------------------------------  *)\n\nFixpoint del_all (a:A)(l: list A): list A:=\n    match l with\n    |nil => nil\n    | a1::l1 => match  (a == a1) with\n               |true => del_all a l1\n               |false => a1 :: del_all a l1\n               end\n    end.\n\n(* This function deletes all occurences of a in the list l *)\n\n  Lemma del_all_elim1 (a b:A)(l: list A): In a (del_all b l)-> In a l.\n  Proof. Admitted.\n  Lemma del_all_elim2 (a b:A)(l: list A): In a (del_all b l)-> (a<>b).\n  Proof. Admitted.\n\n  Lemma del_all_intro (a b: A)(l:list A): In a l -> a<>b -> In a (del_all b l).\n  Proof. Admitted.\n  Lemma del_all_iff (a b:A)(l: list A): (In a (del_all b l) <-> (In a l /\\ a<>b)).\n  Proof. Admitted.\n\n  Hint Resolve del_all_elim1 del_all_elim2 del_all_intro: core.\n  \n  Lemma del_all_nodup (a:A)(l: list A): NoDup l -> NoDup (del_all a l).\n  Proof. Admitted.\n\n  Hint Resolve del_all_nodup: core.\n\n (* ------- count of an element a in the list l ----------------------------------------*)\n\n Fixpoint count (a:A) (l:list A) : nat:= match l with\n                          | nil => 0\n                          |a1::l1 => match a == a1 with\n                                    |true => S (count a l1)\n                                    |false => count a l1\n                                    end\n                                        end.\n  Lemma countP1 (a:A) (l:list A): In a l -> (count a l >= 1).\n  Proof. Admitted.\n  Lemma countP2 (a:A)(l: list A): ~ In a l -> (count a l = 0).\n  Proof. Admitted.\n  Lemma countP3 (a:A)(l: list A): (count a l = 0) -> ~ In a l.\n  Proof. Admitted.\n  Lemma countP4 (a:A)(l: list A): count a (a::l) = S (count a l).\n  Proof. Admitted.\n  Lemma countP5 (a b:A)(l: list A): (count a l) <= count a (b::l).\n  Proof. Admitted.\n  Lemma countP6 (a: A)(l: list A): count a l <= |l|.\n  Proof. Admitted.\n  Lemma countP7 (a:A) (l:list A): In a l -> count a l = S(count a (delete a l)).\n  Proof. Admitted.\n  Lemma countP8 (a:A) (l:list A): forall x, x<>a-> count x (a::l) = count x l.\n  Proof. Admitted.\n  Lemma countP9 (a:A) (l:list A): forall x, x<>a -> count x l = count x (delete a l).\n  Proof. Admitted.\n  Lemma countP10 (a:A)(l s:list A): count a l <= count a s -> count a (a::l) <= count a (a::s).\n  Proof. Admitted.\n  Lemma countP11 (a:A)(l s: list A): count a l = count a s -> count a (a::l) = count a (a::s).\n  Proof. Admitted.\n  Lemma countP12 (a:A)(l s: list A): count a l < count a s -> count a (a::l) < count a (a::s).\n  Proof. Admitted.\n  \n  Hint Immediate countP1 countP2 countP3: core.\n  Hint Resolve countP4 countP5 countP6 countP7 countP8 countP9: core.\n \nEnd MoreDecList.\n\n Hint Resolve del_all_elim1 del_all_elim2 del_all_intro: core.\n Hint Resolve del_all_nodup: core.\n\n Hint Immediate countP1 countP2 countP3: core.\n Hint Resolve countP4 countP5 countP6 countP7 countP8 countP9:  core.\n Hint Resolve countP10 countP11 countP12: core.\n\n\nSection Permutation.\n\n  Context { A: eqType }.\n  \n   Lemma EM:forall x y : A, x=y \\/ x<>y.\n   Proof. eauto. Qed.\n   \n   Definition empty: list A:= nil.\n\n   Lemma count_in_putin1 (a: A)(l: list A)(lr: A-> A-> bool):\n     count a (putin lr a l)= S (count a l).\n   Proof. { induction l. simpl. destruct (a==a) eqn:H. auto. conflict_eq. \n           { simpl. case (lr a a0) eqn: H0.\n             { destruct (a==a0) eqn:H1. move /eqP in H1.\n               subst a0. assert (H: count a (a::a::l)=S(count a (a::l))). eauto.\n               rewrite H. eauto.\n               assert (H: count a (a :: a0 :: l) = S (count a (a0::l))).\n               eauto.  move /eqP in H1. rewrite H. eauto. }\n             { simpl. destruct (a==a0) eqn:H1. omega. auto. } } } Qed.\n   \n   Lemma count_in_putin2 (a b: A)(l: list A)(lr: A-> A-> bool):\n     a<>b -> count a l = count a (putin lr b l).\n   Proof. { induction l.\n            { simpl; destruct (a==b) eqn:H. intros;conflict_eq. auto. }\n            { intros.  simpl. case (lr b a0) eqn: H0.\n              { destruct (a==a0) eqn:H1.\n                move /eqP in H1. subst a0.\n                replace (count a (b :: a :: l)) with (count a (a :: l)).\n                eauto. symmetry; auto. move /eqP in H1.\n                replace (count a (b :: a0 :: l)) with (count a (a0 :: l)).\n                all: symmetry;eauto. }\n              { destruct (a==a0) eqn: H1.\n                move /eqP in H1. subst a0.\n                replace (count a (a :: putin lr b l)) with (S(count a (putin lr b l))).\n                 eauto. symmetry. auto. \n                replace (count a (a0 :: putin lr b l)) with (count a (putin lr b l)).\n                auto. move /eqP in H1. symmetry;auto. }  } } Qed.\n   \n  Lemma count_in_sorted (a: A)(l: list A)(lr: A-> A-> bool): count a l = count a (sort lr l). \n  Proof. { induction l. simpl; auto.\n           simpl. destruct  (a == a0) eqn:H0.\n           move /eqP in H0. subst a.\n           rewrite IHl. symmetry; apply count_in_putin1.\n           move /eqP in H0. rewrite IHl.  apply count_in_putin2. auto. }  Qed.\n\n\n  Hint Resolve count_in_putin1 count_in_putin2 count_in_sorted: core.\n  \n  (* ---------------  sublist of a list (subsequence)------------------------------------ *)\n\n  Fixpoint sublist (l s: list A): bool := match (l, s) with\n                                              |(nil , _) => true\n                                              |(a::l1, nil) => false\n                                              |(a::l1, b::s1) => match (a == b) with\n                                                          |true => sublist l1 s1\n                                                          |false => sublist l s1\n                                                          end\n                                       end.\n  \n  Lemma sublist_intro (l: list A): sublist nil l.\n  Proof.   destruct l;simpl;auto. Qed.\n  Lemma sublist_reflex (l: list A): sublist l l.\n  Proof. induction l;simpl.\n         auto. destruct (a==a) eqn:H; [auto | conflict_eq].  Qed.\n\n \n  Lemma sublist_elim1 (l: list A): sublist l nil -> l=nil.\n  Proof. destruct l; [auto | simpl; intro H; inversion H]. Qed.\n\n  Lemma sublist_elim2 (a:A)(l s: list A): sublist (a::l) s -> In a s.\n  Proof. induction s.  simpl; auto. simpl. destruct (a==a0) eqn:H. move /eqP in H.\n         subst a0; auto. intro;right;auto. Qed.\n  \n  Lemma sublist_elim3 (a: A)(l s: list A): sublist (a::l) s -> sublist l s.\n  Proof. { revert l; revert a. induction s.\n         { auto. }\n         { intros a0 l. \n           simpl. destruct (a0 == a) eqn:H.\n           { destruct l. auto.  destruct (e == a) eqn:H1.\n             apply IHs. auto.  }\n           { destruct l. auto.  destruct (e == a) eqn:H1.\n             { intro H2. assert (H2a: sublist (e::l) s). eapply IHs;exact H2.\n               eapply IHs; exact H2a. }\n             { apply IHs. }\n         } } } Qed.\n  \n  Lemma sublist_elim3a (a e: A)(l s: list A): sublist (a::l)(e::s)-> sublist l s.\n  Proof. simpl. destruct (a==e) eqn:H. auto.   eauto using sublist_elim3. Qed.\n  \n   Lemma sublist_intro1 (a:A)(l s: list A): sublist l s -> sublist l (a::s).\n   Proof.  { revert s;revert a. induction l.\n           { auto. }\n           { intros a0 s.\n             simpl. destruct (a == a0) eqn:H. apply sublist_elim3. auto. } } Qed.\n\n   Lemma sublist_Subset (l s: list A): sublist l s -> Subset l s.\n   Proof. { revert s. induction l.  eauto.\n           intros s H. eauto. unfold \"[<=]\". intros x H1.\n           destruct H1. subst x. eauto using  sublist_elim2. apply sublist_elim3 in H.\n           apply IHl in H. eauto. } Qed.\n\n  \n   Lemma sublist_elim4 (l s: list A): sublist l s -> (forall a, count a l <= count a s).\n   Proof. { revert l. induction s as [| e s'].\n          { intro l. intro H. assert (H1: l=nil); auto using sublist_elim1.\n            subst l; auto.  }\n          { intros l H x. destruct l as [|a l'].\n            simpl. omega. destruct (x==a) eqn:Hxa.\n            { move /eqP in Hxa. subst x.\n              simpl in H. destruct (a == e) eqn: Hae. move /eqP in Hae.\n              subst e.\n              cut (count a l' <= count a s'); auto.\n              assert (H1: count a (a :: l') <= count a  s'). eauto.\n              cut (count a s' <= count a (e::s')). omega. auto. }\n            { assert (H1: count x (a::l')<= count x s').\n              { simpl. rewrite Hxa. eauto using sublist_elim3a. }\n              cut (count x s' <= count x (e::s')). omega. auto. } } } Qed.\n   \n   \n  Lemma sublist_trans (l1 l2 l3: list A): sublist l1 l2 -> sublist l2 l3 -> sublist l1 l3.\n  Proof. Admitted.\n\n  Hint Extern 0 (is_true ( sublist ?x ?z) ) =>\n  match goal with\n  | H: is_true (sublist x  ?y) |- _ => apply (@sublist_trans  x y z)\n  | H: is_true (sublist ?y  z) |- _ => apply (@sublist_trans  x y z) \n  end.\n\n    \n \n  Hint Resolve sublist_intro sublist_intro1 sublist_reflex sublist_Subset sublist_elim1: core.\n  Hint Resolve sublist_elim2 sublist_elim3 sublist_elim4: core.\n\n\n  (* -------------- list inclusion (subset in multiset) ----------------------------------*)\n\n  Fixpoint included (l s: list A): bool := match l with\n                                        |nil => true\n                                        | a::l1 => match (memb a s) with\n                                                  |true => included l1 (delete a s)\n                                                  |false => false\n                                                  end\n                                        end.\n  Lemma included_intro1 (l: list A): included nil l.\n  Proof. Admitted.\n   Lemma included_refl (l: list A): included l l.\n  Proof. Admitted.\n  Lemma included_intro2 (a:A)(l s: list A): In a s -> included l (delete a s)-> included (a::l) s.\n  Proof. Admitted.\n  Lemma included_intro3 (l s: list A): sublist l s -> included l s.\n  Proof. Admitted. \n  Lemma included_intro (l s: list A): (forall a, count a l <= count a s)-> included l s.\n  Proof. { revert s. induction l. intros;apply included_intro1;auto.\n           { intros s H. simpl.  case (memb a s) eqn:Has;move /membP in Has.\n             apply IHl. intro x. destruct (EM x a).\n             Focus 2.  replace (count x l) with (count x (a::l)).\n             replace (count x (delete a s)) with (count x s).\n             all: eauto. subst x. \n             replace (count a l) with ((count a (a::l)) -1). \n             replace (count a (delete a s)) with ((count a s)-1).\n             specialize (H a).  omega.\n             replace (count a s) with (S (count a (delete a s))). omega.\n             symmetry; eauto.\n             replace (count a (a :: l)) with (S (count a l)). omega.\n             symmetry; eauto.\n             specialize (H a). rewrite countP4 in H.\n             replace (count a s) with 0 in H. inversion H. symmetry; eauto. } } Qed. \n\n  Lemma included_elim1 (l: list A): included l nil -> l=nil.\n  Proof. Admitted.\n  Lemma included_elim2 (a:A)(l s: list A): included (a::l) s -> In a s.\n  Proof. Admitted.\n  Lemma included_elim3 (a:A)(l s: list A): included (a::l) s -> included l (delete a s).\n  Proof. Admitted.\n  Lemma included_elim4 (a:A)(l s: list A): included (a::l) s -> included l s.\n  Proof. Admitted.\n  Lemma included_elim5 (l s: list A): included l s -> Subset l s.\n  Proof. Admitted.\n\n  Lemma included_elim (l s: list A): included l s-> (forall a, count a l <= count a s).\n  Proof. { revert s. induction l. simpl. intros;omega. \n           intros s H x. apply included_elim2 in H as H1. apply included_elim3 in H as H2.\n           assert (H3: count a l <= count a (delete a s)).  eapply IHl with (s:= (delete a s)).\n           auto.  destruct (EM x a).\n           subst x. replace (count a (a::l)) with (S(count a l)).\n           replace (count a s) with (S( count a (delete a s))).\n           omega. symmetry; eauto.  eauto.  \n           replace (count x (a::l)) with (count x l).\n           replace (count x s) with  (count x (delete a s)).\n           eauto. all: symmetry;eauto. } Qed. \n  \n\n  Lemma included_trans (l1 l2 l3: list A): \n  included l1 l2-> included l2 l3 -> included l1 l3.\n  Proof. Admitted.\n\n   Hint Extern 0 (is_true ( included ?x ?z) ) =>\n  match goal with\n  | H: is_true (included x  ?y) |- _ => apply (@included_trans  x y z)\n  | H: is_true (included ?y  z) |- _ => apply (@included_trans  x y z) \n  end.\n\n \n  Hint Resolve included_intro1 included_intro2 included_intro3: core.\n  Hint Resolve included_refl included_intro: core.\n  Hint Resolve included_elim1 included_elim2 included_elim3: core.\n  Hint Resolve included_elim4 included_elim5 included_elim: core.\n\n  (* ----- Some Misc Lemmas on nodup, sorted, sublist, subset and included ---------------- *)\n\n  Lemma nodup_subset_included (l s: list A): NoDup l -> l [<=] s -> included l s.\n  Proof. Admitted.\n  Lemma sorted_included_sublist (l s: list A)(lr: A->A-> bool):\n    Sorted lr l-> Sorted lr s-> included l s-> sublist l s.\n  Proof. Admitted.\n  Lemma first_in_ordered_sublists (a e:A)(l s: list A)(lr: A->A-> bool):\n    Sorted lr (a::l)-> Sorted lr (e::s)-> sublist (a::l)(e::s)-> lr e a.\n  Proof. Admitted.\n\n\n  Hint Resolve nodup_subset_included: core.\n  Hint Immediate sorted_included_sublist first_in_ordered_sublists:core.\n  \n\n  (* --------------------  permuted lists (permutation) -------------------------------------*)\n\n  Definition perm (l s: list A): bool:= included l s && included s l. \n\n  Lemma perm_intro  (l s: list A): (forall a, count a l = count a s)-> perm l s.\n  Proof.  { intro H; split_; apply included_intro; intro a; specialize (H a); omega. } Qed.\n\n  Lemma perm_intro0a (l: list A)(lr: A-> A-> bool): perm l (sort lr l).\n  Proof. apply perm_intro. eauto. Qed.\n  \n  Lemma perm_intro0b (l: list A)(lr: A-> A-> bool): perm (sort lr l) l.\n  Proof. apply perm_intro; eauto. Qed.\n \n  Lemma perm_nil: perm nil nil.\n  Proof. split_; eauto.  Qed.\n  \n  Lemma perm_refl (l: list A): perm l l.\n  Proof. split_; eauto.  Qed.\n\n  Lemma perm_intro3 (l s: list A): sublist l s -> sublist s l -> perm l s.\n  Proof. intros; split_; eauto.  Qed.\n\n  Lemma perm_elim   (l s: list A): perm l s -> (forall a, count a l = count a s).\n  Proof.  { intros H a. move /andP in H. destruct H as [H1 H2].\n          cut (count a l <= count a s). cut (count a s <= count a l). omega.\n          all: eauto. } Qed.\n\n  Lemma perm_elim1 (l: list A): perm l nil -> l = nil.\n  Proof. intro H; move /andP in H; destruct H as [H1 H2]; eauto. Qed.\n  Lemma perm_elim2 (l s: list A): perm l s -> l [=] s.\n  Proof. move /andP;intro H; destruct H; split; eauto. Qed.\n  Lemma perm_sym (l s: list A): perm l s -> perm s l.\n  Proof. move /andP;intro H; apply /andP; tauto. Qed.\n\n  Lemma perm_trans (x y z: list A): perm x y -> perm y z -> perm x z.\n  Proof. intros H H1; move /andP in H; move /andP in H1; apply /andP.\n         split;destruct H; destruct H1. all: auto. Qed.\n\n  Hint Extern 0 (is_true ( perm ?x ?z) ) =>\n  match goal with\n  | H: is_true (perm x  ?y) |- _ => apply (@perm_trans x y z)\n  | H: is_true (perm ?y  z) |- _ => apply (@perm_trans x y z) \n  end.\n\n  Hint Resolve  perm_intro0a  perm_intro0b perm_refl perm_nil perm_elim1 : core.\n  Hint Immediate perm_elim perm_intro perm_sym: core.\n  \n  Lemma perm_sort1 (l s: list A)(lr: A-> A-> bool): perm l s -> perm  l (sort lr s).\n  Proof.  eauto. Qed.\n\n   Lemma perm_sort2 (l s: list A)(lr: A-> A-> bool): perm l s -> perm  (sort lr l) s.\n   Proof. eauto.  Qed.\n\n   Lemma perm_sort3 (l s: list A)(lr: A-> A-> bool): perm l s -> perm (sort lr l)(sort lr s).\n   Proof. eauto using perm_sort1. Qed.\n\n   Hint Resolve perm_sort1 perm_sort2 perm_sort3: core.\n   \n End Permutation. \n\n\n\n\n  Hint Resolve count_in_putin1 count_in_putin2 count_in_sorted: core.\n\n\n  Hint Resolve sublist_intro sublist_intro1 sublist_reflex sublist_Subset sublist_elim1: core.\n  Hint Resolve sublist_elim2 sublist_elim3 sublist_elim3a sublist_elim4: core.\n\n  Hint Extern 0 (is_true ( sublist ?x ?z) ) =>\n  match goal with\n  | H: is_true (sublist x  ?y) |- _ => apply (@sublist_trans _ x y z)\n  | H: is_true (sublist ?y  z) |- _ => apply (@sublist_trans _ x y z) \n  end.\n\n\n  Hint Resolve included_intro1 included_intro2 included_intro3: core.\n  Hint Resolve included_refl included_intro: core.\n  Hint Resolve included_elim1 included_elim2 included_elim3: core.\n  Hint Resolve included_elim4 included_elim5 included_elim: core.\n\n  Hint Extern 0 (is_true ( included ?x ?z) ) =>\n  match goal with\n  | H: is_true (included x  ?y) |- _ => apply (@included_trans _ x y z)\n  | H: is_true (included ?y  z) |- _ => apply (@included_trans _ x y z) \n  end.\n\n  Hint Resolve nodup_subset_included: core.\n  Hint Immediate sorted_included_sublist first_in_ordered_sublists:core.\n \n  Hint Resolve  perm_intro0a  perm_intro0b perm_refl perm_nil perm_elim1 : core.\n  Hint Immediate perm_elim perm_intro perm_sym: core.\n  Hint Resolve perm_elim1 perm_elim2: core.\n\n  Hint Extern 0 (is_true ( perm ?x ?z) ) =>\n  match goal with\n  | H: is_true (perm x  ?y) |- _ => apply (@perm_trans _ x y z)\n  | H: is_true (perm ?y  z) |- _ => apply (@perm_trans _ x y z) \n  end.\n\n  Hint Resolve perm_sort1 perm_sort2 perm_sort3: 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/MoreDecList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7653536702844136}}
{"text": "Require Import aula3 aula4 aula5 aula6 aula7.\n\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below. Have a look at the tests to understand\n    what these functions should do. *)\n\n(** **** Exercise: 2 star  *)\nFixpoint nonzeros (l:natlist) : natlist :=\nmatch l with\n | nil => nil \n | h :: t => match h with\n             | 0 => nonzeros t\n             | S n => h :: nonzeros t\n             end\nend.\n\n(** **** Exercise: 1 star  *)\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\nsimpl.\nreflexivity.\nQed.\n(** **** Exercise: 2 star  *)\nFixpoint oddmembers (l:natlist) : natlist :=\nmatch l with\n | nil => nil\n | h :: t => match oddb h with\n            |false => oddmembers t\n            |true => h :: oddmembers t\n            end\nend.\n            \n\n(** **** Exercise: 1 star  *)\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\nsimpl.\nreflexivity.\nQed.\n\n(** **** Exercise: 2 star  *)\nDefinition countoddmembers (l:natlist) : nat := (length(oddmembers l)).\n\n\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof.\nunfold countoddmembers.\nsimpl.\nreflexivity.\nQed.\n\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof.\nreflexivity.\nQed.\n(** **** Exercise: 1 star  *)\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof.\nreflexivity.\nQed.\n\n(** **** Exercise: 3 stars, advanced (alternate)  *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1 with\n| nil => l2\n| h :: t => match l2 with\n           | nil => l1\n           | h0 :: t0 => h :: h0 :: alternate t t0\n           end\nend.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof.\nsimpl.\nreflexivity.\nQed.\n\n", "meta": {"author": "nobreconfrade", "repo": "reidocoq", "sha": "98fc4c357cbc38041b1e83e1a2c468aac0d6ef70", "save_path": "github-repos/coq/nobreconfrade-reidocoq", "path": "github-repos/coq/nobreconfrade-reidocoq/reidocoq-98fc4c357cbc38041b1e83e1a2c468aac0d6ef70/doit5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8902942181173146, "lm_q1q2_score": 0.7653536666040246}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\n\nLemma le_SS : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nLemma plus_le_r : forall (x y z : nat),\n  x <= y -> x + z <= y + z.\nProof.\n  intros x y z.\n  generalize dependent y.\n  generalize dependent x.\n  induction z as [|z' IH].\n  - intros x y. intros H.\n    rewrite plus_0_r. rewrite plus_0_r. apply H.\n  - intros x y. intros H.\n    rewrite <- plus_Snm_nSm.\n    rewrite <- plus_Snm_nSm.\n    apply IH.\n    apply le_SS. apply H.\nQed.\n\nLemma plus_le_l : forall (x y z : nat),\n  x + z <= y + z -> x <= y.\nProof.\n  intros x y z.\n  generalize dependent y.\n  generalize dependent x.\n  induction z as [|z' IH].\n  - intros x y. intros H.\n    rewrite plus_0_r in H.\n    rewrite plus_0_r in H.\n    apply H.\n  - intros x y. intros H.\n    rewrite <- plus_Snm_nSm in H.\n    rewrite <- plus_Snm_nSm in H.\n    apply IH in H.\n    inversion H.\n    + reflexivity.\n    + transitivity (S x).\n      * apply le_S. reflexivity.\n      * apply H1.\nQed.\n\nLemma combine_le : forall x1 y1 x2 y2 : nat,\n  x1 <= y1 ->\n  x2 <= y2 ->\n    x1 + x2 <= y1 + y2.\nProof.\n  intros x1 y1 x2 y2.\n  intros H1 H2.\n  transitivity (x1 + y2).\n  - rewrite plus_comm. rewrite (plus_comm x1).\n    apply plus_le_r. apply H2.\n  - apply plus_le_r. apply H1.\nQed.\n\nLemma lebP : forall n m, reflect (n <= m) (n <=? m).\nProof.\n  intros n m. apply iff_reflect. split.\n  - intros H. apply leb_correct. apply H.\n  - intros H. apply leb_complete. apply H.\nQed.\n\nLemma leb_trans : forall i j k,\n  i <= j -> j <= k ->\n    i <= k.\nProof.\n  intros i j k.\n  intros H1 H2.\n  transitivity j.\n  - apply H1.\n  - apply H2.\nQed.\n", "meta": {"author": "kawu", "repo": "partage-proofs", "sha": "40dc3b6fc189ddd038116893b75e3f0ce7c4d5f2", "save_path": "github-repos/coq/kawu-partage-proofs", "path": "github-repos/coq/kawu-partage-proofs/partage-proofs-40dc3b6fc189ddd038116893b75e3f0ce7c4d5f2/TAG/LE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7653536627774721}}
{"text": "(*|\n##########################################################################################################\nHow to prove that another definition of permutation is the same as the Default Permutation Library for Coq\n##########################################################################################################\n\n:Link: https://stackoverflow.com/q/71083370\n|*)\n\n(*|\nQuestion\n********\n\nI need to prove that a secondary definition of permutation is\nequivalent to the default definition of permutation in Coq:\n\nDown bellow is the default Permutation definition in Coq\n\n.. coq:: none\n|*)\n\nRequire Import List.\nImport ListNotations.\n\nDefinition A := nat.\n\n(*||*)\n\nInductive Permutation : list A -> list A -> Prop :=\n| perm_nil : Permutation [] []\n| perm_skip x l l' : Permutation l l' -> Permutation (x :: l) (x :: l')\n| perm_swap x y l : Permutation (y :: x :: l) (x :: y :: l)\n| perm_trans l l' l'' :\n  Permutation l l' -> Permutation l' l'' -> Permutation l l''.\n\n(*|\nI need to prove that the above mentioned definition is equivalent to\nthe following definition:\n\n.. coq:: none\n|*)\n\nRequire Import PeanoNat.\n\nFixpoint occurences_number x l :=\n  match l with\n  | nil => 0\n  | h :: tl => if (x =? h)\n               then S (occurences_number x tl)\n               else occurences_number x tl\n  end.\n\n(*||*)\n\nDefinition perm l l' := forall x, occurences_number x l = occurences_number x l'.\n\n(*|\nWhich as you have noticed uses the definition ``occurences_number``\ndown bellow:\n|*)\n\nReset occurences_number. (* .none *)\nFixpoint occurences_number x l :=\n  match l with\n  | nil => 0\n  | h :: tl => if (x =? h)\n               then S (occurences_number x tl)\n               else occurences_number x tl\n  end.\n\n(*| .. coq:: none |*)\n\nDefinition perm l l' := forall x, occurences_number x l = occurences_number x l'.\n\n(*| What I need to prove indeed is the following: |*)\n\nLemma permutation_to_perm : forall l l', Permutation l l' -> perm l l'.\n\n(*| Down bellow is my incomplete proof |*)\n\nProof.\n  induction l.\n  - admit.\n  - intros l' Hequiv.\n    generalize dependent a.\n    generalize dependent l.\n    case l'.\n    + Admitted.\n\n(*|\n----\n\n**A (Arthur Azevedo De Amorim):** It is probably easier to do\ninduction on the hypothesis ``Permutation l l'`` instead of ``l``.\n\n**Q:** What do you mean @ArthurAzevedoDeAmorim?\n\n**A (Arthur Azevedo De Amorim):** In Coq, you can do induction not\nonly on data structures, but also on hypotheses that state inductively\ndefined propositions. If you are not familiar with this concept, I\nrecommend having a look at the Software Foundations book:\nhttps://softwarefoundations.cis.upenn.edu/lf-current/IndProp.html#lab216\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nHere is a proof that follows the strategy I outlined above:\n|*)\n\nLemma Permutation_to_perm l l' : Permutation l l' -> perm l l'.\nProof.\n  intros H. induction H as [| x l1 l2 _ IH | x y l | l1 l2 l3 _ IH1 _ IH2 ].\n  - intros ?; reflexivity.\n  - intros y. simpl. now rewrite IH.\n  - intros z. simpl. now destruct (z =? y), (z =? x).\n  - intros ?. now rewrite IH1.\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/how-to-prove-that-another-definition-of-permutation-is-the-same-as-the-default-p.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8902942144788077, "lm_q1q2_score": 0.7653536506722358}}
{"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\t\tpropositions, including conjunction, disjunction, and existential\n\t\tquantification.  In this chapter, we bring yet another new tool\n\t\tinto the mix: _inductive definitions_. *)\n\n(** In past chapters, we have seen two ways of stating that a number\n\t\t[n] is even: We can say\n\n\t\t\t(1) [evenb n = true], or\n\n\t\t\t(2) [exists k, n = double k].\n\n\t\tYet another possibility is to say that [n] is even if we can\n\t\testablish its evenness from the following rules:\n\n\t\t\t - Rule [ev_0]: The number [0] is even.\n\t\t\t - 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\t\tlet's imagine using it to show that [4] is even. By rule [ev_SS],\n\t\tit suffices to show that [2] is even. This, in turn, is again\n\t\tguaranteed by rule [ev_SS], as long as we can show that [0] is\n\t\teven. 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\t\tof the course.  For purposes of informal discussions, it is\n\t\thelpful to have a lightweight notation that makes them easy to\n\t\tread and write.  _Inference rules_ are one such notation:\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t------------             (ev_0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t even 0\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t even n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t----------------          (ev_SS)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t even (S (S n))\n*)\n\n(** Each of the textual rules above is reformatted here as an\n\t\tinference rule; the intended reading is that, if the _premises_\n\t\tabove the line all hold, then the _conclusion_ below the line\n\t\tfollows.  For example, the rule [ev_SS] says that, if [n]\n\t\tsatisfies [even], then [S (S n)] also does.  If a rule has no\n\t\tpremises above the line, then its conclusion holds\n\t\tunconditionally.\n\n\t\tWe can represent a proof using these rules by combining rule\n\t\tapplications into a _proof tree_. Here's how we might transcribe\n\t\tthe above proof that [4] is even:\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t --------  (ev_0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\teven 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t -------- (ev_SS)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\teven 2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t -------- (ev_SS)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\teven 4\n*)\n\n(** (Why call this a \"tree\" (rather than a \"stack\", for example)?\n\t\tBecause, in general, inference rules can have multiple premises.\n\t\tWe 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\t\tevenness into a formal Coq definition using an [Inductive]\n\t\tdeclaration, where each constructor corresponds to an inference\n\t\trule: *)\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\t\tuses of [Inductive]: the thing we are defining is not a [Type],\n\t\tbut rather a function from [nat] to [Prop] -- that is, a property\n\t\tof numbers.  We've already seen other inductive definitions that\n\t\tresult in functions -- for example, [list], whose type is [Type ->\n\t\tType].  What is really new here is that, because the [nat]\n\t\targument of [even] appears to the _right_ of the colon, it is\n\t\tallowed to take different values in the types of different\n\t\tconstructors: [0] in the type of [ev_0] and [S (S n)] in the type\n\t\tof [ev_SS].\n\n\t\tIn contrast, the definition of [list] names the [X] parameter\n\t\t_globally_, to the _left_ of the colon, forcing the result of\n\t\t[nil] and [cons] to be the same ([list X]).  Had we tried to bring\n\t\t[nat] to the left in defining [even], we would have seen an\n\t\terror: *)\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\t\t\t\tas 1st argument in \"[wrong_ev 0]\". *)\n\n(** In an [Inductive] definition, an argument to the type\n\t\tconstructor on the left of the colon is called a \"parameter\",\n\t\twhereas an argument on the right is called an \"index\".\n\n\t\tFor example, in [Inductive list (X : Type) := ...], [X] is a\n\t\tparameter; in [Inductive even : nat -> Prop := ...], the\n\t\tunnamed [nat] argument is an index. *)\n\n(** We can think of the definition of [even] as defining a Coq\n\t\tproperty [even : nat -> Prop], together with primitive theorems\n\t\t[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\tInductive even : nat -> Prop :=\n\t| ev_0 : even 0\n\t| 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\t\ttheorems.  In particular, we can use Coq's [apply] tactic with the\n\t\trule 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\tintros n. simpl. intros Hn.\n\tapply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(** **** Exercise: 1 star, standard (ev_double)  *)\nTheorem ev_double : forall n,\n\teven (double n).\nProof.\n\tintros n. induction n as [| n' Ihn].\n\t- simpl. apply ev_0.\n\t- 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\t\t_reason about_ such evidence.\n\n\t\tIntroducing [even] with an [Inductive] declaration tells Coq not\n\t\tonly that the constructors [ev_0] and [ev_SS] are valid ways to\n\t\tbuild evidence that some number is even, but also that these two\n\t\tconstructors are the _only_ ways to build evidence that numbers\n\t\tare even (in the sense of [even]). *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n\t\t[even n], then we know that [E] must have one of two shapes:\n\n\t\t\t- [E] is [ev_0] (and [n] is [O]), or\n\t\t\t- [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is\n\t\t\t\tevidence for [even n']). *)\n\n(** This suggests that it should be possible to analyze a\n\t\thypothesis of the form [even n] much as we do inductively defined\n\t\tdata structures; in particular, it should be possible to argue by\n\t\t_induction_ and _case analysis_ on such evidence.  Let's look at a\n\t\tfew 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\t\twe are given [even n] as a hypothesis.  We already know how to\n\t\tperform case analysis on [n] using [destruct] or [induction],\n\t\tgenerating separate subgoals for the case where [n = O] and the\n\t\tcase where [n = S n'] for some [n'].  But for some proofs we may\n\t\tinstead want to analyze the evidence that [even n] _directly_. As\n\t\ta tool, we can prove our characterization of evidence for\n\t\t[even n], using [destruct]. *)\n\nTheorem ev_inversion :\n\tforall (n : nat), even n ->\n\t\t(n = 0) \\/ (exists n', n = S (S n') /\\ even n').\nProof.\n\tintros n E.\n\tdestruct E as [ | n' E'].\n\t- (* E = ev_0 : even 0 *)\n\t\tleft. reflexivity.\n\t- (* E = ev_SS n' E' : even (S (S n')) *)\n\t\tright. exists n'. split. reflexivity. apply E'.\nQed.\n\n(** The following theorem can easily be proved using [destruct] on\n\t\tevidence. *)\n\nTheorem ev_minus2 : forall n,\n\teven n -> even (pred (pred n)).\nProof.\n\tintros n E.\n\tdestruct E as [| n' E'].\n\t- (* E = ev_0 *) simpl. apply ev_0.\n\t- (* 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\teven (S (S n)) -> even n.\n(** Intuitively, we know that evidence for the hypothesis cannot\n\t\tconsist just of the [ev_0] constructor, since [O] and [S] are\n\t\tdifferent constructors of the type [nat]; hence, [ev_SS] is the\n\t\tonly case that applies.  Unfortunately, [destruct] is not smart\n\t\tenough to realize this, and it still generates two subgoals.  Even\n\t\tworse, in doing so, it keeps the final goal unchanged, failing to\n\t\tprovide any useful information for completing the proof.  *)\nProof.\n\tintros n E.\n\tdestruct E as [| n' E'].\n\t- (* E = ev_0. *)\n\t\t(* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n\t\treplacing all occurrences of the property argument by the values\n\t\tthat correspond to each constructor.  This is enough in the case\n\t\tof [ev_minus2] because that argument [n] is mentioned directly\n\t\tin the final goal. However, it doesn't help in the case of\n\t\t[evSS_ev] since the term that gets replaced ([S (S n)]) is not\n\t\tmentioned anywhere. *)\n\n(** We could patch this proof by replacing the goal [even n],\n\t\twhich does not mention the replaced term [S (S n)], by the\n\t\tequivalent goal [even (pred (pred (S (S n))))], which does mention\n\t\tthis term, after which [destruct] can make progress. But it is\n\t\tmore 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\t intro Heq. rewrite Heq. apply Hev.\nQed.\n\n(** Coq provides a tactic called [inversion], which does the work of\n\t\tour inversion lemma and more besides. *)\n\n(** The [inversion] tactic can detect (1) that the first case\n\t\t([n = 0]) does not apply and (2) that the [n'] that appears in the\n\t\t[ev_SS] case must be the same as [n].  It has an \"[as]\" variant\n\t\tsimilar to [destruct], allowing us to assign names rather than\n\t\thave Coq choose them. *)\n\nTheorem evSS_ev' : forall n,\n\teven (S (S n)) -> even n.\nProof.\n\tintros n E.\n\tinversion E as [| n' E'].\n\t(* We are in the [E = ev_SS n' E'] case now. *)\n\tapply E'.\nQed.\n\n(** The [inversion] tactic can apply the principle of explosion to\n\t\t\"obviously contradictory\" hypotheses involving inductive\n\t\tproperties, something that takes a bit more work using our\n\t\tinversion lemma. For example: *)\nTheorem one_not_even : ~ even 1.\nProof.\n\tintros H. apply ev_inversion in H.\n\tdestruct H as [ | [m [Hm _]]].\n\t- discriminate H.\n\t- discriminate Hm.\nQed.\n\nTheorem one_not_even' : ~ even 1.\n\tintros H. inversion H. Qed.\n\n(** **** Exercise: 1 star, standard (inversion_practice)\n\n\t\tProve the following result using [inversion].  For extra practice,\n\t\tprove it using the inversion lemma. *)\n\nTheorem SSSSev__even : forall n,\n\teven (S (S (S (S n)))) -> even n.\nProof.\n\tintros n H. inversion H. inversion H1. apply H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (even5_nonsense)\n\n\t\tProve the following result using [inversion]. *)\n\nTheorem even5_nonsense :\n\teven 5 -> 2 + 2 = 9.\nProof.\n\tintros H. inversion H. inversion H1 as [| n' Hn']. inversion Hn'.\nQed.\n(** [] *)\n\n(** The [inversion] tactic does quite a bit of work. When\n\t\tapplied to equalities, as a special case, it does the work of both\n\t\t[discriminate] and [injection]. In addition, it carries out the\n\t\t[intros] and [rewrite]s that are typically necessary in the case\n\t\tof [injection]. It can also be applied, more generally, to analyze\n\t\tevidence for inductively defined propositions.  As examples, we'll\n\t\tuse it to reprove some theorems from [Tactics.v]. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n\t[n; m] = [o; o] ->\n\t[n] = [m].\nProof.\n\tintros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n\tS n = O ->\n\t2 + 2 = 5.\nProof.\n\tintros n contra. inversion contra. Qed.\n\n(** Here's how [inversion] works in general.  Suppose the name\n\t\t[H] refers to an assumption [P] in the current context, where [P]\n\t\thas been defined by an [Inductive] declaration.  Then, for each of\n\t\tthe constructors of [P], [inversion H] generates a subgoal in which\n\t\t[H] has been replaced by the exact, specific conditions under\n\t\twhich this constructor could have been used to prove [P].  Some of\n\t\tthese subgoals will be self-contradictory; [inversion] throws\n\t\tthese away.  The ones that are left represent the cases that must\n\t\tbe proved to establish the original goal.  For those, [inversion]\n\t\tadds all equations into the proof context that must hold of the\n\t\targuments given to [P] (e.g., [S (S n') = n] in the proof of\n\t\t[evSS_ev]). *)\n\n(** The [ev_double] exercise above shows that our new notion of\n\t\tevenness is implied by the two earlier ones (since, by\n\t\t[even_bool_prop] in chapter [Logic], we already know that\n\t\tthose are equivalent to each other). To show that all three\n\t\tcoincide, we just need the following lemma. *)\n\nLemma ev_even_firsttry : forall n,\n\teven 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\t\tsince [even] is mentioned in a premise, this strategy would\n\t\tprobably lead to a dead end, as in the previous section.  Thus, it\n\t\tseems better to first try [inversion] on the evidence for [even].\n\t\tIndeed, the first case can be solved trivially. *)\n\n\tintros n E. inversion E as [| n' E'].\n\t- (* E = ev_0 *)\n\t\texists 0. reflexivity.\n\t- (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n\t\tk, S (S n') = double k], but the only available assumption is\n\t\t[E'], which states that [even n'] holds.  Since this isn't\n\t\tdirectly useful, it seems that we are stuck and that performing\n\t\tcase analysis on [E] was a waste of time.\n\n\t\tIf we look more closely at our second goal, however, we can see\n\t\tthat something interesting happened: By performing case analysis\n\t\ton [E], we were able to reduce the original result to a similar\n\t\tone that involves a _different_ piece of evidence for [even]:\n\t\tnamely [E'].  More formally, we can finish our proof by showing\n\t\tthat\n\n\t\t\t\texists k', n' = double k',\n\n\t\twhich is the same as the original statement, but with [n'] instead\n\t\tof [n].  Indeed, it is not difficult to convince Coq that this\n\t\tintermediate result suffices. *)\n\n\t\tassert (I : (exists k', n' = double k') ->\n\t\t\t\t\t\t\t\t(exists k, S (S n') = double k)).\n\t\t{ intros [k' Hk']. rewrite Hk'. exists (S k'). reflexivity. }\n\t\tapply 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\t\tencountered similar problems in the [Induction] chapter, when\n\t\ttrying to use case analysis to prove results that required\n\t\tinduction.  And once again the solution is... induction!\n\n\t\tThe behavior of [induction] on evidence is the same as its\n\t\tbehavior on data: It causes Coq to generate one subgoal for each\n\t\tconstructor that could have used to build that evidence, while\n\t\tproviding an induction hypotheses for each recursive occurrence of\n\t\tthe property in question.\n\n\t\tTo prove a property of [n] holds for all numbers for which [even\n\t\tn] holds, we can use induction on [even n]. This requires us to\n\t\tprove two things, corresponding to the two ways in which [even n]\n\t\tcould have been constructed. If it was constructed by [ev_0], then\n\t\t[n=0], and the property must hold of [0]. If it was constructed by\n\t\t[ev_SS], then the evidence of [even n] is of the form [ev_SS n'\n\t\tE'], where [n = S (S n')] and [E'] is evidence for [even n']. In\n\t\tthis case, the inductive hypothesis says that the property we are\n\t\ttrying to prove holds for [n']. *)\n\n(** Let's try our current lemma again: *)\n\nLemma ev_even : forall n,\n\teven n -> exists k, n = double k.\nProof.\n\tintros n E.\n\tinduction E as [|n' E' IH].\n\t- (* E = ev_0 *)\n\t\texists 0. reflexivity.\n\t- (* E = ev_SS n' E'\n\t\t\t with IH : exists k', n' = double k' *)\n\t\tdestruct IH as [k' Hk'].\n\t\trewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds\n\t\tto [E'], the single recursive occurrence of [even] in its own\n\t\tdefinition.  Since [E'] mentions [n'], the induction hypothesis\n\t\ttalks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n\t\tevenness now follows. *)\n\nTheorem ev_even_iff : forall n,\n\teven n <-> exists k, n = double k.\nProof.\n\tintros n. split.\n\t- (* -> *) apply ev_even.\n\t- (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n\t\trecurring technique across many areas, and in particular when\n\t\tformalizing the semantics of programming languages, where many\n\t\tproperties of interest are defined inductively. *)\n\n(** The following exercises provide simple examples of this\n\t\ttechnique, 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\tintros n m Hn Hm. induction Hn as [| n' Hn'].\n\t- simpl. apply Hm.\n\t- simpl. apply ev_SS. apply IHHn'.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (even'_ev)\n\n\t\tIn general, there may be multiple ways of defining a\n\t\tproperty inductively.  For example, here's a (slightly contrived)\n\t\talternative 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\t\tone.  (You may want to look at the previous theorem when you get\n\t\tto the induction step.) *)\n\nTheorem even'_ev : forall n, even' n <-> even n.\nProof.\n\tintros n. split.\n\t- intros E. induction E.\n\t\t+ apply ev_0.\n\t\t+ apply ev_SS. apply ev_0.\n\t\t+ apply ev_sum.\n\t\t++ apply IHE1. ++ apply IHE2.\n\t- intros E. induction E.\n\t\t+ apply even'_0.\n\t\t+ assert (S (S n) = 2 + n) as H. simpl. reflexivity.\n\t\t\trewrite -> H. apply even'_sum. apply even'_2. apply IHE.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev)\n\n\t\tFinding the appropriate thing to do induction on is a\n\t\tbit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n\teven (n + m) -> even n -> even m.\nProof.\n\tintros n m Hnm Hn. induction Hn.\n\t- simpl in Hnm. apply Hnm.\n\t- apply IHHn. simpl in Hnm. apply evSS_ev in Hnm. apply Hnm.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (ev_plus_plus)\n\n\t\tThis exercise just requires applying existing lemmas.  No\n\t\tinduction or even case analysis is needed, though some of the\n\t\trewriting may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n\teven (n+m) -> even (n+p) -> even (m+p).\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [even])\n\t\tcan be thought of as a _property_ -- i.e., it defines\n\t\ta subset of [nat], namely those numbers for which the proposition\n\t\tis provable.  In the same way, a two-argument proposition can be\n\t\tthought of as a _relation_ -- i.e., it defines a set of pairs for\n\t\twhich the proposition is provable. *)\n\nModule Playground.\n\n(** One useful example is the \"less than or equal to\" relation on\n\t\tnumbers. *)\n\n(** The following definition should be fairly intuitive.  It\n\t\tsays that there are two ways to give evidence that one number is\n\t\tless than or equal to another: either observe that they are the\n\t\tsame number, or give evidence that the first is less than or equal\n\t\tto the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n\t| le_n n : le n n\n\t| 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\t\t[le_S] follow the same patterns as proofs about properties, like\n\t\t[even] above. We can [apply] the constructors to prove [<=]\n\t\tgoals (e.g., to show that [3<=3] or [3<=6]), and we can use\n\t\ttactics like [inversion] to extract information from [<=]\n\t\thypotheses in the context (e.g., to prove that [(2 <= 1) ->\n\t\t2+2=5].) *)\n\n(** Here are some sanity checks on the definition.  (Notice that,\n\t\talthough these are the same kind of simple \"unit tests\" as we gave\n\t\tfor the testing functions we wrote in the first few lectures, we\n\t\tmust construct their proofs explicitly -- [simpl] and\n\t\t[reflexivity] don't do the job, because the proofs aren't just a\n\t\tmatter of simplifying computations.) *)\n\nTheorem test_le1 :\n\t3 <= 3.\nProof.\n\t(* WORKED IN CLASS *)\n\tapply le_n.  Qed.\n\nTheorem test_le2 :\n\t3 <= 6.\nProof.\n\t(* WORKED IN CLASS *)\n\tapply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n\t(2 <= 1) -> 2 + 2 = 5.\nProof.\n\t(* WORKED IN CLASS *)\n\tintros H. inversion H. inversion H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n\t\tin 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\t| sq n : square_of n (n * n).\n\nInductive next_nat : nat -> nat -> Prop :=\n\t| nn n : next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n\t| ne_1 n : even (S n) -> next_even n (S n)\n\t| 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\t\tDefine an inductive binary relation [total_relation] that holds\n\t\tbetween every pair of natural numbers. *)\n\nInductive total_relation: nat -> nat -> Prop :=\n\ttotal_relation_any: forall n m, total_relation n m.\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation)\n\n\t\tDefine an inductive binary relation [empty_relation] (on numbers)\n\t\tthat never holds. *)\n\nInductive empty_relation: nat -> nat -> Prop :=\n\tempty_relation_all: forall n m, False -> empty_relation n m.\n\n(** From the definition of [le], we can sketch the behaviors of\n\t\t[destruct], [inversion], and [induction] on a hypothesis [H]\n\t\tproviding evidence of the form [le e1 e2].  Doing [destruct H]\n\t\twill generate two cases. In the first case, [e1 = e2], and it\n\t\twill replace instances of [e2] with [e1] in the goal and context.\n\t\tIn the second case, [e2 = S n'] for some [n'] for which [le e1 n']\n\t\tholds, and it will replace instances of [e2] with [S n'].\n\t\tDoing [inversion H] will remove impossible cases and add generated\n\t\tequalities to the context for further use. Doing [induction H]\n\t\twill, in the second case, add the induction hypothesis that the\n\t\tgoal holds when [e2] is replaced with [n']. *)\n\n(** **** Exercise: 3 stars, standard, optional (le_exercises)\n\n\t\tHere are a number of facts about the [<=] and [<] relations that\n\t\twe are going to need later in the course.  The proofs make good\n\t\tpractice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n\tintros m n o Hmn Hno. induction Hno as [| n' o'].\n\t- apply Hmn.\n\t- apply le_S. apply IHo'.\nQed.\n\nTheorem O_le_n : forall n,\n\t0 <= n.\nProof.\n\tintros n. induction n as [| n'].\n\t- apply le_n.\n\t- apply le_S. apply IHn'.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n\tn <= m -> S n <= S m.\nProof.\n\tintros n m H. induction H.\n\t- apply le_n.\n\t- apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n\tS n <= S m -> n <= m.\nProof.\n\tintros n m H. inversion H.\n\t- apply le_n.\n\t- apply (le_trans n (S n)).\n\t\t+ apply le_S. apply le_n.\n\t\t+ apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n\ta <= a + b.\nProof.\n\tintros a b. induction a as [| a'].\n\t- rewrite -> plus_O_n. induction b as [| b'].\n\t\t+ apply le_n.\n\t\t+ apply le_S. apply IHb'.\n\t- simpl. apply n_le_m__Sn_le_Sm. apply IHa'.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n\tn1 + n2 < m ->\n\tn1 < m /\\ n2 < m.\nProof.\n unfold lt. intros n1 n2 m H. split.\n\t- apply (le_trans (S n1) (S (n1 + n2))).\n\t\t+ apply n_le_m__Sn_le_Sm. apply le_plus_l.\n\t\t+ assumption.\n\t- apply (le_trans (S n2) (S (n1 + n2))).\n\t\t+ apply n_le_m__Sn_le_Sm. rewrite -> plus_comm. apply le_plus_l.\n\t\t+ assumption.\nQed.\n\nTheorem lt_S : forall n m,\n\tn < m ->\n\tn < S m.\nProof.\n\tunfold lt. intros n m H.\n\tapply le_S. assumption.\nQed.\n\nTheorem leb_complete : forall n m,\n\tn <=? m = true -> n <= m.\nProof.\n\tintros n m H. generalize dependent n. induction m.\n\t- intros n H. induction n.\n\t\t+ apply le_n.\n\t\t+ simpl in H. discriminate H.\n\t- intros n H. induction n.\n\t\t+ apply le_0_n.\n\t\t+ apply n_le_m__Sn_le_Sm. apply IHm in H. assumption.\nQed.\n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n\tn <= m ->\n\tn <=? m = true.\nProof.\n\tintros n m H. generalize dependent n. induction m.\n\t- intros n H. inversion H. reflexivity.\n\t- intros n H. induction n.\n\t\t+ reflexivity.\n\t\t+ apply IHm. apply Sn_le_Sm__n_le_m. assumption.\nQed.\n\n(** Hint: This one can easily be proved without using [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n\tn <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n\tintros n m o Hnm Hmo.\n\tapply leb_complete in Hnm. apply leb_complete in Hmo. apply leb_correct.\n\tapply (le_trans n m). assumption. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n\tn <=? m = true <-> n <= m.\nProof.\n\tsplit.\n\t- apply leb_complete.\n\t- apply leb_correct.\nQed.\n(** [] *)\n\nModule R.\n\n(** **** Exercise: 3 stars, standard, recommended (R_provability)\n\n\t\tWe can define three-place relations, four-place relations,\n\t\tetc., in just the same way as binary relations.  For example,\n\t\tconsider the following three-place relation on numbers: *)\n\nInductive R : nat -> nat -> nat -> Prop :=\n\t | c1 : R 0 0 0\n\t | c2 m n o (H : R m n o) : R (S m) n (S o)\n\t | c3 m n o (H : R m n o) : R m (S n) (S o)\n\t | c4 m n o (H : R (S m) (S n) (S (S o))) : R m n o\n\t | c5 m n o (H : R m n o) : R n m o.\n\n(** - Which of the following propositions are provable?\n\t\t\t- [R 1 1 2]\n\t\t\t- [R 2 2 6]\n\n\t\t- If we dropped constructor [c5] from the definition of [R],\n\t\t\twould the set of provable propositions change?  Briefly (1\n\t\t\tsentence) explain your answer.\n\n\t\t- If we dropped constructor [c4] from the definition of [R],\n\t\t\twould the set of provable propositions change?  Briefly (1\n\t\t\tsentence) explain your answer.\n\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\t\tThe relation [R] above actually encodes a familiar function.\n\t\tFigure out which function; then state and prove this equivalence\n\t\tin Coq? *)\n\nDefinition fR : nat -> nat -> nat := fun x y => x + y.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof. Admitted.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 2 stars, advanced (subsequence)\n\n\t\tA list is a _subsequence_ of another list if all of the elements\n\t\tin the first list occur in the same order in the second list,\n\t\tpossibly with some extra elements in between. For example,\n\n\t\t\t[1;2;3]\n\n\t\tis a subsequence of each of the lists\n\n\t\t\t[1;2;3]\n\t\t\t[1;1;1;2;2;3]\n\t\t\t[1;2;7;3]\n\t\t\t[5;6;1;9;9;2;7;3;8]\n\n\t\tbut it is _not_ a subsequence of any of the lists\n\n\t\t\t[1;2]\n\t\t\t[1;3]\n\t\t\t[5;6;2;1;7;3;8].\n\n\t\t- Define an inductive proposition [subseq] on [list nat] that\n\t\t\tcaptures what it means to be a subsequence. (Hint: You'll need\n\t\t\tthree cases.)\n\n\t\t- Prove [subseq_refl] that subsequence is reflexive, that is,\n\t\t\tany list is a subsequence of itself.\n\n\t\t- Prove [subseq_app] that for any lists [l1], [l2], and [l3],\n\t\t\tif [l1] is a subsequence of [l2], then [l1] is also a subsequence\n\t\t\tof [l2 ++ l3].\n\n\t\t- (Optional, harder) Prove [subseq_trans] that subsequence is\n\t\t\ttransitive -- that is, if [l1] is a subsequence of [l2] and [l2]\n\t\t\tis a subsequence of [l3], then [l1] is a subsequence of [l3].\n\t\t\tHint: choose your induction carefully! *)\n\nInductive subseq : list nat -> list nat -> Prop :=\n\t| empty l: subseq [] l\n\t| addparent x l1 l2: subseq l1 l2 -> subseq l1 (x :: l2)\n\t| addboth x l1 l2: subseq l1 l2 -> subseq (x :: l1) (x :: l2)\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n\tintros l. induction l.\n\t- apply empty.\n\t- apply addboth. assumption.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n\tsubseq l1 l2 ->\n\tsubseq l1 (l2 ++ l3).\nProof.\n\tintros l1 l2 l3 H. induction H.\n\t- apply empty.\n\t- simpl. apply addparent. assumption.\n\t- simpl. apply addboth. assumption.\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n\tsubseq l1 l2 ->\n\tsubseq l2 l3 ->\n\tsubseq l1 l3.\nProof.\n\t(*intros. generalize dependent l1. induction H0.\n\t- intros. induction H.\n\t\t+ apply empty.\n\t\t+ apply IHsubseq.\n\t\t+\n\t-\n\n\tinduction H12.\n\t- intros _. apply empty.\n\t- intros H. apply IHsubseq. induction H.\n\t\t+\n\t\t+\n\t\t+\n\t-*)\nAdmitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (R_provability2)\n\n\t\tSuppose we give Coq the following definition:\n\n\t\tInductive R : nat -> list nat -> Prop :=\n\t\t\t| c1 : R 0 []\n\t\t\t| c2 : forall n l, R n l -> R (S n) (n :: l)\n\t\t\t| c3 : forall n l, R (S n) l -> R n l.\n\n\t\tWhich of the following propositions are provable?\n\n\t\t- [R 2 [1;0]]\n\t\t- [R 1 [1;2;1;0]]\n\t\t- [R 6 [3;2;1;0]]  *)\n\n(* FILL IN HERE\n\n\t\t[] *)\n\n(* ################################################################# *)\n(** * Case Study: Regular Expressions *)\n\n(** The [even] property provides a simple example for\n\t\tillustrating inductive definitions and the basic techniques for\n\t\treasoning about them, but it is not terribly exciting -- after\n\t\tall, it is equivalent to the two non-inductive definitions of\n\t\tevenness that we had already seen, and does not seem to offer any\n\t\tconcrete benefit over them.\n\n\t\tTo give a better sense of the power of inductive definitions, we\n\t\tnow show how to use them to model a classic concept in computer\n\t\tscience: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing sets of\n\t\tstrings.  Their syntax is defined as follows: *)\n\nInductive reg_exp {T : Type} : Type :=\n\t| EmptySet\n\t| EmptyStr\n\t| Char (t : T)\n\t| App (r1 r2 : reg_exp)\n\t| Union (r1 r2 : reg_exp)\n\t| Star (r : reg_exp).\n\n(** Note that this definition is _polymorphic_: Regular\n\t\texpressions in [reg_exp T] describe strings with characters drawn\n\t\tfrom [T] -- that is, lists of elements of [T].\n\n\t\t(We depart slightly from standard practice in that we do not\n\t\trequire the type [T] to be finite.  This results in a somewhat\n\t\tdifferent theory of regular expressions, but the difference is not\n\t\tsignificant for our purposes.) *)\n\n(** We connect regular expressions and strings via the following\n\t\trules, which define when a regular expression _matches_ some\n\t\tstring:\n\n\t\t\t- The expression [EmptySet] does not match any string.\n\n\t\t\t- The expression [EmptyStr] matches the empty string [[]].\n\n\t\t\t- The expression [Char x] matches the one-character string [[x]].\n\n\t\t\t- If [re1] matches [s1], and [re2] matches [s2],\n\t\t\t\tthen [App re1 re2] matches [s1 ++ s2].\n\n\t\t\t- If at least one of [re1] and [re2] matches [s],\n\t\t\t\tthen [Union re1 re2] matches [s].\n\n\t\t\t- Finally, if we can write some string [s] as the concatenation\n\t\t\t\tof a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n\t\t\t\texpression [re] matches each one of the strings [s_i],\n\t\t\t\tthen [Star re] matches [s].\n\n\t\t\t\tAs a special case, the sequence of strings may be empty, so\n\t\t\t\t[Star re] always matches the empty string [[]] no matter what\n\t\t\t\t[re] is. *)\n\n(** We can easily translate this informal definition into an\n\t\t[Inductive] one as follows: *)\n\nInductive exp_match {T} : list T -> reg_exp -> Prop :=\n\t| MEmpty: exp_match [] EmptyStr\n\t| MChar x: exp_match [x] (Char x)\n\t| MApp s1 re1 s2 re2:\n\t\texp_match s1 re1 -> exp_match s2 re2 ->\n\t\t\texp_match (s1 ++ s2) (App re1 re2)\n\t| MUnionL s1 re1 re2:\n\t\texp_match s1 re1 ->\n\t\t\texp_match s1 (Union re1 re2)\n\t| MUnionR re1 s2 re2:\n\t\texp_match s2 re2 ->\n\t\t\texp_match s2 (Union re1 re2)\n\t| MStar0 re : exp_match [] (Star re)\n\t| MStarApp s1 s2 re:\n\t\texp_match s1 re -> exp_match s2 (Star re) ->\n\t\t\texp_match (s1 ++ s2) (Star re).\n\n(** Again, for readability, we can also display this definition using\n\t\tinference-rule notation.  At the same time, let's introduce a more\n\t\treadable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t----------------                    (MEmpty)\n\t\t\t\t\t\t\t\t\t\t\t\t\t [] =~ EmptyStr\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t---------------                      (MChar)\n\t\t\t\t\t\t\t\t\t\t\t\t\t [x] =~ Char x\n\n\t\t\t\t\t\t\t\t\t\t\t s1 =~ re1    s2 =~ re2\n\t\t\t\t\t\t\t\t\t\t\t-------------------------                 (MApp)\n\t\t\t\t\t\t\t\t\t\t\t s1 ++ s2 =~ App re1 re2\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ts1 =~ re1\n\t\t\t\t\t\t\t\t\t\t\t\t---------------------                (MUnionL)\n\t\t\t\t\t\t\t\t\t\t\t\t s1 =~ Union re1 re2\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ts2 =~ re2\n\t\t\t\t\t\t\t\t\t\t\t\t---------------------                (MUnionR)\n\t\t\t\t\t\t\t\t\t\t\t\t s2 =~ Union re1 re2\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t---------------                     (MStar0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t [] =~ Star re\n\n\t\t\t\t\t\t\t\t\t\t\ts1 =~ re    s2 =~ Star re\n\t\t\t\t\t\t\t\t\t\t ---------------------------            (MStarApp)\n\t\t\t\t\t\t\t\t\t\t\t\ts1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the\n\t\tinformal ones that we gave at the beginning of the section.\n\t\tFirst, we don't need to include a rule explicitly stating that no\n\t\tstring matches [EmptySet]; we just don't happen to include any\n\t\trule that would have the effect of some string matching\n\t\t[EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n\t\teven _allow_ us to give such a \"negative rule.\")\n\n\t\tSecond, the informal rules for [Union] and [Star] correspond\n\t\tto two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n\t\t[MStarApp].  The result is logically equivalent to the original\n\t\trules but more convenient to use in Coq, since the recursive\n\t\toccurrences of [exp_match] are given as direct arguments to the\n\t\tconstructors, making it easier to perform induction on evidence.\n\t\t(The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n\t\tto prove that the constructors given in the inductive declaration\n\t\tand the ones that would arise from a more literal transcription of\n\t\tthe informal rules are indeed equivalent.)\n\n\t\tLet's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n\tapply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n\tapply (MApp [1] _ [2]).\n\t- apply MChar.\n\t- apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the strings\n\t\t[[1]] and [[2]] directly.  Since the goal mentions [[1; 2]]\n\t\tinstead of [[1] ++ [2]], Coq wouldn't be able to figure out how to\n\t\tsplit the string on its own.)\n\n\t\tUsing [inversion], we can also show that certain strings do _not_\n\t\tmatch a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n\tintros H. inversion H.\nQed.\n\n(** We can define helper functions for writing down regular\n\t\texpressions. The [reg_exp_of_list] function constructs a regular\n\t\texpression that matches exactly the list that it receives as an\n\t\targument: *)\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n\tmatch l with\n\t| [] => EmptyStr\n\t| x :: l' => App (Char x) (reg_exp_of_list l')\n\tend.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n\tsimpl. apply (MApp [1]).\n\t{ apply MChar. }\n\tapply (MApp [2]).\n\t{ apply MChar. }\n\tapply (MApp [3]).\n\t{ apply MChar. }\n\tapply MEmpty.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n\t\tthe following lemma shows that every string [s] that matches [re]\n\t\talso matches [Star re]. *)\n\nLemma MStar1 :\n\tforall T s (re : @reg_exp T) ,\n\t\ts =~ re ->\n\t\ts =~ Star re.\nProof.\n\tintros T s re H.\n\trewrite <- (app_nil_r _ s).\n\tapply (MStarApp s [] re).\n\t- apply H.\n\t- apply MStar0.\nQed.\n\n(** (Note the use of [app_nil_r] to change the goal of the theorem to\n\t\texactly the same shape expected by [MStarApp].) *)\n\n(** **** Exercise: 3 stars, standard (exp_match_ex1)\n\n\t\tThe following lemmas show that the informal matching rules given\n\t\tat the beginning of the chapter can be obtained from the formal\n\t\tinductive definition. *)\n\nLemma empty_is_empty : forall T (s : list T),\n\t~ (s =~ EmptySet).\nProof.\n\tintros T s H. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n\ts =~ re1 \\/ s =~ re2 ->\n\ts =~ Union re1 re2.\nProof.\n\tintros T s re1 re2 [H1 | H2].\n\t- apply MUnionL. assumption.\n\t- apply MUnionR. assumption.\nQed.\n\n(** The next lemma is stated in terms of the [fold] function from the\n\t\t[Poly] chapter: If [ss : list (list T)] represents a sequence of\n\t\tstrings [s1, ..., sn], then [fold app ss []] is the result of\n\t\tconcatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n\t(forall s, In s ss -> s =~ re) ->\n\tfold app ss [] =~ Star re.\nProof.\n\tintros. induction ss as [| ss'].\n\t- simpl. apply MStar0.\n\t- simpl. apply MStarApp.\n\t\t+ apply H. simpl. left. reflexivity.\n\t\t+ apply IHss.  intros s Hin. apply H. simpl. right. apply Hin.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, standard, optional (reg_exp_of_list_spec)\n\n\t\tProve that [reg_exp_of_list] satisfies the following\n\t\tspecification: *)\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n\ts1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof. Admitted.\n\n(*Inductive exp_match {T} : list T -> reg_exp -> Prop :=\n\t| MEmpty: exp_match [] EmptyStr\n\t| MChar x: exp_match [x] (Char x)\n\t| MApp s1 re1 s2 re2:\n\t\texp_match s1 re1 -> exp_match s2 re2 ->\n\t\t\texp_match (s1 ++ s2) (App re1 re2)\n\t| MUnionL s1 re1 re2:\n\t\texp_match s1 re1 ->\n\t\t\texp_match s1 (Union re1 re2)\n\t| MUnionR re1 s2 re2:\n\t\texp_match s2 re2 ->\n\t\t\texp_match s2 (Union re1 re2)\n\t| MStar0 re : exp_match [] (Star re)\n\t| MStarApp s1 s2 re:\n\t\texp_match s1 re -> exp_match s2 (Star re) ->\n\t\t\texp_match (s1 ++ s2) (Star re).*)\n\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n\t\tstructure, we might expect that proofs involving regular\n\t\texpressions will often require induction on evidence. *)\n\n(** For example, suppose that we wanted to prove the following\n\t\tintuitive result: If a regular expression [re] matches some string\n\t\t[s], then all elements of [s] must occur as character literals\n\t\tsomewhere in [re].\n\n\t\tTo state this theorem, we first define a function [re_chars] that\n\t\tlists all characters that occur in a regular expression: *)\n\nFixpoint re_chars {T} (re : reg_exp) : list T :=\n\tmatch re with\n\t| EmptySet => []\n\t| EmptyStr => []\n\t| Char x => [x]\n\t| App re1 re2 => re_chars re1 ++ re_chars re2\n\t| Union re1 re2 => re_chars re1 ++ re_chars re2\n\t| Star re => re_chars re\n\tend.\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\ts =~ re ->\n\tIn x s ->\n\tIn x (re_chars re).\nProof.\n\tintros T s re x Hmatch Hin.\n\tinduction Hmatch\n\t\tas [| x'\n\t\t\t\t| s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n\t\t\t\t| s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n\t\t\t\t| re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].\n\t(* WORKED IN CLASS *)\n\t- (* MEmpty *)\n\t\tapply Hin.\n\t- (* MChar *)\n\t\tapply Hin.\n\t- simpl. rewrite In_app_iff in *.\n\t\tdestruct Hin as [Hin | Hin].\n\t\t+ (* In x s1 *)\n\t\t\tleft. apply (IH1 Hin).\n\t\t+ (* In x s2 *)\n\t\t\tright. apply (IH2 Hin).\n\t- (* MUnionL *)\n\t\tsimpl. rewrite In_app_iff.\n\t\tleft. apply (IH Hin).\n\t- (* MUnionR *)\n\t\tsimpl. rewrite In_app_iff.\n\t\tright. apply (IH Hin).\n\t- (* MStar0 *)\n\t\tdestruct Hin.\n\n(** Something interesting happens in the [MStarApp] case.  We obtain\n\t\t_two_ induction hypotheses: One that applies when [x] occurs in\n\t\t[s1] (which matches [re]), and a second one that applies when [x]\n\t\toccurs in [s2] (which matches [Star re]).  This is a good\n\t\tillustration of why we need induction on evidence for [exp_match],\n\t\trather than induction on the regular expression [re]: The latter\n\t\twould only provide an induction hypothesis for strings that match\n\t\t[re], which would not allow us to reason about the case [In x\n\t\ts2]. *)\n\n\t- (* MStarApp *)\n\t\tsimpl. rewrite In_app_iff in Hin.\n\t\tdestruct Hin as [Hin | Hin].\n\t\t+ (* In x s1 *)\n\t\t\tapply (IH1 Hin).\n\t\t+ (* In x s2 *)\n\t\t\tsimpl in IH2. apply (IH2 Hin).\nQed.\n\n(** **** Exercise: 4 stars, standard (re_not_empty)\n\n\t\tWrite a recursive function [re_not_empty] that tests whether a\n\t\tregular expression matches some string. Prove that your function\n\t\tis correct. *)\n\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool :=\n\tmatch re with\n\t| EmptySet => false\n\t| EmptyStr => true\n\t| Char _ => true\n\t| App re1 re2 => (re_not_empty re1) && (re_not_empty re2)\n\t| Union re1 re2 => (re_not_empty re1) || (re_not_empty re2)\n\t| Star _ => true\nend.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n\t(exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n\tsplit.\n\t-\n\t\tintros.\n\t\tdestruct H.\n\t\tinduction H as [|x'|s1 re1 s2 re2 Hm1 IH1 Hm2 IH2\n\t\t\t\t\t\t\t\t\t\t|s1 re1 re2 Hm IH | re1 s2 re2 Hm IH | re\n\t\t\t\t\t\t\t\t\t\t| s1 s2 re Hm1 IH1 Hm2 IH2].\n\t\t+\n\t\t\treflexivity.\n\t\t+\n\t\t\treflexivity.\n\t\t+\n\t\t\tsimpl. rewrite IH1. rewrite IH2. reflexivity.\n\t\t+\n\t\t\tsimpl. rewrite IH. reflexivity.\n\t\t+\n\t\t\tsimpl. rewrite IH.\n\t\t\tdestruct (re_not_empty re1).\n\t\t\t*\n\t\t\t\treflexivity.\n\t\t\t*\n\t\t\t\treflexivity.\n\t\t+\n\t\t\treflexivity.\n\t\t+\n\t\t\treflexivity.\n\t-\n\t\tintros.\n\t\tinduction re as [ | |x'|re1 IH1 re2 IH2|re1 IH1 re2 IH2|re IH].\n\t\t+\n\t\t\tsimpl in H. discriminate.\n\t\t+\n\t\t\texists []. apply MEmpty.\n\t\t+\n\t\t\texists [x']. apply MChar.\n\t\t+\n\t\t\tsimpl in H.\n\t\t\tapply andb_true_iff in H.\n\t\t\tdestruct H.\n\t\t\tapply IH1 in H.\n\t\t\tapply IH2 in H0.\n\t\t\tdestruct H.\n\t\t\tdestruct H0.\n\t\t\texists (x ++ x0).\n\t\t\tapply MApp.\n\t\t\t*\n\t\t\t\tapply H.\n\t\t\t*\n\t\t\t\tapply H0.\n\t\t+\n\t\t\tsimpl in H. apply orb_true_iff in H.\n\t\t\tdestruct H.\n\t\t\t*\n\t\t\t\tapply IH1 in H.\n\t\t\t\tdestruct H.\n\t\t\t\texists x.\n\t\t\t\tapply MUnionL.\n\t\t\t\tapply H.\n\t\t\t*\n\t\t\t\tapply IH2 in H.\n\t\t\t\tdestruct H.\n\t\t\t\texists x.\n\t\t\t\tapply MUnionR.\n\t\t\t\tapply H.\n\t\t+\n\t\t\texists [].\n\t\t\tapply MStar0.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n\t\tthat it will let you try to perform an induction over a term that\n\t\tisn't sufficiently general.  The effect of this is to lose\n\t\tinformation (much as [destruct] without an [eqn:] clause can do),\n\t\tand 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\ts1 =~ Star re ->\n\ts2 =~ Star re ->\n\ts1 ++ s2 =~ Star re.\nProof.\n\tintros T s1 s2 re H1.\n\n(** Just doing an [inversion] on [H1] won't get us very far in\n\t\tthe recursive cases. (Try it!). So we need induction (on\n\t\tevidence!). Here is a naive first attempt: *)\n\n\tinduction H1\n\t\tas [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n\t\t\t\t|s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n\t\t\t\t|re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** But now, although we get seven cases (as we would expect from the\n\t\tdefinition of [exp_match]), we have lost a very important bit of\n\t\tinformation from [H1]: the fact that [s1] matched something of the\n\t\tform [Star re].  This means that we have to give proofs for _all_\n\t\tseven constructors of this definition, even though all but two of\n\t\tthem ([MStar0] and [MStarApp]) are contradictory.  We can still\n\t\tget the proof to go through for a few constructors, such as\n\t\t[MEmpty]... *)\n\n\t- (* MEmpty *)\n\t\tsimpl. intros H. apply H.\n\n(** ... but most cases get stuck.  For [MChar], for instance, we\n\t\tmust show that\n\n\t\ts2 =~ Char x' -> x' :: s2 =~ Char x',\n\n\t\twhich is clearly impossible. *)\n\n\t- (* MChar. Stuck... *)\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n\t\tproperly with hypotheses that are completely general, i.e., ones\n\t\tin which all the arguments are variables, as opposed to more\n\t\tcomplex expressions, such as [Star re].\n\n\t\t(In this respect, [induction] on evidence behaves more like\n\t\t[destruct]-without-[eqn:] than like [inversion].)\n\n\t\tAn awkward way to solve this problem is \"manually generalizing\"\n\t\tover the problematic expressions by adding explicit equality\n\t\thypotheses to the lemma: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),\n\tre' = Star re ->\n\ts1 =~ re' ->\n\ts2 =~ Star re ->\n\ts1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n\t\tbecause the argument to the first hypothesis is sufficiently\n\t\tgeneral, which means that we can discharge most cases by inverting\n\t\tthe [re' = Star re] equality in the context.\n\n\t\tThis idiom is so common that Coq provides a tactic to\n\t\tautomatically generate such equations for us, avoiding thus the\n\t\tneed for changing the statements of our theorems. *)\n\nAbort.\n\n(** The tactic [remember e as x] causes Coq to (1) replace all\n\t\toccurrences of the expression [e] by the variable [x], and (2) add\n\t\tan equation [x = e] to the context.  Here's how we can use it to\n\t\tshow the above result: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp),\n\ts1 =~ Star re ->\n\ts2 =~ Star re ->\n\ts1 ++ s2 =~ Star re.\nProof.\n\tintros T s1 s2 re H1.\n\tremember (Star re) as re'.\n\n(** We now have [Heqre' : re' = Star re]. *)\n\n\tgeneralize dependent s2.\n\tinduction H1\n\t\tas [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n\t\t\t\t|s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n\t\t\t\t|re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n\n(** The [Heqre'] is contradictory in most cases, allowing us to\n\t\tconclude immediately. *)\n\n\t- (* MEmpty *)  discriminate.\n\t- (* MChar *)   discriminate.\n\t- (* MApp *)    discriminate.\n\t- (* MUnionL *) discriminate.\n\t- (* MUnionR *) discriminate.\n\n(** The interesting cases are those that correspond to [Star].  Note\n\t\tthat the induction hypothesis [IH2] on the [MStarApp] case\n\t\tmentions an additional premise [Star re'' = Star re'], which\n\t\tresults from the equality generated by [remember]. *)\n\n\t- (* MStar0 *)\n\t\tinjection Heqre'. intros Heqre'' s H. apply H.\n\n\t- (* MStarApp *)\n\t\tinjection Heqre'. intros H0.\n\t\tintros s2 H1. rewrite <- app_assoc.\n\t\tapply MStarApp.\n\t\t+ apply Hmatch1.\n\t\t+ apply IH2.\n\t\t\t* rewrite H0. reflexivity.\n\t\t\t* 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\t\t[MStar'] exercise above), shows that our definition of [exp_match]\n\t\tfor [Star] is equivalent to the informal one given previously. *)\n\nLemma MStar'' : forall T (s : list T) (re : reg_exp),\n\ts =~ Star re ->\n\texists ss : list (list T),\n\t\ts = fold app ss []\n\t\t/\\ forall s', In s' ss -> s' =~ re.\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (pumping)\n\n\t\tOne of the first really interesting theorems in the theory of\n\t\tregular expressions is the so-called _pumping lemma_, which\n\t\tstates, informally, that any sufficiently long string [s] matching\n\t\ta regular expression [re] can be \"pumped\" by repeating some middle\n\t\tsection of [s] an arbitrary number of times to produce a new\n\t\tstring also matching [re].\n\n\t\tTo begin, we need to define \"sufficiently long.\"  Since we are\n\t\tworking in a constructive logic, we actually need to be able to\n\t\tcalculate, for each regular expression [re], the minimum length\n\t\tfor strings [s] to guarantee \"pumpability.\" *)\n\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\n\tmatch re with\n\t| EmptySet => 0\n\t| EmptyStr => 1\n\t| Char _ => 2\n\t| App re1 re2 =>\n\t\t\tpumping_constant re1 + pumping_constant re2\n\t| Union re1 re2 =>\n\t\t\tpumping_constant re1 + pumping_constant re2\n\t| Star _ => 1\n\tend.\n\n(** Next, it is useful to define an auxiliary function that repeats a\n\t\tstring (appends it to itself) some number of times. *)\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n\tmatch n with\n\t| 0 => []\n\t| S n' => l ++ napp n' l\n\tend.\n\nLemma napp_plus: forall T (n m : nat) (l : list T),\n\tnapp (n + m) l = napp n l ++ napp m l.\nProof.\n\tintros T n m l.\n\tinduction n as [|n IHn].\n\t- reflexivity.\n\t- simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n(** Now, the pumping lemma itself says that, if [s =~ re] and if the\n\t\tlength of [s] is at least the pumping constant of [re], then [s]\n\t\tcan be split into three substrings [s1 ++ s2 ++ s3] in such a way\n\t\tthat [s2] can be repeated any number of times and the result, when\n\t\tcombined with [s1] and [s3] will still match [re].  Since [s2] is\n\t\talso guaranteed not to be the empty string, this gives us\n\t\ta (constructive!) way to generate strings matching [re] that are\n\t\tas long as we like. *)\n\nLemma pumping : forall T (re : @reg_exp T) s,\n\ts =~ re ->\n\tpumping_constant re <= length s ->\n\texists s1 s2 s3,\n\t\ts = s1 ++ s2 ++ s3 /\\\n\t\ts2 <> [] /\\\n\t\tforall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** To streamline the proof (which you are to fill in), the [omega]\n\t\ttactic, which is enabled by the following [Require], is helpful in\n\t\tseveral places for automatically completing tedious low-level\n\t\targuments involving equalities or inequalities over natural\n\t\tnumbers.  We'll return to [omega] in a later chapter, but feel\n\t\tfree to experiment with it now if you like.  The first case of the\n\t\tinduction gives an example of how it is used. *)\n\nImport Coq.omega.Omega.\n\nProof.\n\tintros T re s Hmatch.\n\tinduction Hmatch\n\t\tas [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n\t\t\t | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n\t\t\t | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n\t- (* MEmpty *)\n\t\tsimpl. omega.\n\t(* 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\t\trelate boolean computations to statements in [Prop].  But\n\t\tperforming this conversion as we did it there can result in\n\t\ttedious proof scripts.  Consider the proof of the following\n\t\ttheorem: *)\n\nTheorem filter_not_empty_In : forall n l,\n\tfilter (fun x => n =? x) l <> [] ->\n\tIn n l.\nProof.\n\tintros n l. induction l as [|m l' IHl'].\n\t- (* l = [] *)\n\t\tsimpl. intros H. apply H. reflexivity.\n\t- (* l = m :: l' *)\n\t\tsimpl. destruct (n =? m) eqn:H.\n\t\t+ (* n =? m = true *)\n\t\t\tintros _. rewrite eqb_eq in H. rewrite H.\n\t\t\tleft. reflexivity.\n\t\t+ (* n =? m = false *)\n\t\t\tintros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly apply\n\t\tthe [eqb_eq] lemma to the equation generated by\n\t\tdestructing [n =? m], to convert the assumption [n =? m\n\t\t= true] into the assumption [n = m]; then we had to [rewrite]\n\t\tusing this assumption to complete the case. *)\n\n(** We can streamline this by defining an inductive proposition that\n\t\tyields a better case-analysis principle for [n =? m].\n\t\tInstead of generating an equation such as [(n =? m) = true],\n\t\twhich is generally not directly useful, this principle gives us\n\t\tright 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\t\t[P] and a boolean [b].  Intuitively, it states that the property\n\t\t[P] is _reflected_ in (i.e., equivalent to) the boolean [b]: that\n\t\tis, [P] holds if and only if [b = true].  To see this, notice\n\t\tthat, by definition, the only way we can produce evidence for\n\t\t[reflect P true] is by showing [P] and then using the [ReflectT]\n\t\tconstructor.  If we invert this statement, this means that it\n\t\tshould be possible to extract evidence for [P] from a proof of\n\t\t[reflect P true].  Similarly, the only way to show [reflect P\n\t\tfalse] is by combining evidence for [~ P] with the [ReflectF]\n\t\tconstructor.\n\n\t\tIt is easy to formalize this intuition and show that the\n\t\tstatements [P <-> b = true] and [reflect P b] are indeed\n\t\tequivalent.  First, the left-to-right implication: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n\t(* WORKED IN CLASS *)\n\tintros P b H. destruct b.\n\t- apply ReflectT. rewrite H. reflexivity.\n\t- 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\tintros P b H. split.\n\t- induction H.\n\t\t+ intros HP. reflexivity.\n\t\t+ contradiction.\n\t- induction H.\n\t\t+ intros. assumption.\n\t\t+ intros. discriminate H0.\nQed.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n\t\tconnective is that, by destructing a hypothesis or lemma of the\n\t\tform [reflect P b], we can perform case analysis on [b] while at\n\t\tthe same time generating appropriate hypothesis in the two\n\t\tbranches ([P] in the first subgoal and [~ P] in the second). *)\n\nLemma eqbP : forall n m, reflect (n = m) (n =? m).\nProof.\n\tintros 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\t\tNotice how the calls to [destruct] and [apply] are combined into a\n\t\tsingle call to [destruct]. *)\n\n(** (To see this clearly, look at the two proofs of\n\t\t[filter_not_empty_In] with Coq and observe the differences in\n\t\tproof state at the beginning of the first case of the\n\t\t[destruct].) *)\n\nTheorem filter_not_empty_In' : forall n l,\n\tfilter (fun x => n =? x) l <> [] ->\n\tIn n l.\nProof.\n\tintros n l. induction l as [|m l' IHl'].\n\t- (* l = [] *)\n\t\tsimpl. intros H. apply H. reflexivity.\n\t- (* l = m :: l' *)\n\t\tsimpl. destruct (eqbP n m) as [H | H].\n\t\t+ (* n = m *)\n\t\t\tintros _. rewrite H. left. reflexivity.\n\t\t+ (* n <> m *)\n\t\t\tintros H'. right. apply IHl'. apply H'.\nQed.\n\n(** **** Exercise: 3 stars, standard, recommended (eqbP_practice)\n\n\t\tUse [eqbP] as above to prove the following: *)\n\nFixpoint count n l :=\n\tmatch l with\n\t| [] => 0\n\t| m :: l' => (if n =? m then 1 else 0) + count n l'\n\tend.\n\nTheorem eqbP_practice : forall n l,\n\tcount n l = 0 -> ~(In n l).\nProof.\n\tintros n l. induction l as [| m l'].\n\t- simpl. intros _ F. apply F.\n\t- simpl. destruct (eqbP n m) as [H | H].\n\t\t+ intros C. discriminate C.\n\t\t+ rewrite plus_O_n. unfold not. unfold not in IHl'.\n\t\t\tintros H' H''. apply IHl'. apply H'. destruct H''.\n\t\t\t* unfold not in H. symmetry in H0. apply H in H0. contradiction.\n\t\t\t* apply H0.\nQed.\n(** [] *)\n\n(** This small example shows how reflection gives us a small gain in\n\t\tconvenience; in larger developments, using [reflect] consistently\n\t\tcan often lead to noticeably shorter and clearer proof scripts.\n\t\tWe'll see many more examples in later chapters and in _Programming\n\t\tLanguage Foundations_.\n\n\t\tThe use of the [reflect] property has been popularized by\n\t\t_SSReflect_, a Coq library that has been used to formalize\n\t\timportant results in mathematics, including as the 4-color theorem\n\t\tand the Feit-Thompson theorem.  The name SSReflect stands for\n\t\t_small-scale reflection_, i.e., the pervasive use of reflection to\n\t\tsimplify small proof steps with boolean computations. *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, standard, recommended (nostutter_defn)\n\n\t\tFormulating inductive definitions of properties is an important\n\t\tskill you'll need in this course.  Try to solve this exercise\n\t\twithout any help at all.\n\n\t\tWe say that a list \"stutters\" if it repeats the same element\n\t\tconsecutively.  (This is different from not containing duplicates:\n\t\tthe sequence [[1;4;1]] repeats the element [1] but does not\n\t\tstutter.)  The property \"[nostutter mylist]\" means that [mylist]\n\t\tdoes not stutter.  Formulate an inductive definition for\n\t\t[nostutter]. *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n\t| nostutter_empty: nostutter []\n\t| nostutter_single x: nostutter [x]\n\t| nostutter_append x y l:\n\t\tx <> y -> nostutter l -> nostutter (y :: l) ->\n\t\t\tnostutter (x :: (y :: l))\n.\n(** Make sure each of these tests succeeds, but feel free to change\n\t\tthe suggested proof (in comments) if the given one doesn't work\n\t\tfor you.  Your definition might be different from ours and still\n\t\tbe correct, in which case the examples might need a different\n\t\tproof.  (You'll notice that the suggested proofs use a number of\n\t\ttactics we haven't talked about, to make them more robust to\n\t\tdifferent possible ways of defining [nostutter].  You can probably\n\t\tjust uncomment and use them as-is, but you can also prove each\n\t\texample with more basic tactics.)  *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof. repeat constructor; apply eqb_neq; auto. Qed.\n\nExample test_nostutter_2:  nostutter (@nil nat).\nProof. repeat constructor; apply eqb_neq; auto. Qed.\n\nExample test_nostutter_3:  nostutter [5].\nProof. apply nostutter_single. Qed.\n\nExample test_nostutter_4:      not (nostutter [3;1;1;4]).\n\tProof. intro.\n\trepeat match goal with\n\t\th: nostutter _ |- _ => inversion h; clear h; subst\n\tend.\n\tunfold not in H2. apply H2. reflexivity.\nQed.\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\t\tLet's prove that our definition of [filter] from the [Poly]\n\t\tchapter matches an abstract specification.  Here is the\n\t\tspecification, written out informally in English:\n\n\t\tA list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n\t\tall the same elements as [l1] and [l2], in the same order as [l1]\n\t\tand [l2], but possibly interleaved.  For example,\n\n\t\t[1;4;6;2;3]\n\n\t\tis an in-order merge of\n\n\t\t[1;6;2]\n\n\t\tand\n\n\t\t[4;3].\n\n\t\tNow, suppose we have a set [X], a function [test: X->bool], and a\n\t\tlist [l] of type [list X].  Suppose further that [l] is an\n\t\tin-order merge of two lists, [l1] and [l2], such that every item\n\t\tin [l1] satisfies [test] and no item in [l2] satisfies test.  Then\n\t\t[filter test l = l1].\n\n\t\tTranslate this specification into a Coq theorem and prove\n\t\tit.  (You'll need to begin by defining what it means for one list\n\t\tto be a merge of two others.  Do this with an inductive relation,\n\t\tnot a [Fixpoint].)  *)\n\nInductive iom {X:Type}: list X -> list X -> list X -> Prop :=\n\t| iom_empty: iom [] [] []\n\t| iom_left x l1 l2 m:\n\t\tiom l1 l2 m ->\n\t\t\tiom (x :: l1) l2 (x :: m)\n\t| iom_right x l1 l2 m:\n\t\tiom l1 l2 m ->\n\t\t\tiom l1 (x :: l2) (x :: m)\n.\n\n\nTheorem filter_challenge: forall (X:Type) (l1 l2 l: list X) (test: X -> bool),\n\tiom l1 l2 l ->\n\tfilter test l1 = l1 ->\n\tfilter test l2 = [] ->\n\tfilter test l = l1.\nProof.\n(*\tintros X l1 l2 l test H.\n\tinduction H as [| x' l1' l2' l3' Hmatch IH | x' l1' l2' l3' Hmatch IH].\n\t- intros. reflexivity.\n\t- intros. simpl in H. destruct (test x') as [] eqn:E.\n\t\t+ inversion H. apply (IH H2) in H0. simpl. rewrite E. rewrite H0. rewrite H. reflexivity.\n\t\t+ simpl. rewrite E.\n*)\t-\nAdmitted.\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\t\tA different way to characterize the behavior of [filter] goes like\n\t\tthis: Among all subsequences of [l] with the property that [test]\n\t\tevaluates to [true] on all their members, [filter test l] is the\n\t\tlongest.  Formalize this claim and prove it. *)\n\n(* FILL IN HERE\n\n\t\t[] *)\n\n(** **** Exercise: 4 stars, standard, optional (palindromes)\n\n\t\tA palindrome is a sequence that reads the same backwards as\n\t\tforwards.\n\n\t\t- Define an inductive proposition [pal] on [list X] that\n\t\t\tcaptures what it means to be a palindrome. (Hint: You'll need\n\t\t\tthree cases.  Your definition should be based on the structure\n\t\t\tof the list; just having a single constructor like\n\n\t\t\t\tc : forall l, l = rev l -> pal l\n\n\t\t\tmay seem obvious, but will not work very well.)\n\n\t\t- Prove ([pal_app_rev]) that\n\n\t\t\t forall l, pal (l ++ rev l).\n\n\t\t- Prove ([pal_rev] that)\n\n\t\t\t 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\t\tAgain, the converse direction is significantly more difficult, due\n\t\tto the lack of evidence.  Using your definition of [pal] from the\n\t\tprevious exercise, prove that\n\n\t\t forall l, l = rev l -> pal l.\n*)\n\n(* FILL IN HERE\n\n\t\t[] *)\n\n(** **** Exercise: 4 stars, advanced, optional (NoDup)\n\n\t\tRecall the definition of the [In] property from the [Logic]\n\t\tchapter, which asserts that a value [x] appears at least once in a\n\t\tlist [l]: *)\n\n(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=\n\t match l with\n\t | [] => False\n\t | x' :: l' => x' = x \\/ In A x l'\n\t end *)\n\n(** Your first task is to use [In] to define a proposition [disjoint X\n\t\tl1 l2], which should be provable exactly when [l1] and [l2] are\n\t\tlists (with elements of type X) that have no elements in\n\t\tcommon. *)\n\n(* FILL IN HERE *)\n\n(** Next, use [In] to define an inductive proposition [NoDup X\n\t\tl], which should be provable exactly when [l] is a list (with\n\t\telements of type [X]) where every member is different from every\n\t\tother.  For example, [NoDup nat [1;2;3;4]] and [NoDup\n\t\tbool []] should be provable, while [NoDup nat [1;2;1]] and\n\t\t[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\t\t[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\t\tThe _pigeonhole principle_ states a basic fact about counting: if\n\t\twe distribute more than [n] items into [n] pigeonholes, some\n\t\tpigeonhole must contain at least two items.  As often happens, this\n\t\tapparently trivial fact about numbers requires non-trivial\n\t\tmachinery 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\tIn x l ->\n\texists l1 l2, l = l1 ++ x :: l2.\nProof.\n\tintros. induction l as [| x' l'].\n\t- simpl in H. destruct H.\n\t- simpl in H. destruct H.\n\t\t+ rewrite H. exists []. exists l'. simpl. reflexivity.\n\t\t+ apply IHl' in H. destruct H. destruct H. rewrite H.\n\t\t\texists (x' :: x0). exists x1. simpl. reflexivity.\nQed.\n\n(** Now define a property [repeats] such that [repeats X l] asserts\n\t\tthat [l] contains at least one repeated element (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n\t| repeats_new x l: In x l -> repeats (x :: l)\n\t| repeats_already x l: repeats l -> repeats (x :: l)\n.\n\n(** Now, here's a way to formalize the pigeonhole principle.  Suppose\n\t\tlist [l2] represents a list of pigeonhole labels, and list [l1]\n\t\trepresents the labels assigned to a list of items.  If there are\n\t\tmore items than labels, at least two items must have the same\n\t\tlabel -- i.e., list [l1] must contain repeats.\n\n\t\tThis proof is much easier if you use the [excluded_middle]\n\t\thypothesis to show that [In] is decidable, i.e., [forall x l, (In x\n\t\tl) \\/ ~ (In x l)].  However, it is also possible to make the proof\n\t\tgo through _without_ assuming that [In] is decidable; if you\n\t\tmanage to do this, you will not need the [excluded_middle]\n\t\thypothesis. *)\n\nTheorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),\n\t excluded_middle ->\n\t (forall x, In x l1 -> In x l2) ->\n\t length l2 < length l1 ->\n\t repeats l1.\nProof.\n(*\tintros X l1. induction l1 as [|x l1' IHl1].\n\t- intros. induction l2.\n\t\t+ simpl in H1. inversion H1.\n\t\t+ simpl in H1. inversion H1.\n\t- intros. induction l2 as [| y l2' IHl2].\n\t\t+ simpl in H1. simpl in H0. (*blaine*)\n\t\t+\n\t\tunfold excluded_middle in H.\n\t\tdestruct (H (In x l1')) as [H' | H''].\n\t\t+ apply repeats_new. apply H'.\n\t\t+ unfold not in H''. apply repeats_already. apply (IHl1 l2).\n\t\t\t* unfold excluded_middle. apply H.\n\t\t\t* intros. apply H0. simpl. right. apply H2.\n\t\t\t* unfold lt in H1. simpl in H1. unfold lt.\n\t\t\t\tapply le_S_n in H1.*)\nAdmitted.\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\t\tpolymorphic lists. We can use such a definition to manually prove that\n\t\ta given regex matches a given string, but it does not give us a\n\t\tprogram that we can run to determine a match autmatically.\n\n\t\tIt would be reasonable to hope that we can translate the definitions\n\t\tof the inductive rules for constructing evidence of the match relation\n\t\tinto cases of a recursive function reflects the relation by recursing\n\t\ton a given regex. However, it does not seem straightforward to define\n\t\tsuch a function in which the given regex is a recursion variable\n\t\trecognized by Coq. As a result, Coq will not accept that the function\n\t\talways terminates.\n\n\t\tHeavily-optimized regex matchers match a regex by translating a given\n\t\tregex into a state machine and determining if the state machine\n\t\taccepts a given string. However, regex matching can also be\n\t\timplemented using an algorithm that operates purely on strings and\n\t\tregexes without defining and maintaining additional datatypes, such as\n\t\tstate machines. We'll implemement such an algorithm, and verify that\n\t\tits value reflects the match relation. *)\n\n(** We will implement a regex matcher that matches strings represented\n\t\tas 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\t\tof strings of ASCII characters. However, we will use the above\n\t\tdefinition of strings as lists as ASCII characters in order to apply\n\t\tthe existing definition of the match relation.\n\n\t\tWe could also define a regex matcher over polymorphic lists, not lists\n\t\tof ASCII characters specifically. The matching algorithm that we will\n\t\timplement needs to be able to test equality of elements in a given\n\t\tlist, and thus needs to be given an equality-testing\n\t\tfunction. Generalizing the definitions, theorems, and proofs that we\n\t\tdefine for such a setting is a bit tedious, but workable. *)\n\n(** The proof of correctness of the regex matcher will combine\n\t\tproperties of the regex-matching function with properties of the\n\t\t[match] relation that do not depend on the matching function. We'll go\n\t\tahead and prove the latter class of properties now. Most of them have\n\t\tstraightforward proofs, which have been given to you, although there\n\t\tare 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\tintros.\n\tsplit.\n\t- intros. constructor.\n\t- 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\tintros.\n\tsplit.\n\t- apply H.\n\t- intros. destruct H0.\nQed.\n\n(** [EmptySet] matches no string. *)\nLemma null_matches_none : forall (s : string), (s =~ EmptySet) <-> False.\nProof.\n\tintros.\n\tapply not_equiv_false.\n\tunfold 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\tsplit.\n\t- intros. inversion H. reflexivity.\n\t- 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\tintros.\n\tapply not_equiv_false.\n\tunfold not. intros. inversion H.\nQed.\n\n(** [Char a] matches no string that starts with a non-[a] character. *)\nLemma char_nomatch_char :\n\tforall (a b : ascii) s, b <> a -> (b :: s =~ Char a <-> False).\nProof.\n\tintros.\n\tapply not_equiv_false.\n\tunfold not.\n\tintros.\n\tapply H.\n\tinversion H0.\n\treflexivity.\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\tsplit.\n\t- intros. inversion H. reflexivity.\n\t- intros. rewrite H. apply MChar.\nQed.\n\n(** [App re0 re1] matches string [s] iff [s = s0 ++ s1], where [s0]\n\t\tmatches [re0] and [s1] matches [re1]. *)\nLemma app_exists : forall (s : string) re0 re1,\n\t\ts =~ App re0 re1 <->\n\t\texists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\nProof.\n\tintros.\n\tsplit.\n\t- intros. inversion H. exists s1, s2. split.\n\t\t* reflexivity.\n\t\t* split. apply H3. apply H4.\n\t- intros [ s0 [ s1 [ Happ [ Hmat0 Hmat1 ] ] ] ].\n\t\trewrite Happ. apply (MApp s0 _ s1 _ Hmat0 Hmat1).\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (app_ne)\n\n\t\t[App re0 re1] matches [a::s] iff [re0] matches the empty string\n\t\tand [a::s] matches [re1] or [s=s0++s1], where [a::s0] matches [re0]\n\t\tand [s1] matches [re1].\n\n\t\tEven though this is a property of purely the match relation, it is a\n\t\tcritical observation behind the design of our regex matcher. So (1)\n\t\ttake time to understand it, (2) prove it, and (3) look for how you'll\n\t\tuse it later. *)\nLemma app_ne : forall (a : ascii) s re0 re1,\n\t\ta :: s =~ (App re0 re1) <->\n\t\t([ ] =~ re0 /\\ a :: s =~ re1) \\/\n\t\texists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1.\nProof.\n\t(* 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\t\ts =~ Union re0 re1 <-> s =~ re0 \\/ s =~ re1.\nProof.\n\tintros. split.\n\t- intros. inversion H.\n\t\t+ left. apply H2.\n\t\t+ right. apply H2.\n\t- intros [ H | H ].\n\t\t+ apply MUnionL. apply H.\n\t\t+ apply MUnionR. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (star_ne)\n\n\t\t[a::s] matches [Star re] iff [s = s0 ++ s1], where [a::s0] matches\n\t\t[re] and [s1] matches [Star re]. Like [app_ne], this observation is\n\t\tcritical, so understand it, prove it, and keep it in mind.\n\n\t\tHint: you'll need to perform induction. There are quite a few\n\t\treasonable candidates for [Prop]'s to prove by induction. The only one\n\t\tthat will work is splitting the [iff] into two implications and\n\t\tproving one by induction on the evidence for [a :: s =~ Star re]. The\n\t\tother implication can be proved without induction.\n\n\t\tIn order to prove the right property by induction, you'll need to\n\t\trephrase [a :: s =~ Star re] to be a [Prop] over general variables,\n\t\tusing the [remember] tactic.  *)\n\nLemma star_ne : forall (a : ascii) s re,\n\t\ta :: s =~ Star re <->\n\t\texists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re /\\ s1 =~ Star re.\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The definition of our regex matcher will include two fixpoint\n\t\tfunctions. The first function, given regex [re], will evaluate to a\n\t\tvalue that reflects whether [re] matches the empty string. The\n\t\tfunction will satisfy the following property: *)\nDefinition refl_matches_eps m :=\n\tforall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).\n\n(** **** Exercise: 2 stars, standard, optional (match_eps)\n\n\t\tComplete the definition of [match_eps] so that it tests if a given\n\t\tregex matches the empty string: *)\nFixpoint match_eps (re: @reg_exp ascii) : bool\n\t(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (match_eps_refl)\n\n\t\tNow, prove that [match_eps] indeed tests if a given regex matches\n\t\tthe empty string.  (Hint: You'll want to use the reflection lemmas\n\t\t[ReflectT] and [ReflectF].) *)\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define other functions that use [match_eps]. However, the\n\t\tonly property of [match_eps] that you'll need to use in all proofs\n\t\tover these functions is [match_eps_refl]. *)\n\n(** The key operation that will be performed by our regex matcher will\n\t\tbe to iteratively construct a sequence of regex derivatives. For each\n\t\tcharacter [a] and regex [re], the derivative of [re] on [a] is a regex\n\t\tthat matches all suffixes of strings matched by [re] that start with\n\t\t[a]. I.e., [re'] is a derivative of [re] on [a] if they satisfy the\n\t\tfollowing relation: *)\n\nDefinition is_der re (a : ascii) re' :=\n\tforall s, a :: s =~ re <-> s =~ re'.\n\n(** A function [d] derives strings if, given character [a] and regex\n\t\t[re], it evaluates to the derivative of [re] on [a]. I.e., [d]\n\t\tsatisfies 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\t\tDefine [derive] so that it derives strings. One natural\n\t\timplementation uses [match_eps] in some cases to determine if key\n\t\tregex's match the empty string. *)\nFixpoint derive (a : ascii) (re : @reg_exp ascii) : @reg_exp ascii\n\t(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** The [derive] function should pass the following tests. Each test\n\t\testablishes an equality between an expression that will be\n\t\tevaluated by our regex matcher and the final value that must be\n\t\treturned by the regex matcher. Each test is annotated with the\n\t\tmatch 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\t(* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char c: *)\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof.\n\t(* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Char d: *)\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof.\n\t(* 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\t(* 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\t(* FILL IN HERE *) Admitted.\n\n(** \"c\" =~ Star c: *)\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof.\n\t(* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char c) (Char d): *)\nExample test_der6 :\n\tmatch_eps (derive d (derive c (App (Char c) (Char d)))) = true.\nProof.\n\t(* FILL IN HERE *) Admitted.\n\n(** \"cd\" =~ App (Char d) (Char c): *)\nExample test_der7 :\n\tmatch_eps (derive d (derive c (App (Char d) (Char c)))) = false.\nProof.\n\t(* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 4 stars, standard, optional (derive_corr)\n\n\t\tProve that [derive] in fact always derives strings.\n\n\t\tHint: one proof performs induction on [re], although you'll need\n\t\tto carefully choose the property that you prove by induction by\n\t\tgeneralizing the appropriate terms.\n\n\t\tHint: if your definition of [derive] applies [match_eps] to a\n\t\tparticular regex [re], then a natural proof will apply\n\t\t[match_eps_refl] to [re] and destruct the result to generate cases\n\t\twith assumptions that the [re] does or does not match the empty\n\t\tstring.\n\n\t\tHint: You can save quite a bit of work by using lemmas proved\n\t\tabove. In particular, to prove many cases of the induction, you\n\t\tcan rewrite a [Prop] over a complicated regex (e.g., [s =~ Union\n\t\tre0 re1]) to a Boolean combination of [Prop]'s over simple\n\t\tregex's (e.g., [s =~ re0 \\/ s =~ re1]) using lemmas given above\n\t\tthat are logical equivalences. You can then reason about these\n\t\t[Prop]'s naturally using [intro] and [destruct]. *)\nLemma derive_corr : derives derive.\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We'll define the regex matcher using [derive]. However, the only\n\t\tproperty of [derive] that you'll need to use in all proofs of\n\t\tproperties of the matcher is [derive_corr]. *)\n\n(** A function [m] matches regexes if, given string [s] and regex [re],\n\t\tit evaluates to a value that reflects whether [s] is matched by\n\t\t[re]. I.e., [m] holds the following property: *)\nDefinition matches_regex m : Prop :=\n\tforall (s : string) re, reflect (s =~ re) (m s re).\n\n(** **** Exercise: 2 stars, standard, optional (regex_match)\n\n\t\tComplete the definition of [regex_match] so that it matches\n\t\tregexes. *)\nFixpoint regex_match (s : string) (re : @reg_exp ascii) : bool\n\t(* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (regex_refl)\n\n\t\tFinally, prove that [regex_match] in fact matches regexes.\n\n\t\tHint: if your definition of [regex_match] applies [match_eps] to\n\t\tregex [re], then a natural proof applies [match_eps_refl] to [re]\n\t\tand destructs the result to generate cases in which you may assume\n\t\tthat [re] does or does not match the empty string.\n\n\t\tHint: if your definition of [regex_match] applies [derive] to\n\t\tcharacter [x] and regex [re], then a natural proof applies\n\t\t[derive_corr] to [x] and [re] to prove that [x :: s =~ re] given\n\t\t[s =~ derive x re], and vice versa. *)\nTheorem regex_refl : matches_regex regex_match.\nProof.\n\t(* FILL IN HERE *) Admitted.\n(** [] *)\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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.7653204920979572}}
{"text": "Require Import List.\nRequire Import MyTactics.\n\n(* A few random additions to the [List] module, which is woefully incomplete. *)\n\n(* -------------------------------------------------------------------------- *)\n\nLemma rev_cons_app:\n  forall {A} (x : A) xs ys,\n  rev (x :: xs) ++ ys = rev xs ++ x :: ys.\nProof.\n  intros. simpl. rewrite <- app_assoc. reflexivity.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\nLemma length_nil:\n  forall A,\n  length (@nil A) = 0.\nProof.\n  reflexivity.\nQed.\n\nLemma length_cons:\n  forall A (x : A) xs,\n  length (x :: xs) = 1 + length xs.\nProof.\n  reflexivity.\nQed.\n\nGlobal Hint Rewrite length_nil length_cons app_length map_length : length.\n\nLtac length :=\n  autorewrite with length in *;\n  try lia.\n\n(* -------------------------------------------------------------------------- *)\n\n(* We have [app_nth1] and [app_nth2], but the following lemma, which can be\n   viewed as a special case of [app_nth2], is missing. *)\n\nLemma app_nth:\n  forall {A} (xs ys : list A) x n,\n  n = length xs ->\n  nth n (xs ++ ys) x = nth 0 ys x.\nProof.\n  intros.\n  rewrite app_nth2 by lia.\n  replace (n - length xs) with 0 by lia.\n  reflexivity.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* [rev_nats n] is the semi-open interval (n, 0], counted down. *)\n\n(* It could also be defined as [rev (seq 0 n)], but a direct definition\n   is easier to work with, as it is immediately amenable to proofs by\n   induction. *)\n\nFixpoint rev_nats (n : nat) : list nat :=\n  match n with\n  | 0 =>\n      nil\n  | S n =>\n      n :: rev_nats n\n  end.\n\n(* [nats n] is the semi-open interval [0, n), counted up. *)\n\nDefinition nats (n : nat) : list nat :=\n  seq 0 n.\n\n(* These sequences have length [n]. *)\n\nLemma length_rev_nats:\n  forall n,\n  length (rev_nats n) = n.\nProof.\n  induction n; intros; simpl; [| rewrite IHn ]; eauto.\nQed.\n\nLemma length_nats:\n  forall n,\n  length (nats n) = n.\nProof.\n  unfold nats. intros. eauto using seq_length.\nQed.\n\n(* -------------------------------------------------------------------------- *)\n\n(* A few basic lemmas about [Forall]. *)\n\nLemma Forall_map:\n  forall A B (f : A -> B) (P : B -> Prop) xs,\n  Forall (fun x => P (f x)) xs ->\n  Forall P (map f xs).\nProof.\n  induction 1; intros; subst; simpl; econstructor; eauto.\nQed.\n\nLemma Forall_app:\n  forall A (P : A -> Prop) xs ys,\n  Forall P xs ->\n  Forall P ys ->\n  Forall P (xs ++ ys).\nProof.\n  induction 1; intros; subst; simpl; eauto.\nQed.\n\nLemma Forall_rev:\n  forall A (P : A -> Prop) xs,\n  Forall P xs ->\n  Forall P (rev xs).\nProof.\n  induction 1; intros; subst; simpl; eauto using Forall_app.\nQed.\n\nLemma Forall_seq:\n  forall (P : nat -> Prop) len start,\n  (forall i, start <= i < start + len -> P i) ->\n  Forall P (seq start len).\nProof.\n  induction len; intros; simpl; econstructor; eauto with lia.\nQed.\n\nLemma Forall_filter:\n  forall (P: nat -> bool) l,\n  Forall (fun x => P x = true) (filter P l).\nProof.\n  intros.\n  induction l; simpl.\n  * econstructor.\n  * remember (P a) as b.\n    induction b; [econstructor|]; auto.\nQed.\n\nLemma Forall_modus_ponms {A} {P Q: A -> Prop} {l: list A}:\n  List.Forall (fun x => P x -> Q x) l ->\n  List.Forall (fun x => P x) l ->\n  List.Forall (fun x => Q x) l.\nProof.\n  intros.\n  induction H;\n  inverts_Forall;\n  econstructor;\n  eauto.\nQed.\n\n\nLemma Forall_takewhile' {A} (P Q: A -> Prop) ts:\n  (List.Forall (fun x => P x \\/ Q x) ts) ->\n  exists ts1 ts2, ts = ts1 ++ ts2 /\\ List.Forall P ts1 /\\ List.Forall (fun x => P x \\/ Q x) ts2 /\\ (ts2 = nil \\/ exists ti ts22, ts2 = ti :: ts22 /\\ Q ti ).\nProof.\n  intros.\n  induction H.\n  * eexists nil, nil.\n    simpl.\n    repeat split; eauto.\n  * case H.\n    - (* P x, we apply induction hypothesis. *)\n      intros; unpack.\n      exists (x ::ts1), ts2.\n      simpl; subst.\n      repeat split; eauto.\n    - (* Q x, we cut here. *)\n      intros; unpack.\n      eexists nil, (x :: l).\n      simpl; subst.\n      repeat split; simpl; eauto.\nQed.\n\nLemma Forall_takewhile {A} {P Q: A -> Prop} {ts}:\n  (List.Forall (fun x => P x \\/ Q x) ts) ->\n  (List.Forall P ts) \\/ exists ts1 ti ts2, ts1 ++ ti :: ts2 = ts /\\ List.Forall P ts1 /\\ List.Forall (fun x => P x \\/ Q x) ts2 /\\ Q ti.\nProof.\n  intros.\n  destruct (@Forall_takewhile' A P Q ts H); unzip; subst.\n  - autorewrite with list; left; eauto.\n  - right.\n    rename x into ts1, x1 into ti, x2 into ts2.\n    exists ts1 ti ts2; inverts_Forall; repeat split; eauto.\nQed.\n\nLemma Forall_or_comm {A} {P Q: A -> Prop} {ts}:\n  List.Forall (fun x => P x \\/ Q x) ts ->\n  List.Forall (fun x => Q x \\/ P x) ts\n.\nProof.\n  induction 1; econstructor; unzip; eauto.\nQed.\n\nLemma specialize_Forall {A} {P: A -> Prop} (ts: list A):\n  (forall x, P x) -> List.Forall P ts.\nProof.\n  induction ts; econstructor; eauto.\nQed.\n\n(*\nThis lemma state that if we have two different ways to express a list t = as1 ++ a :: as2 = bs1 ++ b :: bs2, then there is three possibilities: \n* a is before b, hence there is a l such that bs1 = as1 ++ a :: l, and as2 = l ++ b :: bs2\n* a is after b, hence there is a l such that as1 = bs1 ++ b :: l, and bs2 = l ++ a :: as2\n* a is exactly at b, hence a = b /\\ as1 = bs1 /\\ as2 = bs2\n*)\n\n\n\n\nLemma app_inj2: forall A (l1 l2 l2': list A), \n  l1 ++ l2 = l1 ++ l2' -> l2 = l2'.\nProof.\n  induction l1; simpl; intros; injections; eauto.\nQed.\n\nLemma rev_same: forall A (l1 l2: list A),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  rewrite <- rev_involutive at 1.\n  rewrite <- rev_involutive.\n  f_equal; eauto.\nQed.\n\n\nLemma app_inj1: forall A (l1 l1' l2: list A), \n  l1 ++ l2 = l1' ++ l2 -> l1 = l1'.\nProof.\n  intros.\n  (* same as before, but with reversed lists *)\n  forwards: app_inj2 (rev l2) (rev l1) (rev l1').\n  { repeat rewrite <- rev_app_distr. now rewrite H. }\n  now eapply rev_same.\nQed.\n\nLemma split_list_left_and_right:\n  forall (A: Type)\n  (a b: A)\n  (as1 as2 bs1 bs2: list A)\n  (H: as1 ++ a :: as2 = bs1 ++ b :: bs2)\n  (i: nat)\n  (j: nat)\n  (Heqi: i = length as1)\n  (Heqj: j = length bs1)\n  (Hij: i < j),\n  {l : list A | bs1 = as1 ++ a :: l /\\ as2 = l ++ b :: bs2}\n.\nProof.\n  intros.\n  remember (firstn ((j-1) - i) as2) as l.\n    assert (Hbs1: bs1 = as1 ++ a :: l).\n    {\n      rewrite Heql.\n      rewrite <- firstn_cons.\n      replace (S (j-1-i)) with (j - i) by lia.\n      rewrite <- firstn_all2 with A j as1 by lia.\n      rewrite Heqi.\n      rewrite <- firstn_app.\n      rewrite H.\n      rewrite firstn_app.\n      rewrite <- Heqj.\n      replace (_ - _) with 0 by lia.\n      rewrite -> firstn_O, app_nil_r, Heqj, firstn_all.\n      reflexivity.\n    }\n    exists l; split.\n    - apply Hbs1.\n    - (* bs1 ++ b :: bs2 = as1 ++ a :: l ++ b :: bs2 *)\n      (* as1 ++ a :: as2 = as1 ++ a :: l ++ b :: bs2 *)\n      assert (Hfinal: bs1 ++ b :: bs2 = as1 ++ a :: l ++ b :: bs2).\n      { rewrite Hbs1.\n        repeat rewrite <- app_assoc, <- app_comm_cons.\n        f_equal. }\n      rewrite <- H in Hfinal.\n      forward app_inj2.\n      now injections.\nQed.\n\n\n(* Lemma Statement From Evelyne Contejean in SQLfs *)\n\nLemma split_list_aux:\n  forall (A: Type) (a b : A) (as1 as2 bs1 bs2: list A),\n  as1 ++ a :: as2 = bs1 ++ b :: bs2 ->\n  {l | bs1 = as1 ++ a :: l /\\ as2 = l ++ b :: bs2 } +\n  {l | as1 = bs1 ++ b :: l /\\ bs2 = l ++ a :: as2 } +\n  {a = b /\\ as1 = bs1 /\\ as2 = bs2}\n.\nProof.\n  intros.\n  (* remember (as1 ++ a :: as2) as t. *)\n  remember (length as1) as i.\n  remember (length bs1) as j.\n  forwards [[Hij|Hij]|Hij]: lt_eq_lt_dec i j.\n  * (* first case: a is before b *)\n    left; left.\n    eapply split_list_left_and_right; eauto.\n  * right. (* we only need to show that as1 = bs1. The rest will follow from H. *)\n    assert (H1: as1 = bs1).\n    { \n      (* this simply follows from the fact that as1 and bs1 are of the same length *)\n      remember (firstn i (as1 ++ a :: as2)) as l.\n      apply eq_trans with l.\n      { rewrite Heql, Heqi.\n        rewrite firstn_app.\n        replace (_ - _) with 0 by lia.\n        now rewrite firstn_O, firstn_all, app_nil_r.\n      }\n      {\n        rewrite Heql, Hij, Heqj, H.\n        rewrite firstn_app.\n        replace (_ - _) with 0 by lia.\n        now rewrite firstn_O, firstn_all, app_nil_r.\n      }\n    }\n    rewrite H1 in H; forwards: app_inj2 H; injections.\n    eauto.  \n  * left; right. (* same as the first case. *)\n    symmetry in H.\n    eapply split_list_left_and_right; eauto.\nQed.\n\nLemma split_list {A: Type} {a b : A} {as1 as2 bs1 bs2: list A} (H: as1 ++ a :: as2 = bs1 ++ b :: bs2):\nsum (a = b /\\ as1 = bs1 /\\ as2 = bs2)\n(sum {l | bs1 = as1 ++ a :: l /\\ as2 = l ++ b :: bs2 }\n{l | as1 = bs1 ++ b :: l /\\ bs2 = l ++ a :: as2 })\n.\nProof.\n  destruct split_list_aux with A a b as1 as2 bs1 bs2 as [[Hl | Hl] | Hl]; eauto.\nQed.\n\n\n(* Inversion lemma on the number of elements containing either zero, one or two elements without property P. This is used as an inversion lemma to prove  *)\n\nLemma zero_one_two {X} {P: X -> Prop}  {ts: list X}:\n  (List.Forall (fun ti => P ti \\/ ~ P ti) ts) ->\n  List.Forall P ts \\/\n  (exists ts1 ti ts2,\n    ts = ts1 ++ ti :: ts2\n    /\\ ~ (P ti)\n    /\\ List.Forall P ts1\n    /\\ List.Forall P ts2\n  ) \\/\n  (exists ts1 ti ts2 tj ts3, \n    ts = ts1 ++ ti :: ts2 ++ tj :: ts3 \n    /\\ ~ (P ti)\n    /\\ ~ (P tj)\n  ).\nProof.\n  induction 1.\n  * left; left; eauto.\n  * unzip.\n    + left; eauto.\n    + right; left. exists (@nil X) x l; eauto.\n    + right; left. exists (x::x0); repeat eexists; eauto.\n    + right; right. exists (@nil X); repeat eexists; eauto.\n    + right; right. exists (x::x0); repeat eexists; eauto.\n    + right; right. exists (x::x0); repeat eexists; eauto.\nQed.\n", "meta": {"author": "CatalaLang", "repo": "catala-formalization", "sha": "30edf137f1e250a61b46ab1aef03273d9d33b8a0", "save_path": "github-repos/coq/CatalaLang-catala-formalization", "path": "github-repos/coq/CatalaLang-catala-formalization/catala-formalization-30edf137f1e250a61b46ab1aef03273d9d33b8a0/theories/common/MyList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.7653204712968463}}
{"text": "Require Import Recdef Lia.\n\nInductive Z : Type :=\n| Pos  : nat -> Z\n| Zero : Z\n| Neg  : nat -> Z.\n\nFunction inv (k : Z) : Z :=\nmatch k with\n| Pos k' => Neg k'\n| Zero   => Zero\n| Neg k' => Pos k'\nend.\n\nFunction succ (k : Z) : Z :=\nmatch k with\n| Pos n     => Pos (S n)\n| Zero      => Pos 0\n| Neg 0     => Zero\n| Neg (S n) => Neg n\nend.\n\nFunction pred (k : Z) : Z :=\nmatch k with\n| Pos 0     => Zero\n| Pos (S n) => Pos n\n| Zero      => Neg 0\n| Neg n     => Neg (S n)\nend.\n\nFunction add (k1 k2 : Z) : Z :=\nmatch k1, k2 with\n| Zero   , _       => k2\n| _      , Zero    => k1\n| Pos k1', Pos k2' => Pos (1 + k1' + k2')\n| Pos k1', Neg k2' =>\n  match Nat.compare k1' k2' with\n  | Lt => Neg (k2' - k1' - 1)\n  | Eq => Zero\n  | Gt => Pos (k1' - k2' - 1)\n  end\n| Neg k1', Pos k2' =>\n  match Nat.compare k1' k2' with\n  | Lt => Pos (k2' - k1' - 1)\n  | Eq => Zero\n  | Gt => Neg (k1' - k2' - 1)\n  end\n| Neg k1', Neg k2' => Neg (1 + k1' + k2')\nend.\n\nDefinition size (k : Z) : nat :=\nmatch k with\n| Zero => 0\n| Pos k' => 1 + k'\n| Neg k' => 1 + k'\nend.\n\nFunction add' (k1 k2 : Z) {measure size k1} : Z :=\nmatch k1 with\n| Zero        => k2\n| Pos 0       => succ k2\n| Pos (S k1') => succ (add' (Pos k1') k2)\n| Neg 0       => pred k2\n| Neg (S k1') => pred (add' (Neg k1') k2)\nend.\nProof.\n  - intros; cbn; lia.\n  - intros; cbn; lia.\nDefined.\n\nDefinition sub (k1 k2 : Z) :=\n  add k1 (inv k2).\n\nFunction mul (k1 k2 : Z) : Z :=\nmatch k1, k2 with\n| Zero   , _       => Zero\n| _      , Zero    => Zero\n| Pos k1', Pos k2' => Pos (S k1' * S k2' - 1)\n| Pos k1', Neg k2' => Neg (S k1' * S k2' - 1)\n| Neg k1', Pos k2' => Neg (S k1' * S k2' - 1)\n| Neg k1', Neg k2' => Pos (S k1' * S k2' - 1)\nend.\n\nFunction mul' (k1 k2 : Z) {measure size k1} : Z :=\nmatch k1 with\n| Zero      => Zero\n| Pos 0     => k2\n| Pos (S n) => add' k2 (mul' (Pos n) k2)\n| Neg 0     => inv k2\n| Neg (S n) => add' (inv k2) (mul' (Neg n) k2)\nend.\nProof.\n  - intros; cbn; lia.\n  - intros; cbn; lia.\nDefined.\n\nFunction min (k1 k2 : Z) : Z :=\nmatch k1, k2 with\n| Neg n1, Neg n2 => Neg (Nat.max n1 n2)\n| Neg n1, _      => Neg n1\n| _     , Neg n2 => Neg n2\n| Zero  , _      => Zero\n| _     , Zero   => Zero\n| Pos n1, Pos n2 => Pos (Nat.min n1 n2)\nend.\n\nFunction max (k1 k2 : Z) : Z :=\nmatch k1, k2 with\n| Pos n1, Pos n2 => Pos (Nat.max n1 n2)\n| Pos _ , _      => k1\n| _     , Pos _  => k2\n| Zero  , _      => Zero\n| _     , Zero   => Zero\n| Neg n1, Neg n2 => Neg (Nat.min n1 n2)\nend.\n\nCompute add (Pos 5) (Pos 6).\nCompute add (Pos 5) (Neg 2).\nCompute add (Pos 2) (Neg 3).\nCompute add (Neg 2) (Pos 5).\nCompute add (Neg 2) (Pos 3).\n\nCompute mul (Neg 1) (Pos 1).\nCompute mul (Neg 1) (Neg 1).\n\nCompute min (Pos 5) (Pos 6).\nCompute min (Pos 5) (Neg 5).\nCompute min (Neg 5) (Neg 6).\n\nLemma inv_inv :\n  forall k : Z,\n    inv (inv k) = k.\nProof.\n  destruct k; reflexivity.\nQed.\n\nLemma inv_succ :\n  forall k : Z,\n    inv (succ k) = pred (inv k).\nProof.\n  intros k; functional induction (succ k); cbn; reflexivity.\nQed.\n\nLemma inv_pred :\n  forall k : Z,\n    inv (pred k) = succ (inv k).\nProof.\n  intros k; functional induction (pred k); cbn; reflexivity.\nQed.\n\nLemma succ_pred :\n  forall k : Z,\n    succ (pred k) = k.\nProof.\n  intros k; functional induction (pred k); cbn; reflexivity.\nQed.\n\nLemma pred_succ :\n  forall k : Z,\n    pred (succ k) = k.\nProof.\n  intros k; functional induction (succ k); cbn; reflexivity.\nQed.\n\nLemma add_Zero_l :\n  forall k : Z,\n    add Zero k = k.\nProof.\n  reflexivity.\nQed.\n\nLemma add_Zero_r :\n  forall k : Z,\n    add k Zero = k.\nProof.\n  destruct k; reflexivity.\nQed.\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)\n  ; cbn; rewrite ?add_Zero_r, 1?PeanoNat.Nat.compare_antisym, ?e1; cbn\n  ; f_equal; reflexivity + lia.\nQed.\n\nLemma add_inv :\n  forall k1 k2 : Z,\n    add (inv k1) (inv k2) = inv (add k1 k2).\nProof.\n  intros k1 k2; functional induction (add k1 k2)\n  ; cbn; rewrite ?add_Zero_r, ?e1\n  ; f_equal; reflexivity + lia.\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; functional induction (add k1 k2)\n  ; rewrite ?add_Zero_l; try reflexivity.\nAdmitted.\n\nLemma add'_inv :\n  forall k1 k2 : Z,\n    add' (inv k1) (inv k2) = inv (add' k1 k2).\nProof.\n  intros k1 k2; functional induction (add' k1 k2)\n  ; cbn; rewrite ?add'_Zero_r.\n  - reflexivity.\n  - rewrite inv_succ; reflexivity.\n  - rewrite add'_equation, inv_succ, <- IHz; cbn; reflexivity.\n  - rewrite inv_pred; reflexivity.\n  - rewrite add'_equation, inv_pred, <- IHz; cbn; reflexivity.\nQed.\n\nLemma inv_add' :\n  forall k1 k2 : Z,\n    inv (add' k1 k2) = add' (inv k1) (inv k2).\nProof.\n  intros k1 k2; rewrite add'_inv; reflexivity.\nQed.\n\nLemma add'_Zero_l :\n  forall k : Z,\n    add' Zero k = k.\nProof.\n  reflexivity.\nQed.\n\nLemma add'_Zero_r :\n  forall k : Z,\n    add' k Zero = k.\nProof.\n  destruct k as [n | | n]; cycle 1.\n  - reflexivity.\n  - induction n as [| n']; cbn.\n    + reflexivity.\n    + rewrite add'_equation, IHn'; cbn; reflexivity.\n  - induction n as [| n']; cbn.\n    + reflexivity.\n    + rewrite add'_equation, IHn'; cbn; reflexivity.\nQed.\n\nLemma add'_Pos_r :\n  forall (k : Z) (n : nat),\n    add' k (Pos n)\n      =\n    match n with\n    | 0    => succ k\n    | S n' => succ (add' k (Pos n'))\n    end.\nProof.\n  intros [m | | m] n; cbn; cycle 1.\n  - destruct n; reflexivity.\n  - induction m as [| m']; destruct n as [| n']; cbn.\n    + reflexivity.\n    + destruct n'; reflexivity.\n    + rewrite add'_equation, IHm'. destruct m'; reflexivity.\n    + rewrite !(add'_equation (Neg (S m'))), IHm', pred_succ, succ_pred; reflexivity.\n  - induction m as [| m']; destruct n as [| n']; cbn.\n    + reflexivity.\n    + reflexivity.\n    + rewrite add'_equation, IHm'; cbn; reflexivity.\n    + rewrite !(add'_equation (Pos (S m'))), IHm'; reflexivity.\nQed.\n\nLemma add'_Neg_r :\n  forall (k : Z) (n : nat),\n    add' k (Neg n)\n      =\n    match n with\n    | 0    => pred k\n    | S n' => pred (add' k (Neg n'))\n    end.\nProof.\n  intros k n.\n  rewrite <- inv_inv, inv_add' at 1; cbn.\n  rewrite add'_Pos_r.\n  destruct n.\n  - rewrite inv_succ, inv_inv; reflexivity.\n  - rewrite inv_succ, inv_add', inv_inv; cbn; 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; functional induction (succ k1); cbn.\n  - rewrite add'_equation; reflexivity.\n  - reflexivity.\n  - rewrite succ_pred; reflexivity.\n  - rewrite (add'_equation (Neg (S n))), succ_pred; 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  - rewrite pred_succ; reflexivity.\n  - rewrite (add'_equation (Pos (S n))), pred_succ; reflexivity.\n  - reflexivity.\n  - rewrite add'_equation; reflexivity.\nQed.\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).\n  - rewrite add'_Zero_r; reflexivity.\n  - rewrite add'_Pos_r; reflexivity.\n  - rewrite IHz, (add'_Pos_r k2 (S k1')); reflexivity.\n  - rewrite add'_Neg_r; reflexivity.\n  - rewrite IHz, (add'_Neg_r k2 (S k1')); 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; functional induction (add' k1 k2); cbn.\n  - reflexivity.\n  - rewrite add'_succ_l; reflexivity.\n  - rewrite add'_succ_l, IHz, (add'_equation (Pos (S k1'))); reflexivity.\n  - rewrite add'_pred_l; reflexivity.\n  - rewrite add'_pred_l, IHz, (add'_equation (Neg (S k1'))); reflexivity.\nQed.\n\nLemma sub_diag :\n  forall k : Z,\n    add' k (inv k) = Zero.\nProof.\n  intros [n | | n]; cbn; cycle 1.\n  - reflexivity.\n  - induction n as [| n']; cbn in *.\n    + reflexivity.\n    + rewrite add'_equation, add'_Pos_r, IHn', pred_succ; reflexivity.\n  - induction n as [| n']; cbn in *.\n    + reflexivity.\n    + rewrite add'_equation, add'_Neg_r, IHn', succ_pred; reflexivity.\nQed.\n\nLemma mul_Zero_r :\n  forall k : Z,\n    mul k Zero = Zero.\nProof.\n  destruct k; reflexivity.\nQed.\n\nLemma mul_comm :\n  forall k1 k2 : Z,\n    mul k1 k2 = mul k2 k1.\nProof.\n  intros k1 k2; functional induction (mul k1 k2)\n  ; cbn; rewrite ?mul_Zero_r\n  ; f_equal; reflexivity + lia.\nQed.\n\nLemma mul_assoc :\n  forall k1 k2 k3 : Z,\n    mul (mul k1 k2) k3 = mul k1 (mul k2 k3).\nProof.\n  intros k1 k2 k3; functional induction (mul k1 k2)\n  ; cbn; rewrite ?mul_Zero_r\n  ; try reflexivity\n  ; destruct k3 as [k3' | | k3']\n  ; cbn; rewrite ?mult_n_Sm\n  ; f_equal; try reflexivity.\n  all: cbn; rewrite <- ?mult_n_Sm, PeanoNat.Nat.sub_0_r.\nAbort.\n\nLemma inv_mul'_r :\n  forall k1 k2 : Z,\n    inv (mul' k1 k2) = mul' k1 (inv k2).\nProof.\n  intros k1 k2. functional induction (mul' k1 k2); cbn.\n  1-2: reflexivity.\n  - rewrite inv_add', IHz, (mul'_equation (Pos (S n))); reflexivity.\n  - reflexivity.\n  - rewrite inv_add', IHz, (mul'_equation (Neg (S n))); reflexivity.\nQed.\n\nLemma mul'_Zero_r :\n  forall k : Z,\n    mul' k Zero = Zero.\nProof.\n  destruct k as [n | | n]; cbn; cycle 1.\n  - reflexivity.\n  - induction n as [| n']; cbn.\n    + reflexivity.\n    + rewrite mul'_equation, IHn'; cbn; reflexivity.\n  - induction n as [| n']; cbn.\n    + reflexivity.\n    + rewrite mul'_equation, IHn'; cbn; reflexivity.\nQed.\n\nLemma mul'_Pos_r :\n  forall (k : Z) (n : nat),\n    mul' k (Pos n)\n      =\n    match n with\n    | 0    => k\n    | S n' => add' k (mul' k (Pos n'))\n    end.\nProof.\n  intros [m | | m] n; cycle 1.\n  - destruct n; reflexivity.\n  - induction m as [| m'].\n    + rewrite mul'_equation. destruct n; reflexivity.\n    + rewrite mul'_equation, IHm'. unfold inv. destruct n as [| n'].\n      * reflexivity.\n      * rewrite (mul'_equation (Neg (S m'))); unfold inv.\n        rewrite (add'_equation (Neg (S n'))), (add'_equation (Neg (S m'))); f_equal.\n        rewrite <- !add'_assoc, (add'_comm (Neg n') (Neg m')).\n        reflexivity.\n  - induction m as [| m'].\n    + rewrite mul'_equation. destruct n; reflexivity.\n    + rewrite mul'_equation, IHm'. destruct n as [| n'].\n      * reflexivity.\n      * rewrite (mul'_equation (Pos (S m'))); unfold inv.\n        rewrite (add'_equation (Pos (S n'))), (add'_equation (Pos (S m'))); f_equal.\n        rewrite <- !add'_assoc, (add'_comm (Pos n') (Pos m')).\n        reflexivity.\nQed.\n\nLemma mul'_Neg_r :\n  forall (k : Z) (n : nat),\n    mul' k (Neg n)\n      =\n    match n with\n    | 0    => inv k\n    | S n' => add' (inv k) (mul' k (Neg n'))\n    end.\nProof.\n  intros k n.\n  rewrite <- inv_inv, inv_mul'_r at 1; cbn.\n  rewrite mul'_Pos_r.\n  destruct n as [| n']; cbn.\n  - reflexivity.\n  - rewrite inv_add', inv_mul'_r; cbn; reflexivity.\nQed.\n\nLemma mul'_comm :\n  forall k1 k2 : Z,\n    mul' k1 k2 = mul' k2 k1.\nProof.\n  intros k1 k2; functional induction (mul' k1 k2)\n  ; cbn; rewrite ?mul'_Zero_r.\n  - reflexivity.\n  - rewrite mul'_Pos_r; reflexivity.\n  - rewrite mul'_Pos_r, IHz; reflexivity.\n  - rewrite mul'_Neg_r; reflexivity.\n  - rewrite mul'_Neg_r, IHz; reflexivity.\nQed.\n\nLemma mul'_succ_l :\n  forall k1 k2 : Z,\n    mul' (succ k1) k2 = add' k2 (mul' k1 k2).\nProof.\n  intros k1 k2.\n  functional induction (succ k1); cbn.\n  - rewrite mul'_equation; reflexivity.\n  - rewrite add'_Zero_r; reflexivity.\n  - rewrite sub_diag; reflexivity.\n  - rewrite (mul'_equation (Neg (S n))), <- add'_assoc, sub_diag; cbn; reflexivity.\nQed.\n\nLemma mul'_pred_l :\n  forall k1 k2 : Z,\n    mul' (pred k1) k2 = add' (inv k2) (mul' k1 k2).\nProof.\n  intros k1 k2.\n  functional induction (pred k1); cbn.\n  - rewrite add'_comm, sub_diag; reflexivity.\n  - rewrite (mul'_equation (Pos (S n))), <- add'_assoc, (add'_comm (inv _)), sub_diag; cbn.\n    reflexivity.\n  - rewrite add'_Zero_r; reflexivity.\n  - rewrite mul'_equation. reflexivity.\nQed.\n\nLemma mul'_add'_l :\n  forall k1 k2 k3 : Z,\n    mul' (add' k1 k2) k3 = add' (mul' k1 k3) (mul' k2 k3).\nProof.\n  intros k1 k2 k3.\n  functional induction (add' k1 k2); cbn.\n  - reflexivity.\n  - rewrite mul'_succ_l; reflexivity.\n  - rewrite mul'_succ_l, (mul'_equation (Pos (S k1'))), add'_assoc, IHz; reflexivity.\n  - rewrite mul'_pred_l; reflexivity.\n  - rewrite mul'_pred_l, (mul'_equation (Neg (S k1'))), add'_assoc, IHz; reflexivity.\nQed.\n\nLemma mul'_assoc :\n  forall k1 k2 k3 : Z,\n    mul' (mul' k1 k2) k3 = mul' k1 (mul' k2 k3).\nProof.\n  intros k1 k2 k3; functional induction (mul' k1 k2); cbn.\n  1-2: reflexivity.\n  - rewrite (mul'_equation (Pos (S n))), mul'_add'_l, IHz; reflexivity.\n  - rewrite mul'_comm, <- inv_mul'_r, mul'_comm; reflexivity.\n  - rewrite (mul'_equation (Neg (S n))), (mul'_comm k2), inv_mul'_r, (mul'_comm _ (inv _)),\n            mul'_add'_l, (mul'_comm (inv _)), IHz, (mul'_comm k2 k3).\n    reflexivity.\nQed.\n\nLemma min_comm :\n  forall k1 k2 : Z,\n    min k1 k2 = min k2 k1.\nProof.\n  intros k1 k2; functional induction (min k1 k2)\n  ; cbn; f_equal; try (reflexivity + lia).\n  - destruct k2; cbn; reflexivity + contradiction.\n  - destruct k1; cbn; reflexivity + contradiction.\n  - destruct k2; cbn; reflexivity + contradiction.\n  - destruct k1; cbn; reflexivity + contradiction.\nQed.\n\nLemma min_inv :\n  forall k1 k2 : Z,\n    min (inv k1) (inv k2) = inv (max k1 k2).\nProof.\n  intros k1 k2; functional induction (max k1 k2); cbn; f_equal.\n  - destruct k2; cbn in *; reflexivity + contradiction.\n  - destruct k1; cbn in *; reflexivity + contradiction.\n  - destruct k2; cbn in *; reflexivity + contradiction.\n  - destruct k1; cbn in *; reflexivity + contradiction.\nQed.\n\nLemma inv_min :\n  forall k1 k2 : Z,\n    inv (min k1 k2) = max (inv k1) (inv k2).\nProof.\n  intros k1 k2.\n  rewrite <- inv_inv, <- min_inv, !inv_inv.\n  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/UnaryZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7653204629059351}}
{"text": "(** * Define Group with Setoid *)\n\nRequire Import Relation_Definitions Setoid Morphisms.\nRequire Import Arith Omega.\n\n(** ** Example : define Z with two nat-s *) \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.\n\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\n(** eq' is equivalence *)\nLemma refl_eq' : reflexive _ eq'.\nProof.\nunfold reflexive. intro z. destruct z as [a b].\nunfold eq'. omega.\nQed.\nLemma sym_eq' : symmetric _ eq'.\nProof.\nunfold symmetric. intros z1 z2 H.\ndestruct z1 as [a1 b1]. destruct z2 as [a2 b2].\nunfold eq' in *. omega.\nQed.\nLemma trans_eq' : transitive _ eq'.\nProof.\nunfold transitive. intros z1 z2 z3 H12 H23.\ndestruct z1 as [a1 b1].\ndestruct z2 as [a2 b2]. destruct z3 as [a3 b3].\nunfold eq' in *. omega.\nQed.\n\n(** Z' with eq' is setoid *)\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\n(** minus' is well-defined *)\nAdd Parametric Morphism : \n  minus' with signature (eq' ==> eq') as minus'_mor.\nProof.\nintros z1 z2 H.\ndestruct z1 as [a1 b1]; destruct z2 as [a2 b2].\nunfold minus'. unfold eq' in *. omega.\nQed.\n\n(** plus' is well-defined *)\nAdd Parametric Morphism :\n  plus' with signature (eq' ==> eq' ==> eq') as plus'_mor.\nProof.\nintros x1 y1 H1 x2 y2 H2.\ndestruct x1; destruct y1; destruct x2; destruct y2.\nunfold plus; unfold eq' in *. simpl. omega.\nQed.\n\n(** Define group with decidable setoid and morphisms *) \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 : \n    forall x y:S, {eq x y} + {~(eq x y)} ;\n  inv_mor : \n    forall x y:S, eq x y -> eq (inv x) (inv y) ;\n  op_mor :\n    forall x1 y1 x2 y2:S, eq x1 y1 -> eq x2 y2 ->\n    eq (op x1 x2) (op y1 y2) ;\n  op_assoc :\n    forall x y z:S, eq (op (op x y) z) (op x (op y z)) ;\n  left_unit :\n    forall x:S, eq (op e x) x ;\n  right_unit :\n    forall x:S, eq (op x e) x ;\n  left_inv :\n    forall x:S, eq (op (inv x) x) e ;\n  right_inv :\n    forall x:S, eq (op x (inv x)) e\n}.\n\n(** Example *)\nInstance Z'_group : Group eq' (mkZ' O O) minus' plus'.\nProof.\napply Build_Group.\n        (* equiv *)\n        apply Z'_setoid.\n       (* equiv_dec *)\n       intros x y; destruct x; destruct y.\n       unfold eq'. eapply eq_nat_dec.\n      (* inv_mor *)\n      apply minus'_mor.\n     (* op_mor *)\n     intros; eapply plus'_mor; assumption.\n    (* op_assoc *)\n    intros; destruct x; destruct y; destruct z;\n    unfold plus'; unfold eq'; omega.\n   (* left_unit *)\n   intros; destruct x; unfold plus'; unfold eq'; omega.\n  (* right_unit *)\n  intros; destruct x; unfold plus'; unfold eq'; omega.\n (* left_inv *)\n intros; destruct x; unfold minus'; unfold plus'; \n unfold eq'; omega.\n(* right_inv *)\nintros; destruct x; unfold minus'; unfold plus'; \nunfold eq'; omega.\nDefined.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/group/setoid_group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7653137081083556}}
{"text": "Require Import AB.Imp9.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\n\nOpen Scope Z.\n\nModule Polynomial.\nImport Assertion_D.\n\n(** Definitions of poly *)\nDefinition poly := list Z. (* The power increases as the index goes up *)\n\nDefinition ZERO : poly := nil.\nDefinition CONSTANT : poly := 1::nil.\nDefinition LINEAR : poly := 0::1::nil.\nDefinition QUADRATIC : poly := 0::0::1::nil.\nDefinition CUBIC : poly := 0::0::0::1::nil.\n(** [] *)\n\n(** Evaluations of polynomial *)\nFixpoint poly_eval (p : poly) : Z -> Z := \n  fun z => \n    match p with\n    | nil => 0\n    | h :: t => h + z * (poly_eval t z)\n    end.\n\nOpen Scope term_scope.\nPrint aexp'.\n\nFixpoint TPower (v : logical_var) (n : nat) : term :=\n  match n with\n  | O => 1\n  | S n' => v * (TPower v n')\n  end.\n\nFixpoint poly_eval_lv (p : poly) : logical_var -> term :=\n  fun v =>\n    match p with\n    | nil => 0\n    | h :: t => h + v * (poly_eval_lv t v)\n    end.\n\nClose Scope term_scope.\n(** [] *)\n\n(** Operations of polynomial *)\nFixpoint poly_add (p1 p2 : poly) : poly :=\n  match p1, p2 with\n  | nil, nil => nil\n  | h::t, nil => h::t\n  | nil, h::t => h::t\n  | h::t, h'::t' => (h+h')::(poly_add t t')\n  end.\n\nFixpoint trim_0 (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | h :: t => match trim_0 t with\n              | nil => if Z.eq_dec h 0 then nil else h :: nil\n              | _ => h :: trim_0 t\n              end\n  end.\n\nFixpoint poly_scalar_mult (k : Z) (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | h :: t => k * h :: poly_scalar_mult k t\n  end.\n\nFixpoint poly_mult (p1 p2 : poly) : poly := \n  match p1, p2 with\n  | nil, _ => nil\n  | _, nil => nil\n  | h :: t, _ => poly_add (poly_scalar_mult h p2) (0 :: (poly_mult t p2))\n  end.\n\nNotation \"p '+++' q\" := (poly_add p q) (at level 60).\nNotation \"k ** p\" := (poly_scalar_mult k p) (at level 60).\nNotation \"p '***' q\" := (poly_mult p q) (at level 60).\n\nSection Examples.\n\nExample poly_add_eg : poly_eval ((CONSTANT +++ LINEAR) +++ (CONSTANT +++ QUADRATIC)) 2 = 8.\nProof.\n  simpl. reflexivity.\nQed.\n\nExample poly_mult_eg : poly_eval ((CONSTANT +++ LINEAR) *** (CONSTANT +++ QUADRATIC)) 2 = 15.\nProof.\n  simpl. reflexivity.\nQed.\n\nEnd Examples.\n(** [] *)\n\n(** Properties of Shorthand Notations *)\nFact CONSTANT_spec : forall z, poly_eval CONSTANT z = 1.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  reflexivity.\nQed.\n\nFact LINEAR_spec : forall z, poly_eval LINEAR z = z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  omega.\nQed.\n\nFact QUADRATIC_spec : forall z, poly_eval QUADRATIC z = z*z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  ring.\nQed.\n\nFact CUBIC_spec : forall z, poly_eval CUBIC z = z*z*z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  ring.\nQed.\n(** [] *)\n\n(** Properties of Polynomial Operations *)\nLemma poly_add_nil_l : forall p, poly_add nil p = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly_add_nil_r : forall p, poly_add p nil = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly_mult_nil_l : forall p, poly_mult nil p = nil.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_mult_nil_r : forall p, poly_mult p nil = nil.\nProof.\n  intros.\n  destruct p; auto.\nQed.\n\nLemma poly_eval_zero: forall n z,\n  poly_eval (repeat 0 n) z = 0.\nProof.\n  intros.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. omega.\nQed.\n\nTheorem poly_add_spec : forall (p1 p2 : poly) (z : Z),\n  poly_eval (poly_add p1 p2) z = poly_eval p1 z + poly_eval p2 z.\nProof.\n  intro.\n  induction p1; intros.\n  - rewrite poly_add_nil_l. simpl. reflexivity.\n  - destruct p2.\n    + simpl. omega.\n    + simpl. rewrite IHp1.\n      rewrite Z.mul_add_distr_l. omega.\nQed.\n\nTheorem poly_scalar_mult_spec : forall (k : Z) (p : poly) (z : Z),\n  poly_eval (poly_scalar_mult k p) z = k * poly_eval p z.\nProof.\n  intros.\n  induction p.\n  - simpl. rewrite Z.mul_0_r. reflexivity.\n  - simpl. rewrite IHp. ring.\nQed.\n\nTheorem poly_mult_spec : forall (p1 p2 : poly) (z : Z),\n  poly_eval (poly_mult p1 p2) z = poly_eval p1 z * poly_eval p2 z.\nProof.\n  intro.\n  induction p1; intros.\n  - auto.\n  - destruct p2.\n    + simpl. rewrite Z.mul_0_r. reflexivity.\n    + simpl.\n      rewrite poly_add_spec. rewrite IHp1.\n      rewrite poly_scalar_mult_spec. simpl.\n      ring.\nQed.\n\nTheorem trim_invar:\n  forall p z,\n  poly_eval (trim_0 p) z = poly_eval p z.\nProof.\n  intro.\n  induction p; intros.\n  - auto.\n  - simpl.\n    destruct (trim_0 p) eqn:eqp.\n    + destruct (Z.eq_dec a 0) eqn:eqa; rewrite <- IHp; simpl; omega.\n    + rewrite <- eqp in *.\n      simpl. rewrite IHp. reflexivity.\nQed.\n\nLemma poly_eval_cons : forall (p: poly) (a z : Z),\n  poly_eval (a :: p) z = a + z * (poly_eval p z).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_eval_nil : forall (z : Z),\n  poly_eval nil z = 0.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_eval_app : forall (p1 p2 : poly) (z : Z),\n  poly_eval (p1 ++ p2) z = poly_eval p1 z + (z^(Z.of_nat (length p1))) * (poly_eval p2 z).\nProof.\n  intros. induction p1.\n  - assert (Z.of_nat (Datatypes.length (nil:poly)) = 0). auto.\n    rewrite app_nil_l.\n    rewrite H. rewrite Z.pow_0_r.\n    pose proof poly_eval_nil z. rewrite H0.\n    omega.\n  - rewrite <- app_comm_cons.\n    pose proof poly_eval_cons (p1 ++ p2) a z.\n    rewrite H. clear H. rewrite IHp1.\n    rewrite Z.mul_add_distr_l.\n    assert (z * (z ^ Z.of_nat (Datatypes.length p1)) = z ^ Z.of_nat (Datatypes.length (a :: p1))).\n    {\n      pose proof Z.pow_1_r z. rewrite <- H at 1.\n      pose proof Z.pow_add_r z 1 (Z.of_nat (Datatypes.length p1)).\n      assert (0 <= 1). omega.\n      assert (0 <= Z.of_nat (Datatypes.length p1)). \n      {\n        clear IHp1 H H0 H1.\n        induction p1.\n        - simpl. omega.\n        - simpl. apply Zle_0_pos.\n      }\n      pose proof H0 H1 H2.\n      rewrite <- H3.\n      assert (1 + Z.of_nat (Datatypes.length p1) = Z.of_nat (Datatypes.length (a :: p1))).\n      {\n        clear IHp1 H H0 H1 H2 H3.\n        pose proof Nat2Z.inj_add 1 (length p1).\n        assert (Z.of_nat 1 = 1). auto.\n        rewrite <- H0.\n        rewrite <- H.\n        pose proof inj_eq (1 + (length p1)) (length (a::p1)).\n        assert ((1 + Datatypes.length p1)%nat = Datatypes.length (a :: p1)). auto.\n        omega.\n      }\n      rewrite H4.\n      omega.\n    }\n    rewrite <- H.\n    pose proof poly_eval_cons p1 a z.\n    rewrite H0.\n    rewrite Z.mul_assoc.\n    omega.\nQed.\n\nLemma poly_eval_add_zero_l: forall (p : poly) n z,\n  poly_eval (poly_add (repeat 0 n) p) z = poly_eval p z.\nProof.\n  intros.\n  rewrite poly_add_spec.\n  rewrite poly_eval_zero.\n  omega.\nQed.\n\nLemma poly_eval_add_zero_r: forall (p : poly) n z,\n  poly_eval (poly_add p (repeat 0 n)) z = poly_eval p z.\nProof.\n  intros.\n  rewrite poly_add_spec.\n  rewrite poly_eval_zero.\n  omega.\nQed.\n\nLemma poly_add_comm: forall p1 p2,\n  poly_add p1 p2 = poly_add p2 p1.\nProof.\n  intro.\n  induction p1; intros.\n  - rewrite poly_add_nil_l, poly_add_nil_r. reflexivity.\n  - destruct p2.\n    + auto.\n    + simpl.\n      rewrite IHp1.\n      rewrite Z.add_comm.\n      reflexivity.\nQed.\n(** [] *)\n\n(* Dealing with the coef *)\nFixpoint poly_coef_sum (p : poly) : Z :=\n  match p with\n  | nil => 0\n  | h::t => h + (poly_coef_sum t)\n  end.\n\nEnd Polynomial.\n\nModule Polynomial'.\nExport Polynomial.\nImport Assertion_D.\n\nDefinition poly' := list Z. (* The power decreases as the index goes up *)\n\n(** Evaluations of polynomial' *)\nFixpoint poly'_eval (p : poly') : Z -> Z :=\n  fun z =>\n    match p with\n    | nil => 0\n    | h :: t => h * (Z.pow z (Z.of_nat (length t))) + (poly'_eval t z)\n    end.\n\n(** Operations of polynomial *)\nFixpoint poly'_add_body (l1 l2 : list Z) : list Z :=\n  match l1, l2 with\n  | nil, nil => l2\n  | h::t, nil => h::t\n  | nil, h::t => h::t\n  | h::t, h'::t' => (h+h')::(poly'_add_body t t')\n  end.\n\nDefinition poly'_add (p1 p2 : poly') : poly' := rev (poly'_add_body (rev p1) (rev p2)).\n\n(** Properties of Polynomial Operations *)\nLemma poly'_add_body_empty_r : forall l, poly'_add_body l nil = l.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly'_add_empty_r : forall p, poly'_add p nil = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - unfold poly'_add.\n    rewrite poly'_add_body_empty_r.\n    apply rev_involutive.\nQed.\n\nLemma poly'_add_body_empty_l : forall l, poly'_add_body nil l = l.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly'_add_empty_l : forall p, poly'_add nil p = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - unfold poly'_add.\n    rewrite poly'_add_body_empty_l.\n    apply rev_involutive.\nQed.\n\nLemma poly'_eval_0s: forall times n,\n  poly'_eval (repeat 0 times) n = 0.\nProof.\n  intros.\n  induction times.\n  - simpl. reflexivity.\n  - simpl. omega.\nQed.\n\nLemma poly'_cons_eval_comm : forall p z n,\n  poly'_eval (cons z p) n = poly'_eval (cons z (repeat 0 (length p))) n + poly'_eval p n.\nProof.\n  intros.\n  simpl.\n  assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n  { induction p.\n    - simpl. reflexivity.\n    - simpl. rewrite IHp. reflexivity.\n  }\n  rewrite H.\n  pose proof poly'_eval_0s (Datatypes.length p) n.\n  rewrite H0.\n  omega.\nQed.\n\nLemma poly'_app_eval_comm: forall p1 p2 n,\n  poly'_eval (p1 ++ p2) n = poly'_eval (p1 ++ (repeat 0 (length p2))) n + poly'_eval p2 n.\nProof.\n  intros.\n  induction p1.\n  - simpl.\n    pose proof app_nil_l p2.\n    rewrite <- H. simpl.\n    pose proof poly'_eval_0s (Datatypes.length p2) n.\n    rewrite H0.\n    omega.\n  - pose proof poly'_cons_eval_comm.\n    simpl.\n    assert (Datatypes.length (p1 ++ repeat 0 (Datatypes.length p2)) = Datatypes.length (p1 ++ p2)).\n    { clear IHp1 H.\n      Search (length (_ ++ _)).\n      assert (Datatypes.length (repeat 0%Z (Datatypes.length p2)) = Datatypes.length p2).\n      { induction p2.\n        - simpl. reflexivity.\n        - simpl. rewrite IHp2. reflexivity.\n      }\n      pose proof app_length p1 p2.\n      rewrite H0. \n      pose proof app_length p1 (repeat 0 (Datatypes.length p2)).\n      rewrite H1.\n      rewrite H.\n      omega.\n    }\n    rewrite H0.\n    rewrite IHp1.\n    omega.\nQed.\n\nLemma poly'_eval_repeat_length_p: forall a (p : poly') z,\n  poly'_eval (a :: repeat 0 (length p)) z = a * z ^ (Z.of_nat (length p)).\nProof.\n  intros.\n  simpl.\n  pose proof poly'_eval_0s (length p) z.\n  rewrite H.\n  pose proof repeat_length 0 (length p).\n  rewrite H0.\n  omega.\nQed.\n\nTheorem poly'_eval_poly_eval: forall (p : poly') n,\n  poly'_eval p n = poly_eval (rev p) n.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - simpl. \n    pose proof poly_eval_app (rev p) (a::nil) n.\n    rewrite H. simpl. clear H.\n    rewrite IHp.\n    pose proof rev_length p.\n    rewrite H.\n    assert (a + n * 0 = a). { omega. }\n    rewrite H0.\n    rewrite Z.mul_comm.\n    omega.\nQed.\n\nTheorem poly_eval_poly'_eval: forall (p : poly) n,\n  poly_eval p n = poly'_eval (rev p) n.\nProof.\n  intros.\n  pose proof poly'_eval_poly_eval (rev p) n.\n  rewrite rev_involutive in H.\n  omega.\nQed.\n\nEnd Polynomial'.\n\nModule WZY_Poly_Enhance.\nExport Polynomial.\n\nInductive list_le : poly -> poly -> Prop :=\n  | nil_le : list_le nil nil\n  | cons_le : forall p1 p2 a1 a2,\n              length p1 = length p2 ->\n              a1 <= a2 ->\n              list_le p1 p2 ->\n              list_le (a1 :: p1) (a2 :: p2).\n\nEnd WZY_Poly_Enhance.\n\nModule Monomial.\nExport Polynomial.\nExport Polynomial'.\nExport WZY_Poly_Enhance.\n\nFixpoint poly_get_last (p : poly) : Z := \n  match p with\n  | nil => 0\n  | a::nil => a\n  | h::t => poly_get_last t\n  end.\n\nFact poly_app_nonnil: forall (p : poly) a, (p ++ a::nil) <> nil.\nProof.\n  intros. unfold not. intros.\n  induction p.\n  - inversion H; subst.\n  - inversion H; subst.\nQed.\n\nFact poly_get_last_app: forall (p : poly) a,\n  poly_get_last (p ++ a::nil) = a.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - pose proof poly_app_nonnil p a.\n    simpl. \n    destruct (p ++ a ::nil).\n    + unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. }\n      pose proof H H0. destruct H1.\n    + tauto.\nQed.\n\nFact poly_get_last_cons: forall (a h: Z) (t : poly),\n  poly_get_last (a::h::t) = poly_get_last (h::t).\nProof.\n  intros.\n  simpl. reflexivity.\nQed.\n\nFixpoint poly'_get_first (p : poly) : Z := \n  match p with\n  | nil => 0\n  | h::t => h\n  end.\n\nDefinition poly_monomialize (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | _ :: _ => (repeat 0 ((length p) - 1)) ++ (poly_get_last p)::nil\n  end.\n\nDefinition poly'_monomialize (p : poly') : poly' := \n  match p with\n  | nil => nil\n  | h :: _ => h::nil ++ (repeat 0 ((length p) - 1))\n  end.\n\nExample poly_mono_1: poly_monomialize (3::2::1::nil) = 0::0::1::nil.\nProof.\n  simpl. reflexivity.\nQed.\n\nExample poly'_mono_1: poly'_monomialize (1::2::3::nil) = 1::0::0::nil.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma poly'_eval_mono: forall (p : poly') (n : Z),\n  poly'_eval (poly'_monomialize p) n = (poly'_get_first p) * n^(Z.of_nat (length p) - 1).\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - assert (Datatypes.length p - 0 = Datatypes.length p)%nat.\n    { omega. }\n    assert (poly'_eval (poly'_monomialize (a :: p)) n = a * n ^ Z.of_nat (Datatypes.length (repeat 0 (Datatypes.length p - 0))) + poly'_eval (repeat 0 (Datatypes.length p - 0)) n).\n    { simpl. reflexivity. }\n    rewrite H0. clear H0.\n    rewrite H.\n    assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n    { clear IHp H.\n      induction p.\n      - simpl. reflexivity.\n      - simpl. rewrite IHp. reflexivity.\n    }\n    rewrite H0.\n    pose proof poly'_eval_0s (Datatypes.length p) n.\n    rewrite H1.\n    assert (poly'_get_first (a :: p) = a).\n    { simpl. reflexivity. }\n    rewrite H2.\n    assert (Z.of_nat (Datatypes.length (a :: p)) - 1 = Z.of_nat (Datatypes.length p)).\n    { assert (Datatypes.length (a :: p) = Datatypes.length p + 1)%nat.\n      { simpl. omega. }\n      rewrite H3.\n      rewrite Nat2Z.inj_add.\n      simpl. omega.\n    }\n    rewrite H3.\n    omega.\nQed.\n\nLemma poly_mono_app_1 : forall (p : poly) a,\n  poly_monomialize (p ++ a::nil) = (repeat 0 (length p)) ++ a::nil.\nProof.\n  intros.\n  pose proof poly_app_nonnil p a.\n  pose proof poly_get_last_app p a.\n  assert (length (p ++ a::nil) = length p + 1)%nat.\n  { clear H H0.\n    induction p.\n    - simpl. reflexivity.\n    - simpl. rewrite IHp. reflexivity.\n  }\n  unfold poly_monomialize. destruct (p ++ a::nil).\n  { unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. }\n    pose proof H H2. destruct H3.\n  }\n  { rewrite H0. rewrite H1.\n    assert (Datatypes.length p + 1 - 1 = Datatypes.length p)%nat.\n    { omega. }\n    rewrite H2.\n    reflexivity.\n  }\nQed.\n\nLemma poly'_mono_poly_mono : forall (p : poly') n,\n  poly_eval (poly_monomialize (rev p)) n = poly'_eval (poly'_monomialize p) n.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - simpl.\n    assert (Datatypes.length p - 0 = Datatypes.length p)%nat.\n    { omega. }\n    rewrite H.\n    assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n    { clear IHp H.\n      induction p.\n      - simpl. reflexivity.\n      - simpl. rewrite IHp. reflexivity.\n    }\n    rewrite H0.\n    pose proof poly'_eval_0s (Datatypes.length p) n.\n    rewrite H1.\n    pose proof poly_mono_app_1 (rev p) a.\n    rewrite H2.\n    rewrite rev_length.\n    { clear IHp H H0 H1 H2.\n      induction p.\n      - simpl. omega.\n      - simpl. rewrite IHp. \n        assert (n * (a * n ^ Z.of_nat (Datatypes.length p) + 0) = a * n * n ^ Z.of_nat (Datatypes.length p)).\n        { simpl. ring. }\n        rewrite H.\n        pose proof Z.pow_1_r n. rewrite <- H0 at 1. clear H0.\n        pose proof Z.pow_add_r n 1 (Z.of_nat (Datatypes.length p)).\n        assert (0 <= 1). { omega. }\n        assert ( 0 <= Z.of_nat (Datatypes.length p)). { omega. }\n        pose proof H0 H1 H2.\n        assert (a * n ^ 1 * n ^ Z.of_nat (Datatypes.length p) = a * n ^ (1 + Z.of_nat (Datatypes.length p))).\n        { rewrite H3. rewrite Z.mul_assoc. reflexivity. }\n        rewrite H4. clear H4.\n        pose proof Zpos_P_of_succ_nat (Datatypes.length p).\n        rewrite Z.pow_pos_fold.\n        rewrite H4.\n        assert (1 + Z.of_nat (Datatypes.length p) = Z.succ (Z.of_nat (Datatypes.length p))).\n        { rewrite <- Z.add_1_r.\n          rewrite Z.add_comm.\n          reflexivity.\n        }\n        rewrite H5.\n        omega.\n    }\nQed.\n\nLemma poly_mono_poly'_mono : forall (p : poly) n,\n  poly_eval (poly_monomialize p) n = poly'_eval (poly'_monomialize (rev p)) n.\nProof.\n  intros.\n  pose proof poly'_mono_poly_mono (rev p) n.\n  rewrite rev_involutive in H.\n  tauto.\nQed.\n\nLemma poly'_last_poly_first: forall (p : poly'),\n  poly_get_last (rev p) = poly'_get_first p.\nProof.\n  intros. induction p.\n  - simpl. reflexivity.\n  - simpl. pose proof poly_get_last_app (rev p) a.\n    tauto.\nQed.\n\nLemma poly_last_poly'_first: forall (p : poly),\n  poly_get_last p = poly'_get_first (rev p).\nProof.\n  intros. pose proof poly'_last_poly_first (rev p).\n  rewrite rev_involutive in H.\n  tauto.\nQed.\n\nLemma poly_eval_mono: forall (p : poly) (n : Z),\n  poly_eval (poly_monomialize p) n = (poly_get_last p) * n^(Z.of_nat (length p) - 1).\nProof.\n  intros.\n  pose proof poly_mono_poly'_mono p n. \n  rewrite H.\n  pose proof poly_last_poly'_first p.\n  rewrite H0.\n  rewrite <- rev_length.\n  pose proof poly'_eval_mono (rev p) n.\n  tauto.\nQed.\n\nFixpoint poly_get_max (p : poly) (d : Z) : Z := \n  match p with\n    | nil => d\n    | b::t => poly_get_max t (Z.max b d)\n  end.\n\nLemma poly_get_max1: forall (p : poly),\n  forall z, z <= poly_get_max p z.\nProof.\n  induction p; intros.\n  - simpl. reflexivity.\n  - simpl. \n    specialize (IHp (Z.max a z)).\n    assert (z <= Z.max a z).\n    { apply Z.le_max_r. }\n    pose proof Z.le_trans _ _ _ H IHp.\n    tauto.\nQed.\n\nLemma poly_get_max2: forall (p : poly) z1 z2,\n  z1 <= z2 ->\n  poly_get_max p z1 <= poly_get_max p z2.\nProof.\n  induction p; intros.\n  - simpl. tauto.\n  - simpl.\n    assert ( a <= z1 \\/ z1 < a).\n    { omega. }\n    destruct H0.\n    + pose proof Z.max_l _ _ H0.\n      rewrite Z.max_comm in H1.\n      rewrite H1.\n      pose proof Z.le_trans _ _ _ H0 H.\n      pose proof Z.max_l _ _ H2.\n      rewrite Z.max_comm in H3.\n      rewrite H3.\n      specialize (IHp z1 z2).\n      tauto.\n    + apply Z.lt_le_incl in H0.\n      pose proof Z.max_l _ _ H0.\n      rewrite H1.\n      assert ( a <= z2 \\/ z2 < a).\n      { omega. }\n      destruct H2.\n      * pose proof Z.max_l _ _ H2.\n        rewrite Z.max_comm in H3.\n        rewrite H3.\n        pose proof IHp a z2 H2.\n        tauto.\n      * apply Z.lt_le_incl in H2.\n        pose proof Z.max_l _ _ H2.\n        rewrite H3.\n        pose proof IHp a a.\n        pose proof Z.le_refl a.\n        tauto.\nQed.\n\nLemma poly_get_max3: forall (p : poly),\n  forall z, In z p -> z <= poly_get_max p 0.\nProof.\n  induction p; intros.\n  - simpl. inversion H.\n  - simpl.\n    assert (z <= 0 \\/ z > 0).\n    { omega. }\n    destruct H0.\n    + pose proof poly_get_max1 p 0.\n      pose proof poly_get_max2 p 0 (Z.max a 0).\n      pose proof Z.le_max_r a 0.\n      pose proof H2 H3.\n      pose proof Z.le_trans _ _ _ H0 H1.\n      pose proof Z.le_trans _ _ _ H5 H4.\n      tauto.\n    + inversion H; subst.\n      * pose proof poly_get_max1 p z.\n        pose proof poly_get_max2 p z (Z.max z 0).\n        pose proof Z.le_max_l z 0.\n        pose proof H2 H3.\n        pose proof Z.le_trans _ _ _ H1 H4.\n        tauto.\n      * specialize (IHp z).\n        pose proof IHp H1.\n        pose proof poly_get_max2 p 0 (Z.max a 0).\n        pose proof Z.le_max_r a 0.\n        pose proof H3 H4.\n        pose proof Z.le_trans _ _ _ H2 H5.\n        tauto.\nQed.\n\nLemma rev_nil : forall (l : list Z), nil = rev l -> l = nil.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - assert (length (rev (z :: l)) = length (rev (z :: l))). auto.\n    rewrite <- H in H0 at 1.\n    simpl in H0. rewrite app_length in H0.\n    simpl in H0. rewrite Nat.add_1_r in H0.\n    inversion H0.\nQed.\n\nLemma non_empty_list : forall (l : list Z),\n  l <> nil -> exists l' a, l = l' ++ a :: nil.\nProof.\n  intros.\n  remember (rev l) as rl.\n  destruct rl.\n  - apply rev_nil in Heqrl.\n    congruence.\n  - assert (rev (z :: rl) = rev (rev l)).\n    rewrite Heqrl. reflexivity.\n    simpl in H0. rewrite rev_involutive in H0.\n    exists (rev rl), z. auto.\nQed.\n\nLemma poly_get_last_spec : forall l a,\n  poly_get_last (l ++ a :: nil) = a.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    destruct (l ++ a :: nil) eqn:eq.\n    + assert (length (l ++ a :: nil) = length (l ++ a :: nil)); auto.\n      rewrite eq in H at 1.\n      simpl in H. rewrite app_length in H.\n      simpl in H. rewrite Nat.add_1_r in H.\n      inversion H.\n    + auto.\nQed.\n\nFact poly_get_last_in_poly: forall p,\n  p <> nil -> In (poly_get_last p) p.\nProof.\n  intros.\n  apply non_empty_list in H as [l' [a ?]].\n  rewrite H at 1.\n  rewrite poly_get_last_spec, H.\n  rewrite in_app_iff.\n  right. simpl. left. auto.\nQed.\n\nLemma poly_distr_coef_compare:\n  forall K (N : nat) n,\n  K > 0 ->\n  n > 0 ->\n  poly_eval ((repeat 0 (Z.to_nat (Z.of_nat N-1))) ++ (K * Z.of_nat N)::nil) n >= \n  poly_eval (repeat K N) n.\nProof.\n  assert (forall N:nat, (Datatypes.length (repeat 0 N)) = N) as lem_repeat.\n  { intros. simpl.\n    induction N.\n    - simpl. reflexivity.\n    - simpl. rewrite IHN. reflexivity.\n  }\n  intros.\n  induction N.\n  - simpl. omega.\n  - pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat (S N) - 1))) (K * Z.of_nat (S N) :: nil) n.\n    rewrite H1.\n    pose proof poly_eval_zero (Z.to_nat (Z.of_nat (S N) - 1)).\n    rewrite H2.\n    pose proof lem_repeat (Z.to_nat (Z.of_nat (S N) - 1))%nat.\n    rewrite H3.\n    pose proof Z2Nat.id (Z.of_nat (S N) - 1).\n    assert (0 <= Z.of_nat (S N) - 1).\n    { clear IHN H1 H2 H3 H4.\n      induction N. - simpl. omega.\n      - pose proof Nat2Z.inj_succ (S N).\n        rewrite H1.\n        pose proof Z.le_succ_diag_r (Z.of_nat (S N)).\n        omega.\n    }\n    pose proof H4 H5.\n    rewrite H6.\n    assert (poly_eval (K * Z.of_nat (S N) :: nil) n = K * Z.of_nat (S N)).\n    { simpl. omega. }\n    rewrite H7.\n    rewrite Z.add_0_l.\n    assert (S N = N + 1)%nat. { omega. }\n    rewrite H8.\n    assert (Z.of_nat (N + 1) - 1 = Z.of_nat N).\n    { pose proof Nat2Z.inj_sub (N+1) 1.\n      assert (1 <= N + 1)%nat. omega.\n      pose proof H9 H10. simpl in H11.\n      assert (N+1-1=N)%nat. omega.\n      rewrite H12 in H11.\n      omega.\n    }\n    rewrite H9.\n    \n    clear H1 H2 H3 H4 H5 H6 H7 H8 H9.\n    pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat N - 1))) (K * Z.of_nat N :: nil) n.\n    rewrite H1 in IHN.\n    pose proof poly_eval_zero (Z.to_nat (Z.of_nat N - 1)) n.\n    rewrite H2 in IHN.\n    pose proof lem_repeat (Z.to_nat (Z.of_nat N - 1))%nat.\n    rewrite H3 in IHN.\n    assert (poly_eval (K * Z.of_nat N :: nil) n = K * Z.of_nat N).\n    { simpl. omega. }\n    rewrite H4 in IHN.\n    rewrite Z.add_0_l in IHN.\n    assert (Z.to_nat (Z.of_nat N - 1) = N - 1)%nat.\n    { pose proof Nat2Z.id N.\n      pose proof Z2Nat.inj_sub (Z.of_nat N) 1.\n      assert (0<=1). omega. pose proof H6 H7.\n      rewrite H5 in H8.\n      assert (Z.to_nat 1 = 1)%nat. \n      { simpl. apply Pos2Nat.inj_1. }\n      rewrite H9 in H8.\n      exact H8.\n    }\n    rewrite H5 in IHN.\n    \n    clear H1 H2 H3 H4 H5.\n    assert (poly_eval (repeat K (N + 1)) n = K * n ^ (Z.of_nat N) + poly_eval (repeat K N) n).\n    { clear IHN.\n      induction N.\n      - simpl. omega.\n      - assert (poly_eval (repeat K (S N + 1)) n = K + n * poly_eval (repeat K (S N)) n).\n        { clear IHN. simpl. induction N.\n          - simpl. omega.\n          - simpl. rewrite IHN. omega.\n        }\n        rewrite H1.\n        assert (S N = N + 1)%nat. omega.\n        rewrite <- H2 in IHN.\n        rewrite IHN at 1.\n        rewrite Z.mul_add_distr_l.\n        assert (n * (K * n ^ Z.of_nat N) = K * n ^ (Z.of_nat (S N))).\n        { rewrite Z.mul_assoc.\n          rewrite Z.mul_shuffle0.\n          pose proof Z.pow_1_r n.\n          rewrite <- H3 at 1.\n          pose proof Z.pow_add_r n 1 (Z.of_nat N).\n          assert (0 <= 1). { omega. }\n          assert (0 <= Z.of_nat N). { omega. }\n          pose proof H4 H5 H6. rewrite <- H7.\n          assert (Z.of_nat (S N) = 1 + Z.of_nat N). \n          { pose proof Nat2Z.inj_add 1 N. \n            assert (1 + N = S N)%nat. { omega. }\n            assert (1 = Z.of_nat 1). { simpl. omega. }\n            rewrite H9 in H8.\n            rewrite <- H10 in H8.\n            tauto.\n          }\n          rewrite <- H8. \n          rewrite Z.mul_comm.\n          omega.\n        }\n        rewrite H3.\n        rewrite Z.add_assoc.\n        assert (K + K * n ^ Z.of_nat (S N) + n * poly_eval (repeat K N) n = K * n ^ Z.of_nat (S N) + (K + n * poly_eval (repeat K N) n)).\n        { omega. }\n        rewrite H4.\n        assert (K + n * poly_eval (repeat K N) n = poly_eval (repeat K (S N)) n).\n        { simpl. omega. }\n        rewrite H5.\n        omega.\n      }\n      rewrite H1.\n      assert (n ^ Z.of_nat N * (K * Z.of_nat (N + 1)) >= n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N).\n      { clear H1.\n        assert (Z.of_nat (N + 1) = Z.of_nat N + 1). \n        { pose proof Nat2Z.inj_add N 1. simpl in H1. \n          tauto.\n        }\n        rewrite H1.\n        rewrite Z.mul_add_distr_l.\n        rewrite Z.mul_add_distr_l.\n        assert (n >= 1). { omega. }\n        assert (n ^ Z.of_nat N >= n ^ Z.of_nat (N - 1)).\n        { clear IHN H1.\n          induction N.\n          - simpl. omega.\n          - assert (n ^ Z.of_nat (S N) = n * n ^ Z.of_nat N).\n            { assert (S N = N + 1)%nat. omega.\n              rewrite H1. clear H1.\n              assert (Z.of_nat (N + 1) = Z.of_nat N + 1). \n              { pose proof Nat2Z.inj_add N 1. simpl in H1. \n                tauto.\n              }\n              rewrite H1. clear H1.\n              pose proof Z.pow_add_r n (Z.of_nat N) 1.\n              assert (0 <= Z.of_nat N). omega.\n              assert (0 <= 1). omega.\n              pose proof H1 H3 H4. rewrite H5.\n              rewrite Z.pow_1_r.\n              rewrite Z.mul_comm.\n              reflexivity.\n            }\n            rewrite H1.\n            assert (S N - 1 = N)%nat. omega.\n            rewrite H3.\n            pose proof Z.le_mul_diag_r (n ^ Z.of_nat N) n.\n            assert (0 < n ^ Z.of_nat N).\n            { apply Z.pow_pos_nonneg. omega. omega. }\n            assert (1<=n). omega.\n            pose proof H4 H5.\n            apply H7 in H6.\n            rewrite Z.mul_comm in H6.\n            omega.\n        }\n        assert (n ^ Z.of_nat N * (K * 1) = K * n ^ Z.of_nat N).\n        { ring. }\n        rewrite H4.\n        apply Z.le_ge.\n        pose proof Zplus_le_compat_r (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (n ^ Z.of_nat N * (K * Z.of_nat N)) (K * n ^ Z.of_nat N).\n        assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) <= n ^ Z.of_nat N * (K * Z.of_nat N)).\n        { clear H5. \n          pose proof Z.mul_le_mono_nonneg_r (n ^ Z.of_nat (N - 1)) (n ^ Z.of_nat N) (K * Z.of_nat N).\n          assert (0 <= K * Z.of_nat N ).\n          pose proof Z.mul_nonneg_nonneg K (Z.of_nat N).\n          assert (0<=K). omega. pose proof H6 H7.\n          assert (0<=Z.of_nat N). omega. pose proof H8 H9.\n          exact H10.\n          pose proof H5 H6.\n          assert (n ^ Z.of_nat (N - 1) <= n ^ Z.of_nat N). omega.\n          tauto.\n        }\n     pose proof H5 H6.\n     tauto.\n   }\n   assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N >= K * n ^ Z.of_nat N + poly_eval (repeat K N) n).\n   { apply Z.le_ge.\n     pose proof Zplus_le_compat_l (poly_eval (repeat K N) n) (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (K * n ^ Z.of_nat N).\n     apply Z.ge_le in IHN.\n     pose proof H3 IHN. omega.\n   }\n  omega.\nQed.\n\nFact poly_mono_cons: forall a h t,\n  poly_monomialize (a :: h :: t) = 0 :: poly_monomialize (h :: t).\nProof.\n  intros.\n  simpl.\n  assert (Datatypes.length t - 0 = Datatypes.length t)%nat.\n  omega.\n  rewrite H.\n  reflexivity.\nQed.\n\nFact poly_mono_length_invar: forall p : poly,\n  length p = length (poly_monomialize p).\nProof.\n  intros.\n  induction p.\n  - simpl. omega.\n  - destruct p.\n    + simpl. reflexivity.\n    + pose proof poly_mono_cons a z p.\n      rewrite H.\n      assert (Datatypes.length (a :: z :: p) = 1 + Datatypes.length (z :: p))%nat. { simpl. omega. }\n      assert (Datatypes.length (0 :: poly_monomialize (z :: p)) = plus 1 (Datatypes.length (poly_monomialize (z :: p)))).\n      { simpl. reflexivity. }\n      rewrite H0.\n      rewrite H1.\n      f_equal.\n      omega.\nQed.\n\nDefinition term_by_term_le := list_le.\n\nLemma poly_each_coef_compare:\n  forall p1 p2,\n  length p1 = length p2 ->\n  term_by_term_le p1 p2 ->\n  forall n, 0 <= n ->\n  poly_eval p1 n <= poly_eval p2 n.\nProof.\n  intros.\n  induction H0.\n  - omega.\n  - simpl.\n    pose proof IHlist_le H0.\n    apply Z.add_le_mono; auto.\n    apply Z.mul_le_mono_nonneg_l; auto.\nQed.\n\nEnd Monomial.\n\nModule Polynomial_Asympotitic_Bound.\nExport Polynomial.\nExport Monomial.\nImport Assertion_D.\n\nInductive AsymptoticBound : Type :=\n  | BigO : poly -> logical_var -> AsymptoticBound\n  | BigOmega : poly -> logical_var -> AsymptoticBound\n  | BigTheta : poly -> logical_var -> AsymptoticBound.\n\n(* Convert asymtotic bounds to corresponding inequalities. We do not consider input with nonpositive size *)\nDefinition ab_eval (La : Lassn) (T : AsymptoticBound) (a1 a2 t : Z) : Prop :=\n  match T with\n  | BigO p n => 0 < La n ->\n                0 <= t <= a2 * (poly_eval p (La n))\n  | BigOmega p n => 0 < La n ->\n                    0 <= a1 * (poly_eval p (La n)) <= t\n  | BigTheta p n => 0 < La n ->\n                    0 <= a1 * (poly_eval p (La n)) <= t /\\ t <= a2 * (poly_eval p (La n))\n  end.\n\nReserved Notation \"T1 '=<' T2\" (at level 50, no associativity).\n\n(* loosen relationship defines equivalence between bounds *)\nInductive loosen : AsymptoticBound -> AsymptoticBound -> Prop :=\n  (* If time is bounded by Theta, it is bounded by O and Omega *)\n  | Theta2Omega : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigOmega p n\n  | Theta2O : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigO p n\n\n  (* We can relax the bound to a monomial with the same highest order term *)\n  | O_Poly2Mono : forall p n, 0 < poly_get_last p -> BigO p n =< BigO (poly_monomialize p) n\n  (* TODO: a monomial should also be able to be relaxed to polynomial with same highest order, but we did not have time to prove its soundness, thus it is not included yet *)\n\n  (* Multiplying positive constant to a bound can obtain another valid bound *)\n  | O_const : forall p a b n, 0 < a -> 0 < b ->  0 < poly_get_last p -> BigO (a ** p) n =< BigO (b ** p) n\n\n  (* A polynomial can have different forms, if they always evaulate to the same value, then bounds defined by them are equivalent *)\n  | O_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigO p1 n =< BigO p2 n\n  | Theta_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigTheta p1 n =< BigTheta p2 n\n  | Omega_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigOmega p1 n =< BigOmega p2 n\n\n  where \"T1 '=<' T2\" := (loosen T1 T2).\n\n\nEnd Polynomial_Asympotitic_Bound.\n", "meta": {"author": "BruceZoom", "repo": "PLProject-AsymptoticComplexity", "sha": "1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea", "save_path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity", "path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity/PLProject-AsymptoticComplexity-1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea/asymptotic_complexity_final/code/PolyAB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8376199633332893, "lm_q1q2_score": 0.7653136940714188}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nFail Fixpoint gcd (m n : nat) {struct m} : nat :=\n    if m is 0 then n else gcd (n %% m) m.\n(* Recursive definition of gcd is ill-formed. *)\n(* Recursive call to gcd has principal argument equal to \n\"n %% m\" instead of \"n0\". *)\n\n(*\nFixpoint gcd (h m n : nat) {struct h} : nat :=\n    if h is h.+1 then\n        if m is 0 then n else gcd h (n %% m) m\n    else 0.\n*)\n\nRequire Import Wf_nat Recdef.\nCheck lt_wf. (* well_founded lt *)\nCheck lt_wf_ind. (* forall (n : nat) (P : nat -> Prop),\n(forall n0 : nat, (forall m : nat, (m < n0)%coq_nat -> P m) -> P n0) ->\nP n *)\n\nFunction gcd (m n : nat) {wf lt m} : nat :=\n    if m is 0 then n else gcd (modn n m) m.\nProof.\n    - move=> m n m0 _. apply/ltP.\n      by rewrite ltn_mod.\n    - exact: lt_wf.\nQed.\n\nCheck gcd_equation.\nCheck gcd_ind.\nPrint gcd_terminate.\n\nRequire Import Extraction.\nExtraction gcd.\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\nSearch (_ %| _) \"dvdn\".\nCheck divn_eq. (* forall m d : nat, m = m %/ d * d + m %% d *)\nCheck dvdn_add. (* forall d m n : nat, d %| m -> d %| n -> d %| m + n *)\nCheck dvdn_mull. (* forall d m n : nat, d %| n -> d %| m * n *)\n\nTheorem gcd_divides m n : (gcd m n %| m) && (gcd m n %| n).\nProof.\n    functional induction (gcd m n).\n        by rewrite dvdn0 dvdnn.\n        move: IHn0 => /andP [HL HR].\n        apply/andP. split.\n        - exact HR.\n        - rewrite {2}(divn_eq n m).\n          apply: dvdn_add.\n          by apply: dvdn_mull.\n          exact HL.\nRestart.\n    functional induction (gcd m n).\n    by rewrite dvdn0 dvdnn.\n    move: IHn0 => /andP [HL HR].\n    apply/andP. split => //.\n    rewrite {2}(divn_eq n m).\n    apply: dvdn_add => //.\n    by apply: dvdn_mull.\nRestart.\n    functional induction (gcd m n).\n    - rewrite dvdn0. rewrite dvdnn. done.\n    - apply /andP. move :IHn0. move /andP. case.\n      split => //.\n      rewrite {2}(divn_eq n m).\n      rewrite dvdn_add => //.\n      rewrite dvdn_mull => //.\nQed.\n\nCheck addKn. (* forall n : nat, cancel (addn n) (subn^~ n) *)\nTheorem gcd_max g m n : g %| m -> g %| n -> g %| gcd m n.\nProof.\n    functional induction (gcd m n).\n        done.\n        move=> Hgm Hgn.\n        apply: (IHn0 _ Hgm).\n        rewrite (divn_eq n m) in Hgn.\n        have Hgnm: g %| n %/ m * m.\n            apply/dvdn_mull/Hgm.\n        rewrite <- (dvdn_addr _ Hgnm).\n        exact Hgn.\nRestart.\n    functional induction (gcd m n) => //.\n    move => Im. rewrite {1}(divn_eq n m) dvdn_addr.\n    - move => In. by move: In Im.\n    - by rewrite dvdn_mull.\nRestart.\n    functional induction (gcd m n) => //.\n    move => Im. rewrite {1}(divn_eq n m) dvdn_addr.\n    - move => In. by apply: IHn0.\n    - by apply: dvdn_mull.\nRestart.\n    (* addKn 使う版 *)\n    functional induction (gcd m n) => // gm gn.\n    apply: IHn0 => //.\n    rewrite -(addKn (n %/ m * m) (n %% m)) -divn_eq.\n      by rewrite dvdn_sub // dvdn_mull.\nQed.\n\nCheck odd_mul. (* forall m n : nat, odd (m * n) = odd m && odd n *)\nCheck odd_double. (* forall n : nat, odd n.*2 = false *)\nCheck odd_double_half. (* forall n: nat, odd n + n./2.*2 = n *)\nCheck andbb. (* idempotent andb *)(* forall x: bool, x && x = x *)\nCheck negbTE. (* forall b: bool, ~~ b -> b = false *)\nCheck double_inj. (* injective double *)(* forall x x2: nat, x.*2 = x2.*2 -> x = x2 *)\nCheck divn2. (* forall m: nat, m %/ 2 = m./2 *)\nCheck ltn_Pdiv. (* forall m d: nat, 1 < d -> 0 < m -> m %/ d < m *)\nCheck muln2. (* forall m: nat, m * 2 = m.*2 *)\nCheck esym. (* ?x = ?y -> ?y = ?x *)(* forall (A: Type) (x y: A), x = y -> y = x *)\n\nLemma odd_square n : odd n = odd (n*n).\nProof. by rewrite odd_mul andbb. Qed.\nLemma even_double_half n : ~~odd n -> n./2.*2 = n.\nProof.\n    move=>H.\n    rewrite -{2}(odd_double_half n) -{1}(add0n (n./2).*2).\n    apply/esym/eqP.\n    by rewrite eqn_add2r eqb0.\nRestart.\n    move=>H.\n    rewrite -{2}(odd_double_half n).\n    by rewrite (negbTE H).\nQed.\n\n(* 本定理 *)\nTheorem main_thm (n p : nat) : n * n = (p * p).*2 -> p = 0.\nProof.\n    Check posnP. (* forall n : nat, eqn0_xor_gt0 n (n == 0) (0 < n) *)\n    Print eqn0_xor_gt0.\n(*\n    Variant eqn0_xor_gt0 (n : nat) : bool -> bool -> Set :=\n\tEq0NotPos : n = 0 -> eqn0_xor_gt0 n true false\n  | PosNotEq0 : 0 < n -> eqn0_xor_gt0 n false true.\n*)\n  elim/lt_wf_ind: n p => n. (* 整礎帰納法 *)\n    case: (posnP n) => [-> _ [] // | Hn IH p Hnp].\n    have Hon : ~~odd n.\n        apply: negbT. rewrite odd_square Hnp. apply: odd_double.\n    have Hop : ~~odd p.\n        apply: negbT. rewrite odd_square. rewrite -(even_double_half _ Hon) in Hnp.\n        rewrite -muln2 mulnA [n./2*2*n./2]mulnC mulnA in Hnp.\n        rewrite !muln2 in Hnp.\n        rewrite -(double_inj Hnp).\n        apply: odd_double.\n    have Hp20: p./2 = 0 -> p = 0.\n        move => Hp2. by rewrite -double0 -Hp2 (even_double_half _ Hop).\n    apply: Hp20. apply: (IH n./2).\n    - apply/ltP. rewrite -divn2. by apply: ltn_Pdiv.\n    - rewrite -(even_double_half _ Hon) -(even_double_half _ Hop) in Hnp.\n      rewrite -!doubleMr -!doubleMl in Hnp. by apply/double_inj/double_inj.\nRestart.\n    elim/lt_wf_ind: n p => n. (* 整礎帰納法 *)\n    case: (posnP n).\n    - (* n = 0 *)\n    move=> ->.\n    move=> _.\n    move=>[].\n    + (* p = 0 *) done.\n    + (* 0 < p *) move=>n'. cbn.\n        (* 0 = ((n' + (n' * n'.+1)%Nrec)%coq_nat.*2)%Nrec.+2 -> n'.+1 = 0 *)\n        (* 0 = ... .+2 なので前提が成立しない *)\n        done.\n    - (* 0 < n *)\n    move => Hn IH p Hnp.\nRestart.\n    elim/lt_wf_ind: n p => n. (* 整礎帰納法 *)\n    case: (posnP n) => [-> _ [] // | Hn IH p Hnp].\n    have /even_double_half Hon : ~~odd n by rewrite odd_square Hnp odd_double.\n    move: Hnp.\n    rewrite -Hon -muln2 mulnAC mulnA !muln2 => /double_inj Hnp'.\n    have /even_double_half Hop : ~~odd p\n    by rewrite odd_square -Hnp' odd_double.\n    rewrite -Hop.\n    apply/eqP. rewrite double_eq0. apply/eqP.\n    apply: (IH n./2).\n    - apply/ltP. rewrite -divn2. by apply: ltn_Pdiv.\n    - apply/double_inj. by rewrite Hnp' doubleMr Hop mulnC doubleMr Hop.\nRestart.\n    elim/lt_wf_ind: n p => n. (* 整礎帰納法 *)\n    case: (posnP n) => [-> _ [] // | Hn IH p Hnp].\n    have /even_double_half Hevenn : ~~odd n by rewrite odd_square Hnp odd_double.\n    move: Hnp.\n    rewrite -Hevenn -muln2 mulnAC mulnA !muln2 => /double_inj /esym Hnp'.\n    have /even_double_half Hevenp : ~~odd p\n      by rewrite odd_square Hnp' odd_double.\n    move: Hnp'.\n    rewrite -Hevenp -muln2 mulnAC muln2 => /double_inj.\n    rewrite mulnA muln2 => /esym /IH -> //.\n    rewrite -divn2.\n    by apply/ltP/ltn_Pdiv.\nQed.\n\n(* 無理数 *)\nRequire Import Reals Field. (* 実数とそのための field タクティク *)\n\nDefinition irrational (x : R) : Prop :=\n    forall (p q : nat), q <> 0 -> x <> (INR p / INR q)%R. (* %R はringスコープ *)\nLocate \"/\".\n(* Notation \"x / y\" := (Rdiv x y) : R_scope *)\nPrint Rdiv.\n(* Rdiv = fun r1 r2 : R => (r1 * / r2)%R *)\n(* Notation \"/ x\" := (RinvImpl.Rinv x) : R_scope *)\n\nTheorem irrational_sqrt_2: irrational (sqrt (INR 2)).\nProof.\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": "yak1ex", "repo": "ssreflect_study", "sha": "a28ac45bba327df674ceedf45564d91e3fe6dc77", "save_path": "github-repos/coq/yak1ex-ssreflect_study", "path": "github-repos/coq/yak1ex-ssreflect_study/ssreflect_study-a28ac45bba327df674ceedf45564d91e3fe6dc77/ssreflect06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7653079488532956}}
{"text": "Require Import Coq.Arith.Div2.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import N_Z_nat_conversions.\nRequire Export Lia Nlia.\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    exfalso; 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; lia.\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  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 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.\nQed.\n\nTheorem pow2_N : forall n, Npow2 n = N.of_nat (pow2 n).\nProof.\n  intro n.\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 = \n    ltac:(match eval hnf in (1 mod 0) with | 0 => exact 0 | _ => exact 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. cbn 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 Nat2Z.inj_mod.\n      rewrite Nat2Z.inj_sub by lia.\n      rewrite Zdiv.Zminus_mod.\n      rewrite <-! Nat2Z.inj_mod.\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": "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/NatLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7652822794968225}}
{"text": "Require Export chapter03.\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\nModule MumbleBaz.\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\nEnd MumbleBaz.\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\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\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\n(* note: no _ arguments required... *)\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\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\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\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n  | 0 => []\n  | S m => n :: repeat n m\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. induction s as [|y ys].\n  Case \"[]\". reflexivity.\n  Case \"x :: xs\".  simpl. rewrite -> IHys. simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros. induction l as [|x xs].\n  Case \"[]\". reflexivity.\n  Case \"x :: xs\". simpl. rewrite rev_snoc. rewrite IHxs. 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 [|x xs].\n  Case \"[]\". reflexivity.\n  Case \"x :: xs\". simpl. rewrite IHxs. 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\nCheck @combine.\nEval compute in (combine [1;2] [false;false;true;true]).\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n           : (list X) * (list Y) :=\n  match l with\n  | []          => ([],[])\n  | (x, y) :: r => (x :: fst (split r), y :: snd (split r))\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  | x :: xs => Some x\n  end.\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\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\nCheck plus.\n(* ==> nat -> nat -> nat *)\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\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 | (x, y) => f x y end.\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. intros. 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. intros. destruct p as [x y]. 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\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun x => andb (evenb x) (blt_nat 7 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. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\nFixpoint partition {X : Type} (p : X -> bool) (l : list X)\n                   : list X * list X :=\n  match l with\n  | [] => ([],[])\n  | x :: xs => let (y, n) := partition p xs\n                in if p x then (x :: y, n) else (y, x :: n)\n  end.\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\nTheorem snoc_map : forall (X Y : Type) (f : X -> Y) (x : X) (xs : list X),\n  map f (snoc xs x) = snoc (map f xs) (f x).\nProof.\n  intros. induction xs as [|p ps].\n  Case \"[]\". reflexivity.\n  Case \"p :: ps\". simpl. rewrite -> IHps. 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 as [|x xs].\n  Case \"[]\". reflexivity.\n  Case \"x :: xs\". simpl. rewrite <- IHxs. rewrite <- snoc_map. 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\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\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.\nQed.\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  rewrite -> H.\n  reflexivity.\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\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros. unfold fold_length. unfold fold.\n  induction l as [|x xs].\n  Case \"[]\". reflexivity.\n  Case \"x :: xs\". simpl. rewrite -> IHxs. reflexivity.\nQed.", "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/chapter04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7652600789830243}}
{"text": "(* Proyecto 2\n   Reyes Granados Naomi Itzel\n   Árboles Binarios *)\n\nRequire Import Nat.\nRequire Import List.\nRequire Import Arith Omega.\nRequire Import PeanoNat.\nRequire Import NZAxioms NZBase Decidable OrdersTac.\nRequire Import NAxioms NProperties OrdersFacts.\n\nSection TREES.\nVariable V: Type.\n\nParameters (A:Type).\n\nDefinition nodo := V.\n\n(* Definicion de arboles binarios*)\nInductive tree: Type :=\n  | N : nodo -> tree\n  | T : tree -> tree -> tree.\n\n(* Funcion potencia*)\t\t   \nFixpoint pot n m :=\n  match m with\n  | 0 => 1\n  | S p => (n)*(pot n p)\n  end.\n\n(* Función que nos regresa el número de hojas del árbol*)\nFixpoint size (t:tree) : nat :=\n  match t with\n  | N n => 1\n  | T tr tl => (size tr) + (size tl)\n  end.\n\n(* Función que nos regresa el número de nodos internos del árbol*)\nFixpoint nsize (t:tree) : nat :=\n  match t with\n  |N n => 0\n  |T t1 t2 => (nsize t1) + (nsize t2) + 1\n  end.\n\n(* Función que nos regresa la profundidad árbol*)\nFixpoint depth (t:tree) : nat :=\n  match t with\n  |N n => 0\n  |T t1 t2 => 1 + (max (depth t1) (depth t2))\n  end.\n\n(* Función de orden superior que mapea una función f\n   a los elementos de las hojas del árbol*)\nFixpoint maptree (f: V -> V) (t:tree): tree :=\n  match t with\n  |N n => N (f n)\n  |T t1 t2 => T (maptree f t1) (maptree f t2)\n  end.\n\n(* Función de orden superior *)\nFixpoint foldbtree (f: V -> V -> V) (t:tree): V :=\n  match t with\n  |N n => n\n  |T t1 t2 => f (foldbtree f t1) (foldbtree f t2)\n  end.\n\n(* Función que nos regresa una lista con todos los\n   nodos del árbol*)  \nFixpoint subtrees (t:tree) : list (tree) :=\n  match t with\n  |N n => (N n)::nil\n  |T t1 t2 => (subtrees t1) ++ ((T t1 t2)::(subtrees t2))\n  end.\n\n(* Función que regresa la longitud de una lista*)  \nFixpoint length (l:list tree) : nat :=\n  match l with\n  |nil => 0\n  |(b::bs) => 1 + (length bs)\n  end.\n\n(* Función que nos regresa el natural más grande entre\n   dos opciones*)\nFixpoint maximo (n:nat) (m:nat) : nat:=\n  match n with\n  |0 => m\n  |S k => if (m <? (S k)) then (S k) else m\n  end.\n  \n(* Función que nos dice si un árbol es una hoja*)  \nFixpoint esHoja (t:tree): Prop:=\n  match t with\n  |N n => True\n  |T t1 t2 => False\n  end.\n\n(* Función que nos dice si un árbol no es una hoja*)\nFixpoint esInductivo (t:tree): Prop :=\n  match t with\n  |N n => False\n  |T t1 t2 => True\n  end.\n\n(* Función que nos regresa el subárbol izquierdo*)\nFixpoint sacaIzquierdo (t:tree): tree :=\n  match t with\n  |N n => N n\n  |T t1 t2 => t1\n  end.\n(* Función que nos regresa el subárbol derecho*)  \nFixpoint sacaDerecho (t:tree): tree :=\n  match t with\n  |N n => N n\n  |T t1 t2 => t2\n  end.\n\n(* Demostración de que para todo árbol al menos tiene\n   una hoja.*) \nLemma lema0: forall t:tree, 1 <= (size t).\nProof.\nintros.\ninduction t.\nsimpl.\ntrivial.\nsimpl.\nrewrite -> IHt1.\napply le_plus_l.\nQed.\n\n(* Demostación de que para todo natural a, 2^a será\n   mayor o igua a 1*)\nLemma lema01: forall a:nat, 1 <= (pot 2 a).\nProof.\nintros.\ninduction a.\nsimpl.\ntrivial.\nsimpl.\napply le_plus_trans.\napply IHa.\nQed.\n\n(*Demostracion de que 2^(s n) = (2^n) + (2^n)*)\nLemma lema04: forall n:nat, pot 2 (S n)  = (pot 2 n) + (pot 2 n).\nProof.\nintros.\ninduction n.\nsimpl.\ntrivial.\nsimpl.\nrewrite plus_assoc.\nrewrite plus_assoc.\nrewrite plus_assoc.\nrewrite plus_assoc_reverse.\nsimpl.\ntrivial.\nQed.\n\n(* Demostración de que la función length abre con la concatenación*)\nLemma lema11: forall l1 l2 : list (tree), length (l1++l2) = (length l1) + (length l2).\nProof.\nintros.\ninduction l1.\nsimpl.\ntrivial.\nsimpl.\nauto.\nQed.\n\n(* Demostracion de que el sucesor es analogo a sumarle un elemento*)\nLemma lemma10: forall n : nat, S(n) = n+1.\nProof.\nintros.\ninduction n.\nauto.\nsimpl.\nrewrite IHn.\ntrivial.\nQed.\n\n(* Demostacion de untipo de asociatividad*)\nLemma asoc: forall n m k :nat, n+(m+k)=m+(n+k).\nProof.\nintros.\ninduction n.\nsimpl.\ntrivial.\nsimpl.\nrewrite IHn.\nrewrite plus_n_Sm.\ntrivial.\nQed.\n\n(* Demostracion de neutro aditivo*)\nLemma sum0: forall n:nat, n+0 = n.\nProof.\nintros.\ninduction n.\ntrivial.\nsimpl.\nrewrite IHn.\ntrivial.\nQed.\n\n\n(* Demostración de que se cumple la propiedad size t = nsize t + 1 \n   para cualquier t árbol*)\nLemma lema1: forall t:tree, (size t) = (nsize t + 1).\nProof.\nintro.\ninduction t.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHt1.\nrewrite -> IHt2.\nrewrite plus_assoc_reverse.\nsymmetry.\nrewrite plus_assoc_reverse.\nrewrite plus_assoc_reverse.\nsimpl.\nsymmetry.\nrewrite Peano.plus_n_Sm.\nreflexivity.\nQed.\n\n(*Demostracion de que se cumple la propiedad de length (subtrees t) + 1 = 2*(size t)\n  para cualquier t árbol.*)\nLemma lema2: forall t:tree, (length (subtrees t)) + 1 = 2*(size t).\nProof.\nintros.\ninduction t.\nsimpl.\ntrivial.\nsimpl.\nrewrite lema11.\nsimpl.\nrewrite plus_assoc_reverse.\nrewrite asoc.\nrewrite IHt1.\nrewrite lemma10.\nrewrite IHt2.\nsimpl.\nrewrite sum0.\nrewrite asoc.\nrewrite plus_assoc.\nrewrite asoc.\nrewrite sum0.\nrewrite plus_assoc.\nrewrite sum0.\nrewrite plus_assoc.\nrewrite asoc.\nrewrite plus_assoc.\nrewrite plus_assoc.\ntrivial.\nQed.\n\n(* Demostración de que se cumple que para todo número que sea un sucesor \n   será mayor estricto que 0*)\nLemma lema12: forall n:nat, 0 < S n.\nProof.\nintros.\ninduction n.\nauto.\nauto.\nQed.\n\nLemma lema13: forall n m k:nat, (k < n /\\ m = k) -> m<n.\nProof.\nintros.\ndestruct H.\nrewrite H0.\napply H.\nQed.\n\n(* Demostración de que si un árbol tiene profundidad 0 entonces es una hoja*)\nLemma lemma03: forall t:tree, (depth t = 0) -> (esHoja t).\nProof.\nintro.\ninduction t.\nsimpl.\ntrivial.\nsimpl.\nintro.\ninversion H.\nQed.\n\n(* Demostración de que si un árbol tiene profundidad mayor a 0\n  entonces es un árbol con rama derecha e izquierda.*)\nLemma lema02: forall t:tree, (0 < depth t) -> (esInductivo t).\nProof.\nintro.\ninduction t.\nsimpl.\nintro.\ninversion H.\nsimpl.\nintro.\nauto.\nQed.\n\n(* Demostración de que si un árbol es una hoja\n  entonces su prfundidad es 1*)\nLemma lema05: forall t:tree, (esHoja t) -> (size t = 1).\nProof.\nintro.\ninduction t.\nsimpl.\nauto.\nsimpl.\nintro.\nabsurd (False).\ncontradict H.\napply H.\nQed.\n\n\n\n(* Este lema ayudaria a terminar la demostración del lema 4\nLemma lema14: forall n m k:nat, (1 <= k /\\ n <= m) -> 1+n <= m+k.\nintro.\nintro.\nintro.\ninduction n.\nintros.\ndestruct H.\ninduction m.\nsimpl.\napply H.\nsimpl.\n\nCasi salia :C pero ya no me dio tiempo de terminar el\nlema auxiliar anterior para el caso inductivo.\n\nLemma lema4: forall t:tree, (depth t) +1 <= (size t).\nProof.\nintros.\n(*remember (depth t).*)\ninduction t.\nsimpl.\ntrivial.\nsimpl.\ndestruct (Nat.max_dec (depth t1) (depth t2)).\nrewrite e.\nrewrite lemma10.\nrewrite plus_assoc_reverse.\nrewrite asoc.\n\nLema para ver que si es un árbol t con rama derecha e izquierda entonces\n  la altura de cada lado siempre es menor que la del arbol t. Sería ocupado\n  para demostrar el lema 3.\nLemma lema06: forall t:tree, (esInductivo t) -> ((depth (sacaIzquierdo t) < depth t) /\\ (depth (sacaDerecho t) < depth t)).\nProof.\nintro.\ninduction t.\nsimpl.\nintro.\ninversion H.\nsimpl.\nintro.\nsplit.\nunfold lt.\nsimpl.\ndestruct (Nat.max_dec (depth t1) (depth t2)).\nrewrite e.\ntrivial.\nrewrite e.\nrewrite lemma10.\nauto.\n\nEstaba en proceso, pero necesitaba mas cosas para terminar la demostración\nen lo ultimo que me quede es que necesitaba el lema anterior.\nLemma lema3: forall t: tree, size t <= pot 2 (depth t).\nintros.\nremember (depth t).\ninduction n.\nsimpl.\nassert (esHoja t).\napply lemma03.\nrewrite Heqn.\nreflexivity.\nassert (size t = 1).\napply lema05.\napply H.\nrewrite H0.\ntrivial.\nassert (esInductivo t).\napply lema02.\nrewrite <- Heqn.\napply lema12.*)\n\n\n", "meta": {"author": "NaomiReyes", "repo": "BasicosCoq", "sha": "86173446d7b92cdf5d55ce8c2631243a02b87d25", "save_path": "github-repos/coq/NaomiReyes-BasicosCoq", "path": "github-repos/coq/NaomiReyes-BasicosCoq/BasicosCoq-86173446d7b92cdf5d55ce8c2631243a02b87d25/arbolBinario.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7651485489017951}}
{"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 simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday friday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\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\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.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb2: (orb false false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb3: (orb false true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb4: (orb true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition admit {T: Type} : T. Admitted.\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 (andb b1 b2) b3.\n\nExample test_andb31: (andb3 true true true) = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof.\n  reflexivity.\nQed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof.\n\n  reflexivity.\nQed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof.\n  reflexivity.\nQed.\n\nCheck (negb).\n\nModule Playground1.\n\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.\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 O))).\nEval simpl in (minustwo 4).\n\nCheck S.\nCheck prod.\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\nExample test_evenb: (evenb 100) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint oddb (n: nat) : bool :=\n  match n with\n  | O => false\n  | S O => true\n  | S (S n') => oddb n'\n  end.\n\nExample test_oddb1: (oddb (S O)) = true.\nProof.\n  reflexivity.\nQed.\n\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof.\n  simpl. reflexivity.\nQed.\n\nModule Playground2.\n\n  Fixpoint plus (n: nat) (m: nat): nat :=\n    match n with\n    | O => m\n    | S n' => S (plus n' m)\n    end.\n\n  Eval simpl in (plus 5 4).\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  Eval simpl in (mult 3 4).\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 11 5).\n\nEnd Playground2.\n\nFixpoint exp (n m: nat): nat :=\n  match m with\n  | O => 1\n  | S m' => mult n (exp n m')\n  end.\n\nEval simpl in (exp 3 4).\n\nFixpoint factorial (n: nat): nat :=\n  match n with\n  | O => 1\n  | S n' => mult n (factorial n')\n  end.\n\nEval simpl in (factorial 3).\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\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\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\n\nDefinition blt_nat (n m : nat) : bool := 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_0_n: forall n: nat, 0 + n = n.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_0_n': forall n: nat, 0 + n = n.\nProof.\n  reflexivity.\nQed.\n\nTheorem plus_0_n'': forall n: nat, 0 + n = n.\nProof.\n  intros n.\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\nTheorem plus_id_example: forall n m: nat,\n    n = m -> n + n = m + m.\nProof.\n  intros n m 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  rewrite -> H.\n  rewrite -> H0.\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 mult_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\n  intros.\n  rewrite -> plus_1_l.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [ | n']. (* as以下は必要ではない *)\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 zero_nbeq_plus_1 : forall n: nat, beq_nat 0 (n+1) =false.\nProof.\n  intros.\n  destruct 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\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\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    rewrite <- H.\n    reflexivity.\n  Case \"b = fasle\".\n    destruct c.\n    SCase \"c = true\".\n      reflexivity.\n    SCase \"c = false\".\n      rewrite <- H. reflexivity.\nQed.      \n\nTheorem plus_0_r : forall n: nat,\n  n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = Sn'\". simpl. rewrite -> IHn'. reflexivity.  \nQed.\n\nTheorem minus_diag : forall n, minus n n = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. trivial.\nQed.\n\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\". reflexivity.\n  Case \"n = S n'\". simpl. trivial.\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\". reflexivity.\n  Case \"n = S 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  Case \"n = 0\".\n    induction m as [| m'].\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". simpl. rewrite <- IHm'. reflexivity.\n  Case \"n = S n'\".\n    induction m as [| m'].\n    SCase \"m = 0\". simpl. rewrite -> IHn'. reflexivity.\n    SCase \"m = S m'\". simpl. rewrite -> IHn'. simpl. rewrite plus_n_Sm. reflexivity.\nQed.\n\nFixpoint double (n : nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. rewrite plus_n_Sm. reflexivity.\nQed.\n\nLemma 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'].\n    reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.    \n\nTheorem beq_nat_refl: forall n : nat,\n    true = beq_nat n n.\nProof.\n  intros n.\n  induction n as [| n'].\n    reflexivity.\n    simpl. trivial.\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. reflexivity.\nQed.\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    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 (H0: n + (m + p) = (n + m) + p).\n    rewrite <- plus_assoc. reflexivity.\n  assert (H1: m + (n + p) = (m + n) + p).\n    rewrite <- plus_assoc. reflexivity.\n  rewrite H0. rewrite H1.\n  assert (H2: n + m = m + n).\n    rewrite plus_comm. reflexivity.\n  rewrite H2. reflexivity.\nQed.\n\nTheorem  mult_plus_distr_l: forall n m l: nat,\n    m * l + m * n = m * (n + l).\nProof.\n  intros n m l.\n  induction m as [| m'].\n    Case \"m = 0\". reflexivity.\n    Case \"m = S m'\".\n      simpl.\n      rewrite <- IHm'.\n      rewrite <- plus_swap.\n      rewrite <- plus_assoc.\n      rewrite <- plus_assoc.\n      rewrite <- plus_assoc.\n      reflexivity.\nQed.\n\nTheorem mult_1_r: forall n: nat,\n    n * 1 = 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 mult_comm: forall m n: nat,\n    m * n = n * m.\nProof.  \n  induction n as [| n'].\n    Case \"n = 0\". rewrite -> mult_0_r. reflexivity.\n    Case \"n = S n'\".\n      assert (H0: S n' = 1 + n'). reflexivity.\n      simpl.\n      rewrite H0.\n      rewrite <- mult_plus_distr_l.\n      rewrite plus_comm. \n      rewrite -> mult_1_r.\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    Case \"n = 0\". reflexivity.\n    Case \"n = S n'\". simpl. trivial.\nQed.\n\n\nTheorem zero_nbeq_S : forall n: nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros b.\n  destruct b.\n    Case \"b = true\". reflexivity.\n    Case \"b = false\". 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 H.\n  induction p as [| p'].\n    Case \"p = 0\". simpl. trivial.\n    Case \"p = S p'\". simpl. trivial.\nQed.\n\nTheorem S_nbeq_0 : forall n: nat,\n  beq_nat (S n) 0 = false.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_1_l : forall n: nat, 1 * n = n.\nProof.\n  intros n. rewrite <- plus_0_r. reflexivity.\nQed.  \n\nTheorem all3_spec : forall b c : bool,\n    orb (andb b c) (orb (negb b) (negb c)) = true.\nProof.\n  intros b c.\n  destruct b. destruct c.\n  reflexivity. reflexivity. 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\". reflexivity.\n    Case \"n = S n'\". simpl. rewrite IHn'. rewrite plus_assoc. reflexivity.\nQed.\n  \nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.\n  induction n as [| n'].\n    Case \"n = 0\". reflexivity.\n    Case \"n = S n'\". simpl. rewrite mult_plus_distr_r. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite <- plus_assoc. rewrite <- plus_assoc.\n  replace (n + m) with (m + n). reflexivity.\n  rewrite plus_comm. reflexivity.\nQed.\n\n\nInductive bin : Type :=\n| o : bin\n| s : bin -> bin\n| t : bin -> bin.\n\nFixpoint inc (b : bin) : bin :=\n  match b with\n  | o => t o\n  | s b' => t b'\n  | t b' => s (inc b')\n  end.\n\nEval simpl in (inc (inc (inc (inc (inc o))))).\n\nFixpoint bin_nat (b : bin) : nat :=\n  match b with\n  | o => 0\n  | s b' => bin_nat b' + bin_nat b'\n  | t b' => S (bin_nat b' + bin_nat b')\n  end.\n\nEval simpl in (bin_nat (s (t (s (t o))))).\n\nTheorem inc_comm: forall b : bin,\n    bin_nat (inc b) = S (bin_nat b).\nProof.\n  intros b.\n  induction b.\n    reflexivity.\n    reflexivity.\n    simpl. rewrite -> IHb. simpl. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nFixpoint nat_bin (n : nat) : bin :=\n  match n with\n  | O => o\n  | S n' => inc (nat_bin n')\n  end.\n\nEval simpl in nat_bin 1.\nEval simpl in nat_bin 2.\nEval simpl in nat_bin 3.\nEval simpl in nat_bin 4.\nEval simpl in nat_bin 5.\nEval simpl in nat_bin 6.\nEval simpl in nat_bin 10.\n", "meta": {"author": "derbuihan", "repo": "SF", "sha": "db9a0d262433623dd743d724f5fe2ff2af20a37a", "save_path": "github-repos/coq/derbuihan-SF", "path": "github-repos/coq/derbuihan-SF/SF-db9a0d262433623dd743d724f5fe2ff2af20a37a/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7649670689023278}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import BasicDefinitions.\nFrom Undecidability.Shared.Libs.PSL Require Import FiniteTypes.FinTypes.\nFrom Undecidability.Shared.Libs.PSL Require Import Vectors.Vectors.\nImport VectorNotations2.\n\nOpen Scope vector_scope.\n\nFixpoint all_fins (n : nat) : list (Fin.t n) :=\n  match n with\n  | 0 => nil\n  | S n => Fin.F1 :: map Fin.FS (all_fins n)\n  end.\n\n#[global]\nInstance Fin_finTypeC n : finTypeC (EqType (Fin.t n)).\nProof.\n  constructor 1 with (enum := all_fins n).\n  cbn. intros x. eapply dupfreeCount.\n  - clear x. induction n as [|n IH]; simpl; constructor.\n    + now intros [? [? ?]]%in_map_iff.\n    + apply (FinFun.Injective_map_NoDup (@Fin.FS_inj n) IH).\n  - now induction x; [left|right; apply in_map].\nDefined.\n\n(* Function that produces a list of all Vectors of length n over A *)\nFixpoint Vector_pow {X: Type} (A: list X) n {struct n} : list (Vector.t X n) :=\n  match n with\n  | 0 => [Vector.nil _]\n  | S n => concat (map (fun a => map (fun v => a:::v) (Vector_pow A n) ) A)\n  end.\n\n#[global]\nInstance Vector_finTypeC (A:finType) n: finTypeC (EqType (Vector.t A n)).\nProof.\n  exists (nodup (@eqType_dec _) ((Vector_pow (elem A) n))). cbn in *.\n  intros v. eapply dupfreeCount.\n  - eapply NoDup_nodup.\n  - apply nodup_In. induction v; cbn.\n    + eauto.\n    + eapply in_concat. eexists; split.\n      eapply in_map_iff. eexists.\n      split. reflexivity.\n      2:eapply in_map_iff. 2:eauto.\n      eapply elem_spec.\nDefined.\n      \n#[export] Hint Extern 4 (finTypeC (EqType (Vector.t _ _))) => eapply Vector_finTypeC : typeclass_instances.\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/PSL/FiniteTypes/VectorFin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7648920736879238}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra all_field.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory UnityRootTheory.\nOpen Scope ring_scope.\n\nSection PreliminaryLemmas.\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n* Preliminaries\n\nLet's extend the library on rings and algebraic numbers\nwith some easy lemmas first.\n\n** Question -2: prove that if a sum of natural numbers is 1 then one of its term is 0 and the other is 1\n\nNote that we do not consider nat but the copy of nat which is embeded\nin the algebraic numbers algC. The theorem is easy to prove for nat, so\nwe suggest you use a compatibility lemma numbers between nat and Cnat\n*)\nLemma Cnat_add_eq1 : {in Cnat &, forall x y,\n   (x + y == 1) = ((x == 1) && (y == 0)) || ((x == 0) && (y == 1))}.\nProof.\n(*D*)move=> x y /CnatP [n ->] /CnatP [m ->]; rewrite -natrD !pnatr_eq1 ?pnatr_eq0.\n(*D*)by move: n m => [|[|?]] [|[|?]].\n(*A*)Qed.\n(**\n** Question -1: The real part of product\n*)\nLemma algReM (x y : algC) : 'Re (x * y) = 'Re x * 'Re y - 'Im x * 'Im y.\nProof.\n(*D*)rewrite {1}[x]algCrect {1}[y]algCrect mulC_rect algRe_rect //;\n(*D*)by rewrite rpredD ?rpredN // rpredM // ?Creal_Re ?Creal_Im.\n(*A*)Qed.\n(**\n** Question 0: The imaginary part of product\n   (it's the same, don't do it if takes more than 5s\n*)\nLemma algImM (x y : algC) : 'Im (x * y) = 'Re x * 'Im y + 'Re y * 'Im x.\nProof.\n(*D*)rewrite {1}[x]algCrect {1}[y]algCrect mulC_rect algIm_rect //;\n(*D*)by rewrite rpredD ?rpredN // rpredM // ?Creal_Re ?Creal_Im.\n(*A*)Qed.\n\nEnd PreliminaryLemmas.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n* The ring of Gauss integers\n\n - Ref: exercices de mathematiques oraux X-ENS algebre 1\n - Exercice 3.10. ENS Lyon\n\n*)\nSection GaussIntegers.\n(**\nFirst we define a predicate for the algebraic numbers which are gauss integers.\n*)\nDefinition gaussInteger := [qualify a x | ('Re x \\in Cint) && ('Im x \\in Cint)].\n(**\n** Question 1: Prove that integers are gauss integers\n*)\nLemma Cint_GI (x : algC) : x \\in Cint -> x \\is a gaussInteger.\nProof.\n(*D*)move=> x_int; rewrite qualifE (Creal_ReP _ _) ?(Creal_ImP _ _) ?Creal_Cint //.\n(*D*)by rewrite x_int rpred0.\n(*A*)Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n** Question 2: Prove that gauss integers form a subfield\n*)\nLemma GI_subring : subring_closed gaussInteger.\nProof.\n(*D*)split => [|x y /andP[??] /andP[??]|x y /andP[??] /andP[??]].\n(*D*)- by rewrite Cint_GI.\n(*D*)- by rewrite qualifE !raddfB /= ?rpredB.\n(*D*)by rewrite qualifE algReM algImM rpredB ?rpredD // rpredM.\n(*A*)Qed.\n(**\n\nThere follows the boilerplate to use the proof GI_subring in order to\ncanonically provide a subring structure to the predicate gaussInteger.\n\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(**\n\nFinally, we define the type of Gauss Integer, as a sigma type of\nalgebraic numbers. We soon prove that this is in fact a sub type.\n\n*)\nRecord GI := GIof {\n  algGI : algC;\n  algGIP : algGI \\is a gaussInteger }.\n(** We make the defining property of GI a Hint *)\nHint Resolve algGIP.\n(**\n\nWe provide the subtype property.\n\n- This makes it possible to use the generic operator \"val\" to get an\n  algC from a Gauss Integer.\n\n*)\nCanonical GI_subType := [subType for algGI].\n(**\nWe deduce that the real and imaginary parts of a GI are integers\n*)\nLemma GIRe (x : GI) : 'Re (val x) \\in Cint.\nProof. by have /andP [] := algGIP x. Qed.\nLemma GIIm (x : GI) : 'Im (val x) \\in Cint.\nProof. by have /andP [] := algGIP x. Qed.\nHint Resolve GIRe GIIm.\n\nCanonical ReGI x := GIof (Cint_GI (GIRe x)).\nCanonical ImGI x := GIof (Cint_GI (GIIm x)).\n(**\n\nWe provide a ring structure to the type GI, using the subring\ncanonical property for the predicate gaussInteger\n\n*)\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(* Definition GI_unitRingMixin := [unitRingMixin of GI by <:]. *)\n(* Canonical GI_unitRingType := UnitRingType GI GI_unitRingMixin. *)\n(**\n\n - Now we build the unitRing and comUnitRing structure of gauss\n   integers. Contrarily to the previous structures, the operator is\n   not the same as on algebraics. Indeed the invertible algebraics are\n   not necessarily invertible gauss integers.\n\n - Hence, we define the inverse of gauss integers as follow : if the\n   algebraic inverse happens to be a gauss integer we recover the\n   proof and package it together with the element and get a gauss\n   integer, otherwise, we default to the identity.\n\n - A gauss integer is invertible if the algbraic inverse is a gauss\n   integer.\n\n*)\nDefinition invGI (x : GI) := insubd x (val x)^-1.\nDefinition unitGI := [pred x : GI | (x != 0) && ((val x)^-1 \\is a gaussInteger)].\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 3: prove a few facts in order to find a comUnitRingMixin\nfor GI, and then instantiate the interfaces of unitRingType and\ncomUnitRingType.\n\nDo only one of the following proofs.\n\n\n*)\nFact mulGIr : {in unitGI, left_inverse 1 invGI *%R}.\nProof.\n(*D*)move=> x /andP [x_neq0 xVGI]; rewrite /invGI.\n(*D*)by apply: val_inj; rewrite /= insubdK // mulVr ?unitfE.\n(*A*)Qed.\n\nFact unitGIP (x y : GI) : y * x = 1 -> unitGI x.\nProof.\n(*D*)rewrite /unitGI => /(congr1 val) /=.\n(*D*)have [-> /eqP|x_neq0] := altP (x =P 0); first by rewrite mulr0 eq_sym oner_eq0.\n(*D*)by move=> /(canRL (mulfK x_neq0)); rewrite mul1r => <- /=.\n(*A*)Qed.\n\nFact unitGI_out : {in [predC unitGI], invGI =1 id}.\nProof.\nmove=> x.\n(*D*)rewrite !inE /= /unitGI.\n(*D*)rewrite negb_and negbK => /predU1P [->|/negPf xGIF];\n(*D*)by apply: val_inj; rewrite /invGI ?val_insubd /= ?xGIF // invr0 if_same.\n(*A*)Qed.\n(*D*)\nDefinition GI_comUnitRingMixin := ComUnitRingMixin mulGIr unitGIP unitGI_out.\nCanonical GI_unitRingType := UnitRingType GI GI_comUnitRingMixin.\nCanonical GI_comUnitRingType := [comUnitRingType of GI].\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 4: Show that gauss integers are stable by conjugation.\n\n*)\nLemma conjGIE x : (x^* \\is a gaussInteger) = (x \\is a gaussInteger).\n(*A*)Proof. by rewrite ![_ \\is a _]qualifE algRe_conj algIm_conj rpredN. Qed.\n(**\n\nWe use this fact to build the conjugation of a gauss Integers\n\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(**\n\nWe now define the norm (stasm) for gauss integer, we don't need to\nspecialize it to gauss integer so we define it over algebraic numbers\ninstead.\n\n*)\nDefinition gaussNorm (x : algC) := x * x^*.\nLemma gaussNorm_val (x : GI) : gaussNorm (val x) = val (x * conjGI x).\nProof. by []. Qed.\n(**\n\n** Question 4: Show that the gaussNorm of x is the square of the complex modulus of x\n\nHint: only one rewrite with the right theorem.\n*)\nLemma gaussNormE x : gaussNorm x = `|x| ^+ 2.\n(*A*)Proof. by rewrite normCK. Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 5: Show that the gaussNorm of an gauss integer is a natural number.\n\n*)\nLemma gaussNormCnat (x : GI) : gaussNorm (val x) \\in Cnat.\n(*A*)Proof. by rewrite /gaussNorm -normCK normC2_Re_Im rpredD // Cnat_exp_even. Qed.\nHint Resolve gaussNormCnat.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 6: Show that gaussNorm is multiplicative (on all algC).\n\nHint: use morphism lemmas #<code>rmorph1</code># and #<code>rmorphM</code>#\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(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 7 (hard): Find the invertible elements of GI\n\n - This is question 1 of the CPGE exercice\n\nDo unitGI_norm1 first, and come back to side lemmas later.\n*)\n\nLemma rev_unitrPr (R : comUnitRingType) (x y : R) : x * y = 1 -> x \\is a GRing.unit.\nProof. by move=> ?; apply/unitrPr; exists y. Qed.\n\nLemma eq_algC  a b : (a == b :> algC) = ('Re a == 'Re b) && ('Im a == 'Im b).\nProof.\nrewrite -subr_eq0 [a - b]algCrect -normr_eq0 -sqrf_eq0.\nrewrite normC2_rect ?paddr_eq0 ?sqr_ge0 -?realEsqr ?Creal_Re ?Creal_Im //.\nby rewrite !sqrf_eq0 !raddfB ?subr_eq0.\nQed.\n\nLemma primitive_root_i : 4.-primitive_root 'i.\nProof.\n(*D*)have : 'i ^+ 4 = 1 by rewrite [_ ^+ (2 * 2)]exprM sqrCi -signr_odd expr0.\n(*D*)move=> /prim_order_exists [] // [//|[|[|[//|[//|//]]]]] /prim_expr_order.\n(*D*)  rewrite expr1 => /(congr1 (fun x => 'Im x)) /eqP.\n(*D*)  by rewrite algIm_i (Creal_ImP _ _) ?oner_eq0 ?rpred1.\n(*D*)by move/eqP; rewrite sqrCi eq_sym -addr_eq0 paddr_eq0 ?ler01 ?oner_eq0.\n(*A*)Qed.\n\nLemma primitive_rootX_unity (C: fieldType) n (x : C) :\n  n.-primitive_root x -> n.-unity_root =i [seq x ^+ (val k) | k <- enum 'I_n].\nProof.\n(*D*)move=> x_p y; rewrite -topredE /= unity_rootE; apply/idP/idP; last first.\n(*D*)  by move=> /mapP [k _ ->]; rewrite exprAC [x ^+ _]prim_expr_order // expr1n.\n(*D*)by move=> /eqP/(prim_rootP x_p)[k ->]; apply/mapP; exists k; rewrite ?mem_enum.\n(*A*)Qed.\n\nLemma unitGI_norm1 (a : GI) : (a \\in GRing.unit) = (val a \\in 4.-unity_root).\n(*D*)Proof. (*give trace*)\ntransitivity (gaussNorm (val a) == 1).\n  apply/idP/idP; last first.\n(*a*)    by rewrite gaussNorm_val (val_eqE _ (1 : GI)) => /eqP /rev_unitrPr.\n(*D*)  move=> /unitrPr [b /(congr1 (gaussNorm \\o val)) /=] /eqP.\n(*a*) by rewrite gaussNormM gaussNorm1 Cnat_mul_eq1 // => /andP [].\nrewrite (primitive_rootX_unity primitive_root_i).\nrewrite (map_comp (GRing.exp 'i) val) val_enum_ord /=.\nrewrite /= expr0 expr1 sqrCi exprSr sqrCi mulN1r.\nrewrite !in_cons in_nil ?orbF orbA orbAC !orbA orbAC -!orbA.\n(*D*)rewrite [val a in LHS]algCrect gaussNormE normC2_rect ?Creal_Re ?Creal_Im //.\n(*D*)rewrite Cnat_add_eq1 ?Cnat_exp_even // !sqrf_eq0 !sqrf_eq1.\n(*D*)rewrite andb_orr andb_orl -!orbA.\n(*D*)rewrite ?[val _ == _]eq_algC !raddfN /=.\n(*a*)by rewrite algRe_i algIm_i ?(Creal_ReP 1 _) ?(Creal_ImP 1 _) ?oppr0.\n(*A*)Qed.\n\nEnd GaussIntegers.\n(* End of exercices *)\n", "meta": {"author": "gares", "repo": "CWS16", "sha": "608148973a715994ebbedb0a48724f2755c7bc89", "save_path": "github-repos/coq/gares-CWS16", "path": "github-repos/coq/gares-CWS16/CWS16-608148973a715994ebbedb0a48724f2755c7bc89/exercise5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.8840392695254318, "lm_q1q2_score": 0.7648920628649285}}
{"text": "Require Import AB.Imp9.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\n\nOpen Scope Z.\n\nModule Polynomial.\nImport Assertion_D.\n\n(** Definitions of poly *)\nDefinition poly := list Z. (* The power increases as the index goes up *)\n\nDefinition ZERO : poly := nil.\nDefinition CONSTANT : poly := 1::nil.\nDefinition LINEAR : poly := 0::1::nil.\nDefinition QUADRATIC : poly := 0::0::1::nil.\nDefinition CUBIC : poly := 0::0::0::1::nil.\n(** [] *)\n\n(** Evaluations of polynomial *)\nFixpoint poly_eval (p : poly) : Z -> Z := \n  fun z => \n    match p with\n    | nil => 0\n    | h :: t => h + z * (poly_eval t z)\n    end.\n\nOpen Scope term_scope.\n(* Print aexp'. *)\n\nFixpoint TPower (v : logical_var) (n : nat) : term :=\n  match n with\n  | O => 1\n  | S n' => v * (TPower v n')\n  end.\n\nFixpoint poly_eval_lv (p : poly) : logical_var -> term :=\n  fun v =>\n    match p with\n    | nil => 0\n    | h :: t => h + v * (poly_eval_lv t v)\n    end.\n\nClose Scope term_scope.\n(** [] *)\n\n(** Operations of polynomial *)\nFixpoint poly_add (p1 p2 : poly) : poly :=\n  match p1, p2 with\n  | nil, nil => nil\n  | h::t, nil => h::t\n  | nil, h::t => h::t\n  | h::t, h'::t' => (h+h')::(poly_add t t')\n  end.\n\nFixpoint trim_0 (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | h :: t => match trim_0 t with\n              | nil => if Z.eq_dec h 0 then nil else h :: nil\n              | _ => h :: trim_0 t\n              end\n  end.\n\nFixpoint poly_scalar_mult (k : Z) (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | h :: t => k * h :: poly_scalar_mult k t\n  end.\n\nFixpoint poly_mult (p1 p2 : poly) : poly := \n  match p1, p2 with\n  | nil, _ => nil\n  | _, nil => nil\n  | h :: t, _ => poly_add (poly_scalar_mult h p2) (0 :: (poly_mult t p2))\n  end.\n\nNotation \"p '+++' q\" := (poly_add p q) (at level 60).\nNotation \"k ** p\" := (poly_scalar_mult k p) (at level 60).\nNotation \"p '***' q\" := (poly_mult p q) (at level 60).\n\nSection Examples.\n\nExample poly_add_eg : poly_eval ((CONSTANT +++ LINEAR) +++ (CONSTANT +++ QUADRATIC)) 2 = 8.\nProof.\n  simpl. reflexivity.\nQed.\n\nExample poly_mult_eg : poly_eval ((CONSTANT +++ LINEAR) *** (CONSTANT +++ QUADRATIC)) 2 = 15.\nProof.\n  simpl. reflexivity.\nQed.\n\nEnd Examples.\n(** [] *)\n\n(** Properties of Shorthand Notations *)\nFact CONSTANT_spec : forall z, poly_eval CONSTANT z = 1.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  reflexivity.\nQed.\n\nFact LINEAR_spec : forall z, poly_eval LINEAR z = z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  omega.\nQed.\n\nFact QUADRATIC_spec : forall z, poly_eval QUADRATIC z = z*z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  ring.\nQed.\n\nFact CUBIC_spec : forall z, poly_eval CUBIC z = z*z*z.\nProof.\n  intros.\n  simpl.\n  rewrite Z.mul_0_r.\n  ring.\nQed.\n(** [] *)\n\n(** Properties of Polynomial Operations *)\nLemma poly_add_nil_l : forall p, poly_add nil p = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly_add_nil_r : forall p, poly_add p nil = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly_mult_nil_l : forall p, poly_mult nil p = nil.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_mult_nil_r : forall p, poly_mult p nil = nil.\nProof.\n  intros.\n  destruct p; auto.\nQed.\n\nLemma poly_eval_zero: forall n z,\n  poly_eval (repeat 0 n) z = 0.\nProof.\n  intros.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. omega.\nQed.\n\nTheorem poly_add_spec : forall (p1 p2 : poly) (z : Z),\n  poly_eval (poly_add p1 p2) z = poly_eval p1 z + poly_eval p2 z.\nProof.\n  intro.\n  induction p1; intros.\n  - rewrite poly_add_nil_l. simpl. reflexivity.\n  - destruct p2.\n    + simpl. omega.\n    + simpl. rewrite IHp1.\n      rewrite Z.mul_add_distr_l. omega.\nQed.\n\nTheorem poly_scalar_mult_spec : forall (k : Z) (p : poly) (z : Z),\n  poly_eval (poly_scalar_mult k p) z = k * poly_eval p z.\nProof.\n  intros.\n  induction p.\n  - simpl. rewrite Z.mul_0_r. reflexivity.\n  - simpl. rewrite IHp. ring.\nQed.\n\nTheorem poly_mult_spec : forall (p1 p2 : poly) (z : Z),\n  poly_eval (poly_mult p1 p2) z = poly_eval p1 z * poly_eval p2 z.\nProof.\n  intro.\n  induction p1; intros.\n  - auto.\n  - destruct p2.\n    + simpl. rewrite Z.mul_0_r. reflexivity.\n    + simpl.\n      rewrite poly_add_spec. rewrite IHp1.\n      rewrite poly_scalar_mult_spec. simpl.\n      ring.\nQed.\n\nTheorem trim_invar:\n  forall p z,\n  poly_eval (trim_0 p) z = poly_eval p z.\nProof.\n  intro.\n  induction p; intros.\n  - auto.\n  - simpl.\n    destruct (trim_0 p) eqn:eqp.\n    + destruct (Z.eq_dec a 0) eqn:eqa; rewrite <- IHp; simpl; omega.\n    + rewrite <- eqp in *.\n      simpl. rewrite IHp. reflexivity.\nQed.\n\nLemma poly_eval_cons : forall (p: poly) (a z : Z),\n  poly_eval (a :: p) z = a + z * (poly_eval p z).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_eval_nil : forall (z : Z),\n  poly_eval nil z = 0.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nLemma poly_eval_app : forall (p1 p2 : poly) (z : Z),\n  poly_eval (p1 ++ p2) z = poly_eval p1 z + (z^(Z.of_nat (length p1))) * (poly_eval p2 z).\nProof.\n  intros. induction p1.\n  - assert (Z.of_nat (Datatypes.length (nil:poly)) = 0). auto.\n    rewrite app_nil_l.\n    rewrite H. rewrite Z.pow_0_r.\n    pose proof poly_eval_nil z. rewrite H0.\n    omega.\n  - rewrite <- app_comm_cons.\n    pose proof poly_eval_cons (p1 ++ p2) a z.\n    rewrite H. clear H. rewrite IHp1.\n    rewrite Z.mul_add_distr_l.\n    assert (z * (z ^ Z.of_nat (Datatypes.length p1)) = z ^ Z.of_nat (Datatypes.length (a :: p1))).\n    {\n      pose proof Z.pow_1_r z. rewrite <- H at 1.\n      pose proof Z.pow_add_r z 1 (Z.of_nat (Datatypes.length p1)).\n      assert (0 <= 1). omega.\n      assert (0 <= Z.of_nat (Datatypes.length p1)). \n      {\n        clear IHp1 H H0 H1.\n        induction p1.\n        - simpl. omega.\n        - simpl. apply Zle_0_pos.\n      }\n      pose proof H0 H1 H2.\n      rewrite <- H3.\n      assert (1 + Z.of_nat (Datatypes.length p1) = Z.of_nat (Datatypes.length (a :: p1))).\n      {\n        clear IHp1 H H0 H1 H2 H3.\n        pose proof Nat2Z.inj_add 1 (length p1).\n        assert (Z.of_nat 1 = 1). auto.\n        rewrite <- H0.\n        rewrite <- H.\n        pose proof inj_eq (1 + (length p1)) (length (a::p1)).\n        assert ((1 + Datatypes.length p1)%nat = Datatypes.length (a :: p1)). auto.\n        omega.\n      }\n      rewrite H4.\n      omega.\n    }\n    rewrite <- H.\n    pose proof poly_eval_cons p1 a z.\n    rewrite H0.\n    rewrite Z.mul_assoc.\n    omega.\nQed.\n\nLemma poly_eval_add_zero_l: forall (p : poly) n z,\n  poly_eval (poly_add (repeat 0 n) p) z = poly_eval p z.\nProof.\n  intros.\n  rewrite poly_add_spec.\n  rewrite poly_eval_zero.\n  omega.\nQed.\n\nLemma poly_eval_add_zero_r: forall (p : poly) n z,\n  poly_eval (poly_add p (repeat 0 n)) z = poly_eval p z.\nProof.\n  intros.\n  rewrite poly_add_spec.\n  rewrite poly_eval_zero.\n  omega.\nQed.\n\nLemma poly_add_comm: forall p1 p2,\n  poly_add p1 p2 = poly_add p2 p1.\nProof.\n  intro.\n  induction p1; intros.\n  - rewrite poly_add_nil_l, poly_add_nil_r. reflexivity.\n  - destruct p2.\n    + auto.\n    + simpl.\n      rewrite IHp1.\n      rewrite Z.add_comm.\n      reflexivity.\nQed.\n(** [] *)\n\n(* Dealing with the coef *)\nFixpoint poly_coef_sum (p : poly) : Z :=\n  match p with\n  | nil => 0\n  | h::t => h + (poly_coef_sum t)\n  end.\n\nEnd Polynomial.\n\nModule Polynomial'.\nExport Polynomial.\nImport Assertion_D.\n\nDefinition poly' := list Z. (* The power decreases as the index goes up *)\n\n(** Evaluations of polynomial' *)\nFixpoint poly'_eval (p : poly') : Z -> Z :=\n  fun z =>\n    match p with\n    | nil => 0\n    | h :: t => h * (Z.pow z (Z.of_nat (length t))) + (poly'_eval t z)\n    end.\n\n(** Operations of polynomial *)\nFixpoint poly'_add_body (l1 l2 : list Z) : list Z :=\n  match l1, l2 with\n  | nil, nil => l2\n  | h::t, nil => h::t\n  | nil, h::t => h::t\n  | h::t, h'::t' => (h+h')::(poly'_add_body t t')\n  end.\n\nDefinition poly'_add (p1 p2 : poly') : poly' := rev (poly'_add_body (rev p1) (rev p2)).\n\n(** Properties of Polynomial Operations *)\nLemma poly'_add_body_empty_r : forall l, poly'_add_body l nil = l.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly'_add_empty_r : forall p, poly'_add p nil = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - unfold poly'_add.\n    rewrite poly'_add_body_empty_r.\n    apply rev_involutive.\nQed.\n\nLemma poly'_add_body_empty_l : forall l, poly'_add_body nil l = l.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - simpl. reflexivity.\nQed.\n\nLemma poly'_add_empty_l : forall p, poly'_add nil p = p.\nProof.\n  intros.\n  destruct p.\n  - auto.\n  - unfold poly'_add.\n    rewrite poly'_add_body_empty_l.\n    apply rev_involutive.\nQed.\n\nLemma poly'_eval_0s: forall times n,\n  poly'_eval (repeat 0 times) n = 0.\nProof.\n  intros.\n  induction times.\n  - simpl. reflexivity.\n  - simpl. omega.\nQed.\n\nLemma poly'_cons_eval_comm : forall p z n,\n  poly'_eval (cons z p) n = poly'_eval (cons z (repeat 0 (length p))) n + poly'_eval p n.\nProof.\n  intros.\n  simpl.\n  assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n  { induction p.\n    - simpl. reflexivity.\n    - simpl. rewrite IHp. reflexivity.\n  }\n  rewrite H.\n  pose proof poly'_eval_0s (Datatypes.length p) n.\n  rewrite H0.\n  omega.\nQed.\n\nLemma poly'_app_eval_comm: forall p1 p2 n,\n  poly'_eval (p1 ++ p2) n = poly'_eval (p1 ++ (repeat 0 (length p2))) n + poly'_eval p2 n.\nProof.\n  intros.\n  induction p1.\n  - simpl.\n    pose proof app_nil_l p2.\n    rewrite <- H. simpl.\n    pose proof poly'_eval_0s (Datatypes.length p2) n.\n    rewrite H0.\n    omega.\n  - pose proof poly'_cons_eval_comm.\n    simpl.\n    assert (Datatypes.length (p1 ++ repeat 0 (Datatypes.length p2)) = Datatypes.length (p1 ++ p2)).\n    { clear IHp1 H.\n      assert (Datatypes.length (repeat 0%Z (Datatypes.length p2)) = Datatypes.length p2).\n      { induction p2.\n        - simpl. reflexivity.\n        - simpl. rewrite IHp2. reflexivity.\n      }\n      pose proof app_length p1 p2.\n      rewrite H0. \n      pose proof app_length p1 (repeat 0 (Datatypes.length p2)).\n      rewrite H1.\n      rewrite H.\n      omega.\n    }\n    rewrite H0.\n    rewrite IHp1.\n    omega.\nQed.\n\nLemma poly'_eval_repeat_length_p: forall a (p : poly') z,\n  poly'_eval (a :: repeat 0 (length p)) z = a * z ^ (Z.of_nat (length p)).\nProof.\n  intros.\n  simpl.\n  pose proof poly'_eval_0s (length p) z.\n  rewrite H.\n  pose proof repeat_length 0 (length p).\n  rewrite H0.\n  omega.\nQed.\n\nTheorem poly'_eval_poly_eval: forall (p : poly') n,\n  poly'_eval p n = poly_eval (rev p) n.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - simpl. \n    pose proof poly_eval_app (rev p) (a::nil) n.\n    rewrite H. simpl. clear H.\n    rewrite IHp.\n    pose proof rev_length p.\n    rewrite H.\n    assert (a + n * 0 = a). { omega. }\n    rewrite H0.\n    rewrite Z.mul_comm.\n    omega.\nQed.\n\nTheorem poly_eval_poly'_eval: forall (p : poly) n,\n  poly_eval p n = poly'_eval (rev p) n.\nProof.\n  intros.\n  pose proof poly'_eval_poly_eval (rev p) n.\n  rewrite rev_involutive in H.\n  omega.\nQed.\n\nEnd Polynomial'.\n\nModule WZY_Poly_Enhance.\nExport Polynomial.\n\nInductive list_le : poly -> poly -> Prop :=\n  | nil_le : list_le nil nil\n  | cons_le : forall p1 p2 a1 a2,\n              length p1 = length p2 ->\n              a1 <= a2 ->\n              list_le p1 p2 ->\n              list_le (a1 :: p1) (a2 :: p2).\n\nEnd WZY_Poly_Enhance.\n\nModule Monomial.\nExport Polynomial.\nExport Polynomial'.\nExport WZY_Poly_Enhance.\n\nFixpoint poly_get_last (p : poly) : Z := \n  match p with\n  | nil => 0\n  | a::nil => a\n  | h::t => poly_get_last t\n  end.\n\nFact poly_app_nonnil: forall (p : poly) a, (p ++ a::nil) <> nil.\nProof.\n  intros. unfold not. intros.\n  induction p.\n  - inversion H; subst.\n  - inversion H; subst.\nQed.\n\nFact poly_get_last_app: forall (p : poly) a,\n  poly_get_last (p ++ a::nil) = a.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - pose proof poly_app_nonnil p a.\n    simpl. \n    destruct (p ++ a ::nil).\n    + unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. }\n      pose proof H H0. destruct H1.\n    + tauto.\nQed.\n\nFact poly_get_last_cons: forall (a h: Z) (t : poly),\n  poly_get_last (a::h::t) = poly_get_last (h::t).\nProof.\n  intros.\n  simpl. reflexivity.\nQed.\n\nFixpoint poly'_get_first (p : poly) : Z := \n  match p with\n  | nil => 0\n  | h::t => h\n  end.\n\nDefinition poly_monomialize (p : poly) : poly :=\n  match p with\n  | nil => nil\n  | _ :: _ => (repeat 0 ((length p) - 1)) ++ (poly_get_last p)::nil\n  end.\n\nDefinition poly'_monomialize (p : poly') : poly' := \n  match p with\n  | nil => nil\n  | h :: _ => h::nil ++ (repeat 0 ((length p) - 1))\n  end.\n\nExample poly_mono_1: poly_monomialize (3::2::1::nil) = 0::0::1::nil.\nProof.\n  simpl. reflexivity.\nQed.\n\nExample poly'_mono_1: poly'_monomialize (1::2::3::nil) = 1::0::0::nil.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma poly'_eval_mono: forall (p : poly') (n : Z),\n  poly'_eval (poly'_monomialize p) n = (poly'_get_first p) * n^(Z.of_nat (length p) - 1).\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - assert (Datatypes.length p - 0 = Datatypes.length p)%nat.\n    { omega. }\n    assert (poly'_eval (poly'_monomialize (a :: p)) n = a * n ^ Z.of_nat (Datatypes.length (repeat 0 (Datatypes.length p - 0))) + poly'_eval (repeat 0 (Datatypes.length p - 0)) n).\n    { simpl. reflexivity. }\n    rewrite H0. clear H0.\n    rewrite H.\n    assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n    { clear IHp H.\n      induction p.\n      - simpl. reflexivity.\n      - simpl. rewrite IHp. reflexivity.\n    }\n    rewrite H0.\n    pose proof poly'_eval_0s (Datatypes.length p) n.\n    rewrite H1.\n    assert (poly'_get_first (a :: p) = a).\n    { simpl. reflexivity. }\n    rewrite H2.\n    assert (Z.of_nat (Datatypes.length (a :: p)) - 1 = Z.of_nat (Datatypes.length p)).\n    { assert (Datatypes.length (a :: p) = Datatypes.length p + 1)%nat.\n      { simpl. omega. }\n      rewrite H3.\n      rewrite Nat2Z.inj_add.\n      simpl. omega.\n    }\n    rewrite H3.\n    omega.\nQed.\n\nLemma poly_mono_app_1 : forall (p : poly) a,\n  poly_monomialize (p ++ a::nil) = (repeat 0 (length p)) ++ a::nil.\nProof.\n  intros.\n  pose proof poly_app_nonnil p a.\n  pose proof poly_get_last_app p a.\n  assert (length (p ++ a::nil) = length p + 1)%nat.\n  { clear H H0.\n    induction p.\n    - simpl. reflexivity.\n    - simpl. rewrite IHp. reflexivity.\n  }\n  unfold poly_monomialize. destruct (p ++ a::nil).\n  { unfold not in H. assert ((nil:poly) = (nil:poly)). { reflexivity. }\n    pose proof H H2. destruct H3.\n  }\n  { rewrite H0. rewrite H1.\n    assert (Datatypes.length p + 1 - 1 = Datatypes.length p)%nat.\n    { omega. }\n    rewrite H2.\n    reflexivity.\n  }\nQed.\n\nLemma poly'_mono_poly_mono : forall (p : poly') n,\n  poly_eval (poly_monomialize (rev p)) n = poly'_eval (poly'_monomialize p) n.\nProof.\n  intros.\n  induction p.\n  - simpl. reflexivity.\n  - simpl.\n    assert (Datatypes.length p - 0 = Datatypes.length p)%nat.\n    { omega. }\n    rewrite H.\n    assert (Datatypes.length (repeat 0 (Datatypes.length p)) = Datatypes.length p).\n    { clear IHp H.\n      induction p.\n      - simpl. reflexivity.\n      - simpl. rewrite IHp. reflexivity.\n    }\n    rewrite H0.\n    pose proof poly'_eval_0s (Datatypes.length p) n.\n    rewrite H1.\n    pose proof poly_mono_app_1 (rev p) a.\n    rewrite H2.\n    rewrite rev_length.\n    { clear IHp H H0 H1 H2.\n      induction p.\n      - simpl. omega.\n      - simpl. rewrite IHp. \n        assert (n * (a * n ^ Z.of_nat (Datatypes.length p) + 0) = a * n * n ^ Z.of_nat (Datatypes.length p)).\n        { simpl. ring. }\n        rewrite H.\n        pose proof Z.pow_1_r n. rewrite <- H0 at 1. clear H0.\n        pose proof Z.pow_add_r n 1 (Z.of_nat (Datatypes.length p)).\n        assert (0 <= 1). { omega. }\n        assert ( 0 <= Z.of_nat (Datatypes.length p)). { omega. }\n        pose proof H0 H1 H2.\n        assert (a * n ^ 1 * n ^ Z.of_nat (Datatypes.length p) = a * n ^ (1 + Z.of_nat (Datatypes.length p))).\n        { rewrite H3. rewrite Z.mul_assoc. reflexivity. }\n        rewrite H4. clear H4.\n        pose proof Zpos_P_of_succ_nat (Datatypes.length p).\n        rewrite Z.pow_pos_fold.\n        rewrite H4.\n        assert (1 + Z.of_nat (Datatypes.length p) = Z.succ (Z.of_nat (Datatypes.length p))).\n        { rewrite <- Z.add_1_r.\n          rewrite Z.add_comm.\n          reflexivity.\n        }\n        rewrite H5.\n        omega.\n    }\nQed.\n\nLemma poly_mono_poly'_mono : forall (p : poly) n,\n  poly_eval (poly_monomialize p) n = poly'_eval (poly'_monomialize (rev p)) n.\nProof.\n  intros.\n  pose proof poly'_mono_poly_mono (rev p) n.\n  rewrite rev_involutive in H.\n  tauto.\nQed.\n\nLemma poly'_last_poly_first: forall (p : poly'),\n  poly_get_last (rev p) = poly'_get_first p.\nProof.\n  intros. induction p.\n  - simpl. reflexivity.\n  - simpl. pose proof poly_get_last_app (rev p) a.\n    tauto.\nQed.\n\nLemma poly_last_poly'_first: forall (p : poly),\n  poly_get_last p = poly'_get_first (rev p).\nProof.\n  intros. pose proof poly'_last_poly_first (rev p).\n  rewrite rev_involutive in H.\n  tauto.\nQed.\n\nLemma poly_eval_mono: forall (p : poly) (n : Z),\n  poly_eval (poly_monomialize p) n = (poly_get_last p) * n^(Z.of_nat (length p) - 1).\nProof.\n  intros.\n  pose proof poly_mono_poly'_mono p n. \n  rewrite H.\n  pose proof poly_last_poly'_first p.\n  rewrite H0.\n  rewrite <- rev_length.\n  pose proof poly'_eval_mono (rev p) n.\n  tauto.\nQed.\n\nFixpoint poly_get_max (p : poly) (d : Z) : Z := \n  match p with\n    | nil => d\n    | b::t => poly_get_max t (Z.max b d)\n  end.\n\nLemma poly_get_max1: forall (p : poly),\n  forall z, z <= poly_get_max p z.\nProof.\n  induction p; intros.\n  - simpl. reflexivity.\n  - simpl. \n    specialize (IHp (Z.max a z)).\n    assert (z <= Z.max a z).\n    { apply Z.le_max_r. }\n    pose proof Z.le_trans _ _ _ H IHp.\n    tauto.\nQed.\n\nLemma poly_get_max2: forall (p : poly) z1 z2,\n  z1 <= z2 ->\n  poly_get_max p z1 <= poly_get_max p z2.\nProof.\n  induction p; intros.\n  - simpl. tauto.\n  - simpl.\n    assert ( a <= z1 \\/ z1 < a).\n    { omega. }\n    destruct H0.\n    + pose proof Z.max_l _ _ H0.\n      rewrite Z.max_comm in H1.\n      rewrite H1.\n      pose proof Z.le_trans _ _ _ H0 H.\n      pose proof Z.max_l _ _ H2.\n      rewrite Z.max_comm in H3.\n      rewrite H3.\n      specialize (IHp z1 z2).\n      tauto.\n    + apply Z.lt_le_incl in H0.\n      pose proof Z.max_l _ _ H0.\n      rewrite H1.\n      assert ( a <= z2 \\/ z2 < a).\n      { omega. }\n      destruct H2.\n      * pose proof Z.max_l _ _ H2.\n        rewrite Z.max_comm in H3.\n        rewrite H3.\n        pose proof IHp a z2 H2.\n        tauto.\n      * apply Z.lt_le_incl in H2.\n        pose proof Z.max_l _ _ H2.\n        rewrite H3.\n        pose proof IHp a a.\n        pose proof Z.le_refl a.\n        tauto.\nQed.\n\nLemma poly_get_max3: forall (p : poly),\n  forall z, In z p -> z <= poly_get_max p 0.\nProof.\n  induction p; intros.\n  - simpl. inversion H.\n  - simpl.\n    assert (z <= 0 \\/ z > 0).\n    { omega. }\n    destruct H0.\n    + pose proof poly_get_max1 p 0.\n      pose proof poly_get_max2 p 0 (Z.max a 0).\n      pose proof Z.le_max_r a 0.\n      pose proof H2 H3.\n      pose proof Z.le_trans _ _ _ H0 H1.\n      pose proof Z.le_trans _ _ _ H5 H4.\n      tauto.\n    + inversion H; subst.\n      * pose proof poly_get_max1 p z.\n        pose proof poly_get_max2 p z (Z.max z 0).\n        pose proof Z.le_max_l z 0.\n        pose proof H2 H3.\n        pose proof Z.le_trans _ _ _ H1 H4.\n        tauto.\n      * specialize (IHp z).\n        pose proof IHp H1.\n        pose proof poly_get_max2 p 0 (Z.max a 0).\n        pose proof Z.le_max_r a 0.\n        pose proof H3 H4.\n        pose proof Z.le_trans _ _ _ H2 H5.\n        tauto.\nQed.\n\nLemma rev_nil : forall (l : list Z), nil = rev l -> l = nil.\nProof.\n  intros.\n  destruct l.\n  - auto.\n  - assert (length (rev (z :: l)) = length (rev (z :: l))). auto.\n    rewrite <- H in H0 at 1.\n    simpl in H0. rewrite app_length in H0.\n    simpl in H0. rewrite Nat.add_1_r in H0.\n    inversion H0.\nQed.\n\nLemma non_empty_list : forall (l : list Z),\n  l <> nil -> exists l' a, l = l' ++ a :: nil.\nProof.\n  intros.\n  remember (rev l) as rl.\n  destruct rl.\n  - apply rev_nil in Heqrl.\n    congruence.\n  - assert (rev (z :: rl) = rev (rev l)).\n    rewrite Heqrl. reflexivity.\n    simpl in H0. rewrite rev_involutive in H0.\n    exists (rev rl), z. auto.\nQed.\n\nLemma poly_get_last_spec : forall l a,\n  poly_get_last (l ++ a :: nil) = a.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    destruct (l ++ a :: nil) eqn:eq.\n    + assert (length (l ++ a :: nil) = length (l ++ a :: nil)); auto.\n      rewrite eq in H at 1.\n      simpl in H. rewrite app_length in H.\n      simpl in H. rewrite Nat.add_1_r in H.\n      inversion H.\n    + auto.\nQed.\n\nFact poly_get_last_in_poly: forall p,\n  p <> nil -> In (poly_get_last p) p.\nProof.\n  intros.\n  apply non_empty_list in H as [l' [a ?]].\n  rewrite H at 1.\n  rewrite poly_get_last_spec, H.\n  rewrite in_app_iff.\n  right. simpl. left. auto.\nQed.\n\nLemma poly_distr_coef_compare:\n  forall K (N : nat) n,\n  K > 0 ->\n  n > 0 ->\n  poly_eval ((repeat 0 (Z.to_nat (Z.of_nat N-1))) ++ (K * Z.of_nat N)::nil) n >= \n  poly_eval (repeat K N) n.\nProof.\n  assert (forall N:nat, (Datatypes.length (repeat 0 N)) = N) as lem_repeat.\n  { intros. simpl.\n    induction N.\n    - simpl. reflexivity.\n    - simpl. rewrite IHN. reflexivity.\n  }\n  intros.\n  induction N.\n  - simpl. omega.\n  - pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat (S N) - 1))) (K * Z.of_nat (S N) :: nil) n.\n    rewrite H1.\n    pose proof poly_eval_zero (Z.to_nat (Z.of_nat (S N) - 1)).\n    rewrite H2.\n    pose proof lem_repeat (Z.to_nat (Z.of_nat (S N) - 1))%nat.\n    rewrite H3.\n    pose proof Z2Nat.id (Z.of_nat (S N) - 1).\n    assert (0 <= Z.of_nat (S N) - 1).\n    { clear IHN H1 H2 H3 H4.\n      induction N. - simpl. omega.\n      - pose proof Nat2Z.inj_succ (S N).\n        rewrite H1.\n        pose proof Z.le_succ_diag_r (Z.of_nat (S N)).\n        omega.\n    }\n    pose proof H4 H5.\n    rewrite H6.\n    assert (poly_eval (K * Z.of_nat (S N) :: nil) n = K * Z.of_nat (S N)).\n    { simpl. omega. }\n    rewrite H7.\n    rewrite Z.add_0_l.\n    assert (S N = N + 1)%nat. { omega. }\n    rewrite H8.\n    assert (Z.of_nat (N + 1) - 1 = Z.of_nat N).\n    { pose proof Nat2Z.inj_sub (N+1) 1.\n      assert (1 <= N + 1)%nat. omega.\n      pose proof H9 H10. simpl in H11.\n      assert (N+1-1=N)%nat. omega.\n      rewrite H12 in H11.\n      omega.\n    }\n    rewrite H9.\n    \n    clear H1 H2 H3 H4 H5 H6 H7 H8 H9.\n    pose proof poly_eval_app (repeat 0 (Z.to_nat (Z.of_nat N - 1))) (K * Z.of_nat N :: nil) n.\n    rewrite H1 in IHN.\n    pose proof poly_eval_zero (Z.to_nat (Z.of_nat N - 1)) n.\n    rewrite H2 in IHN.\n    pose proof lem_repeat (Z.to_nat (Z.of_nat N - 1))%nat.\n    rewrite H3 in IHN.\n    assert (poly_eval (K * Z.of_nat N :: nil) n = K * Z.of_nat N).\n    { simpl. omega. }\n    rewrite H4 in IHN.\n    rewrite Z.add_0_l in IHN.\n    assert (Z.to_nat (Z.of_nat N - 1) = N - 1)%nat.\n    { pose proof Nat2Z.id N.\n      pose proof Z2Nat.inj_sub (Z.of_nat N) 1.\n      assert (0<=1). omega. pose proof H6 H7.\n      rewrite H5 in H8.\n      assert (Z.to_nat 1 = 1)%nat. \n      { simpl. apply Pos2Nat.inj_1. }\n      rewrite H9 in H8.\n      exact H8.\n    }\n    rewrite H5 in IHN.\n    \n    clear H1 H2 H3 H4 H5.\n    assert (poly_eval (repeat K (N + 1)) n = K * n ^ (Z.of_nat N) + poly_eval (repeat K N) n).\n    { clear IHN.\n      induction N.\n      - simpl. omega.\n      - assert (poly_eval (repeat K (S N + 1)) n = K + n * poly_eval (repeat K (S N)) n).\n        { clear IHN. simpl. induction N.\n          - simpl. omega.\n          - simpl. rewrite IHN. omega.\n        }\n        rewrite H1.\n        assert (S N = N + 1)%nat. omega.\n        rewrite <- H2 in IHN.\n        rewrite IHN at 1.\n        rewrite Z.mul_add_distr_l.\n        assert (n * (K * n ^ Z.of_nat N) = K * n ^ (Z.of_nat (S N))).\n        { rewrite Z.mul_assoc.\n          rewrite Z.mul_shuffle0.\n          pose proof Z.pow_1_r n.\n          rewrite <- H3 at 1.\n          pose proof Z.pow_add_r n 1 (Z.of_nat N).\n          assert (0 <= 1). { omega. }\n          assert (0 <= Z.of_nat N). { omega. }\n          pose proof H4 H5 H6. rewrite <- H7.\n          assert (Z.of_nat (S N) = 1 + Z.of_nat N). \n          { pose proof Nat2Z.inj_add 1 N. \n            assert (1 + N = S N)%nat. { omega. }\n            assert (1 = Z.of_nat 1). { simpl. omega. }\n            rewrite H9 in H8.\n            rewrite <- H10 in H8.\n            tauto.\n          }\n          rewrite <- H8. \n          rewrite Z.mul_comm.\n          omega.\n        }\n        rewrite H3.\n        rewrite Z.add_assoc.\n        assert (K + K * n ^ Z.of_nat (S N) + n * poly_eval (repeat K N) n = K * n ^ Z.of_nat (S N) + (K + n * poly_eval (repeat K N) n)).\n        { omega. }\n        rewrite H4.\n        assert (K + n * poly_eval (repeat K N) n = poly_eval (repeat K (S N)) n).\n        { simpl. omega. }\n        rewrite H5.\n        omega.\n      }\n      rewrite H1.\n      assert (n ^ Z.of_nat N * (K * Z.of_nat (N + 1)) >= n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N).\n      { clear H1.\n        assert (Z.of_nat (N + 1) = Z.of_nat N + 1). \n        { pose proof Nat2Z.inj_add N 1. simpl in H1. \n          tauto.\n        }\n        rewrite H1.\n        rewrite Z.mul_add_distr_l.\n        rewrite Z.mul_add_distr_l.\n        assert (n >= 1). { omega. }\n        assert (n ^ Z.of_nat N >= n ^ Z.of_nat (N - 1)).\n        { clear IHN H1.\n          induction N.\n          - simpl. omega.\n          - assert (n ^ Z.of_nat (S N) = n * n ^ Z.of_nat N).\n            { assert (S N = N + 1)%nat. omega.\n              rewrite H1. clear H1.\n              assert (Z.of_nat (N + 1) = Z.of_nat N + 1). \n              { pose proof Nat2Z.inj_add N 1. simpl in H1. \n                tauto.\n              }\n              rewrite H1. clear H1.\n              pose proof Z.pow_add_r n (Z.of_nat N) 1.\n              assert (0 <= Z.of_nat N). omega.\n              assert (0 <= 1). omega.\n              pose proof H1 H3 H4. rewrite H5.\n              rewrite Z.pow_1_r.\n              rewrite Z.mul_comm.\n              reflexivity.\n            }\n            rewrite H1.\n            assert (S N - 1 = N)%nat. omega.\n            rewrite H3.\n            pose proof Z.le_mul_diag_r (n ^ Z.of_nat N) n.\n            assert (0 < n ^ Z.of_nat N).\n            { apply Z.pow_pos_nonneg. omega. omega. }\n            assert (1<=n). omega.\n            pose proof H4 H5.\n            apply H7 in H6.\n            rewrite Z.mul_comm in H6.\n            omega.\n        }\n        assert (n ^ Z.of_nat N * (K * 1) = K * n ^ Z.of_nat N).\n        { ring. }\n        rewrite H4.\n        apply Z.le_ge.\n        pose proof Zplus_le_compat_r (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (n ^ Z.of_nat N * (K * Z.of_nat N)) (K * n ^ Z.of_nat N).\n        assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) <= n ^ Z.of_nat N * (K * Z.of_nat N)).\n        { clear H5. \n          pose proof Z.mul_le_mono_nonneg_r (n ^ Z.of_nat (N - 1)) (n ^ Z.of_nat N) (K * Z.of_nat N).\n          assert (0 <= K * Z.of_nat N ).\n          pose proof Z.mul_nonneg_nonneg K (Z.of_nat N).\n          assert (0<=K). omega. pose proof H6 H7.\n          assert (0<=Z.of_nat N). omega. pose proof H8 H9.\n          exact H10.\n          pose proof H5 H6.\n          assert (n ^ Z.of_nat (N - 1) <= n ^ Z.of_nat N). omega.\n          tauto.\n        }\n     pose proof H5 H6.\n     tauto.\n   }\n   assert (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N) + K * n ^ Z.of_nat N >= K * n ^ Z.of_nat N + poly_eval (repeat K N) n).\n   { apply Z.le_ge.\n     pose proof Zplus_le_compat_l (poly_eval (repeat K N) n) (n ^ Z.of_nat (N - 1) * (K * Z.of_nat N)) (K * n ^ Z.of_nat N).\n     apply Z.ge_le in IHN.\n     pose proof H3 IHN. omega.\n   }\n  omega.\nQed.\n\nFact poly_mono_cons: forall a h t,\n  poly_monomialize (a :: h :: t) = 0 :: poly_monomialize (h :: t).\nProof.\n  intros.\n  simpl.\n  assert (Datatypes.length t - 0 = Datatypes.length t)%nat.\n  omega.\n  rewrite H.\n  reflexivity.\nQed.\n\nFact poly_mono_length_invar: forall p : poly,\n  length p = length (poly_monomialize p).\nProof.\n  intros.\n  induction p.\n  - simpl. omega.\n  - destruct p.\n    + simpl. reflexivity.\n    + pose proof poly_mono_cons a z p.\n      rewrite H.\n      assert (Datatypes.length (a :: z :: p) = 1 + Datatypes.length (z :: p))%nat. { simpl. omega. }\n      assert (Datatypes.length (0 :: poly_monomialize (z :: p)) = plus 1 (Datatypes.length (poly_monomialize (z :: p)))).\n      { simpl. reflexivity. }\n      rewrite H0.\n      rewrite H1.\n      f_equal.\n      omega.\nQed.\n\nDefinition term_by_term_le := list_le.\n\nLemma poly_each_coef_compare:\n  forall p1 p2,\n  length p1 = length p2 ->\n  term_by_term_le p1 p2 ->\n  forall n, 0 <= n ->\n  poly_eval p1 n <= poly_eval p2 n.\nProof.\n  intros.\n  induction H0.\n  - omega.\n  - simpl.\n    pose proof IHlist_le H0.\n    apply Z.add_le_mono; auto.\n    apply Z.mul_le_mono_nonneg_l; auto.\nQed.\n\nEnd Monomial.\n\nModule Polynomial_Asympotitic_Bound.\nExport Polynomial.\nExport Monomial.\nImport Assertion_D.\n\nInductive AsymptoticBound : Type :=\n  | BigO : poly -> logical_var -> AsymptoticBound\n  | BigOmega : poly -> logical_var -> AsymptoticBound\n  | BigTheta : poly -> logical_var -> AsymptoticBound.\n\n(* Convert asymtotic bounds to corresponding inequalities. We do not consider input with nonpositive size *)\nDefinition ab_eval (La : Lassn) (T : AsymptoticBound) (a1 a2 t : Z) : Prop :=\n  match T with\n  | BigO p n => 0 < La n ->\n                0 <= t <= a2 * (poly_eval p (La n))\n  | BigOmega p n => 0 < La n ->\n                    0 <= a1 * (poly_eval p (La n)) <= t\n  | BigTheta p n => 0 < La n ->\n                    0 <= a1 * (poly_eval p (La n)) <= t /\\ t <= a2 * (poly_eval p (La n))\n  end.\n\nReserved Notation \"T1 '=<' T2\" (at level 50, no associativity).\n\n(* loosen relationship defines equivalence between bounds *)\nInductive loosen : AsymptoticBound -> AsymptoticBound -> Prop :=\n  (* If time is bounded by Theta, it is bounded by O and Omega *)\n  | Theta2Omega : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigOmega p n\n  | Theta2O : forall p n, 0 < poly_get_last p -> BigTheta p n =< BigO p n\n\n  (* We can relax the bound to a monomial with the same highest order term *)\n  | O_Poly2Mono : forall p n, 0 < poly_get_last p -> BigO p n =< BigO (poly_monomialize p) n\n  (* TODO: a monomial should also be able to be relaxed to polynomial with same highest order, but we did not have time to prove its soundness, thus it is not included yet *)\n\n  (* Multiplying positive constant to a bound can obtain another valid bound *)\n  | O_const : forall p a b n, 0 < a -> 0 < b ->  0 < poly_get_last p -> BigO (a ** p) n =< BigO (b ** p) n\n\n  (* A polynomial can have different forms, if they always evaulate to the same value, then bounds defined by them are equivalent *)\n  | O_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigO p1 n =< BigO p2 n\n  | Theta_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigTheta p1 n =< BigTheta p2 n\n  | Omega_id : forall p1 p2 n, (forall z, poly_eval p1 z = poly_eval p2 z) -> BigOmega p1 n =< BigOmega p2 n\n\n  where \"T1 '=<' T2\" := (loosen T1 T2).\n\n\nEnd Polynomial_Asympotitic_Bound.\n", "meta": {"author": "BruceZoom", "repo": "PLProject-AsymptoticComplexity", "sha": "1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea", "save_path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity", "path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity/PLProject-AsymptoticComplexity-1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea/code/PolyAB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7647996555411044}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #18 : 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 [destruct] and [inversion] tactics. *)\n    intros. destruct m. reflexivity.\n    inversion H.\n  }\n  { (* Hint: use the plus_n_Sm lemma *) \n    intros. destruct m. inversion H. inversion H.\n    Lemma plus_n_Sm : forall (n m:nat),\n      n + S m = S (n + m).\n    Proof. intros. induction n. reflexivity.\n      simpl. rewrite -> IHn. reflexivity. Qed.\n    rewrite->plus_n_Sm in H1. symmetry in H1. rewrite -> plus_n_Sm in H1. inversion H1.\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'. symmetry. apply H2.\n  }\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/P19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7647940227990014}}
{"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 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\n\n(* No helper lemma needed. *)\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (even (len (append x y))) (even (plus (len x) (len y))).\nProof.\n induction x.\n  - intros. simpl. rewrite IHx. reflexivity.\n  - intros. 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/goal25.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7647891881329544}}
{"text": "Theorem 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\nCheck nat_ind.\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\ninduction n.\n- reflexivity.\n- simpl. rewrite IHn. reflexivity.\nQed.\n\nInductive yesno : Type :=\n  | yes\n  | no.\n\nCheck yesno_ind.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\n(**\nrgb_ind\n     : forall P : rgb -> Prop, P red -> P green -> P blue -> forall y : rgb, P y\n*)\nCheck rgb_ind.\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\n(**\nnatlist_ind\n     : forall P : natlist -> Prop, P nnil -> (forall (n:nat) (l:listnat): P l -> P (ncons n l))) -> forall y : natlist, P y\n*)\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n  | nnil1\n  | nsnoc1 (l : natlist1) (n : nat).\n\nCheck natlist1_ind.\n\nInductive byntree : Type :=\n | bempty\n | bleaf (yn : yesno)\n | nbranch (yn : yesno) (t1 t2 : byntree).\n\n\n(**\nbyntree_ind\n     : forall P : byntree -> Prop, P bempty -> (forall (yn: yesno): P yn -> P rgb_ind yn) ->\n      (forall (yn: yesno): (forall (t1 t2 :byntree): P yn t1 t2 -> P nbranch yn t1 t2 )) -> \n      forall y : byntree_ind, P y\n*)\n\nCheck byntree_ind.\n\n(**\n  byntree_ind\n     : forall P : byntree -> Prop,\n       P bempty ->\n       (forall yn : yesno, P (bleaf yn)) ->\n       (forall (yn : yesno) (t1 : byntree), P t1 -> forall t2 : byntree, P t2 -> P (nbranch yn t1 t2)) ->\n       forall b : byntree, P b\n*)\n\n\n(** Find an inductive definition that gives rise to the following induction principle:\n ExSet_ind :\n         ∀P : ExSet → Prop,\n             (∀b : bool, P (con1 b)) →\n             (∀(n : nat) (e : ExSet), P e → P (con2 n e)) →\n             ∀e : ExSet, P e\n*)\nInductive ExSet : Type :=\n| cons1 (b :bool)\n| cons2 (n:nat) (e: ExSet)\n.\n\nCheck ExSet_ind.\n\n(* Polymorphism *)\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 : X)\n| node (t1 t2 : tree X).\n\n(**\ntree_ind:\n  : forall (X: Type) (P: tree X -> Prop),\n  forall x: X, P (leaf x X) ->\n  (forall (t1: tree X): P t1 -> forall t2: tree X, P t2 -> P (node X t1 t2)) -> forall t: tree, P t.\n*)\n\nCheck tree_ind.\n\n(**\ntree_ind\n     : forall (X : Type) (P : tree X -> Prop),\n       (forall x : X, P (leaf X x)) ->\n       (forall t1 : tree X, P t1 -> forall t2 : tree X, P t2 -> P (node X t1 t2)) ->\n       forall t : tree X, P t\n*)\n\n\n(** Find an inductive definition that gives rise to the following induction principle:\n  mytype_ind :\n        ∀(X : Type) (P : mytype X → Prop),\n            (∀x : X, P (constr1 X x)) →\n            (∀n : nat, P (constr2 X n)) →\n            (∀m : mytype X, P m →\n               ∀n : nat, P (constr3 X m n)) →\n            ∀m : mytype X, P m\n*)\n\nInductive mytype (X: Type): Type :=\n| constr1 (x: X)\n| constr2 (n:nat)\n| constr3 (m: mytype X) (n :nat)\n.\n\nCheck mytype_ind.\n\n\n(** Find an inductive definition that gives rise to the following induction principle:\n∀(X Y : Type) (P : foo X Y → Prop),\n     (∀x : X, P (bar X Y x)) →\n     (∀y : Y, P (baz X Y y)) →\n     (∀f1 : nat → foo X Y,\n       (∀n : nat, P (f1 n)) → P (quux X Y f1)) →\n     ∀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| quxx : ( nat -> foo X Y ) -> foo X Y.\n\nCheck foo_ind.\n\n\n\n\n(* Induction Hypotheses *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\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    (*  ∀ n', P_m0r n' → P_m0r (S n') *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n\n(* More on the induction Tactic *)\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\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\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\n\n\n\n\n\n\n\n\n", "meta": {"author": "NotBad4U", "repo": "software-foundations-vol1", "sha": "6bc676582dfedbbae664240f1443359fbb496131", "save_path": "github-repos/coq/NotBad4U-software-foundations-vol1", "path": "github-repos/coq/NotBad4U-software-foundations-vol1/software-foundations-vol1-6bc676582dfedbbae664240f1443359fbb496131/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8933093954028816, "lm_q1q2_score": 0.764539873936626}}
{"text": "(* CharacteristicFunctionv. *)\n(* author: Peter Urbak *)\n(* version: 2014-06-02 *)\n\n(** * Characteristic Function *)\n\n(** ** Requirements *)\n\n(* Standard library *)\nRequire Import Arith.\n\n(* Own modules *)\nRequire Import Cases.\nRequire Import Power.\nRequire Import StreamCalculus.\nRequire Import DualMoessnersSieve.\nRequire Import BinomialCoefficients.\n\n(** * Monomials of the binomial expansion *)\n\n(** ** Monomial\n\n  *** Definition *)\n\n(* {MONOMIAL} *)\nDefinition monomial (t r n : nat) : nat :=\n  C(r, n) * (t ^ n).\n(* {END} *)\nHint Unfold monomial : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_monomial :\n  forall (t r n : nat),\n    monomial t r n = C(r, n) * t ^ n.\nProof.\n  intros t r n.\n  unfold monomial.\n  reflexivity.\nQed.\nHint Rewrite unfold_monomial : charfun.\n\n(** *** Properties *)\n\n(* {MONOMIAL_K_EQ_0_IMPLIES_1} *)\nLemma monomial_k_eq_0_implies_1 :\n  forall (t r : nat),\n    monomial t r 0 = 1.\n(* {END} *)\nProof.\n  intros t r.\n  rewrite -> unfold_monomial.\n  rewrite -> mult_1_r.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n  reflexivity.\nQed.\nHint Rewrite monomial_k_eq_0_implies_1 : charfun.\n\n(* {MONOMIAL_R_LT_N_IMPLIES_0} *)\nLemma monomial_r_lt_n_implies_0 :\n  forall (t r n : nat),\n    r < n ->\n    monomial t r n = 0.\n(* {END} *)\nProof.\n  intros t r n H_r_lt_n.\n  rewrite -> unfold_monomial.\n  inversion_clear H_r_lt_n.\n\n  Case \"n = S r\".\n  rewrite -> binomial_coefficient_n_lt_k_implies_0;\n    [ idtac | unfold lt; apply le_n ].\n  rewrite -> mult_0_l.\n  reflexivity.\n\n  Case \"k = S m\".\n  rename H into H_S_r_le_m.\n  rewrite -> binomial_coefficient_n_lt_k_implies_0;\n    [ idtac | unfold lt; apply le_S; exact H_S_r_le_m ].\n  rewrite -> mult_0_l.\n  reflexivity.\nQed.\nHint Resolve monomial_r_lt_n_implies_0 : charfun.\n\n(* {MONOMIAL_R_EQ_N_IMPLIES_POWER} *)\nLemma monomial_r_eq_n_implies_power :\n  forall (t r : nat),\n    monomial t r r = t ^ r.\n(* {END} *)\nProof.\n  intros t r.\n  rewrite -> unfold_monomial.\n  rewrite -> binomial_coefficient_n_eq_k_implies_1.\n  rewrite -> mult_1_l.\n  reflexivity.\nQed.\nHint Rewrite monomial_r_eq_n_implies_power : charfun.\n\n(* {MONOMIAL_DECOMPOSE_RANK} *)\nTheorem monomial_decompose_rank :\n  forall (t r' n' : nat),\n    monomial t (S r') (S n') =\n    monomial t r' (S n') + t * monomial t r' n'.\n(* {END} *)\nProof.\n  intros t r' n'.\n  rewrite ->2 unfold_monomial.\n  rewrite -> Pascal_s_rule.\n  rewrite -> mult_plus_distr_r.\n  rewrite <- unfold_monomial.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> NPeano.Nat.mul_shuffle3.\n  rewrite <- unfold_monomial.\n  reflexivity.\nQed.\nHint Rewrite monomial_decompose_rank : charfun.\n\n(** * Characteristic functions for entries in Moessner triangles\n\n  NOTE: Be aware that [r] means rank for [moessner_entry] and row [r] for\n  [rotated_moessner_entry]. *)\n\n(** ** Moessner entry\n\n  Given a 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(* {MOESSNER_ENTRY} *)\nFixpoint moessner_entry (r n k t : nat) : nat :=\n  match n with\n    | 0 => match k with\n             | 0 => 1\n             | S k' => 0\n           end\n    | S n' => match k with\n                | 0 => monomial t r (S n') +\n                       moessner_entry r n' 0 t\n                | S k' => moessner_entry r n' (S k') t +\n                          moessner_entry r n' k' t\n              end\n  end.\n(* {END} *)\nHint Unfold moessner_entry : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_moessner_entry_base_case_O :\n  forall (r t : nat),\n    moessner_entry r 0 0 t = 1.\nProof.\n  intros r t.\n  unfold moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_moessner_entry_base_case_O : charfun.\n\nLemma unfold_moessner_entry_base_case_S :\n  forall (r k' t : nat),\n    moessner_entry r 0 (S k') t = 0.\nProof.\n  intros r k' t.\n  unfold moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_moessner_entry_base_case_S : charfun.\n\nLemma unfold_moessner_entry_induction_case_O :\n  forall (n' r t : nat),\n    moessner_entry r (S n') 0 t =\n    monomial t r (S n') + moessner_entry r n' 0 t.\nProof.\n  intros n' r t.\n  unfold moessner_entry; fold moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_moessner_entry_induction_case_O : charfun.\n\n(* {UNFOLD_MOESSNER_ENTRY_INDUCTION_CASE_S} *)\nLemma unfold_moessner_entry_induction_case_S :\n  forall (n' r k' t : nat),\n    moessner_entry r (S n') (S k') t =\n    moessner_entry r n' (S k') t +\n    moessner_entry r n' k' t.\n(* {END} *)\nProof.\n  intros n' r k' t.\n  unfold moessner_entry; fold moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_moessner_entry_induction_case_S : charfun.\n\n(** *** Properties *)\n\nDefinition moessner_entry_Pascal_s_rule :=\n  unfold_moessner_entry_induction_case_S.\nHint Rewrite moessner_entry_Pascal_s_rule : charfun.\n\n(*\n(* {MOESSNER_ENTRY_PASCAL_S_RULE} *)\nTheorem moessner_entry_Pascal_s_rule :\n  forall (n' r k' t : nat),\n    moessner_entry r (S n') (S k') t =\n    moessner_entry r n' (S k') t +\n    moessner_entry r n' k' t.\n(* {END} *)\n*)\n\n(* {MOESSNER_ENTRY_EQ_BINOMIAL_COEFFICIENT} *)\nTheorem moessner_entry_eq_binomial_coefficient :\n  forall (n k r : nat),\n    moessner_entry r n k 0 = C(n, k).\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros k r.\n  unfold moessner_entry, binomial_coefficient.\n  reflexivity.\n\n  Case \"n = S n'\".\n  case k as [ | k' ].\n\n  SCase \"k = 0\".\n  intro r.\n  rewrite -> unfold_moessner_entry_induction_case_O.\n  rewrite -> (IH_n' 0 r).\n  rewrite -> unfold_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  reflexivity.\n\n  SCase \"k = S k'\".\n  intro r.\n  rewrite -> moessner_entry_Pascal_s_rule.\n  rewrite -> (IH_n' (S k') r).\n  rewrite -> (IH_n' k' r).\n  rewrite <- Pascal_s_rule.\n  reflexivity.\nQed.\nHint Rewrite moessner_entry_eq_binomial_coefficient : charfun.\n\n(* {MOESSNER_ENTRY_N_LT_K_IMPLIES_0} *)\nLemma moessner_entry_n_lt_k_implies_0 :\n  forall (r n k t : nat),\n    n < k ->\n    moessner_entry r n k t = 0.\n(* {END} *)\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 H_absurd; inversion H_absurd.\n\n  SCase \"k = S k'\".\n  intros t H_0_lt_S_k'.\n  rewrite -> unfold_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 H_absurd; inversion H_absurd.\n\n  SCase \"k = S k'\".\n  intros t H_S_n'_lt_S_k'.\n  rewrite -> 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 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 H_n'_lt_k').\n  reflexivity.\nQed.\nHint Resolve moessner_entry_n_lt_k_implies_0 : charfun.\n\n(* {MOESSNER_ENTRY_N_EQ_K_IMPLIES_1} *)\nLemma moessner_entry_n_eq_k_implies_1 :\n  forall (n r t : nat),\n    moessner_entry r n n t = 1.\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros r t.\n  rewrite -> unfold_moessner_entry_base_case_O.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros r t.\n  rewrite -> moessner_entry_Pascal_s_rule.\n  rewrite -> (IH_n' r t).\n  rewrite -> moessner_entry_n_lt_k_implies_0;\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite moessner_entry_n_eq_k_implies_1 : charfun.\n\n(** ** Moessner entries\n\n  Enumerates a row of moessner entries.\n\n  *** Definition *)\n\n(* {MOESSNER_ENTRIES} *)\nCoFixpoint moessner_entries (r n k t : nat) : Stream nat :=\n  (moessner_entry r n k t) :::\n  (moessner_entries r n (S k) t).\n(* {END} *)\nHint Unfold moessner_entries : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_moessner_entries :\n  forall (r n k t : nat),\n    moessner_entries r n k t =\n    (moessner_entry r n k t) :::\n    (moessner_entries r n (S k) t).\nProof.\n  intros r n k t.\n  rewrite -> (unfold_Stream (moessner_entries r n k t)).\n  unfold moessner_entries; fold moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite unfold_moessner_entries : charfun.\n\nLemma moessner_entries_initial_value :\n  forall (r n k t : nat),\n    (moessner_entries r n k t)(0) =\n    (moessner_entry r n k t).\nProof.\n  intros r n k t.\n  rewrite -> initial_value.\n  rewrite -> unfold_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite moessner_entries_initial_value : charfun.\n\nLemma moessner_entries_stream_derivative :\n  forall (r n k t : nat),\n    (moessner_entries r n k t)` =\n    (moessner_entries r n (S k) t).\nProof.\n  intros r n k t.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite moessner_entries_stream_derivative : charfun.\n\n(** ** Properties *)\n\n(* {STR_NTH_MOESSNER_ENTRIES} *)\nLemma Str_nth_moessner_entries :\n  forall (i r n k t : nat),\n    Str_nth i (moessner_entries r n k t) =\n    moessner_entry r n (i + k) t.\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros r n k t.\n  rewrite -> Str_nth_0.\n  rewrite -> moessner_entries_initial_value.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros r n k t.\n  rewrite -> Str_nth_S_n.\n  rewrite -> moessner_entries_stream_derivative.\n  rewrite -> (IH_i' r n (S k) t).\n  rewrite <- plus_n_Sm.\n  rewrite -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_moessner_entries : charfun.\n\n(** ** Rotated moessner entry\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(* {ROTATED_MOESSNER_ENTRY} *)\nDefinition rotated_moessner_entry (n r c t : nat) : nat :=\n  moessner_entry n (c + r) c t.\n(* {END} *)\nHint Unfold rotated_moessner_entry : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_rotated_moessner_entry :\n  forall (n r c t : nat),\n    rotated_moessner_entry n r c t =\n    moessner_entry n (c + r) c t.\nProof.\n  intros n r c t.\n  unfold rotated_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_rotated_moessner_entry : charfun.\n\n(* {ROTATED_MOESSNER_ENTRY_PASCAL_S_RULE} *)\nLemma rotated_moessner_entry_Pascal_s_rule :\n  forall (n r' c' t : nat),\n    rotated_moessner_entry n (S r') (S c') t =\n    rotated_moessner_entry n r' (S c') t +\n    rotated_moessner_entry n (S r') c' t.\n(* {END} *)\nProof.\n  intros n r' c' t.\n  rewrite ->3 unfold_rotated_moessner_entry.\n  rewrite <-2 plus_n_Sm.\n  rewrite -> plus_Sn_m.\n  rewrite -> moessner_entry_Pascal_s_rule.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entry_Pascal_s_rule : charfun.\n\n(** *** Properties *)\n\n(* {ROTATED_MOESSNER_ENTRY_EQ_BINOMIAL_COEFFICIENT} *)\nCorollary rotated_moessner_entry_eq_binomial_coefficient :\n  forall (n r c : nat),\n    rotated_moessner_entry n r c 0 = C(r + c, c).\n(* {END} *)\nProof.\n  intros n r c.\n  rewrite -> unfold_rotated_moessner_entry.\n  rewrite -> moessner_entry_eq_binomial_coefficient.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite moessner_entry_eq_binomial_coefficient : charfun.\n\n(* {ROTATED_MOESSNER_ENTRY_EQ_ROTATED_BINOMIAL_COEFFICIENT} *)\nCorollary rotated_moessner_entry_eq_rotated_binomial_coefficient :\n  forall (n r c : nat),\n    rotated_moessner_entry n r c 0 = R(r, c).\n(* {END} *)\nProof.\n  intros n r c.\n  rewrite -> rotated_moessner_entry_eq_binomial_coefficient.\n  rewrite -> rotated_binomial_coefficient_is_symmetric.\n  rewrite -> unfold_rotated_binomial_coefficient.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entry_eq_rotated_binomial_coefficient : charfun.\n\n(* {ROTATED_MOESSNER_ENTRY_R_EQ_0_IMPLIES_1} *)\nLemma rotated_moessner_entry_r_eq_0_implies_1 :\n  forall (c n t : nat),\n    rotated_moessner_entry n 0 c t = 1.\n(* {END} *)\nProof.\n  intros c n t.\n  rewrite -> unfold_rotated_moessner_entry.\n  rewrite -> plus_0_r.\n  rewrite -> moessner_entry_n_eq_k_implies_1.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entry_r_eq_0_implies_1 : charfun.\n\n(* {ROTATED_MOESSNER_ENTRY_C_EQ_0} *)\nLemma rotated_moessner_entry_c_eq_0 :\n  forall (r' n t : nat),\n    rotated_moessner_entry n (S r') 0 t =\n    monomial t n (S r') + rotated_moessner_entry n r' 0 t.\n(* {END} *)\nProof.\n  intros r' n t.\n  rewrite ->2 unfold_rotated_moessner_entry.\n  rewrite ->2 plus_0_l.\n  rewrite -> unfold_moessner_entry_induction_case_O.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entry_c_eq_0 : charfun.\n\n(** ** Rotated moessner entries\n\n  *** Definition *)\n\n(* {ROTATED_MOESSNER_ENTRIES} *)\nCoFixpoint rotated_moessner_entries (n r c t : nat) : Stream nat :=\n  (rotated_moessner_entry n r c t) :::\n  (rotated_moessner_entries n (S r) c t).\n(* {END} *)\nHint Unfold rotated_moessner_entries : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_rotated_moessner_entries :\n  forall (n r c t : nat),\n    rotated_moessner_entries n r c t =\n    (rotated_moessner_entry n r c t) :::\n    (rotated_moessner_entries n (S r) c t).\nProof.\n  intros n r c t.\n  rewrite -> (unfold_Stream (rotated_moessner_entries n r c t)).\n  unfold rotated_moessner_entries; fold rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite unfold_rotated_moessner_entries : charfun.\n\nLemma rotated_moessner_entries_initial_value :\n  forall (n r c t : nat),\n    (rotated_moessner_entries n r c t)(0) =\n    (rotated_moessner_entry n r c t).\nProof.\n  intros n r c t.\n  rewrite -> initial_value.\n  rewrite -> unfold_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entries_initial_value : charfun.\n\nLemma rotated_moessner_entries_stream_derivative :\n  forall (n r c t : nat),\n    (rotated_moessner_entries n r c t)` =\n    (rotated_moessner_entries n (S r) c t).\nProof.\n  intros n r c t.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entries_stream_derivative : charfun.\n\n(** ** Properties *)\n\n(* {STR_NTH_ROTATED_MOESSNER_ENTRIES} *)\nLemma Str_nth_rotated_moessner_entries :\n  forall (i n r c t : nat),\n    Str_nth i (rotated_moessner_entries n r c t) =\n    rotated_moessner_entry n (r + i) c t.\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n r c t.\n  rewrite -> Str_nth_0.\n  rewrite -> rotated_moessner_entries_initial_value.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n r c t.\n  rewrite -> Str_nth_S_n.\n  rewrite -> rotated_moessner_entries_stream_derivative.\n  rewrite -> (IH_i' n (S r) c t).\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_rotated_moessner_entries : charfun.\n\nCorollary Str_nth_rotated_moessner_entries_t_eq_0 :\n  forall (i n r c : nat),\n    Str_nth i (rotated_moessner_entries n r c 0) =\n    C(r + i + c, c).\nProof.\n  intros i n r c.\n  rewrite -> Str_nth_rotated_moessner_entries.\n  rewrite -> rotated_moessner_entry_eq_binomial_coefficient.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_rotated_moessner_entries_t_eq_0 : charfun.\n\n(* {ROTATED_MOESSNER_ENTRIES_PASCAL_S_RULE} *)\nLemma rotated_moessner_entries_Pascal_s_rule :\n  forall (n r' c' t : nat),\n    rotated_moessner_entries n (S r') (S c') t ~\n    (rotated_moessner_entries n (S r') c' t) s+\n    (rotated_moessner_entries n r' (S c') t).\n(* {END} *)\nProof.\n  pcofix coIH.\n  intros n r' c' t.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> stream_sum_initial_value.\n  rewrite ->3 rotated_moessner_entries_initial_value.\n  rewrite -> 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 rotated_moessner_entries_stream_derivative.\n  exact (coIH n (S r') c' t).\nQed.\nHint Rewrite rotated_moessner_entries_Pascal_s_rule : charfun.\n\n(** ** Monomials\n\n  Enumerates the monomials of the binomial expansion.\n\n  *** Definition *)\n\n(* {MONOMIALS} *)\nCoFixpoint monomials (t r n : nat) : Stream nat :=\n  (monomial t r n) ::: (monomials t r (S n)).\n(* {END} *)\nHint Unfold monomials : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_monomials :\n  forall (t r n : nat),\n    monomials t r n = (monomial t r n) ::: (monomials t r (S n)).\nProof.\n  intros t r n.\n  rewrite -> (unfold_Stream (monomials t r n)).\n  unfold monomials; fold monomials.\n  reflexivity.\nQed.\nHint Rewrite unfold_monomials : charfun.\n\n(* {MONOMIALS_INITIAL_VALUE} *)\nLemma monomials_initial_value :\n  forall (t r n : nat),\n    (monomials t r n)(0) = (monomial t r n).\n(* {END} *)\nProof.\n  intros t r n.\n  rewrite -> initial_value.\n  rewrite -> unfold_monomials.\n  reflexivity.\nQed.\nHint Rewrite monomials_initial_value : charfun.\n\n(* {MONOMIALS_STREAM_DERIVATIVE} *)\nLemma monomials_stream_derivative :\n  forall (t r n : nat),\n    (monomials t r n)` = (monomials t r (S n)).\n(* {END} *)\nProof.\n  intros t r n.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_monomials.\n  reflexivity.\nQed.\nHint Rewrite monomials_stream_derivative : charfun.\n\n(** *** Properties *)\n\n(* {STR_NTH_MONOMIALS} *)\nLemma Str_nth_monomials :\n  forall (i t r n : nat),\n    Str_nth i (monomials t r n) = monomial t r (i + n).\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t r n.\n  rewrite -> Str_nth_0.\n  rewrite -> monomials_initial_value.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t r n.\n  rewrite -> Str_nth_S_n.\n  rewrite -> monomials_stream_derivative.\n  rewrite -> (IH_i' t r (S n)).\n  rewrite -> plus_Sn_m, <- plus_n_Sm.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_monomials : charfun.\n\nLemma Str_nth_monomials_i_plus_n_gt_r_implies_0 :\n  forall (i r n t : nat),\n    r < n + i ->\n    Str_nth i (monomials t r n) = 0.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros r n t H_r_lt_n.\n  rewrite -> plus_0_r in H_r_lt_n.\n  rewrite -> Str_nth_0.\n  rewrite -> monomials_initial_value.\n  rewrite -> unfold_monomial.\n  rewrite -> (binomial_coefficient_n_lt_k_implies_0 r n H_r_lt_n).\n  rewrite -> mult_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros r n t H_r_lt_n_plus_S_i'.\n  rewrite -> Str_nth_S_n.\n  rewrite monomials_stream_derivative.\n  rewrite -> (IH_i' r (S n) t);\n    [ idtac | rewrite -> plus_Sn_m, -> plus_n_Sm; exact H_r_lt_n_plus_S_i' ].\n  reflexivity.\nQed.\nHint Resolve Str_nth_monomials_i_plus_n_gt_r_implies_0 : charfun.\n\n(* {REV_STR_PREFIX_MONOMIALS} *)\nLemma rev_Str_prefix_monomials :\n  forall (l n r t : nat),\n    rev (Str_prefix (S l) (monomials t r n)) =\n    monomial t r (n + l) :: rev (Str_prefix l (monomials t r n)).\n(* {END} *)\nProof.\n  induction l as [ | l' IH_l' ].\n\n  Case \"l = 0\".\n  intros n r t.\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 -> 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.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> monomials_stream_derivative.\n  rewrite -> IH_l'.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> monomials_initial_value.\n  rewrite -> 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_monomials : charfun.\n\n(* {REV_STR_PREFIX_ROTATED_MOESSNER_ENTRIES} *)\nLemma rev_Str_prefix_rotated_moessner_entries :\n  forall (l n r c t : nat),\n    rev (Str_prefix (S l) (rotated_moessner_entries n r c t)) =\n    rotated_moessner_entry n (r + l) c t\n      :: rev (Str_prefix l (rotated_moessner_entries n r c t )).\n(* {END} *)\nProof.\n  induction l as [ | l' IH_l' ].\n\n  Case \"l = 0\".\n  intros n r c t.\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 -> rotated_moessner_entries_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 c t.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> rotated_moessner_entries_stream_derivative.\n  rewrite -> IH_l'.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> rotated_moessner_entries_initial_value.\n  rewrite -> rotated_moessner_entries_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_rotated_moessner_entries : charfun.\n\nLemma monomials_tail_of_0s :\n  forall (i n t : nat),\n    Str_nth_tl (S i) (monomials t i n) ~ #0.\nProof.\n  pcofix coIH.\n  intros i n t.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite <- unfold_Str_nth.\n  rewrite -> Str_nth_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 monomials_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  exact (coIH i (S n) t).\nQed.\nHint Rewrite monomials_tail_of_0s : tupmos.\n\n(** ** Monomials sum\n\n  Enumerates the partial sums of the monomials of the binomial expansion.\n\n  *** Definition *)\n\n(* {MONOMIALS_SUM} *)\nCoFixpoint monomials_sum (t r n a : nat) : Stream nat :=\n  let a' := (monomial t r n) + a in\n  a' ::: (monomials_sum t r (S n) a').\n(* {END} *)\nHint Unfold monomials_sum : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_monomials_sum :\n  forall (t r n a : nat),\n    monomials_sum t r n a =\n    ((monomial t r n) + a) :::\n    (monomials_sum t r (S n) ((monomial t r n) + a)).\nProof.\n  intros t r n a.\n  rewrite -> (unfold_Stream (monomials_sum t r n a)).\n  unfold monomials_sum; fold monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite unfold_monomials_sum : charfun.\n\n(* {MONOMIALS_SUM_INITIAL_VALUE} *)\nLemma monomials_sum_initial_value :\n  forall (t r n a : nat),\n    (monomials_sum t r n a)(0) = (monomial t r n) + a.\n(* {END} *)\nProof.\n  intros t r n a.\n  rewrite -> initial_value.\n  rewrite -> unfold_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite monomials_sum_initial_value : charfun.\n\n(* {MONOMIALS_SUM_STREAM_DERIVATIVE} *)\nLemma monomials_sum_stream_derivative :\n  forall (t r n a : nat),\n    (monomials_sum t r n a)` =\n    (monomials_sum t r (S n) ((monomial t r n) + a)).\n(* {END} *)\nProof.\n  intros t r n a.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite monomials_sum_stream_derivative : charfun.\n\n(** *** Properties *)\n\nLemma monomials_sum_acc_aux :\n  forall (t l n i j : nat),\n    (monomials_sum t l n (i + j)) ~\n    (monomials_sum t l n i) s+ #j.\nProof.\n  pcofix coIH.\n  intros t l n i j.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> monomials_sum_initial_value.\n  rewrite -> stream_sum_initial_value.\n  rewrite -> monomials_sum_initial_value.\n  rewrite -> stream_constant_initial_value.\n  rewrite <- plus_assoc.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite -> stream_sum_stream_derivative.\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  rewrite -> plus_assoc.\n  exact (coIH t l (S n) (monomial t l n + i) j).\nQed.\nHint Rewrite monomials_sum_acc_aux : charfun.\n\nCorollary monomials_sum_acc :\n  forall (t l n a : nat),\n    (monomials_sum t l n a) ~\n    (monomials_sum t l n 0) s+ #a.\nProof.\n  intros t l n a.\n  rewrite <- monomials_sum_acc_aux.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite monomials_sum_acc : charfun.\n\n(* {STR_NTH_MONOMIALS_SUM_STREAM_DERIVATIVE} *)\nLemma Str_nth_monomials_sum_stream_derivative :\n  forall (i n t l a : nat),\n    Str_nth i (monomials_sum t l n a)` =\n    Str_nth i ((monomials_sum t l (S n) a) s+ #(monomial t l n)).\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n t l a.\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_sum_initial_value.\n  rewrite ->2 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.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite -> stream_sum_stream_derivative.\n  rewrite -> (IH_i' (S n) t l (monomial t l n + a)).\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  rewrite <-2 monomials_sum_acc_aux.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  rewrite -> (plus_comm a _).\n  reflexivity.\nQed.\nHint Rewrite Str_nth_monomials_sum_stream_derivative : charfun.\n\nCorollary monomials_sum_stream_derivative_bisim :\n  forall (n t l a : nat),\n    (monomials_sum t l n a)` ~\n    (monomials_sum t l (S n) a) s+ #(monomial t l n).\nProof.\n  intros n t l a.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact (Str_nth_monomials_sum_stream_derivative i n t l a).\nQed.\nHint Rewrite monomials_sum_stream_derivative_bisim : charfun.\n\nLemma Str_nth_monomials_sum_r_eq_0 :\n  forall (i t n' m' a : nat),\n    Str_nth i (monomials_sum t 0 (S n') a) =\n    Str_nth i (monomials_sum t 0 (S m') a).\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t n' m' a.\n  rewrite ->2 Str_nth_0.\n  rewrite ->2 monomials_sum_initial_value.\n  rewrite ->2 unfold_monomial.\n  rewrite ->2 unfold_binomial_coefficient_base_case_0_S_k'.\n  rewrite ->2 mult_0_l.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t n' m' a.\n  rewrite ->2 Str_nth_S_n.\n  rewrite ->2 Str_nth_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).\n  reflexivity.\nQed.\nHint Rewrite Str_nth_monomials_sum_r_eq_0 : charfun.\n\n(* {SHIFT_START_INDEX_MONOMIALS_SUM} *)\nLemma shift_start_index_monomials_sum :\n  forall (i' r n a t : nat),\n    (monomial t r n) + (Str_nth i' (monomials_sum t r (S n) a)) =\n    (monomial t r (n + (S i'))) + (Str_nth i' (monomials_sum t r n a)).\n(* {END} *)\nProof.\n  induction i' as [ | i'' IH_i'' ].\n\n  Case \"i' = 0\".\n  intros r n a t.\n  rewrite ->2 Str_nth_0.\n  rewrite ->2 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.\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_monomials_sum_stream_derivative.\n  unfold stream_sum.\n  rewrite -> Str_nth_stream_zip.\n  rewrite -> Str_nth_stream_constant.\n  rewrite <- (plus_comm (monomial t r (S n)) _).\n  rewrite -> (IH_i'' r (S n) a t).\n  rewrite <-3 plus_n_Sm, -> plus_Sn_m.\n\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_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 shift_start_index_monomials_sum : charfun.\n\n(** * Relations between monomials, monomials sum,\n moessner  entry rotated, make tuple, and partial sums acc *)\n\n(* {STR_NTH_MONOMIALS_SUM_EQ_ROTATED_MOESSNER_ENTRY} *)\nTheorem Str_nth_monomials_sum_eq_rotated_moessner_entry :\n  forall (i t r a : nat),\n    Str_nth i (monomials_sum t r 0 a) =\n    (rotated_moessner_entry r i 0 t) + a.\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t r a.\n  rewrite -> Str_nth_0.\n  rewrite -> monomials_sum_initial_value.\n  rewrite -> unfold_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_rotated_moessner_entry.\n  rewrite -> plus_0_r.\n  rewrite -> unfold_moessner_entry_base_case_O.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t r a.\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_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 rotated_moessner_entry in *.\n  rewrite -> plus_0_l in *.\n  rewrite -> unfold_moessner_entry_induction_case_O.\n  rewrite <- plus_assoc.\n  rewrite <- (IH_i' t r a).\n  rewrite -> shift_start_index_monomials_sum.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_monomials_sum_eq_rotated_moessner_entry : charfun.\n\n(* {STREAM_PARTIAL_SUMS_ACC_MONOMIALS_BISIM_MONOMIALS_SUM} *)\nLemma stream_partial_sums_acc_monomials_bisim_monomials_sum :\n  forall (t r n a : nat),\n    stream_partial_sums_acc a (monomials t r n) ~\n    monomials_sum t r n a.\n(* {END} *)\nProof.\n  pcofix coIH.\n  intros t n k a.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite -> monomials_initial_value.\n  rewrite -> monomials_sum_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite -> monomials_stream_derivative.\n  rewrite -> monomials_sum_stream_derivative.\n  rewrite -> monomials_initial_value.\n  exact (coIH t n (S k) (monomial t n k + a)).\nQed.\nHint Rewrite stream_partial_sums_acc_monomials_bisim_monomials_sum : charfun.\n\n(* {STREAM_PARTIAL_SUMS_MONOMIALS_BISIM_MONOMIALS_SUM} *)\nCorollary stream_partial_sums_monomials_bisim_monomials_sum :\n  forall (t r n : nat),\n    stream_partial_sums (monomials t r n) ~\n    monomials_sum t r n 0.\n(* {END} *)\nProof.\n  intros t r n.\n  rewrite -> unfold_stream_partial_sums.\n  exact (stream_partial_sums_acc_monomials_bisim_monomials_sum t r n 0).\nQed.\nHint Rewrite stream_partial_sums_monomials_bisim_monomials_sum : charfun.\n\n(* {MAKE_TUPLE_MONOMIALS_EQ_MONOMIALS_SUM} *)\nCorollary make_tuple_monomials_eq_monomials_sum :\n  forall (l t r n a : nat),\n    make_tuple (Str_prefix (S l) (monomials t r n)) a =\n    Str_prefix l (monomials_sum t r n a).\n(* {END} *)\nProof.\n  intros l t r n a.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  rewrite -> stream_partial_sums_acc_monomials_bisim_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite make_tuple_monomials_eq_monomials_sum : charfun.\n\n(* {MONOMIALS_AND_ROTATED_MOESSNER_ENTRY} *)\nCorollary monomials_and_rotated_moessner_entry :\n  forall (l t r a : nat),\n    nth l (make_tuple (Str_prefix (S (S l)) (monomials t r 0)) a) 0 =\n    rotated_moessner_entry r l 0 t + a.\n(* {END} *)\nProof.\n  intros l t r a.\n  rewrite <- Str_nth_monomials_sum_eq_rotated_moessner_entry.\n  rewrite -> make_tuple_monomials_eq_monomials_sum.\n  rewrite -> (nth_and_Str_nth l (S l) (monomials_sum t r 0 a));\n      [ idtac | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite monomials_and_rotated_moessner_entry : charfun.\n\n(* {MONOMIALS_SUM_BISIM_ROTATED_MOESSNER_ENTRIES} *)\nCorollary rotated_moessner_entries_bisim_monomials_sum :\n  forall (n t : nat),\n    monomials_sum t n 0 0 ~\n    rotated_moessner_entries n 0 0 t.\n(* {END} *)\nProof.\n  intros n t.\n  apply Str_nth_implies_bisimilarity; intro i.\n  rewrite -> Str_nth_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  rewrite -> Str_nth_monomials_sum_eq_rotated_moessner_entry.\n  rewrite -> plus_0_r.\n  reflexivity.\nQed.\nHint Rewrite rotated_moessner_entries_bisim_monomials_sum : charfun.\n\n(* {MAKE_TUPLE_MONOMIALS_EQ_ROTATED_MOESSNER_ENTRIES} *)\nCorollary make_tuple_monomials_eq_rotated_moessner_entries :\n  forall (l' n' t : nat),\n    make_tuple (Str_prefix (S l') (monomials t n' 0)) 0 =\n    Str_prefix l' (rotated_moessner_entries n' 0 0 t).\n(* {END} *)\nProof.\n  intros l' n' t.\n  rewrite -> make_tuple_monomials_eq_monomials_sum.\n  rewrite -> rotated_moessner_entries_bisim_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite make_tuple_monomials_eq_rotated_moessner_entries : charfun.\n\n(** * Relation between consecutive columns of arbitrary Moessner triangles *)\n\n(** * Proof that partially summing the [c']th column of rotated moessner entries\n  gives the [S c']th column *)\n\n(* {STR_NTH_ROTATED_MOESSNER_ENTRIES_OVER_R} *)\nLemma Str_nth_rotated_moessner_entries_over_r :\n  forall (i n r' c' t : nat),\n    Str_nth i (rotated_moessner_entries n (S r') (S c') t) =\n    Str_nth i (stream_partial_sums_acc\n                 (rotated_moessner_entry n r' (S c') t)\n                 (rotated_moessner_entries n (S r') c' t)).\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n r' c' t.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite ->2 rotated_moessner_entries_initial_value.\n  rewrite -> rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> plus_comm.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n r' c' t.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite ->2 rotated_moessner_entries_stream_derivative.\n  rewrite -> rotated_moessner_entries_initial_value.\n  rewrite -> (IH_i' n (S r') c' t).\n  rewrite -> rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_rotated_moessner_entries_over_r : charfun.\n\nCorollary partial_sums_rotated_moessner_entries_bisim_next_column_over_r :\n  forall (n r' c' t : nat),\n    (rotated_moessner_entries n (S r') (S c') t) ~\n    (stream_partial_sums_acc (rotated_moessner_entry n r' (S c') t)\n                      (rotated_moessner_entries n (S r') c' t)).\nProof.\n  intros n r' c' t.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact\n  (Str_nth_rotated_moessner_entries_over_r i n r' c' t).\nQed.\nHint Rewrite partial_sums_rotated_moessner_entries_bisim_next_column_over_r\n  : charfun.\n\n(* {STR_NTH_PARTIAL_SUMS_ROTATED_MOESSNER_ENTRIES} *)\nTheorem Str_nth_partial_sums_rotated_moessner_entries :\n  forall (i n c' t : nat),\n    Str_nth i (stream_partial_sums_acc\n                 0 (rotated_moessner_entries n 0 c' t)) =\n    Str_nth i (rotated_moessner_entries n 0 (S c') t).\n(* {END} *)\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n c' t.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite -> plus_0_r.\n  rewrite ->2 rotated_moessner_entries_initial_value.\n  rewrite ->2 unfold_rotated_moessner_entry.\n  rewrite ->2 plus_0_r.\n  rewrite -> moessner_entry_Pascal_s_rule.\n  rewrite -> (moessner_entry_n_lt_k_implies_0 n c' (S c') t);\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n c' t.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite -> plus_0_r.\n  rewrite ->2 rotated_moessner_entries_stream_derivative.\n  rewrite -> rotated_moessner_entries_initial_value.\n  rewrite -> Str_nth_rotated_moessner_entries_over_r.\n  rewrite ->2 unfold_rotated_moessner_entry.\n  rewrite ->2 plus_0_r.\n  rewrite -> moessner_entry_Pascal_s_rule.\n  rewrite -> (moessner_entry_n_lt_k_implies_0 n c' (S c') t);\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite Str_nth_partial_sums_rotated_moessner_entries : charfun.\n\n(* {PARTIAL_SUMS_ROTATED_MOESSNER_ENTRIES_BISIM_NEXT_COLUMN} *)\nCorollary partial_sums_rotated_moessner_entries_bisim_next_column :\n  forall (n c' t : nat),\n    (stream_partial_sums_acc 0 (rotated_moessner_entries n 0 c' t)) ~\n    (rotated_moessner_entries n 0 (S c') t).\n(* {END} *)\nProof.\n  intros n c' t.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact (Str_nth_partial_sums_rotated_moessner_entries i n c' t).\nQed.\nHint Rewrite partial_sums_rotated_moessner_entries_bisim_next_column : charfun.\n\nLemma last_of_rotated_moessner_entries :\n  forall (c l n t : nat),\n    last (Str_prefix (S l) (rotated_moessner_entries n 0 c t)) 0 =\n    rotated_moessner_entry n l c t.\nProof.\n  intros c l n t.\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_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite last_of_rotated_moessner_entries : charfun.\n\n(* {LAST_OF_ROTATED_MOESSNER_ENTRIES_TO_BINOMIAL} *)\nCorollary last_of_rotated_moessner_entries_to_binomial :\n  forall (c l n t : nat),\n    last (Str_prefix (S l) (rotated_moessner_entries n 0 c t)) 0 =\n    moessner_entry n (c + l) c t.\n(* {END} *)\nProof.\n  intros c l n t.\n  rewrite -> last_of_rotated_moessner_entries.\n  rewrite -> unfold_rotated_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite last_of_rotated_moessner_entries_to_binomial : charfun.\n\n(** *** Proof that applying [make_tuple] on a column of [rotated_moessner_entries]\n  gives the next column *)\n\n(* {MAKE_TUPLE_ROTATED_MOESSNER_ENTRIES} *)\nCorollary make_tuple_rotated_moessner_entries :\n  forall (l' n' c' t : nat),\n    make_tuple (Str_prefix\n                  (S l') (rotated_moessner_entries n' 0 c' t)) 0 =\n    Str_prefix l' (rotated_moessner_entries n' 0 (S c') t).\n(* {END} *)\nProof.\n  intros l' n' c' t.\n  rewrite <- partial_sums_rotated_moessner_entries_bisim_next_column.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  reflexivity.\nQed.\nHint Rewrite make_tuple_rotated_moessner_entries : charfun.\n\n(** * Spelled out correctness proof of moessner entry rotated *)\n\n(** ** Repeat make tuple\n\n  *** Definition *)\n\n(* {REPEAT_MAKE_TUPLE} *)\nFixpoint repeat_make_tuple (ys : tuple) (a n : nat) : tuple :=\n  match n with\n    | 0 => ys\n    | S n' => repeat_make_tuple (make_tuple ys a) a n'\n  end.\n(* {END} *)\nHint Unfold repeat_make_tuple : charfun.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_repeat_make_tuple_base_case :\n  forall (ys : tuple) (a : nat),\n    repeat_make_tuple ys a 0 = ys.\nProof.\n  intros ys a.\n  unfold repeat_make_tuple.\n  reflexivity.\nQed.\nHint Rewrite unfold_repeat_make_tuple_base_case : charfun.\n\nLemma unfold_repeat_make_tuple_induction_case :\n  forall (ys : tuple) (a n' : nat),\n    repeat_make_tuple ys a (S n') =\n    repeat_make_tuple (make_tuple ys a) a n'.\nProof.\n  intros ys a n'.\n  unfold repeat_make_tuple; fold repeat_make_tuple.\n  reflexivity.\nQed.\nHint Rewrite unfold_repeat_make_tuple_induction_case : charfun.\n\n(** *** Properties *)\n\nLemma repeat_make_tuple_nil :\n  forall (a n : nat),\n    repeat_make_tuple [] a n = [].\nProof.\n  intros a n; revert a.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intro a.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intro a.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_make_tuple_base_case_nil.\n  exact (IH_n' a).\nQed.\nHint Rewrite repeat_make_tuple_nil : charfun.\n\nLemma repeat_make_tuple_l_eq_0 :\n  forall (ys : tuple) (n : nat),\n    (length ys) <= n ->\n    repeat_make_tuple ys 0 n = [].\nProof.\n  intros ys n; revert ys.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros ys H_length_ys_le_0.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  inversion H_length_ys_le_0;\n   rename H0 into H_length_ys_eq_0.\n  rewrite -> (length_nil_0 ys H_length_ys_eq_0).\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros ys H_length_ys_le_S_n'.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> IH_n'.\n  reflexivity.\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_make_tuple_base_case_nil.\n  rewrite -> unfold_length_base_case.\n  exact (le_0_n n').\n\n  SCase \"ys = y :: ys'\".\n  case ys' as [ | y' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_length_base_case.\n  exact (le_0_n n').\n\n  SSCase \"ys' = y' :: ys''\".\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite -> unfold_length_induction_case.\n  rewrite -> S_length_make_tuple.\n  rewrite -> unfold_length_induction_case.\n  rewrite ->2 unfold_length_induction_case in H_length_ys_le_S_n'.\n  rewrite -> (le_S_n (S (length ys'')) n');\n    [ reflexivity | exact H_length_ys_le_S_n' ].\nQed.\nHint Resolve repeat_make_tuple_l_eq_0 : charfun.\n\n(* {SHIFT_MAKE_TUPLE_IN_REPEAT_MAKE_TUPLE} *)\nLemma shift_make_tuple_in_repeat_make_tuple :\n  forall (ys : tuple) (n a : nat),\n    make_tuple (repeat_make_tuple ys a n) a =\n    repeat_make_tuple (make_tuple ys a) a n.\n(* {END} *)\nProof.\n  intros ys n a; revert ys a.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros ys a.\n  rewrite ->2 unfold_repeat_make_tuple_base_case.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros ys a.\n  rewrite ->2 unfold_repeat_make_tuple_induction_case.\n  rewrite -> (IH_n' (make_tuple ys a) a).\n  reflexivity.\nQed.\nHint Rewrite shift_make_tuple_in_repeat_make_tuple : charfun.\n\nLemma length_repeat_make_tuple :\n  forall (ys : tuple) (a n : nat),\n    length (repeat_make_tuple ys a n) = (length ys) - n.\nProof.\n  intros ys a n; revert ys a.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros ys a.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  rewrite <- minus_n_O.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros ys a.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> IH_n'.\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_make_tuple_base_case_nil.\n  rewrite -> unfold_length_base_case.\n  unfold minus.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  case ys' as [ | y' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_length_base_case.\n  rewrite -> unfold_length_induction_case.\n  rewrite -> unfold_length_base_case.\n  unfold minus.\n  reflexivity.\n\n  SSCase \"ys' = y' :: ys''\".\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite -> unfold_length_induction_case.\n  rewrite -> S_length_make_tuple.\n  rewrite ->3 unfold_length_induction_case.\n  rewrite -> NPeano.Nat.sub_succ.\n  reflexivity.\nQed.\nHint Rewrite length_repeat_make_tuple : charfun.\n\n(** ** Correctness proof of repeat_make_tuple and rotated_moessner_entry *)\n\n(* {REPEAT_MAKE_TUPLE_ROTATED_MOESSNER_ENTRIES} *)\nTheorem repeat_make_tuple_rotated_moessner_entries :\n  forall (c l n t : nat),\n    repeat_make_tuple\n      (Str_prefix (c + l) (rotated_moessner_entries n 0 0 t)) 0 c =\n    Str_prefix l (rotated_moessner_entries n 0 c t).\n(* {END} *)\nProof.\n  induction c as [ | c' IH_c' ].\n\n  Case \"c = 0\".\n  intros l n t.\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.\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).\n  rewrite -> make_tuple_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite repeat_make_tuple_rotated_moessner_entries : charfun.\n\n(* {REPEAT_MAKE_TUPLE_MONOMIALS_EQ_MOESSNER_ENTRIES} *)\nCorollary repeat_make_tuple_monomials_eq_moessner_entries :\n  forall (c l n t : nat),\n    repeat_make_tuple\n      (Str_prefix (S c + l) (monomials t n 0)) 0 (S c) =\n    Str_prefix l (rotated_moessner_entries n 0 c t).\n(* {END} *)\nProof.\n  intros c l n t.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> plus_Sn_m.\n  rewrite -> make_tuple_monomials_eq_monomials_sum.\n  rewrite -> rotated_moessner_entries_bisim_monomials_sum.\n  rewrite -> repeat_make_tuple_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite repeat_make_tuple_monomials_eq_moessner_entries : charfun.\n\n(* {REPEAT_MAKE_TUPLE_MONOMIALS_EQ_MOESSNER_ENTRIES_GENERAL} *)\nLemma repeat_make_tuple_monomials_eq_moessner_entries_general :\n  forall (k j n t : nat),\n    j <= k ->\n    Str_prefix (k - j) (rotated_moessner_entries n 0 j t) =\n    repeat_make_tuple (Str_prefix (S k) (monomials t n 0)) 0 (S j).\n(* {END} *)\nProof.\n  induction k as [ | k' IH_k' ].\n\n  Case \"k = 0\".\n  intros j n t H_j_le_0.\n  unfold minus.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> 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 H_0_le_S_k'.\n  rewrite <- minus_n_O.\n  rewrite <- repeat_make_tuple_monomials_eq_moessner_entries.\n  reflexivity.\n\n  SCase \"j = S j'\".\n  intros n t 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);\n    [ idtac | apply lt_le_weak; unfold lt; exact H_S_j_le_S_k ].\n  rewrite <- make_tuple_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_monomials_eq_moessner_entries_general : charfun.\n\n(** *** Prove relation between [repeat_make_tuple]\n  and [create_triangle_vertically] *)\n\n(* {SHIFT_MAKE_TUPLE_CREATE_TRIANGLE_VERTICALLY} *)\nLemma shift_make_tuple_create_triangle_vertically :\n  forall (j' : nat) (ys : tuple),\n   make_tuple\n     (nth j'\n          (create_triangle_vertically\n             (tuple_constant (length ys) 0) ys) []) 0 =\n   nth (S j')\n       (create_triangle_vertically\n          (tuple_constant (length ys) 0) ys) [].\n(* {END} *)\nProof.\n  induction j' as [ | j'' IH_j'' ].\n\n  Case \"j' = 0\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_length_base_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_nil.\n  rewrite -> unfold_nth_base_case_nil.\n  rewrite -> unfold_make_tuple_base_case_nil.\n  rewrite -> nth_n_nil.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  case ys' as [ | y' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_length_induction_case.\n  rewrite -> unfold_length_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_nth_base_case_nil.\n  rewrite -> unfold_make_tuple_base_case_nil.\n  rewrite -> nth_n_nil.\n  reflexivity.\n\n  SSCase \"ys' = y' :: ys''\".\n  case ys'' as [ | y'' ys''' ].\n\n  SSSCase \"ys'' = []\".\n  rewrite ->2 unfold_length_induction_case.\n  rewrite -> unfold_length_base_case.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_x_nil.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> unfold_nth_induction_case_cons.\n  rewrite -> unfold_nth_base_case_nil.\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  reflexivity.\n\n  SSSCase \"ys'' = y'' :: ys'''\".\n  rewrite ->3 unfold_length_induction_case.\n  rewrite ->3 unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_create_triangle_vertically_induction_case.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> unfold_nth_induction_case_cons.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\n\n  Case \"j' = S j''\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_length_base_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_nil.\n  rewrite ->2 nth_n_nil.\n  rewrite -> unfold_make_tuple_base_case_nil.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  case ys' as [ | y' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_length_induction_case.\n  rewrite -> unfold_length_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 ->2 nth_n_nil.\n  rewrite -> unfold_make_tuple_base_case_nil.\n  reflexivity.\n\n  SSCase \"ys' = y' :: ys''\".\n  symmetry.\n  rewrite ->2 unfold_length_induction_case.\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_length_induction_case y' ys'').\n  rewrite -> unfold_nth_induction_case_cons.\n  rewrite <- (S_length_make_tuple ys'' y' 0).\n  rewrite <- (unfold_length_induction_case y (make_tuple (y' :: ys'') 0)).\n  rewrite -> unfold_nth_induction_case_cons.\n\n  assert (H: (length (y :: make_tuple (y' :: ys'') 0)) =\n             (length (make_tuple (y :: y' :: ys'') 0))).\n    rewrite -> unfold_length_induction_case.\n    rewrite -> unfold_make_tuple_induction_case.\n    rewrite -> unfold_length_induction_case.\n    rewrite -> plus_0_r.\n    rewrite -> (length_tuples_xs_a_eq_ys_b\n                  (y' :: ys'')\n                  (y' :: ys'')\n                  0\n                  y); reflexivity.\n\n  rewrite -> H; clear H.\n  rewrite <- (IH_j'' (make_tuple (y :: y' :: ys'') 0)).\n  reflexivity.\nQed.\nHint Rewrite shift_make_tuple_create_triangle_vertically : charfun.\n\n(* {CORRECTNESS_OF_REPEAT_MAKE_TUPLE} *)\nTheorem correctness_of_repeat_make_tuple :\n  forall (j : nat) (ys : tuple),\n    (repeat_make_tuple ys 0 (S j)) =\n    (nth j (create_triangle_vertically\n              (tuple_constant (length ys) 0)\n              ys)\n         []).\n(* {END} *)\nProof.\n  induction j as [ | j' IH_j' ].\n\n  Case \"j = 0\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  rewrite -> unfold_make_tuple_base_case_nil.\n\n  rewrite -> unfold_length_base_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_nil.\n  rewrite -> unfold_nth_base_case_nil.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  case ys' as [ | x' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n\n  rewrite -> unfold_length_induction_case.\n  rewrite -> unfold_length_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_nth_base_case_nil.\n  reflexivity.\n\n  SSCase \"ys' = y' :: ys''\".\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite -> plus_0_r.\n\n  rewrite ->2 unfold_length_induction_case.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  Case \"j = S j'\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_length_base_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_nil.\n  rewrite -> unfold_nth_induction_case_nil.\n\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_make_tuple_base_case_nil.\n\n  rewrite -> repeat_make_tuple_l_eq_0;\n    [ reflexivity | rewrite -> unfold_length_base_case; exact (le_O_n j') ].\n\n  SCase \"ys = y :: ys''\".\n  case ys' as [ | y' ys'' ].\n\n  SSCase \"ys' = []\".\n  rewrite -> unfold_length_induction_case.\n  rewrite -> unfold_length_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_nth_induction_case_nil.\n\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_make_tuple_base_case_nil.\n\n  rewrite -> repeat_make_tuple_l_eq_0;\n    [ reflexivity | rewrite -> unfold_length_base_case; exact (le_O_n j') ].\n\n  SSCase \"ys' = y' :: ys''\".\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite <- shift_make_tuple_in_repeat_make_tuple.\n  rewrite -> (IH_j' (y :: y' :: ys'')).\n  rewrite -> shift_make_tuple_create_triangle_vertically.\n  reflexivity.\nQed.\nHint Rewrite correctness_of_repeat_make_tuple : charfun.\n\n(* {CORRECTNESS_OF_ROTATED_MOESSNER_ENTRY} *)\nTheorem correctness_of_rotated_moessner_entry :\n  forall (i j r t : 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)) (monomials t r 0)))\n              [])\n         0) =\n    rotated_moessner_entry r i j t.\n(* {END} *)\nProof.\n  intros i j r t 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)) (monomials t r 0)))).\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)) (monomials t r 0))) 0)).\n    f_equal.\n    exact H_length_helper.\n\n  rewrite -> H_rewrite_helper; clear H_length_helper H_rewrite_helper.\n\n  rewrite <- correctness_of_repeat_make_tuple.\n\n  rewrite <- repeat_make_tuple_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_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Resolve correctness_of_rotated_moessner_entry : charfun.", "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/CharacteristicFunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7643846822938045}}
{"text": "Require Import Frap Pset3aSig.\n\n(* The [Prog] datatype defines abstract syntax trees for this language.\n *)\n\nPrint Prog.\n\n\n(* Define [run] such that [run p n] gives the final state\n * that running the program [p] should result in, when the\n * initial state is [n].\n *)\nFixpoint run (p : Prog) (initState : nat) : nat :=\nmatch p with\n| Done  => initState\n| AddThen a b   => run b (initState+a)\n| MulThen a b   => run b (initState*a)\n| SetToThen a b => run b a\nend.\n\nTheorem run_Example1 : run Done 0 = 0.\nProof.\n  simplify. equality.\nQed.\n\nTheorem run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7.\nProof.\n  simplify. equality.\nQed.\n\nTheorem run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6.\nProof.\n  simplify. equality.\nQed.\n\n(* Define [numInstructions] to compute the number of instructions\n * in a program, not counting [Done] as an instruction.\n *)\n\n(* We will define a utlity function that will be used to compute the number of instructions *)\nFixpoint numinsutil (p: Prog) (count:nat) :nat := \nmatch p with \n| Done => count\n| AddThen a b => numinsutil b (count+1)\n| MulThen a b => numinsutil b (count+1)\n| SetToThen a b => numinsutil b (count+1)\nend.\n\nDefinition numInstructions (p : Prog) : nat := numinsutil p 0.\n\nTheorem numInstructions_Example :\n  numInstructions (MulThen 5 (AddThen 2 Done)) = 2.\nProof.\n  simplify. equality.\nQed.\n\n(* Define [concatProg] such that [concatProg p1 p2] is the program\n * that first runs [p1] and then runs [p2].\n *)\nFixpoint concatProg (p1 p2 : Prog) : Prog := match p1 with \n| Done => p2\n| AddThen a b   => AddThen a (concatProg b p2)\n| MulThen a b   => MulThen a (concatProg b p2)\n| SetToThen a b => SetToThen a (concatProg b p2)\nend.\n\nTheorem concatProg_Example :\n     concatProg (AddThen 1 Done) (MulThen 2 Done)\n     = AddThen 1 (MulThen 2 Done).\nProof.\n  simplify. equality.\nQed.\n\n(* Prove that the number of instructions in the concatenation of\n * two programs is the sum of the number of instructions in each\n * program.\n *)\n\n(* We will use the following lemma in the proof for the theorem *)\nLemma util_val: forall (p1: Prog) (v:nat), numinsutil p1 v = v + numinsutil p1 0.\nProof.\n  simplify.\n  induct p1.\n    (* Initial proof based on case by case analysis *)\n    \n      - simplify. ring.\n    - unfold numinsutil. simplify. rewrite IHp1. fold numinsutil. rewrite -> (IHp1 1). linear_arithmetic.\n    - unfold numinsutil. simplify. rewrite IHp1. fold numinsutil. rewrite -> (IHp1 1). linear_arithmetic.\n    - unfold numinsutil. simplify. rewrite IHp1. fold numinsutil. rewrite -> (IHp1 1). linear_arithmetic.\n     \n    (* Try to perform proof automation *)\n    (* \n      try match goal with \n      | [ |- numinsutil Done = _ ] => simplify; ring\n      | _ => unfold numinsutil; simplify; rewrite IHp1; fold numinsutil; rewrite -> (IHp1 1); linear_arithmetic\n      end.\n    *)     \nQed.\n\n\nTheorem concatProg_numInstructions\n  : forall (p1 p2 : Prog), numInstructions (concatProg p1 p2)\n                      = numInstructions p1 + numInstructions p2.\nProof.\n  induct p1.\n   - simplify. equality.   \n   - unfold concatProg. simplify. fold concatProg. unfold numInstructions in IHp1. unfold numInstructions.\n     simplify. rewrite (util_val p1 1). rewrite (util_val (concatProg p1 p2) 1). rewrite IHp1. linear_arithmetic.\n   - unfold concatProg. simplify. fold concatProg. unfold numInstructions in IHp1. unfold numInstructions.\n     simplify. rewrite (util_val p1 1). rewrite (util_val (concatProg p1 p2) 1). rewrite IHp1. linear_arithmetic.\n   - unfold concatProg. simplify. fold concatProg. unfold numInstructions in IHp1. unfold numInstructions.\n     simplify. rewrite (util_val p1 1). rewrite (util_val (concatProg p1 p2) 1). rewrite IHp1. linear_arithmetic.\n\n(* \nall:   unfold concatProg; simplify; fold concatProg; unfold numInstructions in IHp1; unfold numInstructions;\n     simplify; rewrite (util_val p1 1); rewrite (util_val (concatProg p1 p2) 1); rewrite IHp1; linear_arithmetic.\n*)\nQed.           \n\n\n(* Prove that running the concatenation of [p1] with [p2] is\n   equivalent to running [p1] and then running [p2] on the\n   result. *)\nTheorem concatProg_run\n  : forall (p1 p2 : Prog) (initState : nat),\n    run (concatProg p1 p2) initState =\n    run p2 (run p1 initState).\nProof.\n    induct p1.\n      - simplify. equality.\n      - simplify. rewrite (IHp1 (p2) (initState+n)). equality.\n      - simplify. rewrite (IHp1 (p2) (initState*n)). equality.\n      - simplify. rewrite (IHp1 (p2) (n)). equality.\nQed.\n\n(* Ignore the below lines: *)\n(*\nLemma dum: forall (p:Prog), numinsutil p 0 = numInstructions p.\nProof.\n  simplify.\n  unfold numInstructions. rewrite numInstructions.\n  linear_arithmetic.\nAdmitted.\n*)\n(* Lemma concatProg_numInstructions\n  : forall (p1 p2 : Prog) (v:nat), numinsutil (concatProg p1 p2) v\n                      = numinsutil p1 v + numinsutil p2 0.\nProof. \n  induct p1.\n    - simplify.\n*)\n", "meta": {"author": "nvvishnu", "repo": "CS6225-Programs-and-Proofs", "sha": "6faa7d6a880b2243551086b562a292303724032e", "save_path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs", "path": "github-repos/coq/nvvishnu-CS6225-Programs-and-Proofs/CS6225-Programs-and-Proofs-6faa7d6a880b2243551086b562a292303724032e/pset3/Pset3a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.7643606665323889}}
{"text": "Require Import ssreflect.\nRequire Import Ensembles.\n\nVariable U : Type.\n\n\nLemma in_complements_notin_union: forall (A B: Ensemble U) (x: U),\n    In U (Complement U A) x -> In U (Complement U B) x -> \n        ~ In U (Union U A B) x.\nProof.\nintros.\n\n(* unfold not. *)\nmove=> inAuB.\ndestruct inAuB.\n\n(* case x \\in A *)\ndestruct H.\napply H1.\n\n(* case x \\in B *)\ndestruct H0.\napply H1.\nQed.\n\n(* What is a sensible way to generate proofs where the goal includes a negation, given \nthat the Coq standard library defines `~ P` as `P -> False`? *)\n\nLemma demorgan1: forall A B: Ensemble U, \n    Included U \n        (Intersection U (Complement U A) (Complement U B)) \n        (Complement U (Union U A B)).\nProof.\nintros. \nmove=> U1. (* Why do I need this one? something strange about the way the universe type U interacts with the definitions. *)\nmove=> inA.\ndestruct inA.   \napply in_complements_notin_union.\napply H.\napply H0. Show Proof.\nQed.\n\nLemma union_subset_bigger_union: forall A B C: Ensemble U,\n    Included U\n        (Union U A B)\n        (Union U A (Union U B C)).\nProof. \n    intros. \n    move=> U1. \n    move=> inAuB.\n    (* destruct inAuB. *)\n    case inAuB.\n    (* Case 1, x \\in A *)\n    intros.\n    apply Union_introl.\n    apply H.\n    (* Case 2, x \\in B*)\n    intros.\n    apply Union_intror.\n    apply Union_introl.\n    apply H. Show Proof.\nQed.\n    \n(* TODO why does using case un-introduce variables so I then have to use intros?*)\n\n(* Doing this stuff with `In` is weird because it should be translated the same as `:` for the \nproofs that I want to write I guess? But its really annoying to deal with and makin that \nhappen is going to be a pain. This *is* related to the U thing from above *)\n\n(* TODO can I have all the Ensemble stuff automatically parametrised by U throughout so that I \ndon't have to keep explicitly stating it? *)", "meta": {"author": "SethPoulsen", "repo": "robottwo", "sha": "8622f01263416684bb50f93df086b90c40086c20", "save_path": "github-repos/coq/SethPoulsen-robottwo", "path": "github-repos/coq/SethPoulsen-robottwo/robottwo-8622f01263416684bb50f93df086b90c40086c20/extra/sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7642747492660299}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Omega.\n\nTheorem list_in_dec : forall (x : nat) (X : list nat), {In x X} + { ~ In x X}.\nProof.\n  apply in_dec.\n  apply eq_nat_dec.\nDefined.\n\nDefinition list_eq X Y :=\n  forall x : nat, In x X <-> In x Y.\n\nTheorem incl_list_eq : forall X Y, list_eq X Y <-> incl X Y /\\ incl Y X.\nProof.\n  intros.\n  split;\n  unfold list_eq.\n  intros.\n  unfold incl.\n  split;\n  intros;\n  specialize (H a);\n  intuition.\n  intros.\n  destruct H.\n  unfold incl in *.\n  split;\n  intros;\n  specialize (H x);\n  specialize (H0 x);\n  intuition.\nQed.\n\nTheorem incl_dec : forall X Y : list nat, {incl X Y} + {~ incl X Y}.\nProof.\n  intros.\n  induction X.\n  left.\n  unfold incl.\n  intros.\n  inversion H.\n  destruct IHX.\n  assert ({In a Y} + {~In a Y}).\n  apply in_dec.\n  apply eq_nat_dec.\n  destruct H;\n  [left | right].\n  unfold incl.\n  intros.\n  simpl In in *.\n  intuition.\n  replace a0;\n  intuition.\n  unfold not.\n  intros.\n  apply n.\n  unfold incl in H.\n  specialize (H a).\n  apply H;\n  intuition.\n  right.\n  unfold not;\n  intros.\n  apply n.\n  unfold incl in *.\n  intros.\n  specialize (H a0).\n  apply H.\n  intuition.\nDefined.\n\nTheorem list_eq_dec : forall X Y, {list_eq X Y} + {~ list_eq X Y}.\nProof.\n  intros.\n  assert ( {incl X Y} + {~ incl X Y}).\n  apply incl_dec.\n  assert ({incl Y X} + {~ incl Y X} ).\n  apply incl_dec.\n  destruct H;\n  destruct H0;\n  [left | right | right | right];\n  unfold not; \n  intros.\n  apply incl_list_eq.\n  intuition.\n  apply n.\n  apply incl_list_eq in H.\n  intuition.\n  apply n.\n  apply incl_list_eq in H.\n  intuition.\n  apply n.\n  apply incl_list_eq in H.\n  intuition.\nDefined. \n\nTheorem list_eq_ref :\n  forall L, list_eq L L.\nProof. \n  intros.\n  unfold list_eq.\n  intuition.\nQed.\n\nTheorem list_eq_symmetric :\n  forall X Y, list_eq X Y -> list_eq Y X.\nProof.\n  intros.\n  unfold list_eq in *.\n  intuition;\n  apply H;\n  intuition.\nQed.\n\nTheorem list_eq_trans :\n  forall X Y Z, list_eq X Y -> list_eq Y Z -> list_eq X Z.\nProof.\n  intros.\n  unfold list_eq in *.\n  intuition.\n  apply H0.\n  apply H.\n  intuition.\n  apply H.\n  apply H0.\n  intuition.\nQed.\n\nFixpoint LeastElem (X : list nat) : option nat := \n  match X with\n  | nil => None\n  | cons x X' =>\n      match LeastElem X' with\n      | None => Some x\n      | Some y =>  if (lt_dec x y) then Some x else Some y\n      end\n  end.\n\nTheorem LeastElem_spec1 : forall X : list nat, X = nil <-> LeastElem X = None.\nProof.\n  intros.\n  split;\n  intros.\n  replace X.\n  reflexivity.\n  destruct X.\n  reflexivity.\n  simpl LeastElem in H.\n  destruct LeastElem.\n  destruct lt_dec in H;\n  inversion H.\n  inversion H.\nQed.\n\nTheorem LeastElem_spec2 : forall X : list nat, X <> nil <-> exists x : nat,  LeastElem X = Some x.\nProof.\n  split;\n  intros.\n  case_eq X;\n  intuition.\n  simpl LeastElem.\n  case LeastElem.\n  intros.\n  destruct lt_dec;\n  [exists n | exists n0];\n  intuition.\n  exists n.\n  intuition.\n  case_eq X.\n  intros.\n  replace X in H.\n  destruct H.\n  simpl LeastElem in H.\n  inversion H.\n  unfold not.\n  intros.\n  inversion H1.\nQed. \n\nTheorem LeastElemDec : forall (x : nat) (X : list nat), {LeastElem X = Some x} + {LeastElem X <> Some x}.\nProof.\n  intros.\n  destruct LeastElem.\n  assert ({n = x} + {n <> x}).\n  apply eq_nat_dec.\n  destruct H as [H | H]; [left | right].\n    replace n. intuition.\n    unfold not. intros negH.\n    inversion negH. intuition.\n  right. unfold not; intros negH ; inversion negH.\nQed.\n\nTheorem LeastElem_spec3 : forall (x : nat) (X : list nat), LeastElem X = Some x -> In x X.\nProof.\n  intros.\n  induction X.\n  assert (LeastElem nil = None).\n  apply LeastElem_spec1.\n  intuition.\n  replace (LeastElem nil) in H.\n  inversion H.\n  simpl LeastElem in H.\n  destruct (LeastElem X).\n  destruct lt_dec in H;\n  inversion H;\n  replace x;\n  intuition.\n  replace n;\n  intuition.  \n  inversion H.\n  intuition.\nQed.\n\nTheorem LeastElem_decons1 : forall (x y : nat) (X : list nat), LeastElem X = Some y -> (x <= y <-> LeastElem (cons x X) = Some x).\nProof.\n  split;\n  intros.\n  simpl LeastElem.\n  replace (LeastElem X).\n  destruct lt_dec.\n  intuition.\n  assert (x = y).\n  omega.\n  intuition.\n  simpl LeastElem in H0.\n  replace (LeastElem X) in H0.\n  destruct lt_dec in H0.\n  omega.\n  inversion H0.\n  omega.\nQed.\n\nTheorem LeastElem_decons2 : forall (x y : nat) (X : list nat), LeastElem X = Some y -> (y <= x <-> LeastElem (cons x X) = Some y).\nProof.\n  split;\n  intros.\n  simpl LeastElem.\n  replace (LeastElem X).\n  destruct lt_dec.\n  assert (x = y).\n  omega.\n  intuition.\n  intuition.\n  simpl LeastElem in H0.\n  replace (LeastElem X) in H0.\n  destruct lt_dec in H0.\n  inversion H0.\n  omega.\n  omega.\nQed.\n\nTheorem LeastElem_spec4 :\n  forall (X : list nat),  LeastElem X = None \\/ (exists x : nat, LeastElem X = Some x /\\ (forall y : nat, In y X -> x <= y)).\nProof.  \n  intros.\n  induction X.\n  left. reflexivity.\n  right.\n  destruct IHX.\n  exists a.\n  apply LeastElem_spec1 in H.\n  replace X. simpl. intuition.\n  destruct H.\n  destruct H as [H0 H1].\n  assert (H : {x <= a} + {a < x}).\n  apply le_lt_dec.\n  destruct H as [H | H].\n  exists x.\n  simpl LeastElem.\n  replace (LeastElem X).\n  destruct lt_dec.\n  split; intros ; omega.\n  split ; intuition.\n  simpl In in H2.\n  destruct H2 as [H2 | H2].\n  omega.\n  apply H1; intuition.\n  exists a.\n  simpl LeastElem.\n  replace (LeastElem X).\n  destruct lt_dec.\n  split; intros.\n  intuition.\n  simpl In in H2.\n  destruct H2 as [H2 | H2].\n  omega.\n  apply H1 in H2. omega.\n  intuition.\nQed.\n\nFixpoint Subtract_list (X Y : list nat) :=\n  match X with\n  | nil => nil\n  | cons x X' =>\n     if list_in_dec x Y\n       then Subtract_list X' Y\n       else cons x (Subtract_list X' Y)\n  end.\n\nTheorem Subtract_list_r_nil : forall X : list nat, Subtract_list X nil = X.\nProof.\n  intros.\n  induction X.\n  simpl. reflexivity.\n  simpl.\n  rewrite -> IHX.\n  reflexivity.\nQed.\n\nTheorem Subtract_list_l_nil : forall X : list nat, Subtract_list nil X = nil.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem Subtract_list_spec : forall (x : nat) (X Y : list nat),  In x (Subtract_list X Y) <-> (In x X /\\ ~ In x Y).\n  split; \n  intros.\n  induction X.\n  simpl Subtract_list in H.\n  inversion H.\n  simpl Subtract_list in H.\n  destruct list_in_dec.\n  apply IHX in H.\n  simpl In. intuition.\n  simpl In in H.\n  destruct H.\n  replace x.\n  intuition.\n  apply IHX in H.\n  simpl In. intuition.\n  destruct H as [H H0].\n  induction X.\n  inversion H.\n  simpl In in H.\n  destruct H as [H | H];\n  simpl Subtract_list; \n  destruct list_in_dec.\n  replace a in i. intuition.\n  replace x. intuition.\n  apply IHX. intuition.\n  apply IHX in H.\n  simpl In.\n  intuition.\nQed.\n (*Finds the smallest element of X, but not Y*)\nDefinition delta_min ( X Y : list nat) : option nat := \n  LeastElem (Subtract_list X Y).    \n\n  (*Let's prove it!*)\nTheorem delta_min_dec : forall X Y : list nat,\n  delta_min X Y = None \\/\n  (exists x : nat,\n    delta_min  X Y = Some x /\\\n                     In x X /\\\n                     ~ In x Y /\\\n                     forall y : nat, In y X -> ~ In y Y -> x <= y).\nProof.\n  intros.\n  unfold delta_min.\n  assert ( forall (X : list nat),  LeastElem X = None \\/ (exists x : nat, LeastElem X = Some x /\\ (forall y : nat, In y X -> x <= y))).\n  apply LeastElem_spec4.\n  specialize (H (Subtract_list X Y)).\n  destruct H.\n  intuition.\n  right.\n  destruct H.\n  exists x.\n  destruct H.\n  split.\n  exact H.\n  assert (In x X /\\ ~ In x Y).\n  apply Subtract_list_spec.\n  apply LeastElem_spec3.\n  exact H.\n  split; intuition.\n  assert (In y (Subtract_list X Y)).\n  apply Subtract_list_spec.\n  intuition.\n  apply H0.\n  intuition.\nQed.\n\nTheorem delta_min_disj : forall X Y : list nat, delta_min X Y = None \\/ delta_min X Y <> delta_min Y X.\nProof.\n  intros.\n  assert (delta_min X Y = None \\/ (exists x : nat,\n                                    delta_min  X Y = Some x /\\\n                                    In x X /\\\n                                    ~ In x Y /\\\n                                    forall y : nat, In y X -> ~ In y Y -> x <= y)).\n  apply delta_min_dec.\n  assert (delta_min Y X = None \\/ (exists y : nat,\n                                    delta_min  Y X = Some y /\\\n                                    In y Y /\\\n                                    ~ In y X /\\\n                                    forall x : nat, In x Y -> ~ In x X -> y <= x)).\n  apply delta_min_dec.\n  destruct H. intuition.\n  destruct H0.\n  destruct H. destruct H.  right. replace (delta_min X Y). replace (delta_min Y X). intuition.  inversion H2.\n  right.\n  unfold not. intros.\n  destruct H. destruct H0. intuition.\n  rewrite -> H2 in H1. rewrite -> H in H1.\n  inversion H1.\n  rewrite <- H9 in H3.\n  intuition.\nQed.\n\nTheorem delta_min_l_nil : forall  X, delta_min X nil = LeastElem X.\nProof.\n  intros.\n  unfold delta_min.\n  rewrite -> Subtract_list_r_nil.\n  reflexivity.\nQed.\n\nTheorem delta_min_r_nil : forall X, delta_min nil X = None.\nProof.\n  intros.\n  unfold delta_min.\n  rewrite -> Subtract_list_l_nil.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem delta_min_subs : forall X Y : list nat, delta_min X Y = None <-> forall x : nat, In x X -> In x Y.\nProof.\n  split; intros.\n  unfold delta_min in H.\n  induction X.\n  inversion H0.\n  simpl LeastElem in H.\n  destruct list_in_dec in H.\n    simpl In in H0. destruct H0.\n    replace a in i. intuition.\n    apply IHX. intuition.\n    exact H0.\n  assert (exists n : nat,  LeastElem (a :: Subtract_list X Y) = Some n).\n    apply LeastElem_spec2.\n    unfold not. intros. inversion H1.\n  destruct H1.\n  rewrite H1 in H. inversion H.\n  induction X.\n  simpl.\n  simpl.\n  rewrite -> delta_min_r_nil.\n  intuition.\n  unfold delta_min.\n  simpl.\n  destruct list_in_dec.\n  apply IHX.\n  intros. apply H. simpl. right. exact H0.\n  assert (In a (a::X)).\n  intuition.\n  specialize H.\n  apply H in H0.\n  intuition.\nQed.\n\nInductive list_order :=\n| lt_list : list_order\n| eq_list : list_order\n| gt_list : list_order.\n\nFixpoint dec_order (X Y : list nat) : list_order :=\n  match delta_min X Y with\n  | None =>\n      match delta_min Y X with\n      | None => eq_list \n      | Some y => gt_list\n      end\n  | Some x =>\n      match delta_min Y X with\n      | None => lt_list \n      | Some y => \n          if lt_dec x y\n          then lt_list \n          else gt_list\n      end\n  end.\n\n(*Connexity of the above program *)\nTheorem dec_order_dec : forall X Y : list nat, {dec_order X Y = lt_list} + {dec_order X Y = eq_list} + {dec_order X Y = gt_list}.\nProof.\n  intros.\n  destruct dec_order; intuition.\nQed.\n\nTheorem dec_order_nil_l_neg : forall X Y : list nat, dec_order nil X <> lt_list.\nProof.\n  intros.\n  simpl.\n  destruct delta_min;\n  intuition; inversion H.\nQed.\n\nTheorem dec_order_nil_r_neg : forall X Y : list nat, dec_order X nil <> gt_list.\nProof.\n  intros.\n  destruct X.\n  simpl; unfold not; intros; inversion H.\n  unfold dec_order.\n  rewrite -> delta_min_r_nil.\n  destruct delta_min;\n  unfold not;\n  simpl; intros; inversion H.\nQed.\n\nExample dec_order_nil : forall X Y : list nat, dec_order nil nil = eq_list.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n  (*Show that dec_order's eq is equivalent to the membership def in list_eq *)\nTheorem dec_order_eq_spec : forall X Y : list nat, dec_order X Y = eq_list <-> list_eq X Y.\nProof.\n  intros.\n  unfold list_eq.\n  split; intros.\n  assert (delta_min X Y = None).\n    unfold dec_order in H.\n    destruct X; destruct Y;\n    destruct delta_min;\n      try (destruct lt_dec; inversion H); try intuition.\n      destruct delta_min. destruct lt_dec. inversion H.\n      inversion H. inversion H.\n      destruct delta_min. destruct lt_dec.\n      inversion H. inversion H. inversion H.\n      destruct delta_min. destruct lt_dec.\n      inversion H. inversion H. inversion H.\n  assert (delta_min Y X = None).\n    unfold dec_order in H.\n    destruct X; destruct Y;\n    destruct delta_min;\n      try (destruct lt_dec; inversion H); try intuition.\n      destruct delta_min. destruct lt_dec. inversion H.\n      inversion H. inversion H.\n      destruct delta_min.\n        inversion H. reflexivity.\n        destruct delta_min. destruct lt_dec.\n        inversion H. inversion H. inversion H.\n        destruct delta_min. inversion H. reflexivity.\n  split; apply delta_min_subs; intuition.\n  assert (delta_min X Y = None).\n    apply delta_min_subs.\n    apply H.\n  assert (delta_min Y X = None).\n    apply delta_min_subs.\n    apply H.\n  destruct X.\n  simpl. rewrite -> H1. reflexivity.\n  simpl. rewrite -> H0. rewrite -> H1. reflexivity.\nQed.\n\n(*Show that lt is the dual of gt *)\nTheorem dec_order_dual_spec : forall X Y : list nat, dec_order X Y = lt_list <-> dec_order Y X = gt_list.\nProof.\n  split;\n  intros.\n  unfold dec_order in *.\n  destruct Y; destruct X; simpl in *.\n    inversion H.\n    destruct delta_min.\n      intuition.\n      inversion H.\n    destruct delta_min.\n      intuition.\n      inversion H.\n    destruct delta_min;\n    destruct delta_min.\n    destruct lt_dec; destruct lt_dec;\n    try omega; try reflexivity; try inversion H.\n    reflexivity. inversion H. inversion H.\n  unfold dec_order in *.\n  destruct Y; destruct X; simpl in *.\n    inversion H.\n    destruct delta_min.\n      intuition.\n      inversion H.\n    destruct delta_min.\n      intuition.\n      inversion H.\n    remember (delta_min (n0 :: X) (n :: Y)) as i.\n    remember (delta_min (n :: Y) (n0 :: X)) as j.\n    assert (i <> j).\n    unfold not; intros.\n      assert (~ (j = None /\\ i = None)).\n        unfold not; intros.\n        destruct H1.\n        rewrite -> H1 in H.\n        rewrite -> H2 in H.\n        inversion H.\n      assert (delta_min (n0 :: X) (n :: Y) = None \\/ delta_min (n0 :: X) (n :: Y) <> delta_min (n :: Y) (n0 :: X)).\n      apply delta_min_disj.\n      destruct H2. rewrite -> H2 in Heqi. rewrite -> Heqi in H0.\n      apply H1. split. intuition. intuition.\n      rewrite <- Heqi in H2. rewrite <- Heqj in H2.\n      intuition.\n    destruct delta_min; destruct delta_min;\n      replace i in H0; replace j in H0;\n      rewrite -> Heqj in H; rewrite -> Heqi in H; replace i; replace j.\n    destruct lt_dec; destruct lt_dec.\n      reflexivity.\n      inversion H.\n      reflexivity.\n      assert (n1 = n2). omega. assert (Some n1 = Some n2). intuition. intuition.\n      reflexivity.\n      inversion H.\n      intuition.\nQed.\n\nTheorem delta_min_in : forall (x : nat) (X Y : list nat), delta_min X Y = Some x -> In x X.\nProof.\n  intros x X Y H0.\n  assert (delta_min X Y = None \\/\n           (exists x : nat,\n           delta_min X Y = Some x /\\\n           In x X /\\ ~ In x Y /\\ (forall y : nat, In y X -> ~ In y Y -> x <= y))) as H1.\n  apply delta_min_dec.\n  destruct H1 as [H1 | [n [H1 [H2 [H3 H4]]]]].\n  rewrite -> H1 in H0. inversion H0.\n  rewrite -> H0 in H1.\n    assert (x = n) as H5. inversion H1. reflexivity.\n    rewrite -> H5. apply H2.\nQed.\n\nTheorem delta_min_neg_in : forall x X Y, delta_min X Y = Some x -> ~ In x Y.\nProof.\n  intros x X Y H0.\n  assert (delta_min X Y = None \\/\n           (exists x : nat,\n           delta_min X Y = Some x /\\\n           In x X /\\ ~ In x Y /\\ (forall y : nat, In y X -> ~ In y Y -> x <= y))) as H1.\n  apply delta_min_dec.\n  destruct H1 as [H1 | [n [H1 [H2 [H3 H4]]]]].\n  rewrite -> H1 in H0. inversion H0.\n  rewrite -> H0 in H1.\n    assert (x = n) as H5. inversion H1. reflexivity.\n    rewrite -> H5. apply H3.\nQed.\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/lex_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7642747409978515}}
{"text": "(* Code for Coq'Art, Chapter 5: Everyday Logic. *)\n\nSection EverydayLogic.\n\nRequire Import Arith.\nRequire Import ZArith.\nRequire Import List.\n\n(* Examples *)\nSection Examples.\n\nDefinition lt (n p : nat) : Prop :=\n  S n <= p.\n\nTheorem conv_example :\n  forall n : nat, 7 * 5 < n -> 6 * 6 <= n.\n(* The two formulas are convertible:\n  + a delta-reduction on lt,\n  + two beta-reductions, (function application), get \"S (7*5) <= n\".\n  + then, convert \"S (7*5) <= n\" and \"6*6 <= n\" both to 36<=n.\n  After \"intros n h1\", the convertiblity of the goal and hypothesis h1 make the\n  tactic \"apply h1\" succeed.*)\nProof.\n  intros n h1.\n  apply h1.\nQed.\nPrint conv_example.\n\n(* Polymorphic version of \"implication transitivity\". *)\nTheorem imp_trans_poly :\n  forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros P Q R h1 h2 h3.\n  apply h2; apply h1; apply h3.\nQed.\nImplicit Arguments imp_trans_poly [P Q R].\nPrint imp_trans_poly.\nPrint le_S.\nCheck (imp_trans_poly _ _ _ (le_S 0 1) (le_S 0 2)).\n\nDefinition neutral_left (A : Set) (op : A -> A -> A) (e : A) :=\n  forall x : A, op e x = x.\nTheorem neutral_left_one :\n  neutral_left Z Zmult 1%Z.\nProof.\n  intros v.\n  destruct v. (* \"case v.\" and \"elim v.\" are also can solve the proof. *)\n  + simpl; reflexivity.\n  + simpl; reflexivity.\n  + simpl; reflexivity.\nQed.\nPrint neutral_left_one.\n\nTheorem ls_SS :\n  forall i : nat, i <= S (S i).\nProof.\n  intros i.\n  apply le_S; apply le_S; apply le_n.\nQed.\n\nTheorem imp_dist_all :\n  forall (A : Type) (P Q : A -> Prop), (\n    forall x : A, P x -> Q x) -> (\n      forall y : A, P y) ->\n        forall z : A, Q z.\nProof.\n  intros TA P Q h1 h2.\n  intros value.\n  apply h1; apply h2.\nQed.\nPrint imp_dist_all.\n\nLemma zero_le_nat :\n  forall n : nat, O <= n.\nProof.\n  induction n.\n  - apply le_n.\n  - apply le_S; apply IHn.\nQed.\n\nLemma le_trans :\n  forall n m p : nat, n <= m -> m <= p -> n <= p.\nProof.\n  intros n m p h1 h2.\n  induction h2. (* perform induction on the inductive predicate: \"le\". *)\n  + assumption.\n  + apply le_S.\n    assumption.\nQed.\n\nLemma mult_le_compat_l :\n  forall n m p : nat, n <= m -> p * n <= p * m.\nProof.\n  induction p; simpl.\n  + trivial.\n  + intros h1.\n    apply plus_le_compat.\n    - assumption.\n    - apply IHp; assumption.\nQed.\n\nLemma mult_le_compat_r :\n  forall n m p : nat, n <= m -> n * p <= m * p.\nProof.\n  intros n m p.\n  pattern (n * p); rewrite mult_comm.\n  pattern (m * p); rewrite mult_comm.\n  apply mult_le_compat_l.\nQed.\n\n(* Use apply...at... or eapply... . *)\n\nTheorem le_mult_mult :\n  forall a b c d : nat, a <= c -> b <= d -> a * b <= c * d.\nProof.\n  intros a b c d h1 h2.\n  (* apply ... with ... to build explicit mapping. *)\n  apply le_trans with (m := c * b); [\n      apply mult_le_compat_r; apply h1\n    | apply mult_le_compat_l; apply h2\n  ].\nQed.\nPrint le_mult_mult.\n\nTheorem le_mult_mult' :\n  forall a b c d : nat, a <= c -> b <= d -> a * b <= c * d.\nProof.\n  intros a b c d h1 h2.\n  eapply le_trans.\n  apply mult_le_compat_l.\n  apply h2.\n  apply mult_le_compat_r.\n  apply h1.\nQed.\n\nLemma le_0_mult :\n  forall n p : nat, 0 * n <= 0 * p.\nProof.\n  intros n p.\n  apply le_n.\nQed.\n\nLemma lt_8_9 : 8 < 9.\nProof.\n  apply le_n.\nQed.\n\nOpen Scope Z_scope.\n\nDefinition Zsquare_diff (x y : Z) := x * x - y * y.\n\nTheorem unfold_example :\n  forall x y : Z, x * x = y * y -> Zsquare_diff x y * Zsquare_diff (x + y) (x * y) = 0.\nProof.\n  intros x y h1.\n  unfold Zsquare_diff at 1 2.\n  rewrite h1.\n  assert (h2 : y * y - y * y = 0).\n  + omega.\n  + rewrite h2; simpl; reflexivity.\nQed.\nPrint unfold_example.\n\nOpen Scope nat_scope.\n\nTheorem lt_S :\n  forall n p : nat, n < p -> n < S p.\nProof.\n  intros n p h1.\n  apply le_S.\n  apply lt_le_S; assumption. (* or directly use the tactic \"trivial\". *)\nQed.\n\n(* Logic Connectives. *)\nSection LogicConnectives.\n\n(* If a logic system is inconsistant, any propositions can be proved in via\n  eliminating the contradiction (using the \"elim\" tactic).\n  The \"False\" proposition represents the absolute contradiction. There's no\n  introduction rule for this proposition, it's only possible to prove it in\n  a context that already contains a contradiction. *)\nSection InconsistantExample.\n\nHypothesis false : False.\n\nCheck False_ind.\nPrint False_ind.\n\n(* The \"elim\" tactic:\n  usage: \"elim t\".\n  + if \"t\" is a term with type \"False\", then the current goal was solved immediately.\n  + or else, if \"t\" is a negation (with form \"~ x\"), \"elim t\" (\"elim ~ x\") will solve\n    the current goal with creating a new subgoal \"x\". then, if \"x\" can be proved,\n    the original proposition can be proved.\n    NOTE: if \"t\" doesn't have a \"~ \", CAN NOT apply the \"elim\" tactic on it. *)\n\nLemma false_ex1 : 220 = 284.\nProof.\n  apply False_ind.\n  exact false.\nQed.\n\nLemma false_ex2 : 220 = 284.\nProof.\n  elim false.\nQed.\n\nTheorem absurd :\n  forall P Q : Prop, P -> ~ P -> Q.\nProof.\n  intros P Q h1 h2.\n  elim h2. (* \"h2 = ~ p\", so, this step will solve \"q\" and introduce a subgoal \"p\". *)\n  assumption.\nQed.\nPrint absurd.\n\n(* Under the intuitionism logic, the goal \"double_neg_l\" can't be proved, however\n  the goal \"double_neg_r\" can be proved trivially. *)\n\n(* Theorem double_neg_l :\n  forall P : Prop, ~ ~ P -> P. *)\n\nTheorem double_neg_r :\n  forall P : Prop, P -> ~ ~ P.\nProof.\n  intros P hp.\n  (* Here, we want to prove \"~ ~ p\", the \"intros hp_neg\" will introduce a hypothesis\n    \"~ p\" and a subgoal \"False\". The tiatics \"elim\" the \"~ p\" (in the context), and\n    \"apply p\" will lead to a contradiction. (NOTE: CAN NOT \"elim p\"). *)\n  intros hp_neg.\n  elim hp_neg; apply hp. (* another solution: \"apply hg_neg; apply hp.\". *)\nQed.\nPrint False.\nPrint double_neg_r.\n\nTheorem contrad_example :\n  forall P Q : Prop, ((P -> Q) -> P) -> (~ P -> P).\nProof.\n  intros P Q.\n  intros h1 h2.\n  apply h1.\n  intros h3.\n  (* NOTE now we get a contradiction. *)\n  elim h2; assumption.\nQed.\n\nEnd InconsistantExample.\n\n(* The theorem \"double_neg_r\" is a simple instance of the modus ponens rule.\n  \"modus_ponens p False\" equals to \"P -> (P -> False) -> False\".\n  After \"unfold not\", the goal \"P -> ~ ~ P\" becomes \"P -> (P -> False) -> False\". *)\n\nTheorem modus_ponens :\n  forall P Q : Prop, P -> (P -> Q) -> Q.\nProof.\n  intros P Q h1 h2.\n  apply h2; assumption.\nQed.\nPrint modus_ponens.\n\nTheorem double_neg_r' :\n  forall P : Prop, P -> ~ ~ P.\nProof.\n  intros P.\n  unfold not.\n  exact (modus_ponens P False).\nQed.\nPrint double_neg_r'.\n\n(* The contraposition is a direct application of \"implication transitivity\".\n  After \"unfold not.\", the goal becomes \"(a -> b) -> (b -> False) -> a -> False\". *)\n\nTheorem contrap :\n  forall A B : Prop, (A -> B) -> ~ B -> ~ A.\nProof.\n  intros A B.\n  unfold not.\n  apply imp_trans_poly.\nQed.\n\nTheorem split_example :\n  forall P Q : Prop, P -> Q -> P /\\ Q.\nProof.\n  intros P Q h1 h2.\n  split; [assumption | assumption].\nQed.\n\nTheorem conj3 :\n  forall P Q R : Prop, P -> Q -> R -> P /\\ Q /\\ R.\nProof.\n  intros P Q R h1 h2 h3.\n  repeat split; assumption.\nQed.\n\nTheorem disj4_3 :\n  forall P Q R S : Prop, R -> P \\/ Q \\/ R \\/ S.\nProof.\n  intros P Q R S h1.\n  right; right; left; assumption.\nQed.\n\nTheorem and_commutes :\n  forall A B : Prop, A /\\ B -> B /\\ A.\nProof.\n  intros A B h1.\n  split; apply h1.\nQed.\n\nTheorem and_commutes' :\n  forall A B : Prop, A /\\ B -> B /\\ A.\nProof.\n  intros A B h1.\n  elim h1.\n  (* \"split\" = \"intros; apply conj.\" *)\n  split; assumption.\nQed.\n\nTheorem or_commutes :\n  forall A B : Prop, A \\/ B -> B \\/ A.\nProof.\n  intros A B.\n  intros [h1 | h2]; [right | left]; assumption.\nQed.\n\nEnd LogicConnectives.\n\nTheorem ex_imp_ex :\n  forall (A : Type) (P Q : A -> Prop), (ex P) -> (\n    forall x : A, P x -> Q x) -> (ex Q).\nProof.\n  intros TA P Q h1 h2.\n  elim h1.\n  intros x h3.\n  exists x.\n  apply h2; assumption.\nQed.\nPrint ex_imp_ex.\n\nTheorem eq_36 : 6 * 6 = 4 * 9.\nProof.\n  apply refl_equal.\nQed.\n\nTheorem eq_36' : 6 * 6 = 4 * 9.\nProof.\n  reflexivity.\nQed.\n\nOpen Scope Z_scope.\n\nTheorem diff_of_squares :\n  forall a b : Z, (a+b) * (a-b) = a*a - b*b.\nProof.\n  intros.\n  ring. (* defined in \"ZArithRing\" *)\nQed.\n\nTheorem symbol_equal :\n  forall (A : Type) (a b : A), a = b -> b = a.\nProof.\n  intros TA a b.\n  intros h1.\n  rewrite h1. (* also can be done by \"rewrite <- h1\". *)\n  trivial.\nQed.\n\nTheorem Zmult_distr_example_l :\n  forall n x : Z, n * x + x = (n + 1) * x.\nProof.\n  intros n x.\n  rewrite Zmult_plus_distr_l.\n  rewrite Zmult_1_l.\n  trivial.\nQed.\n\nTheorem Zmult_distr_example_r :\n  forall n x : Z, n * x + x = x * (n + 1).\nProof.\n  intros n x.\n  rewrite Zmult_plus_distr_r.\n  rewrite Zmult_1_r.\n  rewrite Z.mul_comm.\n  trivial.\nQed.\n\nTheorem regroup :\n  forall x : Z, x + x + x + x + x = 5 * x.\nProof.\n  intros x.\n  pattern x at 1 2 3 4 5.\n  rewrite <- Zmult_1_l.\n  repeat rewrite <- Zmult_plus_distr_l.\n  trivial.\nQed.\n\nOpen Scope nat_scope.\n\nLemma le_lt_S_eq :\n  forall n p : nat, n <= p -> p < S n -> n = p.\nProof.\n  intros n p.\n  omega.\nQed.\n\nTheorem cond_rewrite_example :\n  forall n : nat, 8 < n + 6 -> 3 + n < 6 -> n * n = n + n.\nProof.\n  (* Where I was always felt stuck here ?\n    I thought when n equals to 2, the first premise \"8 < n + 6\" didn't hold,\n    so, there must be something wrong with this proof, but I couldn't get it.\n    I suddenly realised that when n equals to 2, this proposition is equivalent\n    with \"False -> True -> True\", it holds trivially! *)\n  intros n h1 h2.\n  rewrite <- (le_lt_S_eq 2 n).\n  + reflexivity.\n  + apply plus_le_reg_l with (p := 6).\n    rewrite plus_comm in h1.\n    simpl (6 + 2).\n    apply Nat.lt_le_incl.\n    assumption.\n  + apply plus_lt_reg_l with (p:= 3).\n    apply h2.\nQed.\n\nEnd Examples.\n\n(* Exercises. *)\nSection Exercises.\n\n(* Exercise 5.1 Polymorphic minimal propositional logic. *)\n\nLemma id_P :\n  forall P : Prop, P -> P.\nProof.\n  intros P h1.\n  apply h1.\nQed.\nPrint id_P.\n\nLemma id_PP :\n  forall P : Prop, (P -> P) -> (P -> P).\nProof.\n  intros P h1.\n  apply h1.\nQed.\n\nLemma imp_trans :\n  forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros P Q R h1 h2 h3.\n  apply h2.\n  apply h1.\n  apply h3.\nQed.\n\nLemma imp_perm :\n  forall P Q R : Prop, (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros P Q R h1 h2 h3.\n  apply h1.\n  apply h3.\n  apply h2.\nQed.\n\nLemma ignore_Q :\n  forall P Q R : Prop, (P -> R) -> P -> Q -> R.\nProof.\n  intros P Q R h1 h2 h3.\n  apply h1; apply h2.\nQed.\n\nLemma delta_imp :\n  forall P Q R : Prop, (P -> P -> Q) -> P -> Q.\nProof.\n  intros P Q R h1 h2.\n  apply h1; [apply h2 | apply h2].\nQed.\n\nLemma delta_impR :\n  forall P Q R : Prop, (P -> Q) -> (P -> P -> Q).\nProof.\n  intros P Q R h1 h2.\n  apply h1.\nQed.\n\nLemma diamond :\n  forall P Q R T : Prop, (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\nProof.\n  intros P Q R T h1 h2 h3 h4.\n  apply h3; [apply h1; apply h4 | apply h2; apply h4].\nQed.\nPrint diamond.\n\nLemma weak_peirce :\n  forall P Q R : Prop, ((((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 P Q R 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 5.2 Some proofs in predicate calculus. *)\n\nTheorem 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 TA P h1 v1 v2.\n  apply h1.\nQed.\nPrint all_perm'.\n\nTheorem 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 TA P Q R S h1 h2.\n  intros v1.\n  intros v2 v3.\n  apply h1; [apply h2; apply v2 | apply v3].\nQed.\nPrint resolution.\n\n(* Exercise 5.3 On Negation, prove WITHOUT \"False_ind\". *)\n\nLemma lem1 : ~ False.\nProof.\n  (* If item \"t\" can imply \"False\", then \"~ t\" will be proved. *)\n  intros h1.\n  apply h1.\nQed.\n\nLemma lem2 :\n  forall P : Prop, ~ ~ ~ P -> ~ P.\nProof.\n  intros P.\n  intros h1 h2.\n  apply h1.\n  intros h3.\n  elim h3; apply h2.\nQed.\n\nLemma lem3 :\n  forall P Q : Prop, ~ ~ ~ P -> P -> Q.\nProof.\n  intros P Q h1 h2.\n  elim h1.\n  intros h3.\n  elim h3; apply h2.\nQed.\n\nLemma lem4 :\n  forall P Q : Prop, (P -> Q) -> ~ Q -> ~ P.\nProof.\n  intros P Q h1 h2 h3.\n  (* Assume \"q\" and prove it, the get contradiction. *)\n  elim h2.\n  apply h1; assumption.\nQed.\n\nLemma lem4' :\n  forall P Q : Prop, (P -> Q) -> ~ Q -> ~ P.\nProof.\n  intros P Q.\n  unfold not.\n  apply imp_trans_poly.\nQed.\n\nLemma lem5 :\n  forall P Q R : Prop, (P -> Q) -> (P -> ~ Q) -> P -> R.\nProof.\n  intros P Q R.\n  intros h1 h2 value.\n  elim (h2 value); apply h1; assumption.\nQed.\nPrint lem5.\n\n(* Exercise 5.4 Some bad inference rules. *)\n\n(** TODO **)\n\n(* Exercise 5.5 Introducing equality and disjunction. *)\n\nTheorem refl_eq :\n  forall (A : Set) (a b c d : A), a = c \\/ b = c \\/ c = c \\/ d = c.\nProof.\n  intros TA a b c d.\n  right; right; left.\n  (* The equal relation is reflexive. *)\n  apply refl_equal. (* Here the tactic \"reflexivity\" also work. *)\nQed.\n\n(* Exercise 5.6 Intuitionistic Propositional Logic. *)\n\nTheorem and_assoc :\n  forall A B C : Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n  (* Bind variable in conjunctive pattern with hypothesis using \"intros\". *)\n  intros A B C [h1 [h2 h3]].\n  repeat split; assumption.\nQed.\n\nTheorem and_imp_dist :\n  forall A B C D : Prop, (A -> B) /\\ (C -> D) -> A /\\ C -> B /\\ D.\nProof.\n  intros A B C D [h1 h2] [h3 h4].\n  split; [apply h1 | apply h2]; assumption.\nQed.\n\nTheorem not_contrad :\n  forall A : Prop, ~ (A /\\ ~ A).\nProof.\n  intros A [h1 h2].\n  apply h2; apply h1.\nQed.\nPrint not_contrad.\n\nTheorem or_assoc :\n  forall A B C : Prop, A \\/ (B \\/ C) -> (A \\/ B) \\/ C.\nProof.\n  intros A B C.\n  intros [h1 | [h2 | h3]].\n  left; left; assumption.\n  left; right; assumption.\n  right; assumption.\nQed.\n\nTheorem double_neg_true :\n  forall A : Prop, ~ ~ (A \\/ ~ A).\nProof.\n  intros A h1.\n  elim h1.\n  right; intros h2.\n  elim h1.\n  left; assumption.\nQed.\nPrint double_neg_true.\n\n(* TODO There's another way to finish this proof. Why this implimentation\n  successes ? What's the detailed type of \"h1\" ? *)\nTheorem double_neg_true' :\n  forall A : Prop, ~ ~ (A \\/ ~ A).\nProof.\n  intros A h1.\n  exact (h1 (or_intror (fun value : A => h1 (or_introl value)))).\nQed.\nPrint double_neg_true'.\n\nTheorem or_and_not :\n  forall A B : Prop, (A \\/ B) /\\ ~ A -> B.\nProof.\n  intros A B [[h1 | h2] h3].\n  elim h3; apply h1.\n  assumption.\nQed.\n\n(* Exercise 5.7 Five characterizations of classical logic. *)\n\nDefinition peirce :=\n  forall P Q : Prop, ((P -> Q) -> P) -> P.\nDefinition classic :=\n  forall P : Prop, ~ ~ P -> P.\nDefinition excluded_middle :=\n  forall P : Prop, P \\/ ~ P.\nDefinition de_morgan_not_and_not :=\n  forall P Q : Prop, ~ (~ P /\\ ~ Q) -> P \\/ Q.\nDefinition implies_to_or :=\n  forall P Q : Prop, (P -> Q) -> (~ P \\/ Q).\n\nGoal peirce <-> classic.\nProof.\n  unfold peirce; unfold classic; unfold not.\n\n  split.\n\n  intros hypo_perice.\n  intros P h2.\n  apply (hypo_perice P False).\n  intros h3; elim h2; assumption.\n\n  intros hypo_classic.\n  intros P Q h1.\n  apply hypo_classic; intros h2.\n  apply h2.\n  apply h1.\n  intros h3.\n  apply hypo_classic;\n  intros h4.\n  apply h2; apply h3.\nQed.\n\nGoal peirce <-> excluded_middle.\nProof.\n  unfold peirce; unfold excluded_middle.\n\n  split.\n\n  (* NOTE important skill !!!. *)\n  intros hypo_perice P.\n  apply (hypo_perice (P \\/ ~ P) False).\n  intros h1.\n  right; intros h2.\n  elim h1.\n  left; assumption.\n\n  intros hypo_em P Q h1.\n  elim (hypo_em P);\n    [ intros h2\n    | intros h2; apply h1; intros h3; elim h2\n    ];\n    assumption.\nQed.\n\nGoal peirce <-> de_morgan_not_and_not.\nProof.\n  unfold peirce; unfold de_morgan_not_and_not.\n\n  split.\n  (* TODO *)\nAdmitted.\n\nGoal peirce <-> implies_to_or.\nProof.\n  (* TODO *)\nAdmitted.\n\nGoal classic <-> excluded_middle.\nProof.\n  unfold classic; unfold excluded_middle; unfold not.\n\n  split.\n\n  intros hypo_classic P.\n  (* NOTE important skill !!!. *)\n  apply hypo_classic.\n  intros h2; apply h2.\n  right; intros h3.\n  elim h2.\n  left; assumption.\n\n  intros hypo_em P;\n  elim (hypo_em P); intros h1 h2; [idtac | elim h2]; apply h1.\nQed.\n\nGoal classic <-> de_morgan_not_and_not.\nProof.\n  unfold classic; unfold de_morgan_not_and_not.\n\n  split.\n\n  intros hypo_classic P Q.\n  intros h1.\n  apply (hypo_classic (P \\/ Q)).\n  intros h2.\n  apply h1; split; intros h3; elim h2; [left | right]; apply h3.\n\n  intros hypo_de_morgan P.\n  intros h1.\n  elim (hypo_de_morgan P (~ P));\n    [ trivial\n    | intros h2; elim h1; assumption\n    | intros h2; elim h2; intros h3 h4; elim h4; assumption\n    ].\nQed.\n\nGoal classic <-> implies_to_or.\nProof.\n  (* TODO *)\nAdmitted.\n\nGoal excluded_middle <-> de_morgan_not_and_not.\nProof.\n  (* TODO *)\nAdmitted.\n\nGoal excluded_middle <-> implies_to_or.\nProof.\n  unfold excluded_middle; unfold implies_to_or.\n\n  split.\n\n  unfold not.\n  intros hypo_em P Q.\n  intros h1.\n  elim (hypo_em P);\n    [ intros h2; right; apply h1; apply h2\n    | intros h3; left; apply h3\n    ].\n\n  intros hypo_impl P.\n  elim (hypo_impl P P); intros;\n    [ right\n    | left\n    | idtac];\n    assumption.\nQed.\n\nGoal de_morgan_not_and_not <-> implies_to_or.\nProof.\n  (* TODO *)\nAdmitted.\n\n(* Exercise 5.8 *)\n\n(** The usage of:\n  + \"repeat idtac\" keep a goal as it was.\n  + \"repeat fail\" ? (* TODO *) **)\n\n(* Exercise 5.9 On the existential quantifier. *)\n\nTheorem ex_or_l :\n  forall (A : Type) (P Q : A -> Prop), (\n    exists x : A, P x \\/ Q x) -> ex P \\/ ex Q.\nProof.\n  intros TA P Q h1.\n  elim h1.\n  intros x h2.\n  elim h2; [left | right]; exists x; assumption.\nQed.\n\nTheorem ex_or_r :\n  forall (A : Type) (P Q : A -> Prop), (ex P \\/ ex Q) -> (\n    exists x : A, P x \\/ Q x).\nProof.\n  intros TA P Q.\n  intros [h1 | h2];\n    [ elim h1\n    | elim h2\n    ];\n    intros; exists x;\n    [ left\n    | right\n    ]; assumption.\nQed.\n\nTheorem ex_universal_relation :\n  forall (A : Type) (P Q : A -> Prop), (\n    exists x : A,\n      forall R : A -> Prop, R x) -> 2 = 3.\nProof.\n  intros TA P Q.\n  intros h1.\n  elim h1.\n  intros x hr1.\n  (* Construct  a relation that maps all elements with type \"TA\" to \"False\".\n    TODO The question if that how this approach works and how to construct a solution\n    for general problem ? *)\n  elim (hr1 (fun e : TA => False)).\nQed.\n\nTheorem forall_not_ex :\n  forall (A : Type) (P Q : A -> Prop), (\n    forall x : A, P x) -> ~ (\n      exists y : A, ~ P y).\nProof.\n  intros TA P Q.\n  intros h1 h2.\n  elim h2.\n  intros x h3.\n  elim h3; apply h1.\nQed.\n\n(* Exercise 5.10 Using \"pattern\" and \"rewrite\". *)\n\nOpen Scope nat_scope.\n\nTheorem nat_plus_permute :\n  forall n m p : nat, n + m + p = n + p + m.\nProof.\n  intros n m p.\n  rewrite plus_assoc_reverse.\n  rewrite plus_assoc_reverse.\n  rewrite (plus_comm n (m + p)).\n  rewrite (plus_comm n (p + m)).\n  rewrite (plus_comm m p).\n  trivial.\nQed.\n\n(* Exercise 5.11 Transitivity of Leibniz equality. *)\n\nTheorem eq_trans :\n  forall (A : Type) (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros TA x y z h1 h2.\n  rewrite h1; assumption.\nQed.\n\nTheorem eq_trans' :\n  forall (A : Type) (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros TA x y z h1.\n  rewrite h1; trivial.\nQed.\n\nTheorem eq_trans'' :\n  forall (A : Type) (x y z : A), x = y -> y = z -> x = z.\nProof.\n  intros TA x y z h1.\n  pattern y at 1.\n  apply eq_ind with TA x;\n    [ trivial\n    | assumption\n    ].\nQed.\n\n(* Exercise 5.12 *)\n\n(* Exercise 5.13 On Negation (impredicative definition). *)\n(* Exercise 5.14 An impredicative definition of equality. *)\n(* Exercise 5.15 Some impredicative definitions. *)\n(* Exercise 5.16 An impredicative definition of \"<=\". *)\n\nEnd Exercises.\n\nEnd EverydayLogic.\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/EverydayLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8991213840277783, "lm_q1q2_score": 0.7642272666749936}}
{"text": "Require Arith.\n\nLemma le_n_plus_pn n p : n <= p + n.\nProof.\n  Print le.\n  induction p as [ | p IHp ]; simpl.\n  + constructor 1.\n  + constructor 2; assumption.\nQed.\n\nCheck le_ind.\n\nLemma le_plus n m : n <= m -> exists p, p+n = m.\nProof.\n  Print le.\n  induction 1 as [ | m H IH ].\n  + exists 0; simpl; trivial.\n  + destruct IH as (p & Hp).\n    exists (S p); simpl; f_equal; trivial.\nQed.\n\nLemma foo_gen n : 1 <= n -> n = 0 -> False.\nProof.\n  intros H.\n  induction H.\n  + discriminate.\n  + discriminate.\nQed. \n\nLemma foo_1 : ~ 1 <= 0.\nProof.\n  red.\n  intros H.\n  destruct foo_gen with (1 := H).\n  reflexivity.\nQed.\n\nLemma foo : ~ 1 <= 0.\nProof.\n  intros H.\n  inversion H.\nQed.\n\nLemma le_n_0 n : n <= 0 -> n = 0.\nProof.\n  Print le.\n  inversion 1.\n  reflexivity.\nQed.\n\nFixpoint leb n m : bool := \n  match n, m with\n    | 0, _     => true\n    | S _, 0   => false\n    | S n, S m => leb n m\n  end.\n\nLemma le_5_45 : 5 <= 45.\nProof.\n(*  do 40 constructor.\n  constructor 1. *)\n  repeat constructor.\nQed.\n\nLemma leb_5_45 : leb 5 45 = true.\nProof. reflexivity. Qed.\n\nPrint leb_5_45.\n\nLemma le_trans : forall n p q, n <= p -> p <= q -> n <= q.\nProof.\n(*  intros n p q Hpq.\n  induction 1 as [ | q H1 IH1 ].\n  + trivial.\n  + constructor; trivial. *)\n  induction 2; [ | constructor ]; trivial.\nQed.\n\nLemma le_Sn_Sp_inv n p : S n <= S p -> n <= p.\nProof.\n  inversion 1.\n  + constructor.\n  + apply le_trans with (2 := H1).\n    do 2 constructor.\nQed.\n\nLemma le_Sn_Sp n p : n <= p -> S n <= S p.\nProof.\n  induction 1; constructor; auto.\nQed.\n\nLemma le_leb_iff n m : n <= m <-> leb n m = true.\nProof.\n  split.\n  + revert m.\n    induction n as [ | n IHn ]; intros [ | m ]; simpl; auto.\n    * inversion 1.\n    * intro; apply IHn, le_Sn_Sp_inv; auto.\n  + revert m.\n    induction n as [ | n IHn ].\n    * induction m; simpl; auto.\n    * intros [ | m ]; simpl; auto.\n      - discriminate.\n      - intros H; apply IHn in H.\n        apply le_Sn_Sp; trivial.\nQed.\n\nFact le_78_1090 : 78 <= 1090.\nProof.\n  apply le_leb_iff.\n  reflexivity.\nQed.\n\nPrint le_78_1090.\n\nRequire Import Arith.\n\nFact leb_n_np n p : leb n (n+p) = true.\nProof.\n  apply le_leb_iff.\n  rewrite plus_comm.\n  apply le_n_plus_pn.\nQed.\n\nPrint le.\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\nPrint le.\n\nPrint and.\nPrint or.\nPrint ex.\nPrint eq.\nPrint True.\nPrint False.\n\nCheck refl_equal.\n\nDefinition two_two_four : 2+2 = 4 := eq_refl.\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/C4_ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7642272626982588}}
{"text": "Require Import ZArith.\nSection A_declared.\n\n        Variables (A:Set) (P Q: A-> Prop) (R: A -> A -> Prop).\n        Theorem all_imp_dist:\n                (forall a: A, P a -> Q a)-> (forall a, P a) -> (forall a: A, Q a).\n        intros h1 h2.\n        intro a.\n        apply h1.\n        apply h2.\n        Qed.\n\n        Theorem all_perm:\n                (forall (a b: A), R a b) -> (forall (a b : A), R b a).\n        intros h1.\n        intros a b.\n        apply h1.\n        Qed.\n\n        Theorem all_delta :\n                (forall (a b :A), R a b) -> (forall (a : A), R a a).\n        intros h1 a.\n        apply h1.\n        Qed.\n\nEnd A_declared.\nSection fourpfour_sec.\n        Theorem fpf_id:\n                forall A:Set, A -> A.\n                Proof.  \n        intros A a.\n        assumption.\n                Qed.\n       \n\nTheorem fpf_diag:\n               forall A B : Set, (A -> A -> B) -> A -> B.\n               Proof.\n                       intros A B h1.\n                       intro a.\n                       apply h1.\n                       assumption.\n                       assumption.\n               Qed.\n               Theorem fpf_permute:\n                       forall A B C: Set,(A -> B -> C) -> B ->A ->C.\n                       Proof.\n                               intros A B C h1 b c.\n                               apply h1;assumption.\n                       Qed.\n\n                       Theorem fpf_f_nat_Z:\n                               forall A:Set,(nat -> A) -> Z -> A.\n                               Proof.\nintros A h1 b.\napply h1;apply(fun (a: Z) => 0);assumption.\n                               Qed.\nEnd fourpfour_sec.\n\nSection fourpfive.\n        Theorem fpfv_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).\n        Proof.\n                intros A h1 h2 x y.\n                apply h2.\n        Qed.\n        Theorem fpfv_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).\n        Proof.\n                intros A P Q R S h1 h2 c p r.\n                apply h1;[(apply h2;assumption)| assumption ].\n\n        Qed.\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/4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7641757938510494}}
{"text": "(*the library would generalize over 4, and have good enough automation to not require these specialized lemmas*)\nRequire Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import coqutil.Z.Lia.\n\nLemma mod4_0_add: forall (x y: Z),\n    x mod 4 = 0 ->\n    y mod 4 = 0 ->\n    (x + y) mod 4 = 0.\nProof.\n  intros *. intros Hx Hy.\n  rewrite Zplus_mod. rewrite Hx, Hy. reflexivity.\nQed.\n\nLemma mod4_0_sub: forall (x y: Z),\n    x mod 4 = 0 ->\n    y mod 4 = 0 ->\n    (x - y) mod 4 = 0.\nProof.\n  intros *. intros Hx Hy.\n  rewrite Zminus_mod. rewrite Hx, Hy. reflexivity.\nQed.\n\nLemma mod4_mul4_l: forall (x: Z),\n    (4 * x) mod 4 = 0.\nProof. intros. rewrite Z.mul_comm. rewrite Z.mod_mul; blia. Qed.\n\nLemma mod4_mul4_r: forall (x: Z),\n    (x * 4) mod 4 = 0.\nProof. intros. rewrite Z.mod_mul; blia. Qed.\n\nLemma mod4_mul_l: forall (x y: Z),\n    x mod 4 = 0 ->\n    (x * y) mod 4 = 0.\nProof.\n  intros.\n  rewrite <- Z.mul_mod_idemp_l by blia.\n  rewrite H.\n  rewrite Z.mul_0_l.\n  reflexivity.\nQed.\n\nLemma mod4_mul_r: forall (x y: Z),\n    y mod 4 = 0 ->\n    (x * y) mod 4 = 0.\nProof.\n  intros.\n  rewrite <- Z.mul_mod_idemp_r by blia.\n  rewrite H.\n  rewrite Z.mul_0_r.\n  reflexivity.\nQed.\n\nLemma mod_pow2_mod4: forall x p,\n    2 <= p ->\n    (x mod 2 ^ p) mod 4 = x mod 4.\nProof.\n  intros.\n  rewrite <- Znumtheory.Zmod_div_mod.\n  - reflexivity.\n  - reflexivity.\n  - apply Z.pow_pos_nonneg; blia.\n  - unfold Z.divide.\n    exists (2 ^ p / 2 ^ 2).\n    rewrite <- Z.pow_sub_r by blia.\n    change 4 with (2 ^ 2).\n    rewrite <- Z.pow_add_r by blia.\n    f_equal.\n    blia.\nQed.\n\nLemma mod4_0_mod_pow2: forall (x p: Z),\n    x mod 4 = 0 ->\n    (x mod 2 ^ p) mod 4 = 0.\nProof.\n  intros.\n  assert (p < 0 \\/ p = 0 \\/ p = 1 \\/ 2 <= p) as C by blia. destruct C as [C | [C | [C | C]]].\n  - rewrite Z.pow_neg_r by assumption. now rewrite Zmod_0_r.\n  - subst p. simpl. rewrite Z.mod_1_r. reflexivity.\n  - subst p. change (2 ^ 1) with 2.\n    rewrite Z.mod_eq in H by blia.\n    replace x with (x / 4 * 2 * 2) by blia.\n    rewrite Z.mod_mul by blia.\n    reflexivity.\n  - rewrite mod_pow2_mod4; assumption.\nQed.\n\nLemma mod4_0_4: 4 mod 4 = 0. Proof. reflexivity. Qed.\n\nLemma mod4_0_opp: forall z,\n    z mod 4 = 0 ->\n    - z mod 4 = 0.\nProof.\n  intros. Z.div_mod_to_equations. blia.\nQed.\n\n#[global] Hint Resolve\n     mod4_0_mod_pow2\n     mod4_0_add\n     mod4_0_sub\n     mod4_0_mod_pow2\n     mod4_mul4_l\n     mod4_mul4_r\n     mod4_0_4\n     mod4_mul_l\n     mod4_mul_r\n     mod4_0_opp\n  : mod4_0_hints.\n\nLtac solve_mod4_0 := auto 30 with mod4_0_hints.\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/mod4_0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7641349080882681}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nGoal forall x, (1 <= x)%R -> (0 < x)%R.\nintros.\ninterval.\nQed.\n\nGoal forall x, (1 <= x)%R -> (x <= x * x)%R.\nintros.\ninterval with (i_bisect_diff x).\nQed.\n\nGoal forall x, (2 <= x)%R -> (x < x * x)%R.\nintros.\ninterval with (i_bisect_diff x).\nQed.\n\nGoal forall x, (-1 <= x)%R -> (x < 1 + powerRZ x 3)%R.\nintros.\ninterval with (i_bisect_diff x).\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-20120205.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7640446871148845}}
{"text": "(* Exercise 24 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_024 : (exists x, ~(P x \\/ Q x)) -> ~(forall x, P x).\nProof.\nimp_i a1.\nexi_e (exists x:D, ~(P x \\/ Q x)) a a2.\nhyp a1.\nneg_i (P a) a3.\nneg_i (P a \\/ Q a) a4.\nhyp a2.\ndis_i1.\nhyp a4.\nall_e (forall x:D, P x) 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_pred024.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7640248535628545}}
{"text": "Require Import Coq.Init.Nat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Omega.\n\n\nModule NatAttempt.\n\nDefinition ABigOmega (f g : nat -> nat) : Prop :=\n  exists a, a > 0 ->\n  exists N, forall n, N < n ->\n    g n <= a * (f n).\n\nDefinition ABigO (f g : nat -> nat) : Prop :=\n  exists a, a > 0 ->\n  exists N, forall n, N < n ->\n    f n <= a * (g n).\n\nDefinition ABigTheta (f g : nat -> nat) : Prop :=\n  ABigOmega f g /\\ ABigO f g.\n\n(** An example for asymptotic bound of cubic function *)\nDefinition cube1 : nat -> nat := fun x => x*x*x.\nDefinition poly1 : nat -> nat := fun x => 3*(x*x*x) + x*x - x.\n\nExample boungs_eg1 : ABigTheta poly1 cube1.\nProof.\n  unfold ABigTheta, ABigOmega, ABigO, cube1, poly1.\n  split.\n  - exists 1; intros.\n    exists 1; intros.\n    simpl. repeat rewrite <- plus_n_O.\n    repeat rewrite Nat.mul_add_distr_r.\n    rewrite <- Nat.add_sub_assoc.\n    + rewrite <- Nat.add_assoc.\n      apply le_plus_l.\n    + rewrite <- Nat.mul_1_r at 1.\n      apply Nat.mul_le_mono_l.\n      omega.\n  - exists 4; intros.\n    exists 0; intros.\n    assert (4 = 3 + 1). omega.\n    rewrite H1, Nat.mul_add_distr_r; clear H1.\n    assert (n <= n*n).\n    {\n      rewrite <- Nat.mul_1_r at 1.\n      apply Nat.mul_le_mono_l.\n      omega.\n    }\n    rewrite <- Nat.add_sub_assoc; [| apply H1].\n    Search (_+_<=_+_).\n    apply plus_le_compat_l.\n    simpl. rewrite <- plus_n_O.\n    assert (n = n * 1). omega.\n    rewrite H2 at 3; clear H2.\n    rewrite <- Nat.mul_sub_distr_l.\n    rewrite <- Nat.mul_assoc.\n    apply mult_le_compat_l.\n    eapply le_trans; [| apply H1]. omega.\nQed.\n\nEnd NatAttempt.\n\n\nModule ZAttempt.\n\nOpen Scope Z.\n\nDefinition ABigOmega (f g : Z -> Z) : Prop :=\n  exists (a : Z), a > 0 ->\n  exists (N : Z), forall (n : Z), N < n ->\n    g n <= a * (f n).\n\nDefinition ABigO (f g : Z -> Z) : Prop :=\n  exists a, a > 0 ->\n  exists N, forall n, N < n ->\n    f n <= a * (g n).\n\nDefinition ABigTheta (f g : Z -> Z) : Prop :=\n  ABigOmega f g /\\ ABigO f g.\n\n(** An example for asymptotic bound of cubic function *)\nDefinition cube1 : Z -> Z := fun x => x*x*x.\nDefinition poly1 : Z -> Z := fun x => 3*(x*x*x) + x*x - x.\n\nExample boungs_eg1 : ABigTheta poly1 cube1.\nProof.\n  unfold ABigTheta, ABigOmega, ABigO, cube1, poly1.\n  split.\n  - exists 1; intros.\n    exists 1; intros.\n    rewrite Z.mul_1_l.\n    rewrite <- (Z.mul_1_r n) at 9.\n    rewrite <- Z.add_sub_assoc.\n    rewrite <- Z.mul_sub_distr_l.\n    assert (0 <= n * (n - 1)).\n    {\n      apply (Z.mul_nonneg_nonneg n (n-1)).\n      omega. omega.\n    }\n    assert (n*n*n <= 3*(n*n*n)).\n    {\n      rewrite <- (Z.mul_1_l (n*n*n)) at 1.\n      apply (Z.mul_le_mono_nonneg_r 1 3 (n*n*n)); [| omega].\n      apply Z.mul_nonneg_nonneg.\n      apply Z.square_nonneg.\n      omega.\n    }\n    omega.\n  - exists 4; intros.\n    exists 0; intros.\n    (* split 3 * (n * n * n) + 1 * (n * n * n) *)\n    assert (4 = 3 + 1). omega.\n    rewrite H1; clear H1.\n    rewrite Z.mul_add_distr_r.\n    (* remove 3 * (n * n * n) *)\n    rewrite <- Z.add_sub_assoc.\n    apply Zplus_le_compat_l.\n    (* remove n *)\n    rewrite Z.mul_1_l.\n    rewrite <- (Z.mul_1_r n) at 3.\n    rewrite <- Z.mul_sub_distr_l.\n    rewrite <- Z.mul_assoc.\n    apply Z.mul_le_mono_nonneg_l; [omega |].\n    (* n - 1 <= n <= n * n *)\n    apply Z.le_trans with n; [omega |].\n    rewrite <- (Z.mul_1_r n) at 1.\n    apply Z.mul_le_mono_nonneg_l; omega.\nQed.\n\nEnd ZAttempt.\n", "meta": {"author": "BruceZoom", "repo": "PLProject-AsymptoticComplexity", "sha": "1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea", "save_path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity", "path": "github-repos/coq/BruceZoom-PLProject-AsymptoticComplexity/PLProject-AsymptoticComplexity-1adae6622e9dacc4a64b6e25eebfd1fd11a6c7ea/asymptotic_complexity_final/code/AsymptoticBound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7640248374378364}}
{"text": "Lemma and_assoc : forall A B C:Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n intros A B C [a [b c]]; repeat split; assumption.\nQed.\n\n\nLemma and_imp_dist : forall A B C D:Prop,\n   (A -> B) /\\ (C -> D) -> A /\\ C -> B /\\ D.\nProof.\n  intros A B C D [H1 H2] [a c].\n  split;[apply H1|apply H2];assumption.\nQed.\n\n\nLemma not_contrad : forall A : Prop, ~(A /\\ ~A).\nProof.\n intros A [a a']; apply a'; assumption.\nQed.\n\nLemma or_and_not : forall A B : Prop, (A\\/B)/\\~A -> B.\nProof.\n intros A B [[a|b] a'];[elim a'| idtac]; trivial.\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/everyday/SRC/intuitionism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7639989291431487}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Some basic functions *)\n\nDefinition const {A B} (a : A) := fun _ : B => a.\n\nDefinition flip {A B C} (f : A -> B -> C) : B -> A -> C :=\n  fun b a => f a b.\n\nArguments const {A B} a _ /.\nArguments flip {A B C} f b a /.\n\n(* move to logic_exercises *)\nSection IntLogic.\n\nVariables A B C D : Prop.\n\nLemma axiomK :\n  A -> B -> A.\nProof. exact: const. Qed.\n\n(* note: flip is more general *)\nLemma contraposition :\n  (* (A -> (B -> False)) -> (B -> (A -> False)) *)\n  (A -> ~ B) -> (B -> ~ A).\n(* Proof. exact: flip. Qed. *)\nProof.\n  rewrite /not.\n  Check flip.\n  exact: flip.\nQed.\n\nLemma p_imp_np_iff_np :\n  (* Which is equivalent to:\n    ((A -> (A -> False)) -> (A -> False))        /\\\n    ((A -> False)        -> (A -> (A -> False)))\n  *)\n  (A -> ~A) <-> ~A.\nProof.\n  split.\n  - move => a_i_not_a a.\n    exact: (a_i_not_a a).\n  - move => not_a _.\n    exact: not_a.\nQed.\n\n(* We can generalize the previous lemma into *)\nLemma p_p_q_iff_p_q : (A -> A -> B) <-> (A -> B).\nProof.\n  split.\n  - move=> aa_i_b a.\n    exact: (const aa_i_b a).\n  - move=> a_i_b _.\n    exact: a_i_b.\nQed.\n\n(* [apply] без [:] использует другой движок унификации,\n   что может в дальнейшем привести к проблемам, т.е.\n   лучше всегда использовать версию c [:], т.e. [apply: whatever] *)\n\nLemma p_is_not_equal_not_p :\n  (* ((A -> (A -> False) /\\ (A -> False) -> A) -> False) *)\n  ~ (A <-> ~ A).\nProof.\n  (* unfold not. *)\n  rewrite /not.\n  case.\n  move=> a_i_not_a not_a_i_a.\n  apply: (a_i_not_a).\n  apply: not_a_i_a.\n  move=> a.\n  apply: (a_i_not_a).\n  exact: a.\n  exact: a.\n\n  apply: not_a_i_a.\n  move=> a.\n  apply: a_i_not_a.\n  exact: a.\n  exact: a.\nQed.\n\nLemma p_is_not_equal_not_p' :\n  (* ((A -> (A -> False) /\\ (A -> False) -> A) -> False) *)\n  ~ (A <-> ~ A).\nProof.\n  (* unfold not. *)\n  (* rewrite /not. *)\n  case.\n\n  (* У нас выше есть доказанная лемма:\n     p_imp_np_iff_np : (A -> ~A) <-> ~A *)\n\n  move/p_imp_np_iff_np.\n  move=> not_a not_a_i_a.\n  apply: (not_a).\n  by apply: not_a_i_a.\nQed.\n\nLemma not_not_lem :\n  ~ ~ (A \\/ ~ A).\nProof.\n  rewrite /not.\n  move=> not_lem.\n  apply: (not_lem).\n  left.\n\n  Undo 1.\n\n  right.\n  move=> a.\n  apply: not_lem.\n  left.\n  exact: a.\nQed.\n\nLemma not_not_lem' :\n  ~ ~ (A \\/ ~ A).\nProof. intuition. Defined.\nEval compute in not_not_lem'.\n\nLemma constructiveDNE :\n  ~ ~ ~ A -> ~ A.\nProof.\n  rewrite /not.\n  move=> H a.\n  apply: H.\n  apply.\n  exact: a.\nQed.\n\nEnd IntLogic.\n\n\n(* Boolean logic (decidable fragment enjoys classical laws) *)\n\nSection BooleanLogic.\n\nLemma LEM_decidable a :\n  a || ~~ a.\nProof.\n  (* Используя команду [Set Printing Coercions].\n     можно увидеть, что целью на самом деле является [is_true (a || ~~ a)],\n     где [is_true] определяется как [fun b => b = true] *)\n  Set Printing Coercions.\n  (* [is_true] -- это стандартный способ поднять булево значение\n     на уровень типов, коэрцию Coq вставляет неявно, в зависимости\n     от контекста. Поскольку цель -- это всегда какой-то тип, то\n     Coq понимает, что нужно булево значение преобразовать в тип,\n     используя базу данных коэрций (в которую заранее добавлен [is_true]) *)\n  Unset Printing Coercions.\n\n  (* Unset Printing Notations. *)\n\n  (* Search _ (orb _ (negb _)). *)\n  (* Search _ (_ || ~~_). *)\n\n  (* Print orbN. *)\n  (* apply orbN. *)\n  (* Set Printing Notations. *)\n\n  (* case a. by []. by []. *)\n  (* case a. done. done. *)\n  by case a.\nQed.\n\n(* Check erefl. *)\n(* Check (erefl true). *)\n\nAbout implb.\n\nLemma disj_implb a b :\n  a || (a ==> b).\nProof.\n  case a.\n  - done.\n  done.\n  Restart.\n\n  by case a.\nQed.\n\nLemma iff_is_if_and_only_if a b :\n  (a ==> b) && (b ==> a) = (a == b).\nProof.\n  Locate \"==>\".\n  (* Definition implb (b1 b2:bool) : bool := if b1 then b2 else true. *)\n  by case a; case b.\n\n  Restart.\n\n  move: a b.\n  by case; case.\n\n  Restart.\n\n  move: a b=> [[] | []] /=.\n  Undo.\n  by move: a b=> [[] | []].\nQed.\n\nLemma implb_trans : transitive implb.\nProof.\n  Eval hnf in transitive implb.\n\n  (* case. case. case. done. done. done. *)\n  (* case. done. done. *)\n\n  by do 2! case.\n  Undo 1.\n  by case; case.\nQed.\n\nLemma triple_compb (f : bool -> bool) :\n  f \\o f \\o f =1 f.\nProof.\n  (* Unset Printing Notations. *)\n  (* Print eqfun. *)\n  (* Print funcomp. *)\n  Locate \"=1\".\n  (* Set Printing Notations. *)\n\n  (* Это моё глупое решение, следующие два более хитрые и короткие. *)\n\n (* [simpl] это не ssreflec'овая тактика,\n    так больше не делаем :) *)\n  case. simpl.\n\n  Undo 2.\n\n  (* Если раскрыть определения [eqfun] и [funcomp],\n     то [case] ниже станет более понятным *)\n  rewrite /eqfun.\n  rewrite /funcomp.\n\n  (* Вот так правильно делать вместo [simpl], [//=] упрощает цель *)\n  case=>//=.\n  (* Мы можем разобрать возможные результаты\n     ф-ции [f : bool -> bool] (их всего 2, тк в [bool] всегда 2 жителя) *)\n  - case E1:(f true).\n    (* ^ Именуем вариант, когда [f true = true] и сохраняем его в контексте,\n         тк дальше будем использовать это равенство для переписывания *)\n    + by rewrite E1.\n      (* Здесь тоже рассматриваем возможные результаты ф-ции [f false]*)\n    + case E2:(f false).\n      * by rewrite E1.\n      * by rewrite E2.\n    + case E2:(f false).\n      case E1:(f true).\n      * by rewrite E1.\n      * by rewrite E2.\n\n    (* Приходится повторять тоже самое ещё раз...\n       Если появляется необходимость повторять док-во,\n       то обычно это знак, что есть какая-то симметрия,\n       которую изначально не уловили и пошли другим путём.\n     *)\n\n  Restart.\n\n  (* [rewrite !E1] -- Переписать 1 или более раз\n     [rewrite ?E2] -- Переписать 0 или более раз *)\n\n  by case; case E1:(f true)=>/=; case E2:(f false); rewrite ?E1 ?E2. Restart.\n  by case=>/=; case E1:(f true); case E2:(f false); rewrite ?E1 ?E2.\n\n  (* [by t1; t2; ...] выполняет вот эти вот [t1; t2; ...] для каждой подцели.\n     Т.е [by case;] сгенерит первые пару целей, потом следующие два [case]\n     дадут нам ещё несколько случаев. И вот для каждого случая мы\n     переписываем пока переписывается. *)\n\n   (* The [;] tactical applies the tactic on the right side of the\n      semicolon to all the subgoals produced by tactic on the left\n      side. *)\nQed.\n\n(* negb \\o odd means \"even\" *)\nLemma even_add :\n  {morph (negb \\o odd) : x y / x + y >-> x == y}.\nProof.\n  Eval hnf in {morph (negb \\o odd) : x y / x + y >-> x == y}.\n\n\n  Locate \"morph\".\n  Unset Printing Notations.\n  Set Printing Notations.\n  About morphism_2. (* Print morphism_2. *)\n  (* В сущности мы говорим, что можем \"продавить\" морфизм [f] внутрь аргументов:\n     Definition morphism_2 aOp rOp := forall x y, f (aOp x y) = rOp (f x) (f y). *)\n  rewrite /morphism_2.\n  (* Прикол в том, чтобы научиться доказывать леммы без\n     использования индукции и предпочитать переписывания.\n     Для этого нужно уметь искать другие леммы, тк\n     oбычно значительная часть времени по доказательству\n     уходит на поиск уже доказанных подходящих лемм,\n     которые можно задействовать/использовать. *)\n  move=> x y /=.\n  Search _ (odd (_ + _)).\n  About odd_add.\n  Locate \"(+)\".\n  About addb.\n  (* have H: ~~ odd (x + y). rewrite odd_add. *)\n  (* C [have H] это альтернативный путь, по которому можно пойти.\n     Но можно просто переписывать часть цели/выражения.*)\n  rewrite [in ~~ odd (x + y)] odd_add.\n  (* Вот такой синтаксис как выше позволяет выпoлнить\n     переписывание только в указанной часть выражения. *)\n  (* Search _ (~~ _ (+) _). *)\n  Search _ (~~ _ == _).\n  rewrite eqb_negLR.\n  Search _ (~~ ~~ _).\n  rewrite Bool.negb_involutive.\n  (* Search _ involutive. *)\n  (* Search _ (~~ _ = _). *)\n  (* rewrite negbK. *)\n\n  Search _ (~~ (_ (+) _)).\n  by rewrite negb_add.\nQed.\n\nEnd BooleanLogic.\n\n\n(* some properties of functional composition *)\n\nSection eq_comp.\nVariables A B C D : Type.\n\nLemma compA (f : A -> B) (g : B -> C) (h : C -> D) :\n  h \\o g \\o f = h \\o (g \\o f).\nProof.\n  done. Undo.\n  Unset Printing Notations.\n  (* Search _ (funcomp _). Print invariant. *)\n  Set Printing Notations.\n  About funcomp.\n  (*     (B -> A) ->     (C -> B) -> C -> A *)\n  (* (g : B -> C) \\o (f : A -> B) -> A -> C  *)\n  rewrite /funcomp.\n  done.\nQed.\n\nLemma eq_compl (f g : A -> B) (h : B -> C) :\n  f =1 g -> h \\o f =1 h \\o g.\nProof.\n  Unset Printing Notations.\n  Set Printing Notations.\n  rewrite /eqfun /funcomp.\n  move=> H a.\n  by rewrite (H a).\nQed.\n\nLemma eq_compr (f g : B -> C) (h : A -> B) :\n  f =1 g -> f \\o h =1 g \\o h.\nProof.\n  by rewrite /funcomp; move=> H a; rewrite (H (h a)).\nQed.\n\nLemma eq_idl (g1 g2 : A -> B) (f : B -> B) :\n  f =1 id -> f \\o g1 =1 f \\o g2 -> g1 =1 g2.\nProof.\n  rewrite /funcomp /eqfun.\n  move=> H_id H_eq_comp a.\n  move: (H_eq_comp a); clear H_eq_comp.\n  rewrite (H_id (g1 a)).\n  rewrite (H_id (g2 a)).\n  apply.\nQed.\n\nLemma eq_idr (f1 f2 : A -> B) (g : A -> A) :\n  g =1 id -> f1 \\o g =1 f2 \\o g -> f1 =1 f2.\nProof.\n  rewrite /funcomp.\n  move=> H_id H_eq_comp a.\n  move: (H_eq_comp a); clear H_eq_comp.\n  (* Когда смотришь на что-то типа [g =1 id]\n     нужно всегда иметь ввиду [foral x : A, g x = x]. *)\n  by rewrite (H_id a).\nQed.\n\nEnd eq_comp.\n\n(* Dependent pattern-matching practice.\n   Also see Lecture 3 (+links).\n*)\n\nAbout f_equal.\nAbout eq_add_S.\n\nAbout f_equal_pred.\nPrint eq_refl.\n\n(* f_equal_pred : forall x y : nat, x = y -> x.-1 = y.-1 *)\n\nDefinition succ_inj (n m : nat) :\n  S n = S m -> n = m\n:=\n  fun eqS =>\n    match\n      eqS in (_ = S v) (* v = m *)\n      return (n = v)\n    with\n    | erefl => erefl\n    end.\n\n\nDefinition false_eq_true_implies_False :\n  false = true -> False :=\n  fun prf =>\n    match prf in (_ = t)\n          return (if t then False else True)\n    with\n    | erefl => I\n    end.\n\n(* TL;DR про поиск:\n\n   https://github.com/math-comp/math-comp/wiki/Search\n   https://github.com/math-comp/math-comp/blob/master/CONTRIBUTING.md#where\n\n   В общем виде поисковый запрос выглядит так:\n\n   Search (-)?(symbol|pattern)+ (in (module)+)?\n\n   где\n     symbol  - какая-то подстрока\n     pattern - какой-то шаблон\n\n   Запрос вида Search pattern. ищет только в заключениях.\n   Чтобы поискать везде, включая предпосылки, нужно писать:\n\n   Search _ pattern.\n\n*)\n\nSearch -(_ < _) -(_ = _) \"odd\" in ssrnat.\n\n(*\nDefinition neq_sym A (x y : A) :\n  x <> y -> y <> x\n:=\n\nDefinition f_congr {A B} (f : A -> B) (x y : A) :\n  x = y  ->  f x = f y\n:=\n\nDefinition f_congr' A B (f g : A -> B) (x y : A) :\n  f = g  ->  x = y  ->  f x = g y\n:=\n\nDefinition pair_inj A B (a1 a2 : A) (b1 b2 : B) :\n  (a1, b1) = (a2, b2) -> (a1 = a2) /\\ (b1 = b2)\n:=\n*)\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/seminars/seminar02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8723473730188543, "lm_q1q2_score": 0.7639904843163391}}
{"text": "Require Export P08.\n\n\n\n(** **** Exercise: 4 stars (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    {{ 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    Fill in the blanks in following decorated program:\n    {{ X = m }} ->>\n    {{ (st X)! * Y = m! [Y|->1]}}\n  Y ::= 1;;\n    {{ (st X)! * Y = m! }} : I\n  WHILE X <> 0\n  DO   {{  I  /\\ X <> 0         }} ->>\n       {{    I [Y |-> Y*X] [X |-> X-1]         }}\n     Y ::= Y * X;;\n       {{    I [X |-> X-1]                     }}\n     X ::= X - 1\n       {{    I                                 }}\n  END\n    {{ (st X)! * Y = m!  /\\  st X = 0 }} ->>\n    {{ Y = m! }}\n*)\n\nPrint fact.\n\nLemma mult_dist_l : forall a b c,\n  a * (b + c) = a * b + a * c.\nProof. intros. induction a. reflexivity.\n  simpl. rewrite IHa. omega. Qed.\nLemma mult_dist_r : forall a b c,\n(a + b) * c = a * c + b * c.\nProof. intros. rewrite mult_comm. rewrite mult_dist_l. \n  rewrite mult_comm. replace (c*b) with (b*c). omega. apply mult_comm. Qed.\n\nLemma fact_mult : forall m,\n  m <> 0 -> fact (m - 1) * m = fact m.\nProof. intros. induction m. contradiction H. reflexivity.\n  simpl. replace (m-0) with m. replace (S m) with (1 + m).\n  rewrite mult_dist_l. rewrite mult_comm. simpl. rewrite mult_comm. omega. omega. omega. Qed.\n\nTheorem factorial_dec_correct: forall m,\n  {{ fun st => st X = m }} \n  Y ::= ANum 1 ;;\n  WHILE BNot (BEq (AId X) (ANum 0))\n  DO\n     Y ::= AMult (AId Y) (AId X) ;;\n     X ::= AMinus (AId X) (ANum 1)\n  END\n  {{ fun st => st Y = fact m }}.\nProof.\n  intros m. eapply hoare_consequence with (P':= (fun st=> fact (st X) * st Y = fact m)[Y|->ANum 1]) (Q':= (fun st => fact (st X) * st Y = fact m /\\ st X = 0)).\n  Case \"{{P'}} c;;while {{Q'}}\".\n    apply hoare_seq with (Q:= (fun st=> fact (st X) * st Y = fact m )). (* Q = I *)\n    SCase \"{{I}} while {{Q'}}\".\n      eapply hoare_consequence_post. apply hoare_while.\n      SSCase \"{{I/\\b}} c1;;c2 {{I}}\".\n        eapply hoare_seq. (* {{I'}} c2 {{I}} *) apply hoare_asgn.\n        (* {{I/\\b}} c1 {{I'}} *)\n        eapply hoare_consequence_pre. apply hoare_asgn.\n        unfold assert_implies, assn_sub. simpl. intros.\n        unfold update. simpl.\n        destruct H. destruct H.\n        apply negb_true_iff in H0. apply beq_nat_false_iff in H0.\n        replace (st Y * st X) with (st X * st Y).\n        rewrite mult_assoc. rewrite fact_mult. omega. assumption.\n        apply mult_comm.\n      SSCase \"I ->> Q'\".\n        unfold hoare_triple, assert_implies. intros.\n        destruct H. simpl in H0. apply negb_false_iff in H0. apply beq_nat_true_iff in H0. split; assumption.\n    SCase \"{{P'}} c {{I}}\".\n      apply hoare_asgn. \n  Case \"P ->> P'\".\n    unfold assert_implies, assn_sub.  intros.\n    unfold update. simpl. rewrite H. omega.\n  Case \"Q' ->> Q\".\n    unfold assert_implies. intros.\n    destruct H.  rewrite H0 in H. rewrite<-H. simpl. omega.\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/10/P09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509007, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.7639288983010115}}
{"text": "(** * Generic definitions. *)\n(** This script provides generic definition of relations that are used along the overall formalization. Most of the definitions and lemmas implemented here are quite trivial. *)\n\nRequire Export Arith Relations Program Omega Utf8.\n\n(** Some usefull tactics *)\nLtac inv H := inversion H;try subst;try congruence.\n\nLtac fomega := elimtype False;omega.\n\nLtac do_stable H P x0 :=\n  try assert(P x0) by (eapply H;esplit;eauto).\n\nLtac destruct2 v H :=\n  destruct v;destruct H.\n\n(** Reflexive and transitive closure of a relation [R] *)\n\nInductive star (A:Type)(R:relation A) : A -> A -> Prop :=\n| star_refl : \n  forall x:A, star A R x x\n| star_tran : \n  forall x y:A, \n    R x y -> forall z:A, star A R y z -> star A R x z.\n\n(** Indexed reflexive and transitive closure over a relation [R] *)\n\nInductive starn (A:Type)(R:relation A) : nat -> A -> A -> Prop :=\n| starn_refl : \n  forall x:A, \n    starn A R 0 x x\n| starn_tran : \n  forall x y:A, \n    R x y -> forall (n:nat)(z:A), starn A R n y z -> starn A R (S n) x z.\n\nHint Constructors star starn.\n\n(** Lemmas about the reflexive and transitive closure of a relation *)\n\nLemma star2starn:\n  forall A R x y,\n    star A R x y -> exists n, starn A R n x y.\nProof.\n  induction 1.\n  exists 0;auto.\n  destruct IHstar.\n  exists (S x0);econstructor 2;eauto.\nQed.\n\nLemma starn2star:\n  forall A R n x y,\n    starn A R n x y -> star A R x y.\nProof.\n  induction n;intros.\n  inversion H;auto.\n  inversion_clear H.\n  econstructor 2;eauto.\nQed.\n\n(** Two simple tactics to exchange [nat]-indexed closure with the non-indexed one. *)\n\nLtac do_star2starn H :=\n  let t := fresh \"H\" in \n    pose proof (star2starn _ _ _ _ H) as t;clear H;    \n    let n := fresh \"n\" with m := fresh \"H\" in destruct t as [n m].\n\nLtac do_starn2star H :=\n  let t := fresh \"H\" in \n    pose proof (starn2star _ _ _ _ _ H);clear H.\n\n(** Transitivity of closures (indexed or not). *)\n\nLemma star_starn_trans :\n  forall n A R x y,\n    starn A R n x y -> \n    forall z, \n      star A R y z ->  star A R x z.\nProof.\n  induction n;intros.\n  inversion_clear H.\n  assumption.\n  inversion_clear H.\n  constructor 2 with y0.\n  assumption.\n  eapply IHn.\n  apply H2.\n  assumption.\nQed.\n\nLemma star_trans :\n  forall A R x y,\n    star A R x y ->\n    forall z, star A R y z -> star A R x z.\nProof.\n  intros.\n  do_star2starn H.\n  eapply star_starn_trans;eauto.\nQed.\n\nLemma starn_trans :\n  forall n A R x y,\n    starn A R n x y ->\n    forall m z,\n      starn A R m y z ->\n      starn A R (n+m) x z.\nProof.\n  induction n;intros.\n  inv H.\n  simpl.\n  assumption.\n  inv H.\n  constructor 2 with y0;eauto.\nQed.\n\nLemma starn_ex :\n  forall n A R x y,\n    starn A R n x y ->\n    exists m x', m <= n /\\ starn A R m x x' /\\ starn A R (n-m) x' y.\nProof.\n  induction n;intros.\n  inv H.\n  simpl.\n  exists 0 y.\n  split;auto with arith.\n  inv H.\n  pose proof IHn _ _ _ _ H2.\n  destruct H0 as [m [x' [H4 [H5 H6]]]].\n  exists (S m) x'.\n  split;auto with arith.\n  split.\n  constructor 2 with y0;auto.\n  simpl.\n  assumption.\nQed.\n\n\nLemma star_R_star :\n  forall A (R:relation A) x y,\n    R x y ->\n    star A R x y.\nProof.\n  intros.\n  constructor 2 with y.\n  assumption.\n  constructor.\nQed.\n\n(** Closure for sub-relation. *)\n\nLemma star_R_star_incl :\n  forall A (R1 R2:relation A) x y,\n    (forall a b, R1 a b -> R2 a b) ->\n    star A R1 x y ->\n    star A R2 x y.\nProof.\n  intros until y;intro H.\n  induction 1;auto.\n  constructor 2 with y.\n  apply H.\n  assumption.\n  apply IHstar.\nQed.\n\n(** Closure of a reflexive and transitive relation. *)\n\nLemma star_R_trans_imply_own :\n  forall A (R:relation A) x y,\n    (forall a, R a a) ->\n    (forall a b c, R a b -> R b c -> R a c) ->\n    star _ R x y -> R x y.\nProof.\n  induction 3;intros.\n  apply H.\n  inv H2.\n  apply H0 with y;assumption.\nQed.\n   \n\n(** Alternative inductive principle for dealing with the reflexive and\ntransitive closures. This one is used, in particular, in the soundness\nproof of the while rule. \n\nThis lemma indeed states that if we reach a state [s'] such that [P\ns'] is statisfied in all the intermediate states [s''], then the\nproperty [P] models the overall computation. This implies that the\nreflexive and transitive closure [star] must be decomposed in the nth\ntransitions in the middle. One can look at this particular inductive\nprinciple as a more detailed notion of well-founded induction over the\nnatural numbers, where each natural number refers to the nth-step of\nexecution of a program.\n*)\n\nLemma RT_ind_gen : \n    forall (X:Type) (R P : X -> X -> Prop),\n      (forall x : X, P x x) ->\n      (forall (x y z: X) n, R x y -> starn _ R n y z -> \n      (forall y1 k, k <= n -> starn _ R k y1 z -> P y1 z) -> P x z) ->\n      forall x y : X, star _ R x y -> P x y.\nProof.\n  intros.\n  case (star2starn _ _ _ _ H1).\n  intros.\n  assert (forall k z, k <= x0 -> starn _ R k z y -> P z y).\n  induction H2.\n  intros.\n  replace k with 0 in *;try omega.\n  inv H3;auto.\n  intros.\n  assert(k <= n \\/ k = S n) by omega.\n  destruct H6.\n  eapply IHstarn with k.\n  eapply starn2star with n.\n  assumption.\n  assumption.\n  assumption.\n  subst k.\n  inv H5.\n  pose proof H8.\n  do_starn2star H3.\n  eapply H0;eauto.\n  eapply H3;eauto.\nQed.\n\n", "meta": {"author": "dmrpereira", "repo": "RGCoq", "sha": "20f6aee522cf744e15011104ba23c99f61d4ce9c", "save_path": "github-repos/coq/dmrpereira-RGCoq", "path": "github-repos/coq/dmrpereira-RGCoq/RGCoq-20f6aee522cf744e15011104ba23c99f61d4ce9c/generic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.763928880012843}}
{"text": "(* Exercise 47 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nVariable A : Prop.\n\nTheorem exercise_047 : (forall x, P x -> A) -> (exists x, P x) -> A.\nProof.\nimp_i a1.\nimp_i a2.\nexi_e (exists x:D, P x) a a3.\nhyp a2.\nimp_e (P a).\nall_e (forall x:D, P x -> A) a.\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_pred047.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7638818214300281}}
{"text": "Inductive Exp := ConstE : nat -> Exp | BinopE : (nat -> nat -> nat) -> (Exp -> Exp -> Exp).\nInductive StackOp := PushS : nat -> StackOp | BinopS : (nat -> nat -> nat) -> StackOp.\n\nFixpoint evalExp e := match e with\n    | ConstE n => n\n    | BinopE f e1 e2 => f (evalExp e1) (evalExp e2)\n    end.\n\nDefinition builder A := list A -> list A.\nDefinition build {A} (b : builder A) : list A := b nil.\nDefinition singleton {A} (x : A) : builder A := cons x.\nDefinition append {A} (x y : builder A) : builder A := fun z => x (y z).\nFixpoint prefix {A} (xs : list A) : builder A := match xs with nil => fun a => a | cons y ys => append (singleton y) (prefix ys) end.\n\nRequire Import Setoid.\nLemma build_prefix_id : forall A (xs : list A), build (prefix xs) = xs.\n    intros a xs; induction xs; [|rewrite <- IHxs at 2]; reflexivity. Qed.\nLemma prefix_nil_id : forall A (xs : list A), prefix xs nil = xs.\n    intros a xs; induction xs; [|rewrite <- IHxs at 2]; reflexivity. Qed.\n\nTheorem append_assoc : forall A (x y z : builder A), append x (append y z) = append (append x y) z.\n    intros A x y z. unfold append. reflexivity. Qed.\n\nFixpoint compile e := match e with\n    | ConstE n => singleton (PushS n)\n    | BinopE f e1 e2 => append (append (compile e2) (compile e1)) (singleton (BinopS f))\n    end.\n\nFixpoint bad_compile e := match e with\n    | ConstE n => singleton (PushS n)\n    | BinopE f e1 e2 => append (append (bad_compile e1) (bad_compile e2)) (singleton (BinopS f))\n    end.\n\n(*Eval cbn in compile (BinopE mult (BinopE plus (ConstE 2) (ConstE 3)) (ConstE 4)) nil.*)\n\nFixpoint evalStackM (prog : list StackOp) (stack : list nat) := (match prog with\n    | PushS n :: prog' => evalStackM prog' (n :: stack)\n    | BinopS f :: prog' => match stack with\n        | x :: y :: stack' => evalStackM prog' (f x y :: stack')\n        | _ => None\n        end\n    | nil => match stack with\n        | x :: _ => Some x\n        | nil => None\n        end\n    end)%list.\n\nTheorem compile_correct : forall e p s, evalStackM ((compile e) p) s = evalStackM p (evalExp e :: s)%list.\n    intros e. induction e; intros p s.\n    - reflexivity.\n    - cbn. unfold append. rewrite IHe2, IHe1. reflexivity.\n    Qed.\n\nTheorem bad_compile_correct : forall e p s, evalStackM ((bad_compile e) p) s = evalStackM p (evalExp e :: s)%list.\n    intros e. induction e; intros p s.\n    - reflexivity.\n    - cbn. unfold append. rewrite IHe1, IHe2. cbn.\n(* At this point, the goal is:\nevalStackM p (n (evalExp e2) (evalExp e1) :: s) =\nevalStackM p (n (evalExp e1) (evalExp e2) :: s)\nwhich demonstrates that bad_compile is unprovable without assuming n's commutativity\n*)\n    Show. Abort. \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/expression_language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7637986880760976}}
{"text": "Require Import bool.\nRequire Import list.\nRequire Import In.\nRequire Import filter.\n\n(* merge k m l  == 'l is an in order merge of k and m' *)\nInductive merge (a:Type) : list a -> list a -> list a -> Prop :=\n| merge_nil_l  : forall (l:list a), merge a [] l l\n| merge_nil_r  : forall (l:list a), merge a l [] l\n| merge_cons_l : forall (k m l: list a) (x:a), \n    merge a k m l -> merge a (x :: k) m (x :: l)\n| merge_cons_r : forall (k m l:list a) (x:a),\n    merge a k m l -> merge a k (x :: m) (x :: l) \n.\n\nArguments merge {a} _ _ _.\n\nTheorem filter_merge : forall (a:Type) (test:a -> bool) (k m l:list a),\n    (forall x, In x k -> test x = true) ->\n    (forall x, In x m -> test x = false) ->\n    merge k m l -> \n    filter test l = k.\nProof.\n    intros a test k m l Hk Hm H. revert Hk Hm.\n    induction H as [l|l|k m l x H IH|k m l x H IH].\n    - intros H0 H. clear H0. apply filter_of_false. exact H.\n    - intros H H0. clear H0. apply filter_of_true. exact H.\n    - intros H1 H2. assert (test x = true) as Hx. { apply H1. left. reflexivity. }\n        simpl. rewrite Hx. assert (filter test l = k) as H0.\n            { apply IH.\n                + intros y H'. apply H1. right. exact H'.\n                + exact H2.\n            }\n        rewrite H0. reflexivity.\n    - intros H1 H2. assert (test x = false) as Hx. { apply H2. left. reflexivity. }\n        simpl. rewrite Hx. apply IH.\n            + exact H1.\n            + intros y H'. apply H2. right. exact H'.\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/sf/merge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7637986841659884}}
{"text": "(** Syntax and semantics of the language called IMP, a small\n    imperative structured language. *)\n\nRequire Import Coq.Program.Equality. \nRequire Import Bool.             \nRequire Import ZArith.           \nRequire Import Sequences.        \n\nOpen Scope Z_scope.             \n\n(** * 1. Abstract syntax *)\n\n(** Variables are identified by integers. *)\nDefinition ident : Type := Z.\n\nDefinition eq_ident: forall (x y: ident), {x=y}+{x<>y} := Z_eq_dec.\n\n(** Syntax of arithmetic expressions  *)\nInductive aexp : Type :=\n  | Const: Z -> aexp                    (**r constant *)\n  | Var: ident -> aexp                  (**r variable *)\n  | Plus: aexp -> aexp -> aexp          (**r sum [a1 + a2] *)\n  | Minus: aexp -> aexp -> aexp.         (**r difference [a1 - a2] *)\n\n(** Syntax of boolean expressions.  \n    Boolean expressions are used as conditions in [if] and [while] commands. *)\nInductive bexp : Type :=\n  | TRUE: bexp                          (**r always true *)\n  | FALSE: bexp                         (**r always false *)\n  | Eq: aexp -> aexp -> bexp            (**r equality test [a1 == a2] *)\n  | Le: aexp -> aexp -> bexp            (**r less or equal test [a1 <= a2] *)\n  | Not: bexp -> bexp                   (**r negation [!b] *)\n  | And: bexp -> bexp -> bexp.          (**r conjunction [b1 & b2] *)\n\n(** Syntax of commands (\"statements\"). *)\nInductive command : Type :=\n  | Skip                                (**r do nothing *)\n  | Assign: ident -> aexp -> command    (**r assignment [x = a;] *)\n  | Seq: command -> command -> command  (**r sequence [c1; c2] *)\n  | If: bexp -> command -> command -> command (**r conditional [if (b) { c1 } else {c2}] *)\n  | While: bexp -> command -> command.  (**r loop [while (b) { c }] *)\n\nDefinition vx : ident := 1.\nDefinition vy : ident := 2.\nDefinition vq : ident := 3.\nDefinition vr : ident := 4.\n\n(* Define the following commands : \n- assignment \"vr = vx\"\n- the infinite loop such that its condition is always true and its body is the skip command \n- the euclidian division, corresponding to the following algorithm\n<<\n                      r = x;\n                      q = 0;\n                      while (y <= r) {\n                          r = r - y;\n                          q = q + 1;\n                      }\n>>\n*)\nDefinition assign1 := Assign vx (Var vr).\n\nDefinition infinite_loop := While (TRUE) Skip.\n\nDefinition euclidean_division : command :=\n  Seq (Assign vr (Var vx))\n   (Seq (Assign vq (Const 0))\n     (While (Le (Var vy) (Var vr))\n       (Seq (Assign vr (Minus (Var vr) (Var vy)))\n            (Assign vq (Plus (Var vq) (Const 1)))))).\n\n(** * 2. Denotational semantics (begin) *)\nDefinition state := ident -> Z.\n\nDefinition initial_state: state := fun (x: ident) => 0.\n\n(** Update the value of a variable, without changing the other variables. *)\nDefinition update (s: state) (x: ident) (n: Z) : state :=\n  fun y => if eq_ident x y then n else s y.\n\n(** Good variable properties for [update]. *)\n\nLemma update_same:\n  forall x val m, (update m x val) x = val.\nProof.\n  unfold update; intros. destruct (eq_ident x x); congruence.\nQed.\n\nLemma update_other:\n  forall x val m y, x <> y -> (update m x val) y = m y.\nProof.\n  unfold update; intros. destruct (eq_ident x y); congruence.\nQed.\n\n(* Evaluation of expressions *)\n\nFixpoint aeval (s: state) (e: aexp) {struct e} : Z :=\n  match e with\n  | Var x => s x\n  | Const n => n\n  | Plus e1 e2 => aeval s e1 + aeval s e2 \n  | Minus e1 e2 => aeval s e1 - aeval s e2 \n  end.\n\nFixpoint beval (s: state) (b: bexp) : bool :=\n  match b with\n  | TRUE => true\n  | FALSE => false\n  | Eq e1 e2 =>\n      if Z_eq_dec (aeval s e1) (aeval s e2) then true else false\n  | Le e1 e2 =>\n      if Z_le_dec (aeval s e1) (aeval s e2) then true else false \n  | Not b1     => negb (beval s b1)\n  | And b1 b2  => (beval s b1) && (beval s b2)\n  end.\n\nCompute (aeval initial_state (Var vx)).\n\nCompute (\n  let x : ident := 0 in\n  let s : state := update initial_state x 12 in\n  aeval s (Plus (Var x) (Const 1))).\n\n(* An example of optimization of expressions \n   Write a function that transforms any arithmetic expression such as\n   0 + a into a, and leave other expressions unchanged. *)\n\nFixpoint optimize_0plus (e:aexp) : aexp := \n  match e with\n  | Const n => Const n\n  | Var v => Var v   \n  | Plus (Const 0) e2 => \n      optimize_0plus e2\n  | Plus e1 e2 => \n      Plus (optimize_0plus e1) (optimize_0plus e2)\n  | Minus e1 e2 => \n      Minus (optimize_0plus e1) (optimize_0plus e2)\n  end.\n\nCompute (\n  optimize_0plus (Plus (Const 2) \n                       (Plus (Const 0) \n                             (Plus (Const 0) (Const 1))))).\n\n(* Prove that the previous optimization is sound:\n   every evaluation of an optimized expression yields the same value as\n   the evaluation of the original expression.\n   You should need to use induction here ! \n*)\n\nTheorem optimize_0plus_sound : forall s e,\naeval s (optimize_0plus e) = aeval s e.\nProof.\nintros se; induction e; simpl; auto.\n\n(* Plus *)\ndestruct e1. \ndestruct z; simpl. auto.\nrewrite IHe2; auto.\nrewrite IHe2; auto.\nsimpl. rewrite IHe2; auto.\n\nsimpl; simpl in IHe1; rewrite IHe1; rewrite IHe2; auto.\n\nsimpl. rewrite IHe2. simpl in IHe1. rewrite IHe1. auto. \n\n(* Minus *)\nrewrite IHe1; rewrite IHe2; auto.\nQed.\n\n(** * 3. Small-step semantics *)\n\nInductive red: command * state -> command * state -> Prop :=\n  | red_assign: forall x e s,\n      red (Assign x e, s) (Skip, update s x (aeval s e))\n  | red_seq_left: forall c1 c2 s c1' s',\n      red (c1, s) (c1', s') ->\n      red (Seq c1 c2, s) (Seq c1' c2, s')\n  | red_seq_skip: forall c s,\n      red (Seq Skip c, s) (c, s)\n  | red_if_true: forall s b c1 c2,\n      beval s b = true ->\n      red (If b c1 c2, s) (c1, s)\n  | red_if_false: forall s b c1 c2,\n      beval s b = false ->\n      red (If b c1 c2, s) (c2, s)\n  | red_while_true: forall s b c,\n      beval s b = true ->\n      red (While b c, s) (Seq c (While b c), s)\n  | red_while_false: forall b c s,\n      beval s b = false ->\n      red (While b c, s) (Skip, s).\n\n(* Prove the following lemma stating that red is deterministic.   \n   Use \"induction 1\" to reason by induction on derivations.\n*)\nLemma red_deterministic:\n  forall cs cs1, red cs cs1 -> forall cs2, red cs cs2 -> cs1 = cs2.\nProof.\n  induction 1; intros cs2 RED; inversion RED; subst; auto; try congruence.\n  generalize (IHred _ H4). congruence.\n  inversion H. \n  inversion H3. \nQed.\n\n(** * 4. Natural sematnics (big-step) *)\n\n(** [eval m a n] is true if the expression [a] evaluates to value [n] in memory state [m]. *)\n\nInductive eval: state -> aexp -> Z -> Prop :=\n  | eval_const: forall m n,\n      eval m (Const n) n\n  | eval_var: forall m x n,\n      m x = n ->\n      eval m (Var x) n\n  | eval_plus: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 ->\n      eval m (Plus a1 a2) (n1 + n2)\n  | eval_minus: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 ->\n      eval m (Minus a1 a2) (n1 - n2).\n\n(** Prove the following example of evaluation. *)\nGoal eval (update initial_state vx 42) (Plus (Var vx) (Const 2)) 44.\nProof.\n  change 44 with (42 + 2). apply eval_plus.\n  apply eval_var. apply update_same. \n  apply eval_const.\nQed.\n\n(** ** Boolean expressions *)\n\n(** [beval m be bv] is true if the boolean expression [be] evaluates to the\n  boolean value [bv] (either [true] or [false]) in memory state [m]. *)\n\nInductive beval2: state -> bexp -> bool -> Prop :=\n  | beval_true: forall m,\n      beval2 m TRUE true\n  | beval_false: forall m,\n      beval2 m FALSE false\n  | beval_eq_true: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 -> n1 = n2 ->\n      beval2 m (Eq a1 a2) true\n  | beval_eq_false: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 -> n1 <> n2 ->\n      beval2 m (Eq a1 a2) false\n  | beval_le_true: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 -> n1 <= n2 ->\n      beval2 m (Le a1 a2) true\n  | beval_le_false: forall m a1 a2 n1 n2,\n      eval m a1 n1 -> eval m a2 n2 -> n1 > n2 ->\n      beval2 m (Le a1 a2) false\n  | beval_not: forall m be1 bv1,\n      beval2 m be1 bv1 ->\n      beval2 m (Not be1) (negb bv1)\n  | beval_and: forall m be1 bv1 be2 bv2,\n      beval2 m be1 bv1 -> beval2 m be2 bv2 ->\n      beval2 m (And be1 be2) (bv1 && bv2).\n\n(** [exec m c m'] is true if the command [c], executed in the initial\n  state [m], terminates without error in final state [m']. *)\n\nInductive exec: state -> command -> state -> Prop :=\n  | exec_skip: forall m,\n      exec m Skip m\n  | exec_assign: forall m x a,\n      exec m (Assign x a) (update m x (aeval m a))\n  | exec_seq: forall m c1 c2 m' m'',\n      exec m c1 m' -> exec m' c2 m'' ->\n      exec m (Seq c1 c2) m''\n  | exec_if_true: forall m b ifso ifnot m',\n      beval m b = true -> exec m ifso m' ->\n      exec m (If b ifso ifnot) m'\n  | exec_if_false: forall m b ifso ifnot m',\n      beval m b = false -> exec m ifnot m' ->\n      exec m (If b ifso ifnot) m'\n  | exec_while_false: forall m b body,\n      beval m b = false ->\n      exec m (While b body) m\n  | exec_while_true: forall m b body m' m'',\n      beval m b = true -> exec m body m' -> exec m' (While b body) m'' ->\n      exec m (While b body) m''.\n\n(** Prove the following example of program execution  *)\nGoal let prog := If (Le (Const 1) (Const 2)) (Assign vx (Const 3)) (Assign vx (Const 0)) in\n     exists m, exec initial_state prog m /\\ m vx = 3.\nProof.\n  simpl. econstructor; split. \n  apply exec_if_true. simpl. auto. \n  eapply exec_assign. \n  apply update_same. \nQed.\n\n(** Example of non terminating execution *)\n\nGoal let prog := While TRUE Skip in\n     forall m m', ~ exec m prog m'.\nProof.\n  simpl; intros; red; intros. dependent induction H. inversion H. auto.\nQed.\n\nLtac inv H := inversion H; subst; clear H.\n\n(* In order to prove this lemma, you should need \n  several uses of inversion, but not induction. *)\nLemma equiv1 :\n  forall x i m m', \n   exec m (Seq (Assign x (Const 1)) (While (Le (Var x) (Const 2)) i)) m' -> \n   exec m (Seq (Assign x (Const 1))\n             (Seq i (While (Le (Var x) (Const 2)) i))) m'.\nProof.\nintros.\ninv H. inv H3. inv H5.\ninv H3.\nrewrite update_same in H0. discriminate. \neconstructor.\neconstructor.\neconstructor; eauto.\nQed.\n\n\n(** * 5. Small-step semantics (cont'd) *)\n\n(** Un programme termine sans erreurs s'il existe une suite finie de transitions\n- depuis l'etat initial: commande = programme, etat memoire = etat memoire initial\n- jusqu'a un etat final: commande = [Skip].\n*)\n\nDefinition prog_terminates (prog: command) (m_init m_final: state) : Prop :=\n  star red (prog, m_init) (Skip, m_final).\n\n(** Si [R] est une relation binaire, [star R] est sa fermeture\nreflexive et transitive.  (Voir le module [Sequences] pour la\ndefinition.)  [star red] represente donc une suite de\nzero, une ou plusieurs etapes de calcul. *)\n\n(** Un programme diverge s'il existe une suite infinie de transitions\na partir de l'etat initial. *)\n\nDefinition prog_diverges (prog: command) (m_init: state) : Prop :=\n  infseq red (prog, m_init).\n\n(** De meme, [infseq R] represente une suite infinie de transitions [R].\n  (egalement defini dans le module [Sequences].) *)\n\n(** Enfin, un programme \"plante\" s'il existe une suite finie de transitions depuis \nl'etat initial jusqu'a un etat qui n'est pas final et qui ne peut pas faire de transitions. *)\n\nDefinition prog_crashes (prog: command) (m_init: state) : Prop :=\n  exists c, exists m,\n      star red (prog, m_init) (c, m)\n   /\\ irred red (c, m) /\\ ~(c = Skip ).\n\n(** * 6. Premieres preuves d'equivalences entre semantiques *)\n\n(** ** Semantique naturelle -> semantique a transitions. *)\n\nRemark star_red_seq_left:\n  forall c s c' s' c2,\n  star red (c, s) (c', s') ->\n  star red (Seq c c2, s) (Seq c' c2, s').\nProof.\n  intros. dependent induction H. constructor.\n  destruct b. econstructor. apply red_seq_left; eauto. eauto. \nQed. \n\nLemma exec_terminates:\n  forall m c m', exec m c m' -> prog_terminates c m m'.\nProof.\n  induction 1; intros.\n(* skip *)\n  apply star_refl.\n(* assign *)\n  apply star_one. constructor; auto.\n(* seq *)\n  apply star_trans with (Seq Skip c2, m'). \n  apply star_red_seq_left. auto. \n  apply star_step with (c2, m'). apply red_seq_skip. auto.\n(* if true *)\n  eapply star_step. apply red_if_true; auto. apply IHexec.\n(* if false *)\n  eapply star_step. apply red_if_false; auto. apply IHexec.\n(* while false *)\n  apply star_one. apply red_while_false; auto. \n(* while true *)\n  eapply star_step. apply red_while_true; auto. \n  apply star_trans with (Seq Skip (While b body), m').\n  apply star_red_seq_left. auto. \n  eapply star_step. eapply red_seq_skip. auto.\nQed.\n\n(** ** Small-step -> big-step *)\n\n(** The reverse implication, from small-step to big-step, is more subtle.\nThe key lemma is the following, showing that one step of reduction\nfollowed by a big-step evaluation to a final state can be collapsed\ninto a single big-step evaluation to that final state. *)\n\nLemma red_preserves_exec:\n  forall c1 s1 c2 s2,\n  red (c1, s1) (c2, s2) ->\n  forall s3,\n  exec s2 c2 s3 ->\n  exec s1 c1 s3.\nProof.\n  intros until s2. intro STEP. dependent induction STEP; intros.\n(* assign *)\n  inversion H; subst. apply exec_assign. \n(* sequence *)\n  inversion H; subst. apply exec_seq with m'. eauto. auto.\n(* sequence finish *)\n  apply exec_seq with s2. apply exec_skip. auto.\n(* ifso *)\n  apply exec_if_true; auto.\n(* ifnot *)\n  apply exec_if_false; auto.\n(* while *)\n  inversion H0; subst. \n  apply exec_while_true with m'; auto.\n  inversion H0; subst. \n  apply exec_while_false; auto.\nQed.\n\n(** As a consequence, a term that reduces to [Skip] evaluates in big-step\n  with the same final state. *)\n\nTheorem terminates_exec:\n  forall m c m',\n  prog_terminates c m m' ->\n  exec m c m'.\nProof.\n   unfold prog_terminates; intros. dependent induction H.\n  apply exec_skip.\n  destruct b as [m1 c1]. apply red_preserves_exec with m1 c1; auto.\nQed.\n\n(** *8. Definitionnal interpreter *)\n\n(** We can improve the readability of this definition by introducing\n    an auxiliary function [bind_option] to hide some of the \"plumbing\"\n    involved in repeatedly matching against optional states. *)\n\nDefinition bind (r: option state) (f: state -> option state) : option state :=\n  match r with Some s => f s | None => None end.\n\nFixpoint interp (n: nat) (c: command) (s: state) {struct n} : option state :=\n  match n with\n  | O => None\n  | S n' =>\n      match c with\n      | Skip => Some s\n      | Assign x e => Some (update s x (aeval s e))\n      | Seq c1 c2 => bind (interp n' c1 s) (fun s1 => interp n' c2 s1)\n      | If b c1 c2 => interp n' (if (beval s b) then c1 else c2) s\n      | While b c1 => if (beval s b)\n                      then (bind (interp n' c1 s) (fun s1 => interp n' (While b c1) s1))\n                      else Some s\n     end\n  end.\n\nTheorem interp_more: forall i1 i2 s s' c,\n  (i1 <= i2)%nat -> interp i1 c s = Some s' -> \n  interp i2 c s = Some s'.\nProof. \ninduction i1 as [|i1']; intros i2 s s' c Hle Hinterp.\n(* i1 = 0 *)\n    inversion Hinterp.\n(* i1 = S i1 *)\n    destruct i2 as [|i2']. inversion Hle. \n    assert (Hle': (i1' <= i2')%nat) by omega.\n    destruct c.\n    (* Skip *)\n      simpl in Hinterp. inversion Hinterp. \n      reflexivity.\n    (* assign *)\n      simpl in Hinterp. inversion Hinterp.\n      reflexivity.\n    (* sequence *)\n      simpl in Hinterp. simpl. \n      remember (interp i1' c1 s) as s1'o.\n      destruct s1'o.\n        symmetry in Heqs1'o.\n        apply (IHi1' i2') in Heqs1'o; try assumption.\n        rewrite Heqs1'o. simpl. simpl in Hinterp.\n        apply (IHi1' i2') in Hinterp; try assumption.\n        inversion Hinterp.\n     (* if *)\n      simpl in Hinterp. simpl.\n      remember (beval s b) as bval.\n      destruct bval; apply (IHi1' i2') in Hinterp; assumption.\n     (* while *)\n    simpl in Hinterp. simpl.\n      destruct (beval s b); try assumption. \n      remember (interp i1' c s) as s1'o.\n      destruct s1'o.\n        symmetry in Heqs1'o.\n        apply (IHi1' i2') in Heqs1'o; try assumption. \n        rewrite -> Heqs1'o. simpl. simpl in Hinterp. \n        apply (IHi1' i2') in Hinterp; try assumption.\n        simpl in Hinterp. inversion Hinterp.  \nQed.\n\nLemma interp_exec:\n  forall n c s s', interp n c s = Some s' -> exec s c s'.\nProof.\nAdmitted.\n\nLemma exec_interp:\n  forall s c s', exec s c s' -> exists n, interp n c s = Some s'.\nProof.\nAdmitted.\n\n(** We now show a similar result for the coinductive big-step semantics\n  for divergence. *)\n\nRemark exec_interp_either:\n  forall n c s s', exec s c s' -> interp n c s = None \\/ interp n c s = Some s'.\nProof.\n  intros. \n  destruct (exec_interp _ _ _ H) as [m EVAL].\n  remember (interp n c s). destruct o.\n  right.\n  assert ((m <= n \\/ n <= m)%nat) by omega.\n  destruct H0. \n  assert (interp n c s = Some s'). \n    apply interp_more with m; auto.\n  congruence.\n  assert (interp m c s = Some s0).\n    apply interp_more with n; auto.\n  congruence.\n  left; auto.\nQed.\n\n(** For the converse result, we again need a bit of classical logic\n  (the axiom of excluded middle) to show that the sequence\n  [n => interp st c n] has a limit: it stabilizes to a fixed result\n  when [n] is big enough. *)\n\nRequire Import Classical.\nRequire Import Max.\n\nLemma interp_limit:\n  forall s c,\n  exists res, exists m, forall n, (m <= n)%nat -> interp n s c = res.\nProof.\n  intros.\n  destruct (classic (forall n, interp n s c = None)).\n(* divergence *)\n  exists (@None state); exists 0%nat; auto.\n(* convergence *)\n  assert (EX: exists m, interp m s c <> None).\n    apply not_all_ex_not. auto.\n  destruct EX as [m EVAL].\n  remember (interp m s c) as res.\n  destruct res as [s' | ]. \n  exists (Some s'); exists m; intros.\n  apply interp_more with m; auto. \n  congruence.\nQed.\n\n(** * 9. Definitional interpreter and denotational semantics *)\n\n(** Using yet another bit of logic (an axiom of description -- a variant\n  of the axiom of choice), we can show the existence of a function\n  [denot st c] which is the limit of the sequence [n => ceval_step st c n]\n  as [n] goes to infinity.  The result of this function is to be\n  interpreted as the denotation of command [c] in state [st]:\n- [denot st c = None] (or \"bottom\") means that [c] diverges\n- [denot st c = Some st'] means that [c] terminates with final state [st'].\n*)\n\nRequire Import ClassicalDescription.\n\nDefinition interp_limit_dep (s: state) (c: command) :\n  { res: option state | exists m, forall n, (m <= n)%nat -> interp n c s = res}.\nProof.\n  intros. apply constructive_definite_description. \n  destruct (interp_limit c s) as [res X]. \n  exists res. red. split. auto. intros res' X'. \n  destruct X as [m P]. destruct X' as [m' P']. \n  transitivity (interp (max m m') c s).\n  symmetry. apply P. apply le_max_l.\n  apply P'. apply le_max_r.\nQed.\n\nDefinition denot (s: state) (c: command) : option state :=\n  proj1_sig (interp_limit_dep s c).\n\n\nLemma denot_limit:\n  forall s c,\n  exists m, forall n, (m <= n)%nat -> interp n c s = denot s c.\nProof.\n  intros. unfold denot. apply proj2_sig.\nQed.\n\nLemma denot_charact:\n  forall s c m res,\n  (forall n, (m <= n)%nat -> interp n c s = res) ->\n  denot s c = res.\nProof.\n  intros. destruct (denot_limit s c) as [m' I].\n  assert (interp (max m m') c s = res).\n    apply H. apply le_max_l.\n  assert (interp (max m m') c s = denot s c).\n    apply I. apply le_max_r.\n  congruence.\nQed.\n\n(**  From a definitional interpreter to a denotational semantics *)\n\nLemma denot_terminates:\n  forall s c n s', interp n c s = Some s' -> denot s c = Some s'.\nProof.\n  intros.\n  apply denot_charact with n. intros. apply interp_more with n; auto.\nQed.\n\n(** We can then show that this [denot] function satisfies the equations of\n  denotational semantics for the Imp language. *)\n\nLemma denot_skip:\n  forall s, denot s Skip = Some s.\nProof.\n  intros. apply denot_terminates with 1%nat. simpl. auto.\nQed.\n\nLemma denot_assign:\n  forall v a s, denot s (Assign v a) = Some (update s v (aeval s a)).\nProof.\n  intros. apply denot_terminates with 1%nat. simpl. auto.\nQed.\n\nLemma denot_seq:\n  forall c1 c2 s, \n  denot s (Seq c1 c2) = bind (denot s c1) (fun s' => denot s' c2).\nProof.\n  intros. destruct (denot_limit s c1) as [m1 LIM1].\n  destruct (denot s c1) as [s' | ]; simpl.\n(* c1 terminates *)\n  destruct (denot_limit s' c2) as [m2 LIM2].\n  apply denot_charact with (S (max m1 m2)). intros. \n  destruct n. elimtype False; omega. \n  simpl. rewrite LIM1; simpl. apply LIM2. \n  apply le_trans with (max m1 m2). apply le_max_r. omega.\n  apply le_trans with (max m1 m2). apply le_max_l. omega.\n(* c1 diverges *)\n  apply denot_charact with (S m1); intros.\n  destruct n. elimtype False; omega. \n  simpl. rewrite LIM1; simpl. auto. omega.\nQed.\n\nLemma denot_ifthenelse:\n  forall b c1 c2 s,\n  denot s (If b c1 c2) =\n  if beval s b then denot s c1 else denot s c2.\nProof.\n  intros. \n  remember (beval s b). destruct b0.\n(* b is true *)\n  destruct (denot_limit s c1) as [m LIM].\n  apply denot_charact with (S m); intros.\n  destruct n. elimtype False; omega. \n  simpl. rewrite <- Heqb0. apply LIM. omega.\n(* b is false *)\n  destruct (denot_limit s c2) as [m LIM].\n  apply denot_charact with (S m); intros.\n  destruct n. elimtype False; omega. \n  simpl. rewrite <- Heqb0. apply LIM. omega.\nQed.\n\nLemma denot_while:\n  forall b c s,\n  denot s (While b c) =\n  if beval s b\n  then bind (denot s c) (fun s' => denot s' (While b c))\n  else Some s.\nProof.\n  intros. remember (beval s b). destruct b0.\n(* b is true *)\n  destruct (denot_limit s c) as [m1 LIM1].\n  destruct (denot s c) as [s' | ]; simpl.\n(* c terminates *)\n  destruct (denot_limit s' (While b c)) as [m2 LIM2].\n  apply denot_charact with (S (max m1 m2)). intros. \n  destruct n. elimtype False; omega. \n  simpl. rewrite <- Heqb0. rewrite LIM1; simpl. apply LIM2. \n  apply le_trans with (max m1 m2). apply le_max_r. omega.\n  apply le_trans with (max m1 m2). apply le_max_l. omega.\n(* c diverges *)\n  apply denot_charact with (S m1); intros.\n  destruct n. elimtype False; omega. \n  simpl. rewrite <- Heqb0. rewrite LIM1; simpl. auto. omega.\n(* b is false *)\n  apply denot_terminates with 1%nat. simpl. rewrite <- Heqb0. auto.\nQed.\n\n(** Moreover, [denot s (While b c)] is the least fixpoint of the equation above. *)\n\nDefinition result_less_defined (r1 r2: option state) : Prop :=\n  r1 = None \\/ r1 = r2.\n\nLemma denot_while_least_fixpoint:\n  forall b c (f: state -> option state),\n  (forall s,\n   f s = if beval s b then bind (denot s c) f else Some s) ->\n  (forall s,\n   result_less_defined (denot s (While b c)) (f s)).\nProof.\n  intros. \n  assert (forall n s, result_less_defined (interp n (While b c) s) (f s)).\n    induction n; intros; simpl.\n    red; auto.\n    rewrite (H s0). destruct (beval s0 b). \n    remember (interp n c s0). destruct o; simpl.\n    replace (denot s0 c) with (Some s1). simpl.\n    apply IHn. symmetry. eapply denot_terminates; eauto. \n    red; auto.\n    red; auto.\n  destruct (denot_limit s (While b c)) as [m LIM].\n  rewrite <- (LIM m). auto. omega.\nQed.\n\n(** Composing the various results so far, we obtain the following equivalences\n  between the denotational semantics and the big-step semantics. *)\n\nLemma denot_exec:\n  forall c s s',\n  exec s c s'  <->  denot s c = Some s'.\nProof.\n  intros; split; intros.\n(* -> *)\n  destruct (exec_interp _ _ _ H) as [m EVAL].\n  apply denot_terminates with m; auto.\n(* <- *)\n  destruct (denot_limit s c) as [m LIMIT].\n  apply interp_exec with (n:=m). rewrite <- H. apply LIMIT. omega.\nQed.\n\n\n(** Semantique executable -> semantique relationnelle *)\n\nLemma aeval_sound:\n  forall m a n, aeval m a = n -> eval m a n.\nProof with (try congruence).\n  induction a; simpl; intros.\n  inv H. constructor.\n  constructor; auto.\n  destruct (aeval m a1) as []_eqn... destruct (aeval m a2) as []_eqn... inv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\n  destruct (aeval m a1) as []_eqn... destruct (aeval m a2) as []_eqn... inv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\ninv H; constructor; auto.\nQed.\n\nLemma beval_f_sound:\n  forall m be bv, beval m be = bv -> beval2 m be bv.\nProof with (try congruence).\n  induction be; simpl; intros.\n  inv H. constructor.\n  inv H. constructor.\nAdmitted.\n\n\n(** On peut iterer [interp] jusqu'a obtenir un etat final ou une erreur.\n  Cependant, toutes les fonctions Coq doivent terminer, et donc\n  nous devons borner a priori le nombre d'iterations. *)\n\nDefinition run_prog (prog: command) : option state := interp 100%nat prog initial_state.\n\n(** Quelques exemples d'execution de programmes. *)\n\nCompute (let prog := If (Le (Const 1) (Const 2)) (Assign vx (Const 3)) (Assign vx (Const 0)) in\n         match run_prog prog with\n         | Some s => Some (s vx)\n         | _ => None\n         end).\n\nCompute (let prog := Seq (Assign vx (Const 101)) (Seq (Assign vy (Const 7)) euclidean_division) in\n         match run_prog prog with\n         | Some s => (Some (s vq), Some (s vr))\n         | _ => (None, None)\n         end).\n\nCompute (let prog := Assign vx (Var vx) in\n         run_prog prog).\n\nCompute (let prog := While TRUE Skip in\n         run_prog prog).", "meta": {"author": "kalfazed", "repo": "Coq---Programming-Language", "sha": "829948eab329a9781b8681249e1f1343f226c5c6", "save_path": "github-repos/coq/kalfazed-Coq---Programming-Language", "path": "github-repos/coq/kalfazed-Coq---Programming-Language/Coq---Programming-Language-829948eab329a9781b8681249e1f1343f226c5c6/Asian-Pacific Summer School/solutions/solutions/solutions7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7637021586043958}}
{"text": "Definition tautology :  forall P : Prop, P -> P\n:=\nfun P x => x.\n\nDefinition Modus_tollens' : forall P Q : Prop, ~Q /\\ (P-> Q) -> ~P.\nProof.\nShow Proof.\nintros.\nShow Proof.\nintro.\nShow Proof.\napply H.\nShow Proof.\napply H.\nShow Proof.\napply H0.\nShow Proof.\nQed.\n\nDefinition Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P\n:=\nfun (P Q : Prop) (H1 : ~Q /\\ (P -> Q)) (H2 : P) =>\n((match H1 with | conj notq _ => notq end) ((match H1 with | conj _ ptoq => ptoq end) H2)).\n\nDefinition Disjunctive_syllogism' : forall P Q : Prop, (P \\/ Q) -> ~P -> Q.\nProof.\nintros.\ncase H.\nintros.\nexfalso.\napply H0.\napply H1.\nintros.\napply H1.\nQed.\n\nPrint Disjunctive_syllogism'.\n\nDefinition Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q\n:=\nfun (P Q : Prop) (PorQ : P \\/ Q) (notP : ~P) =>\nmatch PorQ with\n| or_introl P => False_ind Q (notP P)\n| or_intror Q => Q\nend.\n\nDefinition tautology_on_Set' : forall A : Set, A -> A.\nProof.\nintros.\napply H.\nQed.\n\nDefinition tautology_on_Set : forall A : Set, A -> A\n:=\nfun (A : Set) (A : A)\n=> A.\n\nDefinition Modus_tollens_on_Set' : forall A B : Set, (B -> Empty_set) * (A -> B) -> (A -> Empty_set).\nProof.\nintros.\napply H.\napply H.\napply H0.\nQed.\n\nPrint Modus_tollens_on_Set'.\n\nDefinition Modus_tollens_on_Set : forall A B : Set, (B -> Empty_set) * (A -> B)-> (A -> Empty_set)\n:=\nfun (A B : Set) (BtoEMPTYprodAtoB : (B -> Empty_set)*(A->B)) (A : A)\n=>\n((let (BtoEMPTY, _) := BtoEMPTYprodAtoB in BtoEMPTY) ((let (_, AtoB) := BtoEMPTYprodAtoB in AtoB) A)).\n\nDefinition Disjunctive_syllogism_on_Set' : forall A B : Set, (A + B) -> (A -> Empty_set) -> B.\nProof.\nintros.\ncase H.\nintros.\ncontradiction.\nintros.\napply b.\nQed.\n\nPrint Disjunctive_syllogism_on_Set'.\n\nDefinition Disjunctive_syllogism_on_Set : forall A B : Set, (A + B) -> (A -> Empty_set) -> B\n:=\nfun (A B : Set) (AplusB : A + B) (AtoEMPTY : A -> Empty_set) =>\nmatch AplusB with\n| inl A => Empty_set_rec (fun _ : Empty_set => B) (AtoEMPTY A)\n| inr B => B\nend.\n", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/4/16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7636999010461725}}
{"text": "Require Import primRec cPair extEqualNat.\n\n(** The famous Fibonacci function *)\n\n(* begin snippet fibDef *)\n\nFixpoint fib (n:nat) : nat :=\n  match n with\n  | 0 => 1\n  | 1 => 1\n  | S ((S p) as q) => fib q + fib p\n  end.\n\n(* end snippet fibDef *)\n\nSection Proof_of_FibIsPR.\n\n  (** To do :  Some parts of this proof may be made more generic *)\n\n  (** let us consider another definition of fib, as an application of\n      [nat_rec]\n   *)\n\n\n  Let fib_step (p: nat * nat) := (fst p + snd p, fst p).\n\n  Let fib_iter n p:= (nat_rec (fun _ => (nat*nat)%type)\n                              p\n                              (fun _ p => fib_step p)\n                              n).\n  Definition fib_alt n := snd (fib_iter n (1,1)).\n\n  Compute fib_alt 10.\n\n  (** The theory of primitive functions deals only with functions\n    of type [naryFunc n].\n\n   So, let us define a variant of [fib_alt] \n\n   *)\n\n\n  Let fib_step_cPair p := cPair (cPairPi1 p + cPairPi2 p)\n                                (cPairPi1 p).\n\n  Let fib_iter_cPair n p := nat_rec (fun _ => nat)\n                                    p\n                                    (fun _ p => fib_step_cPair p)\n                                    n.\n\n  Definition fibPR n := cPairPi2 (fib_iter_cPair n (cPair 1 1)).\n\n\n  (** Let us prove that [fibPR] is PR *)\n\n  Lemma fibPRIsPR: isPR 1 fibPR.\n    unfold fibPR; apply compose1_1IsPR.\n    - apply indIsPR.\n      unfold fib_step_cPair; apply filter01IsPR.\n      apply compose1_2IsPR.\n      + apply compose1_1IsPR.\n        * apply idIsPR.\n        * apply compose1_2IsPR.\n          --  apply cPairPi1IsPR.\n          -- apply cPairPi2IsPR.\n          -- apply plusIsPR.\n      + apply cPairPi1IsPR.\n      + apply cPairIsPR.\n    - apply cPairPi2IsPR.\n  Qed.\n\n  (** Ok, but we must prove that [fibPR] is extensionaly equal to [fib] *)\n\n  (** let us consider the following relation *)\n\n  Definition inv (p: nat*nat) (c: nat) :=  c = cPair (fst p) (snd p).\n\n  Lemma inv_Pi : forall p c, inv p c ->  snd p = cPairPi2 c.\n  Proof. \n    intros;  unfold inv in H;  subst; now rewrite cPairProjections2.\n  Qed.\n\n  Lemma L0: inv (1,1) (cPair 1 1).\n  Proof. reflexivity. Qed.\n\n  Lemma LS : forall p c,  inv p c -> inv (fib_step p) (fib_step_cPair c).\n  Proof.\n    destruct p as (a,b); intros.\n    unfold inv in *. simpl fst  in *. simpl snd in *.\n    unfold fib_step_cPair.\n    subst;  now rewrite cPairProjections1, cPairProjections2.\n  Qed.\n\n  Lemma L1 : forall  p c,\n      inv p c -> forall n,\n        inv (fib_iter n p)\n            (fib_iter_cPair n c).\n  Proof.\n    induction n.      \n    - cbn; assumption.\n    - cbn; now  apply LS. \n  Qed.\n\n  Lemma L2 : extEqual 1 fib_alt fibPR.\n  Proof.\n    intro n; unfold fib_alt, fibPR. \n    rewrite (inv_Pi _ _ (L1 _ _ L0 n ));  reflexivity.\n  Qed.\n\n  Lemma fib_altIsPR : isPR 1 fib_alt.\n  Proof.    \n    destruct fibPRIsPR  as [x Hx]; exists x.\n    apply extEqualTrans with fibPR; auto.\n    apply extEqualSym, L2.\n  Qed.\n\n\n  (** It remains to prove that fib_alt is equivalent to the \"classical\" fib *)\n  \n  Lemma fib_OK0 : forall n,\n      fib_iter n (1,1) = (fib (S n), fib n).\n  Proof.\n    induction n; simpl; auto.\n    destruct n.\n    -  cbn;  reflexivity.\n    - rewrite IHn; unfold fib_step.\n        simpl fst; simpl snd; auto.\n  Qed.\n\n  Lemma fib_alt_Ok : extEqual 1 fib fib_alt.\n  Proof.\n    intro n;  change (fib n) with (snd (fib (S n), fib n)).\n    rewrite <- fib_OK0; reflexivity. \n  Qed.\n\n\n  Theorem fibIsPR : isPR 1 fib.\n  Proof.\n    destruct fib_altIsPR as [x Hx].\n    exists x;  apply extEqualTrans with fib_alt; auto.\n    apply extEqualSym, fib_alt_Ok.\n  Qed.\n\nEnd Proof_of_FibIsPR.\n\n\n\nCompute fibPR 1.\n\nCompute fibPR 2.\n\n\n(** Too long !\n\nTime Compute fibPR 3.\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/FibonacciPR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7636998980171537}}
{"text": "Inductive list (X: Type): Type :=\n| nil: list X\n| cons: X -> list X -> list X.\n\nCheck nil.\nCheck cons.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\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.\nExample test_length2:\n  length bool (cons bool true (nil bool)) = 1.\nProof. 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 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: rev nat (cons nat 1 (cons nat 2 (nil nat)))\n                   = (cons nat 2 (cons nat 1 (nil nat))).\nProof. reflexivity. Qed.\nExample test_rev2:\n  rev bool (nil bool) = nil bool.\nProof. reflexivity. Qed.\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\nCheck app'.\nCheck app.\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\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\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nCheck (length list123'').\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\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\nFixpoint repeat (X: Type) (n: X) (count: nat): list X :=\n  match count with\n    | O        => nil\n    | S count' => cons n (repeat X n count')\n  end.\n\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. 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 X v s.\n  induction s.\n  + reflexivity.\n  + simpl. rewrite IHs. 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 X l1 l2 v.\n  induction l1.\n  + simpl. reflexivity.\n  + simpl. rewrite IHl1. reflexivity.\nQed.\n\nInductive prod (X Y: Type): Type :=\n  pair: X -> Y -> prod X Y.\nImplicit Arguments 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 (x, y) => x end.\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): 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.\nEval simpl in (combine [1,2] [false,false,true,true]).\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\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' => match m with\n                | O => false\n                | S m' => ble_nat n' m'\n              end\n  end.\n\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 0 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    | a::_ => Some a\n  end.\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\nDefinition doit3times {X: Type} (f:X->X) (n:X): X :=\n  f (f (f n)).\n\nCheck @doit3times.\n\nDefinition minustwo (n: nat): nat := pred (pred n).\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nCheck plus.\nDefinition plus3 := plus 3.\nCheck plus3.\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).\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 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\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)\n                else filter test t\n  end.\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n    | O => true\n    | S O => false\n    | S (S n') => evenb n'\n  end.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\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': 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\nDefinition partition  {X: Type} (f: X -> bool) (l: list X): list X * list X :=\n  (filter f l, filter (fun x => negb (f 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\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 (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.\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_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.\n  + reflexivity.\n  + Lemma snoc_map: forall (X Y: Type) (f: X -> Y) (l: list X) (x: X),\n                      map f (snoc l x) = snoc (map f l) (f x).\n    Proof.\n      intros X Y f l x.\n      induction l.\n      + reflexivity.\n      + simpl. rewrite IHl. reflexivity.\n    Qed.\n    simpl.\n    rewrite snoc_map.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nFixpoint flat_map {X Y: Type} (f:X -> list Y) (l:list X): (list Y) :=\n  match l with\n    | nil   => nil\n    | a::l' => (f a) ++ (flat_map f l')\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n,n,n]) [1,5,4] = [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\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\nDefinition constfun {X: Type} (x: X): nat -> X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\nExample constfun_example1: ftrue 0 = true.\nProof. reflexivity. Qed.\nExample constfun_example: (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.\nExample override_example2: fmostlytrue 1 = 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_examle_bad: forall m n,\n                             3 + n = m -> plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  unfold plus3.\n  rewrite H.\n  reflexivity.\nQed.\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  Lemma beq_nat_refl: forall (n: nat), beq_nat n n = true.\n  Proof. intros n. induction n.\n         + reflexivity.\n         + simpl. apply IHn.\n  Qed.\n  simpl.\n  rewrite beq_nat_refl.\n  reflexivity.\nQed.\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 X x1 x2 k1 k2 f.\n  intros H.\n  unfold override.\n  intros I.\n  rewrite I.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem eq_add_S: forall (n m : nat),\n                    S n = S m -> n = m.\nProof.\n  intros n m eq.\n  inversion eq.\n  reflexivity.\nQed.\n\nTheorem silly4: forall (n m: nat),\n                  [n] = [m] -> n = m.\nProof. intros n m eq. inversion eq. reflexivity. Qed.\n\nTheorem silly5: forall (n m o: nat),\n                  [n, m] = [o, o] ->\n                  [n] = [m].\nProof.\n  intros n m o eq.\n  inversion eq.\n  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 X x y z l j.\n  intros eq1.\n  intros eq2.\n  inversion eq2.\n  reflexivity.\nQed.\n\nTheorem silly6: forall(n: nat),\n                  S n = 0 ->\n                  2 + 2 = 0.\nProof.\n  intros n  contra. inversion contra. Qed.\n\n\nLemma eq_remove_S: forall n m,\n                     n = m -> S n = S m.\nProof.\n  intros n m.\n  intros eq.\n  inversion eq.\n  reflexivity.\nQed.\n\nTheorem beq_nat_eq: forall n m,\n                      true = beq_nat n m -> n = m.\nProof.\n  intros n.\n  induction n as [| n'].\n  + intros m. destruct m as [| m'].\n  - reflexivity.\n  - simpl. intros contra. inversion contra.\n    + intros m. destruct m as [| m'].\n  - simpl. intros contra. inversion contra.\n  - simpl. intros H. apply eq_remove_S. apply IHn'. apply H.\nQed.\n\nTheorem beq_nat_eq': forall n m,\n                       beq_nat n m = true -> n = m.\nProof.\n  intros m. induction m.\n  + intros n.\n    induction n. simpl. reflexivity.\n    simpl. intros contra. inversion contra.\n  + intros n. \n    destruct n. simpl. intros contra. inversion contra.\n    simpl. intros H. apply eq_remove_S. apply IHm. apply H.\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.\n  + intros n eq. rewrite <- eq. reflexivity.\n  + intros n eq. simpl. destruct n.\n  - inversion eq.\n  - apply eq_remove_S. apply IHl. inversion eq. reflexivity.\nQed.\n\nTheorem beq_nat_0_l: forall n,\n                       true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n H. induction n.\n  + reflexivity.\n  + inversion H.\nQed.\n\nTheorem beq_nat_0_r: forall n,\n                       true = beq_nat n 0 -> 0 = n.\nProof.\n  intros n H. induction n.\n  + reflexivity.\n  + inversion H.\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\nTheorem silly3': forall (n: nat),\n                   (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n                   true = beq_nat n 5 -> true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H. apply H.\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 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  + reflexivity.\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 eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.\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\nTheorem fold_length_correct: forall X (l: list X),\n                               fold_length l = length l.\nProof.\n  intros X l.\n  induction l.\n  + simpl. unfold fold_length. simpl. reflexivity.\n  + simpl. unfold fold_length. simpl. unfold fold_length in IHl.\n    apply eq_remove_S. apply IHl.\nQed.\n\n\nTheorem plus_n_n_injective: forall n m,\n                              n + n = m + m -> n = m.\nProof.\n  intros n. induction n.\n  + simpl. intros m. induction m.\n  -reflexivity.\n  - intros H. inversion H.\n    + intros m. induction m.\n  -  intros H. simpl in H. inversion H.\n  - intros H.\n    apply eq_remove_S. apply IHn.\n    simpl in H. apply eq_add_S in H.\n    \n\n    Lemma plus_succ: forall (n m: nat),\n                       n + S m = S (n + m).\n    Proof.\n      intros n. induction n.\n      + intros m. simpl.  reflexivity.\n      + intros m. simpl.\n        apply eq_remove_S.\n        apply IHn.\n    Qed.\n    Lemma plus_succ2: forall (n m: nat),\n                        n + S n = m + S m -> n + n = m + m.\n    Proof.\n      intros n. induction n.\n      + intros m H. simpl.\n        simpl in H.\n        rewrite plus_succ in H.\n        apply eq_add_S.\n        apply H.\n      + intros m H.\n        rewrite plus_succ in H.\n        rewrite plus_succ in H.\n        rewrite plus_succ in H.\n        apply eq_add_S in H.\n        simpl.\n        rewrite plus_succ.\n        apply H.\n    Qed.\n    simpl.\n    rewrite plus_succ in H.\n    rewrite plus_succ in H.\n    apply eq_add_S in H.\n    apply H.\nQed.\n\nTheorem plus_n_n_injective_take2: forall n m,\n                                    n + n = m + m ->\n                                    n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m.\n  + intros n H. induction n.\n  - reflexivity.\n  - simpl in H. simpl in IHn. inversion H.\n    + intros n H. induction n.\n  - inversion H.\n  - simpl in H.\n    apply eq_add_S in H.\n    rewrite plus_succ in H.\n    rewrite plus_succ in H.\n    apply eq_add_S in H.\n    apply IHm in H.\n    rewrite H. reflexivity.\nQed.\n\nTheorem index_afetr_last: forall (n: nat) (X: Type) (l: list X),\n                            length l = n -> index (S n) l = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  generalize dependent X.\n  induction l.\n  +  reflexivity.\n  +  intros n H. \n     simpl. destruct l.\n     - unfold length in H. rewrite <- H.\n     unfold index.\n     reflexivity.\n     - destruct n.\n       inversion H.\n       apply IHl.\n       inversion H.\n       induction l.\n       simpl. reflexivity.\n       simpl. reflexivity.\nQed.\n\nTheorem length_snoc_''': 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  generalize dependent v.\n  induction l.\n  + intros v n H.\n    simpl.\n    simpl in H.\n    rewrite H.\n    reflexivity.\n  + intros v n H.\n    simpl.\n    destruct n.\n  - inversion H.\n  - apply eq_remove_S.\n    apply IHl.\n    inversion H.\n    reflexivity.\nQed.\n\n\nTheorem app_length_cons: 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. induction l1.\n  + simpl. intros l2 x n H.\n    apply H.\n  + simpl. intros l2 x' n H.\n    destruct n.\n  - inversion H.\n  - apply eq_add_S in H.\n    apply IHl1 in H.\n    apply eq_remove_S.\n    apply H.\nQed.\n\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/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.76368255585738}}
{"text": "(** * Computing the next power of 2. *)\n\n(** Apparently there is a Nat.log2_up function that probably obviates\n    the need for most of the things in this file. *)\n\nFrom Coq Require Import\n  Nat\n  PeanoNat\n  Arith\n  Lia\n.\n\nDefinition is_power_of_2 (n : nat) : Prop := exists m, 2^m = n.\n\nDefinition is_power_of_2b (n : nat) := n =? 2 ^ log2 n.\n\nLemma is_power_of_2b_spec (n : nat)\n  : Bool.reflect (is_power_of_2 n) (is_power_of_2b n).\nProof.\n  destruct (is_power_of_2b n) eqn:H; constructor.\n  - unfold is_power_of_2b in H; apply Nat.eqb_eq in H.\n    exists (log2 n); auto.\n  - apply Nat.eqb_neq in H.\n    intro Contra; apply H.\n    destruct Contra as [m Contra].\n    subst; rewrite Nat.log2_pow2; lia.\nQed.\n\n(** The function *)\nDefinition next_pow_2 (n : nat) :=\n  if n =? 0 then 1 else if is_power_of_2b n then n else 2 ^ S (log2 n).\n\nLemma not_pow_2_le_lt (n m : nat) : ~ is_power_of_2 n -> n <= 2^m -> n < 2^m.\nProof.\n  intros H0 H1; unfold is_power_of_2 in H0.\n  assert (forall k, 2 ^ k <> n).\n  { intros k HC. apply H0. exists k; auto. }\n  specialize (H m);  lia.\nQed.\n\nLemma pow_2_lt_le (a b : nat) : 2^a < 2^b -> 2*2^a <= 2^b.\nProof.\n  intro H.\n  assert (H0: 2 * 2^a = 2 ^ (S a)). auto.\n  rewrite H0. clear H0.\n  assert (a < b).\n  { rewrite Nat.pow_lt_mono_r_iff; eauto. }\n  unfold lt in H0.\n  apply Nat.pow_le_mono_r; auto.\nQed.\n\nLemma pow_positive (n k : nat) :\n  0 < n ->\n  0 < pow n k.\nProof.\n  revert n; induction k; simpl; intros n Hlt; try lia.\n  specialize (IHk n Hlt); lia.\nQed.\n\n(** Specification and proof. *)\nLemma next_pow_2_spec (n : nat) :\n  is_power_of_2 (next_pow_2 n) /\\\n    n <= next_pow_2 n /\\\n    forall m, n <= 2^m -> next_pow_2 n <= 2^m.\nProof.\n  split.\n  - unfold next_pow_2. destruct n; simpl.\n    + exists 0; auto.\n    + destruct (is_power_of_2b_spec (S n)); auto.\n      rewrite Nat.add_0_r.\n      exists (S (log2 (S n))); simpl; auto.\n  - split.\n    + unfold next_pow_2.\n      destruct n; simpl; auto.\n      destruct (is_power_of_2b_spec (S n)); auto.\n      generalize (Nat.log2_spec (S n) (Nat.lt_0_succ n)). intros [_ H0].\n      simpl in H0; lia.\n    + intros m Hm; unfold next_pow_2.\n      destruct n; simpl.\n      * clear Hm; induction m; auto; simpl; lia.\n      * destruct (is_power_of_2b_spec (S n)); auto.\n        generalize (Nat.log2_spec (S n) (Nat.lt_0_succ n)). intros [H0 H1].\n        rewrite Nat.add_0_r.\n        apply not_pow_2_le_lt with (m:=m) in n0; auto.\n        assert (H2: 2 ^ log2 (S n) < 2^m). lia.\n        apply pow_2_lt_le in H2; lia.\nQed.\n\n(** Immediate corollaries / helpers. *)\n\nLemma is_power_of_2_next_pow_2 (n : nat) :\n  is_power_of_2 (next_pow_2 n).\nProof. apply next_pow_2_spec. Qed.\n\nLemma next_pow_2_ub (n : nat) :\n  n <= next_pow_2 n.\nProof. apply next_pow_2_spec. Qed.\n\nLemma next_pow_2_positive (n : nat) :\n  0 < next_pow_2 n.\nProof.\n  generalize (is_power_of_2_next_pow_2 n); intros [k H].\n  rewrite <- H.\n  apply pow_positive; lia.\nQed.\n", "meta": {"author": "bagnalla", "repo": "zar", "sha": "ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51", "save_path": "github-repos/coq/bagnalla-zar", "path": "github-repos/coq/bagnalla-zar/zar-ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51/pow_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7636659904840611}}
{"text": "Require Import Arith.\n\nFixpoint sum_odd(n:nat):nat :=\nmatch n with\n|O=>O\n|S m => 1 + m + m + sum_odd m\nend.\n\nGoal forall n, sum_odd n = n*n.\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> IHn.\nreplace (n+n*S n) with (n + n + n*n).\nreflexivity.\nrewrite <- plus_assoc.\napply NPeano.Nat.add_cancel_l.\nreplace (S n) with (n + 1).\nrewrite -> mult_plus_distr_l.\nrewrite -> mult_1_r.\napply (plus_comm n (n*n)).\napply (NPeano.Nat.add_1_r n).\nQed.\n", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/3/11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7636192547502543}}
{"text": "(* The subsequence relation is a partial order. *)\n\nRequire Import List.\nRequire Import Omega.\nImport ListNotations.\n\nSection subseq_sect.\n\n  Variable A: Type.\n\n  Inductive subseq: list A -> list A -> Prop :=\n  | subseq_nil: subseq [] []\n  | subseq_add: forall x ys zs, subseq ys zs -> subseq (x::ys) (x::zs)\n  | subseq_sub: forall x ys zs, subseq ys zs -> subseq ys (x::zs).\n\n  Hint Constructors subseq.\n\n  Lemma subseq_refl:\n    forall xs, subseq xs xs.\n  Proof.\n  Qed.\n\n  Lemma subseq_len:\n    forall xs ys, subseq xs ys -> length xs <= length ys.\n  Proof.\n  Qed.\n\n  Lemma subseq_trans:\n    forall ys zs, subseq ys zs -> forall xs, subseq xs ys -> subseq xs zs.\n  Proof.\n  Qed.\n\n  (* Hint: use subseq_len to dispose of nonsense cases. *)\n  Lemma subseq_antisym:\n    forall xs ys, subseq xs ys -> subseq ys xs -> xs = ys.\n  Proof.\n  Qed.\n\nEnd subseq_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/L11-subsequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489618, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7635638574810485}}
{"text": "(*\nCoq in a Hurry\nYves Bertot\n*)\n\nCheck True.\n\nCheck true.\n\nEval compute in\n  let f := fun x => (x * 3, x) in f 3.\n\nDefinition sum5 (a b c d e : nat) : nat := a+b+c+d+e.\n\nEval compute in sum5 1 2 3 4 5.\n\nCheck sum5.\nPrint sum5.\n\nDefinition example1 := fun x : nat => x*x+2*x+1.\n\nReset example1.\n\nDefinition example1 (x : nat) : nat := x*x+2*x+1.\n\nEval compute in example1 1.\n\nRequire Import Bool.\n\nEval compute in (if true then 4 else 5).\n\nRequire Import Arith.\n\nDefinition is_zero (n : nat) : bool :=\n  match n with\n  | O   => true\n  | S p => false\n  end.\n\nEval compute in (is_zero 1).\n\nFixpoint sum_n (n : nat) : nat :=\n  match n with\n  | O   => O\n  | S p => (S p) + sum_n p\n end.\n\nEval compute in sum_n 4.\n\nFixpoint sum_n2 (n s : nat) :=\n  match n with\n  | O   => s\n  | S p => sum_n2 p (p + s)\n  end.\n\nFixpoint evenb (n : nat) : bool :=\n  match n with\n  | O => true\n  | 1 => false\n  | S (S p) => evenb p\n  end.\n\nRequire Import List.\n\nCheck 1::2::3::nil.\n\nFixpoint n_numbers (n : nat) : list nat :=\n  match n with\n  | O   => nil\n  | S p => (n_numbers p) ++ (p::nil)\n end.\n\nEval compute in n_numbers 2.\n\nFixpoint n_numbers' (n : nat) : list nat :=\n  match n with\n  | O   => nil\n  | S p => map (fun x => x) ((n_numbers' p) ++ (p::nil))\n end.\n\nEval compute in n_numbers' 5.\n\nDefinition head_evb (l: list nat) : bool :=\n  match l with\n  | nil   => false\n  | a::tl => evenb a\n  end.\n\nFixpoint sum_list (l : list nat) :=\n  match l with\n  | nil   => O\n  | n::tl => n + (sum_list tl)\n  end.\n\nFixpoint insert (n : nat) (l : list nat) : list nat :=\n  match l with\n  | nil   => n :: nil\n  | a::tl => if leb n a then (n::l) else (a::insert n tl)\n  end.\n\nFixpoint sort (l : list nat) : list nat :=\n  match l with\n  | nil   => nil\n  | a::tl => insert a (sort tl)\n  end.\n\nEval compute in sort (5::4::3::2::1::nil).\n\nDefinition get_head (A : Type) (r : A) (l : list A) : A :=\n  match l with\n  | nil => r\n  | a::tl => a\n  end.\n\nDefinition get_tail (A : Type) (l : list A) : list A :=\n  match l with\n  | nil => nil\n  | a::tl => tl\n  end.\n\nFixpoint is_sorted (l : list nat) : bool :=\n  match l with\n  | nil      => true\n  | a::nil   => true\n  | a::tl => if leb a (get_head nat 0 tl) then (is_sorted tl) else false\n  end.\n\nEval compute in is_sorted (0::0::nil).\n\nFixpoint count_n (n : nat) (l : list nat) : nat :=\n  match l with\n  | nil   => O\n  | a::tl => if (beq_nat a n) then (S (count_n n tl)) else (count_n n tl)\n  end.\n\nEval compute in count_n 0 (0::0::nil).\n\nSearch True.\n\nSearchPattern (_ + _ <= _ + _).\n\nSearchAbout leb.\n\nLemma example2 : forall a b:Prop, a /\\ b -> b /\\ a.\nProof.\n  intros.\n  elim H; auto.\nQed.\n\nLemma example3 : forall A B, A \\/ B -> B \\/ A.\nProof.\n  intros.\n  elim H; auto.\nQed.\n\n\nLemma test1 : forall A B C:Prop, A/\\(B/\\C)->(A/\\B)/\\C.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  destruct H2 as [H2 H3].\n  auto.\nQed.\n\nLemma test2 : forall A B C D: Prop,(A->B)/\\(C->D)/\\A/\\C -> B/\\D.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  destruct H2 as [H2 H3].\n  destruct H3 as [H3 H4].\n  split; auto.\nQed.\n\nLemma test3 : forall A: Prop, ~(A/\\~A).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H as [H1 H2].\n  apply H2. apply H1.\nQed.\n\nLemma test4 : forall A B C: Prop, A\\/(B\\/C)->(A\\/B)\\/C.\nProof.\n  intros.\n  destruct H; auto.\n  destruct H; auto.\nQed.\n\nLemma test5 : forall A B: Prop, (A\\/B)/\\~A -> B.\nProof.\n  intros.\n  destruct H as [H1 H2].\n  destruct H1; auto.\n  contradiction.\nQed.\n\nLemma exercise_universal_quantification : 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.\n  destruct H.\n  left. apply H.\n  right. apply H.\nQed.\n\nLemma sum_n_p : forall n, 2 * sum_n n + n = n * n.\nProof.\n  induction n.\n  simpl. reflexivity.\n  simpl in IHn.\nAdmitted.\n\n", "meta": {"author": "baberrehman", "repo": "learning-coq", "sha": "fbd36d44f932b7bdbed7b94096b56ac9bd0704d9", "save_path": "github-repos/coq/baberrehman-learning-coq", "path": "github-repos/coq/baberrehman-learning-coq/learning-coq-fbd36d44f932b7bdbed7b94096b56ac9bd0704d9/coq/coq_hurry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.763497833559247}}
{"text": "\n\n\n\n(** * Lists: Working with Structured Data *)\n\n(* $Date: 2012-09-08 20:51:57 -0400 (Sat, 08 Sep 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(** Here are two simple function definitions for extracting the\n    first and second components of a pair.  (The definitions also\n    illustrate how to do pattern matching on two-argument\n    constructors.) *)\n\nDefinition fst (p : natprod) : nat := \n  match p with\n  | pair x y => x\n  end.\nDefinition snd (p : natprod) : nat := \n  match p with\n  | pair x y => y\n  end.\n\nEval simpl in (fst (pair 3 5)).\n\n(** Since pairs are used quite a bit, it is nice to be able to\n    write them with the standard mathematical notation [(x,y)] instead\n    of [pair x y].  We can tell Coq to allow this with a [Notation]\n    declaration. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** The new notation can be used both in expressions and in\n    pattern matches (indeed, we've seen it already in the previous\n    chapter -- this notation is provided as part of the standard\n    library): *)\n\nEval simpl in (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat := \n  match p with\n  | (x,y) => x\n  end.\nDefinition snd' (p : natprod) : nat := \n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod := \n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** Let's try and prove a few simple facts about pairs.  If we\n    state the lemmas in a particular (and slightly peculiar) way, we\n    can prove them with just reflexivity (and its built-in\n    simplification): *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** But reflexivity is not enough if we state the lemma in a more\n    natural way: *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAdmitted.\n\n(** We have to expose the structure of [p] so that [simpl] can\n    perform the pattern match in [fst] and [snd].  We can do this with\n    [destruct].\n\n    Notice that, unlike for [nat]s, [destruct] doesn't generate an\n    extra subgoal here.  That's because [natprod]s can only be\n    constructed in one way.  *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as (n,m).  simpl.  reflexivity.  Qed.\n\n(** Notice that Coq allows us to use the notation we introduced\n    for pairs in the \"[as]...\" pattern that tells it what variables to\n    bind. *)\n\n(** **** Exercise: 1 star (snd_fst_is_swap) *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as (n, m).\n  simpl. reflexivity. Qed.\n  (* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* FILL IN HERE *)\n  intros p. destruct p as (n, m).\n  simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n    describe the type of _lists_ of numbers like this: \"A list is\n    either the empty list or else a pair of a number and another\n    list.\" *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following two declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n    but in case you are interested, here is roughly what's going on.\n\n    The [right associativity] annotation tells Coq how to parenthesize\n    expressions involving several uses of [::] so that, for example,\n    the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\nNotation \"x + y\" := (plus x y)  \n                    (at level 50, left associativity).\n   The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (By the way, it's worth noting in passing that expressions like \"[1\n   + 2 :: [3]]\" can be a little confusing when you read them in a .v\n   file.  The inner brackets, around 3, indicate a list, but the outer\n   brackets are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.\n   These brackets don't appear in the generated HTML.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist := \n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat := \n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y) \n                     (right associativity, at level 60).\n\nExample test_app1:             [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4,5] = [4,5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity.  Qed.\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tail] returns everything but the first\n    element.  Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tail (l:natlist) : natlist :=\n  match l with\n  | nil => nil  \n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1,2,3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tail:            tail [1,2,3] = [2,3].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below.  *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  (* FILL IN HERE *)\n  match l with\n    | nil => nil\n    | h :: t => match h with\n                  | 0 => nonzeros t\n                  | n => [n] ++ nonzeros t\n                end\n  end.\nExample test_nonzeros:            nonzeros [0,1,0,2,3,0,0] = [1,2,3].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t => match oddb h with\n                  | true => [h] ++ oddmembers t\n                  | false => oddmembers t\n                end\n  end.\n\nExample test_oddmembers:            oddmembers [0,1,0,2,3,0,0] = [1,3].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  (* FILL IN HERE *)\n  match l with\n    | nil => O\n    | h :: t => match oddb h with\n                  | true => S (countoddmembers t)\n                  | false => countoddmembers t\n                end\n  end.\n\nExample test_countoddmembers1:    countoddmembers [1,0,3,1,4,5] = 4.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_countoddmembers2:    countoddmembers [0,2,4] = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_countoddmembers3:    countoddmembers nil = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  (* FILL IN HERE *)\n  match l1 with\n      | nil => l2\n      | h1 :: t1 => match l2 with\n                    |  nil => l1\n                    | h2 :: t2 => [h1, h2] ++ (alternate t1 t2)\n                    end\n  end.\nExample test_alternate1:        alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_alternate2:        alternate [1] [4,5,6] = [1,4,5,6].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_alternate3:        alternate [1,2,3] [4] = [1,4,2,3].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_alternate4:        alternate [] [20,30] = [20,30].\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n    multiple times instead of just once.  One reasonable\n    implementation of bags is to represent a bag of numbers as a\n    list. *)\n\nDefinition bag := natlist.  \n\n(** **** Exercise: 3 stars, 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  (* FILL IN HERE *)\n  match s with\n    | nil => O\n    | h :: t => match beq_nat h v with\n                  | false => count v t\n                  | true => S (count v t)\n                end\n  end.\n(* Why I cant replace *)\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1,2,3,1,4,1] = 3.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_count2:              count 6 [1,2,3,1,4,1] = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\n\n\n(** Multiset [sum] is similar to set [union]: [sum a b] contains\n    all the elements of [a] and of [b].  (Mathematicians usually\n    define [union] on multisets a little bit differently, which\n    is why we don't use that name for this operation.)\n    For [sum] we're giving you a header that does not give explicit\n    names to the arguments.  Moreover, it uses the keyword\n    [Definition] instead of [Fixpoint], so even if you had names for\n    the arguments, you wouldn't be able to process them recursively.\n    The point of stating the question this way is to encourage you to\n    think about whether [sum] can be implemented in another way --\n    perhaps by using functions that have already been defined.  *)\n\nDefinition sum : bag -> bag -> bag := \n  (* FILL IN HERE *)\n  app.\n\n\nExample test_sum1:              count 1 (sum [1,2,3] [1,4,1]) = 3.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := \n  (* FILL IN HERE *)\n  v :: s.\n\nExample test_add1:                count 1 (add 1 [1,4,1]) = 3.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_add2:                count 5 (add 1 [1,4,1]) = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n  (* FILL IN HERE *)\n  blt_nat O (count v s).\n\nExample test_member1:             member 1 [1,4,1] = true.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_member2:             member 2 [1,4,1] = false.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  (* When remove_one is applied to a bag without the number to remove,\n     it should return the same bag unchanged. *)\n  (* FILL IN HERE *)\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 (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_remove_one2:         count 5 (remove_one 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *) \nProof. reflexivity. Qed.\nExample test_remove_one3:         count 4 (remove_one 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *) \nProof. reflexivity. Qed.\nExample test_remove_one4: \n  count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\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\n  (* FILL IN HERE *) \n\nExample test_remove_all1:          count 5 (remove_all 5 [2,1,5,4,1]) = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_remove_all2:          count 5 (remove_all 5 [2,1,4,1]) = 0.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_remove_all3:          count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_remove_all4:          count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\n (* FILL IN HERE *) \nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  (* FILL IN HERE *)\n  match s1 with\n    | [] => 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 (* FILL IN HERE *)\nProof. reflexivity. Qed.\nExample test_subset2:              subset [1,2,2] [2,1,4,1] = false.\n (* FILL IN HERE *)\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(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification. For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity.  Qed.\n\n(** ... because the [[]] is substituted into the match position\n    in the definition of [app], allowing the match itself to be\n    simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tail l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\". \n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tail nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far!  It is\n    very important to work through the details of each one, using Coq\n    and thinking about what each step of the proof achieves.\n    Otherwise it is more or less guaranteed that the exercises will\n    make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n    perhaps a little less familiar than standard natural number\n    induction, but the basic idea is equally simple.  Each [Inductive]\n    declaration defines a set of data values that can be built up from\n    the declared constructors: a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to a number; a\n    list can be either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two things together establish the\n    truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist, \n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).   \nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n    static written document -- it is easy to see what's going on if\n    you are reading the proof in an interactive Coq session and you\n    can see the current goal and context at each point, but this state\n    is not visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case.  *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3], \n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n     (the induction hypothesis). We must show\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]]  \n     By the definition of [++], this follows from\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n     which is immediate from the induction hypothesis.  []\n\n  Here is an exercise to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist, \n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** For a slightly more involved example of an inductive proof\n    over lists, suppose we define a \"cons on the right\" function\n    [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n  match l with\n  | nil    => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\n(** ... and use it to define a list-reversing function [rev]\n    like this: *)\n\nFixpoint rev (l:natlist) : natlist := \n  match l with\n  | nil    => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nExample test_rev1:            rev [1,2,3] = [3,2,1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** Now let's prove some more list theorems using our newly\n    defined [snoc] and [rev].  For something a little more challenging\n    than the inductive proofs we've seen so far, let's prove that\n    reversing a list does not change its length.  Our first attempt at\n    this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    (* This is the tricky case.  Let's begin as usual by simplifying. *)\n    simpl. \n    (* Now we seem to be stuck: the goal is an equality involving\n       [snoc], but we don't have any equations in either the\n       immediate context or the global environment that have\n       anything to do with [snoc]! \n\n       We can make a little progress by using the IH to rewrite the \n       goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n    enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l. induction l as [| n' l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl. rewrite -> IHl'. reflexivity.  Qed. \n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> length_snoc. \n    rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems: \n\n    _Theorem_: For all numbers [n] and lists [l],\n       [length (snoc l n) = S (length l)].\n \n    _Proof_: By induction on [l].\n\n    - First, suppose [l = []].  We must show\n        length (snoc [] n) = S (length []),\n      which follows directly from the definitions of\n      [length] and [snoc].\n\n    - Next, suppose [l = n'::l'], with\n        length (snoc l' n) = S (length l').\n      We must show\n        length (snoc (n' :: l') n) = S (length (n' :: l')).\n      By the definitions of [length] and [snoc], this\n      follows from\n        S (length (snoc l' n)) = S (S (length l')),\n]] \n      which is immediate from the induction hypothesis. [] *)\n                        \n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n    \n    _Proof_: By induction on [l].  \n\n      - First, suppose [l = []].  We must show\n          length (rev []) = length [],\n        which follows directly from the definitions of [length] \n        and [rev].\n    \n      - Next, suppose [l = n::l'], with\n          length (rev l') = length l'.\n        We must show\n          length (rev (n :: l')) = length (n :: l').\n        By the definition of [rev], this follows from\n          length (snoc (rev l') n) = S (length l')\n        which, by the previous lemma, is the same as\n          S (length (rev l')) = S (length l').\n        This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n    and pedantic.  After the first few, we might find it easier to\n    follow proofs that give a little less detail overall (since we can\n    easily work them out in our own minds or on scratch paper if\n    necessary) and just highlight the non-obvious steps.  In this more\n    compressed style, the above proof might look more like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that\n       length (snoc l n) = S (length l)\n     for any [l].  This follows by a straightforward induction on [l].\n     The main property now follows by another straightforward\n     induction on [l], using the observation together with the\n     induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and on how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for\n    present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, using [rewrite], and later we will see other ways\n    of reusing previous theorems.  But in order to refer to a theorem,\n    we need to know its name, and remembering the names of all the\n    theorems we might ever want to use can become quite difficult!  It\n    is often hard even to remember what theorems have been proven,\n    much less what they are named.\n\n    Coq's [SearchAbout] command is quite helpful with this.  Typing\n    [SearchAbout foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following to\n    see a list of theorems that we have proved about [rev]: *)\n\nSearchAbout rev.\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n    throughout the rest of the course; it can save you a lot of time! *)\n    \n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n    with [C-c C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, recommended (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist, \n  l ++ [] = l.   \nProof.\n  (* FILL IN HERE *)\n  intro l. induction l as [|n l'].\n  Case \"l is [].\".\n  reflexivity.\n  Case \"l is cons n l.\".\n  simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem rev_snoc : forall l : natlist, forall v : nat,\n  rev (snoc l v) = v :: (rev l).\nProof.\n  intros l v. induction l as [| n l'].\n  Case \"l is [].\".\n  simpl. reflexivity.\n  Case \"l is n :: l'.\".\n  simpl. rewrite -> IHl'. simpl.  reflexivity.\nQed.  \n  \nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *)\n  intro l. induction l as [| n l'].\n  Case \"l is [].\".\n     simpl. reflexivity.\n  Case \"l is cons n l'.\".\n  simpl. rewrite -> rev_snoc.\n  rewrite -> IHl'. reflexivity.\nQed.\n\n(** There is a short solution to the next exercise.  If you find\n    yourself getting tangled up, step back and try to look for a\n    simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  (* FILL IN HERE *)\n  intros l1 l2 l3 l4. rewrite -> app_ass.\n  rewrite -> app_ass. reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  (* FILL IN HERE *)\n  intros l n. induction l as [| m l'].\n  Case \"l is [].\".\n  simpl. reflexivity.\n  Case \"l is l'++ [n].\".\n  simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  (* FILL IN HERE *)\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 is [].\".\n  simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 is n :: l1'.\".\n  simpl. rewrite -> snoc_append.\n  rewrite -> snoc_append.\n  rewrite -> IHl1'.\n  rewrite -> app_ass.\n  reflexivity.\nQed.\n  (** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* FILL IN HERE *)\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 is [].\".\n  simpl. reflexivity.\n  Case \"l1 is n l1'.\".\n  simpl. destruct n as [| n'].\n    SCase \"n is 0.\".\n    rewrite -> IHl1'. reflexivity.\n    SCase \"n is S n'.\".\n    simpl. rewrite <- IHl1'. 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\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bag_proofs) *)\n(** If you did the optional exercise about bags above, here are a\n    couple of little theorems to prove about your definitions. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  (* FILL IN HERE *)\n  intro s. simpl. reflexivity.\nQed.\n(** The following lemma about [ble_nat] might help you in the next proof. *)\n\nTheorem ble_n_Sn : forall n,\n  ble_nat n (S n) = true.\nProof.\n  intros n. induction n as [| n'].\n  Case \"0\".  \n    simpl.  reflexivity.\n  Case \"S n'\".\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  (* FILL IN HERE *)\n  admit.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)  \n(** Write down an interesting theorem about bags involving the\n    functions [count] and [sum], and prove it.*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (rev_injective) *)\n(** Prove that the [rev] function is injective, that is, *)\n\n\n\n(* There is a hard way and an easy way to solve this exercise.*)\nTheorem equal_after_rev : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n(* FILL IN HERE *)\nProof. intros l1 l2 H1.\n       assert (H2: rev l1 = rev l2 -> rev (rev l1) = rev (rev l2) ).\n       intro H'. Admitted.\n\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n    day-to-day programming: *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.  \n\n(** One use of [natoption] is as a way of returning \"error\n    codes\" from functions.  For example, suppose we want to write a\n    function that returns the [n]th element of some list.  If we give\n    it type [nat -> natlist -> nat], then we'll have to return some\n    number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with \n               | true => a \n               | false => index_bad (pred n) l' \n               end\n  end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n    natoption], then we can return [None] when the list is too short\n    and [Some a] when the list has enough members and [a] appears at\n    position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None \n  | a :: l' => match beq_nat n O with \n               | true => Some a\n               | false => index (pred n) l' \n               end\n  end.\n\nExample test_index1 :    index 0 [4,5,6,7]  = Some 4.\nProof. reflexivity.  Qed.\nExample test_index2 :    index 3 [4,5,6,7]  = Some 7.\nProof. reflexivity.  Qed.\nExample test_index3 :    index 10 [4,5,6,7] = None.\nProof. reflexivity.  Qed.\n\n(** This example is also an opportunity to introduce one more\n    small feature of Coq's programming language: conditional\n    expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None \n  | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually allows conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n   have to pass a default element for the [nil] case.  *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n  (* FILL IN HERE *)\n  match l with\n    | nil => None\n    | h :: t => Some h\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  (* FILL IN HERE *)\n  intros l default. induction l as [| n l'].\n  Case \"l is [].\". reflexivity.\n  Case \"l is cons.\". 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]. *)\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  (* FILL IN HERE *)\n  match l1, l2 with\n    | [], [] => true\n    | h1::t1, h2::t2 => if beq_nat h1 h2 then beq_natlist t1 t2 else false\n    | _, _ => false\n  end.\nExample test_beq_natlist1 :   (beq_natlist nil nil = true).\n (* FILL IN HERE *)\nProof. reflexivity. Qed.\n\n (* FILL IN HERE *) Admitted.\nExample test_beq_natlist3 :   beq_natlist [1,2,3] [1,2,4] = false.\n (* FILL IN HERE *) \nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* FILL IN HERE *)\n  intro l. induction l as [| n l'].\n  Case \"l is [].\". reflexivity.\n  Case \"l is cons.\". simpl. rewrite <- beq_nat_refl. apply IHl'.\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. *)\n\nTheorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n (* FILL IN HERE *)\n  intros d k v. simpl. rewrite <- beq_nat_refl. reflexivity.\nQed.  \n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n  (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n (* FILL IN HERE *)\n  intros d m n o H1.\n  simpl. rewrite -> H1. reflexivity.\nQed.  \n(** [] *)\n\nEnd Dictionary.\n\nEnd NatList.\n\n", "meta": {"author": "shotarok", "repo": "SoftwareFoundation", "sha": "3bd4780ccc7d9ae25227cf46341ccddd102f310d", "save_path": "github-repos/coq/shotarok-SoftwareFoundation", "path": "github-repos/coq/shotarok-SoftwareFoundation/SoftwareFoundation-3bd4780ccc7d9ae25227cf46341ccddd102f310d/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.9046505338155469, "lm_q1q2_score": 0.76343015856199}}
{"text": "Require Export Arith.EqNat. \n\nInductive natlist : Type :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition new_bob (a:bool)(b:bool):bool := if a then b else false.\n\nFixpoint beq_natlist (l : natlist) (m : natlist) : bool :=\nmatch l,m with\n|[] , [] => true\n| _ , [] => false\n|[] , _ => false\n|h :: t , h'::t' =>  new_bob (beq_nat h h') (beq_natlist t t')\nend.\n\nCheck new.\n\nEval compute in (beq_natlist [1;2;3] [4;5;6]).\nEval compute in (beq_natlist [1;1;1] [1;1;1]).\n\nExample test_beq_natlist1 : (beq_natlist [] [] = true).\nProof.\nsimpl. reflexivity.\nQed.\n \nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\nProof. \nsimpl. reflexivity.\nQed.\n\n\n\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/beq_natlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7633884656413762}}
{"text": "Require Import MeetSemiLattice.\nRequire Import MyNotations.\nRequire Import PreorderEquiv.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Lists.SetoidList.\nRequire Import EquivlistMap.\n\n(** * Definition of distributive lattices\n    They are meet semilattices\n    with joins. As our meet semilattices have smallest elements,\n    we don't need to reintroduce them here. *)\n\nSection DistrLattice_Def.\n\n  Class DistrLattice `{T:Type} (Tle:Le T) :=\n    MkDistrLattice\n      {\n        (* meet semilattice *)\n        dl_msl :> MeetSemiLattice Tle;\n        (* join *)\n        dl_join :> Join T;\n        join_l : forall x y, x ≤ x ⊔ y;\n        join_r : forall x y, y ≤ x ⊔ y;\n        join_univ : forall x y z, x ≤ z -> y ≤ z -> x ⊔ y ≤ z;\n        (* distributivity *)\n        bdistr_le : forall x y z, x ⊓ (y ⊔ z) ≤ (x ⊓ y) ⊔ (x ⊓ z);\n      }.\n\n  Context {T : Type}.\n  Context {Tle : Le T}.\n  Context {DL : DistrLattice Tle}.\n\n  Existing Instance DL.\n  Existing Instance Feq_equiv.\n\n  (** ** Properties of the join *)\n\n  Lemma join_le_l : forall x y z, x ≤ y -> x ⊔ z ≤ y ⊔ z.\n  Proof.\n    intros.\n    apply join_univ.\n    apply (le_trans _ y _ H).\n    apply join_l.\n    apply join_r.\n  Qed.\n\n  Lemma join_le_r : forall x y z, x ≤ y -> z ⊔ x ≤ z ⊔ y.\n  Proof.    \n    intros.\n    apply join_univ.\n    apply join_l.\n    apply (le_trans _ y _ H).\n    apply join_r.\n  Qed.\n\n  Lemma join_le : forall x y z w, x ≤ y -> z ≤ w -> x ⊔ z ≤ y ⊔ w.\n  Proof.\n    intros.\n    apply (le_trans _ (x ⊔ w) _).\n    apply (join_le_r _ _ _ H0).\n    apply (join_le_l _ _ _ H).\n  Qed.\n\n  Add Morphism join with signature (Feq ==> Feq ==> Feq) as join_morphism.\n  Proof.\n    firstorder.\n    apply (join_le _ _ _ _ H H0).\n    apply (join_le _ _ _ _ H2 H1).\n  Qed.\n\n  Lemma join_comm : forall x y, x ⊔ y = y ⊔ x.\n  Proof.\n    unfold Feq.\n    intros. split.\n    apply join_univ. apply join_r. apply join_l.\n    apply join_univ. apply join_r. apply join_l.\n  Qed.\n\n  Lemma join_assoc : forall x y z, x ⊔ (y ⊔ z) = (x ⊔ y) ⊔ z.\n  Proof.  \n    intros.\n    unfold Feq. split.\n\n    apply join_univ.\n    apply (le_trans _ (x ⊔ y) _).\n    apply join_l.\n    apply join_l.\n    apply join_le_l.\n    apply join_r.\n\n    apply join_univ.\n    apply join_le_r.\n    apply join_l.\n    apply (le_trans _ (y ⊔ z) _).\n    apply join_r.\n    apply join_r.\n  Qed.\n\n  Lemma join_idem : forall x, x ⊔ x = x.\n  Proof.\n    intros.\n    unfold Feq. split.\n    apply (join_univ x x x (le_refl x) (le_refl x)).\n    apply join_l.\n  Qed.\n\n  Lemma join_bot_l : forall x, ⊥ ⊔ x = x.\n  Proof.\n    intros. split.\n    apply join_univ. apply bot_le.\n    apply le_refl.\n    apply join_r.\n  Qed.\n\n  Lemma join_bot_r : forall x, x ⊔ ⊥ = x.\n  Proof.\n    intro. setoid_rewrite join_comm.\n    apply join_bot_l.\n  Qed.\n\n  Lemma join_top_l : forall x, ⊤ ⊔ x = ⊤.\n  Proof.\n    intro. split.\n    apply join_univ. apply le_refl.\n    apply top_le.\n    apply join_l.\n  Qed.\n\n  Lemma join_top_r : forall x, x ⊔ ⊤ = ⊤.\n  Proof.\n    intro. setoid_rewrite join_comm.\n    apply join_top_l.\n  Qed. \n\n  (** ** Equivalent definitions of the order *)\n  Lemma order_join : forall x y, x ≤ y <-> x ⊔ y = y.\n  Proof.\n    intros.\n    unfold iff. split.\n\n    intros. split.\n    apply (le_trans _ (y ⊔ y) _).\n    apply (join_le_l _ _ _ H).\n    setoid_rewrite (join_idem y).\n    apply le_refl.\n    apply join_r.\n\n    intros. setoid_rewrite <- H.\n    apply join_l.\n  Qed.\n\n  (** ** Distributivity *)\n  Lemma bdistr_eq : forall x y z, x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z).\n  Proof.\n    intros.\n    split.\n    - apply bdistr_le.\n    - apply join_univ ; apply meet_le_r.\n      apply join_l.\n      apply join_r.\n  Qed.\n\n  (** ** Finite joins *)\n  \n  Definition Vf l :=\n    fold_left (fun accu x => accu ⊔ x) l ⊥.\n\n  Lemma Vf_nil : Vf [] = ⊥.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma Vf_singleton : forall a, Vf [a] = a.\n  Proof.\n    intros. unfold Vf. simpl. rewrite join_bot_l.\n    reflexivity.\n  Qed.\n\n  Lemma cons_app : forall (a : T) (b : list T), a :: b ≡ [a] ++ b.\n  Proof.\n    intros. reflexivity.\n  Qed.\n\n  Lemma Vf_cons : forall a b, Vf (a :: b) = a ⊔ Vf b.\n  Proof.\n    intros.\n    unfold Vf. simpl.\n    set (F := fold_left (fun accu x => accu ⊔ x)).\n    assert (forall u v, F u v = v ⊔ F u ⊥).\n    induction u ; intros.\n    - simpl. rewrite join_bot_r. reflexivity.\n    - simpl. rewrite IHu.\n      assert (F u (⊥ ⊔ a0) = (⊥ ⊔ a0) ⊔ F u ⊥).\n      apply IHu.\n      rewrite H.\n      rewrite join_bot_l.\n      rewrite join_assoc.\n      reflexivity.\n    - assert (a ⊔ F b ⊥ = (⊥ ⊔ a) ⊔ F b ⊥).\n      rewrite join_bot_l. reflexivity.\n      rewrite H0.\n      apply H.\n  Qed.\n\n  Lemma Vf_meet : forall a b, a ⊓ Vf b = Vf (map (a ⊓) b).\n  Proof.\n    intro.\n    induction b ; simpl.\n    - rewrite Vf_nil.\n      meetsemilattice.\n    - rewrite Vf_cons.\n      rewrite bdistr_eq.\n      rewrite Vf_cons.\n      rewrite IHb.\n      reflexivity.\n   Qed.\n\n  Lemma Vf_app : forall a b, Vf (a ++ b) = Vf a ⊔ Vf b.\n  Proof.\n    induction a ; intros.\n    - unfold Vf. simpl.\n      rewrite join_bot_l.\n      reflexivity.\n    - simpl.\n      rewrite Vf_cons.\n      rewrite Vf_cons.\n      rewrite <- join_assoc.\n      rewrite IHa.\n      reflexivity.\n  Qed.\n\n  Instance in_contains : Contains T (list T) := (InA Feq).\n  \n  Lemma Vf_in_le : forall a U, a ∈ U -> a ≤ Vf U.\n  Proof.\n    intros.\n    induction H ; rewrite Vf_cons.\n    - rewrite H.\n      apply join_l.\n    - apply le_trans with (y0 := Vf l).\n      assumption.\n      apply join_r.\n  Qed.\n\n  Lemma Vf_univ : forall U y, (forall x, x ∈ U -> x ≤ y) -> Vf U ≤ y.\n  Proof.\n    intros.\n    induction U.\n    + rewrite Vf_nil.\n      apply bot_le.\n    + rewrite Vf_cons.\n      apply join_univ.\n      apply H.\n      apply InA_cons_hd.\n      reflexivity.\n      apply IHU.\n      intros.\n      apply H.\n      apply InA_cons_tl.\n      apply H0.\n  Qed.\n\n  Lemma Vf_incl : forall U V, inclA Feq U V -> Vf U ≤ Vf V.\n  Proof.\n    intros.\n    apply Vf_univ.\n    intros.\n    apply Vf_in_le.\n    apply H.\n    apply H0.\n  Qed.\n\n  Lemma Vf_proper : forall U V, equivlistA Feq U V -> Vf U = Vf V.\n  Proof.\n    intros.\n    split ; (\n      apply Vf_incl ;\n      unfold inclA ; intros ;\n      apply H ; assumption).\n  Qed.\n\n  \nEnd DistrLattice_Def.\n\nAdd Parametric Morphism (T : Type) (Tle : Le T) (Tdl : DistrLattice Tle) : (@dl_join T Tle Tdl) with signature (Feq ==> Feq ==> Feq) as f_join_morphism.\nProof.\n  apply join_morphism_Proper.\nQed.\n\nAdd Parametric Morphism (T : Type) (Tle : Le T) (Tdl : DistrLattice Tle) : (@Vf T Tle Tdl) with signature (equivlistA Feq ==> Feq) as Vf_morphism.\nProof.\n  apply Vf_proper.\nQed.\n\n\nAdd Parametric Morphism (T : Type) (R : Type) (Req : relation R) (Requiv : Equivalence Req) : (@map T R) with signature (pointwise_relation T Req  ==> equivlistA (≡) ==> equivlistA Req) as map_morphism.\nProof.\n  unfold equivlistA ; intros.\n  set (L := @inA_map_iff T (≡) _ R Req Requiv).\n  assert (forall f : T -> R, Proper ((≡) ==> Req) f).\n  unfold Proper, respectful. intros. subst. reflexivity.\n  unfold contains, in_containsR, in_containsQ in L.\n  rewrite L.\n  rewrite L.\n  split.\n  - intro.\n    destruct H2.\n    exists x2.\n    destruct H2.\n    split.\n    + rewrite <- H0.\n      apply H2.\n    + rewrite H3.\n      apply H.\n  - intro.\n    destruct H2.\n    exists x2.\n    destruct H2.\n    split.\n    + rewrite H0.\n      apply H2.\n    + rewrite H3.\n      symmetry.\n      apply H.\n  - apply H1.\n  - apply H1.\nQed.\n\n(** * Distributive lattice morphisms *)\n\nSection Frame_Morphism_Definition.\n  Context {tA : Type}.\n  Context {leA : Le tA}.\n  Existing Instance Feq_equiv.\n  \n  Context {tB : Type}.\n  Context {leB : Le tB}.\n\n  Require Import Coq.Program.Basics.\n\n  Variable (DLA : @DistrLattice tA leA).\n  Variable (DLB : @DistrLattice tB leB).\n\n  Definition mslA := @dl_msl tA leA DLA.\n  Definition mslB := @dl_msl tB leB DLB.\n\n  Variable (f : tA -> tB).\n  Class DLMorphism :=\n    MkDLMorphism\n      {\n        dlmorph_mslmorph :> MSLMorphism mslA mslB f;\n        (* preserves countable joins *)\n        morph_join: forall a b, f (a ⊔ b) = (f a) ⊔ (f b)\n      }.\n\n  Variable dlmorph : DLMorphism.\n  Existing Instance dlmorph.\n\n  Proposition morph_Vf : forall a, f (Vf a) = Vf (map f a).\n  Proof.\n    induction a.\n    - simpl.\n      rewrite Vf_nil.\n      rewrite Vf_nil.\n      apply mslmorph_bot.\n      apply dlmorph_mslmorph.\n    - simpl.\n      rewrite Vf_cons.\n      rewrite Vf_cons.\n      rewrite morph_join.\n      rewrite IHa.\n      reflexivity.\n  Qed.\n\nEnd Frame_Morphism_Definition.", "meta": {"author": "wetneb", "repo": "sigmalocales", "sha": "a42975000c9e505103e4321f7413af992fea5e0c", "save_path": "github-repos/coq/wetneb-sigmalocales", "path": "github-repos/coq/wetneb-sigmalocales/sigmalocales-a42975000c9e505103e4321f7413af992fea5e0c/DistrLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7633616840082519}}
{"text": "Require Import ssreflect ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nRequire Import bigop Omega fintype.\n\nDefinition f (n:nat) := (\\sum_(i<n.+1) i).\n\nLemma S10 : f(10)=55.\n\nTheorem sommation : forall (n : nat), 2 * sumn (iota 1 n) = n*(n.+1).\ninduction n; first trivial.\nreplace (n.+1) with (n+1) by ring.\nrewrite (iota_add ).\nrewrite sumn_cat.\nsimpl.\nring_simplify.\nrewrite IHn.\nring.\nQed.\n\nTheorem sommation_ssr n : 2 * sumn (iota 1 n) = n * (n + 1).\nProof.\n  elim: n => [//= | n IHn].\n  (* rewrite -{1 3}[n.+1]addn1. *)\n  rewrite -(addn1 n) iota_add sumn_cat.\n  ring_simplify.\n  rewrite IHn.\n  simpl.\n  ring.\nQed.\n\nTheorem sommation3 n : 2 * sumn (iota 1 n) = n * (n + 1).\nProof.\n  elim: n => [//= | n IHn].\n  (* rewrite -{1 3}[n.+1]addn1. *)\n  rewrite -(addn1 n).\n  rewrite \n iota_add /= sumn_cat !mulnDr IHn /= mulnC -!addnA.\n  congr (_ + _).\n  by rewrite muln0 !muln1 /= !add0n addn0 [RHS]addnA [RHS]addnC [n + 1]addnC.\nQed.\n\nTheorem sommation4 n : 2 * (\\sum_(i<n.+1) i) = n * (n + 1).\nelim : n => [|n IHn].\nrewrite big_ord_recr.\nrewrite big_ord0.\nreflexivity.\nreplace (\\sum_(i < n.+2) i) with ((\\sum_(i < n.+1) i) + n.+1).\nrewrite mulnDr.\nrewrite IHn.\nring.\nsymmetry.\napply big_ord_recr.\nQed.\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/test_somme.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7633616800805417}}
{"text": "Module Ex1. \nFixpoint factorial (n:nat) : nat :=\n    match n with \n    | 0 => 1\n    | S n => (n+1) * factorial (n)\n    end.\n\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\n\nEnd Ex1. ", "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/standard_factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109798251321, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7633451925265891}}
{"text": "(*|\n###################################\nEvery proof deserves its own \"view\"\n###################################\n\nIt is obvious that the validity of statement strongly depends on the\nnumber sets appearing in its formulation. That leads to an illusion\nthat the proof itself should rely on particular properties of these\nnumbers. For instance, the definition of natural numbers in Coq\nfollows `Peano's encoding\n<https://en.wikipedia.org/wiki/Peano_axioms>`__:\n|*)\n\nPrint nat. (* .unfold .messages *)\n\n(*|\nHere, a natural number is created either from the constant ``O`` or by\napplying the function ``S`` to another natural number. ``S`` is the\nsuccessor function which represents adding 1 to a number. Thus, ``O``\nis zero, ``S O`` is one, ``S (S O)`` is two, ``S (S (S O))`` is three,\nand so on.\n\nIn turn, this encoding of natural numbers brings us the ``nat_ind``\ninduction principle playing a vital role in proving properties of\nnatural numbers:\n|*)\n\nCheck nat_ind. (* .unfold .messages *)\n\n(*|\nThe induction principle, usually called `mathematical induction\n<https://en.wikipedia.org/wiki/Mathematical_induction>`__, reads the\nfollowing. Proposition :math:`P(n)` holds for every natural number\n:math:`n = 0, 1, 2, \\dots` if the following two statements are\nsatisfied:\n\n1. The **initial** or **base state**: the proposition holds for\n   :math:`n = 0`.\n2. The **induction step**: if the proposition holds for :math:`n`,\n   then it holds for :math:`n + 1`.\n\nBelow is our illustrating example the consideration of which we start\nfrom applying the induction principle (tactic ``induction``):\n|*)\n\nRequire Import PeanoNat.\n\nLemma triangle_num : forall n : nat, Nat.even (n * S n) = true.\nProof.\n  intro n. rewrite Nat.even_mul, Bool.orb_true_iff.\n  induction n; tauto.\nQed.\n\n(*|\nHere, despite the use of the induction principle, our major\nobservation relates to the fact that ``n`` or ``S n`` is even. The\nrole of the induction principle is to use this fact in order to\nconclude the evenness of ``S n`` or ``S (S n)``.\n|*)\n\nInductive parity n :=\n| parity_even : Nat.even n = true -> parity n\n| parity_even_S : Nat.even (S n) = true -> parity n.\n\nLemma parity_spec : forall n : nat, parity n.\nProof.\n  intro n. induction n as [| ? [? | ?]]; now constructor.\nQed.\n\nLemma triangle_num' : forall n : nat, Nat.even (n * S n) = true.\nProof.\n  intro n. rewrite Nat.even_mul, Bool.orb_true_iff.\n  destruct (parity_spec n); tauto.\nQed.\n\n(*| ---- |*)\n\nLemma mod_sym : forall a b : nat,\n    a <> 0 -> b <> 0 -> a mod b = b mod a <-> a = b.\nAbort. (* .none *)\n\n(*|\nAfter some failed tries, I recommend you to take a coffee break and,\nthen, make a try with pen and paper. It should stimulate you to turn\ninto a case analysis and find out three distinct cases: ``a < b``, ``a\n= b``, and ``a > b``. However, in comparison with mathematical\ninduction, reasoning about cases in Coq seems not so convenient. The\npoint is that every case is a proposition (``Prop``), not inductive\ntype; hence, our case analysis is non-constructive.\n\nThe good news is that Coq provides an appropriate inductive type for\ncase analysis:\n|*)\n\nPrint sumbool. (* .unfold .messages *)\n\n(*|\nIn turn, our case analysis is expressed by decidable equality:\n|*)\n\nRequire Import Compare_dec. (* .none *)\nCheck lt_eq_lt_dec. (* .unfold .messages *)\n\n(*|\nReturning to our example, one can now split the set of natural numbers\ninto the desired cases:\n|*)\n\nRequire Import Compare_dec.\n\nLemma mod_sym : forall a b : nat,\n    a <> 0 -> b <> 0 -> a mod b = b mod a <-> a = b.\nProof.\n  intros a b Ha Hb. pose proof (lt_eq_lt_dec a b) as H.\n  destruct H as [H | H]. 1: destruct H as [H | H].\n  Show 1. (* .unfold .messages *)\n  Show 2. (* .unfold .messages *)\n  Show 3. (* .unfold .messages *)\n\n(*|\nThe rest of proof is straightforward:\n|*)\n\n  all: split; auto.\n  - apply Nat.mod_small in H. intro H0. rewrite H in H0.\n    pose proof (Nat.mod_upper_bound b a Ha) as H1. rewrite <- H0 in H1.\n    contradict H1. apply Nat.lt_irrefl.\n  - apply Nat.mod_small in H. intro H0. rewrite H in H0.\n    pose proof (Nat.mod_upper_bound a b Hb) as H1. rewrite H0 in H1.\n    contradict H1. apply Nat.lt_irrefl.\nQed.\n\n(*|\nIn conclusion, we have emphasized the importance of inductive types to\nenumerate all elements of a set (for instance, natural numbers).\nHowever, we are not restricted to the standard encoding of the set and\nare able to introduce own principles for the enumeration. But we need\nalways keep in mind that such a procedure should be decidable. In\ncontrast, non-decidable procedures are propositions (``Prop``) and not\nthe subject for case analysis (due to the lack of `excluded-middle law\n<https://en.wikipedia.org/wiki/Law_of_excluded_middle>`__ in\nconstructive logic).\n\n----\n\nBelow are appropriate examples found on `Stack Overflow\n<https://stackoverflow.com/>`__:\n\n1. `<../examples/contradiction-on-natural-numbers-zero-test.html>`__\n2. `<../examples/coq-how-to-prove-if-statements-involving-strings.html>`__\n3. `<../examples/coq-how-to-prove-max-a-b-ab.html>`__\n4. `<../examples/coq-leb-does-not-give-me-an-hypothesis-after-case-or-induction.html>`__\n5. `<../examples/finding-a-well-founded-relation-to-prove-termination-of-a-function-that-stops-de.html>`__\n6. `<../examples/how-does-decidable-equality-works-with-list-remove.html>`__\n7. `<../examples/pattern-matching-with-even-and-odd-cases.html>`__\n8. `<../examples/prove-that-the-only-zero-length-vector-is-nil.html>`__\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/notes/inductive-type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7632721077442013}}
{"text": "(*\n    Exercise 1.\n*)\nInductive truth: Set :=\n    | Yes\n    | No\n    | Maybe.\n\nDefinition and (a b: truth): truth :=\n    match a, b with\n        | _, No => No\n        | No, _ => No\n        | _, Maybe => Maybe\n        | Maybe, _ => Maybe\n        | Yes, Yes => Yes\n    end.\n\nDefinition or (a b: truth): truth :=\n    match a, b with\n        | _, Yes => Yes\n        | Yes, _ => Yes\n        | Maybe, _ => Maybe\n        | _, Maybe => Maybe\n        | No, No => No\n    end.\n\nDefinition not (a: truth): truth :=\n    match a with\n        | Yes => No\n        | No => Yes\n        | Maybe => Maybe\n    end.\n\nTheorem and_commutative: forall a b: truth, and a b = and b a.\n    destruct a; destruct b; reflexivity.\nQed.\n\nTheorem and_distribute: forall a b c: truth, and a (or b c) = or (and a b) (and a c).\n    destruct a; destruct b; destruct c; reflexivity.\nQed.\n\n(*\n    Exercise 2.\n*)\nRequire Import List.\n\nSection slist.\n    Variable T: Set.\n\n    Inductive slist: Set :=\n        | empty: slist\n        | single: T -> slist\n        | concat: slist -> slist -> slist.\n\n    Fixpoint flatten (l: slist): list T :=\n        match l with\n            | empty => nil\n            | single a => cons a nil\n            | concat l1 l2 => flatten l1 ++ flatten l2\n        end.\n\n    Theorem flatten_distribute: forall l1 l2: slist,\n        (flatten (concat l1 l2)) = (flatten l1) ++ (flatten l2).\n        destruct l1; destruct l2; reflexivity.\n    Qed.\nEnd slist.\nImplicit Arguments empty [T].\n\n(*\n    Exercise 3.\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\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.", "meta": {"author": "awh44", "repo": "CoqExercises", "sha": "26899115fb86e36621e7954f2918d934ff3f8c64", "save_path": "github-repos/coq/awh44-CoqExercises", "path": "github-repos/coq/awh44-CoqExercises/CoqExercises-26899115fb86e36621e7954f2918d934ff3f8c64/src/inductive_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7632720939408684}}
{"text": "(*\n  10152160137 陈弈君 homeowork 4\n*)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> 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.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\n\n(* 1.Theorem app_nil_r : ∀ l : natlist,  l ++ [] = l. *)\nTheorem app_nil_r : forall l : natlist,  l ++ [] = l.\n\nProof.\n  intros l. induction l as[ |n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(* 2.Theorem rev_app_distr: ∀ l1 l2 : natlist,  rev (l1 ++ l2) = rev l2 ++ rev l1. *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n\nTheorem rev_app_distr: forall l1 l2 : natlist,  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\n\n(* 3.Theorem rev_involutive : ∀ l : natlist,  rev (rev l) = l. *)\nTheorem rev_involutive : forall l : natlist,  rev (rev l) = l.\n\nProof.\n  intros l. induction l as [|n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. simpl. rewrite IHl'. reflexivity.\nQed.", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/homework4_10152160137.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7632720876357895}}
{"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(** # This is the <a href=\"https://math-comp.github.io/htmldoc_2_0_alpha1/mathcomp.ssreflect.seq.html\">doc of seq</a>, use it! #*)\n\n(**\n\n----\nExercise 1: \n    - look up the documentation of [take] and [drop]\n    - prove this by induction (mind the recursive argument)\n*)\nLemma cat_take_drop T n (s : seq T) : take n s ++ drop n s = s.\nProof.\n(*D*)by elim: s n => [|x s IHs] [|n] //=; rewrite IHs.\n(*A*)Qed.\n\n(** Exercise 2:\n   - look at the definition of [take] and [size] and prove the following lemma\n   - the proof goes by cases (recall the spec lemma [leqP])\n*)\nLemma size_take T n (s : seq T) :\n  size (take n s) = if n < size s then n else size s.\nProof.\n(*D*)have [le_sn | lt_ns] := leqP (size s) n; first by rewrite take_oversize.\n(*D*)by rewrite size_takel // ltnW.\n(*A*)Qed.\n\n(** Exercise 3:\n    - another proof by cases \n    - remark that also [eqP] is a spec lemma\n*)\nLemma takel_cat T n (s1 s2 : seq T) :\n  n <= size s1 -> take n (s1 ++ s2) = take n s1.\nProof.\n(*D*)move=> Hn; rewrite take_cat ltn_neqAle Hn andbT.\n(*D*)by case: eqP => //= ->; rewrite subnn take0 cats0 take_size.\n(*A*)Qed.\n\n(** Exercise 4:\n    - Look up the definition of [rot]\n    - Look back in this file the lemma [cat_take_drop] \n    - can you rewrite with it right-to-left in the right-hand-side of the goal? \n*)\nLemma size_rot T n (s : seq T) : size (rot n s) = size s.\nProof.\n(*D*)by rewrite -[s in RHS](cat_take_drop n) /rot !size_cat addnC.\n(*A*)Qed.\n\n(** Exercise 5:\n    - which is the size of an empty sequence?\n    - Use lemmas about [size] and [filter] \n*)\nLemma has_filter (T : eqType) a (s : seq T)  : has a s = (filter a s != [::]).\nProof.\n(*D*)by rewrite -size_eq0 size_filter has_count lt0n.\n(*A*)Qed.\n\n(** Exercise 6:\n    - prove that by induction \n*)\nLemma filter_all T a (s : seq T) : all a (filter a s).\nProof. \n(*D*)by elim: s => //= x s IHs; case: ifP => //= ->. \n(*A*)Qed.\n\n(** Exercise 7:\n  - prove that view (one branch is by induction) \n*)\nLemma all_filterP T a (s : seq T) :\n  reflect (filter a s = s) (all a s).\nProof.\n(*D*)apply: (iffP idP) => [| <-]; last exact: filter_all.\n(*D*)by elim: s => //= x s IHs /andP[-> Hs]; rewrite IHs.\n(*A*)Qed.\n\n(** Exercise 9:\n    - prove this by induction on [s] \n*)\nLemma allP (T : eqType) (a : pred T) (s : seq T) :\n  reflect (forall x, x \\in s -> a x) (all a s).\nProof.\n(*D*)elim: s => [|x s IHs] /=; first by exact: ReflectT.\n(*D*)rewrite andbC; case: IHs => IHs /=.\n(*D*)  apply: (iffP idP) => [Hx y|].\n(*D*)    by rewrite inE => /orP[ /eqP-> // | /IHs ].\n(*D*)  by move=> /(_ x); apply; rewrite inE eqxx.\n(*D*)by apply: ReflectF=> H; apply: IHs => y Hy; apply H; rewrite inE orbC Hy.\n(*A*)Qed.\n\n(** *** Exercise 10:\n  - check out the definitions and theory of [leq] and [maxn]\n  - use only [rewrite] and [apply]\n  - proof sketch:\n<<\n   n <= m = n - m == 0\n          = m + n - m == m + 0\n          = maxn m n == m\n>> *)\nLemma maxn_idPl m n : reflect (maxn m n = m) (m >= n).\n(*D*)Proof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed.\n\n", "meta": {"author": "gares", "repo": "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/exercise4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8918110339361275, "lm_q1q2_score": 0.7632575093880187}}
{"text": "Inductive 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  | (_, y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x, y) => (y, x)\n  end.\n\nCompute fst (pair 3 5).\n\nTheorem snd_fst_is_swap :\n  forall (p : natprod), (snd p, fst p) = swap_pair p.\nProof.\nintros.\ndestruct p.\nsimpl.\nreflexivity.\nQed.\n\nTheorem fst_swap_is_snd :\n  forall (p : natprod), fst (swap_pair p) = snd p.\nProof.\nintros.\ndestruct p.\nsimpl.\nreflexivity.\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 nonzeros (l : natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | O :: l => nonzeros l\n  | x :: l => x :: nonzeros l\n  end.\n\nCompute nonzeros [0;1;0;2;0;3;0;4].\n\nFixpoint oddmembers' (l : natlist) : natlist :=\n  match l with\n  | nil          => nil\n  | x :: nil     => l\n  | x :: y :: l' => x :: oddmembers' l'\n  end.\n\nCompute oddmembers' [0;1;0;2;0;3;0;4].\n\nFixpoint odd (n : nat) : bool :=\n  match n with\n  | O       => false\n  | S O     => true\n  | S (S x) => odd x\n  end.\n\nFixpoint oddmembers (l : natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | x :: l => if odd x then x :: oddmembers l else oddmembers l\n  end.\n\nCompute oddmembers [0;1;0;2;0;3;0;4].\n\nFixpoint add (n m : nat) : nat :=\n  match n with\n  | O    => m\n  | S n' => add n' (S m)\n  end.\n\nFixpoint countmembers (l : natlist) : nat :=\n  match l with\n  | nil    => O\n  | x :: l => add x (countmembers l)\n  end.\n\nCompute countmembers [0;1;0;2;0;3;0;4].\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil     => nil\n  | _ :: l' => l'\n  end.\n\n(* TODO: how to do this? *)\nFail Fixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => nil\n  | x :: l1' =>\n    match l2 with\n    | _ :: l2' => x :: alternate l2' l1'\n    | nil      => nil\n    end\n  end.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | x :: l1' =>\n    match l2 with\n    | y :: l2' => x :: y :: alternate l1' l2'\n    | nil      => x :: alternate l1' l2\n    end\n  end.\n\nCompute alternate [1;2;3] [4;5;6].\n\nDefinition bag := natlist.\n\n(* TODO: how to do this? *)\nFail Fixpoint count (v : nat) (l : natlist) : nat :=\n  match l with\n  | nil     => O\n  | v :: l' => S (count v l')\n  | _ :: l' => count v l'\n  end.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | S n', O    => false\n  | O, S m'    => false\n  | O, O       => true\n  | S n', S m' => eqb n' m'\n  end.\n\nFixpoint count (v : nat) (l : natlist) : nat :=\n  match l with\n  | nil     => O\n  | x :: l' => if eqb x v then S (count v l') else count v l'\n  end.\n\nCompute count 1 [1;2;1].\n\nDefinition sum : bag -> bag -> bag := alternate.\n\nCompute sum [1; 2; 3] [1; 4; 1].\n\nDefinition add' (v : nat) (s : bag) := cons v s.\n\nDefinition member (v : nat) (s : bag) : bool :=\n  if count v s then false else true.\n\nCompute member 1 [1;2;3].\nCompute member 1 [0;2;3].\n\nFixpoint remove1 (v : nat) (s : bag) : bag :=\n  match s with\n  | x :: s' => if eqb x v then s' else x :: remove1 v s'\n  | nil     => nil\n  end.\n\nCompute remove1 1 [1;1;2].\n\nFixpoint remove_all (v : nat) (s : bag) : bag :=\n  match s with\n  | x :: s' => if eqb x v then remove_all v s' else x :: remove_all v s'\n  | nil     => nil\n  end.\n\nCompute remove_all 1 [1;1;2].\n\nLemma eqb_reflexivity :\n  forall (n : nat), eqb n n = true.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nTheorem bag_theorem :\n  forall (v : nat) (s : bag), count v (add' v s) = S (count v s).\nProof.\nintros.\nunfold add'.\nsimpl.\nrewrite eqb_reflexivity.\nreflexivity.\nQed.\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\nTheorem app_assoc :\n  forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\nintros l1 l2 l3.\ninduction l1 as [| n l1' IHl1'].\n- (* l1 = nil *)\n  reflexivity.\n- (* l1 = cons n l1' *)\n  simpl.\n  rewrite -> IHl1'.\n  reflexivity.\nQed.\n\nTheorem app_nil_r :\n  forall (l : natlist), l ++ [] = l.\nProof.\nintros.\ninduction l as [|n l' IHl'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite -> IHl'.\n  reflexivity.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nTheorem rev_app_distr :\n  forall (l1 l2 : natlist),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\nintros.\ninduction l1 as [|n l1' IHl'].\n- simpl.\n  rewrite app_nil_r.\n  reflexivity.\n- simpl.\n  rewrite IHl'.\n  rewrite app_assoc.\n  reflexivity.\nQed.\n\nTheorem rev_head :\n  forall (l : natlist) (n : nat),\n  rev (n :: l) = rev l ++ [n].\nProof.\nintros l.\ninduction l as [|x l' IHl'].\n- simpl.\n  reflexivity.\n- intros.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem rev_involutive :\n  forall (l : natlist), rev (rev l) = l.\nProof.\nintros.\ninduction l as [|n l' IHl'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite rev_app_distr.\n  rewrite IHl'.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem app_assoc4 :\n  forall (l1 l2 l3 l4 : natlist),\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\nintros.\nrewrite app_assoc.\nrewrite app_assoc.\nreflexivity.\nQed.\n\nLemma nonzeros_app :\n  forall (l1 l2 : natlist),\n  nonzeros (l1 ++ l2) = nonzeros l1 ++ nonzeros l2.\nProof.\nintros.\ninduction l1 as [|n l1' IHl'].\n- simpl.\n  reflexivity.\n- destruct n.\n  + simpl.\n    rewrite IHl'.\n    reflexivity.\n  + simpl.\n\n    rewrite IHl'.\n    reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil             => true\n  | x1 :: l1', x2 :: l2' => if eqb x1 x2 then eqblist l1' l2' else false\n  | _, _                 => false\n  end.\n\nTheorem eqb_refl :\n  forall (n : nat), eqb n n = true.\nProof.\ninduction n.\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem eqblist_refl :\n  forall (l : natlist),\n  eqblist l l = true.\nProof.\nintros.\ninduction l as [|n l' IHl'].\n- simpl.\n  reflexivity.\n- destruct n.\n  + simpl.\n    rewrite IHl'.\n    reflexivity.\n  + simpl.\n    rewrite eqb_refl.\n    rewrite IHl'.\n    reflexivity.\nQed.\n\nFixpoint leb (n m : nat) :=\n  match n, m with\n  | O, O => true\n  | S _, O => false\n  | O, S _ => true\n  | S n', S m' => leb n' m'\n  end.\n\nNotation \"x <=? y\" := (leb x y) (at level 60).\n\nTheorem count_member_nonzero :\n  forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\nintros.\nsimpl.\ndestruct (count 1 s); reflexivity.\nQed.\n\nTheorem leb_n_Sn :\n  forall n, n <=? S n = true.\nProof.\nintros.\ninduction n as [|n' IHn'].\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nTheorem remove_does_not_increase_count :\n  forall (s : bag), count 0 (remove1 0 s) <=? (count 0 s) = true.\nProof.\nintros.\ninduction s as [|n s' IHs'].\n- simpl.\n  reflexivity.\n- destruct n.\n  + simpl.\n    rewrite leb_n_Sn.\n    reflexivity.\n  + simpl.\n    rewrite IHs'.\n    reflexivity.\nQed.\n\nTheorem bag_count_sum :\n  forall (a b : bag) (n : nat), count n (sum a b) = count n a + count n b.\nProof.\nintros.\ninduction a as [|x a' IHa'].\nAdmitted. (* TODO *)\n\nLemma cons_is_app :\n  forall (l : natlist) (n : nat), n :: l = [n] ++ l.\nProof.\nintros.\ninduction l; simpl; reflexivity.\nQed.\n\nLemma cons_app_commute :\n  forall (l1 l2 : natlist) (n : nat), (n :: l1) ++ l2 = n :: (l1 ++ l2).\nProof.\nintros.\nrewrite -> cons_is_app.\nassert (n :: l1 ++ l2 = [n] ++ (l1 ++ l2)).\n- rewrite cons_is_app. reflexivity.\n- rewrite -> H.\n  rewrite app_assoc.\n  reflexivity.\nQed.\n\nLemma app1_not_empty :\n  forall (l : natlist) (n : nat), not (l ++ [n] = []).\nProof.\nintros.\ninduction l.\n- simpl.\n  discriminate.\n- rewrite cons_app_commute.\n  discriminate.\nQed.\n\nLemma rev_empty :\n  forall (a : natlist), rev a = [] -> a = [].\nProof.\nintro.\ndestruct a.\n- simpl.\n  intros.\n  reflexivity.\n- simpl.\n  intros.\n  exfalso.\n  apply app1_not_empty in H.\n  assumption.\nQed.\n\nTheorem rev_injective :\n  forall (a b : natlist), rev a = rev b -> a = b.\nProof.\nintros a.\ninduction a.\n- simpl.\n  symmetry.\n  symmetry in H.\n  apply rev_empty.\n  assumption.\n- destruct b.\n  + assert (rev [] = []).\n    * simpl. reflexivity.\n    * rewrite H.\n      apply rev_empty.\n  + (* rev (n :: a) = rev (n0 :: b) -> n :: a = n0 :: b *)\nAdmitted.\n\nTheorem rev_injective_simple :\n  forall (a b : natlist), rev a = rev b -> a = b.\nProof.\nintros.\nassert (rev (rev a) = rev (rev b)).\n- rewrite H.\n  reflexivity.\n- rewrite rev_involutive in H0.\n  rewrite rev_involutive in H0.\n  assumption.\nQed.\n\n(* New stuff: symmetry, exfalso, apply ... in ... VS rewrite *)\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\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  | x :: _ => Some x\n  end.\n\nDefinition hd (d : nat) (l : natlist) :=\n  match l with\n  | nil    => d\n  | x :: _ => x\n  end.\n\nTheorem optional_elimit_hd :\n  forall (l : natlist) (d : nat), hd d l = option_elim d (hd_error l).\nProof.\nintros.\ninduction l; simpl; reflexivity.\nQed.\n\n(* Remaining tasks too simple *)", "meta": {"author": "yugr", "repo": "Lalambda", "sha": "0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7", "save_path": "github-repos/coq/yugr-Lalambda", "path": "github-repos/coq/yugr-Lalambda/Lalambda-0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7/21/Coq/LF/03_Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8918110440002044, "lm_q1q2_score": 0.7632574983277802}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(* Arithmetic expressions and string expressions. *)\n\n(* Arithmetic expressions which evaluate to natural numbers *)\nInductive aexpr : Type :=\n  AE_Lit : forall (n : nat), aexpr\n| AE_Add : aexpr -> aexpr -> aexpr\n| AE_Mult : aexpr -> aexpr -> aexpr.\n\n(* Task 1: Write a function which evaluates an aexpr to a natural number. *)\nFixpoint eval_aexpr (ae : aexpr) : nat. Admitted.\n\n(* Expressions which evaluate to strings. *)\nInductive strexpr : Type :=\n  SE_Lit : forall (s : string), strexpr\n| SE_Append : strexpr -> strexpr -> strexpr\n| SE_Repeat : aexpr -> strexpr -> strexpr.\n\n(* Helper function: Repeat a string n times. *)\nFixpoint repeat_str (num : nat) (str : string) : string :=\n  match num with\n  | O => \"\"%string\n  | S n' => String.append str (repeat_str n' str)\n  end.\n\n(* Task 2: Write a function which evaluates a strexpr to a string. *)\nFixpoint eval_strexpr (se : strexpr) : string. Admitted.\n\n(* The Stack Machine *)\n\n(* We formalize a model of a simple stack machine. The stack itself is a list of strings and nats.\n   The following instructions for our stack machine are available:\n   - Push_nat : Push a nat on the stack.\n   - Push_string : Push a string on the stack.\n   - Add  : Pop two nats from the stack, add them and push the result on the stack.\n   - Mult : Pop two nats from the stack, multiply them and push the result on the stack.\n   - Append : Pop two strings from the stack, append them and push the result on the stack.\n   - Repeat : Pop a string and a nat from the stack, repeat the string n times and push\n              the result on the stack.\n\n  Note that the behaviour of the stack machine is undefined if the required operands of an\n  operation cannot be popped from the stack.\n *)\n\nInductive instruction : Type :=\n| Push_nat : forall (n : nat), instruction\n| Push_string : forall (s : string), instruction\n| Add : instruction\n| Mult : instruction\n| Append : instruction\n| Repeat : instruction.\n\nDefinition stack : Type := list (nat + string).\nDefinition program : Type := list instruction.\nDefinition state : Type := stack * program.\n\n(* Execute one instruction from the program *)\n(* Task 3: Fill in the missing cases *)\nInductive execute_step : state -> state -> Prop :=\n| exec_push_nat : forall (n : nat)(st : stack)(pr : program),\n    execute_step (st, Push_nat n :: pr) (inl n :: st, pr)\n| exec_add : forall (n m : nat) (st : stack) (pr : program),\n    execute_step (inl n :: inl m :: st, Add :: pr) (inl (n + m) :: st, pr).\n\nExample push_nat_example : execute_step ([], [Push_nat 3]) ([inl 3],[]).\nProof.\n  apply exec_push_nat.\nQed.\n\n(* Execute all the instructions from the program. This results with the state\n   of the stack at the end of execution. *)\nInductive execute : state -> stack -> Prop :=\n  execute_nop : forall (st : stack), execute (st, []) st\n| execute_cons : forall (s s' : state) (st : stack),\n    execute_step s s' ->\n    execute s' st ->\n    execute s st.\n\n(* Task 4: Give a proof of the following example. *)\nExample addition_example : execute ([], [Push_nat 2; Push_nat 4; Add]) [inl 6].\nProof.\n  admit.\nAdmitted.\n\n(* Compiling expressions into stack programs. *)\n\n(* We now have expressions for nats and strings, a stack machine, and want to relate them by\n   a compilation step. We want to be able to compile expressions into programs for our\n   stack machine. *)\n\n(* Task 5: Define the following two compilation functions. *)\nFixpoint compile_aexpr (ae : aexpr) : program. Admitted.\n\nFixpoint compile_strexpr (se : strexpr) : program. Admitted.\n\nDefinition example_prog : program :=\n  (compile_strexpr (SE_Repeat (AE_Add (AE_Lit 1) (AE_Lit 1)) (SE_Append (SE_Lit \"Hello \") (SE_Lit \"World \")))).\n\n\n(* Task 6: Define the tactic \"execute_tac\" which can solve the goal below.\n   You should use \"match goal\" for this. Alternatively, you can solve this goal by hand. *)\nLtac execute_tac := idtac.\n\nLemma example_prog_execute : execute ([], example_prog) [inr \"Hello World Hello World \"%string].\nProof.\n  unfold example_prog. simpl.\n  repeat execute_tac.\n  admit.\nAdmitted.\n\n", "meta": {"author": "ps-tuebingen-courses", "repo": "itp-2018-assignment-9", "sha": "9c9c0c7975c14ed3416951f48092e4ff3d3b5c0d", "save_path": "github-repos/coq/ps-tuebingen-courses-itp-2018-assignment-9", "path": "github-repos/coq/ps-tuebingen-courses-itp-2018-assignment-9/itp-2018-assignment-9-9c9c0c7975c14ed3416951f48092e4ff3d3b5c0d/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7632223226770656}}
{"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 wf_utils llist.\n\nSet Implicit Arguments.\n\n(* We provide an implementation of FIFO as a triple of lazy lists \n   satisfying the axioms in fifo_axm.v *)\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 prove the spec from page 587 with lazy lists (llist)\n      with invariant (l,r,l') : llength l' + llength r = llength l\n\n\n      let rec llist_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 (llist_rotate l' r' (lcons y a))\n\n      let fifo_3q_nil = (lnil,lnil,lnil)\n\n      let fifo_3q_make l r l' = match l' with\n        | lnil       -> let l' = llist_rotate l r lnil in (l',lnil,l')\n        | lcons _ l' -> (l, r, l')\n\n      let fifo_3q_enq (l,r,l') x = fifo_3q_make l (lcons x r) l'\n\n      let fifo_3q_deq (lcons x l,r,l') = (x,fifo_3q_make l r l')\n\n      let fifo_3q_void (l,r,n) = l = lnil\n\n    *)\n\n  Variable X : Type.\n\n  Implicit Types (l r : llist X).\n\n  Let Q_spec (c : llist X * llist X * llist X) :=\n    match c with (l,r,l') => exists Hl Hr Hl', lfin_length l' Hl' + lfin_length r Hr = lfin_length l Hl end.\n\n  Definition fifo := sig Q_spec.\n\n  Implicit Types (q : fifo) (x : X).\n\n  Definition fifo_list : fifo -> list X.\n  Proof.\n    intros (((l,r),l') & H).\n    refine (llist_list l _ ++ rev (llist_list r _));\n    destruct H as (? & ? & _); assumption.\n  Defined.\n\n  Let fifo_nil_val : fifo.\n  Proof.\n    refine (exist _ (lnil,lnil,lnil) _).\n    exists (lfin_lnil _), (lfin_lnil _), (lfin_lnil _); simpl.\n    rewrite lfin_length_fix_0; auto.\n  Defined.\n\n  Definition fifo_nil : { q | fifo_list q = nil }.\n  Proof. exists fifo_nil_val; trivial. Defined.\n\n  Definition fifo_make l r l' : (exists Hl Hr Hl', lfin_length l' Hl' + lfin_length r Hr = 1 + lfin_length l Hl) -> fifo.\n  Proof.\n    destruct l' as [ | x l'' ]; intros E.\n    + cut (lfin l); [ intros Hl1 | ].\n      cut (lfin r); [ intros Hr1 | ].\n      2-3 : cycle 1.\n      cut (lfin_length r Hr1 = 1 + lfin_length l Hl1); [ intros E1 | ].\n      2-4 : cycle 1.\n      refine (let l'' := @llist_rotate _ l r lnil Hl1 Hr1 (@lfin_lnil _) E1 \n              in exist _ (l'',lnil,l'') _).\n      all: cycle 1.\n      * destruct E as (? & ? & _); assumption.\n      * destruct E as (? & ? & _); assumption.\n      * destruct E as (Hl & Hr & Hl' & E).\n        rewrite lfin_length_fix_0 in E.\n        rewrite (lfin_length_eq _ Hr), (lfin_length_eq _ Hl); auto.\n      * exists (lfin_rotate _ _ (@lfin_lnil _) E1), \n             (@lfin_lnil _),\n             (lfin_rotate _ _ (@lfin_lnil _) E1).\n        unfold l''; rewrite llist_rotate_length; auto.\n    + refine (exist _ (l,r,l'') _).\n      destruct E as (Hl & Hr & Hl'' & E).\n      exists Hl, Hr, (lfin_inv Hl'').\n      rewrite lfin_length_fix_1 in E; omega.\n  Defined.\n\n  Hint Resolve llist_list_eq.\n\n  Fact fifo_make_spec l r l' Hl Hr H : llist_list l Hl ++ rev (llist_list r Hr) = fifo_list (@fifo_make l r l' H).\n  Proof.\n    destruct H as (Hl1 & Hr1 & Hl' & E).\n    unfold fifo_list, fifo_make; destruct l' as [ | x l' ].\n    + rewrite (llist_rotate_eq _ _ (@lfin_lnil _) _).\n      repeat rewrite llist_list_fix_0; simpl.\n      repeat rewrite <- app_nil_end; repeat (f_equal; auto).\n    + repeat (f_equal; auto).\n  Qed.\n\n  Let fifo_enq_val q x : fifo.\n  Proof.\n    destruct q as (((l,r),l') & H).\n    refine (@fifo_make l (lcons x r) l' _).\n    destruct H as (Hl & Hr & Hl' & E).\n    exists Hl, (lfin_lcons _ Hr), Hl'.\n    rewrite lfin_length_fix_1, (lfin_length_eq _ Hr); omega.\n  Defined.\n\n  Definition fifo_enq q x : { q' | fifo_list q' = fifo_list q ++ x :: nil }.\n  Proof.  \n    exists (fifo_enq_val q x).\n    revert q x.\n    unfold fifo_enq_val.\n    intros  (((l,r),l') & Hl & Hr & Hl' & E) x.\n    rewrite <- (@fifo_make_spec _ _ _ Hl (lfin_lcons _ Hr)).\n    unfold fifo_list. \n    rewrite llist_list_fix_1, app_ass; trivial.\n  Defined.\n\n  Let fifo_deq_val q : fifo_list q <> nil -> X * fifo.\n  Proof.\n    destruct q as (((l,r),l') & H); revert H.\n    refine (match l with \n      | lnil      => fun H1 H2 => _\n      | lcons x l => fun H1 H2 => (x,@fifo_make l r l' _)\n    end); [ exfalso | ]; destruct H1 as (Hl & Hr & Hl' & E).\n    + unfold fifo_list in H2.\n      destruct r.\n      * do 2 rewrite llist_list_fix_0 in H2; destruct H2; trivial.\n      * rewrite lfin_length_fix_1, lfin_length_fix_0 in E; omega.\n    + exists (lfin_inv Hl), Hr, Hl'.\n      rewrite E, lfin_length_fix_1; auto.\n  Defined.\n\n  Definition fifo_deq q : fifo_list q <> nil -> { c : X * fifo | let (x,q') := c in fifo_list q = x::fifo_list q' }.\n  Proof.\n    intros Hq.\n    exists (fifo_deq_val q Hq).\n    revert q Hq.  \n    unfold fifo_deq_val.\n    intros ((([ | x l],r),n) & Hl & Hr & Hl' & E) Hq.\n    + exfalso.\n      unfold fifo_list in Hq.\n      destruct r.\n      * do 2 rewrite llist_list_fix_0 in Hq; destruct Hq; trivial.\n      * rewrite lfin_length_fix_1, lfin_length_fix_0 in E; omega.\n    + rewrite <- (@fifo_make_spec _ _ _ (lfin_inv Hl) Hr).\n      unfold fifo_list.\n      rewrite llist_list_fix_1; auto.\n  Defined.\n\n  Let fifo_void_val : fifo -> bool.\n  Proof.\n    intros ((([ | x l],_),_) & _).\n    + exact true.\n    + exact false.\n  Defined.\n\n  Definition fifo_void q : { b : bool | b = true <-> fifo_list q = nil }.\n  Proof.\n    exists (fifo_void_val q).\n    revert q.\n    unfold fifo_list, fifo_void_val.\n    intros ((([ | x l],r),n) & Hl & Hr & Hl' & E).\n    + split; auto; intros _. \n      rewrite llist_list_fix_0.\n      destruct r.\n      * rewrite llist_list_fix_0; auto.\n      * rewrite lfin_length_fix_0, lfin_length_fix_1 in E; omega.\n    + split; try discriminate.\n      rewrite llist_list_fix_1; discriminate.\n  Defined.\n\nEnd fifo_three_lazy_lists.\n\nArguments fifo_nil {X}.\nArguments fifo_deq {X}.\n\n\n\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/fifo_3llists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7632223055358103}}
{"text": "Require Export P03.\n\nTheorem proj1 : forall P Q : Prop,\n    P /\\ Q -> P.\nProof.\n  intros P Q H. inversion H. apply H0.\nQed.\n\nTheorem proj2 : forall P Q : Prop,\n    P /\\ Q -> Q.\nProof.\n  intros P Q H. inversion H. apply H1.\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 H. inversion  H.\n    + split.\n      { left. apply H0. }\n      { left. apply H0. }\n    + split.\n      { apply proj1 in H0. right. apply H0. }\n      { apply proj2 in H0. right. apply H0. }\n  - (* <- *) intros H. inversion H.\n    + destruct H1.\n      { left. apply H1. }\n      { destruct H0.\n        { left. apply H0. }\n        { right. split.\n          { apply H0. }\n          { apply H1. } } }\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/05/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7631492126139748}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype.\n\nInductive nat: Set :=\n  | O: nat\n  | S: nat -> nat.\n\nFixpoint plus (n m: nat) :=\n  match n with\n  | O    => m\n  | S n' => S (plus n' m)\n  end.\n\nFixpoint mult (n m: nat) :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n\nTheorem plus0n: forall (n: nat),\n  plus O n = n.\nProof.\n  done.\nQed.\n\nTheorem plusn0: forall (n: nat),\n  plus n O = n.\nProof.\n  elim=> [ // | n' IH ] /=.\n    by rewrite IH.\nQed.\n\nTheorem plusSn: forall (n m: nat),\n  plus n (S m) = S (plus n m).\nProof.\n  elim=> [ // | n' IH m ] /=.\n    by rewrite IH.\nQed.\n\nTheorem plusC: forall (n m: nat),\n  plus n m = plus m n.\nProof.\n  elim=> [ m | n' IH m ] /=.\n    by rewrite plusn0.\n    by rewrite plusSn IH.\nQed.\n\nTheorem plusA: forall (n m o: nat),\n  plus n (plus m o) = plus (plus n m) o.\nProof.\n  elim=> [ // | n' IH m o ] /=.\n    by rewrite IH.\nQed.\n\n\nTheorem mult0n: forall (n: nat),\n  mult O n = O.\nProof.\n  done.\nQed.\n\nTheorem multn0: forall (n: nat),\n  mult n O = O.\nProof.\n  elim=> [ // | n' IH ] /=.\n    by rewrite IH.\nQed.\n\nTheorem mult1n: forall (n: nat),\n  mult (S O) n = n.\nProof.\n  by apply plusn0.\nQed.\n\nTheorem multn1: forall (n: nat),\n  mult n (S O) = n.\nProof.\n  elim=> [ // | n' IH ] /=.\n    by rewrite IH.\nQed.\n\nTheorem plusSwap: forall (n m o: nat),\n  plus n (plus m o) = plus m (plus n o).\nProof.\n  move=> n m o.\n  by rewrite plusA [X in plus X]plusC -plusA.\nQed.\n\nTheorem multSn: forall (n m: nat),\n  mult m (S n) = plus m (mult m n).\nProof.\n  move=> n m.\n  move: m.\n  elim=> [ // | m' IH ].\n    rewrite /=.\nQed.\n\nTheorem multC: forall (n m: nat),\n  mult n m = mult m n.\nProof.\n  induction n as [ | n' IH ].\n    (* n = 0 *)\n    intros m.\n    simpl.\n    rewrite -> multn0.\n    reflexivity.\n\n    (* n = S n' *)\n    intros m.\n    simpl.\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/examples/nat-ssr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7629972979111693}}
{"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 Export List.\nRequire Export Sorting.\nRequire Export Setoid Basics Morphisms.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(** * Logical relations over lists with respect to a setoid equality\n      or ordering. *)\n\n(** This can be seen as a complement of predicate [lelistA] and [sort]\n    found in [Sorting]. *)\n\nSection Type_with_equality.\nVariable A : Type.\nVariable eqA : A -> A -> Prop.\n\n(** Being in a list modulo an equality relation over type [A]. *)\n\nInductive InA (x : A) : list A -> Prop :=\n  | InA_cons_hd : forall y l, eqA x y -> InA x (y :: l)\n  | InA_cons_tl : forall y l, InA x l -> InA x (y :: l).\n\nHint Constructors InA.\n\n(** TODO: it would be nice to have a generic definition instead\n    of the previous one. Having [InA = Exists eqA] raises too\n    many compatibility issues. For now, we only state the equivalence: *)\n\nLemma InA_altdef : forall x l, InA x l <-> Exists (eqA x) l.\nProof. split; induction 1; auto. Qed.\n\nLemma InA_cons : forall x y l, InA x (y::l) <-> eqA x y \\/ InA x l.\nProof.\n intuition. invlist InA; auto.\nQed.\n\nLemma InA_nil : forall x, InA x nil <-> False.\nProof.\n intuition. invlist InA.\nQed.\n\n(** An alternative definition of [InA]. *)\n\nLemma InA_alt : forall x l, InA x l <-> exists y, eqA x y /\\ In y l.\nProof.\n intros; rewrite InA_altdef, Exists_exists; firstorder.\nQed.\n\n(** A list without redundancy modulo the equality over [A]. *)\n\nInductive NoDupA : list A -> Prop :=\n  | NoDupA_nil : NoDupA nil\n  | NoDupA_cons : forall x l, ~ InA x l -> NoDupA l -> NoDupA (x::l).\n\nHint Constructors NoDupA.\n\n(** An alternative definition of [NoDupA] based on [ForallOrdPairs] *)\n\nLemma NoDupA_altdef : forall l,\n NoDupA l <-> ForallOrdPairs (complement eqA) l.\nProof.\n split; induction 1; constructor; auto.\n rewrite Forall_forall. intros b Hb.\n intro Eq; elim H. rewrite InA_alt. exists b; auto.\n rewrite InA_alt; intros (a' & Haa' & Ha').\n rewrite Forall_forall in H. exact (H a' Ha' Haa').\nQed.\n\n\n(** lists with same elements modulo [eqA] *)\n\nDefinition inclA l l' := forall x, InA x l -> InA x l'.\nDefinition equivlistA l l' := forall x, InA x l <-> InA x l'.\n\nLemma incl_nil l : inclA nil l.\nProof. intro. intros. inversion H. Qed.\nHint Resolve incl_nil : list.\n\n(** lists with same elements modulo [eqA] at the same place *)\n\nInductive eqlistA : list A -> list A -> Prop :=\n  | eqlistA_nil : eqlistA nil nil\n  | eqlistA_cons : forall x x' l l',\n      eqA x x' -> eqlistA l l' -> eqlistA (x::l) (x'::l').\n\nHint Constructors eqlistA.\n\n(** We could also have written [eqlistA = Forall2 eqA]. *)\n\nLemma eqlistA_altdef : forall l l', eqlistA l l' <-> Forall2 eqA l l'.\nProof. split; induction 1; auto. Qed.\n\n(** Results concerning lists modulo [eqA] *)\n\nHypothesis eqA_equiv : Equivalence eqA.\n\nHint Resolve (@Equivalence_Reflexive _ _ eqA_equiv).\nHint Resolve (@Equivalence_Transitive _ _ eqA_equiv).\nHint Immediate (@Equivalence_Symmetric _ _ eqA_equiv).\n\nLtac inv := invlist InA; invlist sort; invlist lelistA; invlist NoDupA.\n\n(** First, the two notions [equivlistA] and [eqlistA] are indeed equivlances *)\n\nGlobal Instance equivlist_equiv : Equivalence equivlistA.\nProof.\n firstorder.\nQed.\n\nGlobal Instance eqlistA_equiv : Equivalence eqlistA.\nProof.\n constructor; red.\n induction x; auto.\n induction 1; auto.\n intros x y z H; revert z; induction H; auto.\n inversion 1; subst; auto. invlist eqlistA; eauto with *.\nQed.\n\n(** Moreover, [eqlistA] implies [equivlistA]. A reverse result\n    will be proved later for sorted list without duplicates. *)\n\nGlobal Instance eqlistA_equivlistA : subrelation eqlistA equivlistA.\nProof.\n  intros x x' H. induction H.\n  intuition.\n  red; intros.\n  rewrite 2 InA_cons.\n  rewrite (IHeqlistA x0), H; intuition.\nQed.\n\n(** InA is compatible with eqA (for its first arg) and with\n    equivlistA (and hence eqlistA) for its second arg *)\n\nGlobal Instance InA_compat : Proper (eqA==>equivlistA==>iff) InA.\nProof.\n intros x x' Hxx' l l' Hll'. rewrite (Hll' x).\n rewrite 2 InA_alt; firstorder.\nQed.\n\n(** For compatibility, an immediate consequence of [InA_compat] *)\n\nLemma InA_eqA : forall l x y, eqA x y -> InA x l -> InA y l.\nProof.\n intros l x y H H'. rewrite <- H; auto.\nQed.\nHint Immediate InA_eqA.\n\nLemma In_InA : forall l x, In x l -> InA x l.\nProof.\n simple induction l; simpl; intuition.\n subst; auto.\nQed.\nHint Resolve In_InA.\n\nLemma InA_split : forall l x, InA x l ->\n exists l1 y l2, eqA x y /\\ l = l1++y::l2.\nProof.\ninduction l; intros; inv.\nexists (@nil A); exists a; exists l; auto.\ndestruct (IHl x H0) as (l1,(y,(l2,(H1,H2)))).\nexists (a::l1); exists y; exists l2; auto.\nsplit; simpl; f_equal; auto.\nQed.\n\nLemma InA_app : forall l1 l2 x,\n InA x (l1 ++ l2) -> InA x l1 \\/ InA x l2.\nProof.\n induction l1; simpl in *; intuition.\n inv; auto.\n elim (IHl1 l2 x H0); auto.\nQed.\n\nLemma InA_app_iff : forall l1 l2 x,\n InA x (l1 ++ l2) <-> InA x l1 \\/ InA x l2.\nProof.\n split.\n apply InA_app.\n destruct 1; generalize H; do 2 rewrite InA_alt.\n destruct 1 as (y,(H1,H2)); exists y; split; auto.\n apply in_or_app; auto.\n destruct 1 as (y,(H1,H2)); exists y; split; auto.\n apply in_or_app; auto.\nQed.\n\nLemma InA_rev : forall p m,\n InA p (rev m) <-> InA p m.\nProof.\n intros; do 2 rewrite InA_alt.\n split; intros (y,H); exists y; intuition.\n rewrite In_rev; auto.\n rewrite <- In_rev; auto.\nQed.\n\n\n\nSection NoDupA.\n\nLemma NoDupA_app : forall l l', NoDupA l -> NoDupA l' ->\n  (forall x, InA x l -> InA x l' -> False) ->\n  NoDupA (l++l').\nProof.\ninduction l; simpl; auto; intros.\ninv.\nconstructor.\nrewrite InA_alt; intros (y,(H4,H5)).\ndestruct (in_app_or _ _ _ H5).\nelim H2.\nrewrite InA_alt.\nexists y; auto.\napply (H1 a).\nauto.\nrewrite InA_alt.\nexists y; auto.\napply IHl; auto.\nintros.\napply (H1 x); auto.\nQed.\n\nLemma NoDupA_rev : forall l, NoDupA l -> NoDupA (rev l).\nProof.\ninduction l.\nsimpl; auto.\nsimpl; intros.\ninv.\napply NoDupA_app; auto.\nconstructor; auto.\nintro; inv.\nintros x.\nrewrite InA_alt.\nintros (x1,(H2,H3)).\nintro; inv.\ndestruct H0.\nrewrite <- H4, H2.\napply In_InA.\nrewrite In_rev; auto.\nQed.\n\nLemma NoDupA_split : forall l l' x, NoDupA (l++x::l') -> NoDupA (l++l').\nProof.\n induction l; simpl in *; intros; inv; auto.\n constructor; eauto.\n contradict H0.\n rewrite InA_app_iff in *.\n rewrite InA_cons.\n intuition.\nQed.\n\nLemma NoDupA_swap : forall l l' x, NoDupA (l++x::l') -> NoDupA (x::l++l').\nProof.\n induction l; simpl in *; intros; inv; auto.\n constructor; eauto.\n assert (H2:=IHl _ _ H1).\n inv.\n rewrite InA_cons.\n red; destruct 1.\n apply H0.\n rewrite InA_app_iff in *; rewrite InA_cons; auto.\n apply H; auto.\n constructor.\n contradict H0.\n rewrite InA_app_iff in *; rewrite InA_cons; intuition.\n eapply NoDupA_split; eauto.\nQed.\n\nLemma equivlistA_NoDupA_split : forall l l1 l2 x y, eqA x y ->\n NoDupA (x::l) -> NoDupA (l1++y::l2) ->\n equivlistA (x::l) (l1++y::l2) -> equivlistA l (l1++l2).\nProof.\n intros; intro a.\n generalize (H2 a).\n rewrite !InA_app_iff, !InA_cons.\n inv.\n assert (SW:=NoDupA_swap H1). inv.\n rewrite InA_app_iff in H0.\n split; intros.\n assert (~eqA a x) by (contradict H3; rewrite <- H3; auto).\n assert (~eqA a y) by (rewrite <- H; auto).\n tauto.\n assert (OR : eqA a x \\/ InA a l) by intuition. clear H6.\n destruct OR as [EQN|INA]; auto.\n elim H0.\n rewrite <-H,<-EQN; auto.\nQed.\n\nEnd NoDupA.\n\n\n\nSection Fold.\n\nVariable B:Type.\nVariable eqB:B->B->Prop.\nVariable st:Equivalence eqB.\nVariable f:A->B->B.\nVariable i:B.\nVariable Comp:Proper (eqA==>eqB==>eqB) f.\n\nLemma fold_right_eqlistA :\n   forall s s', eqlistA s s' ->\n   eqB (fold_right f i s) (fold_right f i s').\nProof.\ninduction 1; simpl; auto with relations.\napply Comp; auto.\nQed.\n\n(** Fold with restricted [transpose] hypothesis. *)\n\nSection Fold_With_Restriction.\nVariable R : A -> A -> Prop.\nHypothesis R_sym : Symmetric R.\nHypothesis R_compat : Proper (eqA==>eqA==>iff) R.\n\n\n(*\n\n(** [ForallOrdPairs R] is compatible with [equivlistA] over the\n    lists without duplicates, as long as the relation [R]\n    is symmetric and compatible with [eqA]. To prove this fact,\n    we use an auxiliary notion: \"forall distinct pairs, ...\".\n*)\n\nDefinition ForallNeqPairs :=\n ForallPairs (fun a b => ~eqA a b -> R a b).\n\n(** [ForallOrdPairs] and [ForallNeqPairs] are related, but not completely\n    equivalent. For proving one implication, we need to know that the\n    list has no duplicated elements... *)\n\nLemma ForallNeqPairs_ForallOrdPairs : forall l, NoDupA l ->\n ForallNeqPairs l -> ForallOrdPairs R l.\nProof.\n induction l; auto.\n constructor. inv.\n rewrite Forall_forall; intros b Hb.\n apply H0; simpl; auto.\n contradict H1; rewrite H1; auto.\n apply IHl.\n inv; auto.\n intros b c Hb Hc Hneq.\n apply H0; simpl; auto.\nQed.\n\n(** ... and for proving the other implication, we need to be able\n   to reverse relation [R]. *)\n\nLemma ForallOrdPairs_ForallNeqPairs : forall l,\n ForallOrdPairs R l -> ForallNeqPairs l.\nProof.\n intros l Hl x y Hx Hy N.\n destruct (ForallOrdPairs_In Hl x y Hx Hy) as [H|[H|H]].\n subst; elim N; auto.\n assumption.\n apply R_sym; assumption.\nQed.\n\n*)\n\n(** Compatibility of [ForallOrdPairs] with respect to [inclA]. *)\n\nLemma ForallOrdPairs_inclA : forall l l',\n NoDupA l' -> inclA l' l -> ForallOrdPairs R l -> ForallOrdPairs R l'.\nProof.\ninduction l' as [|x l' IH].\nconstructor.\nintros ND Incl FOP. apply FOP_cons; inv; unfold inclA in *; auto.\nrewrite Forall_forall; intros y Hy.\nassert (Ix : InA x (x::l')) by (rewrite InA_cons; auto).\n apply Incl in Ix. rewrite InA_alt in Ix. destruct Ix as (x' & Hxx' & Hx').\nassert (Iy : InA y (x::l')) by (apply In_InA; simpl; auto).\n apply Incl in Iy. rewrite InA_alt in Iy. destruct Iy as (y' & Hyy' & Hy').\nrewrite Hxx', Hyy'.\ndestruct (ForallOrdPairs_In FOP x' y' Hx' Hy') as [E|[?|?]]; auto.\nabsurd (InA x l'); auto. rewrite Hxx', E, <- Hyy'; auto.\nQed.\n\n\n(** Two-argument functions that allow to reorder their arguments. *)\nDefinition transpose (f : A -> B -> B) :=\n  forall (x y : A) (z : B), eqB (f x (f y z)) (f y (f x z)).\n\n(** A version of transpose with restriction on where it should hold *)\nDefinition transpose_restr (R : A -> A -> Prop)(f : A -> B -> B) :=\n  forall (x y : A) (z : B), R x y -> eqB (f x (f y z)) (f y (f x z)).\n\nVariable TraR :transpose_restr R f.\n\nLemma fold_right_commutes_restr :\n  forall s1 s2 x, ForallOrdPairs R (s1++x::s2) ->\n  eqB (fold_right f i (s1++x::s2)) (f x (fold_right f i (s1++s2))).\nProof.\ninduction s1; simpl; auto; intros.\nreflexivity.\ntransitivity (f a (f x (fold_right f i (s1++s2)))).\napply Comp; auto.\napply IHs1.\ninvlist ForallOrdPairs; auto.\napply TraR.\ninvlist ForallOrdPairs; auto.\nrewrite Forall_forall in H0; apply H0.\napply in_or_app; simpl; auto.\nQed.\n\nLemma fold_right_equivlistA_restr :\n  forall s s', NoDupA s -> NoDupA s' -> ForallOrdPairs R s ->\n  equivlistA s s' -> eqB (fold_right f i s) (fold_right f i s').\nProof.\n simple induction s.\n destruct s'; simpl.\n intros; reflexivity.\n unfold equivlistA; intros.\n destruct (H2 a).\n assert (InA a nil) by auto; inv.\n intros x l Hrec s' N N' F E; simpl in *.\n assert (InA x s') by (rewrite <- (E x); auto).\n destruct (InA_split H) as (s1,(y,(s2,(H1,H2)))).\n subst s'.\n transitivity (f x (fold_right f i (s1++s2))).\n apply Comp; auto.\n apply Hrec; auto.\n inv; auto.\n eapply NoDupA_split; eauto.\n invlist ForallOrdPairs; auto.\n eapply equivlistA_NoDupA_split; eauto.\n transitivity (f y (fold_right f i (s1++s2))).\n apply Comp; auto. reflexivity.\n symmetry; apply fold_right_commutes_restr.\n apply ForallOrdPairs_inclA with (x::l); auto.\n  red; intros; rewrite E; auto.\nQed.\n\nLemma fold_right_add_restr :\n  forall s' s x, NoDupA s -> NoDupA s' -> ForallOrdPairs R s' -> ~ InA x s ->\n  equivlistA s' (x::s) -> eqB (fold_right f i s') (f x (fold_right f i s)).\nProof.\n intros; apply (@fold_right_equivlistA_restr s' (x::s)); auto.\nQed.\n\nEnd Fold_With_Restriction.\n\n(** we now state similar results, but without restriction on transpose. *)\n\nVariable Tra :transpose f.\n\nLemma fold_right_commutes : forall s1 s2 x,\n  eqB (fold_right f i (s1++x::s2)) (f x (fold_right f i (s1++s2))).\nProof.\ninduction s1; simpl; auto; intros.\nreflexivity.\ntransitivity (f a (f x (fold_right f i (s1++s2)))); auto.\napply Comp; auto.\nQed.\n\nLemma fold_right_equivlistA :\n  forall s s', NoDupA s -> NoDupA s' ->\n  equivlistA s s' -> eqB (fold_right f i s) (fold_right f i s').\nProof.\nintros; apply fold_right_equivlistA_restr with (R:=fun _ _ => True);\n repeat red; auto.\napply ForallPairs_ForallOrdPairs; try red; auto.\nQed.\n\nLemma fold_right_add :\n  forall s' s x, NoDupA s -> NoDupA s' -> ~ InA x s ->\n  equivlistA s' (x::s) -> eqB (fold_right f i s') (f x (fold_right f i s)).\nProof.\n intros; apply (@fold_right_equivlistA s' (x::s)); auto.\nQed.\n\nEnd Fold.\n\nSection Remove.\n\nHypothesis eqA_dec : forall x y : A, {eqA x y}+{~(eqA x y)}.\n\nLemma InA_dec : forall x l, { InA x l } + { ~ InA x l }.\nProof.\ninduction l.\nright; auto.\nintro; inv.\ndestruct (eqA_dec x a).\nleft; auto.\ndestruct IHl.\nleft; auto.\nright; intro; inv; contradiction.\nDefined.\n\nFixpoint removeA (x : A) (l : list A) : list A :=\n  match l with\n    | nil => nil\n    | y::tl => if (eqA_dec x y) then removeA x tl else y::(removeA x tl)\n  end.\n\nLemma removeA_filter : forall x l,\n  removeA x l = filter (fun y => if eqA_dec x y then false else true) l.\nProof.\ninduction l; simpl; auto.\ndestruct (eqA_dec x a); auto.\nrewrite IHl; auto.\nQed.\n\nLemma removeA_InA : forall l x y, InA y (removeA x l) <-> InA y l /\\ ~eqA x y.\nProof.\ninduction l; simpl; auto.\nsplit.\nintro; inv.\ndestruct 1; inv.\nintros.\ndestruct (eqA_dec x a); simpl; auto.\nrewrite IHl; split; destruct 1; split; auto.\ninv; auto.\ndestruct H0; transitivity a; auto.\nsplit.\nintro; inv.\nsplit; auto.\ncontradict n.\ntransitivity y; auto.\nrewrite (IHl x y) in H0; destruct H0; auto.\ndestruct 1; inv; auto.\nright; rewrite IHl; auto.\nQed.\n\nLemma removeA_NoDupA :\n  forall s x, NoDupA s ->  NoDupA (removeA x s).\nProof.\nsimple induction s; simpl; intros.\nauto.\ninv.\ndestruct (eqA_dec x a); simpl; auto.\nconstructor; auto.\nrewrite removeA_InA.\nintuition.\nQed.\n\nLemma removeA_equivlistA : forall l l' x,\n  ~InA x l -> equivlistA (x :: l) l' -> equivlistA l (removeA x l').\nProof.\nunfold equivlistA; intros.\nrewrite removeA_InA.\nsplit; intros.\nrewrite <- H0; split; auto.\ncontradict H.\napply InA_eqA with x0; auto.\nrewrite <- (H0 x0) in H1.\ndestruct H1.\ninv; auto.\nelim H2; auto.\nQed.\n\nEnd Remove.\n\n\n\n(** Results concerning lists modulo [eqA] and [ltA] *)\n\nVariable ltA : A -> A -> Prop.\nHypothesis ltA_strorder : StrictOrder ltA.\nHypothesis ltA_compat : Proper (eqA==>eqA==>iff) ltA.\n\nHint Resolve (@StrictOrder_Transitive _ _ ltA_strorder).\n\nNotation InfA:=(lelistA ltA).\nNotation SortA:=(sort ltA).\n\nHint Constructors lelistA sort.\n\nLemma InfA_ltA :\n forall l x y, ltA x y -> InfA y l -> InfA x l.\nProof.\n destruct l; constructor. inv; eauto.\nQed.\n\nGlobal Instance InfA_compat : Proper (eqA==>eqlistA==>iff) InfA.\nProof.\n intros x x' Hxx' l l' Hll'.\n inversion_clear Hll'.\n intuition.\n split; intro; inv; constructor.\n rewrite <- Hxx', <- H; auto.\n rewrite Hxx', H; auto.\nQed.\n\n(** For compatibility, can be deduced from [InfA_compat] *)\nLemma InfA_eqA :\n forall l x y, eqA x y -> InfA y l -> InfA x l.\nProof.\n intros l x y H; rewrite H; auto.\nQed.\nHint Immediate InfA_ltA InfA_eqA.\n\nLemma SortA_InfA_InA :\n forall l x a, SortA l -> InfA a l -> InA x l -> ltA a x.\nProof.\n simple induction l.\n intros. inv.\n intros. inv.\n setoid_replace x with a; auto.\n eauto.\nQed.\n\nLemma In_InfA :\n forall l x, (forall y, In y l -> ltA x y) -> InfA x l.\nProof.\n simple induction l; simpl; intros; constructor; auto.\nQed.\n\nLemma InA_InfA :\n forall l x, (forall y, InA y l -> ltA x y) -> InfA x l.\nProof.\n simple induction l; simpl; intros; constructor; auto.\nQed.\n\n(* In fact, this may be used as an alternative definition for InfA: *)\n\nLemma InfA_alt :\n forall l x, SortA l -> (InfA x l <-> (forall y, InA y l -> ltA x y)).\nProof.\nsplit.\nintros; eapply SortA_InfA_InA; eauto.\napply InA_InfA.\nQed.\n\nLemma InfA_app : forall l1 l2 a, InfA a l1 -> InfA a l2 -> InfA a (l1++l2).\nProof.\n induction l1; simpl; auto.\n intros; inv; auto.\nQed.\n\nLemma SortA_app :\n forall l1 l2, SortA l1 -> SortA l2 ->\n (forall x y, InA x l1 -> InA y l2 -> ltA x y) ->\n SortA (l1 ++ l2).\nProof.\n induction l1; simpl in *; intuition.\n inv.\n constructor; auto.\n apply InfA_app; auto.\n destruct l2; auto.\nQed.\n\nLemma SortA_NoDupA : forall l, SortA l -> NoDupA l.\nProof.\n simple induction l; auto.\n intros x l' H H0.\n inv.\n constructor; auto.\n intro.\n apply (StrictOrder_Irreflexive x).\n eapply SortA_InfA_InA; eauto.\nQed.\n\n\n(** Some results about [eqlistA] *)\n\nSection EqlistA.\n\nLemma eqlistA_length : forall l l', eqlistA l l' -> length l = length l'.\nProof.\ninduction 1; auto; simpl; congruence.\nQed.\n\nGlobal Instance app_eqlistA_compat :\n Proper (eqlistA==>eqlistA==>eqlistA) (@app A).\nProof.\n repeat red; induction 1; simpl; auto.\nQed.\n\n(** For compatibility, can be deduced from app_eqlistA_compat **)\nLemma eqlistA_app : forall l1 l1' l2 l2',\n   eqlistA l1 l1' -> eqlistA l2 l2' -> eqlistA (l1++l2) (l1'++l2').\nProof.\nintros l1 l1' l2 l2' H H'; rewrite H, H'; reflexivity.\nQed.\n\nLemma eqlistA_rev_app : forall l1 l1',\n   eqlistA l1 l1' -> forall l2 l2', eqlistA l2 l2' ->\n   eqlistA ((rev l1)++l2) ((rev l1')++l2').\nProof.\ninduction 1; auto.\nsimpl; intros.\ndo 2 rewrite app_ass; simpl; auto.\nQed.\n\nGlobal Instance rev_eqlistA_compat : Proper (eqlistA==>eqlistA) (@rev A).\nProof.\nrepeat red. intros.\nrewrite (app_nil_end (rev x)), (app_nil_end (rev y)).\napply eqlistA_rev_app; auto.\nQed.\n\nLemma eqlistA_rev : forall l1 l1',\n   eqlistA l1 l1' -> eqlistA (rev l1) (rev l1').\nProof.\napply rev_eqlistA_compat.\nQed.\n\nLemma SortA_equivlistA_eqlistA : forall l l',\n   SortA l -> SortA l' -> equivlistA l l' -> eqlistA l l'.\nProof.\ninduction l; destruct l'; simpl; intros; auto.\ndestruct (H1 a); assert (InA a nil) by auto; inv.\ndestruct (H1 a); assert (InA a nil) by auto; inv.\ninv.\nassert (forall y, InA y l -> ltA a y).\nintros; eapply SortA_InfA_InA with (l:=l); eauto.\nassert (forall y, InA y l' -> ltA a0 y).\nintros; eapply SortA_InfA_InA with (l:=l'); eauto.\nclear H3 H4.\nassert (eqA a a0).\n destruct (H1 a).\n destruct (H1 a0).\n assert (InA a (a0::l')) by auto. inv; auto.\n assert (InA a0 (a::l)) by auto. inv; auto.\n elim (StrictOrder_Irreflexive a); eauto.\nconstructor; auto.\napply IHl; auto.\nsplit; intros.\ndestruct (H1 x).\nassert (InA x (a0::l')) by auto. inv; auto.\nrewrite H9,<-H3 in H4. elim (StrictOrder_Irreflexive a); eauto.\ndestruct (H1 x).\nassert (InA x (a::l)) by auto. inv; auto.\nrewrite H9,H3 in H4. elim (StrictOrder_Irreflexive a0); eauto.\nQed.\n\nEnd EqlistA.\n\n(** A few things about [filter] *)\n\nSection Filter.\n\nLemma filter_sort : forall f l, SortA l -> SortA (List.filter f l).\nProof.\ninduction l; simpl; auto.\nintros; inv; auto.\ndestruct (f a); auto.\nconstructor; auto.\napply In_InfA; auto.\nintros.\nrewrite filter_In in H; destruct H.\neapply SortA_InfA_InA; eauto.\nQed.\n\nImplicit Arguments eq [ [A] ].\n\nLemma filter_InA : forall f, Proper (eqA==>eq) f ->\n forall l x, InA x (List.filter f l) <-> InA x l /\\ f x = true.\nProof.\nclear ltA ltA_compat ltA_strorder.\nintros; do 2 rewrite InA_alt; intuition.\ndestruct H0 as (y,(H0,H1)); rewrite filter_In in H1; exists y; intuition.\ndestruct H0 as (y,(H0,H1)); rewrite filter_In in H1; intuition.\n  rewrite (H _ _ H0); auto.\ndestruct H1 as (y,(H0,H1)); exists y; rewrite filter_In; intuition.\n  rewrite <- (H _ _ H0); auto.\nQed.\n\nLemma filter_split :\n forall f, (forall x y, f x = true -> f y = false -> ltA x y) ->\n forall l, SortA l -> l = filter f l ++ filter (fun x=>negb (f x)) l.\nProof.\ninduction l; simpl; intros; auto.\ninv.\nrewrite IHl at 1; auto.\ncase_eq (f a); simpl; intros; auto.\nassert (forall e, In e l -> f e = false).\n  intros.\n  assert (H4:=SortA_InfA_InA H1 H2 (In_InA H3)).\n  case_eq (f e); simpl; intros; auto.\n  elim (StrictOrder_Irreflexive e).\n  transitivity a; auto.\nreplace (List.filter f l) with (@nil A); auto.\ngeneralize H3; clear; induction l; simpl; auto.\ncase_eq (f a); auto; intros.\nrewrite H3 in H; auto; try discriminate.\nQed.\n\nEnd Filter.\nEnd Type_with_equality.\n\n\nHint Constructors InA eqlistA NoDupA sort lelistA.\n\nSection Find.\n\nVariable A B : Type.\nVariable eqA : A -> A -> Prop.\nHypothesis eqA_equiv : Equivalence eqA.\nHypothesis eqA_dec : forall x y : A, {eqA x y}+{~(eqA x y)}.\n\nFixpoint findA (f : A -> bool) (l:list (A*B)) : option B :=\n match l with\n  | nil => None\n  | (a,b)::l => if f a then Some b else findA f l\n end.\n\nLemma findA_NoDupA :\n forall l a b,\n NoDupA (fun p p' => eqA (fst p) (fst p')) l ->\n (InA (fun p p' => eqA (fst p) (fst p') /\\ snd p = snd p') (a,b) l <->\n  findA (fun a' => if eqA_dec a a' then true else false) l = Some b).\nProof.\nset (eqk := fun p p' : A*B => eqA (fst p) (fst p')).\nset (eqke := fun p p' : A*B => eqA (fst p) (fst p') /\\ snd p = snd p').\ninduction l; intros; simpl.\nsplit; intros; try discriminate.\ninvlist InA.\ndestruct a as (a',b'); rename a0 into a.\ninvlist NoDupA.\nsplit; intros.\ninvlist InA.\ncompute in H2; destruct H2. subst b'.\ndestruct (eqA_dec a a'); intuition.\ndestruct (eqA_dec a a'); simpl.\ncontradict H0.\nrevert e H2; clear - eqA_equiv.\ninduction l.\nintros; invlist InA.\nintros; invlist InA; auto.\ndestruct a0.\ncompute in H; destruct H.\nsubst b.\nleft; auto.\ncompute.\ntransitivity a; auto. symmetry; auto.\nrewrite <- IHl; auto.\ndestruct (eqA_dec a a'); simpl in *.\nleft; split; simpl; congruence.\nright. rewrite IHl; auto.\nQed.\n\nEnd Find.\n\n\n(** Compatibility aliases. [Proper] is rather to be used directly now.*)\n\nDefinition compat_bool {A} (eqA:A->A->Prop)(f:A->bool) :=\n Proper (eqA==>Logic.eq) f.\n\nDefinition compat_nat {A} (eqA:A->A->Prop)(f:A->nat) :=\n Proper (eqA==>Logic.eq) f.\n\nDefinition compat_P {A} (eqA:A->A->Prop)(P:A->Prop) :=\n Proper (eqA==>impl) P.\n\nDefinition compat_op {A B} (eqA:A->A->Prop)(eqB:B->B->Prop)(f:A->B->B) :=\n Proper (eqA==>eqB==>eqB) f.\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/Lists/SetoidList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7629729673989987}}
{"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: Zpower.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Import Wf_nat.\nRequire Import ZArith_base.\nRequire Export Zpow_def.\nRequire Import Omega.\nRequire Import Zcomplements.\nOpen Local Scope Z_scope.\n\nInfix \"^\" := Zpower : Z_scope.\n\n(** * Definition of powers over [Z]*)\n\n(** [Zpower_nat z n] is the n-th power of [z] when [n] is an unary\n    integer (type [nat]) and [z] a signed integer (type [Z]) *)\n\nDefinition Zpower_nat (z:Z) (n:nat) := iter_nat n Z (fun x:Z => z * x) 1.\n\n(** [Zpower_nat_is_exp] says [Zpower_nat] is a morphism for\n    [plus : nat->nat] and [Zmult : Z->Z] *)\n\nLemma Zpower_nat_is_exp :\n  forall (n m:nat) (z:Z),\n    Zpower_nat z (n + m) = Zpower_nat z n * Zpower_nat z m.\nProof.\n  intros; elim n;\n   [ simpl in |- *; elim (Zpower_nat z m); auto with zarith\n     | unfold Zpower_nat in |- *; intros; simpl in |- *; rewrite H;\n       apply Zmult_assoc ].\nQed.\n\n(** This theorem shows that powers of unary and binary integers\n   are the same thing, modulo the function convert : [positive -> nat] *)\n\nLemma Zpower_pos_nat :\n  forall (z:Z) (p:positive), Zpower_pos z p = Zpower_nat z (nat_of_P p).\nProof.\n  intros; unfold Zpower_pos in |- *; unfold Zpower_nat in |- *;\n    apply iter_nat_of_P.\nQed.\n\n(** Using the theorem [Zpower_pos_nat] and the lemma [Zpower_nat_is_exp] we\n   deduce that the function [[n:positive](Zpower_pos z n)] is a morphism\n   for [add : positive->positive] and [Zmult : Z->Z] *)\n\nLemma Zpower_pos_is_exp :\n  forall (n m:positive) (z:Z),\n    Zpower_pos z (n + m) = Zpower_pos z n * Zpower_pos z m.\nProof.\n  intros.\n  rewrite (Zpower_pos_nat z n).\n  rewrite (Zpower_pos_nat z m).\n  rewrite (Zpower_pos_nat z (n + m)).\n  rewrite (nat_of_P_plus_morphism n m).\n  apply Zpower_nat_is_exp.\nQed.\n\nHint Immediate Zpower_nat_is_exp Zpower_pos_is_exp : zarith.\nHint Unfold Zpower_pos Zpower_nat: zarith.\n\nTheorem Zpower_exp :\n  forall x n m:Z, n >= 0 -> m >= 0 -> x ^ (n + m) = x ^ n * x ^ m.\nProof.\n  destruct n; destruct m; auto with zarith.\n  simpl; intros; apply Zred_factor0.\n  simpl; auto with zarith.\n  intros; compute in H0; elim H0; auto.\n  intros; compute in H; elim H; auto.\nQed.\n\nSection Powers_of_2.\n\n  (** * Powers of 2 *)\n\n  (** For the powers of two, that will be widely used, a more direct\n      calculus is possible. We will also prove some properties such\n      as [(x:positive) x < 2^x] that are true for all integers bigger\n      than 2 but more difficult to prove and useless. *)\n\n  (** [shift n m] computes [2^n * m], or [m] shifted by [n] positions *)\n\n  Definition shift_nat (n:nat) (z:positive) := iter_nat n positive xO z.\n  Definition shift_pos (n z:positive) := iter_pos n positive xO z.\n  Definition shift (n:Z) (z:positive) :=\n    match n with\n      | Z0 => z\n      | Zpos p => iter_pos p positive xO z\n      | Zneg p => z\n    end.\n\n  Definition two_power_nat (n:nat) := Zpos (shift_nat n 1).\n  Definition two_power_pos (x:positive) := Zpos (shift_pos x 1).\n\n  Lemma two_power_nat_S :\n    forall n:nat, two_power_nat (S n) = 2 * two_power_nat n.\n  Proof.\n    intro; simpl in |- *; apply refl_equal.\n  Qed.\n\n  Lemma shift_nat_plus :\n    forall (n m:nat) (x:positive),\n      shift_nat (n + m) x = shift_nat n (shift_nat m x).\n  Proof.\n    intros; unfold shift_nat in |- *; apply iter_nat_plus.\n  Qed.\n\n  Theorem shift_nat_correct :\n    forall (n:nat) (x:positive), Zpos (shift_nat n x) = Zpower_nat 2 n * Zpos x.\n  Proof.\n    unfold shift_nat in |- *; simple induction n;\n      [ simpl in |- *; trivial with zarith\n\t| intros; replace (Zpower_nat 2 (S n0)) with (2 * Zpower_nat 2 n0);\n\t  [ rewrite <- Zmult_assoc; rewrite <- (H x); simpl in |- *; reflexivity\n\t    | auto with zarith ] ].\n  Qed.\n\n  Theorem two_power_nat_correct :\n    forall n:nat, two_power_nat n = Zpower_nat 2 n.\n  Proof.\n    intro n.\n    unfold two_power_nat in |- *.\n    rewrite (shift_nat_correct n).\n    omega.\n  Qed.\n\n  (** Second we show that [two_power_pos] and [two_power_nat] are the same *)\n  Lemma shift_pos_nat :\n    forall p x:positive, shift_pos p x = shift_nat (nat_of_P p) x.\n  Proof.\n    unfold shift_pos in |- *.\n    unfold shift_nat in |- *.\n    intros; apply iter_nat_of_P.\n  Qed.\n\n  Lemma two_power_pos_nat :\n    forall p:positive, two_power_pos p = two_power_nat (nat_of_P p).\n  Proof.\n    intro; unfold two_power_pos in |- *; unfold two_power_nat in |- *.\n    apply f_equal with (f := Zpos).\n    apply shift_pos_nat.\n  Qed.\n\n  (** Then we deduce that [two_power_pos] is also correct *)\n\n  Theorem shift_pos_correct :\n    forall p x:positive, Zpos (shift_pos p x) = Zpower_pos 2 p * Zpos x.\n  Proof.\n    intros.\n    rewrite (shift_pos_nat p x).\n    rewrite (Zpower_pos_nat 2 p).\n    apply shift_nat_correct.\n  Qed.\n\n  Theorem two_power_pos_correct :\n    forall x:positive, two_power_pos x = Zpower_pos 2 x.\n  Proof.\n    intro.\n    rewrite two_power_pos_nat.\n    rewrite Zpower_pos_nat.\n    apply two_power_nat_correct.\n  Qed.\n\n  (** Some consequences *)\n\n  Theorem two_power_pos_is_exp :\n    forall x y:positive,\n      two_power_pos (x + y) = two_power_pos x * two_power_pos y.\n  Proof.\n    intros.\n    rewrite (two_power_pos_correct (x + y)).\n    rewrite (two_power_pos_correct x).\n    rewrite (two_power_pos_correct y).\n    apply Zpower_pos_is_exp.\n  Qed.\n\n  (** The exponentiation [z -> 2^z] for [z] a signed integer.\n      For convenience, we assume that [2^z = 0] for all [z < 0]\n      We could also define a inductive type [Log_result] with\n      3 contructors [ Zero | Pos positive -> | minus_infty]\n      but it's more complexe and not so useful. *)\n\n  Definition two_p (x:Z) :=\n    match x with\n      | Z0 => 1\n      | Zpos y => two_power_pos y\n      | Zneg y => 0\n    end.\n\n  Theorem two_p_is_exp :\n    forall x y:Z, 0 <= x -> 0 <= y -> two_p (x + y) = two_p x * two_p y.\n  Proof.\n    simple induction x;\n      [ simple induction y; simpl in |- *; auto with zarith\n\t| simple induction y;\n\t  [ unfold two_p in |- *; rewrite (Zmult_comm (two_power_pos p) 1);\n\t    rewrite (Zmult_1_l (two_power_pos p)); auto with zarith\n\t    | unfold Zplus in |- *; unfold two_p in |- *; intros;\n\t      apply two_power_pos_is_exp\n\t    | intros; unfold Zle in H0; unfold Zcompare in H0;\n\t      absurd (Datatypes.Gt = Datatypes.Gt); trivial with zarith ]\n\t| simple induction y;\n\t  [ simpl in |- *; auto with zarith\n\t    | intros; unfold Zle in H; unfold Zcompare in H;\n\t      absurd (Datatypes.Gt = Datatypes.Gt); trivial with zarith\n\t    | intros; unfold Zle in H; unfold Zcompare in H;\n\t      absurd (Datatypes.Gt = Datatypes.Gt); trivial with zarith ] ].\n  Qed.\n\n  Lemma two_p_gt_ZERO : forall x:Z, 0 <= x -> two_p x > 0.\n  Proof.\n    simple induction x; intros;\n      [ simpl in |- *; omega\n\t| simpl in |- *; unfold two_power_pos in |- *; apply Zorder.Zgt_pos_0\n\t| absurd (0 <= Zneg p);\n\t  [ simpl in |- *; unfold Zle in |- *; unfold Zcompare in |- *;\n\t    do 2 unfold not in |- *; auto with zarith\n\t    | assumption ] ].\n  Qed.\n\n  Lemma two_p_S : forall x:Z, 0 <= x -> two_p (Zsucc x) = 2 * two_p x.\n  Proof.\n    intros; unfold Zsucc in |- *.\n    rewrite (two_p_is_exp x 1 H (Zorder.Zle_0_pos 1)).\n    apply Zmult_comm.\n  Qed.\n\n  Lemma two_p_pred : forall x:Z, 0 <= x -> two_p (Zpred x) < two_p x.\n  Proof.\n    intros; apply natlike_ind with (P := fun x:Z => two_p (Zpred x) < two_p x);\n      [ simpl in |- *; unfold Zlt in |- *; auto with zarith\n\t| intros; elim (Zle_lt_or_eq 0 x0 H0);\n\t  [ intros;\n\t    replace (two_p (Zpred (Zsucc x0))) with (two_p (Zsucc (Zpred x0)));\n\t      [ rewrite (two_p_S (Zpred x0));\n\t\t[ rewrite (two_p_S x0); [ omega | assumption ]\n\t\t  | apply Zorder.Zlt_0_le_0_pred; assumption ]\n\t\t| rewrite <- (Zsucc_pred x0); rewrite <- (Zpred_succ x0);\n\t\t  trivial with zarith ]\n\t    | intro Hx0; rewrite <- Hx0; simpl in |- *; unfold Zlt in |- *;\n\t      auto with zarith ]\n\t| assumption ].\n  Qed.\n\n  Lemma Zlt_lt_double : forall x y:Z, 0 <= x < y -> x < 2 * y.\n    intros; omega. Qed.\n\n  End Powers_of_2.\n\nHint Resolve two_p_gt_ZERO: zarith.\nHint Immediate two_p_pred two_p_S: zarith.\n\nSection power_div_with_rest.\n\n  (** * Division by a power of two. *)\n\n  (** To [n:Z] and [p:positive], [q],[r] are associated such that\n      [n = 2^p.q + r] and [0 <= r < 2^p] *)\n\n  (** Invariant: [d*q + r = d'*q + r /\\ d' = 2*d /\\ 0<= r < d /\\ 0 <= r' < d'] *)\n  Definition Zdiv_rest_aux (qrd:Z * Z * Z) :=\n    let (qr, d) := qrd in\n      let (q, r) := qr in\n\t(match q with\n\t   | Z0 => (0, r)\n\t   | Zpos xH => (0, d + r)\n\t   | Zpos (xI n) => (Zpos n, d + r)\n\t   | Zpos (xO n) => (Zpos n, r)\n\t   | Zneg xH => (-1, d + r)\n\t   | Zneg (xI n) => (Zneg n - 1, d + r)\n\t   | Zneg (xO n) => (Zneg n, r)\n\t end, 2 * d).\n\n  Definition Zdiv_rest (x:Z) (p:positive) :=\n    let (qr, d) := iter_pos p _ Zdiv_rest_aux (x, 0, 1) in qr.\n\n  Lemma Zdiv_rest_correct1 :\n    forall (x:Z) (p:positive),\n      let (qr, d) := iter_pos p _ Zdiv_rest_aux (x, 0, 1) in d = two_power_pos p.\n  Proof.\n    intros x p; rewrite (iter_nat_of_P p _ Zdiv_rest_aux (x, 0, 1));\n      rewrite (two_power_pos_nat p); elim (nat_of_P p);\n\tsimpl in |- *;\n\t  [ trivial with zarith\n\t    | intro n; rewrite (two_power_nat_S n); unfold Zdiv_rest_aux at 2 in |- *;\n\t      elim (iter_nat n (Z * Z * Z) Zdiv_rest_aux (x, 0, 1));\n\t\tdestruct a; intros; apply f_equal with (f := fun z:Z => 2 * z);\n\t\t  assumption ].\n  Qed.\n\n  Lemma Zdiv_rest_correct2 :\n    forall (x:Z) (p:positive),\n      let (qr, d) := iter_pos p _ Zdiv_rest_aux (x, 0, 1) in\n\tlet (q, r) := qr in x = q * d + r /\\ 0 <= r < d.\n  Proof.\n    intros;\n      apply iter_pos_invariant with\n\t(f := Zdiv_rest_aux)\n\t(Inv := fun qrd:Z * Z * Z =>\n          let (qr, d) := qrd in\n            let (q, r) := qr in x = q * d + r /\\ 0 <= r < d);\n\t[ intro x0; elim x0; intro y0; elim y0; intros q r d;\n\t  unfold Zdiv_rest_aux in |- *; elim q;\n\t    [ omega\n\t      | destruct p0;\n\t\t[ rewrite BinInt.Zpos_xI; intro; elim H; intros; split;\n\t\t  [ rewrite H0; rewrite Zplus_assoc; rewrite Zmult_plus_distr_l;\n\t\t    rewrite Zmult_1_l; rewrite Zmult_assoc;\n\t\t      rewrite (Zmult_comm (Zpos p0) 2); apply refl_equal\n\t\t    | omega ]\n\t\t  | rewrite BinInt.Zpos_xO; intro; elim H; intros; split;\n\t\t    [ rewrite H0; rewrite Zmult_assoc; rewrite (Zmult_comm (Zpos p0) 2);\n\t\t      apply refl_equal\n\t\t      | omega ]\n\t\t  | omega ]\n\t      | destruct p0;\n\t\t[ rewrite BinInt.Zneg_xI; unfold Zminus in |- *; intro; elim H; intros;\n\t\t  split;\n\t\t    [ rewrite H0; rewrite Zplus_assoc;\n\t\t      apply f_equal with (f := fun z:Z => z + r);\n\t\t\tdo 2 rewrite Zmult_plus_distr_l; rewrite Zmult_assoc;\n\t\t\t  rewrite (Zmult_comm (Zneg p0) 2); rewrite <- Zplus_assoc;\n\t\t\t    apply f_equal with (f := fun z:Z => 2 * Zneg p0 * d + z);\n\t\t\t      omega\n\t\t      | omega ]\n\t\t  | rewrite BinInt.Zneg_xO; unfold Zminus in |- *; intro; elim H; intros;\n\t\t    split;\n\t\t      [ rewrite H0; rewrite Zmult_assoc; rewrite (Zmult_comm (Zneg p0) 2);\n\t\t\tapply refl_equal\n\t\t\t| omega ]\n\t\t  | omega ] ]\n\t  | omega ].\n  Qed.\n\n  Inductive Zdiv_rest_proofs (x:Z) (p:positive) : Set :=\n    Zdiv_rest_proof :\n    forall q r:Z,\n      x = q * two_power_pos p + r ->\n      0 <= r -> r < two_power_pos p -> Zdiv_rest_proofs x p.\n\n  Lemma Zdiv_rest_correct : forall (x:Z) (p:positive), Zdiv_rest_proofs x p.\n  Proof.\n    intros x p.\n    generalize (Zdiv_rest_correct1 x p); generalize (Zdiv_rest_correct2 x p).\n    elim (iter_pos p (Z * Z * Z) Zdiv_rest_aux (x, 0, 1)).\n    simple induction a.\n    intros.\n    elim H; intros H1 H2; clear H.\n    rewrite H0 in H1; rewrite H0 in H2; elim H2; intros;\n      apply Zdiv_rest_proof with (q := a0) (r := b); assumption.\n  Qed.\n\nEnd power_div_with_rest.\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/Zpower.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7629729669203437}}
{"text": "Section SetTheory.\n\nRequire Import Ensembles. (*集合論のライブラリ*)\nRequire Import Classical.\n\n(*集合の定義\nVariable U : Type.\nDefinition Ensemble := U -> Prop.*)\n\n(*要素関係\nDefinition In (A:Ensemble) (x:U) : Prop := A x.*)\n\n(*\n集合の包含関係の定義である．\nDefinition Included (B C:Ensemble) : Prop := forall x:U, In B x -> In C x.*)\n\n(*全体集合と空集合の定義である．*)\n(*Inductive Full set : Ensemble := Full intro : forall x:U, In Full set x.\nInductive Empty set : Ensemble :=.*)\n(*Definitionだと以下\nDefinition Full set : Ensemble := fun x:U=>True.\nDefinition Empty set : Ensemble := fun x:U=>False.*)\n\n(*集合に関する演算の和集合 (union)∪，共通部分 (intersection)\n\nInductive Union (B C:Ensemble) : Ensemble :=\n| Union introl : forall x:U, In B x -> In (Union B C) x\n| Union intror : forall x:U, In C x -> In (Union B C) x.\n\nInductive Intersection (B C:Ensemble) : Ensemble :=\nIntersection intro : forall x:U,\n  In B x -> In C x -> In (Intersection B C) x.*)\n\n\nLtac ok:= trivial; contradiction.\nLtac hairihou := apply NNPP; intro.\n\nVariable U : Type.\nNotation Shugo := (Ensemble U).\nNotation \"x ∈ A\":=(In U A x)(at level 55,no associativity).\nNotation \"A ⊆ B\":=(Included U A B)(at level 54, no associativity).\nNotation \"A ∩ B\":=(Intersection U A B)(at level 53, right associativity).\nNotation \"A ∪ B\" :=(Union U A B)(at level 53, right associativity).\nNotation Ω:=(Full_set U).\nNotation ø :=(Empty_set U).\n\nLemma in_or_not : forall A, forall x,\n      (x ∈ A) \\/ ~(x ∈ A).\nProof. intros; apply classic. Qed.\n\nLemma bubun_transitive : forall A B C,\n    (A ⊆ B) /\\ (B ⊆ C) -> A ⊆ C.\nProof. unfold Included. intros. destruct H as [H H1]. apply H1. apply H. ok. Qed.\n\nLtac bubun := unfold Included; intros.\n\nLemma empty_bubun : forall A, ø ⊆ A. \nProof. bubun.  destruct H. Qed.\n\nLemma bubun_full : forall A, A ⊆ Ω.\nProof. bubun. apply Full_intro. Qed.\n\nLtac seteq := apply Extensionality_Ensembles; unfold Same_set; split.\n\nLemma Union_aa : forall A, A ∪ A = A.\nProof. intros. seteq. bubun.\n       inversion H. apply H0. apply H0.\n       bubun. apply Union_introl. apply H.\nQed.\n\nLemma Union_comm : forall A B, A ∪ B = B ∪ A.\nProof. intros. seteq; bubun;\n       destruct H; try (apply Union_intror; apply H); try (apply Union_introl; apply H).\nQed.\n\nLemma Union_3 : forall A B C, A ∪ ( B ∪ C ) = (A ∪ B) ∪ C.\nProof. intros. seteq; bubun. induction H. repeat (apply Union_introl). apply H. induction H. apply Union_introl.\n       apply Union_intror. apply H. apply Union_intror. apply H.\n       induction H. induction H. apply Union_introl. apply H. apply Union_intror. apply Union_introl. apply H.\n       repeat (apply Union_intror). apply H.\nQed.\n\nLemma bubun_AB_A : forall A B, A ⊆ (A ∪ B).\nProof. intros. bubun. apply Union_introl. apply H. Qed.\n\nLemma bubun_AB_B : forall A B, B ⊆ (A ∪ B).\nProof. intros. bubun. apply Union_intror. apply H. Qed.\n\nLemma bubun_3 : forall A B C, A ⊆ C -> B ⊆ C -> A ∪ B ⊆ C.\nProof. bubun. inversion H1. apply H. apply H2. apply H0. apply H2. Qed.\n\nLemma and_AA : forall A, A ∩ A = A.\nProof. intros. seteq. bubun. inversion H. apply H0. bubun. split; apply H. Qed.\n\nLemma and_comm : forall A B, A ∩ B = B ∩ A.\nProof. intros. seteq; bubun; inversion H; split; assumption. Qed.\n\nLemma and_3 : forall A B C, A ∩ (B ∩ C) = (A ∩ B) ∩ C.\nProof. intros. seteq. bubun. inversion H as [H0  H1]; inversion H2. repeat (split); assumption.\n       bubun. destruct H. destruct H. repeat (split); assumption. Qed.\n\nLemma and_ABA : forall A B, A ∩ B ⊆ A.\nProof. intros. bubun. inversion H. apply H0. Qed.\n\nLemma and_ABB : forall A B, A ∩ B ⊆ B.\nProof. intros. bubun. inversion H. apply H1. Qed.\n\nLemma and_CAB : forall A B C, C ⊆ A -> C ⊆ B -> C ⊆ A ∩ B.\nProof. intros. split. apply H in H1. assumption. apply H0 in H1. assumption. Qed.\n\nLemma and_In_iff : forall A B, A ⊆ B <-> A ∩ B = A.\nProof. intros. split. bubun. seteq. bubun. inversion H0. apply H1. bubun. split. apply H0. apply H. apply H0.\n       intros. bubun. rewrite <- H in H0. inversion H0. apply H2. Qed.\n\n(*Ensembles では，Disjoint は次のように定義されている．\n\nInductive Disjoint (B C:Ensemble) : Prop :=\n  Disjoint intro : (forall x:U, ˜In (Intersection B C) x) -> Disjoint B C.\n\n B ∩ C に元がないときに，Disjoint B C と定義している．*)\n\nLemma Kuu :forall A B, Disjoint U A B <-> (A ∩ B) = ø.\nProof.\n  split. intros. seteq. bubun. destruct H. specialize (H x). ok. apply empty_bubun.\n  intros. apply Disjoint_intro. intros. unfold not. intros. rewrite H in H0. inversion H0.\nQed.\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/set-text/set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7629729594356538}}
{"text": "Coq < Section Predicate.\n\nCoq < Require Import Classical.\n\nCoq < Variable D : Set.\nD is assumed\n\nCoq < Variable R : D -> D -> Prop.\nR is assumed\n\nCoq < Section R_sym_trans.\n\nCoq < Hypothesis R_symmetric : forall x y:D, R x y -> R y x.\nR_symmetric is assumed\n\nCoq < Hypothesis R_transitive : forall x y z:D, R x y -> R y z -> R x z.\nR_transitive is assumed\n\nCoq < Lemma refl_if : forall x:D, (exists y, R x y) -> R x x.\n1 subgoal\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  ============================\n   forall x : D, (exists y : D, R x y) -> R x x\n\nrefl_if < Check ex.\nex\n     : forall A : Type, (A -> Prop) -> Prop\n\nrefl_if < intros x x_Rlinked.\n1 subgoal\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  x : D\n  x_Rlinked : exists y : D, R x y\n  ============================\n   R x x\n\nrefl_if < intro y.\nToplevel input, characters 0-7:\n> intro y.\n> ^^^^^^^\nError: No product even after head-reduction.\n\nrefl_if < elim x_Rlinked.\n1 subgoal\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  x : D\n  x_Rlinked : exists y : D, R x y\n  ============================\n   forall x0 : D, R x x0 -> R x x\n\nrefl_if < intros y Rxy.\n1 subgoal\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  x : D\n  x_Rlinked : exists y : D, R x y\n  y : D\n  Rxy : R x y\n  ============================\n   R x x\n\nrefl_if < apply R_transitive with y.\n2 subgoals\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  x : D\n  x_Rlinked : exists y : D, R x y\n  y : D\n  Rxy : R x y\n  ============================\n   R x y\n\nsubgoal 2 is:\n R y x\n\nrefl_if < assumption.\n1 subgoal\n  \n  D : Set\n  R : D -> D -> Prop\n  R_symmetric : forall x y : D, R x y -> R y x\n  R_transitive : forall x y z : D, R x y -> R y z -> R x z\n  x : D\n  x_Rlinked : exists y : D, R x y\n  y : D\n  Rxy : R x y\n  ============================\n   R y x\n\nrefl_if < apply R_symmetric; assumption.\nNo more subgoals.\n\nrefl_if < Qed.\nintros x x_Rlinked.\nelim x_Rlinked.\nintros y Rxy.\napply R_transitive with y.\n assumption.\n\n apply R_symmetric; assumption.\n\nrefl_if 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/practice19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7628168650796645}}
{"text": "Require Import Cases.\nDefinition admit {T:Type} : T. Admitted.\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.\nDefinition even (n:nat) : Prop := \n  evenb n = true.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(* 1. Explain why proving the following lemma the \"obvious\" way gets stuck. *)\nLemma even__even_broken: forall n : nat, even n -> ev n.\nProof. induction n. Admitted.\n(*\nyou must induct on the proof of evenness (where 'next' is 'S (S _)'), not on the even number (where 'next' is 'S'). \"ev n\" can prove \"ev (S (S n))\" but not \"ev (S n)\".\n*)\n\n(* SearchAbout *)\n\n(*\n\"ev -> even\" is easy because we induct on ev\n\"even -> ev\" is hard\n\n*)\n\nLemma even__iff__even_SS : forall n,\neven (S (S n)) <-> even n.\nProof. intros. split.\n\nCase \"<-\". intros. inversion H. assumption.\n\nCase \"->\". intros. induction n.\nauto. inversion H. apply H1.\n\nQed.\n\nLemma ev_implies_even : forall n : nat,\nev n -> even n.\nintros. induction H.\nreflexivity.\napply even__iff__even_SS. assumption.\nQed.\n\nLemma even_not_odd : forall n,\neven n -> ~(even (S n)).\nunfold not. intros. induction n.\ninversion H0.\napply IHn; assumption.\nQed.\n\nLemma odd_not_even : forall n,\n~(even (S n)) -> even n.\nintros. induction n.\nreflexivity.\nrewrite even__iff__even_SS in H.\napply H in IHn. contradiction.\nintros A. apply H.\ninversion A as [A1].\nunfold even.\n\nAdmitted.\n\n(* 2. Complete the following proof instead. *)\nLemma even__even : forall n : nat,\n(even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof. intro. apply and_comm. split.\n\nCase \"n\". intros. induction n.\n\ninversion H.\n\napply ev_SS. rewrite even__iff__even_SS in H.\nadmit.\n\n\nCase \"S n\". admit.\nQed.\n\n(* cant do it *)\n\n(* 3. Construct a proof object demonstrating the following proposition. *)\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\nfun (P Q R : Prop) (pq : P /\\ Q) (qr : Q /\\ R) => \n(* take proof of P from PQ and proof of Q from QR to make a proof of PR *)\nconj\n match pq with conj p q => p end\n match qr with conj q r => r end\n.\n\n\n(* 4. Distributing or over and *)\n(* This one is provided from the notes... *)\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(* Prove the reverse direction... *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\nintros. inversion H as [[HP | HQ] [HP' | HR]].\nleft. assumption.\nleft. assumption.\nleft. assumption.\nright. split; assumption.\nQed. \n\n(* ...and give a *short* proof of the if-and-only-if *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof. split.\n apply or_distributes_over_and_1.\n apply or_distributes_over_and_2.\nQed.\n\n(* 5. Facts about not and or *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\nunfold not. intros P Q. intros A B C.\napply B. apply A. apply C.\nQed.\n\nTheorem not_both_true_and_false : forall P:Prop, ~(P /\\ ~ P).\nProof.\nintros P H. unfold not in *. inversion H.\napply (H1 H0).\nQed.\n\n(* Why does the following lemma get stuck? *)\nLemma broken : forall (P Q:Prop),\n  (P -> Q) -> (~ P -> False) -> Q.\nProof.\n  intros. apply H. unfold not in *. Admitted.\n(* we just cant prove P. its on the left of the hypotheses. if we try the contrapositive, we just get the same *)\n\n\n(* 6. Tricky!  The following five statements are often \n      considered as characterizations of classical logic.  We can't\n      prove them in Coq, but we can add any of them as an unproven\n      axiom if we want to work in classical logic.  \n\n      For credit in this problem, prove that \"de_morgan_not_and_not\"\n      and \"excluded_middle\" are equivalent.\n\n      For extra credit, prove that all five definitions are \n      equivalent.  If you try this part:\n        Hint 1: You can prove this equivalence in just five\n                implications.\n        Hint 2: Follow the ordering of the definitions below.\n*)\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q) -> P) -> P.\nDefinition classic := forall P:Prop,\n  ~~P  ->  P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P/\\~Q)  ->  P\\/Q.\nDefinition excluded_middle := forall P:Prop,\n  P \\/ ~P.\nDefinition implies_to_or := forall P Q:Prop,\n  (P -> Q)  ->  (~P\\/Q).\n\nTheorem peirce_implies_classic : peirce -> classic.\nunfold peirce, classic. intros Peirce P.\nunfold not at 2. intro NN. apply (Peirce P False). intro N.\ncontradiction.\nQed.\n\nTheorem classic_implies_demorgan : classic -> de_morgan_not_and_not.\nunfold classic, de_morgan_not_and_not.\nintro Classic. intros P Q. unfold not.\nintro nan. apply Classic. unfold not.\nintro nor. apply nan. \nsplit.\n intro. apply nor. left. assumption.\n intro. apply nor. right. assumption.\nQed.\n\nTheorem demorgan_implies_exclude : de_morgan_not_and_not -> excluded_middle.\nunfold de_morgan_not_and_not, excluded_middle.\nintros Demogran P. apply Demogran. unfold not. intro.\ninversion H. contradiction.\nQed.\n\nTheorem exclude__implies__imply_is_or : excluded_middle -> implies_to_or.\nunfold excluded_middle, implies_to_or.\nintros EM. intros P Q H.\nCheck EM P.\nremember (EM P) as either_or. inversion either_or as [T|F].\n(* syntax for \"inversion (EM P)\" ? *)\nCase \"P is true\". right. apply (H T).\nCase \"P is false\". left. assumption.\nQed.\n\n\nTheorem O2I : forall P Q : Prop,\n (P -> False) \\/ Q -> (P -> Q).\nProof. intros. inversion H. contradiction. assumption.\nQed.\n\n(*\nTheorem __classical__or_iff_implies : forall P Q : Prop,\n classic ->\n ((P -> Q)  <->  (P -> False) \\/ Q).\nProof. intros.\napply classic_implies_demorgan in H.\napply demorgan_implies_exclude in H.\napply exclude__implies__imply_is_or in H.\nsplit. apply H. apply O2I.\nQed.\n*)\n\nTheorem __classical__or_iff_implies : forall P Q : Prop,\n ((P -> Q)  <->  (P -> False) \\/ Q).\nAdmitted.\n\nTheorem imply_is_or__implies__peirce : implies_to_or -> peirce.\nunfold implies_to_or, peirce, not.\nintros I2O. intros P Q. intros H.\n\nremember H as H'. clear HeqH'.\napply I2O in H.\nassert (OiffI := __classical__or_iff_implies).\nrewrite (OiffI P Q) in H.\n\ndestruct H as [A|B].\n(* rewrite de_morgan_not_and_not in A. *)\n\n(*\nrewrite (I2O P Q) in L. \napply H. intro HP.\napply I2O in H. destruct H as [L|R]. \n*)\n\nCase \"hard\". (* admit. dammit, the last one *)\nadmit.\n\n\nCase \"easy\". assumption.\nAdmitted.\n\n(* remember (I2O (P->Q) P H) as A. clear HeqA. inversion A as [L|R].\nCase \"P left\". apply H. \n remember (P -> Q) as PiQ. clear HeqPiQ. apply PiQ in L.\nCase \"P right\". assumption.\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(* 7. Forall and exists, in classical logic *)\nTheorem forall__not_exists_not : \n  forall (X:Type) (P : X -> Prop),\n    (forall x, P x) -> ~ (exists x, ~ P x).\nProof. (* This should be a *short* proof *)\nunfold not. intros X P A E.\n inversion E. apply H. apply A.\nQed.\n\n\nTheorem not_exists_not__forall : excluded_middle ->\n  forall (X : Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof. unfold excluded_middle. unfold not.\nintros EM. intro X. intro P. intro NN. intro x.\n\nassert (P x \\/ (P x -> False)). apply EM.\ninversion H as [L|R].\n\nassumption.\n\nassert False. apply NN. exists x.\nassumption.\ncontradiction.\n\nQed.\n\n\n(* Theorem not_exists__forall_not : excluded_middle ->\n  forall (X : Type) (P : X -> Prop), \n    ~ (exists x, P x) -> (forall x, ~ P x).\nProof.\nunfold excluded_middle. unfold not. intros EM X P E w H.\napply E. exists w. assumption.\nQed.\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* 8. Multi-place relations *)\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(* The relation R above relates triples of numbers.  Which of the\n   following two terms are provable?\n\n   R 1 1 2\n   R 2 2 6 *)\nGoal R 1 1 2. apply c3. apply c2. apply c1. Qed.\n\n(* If we dropped the constructor c5 from the definition of R, would\n   the set of provable propositions change?  Why? (1-sentence answer)\n *)\n(* ANSWER no because \"apply c5. apply c2.\" is just \"apply c3.\" when m <> n (and does nothing otherwise) *)\n\n(* If  we dropped the constructor c4, would the set of provable\n   propositions change?  Why?  (1-sentence answer) *)\n(* ANSWER no because  \"apply c5.\" undoes \"apply c2. apply c3.\" *)\n\n(* In words, describe what common relationship between numbers is \n   expressed by R. *)\n(* \"m, n and o are related by R iff m+n=o.\" nice. *)\n", "meta": {"author": "sboosali", "repo": "coq", "sha": "c09f90a114ed7948f8cdf75828832e7d01093a84", "save_path": "github-repos/coq/sboosali-coq", "path": "github-repos/coq/sboosali-coq/coq-c09f90a114ed7948f8cdf75828832e7d01093a84/hw5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.7628083011207585}}
{"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.\nFrom Categories Require Import Category.Opposite.\n\nLocal Open Scope morphism_scope.\n\n(** The basic Definition of an isomorphism in a category.\nAn isomorphism is a pair of arrows f : a -> b and g : b -> a such that\ng ∘ f = id a and f ∘ g = id b. *)\nRecord Isomorphism {C : Category} (a b : C) : Type := \n{\n  iso_morphism : a –≻ b;\n  \n  inverse_morphism : b –≻ a;\n  \n  left_inverse : (inverse_morphism ∘ iso_morphism)%morphism = id;\n  \n  right_inverse : (iso_morphism ∘ inverse_morphism)%morphism = id\n}.\n\n\nBind Scope morphism_scope with Isomorphism.\nBind Scope isomorphism_scope with Isomorphism.\n\nHint Resolve left_inverse.\n\nHint Resolve right_inverse.\n\nCoercion iso_morphism : Isomorphism >-> Hom.\n\nArguments iso_morphism {_ _ _} _.\nArguments inverse_morphism {_ _ _} _.\nArguments left_inverse {_ _ _} _.\nArguments right_inverse {_ _ _} _.\n\nNotation \"f '⁻¹'\" := (inverse_morphism f) : morphism_scope.\n\nNotation \"a ≃ b\" := (Isomorphism a b) : isomorphism_scope.\n\nNotation \"a ≃≃ b ::> C\" := (@Isomorphism C a b) : isomorphism_scope.\n\nLocal Open Scope isomorphism_scope.\n\n(* basic tactics for isomorphisms *)\n\nLtac simpl_isos_in_goal :=\n  repeat(\n      match goal with\n      | [|- context[(iso_morphism ?A ∘ inverse_morphism ?A)%morphism]] =>\n        rewrite (right_inverse A); simpl_ids\n      | [|- context[(inverse_morphism ?A ∘ iso_morphism ?A)%morphism] ] =>\n        rewrite (left_inverse A); simpl_ids\n(* disabled due to problems with reveal_comp complexity *)\n(*        | [|- context[iso_morphism ?A] ] =>\n          reveal_comp (inverse_morphism A) (iso_morphism A) +\n          reveal_comp (iso_morphism A) (inverse_morphism A) *)\n      end\n    )\n.\n\nLtac simpl_isos_in_I I :=\n  repeat(\n      match type of I with\n      | context[(iso_morphism ?A ∘ inverse_morphism ?A)%morphism] =>\n        rewrite (right_inverse A) in I; simpl_ids in I\n      | context[(inverse_morphism ?A ∘ iso_morphism ?A)%morphism] =>\n        rewrite (left_inverse A) in I; simpl_ids in I\n(* disabled due to problems with reveal_comp complexity *)\n(*        | context[inverse_morphism ?A] =>\n          reveal_comp (inverse_morphism A) (iso_morphism A) in I +\n          reveal_comp (iso_morphism A) (inverse_morphism A) in I *)\n      end\n    )\n.\n\nTactic Notation \"simpl_isos\" := simpl_isos_in_goal.\n\nTactic Notation \"simpl_isos\" \"in\" hyp(I) := simpl_isos_in_I I.\n\nHint Extern 3 => progress simpl_isos.\n\nHint Extern 3 => progress (dohyps (fun H => simpl_isos in H)).\n\n(** simplifies equality of iso-morphisms. This theorem uses proof irrelevance\nto assume any two proofs for left and right inverse properties are equal.\nIn other words, two isomorphisms are equal if their underlying morphisms are. *)\nTheorem Isomorphism_eq_simplify {C : Category} {a b : C} (I I' : a ≃ b) :\n  (iso_morphism I = iso_morphism I') →\n  (inverse_morphism I = inverse_morphism I') → I = I'.\nProof.\n  intros H1 H2.\n  destruct I as [iI inI Il Ir]; destruct I' as [iI' inI' Il' Ir'].\n  cbn in *.\n  destruct H1; destruct H2.\n  destruct (proof_irrelevance _ Il Il').\n  destruct (proof_irrelevance _ Ir Ir').\n  trivial.  \nQed.  \n\n(** Isomorphism is an equivalence relation on objects. *)\n\n(** The identity morphism forms an isomorphism, i.e., it is inverse to itself.\nThis is reflexivity property for the equivalence relation of isomorphism\non objects. *)\nProgram Definition Isomorphism_id {C : Category} {a : C} : a ≃ a :=\n{|\n  iso_morphism := id;\n  inverse_morphism := id\n|}.\n\n(** Each ismorphism has an inverse isomorphism. Simply swap the morphisms and\nproofs of left and right inverse properties. This is symmetry property for the\nequivalence relation of isomorphism on objects. *)\nDefinition Inverse_Isomorphism {C : Category} {a b : C} (I : a ≃ b) : b ≃ a :=\n{|\n  iso_morphism := I⁻¹;\n  inverse_morphism := I;\n  left_inverse := right_inverse I;\n  right_inverse := left_inverse I\n|}.\n\nNotation \"f '⁻¹'\" := (Inverse_Isomorphism f) : isomorphism_scope.\n\n(** Isomorphisms compose. Simply compose the underlying morphisms of the \nisomorphism. Left and right inverse properties follow straightforwardly.\nThis is transitivty property for the equivalence relation of isomorphism\non objects. *)\nProgram Definition Isomorphism_Compose\n        {C : Category} {a b c : C} (I : a ≃ b) (I' : b ≃ c) : a ≃ c\n  :=\n{|\n  iso_morphism := I' ∘ I;\n  inverse_morphism := I⁻¹ ∘ I'⁻¹\n|}.\n\nNext Obligation.\nProof.\n  rewrite assoc.\n  rewrite (assoc_sym I).\n  auto.\nQed.\n\nNext Obligation.\nProof.\n  rewrite assoc.\n  rewrite (assoc_sym (I'⁻¹)).\n  auto.\nQed.\n\nNotation \"f ∘ g\" := (Isomorphism_Compose g f) : isomorphism_scope.\n\nLocal Close Scope isomorphism_scope.\n\n(** A monic arrow (AKA, mono, monomorphic arrow and monomorphism) m is an arrow\nsuch that for any two arrows g and h (of the appropriate domain and codomain)\nwe have if m ∘ g = m ∘ h then g = h. *)\nRecord Monic {C : Category} (a b : Obj) :=\n{\n  mono_morphism : a –≻ b;\n  mono_morphism_monomorphic : ∀ (c : Obj) (g h : c –≻ a),\n      (mono_morphism ∘ g = mono_morphism ∘ h) → g = h\n}.\n\nCoercion mono_morphism : Monic >-> Hom.\n\nArguments mono_morphism {_ _ _} _.\nArguments mono_morphism_monomorphic {_ _ _} _ _ _ _ _.\n\nNotation \"a ≫–> b\" := (Monic a b) : morphism_scope.\n\nBind Scope morphism_scope with Monic.\n\n(** An epic arrow (AKA, epi, epimorphic arrow and epimorphism) is a monomorphism\nin the opposite category. That is, m is epic if for any pair of arrows g and h\n(of the appropriate domain and codomain) we have if g ∘ m = h ∘ m then g = h. *)\nDefinition Epic {C : Category} (a b : C) := @Monic (C^op) b a.\n\nNotation \"a –≫ b\" := (Epic a b) : morphism_scope.\n\nBind Scope morphism_scope with Epic.\n\n(** The condition for a morphism to be mono-morphic. *)\nDefinition is_Monic {C : Category} {a b : Obj} (f : a –≻ b) :=\n  ∀ (c : Obj) (g h : c –≻ a), (f ∘ g = f ∘ h) → g = h.\n\n(** A mono-morphic morphism forms a Monic. *)\nDefinition is_Monic_Monic\n           {C : Category}\n           {a b : Obj}\n           {f : a –≻ b}\n           (H : is_Monic f)\n  : Monic a b\n  :=\n    {|\n      mono_morphism := f;\n      mono_morphism_monomorphic := H\n    |}\n.\n\n(** A morphism is ipic if it is monic in the opposit category. *)\nDefinition is_Epic {C : Category} {a b : C} (f : a –≻ b) :=\n  @is_Monic (C^op) b a f.\n\n(** A morphism f : a –≻ b is split monic if there is another morphism\ng : b –≻ a such that g ∘ f = idₐ *)\nRecord is_split_Monic {C : Category} {a b : Obj} (f : a –≻ b) :=\n  {\n    is_split_monic_left_inverse : b –≻ a;\n    is_split_monic_left_inverse_is_left_inverse :\n      (is_split_monic_left_inverse ∘ f) = id\n  }\n.\n\nArguments is_split_monic_left_inverse {_ _ _ _} _.\nArguments is_split_monic_left_inverse_is_left_inverse {_ _ _ _} _.\n\n(** A morphism is ipic if it is monic in the opposit category. *)\nDefinition is_split_Epic {C : Category} {a b : C} (f : a –≻ b) :=\n  @is_split_Monic (C^op) b a f.\n\n(** A split monic morphism is a monomorphism. *)\nProgram Definition is_split_Monic_Monic\n           {C : Category}\n           {a b : Obj}\n           {f : a –≻ b}\n           (H : is_split_Monic f)\n  : Monic a b\n  :=\n    {|\n      mono_morphism := f;\n      mono_morphism_monomorphic := fun c g h H1 => _\n    |}\n.\n\nNext Obligation.\nProof.\n  assert (H2 := f_equal (fun w : c –≻ b => (is_split_monic_left_inverse H) ∘ w) H1).\n  cbn in H2.\n  repeat rewrite assoc_sym in H2.\n  rewrite is_split_monic_left_inverse_is_left_inverse in H2.\n  auto.\nQed.\n\n(** If a monic morphism is split epic, it forms an isomorphism. *)\nProgram Definition Monic_is_split_Epic_Iso\n        {C : Category}\n        (a b : Obj)\n        (f : a ≫–> b)\n        (H : is_split_Epic f)\n  :\n    (a ≃ b)%isomorphism\n  :=\n    {|\n      iso_morphism := f;\n      inverse_morphism := is_split_monic_left_inverse H;\n      right_inverse := is_split_monic_left_inverse_is_left_inverse H\n    |}\n.\n\nNext Obligation.\nProof.\n  apply (mono_morphism_monomorphic f).\n  rewrite assoc_sym.\n  cbn_rewrite (is_split_monic_left_inverse_is_left_inverse H).\n  auto.\nQed.\n\n(** If both g and (f ∘ g) are monic, then so is f. *)\nProgram Definition Compose_Monic_is_Monic_then_Monic\n           {C : Category}\n           {a b c : C}\n           (M : a –≻ b)\n           (M' : b ≫–> c)\n           (H : is_Monic (M' ∘ M))\n  :\n    Monic a b\n  :=\n    {|\n      mono_morphism := M;\n      mono_morphism_monomorphic := fun d g h H1 => _\n    |}\n.\n\nNext Obligation.\nProof.\n  assert (H2 := f_equal (fun w : d –≻ b => M' ∘ w) H1).\n  cbn in H2.\n  repeat rewrite assoc_sym in H2.\n  apply H; trivial.\nQed.\n\n(** Monomorphisms compose. The case for epis follows by duality.*)\nSection Mono_compose.\n  Context {C : Category} {a b c : C} (M : a ≫–> b) (M' : b ≫–> c).\n\n  Local Hint Resolve mono_morphism_monomorphic.\n\n  Local Obligation Tactic := eauto.\n  \n  Program Definition Mono_compose : a ≫–> c :=\n    {|\n      mono_morphism := M' ∘ M\n    |}.\n    \nEnd Mono_compose.\n\nLocal Open Scope isomorphism_scope.\n\n(** An isomorphism is both monic and epic. *)\nSection Iso_Mono_Epi.\n  Context {C : Category} {a b : Obj} (I : a ≃ b).\n\n  Program Definition Ismorphism_Monic : a ≫–> b :=\n    {|\n      mono_morphism := I\n    |}.\n\n  Next Obligation. (* mono_morphism_monomorphism *)\n  Proof.\n    match goal with\n        [ H : (_ ∘ ?f = _ ∘ ?f')%morphism |- ?f = ?f'] =>\n        match type of H with\n            ?A = ?B =>\n            let H' := fresh \"H\" in\n            cut (I⁻¹ ∘ A = I⁻¹ ∘ B)%morphism; [auto | rewrite H; trivial]\n        end\n    end.\n    repeat rewrite assoc_sym.\n    auto.\n  Qed.\n\n  Program Definition Ismorphism_Epic : b –≫ a :=\n    {|\n      mono_morphism := inverse_morphism I\n    |}.\n  Next Obligation. (* epi_morphism_epimorphism *)\n  Proof.\n    match goal with\n        [ H : (?f ∘ _ = ?f' ∘ _)%morphism |- ?f = ?f'] =>\n        match type of H with\n            ?A = ?B =>\n            let H' := fresh \"H\" in\n            cut (A ∘ I = B ∘ I)%morphism; [auto | rewrite H; trivial]\n        end\n    end.\n    repeat rewrite assoc.\n    auto.\n  Qed.\n\nEnd Iso_Mono_Epi.\n\n(** If two objects are isomorphic in category C then they are also isomorphic\nin C^op. *)\nTheorem CoIso {C : Category} (a b : C) : a ≃≃ b ::> C → a ≃≃ b ::> C^op. \nProof.\n  intros I.\n  eapply (Build_Isomorphism (C^op)%category _ _ (I⁻¹) I);\n    unfold compose; simpl; auto.\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/Categories/Category/Morph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7628082973518789}}
{"text": "Set Warnings \"-notation-overriden,-parsing\".\nRequire Export Poly.\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. rewrite <- eq1. apply eq2. Qed.\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. intros n m o p eq1 eq2. apply eq2. apply eq1. Qed.\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. intros n m eq1 eq2. apply eq2. apply eq1. Qed.\n(** *Exercise silly_ex *)\nTheorem silly_ex:\n  (forall n, evenb n = true -> oddb (S n) = true) ->\n  evenb 3 = true -> oddb 4 = true.\nProof. intros H1 H2. apply H1. apply H2. Qed.\nTheorem silly3_firsttry: forall (n: nat),\n    true = beq_nat n 5 -> beq_nat (S (S n)) 7 = true.\nProof. intros n H. symmetry. simpl. apply H. Qed.\n(** *Exercise apply_exercise1 *)\nTheorem rev_exercise1: forall (l l': list nat),\n    l = rev l' -> l' = rev l.\nProof. intros l l' H. rewrite -> H. symmetry. apply rev_involutive. Qed.\n(** *Exercise apply_rewrite\n    apply is a tool to match the target against a consequent of a statement.\n    rewrite performs substitution if the target and the consequent are\n    equalities. *)\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. intros a b c d e f eq1 eq2. rewrite -> eq1, -> eq2. reflexivity. Qed.\nTheorem trans_eq: forall (X:Type) (n m o:X),\n    n = m -> m = o -> n = o.\nProof. intros X n m o eq1 eq2. rewrite -> eq1, -> eq2. reflexivity. Qed.\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. apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2. Qed.\n(** *Exercise apply_with_exercise *)\nExample trans_eq_exercise: forall n m o p: nat,\n    m = minustwo o -> n + p = m -> 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, S n = S m -> n = m.\nProof. intros n m H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex1: forall n m o: nat,\n    [n;m]=[o;o] -> [n]=[m].\nProof. intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2: forall n m: nat, [n] = [m] -> n = m.\nProof. intros n m H. inversion H as [Hnm]. reflexivity. Qed.\n\n(** *Exercise inversion_ex3 *)\nExample inversion_ex3: forall(X: Type)(x y z: X) (l j: list X),\n    x::y::l = z::j -> y::l = x::j -> x = y.\nProof.\n  intros X x y z  l j eq1 eq2. inversion eq2. reflexivity. Qed.\nTheorem beq_nat_0_l: forall n, beq_nat 0 n = true -> n = 0.\nProof.\n  destruct n as [| n'].\n  - intros H. reflexivity.\n  - simpl. intros H. inversion H. Qed.\nTheorem inversion_ex4: forall n, S n = O -> 2 + 2 = 5.\nProof. intros n contra. inversion contra. Qed.\nTheorem inversion_ex5: forall n m: nat, false = true -> [n] = [m].\nProof. intros n m contra. inversion contra. Qed.\n(** *Exercise inversion_ex6 *)\nExample inversion_ex6: forall(X: Type)(x y z: X)(l j: list X),\n    x::y::l = [] -> y::l=z::j -> x = z.\nProof. intros X x y z l j H. inversion 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), beq_nat (S n) (S m) = b -> beq_nat n m = b.\nProof. intros n m b H. simpl in H. apply H. Qed.\nTheorem silly3': forall n: nat,\n    (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->\n    true = beq_nat n 5 -> true = beq_nat (S (S n)) 7.\nProof.\n  intros n eq H. symmetry in H. apply eq in H. symmetry in H. apply H. Qed.\n(** *Exercise plus_n_n_injectie *)\nTheorem plus_n_n_injective: forall n m, n + n = m + m -> n = m.\nProof.\n  intros n. induction n as [| n' I].\n  - destruct m as [|m'].\n    + intros _. reflexivity.\n    + intros H. inversion H.\n  - intros m H. destruct m as [|m'].\n    + inversion H.\n    + rewrite <- ?plus_n_Sm in H. simpl in H. inversion H as [H'].\n      apply I in H'. rewrite H'. reflexivity. Qed.\n\nTheorem double_injective_FAILED: forall n m, double n = double m -> n = m.\nProof.\n  intros n m. induction n as [|n'].\n  - simpl. intros eq. destruct m as [|m'].\n    + reflexivity.\n    + inversion eq.\n  - intros eq. destruct m as [|m'].\n    + inversion eq.\n    + apply f_equal.\nAbort.\nTheorem double_injective: forall n m, double n = double m -> n = m.\nProof.\n  intros n. induction n as [|n' I].\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 I. inversion eq. reflexivity. Qed.\n(** *Exercise beq_nat_true *)\nTheorem beq_nat_true: forall n m, beq_nat n m = true -> n = m.\nProof.\n  induction n as [|n I].\n  - destruct m as [|m].\n    + reflexivity.\n    + intros c. inversion c.\n  - simpl. destruct m as [|m].\n    + intros c. inversion c.\n    + intros H. apply f_equal. apply I. apply H.\nQed.\n(** *Exercise beq_nat_true_informal\nWe need to prove forall n m, beq_nat n m = true -> n = m.\nProceed by induction on n:\nif n = 0, then forall m, beq_nat 0 m = true -> 0 = m is obvious.\nAssume, forall m, plus n m = true -> n = m. Then for S n we need to prove\nforall m, beq_nat (S n) m = true -> S n = m.\nIt is sufficient to consider m of the form S _, since the antecedent is false\notherwise.\nThus, it simplifies to forall m, beq_nat n m -> n = m, which is the assumption.\n*)\n\nTheorem double_injective_take2: forall n m, double n = double m -> n = m.\nProof.\n  intros n m. generalize dependent n.\n  induction m as [|m']; destruct n as [|n']; intros H.\n  - reflexivity.\n  - inversion H.\n  - inversion H.\n  - apply f_equal. simpl in H. inversion H as [H1]. apply IHm' in H1. exact H1.\nQed.\n\nTheorem beq_id_true: forall x y, beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H': m = n).\n  { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** *Exercise gen_dep_practice *)\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 dependent n.\n  induction l as [|h t I]; intros n H.\n  - reflexivity.\n  - simpl in H. destruct n as [|n].\n    + inversion H.\n    + simpl. apply I. inversion H. reflexivity.\nQed.\n\nDefinition square n := n * n.\nLemma square_mult: forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m. simpl. 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. reflexivity. Qed.\n\nDefinition foo (x: nat) := 5.\nFact silly_fact_1: forall m, foo m + 1 = foo (m+1)+1.\nProof. intros m. simpl. reflexivity. Qed.\nDefinition bar x :=\n  match  x with\n  | O => 5\n  | S _ => 5\n  end.\nFact silly_fact_2_FAILED: forall m, bar m + 1 = bar (m + 1) + 1.\nProof. intros m. simpl. Abort.\nFact silly_fact_2: forall m, bar m + 1 = bar (m + 1) + 1.\nProof. destruct m; reflexivity. Qed.\nFact silly_fact_2': forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m. unfold bar. destruct m; reflexivity. Qed.\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 silly_fun_false: forall(n:nat), sillyfun n = false.\nProof. intros n. unfold sillyfun. destruct (beq_nat n 3).\n       - reflexivity.\n       - destruct (beq_nat n 5); reflexivity.\nQed.\n(** *Exercise combine_split *)\nFixpoint split {X Y: Type} (l: list (X*Y)): (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.\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 I]; intros l1 l2 H.\n  - simpl in H. inversion H. reflexivity.\n  - simpl in H. destruct h as [x y].\n    destruct (split t) as [lx ly]. inversion H. simpl.\n    apply f_equal. apply I. reflexivity.\nQed.\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.\nTheorem sillyfun1_odd_FAILED: forall n:nat,\n    sillyfun1 n = true -> oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3). Abort.\nTheorem sillyfun1_odd: forall n:nat, sillyfun1 n = true -> oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  - apply beq_nat_true in Heqe3. rewrite -> Heqe3. reflexivity.\n  - destruct (beq_nat n 5) eqn:Heqe5.\n    + apply beq_nat_true in Heqe5. rewrite Heqe5. reflexivity.\n    + inversion eq. Qed.\n(** *Exercise destruct_eqn_practice *)\nTheorem bool_fn_applied_thrice:\n  forall (f: bool -> bool) (b: bool), f (f (f b)) = f b.\nProof.\n  intros f b.\n  destruct b eqn:eb; destruct (f true) eqn:eqf1;\n    destruct (f false) eqn:eqf2; rewrite ?eqf1; rewrite ?eqf2;\n      try reflexivity.\nQed.\n\n(** *Exercise beq_nat_sym *)\nTheorem beq_nat_sym: forall n m, beq_nat n m = beq_nat m n.\nProof.\n  induction n as [|n I]; intros m.\n  - simpl. destruct m; reflexivity.\n  - simpl. destruct m.\n    + reflexivity.\n    + simpl. apply I.\nQed.\n\n(** *Exercise beq_nat_sym_informal\nTheorem: for any n m, beq_nat n m = beq_nat m n.\nUse induction on n.\n* First we need to prove for any m, beq_nat 0 m = beq_nat m 0.\n  beq_nat 0 m is true if m is 0 and false if m = S m'. Considering both\n  cases let's reduce beq_nat m 0. So, it follows.\n* Prove for any m, beq_nat (S n') m = beq_nat m (S n'), if we know\n  that for any m, beq_nat n' m = beq_nat m n'.\n  Consider cases for m:\n  * m = 0, then both parts evaluate to false.\n  * m = S m', then beq_nat (S n') (S m') reduces to beq_nat n' m' and\n    beq_nat (S m') (S n') reduces to beq_nat m' n', thus giving the assumption.\n *)\n\n(** *Exercise beq_nat_trans *)\nTheorem beq_nat_trans: forall n m p,\n    beq_nat n m = true -> beq_nat m p = true -> beq_nat n p = true.\nProof.\n  intros n m p H1 H2. apply beq_nat_true in H1. rewrite -> H1. apply H2. Qed.\n\n(** *Exercise split_combine *)\nDefinition split_combine_statement: Prop :=\n  forall (X Y: Type)(l1: list X)(l2: list Y),\n    length l1 = length l2 -> split (combine l1 l2) = (l1,l2).\nTheorem split_combine: split_combine_statement.\nProof.\n  intros X Y. induction l1 as [|h1 t1 I]; intros l2 H.\n  - destruct l2 as [|h2 t2].\n    + reflexivity.\n    + inversion H.\n  - destruct l2 as [|h2 t2].\n    + inversion H.\n    + simpl in H. inversion H as [H']. apply I in H'. simpl.\n      rewrite H'. reflexivity.\nQed.\n\n(** *Exercise filter_exercise *)\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 test x l. induction l as [|h t I]; intros lf H.\n  - inversion H.\n  - simpl in H. destruct (test h) eqn:e.\n    + inversion H as [H']. rewrite H' in e. apply e.\n    + apply I in H. exact H.\nQed.\n\n(** *Exercise forall_exists_challenge *)\nFixpoint forallb {X: Type}(p: X -> bool)(l: list X): bool :=\n  match l with\n  | [] => true\n  | h::t => p h && forallb p t\n  end.\nFixpoint existb {X: Type}(p: X -> bool)(l: list X): bool :=\n  match l with\n  | [] => false\n  | h::t => p h || existb p t\n  end.\n\nExample forallb_test1: forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\nExample forallb_test2: forallb negb [false;false] = true.\nProof. reflexivity. Qed.\nExample forallb_test3: forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\nExample forallb_test4: forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\n\nExample existb_test1: existb (beq_nat 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\nExample existb_test2: existb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\nExample existb_test3: existb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample existb_test4: existb evenb [] = false.\nProof. reflexivity. Qed.\n\nDefinition existb' {X:Type}(p: X -> bool)(l: list X) :=\n  negb (forallb (fun x => negb (p x)) l).\n\nTheorem existb_existb': forall (X: Type)(p: X -> bool)(l: list X),\n    existb p l = existb' p l.\nProof.\n  intros X p. induction l as [|h t I].\n  - reflexivity.\n  - unfold existb'. simpl. destruct (p h) eqn:eqn1; simpl.\n    + reflexivity.\n    + apply I.\nQed.", "meta": {"author": "ia-kamog", "repo": "logical_foundations", "sha": "ce2dd0adcd5a83afd37857cbb9d8ef351cae3106", "save_path": "github-repos/coq/ia-kamog-logical_foundations", "path": "github-repos/coq/ia-kamog-logical_foundations/logical_foundations-ce2dd0adcd5a83afd37857cbb9d8ef351cae3106/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8872045907347108, "lm_q1q2_score": 0.7626976387000787}}
{"text": "Fixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => \n      match m with\n      | O => true\n      | S m' => 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\nDefinition ltb (n m : nat) : bool :=\n  andb (leb n m) (negb (eqb n m)).\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nModule NatList.\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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | [] => 0\n  | x :: xs => \n      match eqb v x with\n      | true => S (count v xs)\n      | false => count v xs\n      end\n  end.\n\nDefinition member (v:nat) (s:bag) : bool := ltb 0 (count v s).\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | [] => []\n  | x :: xs => \n      match eqb x v with\n      | true => xs\n      | false => x :: remove_one v xs\n      end\n  end.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | [] => true\n  | x :: xs => andb (member x s2) (subset xs (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\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\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. \n    rewrite -> IHl1'. \n    reflexivity.\n Qed.\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\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. \n    reflexivity.\n  - (* S n' *)\n    simpl. \n    rewrite IHn'. \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. induction s as [|x xs].\n  -(*[]*) \n    simpl. reflexivity.\n  -(*x :: xs*)\n    simpl. destruct x as [|y].\n    +(*0*)\n      simpl. \n      rewrite leb_n_Sn. \n      reflexivity.\n    +(*S y*)\n      simpl. \n      rewrite IHxs. \n      reflexivity.\nQed.\n\n", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347109, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7626976259406173}}
{"text": " Set Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\n\nDefinition relation(X:Type) := \n  X->X->Prop.\n\nPrint le.\nCheck le.\nCheck le : relation nat.\n\nDefinition partial_function{X:Type}\n  (R:relation X) :=\n  forall x y1 y2 : X, \n  R x y1 -> R x y2 -> y1 = y2.\n\nPrint next_nat.\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 eq1 eq2.\n  inversion eq1.\n  inversion eq2.\n  reflexivity.\n  Qed.\n\nTheorem le_not_a_partial_function :\n  ~(partial_function le).\nProof.\n  unfold not.\n  unfold partial_function.\n  intros eq.\n  assert(0=1) as contra.\n  { apply eq with (x:=0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  inversion contra.\n  Qed.\n\nDefinition reflexive{X:Type}(R:relation X)\n  := forall a:X, R a a.\n\nTheorem le_reflexive: reflexive le.\nProof.\n  unfold reflexive.\n  intros a. apply le_n.\n  Qed.\n\nDefinition transitive{X:Type}(R:relation X)\n  := forall a b c : X, \n  (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans : transitive le.\nProof.\n  unfold transitive.\n  intros a b c eqab eqbc.\n  apply le_trans with (m:=a)(n:=b)(o:=c).\n  - apply eqab.\n  - apply eqbc.\n  Qed.\n\nTheorem lt_trans : transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros a b c Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a:=(S a))(b:=(S b))(c:=c).\n  - apply Hnm.\n  - apply Hmo.\n  Qed.\n\n(* Exercise le_trans_hard_way *)\nTheorem lt_trans': transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [|m' Hm'o].\n  - Print le.\n    apply le_S. apply Hnm.\n  - apply le_S. apply IHHm'o.\n  Qed.\n\n(* Exercise le_S_n *)\nTheorem le_Sn_le: forall n m,\n  S n <= m -> \n  n <= m.\nProof.\n  intros n m eq.\n  apply le_trans with (a:=n)(b:=S n)(c:=m).\n  - apply le_S. apply le_n.\n  - apply eq.\n  Qed.\n\nTheorem le_S_n: forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros n m eq.\n  Search le.\n  apply Sn_le_Sm__n_le_m.\n  apply eq.\n  Qed.\n\n(* Exercise le_Sn_n *)\nTheorem le_Sn_n: forall n,\n  ~(S n <= n).\nProof.\n  unfold not. intros n eq.\n  induction n as [|n' IHn'].\n  - inversion eq.\n  - apply Sn_le_Sm__n_le_m in eq.\n  apply IHn' in eq. apply eq.\n  Qed.\n\nDefinition symmetric{X:Type}(R:relation X)\n  := forall a b : X,\n  (R a b) -> (R b a).\n\n(* Exercise le_not_symmetry *)\nTheorem le_not_symmetric:\n  ~(symmetric le).\nProof. \n  unfold symmetric. unfold not.\n  intros eq. apply eq with (a:=0)(b:=S 0) in eq.\n  - apply le_Sn_n in eq. apply eq.\n  - assert(H:0<=S 0).\n  { apply le_S. apply le_n. }\n  apply eq in H. apply H.\n  Qed.\n\nDefinition antisymmetric{X:Type}(R:relation X)\n  := forall a b : X, \n  (R a b) -> (R b a) -> a = b.\n\n(* Exercise le_antisymmetry *)\nLemma eq_S_n: forall n m,\n  n = m ->\n  S n = S m.\nProof.\n  intros. rewrite H. reflexivity.\n  Qed.\n\nTheorem le_antisymmetric: antisymmetric le.\nProof.\n  unfold antisymmetric.\n  induction a as [|a' IHa'].\n  - intros. inversion H0. reflexivity.\n  - induction b as [|b' IHb'].\n    + intros. inversion H.\n    + intros. apply eq_S_n. apply IHa'.\n      * apply le_S_n. apply H.\n      * apply le_S_n. apply H0.\n  Qed.\n\n(* Exercise 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 m p eqnm eqm.\n  apply le_S_n.  \n  apply le_trans with (a:=S n)(b:=m)(c:=S p).\n  - apply eqnm.\n  - apply eqm.\n  Qed.\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\nTheorem le_order : order le.\nProof. \n  unfold order. split.\n  - apply le_reflexive.\n  - split.\n   + apply le_antisymmetric.\n   + apply le_trans.\n  Qed.\n\n\nInductive clos_refl_trans{A:Type}(R:relation A) \n  : 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. split.\n  - intros H. induction H.\n    + apply rt_refl.\n    + apply rt_trans with m.  \n      * apply IHle.\n      * apply rt_step. apply nn.\n  - intros H. induction H.\n    + inversion H. apply le_S. apply le_n.\n    + apply le_n.\n    + apply le_trans with y.\n      * apply IHclos_refl_trans1.\n      * apply IHclos_refl_trans2.\n  Qed.\n\nInductive clos_refl_trans_ln{A:Type}\n      (R:relation A)(x:A) : A->Prop \n  := \n  | rtln_refl: clos_refl_trans_ln R x x\n  | rtln_trans (y z : A) :\n    R x y -> \n    clos_refl_trans_ln R y z ->\n    clos_refl_trans_ln R x z.\n\nLemma rsc_R : forall (X:Type)(R:relation X)\n  (x y : X),  \n  R x y -> clos_refl_trans_ln R x y.\nProof.\n  intros X R x y H.\n  apply rtln_trans with y.  \n  - apply H.\n  - apply rtln_refl.\n  Qed.\n\n(* Exercise rsc_trans *)\nLemma rsc_trans:\n  forall (X:Type)(R:relation X)(x y z : X),\n    clos_refl_trans_ln R x y ->\n      clos_refl_trans_ln R y z ->\n      clos_refl_trans_ln R x z.\nProof.\n  intros X R x y z eqxy eqyz.\n  induction eqxy.\n  - apply eqyz.\n  - apply IHeqxy in eqyz.\n  apply rtln_trans with y.\n    + apply H.\n    + apply eqyz.\n  Qed.\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_ln R x y.\nProof.\n  intros X R x y. split.\n  - intros eq.\n  induction eq.\n    + apply rtln_trans with y.\n      * apply H.\n      * apply rtln_refl.\n    + apply rtln_refl.\n    + apply rsc_trans with y.\n      * apply IHeq1.\n      * apply IHeq2.\n  - intros eq.\n  induction eq.\n    + apply rt_refl.\n    + apply rt_trans with y.\n      * apply rt_step. apply H.\n      * apply IHeq.\n  Qed.", "meta": {"author": "rpgzysb", "repo": "SoftwareFoundation", "sha": "4f987efcec24d880908edcb4f1c1cd3926c60291", "save_path": "github-repos/coq/rpgzysb-SoftwareFoundation", "path": "github-repos/coq/rpgzysb-SoftwareFoundation/SoftwareFoundation-4f987efcec24d880908edcb4f1c1cd3926c60291/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989810230102, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7626854548050102}}
{"text": "Theorem negation_fn_applied_twice:\n    forall (f : bool -> bool), \n    (forall (x : bool), f x = negb x) -> \n    forall (b : bool), f (f b) = b. \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": "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/negation_fn_applied_twice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7626087452869867}}
{"text": "Require Import Coq.Arith.Arith.\n\n(* from http://adam.chlipala.net/cpdt/html/Cpdt.MoreDep.html *)\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\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\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 => andb (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", "meta": {"author": "samuelgruetter", "repo": "counterexamples", "sha": "bb699361b12687fdc6323759745e75d3bf8720b8", "save_path": "github-repos/coq/samuelgruetter-counterexamples", "path": "github-repos/coq/samuelgruetter-counterexamples/counterexamples-bb699361b12687fdc6323759745e75d3bf8720b8/nunchaku/TaglessInterpreter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.762608739655765}}
{"text": "From LF Require Export Poly.\n\nTheorem silly1: forall (n m o p : nat),\n  n = m -> [n;o] = [n;p] -> [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1. apply eq2. (* Hypothesis and the goal is the same. *)\nQed.\n\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. (* Replace the goal with the predicate of eq2. *)\n  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, even n = true -> odd (S n) = true) ->\n  even 2 = true -> odd 3 = true.\nProof.\n  intros eq1 eq2. apply eq1. apply eq2. Qed\n.\n\nTheorem silly3_firsttry : forall (n : nat),\n  true = (n =? 5) ->\n  (S (S n)) =? 7 = true.\nProof.\n  intros n H. symmetry. (* Swap left and right of the goal. *)\n  simpl. apply H. Qed\n.\n\nTheorem rev_injective : forall (l l' : list nat),\n  rev l = rev l' -> l = l'.\nProof.\n  intros l l' H.\n  rewrite <- rev_involutive. rewrite <- H. symmetry. apply rev_involutive.\nQed.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n  l = rev l' -> l' = rev l.\nProof.\n  intros. rewrite -> H. symmetry. apply rev_involutive.\nQed\n.\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  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity. Qed\n.\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\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  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.\nQed\n.\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  transitivity [c;d]. (* transitivity tactic accomplishes the same purpose as applying trans_eq. *)\n  apply eq1. apply eq2.\nQed\n.\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  transitivity m. apply eq2. apply eq1. Qed\n.\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)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(* Any constructors are injective. *)\n(* injection tactic makes use of injectivity of constructors. *)\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. (* generate all equations that it can infer from H using the injectivity of consturctors. i.e (H: S n = S m) -> (Hnm: n m). *)\n  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 as H1 H2.\n  rewrite H1. rewrite H2. reflexivity. Qed\n.\n\nTheorem injection_ex2 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H.\n  injection H. (* All the equations are turned into hypotheses at the beginning of the goal. *)\n  intros H1 H2. rewrite H1. rewrite H2. reflexivity. Qed\n.\n\nExample inejction_ex3: forall (X: Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j -> j = z :: l -> x = y.\nProof.\n  intros X x y z l j eq1 eq2.\n  injection eq1 as eq11 eq12.\n  assert (H : y :: l = z :: l). {\n    transitivity j.\n    apply eq12. apply eq2.\n  }\n  injection H as H1.\n  rewrite eq11. rewrite H1. reflexivity. Qed\n.\n\nTheorem eqb_0_1 : forall n,\n  0 =? n = true -> n = 0.\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - simpl. intros H. discriminate H. (* principle of explosion *)\nQed.\nTheorem discriminate_ex1 : forall n : nat,\n  S n = O -> 2 + 2 = 5.\nProof.\n  intros n contra.\n  discriminate contra.\nQed.\n\nExample discriminate_ex2: forall n m : nat,\n  false = true -> [n] = [m].\nProof.\n  intros. discriminate H.\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. discriminate H.\nQed\n.\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 A B f x y eq. rewrite eq. reflexivity. Qed\n.\n\nTheorem eq_implies_succ_equal : forall n m : nat,\n  n = m -> S n = S m.\nProof.\n  intros. apply f_equal. apply H. Qed.\n\n(* f_equal tactic: Given the goal f a1 ... an = g b1 ... bn, it produce subgoals f = g, a1 = b1, ..., an = bn. *)\nTheorem eq_implies_succ_equal' : forall n m : nat,\n  n = m -> S n = S m.\nProof.\n  intros n m H.\n  f_equal. apply H. Qed\n.\n\n(* Using Tactics on Hypotheses *)\nTheorem S_inj : forall (n m : nat) (b:bool),\n  (S n) =? (S m) = b -> n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H. Qed\n.\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_FAILED : forall n m,\ndouble n = double m ->\nn = m.\nProof.\nintros n m. induction n as [| n' IHn'].\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. Abort\n.\n\nTheorem double_injective : forall n m,\n  double n = double m ->\n  n = m.\n  Proof.\n  induction n as [| n' IHn'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - simpl. intros m eq. destruct m as [|m'] eqn:E.\n    + discriminate eq.\n    + f_equal. apply IHn'. simpl in eq. injection eq as goal. apply goal.\nQed\n.\n\nTheorem eqb_true : forall n m,\n  n =? m = true -> n = m.\nProof.\n  induction n as [|n' IHn'].\n  - destruct m as [|m'].\n    + reflexivity.\n    + intros H. simpl in H. discriminate H.\n  - destruct m as [|m'].\n    + intros H. simpl in H. discriminate H.\n    + simpl. intros H. apply IHn' in H. rewrite H. reflexivity.\nQed\n.\n\nTheorem plus_n_n_injective : forall n m,\n  n + n = m + m -> n = m.\nProof.\n  induction n as [|n' IHn'].\n  - destruct m as [|m'].\n    + reflexivity.\n    + simpl. intros H. simpl in H. discriminate H.\n  - destruct m as [|m'].\n    + simpl. intros H. discriminate H.\n    + simpl. intros H. injection H as H1. rewrite <- plus_n_Sm in H1. symmetry. rewrite <- plus_n_Sm in H1. injection H1 as H2. apply IHn' in H2. rewrite H2. reflexivity.\nQed.\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' IHm'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - intros eq. destruct n as [|n'] eqn:E.\n    + discriminate eq.\n    + f_equal. Abort\n.\n\nTheorem double_injective_take2 : forall n m,\n  double n = double m ->\n  n = m.\nProof.\n  intros n m. (* Context: n, m: nat, Goal: double n = double m -> n = m *)\n  generalize dependent n. (* Context: m : nat, Goal: forall n : nat, double n = double m -> n = m *)\n  induction m as [| m' IHm'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - intros n eq. destruct n as [|n'] eqn:E.\n    + discriminate eq.\n    + f_equal. apply IHm'. simpl in eq. injection eq as goal. apply goal. Qed\n.\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.\n  generalize dependent n.\n  induction l as [| h t IHl'].\n  - intros H. simpl. reflexivity.\n  - intros n H. simpl in H. simpl. destruct n.\n    + discriminate H.\n    + apply IHl'. injection H as H1. apply H1. Qed\n.\n\n(* Unfolding Definitinos *)\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  simpl.\n  unfold square.\n  rewrite mult_assoc.\n  assert (H: n*m*n = n*n*m). { rewrite mul_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity. Qed\n.\n\n\nDefinition foo (x : nat) := 5.\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\n  Qed\n.\n\nDefinition bar x :=\n  match x with | O => 5 | S _ => 5 end\n.\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\nAbort.\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn: E.\n  - reflexivity.\n  - 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 eqn:E.\n  - reflexivity.\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.\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\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 H.\n  generalize dependent l2.\n  generalize dependent l1.\n  induction l as [|h t IH].\n  - unfold split. simpl. intros l1 l2 H. injection H as H1 H2. rewrite <- H1. rewrite <- H2. reflexivity.\n  - intros l1 l2. destruct h as [x y]. intros H. simpl in H. destruct (split t) as [xt yt]. destruct l1 as [|h1 t1].\n    + discriminate H.\n    + destruct l2 as [|h2 t2].\n      * discriminate H.\n      * simpl. f_equal.\n        ** injection H as H1 H2. rewrite H1. rewrite H. reflexivity.\n        ** apply IH. injection H as H1 H2. rewrite H2. rewrite H0. 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\n  Theorem sillyfun1_odd_FAILED : forall (n : nat),\n  sillyfun1 n = true -> odd n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  - Abort\n.\n\nTheorem sillyfun1_odd : forall (n : nat),\n  sillyfun1 n = true -> odd n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:E.\n  - apply eqb_true in E. rewrite E. reflexivity.\n  - destruct (n =? 5) eqn:E5.\n    + apply eqb_true in E5.\n      rewrite E5. reflexivity.\n    + discriminate eq. Qed\n.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b.\n  destruct (f true) eqn:Et.\n  - destruct (f false) eqn:Ef.\n    + destruct b.\n      * rewrite Et. rewrite Et. rewrite Et. reflexivity.\n      * rewrite Ef. rewrite Et. rewrite Et. reflexivity.\n    + destruct b.\n      * rewrite Et. rewrite Et. rewrite Et. reflexivity.\n      * rewrite Ef. rewrite Ef. rewrite Ef. reflexivity.\n  - destruct (f false) eqn:Ef.\n  + destruct b.\n    * rewrite Et. rewrite Ef. rewrite Et. reflexivity.\n    * rewrite Ef. rewrite Et. rewrite Ef. reflexivity.\n  + destruct b.\n    * rewrite Et. rewrite Ef. rewrite Ef. reflexivity.\n    * rewrite Ef. rewrite Ef. rewrite Ef. reflexivity.\nQed\n.\n\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\n  induction n as [| n' IHn'].\n  - destruct m as [| m'].\n    + reflexivity.\n    + reflexivity.\n  - destruct m as [| m'].\n    + reflexivity.\n    + simpl. apply IHn'.\nQed\n.\n\nTheorem eqb_trans : forall n m p,\n  n =? m = true -> m =? p = true -> n =? p = true.\nProof.\n  intros n m p H1 H2.\n  apply eqb_true in H1. apply eqb_true in H2.\n  rewrite H1. rewrite H2. rewrite eqb_refl. reflexivity.\nQed\n.\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.\n  induction l1 as [| h1 t1 IH1].\n  - simpl. destruct l2 as [| h2 t2].\n    + reflexivity.\n    + simpl. discriminate.\n  - simpl. destruct l2 as [| h2 t2].\n    + simpl. discriminate.\n    + simpl. intro H. injection H as H'. apply IH1 in H'. rewrite H'. reflexivity.\nQed.\n\nFixpoint forallb {X:Type} (test:X->bool) (l:list X) : bool := \n  match l with \n  | nil => true\n  | x::t => match test x with\n    | true => forallb test t\n    | false => false\n  end\n  end\n.\n\nFixpoint existsb {X:Type} (test:X->bool) (l:list X) : bool := \n  match l with \n  | nil => false\n  | x::t => match test x with\n    | true => true\n    | false => existsb test t\n  end\n  end\n.\n\nExample test_forallb_1 : forallb odd [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 even [0;2;4;5] = false.\nProof. reflexivity. Qed.\nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. reflexivity. Qed.\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 odd [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample test_existsb_4 : existsb even [] = 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.\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' odd [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample test_existsb_4' : existsb' even [] = false.\nProof. reflexivity. Qed.\n\nTheorem existsb_existsb' : forall (X:Type) (test:X->bool) (l:list X),\n  existsb test l = existsb' test l.\nProof.\n  induction l as [| h t IHl].\n  - reflexivity.\n  - simpl. destruct (test h) eqn: eq.\n    + unfold existsb'. simpl. rewrite eq. reflexivity.\n    + unfold existsb'. simpl. rewrite eq. simpl. unfold existsb' in IHl. apply IHl.\nQed.\n\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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8740772269642948, "lm_q1q2_score": 0.7624989771091208}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Indprop.\n\nPrint even.\n\nCheck ev_SS.\n\nTheorem ev_4 : even 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': even 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\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\nPrint ev_4.\nPrint ev_4'.\nPrint ev_4''.\nPrint ev_4'''.\n\n(*standard (eight_is_even)*)\nTheorem ev_8 : even 8.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\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_8' : even 8 :=\n  ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n(*/standard (eight_is_even)*)\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 -> 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\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\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\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\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun P Q R (PQ:P/\\Q) (QR:Q/\\R) =>\n    match PQ with\n      | conj HP HQ => match QR with\n                        | conj HQ HR => conj HP HR\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 P Q (PQ:P\\/Q) =>\n    match PQ with\n      | or_introl HP => or_intror HP\n      | or_intror HQ => or_introl HQ\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 => 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\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\nInductive True : Prop :=\n  | I : True.\n\nInductive False : Prop := .\n\nEnd Props.\n\nModule MyEquality.\n\nCheck eq.\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\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), []++[x] == x::[] :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\n(*standard (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. intros. destruct H as [H1]. apply H0. Qed.\n(*/standard (equality__leibniz_equality)*)\n\n (*standard, optional (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 X x y. intros. apply (H (eq x) (eq_refl x)). Qed.\n (*/standard, optional (leibniz_equality__equality)*)\n\nEnd MyEquality.\n\n\n\n\n\n", "meta": {"author": "unisuke82", "repo": "SoftwareFoundation", "sha": "1911ed60b7dff597eac434734cb26d67162b6805", "save_path": "github-repos/coq/unisuke82-SoftwareFoundation", "path": "github-repos/coq/unisuke82-SoftwareFoundation/SoftwareFoundation-1911ed60b7dff597eac434734cb26d67162b6805/volume1/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.762498968387039}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nGoal forall x, (1 <= x)%R -> (0 < x)%R.\nProof.\nintros.\ninterval.\nQed.\n\nGoal forall x, (1 <= x)%R -> (x <= x * x)%R.\nProof.\nintros.\napply Rminus_le.\ninterval with (i_autodiff x, i_prec 10).\nQed.\n\nGoal forall x, (2 <= x)%R -> (x < x * x)%R.\nProof.\nintros.\napply Rminus_lt.\ninterval with (i_autodiff x).\nQed.\n\nGoal forall x, (-1 <= x)%R -> (x < 1 + powerRZ x 3)%R.\nProof.\nintros.\napply Rminus_lt.\ninterval with (i_bisect x, i_autodiff x).\nQed.\n", "meta": {"author": "ejgallego", "repo": "interval", "sha": "6e71cac4a9f2f58a5980ade813f1fcd68d115992", "save_path": "github-repos/coq/ejgallego-interval", "path": "github-repos/coq/ejgallego-interval/interval-6e71cac4a9f2f58a5980ade813f1fcd68d115992/testsuite/example-20120205.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7624902465764437}}
{"text": "Require Import Arith.\n\nFixpoint two_power (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S p => 2 * two_power p\n  end.\n\nEval compute in (two_power 5).\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/structinduct/SRC/two_power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7624680266773843}}
{"text": "(** Examples with Standard Library's vectors  *)\n(** \n \n\nKeywords : vectors, dependent types, dependent elimination *)\n\nRequire Import Bool Arith Vector.\nImport VectorNotations.\n\nArguments cons {A} _ {n}  _ .\nArguments nil {A}.\n\n(** A known problem ... *)\n\nFail\nLemma app_assoc {d e f:nat} {A: Type} :\n  forall (u: t A d)( v : t A e) (w: t A f),\n    (u ++ v) ++ w =  u ++ (v ++ w).\n\n(* So, let us define an equivalence relation *)\n\n\nDefinition equiv {A} {n p : nat} (v: t A n) (w: t A p) :=\n  to_list v = to_list w.\n\nInfix \"==\" := equiv (at level 70) : type_scope.\n\nLemma app_assoc {d e f:nat} {A: Type} :\n  forall (u: t A d)( v : t A e) (w: t A f),\n    (u ++ v) ++ w ==  u ++ (v ++ w).\nProof.\nAdmitted.\n\n(** Plesae define a \"cast\" of the following type *)\n\n\nDefinition cast {A:Type}{n:nat}(v : t A n) : forall n', n = n' -> t A n'.\nAdmitted. (* replace with \"Defined\" *)\n\n(** cast's is correct (w.r.t equiv) *)\n\n\nLemma equiv_cast : forall (A:Type) n (v : t A n) n' (e: n = n'),\n    v == cast v n' e.\nProof.\nAdmitted.\n\n(** equivalence is (almost) equality *)\n\nLemma equiv_eq {A : Type}  : forall n (v w : t A n),\n     v == w -> v = w.\nProof.\nAdmitted.\n\n\nLemma cast_eq {A} {n p} (v : t A n) (w : t A p) (e : n = p):\n   v == w -> w = cast v p e.\nProof.\nAdmitted.\n\n\n(** What is the problem with the following definition ? *)\n\nDefinition add_r {A} n a (v : t A n) : t A (S n) :=\n  cast (v ++ [a]) _ (Nat.add_1_r n).\n\nCompute add_r _ 7 [1;2;3].\n\n(** Please give an alternate definition of add_r which has a correct behaviour\n   (see below) *)\n\n(*\n\nAbout add_r'.\n\nadd_r' : forall (A : Type) (n : nat), A -> t A n -> t A (S n)\n\nArgument A is implicit and maximally inserted\nArgument scopes are [type_scope nat_scope _ _]\nadd_r' is transparent\n                                                    \n\nCompute add_r' _ 7 [1;2;3].\n\n  = [1; 2; 3; 7]\n     : t nat 4\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/texts/vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7624259548708313}}
{"text": "(* We consider the discrete plan the coordinate system of which \n    is based on Z *)\nRequire Import List  ZArith  Bool.\nOpen Scope Z_scope.\nRequire Import Relations  Setoid  Morphisms  RelationClasses.\nRequire Import EMonoid.\nRequire Import Lia.\n\n(** Types for representing routes in the dicrete  plane *)\n\nInductive direction : Type := North | East | South | West.\nDefinition route := list direction.\n\nRecord Point : Type :=\n {Point_x : Z;\n  Point_y : Z}.\n\nDefinition Point_O := Build_Point 0 0.\n\nDefinition translate (dx dy:Z) (P : Point) :=\n  Build_Point (Point_x P + dx) (Point_y P + dy).\n\n(** Equality test  between Points *)\n\nDefinition Point_eqb (P P':Point) :=\n   Zeq_bool (Point_x P) (Point_x P') &&\n   Zeq_bool (Point_y P) (Point_y P').\n\n(* Prove the correctness of Point_eqb *)\n\nLemma Point_eqb_correct : forall p p', Point_eqb p p' = true <->\n                                       p = p'.\nProof.\n destruct p;destruct p';simpl;split.\n -  unfold Point_eqb; simpl; rewrite andb_true_iff; destruct 1.\n    repeat rewrite <- Zeq_is_eq_bool in *.\n    now  rewrite H, H0.\n -  injection 1;intros H0 H1;rewrite H0, H1; unfold Point_eqb; simpl;\n    rewrite andb_true_iff;repeat rewrite <- Zeq_is_eq_bool; now split.\nQed.\n\n(**  (move P r) follows the route r starting from P *)\n\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\nDefinition route_equiv : relation route :=\n  fun r r' => forall P:Point , move r P = move  r' P.\n\nInfix \"=r=\" := route_equiv (at level 70):type_scope.\n\nExample Ex1 : East::North::West::South::East::nil =r= East::nil.\nProof.\n intro P;destruct P;simpl; unfold route_equiv, translate;simpl;f_equal; ring.\nQed.\n\nLemma route_equiv_refl : reflexive _ route_equiv.\nProof.  intros r p;reflexivity. Qed.\n\nLemma route_equiv_sym : symmetric _ route_equiv.\nProof.  intros r r' H p; symmetry;apply H. Qed.\n\nLemma route_equiv_trans : transitive _ route_equiv.\nProof.  intros r r' r'' H H' p; rewrite H; apply H'. Qed.\n\n#[local] Instance route_equiv_Equiv : Equivalence  route_equiv.\nProof.\n  split;\n    [apply route_equiv_refl | apply route_equiv_sym |\n      apply route_equiv_trans].\nQed.\n\n\n(* Cons and app are Proper functions w.r.t. route_equiv *)\n\nLemma route_cons : forall r r' d, r =r= r' -> d::r =r= d::r'.\nProof. \n intros r r' d H P;destruct d;simpl;rewrite H;reflexivity.\nQed.\n\nExample Ex2 :  South::East::North::West::South::East::nil =r= South::East::nil.\nProof. apply route_cons;apply Ex1. Qed.\n\n\n#[local] Instance cons_route_Proper (d:direction): \n    Proper (route_equiv ==> route_equiv) (cons d) .\nProof.\n intros r r' H ; now apply route_cons.\nQed.\n\n\n(**  cons_route_Proper allows to replace a route with an =r= equivalent one\n     in a context composed by \"cons\" *)\n\nExample SW : forall r r', r =r= r' ->\n                  South::West::r =r= South::West::r'.\nProof. \n intros r r' H; now rewrite H.\nQed.\n\n\n#[local] Instance move_Proper  :\n  Proper (route_equiv ==> @eq Point ==> @eq Point) move . \nProof.\n intros r r' Hr_r' p q Hpq; rewrite Hpq; apply Hr_r'.\nQed.\n\nExample length_not_Proper : ~Proper (route_equiv ==> @eq nat) (@length _).\nProof.\n intro H; generalize (H (North::South::nil) nil);simpl;intro H0.\n discriminate H0.\n -  intro P;destruct P; simpl;unfold translate; simpl;f_equal;simpl;ring.\nQed.\n\n\n\nLemma route_compose : 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\n#[local] Instance app_route_Proper :\n  Proper (route_equiv==>route_equiv ==> route_equiv)\n    (@app direction).\nProof.\n intros r r' H r'' r''' H' P.\n repeat rewrite route_compose; rewrite H, H';reflexivity.\nQed.\n\n\nExample Ex3 : forall r, North::East::South::West::r =r= r.\nProof. \n intros r P;destruct P;simpl; \n  unfold route_equiv, translate;simpl;do 2 f_equal;ring.\nQed.\n\nExample Ex4 : forall r r', r =r= r' -> \n                North::East::South::West::r =r= r'.\nProof. intros r r' H. now rewrite Ex3. Qed.\n\nExample Ex5 : forall r r',  r++ North::East::South::West::r' =r= r++r'.\nProof. intros r r'; now rewrite Ex3. Qed.\n\n\nLemma translate_comm : forall dx dy dx' dy' P,\n    translate dx dy (translate dx' dy' P) =\n    translate dx' dy' (translate dx dy P).\nProof.\n  unfold translate; simpl; intros; f_equal; ring.\n Qed.\n\nLemma move_translate : forall r P dx dy , move r (translate dx dy P) =\n                                                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 : forall r r' P  , move r (move r' P)  =\n                                   move r' (move r P) .\nProof.\ninduction 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 *)\n\nLemma route_equiv_Origin : forall r r', r =r= r' <->\n                                        move r Point_O  = move r' Point_O .\nProof.\nsplit;intro H.\n- now rewrite H.\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.\nQed.\n\nDefinition route_eqb r r' : bool :=\n   Point_eqb (move r Point_O) (move r' Point_O).\n\n(**  ... we can now prove route_eqb's  correctness *)\n\nLemma route_equiv_equivb : forall r r', route_equiv r r' <->\n                                        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  *)\n\nExample Ex1' : East::North::West::South::East::nil =r= East::nil.\nProof. route_eq_tac. Qed.\n\nLemma north_south_0 : forall r, North::South::r =r=  r.\nProof.\n intro r; change ((North::South::nil)++ r =r=  r).\n setoid_replace (North :: South :: nil) with  (@nil direction);\n  [reflexivity |route_eq_tac ]. \nQed.\n\nLemma north_south_simpl : forall r r', r++ North::South::r' =r=  r++r'.\nProof.\n induction r as [|a r'];simpl.\n -  intro r';rewrite north_south_0;reflexivity.  \n -  intros r1;now rewrite IHr' .\nQed.\n\n\n(* we want to prove that, if some route contains two steps in opposite\n   directions, then the route can be shortened *)\n\nDefinition opposite (d d':direction):= match d,d' with \n        | North,South => True\n        | South, North => True\n        | East, West => True\n        | West, East => True\n        | _, _ => False\nend.\n\n\nInductive  Useless_steps_in (r:route) : Type :=\nUseless_i: forall r0 r1 r2 d d1,  r = r0++(d::r1)++(d1::r2) ->\n                                  opposite d d1 ->\n                                  Useless_steps_in r.\n\nLemma opposite_cons : forall d d1 r, opposite d d1 -> d1::d::r =r= r.\nProof.\n intros d d1 r H;destruct d,d1;simpl ;try contradiction ;\n intro P;destruct P;simpl;auto; unfold translate;simpl; repeat f_equal;ring.\nQed.\n\nLemma cons2_comm : forall d d' r, d::d'::r =r= d'::d::r.\nProof.\n intros d d' r; change ((d::nil)++(d'::nil)++r =r= (d'::nil)++(d::nil)++r).\n do 2  rewrite <- app_ass.\n rewrite (app_comm  (d :: nil) (d'::nil));reflexivity.\nQed.\n\n\nLemma Useless_steps_shorter (r:route) :\n  Useless_steps_in r -> {r' : route | r =r= r' /\\ (length r' < length r)%nat}.\nProof.\n intro H;destruct H as [r0 r1 r2 d d1 H1 H2]. \n exists (r0 ++ r1 ++ r2).\n split.\n -  subst r; replace (r0 ++ (d :: r1) ++ d1 :: r2) with\n         (r0 ++ ((d::nil) ++ r1) ++ ((d1::nil)++r2))  by (simpl;auto).\n     apply app_route_Proper;[reflexivity|].\n     rewrite <- app_ass.\n     apply app_route_Proper;[|reflexivity].\n     transitivity ((d1::nil)++(d::r1)).\n     rewrite app_comm; reflexivity.\n      simpl;rewrite opposite_cons;[reflexivity|trivial].\n -  subst r; repeat (simpl;repeat  rewrite app_length); lia.\nQed.\n\n\n(** Monoid structure on routes *)\n\n#[local] Instance Route : EMonoid route_equiv (@app _)  nil .\nProof.\nsplit.\n- apply route_equiv_Equiv.\n- apply app_route_Proper.\n- intros x y z P;repeat rewrite  route_compose; trivial.\n-  intros x  P;repeat rewrite  route_compose; trivial.\n- intros x  P;repeat rewrite  route_compose; trivial.\nQed.\n\nExample Ex6 : forall n, Epower (South::North::nil) n =r= nil.\nProof. \n induction n as [| p IHp];simpl;[reflexivity|].\n rewrite IHp; route_eq_tac.\nQed.\n\n#[local] Instance AbelianRoute : Abelian_EMonoid Route. \n  split;  apply app_comm.\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/tutorial_type_classes/SRC/Lost_in_NY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7624259531435882}}
{"text": "(** * 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 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     - From the command line:\n\n         [coqc Basics.v]\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') + 0 = S n'], which simplifies to\n    [S (n' + 0) = 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  (* FILL IN HERE *) Admitted.\n\nTheorem plus_n_Sm : forall n m : nat, \n  S (n + m) = n + (S m).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_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 (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 the\n    recursive call on [n - 2]. This makes proofs about [evenb n]\n    harder when done by induction on [n], since we may need an\n    induction hypothesis about [n - 2]. The following lemma gives an\n    alternative characterization of [evenb (S n)] that works better\n    with induction: *)\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\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(** 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: (* 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(* ################################################################# *)\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  (* FILL IN HERE *) Admitted.\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                            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\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\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2016-09-10 06:26:08 +0900 (2016年09月10日 (土)) $ *)\n", "meta": {"author": "hkrsnd", "repo": "coq", "sha": "199cec72dd10c5b08b32f4bd14679a1b544d758f", "save_path": "github-repos/coq/hkrsnd-coq", "path": "github-repos/coq/hkrsnd-coq/coq-199cec72dd10c5b08b32f4bd14679a1b544d758f/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8991213799730774, "lm_q1q2_score": 0.7624259514488063}}
{"text": "Require Import RelationClasses.\nRequire Import Relations Morphisms.\nRequire Import String.\n\nSet Implicit Arguments.\n\n(** ** The [Monoid] type class (with Operational Type Classes) *)\n\n\nDeclare Scope M_scope.\n\n(* begin snippet MultOpClass *)\nClass Mult_op (A:Type) := mult_op : A -> A -> A.\n\n\nPrint Mult_op.\n(* end snippet MultOpClass *)\n\nPrint mult_op.\n\n(* begin snippet MultOpEq:: no-out *)\n\nGoal forall A (op: Mult_op A), @mult_op A op = op.\nreflexivity.\nQed.\n(* end snippet MultOpEq *)\n\n(* begin snippet MultOpInfix *)\nDelimit Scope M_scope with M.\nInfix \"*\" := mult_op : M_scope.\nOpen Scope M_scope.\n(* end snippet MultOpInfix *)\n\n(* begin snippet DemoNatMulta *)\n\nModule Demo.\n  \n  #[local] Instance nat_mult_op : Mult_op nat := Nat.mul.\n  (* end snippet DemoNatMulta *)\n\n(* begin snippet DemoNatMultb *)\n  Set Printing All.\n\n  Check 3 * 4.\n\n   Unset Printing All.\n\n   Compute 3 * 4.\n\nEnd Demo.\n(* end snippet DemoNatMultb *)\n\n(* begin snippet DemoStringMult:: no-out *)\n\n#[ global ] Instance string_op : Mult_op string := append.\nOpen Scope string_scope.\n\nExample ex_string : \"ab\" * \"cde\" = \"abcde\".\nProof. reflexivity. Qed.\n\n(* end snippet DemoStringMult *)\n\n\n#[ global ] Instance bool_and_binop : Mult_op bool := andb.\n\nExample ex_bool : true * false = false.\nProof. reflexivity. Qed.\n\n(*\n\nmult_op : forall (A : Type) (_ : Mult_op A) (_ : A) (_ : A), A\n\nArguments A, Mult_op are implicit and maximally inserted\n*)\n(** within M_scope, a term of the form (x * y) is an abbreviation of\n(mult_op A op x y) where op : Mult_op A and x, y : A.\n*)\n\n(* begin snippet MonoidClass *)\nClass Monoid {A:Type}(op : Mult_op A)(one : A) : Prop :=\n{\n    op_assoc : forall x y z, x * (y * z) = x * y * z;\n    one_left : forall x, one * x = x;\n    one_right : forall x, x * one = x\n}.\n(* end snippet MonoidClass *)\n\n(** *** Exercice\n\nDefine a class for semi-groups, and re-define monoids as semi-groups with a neutral element\n\n*)\n\n\n\n(** *** Monoids and Equivalence Relations \n\nIn some situations, the previous definition may be too restrictive.\nFor instance, consider the computation of  $x^n \\mod{m}$ where\n$x$ and $m$ are positive integers, and $1<m$.\n\nAlthough it could possible to compute with values of the dependent \ntype %\\linebreak% [{n:N | n < m}], it looks simpler to compute with numbers of type\n[N], and consider the multiplication $x \\times y \\mod{m}$.\n\nIt is easy to prove that this operation is associative, using library\n %\\texttt{NArith}%. Unfortunately, it is not possible to prove the \nfollowing proposition,\nrequired for building an instance of [Monoid]:\n\n[[\nforall x:N, 1 * x  mod m = x.\n]]\n\nThus, we define a more general class, parameterized by an equivalence\nrelation [Aeq] on type [A], compatible with the multiplication $\\bullet$. \nThe laws of associativity and neutral element\nare not expressed as Leibniz equalities but as equivalence statements:\n*)\n\n(* begin snippet EquivDef *)\nClass Equiv A := equiv : relation A.\n\nInfix \"==\" := equiv (at level 70) : type_scope.\n(* end snippet EquivDef *)\n\n(*\nequiv : forall A : Type, Equiv A -> relation A\n*)\n(* begin snippet EMonoidDef *)\n\nClass EMonoid (A:Type)(E_op : Mult_op A)(E_one : A) \n      (E_eq: Equiv A): Prop :=\n  {\n    Eq_equiv :> Equivalence equiv;\n    Eop_proper : Proper (equiv ==> equiv ==> equiv) E_op;\n    Eop_assoc : forall x y z, x * (y * z) == x * y * z;\n    Eone_left : forall x,  E_one * x == x;\n    Eone_right : forall x,  x * E_one ==  x\n  }.\n(* end snippet EMonoidDef *)\n\n\n#[ global ] Instance Equiv_Equiv (A:Type)(E_op : Mult_op A)(E_one : A) \n      (E_eq: Equiv A)(M :EMonoid E_op E_one E_eq) :\n   Equivalence E_eq.\ndestruct M;auto.\nQed.\n\n#[ global ] Instance Equiv_Refl (A:Type)(E_op : Mult_op A)(E_one : A) \n      (E_eq: Equiv A)(M :EMonoid E_op E_one E_eq) :\n   Reflexive E_eq.\ndestruct (Equiv_Equiv   M);auto.\nQed.\n\n#[ global ] Instance Equiv_Sym (A:Type)(E_op : Mult_op A)(E_one : A) \n      (E_eq: Equiv A)(M :EMonoid E_op E_one E_eq) :\n   Symmetric E_eq.\ndestruct (Equiv_Equiv   M);auto.\nQed.\n\n#[ global ] Instance Equiv_Trans (A:Type)(E_op : Mult_op A)(E_one : A) \n      (E_eq: Equiv A)(M :EMonoid E_op E_one E_eq) :\n   Transitive E_eq.\ndestruct (Equiv_Equiv   M);auto.\nQed.\n\n\n\n\nGeneralizable All Variables.\n\n\n(** *** Coercion from Monoid to EMonoid \n\nEvery instance of class  [Monoid] can be transformed into an instance of\n[EMonoid], considering Leibniz' equality [eq].\n*)\n\n(* begin snippet Coerciona:: no-out  *)\n#[global] Instance eq_equiv {A} : Equiv A := eq.\n\n#[global] Instance Monoid_EMonoid `(M:@Monoid A op one) :\n        EMonoid  op one eq_equiv.\nProof.\nsplit; unfold eq_equiv, equiv in *.\n - apply eq_equivalence.\n - intros x y H z t H0;  now subst.\n - intros;now rewrite (op_assoc).\n - intro; now rewrite one_left.\n - intro;now rewrite one_right.\nQed.\n(* end snippet Coerciona  *)\n\n(** We can now register [Monoid_EMonoid] as a _coercion_:\n*)\n\n(* begin snippet Coercionb:: no-out  *)\nCoercion Monoid_EMonoid : Monoid >-> EMonoid.\n(* end snippet Coercionb  *)\n\n(** *** Commutative Monoids \n\nThe following type class definitions allow to take advantage of\n  the possible commutativity of the $\\bullet$ operation \n \n*)\n\nClass Abelian_EMonoid `(M:@EMonoid A op one Aeq ):= {\n  Eop_comm : forall x y, op x  y ==  op y  x}.\n\n\nClass Abelian_Monoid `(M:Monoid ):= {\n  op_comm : forall x y, op x  y = op y  x}.\n\n\nLtac add_op_proper M H := \n let h := fresh H in\n   generalize (@Eop_proper _ _ _ _ M); intro h.\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_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7624259434099792}}
{"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 (Trunc convention)\n\n    We use here the convention known as Trunc, or Round-Toward-Zero,\n    where [a/b] is the integer with the largest absolute value to\n    be between zero and the exact fraction. It can be summarized by:\n\n    [a = bq+r /\\ 0 <= |r| < |b| /\\ Sign(r) = Sign(a)]\n\n    This is the convention of Ocaml and many other systems (C, ASM, ...).\n    This convention is named \"T\" 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 [ZDivFloor] and [ZDivEucl] for others conventions.\n*)\n\nModule Type ZQuotProp\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 *)\n\n Module Import Private_Div.\n Module Quot2Div <: NZDiv A.\n  Definition div := quot.\n  Definition modulo := A.rem.\n  Definition div_wd := quot_wd.\n  Definition mod_wd := rem_wd.\n  Definition div_mod := quot_rem.\n  Definition mod_bound_pos := rem_bound_pos.\n End Quot2Div.\n Module NZQuot := Nop <+ NZDivProp A Quot2Div B.\n End Private_Div.\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(** Another formulation of the main equation *)\n\nLemma rem_eq :\n forall a b, b~=0 -> a rem b == a - b*(a÷b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply quot_rem.\nQed.\n\n(** A few sign rules (simple ones) *)\n\nLemma rem_opp_opp : forall a b, b ~= 0 -> (-a) rem (-b) == - (a rem b).\nProof. intros. now rewrite rem_opp_r, rem_opp_l. Qed.\n\nLemma quot_opp_l : forall a b, b ~= 0 -> (-a)÷b == -(a÷b).\nProof.\nintros.\nrewrite <- (mul_cancel_l _ _ b) by trivial.\nrewrite <- (add_cancel_r _ _ ((-a) rem b)).\nnow rewrite <- quot_rem, rem_opp_l, mul_opp_r, <- opp_add_distr, <- quot_rem.\nQed.\n\nLemma quot_opp_r : forall a b, b ~= 0 -> a÷(-b) == -(a÷b).\nProof.\nintros.\nassert (-b ~= 0) by (now rewrite eq_opp_l, opp_0).\nrewrite <- (mul_cancel_l _ _ (-b)) by trivial.\nrewrite <- (add_cancel_r _ _ (a rem (-b))).\nnow rewrite <- quot_rem, rem_opp_r, mul_opp_opp, <- quot_rem.\nQed.\n\nLemma quot_opp_opp : forall a b, b ~= 0 -> (-a)÷(-b) == a÷b.\nProof. intros. now rewrite quot_opp_r, quot_opp_l, opp_involutive. Qed.\n\n(** Uniqueness theorems *)\n\nTheorem quot_rem_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 NZQuot.div_mod_unique with b; trivial.\nrewrite <- (opp_inj_wd r1 r2).\napply NZQuot.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 quot_unique:\n forall a b q r, 0<=a -> 0<=r<b -> a == b*q + r -> q == a÷b.\nProof. intros; now apply NZQuot.div_unique with r. Qed.\n\nTheorem rem_unique:\n forall a b q r, 0<=a -> 0<=r<b -> a == b*q + r -> r == a rem b.\nProof. intros; now apply NZQuot.mod_unique with q. Qed.\n\n(** A division by itself returns 1 *)\n\nLemma quot_same : forall a, a~=0 -> a÷a == 1.\nProof.\nintros. pos_or_neg a. apply NZQuot.div_same; order.\nrewrite <- quot_opp_opp by trivial. now apply NZQuot.div_same.\nQed.\n\nLemma rem_same : forall a, a~=0 -> a rem a == 0.\nProof.\nintros. rewrite rem_eq, quot_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem quot_small: forall a b, 0<=a<b -> a÷b == 0.\nProof. exact NZQuot.div_small. Qed.\n\n(** Same situation, in term of remulo: *)\n\nTheorem rem_small: forall a b, 0<=a<b -> a rem b == a.\nProof. exact NZQuot.mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma quot_0_l: forall a, a~=0 -> 0÷a == 0.\nProof.\nintros. pos_or_neg a. apply NZQuot.div_0_l; order.\nrewrite <- quot_opp_opp, opp_0 by trivial. now apply NZQuot.div_0_l.\nQed.\n\nLemma rem_0_l: forall a, a~=0 -> 0 rem a == 0.\nProof.\nintros; rewrite rem_eq, quot_0_l; now nzsimpl.\nQed.\n\nLemma quot_1_r: forall a, a÷1 == a.\nProof.\nintros. pos_or_neg a. now apply NZQuot.div_1_r.\napply opp_inj. rewrite <- quot_opp_l. apply NZQuot.div_1_r; order.\nintro EQ; symmetry in EQ; revert EQ; apply lt_neq, lt_0_1.\nQed.\n\nLemma rem_1_r: forall a, a rem 1 == 0.\nProof.\nintros. rewrite rem_eq, quot_1_r; nzsimpl; auto using sub_diag.\nintro EQ; symmetry in EQ; revert EQ; apply lt_neq; apply lt_0_1.\nQed.\n\nLemma quot_1_l: forall a, 1<a -> 1÷a == 0.\nProof. exact NZQuot.div_1_l. Qed.\n\nLemma rem_1_l: forall a, 1<a -> 1 rem a == 1.\nProof. exact NZQuot.mod_1_l. Qed.\n\nLemma quot_mul : forall a b, b~=0 -> (a*b)÷b == a.\nProof.\nintros. pos_or_neg a; pos_or_neg b. apply NZQuot.div_mul; order.\nrewrite <- quot_opp_opp, <- mul_opp_r by order. apply NZQuot.div_mul; order.\nrewrite <- opp_inj_wd, <- quot_opp_l, <- mul_opp_l by order.\napply NZQuot.div_mul; order.\nrewrite <- opp_inj_wd, <- quot_opp_r, <- mul_opp_opp by order.\napply NZQuot.div_mul; order.\nQed.\n\nLemma rem_mul : forall a b, b~=0 -> (a*b) rem b == 0.\nProof.\nintros. rewrite rem_eq, quot_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\nTheorem quot_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 quot_mul.\nQed.\n\n(** The sign of [a rem b] is the one of [a] (when it's not null) *)\n\nLemma rem_nonneg : forall a b, b~=0 -> 0 <= a -> 0 <= a rem b.\nProof.\n intros. pos_or_neg b. destruct (rem_bound_pos a b); order.\n rewrite <- rem_opp_r; trivial.\n destruct (rem_bound_pos a (-b)); trivial.\nQed.\n\nLemma rem_nonpos : forall a b, b~=0 -> a <= 0 -> a rem b <= 0.\nProof.\n intros a b Hb Ha.\n apply opp_nonneg_nonpos. apply opp_nonneg_nonpos in Ha.\n rewrite <- rem_opp_l by trivial. now apply rem_nonneg.\nQed.\n\nLemma rem_sign_mul : forall a b, b~=0 -> 0 <= (a rem b) * a.\nProof.\nintros a b Hb. destruct (le_ge_cases 0 a).\n apply mul_nonneg_nonneg; trivial. now apply rem_nonneg.\n apply mul_nonpos_nonpos; trivial. now apply rem_nonpos.\nQed.\n\nLemma rem_sign_nz : forall a b, b~=0 -> a rem b ~= 0 ->\n sgn (a rem b) == sgn a.\nProof.\nintros a b Hb H. destruct (lt_trichotomy 0 a) as [LT|[EQ|LT]].\nrewrite 2 sgn_pos; try easy.\n generalize (rem_nonneg a b Hb (lt_le_incl _ _ LT)). order.\nnow rewrite <- EQ, rem_0_l, sgn_0.\nrewrite 2 sgn_neg; try easy.\n generalize (rem_nonpos a b Hb (lt_le_incl _ _ LT)). order.\nQed.\n\nLemma rem_sign : forall a b, a~=0 -> b~=0 -> sgn (a rem b) ~= -sgn a.\nProof.\nintros a b Ha Hb H.\ndestruct (eq_decidable (a rem b) 0) as [EQ|NEQ].\napply Ha, sgn_null_iff, opp_inj. now rewrite <- H, opp_0, EQ, sgn_0.\napply Ha, sgn_null_iff. apply eq_mul_0_l with 2; try order'. nzsimpl'.\napply add_move_0_l. rewrite <- H. symmetry. now apply rem_sign_nz.\nQed.\n\n(** Operations and absolute value *)\n\nLemma rem_abs_l : forall a b, b ~= 0 -> (abs a) rem b == abs (a rem b).\nProof.\nintros a b Hb. destruct (le_ge_cases 0 a) as [LE|LE].\nrewrite 2 abs_eq; try easy. now apply rem_nonneg.\nrewrite 2 abs_neq, rem_opp_l; try easy. now apply rem_nonpos.\nQed.\n\nLemma rem_abs_r : forall a b, b ~= 0 -> a rem (abs b) == a rem b.\nProof.\nintros a b Hb. destruct (le_ge_cases 0 b).\nnow rewrite abs_eq. now rewrite abs_neq, ?rem_opp_r.\nQed.\n\nLemma rem_abs : forall a b,  b ~= 0 -> (abs a) rem (abs b) == abs (a rem b).\nProof.\nintros. now rewrite rem_abs_r, rem_abs_l.\nQed.\n\nLemma quot_abs_l : forall a b, b ~= 0 -> (abs a)÷b == (sgn a)*(a÷b).\nProof.\nintros a b Hb. destruct (lt_trichotomy 0 a) as [LT|[EQ|LT]].\nrewrite abs_eq, sgn_pos by order. now nzsimpl.\nrewrite <- EQ, abs_0, quot_0_l; trivial. now nzsimpl.\nrewrite abs_neq, quot_opp_l, sgn_neg by order.\n rewrite mul_opp_l. now nzsimpl.\nQed.\n\nLemma quot_abs_r : forall a b, b ~= 0 -> a÷(abs b) == (sgn b)*(a÷b).\nProof.\nintros a b Hb. destruct (lt_trichotomy 0 b) as [LT|[EQ|LT]].\nrewrite abs_eq, sgn_pos by order. now nzsimpl.\norder.\nrewrite abs_neq, quot_opp_r, sgn_neg by order.\n rewrite mul_opp_l. now nzsimpl.\nQed.\n\nLemma quot_abs : forall a b, b ~= 0 -> (abs a)÷(abs b) == abs (a÷b).\nProof.\nintros a b Hb.\npos_or_neg a; [rewrite (abs_eq a)|rewrite (abs_neq a)];\n try apply opp_nonneg_nonpos; try order.\npos_or_neg b; [rewrite (abs_eq b)|rewrite (abs_neq b)];\n try apply opp_nonneg_nonpos; try order.\nrewrite abs_eq; try easy. apply NZQuot.div_pos; order.\nrewrite <- abs_opp, <- quot_opp_r, abs_eq; try easy.\n apply NZQuot.div_pos; order.\npos_or_neg b; [rewrite (abs_eq b)|rewrite (abs_neq b)];\n try apply opp_nonneg_nonpos; try order.\nrewrite <- (abs_opp (_÷_)), <- quot_opp_l, abs_eq; try easy.\n apply NZQuot.div_pos; order.\nrewrite <- (quot_opp_opp a b), abs_eq; try easy.\n apply NZQuot.div_pos; order.\nQed.\n\n(** We have a general bound for absolute values *)\n\nLemma rem_bound_abs :\n forall a b, b~=0 -> abs (a rem b) < abs b.\nProof.\nintros. rewrite <- rem_abs; trivial.\napply rem_bound_pos. apply abs_nonneg. now apply abs_pos.\nQed.\n\n(** * Order results about rem and quot *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem rem_le: forall a b, 0<=a -> 0<b -> a rem b <= a.\nProof. exact NZQuot.mod_le. Qed.\n\nTheorem quot_pos : forall a b, 0<=a -> 0<b -> 0<= a÷b.\nProof. exact NZQuot.div_pos. Qed.\n\nLemma quot_str_pos : forall a b, 0<b<=a -> 0 < a÷b.\nProof. exact NZQuot.div_str_pos. Qed.\n\nLemma quot_small_iff : forall a b, b~=0 -> (a÷b==0 <-> abs a < abs b).\nProof.\nintros. pos_or_neg a; pos_or_neg b.\nrewrite NZQuot.div_small_iff; try order. rewrite 2 abs_eq; intuition; order.\nrewrite <- opp_inj_wd, opp_0, <- quot_opp_r, NZQuot.div_small_iff by order.\n rewrite (abs_eq a), (abs_neq' b); intuition; order.\nrewrite <- opp_inj_wd, opp_0, <- quot_opp_l, NZQuot.div_small_iff by order.\n rewrite (abs_neq' a), (abs_eq b); intuition; order.\nrewrite <- quot_opp_opp, NZQuot.div_small_iff by order.\n rewrite (abs_neq' a), (abs_neq' b); intuition; order.\nQed.\n\nLemma rem_small_iff : forall a b, b~=0 -> (a rem b == a <-> abs a < abs b).\nProof.\nintros. rewrite rem_eq, <- quot_small_iff by order.\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 quot_lt : forall a b, 0<a -> 1<b -> a÷b < a.\nProof. exact NZQuot.div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma quot_le_mono : forall a b c, 0<c -> a<=b -> a÷c <= b÷c.\nProof.\nintros. pos_or_neg a. apply NZQuot.div_le_mono; auto.\npos_or_neg b. apply le_trans with 0.\n rewrite <- opp_nonneg_nonpos, <- quot_opp_l by order.\n apply quot_pos; order.\n apply quot_pos; order.\nrewrite opp_le_mono in *. rewrite <- 2 quot_opp_l by order.\n apply NZQuot.div_le_mono; intuition; order.\nQed.\n\n(** With this choice of division,\n    rounding of quot is always done toward zero: *)\n\nLemma mul_quot_le : forall a b, 0<=a -> b~=0 -> 0 <= b*(a÷b) <= a.\nProof.\nintros. pos_or_neg b.\nsplit.\napply mul_nonneg_nonneg; [|apply quot_pos]; order.\napply NZQuot.mul_div_le; order.\nrewrite <- mul_opp_opp, <- quot_opp_r by order.\nsplit.\napply mul_nonneg_nonneg; [|apply quot_pos]; order.\napply NZQuot.mul_div_le; order.\nQed.\n\nLemma mul_quot_ge : forall a b, a<=0 -> b~=0 -> a <= b*(a÷b) <= 0.\nProof.\nintros.\nrewrite <- opp_nonneg_nonpos, opp_le_mono, <-mul_opp_r, <-quot_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\ndestruct (mul_quot_le (-a) b); tauto.\nQed.\n\n(** For positive numbers, considering [S (a÷b)] leads to an upper bound for [a] *)\n\nLemma mul_succ_quot_gt: forall a b, 0<=a -> 0<b -> a < b*(S (a÷b)).\nProof. exact NZQuot.mul_succ_div_gt. Qed.\n\n(** Similar results with negative numbers *)\n\nLemma mul_pred_quot_lt: forall a b, a<=0 -> 0<b -> b*(P (a÷b)) < a.\nProof.\nintros.\nrewrite opp_lt_mono, <- mul_opp_r, opp_pred, <- quot_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\nnow apply mul_succ_quot_gt.\nQed.\n\nLemma mul_pred_quot_gt: forall a b, 0<=a -> b<0 -> a < b*(P (a÷b)).\nProof.\nintros.\nrewrite <- mul_opp_opp, opp_pred, <- quot_opp_r by order.\nrewrite <- opp_pos_neg in *.\nnow apply mul_succ_quot_gt.\nQed.\n\nLemma mul_succ_quot_lt: forall a b, a<=0 -> b<0 -> b*(S (a÷b)) < a.\nProof.\nintros.\nrewrite opp_lt_mono, <- mul_opp_l, <- quot_opp_opp by order.\nrewrite <- opp_nonneg_nonpos, <- opp_pos_neg in *.\nnow apply mul_succ_quot_gt.\nQed.\n\n(** Inequality [mul_quot_le] is exact iff the modulo is zero. *)\n\nLemma quot_exact : forall a b, b~=0 -> (a == b*(a÷b) <-> a rem b == 0).\nProof.\nintros. rewrite rem_eq by order. rewrite sub_move_r; nzsimpl; tauto.\nQed.\n\n(** Some additional inequalities about quot. *)\n\nTheorem quot_lt_upper_bound:\n  forall a b q, 0<=a -> 0<b -> a < b*q -> a÷b < q.\nProof. exact NZQuot.div_lt_upper_bound. Qed.\n\nTheorem quot_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a÷b <= q.\nProof.\nintros.\nrewrite <- (quot_mul q b) by order.\napply quot_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem quot_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a÷b.\nProof.\nintros.\nrewrite <- (quot_mul q b) by order.\napply quot_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma quot_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p÷r <= p÷q.\nProof. exact NZQuot.div_le_compat_l. Qed.\n\n(** * Relations between usual operations and rem and quot *)\n\n(** Unlike with other division conventions, some results here aren't\n    always valid, and need to be restricted. For instance\n    [(a+b*c) rem c <> a rem c] for [a=9,b=-5,c=2] *)\n\nLemma rem_add : forall a b c, c~=0 -> 0 <= (a+b*c)*a ->\n (a + b * c) rem c == a rem c.\nProof.\nassert (forall a b c, c~=0 -> 0<=a -> 0<=a+b*c -> (a+b*c) rem c == a rem c).\n intros. pos_or_neg c. apply NZQuot.mod_add; order.\n rewrite <- (rem_opp_r a), <- (rem_opp_r (a+b*c)) by order.\n rewrite <- mul_opp_opp in *.\n apply NZQuot.mod_add; order.\nintros a b c Hc Habc.\ndestruct (le_0_mul _ _ Habc) as [(Habc',Ha)|(Habc',Ha)]. auto.\napply opp_inj. revert Ha Habc'.\nrewrite <- 2 opp_nonneg_nonpos.\nrewrite <- 2 rem_opp_l, opp_add_distr, <- mul_opp_l by order. auto.\nQed.\n\nLemma quot_add : forall a b c, c~=0 -> 0 <= (a+b*c)*a ->\n (a + b * c) ÷ c == a ÷ c + b.\nProof.\nintros.\nrewrite <- (mul_cancel_l _ _ c) by trivial.\nrewrite <- (add_cancel_r _ _ ((a+b*c) rem c)).\nrewrite <- quot_rem, rem_add by trivial.\nnow rewrite mul_add_distr_l, add_shuffle0, <-quot_rem, mul_comm.\nQed.\n\nLemma quot_add_l: forall a b c, b~=0 -> 0 <= (a*b+c)*c ->\n (a * b + c) ÷ b == a + c ÷ b.\nProof.\n intros a b c. rewrite add_comm, (add_comm a). now apply quot_add.\nQed.\n\n(** Cancellations. *)\n\nLemma quot_mul_cancel_r : forall a b c, b~=0 -> c~=0 ->\n (a*c)÷(b*c) == a÷b.\nProof.\nassert (Aux1 : forall a b c, 0<=a -> 0<b -> c~=0 -> (a*c)÷(b*c) == a÷b).\n intros. pos_or_neg c. apply NZQuot.div_mul_cancel_r; order.\n rewrite <- quot_opp_opp, <- 2 mul_opp_r. apply NZQuot.div_mul_cancel_r; order.\n rewrite <- neq_mul_0; intuition order.\nassert (Aux2 : forall a b c, 0<=a -> b~=0 -> c~=0 -> (a*c)÷(b*c) == a÷b).\n intros. pos_or_neg b. apply Aux1; order.\n apply opp_inj. rewrite <- 2 quot_opp_r, <- mul_opp_l; try order. apply Aux1; order.\n rewrite <- neq_mul_0; intuition order.\nintros. pos_or_neg a. apply Aux2; order.\napply opp_inj. rewrite <- 2 quot_opp_l, <- mul_opp_l; try order. apply Aux2; order.\nrewrite <- neq_mul_0; intuition order.\nQed.\n\nLemma quot_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 quot_mul_cancel_r.\nQed.\n\nLemma mul_rem_distr_r: forall a b c, b~=0 -> c~=0 ->\n  (a*c) rem (b*c) == (a rem b) * c.\nProof.\nintros.\nassert (b*c ~= 0) by (rewrite <- neq_mul_0; tauto).\nrewrite ! rem_eq by trivial.\nrewrite quot_mul_cancel_r by order.\nnow rewrite mul_sub_distr_r, <- !mul_assoc, (mul_comm (a÷b) c).\nQed.\n\nLemma mul_rem_distr_l: forall a b c, b~=0 -> c~=0 ->\n  (c*a) rem (c*b) == c * (a rem b).\nProof.\nintros; rewrite !(mul_comm c); now apply mul_rem_distr_r.\nQed.\n\n(** Operations modulo. *)\n\nTheorem rem_rem: forall a n, n~=0 ->\n (a rem n) rem n == a rem n.\nProof.\nintros. pos_or_neg a; pos_or_neg n. apply NZQuot.mod_mod; order.\nrewrite <- ! (rem_opp_r _ n) by trivial. apply NZQuot.mod_mod; order.\napply opp_inj. rewrite <- !rem_opp_l by order. apply NZQuot.mod_mod; order.\napply opp_inj. rewrite <- !rem_opp_opp by order. apply NZQuot.mod_mod; order.\nQed.\n\nLemma mul_rem_idemp_l : forall a b n, n~=0 ->\n ((a rem n)*b) rem n == (a*b) rem n.\nProof.\nassert (Aux1 : forall a b n, 0<=a -> 0<=b -> n~=0 ->\n         ((a rem n)*b) rem n == (a*b) rem n).\n intros. pos_or_neg n. apply NZQuot.mul_mod_idemp_l; order.\n rewrite <- ! (rem_opp_r _ n) by order. apply NZQuot.mul_mod_idemp_l; order.\nassert (Aux2 : forall a b n, 0<=a -> n~=0 ->\n         ((a rem n)*b) rem n == (a*b) rem n).\n intros. pos_or_neg b. now apply Aux1.\n apply opp_inj. rewrite <-2 rem_opp_l, <-2 mul_opp_r by order.\n  apply Aux1; order.\nintros a b n Hn. pos_or_neg a. now apply Aux2.\napply opp_inj. rewrite <-2 rem_opp_l, <-2 mul_opp_l, <-rem_opp_l by order.\napply Aux2; order.\nQed.\n\nLemma mul_rem_idemp_r : forall a b n, n~=0 ->\n (a*(b rem n)) rem n == (a*b) rem n.\nProof.\nintros. rewrite !(mul_comm a). now apply mul_rem_idemp_l.\nQed.\n\nTheorem mul_rem: forall a b n, n~=0 ->\n (a * b) rem n == ((a rem n) * (b rem n)) rem n.\nProof.\nintros. now rewrite mul_rem_idemp_l, mul_rem_idemp_r.\nQed.\n\n(** addition and modulo\n\n  Generally speaking, unlike with other conventions, 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*)\n\nLemma add_rem_idemp_l : forall a b n, n~=0 -> 0 <= a*b ->\n ((a rem n)+b) rem n == (a+b) rem n.\nProof.\nassert (Aux : forall a b n, 0<=a -> 0<=b -> n~=0 ->\n          ((a rem n)+b) rem n == (a+b) rem n).\n intros. pos_or_neg n. apply NZQuot.add_mod_idemp_l; order.\n rewrite <- ! (rem_opp_r _ n) by order. apply NZQuot.add_mod_idemp_l; order.\nintros a b n Hn Hab. destruct (le_0_mul _ _ Hab) as [(Ha,Hb)|(Ha,Hb)].\nnow apply Aux.\napply opp_inj. rewrite <-2 rem_opp_l, 2 opp_add_distr, <-rem_opp_l by order.\nrewrite <- opp_nonneg_nonpos in *.\nnow apply Aux.\nQed.\n\nLemma add_rem_idemp_r : forall a b n, n~=0 -> 0 <= a*b ->\n (a+(b rem n)) rem n == (a+b) rem n.\nProof.\nintros. rewrite !(add_comm a). apply add_rem_idemp_l; trivial.\nnow rewrite mul_comm.\nQed.\n\nTheorem add_rem: forall a b n, n~=0 -> 0 <= a*b ->\n (a+b) rem n == (a rem n + b rem n) rem n.\nProof.\nintros a b n Hn Hab. rewrite add_rem_idemp_l, add_rem_idemp_r; trivial.\nreflexivity.\ndestruct (le_0_mul _ _ Hab) as [(Ha,Hb)|(Ha,Hb)];\n destruct (le_0_mul _ _ (rem_sign_mul b n Hn)) as [(Hb',Hm)|(Hb',Hm)];\n auto using mul_nonneg_nonneg, mul_nonpos_nonpos.\n setoid_replace b with 0 by order. rewrite rem_0_l by order. nzsimpl; order.\n setoid_replace b with 0 by order. rewrite rem_0_l by order. nzsimpl; order.\nQed.\n\n(** Conversely, the following results need less restrictions here. *)\n\nLemma quot_quot : forall a b c, b~=0 -> c~=0 ->\n (a÷b)÷c == a÷(b*c).\nProof.\nassert (Aux1 : forall a b c, 0<=a -> 0<b -> c~=0 -> (a÷b)÷c == a÷(b*c)).\n intros. pos_or_neg c. apply NZQuot.div_div; order.\n apply opp_inj. rewrite <- 2 quot_opp_r, <- mul_opp_r; trivial.\n apply NZQuot.div_div; order.\n rewrite <- neq_mul_0; intuition order.\nassert (Aux2 : forall a b c, 0<=a -> b~=0 -> c~=0 -> (a÷b)÷c == a÷(b*c)).\n intros. pos_or_neg b. apply Aux1; order.\n apply opp_inj. rewrite <- quot_opp_l, <- 2 quot_opp_r, <- mul_opp_l; trivial.\n apply Aux1; trivial.\n rewrite <- neq_mul_0; intuition order.\nintros. pos_or_neg a. apply Aux2; order.\napply opp_inj. rewrite <- 3 quot_opp_l; try order. apply Aux2; order.\nrewrite <- neq_mul_0. tauto.\nQed.\n\nLemma mod_mul_r : forall a b c, b~=0 -> c~=0 ->\n a rem (b*c) == a rem b + b*((a÷b) rem c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a÷(b*c))).\n rewrite <- quot_rem by (apply neq_mul_0; split; order).\n rewrite <- quot_quot by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- quot_rem by order.\n apply quot_rem; order.\nQed.\n\nLemma rem_quot: forall a b, b~=0 ->\n a rem b ÷ b == 0.\nProof.\n intros a b Hb.\n rewrite quot_small_iff by assumption.\n auto using rem_bound_abs.\nQed.\n\n(** A last inequality: *)\n\nTheorem quot_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a÷b) <= (c*a)÷b.\nProof. exact NZQuot.div_mul_le. Qed.\n\nEnd ZQuotProp.\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/Numbers/Integer/Abstract/ZDivTrunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7624259365010069}}
{"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.\nProof. simpl. reflexivity. Qed.\n\n(* ------------------------------ *)\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 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(* ----------------------------- *)\n\nCheck true.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\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 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\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\n  (* With this definition, 0 is represented by O, 1 by S O, 2 by S (S O), and so on. *)\n\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  Example test_mult1: (mult 3 3) = 9.\n  Proof. simpl. reflexivity. Qed.\n\n  Fixpoint exp (base power : nat) : nat :=\n    match power with\n      | O => S O\n      | S p => mult base (exp base p)\n    end.\n  Compute (exp 2 4).\n\n  Fixpoint factorial (n:nat) : nat :=\n    match n with\n    | O => S O\n    | S p => mult (S p) (factorial p)\n    end.\n\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\" := (plus x y)\n                         (at level 50, left associativity)\n                         : nat_scope.\n  Notation \"x - y\" := (minus x y)\n                         (at level 50, left associativity)\n                         : nat_scope.\n  Notation \"x * y\" := (mult x y)\n                         (at level 40, left associativity)\n                         : nat_scope.\n\n  Check ((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\n\n\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.\n\n  Notation \"x =< y\" := (leb x y)\n                         (at level 70): nat_scope.\n  Notation \"x =? y\" := (eqb x y) \n                         (at level 70) : nat_scope.\n\n  Example test_leb1: (2 =< 2) = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_leb2: (2 =< 4) = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_leb3: (4 =< 2) = false.\n  Proof. simpl. reflexivity. Qed.\n\n\n\n  Fixpoint ltb (n m : nat) : bool :=\n    match n with \n    | O =>    match m with\n              | O => false\n              | S _ => true\n              end\n    | S n' => match m with\n              | O => false\n              | S m' => ltb n' m'\n              end\n    end.\n\n  Notation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\n  Example test_ltb1: (2 <? 2) = false.\n  Proof. simpl. reflexivity. Qed.\n  Example test_ltb2: (2 <? 4) = true.\n  Proof. simpl. reflexivity. Qed.\n  Example test_ltb3: (4 <? 2) = false.\n  Proof. simpl. reflexivity. Qed.\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/dataANDfunction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7624094700837334}}
{"text": "\nDefinition id : forall X:Prop, X->X := \n\tfun (X:Prop) (a:X) => a.\nCheck id (True->True) : (True->True)->True->True. \n\n(*forall (A:Type)(x y:A), x=y -> y=x*)\n\n(* 2 *)\n\nDefinition sym : forall (A:Type)(x y:A), x=y -> y=x :=\n\tfun (A:Type) (x y:A) (H: x = y) => \n\t\teq_ind x (fun z:A => z=x)\n\t\t(eq_refl x) y H.\n\nDefinition trans : forall (A:Type)(x y z:A), x=y -> y=z -> x=z := \n\tfun (A:Type) (x y z : A) (H1 : x=y) (H2:y=z) =>\n\t\teq_ind y (fun y0:A => x=y0)\n\t\tH1 z H2.\n\n\nDefinition cong : forall (A B:Type) (f:A->B) (x y:A), x=y -> f x = f y := \n\tfun (A B:Type) (f:A->B) (x y:A) (H:x=y) =>\n\t\teq_ind x (fun t:A => f x=f t) \n\t\t(eq_refl (f x)) y H\n\t.\n\n(*Lemma cong_dep : \n\tforall (A:Type) (B:A->Type) (f:forall x:A, B x) (x y:A),\n\t\tx=y -> f x= f y.*)\n\n(* 3 *)\n\nDefinition t := Prop.\nCheck (forall (x:t), x):t.\n\nDefinition u := Type.\nFail Check (forall (x:u), x):u.\nCheck (forall (P:Type), P):Type.\n\n\n(* 4 *)\n\nDefinition imp_and (A:Prop)(B:Prop) := \n\tforall X : Prop,  (A -> B -> X ) -> X.\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/PA/2021/TP2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7623253947150914}}
{"text": "(* Software Foundations *)\n(* Exercice 5 stars, classical_axioms *)\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 peirce_imp_classic: peirce -> classic.\nProof.\n    compute. (* we can also use: unfold peirce. unfold classic. unfold not. *)\nintros. apply H with False. intros. apply H0 in H1. inversion H1.\nQed.\n\nTheorem classic_imp_excluded_middle: classic -> excluded_middle.\n\nProof.\n    compute. intros. apply H. intros. apply H0. right. intros. \n    apply H0. left. apply H1.\nQed.\n\nTheorem excluded_middle_imp_de_morgan_not_and_not: excluded_middle -> de_morgan_not_and_not.\nProof.\n    unfold excluded_middle. unfold de_morgan_not_and_not.\nintros.\ndestruct (H P). left. apply H1.\ndestruct (H Q). right. apply H2.\ndestruct H0. split. apply H1. apply H2.\nQed.\n\nTheorem de_morgan_not_and_not_imp_implies_to_or: de_morgan_not_and_not -> implies_to_or.\nProof.\n    compute. intros. \n    apply H. intros. destruct H1. apply H1. intros. apply H2. apply H0. apply H3. \nQed.\n\nTheorem implies_to_or_imp_peirce: implies_to_or -> peirce.\nProof.\n    Abort. (* Couldn't complet the cycle *)\n\n(* not required just wanted to keep the proof *)\nTheorem pierce_eq_classic: peirce <-> classic.\nProof.\n    unfold peirce, classic.\n    unfold not.\n    split.\n    (* peirce -> classic *)\n    intros. apply H with False.\n    intros.\n    apply H0 in H1. inversion H1.\n    (* peirce <- classic *)\n    intros. apply H. intros. apply H1. apply H0. intros. apply H1 in H2. inversion H2. \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/chapter8_Library_Logic/classical_axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7623253868781549}}
{"text": "\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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nDefinition nandb (b1: bool) (b2:bool) : bool :=        (* 1 star *)\nmatch b1 with\n | true => match b2 with\n            | false => true\n            | true => false\n\t   end\n | false => true\nend.\n\nExample test_nandb1: (nandb true false) = true.\nProof. simpl. reflexivity. Admitted.\n\nExample test_nandb2: (nandb false false) = true.\nProof. simpl. reflexivity. Admitted.\n\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Admitted.\n\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Admitted.\n\nDefinition andb3 (b1: bool) (b2:bool) (b3:bool) : bool :=    (* 1 star *)\nmatch b1 with\n  | false => false\n  | true => match b2 with\n             | false => false\n             | true => b3\n       \t    end\nend.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Admitted.\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Admitted.\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Admitted.\n\nCheck true.\n\nModule Playground1.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nEnd Playground1.\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 :=\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 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 => 1\n  | S n' => n * (factorial n')\n  end.\n\nExample test_factorial1:          (factorial 3) = 6.\nProof. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\nProof. 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).\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.\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\nFixpoint 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.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.  Qed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\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\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.  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 H. \n  simpl. \n  rewrite <- H. \n  reflexivity.\n  Qed.\n\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\nTheorem plus_1_neq_0 : forall n : nat,\n  (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_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\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\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\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\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 zero_nbeq_plus_1 : forall n : nat,\n   0 =? (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\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\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\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 x b. rewrite -> x. rewrite -> x. reflexivity.\nQed.\n\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. rewrite -> x. rewrite -> x. rewrite -> negb_involutive. reflexivity.\nQed.\n\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] [].\n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - reflexivity.\nQed.\n\nPrint nat.\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (n : bin) : bin :=\n  match n with\n  | Z => B Z\n  | A n' => B n'\n  | B n' => A (incr n')\n  end.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n  | Z => 0\n  | A b' => 2 * (bin_to_nat b')\n  | B b' => 1 + 2 * (bin_to_nat b')\n  end.\n\nExample test_bin_incr1 :=\n  bin_to_nat(incr (B (B (B (A Z))))).\n\n\n", "meta": {"author": "AlexDolhescu", "repo": "Coq", "sha": "81daf29eeef8d85797f6a96773da4bb8f6ec8476", "save_path": "github-repos/coq/AlexDolhescu-Coq", "path": "github-repos/coq/AlexDolhescu-Coq/Coq-81daf29eeef8d85797f6a96773da4bb8f6ec8476/SF I/basic_bool_facotrial_demonstations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7623184050337741}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Order relations                                                         *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF (* TLC *) Require Import LibTactics LibLogic LibReflect LibOperation LibRelation.\nGeneralizable Variables A.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Preorder *)\n\n(** Definition *)\n\nRecord preorder A (R:binary A) : Prop := {\n   preorder_refl : refl R;\n   preorder_trans : trans R }.\n\nArguments preorder_trans [A] [R] [p] y [x] [z].\n\n(** Transformations *)\n\nLemma preorder_inverse : forall A (R:binary A),\n  preorder R -> \n  preorder (inverse R).\nProof using. hint trans_inverse. introv [Re Tr]. constructor~. Qed.\n\nLemma preorder_rclosure : forall A (R:binary A),\n  preorder R -> \n  preorder (rclosure R).\nProof using. hint refl_rclosure, trans_rclosure. introv [Re Tr]. constructor~. Qed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total preorder *)\n\n(** Definition of total preorder relations *)\n\nRecord total_preorder A (R:binary A) : Prop := {\n   total_preorder_trans : trans R;\n   total_preorder_total : total R }.\n\nArguments total_preorder_trans [A] [R] t y [x] [z].\n\n(** Conversion to preorder *)\n\nLemma total_preorder_refl : forall A (le:binary A),\n  total_preorder le -> \n  refl le.\nProof using. introv [Tr To]. intros x. destruct~ (To x x). Qed.\n\nHint Resolve total_preorder_refl.\n\nCoercion total_preorder_to_preorder A (R:binary A)\n  (O:total_preorder R) : preorder R.\nProof using. lets [M _]: O. constructor~. Qed.\n\nHint Resolve total_preorder_to_preorder.\n\n(** Transformations *)\n\nLemma total_preorder_inverse : forall A (R:binary A),\n  total_preorder R -> \n  total_preorder (inverse R).\nProof using. hint trans_inverse, total_inverse. introv [Tr To]. constructor~. Qed.\n\nLemma total_preorder_rclosure : forall A (R:binary A),\n  total_preorder R -> \n  total_preorder (rclosure R).\nProof using. hint trans_rclosure, total_rclosure. introv [Re Tr]. constructor~. Qed.\n\n(** Properties *)\n\nLemma inverse_of_not : forall A (R:binary A) x y,\n  total R -> \n  ~ R x y -> \n  inverse R x y.\nProof using. introv T H. destruct (T x y); auto_false~. Qed.\n\nLemma inverse_strict_of_not : forall A (R:binary A) x y,\n  total R -> \n  ~ R x y -> \n  inverse (strict R) x y.\nProof using.\n  introv T H. destruct (T x y). auto_false~.\n  hnf. split~. intro_subst~.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Order *)\n\n(** Definition *)\n\nRecord order A (R:binary A) : Prop := {\n   order_refl : refl R;\n   order_trans : trans R;\n   order_antisym : antisym R }.\n\nArguments order_trans [A] [R] [o] y [x] [z].\nArguments order_antisym [A] [R] [o] [x] [y].\n\n(** Conversion to preorder *)\n\nCoercion order_to_preorder A (R:binary A)\n  (O:order R) : preorder R.\nProof using. destruct* O. constructors*. Qed.\n\nHint Resolve order_to_preorder.\n\n(** Transformations *)\n\nLemma order_inverse : forall A (R:binary A),\n  order R -> \n  order (inverse R).\nProof using.\n  hint trans_inverse, antisym_inverse.\n  introv [Re Tr An]. constructor~. \nQed.\n\nLemma order_rclosure : forall A (R:binary A),\n  order R -> \n  order (rclosure R).\nProof using.\n  hint refl_rclosure, trans_rclosure, antisym_rclosure.\n  introv [Re Tr An]. constructor~.\nQed.\n\n(** Properties *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Order relation upto an equivalence relation *)\n\n(** Note: this is used in LibFix *)\n\nRecord order_wrt (A:Type) (E:binary A) (R:binary A) : Prop := {\n   order_wrt_refl : refl R;\n   order_wrt_trans : trans R;\n   order_wrt_antisym : antisym_wrt E R }.\n\nArguments order_wrt_trans [A] [E] [R] [o] y [x] [z].\nArguments order_wrt_antisym [A] [E] [R] [o] [x] [y].\n\n(** Conversion to preorder *)\n\nCoercion order_wrt_to_preorder A (E:binary A) (R:binary A)\n  (O:order_wrt E R) : preorder R.\nProof using. destruct* O. constructors*. Qed.\n\nHint Resolve order_wrt_to_preorder.\n\n(** Transformations *)\n\nLemma order_wrt_inverse : forall A (E:binary A) (R:binary A),\n  order_wrt E R -> \n  order_wrt E (inverse R).\nProof using.\n  hint trans_inverse, antisym_wrt_inverse.\n  introv [Re Tr An]. constructor~. \nQed.\n\nLemma order_wrt_rclosure : forall A (E:binary A) (R:binary A),\n  order_wrt E R -> \n  order_wrt (rclosure E) (rclosure R).\nProof using.\n  hint refl_rclosure, trans_rclosure, antisym_wrt_rclosure.\n  introv [Re Tr An]. constructor~.\nQed.\n\n(** Properties *)\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total Order *)\n\n(** Definition *)\n\nRecord total_order A (R:binary A) : Prop := {\n   total_order_order :> order R;\n   total_order_total : total R }.\n\n(** Projections *)\n\nDefinition total_order_refl := order_refl.\nDefinition total_order_trans := order_trans.\nDefinition total_order_antisym := order_antisym.\n\nArguments total_order_trans [A] [R] [o] y [x] [z].\nArguments total_order_antisym [A] [R] [o] [x] [y].\n\n(** Construction *)\n\nLemma total_order_intro : forall A (R:binary A),\n   trans R -> \n   antisym R -> \n   total R -> \n   total_order R.\nProof using.\n  introv Tra Ant Tot. constructor~. constructor~.\n  intros_all. destruct~ (Tot x x).\nQed.\n\n(** Conversion to order *)\n\nCoercion total_order_to_total_preorder A (R:binary A)\n  (O:total_order R) : total_preorder R.\nProof using. destruct* O. constructors*. applys* order_trans. Qed.\n\nDefinition total_order_to_order := total_order_order.\n\nHint Resolve total_order_to_order total_order_to_total_preorder.\n\n(** Transformations *)\n\nLemma total_order_inverse : forall A (R:binary A),\n  total_order R -> \n  total_order (inverse R).\nProof using.\n  hint total_inverse, order_inverse.\n  introv [Or To]. constructor~.\nQed.\n\nLemma total_order_rclosure : forall A (R:binary A),\n  total_order R -> \n  total_order (rclosure R).\nProof using.\n  hint total_rclosure, order_rclosure.\n  introv [Or To]. constructor~.\nQed.\n\n(** Properties *)\n   \nSection TotalOrderProp.\nVariables (A:Type) (R : binary A).\n\n(** WARNING: notations here are not typeclass operators \n    -- TODO: is this really what we want? \n    perhaps it would be clearer to inline these notations. *)\n\nNotation \"'le'\" := (R).\nNotation \"'ge'\" := (inverse R).\nNotation \"'lt'\" := (strict R).\nNotation \"'gt'\" := (inverse lt).\n\nLtac total_order_normalize :=\n  repeat rewrite rclosure_eq_fun;\n  repeat rewrite inverse_eq_fun;\n  repeat rewrite strict_eq_fun.\n\nLemma total_order_le_is_rclosure_lt : forall (To:total_order R),\n  le = rclosure lt.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_lt_is_strict_le : forall (To:total_order R),\n  lt = strict le.\nProof using.\n  auto.\nQed.\n\nLemma total_order_ge_is_rclosure_gt : forall (To:total_order R),\n  ge = rclosure gt.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*. subst*. dintuition eauto.\nQed.\n\nLemma total_order_gt_is_strict_ge : forall (To:total_order R),\n  gt = strict ge.\nProof using.\n  extens. intros. total_order_normalize. iff M.\n  tests~: (x = y).\n  destruct M. autos*.\n  destruct M. autos*.\nQed.\n\nLemma total_order_lt_or_eq_or_gt : forall (To:total_order R) x y,\n  lt x y \\/ x = y \\/ gt x y.\nProof using.\n  introv H. intros. total_order_normalize. tests: (x = y).\n    branch~ 2.\n    destruct (total_order_total H x y).\n     branch~ 1. \n     branch~ 3.\nQed.\n\nLemma total_order_lt_or_ge : forall (To:total_order R) x y,\n  lt x y \\/ ge x y.\nProof using.\n  intros. branches (total_order_lt_or_eq_or_gt To x y).\n  left~.\n  right~. subst. hnf. apply~ total_order_refl.\n  right~. rewrite~ total_order_ge_is_rclosure_gt.\n   total_order_normalize. hnfs~.\nQed.\n\nLemma total_order_le_or_gt : forall (To:total_order R) x y,\n  le x y \\/ gt x y.\nProof using.\n  intros. branches~ (total_order_lt_or_eq_or_gt To x y).\n  left~. rewrite~ total_order_le_is_rclosure_lt. total_order_normalize. hnfs~.\n  left~. subst. apply~ total_order_refl.\nQed.\n\nEnd TotalOrderProp.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Strict order *)\n\n(** Definition *)\n\nRecord strict_order A (R:binary A) : Prop := {\n   strict_order_irrefl : irrefl R;\n   strict_order_asym : asym R;\n   strict_order_trans : trans R }.\n\nArguments strict_order_trans [A] [R] [s] y [x] [z].\n\n(** Transformations *)\n\nLemma strict_order_inverse : forall A (R:binary A),\n  strict_order R ->\n  strict_order (inverse R).\nProof using.\n  hint antisym_inverse, trans_inverse, asym_inverse.\n  introv [Ir As Tr]. constructor~.\nQed.\n\nLemma strict_order_strict : forall A (R:binary A),\n  order R -> \n  strict_order (strict R).\nProof using.\n  introv [Re As Tr]. unfold strict. constructor; intros_all; simpls.\n  destruct* H.\n  applys* antisym_inv x y.\n  split. applys* As. intros E. subst. applys* antisym_inv y z.\nQed.\n\nLemma order_rclosure_of_strict_order : forall A (R:binary A),\n  strict_order R -> \n  order (rclosure R).\nProof using.\n  introv [Re As Tr]. rewrite rclosure_eq_fun. constructor; simpl.\n  intros_all~.\n  introv [H1|E1] [H2|E2]; subst; auto.\n    left. apply* trans_inv.\n  introv [H1|E1] [H2|E2]; try subst; auto.\n    false. apply* As.\nQed.\n\n(**************************************************************************)\n(* ################################################################# *)\n(* * Total strict order *)\n\n(** Definition *)\n\nRecord strict_total_order A (R:binary A) : Prop := {\n   strict_total_order_trans : trans R;\n   strict_total_order_trichotomous : trichotomous R }.\n\nArguments strict_total_order_trans [A] [R] [s] y [x] [z].\n\n(** Conversion to strict order and back *)\n\nLemma strict_total_order_irrefl : forall A (R:binary A),\n  strict_total_order R -> \n  irrefl R.\nProof using. introv [Tr Tk]. intros x. lets: (Tk x x). inverts~ H. Qed.\n\nLemma strict_total_order_asym : forall A (R:binary A),\n  strict_total_order R -> \n  asym R.\nProof using. introv [Tr Tk]. intros x y. lets: (Tk x y). inverts~ H. Qed.\n\nCoercion strict_total_order_to_strict_order A (R:binary A)\n  (O:strict_total_order R) : strict_order R.\nProof using.\n  lets [M _]: O. constructor;\n  autos~ strict_total_order_irrefl strict_total_order_asym.\nQed.\n\nHint Resolve strict_total_order_to_strict_order.\n\n(** Transformation *)\n\nLemma strict_total_order_inverse : forall A (R:binary A),\n  strict_total_order R -> \n  strict_total_order (inverse R).\nProof using.\n  introv [Tr Tk]. constructor. apply~ trans_inverse.\n  apply~ trichotomous_inverse.\nQed.\n(** From total order *)\n\nLemma strict_total_order_of_total_order : forall A (R:binary A),\n  total_order R -> \n  strict_total_order (strict R).\nProof using.\n  introv [[Re Tr As] To]. constructor.\n  apply~ trans_strict.\n  intros x y. tests: (x = y).\n    subst. apply trichotomy_eq. unfolds* strict.\n    unfold strict. destruct (To x y).\n      apply* trichotomy_left.\n      apply* trichotomy_right.\nQed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Definition of order operators *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Classes and notation for comparison operators *)\n\n(** Operators *)\n\nClass Le (A : Type) := { le : binary A }.\nClass Ge (A : Type) := { ge : binary A }.\nClass Lt (A : Type) := { lt : binary A }.\nClass Gt (A : Type) := { gt : binary A }.\n\nGlobal Opaque le lt ge gt.\n\n(** Structures *)\n\nClass Le_preorder `{Le A} : Prop :=\n  { le_preorder : preorder le }.\n\nClass Le_total_preorder `{Le A} : Prop :=\n  { le_total_preorder : total_preorder le }.\n\nClass Le_order `{Le A} : Prop :=\n  { le_order : order le }.\n\nClass Le_total_order `{Le A} : Prop :=\n  { le_total_order : total_order le }.\n\nClass Lt_strict_order `{Lt A} : Prop :=\n  { lt_strict_order : strict_order lt }.\n\nClass Lt_strict_total_order `{Lt A} : Prop :=\n  { lt_strict_total_order : strict_total_order lt }.\n\n(** Notation *)\n\nNotation \"x <= y\" := (le x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x >= y\" := (ge x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x < y\" := (lt x y)\n  (at level 70, no associativity) : comp_scope.\nNotation \"x > y\" := (gt x y)\n  (at level 70, no associativity) : comp_scope.\n\nOpen Scope comp_scope.\n\nNotation \"x <= y <= z\" := (x <= y /\\ y <= z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x <= y < z\" := (x <= y /\\ y < z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x < y <= z\" := (x < y /\\ y <= z)\n  (at level 70, y at next level) : comp_scope.\nNotation \"x < y < z\" := (x < y /\\ y < z)\n  (at level 70, y at next level) : comp_scope.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** The operators [ge], [lt] and [gt] are deduced from [le] *)\n\nInstance ge_of_le : forall `{Le A}, Ge A.\n  constructor. apply (inverse le). Defined.\nInstance lt_of_le : forall `{Le A}, Lt A.\n  constructor. apply (strict le). Defined.\nInstance gt_of_le : forall `{Le A}, Gt A.\n  constructor. apply (inverse lt). Defined.\n\nLemma ge_is_inverse_le : forall `{Le A}, ge = inverse le.\nProof using. extens*. Qed.\n\nLemma lt_is_strict_le : forall `{Le A}, lt = strict le.\nProof using. extens*. Qed.\n\nLemma gt_is_inverse_lt : forall `{Le A}, gt = inverse lt.\nProof using. extens*. Qed.\n\nLemma gt_is_inverse_strict_le : forall `{Le A}, gt = inverse (strict le).\nProof using. extens. intros. rewrite gt_is_inverse_lt. rewrite* lt_is_strict_le. Qed.\n\nGlobal Opaque ge_of_le lt_of_le gt_of_le.\n\n(** Local tactic [rew_to_le] *)\n\nHint Rewrite @gt_is_inverse_strict_le @ge_is_inverse_le @lt_is_strict_le : rew_to_le.\n\nTactic Notation \"rew_to_le\" :=\n  autorewrite with rew_to_le in *.\n\nHint Rewrite @ge_is_inverse_le @gt_is_inverse_lt : rew_to_le_lt.\n\nTactic Notation \"rew_to_le_lt\" :=\n  autorewrite with rew_to_le_lt in *.\n\nLemma gt_is_strict_inverse_le : forall `{Le A}, \n  gt = strict (inverse le).\nProof using. intros. rew_to_le. apply inverse_strict. Qed.\n\nLemma le_is_rclosure_lt : forall `{Le A},\n  refl le -> \n  le = rclosure lt.\nProof using. intros. rew_to_le. rewrite~ rclosure_strict. Qed.\n\nLemma le_is_inverse_ge : forall `{Le A}, \n  le = inverse ge.\nProof using. intros. rew_to_le. rewrite~ inverse_inverse. Qed.\n\nLemma lt_is_inverse_gt : forall `{Le A}, \n  lt = inverse gt.\nProof using. intros. rew_to_le. rewrite~ inverse_inverse. Qed.\n\nLemma gt_is_strict_ge : forall `{Le A}, \n  gt = strict ge.\nProof using. intros. rew_to_le. apply inverse_strict. Qed.\n\nLemma ge_is_rclosure_gt : forall `{Le A},\n  refl le -> \n  ge = rclosure gt.\nProof using. intros. rewrite gt_is_strict_ge. rewrite~ rclosure_strict. Qed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Classes for comparison properties *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Definition of classes *)\n\n(** symmetric structure *)\n\nClass Ge_preorder `{Le A} : Prop :=\n  { ge_preorder : preorder ge }.\nClass Ge_total_preorder `{Le A} : Prop :=\n  { ge_total_preorder : total_preorder ge }.\nClass Ge_order `{Le A} : Prop :=\n  { ge_order : order ge }.\nClass Ge_total_order `{Le A} : Prop :=\n  { ge_total_order : total_order le }.\nClass Gt_strict_order `{Le A} : Prop :=\n  { gt_strict_order : strict_order gt }.\nClass Gt_strict_total_order `{Le A} : Prop :=\n  { gt_strict_total_order : strict_total_order gt }.\n\n(** properties of le *)\n\nClass Le_refl `{Le A} :=\n  { le_refl : refl le }.\nClass Le_trans `{Le A} :=\n  { le_trans : trans le }.\nClass Le_antisym `{Le A} :=\n  { le_antisym : antisym le }.\nClass Le_total `{Le A} :=\n  { le_total : total le }.\n\n(** properties of ge *)\n\nClass Ge_refl `{Ge A} :=\n  { ge_refl : refl ge }.\nClass Ge_trans `{Ge A} :=\n  { ge_trans : trans ge }.\nClass Ge_antisym `{Ge A} :=\n  { ge_antisym : antisym ge }.\nClass Ge_total `{Ge A} :=\n  { ge_total : total ge }.\n\n(** properties of lt *)\n\nClass Lt_irrefl `{Lt A} :=\n  { lt_irrefl : irrefl lt }.\nClass Lt_trans `{Lt A} :=\n  { lt_trans : trans lt }.\n\n(** properties of gt *)\n\nClass Gt_irrefl `{Gt A} :=\n  { gt_irrefl : irrefl gt }.\nClass Gt_trans `{Gt A} :=\n  { gt_trans : trans gt }.\n\n(** mixed transitivity results *)\n\nClass Lt_le_trans `{Le A} :=\n  { lt_le_trans : forall y x z, x < y -> y <= z -> x < z }.\nClass Le_lt_trans `{Le A} :=\n  { le_lt_trans : forall y x z, x <= y -> y < z -> x < z }.\nClass Gt_ge_trans `{Le A} :=\n  { gt_ge_trans : forall y x z, x > y -> y >= z -> x > z }.\nClass Ge_gt_trans `{Le A} :=\n  { ge_gt_trans : forall y x z, x >= y -> y > z -> x > z }.\n\nArguments lt_irrefl [A] [H] [Lt_irrefl].\nArguments le_trans {A} {H} {Le_trans} y [x] [z].\nArguments ge_trans {A} {H} {Ge_trans} y [x] [z].\nArguments lt_trans {A} {H} {Lt_trans} y [x] [z].\nArguments gt_trans {A} {H} {Gt_trans} y [x] [z].\n\n(** conversion between operators *)\n\nClass Ge_as_sle `{Le A} : Prop :=\n  { ge_as_sle : forall x y : A, (x >= y) = (y <= x) }.\n\nClass Gt_as_slt `{Le A} : Prop :=\n  { gt_as_slt : forall x y : A, (x > y) = (y < x) }.\n\nClass Ngt_as_sle `{Le A} : Prop :=\n  { ngt_as_sle : forall x y : A, (~ x < y) = (y <= x) }.\n\nClass Nlt_as_ge `{Le A} : Prop :=\n  { nlt_as_ge : forall x y : A, (~ x < y) = (x >= y) }.\n\nClass Ngt_as_le `{Le A} : Prop :=\n  { ngt_as_le : forall x y : A, (~ x > y) = (x <= y) }.\n\nClass Nle_as_gt `{Le A} : Prop :=\n  { nle_as_gt : forall x y : A, (~ x <= y) = (x > y) }.\n\nClass Nge_as_lt `{Le A} : Prop :=\n  { nge_as_lt : forall x y : A, (~ x >= y) = (x < y) }.\n\n(** inclusion between operators *)\n\nClass Lt_to_le `{Le A} : Prop :=\n  { lt_to_le : forall x y : A, (x < y) -> (x <= y) }.\n\nClass Gt_to_ge `{Le A} : Prop :=\n  { gt_to_ge : forall x y : A, (x > y) -> (x >= y) }.\n\nClass Nle_to_sle `{Le A} : Prop :=\n  { nle_to_sle : forall x y : A, (~ x <= y) -> (y <= x) }.\n\nClass Nle_to_slt `{Le A} : Prop :=\n  { nle_to_slt : forall x y : A, (~ x <= y) -> (y < x) }.\n\n(** case analysis *)\n\nClass Case_eq_lt_gt `{Le A} : Prop :=\n  { case_eq_lt_gt : forall x y : A, x = y \\/ x < y \\/ x > y }.\n\nClass Case_eq_lt_slt `{Le A} : Prop :=\n  { case_eq_lt_slt : forall x y : A, x = y \\/ x < y \\/ y < x }.\n\nClass Case_le_gt `{Le A} : Prop :=\n  { case_le_gt : forall x y : A, x <= y \\/ x > y }.\n\nClass Case_le_slt `{Le A} : Prop :=\n  { case_le_slt : forall x y : A, x <= y \\/ y < x }.\n\nClass Case_lt_ge `{Le A} : Prop :=\n  { case_lt_ge : forall x y : A, x < y \\/ x >= y }.\n\nClass Case_lt_sle `{Le A} : Prop :=\n  { case_lt_sle : forall x y : A, x < y \\/ y <= x }.\n\n(** case analysis under one assumption *)\n\nClass Neq_case_lt_gt `{Le A} : Prop :=\n  { neq_case_lt_gt : forall x y : A, x <> y -> x < y \\/ x > y }.\n\nClass Neq_case_lt_slt `{Le A} : Prop :=\n  { neq_case_lt_slt : forall x y : A, x <> y -> x < y \\/ y < x }.\n\nClass Le_case_eq_lt `{Le A} : Prop :=\n  { le_case_eq_lt : forall x y : A, x <= y -> x = y \\/ x < y }.\n\nClass Ge_case_eq_gt `{Le A} : Prop :=\n  { ge_case_eq_gt : forall x y : A, x >= y -> x = y \\/ x > y }.\n\n(** case analysis under two assumptions *)\n\nClass Le_neq_to_lt `{Le A} : Prop :=\n  { le_neq_to_lt : forall x y : A, x <= y -> x <> y -> x < y }.\n\nClass Ge_neq_to_gt `{Le A} : Prop :=\n  { ge_neq_to_gt : forall x y : A, x >= y -> x <> y -> x > y }.\n\nClass Nlt_nslt_to_eq `{Le A} : Prop :=\n  { nlt_nslt_to_eq : forall x y : A, ~ (lt x y) -> ~ (lt y x) -> x = y }.\n\n(** contradiction from case analysis *)\n\nClass Lt_ge_false `{Le A} : Prop :=\n  { lt_ge_false : forall x y : A, x < y -> x >= y -> False }.\n\nClass Lt_gt_false `{Le A} : Prop :=\n  { lt_gt_false : forall x y : A, x < y -> x > y -> False }.\n\nClass Lt_slt_false `{Le A} : Prop :=\n  { lt_slt_false : forall x y : A, x < y -> y < x -> False }.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(* * Instances for comparison structures *)\n\nSection Instances.\nContext `{Le A}.\n\nLtac auto_star ::= try solve [ dauto ].\n\n(** derived structures *)\n\nGlobal Instance Le_preorder_of_Le_order :\n  Le_order -> \n  Le_preorder.\nProof using. constructor. intros. apply* order_to_preorder. Qed.\n\nGlobal Instance Le_total_preorder_of_Le_total_order :\n  Le_total_order -> \n  Le_total_preorder.\nProof using. constructor. intros. apply* total_order_to_total_preorder. Qed.\n\nGlobal Instance Le_preorder_of_Total_preorder :\n  Le_total_preorder -> \n  Le_preorder.\nProof using. constructor. intros. apply* total_preorder_to_preorder. Qed.\n\nGlobal Instance Le_order_of_Le_total_order :\n  Le_total_order -> \n  Le_order.\nProof using. constructor. intros. apply* total_order_to_order. Qed.\n\nGlobal Instance lt_strict_order_of_lt_strict_total_order :\n  Lt_strict_total_order -> \n  Lt_strict_order.\nProof using. constructor. intros. apply* strict_total_order_to_strict_order. Qed.\n\nGlobal Instance Lt_strict_order_of_Le_order :\n  Le_order ->\n  Lt_strict_order.\nProof using. constructor. intros. rew_to_le. apply* strict_order_strict. Qed.\n\nGlobal Instance Lt_strict_total_order_of_Le_total_order :\n  Le_total_order -> \n  Lt_strict_total_order.\nProof using. constructor. intros. rew_to_le. apply* strict_total_order_of_total_order. Qed.\n\n(** symmetric structures *)\n\nGlobal Instance Ge_preorder_of_Le_order :\n  Le_order -> \n  Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_inverse. apply le_preorder. Qed.\n\nGlobal Instance Ge_total_preorder_of_Le_total_order :\n  Le_total_order -> \n  Ge_total_preorder.\nProof using. constructor. rew_to_le. apply total_preorder_inverse. apply le_total_preorder. Qed.\n\nGlobal Instance Ge_preorder_of_Total_preorder :\n  Le_total_preorder -> \n  Ge_preorder.\nProof using. constructor. rew_to_le. apply preorder_inverse. apply le_preorder. Qed.\n\nGlobal Instance Ge_order_of_Le_total_order :\n  Le_total_order -> \n  Ge_order.\nProof using. constructor. rew_to_le. apply order_inverse. apply le_order. Qed.\n\nGlobal Instance Gt_strict_order_of_lt_strict_total_order :\n  Lt_strict_total_order -> \n  Gt_strict_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_order_inverse. apply lt_strict_order. Qed.\n\nGlobal Instance Gt_strict_order_of_Le_order :\n  Le_order -> \n  Gt_strict_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_order_inverse. apply lt_strict_order. Qed.\n\nGlobal Instance Gt_strict_total_order_of_Le_total_order :\n  Le_total_order -> \n  Gt_strict_total_order.\nProof using. constructor. rewrite gt_is_inverse_lt. apply strict_total_order_inverse. apply lt_strict_total_order. Qed.\n\n(** properties of le *)\n\nGlobal Instance Le_refl_of_Le_preorder :\n  Le_preorder -> \n  Le_refl.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance Le_trans_of_Le_preorder :\n  Le_preorder -> \n  Le_trans.\nProof using. intros [[Re Tr]]. constructor~. Qed.\n\nGlobal Instance Le_antisym_of_Le_order :\n  Le_order -> \n  Le_antisym.\nProof using. constructor. intros. apply* order_antisym. Qed.\n\nGlobal Instance Le_total_of_Le_total_order :\n  Le_total_order ->\n  Le_total.\nProof using. constructor. intros. apply* total_order_total. Qed.\n\n(** properties of ge *)\n\nGlobal Instance Ge_refl_of_Le_preorder :\n  Le_preorder -> \n  Ge_refl.\nProof using. constructor. rew_to_le. apply refl_inverse. apply le_refl. Qed.\n\nGlobal Instance Ge_trans_of_Le_preorder :\n  Le_preorder -> \n  Ge_trans.\nProof using. constructor. rew_to_le. apply trans_inverse. apply le_trans. Qed.\n\nGlobal Instance Ge_antisym_of_Le_order :\n  Le_order ->\n  Ge_antisym.\nProof using. constructor. rew_to_le. apply antisym_inverse. apply le_antisym. Qed.\n\nGlobal Instance Ge_total_of_Le_total_order :\n  Le_total_order ->\n  Ge_total.\nProof using. constructor. rew_to_le. apply total_inverse. apply le_total. Qed.\n\n(** properties of lt *)\n\nGlobal Instance Lt_irrefl_of_Le_order :\n  Le_order -> \n  Lt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply lt_strict_order. Qed.\n\nGlobal Instance Lt_trans_of_Le_order :\n  Le_order -> \n  Lt_trans.\nProof using. constructor. apply strict_order_trans. apply lt_strict_order. Qed.\n\n(** properties of gt *)\n\nGlobal Instance Gt_irrefl_of_Le_order :\n  Le_order -> \n  Gt_irrefl.\nProof using. constructor. apply strict_order_irrefl. apply gt_strict_order. Qed.\n\nGlobal Instance Gt_trans_of_Le_order :\n  Le_order -> \n  Gt_trans.\nProof using. constructor. apply strict_order_trans. apply gt_strict_order. Qed.\n\n(** mixed transitivity results *)\n\nGlobal Instance Lt_le_trans_of_Le_order : \n  Le_order -> \n  Lt_le_trans.\nProof using.\n  constructor. introv K L. rew_to_le. destruct K as [U V].\n  split~. apply* le_trans. intro_subst. apply V. apply* le_antisym.\nQed.\n\nGlobal Instance Le_lt_trans_of_Le_order :\n  Le_order ->\n  Le_lt_trans.\nProof using.\n  constructor. introv K L. rew_to_le. destruct L as [U V].\n  split~. apply* le_trans. intro_subst. apply V. apply* le_antisym.\nQed.\n\nGlobal Instance gt_ge_trans_of_Le_order :\n  Le_order -> \n  Gt_ge_trans.\nProof using.\n  constructor. introv K L. rew_to_le_lt. hnf in *. apply* le_lt_trans.\nQed.\n\nGlobal Instance ge_gt_trans_of_Le_order : \n  Le_order -> \n  Ge_gt_trans.\nProof using.\n  constructor. introv K L. rew_to_le_lt. hnf in *. apply* lt_le_trans.\nQed.\n(** conversion between operators *)\n\nGlobal Instance Ge_as_sle_of : \n  Ge_as_sle.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance Gt_as_slt_of : \n  Gt_as_slt.\nProof using. constructor. intros. rew_to_le. auto. Qed.\n\nGlobal Instance Ngt_as_sle_of_Le_total_order :\n  Le_total_order -> \n  Ngt_as_sle.\nProof using.\n  constructor. intros. rew_to_le. unfold strict. rew_logic. iff M.\n  destruct M.\n    forwards K:(inverse_strict_of_not (R:=le)); eauto.\n      apply le_total. apply (proj1 K).\n    subst. apply le_refl.\n  apply or_classic_l. intros P Q. apply P. apply* le_antisym.\nQed.\n\nGlobal Instance Nlt_as_ge_of_Le_total_order : \n  Le_total_order -> \n  Nlt_as_ge.\nProof using. constructor. intros. rew_to_le_lt. unfold inverse. apply ngt_as_sle. Qed.\n\nGlobal Instance Ngt_as_le_of_Le_total_order :\n  Le_total_order ->\n  Ngt_as_le.\nProof using. constructor. intros. rew_to_le_lt. unfold inverse. apply ngt_as_sle. Qed.\n\nGlobal Instance Nle_as_gt_of_Le_total_order : \n  Le_total_order ->\n  Nle_as_gt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold inverse.\n  rewrite <- ngt_as_sle. rewrite~ not_not_eq.\nQed.\n\nGlobal Instance Nge_as_lt_of_Le_total_order : \n  Le_total_order -> \n  Nge_as_lt.\nProof using.\n  constructor. intros. rew_to_le_lt. unfold inverse.\n  rewrite nle_as_gt. rewrite~ gt_is_inverse_lt.\nQed.\n\n(** inclusion between operators *)\n\nGlobal Instance Lt_to_le_of : \n  Lt_to_le.\nProof using. constructor. intros. rew_to_le. unfolds* strict. Qed.\n\nGlobal Instance Gt_to_ge_of : \n  Gt_to_ge.\nProof using. constructor. intros. rew_to_le. unfolds* inverse, strict. Qed.\n\nGlobal Instance Nle_to_sle_of_Le_total_order : \n  Le_total_order -> \n  Nle_to_sle.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* inverse, strict.\nQed.\n\nGlobal Instance Nle_to_slt_of_Le_total_order : \n  Le_total_order -> \n  Nle_to_slt.\nProof using.\n  constructor. introv K. rewrite nle_as_gt in K.\n  rew_to_le. unfolds* inverse, strict.\nQed.\n\n(** case analysis under no assumption *)\n\nGlobal Instance Case_eq_lt_gt_of_Le_total_order : \n  Le_total_order -> \n  Case_eq_lt_gt.\nProof using.\n  introv K. constructor. intros.\n  lets [(M1&M2)|[M|(M1&M2)]]: (total_order_lt_or_eq_or_gt le_total_order x y).\n    rewrite le_is_rclosure_lt in M1 by applys* total_order_refl. destruct* M1.\n    autos*.\n    rewrite le_is_rclosure_lt in M1 by applys* total_order_refl. destruct* M1.\nQed.\n\nGlobal Instance Case_eq_lt_slt_of_Le_total_order :\n  Le_total_order -> \n  Case_eq_lt_slt.\nProof using.\n  constructor. intros. pattern lt at 2. rewrite lt_is_inverse_gt.\n  apply case_eq_lt_gt.\nQed.\n\nGlobal Instance Case_le_gt_of_Le_total_order : \n  Le_total_order -> \n  Case_le_gt.\nProof using.\n  constructor. intros.\n  rewrite le_is_rclosure_lt by applys* total_order_refl. rewrite rclosure_eq.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance Case_eq_lt_ge_of_Le_total_order :  \n  Le_total_order ->  \n  Case_lt_ge.\nProof using.\n  constructor. intros.\n  rewrite ge_is_rclosure_gt by applys* total_order_refl. rewrite rclosure_eq.\n  branches (total_order_lt_or_eq_or_gt le_total_order x y); eauto.\nQed.\n\nGlobal Instance Case_le_slt_of_Le_total_order :  \n  Le_total_order ->  \n  Case_le_slt.\nProof using. constructor. intros. rewrite lt_is_inverse_gt. apply case_le_gt. Qed.\n\nGlobal Instance Case_eq_lt_sle_of_Le_total_order :  \n  Le_total_order ->  \n  Case_lt_sle.\nProof using. constructor. intros. rewrite le_is_inverse_ge. apply case_lt_ge. Qed.\n\n(** case analysis under one assumption *)\n\nGlobal Instance Neq_case_lt_gt_of_Le_total_order :  \n  Le_total_order ->  \n  Neq_case_lt_gt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance Neq_case_lt_slt_of_Le_total_order :  \n  Le_total_order ->  \n  Neq_case_lt_slt.\nProof using. constructor. intros. destruct* (case_eq_lt_gt x y). Qed.\n\nGlobal Instance Le_case_eq_lt_of_Le_total_order :  \n  Le_total_order ->  \n  Le_case_eq_lt.\nProof using. constructor. intros. rew_to_le. unfold strict. tests*: (x = y). Qed.\n\nGlobal Instance Ge_case_eq_gt_of_Le_total_order :  \n  Le_total_order ->  \n  Ge_case_eq_gt.\nProof using. constructor. intros. rew_to_le. unfold inverse, strict. tests*: (x = y). Qed.\n\n(** case analysis under two assumptions *)\n\nGlobal Instance Le_neq_to_lt_of_Le_total_order :  \n  Le_total_order ->  \n  Le_neq_to_lt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance Ge_neq_to_gt_of_Le_total_order :  \n  Le_total_order ->  \n  Ge_neq_to_gt.\nProof using. constructor. intros. rew_to_le. hnfs*. Qed.\n\nGlobal Instance Nlt_nslt_to_eq_of_Le_total_order :  \n  Le_total_order ->  \n  Nlt_nslt_to_eq.\nProof using. constructor. intros. branches* (case_eq_lt_gt x y). Qed.\n\n(** contradiction from case analysis *)\n\nGlobal Instance Lt_ge_false_of_Le_total_order :  \n  Le_total_order ->  \n  Lt_ge_false.\nProof using. constructor. introv H1 H2. rewrite~ <- nlt_as_ge in H2. Qed.\n\nGlobal Instance Lt_gt_false_of_Le_total_order :  \n  Le_total_order ->  \n  Lt_gt_false.\nProof using.\n  constructor. introv H1 H2. rewrite~ <- nle_as_gt in H2.\n  apply H2. apply* lt_to_le.\nQed.\n\nGlobal Instance Lt_slt_false_of_Le_total_order :\n  Le_total_order ->  \n  Lt_slt_false.\nProof using.\n  constructor. introv H1 H2. rewrite <- gt_as_slt in H2.\n  apply* lt_gt_false.\nQed.\n\nEnd Instances.\n\n(** -- Other lemmas needs arguments to be implicit? *)\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Boolean comparison *)\n\nModule BooleanComparison.\nOpen Scope comp_scope.\n\n(** Additional notation for reflected boolean comparison.\n    Use [Open Scope comp_scope_reflect] to use them. *)\n\nNotation \"x ''<=' y\" := (isTrue (@le _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''>=' y\" := (isTrue (@ge _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''<' y\" := (isTrue (@lt _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\nNotation \"x ''>' y\" := (isTrue (@gt _ _ x y))\n  (at level 70, no associativity) : comp_scope_reflect.\n\nEnd BooleanComparison.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Order on relations and on predicates *)\n\nLemma order_rel_incl : forall A B,\n  order (@rel_incl A B).\nProof using. \n  hint refl_rel_incl, antisym_rel_incl, trans_rel_incl.\n  constructors*.\nQed.\n\nLemma order_pred_incl : forall A B,\n  order (@rel_incl A B).\nProof using. \n  hint refl_rel_incl, antisym_rel_incl, trans_rel_incl.\n  constructors*.\nQed.\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/LibOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7623183992800475}}
{"text": "(* We consider the discrete plan the coordinate system of which \n    is based on Z *)\nRequire Import List  ZArith  Bool.\nOpen Scope Z_scope.\nRequire Import Relations  Setoid  Morphisms  RelationClasses.\nRequire Import EMonoid.\n\n\n\n(** Types for representing routes in the dicrete  plane *)\n\nInductive direction : Type := North | East | South | West.\nDefinition route := list direction.\n\nRecord Point : Type :=\n {Point_x : Z;\n  Point_y : Z}.\n\nDefinition Point_O := Build_Point 0 0.\n\nDefinition translate (dx dy:Z) (P : Point) :=\n  Build_Point (Point_x P + dx) (Point_y P + dy).\n\n(** Equality test  between Points *)\n\nDefinition Point_eqb (P P':Point) :=\n   Zeq_bool (Point_x P) (Point_x P') &&\n   Zeq_bool (Point_y P) (Point_y P').\n\n(* Prove the correctness of Point_eqb *)\n\nLemma Point_eqb_correct : forall p p', Point_eqb p p' = true <->\n                                       p = p'.\nProof.\n destruct p;destruct p';simpl;split.\n -  unfold Point_eqb; simpl; rewrite andb_true_iff; destruct 1.\n    repeat rewrite <- Zeq_is_eq_bool in *.\n    now  rewrite H, H0.\n -  injection 1;intros H0 H1;rewrite H0, H1; unfold Point_eqb; simpl;\n    rewrite andb_true_iff;repeat rewrite <- Zeq_is_eq_bool; now split.\nQed.\n\n(**  (move P r) follows the route r starting from P *)\n\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\nDefinition route_equiv : relation route :=\n  fun r r' => forall P:Point , move r P = move  r' P.\n\nInfix \"=r=\" := route_equiv (at level 70):type_scope.\n\nExample Ex1 : East::North::West::South::East::nil =r= East::nil.\nProof.\n intro P;destruct P;simpl; unfold route_equiv, translate;simpl;f_equal; ring.\nQed.\n\nLemma route_equiv_refl : reflexive _ route_equiv.\nProof.  intros r p;reflexivity. Qed.\n\nLemma route_equiv_sym : symmetric _ route_equiv.\nProof.  intros r r' H p; symmetry;apply H. Qed.\n\nLemma route_equiv_trans : transitive _ route_equiv.\nProof.  intros r r' r'' H H' p; rewrite H; apply H'. Qed.\n\nInstance route_equiv_Equiv : Equivalence  route_equiv.\nProof.\nsplit;  [apply route_equiv_refl |  apply route_equiv_sym |  apply route_equiv_trans].\nQed.\n\n\n(* Cons and app are Proper functions w.r.t. route_equiv *)\n\nLemma route_cons : forall r r' d, r =r= r' -> d::r =r= d::r'.\nProof. \n intros r r' d H P;destruct d;simpl;rewrite H;reflexivity.\nQed.\n\nExample Ex2 :  South::East::North::West::South::East::nil =r= South::East::nil.\nProof. apply route_cons;apply Ex1. Qed.\n\n\nInstance cons_route_Proper (d:direction): \n    Proper (route_equiv ==> route_equiv) (cons d) .\nProof.\n intros r r' H ; now apply route_cons.\nQed.\n\n\n(**  cons_route_Proper allows to replace a route with an =r= equivalent one\n     in a context composed by \"cons\" *)\n\nExample SW : forall r r', r =r= r' ->\n                  South::West::r =r= South::West::r'.\nProof. \n intros r r' H; now rewrite H.\nQed.\n\n\nInstance move_Proper  : Proper (route_equiv ==> @eq Point ==> @eq Point) move . \nProof.\n intros r r' Hr_r' p q Hpq; rewrite Hpq; apply Hr_r'.\nQed.\n\nExample length_not_Proper : ~Proper (route_equiv ==> @eq nat) (@length _).\nProof.\n intro H; generalize (H (North::South::nil) nil);simpl;intro H0.\n discriminate H0.\n -  intro P;destruct P; simpl;unfold translate; simpl;f_equal;simpl;ring.\nQed.\n\n\n\nLemma route_compose : 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\nInstance app_route_Proper : Proper (route_equiv==>route_equiv ==> route_equiv)\n (@app direction).\nProof.\n intros r r' H r'' r''' H' P.\n repeat rewrite route_compose; rewrite H, H';reflexivity.\nQed.\n\n\nExample Ex3 : forall r, North::East::South::West::r =r= r.\nProof. \n intros r P;destruct P;simpl; \n  unfold route_equiv, translate;simpl;do 2 f_equal;ring.\nQed.\n\nExample Ex4 : forall r r', r =r= r' -> \n                North::East::South::West::r =r= r'.\nProof. intros r r' H. now rewrite Ex3. Qed.\n\nExample Ex5 : forall r r',  r++ North::East::South::West::r' =r= r++r'.\nProof. intros r r'; now rewrite Ex3. Qed.\n\n\nLemma translate_comm : forall dx dy dx' dy' P,\n    translate dx dy (translate dx' dy' P) =\n    translate dx' dy' (translate dx dy P).\nProof.\n  unfold translate; simpl; intros; f_equal; ring.\n Qed.\n\nLemma move_translate : forall r P dx dy , move r (translate dx dy P) =\n                                                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 : forall r r' P  , move r (move r' P)  =\n                                   move r' (move r P) .\nProof.\ninduction 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 *)\n\nLemma route_equiv_Origin : forall r r', r =r= r' <->\n                                        move r Point_O  = move r' Point_O .\nProof.\nsplit;intro H.\n- now rewrite H.\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.\nQed.\n\nDefinition route_eqb r r' : bool :=\n   Point_eqb (move r Point_O) (move r' Point_O).\n\n(**  ... we can now prove route_eqb's  correctness *)\n\nLemma route_equiv_equivb : forall r r', route_equiv r r' <->\n                                        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  *)\n\nExample Ex1' : East::North::West::South::East::nil =r= East::nil.\nProof. route_eq_tac. Qed.\n\nLemma north_south_0 : forall r, North::South::r =r=  r.\nProof.\n intro r; change ((North::South::nil)++ r =r=  r).\n setoid_replace (North :: South :: nil) with  (@nil direction);\n  [reflexivity |route_eq_tac ]. \nQed.\n\nLemma north_south_simpl : forall r r', r++ North::South::r' =r=  r++r'.\nProof.\n induction r as [|a r'];simpl.\n -  intro r';rewrite north_south_0;reflexivity.  \n -  intros r1;now rewrite IHr' .\nQed.\n\n\n(* we want to prove that, if some route contains two steps in opposite\n   directions, then the route can be shortened *)\n\nDefinition opposite (d d':direction):= match d,d' with \n        | North,South => True\n        | South, North => True\n        | East, West => True\n        | West, East => True\n        | _, _ => False\nend.\n\n\nInductive  Useless_steps_in (r:route) : Type :=\nUseless_i: forall r0 r1 r2 d d1,  r = r0++(d::r1)++(d1::r2) ->\n                                  opposite d d1 ->\n                                  Useless_steps_in r.\n\nLemma opposite_cons : forall d d1 r, opposite d d1 -> d1::d::r =r= r.\nProof.\n intros d d1 r H;destruct d,d1;simpl ;try contradiction ;\n intro P;destruct P;simpl;auto; unfold translate;simpl; repeat f_equal;ring.\nQed.\n\nLemma cons2_comm : forall d d' r, d::d'::r =r= d'::d::r.\nProof.\n intros d d' r; change ((d::nil)++(d'::nil)++r =r= (d'::nil)++(d::nil)++r).\n do 2  rewrite <- app_ass.\n rewrite (app_comm  (d :: nil) (d'::nil));reflexivity.\nQed.\n\n\nLemma Useless_steps_shorter (r:route) :\n  Useless_steps_in r -> {r' : route | r =r= r' /\\ (length r' < length r)%nat}.\nProof.\n intro H;destruct H as [r0 r1 r2 d d1 H1 H2]. \n exists (r0 ++ r1 ++ r2).\n split.\n -  subst r; replace (r0 ++ (d :: r1) ++ d1 :: r2) with\n         (r0 ++ ((d::nil) ++ r1) ++ ((d1::nil)++r2))  by (simpl;auto).\n     apply app_route_Proper;[reflexivity|].\n     rewrite <- app_ass.\n     apply app_route_Proper;[|reflexivity].\n     transitivity ((d1::nil)++(d::r1)).\n     rewrite app_comm; reflexivity.\n      simpl;rewrite opposite_cons;[reflexivity|trivial].\n -  subst r; repeat (simpl;repeat  rewrite app_length); omega.\nQed.\n\n\n(** Monoid structure on routes *)\n\nInstance Route : EMonoid route_equiv (@app _)  nil .\nProof.\nsplit.\n- apply route_equiv_Equiv.\n- apply app_route_Proper.\n- intros x y z P;repeat rewrite  route_compose; trivial.\n-  intros x  P;repeat rewrite  route_compose; trivial.\n- intros x  P;repeat rewrite  route_compose; trivial.\nQed.\n\nExample Ex6 : forall n, Epower (South::North::nil) n =r= nil.\nProof. \n induction n as [| p IHp];simpl;[reflexivity|].\n rewrite IHp; route_eq_tac.\nQed.\n\nInstance AbelianRoute : Abelian_EMonoid Route. \n  split;  apply app_comm.\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", "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/Lost_in_NY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7623183911360579}}
{"text": "Require Import NArith.\nRequire Import PolTac.\n\nOpen Scope N_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  y < 0 -> x + y < x.\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test3 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_test4 x y z :\n  x + y * (y + z) = 2 * z ->\n  2 * x + y * (y + z) = x + z + z.\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem polf_test1 x y :\n  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.\nauto.\nQed.\n\nTheorem polr_test1 x y z :\n  x + z < y -> x + y + z < 2 * y.\nProof.\nintros H.\npolr H.\npols.\nauto.\npols.\nauto.\nQed.\n", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/Nex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7622882400518993}}
{"text": "(**\n * PSet 1: Functional Programming in Coq\n\n  This lab is designed as a file that you should download and complete in a Coq IDE.\n  Before doing that, you need to install Coq.  The installation instructions\n  are on the course website.\n*)\n\n(* Exercise: mult2 [10 points].\n   Define a function that multiplies its input by 2.\n   What is the function's type?\n   What is the result of computing the function on 0?  On 3110?\n*)\n\n(* Exercise: xor [10 points].\n   Define a function that computes the xor of two [bool] inputs.\n   Do this by pattern matching on the inputs.\n   What is the function's type?\n   Compute all four possible combinations of inputs to test your function.\n*)\n\n(* Exercise: is_none [20 points].\n   Define a function that returns [true] if its input is [None], and [false] otherwise.\n   Your function's type should be [forall A : Type, option A -> bool].\n   That means the function will actually need to take two inputs:\n     the first has type [Type], and the second is an option.\n   Hint:  model your solution on [is_empty] in the notes for this lecture.\n*)\n\nRequire Import List.\nImport ListNotations.\n\n(* Exercise: double_all [20 points].\n   There is a function [map] that was imported by the [Require Import List] command above.\n   First, check its type with [Check map].  Explain that type in your own words.\n   Second, print it with [Print map].  Note at the end of that which arguments are _implicit_.\n   For a discussion of what implicit means, see the notes for this lecture.\n   Third, use map to write your own function, which should double (i.e., multiply by 2)\n   every value of a list.\n   For example, [double_all [0;2;10]] should be [[0;4;20]].\n*)\n\n(* Exercise: sum [20 points]\n   Write a function that sums all the natural numbers in a list.\n   Implement this two different ways:\n   - as a recursive function, using the [Fixpoint] syntax.\n   - as a nonrecursive function, using [Definition] and an application of [fold_left].\n*)\n\nInductive day : Type :=\n  | sun : day\n  | mon : day\n  | tue : day\n  | wed : day\n  | thu : day\n  | fri : day\n  | sat : day.\n\nDefinition next_day d :=\n  match d with\n  | sun => mon\n  | mon => tue\n  | tue => wed\n  | wed => thu\n  | thu => fri\n  | fri => sat\n  | sat => sun\n  end.\n\n(* Exercise: thu after wed [20 points].\n   State a theorem that says [thu] is the [next_day] after [wed].\n   Write down in natural language how you would informally explain\n   to a human why this theorem is true.\n   ---> Don't skip this \"natural language\" part of the exercise;\n        it's crucial to develop intuition before proceeding.\n   Prove the theorem in Coq.\n*)\n\n(* Exercise: wed before thu [30 points].\n   Below is a theorem that says if the day after [d] is [thu], then\n   [d] must be [wed].\n   Write down in natural language how you would informally explain\n   to a human why this theorem is true.\n   ---> Don't skip this \"natural language\" part of the exercise;\n        it's crucial to develop intuition before proceeding.\n   Prove the theorem in Coq.  To do that, delete the [Abort]\n   command, which tells Coq to discard the theorem,\n   then fill in your own proof.\n*)\n\nTheorem wed_proceeds_thu : forall d : day, next_day d = thu -> d = wed.\nAbort.\n\n(* Exercise: tl_opt [20 points].\n   Define a function [tl_opt] such that [tl_opt lst] return [Some t] if [t] is the tail of [lst],\n   or [None] if [lst] is empty.\n   We have gotten you started by providing an obviously incorrect definition, below; you should\n   replace the body of the function with a correct definition.\n*)\n\nDefinition tl_opt {A : Type} (lst : list A) : option (list A) :=\n  None.\n\n(* Here is a new tactic: [rewrite x].  If [H: x = e] is an assumption in the\n   proof state, then [rewrite H] replaces [x] with [e] in the subgoal being proved.  For example,\n   here is a proof that incrementing 1 produces 2: *)\n\nTheorem inc1_is_2 : forall n, n=1 -> (fun x => x+1) n = 2.\nProof.\n  intros n n_is_1. rewrite n_is_1. trivial.\nQed.\n\n(* Exercise: tl_opt correct [20 points].\n   Using [rewrite], prove the following theorems. For both, first explain in natural language\n   why the theorem should hold, before moving on to prove it with Coq. *)\n\nTheorem nil_implies_tlopt_none :\n  forall A : Type, forall lst : list A,\n  lst = nil -> tl_opt lst = None.\nAbort.\n\nTheorem cons_implies_tlopt_some :\n  forall {A : Type} (h:A) (t : list A) (lst : list A),\n  lst = h::t -> tl_opt lst = Some t.\nAbort.\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/pset1/pset1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.7622855596985353}}
{"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 < 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 < End Playground2.\nModule Playground2 is defined\n\nCoq < Fixpoint exp (base power : nat) : nat := match power with | O => S O | S p => mult base (exp base p) end.\nexp is defined\nexp is recursively defined (decreasing on 2nd argument)\n\nCoq < Notation \"x + y\" := (plus x y) (at level 50 , left associativity) : nat_scope.\n\nCoq < Notation \"x - y\" := (minus x y) (at level 50, left associativity) : nat_scope.\n\nCoq < Check ((0 + 1) + 1).\n0 + 1 + 1\n     : nat\n\nCoq < Compute 1 + 2.\n     = 3\n     : nat\n\nCoq < Compute 4 - 1.\n     = 3\n     : nat\n\nCoq < Compute 4 * 2.\n     = 8\n     : nat\n\nCoq < Fixpoint beq_nat (n m : nat) : bool := match n with | O => match m with | O => true | S m' => false end | S n' => match m with | O => false | S m' => beq_nat n' m' end end.\nbeq_nat is defined\nbeq_nat is recursively defined (decreasing on 1st argument)\n\nCoq < Fixpoint leb (n m : nat) : bool := match n with | O => true | S n' => match m with | O => false | S m' => leb n' m' end end.\nleb is defined\nleb is recursively defined (decreasing on 1st argument)\n\nCoq < Example test_leb1: (leb 2 2) = true.\n1 subgoal\n  \n  ============================\n  leb 2 2 = true\n\ntest_leb1 < Proof.\n1 subgoal\n  \n  ============================\n  leb 2 2 = true\n\ntest_leb1 < simpl.\n1 subgoal\n  \n  ============================\n  true = true\n\ntest_leb1 < reflexivity.\nNo more subgoals.\n\ntest_leb1 < Qed.\nProof.\nsimpl.\nreflexivity.\n\nQed.\ntest_leb1 is defined\n\nCoq < Example test_leb2: (leb 2 4) = true.\n1 subgoal\n  \n  ============================\n  leb 2 4 = true\n\ntest_leb2 < Proof.\n1 subgoal\n  \n  ============================\n  leb 2 4 = true\n\ntest_leb2 < simpl.\n1 subgoal\n  \n  ============================\n  true = true\n\ntest_leb2 < reflexivity.\nNo more subgoals.\n\ntest_leb2 < Qed.\nProof.\nsimpl.\nreflexivity.\n\nQed.\ntest_leb2 is defined\n\nCoq < Example test_leb3: (leb 4 2) = false.\n1 subgoal\n  \n  ============================\n  leb 4 2 = false\n\ntest_leb3 < Proof.\n1 subgoal\n  \n  ============================\n  leb 4 2 = false\n\ntest_leb3 < simpl.\n1 subgoal\n  \n  ============================\n  false = false\n\ntest_leb3 < reflexivity.\nNo more subgoals.\n\ntest_leb3 < Qed.\nProof.\nsimpl.\nreflexivity.\n\nQed.\ntest_leb3 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/basics008.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.7622516843101055}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq. \n\n\n\n(** Coq's built-in logic is very small: the only primitives are\n    [Inductive] definitions, universal quantification ([forall]), and\n    implication ([->]), while all the other familiar logical\n    connectives -- conjunction, disjunction, negation, existential\n    quantification, even equality -- can be encoded using just these.\n\n    This chapter explains the encodings and shows how the tactics\n    we've seen can be used to carry out standard forms of logical\n    reasoning involving these connectives. *)\n\n(* ########################################################### *)\n(** * Propositions *)\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 \n\n(** In Coq, the type of things that can (potentially) \n    be proven is [Prop]. *)\n\n(** Here is an example of a provable proposition: *)\n\nCheck (3 = 3).\n(* ===> Prop *)\n\n(** Here is an example of an unprovable proposition: *)\n\nCheck (forall (n:nat), n = 2).\n(* ===> Prop *)\n\n(** Recall that [Check] asks Coq to tell us the type of the indicated \n  expression. *)\n\n(* ########################################################### *)\n(** * Proofs and Evidence *)\n\n(** In Coq, propositions have the same status as other types, such as\n    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit\n    the type [nat], a Coq proposition [P] is inhabited by its\n    _proofs_.  We will refer to such inhabitants as _proof term_ or\n    _proof object_ or _evidence_ for the truth of [P]. \n\n    In Coq, when we state and then prove a lemma such as:\n\nLemma silly : 0 * 3 = 0.  \nProof. reflexivity. Qed.\n\n    the tactics we use within the [Proof]...[Qed] keywords tell Coq\n    how to construct a proof term that inhabits the proposition.  In\n    this case, the proposition [0 * 3 = 0] is justified by a\n    combination of the _definition_ of [mult], which says that [0 * 3]\n    _simplifies_ to just [0], and the _reflexive_ principle of\n    equality, which says that [0 = 0].\n\n\n*)\n\n(** *** *)\n\nLemma silly : 0 * 3 = 0.\nProof. reflexivity. Qed.\n\n(** We can see which proof term Coq constructs for a given Lemma by\nusing the [Print] directive: *)\n\nPrint silly.\n(* ===> silly = eq_refl : 0 * 3 = 0 *)\n\n(** Here, the [eq_refl] proof term witnesses the equality. (More on equality later!)*)\n\n(** ** Implications _are_ functions *)\n\n(** Just as we can implement natural number multiplication as a\nfunction:\n\n[\nmult : nat -> nat -> nat \n]\n\nThe _proof term_ for an implication [P -> Q] is a _function_ that takes evidence for [P] as input and produces evidence for [Q] as its output.\n*)     \n\nLemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.\nProof. intros H. reflexivity. Qed.\n\n(** We can see that the proof term for the above lemma is indeed a\nfunction: *)\n\nPrint silly_implication.\n(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl\n     : 1 + 1 = 2 -> 0 * 3 = 0 *)\n\n(** ** Defining Propositions *)\n\n(** Just as we can create user-defined inductive types (like the\n    lists, binary representations of natural numbers, etc., that we\n    seen before), we can also create _user-defined_ propositions.\n\n    Question: How do you define the meaning of a proposition?  \n*)\n\n(** *** *)\n\n(** The meaning of a proposition is given by _rules_ and _definitions_\n    that say how to construct _evidence_ for the truth of the\n    proposition from other evidence.\n\n    - Typically, rules are defined _inductively_, just like any other datatype.\n\n    - Sometimes a proposition is declared to be true without substantiating evidence.  Such propositions are called _axioms_.  \n\n\n    In this, and subsequence chapters, we'll see more about how these\n    proof terms work in more detail.\n*)\n\n(* ########################################################### *)\n(** * Conjunction (Logical \"and\") *)\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(** 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(** ** \"Introducing\" Conjuctions *)\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  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  apply conj.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.  Qed.\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (0 = 0) /\\ (4 = mult 2 2).\nProof.\n  split.\n    Case \"left\". reflexivity.\n    Case \"right\". reflexivity.  Qed.\n\n(** ** \"Eliminating\" conjunctions *)\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. inversion H as [HP HQ]. 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\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\". split.\n    + apply HP.\n    + apply HQ.\n  - Case \"right\". apply HR.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Iff *)\n\n(** The handy \"if and only if\" connective is just the conjunction of\n    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) \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.\n  split.\n  - intros H. apply H.\n  - intros H. 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 H I.\n  destruct H as [H0 H1].\n  destruct I as [H2 H3].\n  split.\n  - intros X. apply H2. apply H0. apply X.\n  - intros X. apply H1. apply H3. apply X.\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\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 (Logical \"or\") *)\n\n(** ** Implementing 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(** *** *)\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  destruct 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\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  destruct H.\n  destruct H0.\n  - left. apply H0.\n  - destruct H.\n    + left. apply H.\n    + right. split. apply H. apply H0.\nQed.\n\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  split. apply or_distributes_over_and_1. apply or_distributes_over_and_2.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\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_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. destruct b.\n  - simpl in H. right. apply H.\n  - left. reflexivity.\nQed.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros. destruct b.\n  - left. reflexivity.\n  - simpl in H. right. apply H.\nQed.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros. destruct b.\n  - inversion H. \n  - split. reflexivity. apply H.\nQed.\n(** [] *)\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\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  destruct 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(** *** *)\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(* #################################################### *)\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, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True := PTrue.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    used fairly rarely. By itself, it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. But it can be useful when defining\n    complex [Prop]s using conditionals, or as a parameter to \n    higher-order [Prop]s. *)\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\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(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H G.\n  unfold not in G. unfold not.\n  intro F. apply G. apply H. apply F.\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. unfold not. intros. destruct H.\n  apply H0. apply H.\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(** *** Constructive logic *)\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     from evidence for [P]. *) \n  Abort.\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 :=\n  forall P Q:Prop, \n    (P->Q) -> (~P\\/Q).\n\nTheorem pierce_classic : peirce -> classic.\nProof.\n  intros. unfold peirce in H.\n  unfold classic. intros.\n  unfold not in H0. apply H with False. intros. apply H0 in H1. destruct H1.\nQed.\n\nTheorem classic_excluded_middle : classic -> excluded_middle.\nProof.\n  unfold classic. unfold excluded_middle. intros.\n  apply H. unfold not. intros. apply H0. right. intros.\n  apply H0. left. apply H1.\nQed.\n\nTheorem excluded_middle_de_morgan : excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle. unfold de_morgan_not_and_not. intros.\n  unfold not in H0. destruct (H P).\n  - left. apply H1.\n  - right. destruct (H Q).\n    + apply H2.\n    + destruct H0. split. apply H1. apply H2.\nQed.\n\nTheorem de_morgan_not_implies_to_or : de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not. unfold implies_to_or. intros.\n  destruct (H (~P) Q).\n  - unfold not. intros. destruct H1. apply contrapositive in H0.\n    + apply H1. apply H0.\n    + unfold not. apply H2.\n  - left. apply H1.\n  - right. apply H1.\nQed.\n\nTheorem implies_to_or_peirce : implies_to_or -> peirce.\nProof.\n  unfold implies_to_or. unfold peirce. intros H. intros.\n  destruct (H P P).\n  - intros X. apply X.\n  - apply H0. intros. destruct H1. apply H2.\n  - apply H1.\nQed.\n\n  \n(** [] *) \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), ~ ~ (P \\/ ~ P).  \nProof.\n  intros. unfold not. intros.\n  apply H. right. intros. apply H. left. apply H0.\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\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\n\n(** *** *)\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  intro n.\n  induction n as [|n'].\n  - destruct m. intros. destruct H. reflexivity. reflexivity.\n  - destruct m. reflexivity. intros. simpl. unfold not in H.\n    apply IHn'. unfold not. intros. apply H. rewrite H0. reflexivity.\nQed.\n(** [] *)\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  unfold not. intros. rewrite H0 in H. rewrite <- beq_nat_refl in H.\n  inversion H.\nQed.\n\n(** [] *)\n\n\n\n\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n", "meta": {"author": "bennofs", "repo": "software-foundations", "sha": "4278136ca18c0909603cab17fbc0c190dedf69c7", "save_path": "github-repos/coq/bennofs-software-foundations", "path": "github-repos/coq/bennofs-software-foundations/software-foundations-4278136ca18c0909603cab17fbc0c190dedf69c7/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.9219218428996603, "lm_q1q2_score": 0.7621636568004084}}
{"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 : Type} (f : A ->  A) (k : nat) (a : A) {struct k} : A :=\n match k with   0%nat => a\n               | S p => f (iter f p a) end.\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 }).\nProof. \n induction  x as [x IHx] using (well_founded_induction (Zwf_well_founded 0)).\n unfold factZ_it_F;case_eq (Z_lt_le_dec x 0).\n - intros h heq1; exists 0, 1%nat.\n   intros k; case k.\n   + intros; omega.\n   + intros; simpl; rewrite heq1; auto.\n - intros h heq2; case_eq (Z_eq_dec 0 x).\n   + intros h' heq3; exists 1, 1%nat.\n   intros k; case k.\n     * intros; omega.\n     * intros; simpl; rewrite heq2;  simpl in heq3; rewrite heq3; auto.\n   + intros h'' heq4; assert (HZwf: Zwf 0 (x - 1) x).\n     * clear heq2 heq4; unfold Zwf; omega.\n      * destruct (IHx (x - 1) HZwf) as [v Hex]; exists (x * v).\n        destruct Hex as [p Heq]; exists (S p); intros k; case k.\n         intros; omega.\n         simpl; intros k' hltk g; rewrite heq2; simpl in heq4;rewrite heq4.\n         fold factZ_it_F;  rewrite Heq; [reflexivity | omega].  \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.\n Proof. \n  intros x; unfold factZ_it;\n  destruct  (factZ_terminates x) as [v [p Heq]];\n  destruct (factZ_terminates (x - 1)) as [v' [p' Heq']].\n  rewrite <- (Heq (S ((p + p') + 1)) factZ_it).\n  - simpl iter; unfold factZ_it_F.\n    case (Z_lt_le_dec x 0); auto.\n    case (Z_eq_dec 0 x); auto.\n    rewrite <- (Heq' ((p + p') + 1)%nat factZ_it).\n    +  reflexivity.\n    +  omega.\n  - omega.\nQed.\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/ch15_general_recursion/SRC/factZ_it.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7621562810175689}}
{"text": "Require Import ZArith.\nRequire Import List.\n\nInductive bop: Set := Badd.\nInductive expr: Set :=\n| e_cst: Z -> expr\n| e_bin: bop -> expr -> expr -> expr.\nFixpoint expr_eval (e: expr): Z :=\nmatch e with\n| e_cst i => i\n| e_bin Badd e1 e2 => Zplus (expr_eval e1) (expr_eval e2)\nend.\nInductive inst: Set :=\n| Ipush: Z -> inst\n| Iadd: inst.\nFixpoint step (s: list Z) (i: inst): list Z :=\nmatch s, i with\n| _, Ipush z => z :: s\n| v :: u :: t, Iadd => (Zplus v u) :: t\n| _, ladd => nil\nend.\nFixpoint fold_left (l: list inst) (s: list Z): list Z :=\nmatch l with\n| nil => s\n| i :: t => fold_left t (step s i)\nend.\nFixpoint exec (l: list inst): list Z :=\nmatch (fold_left l nil) with\n| v :: nil => v :: nil\n| _ => nil\nend.\nFixpoint compile (e: expr): list inst :=\nmatch e with\n| e_cst i => (Ipush i) :: nil\n| e_bin Badd e1 e2 => (compile e1) ++ (compile e2) ++ (Iadd :: nil)\nend.\n\nLemma partial_exec : forall e: expr, forall l1: list inst, forall l2: list Z, fold_left ((compile e) ++ l1) l2 = fold_left l1 ((expr_eval e) :: l2).\nProof.\nintros.\ninduction e.\nsimpl.\n\n\nLemma eq_eval_exec_compile_offset : forall l: list Z, forall e: expr, (expr_eval e) :: l = (fold_left (compile e) nil) ++ l.\nProof.\nintros.\ninduction e.\nsimpl.\ntrivial.\ninduction b.\nsimpl.\n\nTheorem eq_eval_exec_compile: forall e: expr, (expr_eval e) :: nil = exec (compile e).\nProof.\n", "meta": {"author": "aymericbouzy", "repo": "lambda-calculus", "sha": "66ac62175b3f70f723f1bca9bcdc26fb1c184ef2", "save_path": "github-repos/coq/aymericbouzy-lambda-calculus", "path": "github-repos/coq/aymericbouzy-lambda-calculus/lambda-calculus-66ac62175b3f70f723f1bca9bcdc26fb1c184ef2/stack_compile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7621562806131241}}
{"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 OrderedTypeEx.\nRequire 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 FSetFacts 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": "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/amm11262/ascii_format/AMM11262.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7621562687393207}}
{"text": "Require Import Arith.\n\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n  intros.\n  apply plus_lt_compat_r.\n  apply H.\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_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7621492643086799}}
{"text": "Require Export prop_j.\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 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.\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 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 [HQ HR]].\n  apply conj.\n  apply conj.\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 as [| n'].\n  Case \"n = 0\".\n    apply conj.\n    SCase \"left\".\n      intros. apply ev_0.\n    SCase \"right\".\n      intros. inversion H.\n  Case \"n = S n'\".\n    inversion IHn'.\n    apply conj.\n    SCase \"left\".\n      intros. apply H0. apply H1.\n    SCase \"right\".\n      unfold even. simpl. intros. apply ev_SS. \n      apply H. unfold even. apply H1.\nQed.\n\nDefinition conj_fact : forall P Q R,\n  P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) (H : P /\\ Q) (H0 : Q /\\ R) =>\n    match H with\n    | conj _ _ HP HQ =>\n      match H0 with\n      | conj _ _ HQ HR => conj P R HP HR\n      end\n    end.\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\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros. 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  intros. inversion H. inversion H0.\n  split.\n    Case \"->\". intros. apply H3. apply H1. apply H5.\n    Case \"<-\". intros. apply H2. apply H4. apply H5.\nQed.\n\nSearchAbout MyProp.\nPrint iff.\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 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\nDefinition or_commut_object : forall P Q : Prop, P \\/ Q -> Q \\/ P := \n  fun (P Q : Prop) (H : P \\/ Q) =>\n    match H with\n    | or_introl _ _ HP => or_intror _ _ HP\n    | or_intror _ _ HQ => or_introl _ _ HQ\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  inversion H0 as [HP | HQ].\n    SCase \"left\". left. apply HP.\n    SCase \"right\".\n      inversion H1 as [HP | HR].\n        Case \"left\". left. apply HP.\n        Case \"right\".\n          right. apply conj. apply HQ. apply HR.\nQed.\n\nTheorem or_distrubutes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros. unfold iff. apply conj.\n    Case \"->\".\n    intros. inversion H.\n      SCase \"left\".\n      apply conj. left. apply H0. left. apply H0.\n      SCase \"right\".\n      inversion H0.\n      apply conj. right. apply H1. right. apply H2.\n    Case \"<-\".\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  (* 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. unfold andb in H. destruct b.\n    Case \"b = true\". right. apply H.\n    Case \"b = false\". left. apply H.\nQed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros. unfold orb in H. destruct b.\n    Case \"b = true\". left. reflexivity.\n    Case \"b = false\". right. apply H.\nQed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros. unfold orb in H. destruct b.\n    Case \"b = true\". inversion H.\n    Case \"b = false\". apply conj. reflexivity. apply H.\nQed.\n\nInductive False : Prop := .\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\nInductive True : Prop := \n  | true_constructer : True.\n\nPrint True_ind.\n\nDefinition not (P:Prop) := P -> False.\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  (* 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\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not. intros. apply H0. apply H. apply H1.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  unfold not. intros. inversion H. apply H1. apply H0.\nQed.\n\nTheorem five_not_even :\n  ~ ev 5.\nProof.\n  unfold not. intros.\n  inversion H. inversion H1. inversion H3.\nQed.\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof.\n  intros. unfold not. induction H.\n    Case \"ev_0\". intros. inversion H.\n    Case \"ev_SS\".\n      intros.\n      apply IHev.\n      apply ev_minus2 in H0.\n      simpl in H0.\n      apply H0.\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 peirce__classic :\n  peirce -> classic.\nProof.\n  unfold peirce. unfold classic. unfold not.\n  intros. apply H with (Q:=False). intros.\n  apply H0 in H1. inversion H1.\nQed.\n\nTheorem classic__excluded_middle :\n  classic -> excluded_middle.\nProof.\n  unfold classic. unfold excluded_middle. unfold not.\n  intros H Q.  apply H. intros.\n  apply H0. right. intros. apply H0. left. apply H1.\nQed.\n\nTheorem excluded_middle__de_morgan_not_and_not : \n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle.\n  unfold de_morgan_not_and_not.\n  unfold not.\n  intros. assert (P \\/ ~P).\n    Case \"Proof of Assertion\". apply H.\n  unfold not in H1. inversion H1.\n    Case \"left\". left. apply H2.\n    Case \"right\".\n      assert (Q \\/ ~Q).\n        SCase \"Proof of Assertion\". apply H.\n      unfold not in H3.\n      inversion H3.\n        SCase \"left\". right. apply H4.\n        SCase \"right\".\n          assert (False).\n            SSCase \"Proof of assertion\".\n              apply H0.\n              apply conj. apply H2. apply H4.\n          inversion H5.\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. apply H. intros. inversion H1.\n  apply H2. intros. apply H3.\n  apply H0. apply H4.\nQed.\n\nTheorem implies_to_or__excluded_middle :\n  implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or.\n  unfold excluded_middle.\n  intros.\n  apply or_commut.\n  apply H.\n  intros. apply H0.\nQed.\n\nTheorem implies_to_or__peirce :\n  implies_to_or -> peirce.\nProof.\n  unfold peirce.\n  unfold not.\n  intros H.\n  intros P Q.\n  assert excluded_middle.\n    apply implies_to_or__excluded_middle.\n    apply H.\n  unfold excluded_middle in H0.\n  intros.\n  assert (Q \\/ ~Q).\n    apply H0.\n  inversion H2.\n  apply H1.\n  intros.\n  apply H3.\n  assert (P \\/ ~P).\n    apply H0.\n  inversion H4.\n  apply H5.\n  apply H1.\n  intros.\n  unfold not in H5.\n  apply H5 in H6.\n  inversion H6.\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. 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 not_eq_beq_false : forall n n' : nat,\n  n <> n' ->\n  beq_nat n n' = false.\nProof.\n  intros n.\n  unfold not.\n  induction n.\n    Case \"n = 0\".\n    intros.\n    destruct n'.\n      assert (0 = 0). reflexivity.\n      apply H in H0. inversion H0.\n      simpl. reflexivity.\n    intros.\n    Case \"n = S n\".\n    destruct n'.\n      simpl. reflexivity.\n      simpl. apply IHn. intros.\n      apply H. rewrite H0. reflexivity.\nQed.\n\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  unfold not.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros.\n    destruct m.\n      inversion H.\n      intros. inversion H0.\n  Case \"n = S n'\".\n    intros.\n    destruct m.\n      inversion H0.\n      inversion H0. generalize H2.\n      apply IHn'. simpl in H. apply H.\nQed.\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 => ev (S n)) :=\n  ex_intro nat (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.\n  unfold not.\n  intros.\n  inversion H0 as [x IHE].\n  apply IHE. 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  unfold excluded_middle.\n  intros excluded_middle.\n  unfold not.\n  intros X P Hnen x.\n  assert (P x \\/ ~(P x)).\n    Case \"Proof of Assertion\". apply excluded_middle.\n  inversion H.\n  apply H0.\n  assert (exists x : X , ~(P x)).\n    Case \"Proof of Assertion\". exists x. apply H0.\n  apply Hnen in H1. inversion H1.\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  unfold iff.\n  apply conj.\n  Case \" -> \".\n    intros.\n    inversion H.\n    inversion H0.\n      SCase \"left\".\n        left. exists witness. apply H1.\n      SCase \"right\".\n        right. exists witness. apply H1.\n  Case \"<-\".\n    intros.\n    inversion H.\n      SCase \"left\". inversion H0.\n        exists witness. left. apply H1.\n      SCase \"right\". inversion H0.\n        exists witness. right. apply H1.\nQed.\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  unfold iff.\n  intros. apply conj.\n      Case \"->\". intros. inversion H. apply refl_equal'.\n      Case \"<-\". intros. inversion H. apply refl_equal.\nQed.\n\nCheck eq'_ind.\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\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  (* 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\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  | con_total_relation : total_relation n m.\n\nInductive empty_relation (n m : nat) : Prop :=\n  .\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\nTheorem hoge : R 1 1 2.\nProof.\n  apply c2. apply c3. apply c1. Qed.\n\nLemma R_plus : forall (m n o : nat),\n  R m n o -> m + n = o.\nProof.\n  intros.\n  induction H.\n  reflexivity. simpl. rewrite IHR. reflexivity.\n  rewrite plus_comm. simpl. rewrite plus_comm. rewrite IHR. reflexivity.\n  simpl in IHR. rewrite plus_comm in IHR. simpl in IHR. inversion IHR. apply plus_comm.\n  rewrite plus_comm. apply IHR.\nQed.\n\nTheorem hogee : ~ R 2 2 6.\nProof.\n  unfold not. intros. apply R_plus in H. inversion H.\nQed.\n\nLemma R_plus' : forall(n m : nat),\n  R n m (n+m).\nProof.\n  intros.\n  induction n as [| n'].\n    Case \"n = 0\".\n      induction m as [| m'].\n        SCase \"m = 0\". apply c1.\n        SCase \"m = S m'\". apply c3. apply IHm'.\n    Case \"n = S n'\".\n      induction m as [| m'].\n        SCase \"m = 0\". rewrite plus_0_r.\n          apply c2. simpl in IHn'.\n          rewrite plus_0_r in IHn'.\n          apply IHn'.\n        SCase \"m = S m'\". simpl. apply c2. apply IHn'.\nQed.\n\nTheorem R_fact : forall (m n o : nat),\n  R m n o <-> m+n = o.\nProof.\n  intros. unfold iff. split.\n  Case \"->\". apply R_plus.\n  Case \"<-\". intros. rewrite <- H. apply R_plus'.\nQed.\n\nEnd R.\n\n(*all_forallb*)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  | conallnil : all X P []\n  | conall : forall(h : X) (t : list X),\n             P h -> all X P t -> all X P (h::t)\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\nTheorem forallb_prop :\n  forall (X : Type) (test : X -> bool) (l : list X),\n    forallb test l = true\n    <-> all X (fun(x:X) => test x = true) l.\nProof.\n  intros. split.\n  Case \"->\".\n    intros.\n    induction l as [| h t].\n      SCase \"l = []\". apply conallnil.\n      SCase \"l = h::t\".\n        simpl in H.\n        apply conall.\n        apply andb_true_elim1 in H.\n        apply H.\n        apply andb_true_elim2 in H.\n        apply IHt.\n        apply H.\n  Case \"<-\".\n    intros.\n    induction H.\n      SCase \"nil\". reflexivity.\n      SCase \"h::t\".\n        simpl. rewrite H. rewrite IHall. reflexivity.\nQed.\n\n(*filter_challenge*)\n(*filter_challenge2*)\n(*no_repeats*)\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.\n  remember (xs++ys).\n  generalize dependent xs.\n  generalize dependent ys.\n  induction H.\n  Case \"ai_here\".\n    intros.\n    destruct xs.\n    SCase \"[]\".\n      simpl in Heql.\n      rewrite <- Heql.\n      right.\n      apply ai_here.\n    SCase \"x::xs\".\n      simpl in Heql.\n      inversion Heql.\n      left.\n      apply ai_here.\n  Case \"ai_later\".\n    intros.\n    destruct xs.\n    SCase \"[]\".\n      right.\n      simpl in Heql.\n      rewrite <- Heql.\n      apply ai_later.\n      apply H.\n    SCase \"x0::xs\".\n      inversion Heql.\n      apply IHappears_in in H2.\n      inversion H2.\n      left.\n      apply ai_later.\n      apply H0.\n      right.\n      apply H0.\nQed.\n\nLemma app_appears_in_right : forall {X : Type} (xs ys : list X) (x:X),\n  appears_in x ys -> appears_in x (xs++ys).\nProof.\n  intros.\n  inversion H.\n  induction xs.\n    apply ai_here.\n    simpl. apply ai_later. apply IHxs.\n  induction xs.\n    simpl. apply ai_later. apply H0.\n    simpl. apply ai_later. apply IHxs.\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 H0.\n    SCase \"[]\".\n      simpl.\n      apply ai_here.\n      simpl.\n      apply ai_later.\n      apply IHappears_in.\n      left.\n      apply H0.\n  Case \"right\".\n    apply app_appears_in_right.\n    apply H0.\nQed.\n\nDefinition disjoint {X:Type} (l1 l2 : list X) : Prop :=\n  forall (x:X), appears_in x l1 -> appears_in x l2 -> False.\n\nInductive no_repeats {X:Type} : list X -> Prop :=\n  | no_repeats_nil : no_repeats []\n  | no_repeats_con : forall a l, no_repeats l ->\n    (appears_in a l -> False) -> no_repeats (a::l).\n\nTheorem app_no_repeats : forall {X:Type} (xs ys : list X),\n  no_repeats (xs++ys) -> no_repeats xs /\\ no_repeats ys.\nProof.\n  intros.\n  split.\n  Case \"right\".\n    remember (xs++ys).\n    generalize dependent xs.\n    generalize dependent ys.\n    induction H.\n    SCase \"no_repeats_nil\".\n      intros.\n      destruct xs.\n        apply no_repeats_nil.\n        inversion Heql.\n    SCase \"no_repeats_con\".\n      intros.\n      destruct xs.\n      SSCase \"no_repeats_nil\".\n        apply no_repeats_nil.\n      SSCase \"no_repeats_con\".\n        apply no_repeats_con.\n        inversion Heql.\n        apply IHno_repeats with (ys:=ys).\n        apply H3.\n        inversion Heql.\n        intros.\n        apply H0.\n        rewrite H3.\n        apply app_appears_in.\n        left.\n        rewrite H2.\n        apply H1.\n  Case \"left\".\n    remember (xs++ys).\n    generalize dependent xs.\n    generalize dependent ys.\n    induction H.\n    SCase \"no_repeats_nil\".\n      intros.\n      destruct xs.\n      SSCase \"nil\".\n        simpl in Heql.\n        rewrite <- Heql.\n        apply no_repeats_nil.\n      SSCase \"x::xs\".\n        inversion Heql.\n    SCase \"no_repeats_con\".\n      intros.\n      destruct xs.\n        SSCase \"nil\".\n          simpl in Heql.\n          rewrite <- Heql.\n          apply no_repeats_con.\n            apply H.\n            apply H0.\n        SSCase \"x::xs\".\n        apply IHno_repeats with (xs:=(xs)).\n        inversion Heql.\n          reflexivity.\nQed.\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.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros.\n  induction m as [| m'].\n    Case \"0\".\n      inversion H.\n      apply le_n.\n    Case \"S m'\".\n      inversion H.\n        apply le_n.\n        apply le_S.\n        apply IHm'.\n      apply H1.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m.  generalize dependent n.  induction m.\n  Case \"m = 0\".\n    intros.\n    inversion H.\n      SCase \"le_n\".\n        apply le_n.\n      SCase \"le_S\".\n        inversion H1.\n  Case \"m = S m\".\n    intros.\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  induction b.\n  Case \"0\". rewrite plus_0_r. apply le_n.\n  Case \"S b\".\n    rewrite plus_comm. simpl. apply le_S.\n   rewrite plus_comm. apply IHb.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold \"<\".\n  intros.\n  split.\n  Case \"left\".\n    induction H.\n    apply n_le_m__Sn_le_Sm.\n    apply le_plus_l.\n    apply le_S.\n    apply IHle.\n  Case \"right\".\n    induction H.\n    apply n_le_m__Sn_le_Sm.\n    rewrite plus_comm.\n    apply le_plus_l.\n    apply le_S.\n    apply IHle.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold \"<\".\n  intros.\n  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  intros n m H.\n  generalize dependent m.\n  induction n.\n  Case \"0\".\n    intros.\n    assert(m = 0+m). reflexivity.\n    rewrite H0.\n    apply le_plus_l.\n  Case \"S n\".\n    intros.\n    destruct m.\n    SCase \"0\". inversion H. simpl in H.\n    SCase \"S m\".\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  intros.\n  generalize dependent m.\n  induction n as [| n'].\n    Case \"0\". intros. simpl in H. inversion H.\n    Case \"S n\".\n      intros.\n      destruct m as [| m'].\n      SCase \"0\". reflexivity.\n      SCase \"S m\". simpl. apply IHn'. apply H.\nQed.\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof.\n  intros.\n  induction n as [| n'].\n    reflexivity.\n    simpl.\n    apply IHn'.\nQed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  unfold \"~\".\n  intros.\n  induction H0.\n    Case \"le_n\".\n      rewrite <- ble_nat_refl in H.\n      inversion H.\n    Case \"le_S\".\n      apply IHle.\n      apply ble_nat_n_Sn_false.\n      apply H.\nQed.\n\nInductive nostutter : list nat -> Prop :=\n  | nostutter_nil : nostutter []\n  | nostutter_one : forall n:nat, nostutter [n]\n  | nostutter_mul : forall (n h : nat) (t:list nat),\n                      nostutter (h::t) -> n<>h ->\n                      nostutter (n::h::t).\n\nExample test_nosutter_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]).\nProof. intro.\nrepeat match goal with\n  h: nostutter _ |- _ => inversion h; clear h; subst\nend.\ncontradiction H5; 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  Print \"++\".\n  induction l1.\n  Case \"nil\".\n    reflexivity.\n  Case \"x::l1\".\n    simpl. SearchAbout (S _ = S _).\n    apply eq_S.\n    apply IHl1.\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 H.\n  Case \"ai_here\".\n    apply ex_intro with (witness := nil).\n    apply ex_intro with (witness := l).\n    reflexivity.\n  Case \"ai_later\".\n    inversion IHappears_in.\n    inversion H0.\n    rewrite H1.\n    apply ex_intro with (witness:=b::witness).\n    apply ex_intro with (witness:=witness0).\n    reflexivity.\nQed.\n\nInductive repeats {X:Type} : list X -> Prop :=\n  | repeats_here : forall (a:X) (l:list X), \n                   appears_in a l -> repeats (a::l)\n  | repeats_later : forall (b:X) (l:list X),\n                    repeats l -> repeats (b::l).\n\nTheorem Sn_lt_Sn__n_lt_m : forall (n m : nat),\n  S n < S m -> n < m.\nProof.\n  unfold \"<\".\n  intros. apply Sn_le_Sm__n_le_m. apply H.\nQed.\n\n\n\n\n\nLemma lt_irrefl : forall n, ~ n < n.\nProof.\n induction n.\n  intro. inversion H.\n\n  intro. destruct IHn.\n  apply Sn_le_Sm__n_le_m. apply H.\nQed.\n\nLemma lt_not_le: forall n m : nat, n < m -> ~ m <= n.\nProof.\n intros.\n induction H.\n  apply lt_irrefl.\n\n  intro. destruct IHle. inversion H0.\n   apply le_S. apply le_n.\n\n   rewrite <- H2 in H0. apply le_S. apply Sn_le_Sm__n_le_m. apply H0.\nQed. \n\nLemma bag_remove : forall {X:Type} (l1 l2 l3 : list X) (x:X),\n  ~(appears_in x l1) ->\n  (forall (v:X), appears_in v (x::l1) -> appears_in v (l2++(x::l3))) ->\n  (forall (v:X), appears_in v l1 -> appears_in v (l2++l3)).\nProof.\n  intros.\n  assert (appears_in v (l2++x::l3) -> appears_in v (l2++l3)).\n    Case \"Proof of Assertion\".\n    intros. apply app_appears_in. apply appears_in_app in H2.\n    inversion H2.\n      SCase \"left\". left. apply H3.\n      SCase \"right\". right. inversion H3.\n        rewrite H5 in H1. apply H in H1. inversion H1.\n        apply H5.\n  apply H2. apply H0. apply ai_later. apply H1.\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.\n  unfold excluded_middle.\n  intros X l1. induction l1.\n  SCase \"[]\".\n    intros.\n    inversion H1.\n  SCase \"x::l1\".\n    intros.\n    assert(appears_in x l2). apply H0. apply ai_here.\n    assert (appears_in x l1 \\/ ~(appears_in x l1)).\n      apply H with (P:=(appears_in x l1)).\n    inversion H3.\n    SSCase \"appears_in x l1\".\n      apply repeats_here.\n      apply H4.\n    SSCase \"~appears_in x l1\".\n      apply repeats_later.\n      apply appears_in_app_split in H2.\n      inversion H2.\n      inversion H5.\n      apply IHl1 with (l2:=witness++witness0).\n      apply H.\n      apply bag_remove with (x0:=x).\n        apply H4. rewrite <- H6. apply H0.\n      assert (S(length(witness++witness0)) = length(witness++x::witness0)).\n        SSSCase \"Proof of Assertion\".\n        rewrite app_length.\n        rewrite app_length with (l4:=x::witness0).\n        simpl. rewrite plus_n_Sm. reflexivity.\n    apply Sn_lt_Sn__n_lt_m.\n    rewrite H7.\n    rewrite <- H6.\n    apply H1.\nQed.\n\nPrint nat_ind. Print nat_rect.\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 return P n with\n                             0 => P0\n                           | 1 => P1\n                           | S (S n') => PSS n' (f n')\n                          end.\n\nPrint nat_ind.\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\n\n\n\n\n\n\n\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/logic_j.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7620868411383608}}
{"text": "(** * ADT: Abstract data types *)\nRequire Import Omega.\n\n(** Let's consider the concept of lookup tables, indexed by keys that are\n   numbers, mapping those keys to values of arbitrary (parametric) type.\n   We can express this in Coq as follows: *)\n\nModule Type TABLE.\n Parameter V: Type.\n Parameter default: V.\n Parameter table: Type.\n Definition key := nat.\n Parameter empty: table.\n Parameter get: key -> table -> V.\n Parameter set: key -> V -> table -> table.\n Axiom gempty: forall k,   (* get-empty *)\n       get k empty = default.\n Axiom gss: forall k v t,      (* get-set-same *)\n      get k (set k v t) = v.\n Axiom gso: forall j k v t,    (* get-set-other *)\n      j <> k -> get j (set k v t) = get j t.\nEnd TABLE.\n\n(** This means:  in any [Module] that satisfies this [Module Type],\n   there's a type [table] of lookup-tables, a type [V] of values,\n   and operators [empty], [get], [set] that satisfy the axioms\n   [gempty], [gss], and [gso].\n  \n  It's easy to make an implementation of [TABLE], using [Maps].\n  Just for example, let's choose [V] to be [Type]. *)\n\nRequire Import Maps.\n\nModule MapsTable <: TABLE.\n Definition V := Type.\n Definition default: V := Prop.\n Definition table := total_map V.\n Definition key := nat.\n Definition empty : table := t_empty default.\n Definition get (k: key) (m: table) : V := m (Id k).\n Definition set (k: key) (v: V) (m: table) : table :=\n    t_update m (Id k) v.\n Theorem gempty: forall k, get k empty = default.\n   Proof. intros. reflexivity. Qed.\n Theorem gss: forall k v t,  get k (set k v t) = v.\n   Proof. intros. unfold get, set. apply t_update_eq. Qed.  \n Theorem gso: forall j k v t, j<>k -> get j (set k v t) = get j t.\n   Proof. intros. unfold get, set. apply t_update_neq.\n       congruence.\n   Qed.\nEnd MapsTable.\n\n(** In summary:  to make a [Module] that implements a [Module Type],\n   you need to provide a [Definition] or [Theorem] in the [Module], whose type\n   matches the corresponding [Parameter] or [Axiom] in the [Module Type]. *)\n\n(** Now, let's calculate: put 1 and then 3 into a map, then lookup 1. *)\n\nEval compute in MapsTable.get 1 (MapsTable.set 3 unit (MapsTable.set 1 bool MapsTable.empty)).\n (* = bool *)\n\n(** An _Abstract Data Type_ comprises:\n    - A _type_ with a hidden representation (in this case, [t]).\n    - Interface functions that operate on that type ([empty], [get], [set]).\n    - Axioms about the interaction of those functions ([gempty], [gss], [gso]).\n*)\n\n(** So, [MapsTable] is an implementation of the [TABLE] abstract type.\n\n   The problem with [MapsTable] is that the [Maps] implementation is \n   very inefficient: linear time per [get] operation. If you do a sequence\n   of [N] [get] and [set] operations, it can take time quadratic in [N].\n   For a more efficient implementation, let's use our search trees. *)\n\nRequire Import SearchTree.\n\nModule TreeTable <: TABLE.\n Definition V := Type.\n Definition default : V := Prop.\n Definition table := tree V.\n Definition key := nat.\n Definition empty : table := empty_tree V.\n Definition get (k: key) (m: table) : V := lookup V default k m.\n Definition set (k: key) (v: V) (m: table) : table :=\n     insert V k v m.\n Theorem gempty: forall k, get k empty = default.\n   Proof. intros. reflexivity. Qed.\n\n Theorem gss: forall k v t,  get k (set k v t) = v.\n   Proof. intros. unfold get, set.\n     destruct (unrealistically_strong_can_relate V default t)\n        as [cts H].\n     assert (H0 := insert_relate V default k v t cts H).\n     assert (H1 := lookup_relate V default k _ _ H0).\n    rewrite H1. apply t_update_eq.\n   Qed.\n\n(** **** Exercise: 3 stars (TreeTable_gso)  *)\n(** Prove this using techniques similar to the proof of [gss] just above. *)\n\n Theorem gso: forall j k v t,  j<>k -> get j (set k v t) = get j t.\n   Proof. \n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd TreeTable.\n\n(** But suppose we don't have an unrealistically strong can-relate theorem? \n   Remember the type of the \"ordinary\" can_relate: *)\n\nCheck can_relate.\n  (*  : forall (V : Type) (default : V) (t : tree V),\n       SearchTree V t ->\n       exists cts : total_map V, Abs V default t cts *)\n\n(** This requires that [t] have the [SearchTree] property, or in general,\n   any value of type [table] should be well-formed, that is, should satisfy\n   the representation invariant.  We must ensure that  the client of an ADT\n   cannot \"forge\" values, that is, cannot coerce the representation type into\n   the abstract type; especially ill-formed values of the representation type.\n   This \"unforgeability\" is enforced in some real programming languages:  \n   ML (Standard ML or Ocaml) with its module system; Java, whose Classes \n   have \"private variables\" that the client cannot see.\n*)\n\n(* ================================================================= *)\n(** ** A brief excursion into dependent types *)\n(**\n   We can enforce the representation invariant in Coq using dependent types.\n   Suppose [P] is a predicate\n   on type [A], that is, [P: A -> Prop].  Suppose [x] is a value of type [A],\n   and [proof: P x] is the name of the theorem that [x] satisfies [P].\n   Then [ (exist x, proof) ] is a \"package\" of two things: [x], along with the\n   proof of [P(x)].  The type of [(exists x, proof)] is written as [{x | P x}].\n*)\n\nCheck exist. (* forall {A : Type} (P : A -> Prop) (x : A),\n                 P x -> {x | P x}  *)\nCheck proj1_sig. (* forall {A : Type} {P : A -> Prop},\n                 {x | P x} -> A *)\nCheck proj2_sig. (* forall (A : Type) {P : A -> Prop}\n                 (e : {x | P x}),\n                 P (proj1_sig e) *)\n\n(** We'll apply that idea to search trees.  The type [A] will be [tree V].\n  The predicate [P(x)] will be [SearchTree(x)]. *)\n\nModule TreeTable2 <: TABLE.\n Definition V := Type.\n Definition default : V := Prop.\n Definition table := {x | SearchTree V x}.\n Definition key := nat.\n Definition empty : table := \n   exist (SearchTree V) (empty_tree V) (empty_tree_SearchTree V).\n Definition get (k: key) (m: table) : V := \n          (lookup V default k (proj1_sig m)).\n Definition set (k: key) (v: V) (m: table) : table :=\n   exist (SearchTree V) (insert V k v (proj1_sig m)) \n          (insert_SearchTree _ _ _ _ (proj2_sig m)).\n\n Theorem gempty: forall k, get k empty = default.\n   Proof. intros. reflexivity. Qed.\n\n Theorem gss: forall k v t,  get k (set k v t) = v.\n  Proof. intros. unfold get, set.\n    unfold table in t.\n\n(** Now: [t] is a package with two components: \n     The first component is a tree, and the second component is \n     a proof that the first component has the SearchTree property.\n    We can destruct [t] to see that more clearly. *)\n\n    destruct t as [a Ha].\n    (* Watch what this [simpl] does: *)\n    simpl.\n    (* Now we can use [can_relate] instead of [unrealistically_strong_can_relate]: *) \n    destruct (can_relate V default a Ha) as [cts H].\n    pose proof (insert_relate V default k v a cts H).\n    pose proof (lookup_relate V default k _ _ H0).\n    rewrite H1. apply t_update_eq.\n  Qed.\n\n(** **** Exercise: 3 stars (TreeTable_gso)  *)\n(** Prove this using techniques similar to the proof of [gss] just above;\n     don't use [unrealistically_strong_can_relate]. *)\n\n Theorem gso: forall j k v t,  j<>k -> get j (set k v t) = get j t.\n   Proof. \n (* FILL IN HERE *) Admitted.\n(** [] *)\nEnd TreeTable2.\n\n(* ================================================================= *)\n(** ** End of the brief excursion into dependent types *)\n\n(* ################################################################# *)\n(** * Summary of Abstract Data Type proofs: *)\n\nSection ADT_SUMMARY.\nVariable V: Type.\nVariable default: V.\n\n(** Step 1.  Define a _representation invariant_.\n  (In the case of search trees,\n  the representation invariant is the [SearchTree] predicate.)\n  Prove that each operation on the data type _preserves_ the \n  representation invariant.  For example: *)\n\nCheck (empty_tree_SearchTree V).\n  (*  SearchTree V (empty_tree V) *)\nCheck (insert_SearchTree V).\n  (* forall (k : key) (v : V) (t : tree V),\n       SearchTree V t -> SearchTree V (insert V k v t) *)\n\n(** Notice two things:  Any operator (such as [insert]) that takes a [tree] _parameter_\n   can _assume_ that the parameter satisfies the representation invariant.\n   That is, the [insert_SearchTree] theorem takes a premise, [SearchTree V t].\n\n   Any operator that produces a [tree] _result_ must prove that the result\n   satisfies the representation invariant.  Thus, the conclusions,\n   [SearchTree V (empty_tree V)]  and  [SearchTree V (empty_tree V)]\n   of the two theorems above.\n\n   Finally, any operator that produces a result of \"base type\", has no obligation\n   to prove that the result satisfies the representation invariant; that wouldn't\n   make any sense anyway, because the types wouldn't match.  That is,\n   there's no \"lookup_SearchTree\" theorem, because [lookup] doesn't\n   return a result that's a [tree].\n\n   Step 2.  Define an _abstraction relation_.\n     (In the case of search trees, it's the [Abs] relation.\n     This relates the data structure to some mathematical\n     value that is (presumably) simpler to reason about. *)\n\nCheck (Abs V default).  (* tree V -> total_map V -> Prop *)\n\n(** For each operator, prove that:  assuming each [tree] argument satisfies\n    the representation invariant _and_ the abstraction relation, prove that\n    the results also satisfy the appropriate abstraction relation. *)\n\nCheck (empty_tree_relate V default). (*\n       Abs V default (empty_tree V) (t_empty default)    *)\nCheck (lookup_relate' V default). (* forall k t cts,\n       SearchTree V t ->\n       Abs V default t cts ->\n       lookup V default k t = cts (Id k)  *)\nCheck (insert_relate' V default). (*     : forall k v t cts,\n       SearchTree V t ->\n       Abs V default t cts ->\n       Abs V default (insert V k v t) (t_update cts (Id k) v) *)\n\n(** Step 3.  Using the representation invariant and the abstraction relation,\n    prove that all the axioms of your ADT are valid.  For example... *)\n\nCheck TreeTable2.gso. (*\n      : forall (j k : TreeTable2.key) (v : TreeTable2.V)\n         (t : TreeTable2.table),\n       j <> k ->\n       TreeTable2.get j (TreeTable2.set k v t) = TreeTable2.get j t  *)\n\nEnd ADT_SUMMARY.\n\n(* ################################################################# *)\n(** * Exercise in Data Abstraction *)\n(** The rest of this chapter is optional. *)\n\nRequire Import List.\nImport ListNotations.\n\n(** Here's the Fibonacci function. *)\n\nFixpoint fibonacci (n: nat) := \n match n with\n | 0 => 1 \n | S i => match i with 0 => 1 | S j => fibonacci i + fibonacci j end\n end.\n\nEval compute in map fibonacci [0;1;2;3;4;5;6].\n\n(** Here's a silly little program that computes the Fibonacci function. *)\n\nFixpoint repeat {A} (f: A->A) (x: A) n :=\n match n with O => x | S n' => f (repeat f x n') end.\n\nDefinition step (al: list nat) : list nat :=\n List.cons (nth 0 al 0 + nth 1 al 0) al.\n\nEval compute in map (repeat step [1;0;0]) [0;1;2;3;4;5].\n\nDefinition fib n := nth 0 (repeat step [1;0;0] n) 0.\n\nEval compute in map fib [0;1;2;3;4;5;6].\n\n(** Here's a strange \"List\" module. *)\n\nModule Type LISTISH.\n Parameter list: Type.\n Parameter create : nat -> nat -> nat -> list.\n Parameter cons: nat -> list -> list.\n Parameter nth: nat -> list -> nat.\nEnd LISTISH.\n\nModule L <: LISTISH.\n Definition list := (nat*nat*nat)%type.\n Definition create (a b c: nat) : list := (a,b,c).\n Definition cons (i: nat) (il : list) := match il with (a,b,c) => (i,a,b) end.\n Definition nth (n: nat) (al: list) := \n   match al with (a,b,c) =>\n      match n with 0 => a | 1 => b | 2 => c | _ => 0 end\n   end.\nEnd L.\n\nDefinition sixlist := L.cons 0 (L.cons 1 (L.cons 2 (L.create 3 4 5))).\n\nEval compute in map (fun i => L.nth i sixlist) [0;1;2;3;4;5;6;7].\n\n(** Module [L] implements _approximations_ of lists: it can remember\n    the first three elements, and forget the rest.  Now watch: *)\n\nDefinition stepish (al: L.list) : L.list :=\n L.cons (L.nth 0 al + L.nth 1 al) al.\n\nEval compute in map (repeat stepish (L.create 1 0 0)) [0;1;2;3;4;5].\n\nDefinition fibish n := L.nth 0 (repeat stepish  (L.create 1 0 0) n).\n\nEval compute in map fibish [0;1;2;3;4;5;6].\n\n(** This little theorem may be useful in the next exercise. *)\n\nLemma nth_firstn:\n  forall A d i j (al: list A), i<j -> nth i (firstn j al) d = nth i al d.\nProof.\ninduction i; destruct j,al; simpl; intros; auto; try omega.\napply IHi. omega.\nQed.\n\n(** **** Exercise: 4 stars, optional (listish_abstraction)  *)\n(** In this exercise we will not need a _representation invariant_.\n    Define an abstraction relation: *)\n\nInductive L_Abs: L.list -> List.list nat -> Prop :=\n (* FILL IN HERE *)\n .\n\nDefinition O_Abs al al' := L_Abs al al'.\n\n(* State these theorems using O_Abs, not L_Abs.\n   You'll see why below, at \"Opaque\". *)\nLemma create_relate : True.  (* change this line appropriately *)\n(* FILL IN HERE *) Admitted.\n\nLemma cons_relate : True.  (* change this line appropriately *)\n(* FILL IN HERE *) Admitted.\n\nLemma nth_relate : True.  (* change this line appropriately *)\n(* FILL IN HERE *) Admitted.\n\n(** Now, we will make these operators opaque.  Therefore, in the rest of \n   the proofs in this exercise, you will not unfold their definitions.  Instead, \n   you will just use the theorems [create_relate], [cons_relate], [nth_relate]. *)\n\nOpaque L.list.\nOpaque L.create.\nOpaque L.cons.\nOpaque L.nth.\nOpaque O_Abs.\n\nLemma step_relate:\n  forall al al',\n   O_Abs al al' -> \n   O_Abs (stepish al) (step al').\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma repeat_step_relate:\n forall n al al', \n O_Abs al al' ->\n O_Abs (repeat stepish al n) (repeat step al' n).\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma fibish_correct: forall n, fibish n = fib n.\nProof.  (* No induction needed in this proof! *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (fib_time_complexity)  *)\n(** Suppose you run these three programs call-by-value, that is,\n     as if they were ML programs.  \n    [fibonacci N]\n    [fib N]\n    [fibish N]\n  What is the asymptotic time complexity (big-Oh run time) of each,\n  as a function of N?  Assume that the [plus] function runs in constant time.\n  You can use terms like \"linear,\" \"N log N,\" \"quadratic,\" \"cubic,\" \"exponential.\"\n  Explain your answers briefly.\n\n  fibonacci:  (* fill in here *)\n  fib:  (* fill  in here *)\n  fibish: (* fill in here *)\n\n*)\n(** [] *)\n\n\n\n\n\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/SF/vfa/ADT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8902942290328345, "lm_q1q2_score": 0.7619593272360183}}
{"text": "Require Import Notations\n  Coq.Lists.List\n  Coq.Arith.Arith\n  Coq.Arith.Compare_dec\n  Coq.Bool.Sumbool\n  Coq.Bool.Bool\n  Coq.ZArith.ZArith\n  Coq.Logic.FinFun\n  Coq.Program.Basics\n  Coq.Logic.FunctionalExtensionality\n  Psatz\n  ListLemma\n  Candidates.\n\nImport ListNotations.\nOpen Scope Z.\n\nNotation \"'existsT' x .. y , p\" :=\n  (sigT (fun x => .. (sigT (fun y => p)) ..))\n    (at level 200, x binder, right associativity,\n     format \"'[' 'existsT' '/ ' x .. y , '/ ' p ']'\") : type_scope.\n\nModule Margin (Import Cand : Candidate).\n  \n  Section Marg.\n    (* marg is the margin in Schulze counting, i.e. marg c d is the number of\n      voters that perfer c over d. The existence of the margin function\n      is assumed for the specification of Schulze Voting and will be\n      constructed from incoming ballots later *)\n      Variable marg : cand -> cand -> Z.\n\n      (* prop-level path *)\n      Inductive Path (k : Z) : cand -> cand -> Prop :=\n      | unit c d : marg c d >= k -> Path k c d\n      | cons c d e : marg c d >= k -> Path k d e -> Path k c e.\n \n      (* winning condition of Schulze Voting *)\n      Definition wins_prop (c: cand) := forall d: cand, exists k: Z,\n        Path k c d /\\ (forall l, Path l d c -> l <= k).\n\n      (* dually, the notion of not winning: *)\n      Definition loses_prop (c : cand) := exists k: Z, exists  d: cand,\n        Path k d c /\\ (forall l, Path l c d -> l < k).\n\n      (** Section 3: A Scrutiny Sheet for the Schulze Method **)\n\n      (* boolean function that determines whether the margin between a\n        pair  of candidates is below a given integer *)\n      Definition marg_lt (k : Z) (p : (cand * cand)) :=\n        Zlt_bool (marg (fst p) (snd p)) k.\n\n      (* definition of the (monotone) operator W_k that defines coclosed sets *)\n      Definition W (k : Z) (p : cand * cand -> bool) (x : cand * cand) :=\n        andb (marg_lt k x)\n        (forallb (fun m => orb (marg_lt k (fst x, m)) (p (m, snd x))) cand_all).\n\n      (* k-coclosed predicates *)\n      Definition coclosed (k : Z) (p : (cand * cand) -> bool) :=\n        forall x, p x = true -> W k p x = true.\n\n      (* type-level path to replace prop-level path *)\n      Inductive PathT (k: Z) : cand -> cand -> Type :=\n      | unitT c d : marg c d >= k -> PathT k c d\n      | consT c d e : marg c d >= k -> PathT k d e -> PathT k c e.\n\n      (* type-level winning condition in Schulze counting *)\n      Definition wins_type c :=\n        forall d : cand, existsT (k : Z),\n        ((PathT k c d) * (existsT (f : (cand * cand) -> bool), \n          f (d, c) = true /\\ coclosed (k + 1) f))%type.\n\n      (* dually, the type-level condition for non-winners *)\n      Definition loses_type (c : cand) :=\n        existsT (k : Z) (d : cand), ((PathT k d c) *\n          (existsT (f : (cand * cand) -> bool), f (c, d) = true /\\ coclosed k f))%type.\n\n      (* type-level notions of winning and losing are equivalent *)\n      (* auxilary lemmas needed for the proof of equivalence     *)\n      (* search for wins_prop_type and wins_type_prop for the    *)\n      (* statement and proof of equivalence, dually for losing.  *)\n\n      (* type-level paths allow to construct evidence for the existence of paths *)\n      Lemma path_equivalence : forall c d k , PathT k c d -> Path k c d.\n      Proof.\n        refine\n          (fix F c d k H {struct H}:=\n             match H with\n            | unitT _ cf df mrg => unit _ cf df mrg\n            | consT _ cf df ef mrg t => cons _ cf df ef mrg (F _ _ _ t)\n            end).\n      Qed.  \n\n      (* mp stands for midpoint and the lemma below shows that for a pair of candidates (a, c)\n         with x = (a, c) in W_k p, and a putative midpoint b, we have that marg a b < k or p b c. *)\n      Lemma mp_log : forall (k : Z) (x : cand * cand) (p : cand * cand -> bool),\n        (forallb (fun m => orb (marg_lt k (fst x, m)) (p (m, snd x))) cand_all) = true ->\n        forall b, p (b, snd x) = true \\/ marg (fst x) b < k.\n      Proof.\n        intros k x p H b.\n        assert (Hin : In b cand_all) by  apply cand_fin.\n        pose proof (proj1 (forallb_forall _ cand_all) H b Hin) as Hp. simpl in Hp.\n        apply orb_true_iff in Hp; destruct Hp as [Hpl | Hpr]; destruct x as (a, c); simpl in *.\n        + right; apply Zlt_is_lt_bool; auto.\n        + left;auto.\n      Qed.\n\n      (* all elements (x, y) in a k-coclosed set can only be joined by a path of strenght < k *)\n      Lemma coclosed_path : forall k f, coclosed k f -> forall s x y,\n          Path s x y -> f (x, y) = true -> s < k.\n      Proof.\n        intros k f Hcc x s y p. induction p.\n\n        (* unit path *)\n        + intros Hin; specialize (Hcc (c, d) Hin); apply andb_true_iff in Hcc;\n          destruct Hcc as [Hccl Hccr]; apply Zlt_is_lt_bool in Hccl; simpl in Hccl;  lia.\n\n      (* non unit path *)\n        + intros Hin; specialize (Hcc (c, e) Hin); apply andb_true_iff in Hcc;\n          destruct Hcc as [Hccl Hccr]; unfold marg_lt in Hccl; simpl in Hccl.\n          assert (Hmp : forall m, f (m, (snd (c, e))) = true \\/ marg (fst (c, e)) m < k)\n            by (apply mp_log; auto); simpl in Hmp.\n          specialize (Hmp d). destruct Hmp; [intuition | lia].\n      Qed.\n\n\n      Definition listify (m : cand -> cand -> Z) :=\n        map (fun s => (fst s, snd s, m (fst s) (snd s))) (all_pairs cand_all).\n\n\n\n      Lemma in_pairs : forall a b, In a cand_all -> In b cand_all -> In (a, b) (all_pairs cand_all).\n      Proof.\n        intros a b H1 H2. apply all_pairsin; auto.\n      Qed.\n\n\n      Fixpoint linear_search (c d : cand) l :=\n        match l with\n        | [] => marg c d\n        | (c1, c2, k) :: t =>\n          match dec_cand c c1, dec_cand d c2 with\n          | left _, left _ => k\n          | _, _ => linear_search c d t\n          end\n        end.\n \n\n      Theorem equivalent_m : forall c d m, linear_search c d (listify m) = m c d.\n      Proof.\n        unfold listify.  intros c d m.\n        assert (H1 : forall c1 c2, In (c1, c2) (all_pairs cand_all)).\n        intros c1 c2. apply in_pairs; apply cand_fin.\n        specialize (H1 c d).\n        induction (all_pairs cand_all).\n        + inversion H1.\n        + simpl.\n          destruct a as (a1, a2). simpl in *.\n          destruct (dec_cand c a1).\n          destruct (dec_cand d a2). subst. auto.\n          destruct H1. inversion H. symmetry in H2. unfold not in n.\n          specialize (n H2). inversion n.\n          apply IHl. auto.\n          destruct H1. inversion H. unfold not in n. symmetry in H1.\n          specialize (n H1). inversion n.\n          apply IHl. auto.\n      Qed.\n\n\n\n\n      Fixpoint M_old (n : nat) (c d : cand) : Z :=\n        match n with\n        | 0%nat => marg c d\n        | S n' => Z.max (M_old n' c d) \n          (maxlist (map (fun x : cand => Z.min (marg c x) (M_old n' x d)) cand_all))\n        end.\n\n      (* M is the iterated margin function and maps a pair of candidates c, d to the\n        strength of the strongest path of length at most (n + 1) *)\n\n      Fixpoint MM n :=\n        match n with\n        | O => listify marg\n        | S n' =>\n          let uu := MM n' in\n          listify (fun c d =>\n            let u := linear_search c d uu in\n            let t := maxlist (map (fun x => Z.min (marg c x) (linear_search x d uu)) cand_all) in\n            Z.max u t)\n        end.\n\n      Definition M n : cand -> cand -> Z :=\n        let l := MM n in\n        fun c d => linear_search c d l.\n\n\n      Lemma M_M_new_equal : forall n c d , M n c d = M_old n c d.\n      Proof.\n        induction n. unfold M. simpl. intros c d. rewrite equivalent_m. auto.\n        intros c d.  unfold M in *. simpl. rewrite equivalent_m.\n        assert (Ht: maxlist (map (fun x : cand => Z.min (marg c x) (linear_search x d (MM n))) cand_all) =\n                  maxlist (map (fun x : cand => Z.min (marg c x) (M_old n x d)) cand_all)).\n        apply f_equal.\n        \n        induction cand_all. auto. simpl. pose proof (IHn a d).\n        rewrite H. apply f_equal. auto.\n        rewrite Ht. rewrite IHn. auto.\n      Qed.\n\n\n      (* partial correctness of iterated margin function: if the strength M n c d\n        of the strongest path of length <= n+1 between c and d is at least s, then\n        c and d can be joined by a type-level path of this strength *)\n      Theorem iterated_marg_patht : forall n s c d, M n c d >= s -> PathT s c d.\n      Proof.\n        induction n.\n        intros s c d H. constructor. unfold M in *. simpl in *. rewrite equivalent_m in H. auto.\n        intros s c d H. unfold M in *. simpl in H. rewrite equivalent_m in H.\n        unfold Z.max in H.\n        destruct (linear_search c d (MM n)\n                              ?= maxlist (map (fun x : cand => Z.min (marg c x) (linear_search x d (MM n))) cand_all)).\n        apply IHn. auto.\n        apply max_of_nonempty_list_type in H. destruct H as [x [H1 H2]].\n        apply z_min_lb in H2. destruct H2.\n        specialize (IHn _ _ _ H0). specialize (consT _ _ _ _ H IHn); auto.\n        apply cand_not_nil.  apply dec_cand. apply IHn. assumption.\n      Defined.\n\n    \n      (* as type level paths induce prop-level paths, the same as above also holds for prop-level\n        paths *)\n      Lemma iterated_marg_path : forall (n : nat) (s : Z) (c d : cand),\n        M n c d >= s -> Path s c d.\n      Proof.\n        intros n s c d Hm.\n        apply path_equivalence. apply iterated_marg_patht with (n := n).\n        assumption.\n      Qed.\n\n      (* existence of a a path between c and d of strength s gives an interate of the\n         iterated margin function with value at least s *)\n      Lemma path_iterated_marg : forall (s : Z) (c d : cand),\n          Path s c d -> exists n, M n c d >= s.\n      Proof.\n        intros s c d H.  induction H.\n        exists 0%nat. unfold M. simpl. rewrite equivalent_m. auto. destruct IHPath.\n        exists (S x). unfold M in *. simpl.  rewrite equivalent_m. apply z_max_lb. right.\n        apply max_of_nonempty_list.\n        apply cand_not_nil. apply dec_cand. exists d.\n        split. pose proof (cand_fin d). auto.\n        apply z_min_lb. split. auto. auto.\n      Qed.\n\n      (* monotonicity of the iterated margin function *)\n      Lemma monotone_M : forall (n m : nat) c d, (n <= m)%nat  -> M n c d <= M m c d.\n      Proof.\n        intros n m c d H.  induction H; simpl; try lia.\n        apply Z.ge_le. unfold M at 1. simpl. rewrite equivalent_m.\n        apply z_max_lb with (m := M m c d).\n        left. lia.\n      Qed.\n\n      (* Here, we view paths as lists of candidates, and str computes the strength of\n        a path relative to the given margin function *)\n      Fixpoint str c l d :=\n        match l with\n        | [] => marg c d\n        | (x :: xs) => Z.min (marg c x)  (str x xs d)\n        end.\n\n      (* the iterated margin function is correct relative to the length of a path *)\n      Lemma path_len_iterated_marg : forall k c d s l,\n          (length l <= k)%nat -> str c l d >= s -> M k c d >= s.\n      Proof.\n        induction k. intros. assert ((length l <= 0)%nat -> l = []).\n        { destruct l. intros. reflexivity.\n          simpl in *. inversion H. }\n        specialize (H1 H). subst. simpl in *. unfold M in *. simpl. rewrite equivalent_m. auto.\n        intros. simpl in *. destruct l. simpl in *.\n        unfold M in *. simpl.\n\n        rewrite equivalent_m. apply z_max_lb.\n        left. apply IHk with []. simpl. lia. simpl. auto.\n        simpl in *. apply z_min_lb in H0. destruct H0.\n        unfold M in *.  simpl.\n        rewrite equivalent_m.\n        apply z_max_lb. right. apply max_of_nonempty_list.\n        apply cand_not_nil. apply dec_cand. exists c0. split. specialize (cand_fin c0). trivial.\n        apply z_min_lb. split.\n        lia. apply IHk with l. lia. lia.\n      Qed.\n\n      (* characterisation of the iterated margin function in terms of paths *)\n      Lemma iterated_marg_char: forall k c d s,\n          M k c d >= s <-> exists (l : list cand), (length l <= k)%nat /\\ str c l d >= s.\n      Proof.\n        split. generalize dependent s. generalize dependent d.\n        generalize dependent c. induction k. simpl. intros. exists []. simpl. intuition.\n        unfold M in *. simpl in H. rewrite equivalent_m in H. auto.\n\n        simpl. intros. unfold M in *. simpl in H.\n\n        rewrite equivalent_m in H.  pose proof (proj1 (z_max_lb (M k c d) _ s) H).\n        destruct H0.\n        specialize (IHk c d s H0). destruct IHk as [l [H1 H2]]. exists l. lia. clear H.\n        pose proof\n            (max_of_nonempty_list _ cand_all cand_not_nil dec_cand s\n                                  (fun x : cand => Z.min (marg c x) (M k x d))).\n        destruct H. clear H1. specialize (H H0). destruct H as [e [H1 H2]].\n        pose proof (proj1 (z_min_lb _ _ s) H2). destruct H.\n        specialize (IHk e d s H3). destruct IHk as [l [H4 H5]].\n        exists (e :: l). simpl. split. lia.\n        apply z_min_lb. intuition.\n        (* otherway *)\n        intros. destruct H as [l [H1 H2]].\n        pose proof (path_len_iterated_marg k c d s l H1 H2). lia.\n      Qed.\n\n      (* every path of strength >= s can be split into two paths of strength >= s *)\n      Lemma path_split: forall c d a l1 l2 s,\n          str c (l1 ++ a :: l2) d >= s <-> str c l1 a >= s /\\ str a l2 d >= s.\n      Proof.\n        split. generalize dependent s. generalize dependent l2.\n        generalize dependent a. generalize dependent d. generalize dependent c.\n        induction l1; simpl; intros.\n        apply z_min_lb in H. auto. apply z_min_lb in H. destruct H.\n        assert ((marg c a) >= s /\\ (str a l1 a0) >= s /\\ str a0 l2 d >= s ->\n                Z.min (marg c a) (str a l1 a0) >= s /\\ str a0 l2 d >= s).\n        { intros. destruct H1 as [H1 [H2 H3]]. split. apply z_min_lb. auto. auto. }\n        apply H1. split. assumption. apply IHl1. assumption.\n        (* other part *)\n        generalize dependent s. generalize dependent l2.\n        generalize dependent a. generalize dependent d. generalize dependent c.\n        induction l1; simpl; intros. apply z_min_lb. auto.\n        apply z_min_lb. destruct H. apply z_min_lb in H. destruct H.\n        split. auto. apply IHl1. auto.\n      Qed.\n\n      (* cutting out a loop from a path does not decrease its strength *)\n      Lemma path_cut: forall c d a l l1 l2 l3 s,\n          l = l1 ++ a :: l2 ++ a :: l3 -> str c l d >= s -> str c (l1 ++ a :: l3) d >= s.\n      Proof.\n        intros. subst. apply path_split in H0. destruct H0.\n        apply path_split in H0. destruct H0.\n        pose proof (proj2 (path_split c d a l1 l3 s) (conj H H1)). auto.\n      Qed.\n\n      (* the iterated margin function stabilizes after n iterations, where n is the\n        number of candidates. *)\n      Lemma iterated_marg_stabilises: forall k n c d (Hn: (length cand_all = n)%nat),\n          M (k + n) c d <= M n  c d.\n      Proof.\n        induction k using (well_founded_induction lt_wf). intros n c d Hn.\n        remember (M (k + n) c d) as s.\n        pose proof (Z.eq_le_incl _ _ Heqs). apply Z.le_ge in H0.\n        pose proof (proj1 (iterated_marg_char _ _ _ _) H0). destruct H1 as [l [H1 H2]].\n        (* number of candidates <= length Evote.cand_all \\/ > length Evote.cand_all *)\n        assert ((length l <= n)%nat \\/ (length l > n)%nat) by lia.\n        destruct H3 as [H3 | H3].\n        pose proof (proj2 (iterated_marg_char n c d s)\n                          (ex_intro (fun l => (length l <= n)%nat /\\ str c l d >= s) l (conj H3 H2))). lia.\n        (* length l > length Evote.cand_all and there are candidates. Remove the duplicate\n          candidate *)\n        rewrite <- Hn in H3. assert (covers cand cand_all l).\n        { unfold covers. intros. pose proof (cand_fin x). assumption. }\n        pose proof (list_split_dup_elem _ n cand_all dec_cand Hn l H3 H4).\n        destruct H5 as [a [l1 [l2 [l3 H5]]]].\n        pose proof (path_cut  _ _ _ _ _ _ _ _ H5 H2).\n        remember (l1 ++ a :: l3) as l0.\n        assert ((length l0 <= n)%nat \\/ (length l0 > n)%nat) by lia.\n        destruct H7.\n        pose proof (iterated_marg_char n c d s). destruct H8.\n        assert ((exists l : list cand, (length l <= n)%nat /\\ str c l d >= s)).\n        exists l0. intuition. specialize (H9 H10).  lia.\n        rewrite Hn in H3.\n        specialize (list_and_num _ _ _ H3); intros. destruct H8 as [p H8].\n        specialize (list_and_num _ _ _ H7); intros. destruct H9 as [k' H9].\n        assert ((length l0 < length l)%nat).\n        { rewrite Heql0, H5.\n          rewrite app_length. rewrite app_length.\n          simpl. rewrite app_length. simpl.\n          lia. }\n        rewrite H9 in H10. rewrite H8 in H10.\n        assert (((k' + n) < (p + n))%nat -> (k' < p)%nat) by lia.\n        specialize (H11 H10). assert (k' < k)%nat by lia.\n        specialize (H k' H12 n c d Hn).\n        pose proof (iterated_marg_char (length l0) c d (str c l0 d)).\n        destruct H13.\n        assert ((exists l : list cand, (length l <= length l0)%nat /\\ str c l d >= str c l0 d)).\n        { exists l0. lia. }\n        specialize (H14 H15). clear H13. rewrite <- H9 in H. lia.\n      Qed.\n\n      (* the iterated margin function reaches a fixpoint after n iterations, where\n        n is the number of candidates *)\n      Lemma iterated_marg_fp : forall (c d : cand) (n : nat),\n          M n c d <= M (length cand_all) c d.\n      Proof.\n        intros c d n. assert ((n <= (length cand_all))%nat \\/\n                              (n >= (length cand_all))%nat) by lia.\n        destruct H. apply monotone_M. assumption.\n        remember ((length cand_all)) as v.\n        assert ((n >= v)%nat -> exists p, (n = p + v)%nat).\n        { intros. induction H. exists 0%nat. lia.\n          assert ((v <= m)%nat -> (m >= v)%nat) by lia.\n          specialize (H1 H). specialize (IHle H1). destruct IHle as [p H2].\n          exists (S p). lia. }\n        specialize (H0 H). destruct H0 as [p H0].\n        subst. apply  iterated_marg_stabilises. auto.\n      Qed.\n\n      (* boolean valued function that determines election winners based on the\n        (fixpoint of the) iterated margin function *)\n      Definition c_wins c :=\n        forallb (fun d => (M (length cand_all) d c) <=? (M (length cand_all) c d))\n                cand_all.\n\n      \n      (* characterisation of c_wins returning true in terms of iterated margin function *)\n      Lemma c_wins_true (c : cand) :\n        c_wins c = true <-> forall d, M (length cand_all) d c <= M (length cand_all) c d.\n      Proof.\n        split; intros.\n        unfold c_wins in H.\n        pose proof\n            (proj1 (forallb_forall\n                      (fun d : cand => M (length cand_all) d c <=?\n                                        M (length cand_all) c d) cand_all) H).\n        pose proof (H0 d (cand_fin d)). simpl in H1.\n        apply Zle_bool_imp_le. assumption.\n        unfold c_wins. apply forallb_forall. intros x Hin.\n        pose proof H x. apply Zle_imp_le_bool. assumption.\n      Qed.\n\n      \n      (* characterisation of c_wins returning false in terms of the interated margin function *)\n      Lemma c_wins_false (c : cand):\n        c_wins c = false <-> exists d, M (length cand_all) c d < M (length cand_all) d c.\n      Proof.\n        split; intros. unfold c_wins in H.\n        apply forallb_false in H. destruct H as [x [H1 H2]].\n        exists x. apply Z.leb_gt in H2. lia.\n        destruct H as [d H]. unfold c_wins. apply forallb_false.\n        exists d. split. pose proof (cand_fin d). assumption.\n        apply Z.leb_gt. lia.\n      Qed.\n\n\n      (* the propositional winning condition implies winning in terms of the interated margin\n        function *)\n      Lemma wins_prop_iterated_marg (c : cand): wins_prop c ->\n                                                forall d, M (length cand_all) d c <= M (length cand_all) c d.\n      Proof.\n        intros. specialize (H d). destruct H as [k [H1 H2]].\n        remember (M (length cand_all) d c) as s.\n        apply Z.eq_le_incl in Heqs.\n        apply Z.le_ge in Heqs.\n        pose proof (iterated_marg_path _ _ _ _ Heqs). specialize (H2 s H).\n        apply  path_iterated_marg in H1. destruct H1 as [n H1].\n        pose proof (iterated_marg_fp c d n). lia.\n      Qed.\n\n      (* winning in terms of the iterated margin function gives the type-level winning condition *)\n      Lemma iterated_marg_wins_type (c : cand): (forall d,\n                                                    M (length cand_all) d c <= M (length cand_all) c d) ->\n                                                wins_type c.\n      Proof.\n        (* rewrite it using refine tactic *)\n\n        intros H d. specialize (H d).\n        remember (M (length cand_all) c d) as s eqn:Heqs.\n        apply Z.eq_le_incl in Heqs.\n        apply Z.le_ge in Heqs. exists s.\n        pose proof (iterated_marg_patht _ _ _ _ Heqs) as Hi.\n        split.\n        - intuition.\n        - remember (M (length cand_all) d c) as r eqn:Heqr.\n          exists (fun x => M (length cand_all) (fst x) (snd x) <=? r).\n          split.\n          + apply Z.leb_le. simpl. intuition.\n          + intros x Hx. destruct x as (x, z).\n            apply Z.leb_le in Hx. apply andb_true_iff.\n            split.\n            * apply Z.ltb_lt. simpl in *.\n              clear Heqs. clear Heqr.\n              induction (length cand_all); simpl in Hx. unfold M in Hx. simpl in Hx.\n              rewrite equivalent_m in Hx.\n              intuition.\n              apply IHn. unfold M in Hx. simpl in Hx.\n              rewrite equivalent_m in Hx.  apply Z.max_lub_iff in Hx. intuition.\n            * apply forallb_forall. intros y Hy. apply orb_true_iff.\n              simpl in *.\n              assert (A : marg x y <= s \\/ marg x y > s) by lia.\n              destruct A as [A1 | A2].\n              left. apply Z.ltb_lt. simpl. lia.\n              right. apply Z.leb_le.\n              assert (B : M (length cand_all) y z <= r \\/ M (length cand_all) y z >= r + 1) by lia.\n              destruct B as [B1 | B2].\n              intuition.\n              apply iterated_marg_path in B2.\n              assert (A3 : marg x y >= r + 1) by lia.\n              pose proof (cons _ _ _ _ A3 B2) as C.\n              apply  path_iterated_marg in C. destruct C as [n C].\n              pose proof (iterated_marg_fp x z n). lia.\n      Defined.\n\n\n\n      (* the type level winning condition can be reconstruced from *)\n      (* propositional knowledge of winning *)\n      Lemma wins_prop_type : forall c, wins_prop c -> wins_type c.\n      Proof.\n        intros c H. unfold wins_prop, wins_type in *.\n        apply iterated_marg_wins_type. apply wins_prop_iterated_marg. auto.\n      Qed.\n\n      (* dually, the type-level information witnessing winners *)\n      (* entails prop-level knowledge. *)\n      Lemma wins_type_prop : forall c, wins_type c -> wins_prop c.\n      Proof.\n        intros c H. unfold wins_prop, wins_type in *. intros d.\n        destruct (H d) as [k [H1 [f [H3 H4]]]].\n        exists k. split. apply path_equivalence. auto.\n        intros l H5. pose proof (coclosed_path _ _ H4).\n        pose proof (H0 l _ _ H5 H3). lia.\n      Qed.\n\n      (* the losing condition in terms of the iterated margin function *)\n      Lemma loses_prop_iterated_marg (c : cand):\n        loses_prop c ->\n        (exists d, M (length cand_all) c d < M (length cand_all) d c).\n      Proof.\n        intros. destruct H as [k [d [H1 H2]]].\n        exists d. remember (M (length cand_all) c d)  as s.\n        pose proof (Z.eq_le_incl _ _ Heqs) as H3.\n        apply Z.le_ge in H3. apply iterated_marg_path in H3. specialize (H2 s H3).\n        apply  path_iterated_marg in H1. destruct H1 as [n H1].\n        pose proof (iterated_marg_fp d c n). lia.\n      Qed.\n\n      (* existential quantifiers over finite lists can be reified into Sigma-types for\n        decidable properties *)\n      Definition exists_fin_reify {A: Type} (P: A -> Prop):\n        (forall a: A, {P a} + {~(P a)}) ->\n        forall l: list A, (exists a, In a l /\\ P a) -> existsT a, P a :=\n        fun Pdec =>\n          fix F l {struct l} :=\n          match l  as m return ((exists a : A, In a m /\\ P a) -> existsT a : A, P a) with\n          | [] =>\n            fun H : exists a : A, In a [] /\\ P a =>\n              (fun Hf : False => (fun X : existsT a : A,P a => X)\n                                  match Hf return\n                                        (existsT a : A,P a) with end)\n                match H with\n                | ex_intro _ a (conj Ha _) => (fun H1 : False => H1) match Ha return False with end\n                end\n          | h :: t => fun H =>\n                        match (Pdec h) with\n                        | left e => existT _ h e\n                        | right r =>\n                          F t\n                            match H with\n                            | ex_intro _ a (conj (or_introl e) Hpa) =>\n                              (fun rr : ~ P a => False_ind (exists a1 : A, In a1 t /\\ P a1) (rr Hpa))\n                                (eq_ind h (fun hh : A => ~ P hh) r a e)\n                            | ex_intro _ a (conj (or_intror rr as Hin) Hpa as a0) =>\n                              ex_intro _ a (conj rr Hpa)\n                            end\n                        end\n          end.\n\n      (* reification of candidates given propositional existence *)\n      Corollary reify_opponent (c: cand):\n        (exists  d, M  (length cand_all) c d < M (length cand_all) d c) ->\n        (existsT d, M  (length cand_all) c d < M (length cand_all) d c).\n        refine (fun Hex  =>\n                  (fun Hdec : forall d : cand,\n                      {M (length cand_all) c d < M (length cand_all) d c} +\n                      {~ M (length cand_all) c d < M (length cand_all) d c} =>\n                    exists_fin_reify\n                      _  Hdec cand_all\n                      match Hex with\n                      | ex_intro _ d Hex0 =>\n                        ex_intro _ d (conj (cand_fin d) Hex0)\n                      end)\n                    (fun d : cand =>\n                      let s := Z_lt_ge_bool (M (length cand_all) c d) (M (length cand_all) d c) in\n                      let (b, P) := s in\n                      (if b as bt\n                          return\n                          ((if bt\n                            then M (length cand_all) c d < M (length cand_all) d c\n                            else M (length cand_all) c d >= M (length cand_all) d c) ->\n                            {M (length cand_all) c d < M (length cand_all) d c} +\n                            {~ M (length cand_all) c d < M (length cand_all) d c})\n                        then fun Pt => left Pt\n                        else fun Pf => right (fun H => Pf H)) P)).\n      Defined.\n\n\n\n      (* reconstructon of the losing condition type-level losing from interated\n        margin function *)\n      Lemma iterated_marg_loses_type (c : cand) :\n        (exists d, M (length cand_all) c d < M (length cand_all) d c) -> loses_type c.\n      Proof.\n        unfold loses_type. intros.\n        assert (HE:  existsT d, M  (length cand_all) c d < M (length cand_all) d c).\n        apply reify_opponent. assumption.\n        destruct HE as [d HE].\n        remember (M (length cand_all) d c) as s. exists s, d.\n        split. assert (H1 : M (length cand_all) d c >= s) by lia.\n        apply iterated_marg_patht in H1. auto.\n        exists (fun x => M (length cand_all) (fst x) (snd x) <? s).\n        simpl in *. split. apply Z.ltb_lt. lia.\n        unfold coclosed. intros x; destruct x as (x, z); simpl in *.\n        intros. apply Z.ltb_lt in H0. unfold W.\n        apply andb_true_iff. split. unfold marg_lt. simpl. apply Z.ltb_lt.\n        clear H. clear Heqs.\n        induction (length cand_all). unfold M in *. simpl in *.  rewrite equivalent_m in H0.  lia.\n        unfold M in H0.\n        simpl in H0. rewrite equivalent_m in H0.\n        apply Z.max_lub_lt_iff in H0. destruct H0. apply IHn. auto.\n        unfold M in HE.\n        simpl in HE. rewrite equivalent_m in HE.\n        apply Z.max_lub_lt_iff in HE. destruct HE as [H1 H2]. assumption. assumption.\n\n        apply forallb_forall. intros y Hy.\n        apply orb_true_iff. unfold marg_lt. simpl.\n        assert (marg x y < s \\/ marg x y >= s) by lia.\n        destruct H1. left. apply Z.ltb_lt. auto.\n        right. apply Z.ltb_lt.\n        assert (M (length cand_all) y z < s \\/ M (length cand_all) y z >= s) by lia.\n        destruct H2. auto.\n        apply iterated_marg_path in H2.  pose proof (cons _ _ _ _ H1 H2).\n        apply  path_iterated_marg in H3. destruct H3 as [n H3].\n        pose proof (iterated_marg_fp x z n). lia.\n      Defined.\n\n      (* prop-level losing implies type-level losing *)\n      Lemma loses_prop_type : forall c, loses_prop c -> loses_type c.\n      Proof.\n        intros c H. unfold loses_prop, loses_type in *. apply iterated_marg_loses_type.\n        apply loses_prop_iterated_marg. auto.\n      Qed.\n\n      (* type-level losing implies prop-level losing *)\n      Lemma loses_type_prop : forall c, loses_type c -> loses_prop c.\n      Proof.\n        intros c H. unfold loses_prop, loses_type in *.\n        destruct H as [k [d [Hp [f [Hf Hc]]]]].\n        exists k, d. split. apply path_equivalence. auto.\n        intros l H. pose proof (coclosed_path k f Hc).\n        pose proof (H0 l _ _ H Hf). lia.\n      Qed.\n\n      (* decidability of type-level winning *)\n      Lemma wins_loses_type_dec : forall c, (wins_type c) + (loses_type c).\n      Proof.\n        intros c. destruct (c_wins c) eqn : c_wins_val.  left.\n        unfold wins_type. apply  iterated_marg_wins_type. apply wins_prop_iterated_marg. intros d.\n        pose proof (proj1 (forallb_forall _ cand_all) c_wins_val d (cand_fin d)).\n        simpl in H. apply Zle_bool_imp_le in H. apply Z.le_ge in H.\n        remember (M (length cand_all) d c) as s. apply iterated_marg_path in H.\n        exists s. split. assumption.\n        intros. rewrite Heqs. apply  path_iterated_marg in H0. destruct H0 as [n H0].\n        apply Z.ge_le in H0. pose proof (iterated_marg_fp d c n). lia.\n        right. apply iterated_marg_loses_type. unfold c_wins in c_wins_val.\n        apply forallb_false_type in c_wins_val.\n        destruct c_wins_val as [d [H1 H2]]. apply Z.leb_gt in H2. exists d. auto.\n      Defined.\n\n      (* aligning c_wins with type level evidence *)\n      Lemma c_wins_true_type:\n        forall c : cand, c_wins c = true <-> (exists x : wins_type c, wins_loses_type_dec c = inl x).\n      Proof.\n        split; intros. destruct (wins_loses_type_dec c) eqn:Ht. exists w. auto.\n        pose proof (loses_type_prop c l). unfold loses_prop in H0.\n        apply loses_prop_iterated_marg  in H0.\n        pose proof (proj1 (c_wins_true c) H). destruct H0. specialize (H1 x). lia.\n        destruct H. pose proof (wins_type_prop c x). unfold wins_prop in H0.\n        apply c_wins_true. apply wins_prop_iterated_marg. auto.\n      Qed.\n\n      (* aligning of c_wins with losing condition *)\n      Lemma c_wins_false_type:\n        forall c : cand, c_wins c = false <-> (exists x : loses_type c, wins_loses_type_dec c = inr x).\n      Proof.\n        split; intros. destruct (wins_loses_type_dec c) eqn:Ht.\n        pose proof (wins_type_prop c w).\n        pose proof (proj1 (c_wins_false c) H). unfold wins_prop in H0.\n        pose proof (wins_prop_iterated_marg c H0). destruct H1. specialize (H2 x). lia.\n        exists l. auto.\n        destruct H. pose proof (loses_type_prop c x). unfold loses_prop in H0.\n        apply c_wins_false. apply loses_prop_iterated_marg. auto.\n      Qed.\n  End Marg.\nEnd Margin.\n", "meta": {"author": "mukeshtiwari", "repo": "Schulzeproperties", "sha": "9a9a32450e45d09ad4174ce8d6d6b1a994c18dfe", "save_path": "github-repos/coq/mukeshtiwari-Schulzeproperties", "path": "github-repos/coq/mukeshtiwari-Schulzeproperties/Schulzeproperties-9a9a32450e45d09ad4174ce8d6d6b1a994c18dfe/src/Margin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7619197485898555}}
{"text": "Require Import List.\nRequire Import String.\nRequire Import ZArith.\n\nLtac break_if :=\n  match goal with\n    | _ : context [ if ?cond then _ else _ ] |- _ =>\n     destruct cond as [] eqn:?\n    | |- context [ if ?cond then _ else _ ] =>\n      destruct cond as [] eqn:?\n    | _ : context [ match ?cond with _ => _ end ] |- _ =>\n     destruct cond as [] eqn:?\n    | |- context [ match ?cond with _ => _ end ] =>\n      destruct cond as [] eqn:?\n  end.\n\n(*\n  We will extend IMP with the ability to push and pop heaps.\n\n  In normal IMP, program states just included the heap \"h\" and\n  statement to execute \"s\".\n\n  In our extended version of IMP, program state will also include\n  the current stack of heaps \"l\", represented as a list.\n\n  There will be two new statements: \"PushHeap\" and \"PopHeap x\".\n    - \"PushHeap\" adds the current heap \"h\" to the beginning of \"l\".\n      Informally, it copies \"h\" all at once.\n    - \"PopHeap x\" replaces the current heap \"h\" with the first\n      element of \"l\" *except* \"x\" maps to \"lkup x h\" and replaces \"l\"\n      with the tail of \"l\".  If \"l\" is the empty list, then\n     \"PopHeap x\" has no effect.\n  Both \"PushHeap\" and \"PopHeap x\" become Skip in one step.\n*)\n\nSet Implicit Arguments.\n\nDefinition var := string.\n\n(* We'll start by defining the syntax of our extended IMP. *)\n\n(* Expressions are just like those from IMP seen in lecture. *)\nInductive Expr : Type :=\n| Int : Z -> Expr\n| Var : var -> Expr\n| Add : Expr -> Expr -> Expr\n| Mul : Expr -> Expr -> Expr.\n\n(* Add the PushHeap and PopHeap x statements to the Stmt type. *)\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(*\n  [PROBLEM 1]\n  Add constructors for PushHeap and PopHeap x here.\n*)\n.\n\n(* Next we define the semantics of our language *)\n\n(* Heaps are represented as association lists. *)\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\n(* Since expressions are unchanged from IMP, their semantics are the same: *)\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\n(*\n  Define a small-step operational semantics for our extended version of IMP.\n  Because the form of rules has changed, include all the rules.\n*)\nInductive Step : list Heap -> Heap -> Stmt ->\n                 list Heap -> Heap -> Stmt -> Prop :=\n(*\n  [PROBLEM 2]\n  Add the rules (constructors) for the small step semantics of\n  our extended version of IMP.  I have 10 rules in my solution.\n\n  * NOTE *\n  For statements that involve branching (Cond and While), the\n  \"then\" / \"enter loop\" branch should be taken when the condition\n  expression evaluates to something not equal to 0, and the\n  \"else\" / \"exit loop\" branch should be taken when the condition\n  expression evaluates to 0.\n*)\n.\n\n(*\n  [PROBLEM 3]\n  In a short English paragraph, explain why our language would be much less\n  useful if popping a heap did not copy one value from the popped heap.\n*)\n\n(*\n  [PROBLEM 4]\n  Give an interesting IMP program that uses both \"PushHeap\" and \"PopHeap x\".\n*)\n\n(* Interpreters *)\n\n(*\n  In class we saw how to implement and verify a function\n  that evaluates expressions:\n*)\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\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\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\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\n\n(* [Problem 5] *)\n(* Write a function which tests whether a statement is a Skip statement. *)\nDefinition isSkip (s: Stmt) : bool :=\n (* TODO *)\n false.\n\n(* [Problem 6] *)\n(* Prove isSkip correct in the true case. *)\nLemma isSkip_t:\n  forall s, isSkip s = true -> s = Skip.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 7] *)\n(* Prove isSkip correct in the false case. *)\nLemma isSkip_f:\n  forall s, isSkip s = false -> s <> Skip.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 8] *)\n(* Implement step as a function. *)\n(* Hint: Use your isSkip function in the Seq case. *)\n(* Hint: Z.eq_dec decides if a Z is equal to 0. *)\nCheck Z.eq_dec.\nFixpoint step (l: list Heap) (h: Heap) (s: Stmt) :\n  option (list Heap * Heap * Stmt) :=\n  (* TODO *)\n  None.\n\n(* [Problem 9] *)\n(* Prove that only Skip cannot step. *)\nLemma step_None_Skip:\n  forall l h s, step l h s = None -> s = Skip.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 10] *)\n(* Prove that your step function is SOUND with respect to the Step relation. *)\nLemma step_Step:\n  forall l h s l' h' s',\n  step l h s = Some (l', h', s') -> Step l h s l' h' s'.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 11] *)\n(* Prove that your step function is COMPLETE with respect to the Step relation. *)\nLemma Step_step:\n  forall l h s l' h' s',\n  Step l h s l' h' s' -> step l h s = Some (l', h', s').\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* StepN as seen in class *)\nInductive StepN : list Heap -> Heap -> Stmt -> nat ->\n                  list Heap -> Heap -> Stmt -> Prop :=\n| StepN_refl : forall l h s,\n  StepN l h s 0 l h s\n| StepN_step : forall l h s l' h' s' l'' h'' s'' n,\n  Step l h s l' h' s' ->\n  StepN l' h' s' n l'' h'' s'' ->\n  StepN l h s (S n) l'' h'' s''.\n\n(* [Problem 12] *)\n(* Implement stepn as a function. *)\nFixpoint stepn (l: list Heap) (h: Heap) (s: Stmt) (n: nat) :\n  option (list Heap * Heap * Stmt) :=\n  (* TODO *)\n  None.\n\n(* [Problem 13] *)\n(* Prove your stepn function SOUND. *)\nLemma stepn_StepN:\n  forall n l h s l' h' s',\n  stepn l h s n = Some (l', h', s') ->\n  StepN l h s n l' h' s'.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 14] *)\n(* Prove your stepn function COMPLETE. *)\nLemma StepN_stepn:\n  forall l h s n l' h' s',\n  StepN l h s n l' h' s' ->\n  stepn l h s n = Some (l', h', s').\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* The run function, which takes up to n steps. *)\nFixpoint run (n: nat) (l: list Heap) (h: Heap) (s: Stmt) : list Heap * Heap * Stmt :=\n  match n with\n    | O => (l, h, s)\n    | S m =>\n      match step l h s with\n        | Some (l', h', s') => run m l' h' s'\n        | None => (l, h, s)\n      end\n  end.\n\n(* [Problem 15] *)\n(* Define the StepStar relation, which corresponds to taking any number of steps. *)\nInductive StepStar : list Heap -> Heap -> Stmt ->\n                     list Heap -> Heap -> Stmt -> Prop :=\n  (* TODO *)\n.\n\n(* [Problem 16] *)\n(* Prove that run is SOUND with respect to StepStar. *)\nLemma run_StepStar:\n  forall n l h s l' h' s',\n  run n l h s = (l', h', s') -> StepStar l h s l' h' s'.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 17] *)\n(* Prove that running a state that can't step gives that same state. *)\nLemma nostep_run_refl:\n  forall l h s, step l h s = None ->\n  forall n, run n l h s = (l, h, s).\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* [Problem 18] *)\n(* Prove that two consecutive runs are the same as one bigger run. *)\nLemma run_combine:\n  forall m n l h s l' h' s' l'' h'' s'',\n  run m l h s = (l', h', s') ->\n  run n l' h' s' = (l'', h'', s'') ->\n  run (m + n) l h s = (l'', h'', s'').\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n\n(* Here we define what it means for a statement to contain a while. *)\nFixpoint hasWhile (s: Stmt) : bool :=\n  match s with\n    | Skip => false\n    | Assign _ _ => false\n    | Seq s1 s2 => orb (hasWhile s1) (hasWhile s2)\n    | Cond _ s1 s2 =>  orb (hasWhile s1) (hasWhile s2)\n    | While _ _ => true\n    | PushHeap => false\n    | PopHeap _ => false\n  end.\n\n(* Here we define the number of PushHeap statements contained in a statement. *)\nFixpoint nPushHeap (s: Stmt) : nat :=\n  match s with\n    | Skip => 0\n    | Assign _ _ => 0\n    | Seq s1 s2 => nPushHeap s1 + nPushHeap s2\n    | Cond _ s1 s2 => nPushHeap s1 + nPushHeap s2\n    | While _ s1 => nPushHeap s1\n    | PushHeap => 1\n    | PopHeap _ => 0\n  end.\n\n(*\n  [Problem 19]\n  Prove that if we take a step from a statement without any whiles,\n  then the resulting statement still has no whiles.\n*)\nLemma hasWhileStep:\n  forall l h s l' h' s',\n    Step l h s l' h' s' ->\n    hasWhile s = false ->\n    hasWhile s' = false.\nProof.\n  (* TODO *)\n  admit.\nQed.\n\n(* *** A BIT TRICKY! *** *)\n(*\n  [Problem 20]\n\n  State and prove the following property:\n    If statement s has no While loops and from the empty stack\n    (l = nil) and empty heap (h = nil), s can step to stack l',\n    heap h', and statement s', then the length of l' does not\n    exceed the number of PushHeap statements in s (the original\n    statement).\n\n  Hints:\n    - You will need two lemmas to prove this.\n    - Think carefully about your induction hypotheses.\n*)\n\n(*\n  [Problem 21]\n\n  Prove the previous claim is false if we allow s to contain\n  While loops.\n\n  Hint:\n    - No need to use induction.\n*)\n\n(* Define a weak notion of equivalence between programs. *)\nDefinition equiv (s1 s2: Stmt) :=\n  forall l1' h1' l2' h2',\n  StepStar nil nil s1 l1' h1' Skip ->\n  StepStar nil nil s2 l2' h2' Skip ->\n  l1' = l2' /\\ h1' = h2'.\n\n(*\n  [Problem 22]\n  Prove the following equivalence.\n*)\nLemma progs_equiv:\n  ~ (forall s x,\n  equiv (Seq s (Assign x (Int 0%Z))\n        (Seq PushHeap (Seq s (PopHeap x)))).\nProof.\n  (* TODO *)\n  admit.\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/hw02/hw02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.7618808174225402}}
{"text": "(** * Rel: Properties of Relations *)\n\n(* $Date: 2014-08-24 04:24:59 +0900 (2014年08月24日 (日)) $ *)\n\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\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(* Print 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\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 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\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 ->\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  (* 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": "tyage", "repo": "coq-practice", "sha": "bb6e60c7cbd87bebea786abc58821d22ce822eba", "save_path": "github-repos/coq/tyage-coq-practice", "path": "github-repos/coq/tyage-coq-practice/coq-practice-bb6e60c7cbd87bebea786abc58821d22ce822eba/sf/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7618808140665336}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import FinTypes. \nFrom Complexity.NP.Clique Require Import UGraph. \nRequire Import Lia.\n\nSection fixGraph. \n  Variable (g : UGraph). \n  Notation V := (V g).\n  Notation E := (@E g).\n\n  Definition isClique (l : list V) := (forall v1 v2, v1 el l -> v2 el l -> v1 <> v2 -> E (v1, v2)) /\\ dupfree l. \n  Definition isKClique k (l : list V) := |l| = k /\\ isClique l. \n\n  (** an alternative inductive characterisation *)\n  Inductive indKClique : nat -> list V -> Prop := \n    | indKCliqueNil : indKClique 0 []\n    | indKCliqueS L v k : indKClique k L -> not (v el L) -> (forall v', v' el L -> E (v, v')) -> indKClique (S k) (v :: L). \n  Hint Constructors indKClique : core. \n\n  Lemma indKClique_iff k L: isKClique k L <-> indKClique k L. \n  Proof. \n    split.\n    - intros [H1 [H2 H3]]. revert L H1 H2 H3. induction k; intros. \n      + destruct L; cbn in H1; [ eauto | congruence].\n      + destruct L; cbn in *; [congruence | ].\n        constructor.\n        * apply IHk; [lia | intros; apply H2; eauto | now inv H3].\n        * now inv H3. \n        * intros v' Hel. apply H2; [eauto | eauto | ]. inv H3. intros ->. congruence.\n    - induction 1 as [ | ? ? ? ? IH]. \n      + split; [ | split]; [now cbn | intros ? ? [] | constructor].\n      + destruct IH as (IH1 & IH2 & IH3). split; [ | split].\n        * cbn. lia.\n        * intros v1 v2 [-> | H2] [-> | H3] H4; try congruence.\n          -- now apply H1. \n          -- apply E_symm. now apply H1. \n          -- now apply IH2. \n        * now constructor.\n  Qed. \nEnd fixGraph. \n  \nDefinition Clique (i : UGraph * nat) := let (g, k) := i in exists l, @isKClique g k l.  \n\n\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/Clique/Clique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7617878390686204}}
{"text": "Require Import OrdersFacts.\nRequire Import OrdersTac.\nRequire Import QArith.\nRequire Import QOrderedType.\n\n(* Auxiliary facts about Q that don't seem to be readily to\n   hand in the standard library. *)\n\nLocal Open Scope Q.\n\nLemma Q_mul_pos_pos : forall p q : Q, 0 < p -> 0 < q -> 0 < p * q.\nProof.\n  intros p q; unfold Qlt; simpl; rewrite ?Z.mul_1_r; apply Z.mul_pos_pos.\nQed.\n\n\nDefinition QPos := { x : Q | 0 < x }.\n\nDelimit Scope QPos_scope with QPos.\n\nLocal Open Scope QPos.\n\nModule Type OrderedTypeFullWithOrderFunctions :=\n  OrderedTypeFull <+ HasBoolOrdFuns <+ BoolOrdSpecs.\n\nModule QPos\n <: BooleanDecidableType\n <: OrderedTypeFullWithOrderFunctions\n <: LtBool\n <: TotalOrder.\n\nDefinition t := QPos.\n\nLocal Notation \"!\" := proj1_sig.\n\nDefinition eq (p q : t) := (!p == !q)%Q.\nDefinition lt (p q : t) := (!p < !q)%Q.\nDefinition le (p q : t) := (!p <= !q)%Q.\nDefinition compare (p q : t) := (!p ?= !q)%Q.\n\nInfix \"==\" := eq : QPos_scope.\nInfix \"<\" := lt : QPos_scope.\nInfix \"<=\" := le : QPos_scope.\nInfix \"?=\" := compare (at level 70, no associativity) : QPos_scope.\n\nInstance eq_equiv : Equivalence eq.\nProof.\n  split; unfold eq; [intros p | intros p q | intros p q r]; apply Q_Setoid.\nQed.\n\nInstance lt_strorder : StrictOrder lt.\nProof.\n  split; unfold lt; [ intros q ; unfold complement | intros p q r];\n  apply QOrder.TO.lt_strorder.\nQed.\n\nInstance lt_compat : Proper (eq==>eq==>iff) lt.\nProof.\n  split; unfold lt; unfold eq in H, H0; rewrite H; rewrite H0; trivial.\nQed.\n\nLemma le_lteq p q : p <= q <-> p < q \\/ p == q.\nProof. split; unfold eq, le, lt; apply Qle_lteq. Qed.\n\nLemma lt_total p q : p < q \\/ p == q \\/ q < p.\nProof. unfold eq, lt; apply QOrder.TO.lt_total. Qed.\n\nLemma eq_dec p q : { p == q } + { ~ p == q }.\nProof. unfold eq; apply QOrder.TO.eq_dec. Qed.\n\nDefinition eqb p q := if eq_dec p q then true else false.\nDefinition leb p q := match p ?= q with | Gt => false | _ => true end.\nDefinition ltb p q := match p ?= q with | Lt => true | _ => false end.\n\nInfix \"=?\" := eqb (at level 70, no associativity) : QPos_scope.\nInfix \"<=?\" := leb (at level 70, no associativity) : QPos_scope.\nInfix \"<?\" := ltb (at level 70, no associativity) : QPos_scope.\n\nLemma eqb_eq p q : (p =? q) = true <-> p == q.\nProof. unfold eq, eqb; destruct (eq_dec p q); intuition. Qed.\n\nLemma ltb_lt p q : (p <? q) = true <-> p < q.\nProof.\n  unfold ltb, lt, compare; rewrite Qlt_alt; case (!p ?= !q)%Q; split; easy.\nQed.\n\nLemma leb_le p q : (p <=? q) = true <-> p <= q.\nProof.\n  unfold leb, le, compare; rewrite Qle_alt; case (!p ?= !q)%Q; split; easy'.\nQed.\n\nLemma compare_spec p q : CompareSpec (p == q) (p < q) (q < p) (p ?= q).\nProof.\n  unfold eq, lt, compare; case Qcompare_spec; now constructor.\nQed.\n\nInclude OrderedTypeFullFacts.\n\n(* Arithmetic *)\n\nDefinition one : t.\n  refine (exist _ (inject_Z 1) _); easy.\nDefined.\n\nDefinition two : t.\n  refine (exist _ (inject_Z 2) _); easy.\nDefined.\n\nNotation \"1\" := one : QPos_scope.\nNotation \"2\" := two : QPos_scope.\n\n(* Multiplication: definition and order. *)\n\nDefinition mul (p q : t) : t.\n  refine (exist _ (!p * !q) _); destruct p, q; now apply Q_mul_pos_pos.\nDefined.\n\nInfix \"*\" := mul : QPos_scope.\n\n(* Basic facts about multiplication. *)\n\nLemma mul_assoc p q r : p * (q * r) == (p * q) * r.\nProof.\n  apply Qmult_assoc.\nQed.\n\nLemma mul_comm p q : p * q == q * p.\nProof.\n  apply Qmult_comm.\nQed.\n\nLemma mul_1_l p : 1 * p == p.\nProof.\n  apply Qmult_1_l.\nQed.\n\nLemma mul_1_r p : p * 1 == p.\nProof.\n  apply Qmult_1_r.\nQed. \n\n(* Multiplication and order. *)\n\nLemma mul_le_mono_l p q r : q <= r  <->  p * q <= p * r.\nProof.\n  split; apply Qmult_le_l; now destruct p.\nQed.\n\nLemma mul_le_mono_r p q r : q <= r  <->  q * p <= r * p.\nProof.\n  split; apply Qmult_le_r; now destruct p.\nQed.\n\nLemma mul_lt_mono_l p q r :  q < r  <->  p * q < p * r.\nProof.\n  split; apply Qmult_lt_l; now destruct p.\nQed.\n\nLemma mul_lt_mono_r p q r :  q < r  <->  q * p < r * p.\nProof.\n  split; apply Qmult_lt_r; now destruct p.\nQed.\n\n(* Reciprocal. *)\n\nDefinition inv (p : t) : t.\n  refine (exist _ (/ !p)%Q _); apply Qinv_lt_0_compat; now destruct p.\nDefined.\n\nNotation \"/ x\" := (inv x).\n\nLemma mul_inv_r p : p * /p == 1.\nProof.\n  apply Qmult_inv_r; destruct p; simpl; QOrder.order.\nQed.\n\n(* Division. *)\n\nDefinition div (p q : t) : t := p * /q.\n\nInfix \"/\" := div : QPos_scope.\n\n(* QPos and the positive type. *)\n\nDefinition from_pos (m : positive) : t.\n  refine (exist _ (inject_Z (' m)) _); apply Pos2Z.is_pos.\nDefined.\n\nLemma as_fraction (p : t) :\n  exists (m n : positive), p == (from_pos m) / (from_pos n).\nProof.\n  destruct p; exists (Z.to_pos (Qnum x)), (Qden x); unfold eq; simpl; rewrite Z2Pos.id.\n  unfold Qeq; simpl; ring.\n  unfold Qlt in q; simpl in q; ring_simplify in q; easy.\nQed.\n\nEnd QPos.\n\n(* Re-export notations. *)\n\nInfix \"==\" := QPos.eq : QPos_scope.\nInfix \"<\" := QPos.lt : QPos_scope.\nInfix \"<=\" := QPos.le : QPos_scope.\nNotation \"p > q\" := (q < p) (only parsing) : QPos_scope.\nNotation \"p >= q\" := (q <= p) (only parsing) : QPos_scope.\n\nInfix \"?=\" := QPos.compare (at level 70, no associativity) : QPos_scope.\nInfix \"=?\" := QPos.eqb (at level 70, no associativity) : QPos_scope.\nInfix \"<=?\" := QPos.leb (at level 70, no associativity) : QPos_scope.\nInfix \"<?\" := QPos.ltb (at level 70, no associativity) : QPos_scope.\n\nInfix \"*\" := QPos.mul : QPos_scope.\nInfix \"/\" := QPos.div : QPos_scope.\nNotation \"/ p\" := (QPos.inv p) : QPos_scope.\n\nNotation \"1\" := QPos.one : QPos_scope.\nNotation \"2\" := QPos.two : QPos_scope.\n\nNotation \"x < y < z\" := ((x < y) /\\ (y < z)) : QPos_scope.\nNotation \"x <= y < z\" := ((x <= y) /\\ (y < z)) : QPos_scope.\nNotation \"x < y <= z\" := ((x < y) /\\ (y <= z)) : QPos_scope.\nNotation \"x <= y <= z\" := ((x <= y) /\\ (y <= z)) : QPos_scope.\n\n(* Additional results about QPos. *)\n\nLemma QPos_le_eq p q : p == q  ->  p <= q.\nProof.\n  intro p_eq_q. rewrite p_eq_q. unfold QPos.le. destruct q. simpl. auto with qarith.\nQed.\n\n\nLemma QPos_le_antisymm q r : q <= r -> r <= q -> q == r.\nProof.\n  unfold QPos.le, QPos.eq; destruct q, r; simpl.\n  auto with qarith.\nQed.\n\n\nLemma QPos_le_refl q : q <= q.\nProof.\n  unfold QPos.le; destruct q; simpl; auto with qarith.\nQed.\n\n\n(* Positive rationals to and from positive integers. *)\n\nDefinition QPos_num (q : QPos) : positive := Z.to_pos (Qnum (proj1_sig q)).\nDefinition QPos_den (q : QPos) : positive := Qden (proj1_sig q).\n\nDefinition QPos_from_pos (p : positive) : QPos.\n  refine (exist _ (inject_Z (' p)) _); apply Pos2Z.is_pos.\nDefined.\n\n\nLemma QPos_num_positive (q : Q) : (0 < q)%Q -> ('Z.to_pos (Qnum q) = Qnum q)%Z.\nProof.\n  intros q_positive; apply Z2Pos.id; revert q_positive;\n  unfold Qlt; now rewrite Z.mul_1_r.\nQed.\n\nLemma Q_as_fraction (q : Q) : (inject_Z (Qnum q) / inject_Z (' Qden q) == q)%Q.\nProof.\n  unfold Qeq; simpl; ring.\nQed.\n\nLemma num_over_den : forall q : QPos,\n  QPos_from_pos (QPos_num q) / QPos_from_pos (QPos_den q) == q.\nProof.\n  intro q. destruct q.\n  unfold QPos.eq, QPos.div, QPos_num, QPos_den. simpl.\n  rewrite QPos_num_positive; [ | easy].\n  apply Q_as_fraction.\nQed.\n\n\nInstance QPos_Setoid : Equivalence QPos.eq.\nProof.\n  split; unfold QPos.eq; intro; [reflexivity | now symmetry |\n    intros y z; now transitivity (proj1_sig y)].\nQed.\n\nAdd Morphism QPos.lt : QPos_lt_morphism.\nProof.\n  unfold QPos.lt, QPos.eq.\n  destruct x, y. simpl. intro.\n  destruct x1, y0. simpl. intro.\n  rewrite H. rewrite H0. reflexivity.\nQed.\n\nAdd Morphism QPos.le : QPos_le_morphism.\nProof.\n  unfold QPos.le, QPos.eq.\n  destruct x, y. simpl. intro.\n  destruct x1, y0. simpl. intro.\n  rewrite H. rewrite H0. reflexivity.\nQed.\n\nAdd Morphism QPos.mul : QPos_mul_morphism.\n  unfold QPos.eq; simpl; intros; rewrite H; now rewrite H0.\nQed.\n\nAdd Morphism QPos.div : QPos_div_morphism.\n  unfold QPos.eq; simpl; intros; rewrite H; now rewrite H0.\nQed.\n\n\nLemma QPos_from_pos_lt : forall p q, (p < q)%positive  -> QPos_from_pos p < QPos_from_pos q.\nProof.\n  intros; unfold QPos.lt; simpl; rewrite <- Zlt_Qlt; unfold Zlt;\n  now apply Pos.compare_lt_iff.\nQed.\n\nLemma QPos_from_pos_le : forall p q, (p <= q)%positive ->\n  QPos_from_pos p <= QPos_from_pos q.\nProof.\n  intros. unfold QPos.le. simpl. rewrite <- Zle_Qle. unfold Zle.\n  now apply Pos.compare_le_iff.\nQed.\n\nLemma QPos_mul_inv_l p : /p * p == 1.\nProof.\n  rewrite QPos.mul_comm. apply QPos.mul_inv_r.\nQed.\n\nLemma QPos_div_mul b c : b / c * c == b.\nProof.\n  unfold QPos.div.\n  rewrite <- QPos.mul_assoc. rewrite QPos_mul_inv_l.\n  apply QPos.mul_1_r.\nQed.\n\nLemma QPos_mul_div b c : b * c / c == b.\nProof.\n  unfold QPos.div.\n  rewrite <- QPos.mul_assoc.\n  rewrite QPos.mul_inv_r.\n  apply QPos.mul_1_r.\nQed.\n\nLemma QPos_div_mul_r a b c : a == b / c  <->  a * c == b.\n  split; intro; [rewrite H | rewrite <- H].\n  apply QPos_div_mul. symmetry.  apply QPos_mul_div.\nQed.\n\nLemma QPos_div_mul_le_r a b c : b / c <= a  <->  b <= a * c.\nProof.\n  rewrite QPos.mul_le_mono_r with (p := c).\n  setoid_replace (b / c * c) with b. easy.\n  apply QPos_div_mul.\nQed.\n\nLemma QPos_div_mul_le_l a b c : a <= b / c  <->  a * c <= b.\nProof.\n  rewrite QPos.mul_le_mono_r with (p := c).\n  setoid_replace (b / c * c) with b. easy.\n  apply QPos_div_mul.\nQed.\n\nLemma QPos_div_mul_lt_l a b c : a < b / c  <->  a * c < b.\nProof.\n  rewrite QPos.mul_lt_mono_r with (p := c).\n  setoid_replace (b / c * c) with b. easy.\n  apply QPos_div_mul.\nQed.\n\nLemma QPos_div_mul_lt_r a b c : b / c < a  <->  b < a * c.\nProof.\n  rewrite QPos.mul_lt_mono_r with (p := c).\n  setoid_replace (b / c * c) with b. easy.\n  apply QPos_div_mul.\nQed.\n\nLemma QPos_from_pos_one : QPos_from_pos 1 == 1.\nProof.\n  easy.\nQed.\n\nLemma QPos_from_pos_two : QPos_from_pos 2 == 2.\nProof.\n  easy.\nQed.\n\nLemma QPos_from_pos_mul: forall p q, QPos_from_pos (p * q) == QPos_from_pos p * QPos_from_pos q.\nProof.\n  unfold QPos.eq. intros. simpl. easy.\nQed.\n\n\nLemma QPos_lt_le_weak : forall p q, p < q  -> p <= q.\nProof.\n  unfold QPos.le, QPos.lt; intros p q; destruct p, q; auto with qarith.\nQed.\n\n\n\nLemma QPos_le_lt_trans a b c : a <= b -> b < c -> a < c.\nProof.\n  unfold QPos.le, QPos.lt. destruct a, b, c. simpl.\n  apply Qle_lt_trans.\nQed.\n\nLemma QPos_mul_le_lt a b c d : a <= c -> d < b  ->  a * d < c * b.\nProof.\n  intros; apply QPos_le_lt_trans with (b := c * d);\n  [now apply QPos.mul_le_mono_r | now apply QPos.mul_lt_mono_l].\nQed.\n\nLemma QPos_div_le_lt a b c d : a <= c -> d < b  ->  a / b < c / d.\nProof.\n  intros.\n  apply QPos.mul_lt_mono_r with (p := b * d).\n  setoid_replace (a / b * (b * d)) with (a * d).\n  setoid_replace (c / d * (b * d)) with (c * b).\n  now apply QPos_mul_le_lt.\n\n  (* Left with two equality goals. Cheat by mapping to Q and using the big\n  guns. *)\n  unfold QPos.eq; destruct a, b, c, d; simpl; field; apply Qnot_eq_sym;\n  now apply Qlt_not_eq.\n\n  unfold QPos.eq; destruct a, b, c, d; simpl; field. apply Qnot_eq_sym;\n  now apply Qlt_not_eq.\nQed.\n\nLemma QPos_div_lt_le a b c d : a < c -> d <= b -> a / b < c / d.\nProof.\n  intros.\n  apply QPos.mul_lt_mono_r with (p := b * d).\n  setoid_replace (a / b * (b * d)) with (d * a).\n  setoid_replace (c / d * (b * d)) with (b * c).\n  now apply QPos_mul_le_lt.\n\n  unfold QPos.eq; destruct a, b, c, d; simpl; field; apply Qnot_eq_sym;\n  now apply Qlt_not_eq.\n\n  unfold QPos.eq; destruct a, b, c, d; simpl; field; apply Qnot_eq_sym;\n  now apply Qlt_not_eq.\nQed.\n\nLemma QPos_le_trans a b c : a <= b -> b <= c -> a <= c.\nProof.\n  destruct a, b, c; unfold QPos.le; QOrder.order.\nQed.\n\nLemma QPos_lt_le_trans a b c : a < b -> b <= c -> a < c.\nProof.\n  destruct a, b, c; unfold QPos.le, QPos.lt; apply Qlt_le_trans.\nQed.\n\nLemma QPos_lt_trans a b c : a < b -> b < c -> a < c.\nProof.\n  destruct a, b, c; unfold QPos.lt; apply Qlt_trans.\nQed.\n\n\nLemma QPos_le_ngt : forall q r, q <= r  <->  ~ (r < q).\nProof.\n  intros q r; destruct q, r; unfold QPos.le, QPos.lt; split; QOrder.order.\nQed.\n\nLemma QPos_lt_nge : forall q r, q < r  <->  ~ (r <= q).\nProof.\n  intros q r; destruct q, r; unfold QPos.le, QPos.lt; split; QOrder.order.\nQed.\n\n\nLemma QPos_ltb_le : forall q r, (q <? r) = false  <->  r <= q.\nProof.\n  unfold QPos.le, QPos.ltb, QPos.compare. intros q r. destruct q, r. simpl.\n  case_eq (x ?= x0)%Q.\n  rewrite <- Qeq_alt. intuition.\n  rewrite H. auto with qarith.\n  rewrite <- Qlt_alt. intuition. exfalso. assert (x < x)%Q.\n  eapply Qlt_le_trans; eauto. revert H1. unfold Qlt. auto with zarith.\n  rewrite <- Qgt_alt. intuition.\nQed.\n", "meta": {"author": "mdickinson", "repo": "float-proofs", "sha": "8862c6d0113b2d5a6e4b2a3df7b3763248750cfb", "save_path": "github-repos/coq/mdickinson-float-proofs", "path": "github-repos/coq/mdickinson-float-proofs/float-proofs-8862c6d0113b2d5a6e4b2a3df7b3763248750cfb/qpos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7617878352641614}}
{"text": "Fixpoint factorial (n:nat) : nat :=\n  match n with\n  | O     => 1\n  | S n'  => 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.", "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/Factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.761779948950163}}
{"text": "Require Export Basics.\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 fstt (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition sndd (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_pairingg : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  destruct p.\n  reflexivity.\nQed.\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  destruct p. reflexivity.\nQed.\n\nTheorem fst_swap_is_and : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros.\n  destruct p.\n  reflexivity.\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\nDefinition l_123' := 1 :: (2 :: (3 :: nil)).\nDefinition l_123'' := 1 :: 2 :: 3 :: nil.\nDefinition l_123''' := [1,2,3].\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 countt => n :: (repeat n countt)\n  end.\n\nEval simpl in (repeat 15).\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\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | 0 :: t => nonzeros t\n  | h :: t => h :: (nonzeros t)\n  end.\n\nExample test_nonzeros: nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity. Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match oddb h with\n              | true => h :: (oddmembers t)\n              | false => oddmembers t\n              end\n  end.\n\nExample test_oddmembers: oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => match oddb h with\n              | true => S (countoddmembers t)\n              | false => countoddmembers t\n              end\n  end.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\nProof. reflexivity. Qed.\nExample testcountoddmembers2: countoddmembers [0,2,4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, x2 => x2\n  | x1, nil => x1\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. 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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\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.\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_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nProof. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n  [v] ++ s.\n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\nProof. reflexivity. Qed.\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  | O => false\n  | S _ => true\n  end.\n\nExample test_member1: member 1 [1,4,1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\nProof. reflexivity. Qed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => match beq_nat v h with\n              | true => t\n              | false => h :: (remove_one v t)\n              end\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  | h :: t => match beq_nat v h with\n              | true => remove_all v t\n              | false => h :: (remove_all v t)\n              end\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1, s2 with\n  | nil, _ => true\n  | h :: t, s22 => match member h s22 with\n                   | true => subset t (remove_one h s22)\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\nTheorem nil_app : forall (l : natlist), \n  [] ++ l = l.\nProof.\nreflexivity.\nQed.\n\nTheorem tl_length_pred : forall (l : natlist),\n  pred (length l) = length (tail l).\nProof.\n  intros.\n  destruct l as [ | ll].\n  reflexivity. reflexivity.\nQed.\n\nTheorem app_ass : forall (l1 l2 l3 : natlist),\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros.\n  induction l1.\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1\".\n    simpl. rewrite IHl1.\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. reflexivity.\n  simpl. rewrite IHl1. 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\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) (l:natlist),\n  length (snoc l n) = S (length l).\nProof.\n  intros. induction l. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem rev_length : forall (l : natlist),\n  length (rev l) = length l.\nProof.\n  intros.\n  induction l. reflexivity.\n  simpl. rewrite length_snoc.\n  rewrite IHl. reflexivity.\nQed.\n\n(* Usar SearchAbout blablabla *)\n\nTheorem app_nil_end : forall (l : natlist),\n  l ++ [] = l.\nProof.\n  intros.\n  induction l. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma snoc_simpl : forall (n:nat) (l:natlist),\n  snoc l n   = l ++ [n].\nProof.\n  intros.\n  induction l. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed. \n\nTheorem distr_rev : forall (l1 l2 : natlist),\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros.\n  induction l1. simpl. rewrite app_nil_end. reflexivity.\n  simpl. rewrite snoc_simpl.  rewrite snoc_simpl. rewrite IHl1. rewrite app_ass.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall (l:natlist),\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l. reflexivity.\n  simpl. rewrite snoc_simpl.\n  rewrite distr_rev. rewrite IHl.\n  reflexivity.\nQed.\n\nTheorem app_ass4 : forall (l1 l2 l3 l4:natlist),\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros. rewrite app_ass. rewrite app_ass.\n  reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros.  \n  induction l. reflexivity. \n  simpl. rewrite IHl. reflexivity.\nQed.\n\n\nLemma nonzeros_length : forall (l1 l2 : natlist),\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros.\n  induction l1. reflexivity. assert (H : (n :: l1) ++ l2 = n :: (l1 ++ l2)).\n  simpl.\n  reflexivity.\n  rewrite H.\n  destruct n.\n  simpl. apply IHl1.\n  simpl.\n  rewrite IHl1.\n  reflexivity.\nQed. \n\n\n\nTheorem count_member_nonzero : forall (s:bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intros.\n  destruct s; reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall (n:nat),\n  ble_nat n (S n) = true.\nProof.\n  intros. induction n. reflexivity.\n  simpl. rewrite IHn. reflexivity.\nQed.\n\n\nTheorem remove_decreases_count : forall (s:bag),\n  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros.\n  induction s. reflexivity.\n  destruct n.\n  simpl.\n  rewrite ble_n_Sn.\n  reflexivity.\n  simpl.\n  apply IHs.\nQed.\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 (* arbitrary *)\n  | a :: l' => match beq_nat n 0 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 0 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\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n 0 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\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\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim (hd_opt l) default.\nProof.\n  intros. induction l; reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | [], [] => true\n  | [], _ => false\n  | _, [] => false\n  | h1 :: t1, h2 :: t2 => if beq_nat h1 h2 then beq_natlist t1 t2 else false\n  end.\n\nExample test_beq_natlist1  : (beq_natlist nil nil = true).\nProof. reflexivity. Qed.\nExample test_beq_natlist2 : beq_natlist [1,2,3] [1,2,3] = true.\nProof. reflexivity. Qed.\nExample test_beq_natlist3 : beq_natlist [1,2,3] [1,2,4] = false.\nProof. reflexivity. Qed.\n\nTheorem beq_natlist_refl : forall (l:natlist),\n  true = beq_natlist l l.\nProof.\n  intros. induction l. reflexivity.\n  rewrite IHl. simpl.\n  replace (beq_nat n n) with (true).\n  reflexivity. induction n. reflexivity. simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem silly1 : forall (n m o p : nat),\n  n = m -> [n,o] = [n,p] -> [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 -> (forall (q r:nat), q = r -> \n           [q,o] = [r,p]) -> [n,o] = [m,p].\nProof.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\n(*  /\\ IMPOSSÍVEL COM REWRITE?   *)\n\nTheorem silly2a : forall (n m : nat),\n  (n,n) = (m,m) -> \n      (forall (q r:nat), (q,q) = (r,r) ->\n             [q] = [r]) ->\n                 [n] = [m].\nProof.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nTheorem silly_ex : (forall (n:nat), evenb n = true -> oddb (S n) = true) ->\n   evenb 3 = true -> oddb 4 = true.\nProof.\n  intros. apply H0. (* ou apply H0 ??? *)\nQed.\n\nTheorem silly3_firsttry : forall (n:nat),\n  true = beq_nat n 5 -> beq_nat (S (S n)) 7 = true.\nProof.\n  intros.\n  simpl.\n  symmetry in H.\n  assumption.\nQed.\n\nTheorem sill3y3: forall (n:nat),\n  true = beq_nat n 5 ->\n  beq_nat (S (S n)) 7 = true.\nProof.\n  intros.\n  simpl. symmetry. apply H.\nQed.\n\nTheorem rev_exercise1 : forall (l l' : natlist),\n  l = rev l' -> l' = rev l.\nProof.\n  intros.\n  rewrite H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\n\nTheorem app_ass' : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1. induction l1 as [ | n l1'].\n  reflexivity.\n  assert (H : forall l2 l3, ((n::l1') ++ l2) ++ l3 = n :: (l1' ++ l2 ++ l3)).\nAdmitted.\n\n\n\n\n\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/List.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8840392848011833, "lm_q1q2_score": 0.761633628780041}}
{"text": "Inductive list (X : Type) : Type :=\n  | nil \n  | cons (x : X) (l : list X).\n\nDefinition natlist := cons nat.\nDefinition boollist := cons bool.\n\nCheck natlist 1 (nil nat).\nCheck boollist true (nil bool).\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\nExample test_repeat :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof.\n  reflexivity.\nQed.\n  \nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof.\n  reflexivity.\nQed.\n\nModule MumbleGrumble.\n\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     \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\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\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck list123''.\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'\n  | cons' (x : X) (l : 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\nEval compute in rev (cons 2 (cons 1 nil)).\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\nEval compute in length (cons 1 (cons 2 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\nTheorem app_nil_r : forall (X : Type), forall l : list X,\n      l ++ [] = l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\n Qed.\n\nTheorem app_assoc : forall A (l m n : list A),\n    l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros. induction l as [| x l1' IHl1'].\n  - 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.\n  intros. induction l1 as [| n l1' IHl1'].\n  - 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. induction l1 as [| n l1' IHl1'].\n  - rewrite app_nil_r. simpl. 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 as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl'. reflexivity.\nQed.\n\n\nInductive prod (X Y : Type) : Type :=\n | pair (x : X) (y : Y).\n\nArguments pair {X} {Y}.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition scn {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;3] [true;false;false;true].\n               \n \nCheck @combine.\n\n\n\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7616336162085686}}
{"text": "(*\n\n=================================================================\n                 PERMUTATIVE GROUP OF FUNCTIONS\n=================================================================\n\nThe permutative group of functions is defined as a single axiom:\n\n                                        ∃ n : nat { f^n <=> id }\n\nIt has been proved that this axiom implies the axioms of Group Theory\nfor any natural number `n`:\n\nhttps://github.com/advancedresearch/path_semantics/blob/master/papers-wip/permutation-group-of-functions.pdf\n\nThis makes it possible to prove formally with a proof assistant whether\na function generates a permutative group.\n\nHere are some simple examples.\n\nChecked with Coq IDE 8.11.0 (https://coq.inria.fr/)\n\n*)\n\n(* Function composition *)\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x : A => g (f x).\n\n(* Recursive composition `f^n` *)\nFixpoint compn {A : Type} (f : A -> A) (n : nat) :=\n  match n with\n  | 0 => fun x : A => x\n  | 1 => fun x : A => f x\n  | S r => fun x : A => (compn f r) (f x)\n  end.\n\n(* Identity function *)\nDefinition id {A : Type} := fun x: A => x.\n\n(* Permutation group of functions *)\nDefinition fgroup {A : Type} (f : A -> A) :=\n  exists n : nat, (compn f n) = @id A.\n\n(* Prove that identity function of natural numbers is a group *)\nTheorem id_nat_is_fgroup : fgroup (@id nat).\nProof.\n  unfold id.\n  unfold fgroup.\n  pose (two := 2).\n  refine (ex_intro _ two _).\n  unfold compn.\n  auto.\nQed.\n\n(* Prove that identity function of any type is a group *)\nTheorem id_is_fgroup (A : Type) : fgroup (@id A).\nProof.\n  unfold id.\n  unfold fgroup.\n  pose (two := 2).\n  refine (ex_intro _ two _).\n  unfold compn.\n  auto.\nQed.\n\n(* Logical NOT *)\nDefinition not := fun x : bool =>\n  match x with\n  | true => false\n  | false => true\n  end.\n\n(* Use functional extensionality *)\nFrom Coq Require Import FunctionalExtensionality.\n\n(* Prove logical NOT is a group *)\nTheorem not_is_fgroup : fgroup not.\nProof.\n  pose (two := 2).\n  refine (ex_intro _ two _).\n  compute.\n  apply functional_extensionality.\n  intro b.\n  elim b.\n  reflexivity.\n  reflexivity.\nQed.\n\nInductive nat3 : Set :=\n  | one : nat3\n  | two : nat3\n  | three : nat3.\n\nDefinition one_two_three := fun x : nat3 =>\n  match x with\n  | one => two\n  | two => three\n  | three => one\n  end.\n\nTheorem one_two_three_is_fgroup : fgroup one_two_three.\nProof.\n  pose (x := 3).\n  refine (ex_intro _ x _).\n  compute.\n  apply functional_extensionality.\n  intro y.\n  (* Prove case by case and apply reflexivity to each branch *)\n  elim y; reflexivity.\nQed.\n", "meta": {"author": "advancedresearch", "repo": "permutative_group_of_functions", "sha": "7fda0b7cef68912ff82c1f161d6c9cc340e6b115", "save_path": "github-repos/coq/advancedresearch-permutative_group_of_functions", "path": "github-repos/coq/advancedresearch-permutative_group_of_functions/permutative_group_of_functions-7fda0b7cef68912ff82c1f161d6c9cc340e6b115/permutative_group_of_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.761596869681509}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Structures.Orders.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ZUtil.EquivModulo.\nRequire Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.\n\nRequire Import Crypto.Util.Notations.\nImport ListNotations Weight. Local Open Scope Z_scope.\n\n(* extra name wrapper so partition won't be confused with List.partition *)\nModule Partition.\n  Definition partition (weight : nat -> Z) n x :=\n    map (fun i => (x mod weight (S i)) / weight i) (seq 0 n).\nEnd Partition.\n\nSection PartitionProofs.\n  Context weight {wprops : @weight_properties weight}.\n  Local Notation partition := (Partition.partition weight).\n\n  Lemma partition_step n x :\n    partition (S n) x = partition n x ++ [(x mod weight (S n)) / weight n].\n  Proof using Type.\n    cbv [partition]. rewrite seq_snoc.\n    autorewrite with natsimplify push_map. reflexivity.\n  Qed.\n\n  Lemma length_partition n x : length (partition n x) = n.\n  Proof using Type. cbv [partition]; distr_length. Qed.\n  Hint Rewrite length_partition : distr_length.\n\n  Lemma eval_partition n x :\n    Positional.eval weight n (partition n x) = x mod (weight n).\n  Proof using wprops.\n    induction n; intros.\n    { cbn. rewrite (weight_0); auto with zarith. }\n    { rewrite (Z.div_mod (x mod weight (S n)) (weight n)) by auto with zarith.\n      rewrite <-Znumtheory.Zmod_div_mod by (try apply Z.mod_divide; auto with zarith).\n      rewrite partition_step, Positional.eval_snoc with (n:=n) by distr_length.\n      lia. }\n  Qed.\n\n  Lemma partition_Proper n :\n    Proper (Z.equiv_modulo (weight n) ==> eq) (partition n).\n  Proof using wprops.\n    cbv [Proper Z.equiv_modulo respectful].\n    intros x y Hxy; induction n; intros.\n    { reflexivity. }\n    { assert (Hxyn : x mod weight n = y mod weight n).\n      { erewrite (Znumtheory.Zmod_div_mod _ (weight (S n)) x), (Znumtheory.Zmod_div_mod _ (weight (S n)) y), Hxy\n          by (try apply Z.mod_divide; auto with zarith);\n          reflexivity. }\n      rewrite !partition_step, IHn by eauto.\n      rewrite (Z.div_mod (x mod weight (S n)) (weight n)), (Z.div_mod (y mod weight (S n)) (weight n)) by auto with zarith.\n      rewrite <-!Znumtheory.Zmod_div_mod by (try apply Z.mod_divide; auto with zarith).\n      rewrite Hxy, Hxyn; reflexivity. }\n  Qed.\n\n  (* This is basically a shortcut for:\n       apply partition_Proper; [ | cbv [Z.equiv_modulo] *)\n  Lemma partition_eq_mod x y n :\n    x mod weight n = y mod weight n ->\n    partition n x = partition n y.\n  Proof using wprops. apply partition_Proper. Qed.\n\n  Lemma nth_default_partition d n x i :\n    (i < n)%nat ->\n    nth_default d (partition n x) i = x mod weight (S i) / weight i.\n  Proof using Type.\n    cbv [partition]; intros.\n    rewrite map_nth_default with (x:=0%nat) by distr_length.\n    autorewrite with push_nth_default natsimplify. reflexivity.\n  Qed.\n\n  Lemma nth_default_partition_full d n x i :\n    nth_default d (partition n x) i = if lt_dec i n then x mod weight (S i) / weight i else d.\n  Proof using Type.\n    break_innermost_match;\n      try now rewrite nth_default_out_of_bounds by distr_length.\n    now rewrite nth_default_partition by lia.\n  Qed.\n\n  Fixpoint recursive_partition n i x :=\n    match n with\n    | O => []\n    | S n' => x mod (weight (S i) / weight i) :: recursive_partition n' (S i) (x / (weight (S i) / weight i))\n    end.\n\n  Lemma recursive_partition_equiv' n : forall x j,\n      map (fun i => x mod weight (S i) / weight i) (seq j n) = recursive_partition n j (x / weight j).\n  Proof using wprops.\n    induction n; [reflexivity|].\n    intros; cbn. rewrite IHn.\n    pose proof (@weight_positive _ wprops j).\n    pose proof (@weight_divides _ wprops j).\n    f_equal;\n      repeat match goal with\n             | _ => rewrite Z.mod_pull_div by auto with zarith\n             | _ => rewrite weight_multiples by auto with zarith\n             | _ => progress autorewrite with zsimplify_fast zdiv_to_mod pull_Zdiv\n             | _ => reflexivity\n             end.\n  Qed.\n\n  Lemma recursive_partition_equiv n x :\n    partition n x = recursive_partition n 0%nat x.\n  Proof using wprops.\n    cbv [partition]. rewrite recursive_partition_equiv'.\n    rewrite weight_0 by auto; autorewrite with zsimplify_fast.\n    reflexivity.\n  Qed.\n\n  Lemma length_recursive_partition n : forall i x,\n      length (recursive_partition n i x) = n.\n  Proof using Type.\n    induction n; cbn [recursive_partition]; [reflexivity | ].\n    intros; distr_length; auto.\n  Qed.\n\n  Lemma drop_high_to_length_partition n m x :\n    (n <= m)%nat ->\n    Positional.drop_high_to_length n (partition m x) = partition n x.\n  Proof using Type.\n    cbv [Positional.drop_high_to_length partition]; intros.\n    autorewrite with push_firstn.\n    rewrite Nat.min_l by lia.\n    reflexivity.\n  Qed.\n\n  Lemma partition_0 n : partition n 0 = Positional.zeros n.\n  Proof.\n    cbv [partition].\n    erewrite Positional.zeros_ext_map with (p:=seq 0 n) by distr_length.\n    apply map_ext; intros.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n\nEnd PartitionProofs.\n#[global]\nHint Rewrite length_partition length_recursive_partition : distr_length.\n#[global]\nHint Rewrite eval_partition using (solve [auto; distr_length]) : push_eval.\n#[global]\nHint Rewrite nth_default_partition_full : push_nth_default.\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/Partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7615968619550441}}
{"text": "(* A category is very much like a graph. It has vertices\n   named objects and vertices named arrows. Each arrow goes\n   from an object to an object (possibly the same!). *)\nRecord Cat (obj: Type) (arr: obj -> obj -> Type) : Type :=\n  MkCat {\n    (* For each object, there is an arrow called `id` which\n       goes from the object to itself. *)\n    id: forall {o: obj}, arr o o;\n\n    (* Given an arrow `f` from object `a` to `b` and an arrow\n       `g` from `b` to `c`. We can compose these arrow. The\n       result is an arrow from `a` to `c`. *)\n    compose: forall {a b c: obj}, arr a b -> arr b c -> arr a c;\n              \n    (* Here comes some properties of `id` and `compose` *)\n\n    (* For any arrow `f`, compose id f = f *)\n    neutralLeft:   forall {a b: obj} (f: arr a b), compose id f = f;\n\n    (* For any arrow `f`, compose f id = f  *)\n    neutralRight:  forall {a b: obj} (f: arr a b), compose f id = f;\n\n    (* For any arrows `f`, `g` and `h`,\n        composing f with g, and then the result with h\n       gives exatctly the same result as\n        composing f with the result of the composition of g and h\n\n       Which means, like string concatenation than we can commpose\n       the way we preserve the order of each element in the sequence. *)    \n    associativity: forall {a b c d: obj} (f: arr a b) (g: arr b c) (h: arr c d),\n                     compose (compose f g) h = compose f (compose g h);\n  }.\n\nArguments MkCat {_} {_}.\n\n(* `LE n m` encode the property that `n ≤ m`\n    i.e. `n` is less or equal to `m` *)  \nInductive LE : nat -> nat -> Prop :=\n    LERefl: forall {o: nat}, LE o o\n  | LENext: forall {a b: nat}, LE a b -> LE a (S b)\n.\n\n(* Taking naturals as objects and `LE` as arrows,\n   this actually forms a category! *)\nDefinition natPoset: Cat nat LE := ???\n.", "meta": {"author": "chrilves", "repo": "big4-tutorial", "sha": "277e034f7152623a17527c4ae55acc7aa8ce1f89", "save_path": "github-repos/coq/chrilves-big4-tutorial", "path": "github-repos/coq/chrilves-big4-tutorial/big4-tutorial-277e034f7152623a17527c4ae55acc7aa8ce1f89/Coq/CatR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7615719616186731}}
{"text": "Require Export Coq.Lists.List.\nRequire Export Permutation.\nFrom sorting Require Export Utils.\n\nInductive sorted: list nat -> Prop := \n  | sorted_nil : sorted nil\n  | sorted_1 : forall (x : nat), sorted (x :: nil)\n  | sorted_cons : forall (x y : nat) (l : list nat),\n      x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) :=\n  forall (al : list nat), Permutation al (f al) /\\ sorted (f al).\n", "meta": {"author": "joseoliveirajr", "repo": "sorting", "sha": "a55ab8f6270d71b21df2175a871997ba3876812f", "save_path": "github-repos/coq/joseoliveirajr-sorting", "path": "github-repos/coq/joseoliveirajr-sorting/sorting-a55ab8f6270d71b21df2175a871997ba3876812f/Sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7615328680868753}}
{"text": "Require Import Matrix.\nFrom Coq Require Import Lia.\n(*\n  The following constant definitions correspond to Hamming Code being proven.\n  Providing other values should allow this .v file to prove codes beyond the\n  Hamming(7,4)\n*)\n(* Hamming(7,4) values *)\nDefinition H74_WS : nat := 4. (* Word Size *)\nDefinition H74_CS : nat := 7. (* Code Size *)\nDefinition H74_CGM : Matrix 4 7 := (* Code Generator Matrix *)\n  list2D_to_matrix\n  ([\n    [1;1;1;0;0;0;0];\n    [1;0;0;1;1;0;0];\n    [0;1;0;1;0;1;0];\n    [1;1;0;1;0;0;1]\n  ]).\nDefinition H74_PCM : Matrix 7 3 := (* Parity Check Matrix *)\n  list2D_to_matrix\n  ([\n    [1;0;0];\n    [0;1;0];\n    [1;1;0];\n    [0;0;1];\n    [1;0;1];\n    [0;1;1];\n    [1;1;1]\n  ]).\nDefinition H74_DCM : Matrix 7 4 := (* Decoder Matrix *)\n  list2D_to_matrix\n  ([\n    [0;0;0;0];\n    [0;0;0;0];\n    [1;0;0;0];\n    [0;0;0;0];\n    [0;1;0;0];\n    [0;0;1;0];\n    [0;0;0;1]\n  ]).\n(* End Hamming(7,4) Values *)\n\n(* Constant assignment (here to Hamming(7,4)) *)\nDefinition WS : nat := H74_WS.\nDefinition CS : nat := H74_CS.\nDefinition SS : nat := CS - WS. (* Syndrome (parity bit vector) Size *)\nDefinition Max_Word : nat := 2 ^ WS.\nDefinition Code_Generator_Matrix : Matrix WS CS := H74_CGM.\nDefinition Parity_Check_Matrix : Matrix CS SS := H74_PCM.\nDefinition Decoder_Matrix : Matrix CS WS := H74_DCM.\nCheck Code_Generator_Matrix.\nCheck Parity_Check_Matrix.\nCheck Decoder_Matrix.\n\nNotation Word := (Matrix 1 WS).\nDefinition WF_Word (W : Word) : Prop :=\n  WF_Matrix W /\\ forall y, W 1 y = 0 \\/ W 1 y = 1.\n\nNotation Code := (Matrix 1 CS).\nDefinition WF_Code (C : Code) : Prop :=\n  WF_Matrix C /\\ forall y, C 1 y = 0 \\/ C 1 y = 1.\n\nNotation Synd := (Matrix 1 SS).\nDefinition WF_Synd (S : Synd) : Prop :=\n  WF_Matrix S /\\ forall y, S 1 y = 0 \\/ S 1 y = 1.\n\nLtac mat_solve x y :=\n  do 8 (try destruct x; try destruct y; simpl; trivial; try lia).\n\nLemma CGM_WF : WF_Matrix Code_Generator_Matrix.\nProof. unfold WF_Matrix. intros x y [H|H]; compute in H; mat_solve x y. Qed.\n\nLemma PCM_WF : WF_Matrix Parity_Check_Matrix.\nProof. unfold WF_Matrix. intros x y [H|H]; compute in H; mat_solve x y. Qed.\n\nLemma DCM_WF : WF_Matrix Decoder_Matrix.\nProof. unfold WF_Matrix. intros x y [H|H]; compute in H; mat_solve x y. Qed.\n\n(* Basic Binary definitions and operators (from Basics.v and Induction.v) *)\n\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  | B0 m' => B1 m'\n  | B1 m' => B0 (incr m')\n  end.\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\nFixpoint nat_to_bin (n:nat) : bin :=\n  match n with\n  | O      => Z\n  | S (n') => incr(nat_to_bin n')\n  end.\n\n(* digify inputs a binary number and nat and outputs an n bit binary number\n   truncates most significant bits or adds trailing zeroes *)\nFixpoint digify (b : bin) (n : nat) : bin :=\n  match n with\n  | O      => Z\n  | S (n') => match b with\n              | Z     => B0 (digify (B0 Z) n')\n              | B0 b' => B0 (digify b' n')\n              | B1 b' => B1 (digify b' n')\n              end\n  end.\n\nExample dig_test1 :\n  (digify Z 4) = B0 (B0 (B0 (B0 Z))).\nProof. reflexivity. Qed.\n\nExample dig_test2 :\n  (digify (B1 Z) 4) = B1 (B0 (B0 (B0 Z))).\nProof. reflexivity. Qed.\n\nExample dig_test3 :\n  (digify (B1 Z) 0) =  Z.\nProof. reflexivity. Qed.\n\nExample dig_test4 :\n  (digify (B0 (B1 (B0 (B1 Z)))) 3) =  B0 (B1 (B0 Z)).\nProof. reflexivity. Qed.\n\nExample dig_test5 :\n  (digify (B1 (B1 (B0 (B1 Z)))) 4) =  B1 (B1 (B0 (B1 Z))).\nProof. reflexivity. Qed.\n\n(* takes a binary number and outputs a nat list with its digits *)\nFixpoint bin_to_list (b : bin) : list(nat) :=\n  match b with\n  | Z     => []\n  | B0 b' => 0 :: (bin_to_list b')\n  | B1 b' => 1 :: (bin_to_list b')\n  end.\n\nExample btl_test1 :\n  bin_to_list (B0 (B1 Z)) = [0 ; 1].\nProof. reflexivity. Qed.\n\nExample btl_test2 :\n  bin_to_list Z = [].\nProof. reflexivity. Qed.\n\nExample btl_test3 :\n  bin_to_list (B1 (B1 (B0 (B1 Z)))) = [1 ; 1 ; 0 ; 1].\nProof. reflexivity. Qed.\n\n(* transforms a nat into a WS-digit binary word vector *)\nDefinition nat_to_word (n : nat) : Word :=\n  list2D_to_matrix [(bin_to_list (digify (nat_to_bin n) WS))].\n\n(* All WS-bit binary nats make well-formed words *)\nLemma nat_to_word_WF : forall n,\n  n < Max_Word -> WF_Word (nat_to_word n).\nProof. intros n Hn. compute in Hn. unfold WF_Word. split.\n  - unfold WF_Matrix. intros x y [H|H]; compute in H;\n    do 16 (try destruct n; mat_solve x y).\n  - intros x. left. mat_solve x y.\nQed.\n\nDefinition W1 : Word :=\n  fun x y => \n  match (x, y) with\n  | (0, 0) => 0\n  | (0, 1) => 1\n  | (0, 2) => 1\n  | (0, 3) => 0\n  | _ => 0\n  end.\n\nDefinition W1' : Word :=\n  nat_to_word 6.\n\nLemma ntw_test1 : W1 = W1'.\nProof.\n  unfold W1'. prep_matrix_equality. mat_solve x y.\nQed.\n\nDefinition W2 : Word :=\n  fun x y => \n  match (x, y) with\n  | (0, 0) => 1\n  | (0, 1) => 1\n  | (0, 2) => 1\n  | (0, 3) => 1\n  | _ => 0\n  end.\n \nDefinition W2' : Word :=\n  nat_to_word 15.\n\nLemma ntw_test2 : W2 = W2'.\nProof.\n  unfold W2'. prep_matrix_equality. mat_solve x y.\nQed.\n\n(* Generates a code from an input word *)\nDefinition word_to_code (W : Word) : Code :=\n  parity (Mmult W Code_Generator_Matrix).\n\n(* Codes generated from well-formed Words are well-formed\n   NOTE: This proof depends on an admitted proof in Matrix.v\n    This lemma turned out to be unneeded for formally proving the\n    Hamming(7,4) code, but because it was part of what I explored I\n    am leaving it in as an extra informally proven fact. *)\nLemma word_to_code_WF : forall W,\n  WF_Word W ->\n  WF_Code (word_to_code W).\nProof.\n  intros W [H1 H2]. unfold WF_Code. split.\n  - unfold word_to_code. apply WF_parity. apply WF_mult. apply H1. apply CGM_WF.\n  - intros y. unfold word_to_code. \n    assert (H: forall {m n} (A : Matrix m n), parity A m n = 0 \\/ parity A m n = 1).\n    { intros m n A. apply bin_parity. }\n    apply H with (n := y).\nQed. (* DoAP m2_01 *)\n\n(* combines above functions to form a code directly from an input nat n *)\nDefinition nat_to_code (n : nat) : Code :=\n  word_to_code (nat_to_word n).\n\nDefinition Code_0 : Code :=\n  list2D_to_matrix\n  ([[0;0;0;0;0;0;0]]).\n\nDefinition Code_0' : Code :=\n  nat_to_code 0.\n\nLemma ntc_test0 :\n  Code_0 = Code_0'.\nProof.\n  unfold Code_0'. prep_matrix_equality. mat_solve x y.\nQed.\n\nDefinition Code_12 : Code :=\n  list2D_to_matrix\n  ([[1;0;0;0;0;1;1]]).\n\nDefinition Code_12' : Code :=\n  nat_to_code 12.\n\nLemma ntc_test12 :\n  Code_12 = Code_12'.\nProof.\n  unfold Code_12'. prep_matrix_equality. mat_solve x y.\nQed.\n\n(* Generates a Syndrome vector from a given Code.\n   This will be used to error-check the Code.*)\nDefinition code_to_synd (C : Code) : Synd :=\n  parity (Mmult C Parity_Check_Matrix).\n(* Synds generated from well-formed Codes are well-formed\n   NOTE: Dependent on Admitted Proof. See word_to_code_WF above *)\nLemma code_to_synd_WF : forall C,\n  WF_Code C -> WF_Synd (code_to_synd C).\nProof.\n  intros C [H1 H2]. unfold WF_Synd. split.\n  - unfold code_to_synd. apply WF_parity. apply WF_mult. apply H1. apply PCM_WF.\n  - intros y.\n    assert (H: forall {m n} (A : Matrix m n), parity A m n = 0 \\/ parity A m n = 1).\n    { intros m n A. apply bin_parity. }\n    apply H with (n := y).\nQed. (* DoAP m2_01 *)\n\n(* converts Vector of length n to binary (requires an input bin Z to start) *)\nFixpoint vect_to_bin (n : nat) (V : Vector n) (b : bin) : bin :=\n  match n with\n  | O      => b\n  | S (n') => match (V 0 n') with\n              | 1 => (vect_to_bin n' V (B1 b))\n              | _ => (vect_to_bin n' V (B0 b))\n              end\n  end.\n\n(* Determines the erroneous bit if there is a one-bit error\n   + returns 0 if there are no errors\n   + returns n if the nth bit is erroneous (matrix index n-1) *)\nDefinition bit_err (S : Synd) : nat :=\n  bin_to_nat (vect_to_bin SS S Z).\n\nExample be0 : bit_err Zero = 0.\nProof. reflexivity. Qed.\n\nExample be5 : bit_err (list2D_to_matrix([[1;0;1]])) = 5.\nProof. reflexivity. Qed.\n\nExample be6 : bit_err (list2D_to_matrix([[0;1;1]])) = 6.\nProof. reflexivity. Qed.\n\n(* Flips the nth bit of input code C\n   + returns C unchanged if bit 0 is to be flipped\n   + returns C with nth bit (index n-1) flipped otherwise\n   NOTE: used to simulate errors AND correct them *)\nDefinition flip_bit_at_n (C : Code) (n : nat) :=\n  match n with\n  | O      => C\n  | S (n') =>\n    fun x y => if (y =? n') && (x =? 0) then if (C x y) =? 1 then 0 else 1\n      else if (C x y) =? 1 then 1 else 0\n  end.\n\nDefinition t_flip_0s_4 : Code :=\n  list2D_to_matrix\n  ([\n    [0;0;0;1;0;0;0]\n  ]).\n\nExample test_flip_null_4 :\n  t_flip_0s_4 = flip_bit_at_n Zero 4.\nProof. prep_matrix_equality. mat_solve x y. Qed.\n\nDefinition t_flip_1s : Code :=\n  list2D_to_matrix\n  ([\n    [1;1;1;1;1;1;1]\n  ]).\n\nDefinition t_flip_1s_6 : Code :=\n  list2D_to_matrix\n  ([\n    [1;1;1;1;1;0;1]\n  ]).\n\nExample test_flip_1s_6 :\n  t_flip_1s_6 = flip_bit_at_n t_flip_1s 6.\nProof. unfold t_flip_1s_6. simpl. prep_matrix_equality. mat_solve x y. Qed.\n\n(* flipping none of the bits yields the input code *)\nLemma flip_0_refl : forall C,\n  C = flip_bit_at_n C 0.\nProof. reflexivity. Qed.\n\n(* takes a code, corrects one-bit error by flipping the nth bit\n   + nth bit found by generating syndrome vector of C\n   + returns C unchanged if no error is detected *)\nDefinition bit_err_fix (C : Code) : Code :=\n  flip_bit_at_n C (bit_err (code_to_synd C)).\n\n(* decodes a word from a code *)\nDefinition code_to_word (C : Code) : Word :=\n  (Mmult C Decoder_Matrix).\n\nExample nat_code_word1 :\n  code_to_word (nat_to_code 1) = list2D_to_matrix ([[1;0;0;0]]).\nProof. prep_matrix_equality. mat_solve x y. Qed.\n\n(* Generating a code from a nat and decoding it to a word yields the\n   same code as the one generated directly from the nat *)\nLemma nat_code_word : forall n,\n  n < Max_Word ->\n  code_to_word (nat_to_code n) = nat_to_word n.\nProof.\n  intros n H. compute in H.\n  do 16 (destruct n; try prep_matrix_equality; mat_solve x y; try lia).\nQed.\n\n(* converts a word back to a nat *)\nDefinition word_to_nat (W : Word) : nat :=\n  bin_to_nat (vect_to_bin WS W Z).\n\n(* This Lemma shows that all 16 nats in our word size\n   can be encoded and decoded accurately *)\nLemma nat_code_nat : forall n,\n   n < Max_Word ->\n   word_to_nat (code_to_word (nat_to_code n)) = n.\nProof.\n   intros n H. compute in H. do 16 (destruct n; auto; try lia).\nQed.\n\n(* 1-bit errors in codes can be simulated by the flip_bit_at_n function.\n   A Code is 1-bit error safe (bit_err_safe) if the code can recover from\n   any one of its bits being flipped via bit_err_fix *)\nDefinition bit_err_safe (C : Code) : Prop :=\n  forall (i : nat),\n  i < 8 -> bit_err_fix (flip_bit_at_n C i) = C.\n\n(* tactic to check all possible one-bit errors for showing bit_err_safe holds *)\nLtac check_code_safe i x y :=\n  do 8 (destruct i; only 1: mat_solve x y; try lia).\n\n(* Example case showing the code generated from 0 is 1-bit error safe *)\nLemma code0_safe : bit_err_safe (nat_to_code 0).\nProof.\n  unfold bit_err_safe. intros i H. prep_matrix_equality.\n  check_code_safe i x y.\nQed.\n\n(*\n  -- Big Bad Proof --\n  The following proof takes about 75 seconds on my machine. It verifies,\n  for nat n < 16, that the code generated by nat_to_code n is 1-bit error\n  safe. bit_err_safe is the Prop that holds iff a code can be returned to\n  its original state via bit_err_fix for any 1-bit error. The proof shows\n  the Hamming(7,4) code holds for all cases in its scope. It can detect\n  and correct any 1-bit error on any 4-bit unsigned integer.\n*)\nLemma Hamming74_Formal_Proof : forall n,\n  n < 16 ->\n  bit_err_safe (nat_to_code n).\nProof.\n  unfold bit_err_safe. intros n Hn i Hi.\n  prep_matrix_equality.\n  do 16 (destruct n; only 1: check_code_safe i x y; try lia).\nQed.\n\n(*\n  Given the lemmas dependent on the admitted proof are NOT used in any\n  of the components of this last proof, it is safe to say that the\n  Hamming(7,4) code has hereby been formally proven in the coq proof assistant.\n\n  This was the primary goal of my project, and I am very glad to have been\n  able to show this. I attempted to design my functions in a way that would\n  scale to other Hamming codes. Were I to revisit this project I would continue\n  by proving the Hamming(7,4) can detect (but not correct) any 2 bit error with\n  an extra 8th parity bit, before examining differently sized Hamming codes.\n*)", "meta": {"author": "akriegel", "repo": "class-projects", "sha": "7e98f288c964f3b124d0a61b9c417f37becae8e9", "save_path": "github-repos/coq/akriegel-class-projects", "path": "github-repos/coq/akriegel-class-projects/class-projects-7e98f288c964f3b124d0a61b9c417f37becae8e9/Hamming(7,4)/Hamming.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.7615288191517582}}
{"text": "Set Implicit Arguments.\nRequire Import TLC.LibTactics.\nRequire Import TLC.LibInt.\nRequire Import ZArith.\nOpen Scope Z_scope.\nRequire Import Psatz.\n\n(************************************************************)\n(* A preorder on Z*Z *)\n\nDefinition ZZle : Z * Z -> Z * Z -> Prop :=\n  fun '(m,n) '(m', n') => m <= m' /\\ n <= n'.\n\n(************************************************************)\n(* * max *)\n\nHint Resolve Z.le_max_l : zarith.\nHint Resolve Z.le_max_r : zarith.\n\nLemma Zmax_ub_l : forall a b c,\n  c <= a ->\n  c <= Z.max a b.\nProof. intros. lia. Qed.\n\nLemma Zmax_ub_r : forall a b c,\n  c <= b ->\n  c <= Z.max a b.\nProof. intros. lia. Qed.\n\nHint Resolve Zmax_ub_l Zmax_ub_r : zarith.\n\nLemma Zmax_0_l :\n  forall x, 0 <= x -> Z.max 0 x = x.\nProof. intros. lia. Qed.\n\nLemma Zmax_0_r :\n  forall x, 0 <= x -> Z.max x 0 = x.\nProof. intros. lia. Qed.\n\n(************************************************************)\n(* * quotient *)\n\nLemma Zquot_mul_2 : forall x,\n  0 <= x ->\n  x - 1 <= 2 * (x ÷ 2) <= x.\nProof.\n  intros x Hx. rewrite <-Zquot2_quot. set (half := Z.quot2 x).\n  destruct (Zeven_odd_dec x) as [H|H].\n  - rewrite (Zeven_quot2 x); subst half; auto with zarith.\n  - rewrite (Zodd_quot2 x); subst half; auto with zarith.\nQed.\n\n(************************************************************)\n(* * Pow function *)\n\nLemma pow_ge_1 : forall k n,\n  0 < k ->\n  0 <= n ->\n  1 <= k ^ n.\nProof.\n  intros a b A B.\n  rewrite <-(Z.pow_0_r a).\n  apply Z.pow_le_mono_r; auto.\nQed.\n\nHint Resolve pow_ge_1 : zarith.\n\nLemma pow2_ge_1 : forall n,\n  0 <= n ->\n  1 <= 2 ^ n.\nProof using.\n  auto with zarith.\nQed.\n\nHint Resolve pow2_ge_1 : zarith.\n\nLemma pow_succ : forall k n,\n  0 < k ->\n  0 <= n ->\n  k ^ (n + 1) = k * k ^ n.\nProof using.\n  intros.\n  math_rewrite (n+1 = Z.succ n).\n  rewrite Z.pow_succ_r; auto.\nQed.\n\nLemma pow2_succ : forall n,\n  0 <= n ->\n  2 ^ (n+1) = 2 * 2^n.\nProof using.\n  intros.\n  rewrite pow_succ; auto with zarith.\nQed.\n\nLemma pow_succ_quot : forall k n,\n  0 < k ->\n  0 <= n ->\n  k ^ (n+1) ÷ k = k ^ n.\nProof using.\n  intros. rewrite pow_succ, Z.mul_comm, Z.quot_mul; auto with zarith.\nQed.\n\n(* A tactic that helps dealing with goals containing \"b^m\" for multiple m *)\nRequire Import TLC.LibList.\n\nLtac subst_eq_boxer_list l rewrite_tac :=\n  match l with\n  | nil => idtac\n  | (@boxer _ ?p) :: ?Hs =>\n    match p with\n      (?tm, ?Htm) =>\n      rewrite_tac Htm; clear Htm; clear tm;\n      subst_eq_boxer_list Hs rewrite_tac\n    end\n  end.\n\n(* Develop occurences of (b ^ m) in H into (b ^ (m - min_e) * b ^ min_e).\n   (and try to simplify/compute b^(m - min_e)).\n *)\nLtac rew_pow_develop b m min_e H :=\n  let m_eq_plusminus := fresh in\n  assert (m = min_e + (m - min_e)) as m_eq_plusminus\n      by (rewrite Zplus_minus; reflexivity);\n  rewrite m_eq_plusminus in H; clear m_eq_plusminus;\n  rewrite (Z.pow_add_r b min_e (m - min_e)) in H; [\n    rewrite Z.mul_comm in H;\n    let tm' := fresh \"tm'\" in\n    let H' := fresh \"H'\" in\n    remember (b ^ (m - min_e)) as tm' eqn:H' in H;\n    let e := fresh \"e\" in\n    evar (e: int);\n    let Heqe := fresh in\n    assert (e = m - min_e) as Heqe\n        by (ring_simplify; subst e; reflexivity);\n    rewrite <-Heqe in H'; clear Heqe; unfold e in H'; ring_simplify in H';\n    rewrite H' in H; clear H'; clear tm'; clear e;\n    try rewrite Z.mul_1_l in H\n  | ring_simplify; auto with zarith ..].\n\nLtac rew_pow_aux_goal b min_e normalized_acc :=\n  match goal with\n  | |- context [ b ^ ?m ] =>\n    let tm := fresh \"tm\" in\n    let Heqtm := fresh \"Heqtm\" in\n    remember (b ^ m) as tm eqn:Heqtm in |- *;\n    rew_pow_develop b m min_e Heqtm; [\n      rew_pow_aux_goal b min_e ((boxer (tm, Heqtm)) :: normalized_acc)\n    | ..]\n  | _ => subst_eq_boxer_list normalized_acc ltac:(fun E => rewrite E)\n  end.\n\nLtac rew_pow_aux_in b min_e H normalized_acc :=\n  match type of H with\n  | context [ b ^ ?m ] =>\n    let tm := fresh \"tm\" in\n    let Heqtm := fresh \"Heqtm\" in\n    remember (b ^ m) as tm eqn:Heqtm in H;\n    rew_pow_develop b m min_e Heqtm; [\n      rew_pow_aux_in b min_e H ((boxer (tm, Heqtm)) :: normalized_acc)\n    | ..]\n  | _ => subst_eq_boxer_list normalized_acc ltac:(fun E => rewrite E in H)\n  end.\n\nTactic Notation \"rew_pow\" constr(b) constr(min_e) :=\n  rew_pow_aux_goal b min_e (@nil Boxer).\nTactic Notation \"rew_pow\" \"~\" constr(b) constr(min_e) :=\n  rew_pow_aux_goal b min_e (@nil Boxer); auto_tilde.\nTactic Notation \"rew_pow\" \"*\" constr(b) constr(min_e) :=\n  rew_pow_aux_goal b min_e (@nil Boxer); auto_star.\nTactic Notation \"rew_pow\" constr(b) constr(min_e) \"in\" hyp(H) :=\n  rew_pow_aux_in b min_e H (@nil Boxer).\nTactic Notation \"rew_pow\" \"~\" constr(b) constr(min_e) \"in\" hyp(H) :=\n  rew_pow_aux_in b min_e H (@nil Boxer); auto_tilde.\nTactic Notation \"rew_pow\" \"*\" constr(b) constr(min_e) \"in\" hyp(H) :=\n  rew_pow_aux_in b min_e H (@nil Boxer); auto_star.\n\n(* Test *)\nAxiom P : int -> Prop.\nGoal forall n, P (1 + 2 ^ (n + 3) + 2 ^ n + 2 ^ (n+1)).\nProof.\n  intros.\n  skip_asserts H: (3 = 2 ^ (n+3)). rew_pow 2 n in H.\n  rew_pow 2 n.\nAdmitted.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Base 2 logarithm. *)\n\nLemma Zlog2_step : forall x,\n  2 <= x ->\n  1 + Z.log2 (x÷2) = Z.log2 x.\nProof.\n  admit. (* TODO: prove from the log2_step in LibNatExtra? *)\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/LibZExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7613891247251803}}
{"text": "Require Import List Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nPrint unit.\nPrint True.\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  Print False.\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  Print prod.\n\n  Theorem and_comm : P /\\ Q -> Q /\\ P.\n    destruct 1.\n    split; assumption.\n  Qed.\n\n  Print or.\n  Print sum.\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\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\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  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\nInductive even : nat -> Prop :=\n| EvenO : even O\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  repeat constructor.\nQed.\n\nHint Constructors even.\n\nTheorem even_4' : even 4.\n  auto.\nQed.\n\nTheorem even_plus : forall n m, even n -> even m -> even (n + m).\n  induction n; crush.\n  inversion H. simpl.\n  constructor.\n  Restart.\n  induction 1. crush.\n  intros. simpl. constructor. crush.\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;\n    crush.\nQed.\n\nTheorem even_contra : forall n, even (S (n + n)) -> False.\n  intros; eapply even_contra'; eauto.\nQed.", "meta": {"author": "mattjquinn", "repo": "distsyscoq", "sha": "815906ff12881c26010dd8312a3bcb94fc45fe9a", "save_path": "github-repos/coq/mattjquinn-distsyscoq", "path": "github-repos/coq/mattjquinn-distsyscoq/distsyscoq-815906ff12881c26010dd8312a3bcb94fc45fe9a/cpdt/src/MQuinnPredicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7613452633829418}}
{"text": "Require Import Lia.\nRequire Import Nat.\nRequire Import Wellfounded.\n\nFrom Cyclic_PA.Casteran Require Import rpo.\nFrom Cyclic_PA.Maths Require Import naturals.\nFrom Cyclic_PA.Logic Require Import definitions.\n\nInductive ord : Set :=\n| Zero : ord\n| wcon : ord -> nat -> ord -> ord.\n\nDeclare Scope cantor_scope.\n\nInductive ord_lt : ord -> ord -> Prop :=\n|  zero_lt : forall a n b, Zero < wcon a n b\n|  head_lt :\n    forall a a' n n' b b', a < a' ->\n                           wcon a n b < wcon a' n' b'\n|  coeff_lt : forall a n n' b b', (n < n')%nat ->\n                                 wcon a n b < wcon a n' b'\n|  tail_lt : forall a n b b', b < b' ->\n                             wcon a n b < wcon a n b'\nwhere \"o < o'\" := (ord_lt o o') : cantor_scope.\n\nOpen Scope cantor_scope.\n\nDefinition leq (alpha beta : ord) := alpha = beta \\/ alpha < beta.\nNotation \"alpha <= beta\" := (leq alpha beta) : cantor_scope.\n\nLemma ord_semiconnex :\n    forall (alpha beta : ord),\n        alpha < beta \\/ beta < alpha \\/ alpha = beta.\nProof.\ninduction alpha.\n- induction beta.\n  + right.\n    right.\n    reflexivity.\n  + left.\n    apply zero_lt.\n- destruct beta.\n  + right.\n    left.\n    apply zero_lt.\n  + destruct (IHalpha1 beta1) as [LT | [GT | EQ]].\n    * left.\n      apply head_lt.\n      apply LT.\n    * right.\n      left.\n      apply head_lt.\n      apply GT.\n    * destruct EQ.\n      destruct (nat_semiconnex n n0) as [LT | [GT | EQ]].\n      --  left.\n          apply coeff_lt.\n          apply LT.\n      --  right.\n          left.\n          apply coeff_lt.\n          apply GT.\n      --  destruct EQ.\n          destruct (IHalpha2 beta2) as [LT | [GT | EQ]].\n          ++  left.\n              apply tail_lt.\n              apply LT.\n          ++  right.\n              left.\n              apply tail_lt.\n              apply GT.\n          ++  destruct EQ.\n              right.\n              right.\n              reflexivity.\nQed.\n\nLemma wcon_lt_aux :\n    forall (a a' b b' : ord) (n n' : nat),\n        wcon a n b < wcon a' n' b' ->\n            (a < a' \\/ (a = a' /\\ lt n n') \\/ (a = a' /\\ n = n' /\\ b < b')).\nProof.\nintros a a' b b' n n' LT.\ninversion LT.\n- left.\n  apply H0.\n- right.\n  left.\n  split.\n  + reflexivity.\n  + apply H0.\n- right.\n  right.\n  repeat split.\n  apply H0.\nQed.\n\nLemma ord_lt_trans :\n    forall (alpha beta gamma : ord),\n        alpha < beta ->\n            beta < gamma ->\n                alpha < gamma.\nProof.\ninduction alpha as [| a1 IHa1 an a2 IHa2];\nintros beta gamma LTAB LTBG;\ndestruct gamma as [| g1 gn g2].\n1,3 : inversion LTBG.\n1 : apply zero_lt.\n1 : destruct beta as [| b1 bn b2].\n- inversion LTAB.\n- destruct (wcon_lt_aux _ _ _ _ _ _ LTAB) as [LT | [[EQO LT] | [EQO [EQN LT]]]];\n  destruct (wcon_lt_aux _ _ _ _ _ _ LTBG) as [LT' | [[EQO' LT'] | [EQO' [EQN' LT']]]];\n  try destruct EQO; try destruct EQO'; try destruct EQN; try destruct EQN'.\n  + apply head_lt.\n    apply (IHa1 _ _ LT LT').\n  + apply head_lt.\n    apply LT.\n  + apply head_lt.\n    apply LT.\n  + apply head_lt.\n    apply LT'.\n  + apply coeff_lt.\n    apply (nat_lt_trans _ _ _ LT LT').\n  + apply coeff_lt.\n    apply LT.\n  + apply head_lt.\n    apply LT'.\n  + apply coeff_lt.\n    apply LT'.\n  + apply tail_lt.\n    apply (IHa2 _ _ LT LT').\nQed.\n\nLemma ord_lt_irrefl :\n    forall (alpha : ord),\n        ~ (alpha < alpha).\nProof.\nintros alpha Fal.\ninduction alpha as [ | a1 IHa1 n a2 IHa2].\n- inversion Fal.\n- destruct (wcon_lt_aux _ _ _ _ _ _ Fal) as [LT | [[EQO LT] | [EQO [EQN LT]]]].\n  + apply (IHa1 LT).\n  + lia.\n  + apply (IHa2 LT).\nQed.\n\nLemma ord_lt_asymm :\n    forall (alpha beta : ord),\n        alpha < beta ->\n            ~(beta < alpha).\nProof.\nintros alpha beta LT GT.\napply (ord_lt_irrefl _ (ord_lt_trans alpha beta alpha LT GT)).\nQed.\n\n\n(* Here we define Cantor Normal Form, or more accurately, we copy\nPierre Casteran's definition *)\n(* *)\nInductive nf : ord -> Prop :=\n| zero_nf : nf Zero\n| single_nf : forall a n,\n                  nf a ->\n                      nf (wcon a n Zero)\n| wcon_nf : forall a n a' n' b,\n                a' < a ->\n                    nf a ->\n                        nf (wcon a' n' b) ->\n                            nf (wcon a n (wcon a' n' b)).\n\nDefinition nat_ord (n : nat) : ord :=\n  match n with\n  | O => Zero\n  | S n' => wcon Zero n' Zero\n  end.\n\nLemma nf_nat :\n    forall (n : nat),\n        nf (nat_ord n).\nProof.\ninduction n.\n- apply zero_nf.\n- apply single_nf.\n  apply zero_nf.\nQed.\n\nFixpoint ord_eqb (alpha beta : ord) : bool :=\nmatch alpha, beta with\n| Zero, Zero => true\n| _, Zero => false\n| Zero, _ => false\n| wcon a n b, wcon a' n' b' =>\n    (match ord_eqb a a' with\n    | false => false\n    | true =>\n        (match nat_eqb n n' with\n        | false => false\n        | true => ord_eqb b b'\n        end)\n    end)\nend.\n\nFixpoint ord_ltb (alpha beta : ord) : bool :=\nmatch alpha, beta with\n| _, Zero => false\n| Zero, _ => true\n| wcon a n b, wcon a' n' b' =>\n    (match ord_ltb a a', ord_eqb a a' with\n    | true, _ => true\n    | _, false => false\n    | _, true =>\n        (match ltb n n', ltb n' n with\n        | true, _ => true\n        | _, true => false\n        | _, _ => ord_ltb b b'\n        end)\n    end)\nend.\n\nLemma ord_lt_one :\n    forall alpha,\n        ord_lt alpha (nat_ord 1) ->\n            Zero = alpha.\nProof.\nintros alpha LT.\ninduction alpha.\n- reflexivity.\n- inversion LT;\n  inversion H0.\nQed.\n\nLemma nf_hered_third :\n    forall (a b : ord) (n : nat),\n        nf (wcon a n b) ->\n            nf b.\nProof.\nintros a b n N.\ninversion N.\n- apply zero_nf.\n- apply H4.\nQed.\n\nLemma nf_hered_first :\n    forall (a b : ord) (n : nat),\n        nf (wcon a n b) ->\n            nf a.\nProof.\nintros a b n N.\ninversion N.\n- apply H0.\n- apply H3.\nQed.\n\nLemma nf_head_zero :\n    forall (alpha : ord) (n : nat),\n        nf (wcon Zero n alpha) ->\n            Zero = alpha.\nProof.\nintros alpha n NA.\ninversion NA.\nreflexivity.\ninversion H2.\nQed.\n\nLemma ord_eqb_refl :\n    forall (alpha : ord),\n        ord_eqb alpha alpha = true.\nProof.\ninduction alpha.\n- reflexivity.\n- unfold ord_eqb; fold ord_eqb.\n  rewrite IHalpha1.\n  rewrite nat_eqb_refl.\n  rewrite IHalpha2.\n  reflexivity.\nQed.\n\nLemma ord_ltb_irrefl :\n    forall (alpha : ord),\n        ord_ltb alpha alpha = false.\nProof.\ninduction alpha.\n- reflexivity.\n- unfold ord_ltb; fold ord_ltb.\n  rewrite IHalpha1.\n  rewrite ord_eqb_refl.\n  rewrite nat_ltb_irrefl.\n  apply IHalpha2.\nQed.\n\nLemma ord_lt_ltb :\n    forall (alpha beta : ord),\n        alpha < beta ->\n            ord_ltb alpha beta = true.\nProof.\ninduction alpha;\nintros beta LT;\ndestruct beta.\n- inversion LT.\n- reflexivity.\n- inversion LT.\n- apply wcon_lt_aux in LT.\n  destruct LT as [LT | [[EQO LT] | [EQO [EQN LT]]]];\n  unfold ord_ltb; fold ord_ltb.\n  + rewrite IHalpha1.\n    reflexivity.\n    apply LT.\n  + destruct EQO.\n    rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    rewrite (nat_lt_ltb _ _ LT).\n    reflexivity.\n  + destruct EQO,EQN.\n    rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    rewrite nat_ltb_irrefl.\n    apply IHalpha2.\n    apply LT.\nQed.\n\nLemma ord_eqb_eq :\n    forall (alpha beta : ord),\n        ord_eqb alpha beta = true -> alpha = beta.\nProof.\ninduction alpha;\nintros beta EQ;\ndestruct beta.\n- reflexivity.\n- inversion EQ.\n- inversion EQ.\n- unfold ord_eqb in EQ; fold ord_eqb in EQ.\n  case (ord_eqb alpha1 beta1) eqn:EQ1;\n  case (nat_eqb n n0) eqn:EQn;\n  case (ord_eqb alpha2 beta2) eqn:EQ2;\n  try inversion EQ.\n  rewrite (IHalpha1 _ EQ1).\n  rewrite (IHalpha2 _ EQ2).\n  apply nat_eqb_eq in EQn.\n  destruct EQn.\n  reflexivity.\nQed.\n\nLemma ord_semiconnex_bool :\n    forall (alpha beta : ord),\n      ord_ltb alpha beta = true \\/ ord_ltb beta alpha = true \\/ ord_eqb alpha beta = true.\nProof.\nintros alpha beta.\ndestruct (ord_semiconnex alpha beta) as [LT | [GT | EQ]].\n- left.\n  apply ord_lt_ltb.\n  apply LT.\n- right.\n  left.\n  apply ord_lt_ltb.\n  apply GT.\n- right.\n  right.\n  destruct EQ.\n  apply ord_eqb_refl.\nQed.\n\nLemma wcon_ltb_aux :\n    forall (a a' b b' : ord) (n n' : nat),\n        ord_ltb (wcon a n b) (wcon a' n' b') = true ->\n              (ord_ltb a a' = true \\/\n                  (ord_eqb a a' = true /\\ ltb n n' = true) \\/\n                      (ord_eqb a a' = true /\\ n = n' /\\ ord_ltb b b' = true)).\nProof.\nintros a a' b b' n n' LT.\ncase (ord_ltb a a') eqn:LT1. \n- left.\n  reflexivity.\n- unfold ord_ltb in LT; fold ord_ltb in LT.\n  right.\n  rewrite LT1 in LT.\n  case (ord_eqb a a') eqn:EQ1.\n  + apply ord_eqb_eq in EQ1.\n    destruct EQ1.\n    destruct (nat_semiconnex_bool n n') as [LTn | [LTn | EQn]].\n    * left.\n      repeat split.\n      apply LTn.\n    * rewrite LTn in LT.\n      rewrite (nat_ltb_asymm _ _ LTn) in LT.\n      inversion LT.\n    * right.\n      apply nat_eqb_eq in EQn.\n      destruct EQn.\n      rewrite nat_ltb_irrefl in LT.\n      repeat split.\n      apply LT.\n  + inversion LT.\nQed.\n\nLemma ord_ltb_trans :\n    forall (alpha beta gamma : ord),\n        ord_ltb alpha beta = true ->\n            ord_ltb beta gamma = true ->\n                ord_ltb alpha gamma = true.\nProof.\ninduction alpha;\nintros beta gamma LTAB LTBG;\ndestruct gamma;\ndestruct beta.\n1,2,5,6 : inversion LTBG.\n1,3 : inversion LTAB.\n\n- reflexivity.\n- destruct (wcon_ltb_aux _ _ _ _ _ _ LTAB) as [LT | [[EQO LT] | [EQO [EQN LT]]]];\n  destruct (wcon_ltb_aux _ _ _ _ _ _ LTBG) as [LT' | [[EQO' LT'] | [EQO' [EQN' LT']]]];\n  try apply ord_eqb_eq in EQO; try apply ord_eqb_eq in EQO';\n  try apply nat_eqb_eq in EQN; try apply nat_eqb_eq in EQN';\n  try destruct EQO; try destruct EQO'; try destruct EQN; try destruct EQN';\n  unfold ord_ltb; fold ord_ltb;\n  try rewrite ord_ltb_irrefl;\n  try rewrite ord_eqb_refl;\n  try rewrite LT;\n  try rewrite LT';\n  try reflexivity.  \n  + rewrite (IHalpha1 _ _ LT LT').\n    reflexivity.\n  + rewrite (nat_ltb_trans _ _ _ LT LT').\n    reflexivity.\n  + rewrite nat_ltb_irrefl.\n    apply (IHalpha2 _ _ LT LT').\nQed.\n\nLemma ord_ltb_asymm :\n    forall (alpha beta : ord),\n        ord_ltb alpha beta = true ->\n            ord_ltb beta alpha = false.\nProof.\nintros alpha beta LT.\ncase (ord_ltb beta alpha) eqn:IE.\n- pose proof (ord_ltb_trans alpha beta alpha LT IE) as Fal.\n  rewrite (ord_ltb_irrefl alpha) in Fal.\n  inversion Fal.\n- reflexivity.\nQed.\n\nLemma ord_ltb_lt :\n    forall (alpha beta : ord),\n        ord_ltb alpha beta = true ->\n            alpha < beta.\nProof.\nintros alpha beta LTB.\ndestruct (ord_semiconnex alpha beta) as [LT | [GT | EQ]].\n- apply LT.\n- apply ord_lt_ltb in GT.\n  apply ord_ltb_asymm in GT.\n  rewrite GT in LTB.\n  inversion LTB.\n- destruct EQ.\n  rewrite ord_ltb_irrefl in LTB.\n  inversion LTB.\nQed.\n\nLemma ord_eqb_symm :\n    forall (alpha beta : ord),\n        ord_eqb alpha beta = ord_eqb beta alpha.\nProof.\nintros alpha beta.\ncase (ord_eqb beta alpha) eqn:EQ.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  apply ord_eqb_refl.\n- case (ord_eqb alpha beta) eqn:NEQ.\n  + apply ord_eqb_eq in NEQ.\n    destruct NEQ.\n    rewrite ord_eqb_refl in EQ.\n    inversion EQ.\n  + reflexivity.\nQed.\n\nLemma ord_ltb_neb :\n    forall (alpha beta: ord),\n        ord_ltb alpha beta = true ->\n            ord_eqb beta alpha = false.\nProof.\nintros alpha beta LT.\ncase (ord_eqb beta alpha) eqn:EQ.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  rewrite ord_ltb_irrefl in LT.\n  inversion LT.\n- reflexivity.\nQed.\n\nLemma ord_lt_self :\n    forall (alpha beta : ord) (n : nat),\n        alpha < wcon alpha n beta.\nProof.\ninduction alpha.\n- intros. apply zero_lt.\n- intros. apply head_lt. apply IHalpha1.\nQed.\n\nFixpoint ord_add (alpha beta : ord) : ord :=\nmatch alpha, beta with\n| _, Zero => alpha\n| Zero, _ => beta\n| wcon a n b, wcon a' n' b' =>\n    (match ord_ltb a a' with\n    | true => beta\n    | false =>\n      (match ord_eqb a a' with\n      | true => wcon a' (n + n' + 1) b'\n      | false => wcon a n (ord_add b beta)\n      end)\n    end)\nend.\n\nFixpoint ord_mult (alpha beta : ord) : ord :=\nmatch alpha, beta with\n| _, Zero => Zero\n| Zero, _ => Zero\n| wcon a n b, wcon Zero n' b' => wcon a ((S n) * (S n') - 1) b\n| wcon a n b, wcon a' n' b' => wcon (ord_add a a') n' (ord_mult alpha b')\nend.\n\nFixpoint ord_2_exp (alpha : ord) : ord :=\nmatch alpha with\n| Zero => wcon Zero 0 Zero\n| wcon Zero n' _ => nat_ord (2 ^ (S n'))\n| wcon (wcon Zero 0 _) n b =>\n    ord_mult (wcon (wcon Zero n Zero) 0 Zero) (ord_2_exp b)\n| wcon (wcon Zero (S n) _) m b =>\n    ord_mult (wcon (wcon (wcon Zero n Zero) m Zero) 0 Zero) (ord_2_exp b)\n| wcon (wcon a n b) n' b' =>\n    ord_mult (wcon (wcon (wcon a n b) n' Zero) 0 Zero) (ord_2_exp b')\nend.\n\nLemma ord_add_zero :\n    forall (alpha : ord),\n        ord_add alpha Zero = alpha.\nProof. destruct alpha; reflexivity. Qed.\n\nLemma ord_zero_add : \n    forall (alpha : ord),\n        ord_add Zero alpha = alpha.\nProof. destruct alpha; reflexivity. Qed.\n\nLemma ord_add_nat :\n    forall (n m : nat),\n        nat_ord (n + m) = ord_add (nat_ord n) (nat_ord m).\nProof.\nintros n m.\ninduction m as [| m' IH].\n- rewrite ord_add_zero.\n  rewrite <- plus_n_O.\n  reflexivity.\n- induction n as [| n' IHn].\n  + reflexivity.\n  + rewrite <- plus_n_Sm.\n    unfold nat_ord, ord_add, add.\n    fold add.\n    rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    rewrite <- plus_assoc.\n    rewrite <- plus_n_Sm.\n    rewrite <- plus_n_O.\n    rewrite plus_n_Sm.\n    reflexivity.\nQed.\n\nFixpoint ord_succ (alpha : ord) : ord :=\nmatch alpha with\n| Zero => nat_ord 1\n| wcon Zero n b => wcon Zero (S n) b\n| wcon a n b => wcon a n (ord_succ b)\nend.\n\nLemma ord_succ_neb_zero :\n    forall alpha,\n        ord_eqb (ord_succ alpha) Zero = false.\nProof.\ninduction alpha.\n- reflexivity.\n- destruct alpha1;\n  reflexivity.\nQed.\n\nLemma ord_succ_one :\n    forall alpha,\n        wcon Zero 0 Zero = ord_succ alpha ->\n            Zero = alpha.\nProof.\nintros alpha EQ.\ndestruct alpha.\n- reflexivity.\n- unfold ord_succ in EQ.\n  fold ord_succ in EQ.\n  destruct alpha1;\n  inversion EQ.\nQed.\n\nLemma ord_succ_monot :\n    forall (alpha : ord),\n        ord_lt alpha (ord_succ alpha).\nProof.\ninduction alpha.\n- apply zero_lt.\n- destruct alpha1.\n  + apply coeff_lt.\n    unfold lt.\n    reflexivity.\n  + apply tail_lt.\n    apply IHalpha2.\nQed.\n\nLemma ord_succ_nat :\n    forall (n : nat),\n        ord_succ (nat_ord n) = nat_ord (S n).\nProof. destruct n; reflexivity. Qed.\n\nFixpoint is_succ (alpha : ord) : bool :=\nmatch alpha with\n| Zero => false\n| wcon a n b => match b with\n    | Zero => match a with\n        | Zero => true\n        | _ => false\n        end\n    | _ => is_succ b\n    end\nend.\n\nLemma ord_succ_is_succ :\n    forall alpha,\n        nf alpha ->\n            is_succ (ord_succ alpha) = true.\nProof.\nintros alpha NA.\ninduction alpha.\n- reflexivity.\n- destruct alpha1.\n  + destruct (nf_head_zero _ _ NA).\n    reflexivity.\n  + unfold ord_succ, is_succ; fold ord_succ is_succ.\n    destruct (ord_succ alpha2);\n    apply (IHalpha2 (nf_hered_third _ _ _ NA)).\nQed.\n\nFixpoint ord_pred (alpha : ord) : ord :=\nmatch alpha with\n| Zero => Zero\n| wcon a n b => match b with\n    | Zero => match a with\n        | Zero => match n with\n            | 0 => Zero\n            | S p => wcon Zero p Zero\n            end\n        | _ => wcon a n b\n        end\n    | _ => wcon a n (ord_pred b)\n    end\nend.\n\nLemma ord_succ_pred_if_succ :\n    forall alpha,\n        nf alpha ->\n            is_succ alpha = true ->\n                ord_succ (ord_pred alpha) = alpha.\nProof.\nintros alpha NA SA.\ninduction alpha;\nunfold ord_pred, ord_succ; fold ord_pred ord_succ.\n- inversion SA.\n- destruct alpha1.\n  + destruct (nf_head_zero _ _ NA).\n    destruct n;\n    reflexivity.\n  + destruct alpha2.\n    * inversion SA.\n    * rewrite <- (IHalpha2 (nf_hered_third _ _ _ NA) SA) at 2.\n      reflexivity.\nQed.\n\nLemma ord_mult_omega_not_succ :\n    forall alpha,\n        nf alpha ->\n            is_succ (ord_mult (wcon (wcon Zero 0 Zero) 0 Zero) alpha) = false.\nProof.\nintros alpha NA.\ninduction alpha.\n- reflexivity.\n- unfold ord_mult. fold ord_mult.\n  destruct alpha1.\n  + reflexivity.\n  + unfold is_succ; fold is_succ.\n    rewrite (IHalpha2 (nf_hered_third _ _ _ NA)).\n    destruct (ord_mult (wcon (wcon Zero 0 Zero) 0 Zero) alpha2);\n    destruct alpha1_1;\n    reflexivity.\nQed.\n\nLemma ord_lt_succ :\n    forall alpha beta,\n        ord_lt alpha beta ->\n            ord_lt (ord_succ alpha) (ord_succ beta).\nProof.\ninduction alpha as [| a1 IHa1 an a2 IHa2];\nintros beta LT;\ndestruct beta as [| b1 bn b2].\n1,3 : inversion LT.\n- destruct b1.\n  + apply coeff_lt.\n    lia.\n  + apply (head_lt _ _ _ _ _ _ (zero_lt _ _ _)).\n- destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]].\n  + destruct b1.\n    * inversion LT'.\n    * destruct a1.\n      --  apply (head_lt _ _ _ _ _ _ (zero_lt _ _ _)).\n      --  apply (head_lt _ _ _ _ _ _ LT').\n  + destruct EQO.\n    destruct a1.\n    * apply (coeff_lt _ _ _ _ _ (le_n_S _ _ LT')).\n    * apply (coeff_lt _ _ _ _ _ LT').\n  + destruct EQO,EQN.\n    destruct a1.\n    * apply (tail_lt _ _ _ _ LT').\n    * apply (tail_lt _ _ _ _ (IHa2 _ LT')).\nQed.\n\nLemma ord_succ_lt :\n    forall alpha beta,\n        ord_lt (ord_succ alpha) (ord_succ beta) ->\n            ord_lt alpha beta.\nProof.\ninduction alpha as [| a1 IHa1 an a2 IHa2];\nintros beta LT;\ndestruct beta as [| b1 bn b2].\n- destruct (ord_lt_irrefl _ LT).\n- apply zero_lt.\n- destruct a1;\n  unfold ord_succ, nat_ord in LT;\n  destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\n  inversion LT'.\n- destruct b1;\n  destruct a1.\n  3 : apply head_lt;\n      apply zero_lt.\n  all : destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]].\n  + inversion LT'.\n  + apply coeff_lt.\n    apply le_S_n.\n    apply LT'.\n  + apply eq_add_S in EQN.\n    destruct EQN.\n    apply tail_lt.\n    apply LT'.\n  + inversion LT'.\n  + inversion EQO.\n  + inversion EQO.\n  + apply head_lt.\n    apply LT'.\n  + destruct EQO.\n    apply coeff_lt.\n    apply LT'.\n  + destruct EQO,EQN.\n    apply tail_lt.\n    apply IHa2.\n    apply LT'.\nQed.\n\nLemma ord_geb_trans :\n    forall alpha beta gamma,\n        ord_ltb alpha beta = false ->\n            ord_ltb beta gamma = false ->\n                ord_ltb alpha gamma = false.\nProof.\nintros alpha beta gamma GEAB GEBG.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite LT in GEAB.\n  inversion GEAB.\n- destruct (ord_semiconnex_bool beta gamma) as [LT' | [GT' | EQ']].\n  + rewrite LT' in GEBG.\n    inversion GEBG.\n  + apply (ord_ltb_asymm _ _ (ord_ltb_trans _ _ _ GT' GT)).\n  + apply ord_eqb_eq in EQ'.\n    destruct EQ'.\n    apply GEAB.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  apply GEBG.\nQed.\n\nLemma ord_geb_succ :\n    forall alpha beta,\n        ord_ltb alpha beta = false ->\n            ord_ltb (ord_succ alpha) (ord_succ beta) = false.\nProof.\nintros alpha beta GE.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite LT in GE.\n  inversion GE.\n- apply ord_ltb_asymm.\n  apply (ord_lt_ltb _ _ (ord_lt_succ _ _ (ord_ltb_lt _ _ GT))).\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  apply ord_ltb_irrefl.\nQed.\n\nDefinition ord_max (alpha beta : ord) : ord :=\nmatch ord_ltb alpha beta with\n| true => beta\n| false => alpha\nend.\n\nLemma ord_max_ltb_is_r :\n    forall (alpha beta : ord),\n        ord_ltb alpha beta = true ->\n            ord_max alpha beta = beta.\nProof.\nintros alpha beta LT.\nunfold ord_max.\nrewrite LT.\nreflexivity.\nQed.\n\nLemma ord_max_ltb_not_l :\n    forall (alpha beta : ord),\n        ord_ltb alpha beta = false ->\n            ord_max alpha beta = alpha.\nProof.\nintros alpha beta LT.\nunfold ord_max.\nrewrite LT.\nreflexivity.\nQed.\n\nLemma ord_max_symm :\n    forall (alpha beta : ord),\n        ord_max alpha beta = ord_max beta alpha.\nProof.\nintros alpha beta.\nunfold ord_max.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite LT.\n  rewrite (ord_ltb_asymm _ _ LT).\n  reflexivity.\n- rewrite GT.\n  rewrite (ord_ltb_asymm _ _ GT).\n  reflexivity.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  reflexivity.\nQed.\n\nLemma ord_max_succ_succ :\n    forall alpha beta,\n        ord_max (ord_succ alpha) (ord_succ beta) = ord_succ (ord_max alpha beta).\nProof.\nintros alpha beta.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]];\nunfold ord_max.\n- rewrite LT.\n  rewrite (ord_lt_ltb _ _  (ord_lt_succ _ _ (ord_ltb_lt _ _ LT))).\n  reflexivity.\n- rewrite (ord_ltb_asymm _ _ GT).\n  rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _  (ord_lt_succ _ _ (ord_ltb_lt _ _ GT)))).\n  reflexivity.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  repeat rewrite ord_ltb_irrefl.\n  reflexivity.\nQed.\n\nLemma ord_max_self :\n    forall (alpha : ord),\n        alpha = ord_max alpha alpha.\nProof.\nintros alpha.\nunfold ord_max.\nrewrite ord_ltb_irrefl.\nreflexivity.\nQed.\n\nLemma ord_max_nat :\n    forall n m,\n        ord_max (nat_ord n) (nat_ord m) = nat_ord (max n m).\nProof.\ninduction n;\ndestruct m;\ntry reflexivity.\n- unfold max. fold max.\n  repeat rewrite <- ord_succ_nat.\n  rewrite ord_max_succ_succ.\n  rewrite IHn.\n  reflexivity. \nQed.\n\nLemma ord_lt_max_succ_l :\n    forall (alpha beta : ord),\n        ord_lt alpha (ord_succ (ord_max alpha beta)).\nProof.\nintros alpha beta.\nunfold ord_max.\ncase (ord_ltb alpha beta) eqn:LT.\n- apply (ord_lt_trans _ _ _ (ord_ltb_lt _ _ LT) (ord_succ_monot _)).\n- apply ord_succ_monot.\nQed.\n\nLemma ord_lt_max_succ_r :\n    forall (alpha beta : ord),\n        ord_lt beta (ord_succ (ord_max alpha beta)).\nProof.\nintros alpha beta.\nrewrite ord_max_symm.\napply ord_lt_max_succ_l.\nQed.\n\nLemma ord_max_geb_l :\n    forall (alpha beta : ord),\n        ord_ltb (ord_max alpha beta) alpha = false.\nProof.\nintros alpha beta.\nunfold ord_max in *.\ndestruct (ord_ltb alpha beta) eqn:LT.\n- apply (ord_ltb_asymm _ _ LT).\n- apply ord_ltb_irrefl.\nQed.\n\nLemma ord_max_geb_r :\n    forall (alpha beta : ord),\n        ord_ltb (ord_max alpha beta) beta = false.\nProof.\nintros alpha beta.\nrewrite ord_max_symm.\napply ord_max_geb_l.\nQed.\n\nLemma ord_max_zero :\n    forall (alpha beta : ord),\n        Zero = ord_max alpha beta ->\n            Zero = alpha /\\ Zero = beta.\nProof.\nintros alpha beta EQ.\nunfold ord_max in EQ.\ncase (ord_ltb alpha beta) eqn:LT.\n- destruct EQ.\n  destruct alpha.\n  + split;\n    reflexivity.\n  + inversion LT.\n- destruct EQ.\n  destruct beta.\n  + split;\n    reflexivity.\n  + inversion LT.\nQed.\n\nLemma nf_scalar :\n    forall (a b : ord) (n n' : nat),\n        nf (wcon a n b) ->\n            nf (wcon a n' b).\nProof.\nintros a b n n' N.\ninversion N.\n- apply single_nf.\n  apply H0.\n- apply wcon_nf.\n  + apply H2.\n  + apply H3.\n  + apply H4.\nQed.\n\n\nLemma nf_wcon_head_lt :\n    forall (a a' b' : ord) (n n' : nat),\n        nf (wcon a n (wcon a' n' b')) ->\n            a' < a.\nProof.\nintros a a' b' n n' N.\ninversion N.\napply H2.\nQed.\n\nLemma nf_succ_nf :\n    forall alpha,\n        nf (ord_succ alpha) ->\n            nf alpha.\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 an a2 IHa2].\n- apply zero_nf.\n- destruct a1.\n  + apply (nf_scalar _ _ _ _ NA).\n  + unfold ord_succ in NA; fold ord_succ in NA.\n    destruct a2.\n    * apply (single_nf _ _ (nf_hered_first _ _ _ NA)).\n    * refine (wcon_nf _ _ _ _ _ _ (nf_hered_first _ _ _ NA) (IHa2 (nf_hered_third _ _ _ NA))).\n      destruct a2_1.\n      --  apply zero_lt.\n      --  apply (nf_wcon_head_lt _ _ _ _ _ NA).\nQed.\n\nLemma nf_nf_succ :\n    forall alpha,\n        nf alpha ->\n            nf (ord_succ alpha).\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 an a2 IHa2].\n- apply (single_nf _ _ zero_nf).\n- destruct a1.\n  + destruct (nf_head_zero _ _ NA).\n    unfold ord_succ.\n    fold (nat_ord (S (S an))).\n    apply nf_nat.\n  + destruct a2.\n    * apply (wcon_nf _ _ _ _ _ (zero_lt _ _ _) (nf_hered_first _ _ _ NA) (single_nf _ _ zero_nf)).\n    * unfold ord_succ; fold ord_succ.\n      destruct a2_1.\n      --  destruct (nf_head_zero _ _ (nf_hered_third _ _ _ NA)).\n          apply (wcon_nf _ _ _ _ _ (zero_lt _ _ _) (nf_hered_first _ _ _ NA) (nf_scalar _ _ _ _ (nf_hered_third _ _ _ NA))).\n      --  apply (wcon_nf _ _ _ _ _ (nf_wcon_head_lt _ _ _ _ _ NA) (nf_hered_first _ _ _ NA) (IHa2 (nf_hered_third _ _ _ NA))).\nQed.\n\nLemma nf_ord_max :\n    forall alpha beta,\n        nf alpha ->\n            nf beta ->\n                nf (ord_max alpha beta).\nProof.\nintros alpha beta NA NB.\ncase (ord_ltb alpha beta) eqn:LT;\nunfold ord_max;\nrewrite LT.\n- apply NB.\n- apply NA.\nQed.\n\nLemma nf_wcon_decr :\n    forall (alpha beta : ord) (n : nat),\n        nf (wcon alpha n beta) ->\n            beta < wcon alpha n Zero.\nProof.\nintros alpha beta n N.\ninversion N.\n- apply zero_lt.\n- apply head_lt.\n  apply H2.\nQed.\n\nLemma nf_add_eq_exp :\n    forall (a a' a'' b b' b'' : ord) (n n' n'' : nat),\n        wcon a n b = ord_add (wcon a' n' b') (wcon a'' n'' b'') ->\n            (a = a' \\/ a = a'').\nProof.\nintros a a' a'' b b' b'' n n' n''.\nunfold ord_add; fold ord_add.\ncase (ord_ltb a' a'').\n- intros EQ.\n  inversion EQ.\n  right.\n  reflexivity.\n- case (ord_eqb a' a'').\n  + intros EQ.\n    inversion EQ.\n    right.\n    reflexivity.\n  + intros EQ.\n    inversion EQ.\n    left. \n    reflexivity.\nQed.\n\nLemma nf_add : \n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                nf (ord_add alpha beta).\nProof.\ninduction alpha.\n- intros beta NA NB.\n  rewrite ord_zero_add.\n  apply NB.\n- intros beta NA NB.\n  unfold ord_add; fold ord_add.\n  destruct beta.\n  + apply NA.\n  + destruct (ord_semiconnex_bool alpha1 beta1) as [LT | [GT | EQ]].\n    * rewrite LT.\n      apply NB.\n    * rewrite (ord_ltb_asymm _ _ GT).\n      rewrite (ord_ltb_neb _ _ GT).\n      unfold ord_add; fold ord_add.\n      destruct alpha2.\n      --  rewrite ord_zero_add.\n          apply (wcon_nf _ _ _ _ _ (ord_ltb_lt _ _ GT) (nf_hered_first _ _ _ NA) NB).\n      --  remember (ord_add (wcon alpha2_1 n1 alpha2_2) (wcon beta1 n0 beta2)) as A.\n          destruct A.\n          ++  apply (single_nf _ _ (nf_hered_first _ _ _ NA)).\n          ++  refine (wcon_nf _ _ _ _ _ _ (nf_hered_first _ _ _ NA) _).\n              **  destruct (nf_add_eq_exp _ _ _ _ _ _ _ _ _ HeqA) as [EQ | EQ];\n                  destruct EQ.\n                  { apply (nf_wcon_head_lt _ _ _ _ _ NA). }\n                  { apply (ord_ltb_lt _ _ GT). }\n              **  rewrite HeqA.\n                  apply (IHalpha2 _ (nf_hered_third _ _ _ NA) NB).\n    * apply ord_eqb_eq in EQ.\n      destruct EQ.\n      rewrite ord_ltb_irrefl.\n      rewrite ord_eqb_refl.\n      apply (nf_scalar _ _ _ _ NB).\nQed.\n\nLemma add_right_incr :\n    forall (alpha beta gamma : ord),\n        beta < gamma ->\n            ord_add alpha beta < ord_add alpha gamma.\nProof.\ninduction alpha as [| a1 IHa1 an a2 IHa2].\n- intros beta gamma LTBG.\n  repeat rewrite ord_zero_add.\n  apply LTBG.\n- destruct gamma as [| g1 gn g2];\n  intros LTBG.\n  + inversion LTBG.\n  + destruct beta as [| b1 bn b2].\n\n1 : rewrite ord_add_zero.\n\nall : unfold ord_add; fold ord_add;\n      destruct (ord_semiconnex_bool a1 g1) as [LT | [GT | EQ]];\n      try rewrite LT;\n      try rewrite (ord_ltb_asymm _ _ GT);\n      try rewrite (ord_ltb_neb _ _ GT);\n      try apply ord_eqb_eq in EQ;\n      try destruct EQ;\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl.\n\n1 : apply (head_lt _ _ _ _ _ _ (ord_ltb_lt _ _ LT)).\n\n1 : apply tail_lt.\n    rewrite <- ord_add_zero at 1.\n    apply (IHa2 _ _ LTBG).\n\n1 : apply coeff_lt.\n    lia.\n\n1 : { destruct (ord_semiconnex_bool a1 b1) as [LT' | [GT' | EQ']];\n      try rewrite LT';\n      try rewrite (ord_ltb_asymm _ _ GT');\n      try rewrite (ord_ltb_neb _ _ GT');\n      try apply ord_eqb_eq in EQ';\n      try destruct EQ';\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl.\n      - apply LTBG.\n      - apply (head_lt _ _ _ _ _ _ (ord_ltb_lt _ _ LT)).\n      - apply (head_lt _ _ _ _ _ _ (ord_ltb_lt _ _ LT)). }\n\n\nall : destruct (wcon_lt_aux _ _ _ _ _ _ LTBG) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\n      try destruct EQO;\n      try destruct EQO';\n      try destruct EQN;\n      try destruct EQN';\n      try rewrite (ord_ltb_asymm _ _ (ord_ltb_trans _ _ _ (ord_lt_ltb _ _ LT') GT));\n      try rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _ LT'));\n      try rewrite (ord_ltb_asymm _ _ GT);\n      try rewrite (ord_ltb_neb _ _ (ord_ltb_trans _ _ _ (ord_lt_ltb _ _ LT') GT));\n      try rewrite (ord_ltb_neb _ _ GT);\n      try rewrite (ord_ltb_neb _ _ (ord_lt_ltb _ _ LT'));\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl.\n\n1-3 : apply (tail_lt _ _ _ _ (IHa2 _ _ LTBG)).\n\n1,2 : apply coeff_lt; lia.\n\napply (tail_lt _ _ _ _ LT').\nQed.\n\n\nLemma add_right_incr_non_zero :\n    forall (alpha beta : ord),\n        Zero < beta ->\n            alpha < ord_add alpha beta.\nProof.\nintros alpha beta LT.\nrewrite <- (ord_add_zero alpha) at 1.\napply (add_right_incr alpha Zero beta LT).\nQed.\n\nLemma add_right_non_decr :\n    forall alpha beta,\n        ord_ltb (ord_add alpha beta) alpha = false.\nProof.\nintros alpha beta.\ndestruct beta.\n- rewrite ord_add_zero.\n  apply ord_ltb_irrefl.\n- apply ord_ltb_asymm.\n  apply ord_lt_ltb.\n  apply add_right_incr_non_zero.\n  apply zero_lt.\nQed.\n\nLemma add_left_non_decr :\n    forall alpha beta,\n        ord_ltb (ord_add beta alpha) alpha = false.\nProof.\nintros alpha beta.\ndestruct beta as [| b1 nb b2].\n- rewrite ord_zero_add.\n  apply ord_ltb_irrefl.\n- destruct alpha as [| a1 na a2].\n  + reflexivity.\n  + unfold ord_add; fold ord_add.\n    destruct (ord_semiconnex_bool b1 a1) as [LT | [GT | EQ]].\n    * rewrite LT.\n      apply ord_ltb_irrefl.\n    * rewrite (ord_ltb_asymm _ _ GT).\n      rewrite (ord_ltb_neb _ _ GT).\n      apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (head_lt _ _ _ _ _ _ (ord_ltb_lt _ _ GT)))).\n    * apply ord_eqb_eq in EQ.\n      destruct EQ.\n      rewrite ord_ltb_irrefl.\n      rewrite ord_eqb_refl.\n      refine (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (coeff_lt _ _ _ _ _ _))).\n      lia.\nQed.\n\nLemma ord_max_add_comm :\n    forall alpha beta gamma,\n        ord_add alpha (ord_max beta gamma) = ord_max (ord_add alpha beta) (ord_add alpha gamma).\nProof.\nintros alpha beta gamma.\ndestruct (ord_semiconnex_bool beta gamma) as [LT | [GT | EQ]].\n- unfold ord_max.\n  rewrite LT.\n  rewrite (ord_lt_ltb _ _ (add_right_incr _ _ _ (ord_ltb_lt _ _ LT))).\n  reflexivity.\n- unfold ord_max.\n  rewrite (ord_ltb_asymm _ _ GT).\n  rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (add_right_incr _ _ _ (ord_ltb_lt _ _ GT)))).\n  reflexivity.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  unfold ord_max.\n  repeat rewrite ord_ltb_irrefl.\n  reflexivity.\nQed.\n\nLemma ord_max_geb_split :\n    forall alpha beta gamma delta,\n        ord_ltb alpha gamma = false ->\n            ord_ltb beta delta = false ->\n                ord_ltb (ord_max alpha beta) (ord_max gamma delta) = false.\nProof.\nintros alpha beta gamma delta GEAG GEBD;\nunfold ord_max.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]];\ncase (ord_ltb gamma delta) eqn:LTGD.\n1,2 : rewrite LT.\n3,4 : rewrite (ord_ltb_asymm _ _ GT).\n5,6 : apply ord_eqb_eq in EQ;\n      destruct EQ;\n      rewrite ord_ltb_irrefl.\n- apply GEBD.\n- apply (ord_geb_trans _ _ _ (ord_ltb_asymm _ _ LT) GEAG).\n- apply (ord_geb_trans _ _ _ (ord_ltb_asymm _ _ GT) GEBD).\n- apply GEAG.\n- apply GEBD.\n- apply GEAG.\nQed.\n\nLemma ord_max_le_add :\n    forall alpha beta,\n        nf alpha ->\n            nf beta ->\n                ord_ltb (ord_add alpha beta) (ord_max alpha beta) = false.\nProof.\nintros alpha beta NA NB.\nunfold ord_max.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite LT.\n  apply add_left_non_decr.\n- rewrite (ord_ltb_asymm _ _ GT).\n  destruct beta.\n  + rewrite ord_add_zero.\n    apply ord_ltb_irrefl.\n  + apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (add_right_incr_non_zero _ _ (zero_lt _ _ _)))).\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  rewrite ord_ltb_irrefl.\n  destruct alpha.\n  + reflexivity.\n  + unfold ord_add; fold ord_add.\n    rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    apply ord_ltb_asymm.\n    apply ord_lt_ltb.\n    apply coeff_lt.\n    lia.\nQed.\n\nLemma ord_add_one_succ :\n    forall alpha,\n        nf alpha ->\n            ord_add alpha (wcon Zero 0 Zero) = ord_succ alpha.\nProof.\nintros alpha NA.\ninduction alpha.\n- reflexivity.\n- destruct alpha1;\n  unfold ord_add; fold ord_add.\n  + rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    rewrite <- plus_n_Sm.\n    repeat rewrite <- plus_n_O.\n    destruct (nf_head_zero _ _ NA).\n    reflexivity.\n  + unfold ord_ltb, ord_eqb.\n    rewrite (IHalpha2 (nf_hered_third _ _ _ NA)).\n    reflexivity.\nQed.\n\nLemma ord_add_assoc :\n    forall alpha beta gamma,\n        ord_add (ord_add alpha beta) gamma = ord_add alpha (ord_add beta gamma).\nProof.\ninduction alpha as [| a1 IHa1 na a2 IHa2];\nintros beta gamma.\n- repeat rewrite ord_zero_add.\n  reflexivity.\n- destruct beta as [| b1 nb b2].\n  + rewrite ord_zero_add.\n    rewrite ord_add_zero.\n    reflexivity.\n  + destruct gamma as [| g1 ng].\n    * repeat rewrite ord_add_zero.\n      reflexivity.\n    * unfold ord_add; fold ord_add.\n      destruct (ord_semiconnex_bool a1 b1) as [LT | [GT | EQ]];\n      destruct (ord_semiconnex_bool b1 g1) as [LT' | [GT' | EQ']];\n      try apply ord_eqb_eq in EQ;\n      try apply ord_eqb_eq in EQ';\n      try destruct EQ;\n      try destruct EQ';\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl;\n      try rewrite LT;\n      try rewrite LT';\n      try rewrite (ord_ltb_asymm _ _ GT);\n      try rewrite (ord_ltb_asymm _ _ GT');\n      try rewrite (ord_ltb_neb _ _ GT);\n      try rewrite (ord_ltb_neb _ _ GT');\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl;\n      unfold ord_add; fold ord_add;\n      try rewrite ord_ltb_irrefl;\n      try rewrite ord_eqb_refl;\n      try rewrite LT;\n      try rewrite LT';\n      try rewrite (ord_ltb_asymm _ _ GT);\n      try rewrite (ord_ltb_asymm _ _ GT');\n      try rewrite (ord_ltb_neb _ _ GT);\n      try rewrite (ord_ltb_neb _ _ GT');\n      try reflexivity.\n      --  rewrite (ord_ltb_trans _ _ _ LT LT').\n          reflexivity.\n      --  destruct (ord_semiconnex_bool a1 g1) as [LT | [GT' | EQ]].\n          ++  rewrite LT.\n              reflexivity.\n          ++  rewrite (ord_ltb_neb _ _ GT').\n              rewrite (ord_ltb_asymm _ _ GT').\n              rewrite IHa2.\n              unfold ord_add at 2.\n              rewrite LT'.\n              reflexivity.\n          ++  apply ord_eqb_eq in EQ.\n              destruct EQ.\n              rewrite ord_ltb_irrefl.\n              rewrite ord_eqb_refl.\n              reflexivity.\n      --  rewrite (ord_ltb_asymm _ _ (ord_ltb_trans _ _ _ GT' GT)).\n          rewrite (ord_ltb_neb _ _ (ord_ltb_trans _ _ _ GT' GT)).\n          rewrite IHa2.\n          unfold ord_add at 2.\n          rewrite (ord_ltb_asymm _ _ GT').\n          rewrite (ord_ltb_neb _ _ GT').\n          reflexivity.\n      --  rewrite IHa2.\n          unfold ord_add at 2.\n          rewrite ord_ltb_irrefl.\n          rewrite ord_eqb_refl.\n          reflexivity.\n      --  rewrite <- (plus_assoc nb ng 1).\n          rewrite (plus_comm ng 1).\n          repeat rewrite plus_assoc.\n          reflexivity.\nQed.\n\nLemma ord_succ_add_succ :\n    forall alpha beta,\n        nf alpha ->\n            nf beta ->\n                ord_add alpha (ord_succ beta) = ord_succ (ord_add alpha beta).\nProof.\nintros alpha beta NA NB.\nrewrite <- (ord_add_one_succ _ NB).\nrewrite <- ord_add_assoc.\nrewrite (ord_add_one_succ _ (nf_add _ _ NA NB)).\nreflexivity.\nQed.\n\nLemma ord_add_succ_nat_succ_add :\n    forall (alpha : ord) (n : nat),\n        nf alpha ->\n            ord_add alpha (nat_ord (S n)) = ord_add (ord_succ alpha) (nat_ord n).\nProof.\nintros alpha n NA.\ninduction alpha as [| a1 IHa1 an a2 IHa2].\n- destruct n.\n  + reflexivity.\n  + rewrite ord_zero_add.\n    unfold ord_succ, nat_ord, ord_add.\n    rewrite ord_ltb_irrefl.\n    rewrite ord_eqb_refl.\n    rewrite <- plus_n_Sm.\n    rewrite <- plus_n_O.\n    reflexivity.\n- destruct n.\n  + rewrite ord_add_zero.\n    unfold nat_ord.\n    rewrite (ord_add_one_succ _ NA).\n    reflexivity.\n  + destruct a1.\n    * destruct (nf_head_zero _ _ NA).\n      unfold ord_succ, nat_ord, ord_add.\n      rewrite ord_ltb_irrefl.\n      rewrite ord_eqb_refl.\n      repeat rewrite <- plus_n_Sm.\n      reflexivity.\n    * unfold ord_succ; fold ord_succ.\n      unfold ord_add, nat_ord; fold ord_add.\n      unfold ord_ltb, ord_eqb.\n      unfold nat_ord in IHa2.\n      rewrite (IHa2 (nf_hered_third _ _ _ NA)).\n      reflexivity.\nQed.\n\nLemma nf_mult_eval :\n    forall (a a' b b' : ord) (n n' : nat),\n        Zero < a' ->\n            ord_mult (wcon a n b) (wcon a' n' b') = wcon (ord_add a a') n' (ord_mult (wcon a n b) b').\nProof.\nintros a a' b b' n n' LT.\ndestruct a'.\ninversion LT.\nreflexivity.\nQed.\n\nLemma mult_right_incr :\n    forall (alpha beta gamma : ord),\n        beta < gamma ->\n            Zero < alpha ->\n                nf gamma ->\n                    ord_mult alpha beta < ord_mult alpha gamma.\nProof.\ninduction alpha as [| a1 IHa1 an a2 IHa2].\n1 : intros beta gamma LTBG LT NG.\n    inversion LT.\n\ninduction beta as [| b1 IHb1 bn b2 IHb2];\nintros gamma LTBG LT NG;\ndestruct gamma.\n\n1,3 : inversion LTBG.\n\n1 : destruct gamma1;\n    apply zero_lt.\n\ndestruct (wcon_lt_aux _ _ _ _ _ _ LTBG) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\ntry destruct EQO; try destruct EQN.\n\n- destruct gamma1.\n  inversion LT'.\n  rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n  destruct b1.\n  + apply head_lt.\n    apply add_right_incr_non_zero.\n    apply zero_lt.\n  + rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n    apply head_lt.\n    apply add_right_incr.\n    apply LT'.\n\n- destruct b1.\n  + apply coeff_lt.\n    unfold mul; fold mul.\n    unfold add, sub; fold add sub.\n    repeat rewrite minus_n_0.\n    apply (nat_lt_mul_S_lt _ _ _ LT').\n  + repeat rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n    apply (coeff_lt _ _ _ _ _ LT').\n\n- destruct b1.\n  + destruct (nf_head_zero _ _ NG).\n    inversion LT'.\n  + apply tail_lt.\n    apply (IHb2 _ LT' (zero_lt _ _ _) (nf_hered_third _ _ _ NG)).\nQed.\n\n\nLemma nf_mult : \n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                nf (ord_mult alpha beta).\nProof.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- intros beta NA NB.\n  destruct beta;\n  apply zero_nf.\n- intros beta NA NB.\n  induction beta as [| b1 IHb1 nb b2 IHb2].\n  + apply zero_nf.\n  + destruct b1.\n    * destruct (nf_head_zero _ _ NB).\n      unfold ord_mult.\n      apply (nf_scalar _ _ _ _ NA).\n    * rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n      remember (ord_mult (wcon a1 na a2) b2) as gamma.\n      destruct gamma.\n      --  apply (single_nf _ _ (nf_add _ _ (nf_hered_first _ _ _ NA) (nf_hered_first _ _ _ NB))).\n      --  apply wcon_nf.\n          ++  destruct b2.\n              **  inversion Heqgamma.\n              **  destruct b2_1.\n                  { unfold ord_mult in Heqgamma.\n                    inversion Heqgamma.\n                    destruct H0,H1,H2.\n                    apply (add_right_incr_non_zero _ _ (zero_lt _ _ _)). }\n                  { unfold ord_mult in Heqgamma; fold ord_mult in Heqgamma.\n                    inversion Heqgamma.\n                    rewrite H0,H1,H2 in *.\n                    apply add_right_incr.\n                    apply (nf_wcon_head_lt _ _ _ _ _ NB). }\n          ++  apply (nf_add _ _ (nf_hered_first _ _ _ NA) (nf_hered_first _ _ _ NB)).\n          ++  apply (IHb2 (nf_hered_third _ _ _ NB)).\nQed.\n\nLemma nf_2_exp :\n    forall (alpha : ord),\n        nf alpha ->\n            nf (ord_2_exp alpha).\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- apply single_nf.\n  apply zero_nf.\n- destruct a1 as [| a1_1 na1 a1_2].\n  + apply nf_nat.\n  + destruct a1_1 as [| a1_1_1 na1_1 a1_1_2].        \n    * destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n      destruct na1.\n      --  apply (nf_mult _ _ (single_nf _ _ (single_nf _ _ zero_nf)) (IHa2 (nf_hered_third _ _ _ NA))).\n      --  apply (nf_mult _ _ (single_nf _ _ (single_nf _ _ (single_nf _ _ zero_nf))) (IHa2 (nf_hered_third _ _ _ NA))).\n    * apply (nf_mult _ _ (single_nf _ _ (single_nf _ _ (nf_hered_first _ _ _ NA))) (IHa2 (nf_hered_third _ _ _ NA))).\nQed.\n\nLemma ord_mult_1_r :\n    forall (alpha : ord),\n        alpha = ord_mult alpha (nat_ord 1).\nProof.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- reflexivity.\n- unfold nat_ord, ord_mult, mul, add, sub.\n  rewrite minus_n_0.\n  rewrite mult1_r.\n  reflexivity.\nQed.\n\nLemma ord_mult_1_l :\n    forall (alpha : ord),\n        nf alpha ->\n            alpha = ord_mult (nat_ord 1) alpha.\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- reflexivity.\n- destruct a1.\n  + unfold nat_ord, ord_mult, mul, add, sub.\n    rewrite minus_n_0.\n    rewrite <- plus_n_O.\n    destruct (nf_head_zero _ _ NA).\n    reflexivity.\n  + unfold nat_ord, ord_mult in *.\n    fold ord_mult in *.\n    rewrite ord_zero_add.\n    rewrite (IHa2 (nf_hered_third _ _ _ NA)) at 1.\n    reflexivity.\nQed.\n\nLemma ord_mult_monot :\n    forall (alpha beta : ord),\n        nat_ord 1 < beta ->\n            nf beta ->\n                Zero < alpha ->\n                    alpha < ord_mult alpha beta.\nProof.\nintros alpha beta LT1B NB LTZA.\ndestruct alpha as [| a1 na a2].\n- inversion LTZA.\n- rewrite ord_mult_1_r at 1.\n  apply (mult_right_incr _ _ _ LT1B LTZA NB).\nQed.\n\nLemma ord_mult_0_l :\n    forall (alpha : ord),\n        ord_mult Zero alpha = Zero.\nProof.\ninduction alpha;\nreflexivity.\nQed.\n\nLemma ord_mult_0_r :\n    forall (alpha : ord),\n        ord_mult alpha Zero = Zero.\nProof.\ninduction alpha;\nreflexivity.\nQed.\n\nLemma ord_mult_nonzero :\n    forall (alpha beta : ord),\n        Zero < alpha ->\n            Zero < beta ->\n                nf beta ->\n                    Zero < ord_mult alpha beta.\nProof.\nintros alpha beta LTZA LTZB NB.\nrewrite <- (ord_mult_0_r alpha) at 1.\napply (mult_right_incr _ _ _ LTZB LTZA NB).\nQed.\n\nLemma nat_ord_lt :\n    forall (n m : nat),\n        (n < m)%nat ->\n            nat_ord n < nat_ord m.\nProof.\nintros n m LT.\ndestruct m.\n- inversion LT.\n- induction n.\n  + apply zero_lt.\n  + apply (coeff_lt _ _ _ _ _ (le_S_n _ _ LT)).\nQed.\n\nLemma nat_ord_eq :\n    forall (n m : nat),\n        n = m ->\n            nat_ord n = nat_ord m.\nProof. intros n m EQ. destruct EQ. reflexivity. Qed.\n\nLemma ord_2_exp_geq_1 :\n    forall (alpha : ord),\n        nf alpha ->\n            Zero < ord_2_exp alpha.\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- apply zero_lt.\n- destruct a1 as [| a1_1 na1 a1_2].\n  + destruct (nf_head_zero _ _ NA).\n    unfold ord_2_exp.\n    fold (nat_ord 0).\n    apply nat_ord_lt.\n    apply nat_2_exp_non_zero.\n  + destruct a1_1 as [| a1_1_1 na1_1 a1_1_2].\n    * destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n      destruct na1;\n      apply (ord_mult_nonzero _ _ (zero_lt _ _ _) (IHa2 (nf_hered_third _ _ _ NA)) (nf_2_exp _ (nf_hered_third _ _ _ NA))).\n    * apply (ord_mult_nonzero _ _ (zero_lt _ _ _) (IHa2 (nf_hered_third _ _ _ NA)) (nf_2_exp _ (nf_hered_third _ _ _ NA))).\nQed.\n\nLemma ord_gt_one_succ_lt_dub :\n    forall (alpha : ord),\n        nf alpha ->\n            ord_lt (wcon Zero 0 Zero) alpha ->\n                ord_lt (ord_succ alpha) (ord_mult alpha (nat_ord 2)).\nProof.\nintros alpha NA LT.\ninduction alpha.\n- inversion LT.\n- destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]].\n  + destruct alpha1.\n    * inversion LT'.\n    * apply coeff_lt.\n      lia.\n  + destruct EQO.\n    destruct (nf_head_zero _ _ NA).\n    apply coeff_lt.\n    lia.\n  + destruct EQO.\n    destruct (nf_head_zero _ _ NA).\n    inversion LT'.\nQed.  \n\nLemma ord_gt_zero_exp_gt_one :\n    forall (alpha : ord),\n        nf alpha ->\n            ord_lt Zero alpha ->\n                ord_lt (wcon Zero 0 Zero) (ord_2_exp alpha).\nProof.\nintros alpha NA LT.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- inversion LT.\n- destruct a1.\n  + destruct (nf_head_zero _ _ NA).\n    destruct na.\n    * apply coeff_lt.\n      unfold lt.\n      reflexivity.\n    * fold (nat_ord 1).\n      apply nat_ord_lt.\n      pose proof (nat_exp_monot_lem na) as IE.\n      unfold pow; fold pow.\n      lia.\n  + destruct a1_1.\n    * destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n      destruct a2.\n      --  destruct n;\n          apply head_lt;\n          apply zero_lt.\n      --  destruct n;\n          apply (ord_lt_trans _ _ _ (head_lt _ _ _ _ _ _ (zero_lt _ _ _)) (mult_right_incr _ _ _ (IHa2 (nf_hered_third _ _ _ NA) (zero_lt _ _ _)) (zero_lt _ _ _) (nf_2_exp _ (nf_hered_third _ _ _ NA)))).\n    * destruct a2.\n      --  destruct n;\n          apply head_lt;\n          apply zero_lt.\n      --  destruct n;\n          apply (ord_lt_trans _ _ _ (head_lt _ _ _ _ _ _ (zero_lt _ _ _)) (mult_right_incr _ _ _ (IHa2 (nf_hered_third _ _ _ NA) (zero_lt _ _ _)) (zero_lt _ _ _) (nf_2_exp _ (nf_hered_third _ _ _ NA)))).\nQed.\n\nLemma ord_geq_1_cases :\n    forall (alpha : ord),\n        Zero < alpha ->\n            (alpha = nat_ord 1 \\/ nat_ord 1 < alpha).\nProof.\nintros alpha LTZA.\ndestruct (ord_semiconnex (nat_ord 1) alpha) as [LT | [GT | EQ]].\n- right.\n  apply LT.\n- destruct alpha.\n  + inversion LTZA.\n  + destruct (wcon_lt_aux _ _ _ _ _ _ GT) as [LT | [[EQO LT] | [EQO [EQn LT]]]];\n    inversion LT.\n- left.\n  symmetry.\n  apply EQ.\nQed.\n\nLemma ord_mult_geq_1_case_incr :\n    forall (alpha beta : ord),\n        nf beta ->\n            Zero < beta ->\n                alpha <= ord_mult alpha beta.\nProof.\nintros alpha beta NB LTZB.\nunfold leq.\ndestruct (ord_geq_1_cases _ LTZB) as [EQ | LT].\n- left. \n  rewrite EQ.\n  apply ord_mult_1_r.\n- destruct alpha as [| a1 na a2].\n  + left.\n    symmetry.\n    apply ord_mult_0_l.\n  + right.\n    apply (ord_mult_monot _ _ LT NB (zero_lt _ _ _)).\nQed.\n\nLemma ord_le_mult_exp :\n    forall (alpha beta : ord),\n        nf beta ->\n            alpha <= ord_mult alpha (ord_2_exp beta).\nProof.\nintros alpha beta NB.\napply (ord_mult_geq_1_case_incr _ _ (nf_2_exp _ NB) (ord_2_exp_geq_1 _ NB)).\nQed.\n\nLemma ord_mult_exp_monot :\n    forall (alpha beta gamma : ord),\n        nf gamma ->\n            alpha < beta ->\n                alpha < ord_mult beta (ord_2_exp gamma).\nProof.\nintros alpha beta gamma NG LTAB.\ndestruct (ord_le_mult_exp beta gamma NG) as [EQ | LT].\n- destruct EQ.\n  apply LTAB.\n- apply (ord_lt_trans _ _ _ LTAB LT).\nQed.\n\nLemma ord_2_exp_fp :\n    forall (alpha : ord),\n        nf alpha ->\n            alpha < ord_2_exp alpha \\/ alpha = wcon (nat_ord 1) 0 Zero.\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- left.\n  apply zero_lt.\n- destruct a1 as [| a1_1 na1 a1_2].\n  + left.\n    destruct (nf_head_zero _ _ NA).\n    unfold ord_2_exp.\n    fold (nat_ord (S na)).\n    apply nat_ord_lt.\n    unfold pow; fold pow.\n    unfold mul.\n    rewrite <- plus_n_O.\n    apply nat_exp_monot_lem.\n  + destruct a1_1 as [| a1_1_1 na1_1 a1_1_2].\n    * destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n      destruct na1.\n      --  unfold ord_2_exp; fold ord_2_exp.\n          destruct a2.\n          ++  destruct na.\n              **  right.\n                  reflexivity.\n              **  left.\n                  apply (ord_mult_exp_monot _ _ _ zero_nf).\n                  apply head_lt.\n                  apply coeff_lt.\n                  lia.\n          ++  left.\n              destruct (ord_lt_one _ (nf_wcon_head_lt _ _ _ _ _ NA)).\n              destruct (nf_head_zero _ _ (nf_hered_third _ _ _ NA)).\n              unfold ord_2_exp, nat_ord, pow;\n              fold pow.\n              case (2^n) eqn:EQ.\n              **  destruct (nat_2_exp_not_zero _ EQ).\n              **  unfold mul.\n                  rewrite <- plus_n_O.\n                  rewrite <- plus_n_Sm.\n                  unfold ord_mult, mul, sub.\n                  rewrite <- plus_n_O.\n                  rewrite minus_n_0.\n                  destruct na.\n                  { apply coeff_lt.\n                    lia. }\n                  { apply head_lt.\n                    apply coeff_lt.\n                    lia. }\n      --  left.\n          apply (ord_mult_exp_monot _ _ _ (nf_hered_third _ _ _ NA)).\n          repeat apply head_lt.\n          apply zero_lt.\n    * left.\n      apply (ord_mult_exp_monot _ _ _ (nf_hered_third _ _ _ NA)).\n      repeat apply head_lt.\n      apply ord_lt_self.\nQed.\n\nLemma ord_ltb_exp_false :\n    forall (alpha : ord),\n        nf alpha ->\n            ord_ltb (ord_2_exp alpha) alpha = false.\nProof.\nintros alpha Na.\ndestruct (ord_2_exp_fp alpha Na) as [LT | EQ].\n- apply (ord_ltb_asymm _ _ (ord_lt_ltb _ _ LT)).\n- rewrite EQ.\n  apply ord_ltb_irrefl.  \nQed.\n\nLemma ord_succ_not_exp_fp :\n    forall (alpha : ord),\n        nf (ord_succ alpha) ->\n            ord_lt (ord_succ alpha) (ord_2_exp (ord_succ alpha)).\nProof.\nintros alpha NA.\ndestruct (ord_2_exp_fp (ord_succ alpha) NA) as [LT | EQ].\n- apply LT.\n- pose proof (ord_succ_is_succ _ (nf_succ_nf _ NA)) as FAL.\n  rewrite EQ in FAL.\n  inversion FAL.\nQed.\n\nLemma ord_mult_assoc :\n    forall alpha beta gamma,\n        ord_mult (ord_mult alpha beta) gamma = ord_mult alpha (ord_mult beta gamma).\nProof.\nintros alpha beta gamma.\ninduction gamma as [| g1 IHg1 ng g2 IHg2].\n- destruct beta;\n  destruct alpha;\n  try destruct beta1;\n  reflexivity.\n- destruct beta as [| b1 nb b2].\n  + destruct alpha;\n    reflexivity.\n  + destruct alpha as [| a1 na a2].\n    * destruct g1;\n      reflexivity.\n    * destruct g1 as [| g1_1 ng1 g1_2].\n      --  unfold ord_mult; fold ord_mult.\n          destruct b1.\n          ++  assert ((S (S na * S nb - 1) * S ng - 1) = (S na * S (S nb * S ng - 1) - 1)) as EQ.\n              { unfold mul; fold mul.\n                repeat rewrite <- mult_n_Sm.\n                repeat rewrite (plus_comm (S ng)).\n                rewrite (plus_comm (S nb)).\n                rewrite (plus_comm (S _)).\n                repeat rewrite <- plus_assoc.\n                repeat rewrite <- plus_n_Sm.\n                unfold sub; fold sub.\n                repeat rewrite minus_n_0.\n                lia. }\n              rewrite EQ.\n              reflexivity.\n          ++  reflexivity.\n      --  unfold ord_mult; fold ord_mult.\n          destruct b1 as [| b1_1 nb1 b1_2].\n          ++  rewrite ord_zero_add.\n              rewrite <- IHg2.\n              reflexivity.\n          ++  case (ord_add (wcon b1_1 nb1 b1_2) (wcon g1_1 ng1 g1_2)) eqn:EQ.\n              **  unfold ord_add in EQ; fold ord_add in EQ.\n                  destruct (ord_semiconnex_bool b1_1 g1_1) as [LT | [GT | EQ']].\n                  { rewrite LT in EQ.\n                    inversion EQ. }\n                  { rewrite (ord_ltb_asymm _ _ GT) in EQ.\n                    rewrite (ord_ltb_neb _ _ GT) in EQ.\n                    inversion EQ. }\n                  { apply ord_eqb_eq in EQ'.\n                    destruct EQ'.\n                    rewrite ord_ltb_irrefl in EQ.\n                    rewrite ord_eqb_refl in EQ.\n                    inversion EQ. }\n              **  destruct EQ.\n                  rewrite ord_add_assoc.\n                  rewrite <- IHg2.\n                  reflexivity.\nQed.\n\nLemma ord_not_succ_is_mul :\n    forall alpha,\n        nf alpha ->\n            is_succ alpha = false ->\n                { beta : ord & alpha = ord_mult (wcon (wcon Zero 0 Zero) 0 Zero) beta /\\ nf beta}.\nProof.\nintros alpha NA UA.\ninduction alpha as [|a1 IHa1 na a2 IHa2].\n- exists Zero. \n  split.\n  + reflexivity.\n  + apply zero_nf.\n- unfold is_succ in UA. fold is_succ in UA.\n  destruct a1 as [|a1_1 na1 a1_2].\n  + destruct (nf_head_zero _ _ NA).\n    inversion UA.\n  + destruct a2 as [|a2_1 na2 a2_2].\n    * destruct a1_1 as [|a1_1_1 na1_1 a1_1_2].\n      --  exists (wcon (ord_pred (wcon Zero na1 a1_2)) na Zero).\n          destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n          destruct na1.\n          ++  unfold ord_mult, ord_pred, mul.\n              rewrite <- plus_n_O.\n              unfold sub.\n              rewrite minus_n_0.\n              split.\n              **  reflexivity.\n              **  apply single_nf.\n                  apply zero_nf.\n          ++  unfold ord_pred.\n              rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n              rewrite ord_mult_0_r.\n              unfold ord_add.\n              rewrite ord_ltb_irrefl.\n              rewrite ord_eqb_refl.\n              rewrite <- plus_n_Sm.\n              rewrite <- plus_n_O.\n              split.\n              **  reflexivity.\n              **  repeat apply single_nf.\n                  apply zero_nf.\n      --  exists (wcon (wcon (wcon a1_1_1 na1_1 a1_1_2) na1 a1_2) na Zero).\n          rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n          split.\n          ++  reflexivity.\n          ++  apply NA.\n    * destruct (IHa2 (nf_hered_third _ _ _ NA) UA) as [beta [EQ NB]].\n      rewrite EQ.\n      destruct a1_1 as [| a1_1_1 na1_1 a1_1_2].\n      --  destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n          destruct na1.\n        ++  exists Zero.\n            pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as IE.\n            destruct a2_1.\n            **  destruct (nf_head_zero _ _ (nf_hered_third _ _ _ NA)).\n                inversion UA.\n            **  destruct (wcon_lt_aux _ _ _ _ _ _ IE) as [LT | [[EQO LT] | [EQO [EQn LT]]]];\n                inversion LT.\n        ++  exists (wcon (ord_pred (wcon Zero (S na1) Zero)) na beta).\n            unfold ord_pred.\n            rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n            unfold ord_add.\n            rewrite ord_ltb_irrefl.\n            rewrite ord_eqb_refl.\n            rewrite <- plus_n_Sm.\n            rewrite <- plus_n_O.\n            split.\n            **  reflexivity.\n            **  destruct beta.\n                { inversion EQ. }\n                { refine (wcon_nf _ _ _ _ _ _ (single_nf _ _ zero_nf) NB).\n                  destruct beta1.\n                  { apply zero_lt. }\n                  { rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)) in EQ.\n                    pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as LT.\n                    destruct beta1_1.\n                    { destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NB)).\n                      unfold ord_add in EQ.\n                      rewrite ord_ltb_irrefl, ord_eqb_refl, <- plus_n_Sm, <- plus_n_O in EQ.\n                      inversion EQ as [[EQ1 EQ2 EQ3]].\n                      rewrite EQ1 in *.\n                      apply coeff_lt.\n                      apply le_S_n.\n                      destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQn LT']]]].\n                      { inversion LT'. }\n                      { apply LT'. }\n                      { inversion LT'. } }\n                    { unfold ord_add, ord_ltb in EQ.\n                      inversion EQ as [[EQ1 EQ2 EQ3]].\n                      rewrite EQ1 in *.\n                      inversion LT.\n                      inversion H0. } } }\n      --  exists (wcon (wcon (wcon a1_1_1 na1_1 a1_1_2) na1 a1_2) na beta).\n          rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n          split.\n          { reflexivity. }\n          { destruct beta.\n            { inversion EQ. }\n            { refine (wcon_nf _ _ _ _ _ _ (nf_hered_first _ _ _ NA) NB).\n              destruct beta1.\n              { apply zero_lt. }\n              { rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)) in EQ.\n                pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as LT.\n                destruct beta1_1.\n                { destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NB)).\n                  unfold ord_add in EQ.\n                  rewrite ord_ltb_irrefl, ord_eqb_refl, <- plus_n_Sm, <- plus_n_O in EQ.\n                  inversion EQ as [[EQ1 EQ2 EQ3]].\n                  rewrite EQ1 in *.\n                  apply head_lt.\n                  apply zero_lt. }\n                { unfold ord_add, ord_ltb in EQ.\n                  inversion EQ as [[EQ1 EQ2 EQ3]].\n                  rewrite EQ1 in *.\n                  apply LT. } } } }\nQed.\n\nTheorem ord_lt_succ_cases :\n    forall beta alpha,\n        ord_lt alpha (ord_succ beta) ->\n            nf alpha ->\n                nf beta ->\n                    alpha = beta \\/ ord_lt alpha beta.\nProof.\ninduction beta as [|b1 IHb1 nb b2 IHb2];\nintros alpha LT NA NB.\n- left.\n  destruct alpha.\n  + reflexivity.\n  + destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\n    inversion LT'.\n- destruct alpha as [| a1 na a2].\n  + right.\n    apply zero_lt.\n  + destruct b1.\n    * destruct (nf_head_zero _ _ NB).\n      destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\n      try rewrite EQO in *;\n      try rewrite EQN in *.\n      --  inversion LT'.\n      --  destruct (nat_ge_case_type _ _ LT') as [GT | EQ].\n          ++  right.\n              apply coeff_lt.\n              apply (le_S_n _ _ GT).\n          ++  left.\n              destruct (nf_head_zero _ _ NA).\n              apply eq_add_S in EQ.\n              destruct EQ.\n              reflexivity.\n      --  inversion LT'.\n    * destruct (wcon_lt_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]];\n      try rewrite EQO in *;\n      try rewrite EQN in *.\n      --  right.\n          apply head_lt.\n          apply LT'.\n      --  right.\n          apply coeff_lt.\n          apply LT'.\n      --  destruct (IHb2 _ LT' (nf_hered_third _ _ _ NA) (nf_hered_third _ _ _ NB)) as [EQ | LT''].\n          ++  destruct EQ.\n              left.\n              reflexivity.\n          ++  right.\n              apply tail_lt.\n              apply LT''.\nQed.\n\nLemma ord_ltb_succ_leb :\n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                ord_ltb alpha beta = true ->\n                    ord_ltb beta (ord_succ alpha) = false.\nProof.\nintros alpha beta NA NB LT.\napply ord_ltb_lt in LT.\napply ord_lt_succ in LT.\ndestruct (ord_lt_succ_cases _ _ LT (nf_nf_succ _ NA) NB) as [EQ | LT'].\n- destruct EQ.\n  apply ord_ltb_irrefl.\n- apply ord_ltb_asymm.\n  apply ord_lt_ltb.\n  apply LT'.\nQed.\n\nLemma nf_pred :\n    forall alpha,\n        nf alpha ->\n            nf (ord_pred alpha).\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- apply zero_nf.\n- unfold ord_pred; fold ord_pred.\n  destruct a1.\n  + destruct (nf_head_zero _ _ NA).\n    destruct na.\n    * apply zero_nf.\n    * apply single_nf.\n      apply zero_nf.\n  + destruct a2.\n    * apply NA.\n    * case (ord_pred (wcon a2_1 n0 a2_2)) eqn:EQ.\n      --  apply single_nf.\n          apply (nf_hered_first _ _ _ NA).\n      --  apply wcon_nf.\n          ++  pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as LT.\n              unfold ord_pred in EQ; fold ord_pred in EQ.\n              destruct a2_2;\n              destruct a2_1;\n              destruct n0;\n              inversion EQ as [[EQ1 EQ2 EQ3]];\n              destruct EQ1;\n              apply LT.\n          ++  apply (nf_hered_first _ _ _ NA).\n          ++  apply (IHa2 (nf_hered_third _ _ _ NA)).\nQed.\n\nLemma ord_pred_lt :\n    forall alpha,\n        nf alpha ->\n            is_succ alpha = true ->\n                ord_lt (ord_pred alpha) alpha.\nProof.\nintros alpha NA UA.\nrewrite <- (ord_succ_pred_if_succ _ NA UA) at 2.\napply ord_succ_monot.\nQed.\n\nLemma mult_right_incr_conv :\n    forall (alpha beta gamma : ord),\n        Zero < alpha ->\n            nf beta ->\n                ord_mult alpha beta < ord_mult alpha gamma -> beta < gamma.\nProof.\nintros alpha beta gamma LTZA NB LTm.\ndestruct (ord_semiconnex beta gamma) as [LT | [GT | EQ]].\n- apply LT.\n- pose proof (mult_right_incr _ _ _ GT LTZA NB) as FAL.\n  apply (ord_lt_asymm _ _ LTm) in FAL.\n  inversion FAL.\n- destruct EQ.\n  apply ord_lt_irrefl in LTm.\n  inversion LTm.\nQed.\n\nLemma ord_mult_2_is_add :\n    forall (alpha : ord),\n        nf alpha ->\n            (ord_mult alpha (nat_ord 2)) = ord_add alpha alpha.\nProof.\nintros alpha NA.\ninduction alpha as [| a1 IHa1 na a2 IHa2].\n- reflexivity.\n- unfold nat_ord, ord_mult, ord_add, mul;\n  fold ord_add mul.\n  rewrite ord_ltb_irrefl.\n  rewrite ord_eqb_refl.\n  unfold add, sub.\n  fold add sub.\n  rewrite two_mul.\n  rewrite <- plus_n_Sm.\n  rewrite <- plus_n_O.\n  reflexivity.\nQed.\n\nLemma twice_max_ge_add :\n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                ord_ltb (ord_mult (ord_max alpha beta) (nat_ord 2)) (ord_add alpha beta) = false.\nProof.\nintros alpha beta NA NB.\nrewrite (ord_mult_2_is_add _ (nf_ord_max _ _ NA NB)).\nunfold ord_max.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite LT.\n  destruct alpha as [| a1 na a2].\n  + rewrite ord_zero_add.\n    apply ord_ltb_asymm.\n    apply ord_lt_ltb.\n    apply add_right_incr_non_zero.\n    apply ord_ltb_lt.\n    apply LT.\n  + destruct beta as [| b1 nb b2].\n    * inversion LT.\n    * unfold ord_add; fold ord_add.\n      rewrite ord_ltb_irrefl.\n      rewrite ord_eqb_refl.\n      destruct (wcon_ltb_aux _ _ _ _ _ _ LT) as [LT' | [[EQO LT'] | [EQO [EQN LT']]]].\n      --  rewrite LT'.\n          apply ord_ltb_asymm.\n          apply ord_lt_ltb.\n          apply coeff_lt.\n          lia.\n      --  apply ord_eqb_eq in EQO.\n          destruct EQO.\n          apply nat_ltb_lt in LT'.\n          rewrite ord_ltb_irrefl.\n          rewrite ord_eqb_refl.\n          apply ord_ltb_asymm.\n          apply ord_lt_ltb.\n          apply coeff_lt.\n          lia.\n      --  apply ord_eqb_eq in EQO.\n          destruct EQO, EQN.\n          rewrite ord_ltb_irrefl.\n          rewrite ord_eqb_refl.\n          apply ord_ltb_irrefl.\n- rewrite (ord_ltb_asymm _ _ GT).\n  apply ord_ltb_asymm.\n  apply ord_lt_ltb.\n  apply add_right_incr.\n  apply ord_ltb_lt.\n  apply GT.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  rewrite ord_ltb_irrefl.\n  apply ord_ltb_irrefl.\nQed.\n\nLemma add_left_weak_monot :\n    forall (alpha beta gamma : ord),\n        ord_ltb alpha beta = false ->\n            ord_ltb (ord_add alpha gamma) (ord_add beta gamma) = false.\nProof.\ninduction alpha as [| a1 IHa1 na a2 IHa2];\nintros beta gamma GE.\n- destruct beta.\n  + apply ord_ltb_irrefl.\n  + inversion GE.\n- destruct gamma as [| g1 ng g2].\n  + repeat rewrite ord_add_zero.\n    apply GE.\n  + destruct beta as [| b1 nb b2];\n    unfold ord_add; fold ord_add.\n    * destruct (ord_semiconnex_bool a1 g1) as [LT | [GT | EQ]].\n      --  rewrite LT.\n          apply ord_ltb_irrefl.\n      --  rewrite (ord_ltb_asymm _ _ GT).\n          rewrite (ord_ltb_neb _ _ GT).\n          apply ord_ltb_asymm.\n          apply ord_lt_ltb.\n          apply head_lt.\n          apply ord_ltb_lt.\n          apply GT.\n      --  apply ord_eqb_eq in EQ.\n          destruct EQ.\n          rewrite ord_ltb_irrefl.\n          rewrite ord_eqb_refl.\n          apply ord_ltb_asymm.\n          apply ord_lt_ltb.\n          apply coeff_lt.\n          lia.\n    * destruct (ord_semiconnex_bool a1 b1) as [LT | [GT | EQ]].\n      --  unfold ord_ltb in GE; fold ord_ltb in GE.\n          rewrite LT in GE.\n          inversion GE.\n      --  unfold ord_add; fold ord_add.\n          destruct (ord_semiconnex_bool a1 g1) as [LT' | [GT' | EQ]].\n          ++  rewrite LT'.\n              rewrite (ord_ltb_trans _ _ _ GT LT').\n              apply ord_ltb_irrefl.\n          ++  rewrite (ord_ltb_asymm _ _ GT').\n              rewrite (ord_ltb_neb _ _ GT').\n              destruct (ord_semiconnex_bool b1 g1) as [LT'' | [GT'' | EQ]].\n              **  rewrite LT''.\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite (ord_ltb_asymm _ _ GT').\n                  rewrite (ord_ltb_neb _ _ GT').\n                  reflexivity.\n              **  rewrite (ord_ltb_asymm _ _ GT'').\n                  rewrite (ord_ltb_neb _ _ GT'').\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite (ord_ltb_asymm _ _ GT).\n                  rewrite (ord_ltb_neb _ _ GT).\n                  reflexivity.\n              **  apply ord_eqb_eq in EQ.\n                  destruct EQ.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite (ord_ltb_asymm _ _ GT).\n                  rewrite (ord_ltb_neb _ _ GT).\n                  reflexivity.\n          ++  apply ord_eqb_eq in EQ.\n              destruct EQ.\n              rewrite ord_ltb_irrefl.\n              rewrite ord_eqb_refl.\n              rewrite GT.\n              apply ord_ltb_asymm.\n              apply ord_lt_ltb.\n              apply coeff_lt.\n              lia.\n      --  apply ord_eqb_eq in EQ.\n          destruct EQ.\n          unfold ord_ltb in GE; fold ord_ltb in GE.\n          rewrite ord_ltb_irrefl in GE.\n          rewrite ord_eqb_refl in GE.\n          destruct (nat_semiconnex_bool na nb) as [LT | [GT | EQ]].\n          ++  rewrite LT in GE.\n              inversion GE.\n          ++  destruct (ord_semiconnex_bool a1 g1) as [LT' | [GT' | EQ]].\n              **  rewrite LT'.\n                  apply ord_ltb_irrefl.\n              **  rewrite (ord_ltb_asymm _ _ GT').\n                  rewrite (ord_ltb_neb _ _ GT').\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  rewrite GT.\n                  rewrite (nat_ltb_asymm _ _ GT).\n                  reflexivity.\n              **  apply ord_eqb_eq in EQ.\n                  destruct EQ.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  apply ord_ltb_asymm.\n                  apply ord_lt_ltb.\n                  apply coeff_lt.\n                  apply nat_ltb_lt in GT.\n                  lia.\n          ++  apply nat_eqb_eq in EQ.\n              destruct EQ.\n              rewrite nat_ltb_irrefl in GE.\n              destruct (ord_semiconnex_bool a1 g1) as [LT' | [GT' | EQ]].\n              **  rewrite LT'.\n                  apply ord_ltb_irrefl.\n              **  rewrite (ord_ltb_asymm _ _ GT').\n                  rewrite (ord_ltb_neb _ _ GT').\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  rewrite nat_ltb_irrefl.\n                  apply IHa2.\n                  apply GE.\n              **  apply ord_eqb_eq in EQ.\n                  destruct EQ.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  unfold ord_ltb; fold ord_ltb.\n                  rewrite ord_ltb_irrefl.\n                  rewrite ord_eqb_refl.\n                  rewrite nat_ltb_irrefl.\n                  apply ord_ltb_irrefl.\nQed.\n\n(********)\n(*Inline elements from Casteran's Work*)\n(********)\nDeclare Module R : rpo.RPO.\nImport R.\n\nInductive nf2 : ord -> ord -> Prop :=\n| nf2_z : forall a, nf2 Zero a\n| nf2_c : forall a a' n' b', ord_lt a' a ->\n                             nf2 (wcon a' n' b') a.\n\nLemma nf_of_finite :\n    forall n b,\n        nf (wcon Zero n b) ->\n            b = Zero.\nProof.\nintros n b H; inversion_clear H.\n- trivial.\n- inversion H0.\nQed.     \n\nDefinition nf_rect :\n    forall P : ord -> Type,\n        P Zero ->\n            (forall n: nat, \n                P (wcon Zero n Zero))\n            ->  (forall a n b n' b',\n                    nf (wcon a n b) ->\n                        P (wcon a n b) ->\n                            nf2 b' (wcon a n b) ->\n                                nf b' ->\n                                    P b' ->\n                                        P (wcon (wcon a n b) n' b'))\n                ->  forall a,\n                        nf a ->\n                            P a.\nProof.\nintros P H0 Hfinite Hwcon.\ninduction a.\n- trivial.\n- generalize IHa1; case a1.\n  + intros IHc0 H.\n    rewrite (nf_of_finite _ _ H).\n    apply Hfinite.\n  + intros c n0 c0 IHc0 H2; apply Hwcon.\n    * inversion H2; auto.\n    * apply IHc0.\n      inversion H2; auto.\n    * inversion H2.\n      apply nf2_z.\n      apply nf2_c.\n      auto.\n    * inversion H2; auto.\n      apply zero_nf.\n    * apply IHa2.\n      inversion H2; auto.\n      apply zero_nf.\nDefined.\n\nSection restricted_recursion.\n\nVariables (A:Type)(P:A->Prop)(R:A->A->Prop).\n\nDefinition restrict (a b:A):Prop := P a /\\ R a b /\\ P b.\n\nDefinition well_founded_P := forall (a:A), P a -> Acc restrict a.\n\nDefinition P_well_founded_induction_type : well_founded_P  ->\n  forall X : A -> Type,\n    (forall x : A, P x -> (forall y : A,P y-> R y x -> X y) -> X x) ->\n        forall a : A, P a -> X a.\nintros W X H a. pattern a; eapply well_founded_induction_type with (R:=restrict).\n- unfold well_founded. split. unfold well_founded_P in W. intros; apply W. case H0. auto.\n- intros; apply H. auto. intros; apply X0.\n  + unfold restrict; auto.\n  + auto.\nDefined.\n\nEnd restricted_recursion.\n \nTheorem AccElim3 : forall A B C:Type,\n  forall (RA:A->A->Prop)\n        (RB:B->B->Prop)\n        (RC:C->C->Prop),\n  forall (P : A -> B -> C ->  Prop),\n    (forall x y z,\n        (forall (t : A), RA t x -> \n            forall y' z', Acc RB y' -> Acc RC z' ->\n                  P t y' z') -> (forall (t : B), RB t y -> \n          forall z', Acc RC z' -> P x t z') ->\n    (forall (t : C), RC t z -> P x y t) -> \n    P x y z) -> forall x y z, Acc RA x -> Acc RB y -> Acc RC z -> P x y z.\nProof.\nintros A B C RA RB RC P H x y z Ax; generalize y z; clear y z. elim Ax; clear Ax x; intros x _ Hrecx y z Ay; generalize z; clear z. elim Ay; clear Ay y; intros y _ Hrecy z Az; elim Az; clear Az z; auto. \nQed.\n\nTheorem accElim3:\n forall (A B C:Set)(RA : A -> A ->Prop) (RB : B-> B-> Prop)\n                   (RC : C -> C -> Prop)(P : A -> B -> C ->  Prop),\n (forall x y z ,\n  (forall (t : A), RA t x ->  P t y z) ->\n  (forall (t : B), RB t y ->  P x t z) ->\n  (forall (t : C), RC t z ->  P x y t) ->  P x y z) ->\n forall x y z, Acc RA x -> Acc RB y -> Acc RC z ->  P x y z.\nProof.\nintros A B C RA RB RC P H x y z Ax Ay Az. generalize Ax Ay Az. pattern x, y, z;\n eapply AccElim3 with (RA:=RA)(RB:=RB)(RC:=RC) ;eauto. intros; apply H.\n- intros;apply H0; auto. eapply Acc_inv;eauto.\n- intros;apply H1; auto. eapply Acc_inv;eauto.\n- intros;apply H2; auto. eapply Acc_inv;eauto.\nQed.\n\nModule  Eps0_sig <: term.Signature.\nInductive symb0 : Set := nat_0 | nat_S | ord_zero | ord_wcon.\nDefinition symb := symb0.\n\nLemma eq_symbol_dec : forall f1 f2 : symb, {f1 = f2} + {f1 <> f2}.\nProof.\nintros; decide equality.\nQed.\n\n(** The arity of a symbol contains also the information about built-in theories as in CiME *)\nInductive arity_type : Set :=\n| AC : arity_type\n| C : arity_type\n| Free : nat -> arity_type.\n\nDefinition arity : symb -> arity_type := fun f => match f with\n| nat_0 => Free 0\n| ord_zero => Free 0\n| nat_S => Free 1\n| ord_wcon => Free 3\nend.\n\nEnd Eps0_sig.\n\n(** * Module Type Variables. \n There are almost no assumptions, except a decidable equality. *) \nModule Vars <: term.Variables.\nInductive empty_set : Set := .\nDefinition var := empty_set.\n\nLemma eq_variable_dec : forall v1 v2 : var, {v1 = v2} + {v1 <> v2}.\nProof.\nintros; decide equality.\nQed.\n\nEnd Vars.\n\nModule  Eps0_prec <: Precedence.\nDefinition A : Set := Eps0_sig.symb.\nImport Eps0_sig.\nRequire Import Relations.\n\nDefinition prec : relation A := fun f g => match f, g with\n| nat_0, nat_S => True\n| nat_0, ord_zero => True\n| nat_0, ord_wcon => True\n| ord_zero, nat_S => True\n| ord_zero, ord_wcon => True\n| nat_S, ord_wcon => True\n| _, _ => False\nend.\n\nInductive status_type : Set :=\n| Lex : status_type\n| Mul : status_type.\n\nDefinition status : A -> status_type := fun f => Lex.\n\nLemma prec_dec : forall a1 a2 : A, {prec a1 a2} + {~ prec a1 a2}.\nProof.\nintros a1 a2; destruct a1; destruct a2; ((right; intro; contradiction)||(left;simpl;trivial)).\nQed.\n\nLemma prec_antisym : forall s, prec s s -> False.\nProof.\nintros s; destruct s; simpl; trivial.\nQed.\n\nLemma prec_transitive : transitive A prec.\nProof.\nintros s1 s2 s3; destruct s1; destruct s2; destruct s3; simpl; intros; trivial; contradiction.\nQed.\n\nEnd Eps0_prec.\n\nModule Eps0_alg <: term.Term := term.Make (Eps0_sig) (Vars).\nModule Eps0_rpo <: RPO := rpo.Make (Eps0_alg) (Eps0_prec).\nImport Eps0_alg.\nImport Eps0_rpo.\nImport Eps0_sig.\n\nRemark R1 : Acc P.prec nat_0. \n split.\n destruct y; try contradiction.\nQed.\n#[local] Hint Resolve R1 : ords.\n\nRemark R2 : Acc P.prec ord_zero. \n split.\n destruct y; try contradiction; auto with ords.\nQed.\n#[local] Hint Resolve R2 : ords.\n\nRemark R3 : Acc P.prec nat_S.\n split.\n destruct y; try contradiction; auto with ords.\nQed.\n#[local] Hint Resolve R3 : ords.\n\nRemark R4 : Acc P.prec ord_wcon.\n split.\n destruct y; try contradiction; auto with ords.\nQed.\n#[local] Hint Resolve R4 : ords.\n\nTheorem well_founded_rpo : well_founded rpo.\nProof.\napply wf_rpo. red. destruct a; auto with ords.\nQed.\n\nFixpoint nat_2_term (n:nat) : term :=\nmatch n with\n| 0 => (Term nat_0 Datatypes.nil)\n| S p => Term nat_S ((nat_2_term p)::Datatypes.nil)\nend.\n\nFixpoint ord_2_term (alpha : ord) : term := \nmatch alpha with\n| Zero => Term ord_zero Datatypes.nil\n|wcon a n b => Term ord_wcon (ord_2_term a :: nat_2_term n ::ord_2_term b::Datatypes.nil)\nend.\n\nFixpoint ord_size (o : ord):nat :=\nmatch o with\n|Zero => 0\n| wcon a n b => S (ord_size a + n + ord_size b)%nat\nend.\n\nLemma nat_lt_wcon : forall (n:nat) a p  b , rpo (nat_2_term n) (Term ord_wcon (a::p::b::Datatypes.nil)).\nProof.\ninduction n;simpl.\n- constructor 2.\n  + simpl; trivial.\n  + destruct 1.\n- constructor 2.\n  + simpl; trivial.\n  + inversion_clear 1.\n    * subst s';apply IHn.\n    * case H0.\nQed.\n\nLemma nat_2_term_mono : forall n n', (n < n')%nat -> rpo (nat_2_term n) (nat_2_term n').\nProof.\ninduction 1; simpl; eapply Subterm. eleft. esplit. constructor. eleft. esplit. constructor. auto.\nQed.\n\nTheorem lt_inc_rpo_0 : forall n,\n    forall o' o, (ord_size o + ord_size o' <= n)%nat->\n        ord_lt o o' -> nf o -> nf o' -> \n            rpo (ord_2_term o) (ord_2_term o').\nProof.\ninduction n. destruct o'. inversion 2. destruct o. simpl. inversion 1. simpl;inversion 1. inversion 2.\n- simpl. intros; apply Top_gt. simpl;trivial. inversion 1.\n- simpl; intros; apply Top_eq_lex. simpl;trivial.\n  + left.\n    * apply IHn; auto.\n      { subst o;subst o'. unfold ord_size in H. fold ord_size in H. lia. }\n      { inversion H4; auto. }\n      { inversion H5; auto. }\n    * simpl. lia.\n + inversion_clear 1.\n    * subst s'. change (rpo (ord_2_term a) (ord_2_term (wcon a' n' b'))). apply IHn;auto.\n      { subst o;subst o'. unfold ord_size in *. fold ord_size in *. lia. }\n      { refine (ord_lt_trans _ _ _ (ord_lt_self _ Zero 0) (head_lt _ _ _ _ _ _ H1)). }\n      { inversion H4; auto. }\n    * simpl in H7. decompose [or] H7.\n      { subst s'. apply nat_lt_wcon. }\n      { subst s'. change (rpo (ord_2_term b) (ord_2_term (wcon a' n' b'))). apply IHn;auto.\n        { subst o;subst o'. unfold ord_size in *. fold ord_size in *. lia. }\n        { inversion H4. apply zero_lt. apply head_lt. apply (ord_lt_trans _ _ _ H10 H1). }\n        { inversion H4; auto. apply zero_nf. } }\n      { case H8. }\n- intros. simpl;apply Top_eq_lex. auto. constructor 2. constructor 1. apply nat_2_term_mono. auto. auto. inversion_clear 1.\n  + subst s'.  change (rpo (ord_2_term a) (ord_2_term (wcon a n' b'))). apply IHn;auto.\n    * subst o;subst o'. unfold ord_size in *. fold ord_size in *. lia.\n    * apply ord_lt_self.\n    * inversion H4;auto.\n  + simpl in H7. decompose [or] H7. subst s'. apply nat_lt_wcon.\n    * subst s'. change (rpo (ord_2_term b) (ord_2_term (wcon a n' b'))). apply IHn;auto.\n      { subst o;subst o'. unfold ord_size in *. fold ord_size in *. lia. }\n      { inversion H4.\n        { apply zero_lt. }\n        { apply head_lt. auto. } }\n      { inversion H4;auto. apply zero_nf. }\n    * case H8.\n- simpl. intros;apply Top_eq_lex. auto.\n  + right. right. left.\n    * apply IHn; auto.\n      { subst o;subst o';auto. unfold ord_size in H. fold ord_size in H. lia. }\n      { inversion H4;auto. apply zero_nf. }\n      { inversion H5;auto. apply zero_nf. }\n    * auto.\n  + inversion_clear 1. subst s'. eapply Subterm. 2:eleft. left;auto. simpl in H7. decompose [or] H7.\n    * subst s'. apply nat_lt_wcon.\n    * subst s'. change (rpo (ord_2_term b) (ord_2_term (wcon a n0 b'))). apply IHn; auto.\n      { subst o;subst o'. unfold ord_size in *. fold ord_size in *. lia. }\n      { apply (ord_lt_trans _ _ _ H1). inversion H5.\n        apply zero_lt. apply head_lt. apply H10. }\n      { inversion H4; auto. apply zero_nf. }\n    * case H8.\nQed.\n\nLet R := restrict ord nf ord_lt.\n\nLemma R_inc_rpo : forall o o', R o o' -> rpo (ord_2_term o) (ord_2_term o').\nProof.\nintros o o' (H,(H1,H2)). eapply lt_inc_rpo_0;auto.\nQed. \n\nLemma nf_Wf : well_founded_P _ nf ord_lt.\nProof.\nunfold well_founded_P. intros. unfold restrict. generalize (Acc_inverse_image _ _ rpo ord_2_term a (well_founded_rpo (ord_2_term a))). intro.\neapply  Acc_incl  with  (fun x y : ord => rpo (ord_2_term x) (ord_2_term y)). \n- red. apply R_inc_rpo.\n- auto.\nQed.\n\nDefinition transfinite_induction :\n forall (P: ord -> Type),\n   (forall x: ord, nf x ->\n                   (forall y: ord, nf y ->  ord_lt y x -> P y) -> P x) ->\n    forall a, nf a -> P a.\nProof.\nintros; eapply P_well_founded_induction_type; eauto. eexact nf_Wf;auto.\nDefined.\n\n(******************)\n(*End Casteran inline*)\n(******************)\n\n\nLemma ord_2_exp_succ_mult :\n    forall (alpha : ord),\n        nf alpha ->\n            ord_2_exp (ord_succ alpha) = ord_mult (ord_2_exp alpha) (nat_ord 2).\nProof.\napply (transfinite_induction (fun alpha => ord_2_exp (ord_succ alpha) = ord_mult (ord_2_exp alpha) (nat_ord 2))).\nintros alpha NA IND.\ndestruct alpha as [| a1 na a2].\n- reflexivity.\n- destruct a1.\n  + destruct (nf_head_zero _ _ NA).\n    unfold ord_succ, ord_2_exp.\n    unfold pow; fold pow.\n    destruct (2 ^ na).\n    * reflexivity.\n    * destruct (2 * S n).\n      --  reflexivity.\n      --  unfold nat_ord at 2 3.\n          unfold ord_mult.\n          unfold mul; fold mul.\n          rewrite (plus_comm 2).\n          rewrite <- plus_n_Sm.\n          unfold sub; fold sub.\n          rewrite minus_n_0.\n          rewrite <- plus_n_Sm.\n          repeat rewrite <- plus_n_O.\n          rewrite <- plus_n_Sm.\n          rewrite two_mul.\n          reflexivity.\n  + unfold ord_succ; fold ord_succ.\n    unfold ord_2_exp; fold ord_2_exp.\n    destruct a1_1.\n    * destruct n.\n      --  destruct a2.\n          ++  reflexivity.\n          ++  rewrite (IND _ (nf_hered_third _ _ _ NA) (head_lt _ _ _ _ _ _ (nf_wcon_head_lt _ _ _ _ _ NA))).\n              rewrite ord_mult_assoc.\n              reflexivity.\n      --  rewrite (IND _ (nf_hered_third _ _ _ NA)).\n          rewrite ord_mult_assoc.\n          reflexivity.\n          inversion NA.\n          ++  apply zero_lt.\n          ++  apply head_lt.\n              apply H2.\n    * rewrite (IND _ (nf_hered_third _ _ _ NA)).\n      rewrite ord_mult_assoc.\n      reflexivity.\n      inversion NA.\n      --  apply zero_lt.\n      --  apply head_lt.\n          apply H2.\nQed.\n\nLemma ord_succ_lt_exp_succ :\n    forall (alpha : ord),\n        nf alpha ->\n            ord_lt Zero alpha ->\n                ord_lt (ord_succ (ord_2_exp alpha)) (ord_2_exp (ord_succ alpha)).\nProof.\nintros alpha NA LT.\nrewrite (ord_2_exp_succ_mult _ NA).\napply (ord_gt_one_succ_lt_dub _ (nf_2_exp _ NA) (ord_gt_zero_exp_gt_one _ NA LT)).\nQed.\n\nLemma ord_2_exp_eval :\n    forall alpha,\n        nf alpha ->\n            ord_2_exp (ord_mult (wcon (wcon Zero 0 Zero) 0 Zero) alpha) = wcon alpha 0 Zero.\nProof.\napply transfinite_induction.\nintros alpha NA IND.\ndestruct alpha as [| a1 na a2].\n- reflexivity.\n- destruct a1 as [| a1_1 na1 a1_2].\n  + destruct (nf_head_zero _ _ NA).\n    unfold ord_mult, mul, sub.\n    rewrite <- plus_n_O.\n    rewrite minus_n_0.\n    reflexivity.\n  + rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n    destruct a1_1.\n    * destruct (nf_head_zero _ _ (nf_hered_first _ _ _ NA)).\n      unfold ord_add, ord_ltb, ord_eqb.\n      rewrite <- plus_n_Sm, <- plus_n_O.\n      destruct a2.\n      --  reflexivity.\n      --  unfold ord_2_exp; fold ord_2_exp.\n          rewrite (IND _ (nf_hered_third _ _ _ NA)).\n          ++  rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n              unfold ord_add, add.\n              fold add.\n              pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as LT.\n              rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _ LT)).\n              rewrite (ord_ltb_neb _ _ (ord_lt_ltb _ _ LT)).\n              reflexivity.\n          ++  apply (ord_lt_trans _ _ _ (nf_wcon_decr _ _ _ NA) (tail_lt _ _ _ _ (zero_lt _ _ _))).\n    * unfold ord_add, ord_ltb, ord_eqb.\n      destruct a2.\n      --  reflexivity.\n      --  unfold ord_2_exp; fold ord_2_exp.\n          rewrite (IND _ (nf_hered_third _ _ _ NA)).\n          ++  rewrite (nf_mult_eval _ _ _ _ _ _ (zero_lt _ _ _)).\n              unfold ord_add, add.\n              fold add.\n              pose proof (nf_wcon_head_lt _ _ _ _ _ NA) as LT.\n              rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _ LT)).\n              rewrite (ord_ltb_neb _ _ (ord_lt_ltb _ _ LT)).\n              reflexivity.\n          ++  apply (ord_lt_trans _ _ _ (nf_wcon_decr _ _ _ NA) (tail_lt _ _ _ _ (zero_lt _ _ _))).\nQed.\n\nDefinition exp_monot (alpha : ord ) : Prop :=\n      forall beta,\n          nf beta ->\n              ord_lt beta alpha ->\n                  ord_lt (ord_2_exp beta) (ord_2_exp alpha).\n\nDefinition exp_monot_2 (alpha beta : ord ) : Prop :=\n      ord_lt beta alpha ->\n          ord_lt (ord_2_exp beta) (ord_2_exp alpha).\n\nLemma ord_2_exp_monot :\n    forall alpha,\n        nf alpha ->\n            forall beta,\n                nf beta ->\n                    beta < alpha ->\n                        ord_2_exp beta < ord_2_exp alpha.\nProof.\napply (transfinite_induction exp_monot).\nunfold exp_monot.\nintros alpha NA IND beta NB LT.\ndestruct alpha as [| a1 na a2].\n- inversion LT.\n- case (is_succ (wcon a1 na a2)) eqn:UA.\n  + rewrite <- (ord_succ_pred_if_succ _ NA UA) in LT.\n    destruct (ord_lt_succ_cases _ _ LT NB (nf_pred _ NA)) as [EQ | LT'];\n    rewrite <- (ord_succ_pred_if_succ _ NA UA).\n    * destruct EQ.\n      rewrite (ord_2_exp_succ_mult _ NB).\n      refine (ord_mult_monot _ _ (coeff_lt _ _ _ _ _ _) (single_nf _ _ zero_nf) (ord_2_exp_geq_1 _ NB)).\n      lia.\n    * apply (ord_lt_trans _ (ord_2_exp (ord_pred (wcon a1 na a2)))).\n      --  apply (IND _ (nf_pred _ NA) (ord_pred_lt _  NA UA) _ NB LT').\n      --  rewrite (ord_2_exp_succ_mult _ (nf_pred _ NA)).\n          refine (ord_mult_monot _ _ (coeff_lt _ _ _ _ _ _) (single_nf _ _ zero_nf) (ord_2_exp_geq_1 _ (nf_pred _ NA))).\n          lia.\n  + refine (transfinite_induction (exp_monot_2 (wcon a1 na a2)) _ _ NB LT). \n    unfold exp_monot_2.\n    intros gamma NG IND2 LT'. \n    destruct gamma as [|g1 ng g2].\n    * destruct a1.\n      --  destruct (nf_head_zero _ _ NA).\n          unfold ord_2_exp, pow.\n          fold pow.\n          case (2^na) eqn:EQ.\n          ++  apply nat_2_exp_not_zero in EQ.\n              inversion EQ.\n          ++  apply coeff_lt.\n              fold add.\n              lia.\n      --  destruct a1_1;\n          destruct n;\n          apply (ord_mult_exp_monot _ _ _ (nf_hered_third _ _ _ NA) (head_lt _ _ _ _ _ _ (zero_lt _ _ _))).\n  * case (is_succ (wcon g1 ng g2)) eqn:UG.\n    --  destruct (ord_not_succ_is_mul _ NA UA) as [delta [EQ ND]].\n        rewrite EQ.\n        rewrite (ord_2_exp_eval _ ND).\n        rewrite <- (ord_succ_pred_if_succ _ NG UG).\n        rewrite (ord_2_exp_succ_mult _ (nf_pred _ NG)).\n        pose proof (IND2 _ (nf_pred _ NG) (ord_pred_lt _ NG UG) (ord_lt_trans _ _ _ (ord_pred_lt _ NG UG) LT')) as IE.\n        rewrite EQ in IE.\n        rewrite (ord_2_exp_eval _ ND) in IE.\n        case (ord_2_exp (ord_pred (wcon g1 ng g2))) eqn:Y.\n        ++  apply zero_lt.\n        ++  destruct (wcon_lt_aux _ _ _ _ _ _ IE) as [IE1 | [[EQO IE1] | [EQO [EQN IE1]]]].\n            **  apply head_lt.\n                apply IE1.\n            **  inversion IE1.\n            **  inversion IE1.\n    --  destruct (ord_not_succ_is_mul _ NA UA) as [delta [EQ ND]].\n        rewrite EQ in *.\n        rewrite (ord_2_exp_eval _ ND).\n        destruct (ord_not_succ_is_mul _ NG UG) as [epsilon [EQ' NE]].\n        rewrite EQ' in *.\n        rewrite (ord_2_exp_eval _ NE).\n        apply (mult_right_incr_conv _ _ _ (zero_lt _ _ _) NE) in LT'.\n        apply head_lt.\n        apply LT'.\nQed.\n\nLemma ord_max_exp_comm :\n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                (ord_max (ord_2_exp alpha) (ord_2_exp beta)) = (ord_2_exp (ord_max alpha beta)).\nProof.\nintros alpha beta NA NB.\nunfold ord_max.\ndestruct (ord_semiconnex_bool alpha beta) as [LT | [GT | EQ]].\n- rewrite (ord_lt_ltb _ _ (ord_2_exp_monot _ NB _ NA (ord_ltb_lt _ _ LT))).\n  rewrite LT.\n  reflexivity.\n- rewrite (ord_ltb_asymm _ _ (ord_lt_ltb _ _ (ord_2_exp_monot _ NA _ NB (ord_ltb_lt _ _ GT)))).\n  rewrite (ord_ltb_asymm _ _ GT).\n  reflexivity.\n- apply ord_eqb_eq in EQ.\n  destruct EQ.\n  repeat rewrite ord_ltb_irrefl.\n  reflexivity.\nQed.\n\nLemma dub_succ_geb_exp_succ_eqb :\n    forall (alpha : ord),\n        ord_lt Zero alpha ->\n            nf alpha ->\n                ord_ltb (ord_succ (ord_succ (ord_2_exp alpha))) (ord_2_exp (ord_succ alpha)) = false ->\n                    ord_eqb (ord_succ (ord_succ (ord_2_exp alpha))) (ord_2_exp (ord_succ alpha)) = true.\nProof.\nintros alpha LTZA NA GE.\ndestruct alpha.\n- inversion LTZA.\n- pose proof (ord_succ_lt_exp_succ _ NA LTZA) as LT.\n  apply ord_lt_succ in LT.\n  destruct (ord_lt_succ_cases _ _ LT (nf_nf_succ _ (nf_nf_succ _ (nf_2_exp _ NA))) (nf_2_exp _ (nf_nf_succ _ NA))) as [EQ | LT'].\n  + rewrite EQ.\n    apply ord_eqb_refl.\n  + apply ord_lt_ltb in LT'.\n    rewrite LT' in GE.\n    inversion GE.\nQed.\n\nLemma exp_succ_lt_add :\n    forall (alpha beta : ord),\n        nf alpha ->\n            nf beta ->\n                ord_ltb (ord_2_exp (ord_succ (ord_max alpha beta))) (ord_add (ord_2_exp alpha) (ord_2_exp beta)) = false.\nProof.\nintros alpha beta NA NB.\nrewrite (ord_2_exp_succ_mult _ (nf_ord_max _ _ NA NB)).\nrewrite <- (ord_max_exp_comm _ _ NA NB).\napply (twice_max_ge_add _ _ (nf_2_exp _ NA) (nf_2_exp _ NB)).\nQed.\n\nLemma dub_succ_exp_lt_exp_dub_succ:\n    forall (alpha : ord),\n        nf alpha ->\n            (ord_succ (ord_succ (ord_2_exp alpha))) < (ord_2_exp (ord_succ (ord_succ alpha))).\nProof.\nintros alpha NA.\ndestruct alpha.\n- unfold ord_succ, ord_2_exp, nat_ord, pow, mul, plus.\n  apply coeff_lt.\n  unfold lt.\n  reflexivity.\n- apply (ord_lt_trans _ _ _ (ord_lt_succ _ _ (ord_succ_lt_exp_succ _ NA (zero_lt _ _ _)))).\n  apply (ord_succ_lt_exp_succ _ (nf_nf_succ _ NA) (ord_lt_trans _ _ _ (zero_lt _ _ _) (ord_succ_monot _))).\nQed.\n\nClose Scope cantor_scope. ", "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/Maths/ordinals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7613181487657629}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, contrapositive *)\n\nLemma implies_trans: forall P Q R: Prop,\n  (P->Q)->(Q->R)->(P->R).\nProof.\n    intros.\n    apply H in H1.\n    apply H0 in H1.\n    apply H1.\nQed.\n\nTheorem contrapositive: forall P Q: Prop, \n  (P -> Q) -> (~Q -> ~ P).\nProof.\n    intros.\n    unfold not in H0.\n    unfold not.\n    apply implies_trans with Q.\n    apply H.\n    apply H0.\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/chapter8_Library_Logic/contrapositive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7612756354133834}}
{"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\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 rev2 (rev2_arg0 : Lst) (rev2_arg1 : Lst) : Lst\n           := match rev2_arg0, rev2_arg1 with\n              | nil, a => a\n              | cons x t, a => rev2 t (cons x a)\n              end.\n\nDefinition qrev (x : Lst) : Lst\n  := rev2 x nil.\n\nDefinition amortizeQueue (x : Lst) (y : Lst) : Queue\n  := if leb (len y) (len x) then queue x y else queue (append x (qrev y)) nil.\n\nDefinition isAmortized (isAmortized_arg0 : Queue) : bool\n           := let 'queue x y := isAmortized_arg0 in\n              leb (len y) (len x).\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (isAmortized (amortizeQueue x y)) true.\nProof.\n  intros.\n  unfold amortizeQueue.\n  destruct (len y <=? len x) eqn:?.\n  - simpl. assumption.\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/queue_amort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7612756351156259}}
{"text": "Theorem ex3: forall A B C D: Prop, (A -> C) /\\ (B -> D) -> A /\\ B -> C /\\ D.\nProof.\n  intros.\n  split.\n  elim H. intros.\n  elim H0. intros.\n  apply H1.\n  exact H3.\n  elim H. intros.\n  elim H0. intros.\n  apply H2.\n  assumption.\nQed.\n\nAxiom classic: forall P : Prop, P \\/ ~P.\n\nTheorem doubleng: forall A : Prop, A -> ~~A. \nProof.\n  intro.\n  elim (classic A).\n  intros.\n  contradict H.\n  assumption.\n  intros.\n  contradict H0.\n  assumption.\nQed.\n\nTheorem ex4: forall A : Prop, A -> ~~A.\nProof.\n  intros.\n  contradict H.\n  assumption.\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) ->\n             forall x : A, (exists y : A, R x y) -> R x x.\nProof.\n  intros.\n  elim H1. intros.\n  apply H with x0.\n  split.\n  assumption.\n  exact (H0 x x0 H2).\nQed.\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/Fst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7612276863772848}}
{"text": "(*\nInductive or(P Q:Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q\n.\n\nNotation \"P \\/ Q\" := (or P Q).\n*)\n\n(*\nLemma or_introl : forall (P Q:Prop),\n    P -> P \\/ Q.\nProof. intros P Q H. left. exact H. Qed.\n\nLemma or_intror : forall (P Q:Prop),\n    Q -> P \\/ Q.\nProof. intros P Q H. right. exact H. Qed.\n*)\n\nLemma or_comm : forall (P Q:Prop),\n    P \\/ Q -> Q \\/ P.\nProof.\n    intros P Q [H1|H2].\n    - right. exact H1.\n    - left. exact H2.\nQed.\n\n\nLemma or_assoc : forall (P Q R:Prop),\n    P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n    intros P Q R. split.\n    - intros [Hp | [Hq | Hr]].\n        + left. left. exact Hp.\n        + left. right. exact Hq.\n        + right. exact Hr.\n    - intros [[Hp|Hq]|Hr]. \n        + left. exact Hp.\n        + right. left. exact Hq.\n        + right. right. exact Hr.\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/or.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7612166691963687}}
{"text": "Require Import Bool.\n\nTheorem true_is_True : Is_true true.\nProof.\n  simpl.\n  exact I.\nQed.\n\nTheorem False_is_unprovable : ~False.\nProof.\n  intros proof_False.\n  case proof_False.\nQed.\n\nTheorem not_eqb_true_false : ~(Is_true (eqb true false)).\nProof.\n  simpl.\n  exact False_is_unprovable.\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_True.\n    exact I.\n    (* suppos a is false *)\n    simpl.\n    intros proof_False.\n    case proof_False.\nQed.\n\nTheorem and_sym : (forall a b, a && b = b && a).\nProof.\n  intros a b.\n  case a, b.\n    exact (eq_refl true).\n    exact (eq_refl false).\n    exact (eq_refl false).\n    exact (eq_refl false).\nQed.\n\nTheorem neg_nega : (forall a, a <> (negb a)).\nProof.\n  intros a.\n  unfold not.\n  case a.\n    intros a_eq_nega.\n    simpl in a_eq_nega.\n    discriminate a_eq_nega.\n\n    intros a_eq_nega.\n    simpl in a_eq_nega.\n    discriminate a_eq_nega.\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/bools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7611961914594298}}
{"text": "(** Syntax and Semantics of CNF *)\n\nRequire Export BinNums.\n\nLocal Open Scope list_scope.\n\nDefinition var := positive.\n\nDefinition model := var -> bool.\n\nRecord literal := { is_pos: bool ; ident: var }.\n\n(* syntactic clause *)\nDefinition clause := list literal.\n\nFixpoint sat (c: clause) (m: model): Prop := \n  match c with\n  | nil => False\n  | l::c' => m (ident l) = is_pos l \\/ sat c' m\n  end.\n\n(* syntactic cnf *)\nDefinition cnf := list clause.\n\nFixpoint sats (f: cnf) (m: model): Prop :=\n  match f with\n  | nil => True\n  | c::f' => sat c m /\\ sats f' m \n  end.\n\nInductive isUnsat (f:cnf): Prop := \n  isUnsat_proof: (forall m, ~(sats f m)) -> isUnsat f.\n\nDefinition isSat(f: cnf): Prop := exists m, sats f m.\n\nLemma isSat_neg_isUnsat (f: cnf): isUnsat f <-> ~(isSat f).\nProof.\n  firstorder.\nQed.\n", "meta": {"author": "boulme", "repo": "satans-cert", "sha": "ff74c60d6e328cbd521dd82dec435872b7cb0b8a", "save_path": "github-repos/coq/boulme-satans-cert", "path": "github-repos/coq/boulme-satans-cert/satans-cert-ff74c60d6e328cbd521dd82dec435872b7cb0b8a/coq_src/CnfSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7611961897841454}}
{"text": "Require Import ZArith. \nRequire Import List.\nRequire Import String.\n\nOpen Scope Z_scope.\nDelimit Scope string_scope with string.\nLocal Open Scope string_scope.\nSet Implicit Arguments.\n\n(****Expressoes com Variaveis****)\nPrint string.\n(*1*)\n\nInductive Op : Type :=\n  | P   : Op\n  | M   : Op\n  | MM  : Op.\n\nLet var := string.\nInductive El : Type :=\n  | Num  : Z -> El\n  | Var   : var -> El.\n\nInductive aexp :=\n  | Leaf : El -> aexp\n  | Node : aexp -> Op -> aexp -> aexp.\n\nLet state := var -> Z.\nLet init : state := fun _ => 0.\n\nLet update (s : state) (v : var) (z : Z) : state :=\n  fun x => if (string_dec x v)%string then z else s x.\n(*2*)\n\nEval compute in \"123\".\nEval compute in init \"x\".\nEval compute in update init \"x\" 3 \"x\".\nEval compute in update init \"x\" 3 \"y\".\n\nFixpoint aeval (a : aexp) (s : state) : Z :=\n    match a with\n    | Leaf (Num n) => n\n    | Leaf (Var n) => s n\n    | Node L P R  => aeval L s + aeval R s\n    | Node L M R  => aeval L s - aeval R s\n    | Node L MM R => aeval L s * aeval R s\nend.\n\nModule TreeNotations.\nNotation \"( L ; + ; R )\" := (Node L P R).\nNotation \"( L ; - ; R )\" := (Node L M R).\nNotation \"( L ; * ; R )\" := (Node L MM R).\nNotation \"« x »\" := (Leaf (Num x)).\nNotation \"«« x »»\" := (Leaf (Var x)).\nEnd TreeNotations.\n\nImport TreeNotations.\n\nModule ListNotations.\nNotation \"[ ]\" := nil (format \"[ ]\") : list_scope.\nNotation \"[ x ]\" := (cons x nil) : list_scope.\nNotation \"[ x ; y ; .. ; z ]\" := (cons x (cons y .. (cons z nil) ..)) : list_scope.\nEnd ListNotations.\n\nImport ListNotations.\n\nOpen Scope Z.\n\n(*3*)\n\nEval compute in (2*3)+(3*(4-2)).\n\nEval compute in aeval ((«2»;*;«3»);+;(«3»;*;(«4»;-;«2»))) init.\n\nEval compute in (20-40)*(30+(1*1)).\n\nEval compute in aeval ((«20»;-;«40»);*;(«30»;+;(«1»;*;«1»))) init.\n\nEval compute in aeval ((«20»;-;«40»);*;(«30»;+;(««\"x\"»»;*;««\"x\"»»))) (update init \"x\" 1).\n\n(*4*)\n\nFixpoint aevalR (a : aexp) (n : Z) (s : state) : Prop :=\n  match a with\n  | Leaf (Num z) => z = n \n  | Leaf (Var v)  => s v = n \n  | Node a1 op a2 => \n      match op with \n      | P =>\n          exists (n1 n2: Z),  aevalR a1 n1 s /\\ aevalR a2 n2 s /\\ n1 + n2 = n\n      | M => \n          exists (n1 n2: Z),  aevalR a1 n1 s /\\ aevalR a2 n2 s /\\ n1 - n2 = n\n      | MM => \n          exists (n1 n2: Z),  aevalR a1 n1 s /\\ aevalR a2 n2 s /\\ n1 * n2 = n\n     end\n  end.\n(*5*)\n\nTheorem RelEqFun : forall (a : aexp) (n : Z) (s : state),\n                    (aevalR a n s) <-> (aeval a s = n).\nProof.\n  induction a.\n  - intros. \n    induction e.\n    + simpl. reflexivity.\n    + simpl; reflexivity.\n  - red. intros. induction o.\n    + split.\n      * simpl. intros. \n        destruct H as [n1 H]. \n        destruct H as [n2 H]. \n        destruct H. destruct H0. \n        assert (IHa1 := (IHa1 n1 s)).\n        assert (IHa2 := (IHa2 n2 s)).\n        unfold iff in IHa1; destruct IHa1; clear H3.\n        unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H)).\n        assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6.\n        assumption.\n      * simpl. intros.\n        assert (IHa1 := (IHa1 (aeval a1 s) s)).\n        assert (IHa2 := (IHa2 (aeval a2 s) s)).\n        unfold iff in IHa1; destruct IHa1; clear H0.\n        unfold iff in IHa2. destruct IHa2. clear H0.\n        exists (aeval a1 s); exists (aeval a2 s).\n        auto 4.\n(*______________________________________________________________________________________________________________*)\n    + split.\n      * simpl; intros. \n        destruct H as [n1 H];destruct H as [n2 H].  \n        destruct H; destruct H0;\n        assert (IHa1 := (IHa1 n1 s));assert (IHa2 := (IHa2 n2 s)).\n        unfold iff in IHa1; destruct IHa1; clear H3;unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H));assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6;assumption.\n      * simpl; intros.\n        assert (IHa1 := (IHa1 (aeval a1 s) s));assert (IHa2 := (IHa2 (aeval a2 s) s)).\n        unfold iff in IHa1; destruct IHa1; clear H0;unfold iff in IHa2. destruct IHa2. clear H0.\n        exists (aeval a1 s); exists (aeval a2 s); auto 4.\n    + split.\n      * simpl; intros. \n        destruct H as [n1 H];destruct H as [n2 H].  \n        destruct H; destruct H0;\n        assert (IHa1 := (IHa1 n1 s));assert (IHa2 := (IHa2 n2 s)).\n        unfold iff in IHa1; destruct IHa1; clear H3;unfold iff in IHa2; destruct IHa2; clear H4.\n        assert (H5 := (H2 H));assert (H6 := (H3 H0)).\n        rewrite H5; rewrite H6;assumption.\n      * simpl; intros.\n        assert (IHa1 := (IHa1 (aeval a1 s) s));assert (IHa2 := (IHa2 (aeval a2 s) s)).\n        unfold iff in IHa1; destruct IHa1; clear H0;unfold iff in IHa2. destruct IHa2. clear H0.\n        exists (aeval a1 s); exists (aeval a2 s); auto 4.\nQed.\n\n(****Maquina de Stack****)\nLet stack     := list Z.\n\nInductive Exp : Type :=\n  | Elm   : El -> Exp\n  | Pls   : Exp\n  | Min   : Exp\n  | Mul   : Exp.\n\nLet stack_exp := list Exp.\n\nDefinition SPush (n : Z) (st : stack) : stack :=\n  cons n st.\n\nDefinition SLoad (x : var) (st : stack) (s : state) : stack :=\n  cons (s x) st. \n\nDefinition SPlus (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b+a) c)\n  end.\n\nDefinition SMinus (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b-a) c)\n  end.\n\n\nDefinition SMult (st : stack) : option stack :=\n  match st with\n    | nil => None\n    | cons a nil => None\n    | cons a (cons b c) => Some (cons (b*a) c)\n  end.\n\n(*1*)\nFixpoint execute (s : state) (st : stack) (a : stack_exp) : option stack :=\n  match a with\n  | nil => Some st\n  | cons (Elm (Num n)) a' => execute s (SPush n st) a'\n  | cons (Elm (Var v)) a' => execute s (SLoad v st s) a'\n  | cons Pls a'     => \n      match SPlus st with\n      | Some st' => execute s st' a'\n      | None => None\n      end\n  | cons Min a'     => \n      match SMinus st with\n      | Some st' => execute s st' a'\n      | None => None\n      end\n  | cons Mul a'     => \n      match SMult st with\n      | Some st' => execute s st' a'\n      | None => None\n      end\n  end.\n\n\nCheck cons (Elm(Num 2)) (\n                             cons (Elm(Num 3)) (\n                             cons Mul ( \n                             cons (Elm(Num 3)) ( \n                             cons (Elm(Num 4)) ( \n                             cons (Elm(Num 2)) ( \n                             cons Min ( \n                             cons Mul ( \n                             cons Pls ( \n                             nil))))))))).\n\n(*2*)\nLet stack_machine : stack := nil. \n\nLet expression : stack_exp := [Elm (Num 2); Elm (Num 3); Mul; Elm (Num 3); Elm (Num 4); Elm (Num 2); Min; Mul; Pls].\n\nEval compute in execute init stack_machine expression.\n\n(*3*)\n(*\n    Decidimos usar o option para saber se houve problema.\n    *)\n\n\nLocal Open Scope list.\n\n(****Compilador****)\n\n(*1*)\nFixpoint compile (a : aexp) : stack_exp := \n  match a with\n  | Leaf e => cons (Elm e) nil\n  | Node l P r => compile l ++ compile r ++ cons Pls nil\n  | Node l M r => compile l ++ compile r ++ cons Min nil\n  | Node l MM r => compile l ++ compile r ++ cons Mul nil\n  end.\n\n(*2*)\n\nEval compute in execute init nil (compile ((«2»;*;«3»);+;(«3»;*;(«4»;-;«2»)))).\n\n(*3*)\n\nLemma Dinamic_Execute (z : Z) (se1 se2 : stack_exp) :\n  forall (st st1 : stack) (s : state),\n    execute s st se1 = Some (z :: nil) -> \n    execute s (st ++ st1) (se1 ++ se2) = execute s (z :: st1) se2.\nProof.\n  induction se1.\n  - simpl.\n    intros.\n    inversion H.\n    simpl.\n    reflexivity.\n  - induction a. induction e.\n    + simpl.\n      intros.\n      apply (IHse1 (z0 :: st) st1 s).\n      assumption.\n    + simpl.\n      intros.\n      apply (IHse1 ((s v) :: st) st1 s).\n      assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 + a) :: st) st1).\n           assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 - a) :: st) st1).\n           assumption.\n    + induction st.\n      * intros.\n        simpl in H.\n        inversion H.\n      * induction st.\n        -- intros.\n           simpl in H.\n           inversion H.\n        -- simpl.\n           intros.\n           apply (IHse1 ((a0 * a) :: st) st1).\n           assumption.\nQed. \n\nTheorem Correction : forall (a : aexp) (s : state),\n                     (execute s nil (compile a) = Some (cons (aeval a s) nil)).\nProof.\n  intros.\n  induction a. induction e.\n  - simpl. reflexivity.\n  - simpl; reflexivity.\n  - induction o.\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1 s) (compile a1) (compile a2 ++ Pls :: nil) nil nil s) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2 s) (compile a2) (Pls :: nil) nil (aeval a1 s :: nil) s) IHa2)); simpl in H1.\n      rewrite H.\n      rewrite H1.\n      reflexivity.\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1 s) (compile a1) (compile a2 ++ Min :: nil) nil nil s) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2 s) (compile a2) (Min :: nil) nil (aeval a1 s :: nil) s) IHa2)); simpl in H1.\n      rewrite H; rewrite H1; reflexivity.\n    + simpl. \n      assert (H := ((Dinamic_Execute (aeval a1 s) (compile a1) (compile a2 ++ Mul :: nil) nil nil s) IHa1)); rewrite <- (app_nil_end nil) in H.\n      assert (H1 := ((Dinamic_Execute (aeval a2 s) (compile a2) (Mul :: nil) nil (aeval a1 s :: nil) s) IHa2)); simpl in H1.\n      rewrite H; rewrite H1; reflexivity.\nQed.\n", "meta": {"author": "AJGQ", "repo": "trabalhoVF", "sha": "7c4f5679db8389f4b384c5d31a101092ac305cab", "save_path": "github-repos/coq/AJGQ-trabalhoVF", "path": "github-repos/coq/AJGQ-trabalhoVF/trabalhoVF-7c4f5679db8389f4b384c5d31a101092ac305cab/com_vars.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7611264493521943}}
{"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.\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\nEnd EX.\n\nPrint example.\n(* ================================================================== *)\nPrint trivial.\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. \n   Note that when entering in this mode the other subgoals are not displayed. \n   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.\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 H.\n  destruct H.\n  - contradiction.\n  - assumption.\nQed.\n\n\nLemma ex6' : (P \\/ Q) /\\ ~P -> Q.\nProof.\n  intros.\n  destruct H.\n  destruct H.\n  - contradiction.\n  - assumption.\nQed. \n\n\nPrint ex6'.\nPrint ex6.\n\n\nLemma ex7 : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.  \n  red.  (* unfold \"<->\". *)\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.\n  intros.\n  destruct H as [H1 H2].\n  destruct H2 as [H2 H3].\n  destruct H3 as [H3 H4].\n  split.\n  - apply H1. apply H3.\n  - apply H2. apply H4.\nQed.\n\n(* exercise *)\nLemma ex9 : ~ (P /\\ ~P).   \nProof.\n  unfold not.\n  intros.\n  destruct H.\n  apply H0.\n  apply H.\nQed.\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\nLemma ex13 : (exists x, R x) -> (forall x y, R x -> W y) -> forall y, W y.\nProof.\n intros H H1 y1.  \n destruct H as [ x1 H0].\n (* try \"apply H1.\" to see error message *)\n apply H1 with x1 . (* apply  (H1 x1). *) \n assumption.\nQed.\n\n \n(* Exercise *)\nLemma ex14 : (forall x, R x) \\/ (forall x, W x) -> forall x, (R x) \\/ (W x).\nProof.\n  intros H x.\n  destruct H.\n  - left. apply H.\n  - right. apply H.\nQed.\n  \nVariable G : X->X->Prop.\n\n(* Exercise *)\nLemma ex15 : (exists x, exists y, (G x y)) -> exists y, exists x, (G x y).\nProof.\n  intros.\n  destruct H as [x1 H].\n  destruct H as [y1 H].\n  exists y1. exists x1.\n  apply H.\nQed.\n\n(* Exercise *)\nProposition ex16: (forall x, W x) /\\ (forall x, R x) -> (forall x, W x /\\ R x).\nProof.\n  intros.\n  destruct H.\n  split.\n  - apply H.\n  - apply H0.\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.   (* apply (R_transitive x 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": "melpereira7", "repo": "VF_2122", "sha": "cbac6daa9e4640a095cfadc06ad5fa5722d4bbfd", "save_path": "github-repos/coq/melpereira7-VF_2122", "path": "github-repos/coq/melpereira7-VF_2122/VF_2122-cbac6daa9e4640a095cfadc06ad5fa5722d4bbfd/Exercícios/Coq/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7610764957309906}}
{"text": "Require Export chapter06.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* 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\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\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Lmn Lno.\n  generalize dependent Lmn.\n  generalize dependent m.\n  induction Lno.\n  Case \"le_n\". intros. apply Lmn.\n  Case \"le_S\". intros. apply le_S. apply IHLno. apply Lmn.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n.\n  apply le_n.\n  apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros. induction H.\n  apply le_n.\n  apply le_S. apply IHle.\nQed.\n\nTheorem n_le_Sn : forall n, n <= S n.\nProof. intros. apply le_S. apply le_n. Qed.\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 le_trans with (n := S n). apply n_le_Sn.\n    apply H2.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction a.\n  Case \"0\". simpl. apply O_le_n.\n  Case \"S\". simpl. apply n_le_m__Sn_le_Sm. apply IHa.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\nAdmitted.\n \nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. intros. apply le_S. apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intros n m. generalize dependent n. induction m.\n  Case \"0\". destruct n.\n    SCase \"0\". intros. apply le_n.\n    SCase \"S n\". simpl. intros. inversion H.\n  Case \"S m\". intros. destruct n.\n    SCase \"0\". apply O_le_n.\n    SCase \"S n\". apply n_le_m__Sn_le_Sm. apply IHm.\n                 simpl in H. apply H.\nQed.\n\nTheorem le_ble_nat : forall n m,\n  n <= m ->\n  ble_nat n m = true.\nProof.\n  intros. generalize dependent n. induction m.\n  Case \"0\". destruct n.\n    SCase \"0\". simpl. intros. reflexivity.\n    SCase \"S n\". intros. inversion H.\n  Case \"S m\". intros. destruct n.\n    SCase \"0\". simpl. reflexivity.\n    SCase \"S n\". simpl. apply IHm.\n                 apply Sn_le_Sm__n_le_m.\n                 apply H.\nQed.\n\nTheorem ble_nat_true_trans : forall n m o,\n  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.\nProof.\n  intros.\n  apply le_ble_nat.\n  apply le_trans with (n := m).\n    apply ble_nat_true. apply H.\n    apply ble_nat_true. apply H0.\nQed.\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\nTheorem R_add : forall m n o, R m n o -> m + n = o.\nProof.\n  intros.\n  induction H.\n    simpl. reflexivity.\n    simpl. apply f_equal. apply IHR.\n    rewrite plus_comm. simpl. apply f_equal. rewrite -> plus_comm. apply IHR.\n    simpl in IHR. inversion IHR. rewrite -> plus_comm in H1. simpl in H1.\n                  inversion H1. rewrite -> plus_comm. reflexivity.\n    rewrite -> plus_comm. apply IHR.\nQed.\n\n", "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/chapter07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7610574509688114}}
{"text": "Require Import ZArith Nnat Omega.\nOpen Scope Z_scope.\n\n(** Test of the zify preprocessor for (R)Omega *)\n\n(* More details in file PreOmega.v\n\n   (r)omega with Z        : starts with zify_op\n   (r)omega with nat      : starts with zify_nat\n   (r)omega with positive : starts with zify_positive\n   (r)omega with N        : starts with uses zify_N\n   (r)omega with *        : starts zify (a saturation of the others)\n*)\n\n(* zify_op *)\n\nGoal forall a:Z, Zmax a a = a.\nintros.\nomega with *.\nQed.\n\nGoal forall a b:Z, Zmax a b = Zmax b a.\nintros.\nomega with *.\nQed.\n\nGoal forall a b c:Z, Zmax a (Zmax b c) = Zmax (Zmax a b) c.\nintros.\nomega with *.\nQed.\n\nGoal forall a b:Z, Zmax a b + Zmin a b = a + b.\nintros.\nomega with *.\nQed.\n\nGoal forall a:Z, (Zabs a)*(Zsgn a) = a.\nintros.\nzify.\nintuition; subst; omega. (* pure multiplication: omega alone can't do it *)\nQed.\n\nGoal forall a:Z, Zabs a = a -> a >= 0.\nintros.\nomega with *.\nQed.\n\nGoal forall a:Z, Zsgn a = a -> a = 1 \\/ a = 0 \\/ a = -1.\nintros.\nomega with *.\nQed.\n\n(* zify_nat *)\n\nGoal forall m: nat, (m<2)%nat -> (0<= m+m <=2)%nat.\nintros.\nomega with *.\nQed.\n\nGoal forall m:nat, (m<1)%nat -> (m=0)%nat.\nintros.\nomega with *.\nQed.\n\nGoal forall m: nat, (m<=100)%nat -> (0<= m+m <=200)%nat.\nintros.\nomega with *.\nQed.\n(* 2000 instead of 200: works, but quite slow *)\n\nGoal forall m: nat, (m*m>=0)%nat.\nintros.\nomega with *.\nQed.\n\n(* zify_positive *)\n\nGoal forall m: positive, (m<2)%positive -> (2 <= m+m /\\ m+m <= 2)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m:positive, (m<2)%positive -> (m=1)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m: positive, (m<=1000)%positive -> (2<=m+m/\\m+m <=2000)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m: positive, (m*m>=1)%positive.\nintros.\nomega with *.\nQed.\n\n(* zify_N *)\n\nGoal forall m:N, (m<2)%N -> (0 <= m+m /\\ m+m <= 2)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m<1)%N -> (m=0)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m<=1000)%N -> (0<=m+m/\\m+m <=2000)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m*m>=0)%N.\nintros.\nomega with *.\nQed.\n\n(* mix of datatypes *)\n\nGoal forall p, Z_of_N (N_of_nat (nat_of_N (Npos p))) = Zpos p.\nintros.\nomega with *.\nQed.\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/test-suite/success/OmegaPre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7610574440559207}}
{"text": "(* Brandon Reno | Robbie Hughs ----- KNAPSACK PROBLEM ----- Course Project Phase 2 - Implementation *)\nFrom LF Require Import Poly.\nFrom LF Require Export Induction.\nFrom LF Require Export Lists.\n\n\n(* WEIGHTCHECK DEFINITION: Purpose, get the weight of a group of items *)\n\nFixpoint WeightCheck (l:list (nat * nat)): nat :=\nmatch l with\n| [] => 0\n| h :: t => snd h + WeightCheck t\nend.\n\nLemma weightCheck_test1: WeightCheck [(3,4);(5,6);(7,8)] = 18.\nProof. reflexivity. Qed.\n\nLemma weightCheck_test2: WeightCheck [(3,6);(5,8);(7,1)] = 15.\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\n(* VALUECHECK DEFINITION: Purpose, get the value of a group of items *)\n\nFixpoint ValueCheck (l:list (nat * nat)): nat :=\nmatch l with\n| [] => 0\n| h :: t => fst h + ValueCheck t\nend.\n\nLemma valueCheck_test1: ValueCheck [(3,4);(5,6);(7,8)] = 15.\nProof. reflexivity. Qed.\n\nLemma valueCheck_test2: ValueCheck [(1,6);(5,8);(20,1)] = 26.\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\n(*FILTERWEIGHTS DEFINITION: Purpose, to filter a group of items and return only the groups\n of items less than equal to max weight does this by utilizing weight check function defined above *)\n\nFixpoint FilterWeights (l:list(list (nat * nat))) (max: nat): list(list(nat * nat)) :=\nmatch l with\n| [] => [[(0,0)]]\n| h :: t => if leb (WeightCheck h) max then h :: (FilterWeights t max) else FilterWeights t max\nend.\n\nLemma filter_test1: FilterWeights [[(3,4) ; (5,6) ; (7,8) ; (9,10)] ; [(1,6);(5,8);(20,1)] ; [(3,2) ; (2,3)]] 10 = [[(3,2) ; (2,3)]; [(0,0)]].\nProof. reflexivity. Qed.\n\nLemma filter_test2: FilterWeights [[(3,4) ; (5,6) ; (7,8) ; (9,10)] ; [(1,6);(5,8);(20,1)] ; [(3,2) ; (2,3)]] 15 = [[(1, 6); (5, 8); (20, 1)]; [(3, 2); (2, 3)]; [(0, 0)]].\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\n(*SUBSETS DEFINITION: Purpose, generates subsets of differen combinations of items *)\n\nFixpoint Subsets (l:list (nat * nat)): (list (list (nat * nat))) :=\nmatch l with\n| [] => [[]]\n| h::t => Subsets t ++ map (app [h]) (Subsets t)\nend.\nCompute Subsets [(3,4) ; (5,6) ; (7,8)].\n\nLemma subset_test: Subsets [(3,4) ; (5,6) ; (7,8)] = [[ ]; [(7, 8)]; [(5, 6)]; [(5, 6); (7, 8)]; \n       [(3, 4)]; [(3, 4); (7, 8)]; [(3, 4); (5, 6)];\n       [(3, 4); (5, 6); (7, 8)]].\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\n(* KNAPSACK DEFINITION: Purpose find the list that gets the greatest value\n   KNAPSACKDRIVER DEFINITION: Purpose generate subsets of the given list, filter the subsets based on \n        the max weight and then return the list from knapsack which gives best value *)\n\nFixpoint Knapsack (l:list (list (nat * nat))) (l2:list (nat * nat)) (value:nat): list (nat * nat) :=\nmatch l with\n|[] => l2\n|h :: t => if leb value (ValueCheck h) then Knapsack t h (ValueCheck h) else Knapsack t l2 value\nend.\n\nDefinition Knapsack_Driver (l:list (nat * nat)) (l2:list (nat * nat)) (max_weight: nat) : list (nat * nat) :=\nmatch max_weight with\n|O => l2\n|S n => Knapsack (FilterWeights(Subsets l) max_weight) [] 0\nend.\n\n\n(* Testing the knapsack problem now with some test lemmas *)\n\n\nLemma Knapsack_Test: Knapsack_Driver [(3,4) ; (5,6) ; (7,8) ; (9,10)] [] 15 = [(3, 4); (9, 10)].\nProof. reflexivity. Qed.\n\nLemma Knapsack_Test2: Knapsack_Driver [(3,6) ; (5,2) ; (7,5) ; (30,10)] [] 15 =[(7, 5); (30, 10)].\nProof. reflexivity. Qed.\n\nLemma Knapsack_Test3: Knapsack_Driver [(3,6) ; (5,2) ; (7,5) ; (30,10)] [] 10 =[(30, 10)].\nProof. reflexivity. Qed.\n\nLemma Knapsack_Test4: Knapsack_Driver [(33,20) ; (56,23) ; (21,15) ; (30,10) ; (40,1) ; (23,13)] [] 10 =[(40, 1)].\nProof. reflexivity. Qed.\n\nLemma Knapsack_Test5: Knapsack_Driver [(33,20) ; (56,23) ; (21,15) ; (30,10) ; (40,1) ; (23,13)] [] 54 = [(33, 20); (56, 23); (30, 10); (40, 1)].\nProof. reflexivity. Qed.\n\n\n(* Verification phase *)\n\nFixpoint max_val_perm (l : list(list(nat * nat))) (n : nat) : nat :=\nmatch l with\n| [] => n\n| h :: t => if leb n (ValueCheck h) then max_val_perm t (ValueCheck h) else max_val_perm t n\nend.\n\nLemma max_val_perm_test1: max_val_perm(FilterWeights [[(3,4) ; (5,6) ; (7,8) ; (9,10)] ; [(1,6);(5,8);(20,1)] ; [(3,2) ; (2,3)]] 10) 0 = 5.\nProof. intros. reflexivity. Qed.\n\nLemma max_val_perm_test2: max_val_perm(FilterWeights [[(3,4) ; (5,6) ; (7,8) ; (9,10)] ; [(1,6);(5,8);(20,1)] ; [(3,2) ; (2,3)]] 20) 0 = 26.\nProof. intros. reflexivity. Qed.\n\nLemma max_val_perm_test3: max_val_perm(FilterWeights [[(3,4) ; (5,6) ; (7,8) ; (9,10)] ; [(1,6);(5,8);(20,1)] ; [(3,2) ; (2,3)]] 30) 0 = 26.\nProof. intros. reflexivity. Qed.\n\nLemma ksg0: forall (l : list(nat * nat)) (w :nat), leb 0 (ValueCheck(Knapsack_Driver l [] w)) = true.\nProof. intros. induction l.\n  simpl. reflexivity.\n  simpl. reflexivity.\nQed.\n\nLemma vcg0: forall (l : list(nat * nat)) (w : nat), leb 0 (max_val_perm(FilterWeights(Subsets l) w) 0) = true.\nProof. intros. induction l.\n  simpl. reflexivity. \n  simpl. reflexivity.\nQed.\n\n\nLemma ks_help: forall (l : list(nat * nat)) (w : nat) (x : (nat * nat)),\n(Knapsack_Driver l [] w) = (Knapsack_Driver (x :: l) [] w).\nProof. intros. induction w. reflexivity. Admitted.\n\n\nLemma vc_help: forall (l : list(nat * nat)) (w : nat) (x : (nat * nat)),\n(max_val_perm (FilterWeights (Subsets l ) w)0) =  (max_val_perm (FilterWeights (Subsets (x::l)) w)0).\nProof. Admitted.\n\n\nLemma Knap_help: forall (l : list(nat * nat)) (w : nat) (x : (nat * nat)), \n      (ValueCheck (Knapsack_Driver l [ ] w)) =? (max_val_perm (FilterWeights (Subsets l) w) 0) = true-> \n      (ValueCheck (Knapsack_Driver (x::l) [ ] w)) =? (max_val_perm (FilterWeights (Subsets (x::l)) w)0) = true.\nProof. intros. rewrite <- ks_help. rewrite <- vc_help. assumption.\nQed.\n\nTheorem KnapSack_verification: forall (l: list(nat * nat)) (w: nat), \neqb (ValueCheck(Knapsack_Driver l [] w)) (max_val_perm(FilterWeights(Subsets l) w) 0) = true.\nProof. intros. induction l. induction w.\n      - reflexivity.\n      - reflexivity.\n      - simpl. apply Knap_help. assumption.\nQed.\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/Verification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7610158095428871}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\n\n(** * Scope *)\n(** \n\n- core_scope : scope for Gallina basic notation\n- type_scope : scope for Type\n\n- [Open Scope <scope>.] : to open a scope\n- [exp%k] : to specify a scope for an expression, [k] is a delimiting key (a symbol associated to a scope)\n- [Locate <notation>.] : to know how notation(s) are interpreted \n\n*)\n\nOpen Scope Z_scope.\n\nLocate \"_ * _\".\n\n(** \n\n- [Print Scope <scope>.] : to know the associated delimiting key and all notation of a scope.\n\n*)\n\nPrint Scope Z_scope.\n\n(** * Check type *)\n\n(**\n- [Check t.] : To know the type of the term [t].\n- [nat] is the delimiting key of [nat_scope], i.e. Peano numbers (TODO:to verify).\n- [Z] is the delimiting key of [Z_scope], i.e. integers.\n*)\n\nPrint Scope nat_scope.\n\nCheck 33%nat.\nCheck 0%nat.\nCheck 0.\n\nOpen Scope nat_scope.\n\nCheck 33.\nCheck 0.\n\nCheck 33%Z.\nCheck (-12)%Z.\n\nOpen Scope Z_scope.\n\nCheck (-12).\nCheck (33%nat).\n\n(** There is no membership in Gallina, an integer of type [nat] is not include in [Z]. If we want to convert an integer of type [nat] to [Z], we need to define a function.\n*)\n\n(** * Simply typed lambda calculus *)\n\n(**\nTwo types :\n- _atomic_ type : e.g. [nat], [Z] and [bool]\n- _arrow_ type : e.g. [A -> B]. TODO:See Ch05. ML.\n*)\n\n(**\n- Declaration : [(x:A)]\n- Definition : [x := t:A]\n*)\n\n(**\n- _Environment_ : sequence of *global* declarations/definitions  \n- _Context_ : sequence of *local* declarations/definitions\n\nAt the beginning of a session, there is an environment called [initial] and an empty context.\n\n- [Reset Initial.] : come back to [initial] environment.\n- [Reset <id>.] : remove all declaration/definition after [id].\n*)\n\n(**\n- $E$ #E# and $\\Gamma$ #Gamma# denote respectively the environment and the context.\n- \n*)\n\n\n", "meta": {"author": "firmart", "repo": "coq-art", "sha": "cc1d940e9d0fbb03b949015114788723e0a7ec8b", "save_path": "github-repos/coq/firmart-coq-art", "path": "github-repos/coq/firmart-coq-art/coq-art-cc1d940e9d0fbb03b949015114788723e0a7ec8b/Ch03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.7610158049818209}}
{"text": "(* Define a datatype to represent natural numbers. *)\nInductive nat : Set :=\n  (* A natural number can be zero, *)\n  | Z : nat\n  (* or the successor of another natural number. *)\n  | S : nat -> nat.\n\n(* Two is the successor of successor of zero. *)\nDefinition two : nat := S (S Z).\n\n(* We can find the predecessor. *)\nDefinition pred (n : nat) : nat :=\n  (* Let's investigate the given number: *)\n  match n with\n    (* If it's zero, let's just return zero. *)\n  | Z => Z\n    (* Otherwise, pred of \"succ of n\" is just n. *)\n  | S n' => n'\nend.\n\n(* We define addition on two \"nat\"s, recursively.\n   A recursive function is defined using Fixpoint. *)\nFixpoint plus (n m : nat) : nat :=\n  (* Let's analyze n. *)\n  match n with\n    (* If it's zero, we return m. *)\n  | Z => m\n    (* Otherwise, n is S n' for some n'. *)\n  | S n' =>\n    (* We recursively compute \"plus n' m\", then apply S. *)\n    S (plus n' m)\nend.\n\n(* Equality type is defined like this. *)\nInductive eq (A : Set) : A -> A -> Prop :=\n  refl : forall x : A, eq A x x.\n\n(* Don't need to understand this now;\n   just use equality type as \"eq x y\" and reflexivity as \"refl\". *)\nArguments eq {_} x y.\nArguments refl {_ _}.\n\n(* Reflexivity holds by definition. *)\nDefinition this_is_free : eq (S Z) (S Z) := refl.\n\n(* We can write more complex expressions as \"Theorem\", and provide \"Proof\" with tactics. *)\nTheorem this_is_almost_free : eq (plus two Z) (plus Z two).\n(* If you use Coq IDE locally, you can see \"goal\" at this point. *)\nProof.\n  (* If we evaluate the two sides, they're equal, so we can prove the theorem with \"refl\". *)\n  apply refl.\n  (* All goals are satisfied, we close the proof with \"Qed\".\n     Then \"this_is_almost_free\" is defined with auto-generated body. *)\nQed.\n\n(* Now, we define a utility function \"cong\":\n   if two sides are equal, they're still equal after applying a function on both sides. *)\nTheorem cong : forall (f : nat -> nat) (n m : nat), eq n m -> eq (f n) (f m).\nProof.\n  (* Bring the parameters as hypotheses. *)\n  intros f n m eq_n_m.\n  (* The \"inversion\" tactic can identify how we can satisfy \"eq n m\" - n and m should be equal. *)\n  inversion eq_n_m.\n  (* Now n and m are equal, and the goal is \"eq (f m) (f m)\". How do we close it? *)\n  apply refl.\nQed.\n\n(* Let's prove the main theorems. *)\nTheorem plus_O_a : forall n : nat, eq (plus Z n) n.\nProof.\n  (* Bring the parameters as hypotheses. Hint: See above. *)\n  intros.\n  (* \"plus Z n\" is, by definition of plus, \"n\". *)\n  simpl plus.\n  apply refl.\nQed.\n\nTheorem plus_a_O : forall n : nat, eq (plus n Z) n.\nProof.\n  (* This time, it's not simple at all like the above.\n     Let's try induction principle. *)\n  induction n as [ | n' IHn ].\n    (* Base case : the theorem holds when n = Z (this is trivial.) *)\n  - simpl plus.\n    apply refl.\n    (* Induction case : If the theorem holds with n', the theorem holds with S n'.\n       The \"If\" part is given as hypothesis \"IHn\" here.\n       Let's apply the definition of plus. If you're using IDE, you can see S is extracted out. *)\n  - simpl.\n    (* The conclusion has S on both sides. Let's strip it. *)\n    apply cong.\n    (* Now it's exactly the same as the induction hypothesis. *)\n    assumption.\nQed.\n\n(* Congratulations! For better introduction, google Coq Software Foundations. *)\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/additident.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7609631276570606}}
{"text": "Require Import XR_Rabs.\nRequire Import XR_Rsqr_le_abs_0.\nRequire Import XR_plus_le_is_le.\nRequire Import XR_Rle_0_sqr.\n\nLocal Open Scope R_scope.\n\nLemma triangle_rectangle_le : forall x y z:R,\n    Rsqr x + Rsqr y <= Rsqr z -> Rabs x <= Rabs z /\\ Rabs y <= Rabs z.\nProof.\n  intros x y z h.\n  split.\n  {\n    apply Rsqr_le_abs_0.\n    apply plus_le_is_le with (Rsqr y).\n    { apply Rle_0_sqr. }\n    { exact h. }\n    }\n  {\n    apply Rsqr_le_abs_0.\n    apply plus_le_is_le with (Rsqr x).\n    { apply Rle_0_sqr. }\n    {\n      rewrite Rplus_comm.\n      exact h.\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_triangle_rectangle_le.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.760963121618312}}
{"text": "Set Nested Proofs Allowed.\nRequire Import Utf8 ZArith.\nRequire Import Main.RingLike.\nOpen Scope Z_scope.\n\nRecord gauss_int := mk_gi { gi_re : Z; gi_im : Z }.\n\nDefinition gi_zero := mk_gi 0 0.\nDefinition gi_one := mk_gi 1 0.\nDefinition gi_i := mk_gi 0 1.\n\nDefinition gi_add α β := mk_gi (gi_re α + gi_re β) (gi_im α + gi_im β).\nDefinition gi_mul α β :=\n  mk_gi (gi_re α * gi_re β - gi_im α * gi_im β)\n    (gi_re α * gi_im β + gi_im α * gi_re β).\nDefinition gi_opp α := mk_gi (- gi_re α) (- gi_im α).\n\nDefinition gi_sub α β := gi_add α (gi_opp β).\nDefinition gi_conj α := mk_gi (gi_re α) (- gi_im α).\n\nDeclare Scope G_scope.\nDelimit Scope G_scope with G.\nNotation \"0\" := gi_zero : G_scope.\nNotation \"1\" := gi_one : G_scope.\nNotation \"'ⁱ'\" := gi_i (at level 0) : G_scope.\nNotation \"- α\" := (gi_opp α) : G_scope.\nNotation \"α + β\" := (gi_add α β) : G_scope.\nNotation \"α * β\" := (gi_mul α β) : G_scope.\nNotation \"α - β\" := (gi_sub α β) : G_scope.\n\nDefinition gi_gauge (α : gauss_int) :=\n  Z.abs_nat (gi_re α * gi_re α + gi_im α + gi_im α)%Z.\n\nDefinition gi_eucl_div α β :=\n  let d := gi_re β * gi_re β + gi_im β * gi_im β in\n(**)\n  let γ := gi_re (α * gi_conj β)%G / d in\n  let γ' := gi_im (α * gi_conj β)%G / d in\n(*\n  let γ := (gi_re α * gi_re β + gi_im α * gi_im β) / d in\n  let γ' := (gi_im α * gi_re β - gi_re α * gi_im β) / d in\n*)\n  let q :=\n    if lt_dec (gi_gauge (α - β * mk_gi γ γ')%G) (gi_gauge β) then\n      mk_gi γ γ'\n    else if lt_dec (gi_gauge (α - β * mk_gi (γ + 1) γ')%G) (gi_gauge β) then\n      mk_gi (γ + 1) γ'\n    else if lt_dec (gi_gauge (α - β * mk_gi γ (γ' + 1))%G) (gi_gauge β) then\n      mk_gi γ (γ' + 1)\n    else if\n      lt_dec (gi_gauge (α - β * mk_gi (γ + 1) (γ' + 1))%G) (gi_gauge β)\n    then\n      mk_gi (γ + 1) (γ' + 1)\n    else\n      0%G\n  in\n  let r := (α - β * q)%G in\n  (q, r).\n\nDefinition gi_div α β := fst (gi_eucl_div α β).\n\nNotation \"α / β\" := (gi_div α β) : G_scope.\n\nCanonical Structure gauss_int_ring_like_op : ring_like_op gauss_int :=\n  {| rngl_zero := gi_zero;\n     rngl_one := gi_one;\n     rngl_add := gi_add;\n     rngl_mul := gi_mul;\n     rngl_opt_opp_or_subt := Some (inl gi_opp);\n     rngl_opt_inv_or_quot := Some (inr gi_div);\n     rngl_opt_eqb := None; (* to be improved, perhaps *)\n     rngl_opt_le := None |}.\n\n(*\nCompute (mk_gi (- 36) 242 / mk_gi 50 50)%G.\n*)\n\n(* to be completed with gauss_int_ring_like_prop... *)\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/GaussIntRl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331958, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7609631204474424}}
{"text": "Fixpoint even (n : nat) : bool :=\nmatch n with\n| 0 => true\n| S n' => odd n'\nend\n\nwith odd (n : nat) : bool :=\nmatch n with\n| 0 => false\n| S n' => even n'\nend.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/evenodd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810451666345, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7609116261796401}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nRequire Import Coq.omega.Omega.\nRequire Export Logic.\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 new definition of evenness works, let's use\n    its rules to show that [4] is even. By rule [ev_SS], it suffices\n    to show that [2] is even. This, in turn, is again guaranteed by\n    rule [ev_SS], as long as we can show that [0] is even. But this\n    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                                 ev 0\n\n                                  ev n\n                             --------------                      (ev_SS)\n                              ev (S (S n))\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                ------  (ev_0)\n                 ev 0\n                ------ (ev_SS)\n                 ev 2\n                ------ (ev_SS)\n                 ev 4\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\n(* enumerate of all direct proofs *)\nInductive ev : nat -> Prop :=\n| ev_0  : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n\n\n\nCheck (ev_0).\nCheck (ev_SS 12).\nCheck (ev_SS 1).  (* note this proposition does not reduce to ev 0 !*)\n\n(*\n\n compare: \n  Inductive lists (X : Type) : Type :=\n    | Nil  : lists X\n    | cons : X -> lists X -> lists X.\n*)\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 to the _right_ of the colon, it is allowed to take\n    different values in the types of different constructors: [0] in\n    the type of [ev_0] and [S (S n)] in the type of [ev_SS].\n\n         -> depdendent type?\n\n    In contrast, the definition of [list] puts 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\n    error:\n*)\n\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 theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Such \"constructor\n    theorems\" have the same status as proven theorems.  In particular,\n    we can use Coq's [apply] tactic with the rule names to prove [ev]\n    for particular numbers... *)\n\nTheorem ev_2 : ev 2.\nProof. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. (* backward proof: ev 4 is true if ev 2 is true *)\n       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\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.\n  intros n. induction 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(** 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(** ** Inversion on Evidence *)\n\n(** Subtracting two from an even number yields another even number.\n    We can easily prove this claim with the techniques that we've\n    already seen, provided that we phrase it in the right way.  If we\n    state it in terms of [evenb], for instance, we can proceed by a\n    simple case analysis on [n]: *)\n\nTheorem evenb_minus2: forall n,\n  evenb n = true -> evenb (pred (pred n)) = true.\nProof.\n  intros [ | [ | n' ] ].  (* <- what does this destruction pattern do? *)\n  - (* n = 0 *) reflexivity.\n  - (* n = 1; contradiction *) intros H. inversion H.\n  - (* n = n' + 2 *) simpl. intros H. apply H.\nQed.\n\n(** We can state the same claim in terms of [ev], but this quickly\n    leads us to an obstacle: Since [ev] is defined inductively --\n    rather than as a function -- Coq doesn't know how to simplify a\n    goal involving [ev n] after case analysis on [n].  As a\n    consequence, the same proof strategy fails: *)\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; we're stuck! *) simpl. \nAbort.\n\n(** The solution is to perform case analysis on the evidence that [ev\n    n] _directly_. By the definition of [ev], there are two cases to\n    consider:\n\n    - If that 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, that 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(** We can invoke this kind of argument in Coq using the [inversion]\n    tactic.  Besides allowing us to reason about equalities involving\n    constructors, [inversion] provides a case-analysis principle for\n    inductively defined propositions.  When used in this way, its\n    syntax is similar to [destruct]: We pass it a list of identifiers\n    separated by [|] characters to name the arguments to each of the\n    possible constructors.  For instance: *)\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].  (* do case analysis on possible proofs *)\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n(**  AAA: I'm finding it a bit awkward to discuss [inversion] here\n    instead of [destruct], especially given that we are using\n    [destruct] to talk about [reflect] below... Would it be too crazy\n    to use [inversion] only where it is actually needed? \n *)\n(**  BCP: I have never been satisfied with our discussion of\n    destruct vs. inversion.  What's here now is much better than we've\n    ever had before.  But if you have a clear idea for how to clean it\n    up further, I'm all ears.\n\n    One possibility -- perhaps easy enough to do now -- would be to\n    replace inversion by destruct in this discussion and move the\n    inversion vs. destruct discussion into the following\n    subsection.  (In fact, I favor trying this.  The next section also\n    needs some help, and consolidating the discussion would be a good\n    beginning.) \n *)\n\n(** Note that, in this particular case, it is also possible to replace\n    [inversion] by [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'.\nQed.\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'].  (* ev (S S n) implies n is even and n' = n *) \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: *)\nTheorem one_not_even : ~ ev 1.\nProof.\n  unfold not.\n  intros H. inversion H.\nQed.\n\n(** **** Exercise: 1 star (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* ev (n + 4) ==> ev (n' + 2) where n' = n + 2*)\n  intros n E. inversion E as [| n' E'].\n      (* but ev (n' + 2) ==> ev n' *)\n    + inversion E'. apply H1.\nQed.      \n\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros H. inversion H. inversion H1. inversion H3.\nQed.\n\n(** ** The Inversion Tactic Revisited *)\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n(* ####################################################### *)\n(** ** Induction over Evidence *)\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], we already know that those are equivalent to\n    each other). To show that all three coincide, we still need the\n    following lemma: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\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    exists k', n' = double k',\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.\n      reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\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\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       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\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique when studying the semantics of programming\n    languages, where many properties of interest are defined\n    inductively.  The following exercises provide simple examples of\n    this 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.\n  intros n m H1 H2. induction H1 as [n' | H1'].\n    + apply H2.\n    + simpl. apply ev_SS. apply IHev.\nQed.      \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\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\n    the old one. *)\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros n. split.\n  (* -> *)\n  - intros H. induction H.\n      + apply ev_0.\n      + apply ev_SS. apply ev_0.\n      + apply ev_sum. apply IHev'1. apply IHev'2.\n  (* <- *)\n  - intros H. induction H.\n      + apply ev'_0.\n      + destruct IHev.  (*todo: ev' n implies what? why does this make sense??? *)\n          * apply ev'_2.\n          * apply (ev'_sum 2). apply ev'_2. apply ev'_2.\n          * apply (ev'_sum 2 (n+m)). apply ev'_2. apply (ev'_sum n m).\n            apply IHev1. apply IHev2.\nQed.            \n            \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  intros n m Hnm Hn. induction Hn.\n    + simpl in Hnm. apply Hnm.\n    + simpl in Hnm. apply evSS_ev in Hnm.\n      apply IHHn. apply Hnm.\nQed.\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 *) Admitted.\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 of evenness that we had\n    already seen, and does not seem to offer any concrete benefit over\n    them.  To give a better sense of the power of inductive\n    definitions, we now show how to use them to model a classic\n    concept in computer science: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing strings,\n    defined as elements of the following inductive type.  (The names\n    of the constructors should become clear once we explain their\n    meaning below.)  *)\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(** Note that this definition is _polymorphic_: Regular expressions in\n    [reg_exp T] describe strings with characters drawn from [T] --\n    that is, lists of elements of [T].  (We depart slightly from\n    standard practice in that we do not require the type [T] to be\n    finite.  This results in a somewhat different theory of regular\n    expressions, but the difference is not significant for our\n    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].  (As a special case, the sequence of\n      strings may be empty, so [Star re] always matches the empty\n      string [[]] no matter what [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 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(** Once again, for readability, we can also display this definition\n    using inference-rule notation.  At the same time, let's introduce\n    a more readable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\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(** 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\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Furthermore, 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\n    evidence.  (The [exp_match_eq] exercise below asks you to prove\n    that the constructors given in the inductive declaration and the\n    ones that would arise from a more literal transcription of the\n    informal rules are indeed equivalent.) *)\n\n(* ############################################################ *)\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 to help write 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_ex)  *)\n(** The following lemmas show that the informal matching rules given\n    first can be obtained from the formal inductive definition. *)\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros T s. unfold not.\n  intros H. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s re1 re2. intros [H1 | H2].\n    + apply MUnionL. apply H1.\n    + apply MUnionR. apply H2.\nQed.  \n\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\n(*\n   eg: fold (++) [\"hello\",\"world\"] []   =~ star re\n       where re matches the strings\n*)\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros T ss re H. induction ss as [|s' ss'].\n    + simpl. apply MStar0.\n    + simpl. apply MStarApp.\n        - apply H. simpl. left. reflexivity.\n        - apply IHss'. intros s H1.\n          apply H. simpl. right. apply H1.\nQed.          \n  \n\n(** **** Exercise: 4 stars (reg_exp_of_list)  *)\n(** Prove that [reg_exp_of_list] satisfies the following\n    specification: *)\n\n(*\n   suppose s1,s2 are lists, then\n   s1 matches regex(s2)   if and only if   s1 = s2\n*)\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  intros T s1 s2. split.\n  (* -> *)\n  + generalize dependent s1. induction s2 as [|s s2'].\n      - intros s1 H. inversion H. reflexivity.\n      - intros s1 H. inversion H. subst.\n        apply IHs2' in H4. rewrite H4. inversion H3. reflexivity.\n  (* <- *)\n  +  generalize dependent s1. induction s2 as [|s s2'].\n      - intros s1 H. simpl. rewrite H. apply MEmpty.\n      - intros s1 H. rewrite H. simpl. apply (MApp [s]).\n          * apply MChar.\n          * apply IHs2'. reflexivity.\nQed.\n                     \n\n\n(** ** Rule Induction *)\n\n(** Suppose that we wanted to prove the following intuitive result: if\n    a regular expression [re] matches some string [s], then all\n    elements of [s] must occur somewhere in [re]. We begin by defining\n    a function [re_chars] that lists all single-character elements\n    that occur anywhere in a regular expression:\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\nLemma in_re_match :\n  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\n(** When doing induction on [Hmatch], we can name the arguments given\n    to each of the rules in the same way we can name arguments given\n    to data type constructors. Whenever one of these arguments is a\n    premise of the same type as the one we are doing induction on (in\n    this case, [exp_match]), we additionally give a name to the\n    induction hypothesis that is generated for that premise. *)\n\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(** Most cases of the proof are straightforward.  Notice how doing\n    induction directly over [Hmatch] has the benefit of not requiring\n    an explicit inversion on a hypothesis, since that step is\n    performed automatically by the [induction]. *)\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(** In the the [MStarApp] case, notice that we now have an induction\n    hypothesis that we can apply when [x] is a member of [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).\n\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} (re : reg_exp T) : bool := match re with\n  | EmptySet    => false\n  | EmptyStr    => true\n  | Char _      => true\n  | App r1 r2   => re_not_empty r1 && re_not_empty r2\n  | Union r1 r2 => re_not_empty r1 || re_not_empty r2\n  | Star r      => true\n  end.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros T re. split.\n  (* -> *)\n  + intros [s  H]. induction H.\n      - reflexivity.\n      - reflexivity.\n      - simpl. apply andb_true_iff. split.\n          * apply IHexp_match1.\n          * apply IHexp_match2.\n      - simpl. apply orb_true_iff. left. apply IHexp_match.\n      - simpl. apply orb_true_iff. right. apply IHexp_match.\n      - simpl. reflexivity.\n      - reflexivity.\n (* <- *)\n + induction re.\n     - simpl. intros Hc. inversion Hc.\n     - simpl. intros _.  exists []. apply MEmpty.\n     - intros. exists [t]. apply MChar.\n     - simpl. rewrite andb_true_iff. intros [H1 H2]. \n       apply IHre1 in H1. apply IHre2 in H2.\n       destruct H1 as [x1 H1]. destruct H2 as [x2 H2].\n       exists (x1 ++ x2). apply (MApp x1 re1 x2 re2 H1 H2).\n     - simpl. rewrite orb_true_iff. intros [H1 | H2].\n         * apply IHre1 in H1. destruct H1 as [s1 H1].\n           exists s1. apply (MUnionL s1 re1 _ H1).\n         * apply IHre2 in H2. destruct H2 as [s2 H2].\n           exists s2. apply (MUnionR re1 s2 re2 H2).\n     - simpl. intros _. exists []. apply MStar0.\nQed.       \n\n\n(**  Text missing... (And: I'm not sure how much of this you (AAA)\n   envision being presented in class, and how much is exercises...) \n *)\n(**  AAA: This exercise is using remember... Maybe we can add an\n    explanation about it earlier? \n *)\n(**  Yes, it is needed in the rest of the book, and I think it's\n   not explained anyplace right now!  I think it belongs with the\n   explanation of generalize dependent in Tactics.v. \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  remember (Star re) as re'.\n  generalize dependent s2.\n  induction H1\n    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2\n        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH\n        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)    inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n  - (* MStar0 *)\n    inversion Heqre'. intros s H. apply H.\n  - (* MStarApp *)\n    inversion Heqre'. rewrite H0 in IH2, Hmatch1.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * reflexivity.\n      * apply H1.\nQed.\n\n(**  Here starts the pumping lemma! \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\nFixpoint pumping_constant {T} (re : reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 => pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 => pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\nRequire Coq.omega.Omega.\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.\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  - (* MChar *)\n    simpl. omega.\n  - (* MApp *)\n    simpl. intros Hlen.\n    assert (H : pumping_constant re1 <= length s1 \\/\n                pumping_constant re2 <= length s2).\n    { rewrite app_length in Hlen. omega. }\n    destruct H as [H | H].\n    + destruct (IH1 H) as [s11 [s12 [s13 [H1 [H2 H3]]]]].\n      rewrite H1.\n      exists s11. exists s12. exists (s13 ++ s2).\n      rewrite <- app_assoc, <- app_assoc.\n      split. { reflexivity. }\n      split. { apply H2. }\n      intros m.\n      rewrite app_assoc, app_assoc. apply MApp.\n      * rewrite <- app_assoc. apply H3.\n      * apply Hmatch2.\n    + destruct (IH2 H) as [s21 [s22 [s23 [H1 [H2 H3]]]]].\n      rewrite H1.\n      exists (s1 ++ s21). exists s22. exists s23.\n      rewrite <- app_assoc. split. { reflexivity. }\n      split. { apply H2. }\n      intros m.\n      rewrite <- app_assoc. apply MApp.\n      * apply Hmatch1.\n      * apply H3.\n  - (* MUnionL *)\n    simpl. intros Hlen.\n    assert (H : pumping_constant re1 <= length s1) by omega.\n    destruct (IH H) as [s11 [s12 [s13 [H1 [H2 H3]]]]].\n    exists s11. exists s12. exists s13. split. { apply H1. }\n    split. { apply H2. }\n    intros m. apply MUnionL. apply H3.\n  - (* MUnionR *)\n    simpl. intros Hlen.\n    assert (H : pumping_constant re2 <= length s2) by omega.\n    destruct (IH H) as [s21 [s22 [s23 [H1 [H2 H3]]]]].\n    exists s21. exists s22. exists s23. split. { apply H1. }\n    split. { apply H2. }\n    intros m. apply MUnionR. apply H3.\n  - (* MStar0 *)\n    simpl. omega.\n  - (* MStarApp *)\n    simpl. intros Hlen.\n    exists []. exists (s1 ++ s2). exists [].\n    simpl. rewrite app_nil_r. split. { reflexivity. }\n    split.\n    { destruct (s1 ++ s2).\n      - simpl in Hlen. omega.\n      - intros contra. inversion contra. }\n    intros m.\n    rewrite app_nil_r.\n    induction m as [|m IHm].\n    + simpl. apply MStar0.\n    + simpl. apply star_app.\n      * apply (MStarApp _ _ _ Hmatch1 Hmatch2).\n      * apply IHm.\nQed.\n\n(* ####################################################### *)\n(** * Applications and Variations *)\n\n(**  The difficulty with naming this section is probably a signal\n   that the grouping / flow of topics doesn't make sense... \n *)\n(** ** Computational vs. Inductive Definitions *)\n\n(**  Move earlier and compress \n *)\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to _give evidence_ for the property [beautiful] is\n    straightforward. *)\n\n\n(**  This discussion seems kind of homeless, and it's not clear why\n   we're bothering to say it.  Maybe it could be combined with the\n   reflection material? \n *)\n(* ####################################################### *)\n(** ** Propositions about Data Structures *)\n\n(** So far, we have only looked at propositions about natural numbers. However,\n   we can define inductive predicates about any type of data. For example,\n   suppose we would like to characterize lists of _even_ length. We can\n   do that with the following definition.  *)\n\nInductive ev_list {X:Type} : list X -> Prop :=\n  | el_nil : ev_list []\n  | el_cc  : forall x y l, ev_list l -> ev_list (x :: y :: l).\n\n(** Of course, this proposition is equivalent to just saying that the\nlength of the list is even. *)\n\nLemma ev_list__ev_length: forall X (l : list X), ev_list l -> ev (length l).\nProof.\n    intros X l H. induction H.\n    - (* el_nil *) simpl. apply ev_0.\n    - (* el_cc *)  simpl.  apply ev_SS. apply IHev_list.\nQed.\n\n(** However, because evidence for [ev] contains less information than\n    evidence for [ev_list], the converse direction must be stated very\n    carefully. *)\n\nLemma ev_length__ev_list: forall X n,\n  ev n -> forall (l : list X), n = length l -> ev_list l.\nProof.\n  intros X n H.\n  induction H.\n  - (* ev_0 *) intros l H. destruct l.\n    + (* [] *) apply el_nil.\n    + (* x::l *) inversion H.\n  - (* ev_SS *) intros l H2. destruct l as [|x1 [| x2 l]].\n    + (* [] *) inversion H2.\n    + (* [x] *) inversion H2.\n    + (* x :: x0 :: l *) apply el_cc. apply IHev. inversion H2. reflexivity.\nQed.\n\n(**  Move exercises later; delete text above \n *)\n(** **** Exercise: 4 stars, recommended (palindromes)  *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n        c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n\n    - Prove [pal_app_rev] that\n       forall l, pal (l ++ rev l).\n    - Prove [pal_rev] that\n       forall l, pal l -> l = rev l.\n*)\n\n\nInductive pal {X} : list X -> Prop :=\n  | pal_nil  : pal []\n  | pal_one  : forall (x : X), pal [x]\n  | pal_cons : forall (x : X) (l : list X), pal l -> pal ([x] ++ l ++ [x]).\n\n\nLemma list_manip : forall (X : Type) (x : X) (l :  list X),\n  (x::l) ++ rev (x ::l) = [x] ++ (l ++ rev l) ++ [x].                     \nProof.\n  intros X x l.\n  replace (x :: l) with ([x] ++ l).\n   + rewrite rev_app_distr. simpl (rev [x]). apply app_assoc.\n   + reflexivity.\nQed.\n  \n  \nTheorem pal_app_rev : forall (X : Type) (l : list X),\n  pal (l ++ rev l).                        \nProof.\n  intros X l. induction l.\n    - simpl. apply pal_nil.\n    - rewrite list_manip. apply (pal_cons x (l ++ rev l) IHl).\nQed.\n      \n  \nTheorem pal_rev : forall (X: Type) (l : list X),\n  pal l -> l = rev l.\nProof.\n  intros X l H. induction H.\n    + reflexivity.\n    + reflexivity.\n    + rewrite rev_app_distr. rewrite rev_app_distr. simpl.\n      rewrite <- IHpal. reflexivity.\nQed.\n\n\n(* Again, the converse direction is much more difficult, due to the\nlack of evidence. *)\n\n(** **** Exercise: 5 stars, optional (palindrome_converse)  *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n\n\nTheorem palindrome_converse : forall (X : Type) (l : list X),\n  l = rev l -> pal l.                \nProof.\n  intros X l H. induction l as [|x1 l'].\n    + apply pal_nil.\n\n *) (* maybedo: finish this one *)\n\n(*  induction l as [|x1 [| x2 l]].\n    + apply pal_nil.\n    + apply pal_one.\n    + \n*)\n\nCheck (nat_rect).\nCheck (list_rect).\n\n(*\nConsider:\n\nproving this first:\n\n  forall X P, (P []) -> (forall x l, P (rev l) -> P (rev (x :: l))) -> forall l, P (rev l)\"\n\nthen prove this:\nlist_rect_pal := forall (X : Type) (P : list X -> Type),\n       P [] -> forall (x : X), P [x] ->\n       (forall (x1 x2 : X) (l : list X), P l -> P ([x1] ++ l ++ [x2])) ->\n       forall l : list X, P l\n\nList_rect : forall P: forall A:Type, List A -> Type,\n            (forall A:Type, P A (nil A)) ->\n            (forall (A:Type) (a:A)(l:List A), P A l -> P A (cons A a l)) ->\n            forall (A:Type)(l:List A), P A l\n*) \n\n\n(* ####################################################### *)\n(** * Inductive Relations *)\n\n(**  bcp: belongs before regexps \n *)\n(** A proposition parameterized by a number (such as [ev] or\n    [beautiful]) can be thought of as a _property_ -- i.e., it defines\n    a subset of [nat], namely those numbers for which the proposition\n    is provable.  In the same way, a two-argument proposition can be\n    thought of as a _relation_ -- i.e., it defines a set of pairs for\n    which the proposition is provable. *)\n\nModule LeModule.\n\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] in chapter [Prop].  We can [apply] the constructors to prove [<=]\n    goals (e.g., to show that [3<=3] or [3<=6]), and we can use\n    tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [(2 <= 1) -> 2+2=5].) *)\n\n(** Here are some sanity checks on the definition.  (Notice that,\n    although these are the same kind of simple \"unit tests\" as we gave\n    for the testing functions we wrote in the first few lectures, we\n    must construct their proofs explicitly -- [simpl] and\n    [reflexivity] don't do the job, because the proofs aren't just a\n    matter of simplifying computations.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* WORKED IN CLASS *)\n  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.\n\nTheorem test_le3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : 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, recommended (total_relation)  *)\n(** Define an inductive binary relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\n\nInductive total_relation : nat -> nat -> Prop :=\n  tot : forall (n m : nat), total_relation n m.\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation : nat -> nat -> Prop :=.\n\n\n(** **** Exercise: 2 stars, optional (le_exercises)  *)\n(** Here are a number of facts about the [<=] and [<] relations that\n    we are going to need later in the course.  The proofs make good\n    practice exercises. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H1 H2.\n  rewrite H1. apply H2.\nQed.  \n\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n. induction n.\n    - apply le_n.\n    - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H1. 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. generalize dependent n. induction m.\n    + intros n H. inversion H.\n        -  reflexivity.\n        - subst. inversion H1.\n    + intros n H. apply le_S. apply IHm. admit. (*maybedo: finish this up*)\nQed.      \n\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b. induction b.\n    + rewrite plus_comm. reflexivity.\n    + rewrite plus_comm. simpl. rewrite plus_comm.\n      apply le_S. apply IHb.\nQed.\n\nLemma ss_lt : forall n m, S (S n) <= m -> S n <= m.\nProof.\n  intros n m H. induction H.\n    + apply le_S. reflexivity.\n    + apply le_S. apply IHle.\nQed.  \n      \n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt. split.\n  (* LHS *)\n  + induction n2.\n      - rewrite plus_comm in H. simpl in H. apply H.\n      - apply IHn2. rewrite plus_comm in H. simpl in H.\n       rewrite plus_comm in H. apply (ss_lt (n1 + n2) m). apply H.\n\n  (* RHS *)\n  + induction n1.\n      - apply H.\n      - apply IHn1. simpl in H. apply (ss_lt (n1+n2) _). apply H.\nQed.\n       \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  leb n m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  (* Hint: This may be easiest to prove by induction on [m]. *)\n  (* FILL IN HERE *) Admitted.\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  (* Hint: This theorem can be easily proved without using [induction]. *)\n  (* FILL IN HERE *) Admitted.\n\n(** **** Exercise: 2 stars, optional (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_provability2)  *)\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(*\n   todo: confirm this in class\n*)\n(** (a) Which of the following propositions are provable?\n      - [R 1 1 2]\n      - [R 2 2 6]\n\n    (b) 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    (c) 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  (a)\n     [R 1 1 2] provable.\n     Proof by constructing a reduction.\n     By [c4] [c 1 1 2] becomes [c 0 0 0] where\n     [S m = 1], [S n = 1], and [S S o = 2]. Then apply c1.\n\n     [R 2 2 6] not provable.\n\n     There does not exist a series of applications of [c_n] so that\n     [R 2 2 6] reduces to [R 0 0 0]. Note it requires at most\n     6 moves to reduce 6 to 0 by iterative application of c2 or c3,\n     and at least 3 moves to reduce 6 to 0 by application of c4.\n     However, it takes at least 2 moves and at most 3 moves to\n     reduce either [m] or [n] to 0 by applications of c2, c3 and c5.\n     After 3 moves, one of m or n will be 0 while the other one is not,\n     so we have [R 0 n 0] or [R m 0 0] where m,n /= 0, which is not provable.\n\n\n   (b)\n      [R 1 1 2] still provable. Our reduction above does not use c5.\n      [R 2 2 6] still not provable. It now takes at most 2 moves to reduce\n      either m or n to 0 while the other two values are not 0.\n\n   (c)\n      [R 1 1 2] still provable. proof by constructing reduction:\n\n       R 1 1 2 ===> R 0 1 1    by c2\n               ===> R 1 0 1    by c5\n               ===> R 0 0 0    by c2, now use c1.\n\n      [R 2 2 6] would certainly not be provable since it now requires\n      at least 6 moves to reduce 6 to 0.\n      \n*)\n[]\n\n\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact)  *)\n(** Relation [R] actually encodes a familiar function.  State and prove two\n    theorems that formally connects the relation and the function.\n    That is, if [R m n o] is true, what can we say about [m],\n    [n], and [o], and vice versa?\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 4 stars, advanced (subsequence)  *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1;2;3]\n    is a subsequence of each of the lists\n    [1;2;3]\n    [1;1;1;2;2;3]\n    [1;2;7;3]\n    [5;6;1;9;9;2;7;3;8]\n    but it is _not_ a subsequence of any of the lists\n    [1;2]\n    [1;3]\n    [5;6;2;1;7;3;8]\n\n\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\n(* boolean definition\nFixpoint b_subseq (l1 l2 : list nat) : bool := match l1,l2 with\n  | []     , _        => true\n  | _      , []       => false\n  | x::l1' , y::l2'   => if beq_nat x y then b_subseq l1' l2' else b_subseq l1 l2'           \n  end.               \n\n(* adhoc test boolean definition *)\nDefinition l1 := [1;2;3].\nCompute (b_subseq l1 l1).\nCompute (b_subseq l1 [1;1;1;2;2;3]).\nCompute (b_subseq l1 [1;2;7;3]).\nCompute (b_subseq l1 [1;2]).\nCompute (b_subseq l1 [1;3]).\nCompute (b_subseq l1 [5;6;2;1;7;3;8]).\n *)\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | lft_nil : forall l, subseq [] l\n  | x_eq_y  : forall l1 l2 (x y : nat),\n              subseq l1 l2 -> x = y -> subseq (x :: l1) (y :: l2)\n  | x_neq_y : forall l1 l2 (x y : nat),\n              subseq (x :: l1) l2 -> x <> y -> subseq (x :: l1) (y :: l2).\n\n\n\nNotation \"l1 <: l2\" := (subseq l1 l2) (at level 80).\n\nTheorem subseq_refl : forall (l : list nat),\n   l <: l.\nProof.\n  intros l. induction l.\n    + apply lft_nil.\n    + apply x_eq_y. apply IHl. reflexivity.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  l1 <: l2 -> l1 <: (l2 ++ l3).\nProof.  \n  intros l1 l2 l3 H. induction H.\n    + apply lft_nil.\n    + subst. simpl. apply x_eq_y.  apply IHsubseq. reflexivity.\n    + simpl. apply x_neq_y. apply IHsubseq. apply H0.\nQed.\n\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*)\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  l1 <: l2 -> l2 <: l3 -> l1 <: l3.\nProof. Admitted.\n(*\n  intros l1 l2 l3 H1. induction H1.\n    + intros _. apply lft_nil.\n    + intros H2. subst. inversion H2. subst.\n        - apply x_eq_y. admit.\n          \n maybedo : finish this one *)\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability)  *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1;0]]\n    - [R 1 [1;2;1;0]]\n    - [R 6 [3;2;1;0]]\n*)\n\n(** [] *)\n\n\n(* ####################################################### *)\n(** * Improving Reflection *)\n\n(**  AAA: Reflection is more general than just using [reflect]. We\n   should explain the term in the previous chapter, when discussing\n   [bool] vs. [Prop], and make it clear here that we are just\n   developing infrastructure to make it more conveninent. \n *)\n(** We've seen in the previous chapter that it is often\n    necessary to relate boolean computations to statements in\n    [Prop]. Unfortunately, performing this conversion by hand can\n    result in tedious proof scripts. Consider the proof of the\n    following 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 of the [destruct], we must explicitly\n    apply 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], which is what we need to\n    complete this case.\n\n    We can streamline this proof by defining an inductive proposition\n    that yields a better case-analysis principle for [beq_nat n\n    m]. Instead of generating an equation such as [beq_nat n m =\n    true], which is not directly useful, this principle gives us right\n    away the assumption we need: [n = m]. We'll actually define\n    something a bit more general, which can be used with arbitrary\n    properties (and not just equalities): *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\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]: [P]\n    holds if and only if [b = true]. To see this, notice that, by\n    definition, the only way we can produce evidence that [reflect P\n    true] holds is by showing that [P] is true and using the\n    [ReflectT] constructor. If we invert this statement, this means\n    that it should be possible to extract evidence for [P] from a\n    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  intros P [] H.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. unfold not. 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  intros P b H. split.\n  (* -> *)\n  + inversion H. subst.\n      - intros _. reflexivity.\n      - subst. intros p. exfalso. apply H0. apply p.\n  (* <- *)\n  + inversion H. subst.\n      - intros _. apply H0.\n      - intros Hc. inversion Hc.\nQed.        \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    To use [reflect] to produce a better proof of\n    [filter_not_empty_In], we begin by recasting the\n    [beq_nat_iff_true] lemma into a more convenient form in terms of\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(** The new proof of [filter_not_empty_In] is now as\n    follows. Notice how the calls to [destruct] and [apply] are\n    combined into a single call to [destruct].  (To see this clearly,\n    look at the two proofs of [filter_not_empty_In] in your Coq\n    browser and observe the differences in proof state at the\n    beginning of the first case of the [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(** Although this arguably represents only a small gain in\n    convenience for this particular proof, using [reflect]\n    consistently often leads to shorter and clearer proofs. We'll see many\n    more examples where [reflect] comes in handy in later chapters.\n\n    Last, a historical note. The use of the [reflect] property was\n    popularized by _SSReflect_, a Coq library that has been used to\n    formalize important results in mathematics, such as the 4-color\n    theorem or the Feit-Thompson theorem. The name 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(**  These are dumped here from the old MoreLogic.  Need editing... \n *)\n(** **** Exercise: 4 stars, advanced (filter_challenge)  *)\n(** One of the main purposes of Coq is to prove that programs match\n    their specifications.  To this end, let's prove that our\n    definition of [filter] matches a specification.  Here is the\n    specification, written out informally in English.\n\n    Suppose we have a set [X], a function [test: X->bool], and a list\n    [l] of type [list X].  Suppose further that [l] is an \"in-order\n    merge\" of two lists, [l1] and [l2], such that every item in [l1]\n    satisfies [test] and no item in [l2] satisfies test.  Then [filter\n    test l = l1].\n\n    A list [l] is an \"in-order merge\" of [l1] and [l2] if it contains\n    all the same elements as [l1] and [l2], in the same order as [l1]\n    and [l2], but possibly interleaved.  For example,\n    [1;4;6;2;3]\n    is an in-order merge of\n    [1;6;2]\n    and\n    [4;3].\n    Your job is to translate this specification into a Coq theorem and\n    prove it.  (Hint: You'll need to begin by defining what it means\n    for one list to be a merge of two others.  Do this with an\n    inductive relation, not a [Fixpoint].)  *)\n\n\nCompute (filter evenb [2;4;6]).\n\n\nInductive in_order_merge {X : Type} : list X -> list X -> list X -> Prop :=\n  | nils   :                            in_order_merge [] [] []\n  | icons1 : forall l1 l2 l (x : X),\n             in_order_merge l1 l2 l  -> in_order_merge (x :: l1) l2 (x :: l)\n  | icons2 : forall l1 l2 l (x : X),\n             in_order_merge l1 l2 l  -> in_order_merge l1 (x :: l2) (x :: l).\n\n\nLemma filter_len1 : forall (X : Type) (p : X -> bool) (l : list X),\n  length (filter p l ) <= length l.\nProof.\n  intros. induction l as [|x l'].\n    + simpl. reflexivity.\n    + simpl. destruct (p x).\n        (* le_n_S: forall n m : nat, n <= m -> S n <= S m *)\n        - simpl. apply le_n_S in IHl'. apply IHl'.\n        - rewrite IHl'. apply le_n_Sn.\nQed.\n\nLemma duh : forall (n : nat), S n <= n -> False.\nProof.\n  intros. induction n.\n    - inversion H.\n    - apply IHn. apply le_S_n in H. apply H.\nQed.\n      \nLemma filter_len : forall (X : Type) (test : X -> bool) (l : list X) (x : X),\n  filter test l = x :: l -> False.\nProof.\n  intros. assert (length (filter test l) <= length l).\n    + apply filter_len1.\n    + rewrite H in H0. simpl in H0. apply duh in H0.\n      inversion H0.\nQed.      \n\nLemma filter_cons: forall (X : Type) (test : X -> bool) (l : list X) (x : X),\n  filter test (x :: l) = x :: l -> filter test l = l.\nProof. \n  intros X test l x. simpl. destruct (test x) eqn : Hx.\n    + intros H. inversion H. rewrite H1.  apply H1.\n    + intros H.  apply filter_len in H. inversion H.\nQed.\n\nLemma filter_hd_false:  forall (X : Type) (test : X -> bool) (l : list X) (x : X),\n  filter test (x :: l) = []-> test x = false /\\ filter test l = [].\nProof. \n  intros X p l x. simpl. destruct (p x) eqn: Hx. intros H. split.\n    - inversion H.\n    - inversion H.\n    - intros H. split.\n        + reflexivity.\n        + apply H.\nQed.       \n\nTheorem filter_spec : forall (X : Type) (test : X -> bool) (l l1 l2 : list X),\n  in_order_merge l1 l2 l -> filter test l1 = l1 -> filter test l2 = [] ->\n  filter test l = l1.\nProof.\n  intros X test l l1 l2 Hm Hl1 Hl2. induction Hm.\n    (* case: l1 = l2 = l3 = [] *)\n    + reflexivity.\n    (* case : head in l1 is also the head in l*)\n    + simpl. destruct (test x) eqn: Hx.\n        (* case: head in l1 passes the test   <- must be true  by Hl1 *)\n        - apply f_equal. apply IHHm.\n          apply filter_cons in Hl1. apply Hl1.\n          apply Hl2.\n        (* case: head in l1 not pass the test <- must be false by Hl1 *)\n        - rewrite <- Hl1. simpl. destruct (test x).\n            * inversion Hx.\n            * apply filter_cons in Hl1. rewrite Hl1. apply IHHm.\n              apply Hl1.\n              apply Hl2.\n   (* case: head in l2 is also head in l <- must be false by Hl2 *)           \n   + apply filter_hd_false in Hl2. destruct Hl2 as [Hl2l Hl2r]. simpl.\n     destruct (test x) eqn: Hx.\n       - inversion Hl2l.\n       - apply IHHm.\n         apply Hl1.\n         apply Hl2r.\nQed.\n\n\n(*\n\nProof.\n  intros X test l. induction l as [|x' l'].\n    + intros. inversion H. reflexivity.\n    + intros. inversion H. subst.\n      (* case in_order_merge l1 l2 l -> in_order_merge (x :: l1) l2 (x :: l)\n         note : coq named the l1 in (x :: l1) l0.\n       *)\n        - simpl in H0. simpl. destruct (test x').\n            * rewrite (IHl' l0 l2).\n              reflexivity.\n              apply H5. inversion H0. rewrite H3. rewrite H3. reflexivity.\n              apply H1.\n            * apply filter_len in H0. inversion H0.\n      (* case in_order_merge l1 l2 l -> in_order_merge l1 (x :: l2) (x :: l)\n         note : coq named the l2 in (x :: l2) l3.\n         but this can't be the case since filter test l2 = [], so no x in\n         l2 may appear in l.\n      *)\n        - simpl. destruct (test x').\n            * \nQed.\n\n\n*)\n  \n\n\n(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2)  *)\n(** A different way to formally characterize the behavior of [filter]\n    goes like this: Among all subsequences of [l] with the property\n    that [test] evaluates to [true] on all their members, [filter test\n    l] is the longest.  Express this claim formally and prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (NoDup)  *)\n(** Recall the definition of the [In] property of the [Logic] chapter,\n    which asserts that a value [x] appears at least once in a list\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(** 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\n(* todo: is this def repetitive? is dnils needed? *)\nInductive disjoint {X : Type} : list X -> list X -> Prop :=\n  | dnils  :                                                 disjoint [] [] \n  | dnil1  : forall l1,                                      disjoint l1 []\n  | dnil2  : forall l2,                                      disjoint [] l2\n  | dcons  : forall l1 l2 (x : X), In x l1 -> ~ (In x l2) -> disjoint l1 l2.\n\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\nInductive NoDup {X : Type} : list X -> Prop :=\n  | nnils :                                     NoDup []\n  | ncons : forall l (x : X), disjoint [x] l -> NoDup (x::l).                 \n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\nTheorem absolutely_fascinating :\n  forall (X: Type) (l1 l2 l3 : list X),\n  NoDup l1 -> exists l2 l3, l1 = l2 ++ l3 -> disjoint l2 l3.\nProof.\n  intros. induction H.\n    (* l1 is [] *)\n    + exists []. exists []. intros _. apply dnils.\n    (* l1 is some x :: l1' *)\n    + exists [x]. exists l. intros _. apply H.\nQed.    \n\n\n(*\n\nFixpoint b_disjoint (l1 l2 : list nat) : bool := match l1, l2 with\n  | x :: xs, y :: ys => negb (beq_nat x y) && (b_disjoint xs ys)\n  | _      , _       => true\n  end.\n*)\n\n(** **** Exercise: 3 stars, recommended (nostutter)  *)\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.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n  | snils  :                 nostutter []\n  | sone   : forall (x : X), nostutter [x]\n  | scons  : forall (l : list X) (x y : X),\n             x <> y -> nostutter (y::l) -> nostutter (x::y::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\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  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n\n\nExample test_nostutter_2:  nostutter (@nil nat).\n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  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]).\nProof.\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, advanced (pigeonhole principle)  *)\n(** The \"pigeonhole principle\" states a basic fact about counting:\n   if you distribute more than [n] items into [n] pigeonholes, some\n   pigeonhole must contain at least two items.  As is often the case,\n   this apparently trivial fact about numbers requires non-trivial\n   machinery to prove, but we now have enough... *)\n  \n\n(** First a useful lemma (we already proved it for lists of naturals,\n    but not for arbitrary lists). *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  intros. induction l as [|a l'].\n    + inversion H.\n    + inversion H.  (* In x (a :: l') -> x = a \\/ In x l' *)\n        (* case x = a *)\n        - subst. exists []. exists l'. simpl. reflexivity.\n        (* case In x l' *)\n        - apply IHl' in H0. destruct H0. destruct H0.\n          exists (a :: x0). exists x1. rewrite H0.\n          reflexivity.\nQed.\n\n(*\nNow define a property repeats such that repeats X l asserts\nthat l contains at least one repeated element (of type X).\n*)\nInductive repeats {X:Type} : list X -> Prop :=\n  | rconst : forall (l : list X) (x : X),\n            In x l -> repeats (x :: l)\n  | rconsf : forall (l : list X) (x : X),\n            repeats l -> repeats (x :: l).\n\n\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n    represents a list of pigeonhole labels, and list [l1] represents\n    the labels assigned to a list of items: if there are more items\n    than labels, at least two items must have the same label.  This\n    proof is much easier if you use the [excluded_middle] hypothesis\n    to show that [In] is decidable, i.e.\n\n         [forall x l, (In x l) \\/ ~  (In x l)].\n\n         [ Definition excluded_middle := ∀P : Prop, P ∨ ¬ P].\n\n    However, it is also possible to make the proof go\n    through _without_ assuming that [In] is decidable; if you can\n    manage to do this, you will not need the [excluded_middle]\n    hypothesis. *)\n\n(*\nTheorem l2_le_l1 : forall (X: Type) (l1 l21 l22 : list X) (x : X),\n  length l2 < length (x :: l1)   ->\n   In x l2                       ->\n   l2 = l21 ++ x :: l22          ->\n   length (l21 ++ l22)  < length l1.\nProof. Admitted.\n*)\n\n\n\nTheorem inx : forall (X : Type) (l1 l2 : list X) (x : X), In x (l1 ++ x :: l2).\nProof.\n  intros. induction l1.\n    - simpl. left. reflexivity.\n    - simpl. right. apply IHl1.\nQed. \n\n\nTheorem inx0 : forall (X : Type) (l1' : list X) (x0 x : X),\n  In x0 l1' ->  In x0 (x:: l1'). \nProof.\n  intros. simpl. right. apply H.\nQed.\n\n\nTheorem inx0_l2 : forall (X : Type) (l21 l22 : list X) (x0 x : X),\n  x0 <> x -> In x0 (l21 ++ x :: l22) -> In x0 (l21 ++ l22).\nProof.\n  intros. induction l21.\n    + simpl. simpl in H0. destruct H0.\n        - exfalso. apply H. symmetry. apply H0.\n        - apply H0.\n    + simpl. right. apply IHl21. simpl in H0. destruct H0.\n        - admit.\n        - apply H0.\nQed.\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'].\n\n   (* case l1 = [], contradicts hypo *)\n   - intros. inversion H1. \n\n   (* case l1 = x :: l1', x is either repeating in l1' or it's not *)\n   - intros. destruct (H (In x l1')).\n      (* x is repeated in l1', then goal is true by assumption *) \n      + apply rconst. apply H2.\n      (* x is not repeated in l1', *)\n      + apply rconsf. \n\n        (* it can be shown that x is in l2 *)\n        assert (In x l2).\n          apply (H0 x). simpl. left. reflexivity.\n\n        (* since x in l2, we know l2 = l21 ++ [x] ++ l22 *)\n        destruct (in_split X x l2 H3) as [l21 [l22 Hl2x]].\n        apply (IHl1' (l21 ++ l22)). apply H. intros x0 H_x0.\n        \n        assert (x0 <> x). unfold not. intros H_x0x. apply in_split in H_x0.\n        inversion H_x0. inversion H4. rewrite H_x0x in H5.\n        rewrite H5 in H2. apply H2. apply inx. \n\n        assert (H5 : In x0 (x :: l1')). apply inx0. apply H_x0.\n\n        apply H0 in H5. rewrite Hl2x in H5.\n\n        assert (H6 : x0 <> x -> In x0 (l21 ++ x :: l22) -> In x0 (l21 ++ l22)).\n        admit.\n        \n\n        apply H6. apply H4. apply H5.\n\n        assert (H7 : length (x :: l1') = S (length l1')). admit.\n        assert (H8 : length (l21 ++ x :: l22) = S (length (l21 ++ l22))). admit.\n\n        rewrite <- Hl2x in H8. rewrite H8 in H1.\n        rewrite H7 in H1.\n\n        assert (H9 : forall n m : nat, S m < S n -> m < n). admit.\n\n        apply H9 in H1. apply H1.\nQed.\n\n        \n(*\n\nFixpoint inl  (x : nat) (l : list nat) : bool := match l with\n  | []      => false\n  | y :: l' => if beq_nat x y then true else inl x l'\n  end.                                               \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\nFixpoint repeats (l : list nat) : bool := match l with\n  | []       => false\n  | x :: l'  => if inl x l' then true else repeats l'\n  end.\n\n*)       \n\n\n\n(* FILL IN HERE *\n\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *no)\n\n\n", "meta": {"author": "lingxiao", "repo": "CIS500", "sha": "5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a", "save_path": "github-repos/coq/lingxiao-CIS500", "path": "github-repos/coq/lingxiao-CIS500/CIS500-5b6e3a9cfe1ecaeaa9112b350022f3ca84924d4a/hw5/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8688267881258483, "lm_q1q2_score": 0.7609072103028992}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\nRequire Import FunctionalExtensionality.\nRequire Import Sorting.\nRequire Import Permutation.\nImport Nat.\n\nRequire Export list_util.\n\n\n\n(* ===== Polynomial Representation - Data Types ===== *)\n(** * Monomials and Polynomials *)\n\n(** ** Data Type Definitions *)\n\n(** Now that we have defined those functions over lists and proven all of those\n    facts about them, we can begin to apply all of them to our specific project\n    of unification. The first step is to define the data structures we plan on\n    using.\n\n    As mentioned earlier, because of the ten axioms that hold true during\n    [B]-unification, we can represent all possible terms with lists of lists of\n    numbers. The numbers represent variables, and a list of variables is a\n    monomial, where each variable is multiplied together. A polynomial, then, is\n    a list of monomials where each monomial is added together.\n\n    In this representation, the term [0] is represented as the empty polynomial,\n    and the term [1] is represented as the polynomial containing only the empty\n    monomial.\n\n    In addition to the definitions of [var], [mono], and [poly], we also have\n    definitions for [var_eq_dec] amd [mono_eq_dec]; these are a proofs of\n    decidability of varailes and monomials respectively. They make use of a\n    special Coq data structure that allows them to be used as a comparison\n    function - for example, we can [destruct (mono_eq_dec a b)] to compare the\n    two cases where [a = b] and $a \\neq b$. In addition to being useful in some\n    proofs, this is also needed by some functions, such as [remove] and\n    [count_occ], since they compare variables and monomials. *)\n\nDefinition var := nat.\n\nDefinition var_eq_dec := Nat.eq_dec.\n\nDefinition mono := list var.\n\nDefinition mono_eq_dec := (list_eq_dec Nat.eq_dec).\n\nDefinition poly := list mono.\n\n(** ** Comparisons of monomials and polynomials *)\n\n(** In order to easily compare monomials, we make use of the [lex] function we\n    defined at the beginning of the [list_util] file. For convenience, we also\n    define [mono_lt], which is a proposition that states that some monomial is\n    less than another. *)\n\nDefinition mono_cmp := lex compare.\n\nDefinition mono_lt m n := mono_cmp m n = Lt.\n\n(** A simple but useful definition is [vars], which allows us to take any\n    polynomial and get a list of all the variables in it. This is simply done\n    by concatenating all of the monomials into one large list of variables and\n    removing any repeated variables.\n\n    Clearly then, there will never be any duplicates in the [vars] of some\n    polynomial. *)\n\nDefinition vars (p : poly) : list var := nodup var_eq_dec (concat p).\n\nHint Unfold vars.\n\nLemma NoDup_vars : forall (p : poly),\n  NoDup (vars p).\nProof.\n  intros p. unfold vars. apply NoDup_nodup.\nQed.\n\n(** This next lemma allows us to convert from a statement about [vars] to a\n    statement about the monomials themselves. If some variable [x] is not in the\n    variables of a polynomial [p], then every monomial in [p] must not contain\n    [x]. *)\n\nLemma in_mono_in_vars : forall x p,\n  (forall m : mono, In m p -> ~ In x m) <-> ~ In x (vars p).\nProof.\n  intros x p. split.\n  - intros H. induction p.\n    + simpl. auto.\n    + unfold not in *. intro. apply IHp.\n      * intros m Hin. apply H. intuition.\n      * unfold vars in *. apply nodup_In in H0. apply nodup_In. simpl in H0.\n        apply in_app_or in H0. destruct H0.\n        -- exfalso. apply (H a). intuition. auto.\n        -- auto.\n  - intros H m Hin Hin'. apply H. clear H. induction p.\n    + inversion Hin.\n    + unfold vars in *. rewrite nodup_In. rewrite nodup_In in IHp. simpl.\n      apply in_or_app. destruct Hin.\n      * left. rewrite H. auto.\n      * auto.\nQed.\n\n\n(** ** Stronger Definitions *)\n\n(** Because, as far as Coq is concerned, any list of natural numbers is a\n    monomial, it is necessary to define a few more predicates about monomials\n    and polynomials to ensure our desired properties hold. Using these in proofs\n    will prevent any random list from being used as a monomial or polynomial.\n\n    Monomials are simply lists of natural numbers that, for ease of comparison,\n    are sorted least to greatest. A small sublety is that we are insisting they\n    are sorted with [lt], meaning less than, rather than [le], or less than or\n    equal to. This way, the [Sorted] predicate will insist that each number is\n    _less than_ the one following it, thereby preventing any values from being\n    equal to each other. In this way, we simultaneously enforce the sorting and\n    lack of duplicated values in a monomial. *)\n\nDefinition is_mono (m : mono) : Prop := Sorted lt m.\n\n(** Polynomials are sorted lists of lists, where all of the lists in the\n    polynomial are monomials. Similarly to the last example, we use [mono_lt]\n    to simultaneously enforce sorting and no duplicates. *)\n\nDefinition is_poly (p : poly) : Prop :=\n  Sorted mono_lt p /\\ forall m, In m p -> is_mono m.\n\nHint Unfold is_mono is_poly.\nHint Resolve NoDup_cons NoDup_nil Sorted_cons.\n\n(** There are a few useful things we can prove about these definitions too.\n    First, because of the sorting, every element in a monomial is guaranteed to\n    be less than the element after it. *)\n\nLemma mono_order : forall x y m,\n  is_mono (x :: y :: m) ->\n  x < y.\nProof.\n  unfold is_mono.\n  intros x y m H.\n  apply Sorted_inv in H as [].\n  apply HdRel_inv in H0.\n  apply H0.\nQed.\n\n(** Similarly, if [x :: m] is a monomial, then [m] is also a monomial. *)\n\nLemma mono_cons : forall x m,\n  is_mono (x :: m) ->\n  is_mono m.\nProof.\n  unfold is_mono.\n  intros x m H. apply Sorted_inv in H as []. apply H.\nQed.\n\n(** The same properties hold for [is_poly] as well; any list in a polynomial is\n    guaranteed to be less than the lists after it, and if [m :: p] is a\n    polynomial, we know both that [p] is a polynomial and that [m] is a\n    monomial. *)\n\nLemma poly_order : forall m n p,\n  is_poly (m :: n :: p) ->\n  mono_lt m n.\nProof.\n  unfold is_poly.\n  intros.\n  destruct H.\n  apply Sorted_inv in H as [].\n  apply HdRel_inv in H1.\n  apply H1.\nQed.\n\nLemma poly_cons : forall m p,\n  is_poly (m :: p) ->\n  is_poly p /\\ is_mono m.\nProof.\n  unfold is_poly.\n  intros.\n  destruct H.\n  apply Sorted_inv in H as [].\n  split.\n  - split; auto.\n    intros. apply H0, in_cons, H2.\n  - apply H0, in_eq.\nQed.\n\n(** Lastly, for completeness, nil is both a polynomial and monomial, the\n    polynomial representation for one as we described before is a polynomial,\n    and a singleton variable is a polynomial. *)\n\nLemma nil_is_mono :\n  is_mono [].\nProof.\n  unfold is_mono. auto.\nQed.\n\nLemma nil_is_poly :\n  is_poly [].\nProof.\n  unfold is_poly. split; auto.\n  intro; contradiction.\nQed.\n\nLemma one_is_poly :\n  is_poly [[]].\nProof.\n  unfold is_poly. split; auto.\n  intro. intro. simpl in H. destruct H.\n  - rewrite <- H. apply nil_is_mono.\n  - inversion H.\nQed.\n\nLemma var_is_poly : forall x,\n  is_poly [[x]].\nProof.\n  intros x. unfold is_poly. split.\n  - apply Sorted_cons; auto.\n  - intros m H. simpl in H; destruct H; inversion H.\n    unfold is_mono. auto.\nQed.\n\n(** In unification, a common concept is a _ground term_, or a term that contains\n    no variables. If some polynomial is a ground term, then it must either be\n    equal to 0 or 1. *)\n\nLemma no_vars_is_ground : forall p,\n  is_poly p ->\n  vars p = [] ->\n  p = [] \\/ p = [[]].\nProof.\n  intros p H H0. induction p; auto.\n  induction a.\n  - destruct IHp.\n    + apply poly_cons in H. apply H.\n    + unfold vars in H0. simpl in H0. apply H0.\n    + rewrite H1. auto.\n    + rewrite H1 in H. unfold is_poly in H. destruct H. inversion H.\n      inversion H6. inversion H8.\n  - unfold vars in H0. simpl in H0. destruct in_dec in H0.\n    + rewrite <- nodup_In in i. rewrite H0 in i. inversion i.\n    + inversion H0.\nQed.\n\nHint Resolve mono_order mono_cons poly_order poly_cons nil_is_mono nil_is_poly\n  var_is_poly one_is_poly.\n\n\n\n(** * Sorted Lists and Sorting *)\n\n(** Clearly, because we want to maintain that our monomials and polynomials\n    are sorted at all times, we will be dealing with Coq's [Sorted] proposition\n    a lot. In addition, not every list we want to operate on will already be\n    perfectly sorted, so it is often necessary to sort lists ourselves. This\n    next section serves to give us all of the tools necessary to operate on\n    sorted lists. *)\n\n(** ** Sorting Lists *)\n\n(** In order to sort our lists, we will make use of the [Sorting] module in the\n    standard library, which implements a version of merge sort.\n\n    For sorting variables in a monomial, we can simply reuse the already\n    provided [NatSort] module. *)\n\nModule Import VarSort := NatSort.\n\n(** Sorting the monomials in a polynomial is slightly more complicated, but\n    still straightforward thanks to the [Sorting] module. First, we need to\n    define a [MonoOrder], which must be a total less-than-or-equal-to\n    comparator.\n\n    This is accomplished by using our [mono_cmp] defined earlier, and simply\n    returning true for either less than or equal to.\n\n    We also prove a relatively simple lemma about this new [MonoOrder], which\n    states that if [x <= y] and [y <= x], then [x] must be equal to [y]. *)\n\nRequire Import Orders.\n\nModule MonoOrder <: TotalLeBool.\n\n  Definition t := mono.\n\n  Definition leb m n :=\n    match mono_cmp m n with\n    | Lt => true\n    | Eq => true\n    | Gt => false\n    end.\n\n  Infix \"<=m\" := leb (at level 35).\n\n  Lemma leb_total : forall m n, (m <=m n = true) \\/ (n <=m m = true).\n  Proof.\n    intros n m. unfold \"<=m\". destruct (mono_cmp n m) eqn:Hcomp; auto.\n    unfold mono_cmp in *. apply lex_rev_lt_gt in Hcomp. rewrite Hcomp. auto.\n  Qed.\n\nEnd MonoOrder.\n\nLemma leb_both_eq : forall x y,\n  is_true (MonoOrder.leb x y) ->\n  is_true (MonoOrder.leb y x) ->\n  x = y.\nProof.\n  intros x y H H0. unfold is_true, MonoOrder.leb in *.\n  destruct (mono_cmp y x) eqn:Hyx; destruct (mono_cmp x y) eqn:Hxy;\n  unfold mono_cmp in *;\n  try (apply lex_rev_lt_gt in Hxy; rewrite Hxy in Hyx; inversion Hyx);\n  try (apply lex_rev_lt_gt in Hyx; rewrite Hxy in Hyx; inversion Hyx);\n  try inversion H; try inversion H0.\n  apply lex_eq in Hxy; auto.\nQed.\n\n(** After this order has been defined and its totality has been proven, we\n    simply define a new [MonoSort] module to be a sort based on this\n    [MonoOrder].\n\n    Now, we have a simple [sort] function for both monomials and polynomials,\n    as well as a few useful lemmas about the [sort] functions' correctness. *)\n\nModule Import MonoSort := Sort MonoOrder.\n\n(** One technique that helps us deal with the difficulty of sorted lists\n    is proving that each of our four comparators - [lt], [VarOrder], [mono_lt],\n    and [MonoOrder] - are all transitive. This allows us to seamlessly pass\n    between the standard library's [Sorted] and [StronglySorted] propositions,\n    making many proofs significantly easier.\n\n    All four of these are proved relatively easily, mostly by induction and\n    destructing the comparison of the individual values. *)\n\nLemma lt_Transitive :\n  Relations_1.Transitive lt.\nProof.\n  unfold Relations_1.Transitive. intros. apply lt_trans with (m:=y); auto.\nQed.\n\nLemma VarOrder_Transitive :\n  Relations_1.Transitive (fun x y => is_true (NatOrder.leb x y)).\nProof.\n  unfold Relations_1.Transitive, is_true.\n  induction x, y, z; intros; try reflexivity; simpl in *.\n  - inversion H.\n  - inversion H.\n  - inversion H0.\n  - apply IHx with (y:=y); auto.\nQed.\n\nLemma mono_lt_Transitive : Relations_1.Transitive mono_lt.\nProof.\n  unfold Relations_1.Transitive, is_true, mono_lt, mono_cmp.\n  induction x, y, z; intros; try reflexivity; simpl in *.\n  - inversion H.\n  - inversion H0.\n  - inversion H0.\n  - inversion H.\n  - inversion H0.\n  - destruct (a ?= n0) eqn:Han0.\n    + apply compare_eq_iff in Han0. rewrite Han0 in H.\n      destruct (n ?= n0) eqn:Hn0.\n      * rewrite compare_antisym in Hn0. unfold CompOpp in Hn0.\n        destruct (n0?=n); try inversion Hn0. apply (IHx _ _ H H0).\n      * rewrite compare_antisym in Hn0. unfold CompOpp in Hn0.\n        destruct (n0?=n); try inversion Hn0. inversion H.\n      * inversion H0.\n    + auto.\n    + destruct (n ?= n0) eqn:Hnn0.\n      * apply compare_eq_iff in Hnn0. rewrite Hnn0 in H. rewrite Han0 in H.\n        inversion H.\n      * apply compare_lt_iff in Hnn0. apply compare_gt_iff in Han0.\n        apply lt_trans with (n:=n) in Han0; auto. apply compare_lt_iff in Han0.\n        rewrite compare_antisym in Han0. unfold CompOpp in Han0.\n        destruct (a?=n); try inversion Han0. inversion H.\n      * inversion H0.\nQed.\n\nLemma MonoOrder_Transitive : \n  Relations_1.Transitive (fun x y => is_true (MonoOrder.leb x y)).\nProof.\n  unfold Relations_1.Transitive, is_true, MonoOrder.leb, mono_cmp.\n  induction x, y, z; intros; try reflexivity; simpl in *.\n  - inversion H.\n  - inversion H.\n  - inversion H0.\n  - destruct (a ?= n) eqn:Han.\n    + apply compare_eq_iff in Han. rewrite Han. destruct (n ?= n0) eqn:Hn0.\n      * apply (IHx _ _ H H0).\n      * reflexivity.\n      * inversion H0.\n    + destruct (n ?= n0) eqn:Hn0.\n      * apply compare_eq_iff in Hn0. rewrite <- Hn0. rewrite Han. reflexivity.\n      * apply compare_lt_iff in Han. apply compare_lt_iff in Hn0.\n        apply (lt_trans a n n0 Han) in Hn0. apply compare_lt_iff in Hn0.\n        rewrite Hn0. reflexivity.\n      * inversion H0.\n    + inversion H.\nQed.\n\n\n\n(** ** Sorting and Permutations *)\n\n(** The entire purpose of ensuring our monomials and polynomials remain sorted\n    at all times is so that two polynomials containing the same elements are\n    treated as equal. This definition obviously lends itself very well to the\n    use of the [Permutation] predicate from the standard library, which explains\n    why we proved so many lemmas about permutations during [list_util].\n\n    When comparing equality of polynomials or monomials, this [sort] function is\n    often extremely tricky to deal with. Induction over a list being passed to\n    [sort] is nearly impossible, because the induction element [a] is not\n    guaranteed to be the least value, so will not easily make it outside of the\n    sort function. As a result, the induction hypothesis is almost always\n    useless.\n\n    To combat this, we will prove a series of lemmas relating [sort] to\n    [Permutation], since clearly sorting has no effect when we are comparing\n    the lists in an unordered fashion. The simplest of these lemmas is that\n    if either term of a [Permutation] is wrapped in a [sort] function, we can\n    easily get rid of it without changing the provability of these statements.\n    *)\n\nLemma Permutation_VarSort_l : forall m n,\n  Permutation m n <-> Permutation (VarSort.sort m) n.\nProof.\n  intros m n. split; intro.\n  - apply Permutation_trans with (l':=m). apply Permutation_sym.\n    apply VarSort.Permuted_sort. apply H.\n  - apply Permutation_trans with (l':=(VarSort.sort m)).\n    apply VarSort.Permuted_sort. apply H.\nQed.\n\nLemma Permutation_VarSort_r : forall m n,\n  Permutation m n <-> Permutation m (VarSort.sort n).\nProof.\n  intros m n. split; intro.\n  - apply Permutation_sym. rewrite <- Permutation_VarSort_l.\n    apply Permutation_sym; auto.\n  - apply Permutation_sym. rewrite -> Permutation_VarSort_l.\n    apply Permutation_sym; auto.\nQed.\n\nLemma Permutation_MonoSort_r : forall p q,\n  Permutation p q <-> Permutation p (sort q).\nProof.\n  intros p q. split; intro H.\n  - apply Permutation_trans with (l':=q). apply H. apply Permuted_sort.\n  - apply Permutation_trans with (l':=(sort q)). apply H. apply Permutation_sym.\n    apply Permuted_sort.\nQed.\n\nLemma Permutation_MonoSort_l : forall p q,\n  Permutation p q <-> Permutation (sort p) q.\nProof.\n  intros p q. split; intro H.\n  - apply Permutation_sym. rewrite <- Permutation_MonoSort_r.\n    apply Permutation_sym. auto.\n  - apply Permutation_sym. rewrite Permutation_MonoSort_r.\n    apply Permutation_sym. auto.\nQed.\n\n(** More powerful is the idea that, if we know we are dealing with sorted lists,\n    there is no difference between proving lists are equal and proving they\n    are [Permutation]s. While this seems intuitive, it is actually fairly\n    complicated to prove in Coq.\n\n    For monomials, the proof begins by performing induction on both lists. The\n    first three cases are very straightforward, and the only challenge comes\n    from the third case. We approach the third case by first comparing the two\n    induction elements, [a] and [a0].\n\n    This forms three goals for us - one where [a = a0], one where [a < a0], and\n    one where [a > a0]. The first goal is extremely straightforward, and follows\n    from the induction hypothesis almost immediately after using a few [compare]\n    lemmas.\n\n    This leaves us with the next two goals, which seem to be more challenging at\n    first. However, some further thought leads us to the conclusion that both\n    goals should both be contradictions. If the lists are both sorted, and they\n    contain all the same elements, then they should have the same element, at\n    the head of the list, which is the least element of the set. This element is\n    clearly [a] for the first list, and [a0] for the second. However, our\n    destruct of [compare] has left us with a hypothesis stating that they are\n    not equal! This is the source of the contradiction.\n\n    To get Coq to see our contradiction, we first make use of the [Transitive]\n    lemmas we proved earlier to convert to [StronglySorted]. This allows us to\n    get a hypothesis in the second goal that states that [a0] must be less than\n    everything in the second list. Because [a] is not equal to [a0], this\n    implied that [a] is somewhere else in the second list, and therefore [a0] is\n    less than [a]. This clearly contradicts the fact that [a < a0]. The third\n    goal looks the same, but in reverse. *)\n\nLemma Permutation_Sorted_mono_eq : forall (m n : mono),\n  Permutation m n ->\n  Sorted (fun n m => is_true (leb n m)) m ->\n  Sorted (fun n m => is_true (leb n m)) n ->\n  m = n.\nProof.\n  intros m n Hp Hsl Hsm. generalize dependent n.\n  induction m; induction n; intros.\n  - reflexivity.\n  - apply Permutation_nil in Hp. auto.\n  - apply Permutation_sym, Permutation_nil in Hp. auto.\n  - clear IHn. apply Permutation_incl in Hp as Hp'. destruct Hp'.\n    destruct (a ?= a0) eqn:Hcomp.\n    + apply compare_eq_iff in Hcomp. rewrite Hcomp in *.\n      apply Permutation_cons_inv in Hp. f_equal; auto.\n      apply IHm.\n      * apply Sorted_inv in Hsl. apply Hsl.\n      * apply Hp.\n      * apply Sorted_inv in Hsm. apply Hsm.\n    + apply compare_lt_iff in Hcomp as Hneq. apply incl_cons_inv in H.\n      destruct H. apply Sorted_StronglySorted in Hsm.\n      apply StronglySorted_inv in Hsm as [].\n      * simpl in H. destruct H; try (rewrite H in Hneq; apply lt_irrefl in Hneq;\n        contradiction). pose (Forall_In _ _ _ _ H H3). simpl in i.\n        unfold is_true in i. apply leb_le in i. apply lt_not_le in Hneq.\n        contradiction.\n      * apply VarOrder_Transitive.\n    + apply compare_gt_iff in Hcomp as Hneq. apply incl_cons_inv in H0.\n      destruct H0.\n      apply Sorted_StronglySorted in Hsl. apply StronglySorted_inv in Hsl as [].\n      * simpl in H0. destruct H0; try (rewrite H0 in Hneq;\n        apply gt_irrefl in Hneq; contradiction). pose (Forall_In _ _ _ _ H0 H3).\n        simpl in i. unfold is_true in i. apply leb_le in i.\n        apply lt_not_le in Hneq. contradiction.\n      * apply VarOrder_Transitive.\nQed.\n\n(** We also wish to prove the same thing for polynomials. This proof is\n    identical in spirit, as we do the same double induction, destructing of\n    compare, and find the same two contradictions. The only difference is the\n    use of lemmas about [lex] instead of [compare], since now we are dealing\n    with lists of lists. *)\n\nLemma Permutation_Sorted_eq : forall (l m : list mono),\n  Permutation l m ->\n  Sorted (fun x y => is_true (MonoOrder.leb x y)) l ->\n  Sorted (fun x y => is_true (MonoOrder.leb x y)) m ->\n  l = m.\nProof.\n  intros l m Hp Hsl Hsm. generalize dependent m.\n  induction l; induction m; intros.\n  - reflexivity.\n  - apply Permutation_nil in Hp. auto.\n  - apply Permutation_sym, Permutation_nil in Hp. auto.\n  - clear IHm. apply Permutation_incl in Hp as Hp'. destruct Hp'.\n    destruct (mono_cmp a a0) eqn:Hcomp.\n    + apply lex_eq in Hcomp. rewrite Hcomp in *.\n      apply Permutation_cons_inv in Hp. f_equal; auto.\n      apply IHl.\n      * apply Sorted_inv in Hsl. apply Hsl.\n      * apply Hp.\n      * apply Sorted_inv in Hsm. apply Hsm.\n    + apply lex_neq' in Hcomp as Hneq. apply incl_cons_inv in H. destruct H.\n      apply Sorted_StronglySorted in Hsm. apply StronglySorted_inv in Hsm as [].\n      * simpl in H. destruct H; try (rewrite H in Hneq; contradiction).\n        pose (Forall_In _ _ _ _ H H3). simpl in i. unfold is_true,\n        MonoOrder.leb, mono_cmp in i. apply lex_rev_lt_gt in Hcomp.\n        rewrite Hcomp in i. inversion i.\n      * apply MonoOrder_Transitive.\n    + apply lex_neq' in Hcomp as Hneq. apply incl_cons_inv in H0. destruct H0.\n      apply Sorted_StronglySorted in Hsl. apply StronglySorted_inv in Hsl as [].\n      * simpl in H0. destruct H0; try (rewrite H0 in Hneq; contradiction).\n        pose (Forall_In _ _ _ _ H0 H3). simpl in i. unfold is_true in i.\n        unfold MonoOrder.leb in i. rewrite Hcomp in i. inversion i.\n      * apply MonoOrder_Transitive.\nQed.\n\n(** Another useful form of these two lemmas is that if at any point we are\n    attempting to prove that [sort] of one list equals [sort] of another, we\n    can ditch the [sort] and instead prove that the two lists are permutations.\n    These lemmas will come up a lot in future proofs, and has made some of our\n    work much easier. *)\n\nLemma Permutation_sort_mono_eq : forall l m,\n  Permutation l m <-> VarSort.sort l = VarSort.sort m.\nProof.\n  intros l m. split; intros H.\n  - assert (H0 : Permutation (VarSort.sort l) (VarSort.sort m)).\n    + apply Permutation_trans with (l:=(VarSort.sort l)) (l':=m)\n        (l'':=VarSort.sort m).\n      * apply Permutation_sym. apply Permutation_sym in H.\n        apply (Permutation_trans H (VarSort.Permuted_sort l)).\n      * apply VarSort.Permuted_sort.\n    + apply (Permutation_Sorted_mono_eq _ _ H0 (VarSort.LocallySorted_sort l)\n        (VarSort.LocallySorted_sort m)).\n  - assert (Permutation (VarSort.sort l) (VarSort.sort m)).\n    + rewrite H. apply Permutation_refl.\n    + pose (VarSort.Permuted_sort l). pose (VarSort.Permuted_sort m).\n      apply (Permutation_trans p) in H0. apply Permutation_sym in p0.\n      apply (Permutation_trans H0) in p0. apply p0.\nQed.\n\nLemma Permutation_sort_eq : forall l m,\n  Permutation l m <-> sort l = sort m.\nProof.\n  intros l m. split; intros H.\n  - assert (H0 : Permutation (sort l) (sort m)).\n    + apply Permutation_trans with (l:=sort l) (l':=m) (l'':=sort m).\n      * apply Permutation_sym. apply Permutation_sym in H.\n        apply (Permutation_trans H (Permuted_sort l)).\n      * apply Permuted_sort.\n    + apply (Permutation_Sorted_eq _ _ H0 (LocallySorted_sort l)\n        (LocallySorted_sort m)).\n  - assert (Permutation (sort l) (sort m)).\n    + rewrite H. apply Permutation_refl.\n    + pose (Permuted_sort l). pose (Permuted_sort m).\n      apply (Permutation_trans p) in H0. apply Permutation_sym in p0.\n      apply (Permutation_trans H0) in p0. apply p0.\nQed.\n\n(* ===== Repairing ====== *) \n(** * Repairing Invalid Monomials & Polynomials *)\n\n(** Clearly, there is a very strict set of rules we would like to be true about\n    all of the polynomials and monomials we workd with. These rules are,\n    however, relatively tricky to maintain when it comes to writing functions\n    that operate over monomials and polynomials. Rather than rely on our\n    ability to define every function to perfectly maintain this set of rules,\n    we decided to define two functions to \"repair\" any invalid monomials or\n    polynomials. These functions, given a list of variables or a list of list of\n    variables, will apply a few functions to them such that at the end, we are\n    left with a properly formatted monomial or polynomial. *)\n\n(** ** Converting Between [lt] and [le] *)\n\n(** A small problem with the [sort] function provided by the standard\n    library is that it requires us to use a [le] comparator, as opposed to [lt]\n    like we use in our [is_mono] and [is_poly] definitions. However, as we said\n    before, because our lists have no duplicates [le] and [lt] are equivalent.\n    Obviously, though, saying this isn't enough - we must prove it for it to be\n    useful to us in proofs.\n\n    The first step to proving this is proving that this is true when dealing\n    with the [HdRel] definition that [Sorted] is built on top of. These lemmas\n    state that, if [a] holds the [le] relation with a list, and there are also\n    no duplicates in [a :: l], that [a] also holds the [lt] relation with the\n    list. These proofs are both relatively straightforward, especially with the\n    use of the [NoDup_neq] lemma proven earlier. *)\n\nLemma HdRel_le_lt : forall a m,\n  HdRel (fun n m => is_true (leb n m)) a m /\\ NoDup (a :: m) ->\n  HdRel lt a m.\nProof.\n  intros a m []. remember (fun n m => is_true (leb n m)) as le.\n  destruct m.\n  - apply HdRel_nil.\n  - apply HdRel_cons. apply HdRel_inv in H.\n    apply (NoDup_neq _ a n) in H0; intuition. rewrite Heqle in H.\n    unfold is_true in H. apply leb_le in H. destruct (a ?= n) eqn:Hcomp.\n    + apply compare_eq_iff in Hcomp. contradiction.\n    + apply compare_lt_iff in Hcomp. apply Hcomp.\n    + apply compare_gt_iff in Hcomp. apply leb_correct_conv in Hcomp.\n      apply leb_correct in H. rewrite H in Hcomp. inversion Hcomp.\nQed.\n\nLemma HdRel_mono_le_lt : forall a p,\n  HdRel (fun n m => is_true (MonoOrder.leb n m)) a p /\\ NoDup (a :: p) ->\n  HdRel mono_lt a p.\nProof.\n  intros a p []. remember (fun n m => is_true (MonoOrder.leb n m)) as le.\n  destruct p.\n  - apply HdRel_nil.\n  - apply HdRel_cons. apply HdRel_inv in H.\n    apply (NoDup_neq _ a l) in H0; intuition. rewrite Heqle in H.\n    unfold is_true in H. unfold MonoOrder.leb in H. unfold mono_lt.\n    destruct (mono_cmp a l) eqn:Hcomp.\n    + apply lex_eq in Hcomp. contradiction.\n    + reflexivity.\n    + inversion H.\nQed.\n\n(** Now, to apply these lemmas - we prove that if a list is [Sorted] with a [le]\n    operator and has no duplicates, that it is also [Sorted] with the\n    corresponding [lt] operator. *)\n\nLemma VarSort_Sorted : forall m,\n  Sorted (fun n m => is_true (leb n m)) m /\\ NoDup m ->\n  Sorted lt m.\nProof.\n  intros m []. remember (fun n m => is_true (leb n m)) as le.\n  induction m.\n  - apply Sorted_nil.\n  - apply Sorted_inv in H. apply Sorted_cons.\n    + apply IHm.\n      * apply H.\n      * apply NoDup_cons_iff in H0. apply H0.\n    + apply HdRel_le_lt. split.\n      * rewrite <- Heqle. apply H.\n      * apply H0.\nQed.\n\nLemma MonoSort_Sorted : forall p,\n  Sorted (fun n m => is_true (MonoOrder.leb n m)) p /\\ NoDup p ->\n  Sorted mono_lt p.\nProof.\n  intros p []. remember (fun n m => is_true (MonoOrder.leb n m)) as le.\n  induction p.\n  - apply Sorted_nil.\n  - apply Sorted_inv in H. apply Sorted_cons.\n    + apply IHp.\n      * apply H.\n      * apply NoDup_cons_iff in H0. apply H0.\n    + apply HdRel_mono_le_lt. split.\n      * rewrite <- Heqle. apply H.\n      * apply H0.\nQed.\n\n(** For convenience, we also include the inverse - if a list is [Sorted] with an\n    [lt] operator, it is also [Sorted] with the matching [le] operator. *)\n\nLemma Sorted_VarSorted : forall (m : mono),\n  Sorted lt m ->\n  Sorted (fun n m => is_true (leb n m)) m.\nProof.\n  intros m H. induction H.\n  - apply Sorted_nil.\n  - apply Sorted_cons.\n    + apply IHSorted.\n    + destruct l.\n      * apply HdRel_nil.\n      * apply HdRel_cons. apply HdRel_inv in H0. apply lt_le_incl in H0.\n        apply leb_le in H0. apply H0.\nQed.\n\nLemma Sorted_MonoSorted : forall (p : poly),\n  Sorted mono_lt p ->\n  Sorted (fun n m => is_true (MonoOrder.leb n m)) p.\nProof.\n  intros p H. induction H.\n  - apply Sorted_nil.\n  - apply Sorted_cons.\n    + apply IHSorted.\n    + destruct l.\n      * apply HdRel_nil.\n      * apply HdRel_cons. apply HdRel_inv in H0. unfold MonoOrder.leb.\n        rewrite H0. auto.\nQed.\n\n(** Another obvious side effect of what we have just proven is that if a list is\n    [Sorted] with an [lt] operator, clearly there are no duplicates, as no\n    elements are equal to each other. *)\n\nLemma NoDup_VarSorted : forall m,\n  Sorted lt m -> NoDup m.\nProof.\n  intros m H. apply Sorted_StronglySorted in H.\n  - induction m; auto.\n    apply StronglySorted_inv in H as []. apply NoDup_forall_neq.\n    + apply Forall_forall. intros x Hin. rewrite Forall_forall in H0.\n      apply lt_neq. apply H0. apply Hin.\n    + apply IHm. apply H.\n  - apply lt_Transitive.\nQed.\n\nLemma NoDup_MonoSorted : forall p,\n  Sorted mono_lt p -> NoDup p.\nProof.\n  intros p H. apply Sorted_StronglySorted in H.\n  - induction p; auto.\n    apply StronglySorted_inv in H as []. apply NoDup_forall_neq.\n    + apply Forall_forall. intros x Hin. rewrite Forall_forall in H0.\n      pose (lex_neq' a x). destruct a0. apply H1 in H0; auto.\n    + apply IHp. apply H.\n  - apply mono_lt_Transitive.\nQed.\n\n(** There are a few more useful lemmas we would like to prove about our sort\n    functions before we can define and prove the correctness of our repair\n    functions. Mostly, we want to know that sorting a list has no effect on some\n    properties of it.\n\n    Specifically, if an element was in a list before it was sorted, it is also\n    in it after, and vice versa. Similarly, if a list has no duplicates before\n    being sorted, it also has no duplicates after. *)\n\nLemma In_sorted : forall a l,\n  In a l <-> In a (sort l).\nProof.\n  intros a l. pose (MonoSort.Permuted_sort l). split; intros Hin.\n  - apply (Permutation_in _ p Hin).\n  - apply (Permutation_in' (Logic.eq_refl a) p). auto.\nQed.\n\nLemma NoDup_VarSort : forall (m : mono),\n  NoDup m -> NoDup (VarSort.sort m).\nProof.\n  intros m Hdup. pose (VarSort.Permuted_sort m).\n  apply (Permutation_NoDup p Hdup).\nQed.\n\nLemma NoDup_MonoSort : forall (p : poly),\n  NoDup p -> NoDup (MonoSort.sort p).\nProof.\n  intros p Hdup. pose (MonoSort.Permuted_sort p).\n  apply (Permutation_NoDup p0 Hdup).\nQed.\n\n(** ** Defining the Repair Functions *)\n\n(** Now time for our definitions. To convert a list of variables into a\n    monomial, we first apply [nodup], which removes all duplicates. We use\n    [nodup] rather than [nodup_cancel] because $x \\ast x \\approx_{B} x$, so we\n    want one copy to remain. After applying [nodup], we use our [VarSort] module\n    to sort the list from least to greatest. *)\n\nDefinition make_mono (l:list nat) : mono :=\n  VarSort.sort (nodup var_eq_dec l).\n\n(** The process of converting a list of list of variables into a polynomial is\n    very similar. First we [map] across the list applying [make_mono], so that\n    each sublist is properly formatted. Then we apply [nodup_cancel] to remove\n    duplicates. In this case, we use [nodup_cancel] instead of [nodup] because\n    [x+x = 0], so we want pairs to cancel out. Lastly, we use our [MonoSort]\n    module to sort the list. *)\n\nDefinition make_poly (l:list mono) : poly :=\n  MonoSort.sort (nodup_cancel mono_eq_dec (map make_mono l)).\n\nLemma make_poly_refold : forall p,\n  sort (nodup_cancel mono_eq_dec (map make_mono p)) =\n  make_poly p.\nProof. auto. Qed.\n\n(** Now to prove the correctness of these lists - if you apply [make_mono] to\n    something, it is then guaranteed to satisfy the [is_mono] proposition. This\n    proof is relatively straightforward, as we have already done most of the\n    work with [VarSort_Sorted]; all that is left to do is show that\n    [make_mono m] is [Sorted] and has no duplicates, which is obvious\n    considering that is exactly what [make_mono] does! *)\n\nLemma make_mono_is_mono : forall m,\n  is_mono (make_mono m).\nProof.\n  intros m. unfold is_mono, make_mono. apply VarSort_Sorted. split.\n  + apply VarSort.LocallySorted_sort.\n  + apply NoDup_VarSort. apply NoDup_nodup.\nQed.\n\n(** The proof for [make_poly_is_poly] is almost identical, with the addition of\n    one part. The [is_poly] predicate still asks us to prove that the list is\n    [Sorted], which follows from [MonoSort_Sorted] like above. The only\n    difference is that [is_poly] also asks us to show that each element in the\n    list [is_mono], which follows from the use of a few [In] lemmas and the\n    [make_mono_is_mono] we just proved thanks to the [map] in [make_poly]. *)\n\nLemma make_poly_is_poly : forall p,\n  is_poly (make_poly p).\nProof.\n  intros p. unfold is_poly, make_poly. split.\n  - apply MonoSort_Sorted. split.\n    + apply MonoSort.LocallySorted_sort.\n    + apply NoDup_MonoSort. apply NoDup_nodup_cancel.\n  - intros m Hm. apply In_sorted in Hm. apply nodup_cancel_in in Hm.\n    apply in_map_iff in Hm. destruct Hm. destruct H. rewrite <- H.\n    apply make_mono_is_mono.\nQed.\n\nHint Resolve make_poly_is_poly make_mono_is_mono.\n\n\n\n\n(** ** Facts about [make_mono] *)\n\n(** Before we dive into more complicated proofs involving these repair\n    functions, there are a few simple lemmas we can prove about them.\n\n    First is that if some variable [x] was in a list before [make_mono] was\n    applied, it must also be in it after, and vice-versa. *)\n\nLemma make_mono_In : forall x m,\n  In x (make_mono m) <-> In x m.\nProof.\n  intros x m. split; intro H.\n  - unfold make_mono in H. pose (VarSort.Permuted_sort (nodup var_eq_dec m)).\n    apply Permutation_sym in p. apply (Permutation_in _ p) in H.\n    apply nodup_In in H. auto.\n  - unfold make_mono. pose (VarSort.Permuted_sort (nodup var_eq_dec m)).\n    apply Permutation_in with (l:=(nodup var_eq_dec m)); auto. apply nodup_In.\n    auto.\nQed.\n\n(** In addition, if some list [m] is already a monomial, removing anything from\n    it will not change that. *)\n\nLemma remove_is_mono : forall x m,\n  is_mono m ->\n  is_mono (remove var_eq_dec x m).\nProof.\n  intros x m H. unfold is_mono in *. apply StronglySorted_Sorted.\n  apply StronglySorted_remove. apply Sorted_StronglySorted in H. auto.\n  apply lt_Transitive.\nQed.\n\n(** If we know that some (l1 ++ x :: l2) is a mono, then clearly it is still a\n    monomial if we remove the x from the middle, as this will not affect the\n    sorting at all. *)\n\nLemma mono_middle : forall x l1 l2,\n  is_mono (l1 ++ x :: l2) ->\n  is_mono (l1 ++ l2).\nProof.\n  intros x l1 l2 H. unfold is_mono in *. apply Sorted_StronglySorted in H.\n  apply StronglySorted_Sorted. induction l1.\n  - rewrite app_nil_l in *. apply StronglySorted_inv in H as []; auto.\n  - simpl in *. apply StronglySorted_inv in H as []. apply SSorted_cons; auto.\n    apply Forall_forall. rewrite Forall_forall in H0. intros x0 Hin.\n    apply H0. apply in_app_iff in Hin as []; intuition.\n  - apply lt_Transitive.\nQed.\n\n(** Due to the nature of sorting, [make_mono] is commutative across list\n    concatenation. *)\n\nLemma make_mono_app_comm : forall m n,\n  make_mono (m ++ n) = make_mono (n ++ m).\nProof.\n  intros m n. apply Permutation_sort_mono_eq. apply Permutation_nodup.\n  apply Permutation_app_comm.\nQed.\n\n(** Finally, if a list [m] is a member of the list resulting from\n    [map make_mono], then clearly it is a monomial. *)\n\nLemma mono_in_map_make_mono : forall p m,\n  In m (map make_mono p) -> is_mono m.\nProof.\n  intros. apply in_map_iff in H as [x []]. rewrite <- H. auto.\nQed.\n\n(** ** Facts about [make_poly] *)\n\n(** If two lists are permutations of each other, then they will be equivalent\n    after applying [make_poly] to both. *)\n\nLemma make_poly_Permutation : forall p q,\n  Permutation p q -> make_poly p = make_poly q.\nProof.\n  intros. unfold make_poly.\n  apply Permutation_sort_eq, nodup_cancel_Permutation, Permutation_map.\n  auto.\nQed.\n\n(** Because we have shown that [sort] and [Permutation] are equivalent, we can\n    easily show that [make_poly] is commutative accross list concatenation. *)\n\nLemma make_poly_app_comm : forall p q,\n  make_poly (p ++ q) = make_poly (q ++ p).\nProof.\n  intros p q. apply Permutation_sort_eq.\n  apply nodup_cancel_Permutation. apply Permutation_map.\n  apply Permutation_app_comm.\nQed.\n\n(** During [make_poly], we both [sort] and call [nodup_cancel]. A lemma that is\n    useful in some cases shows that it doesn't matter what order we do these\n    in, as [nodup_cancel] will maintain the order of a list. *)\n\nLemma sort_nodup_cancel_assoc : forall l,\n  sort (nodup_cancel mono_eq_dec l) = nodup_cancel mono_eq_dec (sort l).\nProof.\n  intros l. apply Permutation_Sorted_eq.\n  - pose (Permuted_sort (nodup_cancel mono_eq_dec l)).\n    apply Permutation_sym in p. apply (Permutation_trans p). clear p.\n    apply NoDup_Permutation.\n    + apply NoDup_nodup_cancel.\n    + apply NoDup_nodup_cancel.\n    + intros x. split.\n      * intros H. apply Permutation_in with (l:=nodup_cancel mono_eq_dec l).\n        apply nodup_cancel_Permutation. apply Permuted_sort. auto.\n      * intros H.\n        apply Permutation_in with (l:=nodup_cancel mono_eq_dec (sort l)).\n        apply nodup_cancel_Permutation. apply Permutation_sym.\n        apply Permuted_sort. auto.\n  - apply LocallySorted_sort.\n  - apply Sorted_nodup_cancel.\n    + apply MonoOrder_Transitive.\n    + apply LocallySorted_sort.\nQed.\n\n(** Another obvious but useful lemma is that if a monomial [m] is in a list\n    resulting from applying [make_poly], is is clearly a monomial. *)\n\nLemma mono_in_make_poly : forall p m,\n  In m (make_poly p) -> is_mono m.\nProof.\n  intros. unfold make_poly in H. apply In_sorted in H.\n  apply nodup_cancel_in in H. apply (mono_in_map_make_mono _ _ H).\nQed.\n\n\n(** * Proving Functions \"Pointless\" *)\n\n(** In the [list_util] file, we have two lemmas revolving around the idea that,\n    in some cases, calling [nodup_cancel] is \"pointless\". The idea here is that,\n    when comparing very complicated terms, it is sometimes beneficial to either\n    add or remove an extra function call that has no effect on the final term.\n    Until this point, we have only proven this about [nodup_cancel] and\n    [remove], but there are many other cases where this is true, which will make\n    our more complex proofs much easier. This section serves to prove this true\n    of most of our functions. *)\n\n(** ** Working with [sort] Functions *)\n\n(** The next two lemmas very simply prove that, if a list is already [Sorted],\n    then calling either [VarSort] or [MonoSort] on it will have no effect. This\n    is relatively obvious, and is extremely easy to prove with our [Permutation]\n    / [Sorted] lemmas from earlier. *)\n\nLemma no_sort_VarSorted : forall m,\n  Sorted lt m ->\n  VarSort.sort m = m.\nProof.\n  intros m H. apply Permutation_Sorted_mono_eq.\n  - apply Permutation_sym. apply VarSort.Permuted_sort.\n  - apply VarSort.LocallySorted_sort.\n  - apply Sorted_VarSorted. auto.\nQed.\n\nLemma no_sort_MonoSorted : forall p,\n  Sorted mono_lt p ->\n  MonoSort.sort p = p.\nProof.\n  intros p H. unfold make_poly. apply Permutation_Sorted_eq.\n  - apply Permutation_sym. apply Permuted_sort.\n  - apply LocallySorted_sort.\n  - apply Sorted_MonoSorted. auto.\nQed.\n\n(** The following lemma more closely aligns with the format of the\n    [nodup_cancel_pointless] lemma from [list_util]. It states that if the\n    result of appending two lists is already going to be sorted, there is no\n    need to sort the intermediate lists.\n\n    This also applies if the sort is wrapped around the right argument, thanks\n    to the [Permutation] lemmas we proved earlier. *)\n\nLemma sort_pointless : forall p q,\n  sort (sort p ++ q) =\n  sort (p ++ q).\nProof.\n  intros p q. apply Permutation_sort_eq.\n  apply Permutation_app_tail. apply Permutation_sym.\n  apply Permuted_sort.\nQed.\n\n(** ** Working with [make_mono] *)\n\n(** There are a couple forms that the proof of [make_mono] being pointless can\n    take. Firstly, because we already know that [make_mono] simply applies\n    functions to get the list into a form that satisfies [is_mono], it makes\n    sense to prove that if some list is already a mono that [make_mono] will\n    have no effect. This is proved with the help of [no_sort_VarSorted] and\n    [no_nodup_NoDup]. *)\n\nLemma no_make_mono : forall m,\n  is_mono m ->\n  make_mono m = m.\nProof.\n  unfold make_mono, is_mono. intros m H. rewrite no_sort_VarSorted.\n  - apply no_nodup_NoDup. apply NoDup_VarSorted in H. auto.\n  - apply Sorted_nodup; auto. apply lt_Transitive.\nQed.\n\n(** We can also prove the more standard form of [make_mono_pointless], which\n    states that if there are nested calls to [make_mono], we can remove all\n    except the outermost layer. *)\n\nLemma make_mono_pointless : forall m a,\n  make_mono (m ++ make_mono a) = make_mono (m ++ a).\nProof.\n  intros m a. apply Permutation_sort_mono_eq. rewrite <- (nodup_pointless _ a).\n  apply Permutation_nodup. apply Permutation_app_head. unfold make_mono.\n  rewrite <- Permutation_VarSort_l. auto.\nQed.\n\n(** Similarly, if we already know that all of the elements in a list are\n    monomials, then mapping [make_mono] across the list will have no effect on\n    the entire list. *)\n\nLemma no_map_make_mono : forall p,\n  (forall m, In m p -> is_mono m) ->\n  map make_mono p = p.\nProof.\n  intros p H. induction p; auto.\n  simpl. rewrite no_make_mono.\n  - f_equal. apply IHp. intros m Hin. apply H. intuition.\n  - apply H. intuition.\nQed.\n\n(** Lastly, the pointless proof that more closely aligns with what we have done\n    so far - if [make_poly] is already being applied to a list, there is no need\n    to have a call to [map make_mono] on the inside. *)\n\nLemma map_make_mono_pointless : forall p q,\n  make_poly (map make_mono p ++ q) =\n  make_poly (p ++ q).\nProof.\n  intros p q. destruct p; auto.\n  simpl. unfold make_poly. simpl map.\n  rewrite (no_make_mono (make_mono l)); auto. rewrite map_app. rewrite map_app.\n  rewrite (no_map_make_mono (map _ _)). auto. intros m Hin.\n  apply in_map_iff in Hin. destruct Hin as [x[]]. rewrite <- H. auto.\nQed.\n\n(** ** Working with [make_poly] *)\n\n(** Finally, we work to prove some lemmas about [make_poly] as a whole being\n    pointless. These proofs are built upon the previous few lemmas, which prove\n    that we can remove the components of [make_poly] one by one.\n\n    First up, we have a lemma that shows that if [p] already has no duplicates\n    and everything in the list is a mono, then [nodup_cancel] and\n    [map make_mono] will both have no effect. This lemma turns out to be very\n    useful _after_ something like [Permutation_sort_eq] has been applied, as it\n    can strip away the other two functions of [make_poly]. *)\n\nLemma unsorted_poly : forall p,\n  NoDup p ->\n  (forall m, In m p -> is_mono m) ->\n  nodup_cancel mono_eq_dec (map make_mono p) = p.\nProof.\n  intros p Hdup Hin. rewrite no_map_make_mono; auto.\n  apply no_nodup_cancel_NoDup; auto.\nQed.\n\n(** Similarly to [no_make_mono], it is very straightforward to prove that if\n    some list [p] is already a polynomial, then [make_poly] has no effect. *)\n\nLemma no_make_poly : forall p,\n  is_poly p ->\n  make_poly p = p.\nProof.\n  unfold make_poly, is_poly. intros m []. rewrite no_sort_MonoSorted.\n  - rewrite no_nodup_cancel_NoDup.\n    + apply no_map_make_mono. intros m0 Hin. apply H0. auto.\n    + apply NoDup_MonoSorted in H. rewrite no_map_make_mono; auto.\n  - apply Sorted_nodup_cancel.\n    + apply mono_lt_Transitive.\n    + rewrite no_map_make_mono; auto.\nQed.\n\n(** Now onto the most important lemma. In many of the later proofs, there will\n    be times where there are calls to [make_poly] nested inside of each other,\n    or long lists of arguments appended together inside of a [make_poly]. In\n    either case, the ability to add and remove extra calls to [make_poly] as we\n    please proves to be very powerful.\n\n    To prove [make_poly_pointless], we begin by proving a weaker version that\n    insists that all of the arguments of [p] and [q] are all monomials. This\n    addition makes the proof significantly easier. As one might expect, the\n    proof is completed by using [Permutation_sort_eq] to remove the sort calls,\n    [nodup_cancel_pointless] to remove the [nodup_cancel] calls, and\n    [no_map_make_mono] to get rid of the [map make_mono] calls. After this is\n    done, the two sides are identical. *)\n\nLemma make_poly_pointless_weak : forall p q,\n  (forall m, In m p -> is_mono m) ->\n  (forall m, In m q -> is_mono m) ->\n  make_poly (make_poly p ++ q) =\n  make_poly (p ++ q).\nProof.\n  intros p q Hmp Hmq. unfold make_poly.\n  repeat rewrite no_map_make_mono; intuition.\n  apply Permutation_sort_eq. rewrite sort_nodup_cancel_assoc.\n  rewrite nodup_cancel_pointless. apply nodup_cancel_Permutation.\n  apply Permutation_sym. apply Permutation_app_tail. apply Permuted_sort.\n  - simpl in H. rewrite in_app_iff in H. destruct H; intuition.\n  - rewrite in_app_iff in H. destruct H; intuition.\n    apply In_sorted in H. apply nodup_cancel_in in H. intuition.\nQed.\n\n(** Now, to make the stronger and easier to use version, we simply rewrite in\n    the opposite direction with [map_make_mono_pointless] to add extra calls of\n    [map make_mono] in! Ironically, this proof _of_ [make_poly_pointless]\n    is a great example of why these \"pointless\" lemmas are so useful. While we\n    can clearly tell that adding the extra call to [map make_mono] makes no\n    difference, it makes proving things in a way that Coq understands\n    dramatically easier at times.\n\n    After rewriting with [map_make_mono_pointless], clearly both areguments\n    contain all monomials, and we can use [make_poly_pointless_weak] to prove\n    the stronger version. *)\n\nLemma make_poly_pointless : forall p q,\n  make_poly (make_poly p ++ q) =\n  make_poly (p ++ q).\nProof.\n  intros p q. rewrite make_poly_app_comm.\n  rewrite <- map_make_mono_pointless. rewrite make_poly_app_comm.\n  rewrite <- (map_make_mono_pointless p). rewrite (make_poly_app_comm _ q).\n  rewrite <- (map_make_mono_pointless q).\n  rewrite (make_poly_app_comm _ (map make_mono p)).\n  rewrite <- (make_poly_pointless_weak (map make_mono p)). unfold make_poly.\n  rewrite (no_map_make_mono (map make_mono p)). auto.\n  apply mono_in_map_make_mono. apply mono_in_map_make_mono.\n  apply mono_in_map_make_mono.\nQed.\n\n(** For convenience, we also prove that it applies on the right side by using\n    [make_poly_app_comm] twice. *)\n\nLemma make_poly_pointless_r : forall p q,\n  make_poly (p ++ make_poly q) =\n  make_poly (p ++ q).\nProof.\n  intros p q. rewrite make_poly_app_comm. rewrite make_poly_pointless.\n  apply make_poly_app_comm.\nQed.\n\n\n\n(** * Polynomial Arithmetic *)\n\n(** Now, the foundation for operations on polynomails has been put in place, and\n    we can begin to get into the real meat - our arithmetic operators. First up\n    is addition. Because we have so cleverly defined our [make_poly] function,\n    addition over our data structures is as simple as appending the two\n    polynomials and repairing the result back into a proper polynomial.\n\n    We also include a simple refold lemma for convenience, and a quick proof\n    that the result of [addPP] is always a polynomial. *)\n\nDefinition addPP (p q : poly) : poly :=\n  make_poly (p ++ q).\n\nLemma addPP_refold : forall p q,\n  make_poly (p ++ q) = addPP p q.\nProof.\n  auto.\nQed.\n\nLemma addPP_is_poly : forall p q,\n  is_poly (addPP p q).\nProof.\n  intros p q. apply make_poly_is_poly.\nQed.\n\n(** Similarly, the definition for multiplication becomes much easier with the\n    creation of [make_poly]. All we need to do is use our [distribute] function\n    defined earlier to form all combinations of one monomial from each list, and\n    call [make_poly] on the result. *)\n\nDefinition mulPP (p q : poly) : poly :=\n  make_poly (distribute p q).\n\nLemma mulPP_is_poly : forall p q,\n  is_poly (mulPP p q).\nProof.\n  intros p q. apply make_poly_is_poly.\nQed.\n\nHint Resolve addPP_is_poly mulPP_is_poly.\n\n(** While this definition is elegant, sometimes it is hard to work with. This\n    has led us to also create a few more definitions of multiplication. Each is\n    just slightly different from the last, which allows us to choose the level\n    of completeness we need for any given multiplication proof while knowing\n    that at the end of the day, they are all equivalent.\n\n    Each of these new definitions breaks down multiplication into two steps -\n    mutliplying a monomial times a polynomial, and multiplying a polynomial\n    times a polynomial. Multiplying a monomial times a polynomial is simply\n    appending the monomial to each monomial in the polynomial, and multiplying\n    two polynomials is just multiplying each monomial in one polynomial times\n    the other polynomial.\n\n    The difference in each of the following definitions comes from the\n    intermediate step. Because we know that [mulPP] will call [make_poly], there\n    is no need to call [make_poly] on the result of [mulMP], as shown in the\n    first definition. However, some proofs are made easier if the result of\n    [mulMP] is wrapped in [map make_mono], and some are made easier if the\n    result is wrapped in a full [make_poly]. As a result, we have created each\n    of these definitions, and choose between them to help make our proofs\n    easier.\n\n    We also include a refolding method for each, for convenience, and a proof\n    that each new version is equivalent to the last. *)\n\nDefinition mulMP (p : poly) (m : mono) : poly := \n  map (app m) p.\n\nDefinition mulPP' (p q : poly) : poly :=\n  make_poly (concat (map (mulMP p) q)).\n\nLemma mulPP'_refold : forall p q,\n  make_poly (concat (map (mulMP p) q)) =\n  mulPP' p q.\nProof. auto. Qed.\n\nLemma mulPP_mulPP' : forall (p q : poly),\n  mulPP p q = mulPP' p q.\nProof.\n  intros p q. unfold mulPP, mulPP'. induction q; auto.\nQed.\n\n(** Next, the version including a [map make_mono]: *)\n\nDefinition mulMP' (p : poly) (m : mono) : poly :=\n  map make_mono (map (app m) p).\n\nDefinition mulPP'' (p q : poly) : poly :=\n  make_poly (concat (map (mulMP' p) q)).\n\nLemma mulPP''_refold : forall p q,\n  make_poly (concat (map (mulMP' p) q)) =\n  mulPP'' p q.\nProof. auto. Qed.\n\nLemma mulPP'_mulPP'' : forall p q,\n  mulPP' p q = mulPP'' p q.\nProof.\n  intros p q. unfold mulPP', mulPP'', mulMP, mulMP', make_poly.\n  rewrite concat_map_map.\n  rewrite (no_map_make_mono (map _ _)); auto.\n  intros. apply in_map_iff in H as [n []].\n  rewrite <- H.\n  auto.\nQed.\n\n(** And finally, the version including a full [make_poly]: *)\n\nDefinition mulMP'' (p : poly) (m : mono) : poly :=\n  make_poly (map (app m) p).\n\nDefinition mulPP''' (p q : poly) : poly :=\n  make_poly (concat (map (mulMP'' p) q)).\n\nLemma mulPP'''_refold : forall p q,\n  make_poly (concat (map (mulMP'' p) q)) =\n  mulPP''' p q.\nProof. auto. Qed.\n\n(** In order to make the proof of going from [mulPP''] to [mulPP'''] easier, we\n    begin by proving that we can go from their corresponding [mulMP]s if they\n    are wrapped in a [make_poly]. *)\n\nLemma mulMP'_mulMP'' : forall m p q,\n  make_poly (mulMP' p m ++ q) = make_poly (mulMP'' p m ++ q).\nProof.\n  intros m p q. unfold mulMP', mulMP''. rewrite make_poly_app_comm.\n  rewrite <- map_make_mono_pointless. rewrite make_poly_app_comm.\n  rewrite <- make_poly_pointless. unfold make_poly at 2.\n  rewrite (no_map_make_mono (map make_mono _)). unfold make_poly at 3.\n  rewrite (make_poly_app_comm _ q). rewrite <- (map_make_mono_pointless q).\n  rewrite make_poly_app_comm. auto. apply mono_in_map_make_mono.\nQed.\n\nLemma mulPP''_mulPP''' : forall p q,\n  mulPP'' p q = mulPP''' p q.\nProof.\n  intros p q. induction q. auto. unfold mulPP'', mulPP'''. simpl.\n  rewrite mulMP'_mulMP''.\n  repeat rewrite <- (make_poly_pointless_r _ (concat _)).\n  f_equal. f_equal. apply IHq.\nQed.\n\n(** Again, for convenience, we add lemmas to skip from [mulPP] to any of the\n    other varieties. *)\n\nLemma mulPP_mulPP'' : forall p q,\n  mulPP p q = mulPP'' p q.\nProof.\n  intros. rewrite mulPP_mulPP', mulPP'_mulPP''. auto.\nQed.\n\nLemma mulPP_mulPP''' : forall p q,\n  mulPP p q = mulPP''' p q.\nProof.\n  intros. rewrite mulPP_mulPP'', mulPP''_mulPP'''. auto.\nQed.\n\nHint Unfold addPP mulPP mulPP' mulPP'' mulPP''' mulMP mulMP' mulMP''.\n\n\n\n\n(** * Proving the 10 [B]-unification Axioms *)\n\n(** Now that we have defined our operations so carefully, we want to prove that\n    the 10 standard [B]-unification axioms all apply. This is extremely\n    important, as they will both be needed in the higher-level proofs of our\n    unification algorithm, and they show that our list-of-list setup is actually\n    correct and equivalent to any other representation of a term. *)\n\n\n(** ** Axiom 1: Additive Inverse *)\n\n(** We begin with the inverse and identity for each addition and multiplication.\n    First is the additive inverse, which states that forall terms [x],\n    $(x + x)\\downarrow_{P} 0$.\n\n    Thanks to the definition of [nodup_cancel] and the previously proven\n    [nodup_cancel_self], this proof is extremely simple. *)\n\nLemma addPP_p_p : forall p,\n  addPP p p = [].\nProof.\n  intros p. unfold addPP. unfold make_poly. rewrite map_app.\n  rewrite nodup_cancel_self. auto.\nQed.\n\n\n(** ** Axiom 2: Additive Identity *)\n\n(** Next, we prove the additive identity: for all terms [x],\n    $(0 + x)\\downarrow_{P} = x\\downarrow_{P}$. This also applies in the right\n    direction, and is extremely easy to prove since we already know that\n    appending [nil] to a list results in that list.\n\n    Something to note is that, unlike some of the other of the ten axioms, this\n    one is _only_ true if [p] is already a polynomial. Clearly, if it wasn't,\n    [addPP] would not return the same [p], but rather [make_poly p], since\n    [addPP] will only return proper polynomials. *)\n\nLemma addPP_0 : forall p,\n  is_poly p ->\n  addPP [] p = p.\nProof.\n  intros p Hpoly. unfold addPP. simpl. apply no_make_poly. auto.\nQed.\n\nLemma addPP_0r : forall p,\n  is_poly p ->\n  addPP p [] = p.\nProof.\n  intros p Hpoly. unfold addPP. rewrite app_nil_r. apply no_make_poly. auto.\nQed.\n\n\n\n(** ** Axiom 3: Multiplicative Identity - [1] *)\n\n(** Now onto multiplication. In [B]-unification, there are _two_ multiplicative\n    identities. We begin with the easier to prove of the two, which is [1]. In\n    other words, for any term [x], $(x \\ast 1)\\downarrow_{P} = x\\downarrow_{P}$.\n\n    This proof is also very simply proved because of how appending [nil] works.\n    *)\n\nLemma mulPP_1r : forall p,\n  is_poly p ->\n  mulPP p [[]] = p.\nProof.\n  intros p H. unfold mulPP, distribute. simpl. rewrite app_nil_r.\n  rewrite map_id. apply no_make_poly. auto.\nQed.\n\n\n\n(** ** Axiom 4: Multiplicative Inverse *)\n\n(** Next is the multiplicative inverse, which states that for any term [x],\n    $(0 \\ast x)\\downarrow_{P} = 0$.\n\n    This is proven immediately by the [distribute_nil] lemmas we proved in\n    [list_util]. *)\n\nLemma mulPP_0 : forall p,\n  mulPP [] p = [].\nProof.\n  intros p. unfold mulPP. rewrite (@distribute_nil var). auto.\nQed.\n\nLemma mulPP_0r : forall p,\n  mulPP p [] = [].\nProof.\n  intros p. unfold mulPP. rewrite (@distribute_nil_r var). auto.\nQed.\n\n\n\n(** ** Axiom 5: Commutativity of Addition *)\n\n(** The next of the ten axioms states that, for all terms [x] and [y],\n    $(x + y)\\downarrow_{P} = (y + x)\\downarrow_{P}$.\n\n    This axiom is also rather easy, and follows entirely from the\n    [make_poly_app_comm] lemma we proved earlier due to our clever addition\n    definition. *)\n\nLemma addPP_comm : forall p q,\n  addPP p q = addPP q p.\nProof.\n  intros p q. unfold addPP. apply make_poly_app_comm.\nQed.\n\n\n(** ** Axiom 6: Associativity of Addition *)\n\n(** The next axiom states that, for all terms [x], [y], and [z],\n    $(x + (y + z))\\downarrow_{P} = ((x + y) + z)\\downarrow_{P}$.\n\n    Thanks to [addPP_comm] and all of the \"pointless\" lemmas we proved earlier,\n    this proof is much easier than it might have been otherwise. These lemmas\n    allow us to easily manipulate the operations until we end by proving that\n    [p ++ q ++ r] is a permutation of [q ++ r ++ p]. *)\n\nLemma addPP_assoc : forall p q r,\n  addPP (addPP p q) r = addPP p (addPP q r).\nProof.\n  intros p q r. rewrite (addPP_comm _ (addPP _ _)). unfold addPP.\n  repeat rewrite make_poly_pointless. repeat rewrite <- app_assoc.\n  apply Permutation_sort_eq. apply nodup_cancel_Permutation.\n  apply Permutation_map. rewrite (app_assoc q).\n  apply Permutation_app_comm with (l':=q ++ r).\nQed.\n\n\n(** ** Axiom 7: Commutativity of Multiplication *)\n\n(** Now onto the harder half of the axioms. This next one states that for all\n    terms [x] and [y], $(x \\ast y)\\downarrow_{P} = (y \\ast x)\\downarrow_{P}$. In\n    order to prove this, we have opted to use the second version of [mulPP],\n    which wraps the monomial multiplication in a [map make_mono].\n\n    The proof begins with double induction, and the first three cases are rather\n    simple. The fourth case is slightly more complicated, but the\n    [make_poly_pointless] lemma we proved earlier plays a huge role in making it\n    simpler. We begin by simplifying, so that the [m] created by induction on\n    [q] is distributed across the list on the left side, and the [a] created by\n    induction on [p] is distributed accross the list on the right side. Then, we\n    use [make_poly_pointless] to surround the rightmost term - which now has [a]\n    but not [m] on the left and [m] but not [a] on the right - with [make_poly].\n    This additional [make_poly] allows us to refold the mess of [map]s and\n    [concat]s into [mulPP], like they used to be. From there, we use the two\n    induction hypotheses to apply commutativity, remove the redundant\n    [make_poly]s we added, and simplify again.\n\n    In this way, we are able to cause both [a] and [m] to be distributed across\n    the whole list on both the left and right sides of the equation. At this\n    point, it simply requires some rearranging of [app] with the help of\n    [Permutation], and our left and right sides are equal.\n\n    Without the help of [make_poly_pointless], we would not have been able to\n    use the induction hypotheses until much later in the proof, and the proof\n    would have been dramatically longer. This also makes it more readable as\n    you step through the proof, as we can seamlessly move between the original\n    form including [mulPP] and the more functional form consisting of [map]\n    and [concat]. *)\n\nLemma mulPP_comm : forall p q,\n  mulPP p q = mulPP q p.\nProof.\n  intros p q. repeat rewrite mulPP_mulPP''.\n  generalize dependent q. induction p; induction q as [|m].\n  - auto.\n  - unfold mulPP'', mulMP'. simpl. rewrite (@concat_map_nil mono). auto.\n  - unfold mulPP'', mulMP'. simpl. rewrite (@concat_map_nil mono). auto.\n  - unfold mulPP''. simpl. rewrite (app_comm_cons _ _ (make_mono (a++m))).\n    rewrite <- make_poly_pointless_r. rewrite mulPP''_refold. rewrite <- IHp.\n    unfold mulPP''. rewrite make_poly_pointless_r. simpl. unfold mulMP' at 2.\n    rewrite app_comm_cons. rewrite <- make_poly_pointless_r.\n    rewrite mulPP''_refold. rewrite IHq. unfold mulPP''.\n    rewrite make_poly_pointless_r. simpl. unfold mulMP' at 1.\n    rewrite app_comm_cons. rewrite app_assoc. rewrite <- make_poly_pointless_r.\n    rewrite mulPP''_refold. rewrite <- IHp. unfold mulPP''.\n    rewrite make_poly_pointless_r. simpl. rewrite (app_assoc (map _ (map _ q))).\n    apply Permutation_sort_eq. apply nodup_cancel_Permutation.\n    apply Permutation_map. rewrite make_mono_app_comm. apply perm_skip.\n    apply Permutation_app_tail. apply Permutation_app_comm.\nQed.\n\n\n\n(** ** Axiom 8: Associativity of Multiplication *)\n\n(** The eigth axiom states that, for all terms [x], [y], and [z],\n    $(x \\ast (y \\ast z))\\downarrow_{P} = ((x \\ast y) \\ast z)\\downarrow_{P}$.\n\n    This one is also fairly complicated, so we will start small and build up to\n    it. First, we prove a convenient side effect of [make_poly_pointless], which\n    allows us to simplify [mulPP] into a [mulMP] and a [mulPP]. Unlike\n    commutativity, for this proof we opt to use the version of [mulPP] that\n    includes a [make_poly] in its [mulMP], in addition to the [map make_mono]\n    version used previously. *)\n\nLemma mulPP''_cons : forall q a p,\n  make_poly (mulMP' q a ++ mulPP'' q p) =\n  mulPP'' q (a::p).\nProof.\n  intros q a p. unfold mulPP''. rewrite make_poly_pointless_r. auto.\nQed.\n\n(** Next is a deceptively easy lemma [map_app_make_poly], which is the primary\n    application of [nodup_cancel_map], proven in [list_util]. It states that if\n    we are applying [make_poly] twice, we can remove the second application,\n    even if there is a [map app] in between them. Clearly, here, the [map app]\n    is in reference to [mulMP]. *)\n\nLemma map_app_make_poly : forall m p,\n  (forall a, In a p -> is_mono a) ->\n  make_poly (map (app m) (make_poly p)) = make_poly (map (app m) p).\nProof.\n  intros m p Hm. apply Permutation_sort_eq.\n  apply Permutation_trans with (l':=(nodup_cancel mono_eq_dec (map make_mono\n    (map (app m) (nodup_cancel mono_eq_dec (map make_mono p)))))).\n    apply nodup_cancel_Permutation. repeat apply Permutation_map.\n    unfold make_poly. rewrite <- Permutation_MonoSort_l. auto.\n  rewrite (no_map_make_mono p); auto. repeat rewrite map_map.\n  apply nodup_cancel_map.\nQed.\n\n(** The [map_app_make_poly] lemma is then immediately applied here, to state\n    that since [mulMP''] already applies [make_poly] to its result, we can\n    remove any [make_poly] calls inside. *)\n\nLemma mulMP''_make_poly : forall p m,\n  (forall a, In a p -> is_mono a) ->\n  mulMP'' (make_poly p) m =\n  mulMP'' p m.\nProof.\n  intros p m. unfold mulMP''. apply map_app_make_poly.\nQed.\n\n(** This very simple lemma states that since [mulMP] is effectively just a\n    [map], it distributes over [app]. *)\n\nLemma mulMP'_app : forall p q m,\n  mulMP' (p ++ q) m =\n  mulMP' p m ++ mulMP' q m.\nProof.\n  intros p q m. unfold mulMP'. repeat rewrite map_app. auto.\nQed.\n\n(** Now into the meat of the associativity proof. We begin by proving that\n    [mulMP'] is associative. This proof is straightforward, and is proven by\n    induction with the use of [make_mono_pointless] and\n    [Permutation_sort_mono_eq]. *)\n\nLemma mulMP'_assoc : forall q a m,\n  mulMP' (mulMP' q a) m =\n  mulMP' (mulMP' q m) a.\nProof.\n  intros q a m. unfold mulMP'. induction q; auto.\n  simpl. repeat rewrite make_mono_pointless. f_equal.\n  - apply Permutation_sort_mono_eq. apply Permutation_nodup.\n    repeat rewrite app_assoc. apply Permutation_app_tail.\n    apply Permutation_app_comm.\n  - apply IHq.\nQed.\n\n(** For the final associativity proof, we begin by using the commutativity lemma\n    to make it so that [q] is on the leftmost side of the multiplications. This\n    means that it will never be the polynomial being mapped across, and allows\n    us to do induction on just [p] and [r] instead of all three. Thus [p]\n    becomes [a :: p], and [r] becomes [m :: r].\n\n    The first three cases are easily solved with some rewrites and a call to\n    auto, so we move on to the fourth. Similarly to the commutativity proof, the\n    main struggle here is forcing [mulPP] to map across the same term on both\n    sides of the equation. This is accomplished in a very similar way - by\n    simplifying, using [make_poly_pointless] to get [mulPP] back in the goal,\n    and then applying the two induction hypotheses to reorder the terms.\n\n    The crucial point is when we rewrite with [mulMP'_mulMP''], allowing us to\n    wrap our [mulMP]s in [make_poly] and make use of the lemmas we proved\n    earlier in this section. This technique enables us to reorder the\n    multiplications in a way that is convenient for us;\n    $((q \\ast [a :: p]) \\ast m)\\downarrow_{P}$ becomes\n    $((q \\ast a) \\ast m)\\downarrow_{P} ++ ((q \\ast p) \\ast m)\\downarrow_{P}$. At\n    the end of all of this rewriting, we are left with the original\n    $(p \\ast q \\ast r)\\downarrow_{P}$ as the last term of both sides, and\n    $(q \\ast p \\ast m)\\downarrow_{P}$ and $(q \\ast r \\ast a)\\downarrow_{P}$ as\n    the middle terms of both. These three terms are easily eliminated with the\n    standard [Permutation] lemmas, because they are on both sides.\n\n    The only remaining challenge comes from the first term on each side; on the\n    left, we have $((q \\ast a) \\ast m)\\downarrow_{P}$, and on the right we have\n    $((q \\ast m) \\ast a)\\downarrow_{P}$. This is where the above [mulMP'_assoc]\n    lemma comes into play, solving the last piece of the associativity lemma. *)\n\nLemma mulPP_assoc : forall p q r,\n  mulPP (mulPP p q) r = mulPP p (mulPP q r).\nProof.\n  intros p q r. rewrite (mulPP_comm _ (mulPP q _)). rewrite (mulPP_comm p _).\n  generalize dependent r. induction p; induction r as [|m];\n  repeat rewrite mulPP_0; repeat rewrite mulPP_0r; auto.\n  repeat rewrite mulPP_mulPP'' in *. unfold mulPP''. simpl.\n  repeat rewrite <- (make_poly_pointless_r _ (concat _)).\n  repeat rewrite mulPP''_refold. repeat rewrite (mulPP''_cons q).\n  pose (IHp (m::r)). repeat rewrite mulPP_mulPP'' in e. rewrite <- e.\n  rewrite IHr. unfold mulPP'' at 2, mulPP'' at 4. simpl.\n  repeat rewrite make_poly_pointless_r. repeat rewrite app_assoc.\n  repeat rewrite <- (make_poly_pointless_r _ (concat _)).\n  repeat rewrite mulPP''_refold. pose (IHp r).\n  repeat rewrite mulPP_mulPP'' in e0. rewrite <- e0.\n  repeat rewrite <- app_assoc. repeat rewrite mulMP'_mulMP''.\n  repeat rewrite <- mulPP''_cons. repeat rewrite mulMP''_make_poly.\n  repeat rewrite <- mulMP'_mulMP''. repeat rewrite app_assoc.\n  apply Permutation_sort_eq. apply nodup_cancel_Permutation.\n  apply Permutation_map. apply Permutation_app_tail. repeat rewrite mulMP'_app.\n  rewrite mulMP'_assoc. repeat rewrite <- app_assoc. apply Permutation_app_head.\n  apply Permutation_app_comm. intros a0 Hin. apply in_app_iff in Hin as [].\n  unfold mulMP' in H. apply in_map_iff in H as [x[]]. rewrite <- H; auto.\n  apply (make_poly_is_poly (concat (map (mulMP' q) r))). auto.\n  intros a0 Hin. apply in_app_iff in Hin as []. unfold mulMP' in H.\n  apply in_map_iff in H as [x[]]. rewrite <- H; auto.\n  apply (make_poly_is_poly (concat (map (mulMP' q) p))). auto.\nQed.\n\n\n\n(** ** Axiom 9: Multiplicative Identity - Self *)\n\n(** Next comes the other multiplicative identity mentioned earlier. This axiom\n    states that for all terms [x], $(x * x)\\downarrow_{P} = x\\downarrow_{P}$.\n\n    To begin, we prove that this holds for monomials;\n    $(m \\ast m)\\downarrow_{P} = m\\downarrow_{P}$. This proof uses a combination\n    of [Permutation_Sorted_mono_eq] and induction. We then use the standard\n    [Permutation] lemmas to move the induction variable [a] out to the front,\n    and show that [nodup] removes one of the two [a]s. After that, [perm_skip]\n    and the induction hypothesis solve the lemma. *)\n\nLemma make_mono_self : forall m,\n  is_mono m ->\n  make_mono (m ++ m) = m.\nProof.\n  intros m H. apply Permutation_Sorted_mono_eq.\n  - induction m; auto. unfold make_mono. rewrite <- Permutation_VarSort_l.\n    simpl. assert (In a (m ++ a :: m)).\n      intuition. destruct in_dec; try contradiction.\n    apply Permutation_trans with (l':=nodup var_eq_dec (a :: m ++ m)).\n       apply Permutation_nodup. apply Permutation_app_comm.\n    simpl. assert (~ In a (m ++ m)).\n      apply NoDup_VarSorted in H as H1. apply NoDup_cons_iff in H1.\n    intro. apply H1. apply in_app_iff in H2; intuition.\n    destruct in_dec; try contradiction. apply perm_skip.\n    apply Permutation_VarSort_l in IHm. auto. apply (mono_cons _ _ H).\n  - apply VarSort.LocallySorted_sort.\n  - apply Sorted_VarSorted. apply H.\nQed.\n\n(** The full proof of the self multiplicative identity is much longer, but in a\n    way very similar to the proof of commutativity. We begin by doing induction\n    and simplifying, which distributes _one_ of the induction variables across\n    the list on the left side. This leaves us with $a \\ast a$ as the leftmost\n    term, which is easily replaced with [a] with the above lemma and then\n    removed from both sides with [perm_skip].\n\n    At this point we are left with a goal of the form\n    $(a \\ast [a :: p])\\downarrow_{P} ++ ([a :: p] \\ast p)\\downarrow_{P} =\n    p\\downarrow_{P}$ which is not particularly easy to deal with. However, by\n    rewriting with [mulPP_comm], we can force the second term on the left to\n    simplify futher.\n\n    This leaves us with something along the lines of\n    $(a \\ast [a :: p])\\downarrow_{P} ++ (a \\ast [a :: p])\\downarrow_{P} ++\n    (p \\ast p)\\downarrow_{P} = p\\downarrow_{P}$ which is much more workable! We\n    know that $(p \\ast p)\\downarrow_{P} = p\\downarrow_{P}$ from the induction\n    hypothesis, so this is then removed from both sides and all that is left is\n    to prove that the same term added together twice is equal to an empty list.\n    This follows from the [nodup_cancel_self] lemma used to prove [addPP_p_p],\n    and finished the proof of this lemma. *)\n\nLemma mulPP_p_p : forall p,\n  is_poly p ->\n  mulPP p p = p.\nProof.\n  intros p H. rewrite mulPP_mulPP'. rewrite mulPP'_mulPP''.\n  apply Permutation_Sorted_eq.\n  - induction p; auto. unfold mulPP'', make_poly.\n    rewrite <- Permutation_MonoSort_l. simpl map at 1.\n    apply poly_cons in H as H1. destruct H1. rewrite make_mono_self; auto.\n    rewrite no_make_mono; auto. rewrite map_app. apply Permutation_trans with\n      (l':=nodup_cancel mono_eq_dec (map make_mono (concat (map (mulMP' (a ::\n      p)) p)) ++ a :: map make_mono (map make_mono (map (app a) p)))).\n      apply nodup_cancel_Permutation. rewrite app_comm_cons.\n      apply Permutation_app_comm.\n    rewrite <- nodup_cancel_pointless. apply Permutation_trans with\n      (l':=nodup_cancel mono_eq_dec ((nodup_cancel mono_eq_dec (map make_mono\n      (concat (map (mulMP' p) (a :: p))))) ++ (a :: map make_mono (map make_mono\n      (map (app a) p))))). apply nodup_cancel_Permutation.\n      apply Permutation_app_tail. apply Permutation_sort_eq.\n      repeat rewrite make_poly_refold. repeat rewrite mulPP''_refold.\n      repeat rewrite <- mulPP'_mulPP''. repeat rewrite <- mulPP_mulPP'.\n      apply mulPP_comm.\n    rewrite nodup_cancel_pointless. apply Permutation_trans with\n      (l':=nodup_cancel mono_eq_dec (a :: map make_mono (map make_mono (map\n      (app a) p)) ++ (map make_mono (concat (map (mulMP' p) (a :: p)))))).\n      apply nodup_cancel_Permutation. apply Permutation_app_comm.\n    simpl map. rewrite map_app. unfold mulMP' at 1.\n    repeat rewrite (no_map_make_mono (map make_mono _));\n    try apply mono_in_map_make_mono. rewrite (app_assoc (map _ _)).\n    apply Permutation_trans with (l':=nodup_cancel mono_eq_dec ((map make_mono\n      (map (app a) p) ++ map make_mono (map (app a) p)) ++ a :: map make_mono\n      (concat (map (mulMP' p) p)))). apply nodup_cancel_Permutation.\n      apply Permutation_middle. rewrite <- nodup_cancel_pointless.\n      rewrite nodup_cancel_self. simpl app.\n    apply Permutation_trans with (l':=nodup_cancel mono_eq_dec (map make_mono\n      (concat (map (mulMP' p) p)) ++ [a])). apply nodup_cancel_Permutation.\n      replace (a::map make_mono (concat (map (mulMP' p) p))) with ([a] ++ map\n      make_mono (concat (map (mulMP' p) p))); auto. apply Permutation_app_comm.\n    rewrite <- nodup_cancel_pointless. apply Permutation_trans with\n      (l':=nodup_cancel mono_eq_dec (p ++ [a])). apply nodup_cancel_Permutation.\n      apply Permutation_app_tail. unfold mulPP'', make_poly in IHp.\n      rewrite <- Permutation_MonoSort_l in IHp. apply IHp; auto.\n    replace (a::p) with ([a]++p); auto. rewrite no_nodup_cancel_NoDup.\n    apply Permutation_app_comm. apply Permutation_NoDup with (l:=a :: p).\n    replace (a::p) with ([a]++p); auto. apply Permutation_app_comm.\n    destruct H. apply NoDup_MonoSorted in H. auto.\n  - unfold make_poly. apply LocallySorted_sort.\n  - apply Sorted_MonoSorted. apply H.\nQed.\n\n\n\n(** ** Axiom 10: Distribution *)\n\n(** Finally, we are left with the most intimidating of the axioms -\n    distribution. This states, as one would expect, that for all terms [x], [y],\n    and [z],\n    $(x \\ast (y + z))\\downarrow_{P} = ((x * y) + (x * z)\\downarrow_{P}$.\n\n    In a similar approach to what we have done for some of the other lemmas, we\n    begin by proving this on a smaller scale, working with just [mulMP] and\n    [addPP]. This lemma is once again solved easily by the [map_app_make_poly]\n    we proved while working on multiplication associativity, combined with\n    [make_poly_pointless]. *)\n\nLemma mulMP''_distr_addPP : forall m p q,\n  is_poly p -> is_poly q ->\n  mulMP'' (addPP p q) m = addPP (mulMP'' p m) (mulMP'' q m).\nProof.\n  intros m p q Hp Hq. unfold mulMP'', addPP. rewrite map_app_make_poly.\n  rewrite make_poly_pointless. rewrite make_poly_app_comm.\n  rewrite make_poly_pointless. rewrite make_poly_app_comm.\n  rewrite map_app. auto. intros a Hin. apply in_app_iff in Hin as [].\n  apply Hp. auto. apply Hq. auto.\nQed.\n\n(** For the distribution proof itself, we begin by performing induction on [r],\n    the element outside of the [addPP] call initially. We begin by simplifying,\n    and using the usual combination of [make_poly_pointless] and refolding to\n    convert our goal to a form of\n    $((p + q) \\ast a)\\downarrow_{P} ++ ((p + q) \\ast r)\\downarrow_{P}$.\n\n    We then apply similar tactics on the right side, to convert our goal to a\n    form similar to $(p \\ast a + q \\ast a + p \\ast r + q \\ast r)\\downarrow_{P}$.\n    The two terms containing [r] are easy to deal with, since we know they are\n    equal to the $((p + q) \\ast r)\\downarrow_{P}$ we have on the left side due\n    to the induction hypothesis. Similarly, the first two terms are known to be\n    equal to $((p + q) \\ast a)\\downarrow_{P}$ from the [mulMP_distr_addPP] lemma\n    we just proved. This results in us having the same thing on both sides, thus\n    solving the final of the ten [B]-unification axioms. *)\n\nLemma mulPP_distr_addPP : forall p q r,\n  is_poly p -> is_poly q ->\n  mulPP (addPP p q) r = addPP (mulPP p r) (mulPP q r).\nProof.\n  intros p q r Hp Hq. induction r; auto. rewrite mulPP_mulPP''. unfold mulPP''.\n  simpl. rewrite mulPP_mulPP'', (mulPP_mulPP'' q), make_poly_app_comm.\n  rewrite <- make_poly_pointless. rewrite make_poly_app_comm.\n  rewrite mulPP''_refold.\n  rewrite addPP_refold. repeat unfold mulPP'' at 2. simpl. unfold addPP at 4.\n  rewrite make_poly_pointless. rewrite addPP_refold.\n  rewrite (addPP_comm _ (make_poly _)).\n  unfold addPP at 4. rewrite make_poly_pointless. rewrite <- app_assoc.\n  rewrite make_poly_app_comm. rewrite <- app_assoc.\n  rewrite <- make_poly_pointless.\n  rewrite mulPP''_refold. rewrite <- app_assoc. rewrite app_assoc.\n  rewrite make_poly_app_comm.\n  rewrite <- app_assoc. rewrite <- make_poly_pointless. rewrite mulPP''_refold.\n  replace (make_poly (mulPP'' p r ++ mulMP' q a ++ mulPP'' q r ++ mulMP' p a))\n    with (make_poly ((mulPP'' p r ++ mulPP'' q r) ++ mulMP' p a ++ mulMP' q a)).\n  rewrite <- make_poly_pointless. rewrite (addPP_refold (mulPP'' _ _)).\n  rewrite make_poly_app_comm. rewrite addPP_refold.\n  rewrite mulPP_mulPP'', (mulPP_mulPP'' p), (mulPP_mulPP'' q) in IHr.\n  rewrite <- IHr. unfold addPP at 4.\n  rewrite <- make_poly_pointless. unfold addPP. repeat rewrite mulMP'_mulMP''.\n  rewrite (make_poly_app_comm (mulMP'' _ _) (mulMP' _ _)).\n  rewrite mulMP'_mulMP''.\n  rewrite (make_poly_app_comm (mulMP'' _ _) (mulMP'' _ _)).\n  repeat rewrite addPP_refold. f_equal. apply mulMP''_distr_addPP; auto.\n  apply make_poly_Permutation. rewrite <- app_assoc.\n  apply Permutation_app_head. rewrite app_assoc.\n  apply Permutation_trans with\n    (l':=mulMP' q a ++ mulPP'' q r ++ mulMP' p a).\n  apply Permutation_app_comm.\n  auto.\nQed.\n\n(** For convenience, we also prove that distribution can be applied from the\n    right, which follows from [mulPP_comm] and the distribution lemma we just\n    proved. *)\n\nLemma mulPP_distr_addPPr : forall p q r,\n  is_poly p -> is_poly q ->\n  mulPP r (addPP p q) = addPP (mulPP r p) (mulPP r q).\nProof.\n  intros p q r Hp Hq. rewrite mulPP_comm. rewrite (mulPP_comm r p).\n  rewrite (mulPP_comm r q). apply mulPP_distr_addPP; auto.\nQed.\n\n\n\n(** * Other Facts About Polynomials *)\n\n(** Now that we have proven the core ten axioms proven, there are a few more\n    useful lemmas that we will prove to assist us in future parts of the\n    development. *)\n\n(** ** More Arithmetic *)\n\n(** Occasionally, when dealing with multiplication, we already know that one of\n    the variables being multiplied in is less than the rest, meaning it would\n    end up at the front of the list after sorting. For convenience and to bypass\n    the work of dealing with the calls to [sort] and [nodup_cancel], the below\n    lemma allows us to rewrite with this concept. *)\n\nLemma mulPP_mono_cons : forall x m,\n  is_mono (x :: m) ->\n  mulPP [[x]] [m] = [x :: m].\nProof.\n  intros x m H. unfold mulPP, distribute. simpl. apply Permutation_Sorted_eq.\n  - apply Permutation_trans with\n      (l':=nodup_cancel mono_eq_dec (map make_mono [m ++ [x]])).\n    apply Permutation_sym. apply Permuted_sort. rewrite no_nodup_cancel_NoDup.\n    simpl. assert (make_mono (m ++ [x]) = x :: m).\n    + rewrite <- no_make_mono; auto. apply Permutation_sort_mono_eq.\n      repeat rewrite no_nodup_NoDup. replace (x :: m) with ([x] ++ m); auto;\n      apply Permutation_app_comm. apply NoDup_VarSorted; apply H.\n      apply Permutation_NoDup with (l:=x :: m).\n      replace (x :: m) with ([x] ++ m); auto; apply Permutation_app_comm.\n      apply NoDup_VarSorted; apply H.\n    + rewrite H0. auto.\n    + apply NoDup_cons; auto.\n  - apply LocallySorted_sort.\n  - apply Sorted_cons; auto.\nQed.\n\n(** Similarly, if we already know some monomial is less than the polynomials it\n    is being added to, then the monomial will clearly end up at the front of the\n    list. *)\n\nLemma addPP_poly_cons : forall m p,\n  is_poly (m :: p) ->\n  addPP [m] p = m :: p.\nProof.\n  intros m p H. unfold addPP. simpl. rewrite no_make_poly; auto.\nQed.\n\n(** An interesting arithmetic fact is that if we multiply the term\n    $((p \\ast q) + r)\\downarrow_{P}$ by $(1 + q)\\downarrow_{P}$, we\n    effectively eliminate the $(p \\ast q)\\downarrow_{P}$ term and are left with\n    $((1 + q) \\ast r)\\downarrow_{P}$. This will come into play later in the\n    development, as we look to begin building unifiers. *)\n\nLemma mulPP_addPP_1 : forall p q r,\n  is_poly p -> is_poly q -> is_poly r ->\n  mulPP (addPP (mulPP p q) r) (addPP [[]] q) =\n  mulPP (addPP [[]] q) r.\nProof.\n  intros p q r Hp Hq Hr. rewrite mulPP_distr_addPP; auto.\n  rewrite mulPP_distr_addPPr; auto. rewrite mulPP_1r; auto.\n  rewrite mulPP_assoc. rewrite mulPP_p_p; auto. rewrite addPP_p_p; auto.\n  rewrite addPP_0; auto. rewrite mulPP_comm. auto.\nQed.\n\n(** ** Reasoning about Variables *)\n\n(** To more easily deal with the [vars] definition, we have defined a few\n    definitions about it. First, if some [x] is in the variables of\n    [make_poly p], then it must have been in the vars of [p] originally. Note\n    that this is not true in the other direction, as [nodup_cancel] may remove\n    some variables. *)\n\nLemma make_poly_rem_vars : forall p x,\n  In x (vars (make_poly p)) ->\n  In x (vars p).\nProof.\n  intros p x H. induction p.\n  - inversion H.\n  - unfold vars. simpl. apply nodup_In. apply in_app_iff.\n    unfold vars, make_poly in H. apply nodup_In in H.\n    apply In_concat_exists in H as [m []].\n    apply In_sorted in H. apply nodup_cancel_in in H.\n    apply in_map_iff in H as [n []]. destruct H1.\n    + left. apply make_mono_In. rewrite H1. rewrite H. auto.\n    + right. apply In_concat_exists. exists n. split; auto. apply make_mono_In.\n      rewrite H. auto.\nQed.\n\n(** An interesting observation about [addPP] and our [vars] function is that\n    clearly, the variables of some $(p + q)\\downarrow_{P}$ is a subset of the\n    variables of [p] combined with the variables of [q]. The next lemma is a\n    more convenient formulation of that fact, using a list of variables [xs]\n    rather than comparing them directly. *)\n\nLemma incl_vars_addPP : forall p q xs,\n  incl (vars p) xs /\\ incl (vars q) xs ->\n  incl (vars (addPP p q)) xs.\nProof.\n  unfold incl, addPP.\n  intros p q xs [HinP HinQ] x HinPQ.\n  apply make_poly_rem_vars in HinPQ.\n  unfold vars in HinPQ.\n  apply nodup_In in HinPQ.\n  rewrite concat_app in HinPQ.\n  apply in_app_or in HinPQ as [Hin | Hin].\n  - apply HinP. apply nodup_In. auto.\n  - apply HinQ. apply nodup_In. auto.\nQed.\n\n(** We would like to be able to prove a similar fact about [mulPP], but before\n    we can do so, we need to know more about the [distribute] function. This\n    lemma states that if some [a] is in the variables of [distribute l m],\n    then it must have been in either [vars l] or [vars m] originally. *)\n\nLemma In_distribute : forall (l m:poly) a,\n  In a (vars (distribute l m)) ->\n  In a (vars l) \\/ In a (vars m).\nProof.\n  intros l m a H. unfold distribute, vars in H. apply nodup_In in H.\n  apply In_concat_exists in H. destruct H as [ll[]].\n  apply In_concat_exists in H. destruct H as [ll1[]].\n  apply in_map_iff in H. destruct H as [x[]]. rewrite <- H in H1.\n  apply in_map_iff in H1. destruct H1 as [x0[]]. rewrite <- H1 in H0.\n  apply in_app_iff in H0. destruct H0.\n  - right. apply nodup_In. apply In_concat_exists. exists x. auto.\n  - left. apply nodup_In. apply In_concat_exists. exists x0. auto.\nQed.\n\n(** We can then use this fact to prove our desired fact about [mulPP]; the\n    variables of $(p \\ast q)\\downarrow_{P}$ are a subset of the variables of [p]\n    and the variables of [q]. Once again, this is formalized in a way that is\n    more convenient in later proofs, with an extra list [xs]. *)\n\nLemma incl_vars_mulPP : forall p q xs,\n  incl (vars p) xs /\\ incl (vars q) xs ->\n  incl (vars (mulPP p q)) xs.\nProof.\n  unfold incl, mulPP.\n  intros p q xs [HinP HinQ] x HinPQ.\n  apply make_poly_rem_vars in HinPQ.\n  apply In_distribute in HinPQ. destruct HinPQ.\n  - apply HinP. auto.\n  - apply HinQ. auto.\nQed.\n\n(** ** Partition with Polynomials *)\n\n(** When it comes to actually performing successive variable elimination later\n    in the development, the [partition] function will play a big role, so we\n    have opted to prove a few useful facts about its relation to polynomials\n    now.\n\n    First is that if you separate a polynomial with any function [f], you can\n    get the original polynomial back by adding together the two lists returned\n    by [partition]. This is relatively easy to prove thanks to the lemma\n    [partition_Permutation] we proved during [list_util]. *)\n\nLemma part_add_eq : forall f p l r,\n  is_poly p ->\n  partition f p = (l, r) ->\n  p = addPP l r.\nProof.\n  intros f p l r H H0. apply Permutation_Sorted_eq.\n  - generalize dependent l; generalize dependent r. induction p; intros.\n    + simpl in H0. inversion H0. auto.\n    + assert (H1:=H0); auto. apply partition_Permutation in H1. simpl in H0.\n      destruct (partition f p) as [g d]. unfold addPP, make_poly.\n      rewrite <- Permutation_MonoSort_r. rewrite unsorted_poly. destruct (f a);\n      inversion H0.\n      * rewrite <- H3 in H1. apply H1.\n      * rewrite <- H4 in H1. apply H1.\n      * destruct H. apply NoDup_MonoSorted in H. apply (Permutation_NoDup H1 H).\n      * intros m Hin. apply H. apply Permutation_sym in H1.\n        apply (Permutation_in _ H1 Hin).\n  - apply Sorted_MonoSorted. apply H.\n  - apply Sorted_MonoSorted. apply make_poly_is_poly.\nQed.\n\n(** In addition, if you [partition] some polynomial [p] with any function [f],\n    the resulting two lists will both be proper polynomials, since [partition]\n    does not affect the order. *)\n\nLemma part_is_poly : forall f p l r,\n  is_poly p ->\n  partition f p = (l, r) ->\n  is_poly l /\\ is_poly r.\nProof.\n  intros f p l r Hpoly Hpart. destruct Hpoly. split; split.\n  - apply (part_Sorted _ _ _ mono_lt_Transitive H _ _ Hpart).\n  - intros m Hin. apply H0. apply elements_in_partition with (x:=m) in Hpart.\n    apply Hpart; auto.\n  - apply (part_Sorted _ _ _ mono_lt_Transitive H _ _ Hpart).\n  - intros m Hin. apply H0. apply elements_in_partition with (x:=m) in Hpart.\n    apply Hpart; auto.\nQed.\n\n(** ** Multiplication and Remove *)\n\n(** Lastly are some rather complex lemmas relating [remove] and multiplication.\n    Similarly to the [partition] lemmas, these will come to play a large roll in\n    performing successive variable elimination later in the development.\n\n    First is an interesting fact about removing from monomials. If there are two\n    monomials which are equal after removing some [x], and either both contain\n    [x] or both do not contain [x], then they must have been equal originally.\n    This proof begins by performing double induction, and quickly solving the\n    first three cases.\n\n    The fourth case is rather long, and begins by comparing if the [a] and [a0]\n    at the head of each list are equal. The case where they are equal is\n    relatively straightforward; we must also destruct if [x = a = a0], but\n    regardless of whether they are equal or not, we can easily prove this with\n    the use of the induction hypothesis.\n\n    The case where $a \\neq a0$ should be a contradiction, as that element is at\n    the head of both lists, and we know the lists are equal after removing [x].\n    We begin by destructing whether or not [x] is in the two lists. In the case\n    where it is not in either, we can quickly solve this, as we know the call to\n    remove will do nothing, which immediately gives us the contradiction.\n\n    In the case where [x] is in both, we begin by using [in_split] to rewrite\n    both lists to contain [x]. We then use the fact that there are no duplicates\n    in either list to show that [x] is not in [l1], [l2], [l1'], or [l2'], and\n    therefore the calls to remove will do nothing. This leaves us with a\n    hypothesis that [l1 ++ l2 = l1' ++ l2']. To finish the proof, we destruct\n    [l1] and [l1'] to further compare the head of each list.\n\n    In the case where they are both empty, we arrive at a contradiction\n    immediately, as this implies the head of both lists is [x] and therefore\n    contradicts that $a \\neq a0$. In the case where they are both lists, doing\n    inversion on our remove hypothesis gives us that the head of each list is\n    equal again, also contradicting that $a \\neq a0$.\n\n    In the other two cases, we rewrite with the [in_split] hypotheses into the\n    [is_mono] hypotheses. In both cases, we result in one statement that [a]\n    comes before [a0] in the monomial, and one statement that [a0] comes before\n    [a] in the monomial. With the help of [StronglySorted], we are able to turn\n    these into [a < a0] and [a0 < a], which contradict each other to finish the\n    proof. *)\n\nLemma remove_Sorted_eq : forall x (l l':mono),\n  is_mono l -> is_mono l' ->\n  In x l <-> In x l' ->\n  remove var_eq_dec x l = remove var_eq_dec x l' ->\n  l = l'.\nProof.\n  intros x l l' Hl Hl' Hx Hrem.\n  generalize dependent l'; induction l; induction l'; intros.\n  - auto.\n  - destruct (var_eq_dec x a) eqn:Heq.\n    + rewrite e in Hx. exfalso. apply Hx. intuition.\n    + simpl in Hrem. rewrite Heq in Hrem. inversion Hrem.\n  - destruct (var_eq_dec x a) eqn:Heq.\n    + rewrite e in Hx. exfalso. apply Hx. intuition.\n    + simpl in Hrem. rewrite Heq in Hrem. inversion Hrem.\n  - clear IHl'. destruct (var_eq_dec a a0).\n    + rewrite e. f_equal. rewrite e in Hrem. simpl in Hrem.\n      apply mono_cons in Hl as Hl1. apply mono_cons in Hl' as Hl'1.\n      destruct (var_eq_dec x a0).\n      * apply IHl; auto. apply NoDup_VarSorted in Hl.\n        apply NoDup_cons_iff in Hl. rewrite e in Hl. rewrite <- e0 in Hl.\n        destruct Hl. split; intro. contradiction. apply NoDup_VarSorted in Hl'.\n        apply NoDup_cons_iff in Hl'. rewrite <- e0 in Hl'. destruct Hl'.\n        contradiction.\n      * inversion Hrem. apply IHl; auto. destruct Hx. split; intro. simpl in H.\n        rewrite e in H. destruct H; auto. rewrite H in n. contradiction.\n        simpl in H1. rewrite e in H1. destruct H1; auto. rewrite H1 in n.\n        contradiction.\n    + destruct (in_dec var_eq_dec x (a::l)).\n      * apply Hx in i as i'. apply in_split in i. apply in_split in i'.\n        destruct i as [l1[l2 i]]. destruct i' as [l1'[l2' i']].\n        pose (NoDup_VarSorted _ Hl). pose (NoDup_VarSorted _ Hl').\n        apply (NoDup_In_split _ _ _ _ i) in n0 as [].\n        apply (NoDup_In_split _ _ _ _ i') in n1 as [].\n        rewrite i in Hrem. rewrite i' in Hrem.\n        repeat rewrite remove_distr_app in Hrem. simpl in Hrem.\n        destruct (var_eq_dec x x); try contradiction.\n        repeat (rewrite not_In_remove in Hrem; auto). destruct l1; destruct l1';\n        simpl in i; simpl in i'; simpl in Hrem; inversion i; inversion i'.\n        -- rewrite H4 in n. rewrite H6 in n. contradiction.\n        -- rewrite H7 in Hl'. rewrite i in Hl. rewrite Hrem in Hl.\n           rewrite H6 in Hl'. assert (x < v). apply Sorted_inv in Hl as [].\n           apply HdRel_inv in H8. auto. assert (v < x).\n           apply Sorted_StronglySorted in Hl'.\n           apply StronglySorted_inv in Hl' as []. rewrite Forall_forall in H9.\n           apply H9. intuition. apply lt_Transitive. apply lt_asymm in H8.\n           contradiction.\n        -- rewrite H7 in Hl'. rewrite i in Hl. rewrite <- Hrem in Hl'.\n           rewrite H6 in Hl'. assert (n0 < x).\n           apply Sorted_StronglySorted in Hl.\n           apply StronglySorted_inv in Hl as []. rewrite Forall_forall in H8.\n           apply H8. intuition. apply lt_Transitive. assert (x < n0).\n           apply Sorted_inv in Hl' as []. apply HdRel_inv in H9; auto.\n           apply lt_asymm in H8. contradiction.\n        -- inversion Hrem. rewrite <- H4 in H8. rewrite <- H6 in H8.\n        contradiction.\n      * assert (~In x (a0::l')). intro. apply n0. apply Hx. auto.\n        repeat (rewrite not_In_remove in Hrem; auto).\nQed.\n\n(** Next is that if we [map remove] across a polynomial where every monomial\n    contains [x], there will still be no duplicates at the end. *)\n\nLemma NoDup_map_remove : forall x p,\n  is_poly p ->\n  (forall m, In m p -> In x m) ->\n  NoDup (map (remove var_eq_dec x) p).\nProof.\n  intros x p Hp Hx. induction p; simpl; auto.\n  apply NoDup_cons.\n  - intro. apply in_map_iff in H. destruct H as [y []]. assert (y = a).\n    + apply poly_cons in Hp. destruct Hp. unfold is_poly in H1. destruct H1.\n      apply H3 in H0 as H4. apply (remove_Sorted_eq x); auto. split; intro.\n      apply Hx. intuition. apply Hx. intuition.\n    + rewrite H1 in H0. unfold is_poly in Hp. destruct Hp.\n      apply NoDup_MonoSorted in H2 as H4. apply NoDup_cons_iff in H4 as [].\n      contradiction.\n  - apply IHp.\n    + apply poly_cons in Hp. apply Hp.\n    + intros m H. apply Hx. intuition.\nQed.\n\n(** Building off that, if every monomial in a list _does not_ contain some [x],\n    then appending [x] to every monomial and calling [make_mono] still will not\n    create any duplicates. *)\n\nLemma NoDup_map_app : forall x l,\n  is_poly l ->\n  (forall m, In m l -> ~ In x m) ->\n  NoDup (map make_mono (map (fun a => a ++ [x]) l)).\nProof.\n  intros x l Hp Hin. induction l.\n  - simpl. auto.\n  - simpl. apply NoDup_cons.\n    + intros H. rewrite map_map in H. apply in_map_iff in H as [m []].\n      assert (a = m).\n      * apply poly_cons in Hp as []. apply Permutation_Sorted_mono_eq.\n        -- apply Permutation_sort_mono_eq in H. rewrite no_nodup_NoDup in H.\n           rewrite no_nodup_NoDup in H.\n           ++ pose (Permutation_cons_append m x).\n              pose (Permutation_cons_append a x).\n              apply (Permutation_trans p) in H. apply Permutation_sym in p0.\n              apply (Permutation_trans H) in p0.\n              apply Permutation_cons_inv in p0. apply Permutation_sym. auto.\n           ++ apply Permutation_NoDup with (l:=x :: a).\n              apply Permutation_cons_append.\n              apply NoDup_cons. apply Hin. intuition. unfold is_mono in H2.\n              apply NoDup_VarSorted in H2. auto.\n           ++ apply Permutation_NoDup with (l:=x :: m).\n              apply Permutation_cons_append. apply NoDup_cons. apply Hin.\n              intuition. unfold is_poly in H1. destruct H1. apply H3 in H0.\n              unfold is_mono in H0. apply NoDup_VarSorted in H0. auto.\n        -- unfold is_mono in H2. apply Sorted_VarSorted. auto.\n        -- unfold is_poly in H1. destruct H1. apply H3 in H0.\n            apply Sorted_VarSorted. auto.\n      * rewrite <- H1 in H0. unfold is_poly in Hp. destruct Hp.\n        apply NoDup_MonoSorted in H2. apply NoDup_cons_iff in H2 as [].\n        contradiction.\n    + apply IHl. apply poly_cons in Hp. apply Hp. intros m H. apply Hin.\n      intuition.\nQed.\n\n(** This next lemma is relatively straightforward, and really just served to\n    remove the calls to [sort] and [nodup_cancel] for convenience when\n    simplifying a [mulPP]. *)\n\nLemma mulPP_Permutation : forall x a0 l,\n  is_poly (a0 :: l) ->\n  (forall m, In m (a0 :: l) -> ~ In x m) ->\n  Permutation (mulPP [[x]] (a0 :: l))\n              ((make_mono (a0 ++ [x])) :: (mulPP [[x]] l)).\nProof.\n  intros x a0 l Hp Hx. unfold mulPP, distribute. simpl. unfold make_poly.\n  pose (MonoSort.Permuted_sort (nodup_cancel mono_eq_dec\n        (map make_mono ((a0 ++ [x]) :: concat (map (fun a => [a ++ [x]]) l))))).\n  apply Permutation_sym in p. apply (Permutation_trans p). simpl map.\n  rewrite no_nodup_cancel_NoDup; clear p.\n  - apply perm_skip. rewrite <- Permutation_MonoSort_r.\n    rewrite no_nodup_cancel_NoDup; auto. rewrite concat_map.\n    apply NoDup_map_app. apply poly_cons in Hp. apply Hp. intros m H. apply Hx.\n    intuition.\n  - rewrite <- map_cons. rewrite concat_map.\n    rewrite <- map_cons with (f:=fun a => a ++ [x]).\n    apply NoDup_map_app; auto.\nQed.\n\n(** Building off of the previous lemma, this one serves to remove the calls to\n    [make_poly] entirely, and instead replace [mulPP] with just the [map app].\n    We can do this because we know that [x] is not in any of the monomials, so\n    [nodup_cancel] will have no effect as we proved earlier. *)\n\nLemma mulPP_map_app_permutation : forall (x:var) (l l' : poly),\n  is_poly l ->\n  (forall m, In m l -> ~ In x m) ->\n  Permutation l l' ->\n  Permutation (mulPP [[x]] l) (map (fun a => (make_mono (a ++ [x]))) l').\nProof.\n  intros x l l' Hp H H0. generalize dependent l'. induction l; induction l'.\n  - intros. unfold mulPP, distribute, make_poly, MonoSort.sort. simpl. auto.\n  - intros. apply Permutation_nil_cons in H0. contradiction.\n  - intros. apply Permutation_sym in H0. apply Permutation_nil_cons in H0.\n    contradiction.\n  - intros. clear IHl'. destruct (mono_eq_dec a a0).\n    + rewrite e in *. pose (mulPP_Permutation x a0 l Hp H).\n      apply (Permutation_trans p). simpl. apply perm_skip. apply IHl.\n      * clear p. apply poly_cons in Hp. apply Hp.\n      * intros m Hin. apply H. intuition.\n      * apply Permutation_cons_inv in H0. auto.\n    + apply Permutation_incl in H0 as H1. destruct H1.\n      apply incl_cons_inv in H1 as []. destruct H1;\n      try (rewrite H1 in n; contradiction). apply in_split in H1.\n      destruct H1 as [l1 [l2]]. rewrite H1 in H0.\n      pose (Permutation_middle (a0::l1) l2 a). apply Permutation_sym in p.\n      simpl in p. apply (Permutation_trans H0) in p.\n      apply Permutation_cons_inv in p. rewrite H1. simpl. rewrite map_app.\n      simpl. pose (Permutation_middle ((make_mono (a0 ++ [x]) :: map (fun a1 =>\n        make_mono (a1 ++ [x])) l1)) (map (fun a1 => make_mono (a1 ++ [x])) l2)\n        (make_mono (a++[x]))).\n      simpl in p0. simpl. apply Permutation_trans with (l':=make_mono (a ++ [x])\n        :: make_mono (a0 ++ [x]) :: map (fun a1 : list var => make_mono (a1 ++\n        [x])) l1 ++ map (fun a1 : list var => make_mono (a1 ++ [x])) l2); auto.\n      clear p0. rewrite <- map_app.\n      rewrite <- (map_cons (fun a1 => make_mono (a1 ++ [x])) a0 (@app (list var)\n        l1 l2)).\n      pose (mulPP_Permutation x a l Hp H). apply (Permutation_trans p0).\n      apply perm_skip. apply IHl.\n      * clear p0. apply poly_cons in Hp. apply Hp.\n      * intros m Hin. apply H. intuition.\n      * apply p.\nQed.\n\n(** Finally, we combine the lemmas in this section to prove that, if there is\n    some polynomial [p] that has [x] in every monomial, removing and then\n    re-appending [x] to every monomial results in a list that is a permutation\n    of the original polynomial. *)\n\nLemma map_app_remove_Permutation : forall p x,\n  is_poly p ->\n  (forall m, In m p -> In x m) ->\n  Permutation p (map (fun a => (make_mono (a ++ [x])))\n                     (map (remove var_eq_dec x) p)).\nProof.\n  intros p x H H0. rewrite map_map. induction p; auto.\n  simpl. assert (make_mono (@app var (remove var_eq_dec x a) [x]) = a).\n  - unfold make_mono. rewrite no_nodup_NoDup.\n    + apply Permutation_Sorted_mono_eq.\n      * apply Permutation_trans with (l':=remove var_eq_dec x a ++ [x]).\n        apply Permutation_sym. apply VarSort.Permuted_sort.\n        pose (in_split x a). destruct e as [l1 [l2 e]]. apply H0. intuition.\n        rewrite e. apply Permutation_trans with\n          (l':=x :: remove var_eq_dec x (l1 ++ x :: l2)).\n        apply Permutation_sym. apply Permutation_cons_append.\n        apply Permutation_trans with (l':=(x::l1++l2)). apply perm_skip.\n        rewrite remove_distr_app. replace (x::l2) with ([x]++l2); auto.\n        rewrite remove_distr_app. simpl. destruct (var_eq_dec x x);\n        try contradiction. rewrite app_nil_l. repeat rewrite not_In_remove;\n        try apply Permutation_refl; try (apply poly_cons in H as [];\n        unfold is_mono in H1; apply NoDup_VarSorted in H1; rewrite e in H1;\n        apply NoDup_remove_2 in H1). intros x2. apply H1. intuition. intros x1.\n        apply H1. intuition. apply Permutation_middle.\n      * apply VarSort.LocallySorted_sort.\n      * apply poly_cons in H as []. unfold is_mono in H1.\n        apply Sorted_VarSorted. auto.\n    + apply Permutation_NoDup with (l:=(x::remove var_eq_dec x a)).\n      apply Permutation_cons_append. apply NoDup_cons.\n      apply remove_In. apply NoDup_remove. apply poly_cons in H as [].\n      unfold is_mono in H1. apply NoDup_VarSorted. auto.\n  - rewrite H1. apply perm_skip. apply IHp.\n    + apply poly_cons in H. apply H.\n    + intros m Hin. apply H0. intuition.\nQed.\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/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7609071989569671}}
{"text": "(** * Tutoriel 3 - Isomorphisme de Curry-Howard et ses conséquences *)\n\n(** La correspondance de Curry-Howard identifie :\n      - une formule A avec un type de données, et \n      - une preuve (dérivation formelle) avec un objet \n        (du lambda calcul) de type A. \n\n    Autrement dit, les types sont vus comme des propositions,\n    et les programmes comme des preuves *)\n\n(** Une preuve d'une implication par exemple est une fonction, \n    une preuve d'une conjonction est un couple, \n    appliquer la règle du modus-ponens se matérialise par \n    l'application d'une fonction à un argument. *)\n\n(** Cet objet du lambda calcul est appelé terme de preuve. \n    Il représente un arbre de preuve.\n    Lorsque l'on écrit un script de preuve (une suite de tactiques) \n    on construit peu à peu le terme de preuve. \n    Le Qed final vérifie que ce terme représente bien une preuve de \n    la formule de départ. Comment ? En vérifiant que son type est\n    bien celui de la formule.\n    Vous verrez cela de manière plus théorique plus tard. *)\n\n(** L'objet de ce TP est de découvrir ce mécanisme.\n\n    Si [toto] est un théorème ou n'importe quel objet de Coq, \n    la commande [Check toto] permet d'obtenir le type de toto.\n\n    Pour afficher sa valeur on utilisera la commande [Print toto].\n\n    Attention : La définition d’une constante à l’aide du système \n                de tactiques (invoqué par Theorem , etc.) est opaque \n                par défaut; il n’est donc pas possible de consulter sa\n                valeur. Pour que la définition soit transparente, il\n                suffit de remplacer [Qed] par [Defined] à la fin de \n                la preuve. *)\n\n(** ** Exercice 1 - Première observation *)\n\n(** Prouvez la proposition [forall A : Prop, A -> A] et \n    affichez sa preuve. *)\n\n(** En Coq, la fonction qui a x de type T associe e \n   (en OCaml function x → e) se note fun (x : T) => e.\n   Son type est un produit dépendant, noté en Coq,\n   [forall (x : T), U(x)] où U(x)est le type de e. \n\n   Dans le cas où U(x) = U ne dépend pas de la variable x : T , \n   le produit (non) dépendant s’abrège en T -> U et on retrouve le \n   type d'une fonction à la Ocaml. *)\n\n(** ** Exercice 2 - Premiers termes de preuve *)\n\nVariables A B C : Prop. (* On introduit ainsi 3 propositions \n                           logiques. *)\n\n(** A RETENIR : Une preuve de [A → B] est une fonction qui a toute\n                preuve de A associe une preuve de B. *)\n\n(** Prouver les propriétés suivantes et grâce à la commande\n    [Print] regarder les termes de preuve.\n\n      1. A -> A\n      2. (A -> B) -> (B -> C) -> A -> C\n      3. A -> B -> A\n      4. (A -> B -> C) -> (A -> B) -> A -> C\n      5. Essayer de construire directement le terme de preuve \n        (sans utiliser de tactique) de la formule [A -> B -> B]. \n        Pour vérifier que c'est bien la preuve, utiliser la tactique\n        [exact] suivie de ce terme dans la preuve.\n\n           Theorem ex2.5 : A -> B -> B.\n           exact (le terme).\n           Defined.\n*)\n\n\n(** ** Exercice 3 - Retour sur la négation *)\n\n(** On rappelle que [~A] est une abréviation pour [A -> False]. *)\n\n(** Prouver les formules suivantes (en utilisant des tactiques).\n    A l'aide de Print, regardez les termes de preuve.\n       1. A -> ~~A\n       2. (A -> B) -> (~B -> ~A) *)\n\n(** Indication :\n      Pour éliminer la proposition [False], on pourra utiliser \n      la constante prédéfinie (ex falso quod libet) :\n        false_ind : forall P : Prop, False -> P *)\n\n\n(** ** Exercice 4 - Retour sur la conjonction *) \n\n(** À l’aide des constantes prédéfinies\n    and : Prop -> Prop -> Prop (* Sucre : A /\\ B := and A B *)\n    conj : forall A B : Prop, A -> B -> A /\\ B.\n    proj1 : forall A B : Prop, A /\\ B -> A.\n    proj2 : forall A B : Prop, A /\\ B -> B.\n    donnez des termes de preuve des propositions suivantes :\n      1. A /\\ B -> B /\\ A\n      2. (A /\\ B) /\\ C -> A /\\ (B /\\ C)\n      3. (A -> B) /\\ (A -> C) -> (A -> B /\\ C)\n      4. (A -> B /\\ C) → (A -> B) /\\ (A -> C)\n\n    Vous commencerez par faire les preuves à l'aide des tactiques. *)\n\n(** ** Exercice 5 - Retour sur la disjonction *)\n\n(** À l’aide des constantes prédéfinies\n    or : Prop -> Prop -> Prop (* Sucre : A \\/ B := or A B *)\n    or_introl : forall A B : Prop, A -> A \\/ B\n    or_intror : forall A B : Prop, B -> A \\/ B\n    or_ind : forall A B P : Prop, (A -> P) -> (B -> P) -> A \\/ B -> P,\n    donnez des termes de preuve des propositions suivantes :\n      1. A \\/ B -> B \\/ A\n      2. (A \\/ B) \\/ C -> A \\/ (B \\/ C)\n      3. (A \\/ B -> C) <-> (A -> C) /\\ (B -> C)\n      4. ~~ (A \\/ ~A)\n\n    Vous commencerez par faire les preuves à l'aide des tactiques. *)\n\n\n(** Merci à Catherine Dubois. *)\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/TD4_B_Curry-Howard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.7609071823599733}}
{"text": "From Coq Require Import Init.Nat.\n\nInductive Fin: nat -> Type :=\n| Inherit: forall n, (Fin n) -> Fin (S n)\n| Cur: forall n, Fin (S n).\n\n(* Fin0: *)\n\n(* Fin1: *)\nCheck (Cur 0).\n\n(* Fin2: *)\nCheck (Cur 1).\nCheck (Inherit 1 (Cur 0)).\n\n(* Fin3 *)\nCheck (Cur 2).\nCheck (Inherit 2 (Cur 1)).\nCheck (Inherit 2 (Inherit 1 (Cur 0))).\n\n\n(* dependent function *)\nFixpoint fmax (a : nat) :=\n  match a with\n  | 0 => Cur 0\n  | S a => Inherit (S a) (fmax a)\n  end.\n\nCheck (fmax 3).\nCheck (fmax 4).\n\nInductive Product (A B:Type) : Type :=\n  Pr : A -> B -> Product A B.\n\nCheck (Pr nat nat 1 2).\n\nCheck prod_ind.\n\n(* Product Type *)\nDefinition indProduct (A B: Type) (C: Product A B -> Type)\n           (g : forall (a: A) (b: B), C (Pr A B a b)):\n  forall p : Product A B, C p :=\n  fun p => match p with Pr _ _ a b => g a b end.\n\nDefinition recProduct (A B: Type) (C: Type) (g : A -> B -> C) : Product A B -> C :=\n  indProduct A B (fun _ => C) g.\n\nDefinition pr1 (A B : Type) : Product A B -> A :=\n  recProduct A B A (fun a b => a).\n\nDefinition pr2 (A B : Type) : Product A B -> B :=\n  recProduct A B B (fun a b => b).\n\nDefinition uniq (A B: Type) (p: Product A B) : Pr A B (pr1 A B p) (pr2 A B p) = p.\nProof.\n  induction p.\n  reflexivity.\nQed.\n\nCheck (pr1 nat unit (Pr nat unit 1 tt)).\nCheck (pr2 nat unit (Pr nat unit 1 tt)).\nCheck (uniq nat unit (Pr nat unit 1 tt)).\n\n(* dependent pair *)\n\nInductive Sigma (A: Type) (B: A -> Type):=\n| Sig : forall a: A, (B a) -> Sigma A B.\n\nCheck Sig.\n\nInductive FinPlus: nat -> Type :=\n| InheritPlus: forall n, (FinPlus n) -> FinPlus (S n)\n| CurPlus: forall n, FinPlus n.\n\nFixpoint fPlusMax (a : nat) :=\n  match a with\n  | 0 => CurPlus 0\n  | S a => InheritPlus (a) (fPlusMax a)\n  end.\n\nCheck (Sig nat FinPlus 1 (fPlusMax 1)).\n\nDefinition indSigma (A: Type) (B: A -> Type) (C: Sigma A B -> Type) (g : forall (a: A) (b: B a), C (Sig A B a b)): forall p : Sigma A B, C p :=\n  fun p => match p with Sig _ _ a b => g a b end.\n\nDefinition recSigma (A: Type) (B: A -> Type) (C: Type) (g: forall a: A, B a -> C): forall p: Sigma A B, C :=\n  indSigma A B (fun _ => C) g.\n\nDefinition sig1 (A : Type) (B: A -> Type): Sigma A B -> A :=\n  recSigma A B A (fun a b => a).\n\nDefinition sig2 (A : Type) (B: A -> Type): forall p: Sigma A B, B (sig1 A B p) :=\n  indSigma A B (fun p => B (sig1 A B p)) (fun _ b => b).\n\nDefinition ac (A B: Type) (R: forall (a: A) (b: B), Type) (g: forall (x: A) , Sigma B (fun y => R x y)) : Sigma (A -> B) (fun f => forall x: A, R x (f x)):=\n  Sig (A -> B) (fun f => forall x: A, R x (f x)) (fun x => sig1 B (fun y => R x y) (g x)) (fun x => sig2 B (fun y => R x y) (g x)).\n\nDefinition magma : Type := Sigma Type (fun A => A -> A -> A).\n\nDefinition fstm (m : magma) : Type := sig1 _ _ m.\nDefinition sndm (m : magma) : (let A := fstm m in A -> A -> A) := sig2 _ _ m.\n\n(* Magma *)\nDefinition nat_first : magma := Sig Type (fun A => A -> A -> A) nat (fun a _ => a).\nDefinition nat_snd : magma := Sig Type (fun A => A -> A -> A) nat (fun _ b => b).\n\nDefinition PointedMagma: Type := Sigma Type (fun A => Product (A -> A -> A) A).\n\nDefinition nat_add: PointedMagma := Sig Type (fun A => Product (A -> A -> A) A) nat (Pr _ _ (fun a b => a + b) 0).\n\n(* coproduct type *)\n\nInductive Coproduct (A B: Type): Type :=\n|Inl: A -> Coproduct A B\n|Inr: B -> Coproduct A B.\n\nCheck (Inl nat bool 3).\n\nDefinition indCoproduct (A B: Type) (C: Coproduct A B -> Type) (g0: forall a: A, C (Inl A B a)) (g1: forall b: B, C(Inr A B b)): forall c: Coproduct A B, C c :=\n  fun c => match c with | Inl _ _ a => g0 a | Inr _ _ b => g1 b end.\n\nDefinition recCoproduct (A B C:Type) (g0: A -> C) (g1: B -> C): Coproduct A B -> C :=\n  indCoproduct A B (fun _ => C) g0 g1.\n\n(* empty type *)\nInductive Empty: Type :=.\nDefinition indEmpty (C : Empty -> Type) (z: Empty): C z :=\n  match z with end.\n\n(* unit type *)\nInductive Unit: Type := tt : Unit.\nDefinition indUnit (C : Unit -> Type) (g: forall u: Unit, C(u)) : forall x: Unit, C(x) := g.\nPrint Unit_ind.\n\n(* boolean type *)\nDefinition Boolean : Type := Coproduct Unit Unit.\nDefinition b0 : Boolean := Inl Unit Unit tt.\nDefinition b1 : Boolean := Inr Unit Unit tt.\nDefinition indBoolean (C: Boolean -> Type) (g0: forall a: Unit, C (Inl Unit Unit a)) (g1: forall b: Unit, C (Inr Unit Unit b)): forall b: Boolean, C b :=\n  indCoproduct Unit Unit C g0 g1.\n\nDefinition recBoolean (C: Type) (g0: C) (g1: C): Boolean -> C :=\n  indBoolean (fun _ => C) (fun _ => g0) (fun _ => g1).\n\nDefinition CoproductByBoolean (A B: Type): Type := Sigma Boolean (fun x: Boolean => recBoolean Type A B x).\nDefinition InlByBoolean (A B: Type) (a: A) : CoproductByBoolean A B :=\n  Sig Boolean (fun x: Boolean => recBoolean Type A B x) b0 a.\nDefinition InrByBoolean (A B: Type) (b: B) : CoproductByBoolean A B :=\n  Sig Boolean (fun x: Boolean => recBoolean Type A B x) b1 b.\n\nDefinition ProductByBoolean (A B: Type): Type :=\n  (forall x: Boolean, recBoolean Type A B x).\n\nDefinition PrByBoolean (A B: Type) (a: A) (b : B)\n  : ProductByBoolean A B :=\n  indBoolean (fun x => recBoolean Type A B x) (fun _ => a) (fun _ => b).\n\nDefinition RecProduct C A B (g : (A -> B -> C)) (p : ProductByBoolean A B) : C :=\n  g (p b0) (p b1).\n\nDefinition Pr1ByBoolean (A B: Type) (p: ProductByBoolean A B): A := p b0.\nDefinition Pr2ByBoolean (A B: Type) (p: ProductByBoolean A B): B := p b1.\n\nRequire Import FunctionalExtensionality.\n\nTheorem pr1_rec : forall A B,\n    Pr1ByBoolean A B = RecProduct A A B (fun a _ => a).\nProof.\n  intros A B.\n  extensionality p.\n  unfold Pr1ByBoolean.\n  unfold RecProduct.\n  reflexivity.\nQed.\n\nTheorem pr2_rec : forall A B,\n    Pr2ByBoolean A B = RecProduct B A B (fun _ b => b).\nProof.\n  intros A B.\n  extensionality p.\n  reflexivity.\nQed.\n\n(* nat type *)\n\nInductive Natural : Type :=\n| n0: Natural\n| nsucc: forall n: Natural, Natural.\n\n(* work around, as coq fixpoint functions require the first arg to be a structurally snaller one. *)\nDefinition indNatural (C: Natural -> Type) (g0: C n0) (g1: (forall n: Natural, C n -> C (nsucc n))): forall n: Natural, C n :=\n  fix aux (n: Natural) : C n :=\n    match n with | n0 => g0 | nsucc n' => g1 n' (aux n') end.\n\nDefinition recNatural (C: Type) (g0: C) (g1: Natural -> C -> C): Natural -> C :=\n  indNatural (fun _ => C) g0 g1.\n\nDefinition addNatural: Natural -> Natural -> Natural :=\n  recNatural (Natural -> Natural) (fun b => b) (fun _ f b => nsucc (f b)).\n\nDefinition addProperty0 : forall n, addNatural n0 n = n := fun _ => eq_refl.\nDefinition addProperty1 : forall n m, addNatural (nsucc m) n = nsucc (addNatural m n) := fun _ _ => eq_refl.\n\nDefinition doubleNatural: Natural -> Natural:=\n  recNatural Natural n0 (fun _ n => nsucc (nsucc n)).\n\nDefinition assoc0: forall j k: Natural, addNatural n0 (addNatural j k) = addNatural (addNatural n0 j) k :=\n  fun _ _ => eq_refl.\n\nDefinition ap (A B: Type) (f: A -> B) (x y: A) : x = y -> f x = f y.\nProof.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\nPrint ap.\n\nDefinition apSucc (a b: Natural) : a = b -> nsucc a = nsucc b :=\n  ap Natural Natural nsucc a b.\n\nDefinition assocs (i : Natural) (h: forall j k: Natural, addNatural i (addNatural j k) = addNatural (addNatural i j) k) : (forall j k: Natural, addNatural (nsucc i) (addNatural j k) = addNatural (addNatural (nsucc i) j) k) :=\n  fun j k => apSucc (addNatural i (addNatural j k)) (addNatural (addNatural i j) k) (h j k).\n\nDefinition assoc: forall i, forall j k, addNatural i (addNatural j k) = addNatural (addNatural i j) k :=\n  indNatural (fun i => forall j k, addNatural i (addNatural j k) = addNatural (addNatural i j) k) assoc0 assocs.\n\n(* propositions as types *)\n\nDefinition LogicTrue : Type := Unit.\nDefinition LogicFalse : Type := Empty.\nDefinition LogicAnd : Type -> Type -> Type := Product.\nDefinition LogicOr : Type -> Type -> Type := Coproduct.\nDefinition LogicIf : Type -> Type -> Type := fun A B => A -> B.\nDefinition LogicIff : Type -> Type -> Type := fun A B => Product (LogicIf A B) (LogicIf B A).\nDefinition LogicNot : Type -> Type := fun A => LogicIf A LogicFalse.\n\nDefinition PropExample (A B: Type): LogicIf (LogicAnd (LogicNot A) (LogicNot B)) (LogicNot (Coproduct A B)) :=\n  indProduct (LogicNot A) (LogicNot B) (fun _ => (LogicNot (Coproduct A B)))\n             (fun notA notB => indCoproduct A B (fun _ => LogicFalse)(fun a => match notA a with end) (fun b => match notB b with end)).\n\nPrint PropExample.\n\nDefinition LogicExists := Sigma.\n\nDefinition PropExample2 (A: Type) (P: A -> Type) (Q: A -> Type): (forall x: A, Product (P x) (Q x)) -> (Product (forall x: A, P x) (forall x: A, Q x)) :=\n  fun pre => Pr (forall x: A, P x) (forall x: A, Q x)\n             (fun x => recProduct (P x) (Q x) (P x) (fun x _ => x) (pre x))\n             (fun x => recProduct (P x) (Q x) (Q x) (fun _ y => y) (pre x)).\n\nDefinition LessThanEq (n m: Natural): Type := Sigma Natural (fun k => addNatural n k = m).\n\nPrint LessThanEq.\n\nDefinition LessThan (n m: Natural) : Type := Product (LessThanEq n m) (LogicNot (n = m)).\nCheck LessThan.\n\nDefinition LteExample : LessThanEq n0 n0 :=\n  Sig Natural (fun k => addNatural n0 k = n0) n0 eq_refl.\n\nLemma zero_is_not_one: (LogicNot (n0 = (nsucc n0))).\nProof.\n  unfold LogicNot.\n  unfold LogicIf.\n  intros.\n  inversion H.\nQed.\n\nPrint zero_is_not_one.\n\nDefinition LtExample : LessThan n0 (nsucc n0) :=\n  Pr _ _ (Sig Natural (fun k => addNatural n0 k = (nsucc n0)) (nsucc n0) eq_refl) zero_is_not_one.\n\nDefinition Semigroup: Type := Sigma Type (fun A => Sigma (A -> A -> A) (fun m => forall x y z: A, m x (m y z) = m (m x y) z)).\n\nLemma assocNatural: forall x y z : Natural, addNatural x (addNatural y z) = addNatural (addNatural x y) z.\nProof.\n  intro x.\n  induction x; intros.\n  + reflexivity.\n  + simpl. rewrite (IHx y z). reflexivity.\nQed.\n\nDefinition SemigroupExample: Semigroup :=\n  Sig Type (fun A => Sigma (A -> A -> A) (fun m => forall x y z: A, m x (m y z) = m (m x y) z)) Natural\n      (Sig (Natural -> Natural -> Natural) (fun m => forall x y z: Natural, m x (m y z) = m (m x y) z) addNatural assocNatural).\n\nPrint SemigroupExample.\n\n(* identity type. *)\nInductive Identity (A: Type): A -> A -> Type :=\n| idRefl: forall a: A, Identity A a a.\n\n(* path induction *)\n(* induction rule *)\nDefinition indId (A: Type) (C: forall x y: A, Identity A x y -> Type) (f: forall x: A, C x x (idRefl A x)) : forall x y: A, forall p: Identity A x y, C x y p :=\n  fun _ _ p => match p in (Identity _ x' y') return C x' y' p with\n            | idRefl _ a => f a\n            end.\n\n(* indiscernibility of identils *)\n(* rewrite rule *)\n\nDefinition idRewrite (A: Type) (C: A -> Type): forall a b: A, forall p: Identity A a b, (C a) -> (C b) :=\n  fun _ _ p => match p in Identity _ a b return C a -> C b with\n            | idRefl _ _ => fun x => x\n            end.\n\nDefinition idRewrite' (A: Type) (C: A -> Type): forall a b: A, forall p: Identity A a b, (C a) -> (C b) :=\n  indId A (fun x y _ => C x -> C y) (fun _ => fun x => x).\n\n(* base path induction *)\n\nDefinition baseIndId (A: Type) (a: A) (C: forall x: A, Identity A a x -> Type) (c: C a (idRefl A a)) : forall x: A, forall p: Identity A a x, C x p :=\n  fun x p =>\n    (fun _ p => match p in Identity _ a x return forall C': forall x: A, Identity A a x -> Type, forall c: C' a (idRefl A a), C' x p with\n             | idRefl _ _ => fun _ p => p \n             end) x p C c.\n\n(* baseInd is equivalent with ind *)\n\nDefinition baseIndId' (A: Type) (a: A) (C: forall x: A, Identity A a x -> Type) (c: C a (idRefl A a)) (x: A) (p: Identity A a x) : C x p :=\n  (indId A (fun a x p => forall C': forall x: A, Identity A a x -> Type, forall c' : C' a (idRefl A a), C' x p) (fun _ _ p => p)) a x p C c.\n\nDefinition indId' (A: Type) (C: forall x y: A, Identity A x y -> Type) (f: forall x: A, C x x (idRefl A x)) : forall x y: A, forall p: Identity A x y, C x y p :=\n  fun x => baseIndId A x (fun y => C x y) (f x).\n\n(* disequality *)\nDefinition disequal (A: Type) := forall x y: A, LogicNot (Identity A x y).\n\n(* Exercises *)\n\n(* 1.1 *)\nDefinition composite {A B C: Type} (g: B -> C) (f: A -> B) : A -> C := fun x => g (f x).\n\nDefinition compositeRule {A B C D: Type} (f: A -> B) (g: B -> C) (h: C -> D) : Identity (A -> D) (composite h (composite g f)) (composite (composite h g) f) := idRefl (A -> D) (fun x => h (g (f x))).\n\n(* 1.2 *)\n\nDefinition recProduct' (A B: Type) (C: Type) (g : A -> B -> C) : Product A B -> C :=\n  fun p => g (pr1 A B p) (pr2 A B p).\n\nDefinition recSigma' (A: Type) (B: A -> Type) (C: Type) (g: forall a: A, B a -> C): forall p: Sigma A B, C :=\n  fun p => g (sig1 A B p) (sig2 A B p).\n\n(* 1.3 *)\n\nDefinition indProduct' (A B: Type) (C: Product A B -> Type) (g : forall (a: A) (b: B), C (Pr A B a b)): forall p : Product A B, C p :=\n  fun p => eq_rect (Pr A B (pr1 A B p) (pr2 A B p)) C (g (pr1 A B p) (pr2 A B p)) p (uniq A B p).\n\nDefinition sigmaUniq (A: Type)  (B: A -> Type) (p: Sigma A B) : Sig A B (sig1 A B p) (sig2 A B p) = p.\nProof.\n  induction p.\n  reflexivity.\nQed.\n\nDefinition indSigma' (A: Type) (B: A -> Type) (C: Sigma A B -> Type) (g : forall (a: A) (b: B a), C (Sig A B a b)): forall p : Sigma A B, C p :=\n  fun p => eq_rect (Sig A B (sig1 A B p) (sig2 A B p)) C (g (sig1 A B p) (sig2 A B p)) p (sigmaUniq A B p).\n\n(* 1.4 *)\n\nDefinition iter (C: Type) (c0: C) (cs: C -> C) (n: Natural): C :=\n  (fix aux (n: Natural) : C :=\n     match n with\n     | n0 => c0\n     | nsucc n' => cs (aux n')\n     end) n.\n\nDefinition recNatural' (C: Type) (g0: C) (g1: Natural -> C -> C): Natural -> C :=\n  fun n => pr2 _ _ (iter (Product Natural C) (Pr _ _ n0 g0) (fun p => Pr _ _ (nsucc (pr1 _ _ p)) (g1 (pr1 _ _ p) (pr2 _ _ p))) n).\n\nDefinition recEqrec (C: Type) (g0: C) (g1: Natural -> C -> C) (n: Natural): recNatural C g0 g1 n = recNatural' C g0 g1 n.\nProof.\n  intros.\n  induction n.\n  + reflexivity.\n  + simpl.\n    rewrite IHn.\n    unfold recNatural'.\n    simpl.\n    clear IHn.\n    assert (forall n, n = (pr1 Natural C\n                          (iter (Product Natural C) (Pr Natural C n0 g0)\n                                (fun p : Product Natural C => Pr Natural C (nsucc (pr1 Natural C p)) (g1 (pr1 Natural C p) (pr2 Natural C p))) n))).\n  - clear n.\n    intros.\n    induction n.\n    * reflexivity.\n    * simpl.\n      rewrite <- IHn.\n      reflexivity.\n  - rewrite <- (H n).\n    reflexivity.\nQed.\n\n(* 1.5 *)\n\nDefinition CoproductByRec2 (A B: Type) : Type := Sigma Boolean (fun b => recBoolean Type A B b).\n\nDefinition indCoproductByRec2 (A B: Type) (C: CoproductByRec2 A B -> Type) (p1: forall a: A, C (Sig _ _ b0 a)) (p2: forall b: B, C (Sig _ _ b1 b)): forall c: CoproductByRec2 A B, C c :=\n  indSigma _ _ C (fun b x =>\n                    indBoolean (fun b => forall x, C (Sig Boolean (fun b => recBoolean Type A B b) b x))\n                               (fun u x => Unit_rect (fun u => C (Sig Boolean (fun x : Boolean => recBoolean Type A B x) (Inl Unit Unit u) x)) (p1 x) u)\n                               (fun u x => Unit_rect (fun u => C (Sig Boolean (fun x : Boolean => recBoolean Type A B x) (Inr Unit Unit u) x)) (p2 x) u)\n                               b x\n                 ).\n\nDefinition Ex_1_5 (A B: Type) (C: CoproductByRec2 A B -> Type) (p1: forall a: A, C (Sig _ _ b0 a)) (p2: forall b: B, C (Sig _ _ b1 b)) : forall a: A, indCoproductByRec2 A B C p1 p2 (Sig _ _ b0 a) = p1 a := fun _ => eq_refl.\n\nDefinition Ex_1_5' (A B: Type) (C: CoproductByRec2 A B -> Type) (p1: forall a: A, C (Sig _ _ b0 a)) (p2: forall b: B, C (Sig _ _ b1 b)) : forall b: B, indCoproductByRec2 A B C p1 p2 (Sig _ _ b1 b) = p2 b := fun _ => eq_refl.\n\n(* 1.6 *)\n\nDefinition ProductByRec2 (A B: Type) : Type :=\n  forall b: Boolean, recBoolean Type A B b.\n\nDefinition PrByRec2 (A B: Type) (x: A) (y: B)\n  : ProductByRec2 A B :=\n  indBoolean (fun b => recBoolean Type A B b)\n             (fun _ => x)\n             (fun _ => y).\n\nFrom Coq Require Import Logic.FunctionalExtensionality.\n\nDefinition Lemma1_6 (A B: Type): forall p: ProductByRec2 A B, PrByRec2 A B (p b0) (p b1) = p :=\n  fun p => functional_extensionality_dep\n          (PrByRec2 A B (p b0) (p b1))\n          p\n          (fun bo => indBoolean (fun bo => (PrByRec2 A B (p b0) (p b1)) bo = p bo)\n                             (Unit_rect (fun u => PrByRec2 A B (p b0) (p b1) (Inl Unit Unit u) = p (Inl Unit Unit u))\n                                        eq_refl\n                             )\n                             (Unit_rect (fun u => PrByRec2 A B (p b0) (p b1) (Inr Unit Unit u) = p (Inr Unit Unit u))\n                                        eq_refl\n                             )\n                             bo).\n\nDefinition indProductByRec2 (A B: Type) (C: ProductByRec2 A B -> Type) (p: forall a: A, forall b: B, C (PrByRec2 A B a b)) : forall c: ProductByRec2 A B, C c :=\n  fun c => @eq_rect (ProductByRec2 A B) (PrByRec2 A B (c b0) (c b1)) C (p (c b0) (c b1)) c (Lemma1_6 A B c).\n\n(* Sorry Pedrotst, I can not compile this part of code. *)\n\n(* Lemma indProductByRec2LemmaEq (A B: Type) *)\n(*            (C: (recBoolean Type A B) -> Type) : *)\n(*   (forall a b bo, C (PrByRec2 A B a b bo)) = *)\n(*   (forall c a b, ProductByRec c a b). *)\n\nFrom Coq Require Import Logic.Eqdep.\n\n(* Axiom eq_rect_eq : *)\n(*   forall (U:Type) (p:U) (Q:U -> Type) (x:Q p) (h:p = p), x = eq_rect p Q x p h. *)\n\nDefinition Eq1_6 (A B: Type) (C: ProductByRec2 A B -> Type) (g: forall a: A, forall b: B, C (PrByRec2 A B a b)) (a: A) (b: B): indProductByRec2 A B C g (PrByRec2 A B a b) = g a b.\nProof.\n  unfold indProductByRec2.\n  unfold Lemma1_6.\n  rewrite <- eq_rect_eq.\n  reflexivity.\nQed.\n", "meta": {"author": "zhezhouzz", "repo": "Hott-Playground", "sha": "dbd39f120f16d3a8e3370705243b614e84ac69c3", "save_path": "github-repos/coq/zhezhouzz-Hott-Playground", "path": "github-repos/coq/zhezhouzz-Hott-Playground/Hott-Playground-dbd39f120f16d3a8e3370705243b614e84ac69c3/TypeTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7607904274141922}}
{"text": "\nRequire Import Arith.\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\n\nStructure partial_order :=\n  mk_partial_order {\n      po_set     : Type ;\n      po_le      : po_set -> po_set -> Prop ;\n      po_refl    : forall a, po_le a a ;\n      po_antisym : forall a b,\n                     po_le a b ->\n                     po_le b a ->\n                     a = b ;\n      po_trans   : forall a b c,\n                     po_le a b ->\n                     po_le b c ->\n                     po_le a c\n  }.\n\nNotation \"x << y\" := (po_le _ x y) (at level 35).\n\nDefinition subset (A : Type) := A -> Prop.\n\n\nDefinition po_upper_bound po (S : subset (po_set po)) (bound : po_set po) :=\n  forall x, S x -> x << bound.\n\nDefinition po_least_upper_bound po (S : subset (po_set po)) (lub : po_set po) :=\n  po_upper_bound po S lub /\\\n  forall bound, po_upper_bound po S bound -> lub << bound.\n\nLemma po_lub_unique : forall po S lub1 lub2,\n                        po_least_upper_bound po S lub1 ->\n                        po_least_upper_bound po S lub2 ->\n                        lub1 = lub2.\nProof.\n  intros po S lub1 lub2 lub1_prop lub2_prop.\n  apply po_antisym.\n  apply lub1_prop.\n  apply lub2_prop.\n  apply lub2_prop.\n  apply lub1_prop.\nQed.\n\nDefinition po_monotonic A B (f : po_set A -> po_set B) :=\n  forall x y, x << y -> f x << f y.\n\nDefinition f_ap (A B : Type) (f : A -> B) (S : subset A) : subset B :=\n  fun b : B => exists a : A, S a /\\ f a = b.\n\nNotation \"f !! S\" := (f_ap _ _ f S) (at level 35).\n\n(**\n **   \\/ (f !! S)  <<  f (\\/ S)\n **)\nLemma lub_f_vs_f_lub :\n  forall A B f,\n    po_monotonic A B f ->\n    forall (S : subset (po_set A)),\n      forall lubA lubB,\n        po_least_upper_bound A S lubA ->\n        po_least_upper_bound B (f !! S) lubB ->\n        lubB << f lubA.\nProof.\n  intros A B f f_monotonic S lubA lubB lubA_prop lubB_prop.\n  unfold po_least_upper_bound in lubB_prop.\n  destruct lubB_prop as (lubB_upper, lubB_least).\n  apply lubB_least.\n  unfold po_upper_bound.\n  intros x x_in_fS.\n  unfold f_ap in x_in_fS.\n  elim x_in_fS.\n  intros y y_prop.\n  destruct y_prop as (y_in_S, x_eq_fy).\n  replace x with (f y).\n  apply f_monotonic.\n  unfold po_least_upper_bound in lubA_prop.\n  destruct lubA_prop as (lubA_upper, lubA_least).\n  apply lubA_upper.\n  assumption.\nQed.\n\n(** Filters **)\n\nDefinition po_filter po (F : subset (po_set po)) :=\n   forall a b, F a -> F b ->\n               exists c,\n                 F c\n                 /\\ a << c\n                 /\\ b << c.\n\nDefinition singleton (A : Type) (S : subset A) :=\n  forall x y, S x -> S y -> x = y.\n\nLemma filter_singleton : forall po S, singleton (po_set po) S -> po_filter po S.\nProof.\n  unfold po_filter.\n  intros po S S_singleton a b a_in_S b_in_S.\n  exists a.\n  split.\n  assumption.\n  split.\n  apply po_refl.\n  replace b with a. \n  apply po_refl.\n  apply S_singleton.\n  assumption.\n  assumption.\nQed.\n\nStructure domain :=\n  mk_domain {\n      d_po        : partial_order ;\n      d_bot       : po_set d_po ;\n      d_bot_prop  : forall x, d_bot << x ;\n      d_lub       : forall F, po_filter d_po F -> po_set d_po ;\n      d_lub_prop  : forall F (F_filter : po_filter d_po F),\n                        po_least_upper_bound d_po F (d_lub F F_filter)\n  }.\n\nDefinition stream_le po I (f : I -> po_set po) (g : I -> po_set po) :=\n  forall x, f x << g x.\n\nLemma stream_refl : forall po I f, stream_le po I f f.\nProof.\n  intros.\n  unfold stream_le.\n  intro.\n  apply po_refl.\nQed.\n\nLemma stream_antisym :\n  forall po I f g,\n    stream_le po I f g ->\n    stream_le po I g f ->\n    f = g.\nProof.\n  intros po I f g f_le_g g_le_f.\n  apply functional_extensionality.\n  intro.\n  apply po_antisym.\n  apply f_le_g.\n  apply g_le_f.\nQed.\n\nLemma stream_trans :\n  forall po I f g h,\n    stream_le po I f g ->\n    stream_le po I g h ->\n    stream_le po I f h.\nProof.\n  intros po I f g h f_le_g g_le_h.\n  unfold stream_le.\n  intro.\n  apply po_trans with (g x).\n  apply f_le_g.\n  apply g_le_h.\nQed.\n\nDefinition stream po I :=\n  mk_partial_order\n      (I -> po_set po)\n      (stream_le po I)\n      (stream_refl po I)\n      (stream_antisym po I)\n      (stream_trans po I).\n\nDefinition stream_bot (D : domain) I : po_set (stream (d_po D) I) :=\n  fun _ => d_bot D.\n\nLemma stream_bot_prop (D : domain) I :\n  forall f : po_set (stream (d_po D) I), stream_bot D I << f.\nProof.\n  intro f.\n  simpl; unfold stream_le.\n  intro x.\n  unfold stream_bot.\n  apply d_bot_prop.\nQed.\n\nLemma stream_lub_inner_prop\n      (D : domain) I\n      (F : subset (po_set (stream (d_po D) I)))\n      (F_filter : po_filter (stream (d_po D) I) F)\n      (x : I) :\n      po_filter (d_po D) (fun y => exists f, F f /\\ f x = y).\nProof.\n  unfold po_filter.\n  intros a b a_shape b_shape.\n  elim a_shape.\n    intro f.\n    intro a_shape2.\n    destruct a_shape2 as (f_in_F, fx_eq_a).\n  elim b_shape.\n    intro g.\n    intro b_shape2.\n    destruct b_shape2 as (g_in_F, gx_eq_b).\n  assert (exists h, F h /\\ f << h /\\ g << h) as exists_h.\n    unfold po_filter in F_filter.\n    apply F_filter.\n    assumption.\n    assumption.\n  elim exists_h.\n  intro hh.\n  intro hh_prop.\n  destruct hh_prop as (hh_in_F, fg_le_hh).\n  destruct fg_le_hh as (f_le_hh, g_le_hh).\n  exists (hh x).\n  split.\n    exists hh.\n    split.\n    assumption.\n    reflexivity.\n    replace a with (f x).\n    replace b with (g x).\n    split.\n    apply f_le_hh.\n    apply g_le_hh.\nQed.    \n\nDefinition stream_lub (D : domain) I\n                      (F : subset (po_set (stream (d_po D) I)))\n                      (F_filter : po_filter (stream (d_po D) I) F)\n                      : po_set (stream (d_po D) I)\n                      :=\n  fun x : I =>\n    d_lub D\n          (fun y => exists f, F f /\\ f x = y)\n          (stream_lub_inner_prop D I F F_filter x).\n\nLemma stream_lub_prop\n      (D : domain) I\n      (F : subset (po_set (stream (d_po D) I)))\n      (F_filter : po_filter (stream (d_po D) I) F) :\n        po_least_upper_bound (stream (d_po D) I) F (stream_lub D I F F_filter).\nProof.\n  split.\n  (* upper *)\n  unfold po_upper_bound.\n  intro f.\n  intro f_in_F.\n  simpl.\n  unfold stream_le.\n  intro x.\n  unfold stream_lub.\n  apply d_lub_prop.  \n  exists f.\n  split.\n  assumption.\n  reflexivity.\n  (* least *)\n  intros f_bound f_bound_upper_bound.\n  simpl.\n  unfold stream_le.\n  intro x.\n  apply d_lub_prop.\n  unfold po_upper_bound.\n  intro y.\n  intro y_shape.\n  elim y_shape.\n  intro f.\n  intro f_prop.\n  destruct f_prop as (f_in_F, fx_eq_y).\n  replace y with (f x).\n  apply f_bound_upper_bound.\n  assumption.\nQed.  \n\nDefinition stream_domain (D : domain) I :=\n    mk_domain\n      (stream (d_po D) I)\n      (stream_bot D I)\n      (stream_bot_prop D I)\n      (stream_lub D I)\n      (stream_lub_prop D I).\n\n(** Continuous functions **)\n\nDefinition d_set D := po_set (d_po D).\nDefinition d_monotonic D E (f : d_set D -> d_set E) := po_monotonic (d_po D) (d_po E) f.\nDefinition d_filter D (F : subset (d_set D)) := po_filter (d_po D) F.\nDefinition d_least_upper_bound D S lub := po_least_upper_bound (d_po D) S lub.\n\nDefinition d_continuous D E f (f_monotonic : d_monotonic D E f) :=\n  forall F (F_filter : d_filter D F),\n    forall lubD, d_least_upper_bound D F lubD ->\n      forall lubE, d_least_upper_bound E (fun x => exists y, F y /\\ f y = x) lubE ->\n        lubE = f lubD.\n\nDefinition d_function_space (D E : domain) :=\n  { f : d_set D -> d_set E |\n    { f_monotonic : d_monotonic D E f & d_continuous D E f f_monotonic }\n  }.\n\nNotation \"D =>> E\" := (d_function_space D E) (at level 35).\n\nDefinition d_function_ap D E (f : D =>> E) (x : d_set D) := proj1_sig f x.\n\nNotation \"f $ x\" := (d_function_ap _ _ f x) (at level 25).\n\nDefinition d_function_le D E (f g : D =>> E) := forall x, f $ x << g $ x.\n\nLemma d_function_le_refl D E (f : D =>> E) : d_function_le D E f f.\nProof.\n  intro.\n  apply po_refl.\nQed.\n\nLemma d_functional_extensionality :\n  forall D E (f g : D =>> E),\n    (forall x, f $ x = g $ x) -> f = g.\nProof.\n  intros D E f g fx_eq_gx.\n  case_eq f. intros f_function f_continuous f_shape.\n  case_eq g. intros g_function g_continuous g_shape.\n  cut (f_function = g_function); [ intro H; destruct H | ].\n  cut (f_continuous = g_continuous); [ intro H; destruct H | ].\n  reflexivity.\n  apply proof_irrelevance.\n  rewrite f_shape in fx_eq_gx.\n  rewrite g_shape in fx_eq_gx.\n  simpl in fx_eq_gx.\n  apply functional_extensionality.\n  assumption.\nQed.\n\nLemma d_le_extensional :\n  forall D E (f g : D =>> E) x, d_function_le D E f g -> f $ x << g $ x.\nProof.\n  intros D E f g x H.\n  unfold d_function_le in H.\n  specialize H with x.\n  assumption.\nQed.\n\nLemma d_function_le_antisym D E (f g : D =>> E) :\n  d_function_le D E f g ->\n  d_function_le D E g f ->\n  f = g.\nProof.\n  unfold d_function_le.\n  intros f_le_g g_le_f.\n  apply d_functional_extensionality.\n  intro x.\n  apply po_antisym.\n  specialize f_le_g with x.\n  assumption.\n  specialize g_le_f with x.\n  assumption.\nQed.\n\nLemma d_function_le_trans D E (f g h : D =>> E) :\n  d_function_le D E f g ->\n  d_function_le D E g h ->\n  d_function_le D E f h.\nProof.\n  intros f_le_g g_le_h.\n  unfold d_function_le in *.\n  intro x.\n  specialize f_le_g with x.\n  specialize g_le_h with x.\n  apply po_trans with (g $ x).\n  assumption.\n  assumption.\nQed.\n\nDefinition d_function_space_partial_order (D E : domain) : partial_order :=\n  mk_partial_order\n    (d_function_space D E)\n    (d_function_le D E)\n    (d_function_le_refl D E)\n    (d_function_le_antisym D E)\n    (d_function_le_trans D E).\n\nDefinition d_function_domain_bot_function D E : d_set D -> d_set E :=\n  fun _ : d_set D => d_bot E.\n\nLemma d_function_domain_bot_monotonic D E :\n  d_monotonic D E (d_function_domain_bot_function D E).\nProof.\n  unfold d_monotonic.\n  unfold po_monotonic.\n  intros x y x_le_y.\n  apply po_refl. \nQed.\n\nLemma d_function_domain_bot_continuous D E :\n  d_continuous D E\n               (d_function_domain_bot_function D E)\n               (d_function_domain_bot_monotonic D E).\nProof.\n  unfold d_continuous. \n  intros F F_filter lubD lubD_lub lubE lubE_lub.\n  unfold d_function_domain_bot_function.  \n  apply po_lub_unique\n   with (S :=\n         fun x : po_set (d_po E) =>\n           exists y : d_set D,\n             F y /\\ d_function_domain_bot_function D E y = x).\n  apply lubE_lub.\n  unfold po_least_upper_bound.\n  split.\n    (* bot is upper bound *)\n    unfold po_upper_bound.\n    intros x x_prop.\n    elim x_prop.\n    intros y x_shape.\n    destruct x_shape as (Fy, dom_bot_func_y_eq_x).\n    rewrite <- dom_bot_func_y_eq_x.\n    unfold d_function_domain_bot_function.\n    apply po_refl.\n    (* bot is least upper bound *)\n    intros.\n    apply d_bot_prop.\nQed.\n\nDefinition d_function_domain_bot D E : po_set (d_function_space_partial_order D E).\n  exists (d_function_domain_bot_function D E).\n  exists (d_function_domain_bot_monotonic D E).\n  apply d_function_domain_bot_continuous.\nDefined.\n  \nLemma d_function_domain_bot_apply :\n  forall D E x,\n    d_function_domain_bot D E $ x = d_bot E.\nProof.\n  intros.\n  unfold d_function_ap.\n  unfold d_function_domain_bot.\n  unfold proj1_sig.\n  reflexivity.\nQed.\n\nLemma d_function_domain_bot_prop D E :\n  forall f : po_set (d_function_space_partial_order D E),\n    d_function_domain_bot D E << f.\nProof.\n  intros.\n  simpl.\n  unfold d_function_le.\n  intros.\n  rewrite d_function_domain_bot_apply.\n  apply d_bot_prop.\nQed.\n\nLemma d_function_domain_lub_function_filter :\n  forall D E F (F_filter : po_filter (d_function_space_partial_order D E) F) x,\n    po_filter (d_po E) (fun y : d_set E => exists f, F f /\\ f $ x = y).\nProof.\n  intros D E F F_filter x.\n  unfold po_filter.\n  intros y1 y2.\n  intros y1_prop y2_prop.\n  elim y1_prop; intros f1 y1_shape.\n  elim y2_prop; intros f2 y2_shape.\n  destruct y1_shape as (f1_in_F, f1_x_eq_y1).\n  destruct y2_shape as (f2_in_F, f2_x_eq_y2).\n  assert (exists g, F g /\\ f1 << g /\\ f2 << g) as exists_g.\n    apply F_filter.\n    assumption.\n    assumption.\n  elim exists_g; intros g g_prop.\n  exists (g $ x).\n  split.\n    exists g.\n    split.\n    apply g_prop.\n    reflexivity.\n    replace y1 with (f1 $ x).\n    replace y2 with (f2 $ x).\n    destruct g_prop as (g_in_F, (f1_le_g, f2_le_g)).\n    \n    split.\n       apply d_le_extensional; assumption.\n       apply d_le_extensional; assumption.\nQed.\n\nDefinition d_function_domain_lub_function \n           D E F (F_filter : po_filter (d_function_space_partial_order D E) F) :\n           d_set D -> d_set E :=\n  fun x : d_set D =>\n    d_lub E\n          (fun y : d_set E => exists f, F f /\\ f $ x = y)\n          (d_function_domain_lub_function_filter D E F F_filter x).\n\nLemma d_functional_monotonic :\n  forall D E (f : D =>> E), d_monotonic D E (proj1_sig f).\nProof.\n  intros D E f.\n  case f.\n  simpl.\n  intros f_function f_shape.\n  destruct f_shape.\n  assumption.\nQed.\n\nLemma d_functional_continuous :\n  forall D E (f : D =>> E), d_continuous D E\n                                         (proj1_sig f)\n                                         (d_functional_monotonic D E f).\nProof.\n  intros D E f.\n  case f.\n  simpl.\n  intros f_function f_prop.\n  destruct f_prop.\n  assumption.\nQed.\n\nLemma d_function_domain_lub_monotonic\n           D E F (F_filter : po_filter (d_function_space_partial_order D E) F) :\n             d_monotonic D E (d_function_domain_lub_function D E F F_filter).\nProof.\n  unfold d_monotonic.\n  unfold po_monotonic.\n  intros x y x_le_y.\n  unfold d_function_domain_lub_function.\n  simpl.\n  apply d_lub_prop.\n  unfold po_upper_bound.\n  intros fx fx_prop.\n  elim fx_prop. intros f fx_shape.\n  destruct fx_shape as (f_in_F, f_ap_x_eq_fx).\n  apply po_trans with (f $ y).\n  rewrite <- f_ap_x_eq_fx.\n  assert (d_monotonic D E (proj1_sig f)) as f_monotonic.\n    apply d_functional_monotonic.\n  apply f_monotonic.\n  assumption.\n  apply d_lub_prop.\n  exists f.\n  split.\n  assumption.\n  reflexivity.\nQed.\n\nLemma d_functional_preserves_filter :\n  forall D E (f : D =>> E) F, d_filter D F -> d_filter E (proj1_sig f !! F).\nProof.\n  intros D E f F F_filter.\n  unfold d_filter.\n  unfold po_filter.\n  intros a b a_prop b_prop.\n  unfold f_ap in a_prop.\n  unfold f_ap in b_prop.\n  elim a_prop.\n  intros a_pre a_shape.\n  elim b_prop.\n  intros b_pre b_shape.\n  destruct a_shape as (a_pre_in_F, a_eq_f_a_pre).\n  destruct b_shape as (b_pre_in_F, b_eq_f_b_pre).\n  assert (exists c_pre, F c_pre /\\ a_pre << c_pre /\\ b_pre << c_pre)\n      as exists_c_pre.\n    apply F_filter.\n    assumption.\n    assumption.\n  elim exists_c_pre.\n  intros c_pre c_pre_shape.\n  destruct c_pre_shape as (c_pre_in_F, (a_pre_le_c_pre, b_pre_le_c_pre)).\n  exists (proj1_sig f c_pre).\n  assert (d_monotonic D E (proj1_sig f)) as f_monotonic.\n    apply d_functional_monotonic.\n  split.\n    unfold f_ap.\n    exists c_pre. \n    split. assumption. reflexivity.\n    split.\n    rewrite <- a_eq_f_a_pre. \n    apply f_monotonic.\n    assumption.\n    rewrite <- b_eq_f_b_pre. \n    apply f_monotonic.\n    assumption.\nQed.\n\nLemma d_function_domain_lub_continuous\n           D E F (F_filter : po_filter (d_function_space_partial_order D E) F) :\n             d_continuous D E\n                          (d_function_domain_lub_function D E F F_filter)\n                          (d_function_domain_lub_monotonic D E F F_filter).\nProof.\n  unfold d_continuous.\n  intros G G_filter lubD lubD_lub lubE lubE_lub.\n  apply po_lub_unique\n   with (S := fun x : d_set E =>\n                exists y : d_set D,\n                  G y /\\ d_function_domain_lub_function D E F F_filter y = x).\n  assumption.\n  unfold po_least_upper_bound.\n  split.\n  (* upper bound *)\n  unfold po_upper_bound.\n  intros lub_fx lub_fx_prop.\n  elim lub_fx_prop.\n  intros x lub_fx_shape.\n  destruct lub_fx_shape as (x_in_G, lub_f_ap_x_eq_lub_fx).\n  rewrite <- lub_f_ap_x_eq_lub_fx.\n  apply d_lub_prop.\n  unfold po_upper_bound.\n  intros f_ap_x f_ap_x_prop.\n  elim f_ap_x_prop.\n  intros f f_ap_x_shape.\n  destruct f_ap_x_shape as (f_in_F, f_x_eq_f_ap_x).\n  rewrite <- f_x_eq_f_ap_x.\n  apply po_trans with (f $ lubD).\n  assert (d_monotonic D E (proj1_sig f)) as f_monotonic.\n    apply d_functional_monotonic.\n  apply f_monotonic.\n  apply lubD_lub.\n  assumption.\n  apply d_lub_prop.\n  exists f.\n  split.\n  assumption.\n  reflexivity.\n  (* least *)\n  intros z z_prop.\n  apply d_lub_prop.\n  unfold po_upper_bound.\n  intros flubD flubD_prop.\n  elim flubD_prop.\n  intros f f_shape.\n  destruct f_shape as (f_in_F, f_lubD_eq_flubD).\n  rewrite <- f_lubD_eq_flubD.\n  (* using the fact that f is continuous *)\n  assert (d_continuous D E (proj1_sig f) (d_functional_monotonic D E f))\n      as f_continuous.\n    apply d_functional_continuous.\n  unfold d_continuous in f_continuous.\n  unfold d_function_ap.\n  rewrite <- f_continuous\n     with (F := G)\n          (lubE := d_lub E\n                     (proj1_sig f !! G)\n                     (d_functional_preserves_filter D E f G G_filter)).\n    (* (1) *)\n    apply d_lub_prop.\n      unfold po_upper_bound.\n      intros fx fx_in_fG.\n      unfold f_ap in fx_in_fG.\n      elim fx_in_fG.\n      intros x fx_shape.\n      destruct fx_shape as (x_in_G, fx_eq_f_x).\n      rewrite <- fx_eq_f_x.\n      apply po_trans\n       with (d_lub E\n                   (fun y => exists f, F f /\\ f $ x = y)\n                   (d_function_domain_lub_function_filter D E F F_filter x)).\n      (* trans1 *)\n        apply d_lub_prop.\n        exists f.\n        split.\n        assumption.\n        unfold d_function_ap.\n        reflexivity.\n      (* trans2 *)\n        apply z_prop.\n        exists x. \n        split.\n        assumption.\n        unfold d_function_domain_lub_function.        \n        reflexivity.\n    (* (2) *)\n    assumption.\n    (* (3) *)\n    assumption.\n    (* (4) *)\n    unfold f_ap.\n    apply d_lub_prop.\nQed.\n\nDefinition d_function_domain_lub\n             D E F (F_filter : po_filter (d_function_space_partial_order D E) F) :\n             po_set (d_function_space_partial_order D E).\n  exists (d_function_domain_lub_function D E F F_filter).\n  exists (d_function_domain_lub_monotonic D E F F_filter).\n  apply (d_function_domain_lub_continuous D E F F_filter).\nDefined.\n\nDefinition d_function_domain_lub_prop\n             D E F (F_filter : po_filter (d_function_space_partial_order D E) F) :\n             po_least_upper_bound (d_function_space_partial_order D E)\n                                  F (d_function_domain_lub D E F F_filter).\n  unfold po_least_upper_bound.\n  split.\n  (* upper *)\n    unfold po_upper_bound.\n    intros f f_in_F.\n    simpl.\n    unfold d_function_le.\n    intro.\n    simpl.\n    unfold d_function_domain_lub_function.\n    apply d_lub_prop.\n    exists f. \n    split.\n    assumption.\n    reflexivity.\n  (* least *)\n    intros g g_upper_bound.\n    simpl. \n    unfold d_function_le.\n    intro x.\n    simpl.\n    unfold d_function_domain_lub_function.\n    apply d_lub_prop.\n    unfold po_upper_bound.\n    intro fx.\n    intro fx_prop.\n    elim fx_prop.\n    intros f fx_shape.\n    destruct fx_shape as (f_in_F, f_x_eq_fx).\n    rewrite <- f_x_eq_fx.\n    apply d_le_extensional.\n    apply g_upper_bound.\n    assumption.\nDefined.\n \nDefinition d_function_domain (D E : domain) :=\n  mk_domain\n    (d_function_space_partial_order D E)\n    (d_function_domain_bot D E)\n    (d_function_domain_bot_prop D E)\n    (d_function_domain_lub D E)\n    (d_function_domain_lub_prop D E).\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/domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7607189078543088}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\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 (a: aexp) : nat :=\n  match a with\n  | ANum n => n\n  | APlus l r => (aeval l) + (aeval r)\n  | AMinus l r => (aeval l) - (aeval r)\n  | AMult l r => (aeval l) * (aeval r)\n  end.\n\nFixpoint beval (b: bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | BEq l r => beq_nat (aeval l) (aeval r)\n  | BLe l r => leb (aeval l) (aeval r)\n  | BNot b' => negb (beval b')\n  | BAnd l r => andb (beval l) (beval r)\n  end.\n\nFixpoint optimize_0plus (a: aexp) : aexp :=\n  match a with\n  | ANum n => ANum n\n  | APlus (ANum 0) r => (optimize_0plus r)\n  | APlus l r => APlus (optimize_0plus l) (optimize_0plus r)\n  | AMinus l r => AMinus (optimize_0plus l) (optimize_0plus r)\n  | AMult l r => AMult (optimize_0plus l) (optimize_0plus r)\n  end.\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n  match b with\n  | BEq l r => BEq (optimize_0plus l) (optimize_0plus r)\n  | BLe l r => BLe (optimize_0plus l) (optimize_0plus r)\n  | BNot b' => BNot (optimize_0plus_b b')\n  | BAnd l r => BAnd (optimize_0plus_b l) (optimize_0plus_b r)\n  | _ => b\n  end.\n\nTheorem optimize_0plus_sound: forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  induction a.\n  - reflexivity.\n  - destruct a1.\n    + destruct n.\n      * simpl. apply IHa2.\n      * simpl. rewrite IHa2. reflexivity.\n    + simpl. simpl in IHa1.\n      rewrite IHa1. rewrite IHa2.\n      reflexivity.\n    + simpl. simpl in IHa1.\n      rewrite IHa1. rewrite IHa2.\n      reflexivity.\n    + simpl. simpl in IHa1.\n      rewrite IHa1. rewrite IHa2.\n      reflexivity.\n  - simpl.\n    rewrite IHa1. rewrite IHa2.\n    reflexivity.\n  - simpl.\n    rewrite IHa1. rewrite IHa2.\n    reflexivity.\nQed.\n\nTheorem optimize_0plus_b_sound : forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros.\n  induction b;\n    try (simpl; reflexivity);\n    try (simpl; repeat rewrite optimize_0plus_sound; reflexivity).\n  - simpl. rewrite IHb. reflexivity.\n  - simpl. rewrite IHb1. rewrite IHb2. reflexivity.\nQed.", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7607140065329766}}
{"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_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": "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/goal81.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7606589514173089}}
{"text": "Set Implicit Arguments.\n\nSection vectors.\n\nVariable (A : Set).\n\nFixpoint vec (n : nat) : Set :=\n  match n with\n  | 0    => unit\n  | S m  => (A*(vec m))%type\n  end.\n\nDefinition vhead (n : nat)(v : vec (S n)) : A :=\n  match v with\n  |(a,w) => a\n  end.\n\nDefinition vtail (n : nat)(v : vec (S n)) : vec n :=\n  match v with\n  |(a,w) => w\n  end.\n\nFixpoint const_vec (n : nat) (a : A) : vec n :=\n  match n with\n    0   => tt \n  | S m => (a,const_vec m a)\n  end. \n\nInductive empty : Type := .\n\nDefinition emptyf : empty -> A.\n  intro.\n  destruct H.\nQed.\n\nFixpoint fin (n : nat) : Set :=\n  match n with \n    0   => empty\n  | S n => (unit + fin n)%type\n  end.\n\n(*\n\nFixpoint rm_nth_vec (n : nat) : forall (m : nat), vec (n + S m) -> vec (n + m) :=\n  match n as n return (forall m : nat, vec (n + S m) -> vec (n + m)) with\n    0   => vtail\n  | S n => fun m v => ((vhead v),(rm_nth_vec n m (vtail v)))\n  end.\n\n*)\n\nFixpoint item_at (n : nat) : fin n -> vec n -> A :=\n  match n as n return fin n -> vec n -> A with\n  |0   => fun i v => emptyf i\n  |S m => fun i v => match i with\n                     |inl tt => vhead v\n                     |inr j  => item_at m j (vtail v)\n                     end\n  end.\n\nLemma vec_ext : forall (n : nat)(v w : vec n),\n  (forall i : fin n, item_at n i v = item_at n i w) -> v = w.\nProof.\n  induction n.\n  intros.\n  destruct v,w; reflexivity.\n  intros.\n  destruct v as [b v'], w as [c w'].\n  assert (b = c).\n  transitivity (item_at (S n) (inl tt) (b,v')).\n  simpl; reflexivity.\n  rewrite H.\n  simpl; reflexivity.\n  assert (v' = w').\n  apply IHn.\n  intro i.\n  transitivity (item_at (S n) (inr i) (b , v')).\n  simpl; reflexivity.\n  rewrite H.\n  simpl; reflexivity.\n  rewrite H0, H1; reflexivity.\nQed.\n\nLemma const_vec_constant : forall (n : nat)(i : fin n)(a : A),\n  item_at n i (const_vec n a) = a.\nProof.\n  intros.\n  induction n.\n  destruct i.\n  destruct i.\n  destruct u.\n  simpl; reflexivity.\n  apply IHn.\nQed.\n\nEnd vectors.\n\n(* Notation borrowed from Coq.Lists.List *)\n\nNotation \" [ ] \" := (tt : vec 0).\nNotation \" [ x ] \" := ((x,tt) : vec 1).\nNotation \" [ x , .. , y ] \" := (pair x .. (pair y tt) ..).\n\nFixpoint vec_ap (A B : Set) (n : nat) : vec (A -> B) n -> A -> vec B n :=\n  match n as n return vec (A -> B) n -> A -> vec B n with\n    0   => fun _ _ => (tt : vec B 0)\n  | S m => fun fs a => ( ((vhead fs) a) , (vec_ap B m (vtail fs) a) )\n  end.\n\nLemma vec_ap_lemma : forall (A B : Set)(n : nat)(i : fin n)(fs : vec (A -> B) n)(a : A),\n  item_at B n i (vec_ap B n fs a) = (item_at (A -> B) n i fs) a.\nProof.\n  intros A B.\n  induction n.\n  intro i; destruct i.\n  intros.\n  destruct fs as [f1 fs'].\n  destruct i.\n  destruct u.\n  simpl.\n  reflexivity.\n  simpl.\n  apply IHn.\nQed.\n\nLemma vec_ap_vtail_comm : forall (A B : Set)(n : nat)(fs : vec (A -> B) (S n))(a : A),\n  vec_ap B n (vtail fs) a = vtail (vec_ap B (S n) fs a).\nProof.\n  intros.\n  auto.\nQed.\n\nFixpoint to_vec(n : nat)(A : Set) : (fin n -> A) -> vec A n :=\n  match n as n return (fin n -> A) -> vec A n with\n  |0     => fun f => (tt : vec A 0)\n  |(S m) => fun f => ( f (inl tt) , to_vec m (fun j => f (inr j)) )\n  end.\n\nLemma to_vec_correct : forall (n : nat)(A : Set)(f : fin n -> A)(i : fin n),\n   item_at A n i (to_vec n f) = f i.\nProof.\n  intro n.\n  induction n.\n  intros.\n  destruct i.\n  intros.\n  destruct i.\n  destruct u.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n", "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/vecs_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7606589434634656}}
{"text": "Module Ex2_7.\n\nRequire Import Arith.\n\n(* Problem 6 *)\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n  intros.\n  SearchAbout (_ + _ < _ + _).\n  apply plus_lt_compat_r.\n  apply H.\nQed.\n\n\n(* Problem 7 *)\nGoal forall P Q : nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\n  intros.\n  apply (H0 0).\n  apply H.\nQed.\n\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\n  intros.\n  exists 1.\n  apply H.\nQed.\n\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\nEnd Ex2_7.\n\nModule Ex2_8.\nRequire 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.\n\nEnd Ex2_8.\n\nModule Ex2_9.\n\nRequire Import Arith.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  SearchAbout (_+(_+_)).\n  rewrite plus_assoc.\n  rewrite plus_assoc.\n  SearchAbout (_+_=_+_).\n  apply NPeano.Nat.add_cancel_r.\n  rewrite <- plus_assoc.\n  rewrite <- plus_assoc.\n  apply NPeano.Nat.add_cancel_l.\n  apply plus_comm.\nQed.\n\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\n  intros.\n  SearchAbout ((_+_)*_).\n  rewrite NPeano.Nat.mul_add_distr_r.\n  rewrite NPeano.Nat.mul_add_distr_l.\n  rewrite NPeano.Nat.mul_add_distr_l.\n  rewrite <- plus_assoc.\n  rewrite <- plus_assoc.\n  apply NPeano.Nat.add_cancel_l.\n  rewrite plus_assoc.\n  rewrite plus_comm.\n  apply NPeano.Nat.add_cancel_l.\n  simpl.\n  SearchAbout (_ + 0).\n  rewrite plus_0_r.\n  rewrite mult_comm.\n  rewrite mult_comm.\n  SearchAbout ((_+_)*_).  \n  rewrite mult_plus_distr_r.\n  reflexivity.\nQed.\n\nEnd Ex2_9.\n\n", "meta": {"author": "katayamak", "repo": "Coq2014", "sha": "bc953683fbe977c69b35311661eedbdaae4d1d61", "save_path": "github-repos/coq/katayamak-Coq2014", "path": "github-repos/coq/katayamak-Coq2014/Coq2014-bc953683fbe977c69b35311661eedbdaae4d1d61/ex02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7606452336756284}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Export MoreCoq.\n\n(** In previous chapters, we have seen many examples of factual\n    claims (_propositions_) and ways of presenting evidence of their\n    truth (_proofs_).  In particular, we have worked extensively with\n    _equality propositions_ of the form [e1 = e2], with\n    implications ([P -> Q]), and with quantified propositions\n    ([forall x, P]).\n\n    This chapter will take us on a first tour of the\n    propositional (logical) side of Coq.\n    In particular, we will expand our repertoire of primitive\n    propositions to include _user-defined_ propositions, not just\n    equality propositions (which are more-or-less \"built in\" to Coq).\n*)\n\n\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(**  As a running example, let's\n    define a simple property of natural numbers -- we'll call it\n    \"[beautiful].\" *)\n\n(** Informally, a number is [beautiful] if it is [0], [3], [5], or the\n    sum of two [beautiful] numbers.\n\n    More pedantically, we can define [beautiful] numbers by giving four\n    rules:\n\n       - Rule [b_0]: The number [0] is [beautiful].\n       - Rule [b_3]: The number [3] is [beautiful].\n       - Rule [b_5]: The number [5] is [beautiful].\n       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is\n         their sum. *)\n\n(** We will see many definitions like this one during the rest\n    of the course, and for purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation: *)\n(**\n                              -----------                               (b_0)\n                              beautiful 0\n\n                              ------------                              (b_3)\n                              beautiful 3\n\n                              ------------                              (b_5)\n                              beautiful 5\n\n                       beautiful n     beautiful m\n                       ---------------------------                      (b_sum)\n                              beautiful (n+m)\n*)\n\n(** Each of the textual rules above is reformatted here as an\n    inference rule; the intended reading is that, if the _premises_\n    above the line all hold, then the _conclusion_ below the line\n    follows.  For example, the rule [b_sum] says that, if [n] and [m]\n    are both [beautiful] numbers, then it follows that [n+m] is\n    [beautiful] too.  If a rule has no premises above the line, then\n    its conclusion hold unconditionally.\n\n    These rules _define_ the property [beautiful].  That is, if we\n    want to convince someone that some particular number is [beautiful],\n    our argument must be based on these rules.  For a simple example,\n    suppose we claim that the number [5] is [beautiful].  To support\n    this claim, we just need to point out that rule [b_5] says so.\n    Or, if we want to claim that [8] is [beautiful], we can support our\n    claim by first observing that [3] and [5] are both [beautiful] (by\n    rules [b_3] and [b_5]) and then pointing out that their sum, [8],\n    is therefore [beautiful] by rule [b_sum].  This argument can be\n    expressed graphically with the following _proof tree_: *)\n(**\n         ----------- (b_3)   ----------- (b_5)\n         beautiful 3         beautiful 5\n         ------------------------------- (b_sum)\n                   beautiful 8\n    Of course, there are other ways of using these rules to argue that\n    [8] is [beautiful], for instance:\n         ----------- (b_5)   ----------- (b_3)\n         beautiful 5         beautiful 3\n         ------------------------------- (b_sum)\n                   beautiful 8\n*)\n\n(** **** Exercise: 1 star (varieties_of_beauty) *)\n(** How many different ways are there to show that [8] is [beautiful]? *)\n\n(* there are infinite number of different ways of showing that [8] is [beautiful].\n\n   Because [0] is beautiful, and we can insert the proof tree:\n\n                ----------- (b_0)\n                 beautiful 0\n\n   into any existing proof tree of beautiful by changing one of the subtree:\n\n               pred X\n            -------------- (rule X)\n              beautiful X\n\n   into:\n\n           pred X\n        -------------- (rule X)  ------------ (b_0)\n          beautiful X            beautiful 0\n        -------------------------------------------- (b_sum)\n                        beautiful X\n\n   Therefore the proofs for [beautiful 8] can be infinite.\n*)\n(** [] *)\n\n(** In Coq, we can express the definition of [beautiful] as\n    follows: *)\n\nInductive beautiful : nat -> Prop :=\n  b_0   : beautiful 0\n| b_3   : beautiful 3\n| b_5   : beautiful 5\n| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).\n\n\n(** The first line declares that [beautiful] is a proposition -- or,\n    more formally, a family of propositions \"indexed by\" natural\n    numbers.  (That is, for each number [n], the claim that \"[n] is\n    [beautiful]\" is a proposition.)  Such a family of propositions is\n    often called a _property_ of numbers.  Each of the remaining lines\n    embodies one of the rules for [beautiful] numbers.\n\n    The rules introduced this way have the same status as proven\n    theorems; that is, they are true axiomatically.\n    So we can use Coq's [apply] tactic with the rule names to prove\n    that particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the rule [b_3]. *)\n   apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n   (* First we use the rule [b_sum], telling Coq how to\n      instantiate [n] and [m]. *)\n   apply b_sum with (n:=3) (m:=5).\n   (* To solve the subgoals generated by [b_sum], we must provide\n      evidence of [beautiful 3] and [beautiful 5]. Fortunately we\n      have rules for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(** As you would expect, we can also prove theorems that have\nhypotheses about [beautiful]. *)\n\nTheorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).\nProof.\n  intros n B.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply B.\nQed.\n\n\n(** **** Exercise: 2 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n  intros n m B. induction m as [|m'].\n  Case \"m = 0\". apply b_0.\n  Case \"m = S m'\". assert (S m' * n = n + m' * n). reflexivity.\n    rewrite H. apply b_sum with (n:=n) (m:=m'*n).\n    apply B. apply IHm'.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** Induction Over Evidence *)\n\n(** Besides _constructing_ evidence that numbers are beautiful, we can\n    also _reason about_ such evidence. *)\n\n(** The fact that we introduced [beautiful] with an [Inductive]\n    declaration tells Coq not only that the constructors [b_0], [b_3],\n    [b_5] and [b_sum] are ways to build evidence, but also that these\n    two constructors are the _only_ ways to build evidence that\n    numbers are beautiful. *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [beautiful n], then we know that [E] must have one of four shapes:\n\n      - [E] is [b_0] (and [n] is [O]),\n      - [E] is [b_3] (and [n] is [3]),\n      - [E] is [b_5] (and [n] is [5]), or\n      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is\n        evidence that [n1] is beautiful and [E2] is evidence that [n2]\n        is beautiful). *)\n\n(** This permits us to _analyze_ any hypothesis of the form [beautiful\n    n] to see how it was constructed, using the tactics we already\n    know.  In particular, we can use the [induction] tactic that we\n    have already seen for reasoning about inductively defined _data_\n    to reason about inductively defined _evidence_.\n\n    To illustrate this, let's define another property of numbers: *)\n\nInductive gorgeous : nat -> Prop :=\n  g_0 : gorgeous 0\n| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)\n| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).\n\n(** **** Exercise: 1 star (gorgeous_tree) *)\n(** Write out the definition of [gorgeous] numbers using inference rule\n    notation.\n\n  ---------- (g_0)\n  gorgeous 0\n\n  forall n. gorgeous n\n  -------------------- (g_plus3)\n  gorgeous (3+n)\n\n  forall n. gorgeous n\n  -------------------- (g_plus5)\n  gorgeous (5+n)\n\n[]\n*)\n\n\n(** **** Exercise: 1 star (gorgeous_plus13) *)\nTheorem gorgeous_plus13: forall n,\n  gorgeous n -> gorgeous (13+n).\nProof.\n  intros n G. assert (13 + n = 3 + (5 + (5 + n))). reflexivity.\n  rewrite H. apply g_plus3. apply g_plus5. apply g_plus5.\n  apply G.\nQed.\n(** [] *)\n\n(** It seems intuitively obvious that, although [gorgeous] and\n    [beautiful] are presented using slightly different rules, they are\n    actually the same property in the sense that they are true of the\n    same numbers.  Indeed, we can prove this. *)\n\nTheorem gorgeous__beautiful : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros n H.\n   induction H as [|n'|n'].\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       apply b_sum. apply b_3.\n       apply IHgorgeous.\n   Case \"g_plus5\".\n       apply b_sum. apply b_5. apply IHgorgeous.\nQed.\n\n(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)\n\n(** Let's see what happens if we try to prove this by induction on [n]\n   instead of induction on the evidence [H]. *)\n\nTheorem gorgeous__beautiful_FAILED : forall n,\n  gorgeous n -> beautiful n.\nProof.\n   intros. induction n as [| n'].\n   Case \"n = 0\". apply b_0.\n   Case \"n = S n'\". (* We are stuck! *)\nAbort.\n\n(** The problem here is that doing induction on [n] doesn't yield a\n    useful induction hypothesis. Knowing how the property we are\n    interested in behaves on the predecessor of [n] doesn't help us\n    prove that it holds for [n]. Instead, we would like to be able to\n    have induction hypotheses that mention other numbers, such as [n -\n    3] and [n - 5]. This is given precisely by the shape of the\n    constructors for [gorgeous]. *)\n\n\n\n\n(** **** Exercise: 2 stars (gorgeous_sum) *)\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m Hn Hm. induction Hn as [|n'|n'].\n  Case \"g_0\". apply Hm.\n  Case \"g_plus3\". apply g_plus3. apply IHHn.\n  Case \"g_plus5\". apply g_plus5. apply IHHn.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros n Bn. induction Bn as [ | | |n' m'].\n  Case \"b_0\". apply g_0.\n  Case \"b_3\". apply g_plus3. apply g_0.\n  Case \"b_5\". apply g_plus5. apply g_0.\n  Case \"b_sum\". apply gorgeous_sum.\n    apply IHBn1. apply IHBn2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (g_times2) *)\n(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].\n    You might find the following helper lemma useful. *)\n\nLemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.\nProof.\n  intros x y z. rewrite plus_assoc.\n  assert (x + z = z + x). apply plus_comm. rewrite H.\n  reflexivity.\nQed.\n\nTheorem g_times2: forall n, gorgeous n -> gorgeous (2*n).\nProof.\n   intros n H. simpl.\n   induction H.\n   Case \"g_0\". apply g_0.\n   Case \"g_plus3\".\n     assert (gorgeous (3+n)) as H3n. apply g_plus3. apply H.\n     apply gorgeous_sum with (n:=3+n).\n     apply H3n. apply gorgeous_sum with (n:=3+n). apply H3n. apply g_0.\n   Case \"g_plus5\".\n     assert (gorgeous (5+n)) as H5n. apply g_plus5. apply H.\n     apply gorgeous_sum with (n:=5+n).\n     apply H5n. apply gorgeous_sum with (n:=5+n). apply H5n. apply g_0.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** From Boolean Functions to Propositions *)\n\n(** In chapter [Basics] we defined a _function_ [evenb] that tests a\n    number for evenness, yielding [true] if so.  We can use this\n    function to define the _proposition_ that some number [n] is\n    even: *)\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n(** That is, we can define \"[n] is even\" to mean \"the function [evenb]\n    returns [true] when applied to [n].\"\n\n    Note that here we have given a name\n    to a proposition using a [Definition], just as we have\n    given names to expressions of other sorts. This isn't a fundamentally\n    new kind of proposition;  it is still just an equality. *)\n\n(** Another alternative is to define the concept of evenness\n    directly.  Instead of going via the [evenb] function (\"a number is\n    even if a certain computation yields [true]\"), we can say what the\n    concept of evenness means by giving two different ways of\n    presenting _evidence_ that a number is even. *)\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\n(** This definition says that there are two ways to give\n    evidence that a number [m] is even.  First, [0] is even, and\n    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some\n    [n] and we can give evidence [e] that [n] is even, then [m] is\n    also even, and [ev_SS n e] is the evidence. *)\n\n\n(** **** Exercise: 1 star (double_even) *)\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros n. induction n as [|n'].\n  Case \"n = 0\". simpl. apply ev_0.\n  Case \"n = S n'\". simpl. apply ev_SS. apply IHn'.\nQed.\n(** [] *)\n\n\n(** *** Discussion: Computational vs. Inductive Definitions *)\n\n(** We have seen that the proposition \"[n] is even\" can be\n    phrased in two different ways -- indirectly, via a boolean testing\n    function [evenb], or directly, by inductively describing what\n    constitutes evidence for evenness.  These two ways of defining\n    evenness are about equally easy to state and work with.  Which we\n    choose is basically a question of taste.\n\n    However, for many other properties of interest, the direct\n    inductive definition is preferable, since writing a testing\n    function may be awkward or even impossible.\n\n    One such property is [beautiful].  This is a perfectly sensible\n    definition of a set of numbers, but we cannot translate its\n    definition directly into a Coq Fixpoint (or into a recursive\n    function in any other common programming language).  We might be\n    able to find a clever way of testing this property using a\n    [Fixpoint] (indeed, it is not too hard to find one in this case),\n    but in general this could require arbitrarily deep thinking.  In\n    fact, if the property we are interested in is uncomputable, then\n    we cannot define it as a [Fixpoint] no matter how hard we try,\n    because Coq requires that all [Fixpoint]s correspond to\n    terminating computations.\n\n    On the other hand, writing an inductive definition of what it\n    means to give evidence for the property [beautiful] is\n    straightforward. *)\n\n\n\n\n(** **** Exercise: 1 star (ev__even) *)\n(** Here is a proof that the inductive definition of evenness implies\n    the computational one. *)\n\nTheorem ev__even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\".\n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".\n    unfold even. apply IHE'.\nQed.\n\n(** Could this proof also be carried out by induction on [n] instead\n    of [E]?  If not, why not? *)\n(* cannot proof by induction on [n]. As mentioned before that\n   inductive definition does not construct [n]s which can be computed.\n*)\n(** [] *)\n\n(** The induction principle for inductively defined propositions does\n    not follow quite the same form as that of inductively defined\n    sets.  For now, you can take the intuitive view that induction on\n    evidence [ev n] is similar to induction on [n], but restricts our\n    attention to only those numbers for which evidence [ev n] could be\n    generated.  We'll look at the induction principle of [ev] in more\n    depth below, to explain what's really going on. *)\n\n(** **** Exercise: 1 star (l_fails) *)\n(** The following proof attempt will not succeed.\n     Theorem l : forall n,\n       ev n.\n     Proof.\n       intros n. induction n.\n         Case \"O\". simpl. apply ev_0.\n         Case \"S\".\n           ...\n   Intuitively, we expect the proof to fail because not every\n   number is even. However, what exactly causes the proof to fail?\n\n   In order to prove [ev n], either [n = 0] or\n   there's a prove for [ev n'] where [n = S (S n')].\n   and the inductive hypothesis is not useful in this case.\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars (ev_sum) *)\n(** Here's another exercise requiring induction. *)\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros n m En Em. induction En as [|n' En'].\n  Case \"ev_0\". simpl. apply Em.\n  Case \"ev_SS n' En'\". simpl. apply ev_SS. apply IHEn'.\nQed.\n(** [] *)\n\n\n(* ####################################################### *)\n(** ** [Inversion] on Evidence *)\n\n(** Another situation where we want to analyze evidence for evenness\n    is when proving that, if [n] is even, then [pred (pred n))] is\n    too.  In this case, we don't need to do an inductive proof.  The\n    right tactic turns out to be [inversion].  *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.  Qed.\n(* p.s. it turns out \"inversion\" can be used here and nothing will be changed\n   so this example might be a little bit confusing...\n*)\n\n(** **** Exercise: 1 star, optional (ev_minus2_n) *)\n(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)\n\n(* works when [n = 0]. but will have no clue to proceed\n   when workings with [n = S n'].\n*)\n(** [] *)\n\n\n(** Another example, in which [inversion] helps narrow down to\nthe relevant cases. *)\n\nTheorem SSev__even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'. Qed.\n\n(** These uses of [inversion] may seem a bit mysterious at first.\n    Until now, we've only used [inversion] on equality\n    propositions, to utilize injectivity of constructors or to\n    discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence\n    for inductively defined propositions.\n\n    (You might also expect that [destruct] would be a more suitable\n    tactic to use here. Indeed, it is possible to use [destruct], but\n    it often throws away useful information, and the [eqn:] qualifier\n    doesn't help much in this case.)\n\n    Here's how [inversion] works in general.  Suppose the name\n    [I] refers to an assumption [P] in the current context, where\n    [P] has been defined by an [Inductive] declaration.  Then,\n    for each of the constructors of [P], [inversion I] generates\n    a subgoal in which [I] has been replaced by the exact,\n    specific conditions under which this constructor could have\n    been used to prove [P].  Some of these subgoals will be\n    self-contradictory; [inversion] throws these away.  The ones\n    that are left represent the cases that must be proved to\n    establish the original goal.\n\n    In this particular case, the [inversion] analyzed the construction\n    [ev (S (S n))], determined that this could only have been\n    constructed using [ev_SS], and generated a new subgoal with the\n    arguments of that constructor as new hypotheses.  (It also\n    produced an auxiliary equality, which happens to be useless here.)\n    We'll begin exploring this more general behavior of inversion in\n    what follows. *)\n\n\n(** **** Exercise: 1 star (inversion_practice) *)\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E'].\n  apply SSev__even. apply E'.\nQed.\n(** The [inversion] tactic can also be used to derive goals by showing\n    the absurdity of a hypothesis. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros E. inversion E. inversion H0. inversion H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)\n(** Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m E En. induction En as [|n' En'].\n  Case \"ev_0\". simpl in E. apply E.\n  Case \"ev_SS n' En'\". apply IHEn'.\n    simpl in E. inversion E. apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus) *)\n(** Here's an exercise that just requires applying existing lemmas.  No\n    induction or even case analysis is needed, but some of the rewriting\n    may be tedious. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros n m p Enm Enp.\n  apply ev_ev__ev with (n:=(n+m)).\n  rewrite plus_assoc. rewrite <- (plus_assoc n m m).\n  rewrite (plus_comm n (m+m)). rewrite <- (plus_assoc (m+m) n p).\n  apply ev_sum. rewrite <- double_plus. apply double_even.\n  apply Enp. apply Enm.\nQed.\n(** [] *)\n\n\n\n\n\n(* ####################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (palindromes) *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n    c : forall l, l = rev l -> pal l\n      may seem obvious, but will not work very well.)\n\n    - Prove that\n       forall l, pal (l ++ rev l).\n    - Prove that\n       forall l, pal l -> l = rev l.\n*)\n\nInductive pal {X:Type} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_single : forall x:X, pal [x]\n  | pal_lr : forall (x:X) (sub : list X), pal sub -> pal (x :: snoc sub x).\n\nTheorem pal_concat_id_rev : forall {X : Type} (l : list X),\n  pal (l ++ rev l).\nProof.\n  intros X l. induction l.\n  Case \"l = nil\". simpl. apply pal_nil.\n  Case \"l = x:l'\". simpl. rewrite <- snoc_with_append. apply pal_lr.\n  apply IHl.\nQed.\n\nTheorem pal_id_is_rev : forall {X : Type} (l : list X),\n  pal l -> l = rev l.\nProof.\n  intros X l H. induction H. reflexivity. reflexivity.\n  simpl. rewrite rev_snoc. simpl. rewrite <- IHpal. reflexivity.\nQed.\n\n(** **** Exercise: 5 stars, optional (palindrome_converse) *)\n(** Using your definition of [pal] from the previous exercise, prove\n    that\n     forall l, l = rev l -> pal l.\n*)\n\nFixpoint list_head {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h :: t => Some h\n  end.\n\nDefinition list_last {X : Type} (l : list X) : option X :=\n  list_head (rev l).\n\nTheorem palindrome_head_last : forall (X : Type) (l : list X),\n  l = rev l -> list_head l = list_last l.\nProof.\n  intros X l Hl. unfold list_last. rewrite <- Hl. reflexivity.\nQed.\n\nFixpoint list_tail {X : Type} (l : list X) : option (list X) :=\n  match l with\n  | [] => None\n  | h :: t => Some t\n  end.\n\nDefinition list_init {X : Type} (l : list X) : option (list X) :=\n  match list_tail (rev l) with\n  | None => None\n  | Some l' => Some (rev l')\n  end.\n\nLemma palindrome_rev_hd_lt : forall {X : Type} (l : list X),\n  l = rev l -> list_head l = list_last l.\nProof.\n  intros X l Hri. induction l. reflexivity.\n  simpl. unfold list_last. rewrite Hri. rewrite rev_involutive. reflexivity.\nQed.\n\nLemma pal_aux :\n  forall (X:Type) (l : list X) (x : X),\n    (l = rev l -> pal l) -> l = rev l -> pal (x :: snoc l x).\nProof.\n  intros X l x Hrev HInd. apply pal_lr. apply Hrev. apply HInd.\nQed.\n\n(*\nInductive tril (X : Type) : Type :=\n  | tril_nil : tril X\n  | tril_single : X -> tril X\n  | tril_sub : X -> tril X -> X -> tril X.\n\nFixpoint tril_to_list (X : Type) (l : list X) : tril X :=\n  match l with\n    | [] => tril_nil X\n    | (h::t) =>\n      match t with\n        | [] => tril_single X h\n        | t2 => match list_init t2 with\n                  | None => tril_nil X\n                  | Some sub => match list_last t2 with\n                                 | None => tril_nil\n                                 | Some y => tril_sub X (tril_to_list X sub) y\n                                end\n                end\n      end\n  end.\n *)\n\nTheorem palindrome_converse : forall (X : Type) (l : list X),\n  l = rev l -> pal l.\nProof.\n  intros X l eq1. induction l.\nAbort.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (subsequence) *)\n(** A list is a _subsequence_ of another list if all of the elements\n    in the first list occur in the same order in the second list,\n    possibly with some extra elements in between. For example,\n    [1,2,3]\n    is a subsequence of each of the lists\n    [1,2,3]\n    [1,1,1,2,2,3]\n    [1,2,7,3]\n    [5,6,1,9,9,2,7,3,8]\n    but it is _not_ a subsequence of any of the lists\n    [1,2]\n    [1,3]\n    [5,6,2,1,7,3,8]\n\n    - Define an inductive proposition [subseq] on [list nat] that\n      captures what it means to be a subsequence. (Hint: You'll need\n      three cases.)\n\n    - Prove that subsequence is reflexive, that is, any list is a\n      subsequence of itself.\n\n    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a\n      subsequence of [l2], then [l1] is also a subsequence of [l2 ++\n      l3].\n\n    - (Optional, harder) Prove that subsequence is transitive -- that\n      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence\n      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your\n      induction carefully!\n *)\nInductive subseq : list nat -> list nat -> Prop :=\n  subseq_nil_any : forall ys, subseq nil ys\n| subseq_h1_h2 : forall xs ys a, subseq xs ys -> subseq (a::xs) (a::ys)\n| subseq_h1_any : forall xs ys a, subseq xs ys -> subseq xs (a::ys).\n\nTheorem subseq_reflexive :\n  forall xs,\n    subseq xs xs.\nProof.\n  intros xs. induction xs.\n  Case \"nil nil\". apply subseq_nil_any.\n  Case \"h1 h2\". apply subseq_h1_h2. apply IHxs.\nQed.\n\n(*\nLemma cons_list_app_rev:\n  forall (X : Type) (a : X) (xs : list X),\n    a :: (rev xs) = [a] ++ (rev xs).\nProof.\n  intros. induction xs.\n  reflexivity. simpl. rewrite <- rev_cons. reflexivity.\nQed.\n\nLemma cons_list_app:\n  forall (X : Type) (a : X) (xs : list X),\n    a :: xs = [a] ++ xs.\nProof.\n  intros. assert (xs = (rev (rev xs))). rewrite rev_involutive. reflexivity.\n  rewrite H. apply cons_list_app_rev.\nQed.\n\nLemma cons_app:\n  forall (X : Type) (a : X) (xs ys : list X),\n    (a :: xs) ++ ys = a :: xs ++ ys.\nProof.\n  intros. apply cons_list_app.\nQed.\n\nTheorem subseq_append_one :\n  forall l1 l2 a,\n    subseq l1 l2 -> subseq l1 (l2 ++ [a]).\nProof.\n  intros. induction H. apply subseq_nil_any.\n  rewrite cons_app. apply subseq_h1_h2. apply IHsubseq.\n  apply subseq_h1_any. apply IHsubseq.\nQed.*)\n\nTheorem subseq_append:\n  forall l1 l2 l3,\n    subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros l1 l2 l3 H1. induction H1.\n  Case \"nil any\". apply subseq_nil_any.\n  Case \"h1 h2\". apply subseq_h1_h2. apply IHsubseq.\n  Case \"h1 any\". apply subseq_h1_any. apply IHsubseq.\nQed.\n(** [] *)\n\nTheorem subseq_transitive:\n  forall l1 l2 l3,\n    subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3.\nAbort.\n\n(** **** Exercise: 2 stars, optional (R_provability) *)\n(** Suppose we give Coq the following definition:\n    Inductive R : nat -> list nat -> Prop :=\n      | c1 : R 0 []\n      | c2 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, R (S n) l -> R n l.\n    Which of the following propositions are provable?\n\n    - [R 2 [1,0]]\n    - [R 1 [1,2,1,0]]\n    - [R 6 [3,2,1,0]]\n*)\nInductive R : nat -> list nat -> Prop :=\n  | c1 : R 0 []\n  | c2 : forall n l, R n l -> R (S n) (n :: l)\n  | c3 : forall n l, R (S n) l -> R n l.\n\nTheorem r_provable1: R 2 [1;0].\nProof. apply c2,c2,c1. Qed.\n\nTheorem r_provable2: R 1 [1;2;1;0].\nProof. apply c3,c2,c3,c3,c2,r_provable1. Qed.\n\n(* the third one is not provable. since whenever \"n\" increases,\n   the list gets longer, therefore \"n\" is less or equal to the list length.\n *)\nTheorem r_n_le_len:\n  forall n l,\n    R n l -> n <= length l.\nProof.\n  intros. induction H. reflexivity.\n  simpl. apply Le.le_n_S. apply IHR.\n  apply Le.le_Sn_le. apply IHR.\nQed.\n(** [] *)\n\n(* $Date: 2013-07-01 18:48:47 -0400 (Mon, 01 Jul 2013) $ *)\n", "meta": {"author": "Javran", "repo": "Thinking-dumps", "sha": "bfb0639c81078602e4b57d9dd89abd17fce0491f", "save_path": "github-repos/coq/Javran-Thinking-dumps", "path": "github-repos/coq/Javran-Thinking-dumps/Thinking-dumps-bfb0639c81078602e4b57d9dd89abd17fce0491f/software-foundations/old/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.7606452166803122}}
{"text": "Require Export Unions.\n\nDefinition FamUnion (X : set) (F : set → set) : set := Union (Repl F X).\n\nLemma FamUnion_I : ∀ X F x y, x ∈ X → y ∈ (F x) → y ∈ (FamUnion X F).\nProof.\n  intros. compute.\n  apply Union_I with (Y := F x). auto.\n  apply Repl_I. auto.\nQed.\n\nHint Resolve FamUnion_I.\n\nLemma FamUnion_E : ∀ X F y, y ∈ (FamUnion X F) → ∃ x, x ∈ X ∧ y ∈ (F x ).\nProof.\n  intros. compute in H.\n  apply Union_E in H. destruct H. inv H.\n  apply Repl_E in H1. destruct H1. inv H.\n  exists x0. split; auto.\nQed.\n\nHint Resolve FamUnion_E.\n\n(* Properties of the union over families of indexed sets.\n\n   1. ∪ x∈∅ Fx = ∅\n   2. (∀x ∈ X, Fx ∈ 2) −→ (∃x ∈ X, Fx = 1) −→ ∪ x∈X Fx = 1\n   3. inhset X −→ (∀x ∈ X, Fx = C) −→ ∪ x∈X Fx = C\n   4. (∀x ∈ X, Fx = ∅) −→ ∪ x∈X Fx = ∅\n   5. (∀x ∈ X, Fx ∈ 2) −→ ∪ x∈X Fx ∈ 2\n*)\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/Families.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7606049356433884}}
{"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(* ################################################################# *)\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\n(* Inductive le' (n m : nat) : Prop := *)\n(*   | le_n_ : le' n n *)\n(*   | le_S_ : le' n m -> le' n (S m). *)\n\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. *)\nTheorem all_eq_total : ~ (partial_function all_eq).\nProof.\n  unfold not. unfold partial_function. intros.\n  assert (0 = 1) as Nope. {\n    apply H with (x := 0).\n    - apply eq. reflexivity.\n    - apply neqM. apply le_S. apply le_n.\n  } inversion Nope. Qed.\n\n\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(* DISUCSS THIS IN MEETING. HOW DO YOU ACTUALLY DEFINE AN EMPTY RELATION *)\nTheorem never_eq : partial_function never_eq.\nProof.\n  unfold partial_function. intros. inversion H. inversion H0. reflexivity. Qed.\n\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 in Hnm. apply Hnm.\n  -  apply le_S in IHHm'o. 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 as [].\n    + apply le_S. apply Hnm.\n    + apply le_S. apply IHHmo.\nQed.\n\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, optional (le_S_n)  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros. inversion H. trivial. apply le_Sn_le. apply H1. Qed.\n\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    writing an informal proof without doing the formal proof first.\n\n    Proof: *)\n    (* induction on n, the base case follows from the definition of <=*)\n    (* The inductive case, when n = S n', follows equally as trivially *)\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. unfold not. intros.\n  induction n as [].\n  - inversion H.\n  - apply IHn. apply le_S_n. apply H. Qed.\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 not. unfold symmetric. intros.\n  assert (1 <= 0) as Nope. {\n    apply H. apply le_S, le_n.\n  } inversion Nope. Qed.\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, optional (le_antisymmetric)  *)\nLemma Sn_le_n_false: forall n : nat, (S n) <= n -> False.\n  Proof.\n    intros.  induction n as [].\n    - inversion H.\n    - apply IHn. apply le_Sn_n in H. inversion H.\n  Qed.\n\n  (* WHY CANT WE FORWARD PROVE WITH LE_TRANS IN THE HYPOTHESIS??? *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric. intros. destruct H as [].\n  - trivial.\n  - assert (S m <= m) as Hn. {\n      apply le_trans with (S m). trivial. apply le_trans with a. apply H0. apply H.\n    } apply Sn_le_n_false in Hn. inversion Hn.\nQed.\n\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  intros. unfold lt in H. apply le_S_n. apply le_trans with m.\n  - apply H.\n  - apply H0.\nQed.\n\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", "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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.8947894724152068, "lm_q1q2_score": 0.760545270036441}}
{"text": "Require Export ZArith List Arith Bool.\n\nInductive month : Set\n  := January | February | March | April | May | June\n     | July | August | September | October | November | December.\n\n(* Exercise 6.1\n   Define an inductive type for seasons and then use the function\n   [month_rec] to define a function that maps every month to the season that\n   contains most of its days. *)\nInductive season : Set := Winter | Spring | Summer | Fall.\n\nCheck season_rec.\n(* season_rec : forall P : season -> Set,\n   P Winter -> P Spring -> P Summer -> P Fall\n   -> forall s : season, P s *)\n\nDefinition is_winter : season -> bool.\n  intro s. apply season_rec.\n  - (* Winter *) exact true.\n  - (* Spring *) exact false.\n  - (* Summer *) exact false.\n  - (* Fall   *) exact false.\n  - exact s.\nDefined.\n\nPrint is_winter.\n(* is_winter : season -> bool\n   := fun s : season\n      => season_rec (fun _ : season => bool) true false false false s *)\n\nCompute (is_winter Winter). (* = true : bool *)\nCompute (is_winter Fall). (* = false : bool *)\n\nDefinition season_of_month : month -> season\n  := month_rec (fun _ : month => season)\n               Winter Winter\n               Spring Spring Spring\n               Summer Summer Summer\n               Fall Fall Fall\n               Winter.\n\nCompute (season_of_month December). (* = Winter : season *)\nCompute (season_of_month July). (* = Summer : season *)\n\n(* Exercise 6.2\n   What are the types of [bool_ind] and [bool_rec] that are\n   generated by the Coq system for the type bool? *)\nCheck bool_ind.\n(* bool_ind : forall P : bool -> Prop,\n     P true -> P false -> forall b : bool, P b *)\n\n(* 6.1.2 Simple Reasoning and Computing *)\nTheorem month_equal (m : month)\n : m=January \\/ m=February \\/ m=March \\/ m=April \\/ m=May \\/ m=June\n   \\/ m=July \\/ m=August \\/  m=September \\/ m=October \\/ m=November\n   \\/ m=December.\nProof. destruct m; auto 12. Qed.\n\n(** explicit use of month_ind: *)\nTheorem month_equal' (m : month)\n : m=January \\/ m=February \\/ m=March \\/ m=April\n   \\/ m=May \\/ m=June \\/ m=July \\/ m=August\n   \\/ m=September \\/ m=October \\/ m=November \\/ m=December.\nProof. pattern m. apply month_ind; auto 12. Qed.\n\n(* Exercise 6.3 Prove in two different ways the following theorem:\n   1. Give directly a proof term, with occurences of\n      bool_ind, or_introl, or_intror and refl_equal.\n   2. Use the following tactics :\n      pattern, apply, left, right, and reflexivity. *)\nTheorem bool_cases (b : bool) : b = true \\/ b = false.\nProof.\n  exact (bool_ind (fun c => c = true \\/ c = false)\n                  (or_introl eq_refl)\n                  (or_intror eq_refl) b).\nQed.\n\nTheorem bool_cases' (b : bool) : b = true \\/ b = false.\nProof. pattern b. apply bool_ind; [left | right]; reflexivity. Qed.\n\nTheorem bool_cases'' (b : bool) : b = true \\/ b = false.\nProof. destruct b; [left | right]; reflexivity. Qed.\n\n(* 6.1.4 Pattern Matching *)\nCheck (fun b : bool => match b with false => 45 | true => 33 end).\n(* fun b : bool => if b then 33 else 45 : bool -> nat *)\n\nDefinition month_length (leap : bool) (m : month) : nat\n  := match m with\n     | January => 31 | February => if leap then 29 else 28\n     | March => 31   | April => 30    | May => 31  | June => 30\n     | July => 31    | August => 31   | September => 30\n     | October => 31 | November => 30 | December => 31\n     end.\n\nDefinition month_length' (leap : bool)\n  := month_rec (fun _ : month => nat)\n               31 (if leap then 29 else 28)\n               31 30 31 30 31 31 30 31 30 31.\n\nDefinition month_length'' (leap : bool) (m : month)\n  := match m with\n     | February => if leap then 29 else 28\n     | April  | June  | September | November => 30\n     | _  => 31\n     end.\n\nExample month_length_eq1 : month_length = month_length'.\nProof. reflexivity. Qed.\n\nExample month_length_eq2 : month_length = month_length''.\nProof. reflexivity. Qed.\n\nEval compute in (fun leap => month_length leap November).\n(* = fun _ : bool => 30 : bool -> nat *)\n\nExample length_february : month_length false February = 28.\nProof. reflexivity. Qed.\n\n(* Exercise 6.4\n   Using the type introduced for seasons in Exercise 6.1 page 139,\n   write the function that maps any month to the season\n   that contains most of its days, this time\n   using the pattern matching construct. *)\n\nDefinition season_of_month' (m : month) : season\n  := match m with\n     | December | January | February => Winter\n     | March | April | May => Spring\n     | June | July | August => Summer\n     | September | October | November => Fall\n     end.\n\nExample season_of_month_eq : season_of_month = season_of_month'.\nProof. reflexivity. Qed.\n\n(* Exercise 6.5\n   Write the function that maps every month that has an even\n   number of days to the boolean value true and the others to false. *)\nDefinition is_even_days_in_month (leap : bool) (m : month)\n  := Nat.even (month_length leap m).\n\n(* Exercise 6.6\n   Define the functions associated with the following boolean connectives:\n   Notice that these functions are already defined in the standard library\n   under the names negb, orb, andb, xorb and Bool.eqb. *)\nDefinition bool_not (b : bool) : bool := if b then false else true.\nDefinition bool_or (a b : bool) : bool\n  := if a then true else\n       if b then true else false.\nDefinition bool_and (a b : bool) : bool := if a then b else false.\nDefinition bool_xor (a b : bool) : bool\n  := if a then bool_not b else b.\nDefinition bool_eq (a b : bool) : bool\n  := if a then b else bool_not b.\n\n(* Prove the following theorems: *)\nTheorem bool_xor_not_eq (b1 b2 : bool)\n  : bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof. destruct b1, b2; reflexivity. Qed.\n\nTheorem bool_not_and (b1 b2 : bool)\n  : bool_not (bool_and b1 b2) = bool_or (bool_not b1) (bool_not b2).\nProof. destruct b1, b2; reflexivity. Qed.\n\nTheorem bool_not_not (b : bool) : bool_not (bool_not b) = b.\nProof. destruct b; reflexivity. Qed.\n\nTheorem bool_tex (b : bool) : bool_or b (bool_not b) = true.\nProof. destruct b; reflexivity. Qed.\n\nTheorem bool_eq_reflect (b1 b2 : bool) : bool_eq b1 b2 = true -> b1 = b2.\nProof.\n  destruct b1, b2; simpl; intro H;\n    try rewrite H; reflexivity.\nQed.\n\nTheorem bool_eq_reflect2 (b1 b2 : bool) : b1 = b2 -> bool_eq b1 b2 = true.\nProof. intro H. subst b2. destruct b1; reflexivity. Qed.\n\nTheorem bool_not_or (b1 b2 : bool)\n  : bool_not (bool_or b1 b2) = bool_and (bool_not b1) (bool_not b2).\nProof. destruct b1, b2; reflexivity. Qed.\n\nTheorem bool_or_and_distr (b1 b2 b3 : bool)\n  : bool_or (bool_and b1 b3) (bool_and b2 b3) = bool_and (bool_or b1 b2) b3.\nProof. destruct b1, b2, b3; reflexivity. Qed.\n\n(* 6.1.5 Record Types *)\nOpen Scope Z_scope.\nInductive plane : Set := point : Z -> Z -> plane.\n(*\nplane is defined\nplane_rect is defined\nplane_ind is defined\nplane_rec is defined\nplane_sind is defined\n*)\n\nCheck point. (* point : Z -> Z -> plane *)\nCheck plane_ind.\n(* plane_ind : forall P : plane -> Prop,\n   (forall z z0 : Z, P (point z z0)) -> forall p : plane, P p *)\n\nDefinition abscissa (p : plane) : Z\n  := match p with point x y => x end.\nCheck abscissa. (* abscissa : plane -> Z *)\n\nReset plane. (* also reset [abscissa] *)\n\nRecord plane : Set := point {abscissa : Z; ordinate : Z}.\n(*\nplane is defined\nabscissa is defined\nordinate is defined\n*)\nPrint plane.\n(* Record plane : Set := point { abscissa : Z;  ordinate : Z } *)\nCheck point. (* point : Z -> Z -> plane *)\nCheck abscissa. (* abscissa : plane -> Z *)\nPrint abscissa.\n(* abscissa : plane -> Z\n   := fun p : plane => let (abscissa, _) := p in abscissa *)\n\n(* Exercise 6.7 What is the type of plane_rec? *)\n(* Check plane_rec. *)\n(* Error: The reference plane_rec was not found in the current environment. *)\n\n(* Exercise 6.8\n   Define a function that computes the \"Manhattan\" distance for\n   points of the plane (the Manhattan distance\n   is the sum of the absolute values of differences of coordinates). *)\nDefinition manhattan_distance (p1 p2 : plane) : Z\n  := let (x1, y1) := p1 in\n     let (x2, y2) := p2 in\n     Z.abs (x1 - x2) + Z.abs (y1 - y2).\n\nCheck (point 1 2).\nCheck (point 1 (-2)).\n\nExample manhattan_distance_ex\n  : manhattan_distance (point (-1) (-2)) (point 4 2) = 9.\nProof. reflexivity. Qed.\n\n(* 6.1.6 Records with Variants *)\nInductive vehicle : Set\n  := bicycle (* [number of seats] *) : nat -> vehicle\n   | motorized (* [number of seats, number of wheels] *)\n     : nat -> nat -> vehicle.\n\nCheck vehicle_ind.\n(* vehicle_ind : forall P : vehicle -> Prop,\n   (forall n : nat, P (bicycle n)) ->\n   (forall n n0 : nat, P (motorized n n0)) -> forall v : vehicle, P v *)\n\nDefinition nb_seats (v : vehicle) : nat\n  := match v with\n     | bicycle n => n\n     | motorized n _ => n\n     end.\n\nDefinition nb_wheels (v : vehicle) : nat\n  := match v with\n     | bicycle _ => 2\n     | motorized _ m => m\n     end.\n\n(* Exercise 6.9\n   What is the type of [vehicle_rec]? Use this function to define\n   an equivalent to [nb_seats]. *)\nCheck vehicle_rec.\n(* vehicle_rec : forall P : vehicle -> Set,\n   (forall n : nat, P (bicycle n)) ->\n   (forall n n0 : nat, P (motorized n n0)) -> forall v : vehicle, P v *)\n\nDefinition nb_seats' : vehicle -> nat\n  := vehicle_rec (fun _ : vehicle => nat)\n                 (fun n => n)\n                 (fun n _ => n).\n\nExample nb_seats_eq : nb_seats = nb_seats'.\nProof. reflexivity. Qed.\n\n(* 6.2 Case-Based Reasoning *)\nOpen Scope nat_scope.\nTheorem at_least_28 (leap : bool) (m : month)\n  : 28 <= month_length leap m.\nProof. case m, leap; simpl; auto with arith. Qed.\n\nTheorem at_least_28' (leap : bool) (m : month)\n  : 28 <= month_length leap m.\nProof.\n  case m, leap; simpl;\n    repeat ( try apply le_n; apply le_S ).\nQed.\n\nPrint at_least_28.\n(* at_least_28 : forall (leap : bool) (m : month), 28 <= month_length leap m\n  := fun (leap : bool) (m : month) =>\n       match m as m0 return (28 <= month_length leap m0) with\n       | January =>\n         if leap as b return (28 <= month_length b January)\n         then le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n         else le_S 28 30 (le_S 28 29 (le_S 28 28 (le_n 28)))\n       | February =>\n         if leap as b return (28 <= month_length b February)\n         then le_S 28 28 (le_n 28)\n         else le_n 28\n       ...\n       end. *)\n\n(* 6.2.2.1 The discriminate Tactic *)\nDefinition next_month (m : month)\n  := match m with\n     | January => February  | February => March | March => April\n     | April => May         | May => June       | June => July\n     | July => August       | August => September\n     | September => October | October => November\n     | November => December | December => January\n     end.\n\nTheorem next_august_then_july (m : month) : next_month m = August -> m = July.\nProof.\n  case m; simpl; intros H;\n    (reflexivity || discriminate H).\nQed.\n\n(* 6.2.2.2 ** The Inner Workings of discriminate *)\nTheorem not_January_eq_February : January <> February.\nProof. discriminate. Qed.\n\n(* not using [discriminate] *)\nTheorem not_January_eq_February' : January <> February.\nProof.\n  unfold not. intros H.\n  change ((fun m : month\n           => match m with | January => True | _ => False end)\n            February).\n  now rewrite <- H.\nQed.\n\n(* not using [change], [rewrite] and [reflexivity] *)\nTheorem not_January_eq_February'' : January <> February.\nProof.\n  unfold not. intros H.\n  pose (f := (fun m : month\n              => match m with\n                 | January => True\n                 | _ => False end)).\n  apply (eq_ind (f February) (fun P => P)).\n  - apply (eq_ind January f).\n    + unfold f. apply I.\n    + exact H.\n  - unfold f. apply eq_refl.\nQed.\n\n(* Exercise 6.10\n   Define a function [is_January] that maps [January] to [True]\n   and any other month to [False], using the function [month_rect]. *)\nDefinition is_January' (m : month) : Prop\n  := match m with\n     | January => True\n     | _ => False\n     end.\n\nDefinition is_January : month -> Prop\n  := month_rect (fun _ => Prop)\n                True\n                False False False False False False False False\n                False False False.\n\nExample is_January_eq : is_January = is_January'.\nProof. reflexivity. Qed.\n\n(* Try to automate applying [month_rect (fun _ => Prop) True]\n   to [False] 11 times *)\nDefinition add_arg_type (A B : Type) : Type := A -> B.\nCompute ((add_arg_type Prop) ((add_arg_type Prop) nat)).\n(* = Prop -> Prop -> nat : Type *)\n\nFixpoint iterate (A : Type) (f : A -> A) (n : nat) (a : A) : A\n  := match n with\n     | O => a\n     | S n' => iterate A f n' (f a)\n     end.\nCompute (iterate nat S 3 O). (* = 3 : nat *)\nCompute (iterate Type (add_arg_type Prop) 3 nat).\n(* = Prop -> Prop -> Prop -> nat : Type *)\n\nDefinition add_n_arg_types (A B : Type) (n : nat) : Type\n  := (iterate Type (add_arg_type A) n B).\nCompute (add_n_arg_types Prop nat 3).\n(* = Prop -> Prop -> Prop -> nat : Type *)\nCompute (add_n_arg_types Prop nat 0). (* = nat : Type *)\n\n(* TODO Attempt failed *)\n(* Fixpoint repeat_arg (A B : Type) (a : A)\n         (n : nat) (f : add_n_arg_types A B n) : B\n  := match n with\n     | O => f (* The term \"f\" has type \"add_n_arg_types A B n\"\n                 while it is expected to have type \"B\". *)\n     | S n' => repeat_arg A B a n' (f a)\n     end. *)\n\n(* Fixpoint repeat_arg (A B : Type) (a : A)\n         (n : nat) (f : add_n_arg_types A B n) : B\n  := match n\n           return (match n with\n                   | O => add_n_arg_types A B n\n                   | S n' => add_n_arg_types A B n'\n                   end)\n     with\n     | O => f (* The term \"f\" has type \"add_n_arg_types A B n\"\n                 while it is expected to have type \"add_n_arg_types A B 0\". *)\n     | S n' => repeat_arg A B a n' (f a)\n     end. *)\n\nReset iterate.\n\n(* Exercise 6.11 *\n   Use the same technique to build a proof of [true <> false]. *)\nTheorem true_is_not_false : true <> false.\nProof. discriminate. Qed.\n\nTheorem true_is_not_false' : true <> false.\nProof.\n  intro H.\n  change ((fun b : bool => if b then True else False) false).\n  now rewrite <- H.\nQed.\n\n(* Exercise 6.12\n   For the [vehicle] type (see Sect. 6.1.6), use the same technique\n   to build a proof that no [bicycle] is equal to a [motorized] vehicle. *)\nTheorem bicycle_is_not_motorized (n m : nat) : bicycle n <> motorized n m.\nProof. discriminate. Qed.\n\nTheorem bicycle_is_not_motorized' (n m : nat) : bicycle n <> motorized n m.\nProof.\n  intro H.\n  change ((fun v : vehicle\n           => match v with\n              | bicycle _ => False\n              | motorized _ _ => True\n              end) (bicycle n)).\n  now rewrite H.\nQed.\n\n(* 6.2.3 Injective Constructors *)\nTheorem bicycle_eq_seats (x1 y1 : nat) : bicycle x1 = bicycle y1 -> x1 = y1.\nProof. intro H. now injection H. Qed.\n\n(* Simulating injection (for the fun) *)\nTheorem bicycle_eq_seats' (x1 y1 : nat) : bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intro H.\n change (nb_seats (bicycle x1) = nb_seats (bicycle y1)).\n rewrite H. reflexivity.\nQed.\n\n(* use more primitive tactics *)\nTheorem bicycle_eq_seats'' (x1 y1 : nat) : bicycle x1 = bicycle y1 -> x1 = y1.\nProof.\n intro H.\n apply (eq_ind (bicycle x1)\n               (fun v : vehicle => nb_seats (bicycle x1) = nb_seats v)\n               (eq_refl (nb_seats (bicycle x1)))\n               (bicycle y1) H).\nQed.\n\nSection injection_example.\n  Variables A B : Set.\n  Inductive T : Set := c1 : A -> T | c2 : B -> T.\n\n  Theorem inject_c2 (x y : B) : c2 x = c2 y -> x = y.\n  Proof using. intro H. now injection H. Qed.\n\n  Theorem inject_c2' (x y : B) : c2 x = c2 y -> x = y.\n  Proof using.\n    intro H.\n    pose (fun t : T => match t with | c1 a => x | c2 b => b end) as f.\n    change (f (c2 x) = f (c2 y)).\n    rewrite H. reflexivity.\n  Qed.\nEnd injection_example.\n\n(* 6.2.4 Inductive Types and Equality *)\n\n(* Exercise 6.13 **\n   This exercise shows a use of discriminate and underlines\n   the danger of adding axioms to the system.\n   The ''theory'' introduced here proposes a description of rational numbers\n   as fractions with a non-zero denominator. An axiom is added to\n   indicate that two rational numbers are equal as soon\n   as they satisfy a classical arithmetic condition. *)\n\nRequire Import Arith.\n\nRecord RatPlus : Set\n  := mkRat {top : nat; bottom : nat; bottom_condition : bottom <> 0}.\n\nAxiom eq_RatPlus : forall r1 r2 : RatPlus,\n    top r1 * bottom r2 = top r2 * bottom r1 -> r1 = r2.\n\nTheorem eq_RatPlus_imp_False : False.\nProof.\n  pose (mkRat 1 1 (Nat.neq_succ_0 _)) as r1.\n  pose (mkRat 2 2 (Nat.neq_succ_0 _)) as r2.\n  assert (r1 = r2) as eq.\n  { apply eq_RatPlus. reflexivity. }\n  discriminate eq.\nQed.\n\nReset RatPlus.\n\n(* 6.2.5 * Guidelines for the case Tactic *)\n(* solution from authors *)\nTheorem next_march_shorter (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  intros H.\n  case_eq m1; intro eq; rewrite eq in H; simpl in H;\n    try discriminate H.\n  case leap, m2; simpl; auto with arith.\nQed.\n\n(* my solution using destruct *)\nTheorem next_march_shorter1 (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  intros H. destruct m1; simpl in H; try discriminate H.\n  destruct leap, m2; simpl; auto with arith.\nQed.\n\n(* my solution using [case] with delaying [into] *)\nTheorem next_march_shorter2 (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  case m1; simpl; intro H; try discriminate H.\n  case leap, m2; simpl; auto with arith.\nQed.\n\n(* use generalize *)\nTheorem next_march_shorter3 (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  intro H. generalize H. clear H.\n  case m1; simpl; intros H; try discriminate H.\n  case leap, m2; simpl; auto with arith.\nQed.\n\n(* introduce equality *)\nTheorem next_march_shorter4 (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  intro H. generalize (eq_refl m1). pattern m1 at -1.\n  case m1; intro eq; rewrite eq in H; simpl in H;\n    try discriminate H.\n  case leap, m2; simpl; auto with arith.\nQed.\n\n(* how to define own case_eq tactic *)\nLtac caseEq f := generalize (refl_equal f); pattern f at -1; case f.\n\n(* test it *)\nTheorem next_march_shorter5 (leap : bool) (m1 m2 : month)\n  : next_month m1 = March\n    -> month_length leap m1 <= month_length leap m2.\nProof.\n  intros H.\n  caseEq m1; intro eq; rewrite eq in H; simpl in H;\n    try discriminate H.\n  case leap, m2; simpl; auto with arith.\nQed.\n\n(* New exercise - On partial functions\n Complete the following development: *)\nSection partial_functions.\n  Variable P : nat -> Prop.\n  Variable f : nat -> option nat.\n\n  Hypothesis f_domain : forall n, P n <-> f n <> None.\n\n  Definition g n : option nat\n    := match f (n + 2) with\n       | None => None\n       | Some y => Some (y + 2)\n       end.\n\n  Lemma g_domain : forall n, P (n + 2) <-> g n <> None.\n  Proof using f_domain.\n    intro n. unfold g. split; intro H.\n    - cut (f (n + 2) <> None).\n      + intro H'.\n        destruct (f (n + 2)) eqn:eq; [discriminate | assumption].\n      + apply f_domain, H.\n    - apply f_domain.\n      destruct (f (n + 2)) eqn:eq; [discriminate | assumption].\n  Qed.\n\nEnd partial_functions.\n\n(* 6.3 Recursive Types *)\nPrint nat. (* Inductive nat : Set :=  O : nat | S : nat -> nat *)\nCheck plus. (* Init.Nat.add : nat -> nat -> nat *)\nCheck plus_O_n. (* plus_O_n : forall n : nat, 0 + n = n *)\nCheck plus_Sn_m. (* plus_Sn_m : forall n m : nat, S n + m = S (n + m) *)\n\n(* A first, detailed, proof of associativity of + *)\n(* authors' solution *)\nTheorem plus_assoc (x y z : nat) : x + (y + z) = (x + y) + z.\nProof.\n  induction x as [| x0 IH].\n  - simpl. reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\n(* my variation *)\nTheorem plus_assoc' (x y z : nat) : (x + y) + z = x + (y + z).\nProof.\n  induction x as [| x' IH]; simpl; [| rewrite IH]; reflexivity.\nQed.\n\nTheorem plus_assoc'' (x y z : nat) : (x + y) + z = x + (y + z).\nProof.\n  pattern x.\n  apply nat_ind; simpl; [| intros x' IH; rewrite IH]; reflexivity.\nQed.\n\nTheorem plus_n_O (n : nat) : n + 0 = n.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem plus_n_Sm (n m : nat) : n + (S m) = S (n + m).\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem plus_comm (n m : nat) : n + m = m + n.\nProof.\n  induction n as [| p IH].\n  - rewrite plus_n_O. reflexivity.\n  - simpl. rewrite IH, plus_n_Sm. reflexivity.\nQed.\n\n(* 6.3.3 Recursive Programming *)\nFixpoint mult2 (n : nat) : nat\n  := match n with\n     | 0 => 0\n     | S p => S (S (mult2 p))\n     end.\n\nFixpoint iterate {A : Type} (f : A -> A) (n : nat) (x : A) {struct n} : A\n  := match n with\n     | O => x\n     | S p => f (iterate f p x)\n     end.\n\n(* Tail call *)\nFixpoint iterate' {A : Type} (f : A -> A) (n : nat) (x : A) {struct n} : A\n  := match n with\n     | O => x\n     | S p => iterate' f p (f x)\n     end.\n\nTheorem iterate_step {A : Type} (f : A -> A) (n : nat) (x : A)\n  : iterate f (S n) x = f (iterate f n x).\nProof. reflexivity. Qed.\n\nTheorem iterate'_step {A : Type} (f : A -> A) (n : nat) (x : A)\n  : iterate' f (S n) x = iterate' f n (f x).\nProof. reflexivity. Qed.\n\nTheorem iterate_fstep {A : Type} (f : A -> A) (n : nat) (x : A)\n  : iterate f n (f x) = f (iterate f n x).\nProof.\n  generalize dependent x.\n  induction n as [| p IH]; try reflexivity.\n  simpl. intro x. now rewrite IH.\nQed.\n\nTheorem iterate'_fstep {A : Type} (f : A -> A) (n : nat) (x : A)\n  : iterate' f n (f x) = f (iterate' f n x).\nProof.\n  generalize dependent x.\n  induction n as [| p IH]; try reflexivity.\n  simpl. intro x. apply IH.\nQed.\n\nTheorem iterate_eq {A : Type} (f : A -> A) (n : nat) (x : A)\n  : iterate f n x = iterate' f n x.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. rewrite IH, iterate'_fstep. reflexivity.\nQed.\n\nTheorem iterate_fixpoint {X : Type} (f : X -> X) (x : X)\n  : f x = x -> forall n : nat, iterate f n x = x.\nProof.\n  intros H n. induction n as [| n' IH]; try reflexivity.\n  simpl. now rewrite IH, H.\nQed.\n\nTheorem iterate_fixpoint1 {X : Type} (f : X -> X) (x y : X)\n  : f x = y -> f y = y -> forall n : nat, iterate f (S n) x = y.\nProof.\n  intros H0 H n. rewrite iterate_eq. simpl. rewrite H0.\n  now rewrite <- iterate_eq, iterate_fixpoint.\nQed.\n\n(* Exercise 6.14\n   Reproduce the above discussion for the function mult:\n   compile a table describing convertibility\n   for simple patterns of the two arguments. *)\nExample mult_O_O : 0 * 0 = 0.\nProof. reflexivity. Qed.\n\nExample mult_O_m (m : nat) : 0 * m = 0.\nProof. reflexivity. Qed.\n\nExample mult_Sn_m (n m : nat) : (S n) * m = m + n * m.\nProof. reflexivity. Qed.\n\nTheorem mult_n_O (n : nat) : n * 0 = 0.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. assumption.\nQed.\n\nExample mult_n_Sm (n m : nat) : n * (S m) = n + n * m.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. rewrite IH. apply eq_S.\n  repeat rewrite plus_assoc.\n  pattern (m + p). rewrite plus_comm. reflexivity.\nQed.\n\nTheorem mult_comm (n m : nat) : n * m = m * n.\nProof.\n  induction n as [| p IH].\n  - rewrite mult_n_O. reflexivity.\n  - simpl. rewrite IH, mult_n_Sm. reflexivity.\nQed.\n\n(* Exercise 6.15\n   Define a function of type [nat -> bool] that only returns [true]\n   for numbers smaller than 3, in other terms [S (S (S 0))] *)\nDefinition smaller_than_three (n : nat) : bool\n  := match n with\n     | O | S O | S (S O) => true\n     | _ => false\n     end.\n\nExample zero_is_smaller_than_three : smaller_than_three 0 = true.\nProof. reflexivity. Qed.\n\nExample two_is_smaller_than_three : smaller_than_three 2 = true.\nProof. reflexivity. Qed.\n\nExample three_is_not_smaller_than_three : smaller_than_three 3 = false.\nProof. reflexivity. Qed.\n\nExample fourty_five_is_not_smaller_than_three\n  : smaller_than_three 45 = false.\nProof. reflexivity. Qed.\n\nFixpoint smaller_than (n m : nat) : bool\n  := match n, m with\n     | O, O => false\n     | O, S _ => true\n     | S _, O => false\n     | S n', S m' => smaller_than n' m'\n     end.\n\nTheorem smaller_than_is_ltb (n m : nat) : smaller_than n m = (n <? m).\nProof.\n  generalize dependent m.\n  induction n as [| n' IHn]; intro m.\n  - destruct m as [| m']; reflexivity.\n  - destruct m as [| m']; try reflexivity.\n    simpl. rewrite IHn.\n    destruct (n' <? m') eqn:H; symmetry.\n    + apply Nat.ltb_lt, lt_n_S, Nat.ltb_lt, H.\n    + apply Nat.ltb_nlt in H. apply Nat.ltb_nlt.\n      intro H'. apply H, lt_S_n, H'.\nQed.\n\nDefinition smaller_than_three' (n : nat) : bool := smaller_than n 3.\n\nTheorem smaller_than_three_eq (n : nat)\n  : smaller_than_three n = smaller_than_three' n.\nProof.\n  unfold smaller_than_three'.\n  destruct n as [| [| [| [| p]]]]; reflexivity.\nQed.\n\n(* Exercise 6.16\n   Define an addition function so that the principal argument is\n   second instead of first argument. *)\nFixpoint left_add (n m : nat) {struct m} : nat\n  := match m with\n     | O => n\n     | S p => S (left_add n p)\n     end.\n\nTheorem left_add_correct (n m : nat) : left_add n m = n + m.\nProof.\n  induction m as [| p IH].\n  - rewrite plus_n_O. reflexivity.\n  - rewrite plus_n_Sm. simpl.\n    rewrite IH. reflexivity.\nQed.\n\n(* Exercise 6.17\n   Define a function [sum_f] that takes as arguments a number [n]\n   and a function [f] of type [nat -> Z] and returns the sum of\n   all values of [f] for the natural numbers\n   that are strictly smaller than [n] *)\nFixpoint sum_f (n : nat) (f : nat -> Z) {struct n} : Z\n  := match n with\n     | O => 0\n     | S p => (f p) + sum_f p f\n     end.\n\nExample sum_id1 : sum_f 1 Z.of_nat = 0%Z.\nProof. reflexivity. Qed.\n\nExample sum_id3 : sum_f 3 Z.of_nat = 3%Z.\nProof. reflexivity. Qed.\n\nExample sum_id4 : sum_f 4 Z.of_nat = 6%Z.\nProof. reflexivity. Qed.\n\nRequire Import Program.Basics.\n\nExample sum_S4 : sum_f 4 (compose Z.of_nat S) = 10%Z.\nProof. reflexivity. Qed.\n\n(* Exercise 6.18\n   Define [two_power : nat -> nat] so that [two_power n] is [2^n]. *)\nDefinition two_power (n : nat) : nat := iterate (Nat.mul 2) n 1.\n\nExample two_power0 : two_power 0 = 1.\nProof. reflexivity. Qed.\n\nExample two_power1 : two_power 1 = 2.\nProof. reflexivity. Qed.\n\nExample two_power3 : two_power 3 = 8.\nProof. reflexivity. Qed.\n\nFixpoint two_power' (n : nat) : nat\n  := match n with\n     | O => 1\n     | S p => 2 * two_power' p\n     end.\n\nLemma two_power_Sn (n : nat) : two_power (S n) = 2 * two_power n.\nProof. reflexivity. Qed.\n\nTheorem two_power_eq (n : nat) : two_power n = two_power' n.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  rewrite two_power_Sn. simpl. now rewrite ?IH.\nQed.\n\n(* 6.3.4 Variations in the Form of Constructors *)\nOpen Scope Z_scope.\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(* Z_btree_ind : forall P : Z_btree -> Prop,\n   P Z_leaf\n   -> (forall (z : Z) (z0 : Z_btree), P z0\n      -> forall z1 : Z_btree, P z1 -> P (Z_bnode z z0 z1))\n         -> forall z : Z_btree, P z *)\n\nPrint positive.\n(* Inductive positive : Set\n   := xI : positive -> positive\n    | xO : positive -> positive\n    | xH : positive *)\n\nCheck positive_ind.\n(* positive_ind : forall P : positive -> Prop,\n   (forall p : positive, P p -> P (p~1))\n   -> (forall p : positive, P p -> P (p~0))\n   -> P 1 -> forall p : positive, P p *)\n\nPrint Z.\n(* Inductive Z : Set\n   :=  Z0 : Z\n    | Zpos : positive -> Z\n    | Zneg : positive -> Z *)\n\nFixpoint sum_all_values (t : Z_btree) : Z\n  := match t with\n     | Z_leaf => 0\n     | Z_bnode x t1 t2 => x + sum_all_values t1 + sum_all_values t2\n     end.\n\nExample sum_all_values_ex1 : sum_all_values Z_leaf = 0.\nProof. reflexivity. Qed.\n\nDefinition zbtree3 := Z_bnode 1 Z_leaf (Z_bnode 2 Z_leaf Z_leaf).\nExample sum_all_values_ex2 : sum_all_values zbtree3 = 3.\nProof. reflexivity. Qed.\n\n(* authors' solution *)\nFixpoint zero_present (t : Z_btree) : bool\n  := match t with\n     | Z_leaf => false\n     | Z_bnode 0 t1 t2 => true\n     | Z_bnode _ t1 t2 => zero_present t1 || zero_present t2\n     end.\n\nFixpoint zero_present' (t : Z_btree) : bool\n  := match t with\n     | Z_leaf => false\n     | Z_bnode x t1 t2 => (x =? 0) || zero_present' t1 || zero_present' t2\n     end.\n\nExample zero_present_ex1 : zero_present Z_leaf = false.\nProof. reflexivity. Qed.\n\nExample zero_present_ex2 : zero_present zbtree3 = false.\nProof. reflexivity. Qed.\n\nDefinition zbtree01 := Z_bnode 0 Z_leaf Z_leaf.\nDefinition zbtree02 := Z_bnode 1 zbtree3 (Z_bnode 2 zbtree01 zbtree3).\n\nExample zero_present_ex3 : zero_present zbtree01 = true.\nProof. reflexivity. Qed.\n\nExample zero_present_ex4 : zero_present zbtree02 = true.\nProof. reflexivity. Qed.\n\nTheorem zero_present_eq (t : Z_btree) : zero_present t = zero_present' t.\nProof.\n  induction t as [| x t1 IH1 t2 IH2]; try reflexivity.\n  simpl. rewrite IH1, IH2.\n  destruct x as [| x_pos | x_neg]; try reflexivity.\nQed.\n\nOpen Scope positive_scope.\n\nFixpoint add_one (x : positive) : positive\n  := match x with\n     | xH => (xO xH)\n     | xO p => xI p\n     | xI p => xO (add_one p)\n     end.\n\nExample add_one_ex1 : add_one 1 = 2.\nProof. reflexivity. Qed.\n\nExample add_one_ex2 : add_one 2 = 3.\nProof. reflexivity. Qed.\n\nExample add_one_ex3 : add_one 3 = 4.\nProof. reflexivity. Qed.\n\nExample add_one_ex31 : add_one 31 = 32.\nProof. reflexivity. Qed.\n\nExample add_one_ex32 : add_one 32 = 33.\nProof. reflexivity. Qed.\n\nExample add_one_ex33 : add_one 33 = 34.\nProof. reflexivity. Qed.\n\n(* Exercise 6.19\n   What is the representation in the type positive\n   for numbers 1000, 25, 512? *)\nExample pos25 : 25 = xI (xO (xO (xI xH))).\nProof. reflexivity. Qed.\n\nExample pos512 : 512 = xO (xO (xO (xO (xO (xO (xO (xO (xO xH)))))))).\nProof. reflexivity. Qed.\n\nExample pos1000 : 1000 = xO (xO (xO (xI (xO (xI (xI (xI (xI xH)))))))).\nProof. reflexivity. Qed.\n\nUnset Printing Notations.\nCheck 1000. (* xO (xO (xO (xI (xO (xI (xI (xI (xI xH)))))))) : positive *)\nSet Printing Notations.\n\n(* Exercise 6.20\n   Build the function [pos_even_bool] of type [positive -> bool]\n   that returns the value [true] exactly when the argument is even. *)\nDefinition pos_even_bool (x : positive) : bool\n  := match x with xO _ => true | _ => false end.\n\nExample pos_even_bool_ex1 : pos_even_bool 1 = false.\nProof. reflexivity. Qed.\n\nExample pos_even_bool_ex2 : pos_even_bool 2 = true.\nProof. reflexivity. Qed.\n\nExample pos_even_bool_ex3 : pos_even_bool 3 = false.\nProof. reflexivity. Qed.\n\nExample pos_even_bool_ex24 : pos_even_bool 24 = true.\nProof. reflexivity. Qed.\n\nExample pos_even_bool_ex31 : pos_even_bool 31 = false.\nProof. reflexivity. Qed.\n\nLemma xI_is_not_even (x : positive) : Nat.even (Pos.to_nat x~1) = false.\nProof.\n  rewrite Pos2Nat.inj_xI, <- Nat.add_1_l, Nat.even_add_mul_2. reflexivity.\nQed.\n\nTheorem pos_even_bool_correct (x : positive)\n  : pos_even_bool x = Nat.even (Pos.to_nat x).\nProof.\n  destruct x as [p | p |]; try reflexivity.\n  - rewrite Pos2Nat.inj_xI, <- Nat.add_1_l.\n    rewrite Nat.even_add_mul_2. reflexivity.\n  - rewrite Pos2Nat.inj_xO.\n    pattern (2 * Pos.to_nat p)%nat. rewrite <- Nat.add_0_l.\n    rewrite Nat.even_add_mul_2. reflexivity.\nQed.\n\n(* Exercise 6.21\n   Build the function [pos_div4] of type [positive -> Z]\n   that maps any number [z] to the integer part of [z/4]. *)\nDefinition N_div2 (z : N) : N\n  := match z with\n     | Npos (xI p) | Npos (xO p) => Npos p\n     | _ => N0\n     end.\n\nExample N_div2_ex0 : N_div2 N0 = N0.\nProof. reflexivity. Qed.\n\nExample N_div2_ex1 : N_div2 1 = N0.\nProof. reflexivity. Qed.\n\nExample N_div2_ex2 : N_div2 2 = 1%N.\nProof. reflexivity. Qed.\n\nExample N_div2_ex3 : N_div2 3 = 1%N.\nProof. reflexivity. Qed.\n\nExample N_div2_ex4 : N_div2 4 = 2%N.\nProof. reflexivity. Qed.\n\nExample N_div2_ex20 : N_div2 20 = 10%N.\nProof. reflexivity. Qed.\n\nExample N_div2_ex21 : N_div2 21 = 10%N.\nProof. reflexivity. Qed.\n\nTheorem N_div2_correct (z : N) : N_div2 z = (z / 2)%N.\nProof.\n  rewrite <- N.div2_div.\n  destruct z as [| z']; reflexivity.\nQed.\n\nDefinition pos_div4 (z : positive) : Z\n  := Z.of_N (N_div2 (N_div2 (Npos z))).\n\nExample pos_div4_ex1 : pos_div4 1 = Z0.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex2 : pos_div4 2 = Z0.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex3 : pos_div4 3 = Z0.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex4 : pos_div4 4 = 1%Z.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex5 : pos_div4 5 = 1%Z.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex20 : pos_div4 20 = 5%Z.\nProof. reflexivity. Qed.\n\nExample pos_div4_ex21 : pos_div4 23 = 5%Z.\nProof. reflexivity. Qed.\n\nDefinition pos_div4' (z : positive) : Z\n  := match z with\n     | xI (xI p) | xI (xO p) | xO (xI p) | xO (xO p) => Zpos p\n     | _ => Z0\n     end.\n\nTheorem pos_div4_eq (z : positive) : pos_div4 z = pos_div4' z.\nProof.\n  destruct z as [p | p |]; try reflexivity;\n    destruct p as [p' | p' |]; reflexivity.\nQed.\n\nTheorem pos_div4_correct (z : positive) : pos_div4 z = Zpos z / 4.\nProof.\n  unfold pos_div4. rewrite 2 N_div2_correct.\n  rewrite N.div_div; try discriminate. simpl.\n  rewrite N2Z.inj_div. reflexivity.\nQed.\n\n(* Exercise 6.22\n   Assuming there exists a function [Pos.mul] t that describes the\n   multiplication of two [positive] representations and returns\n   a [positive] representation, use this function to build\n   a function that multiplies numbers of type [Z]\n   and returns a value of type [Z]. *)\nDefinition Z_mul (x y : Z) : Z\n  := match x, y with\n     | Z0, _ | _, Z0 => Z0\n     | Zpos x', Zpos y' | Zneg x', Zneg y' => Zpos (Pos.mul x' y')\n     | Zneg x', Zpos y' | Zpos x', Zneg y' => Zneg (Pos.mul x' y')\n     end.\n\nTheorem Z_mul_correct (x y : Z) : Z_mul x y = (x * y)%Z.\nProof. reflexivity. Qed.\n\n(* Exercise 6.23\n   Build the inductive type that represents the language of\n   propositional logic without variables: *)\nInductive L : Set\n  := L_and : L -> L -> L\n   | L_or : L -> L -> L\n   | L_not : L -> L\n   | L_impl : L -> L -> L\n   | L_True | L_False.\n\nCheck (L_and L_True (L_impl (L_not L_True) L_False)).\n\nFixpoint L_ev (f : L) : bool\n  := match f with\n     | L_and x y => (L_ev x) && (L_ev y)\n     | L_or x y => (L_ev x) || (L_ev y)\n     | L_not x => negb (L_ev x)\n     | L_impl x y => implb (L_ev x) (L_ev y)\n     | L_True => true\n     | L_False => false\n     end.\n\nExample L_ev_ex : L_ev (L_and L_True (L_impl (L_not L_True) L_False)) = true.\nProof. reflexivity. Qed.\n\n(* Exercise 6.24 *\n   Every strictly positive rational number can be obtained in a\n   unique manner by a succession of applications of functions N and D on the\n   number one, where N and D are defined by the following equations:\n   N(x) = 1 + x\n   D(x) = 1 / (1 + 1/x)\n   We can associate any strictly positive rational number with an element of\n   an inductive type with one constructor for one, and two other constructors\n   representing the functions N and D. Define this inductive type\n   (see the related exercise 6.44). *)\nInductive F : Set\n  := one : F (* 1 *)\n   | n : F -> F (* 1 + f *)\n   | d : F -> F (* 1 / (1 + (1 / f)) *)\n.\n\n(* Exercise 6.25\n   Define a function [value_present] with the type\n   [value_present : Z -> Z_btree -> bool]\n   that determines whether an integer appears in a binary tree. *)\nFixpoint value_present (z : Z) (t : Z_btree) {struct t} : bool\n  := match t with\n     | Z_leaf => false\n     | Z_bnode x t1 t2 => (x =? z)%Z || value_present z t1 || value_present z t2\n     end.\n\n(* Exercise 6.26\n   Define a function [power: Z -> nat -> Z] to compute\n   the power of an integer and\n   a function [discrete_log : positive -> nat] that maps\n   any number [p] to the number [n] such that 2^n <= p < 2^(n+1). *)\nFixpoint power (z : Z) (n : nat) {struct n} : Z\n  := match n with\n     | O => 1\n     | S p => z * power z p\n     end.\n\nExample power_ex1 : power 3 3 = 27%Z.\nProof. reflexivity. Qed.\n\nTheorem two_power_is_power (n : nat) : Z.of_nat (two_power n) = power 2 n.\nProof.\n  rewrite two_power_eq.\n  induction n as [| p IH]; try reflexivity.\n  cbv delta [two_power' power] beta iota.\n  fold two_power' power.\n  rewrite Nat2Z.inj_mul. rewrite IH. reflexivity.\nQed.\n\nTheorem power_correct (z : Z) (n : nat) : power z n = Zpower_nat z n.\nProof.\n  induction n as [| p IH]; try reflexivity.\n  simpl. rewrite IH. reflexivity.\nQed.\n\nFixpoint discrete_log (z : positive) : nat\n  := match z with\n     | xH => O\n     | xO p | xI p => S (discrete_log p)\n     end.\n\nExample discrete_log_ex1 : discrete_log 1 = 0%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex2 : discrete_log 2 = 1%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex3 : discrete_log 3 = 1%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex4 : discrete_log 4 = 2%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex5 : discrete_log 5 = 2%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex7 : discrete_log 7 = 2%nat.\nProof. reflexivity. Qed.\n\nExample discrete_log_ex8 : discrete_log 8 = 3%nat.\nProof. reflexivity. Qed.\n\nLemma pos_le_shift (x y : positive) : x <= y -> x~0 <= y~1.\nProof.\n  intro H. unfold Pos.le, Pos.compare. simpl.\n  apply Pos.compare_cont_Lt_not_Gt. assumption.\nQed.\n\nLemma pos_lt_shift (y z : positive) : y < z -> y~1 < z~0.\nProof.\n  intro H. unfold Pos.lt, Pos.compare. simpl.\n  apply Pos.compare_cont_Gt_Lt. assumption.\nQed.\n\nLemma pos_le_lt_shift (x y z : positive) : x <= y < z -> x~0 <= y~0 < z~0.\nProof.\n  intros [Hle Hlt].\n  split; [unfold Pos.le | unfold Pos.lt]; unfold Pos.compare; simpl;\n    fold Pos.compare; assumption.\nQed.\n\nLemma pos_le_lt_shift' (x y z : positive) : x <= y < z -> x~0 <= y~1 < z~0.\nProof.\n  intros [Hle Hlt].\n  split; [apply pos_le_shift | apply pos_lt_shift]; assumption.\nQed.\n\nTheorem discrete_log_correct (z : positive) (n : nat)\n  : discrete_log z = n -> shift_nat n 1 <= z < shift_nat (n + 1) 1.\nProof.\n  generalize dependent n.\n  induction z as [p IH | p IH |]; simpl; intros n H.\n  - destruct n as [| n']; try discriminate H.\n    apply Nat.succ_inj in H. simpl.\n    apply pos_le_lt_shift', IH, H.\n  - destruct n as [| n']; try discriminate H.\n    apply Nat.succ_inj in H. simpl.\n    apply pos_le_lt_shift, IH, H.\n  - subst n. simpl. unfold Pos.le, Pos.lt, Pos.compare.\n    simpl. split; [discriminate | reflexivity].\nQed.\n\n(* 6.3.5 ** Types with Functional Fields *)\nInductive Z_fbtree : Set\n  := Z_fleaf : Z_fbtree\n   | Z_fnode : Z -> (bool -> Z_fbtree) -> Z_fbtree.\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\nCheck Z_fbtree_ind.\n(* Z_fbtree_ind : forall P : Z_fbtree -> Prop,\n   P Z_fleaf\n   -> (forall (z : Z) (z0 : bool -> Z_fbtree),\n        (forall b : bool, P (z0 b)) -> P (Z_fnode z z0))\n   -> forall z : Z_fbtree, P z *)\n\nFixpoint fsum_all_values (t : Z_fbtree) : Z\n  := match t with\n     | Z_fleaf => 0\n     | Z_fnode z f => z + fsum_all_values (f true) + fsum_all_values (f false)\n     end.\n\n(* Exercise 6.27\n   Define a function [fzero_present : Z_fbtree -> bool] that maps\n   any tree x to true if and only if x contains the value zero. *)\nFixpoint fzero_present (t : Z_fbtree) : bool\n  := match t with\n     | Z_fleaf => false\n     | Z_fnode z f => (z =? 0)%Z || fzero_present (f true) || fzero_present (f false)\n     end.\n\nFixpoint Z_btree_from_f (t : Z_fbtree) : Z_btree\n  := match t with\n     | Z_fleaf => Z_leaf\n     | Z_fnode z f => Z_bnode z (Z_btree_from_f (f true)) (Z_btree_from_f (f false))\n     end.\n\nDefinition fzero_present' (t : Z_fbtree) : bool := zero_present' (Z_btree_from_f t).\n\nTheorem fzero_present_eq (t : Z_fbtree) : fzero_present t = fzero_present' t.\nProof.\n  induction t as [| z f IH]; try reflexivity.\n  unfold fzero_present'. simpl. rewrite !IH. reflexivity.\nQed.\n\n(* 6.3.5.2 *** Infinitely Branching Trees *)\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 n_sum_all_values (n : nat) (t : Z_inf_branch_tree) : Z\n  := match t with\n     | Z_inf_leaf => Z0\n     | Z_inf_node z f\n       => z + sum_f n (fun x : nat => n_sum_all_values n (f x))\n     end.\n\n(* Exercise 6.28 **\n   Define a function that checks whether the zero value occurs\n   in an infinitely branching tree at a node reachable only\n   by indices smaller than a number n. *)\n\n(* authors' solution (fixed) *)\nFixpoint any_true (n : nat) (f : nat -> bool) {struct n} : bool\n  := match n with\n     | O => false\n     | S p => orb (f 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          | Z0 => true\n          | _ => any_true n (fun p => izero_present n (f p))\n          end\n     end.\n\n(* My solution *)\n(* do map and reduce (foldl) in one on natural range (from 0 to n, excluding n) *)\nFixpoint mr_range {A : Type} (n : nat) (f : nat -> A)\n         (r : A -> A -> A) (a0 : A) {struct n}\n  := match n with\n     | O => a0\n     | S n' => r (mr_range n' f r a0) (f n')\n     end.\n\nDefinition sum_f' (n : nat) (f : nat -> Z) := mr_range n f Z.add Z0.\nTheorem sum_f_eq (n : nat) (f : nat -> Z) : sum_f n f = sum_f' n f.\nProof.\n  unfold sum_f'. induction n as [| n' IH]; try reflexivity.\n  simpl. rewrite <- IH, Z.add_comm. reflexivity.\nQed.\n\nDefinition any_true' (n : nat) (f : nat -> bool) : bool := mr_range n f orb false.\nTheorem any_true_eq (n : nat) (f : nat -> bool) : any_true n f = any_true' n f.\nProof.\n  unfold any_true'. induction n as [| n' IH]; try reflexivity.\n  simpl. rewrite <- IH, orb_comm. reflexivity.\nQed.\n\nFixpoint inf_zero_present (n : nat) (t : Z_inf_branch_tree) {struct t} : bool\n  := match t with\n     | Z_inf_leaf => false\n     | Z_inf_node z f => (z =? 0)%Z\n                         || mr_range n (compose (inf_zero_present n) f) orb false\n     end.\n\nRequire Import FunctionalExtensionality.\n\nTheorem inf_zero_present_eq (n : nat) (t : Z_inf_branch_tree)\n  : izero_present n t = inf_zero_present n t.\nProof.\n  induction t as [| z f IH]; try reflexivity.\n  simpl. rewrite any_true_eq. unfold any_true', compose.\n  destruct z as [| z' | z'] eqn:H; try reflexivity;\n    simpl; f_equal; extensionality k; apply IH.\nQed.\n\n(* 6.3.6 Proofs on Recursive Functions *)\n\n(* Exercise 6.29\nRedo the proof of theorem [plus_n_0], using only the tactics\n[intro], [assumption], [elim], [simpl], [apply], and [reflexivity]. *)\nOpen Scope nat_scope.\nTheorem plus_n_O' (n : nat) : n + 0 = n.\nProof.\n  elim n; try reflexivity.\n  intros n' IH. simpl. apply eq_S, IH.\nQed.\n\nTheorem plus_n_O'' (n : nat) : n + 0 = n.\nProof.\n  elim n; try reflexivity. intros n' IH. simpl.\n  apply (eq_ind (n' + 0) (fun t => S (n' + 0) = S t)).\n  - apply eq_refl.\n  - assumption.\nQed.\n\n(* Exercise 6.30 **\n   This exercise uses the types [Z_btree] and [Z_fbtree]\n   introduced in Sects. 6.3.4 and 6.3.5.1.\n   Define functions :\n   [f1 : Z_btree : Z_fbtree]\n   [f2 : Z_fbtree : Z_btree]\n   that establish the most natural bijection between the two types.\n\n   Prove the following theorem:\n   [Theorem f2_f1 : forall t: Z_btree, f2 (f1 t) = t.]\n\n   What is missing to prove the following statement?\n   [Theorem f1_f2 : forall t: Z_fbtree, f1 (f2 t) = t.] *)\n\nFixpoint f1 (t : Z_btree) : Z_fbtree\n  := match t with\n     | Z_leaf => Z_fleaf\n     | Z_bnode z t1 t2 => Z_fnode z (fun b : bool => f1 (if b then t1 else t2))\n     end.\n\nFixpoint f2 (t : Z_fbtree) : Z_btree\n  := match t with\n     | Z_fleaf => Z_leaf\n     | Z_fnode z f => Z_bnode z (f2 (f true)) (f2 (f false))\n     end.\n\n(* proove that this functions are bijective *)\nTheorem f2_f1 (t : Z_btree) : f2 (f1 t) = t.\nProof.\n  induction t as [| z t1 IH1 t2 IH2]; try reflexivity.\n  simpl. rewrite IH1, IH2. reflexivity.\nQed.\n\n(* use extensionality *)\nTheorem f1_f2 (t : Z_fbtree) : f1 (f2 t) = t.\nProof.\n  induction t as [| z f IH]; try reflexivity.\n  simpl. f_equal. extensionality b.\n  destruct b; rewrite IH; reflexivity.\nQed.\n\n(* Exercise 6.31\n   Prove [forall n : nat, (mult2 n) = n + n] (see Sect. 6.3.3) *)\nTheorem mult2_to_sum (n : nat) : mult2 n = n + n.\nProof.\n  induction n as [| n' IH]; try reflexivity.\n  simpl. rewrite IH. rewrite plus_n_Sm. reflexivity.\nQed.\n\n(* Exercise 6.32\n   The sum of the first n natural numbers is defined with the following function: *)\nFixpoint sum_n (n : nat) : nat\n  := match n with\n     | O => O\n     | (S p) => n + sum_n p\n     end.\n(* Show that for each n, we have: [2 * (sum_n n) = n * (n+1)]. *)\nTheorem sum_n_eq (n : nat) : 2 * (sum_n n) = n * (n + 1).\nProof.\n  induction n as [| n' IH]; try reflexivity.\n  simpl (sum_n (S n')). rewrite mult_n_Sm, Nat.mul_add_distr_l, IH.\n  ring.\nQed.\n\n(* Exercise 6.33\n   Prove the following statement: [n <= sum_n n] *)\nTheorem sum_n_gt_n (n : nat) : n <= sum_n n.\nProof.\n  induction n as [| n' IH]; simpl.\n  - apply Nat.le_refl.\n  - apply Peano.le_n_S, Nat.le_add_r.\nQed.\n\n(* 6.3.7 Anonymous Recursive Functions (fix) *)\nDefinition mult2' : nat -> nat\n  := fix f (n : nat) : nat\n       := match n with\n          | 0 => 0\n          | S p => S (S (f p)) end.\n\nTheorem mult2_eq (n : nat) : mult2 n = mult2' n.\nProof. reflexivity. Qed.\n\n(* 6.4 Polymorphic Types *)\n(* 6.4.1 Polymorphic Lists *)\nRequire Import List.\nPrint list.\n(* Inductive list (A : Type) : Type\n   := nil : list A\n    | cons : A -> list A -> list A *)\n\nCheck list_ind.\n(* list_ind : forall (A : Type) (P : list A -> Prop),\n                P nil\n                -> (forall (a : A) (l : list A), P l -> P (a :: l))\n                -> forall l : list A, P l *)\n\nFixpoint app {A : Type} (l m : list A) : list A\n  := match l with\n     | nil => m\n     | cons a l1 => cons a (app l1 m)\n     end.\n\n(* Exercise 6.34\n   Build a polymorphic function that takes a list as argument\n   and returns a list containing the first two elements when they exist. *)\nDefinition first_two {X : Type} (xs : list X) : list X\n  := match xs with\n     | x1 :: x2 :: _ => x1 :: x2 :: nil\n     | x1 :: nil => x1 :: nil\n     | nil => nil\n     end.\n\nExample first_two_ex0 : first_two (X := nat) nil = nil.\nProof. reflexivity. Qed.\n\nExample first_two_ex1 : first_two (1 :: nil) = (1 :: nil).\nProof. reflexivity. Qed.\n\nExample first_two_ex2 : first_two (1 :: 2 :: nil) = (1 :: 2 :: nil).\nProof. reflexivity. Qed.\n\nExample first_two_ex3 : first_two (1 :: 2 :: 3 :: nil) = (1 :: 2 :: nil).\nProof. reflexivity. Qed.\n\n(* Exercise 6.35\n   Build a function that takes a natural number [n] and a list as\n   arguments and returns the list containing the first n elements\n   of the list when they exist. *)\nFixpoint first_n {X : Type} (xs : list X) (n : nat) : list X\n  := match n, xs with\n     | O, _ | _, nil => nil\n     | S n', x1 :: xs1  => x1 :: first_n xs1 n'\n     end.\n\nExample first_n_ex : first_n (1 :: 2 :: 3 :: 4 :: nil) 3 = (1 :: 2 :: 3 :: nil).\nProof. reflexivity. Qed.\n\nTheorem first_two_is_first_n {X : Type} (xs : list X) : first_two xs = first_n xs 2.\nProof.\n  destruct xs as [| x1 [| x2 [| x3 xs3]]]; reflexivity.\nQed.\n\n(* Exercise 6.36\n   Build a function that takes a list of integers as argument and\n   returns the sum of these numbers. *)\nOpen Scope Z_scope.\nFixpoint list_sum (xs : list Z) : Z\n  := match xs with\n     | nil => Z0\n     | x1 :: xs1 => x1 + list_sum xs1\n     end.\n\nTheorem list_sum_step (x : Z) (xs : list Z) : list_sum (x :: xs) = x + list_sum xs.\nProof. reflexivity. Qed.\n\nExample list_sum_ex : list_sum (1 :: 2 :: 3 :: nil) = 6.\nProof. reflexivity. Qed.\n\n(* Exercise 6.37\n   Build a function that takes a natural number n as argument\n   and builds a list containing n occurrences of the number one. *)\nFixpoint list_repeat_one (n : nat) : list Z\n  := match n with\n     | O => nil\n     | S n' => 1 :: list_repeat_one n'\n     end.\n\nFixpoint list_repeat {X : Type} (x : X) (n : nat) : list X\n  := match n with\n     | O => nil\n     | S n' => x :: list_repeat x n'\n     end.\n\nTheorem list_repeat_one_correct (n : nat) : list_repeat_one n = list_repeat 1 n.\nProof.\n  induction n as [| n' IH]; try reflexivity.\n  simpl. rewrite IH. reflexivity.\nQed.\n\nExample sum_of_repeat_one (n : nat) : list_sum (list_repeat_one n) = Z.of_nat n.\nProof.\n  induction n as [| n' IH]; try reflexivity.\n  simpl list_repeat_one. rewrite list_sum_step, Nat2Z.inj_succ.\n  unfold Z.succ. rewrite Z.add_comm, IH. reflexivity.\nQed.\n\n(* Exercise 6.38\n   Build a function that takes a number n and returns the list\n   containing the integers from 1 to n, in this order. *)\nOpen Scope nat_scope.\nFixpoint list_from_k (k n : nat) : list nat\n  := match n with\n     | O => nil\n     | S n' => k :: list_from_k (S k) n'\n     end.\n\nExample list_from_k_ex3 : list_from_k 2 2 = 2 :: 3 :: nil.\nProof. reflexivity. Qed.\n\nDefinition list_from_one_to_n (n : nat) : list nat := list_from_k 1 n.\n\nExample list_from_one_to_n_ex0 : list_from_one_to_n 0 = nil.\nProof. reflexivity. Qed.\n\nExample list_from_one_to_n_ex1 : list_from_one_to_n 1 = 1 :: nil.\nProof. reflexivity. Qed.\n\nExample list_from_one_to_n_ex2 : list_from_one_to_n 2 = 1 :: 2 :: nil.\nProof. reflexivity. Qed.\n\nExample list_from_one_to_n_ex3 : list_from_one_to_n 3 = 1 :: 2 :: 3 :: nil.\nProof. reflexivity. Qed.\n\n(* authors' solution *)\nFixpoint iota_iter (n : nat) (ns : list nat) {struct n} : list nat\n  := match n with\n     | 0 => ns\n     | S n' => iota_iter n' (n :: ns)\n     end.\n\nDefinition iota (n : nat) : list nat := iota_iter n nil.\n\nExample iota_ex0 : iota 0 = nil.\nProof. reflexivity. Qed.\n\nExample iota_ex1 : iota 1 = 1 :: nil.\nProof. reflexivity. Qed.\n\nExample iota_ex2 : iota 2 = 1 :: 2 :: nil.\nProof. reflexivity. Qed.\n\nExample iota_ex3 : iota 3 = 1 :: 2 :: 3 :: nil.\nProof. reflexivity. Qed.\n\nTheorem iota_iter_to_list_from_k1 (k n : nat) : iota_iter k (list_from_k (S k) n) = list_from_k 1 (k + n).\nProof.\n  generalize dependent n.\n  induction k as [| k' IH]; try reflexivity.\n  intro n. simpl iota_iter.\n  replace ((S k') :: list_from_k (S (S k')) n)\n    with (list_from_k (S k') (S n)) by reflexivity.\n  rewrite IH. rewrite Nat.add_succ_r, Nat.add_succ_l.\n  reflexivity.\nQed.\n\nRequire Import Lia.\n\nTheorem iota_is_list_from_one_to_n (n : nat) : list_from_one_to_n n = iota n.\nProof.\n  destruct n as [| n']; try reflexivity.\n  unfold iota. simpl.\n  replace (S n' :: nil) with (list_from_k (S n') 1) by reflexivity.\n  rewrite iota_iter_to_list_from_k1.\n  unfold list_from_one_to_n.\n  now rewrite Nat.add_1_r.\nQed.\n\nTheorem iota_iter_to_list_from_k2 (k n : nat)\n  : iota_iter k (list_from_k (S k) n) = iota_iter (k + n) nil.\nProof.\n  generalize dependent n.\n  induction k as [| k' IH]; intro n.\n  - simpl. fold (list_from_one_to_n n). fold (iota n).\n    now rewrite iota_is_list_from_one_to_n.\n  - simpl iota_iter.\n  replace ((S k') :: list_from_k (S (S k')) n)\n    with (list_from_k (S k') (S n)) by reflexivity.\n  rewrite IH. rewrite Nat.add_succ_r.\n  reflexivity.\nQed.\n\n(* 6.4.2 The option Type *)\nPrint option.\n(* Inductive option (A : Type) : Type\n   := Some : A -> option A\n    | None : option A *)\nDefinition pred_option (n : nat) : option nat\n  := match n with\n     | O => None\n     | S n' => Some n'\n     end.\n\nDefinition pred2_option (n : nat) : option nat\n  := match pred_option n with\n     | None => None\n     | Some p => pred_option p\n     end.\n\n(* my attempt to get convenient combinators for [option] type *)\nDefinition option_map {X Y : Type} (opt_x : option X) (f : X -> Y) : option Y\n  := match opt_x with\n     | Some x => Some (f x)\n     | None => None\n     end.\n\nNotation \"opt_x '|>' f\" := (option_map opt_x f)\n                             (at level 65, left associativity).\n\nExample option_map_ex : Some 1 |> S = Some 2.\nProof. reflexivity. Qed.\n\nDefinition option_flat_map {X Y : Type} (opt_x : option X) (f : X -> option Y) : option Y\n  := match opt_x with\n     | Some x => f x\n     | None => None\n     end.\n\nNotation \"opt_x '|>>' f\" := (option_flat_map opt_x f)\n                              (at level 65, left associativity).\n\nExample option_flat_map_ex0 : Some 0 |>> pred_option = None.\nProof. reflexivity. Qed.\n\nExample option_flat_map_ex1 : Some 1 |>> pred_option = Some 0.\nProof. reflexivity. Qed.\n\nDefinition option_get {X : Type} (opt_x : option X) (default : X)\n  := match opt_x with\n     | Some x => x\n     | None => default\n     end.\n\nNotation \"opt_x '|v' default\" := (option_get opt_x default)\n                              (at level 65, left associativity).\n\nExample option_get_ex0 : None |v 1 = 1.\nProof. reflexivity. Qed.\n\nExample option_get_ex1 : Some 2 |v 1 = 2.\nProof. reflexivity. Qed.\n\nExample option_helpers_ex : Some 1 |> S |>> pred_option |v 0 = 1.\nProof. reflexivity. Qed.\n(* end *)\n\n(* rewrite [pred2_option] using new helpers *)\nDefinition pred2_option' (n : nat) : option nat\n  := pred_option n |>> pred_option.\n\nTheorem pred2_option_eq (n : nat) : pred2_option n = pred2_option' n.\nProof. reflexivity. Qed.\n\nFixpoint nth_option {X : Type} (n : nat) (xs : list X) {struct xs} : option X\n  := match n, xs with\n     | _, nil => None\n     | O, x1 :: _ => Some x1\n     | S n', x1 :: xs1 => nth_option n' xs1\n     end.\n\n(* Theorem nth_option_zero {X : Type} (xs : list X) : nth_option 0 xs = None. *)\n(* Proof. *)\n(*   destruct xs; try reflexivity. simpl. *)\n\nDefinition tl_error {X : Type} (xs : list X)\n  := match xs with\n     | nil => None\n     | _ :: xs1 => Some xs1\n     end.\n\nDefinition nth_option_it {X : Type} (n : nat) (xs : list X) : option X\n  := iterate (fun opt_xs => opt_xs |>> tl_error) n (Some xs) |>> @hd_error X.\n\nTheorem nth_option_it_of_nil {X : Type} (n : nat) : nth_option_it n (@nil X) = None.\nProof.\n  unfold nth_option_it. destruct n as [| n']; try reflexivity.\n  rewrite iterate_fixpoint1 with (y := None); reflexivity.\nQed.\n\nTheorem nth_option_it_step {X : Type} (n : nat) (x : X) (xs : list X)\n  : nth_option_it (S n) (x :: xs)  = nth_option_it n xs.\nProof.\n  unfold nth_option_it.\n  generalize dependent xs.\n  generalize dependent x.\n  induction n as [| n' IH]; try reflexivity. intros x xs.\n  remember (fun opt_xs => opt_xs |>> tl_error) as f eqn:feq.\n  rewrite iterate_eq, iterate'_step, iterate_eq, <- iterate_eq.\n  rewrite iterate'_step, <- iterate_eq.\n  replace (f (Some (x :: xs))) with (Some xs) by (subst f; reflexivity).\n  destruct xs as [| x1 xs1].\n  - rewrite iterate_fixpoint1 with (y := None); try (subst f; reflexivity).\n    replace (f (Some nil)) with (@None (list X)) by (subst f; reflexivity).\n    rewrite iterate_fixpoint; subst f; reflexivity.\n  - rewrite IH. subst f; reflexivity.\nQed.\n\nTheorem nth_option_it_eq {X : Type} (n : nat) (xs : list X)\n  : nth_option n xs = nth_option_it n xs.\nProof.\n  generalize dependent xs.\n  induction n as [| n' IH]; destruct xs as [| x1 xs1]; try reflexivity.\n  - now rewrite nth_option_it_of_nil.\n  - rewrite nth_option_it_step. simpl. now rewrite IH.\nQed.\n\n(* Exercise 6.39\n   Define the other variant [nth_option']. The arguments are\n   given in the same order, but the principal argument is the number [n].\n   Prove that both functions always give the same result\n   when applied on the same input. *)\nFixpoint nth_option' {X : Type} (n : nat) (xs : list X) {struct n} : option X\n  := match n, xs with\n     | _, nil => None\n     | O, x1 :: _ => Some x1\n     | S n', x1 :: xs1 => nth_option' n' xs1\n     end.\n\nTheorem nth_option_eq {X : Type} (n : nat) (xs : list X)\n  : nth_option n xs = nth_option' n xs.\nProof.\n  generalize dependent xs.\n  induction n as [| n' IH]; destruct xs as [| x1 xs1]; try reflexivity.\n  simpl. apply IH.\nQed.\n\n(* Exercise 6.40 * Prove: *)\nLemma nth_length (X : Set) (n : nat) (xs : list X)\n  : nth_option n xs = None <-> length xs <= n.\nProof.\n  generalize dependent xs.\n  induction n as [| n' IH]; destruct xs as [| x1 xs1]; simpl;\n    split; intro H; try reflexivity.\n    + discriminate H.\n    + inversion H.\n    + apply Nat.le_0_l.\n    + apply Peano.le_n_S. apply IH, H.\n    + apply Peano.le_S_n in H. apply IH, H.\nQed.\n\n\n(* Exercise 6.41 *\n   Define a function that takes as arguments a type A,\n   a function of type [A->bool], and a list\n   and returns the first element in the list, for which the function is true\n   (use the option type). *)\nFixpoint find {X : Type} (P : X -> bool) (xs : list X) : option X\n  := match xs with\n     | nil => None\n     | x1 :: xs1 => if P x1 then Some x1\n                  else find P xs1\n     end.\n\nTheorem find_correct {X : Type} (P : X -> bool) (xs : list X) : find P xs = List.find P xs.\nProof.\n  induction xs as [| x1 xs1 IH]; try reflexivity.\n  simpl. now rewrite IH.\nQed.\n\n(* 6.4.3 The Type of Pairs *)\n\n(* Exercise 6.42\n   Define two functions with the following type\n   [split : forall A B : Type, list (A * B) -> list A * list B]\n   [combine : forall A B : Type, list A -> list B -> list (A * B)]\n   and the usual behavior (transform a list of pairs into a pair of lists\n   containing the same data, and vice-versa, whenever possible)\n   Prove a simple theorem relating split and combine. *)\nFixpoint combine {X Y : Type} (xs : list X) (ys : list Y) : list (X * Y)\n  := match xs, ys with\n     | nil, _ | _, nil => nil\n     | x1 :: xs1, y1 :: ys1 => (x1, y1) :: combine xs1 ys1\n     end.\n\nFixpoint split {X Y : Type} (xys : list (X * Y)) : list X * list Y\n  := match xys with\n     | nil => (nil, nil)\n     | (x1, y1) :: xys1 => let s := split xys1\n                         in (x1 :: fst s, y1 :: snd s)\n     end.\n\nImport ListNotations.\n\nExample combine_ex : combine [1; 2; 3] [4; 5; 6; 7] = [(1, 4); (2, 5); (3, 6)].\nProof. reflexivity. Qed.\n\nExample split_ex : split [(1, 4); (2, 5); (3, 6)] = ([1; 2; 3], [4; 5; 6]).\nProof. reflexivity. Qed.\n\nTheorem split_combine_is_id {X Y : Type} (xs : list X) (ys : list Y)\n  : length xs = length ys -> split (combine xs ys) = (xs, ys).\nProof.\n  generalize dependent ys.\n  induction xs as [| x1 xs1 IH]; intros ys H.\n  - simpl in H. symmetry in H. apply length_zero_iff_nil in H.\n    subst ys. reflexivity.\n  - destruct ys as [| y1 ys1].\n    + simpl length in H at 2. apply length_zero_iff_nil in H.\n      discriminate H.\n    + simpl. simpl in H. apply Nat.succ_inj in H.\n      apply IH in H. rewrite !H. reflexivity.\nQed.\n\nTheorem combine_split_is_id {X Y : Type} (xys : list (X * Y))\n  : (uncurry combine) (split xys) = xys.\nProof.\n  induction xys as [| xy1 xys1 IH]; try reflexivity.\n  simpl. destruct xy1 as (x1, y1). simpl.\n  unfold uncurry in IH.\n  destruct (split xys1) as (xs1, ys1). simpl.\n  rewrite IH. reflexivity.\nQed.\n\n(* Authors' theorem *)\nTheorem combine_of_split {A B : Type} (l : list (A * B))\n  : let (l1, l2) :=  split l\n    in combine l1 l2 = l.\nProof.\n  induction l; simpl; auto.\n  destruct a, (split l). simpl. congruence.\nQed.\n\n(* Exercise 6.43\n   Build the type [btree] of polymorphic binary trees.\n   Define translation functions from [Z_btree] to [btree Z] and vice versa.\n   Prove that they are inverse to each other. *)\nInductive btree (X : Type) : Type\n  := bleaf : btree X\n   | bnode : X -> btree X -> btree X -> btree X.\n\nArguments bleaf {X}.\nArguments bnode {X}.\n\nFixpoint btree_from_Z (t : Z_btree) : btree Z\n  := match t with\n     | Z_leaf => bleaf\n     | Z_bnode z t1 t2 => bnode z (btree_from_Z t1) (btree_from_Z t2)\n     end.\n\nFixpoint btree_to_Z (t : btree Z) : Z_btree\n  := match t with\n     | bleaf => Z_leaf\n     | bnode z t1 t2 => Z_bnode z (btree_to_Z t1) (btree_to_Z t2)\n     end.\n\nTheorem Z_btree_conv1 (t : Z_btree) : btree_to_Z (btree_from_Z t) = t.\nProof.\n  induction t as [| z t1 IH1 t2 IH2]; [reflexivity|].\n  simpl. rewrite IH1, IH2. reflexivity.\nQed.\n\nTheorem Z_btree_conv2 (t : btree Z) : btree_from_Z (btree_to_Z t) = t.\nProof.\n  induction t as [| z t1 IH1 t2 IH2]; [reflexivity|].\n  simpl. rewrite IH1, IH2. reflexivity.\nQed.\n\n(* Exercise 6.44\n   This exercise continues Exercise 6.24 page 169.\n   Build the function that takes an element of the type defined\n   to represent rational numbers and returns the numerator and denominator\n   of the corresponding reduced fraction. *)\nPrint F.\n(* Inductive F : Set :=  one : F | n : F -> F | d : F -> F *)\n\n(* N(x) = 1 + x\n   D(x) = 1 / (1 + 1/x) *)\n\nDefinition rat_simp (m k : nat) : nat * nat := let d := Nat.gcd m k in (m / d, k / d).\nFixpoint F_to_rat (f : F) : nat * nat (* return [m / k], [k > 0] *)\n  := match f with\n   | one => (1, 1)\n   | n x => let (m, k) := F_to_rat x in (m + k, k)\n   | d x =>  let (m, k) := F_to_rat x\n            in (uncurry rat_simp) (k, k + m)\n   end.\n\nTheorem rat_simp_is_irreducible (m k : nat)\n  : let (m', k') := rat_simp m k in Nat.gcd m' k' <= 1.\nProof.\n  destruct (rat_simp m k) as (m', k') eqn:eq.\n  unfold rat_simp in eq. apply pair_equal_spec in eq.\n  destruct eq as (eqm, eqk). subst m' k'.\n  destruct (Nat.gcd m k =? 0) eqn:H.\n  - apply Nat.eqb_eq in H. rewrite !H. simpl. apply Nat.le_0_1.\n  - apply Nat.eqb_neq in H. remember (Nat.gcd m k) as g eqn:eq.\n    now rewrite Nat.gcd_div_gcd.\nQed.\n\nTheorem F_to_rat_is_irreducible (f : F)\n  : let (m, k) := F_to_rat f in Nat.gcd m k <= 1.\nProof.\n  induction f as [| x IH | x IH].\n  - simpl. reflexivity.\n  - simpl. destruct (F_to_rat x) as (m, k).\n    rewrite Nat.gcd_comm, Nat.gcd_add_diag_r, Nat.gcd_comm.\n    assumption.\n  - simpl. destruct (F_to_rat x) as (m, k).\n    apply rat_simp_is_irreducible.\nQed.\n\n(* Exercise 6.45 ***\n   The aim of this exercise is to implement a sieve function\n   that computes all the prime numbers that are less than a given number.\n   The first step is to define a type of comparison values: *)\nInductive cmp : Set := Less | Equal | Greater.\n\n(* Then define the following functions:\n   1. [three_way_compare : nat -> nat -> cmp]\n   for comparing two natural numbers.\n\n   2. [update_primes : nat -> (list nat * nat) -> (list nat * nat) * bool]\n   such that if [k] is a natural number and [l] is a list of pairs [(p,m)]\n   such that [m] is the smallest multiple of [p] greater than or equal to [k],\n   then [update_primes k l] returns the list of pairs [(p,m')]\n   where [m'] is the smallest multiple of [p] strictly greater than [k]\n   and a boolean value that is true if one of the [m] was equal to [k].\n\n   3. [prime_sieve : nat -> (list nat * nat)]\n   to map a number [k] to the list of pairs [(p,m)]\n   where [p] is a prime number smaller or equal to [k]\n   and [m] is the smallest multiple of [p] greater than or equal to [k + 1].\n\n   Prove that [prime_sieve] can be used to compute all the prime numbers\n   smaller than a given [k]. *)\n\nFixpoint three_way_compare (n m : nat) : cmp\n  := match n, m with\n     | O, O => Equal\n     | O, S _ => Less\n     | S _, O => Greater\n     | S n', S m' => three_way_compare n' m'\n     end.\n\nTheorem both_true_iff (A B : Prop) : A -> B -> A <-> B.\nProof. intros a b. split; intro H; assumption. Qed.\n\nTheorem both_false_iff (A B : Prop) : ~A -> ~B -> A <-> B.\nProof. intros na nb. split; intro H; contradiction. Qed.\n\nTheorem Equal_is_eq (n m : nat) : three_way_compare n m = Equal <-> n = m.\nProof.\n  generalize dependent m.\n  induction n as [| n' IH]; intro m; destruct m as [| m']; simpl.\n  - apply both_true_iff; reflexivity.\n  - apply both_false_iff; [discriminate | apply Nat.neq_0_succ].\n  - apply both_false_iff; [discriminate | apply Nat.neq_succ_0].\n  - rewrite IH. rewrite Nat.succ_inj_wd. reflexivity.\nQed.\n\nTheorem Less_is_lt (n m : nat) : three_way_compare n m = Less <-> n < m.\nProof.\n  generalize dependent m.\n  induction n as [| n' IH]; intro m; destruct m as [| m']; simpl.\n  - apply both_false_iff; [discriminate | apply Nat.nle_succ_0].\n  - apply both_true_iff; [reflexivity | apply Peano.le_n_S, Peano.le_0_n].\n  - apply both_false_iff; [discriminate | apply Nat.nle_succ_0].\n  - rewrite IH. apply Nat.succ_lt_mono.\nQed.\n\nTheorem Greater_is_gt (n m : nat) : three_way_compare n m = Greater <-> n > m.\nProof.\n  generalize dependent m.\n  induction n as [| n' IH]; intro m; destruct m as [| m']; simpl.\n  - apply both_false_iff; [discriminate | apply gt_irrefl].\n  - apply both_false_iff; [discriminate | apply Nat.nlt_0_r].\n  - apply both_true_iff; [reflexivity | apply Peano.le_n_S, Peano.le_0_n].\n  - rewrite IH. apply Nat.succ_lt_mono.\nQed.\n\nDefinition update_prime (k p m : nat) : nat * bool\n  := match three_way_compare m k with\n     | Equal => (m + p, true)\n     | Less => (m + p, false) (* assume that m >= k so it is not possible *)\n     | Greater => (m, false)\n     end.\n\nLemma update_prime_m_mult (p m k m' : nat) (is_comp : bool)\n  : p <> 0 -> (m mod p =? 0) = true -> update_prime k p m = (m', is_comp)\n    -> (m' mod p =? 0) = true.\nProof.\n  intros pnz eq0. unfold update_prime.\n  destruct (three_way_compare m k);\n    intro H; injection H; clear H; intros eq1 eq2.\n  - rewrite <- eq2. simpl. rewrite <- (Nat.mul_1_l p) at 1.\n    rewrite Nat.mod_add; assumption.\n  - rewrite <- eq2. simpl. rewrite <- (Nat.mul_1_l p) at 1.\n    rewrite Nat.mod_add; assumption.\n  - rewrite <- eq2. assumption.\nQed.\n\nLemma update_prime_gt_k (p m k m' : nat) (is_comp : bool)\n  : p <> 0 -> k <= m -> update_prime k p m = (m', is_comp) -> k < m'.\nProof.\n  intros pnz ge eq. unfold update_prime in eq.\n  destruct (three_way_compare m k) eqn:cmp;\n    injection eq; clear eq; intros eq1 eq2.\n  - apply Less_is_lt in cmp. apply le_not_lt in ge.\n    contradiction cmp.\n  - apply Equal_is_eq in cmp. subst k m'.\n    apply Nat.lt_add_pos_r, Nat.neq_0_lt_0, pnz.\n  - apply Greater_is_gt in cmp. unfold gt in cmp.\n    subst m'. assumption.\nQed.\n\nLemma update_prime_min (p m k m' : nat) (is_comp : bool)\n  : m - p < k -> update_prime k p m = (m', is_comp)\n    -> m' - p <= k.\nProof.\n  intros lt eq. unfold update_prime in eq.\n  destruct (three_way_compare m k) eqn:cmp;\n    injection eq; clear eq; intros eq1 eq2; subst m'.\n  - apply Less_is_lt in cmp.\n    rewrite Nat.add_sub. apply Nat.lt_le_incl, cmp.\n  - apply Equal_is_eq in cmp. subst k.\n    rewrite Nat.add_sub. apply Nat.le_refl.\n  - apply Greater_is_gt in cmp. unfold gt in cmp.\n    apply Nat.lt_le_incl, lt.\nQed.\n\nLemma update_prime_is_comp (p m k m' : nat) (is_comp : bool)\n  : update_prime k p m = (m', is_comp) -> is_comp = (m =? k).\nProof.\n  intro eq. unfold update_prime in eq.\n  destruct (three_way_compare m k) eqn:cmp;\n    injection eq; clear eq; intros eq1 eq2; subst m'.\n  - apply Less_is_lt in cmp. subst is_comp. symmetry.\n    apply Nat.eqb_neq, Nat.lt_neq, cmp.\n  - apply Equal_is_eq in cmp. subst k is_comp.\n    apply beq_nat_refl.\n  - apply Greater_is_gt in cmp. unfold gt in cmp.\n    subst is_comp. symmetry. rewrite Nat.eqb_sym.\n    apply Nat.eqb_neq, Nat.lt_neq, cmp.\nQed.\n\nFixpoint update_primes (k : nat) (ps : list (nat * nat)) {struct ps}\n  : (list (nat * nat)) * bool\n  := match ps with\n     | [] => ([], false)\n     | (p, m) :: ps0 => let (ps1, is_comp1) := update_primes k ps0 in\n                      let (m2, is_comp2) := update_prime k p m in\n                      ((p, m2) :: ps1, is_comp1 || is_comp2)\n     end.\n\nExample update_primes_ex0 : update_primes 2 [] = ([], false).\nProof. reflexivity. Qed.\n\nExample update_primes_ex1 : update_primes 2 [(2, 2)] = ([(2, 4)], true).\nProof. reflexivity. Qed.\n\nExample update_primes_ex2 : update_primes 5 [(2, 6)] = ([(2, 6)], false).\nProof. reflexivity. Qed.\n\nExample update_primes_ex3 : update_primes 6 [(3, 6)] = ([(3, 9)], true).\nProof. reflexivity. Qed.\n\nDefinition prime (n : nat)\n  := (n <> 0 /\\ n <> 1) /\\ ~(exists k : nat, 1 < k < n /\\ n mod k = 0).\n\n(* return true if [p k = true] for all [k] such that [n0 < k < n] *)\nFixpoint forallb_in_interval (n0 n : nat) (p : nat -> bool) : bool\n  := match n with\n     | O => true\n     | S n' => if n <=? S n0 then true\n              else p n' && forallb_in_interval n0 n' p\n     end.\n\nExample forallb_in_interval_ex1\n  : forallb_in_interval 3 5 (fun k => k =? 4) = true.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex2\n  : forallb_in_interval 3 4 (fun k => false) = true.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex3\n  : forallb_in_interval 3 3 (fun k => false) = true.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex4\n  : forallb_in_interval 3 2 (fun k => false) = true.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex5\n  : forallb_in_interval 2 10 (fun k => (2 <? k) && (k <? 10)) = true.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex6\n  : forallb_in_interval 1 10 (fun k => (2 <? k) && (k <? 10)) = false.\nProof. reflexivity. Qed.\n\nExample forallb_in_interval_ex7\n  : forallb_in_interval 3 11 (fun k => (2 <? k) && (k <? 10)) = false.\nProof. reflexivity. Qed.\n\n(* return true if [p k = true] for all [k] such that [n0 < k < n] *)\nFixpoint existsb_in_interval (n0 n : nat) (p : nat -> bool) : bool\n  := match n with\n     | O => false\n     | S n' => if n <=? S n0 then false\n              else p n' || existsb_in_interval n0 n' p\n     end.\n\nTheorem existsb_in_interval_correct\n        (n0 n : nat) (f : nat -> bool) (P : nat -> Prop)\n  : (forall k : nat, P k <-> f k = true)\n    -> (exists k : nat, n0 < k < n /\\ P k) <-> (existsb_in_interval n0 n f = true).\nProof.\n  intro P_is_f. split; intro H.\n  - destruct H as [k [[neq_n0_k neq_k] pk]].\n    induction n as [| n' IH].\n    + contradict neq_k. apply Nat.nlt_0_r.\n    + simpl. apply lt_n_Sm_le in neq_k.\n      replace (n' <=? n0) with false.\n      2:{ symmetry. apply Nat.leb_gt.\n          apply (Nat.lt_le_trans n0 k n'); assumption. }\n      pose (le_lt_or_eq k n' neq_k) as neq_k2.\n      destruct neq_k2 as [neq_k2 | eq_k].\n      * now rewrite (IH neq_k2), orb_true_r.\n      * apply P_is_f in pk. subst k. now rewrite pk.\n  - induction n as [| n' IH]; simpl in H.\n    + discriminate H.\n    + destruct (lt_eq_lt_dec n0 n') as [[n0_lt_n | n0_eq_n] | n0_gt_n].\n      * replace (n' <=? n0) with false in H.\n        2:{ symmetry. apply Nat.leb_gt. assumption. }\n        { apply orb_prop in H as [H | H].\n          - apply P_is_f in H. exists n'. split; auto with arith.\n          - apply IH in H. destruct H as [k [[neq_k1 neq_k2] pk]].\n            exists k. split; [| exact pk].\n            split; [exact neq_k1| apply Nat.lt_lt_succ_r, neq_k2].\n        }\n      * subst n'. rewrite Nat.leb_refl in H. discriminate H.\n      * replace (n' <=? n0) with true in H.\n        2:{ apply Nat.lt_le_incl, Nat.leb_le in n0_gt_n.\n            now rewrite n0_gt_n. }\n        discriminate H.\nQed.\n\nDefinition is_prime (n : nat) : bool\n  := negb ((n =? 0) || (n =? 1)\n           || existsb_in_interval 1 n (fun k => n mod k =? 0)).\n\nCompute (seq 1 13).\n(* = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13] : list nat *)\n\nCompute (map is_prime (seq 1 13)).\n(* = [1: false; 2: true; 3: true; 4: false; 5: true; 6: false;\n      7: true; 8: false; 9: false; 10: false; 11: true;\n      12: false; 13: true] : list bool *)\n\nExample is_prime_ex\n  : map is_prime (seq 1 13)\n    = [false; true; true; false; true; false; true; false; false;\n      false; true; false; true].\nProof. reflexivity. Qed.\n\nTheorem prime_is_prime (n : nat) : prime n <-> is_prime n = true.\nProof.\n  unfold prime, is_prime.\n  rewrite !negb_orb, !andb_true_iff.\n  rewrite !negb_true_iff, !Nat.eqb_neq.\n  apply and_iff_compat_l. rewrite <- not_true_iff_false.\n  apply not_iff_compat. apply existsb_in_interval_correct.\n  intro k. rewrite Nat.eqb_eq. reflexivity.\nQed.\n\n(* Check that [ps] is a list of pairs [(p,m)]\n   such that [m] is the smallest multiple of [p]\n   greater than or equal to [k] *)\nFixpoint is_ps_list (k : nat) (ps : list (nat * nat)) : bool\n  := match ps with\n     | [] => true\n     | (p, m) :: ps' => negb (p =? 0)\n                      && (m mod p =? 0)\n                      && (k <=? m) && (m - p <? k)\n                      && is_ps_list k ps'\n     end.\n\nTheorem is_ps_list_step (k p m : nat) (ps : list (nat * nat))\n  : is_ps_list k ((p, m) :: ps)\n    = negb (p =? 0)\n      && (m mod p =? 0)\n      && (k <=? m) && (m - p <? k)\n      && is_ps_list k ps.\nProof. reflexivity. Qed.\n\nExample is_ps_list_ex1 : is_ps_list 2 [(2, 2)] = true.\nProof. reflexivity. Qed.\n\nExample is_ps_list_ex2 : is_ps_list 5 [(2, 6)] = true.\nProof. reflexivity. Qed.\n\nExample is_ps_list_ex3 : is_ps_list 5 [(2, 5)] = false.\nProof. reflexivity. Qed.\n\nExample is_ps_list_ex4 : is_ps_list 5 [(2, 4)] = false.\nProof. reflexivity. Qed.\n\n(* Returns true if exists pair [(p, m) In ps] such that [m = k].\n   It means that one of [p] numbers is divisor of [k] *)\nFixpoint is_composite (k : nat) (ps : list (nat * nat)) : bool\n  := match ps with\n     | [] => false\n     | (p, m) :: ps' => (m =? k) || is_composite k ps'\n     end.\n\nLemma eq_orb_intro_r (a1 a2 b : bool) : a1 = a2 -> a1 || b = a2 || b.\nProof. intro H. now subst a2. Qed.\n\n(* [update_primes k ps] returns the list of pairs [(p,m')]\n   where [m'] is the smallest multiple of [p] strictly greater than [k]\n   and a boolean value that is true if one of the [m] was equal to [k]. *)\nTheorem update_primes_correct (k : nat) (ps : list (nat * nat))\n  : is_ps_list k ps = true\n    -> let (ps1, is_comp1) := update_primes k ps in\n      (is_ps_list (S k) ps1 = true)\n      /\\ (is_comp1 = is_composite k ps).\nProof.\n  generalize dependent k.\n  induction ps as [| (p, m) ps' IH]; intros k eq0; simpl; try easy.\n  (* get rid of let *)\n  destruct (update_primes k ps') as (ps1, is_comp1) eqn:eq1.\n  destruct (update_prime k p m) as (m2, is_comp2) eqn:eq2.\n  (* destruct [eq0] *)\n  simpl in eq0.\n  apply andb_prop in eq0. destruct eq0 as [H0 eq0].\n  apply andb_prop in H0. destruct H0 as [H0 m_min].\n  apply Nat.ltb_lt in m_min.\n  apply andb_prop in H0. destruct H0 as [H0 m_ge].\n  apply Nat.leb_le in m_ge.\n  apply andb_prop in H0. destruct H0 as [pnz m_mult].\n  apply negb_true_iff in pnz as pnz'. apply beq_nat_false in pnz'.\n  (* use IH *) pose (IH k eq0) as H.\n  rewrite eq1 in H. destruct H as [eq3 eq4].\n  split.\n  - simpl. rewrite eq3. rewrite andb_true_r.\n    repeat (apply andb_true_intro; split); try assumption.\n    + apply (update_prime_m_mult p m k m2 is_comp2); assumption.\n    + pose (update_prime_gt_k p m k m2 _ pnz' m_ge eq2) as m_gt.\n      destruct m2 as [| m2'].\n      * exfalso. apply (Nat.nlt_0_r k), m_gt.\n      * unfold lt in m_gt. apply le_S_n in m_gt.\n        apply Nat.leb_le, m_gt.\n    + apply Nat.ltb_lt. unfold lt. apply le_n_S.\n      apply (update_prime_min p m k m2 _ m_min eq2).\n  - subst is_comp1. rewrite orb_comm. apply eq_orb_intro_r.\n    exact (update_prime_is_comp p m k m2 is_comp2 eq2).\nQed.\n\n(* to map a number [k] to the list of pairs [(p,m)]\n   where [p] is a prime number smaller or equal to [k]\n   and [m] is the smallest multiple of [p] greater than or equal to [k + 1]. *)\nFixpoint prime_sieve (k : nat) : list (nat * nat)\n  := match k with\n     | 0 | 1 => []\n     | S k' => let (ps, is_comp) := update_primes k (prime_sieve k') in\n              if is_comp then ps else (k, 2*k) :: ps\n     end.\n\nExample prime_sieve_ex2 : prime_sieve 2 = [(2, 4)].\nProof. reflexivity. Qed.\n\nExample prime_sieve_ex3 : prime_sieve 3 = [(3, 6); (2, 4)].\nProof. reflexivity. Qed.\n\nExample prime_sieve_ex4 : prime_sieve 4 = [(3, 6); (2, 6)].\nProof. reflexivity. Qed.\n\nExample prime_sieve_1_is_ps_list\n  : is_ps_list 2 (prime_sieve 1) = true.\nProof. reflexivity. Qed.\n\nExample prime_sieve_2_is_ps_list\n  : is_ps_list 3 (prime_sieve 2) = true.\nProof. reflexivity. Qed.\n\nExample prime_sieve_3_is_ps_list\n  : is_ps_list 4 (prime_sieve 3) = true.\nProof. reflexivity. Qed.\n\nExample prime_sieve_4_is_ps_list\n  : is_ps_list 5 (prime_sieve 4) = true.\nProof. reflexivity. Qed.\n\nExample prime_sieve_10_is_ps_list\n  : is_ps_list 11 (prime_sieve 10) = true.\nProof. reflexivity. Qed.\n\nTheorem prime_sieve_is_ps_list (k : nat)\n  : is_ps_list (S k) (prime_sieve k) = true.\nProof.\n  induction k as [| k1 IH]; [reflexivity |].\n  apply update_primes_correct in IH as H.\n  simpl prime_sieve.\n  destruct (update_primes (S k1) (prime_sieve k1)) as (ps1, is_comp1) eqn:eq.\n  destruct H as [H1 H2].\n  destruct k1 as [| k2]; [reflexivity |].\n  destruct is_comp1 eqn:Hcomp; [exact H1| ].\n  rewrite is_ps_list_step.\n  repeat (apply andb_true_intro; split); try auto with arith.\n  - replace (S (S k2 + S (S k2 + 0))) with (2 * (S (S k2))) by lia.\n    rewrite Nat.mod_mul; auto with arith.\n  - apply Nat.leb_le. lia.\n  - apply Nat.ltb_lt. lia.\nQed.\n\nDefinition get_primes (k : nat) : list nat := map fst (prime_sieve k).\n\nTheorem prime_sieve_Sk_eq (k : nat)\n  : snd (update_primes (S k) (prime_sieve k)) = true\n    -> prime_sieve (S k) = fst (update_primes (S k) (prime_sieve k)).\nProof.\n  simpl (prime_sieve (S k)).\n  remember (prime_sieve k) as ps eqn:eq_ps.\n  remember (update_primes (S k) ps) as U eqn:eq_U.\n  intro H. destruct U as (ps__u, is_comp). simpl in H.\n  rewrite H. simpl. destruct k as [| k'].\n  - simpl in eq_ps. rewrite eq_ps in eq_U.\n    simpl in eq_U. injection eq_U. auto.\n  - reflexivity.\nQed.\n\nTheorem prime_sieve_Sk_cons (k : nat)\n  : 0 < k\n    -> snd (update_primes (S k) (prime_sieve k)) = false\n    -> prime_sieve (S k)\n      = (S k, 2*(S k)) :: fst (update_primes (S k) (prime_sieve k)).\nProof.\n  simpl (prime_sieve (S k)).\n  remember (prime_sieve k) as ps eqn:eq_ps.\n  remember (update_primes (S k) ps) as U eqn:eq_U.\n  intros k_gt H. destruct U as (ps__u, is_comp). simpl in H.\n  rewrite H. simpl. destruct k as [| k'].\n  - contradict k_gt. apply Nat.nlt_0_r.\n  - reflexivity.\nQed.\n\nTheorem update_primes_dont_changes_primes (k : nat) (ps : list (nat * nat))\n  : map fst (fst (update_primes k ps)) = map fst ps.\nProof.\n  induction ps as [| (p, m) ps1 IH]; [reflexivity|]. simpl.\n  destruct (update_primes k ps1) as (ps__u, is_comp1) eqn:eq1.\n  simpl in IH.\n  destruct (update_prime k p m) as (m', is_comp') eqn:eq'.\n  simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem get_primes_Sk_eq (k : nat)\n  : snd (update_primes (S k) (prime_sieve k)) = true\n    -> get_primes (S k) = get_primes k.\nProof.\n  intro H. unfold get_primes. rewrite (prime_sieve_Sk_eq k H).\n  rewrite update_primes_dont_changes_primes. reflexivity.\nQed.\n\nTheorem get_primes_Sk_cons (k : nat)\n  : 0 < k\n    -> snd (update_primes (S k) (prime_sieve k)) = false\n    -> get_primes (S k) = (S k) :: get_primes k.\nProof.\n  intros k_gt H. unfold get_primes.\n  rewrite (prime_sieve_Sk_cons k k_gt H). simpl.\n  rewrite update_primes_dont_changes_primes. reflexivity.\nQed.\n\nTheorem is_composite_prop (k : nat) (ps : list (nat * nat))\n  : is_ps_list k ps = true -> is_composite k ps = true\n    -> exists q : nat, In q (map fst ps) /\\ k mod q = 0.\nProof.\n  induction ps as [| (p, m) ps1 IH];\n    intros psl comp; [discriminate comp|].\n  simpl in psl, comp. rewrite !andb_true_iff in psl.\n  destruct psl as [[[[pnz p_div] k_lt] k_gt] psl].\n  rewrite negb_true_iff, Nat.eqb_neq in pnz.\n  rewrite Nat.eqb_eq in p_div. rewrite Nat.leb_le in k_lt.\n  rewrite Nat.ltb_lt in k_gt.\n  rewrite orb_true_iff in comp.\n  destruct comp as [eq | comp].\n  - apply Nat.eqb_eq in eq. subst m.\n    exists p. simpl. auto.\n  - simpl. apply (IH psl) in comp as [q [q_in q_div]].\n    exists q. auto.\nQed.\n\nTheorem is_composite_prop_neg (k : nat) (ps : list (nat * nat))\n  : is_ps_list k ps = true -> is_composite k ps = false\n    -> forall q : nat, In q (map fst ps) -> k mod q <> 0.\nProof.\n  induction ps as [| (p, m) ps' IH];\n    intros psl ncomp q qin; [contradict qin|].\n  simpl in *.\n  apply orb_false_elim in ncomp. destruct ncomp as [mnk ncomp'].\n  apply Nat.eqb_neq in mnk.\n  rewrite !andb_true_iff in psl.\n  destruct psl as [[[[pnz m_div_p] k_lt] k_gt] psl'].\n  apply negb_true_iff, Nat.eqb_neq in pnz.\n  apply Nat.eqb_eq in m_div_p. apply Nat.leb_le in k_lt.\n  apply Nat.ltb_lt in k_gt.\n  pose (IH psl' ncomp') as IH'.\n  destruct qin as [p_is_q | qin'].\n  - subst q. intro C.\n    apply Nat.mod_divides in C; [| exact pnz].\n    destruct C as [s eq_k].\n    apply Nat.mod_divides in m_div_p; [| exact pnz].\n    destruct m_div_p as [q eq_m]. subst k m.\n    apply Nat.neq_0_lt_0 in pnz as p_gt.\n    rewrite <- Nat.mul_le_mono_pos_l in k_lt; [|exact p_gt].\n    rewrite <- Nat.mul_pred_r in k_gt.\n    rewrite <- Nat.mul_lt_mono_pos_l in k_gt; [|exact p_gt].\n    apply mnk. rewrite Nat.mul_cancel_l; [|exact pnz].\n    destruct q as [| q'].\n    + apply le_n_0_eq in k_lt. now subst s.\n    + simpl in k_gt. rewrite Nat.le_succ_r in k_lt.\n      destruct k_lt as [neq | eq].\n      * apply (Nat.lt_le_trans _ _ _ k_gt) in neq.\n        contradict neq. apply Nat.lt_irrefl.\n      * now subst s.\n  - apply IH' in qin' as H. apply H.\nQed.\n\nTheorem update_primes_snd_is_composite (k : nat)\n  : snd (update_primes (S k) (prime_sieve k))\n    = is_composite (S k) (prime_sieve k).\nProof.\n  pose (prime_sieve_is_ps_list k) as H.\n  apply update_primes_correct in H.\n  destruct (update_primes (S k) (prime_sieve k)) as (ps, is_comp).\n  destruct H as [H1 H2]. rewrite <- H2. reflexivity.\nQed.\n\nTheorem in_get_primes_Sk (p k : nat)\n  : In p (get_primes (S k))\n    -> In p (get_primes k)\n      \\/ (p = S k /\\ forall q : nat, In q (get_primes k) -> p mod q <> 0).\nProof.\n  destruct (snd (update_primes (S k) (prime_sieve k))) eqn:eq.\n  - apply get_primes_Sk_eq in eq. rewrite eq. auto.\n  - destruct k as [| k']; intro H.\n    + simpl in *. contradict H.\n    + apply (get_primes_Sk_cons (S k')) in eq as T.\n      2:{ apply Nat.lt_0_succ. }\n      rewrite T in H. simpl in H. destruct H as [H | H].\n      * right. split; [auto|]. subst p. clear T.\n        rewrite update_primes_snd_is_composite in eq.\n        apply is_composite_prop_neg; [apply prime_sieve_is_ps_list | assumption].\n      * left. exact H.\nQed.\n\nTheorem get_primes_include_Sk (k p : nat)\n  : In p (get_primes k) -> In p (get_primes (S k)).\nProof.\n  destruct (snd (update_primes (S k) (prime_sieve k))) eqn:H.\n  - rewrite (get_primes_Sk_eq k H). auto.\n  - destruct k as [| k'].\n    + simpl. auto.\n    + pose (Nat.lt_0_succ k') as neq.\n      rewrite (get_primes_Sk_cons (S k') neq H).\n      intro H'. simpl. right. exact H'.\nQed.\n\nTheorem prime_le_k (k p : nat) : In p (get_primes k) -> 1 < p <= k.\nProof.\n  induction k as [| k1 IH]; [contradiction|]. intro H.\n  pose (prime_sieve_is_ps_list (S k1)) as psl.\n  destruct k1 as [| k2]; [contradict H|].\n  apply (in_get_primes_Sk p (S k2)) in H as [H | [H _]].\n  - apply IH in H. lia.\n  - subst p. lia.\nQed.\n\nTheorem get_primes_prime_head (k : nat)\n  : prime k -> In k (get_primes k).\nProof.\n  induction k as [| k1 IH]; intro H.\n  { simpl in *. unfold prime in H.\n    destruct H as [[C _] _]. now apply C. }\n  destruct (snd (update_primes (S k1) (prime_sieve k1))) eqn:H1.\n  - rewrite (get_primes_Sk_eq k1 H1).\n    rewrite update_primes_snd_is_composite in H1.\n    apply (is_composite_prop (S k1) _ (prime_sieve_is_ps_list k1)) in H1.\n    destruct H1 as [q [q_in q_div]].\n    unfold prime in H. destruct H as [[kn0 kn1] H].\n    exfalso. apply H. exists q. apply prime_le_k in q_in.\n    split; lia.\n  - destruct k1 as [| k2].\n    { apply prime_is_prime in H. unfold is_prime in H.\n      discriminate H. }\n    pose (Nat.lt_0_succ k2) as k_gt.\n    rewrite (get_primes_Sk_cons (S k2) k_gt H1).\n    simpl. now left.\nQed.\n\nTheorem get_primes_div_k (k : nat)\n  : 1 < k -> exists p : nat, In p (get_primes k) /\\ k mod p = 0.\nProof.\n  intro k_gt.\n  destruct k as [| k1];\n    [contradict k_gt; apply Nat.nlt_0_r|].\n  destruct (snd (update_primes (S k1) (prime_sieve k1))) eqn:comp.\n  - rewrite (get_primes_Sk_eq k1 comp).\n    rewrite update_primes_snd_is_composite in comp.\n    apply (is_composite_prop\n             (S k1) (prime_sieve k1)\n             (prime_sieve_is_ps_list k1)\n             comp).\n  - apply lt_S_n in k_gt. rewrite (get_primes_Sk_cons k1 k_gt comp).\n    simpl. exists (S k1). split.\n    + left. reflexivity.\n    + apply Nat.mod_same. lia.\nQed.\n\nLemma get_primes_div' (k n : nat)\n  : 1 < n -> exists p : nat, 1 < p <= n /\\ In p (get_primes (k + n)) /\\ n mod p = 0.\nProof.\n  induction k as [| k1 IH]; intro n_gt.\n  - simpl. apply get_primes_div_k in n_gt as [p [p_in p_div]].\n    exists p. split; [|split]; try assumption.\n    apply prime_le_k, p_in.\n  - apply IH in n_gt as [p [[p_gt p_lt] [p_in p_div]]].\n    clear IH. exists p. split; [auto | split]; [|exact p_div].\n    simpl. apply get_primes_include_Sk, p_in.\nQed.\n\nTheorem get_primes_div (k n : nat)\n  : 1 < n <= k -> exists p : nat, 1 < p <= n /\\ In p (get_primes k) /\\ n mod p = 0.\nProof.\n  intros [n_gt n_lt]. pose (k - n) as d.\n  replace k with (d + n) by lia.\n  apply get_primes_div', n_gt.\nQed.\n\nTheorem hd_in {X : Type} (x : X) (xs : list X)\n  : hd_error xs = Some x -> In x xs.\nProof.\n  intro H. destruct xs as [| x1 xs1].\n  - simpl in H. discriminate H.\n  - simpl in H. inversion H as [eq]. simpl. left. reflexivity.\nQed.\n\nTheorem get_primes_return_primes (k p : nat)\n  : In p (get_primes k) <-> (p <= k /\\ prime p).\nProof.\n  generalize dependent p.\n  induction k as [| k1 IH]; intro p.\n  - simpl. split; intro H; try contradiction.\n    destruct H as [H1 H2]. apply Nat.le_0_r in H1.\n    subst p. rewrite prime_is_prime in H2.\n    unfold is_prime in H2. simpl in H2. discriminate H2.\n  - split; intro H.\n    + apply in_get_primes_Sk in H as H'.\n      destruct H' as [H1 | [H1 H2]].\n      * apply IH in H1 as [H1 H2]. split; [| exact H2].\n        apply Nat.le_le_succ_r, H1.\n      * { split.\n          - rewrite <- H1. apply Nat.le_refl.\n          - subst p. unfold prime. split; [split|].\n            + apply Nat.neq_succ_0.\n            + intro Hc. rewrite Hc in H. apply H.\n            + intros [q [[q_gt q_lt] q_div]]. apply lt_n_Sm_le in q_lt.\n              pose (get_primes_div k1 q (conj q_gt q_lt)) as H3.\n              destruct H3 as [r [[r_gt r_lt] [r_in r_div]]].\n              apply H2 in r_in as r_ndiv.\n              rewrite Nat.mod_divide in *|-; try lia.\n              apply r_ndiv, (Nat.divide_trans r q (S k1)); assumption.\n        }\n    + destruct H as [p_lt p_prime].\n      apply le_lt_or_eq in p_lt. destruct p_lt as [p_lt | p_eq].\n      * apply lt_n_Sm_le in p_lt. apply get_primes_include_Sk.\n        apply ((proj2 (IH p)) (conj p_lt p_prime)).\n      * subst p. destruct k1 as [| k2] eqn:eq.\n        { subst k1. simpl. apply prime_is_prime in p_prime.\n          discriminate p_prime. }\n        assert (0 < (S k2)) as neq_k by lia.\n        apply get_primes_prime_head, p_prime.\nQed.\n\nTheorem get_primes_return_all_primes (k p : nat)\n  : p <= k  -> prime p -> In p (get_primes k).\nProof.\n  intros p_lt p_prime. apply get_primes_return_primes. auto.\nQed.\n\n(* 6.4.4 The Type of Disjoint Sums *)\nPrint sum.\n(* Inductive sum (A B : Type) : Type\n   := inl : A -> A + B\n    | inr : B -> A + B *)\nCheck (sum nat bool).     (* (nat + bool)%type : Set *)\nCheck (inl bool 4).     (* inl 4 : nat + bool *)\nCheck (inr nat false). (* inr false : nat + bool *)\n\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/ch06/6_inductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7604728041194526}}
{"text": "(******************************************************************************)\n(* Solutions of exercises : Type inference by canonical structures            *)\n(******************************************************************************)\n\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.\nFrom mathcomp Require Import choice fintype  tuple finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(******************************************************************************)\n(* Exercise 5.1.1                                                             *)\n(******************************************************************************)\n\nRecord zmodule_mixin (T : Type) : Type := ZmoduleMixin {\n  zero : T;\n  opp : T -> T;\n  add : T -> T -> T;\n  addA : associative add;\n  addC: commutative add;\n  addm0 : left_id zero add;\n  add0m : left_inverse zero opp add\n}.\n\nRecord zmodule : Type := Zmodule {\n  carrier :> Type;\n  spec : zmodule_mixin carrier\n}.\n\n\nDefinition bool_zmoduleMixin := ZmoduleMixin addbA addbC addFb addbb.\n\n\nDefinition bool_zmodule := Zmodule bool_zmoduleMixin.\n\n\nDefinition zmadd (Z : zmodule) := add (spec Z).\n\nNotation \"x \\+ y\" :=    (@zmadd _ x y)(at level 50,left associativity).\n\n\n(* We first need to prove that zmadd is associative and commutative *)\n(* The proof consists in breaking successivly the two nested records *)\n(*to recover all the ingredients present in the zmodule_mixin. Then *)\n(*the goal becomes trivial because the associative and commutative *)\n(*requirements were present in the spec. *)\nLemma zmaddA : forall m : zmodule, associative (@zmadd m).\nProof. by case=> Mc []. Qed.\n\nLemma zmaddC : forall m : zmodule, commutative (@zmadd m).\nProof. by case=> Mc []. Qed.\n\n(* No we can conveniently prove the lemma *)\n(* The ssreflect rewrite tactic allows rewrite redex selection by *)\n(* pattern, and this is used here to select the occurrence where *)\n(* commutativity should be used.*)\nLemma zmaddAC : forall (m : zmodule)(x y z : m), x \\+ y \\+ z = x \\+ z \\+ y.\nProof.\nby move=> M x y z; rewrite -zmaddA [y \\+ _]zmaddC zmaddA.\nQed.\n\n(******************************************************************************)\n(* Exercise 5.2.1                                                             *)\n(******************************************************************************)\n\n(* Be aware that the Print command shows terms as they are represented *)\n(*by the system, which is possibliy syntactically slightly different *)\n(*from the definition typed by the user (specially in the case of *)\n(*nested pattern matching *)\nPrint nat_eqType.\nPrint nat_eqMixin.\nPrint eqn.\nCheck @eqnP.\n\nPrint bool_eqType.\nPrint bool_eqMixin.\nPrint eqb.\nCheck @eqbP.\n\n(* Look for nat, bool, Equality.sort in the answer of the command: *)\nPrint Canonical Projections.\n(* The equations stored after these declarations are respectively :\n[ Equality.sort ? == nat  ] => ? = nat_eqType\n[ Equality.sort ? == bool ] => ? = bool_eqType\n*)\n\n\n(******************************************************************************)\n(* Exercise 5.2.2                                                             *)\n(******************************************************************************)\n\n(* This script uses a complex intro pattern: the apply: (iffP andP) *)\n(*tactic breaks the reflect goal into two subgoals for each *)\n(*implication, while interpreting the first assumption of each *)\n(*generated sugoal with the andP view. Then the [[] | [<- <- ]] // *)\n(*intropattern simultaneously describes the introduction operations *)\n(*performed on the two subgoals:*)\n(*- on the first subgoal the [] casing intropattern splits the *)\n(*conjunction hypothesis into two distinct assumptions.*)\n(*   - on the second hypothesis the  [<- <- ] is composed of a [] *)\n(*casing intropattern and two <- rewrite intropatterns. [] performs an *)\n(*injection on the equality, generating two equalities, one for each *)\n(*components of the pairs.  Then both equalities are rewritten form *)\n(*left to right by <- <-.  This subgoal is now trivial hence closed by *)\n(*// *)\nLemma tuto_pair_eqP : forall T1 T2, Equality.axiom (@pair_eq T1 T2).\nProof. \nmove=> T1 T2 [u1 u2] [v1 v2] /=. \napply: (iffP andP) => [[]|[<- <-]] //.\nby do 2!move/eqP->.\nQed.\n\n\n(******************************************************************************)\n(* Exercise 5.3.1                                                             *)\n(******************************************************************************)\nSection SeqMem.\n\nVariable T : eqType.\n\nImplicit Type s : seq T.\nImplicit Types x y : T.\n\nLemma tuto_in_cons : forall y s x,\n  (x \\in y :: s) = (x == y) || (x \\in s).\nProof. by []. Qed.\n\n(* by [] is an alternative syntax for the done tactic *)\nLemma tuto_in_nil : forall x, (x \\in [::]) = false.\nProof. by []. Qed.\n\nLemma tuto_mem_seq1 : forall x y, (x \\in [:: y]) = (x == y).\nProof. by move=> x y; rewrite in_cons orbF. Qed.\n\n(* Here we do not even need to name the elements introduced since they *)\n(*will never be used later in the script. We let the system choose *)\n(*names using the move=> * tactic. *)\nLemma tuto_mem_head : forall x s, x \\in x :: s.\nProof.  by move=> *; exact: predU1l. Qed.\n\n(******************************************************************************)\n(* Exercise 5.3.2                                                             *)\n(******************************************************************************)\n\nLemma tuto_mem_cat : forall x s1 s2,\n  (x \\in s1 ++ s2) = (x \\in s1) || (x \\in s2).\nProof.\nby move=> x s1 s2; elim: s1 => //= y s1 IHs; rewrite !inE /= -orbA -IHs.\nQed.\n\nLemma tuto_mem_behead: forall s, {subset behead s <= s}.\nProof. move=> [|y s] x //; exact: predU1r. Qed.\n\nFixpoint tuto_has (a : pred T) s := \n  if s is x :: s' then a x || tuto_has a s' else false.\n\nLemma tuto_hasP : forall (a : pred T) s,\n  reflect (exists2 x, x \\in s & a x) (has a s).\nProof.\nmove=> a; elim=> [|y s IHs] /=; first by right; case.\ncase ay: (a y); first by left; exists y; rewrite ?mem_head.\napply: (iffP IHs) => [] [x ysx ax]; exists x => //; first exact: mem_behead.\nSearch _ (_ \\in cons _ _).\nby move: ysx ax; rewrite in_cons; case/orP=> //; move/eqP->; rewrite ay.\nQed.\n\n(* In fact, the last line of the previous script can be simplified by *)\n(*the use of the predU1P view lemma. This is possible since the mem *)\n(*function on sequences is exactly programmed as required by the statement *)\n(*of predU1P. *)\n\n\nLemma tuto_hasP_alt: forall (a : pred T) s,\n  reflect (exists2 x, x \\in s & a x) (has a s).\nProof.\nmove=> a; elim=> [|y s IHs] /=; first by right; case.\ncase ay: (a y); first by left; exists y; rewrite ?mem_head.\napply: (iffP IHs) => [] [x ysx ax]; exists x => //; first exact: mem_behead.\nby case: (predU1P ysx) ax => [->|//]; rewrite ay.\nQed.\n\n\nFixpoint tuto_all a s := if s is x :: s' then a x && tuto_all a s' else true.\n\n(* We again use predU1P to shortcut the combination of incons and eqP *)\nLemma tuto_allP : forall (a : pred T) s,\n    reflect (forall x, x \\in s -> a x) (all a s).\nProof.\nProof.\nmove=> a; elim=> [|x s IHs]; first by left.\nrewrite /= andbC; case: IHs => IHs /=.\n  apply: (iffP idP) => [Hx y|]; last by apply; exact: mem_head.\n  by case/predU1P=> [->|Hy]; auto.\nby right; move=> H; case IHs; move=> y Hy; apply H; exact: mem_behead.\nQed.\n\nEnd SeqMem.", "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/section5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7604162385840604}}
{"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 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. lfind.  rewrite (plus_commut y x). lfind.  rewrite IHx.  rewrite plus_succ.  reflexivity. \nAdmitted.\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. rewrite mult_assoc. rewrite (mult_commut x y). 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_goal84_mult_succ_80_plus_assoc/goal84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7604135759050459}}
{"text": "Inductive subseq : list nat -> list nat -> Prop :=\n| first_case: forall (l2: list nat), subseq [] l2\n| second_case: forall (l1 l2: list nat) (x: nat),\n    subseq l1 l2  ->\n    subseq (x :: l1) (x :: l2)\n| third_case: forall (l1 l2: list nat) (x: nat),\n    subseq l1 l2 -> subseq l1 (x :: l2).\n\nTheorem subseq_refl : forall (l: list nat),\n    subseq l l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - apply first_case.\n  - apply second_case. apply IH.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3: list nat),\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H.\n  - apply first_case.\n  - simpl. apply second_case. apply IHsubseq.\n  - simpl. apply third_case. apply IHsubseq.\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/Chapter7/subsequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7604135701042825}}
{"text": "(**  \n  Exercícios\n\n  1) Theorem ex1 : forall P Q, P /\\ Q -> P.\n  2) Theorem ex2 : forall P Q, P /\\ Q -> Q.\n  3) Theorem ex3 : forall P Q, (P -> Q) -> P -> Q.\n  4) Theorem ex4 : forall P Q R, (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\n\n**)\n\nTheorem ex1 : forall P Q, P /\\ Q -> P.\nProof.\n  intros. destruct H as [H1 H2]. apply H1.\nQed.\n\nTheorem ex2 : forall P Q, P /\\ Q -> Q.\nProof.\n  intros. destruct H as [H1 H2]. apply H2.\nQed.\n\nTheorem ex3 : forall P Q, (P -> Q) /\\ P -> Q.\nProof.\n(* Prova aqui *)\nAdmitted.\n\nTheorem ex4 : forall P Q R, (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\nProof.\n(* Prova aqui *)\nAdmitted.", "meta": {"author": "renatoleme", "repo": "Grupo_Coq", "sha": "9c8f8237815c08b8db400a9c25dd46cd586b6efe", "save_path": "github-repos/coq/renatoleme-Grupo_Coq", "path": "github-repos/coq/renatoleme-Grupo_Coq/Grupo_Coq-9c8f8237815c08b8db400a9c25dd46cd586b6efe/wsp/ND/ND.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7603877771909089}}
{"text": "\n  Axiom Tf1_equality  : forall {T U:Type} (f g:T->U),\n    (forall x, f x = g x) -> f = g.\n\n  Axiom Tf2_equality : forall {T U V:Type} (f g:T->U->V),\n    (forall x y, f x y = g x y) -> f = g.\n\n  Definition idempotent {T:Type} (f:T->T) :=\n    forall x, f x =  f (f x).\n\n  Definition involutive {T:Type} (f:T->T) :=\n     forall x, f (f x) = x.\n\n  Definition injective {T U:Type} (f:T->U) :=\n    forall x y, f x = f y -> x = y.\n\n  Definition surjective {T U:Type} (f:T-> U) :=\n    forall y, exists x, f x = y.\n\n  Definition bijective {T U:Type} (f:T->U) :=\n    injective f /\\ surjective f.\n\n  Definition periodic {T U:Type} (f:T->U) (Tplus:T->T->T) :=\n    exists P, forall x, f(Tplus x P) = f x.\n\n  Definition commutative {T:Type} (f:T->T->T) := \n    forall x y, f x y = f y x.\n\n  Definition associative {T:Type} (f:T->T->T) :=\n    forall x y z, f x (f y z) = f (f x y) z.\n\n  Definition distributive_r {T:Type} (f g:T->T->T) :=\n    forall x y z, f (g x y) z = f (g x z) (g y z).\n\n  Definition distributive_l {T:Type} (f g:T->T->T) :=\n    forall x y z, f z (g x y) = f (g z x) (g z y).\n\n  Definition neutral {T:Type} (Top:T->T->T)(e:T) :=\n    forall x, Top x e = x.\n\n  Definition cancel {T:Type} (Top:T->T->T) (e:T) :=\n    forall x, Top x e = e.\n\n  Definition even {T:Type} (f:T->T) (Topp:T->T) :=\n    forall x, f (Topp x) = f x.\n\n  Definition odd {T:Type} (f:T->T) (Topp:T->T) :=\n    forall x, f (Topp x) = Topp (f x).\n\n  Definition monotonic {T U:Type} (f:T->U) (ordT:T->T->Prop) (ordU:U->U->Prop) :=\n    forall x y, ordT x y -> ordU (f x) (f y).\n\n  Definition between {T:Type} (R:T->T->Prop) x y z :=\n    R x y /\\ R y z.\n\n  (* TODO: Check correctness *)\n  Definition continuous {T U:Type}\n      (RT:T->T->Prop) (RU:U->U->Prop)\n      (Tzero:T) (Uzero:U)\n      (Tminus:T->T->T) (Tplus:T->T->T)\n      (Uminus:U->U->U) (Uplus:U->U->U)\n      (f:T->U) (D:T->Prop) (x0:T) :=\n    D x0 ->\n    forall e, RU Uzero e -> (\n      exists d, RT Tzero d -> (\n        forall x, D x ->\n          between RT (Tminus x0 d) x (Tplus x0 d) ->\n          between RU (Uminus (f x0) e) (f x) (Uplus (f x0) e)\n      )\n    ).\n\n  (* TODO: Check correctness *)\n  Definition uniform_continuous {T U:Type}\n      (RT:T->T->Prop) (RU:U->U->Prop)\n      (Tzero:T) (Uzero:U)\n      (Tminus:T->T->T) (Tplus:T->T->T)\n      (Uminus:U->U->U) (Uplus:U->U->U)\n      (f:T->U) (D:T->Prop) (x0:T) :=\n    D x0 ->\n    forall e, RU Uzero e -> (\n      exists d, RT Tzero d -> (\n        forall x y, D x -> D y ->\n          (RT (Tminus x y) d /\\ RT (Tminus y x) d) ->\n          (RU (Uminus (f x) (f y)) e /\\ RU (Uminus (f y) (f x)) e)\n      )\n    ).\n\n  Definition reflexive {T:Type} (R:T->T->Prop) :=\n    forall x, R x x.\n\n  Definition irreflexive {T:Type} (R:T->T->Prop) := \n    forall x y, R x y -> R y x -> False.\n\n  Definition symmetric {T:Type} (R:T->T->Prop) :=\n    forall x y, R x y -> R y x.\n\n  Definition transitive {T:Type} (R:T->T->Prop) :=\n    forall x y z, R x y -> R y z -> R x z.\n\n  Definition antisymmetric {T:Type} (R:T->T->Prop) :=\n    forall x y, R x y -> R y x -> x = y.\n\n  Definition equivalence {T:Type} (R:T->T->Prop) :=\n    reflexive R  /\\ symmetric R /\\ transitive R.\n\n  Definition identity (T:Type) (x:T) := x.\n\n  Lemma Tidentity_bijective : forall (T:Type), bijective (identity T).\n  Proof.\n    intro T.\n    red.\n    split;red.\n    {\n      intros x y h.\n      unfold identity in h.\n      exact h.\n    }\n    {\n      intro y.\n      unfold identity.\n      exists y.\n      reflexivity.\n    }\n  Qed.\n\n  Lemma Tf1_intro : forall {T U:Type} (f:T->U) x y, x = y -> f x = f y.\n  Proof.\n  intros T U f x y heq.\n  subst y.\n  reflexivity.\n  Qed.\n\n  Lemma Tf2_intro_r : forall {T U V:Type} {f:T->U->V} x y z, x = y -> f x z = f y z.\n  Proof.\n    intros T U V f x y z heq.\n    subst y.\n    reflexivity.\n  Qed.\n\n  Lemma Tf2_intro_l : forall {T U V:Type} {f:T->U->V} x y z, x = y -> f z x = f z y.\n  Proof.\n    intros T U V f x y z heq.\n    subst y.\n    reflexivity.\n  Qed.\n\n  Parameter A:Type.\n\n  Parameter Aplus : A->A->A.\n  Parameter Amult : A->A->A.\n\n  Axiom Aplus_comm: commutative Aplus.\n  Axiom Amult_comm: commutative Amult.\n  Axiom Aplus_assoc: associative Aplus.\n  Axiom Amult_assoc: associative Amult.\n\n  Parameter Azero : A.\n  Parameter Aone : A.\n\n  Axiom Aplus_zero_l : forall x, Aplus Azero x = x.\n  Axiom Amult_zero_l : forall x, Amult Azero x = Azero.\n  Axiom Amult_one_l : forall x, Amult Aone x = x.\n\n  Parameter Aopp : A->A.\n\n  Axiom Aopp_cancel_r : forall x, Aplus x (Aopp x) = Azero.\n\n  Parameter Ale : A->A->Prop.\n\n  Axiom Aeq_neq : forall (x y:A), x = y \\/ x <> y.\n  Axiom Aeq_dec : forall (x y:A), sumbool (x=y) (x<>y).\n\n  Axiom Ale_le : forall x y, Ale x y \\/ Ale y x.\n  Axiom Ale_dec : forall x y, sumbool (Ale x y) (Ale y x).\n\n  Definition Alt x y := Ale x y /\\ x <> y.\n\n  Axiom Aplus_elim_r : forall x y z, Aplus x z = Aplus y z -> x = y.\n  Axiom Amult_elim_r : forall x y z, Amult x z = Amult y z -> x = y.\n\n  Lemma Aopp_cancel_l : forall x, Aplus (Aopp x) x = Azero.\n  Proof.\n    intro x.\n    rewrite (Aplus_comm _ x).\n    rewrite Aopp_cancel_r.\n    reflexivity.\n  Qed.\n\n  Lemma Aplus_elim_l : forall x y z, Aplus z x = Aplus z y -> x = y.\n  Proof.\n    intros x y z heq.\n    apply Aplus_elim_r with z.\n    repeat rewrite (Aplus_comm _ z).\n    exact heq.\n  Qed.\n\n  Lemma Amult_elim_l : forall x y z, Amult z x = Amult z y -> x = y.\n  Proof.\n    intros x y z heq.\n    apply Amult_elim_r with z.\n    repeat rewrite (Amult_comm _ z).\n    exact heq.\n  Qed.\n\n  Lemma Aplus_intro_l : forall x y z, x = y -> Aplus x z = Aplus y z.\n  Proof.\n    intros x y z heq.\n    apply Tf2_intro_r.\n    assumption.\n  Qed.\n\n  Lemma Aplus_intro_r : forall x y z, x = y -> Aplus z x = Aplus z y.\n  Proof.\n    intros x y z heq.\n    apply Tf2_intro_l.\n    assumption.\n  Qed.\n\n  Lemma Amult_intro_l : forall x y z, x = y -> Amult x z = Amult y z.\n  Proof.\n    intros x y z heq.\n    apply Tf2_intro_r.\n    assumption.\n  Qed.\n\n  Lemma Amult_intro_r : forall x y z, x = y -> Amult z x = Amult z y.\n  Proof.\n    intros x y z heq.\n    apply Tf2_intro_l.\n    assumption.\n  Qed.\n\n  Lemma Aopp_intro : forall x y, x = y -> Aopp x = Aopp y.\n  Proof.\n    intros x y heq.\n    apply Tf1_intro.\n    assumption.\n  Qed.\n\n\n  Lemma Aplus_zero_r : forall x, Aplus x Azero = x.\n  Proof.\n    intro x. rewrite Aplus_comm. apply Aplus_zero_l.\n  Qed.\n\n  Lemma Amult_zero_r : forall x, Amult x Azero = Azero.\n  Proof.\n    intro x. rewrite Amult_comm. apply Amult_zero_l.\n  Qed.\n\n  Lemma Amult_one_r : forall x, Amult x Aone = x.\n  Proof.\n    intro x. rewrite Amult_comm. apply Amult_one_l.\n  Qed.\n\n  Lemma Ale_refl : forall x, Ale x x.\n  Proof.\n    intro x.\n    assert (ha:=Ale_le x x ).\n    destruct ha as [h|h].\n    { exact h. }\n    { exact h. }\n  Qed.\n\n  Lemma Aopp_involutive : involutive Aopp.\n  Proof.\n    red.\n    intro x.\n    Search Aopp.\n    apply Aplus_elim_r with (Aopp x).\n    rewrite Aopp_cancel_l.\n    rewrite Aopp_cancel_r.\n    reflexivity.\n  Qed.\n\n", "meta": {"author": "xavierdpt", "repo": "xdcoq", "sha": "e17c739a571f0fc6c5a7fd912bc93a5b18c22f02", "save_path": "github-repos/coq/xavierdpt-xdcoq", "path": "github-repos/coq/xavierdpt-xdcoq/xdcoq-e17c739a571f0fc6c5a7fd912bc93a5b18c22f02/Abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7603877753168777}}
{"text": "Require Import prosa.classic.util.all.\nRequire Import prosa.classic.model.arrival.basic.task prosa.classic.model.arrival.basic.job prosa.classic.model.priority\n               prosa.classic.model.arrival.basic.task_arrival prosa.classic.model.arrival.basic.arrival_bounds.\nRequire Import prosa.classic.model.schedule.uni.schedule prosa.classic.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, duplicate-free 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": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/analysis/uni/basic/workload_bound_fp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7603877660109277}}
{"text": "(**\n  * Relations\n*)\n\nSet Implicit Arguments.\n\nModule Relation.\n  Definition relation (A: Type) := A -> A -> Prop.\n\n  Class Reflexive {A: Type}(R: relation A) :=\n    Reflexivity: forall x: A, R x x.\n\n  Class Symmetric {A: Type}(R: relation A) :=\n    Symmetry: forall x y: A, R x y -> R y x.\n\n  Class Transitive {A: Type}(R: relation A) :=\n    Transitivity: forall x y z: A, R x y -> R y z -> R x z.\n\n  Class Equivalence {A: Type}(eq: relation A) :=\n    {\n      equiv_eq:= eq;\n      equiv_refl :> Reflexive equiv_eq;\n      equiv_sym :> Symmetric equiv_eq;\n      equiv_trans :> Transitive equiv_eq\n    }.\n  Notation \"A == B\" := (equiv_eq A B) (at level 90, no associativity).\n\n  Class Antisymmetric {A: Type}{eq: relation A}(equiv: Equivalence eq)(R: relation A) :=\n    Antisymmetry: forall x y: A, R x y -> R y x -> x == y.\n\n\n  Class PartialOrder {A: Type}{eq: relation A}(equiv: Equivalence eq) :=\n    {\n      pord_ord: relation A;\n      pord_refl:> Reflexive pord_ord;\n      pord_trans:> Transitive pord_ord;\n      pord_antisym:> Antisymmetric equiv pord_ord;\n\n      pord_refl_eq:\n        forall x y: A,\n          x == y -> pord_ord x y\n    }.\n\n  Notation \"A <= B\" := (pord_ord A B) (at level 70, no associativity).\n\n  Section eq_Equivalence.\n    Require Import List.\n\n    Program Instance eq_Reflexive (A: Type): Reflexive (eq (A:=A)).\n    \n    Program Instance eq_Symmetric (A: Type): Symmetric (eq (A:=A)).\n    \n    Program Instance eq_Transitive (A: Type): Transitive (eq (A:=A)).\n    \n    Program Instance eq_Equivalence (A: Type): Equivalence (eq (A:=A)).\n  End eq_Equivalence.  \n\n\n  Section iff_Equivalence.\n    Program Instance iff_Reflexive: Reflexive iff.\n    Next Obligation.\n      tauto.\n    Qed.\n    \n    Program Instance iff_Symmetric: Symmetric iff.\n    Next Obligation.\n      tauto.\n    Qed.\n    \n    Program Instance iff_Transitive: Transitive iff.\n    Next Obligation.\n      tauto.\n    Qed.\n    \n    Program Instance iff_Equivalence: Equivalence iff | 100.\n\n  End iff_Equivalence.  \n\nEnd Relation.", "meta": {"author": "mathink", "repo": "mpl", "sha": "fd4ee5ca36aafac655635574df9e67743ca90442", "save_path": "github-repos/coq/mathink-mpl", "path": "github-repos/coq/mathink-mpl/mpl-fd4ee5ca36aafac655635574df9e67743ca90442/src/RelDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7603126029983749}}
{"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  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  ring.\nQed.\n", "meta": {"author": "nolze", "repo": "coqex2014", "sha": "a9de850298c66865d7aff5c8bc91da32d696d661", "save_path": "github-repos/coq/nolze-coqex2014", "path": "github-repos/coq/nolze-coqex2014/coqex2014-a9de850298c66865d7aff5c8bc91da32d696d661/011.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7602816456831964}}
{"text": "(* Cantor's pairing function. *)\n\nFrom set_theory Require Import lib fn.\n\n(* Quadratic form of Cantors pairing function *)\nDefinition π (k : nat * nat) :=\n  let k1 := fst k in\n  let k2 := snd k in\n  div2 ((k1 + k2) * (k1 + k2 + 1)) + k2.\n\n(* Step mapping *)\nDefinition π_step (k : nat * nat) : nat * nat :=\n  match k with\n  | (0, y) => (S y, 0)\n  | (S x, y) => (x, S y)\n  end.\n\n(* Compute stepped inversion of π. *)\nDefinition π_inv n := (π_step ↑ n) (0, 0).\n\nExample π_47_32 : π (47, 32) = 3192.\nProof. now lazy. Qed.\n\nExample π_inv_3192 : π_inv 3192 = (47, 32).\nProof. now lazy. Qed.\n\nLemma π_inv_succ n : π_inv (S n) = π_step (π_inv n).\nProof. easy. Qed.\n\nLemma π_steps_diagonal k1 k2 n :\n  π_inv n = (k1, 0) -> k2 <= k1 -> π_inv (n + k2) = (k1 - k2, k2).\nProof.\nunfold π_inv. induction k2; intros.\nnow rewrite add_0_r, sub_0_r.\napply IHk2 in H. rewrite add_succ_r; simpl. rewrite H.\ndestruct k1. lia. rewrite sub_succ_l; simpl. easy. all: lia.\nQed.\n\nLemma π_steps_axis k1 :\n  ∃n, π_inv n = (k1, 0).\nProof.\ninduction k1. now exists 0.\ndestruct IHk1 as [m Hm]. exists (S (m + k1)).\nerewrite π_inv_succ, π_steps_diagonal. 2: apply Hm.\nrewrite sub_diag. all: easy.\nQed.\n\n(* π_inv ranges over the entire set of pairs. *)\nTheorem π_steps_range k :\n  ∃n, π_inv n = k.\nProof.\ndestruct k as [k1 k2]. destruct (π_steps_axis (k1 + k2)) as [n Hn].\nexists (n + k2). erewrite π_steps_diagonal. 2: apply Hn.\nnow rewrite add_sub. lia.\nQed.\n\nLemma div2_cancel m n :\n  div2 (m + n * 2) = div2 m + n.\nProof.\nrewrite div2_div, div_add, <-div2_div. all: easy.\nQed.\n\n(* π is the inverse of π_inv. *)\nTheorem π_π_inv_id n :\n  π (π_inv n) = n.\nProof.\nunfold π_inv. induction n. easy. simpl.\nremember ((π_step ↑ n) (0, 0)) as k. rewrite <-IHn.\ndestruct k as [k0 k1], k0, k1; unfold π; simpl; rewrite ?add_0_r. easy.\n(* Simplify div2 match. *)\n1: replace (k1 + 1 + k1 * S (k1 + 1))\n      with (S (k1*k1 + 3*k1)) by lia.\n2: replace (k0 + 1 + k0 * S (k0 + 1))\n      with (S (k0*k0 + 3*k0)) by lia.\n3: replace (k0 + S k1 + 1 + (k0 + S k1) * S (k0 + S k1 + 1))\n      with (S (k0*k0 + k1*k1 + 2*k0*k1 + 5*k0 + 5*k1 + 2*2)) by lia.\n(* Simplify other side *)\n1: replace (k1 + 1 + S (S (k1 + 1 + k1 * S (S (k1 + 1)))))\n      with (k1 * k1 + 3 * k1 + (k1 + 2)*2) by lia.\n2: replace ((k0 + 1) * (k0 + 1 + 1))\n      with (k0*k0 + 3*k0 + 1*2) by lia.\n3: replace ((k0 + S (S k1)) * (k0 + S (S k1) + 1))\n      with (k0*k0 + k1*k1 + 2*k0*k1 + 5*k0 + 5*k1 + 3*2) by lia.\n(* Simplify div2 and finish. *)\nall: rewrite ?div2_cancel; lia.\nQed.\n\n(* π_inv is the inverse of π. *)\nCorollary π_inv_π_id k :\n  π_inv (π k) = k.\nProof.\ndestruct (π_steps_range k).\nnow rewrite <-H, π_π_inv_id.\nQed.\n\nCorollary π_bijective : Bijective π.\nProof. exists π_inv; split. apply π_inv_π_id. apply π_π_inv_id. Qed.\n\nCorollary π_inv_bijective : Bijective π_inv.\nProof. exists π; split. apply π_π_inv_id. apply π_inv_π_id. Qed.\n", "meta": {"author": "bergwerf", "repo": "settheory", "sha": "e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd", "save_path": "github-repos/coq/bergwerf-settheory", "path": "github-repos/coq/bergwerf-settheory/settheory-e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd/pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7602793274234603}}
{"text": "Require Import ZArith.\n\nDefinition INC : Z := 1.\n\nModule divsteps.\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 (divsteps.g (Nat.iter n step st) = 0%Z /\\ divsteps.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 := divsteps.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 divsteps.\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/divsteps/divsteps_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7602793268536884}}
{"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\nSet Implicit Arguments.\n\nSection Non_deterministic_Minsky_Machines.\n\n  (* locations: index type for instructions, normally is nat *)\n\n  Variables loc : Set.\n\n  (* four instructions: STOPₙ, INCₙ, DECₙ and ZEROₙ (test) \n\n     only two nat valued registers, indexed with bool\n     ie true/α of which the values are denoted \"a\" below\n     and false/β of which the values are denoted \"b\" below \n\n     In any of the cases above, several instructions can \n     co-exist at a given location, hence, no instruction\n     can stop the computation by itself. This model is\n     inherently no-deterministic.\n\n     STOPₙ p:     accepts location p when α = β = 0\n     INCₙ x p q:  at location p, x += 1 and jumps to location q\n     DECₙ x p q:  at location p, x -= 1 (if possible) and jumps to location q\n                  if x is already 0 then this instruction cannot compute\n     ZEROₙ x p q: at location p, jumps to location q when x = 0 \n\n     *)\n\n  Inductive ndmm2_instr : Set :=\n    | ndmm2_stop    : loc  -> ndmm2_instr\n    | ndmm2_inc     : bool -> loc -> loc -> ndmm2_instr\n    | ndmm2_dec     : bool -> loc -> loc -> ndmm2_instr\n    | ndmm2_zero    : bool -> loc -> loc -> ndmm2_instr.\n\n  Notation α := true. \n  Notation β := false.\n\n  Notation STOPₙ := ndmm2_stop.\n  Notation INCₙ  := ndmm2_inc.\n  Notation DECₙ  := ndmm2_dec.\n  Notation ZEROₙ := ndmm2_zero.\n\n  Infix \"∊\" := In (at level 70).\n\n  (* Programs are non-deterministic and described by \n     a (finite) list of instructions \n\n     Notice that eg \n\n          [ STOPₙ 0 ; INCₙ α 0 4 ; DECₙ β 0 2 ]\n\n     can both accept location 0 (if α = β = 0)\n     or increment α and jump to location 4\n     or decrement β (if not zero already) and jump to location 2\n\n     Also repetitions and order do not matter hence these\n     lists are viewed as finite sets, see ndmm2_accept_mono \n     in ndMM2/ndmm2_utils.v\n  *)\n\n  Reserved Notation \"Σ //ₙ a ⊕ b ⊦ u\" (at level 70, no associativity).\n\n  (* Σ //ₙ a ⊕ b ⊦ u denotes \n\n         \"Σ accepts the initial location u with values α:=a and β:=b\"\n\n    This big step semantics only describes the overall accepts predicate\n    and does not capture output values.\n\n   *)\n\n  Inductive ndmm2_accept (Σ : list ndmm2_instr) : nat -> nat -> loc -> Prop :=\n\n    | in_ndmm2a_stop  : forall p,         STOPₙ p ∊ Σ      ->  Σ //ₙ   0 ⊕   0 ⊦ p\n\n    | in_ndmm2a_inc_a : forall a b p q,   INCₙ α p q ∊ Σ   ->  Σ //ₙ 1+a ⊕   b ⊦ q\n                                                           ->  Σ //ₙ   a ⊕   b ⊦ p\n\n    | in_ndmm2a_inc_b : forall a b p q,   INCₙ β p q ∊ Σ   ->  Σ //ₙ   a ⊕ 1+b ⊦ q\n                                                           ->  Σ //ₙ   a ⊕   b ⊦ p\n\n    | in_ndmm2a_dec_a : forall a b p q,   DECₙ α p q ∊ Σ   ->  Σ //ₙ   a ⊕   b ⊦ q\n                                                           ->  Σ //ₙ 1+a ⊕   b ⊦ p\n\n    | in_ndmm2a_dec_b : forall a b p q,   DECₙ β p q ∊ Σ   ->  Σ //ₙ   a ⊕   b ⊦ q\n                                                           ->  Σ //ₙ   a ⊕ 1+b ⊦ p\n\n    | in_ndmm2a_zero_a : forall b p q,    ZEROₙ α p q ∊ Σ  ->  Σ //ₙ   0 ⊕   b ⊦ q\n                                                           ->  Σ //ₙ   0 ⊕   b ⊦ p\n\n    | in_ndmm2a_zero_b : forall a p q,    ZEROₙ β p q ∊ Σ  ->  Σ //ₙ   a ⊕   0 ⊦ q\n                                                           ->  Σ //ₙ   a ⊕   0 ⊦ p\n\n  where \"Σ //ₙ a ⊕ b ⊦ u\" := (ndmm2_accept Σ a b u).\n\n  (* A problem is a program, a start location and initial values for α/β *)\n\n  Definition ndMM2_problem := { Σ : list ndmm2_instr & loc * (nat * nat) }%type.\n\n  Definition ndMM2_ACCEPT (i : ndMM2_problem) : Prop := \n    match i with existT _ Σ (u,(a,b)) => Σ //ₙ a ⊕ b ⊦ u end.\n\nEnd Non_deterministic_Minsky_Machines.\n\n\n\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/MinskyMachines/ndMM2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7602793174650683}}
{"text": "Require Import Coq.Arith.Minus.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import Definitions.\nRequire Import Environment.\nRequire Import Keys.\nRequire Import Ascii.\nRequire Import Coq.ZArith.Znat.\nRequire Import Coq.Arith.Peano_dec.\n         \nImport EvalBigStep.\nImport Expressions.\nImport Effects.  \n \nOpen Scope list_scope.\n\nFixpoint factorial (n : nat) : nat :=\nmatch n with\n  | O => S O\n  | S n' => mult n (factorial n')\nend.\n\nFixpoint fact (x : nat) : Exp :=\n  match x with\n    | 0 => pure (S 0)\n    | S n => (pure x) Times (fact n)\n  end.                    \n\n   \nDefinition Fact : Exp\n  := If (var \"x\") Equals (pure 0) Then pure 1\n     Else ((var \"x\") Times (capp  (var \"f\")((var \"x\") Minus (pure 1)))).\n\n\nDefinition MuFact : Exp\n  := mu \"f\" • lambda \"x\" • Fact.\n\nDefinition LetFactEff : Exp\n  := Let (var \"y\") As (eapp (MuFact {{ Top }}) (pure 5 {{ Top }})) In (var \"y\").\n\n\nLemma e_rec_aux :\n  forall (facts aacts bacts : Phi) \n         (f x : ascii)\n         (ef ea e': Exp)\n         (v v' : Val) \n         (env env': Env)\n         (heap fheap aheap bheap : Heap)\n         (acts : Phi),\n    (heap, env, proj_c ef) ⇓ (fheap, Cls (env', Mu f x e'), facts) ->\n    (fheap, env, proj_c ea) ⇓ (aheap, v, aacts) ->\n    (aheap, update_rec_E (f, Cls (env', Mu f x e')) (x, v) env', e') ⇓ (bheap, v', bacts) ->\n    acts = facts ++ aacts ++ bacts ->\n    (heap, env, capp (ef) (ea)) ⇓ (bheap, v', acts).\nProof.\n  intros. subst. eapply E_Capp; eauto.\nQed.\n\nLemma e_rec_eff_aux :\n  forall (facts aacts bacts : Phi)\n         (ef ea : Exp)\n         (vef vea : EffSpec) \n         (env: Env)\n         (heap fheap aheap bheap : Heap)\n         (acts : Phi)\n         (spec : Val),\n    (heap, env, proj_e ef) ⇓ (fheap, Eff vef, facts) ->\n    (fheap, env, proj_e ea) ⇓ (aheap, Eff vea, aacts) ->\n    acts = facts ++ aacts ++ bacts ->\n    spec =  Eff (vef ⊕ vea) ->\n    (heap, env, eapp (ef) (ea)) ⇓ (bheap, spec, acts).\nProof.\n  intros. subst. eapply E_Eapp; eauto.\nQed.\n\nLemma e_false_aux :\n  forall (cacts facts : Phi)\n         (e e1 e2 : Exp)\n         (v : Val)\n         (env : Env)\n         (heap cheap fheap : Heap)\n         (b : bool) (acts : Phi),\n    (heap, env, e) ⇓ (cheap, (Bit b), cacts) -> \n    (cheap, env, e2) ⇓ (fheap, v, facts) -> \n    b = false ->\n    acts = cacts ++ facts ->\n    (heap, env, If e Then e1 Else e2 {{ Top }} ) ⇓ (fheap, v, acts).\nProof.\n  intros. subst.  eapply E_False; eauto.\nQed.\n\nLemma e_true_aux :\n  forall (cacts facts : Phi)\n         (e e1 e2 : Exp)\n         (v : Val)\n         (env : Env)\n         (heap cheap theap : Heap)\n         (b : bool) (acts : Phi),\n    (heap, env, e) ⇓ (cheap, (Bit b), cacts) -> \n    (cheap, env, e1) ⇓ (theap, v, facts) -> \n    b = true ->\n    acts = cacts ++ facts ->\n    (heap, env, If e Then e1 Else e2 {{Top }} ) ⇓ (theap, v, acts).\nProof.\n  intros. subst. eapply E_True; eauto.\nQed.\n\n\nHint Constructors Dynamic.\nHint Resolve R_same_key R_diff_key_2 EProofs.add_bst.\n\nLemma example :\n  forall env heap,\n    E.Raw.bst env ->\n    Dynamic (heap, env, capp (mu \"f\" • lambda \"x\" • Fact {{ Top }} ) (pure 5 {{ Top }} ))\n                 (heap, Num 120, nil).\nProof.\n  intros env heap bst. \n  assert (x_neq_f: \"x\"%char <> \"f\"%char) by (unfold not; intro H; inversion H).\n  assert (f_neq_x: \"f\"%char <> \"x\"%char) by (unfold not; intro H; inversion H).\n  replace (Num 120) with (Num (5 * (4 * (3 * (2 * (1 * 1)))))) by (simpl; reflexivity).\n  unfold Fact.\n  \n  eapply e_rec_aux; \n    repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) || reflexivity ).\n  unfold update_rec_E, find_E, fst, snd.\n  eapply e_false_aux with (b := beq_nat 5 0); auto.  \n  eapply E_Beq; repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) ).\n  eapply E_Times; repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) ).\n\n  eapply e_rec_aux;\n    repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) || reflexivity). \n  unfold update_rec_E, fst, snd.\n  eapply e_false_aux with (b := beq_nat 4 0); auto.\n  eapply E_Beq; repeat (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)). \n  eapply E_Times; repeat (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)).\n\n  eapply e_rec_aux;\n    repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus ||  (eapply E_Var; unfold find_E; eauto) || reflexivity).\n  unfold update_rec_E, fst, snd.\n  eapply e_false_aux with (b := beq_nat 3 0); auto.\n  eapply E_Beq; (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)).\n  eapply E_Times; repeat (eapply E_Abs || eapply E_Cnt ||  (eapply E_Var; unfold find_E; eauto)).\n\n  eapply e_rec_aux;\n    repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) || reflexivity).\n  unfold update_rec_E, fst, snd.\n  eapply e_false_aux with (b := beq_nat 2 0);auto.\n  eapply E_Beq; (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)).\n  eapply E_Times; repeat (eapply E_Abs || eapply E_Cnt ||  (eapply E_Var; unfold find_E; eauto)).\n\n  eapply e_rec_aux;\n    repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) || reflexivity).\n  unfold update_rec_E, fst, snd.\n  eapply e_false_aux with (b := beq_nat 1 0);auto.\n  eapply E_Beq; (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)).\n  eapply E_Times; repeat (eapply E_Abs || eapply E_Cnt ||  (eapply E_Var; unfold find_E; eauto)).\n\n  eapply e_rec_aux;\n   repeat (eapply E_Abs || eapply E_Cnt || eapply E_Minus || (eapply E_Var; unfold find_E; eauto) || reflexivity).\n  unfold update_rec_E, fst, snd.\n  eapply e_true_aux with (b := beq_nat 0 0);auto.\n  eapply E_Beq; (eapply E_Abs || eapply E_Cnt || (eapply E_Var; unfold find_E; eauto)). \n\n  simpl; reflexivity. \nQed.\n\nLemma example2 :\n  forall env heap,\n    E.Raw.bst env ->\n    Dynamic (heap, env, LetFactEff)\n            (heap, Eff Top, nil).\nProof.\n  intros env heap bst.\n  apply E_Let. unfold MuFact.\n\n  eapply e_rec_eff_aux; simpl.\n  - eapply E_Eff.\n  - eapply E_Eff.\n  - now simpl.\n  - admit.\nQed.    \n", "meta": {"author": "esmifro", "repo": "surface-effects", "sha": "ee3a0c769c7d9f5ac17fde22971fe8d39c2e527e", "save_path": "github-repos/coq/esmifro-surface-effects", "path": "github-repos/coq/esmifro-surface-effects/surface-effects-ee3a0c769c7d9f5ac17fde22971fe8d39c2e527e/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7602123335131276}}
{"text": "From CoqAlgs Require Export Base.\n\nSet Implicit Arguments.\n\n(* Commutative rings with unit. *)\nClass UCRing : Type :=\n{\n    carrier : Type;\n    add : carrier -> carrier -> carrier;\n    mul : carrier -> carrier -> carrier;\n    zero : carrier;\n    one : carrier;\n    neg : carrier -> carrier;\n    add_assoc: forall x y z : carrier, add (add x y) z = add x (add y z);\n    add_comm : forall x y : carrier, add x y = add y x;\n    zero_l : forall x : carrier, add zero x = x;\n    zero_r : forall x : carrier, add x zero = x;\n    neg_l : forall x : carrier, add (neg x) x = zero;\n    neg_r : forall x : carrier, add x (neg x) = zero;\n    mul_assoc: forall x y z : carrier, mul (mul x y) z = mul x (mul y z);\n    mul_comm : forall x y : carrier, mul x y = mul y x;\n    one_l : forall x : carrier, mul one x = x;\n    one_r : forall x : carrier, mul x one = x;\n    distr_l : forall x y z : carrier,\n      mul x (add y z) = add (mul x y) (mul x z);\n    distr_r : forall x y z : carrier,\n      mul (add x y) z = add (mul x z) (mul y z);\n}.\n\nNotation \"x + y\" := (add x y).\nNotation \"x - y\" := (add x (neg y)).\nNotation \"x * y\" := (mul x y).\nNotation \"0\" := zero.\nNotation \"1\" := one.\nNotation \"- x\" := (neg x).\n\nCoercion carrier : UCRing >-> Sortclass.\n\n(* Basic tactics for rewriting UCRing axioms. *)\n#[global] Hint Rewrite @zero_l @zero_r @one_l @one_r @neg_l @neg_r : units.\n#[global] Hint Rewrite @add_assoc @mul_assoc : assoc.\n#[global] Hint Rewrite <- @add_assoc @mul_assoc : assoc'.\n#[global] Hint Rewrite @add_comm @mul_comm : comm.\n#[global] Hint Rewrite @distr_l @distr_r : distr.\n#[global] Hint Rewrite <- @distr_l @distr_r : distr'.\n\nLtac rng := cbn; intros; autorewrite with units assoc distr; try congruence.\nLtac rng' := cbn; intros; autorewrite with units assoc' distr'; try congruence.\n\n(* Basic lemmas. *)\nLemma add_cancel_l :\n  forall (X : UCRing) (a b b' : X), a + b = a + b' -> b = b'.\nProof.\n  intros.\n  assert (-a + (a + b) = b); rng'.\n  assert (-a + (a + b') = b'); rng'.\nQed.\n\nLemma add_cancel_r :\n  forall (X : UCRing) (a a' b : X), a + b = a' + b -> a = a'.\nProof.\n  intros. rewrite (add_comm a), (add_comm a') in H.\n  eapply add_cancel_l. exact H.\nQed.\n\nLemma neg_neg :\n  forall (X : UCRing) (x : X), --x = x.\nProof.\n  intros.\n  assert (-x + x = 0); rng.\n  assert (-x + --x = 0); rng.\n  eapply add_cancel_l. rewrite H0. rng.\nQed.\n\nLemma minus_a_a :\n  forall (X : UCRing) (a : X), a - a = 0.\nProof. rng. Qed.\n\nLemma mul_0_l :\n  forall (X : UCRing) (x : X), 0 * x = 0.\nProof.\n  intros.\n  assert (0 * x = (0 + 0) * x); rng.\n  rewrite distr_r in H.\n  assert (0 * x - 0 * x = 0 * x + (0 * x - 0 * x)).\n    rewrite <- add_assoc, <- H. trivial.\n    rewrite (minus_a_a X (0 * x)) in H0. rewrite zero_r in H0. rng.\nQed.\n\nLemma mul_0_r :\n  forall (X : UCRing) (x : X), x * 0 = 0.\nProof.\n  intros. rewrite mul_comm. apply mul_0_l.\nQed.\n\nLemma minus_zero :\n  forall X : UCRing, -0 = 0.\nProof.\n  intro.\n  rewrite <- (neg_l zero) at 2.\n  rewrite zero_r.\n  reflexivity.\nQed.\n\nLemma minus_one_l :\n  forall (X : UCRing) (a : X), -(1) * a = -a.\nProof.\n  intros.\n  apply (add_cancel_l X (1 * a)).\n  rewrite <- distr_r, one_l, 2!minus_a_a, mul_0_l.\n  reflexivity.\nQed.\n\nLemma minus_one_r :\n  forall (X : UCRing) (a : X), a * -(1) = -a.\nProof.\n  intros. rewrite mul_comm. apply minus_one_l.\nQed.\n\nLemma minus_one_x2 :\n  forall X : UCRing, -(1) * -(1) = 1.\nProof.\n  intros. rewrite minus_one_l, neg_neg. trivial.\nQed.\n\nLemma mul_minus_minus :\n  forall (X : UCRing) (a b : X), -a * -b = a * b.\nProof.\n  intros. rewrite <- (minus_one_l X a), <- (minus_one_l X b).\n  rewrite <- mul_assoc, (mul_comm (-(1))).\n  rewrite 2!mul_assoc, <- (mul_assoc (-(1))), minus_one_x2. rng.\nQed.\n\nLemma neg_add :\n  forall (X : UCRing) (a b : X), -(a + b) = -a + -b.\nProof.\n  intros.\n  assert (-(a + b) + (a + b) = 0); rng.\n  assert ((-a - b) + (a + b) = 0); rng.\n    rewrite (add_comm a). rewrite <- (add_assoc (-b)). rewrite neg_l. rng.\n    rewrite <- H0 in H. apply add_cancel_r in H. assumption.\nQed.\n\nLemma neg_mul :\n  forall (X : UCRing) (a b : X), -(a * b) = (-a) * b.\nProof.\n  intros. rewrite <- (minus_one_l X (a * b)), <- (minus_one_l X a).\n  rewrite ?mul_assoc. trivial.\nQed.\n\nLemma neg_eq :\n  forall (X : UCRing) (a b : X), -a = -b -> a = b.\nProof.\n  intros. rewrite <- (neg_neg X a), <- (neg_neg X b).\n  rewrite H. trivial.\nQed.\n\n(* Hint base for lemma rewriting. *)\n#[global] Hint Rewrite\n  add_cancel_l add_cancel_r\n  neg_neg neg_add neg_mul neg_eq\n  mul_0_l mul_0_r mul_minus_minus\n  minus_zero minus_one_l minus_one_r minus_one_x2\n  : lemmas.", "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/Structures/UCRing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7602123158527506}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nFrom mathcomp Require Import ssrnum ssralg ssrint intdiv rat order.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope ring_scope.\nImport GRing.Theory.\nImport Order.Theory.\nImport Num.Theory.\n\n(** Theorem 1.2 First-order Diophantine Equation *)\nTheorem first_diophantine (a b d g: int):\n  a <> 0 -> b <> 0 -> gcdz a b = g -> (g %| d)%Z ->\n  (exists (x y: int), (a * x) + (b * y) = d).\nProof.\n  (* implementing infinite-descending method (book's method) is somewhat hard\n     just use Bezout's coefficient.*)\n  move=> neq_a0 neq_b0 gcd_ab.\n  case: (egcdzP a b) => u v Huv _.\n  case/dvdzP => h ->.\n  exists (u * h), (v * h). subst.\n  rewrite -Huv.\n  rewrite mulrDr.\n  rewrite mulrC -mulrA mulrC mulrA -mulrA.\n  by rewrite [in a * u]mulrC [in b * v]mulrC [in v * b * h]mulrC.\nQed.\n\nTheorem first_diophantine_false (a b d g: int):\n  a <> 0 -> b <> 0 -> gcdz a b = g -> (g %| d)%Z = false ->\n  ~(exists (x y: int), (a * x) + (b * y) = d).\nProof.\n  move=> neq_a0 neq_b0 gcd_ab false_dvd.\n  case=> x [y eq_xy].\n  have dvd_gd: (g %| d)%Z.\n  rewrite -eq_xy rpredD => //=; subst;  apply: dvdz_mulr;\n                     by [apply dvdz_gcdl|apply dvdz_gcdr].\n  move: dvd_gd.\n  apply: (contraFnot _ (g %| d)%Z) => //=.\nQed.\n", "meta": {"author": "MerHS", "repo": "galois-top", "sha": "c947129b857b6d67ec54e6a9fbd52df7f84dc82d", "save_path": "github-repos/coq/MerHS-galois-top", "path": "github-repos/coq/MerHS-galois-top/galois-top-c947129b857b6d67ec54e6a9fbd52df7f84dc82d/theories/Chap1_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.760212310084295}}
{"text": "Require Export DMFP.Day11_propositions.\n\n(** Today is a long day: we're going to teach you several tactics and\n    proof methods. There are a few more exercises than usual, too. So:\n    please start early and ask for help if you need it! *)\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(* ################################################################# *)\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. We've already met\n    the [unfold] tactic when talking about [not], but it's generally\n    useful. 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,\n    (forall n m o, n * (m * o) = (n * m) * o) -> (* we'll prove this later *)\n    (forall n m, n * m = m * n) ->               (* same *)\n    square (n * m) = square n * square m.\nProof.\n  intros n m mult_assoc mult_comm.\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(* ################################################################# *)\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  eqb (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 [eqb (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, [eqb (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  eqb (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. 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    It's worth contrasting intro patterns with _match patterns_, i.e.,\n    what we write in [match] expressions. A match pattern in a branch\n    of a [match] expression names each constructor and its arguments,\n    with a [|] before each one, e.g.:\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    In contrast, an intro pattern names only the arguments of each\n    constructor, leaving out the constructor name itself, as in:\n\n   destruct n as [| n'].\n\n    You can nest patterns, e.g., to do case analysis on [n] and [n']\n    simultaneously, write:\n\n   destruct n as [| [| n']].\n\n    There will be three subgoals: [n = O], [n = S O], and [n = S (S\n    n')].\n *)\n\n(** When doing case analysis with [destruct], in each subgoal, Coq\n    remembers the assumption about [n] that is relevant for this\n    subgoal -- either [n = 0] or [n = S n'] for some n'.  The [eqn:E]\n    annotation tells [destruct] to give the name [E] to this equation.\n    Leaving off the [eqn:E] annotation causes Coq to elide these\n    assumptions in the subgoals.  This slightly streamlines proofs\n    where the assumptions are not explicitly used, but it is better\n    practice to keep them for the sake of documentation, as they can\n    help keep you oriented when working with the subgoals.  *)\n\n(** The [-] signs on the second and third lines are called\n    _bullets_, and they mark the parts of the proof that correspond to\n    each generated subgoal.  The proof script that comes after a\n    bullet is the entire proof for a subgoal.  In this example, each\n    of the subgoals is easily proved by a single use of [reflexivity],\n    which itself performs some simplification -- e.g., the first one\n    simplifies [eqb (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- _Theorem_: For any natural number [n],\n\n      eqb (n + 1) 0 = false.\n\n    _Proof_: Let [n] be given ([intros n]).\n    We go by cases on [n] ([destruct n as [| n']]):\n\n      - First, suppose [n=0]. We must show that [eqb (0 + 1) 0 = false], which we have by\n        definition ([reflexivity]).\n      - Next, suppose [n=S n']. We must show that [eqb ((S n') + 1) 0 = false], which holds\n        by the definition of [eqb] ([reflexivity]).\n\n    _Qed_.\n\n    Notice how the [destruct] lines up with what we say in the\n    paper proof. We open with announcing our intention---to do case\n    analysis on [n]. While Coq wants to know the names of any possible\n    subparts of [n] up front, in the _[as] pattern_ of the destruct;\n    in the paper proof, we find out the names when we write out which\n    case we're in explicitly: each subcase is written as its own\n    bullet, where we announce the case we're in.\n\n    We've encounted our first significant divergence (of many!)\n    between how Coq and paper proofs work. Coq keeps track of the\n    context for you, so Coq proof scripts can leave quite a bit\n    implicit. Paper proofs are meant to communicate an idea from one\n    human to another, so it's important to check in and make sure\n    everyone is on the same page---by, for example, saying what each\n    case is up front.\n\n    Finally, note that we're not \"transliterating\" the Coq: the two\n    uses of reflexivity in each branch are written slightly\n    differently in the paper proof.\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. In a paper proof, it'd be good to announce that [b=false]\n    in the first case and [b=true] in the second case.\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\nPrint complement. (* Just to remind you. *)\n\nLemma complement_involutive : forall (b : base),\n    complement (complement b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.\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\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(** As you may have noticed, many proofs perform case analysis on a variable\n    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  eqb (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** **** Exercise: 1 star, standard (minus_n_O) *)\nLemma minus_n_O : forall n : nat, n = n - 0.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n(** [] *)\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, standard (andb_true_elim2)\n\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 b c h. destruct c eqn :Ec.\n  - destruct b eqn: Eb.\n    + apply h.\n    + reflexivity.\n  - destruct b eqn: Eb.\n    + apply h.\n    + apply h.\nQed.\n(** [] *)\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(** Finally, it's often useful to do the [unfold]/[fold] 1-2 punch:\n    [unfold]ing a recursive definition and then immediately [fold]ing\n    it back up will reveal the work one step of recursion is doing\n    without doing any simplification. *)\n\nFixpoint funny_rec (n : nat) : nat :=\n  match n with\n  | O => 0\n  | S n' => if evenb n then 0 else funny_rec n'\n  end.\n\n(** **** Exercise: 2 stars, standard (funny_rec_evenb_0)\n\n    In the [n = S n'] case, notice that [simpl] gives you an annoying\n    answer, but [unfold]/[fold] works a treat. *)\nLemma funny_rec_evenb_0 : forall n,\n    evenb n = true ->\n    funny_rec n = 0.\nProof.\n  intros n H.\n  unfold funny_rec.\n  destruct n.\n  - reflexivity.\n  - rewrite -> H. reflexivity.\nQed.\n(** [] *)\n\n(** We can formalize this trick in a new tactic (yet another\n    programming language inside of Coq!).  Now, we can say [step\n    funny_rec] to go through one level of its recursion.\n\n    [step] here does the work of [unfold] followed by [fold].\n    The notations defined below mean we can also use [step] on hypotheses.\n *)\n\nLtac step_goal A := unfold A; fold A.\nLtac step_in A H := unfold A in H; fold A in H.\nTactic Notation \"step\" constr(A) := step_goal A.\nTactic Notation \"step\" constr(A) \"in\" hyp(H) := step_in A H.\n\n(* ################################################################# *)\n(** * Logical Connectives *)\n\n(** Now that we've seen [destruct], we can do more with logical\n    connectives. So far we've only _proved_ conjunctions and\n    disjunctions. How do you use them? And what about negation? *)\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** We've seen that proving a conjunction means using [split] to prove\n    each part. To go in the other direction -- i.e., to _use_ a\n    conjunctive hypothesis to help prove something else -- we employ\n    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. *)\n\n(** The following lemmas not only show the general idea, but they're\n    generally useful: it's a common situation to know [A /\\ B] but\n    only really need just [A] (or just [B]). *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ]. (* \"Let P and Q be given, and assume P /\\ Q.\" *)\n  apply HP. (* \"We have to show P; but we've just assumed P, so we're done.\" *)\nQed.\n\n(** **** Exercise: 1 star, standard, optional (proj2) *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\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  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n\n(** **** Exercise: 2 stars, standard (and_assoc)\n\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.\n    + apply HP. \n    + apply HQ.\n  - apply HR.\nQed.\n(** [] *)\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  (* \"Let [n] and [m] be given, and assume [n = 0] and [m = 0].  We\n     need to show [n + m = 0] \" *)\n  intros n m [Hn Hm].\n  (* Since n is 0 and m is 0, showing [n + m = 0] means showing [0 + 0\n     = 0], .... *)\n  rewrite Hn. rewrite Hm.\n  (* ... which is immediate by the definition of [plus]. *)\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\n    important to understand how to work with conjunctive hypotheses\n    because conjunctions often arise from intermediate steps in\n    proofs, especially in bigger developments. We'll see an example on\n    day 12. *)\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] is.\n    (Alternatively, we can write [or A B], where [or : Prop -> Prop ->\n    Prop].)\n\n    Recall that we used [left] and [right] to choose which branch of\n    disjunction to prove. Just as for conjunction, we use [destruct]\n    to ask: if we know [P \\/ Q], which one holds?  *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q HPQ. destruct HPQ as [HP | HQ].\n  - (* left *) right. apply HP.\n  - (* right *) left. apply HQ.  Qed.\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [HP | HQ].\n  - (* left *) right. apply HP.\n  - (* right *) left. apply HQ.  Qed.\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  (* WORKED IN CLASS *)\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\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\n    we assume a contradiction, then any other proposition can be\n    derived.  Following this intuition, we could define [~ P] (\"not\n    [P]\") as [forall Q, P -> Q].  Coq actually makes a slightly\n    different choice, defining [~ P] as [P -> False], where [False] is\n    a specific 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(** PROP ::= EXPR1 = EXPR2\n           | forall x : TYPE, PROP\n           | PROP1 -> PROP2\n           | PROP1 /\\ PROP2\n           | PROP1 \\/ PROP2\n           | True\n           | ~ PROP\n           | False\n *)\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\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\nTheorem not_False :\n  ~ False.\nProof.\n  (* We must show [~ False].  Towards a contradiction, assume [False].  *)\n  unfold not. intros H.\n  (* But we've already assumed something impossible---that [False]\n    holds!  By the principle of explosion, the original claim of [~\n    False] must be true. *)\n  destruct H. (* Or... [apply H]! *)\nQed.\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    (Optionally) show that Coq's definition of negation implies the\n    intuitive one mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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*)\n\n(** Especially as you're getting used to our notion of negation, using\n    the [unfold] tactic is helpful: it will turn a negation into an\n    implication. (You can use [unfold] and its partner, [fold], on any\n    [Definition] or [Fixpoint], not just [not]!) *)\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.\nQed.\n\n(** **** Exercise: 2 stars, standard (contrapositive) *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H.\n  unfold not.\n  intros HQ HP.\n  apply HQ.\n  apply H.\n  apply HP.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (boolean_functions)\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  intros f x b.\n  destruct b  eqn : Eb.\n  - rewrite x. rewrite x. reflexivity.\n  - rewrite x. rewrite x. reflexivity.\nQed.\n\n(** Now state and prove a theorem in Coq; call it\n    [negation_fn_applied_twice]. It should be similar to the previous\n    one but where the second hypothesis says that the function [f] has\n    the property that [f x = negb x].\n\n    Just like for definitions, the autograder will reject your program\n    if you don't define this theorem at the correct type! If you're\n    having trouble, talk to Prof. or a TA.  *)\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  unfold negb.\n  intros f x b.\n  destruct b  eqn : Eb.\n  - rewrite x. rewrite x. reflexivity.\n  - rewrite x. rewrite x. reflexivity.\nQed.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [injection] and [discriminate] Tactics *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O\n       | S (n : nat).\n\n    This definition asserts that every number has one of two forms:\n    either it is the constructor [O] or it is built by applying the\n    constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition are two more facts:\n\n    - The constructor [S] is _injective_, or _one-to-one_.  That is,\n      if [S n = S m], it must be 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 [true] and\n    [false] take no arguments, their injectivity is neither here\n    nor there.)  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  (* Our use of [assert] here 'captures' [n]: we're proving this just\n     for the [n] we have, not for all [n] (though it's true for all\n     [n]). *)\n  assert (H2: n = pred (S n)). { reflexivity. }\n  (* For \"obvious\" properties like this, we might prefer to write\n     [assert (H2: n = pred (S n)) by reflexivity.], avoiding the\n     nested proof. *)\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(** This technique can be generalized to any constructor by\n    writing the equivalent of [pred] -- i.e., writing a function that\n    \"undoes\" one application of the constructor. As a more convenient\n    alternative, Coq provides a tactic called [injection] that allows\n    us to exploit the injectivity of any constructor.  Here is an\n    alternate proof of the 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(** By writing [injection H as Hmn] at this point, we are asking Coq\n    to generate all equations that it can infer from [H] using the\n    injectivity of constructors (in the present example, the equation\n    [n = m]). Each such equation is added as a hypothesis (with the\n    name [Hmn] in this case) into the context. *)\n  injection H as 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  (* WORKED IN CLASS *)\n  injection H as H1 H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** Alternatively, if you just say [injection H] with no [as] clause,\n    then all the equations will be turned into hypotheses at the\n    beginning of the goal. *)\n\nTheorem injection_ex2 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  (* Let n, m, and o be given; assume [[n;m] = [o;o]]. *)\n  intros n m o H.\n  (* By this assumption and the injectivity of [cons], n must be o and\n  m must also be o. *)\n  injection H.\n  (* WORKED IN CLASS *)\n  intros H1 H2. rewrite H1. rewrite H2.\n  (* So [[n] = [m]] is just [[o]=[o]], which is immediate. *)\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (injection_ex3) *)\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 H Hj.\n  injection H.\n  rewrite Hj.\n  intros H1 H2.\n  injection H1.\n  intros H3.\n  rewrite H2.\n  rewrite H3.\n  reflexivity.\nQed.\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    in a context where we've _assumed_ that two such terms are equal,\n    we are justified in concluding anything we want, since the\n    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.  Here is an example: *)\n\nTheorem eqb_0_l : forall n,\n   eqb 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 [eqb 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(** The [discriminate] tactic is an instance of the logical principle\n    we met earlier: the _principle of explosion_. *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  (* Let n be given, and assume [S n = 0]. *)\n  intros n contra.\n  (* But by the disjointness of the constructors for [nat], this is\n  impossible---[S] of anything can't possibly be [O].  So we have a\n  contradition. *)\n  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 also follow, because we'd\n    be living in an inconsistent universe where every statement is\n    true.  We'll explore the principle of explosion in more detail in\n    the next chapter, [Logic]. *)\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  intros X x y z l j H.\n  discriminate H.\nQed.\n(** [] *)\n\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  (** The proposition [0 <> 1] is exactly the same as\n      [~(0 = 1)], that is [not (0 = 1)], which unfolds to\n      [(0 = 1) -> False]. (We use [unfold not] explicitly here\n      to illustrate that point, but generally it can be omitted.) *)\n\n  unfold not.\n\n  (** To prove an inequality, we may assume the opposite\n      equality... *)\n\n  intros contra.\n\n  (** ... and deduce a contradiction from it. Here, the\n      equality [O = S O] contradicts the disjointness of\n      constructors [O] and [S], so [discriminate] takes care\n      of it. *)\n\n  discriminate 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. discriminate H.\nQed.\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  (* Let b be given, and assume [b <> true]. Observe that b is either true or false. *)\n  intros b H. destruct b.\n  - (* b = true *)\n    (* If b is true, we must show [b = false]. But we've already\n    assumed [b <> true], so this case will never arise. *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    (* If b is false, we have our goal of [b = false] immediately. *)\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\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\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\n(** **** Exercise: 1 star, standard, optional (not_both_true_and_false)\n\n    Some (optional!) practice with logical connectives. *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" a/k/a iff connective, which asserts\n    that two propositions have the same truth value, is just the\n    conjunction of two implications. *)\n\n(** PROP ::= EXPR1 = EXPR2\n           | forall x : TYPE, PROP\n           | PROP1 -> PROP2\n           | PROP1 /\\ PROP2\n           | PROP1 \\/ PROP2\n           | True\n           | ~ PROP\n           | False\n           | PROP1 <-> PROP2\n *)\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\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  (* 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\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\n    imported a \"Setoid\" Coq library on Day11. *)\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 orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* We proceed by cases on b1. *)\n  intros [].\n  - (* Assuming [b1 = true], we must show [true || b2 = true <-> true = true \\/ b2 = true]. *)\n    (* By the definition of [orb], this is the same as showing [true = true <-> true = true \\/ b2 = true]. *)\n    simpl. intros b2.\n    (* We will prove each direction of the biconditional. *)\n    split.\n    + (* Assume [true = true].  We must show [true = true \\/ b2 = true], and the left disjunct is immediate from our assumption. *)\n      intros _. left. reflexivity.\n    + (* Now assume [true = true \\/ b2 = true]. We must show [true = true]; but this is immediate anyhow. *)\n      intros _. reflexivity.\n  - (* Assuming [b1 = false], we must show [false || b2 = true <-> false = true \\/ b2 = true].  By the definition of [orb] this is the same as showing [b2 = true <-> false = true \\/ b2 = true]. *)\n    simpl. intros []. (* We go by cases on b2. *)\n    + (* If b2 is true, we must show [true = true <-> false = true \\/ true = true].  We prove each direction separately. *)\n      split.\n      * (* Assuming [true = true], we must show [false = true \\/ true = true].  The right hand of the disjunction is immediate. *)\n        intros _. right. reflexivity.\n      * (* Assuming [false = true \\/ true = true], we must show [true = true], but that's immediate. *)\n        intros _. reflexivity.\n    + (* If b2 is false, we must show [false = true <-> false = true \\/ false = true]. *)\n      (* We prove each direction separately. *)\n      split.\n      * (* Assuming [false = true], we must show [false = true \\/ false = true].  But we've just assumed that [false = true], which is a contradiction by the disjointness of the constructors of bool. *)\n        intros H. discriminate H.\n      * (* Now assume [false = true \\/ false = true].  In either case we must prove [false = true], which is immediate by the (contradictory) assumption. *)\n        intros [H | H].\n        { apply H. }\n        { apply H. }\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 [orb_true_iff] result: *)\n\nLemma orb_true_3 :\n  forall a b c : bool, a || b || c = true <-> a = true \\/ b = true \\/ c = true.\nProof.\n  intros n m p.\n  rewrite orb_true_iff. rewrite orb_true_iff. 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 a b : bool, a || b = true -> a = true \\/ b = true.\nProof.\n  intros n m H. apply orb_true_iff. apply H.\nQed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  (* WORKED IN CLASS *)\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *)\n    intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\n(** It's common to use iff to relate functions to propositions---like\n    we already saw for [orb_true_iff]. Here we relate the [eq_base]\n    function to the [=] proposition. All of these are good practice,\n    but we leave them optional. *)\n\n(** **** Exercise: 1 star, standard, optional (eq_base_refl) *)\nLemma eq_base_refl : forall (b : base),\n    eq_base b b = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (eq_base_true) *)\nLemma eq_base_true : forall (b1 b2 : base),\n    eq_base b1 b2 = true -> b1 = b2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (eq_base_iff)\n\n    Prove a theorem characterizing equality on DNA bases.\n\n    Proofs relating equality predicates (i.e., functions) to the\n    equality proposition tend to take this form: one direction is\n    simply reflexivity (if [b1 = b2], then you need only show that\n    [eq_blah b1 b1 = true]) and the other is more involved (if\n    [eq_blah b1 b2 = true], then [b1 = b2] for real).  *)\nLemma eq_base_iff : forall (b1 b2 : base),\n    eq_base b1 b2 = true <-> b1 = b2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (not_P__P_true)\n\n    This lemma is particularly useful for when we have computational\n    characterizations of interesting properties. *)\nLemma not_P__P_true : forall P b,\n    b = true <-> P ->\n    b = false <-> ~P.\nProof.\n  intros P b H.\n  split.\n  - rewrite <-H. intros H1. rewrite H1. apply not_true_iff_false. reflexivity.\n  - destruct b eqn: bc.\n    + rewrite <-H. intros H1.  apply not_true_iff_false. apply H1.\n    + rewrite <-H. intros H1.  apply not_true_iff_false. apply H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (andb_true_iff)\n\n    The following lemma relates the conjunction to the corresponding\n    boolean operations. *)\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\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, many 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     eqb (S n) (S m) = b  ->\n     eqb 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  (eqb n 5 = true -> eqb (S (S n)) 7 = true) ->\n  true = eqb n 5  ->\n  true = eqb (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\n    class), they probably used forward reasoning. They might have even\n    told you that backward reasoning was wrong or not allowed! 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\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 eqb n 3 then false\n  else if eqb 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 (eqb n 3).\n  - (* eqb n 3 = true *) reflexivity.\n  - (* eqb n 3 = false *) destruct (eqb n 5).\n    + (* eqb n 5 = true *) reflexivity.\n    + (* eqb n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (eqb n 3) then ... else ...].  But either [n]\n    is equal to [3] or it isn't, so we can use [destruct (eqb n 3)] to\n    let us reason about the two cases.\n\n    Informally, we might read the proof above like so:\n\n    We want to show that for any number n, [sillyfun n = false].  Let\n    a number [n] be given.  Observe that [sillyfun] is defined so that\n    when [eqb n 3 = true] the result is false, when [eqb n 5 = true]\n    the result is false, and if both are false then the result is\n    [false].  We handle each case in turn.\n\n    First, suppose that [eqb n 3 = true].  Then we hit the first\n    branch of [sillyfun] and return false, and [false = false] is\n    immediate.\n\n    Second, suppose that [eqb n 5 = true].  Then we hit the second\n    branch of [sillyfun] and likewise return false.\n\n    Finally, suppose that neither of those cases hold.  Then\n    [sillyfun] also returns false and the same reasoning holds. *)\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(** More practically, we can use these case analyses to reason about\n    the complex decisions made in programs.  As a rule of thumb, you\n    will need this trick whenever you are stuck on a [match] or an\n    [if] which depends on the result of some function call rather than\n    some ready-to-hand value.\n\n    Here's a function that computes the minimum of three\n    arguments. First, let's make sure we have a good [leb] defined. *)\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\nDefinition min3 (n1 n2 n3 : nat) : nat :=\n  if leb n1 n2\n  then if leb n1 n3\n       then n1\n       else n3\n  else if leb n2 n3\n       then n2\n       else n3.\n\nDefinition argmin3 {A:Type} (cost : A -> nat) (o1 o2 o3 : A) : A :=\n  let c1 := cost o1 in\n  let c2 := cost o2 in\n  let c3 := cost o3 in\n  if leb c1 c2\n  then if leb c1 c3\n       then o1\n       else o3\n  else if leb c2 c3\n       then o2\n       else o3.\n\n(** **** Exercise: 2 stars, standard (argmin3_min3_eqs)\n\n    Relate [min3] to [argmin3]. Your proof will need to navigate why\n    [argmin3] should go one direction or another by using [destruct]\n    with a compound term relevant to the decision-making process of\n    [arg3min]. *)\nLemma argmin3_min3_eqs : forall {A:Type} (cost : A -> nat) (o1 o2 o3 : A) (n1 n2 n3 : nat),\n    cost o1 = n1 ->\n    cost o2 = n2 ->\n    cost o3 = n3 ->\n    cost (argmin3 cost o1 o2 o3) = min3 n1 n2 n3.\nProof.\n  intros A cost o1 o2 o3 n1 n2 n3 H1 H2 H3.\n  unfold argmin3.\n  unfold min3.\n  rewrite H1.\n  rewrite H2.\n  rewrite H3.\n  destruct( leb n1 n2).\n  -destruct (leb n1 n3).\n   + apply H1.\n   + apply H3.\n  -destruct (leb n2 n3).\n   + apply H2.\n   + apply H3.\nQed.\n\n\n(** To prove this one, you should be able to just use [argmin3_min3_eqs]. *)\nCorollary argmin3_min3 : forall {A:Type} (cost : A -> nat) (o1 o2 o3 : A),\n    cost (argmin3 cost o1 o2 o3) = min3 (cost o1) (cost o2) (cost o3).\nProof.\n  intros A cost o1 o2 o3. apply argmin3_min3_eqs.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\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\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if eqb n 3 then true\n  else if eqb 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    (forall n m, eqb n m = true -> n = m) ->\n    sillyfun1 n = true ->\n    oddb n = true.\nProof.\n  intros n eqb_true eq. unfold sillyfun1 in eq.\n  destruct (eqb 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 [eqb 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 [eqb 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 [eqb n 3], but at the same time add an equation to\n    the context that records which case we are in.  Recall that the\n    [eqn:] qualifier allows us to introduce such an equation, giving\n    it a name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n    (forall n m, eqb n m = true -> n = m) ->\n    sillyfun1 n = true ->\n    oddb n = true.\nProof.\n  (* Let n be given, and assume that for all n and m, if [eqb n m =\n  true] then [n = m].  Also assume [sillyfun1 n = true].  *)\n  intros n eqb_true eq. unfold sillyfun1 in eq.\n  (* \"Observe that [eqb n 3] is either true or false.\" *)\n  destruct (eqb 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 equality\n     assumption, which is exactly what we need to make progress. *)\n  - (* e3 = true *) apply eqb_true in Heqe3.\n    (* If it is true, then we know that [n = 3] by our earlier assumption. *)\n    rewrite -> Heqe3. reflexivity.\n  - (* e3 = false *)\n    (* Otherwise, [eqb n 5] is also either true or false. *)\n    (* When we come to the second equality test in the body of\n       the function we are reasoning about, we can use [eqn:] again in\n       the same way, allow us to finish the proof. *)\n    destruct (eqb n 5) eqn:Heqe5.\n    + (* e5 = true *)\n      (* If it is true, then we know [n = 5]. *)\n      apply eqb_true in Heqe5.\n      rewrite -> Heqe5. reflexivity.\n    + (* e5 = false *)\n      (* If [n] is neither 3 nor 5, [sillyfun1] could not possibly\n         have returned true, so we have a contradiction in our\n         assumptions. *)\n      discriminate eq.  Qed.\n\n(* 2021-10-04 14:37 *)\n", "meta": {"author": "Michaelcho1201", "repo": "Personal-work", "sha": "137d0a93555c62466d263a22dea2830f16a18a22", "save_path": "github-repos/coq/Michaelcho1201-Personal-work", "path": "github-repos/coq/Michaelcho1201-Personal-work/Personal-work-137d0a93555c62466d263a22dea2830f16a18a22/good work/Day12_cases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896956, "lm_q2_score": 0.9219218305645895, "lm_q1q2_score": 0.76008945237226}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.Ztestbit.\nRequire Import Crypto.Util.ZUtil.Testbit.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma pow2_mod_spec : forall a b, (0 <= b) -> Z.pow2_mod a b = a mod (2 ^ b).\n  Proof.\n    intros.\n    unfold Z.pow2_mod.\n    rewrite Z.land_ones; auto.\n  Qed.\n  Hint Rewrite <- Z.pow2_mod_spec using zutil_arith : convert_to_Ztestbit.\n\n  Lemma pow2_mod_0_r : forall a, Z.pow2_mod a 0 = 0.\n  Proof.\n    intros; rewrite Z.pow2_mod_spec, Z.mod_1_r; reflexivity.\n  Qed.\n\n  Lemma pow2_mod_0_l : forall n, 0 <= n -> Z.pow2_mod 0 n = 0.\n  Proof.\n    intros; rewrite Z.pow2_mod_spec, Z.mod_0_l; try reflexivity; try apply Z.pow_nonzero; omega.\n  Qed.\n\n  Lemma pow2_mod_split : forall a n m, 0 <= n -> 0 <= m ->\n                                       Z.pow2_mod a (n + m) = Z.lor (Z.pow2_mod a n) ((Z.pow2_mod (a >> n) m) << n).\n  Proof.\n    intros; cbv [Z.pow2_mod].\n    apply Z.bits_inj'; intros.\n    repeat progress (try break_match; autorewrite with Ztestbit zsimplify; try reflexivity).\n    try match goal with H : ?a < ?b |- context[Z.testbit _ (?a - ?b)] =>\n      rewrite !Z.testbit_neg_r with (n := a - b) by omega end.\n    autorewrite with Ztestbit; reflexivity.\n  Qed.\n\n  Lemma pow2_mod_pow2_mod : forall a n m, 0 <= n -> 0 <= m ->\n                                          Z.pow2_mod (Z.pow2_mod a n) m = Z.pow2_mod a (Z.min n m).\n  Proof.\n    intros; cbv [Z.pow2_mod].\n    apply Z.bits_inj'; intros.\n    apply Z.min_case_strong; intros; repeat progress (try break_match; autorewrite with Ztestbit zsimplify; try reflexivity).\n  Qed.\n\n  Lemma pow2_mod_pos_bound a b : 0 < b -> 0 <= Z.pow2_mod a b < 2^b.\n  Proof.\n    intros; rewrite Z.pow2_mod_spec by omega.\n    auto with zarith.\n  Qed.\n  Hint Resolve pow2_mod_pos_bound : zarith.\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/Pow2Mod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7600894486154175}}
{"text": "Module Nat.\n\nInductive Nat : Type :=\n  | O : Nat\n  | S : Nat -> Nat.\n\nNotation \"1\" := (S O).\n\nFixpoint pred (n:Nat) : Nat :=\n  match n with\n  | O    => O\n  | S n' => n'\n  end.\n\nInductive Vector : Nat -> Type :=\n  | vnil  : Vector O\n  | vcons : forall n, Nat -> Vector n -> Vector (S n).\n\nFixpoint\n  is_odd (n:Nat) : bool :=\n    match n with\n    | O    => false\n    | S n' => is_even n'\n    end\nwith\n  is_even (n:Nat) : bool :=\n    match n with\n    | O    => true\n    | S n' => is_odd n'\n    end.\n\nLemma succ_pred_0 : forall n, n <> O -> S (pred n) = n.\nProof.\n  intros n.\n  unfold not.\n  destruct n as [|n'].\n    (* n = O *)\n    intros O_neq_O.\n    case (O_neq_O (eq_refl : O = O) : False).\n    (* n = S n' *)\n    intros H. simpl. reflexivity.\nQed.\n\nLemma succ_pred : forall n, S (pred (S n)) = S n.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\nFixpoint add (m n:Nat) : Nat :=\n  match m with\n  | O    => n\n  | S m' => S (add m' n)\n  end.\n\nNotation \"m + n\" := (add m n).\n\nFixpoint mult (m n:Nat) : Nat :=\n  match m with\n  | O    => O\n  | 1  => n\n  | S m' => n + (mult m' n)\n  end.\n\nNotation \"m * n\" := (mult m n).\n\nLemma add_id_right : forall n, n + O = n.\nProof.\n  intro n.\n  induction n.\n    (* base case: O *)\n    simpl. reflexivity.\n    (* inductive: S n *)\n    simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma succ_add_one : forall n, n + 1 = S n.\nProof.\n  intros n.\n  induction n as [|n'].\n    simpl. reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma succ_associative_right : forall n m, S (n + m) = n + S m.\nProof.\n  intros n m.\n  induction n as [|n'].\n    (* base case: n = O *)\n    simpl. reflexivity.\n    (* inductive: n = S n' *)\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma succ_associative_left : forall n m, S (n + m) = S n + m.\nProof.\n  intros n m.\n  induction n as [|n'].\n    (* base case: n = O *)\n    simpl. reflexivity.\n    (* inductive: n = S n' *)\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma add_commutative : forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [|n'].\n    (* base case: n = O *)\n    simpl. rewrite add_id_right. reflexivity.\n    (* inductive: n = S n' *)\n    simpl. rewrite IHn'. rewrite succ_associative_right. reflexivity.\nQed.\n\nLemma add_associative : forall n m o, (n + m) + o = n + (m + o).\nProof.\n  intros n m o.\n  induction n. induction m. induction o.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma mult_zero_right : forall n, n * O = O.\nProof.\n  intro n.\n  induction n.\n    (* base case: O *)\n    simpl. reflexivity.\n    (* induction step: S n *)\n    simpl. rewrite IHn. destruct n as [|n].\n      simpl. reflexivity.\n      simpl. reflexivity.\nQed.\n\nLemma mult_unit_right : forall n, n * 1 = n.\nProof.\n  intro n.\n  induction n.\n    (* base case: O *)\n    simpl. reflexivity.\n    (* induction step: S n *)\n    simpl. rewrite IHn. destruct n as [|n].\n      simpl. reflexivity.\n      simpl. reflexivity.\nQed.\n\nInductive Le (n n':Nat) : Type :=\n  | le_b   : S n = n' -> Le n n'\n  | le_r   : Le n (pred n') -> Le n n'.\n\nInductive Leeq (n n':Nat) : Type :=\n  | leeq_b : n = n -> Leeq n n'\n  | leeq_r : Leeq n (pred n') -> Leeq n n'.\n\nInductive Gr (n n':Nat) : Type :=\n  | gr_b   : n = S n' -> Gr n n'\n  | gr_r   : Gr n (S n') -> Gr n n'.\n\nInductive Greq (n n':Nat) : Type :=\n  | greq_b : n = n' -> Greq n n'\n  | greq_r : Greq n (S n') -> Greq n n'.\n\nNotation \"m <  n\" := (Le   m n).\nNotation \"m <= n\" := (Leeq m n).\nNotation \"m >  n\" := (Gr   m n).\nNotation \"m >= n\" := (Greq m n).\n\nLemma le_transitive : forall m n o, m < n -> n < o -> m < o.\nProof.\n  intros m n o.\n  intros m_le_n n_le_o.\n  induction m.\n    induction n.\n      induction o.\n        discriminate.\n\nLemma helper : forall n, S n <= pred (S (S n)).\nProof.\n  intros n. simpl. exact (leeq_b (S n) (S n) eq_refl).\nQed.\n\nLemma leeq_succ : forall n, n <= S n.\nProof.\n  intro n.\n  induction n.\n    exact (leeq_r O 1 (leeq_b O O eq_refl)).\n    exact (leeq_r (S n) (S (S n)) (helper n)).\nQed.\n\nLemma leeq_succ_S : forall m n, m <= n -> m <= S n.\nProof.\n  intros m n m_leeq_n.\n  \n\nLemma lower_bound_O : forall n, O <= n.\nProof.\n  induction n.\n    exact (leeq_b O O eq_refl).\n    destruct n.\n    exact (leeq_succ O). exact (leeq_succ\n\nLemma add_leeq : forall m n, m <= n -> S m <= S n.\nProof.\n  intros m n m_leeq_n.\n  induction m.\n    induction n.\n      exact (leeq_b 1 1 eq_refl).\n      exact (IHn ())", "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/Practice/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7599922573261302}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 :=\n  plus Zero (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/goal33conj202_coqofml_63dEDd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7598867449087018}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_congruencesymmetric :\n\tforall A B C D,\n\tCong A B C D ->\n\tCong C D A B.\nProof.\n\tintros A B C D.\n\tintros Cong_AB_CD.\n\tassert (Cong A B A B) as Cong_AB_AB by (apply cn_congruencereflexive).\n\tpose proof (cn_congruencetransitive _ _ _ _ _ _ Cong_AB_CD Cong_AB_AB) as Cong_CD_AB.\n\texact Cong_CD_AB.\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_congruencesymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7598193723579781}}
{"text": "(*\n  Church Number in Coq.\n*)\n\nDefinition apply3 {X : Type} (f : X -> X) (n : X) : X :=\n  f (f (f n)).\n\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\nDefinition czero : cnat := fun (X : Type) (_ : X -> X) (x : X) => x.\nDefinition cone  : cnat := fun (X : Type) (f : X -> X) (x : X) => f x.\nDefinition ctwo  : cnat := fun _ f x => f (f x).\nDefinition cthree : cnat := @apply3.\n(* Definition cthree       := fun _ f x => f (f (f x)).*)\n\nDefinition cadd (c1 c2 : cnat) : cnat := fun _ f x => c1 _ f (c2 _ f x).\nCompute (cadd cone ctwo).\n\nDefinition cmul (c1 c2 : cnat) : cnat := fun _ f x => c1 _ (c2 _ f) x.\nCompute (cmul (cadd cone ctwo) ctwo) _ S O.\n\nDefinition cpow (c1 c2 : cnat) : cnat := fun _ f x => (c2 _ (c1 _) f) x.\nCompute (cpow ctwo cthree) _ S O.\n\n(*\nDefinition cadd (c1 c2 : cnat) : cnat := fun f x => (c1 f (c2 f x)).\nCompute (cadd cone ctwo) nat S O.\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/Coq05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867714, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7597646448110043}}
{"text": "Require Import Basics.Aux.\nRequire Import Basics.Identifier.\nRequire Import Languages.LC.Syntax.\nRequire Import Languages.LC.Semantics.\n\n(* Variables. *)\nDefinition A := Identifier 0.\nDefinition B := Identifier 1.\n\nDefinition F := Identifier 2.\nDefinition G := Identifier 3.\nDefinition H := Identifier 4.\n\nDefinition M := Identifier 5.\nDefinition N := Identifier 6.\n\nDefinition P := Identifier 7.\nDefinition Q := Identifier 8.\n\nDefinition T := Identifier 9.\nDefinition U := Identifier 10.\n\nDefinition X := Identifier 11.\nDefinition Y := Identifier 12.\nDefinition Z := Identifier 13.\n\n\n(* Church numerals. *)\nFixpoint natToChurch_aux (n:nat): exp :=\n  match n with\n  | O    => X\n  | S n' => EApp F $ natToChurch_aux n'\n  end.\nDefinition natToChurch (n:nat) :=\n  EAbs F $ EAbs X $ natToChurch_aux n.\n\nDefinition zero  := natToChurch 0.\nDefinition one   := natToChurch 1.\nDefinition two   := natToChurch 2.\nDefinition three := natToChurch 3.\n\n\n(* Church numeral arithmetic. *)\nDefinition add := EAbs M $ EAbs N $ EAbs F $ EAbs X $\n  EApp (EApp M F) $ EApp (EApp N F) X.\nDefinition add' (m n:exp) :=\n  EApp (EApp add m) n.\n\nDefinition succ := EAbs N $ EAbs F $ EAbs X $\n  EApp F $ EApp (EApp N F) X.\nDefinition succ' (n:exp) :=\n  EApp succ n.\n\nDefinition pred := EAbs N $ EAbs F $ EAbs X $\n  EApp\n    (EApp\n      (EApp N $ EAbs G $ EAbs H $ EApp H (EApp G F))\n      (EAbs U X))\n    (EAbs U U).\nDefinition pred' (n:exp) :=\n  EApp pred n.\n\nDefinition sub := EAbs M $ EAbs N $\n  EApp (EApp N pred) M.\nDefinition sub' (m n:exp) :=\n  EApp (EApp sub m) n.\n\n\n(* Church predicates. *)\nDefinition true  := EAbs A $ EAbs B A.\nDefinition false := EAbs A $ EAbs B B.\n\nDefinition and := EAbs P $ EAbs Q $\n  EApp (EApp P Q) P.\nDefinition and' (p q:exp) :=\n  EApp (EApp and p) q.\n\nDefinition isZero := EAbs N $\n  EApp (EApp N $ EAbs X false) true.\nDefinition isZero' (n:exp) :=\n  EApp isZero n.\n\nDefinition leq := EAbs M $ EAbs N $\n  isZero' $ sub' M N.\nDefinition leq' (m n:exp) :=\n  EApp (EApp leq m) n.\n\nDefinition eq := EAbs M $ EAbs N $\n  and' (leq' M N) (leq' N M).\nDefinition eq' (m n:exp) :=\n  EApp (EApp eq m) n.\n\nDefinition ite := EAbs P $ EAbs A $ EAbs B $\n  EApp (EApp P A) B.\nDefinition ite' (p a b:exp) :=\n  EApp (EApp (EApp ite p) a) b.\n\n\n(* Church pairs. *)\nDefinition pair := EAbs X $ EAbs Y $ EAbs Z $\n  EApp (EApp Z X) Y.\nDefinition pair' (x y: exp) :=\n  EApp (EApp pair x) y.\n\nDefinition fst := EAbs P $\n  EApp P (EAbs X $ EAbs Y X).\nDefinition fst' (p:exp) :=\n  EApp fst p.\n\nDefinition snd := EAbs P $\n  EApp P (EAbs X $ EAbs Y Y).\nDefinition snd' (p:exp) :=\n  EApp snd p.\n\n\n(* Church lists. *)\nDefinition nil :=\n  pair' true true.\n\nDefinition isNil :=\n  fst.\n\nDefinition cons := EAbs H $ EAbs T $ \n  pair' false (pair' H T).\nDefinition cons' (h t:exp) :=\n  EApp (EApp cons h) t.\n\nDefinition head := EAbs Z $\n  fst' (snd' Z).\nDefinition head' (z:exp) :=\n  EApp head z.\n\nDefinition tail := EAbs Z $\n  snd' (snd' Z).\nDefinition tail' (z:exp) :=\n  EApp tail z.\n\n(* Auxiliary Church functions. *)\nDefinition listFromNToM_aux := EAbs F $ EAbs N $ EAbs M $\n  ite' (leq' N M)\n    (cons' N $ EApp (EApp F $ succ' N) M)\n     nil.\nDefinition listFromNToM :=\n  EApp listFromNToM_aux listFromNToM_aux.\nDefinition listFromNToM' (n m:exp) :=\n  EApp (EApp listFromNToM n) m.\n\nDefinition sumFromNToM_aux := EAbs F $ EAbs N $ EAbs M $\n  ite' (leq' N M)\n    (add' N $ EApp (EApp F $ succ' N) M)\n     zero.\nDefinition sumFromNToM :=\n  EApp sumFromNToM_aux sumFromNToM_aux.\nDefinition sumFromNToM' (n m:exp) :=\n  EApp (EApp sumFromNToM n) m.\n", "meta": {"author": "Paul-Reftu", "repo": "coq-program-equivalence", "sha": "27b2bb56cc474d98ad120f2133ae9d0b3438b914", "save_path": "github-repos/coq/Paul-Reftu-coq-program-equivalence", "path": "github-repos/coq/Paul-Reftu-coq-program-equivalence/coq-program-equivalence-27b2bb56cc474d98ad120f2133ae9d0b3438b914/src/Languages/LC/ChurchEncoding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7596657799131907}}
{"text": "Require Import nat.\nRequire Import inductive_prop.\n\n\nDefinition some_nat_is_even : ex ev := ex_intro ev 0 ev_0.\nDefinition some_nat_is_even': ex ev := ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\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", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/test_ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7595729471011066}}
{"text": "Inductive pos : Set :=\n| SO : pos\n| S : pos -> pos.\n\nFixpoint plus(n m:pos) : pos :=\n  match n with\n    | SO => S m\n    | S p => S (p + m)\n  end\n    where \"n + m\" := (plus n m).\n\nInfix \"+\" := plus.\n\nTheorem plus_assoc : forall n m p, n + (m + p) = (n + m) + p.\nProof.\n  intros.\n  induction n.\n  reflexivity.\n  simpl.\n  f_equal.\n  assumption.\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/13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7595392938109916}}
{"text": "Theorem first_proof: (forall A : Prop, A -> A).\nProof.\n        intros A.\n        intros proof_of_A.\n        exact proof_of_A.\nQed.\n\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\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\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                        refine (A_implies_B _).\n                                exact proof_of_A.\nQed.\n\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", "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/first_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7595131550582614}}
{"text": "(*\nAuthor: Lukasz Czajka\n\nThis file is in the public domain (no copyright).\n*)\n\n(* This is a readable Coq formalisation of two variants of\nDiaconescu's theorem.\n\n1. Predicate extensionality and the relativised axiom of choice\n   together imply the excluded middle axiom.\n\n2. Predicate extensionality and the axiom of choice together imply the\n   excluded middle axiom.\n\nThe formalisation is based on the paper: N. Goodman, J. Myhill,\n\"Choice implies excluded middle\", Zeitschrift für mathematische Logik\nund Grundlagen der Mathematik 24:461 (1978)\n *)\n\n(************************************************************************************)\n(* Definitions *)\n\nDefinition AxiomOfChoice := forall (A B : Type) (R : A -> B -> Prop),\n    (forall x : A, exists y : B, R x y) -> exists f : A -> B, forall x : A, R x (f x).\n\nDefinition RelativisedAxiomOfChoice :=\n  forall (A B : Type) (Q : A -> Prop) (R : A -> B -> Prop),\n    (forall x : A, Q x -> exists y : B, R x y) ->\n    exists f : A -> B, forall x : A, Q x -> R x (f x).\n\nDefinition ExcludedMiddle := forall P : Prop, P \\/ ~P.\n\nDefinition ProofIrrelevance := forall (P : Prop) (p q : P), p = q.\n\nDefinition PredicateExtensionality := forall (A : Type) (R1 R2 : A -> Prop),\n    (forall x : A, R1 x <-> R2 x) -> R1 = R2.\n\nDefinition PropositionalExtensionality := forall (P Q : Prop), (P <-> Q) -> P = Q.\n\n(************************************************************************************)\n(* Diaconescu's theorem from relativised choice and predicate extensionality        *)\n\nTheorem pre_diaconescu_rel :\n  RelativisedAxiomOfChoice -> forall A (a b : A), a = b \\/ a <> b.\nProof.\n  unfold RelativisedAxiomOfChoice.\n  intros Hc.\n  intros A a b.\n  pose (Q := fun x : A => x = a \\/ x = b).\n  pose (R := fun (x : A) (y : bool) => (x = a /\\ y = true) \\/ (x = b /\\ y = false)).\n  assert (H : exists f : A -> bool, forall x : A, Q x -> R x (f x)).\n  { apply Hc.\n    unfold Q, R.\n    intros x H.\n    destruct H; eauto. }\n  destruct H as [f H].\n  unfold Q, R in H.\n  generalize (H a).\n  generalize (H b).\n  intros Ha Hb.\n  destruct Ha as [[? Ha]|[? Ha]]; auto.\n  destruct Hb as [[? Hb]|[? Hb]]; auto.\n  right.\n  intro.\n  subst.\n  rewrite Ha in Hb.\n  discriminate Hb.\nQed.\n\nTheorem diaconescu_rel :\n  PredicateExtensionality -> RelativisedAxiomOfChoice -> ExcludedMiddle.\nProof.\n  unfold PredicateExtensionality, RelativisedAxiomOfChoice, ExcludedMiddle.\n  intros He Hc P.\n  pose (U := fun x => x = true \\/ P).\n  pose (V := fun x => x = false \\/ P).\n  assert (H: U = V \\/ U <> V) by auto using pre_diaconescu_rel.\n  destruct H as [H|H].\n  - left.\n    assert (Heq: U false = V false) by congruence.\n    unfold U, V in Heq.\n    enough (H1: false = true \\/ P) by\n        (destruct H1 as [H1|?]; [ discriminate H1 | auto ]).\n    rewrite Heq.\n    auto.\n  - right.\n    intro HP.\n    apply H.\n    apply He.\n    intro x.\n    unfold U, V.\n    split; auto.\nQed.\n\n(************************************************************************************)\n(* Diaconescu's theorem (non-relativised version) *)\n\nTheorem pre_diaconescu : ProofIrrelevance -> AxiomOfChoice -> forall A (a b : A), a = b \\/ a <> b.\nProof.\n  unfold ProofIrrelevance, AxiomOfChoice.\n  intros Hi Hc.\n  intros A a b.\n  pose (A' := {x : A | x = a \\/ x = b}).\n  pose (R := fun (x : A') (y : bool) => (proj1_sig x = a /\\ y = true) \\/ (proj1_sig x = b /\\ y = false)).\n  assert (H : exists f : A' -> bool, forall x : A', R x (f x)).\n  { apply Hc.\n    unfold R.\n    intro x.\n    destruct x as [x H].\n    simpl.\n    destruct H; subst; eauto. }\n  destruct H as [f H].\n  unfold R in H.\n  generalize (H ltac:(unfold A'; exists a; auto)).\n  generalize (H ltac:(unfold A'; exists b; auto)).\n  simpl.\n  intros Ha Hb.\n  destruct Ha as [[? Ha]|[? Ha]]; auto.\n  destruct Hb as [[? Hb]|[? Hb]]; auto.\n  right.\n  intro; subst.\n  assert (He: or_introl eq_refl = or_intror eq_refl :> (b = b \\/ b = b)) by auto.\n  rewrite He in Hb.\n  rewrite Hb in Ha.\n  discriminate Ha.\nQed.\n\nLemma lem_pred_to_prop : PredicateExtensionality -> PropositionalExtensionality.\nProof.\n  unfold PredicateExtensionality, PropositionalExtensionality.\n  intros H P Q H1.\n  generalize (H bool (fun _ => P) (fun _ => Q)).\n  intro H2.\n  generalize (H2 (fun _ => H1)).\n  intro H3.\n  change ((fun _ => P) true = (fun _ => Q) true).\n  rewrite H3.\n  reflexivity.\nQed.\n\nLemma lem_prop_to_irrelev : PropositionalExtensionality -> ProofIrrelevance.\nProof.\n  unfold PropositionalExtensionality, ProofIrrelevance.\n  intros H P p q.\n  unfold iff in H.\n  assert (H1: P = True) by auto.\n  subst.\n  destruct p, q.\n  reflexivity.\nQed.\n\nTheorem diaconescu : PredicateExtensionality -> AxiomOfChoice -> ExcludedMiddle.\nProof.\n  unfold PredicateExtensionality, AxiomOfChoice, ExcludedMiddle.\n  intros He Hc P.\n  pose (U := fun x => x = true \\/ P).\n  pose (V := fun x => x = false \\/ P).\n  assert (H: U = V \\/ U <> V) by\n      eauto using pre_diaconescu, lem_pred_to_prop, lem_prop_to_irrelev.\n  destruct H as [H|H].\n  - assert (Heq: U false = V false) by congruence.\n    unfold U, V in Heq.\n    enough (HH: false = true \\/ P)\n      by (destruct HH; [ easy | auto ]).\n    rewrite Heq.\n    auto.\n  - enough (~P) by auto.\n    intro H1.\n    apply H.\n    apply He.\n    unfold U, V.\n    tauto.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "diaconescu", "sha": "c99591506d56cf16e734c51265c0ad440cf5b93f", "save_path": "github-repos/coq/lukaszcz-diaconescu", "path": "github-repos/coq/lukaszcz-diaconescu/diaconescu-c99591506d56cf16e734c51265c0ad440cf5b93f/diaconescu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7594217048676707}}
{"text": "(* Four different ways of proving the same theorem: evenb (double x 0) = true. *)\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\n(* double: computes 2x using an accumulator *)\nFixpoint double (x y : nat) : nat :=\n  match x with\n    | O => y\n    | S x' => double x' (S (S y))\n  end.\n\n\n\n\nTheorem even_double_1 : forall x:nat,\n  evenb (double x 0) = true.\nProof.\n  (* METHOD 1: PE with loop detection (automatic) *)\n  intros.\n\n  (* initial *)\n  induction x.\n  reflexivity.\n\n  (* recursive case *)\n  simpl.                        (* unable to use IHx *)\n  induction x.\n  reflexivity.\n\n  (* back to the recursive case *)\n  simpl.\n\n  (* Now we know this is going to go on forever, we find that the only\n  thing that is changing is the second argument to double (y). It\n  changes from y to (S (S y)) at every iteration. *)\n\n  assert (forall x y : nat,\n    evenb (double x y) = evenb (double x (S (S y)))).\n  induction x0.\n  reflexivity.\n  intros.\n  apply IHx1.\n  rewrite <- H.\n  apply IHx.\n  (* Done *)\nQed.\n\n\n\n\n(* METHOD 2: use lemma even_ss extracted from METHOD 1 *)\nLemma even_ss : \n  forall x y : nat,\n    evenb (double x y) = evenb (double x (S (S y))).\nProof.\n  induction x.\n  reflexivity.\n\n  intros y.\n  simpl. apply IHx.\nQed.\n\nTheorem even_double_2 :\n  forall x : nat, \n    evenb (double x 0) = true.\nProof.\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  rewrite <- even_ss.\n  apply IHx.\nQed.\n\n\n\n\n\nLemma even_ss_b :\n  forall x y : nat,\n    evenb (double x y) = true -> evenb (double x (S (S y))) = true.\nProof.\n  induction x.\n  intros.\n  simpl in *.\n  apply H.\n\n  simpl. \n  intros y. apply IHx.\nQed.\n\nTheorem even_double_2b :\n  forall x : nat, \n    evenb (double x 0) = true.\nProof.\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  apply even_ss2.\n  apply IHx.\nQed.\n\n\n\n\n\n(* METHOD 3: use lemma even_y *)\nLemma even_y : \n  forall x y : nat,\n    evenb y = true -> evenb (double x y) = true.\nProof.\n  (* METHOD 1: the dumb way *)\n  induction x; intros; simpl.\n  apply H.\n  apply IHx.\n  simpl.\n  apply H.\n\n  (* METHOD 2: use ; and auto *)\n  Restart.\n  induction x; simpl; auto.\nQed.\n\n\nTheorem even_double_3 :\n  forall x : nat,\n    evenb (double x 0) = true.\nProof.\n  intros.\n  apply even_y.\n  reflexivity.\nQed.\n\n\n\n\n(* By Rebecca Swords *)\nLemma double_s :\n  forall x y : nat, \n    double (S x) y = S (S (double x y)).\nProof.\n  intros x.\n  induction x.\n  reflexivity.\n\n  intros y.\n  simpl in *.\n  apply IHx.\nQed.\n\n\nTheorem even_double_4 :\n  forall x : nat, \n    evenb (double x 0) = true.\nProof.\n  induction x.\n  reflexivity.\n\n  rewrite double_s.\n  simpl.\n  apply IHx.\nQed.\n\n\n\n\n(* proof terms\n\nMETHOD 1:\n---------------------------------------------------------------\neven_double_1 =\nfun x : nat =>\nnat_ind (fun x0 : nat => evenb (double x0 0) = true) eq_refl\n  (fun (x0 : nat) (IHx : evenb (double x0 0) = true) =>\n   nat_ind\n     (fun x1 : nat =>\n      evenb (double x1 0) = true -> evenb (double x1 2) = true)\n     (fun _ : evenb (double 0 0) = true => eq_refl)\n     (fun (x1 : nat)\n        (_ : evenb (double x1 0) = true -> evenb (double x1 2) = true)\n        (IHx1 : evenb (double (S x1) 0) = true) =>\n      (fun\n         H : forall x2 y : nat,\n             evenb (double x2 y) = evenb (double x2 (S (S y))) =>\n       eq_ind (evenb (double x1 2)) (fun b : bool => b = true) IHx1\n         (evenb (double x1 4)) (H x1 2))\n        (fun x2 : nat =>\n         nat_ind\n           (fun x3 : nat =>\n            forall y : nat, evenb (double x3 y) = evenb (double x3 (S (S y))))\n           (fun y : nat => eq_refl)\n           (fun (x3 : nat)\n              (IHx2 : forall y : nat,\n                      evenb (double x3 y) = evenb (double x3 (S (S y))))\n              (y : nat) => IHx2 (S (S y))) x2)) x0 IHx) x\n     : forall x : nat, evenb (double x 0) = true\n\n\n\nMETHOD 2:\n-----------------------------------------------------\neven_double_2 =\nfun x : nat =>\nnat_ind (fun x0 : nat => evenb (double x0 0) = true) eq_refl\n  (fun (x0 : nat) (IHx : evenb (double x0 0) = true) =>\n   eq_ind (evenb (double x0 0)) (fun b : bool => b = true) IHx\n     (evenb (double x0 2)) (even_ss x0 0)) x\n     : forall x : nat, evenb (double x 0) = true\n\neven_ss =\nfun x : nat =>\nnat_ind\n  (fun x0 : nat =>\n   forall y : nat, evenb (double x0 y) = evenb (double x0 (S (S y))))\n  (fun y : nat => eq_refl)\n  (fun (x0 : nat)\n     (IHx : forall y : nat, evenb (double x0 y) = evenb (double x0 (S (S y))))\n     (y : nat) => IHx (S (S y))) x\n     : forall x y : nat, evenb (double x y) = evenb (double x (S (S y)))\n\n\n\nMETHOD 3:\n------------------------------------------------------\neven_double_3 =\nfun x : nat => even_y x 0 eq_refl\n     : forall x : nat, evenb (double x 0) = true\n\neven_y =\nfun x : nat =>\nnat_ind\n  (fun x0 : nat =>\n   forall y : nat, evenb y = true -> evenb (double x0 y) = true)\n  (fun (y : nat) (H : evenb y = true) => H)\n  (fun (x0 : nat)\n     (IHx : forall y : nat, evenb y = true -> evenb (double x0 y) = true)\n     (y : nat) (H : evenb y = true) => IHx (S (S y)) H) x\n     : forall x y : nat, evenb y = true -> evenb (double x y) = true\n\n*)\n", "meta": {"author": "zhengguan", "repo": "proofs", "sha": "9af60412af469044f0240a356a1cd6939cba0e78", "save_path": "github-repos/coq/zhengguan-proofs", "path": "github-repos/coq/zhengguan-proofs/proofs-9af60412af469044f0240a356a1cd6939cba0e78/even-double.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.7594217032050325}}
{"text": "(* Theorems about basic logic and lists. *)\n\nRequire Import PeanoNat.\nFrom larith Require Import A_setup.\n\n(******************************************************************************)\n(* I. Laws of constructive propositional and predicate logic.                 *)\n(******************************************************************************)\nSection Laws_of_logic.\n\nSection Propositions.\n\nVariable P Q : Prop.\n\nTheorem contra :\n  (P -> Q) -> (¬Q -> ¬P).\nProof.\nauto.\nQed.\n\nTheorem and_remove_r :\n  Q -> P /\\ Q <-> P.\nProof.\neasy.\nQed.\n\nTheorem or_remove_r :\n  ¬Q -> P \\/ Q <-> P.\nProof.\nintros nQ; split; intros.\nnow destruct H. now left.\nQed.\n\nTheorem exfalso_iff :\n  ¬P -> ¬Q -> P <-> Q.\nProof.\neasy.\nQed.\n\nVariable P_dec : {P} + {¬P}.\nVariable Q_dec : {Q} + {¬Q}.\n\nTheorem not_dec :\n  {¬P} + {¬¬P}.\nProof.\ndestruct P_dec; auto.\nDefined.\n\nEnd Propositions.\n\nSection Predicates.\n\nVariable X Y : Type.\nVariable P Q : X -> Prop.\n\nTheorem ex_iff :\n  (∀x, P x <-> Q x) -> (∃x, P x) <-> (∃x, Q x).\nProof.\nintros H; split; intros [x Hx]; exists x; apply H, Hx.\nQed.\n\nEnd Predicates.\n\nEnd Laws_of_logic.\n\n(******************************************************************************)\n(* II. Lists witnessing a transitive path.                                    *)\n(******************************************************************************)\nSection Reflexive_transitive_closure.\n\nVariable X : Type.\nVariable R : X -> X -> Prop.\n\nInductive RTC : list X -> Prop :=\n  | RTC_nil : RTC []\n  | RTC_refl x : RTC [x]\n  | RTC_cons x y l : RTC (y :: l) -> R x y -> RTC (x :: y :: l).\n\nTheorem RTC_weaken x l :\n  RTC (x :: l) -> RTC l.\nProof.\ndestruct l; intros.\nconstructor. inv H.\nQed.\n\nTheorem RTC_trans l1 l2 d :\n  RTC l1 -> RTC (last l1 d :: l2) -> RTC (l1 ++ l2).\nProof.\ninduction l1; simpl; intros. inv H0.\ndestruct l1; subst; simpl in *. easy.\ninv H; apply RTC_cons. apply IHl1; easy. easy.\nQed.\n\nTheorem RTC_app_inv l1 l2 :\n  RTC (l1 ++ l2) -> RTC l1 /\\ RTC l2.\nProof.\ninduction l1; simpl; intros.\nsplit; [apply RTC_nil|easy]. inv H.\n- apply eq_sym, app_eq_nil in H2 as [H1 H2]; subst.\n  split; [apply RTC_refl|apply RTC_nil].\n- rewrite H1 in H2; apply IHl1 in H2. split; [|easy].\n  destruct l1; [apply RTC_refl|inv H1; apply RTC_cons; easy].\nQed.\n\nEnd Reflexive_transitive_closure.\n\nArguments RTC {_}.\n\n(******************************************************************************)\n(* III. Various list utilities.                                               *)\n(******************************************************************************)\nModule ListUtils.\n\nTheorem cons_app {X} (x : X) l :\n  x :: l = [x] ++ l.\nProof.\neasy.\nQed.\n\nTheorem list_singleton {X} (l : list X) :\n  length l = 1 -> ∃x, l = [x].\nProof.\nintros. destruct l. easy. destruct l.\nnow exists x. easy.\nQed.\n\nTheorem last_cons {X} (x d : X) l :\n  last (x :: l) d = last l x.\nProof.\nrevert x d; induction l; simpl; intros.\neasy. destruct l. easy. apply IHl.\nQed.\n\nTheorem last_app {X} (x d : X) l1 l2 :\n  last (l1 ++ x :: l2) d = last l2 x.\nProof.\nrevert d; induction l1; intros.\nrewrite app_nil_l; apply last_cons.\nrewrite <-app_comm_cons, last_cons; apply IHl1.\nQed.\n\nTheorem split_list {X} (x : X) l :\n  In x l -> ∃l1 l2, l = l1 ++ x :: l2.\nProof.\ninduction l; intros. easy. inv H.\n- exists [], l; easy.\n- apply IHl in H0 as [l1 [l2 H]].\n  exists (a :: l1), l2; simpl; rewrite H; easy.\nQed.\n\nTheorem Forall_incl {X} P (l l' : list X) :\n  (∀x, In x l -> In x l') -> Forall P l' -> Forall P l.\nProof.\nintros; apply Forall_forall; intros.\napply Forall_forall with (x:=x) in H0; auto.\nQed.\n\nNotation lmax l := (fold_right max 0 l).\n\nTheorem lmax_in n l :\n  In n l -> n <= lmax l.\nProof.\ninduction l; simpl. easy.\nintros [H|H]; subst. apply Nat.le_max_l.\napply Nat.max_le_iff; right; apply IHl, H.\nQed.\n\nSection Forall2.\n\nSection Type_agnostic.\n\nVariable X Y Z : Type.\nVariable R S : X -> Y -> Prop.\n\nTheorem Forall2_eq (l l' : list X) :\n  Forall2 eq l l' <-> l = l'.\nProof.\nrevert l'; induction l; destruct l'; try easy.\nsplit; intros H; inv H. apply IHl in H5; now subst.\napply Forall2_cons, IHl; easy.\nQed.\n\nTheorem Forall2_impl xs ys :\n  Forall2 R xs ys -> (∀x y, R x y -> S x y) -> Forall2 S xs ys.\nProof.\nintros HR HRS; induction HR. apply Forall2_nil.\napply Forall2_cons. apply HRS, H. apply IHHR.\nQed.\n\nTheorem Forall2_map (f : Z -> Y) xs zs :\n  Forall2 R xs (map f zs) <-> Forall2 (λ x z, R x (f z)) xs zs.\nProof.\nrevert zs; induction xs; destruct zs; simpl; intros; try easy.\nsplit; intros H; inv H. all: apply Forall2_cons; [easy|now apply IHxs].\nQed.\n\nEnd Type_agnostic.\n\nCorollary Forall2_In_singleton {X} (l l' : list X) :\n  Forall2 (@In _) l (map (λ x, [x]) l') <-> l = l'.\nProof.\nrewrite Forall2_map, <-Forall2_eq. split; intros.\nall: eapply Forall2_impl; [apply H|].\nall: intros; simpl in *. inv H0. now left.\nQed.\n\nEnd Forall2.\n\nSection Mapping.\n\nVariable X Y : Type.\nVariable f : X -> Y.\n\nTheorem map_map_singleton l :\n  map (λ x, [f x]) l = map (λ y, [y]) (map f l).\nProof.\nnow rewrite map_map.\nQed.\n\nTheorem flat_map_singleton l :\n  flat_map (λ x, [f x]) l = map f l.\nProof.\ninduction l; simpl.\neasy. now rewrite IHl.\nQed.\n\nTheorem nth_map i l d x :\n  nth i l d = x -> nth i (map f l) (f d) = f x.\nProof.\nrevert i; induction l; destruct i; simpl.\n1-3: congruence. apply IHl.\nQed.\n\nHypothesis f_inj : ∀x x', f x = f x' -> x = x'.\n\nTheorem nth_map_inj i l d x :\n  nth i (map f l) (f d) = f x -> nth i l d = x.\nProof.\nrevert i; induction l; destruct i; simpl.\n1-3: apply f_inj. apply IHl.\nQed.\n\nEnd Mapping.\n\nSection Double_mapping.\n\nVariable X Y Z : Type.\nVariable f : X -> Y -> Z.\n\nFixpoint map2 xs ys :=\n  match xs, ys with\n  | x :: xs', y :: ys' => f x y :: map2 xs' ys'\n  | _, _ => []\n  end.\n\nEnd Double_mapping.\n\nSection Strip_option_list.\n\nVariable X : Type.\n\nFixpoint strip (l : list (option X)) :=\n  match l with\n  | [] => []\n  | None :: l' => strip l'\n  | Some x :: l' => x :: strip l'\n  end.\n\nTheorem strip_map_id l :\n  strip (map Some l) = l.\nProof.\ninduction l; simpl.\neasy. now rewrite IHl.\nQed.\n\nTheorem strip_app l l' :\n  strip (l ++ l') = strip l ++ strip l'.\nProof.\ninduction l as [|[x|] l]; simpl. easy.\nnow rewrite IHl. apply IHl.\nQed.\n\nEnd Strip_option_list.\n\nSection List_constructions_using_decidability.\n\nVariable X : Type.\nHypothesis dec : ∀x y : X, {x = y} + {x ≠ y}.\n\nTheorem split_at_last_instance (x : X) l :\n  In x l -> ∃l1 l2, l = l1 ++ x :: l2 /\\ ¬In x l2.\nProof.\ninduction l; intros. easy. inv H.\ndestruct (in_dec dec x l) as [H0|H0].\n1,3: apply IHl in H0 as [l1 [l2 []]]; rewrite H.\n1: exists (x :: l1), l2. 2: exists (a :: l1), l2. 3: exists [], l. all: easy.\nQed.\n\nSection Filtering.\n\nVariable P : X -> Prop.\nHypothesis P_dec : ∀x, {P x} + {¬P x}.\n\nFixpoint pfilter (l : list X) :=\n  match l with\n  | [] => []\n  | x :: l' => if P_dec x then x :: pfilter l' else pfilter l'\n  end.\n\nTheorem pfilter_spec l x :\n  In x (pfilter l) <-> In x l /\\ P x.\nProof.\ninduction l; simpl. easy.\ndestruct (P_dec a); simpl; split; intros.\nall: try split; repeat destruct H; subst.\nall: try apply IHl in H; try easy; auto.\nnow right. right; apply IHl; easy. now right. now apply IHl.\nQed.\n\nTheorem pfilter_length l :\n  length (pfilter l) <= length l.\nProof.\ninduction l; simpl. easy.\ndestruct (P_dec a); simpl.\napply le_n_S, IHl. apply le_S, IHl.\nQed.\n\nEnd Filtering.\n\nSection Intersection_and_subtraction.\n\nSection Definition_using_pfilter.\n\nVariable l s : list X.\n\nDefinition intersect :=\n  pfilter (λ x, In x s) (λ x, in_dec dec x s) l.\n\nDefinition subtract :=\n  pfilter (λ x, ¬In x s) (λ x, not_dec _ (in_dec dec x s)) l. \n\nCorollary intersect_spec x :\n  In x intersect <-> In x l /\\ In x s.\nProof.\napply pfilter_spec.\nQed.\n\nCorollary subtract_spec x :\n  In x subtract <-> In x l /\\ ¬In x s.\nProof.\napply pfilter_spec.\nQed.\n\nTheorem subtract_length :\n  length subtract = length l - length intersect.\nProof.\nunfold subtract, intersect; induction l; simpl pfilter. easy.\ndestruct (in_dec _), (not_dec _ _); try easy.\nsimpl length; rewrite IHl0; clear IHl0. remember (pfilter _ _ l0) as l1.\nassert(length l1 <= length l0) by (subst; apply pfilter_length).\nrewrite <-Nat.sub_succ_l. reflexivity. easy.\nQed.\n\nCorollary intersect_length :\n  length intersect = length l - length subtract.\nProof.\nrewrite subtract_length.\nassert(length intersect <= length l) by apply pfilter_length.\nsymmetry; apply Nat.add_sub_eq_l, Nat.sub_add, H.\nQed.\n\nEnd Definition_using_pfilter.\n\nTheorem subtract_length_le_cons_r x a b :\n  length (subtract a (x :: b)) <= length (subtract a b).\nProof.\ninduction a; simpl. easy.\ndestruct (dec _), (in_dec _); simpl.\n2: apply le_S. 4: apply le_n_S. all: apply IHa.\nQed.\n\nTheorem length_subtract_le_incl_r a b c :\n  (∀x, In x b -> In x c) ->\n  length (subtract a c) <= length (subtract a b).\nProof.\ninduction a; simpl; intros. easy.\ndestruct (in_dec _), (in_dec _); simpl.\n2: apply le_S. 4: apply le_n_S.\n3: exfalso; apply n, H, i. all: apply IHa, H.\nQed.\n\nTheorem subtract_length_lt_cons_r x a b :\n  In x a -> ¬In x b ->\n  length (subtract a (x :: b)) < length (subtract a b).\nProof.\ninduction a; simpl; intros. easy.\ndestruct H, (dec _), (in_dec _); subst; simpl; try easy.\napply Nat.lt_succ_r, subtract_length_le_cons_r.\n1: apply Nat.lt_lt_succ_r. 3: apply Nat.lt_succ_r.\nall: apply IHa; easy.\nQed.\n\nEnd Intersection_and_subtraction.\n\nEnd List_constructions_using_decidability.\n\nArguments map2 {_ _ _}.\nArguments strip {_}.\nArguments pfilter {_}.\nArguments intersect {_}.\nArguments subtract {_}.\n\nEnd ListUtils.\nExport ListUtils.\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/B1_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.759398541622365}}
{"text": "From HoTT Require Import Spaces.Pos Spaces.Int.\nFrom HoTT Require Import Basics Types.\nFrom HoTT Require Import Spaces.Circle.\n\nLocal Open Scope int_scope.\n\nContext `{Univalence}.\n\n(*\nHere we defined the function helix from https://dl.acm.org/doi/abs/10.1145/3372885.3373825\nIn the HoTT book this is called code (Def. 8.1.1.)\n *)\n\nDefinition helix : Circle -> Set \n  := Circle_rec Set Int (path_universe int_succ).\n\n(*\nIf we input loop^n to winding, we get n. So it counts, how much we go around the circle.\n*)\n\nDefinition winding (p : (base = base)): Int\n  := transport helix p (zero).\n\n(*\nthe function winding number does not compute, if you check the following proofs you will get an error\n*)\n\nDefinition winding_at_3 : winding (loopexp loop 3) = 3.\nProof.\nreflexivity.\nAbort.\n\nDefinition winding_at_m1 : winding (loop^ @ loop @ loop^) = -1.\nProof.\nreflexivity.\nAbort.\n\n(*\nIn the following we use two theorems from https://github.com/HoTT/Coq-HoTT/blob/master/theories/Spaces/Circle.v \nto actually proof winding_at_3 and winding_at_m1\n*)\n\nTheorem transport_helix_loopV (z : Int)\n    : transport helix loop^ z = int_pred z.\nProof.\n    refine (transport_compose idmap helix loop^ z @ _).\n    rewrite ap_V.\n    unfold helix; rewrite Circle_rec_beta_loop.\n    rewrite <- (path_universe_V int_succ).\n    apply transport_path_universe.\nQed.\n\nTheorem Circle_encode_loopexp (z:Int)\n    : Circle_encode base (loopexp loop z) = z.\nProof.\n    destruct z as [n | | n]; unfold Circle_encode.\n    - induction n using pos_peano_ind; simpl in *.\n      + refine (moveR_transport_V _ loop _ _ _).\n        by symmetry; apply transport_Circle_code_loop.\n      + unfold loopexp_pos.\n        rewrite pos_peano_ind_beta_pos_succ.\n        rewrite transport_pp.\n        refine (moveR_transport_V _ loop _ _ _).\n        refine (_ @ (transport_Circle_code_loop _)^).\n        refine (IHn @ _^).\n        rewrite int_neg_pos_succ.\n        by rewrite int_succ_pred.\n    - reflexivity.\n    - induction n using pos_peano_ind; simpl in *.\n      + by apply transport_Circle_code_loop.\n      + unfold loopexp_pos.\n        rewrite pos_peano_ind_beta_pos_succ.\n        rewrite transport_pp.\n        refine (moveR_transport_p _ loop _ _ _).\n        refine (_ @ (transport_Circle_code_loopV _)^).\n        refine (IHn @ _^).\n        rewrite <- pos_add_1_r.\n        change (int_pred (int_succ (pos n)) = pos n).\n        apply int_pred_succ.\nQed.\n\nTheorem p: Circle_encode base (loopexp loop 3) = transport helix (loopexp loop 3) 0.\nProof.\nreflexivity.\nQed.\n\n(*\nNow we can proof, that winding actually computes the way we proposed.\n*)\n\n\nDefinition winding_at_3  : winding (loopexp loop 3) = 3.\nProof.\nunfold winding.\nrewrite <- p.\nrewrite Circle_encode_loopexp.\nreflexivity.\nQed.\n\nDefinition winding_at_m1 : winding (loop^ @ loop @ loop^) = -1.\nProof.\nunfold winding.\nrewrite concat_Vp.\nrewrite concat_1p.\nrewrite transport_helix_loopV.\nreflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "MaltyBlanket", "repo": "UnivalenceDoesNotCompute", "sha": "f658b2e600bbfb316e0b69c3d6ccbd9c4ea304a0", "save_path": "github-repos/coq/MaltyBlanket-UnivalenceDoesNotCompute", "path": "github-repos/coq/MaltyBlanket-UnivalenceDoesNotCompute/UnivalenceDoesNotCompute-f658b2e600bbfb316e0b69c3d6ccbd9c4ea304a0/WindingNumberInCoq_doesNotCompute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.759395900152052}}
{"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 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\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": "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/goal22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7593958961589733}}
{"text": "(* Require Export Ring. *)\nSet Implicit Arguments. \nSection mat.                                (* matrices. *)\n  Variables (A:Type)\n            (zero one : A) \n            (plus mult minus : A -> A -> A)\n            (sym : A -> A).\n  Notation \"0\" := zero.  Notation \"1\" := one.\n  Notation \"x + y\" := (plus x y).  \n  Notation \"x * y \" := (mult x y).\n  \n  \n  Structure M2 : Type := {c00 : A;  c01 : A;\n                          c10 : A;  c11 : A}.\n  \n  \n  Definition Zero2 : M2 := Build_M2 0 0 0 0.\n  Definition Id2 : M2 := Build_M2  1 0 0 1.\n  \n  Definition 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  \n  Definition M2_plus (m m' : M2) : M2 :=\n    @Build_M2 (c00 m + c00 m')\n              (c01 m + c01 m')\n              (c10 m + c10 m')\n              (c11 m + c11 m').\n  \n  Lemma M2_eq_intros :\n    forall m m':M2, c00 m = c00 m' ->\n                    c01 m = c01 m' ->\n                    c10 m = c10 m' ->\n                    c11 m = c11 m' -> m = m'.\n    destruct m;destruct m';simpl.\n    intros H H1 H2 H3;rewrite H ,H1, H2, H3;trivial.\n  Qed.\nEnd mat.                                    (* matrices. *)\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/gitcrc/Mat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7593958846086083}}
{"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\nDefinition nand(x y : bool):bool:=\nmatch x with\n|true => not y\n|false => true\nend.\n\nDefinition or(x y : bool):bool:=\nmatch x with\n|true => true\n|false => y\nend.\n\n\nDefinition nor(x y : bool):bool:=\nmatch x with\n|true => false\n|false => not y\nend.\n\n\nTheorem not_not: forall x:bool, not(not x) = x.\nProof.\nintros.\ndestruct x.\nsimpl. reflexivity.\nsimpl. reflexivity.\nQed.\n\nExample ex1 : (nor true false) = false.\nProof.\nintros.\nsimpl. reflexivity.\nQed.\n\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/NAND/Nand.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7593958807013035}}
{"text": "Require Import Arith Omega String.\n\nInductive exp : Set :=\n| Var : string -> exp\n| Const : nat -> exp\n| Plus : exp -> exp -> exp\n| Times : exp -> exp -> exp.\n\nFixpoint eval (e : exp) (f : string -> nat) : nat :=\n  match e with\n    | Var x => f x\n    | Const n => n\n    | Plus e1 e2 => eval e1 f + eval e2 f\n    | Times e1 e2 => eval e1 f * eval e2 f\n  end.\n\nFixpoint cfold (e : exp) : exp :=\n  match e with\n    | Var x => Var x\n    | Const n => Const n\n    | Plus e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold 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' := cfold e1 in\n      let e2' := cfold 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\nFixpoint cfold' (e : exp) : exp :=\n  match e with\n    | Var x => Var x\n    | Const n => Const n\n    | Plus e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold 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' := cfold e1 in\n      let e2' := cfold 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\nHint Extern 1 (_ = _) => omega.\n\nTheorem cfold_ok : forall f e, eval (cfold e) f = eval e f.\nProof.\n  induction e; simpl; intuition;\n  repeat match goal with\n           | [ |- context[match ?E with _ => _ end] ] =>\n             destruct E; simpl in *; subst; auto\n         end.\nQed.\n", "meta": {"author": "kolemannix", "repo": "oplss2015", "sha": "d2973dfbcb3bc345bec49841fb6c8bbf78d65a16", "save_path": "github-repos/coq/kolemannix-oplss2015", "path": "github-repos/coq/kolemannix-oplss2015/oplss2015-d2973dfbcb3bc345bec49841fb6c8bbf78d65a16/chlipala/Exercise1_adam_solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7593150693393882}}
{"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(** Números naturais: **)\n\nInductive natural :=\n| z: natural\n| s: natural -> natural.\n\n(** Igualdade proposicional. *)\nInductive eq_prop : natural -> natural -> Prop :=\n| eq_prop_refl: forall x, eq_prop x x.\n\nNotation \"A == B\" := (eq_prop A B) (at level 70).\n\n(** Disjunção: *)\nInductive disj (A B: Prop) : Set :=\n  | esq : A -> disj A B\n  | dir : B -> disj A B.\n\n(** Definimos o absurdo como um tipo indutivo vazio, isto é, sem construtores. Desta maneira podemos representar a negação de A como sendo (A -> falso). *)\nInductive falso: Prop :=.\n\n(** Exercício 2: *)\nLemma eq_sn_not_n: forall n, (eq_prop (s n) n) -> falso.\nProof.\n  induction n.\n  - intro.\n    inversion H.\n  - intro.\n    apply IHn.\n    inversion H.\n    exact H.\nQed.\n\n(** Exercício 1: Decidibilidade da igualdade. *)\nLemma eq_dec: forall (n m: natural), disj (eq_prop n m) (((eq_prop n m)-> falso)) .\nProof.\n  induction n.\n  - induction m.\n    + apply esq.\n      apply eq_prop_refl.\n    + destruct IHm.\n      * apply dir.\n        intro.\n        inversion H.\n      * apply dir.\n        intro.\n        inversion H.\n  - induction m.\n    + apply dir.\n      intro.\n      inversion H.\n    + destruct IHm.\n      * apply dir.\n        intro.\n        inversion H.\n        rewrite H2 in e.\n        inversion e.\n        apply (eq_sn_not_n m).\n        exact e.\n      * assert (disj (eq_prop n m) (eq_prop n m -> falso)).\n        { apply IHn. }\n        destruct H.\n         apply esq.\n           inversion e.\n           apply eq_prop_refl.\n         apply dir.\n         intro.\n         inversion H.\n         rewrite H2 in f0.\n         apply f0.\n         apply eq_prop_refl.\nDefined.\n\nLemma eq_s: forall n m, n == m -> (s n) == (s m).\nProof.\n  intros.\n  induction H.\n  apply eq_prop_refl.\nQed.\n\nLemma eq_comm: forall n m, n == m -> m == n.\nProof.\n  intros.\n  induction H.\n  apply eq_prop_refl.\nQed.\n\nLemma eq_trans: forall n m l, n == m -> m == l -> n == l.\nProof.\n  intros.\n  induction H0.\n  assumption.\nQed.\n\n(** Considere o predicado binário le que define a relação de \"menor ou igual que\".  *)\nInductive le : natural -> natural -> Prop :=\n| le_refl: forall n, le n n\n| le_n_sm: forall n m, le n m -> le n (s m).\n\n(** Exercício 3: *)\nLemma le_n_z: forall n, le n z -> (eq_prop n z).\nProof.\n  intros.\n  inversion H.\n  apply eq_prop_refl.\nQed.\n\n(** Exercício 4: O zero é menor ou igual que qualquer natural. *)\nLemma le_z: forall n, le z n.\nProof.\n  intros.\n  induction n.\n  apply le_refl.\n  apply le_n_sm.\n  apply IHn.\nQed.\n\n(** Exercício 5: *)\nLemma le_trans: forall n m k, le n m -> le m k -> le n k.\nProof.\n  intros.\n  induction H0.\n  - exact H.\n  - destruct IHle.\n    * exact H.\n    * inversion H0. subst.\n      + apply le_n_sm.\n        assumption.\n      + apply le_n_sm.\n        apply le_refl.\n    * apply le_n_sm.\n      apply le_n_sm.\n      assumption.\nQed.\n\n(** Exercício 6: *)\nLemma le_s: forall n m, le (s n) (s m) <-> le n m.\nProof.\n  intros.\n  split.\n  - intro.\n    inversion H. subst.\n    * apply le_refl.\n    * subst.\n      assert (le n (s n) -> le (s n) m -> le n m).\n      { intros. apply (le_trans n (s n) m). assumption. assumption. }\n      apply H0.\n      + apply le_n_sm.\n        apply le_refl.\n      + assumption.\n  - intro.\n    induction H.\n    + apply le_refl.\n    + apply le_n_sm.\n      assumption.\nQed.\n\n(** Exercício 7: *)\nLemma le_n_sm_eq: forall n m, (le n m -> falso) -> (le n (s m)) -> n == (s m).\nProof.\n  intros n m Hfalso Hle.\n  inversion Hle; subst.\n  - apply eq_prop_refl.\n  - apply falso_ind.\n    apply Hfalso.\n    assumption.\nQed.\n\n(** Exercício 8: *)\nLemma le_nm_falso: forall n m, (le n m -> falso) -> (le m n).\nProof.\n    induction n.\n    - intros m H.\n      assert (le z m).\n      { apply le_z. }\n      apply falso_ind.\n      apply H; assumption.\n    - intro m. case m.\n      + intro H.\n        apply le_n_sm.\n        apply le_z.\n      + intros n' Hfalso.        \n        apply le_s.\n        apply IHn.\n        intro Hle.\n        apply Hfalso.\n        apply le_s.\n        assumption.\nQed.\n\n(** Exercício 9: *)\nLemma le_sn_not_n: forall n, le (s n) n -> falso.\nProof.\n  induction n.\n  - intro H.\n    inversion H.\n  - intro H.\n    apply IHn.\n    inversion H; subst.\n      * assumption.\n      * apply le_trans with (s(s n)).\n        ** apply le_n_sm.\n           apply le_refl.\n        ** assumption.\nQed.\n\n(** Exercício 10: O predicado [le] é decidível. *)\nLemma le_dec: forall (n m: natural), disj (le n m) (le n m -> falso).\nProof.\n  induction n.\n  - intro m.\n    apply esq. \n    apply le_z.\n  - induction m.\n    + apply dir.\n      intro H.\n      inversion H.\n    + destruct IHm as [H1 | H2].\n      * apply esq.\n        apply le_n_sm.\n        assumption.\n      * destruct (IHn m).\n        ** apply esq.\n           apply le_s.\n           assumption.\n        ** apply dir.\n           intro H.\n           apply f.\n           apply le_s.\n           assumption.\nDefined. \n(**Defined**)", "meta": {"author": "Gastd", "repo": "fptt", "sha": "999472e6b0df8652a299f271f1676c8c0dc78256", "save_path": "github-repos/coq/Gastd-fptt", "path": "github-repos/coq/Gastd-fptt/fptt-999472e6b0df8652a299f271f1676c8c0dc78256/naturais20172.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7593150616819273}}
{"text": "Require Import Psatz.\nRequire Import String.\nRequire Import Program.\nRequire Export Complex.\nRequire Import List.\n\n\n(* TODO: Use matrix equality everywhere, declare equivalence relation *)\n(* TODO: Make all nat arguments to matrix lemmas implicit *)\n\nLocal Open Scope nat_scope.\n\n(* Some prelim lemmas. Should probably be moved *)\nLemma easy_sub : forall (n : nat), S n - 1 = n. Proof. lia. Qed.\n\n\nLemma Csum_simplify : forall (a b c d : C), a = b -> c = d -> (a + c = b + d)%C.\nProof. intros. \n       rewrite H, H0; easy.\nQed.\n\n\nLemma Cmult_simplify : forall (a b c d : C), a = b -> c = d -> (a * c = b * d)%C.\nProof. intros. \n       rewrite H, H0; easy.\nQed.\n\n\nLemma sqrt_1_unique : forall x, √ x = 1%R -> x = 1%R.\nProof. intros. assert (H' := H). unfold sqrt in H. destruct (Rcase_abs x).\n       - assert (H0: 1%R <> 0%R). { apply R1_neq_R0. }\n         rewrite H in H0. easy.\n       - rewrite <- (sqrt_def x). rewrite H'. lra. \n         apply Rge_le. easy.\nQed.\n\n\n(*******************************************)\n(** Matrix Definitions and Infrastructure **)\n(*******************************************)\n\nDeclare Scope matrix_scope.\nDelimit Scope matrix_scope with M.\nOpen Scope matrix_scope.\n\nLocal Open Scope nat_scope.\n\nDefinition Matrix (m n : nat) := nat -> nat -> C.\n\n(* Definition Vector (n : nat) := Matrix n 1. *)\n\nDefinition WF_Matrix {m n: nat} (A : Matrix m n) : Prop := \n  forall x y, x >= m \\/ y >= n -> A x y = C0. \n\nNotation Vector n := (Matrix n 1).\n\nNotation Square n := (Matrix n n).\n\n(* Showing equality via functional extensionality *)\nLtac prep_matrix_equality :=\n  let x := fresh \"x\" in \n  let y := fresh \"y\" in \n  apply functional_extensionality; intros x;\n  apply functional_extensionality; intros y.\n\n(* Matrix Equivalence *)\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 70) : matrix_scope.\n\nLemma mat_equiv_refl : forall m n (A : Matrix m n), mat_equiv A A.\nProof. unfold mat_equiv; reflexivity. Qed.\n\nLemma mat_equiv_eq : forall {m n : nat} (A B : Matrix m n),\n  WF_Matrix A -> \n  WF_Matrix B -> \n  A == B ->\n  A = B.\nProof.\n  intros m n A' B' WFA WFB Eq.\n  prep_matrix_equality.\n  unfold mat_equiv in Eq.\n  bdestruct (x <? m).\n  bdestruct (y <? n).\n  + apply Eq; easy.\n  + rewrite WFA, WFB; trivial; right; try lia.\n  + rewrite WFA, WFB; trivial; left; try lia.\nQed.\n\n(* Printing *)\n\nParameter print_C : C -> string.\nFixpoint print_row {m n} i j (A : Matrix m n) : string :=\n  match j with\n  | 0   => \"\\n\"\n  | S j' => print_C (A i j') ++ \", \" ++ print_row i j' A\n  end.\nFixpoint print_rows {m n} i j (A : Matrix m n) : string :=\n  match i with\n  | 0   => \"\"\n  | S i' => print_row i' n A ++ print_rows i' n A\n  end.\nDefinition print_matrix {m n} (A : Matrix m n) : string :=\n  print_rows m n A.\n\n(* 2D List Representation *)\n    \nDefinition list2D_to_matrix (l : list (list C)) : \n  Matrix (length l) (length (hd [] l)) :=\n  (fun x y => nth y (nth x l []) 0%R).\n\nLemma WF_list2D_to_matrix : forall m n li, \n    length li = m ->\n    (forall li', In li' li -> length li' = n)  ->\n    @WF_Matrix m n (list2D_to_matrix li).\nProof.\n  intros m n li L F x y [l | r].\n  - unfold list2D_to_matrix. \n    rewrite (nth_overflow _ []).\n    destruct y; easy.\n    rewrite L. apply l.\n  - unfold list2D_to_matrix. \n    rewrite (nth_overflow _ C0).\n    easy.\n    destruct (nth_in_or_default x li []) as [IN | DEF].\n    apply F in IN.\n    rewrite IN. apply r.\n    rewrite DEF.\n    simpl; lia.\nQed.\n\n(* Example *)\nDefinition M23 : Matrix 2 3 :=\n  fun x y => \n  match (x, y) with\n  | (0, 0) => 1%R\n  | (0, 1) => 2%R\n  | (0, 2) => 3%R\n  | (1, 0) => 4%R\n  | (1, 1) => 5%R\n  | (1, 2) => 6%R\n  | _ => C0\n  end.\n\nDefinition M23' : Matrix 2 3 := \n  list2D_to_matrix  \n  ([[RtoC 1; RtoC 2; RtoC 3];\n    [RtoC 4; RtoC 5; RtoC 6]]).\n\nLemma M23eq : M23 = M23'.\nProof.\n  unfold M23'.\n  compute.\n  prep_matrix_equality.\n  do 4 (try destruct x; try destruct y; simpl; trivial).\nQed.\n\n(*****************************)\n(** Operands and Operations **)\n(*****************************)\n\nDefinition Zero {m n : nat} : Matrix m n := fun x y => 0%R.\n\nDefinition I (n : nat) : Square n := \n  (fun x y => if (x =? y) && (x <? n) then C1 else C0).\n\n(* Optional coercion to scalar (should be limited to 1 × 1 matrices):\nDefinition to_scalar (m n : nat) (A: Matrix m n) : C := A 0 0.\nCoercion to_scalar : Matrix >-> C.\n *)\n\n\n  (*\nDefinition I (n : nat) : Square n := \n  (fun x y => if (x =? y) && (x <? n) then C1 else C0).\nDefinition I1 := I (2^0).\nNotation \"I  n\" := (I n) (at level 10).\n*)\n\n(* This isn't used, but is interesting *)\nDefinition I__inf := fun x y => if x =? y then C1 else C0.\nNotation \"I∞\" := I__inf : matrix_scope.\n\n(* sum to n exclusive *)\nFixpoint Csum (f : nat -> C) (n : nat) : C := \n  match n with\n  | 0 => C0\n  | S n' => (Csum f n' +  f n')%C\n  end.\n\nDefinition trace {n : nat} (A : Square n) := \n  Csum (fun x => A x x) n.\n\nDefinition scale {m n : nat} (r : C) (A : Matrix m n) : Matrix m n := \n  fun x y => (r * A x y)%C.\n\nDefinition dot {n : nat} (A : Vector n) (B : Vector n) : C :=\n  Csum (fun x => A x 0  * B x 0)%C n.\n\nDefinition Mplus {m n : nat} (A B : Matrix m n) : Matrix m n :=\n  fun x y => (A x y + B x y)%C.\n\nDefinition Mmult {m n o : nat} (A : Matrix m n) (B : Matrix n o) : Matrix m o := \n  fun x z => Csum (fun y => A x y * B y z)%C n.\n\n(* Only well-defined when o and p are non-zero *)\nDefinition kron {m n o p : nat} (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 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\n(* Kronecker of n copies of A *)\nFixpoint kron_n n {m1 m2} (A : Matrix m1 m2) : Matrix (m1^n) (m2^n) :=\n  match n with\n  | 0    => I 1\n  | S n' => kron (kron_n n' A) A\n  end.\n\n(* Kronecker product of a list *)\nFixpoint big_kron {m n} (As : list (Matrix m n)) : \n  Matrix (m^(length As)) (n^(length As)) := \n  match As with\n  | [] => I 1\n  | A :: As' => kron A (big_kron As')\n  end.\n\n(* Product of n copies of A *)\nFixpoint Mmult_n n {m} (A : Square m) : Square m :=\n  match n with\n  | 0    => I m\n  | S n' => Mmult A (Mmult_n n' A)\n  end.\n\n(* Indexed sum over matrices *)\nFixpoint Msum {m1 m2} n (f : nat -> Matrix m1 m2) : Matrix m1 m2 :=\n  match n with\n  | 0 => Zero\n  | S n' => Mplus (Msum n' f) (f n')\nend.\n\nInfix \"∘\" := dot (at level 40, left associativity) : matrix_scope.\nInfix \".+\" := Mplus (at level 50, left associativity) : matrix_scope.\nInfix \".*\" := scale (at level 40, left associativity) : matrix_scope.\nInfix \"×\" := Mmult (at level 40, left associativity) : matrix_scope.\nInfix \"⊗\" := kron (at level 40, left associativity) : matrix_scope.\nInfix \"≡\" := mat_equiv (at level 70) : matrix_scope.\nNotation \"A ⊤\" := (transpose A) (at level 0) : matrix_scope. \nNotation \"A †\" := (adjoint A) (at level 0) : matrix_scope. \nNotation \"Σ^ n f\" := (Csum f n) (at level 60) : matrix_scope.\nNotation \"n ⨂ A\" := (kron_n n A) (at level 30, no associativity) : matrix_scope.\nNotation \"⨂ A\" := (big_kron A) (at level 60): matrix_scope.\nNotation \"n ⨉ A\" := (Mmult_n n A) (at level 30, no associativity) : matrix_scope.\nHint Unfold Zero I trace dot Mplus scale Mmult kron mat_equiv transpose \n            adjoint : U_db.\n  \nLtac destruct_m_1 :=\n  match goal with\n  | [ |- context[match ?x with \n                 | 0   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  end.\nLtac destruct_m_eq := repeat (destruct_m_1; simpl).\n\nLtac lma := \n  autounfold with U_db;\n  prep_matrix_equality;\n  destruct_m_eq; \n  lca.\n\n\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;\n  let i := fresh \"i\" in \n  let j := fresh \"j\" in \n  let Hi := fresh \"Hi\" in \n  let Hj := fresh \"Hj\" in \n  intros i j Hi Hj; try solve_end;\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\n\n\nLtac lma' :=\n  apply mat_equiv_eq;\n  repeat match goal with\n  | [ |- WF_Matrix (?A) ]  => auto with wf_db (* (try show_wf) *)\n  | [ |- mat_equiv (?A) (?B) ] => by_cell; try lca                 \n  end.\n\n\n\n\n(******************************)\n(** Proofs about finite sums **)\n(******************************)\n\nLocal Close Scope nat_scope.\n\nLemma Csum_0 : forall f n, (forall x, f x = C0) -> Csum f n = 0. \nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn, H. \n    lca.\nQed.\n\nLemma Csum_1 : forall f n, (forall x, f x = C1) -> Csum f n = INR n. \nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn, H. \n    destruct n; lca.    \nQed.\n\nLemma Csum_constant : forall c n, Csum (fun x => c) n = INR n * c.\nProof.\n  intros c n.\n  induction n.\n  + simpl; lca.\n  + simpl.\n    rewrite IHn.\n    destruct n; lca.\nQed.\n\nLemma Csum_eq : forall f g n, f = g -> Csum f n = Csum g n.\nProof. intros f g n H. subst. reflexivity. Qed.\n\nLemma Csum_0_bounded : forall f n, (forall x, (x < n)%nat -> f x = C0) -> Csum f n = 0. \nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl.\n    rewrite IHn, H. \n    lca.\n    lia.\n    intros.\n    apply H.\n    lia.\nQed.\n\nLemma Csum_eq_bounded : forall f g n, (forall x, (x < n)%nat -> f x = g x) -> Csum f n = Csum g n.\nProof. \n  intros f g n H. \n  induction n.\n  + simpl. reflexivity.\n  + simpl. \n    rewrite H by lia.\n    rewrite IHn by (intros; apply H; lia).\n    reflexivity.\nQed.\n\nLemma Csum_plus : forall f g n, Csum (fun x => f x + g x) n = Csum f n + Csum g n.\nProof.\n  intros f g n.\n  induction n.\n  + simpl. lca.\n  + simpl. rewrite IHn. lca.\nQed.\n\nLemma Csum_mult_l : forall c f n, c * Csum f n = Csum (fun x => c * f x) n.\nProof.\n  intros c f n.\n  induction n.\n  + simpl; lca.\n  + simpl.\n    rewrite Cmult_plus_distr_l.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nLemma Csum_mult_r : forall c f n, Csum f n * c = Csum (fun x => f x * c) n.\nProof.\n  intros c f n.\n  induction n.\n  + simpl; lca.\n  + simpl.\n    rewrite Cmult_plus_distr_r.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nLemma Csum_conj_distr : forall f n, (Csum f n) ^* = Csum (fun x => (f x)^*) n.\nProof. \n  intros f n.\n  induction n.\n  + simpl; lca.\n  + simpl. \n    rewrite Cconj_plus_distr.\n    rewrite IHn.\n    reflexivity.\nQed.\n    \nLemma Csum_extend_r : forall n f, Csum f n + f n = Csum f (S n).\nProof. reflexivity. Qed.\n\nLemma Csum_extend_l : forall n f, f O + Csum (fun x => f (S x)) n = Csum f (S n).\nProof.\n  intros n f.\n  induction n.\n  + simpl; lca.\n  + simpl.\n    rewrite Cplus_assoc.\n    rewrite IHn.\n    simpl.\n    reflexivity.\nQed.\n\nLemma Csum_unique : forall k (f : nat -> C) n, \n  (exists x, (x < n)%nat /\\ f x = k /\\ (forall x', x <> x' -> f x' = 0)) ->\n  Csum f n = k.\nProof.                    \n  intros k f n [x [L [Eq Unique]]].\n  induction n; try lia.\n  Search Csum.\n  rewrite <- Csum_extend_r.\n  destruct (Nat.eq_dec x n).\n  - subst. \n    rewrite Csum_0_bounded.\n    lca.\n    intros.\n    apply Unique.\n    lia.\n  - rewrite Unique by easy.\n    Csimpl.\n    apply IHn.\n    lia.\nQed.    \n\nLemma Csum_sum : forall m n f, Csum f (m + n) = \n                          Csum f m + Csum (fun x => f (m + x)%nat) n. \nProof.    \n  intros m n f.\n  induction m.\n  + simpl. rewrite Cplus_0_l. reflexivity. \n  + simpl.\n    rewrite IHm.\n    repeat rewrite <- Cplus_assoc.\n    remember (fun y => f (m + y)%nat) as g.\n    replace (f m) with (g O) by (subst; rewrite plus_0_r; reflexivity).\n    replace (f (m + n)%nat) with (g n) by (subst; reflexivity).\n    replace (Csum (fun x : nat => f (S (m + x))) n) with\n            (Csum (fun x : nat => g (S x)) n).\n    2:{ apply Csum_eq. subst. apply functional_extensionality.\n    intros; rewrite <- plus_n_Sm. reflexivity. }\n    rewrite Csum_extend_l.\n    rewrite Csum_extend_r.\n    reflexivity.\nQed.\n\nLemma Csum_product : forall m n f g, n <> O ->\n                              Csum f m * Csum g n = \n                              Csum (fun x => f (x / n)%nat * g (x mod n)%nat) (m * n). \nProof.\n  intros.\n  induction m.\n  + simpl; lca.\n  + simpl.      \n    rewrite Cmult_plus_distr_r.\n    rewrite IHm. clear IHm.\n    rewrite Csum_mult_l.    \n    remember ((fun x : nat => f (x / n)%nat * g (x mod n)%nat)) as h.\n    replace (Csum (fun x : nat => f m * g x) n) with\n            (Csum (fun x : nat => h ((m * n) + x)%nat) n). \n    2:{\n      subst.\n      apply Csum_eq_bounded.\n      intros x Hx.\n      rewrite Nat.div_add_l by assumption.\n      rewrite Nat.div_small; trivial.\n      rewrite plus_0_r.\n      rewrite Nat.add_mod by assumption.\n      rewrite Nat.mod_mul by assumption.\n      rewrite plus_0_l.\n      repeat rewrite Nat.mod_small; trivial. }\n    rewrite <- Csum_sum.\n    rewrite plus_comm.\n    reflexivity.\nQed.\n\nLemma Csum_ge_0 : forall f n, (forall x, 0 <= fst (f x)) -> 0 <= fst (Csum f n).\nProof.\n  intros f n H.\n  induction n.\n  - simpl. lra. \n  - simpl in *.\n    rewrite <- Rplus_0_r at 1.\n    apply Rplus_le_compat; easy.\nQed.\n\n\nLemma Csum_gt_0 : forall f n, (forall x, 0 <= fst (f x)) -> \n                              (exists y : nat, (y < n)%nat /\\ 0 < fst (f y)) ->\n                              0 < fst (Csum f n).\nProof.\n  intros f n H [y [H0 H1]].\n  induction n.\n  - simpl. lia. \n  - simpl in *.\n    bdestruct (y <? n)%nat; bdestruct (y =? n)%nat; try lia. \n    + assert (H' : 0 <= fst (f n)). { apply H. } \n      apply IHn in H2. lra. \n    + apply (Csum_ge_0 f n) in H.\n      rewrite H3 in H1.\n      lra. \nQed.\n\n\n\nLemma Csum_member_le : forall (f : nat -> C) (n : nat), (forall x, 0 <= fst (f x)) -> \n                      (forall x, (x < n)%nat -> fst (f x) <= fst (Csum f n)).\nProof.\n  intros f.\n  induction n.\n  - intros H x Lt. inversion Lt.\n  - intros H x Lt.\n    bdestruct (Nat.ltb x n).\n    + simpl.\n      rewrite <- Rplus_0_r at 1.\n      apply Rplus_le_compat.\n      apply IHn; easy.\n      apply H.\n    + assert (E: x = n) by lia.\n      rewrite E.\n      simpl.\n      rewrite <- Rplus_0_l at 1.\n      apply Rplus_le_compat. \n      apply Csum_ge_0; easy.\n      lra.\nQed.      \n\nLemma Csum_squeeze : forall (f : nat -> C) (n : nat), \n  (forall x, (0 <= fst (f x)))%R -> Csum f n = C0 ->\n  (forall x, (x < n)%nat -> fst (f x) = fst C0).\nProof. intros. \n       assert (H2 : (forall x, (x < n)%nat -> (fst (f x) <= 0)%R)).\n       { intros. \n         replace 0%R with (fst (C0)) by easy.\n         rewrite <- H0.\n         apply Csum_member_le; try easy. }\n       assert (H3 : forall r : R, (r <= 0 -> 0 <= r -> r = 0)%R). \n       intros. lra. \n       simpl. \n       apply H3.\n       apply H2; easy.\n       apply H.\nQed.\n\n\nLemma Csum_snd_0 : forall n f, (forall x, snd (f x) = 0) -> snd (Csum f n) = 0.       \nProof. intros. induction n.\n       - reflexivity.\n       - rewrite <- Csum_extend_r.\n         unfold Cplus. simpl. rewrite H, IHn.\n         lra.\nQed.\n\n\nLemma Csum_comm : forall f g n, \n    (forall c1 c2 : C, g (c1 + c2) = g c1 + g c2) ->\n    Csum (fun x => g (f x)) n = g (Csum f n).\nProof. intros. induction n as [| n'].\n       - simpl.\n         assert (H0 : g 0 - g 0 = g 0 + g 0 - g 0). \n         { rewrite <- H. rewrite Cplus_0_r. easy. }\n         unfold Cminus in H0. \n         rewrite <- Cplus_assoc in H0.\n         rewrite Cplus_opp_r in H0.\n         rewrite Cplus_0_r in H0. \n         apply H0. \n       - do 2 (rewrite <- Csum_extend_r).\n         rewrite IHn'.\n         rewrite H.\n         reflexivity.\nQed.\n\n\nLocal Open Scope nat_scope.\n\nLemma Csum_double_sum : forall (f : nat -> nat -> C) (n m : nat),\n    Csum (fun x => (Csum (fun y => f x y) n)) m = Csum (fun z => f (z / n) (z mod n)) (n * m).\nProof. induction m as [| m'].\n       - rewrite Nat.mul_0_r.\n         easy.\n       - rewrite Nat.mul_succ_r.\n         rewrite <- Csum_extend_r.\n         rewrite Csum_sum.\n         apply Csum_simplify; try easy.\n         apply Csum_eq_bounded; intros.\n         rewrite mult_comm.\n         rewrite Nat.div_add_l; try lia. \n         rewrite (plus_comm (m' * n)).\n         rewrite Nat.mod_add; try lia.\n         destruct (Nat.mod_small_iff x n) as [_ HD]; try lia.\n         destruct (Nat.div_small_iff x n) as [_ HA]; try lia.\n         rewrite HD, HA; try lia.\n         rewrite Nat.add_0_r.\n         easy.\nQed.\n         \n\nLemma Csum_extend_double : forall (n m : nat) (f : nat -> nat -> C),\n  (Csum (fun i => Csum (fun j => f i j) (S m)) (S n)) = \n  ((Csum (fun i => Csum (fun j => f i j) m) n) + (Csum (fun j => f n j) m) + \n                      (Csum (fun i => f i m) n) + f n m)%C.\nProof. intros. \n       rewrite <- Csum_extend_r.\n       assert (H' : forall a b c d, (a + b + c + d = (a + c) + (b + d))%C). \n       { intros. lca. }\n       rewrite H'.\n       apply Csum_simplify; try easy.\n       rewrite <- Csum_plus.\n       apply Csum_eq_bounded; intros. \n       easy.\nQed.\n\nLemma Csum_rearrange : forall (n : nat) (f g : nat -> nat -> C),\n  (forall x y, x <= y -> f x y = -C1 * g (S y) x)%C ->\n  (forall x y, y <= x -> f (S x) y = -C1 * g y x)%C ->\n  Csum (fun i => Csum (fun j => f i j) n) (S n) = \n  (-C1 * (Csum (fun i => Csum (fun j => g i j) n) (S n)))%C.\nProof. induction n as [| n'].\n       - intros. lca. \n       - intros. \n         do 2 rewrite Csum_extend_double.\n         rewrite (IHn' f g); try easy.\n         repeat rewrite Cmult_plus_distr_l.\n         repeat rewrite <- Cplus_assoc.\n         apply Csum_simplify; try easy.\n         assert (H' : forall a b c, (a + (b + c) = (a + c) + b)%C). \n         intros. lca. \n         do 2 rewrite H'.\n         rewrite <- Cmult_plus_distr_l.\n         do 2 rewrite Csum_extend_r. \n         do 2 rewrite Csum_mult_l.\n         rewrite Cplus_comm.\n         apply Csum_simplify.\n         all : apply Csum_eq_bounded; intros. \n         apply H; lia. \n         apply H0; lia. \nQed.\n         \n(**********************************)\n(** Proofs about Well-Formedness **)\n(**********************************)\n\n\n\nLemma WF_Matrix_dim_change : forall (m n m' n' : nat) (A : Matrix m n),\n  m = m' ->\n  n = n' ->\n  @WF_Matrix m n A ->\n  @WF_Matrix m' n' A.\nProof. intros. subst. easy. Qed.\n\nLemma WF_Zero : forall m n : nat, WF_Matrix (@Zero m n).\nProof. intros m n. unfold WF_Matrix. reflexivity. Qed.\n\nLemma WF_I : forall n : nat, WF_Matrix (I n). \nProof. \n  unfold WF_Matrix, I. intros n x y H. simpl.\n  destruct H; bdestruct (x =? y); bdestruct (x <? n); trivial; lia.\nQed.\n\nLemma WF_I1 : WF_Matrix (I 1). Proof. apply WF_I. Qed.\n\nLemma WF_scale : forall {m n : nat} (r : C) (A : Matrix m n), \n  WF_Matrix A -> WF_Matrix (scale r A).\nProof.\n  unfold WF_Matrix, scale.\n  intros m n r A H x y H0. simpl.\n  rewrite H; trivial.\n  rewrite Cmult_0_r.\n  reflexivity.\nQed.\n\nLemma WF_plus : forall {m n} (A B : Matrix m n), \n  WF_Matrix A -> WF_Matrix B -> WF_Matrix (A .+ B).\nProof.\n  unfold WF_Matrix, Mplus.\n  intros m n A B H H0 x y H1. simpl.\n  rewrite H, H0; trivial.\n  rewrite Cplus_0_l.\n  reflexivity.\nQed.\n\nLemma WF_mult : forall {m n o : nat} (A : Matrix m n) (B : Matrix n o), \n  WF_Matrix A -> WF_Matrix B -> WF_Matrix (A × B).\nProof.\n  unfold WF_Matrix, Mmult.\n  intros m n o A B H H0 x y D. simpl.\n  apply Csum_0.\n  destruct D; intros z.\n  + rewrite H; [lca | auto].\n  + rewrite H0; [lca | auto].\nQed.\n\nLemma WF_kron : forall {m n o p q r : nat} (A : Matrix m n) (B : Matrix o p), \n                  q = m * o -> r = n * p -> \n                  WF_Matrix A -> WF_Matrix B -> @WF_Matrix q r (A ⊗ B).\nProof.\n  unfold WF_Matrix, kron.\n  intros m n o p q r A B Nn No H H0 x y H1. subst.\n  bdestruct (o =? 0). rewrite H0; [lca|lia]. \n  bdestruct (p =? 0). rewrite H0; [lca|lia]. \n  rewrite H.\n  rewrite Cmult_0_l; reflexivity.\n  destruct H1.\n  unfold ge in *.\n  left. \n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\n  right.\n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\nQed. \n\n\n(* More succinct but sometimes doesn't succeed \nLemma WF_kron : forall {m n o p: nat} (A : Matrix m n) (B : Matrix o p), \n                  WF_Matrix A -> WF_Matrix B -> WF_Matrix (A ⊗ B).\nProof.\n  unfold WF_Matrix, kron.\n  intros m n o p A B WFA WFB x y H.\n  bdestruct (o =? 0). rewrite WFB; [lca|lia]. \n  bdestruct (p =? 0). rewrite WFB; [lca|lia].  \n  rewrite WFA.\n  rewrite Cmult_0_l; reflexivity.\n  destruct H.\n  unfold ge in *.\n  left. \n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\n  right.\n  apply Nat.div_le_lower_bound; trivial.\n  rewrite Nat.mul_comm.\n  assumption.\nQed. \n*)\n\nLemma WF_transpose : forall {m n : nat} (A : Matrix m n), \n                     WF_Matrix A -> WF_Matrix A⊤. \nProof. unfold WF_Matrix, transpose. intros m n A H x y H0. apply H. \n       destruct H0; auto. Qed.\n\nLemma WF_adjoint : forall {m n : nat} (A : Matrix m n), \n      WF_Matrix A -> WF_Matrix A†. \nProof. unfold WF_Matrix, adjoint, Cconj. intros m n A H x y H0. simpl. \nrewrite H. lca. lia. Qed.\n\nLemma WF_outer_product : forall {n} (u v : Vector n),\n    WF_Matrix u ->\n    WF_Matrix v ->\n    WF_Matrix (outer_product u v).\nProof. intros. apply WF_mult; [|apply WF_adjoint]; assumption. Qed.\n\nLemma WF_kron_n : forall n {m1 m2} (A : Matrix m1 m2),\n   WF_Matrix A ->  WF_Matrix (kron_n n A).\nProof.\n  intros.\n  induction n; simpl.\n  - apply WF_I.\n  - apply WF_kron; try lia; assumption. \nQed.\n\nLemma WF_big_kron : forall n m (l : list (Matrix m n)) (A : Matrix m n), \n                        (forall i, WF_Matrix (nth i l A)) ->\n                         WF_Matrix (⨂ l). \nProof.                         \n  intros n m l A H.\n  induction l.\n  - simpl. apply WF_I.\n  - simpl. apply WF_kron; trivial. apply (H O).\n    apply IHl. intros i. apply (H (S i)).\nQed.\n\nLemma WF_Mmult_n : forall n {m} (A : Square m),\n   WF_Matrix A -> WF_Matrix (Mmult_n n A).\nProof.\n  intros.\n  induction n; simpl.\n  - apply WF_I.\n  - apply WF_mult; assumption. \nQed.\n\nLemma WF_Msum : forall d1 d2 n (f : nat -> Matrix d1 d2), \n  (forall i, (i < n)%nat -> WF_Matrix (f i)) -> \n  WF_Matrix (Msum n f).\nProof.\n  intros. \n  induction n; simpl.\n  - apply WF_Zero.\n  - apply WF_plus; auto.\nQed.\n\nLocal Close Scope nat_scope.\n\n(***************************************)\n(* Tactics for showing well-formedness *)\n(***************************************)\n\nLocal Open Scope nat.\nLocal Open Scope R.\nLocal Open Scope C.\n\n(*\nLtac show_wf := \n  repeat match goal with\n  | [ |- WF_Matrix _ _ (?A × ?B) ]  => apply WF_mult \n  | [ |- WF_Matrix _ _ (?A .+ ?B) ] => apply WF_plus \n  | [ |- WF_Matrix _ _ (?p .* ?B) ] => apply WF_scale\n  | [ |- WF_Matrix _ _ (?A ⊗ ?B) ]  => apply WF_kron\n  | [ |- WF_Matrix _ _ (?A⊤) ]      => apply WF_transpose \n  | [ |- WF_Matrix _ _ (?A†) ]      => apply WF_adjoint \n  | [ |- WF_Matrix _ _ (I _) ]     => apply WF_I\n  end;\n  trivial;\n  unfold WF_Matrix;\n  let x := fresh \"x\" in\n  let y := fresh \"y\" in\n  let H := fresh \"H\" in\n  intros x y [H | H];\n    repeat (destruct x; try reflexivity; try lia);\n    repeat (destruct y; try reflexivity; try lia).\n*)\n\n(* Much less awful *)\nLtac show_wf := \n  unfold WF_Matrix;\n  let x := fresh \"x\" in\n  let y := fresh \"y\" in\n  let H := fresh \"H\" in\n  intros x y [H | H];\n  apply le_plus_minus in H; rewrite H;\n  cbv;\n  destruct_m_eq;\n  try lca.\n\n(* Create HintDb wf_db. *)\nHint Resolve WF_Zero WF_I WF_I1 WF_mult WF_plus WF_scale WF_transpose \n     WF_adjoint WF_outer_product WF_big_kron WF_kron_n WF_kron \n     WF_Mmult_n WF_Msum : wf_db.\nHint Extern 2 (_ = _) => unify_pows_two : wf_db.\n\n(* Hint Resolve WF_Matrix_dim_change : wf_db. *)\n\n\n(** Basic Matrix Lemmas **)\n\nLemma WF0_Zero_l :forall (n : nat) (A : Matrix 0%nat n), WF_Matrix A -> A = Zero.\nProof.\n  intros n A WFA.\n  prep_matrix_equality.\n  rewrite WFA.\n  reflexivity.\n  lia.\nQed.\n\nLemma WF0_Zero_r :forall (n : nat) (A : Matrix n 0%nat), WF_Matrix A -> A = Zero.\nProof.\n  intros n A WFA.\n  prep_matrix_equality.\n  rewrite WFA.\n  reflexivity.\n  lia.\nQed.\n\nLemma WF0_Zero :forall (A : Matrix 0%nat 0%nat), WF_Matrix A -> A = Zero.\nProof.\n  apply WF0_Zero_l.\nQed.\n\nLemma I0_Zero : I 0 = Zero.\nProof.\n  apply WF0_Zero.\n  apply WF_I.\nQed.\n\nLemma trace_plus_dist : forall (n : nat) (A B : Square n), \n    trace (A .+ B) = (trace A + trace B)%C. \nProof. \n  intros.\n  unfold trace, Mplus.\n  induction n.\n  - simpl. lca.\n  - simpl. rewrite IHn. lca.\nQed.\n\nLemma trace_mult_dist : forall n p (A : Square n), trace (p .* A) = (p * trace A)%C. \nProof.\n  intros.\n  unfold trace, scale.\n  induction n.\n  - simpl. lca.\n  - simpl. rewrite IHn. lca.\nQed.\n\nLemma Mplus_0_l : forall (m n : nat) (A : Matrix m n), Zero .+ A = A.\nProof. intros. lma. Qed.\n\nLemma Mplus_0_r : forall (m n : nat) (A : Matrix m n), A .+ Zero = A.\nProof. intros. lma. Qed.\n    \nLemma Mmult_0_l : forall (m n o : nat) (A : Matrix n o), @Zero m n × A = Zero.\nProof.\n  intros m n o A. \n  unfold Mmult, Zero.\n  prep_matrix_equality.\n  induction n.\n  + simpl. reflexivity.\n  + simpl in *.\n    autorewrite with C_db.\n    apply IHn.\nQed.    \n\nLemma Mmult_0_r : forall (m n o : nat) (A : Matrix m n), A × @Zero n o = Zero.\nProof.\n  intros m n o A. \n  unfold Zero, Mmult.\n  prep_matrix_equality.\n  induction n.\n  + simpl. reflexivity.\n  + simpl. \n    autorewrite with C_db.\n    apply IHn.\nQed.\n\n(* using <= because our form Csum is exclusive. *)\nLemma Mmult_1_l_gen: forall (m n : nat) (A : Matrix m n) (x z k : nat), \n  (k <= m)%nat ->\n  ((k <= x)%nat -> Csum (fun y : nat => I m x y * A y z) k = 0) /\\\n  ((k > x)%nat -> Csum (fun y : nat => I m x y * A y z) k = A x z).\nProof.  \n  intros m n A x z k B.\n  induction k.\n  * simpl. split. reflexivity. lia.\n  * destruct IHk as [IHl IHr]. lia.  \n    split.\n    + intros leSkx.\n      simpl.\n      unfold I.\n      bdestruct (x =? k); try lia.\n      autorewrite with C_db.\n      apply IHl.\n      lia.\n    + intros gtSkx.\n      simpl in *.\n      unfold I in *.\n      bdestruct (x =? k); bdestruct (x <? m); subst; try lia.\n      rewrite IHl by lia; simpl; lca.\n      rewrite IHr by lia; simpl; lca.\nQed.\n\nLemma Mmult_1_l_mat_eq : forall (m n : nat) (A : Matrix m n), I m × A == A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold Mmult.\n  edestruct (@Mmult_1_l_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  unfold get.\n  apply Hr.\n  simpl in *.\n  lia.\nQed.  \n\n\nLemma Mmult_1_l: forall (m n : nat) (A : Matrix m n), \n  WF_Matrix A -> I m × A = A.\nProof.\n  intros m n A H.\n  apply mat_equiv_eq; trivial.\n  auto with wf_db.\n  apply Mmult_1_l_mat_eq.\nQed.\n\nLemma Mmult_1_r_gen: forall (m n : nat) (A : Matrix m n) (x z k : nat), \n  (k <= n)%nat ->\n  ((k <= z)%nat -> Csum (fun y : nat => A x y * (I n) y z) k = 0) /\\\n  ((k > z)%nat -> Csum (fun y : nat => A x y * (I n) y z) k = A x z).\nProof.  \n  intros m n A x z k B.\n  induction k.\n  simpl. split. reflexivity. lia.\n  destruct IHk as [IHl IHr].\n  lia.\n  split.\n  + intros leSkz.\n    simpl in *.\n    unfold I.\n    bdestruct (k =? z); try lia.\n    autorewrite with C_db.\n    apply IHl; lia.\n  + intros gtSkz.\n    simpl in *.\n    unfold I in *.\n    bdestruct (k =? z); subst.\n    - bdestruct (z <? n); try lia.\n      rewrite IHl by lia; lca.\n    - rewrite IHr by lia; simpl; lca.\nQed.\n\nLemma Mmult_1_r_mat_eq : forall (m n : nat) (A : Matrix m n), A × I n ≡ A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold Mmult.\n  edestruct (@Mmult_1_r_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  unfold get; simpl.\n  apply Hr.\n  lia.\nQed.  \n\nLemma Mmult_1_r: forall (m n : nat) (A : Matrix m n), \n  WF_Matrix A -> A × I n = A.\nProof.\n  intros m n A H.\n  apply mat_equiv_eq; trivial.\n  auto with wf_db.\n  apply Mmult_1_r_mat_eq.\nQed.\n\n(* Cool facts about I∞, not used in the development *) \nLemma Mmult_inf_l : forall(m n : nat) (A : Matrix m n),\n  WF_Matrix A -> I∞ × A = A.\nProof. \n  intros m n A H.\n  prep_matrix_equality.\n  unfold Mmult.\n  edestruct (@Mmult_1_l_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  bdestruct (m <=? x).\n  rewrite H by auto.\n  apply Csum_0_bounded.\n  intros z L. \n  unfold I__inf, I.\n  bdestruct (x =? z). lia. lca.  \n  unfold I__inf, I in *.\n  erewrite Csum_eq.\n  apply Hr.\n  assumption.\n  bdestruct (x <? m); [|lia]. \n  apply functional_extensionality. intros. rewrite andb_true_r. reflexivity.\nQed.\n\nLemma Mmult_inf_r : forall(m n : nat) (A : Matrix m n),\n  WF_Matrix A -> A × I∞ = A.\nProof. \n  intros m n A H.\n  prep_matrix_equality.\n  unfold Mmult.\n  edestruct (@Mmult_1_r_gen m n) as [Hl Hr].\n  apply Nat.le_refl.\n  bdestruct (n <=? y).\n  rewrite H by auto.\n  apply Csum_0_bounded.\n  intros z L. \n  unfold I__inf, I.\n  bdestruct (z =? y). lia. lca.  \n  unfold I__inf, I in *.\n  erewrite Csum_eq.\n  apply Hr.\n  assumption.\n  apply functional_extensionality. intros z. \n  bdestruct (z =? y); bdestruct (z <? n); simpl; try lca; try lia. \nQed.\n\nLemma kron_0_l : forall (m n o p : nat) (A : Matrix o p), \n  @Zero m n ⊗ A = Zero.\nProof.\n  intros m n o p A.\n  prep_matrix_equality.\n  unfold Zero, kron.\n  rewrite Cmult_0_l.\n  reflexivity.\nQed.\n\nLemma kron_0_r : forall (m n o p : nat) (A : Matrix m n), \n   A ⊗ @Zero o p = Zero.\nProof.\n  intros m n o p A.\n  prep_matrix_equality.\n  unfold Zero, kron.\n  rewrite Cmult_0_r.\n  reflexivity.\nQed.\n\nLemma kron_1_r : forall (m n : nat) (A : Matrix m n), A ⊗ I 1 = A.\nProof.\n  intros m n A.\n  prep_matrix_equality.\n  unfold I, kron.\n  rewrite 2 Nat.div_1_r.\n  rewrite 2 Nat.mod_1_r.\n  simpl.\n  autorewrite with C_db.\n  reflexivity.\nQed.\n\n(* This side is more limited *)\nLemma kron_1_l : forall (m n : nat) (A : Matrix m n), \n  WF_Matrix A -> I 1 ⊗ A = A.\nProof.\n  intros m n A WF.\n  prep_matrix_equality.\n  unfold kron.\n  unfold I, kron.\n  bdestruct (m =? 0). rewrite 2 WF by lia. lca. \n  bdestruct (n =? 0). rewrite 2 WF by lia. lca.\n  bdestruct (x / m <? 1); rename H1 into Eq1.\n  bdestruct (x / m =? y / n); rename H1 into Eq2; simpl.\n  + assert (x / m = 0)%nat by lia. clear Eq1. rename H1 into Eq1.\n    rewrite Eq1 in Eq2.     \n    symmetry in Eq2.\n    rewrite Nat.div_small_iff in Eq2 by lia.\n    rewrite Nat.div_small_iff in Eq1 by lia.\n    rewrite 2 Nat.mod_small; trivial.\n    lca.\n  + assert (x / m = 0)%nat by lia. clear Eq1.\n    rewrite H1 in Eq2. clear H1.\n    assert (y / n <> 0)%nat by lia. clear Eq2.\n    rewrite Nat.div_small_iff in H1 by lia.\n    rewrite Cmult_0_l.\n    destruct WF with (x := x) (y := y). lia.\n    reflexivity.\n  + rewrite andb_false_r.\n    assert (x / m <> 0)%nat by lia. clear Eq1.\n    rewrite Nat.div_small_iff in H1 by lia.\n    rewrite Cmult_0_l.\n    destruct WF with (x := x) (y := y). lia.\n    reflexivity.\nQed.\n\nTheorem transpose_involutive : forall (m n : nat) (A : Matrix m n), (A⊤)⊤ = A.\nProof. reflexivity. Qed.\n\nTheorem adjoint_involutive : forall (m n : nat) (A : Matrix m n), A†† = A.\nProof. intros. lma. Qed.  \n\nLemma id_transpose_eq : forall n, (I n)⊤ = (I n).\nProof.\n  intros n. unfold transpose, I.\n  prep_matrix_equality.\n  bdestruct (y =? x); bdestruct (x =? y); bdestruct (y <? n); bdestruct (x <? n);\n    trivial; lia.\nQed.\n\nLemma zero_transpose_eq : forall m n, (@Zero m n)⊤ = @Zero m n.\nProof. reflexivity. Qed.\n\nLemma id_adjoint_eq : forall n, (I n)† = (I n).\nProof.\n  intros n.\n  unfold adjoint, I.\n  prep_matrix_equality.\n  bdestruct (y =? x); bdestruct (x =? y); bdestruct (y <? n); bdestruct (x <? n);\n    try lia; lca.\nQed.\n\nLemma zero_adjoint_eq : forall m n, (@Zero m n)† = @Zero n m.\nProof. unfold adjoint, Zero. rewrite Cconj_0. reflexivity. Qed.\n\nTheorem Mplus_comm : forall (m n : nat) (A B : Matrix m n), A .+ B = B .+ A.\nProof.\n  unfold Mplus. \n  intros m n A B.\n  prep_matrix_equality.\n  apply Cplus_comm.\nQed.\n\nTheorem Mplus_assoc : forall (m n : nat) (A B C : Matrix m n), A .+ B .+ C = A .+ (B .+ C).\nProof.\n  unfold Mplus. \n  intros m n A B C.\n  prep_matrix_equality.\n  rewrite Cplus_assoc.\n  reflexivity.\nQed.\n\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.\n  unfold Mmult.\n  prep_matrix_equality.\n  induction n.\n  + simpl.\n    clear B.\n    induction o. reflexivity.\n    simpl. rewrite IHo. lca.\n  + simpl. \n    rewrite <- IHn.\n    simpl.\n    rewrite Csum_mult_l.\n    rewrite <- Csum_plus.\n    apply Csum_eq.\n    apply functional_extensionality. intros z.\n    rewrite Cmult_plus_distr_r.\n    rewrite Cmult_assoc.\n    reflexivity.\nQed.\n\nLemma Mmult_plus_distr_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 m n o A B C.\n  unfold Mplus, Mmult.\n  prep_matrix_equality.\n  rewrite <- Csum_plus.\n  apply Csum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Cmult_plus_distr_l. \n  reflexivity.\nQed.\n\nLemma Mmult_plus_distr_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 m n o A B C.\n  unfold Mplus, Mmult.\n  prep_matrix_equality.\n  rewrite <- Csum_plus.\n  apply Csum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Cmult_plus_distr_r. \n  reflexivity.\nQed.\n\nLemma kron_plus_distr_l : forall (m n o p : nat) (A : Matrix m n) (B C : Matrix o p), \n                           A ⊗ (B .+ C) = A ⊗ B .+ A ⊗ C.\nProof. \n  intros m n o p A B C.\n  unfold Mplus, kron.\n  prep_matrix_equality.\n  rewrite Cmult_plus_distr_l.\n  easy.\nQed.\n\nLemma kron_plus_distr_r : forall (m n o p : nat) (A B : Matrix m n) (C : Matrix o p), \n                           (A .+ B) ⊗ C = A ⊗ C .+ B ⊗ C.\nProof. \n  intros m n o p A B C.\n  unfold Mplus, kron.\n  prep_matrix_equality.\n  rewrite Cmult_plus_distr_r. \n  reflexivity.\nQed.\n\nLemma Mscale_0_l : forall (m n : nat) (A : Matrix m n), C0 .* A = Zero.\nProof.\n  intros m n A.\n  prep_matrix_equality.\n  unfold Zero, scale.\n  rewrite Cmult_0_l.\n  reflexivity.\nQed.\n\nLemma Mscale_0_r : forall (m n : nat) (c : C), c .* @Zero m n = Zero.\nProof.\n  intros m n c.\n  prep_matrix_equality.\n  unfold Zero, scale.\n  rewrite Cmult_0_r.\n  reflexivity.\nQed.\n\nLemma Mscale_1_l : forall (m n : nat) (A : Matrix m n), C1 .* A = A.\nProof.\n  intros m n A.\n  prep_matrix_equality.\n  unfold scale.\n  rewrite Cmult_1_l.\n  reflexivity.\nQed.\n\nLemma Mscale_1_r : forall (n : nat) (c : C),\n    c .* I n = fun x y => if (x =? y) && (x <? n) then c else C0.\nProof.\n  intros n c.\n  prep_matrix_equality.\n  unfold scale, I.\n  destruct ((x =? y) && (x <? n)).\n  rewrite Cmult_1_r; reflexivity.\n  rewrite Cmult_0_r; reflexivity.\nQed.\n\nLemma Mscale_assoc : forall (m n : nat) (x y : C) (A : Matrix m n),\n  x .* (y .* A) = (x * y) .* A.\nProof.\n  intros. unfold scale. prep_matrix_equality.\n  rewrite Cmult_assoc; reflexivity.\nQed.\n\n\nLemma Mscale_div : forall {n m} (c : C) (A B : Matrix n m),\n  c <> C0 -> c .* A = c .* B -> A = B.\nProof. intros. \n       rewrite <- Mscale_1_l. rewrite <- (Mscale_1_l n m A).\n       rewrite <- (Cinv_l c).\n       rewrite <- Mscale_assoc.\n       rewrite H0. \n       lma.\n       apply H.\nQed.\n\n\nLemma Mscale_plus_distr_l : forall (m n : nat) (x y : C) (A : Matrix m n),\n  (x + y) .* A = x .* A .+ y .* A.\nProof.\n  intros. unfold Mplus, scale. prep_matrix_equality. apply Cmult_plus_distr_r.\nQed.\n\nLemma Mscale_plus_distr_r : forall (m n : nat) (x : C) (A B : Matrix m n),\n  x .* (A .+ B) = x .* A .+ x .* B.\nProof.\n  intros. unfold Mplus, scale. prep_matrix_equality. apply Cmult_plus_distr_l.\nQed.\n\nLemma Mscale_mult_dist_l : forall (m n o : nat) (x : C) (A : Matrix m n) (B : Matrix n o), \n    ((x .* A) × B) = x .* (A × B).\nProof.\n  intros m n o x A B.\n  unfold scale, Mmult.\n  prep_matrix_equality.\n  rewrite Csum_mult_l.\n  apply Csum_eq.\n  apply functional_extensionality. intros z.\n  rewrite Cmult_assoc.\n  reflexivity.\nQed.\n\nLemma Mscale_mult_dist_r : forall (m n o : nat) (x : C) (A : Matrix m n) (B : Matrix n o),\n    (A × (x .* B)) = x .* (A × B).\nProof.\n  intros m n o x A B.\n  unfold scale, Mmult.\n  prep_matrix_equality.\n  rewrite Csum_mult_l.\n  apply Csum_eq.\n  apply functional_extensionality. intros z.\n  repeat rewrite Cmult_assoc.\n  rewrite (Cmult_comm _ x).\n  reflexivity.\nQed.\n\nLemma Mscale_kron_dist_l : forall (m n o p : nat) (x : C) (A : Matrix m n) (B : Matrix o p), \n    ((x .* A) ⊗ B) = x .* (A ⊗ B).\nProof.\n  intros m n o p x A B.\n  unfold scale, kron.\n  prep_matrix_equality.\n  rewrite Cmult_assoc.\n  reflexivity.\nQed.\n\nLemma Mscale_kron_dist_r : forall (m n o p : nat) (x : C) (A : Matrix m n) (B : Matrix o p), \n    (A ⊗ (x .* B)) = x .* (A ⊗ B).\nProof.\n  intros m n o p x A B.\n  unfold scale, kron.\n  prep_matrix_equality.\n  rewrite Cmult_assoc.  \n  rewrite (Cmult_comm (A _ _) x).\n  rewrite Cmult_assoc.  \n  reflexivity.\nQed.\n\nLemma Mscale_trans : forall (m n : nat) (x : C) (A : Matrix m n),\n    (x .* A)⊤ = x .* A⊤.\nProof. reflexivity. Qed.\n\nLemma Mscale_adj : forall (m n : nat) (x : C) (A : Matrix m n),\n    (x .* A)† = x^* .* A†.\nProof.\n  intros m n xtranspose A.\n  unfold scale, adjoint.\n  prep_matrix_equality.\n  rewrite Cconj_mult_distr.          \n  reflexivity.\nQed.\n\n\nLemma Mplus_transpose : forall (m n : nat) (A : Matrix m n) (B : Matrix m n),\n  (A .+ B)⊤ = A⊤ .+ B⊤.\nProof. reflexivity. Qed.\n\nLemma Mmult_transpose : forall (m n o : nat) (A : Matrix m n) (B : Matrix n o),\n      (A × B)⊤ = B⊤ × A⊤.\nProof.\n  intros m n o A B.\n  unfold Mmult, transpose.\n  prep_matrix_equality.\n  apply Csum_eq.  \n  apply functional_extensionality. intros z.\n  rewrite Cmult_comm.\n  reflexivity.\nQed.\n\nLemma kron_transpose : forall (m n o p : nat) (A : Matrix m n) (B : Matrix o p ),\n  (A ⊗ B)⊤ = A⊤ ⊗ B⊤.\nProof. reflexivity. Qed.\n\n\nLemma Mplus_adjoint : forall (m n : nat) (A : Matrix m n) (B : Matrix m n),\n  (A .+ B)† = A† .+ B†.\nProof.  \n  intros m n A B.\n  unfold Mplus, adjoint.\n  prep_matrix_equality.\n  rewrite Cconj_plus_distr.\n  reflexivity.\nQed.\n\nLemma Mmult_adjoint : forall {m n o : nat} (A : Matrix m n) (B : Matrix n o),\n      (A × B)† = B† × A†.\nProof.\n  intros m n o A B.\n  unfold Mmult, adjoint.\n  prep_matrix_equality.\n  rewrite Csum_conj_distr.\n  apply Csum_eq.  \n  apply functional_extensionality. intros z.\n  rewrite Cconj_mult_distr.\n  rewrite Cmult_comm.\n  reflexivity.\nQed.\n\nLemma kron_adjoint : forall {m n o p : nat} (A : Matrix m n) (B : Matrix o p),\n  (A ⊗ B)† = A† ⊗ B†.\nProof. \n  intros. unfold adjoint, kron. \n  prep_matrix_equality.\n  rewrite Cconj_mult_distr.\n  reflexivity.\nQed.\n\nLemma id_kron : forall (m n : nat),  I m ⊗ I n = I (m * n).\nProof.\n  intros.\n  unfold I, kron.\n  prep_matrix_equality.\n  bdestruct (x =? y); rename H into Eq; subst.\n  + repeat rewrite <- beq_nat_refl; simpl.\n    destruct n.\n    - simpl.\n      rewrite mult_0_r.\n      bdestruct (y <? 0); try lia.\n      autorewrite with C_db; reflexivity.\n    - bdestruct (y mod S n <? S n). \n      2: specialize (Nat.mod_upper_bound y (S n)); intros; lia. \n      rewrite Cmult_1_r.\n      destruct (y / S n <? m) eqn:L1, (y <? m * S n) eqn:L2; trivial.\n      * apply Nat.ltb_lt in L1. \n        apply Nat.ltb_nlt in L2. \n        contradict L2. \n        clear H.\n        (* Why doesn't this lemma exist??? *)\n        destruct m.\n        lia.\n        apply Nat.div_small_iff. \n        simpl. apply Nat.neq_succ_0. (* `lia` will solve in 8.11+ *)\n        apply Nat.div_small in L1.\n        rewrite Nat.div_div in L1; try lia.\n        rewrite mult_comm.\n        assumption.\n      * apply Nat.ltb_nlt in L1. \n        apply Nat.ltb_lt in L2. \n        contradict L1. \n        apply Nat.div_lt_upper_bound. lia.\n        rewrite mult_comm.\n        assumption.\n  + simpl.\n    bdestruct (x / n =? y / n); simpl; try lca.\n    bdestruct (x mod n =? y mod n); simpl; try lca.\n    destruct n; try lca.    \n    contradict Eq.\n    rewrite (Nat.div_mod x (S n)) by lia.\n    rewrite (Nat.div_mod y (S n)) by lia.\n    rewrite H, H0; reflexivity.\nQed.\n\n\n(* this was origionally with the other Msum stuff, but I needed it earlier... *)\nLemma Msum_Csum : forall {d1 d2} n (f : nat -> Matrix d1 d2) i j,\n  Msum n f i j = Csum (fun x => f x i j) n.\nProof.\n  intros. \n  induction n; simpl.\n  reflexivity.\n  unfold Mplus.\n  rewrite IHn.\n  reflexivity.\nQed.\n\n\n\n(*****************************************************)\n(* Defining matrix altering/col operations functions *)\n(*****************************************************)\n\nLocal Open Scope nat_scope.\n\nDefinition get_vec {n m} (i : nat) (S : Matrix n m) : Vector n :=\n  fun x y => (if (y =? 0) then S x i else C0).   \n\n\nDefinition get_row {n m} (i : nat) (S : Matrix n m) : Matrix 1 m :=\n  fun x y => (if (x =? 0) then S i y else C0).  \n\n\nDefinition reduce_row {n m} (A : Matrix n m) (row : nat) : Matrix (n - 1) m :=\n  fun x y => if x <? row\n             then A x y\n             else A (1 + x) y.\n\nDefinition reduce_col {n m} (A : Matrix n m) (col : nat) : Matrix n (m - 1) :=\n  fun x y => if y <? col\n             then A x y\n             else A x (1 + y).\n\n\n(* more specific form for vectors *)\nDefinition reduce_vecn {n} (v : Vector n) : Vector (n - 1) :=\n  fun x y => if x <? (n - 1)\n             then v x y\n             else v (1 + x) y.\n\n\n(* More specific form for squares *)\nDefinition reduce {n} (A : Square n) (row col : nat) : Square (n - 1) :=\n  fun x y => (if x <? row \n              then (if y <? col \n                    then A x y\n                    else A x (1+y))\n              else (if y <? col \n                    then A (1+x) y\n                    else A (1+x) (1+y))).\n\nDefinition col_append {n m} (T : Matrix n m) (v : Vector n) : Matrix n (S m) :=\n  fun i j => if (j =? m) then v i 0 else T i j.\n\n\nDefinition row_append {n m} (T : Matrix n m) (v : Matrix 1 m) : Matrix (S n) m :=\n  fun i j => if (i =? n) then v 0 j else T i j.\n\n(* more general than col_append *)\nDefinition smash {n m1 m2} (T1 : Matrix n m1) (T2 : Matrix n m2) : Matrix n (m1 + m2) :=\n  fun i j => if j <? m1 then T1 i j else T2 i (j - m1).\n\n\nDefinition col_wedge {n m} (T : Matrix n m) (v : Vector n) (spot : nat) : Matrix n (S m) :=\n  fun i j => if j <? spot \n             then T i j\n             else if j =? spot\n                  then v i 0\n                  else T i (j-1).\n\nDefinition row_wedge {n m} (T : Matrix n m) (v : Matrix 1 m) (spot : nat) : Matrix (S n) m :=\n  fun i j => if i <? spot \n             then T i j\n             else if i =? spot\n                  then v 0 j\n                  else T (i-1) j.\n\n\nDefinition col_swap {n m : nat} (S : Matrix n m) (x y : nat) : Matrix n m := \n  fun i j => if (j =? x) \n             then S i y\n             else if (j =? y) \n                  then S i x\n                  else S i j.\n\nDefinition row_swap {n m : nat} (S : Matrix n m) (x y : nat) : Matrix n m := \n  fun i j => if (i =? x) \n             then S y j\n             else if (i =? y) \n                  then S x j\n                  else S i j.\n\nDefinition col_scale {n m : nat} (S : Matrix n m) (col : nat) (a : C) : Matrix n m := \n  fun i j => if (j =? col) \n             then (a * S i j)%C\n             else S i j.\n\nDefinition row_scale {n m : nat} (S : Matrix n m) (row : nat) (a : C) : Matrix n m := \n  fun i j => if (i =? row) \n             then (a * S i j)%C\n             else S i j.\n\n(* adding one column to another *)\nDefinition col_add {n m : nat} (S : Matrix n m) (col to_add : nat) (a : C) : Matrix n m := \n  fun i j => if (j =? col) \n             then (S i j + a * S i to_add)%C\n             else S i j.\n\n(* adding one row to another *)\nDefinition row_add {n m : nat} (S : Matrix n m) (row to_add : nat) (a : C) : Matrix n m := \n  fun i j => if (i =? row) \n             then (S i j + a * S to_add j)%C\n             else S i j.\n\n\n(* generalizing col_add *)\nDefinition gen_new_vec (n m : nat) (S : Matrix n m) (as' : Vector m) : Vector n :=\n  Msum m (fun i => (as' i 0) .* (get_vec i S)).\n\nDefinition gen_new_row (n m : nat) (S : Matrix n m) (as' : Matrix 1 n) : Matrix 1 m :=\n  Msum n (fun i => (as' 0 i) .* (get_row i S)).\n\n(* adds all columns to single column *)\nDefinition col_add_many {n m} (col : nat) (as' : Vector m) (S : Matrix n m) : Matrix n m :=\n  fun i j => if (j =? col) \n             then (S i j + (gen_new_vec n m S as') i 0)%C\n             else S i j.\n\nDefinition row_add_many {n m} (row : nat) (as' : Matrix 1 n) (S : Matrix n m) : Matrix n m :=\n  fun i j => if (i =? row) \n             then (S i j + (gen_new_row n m S as') 0 j)%C\n             else S i j.\n\n(* adds single column to each other column *)\nDefinition col_add_each {n m} (col : nat) (as' : Matrix 1 m) (S : Matrix n m) : Matrix n m := \n  S .+ ((get_vec col S) × as').\n\n\nDefinition row_add_each {n m} (row : nat) (as' : Vector n) (S : Matrix n m) : Matrix n m := \n  S .+ (as' × get_row row S).\n\n\nDefinition make_col_zero {n m} (col : nat) (S : Matrix n m) : Matrix n m :=\n  fun i j => if (j =? col) \n             then C0\n             else S i j.\n\nDefinition make_row_zero {n m} (row : nat) (S : Matrix n m) : Matrix n m :=\n  fun i j => if (i =? row) \n             then C0\n             else S i j.\n\nDefinition make_WF {n m} (S : Matrix n m) : Matrix n m :=\n  fun i j => if (i <? n) && (j <? m) then S i j else C0.\n\n\n(* proving lemmas about these new functions *)\n\nLemma WF_get_vec : forall {n m} (i : nat) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix (get_vec i S). \nProof. unfold WF_Matrix, get_vec in *.\n       intros.\n       bdestruct (y =? 0); try lia; try easy.\n       apply H.\n       destruct H0. \n       left; easy.\n       lia. \nQed.\n\nLemma WF_get_row : forall {n m} (i : nat) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix (get_row i S). \nProof. unfold WF_Matrix, get_row in *.\n       intros.\n       bdestruct (x =? 0); try lia; try easy.\n       apply H.\n       destruct H0. \n       lia. \n       right; easy.\nQed.\n\n\nLemma WF_reduce_row : forall {n m} (row : nat) (A : Matrix n m),\n  row < n -> WF_Matrix A -> WF_Matrix (reduce_row A row).\nProof. unfold WF_Matrix, reduce_row. intros. \n       bdestruct (x <? row). \n       - destruct H1 as [H1 | H1].\n         + assert (nibzo : forall (a b c : nat), a < b -> b < c -> 1 + a < c).\n           { lia. }\n           apply (nibzo x row n) in H2.\n           simpl in H2. lia. apply H.\n         + apply H0; auto.\n       - apply H0. destruct H1. \n         + left. simpl. lia.\n         + right. apply H1. \nQed.\n\n\nLemma WF_reduce_col : forall {n m} (col : nat) (A : Matrix n m),\n  col < m -> WF_Matrix A -> WF_Matrix (reduce_col A col).\nProof. unfold WF_Matrix, reduce_col. intros. \n       bdestruct (y <? col). \n       - destruct H1 as [H1 | H1].   \n         + apply H0; auto. \n         + assert (nibzo : forall (a b c : nat), a < b -> b < c -> 1 + a < c).\n           { lia. }\n           apply (nibzo y col m) in H2.\n           simpl in H2. lia. apply H.\n       - apply H0. destruct H1.\n         + left. apply H1. \n         + right. simpl. lia. \nQed.\n\n\nLemma rvn_is_rr_n : forall {n : nat} (v : Vector n),\n  reduce_vecn v = reduce_row v (n - 1).\nProof. intros.\n       prep_matrix_equality.\n       unfold reduce_row, reduce_vecn.\n       easy.\nQed.\n\nLemma WF_reduce_vecn : forall {n} (v : Vector n),\n  n <> 0 -> WF_Matrix v -> WF_Matrix (reduce_vecn v).\nProof. intros. \n       rewrite rvn_is_rr_n.\n       apply WF_reduce_row; try lia; try easy. \nQed.\n\n\nLemma reduce_is_redrow_redcol : forall {n} (A : Square n) (row col : nat),\n  reduce A row col = reduce_col (reduce_row A row) col.\nProof. intros. \n       prep_matrix_equality.\n       unfold reduce, reduce_col, reduce_row.\n       bdestruct (x <? row); bdestruct (y <? col); try easy.\nQed. \n\n\nLemma reduce_is_redcol_redrow : forall {n} (A : Square n) (row col : nat),\n  reduce A row col = reduce_row (reduce_col A col) row.\nProof. intros. \n       prep_matrix_equality.\n       unfold reduce, reduce_col, reduce_row.\n       bdestruct (x <? row); bdestruct (y <? col); try easy.\nQed. \n\n\nLemma WF_reduce : forall {n} (A : Square n) (row col : nat),\n  n <> 0 -> row < n -> col < n -> WF_Matrix A -> WF_Matrix (reduce A row col).\nProof. intros.\n       rewrite reduce_is_redrow_redcol.\n       apply WF_reduce_col; try easy.\n       apply WF_reduce_row; try easy.\nQed.\n\nLemma WF_col_swap : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  x < m -> y < m -> WF_Matrix S -> WF_Matrix (col_swap S x y).\nProof. unfold WF_Matrix, col_swap in *.\n       intros. \n       bdestruct (y0 =? x); bdestruct (y0 =? y); destruct H2; try lia. \n       all : apply H1; try (left; apply H2).\n       auto.\nQed.\n\nLemma WF_row_swap : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  x < n -> y < n -> WF_Matrix S -> WF_Matrix (row_swap S x y).\nProof. unfold WF_Matrix, row_swap in *.\n       intros. \n       bdestruct (x0 =? x); bdestruct (x0 =? y); destruct H2; try lia. \n       all : apply H1; try (right; apply H2).\n       auto.\nQed.\n\nLemma WF_col_scale : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  WF_Matrix S -> WF_Matrix (col_scale S x a).\nProof. unfold WF_Matrix, col_scale in *.\n       intros. \n       apply H in H0.\n       rewrite H0.\n       rewrite Cmult_0_r.\n       bdestruct (y =? x); easy.\nQed.\n\nLemma WF_row_scale : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  WF_Matrix S -> WF_Matrix (row_scale S x a).\nProof. unfold WF_Matrix, row_scale in *.\n       intros. \n       apply H in H0.\n       rewrite H0.\n       rewrite Cmult_0_r.\n       bdestruct (x0 =? x); easy.\nQed.\n\n\nLemma WF_col_add : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  x < m -> WF_Matrix S -> WF_Matrix (col_add S x y a).\nProof. unfold WF_Matrix, col_add in *.\n       intros.\n       bdestruct (y0 =? x); destruct H1; try lia. \n       do 2 (rewrite H0; auto). lca. \n       all : apply H0; auto.\nQed.\n\n\nLemma WF_row_add : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  x < n -> WF_Matrix S -> WF_Matrix (row_add S x y a).\nProof. unfold WF_Matrix, row_add in *.\n       intros.\n       bdestruct (x0 =? x); destruct H1; try lia. \n       do 2 (rewrite H0; auto). lca. \n       all : apply H0; auto.\nQed.\n\n\nLemma WF_gen_new_vec : forall {n m} (S : Matrix n m) (as' : Vector m),\n  WF_Matrix S -> WF_Matrix (gen_new_vec n m S as').\nProof. intros.\n       unfold gen_new_vec.\n       apply WF_Msum; intros. \n       apply WF_scale. \n       apply WF_get_vec.\n       easy.\nQed.\n\n\nLemma WF_gen_new_row : forall {n m} (S : Matrix n m) (as' : Matrix 1 n),\n  WF_Matrix S -> WF_Matrix (gen_new_row n m S as').\nProof. intros.\n       unfold gen_new_row.\n       apply WF_Msum; intros. \n       apply WF_scale. \n       apply WF_get_row.\n       easy.\nQed.\n\nLemma WF_col_add_many : forall {n m} (col : nat) (as' : Vector m) (S : Matrix n m),\n  col < m -> WF_Matrix S -> WF_Matrix (col_add_many col as' S).\nProof. unfold WF_Matrix, col_add_many.\n       intros. \n       bdestruct (y =? col).\n       assert (H4 := (WF_gen_new_vec S as')).\n       rewrite H4, H0; try easy.\n       lca. destruct H2; lia. \n       rewrite H0; easy.\nQed.\n\nLemma WF_row_add_many : forall {n m} (row : nat) (as' : Matrix 1 n) (S : Matrix n m),\n  row < n -> WF_Matrix S -> WF_Matrix (row_add_many row as' S).\nProof. unfold WF_Matrix, row_add_many.\n       intros. \n       bdestruct (x =? row).\n       assert (H4 := (WF_gen_new_row S as')).\n       rewrite H4, H0; try easy.\n       lca. destruct H2; lia. \n       rewrite H0; easy.\nQed.\n\n\nLemma WF_col_append : forall {n m} (T : Matrix n m) (v : Vector n),\n  WF_Matrix T -> WF_Matrix v -> WF_Matrix (col_append T v).\nProof. unfold WF_Matrix in *.\n       intros; destruct H1 as [H1 | H1]. \n       - unfold col_append.\n         rewrite H, H0; try lia. \n         bdestruct (y =? m); easy. \n       - unfold col_append.\n         bdestruct (y =? m); try lia. \n         apply H; lia. \nQed.\n\n\nLemma WF_row_append : forall {n m} (T : Matrix n m) (v : Matrix 1 m),\n  WF_Matrix T -> WF_Matrix v -> WF_Matrix (row_append T v).\nProof. unfold WF_Matrix in *.\n       intros; destruct H1 as [H1 | H1]. \n       - unfold row_append.\n         bdestruct (x =? n); try lia. \n         apply H; lia. \n       - unfold row_append.\n         rewrite H, H0; try lia. \n         bdestruct (x =? n); easy. \nQed.\n\n\nLemma WF_col_wedge : forall {n m} (T : Matrix n m) (v : Vector n) (spot : nat),\n  spot <= m -> WF_Matrix T -> WF_Matrix v -> WF_Matrix (col_wedge T v spot).\nProof. unfold WF_Matrix in *.\n       intros; destruct H2 as [H2 | H2]. \n       - unfold col_wedge.\n         rewrite H0, H1; try lia. \n         rewrite H0; try lia. \n         bdestruct (y <? spot); bdestruct (y =? spot); easy. \n       - unfold col_wedge.\n         bdestruct (y <? spot); bdestruct (y =? spot); try lia. \n         rewrite H0; try lia. \n         easy.  \nQed.\n\n\nLemma WF_row_wedge : forall {n m} (T : Matrix n m) (v : Matrix 1 m) (spot : nat),\n  spot <= n -> WF_Matrix T -> WF_Matrix v -> WF_Matrix (row_wedge T v spot).\nProof. unfold WF_Matrix in *.\n       intros; destruct H2 as [H2 | H2]. \n       - unfold row_wedge.\n         bdestruct (x <? spot); bdestruct (x =? spot); try lia. \n         rewrite H0; try lia. \n         easy.  \n       - unfold row_wedge.\n         rewrite H0, H1; try lia. \n         rewrite H0; try lia. \n         bdestruct (x <? spot); bdestruct (x =? spot); easy. \nQed.\n\n\nLemma WF_smash : forall {n m1 m2} (T1 : Matrix n m1) (T2 : Matrix n m2),\n  WF_Matrix T1 -> WF_Matrix T2 -> WF_Matrix (smash T1 T2).\nProof. unfold WF_Matrix, smash in *.\n       intros. \n       bdestruct (y <? m1).\n       - apply H; lia. \n       - apply H0; lia.\nQed.\n\n\nLemma WF_col_add_each : forall {n m} (col : nat) (as' : Matrix 1 m) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix as' -> WF_Matrix (col_add_each col as' S).\nProof. intros.\n       unfold col_add_each.\n       apply WF_plus; try easy;\n       apply WF_mult; try easy;\n       apply WF_get_vec; easy.\nQed.\n\nLemma WF_row_add_each : forall {n m} (row : nat) (as' : Vector n) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix as' -> WF_Matrix (row_add_each row as' S).\nProof. intros.\n       unfold row_add_each.\n       apply WF_plus; try easy;\n       apply WF_mult; try easy;\n       apply WF_get_row; easy.\nQed.\n\nLemma WF_make_col_zero : forall {n m} (col : nat) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix (make_col_zero col S).\nProof. unfold make_col_zero, WF_Matrix.\n       intros. \n       rewrite H; try easy.\n       bdestruct (y =? col); easy.\nQed.\n\nLemma WF_make_row_zero : forall {n m} (row : nat) (S : Matrix n m),\n  WF_Matrix S -> WF_Matrix (make_row_zero row S).\nProof. unfold make_row_zero, WF_Matrix.\n       intros. \n       rewrite H; try easy.\n       bdestruct (x =? row); easy.\nQed.\n\nLemma WF_make_WF : forall {n m} (S : Matrix n m), WF_Matrix (make_WF S).\nProof. intros. \n       unfold WF_Matrix, make_WF; intros. \n       destruct H as [H | H].\n       bdestruct (x <? n); try lia; easy. \n       bdestruct (y <? m); bdestruct (x <? n); try lia; easy.\nQed.\n\n\nHint Resolve WF_get_vec WF_get_row WF_reduce_row WF_reduce_col WF_reduce_vecn WF_reduce : wf_db.\nHint Resolve WF_col_swap WF_row_swap WF_col_scale WF_row_scale WF_col_add WF_row_add  : wf_db.\nHint Resolve WF_gen_new_vec WF_gen_new_row WF_col_add_many WF_row_add_many : wf_db.\nHint Resolve WF_col_append WF_row_append WF_row_wedge WF_col_wedge WF_smash : wf_db.\nHint Resolve WF_col_add_each WF_row_add_each WF_make_col_zero WF_make_row_zero : wf_db.\n \n\nLemma get_vec_reduce_col : forall {n m} (i col : nat) (A : Matrix n m),\n  i < col -> get_vec i (reduce_col A col) = get_vec i A.\nProof. intros. \n       prep_matrix_equality. \n       unfold get_vec, reduce_col.\n       bdestruct (i <? col); try lia; easy.\nQed.\n\n\n\nLemma get_vec_conv : forall {n m} (x y : nat) (S : Matrix n m),\n  (get_vec y S) x 0 = S x y.\nProof. intros. unfold get_vec.\n       easy.\nQed.\n\n\nLemma get_vec_mult : forall {n} (i : nat) (A B : Square n),\n  A × (get_vec i B) = get_vec i (A × B).\nProof. intros. unfold get_vec, Mmult.\n       prep_matrix_equality.\n       bdestruct (y =? 0).\n       - reflexivity.\n       - apply Csum_0. intros.\n         apply Cmult_0_r.\nQed.\n\n\nLemma det_by_get_vec : forall {n} (A B : Square n),\n  (forall i, get_vec i A = get_vec i B) -> A = B.\nProof. intros. prep_matrix_equality.\n       rewrite <- get_vec_conv.\n       rewrite <- (get_vec_conv _ _ B).\n       rewrite H.\n       reflexivity.\nQed.\n\n\nLemma col_scale_reduce_col_same : forall {n m} (T : Matrix n m) (y col : nat) (a : C),\n  y = col -> reduce_col (col_scale T col a) y = reduce_col T y.\nProof. intros.\n       prep_matrix_equality. \n       unfold reduce_col, col_scale. \n       bdestruct (y0 <? y); bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\n\nLemma col_swap_reduce_before : forall {n : nat} (T : Square n) (row col c1 c2 : nat),\n  col < (S c1) -> col < (S c2) ->\n  reduce (col_swap T (S c1) (S c2)) row col = col_swap (reduce T row col) c1 c2.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce, col_swap.\n       bdestruct (c1 <? col); bdestruct (c2 <? col); try lia. \n       simpl. \n       bdestruct (x <? row); bdestruct (y <? col); bdestruct (y =? c1);\n         bdestruct (y =? S c1); bdestruct (y =? c2); bdestruct (y =? S c2); try lia; try easy. \nQed.\n\n\nLemma col_scale_reduce_before : forall {n : nat} (T : Square n) (x y col : nat) (a : C),\n  y < col -> reduce (col_scale T col a) x y = col_scale (reduce T x y) (col - 1) a.\nProof. intros. \n       prep_matrix_equality. \n       destruct col; try lia. \n       rewrite easy_sub. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y); bdestruct (y0 =? S col);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? S col); try lia; easy. \nQed.\n\n\nLemma col_scale_reduce_same : forall {n : nat} (T : Square n) (x y col : nat) (a : C),\n  y = col -> reduce (col_scale T col a) x y = reduce T x y.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\n\nLemma col_scale_reduce_after : forall {n : nat} (T : Square n) (x y col : nat) (a : C),\n  y > col -> reduce (col_scale T col a) x y = col_scale (reduce T x y) col a.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce, col_scale. \n       bdestruct (x0 <? x); bdestruct (y0 <? y);\n         bdestruct (y0 =? col); bdestruct (1 + y0 =? col); try lia; easy. \nQed.\n\n\nLemma mcz_reduce_col_same : forall {n m} (T : Matrix n m) (col : nat),\n  reduce_col (make_col_zero col T) col = reduce_col T col.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce_col, make_col_zero. \n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; easy. \nQed.\n\nLemma mrz_reduce_row_same : forall {n m} (T : Matrix n m) (row : nat),\n  reduce_row (make_row_zero row T) row = reduce_row T row.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce_row, make_row_zero. \n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; easy. \nQed.\n\nLemma col_add_many_reduce_col_same : forall {n m} (T : Matrix n m) (v : Vector m) (col : nat),\n  reduce_col (col_add_many col v T) col = reduce_col T col.\nProof. intros. \n       unfold reduce_col, col_add_many.\n       prep_matrix_equality. \n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; easy. \nQed.\n\nLemma row_add_many_reduce_row_same : forall {n m} (T : Matrix n m) (v : Matrix 1 n) (row : nat),\n  reduce_row (row_add_many row v T) row = reduce_row T row.\nProof. intros. \n       unfold reduce_row, row_add_many.\n       prep_matrix_equality. \n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; easy. \nQed.\n\nLemma col_wedge_reduce_col_same : forall {n m} (T : Matrix n m) (v : Vector m) (col : nat),\n  reduce_col (col_wedge T v col) col = T.\nProof. intros.\n       prep_matrix_equality.\n       unfold reduce_col, col_wedge.\n       assert (p : (1 + y - 1) = y). lia.\n       bdestruct (y <? col); bdestruct (1 + y <? col); \n         bdestruct (y =? col); bdestruct (1 + y =? col); try lia; try easy. \n       all : rewrite p; easy.\nQed.\n\nLemma row_wedge_reduce_row_same : forall {n m} (T : Matrix n m) (v : Matrix 1 n) (row : nat),\n  reduce_row (row_wedge T v row) row = T.\nProof. intros.\n       prep_matrix_equality.\n       unfold reduce_row, row_wedge.\n       assert (p : (1 + x - 1) = x). lia.\n       bdestruct (x <? row); bdestruct (1 + x <? row); \n         bdestruct (x =? row); bdestruct (1 + x =? row); try lia; try easy. \n       all : rewrite p; easy.\nQed.\n\nLemma col_add_many_reduce_row : forall {n m} (T : Matrix n m) (v : Vector m) (col row : nat),\n  col_add_many col v (reduce_row T row) = reduce_row (col_add_many col v T) row.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_add_many, reduce_row, gen_new_vec, scale, get_vec. \n       bdestruct (y =? col); try lia; try easy. \n       bdestruct (x <? row); try lia. \n       apply Csum_simplify; try easy. \n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       bdestruct (x <? row); try lia; easy.\n       apply Csum_simplify; try easy. \n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       bdestruct (x <? row); try lia; easy.\nQed.\n\n\nLemma col_swap_same : forall {n m : nat} (S : Matrix n m) (x : nat),\n  col_swap S x x = S.\nProof. intros. \n       unfold col_swap. \n       prep_matrix_equality. \n       bdestruct (y =? x); try easy.\n       rewrite H; easy.\nQed. \n\n\nLemma row_swap_same : forall {n m : nat} (S : Matrix n m) (x : nat),\n  row_swap S x x = S.\nProof. intros. \n       unfold row_swap. \n       prep_matrix_equality. \n       bdestruct (x0 =? x); try easy.\n       rewrite H; easy.\nQed. \n\nLemma col_swap_diff_order : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  col_swap S x y = col_swap S y x.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_swap.\n       bdestruct (y0 =? x); bdestruct (y0 =? y); try easy.\n       rewrite <- H, <- H0; easy.\nQed.\n\nLemma row_swap_diff_order : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  row_swap S x y = row_swap S y x.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_swap.\n       bdestruct (x0 =? x); bdestruct (x0 =? y); try easy.\n       rewrite <- H, <- H0; easy.\nQed.\n\n\nLemma col_swap_inv : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  S = col_swap (col_swap S x y) x y.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_swap.\n       bdestruct (y0 =? x); bdestruct (y0 =? y); \n         bdestruct (y =? x); bdestruct (x =? x); bdestruct (y =? y); \n         try easy. \n       all : (try rewrite H; try rewrite H0; try rewrite H1; easy).\nQed.\n\nLemma row_swap_inv : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  S = row_swap (row_swap S x y) x y.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_swap.\n       bdestruct (x0 =? x); bdestruct (x0 =? y); \n         bdestruct (y =? x); bdestruct (x =? x); bdestruct (y =? y); \n         try easy. \n       all : (try rewrite H; try rewrite H0; try rewrite H1; easy).\nQed.\n\n\nLemma col_swap_get_vec : forall {n m : nat} (S : Matrix n m) (x y : nat),\n  get_vec y S = get_vec x (col_swap S x y).\nProof. intros. \n       prep_matrix_equality. \n       unfold get_vec, col_swap. \n       bdestruct (x =? x); bdestruct (x =? y); try lia; try easy.\nQed.\n\n\nLemma col_swap_three : forall {n m} (T : Matrix n m) (x y z : nat),\n  x <> z -> y <> z -> col_swap T x z = col_swap (col_swap (col_swap T x y) y z) x y.\nProof. intros.\n       bdestruct (x =? y).\n       rewrite H1, col_swap_same, col_swap_same.\n       easy. \n       prep_matrix_equality. \n       unfold col_swap.\n       bdestruct (y =? y); bdestruct (y =? x); bdestruct (y =? z); try lia. \n       bdestruct (x =? y); bdestruct (x =? x); bdestruct (x =? z); try lia. \n       bdestruct (z =? y); bdestruct (z =? x); try lia. \n       bdestruct (y0 =? y); bdestruct (y0 =? x); bdestruct (y0 =? z); \n         try lia; try easy.\n       rewrite H10.\n       easy.\nQed.\n\nLemma reduce_row_reduce_col : forall {n m} (A : Matrix n m) (i j : nat),\n  reduce_col (reduce_row A i) j = reduce_row (reduce_col A j) i.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce_col, reduce_row.\n       bdestruct (y <? j); bdestruct (x <? i); try lia; try easy. \nQed.\nLemma reduce_col_swap_01 : forall {n} (A : Square n),\n  reduce_col (reduce_col (col_swap A 0 1) 0) 0 = reduce_col (reduce_col A 0) 0.\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce_col, col_swap.\n       bdestruct (y <? 0); bdestruct (1 + y <? 0); try lia. \n       bdestruct (1 + (1 + y) =? 0); bdestruct (1 + (1 + y) =? 1); try lia. \n       easy. \nQed.\n\nLemma reduce_reduce_0 : forall {n} (A : Square n) (x y : nat),\n  x <= y ->\n  (reduce (reduce A x 0) y 0) = (reduce (reduce A (S y) 0) x 0).\nProof. intros.\n       prep_matrix_equality.\n       unfold reduce. \n       bdestruct (y0 <? 0); bdestruct (1 + y0 <? 0); try lia. \n       bdestruct (x0 <? y); bdestruct (x0 <? S y); bdestruct (x0 <? x); \n         bdestruct (1 + x0 <? S y); bdestruct (1 + x0 <? x); \n         try lia; try easy.\nQed.     \n\n\nLemma col_add_split : forall {n} (A : Square n) (i : nat) (c : C),\n  col_add A 0 i c = col_wedge (reduce_col A 0) (get_vec 0 A .+ c.* get_vec i A) 0.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_add, col_wedge, reduce_col, get_vec, Mplus, scale.\n       bdestruct (y =? 0); try lia; simpl. \n       rewrite H; easy.\n       replace (S (y - 1)) with y by lia. \n       easy.\nQed.\n\n\nLemma col_swap_col_add_Si : forall {n} (A : Square n) (i j : nat) (c : C),\n  i <> 0 -> i <> j -> col_swap (col_add (col_swap A j 0) 0 i c) j 0 = col_add A j i c.\nProof. intros. \n       bdestruct (j =? 0).\n       - rewrite H1.\n         do 2 rewrite col_swap_same; easy.\n       - prep_matrix_equality. \n         unfold col_swap, col_add.\n         bdestruct (y =? j); bdestruct (j =? j); try lia; simpl. \n         destruct j; try lia. \n         bdestruct (i =? S j); bdestruct (i =? 0); try lia.  \n         rewrite H2; easy.\n         bdestruct (y =? 0); bdestruct (j =? 0); try easy. \n         rewrite H4; easy. \nQed.\n\nLemma col_swap_col_add_0 : forall {n} (A : Square n) (j : nat) (c : C),\n  j <> 0 -> col_swap (col_add (col_swap A j 0) 0 j c) j 0 = col_add A j 0 c.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_swap, col_add.\n       bdestruct (y =? j); bdestruct (j =? j); bdestruct (0 =? j); try lia; simpl. \n       rewrite H0; easy.\n       bdestruct (y =? 0); bdestruct (j =? 0); try easy. \n       rewrite H3; easy.\nQed.\n\nLemma col_swap_end_reduce_col_hit : forall {n m : nat} (T : Matrix n (S (S m))) (i : nat),\n  i <= m -> col_swap (reduce_col T i) m i = reduce_col (col_swap T (S m) (S i)) i.\nProof. intros.\n       prep_matrix_equality. \n       unfold reduce_col, col_swap. \n       bdestruct (i <? i); bdestruct (m <? i); bdestruct (y =? m); bdestruct (y =? i); \n         bdestruct (y <? i); bdestruct (1 + y =? S m); try lia; try easy. \n       bdestruct (1 + y =? S i); try lia; easy.\n       bdestruct (y =? S m); bdestruct (y =? S i); try lia; easy. \n       bdestruct (1 + y =? S i); try lia; easy.\nQed.\n\n\nLemma col_swap_reduce_row : forall {n m : nat} (S : Matrix n m) (x y row : nat),\n  col_swap (reduce_row S row) x y = reduce_row (col_swap S x y) row.\nProof. intros. \n       prep_matrix_equality. \n       unfold col_swap, reduce_row. \n       bdestruct (y0 =? x); bdestruct (x0 <? row); bdestruct (y0 =? y); try lia; easy. \nQed.\n\n\nLemma col_scale_inv : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  a <> C0 -> S = col_scale (col_scale S x a) x (/ a).\nProof. intros. \n       prep_matrix_equality. \n       unfold col_scale.\n       bdestruct (y =? x); try easy.\n       rewrite Cmult_assoc.\n       rewrite Cinv_l; try lca; easy. \nQed.\n\n\nLemma row_scale_inv : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  a <> C0 -> S = row_scale (row_scale S x a) x (/ a).\nProof. intros. \n       prep_matrix_equality. \n       unfold row_scale.\n       bdestruct (x0 =? x); try easy.\n       rewrite Cmult_assoc.\n       rewrite Cinv_l; try lca; easy. \nQed.\n\n\n\nLemma col_add_double : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  col_add S x x a = col_scale S x (C1 + a).\nProof. intros. \n       prep_matrix_equality. \n       unfold col_add, col_scale. \n       bdestruct (y =? x).\n       - rewrite H; lca. \n       - easy.\nQed.\n\nLemma row_add_double : forall {n m : nat} (S : Matrix n m) (x : nat) (a : C),\n  row_add S x x a = row_scale S x (C1 + a).\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add, row_scale. \n       bdestruct (x0 =? x).\n       - rewrite H; lca. \n       - easy.\nQed.\n\nLemma col_add_swap : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  col_swap (col_add S x y a) x y = col_add (col_swap S x y) y x a. \nProof. intros. \n       prep_matrix_equality. \n       unfold col_swap, col_add.\n       bdestruct (y0 =? x); bdestruct (y =? x);\n         bdestruct (y0 =? y); bdestruct (x =? x); try lia; easy. \nQed.\n       \nLemma row_add_swap : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  row_swap (row_add S x y a) x y = row_add (row_swap S x y) y x a. \nProof. intros. \n       prep_matrix_equality. \n       unfold row_swap, row_add.\n       bdestruct (x0 =? x); bdestruct (y =? x);\n         bdestruct (x0 =? y); bdestruct (x =? x); try lia; easy. \nQed.\n\n\nLemma col_add_inv : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  x <> y -> S = col_add (col_add S x y a) x y (-a).\nProof. intros. \n       prep_matrix_equality.\n       unfold col_add.\n       bdestruct (y0 =? x); bdestruct (y =? x); try lia. \n       lca. easy. \nQed.\n\nLemma row_add_inv : forall {n m : nat} (S : Matrix n m) (x y : nat) (a : C),\n  x <> y -> S = row_add (row_add S x y a) x y (-a).\nProof. intros. \n       prep_matrix_equality.\n       unfold row_add.\n       bdestruct (x0 =? x); bdestruct (y =? x); try lia. \n       lca. easy. \nQed.\n\n\n\nLemma mat_equiv_make_WF : forall {n m} (T : Matrix n m),\n  T == make_WF T.\nProof. unfold make_WF, mat_equiv; intros. \n       bdestruct (i <? n); bdestruct (j <? m); try lia; easy.\nQed.\n\n\nLemma gen_new_vec_0 : forall {n m} (T : Matrix n m) (as' : Vector m),\n  as' == Zero -> gen_new_vec n m T as' = Zero.\nProof. intros.\n       unfold mat_equiv, gen_new_vec in *.\n       prep_matrix_equality.\n       rewrite Msum_Csum.\n       unfold Zero in *.\n       apply Csum_0_bounded; intros. \n       rewrite H; try lia. \n       rewrite Mscale_0_l.\n       easy.\nQed.\n\nLemma gen_new_row_0 : forall {n m} (T : Matrix n m) (as' : Matrix 1 n),\n  as' == Zero -> gen_new_row n m T as' = Zero.\nProof. intros.\n       unfold mat_equiv, gen_new_row in *.\n       prep_matrix_equality.\n       rewrite Msum_Csum.\n       unfold Zero in *.\n       apply Csum_0_bounded; intros. \n       rewrite H; try lia. \n       rewrite Mscale_0_l.\n       easy.\nQed.\n\nLemma col_add_many_0 : forall {n m} (col : nat) (T : Matrix n m) (as' : Vector m),\n  as' == Zero -> T = col_add_many col as' T.\nProof. intros. \n       unfold col_add_many in *.\n       prep_matrix_equality.\n       bdestruct (y =? col); try easy.\n       rewrite gen_new_vec_0; try easy.\n       unfold Zero; lca. \nQed.\n\nLemma row_add_many_0 : forall {n m} (row : nat) (T : Matrix n m) (as' : Matrix 1 n),\n  as' == Zero -> T = row_add_many row as' T.\nProof. intros. \n       unfold row_add_many in *.\n       prep_matrix_equality.\n       bdestruct (x =? row); try easy.\n       rewrite gen_new_row_0; try easy.\n       unfold Zero; lca. \nQed.\n\n\nLemma gen_new_vec_mat_equiv : forall {n m} (T : Matrix n m) (as' bs : Vector m),\n  as' == bs -> gen_new_vec n m T as' = gen_new_vec n m T bs.\nProof. unfold mat_equiv, gen_new_vec; intros.\n       prep_matrix_equality.\n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       rewrite H; try lia. \n       easy.\nQed.\n\nLemma gen_new_row_mat_equiv : forall {n m} (T : Matrix n m) (as' bs : Matrix 1 n),\n  as' == bs -> gen_new_row n m T as' = gen_new_row n m T bs.\nProof. unfold mat_equiv, gen_new_row; intros.\n       prep_matrix_equality.\n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       rewrite H; try lia. \n       easy.\nQed.\n\nLemma col_add_many_mat_equiv : forall {n m} (col : nat) (T : Matrix n m) (as' bs : Vector m),\n  as' == bs -> col_add_many col as' T = col_add_many col bs T.\nProof. intros. \n       unfold col_add_many.\n       rewrite (gen_new_vec_mat_equiv _ as' bs); easy.\nQed.\n\nLemma row_add_many_mat_equiv : forall {n m} (row : nat) (T : Matrix n m) (as' bs : Matrix 1 n),\n  as' == bs -> row_add_many row as' T = row_add_many row bs T.\nProof. intros. \n       unfold row_add_many.\n       rewrite (gen_new_row_mat_equiv _ as' bs); easy.\nQed.\n\n\nLemma col_add_each_0 : forall {n m} (col : nat) (T : Matrix n m) (v : Matrix 1 m),\n  v = Zero -> T = col_add_each col v T.\nProof. intros. \n       rewrite H.\n       unfold col_add_each.\n       rewrite Mmult_0_r.\n       rewrite Mplus_0_r.\n       easy. \nQed.\n\nLemma row_add_each_0 : forall {n m} (row : nat) (T : Matrix n m) (v : Vector n),\n  v = Zero -> T = row_add_each row v T.\nProof. intros. \n       rewrite H.\n       unfold row_add_each.\n       rewrite Mmult_0_l.\n       rewrite Mplus_0_r.\n       easy. \nQed.\n\n\n\nLemma col_add_many_col_add : forall {n m} (col e : nat) (T : Matrix n m) (as' : Vector m),\n  col <> e -> e < m -> as' col 0 = C0 ->\n  col_add_many col as' T = \n  col_add (col_add_many col (make_row_zero e as') T) col e (as' e 0).\nProof. intros. \n       unfold col_add_many, col_add, gen_new_vec.\n       prep_matrix_equality.\n       bdestruct (y =? col); try easy.\n       bdestruct (e =? col); try lia.\n       rewrite <- Cplus_assoc.\n       apply Csum_simplify; try easy.\n       assert (H' : m = e + (m - e)). lia. \n       rewrite H'.\n       do 2 rewrite Msum_Csum. \n       rewrite Csum_sum.\n       rewrite Csum_sum.\n       rewrite <- Cplus_assoc.\n       apply Csum_simplify.\n       apply Csum_eq_bounded; intros.\n       unfold make_row_zero.\n       bdestruct (x0 =? e); try lia; easy. \n       destruct (m - e); try lia. \n       do 2 rewrite <- Csum_extend_l.\n       unfold make_row_zero.\n       bdestruct (e + 0 =? e); try lia. \n       unfold scale.\n       rewrite Cmult_0_l, Cplus_0_l.\n       rewrite Cplus_comm.\n       apply Csum_simplify.\n       apply Csum_eq_bounded; intros.\n       bdestruct (e + S x0 =? e); try lia; easy.\n       unfold get_vec. simpl. \n       rewrite plus_0_r; easy.\nQed.\n\n\nLemma col_add_many_cancel : forall {n m} (T : Matrix n m) (as' : Vector m) (col : nat),\n  col < m -> as' col 0 = C0 ->\n  (reduce_col T col) × (reduce_row as' col) = -C1 .* (get_vec col T) -> \n  (forall i : nat, (col_add_many col as' T) i col = C0).\nProof. intros.\n       destruct m; try lia. \n       unfold col_add_many, gen_new_vec.\n       bdestruct (col =? col); try lia. \n       rewrite Msum_Csum. \n       assert (H' : (Csum (fun x : nat => (as' x 0 .* get_vec x T) i 0) (S m) = \n                     (@Mmult n m 1 (reduce_col T col) (reduce_row as' col)) i 0)%C).\n       { unfold Mmult. \n         assert (p : S m = col + (S (m - col))). lia.\n         assert (p1 : m = col + (m - col)). lia.\n         rewrite p; rewrite Csum_sum. \n         rewrite p1; rewrite Csum_sum. \n         apply Csum_simplify. \n         apply Csum_eq_bounded; intros. \n         unfold get_vec, scale, reduce_col, reduce_row. \n         bdestruct (x <? col); simpl; try lia; lca.  \n         rewrite <- p1, <- Csum_extend_l. \n         assert (p2 : col + 0 = col). lia. rewrite p2, H0.\n         unfold scale; rewrite Cmult_0_l, Cplus_0_l.\n         apply Csum_eq_bounded; intros. \n         unfold get_vec, scale, reduce_col, reduce_row. \n         bdestruct (col + x <? col); simpl; try lia.\n         assert (p3 : (col + S x) = (S (col + x))). lia.\n         rewrite p3. lca. }\n       rewrite H'.\n       rewrite easy_sub in *.\n       rewrite H1.\n       unfold scale, get_vec. \n       bdestruct (0 =? 0); try lia. \n       lca.\nQed.\n\n\nLemma col_add_many_inv : forall {n m} (S : Matrix n m) (col : nat) (as' : Vector m),\n  as' col 0 = C0 -> S = col_add_many col (-C1 .* as') (col_add_many col as' S).\nProof. intros. \n       unfold col_add_many, gen_new_vec.\n       prep_matrix_equality. \n       bdestruct (y =? col); try easy.\n       rewrite <- (Cplus_0_r (S x y)).\n       rewrite <- Cplus_assoc.\n       apply Csum_simplify; try lca.\n       do 2 rewrite Msum_Csum.\n       rewrite <- Csum_plus.\n       rewrite Csum_0_bounded; try lca.\n       intros. \n       unfold get_vec, scale.\n       bdestruct (0 =? 0); bdestruct (x0 =? col); try lia; try lca.\n       rewrite Msum_Csum.\n       bdestruct (0 =? 0); try lia. \n       rewrite H3, H. lca.\nQed.\n\n\nLemma col_add_each_col_add : forall {n m} (col e : nat) (S : Matrix n m) (as' : Matrix 1 m),\n  col <> e -> (forall x, as' x col = C0) ->\n              col_add_each col as' S = \n              col_add (col_add_each col (make_col_zero e as') S) e col (as' 0 e).\nProof. intros.\n       prep_matrix_equality.\n       unfold col_add_each, col_add, make_col_zero, Mmult, Mplus, get_vec, Csum.\n       bdestruct (y =? col); bdestruct (y =? e); bdestruct (col =? e); \n         bdestruct (e =? e); bdestruct (0 =? 0); try lia; try lca. \n       rewrite H0. \n       rewrite H2. lca.\nQed.\n\n\nLemma row_add_each_row_add : forall {n m} (row e : nat) (S : Matrix n m) (as' : Vector n),\n  row <> e -> (forall y, as' row y = C0) ->\n              row_add_each row as' S = \n              row_add (row_add_each row (make_row_zero e as') S) e row (as' e 0).\nProof. intros.\n       prep_matrix_equality.\n       unfold row_add_each, row_add, make_row_zero, Mmult, Mplus, get_row, Csum.\n       bdestruct (x =? row); bdestruct (x =? e); bdestruct (row =? e); \n         bdestruct (e =? e); bdestruct (0 =? 0); try lia; try lca. \n       rewrite H0. \n       rewrite H2. lca.\nQed.\n\n\n(* must use make_col_zero here instead of just as' col 0 = C0, since def requires stronger supp *)\nLemma col_add_each_inv : forall {n m} (col : nat) (as' : Matrix 1 m) (T : Matrix n m),\n  T = col_add_each col (make_col_zero col (-C1 .* as')) \n                   (col_add_each col (make_col_zero col as') T).\nProof. intros. \n       prep_matrix_equality. \n       unfold col_add_each, make_col_zero, Mmult, Mplus, get_vec, scale.\n       simpl. bdestruct (y =? col); bdestruct (col =? col); try lia; try lca. \nQed.\n\nLemma row_add_each_inv : forall {n m} (row : nat) (as' : Vector n) (T : Matrix n m),\n  T = row_add_each row (make_row_zero row (-C1 .* as')) \n                   (row_add_each row (make_row_zero row as') T).\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add_each, make_row_zero, Mmult, Mplus, get_row, scale.\n       simpl. bdestruct (x =? row); bdestruct (row =? row); try lia; try lca. \nQed.\n\n\n(* we can show that we get from col_XXX to row_XXX via transposing *)\n\nLemma get_vec_transpose : forall {n m} (A : Matrix n m) (i : nat),\n  (get_vec i A)⊤ = get_row i (A⊤).\nProof. intros. \n       prep_matrix_equality. \n       unfold get_vec, get_row, transpose. \n       easy.\nQed.\n\nLemma get_row_transpose : forall {n m} (A : Matrix n m) (i : nat),\n  (get_row i A)⊤ = get_vec i (A⊤).\nProof. intros. \n       prep_matrix_equality. \n       unfold get_vec, get_row, transpose. \n       easy.\nQed.\n\nLemma col_swap_transpose : forall {n m} (A : Matrix n m) (x y : nat),\n  (col_swap A x y)⊤ = row_swap (A⊤) x y.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_swap, col_swap, transpose. \n       easy. \nQed.\n\nLemma row_swap_transpose : forall {n m} (A : Matrix n m) (x y : nat),\n  (row_swap A x y)⊤ = col_swap (A⊤) x y.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_swap, col_swap, transpose. \n       easy. \nQed.\n\nLemma col_scale_transpose : forall {n m} (A : Matrix n m) (x : nat) (a : C),\n  (col_scale A x a)⊤ = row_scale (A⊤) x a.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_scale, col_scale, transpose. \n       easy. \nQed.\n\nLemma row_scale_transpose : forall {n m} (A : Matrix n m) (x : nat) (a : C),\n  (row_scale A x a)⊤ = col_scale (A⊤) x a.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_scale, col_scale, transpose. \n       easy. \nQed.\n\nLemma col_add_transpose : forall {n m} (A : Matrix n m) (col to_add : nat) (a : C),\n  (col_add A col to_add a)⊤ = row_add (A⊤) col to_add a.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add, col_add, transpose. \n       easy. \nQed.\n\nLemma row_add_transpose : forall {n m} (A : Matrix n m) (row to_add : nat) (a : C),\n  (row_add A row to_add a)⊤ = col_add (A⊤) row to_add a.\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add, col_add, transpose. \n       easy. \nQed.\n\nLemma col_add_many_transpose : forall {n m} (A : Matrix n m) (col : nat) (as' : Vector m),\n  (col_add_many col as' A)⊤ = row_add_many col (as'⊤) (A⊤).\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add_many, col_add_many, transpose. \n       bdestruct (x =? col); try easy. \n       apply Csum_simplify; try easy.\n       unfold gen_new_vec, gen_new_row, get_vec, get_row, scale.\n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       easy. \nQed.\n\nLemma row_add_many_transpose : forall {n m} (A : Matrix n m) (row : nat) (as' : Matrix 1 n),\n  (row_add_many row as' A)⊤ = col_add_many row (as'⊤) (A⊤).\nProof. intros. \n       prep_matrix_equality. \n       unfold row_add_many, col_add_many, transpose. \n       bdestruct (y =? row); try easy. \n       apply Csum_simplify; try easy.\n       unfold gen_new_vec, gen_new_row, get_vec, get_row, scale.\n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       easy. \nQed.\n\nLemma col_add_each_transpose : forall {n m} (A : Matrix n m) (col : nat) (as' : Matrix 1 m),\n  (col_add_each col as' A)⊤ = row_add_each col (as'⊤) (A⊤).\nProof. intros. \n       unfold row_add_each, col_add_each. \n       rewrite Mplus_transpose.\n       rewrite Mmult_transpose. \n       rewrite get_vec_transpose. \n       easy.\nQed.\n\nLemma row_add_each_transpose : forall {n m} (A : Matrix n m) (row : nat) (as' : Vector n),\n  (row_add_each row as' A)⊤ = col_add_each row (as'⊤) (A⊤).\nProof. intros. \n       unfold row_add_each, col_add_each. \n       rewrite Mplus_transpose.\n       rewrite Mmult_transpose. \n       rewrite get_row_transpose. \n       easy.\nQed.\n\nLemma swap_preserves_mul_lt : forall {n m o} (A : Matrix n m) (B : Matrix m o) (x y : nat),\n  x < y -> x < m -> y < m -> A × B = (col_swap A x y) × (row_swap B x y).\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult. \n       bdestruct (x <? m); try lia.\n       rewrite (le_plus_minus x m); try lia.\n       do 2 rewrite Csum_sum. \n       apply Csum_simplify. \n       apply Csum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x1 =? x); bdestruct (x1 =? y); try lia; try easy.   \n       destruct (m - x) as [| x'] eqn:E; try lia. \n       do 2 rewrite <- Csum_extend_l.\n       rewrite Cplus_comm.\n       rewrite (Cplus_comm (col_swap A x y x0 (x + 0)%nat * row_swap B x y (x + 0)%nat y0)%C _).\n       bdestruct ((y - x - 1) <? x'); try lia.  \n       rewrite (le_plus_minus (y - x - 1) x'); try lia. \n       do 2 rewrite Csum_sum.\n       do 2 rewrite <- Cplus_assoc.\n       apply Csum_simplify. \n       apply Csum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x + S x1 =? x); bdestruct (x + S x1 =? y); try lia; try easy. \n       destruct (x' - (y - x - 1)) as [| x''] eqn:E1; try lia. \n       do 2 rewrite <- Csum_extend_l.\n       rewrite Cplus_comm.\n       rewrite (Cplus_comm _ (col_swap A x y x0 (x + 0)%nat * row_swap B x y (x + 0)%nat y0)%C). \n       do 2 rewrite Cplus_assoc.\n       apply Csum_simplify.\n       do 2 rewrite <- plus_n_O. \n       unfold col_swap, row_swap.\n       bdestruct (x + S (y - x - 1) =? x); bdestruct (x + S (y - x - 1) =? y); \n         bdestruct (x =? x); try lia.\n       rewrite H5. lca. \n       apply Csum_eq_bounded.\n       intros. \n       unfold col_swap, row_swap.\n       bdestruct (x + S (y - x - 1 + S x1) =? x); \n         bdestruct (x + S (y - x - 1 + S x1) =? y); try lia; try easy.\nQed.           \n\n\nLemma swap_preserves_mul : forall {n m o} (A : Matrix n m) (B : Matrix m o) (x y : nat),\n  x < m -> y < m -> A × B = (col_swap A x y) × (row_swap B x y).\nProof. intros. bdestruct (x <? y).\n       - apply swap_preserves_mul_lt; easy.\n       - destruct H1.\n         + rewrite col_swap_same, row_swap_same; easy.\n         + rewrite col_swap_diff_order, row_swap_diff_order. \n           apply swap_preserves_mul_lt; lia.\nQed.\n\n\nLemma scale_preserves_mul : forall {n m o} (A : Matrix n m) (B : Matrix m o) (x : nat) (a : C),\n  A × (row_scale B x a) = (col_scale A x a) × B.\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult. \n       apply Csum_eq_bounded.\n       intros. \n       unfold col_scale, row_scale.\n       bdestruct (x1 =? x).\n       - rewrite Cmult_assoc.\n         lca. \n       - reflexivity. \nQed.        \n\n\nLemma col_add_preserves_mul_lt : forall {n m o} (A : Matrix n m) (B : Matrix m o) \n                                                (x y : nat) (a : C),\n   x < y -> x < m -> y < m -> A × (row_add B y x a) = (col_add A x y a) × B.\nProof. intros.  \n       prep_matrix_equality. \n       unfold Mmult.   \n       bdestruct (x <? m); try lia.\n       rewrite (le_plus_minus x m); try lia.       \n       do 2 rewrite Csum_sum.\n       apply Csum_simplify. \n       apply Csum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x1 =? y); bdestruct (x1 =? x); try lia; easy. \n       destruct (m - x) as [| x'] eqn:E; try lia. \n       do 2 rewrite <- Csum_extend_l.\n       rewrite Cplus_comm. \n       rewrite (Cplus_comm (col_add A x y a x0 (x + 0)%nat * B (x + 0)%nat y0)%C _).\n       bdestruct ((y - x - 1) <? x'); try lia.  \n       rewrite (le_plus_minus (y - x - 1) x'); try lia. \n       do 2 rewrite Csum_sum.\n       do 2 rewrite <- Cplus_assoc.\n       apply Csum_simplify. \n       apply Csum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x + S x1 =? y); bdestruct (x + S x1 =? x); try lia; easy. \n       destruct (x' - (y - x - 1)) as [| x''] eqn:E1; try lia. \n       do 2 rewrite <- Csum_extend_l.\n       rewrite Cplus_comm. \n       rewrite (Cplus_comm _ (col_add A x y a x0 (x + 0)%nat * B (x + 0)%nat y0)%C).\n       do 2 rewrite Cplus_assoc.\n       apply Csum_simplify. \n       unfold row_add, col_add.\n       do 2 rewrite <- plus_n_O.\n       bdestruct (x =? y); bdestruct (x =? x); \n         bdestruct (x + S (y - x - 1) =? y); bdestruct (x + S (y - x - 1) =? x); try lia. \n       rewrite H6. lca. \n       apply Csum_eq_bounded.\n       intros. \n       unfold row_add, col_add.\n       bdestruct (x + S (y - x - 1 + S x1) =? y); \n         bdestruct (x + S (y - x - 1 + S x1) =? x); try lia; easy. \nQed.\n\nLemma col_add_preserves_mul : forall {n m o} (A : Matrix n m) (B : Matrix m o) \n                                             (x y : nat) (a : C),\n   x < m -> y < m -> A × (row_add B y x a) = (col_add A x y a) × B.\nProof. intros. bdestruct (x <? y).\n       - apply col_add_preserves_mul_lt; easy.\n       - destruct H1.\n         + rewrite col_add_double, row_add_double. \n           apply scale_preserves_mul.\n         + rewrite (swap_preserves_mul A _ y (S m0)); try easy.\n           rewrite (swap_preserves_mul _ B (S m0) y); try easy.\n           rewrite col_add_swap.\n           rewrite row_add_swap.\n           rewrite row_swap_diff_order.\n           rewrite col_swap_diff_order.\n           apply col_add_preserves_mul_lt; lia. \nQed.\n\n\n(* used for the below induction where basically we may have to go from n to (n + 2) *)\n(* might want to move this somewhere else. cool technique though! Maybe coq already has something like this  *) \nDefinition skip_count (skip i : nat) : nat :=\n  if (i <? skip) then i else S i.\n\n\nLemma skip_count_le : forall (skip i : nat),\n  i <= skip_count skip i.\nProof. intros; unfold skip_count. \n       bdestruct (i <? skip); lia.\nQed.\n\nLemma skip_count_not_skip : forall (skip i : nat),\n  skip <> skip_count skip i. \nProof. intros; unfold skip_count. \n       bdestruct (i <? skip); try lia. \nQed.\n\n\nLemma skip_count_mono : forall (skip i1 i2 : nat),\n  i1 < i2 -> skip_count skip i1 < skip_count skip i2.\nProof. intros; unfold skip_count. \n       bdestruct (i1 <? skip); bdestruct (i2 <? skip); try lia. \nQed.\n\n\n\nLemma cam_ca_switch : forall {n m} (T : Matrix n m) (as' : Vector m) (col to_add : nat) (c : C),\n  as' col 0 = C0 -> to_add <> col -> \n  col_add (col_add_many col as' T) col to_add c = \n  col_add_many col as' (col_add T col to_add c).\nProof. intros. \n       prep_matrix_equality. \n       unfold col_add, col_add_many.\n       bdestruct (y =? col); try lia; try easy.\n       repeat rewrite <- Cplus_assoc.\n       apply Csum_simplify; try easy.\n       bdestruct (to_add =? col); try lia.\n       rewrite Cplus_comm.\n       apply Csum_simplify; try easy. \n       unfold gen_new_vec.\n       do 2 rewrite Msum_Csum.\n       apply Csum_eq_bounded; intros. \n       unfold get_vec, scale; simpl.\n       bdestruct (x0 =? col); try lca. \n       rewrite H4, H; lca.\nQed.\n\n\n\nLemma col_add_many_preserves_mul_some : forall (n m o e col : nat) \n                                               (A : Matrix n m) (B : Matrix m o) (v : Vector m),\n  WF_Matrix v -> (skip_count col e) < m -> col < m -> \n  (forall i : nat, (skip_count col e) < i -> v i 0 = C0) -> v col 0 = C0 ->\n  A × (row_add_each col v B) = (col_add_many col v A) × B.  \nProof. induction e as [| e].\n       - intros.\n         destruct m; try easy.\n         rewrite (col_add_many_col_add col (skip_count col 0) _ _); try easy.\n         rewrite <- (col_add_many_0 col A (make_row_zero (skip_count col 0) v)).\n         rewrite (row_add_each_row_add col (skip_count col 0) _ _); try easy.\n         rewrite <- (row_add_each_0 col B (make_row_zero (skip_count col 0) v)).\n         apply col_add_preserves_mul; try easy.\n         apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         destruct j; try lia. \n         unfold make_row_zero.\n         bdestruct (i =? skip_count col 0); try lia; try easy. \n         destruct col; destruct i; try easy.\n         rewrite H2; try easy. unfold skip_count in *. \n         bdestruct (0 <? 0); lia. \n         rewrite H2; try easy.\n         unfold skip_count in *. simpl; lia. \n         all : try apply skip_count_not_skip.\n         intros. destruct y; try easy.\n         apply H; lia. \n         unfold mat_equiv, make_row_zero; intros. \n         destruct j; try lia. \n         bdestruct (i =? skip_count col 0); try lia; try easy. \n         destruct col; try easy.\n         destruct i; try easy.\n         rewrite H2; try easy. \n         unfold skip_count in *; simpl in *; lia. \n         rewrite H2; try easy.\n         unfold skip_count in *; simpl in *; lia. \n       - intros. \n         destruct m; try easy.\n         rewrite (col_add_many_col_add col (skip_count col (S e)) _ _); try easy.\n         rewrite (row_add_each_row_add col (skip_count col (S e)) _ _); try easy.\n         rewrite col_add_preserves_mul; try easy.\n         rewrite cam_ca_switch. \n         rewrite IHe; try easy; auto with wf_db.\n         assert (p : e < S e). lia. \n         apply (skip_count_mono col) in p.\n         lia. \n         intros.\n         unfold make_row_zero.\n         bdestruct (i =? skip_count col (S e)); try easy. \n         unfold skip_count in *. \n         bdestruct (e <? col); bdestruct (S e <? col); try lia. \n         all : try (apply H2; lia). \n         bdestruct (i =? col); bdestruct (S e =? col); try lia. \n         rewrite H8; apply H3.\n         apply H2. lia. \n         unfold make_row_zero.\n         bdestruct (col =? skip_count col (S e)); try easy.\n         unfold make_row_zero.\n         bdestruct (col =? skip_count col (S e)); try easy.\n         assert (H4 := skip_count_not_skip). auto.\n         all : try apply skip_count_not_skip.\n         intros. \n         destruct y; try easy.\n         apply H; lia. \nQed.\n\n\n\nLemma col_add_many_preserves_mul: forall (n m o col : nat) \n                                               (A : Matrix n m) (B : Matrix m o) (v : Vector m),\n  WF_Matrix v -> col < m -> v col 0 = C0 ->\n  A × (row_add_each col v B) = (col_add_many col v A) × B.  \nProof. intros. \n       destruct m; try easy.\n       destruct m.\n       - assert (H' : v = Zero).\n         apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         destruct i; destruct j; destruct col; try lia; easy.\n         rewrite <- col_add_many_0, <- row_add_each_0; try easy.\n         rewrite H'; easy.\n       - apply (col_add_many_preserves_mul_some _ _ _ m col); try easy.\n         unfold skip_count.\n         bdestruct (m <? col); lia. \n         intros. \n         unfold skip_count in H2.\n         bdestruct (m <? col). \n         bdestruct (col =? (S m)); try lia. \n         bdestruct (i =? (S m)). \n         rewrite H5, <- H4. apply H1.\n         apply H; lia. \n         apply H; lia. \nQed.\n\n(* we can now prove this much more easily using transpose *)\nLemma col_add_each_preserves_mul: forall (n m o col : nat) (A : Matrix n m) \n                                                         (B : Matrix m o) (v : Matrix 1 m),\n  WF_Matrix v -> col < m -> v 0 col = C0 ->\n  A × (row_add_many col v B) = (col_add_each col v A) × B.  \nProof. intros. \n       assert (H' : ((B⊤) × (row_add_each col (v⊤) (A⊤)))⊤ = \n                               ((col_add_many col (v⊤) (B⊤)) × (A⊤))⊤).  \n       rewrite col_add_many_preserves_mul; auto with wf_db; try easy.\n       do 2 rewrite Mmult_transpose in H'. \n       rewrite row_add_each_transpose in H'. \n       rewrite col_add_many_transpose in H'. \n       repeat rewrite transpose_involutive in H'.\n       easy. \nQed.\n\n\nLemma col_swap_mult_r : forall {n} (A : Square n) (x y : nat),\n  x < n -> y < n -> WF_Matrix A -> \n  col_swap A x y = A × (row_swap (I n) x y).\nProof. intros.\n       assert (H2 := (swap_preserves_mul A (row_swap (I n) x y) x y)).\n       rewrite <- (Mmult_1_r _ _ (col_swap A x y)); auto with wf_db.\n       rewrite H2; try easy.\n       rewrite <- (row_swap_inv (I n) x y).\n       reflexivity. \nQed.\n\nLemma col_scale_mult_r : forall {n} (A : Square n) (x : nat) (a : C),\n  WF_Matrix A -> \n  col_scale A x a = A × (row_scale (I n) x a).\nProof. intros. \n       rewrite scale_preserves_mul.\n       rewrite Mmult_1_r; auto with wf_db. \nQed.\n\n\nLemma col_add_many_mult_r : forall {n} (A : Square n) (v : Vector n) (col : nat),\n  WF_Matrix A -> WF_Matrix v -> col < n -> v col 0 = C0 ->\n  col_add_many col v A = A × (row_add_each col v (I n)).\nProof. intros. \n       rewrite col_add_many_preserves_mul; try easy.\n       rewrite Mmult_1_r; auto with wf_db.\nQed.\n\n\nLemma col_add_each_mult_r : forall {n} (A : Square n) (v : Matrix 1 n) (col : nat),\n  WF_Matrix A -> WF_Matrix v -> col < n -> v 0 col = C0 ->\n  col_add_each col v A = A × (row_add_many col v (I n)).\nProof. intros. \n       rewrite col_add_each_preserves_mul; try easy.\n       rewrite Mmult_1_r; auto with wf_db.\nQed.\n\n\n\nLemma reduce_append_split : forall {n m} (T : Matrix n (S m)), \n  WF_Matrix T -> T = col_append (reduce_col T m) (get_vec m T).\nProof. intros. \n       prep_matrix_equality. \n       unfold col_append, get_vec, reduce_col.\n       bdestruct (y =? S m - 1); bdestruct (0 =? 0); bdestruct (y <? m); try lia; try easy. \n       rewrite H0. rewrite easy_sub; easy.\n       rewrite H; try lia. rewrite H; try lia. lca.\nQed.\n\n\nLemma smash_zero : forall {n m} (T : Matrix n m) (i : nat),\n  WF_Matrix T -> smash T (@Zero n i) = T. \nProof. intros. \n       prep_matrix_equality.\n       unfold smash, Zero. \n       bdestruct (y <? m); try easy.\n       rewrite H; try lia; easy.\nQed.\n\n\nLemma smash_assoc : forall {n m1 m2 m3}\n                           (T1 : Matrix n m1) (T2 : Matrix n m2) (T3 : Matrix n m3),\n  smash (smash T1 T2) T3 = smash T1 (smash T2 T3).\nProof. intros. \n       unfold smash.\n       prep_matrix_equality.\n       bdestruct (y <? m1 + m2); bdestruct (y <? m1); \n         bdestruct (y - m1 <? m2); try lia; try easy.\n       assert (H' : y - (m1 + m2) = y - m1 - m2).\n       lia. rewrite H'; easy.\nQed.\n\n\nLemma smash_append : forall {n m} (T : Matrix n m) (v : Vector n),\n  WF_Matrix T -> WF_Matrix v ->\n  col_append T v = smash T v.\nProof. intros. \n       unfold smash, col_append, WF_Matrix in *.\n       prep_matrix_equality. \n       bdestruct (y =? m); bdestruct (y <? m); try lia; try easy.\n       rewrite H1.\n       rewrite <- minus_diag_reverse; easy. \n       rewrite H0, H; try lia; try easy.\nQed.       \n\n\nLemma smash_reduce : forall {n m1 m2} (T1 : Matrix n m1) (T2 : Matrix n (S m2)),\n  reduce_col (smash T1 T2) (m1 + m2) = smash T1 (reduce_col T2 m2).\nProof. intros. \n       prep_matrix_equality. \n       unfold reduce_col, smash. \n       bdestruct (y <? m1 + m2); bdestruct (y <? m1); bdestruct (1 + y <? m1);\n         bdestruct (y - m1 <? m2); try lia; try easy.\n       assert (H' : 1 + y - m1 = 1 + (y - m1)). lia.  \n       rewrite H'; easy.\nQed.\n\n\nLemma split : forall {n m} (T : Matrix n (S m)), \n  T = smash (get_vec 0 T) (reduce_col T 0).\nProof. intros. \n       prep_matrix_equality. \n       unfold smash, get_vec, reduce_col.\n       bdestruct (y <? 1); bdestruct (y =? 0); bdestruct (y - 1 <? 0); try lia; try easy.\n       rewrite H0; easy. \n       destruct y; try lia. \n       simpl. assert (H' : y - 0 = y). lia. \n       rewrite H'; easy.\nQed.\n\n\n(* We can now show that matrix_equivalence is decidable *)\nLemma vec_equiv_dec : forall {n : nat} (A B : Vector n), \n    { A == B } + { ~ (A == B) }.\nProof. induction n as [| n'].\n       - left; easy.\n       - intros. destruct (IHn' (reduce_vecn A) (reduce_vecn B)).\n         + destruct (Ceq_dec (A n' 0) (B n' 0)).\n           * left. \n             unfold mat_equiv in *.\n             intros.\n             bdestruct (i =? n'); bdestruct (n' <? i); try lia. \n             rewrite H1.\n             destruct j.\n             apply e. lia.\n             apply (m i j) in H0.\n             unfold reduce_vecn in H0.\n             assert (H' : i <? S n' - 1 = true).\n             { apply leb_correct. lia. }\n             rewrite H' in H0.\n             apply H0. lia. \n           * right. unfold not. \n             intros. unfold mat_equiv in H.\n             apply n. apply H; lia. \n         + right. \n           unfold not in *. \n           intros. apply n.\n           unfold mat_equiv in *.\n           intros. unfold reduce_vecn.\n           assert (H' : i <? S n' - 1 = true).\n           { apply leb_correct. lia. }\n           rewrite H'. \n           apply H; lia. \nQed.\n\n\nLemma mat_equiv_dec : forall {n m : nat} (A B : Matrix n m), \n    { A == B } + { ~ (A == B) }.\nProof. induction m as [| m']. intros.  \n       - left. easy.\n       - intros. destruct (IHm' (reduce_col A m') (reduce_col B m')).\n         + destruct (vec_equiv_dec (get_vec m' A) (get_vec m' B)).\n           * left. \n             unfold mat_equiv in *.\n             intros. \n             bdestruct (j =? m'); bdestruct (m' <? j); try lia.\n             ++ apply (m0 i 0) in H.\n                do 2 rewrite get_vec_conv in H.\n                rewrite H1. easy. lia. \n             ++ apply (m i j) in H.\n                unfold reduce_col in H.\n                bdestruct (j <? m'); try lia; try easy.\n                lia. \n           * right. \n             unfold not, mat_equiv in *.\n             intros. apply n0.\n             intros. \n             destruct j; try easy.\n             do 2 rewrite get_vec_conv.\n             apply H; lia.\n         + right. \n           unfold not, mat_equiv, reduce_col in *.\n           intros. apply n0. \n           intros. \n           bdestruct (j <? m'); try lia.\n           apply H; lia.            \nQed.\n \n\n(* we can also now prove some useful lemmas about nonzero vectors *)\nLemma last_zero_simplification : forall {n : nat} (v : Vector n),\n  WF_Matrix v -> v (n - 1) 0 = C0 -> v = reduce_vecn v.\nProof. intros. unfold reduce_vecn.\n       prep_matrix_equality.\n       bdestruct (x <? (n - 1)).\n       - easy.\n       - unfold WF_Matrix in H.\n         destruct H1.\n         + destruct y. \n           * rewrite H0, H. reflexivity.\n             left. nia. \n           * rewrite H. rewrite H. reflexivity.\n             right; nia. right; nia.\n         + rewrite H. rewrite H. reflexivity.\n           left. nia. left. nia.\nQed.\n\n\nLemma zero_reduce : forall {n : nat} (v : Vector (S n)) (x : nat),\n  WF_Matrix v -> (v = Zero <-> (reduce_row v x) = Zero /\\ v x 0 = C0).\nProof. intros. split.    \n       - intros. rewrite H0. split.\n         + prep_matrix_equality. unfold reduce_row. \n           bdestruct (x0 <? x); easy. \n         + easy.\n       - intros [H0 H1]. \n         prep_matrix_equality.\n         unfold Zero.\n         bdestruct (x0 =? x).\n         + rewrite H2. \n           destruct y; try easy.          \n           apply H; lia.\n         + bdestruct (x0 <? x). \n           * assert (H' : (reduce_row v x) x0 y = C0). \n             { rewrite H0. easy. }\n             unfold reduce_row in H'.\n             bdestruct (x0 <? x); try lia; try easy.\n           * destruct x0; try lia. \n             assert (H'' : (reduce_row v x) x0 y = C0). \n             { rewrite H0. easy. }\n             unfold reduce_row in H''.\n             bdestruct (x0 <? x); try lia. \n             rewrite <- H''. easy.\nQed.\n  \n\nLemma nonzero_vec_nonzero_elem : forall {n} (v : Vector n),\n  WF_Matrix v -> v <> Zero -> exists x, v x 0 <> C0.\nProof. induction n as [| n']. \n       - intros. \n         assert (H' : v = Zero).\n         { prep_matrix_equality.\n           unfold Zero.\n           unfold WF_Matrix in H.\n           apply H.\n           left. lia. }\n         easy.\n       - intros.   \n         destruct (Ceq_dec (v n' 0) C0). \n         + destruct (vec_equiv_dec (reduce_row v n') Zero). \n           * assert (H' := H). \n             apply (zero_reduce _ n') in H'.\n             destruct H'.\n             assert (H' : v = Zero). \n             { apply H2.\n               split. \n               apply mat_equiv_eq; auto with wf_db.\n               easy. }\n             easy.             \n           * assert (H1 : exists x, (reduce_row v n') x 0 <> C0).\n             { apply IHn'. \n               assert (H1' := (@WF_reduce_row (S n') 1 n')).\n               rewrite easy_sub in *.\n               apply H1'; try lia; try easy.\n               unfold not in *. intros. apply n. \n               rewrite H1. easy. }\n             destruct H1. \n             exists x. \n             rewrite (last_zero_simplification v); try easy.\n             rewrite rvn_is_rr_n.\n             all : rewrite easy_sub.\n             apply H1. \n             apply e.\n         + exists n'. \n           apply n.\nQed.\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\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\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\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\n\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\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\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\nHint Resolve WF_e_i : 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\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       rewrite easy_sub. \n       bdestruct (x <? 0); try lia.  \n       rewrite <- Csum_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 Csum_eq_bounded. \n       intros. bdestruct (x0 <? 0); try lia; try easy.\nQed.\n\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 <- Csum_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         rewrite easy_sub.\n         apply Csum_eq_bounded. \n         intros. bdestruct (x0 <? n); try lia; try easy.\n       - rewrite <- Csum_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         rewrite easy_sub.\n         apply Csum_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 Csum_eq_bounded. \n       intros. \n       unfold col_append, row_append. \n       bdestruct (x0 =? m); try lia; try easy.\nQed.\n\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\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 (Csum_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 Csum_0; try reflexivity.\n         intros. rewrite andb_false_r. \n         rewrite Cmult_0_r. reflexivity.\nQed.     \n\n\nLemma zero_vec_lin_dep : forall {n m} (T : Matrix n m) (i : nat),\n  i < m -> (get_vec i T) = Zero -> linearly_dependent T.\nProof. intros.\n       unfold linearly_dependent in *; intros. \n       exists (@e_i m i).\n       split. apply WF_e_i.\n       split. \n       unfold not; intros. \n       assert (H' : (@e_i m i) i 0 = C0).\n       { rewrite H1; 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\n\nLemma lin_indep_nonzero_cols : forall {n m} (T : Matrix n m),\n  linearly_independent T -> (forall i, i < m -> (get_vec i T) <> Zero). \nProof. intros. unfold not. intros. \n       apply (zero_vec_lin_dep T i) in H0; try easy.\n       apply lindep_implies_not_linindep in H0.\n       easy. \nQed.\n\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         rewrite easy_sub in *.\n         apply WF_row_append; try easy.\n         prep_matrix_equality. \n         unfold Mmult, row_append, Zero. \n         rewrite <- Csum_extend_r. \n         bdestruct (m =? S m - 1); 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         rewrite easy_sub.\n         apply Csum_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       rewrite easy_sub. \n       bdestruct (x =? m); try easy.\n       unfold WF_Matrix in H0. \n       unfold Zero; simpl. \n       apply H0. lia. \nQed.\n\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 Csum_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         assert (H' : (Init.Nat.add m1 (S m2')) = (S (Init.Nat.add m1 m2'))). { lia. }\n         rewrite H' in H.\n         apply H1 in H.\n         assert (H1' : S (Nat.add m1 m2') = Nat.add m1 (S m2')). { lia. } \n         rewrite H1' in H. \n         rewrite smash_reduce in H.\n         apply (IHm2' m1 A1 (reduce_col A2 m2')).\n         rewrite easy_sub in *.\n         assert (H2' : (m1 + S m2' - 1) = m1 + m2'). { lia. }\n         rewrite H2' in *; easy.\nQed.\n\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\nLemma lin_indep_swap : forall {n m} (T : Matrix n m) (x y : nat),\n  x < m -> y < m -> linearly_independent T -> linearly_independent (col_swap T x y).\nProof. 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_swap_conv : forall {n m} (T : Matrix n m) (x y : nat),\n  x < m -> y < m -> linearly_independent (col_swap T x y) -> linearly_independent T.\nProof. intros. \n       rewrite (col_swap_inv T x y).\n       apply lin_indep_swap; easy.\nQed.\n\n\nLemma lin_indep_scale : forall {n m} (T : Matrix n m) (x : nat) (c : C),\n  c <> C0 -> linearly_independent T -> linearly_independent (col_scale T x c).\nProof. 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\n\nLemma lin_indep_scale_conv : forall {n m} (T : Matrix n m) (x : nat) (c : C),\n  c <> C0 -> linearly_independent (col_scale T x c) -> linearly_independent T.\nProof. intros. \n       rewrite (col_scale_inv T x c); try easy.\n       apply lin_indep_scale; try apply nonzero_div_nonzero; easy.\nQed.\n\n\nLemma lin_indep_add : forall {n m} (T : Matrix n m) (x y : nat) (c : C),\n  x <> y -> x < m -> y < m -> linearly_independent T -> linearly_independent (col_add T x y c).\nProof. intros.\n       unfold linearly_independent in *.\n       intros.  \n       rewrite <- col_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\n\n\n\nLemma lin_indep_col_add_many_some : forall (e n m col : nat) (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  linearly_independent T -> linearly_independent (col_add_many col as' T).\nProof. induction e as [| e].\n       - intros. \n         rewrite (col_add_many_col_add _ (skip_count col 0)); \n           try lia; try easy.  \n         apply lin_indep_add; 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 Csum_simplify; try easy.\n           rewrite Msum_Csum.\n           apply Csum_0_bounded; 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         rewrite (col_add_many_col_add _ (skip_count col (S e))); \n           try lia; try easy.\n         apply lin_indep_add; 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 H7, H9. 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 lin_indep_col_add_many : forall (n m col : nat) (T : Matrix n m) (as' : Vector m),\n  col < m -> as' col 0 = C0 -> linearly_independent T -> \n  linearly_independent (col_add_many col as' T).\nProof. 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 (lin_indep_col_add_many_some m); try lia; try easy.\n           unfold skip_count. bdestruct (m <? col); lia. \n           intros. \n           unfold skip_count in H3; rewrite H2 in H3. \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 H7, <- H2; easy.\n           unfold make_WF. \n           bdestruct (col =? col); bdestruct (col <? S (S m)); try lia; auto. \n         + apply (lin_indep_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 H3.\n           bdestruct (m <? col); try lia. \n           bdestruct (i <? S (S m)); try lia; try easy.\n           unfold make_WF. \n           bdestruct (col =? col); bdestruct (col <? S (S m)); try lia; auto. \nQed.\n\n\n\nLemma lin_indep_col_add_many_conv : forall (n m col : nat) (T : Matrix n m) (as' : Vector m),\n  col < m -> as' col 0 = C0 -> \n  linearly_independent (col_add_many col as' T) ->\n  linearly_independent T.\nProof. intros. \n       rewrite (col_add_many_inv T col as'); try easy.\n       apply lin_indep_col_add_many; try easy. \n       unfold scale; rewrite H0.\n       lca. \nQed.\n\n\n\nLemma lin_indep_col_add_each_some : forall (e n m col : nat) (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  linearly_independent T -> linearly_independent (col_add_each col as' T).\nProof. induction e as [| e].\n       - intros.\n         rewrite (col_add_each_col_add _ (skip_count col 0)); try lia. \n         apply lin_indep_add; 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         rewrite (col_add_each_col_add _ (skip_count col (S e))); try lia. \n         apply lin_indep_add; 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 H8, H10. 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       \n        \n         \nLemma lin_indep_col_add_each : forall (n m col : nat) (as' : Matrix 1 (S m)) \n                                          (T : Matrix n (S m)),\n  col < (S m) -> WF_Matrix as' -> linearly_independent T -> \n  linearly_independent (col_add_each col (make_col_zero col as') T).\nProof. intros. \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 (lin_indep_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 H2 in H3; unfold skip_count in H3.\n           bdestruct (m <? S m); try lia. \n           rewrite H0; try lia; easy.\n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\n         + apply (lin_indep_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 H3.\n           bdestruct (m <? col); try lia. \n           apply H0; lia. \n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\nQed.\n\n\nLemma lin_dep_swap : forall {n m} (T : Matrix n m) (x y : nat),\n  x < m -> y < m -> linearly_dependent T -> linearly_dependent (col_swap T x y).\nProof. unfold linearly_dependent in *.\n       intros. \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 \n\nLemma lin_dep_swap_conv : forall {n m} (T : Matrix n m) (x y : nat),\n  x < m -> y < m -> linearly_dependent (col_swap T x y) -> linearly_dependent T.\nProof. intros. \n       rewrite (col_swap_inv T x y).\n       apply lin_dep_swap; easy.\nQed.\n\n\nLemma lin_dep_scale : forall {n m} (T : Matrix n m) (x : nat) (c : C),\n  linearly_dependent T -> linearly_dependent (col_scale T x c).\nProof. intros. \n       destruct (Ceq_dec c C0).\n       - bdestruct (x <? m).\n         + apply (zero_vec_lin_dep _ x); try easy.\n           rewrite e; unfold get_vec, col_scale.\n           prep_matrix_equality. \n           bdestruct (y =? 0); bdestruct (x =? x); try lia; lca. \n         + unfold linearly_dependent, col_scale in *.\n           destruct H as [a [H [H1 H2]]].\n           exists a. split; try easy.\n           split; try easy.\n           rewrite <- H2.\n           prep_matrix_equality. \n           unfold Mmult. \n           apply Csum_eq_bounded. \n           intros. \n           bdestruct (x1 =? x); try lia; easy. \n       -  unfold linearly_dependent in *.\n          destruct H 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 H. \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\n\nLemma lin_dep_scale_conv : forall {n m} (T : Matrix n m) (x : nat) (c : C),\n  c <> C0 -> linearly_dependent (col_scale T x c) -> linearly_dependent T. \nProof. intros. \n       rewrite (col_scale_inv T x c); try easy.\n       apply lin_dep_scale; easy. \nQed.\n\n\nLemma lin_dep_add : forall {n m} (T : Matrix n m) (x y : nat) (c : C),\n  x <> y -> x < m -> y < m -> linearly_dependent T -> linearly_dependent (col_add T x y c).\nProof. 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 col_add_preserves_mul; try easy.\n       rewrite <- (col_add_inv T x y c); try lia; easy.\nQed.\n\n\nLemma lin_dep_col_add_many_some : forall (e n m col : nat) (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  linearly_dependent T -> linearly_dependent (col_add_many col as' T).\nProof. induction e as [| e].\n       - intros. \n         rewrite (col_add_many_col_add _ (skip_count col 0)); \n           try lia; try easy.  \n         apply lin_dep_add; 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 Csum_simplify; try easy.\n           rewrite Msum_Csum.\n           apply Csum_0_bounded; 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         rewrite (col_add_many_col_add _ (skip_count col (S e))); \n           try lia; try easy.\n         apply lin_dep_add; 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 H7, H9. 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 lin_dep_col_add_many : forall (n m col : nat) (T : Matrix n m) (as' : Vector m),\n  col < m -> as' col 0 = C0 -> linearly_dependent T -> \n  linearly_dependent (col_add_many col as' T).\nProof. 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 (lin_dep_col_add_many_some m); try lia; try easy.\n           unfold skip_count. bdestruct (m <? col); lia. \n           intros. \n           unfold skip_count in H3; rewrite H2 in H3. \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 H7, <- H2; easy.\n           unfold make_WF. \n           bdestruct (col =? col); bdestruct (col <? S (S m)); try lia; auto. \n         + apply (lin_dep_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 H3.\n           bdestruct (m <? col); try lia. \n           bdestruct (i <? S (S m)); try lia; try easy.\n           unfold make_WF. \n           bdestruct (col =? col); bdestruct (col <? S (S m)); try lia; auto. \nQed.\n\n\nLemma lin_dep_col_add_many_conv : forall (n m col : nat) (T : Matrix n m) (as' : Vector m),\n  col < m -> as' col 0 = C0 -> \n  linearly_dependent (col_add_many col as' T) ->\n  linearly_dependent T.\nProof. intros. \n       rewrite (col_add_many_inv T col as'); try easy.\n       apply lin_dep_col_add_many; try easy. \n       unfold scale; rewrite H0.\n       lca. \nQed.\n\n\nLemma lin_dep_col_add_each_some : forall (e n m col : nat) (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  linearly_dependent T -> linearly_dependent (col_add_each col as' T).\nProof. induction e as [| e].\n       - intros.\n         rewrite (col_add_each_col_add _ (skip_count col 0)); try lia. \n         apply lin_dep_add; 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         assert (H' := skip_count_not_skip col 0). auto.\n         intros. destruct x; try easy.\n         apply H; lia.\n       - intros.  \n         rewrite (col_add_each_col_add _ (skip_count col (S e))); try lia. \n         apply lin_dep_add; 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 H8, H10. 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         apply skip_count_not_skip.\n         intros. destruct x; try easy.\n         apply H; lia.\nQed.\n       \n        \n         \nLemma lin_dep_col_add_each : forall (n m col : nat) (as' : Matrix 1 (S m)) \n                                          (T : Matrix n (S m)),\n  col < (S m) -> WF_Matrix as' -> linearly_dependent T -> \n  linearly_dependent (col_add_each col (make_col_zero col as') T).\nProof. intros. \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 (lin_dep_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 H2 in H3; unfold skip_count in H3.\n           bdestruct (m <? S m); try lia. \n           rewrite H0; try lia; easy.\n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\n         + apply (lin_dep_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 H3.\n           bdestruct (m <? col); try lia. \n           apply H0; lia. \n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\nQed.\n\n\n\nLemma lin_dep_col_add_each_conv : forall (n m col : nat) (as' : Matrix 1 (S m)) \n                                          (T : Matrix n (S m)),\n  col < (S m) -> WF_Matrix as' -> \n  linearly_dependent (col_add_each col (make_col_zero col as') T) ->\n  linearly_dependent T.\nProof. intros. \n       rewrite (col_add_each_inv col as').\n       apply lin_dep_col_add_each; auto with wf_db.\nQed.\n\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. rewrite easy_sub.\n         apply WF_scale.\n         assert (H' := (@WF_reduce_row (S m) 1 x a)).\n         rewrite easy_sub in *.\n         apply H'; easy.\n         apply mat_equiv_eq; auto with wf_db.\n         apply WF_mult.\n         assert (H' := (@WF_reduce_col n (S m) x T)).\n         rewrite easy_sub in *.\n         apply H'; try lia; try easy.\n         rewrite easy_sub in *.\n         apply WF_scale.\n         assert (H' := (@WF_reduce_row (S m) 1 x a)).\n         rewrite easy_sub in *.\n         apply H'; try lia; try easy.\n         rewrite easy_sub.\n         rewrite Mscale_mult_dist_r.  \n         unfold mat_equiv; intros. \n         unfold Mmult, scale.\n         assert (H' : (Csum (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 Csum_sum.\n           rewrite <- H''. \n           assert (H2' : S m = x + S (m - x)). lia. \n           rewrite H2'. \n           rewrite Csum_sum.\n           rewrite <- Csum_extend_l.\n           rewrite <- Cplus_assoc.\n           apply Csum_simplify. \n           apply Csum_eq_bounded.\n           intros. unfold reduce_col, reduce_row. \n           bdestruct (x0 <? x); try lia; easy.\n           rewrite Cplus_comm.\n           apply Csum_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 Csum_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' : (Csum (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 (lin_dep_col_add_each_conv _ _  col (-C1 .* (get_row 0 T))); \n         auto with wf_db; try lia.\n       unfold linearly_dependent in *.\n       destruct H2 as [a [H3 [H4 H5]]]. \n       repeat rewrite easy_sub in *.\n       exists (row_wedge a (@Zero 1 1) col).\n       split. \n       - rewrite easy_sub in *.\n         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 easy_sub in *; easy. \n         + repeat rewrite easy_sub 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 Csum_0_bounded. \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 easy_sub in *; rewrite H5. easy.\n             rewrite <- H0'.\n             unfold Mmult, reduce_row, reduce_col.\n             repeat rewrite easy_sub in *.\n             assert (p : S m = col + (S m - col)). lia.\n             rewrite p.\n             rewrite Csum_sum.\n             assert (p1 : S m - col = S (m - col)). lia. \n             rewrite p1. \n             rewrite <- Csum_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.\n             rewrite Csum_sum.\n             rewrite <- p2.\n             apply Csum_simplify.\n             apply Csum_eq_bounded; intros. \n             bdestruct (x <? col); bdestruct (x =? col); try lia.\n             rewrite H'. lca. \n             rewrite <- Cplus_0_l.\n             apply Csum_simplify; try lca.\n             apply Csum_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\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 (S 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       { repeat rewrite easy_sub in *; apply H'; try easy. }\n       repeat rewrite easy_sub in *.\n       apply (lin_dep_col_add_many_conv _ _ col _ v); try easy.\n       destruct (Ceq_dec ((col_add_many col v T) 0 col) C0).\n       - apply (zero_vec_lin_dep _ col); try lia. \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 Csum_simplify. \n         easy. unfold gen_new_vec.\n         do 2 rewrite Msum_Csum.\n         apply Csum_eq_bounded; intros. \n         unfold scale, get_vec; lca.  \n       - apply (lin_dep_scale_conv _ col (/ (col_add_many col v T 0 col))); \n           try apply nonzero_div_nonzero; try easy.\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 Csum_simplify; try easy.\n             do 2 rewrite Msum_Csum. \n             apply Csum_eq_bounded; intros. \n             bdestruct (i <? 0); try lia; easy. }\n           rewrite r. \n           rewrite easy_sub in *. \n           rewrite (H0' i); lca. \n         + rewrite col_scale_reduce_col_same; try easy.\n           rewrite col_add_many_reduce_col_same. \n           repeat rewrite easy_sub in *. 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             do 2 rewrite easy_sub in *.\n             apply H''.\n             apply IHm'; try easy.\n             assert (H0' := (@WF_reduce_col n' (S m'))).\n             rewrite easy_sub in *.\n             apply H0'; try lia.\n             assert (H1' := (@WF_reduce_row (S n') (S m'))).\n             rewrite easy_sub in *.\n             apply H1'; try lia; easy. \n             assert (H1' := (@WF_reduce_row (S n') (S m'))).\n             rewrite easy_sub in *.\n             apply H1'; try lia; easy. }\n           apply lin_dep_gen_elem in H'. \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. \n             repeat rewrite easy_sub in *; easy.\n             assert (H' := (IHm' n' (reduce_row (reduce_col T i) 0))).\n             repeat rewrite easy_sub in *.\n             apply H'; try lia. \n             assert (H1' := (@WF_reduce_row (S n') m')).\n             rewrite easy_sub in *; apply H1'; try lia. \n             assert (H2' := (@WF_reduce_col (S n') (S m'))).\n             rewrite easy_sub in *; apply H2'; try lia; easy. \n           * apply WF_reduce_row; try lia; easy.\nQed.\n\n\n\n\nDefinition pad {n : nat} (A : Square n) (c : C) : Square (S n) :=\n  col_wedge (row_wedge A Zero 0) (c .* e_i 0) 0.\n\nLemma pad_conv : forall {n : nat} (A : Square n) (c : C) (i j : nat),\n  (pad A c) (S i) (S j) = A i j.\nProof. intros.\n       unfold pad, 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 easy_sub.\n       easy.\nQed.\n\nLemma WF_pad : forall {n : nat} (A : Square n) (c : C),\n  WF_Matrix A <-> WF_Matrix (pad A c).\nProof. unfold WF_Matrix, pad. 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 easy_sub. \n         bdestruct (x <? 0); bdestruct (x =? 0); try lia; try easy. \n         destruct x; try lia. \n         rewrite easy_sub.\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 easy_sub; easy.\nQed.\n\nLemma pad_mult : forall {n : nat} (A B : Square n) (c1 c2 : C),\n  pad (A × B) (c1 * c2)%C = (pad A c1) × (pad B c2).\nProof. intros. \n       prep_matrix_equality. \n       unfold pad, Mmult, col_wedge, row_wedge, e_i, scale.\n       bdestruct (y <? 0); bdestruct (y =? 0); bdestruct (x <? 0); \n         bdestruct (x =? 0); try lia; try easy.\n       bdestruct (x <? S n).\n       rewrite <- Csum_extend_l. simpl. \n       rewrite <- (Cplus_0_l (c1 * c2 * C1)).\n       rewrite Cplus_comm.\n       apply Csum_simplify; try lca. \n       rewrite Csum_0_bounded; try easy.\n       intros. lca. \n       simpl. \n       rewrite Csum_0_bounded; try easy.\n       destruct n; try lca. \n       intros. \n       bdestruct (x0 =? 0); try lca. \n       rewrite Csum_0_bounded; try lca.       \n       intros. bdestruct (x0 <? 0); bdestruct (x0 =? 0); try lia; lca. \n       rewrite Csum_0_bounded; try lca.\n       intros. bdestruct (x0 <? 0); bdestruct (x0 =? 0); try lia; lca. \n       rewrite <- Csum_extend_l. simpl. \n       rewrite Cmult_0_r, Cplus_0_l.\n       apply Csum_eq_bounded. \n       intros. \n       rewrite Nat.sub_0_r.\n       easy. \nQed.\n \nLemma pad_I : forall (n : nat), pad (I n) C1 = I (S n).\nProof. intros. \n       unfold pad, 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\nLemma padded : forall {n : nat} (A : Square (S n)) (c : C),\n  (forall (i j : nat), (i = 0 \\/ j = 0) /\\ i <> j -> A i j = C0) -> A 0 0 = c ->\n  exists a : Square n, pad a c = A.\nProof. intros.  \n       exists (reduce A 0 0).\n       unfold pad, reduce, 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 easy_sub in *.\n       bdestruct (x <? 0); bdestruct (y <? 0); try lia. \n       easy.\nQed.\n\n\n\nLemma lin_indep_pad : forall {n : nat} (A : Square n) (c : C),\n  linearly_independent (pad A c) -> linearly_independent A.\nProof. unfold linearly_independent.\n       intros. \n       assert (H2 : (pad A c) × (row_wedge a Zero 0) = Zero).\n       { prep_matrix_equality. \n         destruct x. unfold Mmult. \n         unfold Zero. apply Csum_0_bounded. \n         intros.\n         unfold pad, 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' : (A × a) x y = C0). \n         rewrite H1; easy.\n         rewrite p. \n         rewrite <- H2'.\n         unfold Mmult. rewrite <- Csum_extend_l.  \n         rewrite <- Cplus_0_l.\n         apply Csum_simplify.\n         unfold pad, row_wedge, col_wedge, e_i.\n         bdestruct (x <? 0); bdestruct (x =? 0); try lia. \n         rewrite H3; simpl. lca. \n         rewrite easy_sub. lca. \n         apply Csum_eq_bounded; intros. \n         rewrite pad_conv.\n         unfold row_wedge.\n         rewrite easy_sub. \n         easy. }\n       apply H in H2.\n       prep_matrix_equality. \n       assert (H3 : row_wedge a Zero 0 (S x) y = C0).\n       rewrite H2. easy.\n       unfold Zero. rewrite <- H3.\n       unfold row_wedge. \n       rewrite easy_sub.\n       easy.\n       apply WF_row_wedge; try lia; easy.\nQed.   \n         \n\nLemma lin_indep_ind_step1 : forall {n} (A : Square (S n)), \n  WF_Matrix A -> linearly_independent A -> \n  (exists B : Square (S n), WF_Matrix B /\\ linearly_independent (A × B) /\\\n                            (exists i, i < (S n) /\\ get_vec i (A × B) = e_i 0)).\nProof. intros. \n       assert (H1 : WF_Matrix (reduce_row A 0)).\n       { assert (H1' := (@WF_reduce_row (S n) (S n))).\n         rewrite easy_sub in *.\n         apply H1'; try lia; easy. }\n       assert (H2 : linearly_dependent (reduce_row A 0)).\n       { apply gt_dim_lindep; try lia. \n         apply H1. }\n       apply lin_dep_gen_elem in H2; try easy. \n       destruct H2 as [i [H2 H3]]. \n       destruct H3 as [v [H3 H4]].\n       apply (lin_indep_col_add_many (S n) (S n) i A (row_wedge v Zero i)) in H0; try easy.\n       destruct (Ceq_dec ((col_add_many i (row_wedge v Zero i) A) 0 i) C0).\n       - assert (H5 : 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         rewrite easy_sub in *.\n         easy. \n         assert (H6: 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 H5.\n           assert (p : (@Zero (S n) 1 (S i0) 0) = C0). easy.  \n           rewrite p.\n           rewrite <- (H5 i0).\n           unfold reduce_row.\n           bdestruct (i0 <? 0); try lia. \n           easy. }\n         apply zero_vec_lin_dep in H6; try easy.\n         apply lindep_implies_not_linindep in H6.\n         easy. \n       - apply (lin_indep_scale (col_add_many i (row_wedge v Zero i) A) i\n                 (/ col_add_many i (row_wedge v Zero i) A 0 i)) in H0.\n         assert (H6 : 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         rewrite easy_sub in *.\n         easy. \n         rewrite col_add_many_reduce_row in H6. \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. apply WF_mult; auto with wf_db.\n         apply WF_row_add_each; auto with wf_db.\n         apply WF_row_wedge; auto with wf_db; lia.\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 (H10 : col_add_many i (row_wedge v Zero i) A (S i0) i = C0).\n         rewrite <- (H6 i0).\n         unfold reduce_row.\n         bdestruct (i0 <? 0); try lia; easy.\n         rewrite H10. 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. \n         apply nonzero_div_nonzero; easy.\n       - unfold row_wedge.\n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy.\nQed.         \n\n\nLemma lin_indep_ind_step2 : forall {n} (A : Square (S n)), \n  WF_Matrix A -> linearly_independent A -> (exists i, i < (S n) /\\ get_vec i A = e_i 0) ->\n  (exists B : Square (S n), WF_Matrix B /\\ linearly_independent (A × B) /\\\n                            (exists a : Square n, pad a C1 = (A × B))).\nProof. intros.\n       destruct H1 as [i [H1 H2]].\n       apply (lin_indep_swap A 0 i) in H0; try lia; try easy.\n       apply (lin_indep_col_add_each _ _ 0 \n                           (-C1 .* (get_row 0 (col_swap A 0 i))) (col_swap A 0 i)) in H0; 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 WF_mult. \n       apply WF_row_swap; try lia; auto with wf_db.\n       apply WF_row_add_many; try lia; auto with wf_db.\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 padded; intros. \n       destruct H3 as [H3 H4].\n       destruct H3. \n       + unfold col_add_each, make_col_zero, get_row, col_swap, \n         Mplus, Mmult, get_vec, scale.\n         rewrite H3 in *.\n         bdestruct (j =? 0); try lia. \n         assert (H' : (get_vec i A) 0 0 = C1).\n         { rewrite H2. 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 H3 in *; simpl. \n         destruct i0; try lia.\n         assert (H' : (get_vec i A) (S i0) 0 = C0).\n         { rewrite H2. 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 H2. easy. }\n         unfold get_vec in H'; simpl in H'.\n         rewrite H'; lca.\n       + apply WF_col_swap; try lia; easy. \n       + apply WF_make_col_zero.\n         apply WF_scale. \n         apply WF_get_row.\n         apply WF_col_swap; try lia; easy.\n       + apply WF_scale. \n         apply WF_get_row.\n         apply WF_col_swap; try lia; easy.\nQed.    \n\n\nTheorem lin_ind_implies_invertible_r : forall {n} (A : Square n),\n  WF_Matrix A -> linearly_independent A -> \n  (exists B, WF_Matrix B /\\ A × B = I n).\nProof. induction n as [| n'].\n       - intros.  \n         exists Zero. split; auto with wf_db.\n         rewrite Mmult_0_r.\n         apply mat_equiv_eq; auto with wf_db. \n         unfold mat_equiv. lia. \n       - intros. apply lin_indep_ind_step1 in H0; try easy.\n         destruct H0 as [B1 [H0 [H1 H2]]].\n         destruct H2 as [i [H2 H3]].\n         apply lin_indep_ind_step2 in H1; auto with wf_db.\n         destruct H1 as [B2 [H1 [H4 H5]]].\n         destruct H5 as [a H5].\n         rewrite <- H5 in H4.\n         apply lin_indep_pad in H4.\n         apply IHn' in H4.\n         destruct H4 as [B3 [H6 H7]].\n         exists (B1 × B2 × (pad B3 C1)).\n         split. apply WF_mult. \n         apply WF_mult; easy.\n         apply (WF_pad B3 C1). easy.\n         do 2 rewrite <- Mmult_assoc. \n         rewrite <- H5.\n         rewrite <- pad_mult.\n         rewrite Cmult_1_l.\n         rewrite H7, pad_I; easy.\n         apply (WF_pad a C1). \n         rewrite H5. \n         auto with wf_db.\n         exists i; split; try lia. \n         easy.\nQed.\n\n\n         \n\n(* Inverses of square matrices *)\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; easy. }\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\nLemma 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; easy.\n       - intros. \n         destruct H0 as [B [H1 H2]].\n         apply invertible_l_implies_linind in H2.\n         easy.\nQed.\n\nLemma div_mod : forall (x y z : nat), (x / y) mod z = (x mod (y * z)) / y.\nProof.\n  intros. bdestruct (y =? 0). subst. simpl.\n  bdestruct (z =? 0). subst. easy.\n  apply Nat.mod_0_l. easy.\n  bdestruct (z =? 0). subst. rewrite Nat.mul_0_r. simpl. rewrite Nat.div_0_l; easy.\n  pattern x at 1. rewrite (Nat.div_mod x (y * z)) by nia.\n  replace (y * z * (x / (y * z))) with ((z * (x / (y * z))) * y) by lia.\n  rewrite Nat.div_add_l with (b := y) by easy.\n  replace (z * (x / (y * z)) + x mod (y * z) / y) with\n      (x mod (y * z) / y + (x / (y * z)) * z) by lia.\n  rewrite Nat.mod_add by easy.\n  apply Nat.mod_small.\n  apply Nat.div_lt_upper_bound. easy. apply Nat.mod_upper_bound. nia.\nQed.\n\nLemma sub_mul_mod :\n  forall x y z,\n    y * z <= x ->\n    (x - y * z) mod z = x mod z.\nProof.\n  intros. bdestruct (z =? 0). subst. easy.\n  specialize (le_plus_minus_r (y * z) x H) as G.\n  remember (x - (y * z)) as r.\n  rewrite <- G. rewrite <- Nat.add_mod_idemp_l by easy. rewrite Nat.mod_mul by easy.\n  easy.\nQed.\n\nLemma mod_product : forall x y z, y <> 0 -> x mod (y * z) mod z = x mod z.\nProof.\n  intros x y z H. bdestruct (z =? 0). subst. easy.\n  pattern x at 2. rewrite Nat.mod_eq with (b := y * z) by nia.\n  replace (y * z * (x / (y * z))) with (y * (x / (y * z)) * z) by lia.\n  rewrite sub_mul_mod. easy.\n  replace (y * (x / (y * z)) * z) with (y * z * (x / (y * z))) by lia.\n  apply Nat.mul_div_le. nia.\nQed.\n\nLemma kron_assoc_mat_equiv : forall {m n p q r s : nat}\n  (A : Matrix m n) (B : Matrix p q) (C : Matrix r s),\n  (A ⊗ B ⊗ C) == A ⊗ (B ⊗ C).                                \nProof.\n  intros. intros i j Hi Hj.\n  remember (A ⊗ B ⊗ C) as LHS.\n  unfold kron.  \n  rewrite (mult_comm p r) at 1 2.\n  rewrite (mult_comm q s) at 1 2.\n  assert (m * p * r <> 0) by lia.\n  assert (n * q * s <> 0) by lia.\n  apply Nat.neq_mul_0 in H as [Hmp Hr].\n  apply Nat.neq_mul_0 in Hmp as [Hm Hp].\n  apply Nat.neq_mul_0 in H0 as [Hnq Hs].\n  apply Nat.neq_mul_0 in Hnq as [Hn Hq].\n  rewrite <- 2 Nat.div_div by assumption.\n  rewrite <- 2 div_mod.\n  rewrite 2 mod_product by assumption.\n  rewrite Cmult_assoc.\n  subst.\n  reflexivity.\nQed.  \n\nLemma kron_assoc : forall {m n p q r s : nat}\n  (A : Matrix m n) (B : Matrix p q) (C : Matrix r s),\n  WF_Matrix A -> WF_Matrix B -> WF_Matrix C ->\n  (A ⊗ B ⊗ C) = A ⊗ (B ⊗ C).                                \nProof.\n  intros.\n  apply mat_equiv_eq; auto with wf_db.\n  apply WF_kron; auto with wf_db; lia.\n  apply kron_assoc_mat_equiv.\nQed.  \n\n\nLemma kron_mixed_product : forall {m n o p q r : nat} (A : Matrix m n) (B : Matrix p q ) \n  (C : Matrix n o) (D : Matrix q r), (A ⊗ B) × (C ⊗ D) = (A × C) ⊗ (B × D).\nProof.\n  intros m n o p q r A B C D.\n  unfold kron, Mmult.\n  prep_matrix_equality.\n  destruct q.\n  + simpl.\n    rewrite mult_0_r.\n    simpl.\n    rewrite Cmult_0_r.\n    reflexivity. \n  + rewrite Csum_product.\n    apply Csum_eq.\n    apply functional_extensionality.\n    intros; lca.\n    lia.\nQed.\n\n(* Arguments kron_mixed_product [m n o p q r]. *)\n\n\n(* A more explicit version, for when typechecking fails *)\nLemma kron_mixed_product' : forall (m n n' o p q q' r mp nq or: nat)\n    (A : Matrix m n) (B : Matrix p q) (C : Matrix n' o) (D : Matrix q' r),\n    n = n' -> q = q' ->    \n    mp = m * p -> nq = n * q -> or = o * r ->\n  (@Mmult mp nq or (@kron m n p q A B) (@kron n' o q' r C D)) =\n  (@kron m o p r (@Mmult m n o A C) (@Mmult p q r B D)).\nProof. intros. subst. apply kron_mixed_product. Qed.\n\n\nLemma outer_product_eq : forall m (φ ψ : Matrix m 1),\n φ = ψ -> outer_product φ φ = outer_product ψ ψ.\nProof. congruence. Qed.\n\nLemma outer_product_kron : forall m n (φ : Matrix m 1) (ψ : Matrix n 1), \n    outer_product φ φ ⊗ outer_product ψ ψ = outer_product (φ ⊗ ψ) (φ ⊗ ψ).\nProof. \n  intros. unfold outer_product. \n  specialize (kron_adjoint φ ψ) as KT. \n  simpl in *. rewrite KT.\n  specialize (kron_mixed_product φ ψ (φ†) (ψ†)) as KM. \n  simpl in *. rewrite KM.\n  reflexivity.\nQed.\n\nLemma kron_n_assoc :\n  forall n {m1 m2} (A : Matrix m1 m2), WF_Matrix A -> (S n) ⨂ A = A ⊗ (n ⨂ A).\nProof.\n  intros. induction n.\n  - simpl. \n    rewrite kron_1_r. \n    rewrite kron_1_l; try assumption.\n    reflexivity.\n  - simpl.\n    replace (m1 * (m1 ^ n)) with ((m1 ^ n) * m1) by apply Nat.mul_comm.\n    replace (m2 * (m2 ^ n)) with ((m2 ^ n) * m2) by apply Nat.mul_comm.\n    rewrite <- kron_assoc; auto with wf_db.\n    rewrite <- IHn.\n    reflexivity.\nQed.\n\nLemma kron_n_adjoint : forall n {m1 m2} (A : Matrix m1 m2),\n  WF_Matrix A -> (n ⨂ A)† = n ⨂ A†.\nProof.\n  intros. induction n.\n  - simpl. apply id_adjoint_eq.\n  - simpl.\n    replace (m1 * (m1 ^ n)) with ((m1 ^ n) * m1) by apply Nat.mul_comm.\n    replace (m2 * (m2 ^ n)) with ((m2 ^ n) * m2) by apply Nat.mul_comm.\n    rewrite kron_adjoint, IHn.\n    reflexivity.\nQed.\n\nLemma Mscale_kron_n_distr_r : forall {m1 m2} n α (A : Matrix m1 m2),\n  n ⨂ (α .* A) = (α ^ n) .* (n ⨂ A).\nProof.\n  intros.\n  induction n; simpl.\n  rewrite Mscale_1_l. reflexivity.\n  rewrite IHn. \n  rewrite Mscale_kron_dist_r, Mscale_kron_dist_l. \n  rewrite Mscale_assoc.\n  reflexivity.\nQed.\n\nLemma kron_n_mult : forall {m1 m2 m3} n (A : Matrix m1 m2) (B : Matrix m2 m3),\n  n ⨂ A × n ⨂ B = n ⨂ (A × B).\nProof.\n  intros.\n  induction n; simpl.\n  rewrite Mmult_1_l. reflexivity.\n  apply WF_I.\n  replace (m1 * m1 ^ n) with (m1 ^ n * m1) by apply Nat.mul_comm.\n  replace (m2 * m2 ^ n) with (m2 ^ n * m2) by apply Nat.mul_comm.\n  replace (m3 * m3 ^ n) with (m3 ^ n * m3) by apply Nat.mul_comm.\n  rewrite kron_mixed_product.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma kron_n_I : forall n, n ⨂ I 2 = I (2 ^ n).\nProof.\n  intros.\n  induction n; simpl.\n  reflexivity.\n  rewrite IHn. \n  rewrite id_kron.\n  apply f_equal.\n  lia.\nQed.\n\nLemma Mmult_n_kron_distr_l : forall {m n} i (A : Square m) (B : Square n),\n  i ⨉ (A ⊗ B) = (i ⨉ A) ⊗ (i ⨉ B).\nProof.\n  intros m n i A B.\n  induction i; simpl.\n  rewrite id_kron; reflexivity.\n  rewrite IHi.\n  rewrite kron_mixed_product.\n  reflexivity.\nQed.\n\nLemma Mmult_n_1_l : forall {n} (A : Square n),\n  WF_Matrix A ->\n  1 ⨉ A = A.\nProof. intros n A WF. simpl. rewrite Mmult_1_r; auto. Qed.\n\nLemma Mmult_n_1_r : forall n i,\n  i ⨉ (I n) = I n.\nProof.\n  intros n i.\n  induction i; simpl.\n  reflexivity.\n  rewrite IHi.  \n  rewrite Mmult_1_l; auto with wf_db.\nQed.\n\nLemma Mmult_n_eigenvector : forall {n} (A : Square n) (ψ : Vector n) λ i,\n  WF_Matrix ψ -> A × ψ = λ .* ψ ->\n  i ⨉ A × ψ = (λ ^ i) .* ψ.\nProof.\n  intros n A ψ λ i WF H.\n  induction i; simpl.\n  rewrite Mmult_1_l; auto.\n  rewrite Mscale_1_l; auto.\n  rewrite Mmult_assoc.\n  rewrite IHi.\n  rewrite Mscale_mult_dist_r.\n  rewrite H.\n  rewrite Mscale_assoc.\n  rewrite Cmult_comm.\n  reflexivity.\nQed.\n\nLemma Msum_eq_bounded : forall {d1 d2} n (f f' : nat -> Matrix d1 d2),\n  (forall i, (i < n)%nat -> f i = f' i) -> Msum n f = Msum n f'.\nProof.\n  intros d1 d2 n f f' Heq.\n  induction n; simpl.\n  reflexivity.\n  rewrite Heq by lia.\n  rewrite IHn. reflexivity.\n  intros. apply Heq. lia.\nQed.\n\nLemma kron_Msum_distr_l : \n  forall {d1 d2 d3 d4} n (f : nat -> Matrix d1 d2) (A : Matrix d3 d4),\n  A ⊗ Msum n f = Msum n (fun i => A ⊗ f i).\nProof.\n  intros.\n  induction n; simpl. lma.\n  rewrite kron_plus_distr_l, IHn. reflexivity.\nQed.\n\nLemma kron_Msum_distr_r : \n  forall {d1 d2 d3 d4} n (f : nat -> Matrix d1 d2) (A : Matrix d3 d4),\n  Msum n f ⊗ A = Msum n (fun i => f i ⊗ A).\nProof.\n  intros.\n  induction n; simpl. lma.\n  rewrite kron_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma Mmult_Msum_distr_l : forall {d1 d2 m} n (f : nat -> Matrix d1 d2) (A : Matrix m d1),\n  A × Msum n f = Msum n (fun i => A × f i).\nProof.\n  intros.\n  induction n; simpl. \n  rewrite Mmult_0_r. reflexivity.\n  rewrite Mmult_plus_distr_l, IHn. reflexivity.\nQed.\n\nLemma Mmult_Msum_distr_r : forall {d1 d2 m} n (f : nat -> Matrix d1 d2) (A : Matrix d2 m),\n  Msum n f × A = Msum n (fun i => f i × A).\nProof.\n  intros.\n  induction n; simpl. \n  rewrite Mmult_0_l. reflexivity.\n  rewrite Mmult_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma Mscale_Msum_distr_r : forall {d1 d2} x n (f : nat -> Matrix d1 d2),\n  x .* Msum n f = Msum n (fun i => x .* f i).\nProof.\n  intros d1 d2 x n f.\n  induction n; simpl. lma.\n  rewrite Mscale_plus_distr_r, IHn. reflexivity.\nQed.\n\nLemma Mscale_Msum_distr_l : forall {d1 d2} n (f : nat -> C) (A : Matrix d1 d2),\n  Msum n (fun i => (f i) .* A) = Csum f n .* A.\nProof.\n  intros d1 d2 n f A.\n  induction n; simpl. lma.\n  rewrite Mscale_plus_distr_l, IHn. reflexivity.\nQed.\n\nLemma Msum_0 : forall {d1 d2} n (f : nat -> Matrix d1 d2),\n  (forall x, x < n -> f x = Zero) -> Msum n f = Zero.\nProof.\n  intros d1 d2 n f Hf.\n  induction n; simpl. reflexivity.\n  rewrite IHn, Hf. lma.\n  lia. intros. apply Hf. lia.\nQed.\n\nLemma Msum_constant : forall {d1 d2} n (A : Matrix d1 d2),  Msum n (fun _ => A) = INR n .* A.\nProof.\n  intros. \n  induction n.\n  simpl. lma.\n  simpl Msum.\n  rewrite IHn.\n  replace (S n) with (n + 1)%nat by lia. \n  rewrite plus_INR; simpl. \n  rewrite RtoC_plus. \n  rewrite Mscale_plus_distr_l.\n  lma.\nQed.\n\nLemma Msum_plus : forall {d1 d2} n (f1 f2 : nat -> Matrix d1 d2),\n  Msum n (fun i => (f1 i) .+ (f2 i)) = Msum n f1 .+ Msum n f2.\nProof.\n  intros d1 d2 n f1 f2.\n  induction n; simpl. lma.\n  rewrite IHn. lma.\nQed.\n\nLemma Msum_adjoint : forall {d1 d2} n (f : nat -> Matrix d1 d2),\n  (Msum n f)† = Msum n (fun i => (f i)†).\nProof.\n  intros.\n  induction n; simpl.\n  lma.\n  rewrite Mplus_adjoint, IHn.  \n  reflexivity.\nQed.\n\nLemma Msum_unique : forall {d1 d2} n (f : nat -> Matrix d1 d2) (A : Matrix d1 d2),\n  (exists i, i < n /\\ f i = A /\\ (forall j, j < n -> j <> i -> f j = Zero)) -> \n  Msum n f = A.\nProof.\n  intros d1 d2 n f A H.\n  destruct H as [i [? [? H]]].\n  induction n; try lia.\n  simpl.\n  bdestruct (n =? i).\n  rewrite (Msum_eq_bounded _ _ (fun _ : nat => Zero)).\n  rewrite Msum_0. subst. lma. reflexivity.\n  intros x ?. apply H; lia.\n  rewrite IHn; try lia.\n  rewrite H by lia. lma.\n  intros. apply H; lia.\nQed.\n\nLemma Msum_diagonal :\n  forall {d1 d2} n (f : nat -> nat -> Matrix d1 d2),\n    (forall i j, (i < n)%nat -> (j < n)%nat -> (i <> j)%nat -> f i j = Zero) ->\n    Msum n (fun i => Msum n (fun j => f i j)) = Msum n (fun i => f i i).\nProof.\n  intros. apply Msum_eq_bounded. intros.\n  apply Msum_unique. \n  exists i. auto.\nQed.\n\n(* Note on \"using [tactics]\": Most generated subgoals will be of the form \n   WF_Matrix M, where auto with wf_db will work.\n   Occasionally WF_Matrix M will rely on rewriting to match an assumption in the \n   context, here we recursively autorewrite (which adds time). \n   kron_1_l requires proofs of (n > 0)%nat, here we use lia. *)\n\n(* *)\n\n(*******************************)\n(* Restoring Matrix Dimensions *)\n(*******************************)\n\n(** Restoring Matrix dimensions *)\nLtac is_nat n := match type of n with nat => idtac end.\n\nLtac is_nat_equality :=\n  match goal with \n  | |- ?A = ?B => is_nat A\n  end.\n\nLtac unify_matrix_dims tac := \n  try reflexivity; \n  repeat (apply f_equal_gen; try reflexivity; \n          try (is_nat_equality; tac)).\n\nLtac restore_dims_rec A :=\n   match A with\n(* special cases *)\n  | ?A × I _          => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | Matrix ?m' ?n' => constr:(@Mmult m' n' n' A' (I n'))\n                        end\n  | I _ × ?B          => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | Matrix ?n' ?o' => constr:(@Mmult n' n' o' (I n')  B')\n                        end\n  | ?A × @Zero ?n ?n  => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | Matrix ?m' ?n' => constr:(@Mmult m' n' n' A' (@Zero n' n'))\n                        end\n  | @Zero ?n ?n × ?B  => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | Matrix ?n' ?o' => constr:(@Mmult n' n' o' (@Zero n' n') B')\n                        end\n  | ?A × @Zero ?n ?o  => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | Matrix ?m' ?n' => constr:(@Mmult m' n' o A' (@Zero n' o))\n                        end\n  | @Zero ?m ?n × ?B  => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | Matrix ?n' ?o' => constr:(@Mmult n' n' o' (@Zero m n') B')\n                        end\n  | ?A .+ @Zero ?m ?n => let A' := restore_dims_rec A in \n                        match type of A' with \n                        | Matrix ?m' ?n' => constr:(@Mplus m' n' A' (@Zero m' n'))\n                        end\n  | @Zero ?m ?n .+ ?B => let B' := restore_dims_rec B in \n                        match type of B' with \n                        | Matrix ?m' ?n' => constr:(@Mplus m' n' (@Zero m' n') B')\n                        end\n(* general cases *)\n  | ?A = ?B  => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | Matrix ?m' ?n' => constr:(@eq (Matrix m' n') A' B')\n                  end\n  | ?A × ?B   => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | Matrix ?m' ?n' =>\n                  match type of B' with \n                  | Matrix ?n'' ?o' => constr:(@Mmult m' n' o' A' B')\n                  end\n                end \n  | ?A ⊗ ?B   => let A' := restore_dims_rec A in \n                let B' := restore_dims_rec B in \n                match type of A' with \n                | Matrix ?m' ?n' =>\n                  match type of B' with \n                  | Matrix ?o' ?p' => constr:(@kron m' n' o' p' A' B')\n                  end\n                end\n  | ?A †      => let A' := restore_dims_rec A in \n                match type of A' with\n                | Matrix ?m' ?n' => constr:(@adjoint m' n' A')\n                end\n  | ?A .+ ?B => let A' := restore_dims_rec A in \n               let B' := restore_dims_rec B in \n               match type of A' with \n               | Matrix ?m' ?n' =>\n                 match type of B' with \n                 | Matrix ?m'' ?n'' => constr:(@Mplus m' n' A' B')\n                 end\n               end\n  | ?c .* ?AA => let A' := restore_dims_rec A in \n               match type of A' with\n               | Matrix ?m' ?n' => constr:(@scale m' n' c A')\n               end\n  | ?n ⨂ ?A => let A' := restore_dims_rec A in\n               match type of A' with\n               | Matrix ?m' ?n' => constr:(@kron_n n m' n' A')\n               end\n  (* For predicates (eg. WF_Matrix, Mixed_State) on Matrices *)\n  | ?P ?m ?n ?A => match type of P with\n                  | nat -> nat -> Matrix _ _ -> Prop =>\n                    let A' := restore_dims_rec A in \n                    match type of A' with\n                    | Matrix ?m' ?n' => constr:(P m' n' A')\n                    end\n                  end\n  | ?P ?n ?A => match type of P with\n               | nat -> Matrix _ _ -> Prop =>\n                 let A' := restore_dims_rec A in \n                 match type of A' with\n                 | Matrix ?m' ?n' => constr:(P m' A')\n                 end\n               end\n  (* Handle functions applied to matrices *)\n  | ?f ?A    => let f' := restore_dims_rec f in \n               let A' := restore_dims_rec A in \n               constr:(f' A')\n  (* default *)\n  | ?A       => A\n   end.\n\nLtac restore_dims tac := \n  match goal with\n  | |- ?A      => let A' := restore_dims_rec A in \n                replace A with A' by unify_matrix_dims tac\n  end.\n\nTactic Notation \"restore_dims\" tactic(tac) := restore_dims tac.\n\nTactic Notation \"restore_dims\" := restore_dims (repeat rewrite Nat.pow_1_l; try ring; unify_pows_two; simpl; lia).\n\n(*************************)\n(* Matrix Simplification *)\n(*************************)\n\n(* Old: \nHint Rewrite kron_1_l kron_1_r Mmult_1_l Mmult_1_r id_kron id_adjoint_eq\n     @Mmult_adjoint Mplus_adjoint @kron_adjoint @kron_mixed_product\n     id_adjoint_eq adjoint_involutive using \n     (auto 100 with wf_db; autorewrite with M_db; auto 100 with wf_db; lia) : M_db.\n*)\n\n(* eauto will cause major choking... *)\nHint Rewrite  @kron_1_l @kron_1_r @Mmult_1_l @Mmult_1_r @Mscale_1_l \n     @id_adjoint_eq @id_transpose_eq using (auto 100 with wf_db) : M_db_light.\nHint Rewrite @kron_0_l @kron_0_r @Mmult_0_l @Mmult_0_r @Mplus_0_l @Mplus_0_r\n     @Mscale_0_l @Mscale_0_r @zero_adjoint_eq @zero_transpose_eq using (auto 100 with wf_db) : M_db_light.\n\n(* I don't like always doing restore_dims first, but otherwise sometimes leaves \n   unsolvable WF_Matrix goals. *)\nLtac Msimpl_light := try restore_dims; autorewrite with M_db_light.\n\nHint Rewrite @Mmult_adjoint @Mplus_adjoint @kron_adjoint @kron_mixed_product\n     @adjoint_involutive using (auto 100 with wf_db) : M_db.\n\nLtac Msimpl := try restore_dims; autorewrite with M_db_light M_db.\n\n(** Distribute addition to the outside of matrix expressions. *)\n\nLtac distribute_plus :=\n  repeat match goal with \n  | |- context [?a × (?b .+ ?c)] => rewrite (Mmult_plus_distr_l _ _ _ a b c)\n  | |- context [(?a .+ ?b) × ?c] => rewrite (Mmult_plus_distr_r _ _ _ a b c)\n  | |- context [?a ⊗ (?b .+ ?c)] => rewrite (kron_plus_distr_l _ _ _ _ a b c)\n  | |- context [(?a .+ ?b) ⊗ ?c] => rewrite (kron_plus_distr_r _ _ _ _ a b c)\n  end.\n\n(** Distribute scaling to the outside of matrix expressions *)\n\nLtac distribute_scale := \n  repeat\n   match goal with\n   | |- context [ (?c .* ?A) × ?B   ] => rewrite (Mscale_mult_dist_l _ _ _ c A B)\n   | |- context [ ?A × (?c .* ?B)   ] => rewrite (Mscale_mult_dist_r _ _ _ c A B)\n   | |- context [ (?c .* ?A) ⊗ ?B   ] => rewrite (Mscale_kron_dist_l _ _ _ _ c A B)\n   | |- context [ ?A ⊗ (?c .* ?B)   ] => rewrite (Mscale_kron_dist_r _ _ _ _ c A B)\n   | |- context [ ?c .* (?c' .* ?A) ] => rewrite (Mscale_assoc _ _ c c' A)\n   end.\n\nLtac distribute_adjoint :=\n  repeat match goal with\n  | |- context [(?c .* ?A)†] => rewrite (Mscale_adj _ _ c A)\n  | |- context [(?A .+ ?B)†] => rewrite (Mplus_adjoint _ _ A B)\n  | |- context [(?A × ?B)†] => rewrite (Mmult_adjoint A B)\n  | |- context [(?A ⊗ ?B)†] => rewrite (kron_adjoint A B)\n  end.\n\n(*********************************************************)\n(** Tactics for solving computational matrix equalities **)\n(*********************************************************)\n\n\n(* Construct matrices full of evars *)\nLtac mk_evar t T := match goal with _ => evar (t : T) end.\n\nLtac evar_list n := \n  match n with \n  | O => constr:(@nil C)\n  | S ?n' => let e := fresh \"e\" in\n            let none := mk_evar e C in \n            let ls := evar_list n' in \n            constr:(e :: ls)\n            \n  end.\n\nLtac evar_list_2d m n := \n  match m with \n  | O => constr:(@nil (list C))\n  | S ?m' => let ls := evar_list n in \n            let ls2d := evar_list_2d m' n in  \n            constr:(ls :: ls2d)\n  end.\n\nLtac evar_matrix m n := let ls2d := (evar_list_2d m n) \n                        in constr:(list2D_to_matrix ls2d).   \n\n(* Tactic version of Nat.lt *)\nLtac tac_lt m n := \n  match n with \n  | S ?n' => match m with \n            | O => idtac\n            | S ?m' => tac_lt m' n'\n            end\n  end.\n\n(* Possible TODO: We could have the tactic below use restore_dims instead of \n   simplifying before rewriting. *)\n(* Reassociate matrices so that smallest dimensions are multiplied first:\nFor (m x n) × (n x o) × (o x p):\nIf m or o is the smallest, associate left\nIf n or p is the smallest, associate right\n(The actual time for left is (m * o * n) + (m * p * o) = mo(n+p) \n                      versus (n * p * o) + (m * p * n) = np(m+o) for right. \nWe find our heuristic to be pretty accurate, though.)\n*)\nLtac assoc_least := \n  repeat (simpl; match goal with\n  | [|- context[@Mmult ?m ?o ?p (@Mmult ?m ?n ?o ?A ?B) ?C]] => tac_lt p o; tac_lt p m; \n       let H := fresh \"H\" in \n       specialize (Mmult_assoc A B C) as H; simpl in H; rewrite H; clear H\n  | [|- context[@Mmult ?m ?o ?p (@Mmult ?m ?n ?o ?A ?B) ?C]] => tac_lt n o; tac_lt n m; \n       let H := fresh \"H\" in \n       specialize (Mmult_assoc  A B C) as H; simpl in H; rewrite H; clear H\n  | [|- context[@Mmult ?m ?n ?p ?A (@Mmult ?n ?o ?p ?B ?C)]] => tac_lt m n; tac_lt m p; \n       let H := fresh \"H\" in \n       specialize (Mmult_assoc A B C) as H; simpl in H; rewrite <- H; clear H\n  | [|- context[@Mmult ?m ?n ?p ?A (@Mmult ?n ?o ?p ?B ?C)]] => tac_lt o n; tac_lt o p; \n       let H := fresh \"H\" in \n       specialize (Mmult_assoc A B C) as H; simpl in H; rewrite <- H; clear H\n  end).\n\n\n(* Helper function for crunch_matrix *)\nLtac solve_out_of_bounds := \n  repeat match goal with \n  | [H : WF_Matrix ?M |- context[?M ?a ?b] ] => \n      rewrite (H a b) by (left; simpl; lia) \n  | [H : WF_Matrix ?M |- context[?M ?a ?b] ] => \n      rewrite (H a b) by (right; simpl; lia) \n  end;\n  autorewrite with C_db; auto.\n\n\nLemma divmod_eq : forall x y n z, \n  fst (Nat.divmod x y n z) = (n + fst (Nat.divmod x y 0 z))%nat.\nProof.\n  induction x.\n  + intros. simpl. lia.\n  + intros. simpl. \n    destruct z.\n    rewrite IHx.\n    rewrite IHx with (n:=1%nat).\n    lia.\n    rewrite IHx.\n    reflexivity.\nQed.\n\nLemma divmod_S : forall x y n z, \n  fst (Nat.divmod x y (S n) z) = (S n + fst (Nat.divmod x y 0 z))%nat.\nProof. intros. apply divmod_eq. Qed.\n\nLtac destruct_m_1' :=\n  match goal with\n  | [ |- context[match ?x with \n                 | 0   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  | [ |- context[match fst (Nat.divmod ?x _ _ _) with \n                 | 0   => _\n                 | S _ => _\n                 end] ] => is_var x; destruct x\n  end.\n\nLemma divmod_0q0 : forall x q, fst (Nat.divmod x 0 q 0) = (x + q)%nat. \nProof.\n  induction x.\n  - intros. simpl. reflexivity.\n  - intros. simpl. rewrite IHx. lia.\nQed.\n\nLemma divmod_0 : forall x, fst (Nat.divmod x 0 0 0) = x. \nProof. intros. rewrite divmod_0q0. lia. Qed.\n\nLtac destruct_m_eq' := repeat \n  (progress (try destruct_m_1'; try rewrite divmod_0; try rewrite divmod_S; simpl)).\n\n(* Unify A × B with list (list (evars)) *)\n(* We convert the matrices back to functional representation for \n   unification. Simply comparing the matrices may be more efficient,\n   however. *)\n\nLtac crunch_matrix := \n                    match goal with \n                      | [|- ?G ] => idtac \"Crunching:\" G\n                      end;\n                      repeat match goal with\n                             | [ c : C |- _ ] => cbv [c]; clear c (* 'unfold' hangs *)\n                             end; \n                      simpl;\n                      unfold list2D_to_matrix;    \n                      autounfold with U_db;\n                      prep_matrix_equality;\n                      simpl;\n                      destruct_m_eq';\n                      simpl;\n                      Csimpl; (* basic rewrites only *) \n                      try reflexivity;\n                      try solve_out_of_bounds. \n\nLtac compound M := \n  match M with\n  | ?A × ?B  => idtac\n  | ?A .+ ?B => idtac \n  | ?A †     => compound A\n  end.\n\n(* Reduce inner matrices first *)\nLtac reduce_aux M := \n  match M with \n  | ?A .+ ?B     => compound A; reduce_aux A\n  | ?A .+ ?B     => compound B; reduce_aux B\n  | ?A × ?B      => compound A; reduce_aux A\n  | ?A × ?B      => compound B; reduce_aux B\n  | @Mmult ?m ?n ?o ?A ?B      => let M' := evar_matrix m o in\n                                 replace M with M';\n                                 [| crunch_matrix ] \n  | @Mplus ?m ?n ?A ?B         => let M' := evar_matrix m n in\n                                 replace M with M';\n                                 [| crunch_matrix ] \n  end.\n\nLtac reduce_matrix := match goal with \n                       | [ |- ?M = _] => reduce_aux M\n                       | [ |- _ = ?M] => reduce_aux M\n                       end;\n                       repeat match goal with \n                              | [ |- context[?c :: _ ]] => cbv [c]; clear c\n                              end.\n\n(* Reduces matrices anywhere they appear *)\nLtac reduce_matrices := assoc_least;\n                        match goal with \n                        | [ |- context[?M]] => reduce_aux M\n                        end;\n                        repeat match goal with \n                               | [ |- context[?c :: _ ]] => cbv [c]; clear c\n                               end.\n\n\nLtac solve_matrix := assoc_least;\n                     repeat reduce_matrix; try crunch_matrix;\n                     (* handle out-of-bounds *)\n                     unfold Nat.ltb; simpl; try rewrite andb_false_r; \n                     (* try to solve complex equalities *)\n                     autorewrite with C_db; try lca.\n\n(*********************************************************)\n(**                         Gridify                     **)\n(*********************************************************)\n\n(** Gridify: Turns an matrix expression into a normal form with \n    plus on the outside, then tensor, then matrix multiplication.\n    Eg: ((..×..×..)⊗(..×..×..)⊗(..×..×..)) .+ ((..×..)⊗(..×..))\n*)\n\nLocal Open Scope nat_scope.\n\nLemma repad_lemma1_l : forall (a b d : nat),\n  a < b -> d = (b - a - 1) -> b = a + 1 + d.\nProof. intros. subst. lia. Qed. \n\nLemma repad_lemma1_r : forall (a b d : nat),\n  a < b -> d = (b - a - 1) -> b = d + 1 + a.\nProof. intros. subst. lia. Qed.\n\nLemma repad_lemma2 : forall (a b d : nat),\n  a <= b -> d = (b - a) -> b = a + d.\nProof. intros. subst. lia. Qed.\n\nLemma le_ex_diff_l : forall a b, a <= b -> exists d, b = d + a. \nProof. intros. exists (b - a). lia. Qed.\n\nLemma le_ex_diff_r : forall a b, a <= b -> exists d, b = a + d. \nProof. intros. exists (b - a). lia. Qed.  \n\nLemma lt_ex_diff_l : forall a b, a < b -> exists d, b = d + 1 + a. \nProof. intros. exists (b - a - 1). lia. Qed.\n\nLemma lt_ex_diff_r : forall a b, a < b -> exists d, b = a + 1 + d. \nProof. intros. exists (b - a - 1). lia. Qed.\n\nLtac bdestruct_all :=\n  repeat match goal with\n  | |- context[?a <? ?b] => bdestruct (a <? b)\n  | |- context[?a <=? ?b] => bdestruct (a <=? b)                                       \n  | |- context[?a =? ?b] => bdestruct (a =? b)\n  end; try (exfalso; lia).\n\n(* Remove _ < _ from hyps, remove _ - _  from goal *)\nLtac remember_differences :=\n  repeat match goal with\n  | H : ?a < ?b |- context[?b - ?a - 1] => \n    let d := fresh \"d\" in\n    let R := fresh \"R\" in\n    remember (b - a - 1) as d eqn:R ;\n    apply (repad_lemma1_l a b d) in H; trivial;\n    clear R;\n    try rewrite H in *;\n    try clear b H\n  | H:?a <= ?b  |- context [ ?b - ?a ] =>\n    let d := fresh \"d\" in\n    let R := fresh \"R\" in\n    remember (b - a) as d eqn:R ;\n    apply (repad_lemma2 a b d) in H; trivial;\n    clear R;\n    try rewrite H in *;\n    try clear b H\n  end.\n\n(* gets the exponents of the dimensions of the given matrix expression *)\n(* assumes all matrices are square *)\nLtac get_dimensions M :=\n  match M with\n  | ?A ⊗ ?B  => let a := get_dimensions A in\n               let b := get_dimensions B in\n               constr:(a + b)\n  | ?A .+ ?B => get_dimensions A\n  | _        => match type of M with\n               | Matrix 2 2 => constr:(1)\n               | Matrix 4 4 => constr:(2)\n               | Matrix (2^?a) (2^?a) => constr:(a)\n(*             | Matrix ?a ?b => idtac \"bad dims\";\n                                idtac M;\n                                constr:(a) *)\n               end\n  end.\n\n(* not necessary in this instance - produced hypothesis is H1 *)\n(* This is probably fragile and should be rewritten *)\n(*\nLtac hypothesize_dims :=\n  match goal with\n  | |- ?A × ?B = _ => let a := get_dimensions A in\n                    let b := get_dimensions B in\n                    assert(a = b) by lia\n  | |- _ = ?A × ?B => let a := get_dimensions A in\n                    let b := get_dimensions B in\n                    assert(a = b) by lia\n  end.\n*)\n\n(* Hopefully always grabs the outermost product. *)\nLtac hypothesize_dims :=\n  match goal with\n  | |- context[?A × ?B] => let a := get_dimensions A in\n                         let b := get_dimensions B in\n                         assert(a = b) by lia\n  end.\n\n(* Unifies an equation of the form `a + 1 + b + 1 + c = a' + 1 + b' + 1 + c'`\n   (exact symmetry isn't required) by filling in the holes *) \nLtac fill_differences :=\n  repeat match goal with \n  | R : _ < _ |- _           => let d := fresh \"d\" in\n                              destruct (lt_ex_diff_r _ _ R);\n                              clear R; subst\n  | H : _ = _ |- _           => rewrite <- plus_assoc in H\n  | H : ?a + _ = ?a + _ |- _ => apply Nat.add_cancel_l in H; subst\n  | H : ?a + _ = ?b + _ |- _ => destruct (lt_eq_lt_dec a b) as [[?|?]|?]; subst\n  end; try lia.\n\nLtac repad := \n  (* remove boolean comparisons *)\n  bdestruct_all; Msimpl_light; try reflexivity;\n  (* remove minus signs *) \n  remember_differences;\n  (* put dimensions in hypothesis [will sometimes exist] *)\n  try hypothesize_dims; clear_dups;\n  (* where a < b, replace b with a + 1 + fresh *)\n  fill_differences.\n\nLtac gridify :=\n  (* remove boolean comparisons *)\n  bdestruct_all; Msimpl_light; try reflexivity;\n  (* remove minus signs *) \n  remember_differences;\n  (* put dimensions in hypothesis [will sometimes exist] *)\n  try hypothesize_dims; clear_dups;\n  (* where a < b, replace b with a + 1 + fresh *)\n  fill_differences;\n  (* distribute *)  \n  restore_dims; distribute_plus;\n  repeat rewrite Nat.pow_add_r;\n  repeat rewrite <- id_kron; simpl;\n  repeat rewrite mult_assoc;\n  restore_dims; repeat rewrite <- kron_assoc by auto 100 with wf_db;\n  restore_dims; repeat rewrite kron_mixed_product;\n  (* simplify *)\n  Msimpl_light.\n\n(**************************************)\n(* Tactics to show implicit arguments *)\n(**************************************)\n\nDefinition kron' := @kron.      \nLemma kron_shadow : @kron = kron'. Proof. reflexivity. Qed.\n\nDefinition Mmult' := @Mmult.\nLemma Mmult_shadow : @Mmult = Mmult'. Proof. reflexivity. Qed.\n\nLtac show_dimensions := try rewrite kron_shadow in *; \n                        try rewrite Mmult_shadow in *.\nLtac hide_dimensions := try rewrite <- kron_shadow in *; \n                        try rewrite <- Mmult_shadow in *.\n", "meta": {"author": "inQWIRE", "repo": "Stabilizer-Types", "sha": "28f74af2fb9c42433f17138418e8192cfd964532", "save_path": "github-repos/coq/inQWIRE-Stabilizer-Types", "path": "github-repos/coq/inQWIRE-Stabilizer-Types/Stabilizer-Types-28f74af2fb9c42433f17138418e8192cfd964532/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7593084629780615}}
{"text": "Coq < Section More_Practice.\n\nCoq < Require Import Classical.\n\nCoq < Variables P Q : Prop.\nP is assumed\nQ is assumed\n\nCoq < Goal (P /\\ Q) -> (Q /\\ P).\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  ============================\n   P /\\ Q -> Q /\\ P\n\nUnnamed_thm < intros.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P /\\ Q\n  ============================\n   Q /\\ P\n\nUnnamed_thm < destruct H.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P\n  H0 : Q\n  ============================\n   Q /\\ P\n\nUnnamed_thm < split.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  H : P\n  H0 : Q\n  ============================\n   Q\n\nsubgoal 2 is:\n P\n\nUnnamed_thm < exact H0.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  H : P\n  H0 : Q\n  ============================\n   P\n\nUnnamed_thm < exact H.\nNo more subgoals.\n\nUnnamed_thm < Qed.\nintros.\ndestruct H.\nsplit.\n exact H0.\n\n exact H.\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/practice20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118215, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.759308461216266}}
{"text": "Require Import ZArith Nnat Omega.\nOpen Scope Z_scope.\n\n(** Test of the zify preprocessor for (R)Omega *)\n\n(* More details in file PreOmega.v\n\n   (r)omega with Z        : starts with zify_op\n   (r)omega with nat      : starts with zify_nat\n   (r)omega with positive : starts with zify_positive\n   (r)omega with N        : starts with uses zify_N\n   (r)omega with *        : starts zify (a saturation of the others)\n*)\n\n(* zify_op *)\n\nGoal forall a:Z, Z.max a a = a.\nintros.\nomega with *.\nQed.\n\nGoal forall a b:Z, Z.max a b = Z.max b a.\nintros.\nomega with *.\nQed.\n\nGoal forall a b c:Z, Z.max a (Z.max b c) = Z.max (Z.max a b) c.\nintros.\nomega with *.\nQed.\n\nGoal forall a b:Z, Z.max a b + Z.min a b = a + b.\nintros.\nomega with *.\nQed.\n\nGoal forall a:Z, (Z.abs a)*(Z.sgn a) = a.\nintros.\nzify.\nintuition; subst; omega. (* pure multiplication: omega alone can't do it *)\nQed.\n\nGoal forall a:Z, Z.abs a = a -> a >= 0.\nintros.\nomega with *.\nQed.\n\nGoal forall a:Z, Z.sgn a = a -> a = 1 \\/ a = 0 \\/ a = -1.\nintros.\nomega with *.\nQed.\n\n(* zify_nat *)\n\nGoal forall m: nat, (m<2)%nat -> (0<= m+m <=2)%nat.\nintros.\nomega with *.\nQed.\n\nGoal forall m:nat, (m<1)%nat -> (m=0)%nat.\nintros.\nomega with *.\nQed.\n\nGoal forall m: nat, (m<=100)%nat -> (0<= m+m <=200)%nat.\nintros.\nomega with *.\nQed.\n(* 2000 instead of 200: works, but quite slow *)\n\nGoal forall m: nat, (m*m>=0)%nat.\nintros.\nomega with *.\nQed.\n\n(* zify_positive *)\n\nGoal forall m: positive, (m<2)%positive -> (2 <= m+m /\\ m+m <= 2)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m:positive, (m<2)%positive -> (m=1)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m: positive, (m<=1000)%positive -> (2<=m+m/\\m+m <=2000)%positive.\nintros.\nomega with *.\nQed.\n\nGoal forall m: positive, (m*m>=1)%positive.\nintros.\nomega with *.\nQed.\n\n(* zify_N *)\n\nGoal forall m:N, (m<2)%N -> (0 <= m+m /\\ m+m <= 2)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m<1)%N -> (m=0)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m<=1000)%N -> (0<=m+m/\\m+m <=2000)%N.\nintros.\nomega with *.\nQed.\n\nGoal forall m:N, (m*m>=0)%N.\nintros.\nomega with *.\nQed.\n\n(* mix of datatypes *)\n\nGoal forall p, Z.of_N (N.of_nat (N.to_nat (Npos p))) = Zpos p.\nintros.\nomega with *.\nQed.\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/test-suite/success/OmegaPre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7592872492210204}}
{"text": "(** Calculation of an abstract machine for the call-by-value lambda\ncalculus. The resulting abstract machine coincides with the CEK\nmachine. *)\n\nRequire Import List.\nRequire Import ListIndex.\nRequire Import Tactics.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Var : nat -> Expr\n| Abs : Expr -> Expr\n| App : Expr -> Expr -> Expr.\n\n(** * Semantics *)\n\n(** The evaluator for this language is given as follows:\n<<\ntype Env = [Value]\ndata Value =  Fun (Value -> Value)\n\neval ::  Expr -> Env -> Value\neval (Var i) e   = e !! i\neval (Abs x) e   = Fun (\\v -> eval x (v:e))\neval (App x y) e = case eval x e of\n                     Fun f -> f (eval y e)\n>>\nAfter defunctionalisation and translation into relational form we\nobtain the semantics below. *)\n\nInductive Value : Set :=\n| Clo : Expr -> list Value -> Value.\n\nDefinition Env := list Value.\n\nReserved Notation \"x ⇓[ e ] y\" (at level 80, no associativity).\n\nInductive eval : Expr -> Env -> Value -> Prop :=\n| eval_var e i v : nth e i = Some v -> Var i ⇓[e] v\n| eval_abs e x : Abs x ⇓[e] Clo x e\n| eval_app e e' x x' w y v : x ⇓[e] Clo x' e' -> y ⇓[e] v -> x' ⇓[v :: e'] w -> App x y ⇓[e] w\nwhere \"x ⇓[ e ] y\" := (eval x e y).\n\n(** * Abstract machine *)\n\nInductive CONT : Set :=\n| FUN : Expr -> Env -> CONT -> CONT\n| ARG : Expr -> Env -> CONT -> CONT\n| HALT : CONT\n.\n\nInductive Conf : Set := \n| eval'' : Expr -> Env -> CONT -> Conf\n| apply : CONT -> Value -> Conf.\n\nNotation \"⟨ x , e , c ⟩\" := (eval'' x e 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_var i e c v : nth e i = Some v -> ⟨Var i, e, c⟩ ==> ⟪c, v⟫\n| am_abs x e c : ⟨Abs x, e, c⟩ ==> ⟪c, Clo x e⟫\n| am_app x y e c : ⟨App x y, e, c⟩ ==> ⟨x, e, ARG y e c⟩\n| am_FUN x' e' c v : ⟪FUN x' e' c, v⟫ ==> ⟨x', v::e', c⟩\n| am_ARG y e c x' e' : ⟪ARG y e c, Clo x' e'⟫ ==> ⟨y, e, FUN x' e' c⟩\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 e r c : x ⇓[e] r -> ⟨x, e, c⟩ =>> ⟪c, r⟫.\n\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\n(** - [Var i ⇓[e] v] *)\n\n  begin\n    ⟪c, v ⟫.\n  <== {apply am_var}\n    ⟨Var i, e, c ⟩.\n   [].\n\n(** - [Abs x ⇓[e] Clo x e] *)\n\n  begin\n    ⟪c, Clo x e⟫.\n  <== { apply am_abs }\n    ⟨Abs x, e, c⟩.\n  [].\n\n(** - [App x y ⇓[e] w] *)\n\n  begin\n    ⟪c, w⟫.\n  <<= { apply IHeval3 }\n    ⟨x', (v::e'), c⟩.\n  <== { apply am_FUN }\n    ⟪FUN x' e' c, v⟫.\n  <<= {apply IHeval2}\n    ⟨y, e, FUN x' e' c⟩.\n  <== {apply am_ARG}\n    ⟪ARG y e c, Clo x' e'⟫.\n  <<= {apply IHeval1}\n    ⟨x, e, ARG y e c⟩.\n  <== {apply am_app}\n    ⟨App x y, e, c⟩.\n  [].\nQed.\n  \n(** * Soundness *)\n\nLemma determ_am : determ AM.\n  intros C c1 c2 V. induction V; intro V'; inversion V'; subst; congruence.\nQed.\n  \n\nDefinition terminates (p : Expr) : Prop := exists r, p ⇓[nil] r.\n\nTheorem sound x C : terminates x -> ⟨x, nil, HALT⟩ =>>! C -> \n                          exists r, C = ⟪HALT, r⟫ /\\ x ⇓[nil] r.\nProof.\n  unfold terminates. intros. destruct H as [r T].\n  \n  pose (spec x nil 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/LambdaCBV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7592599608681756}}
{"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), so readers who are already comfortable with\n    these ideas can safely skim or skip this chapter.  However,\n    relations are also a good source of exercises for developing\n    facility with Coq's basic reasoning facilities, so it may be\n    useful to look at this material just after the [IndProp]\n    chapter. *)\n\nRequire Export SF.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(** *** 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(** *** 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(** *** 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(** *** 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(** *** 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(** *** 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: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "erikmd", "repo": "tryjscoq", "sha": "b5636d1b7bc6616fe7f136678e30bc4030484f22", "save_path": "github-repos/coq/erikmd-tryjscoq", "path": "github-repos/coq/erikmd-tryjscoq/tryjscoq-b5636d1b7bc6616fe7f136678e30bc4030484f22/jscoq/examples/sf/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832332, "lm_q2_score": 0.9019206811430763, "lm_q1q2_score": 0.7592599575937221}}
{"text": "Require Export MoreCoq.\n\n(* ((Conjunction (Logical \"and\"))) *)\n\n(* Exercise: 2 stars (and_exercise) *)\n\nExample and_exercise:\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  destruct n.\n  Case \"n = 0\".\n    split.\n    SCase \"0 = 0 ?\".\n      reflexivity.\n    SCase \"m = 0\".\n      simpl in H.\n      rewrite H.\n      reflexivity.\n  Case \"n != 0\".\n    inversion H.\nQed.\n\n(* END and_exercise. *)\n\n(* Exercise: 1 star, optional (proj2) *)\n\nTheorem proj2 : forall (P Q : Prop), P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ].\n  apply HQ.\nQed.\n\n(* END proj2. *)\n\n(* Exercise: 2 stars (and_assoc) *)\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  split.\n  Case \"P and Q\".\n    split.\n    SCase \"P\".\n      apply HP.\n    SCase \"Q\".\n      apply HQ.\n  Case \"R\".\n    apply HR.\nQed.\n\n(* END and_assoc. *)\n\n(* ((Iff)) *)\n\n(* Exercise: 1 star, optional (iff_properties) *)\n\nTheorem iff_refl : forall P : Prop, P <-> P.\nProof.\n  intros P.\n  split.\n  Case \"P -> P #1\".\n    intros H.\n    apply H.\n  Case \"P -> P #2\".\n    intros H.\n    apply H.\nQed.\n\n(* END iff_properties. *)\n\n(* Exercise: 2 stars (or_distributes_over_and_2) *)\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  destruct H as [[HP|HQ] [HP2|HR]] eqn: Hd.\n  Case \"(true \\/ _) /\\ (true \\/ _)\".\n    left.\n    apply HP.\n  Case \"(true \\/ _) /\\ (_ \\/ true)\".\n    left.\n    apply HP.\n  Case \"(_ \\/ true) /\\ (true \\/ _)\".\n    left.\n    apply HP2.\n  Case \"(_ \\/ true) /\\ (_ \\/ true)\".\n    right.\n    split.\n    SCase \"Q\".\n      apply HQ.\n    SCase \"R\".\n      apply HR.\nQed.\n\n(* END or_distributes_over_and_2. *)\n\n(* Exercise: 1 star, optional (or_distributes_over_and) *)\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 H.\n  split.\n  Case \"P \\/ Q\".\n    destruct H as [HP | [HQ HR]] eqn: Hd.\n    SCase \"true \\/ _\".\n      left.\n      apply HP.\n    SCase \"_ \\/ (true /\\ true)\".\n      right.\n      apply HQ.\n  Case \"P \\/ R\".\n    destruct H as [HP | [HQ HR]] eqn: Hd.\n    SCase \"true \\/ _\".\n      left.\n      apply HP.\n    SCase \"_ \\/ (true /\\ true)\".\n      right.\n      apply HR.\nQed.\n\n(* END or_distributes_over_and. *)\n\n(* Exercise: 2 stars, optional (andb_false) *)\n\nTheorem andb_false : forall b c, andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b eqn : Hd.\n  Case \"b = true\".\n    simpl in H.\n    right.\n    apply H.\n  Case \"b = false\".\n    left.\n    trivial.\nQed.\n\n(* END andb_false. *)\n\n(* Exercise: 2 stars, optional (orb_false) *)\n\nTheorem orb_prop : forall b c, orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c.\n  intros H.\n  destruct b eqn : Hd.\n  Case \"b = true\".\n    left.\n    trivial.\n  Case \"b = false\".\n    right.\n    simpl in H.\n    apply H.\nQed.\n\n(* END orb_false. *)\n\n(* Exercise: 2 stars, optional (orb_false_elim) *)\n\nTheorem orb_false_elim : forall b c, orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b eqn : Hd.\n  Case \"b = true\".\n    inversion H.\n  Case \"b = false\".\n    split.\n    SCase \"false = false\".\n      trivial.\n    SCase \"c = false\".\n      simpl in H.\n      apply H.\nQed.\n\n(* END orb_false_elim. *)\n\n(* ((Falsehood)) *)\n\n(* Exercise: 2 stars, advanced (True) *)\n\nInductive True : Prop :=\n  truth : True.\n\n(* END True. *)\n\n(* ((Negation)) *)\n\n(* Exercise: 2 stars, advanced (double_neg_inf) *)\n\n(* By definition of negation, ~~P means (P -> False) -> False, i. e. in order\n* to prove a false statement P is enough, and the goal is to prove a false\n* statement. Thus, (P -> False) -> False simplifies to just P, which is given.\n*)\n\n(* END double_neg_inf. *)\n\n(* Exercise: 2 stars (contrapositive) *)\n\nTheorem contrapositive : forall P Q : Prop, (P -> Q) -> (not Q -> not P).\nProof.\n  intros P Q H.\n  unfold not.\n  intros G HP.\n  apply G.\n  apply H.\n  apply HP.\nQed.\n\n(* END contrapositive. *)\n\n(* Exercise: 1 star (not_both_true_and_false) *)\n\nTheorem not_both_true_and_false : forall P : Prop, not (P /\\ not P).\nProof.\n  intros P.\n  unfold not.\n  intros H.\n  inversion H.\n  apply H1.\n  apply H0.\nQed.\n\n(* END not_both_true_and_false. *)\n\n(* Exercise: 1 star, advanced (informal_not_PNP) *)\n\n(* not (P /\\ not P), by definition of negation, is the same as (P /\\ not P) ->\n* False. By definition of /\\, both P and `not P` must be true for the implied\n* False to be true. `not P` unfolds into P -> False, that is, P is sufficient\n* to prove False. P is a given to the implication. *)\n\n(* END informal_not_PNP. *)\n\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    | nil => l2\n    | (x :: l1')%list => rev_append l1' (x :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l nil.\n\n(* Exercise: 5 stars (tr_rev) *)\n\nTheorem snoc_append : forall (X : Type) (x : X) (l : list X),\n  snoc l x = app l (cons x nil).\nProof.\n  induction l; simpl; auto. rewrite -> IHl. trivial.\nQed.\n\nTheorem rev_append_snoc_helper : forall X (x : list X) (a1 a2 : X),\n  (a1 :: (x ++ a2 :: nil))%list = ((a1 :: x) ++ (a2 :: nil))%list.\nProof.\n  induction x.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma rev_append_snoc : forall X (x1 x2 : list X) (a : X),\n  rev_append x1 (x2 ++ a :: nil) = snoc (rev_append x1 x2) a.\nProof.\n  intros X x.\n  induction x.\n  - simpl. intros. rewrite -> snoc_append. reflexivity.\n  - simpl. intros. rewrite -> rev_append_snoc_helper. rewrite -> IHx.\n    reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intro X.\n  apply functional_extensionality.\n  intro x.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite <- IHx. unfold tr_rev. simpl.\n    replace (a :: nil)%list with (nil ++ a :: nil)%list.\n    + rewrite -> rev_append_snoc. reflexivity.\n    + reflexivity.\nQed.\n\n(* END tr_rev. *)\n\nTheorem double_neg : forall P : Prop, P -> ~~P.\nProof.\n  unfold not.\n  intros P P_ PF.\n  apply PF.\n  apply P_.\nQed.\n\n(* Exercise: 3 stars (excluded_middle_irrefutable) *)\n\nTheorem excluded_middle_irrefutable : forall P : Prop, ~ ~ (P \\/ ~P).\nProof.\n  unfold not.\n  intros P H1.\n  apply H1.\n  right.\n  intros P1.\n  apply H1.\n  left.\n  apply P1.\nQed.\n\n(* END excluded_middle_irrefutable. *)\n\nTheorem ex_falso_quodlibet : forall P : Prop, False -> P.\nProof. intros P H. inversion H. Qed.\n\n(* Exercise: 5 stars, advanced, optional (classical_axioms) *)\n\nDefinition pierce := forall P Q : Prop, ((P -> Q) -> P) -> P.\n\nDefinition classic := forall P : Prop, not (not P) -> P.\n\nDefinition excluded_middle := forall P : Prop, P \\/ not P.\n\nDefinition de_morgan_not_and_not := forall P Q : Prop,\n  not (not P /\\ not Q) -> P \\/ Q.\n\nDefinition implies_to_or := forall P Q : Prop, (P -> Q) -> (not P \\/ Q).\n\nTheorem P_or_false : forall P : Prop, P \\/ False -> P.\nProof.\n  intros P PoFH.\n  destruct PoFH.\n  apply H.\n  inversion H.\nQed.\n\nTheorem or_com : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q PQ.\n  destruct PQ.\n  right.\n  apply H.\n  left.\n  apply H.\nQed.\n\nTheorem pierce_implies_classic : pierce -> classic.\nProof.\n  unfold pierce.\n  unfold classic.\n  intros pierce.\n  intros P.\n  unfold not.\n  intros pff.\n  apply pierce with (Q := False).\n  intros pf.\n  apply pff in pf.\n  inversion pf.\nQed.\n\nTheorem classic_implies_pierce : classic -> pierce.\nProof.\n  unfold classic.\n  unfold pierce.\n  intros C.\n  intros P Q PQP.\n  unfold not in C.\n  apply C.\n  intros pf.\n  apply pf.\n  apply PQP.\n  intros P_.\n  apply pf in P_.\n  inversion P_.\nQed.\n\nTheorem classic_implies_excluded_middle : classic -> excluded_middle.\nProof.\n  unfold classic.\n  unfold excluded_middle.\n  intros H.\n  intros P.\n  apply H.\n  apply excluded_middle_irrefutable.\nQed.\n\nTheorem excluded_middle_implies_classic :\n  excluded_middle -> classic.\nProof.\n  unfold excluded_middle.\n  unfold classic.\n  unfold not.\n  intros EM P nnP.\n  assert ((P \\/ (P -> False)) -> P).\n    intros kh.\n    destruct kh.\n    apply H.\n    apply ex_falso_quodlibet.\n    apply nnP.\n    apply H.\n  apply H.\n  apply EM.\nQed.\n\nTheorem classic_implies_de_morgan_not_and_not :\n  classic -> de_morgan_not_and_not.\nProof.\n  unfold classic.\n  intros EM.\n  unfold de_morgan_not_and_not.\n  intros P Q Hand.\n  unfold not in Hand.\n  apply EM.\n  unfold not.\n  intros Hor.\n  apply Hand.\n  split.\n  Case \"P -> False\".\n    intros P_.\n    apply Hor.\n    left.\n    apply P_.\n  Case \"Q -> False\".\n    intros Q_.\n    apply Hor.\n    right.\n    apply Q_.\nQed.\n\nTheorem de_morgan_not_and_not_implies_classic :\n  de_morgan_not_and_not -> classic.\nProof.\n  unfold de_morgan_not_and_not.\n  unfold classic.\n  unfold not.\n  intros H.\n  intros P.\n  intros N.\n  apply P_or_false.\n  apply H.\n  intros R.\n  apply N.\n  intros P_.\n  apply N.\n  destruct R.\n  apply H0.\nQed.\n\nTheorem classic_implies_implies_to_or : classic -> implies_to_or.\nProof.\n  unfold classic.\n  intros CL.\n  unfold implies_to_or.\n  intros P Q.\n  intros H.\n  apply CL.\n  unfold not.\n  intros H1.\n  apply H1.\n  left.\n  intros P_.\n  apply H1.\n  right.\n  apply H.\n  apply P_.\nQed.\n\nTheorem implies_to_or_implies_excluded_middle :\n  implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or.\n  unfold excluded_middle.\n  unfold not.\n  intros ITO P.\n  apply or_com.\n  apply ITO.\n  intros P_.\n  apply P_.\nQed.\n\n(* END classical_axioms. *)\n\n(* Exercise: 2 stars (false_beq_nat) *)\n\nTheorem false_beq_nat : forall n m : nat, n <> m ->  beq_nat n m = false.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      intros H.\n      unfold not in H.\n      apply ex_falso_quodlibet.\n      apply H.\n      trivial.\n    SCase \"m = S m'\".\n      reflexivity.\n  Case \"n = S n'\".\n    destruct m as [|m'].\n    SCase \"m = 0\".\n      reflexivity.\n    SCase \"m = S m'\".\n      intros H.\n      simpl.\n      apply IHn'.\n      unfold not.\n      unfold not in H.\n      intros n'm'.\n      apply H.\n      rewrite -> n'm'.\n      reflexivity.\nQed.\n\n(* END false_beq_nat. *)\n\n(* Exercise: 2 stars, optional (beq_nat_false) *)\n\nTheorem beq_nat_false : forall n m : nat, beq_nat n m = false -> n <> m.\nProof.\n  intros n m H.\n  unfold not.\n  intros nm.\n  rewrite -> nm in H.\n  rewrite <- beq_nat_refl in H.\n  inversion H.\nQed.\n\n(* END beq_nat_false. *)\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7592599492713078}}
{"text": "Require Import Classical.\n\nTheorem Ex025 (A : Prop): A <-> ~~A.\nProof.\n  split.\n  + intro.\n    intro.\n    contradiction.\n  + intro.\n    apply NNPP.\n    intro. \n    contradiction.\nQed.\n\n(*without NNPP*)\n\nTheorem Ex025_2 (A : Prop): A <-> ~~A.\nProof.\n  split.\n  + intro.\n    intro.\n    contradiction.\n  + intro.\n    pose proof (classic A).\n    destruct H0.\n    - exact H0.\n    - contradiction.\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/Ex025.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7592599448326866}}
{"text": "\n(** TD1 *)\n\nSet Universe Polymorphism. (* Indispensable pour [church_minus] (Exo 3) *)\n\n(** Exo 1 *)\n\nDefinition compose {A B C} (f:B->C)(g:A->B) := fun x => f (g x).\n\nCompute compose S pred 7.\nCompute compose S pred 0.\nCompute compose pred S 0.\n\n(** Exo 2 *)\n\nDefinition mybool := forall X, X->X->X.\n\nDefinition mytrue : mybool := fun _ x y => x.\nDefinition myfalse : mybool := fun _ x y => y.\n\nDefinition myif : forall {Y}, mybool -> Y -> Y -> Y :=\n fun _ b x y => b _ x y.\n\nCompute myif mytrue 0 1.\nCompute myif myfalse 0 1.\n\n(** Exo 3 *)\n\nDefinition church := forall X, (X->X)->(X->X).\n\nDefinition zero : church := fun _ f x => x.\nDefinition one : church := fun _ f x => f x.\nDefinition onebis : church := fun _ f => f.\nDefinition two : church := fun _ f x => f (f x).\n\nDefinition succ : church -> church :=\n fun n => fun _ f x => n _ f (f x).\n\nCompute succ one.\n\nDefinition church2nat (n:church) := n _ S 0.\n\nCompute church2nat zero.\nCompute church2nat one.\nCompute church2nat onebis.\nCompute church2nat two.\n\nFixpoint nat2church (n:nat) :=\n match n with\n | O => zero\n | S m => succ (nat2church m)\n end.\n\nCompute nat2church 3.\nCompute church2nat (nat2church 100).\n\nDefinition church_plus (n m:church) : church :=\n  fun _ f x => n _ f (m _ f x).\n\nCompute church_plus one two.\nCompute church2nat (church_plus (nat2church 13) (nat2church 10)).\n\nDefinition church_mult (n m:church) : church :=\n fun _ f =>  n _ (m _ f).\n\nCompute church_mult one two.\nCompute church2nat (church_mult (nat2church 13) (nat2church 10)).\n\nDefinition church_pow (n m:church) : church :=\n fun _ =>  m _ (n _).\n\nCompute church_pow two two.\nCompute church2nat (church_pow (nat2church 2) (nat2church 5)).\n\nDefinition is_zero (n : church) : bool :=\n  n _ (fun _ => false) true.\n\nCompute is_zero zero.\nCompute is_zero one.\n\nCompute church.\n\nDefinition church_pred (n:church) : church :=\n fun _ f x =>\n   n _ (fun g h => h (g f)) (fun _ => x) (fun u => u).\n\nFail Compute (church church).\n\nCompute church2nat (church_pred zero).\nCompute church2nat (church_pred one).\nCompute church2nat (church_pred (nat2church 13)).\n\n(** Attention, donne [universe inconsistency] si les univers\n    polymorphes ne sont pas activés. *)\n\nDefinition church_minus (n m : church) : church :=\n  m _ church_pred n.\n\nDefinition f (x:False) : False := x.\n\nInductive bool :=\n|true : bool\n|false : bool.\n\nCompute bool_rect. \n\nFail Inductive t :=\n|c1 : (t -> t) -> t.\n\n\nCompute church2nat (church_minus two two).\nCompute church2nat (church_minus (nat2church 10) (nat2church 7)).\n\n\n(** Exo 4 *)\n\nOpen Scope bool_scope.\n\nDefinition checktauto f := f true && f false.\nDefinition checktauto2 f := checktauto (compose checktauto f).\nDefinition checktauto3 f := checktauto (compose checktauto2 f).\n\nCompute checktauto3\n        (fun a b c => a || b || c || negb (a && b) || negb (a && c)).\nCompute checktauto3 (fun a b c => a || b || c).\n\n(** A revoir lors du cours sur les \"types dépendants\" :\n    une généralisation de checktauto aux fonctions booléennes\n    à n arguments. P.ex. nbool 2 = bool -> bool -> bool\n    Et nchecktauto 2 se comportera comme le checktauto2 précédent. *)\n\nFixpoint nbool n :=\n match n with\n | 0 => bool\n | S n => bool -> nary n\n end.\n\nFixpoint nchecktauto n : nbool n -> bool :=\n match n with\n | 0 => fun b => b\n | S n => fun f => nchecktauto n (f true) && nchecktauto n (f false)\n end.\n\nCompute nchecktauto 3\n        (fun a b c => a || b || c || negb (a && b) || negb (a && c)).\nCompute nchecktauto 3 (fun a b c => a || b || c).\n\n\n\n(** Exo 5 *)\n\nRequire Import Arith.\n\nFixpoint add n m :=\n match n with\n | 0 => m\n | S n => S (add n m)\n end.\n\nCompute add 3 7.\n\nFixpoint mul n m :=\n match n with\n | 0 => 0\n | S n => add m (mul n m)\n end.\n\nCompute mul 3 7.\n\nFixpoint sub n m :=\n match n, m with\n | _,0 => n\n | 0,_ => n\n | S n, S m => sub n m\n end.\n\nCompute sub 7 3.\nCompute sub 3 7.\n\nFixpoint fact n :=\n match n with\n | 0 => 1\n | S m => mul n (fact m)\n end.\n\nCompute fact 8.\n\nFixpoint pow a b :=\n match b with\n | 0 => 1\n | S b => mul a (pow a b)\n end.\n\nCompute pow 2 10.\n\n(* En Coq 8.4, ajouter:\nRequire Import NPeano.\nInfix \"=?\" := Nat.eqb (at level 70, no associativity) : nat_scope.\n*)\n\nFixpoint modulo_loop a b n :=\n match n with\n | 0 => 0\n | S n =>\n   if a <? b then a\n   else modulo_loop (sub a b) b n\n end.\n\nDefinition modulo a b := modulo_loop a b a.\n\nCompute modulo 10 3.\nCompute modulo 3 0.\n\nFixpoint gcd_loop a b n :=\n  match n with\n  | 0 => 0\n  | S n =>\n    if b =? 0 then a\n    else gcd_loop b (modulo a b) n\n  end.\n\nDefinition gcd a b := gcd_loop a b (S b).\n\nCompute gcd 17 23.\nCompute gcd 23 17.\nCompute gcd 12 9.\nCompute gcd 9 12.\nCompute gcd 10 1.\nCompute gcd 1 10.\nCompute gcd 0 7.\nCompute gcd 7 0.\n\n(* ---------------------------------------- *)\nRequire Import List.\nImport ListNotations.\nCheck [].", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/LMFI/td2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7592140530058559}}
{"text": "(**************************************\n  Finish reading, Finish exercise\n**************************************)\n\nFixpoint beq_nat (n m : nat) : bool :=\n  match n with\n  | O => \n    match m with\n    | O => true\n    | S m' => false\n    end\n  | S n' => \n    match m with\n    | O => false\n    | S m' => beq_nat n' m'\n    end\n  end.\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n  | O => true\n  | S n' =>\n      match m with\n      | O => false\n      | S m' => leb n' m'\n      end\n  end.\n\n\n(** **** Exercise: 1 star (nandb)  *)\nDefinition nandb (b1: bool) (b2: bool): bool :=\n  match b1, b2 with\n  | true, true => false\n  | _, _       => true\n  end.\n\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\n\n(** **** Exercise: 1 star (andb3)  *)\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\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\n\n\n(** **** Exercise: 1 star (factorial)  *)\nFixpoint factorial (n:nat): nat :=\n  match n with\n  | 0 => 1\n  | S n => S n * factorial n\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. reflexivity. Qed.\n\n\n\n(** **** Exercise: 1 star (blt_nat)  *)\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. 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\n\n\n(** ****  Exercise: 1 star (plus_id_exercise)  *)\nTheorem plus_id_exercise: forall n m o: nat, n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros A B.\n  rewrite -> A.\n  rewrite -> B.\n  reflexivity.\nQed.\n\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 H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n\n(** **** Exercise: 2 stars (andb_true_elim2)  *)\nTheorem andb_true_elim2: forall b c: bool, andb b c = true -> c = true.\nProof.\n  intros [] [].\n  - intros H.\n    reflexivity.\n  - simpl.\n    intros H.\n    rewrite H.\n    reflexivity.\n  - reflexivity.\n  - simpl.\n    intros H.\n    rewrite H.\n    reflexivity.\nQed.\n\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)\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\n\n\n(** **** Exercise: 2 stars, optional (decreasing)  *)\n(*\nFixpoint func (n: nat) (c: bool): bool := \n  match n, c with\n  | 0, false => false\n  | 0, true  => true\n  | 1, false => false\n  | 1, true => true\n  | S (S n'), false => func n' true\n  | S (S n'), true => func (S n') false\n  end.\n*)\n\n\n\n\n(** **** Exercise: 2 stars (boolean_functions)  *)\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\n\n(** **** Exercise: 2 stars (andb_eq_orb)  *)\nTheorem andb_eq_orb: forall (b c : bool),\n  (andb b c = orb b c)-> b = c.\nProof.\n  intros [] [].\n  - simpl.\n    reflexivity.\n  - simpl.\n    intro H.\n    rewrite -> H.\n    reflexivity.\n  - simpl.\n    intro H.\n    rewrite H.\n    reflexivity.\n  - reflexivity.\nQed.\n\n\n(** **** Exercise: 3 stars (binary)  *)\nInductive bin: Type :=\n  | zero: bin\n  | twice: bin -> bin\n  | extra: bin -> bin.\n\n\nFixpoint incr (b: bin): bin := \n  match b with\n  | zero => extra zero\n  | twice b' => extra b'\n  | extra b' => twice (incr b')\n  end.\n\nExample test_bin_incr1: incr zero = extra zero.\nProof. reflexivity. Qed.\n\nExample test_bin_incr2: incr (incr zero) = twice (extra zero).\nProof. reflexivity. Qed.\n\nExample test_bin_incr3: incr (incr (incr zero)) = extra (extra zero).\nProof. reflexivity. Qed.\n\nExample test_bin_incr4: incr (incr (incr (incr zero))) = twice (twice (extra zero)).\nProof. reflexivity. Qed.\n\nExample test_bin_incr5: incr (incr (incr (incr (incr zero)))) = extra (twice (extra zero)).\nProof. reflexivity. Qed.\n\n\nFixpoint bin_to_nat (b: bin): nat :=\n  match b with\n  | zero => 0\n  | twice b' => 2 * bin_to_nat b'\n  | extra b' => 1 + 2 * bin_to_nat b'\n  end.\n\n\nExample test_bin_to_nat1: bin_to_nat zero = 0.\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat2: bin_to_nat (incr zero) = 1.\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat3: bin_to_nat (incr (incr zero)) = 2.\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat4: bin_to_nat (incr (incr (incr zero))) = 3.\nProof. reflexivity. Qed.\n\nExample test_bin_to_nat5: bin_to_nat (incr (incr (incr (incr zero)))) = 4.\nProof. reflexivity. Qed.\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8652240964782012, "lm_q1q2_score": 0.7592140523128136}}
{"text": "(***************************************\n    Definitions and facts about words \n    on the alphabet {O, I}\n***************************************)\n\n\nRequire Import Arith.\n\nSection Definitions.\n\n  Inductive char : Type :=\n    | O\n    | I.\n\n  Inductive word : Type :=\n    | Void\n    | Concat: char -> word -> word.\n\n  Fixpoint size (w:word) :=\n    match w with\n    | Void => 0\n    | Concat _ w => 1 + size (w)\n    end.\n\n  Fixpoint concat_words w1 w2 :=\n    match w1 with\n    | Void => w2\n    | Concat c w => \n      Concat c (concat_words w w2)\n    end.\n\n  Notation \"a ^ b\" := (concat_words a b).\n\nEnd Definitions.\n\n\nSection Facts.\n\n  Notation \"a ^ b\" := (concat_words a b).\n\n  Lemma concat_w_void :\n    forall w, w ^ Void = w.\n  Proof.\n    intros.\n    - induction w.\n      + simpl. reflexivity.\n      + simpl. rewrite IHw. reflexivity.\n  Qed.\n\n  Lemma concat_assoc:\n    forall w1 w2 w3, w1 ^ w2 ^ w3 = (w1 ^ w2) ^ w3.\n  Proof.\n    intros.\n    induction w1.\n    + simpl. reflexivity.\n    + simpl. rewrite IHw1. reflexivity.\n  Qed.\n\n\n  Lemma size_concat :\n    forall w1 w2, size (w1 ^ w2) = (size w1) + (size w2).\n  Proof.\n    intros.\n    induction w1 as [|c w IH].\n    + simpl. reflexivity.\n    + simpl. rewrite IH. reflexivity.\n  Qed.\n\n\n  Lemma concat_w_void_void :\n    forall w, concat_words w Void = Void -> w = Void.\n  Proof.\n    intros.\n    induction w.\n    + auto.\n    + simpl in H.\n      discriminate H.\n  Qed.\n\n  Lemma concat_w_w_void: \n    forall u v,  u ^ v = Void -> u = Void /\\ v = Void.\n  Proof.\n    intros.\n    split.\n    + induction v.\n      ++ apply concat_w_void_void. assumption.\n      ++ induction u.\n        * auto.\n        * discriminate H.\n    + induction u.\n      simpl in H; assumption.\n      ++ induction v.\n        * auto.\n        * discriminate H.\n  Qed.\n\n  Lemma concat_left_void :\n    forall v w,\n      v ^ w = v -> w = Void.\n  Proof.\n    intros.\n    induction v.\n    + apply H.\n    + simpl in H.\n      inversion H.\n      apply IHv. assumption.\n  Qed.\n\n  Lemma eq_size:\n    forall u v,\n      u = v -> size(u) = size(v).\n  Proof.\n    intros [|u H1] [|v H2].\n    + auto.\n    + intros []. auto.\n    + intros []. auto.\n    + intros.\n      inversion H.\n      reflexivity.\n  Qed.\n\n  Lemma size_le_concat_l:\n    forall u v, size(v) <= size(u ^ v).\n  Proof.\n    intros.\n    induction u.\n    + simpl. auto.\n    + simpl. apply le_S. assumption.\n  Qed.\n\n  Lemma size_le_concat_r:\n    forall u v, size(v) <= size(v ^ u).\n  Proof.\n    intros.\n    induction v.\n    + simpl. apply Nat.le_0_l.\n    + simpl. apply le_n_S. apply IHv.\n  Qed.\n\n  Lemma size_0_iff:\n    forall u, u = Void <-> size(u) = 0.\n  Proof.\n    intros.\n    split.\n    + intro. rewrite H. auto.\n    + intro. induction u.\n      * reflexivity.\n      * discriminate H.\n  Qed.\n\n  Lemma size_concat_void_l:\n    forall u v, size(u ^ v) = size(v) <-> u = Void.\n  Proof.\n    intros.\n    split.\n    + rewrite size_concat. \n      intro. \n      rewrite Nat.add_comm in H.\n      rewrite <- Nat.add_0_r in H.\n      apply plus_reg_l in H.\n      apply size_0_iff in H. assumption.\n    + intro.\n      rewrite H.\n      auto.\n  Qed.\n\n  Lemma size_concat_void_r:\n    forall u v, size(v ^ u) = size(v) <-> u = Void.\n  Proof.\n    intros.\n    split.\n    + rewrite size_concat.\n      intro.\n      rewrite <- Nat.add_0_r in H.\n      apply plus_reg_l in H.\n      apply size_0_iff in H. assumption.\n    + intro.\n      rewrite H.\n      rewrite concat_w_void.\n      auto.\n  Qed.\n\n  Lemma concat_void_iff:\n    forall u v, u ^ v = Void <-> u = Void /\\ v = Void.\n  Proof.\n    intros.\n    split; intro.\n    - apply eq_size in H.\n      rewrite size_concat in H.\n      simpl in H.\n      apply plus_is_O in H.\n      inversion H. \n      apply size_0_iff in H0.\n      apply size_0_iff in H1.\n      auto.\n    - elim H.\n      intros H2 H3.\n      rewrite H2, H3.\n      simpl. reflexivity.\n  Qed.\n\n\n  Lemma size_concat_void_lr:\n    forall u v w, size(u ^ v ^ w) = size(v) <-> u = Void /\\ w = Void.\n  Proof.\n    intros.\n    split.\n    + intros.\n      induction v.\n      - simpl in H. apply size_0_iff in H.\n        apply concat_w_w_void in H. assumption.\n      - rewrite size_concat in H.\n        rewrite size_concat in H.\n        simpl in H. rewrite Nat.add_comm in H.\n        simpl in H.\n        inversion H.\n        apply IHv.\n        rewrite size_concat.\n        rewrite size_concat.\n        rewrite Nat.add_comm.\n        assumption.\n    + intros.\n      inversion H.\n      rewrite H0, H1.\n      simpl. rewrite concat_w_void. reflexivity.\n  Qed.\n\nEnd Facts.", "meta": {"author": "acorrenson", "repo": "friday_night_mood", "sha": "ab58958ad0adfa68882fe0458e31b59247dfae70", "save_path": "github-repos/coq/acorrenson-friday_night_mood", "path": "github-repos/coq/acorrenson-friday_night_mood/friday_night_mood-ab58958ad0adfa68882fe0458e31b59247dfae70/proof/utils/language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7591353043292297}}
{"text": "From HoTT Require Import Basics Types Spaces.Nat.\n\n(** * Monoids *)\n\n(** This defines the type of monoids as a record, which is equvialent to a nested sigma-type but has the convenience of 'named projections' (explained below). *)\n\nRecord Monoid := {\n    monoid_type : Type;\n    monoid_ishset : IsHSet monoid_type;\n    monoid_unit : monoid_type;\n    monoid_op : monoid_type -> monoid_type -> monoid_type;\n    monoid_op_assoc : forall x y z,\n      monoid_op x (monoid_op y z) = monoid_op (monoid_op x y) z;\n    monoid_left_identity : forall x, monoid_op monoid_unit x = x;\n    monoid_right_identity : forall x, monoid_op x monoid_unit = x;\n  }.\n\n(** [monoid_type], [monoid_op], etc... are \"named projections\" or \"accessors\". Given [M : Monoid], the underlying type is [monoid_type M]. Simlarly, [monoid_op M] is the binary operation. *)\nCheck monoid_type.\n\n(** If we have [M : Monoid], then to pick an element of [M] we have to write [x : monoid_type M]. This line lets us simply write [x : M] by making [monoid_type] a coercion. *)\nCoercion monoid_type : Monoid >-> Sortclass.\n\n(** We make the monoid an implicit argument to some of the accessors, as Coq can usually figure it out. *)\nArguments monoid_unit {_}.\nArguments monoid_op {_} _ _.\nArguments monoid_left_identity {_} _.\nArguments monoid_right_identity {_} _.\n\n(** This adds the fact that monoids are sets to Coq's \"typeclass database,\" which lets us apply results about sets to monoids without having to repeatedly prove to Coq that monoids are sets. *)\nLocal Existing Instance monoid_ishset.\n\n(** Standard notation. *)\nLocal Notation \"1\" := monoid_unit.\nLocal Notation \"x * y\" := (monoid_op x y).\n\n\nRecord MonoidHom (M N : Monoid) := {\n    monoidhom_fun : M -> N;\n    monoidhom_unit : monoidhom_fun 1 = 1;\n    monoidhom_op : forall x y : M,\n      monoidhom_fun (x * y) = monoidhom_fun x * monoidhom_fun y;\n  }.\n\nCoercion monoidhom_fun : MonoidHom >-> Funclass.\n\n\n(** ** Basics *)\n\nLemma unique_left_unit (M : Monoid) (u : M)\n  : (forall x : M, u * x = x) -> (u = 1).\nProof.\n  intro is_left_unit_u.\n  pose (u1 := is_left_unit_u 1).\n  refine (_ @ u1). (* the symbol [@] is for path concatenation *)\n  exact (monoid_right_identity u)^. (* the hat [^] inverts a path *)\nDefined.\n\nLemma unique_right_unit (M : Monoid) (u : M)\n  : (forall x : M, x * u = x) -> (u = 1).\nProof.\n  intro is_right_unit_u.\n  pose (u' := is_right_unit_u 1).\n  exact ((monoid_left_identity u)^ @ u').\nDefined.\n\n(** Next, state and prove the following:  for [x] in a monoid, if [y] is a left-inverse to [x] and [z] is a right-inverse to [x], then [y = z]. *)\n(** It follows that two two-sided inverses are equal.  Do you think it is true that two left-inverses are necessarily equal? *)\n\nLemma inverses_coincide (M : Monoid) (x y z : M) : (y * x = 1) * (x * z = 1) -> (y = z).\nProof.\n  intro pq; destruct pq as (p,q).\n  pose (y_unit := (monoid_right_identity y)^).\n  pose (z_unit := monoid_left_identity z).\n  pose (y_path := y_unit @ (ap (monoid_op(y)) q)^ @ (monoid_op_assoc _ y x z)).\n  exact (y_path @ (ap (fun m => m*z)) p @ z_unit).\nDefined.\n\n\n(** ** The two monoid structures on [Bool] *)\n\n(** Look at the definition of [Bool] in Types/Bool. There are two monoid structures on [Bool], one using [andb] and one using [orb]. *)\n\nDefinition monoid_bool_orb : Monoid.\nProof.\n  (* Coq automatically gives us a function [Build_Monoid] which lets us construct monoids. *)\n  (* [srapply] is a custom tactic in the HoTT library which figures out how many arguments need to be supplied to a function and leaves those as goals for you to figure out. *)\n  srapply (Build_Monoid Bool).\n  - exact false.\n  - intros b1 b2. exact (orb b1 b2).\n  - simpl.\n    induction x; induction y; reflexivity.\n  - simpl. reflexivity.\n  - simpl. induction x; reflexivity.\nDefined.\n\nDefinition monoid_bool_andb : Monoid.\nProof.\n  srapply (Build_Monoid Bool).\n  - exact true.\n  - intros b1 b2. exact (andb b1 b2).\n  - induction x; induction y; reflexivity.\n  - simpl. reflexivity.\n  - simpl. induction x; reflexivity.\nDefined.\n\n(** The negation function [negb] defines a homomorphism between these monoid structures. *)\n\nDefinition monoid_negb : MonoidHom monoid_bool_andb monoid_bool_orb.\n  srapply Build_MonoidHom.\n  - intro b. induction b.\n    + exact false.\n    + exact true.\n  - simpl. reflexivity.\n  - simpl. induction x; reflexivity.\nDefined.\n\n\n(** ** The monoid structure on [nat] *)\n\n(** Next show that set of natural numbers is a monoid. The natural numbers are defined in Basics/Overture (search for \"Natural numbers\"), and there are useful functions in Spaces/Nat. You can also use Coq's search functionality to find things, by giving the signature of the term that you want: *)\nSearch (nat -> nat -> nat).\n  \nDefinition monoid_nat : Monoid.\nProof.\nsrapply (Build_Monoid nat).\n- exact O.\n- exact add.\n- intros x y z. induction x.\n  + reflexivity.\n  + exact (ap (add 1) IHx).\n- reflexivity.\n- induction x.\n  + reflexivity.\n  + exact (ap (add 1) IHx).\nDefined.\n\n(* Need to prove that everything in the image of the proposed homomorphism below commutes, so I define it as a\n   function of its underlying types first and check the identifications in the next Lemma. *)\n\n\n(* Essentially exponentiation on x by natural numbers *)\nDefinition ptd_mon_function (M : Monoid) (x : M) : monoid_nat -> M.\nProof.\n  - intro n. induction n.\n    + exact 1.\n    + exact (IHn * x).\nDefined.\n\n(* Is there a way to coerce Coq into understanding a different encoding for a function? Writing\n   ptd_mon_function M x for each application is a bit cumbersome and obfuscates the code, but I wanted a \n   descriptive name. *)\nLemma xy_paths_commute (M : Monoid) (x : M) : forall y, (ptd_mon_function _ x y)*x = x*(ptd_mon_function _ x y).\nProof.\n  intro y. induction y.\n  + cbn.\n    pose (u1 := monoid_left_identity x).\n    pose (u2 := (monoid_right_identity x)^).\n    exact (u1 @ u2).\n  + cbn. \n    pose (ap_IH := ap (fun m => m*x) IHy).\n    pose (assoc := monoid_op_assoc M x (ptd_mon_function M x y) x).\n    exact (ap_IH @ assoc^).\nDefined.\n\n(** Next state and prove that if [M] is any monoid with a chosen element [x], there is a monoid homomorphism from [nat] to [M] sending [1] to [x]. *)\n\n(* Jarl and I did a similar path concatenation on the board; is there a more concise way of making this proof go through? *)\n\nLemma pointed_monoid_from_nat (M : Monoid) (x : M) : MonoidHom monoid_nat M.\nProof.\nsrapply Build_MonoidHom.\n- exact (ptd_mon_function M x).\n- cbn. reflexivity.\n- intros x0. cbn. induction x0.\n  + intro y. cbn. symmetry. apply monoid_left_identity.\n  + intro y. cbn.\n    pose (ap_IH := ap (fun m => m*x) (IHx0 y)).\n    pose (assoc := monoid_op_assoc M (ptd_mon_function M x x0) (ptd_mon_function M x y) x).\n    pose (IH_assoc := ap_IH @ assoc^).\n    pose (ap_comm_paths := ap (monoid_op (ptd_mon_function M x x0)) (xy_paths_commute M x y)).\n    pose (IH_assoc_comm := IH_assoc @ ap_comm_paths).\n    pose (assoc' := monoid_op_assoc M (ptd_mon_function M x x0) x (ptd_mon_function M x y)).\n    exact (IH_assoc_comm @ assoc').\nDefined.\n", "meta": {"author": "JacobEnder", "repo": "Coq-HoTT-Exercises", "sha": "166ae957769ba9b38bd09a01bf97ecfc8bfd370a", "save_path": "github-repos/coq/JacobEnder-Coq-HoTT-Exercises", "path": "github-repos/coq/JacobEnder-Coq-HoTT-Exercises/Coq-HoTT-Exercises-166ae957769ba9b38bd09a01bf97ecfc8bfd370a/Completed/Monoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.7590479406258328}}
{"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\".\nRequire Export IndProp.\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  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.\nSearch total_relation.\nTheorem total_relation_not_partial :\n  ~(partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply tot_rel.\n    - apply tot_rel.\n    }\n  inversion Nonsense.   Qed.\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    (* FILL IN HERE *) Admitted.\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  (* 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 (le_S_n)  *)\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(** **** Exercise: 1 star, optional (le_Sn_n)  *)\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 (le_not_symmetric)  *)\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 (le_antisymmetric)  *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  intros a b LH RH. inversion LH as [ | a1 Hab ].\n  - reflexivity.\n  - assert (S a1 <= a1).\n    { \n      apply le_trans with a.\n      rewrite -> H.\n      + assumption.\n      + assumption.\n    }\n    apply le_Sn_n in H0.\n    inversion 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  intros n m p Hnm Hmp. unfold lt in Hnm.\n  assert (S n <= S p).\n  {\n    apply le_trans with m. \n    - assumption.\n    - assumption.\n  }\n  apply le_S_n.\n  assumption.\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\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 Hyz.\n  induction Hxy as [x| x y y' Rxy Hyy].\n  - assumption.\n  - apply rt1n_trans with y.\n    + assumption.\n    + apply IHHyy in Hyz. apply Hyz.\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, 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", "meta": {"author": "yijunc", "repo": "FunctionalProgramming", "sha": "b3f585f6a39e114c8cd2fc5ae872f713777a9154", "save_path": "github-repos/coq/yijunc-FunctionalProgramming", "path": "github-repos/coq/yijunc-FunctionalProgramming/FunctionalProgramming-b3f585f6a39e114c8cd2fc5ae872f713777a9154/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8887587964389112, "lm_q1q2_score": 0.7589224639688928}}
{"text": "Require Import init.\n\nRequire Export nat_base.\nRequire Export nat_plus.\nRequire Export nat_mult.\nRequire Export nat_order.\nRequire Export nat_binom.\n\nFixpoint nat_mult {U} `{Plus U, Zero U} (a : nat) (b : U) :=\n    match a with\n    | nat_zero => 0\n    | nat_suc a' => b + nat_mult a' b\n    end.\nInfix \"×\" := nat_mult (at level 40, left associativity).\nArguments nat_mult : simpl never.\n\nFixpoint nat_pow {U} `{Mult U} `{One U} a b :=\n    match b with\n    | nat_zero => 1\n    | nat_suc b' => nat_pow a b' * a\n    end.\nInfix \"^\" := nat_pow : nat_scope.\nArguments nat_pow : simpl never.\n\n(* begin hide *)\nSection NatAbstract.\n\nContext {U} `{OrderedField U}.\nLocal Open Scope nat_scope.\n(* end hide *)\nTheorem nat_mult_lanni : ∀ a, 0 × a = 0.\nProof.\n    reflexivity.\nQed.\n\nTheorem nat_mult_suc : ∀ n a, (nat_suc n) × a = a + n × a.\nProof.\n    reflexivity.\nQed.\n\nTheorem nat_mult_ranni : ∀ a, a × 0 = 0.\nProof.\n    intros a.\n    nat_induction a.\n    -   apply nat_mult_lanni.\n    -   rewrite nat_mult_suc.\n        rewrite plus_lid.\n        exact IHa.\nQed.\n\nTheorem nat_mult_lid : ∀ a, 1 × a = a.\nProof.\n    intros a.\n    rewrite <- nat_one_eq.\n    rewrite nat_mult_suc, nat_mult_lanni.\n    apply plus_rid.\nQed.\n\nTheorem nat_mult_ldist : ∀ a b c, a × (b + c) = a × b + a × c.\nProof.\n    intros a b c.\n    nat_induction a.\n    -   do 3 rewrite nat_mult_lanni.\n        rewrite plus_lid.\n        reflexivity.\n    -   do 3 rewrite nat_mult_suc.\n        do 2 rewrite <- plus_assoc.\n        apply lplus.\n        rewrite plus_assoc.\n        rewrite (plus_comm (a × b) c).\n        rewrite <- plus_assoc.\n        apply lplus.\n        exact IHa.\nQed.\n\nTheorem nat_mult_rdist : ∀ a b c, (a + b) × c = a × c + b × c.\nProof.\n    intros a b c.\n    nat_induction a.\n    -   rewrite nat_mult_lanni.\n        do 2 rewrite plus_lid.\n        reflexivity.\n    -   rewrite nat_plus_lsuc.\n        do 2 rewrite nat_mult_suc.\n        rewrite IHa.\n        apply plus_assoc.\nQed.\n\nTheorem nat_mult_mult : ∀ a b c, a × (b × c) = (a * b) × c.\nProof.\n    intros a b c.\n    nat_induction a.\n    -   rewrite mult_lanni.\n        do 2 rewrite nat_mult_lanni.\n        reflexivity.\n    -   rewrite nat_mult_suc.\n        rewrite nat_mult_lsuc.\n        rewrite IHa.\n        rewrite nat_mult_rdist.\n        reflexivity.\nQed.\n\nTheorem nat_mult_rneg : ∀ a b, -(a × b) = a × (-b).\nProof.\n    intros a b.\n    nat_induction a.\n    -   do 2 rewrite nat_mult_lanni.\n        apply neg_zero.\n    -   do 2 rewrite nat_mult_suc.\n        rewrite neg_plus.\n        rewrite IHa.\n        reflexivity.\nQed.\n\nTheorem nat_pow_zero : ∀ a, a ^ 0 = 1.\nProof.\n    reflexivity.\nQed.\n\nTheorem nat_pow_suc : ∀ a n, a ^ (nat_suc n) = a^n * a.\nProof.\n    reflexivity.\nQed.\n\nTheorem zero_nat_pow : ∀ n, 0 ^ (nat_suc n) = 0.\nProof.\n    intros n.\n    rewrite nat_pow_suc.\n    apply mult_ranni.\nQed.\n\nTheorem nat_pow_one : ∀ a, a ^ 1 = a.\nProof.\n    intros a.\n    rewrite <- nat_one_eq.\n    rewrite nat_pow_suc.\n    rewrite nat_pow_zero.\n    apply mult_lid.\nQed.\n\nTheorem one_nat_pow : ∀ n, 1 ^ n = 1.\nProof.\n    nat_induction n.\n    -   apply nat_pow_zero.\n    -   rewrite nat_pow_suc.\n        rewrite IHn.\n        apply mult_lid.\nQed.\n\nTheorem nat_pow_plus : ∀ a m n, a ^ (m + n) = a ^ m * a ^ n.\nProof.\n    intros a m n.\n    nat_induction n.\n    -   rewrite nat_pow_zero, mult_rid.\n        rewrite plus_rid.\n        reflexivity.\n    -   rewrite nat_plus_rsuc.\n        do 2 rewrite nat_pow_suc.\n        rewrite IHn.\n        rewrite mult_assoc.\n        reflexivity.\nQed.\n\nTheorem nat_pow_mult : ∀ a b n, (a * b) ^ n = a ^ n * b ^ n.\nProof.\n    intros a b n.\n    nat_induction n.\n    -   do 3 rewrite nat_pow_zero.\n        rewrite mult_lid.\n        reflexivity.\n    -   do 3 rewrite nat_pow_suc.\n        rewrite IHn.\n        do 2 rewrite <- mult_assoc.\n        apply lmult.\n        do 2 rewrite mult_assoc.\n        apply rmult.\n        apply mult_comm.\nQed.\n\nTheorem nat_pow_pow : ∀ a m n, (a ^ m) ^ n = a ^ (m * n).\nProof.\n    intros a m n.\n    nat_induction n.\n    -   rewrite mult_ranni.\n        do 2 rewrite nat_pow_zero.\n        reflexivity.\n    -   rewrite nat_pow_suc.\n        rewrite IHn.\n        rewrite nat_mult_rsuc.\n        rewrite nat_pow_plus.\n        apply mult_comm.\nQed.\n\nTheorem nat_pow_not_zero : ∀ a n, 0 ≠ a → 0 ≠ a ^ n.\nProof.\n    intros a n a_nz eq.\n    nat_induction n.\n    -   rewrite nat_pow_zero in eq.\n        exact (not_trivial_one eq).\n    -   apply IHn.\n        rewrite nat_pow_suc in eq.\n        pose proof (mult_zero _ _ eq) as [an_z|a_z].\n        +   exact an_z.\n        +   contradiction.\nQed.\n\nTheorem nat_pow_neg_even : ∀ n, (-1) ^ (2*n) = 1.\nProof.\n    intros n.\n    nat_induction n.\n    -   rewrite mult_ranni.\n        apply nat_pow_zero.\n    -   rewrite nat_mult_rsuc.\n        rewrite nat_pow_plus.\n        rewrite IHn.\n        rewrite mult_rid.\n        rewrite nat_pow_plus.\n        rewrite nat_pow_one.\n        rewrite mult_neg_one.\n        apply neg_neg.\nQed.\n\nTheorem nat_pow_neg_odd : ∀ n, (-1) ^ (2*n + 1) = -1.\nProof.\n    intros n.\n    rewrite nat_pow_plus.\n    rewrite nat_pow_neg_even.\n    rewrite mult_lid.\n    apply nat_pow_one.\nQed.\n\nTheorem nat_pow_neg_binom2 : ∀ n,\n    (-1) ^ binom (nat_suc (nat_suc n)) 2 = -(-1) ^ binom n 2.\nProof.\n    intros n.\n    change 2 with (nat_suc (nat_suc 0)) at 1.\n    do 3 rewrite binom_suc.\n    rewrite binom_zero.\n    rewrite binom_one.\n    rewrite <- plus_assoc.\n    rewrite nat_pow_plus.\n    rewrite nat_pow_one.\n    rewrite mult_neg_one.\n    rewrite plus_assoc.\n    rewrite plus_two.\n    rewrite nat_pow_plus.\n    rewrite nat_pow_neg_even.\n    rewrite mult_lid.\n    reflexivity.\nQed.\n\nTheorem nat_pow_pos : ∀ a n, 0 ≤ a → 0 ≤ a^n.\nProof.\n    intros a n a_pos.\n    nat_induction n.\n    -   rewrite nat_pow_zero.\n        apply one_pos.\n    -   rewrite nat_pow_suc.\n        apply le_mult; assumption.\nQed.\n\nTheorem nat_pow_pos2 : ∀ a n, 0 < a → 0 < a^n.\nProof.\n    intros a n a_pos.\n    nat_induction n.\n    -   rewrite nat_pow_zero.\n        exact one_pos.\n    -   rewrite nat_pow_suc.\n        apply lt_mult; assumption.\nQed.\n\nTheorem nat_pow_le : ∀ a m n, 1 ≤ a → m ≤ n → a^m ≤ a^n.\nProof.\n    intros a m n a_ge mn.\n    apply nat_le_ex in mn as [c eq]; subst.\n    nat_induction c; [>rewrite plus_rid; apply refl|].\n    rewrite nat_plus_rsuc.\n    rewrite nat_pow_suc.\n    apply (trans IHc).\n    rewrite <- le_mult_1_a_b_ba_pos.\n    +   exact a_ge.\n    +   apply nat_pow_pos2.\n        exact (lt_le_trans one_pos a_ge).\nQed.\n\nTheorem nat_pow_lt : ∀ a m n, 1 < a → m < n → a^m < a^n.\nProof.\n    intros a m n a_gt mn.\n    assert (∀ n, a ^ n < a ^ n * a) as lemma.\n    {\n        clear m n mn.\n        intros n.\n        rewrite <- lt_mult_1_a_b_ba_pos.\n        +   exact a_gt.\n        +   apply nat_pow_pos2.\n            exact (trans one_pos a_gt).\n    }\n    apply nat_lt_ex in mn as [c eq]; subst.\n    rewrite nat_plus_rsuc.\n    nat_induction c.\n    -   rewrite plus_rid.\n        apply lemma.\n    -   rewrite nat_pow_suc.\n        apply (trans IHc).\n        rewrite nat_plus_rsuc.\n        apply lemma.\nQed.\n\nTheorem nat_pow_le_one : ∀ a n, 1 ≤ a → 1 ≤ a^n.\nProof.\n    intros a n a_one.\n    nat_induction n.\n    -   rewrite nat_pow_zero.\n        apply refl.\n    -   rewrite nat_pow_suc.\n        rewrite <- (mult_lid 1).\n        apply le_lrmult_pos; [>\n            apply one_pos|\n            apply one_pos|\n            exact IHn|\n            exact a_one\n        ].\nQed.\n\nTheorem nat_pow_lt_one : ∀ a n, 1 < a → 1 < a^(nat_suc n).\nProof.\n    intros a n a_one.\n    nat_induction n.\n    -   rewrite nat_pow_one.\n        exact a_one.\n    -   rewrite nat_pow_suc.\n        rewrite <- (mult_lid 1).\n        apply lt_lrmult_pos; [>\n            apply one_pos|\n            apply one_pos|\n            exact IHn|\n            exact a_one\n        ].\nQed.\n(* begin hide *)\nEnd NatAbstract.\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/Number/Nat/nat_abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7589127682069472}}
{"text": "Require Import Logic.Rel.R.\nRequire Import Logic.Rel.Include.\nRequire Import Logic.Rel.Properties.\n\nRequire Import Logic.Fol.Syntax.\nRequire Import Logic.Fol.Functor.\n\n\nDefinition congruent (v:Type) (r:Rel (P v)) : Prop := \n    (forall (p1 p2 q1 q2:P v), r p1 q1 -> r p2 q2 -> r (Imp p1 p2) (Imp q1 q2)) /\\\n    (forall (x:v) (p1 q1:P v), r p1 q1 -> r (All x p1) (All x q1)).\n\nArguments congruent {v} _.\n\nDefinition congruence (v:Type) (r:Rel (P v)) : Prop :=\n   equivalence r /\\ congruent r. \n\nArguments congruence {v} _.\n\nLemma fmap_congruence : forall (v w:Type) (f:v -> w) (r:Rel (P w)),\n    congruence r -> congruence (fun (p q:P v) => r (fmap f p) (fmap f q)).\nProof.\n    intros v w f r [H1 [HImp HAll]]. \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 HImp.\n        + intros x s1 t1. apply HAll.\nQed. \n\n(* Congruence relation generated by a given relation on P v.                    *)\nInductive Cong (v:Type) (r:Rel (P v)) : Rel (P v) :=\n| CongBase  : forall (p q:P v), r p q -> Cong v r p q\n| CongRefl  : forall (p:P v), Cong v r p p\n| CongSym   : forall (p q:P v), Cong v r p q -> Cong v r q p\n| CongTrans : forall (p q t:P v), Cong v r p q -> Cong v r q t -> Cong v r p t\n| CongImp   : forall (p1 p2 q1 q2:P v), \n    Cong v r p1 q1 -> \n    Cong v r p2 q2 ->\n    Cong v r (Imp p1 p2) (Imp q1 q2)\n| CongAll   : forall (x:v) (p1 q1:P v),\n    Cong v r p1 q1 ->\n    Cong v r (All x p1 )(All x q1)\n.\n  \nArguments Cong      {v}.\nArguments CongBase  {v}.\nArguments CongRefl  {v}.\nArguments CongSym   {v}.\nArguments CongTrans {v}.\nArguments CongImp   {v}.\nArguments CongAll   {v}.\n\n(* The congruence relation generated by a given relation is reflexive.          *)\nLemma Cong_reflexive : forall (v:Type) (r:Rel (P 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 (P 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 (P 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 (P 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 (P v)), congruent (Cong r).\nProof.\n    intros v r. unfold congruent. split.\n    - apply CongImp.\n    - apply CongAll.\nQed.\n\n(* The congruence relation generated by a given relation is a congruence.       *)\nLemma Cong_congruence : forall (v:Type) (r:Rel (P 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 (P 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 (P 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/Fol/Congruence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7589127586932253}}
{"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.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": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/real/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7588751558775858}}
{"text": "Inductive month : Set :=\n  | January  | February | March  | April     | May\n  | June     | July    | August | September | October\n  | November | December.\n\nPrint month_rect.\nPrint month_ind.\nPrint month_rec.\n\nInductive season : Set :=\n  | Winter | Spring | Summer | Fall.\n\nPrint month_rec.\n\nDefinition season_for_month : month -> season\n  := month_rec (fun _ => season)\n               Winter Winter Winter\n               Spring Spring Spring\n               Summer Summer Summer\n               Fall Fall Fall.\n\nPrint season_for_month.\n\nDefinition season_for_month' (m : month) : season :=\n  match m with\n      | January => Winter\n      | February => Winter\n      | March => Winter\n      | April => Spring\n      | May => Spring\n      | June => Spring\n      | July => Summer\n      | August => Summer\n      | September => Summer\n      | October => Fall\n      | November => Fall\n      | December => Fall\n  end.\n\n\nTheorem month_equal :\n  forall m : month, m = January \\/ m = February \\/ m = March     \\/\n                    m = April   \\/ m = May      \\/ m = June      \\/\n                    m = July    \\/ m = August   \\/ m = September \\/\n                    m = October \\/ m = November \\/ m = December.\nProof.\n  intro m.\n  pattern m.\n  Check month_ind.\n  apply month_ind.\n  left. reflexivity.\n  right. left. reflexivity.\n  right. right. left. reflexivity.\n  right. right. right. left. reflexivity.\n  right. right. right. right. left. reflexivity.\n  right. right. right. right. right. left. reflexivity.\n  right. right. right. right. right. right. left. reflexivity.\n  right. right. right. right. right. right. right. left. reflexivity.\n  right. right. right. right. right. right. right. right. left. reflexivity.\n  right. right. right. right. right. right. right. right. right. left. reflexivity.\n  right. right. right. right. right. right. right. right. right.\n  right. left. reflexivity.\n  right. right. right. right. right. right. right. right. right.\n  right. right. reflexivity.\nQed.\n\n(* right? right. *)\n\nTheorem bool_equal_0 : forall b : bool, b = true \\/ b = false.\nProof.\n  Check bool_ind.\n  Check or_introl.\n  Check or_intror.\n  Check refl_equal.\n  Check (bool_ind (fun b : bool => b = true \\/ b = false)\n                  (or_introl _ (refl_equal true))\n                  (or_intror _ (refl_equal false))).\n  exact (bool_ind (fun b : bool => b = true \\/ b = false)\n                  (or_introl _ (refl_equal true))\n                  (or_intror _ (refl_equal false))).\nQed.\n\nTheorem t : True \\/ True.\nProof.\n  Print or_introl.\n  Print True.\n  exact (or_introl True I).\nQed.\n\n(* yep.. still don't know what I'm doing... :-[ *)\n\n\nTheorem bool_equal_1 : forall b : bool, b = true \\/ b = false.\nProof.\n  intro b.\n  pattern b.\n  Check bool_ind.\n  apply bool_ind.\n  left.\n  reflexivity.\n  right.\n  reflexivity.\nQed.\n\nDefinition f_0 (b : bool) :=\n  match b with\n  | true  => 1\n  | false => 2\n  end.\n\nPrint f_0.\n\nDefinition month_length (leap : bool) (m : month) : nat :=\n  match m with\n  | January  => 31\n  | February => if leap then 29 else 28\n  | March => 31\n  | April => 30\n  | May => 31\n  | June => 30\n  | July => 31\n  | August => 31\n  | September => 30\n  | October => 31\n  | November => 30\n  | December => 31\n  end.\n\nCheck month_rec.\nDefinition month_length' (leap : bool) : month -> nat :=\n  month_rec (fun (m : month) => nat)\n            31\n            (if leap then 29 else 28)\n            31\n            30\n            31\n            30\n            31\n            31\n            30\n            31\n            30\n            31.\n\nDefinition month_length'' (leap : bool) (m : month) : nat :=\n  match m with\n  | February => if leap then 29 else 28\n  | April => 30\n  | June => 30\n  | September => 30\n  | November => 30\n  | otherwise => 31\n  end.\n\nEval compute in month_length'' false April.\n\n\nSection ex_6_6.\n  Definition bool_and (b1 b2 : bool) : bool :=\n    match b1 with\n    | true  => b2\n    | false => false\n    end.\n\n  Definition bool_or (b1 b2 : bool) : bool :=\n    match b1 with\n    | true  => true\n    | false => b2\n    end.\n\n  Definition bool_xor (b1 b2 : bool) : bool :=\n    match b1 with\n    | false => b2\n    | true => match b2 with\n              | true  => false\n              | false => true\n              end\n    end.\n\n  Definition bool_not (b : bool) : bool :=\n    match b with\n    | false => true\n    | true  => false\n    end.\n\n  Definition bool_eq (b1 b2 : bool) : bool :=\n    match b1 with\n    | false => bool_not b2\n    | true  => b2\n    end.\n              \n  Theorem bool_xor_not_eq_iso : forall b1 b2 : bool,\n                                     bool_xor b1 b2 = bool_not (bool_eq b1 b2).\n  Proof.\n    intros b1 b2.\n    unfold bool_xor.\n    unfold bool_not.\n    unfold bool_eq.\n    pattern b1.\n    apply bool_ind.\n    reflexivity.\n    pattern b2.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n  \n  Theorem bool_not_and_iso_or_not_not : forall b1 b2 : bool,\n                                          bool_not (bool_and b1 b2) =\n                                          bool_or (bool_not b1) (bool_not b2).\n  Proof.\n    intros b1 b2.\n    unfold bool_or.\n    pattern b1.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem bool_not_not_iso : forall b : bool, bool_not (bool_not b) = b.\n  Proof.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem bool_or_not_iso_true : forall b : bool, bool_or b (bool_not b) = true.\n  Proof.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem bool_eq_iso_eq : forall b1 b2 : bool, b1 = b2 -> bool_eq b1 b2 = true.\n  Proof.\n    intros b1 b2.\n    pattern b2.\n    apply bool_ind.\n    intros H_b1_eq_true.\n    rewrite -> H_b1_eq_true.\n    simpl bool_eq.\n    reflexivity.\n    intros H_b1_eq_false.\n    rewrite -> H_b1_eq_false.\n    simpl bool_eq.\n    reflexivity.\n  Qed.\n\n  Theorem not_or_eq_and_not_not : forall b1 b2 : bool,\n                                    bool_not (bool_or b1 b2) = bool_and (bool_not b1)\n                                                                        (bool_not b2).\n  Proof.\n    intros b1 b2.\n    pattern b1.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem or_and_and_eq_and_or : forall b1 b2 b3 : bool,\n                                   bool_or (bool_and b1 b3) (bool_and b2 b3) =\n                                   bool_and (bool_or b1 b2) b3.\n  Proof.\n    intros b1 b2 b3.\n    pattern b1.\n    apply bool_ind.\n    simpl.\n    pattern b2.\n    apply bool_ind.\n    simpl.\n    unfold bool_or.\n    pattern b3.\n    apply bool_ind.\n    reflexivity.\n    reflexivity.\n    pattern b3.\n    apply bool_ind.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\nEnd ex_6_6.\n\nRequire Import ZArith.\n\nInductive plane : Set := point : Z -> Z -> plane.\n\nPrint plane_ind.\n\nDefinition abscissa (p : plane) : Z :=\n  match p with point x y => x end.\n\nReset plane.\n\nRecord plane : Set := point { abscissa : Z; ordinate : Z }.\n\nPrint plane.\n\nPrint abscissa.\n\nOpen Scope Z_scope.\n\nDefinition ex_6_8 (p : plane) : Z :=\n  let (abscissa, ordinate) := p\n  in Zabs abscissa + Zabs ordinate.\n\nEval compute in ex_6_8 (point 1 3).\n\nInductive vehicle : Set :=\n  | bicycle   : nat -> vehicle\n  | motorized : nat -> nat -> vehicle.\n\nPrint vehicle_ind.\n\nDefinition nb_wheels (v : vehicle) : nat :=\n  match v with\n  | bicycle _     => 2%nat\n  | motorized _ n => n\n  end.\n\nDefinition nb_seats (v : vehicle) : nat :=\n  match v with\n  | bicycle   n   => n\n  | motorized n _ => n\n  end.\n\nCheck vehicle_rec.\n\nDefinition nb_seats' (v : vehicle) : nat :=\n  vehicle_rec (fun _   => nat)\n              (fun n   => n)\n              (fun n _ => n)\n              v.\n\nPrint nb_seats'.\n\nOpen Scope nat_scope.\n\nTheorem at_least_28 : forall (leap:bool) (m:month), 28 <= month_length leap m.\nProof.\n  intros leap m.\n  case m ; simpl ; auto with arith.\n  case leap; simpl ; auto with arith.\nQed.\n\nReset at_least_28.\n\nTheorem at_least_28 : forall (leap:bool) (m:month), 28 <= month_length leap m.\nProof.\n  intros leap m.\n  case m.\n  simpl month_length.\n  Check le_n.\n  Check le_S.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  case leap.\n  apply le_S.\n  apply le_n.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_n.\n  simpl month_length.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\n(* that was tiring *)\nPrint at_least_28.\nPrint le_S.\n\nDefinition next_month (m : month) : month :=\n  match m with\n      January => February | February  => March     | March     => April\n  |   April   => May      | May       => June      | June      => July\n  |   July    => August   | August    => September | September => October\n  |   October => November | November  => December  | December  => January\n  end.\n\n(* this version is way less interesting. *)\nTheorem next_auguest_then_july_boring :\n  forall m : month, m = July -> next_month m = August.\nProof.\n  intros m.\n  intros H_m_eq_july.\n  rewrite -> H_m_eq_july.\n  simpl.\n  reflexivity.\nQed.  \n\nTheorem next_august_then_july :\n  forall m : month, next_month m = August -> m = July.\nProof.\n  intros m.\n  case m ; simpl ; intros H_next_eq; discriminate H_next_eq || reflexivity.\n  (* The above was very compact, but I think some connectives would\nimprove understandably. *)\nQed.\n\n(* I am having a hard time understanding the evidence function of this: *)\nPrint next_august_then_july.\n(* a bit complex no? *)\n\nTheorem not_January_eq_February : ~January = February.\nProof.\n  unfold not.\n  intros H_january_eq_february.\n  change ((fun m:month => match m with January => True | _ => False end)\n          February).\n  rewrite <- H_january_eq_february.\n  trivial.\nQed.\n\nPrint month_rect.\n\nDefinition is_January' (m:month) : Prop :=\n  match m with\n    January => True\n  | _       => False\n  end.\n\nDefinition is_January (m:month) : Prop :=\n  month_rect (fun _ => Prop)\n             True\n             False\n             False\n             False\n             False\n             False\n             False\n             False\n             False\n             False\n             False\n             False\n             m.\n\nEval compute in is_January January.\nEval compute in is_January March.\n\nTheorem not_true_false : ~true = false.\nProof.\n  unfold not.\n  intros H_eq.\n  change ((fun (v:bool) => match v with true => True | false => False end)\n          false).\n  rewrite <- H_eq.\n  trivial.\nQed.\n\nPrint not_true_false.\n\nTheorem not_bike_eq_moto : forall (n m : nat), ~(bicycle n = motorized n m).\nProof.\n  intros n m.\n  unfold not.\n  intro H_eq.\n  change ((fun (v : vehicle) => match v with\n                                  bicycle _ => True\n                                | motorized _ _ => False\n                                end)\n          (motorized n m)).\n  rewrite <- H_eq.\n  trivial.\nQed.\n\nTheorem not_bike_eq_moto' : forall (n m : nat), ~(bicycle n = motorized n m).\nProof.\n  intros n m.\n  unfold not.\n  intros H_eq.\n  discriminate H_eq.\nQed.\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/inductive_data_types_chap_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7588403385632807}}
{"text": "(*|\n#######################################\nCoq: adding a \"strong induction\" tactic\n#######################################\n\n:Link: https://stackoverflow.com/q/20883855\n|*)\n\n(*|\nQuestion\n********\n\n\"Strong\" (or \"complete\") induction on the natural number means that\nwhen proving the induction step on ``n``, you can assume the property\nholds for any ``k``\n|*)\n\nRequire Import PeanoNat. (* .none *)\nTheorem strong_induction :\n  forall P : nat -> Prop,\n    (forall n : nat, (forall k : nat, (k < n -> P k)) -> P n) ->\n    forall n : nat, P n.\n\n(*| .. coq:: none |*)\n\nProof.\n  intros P H n. induction n; apply H; intros k H0.\n  - contradiction (Nat.nlt_0_r k).\n  - rewrite Nat.lt_succ_r, Nat.le_lteq in H0. destruct H0.\n    + clear IHn. revert k H0. induction n; intros k H0.\n      * contradiction (Nat.nlt_0_r k).\n      * rewrite Nat.lt_succ_r, Nat.le_lteq in H0. destruct H0.\n        -- exact (IHn _ H0).\n        -- subst k. exact (H _ IHn).\n    + now subst k.\nQed.\n\n(*|\nI have managed to prove this theorem without too many difficulties.\nNow I want to use it in a new tactic, ``strong_induction``, which\nshould be similar to the standard ``induction n`` technique on the\nnatural numbers. Recall that when using ``induction n`` when ``n`` is\na natural number and the goal is ``P(n)``, we get two goals: one of\nthe form ``P(0)`` and the second of the form ``P(S(n))``, where for\nthe second goal we get ``P(n)`` as assumption.\n\nSo I want, when the current goal is ``P(n)``, to get one new goal,\nalso ``P(n)``, but the new assumption ``forall k : nat, (k < n ->\nP(k)))``.\n\nThe problem is I don't know how to do it technically. My main problem\nis this: suppose ``P`` is a complex statement, i.e.\n\n.. coq:: none\n|*)\n\nGoal forall a b, exists q r : nat, a = b * q + r.\n  intros a b.\n\n(*||*)\n\n  Show. (* .unfold .goals *)\n\n(*|\nwith ``a b : nat`` in the context; how can I tell Coq to do the strong\ninduction on ``a`` and not on ``b``? Simply doing ``apply\nstrong_induction`` results in\n|*)\n\n  apply strong_induction; intros. (* .none *)\n  Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nwhere the assumption is useless (since ``n`` does not relate to ``a``)\nand I have no idea what the second goal means.\n|*)\n\n(*|\nAnswer\n******\n\nIn this case, to ``apply strong_induction`` you need to ``change`` the\nconclusion of the goal so that it better matches the conclusion of the\ntheorem.\n|*)\n\nGoal forall a b, b <> 0 -> exists ! q r, a = q * b + r /\\ r < b.\n  change (forall a, (fun c => forall b,\n                         b <> 0 -> exists ! q r, c = q * b + r /\\ r < b) a).\n  eapply strong_induction.\nAbort. (* .none *)\n\n(*|\nYou could also use more directly the ``refine`` tactic. This tactic is\nsimilar to the ``apply`` tactic.\n|*)\n\nGoal forall a b, b <> 0 -> exists ! q r, a = q * b + r /\\ r < b.\n  refine (strong_induction _ _).\nAbort. (* .none *)\n\n(*|\nBut the ``induction`` tactic already handles arbitrary induction\nprinciples.\n|*)\n\nGoal forall a b, b <> 0 -> exists ! q r, a = q * b + r /\\ r < b.\n  induction a using strong_induction.\n\n(*|\nMore on these tactics `here\n<http://coq.inria.fr/refman/tactic-index.html>`__. You should probably\nuse ``induction`` before ``intro``-ing and ``split``-ing.\n\n----\n\n**Q:** ``induction a using strong_induction`` works great! On the\nother hand, the ``change`` tactic fails with \"Error: Not convertible.\"\n\n**A:** when the change is too complex, you can try with the\n``replace`` tactic, which will ask for a proof of equality. ``change``\nis just ``replace`` when the proof is trivially reflexivity.\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/coq-adding-a-strong-induction-tactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7588403302993824}}
{"text": "Require Import Arith.\n\nFixpoint sum (n:nat) : nat :=\n match n with\n  | 0 => 0\n  | S n => S n + sum n\n end.\n\nTheorem sum_of_nat : forall n:nat, 2 * sum n = n * (n + 1).\nProof.\n  intro n.\n  induction n.\n    simpl.\n    reflexivity.\n    \n    unfold sum; fold sum.\n    rewrite mult_plus_distr_l.\n    rewrite IHn.\n    ring.\nQed.\n\n", "meta": {"author": "rf0444", "repo": "coq", "sha": "ea26e698cd68ccc051a309b856c7724181be6aae", "save_path": "github-repos/coq/rf0444-coq", "path": "github-repos/coq/rf0444-coq/coq-ea26e698cd68ccc051a309b856c7724181be6aae/arith_prac/sum2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7588392560921317}}
{"text": "Require Import PeanoNat.\nRequire Import Hack.CMP.Arith.\nRequire Import Hack.CMP.Bounded.\n\nDefinition decr(f : nat -> nat) := forall n, f (S n) <= f n.\n\nTheorem decr_estimate: forall f, decr f -> forall x y, x <= y -> f y <= f x.\nProof.\n  intros f D x.\n  induction y.\n  + intro.\n    rewrite (proj1 (Nat.le_0_r _) H).\n    apply le_n.\n  + intro.\n    case (Nat.eq_dec x (S y)).\n    - intro.\n      rewrite e.\n      apply le_n.\n    - intro.\n      pose (p := IHy (leq_and_not' _ _ H n)).\n      pose (q := D y).\n      Nat.order.\nQed.\n\nTheorem decr_is_bounded: forall f, decr f -> bounded f.\nProof.\n  intros.\n  refine (ex_intro _ (f 0) _).\n  unfold bounded_by.\n  induction x.\n  - exact (le_n (f 0)).\n  - pose (p := H x).\n    Nat.order.\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/Decr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7587951625448239}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Functions                                                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic.\nGeneralizable Variables A.\n\n\n(* ********************************************************************** *)\n(** * Function combinators *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of the combinators *)\n\n(** Indentity function *)\n\nDefinition id {A} (x : A) := \n  x.\n\n(** Constant function *)\n\nDefinition const {A B} (v : B) : A -> B := \n  fun _ => v.\n\n(** Constant function of higher arities *)\n\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(** 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(** 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\nOpen Scope fun_scope.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of combinators *)\n\nSection Combinators.\nVariables (A B C D : Type).\n\nLemma compose_id_l : forall (f:A->B),\n  id \\o f = f. \nProof. intros. apply~ func_ext_1. Qed.\n\nLemma compose_id_r : forall (f:A->B),\n  f \\o id = f. \nProof. 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. 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. 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. intros. subst~. Qed.\n\nEnd Combinators.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tactic for simplifying function compositions *)\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", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/lib/tlc/LibFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.8991213745668094, "lm_q1q2_score": 0.7587641281290285}}
{"text": "Inductive 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) ..).\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 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\nTheorem rev_snoc : forall l :natlist, forall n:nat, reverse(snoc l n) = n :: reverse l.\nProof.\nintros.\ninduction l.\nsimpl.\nsimpl. reflexivity.\nsimpl. rewrite -> IHl.\nsimpl. reflexivity.\nQed.\n\nTheorem reverseInvolutive : forall list : natlist, reverse(reverse list) = list.   \nProof.\nintros.\ninduction list as [| x xs].\nsimpl. reflexivity.\nsimpl. rewrite -> rev_snoc.\nrewrite IHxs.\nreflexivity.\nQed.\n\nEval compute in ( reverseInvolutive [1;2;3;4;5]).", "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/2_rev_involutive/reverseInvolutive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7587641279125339}}
{"text": "(* Chapter 12 Simple imperative programs *)\n\nRequire Export SfLib.\n\n\n(* Arithmetic and boolean expressions *)\n\n(* syntax *)\nModule AExp.\n  Inductive aexp : Type :=\n    | ANum : nat -> aexp\n    | APlus : aexp -> aexp -> aexp\n    | AMinus : aexp -> aexp -> aexp\n    | AMult : aexp -> aexp -> aexp.\n\n  Inductive 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\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_aeval1: aeval (APlus (ANum 2) (ANum 2)) = 4.\n  Proof. reflexivity. Qed.\n\n  Fixpoint beval (b:bexp) : bool :=\n    match b 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\n  (* optimisation *)\n  Fixpoint optimize_0plus (a:aexp) : aexp :=\n    match a with\n      | ANum n            => ANum n\n      | APlus (ANum 0) e2 => optimize_0plus e2\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\n  Example test_optimize_0plus:\n    optimize_0plus (APlus (ANum 2)\n                          (APlus (ANum 0)\n                                 (APlus (ANum 0) (ANum 1)))) = APlus (ANum 2) (ANum 1).\n  Proof. reflexivity. Qed.\n\n  Theorem optimize_0plus_sound: forall a,\n    aeval (optimize_0plus a) = aeval a.\n  Proof.\n    intros. induction a.\n    Case \"ANum\". reflexivity.\n    Case \"APlus\". destruct a1.\n      SCase \"ANum\". destruct n.\n        SSCase \"0\". simpl. apply IHa2.\n        SSCase \"S\". simpl. rewrite IHa2. reflexivity.\n      SCase \"APlus\". simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n      SCase \"AMinus\". simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n      SCase \"AMult\". simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n    Case \"AMinus\". simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n    Case \"AMult\". simpl in *. rewrite IHa1. rewrite IHa2. reflexivity.\n  Qed.\n\n  Theorem optimize_0plus_sound''': forall a,\n    aeval (optimize_0plus a) = aeval a.\n  Proof.\n    intros.\n    induction a.\n\n    reflexivity.\n\n    destruct a1.\n    try (destruct n; simpl; rewrite IHa2; reflexivity).\n\n    try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    try (simpl in * ; rewrite IHa1 ; rewrite IHa2 ; reflexivity).\n    try (simpl in * ; rewrite IHa1 ; rewrite IHa2 ; reflexivity).\n    try (simpl in * ; rewrite IHa1 ; rewrite IHa2 ; reflexivity).\n    try (simpl in * ; rewrite IHa1 ; rewrite IHa2 ; reflexivity).\nQed.\n\n\n(* Coq automation *)\n\n(* [repeat] tactical *)\nTheorem ev100 : ev 100.\nProof.\n  repeat (apply ev_SS). apply ev_0.\nQed.\n\nTheorem ev100' : ev 100.\nProof.\n  repeat (apply ev_0). (* does nothing *)\n  repeat apply ev_SS. apply ev_0.\nQed.\n\n(* need to watch out for tactics that always succeed in combination with repeat.\n   coq's term language terminates, but the tactic language might not...\n*)\n\n\n(* [try] tactical *)\nTheorem silly1 : forall ae, aeval ae = aeval ae.\nProof. try reflexivity. Qed.\n\nTheorem silly2 : forall (P:Prop), P -> P.\nProof.\n  intros.\n  try reflexivity. (* plain [reflexivity] would fail here *)\n  apply H.\nQed.\n\n(* using [try] in a manual situation like above is silly, but [try] is handy\n   when doing automated proofs in combination with [;] tactical\n*)\n\n\n\n(* [;] tactical (simple form) *)\n\n(* T ; T'\n   Perform tactic T then perform T' on each subgoal generated by T *)\nLemma foo : forall n, ble_nat 0 n = true.\nProof.\n  intros. destruct n. simpl. reflexivity. simpl. reflexivity.\nQed.\n\nLemma foo' : forall n, ble_nat 0 n = true.\nProof.\n  intros.\n  destruct n;    (* destruct current goal *)\n    simpl;       (* simpl each resulting subgoal *)\n    reflexivity. (* refl on each of those subgoals *)\nQed.\n\n(* Use try and ; together *)\nTheorem optimize_0plus_sound' : forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  induction a;\n    try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n  Case \"ANum\". reflexivity.\n  Case \"APlus\".\n    destruct a1;\n      try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    SCase \"ANum\".\n      destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound'' : forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  induction a;\n    try reflexivity;\n    try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n  (* why has coq changed the order of how things are treated?\n\n     it's the [ T ; try T' ] idiom\n     T' is attempted on all subgoals. if it succeeds, that subgoal is proven and\n     so only the unsolved subgoals remain\n  *)\n\n  Case \"APlus\".\n    destruct a1; try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    SCase \"ANum\".\n      destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\n\n(* [;] tactical (general form)\n\n\n   T ; T' is shorthand for T ; [T' | T' | T' ... | T']\n\n   T ; [T1 | T2 | T3 | ... | Tn] first performs T, then performs Ti on the ith\n   subgoal generated by T\n*)\n\n\n\n(* Definining new tactic notations *)\nTactic Notation \"simpl_and_try\" tactic(c) := simpl ; try c.\n\n(* Bulletproofing case analyses *)\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ANum\"\n  | Case_aux c \"APlus\"\n  | Case_aux c \"AMinus\"\n  | Case_aux c \"AMult\"\n  ].\n\n\nTheorem optimize_0plus_sound'''': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros.\n  aexp_cases (induction a) Case;\n    try reflexivity;\n    try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n    Case \"APlus\".\n      aexp_cases (destruct a1) SCase;\n        try (simpl in *; rewrite IHa1; rewrite IHa2; reflexivity).\n        SCase \"ANum\".\n          destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\n\n(* Exercise: *** *)\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    | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n    | BNot e => BNot (optimize_0plus_b e)\n    | BAnd e1 e2 => BAnd (optimize_0plus_b e1) (optimize_0plus_b e2)\n  end.\n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\"\n  | Case_aux c \"BFalse\"\n  | Case_aux c \"BEq\"\n  | Case_aux c \"BLe\"\n  | Case_aux c \"BNot\"\n  | Case_aux c \"BAnd\"\n  ].\n\nTheorem optimize_0plus_b_sound: forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros.\n  bexp_cases (induction b) Case;\n    try reflexivity;\n    try (simpl; rewrite IHb; reflexivity);\n    try (simpl; rewrite IHb1, IHb2; reflexivity).\n    Case \"BEq\".\n      simpl. repeat rewrite optimize_0plus_sound''''. reflexivity.\n    Case \"BLe\".\n      simpl. repeat rewrite optimize_0plus_sound''''. reflexivity.\nQed. (* not very pretty, but meh *)\n\n\n(* Exercise: **** *)\n(* Design exercise: come up with a more sophisticated optimizer and\n   prove it correct *)\n\n\n\n(* the [omega] tactic *)\nExample silly_presburger_ex: forall m n o p,\n  m + n <= n + o /\\ o + 3 = p + 3 ->\n  m <= p.\nProof.\n  intros. omega.\nQed.\n\n\n(* a few more handy tactics *)\n\n\n(* clear H: delete hypothesis H from the context *)\n(* subst x: find assumption x = e or e = x in the context,\n            replace x with e everywhere, clear assumption *)\n(* subst: substitute all assumptions of the form x = e *)\n(* rename H into J: rename hypothesis H to J in the context *)\n(* assumption: look for a hypothesis in the context that\n               matches the goal and apply it *)\n(* contradiction: find H in the context that is logically\n                  equivalent to False *)\n(* constructor: try to find a constructor from an inductive\n                definition that can solve the goal *)\n\n\n\n(* Evaluation as a relation *)\n  Reserved Notation \"e '||' n\" (at level 50, left associativity).\n\n  Inductive 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 ->\n                  e2 || n2 ->\n                  (APlus e1 e2) || (n1 + n2)\n    | E_AMinus : forall (e1 e2 : aexp) (n1 n2 : nat),\n                   e1 || n1 ->\n                   e2 || n2 ->\n                   (AMinus e1 e2) || (n1 - n2)\n    | E_AMult : forall (e1 e2 : aexp) (n1 n2 : nat),\n                  e1 || n1 ->\n                  e2 || n2 ->\n                  (AMult e1 e2) || (n1 * n2)\n  where \"e '||' n\" := (aevalR e n) : type_scope.\n\n  Tactic Notation \"aevalR_cases\" tactic(first) ident(c) :=\n    first;\n    [ Case_aux c \"E_ANum\"\n    | Case_aux c \"E_APlus\"\n    | Case_aux c \"E_AMinus\"\n    | Case_aux c \"E_AMult\"\n    ].\n\n(* equivalence of the definitions *)\nTheorem aeval_iff_aevalR : forall a n,\n  (a || n) <-> aeval a = n.\nProof.\n  split.\n  Case \"->\".\n    intro H. aevalR_cases (induction H) SCase; simpl.\n    SCase \"E_ANum\". reflexivity.\n    SCase \"E_APlus\". rewrite IHaevalR1, IHaevalR2. reflexivity.\n    SCase \"E_AMinus\". rewrite IHaevalR1, IHaevalR2. reflexivity.\n    SCase \"E_AMult\". rewrite IHaevalR1, IHaevalR2. reflexivity.\n  Case \"<-\".\n    generalize dependent n. aexp_cases (induction a) SCase; simpl.\n    SCase \"ANum\".\n      intros. subst. apply E_ANum.\n    SCase \"APlus\". intros. subst. apply E_APlus. apply IHa1. reflexivity. apply IHa2. reflexivity.\n    SCase \"AMinus\". intros. subst. apply E_AMinus. apply IHa1. reflexivity. apply IHa2. reflexivity.\n    SCase \"AMult\". intros. subst. apply E_AMult. apply IHa1. reflexivity. apply IHa2. reflexivity.\nQed.\n\n(* this time using more tacticals *)\nTheorem aeval_iff_aevalR' : forall a n,\n  (a || n) <-> aeval a = n.\nProof.\n  split.\n  Case \"->\".\n    intros H.\n    induction H; subst; reflexivity.\n  Case \"<-\".\n    generalize dependent n.\n    induction a;\n      simpl; intros; subst; constructor;\n      try apply IHa1; try apply IHa2; reflexivity.\nQed.\n\n\n(* Exercise: *** *)\nReserved Notation \" e '|||' b \" (at level 50, left associativity).\n\nInductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : BTrue ||| true\n  | E_BFalse : BFalse ||| false\n  | E_BEq : forall (a1 a2 : aexp) (n1 n2 : nat),\n              a1 || n1 ->\n              a2 || n2 ->\n              BEq a1 a2 ||| beq_nat n1 n2\n  | E_BLe : forall (a1 a2 : aexp) (n1 n2 : nat),\n              a1 || n1 ->\n              a2 || n2 ->\n              BLe a1 a2 ||| ble_nat n1 n2\n  | E_BNot : forall (e:bexp) (b:bool),\n               e ||| b  ->\n               BNot e ||| negb b\n  | E_BAnd : forall (e1 e2 : bexp) (b1 b2:bool),\n               e1 ||| b1 ->\n               e2 ||| b2 ->\n               BAnd e1 e2 ||| andb b1 b2\n  where \"e '|||' b\" := (bevalR e b) : type_scope.\n\nTactic Notation \"bevalR_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"E_BTrue\"\n  | Case_aux c \"E_BFalse\"\n  | Case_aux c \"E_BEq\"\n  | Case_aux c \"E_BLe\"\n  | Case_aux c \"E_BNot\"\n  | Case_aux c \"E_BAnd\"\n  ].\n\nTheorem beval_iff_bevalR: forall e b,\n  (e ||| b) <-> beval e = b.\nProof.\n  split.\n  Case \"->\".\n    intros.\n    induction H; try simpl; try subst; try reflexivity; try assumption;\n    (* repeat section for: BEq and BLe *)\n    repeat (replace (aeval a1) with n1; replace (aeval a2) with n2; try reflexivity; try symmetry; apply aeval_iff_aevalR; assumption).\n\n  Case \"<-\".\n    (* was stuck on E_BNot case.\n       induction is on e, but [b] depends on [beval e]\n       had to [generalize dependent b] in order for it to work *)\n    generalize dependent b.\n    bevalR_cases (induction e) SCase; intros;\n      rewrite <- H; constructor;\n      try apply aeval_iff_aevalR; (* for E_BEq and E_BLe *)\n      try apply IHe;              (* for E_BNot *)\n      try apply IHe1;             (* for E_BAnd *)\n      try apply IHe2;             (* for E_BAnd *)\n      reflexivity.\nQed.\n\nEnd AExp.\n\n(* Computational vs. relational definitions *)\nModule aevalR_division.\n  Inductive aexp : Type :=\n    | ANum   : nat -> aexp\n    | APlus  : aexp -> aexp -> aexp\n    | AMinus : aexp -> aexp -> aexp\n    | AMult  : aexp -> aexp -> aexp\n    | ADiv   : aexp -> aexp -> aexp.\n\n  (* functional definition of aeval: how would it handle division by 0? *)\n\n  (* Not a problem in the relational definition *)\n  Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum   : forall n : nat,\n                   (ANum n) || n\n    | E_APlus  : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (APlus a1 a2) || (n1 + n2)\n    | E_AMinus : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (AMinus a1 a2) || (n1 - n2)\n    | E_AMult  : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (AMult a1 a2) || (n1 * n2)\n    | E_ADiv   : forall (a1 a2 : aexp) (n1 n2 n3 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (mult n2 n3 = n1) ->\n                   (ADiv a1 a2) || n3\n  where \"a '||' n\" := (aevalR a n) : type_scope.\nEnd aevalR_division.\n\n\n(* Adding nondeterminism *)\nModule aevalR_extended.\n  Inductive aexp : Type :=\n    | AAny : aexp (* what number comes out here? *)\n    | ANum : nat -> aexp\n    | APlus : aexp -> aexp -> aexp\n    | AMinus : aexp -> aexp -> aexp\n    | AMult : aexp -> aexp -> aexp.\n  (* again, how would the aeval function handle AAny? *)\n\n  (* not a problem for the relation *)\n  Inductive aevalR : aexp -> nat -> Prop :=\n    | E_Any    : forall n : nat,\n                   AAny || n\n    | E_ANum   : forall n : nat,\n                   (ANum n) || n\n    | E_APlus  : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (APlus a1 a2) || (n1 + n2)\n    | E_AMinus : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (AMinus a1 a2) || (n1 - n2)\n    | E_AMult  : forall (a1 a2 : aexp) (n1 n2 : nat),\n                   a1 || n1 ->\n                   a2 || n2 ->\n                   (AMult a1 a2) || (n1 * n2)\n  where \"a '||' n\" := (aevalR a n) : type_scope.\nEnd aevalR_extended.\n\n\n(* Expressions with variables *)\nModule Id.\n  Inductive id : Type :=\n    Id : nat -> id.\n\n  Theorem eq_id_dec: forall i1 i2 : id,\n    {i1 = i2} + {i1 <> i2}.\n  Proof.\n    intros.\n    destruct i1 as [n]. destruct i2 as [m].\n    destruct (eq_nat_dec n m) as [eq | neq].\n    Case \"=\".\n      left. rewrite eq. reflexivity.\n    Case \"<>\".\n      right. intro. inversion H. apply neq, H1.\n  Defined.\n\n\nLemma eq_id: forall (T:Type) x (p q : T),\n  (if eq_id_dec x x then p else q) = p.\nProof.\n  intros.\n  destruct (eq_id_dec x x).\n  Case \"=\". reflexivity.\n  Case \"<>\". apply ex_falso_quodlibet. apply n. reflexivity.\nQed.\n\n\n(* Exercise: * optional *)\nLemma neq_id: forall (T:Type) x y (p q : T),\n  x <> y -> (if eq_id_dec x y then p else q) = q.\nProof.\n  intros.\n  destruct (eq_id_dec x y).\n  Case \"=\". apply ex_falso_quodlibet, H, e.\n  Case \"<>\". reflexivity.\nQed.\n\nEnd Id.\n\n(* State *)\nDefinition state := id -> nat.\n\nDefinition empty_state : state :=\n  fun _ => 0.\n\nDefinition update (st:state) (x:id) (n:nat) : state :=\n  fun x' => if eq_id_dec x x' then n else st x'.\n\n(* Exercise: * *)\nTheorem update_eq : forall n x st,\n  (update st x n) x = n.\nProof.\n  intros. unfold update.\n  destruct (eq_id_dec x x); try apply ex_falso_quodlibet, n0; reflexivity.\nQed.\n\n(* Exercise: * *)\nTheorem update_neq : forall x2 x1 n st,\n  x2 <> x1 ->\n  (update st x2 n) x1 = (st x1).\nProof.\n  intros. unfold update.\n  destruct (eq_id_dec x2 x1). contradiction. reflexivity.\nQed.\n\n\n(* Exercise: * *)\nTheorem update_example: forall n:nat,\n  (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  intros. unfold update. reflexivity.\nQed.\n\n(* Exercise: * *)\nTheorem update_shadow: forall n1 n2 x1 x2 (st:state),\n  (update (update st x2 n1) x2 n2) x1 = (update st x2 n2) x1.\nProof.\n  intros. unfold update. destruct (eq_id_dec x2 x1) eqn:H; reflexivity.\nQed.\n\n\n(* Exercise: ** *)\nTheorem update_same: forall n1 x1 x2 (st:state),\n  st x1 = n1 ->\n  (update st x1 n1) x2 = st x2.\nProof.\n  intros. unfold update.\n  destruct (eq_id_dec x1 x2) eqn:eq;\n  subst; reflexivity.\nQed.\n\n\n(* Exercise: *** *)\nTheorem update_permute: forall n1 n2 x1 x2 x3 st,\n  x2 <> x1 ->\n  (update (update st x2 n1) x1 n2) x3 = (update (update st x1 n2) x2 n1) x3.\nProof.\n  intros. unfold update.\n  destruct (eq_id_dec x1 x3) eqn:x13. destruct (eq_id_dec x2 x3) eqn:x23.\n  subst. contradiction H. reflexivity. reflexivity. reflexivity.\nQed.\n\n\n(* Syntax *)\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\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ANum\"\n  | Case_aux c \"AId\"\n  | Case_aux c \"APlus\"\n  | Case_aux c \"AMinus\"\n  | Case_aux c \"AMult\"\n  ].\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\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\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\"\n  | Case_aux c \"BFalse\"\n  | Case_aux c \"BEq\"\n  | Case_aux c \"BLe\"\n  | Case_aux c \"BNot\"\n  | Case_aux c \"BAnd\"\n  ].\n\n(* Evaluation *)\nFixpoint aeval (st:state) (a:aexp) : nat :=\n  match a with\n    | ANum n => n\n    | AId x => st x\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  => 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\nExample aexp1:\n  aeval (update empty_state X 5)\n        (APlus (ANum 3) (AMult (AId X) (ANum 2)))\n  = 13.\nProof. reflexivity. Qed.\n\nExample bexp1:\n  beval (update empty_state X 5)\n        (BAnd BTrue (BNot (BLe (AId X) (ANum 4))))\n  = true.\nProof. reflexivity. Qed.\n\n\n\n(* Commands *)\n\n(*\n   informally, our commands have the following BNF grammar\n\n   c ::= SKIP\n       | x ::= a\n       | c ;; c\n       | WHILE b DO c END\n       | IFB b THEN c ELSE c FI\n*)\n\n(*\n   factorial in Imp:\n\n   Z ::= X;;\n   Y ::= 1;;\n   WHILE not (Z = 0) DO\n     Y ::= Y * Z;;\n     Z ::= Z - 1\n   END\n*)\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\nTactic Notation \"com_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"SKIP\"\n  | Case_aux c \"::=\"\n  | Case_aux c \";;\"\n  | Case_aux c \"IFB\"\n  | Case_aux c \"WHILE\"\n  ].\n\nNotation \"'SKIP'\" := 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' c 'THEN' a 'ELSE' b 'FI'\" :=\n  (CIf c a b) (at level 80, right associativity).\n\nDefinition fact_in_coq : com :=\n  Z ::= AId X;;\n  Y ::= ANum 1;;\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n    Y ::= AMult (AId Y) (AId Z);;\n    Z ::= AMinus (AId Z) (ANum 1)\n  END.\n\n\n(* Examples *)\nDefinition plus2 : com :=\n  X ::= (APlus (AId X) (ANum 2)).\n\nDefinition XtimesYinZ : com :=\n  Z ::= (AMult (AId X) (AId Y)).\n\nDefinition subtract_slowly_body : com :=\n  Z ::= AMinus (AId Z) (ANum 1) ;;\n  X ::= AMinus (AId X) (ANum 1).\n\n(* loops *)\nDefinition subtract_slowly : com :=\n  WHILE BNot (BEq (AId X) (ANum 0)) DO\n    subtract_slowly_body\n  END.\n\nDefinition subtract_3_from_5_slowly : com :=\n  X ::= ANum 3 ;;\n  Z ::= ANum 5 ;;\n  subtract_slowly.\n\n(* infinite loop *)\nDefinition loop : com :=\n  WHILE BTrue DO\n    SKIP\n  END.\n\n\n\n(* Evaluation *)\nFixpoint ceval_fun_no_while (st:state) (c:com) : state :=\n  match c with\n    | SKIP => st\n    | x ::= a1 => update st x (aeval st a1)\n    | c1 ;; c2 => let st' := ceval_fun_no_while st c1\n                  in  ceval_fun_no_while st' c2\n    | IFB c THEN a ELSE b FI => if   (beval st c)\n                                then ceval_fun_no_while st a\n                                else ceval_fun_no_while st b\n    | WHILE b DO c END => st (* bogus *)\n  end.\n\n\n(* Evaluation as a relation *)\nReserved Notation \"c1 '/' st '||' st'\" (at level 40, st at level 39).\n\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st, SKIP / st || st\n  | E_Ass : forall st a n x,\n              aeval st a = n ->\n              (x ::= a) / st || (update st x 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' c a b,\n                 beval st c = true ->\n                 a / st || st' ->\n                 (IFB c THEN a ELSE b FI) / st || st'\n  | E_IfFalse : forall st st' c a b,\n                  beval st c = false ->\n                  b / st || st' ->\n                  (IFB c THEN a ELSE b FI) / st || st'\n  | E_WhileEnd : forall b st c,\n                   beval st b = false ->\n                   (WHILE b DO c END) / st || st\n  | E_WhileLoop : forall st st' st'' b c,\n                    beval st b = true ->\n                    c / st || st' ->\n                    (WHILE b DO c END) / st' || st'' ->\n                    (WHILE b DO c END) / st || st''\n  where \"c '/' st '||' st'\" := (ceval c st st').\n\nTactic Notation \"ceval_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"E_Skip\"\n  | Case_aux c \"E_Ass\"\n  | Case_aux c \"E_Seq\"\n  | Case_aux c \"E_IfTrue\"\n  | Case_aux c \"E_IfFalse\"\n  | Case_aux c \"E_WhileEnd\"\n  | Case_aux c \"E_WhileLoop\"\n  ].\n\n\nExample ceval_example1:\n  (X::=ANum 2 ;;\n   IFB BLe (AId X) (ANum 1)\n     THEN Y ::= ANum 3\n     ELSE Z ::= ANum 4\n   FI)\n  / empty_state || (update (update empty_state X 2) Z 4).\nProof.\n  apply E_Seq with (update empty_state X 2).\n  Case \"::=\". apply E_Ass. reflexivity.\n  Case \"if\".\n    apply E_IfFalse. reflexivity. apply E_Ass. reflexivity.\nQed.\n\n\n(* Exercise: ** *)\nExample ceval_example2:\n  (X ::= ANum 0;;\n   Y ::= ANum 1;;\n   Z ::= ANum 2)\n  / empty_state || (update (update (update empty_state X 0) Y 1) Z 2).\nProof.\n  try apply E_Seq with (update empty_state X 0);\n  try apply E_Seq with (update (update empty_state X 0) Y 1);\n  apply E_Ass;\n  reflexivity.\nQed.\n\n(* Exercise: *** advanced *)\nDefinition pup_to_n : com :=\n  (Y ::= ANum 0;;\n   WHILE BNot (BEq (ANum 0) (AId X)) DO\n     Y ::= APlus (AId Y) (AId X);;\n     X ::= AMinus (AId X) (ANum 1)\n   END).\n\nTheorem pup_to_2_ceval:\n  pup_to_n /\n  (update empty_state X 2) ||\n  update (update (update (update (update (update empty_state X 2) Y 0) Y 2) X 1) Y 3) X 0.\nProof.\n  apply E_Seq with (update (update empty_state X 2) Y 0).\n  (* Y 0 *) apply E_Ass. reflexivity.\n\n  (* while conditional *)\n  apply E_WhileLoop with (update (update (update (update empty_state X 2) Y 0) Y 2) X 1).\n  reflexivity.\n  (* while body *) apply E_Seq with (update (update (update empty_state X 2) Y 0) Y 2).\n  (* Y = *) apply E_Ass. reflexivity.\n  (* X = *) apply E_Ass. reflexivity.\n\n  (* while conditional *)\n  apply E_WhileLoop with (update (update (update (update (update (update empty_state X 2) Y 0) Y 2) X 1) Y 3) X 0). reflexivity.\n  (* while body *) apply E_Seq with (update (update (update (update (update empty_state X 2) Y 0) Y 2) X 1) Y 3).\n  (* Y ::= *) apply E_Ass. reflexivity.\n  (* X ::= *) apply E_Ass. reflexivity.\n\n  apply E_WhileEnd. reflexivity.\nQed.\n\nTheorem ceval_deterministic: forall c st st1 st2,\n  c / st || st1 ->\n  c / st || st2 ->\n  st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2. generalize dependent st2. ceval_cases (induction E1) Case; intros st2 E2; inversion E2; subst.\n  Case \"E_Skip\".\n    reflexivity.\n  Case \"E_Ass\".\n    reflexivity.\n  Case \"E_Seq\".\n    assert (st' = st'0) as eq1.\n    apply IHE1_1; assumption. subst. apply IHE1_2. assumption.\n  Case \"E_IfTrue\".\n    apply IHE1. assumption. rewrite H in H5. inversion H5.\n  Case \"E_IfFalse\".\n    rewrite H in H5. inversion H5. apply IHE1. assumption.\n  Case \"E_WhileEnd\".\n    reflexivity. rewrite H in H2. inversion H2.\n  Case \"E_WhileLoop\".\n    rewrite H in H4. inversion H4.\n    assert (st' = st'0) as eq1. apply IHE1_1; assumption.\n    subst st'0. apply IHE1_2. assumption.\nQed.\n\n\n\n(* Reasoning about Imp programs *)\nTheorem plus2_spec: forall st n st',\n  st X = n ->\n  plus2 / st || st' ->\n  st' X = n + 2.\nProof.\n  intros st n st' hx heval.\n  inversion heval. subst. apply update_eq.\nQed.\n\n(* Exercise: *** *)\n(* prove a specification of XtimesYinZ *)\nTheorem XtimesYinZ_spec: forall st n st',\n  st X = n ->\n  XtimesYinZ / st || st' ->\n  st' X = n.\nProof.\n  intros st n st' xn ev. generalize dependent n.\n  induction ev; intros; try assumption.\n  subst.\nAdmitted.\n\n(* Exercise: *** *)\nTheorem loop_never_stops: forall st st',\n  ~ (loop / st || st').\nProof.\n  intros st st' contra. unfold loop in contra.\n  remember (WHILE BTrue DO SKIP END) as loopdef eqn:eqld.\n  ceval_cases(induction contra) Case; inversion eqld.\n  Case \"E_WhileEnd\". subst. inversion H.\n  Case \"E_WhileLoop\". apply IHcontra2. subst. reflexivity.\nQed.\n\n(* Exercise: *** *)\nFixpoint no_whiles (c:com) : bool :=\n  match c with\n    | SKIP => true\n    | _ ::= _ => true\n    | c1 ;; c2 => andb (no_whiles c1) (no_whiles c2)\n    | IFB _ THEN a ELSE b FI => andb (no_whiles a) (no_whiles b)\n    | WHILE _ DO _ END => false\n  end.\n\nInductive no_whilesR: com -> Prop :=\n  | n_skip : no_whilesR SKIP\n  | n_asgn : forall x a, no_whilesR (x ::= a)\n  | n_seq  : forall a b, no_whilesR a -> no_whilesR b -> no_whilesR (a ;; b)\n  | n_if   : forall c a b, no_whilesR a -> no_whilesR b -> no_whilesR (IFB c THEN a ELSE b FI).\n\nTheorem no_whiles_eqv: forall c,\n  no_whiles c = true <-> no_whilesR c.\nProof.\n  intro c. split.\n  Case \"->\".\n    induction c; intros; try constructor.\n    SCase \"::=\".\n      simpl in H.\n      apply IHc1. apply andb_true_elim1 in H. assumption.\n      apply IHc2. apply andb_true_elim2 in H. assumption.\n    SCase \"IF\".\n      simpl in H.\n      apply IHc1. apply andb_true_elim1 in H. assumption.\n      apply IHc2. apply andb_true_elim2 in H. assumption.\n    SCase \"WHILE\".\n      inversion H.\n\n  Case \"<-\".\n    induction c; intros; simpl; try rewrite IHc1, IHc2; try reflexivity;\n    repeat (try inversion H; try assumption).\nQed.\n\n\n(* Exercise: **** *)\n(* state and prove a theorem that says 'if there are no while loops in an imp\n   program, then it always terminates' *)\n\n\n\n(* Additional exercises *)\n\n(* Exercise: *** stack compiler *)\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) (prog:list sinstr) : list nat :=\n  match prog with\n    | nil => stack\n    | ins :: inss => match ins, stack with\n                       | SPush n, _              => s_execute st (n :: stack) inss\n                       | SLoad i, _              => s_execute st (st i :: stack) inss\n                       | SPlus, (a :: (b :: c))  => s_execute st ((a + b) :: c) inss\n                       | SMinus, (a :: (b :: c)) => s_execute st ((b - a) :: c) inss\n                       | SMult, (a :: (b :: c))  => s_execute st ((a * b) :: c) inss\n                       | _, _                    => stack\n                     end\n  end.\n\nExample s_execute1: s_execute empty_state []\n  [SPush 5; SPush 3; SPush 1; SMinus] = [2;5].\nProof. reflexivity. Qed.\n\nExample s_execute2: s_execute (update empty_state X 3) [3;4]\n  [SPush 4; SLoad X; SMult; SPlus] = [15;4].\nProof. reflexivity. Qed.\n\nFixpoint s_compile (e:aexp) : list sinstr :=\n  match e with\n    | ANum n     => [SPush n]\n    | AId i      => [SLoad i]\n    | APlus n m  => s_compile n ++ s_compile m ++ [SPlus]\n    | AMinus n m => s_compile n ++ s_compile m ++ [SMinus]\n    | AMult n m  => s_compile n ++ s_compile m ++ [SMult]\n  end.\n\nExample s_compile1: s_compile\n  (AMinus (AId X) (AMult (ANum 2) (AId Y))) = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\nProof. reflexivity. Qed.\n\n(* Exercise: *** advanced *)\nTheorem s_compile_correct: forall (st:state) (e:aexp),\n  s_execute st [] (s_compile e) = [aeval st e].\nProof.\n  intros.\n  induction e; simpl; try reflexivity.\nAdmitted.\n\n\n(* Exercise: ***** advanced *)\nModule BreakImp.\n  Inductive com : Type :=\n    | CSkip : com\n    | CBreak : com\n    | CAss : id -> aexp -> com\n    | CSeq : com -> com -> com\n    | CIf  : bexp -> com -> com -> com\n    | CWhile : bexp -> com -> com.\n\n  Tactic Notation \"com_cases\" tactic(first) ident(c) :=\n    first;\n    [ Case_aux c \"SKIP\"\n    | Case_aux c \"BREAK\"\n    | Case_aux c \"::=\"\n    | Case_aux c \";\"\n    | Case_aux c \"IFB\"\n    | Case_aux c \"WHILE\"\n    ].\n\n  Notation \"'SKIP'\"    := CSkip.\n  Notation \"'BREAK'\"   := CBreak.\n  Notation \"x '::=' a\" := (CAss x a) (at level 60).\n  Notation \"c1 ; c2\"   := (CSeq c1 c2) (at level 80, right associativity).\n  Notation \"'WHILE' b 'DO' c 'END'\" :=\n    (CWhile b c) (at level 80, right associativity).\n  Notation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n    (CIf c1 c2 c3) (at level 80, right associativity).\n\n  (* BREAK should exit the inner most loop only, if it is called outside\n     a loop, the program terminates.\n  *)\n\n  Inductive status : Type :=\n    | SContinue : status\n    | SBreak : status.\n\n  Reserved Notation \"c '/' st '||' s '/' st'\" (at level 40, st, s at level 39).\nEnd BreakImp.\n", "meta": {"author": "bishboria", "repo": "software-foundations", "sha": "48da9007beb2e6692bab277c12ddc8e1a6c56b2c", "save_path": "github-repos/coq/bishboria-software-foundations", "path": "github-repos/coq/bishboria-software-foundations/software-foundations-48da9007beb2e6692bab277c12ddc8e1a6c56b2c/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7587526173924654}}
{"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 Setoid.\n\nSet Implicit Arguments.\n\n(*\nInductive bt :=\n  | leaf : bt\n  | node : bt -> bt -> bt.\n\nCheck bt_rect.\nCheck bt_ind.\n*)\n\nSection list.\n\n  Variable X : Type.\n\n  Implicit Type l : list X.\n\n  Infix \"::\" := cons.\n  Infix \"++\" := (@app _).\n  Notation \"⌊ l ⌋\" := (length l) (at level 1, format \"⌊ l ⌋\").\n\n  Print list.\n  \n  Print Implicit nil.\n  Check nil.\n  Check @nil _.\n  \n  Print app.\n\n  Arguments app {A}.\n  Check app.\n  \n  Arguments app [A].\n  Check app.\n\n  Print app.\n\n  Fact app_nil_head l : nil++l = l.\n  Proof. reflexivity. Qed.\n\n  Fact app_cons_head x l m : (x::l) ++ m = x::(l++m).\n  Proof. reflexivity. Qed. \n\n  Fact app_assoc l m p : (l++m)++p = l++m++p.\n  Proof.\n    induction l as [ | x l IHl ].\n    + simpl. trivial.\n    + simpl.\n      f_equal.\n      trivial.\n    (* induction l; simpl; f_equal; trivial. *)\n  Qed.\n\n  Fact app_nil_end l : l++nil = l.\n  Proof.\n  (*  induction l; simpl; f_equal; trivial. *)\n    induction l as [ | x l IHl ].\n    + simpl. trivial.\n    + simpl.\n      f_equal.\n      trivial.\n  Qed.\n\n  Print length.\n\n  Fact app_length l m : ⌊l++m⌋ = ⌊l⌋+⌊m⌋.\n  Proof.\n  (*  induction l; simpl; f_equal; trivial. *)\n    induction l as [ | x l IHl ].\n    + simpl. \n      trivial.\n    + simpl.\n      f_equal.\n      trivial.\n  Qed.\n\n  Section map.\n\n    Variable (Y : Type) (f : X -> Y).\n\n    Fixpoint map l :=\n      match l with \n        | nil  => nil\n        | x::l => f x::map l\n      end.\n\n    Fact map_length l : ⌊map l⌋ = ⌊l⌋.\n    Proof.\n      induction l; simpl; f_equal; trivial.\n    Qed.\n\n    Fact map_app l m : map (l++m) = map l ++ map m.\n    Proof.\n      induction l; simpl; f_equal; trivial.\n    Qed.\n\n  End map.\n\n  Check map.\n\n  Fixpoint rev l :=\n    match l with\n      | nil  => nil\n      | x::l => rev l ++ x :: nil\n    end.\n\n  Fixpoint rev_app a l :=\n    match l with \n      | nil  => a\n      | x::l => rev_app (x::a) l\n    end.\n\n  Print rev_app.\n\n  Fact rev_rev_app_eq a l : rev_app a l = rev l ++ a.\n  Proof.\n    revert a. \n    induction l as [ | x l IHl ]; intros a; simpl.\n    + trivial.\n    + rewrite app_assoc; simpl.\n      apply IHl.\n  Qed.\n\n  Fact rev_app_equiv l : rev_app nil l = rev l.\n  Proof. rewrite rev_rev_app_eq, app_nil_end; trivial. Qed.\n\n  Reserved Notation \"x ∈ l\" (at level 70, no associativity).\n\n  Fixpoint In x l := \n    match l with\n      | nil  => False\n      | y::l => x = y \\/ x ∈ l\n    end\n  where \"x ∈ l\" := (In x l).\n\n  Fact in_app_iff x l m : x ∈ l++m <-> x ∈ l \\/ x ∈ m.\n  Proof.\n(*    Print list.\n    Check list_rect.\n    Check list_ind. *)\n    induction l as [ | y l IHl ]; simpl.\n    + tauto.\n    + rewrite IHl.\n      tauto.\n  (*  induction l as [ | ? ? IHl ]; simpl; [ | rewrite IHl ]; tauto. *)\n  Qed.\n\n(*\nEnd list.\n\nEval compute in In 2 (2::3::4::nil). *)\n    \n  Definition incl l m := forall x, x ∈ l -> x ∈ m.\n\n  Infix \"⊆\" := incl (at level 70, no associativity).\n\n  Fact incl_refl l : l ⊆ l.\n  Proof.\n    unfold incl. auto.\n  Qed.\n\n  Fact incl_trans l m p : l ⊆ m -> m ⊆ p -> l ⊆ p. \n  Proof.\n    unfold incl.\n  (*  intros H1 H2 x H3.\n    apply H2, H1, H3. *)\n    firstorder.\n  Qed.\n\n  Hint Resolve incl_refl : core.\n\n  Fact incl_app_l l m : l ⊆ l++m.\n  Proof.\n(*    red.\n    intros x Hx.\n    apply in_app_iff.\n    left; trivial. *)\n    intro.\n    Check in_app_iff. (* rewrite with <-> instead of = *)\n    rewrite in_app_iff. \n    tauto.\n  Qed.\n\n  Fact incl_app_r l m : m ⊆ l++m.\n  Proof.\n    intro; rewrite in_app_iff; tauto.\n  Qed.\n\n  Fact sg_incl x m : x::nil ⊆ m <-> x ∈ m.\n  Proof.\n    unfold incl; split.\n    + intros H.\n      apply H.\n      simpl.\n      auto.\n    + intros H y; simpl.\n      intros D.\n      destruct D as [ E | A ].\n      * rewrite E. \n        trivial.\n      * destruct A.\n      (* intros ? ? [ -> | [] ]; trivial. *)\n  Qed.\n\n  Hint Resolve incl_app_l incl_app_r : core.\n\n  Fact app_incl_left l r m : l++r ⊆ m <-> l ⊆ m /\\ r ⊆ m.\n  Proof.\n    split.\n    + intros H.\n      split. \n      * Check incl_trans.\n     (*   apply incl_trans with (l++r). *)\n        apply incl_trans with (2 := H). \n        trivial.\n      * apply incl_trans with (2 := H); trivial.\n    + intros [ H1 H2 ] x.\n      rewrite in_app_iff.\n      intros [ H | H ]; revert H.\n      * auto.\n      * auto.\n  Qed.\n\n  Fact cons_incl_left x l m : x::l ⊆ m <-> x ∈ m /\\ l ⊆ m.\n  Proof.\n    rewrite <- sg_incl, <- app_incl_left.\n    simpl; tauto.\n  Qed.\n\n  Fact incl_cons_r x l : l ⊆ x::l.\n  Proof.\n    unfold incl; simpl; auto.\n  Qed.\n\n  Fact incl_nil_l l : nil ⊆ l.\n  Proof.\n    (* unfold incl. \n    simpl. *)\n    intros _ [].\n  Qed.\n\n  Hint Resolve incl_nil_l incl_cons_r : core.\n\n  Fact incl_nil_r l : l ⊆ nil <-> l = nil.\n  Proof.\n    split.\n    + unfold incl.\n      simpl.\n      intros H.\n      destruct l as [ | x l ]. \n      * trivial.\n      * destruct H with x.\n        simpl; auto.\n    + intros ->. (* equiv intros E; rewrite -> E *)\n      auto. (* apply incl_refl. *)\n  Qed.\n\n  Fact incl_app_comm l m : l++m ⊆ m++l.\n  Proof.\n    intro.\n    rewrite !in_app_iff.\n    tauto.\n  Qed.\n\n  (* Alternative inductive definitions of In/∈ and incl/⊆ *)\n\n  Reserved Notation \"x ∈' y\" (at level 70, no associativity).\n\n  Inductive ind_In : X -> list X -> Prop :=\n    | in_ind_In0 : forall x l, x ∈' x::l\n    | in_ind_In1 : forall x y l, x ∈' l -> x ∈' y::l\n  where \"x ∈' l\" := (ind_In x l).\n\n  (**                         x ∈' l\n          -------------   ---------------   \n            x ∈' x::l        x ∈' y::l     *)\n\n  Fact ind_In_equiv x l : x ∈ l <-> x ∈' l.\n  Proof.\n    split.\n    + induction l as [ | y l IHl ]; simpl.\n      * intros [].\n      * (* intros [ -> | ]; constructor; auto. *)\n        intros [ E | H ].\n        - rewrite E.\n          constructor 1. (* apply in_ind_In0. *)\n        - constructor 2.\n          apply IHl, H.\n    + intros H.\n      induction H as [ x l | x y l H IH ].\n      * simpl. auto.\n      * simpl. auto.\n  Qed.\n\n  Reserved Notation \"x ⊆' y\" (at level 70, no associativity).\n\n  Inductive ind_incl : list X -> list X -> Prop :=\n    | in_ii0 : forall m, nil ⊆' m\n    | in_ii1 : forall x l m, x ∈' m -> l ⊆' m -> x::l ⊆' m \n  where \"l ⊆' m\" := (ind_incl l m).\n\n  (**                             x ∈' m     l ⊆' m\n            -------------      ------------------------\n               nil ⊆' m                x::l ⊆' m    *)\n\n  Fact ind_incl_equiv l m : l ⊆ m <-> l ⊆' m.\n  Proof.\n    split.\n    + intros H.\n      induction l as [ | x l IHl ].\n      * constructor.\n      * constructor.\n        - apply ind_In_equiv.\n          apply H.\n          simpl; auto.\n        - apply IHl.\n          rewrite cons_incl_left in H.\n          tauto.\n    + intros H.\n      induction H as [ m | x l m H1 H2 IH2 ].\n      * auto.\n      * rewrite cons_incl_left, ind_In_equiv.\n        auto.\n  Qed.\n\nEnd list.\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_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.8947894534772126, "lm_q1q2_score": 0.7587526036473491}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\n\nFrom LF Require Export Induction.\nFrom LF Require Export Poly.\n\n(* The apply Tactic *)\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\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.\n  apply eq1.\nQed.\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     oddb 3 = true ->\n     evenb 4 = true.\nProof.\nintros cond res.\napply res.\nQed.\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n =? 5) ->\n     (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' -> l' = rev l.\nProof.\nintros l l' H.\nrewrite -> H.\nSearch \"rev\".\nsymmetry.\napply rev_involutive.\nQed.\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.\n  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity.\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.\nintros n m o p H H2.\nrewrite H2.\napply H.\nQed.\n\n(* The injection and discriminate Tactics *)\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\nTheorem S_injective' :  forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n  injection H.\n  intro.\n  apply H0.\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.\n  intros Hmo Hno.\n  rewrite Hmo.\n  rewrite Hno.\n  reflexivity.\nQed.\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\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.\n  injection H2.\n  intros H3 h4.\n  rewrite h4.\n  reflexivity.\nQed.\n\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - intros H. reflexivity.\n  - simpl.\n    intros contradiction.\n    discriminate contradiction.\nQed.\n\n\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    x = z.\nProof.\nintros X x y z l H H1.\ndiscriminate H1.\nQed.\n\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\nTheorem S_inj : forall (n m : nat) (b : bool),\n     eqb (S n) (S m) = b  ->\n     eqb n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.\nQed.\n\n(* Using Tactics on Hypotheses *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\nintros n.\ninduction n as [| n'].\n- intros m H.\n  simpl in H.\n  destruct m.\n  reflexivity.\n  discriminate.\n- Search \"plus_n_Sm\".\n  intros m H. destruct m as [|m'].\n    + discriminate H.\n    + rewrite <- plus_n_Sm in H.\n    rewrite <- plus_n_Sm in H.\n    injection H.\n    intro.\n    apply IHn' in H0.\n    rewrite -> H0.\n    reflexivity.\nQed.\n\n(* Varying the Induction Hypothesis *)\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.\nAbort.\n\nTheorem double_injective: forall n m,\n         double n = double m -> 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  - intros m eq.\n    destruct m as [| m'] eqn:E.\n    + discriminate eq.\n    + apply f_equal.\n     apply IHn'.\n     injection eq as goal.\n     apply goal.\nQed.\n\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  intros n.\n  induction n as [| n'].\n  + intros m. destruct m as [| m'] eqn: E.\n    - reflexivity.\n    - intro. discriminate.\n  + intros m eq.\n    destruct m as [| m'] eqn: E.\n    - discriminate.\n    - apply IHn' in eq.\n      rewrite eq.\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  - (* 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.\nQed.\n\n(* to be review *)\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\nintros n X l.\n  generalize dependent n.\n induction l as [| l'].\n- reflexivity.\n- intros n H.\n    induction n as [| n'].\n    + inversion H.\n    + apply S_injective in H. apply IHl in H. apply H.\nQed.\n\n\n(* Unfolding Definitions *)\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  simpl.\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.\n  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  simpl.\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  simpl. (* Does nothing! *)\nAbort.\n\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n  destruct m  eqn:E.\n  - simpl.\n  reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\n\n(* Using destruct on Compound Expressions *)\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.\nintros n.\nunfold sillyfun.\ndestruct (n =? 3).\n- reflexivity.\n- destruct (n =? 5).\n  + reflexivity.\n  + reflexivity.\nQed.\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 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\n    intros l1 l2 eq. inversion eq. reflexivity.\n\n    simpl. destruct (split l') as [l1' l2'].\n    intros l1 l2 eq. inversion eq.\n    simpl. apply f_equal. apply IHl'. reflexivity.  Qed.\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  - intros l1 l2 H.\n    injection H.\n    intros.\n    rewrite <- H0.\n    rewrite <- H1.\n    reflexivity.\n  - simpl.\n    destruct (split l') as [x' y'] eqn: E.\n    intros l1 l2 eq.\n    injection eq.\n    simpl.\n    intros Hl2 Hl1.\n    rewrite <- Hl1.\n    rewrite <- Hl2.\n    simpl; rewrite IHl'.\n    + reflexivity.\n    + 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\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) eqn:Heqe3.\n  apply eqb_true in Heqe3.\n  rewrite -> Heqe3. reflexivity.\n  destruct (n =? 5) eqn:Heqe5.\n  apply eqb_true in Heqe5.\n  rewrite -> Heqe5. reflexivity.\n  discriminate eq.\nQed.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\nintros.\ndestruct (f b) eqn: HFB.\n- destruct b eqn: HB.\n  + rewrite HFB. apply HFB.\n  + destruct (f true) eqn: HT.\n    *  apply HT.\n    * apply HFB.\n- destruct b.\n  + destruct (f false) eqn:HF.\n    * apply HFB.\n    * apply HF.\n  + rewrite HFB; apply HFB.\nQed.\n\n(* Additional Exercises *)\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\nintros n m.\ndestruct (m =? n) eqn: HNM.\napply eqb_true in HNM.\nrewrite HNM.\nSearch \"eqb_sym_informal\".\nsymmetry.\napply eqb_nat_refl.\nAbort.\n\n", "meta": {"author": "NotBad4U", "repo": "software-foundations-vol1", "sha": "6bc676582dfedbbae664240f1443359fbb496131", "save_path": "github-repos/coq/NotBad4U-software-foundations-vol1", "path": "github-repos/coq/NotBad4U-software-foundations-vol1/software-foundations-vol1-6bc676582dfedbbae664240f1443359fbb496131/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7585912476867928}}
{"text": "Require Import CpdtTactics.\n\n(** ** Source Language *)\n\nInductive binop : Set := Plus | Times.\n\nDefinition var := nat.\n\nInductive exp : Set :=\n| Var : nat -> exp\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 (val : var -> nat) (e : exp) : nat :=\n  match e with\n    | Var v => val v \n    | Const n => n\n    | Binop b e1 e2 => (binopDenote b) (expDenote val e1) (expDenote val e2)\n  end.\n\nDefinition val (n : nat) := n.\n\nEval simpl in expDenote val (Const 42).\n(** [= 42 : nat] *)\n\nEval simpl in expDenote val (Binop Plus (Const 2) (Const 2)).\n(** [= 4 : nat] *)\n\nEval simpl in expDenote val (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n(** [= 28 : nat] *)\n\nEval simpl in expDenote val (Binop Times (Binop Plus (Var 5) (Const 2)) (Const 7)).\n(** [= 49 : nat] *)\n\n\nFixpoint cf (e : exp) : exp :=\n  match e with\n    | Binop b e1 e2 => \n        let e1' := cf e1 in\n        let e2' := cf e2 in\n        match e1', e2' with\n        | Const c1, Const c2 => Const (binopDenote b c1 c2)\n        | _, _ => Binop b e1' e2'\n        end\n    | e' => e'\n  end.\n\nEval simpl in (cf (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))).\n\nEval simpl in (cf (Binop Times (Binop Plus (Var 5) (Const 2)) (Const 7))).\n\nEval simpl in (cf (Binop Times (Binop Plus (Const 2) (Const 2)) (Var 7))).\n\nLemma cf_good : forall v e, expDenote v (cf e) = expDenote v e.\ninduction e; simpl.\n+ trivial.\n+ trivial.\n+ destruct (cf e1); destruct (cf e2).\n crush.\n(*\nHint Extern 1 (expDenote ?V (match ?E with Var _ => _ | Const _ => _ | Binop _ _ _ => _ end) = _) => \n destruct E; crush.\ninduction e; crush.\n*)\n\nQed.\n\n", "meta": {"author": "konradxyz", "repo": "coq", "sha": "d0e0ffc0026fab96166ecc9758807c1e2cea8ada", "save_path": "github-repos/coq/konradxyz-coq", "path": "github-repos/coq/konradxyz-coq/coq-d0e0ffc0026fab96166ecc9758807c1e2cea8ada/prog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7585912455009873}}
{"text": "(* (Deeply Embedded) Church Encoded Datatypes in Coq. *)\n\n(** Our job for this lab: Demo church encoded datatypes using our\n    formalization of the untyped lambda calculus.\n    *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Smallstep.\nFrom Church Require Import LCNat.\n\n(* Defining some helpful variable identifiers. *)\nDefinition c : string := \"c\".\nDefinition n : string := \"n\".\nDefinition l : string := \"l\".\nDefinition hd : string := \"hd\".\nDefinition tl : string := \"tl\".\n\n\n(* Church Encodings: *)\n(* We can actually encode booleans in the pure lambda calculus. We\n   will define true and false as follows: *)\n\nDefinition true_church := <{\\t, \\f, t}>.\nDefinition false_church := <{\\t, \\f, f}>.\n\n(* These terms encode booleans, in the sense that we can use these\n   terms to mimic the behavior of conditionals in the pure lambda\n   calculus. In particular, we can encode an if expression as follows:\n   *)\n\nDefinition if_church := <{\\x, \\t, \\f, x t f}>.\n(* This term doesn't do much: it just applies the conditional to the\n   two branches: if it is [true_church], it evaluates to the first\n   expression, and [false_church] evaluates to the second. *)\n\nExample if_true :\n  <{if_church true_church (S tm_zero) tm_zero}> -->* <{S tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample if_false :\n  <{if_church false_church (S tm_zero) tm_zero}> -->* <{tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* We can define boolean operations like and as well! *)\nDefinition and_church :=\n  <{\\x, \\y, x y false_church}>.\n\nExample if_and_false :\n  <{if_church (and_church true_church false_church) (S tm_zero) tm_zero}> -->* <{tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* We can encode pairs as terms using booleans: *)\nDefinition pair_church :=\n  <{\\f, \\s, \\x, x f s}>.\n\nDefinition fst_church :=\n  <{\\y, y true_church}>.\n\nDefinition snd_church :=\n  <{\\y, y false_church}>.\n\n(* That is, [pair f s] is a function, that when applied to a boolean\n   [x], applies [x] to [f] and [s]. By definition, this function\n   returns [f] when [x] is [true_church] and [s] when [x] is\n   [false_church]. The standard projection functions just supply the\n   appropriate church-encoded boolean. *)\n\nExample fst_pair :\n  <{fst_church (pair_church (S tm_zero) tm_zero)}> -->* <{S tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Interestingly, we can encode numbers using a similar technique.\n   The key difference is that we need to handle recursion more\n   delicately.\n\n   Informally, we can define church-encoded numbers as follows:\n\n   C0 = \\s, \\z, z\n   C1 = \\s, \\z, s z\n   C2 = \\s, \\z, s (s z)\n   C3 = \\s, \\z, s (s (s z))\n *)\n\n(* That is, a number takes two functions: one for the successor case,\n   and one for the zero case.  The key bit is that the function for\n   what to do in the successor case takes an argument for the result\n   of its predecessor. The 'number' simply recursively applies the\n   successor function the appropriate number of times. *)\n\n(* As examples, here are the church encoding of zero and three: *)\n\nDefinition zero_church :=\n  <{\\s, \\z, z}>.\n\nDefinition three_church :=\n  <{\\s, \\z, s (s (s z))}>.\n\n(* To make it easier to read numbers, we can define a lambda\n   expression that converts a church-encoded natural number to a\n   representation using our calculi's built-in numbers.\n\n   This conversion function takes a number and applies tm_succ for the\n   recursive case, and tm_zero for the base case. *)\nDefinition toNat_church :=\n  <{\\n, n (\\z, S z) tm_zero}>.\n\n(* The chuch encoded numbers from above produce the expected primitive\n   value. *)\n\nExample zero_church_ex :\n  <{toNat_church zero_church}> -->* <{tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample three_church_ex :\n  <{toNat_church three_church}> -->* <{S (S (S tm_zero)) }>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* We can define a generalized successor function, which takes a\n   church number and yields another church number: *)\nDefinition succ_church :=\n  <{\\x, \\s, \\z, s (x s z)}>.\n\nDefinition one_church :=\n  <{succ_church zero_church}>.\n\nDefinition two_church :=\n  <{succ_church (succ_church zero_church)}>.\n\nExample succ_church_ex_2 :\n  <{toNat_church (succ_church zero_church)}> -->* <{S tm_zero }>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* We can also define addition on church encoded numerals: *)\nDefinition plus_church :=\n  <{\\x, \\y, \\s, \\z, x s (y s z)}>.\n\nExample plus_ex_1 :\n  <{toNat_church (plus_church (succ_church zero_church) zero_church)}> -->* <{S tm_zero }>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Testing if a number is zero is straightforward: *)\nDefinition is_zero_church :=\n  <{\\x, x (\\y, false_church) true_church}>.\n(* It returns true in the base (zero) case, and throws away the\n   recursive result in the second case to simply return false.*)\nExample is_zero_ex :\n  <{is_zero_church (succ_church zero_church)}> -->* <{false_church}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Finally, for good measure, here are the church encoding of nil and\n   cons (for lists of natural numbers): *)\n\nDefinition nil_church :=\n  <{\\c, \\n, n}>.\n\nDefinition cons_church :=\n  <{\\hd, \\tl, \\c, \\n, c hd (tl c n)}>.\n\n(* The list [1; 2]*)\nDefinition one_two_church :=\n  <{cons_church one_church (cons_church two_church nil_church)}>.\n\n(* IsNil for church-encoded lists:\n   λl. l (λt f. t) (λt f. f)          *)\n\nDefinition isnil_church :=\n  <{\\l, l (\\x, \\y, false_church) true_church}>.\n\nExample isnil_ex :\n  <{ isnil_church nil_church }> -->* <{true_church}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample isnil_ex_2 :\n  <{ isnil_church one_two_church }> -->* <{false_church}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Length of a church-encoded list:\n   λl. l (λhd n. λz s. s (n z s)) (λz. λs. z) *)\n\nDefinition length_church :=\n  <{\\l, l (\\x, succ_church) zero_church }>.\n\nExample length_ex :\n  <{ toNat_church (length_church nil_church)}> -->* <{tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample length_ex_2 :\n  <{ toNat_church (length_church one_two_church)}> -->* <{S (S tm_zero)}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample length_ex_3 :\n  <{ toNat_church (length_church (cons_church three_church one_two_church))}> -->* <{S (S (S tm_zero))}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Summing the elements of a church-encoded list of numbers:\n   λl. l (λz. λs. z) (λhd n. λz s. plus hd (n z s)) *)\n\nDefinition sum_church :=\n  <{\\l, l (\\hd, \\tl, plus_church hd tl) zero_church }>.\n\nExample sum_ex :\n  <{toNat_church (sum_church nil_church)}> -->* <{tm_zero}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\nExample sum_ex_2 :\n  <{ toNat_church (sum_church one_two_church)}> -->* <{S (S (S tm_zero))}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n\n(* Surprisingly, the predecessor function is quite tricky to\n   define. This is because Church encodings are destructive: they\n   always \"process\" subdata by applying the recursive call. Thus, we\n   can't access any of the recursive subdata of a constructor, only\n   the 'result' of recursively processing that function. *)\n\nDefinition pred_church :=\n  <{\\x, fst_church (x (\\y, pair_church (snd_church y)\n                                       (succ_church (snd_church y)))\n                      (pair_church zero_church zero_church)) }>.\n\n(* The definition works by using [x] to apply [x] copies of a function\n   that takes a pair [(c1, c2)] and produces a pair [(c2, 1 + c2)].\n   applying this function x times to the pair [(0, 0)] results in the\n   pair [(x - 1, x)]. Throwing away the second argument yields the\n   predecessor of x.  *)\n\nExample pred_ex :\n  <{ toNat_church (pred_church three_church) }> -->* <{S (S tm_zero)}>.\nProof.\n  normalize_lambda.\n  apply multi_refl.\nQed.\n", "meta": {"author": "bendy", "repo": "SFExtras", "sha": "a9676cc28a5d3d27d09da3e620ca6e7ceb43de65", "save_path": "github-repos/coq/bendy-SFExtras", "path": "github-repos/coq/bendy-SFExtras/SFExtras-a9676cc28a5d3d27d09da3e620ca6e7ceb43de65/ChurchEncodings/Church.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7585268441611694}}
{"text": "\n\nInductive Likes : Type := O | L : Likes -> Likes.\n\n\nFixpoint add x y := \n  match x with\n  | O => y\n  | L n => L (add n y)\n  end.\n\nFixpoint mult x y := \n  match x with \n  | O => O\n  | L n => add y (mult n y)\n  end.\n\nNotation \"x ⊕ y\" := (add x y) (at level 50).\nNotation \"x ⊗ y\" := (mult x y) (at level 40).\n\nFixpoint Σ N := \n  match N with\n  | O => O\n  | L n => N ⊕ (Σ n)\n  end.\n\n\n\nLemma add_O_r x: x ⊕ O = x.\nProof.\n  induction x.\n  - reflexivity.\n  - cbn. rewrite IHx. reflexivity.\nQed.\n\nLemma add_L_r x y : x ⊕ L y = (L x) ⊕ y.\nProof.\n  induction x.\n  - cbn. reflexivity.\n  - cbn. rewrite IHx. reflexivity.\nQed.\n\n\nLemma add_comm x y : x ⊕ y = y ⊕ x.\nProof.\n  induction x.\n  - cbn. rewrite add_O_r. reflexivity.\n  - cbn. rewrite IHx. rewrite add_L_r. reflexivity.\nQed.\n\n\nLemma add_asso x y z : (x ⊕ y) ⊕ z = x ⊕ (y ⊕ z).\nProof.\n  induction x.\n  - cbn. reflexivity.\n  - cbn. rewrite IHx. reflexivity.\nQed.\n\n\nLemma mult_distr_l x y z : x ⊗ (y ⊕ z) = x ⊗ y ⊕ x ⊗ z.\nProof.\n  induction x; cbn.\n  - reflexivity.\n  - rewrite IHx.\n    rewrite <-add_asso, (add_asso y).\n    rewrite (add_comm z).\n    rewrite !add_asso.\n    reflexivity.\nQed.\n\n\nLemma mult_O_r x : x ⊗ O = O.\nProof.\n  induction x; cbn.\n  - reflexivity.\n  - apply IHx.\nQed.\n\nLemma mult_L_r x y : x ⊗ (L y) = x ⊕ x ⊗ y.\nProof.\n  induction x; cbn.\n  - reflexivity.\n  - rewrite IHx. \n    rewrite <- add_asso.\n    rewrite (add_comm y x).\n    rewrite add_asso.\n    reflexivity.\nQed.\n\nLemma mult_comm x y : x ⊗ y = y ⊗ x.\nProof.\n  induction x; cbn.\n  - rewrite mult_O_r. reflexivity.\n  - rewrite mult_L_r. rewrite IHx. reflexivity.\nQed.\n\n\nTheorem Gauss_Sum N : (L (L O)) ⊗ Σ N = N ⊗ L N.\nProof.\n  induction N.\n  - cbn. reflexivity.\n  - cbn [Σ]. \n    rewrite mult_distr_l.\n    rewrite IHN.\n    rewrite !(mult_comm _ (L N)).\n    rewrite <- mult_distr_l.\n    cbn [add].\n    reflexivity.\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/Videos/Gauss_Sum2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.758526829294721}}
{"text": "(**\nObjectif de ce suppport de TD :\ninitiation aux relations ou prédicats définis inductivement,\npour préparer la définition des sémantiques relationnelles.\n*)\n\n(* Les exercices sont faciles, progressifs, et sont prévus\n   pour une durée d'environ 1/2h).\n*)\n\n(* ------------------------------------------------------------ *)\n(** * Relations ou prédicats définis inductivement *)\n\n(** ** Prédicats à 1 argument sur un type énuméré  *)\n\n(** Commençons par un prédicat très simple qui indique comment\n    sélectionner quelques valeurs dans un type énuméré. *)\n\n\n    Inductive coul : Set :=\n    | violet : coul\n    | indigo : coul\n    | bleu : coul\n    | vert : coul\n    | jaune : coul\n    | orange : coul\n    | rouge : coul\n    .\n    \n    (** Rappel : on ne peut PAS définir un autre type qui partage des\n        constructeurs avec un type déjà défini. *)\n    Fail Inductive coulfeu : Set :=\n    | vert : coulfeu\n    | orange : coulfeu\n    | rouge : coulfeu\n    .\n    \n    Definition ATTENTION_QUESTION_EN_COMMENTAIRE_1 : bool.\n    (**\n    Pourquoi interdire à un constructeur d'être dans des types inductifs différents ?\n     *)\n    (* Répondre ici\n    Il pourait y avoir des problèmes lors des raisonnement inductifs\n     *)\n    Admitted.\n    \n    (** Mais on peut définir un prédicat sur coul qui est démontrable\n        pour vert orange et rouge (et seulement pour ces derniers). *)\n    \n    Inductive estCoulfeu : coul -> Prop :=\n    | Fver : estCoulfeu vert\n    | Fora : estCoulfeu orange\n    | Frou : estCoulfeu rouge\n    .\n    \n    (** Par exemple on peut démontrer que vert satisfait ce prédicat. *)\n    Example exemple_feu_vert : estCoulfeu vert.\n    Proof.\n      apply Fver.\n    Qed.\n    \n    (** Certains feux de circulation ne présentent que les deux couleurs\n        vert et rouge. *)\n    \n    Inductive feu2couls : coul -> Prop :=\n    | F2ver : feu2couls vert\n    | F2rou : feu2couls rouge\n    .\n    \n    (** On veut démontrer que le second prédicat implique le premier. *)\n    \n    Lemma feu2couls_estCoulfeu : forall c, feu2couls c -> estCoulfeu c.\n    Proof.\n      intro c.\n      (** On essaie d'abord un raisonnement par cas sur [c].*)\n      destruct c.\n      (** Beaucoup de cas inutiles (et qui requièrent une technique spéciale).\n          Donc on essaye une meilleure stratégie. *)\n      Undo 1.\n      (** Introduction de l'hypothèse sur [c]. *)\n      intro f2c.\n      (** Il suffit de raisonner par cas sur les deux façons\n          dont [f2c] peut être construite *)\n      refine (match f2c with F2ver => _ | F2rou => _ end).\n      clear.\n      (** Même chose en utilisant la tactique destruct sur l'HYPOTHÈSE [f2c] *)\n      Undo 2.\n      destruct f2c as [ (*F2ver*) | (*F2rou*) ].\n      - apply Fver.\n      - refine Frou.\n    Qed.\n    \n    (** Exercice *)\n    \n    (** Sur le modèle du prédicat estCoulfeu, définir un autre prédicat nommé boivr,\n        qui sélectionne les couleurs bleu, orange, indigo, vert et rouge. *)\n    \n    (* Inductive boivr à compléter *)\n    \n    Inductive boivr : coul -> Prop := \n    | bBleu : boivr bleu\n    | bOrange : boivr orange\n    | bIndigo : boivr indigo\n    | bVert  : boivr vert\n    | bRouge : boivr rouge\n    .\n    \n    (** Démontrer ensuite : *)\n    \n    Lemma estCoulfeu_boivr : forall c, estCoulfeu c -> boivr c.\n    Proof.\n      (** compléter *)\n      intro c.\n      intro ec.\n\n      destruct ec as [ (*FVer*) | (*Fora*) | (*Frou*)].\n      - apply bVert.\n      - apply bOrange.\n      - apply bRouge.\n    Qed.\n\n    (** ** Relations à 2 arguments sur un type énuméré *)\n    \n    (** Les relations inductives permettent de représenter des fonction partielles\n        i.e., qui ne sont pas définies partout. Voici un exemple où coulsuiv\n        est définie pour vert, orange et rouge, mais pas pour les autres couleurs\n        prévues dans coul. *)\n    \n    Inductive coulsuiv : coul -> coul -> Prop :=\n    | CSv : coulsuiv vert orange\n    | CSo : coulsuiv orange rouge\n    | CSr : coulsuiv rouge vert\n    .\n    \n    (** Exercice (même technique qu'auparavant) *)\n    \n    Lemma coulsuiv_estCoulfeu : forall c1 c2, coulsuiv c1 c2 -> estCoulfeu c1.\n    Proof.\n      (** compléter *) \n      intro c1.\n      intro c2.\n      intro cs.\n\n      destruct cs as [ (*CSv*) | (*CSo*) | (*CSr*)].\n      - apply Fver.\n      - apply Fora.\n      - apply Frou.\n    Qed.\n    \n    (** ** Prédicat even sur nat *)\n    \n    (** De même que les types inductifs de données peuvent être récursifs,\n        par exemple nat ou aexp, les prédicats inductifs peuvent être\n        récursifs. C'est le cas de even, présenté au CM4. *)\n    \n    Inductive even : nat -> Prop :=\n    | E0 : even 0\n    | E2 : forall n, even n -> even (S (S n))\n    .\n    \n    (** Exercice : démontrer que 6 est pair. *)\n    \n    Example ev10 : even 10.\n    Proof.\n      refine (E2 8 _).\n      apply (E2 6).\n      apply E2.\n      apply E2.\n      apply E2.\n      apply E0.\n    Qed.\n    \n    Print ev10.\n    \n    Definition ATTENTION_QUESTION_EN_COMMENTAIRE_2 : bool.\n    (** Exercice :\n        - quel est le type et la signification de E2 4 ?\n        - quel est le type et la signification de E2 5 ?\n    *)\n    (* Répondre ici\n    E2 4 : even 4\n    E2 5 : even 5\n     *)\n    Admitted.\n    \n    \n    (** Entiers atteignables en ajoutant des 2 ou des 7 en partant de 0. *)\n    Inductive p2p7 : nat -> Prop :=\n    | PP0 : p2p7 0\n    | PP2 : forall n, p2p7 n -> p2p7 (2 + n)\n    | PP7 : forall n, p2p7 n -> p2p7 (7 + n)\n    .\n    \n    (** Exercice : démontrer de 3 façons que 11 est atteignable par p2p7. *)\n    Example p2p7_11_methode1 : p2p7 11.\n    Proof.\n      apply PP7.\n      apply PP2.\n      apply PP2.\n      apply PP0.\n    Qed.\n    \n    Example p2p7_11_methode2 : p2p7 11.\n    Proof.\n      apply PP2.\n      apply PP2.\n      apply PP7.\n      apply PP0.\n    Qed.\n    \n    Example p2p7_11_methode23 : p2p7 11.\n    Proof.\n      refine (PP7 4 _).\n      refine (PP2 2 _).\n      refine (PP2 0 _).\n      apply PP0.\n    Qed.\n\n\n    \n    Print p2p7_11_methode2.\n    \n    (** Démontrer que tout entier pair satisfait p2p7. *)\n    \n    Theorem even_p2p7 : forall n, even n -> p2p7 n.\n    Proof.\n      intros n en.\n      (** Comme il y a une infinité d'entiers pairs, une preuve par cas\n          ne suffit pas. On procède par récurrence structurelle sur les\n          façons de démontrer [even n], autrement les formes possibles\n          d'arbres de preuve pour [en].\n          On a deux cas, celui où [en] est [E0], et celui où [en]\n          est de la forme [E2 n' en'], avec [en' : even n'] ;\n          dans ce dernier cas, on a droit à une hypothèse de récurrence\n          sur en', assurant que [n'] satisfait p2p7.\n      *)\n      induction en as [ (*E0*) | (*E2*) n' evn' Hrec_evn'].\n      - apply PP0.\n      - (** Facultatif : mise sous une forme clairement adaptée à p2p7 *)\n        change (p2p7 (2 + n')).\n        (** Utilisation du constructeur approprié de p2p7 *)\n        apply PP2.\n        (** Utilisation de l'hypothèse de récurrence *)\n        apply Hrec_evn'.\n    Qed.\n    \n    (** Il est instructif de démontrer le même théorème par une\n        fonction récursive. *)\n    \n    Fixpoint fct_even_p2p7 n (en : even n) : p2p7 n :=\n      match en with\n      | E0 => PP0\n      | E2 n' evn' => PP2 n' (fct_even_p2p7 n' evn')\n      end.\n    \n    (** On peut transformer un arbre de preuve de [even 4]\n        en un arbre de preuve de [p2p7 4] *)\n    Compute fct_even_p2p7 4 (E2 2 (E2 0 E0)).\n    \n    (** La somme de deux entiers pairs est paire *)\n    Lemma even_plus : forall n m, even n -> even m -> even (n + m).\n    Proof.\n      intros n m evn evm.\n      induction evn as [ (*E0*) | (*E2*) n' evn' Hrec_evn'].\n        - apply evm.\n        - change (even (S (S (n' + m)))).\n          apply E2.\n          apply Hrec_evn'.\n    Qed.\n    \n    (** Exercice facultatif :\n        en donner une preuve sous forme de fonction. *)\n    \n    Fixpoint fct_even_plus n m (evn : even n) (evm : even m) : even (n + m).\n      (** A compléter *)\n    Admitted.\n    \n    (* Les multiples de 4 sont pairs *)\n    Inductive mul4 : nat -> Prop :=\n    | M4_0 : mul4 0\n    | M4_4 : forall n, mul4 n -> mul4 (S (S (S (S n))))\n    .\n    \n    Lemma mul4_even : forall n, mul4 n -> even n.\n    Proof.\n      intros n m4n.\n      (** Terminer par récurrence structurelle sur [m4n] *)\n    Admitted.", "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_env_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.7584886662207987}}
{"text": "(**Pattern Matching**)\nInductive month:Set:= January|February|March|April|May|June|July|August|September|October|November|December.\n\n\nDefinition nbdays (m:month) :=\nmatch m with\n| April => 30\n| June => 30\n|September=> 30\n|November=>30\n|February=>28\n| _ => 31\nend.\nCheck nbdays.\nCompute nbdays June.\nCompute nbdays October.\n\nRequire Import Omega.\nRequire Import Arith. \nTheorem monthcase: forall m: month, le 28 (nbdays m). \n  intro. case ( m). simpl.  omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega. simpl. omega.  simpl. omega. \nQed. (*we could use some autoamation here**)\n                                                                        (**Function that returns true in case a month is a winter month, false otherwise**)\nDefinition is_winter_month (m:month) :=\n  match m with\n|December => True\n| January => True\n|February => True\n|_ => False\n  end.\nCompute is_winter_month July.\nCompute is_winter_month February.\nInductive season:Set:= Winter|Spring|Summer|\n                       Autumn.\nDefinition winter_season_month_match (s: season) (m:month) :=\n  match s, m with\n  | Winter, December => True\n  | Winter, January => True\n  | Winter, February => True\n  |_ , _ => False\n  end.\n\n(**Pattern matching with recursive functions**) \nFixpoint plus (n m : nat) : nat :=\nmatch n with\nO => m\n| S p => S (plus p m)\nend.\nCompute plus 4 8.\n\nFixpoint minus (n m : nat) : nat :=\nmatch n, m with\nS p, S q => minus p q\n| _, _ => n\nend.\nCompute minus 11 9.\nDefinition e:= Set.\nInductive Gender:Set:= Fem|Masc|Neut.\nInductive Case:Set:= Nom|Acc.\nParameter he she it him her they I me we  you: e. \nDefinition  pronoun (g: Gender) (c:Case):=\n  match g, c with\n|Fem, Nom=> she\n|Fem, Acc => her\n|Masc, Nom=> he\n|Masc, Acc=> him\n|Neut, _=> it\n  end.\nCompute pronoun Neut Acc.\n\n\n(** Some record examples. Defining Entity as a more structured type**)\nParameter human walk: e->Prop. \n  Record Entity : Type := mkentity {x: e; z: human x}.\n  Parameter John: Entity. \n  Check walk (John.(x)).\n  Theorem en: Entity-> exists x, human x.\n    intro.      decompose record X. exists x0. assumption. Qed.\n  Theorem WALK: walk (John.(x))-> exists x:e, walk x. intro. decompose record John. exists John.(x). assumption. Qed.\n\n\n  Section SUB.\n Definition CN:=Set.\n Parameters Woman  Man Human Animal Object: CN. (**CNs as types**)\n Axiom wh: Woman  ->Human. Coercion wh: Woman >->Human.\n Axiom mh: Man ->Human. Coercion mh: Man >->Human.\n  Axiom ha: Human -> Animal. Coercion ha: Human>->Animal.\n  Axiom ao: Animal -> Object. Coercion ao: Animal >-> Object.\n\n  Parameter drive: Human -> Prop.\n  Parameter George  : Man.\n  Parameter Mary: Woman. \n  Check drive Mary.  (**work because of the subtyping**)\n  Check and(drive George)(drive Mary). \n  (** some reasoning **)\n  Theorem MARY: drive Mary -> exists x: Woman, drive x. \n  cbv.   intro. exists Mary. assumption. Qed. \n\nTheorem MARY1:  drive Mary -> exists x: Human, drive x.\n  cbv.   intro. exists Mary. assumption. Qed.  (**subtyping**)\n\n(**Monotonicity on the first argument for free with subtyping**)\nTheorem MONIN: exists x: Man, drive x -> exists x: Human, drive x.\nexists George.  intro. exists George. assumption. Qed. \nTheorem MONDEC: not (exists x: Human, drive x) -> not(exists x: Man, drive x).\ncbv.   intros. apply H.   elim H0. intros. exists x0. assumption. Qed. (**bool in nat**)\nDefinition bool_in_nat (b:bool) := if b then 0 else 1.\nCheck bool_in_nat.\nCoercion bool_in_nat : bool >-> nat.\nCheck (0 = true).\nSet Printing Coercions.\nCheck (0 = true).\n\n\n(**Co-induction**)\nSet Implicit Arguments. \nCoInductive LList (A:Set) : Set :=\nLNil : LList A\n| LCons : A -> LList A -> LList A.\nImplicit Arguments LNil [A].\nPrint LList.\nRequire Import Streams. \nCheck Stream. Print Stream.\n\nCheck (LCons 1 (LCons 2 (LCons 3 LNil))).\nEval compute  in (LCons 1 (LCons 2 (LCons 3 LNil))).\n(**Eval compute  in (Cons 1 (Cons 2 (Cons 3))).**) (**there is no Nil to provide the Stream nat argument**)\nDefinition next_month (m:month) :=\nmatch m with\n| January => February\n| February => March \n| March => April\n| April => May\n| May => June \n| June => July\n| July => August\n| August => September\n| September => October\n| October => November\n| November => December\n| December => January\nend.\n\n\nTheorem next_august_then_july: forall m:month, next_month m = August -> m = July. intros m. case m. simpl. intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. reflexivity.   intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. discriminate H.  intros. discriminate H. Qed.\n\n\nLemma incorrect_equality_implies_anything: forall a, false = true -> a. intros. discriminate. Qed. ", "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_basics1c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7584886522746792}}
{"text": "Inductive pFormula : Set :=\n| Top  : pFormula\n| Bot  : pFormula\n| Conj : pFormula -> pFormula -> pFormula\n.\n\nFixpoint pFormulaDenote (p:pFormula) : Prop :=\n    match p with\n    | Top           => True\n    | Bot           => False\n    | Conj p1 p2    => pFormulaDenote p1 /\\ pFormulaDenote p2\n    end.\n\n(*  Def: An reflexive type is an inductive type which includes at \n    least one constructor that takes as an argument a function \n    returning the same type we are defining                        *)\n\nInductive Formula : Set :=\n| Eq     : nat -> nat -> Formula\n| And    : Formula -> Formula -> Formula\n| Forall : (nat -> Formula) -> Formula     (* reflexive type ! *)\n.\n\nDefinition forall_refl : Formula := Forall (fun x => Eq x x). \n\nFixpoint formulaDenote (p:Formula) : Prop :=\n    match p with\n    | Eq n m        => n = m\n    | And p1 p2     => formulaDenote p1 /\\ formulaDenote p2\n    | Forall P      => forall (n:nat), formulaDenote (P n)\n    end.\n\nFixpoint swapper (p:Formula) : Formula :=\n    match p with \n    | Eq n m        => Eq m n \n    | And p1 p2     => And (swapper p2) (swapper p1)\n    | Forall P      => Forall (fun n => swapper (P n))\n    end.\n\nLemma swapper_preserves_truth : forall (p:Formula), \n    formulaDenote p -> formulaDenote (swapper p).\nProof.\n    induction p as [n m|p1 IH1 p2 IH2|P IH]; simpl.\n    - intros. symmetry. assumption.\n    - intros [H1 H2]. split.\n        + apply IH2. assumption.\n        + apply IH1. assumption.\n    - intros H n. apply IH, H.\nQed.\n\n(*\nCheck Formula_ind.\n*)\n\n(* Error: Non strictly positive occurrence of \"Term\" \nInductive Term : Set :=\n| App : Term -> Term -> Term\n| Lam : (Term -> Term) -> Term \n.\n\nIf this definition was accepted by Coq, then we could define:\n\nDefinition uhoh (t:Term) : Term :=\n    match t with \n    | Abs f         => f t\n    | _             => t\n    end.\n\nfrom which we would obtain:\n\nuhoh (Abs uhoh) = \nuhoh (Abs uhoh) = ...\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/reflexive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7584886488680018}}
{"text": "Require Import Frap.\n\n(* Sum to and CPS *)\nFixpoint sum_to (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S n' => n + sum_to n'\n  end.\n\nTheorem sum_to_thm : forall (n: nat),\n  2 * sum_to n = n * (n+1).\nProof.\n  induct n.\n  + simplify; linear_arithmetic.\n  + assert (2 * sum_to (S n) = 2 * (S n) + 2 * sum_to n) by (simplify; ring).\n    rewrite H.\n    rewrite IHn.\n    clear H IHn.\n    ring.\nQed.\n\nFixpoint sum_to_CPS (n: nat) (C: nat -> nat): nat :=\n  match n with\n  | 0 => C 0\n  | S n' => sum_to_CPS n' (fun R => C (n + R))\n  end.\n\nTheorem CPS_correct: forall (n: nat) (f: nat -> nat),\n  f (sum_to n) = sum_to_CPS n f.\nProof.\n  induct n; simplify.\n  + trivial.\n  + apply IHn with (f := fun R: nat => f (S (n + R))).\nQed.\n\nTheorem sum_to_thm2: forall (n: nat),\n  2 * (sum_to_CPS n (fun R: nat => R)) = n * (n + 1).\nProof.\n  simplify.\n  pose CPS_correct.\n  symmetry in e.\n  rewrite e with (n := n) (f := fun R: nat => R).\n  apply sum_to_thm.\nQed.", "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/sum_to.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7583969073640058}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_NCorder.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_BCD.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\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_s_ncol_ABD_col_ABC_ncol_ACD :\n\tforall A B D C,\n\tnCol A B D ->\n\tCol A B C ->\n\tneq A C ->\n\tnCol A C D.\nProof.\n\tintros A B D C.\n\tintros nCol_A_B_D.\n\tintros Col_A_B_C.\n\tintros neq_A_C.\n\n\tassert (~ Col A C D) as n_Col_A_C_D.\n\t{\n\t\tintros Col_A_C_D.\n\n\t\tpose proof (lemma_inequalitysymmetric _ _ neq_A_C) as neq_C_A.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_B_C) as (_ & _ & Col_C_A_B & _ & _).\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_C_D) as (Col_C_A_D & _ & _ & _ & _).\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_C_A_B Col_C_A_D neq_C_A) as Col_A_B_D.\n\n\t\tcontradict Col_A_B_D.\n\t\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_A_B_D) as n_Col_A_B_D.\n\t\texact n_Col_A_B_D.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_A_C_D) as nCol_A_C_D.\n\texact nCol_A_C_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_ncol_ABD_col_ABC_ncol_ACD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7583449215373265}}
{"text": "Section Inf_List.\nRequire Import Arith.\n\nCoInductive inf_list : Set :=\n  | inf_cons : nat -> inf_list -> inf_list.\n\nDefinition head (l:inf_list) :=\n  match l with\n    | inf_cons n l' => n\n  end.\n\nDefinition tail (l:inf_list) :=\n  match l with\n    | inf_cons n l' => l'\n  end.\n\nCoFixpoint ext (f : nat -> nat) (l : inf_list) : inf_list :=\n  match l with\n    | inf_cons n l' => inf_cons (f n) (ext f l')\n  end.\n(** Notice that this definition fits the pattern on page 9 of \n    Jacobs:1997.  That is \n        [head(ext f l) = f (head l)]\n        [tail(ext f l) = ext f (tail l)].\n    In fact the proof of this claim is trivial. *)\nLemma ext_fits_coind_pattern : forall f l,\n  head (ext f l) = f (head l) /\\\n  tail (ext f l) = ext f (tail l).\nProof.\n  auto.\n  Restart.\n  intros; destruct l; split; reflexivity.\nQed.\n(** Our pattern above tells us that we can actually define\n    [ext] interms of [head] and [tail]. *)\nReset ext.\nCoFixpoint ext (f : nat -> nat) (l : inf_list) : inf_list := \n  inf_cons (f (head l)) (ext f (tail l)).\n\n(** Next we define the definition of a co-inductive function called odd.\n    It takes an infinite list and produces the infinite list containing \n    the elements at odd positions in the input list *)\nCoFixpoint odd (l : inf_list) : inf_list := inf_cons (head l) (tail (tail l)).\n(** We can also define [even], but this is easy.  *)\nDefinition even (l: inf_list) : inf_list := odd (tail l).\n\n(** The following co-inductive function merges two [inf_list]'s into a single\n    [inf_list] in turn starting with the first. *)\nCoFixpoint merge (l1 : inf_list) (l2 : inf_list) : inf_list :=\n  inf_cons (head l1) (merge l2 (tail l1)).\n(** This definition is equivalent to the following: *)\nReset merge.\nCoFixpoint merge (l1 : inf_list) (l2 : inf_list) : inf_list :=\n  inf_cons (head l1) (inf_cons (head l2) (merge (tail l1) (tail l2))).\n(** Another example is to merge three [inf_list]'s in a round robin way. *)\nCoFixpoint merge3 (l1 : inf_list) (l2 : inf_list) (l3 : inf_list) : inf_list :=\n  inf_cons (head l1) (inf_cons (head l2) (inf_cons (head l3) (merge3 (tail l1) (tail l2) (tail l3)))).\n(** The following is a more compact definition. *)\nReset merge3.\nCoFixpoint merge3 (l1 : inf_list) (l2 : inf_list) (l3 : inf_list) : inf_list :=\n  inf_cons (head l1) (merge3 l2 l3 (tail l1)).\n(** Using this definition we can define the following merge function which takes two elements of the\n   first [inf_list] for every one element in the second. This was proposed as an exercise in Jacobs:1997\n   (page 10).  They give no indication of what order we choose the elements from the first list or\n   weather or not they should repeat.  In the footnote they suggest using [merge3], but this results\n   in repeats if we maintain the order of the first. Here is the first definition. *)\nCoFixpoint merge_2_1 (l1 : inf_list) (l2 : inf_list) : inf_list := merge3 l1 (tail l1) l2.\nReset merge_2_1.\n(** We can get around the repeats with this definition if we do not maintain the order of\n    the first list. *)\nCoFixpoint merge_2_1 (l1 : inf_list) (l2 : inf_list) : inf_list := merge3 l1 (tail (tail l1)) l2.\nReset merge_2_1.\n(** The following definition maintains the order of the first list and does not repeat, but it does\n    not have as elegant of a solution as the previous ones. *)\nCoFixpoint merge_2_1 (l1 : inf_list) (l2 : inf_list) : inf_list :=\n  inf_cons (head l1) (inf_cons (head (tail l1)) (inf_cons (head l2) (merge_2_1 (tail (tail l1)) (tail l2)))).\nEnd Inf_List.\n", "meta": {"author": "heades", "repo": "examples", "sha": "30f2f4811828870820f34253ed5a51c76723eef1", "save_path": "github-repos/coq/heades-examples", "path": "github-repos/coq/heades-examples/examples-30f2f4811828870820f34253ed5a51c76723eef1/coq/infinite_lists/inf_lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7583007000338127}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_equalanglesNC.\nRequire Import ProofCheckingEuclid.lemma_s_conga.\n\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equalanglessymmetric :\n\tforall A B C a b c,\n\tCongA A B C a b c ->\n\tCongA a b c A B C.\nProof.\n\tintros A B C a b c.\n\tintros CongA_ABC_abc.\n\n\tassert (CongA_ABC_abc2 := CongA_ABC_abc).\n\tdestruct CongA_ABC_abc2 as (U & V & u & v & OnRay_BA_U & OnRay_BC_V & OnRay_ba_u & OnRay_bc_v & Cong_BU_bu & Cong_BV_bv & Cong_UV_uv & nCol_A_B_C).\n\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_BU_bu) as Cong_bu_BU.\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_BV_bv) as Cong_bv_BV.\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_UV_uv) as Cong_uv_UV.\n\n\tpose proof (lemma_equalanglesNC _ _ _ _ _ _ CongA_ABC_abc) as nCol_a_b_c.\n\n\tpose proof (\n\t\tlemma_s_conga\n\t\ta b c A B C\n\t\t_ _ _ _\n\t\tOnRay_ba_u\n\t\tOnRay_bc_v\n\t\tOnRay_BA_U\n\t\tOnRay_BC_V\n\t\tCong_bu_BU\n\t\tCong_bv_BV\n\t\tCong_uv_UV\n\t\tnCol_a_b_c\n\t) as CongA_abc_ABC.\n\n\texact CongA_abc_ABC.\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_equalanglessymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7582478861529622}}
{"text": "(* 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.\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 RndNat.\nRequire Import 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\nHint Resolve RndGrpElem_wf : wftac.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/OTP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.758247881623242}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\nFrom mathcomp.analysis Require Import sequences.\n\nOpen Scope ring_scope.\n\nModule CustomSequences.\n  (* This module was written before I knew about mathcomp-analysis,\n       hence the [Definition Sequence]. *)\n\n  Import GRing.Theory.\n\n  Definition Sequence (K : fieldType) := nat -> K.\n  Definition SequenceSum {K : fieldType} (s : Sequence K) (n : nat) := \\sum_(0 <= i < n.+1) s i.\n\n  Inductive GeometricSequence {K : fieldType} : Sequence K -> K -> Prop :=\n  | geo_seq (s : Sequence K) (q : K) (H : forall (n : nat), s n * q = s n.+1) : GeometricSequence s q.\n\n  Lemma sum_distrr {K : fieldType} (m n : nat) (s : Sequence K) (q : K) :\n    q * (\\sum_(m <= i < n) s i) = \\sum_(m <= i < n) q * s i.\n  Proof.\n    by rewrite big_distrr.\n  Qed.\n\n  Lemma sum_extract_fst {K : fieldType} (s : Sequence K) (m n : nat) :\n    (m <= n)%N -> \\sum_(m <= i < n.+1) s i = s m + \\sum_(m <= i < n) s i.+1.\n  Proof.\n    move => le_mn.\n    by rewrite big_nat_recl.\n  Qed.\n\n  Lemma sum_extract_lst {K : fieldType} (s : Sequence K) (m n : nat) :\n    (m <= n)%N -> \\sum_(m <= i < n.+1) s i = \\sum_(m <= i < n) s i + s n.\n  Proof.\n    move => le_mn.\n    by rewrite big_nat_recr/=.\n  Qed.\n\n  Lemma geo_seq_n_term {K : fieldType} (s : Sequence K) (q : K) :\n    GeometricSequence s q -> forall (n : nat), s n = s O * q ^+ n.\n  Proof.\n    move => geo_s.\n    inversion geo_s.\n    clear s0 q0 H0 H1.\n    elim => [|n IHn].\n    by rewrite mulrC mul1r.\n    rewrite -H IHn.\n    by rewrite -mulrA -exprSr.\n  Qed.\n\n  Lemma GeometricSequence_Sum {K : fieldType} (s : Sequence K) (q : K) :\n    1 - q != 0 -> GeometricSequence s q -> forall n : nat, SequenceSum s n = s O * (1 - q ^+ n.+1) / (1 - q).\n  Proof.\n    move => neq_q1 geo_s n.\n    inversion geo_s.\n    clear s0 q0 H0 H1 geo_s.\n    rewrite /SequenceSum.\n    under eq_bigr => *.\n    by rewrite (geo_seq_n_term s q)// over.\n    rewrite -sum_distrr.\n    set sum := (\\sum_(_ <= i < _.+1) _).\n    rewrite -(mulKf (F := K) (x := 1 - q) _ sum)//.\n    have -> : (1 - q) * sum = 1 - q ^+ n.+1.\n    {\n      rewrite mulrBl.\n      rewrite /sum {1}sum_extract_fst//\n        sum_distrr sum_extract_lst//.\n      under (eq_bigr (F1 := fun _ => _ * _)) do rewrite -exprS.\n                                             by rewrite -exprS mul1r addrKA.\n    }\n    by rewrite (mulrC (_ ^-1)) mulrA.\n  Qed.\n\nEnd CustomSequences.\n\n", "meta": {"author": "0poss", "repo": "CoqL1", "sha": "43ac59ff9913cc7467b804165d72230116da0756", "save_path": "github-repos/coq/0poss-CoqL1", "path": "github-repos/coq/0poss-CoqL1/CoqL1-43ac59ff9913cc7467b804165d72230116da0756/Analysis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.758210258949943}}
{"text": "Require Import ssreflect ssrfun ssrbool.\n\n(** specification *)\n\n\nModule Type ProjectiveSpace.\n\n  Parameter Point : Type.\n\n  Parameter Line: Type.\n\n  (* eventuellement FinType *)\n  (* Check ([forall p1 : Point, forall p2:Point, p1==p2]). *)\n  (* Search _ [exists _ : _,_]. *)\n  (* Search _ pick. *)\n  (* Check (forall p1 p2:Point, forall l:Line, ((a1_exists p1) p2)=l). *)\n  Parameter eqP : Point -> Point -> bool.\n  Parameter eqL : Line -> Line -> bool.\n\n  Parameter incid_lp : Point -> Line -> bool.\n  \n  (* A1 : any two points lie on a unique Line *)\n  \n  Axiom a1_exists : forall A B : Point,\n                          {l : Line| incid_lp A l && incid_lp B l}.\n\n  Axiom uniqueness : forall (A B :Point)(l1 l2:Line),\n      incid_lp A l1 -> incid_lp B l1  ->\n      incid_lp A l2 -> incid_lp B l2 -> A = B \\/ l1 = l2.\n\n(* A2 : Pasch's axiom *)\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  Axiom a2 : forall A B C D:Point, forall lAB lCD lAC lBD :Line,\n  \tdist_4p A B C D -> \n\tincid_lp A lAB && incid_lp B lAB ->\n\tincid_lp C lCD && incid_lp D lCD ->\n\tincid_lp A lAC && incid_lp C lAC ->\n\tincid_lp B lBD && incid_lp D lBD ->\n\t(exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n        exists J:Point, incid_lp J lAC && incid_lp J lBD.\n\n    (** A3 : dimension-related axioms *)\n  Definition dist_3p  (A B C :Point) : bool := (negb (eqP A B)) && (negb (eqP A C)) && (negb (eqP B C)).\n\n  Axiom a3_1 :\n    forall l:Line,{A:Point & {B:Point & {C:Point |\n                                         (dist_3p A B C) &&\n                                         (incid_lp A l && incid_lp B l && incid_lp C l)}}}.\n\n  (** there exists 2 lines which do not intersect *)\n  Axiom a3_2 (* dim >= 3 *) :\n    exists l1:Line, exists l2:Line,\n      forall p:Point, ~(incid_lp p l1 && incid_lp p l2).\n\n  Definition Intersect_In (l1 l2 :Line) (P:Point) := incid_lp P l1 && incid_lp P l2.\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  Axiom a3_3 :  forall l1 l2 l3:Line,\n      dist_3l l1 l2 l3 ->\n      exists l4 :Line,  exists J1:Point, exists J2:Point, exists J3:Point,\n\t     Intersect_In l1 l4 J1 && Intersect_In l2 l4 J2 && Intersect_In l3 l4 J3.\n\nEnd ProjectiveSpace.\n\n(* Local Variables: *)\n(* coq-prog-name: \"/Users/magaud/.opam/4.06.0/bin/coqtop\" *)\n(* coq-load-path: ( (\".\" \"Top\") ) *)\n(* suffixes: .v *)\n(* End: *)\n\n", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Finite/pg3x_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7581885610993152}}
{"text": "Require Import List Omega.\nImport ListNotations.\n\nInductive bintree : Type := \n| leaf : bintree\n| node : nat -> bintree -> bintree -> bintree.\n\nFixpoint lookup (n : nat) (t : bintree) : Prop :=\n    match t with\n    | leaf => False \n    | node x l r => if eq_nat_dec x n\n                    then True \n                    else if le_lt_dec n x\n                    then lookup n l\n                    else lookup n r\n    end.\n\nInductive valid : bintree -> Type :=\n| val_leaf : valid leaf\n| val_node : forall x l r, valid l -> valid r ->\n                      (forall y, lookup y l -> y <= x)  ->\n                      (forall y, lookup y r -> y > x) -> \n                      valid (node x l r).\n\nFixpoint insert (x : nat) (t : bintree) : bintree :=\n    match t with\n    | leaf => node x leaf leaf\n    | node y l r => if le_lt_dec x y\n                    then node y (insert x l) r\n                    else node y l (insert x r)\n    end.\n\nFixpoint inorder (t : bintree) : list nat :=\n    match t with\n    | leaf => []\n    | node x l r => inorder l ++ (x :: inorder r)\n    end.\n\nFixpoint list_to_bin (xs : list nat) : bintree :=\n    match xs with\n    | [] => leaf\n    | x :: xs' => insert x (list_to_bin xs')\n    end.\n\nDefinition binsort (xs : list nat) : list nat := inorder (list_to_bin xs).\n\nExample binsort_ex_01 : binsort [10;4;3;6;2;3;0;0;1] = [0;0;1;2;3;3;4;6;10].\nProof. reflexivity. Qed.\n\nInductive ordered : list nat -> Type :=\n| o_nil  : ordered []\n| o_sing : forall x, ordered [x]\n| o_cons : forall x y xs, x <= y -> ordered (y :: xs) -> ordered (x :: y :: xs).\n\nLemma lookup_leaf_false (x : nat) : lookup x leaf -> False.\nProof.\n  intros. inversion H.\nQed.\n\nLemma lookup_insert (t : bintree) (x y : nat) :\n  lookup y (insert x t) -> y = x \\/ lookup y t.\nProof.\n  induction t; intros; simpl in *.\n  - destruct (Nat.eq_dec x y).\n    + left. symmetry. assumption.\n    + right. destruct (le_lt_dec y x); assumption.\n  - destruct (le_lt_dec x n); simpl in *; destruct (Nat.eq_dec n y);\n        try (right; constructor); destruct (le_lt_dec y n).\n    + apply (IHt1 H).\n    + right. assumption.\n    + right. assumption.\n    + apply (IHt2 H).\n  Qed.\n\nLemma insert_valid (x : nat) (t : bintree) : valid t -> valid (insert x t).\nProof.\n  intros. generalize dependent x. induction t; intros; simpl in *.\n  - constructor; intros; try constructor; contradiction (lookup_leaf_false y H0).\n  - inversion H. subst. destruct (le_lt_dec x n).\n    + apply (val_node _ _ _ (IHt1 H3 x) H4); intros.\n      * destruct (lookup_insert t1 x y H0); \n                [subst; assumption | apply (H5 _ H1)].\n      * apply (H6 _ H0).\n    + apply (val_node _ _ _ H3 (IHt2 H4 x) H5).\n      intros. destruct (lookup_insert t2 x y H0).\n      * subst. omega.\n      * apply (H6 _ H1).\nQed.\n\nLemma list_to_bin_valid (xs : list nat) : valid (list_to_bin xs).\nProof.\n    induction xs; simpl; [constructor |].\n    apply (insert_valid _ _ IHxs).\nQed.\n\nLemma ordered_app (xs ys : list nat) (y : nat) : \n  ordered xs -> ordered (y :: ys) -> (forall x, In x xs -> x <= y) ->\n  ordered (xs ++ y :: ys).\nProof.\n  induction xs; intros; simpl in *; [assumption |].\n  inversion H; subst; simpl in *.\n  - constructor.\n    + apply H1. left. reflexivity.\n    + assumption.\n  - constructor.\n    + assumption.\n    + apply (IHxs H5 H0). intros. destruct H2; simpl in *.\n      * subst. apply H1. right. left. reflexivity.\n      * apply H1. right. right. assumption.\nQed.\n\nLemma ordered_cons (xs : list nat) :\n  forall (x : nat), (forall z, In z xs -> x <= z) -> ordered xs -> ordered (x :: xs).\nProof.\n  induction xs; intros; simpl in *; constructor.\n  - apply H. left. reflexivity.\n  - apply (IHxs a). intros.\n    + inversion H0; subst. inversion H1. \n      apply le_trans with (m := y). assumption. \n      simpl in *. destruct H1.\n      * omega.\n      * more stuff\n\n\n  \nLemma inorder_valid_ordered (t : bintree) : valid t -> ordered (inorder t).\nProof.\n  intros H. induction H; [constructor |].\n  simpl in *. apply (ordered_app _ _ _ IHvalid1).\n  - \n\nTheorem ordered_binsort (xs : list nat) : ordered (binsort xs).\nProof. \n  unfold binsort. simpl. intros.\nTheorem binsort_perm x (xs : list nat) : In x xs <-> In x (binsort xs).\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/BinTree2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7581885549162447}}
{"text": "Require Import Arith String.\n\n(* This is a comment *)\n\nInductive exp : Set :=\n  | Constant : nat -> exp\n  | Plus : exp -> exp -> exp\n  | Times : exp -> exp -> exp.\n\nFixpoint eval (e : exp) : nat :=\n  match e with\n    | Constant n => n\n    | Plus e1 e2 => eval e1 + eval e2\n    | Times e1 e2 => eval e1 + eval e2\n  end.\n\nFixpoint commuter (e : exp) : exp :=\n  match e with\n   | Constant _ => e\n   | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n   | Times e1 e2 => Times (commuter e2) (commuter e1)\n  end.\n\nInductive natural : Set :=\n  | Zero : natural\n  | Succ : natural -> natural.\n\nFixpoint add (n m : natural) : natural :=\n  match n with\n   | Zero => m\n   | Succ n' => Succ (add n' m)\n  end.\n\nTheorem add_assoc : forall n m o,\n  add (add n m) o = add n (add m o).\nProof.\n  induction n.\n  intros.\n  simpl.\n  reflexivity.\n\n  intros.\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma add_Zero : forall n,\n  add n Zero = n.\nProof.\n  induction n; simpl.\n  reflexivity.\n\n  rewrite IHn.\n  reflexivity.\nQed.\n\nLemma add_Succ  : forall n m,\n  add n (Succ m) = Succ (add n m).\nProof.\n  induction n; simpl; intros.\n  reflexivity.\n\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem add_comm : forall n m,\n  add n m = add m n.\nProof.\n  induction n; intros; simpl.\n\n  rewrite add_Zero.\n  reflexivity.\n  rewrite IHn.\n  rewrite add_Succ.\n  reflexivity.\nQed.\n\nTheorem eval_commuter : forall e,\n  eval (commuter e) = eval e.\nProof.\n  induction e; simpl.\n  reflexivity.\n  rewrite IHe1, IHe2.\n  ring.\n\n  rewrite IHe1, IHe2.\n  ring.\nQed.", "meta": {"author": "sguzman", "repo": "CoqRepo", "sha": "e802df1540b7cff7dad5731c6abfcbf8e669f44e", "save_path": "github-repos/coq/sguzman-CoqRepo", "path": "github-repos/coq/sguzman-CoqRepo/CoqRepo-e802df1540b7cff7dad5731c6abfcbf8e669f44e/induction_and_recursion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7581885462900888}}
{"text": "Module Four.\n\nInductive Day_of_the_Week : Set :=\nMonday | Tuesday | Wednesday\n| Thursday | Friday\n| Saturday | Sunday.\n\nInductive Month_of_the_Year : Set :=\nJanuary | February | March\n| April | May | June\n| July | August | September\n| October | November | December.\n\nDefinition Day_after (d : Day_of_the_Week) :=\n    match d\n    with Monday => Tuesday\n    | Tuesday => Wednesday\n    | Wednesday => Thursday\n    | Thursday => Friday\n    | Friday => Saturday\n    | Saturday => Sunday\n    | Sunday => Monday\n    end.\n\nFail Definition Day_before (d : Day_of_the_Week) :=\n    match d\n    with Monday => Sunday\n    | Tuesday => Monday\n    | Wednesday => Tuesday\n    | Thursday => Wednesday\n    | Saturday => Friday\n    | Sunday => Saturday\n    end.\n\n(* The command has indeed failed with message:\n   Non exhaustive pattern-matching: no clause found for pattern\n   Friday *)\n\nDefinition Day_before (d : Day_of_the_Week) :=\n    match d\n    with Monday => Sunday\n    | Tuesday => Monday\n    | Wednesday => Tuesday\n    | Thursday => Wednesday\n    | Friday => Thursday\n    | Saturday => Friday\n    | Sunday => Saturday\n    end.\n\nTheorem Two_days_after :\n    eq (Wednesday) (Day_after (Day_after (Monday))).\nProof.\n    assert (P1 := eq_refl : eq (Tuesday) (Day_after (Monday))).\n    assert (P2 := eq_refl : eq (Wednesday) (Day_after (Tuesday))).\n    rewrite P1 in P2.\n    exact P2.\nQed.\n\nTheorem Two_days_after_2 :\n    eq (Wednesday) (Day_after (Day_after (Monday))).\nProof.\n    assert (P2 := eq_refl : eq (Wednesday) (Day_after (Day_after (Monday)))).\n    exact P2.\nQed.\n\nTheorem Two_days_after_3 :\n    eq (Wednesday) (Day_after (Day_after (Monday))).\nProof.\n    exact (eq_refl : eq (Wednesday) (Day_after (Day_after (Monday)))).\nQed.\n\n\n\nTheorem After_inverse_of_before\n    (d : Day_of_the_Week)\n    : Day_after (Day_before d) = d.\nProof.\n    assert (D_A_D_B_Monday := eq_refl : eq (Day_after (Day_before (Monday))) (Monday)).\n    assert (D_A_D_B_Tuesday := eq_refl : eq (Day_after (Day_before (Tuesday))) (Tuesday)).\n    assert (D_A_D_B_Wednesday := eq_refl : eq (Day_after (Day_before (Wednesday))) (Wednesday)).\n    assert (D_A_D_B_Thursday := eq_refl : eq (Day_after (Day_before (Thursday))) (Thursday)).\n    assert (D_A_D_B_Friday := eq_refl : eq (Day_after (Day_before (Friday))) (Friday)).\n    assert (D_A_D_B_Saturday := eq_refl : eq (Day_after (Day_before (Saturday))) (Saturday)).\n    assert (D_A_D_B_Sunday := eq_refl : eq (Day_after (Day_before (Sunday))) (Sunday)).\n    destruct d.\n    { exact D_A_D_B_Monday. }\n    { exact D_A_D_B_Tuesday. }\n    { exact D_A_D_B_Wednesday. }\n    { exact D_A_D_B_Thursday. }\n    { exact D_A_D_B_Friday. }\n    { exact D_A_D_B_Saturday. }\n    { exact D_A_D_B_Sunday. }\nQed.\n\n\n\nTheorem Day_must_be_MTWTFSS :\nforall d : Day_of_the_Week,\nor (eq d Monday) (or (eq d Tuesday)\n(or (eq d Wednesday) (or (eq d Thursday)\n(or (eq d Friday) (or (eq d Saturday)\n(eq d Sunday)))))).\n\nProof.\n\nintro d.\n\ndestruct d.\n\nassert (A1 := eq_refl : eq Monday Monday).\n\nassert (A2 := or_introl A1 : or\n (eq Monday Monday)\n (or (eq Monday Tuesday)\n (or (eq Monday Wednesday)\n (or (eq Monday Thursday)\n (or (eq Monday Friday)\n (or (eq Monday Saturday)\n (eq Monday Sunday))))))).\n\nexact A2.\n\nassert (B1 := eq_refl : eq Tuesday Tuesday).\n\nassert (B2 := or_introl B1 : or\n  (eq Tuesday Tuesday)\n  (or (eq Tuesday Wednesday)\n  (or (eq Tuesday Thursday)\n  (or (eq Tuesday Friday)\n  (or (eq Tuesday Saturday)\n  (eq Tuesday Sunday)))))).\n\nassert (B3 := or_intror B2 : or\n  (eq Tuesday Monday)\n  (or (eq Tuesday Tuesday)\n  (or (eq Tuesday Wednesday)\n  (or (eq Tuesday Thursday)\n  (or (eq Tuesday Friday)\n  (or (eq Tuesday Saturday)\n  (eq Tuesday Sunday))))))).\n\nexact B3.\n\nassert (C1 := eq_refl : eq Wednesday Wednesday).\n\nassert (C2 := or_introl C1 :\n  or (eq Wednesday Wednesday)\n  (or (eq Wednesday Thursday)\n  (or (eq Wednesday Friday)\n  (or (eq Wednesday Saturday)\n  (eq Wednesday Sunday))))).\n\nassert (C3 := or_intror C2 :\n  or (eq Wednesday Tuesday)\n  (or (eq Wednesday Wednesday)\n  (or (eq Wednesday Thursday)\n  (or (eq Wednesday Friday)\n  (or (eq Wednesday Saturday)\n  (eq Wednesday Sunday)))))).\n\nassert (C4 := or_intror C3 :\n  or (eq Wednesday Monday)\n  (or (eq Wednesday Tuesday)\n  (or (eq Wednesday Wednesday)\n  (or (eq Wednesday Thursday)\n  (or (eq Wednesday Friday)\n  (or (eq Wednesday Saturday)\n  (eq Wednesday Sunday))))))).\n\nexact C4.\n\nassert (D1 := eq_refl : eq Thursday Thursday).\n\nassert (D2 := or_introl D1 :\n  or (eq Thursday Thursday)\n  (or (eq Thursday Friday)\n  (or (eq Thursday Saturday)\n  (eq Thursday Sunday)))).\n\nassert (D3 := or_intror D2 :\n  or (eq Thursday Wednesday)\n  (or (eq Thursday Thursday)\n  (or (eq Thursday Friday)\n  (or (eq Thursday Saturday)\n  (eq Thursday Sunday))))).\n\nassert (D4 := or_intror D3 :\n  or (eq Thursday Tuesday)\n  (or (eq Thursday Wednesday)\n  (or (eq Thursday Thursday)\n  (or (eq Thursday Friday)\n  (or (eq Thursday Saturday)\n  (eq Thursday Sunday)))))).\n\nassert (D5 := or_intror D4 :\n  or (eq Thursday Monday)\n  (or (eq Thursday Tuesday)\n  (or (eq Thursday Wednesday)\n  (or (eq Thursday Thursday)\n  (or (eq Thursday Friday)\n  (or (eq Thursday Saturday)\n  (eq Thursday Sunday))))))).\n\nexact D5.\n\nassert (E1 := eq_refl : eq Friday Friday).\n\nassert (E2 := or_introl E1 :\n  or (eq Friday Friday)\n  (or (eq Friday Saturday)\n  (eq Friday Sunday))).\n\nassert (E3 := or_intror E2 :\n  or (eq Friday Thursday)\n  (or (eq Friday Friday)\n  (or (eq Friday Saturday)\n  (eq Friday Sunday)))).\n\nassert (E4 := or_intror E3 :\n  or (eq Friday Wednesday)\n  (or (eq Friday Thursday)\n  (or (eq Friday Friday)\n  (or (eq Friday Saturday)\n  (eq Friday Sunday))))).\n\nassert (E5 := or_intror E4 :\n  or (eq Friday Tuesday)\n  (or (eq Friday Wednesday)\n  (or (eq Friday Thursday)\n  (or (eq Friday Friday)\n  (or (eq Friday Saturday)\n  (eq Friday Sunday)))))).\n\nassert (E6 := or_intror E5 :\n  or (eq Friday Monday)\n  (or (eq Friday Tuesday)\n  (or (eq Friday Wednesday)\n  (or (eq Friday Thursday)\n  (or (eq Friday Friday)\n  (or (eq Friday Saturday)\n  (eq Friday Sunday))))))).\n\nexact E6.\n\nassert (F1 := eq_refl : eq Saturday Saturday).\n\nassert (F2 := or_introl F1 :\n  or (eq Saturday Saturday)\n  (eq Saturday Sunday)).\n\nassert (F3 := or_intror F2 :\n  or (eq Saturday Friday)\n  (or (eq Saturday Saturday)\n  (eq Saturday Sunday))).\n\nassert (F4 := or_intror F3 :\n  or (eq Saturday Thursday)\n  (or (eq Saturday Friday)\n  (or (eq Saturday Saturday)\n  (eq Saturday Sunday)))).\n\nassert (F5 := or_intror F4 :\n  or (eq Saturday Wednesday)\n  (or (eq Saturday Thursday)\n  (or (eq Saturday Friday)\n  (or (eq Saturday Saturday)\n  (eq Saturday Sunday))))).\n\nassert (F6 := or_intror F5 :\n  or (eq Saturday Tuesday)\n  (or (eq Saturday Wednesday)\n  (or (eq Saturday Thursday)\n  (or (eq Saturday Friday)\n  (or (eq Saturday Saturday)\n  (eq Saturday Sunday)))))).\n\nassert (F7 := or_intror F6 :\n  or (eq Saturday Monday)\n  (or (eq Saturday Tuesday)\n  (or (eq Saturday Wednesday)\n  (or (eq Saturday Thursday)\n  (or (eq Saturday Friday)\n  (or (eq Saturday Saturday)\n  (eq Saturday Sunday))))))).\n\nexact F7.\n\nassert (G1 := eq_refl : eq Sunday Sunday).\n\nassert (G2 := or_intror G1 :\n  or (eq Sunday Saturday)\n  (eq Sunday Sunday)).\n\nassert (G3 := or_intror G2 :\n  or (eq Sunday Friday)\n  (or (eq Sunday Saturday)\n  (eq Sunday Sunday))).\n\nassert (G4 := or_intror G3 :\n  or (eq Sunday Thursday)\n  (or (eq Sunday Friday)\n  (or (eq Sunday Saturday)\n  (eq Sunday Sunday)))).\n\nassert (G5 := or_intror G4 :\n  or (eq Sunday Wednesday)\n  (or (eq Sunday Thursday)\n  (or (eq Sunday Friday)\n  (or (eq Sunday Saturday)\n  (eq Sunday Sunday))))).\n\nassert (G6 := or_intror G5 :\n  or (eq Sunday Tuesday)\n  (or (eq Sunday Wednesday)\n  (or (eq Sunday Thursday)\n  (or (eq Sunday Friday)\n  (or (eq Sunday Saturday)\n  (eq Sunday Sunday)))))).\n\nassert (G7 := or_intror G6 :\n  or (eq Sunday Monday)\n  (or (eq Sunday Tuesday)\n  (or (eq Sunday Wednesday)\n  (or (eq Sunday Thursday)\n  (or (eq Sunday Friday)\n  (or (eq Sunday Saturday)\n  (eq Sunday Sunday))))))).\n\nexact G7.\n\nQed.\n\nEnd Four.", "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/Articles/Article_4_Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7581770768550014}}
{"text": "Set Implicit Arguments.\n\nRequire Export Coq.Init.Ltac.\nRequire Export Init.Notations.\n\n(* Truth *)\nInductive True: Prop :=\n  | tt: True.\n\nInductive False: Prop :=.\n\nNotation \"⊤\" := True.\nNotation \"⊥\" := False.\n\n(* Implication *)\nNotation \"A → B\" := (forall (_: A), B).\n\n(* Negation *)\nDefinition not (A: Prop) := A → ⊥.\n\nNotation \"~ x\" := (not x).\n\n(* Conjunction *)\nInductive and (A B: Prop): Prop :=\n  | conj: A → B → and A B.\n\nNotation \"A ∧ B\" := (and A B).\n\n(* Disjunction *)\nInductive or (A B: Prop): Prop :=\n  | inl: A → or A B\n  | inr: B → or A B.\n\nNotation \"A ∨ B\" := (or A B).\n\n(* If and Only If *)\nNotation \"A ↔ B\" := ((A → B) ∧ (B → A)).\n\n(* Basic Properties of Logic *)\nSection Logic.\n  Variable P Q R S : Prop.\n  \n  Lemma bot_e: ⊥ → P.\n  Proof.\n    intros [].\n  Qed.\n\n  Lemma explo_: Q → ~Q → P.\n  Proof.\n    intros P1 P2.\n    apply bot_e.\n    apply (P2 P1).\n  Qed.\n\n  Lemma and_i: P → Q → P ∧ Q.\n  Proof.\n    intros P1 P2.\n    apply (conj P1 P2).\n  Qed.\n\n  Lemma and_el: P ∧ Q → P.\n  Proof.\n    intros [P1 _].\n    apply P1.\n  Qed.\n\n  Lemma and_er: P ∧ Q → Q.\n  Proof.\n    intros [_ P1].\n    apply P1.\n  Qed.\n\n  Lemma and_s: P ∧ Q → Q ∧ P.\n  Proof.\n    intros [P1 P2].\n    apply (conj P2 P1).\n  Qed.\n\n  Lemma and_t: P ∧ Q → Q ∧ R → P ∧ R.\n  Proof.\n    intros [P1 _] [_ P2].\n    apply (conj P1 P2).\n  Qed.\n\n  Lemma and_reorder: P ∧ Q → R ∧ S → P ∧ R.\n  Proof.\n    intros [P1 _] [P2 _].\n    apply (conj P1 P2).\n  Qed.\n\n  Lemma or_il: P → P ∨ Q.\n  Proof.\n    intros P1.\n    apply (inl _ P1).\n  Qed.\n\n  Lemma or_ir: Q → P ∨ Q.\n  Proof.\n    intros P1.\n    apply (inr _ P1).\n  Qed.\n\n  Lemma or_s: P ∨ Q → Q ∨ P.\n  Proof.\n    intros [P1 | P1].\n    + apply (inr _ P1).\n    + apply (inl _ P1).\n  Qed.\n\n  Lemma imp_r: P → P.\n  Proof.\n    intros P1.\n    apply P1.\n  Qed.\n\n  Lemma imp_t: (P → Q) → (Q → R) → P → R.\n  Proof.\n    intros P1 P2 P3.\n    apply (P2 (P1 P3)).\n  Qed.\n\n  Lemma imp_i: ~P ∨ Q → (P → Q).\n  Proof.\n    intros [P1 | P1].\n    + intros P2.\n      destruct (P1 P2).\n    + intros _.\n      apply P1.\n  Qed.\n\n  (* imp_e in Classical *)\n  \n  Lemma iff_r: P ↔ P.\n  Proof.\n    split.\n    + apply imp_r.\n    + apply imp_r.\n  Qed.\n  \n  Lemma iff_s: (P ↔ Q) → (Q ↔ P).\n  Proof.\n    intros [P1 P2].\n    apply (conj P2 P1).\n  Qed.\n\n  Lemma iff_t: (P ↔ Q) → (Q ↔ R) → (P ↔ R).\n  Proof.\n    intros [P1 P2] [P3 P4].\n    split.\n    + intros P5.\n      apply (P3 (P1 P5)).\n    + intros P5.\n      apply (P2 (P4 P5)).\n  Qed.\nEnd Logic.\n(*----------------------------------------------------------------------------*)\n\n(* Set *)\nParameter J    : Prop.\nParameter J_in : J → J → Prop.\n\nNotation \"x ∈ y\" := (J_in x y).\nNotation \"x ∉ y\" := (~(x ∈ y)).\n\n(* Equality *)\nInductive eq: J → J → Prop :=\n  | refl: forall x: J, eq x x.\n\nNotation \"x = y\" := (eq x y).\nNotation \"x ≠ y\" := (~(x = y)).\n\n(* Basic Properties of Equality *)\nSection Equality.\n  Variable A B C: J.\n  \n  Theorem eq_r : A = A.\n  Proof.\n    apply refl.\n  Qed.\n  \n  Theorem eq_s : A = B → B = A.\n  Proof.\n    intros [x].\n    apply refl.\n  Qed.\n\n  Theorem eq_t : A = B → B = C → A = C.\n  Proof.\n    intros [_] [x].\n    apply refl.\n  Qed.\n\n  Theorem eq_cl : forall P : J → Prop, A = B → P A → P B.\n  Proof.\n    intros P [x] H1.\n    apply H1.\n  Qed.\n\n  Theorem eq_cr : forall P : J → Prop, A = B → P B → P A.\n  Proof.\n    intros P [x] H1.\n    apply H1.\n  Qed.\n\n  Theorem eq_w : forall P : J → J, A = B → P A = P B.\n  Proof.\n    intros P [x].\n    apply refl.\n  Qed.\n\n  Lemma neq_s: A ≠ B → B ≠ A.\n  Proof.\n    intros P1 P2.\n    destruct P2.\n    apply P1.\n    apply refl.\n  Qed.\nEnd Equality.\n(*----------------------------------------------------------------------------*)\n\n(* Quantifier *)\nInductive ex (P: J → Prop): Prop :=\n  | ex_i: forall x: J, P x → ex P.\n\n(*Notation \"'exists' x , p\" := (ex (fun x => p)) (at level 200, right associativity).*)\nNotation \"∃   A , P\" := (ex (fun A => P)).\nNotation \"∀   A , P\" := (forall A: J, P).\nNotation \"∀ₚ  A , P\" := (forall A: (J → Prop), P).\nNotation \"∀ₚₚ A , P\" := (forall A: (J → J → Prop), P).\nNotation \"'λ' x , P\" := (fun x => P).\n\nSection Exist.\n  Variable (P : J → Prop).\n\n  Definition ex_outl (x : ex P) : J :=\n    match x with \n      | ex_i _ a _ => a\n    end.\n\n  Definition ex_outr (x : ex P) : P (ex_outl x) :=\n    match x with\n      | ex_i _ _ a => a\n    end.\nEnd Exist.\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7581770763219953}}
{"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\nExample test1_negb : (negb true) = false.\nProof. simpl. reflexivity. Qed.\nExample test2_negb : (negb false) = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb (b1 b2:bool) :=\n  match b1 with\n    | true => b2\n    | false => false\n  end.\n\nExample test1_andb : (andb true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test2_andb : (andb true false) = false.\nProof. simpl. reflexivity. Qed.\nExample test3_andb : (andb false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test4_andb : (andb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition orb (b1 b2 :bool) : bool :=\n  match b1 with\n    | true => true\n    | false => b2\n  end.\n\nExample test1_orb : (orb true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test2_orb : (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test3_orb : (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test4_odb : (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n\n(* Excercise 1, nandb *)\nDefinition nandb (b1 b2:bool) :=\n  match b1 with\n    | true => b2\n    | false => negb(b2)\n  end.\n\nExample test1_nandb: (nandb true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test2_nandb: (nandb true false) = false.\nProof. simpl. reflexivity. Qed.\nExample test3_nandb: (nandb false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test4_nandb: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\n\n\n(* Excercise 2, andb3 *)\nDefinition andb3 (b1 b2 b3:bool) : bool :=\n  match b1 with\n    | true => andb b2 b3\n    | false => false\n  end.\n\n\nExample test1_andb3: (andb3 true true true) = true.\nProof.  reflexivity. Qed.\nExample test2_andb3: (andb3 false true true) = false.\nProof. reflexivity. Qed.\nExample test3_andb3: (andb3 true false true) = false.\nProof. reflexivity. Qed.\nExample test4_andb3: (andb3 true true false) = false.\nProof. reflexivity. Qed.\n\nNotation \"x || y\" := (orb x y).\nCheck true || false.\n\nEval simpl in (pred 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\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 0))))) = false.\nProof. simpl. reflexivity. Qed.\n\nModule playground2.\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\nEval compute in (plus (S (S (S 0))) (S 0)).\n\nFixpoint minus (n m:nat): nat :=\n  match n, m with\n    | 0, _ => 0\n    | S _, 0 => n\n    | S n', S m' => minus n' m'\n  end.\n\nExample test_minus1: (minus 4 3) = 1.\nProof. simpl. reflexivity. Qed.\nExample test_minus2: (minus 3 3) = 0.\nProof. simpl. reflexivity. Qed.\nExample test_minus3: (minus 1 4) = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint mult (n m: nat): nat :=\n  match n with\n    | O => 0\n    | S n' => plus m (mult n' m)\n  end.\n\nExample test_mult1: (mult 3 4) = 12.\nProof. simpl. reflexivity. Qed.\n\nEnd playground2.\n\nFixpoint exp (base power: nat) :nat :=\n  match power with\n    | 0 => S(O)\n    | S n' => mult base (exp base n')\n  end.\n\nEval simpl in (exp 3 3).\n\nFixpoint factorial (n :nat) :nat :=\n  match n with\n    | O => S O\n    | S O => S O\n    | S m => mult n (factorial m)\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\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\nExample beq_nat1: (beq_nat 3 4) = false.\nProof. reflexivity. Qed.\nExample beq_nat2: (beq_nat 3 3) = true.\nProof. reflexivity. Qed.\nExample beq_nat3: (beq_nat 0 1) = false.\nProof. reflexivity. Qed.\nExample beq_nat4: (beq_nat 0 0) = true.\nProof. reflexivity. Qed.\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\n\nExample ble_nat1: (ble_nat 4 4) = true.\nProof. simpl. reflexivity. Qed.\nExample ble_nat2: (ble_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\nEval simpl in (minus 2 4).\nExample ble_nat3: (ble_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\n\n\nDefinition blt_nat (n m :nat) : bool :=\n  match (minus m n) with\n    | S n' => true\n    | O => false\n  end.\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\n\nTheorem plus_0_n : forall n:nat, 0 + n = n.\nProof.\n  compute. reflexivity. Qed.\n\n\nEval simpl in (forall n:nat, n + 0 = n).\nEval simpl in (forall n:nat, 0 + n = n).\n\n(* 2. tjedan *)\n\nTheorem plus_0_n'' : forall n:nat, 0 + n = n.\nProof.\n  intros. reflexivity. Qed.\n\nTheorem mult_0_n' : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_1_n' : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example: forall n m:nat,\n  n = m -> n + m = m + n.\nProof.\n  intros n m H.\n  rewrite <- H.\n  reflexivity. Qed.\n\nTheorem plus_id_excercise: 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. 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  simpl.\n  reflexivity. Qed.\n\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. Qed.\n\nTheorem plus_1_neq_0: forall n: nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n.\n  reflexivity.\n  compute.\n  reflexivity. Qed.\n\nTheorem negb_involutive: forall b:bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  compute.\n  reflexivity.\n  reflexivity. Qed.\n\nTheorem zero_nbeq_plus : forall n:nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  reflexivity.\n  reflexivity. Qed.\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. reflexivity. Qed.\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. Qed.\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  intros n.\n  induction n.\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn.\n    reflexivity. Qed.\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros. induction n.\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n\".\n    simpl. rewrite -> IHn. reflexivity. Qed.\n\nTheorem plus_n_Sm : forall n m : nat, \n  S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n.\n  Case \"n = 0\".\n    simpl.\n    reflexivity.\n  Case \"n = S n\".\n    simpl. rewrite -> IHn. reflexivity. Qed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  simpl. rewrite -> plus_0_r.\n  reflexivity.\n\n  simpl. rewrite -> IHn.\n  rewrite -> plus_n_Sm.\n  reflexivity. Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n.\n  induction n.\n  simpl. reflexivity.\n  simpl. rewrite -> IHn.\n  rewrite -> plus_n_Sm.\n  reflexivity. Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  intros n m p. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\nTheorem beq_nat_refl: forall n: nat,\n  true = beq_nat n n .\nProof.\n  intro n.\n  induction n.\n  (* base: n = 0 *)\n  reflexivity.\n  (* suppose n = S n where true = beq_nat n n *)\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\nQed.\n\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n    Case \"Proof of assertion\". 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  (* 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! *)\nAdmitted.\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    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  simpl.\n  rewrite -> plus_assoc.\n  assert (H: m + n = n + m).\n    rewrite -> plus_comm. reflexivity.\n  rewrite -> plus_assoc.\n  rewrite -> H. reflexivity.\nQed.\n\nTheorem mult_n_Sm : forall n m : nat, n * S m = n + n * m.\n  Proof.\n    intros n m.\n    induction n.\n    reflexivity.\n    simpl.\n    rewrite -> IHn.\n    rewrite plus_swap.\n    reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n m * n = n * m.\nProof.\n  intros m n.\n  simpl.\n  induction n.\n    induction m.\n      reflexivity.\n      simpl. rewrite -> IHm. reflexivity.\n  simpl. rewrite -> mult_n_Sm. rewrite -> IHn. reflexivity.\nQed.\n\n\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof.\n  intros n.\n  induction n.\n  reflexivity.\n  simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n.\n  simpl. reflexivity.\nQed.\n\nTheorem plus_swap' : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  replace (n + m) with (m + n).\n  reflexivity.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\n", "meta": {"author": "nhenezi", "repo": "coq-sf", "sha": "bfe419c04eb4f8508a1caad282aa2be7bae8c116", "save_path": "github-repos/coq/nhenezi-coq-sf", "path": "github-repos/coq/nhenezi-coq-sf/coq-sf-bfe419c04eb4f8508a1caad282aa2be7bae8c116/numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7580890624602935}}
{"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 Proj1SigInjective.\nRequire Import EnsemblesSpec.\n\nUnset Standard Proposition Elimination Names.\n\nSection WellOrder.\n\n(* this definition is for the strict order, e.g. the element relation for ordinals of ZFC *)\n\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_compatT.\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_compatT.\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_compatT.\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_compatT.\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": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/zorn/WellOrders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7580444313928926}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Psatz. \nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Maps.\n\nModule AExp.\n\n  Inductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\n  Inductive 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\n  Fixpoint aeval (a : aexp) : nat :=\n    match a with\n    | ANum n => n\n    | APlus e1 e2 => aeval e1 + aeval e2\n    | AMinus e1 e2 => aeval e1 - aeval e2\n    | AMult e1 e2 => aeval e1 * aeval e2\n    end.\n\n\n  Fixpoint beval (b : bexp) : bool :=\n    match b with\n    | BTrue => true\n    | BFalse => false\n    | BEq a1 a2 => beq_nat (aeval a1) (aeval a2)\n    | BLe a1 a2 => leb (aeval a1) (aeval a2)\n    | BNot b1 => negb (beval b1)\n    | BAnd b1 b2 => andb (beval b1) (beval b2)\n    end.\n\n  Fixpoint optimize_0plus (a:aexp) : aexp :=\n    match a with\n    | ANum n =>\n           ANum n\n    | APlus (ANum 0) e2 =>\n            optimize_0plus e2\n    | APlus e1 e2 =>\n            APlus (optimize_0plus e1) (optimize_0plus e2)\n    | AMinus e1 e2 =>\n             AMinus (optimize_0plus e1) (optimize_0plus e2)\n    | AMult e1 e2 =>\n            AMult (optimize_0plus e1) (optimize_0plus e2)\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  cbn. auto. Qed.\n\n\n  Theorem optimize_0plus_sound: forall a,\n      aeval (optimize_0plus a) = aeval a.\n  Proof.\n    induction a;\n      try (cbn; rewrite IHa1; rewrite IHa2; auto).\n    + auto.\n    + cbn. destruct a1;\n             try (rewrite <- IHa1; rewrite <- IHa2; auto).\n      ++ destruct n; try auto.\n  Qed.\n\n  \n  \n\n  Module aevalR_first_try.\n\n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum n : aevalR (ANum n) n\n    | E_APlus e1 e2 n1 n2 :\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    Notation \"e '\\\\' n\"\n      := (aevalR e n)\n           (at level 50, left associativity)\n         : type_scope.\n    \n  End aevalR_first_try.\n\n  Reserved Notation \"e '\\\\' n\" (at level 50, left associativity).\n\n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum n : (ANum n) \\\\ n\n  | E_APlus e1 e2 n1 n2 :\n      e1 \\\\ n1 -> e2 \\\\ n2 ->  (APlus e1 e2) \\\\ (n1 + n2)\n  | E_AMinus (e1 e2: aexp) (n1 n2: nat) : \n      e1 \\\\ n1 -> e2 \\\\ n2 -> (AMinus e1 e2) \\\\ (n1 - n2)\n  | E_AMult (e1 e2: aexp) (n1 n2: nat) :\n      e1 \\\\ n1 -> e2 \\\\ n2 -> (AMult e1 e2) \\\\ (n1 * n2)\n  where \"e '\\\\' n\" := (aevalR e n) : type_scope.\n\n  Theorem aeval_iff_aevalR : forall a n,\n      (a \\\\ n) <-> aeval a = n.\n  Proof.\n    split. \n    + revert n.\n      induction a; cbn; intros; inversion H; subst; clear H; try auto.\n    + revert n. induction a; cbn; intros; subst; constructor;\n                  try (eapply IHa1); try (eapply IHa2); auto.\n  Qed.\n\n  Inductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : bevalR BTrue true\n  | E_BFalse : bevalR BFalse false\n  | E_BEq a1 a2 n1 n2 : aevalR a1 n1 -> aevalR a2 n2 -> bevalR (BEq a1 a2) (n1 =? n2)\n  | E_BLe a1 a2 n1 n2 : aevalR a1 n1 -> aevalR a2 n2 -> bevalR (BLe a1 a2) (n1 <=? n2)\n  | E_BNot b1 v1 : bevalR b1 v1 -> bevalR (BNot b1) (negb v1)\n  | E_BAnd b1 b2 v1 v2 : bevalR b1 v1 -> bevalR b2 v2 -> bevalR (BAnd b1 b2) (andb v1 v2).\n\n\n  \n\n  Lemma beval_iff_bevalR : forall b bv,\n      bevalR b bv <-> beval b = bv.\n  Proof.\n    split.\n    + intros H. induction H; cbn; try auto.\n      pose proof (aeval_iff_aevalR a1 n1).\n      pose proof (aeval_iff_aevalR a2 n2).\n      apply H1 in H. apply H2 in H0; subst; auto.\n\n      pose proof (aeval_iff_aevalR a1 n1).\n      pose proof (aeval_iff_aevalR a2 n2).\n      apply H1 in H. apply H2 in H0; subst; auto.\n\n      subst. auto.\n      subst; auto.\n\n\n    + generalize dependent bv.\n      induction b; cbn; intros; subst.\n      eapply E_BTrue.\n      eapply E_BFalse.\n      eapply E_BEq; eapply  aeval_iff_aevalR; auto.\n      eapply E_BLe; eapply  aeval_iff_aevalR; auto.\n      eapply E_BNot; eapply IHb; auto.\n      eapply E_BAnd; [eapply IHb1 | eapply IHb2]; auto.\n  Qed.\n\n  Module aevalR_division.\n\n    Inductive aexp : Type :=\n    | ANum : nat -> aexp\n    | APlus : aexp -> aexp -> aexp\n    | AMinus : aexp -> aexp -> aexp\n    | AMult : aexp -> aexp -> aexp\n    | ADiv : aexp -> aexp -> aexp.\n\n    \n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum n : (ANum n) \\\\ n\n    | E_APlus e1 e2 n1 n2 :\n        e1 \\\\ n1 -> e2 \\\\ n2 ->  (APlus e1 e2) \\\\ (n1 + n2)\n    | E_AMinus (e1 e2: aexp) (n1 n2: nat) : \n        e1 \\\\ n1 -> e2 \\\\ n2 -> (AMinus e1 e2) \\\\ (n1 - n2)\n    | E_AMult (e1 e2: aexp) (n1 n2: nat) :\n        e1 \\\\ n1 -> e2 \\\\ n2 -> (AMult e1 e2) \\\\ (n1 * n2)\n    | E_ADiv e1 e2 n1 n2 n3 :\n        e1 \\\\ n1 -> e2 \\\\ n2 -> (n2 > 0) ->\n        (mult n1 n2 = n3) -> (ADiv e1 e2) \\\\ n3\n    where \"e '\\\\' n\" := (aevalR e n) : type_scope.\n\n  End aevalR_division.\n  Module aevalR_extended.\n\n    Inductive aexp : Type :=\n    | AAny : aexp\n    | ANum : nat -> aexp\n    | APlus : aexp -> aexp -> aexp\n    | AMinus : aexp -> aexp -> aexp\n    | AMult : aexp -> aexp -> aexp.\n\n    Reserved Notation \"e '\\\\' n\" (at level 50, left associativity).\n\n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_AAny n : AAny \\\\ n\n    | E_ANum n : (ANum n) \\\\ n\n    | E_APlus e1 e2 n1 n2 :\n        e1 \\\\ n1 -> e2 \\\\ n2 ->  (APlus e1 e2) \\\\ (n1 + n2)\n    | E_AMinus (e1 e2: aexp) (n1 n2: nat) : \n        e1 \\\\ n1 -> e2 \\\\ n2 -> (AMinus e1 e2) \\\\ (n1 - n2)\n    | E_AMult (e1 e2: aexp) (n1 n2: nat) :\n        e1 \\\\ n1 -> e2 \\\\ n2 -> (AMult e1 e2) \\\\ (n1 * n2)\n    where \"e '\\\\' n\" := (aevalR e n) : type_scope.\n\n  End aevalR_extended.\n\nEnd AExp.\n\nModule AState.\n  Definition state := total_map nat.\n\n  Print total_map.\n  \n  Inductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : string -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\n  Definition W : string := \"W\".\n  Definition X : string := \"X\".\n  Definition Y : string := \"Y\".\n  Definition Z : string := \"Z\".\n\n  \n  Inductive 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\n\n  Coercion AId : string >-> aexp.\n  Coercion ANum : nat >-> aexp.\n  Definition bool_to_bexp (b: bool) : bexp :=\n    if b then BTrue else BFalse.\n  Coercion bool_to_bexp : bool >-> bexp.\n  Bind Scope aexp_scope with aexp.\n  Infix \"+\" := APlus : aexp_scope.\n  Infix \"-\" := AMinus : aexp_scope.\n  Infix \"*\" := AMult : aexp_scope.\n  Bind Scope bexp_scope with bexp.\n  Infix \"<=\" := BLe : bexp_scope.\n  Infix \"=\" := BEq : bexp_scope.\n  Infix \"&&\" := BAnd : bexp_scope.\n  Notation \"'!' b\" := (BNot b) (at level 60) : bexp_scope.\n\n  Fixpoint aeval (st : state) (a : aexp) : nat :=\n    match a with\n    | ANum n => n\n    | AId x => st x\n    | APlus e1 e2 => aeval st e1 + aeval st e2\n    | AMinus e1 e2 => aeval st e1 - aeval st e2\n    | AMult e1 e2 => aeval st e1 * aeval st e2\n    end.\n\n    Fixpoint beval (st : state) (b : bexp) : bool :=\n    match b with\n    | BTrue => true\n    | BFalse => false\n    | BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)\n    | BLe a1 a2 => leb (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\n    Notation \"{ a --> x }\" :=\n      (t_update { --> 0 } a x) (at level 0).\n    Notation \"{ a --> x ; b --> y }\" :=\n      (t_update ({ a --> x }) b y) (at level 0).\n    Notation \"{ a --> x ; b --> y ; c --> z }\" :=\n      (t_update ({ a --> x ; b --> y }) c z) (at level 0).\n    Notation \"{ a --> x ; b --> y ; c --> z ; d --> t }\" :=\n      (t_update ({ a --> x ; b --> y ; c --> z }) d t) (at level 0).\n    Notation \"{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }\" :=\n      (t_update ({ a --> x ; b --> y ; c --> z ; d --> t }) e u) (at level 0).\n    Notation \"{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u ; f --> v }\" :=\n      (t_update ({ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }) f v) (at level 0).\n    Example aexp1 :\n      aeval { X --> 5 } (3 + (X * 2))\n      = 13.\n    cbn. auto.\n  Qed.\n\n  Example bexp1 :\n    beval { X --> 5 } (true && !(X <= 4))\n    = true.\n  cbn. auto. Qed.\n\n\n  Inductive 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\n  Bind Scope com_scope with com.\n  Notation \"'SKIP'\" :=\n    CSkip : com_scope.\n  Notation \"x '::=' a\" :=\n    (CAss x a) (at level 60) : com_scope.\n  Notation \"c1 ;; c2\" :=\n    (CSeq c1 c2) (at level 80, right associativity) : com_scope.\n  Notation \"'WHILE' b 'DO' c 'END'\" :=\n    (CWhile b c) (at level 80, right associativity) : com_scope.\n  Notation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n    (CIf c1 c2 c3) (at level 80, right associativity) : com_scope.\n\n  Open Scope com_scope.\n\n  Definition fact_in_coq : com :=\n    Z ::= X;;\n    Y ::= 1;;\n    WHILE ! (Z = 0) DO\n         Y ::= Y * Z;;\n         Z ::= Z - 1\n    END.\n\n  Definition plus2 : com :=\n    X ::= X + 2.\n  Definition XtimesYinZ : com :=\n    Z ::= X * Y.\n  Definition subtract_slowly_body : com :=\n    Z ::= Z - 1 ;;\n    X ::= X - 1.\n\n\n  Definition subtract_slowly : com :=\n  WHILE ! (X = 0) DO\n    subtract_slowly_body\n    END.\n\n  Definition subtract_3_from_5_slowly : com :=\n    X ::= 3 ;;\n    Z ::= 5 ;;\n    subtract_slowly.\n\n  Definition loop : com :=\n  WHILE true DO\n    SKIP\n  END.\n\n  Check t_update. \n Fixpoint ceval_fun_no_while (st : state) (c : com)\n                          : state :=\n  match c with\n    | SKIP =>\n        st\n    | x ::= a1 =>\n        st & { x --> (aeval st a1) }\n    | c1 ;; c2 =>\n        let st' := ceval_fun_no_while st c1 in\n        ceval_fun_no_while st' c2\n    | IFB b THEN c1 ELSE c2 FI =>\n        if (beval st b)\n          then ceval_fun_no_while st c1\n          else ceval_fun_no_while st c2\n    | WHILE b DO c END =>\n        st (* bogus *)\n  end.\n\n Reserved Notation \"c1 '/' st '\\\\' st'\"\n          (at level 40, st at level 39).\n Inductive ceval : com -> state -> state -> Prop :=\n | E_Skip st : SKIP / st \\\\ st\n | E_Ass st a1 n x :\n     aeval st a1 = n -> (x ::= a1) / st \\\\ st & {x --> n}\n | E_Seq c1 c2 st st' st'' :\n     c1 / st \\\\ st' -> c2 / st' \\\\ st'' -> (c1 ;; c2) / st \\\\ st''\n | E_IfTrue st st' b c1 c2 :\n     beval st b = true ->\n     c1 / st \\\\ st' ->\n     (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n | E_IfFalse st st' b c1 c2 :\n     beval st b = false ->\n     c2 / st \\\\ st' -> \n     (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n | E_WhileFalse b st c :\n     beval st b = false ->\n     (WHILE b DO c END) / st \\\\ st\n | E_WhileTrue b st st' st'' c :\n     beval st b = true ->\n     c / st \\\\ st' ->\n     (WHILE b DO c END) / st' \\\\ st'' ->\n     (WHILE b DO c END) / st \\\\ st''\n                    \n where \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\n\n Example ceval_example1:\n   (X ::= 2;;\n     IFB X <= 1\n       THEN Y ::= 3\n       ELSE Z ::= 4\n     FI)\n   / { --> 0 } \\\\ { X --> 2 ; Z --> 4 }.\n Proof.\n   apply E_Seq with { X --> 2 }.\n   - apply E_Ass; auto.\n   - apply E_IfFalse; auto.\n     apply E_Ass; auto.\n Qed.\n\n\n Example ceval_example2:\n  (X ::= 0;; Y ::= 1;; Z ::= 2) / { --> 0 } \\\\\n  { X --> 0 ; Y --> 1 ; Z --> 2 }.\n Proof.\n   eapply E_Seq. eapply E_Ass. cbn. instantiate (1 := 0). auto.\n   eapply E_Seq; eapply E_Ass. cbn. auto.\n   cbn. auto.\n Qed.\n\n\n Definition pup_to_n : com :=\n   Y ::= 0;;\n   WHILE ! (X = 0) DO\n      Y ::= Y + X;;\n      X ::= X - 1\n   END.                   \n\n\n Theorem pup_to_2_ceval :\n   pup_to_n / { X --> 2 }\n            \\\\ { X --> 2 ; Y --> 0 ; Y --> 2 ; X --> 1 ; Y --> 3 ; X --> 0 }.\n Proof.\n   unfold pup_to_n.\n   eapply E_Seq. eapply E_Ass. cbn. instantiate (1 := 0). auto.\n   eapply E_WhileTrue; auto.\n   eapply E_Seq; eapply E_Ass; cbn. instantiate (1 := 2). auto.\n   instantiate (1 := 1). auto.\n   eapply E_WhileTrue; auto.\n   eapply E_Seq; eapply E_Ass. cbn. instantiate (1 := 3); auto.\n   cbn. instantiate (1 := 0); auto.\n   eapply E_WhileFalse; cbn; auto.\n Qed.\n\n\n\n Theorem ceval_deterministic: forall c st st1 st2,\n     c / st \\\\ st1 ->\n     c / st \\\\ st2 ->\n     st1 = st2.\n   (* proof by induction on c *)\n Proof.\n   intros  c st st1 st2 E1 E2.\n   generalize dependent st2.\n   induction E1; intros st2 E2; inversion E2; subst; clear E2.\n   + auto.\n   + auto.\n   + pose proof (IHE1_1 _ H1). subst. \n     pose proof (IHE1_2 _ H4). auto.\n   + pose proof (IHE1 _ H6). auto.\n   + rewrite H in H5. inversion H5.\n   + rewrite H in H5. inversion H5.\n   + pose proof (IHE1 _ H6). auto.\n   + auto.\n   + rewrite H in H2.  inversion H2.\n   + rewrite H in H4.  inversion H4.\n   + assert (st' = st'0). pose proof (IHE1_1 _ H3). auto.\n     subst st'. pose proof (IHE1_2 _ H6). auto.\n Qed.\n \n      \nEnd AState.\n", "meta": {"author": "mukeshtiwari", "repo": "Coq-reading-group", "sha": "3801ef7e534bb00590a062e905a330c7727b4bdd", "save_path": "github-repos/coq/mukeshtiwari-Coq-reading-group", "path": "github-repos/coq/mukeshtiwari-Coq-reading-group/Coq-reading-group-3801ef7e534bb00590a062e905a330c7727b4bdd/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7580444174420676}}
{"text": "Require Import BA.Basics.\nModule NatList.\n\nInductive natprod: Type:=\n  |pair: nat -> nat -> natprod.\n\n\nDefinition fst (s:natprod): nat:=\n    match s with \n     | pair n _ => n\n    end.\n\nCheck (pair 5 6).\nCompute (fst (pair 4 3)).\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | pair x y => y\n  end.\n\nCheck (pair 5 6).\nCompute (fst (pair 4 3)).\n\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(* Exercise: 1 star (snd_fst_is_swap)*)\n\n Theorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros p. destruct p as [n m]. simpl. reflexivity. Qed.\n\n\n(*Exercise: 1 star, optional (fst_swap_is_snd)*)\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]. simpl. reflexivity. Qed.\n\n\n(* inductive definition of a list *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(* a more  suitble Notation*)\n\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\n\nFixpoint repeat (n count: nat): natlist:=\n      match count with\n        | O => []\n        | S n' => n: repeat n n'\n      end.   \n\n\nFixpoint length (xs : natlist): nat :=\n      match xs with\n       | [] => 0\n       | (x:ys) => 1 + length ys\n     end.\n\nCompute (length [1,2,3,4,5]).\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 \" xs ++ ys \" := (app xs ys).\nFixpoint nonzeros (l:natlist) : natlist :=\n    match l with\n      | [] => []\n      | (x:xs) => match x with\n                    |O => nonzeros xs\n                    |S n => S n : nonzeros xs\n                  end\n   end.\n  \n\nExample test_nonzeros:\n  nonzeros [0,1,0,2,3,0,0] = [1,2,3].\n  reflexivity. Qed.\n\n\nFixpoint oddmembers (l:natlist) : natlist :=\n    match l with\n      | [] => []\n      |x:xs => match (evenb x) with\n               |true => oddmembers xs\n               |false => x:oddmembers xs\n               end\n    end.\n\nExample test_oddmembers:\n  oddmembers [0,1,0,2,3,0,0] = [1,3].\n  reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n   length(oddmembers l).\n  \n\nExample test_countoddmembers1:\n  countoddmembers [1,0,3,1,4,5] = 4.\n   reflexivity. Qed.\n\nExample test_countoddmembers2:\n  countoddmembers [0,2,4] = 0.\n   reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n   reflexivity. Qed.\n\n (* \nExercise: 3 stars, advanced (alternate)*)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n     match l1  with\n       |  [] => l2\n       | (x:xs) => match l2 with\n                    | [] =>( x:xs)\n                    | (y:ys) => x: (y: alternate xs ys)\n                    end\n    end.\n \n\nExample test_alternate1:\n  alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\n reflexivity. Qed.\n\nCompute (alternate [1,3,5,7] [2,4,6]).\n\nExample test_alternate2:\n  alternate [1] [4,5,6] = [1,4,5,6].\n  reflexivity. Qed.\n\nExample test_alternate3:\n  alternate [1,2,3] [4] = [1,4,2,3].\n  reflexivity. Qed.\n\nExample test_alternate4:\n  alternate [] [20,30] = [20,30].\n  reflexivity. Qed.\n\nDefinition bag:= natlist.\n\n\n\nFixpoint count (v:nat) (s:bag) : nat:=\n    match s with\n     | [] => 0\n     |(x:xs) => match (beq_nat x v) with\n                | true => 1+ count v xs\n                | false => count v xs\n               end\n    end.\n\nCompute (count 1 [1,2,3,1,4,1]).\nExample test_count1: count 1 [1,2,3,1,4,1] = 3.\n reflexivity. Qed.\nExample test_count2: count 6 [1,2,3,1,4,1] = 0.\n reflexivity. Qed.\n\n\nDefinition sum : bag -> bag -> bag :=\n    app.\n\n\nExample test_sum1: count 1 (sum [1,2,3] [1,4,1]) = 3.\nsimpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag :=\n   app (v:[]) s.\n  \n\nExample test_add1: count 1 (add 1 [1,4,1]) = 3.\n simpl. reflexivity. Qed.\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nsimpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n     match (count v (sum []  s)) with\n       |O => false\n       | _ => true\n     end.\n \n\nExample test_member1: member 1 [1,4,1] = true.\nsimpl. reflexivity. Qed. \n\nExample test_member2: member 2 [1,4,1] = false.\nsimpl. reflexivity. Qed.\n\n(*proof some properteies over list *)\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    reflexivity.\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\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(*---OPTIONS--*)\n\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a : l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4,5,6,7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4,5,6,7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4,5,6,7] 9 = None.\nProof. reflexivity. Qed.\n\n\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\n(*Exercise: 2 stars (hd_error) *)\n\n\n\nDefinition hd_error (l : natlist) : natoption:=\n   match l with \n    | [] => None\n    | (x:xs) => Some  x\n   end.\n\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 (* Haskell -> Coq\n\n  indexOf :: Int -> [Int] -> Maybe Int\nindexOf _ []                 = Nothing\nindexOf x (y:ys) | x == y    = Just 0\n                 | otherwise = case indexOf x ys of\n                                 Nothing -> Nothing\n                                 Just i  -> Just (i + 1)   *)\n\nFixpoint indexOf (n:nat) (xs:natlist): natoption :=\n     match xs with\n      | [] => None\n      | (y:ys) => match (beq_nat y n) with\n                    | true => Some 0\n                    |false => match (indexOf n ys) with\n                                | None => None\n                                | Some n => Some (S n)\n                              end\n                  end\n    end.\n\nExample indexOf1: (indexOf 3 [1,2,3]) = Some 2.\nProof. reflexivity. Qed.\n\nEnd NatList.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Tsatia", "repo": "Coq_Basics", "sha": "e787476f8e0cef8576f8efd3546ceb01f908fb62", "save_path": "github-repos/coq/Tsatia-Coq_Basics", "path": "github-repos/coq/Tsatia-Coq_Basics/Coq_Basics-e787476f8e0cef8576f8efd3546ceb01f908fb62/src/NatList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.8918110440002045, "lm_q1q2_score": 0.758013695090208}}
{"text": "Require Import Omega.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFrom q3_2001 Require Export ceil.\nFrom q3_2001 Require Export misc.\nFrom q3_2001 Require Export nat_list_sum.\n\n(* TODO Fold instead of Fixpoint ? *)\nFixpoint largest_elt {X : Type} (l : list X) (size : X -> nat) : option X :=\n  match l with\n  | [] => None\n  | x::l' => match largest_elt l' size with\n             | None => Some x\n             | Some y => if size x <=? size y then Some y else Some x\n             end\n  end.\n\nLemma largest_elt_spec_1 : forall {X : Type} (l : list X) (size : X -> nat),\n  (exists y, largest_elt l size = Some y) <-> l <> [].\nProof. (* TODO Prove largest_elt_2 directly and get this via option_spec *)\n  destruct l; split; intros.\n  - destruct H as [y Hy]. simpl in Hy. inversion Hy.\n  - contradiction.\n  - intros Hl. inversion Hl.\n  - destruct (largest_elt l size) eqn:Hl; simpl; rewrite -> Hl.\n    + destruct (size x <=? size x0).\n      * exists x0. reflexivity.\n      * exists x. reflexivity.\n    + exists x. reflexivity.\nQed.\n\nLemma largest_elt_spec_2 : forall {X : Type} (l : list X) (size : X -> nat),\n  largest_elt l size = None <-> l = [].\nProof.\n  intros. destruct (list_empty_dec l) as [Hl|Hl]; subst.\n  - simpl. split; reflexivity.\n  - assert (Hl' : exists y : X, largest_elt l size = Some y). { apply largest_elt_spec_1. assumption. }\n    destruct Hl' as [y Hy]. rewrite -> Hy. split; intros H.\n    + inversion H.\n    + contradiction.\nQed.\n\nLemma largest_elt_spec_3 : forall {X : Type} (l : list X) (size : X -> nat) (y : X),\n  largest_elt l size = Some y -> In y l.\nProof.\n  induction l as [| x l IHl]; intros.\n  - inversion H.\n  - destruct (largest_elt l size) eqn:Hl; simpl in H; rewrite -> Hl in H.\n    + apply IHl in Hl. destruct (size x <=? size x0).\n      * right. inversion H. subst. assumption.\n      * left. inversion H. reflexivity.\n    + inversion H. left. reflexivity.\nQed.\n\nLemma largest_elt_spec_4 : forall {X : Type} (l : list X) (size : X -> nat) (y z : X),\n  largest_elt l size = Some y -> In z l -> size z <= size y.\nProof.\n  induction l as [| x l IHl]; intros size y z H_largest H_in.\n  - intros. inversion H_in.\n  - destruct H_in; subst.\n    + destruct (largest_elt l size) eqn:Hl. simpl in H_largest; rewrite -> Hl in H_largest.\n      * destruct (Nat.leb_spec0 (size z) (size x)) as [Hx|Hx]; inversion H_largest; subst.\n        -- assumption.\n        -- apply le_n.\n      * simpl in H_largest. rewrite -> Hl in H_largest. inversion H_largest. apply le_n.\n    + destruct (largest_elt l size) eqn:Hl. simpl in H_largest; rewrite -> Hl in H_largest.\n      destruct (Nat.leb_spec0 (size x) (size x0)) as [Hx|Hx]; inversion H_largest; subst.\n      * apply IHl; assumption.\n      * apply (le_trans (size z) (size x0) (size y)).\n        -- apply IHl; assumption.\n        -- omega.\n      * apply largest_elt_spec_2 in Hl. subst. inversion H.\nQed.\n\nLemma largest_elt_spec_5 : forall {X : Type} (l : list X) (size : X -> nat) (y : X),\n  largest_elt l size = Some y -> nat_list_sum (map size l) <= (length l) * (size y).\nProof.\n  intros. assert (H_len : length (map size l) = length l). { apply map_length. } rewrite <- H_len.\n  apply nat_list_sum_bound. intros m H_in. rewrite in_map_iff in H_in. destruct H_in as [x [Hx Hx_in]]. subst.\n  apply (largest_elt_spec_4 l); assumption.\nQed.\n\nLemma largest_elt_spec_6 : forall {X : Type} (l : list X) (size : X -> nat) (x y z : X),\n  largest_elt l size = Some y -> largest_elt (x::l) size = Some z -> size y <= size z.\nProof.\n  intros X l size x y z Hy Hz. simpl in Hz. rewrite -> Hy in Hz.\n  destruct (Nat.leb_spec0 (size x) (size y)) as [Hxy|Hxy]; inversion Hz; subst; omega.\nQed.\n\nLemma largest_elt_spec_7 : forall {X : Type} (l : list X) (size : X -> nat) (y : X),\n  let N' := nat_list_sum (map size l) in\n    largest_elt l size = Some y -> ceil N' (length l) <= size y.\nProof.\n  destruct l as [| s l']; intros size y N' H.\n  - simpl. apply Nat.le_0_l.\n  - destruct (list_empty_dec l') as [Hl' | Hl']; subst.\n    + unfold length. rewrite ceil_spec_2. unfold N'. simpl. simpl in H. rewrite Nat.add_0_r. inversion H. subst. apply le_n.\n    + assert (Hlenl' : length l' <> 0). { rewrite length_zero_iff_nil. assumption. }\n      rewrite <- (largest_elt_spec_1 l' size) in Hl'. destruct Hl' as [y' Hl'].\n      rewrite ceil_spec_0.\n      * assert (H1 : size s <= size y). {\n          apply (largest_elt_spec_4 (s::l')).\n          - assumption.\n          - left. reflexivity. }\n        assert (H2 : nat_list_sum (map size l') <= (length l') * (size y')). {\n          apply largest_elt_spec_5. assumption. }\n        assert (H3 : (length l') * (size y') <= (length l') * (size y)). {\n          apply mult_le_compat_l.\n          apply (largest_elt_spec_6 l' size s y' y); assumption. }\n        unfold N'. simpl. omega.\n      * simpl. intros contra. inversion contra.\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/largest_elt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7580136868939562}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 4 stars (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    {{ 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    Fill in the blanks in following decorated program:\n    {{ X = m }} ->>\n    {{ 1 * X! = m! }}\n  Y ::= 1;;\n    {{ Y * X! = m! }}\n  WHILE X <> 0\n  DO   {{ Y * X! = m! /\\ X <> 0  }} ->>\n       {{ (Y*X) * (X-1)! = m! }}\n     Y ::= Y * X;;\n       {{ Y * (X-1)! = m! }}\n     X ::= X - 1\n       {{ Y * X! = m! }}\n  END\n    {{ Y * X! = m! /\\ X = 0  }} ->>\n    {{ Y = m! }}\n*)\n\nPrint fact.\n\nLemma fact_mult : forall m,\n  m <> 0 -> m * fact (m - 1) = fact m.\nProof.\n  intros. induction m.\n  - exfalso. unfold not in H. apply H. reflexivity.\n  - simpl. rewrite <- minus_n_O. reflexivity.\nQed.\n\nTheorem factorial_correct: forall m,\n  {{ fun st => st X = m }} \n  Y ::= ANum 1 ;;\n  WHILE BNot (BEq (AId X) (ANum 0))\n  DO\n     Y ::= AMult (AId Y) (AId X) ;;\n     X ::= AMinus (AId X) (ANum 1)\n  END\n  {{ fun st => st Y = fact m }}.\nProof.\n  intros. eapply hoare_consequence.\n  - eapply hoare_seq with (Q := fun st => (st Y * fact (st X)) = fact m).\n    + eapply hoare_while. eapply hoare_consequence_pre.\n      * eapply hoare_seq.\n        ++ apply hoare_asgn.\n        ++ apply hoare_asgn.\n      * unfold bassn, assert_implies, assn_sub, t_update. simpl. intros st [H1 H2].\n        apply negb_true_iff in H2. apply beq_nat_false in H2. apply fact_mult in H2.\n        rewrite mult_assoc_reverse. rewrite H2. assumption.\n    + apply hoare_asgn.\n  - unfold assn_sub, t_update. intros st H. subst. simpl. omega. \n  - unfold bassn; simpl; intros st [H1 H2].\n    apply eq_true_negb_classical in H2.\n    apply Nat.eqb_eq in H2.\n    rewrite H2 in H1. simpl in H1. omega.\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/09/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.75801367861662}}
{"text": "Add LoadPath \"bezier-functions\".\n\nRequire Import polynomial.\nImport auxiliary.\nRequire Import QArith.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.RelationClasses.\n\nTheorem bezier_curve_fst_order_interpolation_polynomial : forall (P0 P1 : point) (q : Q), \n  calc_bezier_polynomial (P0 :: [P1]) q == (((1 - q) qp* P0) pp+ (q qp* P1)).\nProof.\n  intros P0 P1 q.\n  unfold calc_bezier_polynomial. unfold calc_polynomial. simpl.\n  unfold calc_fact_div. simpl. unfold minus_1_sgn. simpl. unfold inject_Z.\n  Search (_ qp* _). try rewrite qp_1_l.\n  destruct P0 as [x0 y0]. destruct P1 as [x1 y1]. unfold \"==\". split.\n  - simpl. ring.\n  - simpl. ring. \nQed.\n\nTheorem bezier_curve_fst_order_interpolation_polynomial_rev : forall (P0 P1 : point) (q : Q), \n  calc_bezier_polynomial (rev (P0 :: [P1])) (1 - q) == (((1 - q) qp* P0) pp+ (q qp* P1)).\nProof.\n  intros P0 P1 q.\n  unfold calc_bezier_polynomial. unfold calc_polynomial. simpl.\n  unfold calc_fact_div. simpl. unfold minus_1_sgn. simpl. unfold inject_Z.\n  Search (_ qp* _). try rewrite qp_1_l.\n  destruct P0 as [x0 y0]. destruct P1 as [x1 y1]. unfold \"==\". split.\n  - simpl. ring.\n  - simpl. ring. \nQed.", "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_interpolation/fst_order_interpolation_polynomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.757994114847067}}
{"text": "Require Import NPeano.\nRequire Import Coq.Program.Wf.\nRequire Import Recdef.\n\n\n(** *Even length*)\nInductive even : nat -> Prop :=\n| EvenO : even 0\n| EvenS : forall n, even n -> even (S (S n)). \n\nFunction length_of_even (ls:list nat) : option nat :=\n  match ls with\n  | nil => Some 0\n  | cons x1 (cons x2 ls') =>\n    match length_of_even ls' with\n    | Some n' => Some ( 2 + n')\n    | _ => None\n    end\n  | cons x nil => None \n  end.\n\nLemma LOE_correct:\n  forall ls n,\n    length_of_even ls = Some n ->\n    even (length ls).\nProof.\n  intros.\n  induction ls;\n    try constructor; simpl.\n  simpl in H.\n  destruct ls; try solve[inversion H].\n  simpl; constructor. \n\n  Restart.\n  \n  intros ls.\n  functional induction (length_of_even ls).\n  - constructor. \n  - simpl; constructor.\n    eapply IHo; eassumption.\n  - intros ? HH; inversion HH.\n  - intros ? HH; inversion HH.\nQed.\n\n\n(** * Perm_of_sh *)\nRequire Import VST.veric.juicy_mem.\nRequire Import compcert.common.Memory.\n\nPrint perm_of_sh.\nLemma perm_of_sh_readable:\n  forall sh P,\n    shares.readable_share_dec sh = left P ->\n    Mem.perm_order'' (perm_of_sh sh) (Some Readable).\nProof.\n  intros.\n  unfold perm_of_sh.\n  destruct (shares.writable_share_dec sh).\n  Restart.\n  \n  Functional Scheme perm_of_sh_ind := Induction for perm_of_sh Sort Prop.\n\n  intros.\n  functional induction (perm_of_sh sh);\n    try congruence; (* Discard the impossible cases *)\n    try solve[constructor]. (* Discard the rest of the cases *)\nQed.\n\n\n\n(** * Merge *)\n\n\nDefinition double_measure (lss: list nat * list nat):= (length (fst lss) + length (snd lss)).\n\nFunction merge (lss: list nat * list nat)\n         {measure double_measure}:=\n  match lss with\n    | (ls1, ls2) =>\n  match ls1 with\n    nil => ls2\n  | cons n ls1' =>\n    match ls2 with\n      nil => ls1\n    | cons m ls2' =>\n      if n <? m then\n        cons n (merge (ls1', ls2))\n      else\n        cons m (merge (ls1, ls2'))\n    end\n  end\n    end.\n- intros; simpl.\n  unfold double_measure; simpl.\n  lia.\n- intros; simpl.\n  unfold double_measure; simpl.\n  lia.\nDefined.\n\nLemma merge_length: forall lss,\n    length (merge lss) = length (fst lss) + length (snd lss).\nProof.\n  intros.\n  \n  functional induction (merge lss);\n    auto; (*Trivial cases*)\n    simpl; f_equal.\n  - apply IHl.\n  - rewrite IHl; simpl; lia.\nQed.\n  \n\n(** *Mutual recursion*)\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\nFunction 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\nFunction 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\nFunctional Scheme eapp_mut := Induction for eapp Sort Prop\nwith oapp_mut := Induction for oapp Sort Prop.\n\nTheorem elength_eapp : forall el1 el2 : even_list,\n  elength (eapp el1 el2) = plus (elength el1) (elength el2).\nProof.\n  intros.\n  \n  functional induction (eapp el1 el2) using eapp_mut\n  with (P0:= (fun (ol: odd_list)( el : even_list)( ol': odd_list) =>\n         olength ol' = plus (olength ol) (elength el))).\n  - intros; reflexivity.\n  - intros. simpl; f_equal; apply IHe.\n  - intros. simpl; f_equal; apply IHe.\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\nRequire Import mathcomp.ssreflect.ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Test.\n\nVariable A : Type.\n\nTheorem counterexample P : (exists x : A, ~P x) -> ~(forall x, P x).\nProof.\nby case=>x H1 H2; apply: H1 (H2 x).\nQed.\n\nPrint counterexample.\n\nEnd Test.\n\n\nRequire Import List.\nFixpoint add_list l:=\n  match l with\n    | nil => 0\n    | h::tl => h + (add_list tl)\n  end.\n\n\n\nInductive subseq {A: Type}: list A -> list A -> Prop :=\n  | nil_subseq : subseq nil nil\n  | hd_subseq: forall a l1 l2, subseq l1 l2 -> subseq (a :: l1) (a :: l2)\n  | tl_subseq: forall a l1 l2, subseq l1 l2 -> subseq l1 (a :: l2)\n  .\n\nInductive subseq' {A: Type}: list A -> list A -> Prop :=\n  | nilss : forall l, subseq' nil l\n  | hdss: forall a l l1 l2, subseq' l l2 -> subseq' (a :: l) (l1 ++ a :: l2)\n  .\n\nTheorem ssss: forall A (l1 l2: list A), subseq l1 l2 <-> subseq' l1 l2.\nsplit.\n+ intros H; induction H; try constructor.\n  replace (a::l2) with (nil ++ a::l2) by auto; constructor; auto.\n  replace (cons a l2) with (app (cons a nil) l2) by auto. \n  inversion IHsubseq. constructor. rewrite app_assoc. constructor.\n  auto.\n+ intros. induction H.\n  induction l; constructor; auto.\n  induction l1.\n  simpl; constructor; auto.\n  simpl. \n  constructor; auto.\nQed.\n\nLemma subseq_trans: forall {A} (l1 l2 l3: list A), subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof. \nintros A l1 l2 l3 H H0. \ngeneralize dependent l3. induction H.\nintros. \n+ inversion H0; constructor. exact H.\n+ intros. \n  induction l3. inversion H0.\n  constructor. apply IHl3.\n  \n\napply ssss; apply ssss in H; apply ssss in H0.\ngeneralize dependent l3.\ninduction H.\n+ constructor.\n+ \n\ninduction l1; intros l3 H0; inversion H0.\n  -  constructor; apply IHsubseq'; exact H4.\n  - subst. apply IHl1. \n    inversion H4. destruct l1; inversion H2.\n    replace (l4 ++ a0 :: l3 ++ a1 :: l6) with ((l4 ++ a0 :: l3) ++ a1 :: l6 ).\n    constructor. exact H2.\n    rewrite app_comm_cons.\n    rewrite app_assoc. reflexivity.\nQed.\n\n\n+ constructor.\n+ inversion H. subst l2. inversion H0.\n  - destruct l0; simpl in H5; inversion H5.\n  - clear H6. destruct l0; inversion H5.\n    * subst. simpl in *. inversion H2. subst; inversion H4.\n       \n      constructor.\n    \n\nconstructor.\nsubst l3; auto.\n  -  auto.\n  \n\n\nrevert l3.\ninduction H; intros l3 H0.\n+ admit.\n+ inversion H0.\n  - constructor.\n    apply IHsubseq; auto.\n  - constructor. apply \n\n\nInductive foo: Type :=\n   bar: foo -> foo.\n\nTheorem blah: forall (x: foo), False.\n  Proof. \n    \n    \n\nLemma and_or: forall (a b: bool),\n             a = b ->\n             andb a b = orb a b.\nProof.\ndestruct a; intros b H.\n+ destruct b.\n  - reflexivity.\n  - inversion H.\n+ destruct b.\n  - inversion H.\n  - reflexivity.\nQed.\n\nLemma blah: forall x, x=O -> ~ exists y, x = S y .\nintros x H H0; destruct x.\n+ destruct H0; inversion H0.\n+ inversion H.\nQed.\n\nLemma zero_no_succ: forall n, O<>S n.\nunfold not; intros n H.\n\nDefinition Is_S (n:nat) := match n with (*This is a hint!!!*)\n                            | O => False\n                            | S p => True\n                            end.\nLemma Zero_not_Succ: forall n:nat, 0 <> S n.\n\tunfold not; intros n H.\n        assert (HH: Is_S O = False) by reflexivity.\n        rewrite <- HH.\n        rewrite H. simpl.\n\nInductive bin:=\n   OO: bin\n  | SS: bin -> bin\n  | TT: bin -> bin.\n\nTheorem bin_to_nat_pres_incr : forall b : bin,\n  bin_to_nat (incr b) = plus (bin_to_nat b) 1.\n\nLemma blah': forall x, x=0 -> \n\nunfold not in H.\n\n\nRequire Import ssreflect.\n\nRequire Import ssrbool.\nRequire Import ssrnat.\nRequire Import ssrfun.\n\nRequire Import eqtype.\nRequire Import seq.\nRequire Import fintype.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/try.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8688267626522814, "lm_q1q2_score": 0.7579187541000376}}
{"text": "From VFA Require Import Perm.\n\n\nFixpoint insert (v: nat) (l: list nat): list nat :=\n  match l with\n  | [] => [v]\n  | h :: t => if v <=? h\n              then v :: l\n              else h :: (insert v t)\n  end.\n\n\nFixpoint sort (l: list nat): list nat :=\n  match l with\n  | [] => []\n  | h :: t => insert h (sort t)\n  end.\n\nCompute (sort [5; 4; 7; 0; 1; 2; 3; 1; 8; 9]).\n\n\nExample sort_pi: 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.\n  simpl. reflexivity.\nQed.\n\n\nEval compute in insert 7 [1; 3; 4; 8; 12; 14; 18].\n\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\nCheck length.\nCheck nth.\n\nDefinition sorted' (l: list nat): Prop :=\n  forall i j, i < j < (length l) -> (nth i l 0) <= (nth j l 0).\n\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat): Prop :=\n  forall l, Permutation l (f l) /\\ sorted (f l).\n\n\n\nSearch Permutation.\n\nLemma insert_perm: forall x l, Permutation (x :: l) (insert x l).\nProof.\n  intros. induction l as [| h t IHl'].\n  - simpl. Check Permutation_refl. apply Permutation_refl.\n  - simpl. bdestruct (x <=? h).\n    + apply Permutation_refl.\n    + Check perm_swap. eapply perm_trans.\n      * apply perm_swap.\n      * Search (Permutation (_ :: _) (_ :: _)). apply perm_skip.\n        apply IHl'.\nQed.\n\n\n\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.  \n  intro. induction l as [| h t IHl'].\n  - simpl. Search (Permutation [] []). apply perm_nil.\n  - simpl. apply perm_trans with (l' := (h :: sort t)).\n    + apply perm_skip. apply IHl'.\n    + apply insert_perm.\nQed.\n\n\nLemma insert_sorted: forall a l,\n    sorted l -> sorted (insert a l).\nProof.\n  intros a l H. induction H.\n  - simpl. apply sorted_1.\n  - simpl. bdestruct (a <=? x);\n             apply sorted_cons; try omega; try apply sorted_1.\n  - simpl. bdestruct (a <=? x).\n    + apply sorted_cons;\n        try assumption; try apply sorted_cons; try assumption.\n    + simpl in IHsorted.\n      bdestruct (a <=? y);\n        apply sorted_cons; try omega; try assumption.\nQed.\n\n\n\nTheorem sort_sorted: forall l,\n    sorted (sort l).\nProof.\n  intro l. induction l as [| h t IHl'].\n  - simpl. apply sorted_nil.\n  - simpl. apply insert_sorted. apply IHl'.\nQed.\n\n\nTheorem insertion_sort_correct:\n  is_a_sorting_algorithm sort.\nProof.\n  unfold is_a_sorting_algorithm. intro l. split.\n  - apply sort_perm.\n  - apply sort_sorted.\nQed.\n", "meta": {"author": "jamshed", "repo": "Formal-Verification-of-Bubble-Sort", "sha": "3a213e17b5dd4e31cd3d76b596fc6a0e2fa1721e", "save_path": "github-repos/coq/jamshed-Formal-Verification-of-Bubble-Sort", "path": "github-repos/coq/jamshed-Formal-Verification-of-Bubble-Sort/Formal-Verification-of-Bubble-Sort-3a213e17b5dd4e31cd3d76b596fc6a0e2fa1721e/Sort_rep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7578562296712169}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\n\nLocal Open Scope morphism_scope.\n\nSection Equalizer.\n  Context {C : Category} {a b : Obj} (f g : a –≻ b).\n\n  (** given two parallel arrows f,g : a -> b, their equalizer is an object e together with an arrow eq : e -> a such that f ∘ eq = g ∘ eq such that for any other object z and eqz : z -> a that we have f ∘ eqz = g ∘ eqz, there is a unique arrow h : z -> e that makes the following fiagram commute:\n\n#\n<pre>\n\n          eqz\n/—————————————————\\     f\n|                 ↓  ———————>\nz ———–> e ——————> a          b\n   ∃!h      eq       ———–——–>\n                        g\n</pre>\n#\n *)\n\n  Local Open Scope morphism_scope.\n  \n  Record Equalizer : Type :=\n    {\n      equalizer : C;\n\n      equalizer_morph : equalizer –≻ a;\n\n      equalizer_morph_com : f ∘ equalizer_morph = g ∘ equalizer_morph;\n\n      equalizer_morph_ex (e' : Obj) (eqm : e' –≻ a) : f ∘ eqm = g ∘ eqm → e' –≻ equalizer;\n\n      equalizer_morph_ex_com (e' : Obj) (eqm : e' –≻ a) (eqmc : f ∘ eqm = g ∘ eqm) :\n        equalizer_morph ∘ (equalizer_morph_ex e' eqm eqmc) = eqm;\n\n      equalizer_morph_unique (e' : Obj) (eqm : e' –≻ a) (com : f ∘ eqm = g ∘ eqm) (u u' : e' –≻ equalizer) : equalizer_morph ∘ u = eqm → equalizer_morph ∘ u' = eqm → u = u'\n    }.\n\n  Coercion equalizer : Equalizer >-> Obj.\n  \n  (** Equalizers are unique up to isomorphism. *)\n  Theorem Equalizer_iso (e1 e2 : Equalizer) : (e1 ≃ e2)%isomorphism.\n  Proof.\n    apply (Build_Isomorphism _ _ _ (equalizer_morph_ex e2 _ (equalizer_morph e1) (equalizer_morph_com e1)) ((equalizer_morph_ex e1 _ (equalizer_morph e2) (equalizer_morph_com e2))));\n    eapply equalizer_morph_unique; [| | simpl_ids; trivial| | |simpl_ids; trivial]; try apply equalizer_morph_com;\n    rewrite <- assoc; repeat rewrite equalizer_morph_ex_com; auto.\n  Qed.\n\nEnd Equalizer.\n\nArguments equalizer_morph {_ _ _ _ _} _.\nArguments equalizer_morph_com {_ _ _ _ _} _.\nArguments equalizer_morph_ex {_ _ _ _ _} _ {_ _} _.\nArguments equalizer_morph_ex_com {_ _ _ _ _} _ {_ _} _.\nArguments equalizer_morph_unique {_ _ _ _ _} _ {_ _ _} _ _ _ _.\n\nArguments Equalizer _ {_ _} _ _, {_ _ _} _ _.\n\nDefinition Has_Equalizers (C : Category) : Type := ∀ (a b : C) (f g : a –≻ b), Equalizer f g.\n\nExisting Class Has_Equalizers.\n\n(** CoEqualizer is the dual of equalzier *)\nDefinition CoEqualizer {C : Category} := @Equalizer (C^op).\n\nArguments CoEqualizer _ {_ _} _ _, {_ _ _} _ _.\n\nDefinition Has_CoEqualizers (C : Category) : Type := Has_Equalizers (C^op).\n\nExisting Class Has_CoEqualizers.\n\n\n\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/Basic_Cons/Equalizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7577533489999282}}
{"text": "Inductive Var :=\n| x : Var\n| y : Var\n| n : Var\n| i : Var\n| sum : Var.\n\nFixpoint var_eq (v1 v2 : Var) :=\n  match v1, v2 with\n  | x, x => true\n  | y, y => true\n  | n, n => true\n  | i, i => true\n  | sum, sum => true\n  | _, _ => false\n  end.\n\nInductive AExp :=\n| anum : nat -> AExp\n| avar : Var -> AExp\n| aplus : AExp -> AExp -> AExp\n| amul : AExp -> AExp -> AExp.\n\n\nNotation \"A +' B\" := (aplus A B) (at level 50).\nNotation \"A *' B\" := (amul A B) (at level 46).\n\nCoercion anum : nat >-> AExp.\nCheck 5 +' 4 .\nCoercion avar : Var >-> AExp.\n\nDefinition State := Var -> nat.\n(* lookup:  *)\nDefinition sigma0 : State := fun n => 0.\nCheck sigma0.\nCompute (sigma0 x).\nCompute (sigma0 y).\n\n\n(* update *)\nDefinition update (sigma : State)\n           (v : Var) (val : nat) : State :=\n  fun v' => if (var_eq v v')\n            then val\n            else (sigma v').\nDefinition sigma1 := (update sigma0 x 10).\nCompute (sigma1 x).\n\nReserved Notation \"A -[ S ]-> N\" (at level 60).\n\nInductive aeval_small_step :\n  AExp -> State -> AExp -> Prop :=\n| aconst : forall n st, n -[ st ]-> n\n| alookup : forall v st, avar v -[ st ]-> (st v)\n| aadd_1 : forall a1 a2 a1' st n,\n    a1 -[ st ]-> a1' ->\n    n = a1' +' a2 ->\n    a1 +' a2 -[ st ]-> n\n| aadd_2 : forall a1 a2 a2' st n,\n    a2 -[ st ]-> a2' ->\n    n = a1 +' a2' ->\n    a1 +' a2 -[ st ]-> n\n| aadd : forall i1 i2 st,\n    (anum i1) +' (anum i2) -[ st ]-> i1 + i2\n| atimes_1 : forall a1 a2 a1' st n,\n    a1 -[ st ]-> a1' ->\n    n = a1' *' a2 ->\n    a1 *' a2 -[ st ]-> n\n| atimes_2 : forall a1 a2 a2' st n,\n    a2 -[ st ]-> a2' ->\n    n = a1 *' a2' ->\n    a1 *' a2 -[ st ]-> n\n| atimes : forall i1 i2 st,\n    (anum i1) *' (anum i2) -[ st ]-> i1 * i2\nwhere \"A -[ S ]-> N\" := (aeval_small_step A S N).\n\nCompute sigma1 x.\n\nExample e1 :\n  2 +' x -[ sigma1 ]-> 2 +' 10.\nProof.\n  apply aadd_2 with (a2' := 10); auto.\n  apply alookup.\nQed.\n\n\nReserved Notation \"A -[ S ]*> N\" (at level 60).\nInductive aeval_steps :\n  AExp -> State -> AExp -> Prop :=\n| refl : forall a st, a -[ st ]*> a\n| tran : forall a1 a2 a3 st,\n    a1 -[ st ]-> a2 ->\n    a2 -[ st ]*> a3 ->\n    a1 -[ st ]*> a3\nwhere \"A -[ S ]*> N\" := (aeval_steps A S N).\n\nExample e2 :\n  2 +' x -[ sigma1 ]*> 12.\nProof.\n  eapply tran.\n  - apply e1.\n  - eapply tran.\n    + Check aadd.\n      apply aadd.\n    + simpl.\n      apply refl.\nQed.\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/small_steps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7577533465269095}}
{"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.\n  rewrite /not.\n  exact. Undo 1.\n  by []. Undo 1.\n  by split; exact; exact. Undo 1.\n  split. exact. exact.\n\n  Restart.\n\n  rewrite /not.\n  split.\n  - apply. exact: I.\n  exact.\nQed.\n\nLemma dne_False : ~ ~ False -> False.\nProof.\n  rewrite /not.\n  apply. exact. Undo 2.\n  exact.\nQed.\n\nLemma dne_True : ~ ~ True -> True.\nProof.\n  rewrite /not.\n  by []. Undo 1.\n  exact. Undo 1.\n  by move=> //.\nQed.\n\nLemma weak_peirce : ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\n  move=> H1.\n  apply: (H1).\n  apply.\n  move=> a.\n  apply: H1.\n  by [].\nQed.\n\nLemma imp_trans : (A -> B) -> (B -> C) -> (A -> C).\nProof.\n  move=> H1 H2 a.\n  by apply H2; apply H1.\nQed.\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. by case b. Qed.\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.\n  rewrite /involutive. (* cancel negb negb *)\n  rewrite /cancel.     (* ~~ ~~ x0 = x0 *)\n  by case.\nQed.\n\nLemma negb_inj : injective negb.\nProof.\n  rewrite /injective.\n  by case; case.\nQed.\n\nLemma ifT : b -> (if b then vT else vF) = vT.\nProof. by case b. Qed.\n\nLemma ifF : b = false -> (if b then vT else vF) = vF.\nProof. by case b. Qed.\n\nLemma if_same : (if b then vT else vT) = vT.\nProof. by case b. Qed.\n\nLemma if_neg : (if ~~ b then vT else vF) = if b then vF else vT.\nProof. by case b. Qed.\n\nLemma fun_if : f (if b then vT else vF) = if b then f vT else f vF.\nProof. by case b. Qed.\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. by case b. Qed.\n\nLemma andbK : a && b || a = a.\nProof. by case a; case b. Qed.\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.\n(* [addb] means XOR (eXclusive OR operation) *)\nProof.\n  (* https://en.wikipedia.org/wiki/Identity_element *)\n\n  (* Левая \"единица\" (нейтральный элемент) *)\n  About  left_id. (* S -> (S -> T -> T)           *)\n  Print  left_id. (* op (e : S) (x : T) = (x : T) *)\n\n  (* Правая \"единица\" (нейтральный элемент) *)\n  About right_id. (* T -> (S -> T -> S)           *)\n  Print right_id. (* op (x : S) (e : T) = (x : T) *)\n\n  (* Search _ ( left_id _ _). *)\n  (* Search _ (right_id _ _). *)\n  rewrite /left_id.\n  move=> v. rewrite /addb. done.\n  Undo 2.\n  by [].\nQed.\n\nLemma addbF : right_id false addb.\nProof.\n  by case.\n  Undo.\n  rewrite /addb.\n  case.\n  - rewrite /negb. done.\n  - done.\nQed.\n\nLemma addbC : commutative addb.\nProof.\n  by case; case.\n  Undo.\n  (* Если есть желание посмотреть что происходит под капотом,\n     то можно прошагать вот эту дичь, которую я написал далее. *)\n  rewrite /commutative.\n  case. case.\n  - rewrite /addb. done.\n  - rewrite /addb. rewrite /negb. done.\n  - case. rewrite /addb. rewrite /negb. done.\n  - rewrite /addb. done.\nQed.\n\nLemma addbA : associative addb.\nProof.\n  rewrite /associative.\n  move=> m n k.\n  (* Я тут уже не буду расписывать так же как выше,\n     но тут происходит ровно тоже самое, только уже с 3 переменными. *)\n  Undo 2.\n  by case; case; case.\nQed.\n\n(** Formulate analogous laws\n    (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\nLemma orbF : right_id false orb.\nProof.\n  by case.\n  Undo.\n  (* Оставил просто для того,\n     чтобы пошагать и посмотреть что происходит *)\n  rewrite /right_id.\n  case.\n  - done.\n  - done.\nQed.\n\n(* Аналогично и всё остальное *)\n\nLemma orFb : left_id false orb. Proof. by case. Qed.\n\nLemma andbT : right_id true andb. Proof. by case. Qed.\nLemma andTB : left_id true andb. Proof. by case. Qed.\n\nLemma orbC : commutative orb. Proof. by case; case. Qed.\nLemma andbC : commutative andb. Proof. by case; case. Qed.\n\nLemma orbA : associative orb. Proof. by case; case; case. Qed.\nLemma andbA : associative andb. Proof. by case; case; case. Qed.\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.\n  About cancel.\n  About succn. Print succn. Print predn.\n  by [].\n  Undo.\n  rewrite /cancel.\n  done.\nQed.\n\nLemma add0n : left_id 0 addn.\nProof. by []. Qed.\n\nLemma addSn m n : m.+1 + n = (m + n).+1.\nProof. by []. Qed.\n\nLemma add1n n : 1 + n = n.+1.\nProof. by []. Qed.\n\nLemma add2n m : 2 + m = m.+2.\nProof. by []. Qed.\n\nLemma subn0 : right_id 0 subn.\nProof.\n  rewrite /right_id.\n  by case.\nQed.\n\nEnd NaturalNumbers.\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/hw02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.8757869884059266, "lm_q1q2_score": 0.7577519996636563}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Tactics.\nRequire Export Lists.\n\n\nCheck 3 = 3.\n\nCheck forall n m : nat, n + m = m + n.\n\nCheck 2 = 2.\n\nCheck forall n : nat, n = 2.\n\nCheck 3 = 4.\n\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof.\n  reflexivity.\nQed.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof.\n  reflexivity.\nQed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\n\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.\n  inversion H.\n  reflexivity.\nQed.\n\nCheck @eq.\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 A B HA 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\n(* Exercise: 2 stars (and_exercise) *)\nExample and_exercise_firsttry :\n  forall n m : nat,\n  n + m = 0 ->\n  n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  induction n, m.\n  - auto.\n  - auto.\n  - split.\n    + simpl in H. rewrite <- plus_n_O in H. apply H.\n    + auto.\n  - inversion H.\nQed.\n\nExample and_exercise :\n  forall n m : nat,\n  n + m = 0 ->\n  n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  induction n.\n  - auto.\n  - inversion H.\nQed.\n\n\nLemma and_example2 : forall n m : nat,\n  n = 0 /\\ m = 0 ->\n  n + m = 0.\nProof.\n  intros.\n  destruct H as [Hn Hm].\n  rewrite Hn. apply Hm.\nQed.\n\nLemma and_example2' : forall n m : nat,\n  n = 0 ->\n  m = 0 ->\n  n + m = 0.\nProof.\n  intros.\n  rewrite H. apply H0.\nQed.\n\nLemma and_example3 : forall n m : nat,\n  n + m = 0 ->\n  n * m = 0.\nProof.\n  intros.\n  assert (H' : n = 0 /\\ m = 0).\n  { induction n.\n    - auto.\n    - inversion H.\n  }\n  destruct H' as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.\nQed.\n\n\n(* Exercise: 1 star, optional (proj2) *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ.\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\n(* Exercise: 2 stars (and_assoc) *)\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\n\nLemma or_example : forall n m : nat,\n  n = 0 \\/ m = 0 ->\n  n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on \n    n = 0 \\/ m = 0 *)\n  intros n m [Hn | Hm].\n  - rewrite Hn. reflexivity.\n  - rewrite Hm. rewrite <- mult_n_O. reflexivity.\nQed.\n\n\nLemma or_intro : forall A B : Prop,\n  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  induction 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  generalize dependent n.\n  induction n.\n  - intros Hm. left. reflexivity.\n  - intros Hnm. induction m.\n    + right. reflexivity.\n    + left. inversion Hnm.\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\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nEnd MyNot.\n\nTheorem ex_falso_quadlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\n(* Exercise: 2 stars, optional (not_implies_our_not) *)\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 contra.\n  inversion contra.\nQed.\n\nCheck (0 <> 1).\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything: forall P Q : Prop,\n  (P /\\ ~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 HP.\n  unfold not.\n  intros G.\n  apply G.\n  apply HP.\nQed.\n\n(* Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q HPQ HQ HP.\n  unfold not in HQ.\n  apply HQ.\n  apply HPQ.\n  apply HP.\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 [HP HNP].\n  apply HNP.\n  apply HP.\nQed.\n\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - apply ex_falso_quadlibet. unfold not in H. 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\nLemma True_is_true : True.\nProof. apply I. Qed.\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 P Q [HP HQ].\n  unfold iff.\n  split.\n  - apply HQ.\n  - apply HP.\nQed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros.\n  unfold iff.\n  split.\n  - intros H. induction b. \n    + exfalso. apply H. reflexivity.\n    + reflexivity.\n  - intros H. induction b.\n    + inversion H.\n    + unfold not. intros H'. inversion H'.\nQed.\n\nLemma or_intro_2 : forall A B : Prop,\n  B -> A \\/ B.\nProof.\n  intros A B HB.\n  right.\n  apply HB.\nQed.\n\n(* Exercise: 3 stars (or_distributes_over_and) *)\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 [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. split.\n      { - apply HQ. }\n      { - apply HR. }\nQed.\n\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.RelationClasses.\n\nLemma mult_0 : forall n m, \n  n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc : forall P Q R : Prop,\n  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. rewrite mult_0. rewrite or_assoc. reflexivity.\nQed.\n\nLemma apply_iff_example : forall n m : nat,\n  n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  apply mult_0.\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 [m Hm].\n  exists (2 + m).\n  apply Hm.\nQed.\n\n(* Exercise: 1 star, recommend (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.\n  destruct H0.\n  apply H0.\n  apply H.\nQed.\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.\n  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\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. induction l.\n  - apply H.\n  - simpl. destruct H as [Hx | ].\n    + left. rewrite Hx. reflexivity.\n    + right. apply IHl. apply H.\nQed. \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. induction l.\n      { - inversion H. }\n      { - simpl. simpl in H. induction H as [Hx | E].\n          + exists (x). split.\n            * apply Hx.\n            * left. reflexivity.\n          + apply IHl in E. destruct E as [x' H1]. \n            exists (x'). split. \n            * apply H1.\n            * right. apply H1.\n       }\n   - intros [x H]. induction l.\n    + destruct H. apply H0. \n    + simpl. simpl in H. destruct H as [Hfx [Hx0 | Hxl]].\n      * left. rewrite <- Hx0 in Hfx. apply Hfx.\n      * right. apply IHl. split.\n        { - apply Hfx. }\n        { - apply Hxl. }\nQed.\n\nLemma app_r_nil : forall X (l : list X),\n  [] ++ l = l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. reflexivity.\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  - intros H. induction l.\n    + simpl in H. right. apply H.\n    + simpl in H. destruct H as [Hx | Ha].\n      * simpl. left. left. apply Hx.\n      * apply IHl in Ha. destruct Ha.\n        { - simpl. left. right. apply H. }\n        { - right. apply H. }\n  - intros H. induction l.\n    + simpl. destruct H.\n      * induction H.\n      * apply H.\n    + destruct H as [H1 | H2].\n      * simpl. simpl in H1. destruct H1.\n        { - left. apply H. }\n        { - right. apply IHl. left. apply H. }\n      * simpl. right. apply IHl. right. apply H2.\nQed.\n\n(* Exercise: 3 stars, recommended (All) *)\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  - intros H. induction l.\n    + simpl. apply I.\n    + simpl. split.\n      * apply H. simpl. left. reflexivity.\n      * apply IHl. intros. apply H. simpl. right. apply H0.\n  - intros. induction l.\n    + destruct H0.\n    + simpl in H. simpl in H0. \n      destruct H. destruct H0.\n        * rewrite H0 in H. apply H.\n        * apply IHl in H1.\n          { - apply H1. }\n          { - apply H0. }\nQed.\n\n(* Exercise: 3 stars (combine_odd_even) *)\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop\n  := fun (n : nat) =>\n      match (oddb n) with\n      | true => Podd n\n      | false => Peven n\n      end.\n\nLemma oddb_S : forall n,\n  oddb (S n) = negb (oddb n).\nProof.\n  intros. induction n.\n  - simpl. reflexivity.\n  - rewrite IHn. rewrite negb_involutive. reflexivity.\nQed.\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    exfalso.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\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  induction n.\n  - unfold combine_odd_even. simpl. apply H0. reflexivity.\n  - unfold combine_odd_even. destruct (oddb (S n)). \n      * apply H. reflexivity.\n      * apply H0. reflexivity. \nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  intros. unfold combine_odd_even in H. destruct (oddb n).\n  - apply H.\n  - inversion H0.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = false ->\n    Peven n.\nProof.\n  intros. unfold combine_odd_even in H. destruct (oddb n).\n  - inversion H0.\n  - apply H.\nQed.\n\nCheck plus_comm.\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros. rewrite plus_comm.\n  assert (H: y + z = z + y).\n  { - apply plus_comm. }\n  rewrite H. reflexivity.\nQed.\n\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros. \n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\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  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n          as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\nExample function_equality_ex1 : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\nAbort.\n\nAxiom function_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 function_extensionality. intros x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n\n(* Exercise: 4 stars (tr_rev_correct) *)\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\nCompute app [1;2;3] [4;5;6].\n\nCompute rev_append [1;2;3] [4;5;6].\n\nCompute tr_rev [1;2;3].\n\nLemma rev_append_aux : forall X (l1 l2 : list X),\n  rev_append l1 l2 = rev_append l1 [] ++ l2.\nProof.\n  induction l1.\n  - reflexivity.\n  - intros l2. simpl. \n    rewrite (IHl1 ([x])).\n    rewrite (IHl1 (x::l2)).\n    rewrite <- app_assoc. reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros.\n  apply function_extensionality. induction x.\n  - reflexivity.\n  - unfold tr_rev. simpl. rewrite rev_append_aux. unfold tr_rev in IHx. rewrite IHx. reflexivity.\nQed.\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros k.\n  induction k.\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  intros.\n  induction n.\n  - exists 0. reflexivity.\n  - rewrite evenb_S. destruct IHn.\n    destruct (evenb n).\n    + simpl. exists x. rewrite <- H. reflexivity.\n    + exists (S x). simpl. rewrite <- H. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n.\n  split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    exists k. rewrite H in Hk. apply Hk.\n  - intros [k Hk]. rewrite Hk. 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. split.\n  - intros H. apply beq_nat_true. apply H.  \n  - intros H. rewrite H. symmetry. apply beq_nat_refl.\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.\n  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\n(* Exercise: 2 stars (logical_connectives) *)\nLemma andb_true_iff : forall b1 b2 : bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  split.\n  - intros H. split.\n    + destruct b1.\n      * reflexivity.\n      * destruct H. unfold andb. reflexivity.\n    + destruct b2.\n      * reflexivity.\n      * destruct H. unfold andb. destruct b1.\n        { - reflexivity. }\n        { - reflexivity. }\n  - intros [H1 H2]. rewrite H1. apply H2.\nQed.\n\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  split.\n  - intros H. rewrite <- H. unfold orb. destruct b1.\n    + left. reflexivity.\n    + right. reflexivity.\n  - intros [H1 | H2].\n    + rewrite H1. reflexivity.\n    + rewrite H2. destruct b1.\n      * reflexivity.\n      * reflexivity.\nQed.\n\nRequire Import NArith.\n\n(* Exercise: 1 star (beq_nat_false_iff) *)\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  intros x y.\n  split.\n  - unfold not. intros H G. rewrite <- G in H.\n    rewrite <- beq_nat_refl in H. inversion H.\n  - unfold not. intros. destruct (beq_nat x y) eqn:G.\n    + exfalso. apply beq_nat_true in G. apply H. apply G.\n    + reflexivity.\nQed.\n\n(* Exercise: 3 stars (beq_list) *)\nFixpoint beq_list {A : Type} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | [], [] => true\n  | x :: l1', y :: l2' => beq x y && beq_list beq l1' l2'\n  | _, _ => false\n  end.\n\nLemma list_body_eq : forall X (x:X) (l1 l2 : list X),\n  x :: l1 = x :: l2 ->\n  l1 = l2.\nProof.\n  intros.\n  induction l1, l2.\n  - reflexivity.\n  - inversion H.\n  - inversion H.\n  - inversion H. rewrite <- H2. reflexivity.\nQed.\n\nLemma list_body_eq_inv : forall X (x:X) (l1 l2 : list X),\n  l1 = l2 ->\n  x :: l1 = x :: l2.\nProof.\n  intros. rewrite H. reflexivity.\nQed.\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.\n  induction l1 as [| x l1'], l2 as [| y l2'].\n  - simpl. split.\n    + reflexivity.\n    + reflexivity.\n  - simpl. split.\n    + intros G. inversion G.\n    + intros G. inversion G.\n  - simpl. split.\n    + intros G. inversion G.\n    + intros G. inversion G.\n  - simpl. split.\n    + intros G. rewrite andb_true_iff in G.\n      destruct G. apply IHl1' in H1. apply H in H0. \n      rewrite H0. rewrite H1. reflexivity.\n    + intros G. rewrite andb_true_iff. split.\n      * inversion G. apply H. reflexivity.\n      * inversion G. apply IHl1' in H2. \n        inversion G. rewrite H4 in H2. apply H2.\nQed.\n\n(* Exercise: 2 stars, recommended (All_forallb) *)\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_true_iff : forall X test (l : list X),\n  forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  intros. split.\n  - intros H. induction l.\n    + simpl. apply I.\n    + simpl. simpl in H. rewrite andb_true_iff in H. destruct H.  split.\n      * apply H.\n      * apply IHl. apply H0.\n  - intros H. induction l.\n    + reflexivity.\n    + simpl. rewrite andb_true_iff. simpl in H. destruct H. split.\n      * apply H.\n      * apply IHl. apply H0.\nQed.\n\n(* Classical vs. Constructive Logic *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~P.\n\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~P.\nProof.\n  intros. destruct b.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\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. apply beq_nat_true_iff.\nQed.\n\n\n(* Exercise: 3 stars (excluded_middle_irrefutable) *)\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~P).\nProof.\n  intros. apply double_neg.\nAbort.\n\n\n(* Exercise:  3 stars, advanced (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  intros.\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": "prashantpawar", "repo": "logical-foundations", "sha": "8c2126869f2104e2fe38249e3b86de080ea12d2f", "save_path": "github-repos/coq/prashantpawar-logical-foundations", "path": "github-repos/coq/prashantpawar-logical-foundations/logical-foundations-8c2126869f2104e2fe38249e3b86de080ea12d2f/Logic_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8757869786798663, "lm_q1q2_score": 0.7577519942920478}}
{"text": "Require Import List.\nImport ListNotations.\nSet Implicit Arguments.\nRequire Import Arith.\nRequire Import Coq.Sorting.Sorted.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Program.Combinators.\nRequire Import quicksort.\n\nInductive bt :=\n| Leaf : bt\n| Node : nat -> bt -> bt -> bt.\n\nInductive in_bt : nat -> bt -> Prop :=\n| Curnode : forall n1 n2 tl tr, n1 = n2 -> in_bt n1 (Node n2 tl tr)\n| Lefttree : forall n1 n2 tl tr, in_bt n1 tl -> in_bt n1 (Node n2 tl tr)\n| Righttree : forall n1 n2 tl tr, in_bt n1 tr -> in_bt n1 (Node n2 tl tr).\n\nInductive bst : bt -> Prop :=\n| BSTLeaf : bst Leaf\n| BSTNode : forall n1 tl tr, (forall n2, in_bt n2 tl -> n2 < n1)\n                        -> (forall n2, in_bt n2 tr -> n2 >= n1)\n                        -> bst tl\n                        -> bst tr\n                        -> bst (Node n1 tl tr).\n\nFixpoint insert n1 t :=\n  match t with\n  | Leaf => Node n1 Leaf Leaf\n  | Node n2 tl tr => if n1 <? n2\n                    then Node n2 (insert n1 tl) tr\n                    else Node n2 tl (insert n1 tr)\n  end.\n\n\nLemma insert_in : forall t n, in_bt n (insert n t).\nProof.\n  intros. induction t. compute. constructor. reflexivity.\n  simpl. destruct (n <? n0); [ apply Lefttree | apply Righttree ]; assumption.\nQed.\n\nLemma insert_still_in : forall t n n1, in_bt n1 t -> in_bt n1 (insert n t).\nProof.\n  intros. induction t. inversion H.\n  simpl. destruct (n <? n0); inversion H.\n  constructor. auto.\n  apply Lefttree. apply IHt1. assumption.\n  apply Righttree. assumption.\n\n  constructor. auto.\n  apply Lefttree. assumption.\n  apply Righttree. apply IHt2. assumption.\nQed.\n  \nLemma insert_inversion : forall t n n2, in_bt n2 (insert n t) -> in_bt n2 t \\/  n2 = n.\nProof.\n  intros. induction t.\n  simpl in H. inversion H. right. assumption.\n  inversion H2. inversion H2.\n\n  simpl in *. destruct (n <? n0) eqn:res; inversion H.\n  subst. left. constructor. reflexivity.\n  assert (in_bt n2 t1 \\/ n2 = n). apply IHt1. assumption.\n  destruct H5. left. apply Lefttree. assumption.\n  subst. right. reflexivity.\n  subst. left. apply Righttree. assumption.\n\n  subst. left. constructor. reflexivity.\n  left. apply Lefttree. assumption.\n  assert (in_bt n2 t2 \\/ n2 = n). apply IHt2. assumption.\n  destruct H5. subst. left. apply Righttree. assumption.\n  right. assumption.\nQed.\n\nTheorem insert_bst : forall t n, bst t -> bst (insert n t).\nProof.\n  intros. induction H.\n  compute. constructor; intros; try inversion H; try constructor.\n  simpl. destruct (n <? n1) eqn:res.\n  constructor. intros. apply insert_inversion in H3. destruct H3.\n  apply H. assumption. rewrite <- H3 in res. apply Nat.ltb_lt in res.\n  assumption. intros. apply H0. assumption. assumption. assumption.\n\n  constructor. assumption. intros. apply insert_inversion in H3.\n  destruct H3. apply H0. assumption. rewrite H3. apply Nat.ltb_nlt in res.\n  apply not_gt in res. assumption. assumption. assumption.\nQed.\n\nDefinition insert_list l := List.fold_right insert Leaf l.\n\nLemma insert_list_bst : forall l, bst (insert_list l).\nProof.\n  intros. induction l. compute. constructor.\n  unfold insert_list in *. simpl. apply insert_bst. assumption.\nQed.\n\nFixpoint marshall t :=\n  match t with\n  | Leaf => []\n  | Node a tl tr =>  (marshall tl) ++ (a :: (marshall tr))\n  end.\n  \nTheorem in_marshall : forall x t, in_bt x t <-> In x (marshall t).\nProof.\n  intros. split; intros.\n  induction t. inversion H.\n  simpl. apply in_app_iff. inversion H.\n  subst. right. constructor. reflexivity.\n  subst. left. apply IHt1. assumption.\n  subst. right. apply in_cons. apply IHt2. assumption.\n\n  induction t. inversion H. simpl in H. apply in_app_iff in H.\n  destruct H. apply Lefttree. apply IHt1. assumption.\n  simpl in H. destruct H. subst. constructor. reflexivity.\n  apply Righttree. apply IHt2. assumption.\nQed.\n  \nLemma lt_gt : forall n1 n2, n1 <= n2 <-> n2 >= n1.\nProof.\n  intros. split;\n  auto with arith.\nQed.\n  \n\nTheorem marshall_sorted : forall t, bst t -> LocallySorted le (marshall t).\nProof.\n  intros. induction t. compute. constructor.\n  simpl. inversion H. subst.\n  assert (LocallySorted le (marshall t1)).\n  apply IHt1. assumption.\n  assert (LocallySorted le (marshall t2)).\n  apply IHt2. assumption. \n  apply app_lt_sorted. assumption. assumption.\n  intros. assert (a < n). apply H3. apply in_marshall.\n  assumption. auto with arith.\n  intros. apply lt_gt. apply H4. apply in_marshall. assumption.\nQed.\n\nDefinition treesort l :=\n  marshall (insert_list l).\n\nTheorem treesort_sorted : forall l, LocallySorted le (treesort l).\nProof.\n  intros. unfold treesort. apply marshall_sorted.\n  apply insert_list_bst.\nQed.\n\nFixpoint tree_size t :=\n  match t with\n  | Leaf => 0\n  | Node n tl tr => 1 + (tree_size tl) + (tree_size tr)\n  end.\n\nLemma le_plus_l_elim : forall n m p, n + m <= p -> n <= p.\nProof.\n  intros. induction m. rewrite plus_comm in H. simpl in H.\n  assumption.\n  apply IHm. rewrite plus_comm in H. inversion H.\n  rewrite plus_comm. simpl. auto. constructor.\n  rewrite plus_comm. apply le_Sn_le. simpl in H0.\n  assumption.\nQed.\n  \nLemma permutation_append : forall {A : Type} (l1 l2 l3 l4  : list A) a,\n    Permutation l1 l2 -> Permutation l3 l4 ->\n    Permutation (a :: (l1 ++ l3)) (l2 ++ (a :: l4)).\nProof.\n  intros. apply Permutation_cons_app. apply Permutation_app.\n  assumption. assumption.\nQed.\n\nLemma insert_permutation : forall a t,\n    Permutation (a :: (marshall t))\n                (marshall (insert a t)).\nProof.\n  intros. remember (tree_size t) as n.\n  assert ((tree_size t) <= n). rewrite Heqn. constructor.\n  clear Heqn. generalize dependent t. induction n; intros.\n  destruct t. auto.\n  inversion H.\n\n  destruct t. auto. simpl. destruct (a <? n0). simpl.\n  assert (Permutation (a :: (marshall t1)) (marshall (insert a t1))).\n  apply IHn. simpl in H. apply le_S_n in H. apply le_plus_l_elim in H.\n  assumption. remember (n0 :: (marshall t2)) as l2.\n  apply Permutation_app_tail with (tl := l2) in H0.\n  simpl in H0. assumption.\n\n  simpl.\n  assert (Permutation (a :: marshall t2) (marshall (insert a t2))).\n  apply IHn. simpl in H. apply le_S_n in H.\n  rewrite plus_comm in H. apply le_plus_l_elim in H. assumption.\n  remember (n0 :: marshall (insert a t2)) as x.\n  remember (marshall t1) as y.\n  assert\n    (Permutation (a :: y ++ n0 :: (marshall t2)) (y ++ a :: n0 :: (marshall t2))).\n  apply Permutation_cons_app. auto.\n  apply Permutation_trans with (l' := (y ++ a :: n0 :: marshall t2)).\n  assumption. rewrite Heqx. rewrite Heqy. apply Permutation_app.\n  auto. assert (Permutation (a :: n0 :: marshall t2) (n0 :: a :: marshall t2)).\n  apply perm_swap. apply Permutation_trans with (l' := (n0 :: a :: marshall t2)).\n  assumption. constructor. assumption.\nQed.\n\n\nTheorem treesort_permutation : forall l, Permutation l (treesort l).\nProof.\n  intros. induction l. auto.\n  unfold treesort in *. simpl.\n  assert (Permutation (a :: marshall (insert_list l))\n                      (marshall (insert a (insert_list l)))).\n  apply insert_permutation.\n  apply Permutation_trans with (l' := (a :: marshall (insert_list l))).\n  constructor. assumption. assumption.\nQed.\n", "meta": {"author": "MiloDavis", "repo": "verified-sorts", "sha": "4f4a1accdaf630f2ea01bdc8c901e9bf18e42bc2", "save_path": "github-repos/coq/MiloDavis-verified-sorts", "path": "github-repos/coq/MiloDavis-verified-sorts/verified-sorts-4f4a1accdaf630f2ea01bdc8c901e9bf18e42bc2/treesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7577100188845896}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Rbase.\nRequire Import Rfunctions.\nLocal Open Scope R_scope.\n\nInductive Rlist : Type :=\n| nil : Rlist\n| cons : R -> Rlist -> Rlist.\n\nFixpoint In (x:R) (l:Rlist) : Prop :=\nmatch l with\n| nil => False\n| cons a l' => x = a \\/ In x l'\nend.\n\nFixpoint Rlength (l:Rlist) : nat :=\nmatch l with\n| nil => 0%nat\n| cons a l' => S (Rlength l')\nend.\n\nFixpoint MaxRlist (l:Rlist) : R :=\nmatch l with\n| nil => 0\n| cons a l1 =>\nmatch l1 with\n| nil => a\n| cons a' l2 => Rmax a (MaxRlist l1)\nend\nend.\n\nFixpoint MinRlist (l:Rlist) : R :=\nmatch l with\n| nil => 1\n| cons a l1 =>\nmatch l1 with\n| nil => a\n| cons a' l2 => Rmin a (MinRlist l1)\nend\nend.\n\nLemma MaxRlist_P1 : forall (l:Rlist) (x:R), In x l -> x <= MaxRlist l.\nProof. hammer_hook \"RList\" \"RList.MaxRlist_P1\".  \nintros; induction  l as [| r l Hrecl].\nsimpl in H; elim H.\ninduction  l as [| r0 l Hrecl0].\nsimpl in H; elim H; intro.\nsimpl; right; assumption.\nelim H0.\nreplace (MaxRlist (cons r (cons r0 l))) with (Rmax r (MaxRlist (cons r0 l))).\nsimpl in H; decompose [or] H.\nrewrite H0; apply RmaxLess1.\nunfold Rmax; case (Rle_dec r (MaxRlist (cons r0 l))); intro.\napply Hrecl; simpl; tauto.\napply Rle_trans with (MaxRlist (cons r0 l));\n[ apply Hrecl; simpl; tauto | left; auto with real ].\nunfold Rmax; case (Rle_dec r (MaxRlist (cons r0 l))); intro.\napply Hrecl; simpl; tauto.\napply Rle_trans with (MaxRlist (cons r0 l));\n[ apply Hrecl; simpl; tauto | left; auto with real ].\nreflexivity.\nQed.\n\nFixpoint AbsList (l:Rlist) (x:R) : Rlist :=\nmatch l with\n| nil => nil\n| cons a l' => cons (Rabs (a - x) / 2) (AbsList l' x)\nend.\n\nLemma MinRlist_P1 : forall (l:Rlist) (x:R), In x l -> MinRlist l <= x.\nProof. hammer_hook \"RList\" \"RList.MinRlist_P1\".  \nintros; induction  l as [| r l Hrecl].\nsimpl in H; elim H.\ninduction  l as [| r0 l Hrecl0].\nsimpl in H; elim H; intro.\nsimpl; right; symmetry ; assumption.\nelim H0.\nreplace (MinRlist (cons r (cons r0 l))) with (Rmin r (MinRlist (cons r0 l))).\nsimpl in H; decompose [or] H.\nrewrite H0; apply Rmin_l.\nunfold Rmin; case (Rle_dec r (MinRlist (cons r0 l))); intro.\napply Rle_trans with (MinRlist (cons r0 l)).\nassumption.\napply Hrecl; simpl; tauto.\napply Hrecl; simpl; tauto.\napply Rle_trans with (MinRlist (cons r0 l)).\napply Rmin_r.\napply Hrecl; simpl; tauto.\nreflexivity.\nQed.\n\nLemma AbsList_P1 :\nforall (l:Rlist) (x y:R), In y l -> In (Rabs (y - x) / 2) (AbsList l x).\nProof. hammer_hook \"RList\" \"RList.AbsList_P1\".  \nintros; induction  l as [| r l Hrecl].\nelim H.\nsimpl; simpl in H; elim H; intro.\nleft; rewrite H0; reflexivity.\nright; apply Hrecl; assumption.\nQed.\n\nLemma MinRlist_P2 :\nforall l:Rlist, (forall y:R, In y l -> 0 < y) -> 0 < MinRlist l.\nProof. hammer_hook \"RList\" \"RList.MinRlist_P2\".  \nintros; induction  l as [| r l Hrecl].\napply Rlt_0_1.\ninduction  l as [| r0 l Hrecl0].\nsimpl; apply H; simpl; tauto.\nreplace (MinRlist (cons r (cons r0 l))) with (Rmin r (MinRlist (cons r0 l))).\nunfold Rmin; case (Rle_dec r (MinRlist (cons r0 l))); intro.\napply H; simpl; tauto.\napply Hrecl; intros; apply H; simpl; simpl in H0; tauto.\nreflexivity.\nQed.\n\nLemma AbsList_P2 :\nforall (l:Rlist) (x y:R),\nIn y (AbsList l x) ->  exists z : R, In z l /\\ y = Rabs (z - x) / 2.\nProof. hammer_hook \"RList\" \"RList.AbsList_P2\".  \nintros; induction  l as [| r l Hrecl].\nelim H.\nelim H; intro.\nexists r; split.\nsimpl; tauto.\nassumption.\nassert (H1 := Hrecl H0); elim H1; intros; elim H2; clear H2; intros;\nexists x0; simpl; simpl in H2; tauto.\nQed.\n\nLemma MaxRlist_P2 :\nforall l:Rlist, (exists y : R, In y l) -> In (MaxRlist l) l.\nProof. hammer_hook \"RList\" \"RList.MaxRlist_P2\".  \nintros; induction  l as [| r l Hrecl].\nsimpl in H; elim H; trivial.\ninduction  l as [| r0 l Hrecl0].\nsimpl; left; reflexivity.\nchange (In (Rmax r (MaxRlist (cons r0 l))) (cons r (cons r0 l)));\nunfold Rmax; case (Rle_dec r (MaxRlist (cons r0 l)));\nintro.\nright; apply Hrecl; exists r0; left; reflexivity.\nleft; reflexivity.\nQed.\n\nFixpoint pos_Rl (l:Rlist) (i:nat) : R :=\nmatch l with\n| nil => 0\n| cons a l' => match i with\n| O => a\n| S i' => pos_Rl l' i'\nend\nend.\n\nLemma pos_Rl_P1 :\nforall (l:Rlist) (a:R),\n(0 < Rlength l)%nat ->\npos_Rl (cons a l) (Rlength l) = pos_Rl l (pred (Rlength l)).\nProof. hammer_hook \"RList\" \"RList.pos_Rl_P1\".  \nintros; induction  l as [| r l Hrecl];\n[ elim (lt_n_O _ H)\n| simpl; case (Rlength l); [ reflexivity | intro; reflexivity ] ].\nQed.\n\nLemma pos_Rl_P2 :\nforall (l:Rlist) (x:R),\nIn x l <-> (exists i : nat, (i < Rlength l)%nat /\\ x = pos_Rl l i).\nProof. hammer_hook \"RList\" \"RList.pos_Rl_P2\".  \nintros; induction  l as [| r l Hrecl].\nsplit; intro;\n[ elim H | elim H; intros; elim H0; intros; elim (lt_n_O _ H1) ].\nsplit; intro.\nelim H; intro.\nexists 0%nat; split;\n[ simpl; apply lt_O_Sn | simpl; apply H0 ].\nelim Hrecl; intros; assert (H3 := H1 H0); elim H3; intros; elim H4; intros;\nexists (S x0); split;\n[ simpl; apply lt_n_S; assumption | simpl; assumption ].\nelim H; intros; elim H0; intros; destruct (zerop x0) as [->|].\nsimpl in H2; left; assumption.\nright; elim Hrecl; intros H4 H5; apply H5; assert (H6 : S (pred x0) = x0).\nsymmetry ; apply S_pred with 0%nat; assumption.\nexists (pred x0); split;\n[ simpl in H1; apply lt_S_n; rewrite H6; assumption\n| rewrite <- H6 in H2; simpl in H2; assumption ].\nQed.\n\nLemma Rlist_P1 :\nforall (l:Rlist) (P:R -> R -> Prop),\n(forall x:R, In x l ->  exists y : R, P x y) ->\nexists l' : Rlist,\nRlength l = Rlength l' /\\\n(forall i:nat, (i < Rlength l)%nat -> P (pos_Rl l i) (pos_Rl l' i)).\nProof. hammer_hook \"RList\" \"RList.Rlist_P1\".  \nintros; induction  l as [| r l Hrecl].\nexists nil; intros; split;\n[ reflexivity | intros; simpl in H0; elim (lt_n_O _ H0) ].\nassert (H0 : In r (cons r l)).\nsimpl; left; reflexivity.\nassert (H1 := H _ H0);\nassert (H2 : forall x:R, In x l ->  exists y : R, P x y).\nintros; apply H; simpl; right; assumption.\nassert (H3 := Hrecl H2); elim H1; intros; elim H3; intros; exists (cons x x0);\nintros; elim H5; clear H5; intros; split.\nsimpl; rewrite H5; reflexivity.\nintros; destruct (zerop i) as [->|].\nsimpl; assumption.\nassert (H9 : i = S (pred i)).\napply S_pred with 0%nat; assumption.\nrewrite H9; simpl; apply H6; simpl in H7; apply lt_S_n; rewrite <- H9;\nassumption.\nQed.\n\nDefinition ordered_Rlist (l:Rlist) : Prop :=\nforall i:nat, (i < pred (Rlength l))%nat -> pos_Rl l i <= pos_Rl l (S i).\n\nFixpoint insert (l:Rlist) (x:R) : Rlist :=\nmatch l with\n| nil => cons x nil\n| cons a l' =>\nmatch Rle_dec a x with\n| left _ => cons a (insert l' x)\n| right _ => cons x l\nend\nend.\n\nFixpoint cons_Rlist (l k:Rlist) : Rlist :=\nmatch l with\n| nil => k\n| cons a l' => cons a (cons_Rlist l' k)\nend.\n\nFixpoint cons_ORlist (k l:Rlist) : Rlist :=\nmatch k with\n| nil => l\n| cons a k' => cons_ORlist k' (insert l a)\nend.\n\nFixpoint app_Rlist (l:Rlist) (f:R -> R) : Rlist :=\nmatch l with\n| nil => nil\n| cons a l' => cons (f a) (app_Rlist l' f)\nend.\n\nFixpoint mid_Rlist (l:Rlist) (x:R) : Rlist :=\nmatch l with\n| nil => nil\n| cons a l' => cons ((x + a) / 2) (mid_Rlist l' a)\nend.\n\nDefinition Rtail (l:Rlist) : Rlist :=\nmatch l with\n| nil => nil\n| cons a l' => l'\nend.\n\nDefinition FF (l:Rlist) (f:R -> R) : Rlist :=\nmatch l with\n| nil => nil\n| cons a l' => app_Rlist (mid_Rlist l' a) f\nend.\n\nLemma RList_P0 :\nforall (l:Rlist) (a:R),\npos_Rl (insert l a) 0 = a \\/ pos_Rl (insert l a) 0 = pos_Rl l 0.\nProof. hammer_hook \"RList\" \"RList.RList_P0\".  \nintros; induction  l as [| r l Hrecl];\n[ left; reflexivity\n| simpl; case (Rle_dec r a); intro;\n[ right; reflexivity | left; reflexivity ] ].\nQed.\n\nLemma RList_P1 :\nforall (l:Rlist) (a:R), ordered_Rlist l -> ordered_Rlist (insert l a).\nProof. hammer_hook \"RList\" \"RList.RList_P1\".  \nintros; induction  l as [| r l Hrecl].\nsimpl; unfold ordered_Rlist; intros; simpl in H0;\nelim (lt_n_O _ H0).\nsimpl; case (Rle_dec r a); intro.\nassert (H1 : ordered_Rlist l).\nunfold ordered_Rlist; unfold ordered_Rlist in H; intros;\nassert (H1 : (S i < pred (Rlength (cons r l)))%nat);\n[ simpl; replace (Rlength l) with (S (pred (Rlength l)));\n[ apply lt_n_S; assumption\n| symmetry ; apply S_pred with 0%nat; apply neq_O_lt; red;\nintro; rewrite <- H1 in H0; simpl in H0; elim (lt_n_O _ H0) ]\n| apply (H _ H1) ].\nassert (H2 := Hrecl H1); unfold ordered_Rlist; intros;\ninduction  i as [| i Hreci].\nsimpl; assert (H3 := RList_P0 l a); elim H3; intro.\nrewrite H4; assumption.\ninduction  l as [| r1 l Hrecl0];\n[ simpl; assumption\n| rewrite H4; apply (H 0%nat); simpl; apply lt_O_Sn ].\nsimpl; apply H2; simpl in H0; apply lt_S_n;\nreplace (S (pred (Rlength (insert l a)))) with (Rlength (insert l a));\n[ assumption\n| apply S_pred with 0%nat; apply neq_O_lt; red; intro;\nrewrite <- H3 in H0; elim (lt_n_O _ H0) ].\nunfold ordered_Rlist; intros; induction  i as [| i Hreci];\n[ simpl; auto with real\n| change (pos_Rl (cons r l) i <= pos_Rl (cons r l) (S i)); apply H;\nsimpl in H0; simpl; apply (lt_S_n _ _ H0) ].\nQed.\n\nLemma RList_P2 :\nforall l1 l2:Rlist, ordered_Rlist l2 -> ordered_Rlist (cons_ORlist l1 l2).\nProof. hammer_hook \"RList\" \"RList.RList_P2\".  \nsimple induction l1;\n[ intros; simpl; apply H\n| intros; simpl; apply H; apply RList_P1; assumption ].\nQed.\n\nLemma RList_P3 :\nforall (l:Rlist) (x:R),\nIn x l <-> (exists i : nat, x = pos_Rl l i /\\ (i < Rlength l)%nat).\nProof. hammer_hook \"RList\" \"RList.RList_P3\".  \nintros; split; intro;\n[ induction  l as [| r l Hrecl] | induction  l as [| r l Hrecl] ].\nelim H.\nelim H; intro;\n[ exists 0%nat; split; [ apply H0 | simpl; apply lt_O_Sn ]\n| elim (Hrecl H0); intros; elim H1; clear H1; intros; exists (S x0); split;\n[ apply H1 | simpl; apply lt_n_S; assumption ] ].\nelim H; intros; elim H0; intros; elim (lt_n_O _ H2).\nsimpl; elim H; intros; elim H0; clear H0; intros;\ninduction  x0 as [| x0 Hrecx0];\n[ left; apply H0\n| right; apply Hrecl; exists x0; split;\n[ apply H0 | simpl in H1; apply lt_S_n; assumption ] ].\nQed.\n\nLemma RList_P4 :\nforall (l1:Rlist) (a:R), ordered_Rlist (cons a l1) -> ordered_Rlist l1.\nProof. hammer_hook \"RList\" \"RList.RList_P4\".  \nintros; unfold ordered_Rlist; intros; apply (H (S i)); simpl;\nreplace (Rlength l1) with (S (pred (Rlength l1)));\n[ apply lt_n_S; assumption\n| symmetry ; apply S_pred with 0%nat; apply neq_O_lt; red;\nintro; rewrite <- H1 in H0; elim (lt_n_O _ H0) ].\nQed.\n\nLemma RList_P5 :\nforall (l:Rlist) (x:R), ordered_Rlist l -> In x l -> pos_Rl l 0 <= x.\nProof. hammer_hook \"RList\" \"RList.RList_P5\".  \nintros; induction  l as [| r l Hrecl];\n[ elim H0\n| simpl; elim H0; intro;\n[ rewrite H1; right; reflexivity\n| apply Rle_trans with (pos_Rl l 0);\n[ apply (H 0%nat); simpl; induction  l as [| r0 l Hrecl0];\n[ elim H1 | simpl; apply lt_O_Sn ]\n| apply Hrecl; [ eapply RList_P4; apply H | assumption ] ] ] ].\nQed.\n\nLemma RList_P6 :\nforall l:Rlist,\nordered_Rlist l <->\n(forall i j:nat,\n(i <= j)%nat -> (j < Rlength l)%nat -> pos_Rl l i <= pos_Rl l j).\nProof. hammer_hook \"RList\" \"RList.RList_P6\".  \nsimple induction l; split; intro.\nintros; right; reflexivity.\nunfold ordered_Rlist; intros; simpl in H0; elim (lt_n_O _ H0).\nintros; induction  i as [| i Hreci];\n[ induction  j as [| j Hrecj];\n[ right; reflexivity\n| simpl; apply Rle_trans with (pos_Rl r0 0);\n[ apply (H0 0%nat); simpl; simpl in H2; apply neq_O_lt;\nred; intro; rewrite <- H3 in H2;\nassert (H4 := lt_S_n _ _ H2); elim (lt_n_O _ H4)\n| elim H; intros; apply H3;\n[ apply RList_P4 with r; assumption\n| apply le_O_n\n| simpl in H2; apply lt_S_n; assumption ] ] ]\n| induction  j as [| j Hrecj];\n[ elim (le_Sn_O _ H1)\n| simpl; elim H; intros; apply H3;\n[ apply RList_P4 with r; assumption\n| apply le_S_n; assumption\n| simpl in H2; apply lt_S_n; assumption ] ] ].\nunfold ordered_Rlist; intros; apply H0;\n[ apply le_n_Sn | simpl; simpl in H1; apply lt_n_S; assumption ].\nQed.\n\nLemma RList_P7 :\nforall (l:Rlist) (x:R),\nordered_Rlist l -> In x l -> x <= pos_Rl l (pred (Rlength l)).\nProof. hammer_hook \"RList\" \"RList.RList_P7\".  \nintros; assert (H1 := RList_P6 l); elim H1; intros H2 _; assert (H3 := H2 H);\nclear H1 H2; assert (H1 := RList_P3 l x); elim H1;\nclear H1; intros; assert (H4 := H1 H0); elim H4; clear H4;\nintros; elim H4; clear H4; intros; rewrite H4;\nassert (H6 : Rlength l = S (pred (Rlength l))).\napply S_pred with 0%nat; apply neq_O_lt; red; intro;\nrewrite <- H6 in H5; elim (lt_n_O _ H5).\napply H3;\n[ rewrite H6 in H5; apply lt_n_Sm_le; assumption\n| apply lt_pred_n_n; apply neq_O_lt; red; intro; rewrite <- H7 in H5;\nelim (lt_n_O _ H5) ].\nQed.\n\nLemma RList_P8 :\nforall (l:Rlist) (a x:R), In x (insert l a) <-> x = a \\/ In x l.\nProof. hammer_hook \"RList\" \"RList.RList_P8\".  \nsimple induction l.\nintros; split; intro; simpl in H; apply H.\nintros; split; intro;\n[ simpl in H0; generalize H0; case (Rle_dec r a); intros;\n[ simpl in H1; elim H1; intro;\n[ right; left; assumption\n| elim (H a x); intros; elim (H3 H2); intro;\n[ left; assumption | right; right; assumption ] ]\n| simpl in H1; decompose [or] H1;\n[ left; assumption\n| right; left; assumption\n| right; right; assumption ] ]\n| simpl; case (Rle_dec r a); intro;\n[ simpl in H0; decompose [or] H0;\n[ right; elim (H a x); intros; apply H3; left\n| left\n| right; elim (H a x); intros; apply H3; right ]\n| simpl in H0; decompose [or] H0; [ left | right; left | right; right ] ];\nassumption ].\nQed.\n\nLemma RList_P9 :\nforall (l1 l2:Rlist) (x:R), In x (cons_ORlist l1 l2) <-> In x l1 \\/ In x l2.\nProof. hammer_hook \"RList\" \"RList.RList_P9\".  \nsimple induction l1.\nintros; split; intro;\n[ simpl in H; right; assumption\n| simpl; elim H; intro; [ elim H0 | assumption ] ].\nintros; split.\nsimpl; intros; elim (H (insert l2 r) x); intros; assert (H3 := H1 H0);\nelim H3; intro;\n[ left; right; assumption\n| elim (RList_P8 l2 r x); intros H5 _; assert (H6 := H5 H4); elim H6; intro;\n[ left; left; assumption | right; assumption ] ].\nintro; simpl; elim (H (insert l2 r) x); intros _ H1; apply H1;\nelim H0; intro;\n[ elim H2; intro;\n[ right; elim (RList_P8 l2 r x); intros _ H4; apply H4; left; assumption\n| left; assumption ]\n| right; elim (RList_P8 l2 r x); intros _ H3; apply H3; right; assumption ].\nQed.\n\nLemma RList_P10 :\nforall (l:Rlist) (a:R), Rlength (insert l a) = S (Rlength l).\nProof. hammer_hook \"RList\" \"RList.RList_P10\".  \nintros; induction  l as [| r l Hrecl];\n[ reflexivity\n| simpl; case (Rle_dec r a); intro;\n[ simpl; rewrite Hrecl; reflexivity | reflexivity ] ].\nQed.\n\nLemma RList_P11 :\nforall l1 l2:Rlist,\nRlength (cons_ORlist l1 l2) = (Rlength l1 + Rlength l2)%nat.\nProof. hammer_hook \"RList\" \"RList.RList_P11\".  \nsimple induction l1;\n[ intro; reflexivity\n| intros; simpl; rewrite (H (insert l2 r)); rewrite RList_P10;\napply INR_eq; rewrite S_INR; do 2 rewrite plus_INR;\nrewrite S_INR; ring ].\nQed.\n\nLemma RList_P12 :\nforall (l:Rlist) (i:nat) (f:R -> R),\n(i < Rlength l)%nat -> pos_Rl (app_Rlist l f) i = f (pos_Rl l i).\nProof. hammer_hook \"RList\" \"RList.RList_P12\".  \nsimple induction l;\n[ intros; elim (lt_n_O _ H)\n| intros; induction  i as [| i Hreci];\n[ reflexivity | simpl; apply H; apply lt_S_n; apply H0 ] ].\nQed.\n\nLemma RList_P13 :\nforall (l:Rlist) (i:nat) (a:R),\n(i < pred (Rlength l))%nat ->\npos_Rl (mid_Rlist l a) (S i) = (pos_Rl l i + pos_Rl l (S i)) / 2.\nProof. hammer_hook \"RList\" \"RList.RList_P13\".  \nsimple induction l.\nintros; simpl in H; elim (lt_n_O _ H).\nsimple induction r0.\nintros; simpl in H0; elim (lt_n_O _ H0).\nintros; simpl in H1; induction  i as [| i Hreci].\nreflexivity.\nchange\n(pos_Rl (mid_Rlist (cons r1 r2) r) (S i) =\n(pos_Rl (cons r1 r2) i + pos_Rl (cons r1 r2) (S i)) / 2)\n; apply H0; simpl; apply lt_S_n; assumption.\nQed.\n\nLemma RList_P14 : forall (l:Rlist) (a:R), Rlength (mid_Rlist l a) = Rlength l.\nProof. hammer_hook \"RList\" \"RList.RList_P14\".  \nsimple induction l; intros;\n[ reflexivity | simpl; rewrite (H r); reflexivity ].\nQed.\n\nLemma RList_P15 :\nforall l1 l2:Rlist,\nordered_Rlist l1 ->\nordered_Rlist l2 ->\npos_Rl l1 0 = pos_Rl l2 0 -> pos_Rl (cons_ORlist l1 l2) 0 = pos_Rl l1 0.\nProof. hammer_hook \"RList\" \"RList.RList_P15\".  \nintros; apply Rle_antisym.\ninduction  l1 as [| r l1 Hrecl1];\n[ simpl; simpl in H1; right; symmetry ; assumption\n| elim (RList_P9 (cons r l1) l2 (pos_Rl (cons r l1) 0)); intros;\nassert\n(H4 :\nIn (pos_Rl (cons r l1) 0) (cons r l1) \\/ In (pos_Rl (cons r l1) 0) l2);\n[ left; left; reflexivity\n| assert (H5 := H3 H4); apply RList_P5;\n[ apply RList_P2; assumption | assumption ] ] ].\ninduction  l1 as [| r l1 Hrecl1];\n[ simpl; simpl in H1; right; assumption\n| assert\n(H2 :\nIn (pos_Rl (cons_ORlist (cons r l1) l2) 0) (cons_ORlist (cons r l1) l2));\n[ elim\n(RList_P3 (cons_ORlist (cons r l1) l2)\n(pos_Rl (cons_ORlist (cons r l1) l2) 0));\nintros; apply H3; exists 0%nat; split;\n[ reflexivity | rewrite RList_P11; simpl; apply lt_O_Sn ]\n| elim (RList_P9 (cons r l1) l2 (pos_Rl (cons_ORlist (cons r l1) l2) 0));\nintros; assert (H5 := H3 H2); elim H5; intro;\n[ apply RList_P5; assumption\n| rewrite H1; apply RList_P5; assumption ] ] ].\nQed.\n\nLemma RList_P16 :\nforall l1 l2:Rlist,\nordered_Rlist l1 ->\nordered_Rlist l2 ->\npos_Rl l1 (pred (Rlength l1)) = pos_Rl l2 (pred (Rlength l2)) ->\npos_Rl (cons_ORlist l1 l2) (pred (Rlength (cons_ORlist l1 l2))) =\npos_Rl l1 (pred (Rlength l1)).\nProof. hammer_hook \"RList\" \"RList.RList_P16\".  \nintros; apply Rle_antisym.\ninduction  l1 as [| r l1 Hrecl1].\nsimpl; simpl in H1; right; symmetry ; assumption.\nassert\n(H2 :\nIn\n(pos_Rl (cons_ORlist (cons r l1) l2)\n(pred (Rlength (cons_ORlist (cons r l1) l2))))\n(cons_ORlist (cons r l1) l2));\n[ elim\n(RList_P3 (cons_ORlist (cons r l1) l2)\n(pos_Rl (cons_ORlist (cons r l1) l2)\n(pred (Rlength (cons_ORlist (cons r l1) l2)))));\nintros; apply H3; exists (pred (Rlength (cons_ORlist (cons r l1) l2)));\nsplit; [ reflexivity | rewrite RList_P11; simpl; apply lt_n_Sn ]\n| elim\n(RList_P9 (cons r l1) l2\n(pos_Rl (cons_ORlist (cons r l1) l2)\n(pred (Rlength (cons_ORlist (cons r l1) l2)))));\nintros; assert (H5 := H3 H2); elim H5; intro;\n[ apply RList_P7; assumption | rewrite H1; apply RList_P7; assumption ] ].\ninduction  l1 as [| r l1 Hrecl1].\nsimpl; simpl in H1; right; assumption.\nelim\n(RList_P9 (cons r l1) l2 (pos_Rl (cons r l1) (pred (Rlength (cons r l1)))));\nintros;\nassert\n(H4 :\nIn (pos_Rl (cons r l1) (pred (Rlength (cons r l1)))) (cons r l1) \\/\nIn (pos_Rl (cons r l1) (pred (Rlength (cons r l1)))) l2);\n[ left; change (In (pos_Rl (cons r l1) (Rlength l1)) (cons r l1));\nelim (RList_P3 (cons r l1) (pos_Rl (cons r l1) (Rlength l1)));\nintros; apply H5; exists (Rlength l1); split;\n[ reflexivity | simpl; apply lt_n_Sn ]\n| assert (H5 := H3 H4); apply RList_P7;\n[ apply RList_P2; assumption\n| elim\n(RList_P9 (cons r l1) l2\n(pos_Rl (cons r l1) (pred (Rlength (cons r l1)))));\nintros; apply H7; left;\nelim\n(RList_P3 (cons r l1)\n(pos_Rl (cons r l1) (pred (Rlength (cons r l1)))));\nintros; apply H9; exists (pred (Rlength (cons r l1)));\nsplit; [ reflexivity | simpl; apply lt_n_Sn ] ] ].\nQed.\n\nLemma RList_P17 :\nforall (l1:Rlist) (x:R) (i:nat),\nordered_Rlist l1 ->\nIn x l1 ->\npos_Rl l1 i < x -> (i < pred (Rlength l1))%nat -> pos_Rl l1 (S i) <= x.\nProof. hammer_hook \"RList\" \"RList.RList_P17\".  \nsimple induction l1.\nintros; elim H0.\nintros; induction  i as [| i Hreci].\nsimpl; elim H1; intro;\n[ simpl in H2; rewrite H4 in H2; elim (Rlt_irrefl _ H2)\n| apply RList_P5; [ apply RList_P4 with r; assumption | assumption ] ].\nsimpl; simpl in H2; elim H1; intro.\nrewrite H4 in H2; assert (H5 : r <= pos_Rl r0 i);\n[ apply Rle_trans with (pos_Rl r0 0);\n[ apply (H0 0%nat); simpl; simpl in H3; apply neq_O_lt;\nred; intro; rewrite <- H5 in H3; elim (lt_n_O _ H3)\n| elim (RList_P6 r0); intros; apply H5;\n[ apply RList_P4 with r; assumption\n| apply le_O_n\n| simpl in H3; apply lt_S_n; apply lt_trans with (Rlength r0);\n[ apply H3 | apply lt_n_Sn ] ] ]\n| elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H5 H2)) ].\napply H; try assumption;\n[ apply RList_P4 with r; assumption\n| simpl in H3; apply lt_S_n;\nreplace (S (pred (Rlength r0))) with (Rlength r0);\n[ apply H3\n| apply S_pred with 0%nat; apply neq_O_lt; red; intro;\nrewrite <- H5 in H3; elim (lt_n_O _ H3) ] ].\nQed.\n\nLemma RList_P18 :\nforall (l:Rlist) (f:R -> R), Rlength (app_Rlist l f) = Rlength l.\nProof. hammer_hook \"RList\" \"RList.RList_P18\".  \nsimple induction l; intros;\n[ reflexivity | simpl; rewrite H; reflexivity ].\nQed.\n\nLemma RList_P19 :\nforall l:Rlist,\nl <> nil ->  exists r : R, (exists r0 : Rlist, l = cons r r0).\nProof. hammer_hook \"RList\" \"RList.RList_P19\".  \nintros; induction  l as [| r l Hrecl];\n[ elim H; reflexivity | exists r; exists l; reflexivity ].\nQed.\n\nLemma RList_P20 :\nforall l:Rlist,\n(2 <= Rlength l)%nat ->\nexists r : R,\n(exists r1 : R, (exists l' : Rlist, l = cons r (cons r1 l'))).\nProof. hammer_hook \"RList\" \"RList.RList_P20\".  \nintros; induction  l as [| r l Hrecl];\n[ simpl in H; elim (le_Sn_O _ H)\n| induction  l as [| r0 l Hrecl0];\n[ simpl in H; elim (le_Sn_O _ (le_S_n _ _ H))\n| exists r; exists r0; exists l; reflexivity ] ].\nQed.\n\nLemma RList_P21 : forall l l':Rlist, l = l' -> Rtail l = Rtail l'.\nProof. hammer_hook \"RList\" \"RList.RList_P21\".  \nintros; rewrite H; reflexivity.\nQed.\n\nLemma RList_P22 :\nforall l1 l2:Rlist, l1 <> nil -> pos_Rl (cons_Rlist l1 l2) 0 = pos_Rl l1 0.\nProof. hammer_hook \"RList\" \"RList.RList_P22\".  \nsimple induction l1; [ intros; elim H; reflexivity | intros; reflexivity ].\nQed.\n\nLemma RList_P23 :\nforall l1 l2:Rlist,\nRlength (cons_Rlist l1 l2) = (Rlength l1 + Rlength l2)%nat.\nProof. hammer_hook \"RList\" \"RList.RList_P23\".  \nsimple induction l1;\n[ intro; reflexivity | intros; simpl; rewrite H; reflexivity ].\nQed.\n\nLemma RList_P24 :\nforall l1 l2:Rlist,\nl2 <> nil ->\npos_Rl (cons_Rlist l1 l2) (pred (Rlength (cons_Rlist l1 l2))) =\npos_Rl l2 (pred (Rlength l2)).\nProof. hammer_hook \"RList\" \"RList.RList_P24\".  \nsimple induction l1.\nintros; reflexivity.\nintros; rewrite <- (H l2 H0); induction  l2 as [| r1 l2 Hrecl2].\nelim H0; reflexivity.\ndo 2 rewrite RList_P23;\nreplace (Rlength (cons r r0) + Rlength (cons r1 l2))%nat with\n(S (S (Rlength r0 + Rlength l2)));\n[ replace (Rlength r0 + Rlength (cons r1 l2))%nat with\n(S (Rlength r0 + Rlength l2));\n[ reflexivity\n| simpl; apply INR_eq; rewrite S_INR; do 2 rewrite plus_INR;\nrewrite S_INR; ring ]\n| simpl; apply INR_eq; do 3 rewrite S_INR; do 2 rewrite plus_INR;\nrewrite S_INR; ring ].\nQed.\n\nLemma RList_P25 :\nforall l1 l2:Rlist,\nordered_Rlist l1 ->\nordered_Rlist l2 ->\npos_Rl l1 (pred (Rlength l1)) <= pos_Rl l2 0 ->\nordered_Rlist (cons_Rlist l1 l2).\nProof. hammer_hook \"RList\" \"RList.RList_P25\".  \nsimple induction l1.\nintros; simpl; assumption.\nsimple induction r0.\nintros; simpl; simpl in H2; unfold ordered_Rlist; intros;\nsimpl in H3.\ninduction  i as [| i Hreci].\nsimpl; assumption.\nchange (pos_Rl l2 i <= pos_Rl l2 (S i)); apply (H1 i); apply lt_S_n;\nreplace (S (pred (Rlength l2))) with (Rlength l2);\n[ assumption\n| apply S_pred with 0%nat; apply neq_O_lt; red; intro;\nrewrite <- H4 in H3; elim (lt_n_O _ H3) ].\nintros; clear H; assert (H : ordered_Rlist (cons_Rlist (cons r1 r2) l2)).\napply H0; try assumption.\napply RList_P4 with r; assumption.\nunfold ordered_Rlist; intros; simpl in H4;\ninduction  i as [| i Hreci].\nsimpl; apply (H1 0%nat); simpl; apply lt_O_Sn.\nchange\n(pos_Rl (cons_Rlist (cons r1 r2) l2) i <=\npos_Rl (cons_Rlist (cons r1 r2) l2) (S i));\napply (H i); simpl; apply lt_S_n; assumption.\nQed.\n\nLemma RList_P26 :\nforall (l1 l2:Rlist) (i:nat),\n(i < Rlength l1)%nat -> pos_Rl (cons_Rlist l1 l2) i = pos_Rl l1 i.\nProof. hammer_hook \"RList\" \"RList.RList_P26\".  \nsimple induction l1.\nintros; elim (lt_n_O _ H).\nintros; induction  i as [| i Hreci].\napply RList_P22; discriminate.\napply (H l2 i); simpl in H0; apply lt_S_n; assumption.\nQed.\n\nLemma RList_P27 :\nforall l1 l2 l3:Rlist,\ncons_Rlist l1 (cons_Rlist l2 l3) = cons_Rlist (cons_Rlist l1 l2) l3.\nProof. hammer_hook \"RList\" \"RList.RList_P27\".  \nsimple induction l1; intros;\n[ reflexivity | simpl; rewrite (H l2 l3); reflexivity ].\nQed.\n\nLemma RList_P28 : forall l:Rlist, cons_Rlist l nil = l.\nProof. hammer_hook \"RList\" \"RList.RList_P28\".  \nsimple induction l;\n[ reflexivity | intros; simpl; rewrite H; reflexivity ].\nQed.\n\nLemma RList_P29 :\nforall (l2 l1:Rlist) (i:nat),\n(Rlength l1 <= i)%nat ->\n(i < Rlength (cons_Rlist l1 l2))%nat ->\npos_Rl (cons_Rlist l1 l2) i = pos_Rl l2 (i - Rlength l1).\nProof. hammer_hook \"RList\" \"RList.RList_P29\".  \nsimple induction l2.\nintros; rewrite RList_P28 in H0; elim (lt_irrefl _ (le_lt_trans _ _ _ H H0)).\nintros;\nreplace (cons_Rlist l1 (cons r r0)) with\n(cons_Rlist (cons_Rlist l1 (cons r nil)) r0).\ninversion H0.\nrewrite <- minus_n_n; simpl; rewrite RList_P26.\nclear l2 r0 H i H0 H1 H2; induction  l1 as [| r0 l1 Hrecl1].\nreflexivity.\nsimpl; assumption.\nrewrite RList_P23; rewrite plus_comm; simpl; apply lt_n_Sn.\nreplace (S m - Rlength l1)%nat with (S (S m - S (Rlength l1))).\nrewrite H3; simpl;\nreplace (S (Rlength l1)) with (Rlength (cons_Rlist l1 (cons r nil))).\napply (H (cons_Rlist l1 (cons r nil)) i).\nrewrite RList_P23; rewrite plus_comm; simpl; rewrite <- H3;\napply le_n_S; assumption.\nrepeat rewrite RList_P23; simpl; rewrite RList_P23 in H1;\nrewrite plus_comm in H1; simpl in H1; rewrite (plus_comm (Rlength l1));\nsimpl; rewrite plus_comm; apply H1.\nrewrite RList_P23; rewrite plus_comm; reflexivity.\nchange (S (m - Rlength l1) = (S m - Rlength l1)%nat);\napply minus_Sn_m; assumption.\nreplace (cons r r0) with (cons_Rlist (cons r nil) r0);\n[ symmetry ; apply RList_P27 | 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/RList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7576061070539731}}
{"text": "\n(* Source langauge *)\n\nRequire 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\n(* Examples *)\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\n(* Target Language *)\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\n(* Translation *)\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)).\n\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))) nil.\n\n(* Correctness proof *)\n\nTheorem compile_correct : forall e , progDenote (compile e) nil = Some (expDenote e :: nil).\n\nAbort.\n\n(* Trick: Strengtening the induction hypothesis *)\n\nLemma compile_correct' : forall e p s ,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n\n(* First subgoal *)\ninduction e.\nintros.\nunfold compile.\nunfold expDenote.\nunfold progDenote at 1.\nsimpl.\nfold progDenote.\nreflexivity.\n\nintros.\nunfold compile.\nfold compile.\nunfold expDenote.\nfold expDenote.\n\nCheck app_assoc_reverse.\nSearchRewrite ((_ ++ _) ++ _).\n\nrewrite app_assoc_reverse.\nrewrite IHe2.\n\nrewrite app_assoc_reverse.\nrewrite IHe1.\n\nunfold progDenote at 1.\nsimpl.\nfold progDenote.\nreflexivity.\n\nAbort.\n\n(* Automatic reasoning *)\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 = Some (expDenote e :: nil).\n\nintros.\n\nCheck app_nil_end.\n\nrewrite (app_nil_end (compile e)).\nrewrite compile_correct''.\nreflexivity.\nQed.\n", "meta": {"author": "andorp", "repo": "cpdt", "sha": "dd2099eeae2f12e1379a8706420f072aa174adc5", "save_path": "github-repos/coq/andorp-cpdt", "path": "github-repos/coq/andorp-cpdt/cpdt-dd2099eeae2f12e1379a8706420f072aa174adc5/StackMachines.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7576061060999103}}
{"text": "Require Import List QArith Qreals.\n\nLocal Open Scope Q.\n\nImport ListNotations.\nNotation Qmin := Qminmax.Qmin.\n\nFixpoint Qmin_list l : Q :=\n  match l with\n  | nil => 0\n  | a :: l0 => match l0 with\n            | nil => a\n            | _ => Qmin a (Qmin_list l0)\n            end\n  end.\n\nLemma Qmin_list_cons a b l :\n  Qmin_list (a :: b :: l) = Qmin a (Qmin_list (b :: l)).\nProof. reflexivity. Qed.\n\nLemma Qmin_list_snoc a b l :\n  Qmin_list (a :: l ++ [b]) == Qmin (Qmin_list (a :: l)) b.\nProof.\n  revert a; induction l; intros.\n  - reflexivity.\n  - rewrite <- app_comm_cons, Qmin_list_cons. rewrite IHl.\n    rewrite Qmin_list_cons. apply Qminmax.Q.min_assoc.\nQed.\n\nLemma Qmin_list_cons_cons a b l :\n  Qmin_list (a :: b :: l) == Qmin_list (b :: a :: l).\nProof.\n  remember (rev l).\n  revert l Heql0; induction l0; intros.\n  - apply (f_equal (@rev Q)) in Heql0.\n    rewrite rev_involutive in Heql0. simpl in Heql0. subst.\n    apply Qminmax.Q.min_comm.\n  - apply (f_equal (@rev Q)) in Heql0.\n    rewrite rev_involutive in Heql0. simpl in Heql0. subst.\n    rewrite !app_comm_cons.\n    setoid_rewrite Qmin_list_snoc.\n    rewrite IHl0.\n    reflexivity.\n    symmetry; apply rev_involutive.\nQed.\n\nLemma Qmin_list_spec l :\n  forall a, In a l -> Qmin_list l <= a.\nProof.\n  induction l; intros.\n  - destruct H.\n  - destruct H.\n    + subst. destruct l.\n      * apply Qle_refl.\n      * rewrite Qmin_list_cons.\n        apply Qminmax.Q.le_min_l.\n    + destruct l.\n      * destruct H.\n      * rewrite Qmin_list_cons.\n        eapply Qle_trans.\n        apply Qminmax.Q.le_min_r.\n        apply IHl. assumption. Qed.\n\nLemma Qmin_list_spec2 l (H : ~ (l = nil)) :\n  exists a, In a l /\\ Qmin_list l == a.\nProof.\n  induction l.\n  - contradiction.\n  -\n    destruct l.\n    + simpl. exists a. split. left; reflexivity. reflexivity.\n    + assert (q :: l <> nil) by congruence.\n      apply IHl in H0. destruct H0 as [x []].\n      destruct (Qminmax.Q.min_dec a x).\n      * exists a. split. left; reflexivity. rewrite Qmin_list_cons. rewrite H1. assumption.\n      * exists x. split. right; assumption. rewrite Qmin_list_cons. rewrite H1. assumption. Qed.\n\nLemma Qmin_list_app l k : l <> [] -> k <> [] ->\n  Qmin_list (l ++ k) == Qmin (Qmin_list l) (Qmin_list k).\nProof.\n  destruct k; destruct l; try congruence; intros.\n  revert q k H0; induction l; intros.\n  - reflexivity.\n  -\n    rewrite <- app_comm_cons.\n    rewrite <- app_comm_cons.\n    rewrite Qmin_list_cons_cons.\n    rewrite Qmin_list_cons.\n    setoid_rewrite IHl; try congruence.\n    rewrite Qmin_list_cons_cons.\n    rewrite Qmin_list_cons.\n    rewrite Qminmax.Q.min_assoc. reflexivity.\nQed.\n\nInstance Qmin_list_single_proper : Proper (Qeq ==> Qeq) (fun q => Qmin_list [q]).\nProof.\n  do 2 red; intros. apply H.\nQed.\n\nInstance Qmin_list_proper : Proper (eq ==> Qeq) Qmin_list.\nProof.\n  do 2 red; intros. rewrite H. reflexivity.\nQed.\n\nLemma Qmin_list_single q : Qmin_list [q] = q.\nProof. reflexivity. Qed.\n\nInductive Qlist_eq : list Q -> list Q -> Prop :=\n| Qlist_eq_nil : Qlist_eq [] []\n| Qlist_eq_cons x y l k : x == y -> Qlist_eq l k -> Qlist_eq (x :: l) (y :: k).\nLocal Notation \"l == k\" := (Qlist_eq l k).\n\nRequire Import Classes.RelationClasses.\n\nInstance Qlist_eq_refl : Reflexive Qlist_eq.\nProof. red; intros; induction x; constructor; [reflexivity|assumption]. Qed.\nInstance Qlist_eq_sym : Symmetric Qlist_eq.\nProof. red; intros. induction H; [reflexivity|constructor; [symmetry|]; assumption]. Qed.\nInstance Qlist_eq_trans : Transitive Qlist_eq.\nProof. red. intros x. induction x; intros.\n       - inversion H; subst; assumption.\n       - destruct z.\n         + inversion H0; subst; assumption.\n         + inversion H. subst. inversion H0. subst. constructor.\n           etransitivity. eassumption. assumption.\n           apply IHx with (y:=k); assumption. Qed.\n\nInstance cons_Qlist_eq_proper : Proper (Qeq ==> Qlist_eq ==> Qlist_eq) cons.\nProof.\n  red; red; intros.\n  red; intros. constructor; assumption. Qed.\n\nInstance app_Qlist_eq_proper : Proper (Qlist_eq ==> Qlist_eq ==> Qlist_eq) (@app Q).\nProof.\n  red; red; intros.\n  red; intros. induction H.\n  - assumption.\n  - rewrite <- !app_comm_cons. constructor. assumption. assumption. Qed.\n\nInstance Qmin_list_proper2 : Proper (Qlist_eq ==> Qeq) Qmin_list.\nProof.\n  do 2 red. intros.\n  destruct H.\n  - reflexivity.\n  - induction H0.\n    + assumption.\n    + do 2 rewrite Qmin_list_cons_cons, Qmin_list_cons.\n      setoid_rewrite IHQlist_eq.\n      setoid_rewrite H0. reflexivity. 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/Qmin_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7576060900897638}}
{"text": "(* Definitions that are used by ott-generated output (when using non-expanded lists) *)\n\nRequire Import Bool.\nRequire Import List.\nSet Implicit Arguments.\n\n\n\nSection list_predicates.\nVariable (A : Type).\n\n(* Test whether a predicate [p] holds for every element of a list [l]. *)\nDefinition forall_list (p:A->bool) (l:list A) :=\n  fold_left (fun b (z:A) => b && p z) l true.\n\n(* Test whether a predicate [p] holds for some element of a list [l]. *)\nDefinition exists_list (p:A->bool) (l:list A) :=\n  fold_left (fun b (z:A) => b || p z) l false.\n\n(* Assert that a property holds for every element of a list *)\nInductive Forall_list (P:A->Prop) : list A -> Prop :=\n  | Forall_nil : Forall_list P nil\n  | Forall_cons :\n    forall x l, P x -> Forall_list P l -> Forall_list P (x::l).\n(* Assert that a property holds for some element of a list *)\nInductive Exists_list (P:A->Prop) : list A -> Prop :=\n  | Exists_head : forall x l, P x -> Exists_list P (x::l)\n  | Exists_tail : forall x l, Exists_list P l -> Exists_list P (x::l).\n\nEnd list_predicates.\nHint Constructors Forall_list Exists_list : core.\n\n\n\nSection list_mem.\n(* Functions about membership in a list, with equality between a list\n   element and a potential member being decided by [eq_dec]. *)\nVariable (A : Type).\nVariable (eq_dec : forall (a b:A), {a=b} + {a<>b}).\n\n(* Test whether [x] appears in [l]. *)\nFixpoint list_mem (x:A) (l:list A) {struct l} : bool :=\n  match l with\n  | nil => false\n  | cons h t => if eq_dec h x then true else list_mem x t\nend.\n\n(* Remove any element of [l1] that is present in [l2]. *)\nFixpoint list_minus (l1 l2:list A) {struct l1} : list A :=\n  match l1 with\n  | nil => nil\n  | cons h t =>\n    if (list_mem h l2) then list_minus t l2 else cons h (list_minus t l2)\nend.\nEnd list_mem.\n\n\n\nSection Flat_map_definition.\nVariables (A B : Type).\nVariable (f : A -> list B).\n(* This definition is almost the same as the one in the standard library of\n   Coq V8.0 or V8.1. The difference is that this version has the shape\n    fun A B f => (fix flat_map l := _)\n   while the standard library has\n    fun A B => (fix flat_map f l := _)\n   Our version has the advantage of making recursive definitions such as\n    fix foo x := match x with ... | List xs => flat_map foo xs end\n   well-founded.\n *)\nFixpoint flat_map (l:list A) {struct l} : list B :=\n  match l with\n    | nil => nil\n    | cons x t => (f x) ++ (flat_map t)\n  end.\nEnd Flat_map_definition.\n\n\n\n(* Provide helper lemmas for {{coq-equality}} homs. *)\nRequire Export Ott.ott_list_eq_dec.\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_core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7575953203507454}}
{"text": "Require Export D.\n\n\n\n(** 3 star (even__ev)  \n    Note that proving [even__ev] directly is hard.\n    You might find it easier to prove [even__ev_strong] first\n    and then prove [even__ev] using it.\n*)\n\nLemma even__ev_weak: forall n: nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  induction n. \n  Case \"n = 0\". split. intro H. apply ev_0. intro Hcontra. inversion Hcontra.\n  Case \"n = S n\". inversion IHn. split. apply H0.\n    intro HSS. apply ev_SS. unfold even in HSS. simpl in HSS. apply H. apply HSS. Qed.\n\nLemma even__ev_strong: forall n : nat, \n  (even (pred n) -> ev (pred n)) /\\ (even n -> ev n).\nProof.\n  induction n.\n  Case \"n = 0\". simpl. split. intro H. apply ev_0. intro H. apply ev_0.\n  Case \"n = S n\". simpl. apply even__ev_weak. Qed.\n\nTheorem even__ev: forall n : nat,\n  even n -> ev n.\nProof.\n  intro. apply even__ev_strong.\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/06/P10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7575953002688038}}
{"text": "(** * Lists: Working with Structured Data *)\n\n(* $Date: 2012-09-08 20:51:57 -0400 (Sat, 08 Sep 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. destruct p as (n,m). simpl. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (fst_swap_is_snd) *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as (n,m). simpl. reflexivity.  Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Lists of Numbers *)\n\n(** Generalizing the definition of pairs a little, we can\n    describe the type of _lists_ of numbers like this: \"A list is\n    either the empty list or else a pair of a number and another\n    list.\" *)\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** For example, here is a three-element list: *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** As with pairs, it is more convenient to write lists in\n    familiar programming notation.  The following two declarations\n    allow us to use [::] as an infix [cons] operator and square\n    brackets as an \"outfix\" notation for constructing lists. *)\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(** It is not necessary to fully understand these declarations,\n    but in case you are interested, here is roughly what's going on.\n\n    The [right associativity] annotation tells Coq how to parenthesize\n    expressions involving several uses of [::] so that, for example,\n    the next three declarations mean exactly the same thing: *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\n(** The [at level 60] part tells Coq how to parenthesize\n    expressions that involve both [::] and some other infix operator.\n    For example, since we defined [+] as infix notation for the [plus]\n    function at level 50,\nNotation \"x + y\" := (plus x y)\n                    (at level 50, left associativity).\n   The [+] operator will bind tighter than [::], so [1 + 2 :: [3]]\n   will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than [1\n   + (2 :: [3])].\n\n   (By the way, it's worth noting in passing that expressions like \"[1\n   + 2 :: [3]]\" can be a little confusing when you read them in a .v\n   file.  The inner brackets, around 3, indicate a list, but the outer\n   brackets are there to instruct the \"coqdoc\" tool that the bracketed\n   part should be displayed as Coq code rather than running text.\n   These brackets don't appear in the generated HTML.)\n\n   The second and third [Notation] declarations above introduce the\n   standard square-bracket notation for lists; the right-hand side of\n   the third one illustrates Coq's syntax for declaring n-ary\n   notations and translating them to nested sequences of binary\n   constructors. *)\n\n(** A number of functions are useful for manipulating lists.\n    For example, the [repeat] function takes a number [n] and a\n    [count] and returns a list of length [count] where every element\n    is [n]. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\n(** The [length] function calculates the length of a list. *)\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(** The [app] (\"append\") function concatenates two lists. *)\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\n(** Actually, [app] will be used a lot in some parts of what\n    follows, so it is convenient to have an infix operator for it. *)\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:             [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof. reflexivity.  Qed.\nExample test_app2:             nil ++ [4,5] = [4,5].\nProof. reflexivity.  Qed.\nExample test_app3:             [1,2,3] ++ nil = [1,2,3].\nProof. reflexivity.  Qed.\n\n(** Here are two smaller examples of programming with lists.\n    The [hd] function returns the first element (the \"head\") of the\n    list, while [tail] returns everything but the first\n    element.  Of course, the empty list has no first element, so we\n    must pass a default value to be returned in that case.  *)\n\nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n  | nil => default\n  | h :: t => h\n  end.\n\nDefinition tail (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => t\n  end.\n\nExample test_hd1:             hd 0 [1,2,3] = 1.\nProof. reflexivity.  Qed.\nExample test_hd2:             hd 0 [] = 0.\nProof. reflexivity.  Qed.\nExample test_tail:            tail [1,2,3] = [2,3].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, recommended (list_funs) *)\n(** Complete the definitions of [nonzeros], [oddmembers] and\n    [countoddmembers] below.  *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | O :: t => nonzeros t\n  | n :: t => n :: nonzeros t\n  end.\n\nExample test_nonzeros:            nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof. reflexivity.  Qed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => if oddb 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\nFixpoint countoddmembers (l:natlist) : nat :=\n  match l with\n  | nil => 0\n  | h :: t => if oddb h\n    then 1 + countoddmembers t\n    else countoddmembers t\n  end.\n\nExample test_countoddmembers1:    countoddmembers [1,0,3,1,4,5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers2:    countoddmembers [0,2,4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers3:    countoddmembers nil = 0.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (alternate) *)\n(** Complete the definition of [alternate], which \"zips up\" two lists\n    into one, alternating between elements taken from the first list\n    and elements from the second.  See the tests below for more\n    specific examples.\n\n    Note: one natural and elegant way of writing [alternate] will fail\n    to satisfy Coq's requirement that all [Fixpoint] definitions be\n    \"obviously terminating.\"  If you find yourself in this rut, look\n    for a slightly more verbose solution that considers elements of\n    both lists at the same time.  (One possible solution requires\n    defining a new kind of pairs, but this is not the only way.)  *)\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, _ => l2\n  | _, nil => l1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  end.\n\n\nExample test_alternate1:        alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6].\nProof. reflexivity.  Qed.\nExample test_alternate2:        alternate [1] [4,5,6] = [1,4,5,6].\nProof. reflexivity.  Qed.\nExample test_alternate3:        alternate [1,2,3] [4] = [1,4,2,3].\nProof. reflexivity.  Qed.\nExample test_alternate4:        alternate [] [20,30] = [20,30].\nProof. reflexivity.  Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Bags via Lists *)\n\n(** A [bag] (or [multiset]) is like a set, but each element can appear\n    multiple times instead of just once.  One reasonable\n    implementation of bags is to represent a bag of numbers as a\n    list. *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, 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    => 0\n  | h :: t => if beq_nat h v\n    then 1 + count v t\n    else count v t\n  end.\n\n(** All these proofs can be done just by [reflexivity]. *)\n\nExample test_count1:              count 1 [1,2,3,1,4,1] = 3.\nProof. 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  alternate.\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  s ++ [v].\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 (beq_nat (count v s) 0).\n\nExample test_member1:             member 1 [1,4,1] = true.\nProof. reflexivity.  Qed.\nExample test_member2:             member 2 [1,4,1] = false.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_more_functions) *)\n(** Here are some more bag functions for you to practice with. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t => if beq_nat h v\n    then t\n    else h :: remove_one v t\n  end.\n\nExample test_remove_one1:         count 5 (remove_one 5 [2,1,5,4,1]) = 0.\nProof. 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  | h :: t => if beq_nat h v\n    then remove_all v t\n    else h :: remove_all v t\n  end.\n\nExample test_remove_all1:          count 5 (remove_all 5 [2,1,5,4,1]) = 0.\nProof. 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  admit.\n\nExample test_subset1:              subset [1,2] [2,1,4,1] = true.\nAdmitted.\nExample test_subset2:              subset [1,2,2] [2,1,4,1] = false.\nAdmitted.\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\nTheorem bag_theorem : forall (n : nat) (s : bag),\n  count n (add n s) = S (count n s).\nProof.\n  Admitted.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\n(** Just as with numbers, simple facts about list-processing\n    functions can sometimes be proved entirely by simplification. For\n    example, the simplification performed by [reflexivity] is enough\n    for this theorem... *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity.  Qed.\n\n(** ... because the [[]] is substituted into the match position\n    in the definition of [app], allowing the match itself to be\n    simplified. *)\n\n(** Also, as with numbers, it is sometimes helpful to perform case\n    analysis on the possible shapes (empty or non-empty) of an unknown\n    list. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tail l).\nProof.\n  intros l. destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    reflexivity.  Qed.\n\n(** Here, the [nil] case works because we've chosen to define\n    [tail nil = nil]. Notice that the [as] annotation on the [destruct]\n    tactic here introduces two names, [n] and [l'], corresponding to\n    the fact that the [cons] constructor for lists takes two\n    arguments (the head and tail of the list it is constructing). *)\n\n(** Usually, though, interesting theorems about lists require\n    induction for their proofs. *)\n\n(* ###################################################### *)\n(** ** Micro-Sermon *)\n\n(** Simply reading example proofs will not get you very far!  It is\n    very important to work through the details of each one, using Coq\n    and thinking about what each step of the proof achieves.\n    Otherwise it is more or less guaranteed that the exercises will\n    make no sense. *)\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n(** Proofs by induction over datatypes like [natlist] are\n    perhaps a little less familiar than standard natural number\n    induction, but the basic idea is equally simple.  Each [Inductive]\n    declaration defines a set of data values that can be built up from\n    the declared constructors: a boolean can be either [true] or\n    [false]; a number can be either [O] or [S] applied to a number; a\n    list can be either [nil] or [cons] applied to a number and a list.\n\n    Moreover, applications of the declared constructors to one another\n    are the _only_ possible shapes that elements of an inductively\n    defined set can have, and this fact directly gives rise to a way\n    of reasoning about inductively defined sets: a number is either\n    [O] or else it is [S] applied to some _smaller_ number; a list is\n    either [nil] or else it is [cons] applied to some number and some\n    _smaller_ list; etc. So, if we have in mind some proposition [P]\n    that mentions a list [l] and we want to argue that [P] holds for\n    _all_ lists, we can reason as follows:\n\n      - First, show that [P] is true of [l] when [l] is [nil].\n\n      - Then show that [P] is true of [l] when [l] is [cons n l'] for\n        some number [n] and some smaller list [l'], assuming that [P]\n        is true for [l'].\n\n    Since larger lists can only be built up from smaller ones,\n    eventually reaching [nil], these two things together establish the\n    truth of [P] for all lists [l].  Here's a concrete example: *)\n\nTheorem app_ass : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** Again, this Coq proof is not especially illuminating as a\n    static written document -- it is easy to see what's going on if\n    you are reading the proof in an interactive Coq session and you\n    can see the current goal and context at each point, but this state\n    is not visible in the written-down parts of the Coq proof.  So a\n    natural-language proof -- one written for human readers -- will\n    need to include more explicit signposts; in particular, it will\n    help the reader stay oriented if we remind them exactly what the\n    induction hypothesis is in the second case.  *)\n\n(** _Theorem_: For all lists [l1], [l2], and [l3],\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _Proof_: By induction on [l1].\n\n   - First, suppose [l1 = []].  We must show\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n     which follows directly from the definition of [++].\n\n   - Next, suppose [l1 = n::l1'], with\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n     (the induction hypothesis). We must show\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n]]\n     By the definition of [++], this follows from\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n     which is immediate from the induction hypothesis.  []\n\n  Here is an exercise to be worked together in class: *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros l1 l2. induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** For a slightly more involved example of an inductive proof\n    over lists, suppose we define a \"cons on the right\" function\n    [snoc] like this... *)\n\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n  match l with\n  | nil    => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\n(** ... and use it to define a list-reversing function [rev]\n    like this: *)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nExample test_rev1:            rev [1,2,3] = [3,2,1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** Now let's prove some more list theorems using our newly\n    defined [snoc] and [rev].  For something a little more challenging\n    than the inductive proofs we've seen so far, let's prove that\n    reversing a list does not change its length.  Our first attempt at\n    this proof gets stuck in the successor case... *)\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    (* This is the tricky case.  Let's begin as usual by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality involving\n       [snoc], but we don't have any equations in either the\n       immediate context or the global environment that have\n       anything to do with [snoc]!\n\n       We can make a little progress by using the IH to rewrite the\n       goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAdmitted.\n\n(** So let's take the equation about [snoc] that would have\n    enabled us to make progress and prove it as a separate lemma. *)\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l. induction l as [| n' l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl. rewrite -> IHl'. reflexivity.  Qed.\n\n(** Now we can complete the original proof. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons\".\n    simpl. rewrite -> length_snoc.\n    rewrite -> IHl'. reflexivity.  Qed.\n\n(** For comparison, here are informal proofs of these two theorems:\n\n    _Theorem_: For all numbers [n] and lists [l],\n       [length (snoc l n) = S (length l)].\n\n    _Proof_: By induction on [l].\n\n    - First, suppose [l = []].  We must show\n        length (snoc [] n) = S (length []),\n      which follows directly from the definitions of\n      [length] and [snoc].\n\n    - Next, suppose [l = n'::l'], with\n        length (snoc l' n) = S (length l').\n      We must show\n        length (snoc (n' :: l') n) = S (length (n' :: l')).\n      By the definitions of [length] and [snoc], this\n      follows from\n        S (length (snoc l' n)) = S (S (length l')),\n]]\n      which is immediate from the induction hypothesis. [] *)\n\n(** _Theorem_: For all lists [l], [length (rev l) = length l].\n\n    _Proof_: By induction on [l].\n\n      - First, suppose [l = []].  We must show\n          length (rev []) = length [],\n        which follows directly from the definitions of [length]\n        and [rev].\n\n      - Next, suppose [l = n::l'], with\n          length (rev l') = length l'.\n        We must show\n          length (rev (n :: l')) = length (n :: l').\n        By the definition of [rev], this follows from\n          length (snoc (rev l') n) = S (length l')\n        which, by the previous lemma, is the same as\n          S (length (rev l')) = S (length l').\n        This is immediate from the induction hypothesis. [] *)\n\n(** Obviously, the style of these proofs is rather longwinded\n    and pedantic.  After the first few, we might find it easier to\n    follow proofs that give a little less detail overall (since we can\n    easily work them out in our own minds or on scratch paper if\n    necessary) and just highlight the non-obvious steps.  In this more\n    compressed style, the above proof might look more like this: *)\n\n(** _Theorem_:\n     For all lists [l], [length (rev l) = length l].\n\n    _Proof_: First, observe that\n       length (snoc l n) = S (length l)\n     for any [l].  This follows by a straightforward induction on [l].\n     The main property now follows by another straightforward\n     induction on [l], using the observation together with the\n     induction hypothesis in the case where [l = n'::l']. [] *)\n\n(** Which style is preferable in a given situation depends on\n    the sophistication of the expected audience and on how similar the\n    proof at hand is to ones that the audience will already be\n    familiar with.  The more pedantic style is a good default for\n    present purposes. *)\n\n(* ###################################################### *)\n(** ** [SearchAbout] *)\n\n(** We've seen that proofs can make use of other theorems we've\n    already proved, using [rewrite], and later we will see other ways\n    of reusing previous theorems.  But in order to refer to a theorem,\n    we need to know its name, and remembering the names of all the\n    theorems we might ever want to use can become quite difficult!  It\n    is often hard even to remember what theorems have been proven,\n    much less what they are named.\n\n    Coq's [SearchAbout] command is quite helpful with this.  Typing\n    [SearchAbout foo] will cause Coq to display a list of all theorems\n    involving [foo].  For example, try uncommenting the following to\n    see a list of theorems that we have proved about [rev]: *)\n\n(* SearchAbout rev. *)\n\n(** Keep [SearchAbout] in mind as you do the following exercises and\n    throughout the rest of the course; it can save you a lot of time! *)\n\n(** Also, if you are using ProofGeneral, you can run [SearchAbout]\n    with [C-c C-a C-a]. Pasting its response into your buffer can be\n    accomplished with [C-c C-;]. *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\n(** **** Exercise: 3 stars, recommended (list_exercises) *)\n(** More practice with lists. *)\n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = n :: l'\". simpl. rewrite -> IHl'. reflexivity.  Qed.\n\nTheorem rev_snoc : forall l : natlist, forall n : nat,\n  rev (snoc l n) = n :: (rev l).\nProof.\n  intros l n. induction l.\n  reflexivity.\n  simpl. rewrite -> IHl. reflexivity.  Qed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l'].\n  Case \"l = []\". reflexivity.\n  Case \"l = n : l'\".\n    simpl.\n    rewrite -> rev_snoc.\n    rewrite -> IHl'.\n    reflexivity.  Qed.\n\n(** There is a short solution to the next exercise.  If you find\n    yourself getting tangled up, step back and try to look for a\n    simpler way. *)\n\nTheorem app_ass4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros l1 l2 l3 l4.\n  rewrite -> app_ass. rewrite -> app_ass.\n  reflexivity.  Qed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros l n. induction l.\n  reflexivity.\n  simpl. rewrite -> IHl. reflexivity.  Qed.\n\nTheorem app_nil : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l. induction l.\n  reflexivity.\n  simpl. rewrite -> IHl. reflexivity.  Qed.\n\nTheorem distr_rev : forall l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2. induction l1.\n  simpl. rewrite -> app_nil. reflexivity.\n  simpl.\n  rewrite -> IHl1.\n  rewrite -> snoc_append.\n  rewrite -> snoc_append.\n  rewrite -> app_ass.\n  reflexivity.  Qed.\n\n(** An exercise about your implementation of [nonzeros]: *)\n\nLemma nonzeros_length : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1.\n    simpl. reflexivity.\n    destruct n.\n      simpl. rewrite -> IHl1. reflexivity.\n      simpl. rewrite -> IHl1. reflexivity.  Qed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\n(** **** Exercise: 2 stars, recommended (list_design) *)\n(** Design exercise:\n     - Write down a non-trivial theorem involving [cons]\n       ([::]), [snoc], and [append] ([++]).\n     - Prove it. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bag_proofs) *)\n(** If you did the optional exercise about bags above, here are a\n    couple of little theorems to prove about your definitions. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. 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.\n    reflexivity.\n    destruct n.\n      simpl. rewrite -> ble_n_Sn. reflexivity.\n      simpl. rewrite -> IHs. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (bag_count_sum) *)\n(** Write down an interesting theorem about bags involving the\n    functions [count] and [sum], and prove it.*)\n\n(** FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\nThere is a hard way and an easy way to solve this exercise.\n*)\n\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.  Qed.\n\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Options *)\n\n(** Here is another type definition that is often useful in\n    day-to-day programming: *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** One use of [natoption] is as a way of returning \"error\n    codes\" from functions.  For example, suppose we want to write a\n    function that returns the [n]th element of some list.  If we give\n    it type [nat -> natlist -> nat], then we'll have to return some\n    number when the list is too short! *)\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => index_bad (pred n) l'\n               end\n  end.\n\n(** On the other hand, if we give it type [nat -> natlist ->\n    natoption], then we can return [None] when the list is too short\n    and [Some a] when the list has enough members and [a] appears at\n    position [n]. *)\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => index (pred n) l'\n               end\n  end.\n\nExample test_index1 :    index 0 [4,5,6,7]  = Some 4.\nProof. reflexivity.  Qed.\nExample test_index2 :    index 3 [4,5,6,7]  = Some 7.\nProof. reflexivity.  Qed.\nExample test_index3 :    index 10 [4,5,6,7] = None.\nProof. reflexivity.  Qed.\n\n(** This example is also an opportunity to introduce one more\n    small feature of Coq's programming language: conditional\n    expressions... *)\n\nFixpoint index' (n:nat) (l:natlist) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a else index' (pred n) l'\n  end.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the boolean type\n    is not built in, Coq actually allows conditional expressions over\n    _any_ inductively defined type with exactly two constructors.  The\n    guard is considered true if it evaluates to the first constructor\n    in the [Inductive] definition and false if it evaluates to the\n    second. *)\n\n(** The function below pulls the [nat] out of a [natoption], returning\n    a supplied default in the [None] case. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** Exercise: 2 stars (hd_opt) *)\n(** Using the same idea, fix the [hd] function from earlier so we don't\n   have to pass a default element for the [nil] case.  *)\n\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n  | nil    => None\n  | h :: _ => Some h\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nProof. reflexivity.  Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nProof. reflexivity.  Qed.\n\nExample test_hd_opt3 : hd_opt [5,6] = Some 5.\nProof. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (option_elim_hd) *)\n(** This exercise relates your new [hd_opt] to the old [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_opt l).\nProof.\n  intros l default. destruct l.\n    reflexivity.\n    simpl. reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (beq_natlist) *)\n(** Fill in the definition of [beq_natlist], which compares\n    lists of numbers for equality.  Prove that [beq_natlist l l]\n    yields [true] for every list [l]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | nil, _   => false\n  | _, nil   => false\n  | h1 :: t1, h2 :: t2 => andb (beq_nat h1 h2) (beq_natlist t1 t2)\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. induction l as [| h l'].\n    Case \"l = []\". reflexivity.\n    Case \"l = cons\".\n      simpl.\n      rewrite <- IHl'.\n      rewrite <- beq_nat_refl.\n      simpl. reflexivity.  Qed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Extended Exercise: Dictionaries *)\n\n(** As a final illustration of how fundamental data structures\n    can be defined in Coq, here is the declaration of a simple\n    [dictionary] data type, using numbers for both the keys and the\n    values stored under these keys.  (That is, a dictionary represents\n    a finite map from numbers to numbers.) *)\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n  | empty  : dictionary\n  | record : nat -> nat -> dictionary -> dictionary.\n\n(** This declaration can be read: \"There are two ways to construct a\n    [dictionary]: either using the constructor [empty] to represent an\n    empty dictionary, or by applying the constructor [record] to\n    a key, a value, and an existing [dictionary] to construct a\n    [dictionary] with an additional key to value mapping.\" *)\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n  (record key value d).\n\n(** Here is a function [find] that searches a [dictionary] for a\n    given key.  It evaluates evaluates to [None] if the key was not\n    found and [Some val] if the key was mapped to [val] in the\n    dictionary. If the same key is mapped to multiple values, [find]\n    will return the first one it finds. *)\n\nFixpoint find (key : nat) (d : dictionary) : natoption :=\n  match d with\n  | empty         => None\n  | record k v d' => if (beq_nat key k) then (Some v) else (find key d')\n  end.\n\n(** **** Exercise: 1 star (dictionary_invariant1) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant1 : forall (d : dictionary) (k v: nat),\n  (find k (insert k v d)) = Some v.\nProof.\n  intros d k v.\n  simpl.\n  rewrite <- beq_nat_refl.\n  reflexivity.  Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\n\nTheorem dictionary_invariant2 : forall (d : dictionary) (m n o: nat),\n  (beq_nat m n) = false -> (find m d) = (find m (insert n o d)).\nProof.\n  intros d m n o.\n  intros H.\n  simpl.\n  rewrite -> H.\n  reflexivity.  Qed.\n(** [] *)\n\nEnd Dictionary.\n\nEnd NatList.\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.757497577600433}}
{"text": "Set Implicit Arguments.\nRequire Import Arith.\n\n  (* factorial *)\n\n  Definition state : Set := nat * nat.     (* (n, a) *)\n\n  Inductive init n0 : state -> Prop :=\n    start : init n0 (n0, 1).\n  \n  Inductive step : state -> state -> Prop :=\n    step0 : forall n a, n > 0 -> step (n, a) (n - 1, a * n).\n\n  (*\n   * Specification -- program returns `fact n0`\n   *  (where n0 is the input, i.e. initial value of n)\n   *)\n  Definition spec n0 s :=\n    match s with\n      (0, a) => a = fact n0\n    | _ => True\n    end.\n\n  Print fact.  (* `fact` is defined in the Arith library *)\n  \n\n  (* General Definition *)\n  Section ReflexiveTransitiveClosureDef.\n\n    Variable D : Set.\n    Variable R : D -> D -> Prop.\n\n    Inductive tc : D -> D -> Prop :=\n      tc_refl : forall s, tc s s\n    | tc_step : forall s u t, R s u -> tc u t -> tc s t.\n\n  End ReflexiveTransitiveClosureDef.\n\n  Check tc.\n  Print Implicit tc.\n\n  \n  Theorem spec_holds n0 s0 s : init n0 s0 -> tc step s0 s -> spec n0 s.\n  Proof.\n    intros.\n    induction H0.\n    - admit.\n    - apply IHtc.\nAbort.\n  \n\n\n\n\n\n\n  \n  Definition inv n0 s :=\n    match s with\n      (n, a) => a * fact n = fact n0\n    end.\n\n  Lemma inv_inv n0 s0 s : init n0 s0 -> tc step s0 s -> inv n0 s.\n  Proof.\n    intros. induction H0.\n    - admit.\n    - apply IHtc.\n  Abort.\n\n\n\n    \n\n\n\n\n    \n  Lemma inv_inv' n0 s0 s : inv n0 s0 -> tc step s0 s -> inv n0 s.\n  Proof.\n    intros Inv Reach. induction Reach.\n    - assumption.\n    - apply IHReach.\n      destruct H.\n      destruct n.\n      + inversion H.\n      + simpl. unfold inv in Inv.\n        rewrite Nat.sub_0_r.\n        rewrite <- Nat.mul_assoc.\n        assumption.\n  Qed.\n\n\n  Lemma inv_inv n0 s0 s : init n0 s0 -> tc step s0 s -> inv n0 s.\n  Proof.\n    intro Init.\n    apply inv_inv'.\n    unfold inv. destruct Init.\n    firstorder.\n  Qed.\n\n  Theorem spec_holds n0 s0 s : init n0 s0 -> tc step s0 s -> spec n0 s.\n  Proof.\n    intros.\n    enough (inv n0 s).\n    - destruct s.\n      unfold spec.\n      destruct n.\n      destruct H1.\n      + firstorder.\n      + constructor.\n    - eapply inv_inv.\n      eassumption.\n      assumption.\n  Qed.", "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/demo-factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7574975622158181}}
{"text": "(** * Tutoriel 1 - Prouver avec Coq : Logique du premier ordre *)\n\n(** Dans cette feuille, nous simulons la logique du premier ordre \n    dans le cadre plus riche de la logique de Coq.\n    À cet effet, nous déclarons un type [T] pour les termes, un prédicat \n    unaire [P], une proposition [Q], et une relation [R]. *)\n\nVariable T : Type.\nVariable P : T -> Prop.\nVariable Q : Prop.\nVariable R : T -> T -> Prop.\n\n(** ** I. Quantifications universelle et existentielle *)\n\n(** Les tactiques [intro] et [apply] sont utilisées également pour raisonner\n    sur les quantifications universelles, tandis que les tactiques [exists]\n    et [destruct] sont utilisées pour les quantifications existentielles. *)\n\nGoal (exists x:T, forall y:T, R x y)\n  -> (forall y:T, exists x:T, R x y).\nProof.\n  intros H y.\n  destruct H.\n  exists x.\n  apply H.\nQed.\n\nGoal (exists x:T, P x \\/ Q) -> ((exists x:T, P x) \\/ Q).\nProof.\n  intro H. destruct H. destruct H.\n   + left.  exists x. exact H.\n   + right. exact H.\nQed.\n\n(** *** Exercice 1 - A vous de jouer ! *)\n\nLemma exists_not_forall : forall P : nat -> Prop,\n(exists n, P n) ->  ~(forall n,~ (P n)).\nProof.\nintros P H. unfold not. intro Hn. destruct H. apply Hn with (n:=x). exact H.\nQed.\n\n(** Note : Ici aussi, l'ordre supérieur a été utilisé. *)\n\n(** *** Exercice 2 - A vous de jouer ! *)\n\n(** Pour le résultat suivant, nous devons être capable d'introduire une\n    existentielle avec un terme arbitraire. Ceci n'est pas autorisé dans Coq,\n    où les types peuvent être vides. Nous postulons donc l'existence de\n    au moins un élément dans [T]. *)\n\nVariable a : T.\n\nGoal ((exists x:T, P x) \\/ Q) -> (exists x:T, P x \\/ Q).\nProof.\nintros H. destruct H. destruct H. exists x. left. exact H. exists a. right. exact H.\nQed.\n\n(** ** II. Egalité *)\n\n(** L'égalité étant réflexive, la tactique [reflexivity] permet de clore\n    un but lorsque les 2 éléments à gauche et à droite d'une égalité sont\n    égaux syntaxiquement.\n\n    De plus, la tactique [rewrite] permet d'utiliser une égalité, \n    c'est-à-dire de réécrire x en y grâce à x = y.\n    Pour réécrire y en x grâce à x = y, il faut utiliser la tactique \n    [rewrite <-]. *)\n\nVariable f : T -> T.\n\nLemma eq_arg : forall x y : T, x = y -> f x = f y.\nProof.\n  intros x y Heq.\n  rewrite Heq.\n  reflexivity.\nQed.\n\nGoal forall x y : T, x = y -> P y -> P x.\nProof.\n  intros x y Heq H.\n  rewrite Heq.\n  exact H.\nQed.\n\nGoal forall x y : T, forall z:T,\n  x = y -> f y = z -> P (f x) -> P z.\nProof.\n  intros x y z Hxy Hfyz H.\n  rewrite <- Hxy in Hfyz.\n  rewrite Hfyz in H.\n  exact H.\nQed.\n\n(** *** Exercice 3 - Symétrie et transitivité de l'égalité *)\n\n(** La symétrie et la transitivité sont des conséquences du principe \n    de substitution incarné par la tactique de [rewrite] : prouvez-le ! *)\n\nLemma symmetry : forall x y : T, x = y -> y = x.\nProof.\nintros x y Eq. rewrite <- Eq. reflexivity.\nQed.\n\nLemma transitivity : forall x y z : T, x = y -> y = z -> x = z.\nProof.\nintros x y z Eq1 Eq2. rewrite <- Eq1 in Eq2. exact Eq2.\nQed.\n\n(** A présent, vous avez le droit d'utiliser la tactique [symmetry]\n    pour échanger les 2 membres d'une égalité. *)\n\n(** *** Exercice 4 - Fonctions *)\n\n(** Ici, nous définissons une nouvelle sorte de termes, et diverses\n    propriétés de fonctions sur ces termes.\n    Démontrez le théorème en guise d'exercice. *)\n\nModule Functions.\n\n  Variable A : Type.\n\n  Definition injective (f:A->A) :=\n    forall x:A, forall y:A, f x = f y -> x = y.\n\n  Definition surjective (f:A->A) :=\n    forall x:A, exists y:A, x = f y.\n\n  Definition bijective (f:A->A) := injective f /\\ surjective f.\n\n  Definition involutive (f:A->A) := forall x:A, f (f x) = x.\n\n  Theorem inv_bij : forall (f:A->A), involutive f -> bijective f.\n  Proof.\n  intros f HypInv. split.\n  + intros x y HypEq. destruct (HypInv x). destruct (HypInv y). rewrite HypEq. reflexivity.\n  + intro x. exists (f x). rewrite HypInv. reflexivity.\nQed.\n\nEnd Functions.\n\n(** ** III. Exercice avancé *)\n\n(** *** Exercice 5 - Le paradoxe du buveur (Drinker's paradox) *)\n\n(** Comme exercice avancé (probablement pour la prochaine fois), prouvez que\n    la formule du buveur tient, en utilisant un raisonnement classique et en\n    en supposant que l'univers des termes n'est pas vide. *)\n\nModule Drinker.\n\n  (** Supposons un bar non vide, et un prédicat indiquant\n      quelles personnes dans le bar boivent. *)\n\n  Variable Person : Type.\n  Variable p : Person.\n  Variable Drinks : Person -> Prop.\n\n  (** Vous pouvez utiliser n'importe lequel des deux axiomes équivalents. *)\n\n  Axiom RAA : forall P:Prop, ~~P -> P.\n  Axiom LEM : forall P:Prop, P \\/ ~P.\n\n  (** Vous allez probablement vouloir utiliser [LEM] en premier,\n      mais sachez que l'utilisation de seulement [RAA] amène à plus\n      de difficulté. *)\n\n  Goal exists x:Person, Drinks x -> forall y:Person, Drinks y.\n  Proof.\n    apply RAA. unfold not. intro H.\n\n\nEnd Drinker.\n\n(** Merci à David Baelde et Catherine Dubois. *)", "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/TD1_B_prouver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7574185432167162}}
{"text": "(** * 6.512 Formal Reasoning About Programs, Spring 2023 - Pset 4 *)\n\n\nRequire Coq816.\nRequire Import Frap.\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 lot less guided than previous assignments: you will need to prove multiple 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.\n\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.\n\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 precondition. 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": "spring23", "sha": "10355d5a1cee8464cdd3722efa1fd58527c8a4d2", "save_path": "github-repos/coq/mit-frap-spring23", "path": "github-repos/coq/mit-frap-spring23/spring23-10355d5a1cee8464cdd3722efa1fd58527c8a4d2/pset04_BSTs/Pset4Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7574185373632419}}
{"text": "Require Import Graph.\nRequire Import Helper.\nRequire Import Wellfounded.\nRequire Import Coq.Lists.ListDec.\nRequire Import Omega.\n\n\nModule PathTheories  (O: UsualOrderedType)(S: FSetInterface.Sfun O)(G: Graph O S).\n\n\n  Import G.\n\n(*There are a lot of essentially equivalent definitions of being a path in here. The only ones I use\n  are [path_list_ind] and [path_list_rev], which are also the most general, so we can get rid of the others*)\n  \n\n  Inductive path : graph -> vertex -> vertex -> Prop :=\n  | p_start : forall g u v,\n    contains_edge g u v = true -> path g u v\n  | p_continue: forall g u v w,\n    path g u w ->\n    contains_edge g w v = true ->\n    path g u v.\n\n  Inductive path' : graph -> vertex -> vertex -> Prop :=\n  | p_start' : forall g u v,\n    contains_edge g u v = true -> path' g u v\n  | p_continue': forall g u v w,\n    contains_edge g u w = true ->\n    path' g w v ->\n    path' g u v.\n\n  Lemma path_trans: forall g u v w,\n    path g u v ->\n    path g v w ->\n    path g u w.\n  Proof.\n    intros. induction H0.\n    - eapply p_continue. apply H. apply H0.\n    - eapply p_continue. apply IHpath. apply H. apply H1.\n  Qed.\n\n  Lemma path'_trans: forall g u v w,\n    path' g u v ->\n    path' g v w ->\n    path' g u w.\n  Proof.\n    intros. induction H. \n    - eapply p_continue'. apply H. apply H0.\n    - eapply p_continue'. apply H. apply IHpath'. apply H0. \n  Qed.\n\n  Lemma path_path': forall g v u,\n    path g u v <-> path' g u v.\n  Proof.\n    intros. split; intros H; induction H.\n    - apply p_start'. apply H.\n    - eapply path'_trans. apply IHpath. apply p_start'. apply H0.\n    - apply p_start. apply H.\n    - eapply path_trans. apply p_start. apply H. apply IHpath'.\nQed.\n\n  Inductive path_with: graph -> vertex -> vertex -> (vertex -> bool) -> Prop :=\n    |  pw_start : forall g u v f,\n      contains_edge g u v = true ->\n      f v = true ->\n      path_with g u v f\n    | pw_continue: forall g u v w f,\n      path_with g u w f ->\n      f v = true ->\n      contains_edge g w v = true ->\n      path_with g u v f.\n\n  Inductive path_list_ind: graph -> vertex -> vertex -> (vertex -> bool) -> list vertex -> Prop :=\n    | pl_start : forall g u v f,\n      contains_edge g u v = true ->\n      f v = true ->\n      path_list_ind g u v f nil\n    | pl_continue: forall g u v w f l,\n      path_list_ind g u w f l ->\n      f v = true ->\n      contains_edge g w v = true ->\n      path_list_ind g u v f (w :: l).\n\nFixpoint path_list_rev (g: graph) (u v: vertex) (l: list vertex) : bool :=\n  match l with\n  | nil => G.contains_edge g u v\n  | x :: tl => G.contains_edge g x v && path_list_rev g u x tl\n  end.\n\nLemma path_list_ind_rev: forall g u v l f,\n  path_list_ind g u v f l <-> (path_list_rev g u v l = true /\\ (forall y, In y l -> f y = true) /\\ f v = true).\nProof.\n  intros. split; intros. induction H.\n  - simpl in *. split. apply H. split. intros. destruct H1. apply H0.\n  - simpl. destruct IHpath_list_ind. destruct H3. split. rewrite H1. rewrite H2. reflexivity.\n    split. intros. destruct H5. subst. apply H4. apply H3. apply H5. apply H0.\n  - generalize dependent v. induction l; intros.\n    + destruct H. destruct H0. simpl in *. apply pl_start. apply H. apply H1.\n    + simpl in *. apply pl_continue. apply IHl. destruct H. destruct H0. split. rewrite andb_true_iff in H.\n      apply H. split. intros. apply H0. right. apply H2. apply H0. left. reflexivity. destruct H.\n      destruct H0. apply H1. destruct H. rewrite andb_true_iff in H. destruct H. apply H.\nQed. \n\n  Lemma path_with_implies_path: forall g u v f,\n    path_with g u v f ->\n    path g u v.\n  Proof.\n    intros. induction H.\n    - apply p_start. apply H.\n    - eapply p_continue. apply IHpath_with. apply H1.\n  Qed.\n\n  Lemma path_path_list_rev: forall g u v,\n    path g u v <-> (exists l, path_list_rev g u v l = true).\n  Proof.\n    intros. split; intros. induction H.\n    - exists nil. simpl. apply H.\n    - destruct_all. exists (w :: x). simpl. simplify.\n    - destruct H. generalize dependent v. induction x; intros.\n      + simpl in H. constructor. apply H.\n      + simpl in H. simplify. eapply p_continue. apply IHx. apply H1. apply H0.\n  Qed.\n\n  Definition cyclic (g: graph) := exists v, path g v v.\n\n  (*There is a cycle that does not consist only of a single vertex*)\n  Definition nontrivial_cyclic (g: graph) := exists v l, (exists x, x <> v /\\ In x l)\n   /\\ path_list_rev g v v l = true.\n\n  Definition acyclic (g: graph):= ~ exists v, path g v v.\n\n  Definition acyclic' (g: graph) := forall v, ~path g v v.\n\n  Lemma acylic_no_nontrivial: forall g,\n    acyclic g ->\n    ~nontrivial_cyclic g.\n  Proof.\n   intros. intro.  unfold acyclic in H. unfold nontrivial_cyclic in H0. destruct_all.\n    apply H. exists x. rewrite path_path_list_rev. exists x0. apply H1.\n  Qed.\n\n  Lemma acyclic_equiv: forall g,\n    acyclic' g <-> acyclic g.\n  Proof.\n    intros. split; intros; unfold acyclic in *; unfold acyclic' in *. intro. destruct H0. apply (H x). apply H0.\n    intros. intro. apply H. exists v. apply H0.\n  Qed.\n\n  Lemma alt_acyclic: forall g,\n    acyclic g <-> (forall u v, path g u v -> u <> v).\n  Proof.\n    intros. split; intros.\n    - intro. subst. unfold acyclic in H. apply H. exists v. apply H0.\n    - unfold acyclic. intro. destruct H0. apply H in H0. contradiction.\n  Qed.\n\n(** ** Some results about paths **)\n  Lemma path_app: forall g u v a l1 l2,\n    path_list_rev g u v (l1 ++ a :: l2) = true <->\n    path_list_rev g a v l1 = true /\\ path_list_rev g u a l2 = true.\n  Proof.\n    intros. split; intros. generalize dependent v. generalize dependent l2. induction l1; intros.\n    - simpl in H. simpl. rewrite andb_true_iff in H. apply H.\n    - simpl in *. simplify; apply IHl1 in H1; destruct H1; assumption.\n    - destruct_all. generalize dependent v. generalize dependent a. revert l2. induction l1; intros.\n      + simpl in *. simplify.\n      + simpl in *. simplify.\n  Qed.\n\n  Lemma path_end: forall u v l x g l1,\n    l = l1 ++ x :: nil ->\n    path_list_rev g u v l = true <-> path_list_rev g x v l1 = true /\\ G.contains_edge g u x = true.\n  Proof.\n    intros. subst. split; intros.\n    - apply path_app in H. simpl in H. apply H. \n    - apply path_app. simpl. apply H.\nQed.\n\n  (*If there is a path from u to v, then there is a path from u to v that does not contain u as an intermediate\n    vertex*)\n  Lemma path_start_unique: forall g u v l,\n    path_list_rev g u v l = true ->\n    exists l1, path_list_rev g u v l1 = true /\\ ~In u l1.\n  Proof.\n    intros. destruct (in_dec O.eq_dec u l).\n    - apply in_split_app_fst in i. destruct_all. rewrite H0 in H.\n      apply path_app in H. destruct H. exists x. split. apply H.\n      intro. apply H1 in H3. contradiction. apply O.eq_dec.\n    - exists l. split; assumption.\n  Qed. \n    \n  Lemma path_implies_in_graph: forall g u v l,\n    path_list_rev g u v l = true ->\n    G.contains_vertex g u = true /\\ G.contains_vertex g v = true /\\ (forall x, In x l -> G.contains_vertex g x = true).\n  Proof.\n    intros. generalize dependent v. induction l; intros.\n    - simpl in H. split. eapply G.contains_edge_1. apply H. split. eapply G.contains_edge_2. apply H.\n      intros. inversion H0.\n    - simpl in H. simplify. apply IHl in H1. simplify. eapply G.contains_edge_2. apply H0.\n      simpl in H. destruct H. subst. eapply G.contains_edge_1. apply H0. apply IHl in H1.\n      destruct_all. apply H3. apply H.\n  Qed.\n\n\n(* Results about cycle *)\nLemma any_cycle: forall g u v l,\n  path_list_rev g u u l = true ->\n  In v l ->\n  exists l1, path_list_rev g v v l1 = true /\\ In u l1 /\\ (forall x, x <> u -> x <> v -> In x l <-> In x l1).\nProof.\n  intros. apply in_split_app_fst in H0. destruct_all.\n  rewrite H0 in H. apply path_app in H. destruct_all.\n  exists (x0 ++ u :: x). split. eapply path_app; simplify.\n  intros. split. solve_in. split; intros.  subst. apply in_app_or in H5. destruct H5. solve_in.\n  simpl in H0. destruct H0. subst. contradiction. solve_in.\n  subst. apply in_app_or in H5. destruct H5. solve_in. simpl in H0. destruct H0.\n  subst. contradiction. solve_in.\n  apply O.eq_dec.\nQed.\n\nLemma path_remove_cycle: forall g u v w l1 l2 l3,\n  path_list_rev g u v (l1 ++ w :: l2 ++ w :: l3) = true ->\n  path_list_rev g u v (l1 ++ w :: l3) = true.\nProof.\n  intros. apply path_app in H. destruct_all. apply path_app in H0. destruct_all.\n  apply path_app. simplify.\nQed.\n\n\nLemma path_no_end: forall g u v l,\n  path_list_rev g u v l = true ->\n  exists l, path_list_rev g u v l = true /\\ ~In v l.\nProof.\n  intros. destruct (in_dec O.eq_dec v l).\n    - apply in_split_app_snd in i. destruct_all. rewrite H0 in H.\n      apply path_app in H. destruct H. exists x0. split. apply H2.\n      intro. apply H1 in H3. contradiction. apply O.eq_dec.\n    - exists l. split; assumption.\nQed.\n\n(*If there is a path, then there is a path with no duplicates*)\nLemma path_no_dups: forall g u v l,\n  path_list_rev g u v l = true ->\n  exists l1, path_list_rev g u v l1 = true /\\ NoDup l1 /\\ ~In u l1 /\\  ~In v l1 /\\ \n  (forall x, In x l1 -> In x l). \n  Proof.\n    intros. induction l using (well_founded_induction\n                       (wf_inverse_image _ nat _ (@length _)\n                          PeanoNat.Nat.lt_wf_0)).\n    destruct (NoDup_dec (O.eq_dec) l).\n    - destruct (In_dec O.eq_dec u l).\n      + eapply in_split_app_fst in i. destruct_all. clear H2. subst.\n        apply path_app in H. destruct H. specialize (H0 x). destruct H0 as [l]. \n        rewrite app_length. simpl. assert (forall n m, n < n + S(m)) by (intros; omega). apply H0.\n        apply H. exists l. simplify. apply O.eq_dec.\n      + destruct (In_dec O.eq_dec v l).\n        * eapply in_split_app_fst in i. destruct_all; subst. clear H2. apply path_app in H.\n          destruct H. specialize (H0 x0). destruct H0 as [l]. rewrite app_length. simpl.\n          assert (forall n m, n < m + S(n)) by (intros; omega). apply H0. apply H1. exists l.\n          simplify. apply O.eq_dec.\n        * exists l. simplify.\n    - rewrite no_no_dup in n. destruct_all. subst. \n      apply path_remove_cycle in H. specialize (H0 (x0 ++ x :: x2)). destruct H0 as [l].\n      repeat(rewrite app_length; simpl). omega. apply H. exists l. simplify. apply H5 in H4.\n      apply in_app_or in H4. destruct H4. apply in_or_app. left. apply H4. simpl in H4.\n      destruct H4. subst. solve_in. solve_in. apply O.eq_dec.\nQed.\n\n(*A crucial lemma for proving the correctness of cycle detection: If there is a cycle that does not\n  consist solely of the same vertex, then there is a cycle with no duplicates\nTODO: see if I can prove this from path_no_dups*)\nLemma cycle_no_dups_strong: forall g u l,\n  path_list_rev g u u l = true ->\n  (exists w, In w l /\\ w <> u) ->\n  exists l1, path_list_rev g u u l1 = true /\\ NoDup l1 /\\ ~In u l1 /\\ l1 <> nil /\\ (forall x, In x l1 -> In x l).\nProof.\n  intros. induction l using (well_founded_induction\n                     (wf_inverse_image _ nat _ (@length _)\n                        PeanoNat.Nat.lt_wf_0)). destruct_all. destruct l.\n  inversion H0. destruct (In_dec O.eq_dec u (v ::l)).\n  apply in_split_app_fst in i. destruct_all.\n  rewrite H3 in H. apply path_app in H. destruct_all. rewrite H3 in H0.\n  apply in_app_or in H0. destruct H0. \n  assert (exists l1 : list vertex,\n       path_list_rev g u u l1 = true /\\\n       NoDup l1 /\\ ~ In u l1 /\\ l1 <> nil /\\ (forall x : vertex, In x l1 -> In x x0)).\n  apply H1. rewrite H3. rewrite app_length. simpl.\n  assert (forall n m, n < n + S(m)). intros. omega. apply H6.\n  apply H. exists x. split; assumption.\n  destruct_all. exists x2. repeat(split; try(assumption)). intros. rewrite H3.\n  apply H10 in H11. solve_in.\n  simpl in H0. destruct H0. subst. contradiction. \n  assert ( exists l1 : list vertex,\n       path_list_rev g u u l1 = true /\\\n       NoDup l1 /\\ ~ In u l1 /\\ l1 <> nil /\\ (forall x : vertex, In x l1 -> In x x1)).\n  apply (H1 x1). rewrite H3. rewrite app_length. simpl.\n  assert (forall n m, n < m + S(n)). intros. omega. apply H6.\n  apply H5. exists x. split; assumption. destruct_all.\n  exists x2. repeat(split; try(assumption)). intros.\n  apply H10 in H11. rewrite H3. solve_in. apply O.eq_dec.\n  destruct (NoDup_dec (O.eq_dec) (v :: l)).\n  exists (v :: l). split; try(split); try(assumption). split. apply n. split.\n  intro. inversion H3. intros. apply H3.\n  rewrite no_no_dup in n0. destruct_all. rewrite H3 in H.\n  apply path_remove_cycle in H. rewrite H3 in H0. \n  rewrite H3 in n. assert (exists l1 : list vertex,\n       path_list_rev g u u l1 = true /\\\n       NoDup l1 /\\ ~ In u l1 /\\ l1 <> nil /\\ (forall x : vertex, In x l1 -> In x (x1 ++ x0 :: x3))).\n  apply H1.  rewrite H3.\n  repeat(rewrite app_length; simpl). omega. apply H. exists x0.\n  split. solve_in. intro. subst. apply n. solve_in. destruct_all. exists x4.\n  repeat(split; try(assumption)). intros. rewrite H3. apply H8 in H9.\n  apply in_app_or in H9. simpl in H9. destruct H9. apply in_or_app. left. apply H9.\n  destruct H9. subst. solve_in. solve_in.  apply O.eq_dec.\nQed. \n\n(** Decidability of [path] **)\n\n(*We want to be able to use the existence of a path as a boolean in other functions, so we need to show that\n  it is decidable. To do this, we give a (very inefficient) algorithm to find a path and prove it correct.\n  But we are only concerned with existence so its efficiency is not important*)\n\n(*A terrible function to find if a path of length <= n between two vertices exists*)\nFixpoint path_of_length g (u v : G.vertex) (n: nat) {struct n} : bool :=\n  match n with\n  | 0 => G.contains_edge g u v\n  | S(m) => if G.contains_edge g u v then true else\n  fold_right (fun x t => if path_of_length g u x m && G.contains_edge g x v then true else t) false \n  (G.list_of_graph g)\n  end.\n\n(*If this function returns true, there is a path between two vertices *)\nLemma path_of_length_implies_path: forall g u v n,\n  path_of_length g u v n = true -> path g u v.\nProof.\n  intros. generalize dependent v. induction n; intros.\n  - simpl in H. constructor. apply H.\n  - simpl in *. destruct (G.contains_edge g u v) eqn : ?.\n    + apply p_start. apply Heqb.\n    + assert (forall l, fold_right\n      (fun (x : G.vertex) (t : bool) => if path_of_length g u x n && G.contains_edge g x v then true else t) false\n      l = true-> exists x, In x l /\\ path_of_length g u x n = true /\\ G.contains_edge g x v = true). {\n      intros. induction l; simpl in *.\n      * inversion H0.\n      * destruct (path_of_length g u a n && G.contains_edge g a v) eqn : ?.\n        -- simplify. exists a. simplify. \n        -- apply IHl in H0. destruct_all. exists x. simplify. }\n      apply H0 in H. destruct_all. eapply p_continue. apply IHn. apply H1. apply H2.\nQed. \n\nLemma path_of_size_implies_function: forall g u v l n,\n  length l <= n ->\n  path_list_rev g u v l = true -> path_of_length g u v n = true.\nProof.\n  intros. generalize dependent v. revert u. generalize dependent n. induction l; simpl in *; intros.\n  - destruct n. simpl. apply H0. simpl. rewrite H0. reflexivity.\n  - simplify. destruct n. omega. assert (length l <= n) by omega. clear H.\n    simpl. destruct (G.contains_edge g u v) eqn : ?. reflexivity.\n      assert (forall a l', In a l' ->\n      path_of_length g u a n = true ->\n      G.contains_edge g a v = true ->\n      fold_right\n  (fun (x : G.vertex) (t : bool) => if path_of_length g u x n && G.contains_edge g x v then true else t)\n  false l' = true). { intros. induction l'; simpl in *.\n  - destruct H.\n  - destruct H. subst. rewrite H3. rewrite H4. simpl. reflexivity. apply IHl' in H. \n    destruct (path_of_length g u a1 n && G.contains_edge g a1 v). reflexivity. apply H. }\n    apply (H a). apply G.list_of_graph_1. eapply G.contains_edge_1. apply H1. apply IHl. apply H0. apply H2.\n    apply H1. \nQed.\n\n(*If there is a path, then there is a path at most as large as the number of vertices in the graph (because\n  there is a path with no duplicates and every vertex is in the graph*)\nLemma path_shorter_than_graph_size: forall g u v l,\n  path_list_rev g u v l = true ->\n  exists l', path_list_rev g u v l' = true /\\ length l' <= length(G.list_of_graph g).\nProof.\n  intros. apply path_no_dups in H. destruct_all. \n  assert (forall a, In a x -> In a (G.list_of_graph g)). intros.\n  apply path_implies_in_graph in H. destruct_all. apply H6 in H4. apply G.list_of_graph_1. apply H4.\n  exists x. split. apply H. eapply NoDup_incl_length. apply H0. unfold incl. apply H4.\nQed.\n\nLemma path_equiv: forall g u v,\n  path g u v <-> path_of_length g u v (length(G.list_of_graph g)) = true.\nProof.\n  intros. split; intros.\n  - rewrite path_path_list_rev in H. destruct H. apply path_shorter_than_graph_size in H.\n    destruct_all. eapply path_of_size_implies_function. apply H0. apply H.\n  - eapply path_of_length_implies_path. apply H.\nQed.\n\nLemma path_dec: forall g u v,\n  {path g u v} + {~path g u v}.\nProof.\n  intros. destruct (path_of_length g u v (length(G.list_of_graph g))) eqn : ?.\n  left. apply path_equiv; assumption.\n  right. intro. apply path_equiv in H. rewrite H in Heqb. inversion Heqb.\nQed.\n\nLemma path_transpose: forall g u v,\n  path g u v <-> path (G.get_transpose g) v u.\nProof.\n  intros. split; intros.\n  - induction H.\n    + constructor. rewrite <- G.transpose_edges. apply H.\n    + eapply path_trans. apply p_start. rewrite <- G.transpose_edges. apply H0. apply IHpath.\n  - remember (get_transpose g) as gt. induction H; subst.\n    + apply G.transpose_edges in H. constructor. apply H.\n    + eapply path_trans. apply p_start. apply G.transpose_edges. apply H0. apply IHpath. reflexivity.\nQed.\n\n\n  \n\n\nEnd PathTheories.", "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/Path.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658464, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.757373435867741}}
{"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 f_id.\n  intros b.\n  rewrite f_id.\n  rewrite f_id.\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. induction b.\n    - induction c.\n      + simpl. intro t_t. exact t_t.\n      + simpl. intro f_t. rewrite f_t. reflexivity.\n    - simpl. intro f_c. exact f_c.\nAdmitted.\n\nModule NatPlayground.\nInductive binary_nat : Type :=\n| O : binary_nat\n| E : binary_nat -> binary_nat\n| D : binary_nat -> binary_nat.\n\nDefinition incr (n : binary_nat) : binary_nat :=\n  match n with\n  | O => E O\n  | E n => D n\n  | D (E n) => D (D n)\n  | D n => D (E n)\n  end.\n\nFixpoint bin_to_nat (n : binary_nat) : nat :=\n  match n with\n  | O => 0\n  | E n => 1 + (bin_to_nat n)\n  | D n => 2 + (bin_to_nat n)\n  end.\n\nExample test_bin_incr1 : bin_to_nat O = 0.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_bin_incr2 : bin_to_nat (incr O) = 1.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_bin_incr3 : bin_to_nat (incr (incr O)) = 2.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_bin_incr4 : bin_to_nat (incr (incr (incr O))) = 3.\nProof.\nsimpl. reflexivity.\nQed.\n\nExample test_bin_incr5 : bin_to_nat (incr (incr (incr (incr O)))) = 4.\nProof.\nsimpl. reflexivity.\nQed.\n\nEnd NatPlayground.", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/1_Basics/6_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7573586202602527}}
{"text": "Definition minus (m n : nat) : nat :=\n  match m, n with\n  | _, O => O\n  | O, S n' => n\n  | S m', S n' => (minus m' n')\n  end.\n\nDefinition ltb (n m : nat) : bool :=\n  match n, m with\n  | _, O => false\n  | O, S m' => true\n  | S n' as p, S m' as q => match (minus q p) with\n                            | O => false\n                            | _ => true\n                            end\n  end.\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.\nExample test_ltb4: (ltb 0 2) = true.\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/ltb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7573222883592711}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_equalitysymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_inequalitysymmetric :\n\tforall A B,\n\tneq A B ->\n\tneq B A.\nProof.\n\tintros A B.\n\tintros neq_A_B.\n\tintros eq_B_A.\n\n\tpose proof (lemma_equalitysymmetric _ _ eq_B_A) as eq_A_B.\n\tcontradict eq_A_B.\n\texact neq_A_B.\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_inequalitysymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7573206774156727}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Logic.\nFrom Coq Require Import Lia.\n\n(* ################################################################# *)\n(** * Inductively Defined Propositions *)\n\n(** In the [Logic] chapter, we looked at several ways of writing\n    propositions, including conjunction, disjunction, and existential\n    quantification.  In this chapter, we bring yet another new tool\n    into the mix: _inductively defined propositions_.\n\n    _Note_: For the sake of simplicity, most of this chapter uses an\n    inductive definition of \"evenness\" as a running example.  This is\n    arguably a bit confusing, since we already have a perfectly good\n    way of defining evenness as a proposition (\"[n] is even if it is\n    equal to the result of doubling some number\").  Rest assured that\n    we will see many more compelling examples of inductively defined\n    propositions toward the end of this chapter and in future\n    chapters. *)\n\n(** We've already seen two ways of stating a proposition that a number\n    [n] is even: We can say\n\n      (1) [even n = true], or\n\n      (2) [exists k, n = double k].\n\n    A third possibility that we'll explore here is to say that [n] is\n    even if we can _establish_ its evenness from the following rules:\n\n       - Rule [ev_0]: The number [0] is even.\n       - Rule [ev_SS]: If [n] is even, then [S (S n)] is even. *)\n\n(** To illustrate how this new definition of evenness works,\n    let's imagine using it to show that [4] is even. By rule [ev_SS],\n    it suffices to show that [2] is even. This, in turn, is again\n    guaranteed by rule [ev_SS], as long as we can show that [0] is\n    even. But this last fact follows directly from the [ev_0] rule. *)\n\n(** We will see many definitions like this one during the rest\n    of the course.  For purposes of informal discussions, it is\n    helpful to have a lightweight notation that makes them easy to\n    read and write.  _Inference rules_ are one such notation.  (We'll\n    use [ev] for the name of this property, since [even] is already\n    used.)\n\n                              ------------             (ev_0)\n                                 ev 0\n\n                                 ev n\n                            ----------------          (ev_SS)\n                             ev (S (S n))\n*)\n\n(** Each of the textual rules that we started with is\n    reformatted here as an inference rule; the intended reading is\n    that, if the _premises_ above the line all hold, then the\n    _conclusion_ below the line follows.  For example, the rule\n    [ev_SS] says that, if [n] satisfies [ev], then [S (S n)] also\n    does.  If a rule has no premises above the line, then its\n    conclusion holds unconditionally.\n\n    We can represent a proof using these rules by combining rule\n    applications into a _proof tree_. Here's how we might transcribe\n    the above proof that [4] is even:\n\n                             --------  (ev_0)\n                              ev 0\n                             -------- (ev_SS)\n                              ev 2\n                             -------- (ev_SS)\n                              ev 4\n*)\n\n(** (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\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 this as defining a Coq property [ev : nat ->\n    Prop], together with \"evidence constructors\" [ev_0 : ev 0]\n    and [ev_SS : forall n, ev n -> ev (S (S n))]. *)\n\n(** These evidence constructors can be thought of as \"primitive\n    evidence of evenness\", and they can be used just like proven\n    theorems.  In particular, we can use Coq's [apply] tactic with the\n    constructor names to obtain evidence for [ev] of particular\n    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 to combine several\n    constructors: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** In this way, we can also prove theorems that have hypotheses\n    involving [ev]. *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(** **** Exercise: 1 star, standard (ev_double) *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros. induction n.\n  - simpl. constructor.\n  - simpl. constructor. assumption.\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 for [ev n] _directly_. As\n    a tool, we can prove our characterization of evidence for\n    [ev n], using [destruct]. *)\n\nTheorem ev_inversion :\n  forall (n : nat), ev n ->\n    (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n  intros n E.\n  destruct E as [ | n' E'] eqn:EE.\n  - (* E = ev_0 : ev 0 *)\n    left. reflexivity.\n  - (* E = ev_SS n' E' : ev (S (S n')) *)\n    right. exists n'. split. reflexivity. apply E'.\nQed.\n\n(** Facts like this are often called \"inversion lemmas\" because they\n    allow us to \"invert\" some given information to reason about all\n    the different ways it could have been derived.\n\n    Here, there are two ways to prove that a number is [ev], and\n    the inversion lemma makes this explicit. *)\n\n(** The following theorem can easily be proved using [destruct] on\n    evidence. *)\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'] eqn:EE.\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\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.\n  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 the inversion\n    lemma that we proved above. *)\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.\nProof.\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  inversion H. inversion H1.\n  auto.\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.\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 re-prove 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  unfold Even.\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' *)\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    n0, S (S n') = double n0], 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    assert (H: (exists k', n' = double k') -> (exists n0, S (S n') = double n0)).\n    { intros [k' EQ'']. exists (S k'). simpl. rewrite <- EQ''. reflexivity. }\n    apply H.\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    unfold Even. 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.\n    unfold Even. 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. 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  induction H.\n  - auto.\n  - simpl. constructor. auto.\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\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  split; intros.\n  - induction H; simpl.\n    + constructor.\n    + repeat constructor.\n    + apply ev_sum; auto.\n  - induction H.\n    + constructor.\n    + replace (S (S n)) with (2 + n). apply (ev'_sum 2 n).\n      * constructor.\n      * auto.\n      * lia.\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  induction H0; simpl in *.\n  - auto.\n  - inversion H. apply IHev in H2. auto.\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  assert (ev ((n+m) + (n+p))). { apply ev_sum; auto. }\n  assert ((n + m) + (n + p) = (n+n) + (m+p)). { lia. }\n  rewrite H2 in H1.\n  apply ev_ev__ev with (m:=m+p) (n:=n+n).\n  - auto.\n  - replace (n+n) with (double n). apply ev_double.\n    apply double_plus.\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(** ... And, just like properties, relations can be defined\n    inductively.  One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition says that there are two ways to\n    show that one number is less than or equal to another: either\n    observe that they are the same number, or, if the second has the\n    form [S m], give evidence that the first is less than or equal to\n    [m]. *)\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\nInductive my_total : nat -> nat -> Prop :=\n  | total_refl n : my_total n n\n  | total_suc n m (H : my_total n m) : my_total n (S m)\n  | total_pred n m (H : my_total n m) : my_total n (pred m).\n                                                \n(** **** Exercise: 2 stars, standard, optional (empty_relation)\n\n    Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive my_empty : nat -> nat -> Prop :=\n  | empty_none n m (H : my_empty (pred n) (pred m)) : my_empty n m.\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. induction H0.\n  - assumption.\n  - constructor. assumption.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n; auto.\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; auto.\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  - auto.\n  - apply le_trans with (n:=S n); auto.\nQed.\n\nTheorem lt_ge_cases : forall n m,\n  n < m \\/ n >= m.\nProof.\n  intro n. induction n; intros.\n  - induction m.\n    + right. auto.\n    + inversion IHm. left. inversion H; auto.\n      inversion H. left. auto.\n  - induction m.\n    + right. constructor. apply O_le_n.\n    + inversion IHm.\n      * left. inversion H; auto.\n      * inversion H.\n        -- left. auto.\n        -- right. apply n_le_m__Sn_le_Sm. auto.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction a.\n  - apply O_le_n.\n  - apply n_le_m__Sn_le_Sm. auto.\nQed.\n\nTheorem plus_le : forall n1 n2 m,\n  n1 + n2 <= m ->\n  n1 <= m /\\ n2 <= m.\nProof.\n  intros.\n  specialize (le_plus_l n1 n2) as H1.\n  specialize (le_plus_l n2 n1) as H2.\n  split.\n  - eapply le_trans; eauto.\n  - rewrite add_comm in H2. eapply le_trans; eauto.\nQed.\n\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  intro n.\n  induction n; simpl; intros.\n  - left. apply O_le_n.\n  - destruct p.\n    + right. apply le_trans with (n:=(S (n + m))).\n      constructor. rewrite add_comm. apply le_plus_l. simpl in H. assumption.\n    + specialize (IHn m p q).\n      simpl in H. apply Sn_le_Sm__n_le_m in H. apply IHn in H.\n      inversion H.\n      * left. apply n_le_m__Sn_le_Sm. auto.\n      * right. auto.\nQed.        \n\nTheorem plus_le_compat_l : forall n m p,\n  n <= m ->\n  p + n <= p + m.\nProof.\n  intros. induction p.\n  - auto.\n  - simpl. apply n_le_m__Sn_le_Sm. auto.\nQed.\n\nTheorem plus_le_compat_r : forall n m p,\n  n <= m ->\n  n + p <= m + p.\nProof.\n  intros.\n  rewrite add_comm. assert (m + p = p + m). { apply add_comm. }\n  rewrite H0.\n  apply plus_le_compat_l. auto.\nQed.\n  \nTheorem le_plus_trans : forall n m p,\n  n <= m ->\n  n <= m + p.\nProof.\n  intros.\n  specialize (le_plus_l n p). intros.\n  specialize (plus_le_compat_r n m p H). intros.\n  eapply le_trans; eauto.\nQed.\n\nTheorem n_lt_m__n_le_m : forall n m,\n  n < m ->\n  n <= m.\nProof.\n  intros.\n  inversion H.\n  - auto.\n  - constructor. apply le_trans with (n:=S n); auto.\nQed.\n\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  intros. unfold lt. induction H; split.\n  - apply n_le_m__Sn_le_Sm. apply le_plus_l.\n  - apply n_le_m__Sn_le_Sm. rewrite add_comm. apply le_plus_l.\n  - inversion IHle. auto.\n  - inversion IHle. auto.\nQed.\n\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intro n. induction n. intros.\n  - apply O_le_n.\n  - intros. destruct m.\n    * inversion H.\n    * apply n_le_m__Sn_le_Sm. auto.\nQed.\n\n(** Hint: The next one may be easiest to prove by induction on [m]. *)\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\nProof.\n  intros. generalize dependent n. induction m; intros.\n  - inversion H. auto.\n  - destruct n.\n    + auto.\n    + simpl. apply IHm. apply Sn_le_Sm__n_le_m. auto.\nQed. \n\n(** Hint: The next one can easily be proved without using [induction]. *)\n\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. apply leb_complete in H0.\n  apply leb_correct.\n  eapply le_trans; eauto.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (leb_iff) *)\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  split; intros.\n  apply leb_complete. auto.\n  apply leb_correct. auto.\nQed.\n(** [] *)\n\n\nTheorem leb_false_rev : forall n m,\n   n <=? m = false -> m <=? n = true.\nProof.\n  intros.\n  generalize dependent m.\n  induction n; intros.\n  - destruct m.\n    + auto.\n    + simpl in H. discriminate.\n  - destruct m; auto.\n    + simpl in *. apply IHn, H.\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\n(** - Which of the following propositions are provable?\n      - [R 1 1 2] yes\n      - [R 2 2 6] no\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      no, swap c2 and c3 \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      no. c4 can be replaced by c2 + c3\n *)\n\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  fun a => fun b => a + b.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n  unfold fR. split; intros.\n  - induction H; subst; auto.\n    + simpl in IHR. rewrite <- plus_n_Sm in IHR. do 2 inversion IHR. auto.\n    + apply add_comm.\n  - generalize dependent m. generalize dependent n.\n    induction o; intros; destruct n; destruct m; try inversion H.\n    + constructor.\n    + rewrite H1. constructor. apply IHo. auto.\n    + constructor. apply IHo. auto.\n    + rewrite H1. apply c2. apply IHo. auto.\nQed.\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  | subseq_zero : subseq [] []\n  | subseq_one (n : nat) (ls1 ls2 : list nat) (H : subseq ls1 ls2) : subseq ls1 (n :: ls2)\n  | subseq_two (n : nat) (ls1 ls2 : list nat) (H : subseq ls1 ls2) : subseq (n :: ls1) (n :: ls2)                       .                                        \n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  induction l; intros.\n  - apply subseq_zero.\n  - apply subseq_two. auto.\nQed.    \n\nTheorem subseq_empty : forall (l : list nat), subseq [] l.\nProof.\n  induction l; intros.\n  - apply subseq_zero.\n  - apply subseq_one. auto.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros. induction H.\n  - apply subseq_empty.\n  - simpl. apply subseq_one. apply IHsubseq.\n  - simpl. apply subseq_two. apply IHsubseq.\nQed.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n intros.\n generalize dependent l1.\n induction H0.\n - intros. apply H.\n - intros. apply subseq_one, IHsubseq, H.\n - intros. inversion H; subst.\n   + apply subseq_one, IHsubseq, H3.\n   + apply subseq_two, IHsubseq, H3.\nQed.\n    \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]] yes \n    - [R 1 [1;2;1;0]] no\n    - [R 6 [3;2;1;0]] yes *)   \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\n(** Again, for readability, we can also 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  unfold not. intros. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros. inversion H.\n  - apply MUnionL. auto.\n  - apply MUnionR. auto.\nQed.\n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  intros.\n  induction ss.\n  - apply MStar0.\n  - simpl. apply MStarApp.\n    + specialize (H x). assert (In x (x::ss)). { simpl. left. auto. } apply H in H0. auto.\n    + apply IHss. intros. apply H. simpl. right. auto.\nQed.\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  split; intros.\n  - generalize dependent s1. induction s2; intros; inversion H.\n    + auto.\n    + subst. inversion H3. specialize (IHs2 s3 H4).\n      rewrite IHs2. auto.\n  - rewrite <- H. induction H. induction s1; simpl.\n    + constructor.\n    + replace (x :: s1) with ([x] ++ s1). Focus 2. auto.\n      constructor.\n      * constructor.\n      * auto.\nQed.\n\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\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    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  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char x => true\n  | App re1 re2 => andb (re_not_empty re1) (re_not_empty re2)\n  | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n  | Star re => true\n  end.\n   \n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  split; intros.\n  - induction re; inversion H; auto; simpl.\n    + inversion H0.\n    + inversion H0; subst. apply andb_true_iff. split.\n      apply IHre1. exists s1. auto. apply IHre2. exists s2. auto.\n    + inversion H0; subst; apply orb_true_iff.\n      left. apply IHre1. exists x. auto.\n      right. apply IHre2. exists x. auto.\n  - induction re.\n    + inversion H.\n    + exists []. constructor.\n    + exists [t]. constructor.\n    + inversion H. apply andb_true_iff in H1. inversion H1.\n      specialize (IHre1 H0). specialize (IHre2 H2).\n      inversion IHre1. inversion IHre2.\n      exists (x ++ x0). constructor; auto.\n    + inversion H. apply orb_true_iff in H1. inversion H1.\n      * specialize (IHre1 H0). inversion IHre1. exists x. apply MUnionL. auto.\n      * specialize (IHre2 H0). inversion IHre2. exists x. apply MUnionR. auto.\n    + exists []. apply MStar0.\nQed.\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(** Now, 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    (We can begin by generalizing [s2], since it's pretty clear that we\n    are going to have to walk over both [s1] and [s2] in parallel.) *)\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\n    from the definition of [exp_match]), we have lost a very important\n    bit of information from [H1]: the fact that [s1] matched something\n    of the form [Star re].  This means that we have to give proofs for\n    _all_ seven constructors of this definition, even though all but\n    two of them ([MStar0] and [MStarApp]) are contradictory.  We can\n    still 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\n    directly, because the argument to the first hypothesis is\n    sufficiently general, which means that we can discharge most cases\n    by inverting the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a\n    tactic to automatically generate such equations for us, avoiding\n    thus the need for changing the statements of our theorems. *)\nAbort.\n\n(** As we saw above, The tactic [remember e as x] causes Coq to (1)\n    replace all occurrences of the expression [e] by the variable [x],\n    and (2) add an equation [x = e] to the context.  Here's how we can\n    use it to 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  intros.  \n  remember (Star re) as re'.\n  induction H; try discriminate.\n  - exists []. split.\n    + auto.\n    + intros. contradiction.\n  - inversion Heqre'. subst.\n    specialize (IHexp_match2 Heqre') as H1.\n    destruct H1 as [ss2 [Hss2_1 Hss2_2]].\n    exists (s1 :: ss2). split.\n    + simpl. rewrite Hss2_1. auto.\n    + intros. inversion H1.\n      * subst. auto.\n      * apply Hss2_2. auto.\nQed.      \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\n\nLtac app_assoc_eq := repeat rewrite app_assoc; auto.\n\nLtac split_all := repeat (try split).\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\n\nLemma napp_star' : forall T s (re : reg_exp T)  m, s =~ Star re -> napp m s =~ Star re.\nProof.\n  intros.\n  induction m.\n  - simpl. constructor.\n  - simpl. apply star_app; auto.\nQed.\n\nLemma weak_pumping : forall T (re : reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** You are to fill in the proof. Several of the lemmas about\n    [le] that were in an optional exercise earlier in this chapter\n    may be useful. *)\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - (* MEmpty *)\n    simpl. intros contra. inversion contra.\n  -\n    simpl. intros contra. inversion contra. inversion H0.\n  -\n    simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H as [H1 | H2].\n    + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n      exists s2', s3', (s4' ++ s2). all : split_all.\n      * rewrite Heq. app_assoc_eq. \n      * auto.\n      * intros. assert (s2' ++ (napp m s3') ++ s4' ++ s2 = (s2' ++ (napp m s3') ++ s4') ++ s2). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n   + apply IH2 in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n      exists (s1 ++ s2'), s3', s4'. all : split_all.\n      * rewrite Heq. app_assoc_eq.\n      * auto.\n      * intros. assert (((s1 ++ s2') ++ napp m s3' ++ s4') = (s1 ++ (s2' ++ napp m s3' ++ s4'))). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n  -\n    simpl. intros. apply plus_le in H. destruct H as [H1 H2]. \n    apply IH in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n    exists s2', s3', s4'.  all : split_all; auto.\n    intros. apply MUnionL. auto.\n  -\n    simpl. intros. apply plus_le in H. destruct H as [H1 H2]. \n    apply IH in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n    exists s2'. exists s3'. exists s4'.  all : split_all; auto.\n    intros. apply MUnionR. auto.\n  -\n    simpl. intros. inversion H. apply pumping_constant_0_false in H1.  inversion H1.\n  -\n    intros. destruct s1; destruct s2.\n    + simpl in H. inversion H. apply pumping_constant_0_false in H1. contradiction.      \n    + exists []. exists (x :: s2). exists []. all : split_all; simpl.\n      * rewrite app_nil_r. auto.\n      * unfold not. intros. inversion H0.\n      * intros. rewrite app_nil_r. apply napp_star'. assumption.\n    + exists []. exists (x :: s1). exists []. all : split_all; simpl.\n      * unfold not. intro contra. inversion contra.\n      * intros. apply napp_star; auto.\n    + exists [], (x :: s1), (x0::s2). all : split_all; auto.\n      * unfold not. intro contra. inversion contra.\n      * intros. simpl. apply napp_star; auto.\nQed.\n\n\nLemma negb_true_iff : forall b, (negb b = true) <-> b = false.\n  split; intros; destruct b; try auto.\nQed.\n\nLemma weak_pumping' : forall T (re : reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** You are to fill in the proof. Several of the lemmas about\n    [le] that were in an optional exercise earlier in this chapter\n    may be useful. *)\nProof.\n  intros T re s Hmatch.\n  induction Hmatch\n    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2\n       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH\n       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].\n  - (* MEmpty *)\n    simpl. intros contra. inversion contra.\n  -\n    simpl. intros contra. inversion contra. inversion H0.\n  -\n    simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H as [H1 | H2].\n    + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n      exists s2', s3', (s4' ++ s2). all : split_all.\n      * rewrite Heq. app_assoc_eq. \n      * auto.\n      * intros. assert (s2' ++ (napp m s3') ++ s4' ++ s2 = (s2' ++ (napp m s3') ++ s4') ++ s2). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n   + apply IH2 in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n      exists (s1 ++ s2'), s3', s4'. all : split_all.\n      * rewrite Heq. app_assoc_eq.\n      * auto.\n      * intros. assert (((s1 ++ s2') ++ napp m s3' ++ s4') = (s1 ++ (s2' ++ napp m s3' ++ s4'))). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n  -\n    simpl. intros. apply plus_le in H. destruct H as [H1 H2]. \n    apply IH in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n    exists s2', s3', s4'.  all : split_all; auto.\n    intros. apply MUnionL. auto.\n  -\n    simpl. intros. apply plus_le in H. destruct H as [H1 H2]. \n    apply IH in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty Hs234pumping]]]]].\n    exists s2', s3', s4'.  all : split_all; auto.\n    intros. apply MUnionR. auto.\n  -\n    simpl. intros. inversion H. apply pumping_constant_0_false in H1.  inversion H1.\n  -\n    intros.\n    assert ((eqb (length s1) 0) && (eqb (length s2) 0) || (negb (eqb (length s1) 0) || negb (eqb (length s2) 0)) = true).\n    apply all3_spec. apply orb_true_iff in H0. inversion H0.\n    + (* length s1 = 0 && length s2 ==0 *)\n      apply andb_true_iff in H1. destruct H1 as [H0lens1 H0lens2].\n      apply eqb_eq in H0lens1, H0lens2.\n      rewrite app_length in H. rewrite H0lens1, H0lens2 in H. simpl in H.\n      inversion H. apply pumping_constant_0_false in H2. inversion H2.\n    + (* length s1 <> 0 || length s2 <> 0 *)\n      apply orb_true_iff in H1.\n      inversion H1.\n      * apply negb_true_iff in H2. apply eqb_neq in H2.\n        exists [], s1, s2. all : split_all; auto.\n        -- unfold not. intros. subst s1. simpl in H2. specialize (H2 (eq_refl 0)). contradiction.\n        -- intros. apply napp_star; auto.\n      * apply negb_true_iff in H2. apply eqb_neq in H2.\n        exists s1, s2, [].  all : split_all. auto.\n        -- rewrite app_nil_r. auto.\n        -- unfold not. intros. subst s2. simpl in H2. specialize (H2 (eq_refl 0)). contradiction.\n        -- intros. rewrite app_nil_r. constructor; auto. apply napp_star'. auto.\nQed.\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\n(* Lemma 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  -\n    simpl. intros contra. inversion contra. inversion H0.\n  -\n    simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H as [H1 | H2].\n    + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n      exists s2', s3', (s4' ++ s2).  all : split_all.\n      * rewrite Heq. app_assoc_eq.\n      * auto.\n      * eapply le_trans. eauto. apply le_plus_l.\n      * intros. assert (s2' ++ (napp m s3') ++ s4' ++ s2 = (s2' ++ (napp m s3') ++ s4') ++ s2). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n    + apply IH2 in H2. destruct H2 as [s2' [s3' [s4' [Heq' [Hs3'notempty [Hs'234len Hs'234pumping]]]]]].\n      destruct (leb (pumping_constant re1) (length s1)) eqn: Hpcre1.\n      * apply leb_iff in Hpcre1. apply IH1 in Hpcre1.\n        destruct Hpcre1 as [s2'' [s3'' [s4'' [Heq'' [Hs3''notempty [Hs''234len Hs''234pumping]]]]]].\n        exists s2'', s3'', (s4'' ++ s2). all : split_all.\n        -- rewrite Heq''. app_assoc_eq.\n        -- auto.\n        -- eapply le_trans. eauto. apply le_plus_l.\n        -- intros. assert (s2'' ++ napp m s3'' ++ s4'' ++ s2 = (s2'' ++ napp m s3'' ++ s4'') ++ s2). { app_assoc_eq. }\n           rewrite H. constructor; auto.\n      * exists (s1 ++ s2'), s3', s4'. all : split_all.\n        -- rewrite Heq'. app_assoc_eq.\n        -- auto.\n        -- rewrite app_length. apply le_trans with (n:=pumping_constant re1 + length s2' + length s3').\n           ++ repeat apply plus_le_compat_r; auto. apply leb_false_rev in Hpcre1. apply leb_complete in Hpcre1. auto.\n           ++ rewrite <- add_assoc. apply plus_le_compat_l. auto.\n        -- intros. simpl. assert ((s1 ++ s2') ++ napp m s3' ++ s4' = s1 ++ (s2' ++ napp m s3' ++ s4')). { app_assoc_eq. }\n           rewrite H. constructor; auto.\n  -\n    simpl. intros.\n    assert (H1: pumping_constant re1 <= length s1). { eapply le_trans. 2: apply H. apply le_plus_l. }\n    apply IH in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n    exists s2', s3', s4'. all : split_all; auto.\n    + eapply le_trans. apply Hs234len. apply le_plus_l.\n    + intros. apply MUnionL. auto.\n  -\n    simpl. intros.\n    assert (H2: pumping_constant re2 <= length s2). { eapply le_trans. 2: apply H. rewrite add_comm. apply le_plus_l. }\n    apply IH in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n    exists s2', s3', s4'. all : split_all; auto.\n    + eapply le_trans. apply Hs234len. rewrite add_comm. apply le_plus_l.\n    + intros. apply MUnionR. auto.\n  -\n    simpl. intro contra. inversion contra. apply pumping_constant_0_false in H0. contradiction.\n  -\n    intros.\n    assert ((eqb (length s1) 0) && (eqb (length s2) 0) || (negb (eqb (length s1) 0) || negb (eqb (length s2) 0)) = true).\n    apply all3_spec. apply orb_true_iff in H0. inversion H0.\n    + (* length s1 = 0 && length s2 ==0 *)\n      apply andb_true_iff in H1. destruct H1 as [H0lens1 H0lens2].\n      apply eqb_eq in H0lens1, H0lens2.\n      rewrite app_length in H. rewrite H0lens1, H0lens2 in H. simpl in H.\n      inversion H. apply pumping_constant_0_false in H2. inversion H2.\n    + (* length s1 <> 0 || length s2 <> 0 *)\n      apply orb_true_iff in H1.\n      inversion H1.\n      -- (* length s1 <> 0 *)\n         destruct (leb (pumping_constant re) (length s1)) eqn:Hlens1.\n         ++ apply leb_complete in Hlens1.\n            apply IH1 in Hlens1.\n            destruct Hlens1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n            exists s2', s3', (s4' ++ s2). all : split_all.\n            ** rewrite Heq. app_assoc_eq.\n            ** auto.\n            ** simpl. auto.\n            ** intros. assert  (s2' ++ napp m s3' ++ s4' ++ s2 = (s2' ++ napp m s3' ++ s4') ++ s2). { app_assoc_eq. }\n             rewrite H3. constructor; auto.\n         ++ exists [], s1, s2. all : split_all.\n            ** unfold not. intro. subst s1. simpl in H2. discriminate.\n            ** simpl. apply leb_false_rev in Hlens1. apply leb_complete in Hlens1. auto.\n            ** intros. simpl. apply napp_star; auto.               \n      -- (* length s2 <> 0 *)\n         destruct (leb (pumping_constant re) (length s1)) eqn:Hlens1.\n         ++ (* length s1 >= pumping_constant re *)\n            apply leb_complete in Hlens1.\n            apply IH1 in Hlens1.\n            destruct Hlens1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n            exists s2', s3', (s4' ++ s2). all : split_all.\n            ** rewrite Heq. app_assoc_eq.\n            ** auto.\n            ** simpl. auto.\n            ** intros. assert  (s2' ++ napp m s3' ++ s4' ++ s2 = (s2' ++ napp m s3' ++ s4') ++ s2). { app_assoc_eq. }\n             rewrite H3. constructor; auto.\n         ++ (* length s1 <= pumping_constant re *)\n            destruct (length s1) eqn:Hlens1eq0. assert (s1 = []). { destruct s1. auto. inversion Hlens1eq0. }\n            ** (* length s1 = 0 *)\n               inversion Hlens1eq0.\n               destruct (leb (pumping_constant re) (length s2)) eqn:Hlens2.\n               --- apply leb_complete in Hlens2.\n                   apply IH2 in Hlens2. destruct Hlens2 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n                   exists s2', s3', s4'. all : split_all; auto.\n                   +++ subst. auto.\n               --- apply leb_false_rev in Hlens2.\n                   exists [], s2, []. all : split_all; auto.\n                   +++ subst. rewrite app_nil_r. auto.\n                   +++ unfold not. intro. subst. inversion H2.\n                   +++ apply leb_complete in Hlens2. auto.\n                   +++ intros. rewrite app_nil_r. apply napp_star'. auto.\n            ** exists [], s1, s2. all : split_all.\n               --- unfold not. intros. subst s1. inversion Hlens1eq0.\n               --- simpl. apply leb_false_rev in Hlens1.  rewrite Hlens1eq0. apply leb_complete in Hlens1. auto.\n               --- intros. simpl. apply napp_star; auto.\nQed. *)\n\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    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  - \n    simpl. intros contra. inversion contra. inversion H0.\n  -\n    simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H as [H1 | H2].\n    + apply IH1 in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n      exists s2', s3', (s4' ++ s2). all : split_all.\n      * rewrite Heq. app_assoc_eq.\n      * auto.\n      * eapply le_trans. eauto. apply le_plus_l.\n      * intros. assert (s2' ++ (napp m s3') ++ s4' ++ s2 = (s2' ++ (napp m s3') ++ s4') ++ s2). { app_assoc_eq. }\n        rewrite H. constructor; auto.\n    + apply IH2 in H2. destruct H2 as [s2' [s3' [s4' [Heq' [Hs3'notempty [Hs'234len Hs'234pumping]]]]]].\n      destruct (leb (pumping_constant re1) (length s1)) eqn: Hpcre1.\n      * apply leb_iff in Hpcre1. apply IH1 in Hpcre1.\n        destruct Hpcre1 as [s2'' [s3'' [s4'' [Heq'' [Hs3''notempty [Hs''234len Hs''234pumping]]]]]].\n        exists s2'', s3'', (s4'' ++ s2). all : split_all.\n        -- rewrite Heq''. app_assoc_eq.\n        -- auto.\n        -- eapply le_trans. eauto. apply le_plus_l. \n        -- intros. assert (s2'' ++ napp m s3'' ++ s4'' ++ s2 = (s2'' ++ napp m s3'' ++ s4'') ++ s2). { app_assoc_eq. }\n           rewrite H. constructor; auto.\n      * exists (s1 ++ s2'), s3', s4'. all : split_all.\n        -- rewrite Heq'. app_assoc_eq.\n        -- auto.\n        -- rewrite app_length. apply le_trans with (n:=pumping_constant re1 + length s2' + length s3').\n           ++ repeat apply plus_le_compat_r; auto. apply leb_false_rev in Hpcre1. apply leb_complete in Hpcre1. auto.\n           ++ rewrite <- add_assoc. apply plus_le_compat_l. auto.\n        -- intros. simpl. assert ((s1 ++ s2') ++ napp m s3' ++ s4' = s1 ++ (s2' ++ napp m s3' ++ s4')). { app_assoc_eq. }\n           rewrite H. constructor; auto.\n  -\n    simpl. intros.\n    assert (H1: pumping_constant re1 <= length s1). { eapply le_trans. 2 : apply H. apply le_plus_l. }\n    apply IH in H1. destruct H1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n    exists s2', s3', s4'. all : split_all; auto.\n    + eapply le_trans. apply Hs234len. apply le_plus_l.\n    + intros. apply MUnionL. auto.\n  -\n    simpl. intros.\n    assert (H2: pumping_constant re2 <= length s2). { eapply le_trans. 2 : apply H. rewrite add_comm. apply le_plus_l. }\n    apply IH in H2. destruct H2 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n    exists s2', s3', s4'. all : split_all; auto.\n    + eapply le_trans. apply Hs234len. rewrite add_comm. apply le_plus_l.\n    + intros. apply MUnionR. auto.\n  -\n    simpl. intro contra. inversion contra. apply pumping_constant_0_false in H0. contradiction.\n  -\n    intros.\n    destruct (leb (pumping_constant re) (length s1)) eqn: Hpcre1.\n    +\n      apply leb_complete in Hpcre1.\n      apply IH1 in Hpcre1.\n      destruct Hpcre1 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n      exists s2', s3', (s4' ++ s2). all : split_all; auto.\n      * subst. app_assoc_eq.\n      * intros. assert (s2' ++ napp m s3' ++ s4' ++ s2 = (s2' ++ napp m s3' ++ s4') ++ s2). { app_assoc_eq. }\n        rewrite H0. constructor; auto.\n    +\n      destruct (eqb (length s1) 0) eqn:Hlens1eq0. \n      **\n         assert (s1 = []). { destruct s1. auto. inversion Hlens1eq0. } subst s1.\n         destruct (leb (pumping_constant re) (length s2)) eqn: Hpcre2.\n         --- apply leb_complete in Hpcre2.\n             apply IH2 in Hpcre2. destruct Hpcre2 as [s2' [s3' [s4' [Heq [Hs3notempty [Hs234len Hs234pumping]]]]]].\n             exists s2', s3', s4'. all : split_all; auto.\n         --- apply leb_false_rev in Hpcre2.\n             destruct (eqb (length s2) 0) eqn:Hlens2eq0.\n             +++ assert (s2 = []). { destruct s2. auto. inversion Hlens2eq0. } subst s2.\n                 simpl in H. inversion H. apply pumping_constant_0_false in H1. contradiction.\n             +++\n                 exists [], s2, []. all : split_all; auto.\n                 *** rewrite app_nil_r. auto.\n                 *** unfold not. intro. subst. inversion Hlens2eq0.\n                 *** apply leb_complete in Hpcre2. auto.\n                 *** intros. rewrite app_nil_r. apply napp_star'. auto.\n      **\n         exists [], s1, s2. all : split_all.\n         --- unfold not. intros. subst s1. inversion Hlens1eq0.\n         --- apply leb_false_rev in Hpcre1. apply leb_complete in Hpcre1. auto.\n         --- intros. apply napp_star; auto.\nQed.\n\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].  Instead of\n    generating an equation such as [(n =? m) = true], which is\n    generally not directly useful, this principle gives us right away\n    the assumption we really need: [n = m].\n\n    Following the terminology introduced in [Logic], we call\n    this the \"reflection principle for equality (between numbers),\"\n    and we say that the boolean [n =? m] is _reflected in_ the\n    proposition [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(** To put this observation to work, we first prove 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 eqn:Eb.\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  intros.\n  inversion H.\n  - split; auto.\n  - split; intros.\n    + contradiction.\n    + inversion H2.\nQed.\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\nLemma eq_symm : forall A (x y : A), x = y <-> y = x.\nProof.\n  intros. split; auto.\nQed.\n\n\nTheorem eqbP_practice : forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros; unfold not; intros.\n  induction l as [| n' l'].\n  - inversion H0.\n  - destruct (eqb n n') eqn:Heqnn'.\n    + apply eqb_eq in Heqnn'. subst. simpl in H. rewrite (eqb_refl n') in H. inversion H.\n    + simpl in H0. inversion H0.\n      * rewrite eq_symm in H1. apply eqb_eq in H1. rewrite H1 in Heqnn'. discriminate.\n      * inversion H. rewrite Heqnn' in H3. simpl in H3.\n        specialize (IHl' H3 H1). contradiction.\nQed.\n(** [] *)\n\n(** This small example shows reflection giving 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| ns_empty : nostutter []\n| ns_one : forall (x: X), nostutter [x]\n| ns_app : forall (x y : X) (ls:list X) (H: x<>y) (H2 : nostutter (x::ls)), nostutter (y::x::ls)                             \n (* FILL IN HERE *)\n.\n\n(** Make sure each of these tests succeeds, but feel free to change\n    the suggested proof (in comments) if the given one doesn't work\n    for you.  Your definition might be different from ours and still\n    be correct, in which case the examples might need a different\n    proof.  (You'll notice that the suggested proofs use a number of\n    tactics we haven't talked about, to make them more robust to\n    different possible ways of defining [nostutter].  You can probably\n    just uncomment and use them as-is, but you can also prove each\n    example with more basic tactics.)  *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof. repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_2:  nostutter (@nil nat).\nProof. repeat constructor; apply eqb_neq; auto.\nQed.\n\nExample test_nostutter_3:  nostutter [5].\nProof. 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. Qed.\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\nInductive inordermerge {X:Type} : list X -> list X -> list X -> Prop :=\n| iom_nil : inordermerge [] [] []\n| iom_app_l : forall (x : X) (l1 l2 l : list X) (H : inordermerge l1 l2 l), inordermerge (x::l1) l2 (x::l)\n| iom_app_r : forall (x : X) (l1 l2 l : list X) (H : inordermerge l1 l2 l), inordermerge l1 (x::l2) (x::l)                            \n (* FILL IN HERE *)\n.\n\nTheorem inordermerge_test1 : inordermerge [1;6;2] [4;3] [1;4;6;2;3].\nProof.\n  repeat constructor.\nQed.\n\nLemma In_cons : forall X (x : X) (l : list X), In x (x ::l).\nProof.\n  intros.\n  replace (x::l) with ([x] ++ l).\n  apply In_app_iff. left. simpl. left. auto. auto.\nQed.\n\nTheorem sublist_holds_P : forall X (x0 : X) (l : list X) (P : X -> Prop), \n  (forall x, In x (x0::l) -> P x) -> (forall x, In x l -> P x).\nProof.\n  intros.\n  specialize (H x).\n  assert (In x (x0 :: l)). {\n    replace (x0 :: l) with ([x0] ++ l).\n    apply In_app_iff. right. auto.\n    auto.\n  }\n  apply H. auto.\nQed.\n\nTheorem filter_challenge : forall X (l1 l2 l : list X) (test : X -> bool), \n  inordermerge l1 l2 l -> \n  (forall x, In x l1 -> test x = true) -> \n  (forall x, In x l2 -> test x = false) -> \n  filter test l = l1.\nProof.\n  intros. generalize dependent l1. generalize dependent l2.\n  induction l; intros.\n  - inversion H. auto.\n  - inversion H; subst.\n    + specialize (IHl l2 H1 l0 H5). \n      specialize (H0 x (In_cons X x l0)) as Htestt. simpl. rewrite H0. simpl. \n      specialize (sublist_holds_P X x l0 (fun x => test x = true) H0). intros. apply IHl in H2. rewrite H2. auto.\n      apply (In_cons X x l0).\n    + specialize (sublist_holds_P X x l3 (fun x => test x = false) H1). intros.\n      specialize (IHl l3 H2 l1 H5 H0).\n      specialize (H1 x (In_cons X x l3)). simpl. rewrite H1. auto.\nQed. \n\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(* To avoid re-defining subseq relation, use list nat instead of list X, but the proof should be same *)\nTheorem filter_challenge2 : forall (l l' : list nat) (test : nat -> bool) , (subseq l' l) -> (forall x, In x l' -> test x = true)\n  -> length l' <= length (filter test l).\nProof.\n  intros. generalize dependent l'.\n  induction l; intros.\n  - inversion H. simpl. lia.\n  - inversion H; subst.\n    + simpl. specialize (IHl l' H3 H0). destruct (test x); simpl; lia.\n    + simpl. \n      specialize (sublist_holds_P nat x ls1 (fun x => test x = true) H0) as Ht.\n      specialize (IHl ls1 H3 Ht).\n      specialize (H0 x (In_cons nat x ls1)). rewrite H0. simpl. lia.\nQed. \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\nInductive pal {X:Type} : list X -> Prop :=\n| pal_zero : pal []\n| pal_one (x : X) : pal [x]\n| pal_add (x : X) (ls : list X) (H : pal ls) : pal ([x] ++ ls ++ [x])\n.\n\n(* A failed but insteresting try \n\nFixpoint take_not_last X (ls : list X) : list X :=\n  match ls with\n  | [] => []\n  | [x] => []\n  | x::ls' => x :: take_not_last X ls'\n  end.\n\nLocate \"{ _ : _ | _ }\".\n\nLemma zgtz : 0 > 0 -> False.\nProof. intros. inversion H.  Qed.\n\nCheck proj1_sig.\n\n(* Fixpoint take_last X (l : list X) {struct l}: length l > 0 -> X.\nrefine (\n  match l return length l > 0 -> X with \n  | [] => fun pf : 0 > 0 => match zgtz pf with end\n  | [x] => fun _ => x\n  | x::y::ls => fun _ => take_last X (y::ls) _\n  end).\n  simpl. lia.\nFail Defined. *)\n\nDefinition take_middle X (ls : list X) : list X :=\n  match ls with \n  | [] => []\n  | [x] => []\n  | x::y::ls' => take_not_last X ls'\n  end.\n\nDefinition list_ind2:\n  forall X (P : list X -> Prop),\n    P [] ->\n    (forall x, P [x]) ->\n    (forall x y ls, P ls -> P ([x] ++ ls ++ [y])) ->\n    forall (ls : list X), P ls.\nProof.\n  intros. \n      fun X => fun P => fun P0 => fun P1 => fun Pss => \n        fix f (ls : list X) := match ls with \n                               | [] => P0\n                               | [x] => P1 x\n                               | x :: y :: ls => Pss x y (take_middle X ls) (f (take_middle X ls))\n        end. \n\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\nLemma pal_converse': forall X len (l:list X), length l <= len -> l = rev l -> pal l.\nProof.\n  intros X len.\n  induction len; intros.\n  - destruct l. constructor. inversion H.\n  - destruct l. constructor. simpl in *.\n      destruct (rev l) eqn:Heqrevl.\n      + rewrite H0. constructor.\n      + inversion H0. constructor.\n        apply Sn_le_Sm__n_le_m in H.\n        assert (length l = length (l0 ++ [x0])). { rewrite H3. auto. }\n        rewrite app_length in H1. \n        simpl in H1.\n        assert (length l0 <= len). { lia. }\n        specialize (IHlen l0 H4).\n        apply IHlen.\n        rewrite H3 in Heqrevl.\n        rewrite rev_app_distr in Heqrevl.\n        simpl in Heqrevl.\n        inversion Heqrevl.\n        rewrite H6 at 2. auto.\nQed.\n\nLemma pal_converse: forall X (l:list X), l = rev l -> pal l.\nProof.\n  intros.\n  eapply pal_converse'; eauto.\nQed.\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\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\nInductive disjoint (X : Type) : list X -> list X -> Prop :=\n| disj_nil    : disjoint X [] []\n| disj_cons_l : forall (l1 l2 : list X) (x : X),\n                ~ In x l2 -> \n                  disjoint X l1 l2 -> disjoint X (x :: l1) l2\n| disj_cons_r : forall (l1 l2 : list X) (x : X),\n                ~ In x l1 -> \n                  disjoint X l1 l2 -> disjoint X l1 (x :: l2).\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\nInductive NoDup (X : Type) : list X -> Prop :=\n| nodup_nil    : NoDup X []\n| nodup_app (x : X) (l : list X) (H1 : ~ In x l) (H2 : NoDup X l) : NoDup X (x :: l).\n\nLemma disjoint_nil_l : forall X (l : list X), disjoint X [] l.\nProof.\n  induction l.\n  - constructor. \n  - constructor; auto.\nQed.\n\nLemma disjoint_nil_r : forall X (l : list X), disjoint X l [].\nProof.\n  induction l.\n  - constructor. \n  - constructor; auto.\nQed.\n\nLemma disjoint_sub_l: forall X (x: X) (l1 l2 : list X), disjoint X (x :: l1) l2 -> disjoint X l1 l2.\nProof.\n  intros.\n  generalize dependent x. generalize dependent l1.\n  induction l2; intros.\n  - eapply disjoint_nil_r.\n  - induction l1.\n    + eapply disjoint_nil_l.\n    + inversion H; subst.\n      * auto.\n      * specialize (IHl2 (x1::l1) x0 H4).\n        apply disj_cons_r.\n        -- unfold not. intros. assert (In x (x0 :: x1 :: l1)). \n        { replace (x0 :: x1 :: l1) with ([x0] ++ (x1 :: l1)). apply In_app_iff. right. assumption. auto. } contradiction.\n        -- auto.\nQed.\n\n\nLemma disjoint_sub_r: forall X (x: X) (l1 l2 : list X), disjoint X l1 (x :: l2) -> disjoint X l1 l2.\nProof.\n  intros.\n  generalize dependent x. generalize dependent l2.\n  induction l1; intros.\n  - eapply disjoint_nil_l.\n  - induction l2.\n    + eapply disjoint_nil_r.\n    + inversion H; subst.\n      * specialize (IHl1 (x1::l2) x0 H4).\n        apply disj_cons_l.\n        -- unfold not. intros. assert (In x (x0 :: x1 :: l2)). \n        { replace (x0 :: x1 :: l2) with ([x0] ++ (x1 :: l2)). apply In_app_iff. right. assumption. auto. } contradiction.\n        -- auto.\n      * auto.\nQed.\n\nLemma disjoint_one : forall X (x: X) (l1 l2 : list X), disjoint X (x::l1) l2 -> ~ In x l2.\nProof.\n  intros. generalize dependent x. generalize dependent l1.\n  induction l2; intros.\n  - unfold not. intros. inversion H0. \n  - unfold not. intros.\n  inversion H; subst.\n  + contradiction.\n  + unfold not in H4.\n    replace (x::l2) with ([x] ++ l2) in H0. apply In_app_iff in H0. inversion H0.\n    * inversion H1.\n      -- subst. assert (In x0 (x0::l1)). {  \n        replace (x0::l1) with ([x0] ++ l1).\n        apply In_app_iff. left. auto. auto.\n      } \n      apply H4 in H2. contradiction.\n      -- inversion H2.\n    * specialize (IHl2 l1 x0 H5). contradiction.\n    * auto.\nQed.\n\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [NoDup] and [++] (list append).  *)\nTheorem disjoint_app_nodup : forall X (l1 l2 : list X), NoDup X l1 -> NoDup X l2 -> disjoint X l1 l2 -> NoDup X (l1 ++ l2).\nProof.\n  intros. generalize dependent l2.\n  induction H; intros.\n  - auto.\n  - simpl. constructor.\n    + unfold not. intros. apply In_app_iff in H3.\n      inversion H3.\n      * contradiction.\n      * specialize (disjoint_one X x l l2 H2).\n        unfold not. intros. contradiction.\n    + apply IHNoDup; auto.\n      eapply disjoint_sub_l. eauto. \nQed.\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 and useful lemma. *)\n\nLemma in_split : forall (X:Type) (x:X) (l:list X),\n  In x l ->\n  exists l1 l2, l = l1 ++ x :: l2.\nProof.\n  intros.\n  induction l; inversion H.\n  - subst x0. exists [], l. auto.\n  - apply IHl in H0. destruct H0 as [l1 [l2]].\n    exists (x0::l1), l2. rewrite H0. auto. \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\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: excluded_middle ->\n  forall (X:Type) (l1 l2:list X),\n  (forall x, In x l1 -> In x l2) ->\n  length l2 < length l1 ->\n  repeats l1.\nProof.\n  intros EM X l1. induction l1 as [|x l1' IHl1'].\n  - intros. inversion H0.\n  - intros. specialize (EM (In x l1')) as Hxinl1'. \n    inversion Hxinl1'. \n    + apply rp_base. auto.\n    + apply rp_next. destruct (in_split X x l2).\n      * apply H. apply In_cons.\n      * destruct H2 as [l3 Heql2]. subst. \n        apply IHl1' with (l2:=x0 ++ l3).\n        -- intros. specialize (EM (x = x1)) as Hxeqx1.\n           inversion Hxeqx1.\n           ++ subst. contradiction. \n           ++ assert (In x1 (x0 ++ x :: l3) -> In x1 (x0 ++ l3)).\n              { intros. apply In_app_iff in H4. inversion H4.\n                + apply In_app_iff. left. auto.\n                + replace (x :: l3) with ([x] ++ l3) in H5. apply In_app_iff in H5. inversion H5.\n                * simpl in H6. inversion H6. contradiction. inversion H7.\n                * apply In_app_iff. right. auto.\n                * auto.\n              }\n              apply H4. apply H. replace (x :: l1') with ([x] ++ l1').\n              apply In_app_iff. right. auto. auto.\n        -- rewrite app_length in H0. rewrite app_length. simpl in *. lia.\nQed.\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 automatically.\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 implement 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  intros. split; intros.\n  - inversion H. subst.\n    induction s1; intros.\n    + left; split; subst; auto.\n    + right. inversion H1. subst. exists s1, s2. all : split_all; auto. \n  - inversion H. \n    + inversion H0. replace (a::s) with ([] ++ (a :: s)). constructor; auto. auto.\n    + destruct H0 as [s0 [s1 [Heq [Hmre0 Hmre1]]]].\n      replace (a::s) with ((a::s0) ++ s1). constructor; auto. rewrite Heq. app_assoc_eq.\nQed.\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.  *)\nCheck exp_match_ind.\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  intros. split; intros.\n  - remember (Star re) as re'. remember (a::s) as s'. induction H; try discriminate.\n    + destruct s1.\n      * simpl in Heqs'. eapply IHexp_match2; auto.\n      * inversion Heqs'. inversion Heqre'. subst.\n        exists s1, s2. all : split_all; auto. \n  - destruct H as [s0 [s1 [Heq [Hmre Hmstarre]]]].\n    replace (a :: s) with ((a :: s0) ++ s1). constructor; auto. rewrite Heq. auto.\nQed.\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  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char x => false\n  | App re1 re2 => andb (match_eps re1) (match_eps re2)\n  | Union re1 re2 => orb (match_eps re1) (match_eps re2)\n  | Star re => true\n  end.\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  unfold refl_matches_eps. intros.\n  destruct (match_eps re) eqn:Hmepsre.\n  - apply ReflectT. induction re; inversion Hmepsre.\n    + constructor.\n    + apply andb_true_iff in H0. inversion H0.\n      replace ([]) with (@app ascii [] []). constructor; auto. auto.\n    + apply union_disj. apply orb_true_iff in H0. inversion H0.\n      * left. auto.\n      * right. auto.\n    + constructor.\n  - apply ReflectF. induction re; inversion Hmepsre; unfold not; \n    intros contra; inversion contra.\n    + destruct s1; destruct s2; inversion H1.\n      apply andb_false_iff in H0. inversion H0. \n      * apply IHre1 in H5. contradiction.\n      * apply IHre2 in H5. contradiction.\n    + apply orb_false_iff in H0; inversion H0.\n      apply IHre1 in H4. contradiction.\n    + apply orb_false_iff in H0; inversion H0.\n      apply IHre2 in H5. contradiction.\nQed.\n\nLemma match_eps_refl' : refl_matches_eps match_eps.\nProof.\n  unfold refl_matches_eps. intros.\n  apply iff_reflect. split; intros.\n  - remember ([]) as s. induction H; try discriminate; auto.\n    + destruct s1; destruct s2; inversion Heqs.\n      simpl. specialize (IHexp_match2 (eq_refl [])). specialize (IHexp_match1 (eq_refl [])). \n      rewrite IHexp_match1. rewrite IHexp_match2. auto.\n    + simpl. apply orb_true_iff. left. apply IHexp_match. auto.\n    + simpl. apply orb_true_iff. right. apply IHexp_match. auto.\n  -\n    induction re; inversion H; try solve constructor.\n    + constructor.\n    + replace ([]) with (@app ascii [] []). \n      apply andb_true_iff in H1. inversion H1. constructor; auto.\n      auto.\n    + apply orb_true_iff in H1.\n      inversion H1. \n      apply MUnionL; auto.\n      apply MUnionR; auto.\n    + constructor.\nQed.\n\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  match re with\n  | EmptySet => EmptySet\n  | EmptyStr => EmptySet\n  | Char x => if (eqb a x) then EmptyStr else EmptySet\n  | App re1 re2 => if (match_eps re1) \n                   then\n                     (Union (App (derive a re1) re2) (derive a re2)) \n                   else App (derive a re1) re2\n  | Union re1 re2 => Union (derive a re1) (derive a re2)\n  | Star re' => App (derive a re') re\n  end.\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  auto. Qed.\n\n(** \"c\" =~ Char c: *)\nExample test_der1 : match_eps (derive c (Char c)) = true.\nProof.\n  auto. Qed.\n\n(** \"c\" =~ Char d: *)\nExample test_der2 : match_eps (derive c (Char d)) = false.\nProof.\n  auto. Qed.\n\n(** \"c\" =~ App (Char c) EmptyStr: *)\nExample test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\nProof.\n  auto. Qed.\n\n(** \"c\" =~ App EmptyStr (Char c): *)\nExample test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\nProof.\n  auto. Qed.\n\n(** \"c\" =~ Star c: *)\nExample test_der5 : match_eps (derive c (Star (Char c))) = true.\nProof.\n  auto. Qed.\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  auto. Qed.\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  auto. Qed.\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]. *)\n\nLtac reflect_transform H re := \n  match goal with \n  H1 : refl_matches_eps match_eps\n  |- _ => specialize (H1 re); apply reflect_iff in H1; apply H1 in H; auto\n  end.\n\nLemma derive_corr : derives derive.\nProof.\n  specialize match_eps_refl. intros Hreflmeps.\n  unfold derives. intros. generalize dependent a.\n  induction re; unfold is_der in *; intros.\n  - split; intros; try inversion H.\n  - split; intros; try inversion H.\n  - split; intros; specialize (ascii_dec a t) as Hateqdec; intros; destruct Hateqdec as [Hateq | Hatneq].\n    + subst. inversion H. simpl. rewrite eqb_refl. constructor.\n    + inversion H. contradiction.\n    + subst. simpl in H. rewrite eqb_refl in H. inversion H. constructor.\n    + simpl in H. apply eqb_neq in Hatneq. rewrite Hatneq in H. inversion H.\n  - split; intros. \n    + apply app_ne in H. inversion H.\n      * destruct H0 as [Hmre1 Hmre2].\n        pose proof Hmre1 as Hmre1t. reflect_transform Hmre1t re1. simpl.\n        rewrite Hmre1t. apply MUnionR. replace s with ([] ++ s). apply IHre2; auto. auto.\n      * destruct H0 as [s0 [s1 [Heqs [Hmre1 Hmre2]]]].\n        simpl. destruct (match_eps re1).\n        -- apply MUnionL. rewrite Heqs. constructor. apply IHre1; auto. auto.\n        -- rewrite Heqs. constructor. apply IHre1; auto. auto.\n    + simpl in H. \n      assert (Happd : s =~ App (derive a re1) re2 -> a :: s =~ App re1 re2). {\n        intros.\n        apply app_exists in H0.\n        destruct H0 as [s0' [s1' [Heqs [Hmre1 Hmre2]]]].\n        replace (a :: s) with ((a :: s0') ++ s1'). constructor; auto.\n        ++ apply IHre1 in Hmre1. auto.\n        ++ rewrite Heqs. app_assoc_eq.\n      }\n      destruct (match_eps re1) eqn:Hre1meps.\n      * inversion H.\n        -- apply Happd. auto.\n        -- replace (a :: s) with ([] ++ (a :: s)).\n        constructor.\n        ++ reflect_transform Hre1meps re1. \n        ++ apply IHre2. auto.\n        ++ auto.\n      * apply Happd. auto.\n  - split; intros. \n    + inversion H; simpl.\n      apply MUnionL. apply IHre1. auto.\n      apply MUnionR. apply IHre2. auto.\n    + simpl in H. inversion H.\n      apply MUnionL. apply IHre1. auto.\n      apply MUnionR. apply IHre2. auto.\n  - split; intros.\n    + apply star_ne in H.\n      destruct H as [s0 [s1 [Heqs [Hmre1 Hmre2]]]].\n      simpl. rewrite Heqs. constructor.\n      apply IHre. auto. auto.\n    + simpl in H.\n      apply app_exists in H.\n      destruct H as [s0 [s1 [Heqs [Hmre1 Hmre2]]]].\n      apply IHre in Hmre1.\n      rewrite Heqs. replace (a :: s0 ++ s1) with ((a::s0) ++ s1). constructor; auto.\n      app_assoc_eq.\nQed.\n\n\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  match s with\n  | a :: s' => regex_match s' (derive a re)\n  | [] => match_eps re\n  end.\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. *)\n\n\nTheorem regex_refl : matches_regex regex_match.\nProof.\n  specialize derive_corr. specialize match_eps_refl. unfold derives. unfold is_der.\n  unfold matches_regex. intros Hmeps Hdc. intros. \n  apply iff_reflect. split; intros; generalize dependent re; induction s; intros.\n  - simpl. reflect_transform H re.\n  - simpl. apply Hdc in H. apply IHs. auto.\n  - simpl in H. reflect_transform H re.\n  - apply Hdc. simpl in H. apply IHs. auto.\nQed.\n(** [] *)\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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.7571893203607138}}
{"text": "(*|\n##############################################\n A compiler from expressions to stack machine\n##############################################\n|*)\n\n(*|\n\n.. contents:: Table of Contents\n\n|*)\n\nFrom QuickChick Require Import QuickChick.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom mathcomp Require Import zify. (* lia *)\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\n\nGlobal Set Bullet Behavior \"None\".\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*|\n*******************************\n Simple Arithmetic Expressions\n******************************* |*)\n\nModule ArithExpr.\n\n(*|\nExpressions\n=========== |*)\n\n(*|\nAbstract Syntax Tree\n-------------------- |*)\n\n(*| Abstract Syntax Tree (AST) for arithmetic expressions: we support numerals\n(`Const`) and three arithmetic operations: addition (represented with the `Plus`\nconstructor), truncating subtraction (`Minus`), multiplication (`Mult`). |*)\n\nInductive aexp : Type :=\n| Const of nat\n| Plus of aexp & aexp\n| Minus of aexp & aexp\n| Mult of aexp & aexp.\n\n(*| QuickChick (see below) comes with a derivation mechanism for random\ngenerators and conversion to strings for a wide class of inductive types. |*)\nDerive (Arbitrary, Show) for aexp.\n\nImplicit Types (e : aexp).\n\n(*|\nEvaluator\n========= |*)\n\nSection Evaluator.\n\n(*| Computable big-step semantics for arithmetic expressions: |*)\nFixpoint aeval (e : aexp) : nat :=\n  match e with\n  | Const n     => n\n  | Plus e1 e2  => aeval e1 + aeval e2\n  | Minus e1 e2 => aeval e1 - aeval e2\n  | Mult e1 e2  => aeval e1 * aeval e2\n  end.\n\nEnd Evaluator.\n\n(*| Unit and notation tests: |*)\nCheck erefl : aeval (Minus (Const 0) (Const 4)) = 0.\nCheck erefl : aeval (Minus (Minus (Const 40) (Const 3)) (Const 1)) = 36.\nCheck erefl : aeval (Minus (Const 40) (Minus (Const 3) (Const 1))) = 38.\nCheck erefl : aeval (Plus (Const 2) (Mult (Const 2) (Const 2))) = 6.\nCheck erefl : aeval (Mult (Plus (Const 2) (Const 2)) (Const 2)) = 8.\nCheck erefl : aeval (Minus (Plus (Const 40) (Const 3)) (Const 1)) = 42.\n\n\n(*|\nSimple Stack Machine\n==================== |*)\n\n(*|\nAbstract Syntax for Simple Stack Machine\n---------------------------------------- |*)\n\n(*| The stack machine instructions: |*)\nInductive instr := Push (n : nat) | Add | Sub | Mul.\n\n\n(*| QuickChick (see below) comes with a derivation mechanism for random\ngenerators and conversion to strings for a wide class of inductive types. |*)\nDerive (Arbitrary, Show) for instr.\n\n(*| A program for our stack machine is simply a sequence of instructions: |*)\nDefinition prog := seq instr.\n\n(*| The stack of our stack machine is represented as a list of natural numbers |*)\nDefinition stack := seq nat.\n\nImplicit Types (p : prog) (s : stack).\n\n(*|\nStack Programs Semantics\n------------------------ |*)\n\nFixpoint run p s : stack :=\n  match p, s with\n  | (Push n) :: p, s          => run p (n :: s)\n  | Add :: p, (a1 :: a2 :: s) => run p ((a2 + a1) :: s)\n  | Sub :: p, (a1 :: a2 :: s) => run p ((a2 - a1) :: s)\n  | Mul :: p, (a1 :: a2 :: s) => run p ((a2 * a1) :: s)\n  | _ :: p, s                 => run p s\n  | _, _                      => s\n  end.\n\nArguments run : simpl nomatch.\n\n(*| Unit and notation tests: |*)\nCheck erefl : run [:: Push 21; Push 21; Add] [::] = [:: 42].\n\n\n(*|\nCompiler from Simple Arithmetic Expressions to Stack Machine Language\n===================================================================== |*)\n\nFixpoint compile e : prog :=\n  match e with\n  | Const n     => [:: Push n]\n  | Plus e1 e2  => compile e1 ++ compile e2 ++ [:: Add]\n  | Minus e1 e2 => compile e1 ++ compile e2 ++ [:: Sub]\n  | Mult e1 e2  => compile e1 ++ compile e2 ++ [:: Mul]\n  end.\n\nCheck erefl: run (compile (Minus (Plus (Const 40) (Const 3)) (Const 1))) [::] = [:: 42].\n\n(*|\nProperty-based randomized testing\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |*)\n(*\n+++ Passed 10000 tests (0 discards)\n*)\n\n(*|\nCompiler correctness: specification and first steps to prove it\n--------------------------------------------------------------- |*)\n\n(* TODO: maybe show the non-generalized version first *)\n\nQuickChick (fun (a : instr) l s  =>\n  run (cons a l) s == run l (run (cons a nil) s)).\n\nLemma run_cons_comm a l s :\n  run (a :: l) s = run l (run (cons a nil) s).\nProof.\ncase: a.\n- move=> n /=.\n  exact: erefl.\n- (* Proove for Plus *)\n  case: s.\n  + by [].\n  + move=> a1 l1 /=.\n    case: l1.\n    * by [].\n    * move=> a2 l2 /=.\n      exact: erefl.\n- (* Proove for Minus *)\n  case: s.\n  + by [].\n  + move=> a1 l1 /=.\n    case: l1.\n    * by [].\n    * move=> a2 l2 /=.\n      exact: erefl.\n- (* Proove for Mult *)\n  case: s.\n  + by [].\n  + move=> a1 l1 /=.\n    case: l1.\n    * by [].\n    * move=> a2 l2 /=.\n      exact: erefl.\nQed.\n\nLemma run_cons_comm' a l s :\n  run (a :: l) s = run l (run (cons a nil) s).\nProof.\ncase: a.\n- move=> n /=.\n  exact: erefl.\nall: case: s => // a1 l1 //; case: l1 => // a2 l2 /=; exact: erefl.\nQed.\n\nQuickChick (fun (p1 p2 : prog) s  =>\n  run (p1 ++ p2) s == run p2 (run p1 s)).\n\nLemma run_cat_comm :\n  forall p1 p2 s, run (p1 ++ p2) s = run p2 (run p1 s).\nProof.\nelim => /=.\n- move=> p2 s.\n  exact: erefl.\n- move=> a l IHl /= p2 s.\n  rewrite run_cons_comm.\n  rewrite IHl.\n  rewrite -run_cons_comm.\n  exact: erefl.\nQed.\n\nTheorem compile_correct_helper e :\n  forall s, run (compile e) s = (aeval e) :: s.\nProof.\nelim: e.\n- by [].\n- (* Proove for Plus *)\n  move=> e1 IHe1 e2 IHe2 s /=.\n  rewrite run_cat_comm.\n  rewrite IHe1.\n  rewrite run_cat_comm.\n  rewrite IHe2.\n  rewrite /IHe2.\n  move => /=.\n  exact: erefl.\n- (* Proove for Minus *)\n  move=> e1 IHe1 e2 IHe2 s /=.\n  rewrite run_cat_comm.\n  rewrite IHe1.\n  rewrite run_cat_comm.\n  rewrite IHe2.\n  rewrite /IHe2.\n  move => /=.\n  exact: erefl.\n- (* Proove for Mult *)\n  move=> e1 IHe1 e2 IHe2 s /=.\n  rewrite run_cat_comm.\n  rewrite IHe1.\n  rewrite run_cat_comm.\n  rewrite IHe2.\n  rewrite /IHe2.\n  move => /=.\n  exact: erefl.\nQed.\n\nTheorem compile_correct_helper' e :\n  forall s, run (compile e) s = (aeval e) :: s.\nProof.\nelim: e=> // e1 IHe1 e2 IHe2 s /=; rewrite ?run_cat_comm IHe1 IHe2 //=.\nQed.\n\nTheorem compile_correct_helper'' e :\n  forall s, run (compile e) s = (aeval e) :: s.\nProof.\nelim: e.\n- by [].\nall: move=> e1 IHe1 e2 IHe2 s /=; rewrite ?run_cat_comm IHe1 IHe2 //=.\nQed.\n\nTheorem compile_correct e :\n  run (compile e) nil = [ :: aeval e ].\nProof.\nexact: (compile_correct_helper e nil).\nQed.\n\n(*|\nCompiler is not very inefficient\n-------------------------------- |*)\n\n(*| Let us show the compiler does not produce very inefficient code: we are\ngoing to assume that the measure of inefficiency in our case is the length of\nthe code the compiler produces. In our case the length of produced code should\nnot exceed the number of symbols (operations and constants) in the source\narithmetic expression. In fact, our compiler is efficient in a sense, for\ninstance, it does not add spurious instructions like `<some-code>; ⧐ 0; ⊕; ...`\nbut our specification so far does not ensure that. |*)\n\nFixpoint nsymb (e : aexp) : nat :=\n  match e with\n  | Const n                               => 1\n  | Plus e1 e2 | Minus e1 e2 | Mult e1 e2 => S (nsymb e1 + nsymb e2)\n  end.\n\n(*| First, let's check the property holds using QuickChick: |*)\n\nPrint size.\n\nQuickChick (fun e =>\n  size (compile e) <= nsymb e).\n\nLemma compile_is_not_very_inefficient e :\n  size (compile e) <= nsymb e.\nProof.\nelim: e => // => e1 IHe1 e2 IHe2 /=.\n- rewrite ?size_cat => /=.\n  rewrite addnA addn1.\n  apply: leq_ltS (leq_add IHe1 IHe2).\n- rewrite ?size_cat => /=.\n  rewrite addnA addn1.\n  apply: leq_ltS (leq_add IHe1 IHe2).\n- rewrite ?size_cat => /=.\n  rewrite addnA addn1.\n  apply: leq_ltS (leq_add IHe1 IHe2).\nQed.\n\nLemma compile_is_not_very_inefficient' e :\n  size (compile e) <= nsymb e.\nProof.\nelim: e => // e1 IHe1 e2 IHe2 /=;\n  rewrite ?size_cat => /=;\n  rewrite addnA addn1;\n  apply: leq_ltS (leq_add IHe1 IHe2).\nQed.\n\nEnd ArithExpr.", "meta": {"author": "yugr", "repo": "Lalambda", "sha": "0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7", "save_path": "github-repos/coq/yugr-Lalambda", "path": "github-repos/coq/yugr-Lalambda/Lalambda-0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7/21/lecture-notes/Coq-prep/compiler1_lean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.75718931458967}}
{"text": "Inductive 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) ..).\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\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 :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(* EXERCISE *)\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.\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(* EXERCISE *)\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof. \n    intros l n. induction l as [| l' IHl'].\n    - simpl. reflexivity.\n    - 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/lists/exercises/hd_error.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7571893125293617}}
{"text": "(*\n * その5: https://www.fos.kuis.kyoto-u.ac.jp/~igarashi/class/cal/handout5.pdf\n * タクティクスの練習\n *)\n\nRequire Import Arith List Omega ZArith.\nFrom mathcomp Require Import all_ssreflect.\nImport ListNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nTheorem trans_eq : forall (X : Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  congruence.\nQed.\n\n(*\n * ただの apply では m が推測できないが with でヒントを与えることが出来る\n *)\n\nExample trans_eq_example :\n  forall (a b c d e f : nat),\n  [a;b] = [c;d] -> [c;d] = [e;f] -> [a;b] = [e;f].\nProof.\n  intros.\n  apply trans_eq with (m := [c;d]).\n  - exact.\n  - exact.\nQed.\n\n(*\n * 帰納的定義では、イコールは構築の仕方から自明なもの\n *)\n\nTheorem S_injective : forall n m,\n  S n = S m -> n = m.\nProof.\n  intros.\n  assert (H2 : n = (n.+1).-1). {\n    by simpl.\n  }\n  rewrite H2.\n  rewrite H.\n  by simpl.\nQed.\n\n(*\n * これをやってくれる injection というタクティクがある\n *)\n\nTheorem S_injective' : forall n m,\n  S n = S m -> n = m.\nProof.\n  intros.\n  injection H.\n  apply.\nQed.\n\nTheorem injection_ex1 : forall n m o : nat,\n  [n;m] = [o;o] -> [n] = [m].\nProof.\n  intros.\n  injection H.\n  intros.\n  rewrite H0.\n  rewrite H1.\n  trivial.\nQed.\n\nTheorem injection_ex2 : forall n m : nat,\n  [n] = [m] -> n = m.\nProof.\n  intros n m.\n  intros H.\n  injection H as Hnm.\n  exact.\nQed.\n\nTheorem injection_ex2' : forall n m : nat,\n  Some n = Some m -> n = m.\nProof.\n  intros n m H.\n  injection H as Hnm.\n  exact.\nQed.\n\n(*\n* 同様にイコールでないことも構築の仕方から自明に分かる\n* それを即座に使うのが discriminate\n*)\n\nTheorem eqb_0_1 : forall n, 0 = n -> n = 0.\nProof.\n  intros [|m].\n  - done.\n  - discriminate.\nQed.\n\nTheorem explosion_ex1 : forall n, n.+1 = 0 -> 0 = 100.\nProof.\n  discriminate.\nQed.\n\n(*\n* ちなみに injection の逆は定理である\n*)\n\nCheck f_equal.\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  trivial.\nQed.\n\n(*\n自然数の二倍にする関数 double が injective であることを\n数学的帰納法で示す練習\n*)\n\nCheck double.\nCompute (double 3). (* 6 *)\n\nTheorem double_injective : forall n m,\n  double n = double m -> n = m.\nProof.\n  induction n.\n  - (* when n = 0; m must be 0 *)\n    case.\n    + (* when m = 0; ok *)\n      done.\n    + (* when m = _.+1; ng *)\n      discriminate.\n  - (* when n = _.+1 *)\n    induction m.\n    + (* when m = 0; ng *)\n      discriminate.\n      rewrite -! muln2.\n      rewrite !mulSn.\n      rewrite !muln2.\n      intro SS.\n      injection SS.\n      move/IHn.\n      apply f_equal.\nQed.\n\n(*\n量化に気をつけないと失敗する\n*)\n\nTheorem double_injective_FAILED : forall n m,\n  double n = double m -> n = m.\nProof.\n  intros n m.\n  induction n as [|n'].\n  - (* when n = 0 *)\n    intro eq.\n    destruct m.\n    + done.\n    + discriminate.\n  - (* when n = S n' *)\n    intro eq.\n    destruct m as [|m'].\n    + (* when m = 0 *)\n      discriminate.\n    + (* when m = S m' *)\nAbort.\n\n(*\ngeneralize dependent タクティクは全称量化を導入できる\nmove: とか revert と同じ？\n*)\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  (*\n  move: n.\n  revert n.\n  *)\n  induction m.\nAbort.\n\n(*\n条件式の場合分け\n*)\n\nDefinition silly_fun (n : nat) : bool :=\n  if n == 3 then false\n  else if n == 5 then false\n  else false.\n\nTheorem silly_fun_returns_false : forall n, silly_fun n = false.\nProof.\n  intro n.\n  unfold silly_fun.\n  - case (n == 3).\n    done.\n  - case (n == 5).\n    done.\n  - (* else *)\n    done.\nQed.\n\nCheck odd.\nCompute (odd 3).\nCompute (odd 4).\n\nDefinition silly_fun1 (n : nat) : bool :=\n  if n == 3 then true\n  else if n == 5 then true\n  else false.\n\nTheorem silly_fun1_is_true : forall n : nat,\n  silly_fun1 n = true -> odd n = true.\nProof.\n  intro n.\n  unfold silly_fun1.\n  - case (n == 3) eqn:n_is_3.\n    move/eqP in n_is_3.  (* _ == _ -> _ = _ *)\n    rewrite n_is_3.\n    done.\n  - case (n == 5) eqn:n_is_5.\n    move/eqP in n_is_5.\n    rewrite n_is_5.\n    done.\n  - discriminate.\nQed.\n", "meta": {"author": "cympfh", "repo": "coq-etude", "sha": "83deac7d6931ad48540b999e3c1649cf93b0a41e", "save_path": "github-repos/coq/cympfh-coq-etude", "path": "github-repos/coq/cympfh-coq-etude/coq-etude-83deac7d6931ad48540b999e3c1649cf93b0a41e/igarashi/class05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7571893122909145}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\n\nPrint ev.\nCheck ev_SS.\n\nTheorem ev_4: ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0.\n  Qed.\n\nPrint ev_4.\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\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.\n  Qed.\n\n(* Exercise eight_is_even *)\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.\n  Qed.\n\nDefinition ev_plus4' : forall n,\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) : ev (4+n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\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.\nShow Proof.\nDefined.\n\nPrint add1.\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\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. apply HP.\n  - intros [HQ HP]. split.\n    apply HP. apply HQ.\n  Qed.\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 conj_fact *)\nDefinition conj_fact: forall P Q R,\n  P/\\Q ->\n  Q/\\R ->\n  P/\\R.\nProof.\n  intros P Q R [HP HQ1] [HQ2 HR].\n  split.\n  apply HP.\n  apply HR.\n  Qed.\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(* Exercise or_commut'' *)\nDefinition or_comm: forall P Q,\n  P\\/Q -> Q\\/P.\nProof.\n  intros P Q [HP|HQ].\n  - right. apply HP.\n  - left. apply HQ.\n  Qed.\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\n(* Exercise ex_ev_Sn *)\n\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(* Exercise leibniz_equality *)\nLemma leibniz_equality: forall (X:Type)(x y : X),\n  x = y -> \n  forall P:X->Prop,\n  P x -> P y.\nProof.\n  intros X x y eqxy Px Hx.\n  induction eqxy. \n  apply Hx.\n  Qed.\n\nLemma four: 2+2 = 1+3.\nProof.\n  apply eq_refl.\n  Qed.\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.", "meta": {"author": "rpgzysb", "repo": "SoftwareFoundation", "sha": "4f987efcec24d880908edcb4f1c1cd3926c60291", "save_path": "github-repos/coq/rpgzysb-SoftwareFoundation", "path": "github-repos/coq/rpgzysb-SoftwareFoundation/SoftwareFoundation-4f987efcec24d880908edcb4f1c1cd3926c60291/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7571893066726005}}
{"text": "\nRequire Import Coq.Classes.SetoidClass.\nRequire Import MyInductions.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Peano_dec.\n\n\nModule NatList.\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\nend.\n\nDefinition snd(p : natprod) : nat :=\n  match p with\n      | pair x y => y\nend.\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.\nreflexivity.\nQed.\n\n\nTheorem surjective_pairing_stuck : forall (p : natprod), 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), (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), fst(swap_pair p) = snd p.\nProof.\n  intros p.\n  destruct p as [n m].\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).\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\nNotation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n      | 0 => 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 => S (length t)\nend.\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.\n\nExample test_app2: nil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\n\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.\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 nonzeros (l : natlist) : natlist :=\n  match l with\n    |    nil => nil\n    | h :: t => match h with\n                  | 0 => (nonzeros t)\n                  | _ => h::(nonzeros t)\n                end\n  end.\n\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nFixpoint odd(n : nat) :=\n  match n with\n    | 0 => false\n    | 1 => true\n    | S p => odd(p-1)\n  end.\n\nCheck odd.\n\nExample tst_odd : odd(31) = true.\nProof. simpl. reflexivity. Qed.\n\nFixpoint oddmembers (l : natlist) : natlist :=\n  match l with\n    | nil => nil\n    | h :: t => match (odd h) with\n                    | true => h::(oddmembers t)\n                    | false => (oddmembers t)\n                end\n  end.\n\nExample test_oddmembers : oddmembers([2;3;4;5;6;7;8;9;10;111;12;0;0;0;0;0;0;0]) = [3;5;7;9;111].\nProof. reflexivity. Qed.\n\nFixpoint countoddnumbers (l : natlist) : nat :=\n  match l with\n      | nil => 0\n      | h :: t => match (odd h) with\n                      | true => 1+(countoddnumbers t)\n                      | false => (countoddnumbers t)\n                  end\n  end.\n\nExample test_countoddnumbers : countoddnumbers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_coundoddnumbers2 : countoddnumbers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddnumbers3 : countoddnumbers nil = 0.      \nProof. reflexivity. Qed.\n\nFixpoint alternate(l1 l2 : natlist) : natlist :=\n  match l1 with\n      | nil => l2\n      | h1 :: t1 => match l2 with\n                    | nil => l1\n                    | h2 :: t2 => h1::h2::(alternate t1 t2)\n                    end\n  end.\n\nExample test_alternate1:\n  alternate [1;3;5] [2;4;6] = [1;2;3;4;5;6].\nProof. reflexivity. Qed.\n\nExample test_aternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\nProof. reflexivity. Qed.\n\n\nDefinition bag := natlist.\n\nCheck (1=1).\n\nFixpoint myeq_nat n m  :=\n  match n, m with\n    | O, O => true\n    | O, S _ => false\n    | S _, O => false\n    | S n1, S m1 => myeq_nat n1 m1\n  end.\n\nTheorem myeq_nat_eq : forall n, (myeq_nat n n) = true.\nProof.\ninduction n.\nsimpl.\nreflexivity.\nsimpl.\nassumption.\nQed.\n\nFixpoint count (v : nat) (s:bag) : nat :=\n  \n  match s with\n      | nil => 0\n      | h1 :: t1 => (if (myeq_nat v h1) then\n                      1+(count v t1)\n                    else\n                      (count v t1))\n                    \n  end.\n\nExample test_count1: count 1 [1;2;3;4;1;4;1] = 3.\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 := (cons v s).\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.                                   \nProof. reflexivity. Qed.\n\nExample test_add2 : count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool := \n  match (myeq_nat (count v s) 0) with\n    |      true => false\n    |      false => true\n  end.\n\nExample test_member1 : member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\n\nExample test_member2 : member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n\nFixpoint remove (v:nat) (s:bag) : bag :=\n match s with\n  |   [] => []\n  |   h::t => if (myeq_nat v h) then\n                (remove v t)\n              else\n                (h::remove v t)\n end.\n\nExample test_remove1 : remove 1 [1;4;1] = [4].\nProof. reflexivity. Qed.\n\nTheorem nat_p_1 : forall n : nat, S(n) <> 0.\nProof.\nintros.\ninduction n.\nauto.\nauto.\nQed.\n\nTheorem bag_theorem : forall n : nat, forall b : bag, ((count n (add n b)) <> 0).\nProof.\nintros.\nsimpl.\ninduction b.\ninduction n.\nsimpl.\nauto.\ninduction n.\nreplace (myeq_nat 1 1) with true.\nsimpl.\nauto.\nsimpl.\nreflexivity.\nreplace (myeq_nat (S (S n)) (S (S(n)))) with true.\ninduction n.\nsimpl.\nauto.\nset (count (S (S (S n))) []).\napply nat_p_1.\nset (S (S n)).\nsimpl.\nrewrite -> myeq_nat_eq.\nreflexivity.\nrewrite -> myeq_nat_eq.\nset (count n (n0 :: b)).\napply nat_p_1.\nQed.\n\nTheorem bag_theorem2 : forall n : nat, forall b : bag, ((count n (add n b)) = S(count n b)).\nintros.\nsimpl.\nrewrite -> myeq_nat_eq.\nset (count n b).\nreflexivity.\nQed.\n\nTheorem nil_app : forall l : natlist, [] ++ l = l.\nProof. reflexivity. Qed.\n\n\nTheorem tl_length_pred : forall l : natlist, pred (length l) = length(tl l).\nProof.\nintros l.\ndestruct l as [|n l'].\nreflexivity.\nreflexivity.\nQed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n                      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nintros l1 l2 l3.\ninduction l1 as [|n l1' IHl1'].\nreflexivity.\nsimpl. 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\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros.\n  induction l as [|n l' IHl'].\n  reflexivity.\n  simpl.\n  rewrite <- IHl'. \nAbort.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\nintros.\ninduction l1 as [|n l1' IHl1'].\nreflexivity.\nsimpl.\nrewrite -> IHl1'.\nreflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist, length (rev l) = length l.\nProof.\nintros l.\ninduction l as [|n l' IHl'].\nsimpl.\nreflexivity.\nsimpl.\nrewrite -> app_length, plus_comm.\nrewrite -> IHl'.\nreflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist, l ++ [] = l.\nProof.\nintros.\ninduction l.\nsimpl.\nreflexivity.\nreplace ((n::l) ++ []) with (n::(l++[])).\nrewrite ->IHl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n rev (rev l) = l.\nProof.\nintros.\ninduction l as [|n l' IHl'].\nreflexivity.\nsimpl.\nreplace (rev ( rev l' ++ [n])) with (n::(rev (rev l'))).\nrewrite -> IHl'.\nreflexivity.\nset (rev l').\ninduction n0.\nreflexivity.\nsimpl.\nrewrite <- IHn0.\nsimpl.\nreflexivity.\nQed.\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist, l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  intros.\n  induction l1.\n  simpl.\n  induction l2.\n  simpl.\n  reflexivity.\n  rewrite <- app_assoc.\n  reflexivity.\n  set (l1 ++ l2).\n  set (n::l1).\n  replace (((n1 ++ l2) ++ l3 ) ++ l4) with (n1 ++ (l2 ++ l3 ++ l4)).\n  reflexivity.\n  rewrite -> app_assoc.\n  unfold n1.\n  set (l3 ++ l4).\n  rewrite -> app_assoc.\n  reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist, nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros.\n  induction l1.\n  reflexivity.\n  induction l2.\n  rewrite -> app_nil_r.\n  replace (nonzeros []) with ([]).\n  replace (nonzeros (n::l1) ++ []) with (nonzeros(n::l1)).\n  reflexivity.\n  rewrite -> app_nil_r.\n  reflexivity.\n  reflexivity.\n  induction n.\n  induction n0.\n  simpl.\n  rewrite ->IHl1.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite ->IHl1.\n  simpl.\n  reflexivity.\n  simpl.\n  induction n0.\n  rewrite ->IHl1.\n  simpl.\n  reflexivity.\n  rewrite ->IHl1.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n|      [] => match l2 with \n               |  [] => true \n               | h::t => false\n             end\n|       h1::t1 => match l2 with\n                 | [] => false\n                 | h2::t2 => (if (myeq_nat h1 h2) then (beq_natlist t1 t2) else false)\n                  end\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, true = beq_natlist l l.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  induction n.\n  simpl.\n  assumption.\n  simpl.\n  replace (myeq_nat n n) with true.\n  assumption.\n  rewrite -> myeq_nat_eq.\n  reflexivity.\nQed.\n\n\n(*SearchAbout rev.*)\n\nTheorem count_member_nonzero : forall (s : bag), leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros.\n  induction s.\n  simpl.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n, leb n (S n) = true.\nProof.\n  intros.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  assumption.\nQed.\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n|      [] => []\n|      h::t => (if (myeq_nat v h) then t else h::(remove_one v (t)) )\n  end.\n\nExample test_remove_one1 : count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof.\n  reflexivity.\nQed.\n\nExample test_remove_one2 : count 5 (remove_one 5 [2;1;4;1]) = 0.\nProof.\n  reflexivity.\nQed.\n\n\nTheorem remove_decreases_count : forall s : bag, leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros.\n  induction s.\n  reflexivity.\n  induction n.  \n  simpl.\n  set (count 0 s).\n  rewrite -> ble_n_Sn.\n  reflexivity.\n  simpl.\n  assumption.\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    | (aa :: t) => (match myeq_nat n 0 with\n                   | true => Some aa\n                   | false => nth_error t (pred n)\n               end)\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\n\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\n\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\nEnd NatList.", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/NatList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7571805510807508}}
{"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\nDefinition leq (x : Nat) (y : Nat) : bool :=\n  Nat_beq x y || less x y.\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 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.\n\nLemma not_less : forall (x y : Nat), 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    + reflexivity.\n    + discriminate.\n  - intros. unfold leq. destruct y.\n    + reflexivity.\n    + simpl in H. apply IHx in H. unfold leq in H. simpl. assumption.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Nat), sorted x = true -> sorted (insort y x) = true.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - destruct x.\n    + simpl. destruct (less y n) eqn:?.\n      * simpl. unfold leq. rewrite Heqb. apply orb_true_r.\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.\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/goal62.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7571805393786822}}
{"text": "Require Import List.\n\nInductive Typ : Set :=\n  | Top : Typ\n  | Imp : Typ -> Typ -> Typ\n  | Cnj : Typ -> Typ -> Typ.\n\nInductive Trm : Set :=\n  | top : Trm\n  | hyp : nat -> Trm\n  | lam : Typ -> Trm -> Trm\n  | app : Trm -> Trm -> Trm\n  | cnj : Trm -> Trm -> Trm\n  | proj_1 : Trm -> Trm\n  | proj_2 : Trm -> Trm.\n\nDefinition  Cntxt := list Typ.\n\nInductive Tyty : Cntxt -> Trm -> Typ -> Prop :=\n  | ND_top_intro : forall G, Tyty G top Top\n  | ND_hypO : forall G A, Tyty (A :: G) (hyp 0) A\n  | ND_hypS :\n      forall G A B I,\n      Tyty G (hyp I) A -> Tyty (B :: G) (hyp (S I)) A\n  | ND_lam :\n      forall G t A B,\n      Tyty (A :: G) t B -> Tyty G (lam A t) (Imp A B)\n  | ND_app :\n      forall G t s A B,\n      Tyty G t (Imp A B) -> Tyty G s B -> Tyty G (app t s) B\n  | ND_cnj :\n      forall G t s A B,\n      Tyty G t A -> Tyty G s B -> Tyty G (cnj t s) (Cnj A B)\n  | ND_proj_1 :\n      forall G t A B,\n      Tyty G t (Cnj A B) -> Tyty G (proj_1 t) A\n  | ND_proj_2 :\n      forall G t A B,\n      Tyty G t (Cnj A B) -> Tyty G (proj_2 t) B.\n\nNotation \"G '⊢' t '[:]' A\" := (Tyty G t A) (at level 70, no associativity) : type_scope.\n\nNotation \"'⊢' t '[:]' A\" := (Tyty nil t A) (at level 70, no associativity) : type_scope.\n\n\nLemma problem_1 : forall A B, exists t, ⊢ t [:] (Imp A (Imp B A)).\nProof.\n  intros.\n  exists (lam A (lam B (hyp 1))).\n  apply ND_lam.\n  apply ND_lam.\n  apply ND_hypS.\n  apply ND_hypO.\n  Show Proof.\nQed.\n", "meta": {"author": "mozow01", "repo": "logic_and_category", "sha": "7ee90681839be81f7a70b78f0c518df903b9086d", "save_path": "github-repos/coq/mozow01-logic_and_category", "path": "github-repos/coq/mozow01-logic_and_category/logic_and_category-7ee90681839be81f7a70b78f0c518df903b9086d/mindenfele/natural deduction for the negative fragment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7571736472595425}}
{"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.FOL.TRAKHTENBROT\n  Require Import notations utils decidable.\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-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/discernable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.75717364689649}}
{"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.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 :\nforall (x:R),\n ((0%R <= x)%R -> ((Reals.Rbasic_fun.Rabs x) = x))\n /\\ ((~ (0%R <= x)%R) -> ((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 :\nforall (x:R) (y:R),\n ((Reals.Rbasic_fun.Rabs x) <= y)%R <-> (((-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 :\nforall (x:R), (0%R <= (Reals.Rbasic_fun.Rabs x))%R.\nexact Rabs_pos.\nQed.\n\n(* Why3 goal *)\nLemma Abs_sum :\nforall (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 :\nforall (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 :\nforall (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": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/real/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7571736395557775}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.ZArith.Znumtheory.\nRequire Import Coq.micromega.Lia.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma prime_odd_or_2 : forall p (prime_p : prime p), p = 2 \\/ Z.odd p = true.\n  Proof.\n    intros p prime_p.\n    apply Decidable.imp_not_l; try apply Z.eq_decidable.\n    intros p_neq2.\n    pose proof (Zmod_odd p) as mod_odd.\n    destruct (Sumbool.sumbool_of_bool (Z.odd p)) as [? | p_not_odd]; auto.\n    rewrite p_not_odd in mod_odd.\n    apply Zmod_divides in mod_odd; try lia.\n    destruct mod_odd as [c c_id].\n    rewrite Z.mul_comm in c_id.\n    apply Zdivide_intro in c_id.\n    apply prime_divisors in c_id; auto.\n    destruct c_id; [lia | destruct H; [lia | destruct H; auto] ].\n    pose proof (prime_ge_2 p prime_p); lia.\n  Qed.\n\n  Lemma odd_mod : forall a b, (b <> 0)%Z ->\n    Z.odd (a mod b) = if Z.odd b then xorb (Z.odd a) (Z.odd (a / b)) else Z.odd a.\n  Proof.\n    intros a b H.\n    rewrite Zmod_eq_full by assumption.\n    rewrite <-Z.add_opp_r, Z.odd_add, Z.odd_opp, Z.odd_mul.\n    case_eq (Z.odd b); intros; rewrite ?Bool.andb_true_r, ?Bool.andb_false_r; auto using Bool.xorb_false_r.\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/Odd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7569966908059245}}
{"text": "(******************************************************************************)\n(* Solutions of exercises : A script language for structured proofs           *)\n(******************************************************************************)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nRequire Import path choice fintype tuple finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(******************************************************************************)\n(* Exercise 3.2.1                                                             *)\n(******************************************************************************)\n\nSection Tauto.\n\nVariables A B C : Prop.\n\n(* The exact tactic takes its argument on top of the goal stack *)\nLemma tauto1 : A -> A.\nProof.\nexact.\nQed.\n\n(* exact: hAB behaves like (by apply: hAB) and hence finds the hypothesis A\nin the context needed to solve the goal *)\nLemma tauto2 : (A -> B) -> (B -> C) -> A -> C.\nProof.\nmove=> hAB hBC hA.\napply: hBC.\nexact: hAB.\nQed.\n\nLemma tauto3 : A /\\ B <-> B /\\ A.\nProof. by split; case=> h1 h2; split. Qed.\n  \nEnd Tauto.\n\n(******************************************************************************)\n(* Exercise 3.2.2                                                             *)\n(******************************************************************************)\n\nSection MoreBasics.\n\nVariables A B C : Prop.\nVariable P : nat -> Prop.\n\nLemma foo1 : ~(exists x, P x) -> forall x, ~P x.\nmove=> h x Px.\napply: h.\nby exists x.\nQed.\n\n\nLemma foo2 : (exists x, A -> P x) -> (forall x, ~P x) -> ~A.\nProof.\ncase=> x hx hP hA.\napply: (hP x).\nexact: hx.\nQed.\nEnd MoreBasics.\n\n(******************************************************************************)\n(* Exercise 3.2.3                                                             *)\n(******************************************************************************)\n\n(* Try Search \"<=\" to see the various notations featuring <= *)\n\n(* The first line of the returned answer gives the name of\n   the predicate (leq) *)\nSearch \"_ <= _\".\n\n(* The Print command shows that leq is defined using subtraction *)\nPrint leq.\n\n(* This time we see that the first line of the answer gives the *)\n(*answer: there is no constant defining \"<\" but the notation hides a *)\n(* defintiion using leq *)\n\nSearch \"_ < _\".\n\n(* Both cases gereated by the induction lead to trivial goals *)\nLemma tuto_subnn : forall n : nat, n - n = 0.\nProof. by elim=> [|n ihn]. Qed.\n  \n(* This proof is an induction on m, followed by a case  analysis on *)\n(* the second n. Base case is trivial (hence discarded by the // *)\n(* switch. *)\nLemma tuto_subn_gt0 : forall m n, (0 < n - m) = (m < n).\nProof. elim=> [|m IHm] [|n] //; exact: IHm. Qed.\n\n\n(* This proof starts the same way as the one of subn_gt0. *)\n(* Then two rewriting are chained to reach to trivial subgoals *)\nLemma tuto_subnKC : forall m n : nat, m <= n -> m + (n - m) = n.\nProof.\nelim=> [|m IHm] [|n] // Hmn.\nSearch _ (_.+1 + _ = _.+1).\nby rewrite addSn IHm.\nQed.\n  \n(* The first Search command suggests we need to use something like *)\n(*subn_add2r, hence to transform n into n - p + p *)\n(* The second Search command finds the appropriate lemma. We rewrite *)\n(*it from right to left, only at the second occurrence of n, the *)\n(*condition of the lemma is fullfilled thanks to the le_pn hypothesis, *)\n(*hence the generated subgoal is closed by the // switch *)\n\nLemma tuto_subn_subA : forall m n p, p <= n -> m - (n - p) = m + p - n.\nProof. \nmove=> m n p le_pn.\nSearch _ (_ + _ - _ = _) in ssrnat.\nSearch _ (_ - _ + _).\nrewrite -{2}(subnK le_pn) // subn_add2r.\ndone. \nQed.\n\n(******************************************************************************)\n(* Exercise 3.5.1                                                             *)\n(******************************************************************************)\n\n(* The Check instruction only gives the type of a constant, the *)\n(*statement of a lemma. The Print command gives the body of the *)\n(*definition, and possibly some extra information (scope, implicit *)\n(*arguments,...). Print should not be used in general on lemmas *)\n(* since the body of a proof is seldom relevant...*)\n\nPrint edivn.\nPrint edivn_rec.\nPrint edivn_spec.\n(* The edivn_spec is defined as a CoInductive predicate. The intended *)\n(* meaning is not to define an coinductive structure, but rather an *)\n(* inductive one. CoInductive in this case indeed behaves as Inductive *)\n(*but does not generate an induction principle, which would be is *)\n(*useless in this case. *)\n\n\n(******************************************************************************)\n(* Exercise 3.5.2                                                             *)\n(******************************************************************************)\n\n(* At this point, the top of the goal stack was featuring three *)\n(*natural numers: an induction on the first one generated two subgoals. *)\n(*In the second subgoal, corresponding to the inductive case, the *)\n(*generated natural number and induction hypothesis have  been *)\n(*introduced by the branching intro pattern [| n IHn], which leaves *)\n(*the first subgoal, corresponding to the base case of the induction, *)\n(*unchanged. Then [|m] performs in both subgoals a case analysis on the *)\n(*second natural number. This case analysis again leads to two new *)\n(*subgoal for each initial branch (which makes four subgoals). In the *)\n(*second case of the analysis, the new natural number is introduced *)\n(*and named m. Then the third natural number is uniformly introdued in *)\n(*the four cases under the name q. Finally the //= switch simplifies *)\n(*in the four bracnhes and closes the goals that have become trivial *)\n(*(i.e. which are solved by done). *)\n\n(******************************************************************************)\n(* Exercise 3.5.3                                                             *)\n(******************************************************************************)\n\n(* The pattern [// | le_dm] closes the first subgoal and introduces an *)\n(*hypothesis named le_dm in the second subgoal. This is equivalent to *)\n(* // le_dm. *)\n\n(******************************************************************************)\n(* Exercise 3.5.4                                                             *)\n(******************************************************************************)\n\n(* Replacing (ltnP m d) by ltnP does not change the behaviour of the *)\n(*script: Coq's unification is powerful enough to guess the arguments *)\n(*in this case since there is only one instance of the comparison in *)\n(* (_ <_) the goal. Arguments are mandatory only in the case the frist *)\n(*occurrence of the comparison is not the one the user whould like to *)\n(*pick as support for ase analysis. *)\n\nCheck ltnP.\nPrint ltn_xor_geq.\n\n(* For any two natural numbers n and m, (ltn_xor_geq m n) is a binary *)\n(*relation on boolean. Its inductive definition has two constructors *)\n(*and states that *)\n(* - (false, true) is in the relation(ltn_xor_geq m n) as soon as \n     m < n *)\n(* - (true, false) is in the relation(ltn_xor_geq m n) as soon as \n     n <= m *)\n(* The inductive construction implies that these two rules are the *)\n(*only ways to populate the relation.*)\n(* Now the theorem:*)\n(* ltnP :  forall m n : nat, ltn_xor_geq m n (n <= m)(m < n)*)\n(*proves that for any two natural numbers m and n, there are only two*)\n(*possible situations:*)\n(* - either m < n (first rule of the relation definition), and in this *)\n(*case n <= m = false and m < n = true *)\n(* - or n <= m (second rule of the relation definition, and in this *)\n(*case n <= m = true and m < n = false *)\n(* A case analysis on this result hence generates two subgoals, one *)\n(*for each constructor of ltn_xor_gep. In each subgoal the hypothesis *)\n(*of the rule (repectively m < n and n <= m) appears on the stack. Also *)\n(*every occurrence of (n <= m) and (m < n) is replaced by the value *)\n(*imposed by the ltn_xor_gep constructor used in the branch.*)\n\nCoInductive tuto_compare_nat (m n : nat) : bool -> bool -> bool -> Set :=\n  | TCompareNatLt of m < n : tuto_compare_nat m n true false false\n  | TCompareNatGt of m > n : tuto_compare_nat m n false true false\n  | TCompareNatEq of m = n : tuto_compare_nat m n false false true.\n\n(* Let's check against what is defined in the ssrnat library *)\nPrint compare_nat.\n\nLemma tuto_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\n\n\n", "meta": {"author": "catalin-hritcu", "repo": "exos-ssr", "sha": "ad161e4130822e4cef2e29dc76cae1c92f28ab0c", "save_path": "github-repos/coq/catalin-hritcu-exos-ssr", "path": "github-repos/coq/catalin-hritcu-exos-ssr/exos-ssr-ad161e4130822e4cef2e29dc76cae1c92f28ab0c/OnLineExos/section3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.7569184870984077}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Setoid.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import PeanoNat.\nImport Nat.\n\nRequire Import Lib.LinearOrder.\nRequire Import Lib.Sorted.\n\nInductive BT(A : Type) : Type :=\n  | leaf : A -> BT A\n  | node : BT A -> BT A -> BT A.\n\nArguments leaf {A}.\nArguments node {A}.\n\nFixpoint BTInsert {A : Type} (x : A) (tree : BT A) :=\n  match tree with\n  | leaf y => node (leaf x)(leaf y)\n  | node l r => node r (BTInsert x l)\n  end.\n\nFixpoint BTSize{A : Type}(tree : BT A) :=\n  match tree with\n  | leaf y => 1\n  | node l r => BTSize l + BTSize r\n  end.\n\nFixpoint listToBT{A : Type}(x : A)(list : list A): BT A :=\n  match list with\n  | nil => leaf x\n  | cons y list' => BTInsert x (listToBT y list')\n  end.\n\nFixpoint merge {A : Type} (ord : A -> A -> bool) (l1 : list A): (list A) -> list A :=\n  match l1 with\n  | [] => fun (l2 : list A) => l2\n  | h1::t1 => fix anc (l2 : list A) : list A :=\n    match l2 with\n    | [] => l1\n    | h2::t2 => if ord h1 h2 \n                then h1::(merge ord t1) l2\n                else h2::anc t2\n    end\n  end.\n\nFixpoint BTSort {A : Type} (ord : A -> A -> bool) (t : BT A): list A :=\n  match t with\n  | leaf x => [x]\n  | node l r => merge ord (BTSort ord l) (BTSort ord r)\n  end. \n\nDefinition mergeSort {A: Type} (ord : A -> A -> bool) (l: list A): list A :=\n  match l with\n  | [] => []\n  | x::l' => BTSort ord (listToBT x l')\n  end.\n\nFixpoint BTToList{A: Type}(t: BT A) : list A :=\n  match t with\n  | leaf a => [a]\n  | node l r => (BTToList l) ++ (BTToList r)\n  end.\n\n\n(* Perm def *)\nFixpoint BTCount {A: Type} (p: A -> bool) (t: BT A) :=\n  match t with\n  | leaf x => if p x then 1 else 0\n  | node l r => BTCount p l + BTCount p r\n  end.\n\nDefinition BTListPermutation{A: Type}(t: BT A)(l: list A) : Prop :=\n  forall p: A->bool, BTCount p t = count p l.\n\nDefinition BTPermutation{A: Type}(t1 t2: BT A) : Prop :=\n  forall p: A->bool, BTCount p t1 = BTCount p t2.\n\nLemma merge_perm {A: Type} (p: A->bool) (ord: A->A->bool) (l1 l2 : list A) :\n  count p l1 + count p l2 = count p (merge ord l1 l2).\nProof.\n  revert l2. induction l1; intros l2; auto.\n  induction l2.\n  - cbn. rewrite add_0_r. trivial.\n  - cbn. destruct (ord a a0).\n    + destruct (ord a0 a); cbn; destruct (p a); cbn;\n      f_equal; rewrite <- IHl1; auto.\n    + destruct (ord a0 a); cbn in *; destruct (p a0);\n      try rewrite Nat.add_succ_r; try f_equal;\n      rewrite <- IHl2; auto.\nQed.\n\nLemma BTSort_is_perm (A:Type) (ord: A->A->bool) (t : BT A) (p: A->bool) :\n  BTCount p t = count p (BTSort ord t).\nProof.\n  revert p. induction t; intro p; auto. cbn.\n  rewrite IHt1, IHt2, <- merge_perm. auto.\nQed.\n\nLemma BT_insert_count (A : Type) (p: A->bool) (x : A) (t : BT A):\n  BTCount p (BTInsert x t) = if p x then S (BTCount p t) else BTCount p t.\nProof.\n  induction t; cbn.\n  - destruct (p x), (p a); auto.\n  - rewrite IHt1. destruct (p x); cbn.\n    1: rewrite add_succ_r; f_equal.\n    1-2: rewrite add_comm; auto. \nQed.\n\nLemma BTSort_perm (A: Type) (ord: A->A->bool) (l : list A) (x: A) :\n   permutation (x::l) (BTSort ord (listToBT x l)).\nProof.\n  revert x. induction l; intro x; cbn; try constructor.\n  unfold permutation in *. intros p. rewrite <- BTSort_is_perm.\n  rewrite BT_insert_count. cbn. destruct (p x) eqn:e.\n  1: f_equal.\n  1-2: cbn in *; rewrite IHl, <- BTSort_is_perm; auto.\nQed.\n\n\nLemma merged_sorted_lists (A: Type) `{lo: LinearOrder A} (l1 l2: list A) :\n  Sorted l1 -> Sorted l2 -> Sorted (merge ord l1 l2).\nProof.\n  intros s1. revert l2. induction s1; auto.\n  - intros l2 s2. induction s2; cbn; try constructor.\n    + destruct (ord h h0) eqn:o; constructor; try constructor; auto.\n      apply ord_false_true. auto.\n    + cbn. destruct (ord h h0) eqn:o.\n      * assert (ord h h' = true) by (apply (trans h h0 h'); auto).\n        cbn in IHs2. rewrite H0 in IHs2. \n        constructor; try constructor; [dependent destruction IHs2 | | ]; auto.\n      * cbn in IHs2. destruct (ord h h') eqn:o2; constructor; auto.\n        apply ord_false_true; auto.\n  - intros l2 s2. induction s2.\n    + cbn. constructor; auto.\n    + specialize (IHs1 [h0]). cbn in *. destruct (ord h' h0) eqn:o1.\n      * assert (ord h h0 = true) by (apply (trans _ h' _); auto).\n        rewrite H0. constructor; auto. apply IHs1. constructor.\n      * destruct (ord h h0) eqn:o2; constructor; auto.\n        -- apply IHs1; constructor.\n        -- constructor; auto.\n        -- apply ord_false_true; auto.\n    + destruct (ord h h0) eqn:o1.\n      * specialize (IHs1 (h0 :: h'0 :: t1)). cbn. rewrite o1.\n        destruct (ord h' h0) eqn:o2; constructor; auto.\n        1-2: cbn in IHs1; rewrite o2 in IHs1; apply IHs1; constructor; auto.\n      * cbn in *. rewrite o1. destruct (ord h h'0) eqn:o2; constructor; auto.\n        apply ord_false_true; assumption.\nQed.\n\nLemma BT_sorts (A: Type) `{lo: LinearOrder A} (t: BT A) : Sorted (BTSort ord t).\nProof.\n  induction t; cbn.\n  - constructor.\n  - apply merged_sorted_lists; assumption.\nQed.\n\nTheorem mergeSort_is_sorted (A: Type) `{lo: LinearOrder A} (l: list A):\n  Sorted (mergeSort ord l).\nProof.\n  induction l; cbn; try constructor. now apply BT_sorts.\nQed.\n\nTheorem mergeSort_is_perm (A: Type) `{lo: LinearOrder A} (l: list A):\n  permutation l (mergeSort ord l).\nProof.\n  induction l; cbn.\n  - unfold permutation. intro. cbn. reflexivity.\n  - now apply BTSort_perm.\nQed.\n\nTheorem merge_sort_idempotent (A: Type) `{lo: LinearOrder A} (l: list A):\n  (mergeSort ord l) = (mergeSort ord (mergeSort ord l)).\nProof.\n  apply sorted_unique_representation; auto.\n  - apply mergeSort_is_perm.\n  - apply mergeSort_is_sorted.\n  - apply mergeSort_is_sorted.\nQed.\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/Lib/MergeSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7569184824992682}}
{"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 Relations Permutation.\n\nRequire Import rel_utils.\n\nRequire Import list_aux.\nRequire Import list_perm.\nRequire Import list_prod.\nRequire Import list_forall.\n\n(*\nRequire Import finite.\n*)\n\nSet Implicit Arguments.\n\nSection list_fan.\n\n  Variable (X : Type).\n\n  Fixpoint list_fan (lw : list (list X)) := \n    match lw with\n      | nil => nil::nil\n      | w::lw => list_prod (@cons _) w (list_fan lw)\n    end.\n\n  (* list_fan [l1;...;lk] contains all the list of the form [x1;...;xk] \n     with x1 in l1, x2 in l2 ... xk in lk \n  *)\n\n  Fact list_fan_eq_nil lw : list_fan lw = nil -> exists w, In w lw /\\ w = nil.\n  Proof.\n    induction lw as [ | w lw IH ]; simpl.\n    discriminate 1.\n    intros H.\n    apply list_prod_nil in H.\n    destruct H as [ H | H ].\n    exists w; auto.\n    destruct (IH H) as (w' & ? & ?).\n    exists w'; auto.\n  Qed.\n\n  Fact list_fan_spec lw : forall w, In w (list_fan lw) <-> Forall2 (@In _) w lw.\n  Proof.\n    induction lw as [ | w lw ]; intros x; simpl.\n    destruct x as [ | ].\n    split; auto.\n    split.\n    intros [ H | [] ]; discriminate H.\n    intros H; inversion H.\n    rewrite list_prod_spec.\n    split.\n    intros (a & u & H1 & H2 & ?); subst.\n    constructor; auto.\n    revert H2; apply IHlw.\n    intros H; destruct x as [ | a x ]; inversion_clear H.\n    exists a, x; repeat split; auto.\n    apply IHlw; auto.\n  Qed.\n\n  Fact list_fan_cons_In w lw l : In l (list_fan (w::lw)) <-> exists x l', In x w /\\ In l' (list_fan lw) /\\ l = x::l'.\n  Proof.\n    simpl.\n    rewrite list_prod_spec.\n    split; auto.\n  Qed.\n \n  Fact list_fan_app w1 w2 lw : list_fan ((w1++w2)::lw) ~p list_fan (w1::lw) ++ list_fan (w2::lw).\n  Proof.\n    apply list_prod_app_left.\n  Qed.\n\n  Fact list_fan_cons a w lw : list_fan ((a::w)::lw) ~p list_fan ((a::nil)::lw) ++ list_fan (w::lw).\n  Proof.\n    apply (list_fan_app (a::nil)).\n  Qed.\n\n  Fact list_fan_nil lw rw : list_fan (lw++nil::rw) = nil.\n  Proof.\n    induction lw as [ | w lw IH ]; simpl.\n    apply list_prod_nil_left.    \n    rewrite IH, list_prod_nil_right; auto.\n  Qed.\n\n  Fact list_fan_sg_left lw a : list_fan ((a::nil)::lw) = map (cons a) (list_fan lw).\n  Proof.\n    simpl list_fan at 1.\n    unfold list_prod.\n    generalize (list_fan lw); clear lw.\n    induction l; simpl; f_equal; auto.\n  Qed.\n\n  Fact list_fan_sg_right lw a : list_fan (lw++(a::nil)::nil) = map (fun w => w++a::nil) (list_fan lw).\n  Proof.\n    induction lw as [ | w lw IH ]; simpl; auto.\n    rewrite IH.\n    unfold list_prod.\n    rewrite map_flat_map, flat_map_map.\n    apply flat_map_ext.\n    intros x _.\n    rewrite map_map.\n    apply map_ext.\n    intros ?; auto.\n  Qed.\n\n  Fact list_fan_middle_app lw w1 w2 rw : list_fan (lw++(w1++w2)::rw) ~p list_fan (lw++w1::rw) ++ list_fan (lw++w2::rw).\n  Proof.\n    induction lw as [ | w lw IHlw ].\n    simpl app at 1 3.\n    rewrite list_fan_app; auto; simpl.\n    apply list_prod_perm with (f := @cons X) (1 := Permutation_refl w) in IHlw.\n    apply Permutation_trans with (1 := IHlw),\n          Permutation_trans with (1 := list_prod_app_right _ _ _ _); auto.\n  Qed.\n  \n  Fact list_fan_middle_cons lw a w rw : list_fan (lw++(a::w)::rw) ~p list_fan (lw++(a::nil)::rw) ++ list_fan (lw++w::rw).\n  Proof.\n    apply list_fan_middle_app with (w1 := a::nil).\n  Qed.\n\n  Fact list_fan_mono lw mw : Forall2 (@incl _) lw mw -> incl (list_fan lw) (list_fan mw).\n  Proof.\n    induction 1 as [ | l m lw mw H1 H2 IH2 ].\n    apply incl_refl.\n    intros x Hx.\n    rewrite list_fan_spec in Hx.\n    rewrite list_fan_spec.\n    destruct x as [ | a x ].\n    inversion Hx.\n    apply Forall2_cons_inv in Hx.\n    destruct Hx as [ Ha Hx ].\n    constructor 2.\n    revert Ha; auto.\n    revert Hx; do 2 rewrite <- list_fan_spec; auto.\n  Qed.\n\n  Let list_fan_rev_alt x lw : In x (list_fan lw) -> In (rev x)  (list_fan (rev lw)).\n  Proof.\n    do 2 rewrite list_fan_spec.\n    induction 1; simpl.\n    constructor.\n    apply Forall2_app; auto.\n  Qed.\n\n  Fact list_fan_rev x lw : In (rev x)  (list_fan (rev lw)) <-> In x (list_fan lw).\n  Proof.\n    split; auto.\n    rewrite <- (rev_involutive lw) at 2.\n    rewrite <- (rev_involutive x) at 2.\n    auto.\n  Qed.\n\n  Fact list_fan_length lw w : In w (list_fan lw) -> length w = length lw.\n  Proof.\n    rewrite list_fan_spec.\n    apply Forall2_length.\n  Qed.    \n\n  Section list_fan_Forall.\n\n    Variable P : list X -> Prop.\n  \n    Fact list_fan_Forall_cons a lw : Forall (fun l => P (a::l)) (list_fan lw) \n                                  -> Forall P (list_fan ((a::nil)::lw)).\n    Proof.\n      do 2 rewrite Forall_forall.\n      intros H x Hx.\n      rewrite list_fan_sg_left, in_map_iff in Hx.\n      destruct Hx as (y & H1 & Hx); subst; auto.\n    Qed.\n    \n    Fact list_fan_Forall w lw : Forall (fun a => Forall (fun l => P (a::l)) (list_fan lw)) w \n                             -> Forall P (list_fan (w::lw)).\n    Proof.\n      induction w as [ | a w IH ].\n      generalize (list_fan_nil nil lw); simpl; intros H; rewrite H; constructor.\n      intros H; rewrite (Forall_perm _ (list_fan_cons _ _ _)), Forall_app; split.\n      apply list_fan_Forall_cons.\n      apply Forall_inv in H; auto.\n      apply IH.\n      inversion_clear H; auto.\n    Qed.\n\n  End list_fan_Forall.\n\n  Fact list_fan_Forall_Forall P ll : Forall (Forall P) ll -> Forall (Forall P) (list_fan ll).\n  Proof.\n    induction 1 as [ | x ll Hx Hll IHll ].\n    constructor; constructor.\n    apply list_fan_Forall.\n    revert Hx; do 2 rewrite Forall_forall; intros Hx u Hu.\n    revert IHll; apply Forall_impl; constructor; auto.\n  Qed.\n\nEnd list_fan.\n\nFact list_fan_map_map U V (f : U -> V) (ll : list (list U)) : list_fan (map (map f) ll) = map (map f) (list_fan ll).\nProof.\n  induction ll as [ | ? ? IH ]; simpl; f_equal.\n  rewrite IH.\n  rewrite <- list_prod_map, map_list_prod.\n  auto.\nQed.\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_fan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7569184734947615}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\n\n(* The set of the group. *)\nAxiom G : Set.\n\n(* The left identity for +. *)\nAxiom e : G.\n\n(* The right identity for +. *)\nAxiom m : G.\n\n(* + binary operator. *)\nAxiom f : G -> G -> G.\n\n(* For readability, we use infix <+> to stand for the binary operator. *)\nInfix \"<+>\" := f (at level 50).\n\n(* [m] is the right-identity for all elements [a] *)\nAxiom id_r : forall a, a <+> m = a.\n\n(* [e] is the left-identity for all elements [a] *)\nAxiom id_l : forall a, e <+> a = a.\n\nLtac surgery dir e1 e2 :=\n  match goal with\n  | [ |- _ ] =>\n    let H := fresh in\n    (have H : e1 = e2 by repeat (rewrite dir); reflexivity); rewrite H; clear H\n  end.\n\nLemma rewrite_eq_0: forall b: G, ((e <+> (e <+> m)) <+> ((b <+> ((m <+> m) <+> m)) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f b (f (f m m) m)) (f (f e e) m)))) ((f (f e m) (f (f b (f (f m m) m)) (f (f e e) m)))).\nsurgery id_r ((f (f e m) (f (f b (f (f m m) m)) (f (f e e) m)))) ((f e (f (f b (f (f m m) m)) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b (f (f m m) m)) (f (f e e) m)))) ((f e (f (f b (f m m)) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f (f e e) m)))) ((f e (f (f b m) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e e) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_1: forall b: G, ((((e <+> e) <+> m) <+> ((e <+> m) <+> ((e <+> m) <+> m))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f (f e m) (f (f e m) m))) (f b m))) ((f (f (f e e) (f (f e m) (f (f e m) m))) (f b m))).\nsurgery id_l ((f (f (f e e) (f (f e m) (f (f e m) m))) (f b m))) ((f (f e (f (f e m) (f (f e m) m))) (f b m))).\nsurgery id_r ((f (f e (f (f e m) (f (f e m) m))) (f b m))) ((f (f e (f e (f (f e m) m))) (f b m))).\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_2: forall b: G, ((e <+> ((((e <+> e) <+> m) <+> e) <+> m)) <+> (e <+> (e <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f (f e e) m) e) m)) (f e (f e (f e b))))) ((f (f e (f (f (f e e) e) m)) (f e (f e (f e b))))).\nsurgery id_l ((f (f e (f (f (f e e) e) m)) (f e (f e (f e b))))) ((f (f e (f (f e e) m)) (f e (f e (f e b))))).\nsurgery id_l ((f (f e (f (f e e) m)) (f e (f e (f e b))))) ((f (f e (f e m)) (f e (f e (f e b))))).\nsurgery id_l ((f (f e (f e m)) (f e (f e (f e b))))) ((f (f e m) (f e (f e (f e b))))).\nsurgery id_r ((f (f e m) (f e (f e (f e b))))) ((f e (f e (f e (f e b))))).\nsurgery id_l ((f e (f e (f e (f e b))))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_3: forall b: G, (e <+> (((e <+> m) <+> e) <+> (e <+> (((e <+> e) <+> m) <+> (b <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f e m) e) (f e (f (f (f e e) m) (f b m)))))) ((f e (f (f e e) (f e (f (f (f e e) m) (f b m)))))).\nsurgery id_l ((f e (f (f e e) (f e (f (f (f e e) m) (f b m)))))) ((f e (f e (f e (f (f (f e e) m) (f b m)))))).\nsurgery id_l ((f e (f e (f e (f (f (f e e) m) (f b m)))))) ((f e (f e (f (f (f e e) m) (f b m))))).\nsurgery id_l ((f e (f e (f (f (f e e) m) (f b m))))) ((f e (f (f (f e e) m) (f b m)))).\nsurgery id_r ((f e (f (f (f e e) m) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_4: forall b: G, (((e <+> (e <+> (((e <+> m) <+> m) <+> (m <+> m)))) <+> m) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f e (f (f (f e m) m) (f m m)))) m) (f e b))) ((f (f e (f e (f (f (f e m) m) (f m m)))) (f e b))).\nsurgery id_l ((f (f e (f e (f (f (f e m) m) (f m m)))) (f e b))) ((f (f e (f (f (f e m) m) (f m m))) (f e b))).\nsurgery id_r ((f (f e (f (f (f e m) m) (f m m))) (f e b))) ((f (f e (f (f e m) (f m m))) (f e b))).\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f e b))) ((f (f e (f e (f m m))) (f e b))).\nsurgery id_l ((f (f e (f e (f m m))) (f e b))) ((f (f e (f m m)) (f e b))).\nsurgery id_r ((f (f e (f m m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_5: forall b: G, ((((e <+> e) <+> ((e <+> e) <+> (e <+> m))) <+> (e <+> m)) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f (f e e) (f e m))) (f e m)) (f b m))) ((f (f (f e (f (f e e) (f e m))) (f e m)) (f b m))).\nsurgery id_l ((f (f (f e (f (f e e) (f e m))) (f e m)) (f b m))) ((f (f (f e (f e (f e m))) (f e m)) (f b m))).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e m)) (f b m))) ((f (f (f e (f e m)) (f e m)) (f b m))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f b m))) ((f (f (f e m) (f e m)) (f b m))).\nsurgery id_r ((f (f (f e m) (f e m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_6: forall b: G, (e <+> (((e <+> m) <+> (e <+> (m <+> ((e <+> e) <+> m)))) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f e m) (f e (f m (f (f e e) m)))) (f e b)))) ((f e (f (f e (f e (f m (f (f e e) m)))) (f e b)))).\nsurgery id_l ((f e (f (f e (f e (f m (f (f e e) m)))) (f e b)))) ((f e (f (f e (f m (f (f e e) m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f m (f (f e e) m))) (f e b)))) ((f e (f (f e (f m (f e m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f m (f e m))) (f e b)))) ((f e (f (f e (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f m m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_7: forall b: G, (((e <+> m) <+> ((e <+> m) <+> (e <+> ((e <+> (m <+> m)) <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e m) (f e (f (f e (f m m)) m)))) b)) ((f (f e (f (f e m) (f e (f (f e (f m m)) m)))) b)).\nsurgery id_r ((f (f e (f (f e m) (f e (f (f e (f m m)) m)))) b)) ((f (f e (f e (f e (f (f e (f m m)) m)))) b)).\nsurgery id_l ((f (f e (f e (f e (f (f e (f m m)) m)))) b)) ((f (f e (f e (f (f e (f m m)) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e (f m m)) m))) b)) ((f (f e (f (f e (f m m)) m)) b)).\nsurgery id_r ((f (f e (f (f e (f m m)) m)) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_8: forall b: G, (((((e <+> e) <+> m) <+> m) <+> (e <+> m)) <+> ((e <+> e) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) m) m) (f e m)) (f (f e e) (f b m)))) ((f (f (f (f e e) m) (f e m)) (f (f e e) (f b m)))).\nsurgery id_r ((f (f (f (f e e) m) (f e m)) (f (f e e) (f b m)))) ((f (f (f e e) (f e m)) (f (f e e) (f b m)))).\nsurgery id_l ((f (f (f e e) (f e m)) (f (f e e) (f b m)))) ((f (f e (f e m)) (f (f e e) (f b m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e e) (f b m)))) ((f (f e m) (f (f e e) (f b m)))).\nsurgery id_r ((f (f e m) (f (f e e) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_9: forall b: G, (((((e <+> e) <+> m) <+> m) <+> ((e <+> (e <+> b)) <+> (m <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) m) m) (f (f e (f e b)) (f m m))) m)) ((f (f (f (f e e) m) m) (f (f e (f e b)) (f m m)))).\nsurgery id_r ((f (f (f (f e e) m) m) (f (f e (f e b)) (f m m)))) ((f (f (f e e) m) (f (f e (f e b)) (f m m)))).\nsurgery id_r ((f (f (f e e) m) (f (f e (f e b)) (f m m)))) ((f (f e e) (f (f e (f e b)) (f m m)))).\nsurgery id_l ((f (f e e) (f (f e (f e b)) (f m m)))) ((f e (f (f e (f e b)) (f m m)))).\nsurgery id_l ((f e (f (f e (f e b)) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_10: forall b: G, ((e <+> ((e <+> m) <+> m)) <+> (e <+> ((b <+> m) <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f (f b m) (f (f e m) m))))) ((f (f e (f e m)) (f e (f (f b m) (f (f e m) m))))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f b m) (f (f e m) m))))) ((f (f e m) (f e (f (f b m) (f (f e m) m))))).\nsurgery id_r ((f (f e m) (f e (f (f b m) (f (f e m) m))))) ((f e (f e (f (f b m) (f (f e m) m))))).\nsurgery id_l ((f e (f e (f (f b m) (f (f e m) m))))) ((f e (f (f b m) (f (f e m) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_11: forall b: G, ((((e <+> (e <+> (m <+> (e <+> m)))) <+> b) <+> m) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f e (f m (f e m)))) b) m) (f (f e m) m))) ((f (f (f e (f e (f m (f e m)))) b) (f (f e m) m))).\nsurgery id_l ((f (f (f e (f e (f m (f e m)))) b) (f (f e m) m))) ((f (f (f e (f m (f e m))) b) (f (f e m) m))).\nsurgery id_l ((f (f (f e (f m (f e m))) b) (f (f e m) m))) ((f (f (f e (f m m)) b) (f (f e m) m))).\nsurgery id_r ((f (f (f e (f m m)) b) (f (f e m) m))) ((f (f (f e m) b) (f (f e m) m))).\nsurgery id_r ((f (f (f e m) b) (f (f e m) m))) ((f (f e b) (f (f e m) m))).\nsurgery id_l ((f (f e b) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_12: forall b: G, ((((e <+> m) <+> b) <+> m) <+> (((((e <+> e) <+> e) <+> m) <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) b) m) (f (f (f (f (f e e) e) m) e) m))) ((f (f (f e m) b) (f (f (f (f (f e e) e) m) e) m))).\nsurgery id_r ((f (f (f e m) b) (f (f (f (f (f e e) e) m) e) m))) ((f (f e b) (f (f (f (f (f e e) e) m) e) m))).\nsurgery id_l ((f (f e b) (f (f (f (f (f e e) e) m) e) m))) ((f b (f (f (f (f (f e e) e) m) e) m))).\nsurgery id_r ((f b (f (f (f (f (f e e) e) m) e) m))) ((f b (f (f (f (f e e) e) e) m))).\nsurgery id_l ((f b (f (f (f (f e e) e) e) m))) ((f b (f (f (f e e) e) m))).\nsurgery id_l ((f b (f (f (f e e) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_13: forall b: G, (((e <+> (e <+> m)) <+> (e <+> m)) <+> ((b <+> m) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f (f b m) (f (f e m) m)))) ((f (f (f e m) (f e m)) (f (f b m) (f (f e m) m)))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f b m) (f (f e m) m)))) ((f (f e (f e m)) (f (f b m) (f (f e m) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) (f (f e m) m)))) ((f (f e m) (f (f b m) (f (f e m) m)))).\nsurgery id_r ((f (f e m) (f (f b m) (f (f e m) m)))) ((f e (f (f b m) (f (f e m) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_14: forall b: G, ((((e <+> m) <+> (e <+> e)) <+> (((e <+> m) <+> m) <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e e)) (f (f (f e m) m) (f e m))) b)) ((f (f (f e (f e e)) (f (f (f e m) m) (f e m))) b)).\nsurgery id_l ((f (f (f e (f e e)) (f (f (f e m) m) (f e m))) b)) ((f (f (f e e) (f (f (f e m) m) (f e m))) b)).\nsurgery id_l ((f (f (f e e) (f (f (f e m) m) (f e m))) b)) ((f (f e (f (f (f e m) m) (f e m))) b)).\nsurgery id_r ((f (f e (f (f (f e m) m) (f e m))) b)) ((f (f e (f (f e m) (f e m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_15: forall b: G, ((((e <+> e) <+> m) <+> (e <+> (b <+> m))) <+> ((e <+> e) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f e (f b m))) (f (f e e) (f m m)))) ((f (f (f e e) (f e (f b m))) (f (f e e) (f m m)))).\nsurgery id_l ((f (f (f e e) (f e (f b m))) (f (f e e) (f m m)))) ((f (f e (f e (f b m))) (f (f e e) (f m m)))).\nsurgery id_l ((f (f e (f e (f b m))) (f (f e e) (f m m)))) ((f (f e (f b m)) (f (f e e) (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e e) (f m m)))) ((f (f e b) (f (f e e) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e e) (f m m)))) ((f b (f (f e e) (f m m)))).\nsurgery id_l ((f b (f (f e e) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_16: forall b: G, (b <+> ((m <+> (m <+> m)) <+> ((e <+> e) <+> (((e <+> m) <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f m (f m m)) (f (f e e) (f (f (f e m) m) m))))) ((f b (f (f m m) (f (f e e) (f (f (f e m) m) m))))).\nsurgery id_r ((f b (f (f m m) (f (f e e) (f (f (f e m) m) m))))) ((f b (f m (f (f e e) (f (f (f e m) m) m))))).\nsurgery id_l ((f b (f m (f (f e e) (f (f (f e m) m) m))))) ((f b (f m (f e (f (f (f e m) m) m))))).\nsurgery id_l ((f b (f m (f e (f (f (f e m) m) m))))) ((f b (f m (f (f (f e m) m) m)))).\nsurgery id_r ((f b (f m (f (f (f e m) m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_17: forall b: G, ((e <+> m) <+> ((((e <+> m) <+> e) <+> e) <+> (b <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f (f e m) e) e) (f b (f (f e m) m))))) ((f e (f (f (f (f e m) e) e) (f b (f (f e m) m))))).\nsurgery id_r ((f e (f (f (f (f e m) e) e) (f b (f (f e m) m))))) ((f e (f (f (f e e) e) (f b (f (f e m) m))))).\nsurgery id_l ((f e (f (f (f e e) e) (f b (f (f e m) m))))) ((f e (f (f e e) (f b (f (f e m) m))))).\nsurgery id_l ((f e (f (f e e) (f b (f (f e m) m))))) ((f e (f e (f b (f (f e m) m))))).\nsurgery id_l ((f e (f e (f b (f (f e m) m))))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_18: forall b: G, ((((e <+> e) <+> (e <+> m)) <+> (((e <+> e) <+> (b <+> m)) <+> m)) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f e m)) (f (f (f e e) (f b m)) m)) m)) ((f (f (f e e) (f e m)) (f (f (f e e) (f b m)) m))).\nsurgery id_l ((f (f (f e e) (f e m)) (f (f (f e e) (f b m)) m))) ((f (f e (f e m)) (f (f (f e e) (f b m)) m))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e e) (f b m)) m))) ((f (f e m) (f (f (f e e) (f b m)) m))).\nsurgery id_r ((f (f e m) (f (f (f e e) (f b m)) m))) ((f e (f (f (f e e) (f b m)) m))).\nsurgery id_l ((f e (f (f (f e e) (f b m)) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_19: forall b: G, ((((e <+> e) <+> (e <+> (e <+> m))) <+> m) <+> (b <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f e (f e m))) m) (f b (f e (f e m))))) ((f (f (f e e) (f e (f e m))) (f b (f e (f e m))))).\nsurgery id_l ((f (f (f e e) (f e (f e m))) (f b (f e (f e m))))) ((f (f e (f e (f e m))) (f b (f e (f e m))))).\nsurgery id_l ((f (f e (f e (f e m))) (f b (f e (f e m))))) ((f (f e (f e m)) (f b (f e (f e m))))).\nsurgery id_l ((f (f e (f e m)) (f b (f e (f e m))))) ((f (f e m) (f b (f e (f e m))))).\nsurgery id_r ((f (f e m) (f b (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_20: forall b: G, (((b <+> m) <+> m) <+> ((((e <+> m) <+> m) <+> m) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) m) (f (f (f (f e m) m) m) (f (f e e) m)))) ((f (f b m) (f (f (f (f e m) m) m) (f (f e e) m)))).\nsurgery id_r ((f (f b m) (f (f (f (f e m) m) m) (f (f e e) m)))) ((f b (f (f (f (f e m) m) m) (f (f e e) m)))).\nsurgery id_r ((f b (f (f (f (f e m) m) m) (f (f e e) m)))) ((f b (f (f (f e m) m) (f (f e e) m)))).\nsurgery id_r ((f b (f (f (f e m) m) (f (f e e) m)))) ((f b (f (f e m) (f (f e e) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e e) m)))) ((f b (f e (f (f e e) m)))).\nsurgery id_l ((f b (f e (f (f e e) m)))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_21: forall b: G, (((e <+> e) <+> ((e <+> e) <+> (e <+> (e <+> b)))) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e e) (f e (f e b)))) (f (f e m) m))) ((f (f e (f (f e e) (f e (f e b)))) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f e e) (f e (f e b)))) (f (f e m) m))) ((f (f e (f e (f e (f e b)))) (f (f e m) m))).\nsurgery id_l ((f (f e (f e (f e (f e b)))) (f (f e m) m))) ((f (f e (f e (f e b))) (f (f e m) m))).\nsurgery id_l ((f (f e (f e (f e b))) (f (f e m) m))) ((f (f e (f e b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f e m) m))) ((f (f e b) (f (f e m) m))).\nsurgery id_l ((f (f e b) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_22: forall b: G, ((((e <+> ((e <+> m) <+> b)) <+> m) <+> m) <+> ((e <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f (f e m) b)) m) m) (f (f e m) (f e m)))) ((f (f (f e (f (f e m) b)) m) (f (f e m) (f e m)))).\nsurgery id_r ((f (f (f e (f (f e m) b)) m) (f (f e m) (f e m)))) ((f (f e (f (f e m) b)) (f (f e m) (f e m)))).\nsurgery id_r ((f (f e (f (f e m) b)) (f (f e m) (f e m)))) ((f (f e (f e b)) (f (f e m) (f e m)))).\nsurgery id_l ((f (f e (f e b)) (f (f e m) (f e m)))) ((f (f e b) (f (f e m) (f e m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_23: forall b: G, (e <+> (((e <+> (e <+> m)) <+> e) <+> ((b <+> (m <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f e (f (f (f e (f e m)) e) (f (f b (f m m)) (f m m))))) ((f e (f (f (f e m) e) (f (f b (f m m)) (f m m))))).\nsurgery id_r ((f e (f (f (f e m) e) (f (f b (f m m)) (f m m))))) ((f e (f (f e e) (f (f b (f m m)) (f m m))))).\nsurgery id_l ((f e (f (f e e) (f (f b (f m m)) (f m m))))) ((f e (f e (f (f b (f m m)) (f m m))))).\nsurgery id_l ((f e (f e (f (f b (f m m)) (f m m))))) ((f e (f (f b (f m m)) (f m m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f m m)))) ((f e (f (f b m) (f m m)))).\nsurgery id_r ((f e (f (f b m) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_24: forall b: G, (((e <+> (e <+> (e <+> m))) <+> (b <+> ((e <+> m) <+> m))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e m))) (f b (f (f e m) m))) (f e m))) ((f (f (f e (f e m)) (f b (f (f e m) m))) (f e m))).\nsurgery id_l ((f (f (f e (f e m)) (f b (f (f e m) m))) (f e m))) ((f (f (f e m) (f b (f (f e m) m))) (f e m))).\nsurgery id_r ((f (f (f e m) (f b (f (f e m) m))) (f e m))) ((f (f e (f b (f (f e m) m))) (f e m))).\nsurgery id_r ((f (f e (f b (f (f e m) m))) (f e m))) ((f (f e (f b (f e m))) (f e m))).\nsurgery id_l ((f (f e (f b (f e m))) (f e m))) ((f (f e (f b m)) (f e m))).\nsurgery id_r ((f (f e (f b m)) (f e m))) ((f (f e b) (f e m))).\nsurgery id_l ((f (f e b) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_25: forall b: G, (((e <+> ((e <+> (e <+> m)) <+> (m <+> m))) <+> (m <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f (f e (f e m)) (f m m))) (f m (f e m))) b)) ((f (f (f e (f (f e m) (f m m))) (f m (f e m))) b)).\nsurgery id_r ((f (f (f e (f (f e m) (f m m))) (f m (f e m))) b)) ((f (f (f e (f e (f m m))) (f m (f e m))) b)).\nsurgery id_l ((f (f (f e (f e (f m m))) (f m (f e m))) b)) ((f (f (f e (f m m)) (f m (f e m))) b)).\nsurgery id_r ((f (f (f e (f m m)) (f m (f e m))) b)) ((f (f (f e m) (f m (f e m))) b)).\nsurgery id_r ((f (f (f e m) (f m (f e m))) b)) ((f (f e (f m (f e m))) b)).\nsurgery id_l ((f (f e (f m (f e m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_26: forall b: G, (e <+> ((b <+> ((e <+> m) <+> m)) <+> ((e <+> (e <+> (e <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f b (f (f e m) m)) (f (f e (f e (f e m))) m)))) ((f e (f (f b (f e m)) (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f e (f (f b (f e m)) (f (f e (f e (f e m))) m)))) ((f e (f (f b m) (f (f e (f e (f e m))) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e (f e (f e m))) m)))) ((f e (f b (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f e (f b (f (f e (f e (f e m))) m)))) ((f e (f b (f (f e (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f e (f e m)) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_27: forall b: G, (((e <+> m) <+> ((e <+> m) <+> ((e <+> m) <+> ((e <+> m) <+> b)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e m) (f (f e m) (f (f e m) b)))) m)) ((f (f e m) (f (f e m) (f (f e m) (f (f e m) b))))).\nsurgery id_r ((f (f e m) (f (f e m) (f (f e m) (f (f e m) b))))) ((f e (f (f e m) (f (f e m) (f (f e m) b))))).\nsurgery id_r ((f e (f (f e m) (f (f e m) (f (f e m) b))))) ((f e (f e (f (f e m) (f (f e m) b))))).\nsurgery id_l ((f e (f e (f (f e m) (f (f e m) b))))) ((f e (f (f e m) (f (f e m) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e m) b)))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_28: forall b: G, (((e <+> e) <+> e) <+> (b <+> (((e <+> m) <+> m) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) e) (f b (f (f (f e m) m) (f e (f m m)))))) ((f (f e e) (f b (f (f (f e m) m) (f e (f m m)))))).\nsurgery id_l ((f (f e e) (f b (f (f (f e m) m) (f e (f m m)))))) ((f e (f b (f (f (f e m) m) (f e (f m m)))))).\nsurgery id_r ((f e (f b (f (f (f e m) m) (f e (f m m)))))) ((f e (f b (f (f e m) (f e (f m m)))))).\nsurgery id_r ((f e (f b (f (f e m) (f e (f m m)))))) ((f e (f b (f e (f e (f m m)))))).\nsurgery id_l ((f e (f b (f e (f e (f m m)))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_29: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> (e <+> (e <+> e))) <+> ((e <+> e) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) (f e (f e e))) (f (f e e) b))) ((f (f (f e (f e m)) (f e (f e e))) (f (f e e) b))).\nsurgery id_l ((f (f (f e (f e m)) (f e (f e e))) (f (f e e) b))) ((f (f (f e m) (f e (f e e))) (f (f e e) b))).\nsurgery id_r ((f (f (f e m) (f e (f e e))) (f (f e e) b))) ((f (f e (f e (f e e))) (f (f e e) b))).\nsurgery id_l ((f (f e (f e (f e e))) (f (f e e) b))) ((f (f e (f e e)) (f (f e e) b))).\nsurgery id_l ((f (f e (f e e)) (f (f e e) b))) ((f (f e e) (f (f e e) b))).\nsurgery id_l ((f (f e e) (f (f e e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_30: forall b: G, (((((e <+> e) <+> e) <+> ((e <+> m) <+> m)) <+> ((e <+> m) <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f (f e e) e) (f (f e m) m)) (f (f e m) m)) b)) ((f (f (f (f e e) (f (f e m) m)) (f (f e m) m)) b)).\nsurgery id_l ((f (f (f (f e e) (f (f e m) m)) (f (f e m) m)) b)) ((f (f (f e (f (f e m) m)) (f (f e m) m)) b)).\nsurgery id_r ((f (f (f e (f (f e m) m)) (f (f e m) m)) b)) ((f (f (f e (f e m)) (f (f e m) m)) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) m)) b)) ((f (f (f e m) (f (f e m) m)) b)).\nsurgery id_r ((f (f (f e m) (f (f e m) m)) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_31: forall b: G, (e <+> ((e <+> ((e <+> (m <+> m)) <+> m)) <+> ((e <+> (e <+> m)) <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e (f (f e (f m m)) m)) (f (f e (f e m)) b)))) ((f e (f (f e (f (f e m) m)) (f (f e (f e m)) b)))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) (f (f e (f e m)) b)))) ((f e (f (f e (f e m)) (f (f e (f e m)) b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f (f e (f e m)) b)))) ((f e (f (f e m) (f (f e (f e m)) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e (f e m)) b)))) ((f e (f e (f (f e (f e m)) b)))).\nsurgery id_l ((f e (f e (f (f e (f e m)) b)))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_32: forall b: G, ((((e <+> b) <+> m) <+> ((m <+> (e <+> m)) <+> m)) <+> ((m <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e b) m) (f (f m (f e m)) m)) (f (f m m) m))) ((f (f (f e b) (f (f m (f e m)) m)) (f (f m m) m))).\nsurgery id_l ((f (f (f e b) (f (f m (f e m)) m)) (f (f m m) m))) ((f (f b (f (f m (f e m)) m)) (f (f m m) m))).\nsurgery id_l ((f (f b (f (f m (f e m)) m)) (f (f m m) m))) ((f (f b (f (f m m) m)) (f (f m m) m))).\nsurgery id_r ((f (f b (f (f m m) m)) (f (f m m) m))) ((f (f b (f m m)) (f (f m m) m))).\nsurgery id_r ((f (f b (f m m)) (f (f m m) m))) ((f (f b m) (f (f m m) m))).\nsurgery id_r ((f (f b m) (f (f m m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_33: forall b: G, (((e <+> ((((e <+> m) <+> (e <+> m)) <+> m) <+> m)) <+> b) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f (f (f e m) (f e m)) m) m)) b) (f m m))) ((f (f (f e (f (f (f e m) (f e m)) m)) b) (f m m))).\nsurgery id_r ((f (f (f e (f (f (f e m) (f e m)) m)) b) (f m m))) ((f (f (f e (f (f e (f e m)) m)) b) (f m m))).\nsurgery id_l ((f (f (f e (f (f e (f e m)) m)) b) (f m m))) ((f (f (f e (f (f e m) m)) b) (f m m))).\nsurgery id_r ((f (f (f e (f (f e m) m)) b) (f m m))) ((f (f (f e (f e m)) b) (f m m))).\nsurgery id_l ((f (f (f e (f e m)) b) (f m m))) ((f (f (f e m) b) (f m m))).\nsurgery id_r ((f (f (f e m) b) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_34: forall b: G, (((e <+> e) <+> (b <+> ((e <+> m) <+> ((e <+> m) <+> m)))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f b (f (f e m) (f (f e m) m)))) (f e m))) ((f (f e (f b (f (f e m) (f (f e m) m)))) (f e m))).\nsurgery id_r ((f (f e (f b (f (f e m) (f (f e m) m)))) (f e m))) ((f (f e (f b (f e (f (f e m) m)))) (f e m))).\nsurgery id_l ((f (f e (f b (f e (f (f e m) m)))) (f e m))) ((f (f e (f b (f (f e m) m))) (f e m))).\nsurgery id_r ((f (f e (f b (f (f e m) m))) (f e m))) ((f (f e (f b (f e m))) (f e m))).\nsurgery id_l ((f (f e (f b (f e m))) (f e m))) ((f (f e (f b m)) (f e m))).\nsurgery id_r ((f (f e (f b m)) (f e m))) ((f (f e b) (f e m))).\nsurgery id_l ((f (f e b) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_35: forall b: G, ((e <+> m) <+> (((e <+> (((e <+> m) <+> m) <+> m)) <+> (b <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e (f (f (f e m) m) m)) (f b m)) m))) ((f e (f (f (f e (f (f (f e m) m) m)) (f b m)) m))).\nsurgery id_r ((f e (f (f (f e (f (f (f e m) m) m)) (f b m)) m))) ((f e (f (f (f e (f (f e m) m)) (f b m)) m))).\nsurgery id_r ((f e (f (f (f e (f (f e m) m)) (f b m)) m))) ((f e (f (f (f e (f e m)) (f b m)) m))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f b m)) m))) ((f e (f (f (f e m) (f b m)) m))).\nsurgery id_r ((f e (f (f (f e m) (f b m)) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_36: forall b: G, (((e <+> m) <+> (e <+> (e <+> m))) <+> ((e <+> (e <+> m)) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e (f e m))) (f (f e (f e m)) (f e b)))) ((f (f e (f e (f e m))) (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f (f e (f e (f e m))) (f (f e (f e m)) (f e b)))) ((f (f e (f e m)) (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f (f e (f e m)) (f e b)))) ((f (f e m) (f (f e (f e m)) (f e b)))).\nsurgery id_r ((f (f e m) (f (f e (f e m)) (f e b)))) ((f e (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_37: forall b: G, ((e <+> (e <+> (e <+> (e <+> ((b <+> m) <+> m))))) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f e (f e (f (f b m) m))))) (f (f e m) m))) ((f (f e (f e (f e (f (f b m) m)))) (f (f e m) m))).\nsurgery id_l ((f (f e (f e (f e (f (f b m) m)))) (f (f e m) m))) ((f (f e (f e (f (f b m) m))) (f (f e m) m))).\nsurgery id_l ((f (f e (f e (f (f b m) m))) (f (f e m) m))) ((f (f e (f (f b m) m)) (f (f e m) m))).\nsurgery id_r ((f (f e (f (f b m) m)) (f (f e m) m))) ((f (f e (f b m)) (f (f e m) m))).\nsurgery id_r ((f (f e (f b m)) (f (f e m) m))) ((f (f e b) (f (f e m) m))).\nsurgery id_l ((f (f e b) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_38: forall b: G, (((((b <+> m) <+> m) <+> m) <+> (m <+> m)) <+> (m <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f b m) m) m) (f m m)) (f m (f (f e m) m)))) ((f (f (f (f b m) m) (f m m)) (f m (f (f e m) m)))).\nsurgery id_r ((f (f (f (f b m) m) (f m m)) (f m (f (f e m) m)))) ((f (f (f b m) (f m m)) (f m (f (f e m) m)))).\nsurgery id_r ((f (f (f b m) (f m m)) (f m (f (f e m) m)))) ((f (f b (f m m)) (f m (f (f e m) m)))).\nsurgery id_r ((f (f b (f m m)) (f m (f (f e m) m)))) ((f (f b m) (f m (f (f e m) m)))).\nsurgery id_r ((f (f b m) (f m (f (f e m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_39: forall b: G, ((((e <+> (e <+> e)) <+> e) <+> ((e <+> (m <+> m)) <+> b)) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e e)) e) (f (f e (f m m)) b)) (f e m))) ((f (f (f (f e e) e) (f (f e (f m m)) b)) (f e m))).\nsurgery id_l ((f (f (f (f e e) e) (f (f e (f m m)) b)) (f e m))) ((f (f (f e e) (f (f e (f m m)) b)) (f e m))).\nsurgery id_l ((f (f (f e e) (f (f e (f m m)) b)) (f e m))) ((f (f e (f (f e (f m m)) b)) (f e m))).\nsurgery id_r ((f (f e (f (f e (f m m)) b)) (f e m))) ((f (f e (f (f e m) b)) (f e m))).\nsurgery id_r ((f (f e (f (f e m) b)) (f e m))) ((f (f e (f e b)) (f e m))).\nsurgery id_l ((f (f e (f e b)) (f e m))) ((f (f e b) (f e m))).\nsurgery id_l ((f (f e b) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_40: forall b: G, (((e <+> m) <+> e) <+> ((((e <+> b) <+> m) <+> m) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) e) (f (f (f (f e b) m) m) (f m (f m m))))) ((f (f e e) (f (f (f (f e b) m) m) (f m (f m m))))).\nsurgery id_l ((f (f e e) (f (f (f (f e b) m) m) (f m (f m m))))) ((f e (f (f (f (f e b) m) m) (f m (f m m))))).\nsurgery id_r ((f e (f (f (f (f e b) m) m) (f m (f m m))))) ((f e (f (f (f e b) m) (f m (f m m))))).\nsurgery id_r ((f e (f (f (f e b) m) (f m (f m m))))) ((f e (f (f e b) (f m (f m m))))).\nsurgery id_l ((f e (f (f e b) (f m (f m m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_41: forall b: G, ((e <+> (e <+> e)) <+> ((e <+> (e <+> e)) <+> ((e <+> e) <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f e (f e e)) (f (f e e) (f e b))))) ((f (f e e) (f (f e (f e e)) (f (f e e) (f e b))))).\nsurgery id_l ((f (f e e) (f (f e (f e e)) (f (f e e) (f e b))))) ((f e (f (f e (f e e)) (f (f e e) (f e b))))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f e e) (f e b))))) ((f e (f (f e e) (f (f e e) (f e b))))).\nsurgery id_l ((f e (f (f e e) (f (f e e) (f e b))))) ((f e (f e (f (f e e) (f e b))))).\nsurgery id_l ((f e (f e (f (f e e) (f e b))))) ((f e (f (f e e) (f e b)))).\nsurgery id_l ((f e (f (f e e) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_42: forall b: G, ((b <+> ((e <+> m) <+> (m <+> m))) <+> ((e <+> e) <+> ((m <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e m) (f m m))) (f (f e e) (f (f m m) m)))) ((f (f b (f e (f m m))) (f (f e e) (f (f m m) m)))).\nsurgery id_l ((f (f b (f e (f m m))) (f (f e e) (f (f m m) m)))) ((f (f b (f m m)) (f (f e e) (f (f m m) m)))).\nsurgery id_r ((f (f b (f m m)) (f (f e e) (f (f m m) m)))) ((f (f b m) (f (f e e) (f (f m m) m)))).\nsurgery id_r ((f (f b m) (f (f e e) (f (f m m) m)))) ((f b (f (f e e) (f (f m m) m)))).\nsurgery id_l ((f b (f (f e e) (f (f m m) m)))) ((f b (f e (f (f m m) m)))).\nsurgery id_l ((f b (f e (f (f m m) m)))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_43: forall b: G, ((e <+> ((e <+> m) <+> (m <+> ((e <+> m) <+> m)))) <+> (e <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) (f m (f (f e m) m)))) (f e (f b m)))) ((f (f e (f e (f m (f (f e m) m)))) (f e (f b m)))).\nsurgery id_l ((f (f e (f e (f m (f (f e m) m)))) (f e (f b m)))) ((f (f e (f m (f (f e m) m))) (f e (f b m)))).\nsurgery id_r ((f (f e (f m (f (f e m) m))) (f e (f b m)))) ((f (f e (f m (f e m))) (f e (f b m)))).\nsurgery id_l ((f (f e (f m (f e m))) (f e (f b m)))) ((f (f e (f m m)) (f e (f b m)))).\nsurgery id_r ((f (f e (f m m)) (f e (f b m)))) ((f (f e m) (f e (f b m)))).\nsurgery id_r ((f (f e m) (f e (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_44: forall b: G, ((((e <+> (e <+> b)) <+> ((((e <+> e) <+> m) <+> m) <+> m)) <+> m) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f e b)) (f (f (f (f e e) m) m) m)) m) m)) ((f (f (f e (f e b)) (f (f (f (f e e) m) m) m)) m)).\nsurgery id_r ((f (f (f e (f e b)) (f (f (f (f e e) m) m) m)) m)) ((f (f e (f e b)) (f (f (f (f e e) m) m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f (f (f e e) m) m) m))) ((f (f e b) (f (f (f (f e e) m) m) m))).\nsurgery id_l ((f (f e b) (f (f (f (f e e) m) m) m))) ((f b (f (f (f (f e e) m) m) m))).\nsurgery id_r ((f b (f (f (f (f e e) m) m) m))) ((f b (f (f (f e e) m) m))).\nsurgery id_r ((f b (f (f (f e e) m) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_45: forall b: G, ((((e <+> b) <+> (e <+> m)) <+> m) <+> (e <+> (m <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e b) (f e m)) m) (f e (f m (f e (f m m)))))) ((f (f (f e b) (f e m)) (f e (f m (f e (f m m)))))).\nsurgery id_l ((f (f (f e b) (f e m)) (f e (f m (f e (f m m)))))) ((f (f b (f e m)) (f e (f m (f e (f m m)))))).\nsurgery id_l ((f (f b (f e m)) (f e (f m (f e (f m m)))))) ((f (f b m) (f e (f m (f e (f m m)))))).\nsurgery id_r ((f (f b m) (f e (f m (f e (f m m)))))) ((f b (f e (f m (f e (f m m)))))).\nsurgery id_l ((f b (f e (f m (f e (f m m)))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_46: forall b: G, (((e <+> ((e <+> m) <+> m)) <+> (e <+> (m <+> (e <+> m)))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) m)) (f e (f m (f e m)))) (f e b))) ((f (f (f e (f e m)) (f e (f m (f e m)))) (f e b))).\nsurgery id_l ((f (f (f e (f e m)) (f e (f m (f e m)))) (f e b))) ((f (f (f e m) (f e (f m (f e m)))) (f e b))).\nsurgery id_r ((f (f (f e m) (f e (f m (f e m)))) (f e b))) ((f (f e (f e (f m (f e m)))) (f e b))).\nsurgery id_l ((f (f e (f e (f m (f e m)))) (f e b))) ((f (f e (f m (f e m))) (f e b))).\nsurgery id_l ((f (f e (f m (f e m))) (f e b))) ((f (f e (f m m)) (f e b))).\nsurgery id_r ((f (f e (f m m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_47: forall b: G, (((e <+> (e <+> m)) <+> e) <+> ((b <+> (m <+> (m <+> m))) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) e) (f (f b (f m (f m m))) (f e m)))) ((f (f (f e m) e) (f (f b (f m (f m m))) (f e m)))).\nsurgery id_r ((f (f (f e m) e) (f (f b (f m (f m m))) (f e m)))) ((f (f e e) (f (f b (f m (f m m))) (f e m)))).\nsurgery id_l ((f (f e e) (f (f b (f m (f m m))) (f e m)))) ((f e (f (f b (f m (f m m))) (f e m)))).\nsurgery id_r ((f e (f (f b (f m (f m m))) (f e m)))) ((f e (f (f b (f m m)) (f e m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_48: forall b: G, ((((e <+> m) <+> e) <+> (m <+> m)) <+> (b <+> (((e <+> e) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f m m)) (f b (f (f (f e e) m) m)))) ((f (f (f e e) (f m m)) (f b (f (f (f e e) m) m)))).\nsurgery id_l ((f (f (f e e) (f m m)) (f b (f (f (f e e) m) m)))) ((f (f e (f m m)) (f b (f (f (f e e) m) m)))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f (f e e) m) m)))) ((f (f e m) (f b (f (f (f e e) m) m)))).\nsurgery id_r ((f (f e m) (f b (f (f (f e e) m) m)))) ((f e (f b (f (f (f e e) m) m)))).\nsurgery id_r ((f e (f b (f (f (f e e) m) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_49: forall b: G, ((((e <+> m) <+> b) <+> (((e <+> e) <+> (e <+> e)) <+> m)) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) b) (f (f (f e e) (f e e)) m)) (f e m))) ((f (f (f e b) (f (f (f e e) (f e e)) m)) (f e m))).\nsurgery id_l ((f (f (f e b) (f (f (f e e) (f e e)) m)) (f e m))) ((f (f b (f (f (f e e) (f e e)) m)) (f e m))).\nsurgery id_l ((f (f b (f (f (f e e) (f e e)) m)) (f e m))) ((f (f b (f (f e (f e e)) m)) (f e m))).\nsurgery id_l ((f (f b (f (f e (f e e)) m)) (f e m))) ((f (f b (f (f e e) m)) (f e m))).\nsurgery id_l ((f (f b (f (f e e) m)) (f e m))) ((f (f b (f e m)) (f e m))).\nsurgery id_l ((f (f b (f e m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_50: forall b: G, ((b <+> (e <+> m)) <+> ((((e <+> m) <+> (e <+> (e <+> m))) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e m)) (f (f (f (f e m) (f e (f e m))) m) m))) ((f (f b m) (f (f (f (f e m) (f e (f e m))) m) m))).\nsurgery id_r ((f (f b m) (f (f (f (f e m) (f e (f e m))) m) m))) ((f b (f (f (f (f e m) (f e (f e m))) m) m))).\nsurgery id_r ((f b (f (f (f (f e m) (f e (f e m))) m) m))) ((f b (f (f (f e m) (f e (f e m))) m))).\nsurgery id_r ((f b (f (f (f e m) (f e (f e m))) m))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_51: forall b: G, (e <+> (((e <+> m) <+> m) <+> (b <+> ((e <+> m) <+> (e <+> (e <+> m)))))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f e m) m) (f b (f (f e m) (f e (f e m))))))) ((f e (f (f e m) (f b (f (f e m) (f e (f e m))))))).\nsurgery id_r ((f e (f (f e m) (f b (f (f e m) (f e (f e m))))))) ((f e (f e (f b (f (f e m) (f e (f e m))))))).\nsurgery id_l ((f e (f e (f b (f (f e m) (f e (f e m))))))) ((f e (f b (f (f e m) (f e (f e m)))))).\nsurgery id_r ((f e (f b (f (f e m) (f e (f e m)))))) ((f e (f b (f e (f e (f e m)))))).\nsurgery id_l ((f e (f b (f e (f e (f e m)))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_52: forall b: G, ((e <+> (e <+> ((e <+> e) <+> e))) <+> ((e <+> m) <+> (b <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f (f e e) e))) (f (f e m) (f b (f m m))))) ((f (f e (f (f e e) e)) (f (f e m) (f b (f m m))))).\nsurgery id_l ((f (f e (f (f e e) e)) (f (f e m) (f b (f m m))))) ((f (f e (f e e)) (f (f e m) (f b (f m m))))).\nsurgery id_l ((f (f e (f e e)) (f (f e m) (f b (f m m))))) ((f (f e e) (f (f e m) (f b (f m m))))).\nsurgery id_l ((f (f e e) (f (f e m) (f b (f m m))))) ((f e (f (f e m) (f b (f m m))))).\nsurgery id_r ((f e (f (f e m) (f b (f m m))))) ((f e (f e (f b (f m m))))).\nsurgery id_l ((f e (f e (f b (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_53: forall b: G, (((((e <+> e) <+> m) <+> (m <+> m)) <+> b) <+> (m <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) m) (f m m)) b) (f m (f (f e m) m)))) ((f (f (f (f e e) (f m m)) b) (f m (f (f e m) m)))).\nsurgery id_l ((f (f (f (f e e) (f m m)) b) (f m (f (f e m) m)))) ((f (f (f e (f m m)) b) (f m (f (f e m) m)))).\nsurgery id_r ((f (f (f e (f m m)) b) (f m (f (f e m) m)))) ((f (f (f e m) b) (f m (f (f e m) m)))).\nsurgery id_r ((f (f (f e m) b) (f m (f (f e m) m)))) ((f (f e b) (f m (f (f e m) m)))).\nsurgery id_l ((f (f e b) (f m (f (f e m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_54: forall b: G, ((e <+> (((e <+> e) <+> e) <+> m)) <+> (e <+> ((e <+> (e <+> e)) <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f (f e e) e) m)) (f e (f (f e (f e e)) b)))) ((f (f e (f (f e e) m)) (f e (f (f e (f e e)) b)))).\nsurgery id_l ((f (f e (f (f e e) m)) (f e (f (f e (f e e)) b)))) ((f (f e (f e m)) (f e (f (f e (f e e)) b)))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f e (f e e)) b)))) ((f (f e m) (f e (f (f e (f e e)) b)))).\nsurgery id_r ((f (f e m) (f e (f (f e (f e e)) b)))) ((f e (f e (f (f e (f e e)) b)))).\nsurgery id_l ((f e (f e (f (f e (f e e)) b)))) ((f e (f (f e (f e e)) b))).\nsurgery id_l ((f e (f (f e (f e e)) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_55: forall b: G, ((e <+> b) <+> (((m <+> m) <+> (e <+> ((e <+> m) <+> m))) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f (f m m) (f e (f (f e m) m))) (f e m)))) ((f b (f (f (f m m) (f e (f (f e m) m))) (f e m)))).\nsurgery id_r ((f b (f (f (f m m) (f e (f (f e m) m))) (f e m)))) ((f b (f (f m (f e (f (f e m) m))) (f e m)))).\nsurgery id_l ((f b (f (f m (f e (f (f e m) m))) (f e m)))) ((f b (f (f m (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f m (f (f e m) m)) (f e m)))) ((f b (f (f m (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f m (f e m)) (f e m)))) ((f b (f (f m m) (f e m)))).\nsurgery id_r ((f b (f (f m m) (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_56: forall b: G, ((e <+> m) <+> ((e <+> b) <+> ((e <+> (m <+> m)) <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e b) (f (f e (f m m)) (f (f e m) m))))) ((f e (f (f e b) (f (f e (f m m)) (f (f e m) m))))).\nsurgery id_l ((f e (f (f e b) (f (f e (f m m)) (f (f e m) m))))) ((f e (f b (f (f e (f m m)) (f (f e m) m))))).\nsurgery id_r ((f e (f b (f (f e (f m m)) (f (f e m) m))))) ((f e (f b (f (f e m) (f (f e m) m))))).\nsurgery id_r ((f e (f b (f (f e m) (f (f e m) m))))) ((f e (f b (f e (f (f e m) m))))).\nsurgery id_l ((f e (f b (f e (f (f e m) m))))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_57: forall b: G, ((b <+> m) <+> (((e <+> (e <+> m)) <+> ((e <+> e) <+> (e <+> m))) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f (f e (f e m)) (f (f e e) (f e m))) m))) ((f b (f (f (f e (f e m)) (f (f e e) (f e m))) m))).\nsurgery id_l ((f b (f (f (f e (f e m)) (f (f e e) (f e m))) m))) ((f b (f (f (f e m) (f (f e e) (f e m))) m))).\nsurgery id_r ((f b (f (f (f e m) (f (f e e) (f e m))) m))) ((f b (f (f e (f (f e e) (f e m))) m))).\nsurgery id_l ((f b (f (f e (f (f e e) (f e m))) m))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_58: forall b: G, (e <+> (((((e <+> m) <+> e) <+> m) <+> (b <+> m)) <+> ((m <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f (f (f e m) e) m) (f b m)) (f (f m m) m)))) ((f e (f (f (f (f e m) e) (f b m)) (f (f m m) m)))).\nsurgery id_r ((f e (f (f (f (f e m) e) (f b m)) (f (f m m) m)))) ((f e (f (f (f e e) (f b m)) (f (f m m) m)))).\nsurgery id_l ((f e (f (f (f e e) (f b m)) (f (f m m) m)))) ((f e (f (f e (f b m)) (f (f m m) m)))).\nsurgery id_r ((f e (f (f e (f b m)) (f (f m m) m)))) ((f e (f (f e b) (f (f m m) m)))).\nsurgery id_l ((f e (f (f e b) (f (f m m) m)))) ((f e (f b (f (f m m) m)))).\nsurgery id_r ((f e (f b (f (f m m) m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_59: forall b: G, ((e <+> ((e <+> m) <+> (((e <+> e) <+> e) <+> ((e <+> m) <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) (f (f (f e e) e) (f (f e m) m)))) b)) ((f (f e (f e (f (f (f e e) e) (f (f e m) m)))) b)).\nsurgery id_l ((f (f e (f e (f (f (f e e) e) (f (f e m) m)))) b)) ((f (f e (f (f (f e e) e) (f (f e m) m))) b)).\nsurgery id_l ((f (f e (f (f (f e e) e) (f (f e m) m))) b)) ((f (f e (f (f e e) (f (f e m) m))) b)).\nsurgery id_l ((f (f e (f (f e e) (f (f e m) m))) b)) ((f (f e (f e (f (f e m) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e m) m))) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_60: forall b: G, (((e <+> e) <+> (((e <+> m) <+> (b <+> m)) <+> ((e <+> m) <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e e) (f (f (f e m) (f b m)) (f (f e m) m))) m)) ((f (f e e) (f (f (f e m) (f b m)) (f (f e m) m)))).\nsurgery id_l ((f (f e e) (f (f (f e m) (f b m)) (f (f e m) m)))) ((f e (f (f (f e m) (f b m)) (f (f e m) m)))).\nsurgery id_r ((f e (f (f (f e m) (f b m)) (f (f e m) m)))) ((f e (f (f e (f b m)) (f (f e m) m)))).\nsurgery id_r ((f e (f (f e (f b m)) (f (f e m) m)))) ((f e (f (f e b) (f (f e m) m)))).\nsurgery id_l ((f e (f (f e b) (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_61: forall b: G, ((((e <+> e) <+> e) <+> m) <+> ((e <+> m) <+> (b <+> ((e <+> e) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) e) m) (f (f e m) (f b (f (f e e) m))))) ((f (f (f e e) e) (f (f e m) (f b (f (f e e) m))))).\nsurgery id_l ((f (f (f e e) e) (f (f e m) (f b (f (f e e) m))))) ((f (f e e) (f (f e m) (f b (f (f e e) m))))).\nsurgery id_l ((f (f e e) (f (f e m) (f b (f (f e e) m))))) ((f e (f (f e m) (f b (f (f e e) m))))).\nsurgery id_r ((f e (f (f e m) (f b (f (f e e) m))))) ((f e (f e (f b (f (f e e) m))))).\nsurgery id_l ((f e (f e (f b (f (f e e) m))))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_62: forall b: G, ((e <+> b) <+> ((((e <+> (m <+> (m <+> m))) <+> m) <+> (m <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f (f (f e (f m (f m m))) m) (f m m)) m))) ((f b (f (f (f (f e (f m (f m m))) m) (f m m)) m))).\nsurgery id_r ((f b (f (f (f (f e (f m (f m m))) m) (f m m)) m))) ((f b (f (f (f e (f m (f m m))) (f m m)) m))).\nsurgery id_r ((f b (f (f (f e (f m (f m m))) (f m m)) m))) ((f b (f (f (f e (f m m)) (f m m)) m))).\nsurgery id_r ((f b (f (f (f e (f m m)) (f m m)) m))) ((f b (f (f (f e m) (f m m)) m))).\nsurgery id_r ((f b (f (f (f e m) (f m m)) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_63: forall b: G, ((e <+> b) <+> (m <+> ((m <+> m) <+> (((m <+> (e <+> m)) <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f m (f (f m m) (f (f (f m (f e m)) m) m))))) ((f b (f m (f (f m m) (f (f (f m (f e m)) m) m))))).\nsurgery id_r ((f b (f m (f (f m m) (f (f (f m (f e m)) m) m))))) ((f b (f m (f m (f (f (f m (f e m)) m) m))))).\nsurgery id_r ((f b (f m (f m (f (f (f m (f e m)) m) m))))) ((f b (f m (f m (f (f m (f e m)) m))))).\nsurgery id_l ((f b (f m (f m (f (f m (f e m)) m))))) ((f b (f m (f m (f (f m m) m))))).\nsurgery id_r ((f b (f m (f m (f (f m m) m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_64: forall b: G, (b <+> (((e <+> (e <+> m)) <+> ((e <+> m) <+> (e <+> (e <+> m)))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f (f e (f e m)) (f (f e m) (f e (f e m)))) m))) ((f b (f (f (f e m) (f (f e m) (f e (f e m)))) m))).\nsurgery id_r ((f b (f (f (f e m) (f (f e m) (f e (f e m)))) m))) ((f b (f (f e (f (f e m) (f e (f e m)))) m))).\nsurgery id_r ((f b (f (f e (f (f e m) (f e (f e m)))) m))) ((f b (f (f e (f e (f e (f e m)))) m))).\nsurgery id_l ((f b (f (f e (f e (f e (f e m)))) m))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_65: forall b: G, ((e <+> (m <+> m)) <+> ((((e <+> m) <+> e) <+> (e <+> m)) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f m m)) (f (f (f (f e m) e) (f e m)) (f b m)))) ((f (f e m) (f (f (f (f e m) e) (f e m)) (f b m)))).\nsurgery id_r ((f (f e m) (f (f (f (f e m) e) (f e m)) (f b m)))) ((f e (f (f (f (f e m) e) (f e m)) (f b m)))).\nsurgery id_r ((f e (f (f (f (f e m) e) (f e m)) (f b m)))) ((f e (f (f (f e e) (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f (f e e) (f e m)) (f b m)))) ((f e (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_66: forall b: G, ((e <+> b) <+> ((m <+> m) <+> (((e <+> e) <+> e) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f m m) (f (f (f e e) e) (f e (f m m)))))) ((f b (f (f m m) (f (f (f e e) e) (f e (f m m)))))).\nsurgery id_r ((f b (f (f m m) (f (f (f e e) e) (f e (f m m)))))) ((f b (f m (f (f (f e e) e) (f e (f m m)))))).\nsurgery id_l ((f b (f m (f (f (f e e) e) (f e (f m m)))))) ((f b (f m (f (f e e) (f e (f m m)))))).\nsurgery id_l ((f b (f m (f (f e e) (f e (f m m)))))) ((f b (f m (f e (f e (f m m)))))).\nsurgery id_l ((f b (f m (f e (f e (f m m)))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_67: forall b: G, (((e <+> m) <+> (e <+> ((e <+> e) <+> e))) <+> ((e <+> (b <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e (f (f e e) e))) (f (f e (f b m)) m))) ((f (f e (f e (f (f e e) e))) (f (f e (f b m)) m))).\nsurgery id_l ((f (f e (f e (f (f e e) e))) (f (f e (f b m)) m))) ((f (f e (f (f e e) e)) (f (f e (f b m)) m))).\nsurgery id_l ((f (f e (f (f e e) e)) (f (f e (f b m)) m))) ((f (f e (f e e)) (f (f e (f b m)) m))).\nsurgery id_l ((f (f e (f e e)) (f (f e (f b m)) m))) ((f (f e e) (f (f e (f b m)) m))).\nsurgery id_l ((f (f e e) (f (f e (f b m)) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_68: forall b: G, (((e <+> (e <+> b)) <+> ((e <+> ((e <+> e) <+> e)) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e b)) (f (f e (f (f e e) e)) m)) (f m m))) ((f (f (f e b) (f (f e (f (f e e) e)) m)) (f m m))).\nsurgery id_l ((f (f (f e b) (f (f e (f (f e e) e)) m)) (f m m))) ((f (f b (f (f e (f (f e e) e)) m)) (f m m))).\nsurgery id_l ((f (f b (f (f e (f (f e e) e)) m)) (f m m))) ((f (f b (f (f e (f e e)) m)) (f m m))).\nsurgery id_l ((f (f b (f (f e (f e e)) m)) (f m m))) ((f (f b (f (f e e) m)) (f m m))).\nsurgery id_l ((f (f b (f (f e e) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_69: forall b: G, ((e <+> (e <+> m)) <+> (((e <+> (m <+> m)) <+> ((m <+> m) <+> m)) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f (f e (f m m)) (f (f m m) m)) b))) ((f (f e m) (f (f (f e (f m m)) (f (f m m) m)) b))).\nsurgery id_r ((f (f e m) (f (f (f e (f m m)) (f (f m m) m)) b))) ((f e (f (f (f e (f m m)) (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f (f e (f m m)) (f (f m m) m)) b))) ((f e (f (f (f e m) (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f (f e m) (f (f m m) m)) b))) ((f e (f (f e (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f m m) m)) b))) ((f e (f (f e (f m m)) b))).\nsurgery id_r ((f e (f (f e (f m m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_70: forall b: G, ((b <+> ((e <+> (((e <+> m) <+> m) <+> m)) <+> m)) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e (f (f (f e m) m) m)) m)) (f (f e m) m))) ((f (f b (f (f e (f (f e m) m)) m)) (f (f e m) m))).\nsurgery id_r ((f (f b (f (f e (f (f e m) m)) m)) (f (f e m) m))) ((f (f b (f (f e (f e m)) m)) (f (f e m) m))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f (f e m) m))) ((f (f b (f (f e m) m)) (f (f e m) m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f (f e m) m))) ((f (f b (f e m)) (f (f e m) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e m) m))) ((f (f b m) (f (f e m) m))).\nsurgery id_r ((f (f b m) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_71: forall b: G, (((e <+> e) <+> ((e <+> m) <+> e)) <+> ((e <+> (e <+> (m <+> m))) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e m) e)) (f (f e (f e (f m m))) b))) ((f (f e (f (f e m) e)) (f (f e (f e (f m m))) b))).\nsurgery id_r ((f (f e (f (f e m) e)) (f (f e (f e (f m m))) b))) ((f (f e (f e e)) (f (f e (f e (f m m))) b))).\nsurgery id_l ((f (f e (f e e)) (f (f e (f e (f m m))) b))) ((f (f e e) (f (f e (f e (f m m))) b))).\nsurgery id_l ((f (f e e) (f (f e (f e (f m m))) b))) ((f e (f (f e (f e (f m m))) b))).\nsurgery id_l ((f e (f (f e (f e (f m m))) b))) ((f e (f (f e (f m m)) b))).\nsurgery id_r ((f e (f (f e (f m m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_72: forall b: G, (((e <+> e) <+> b) <+> (e <+> ((e <+> e) <+> ((e <+> (e <+> m)) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) b) (f e (f (f e e) (f (f e (f e m)) m))))) ((f (f e b) (f e (f (f e e) (f (f e (f e m)) m))))).\nsurgery id_l ((f (f e b) (f e (f (f e e) (f (f e (f e m)) m))))) ((f b (f e (f (f e e) (f (f e (f e m)) m))))).\nsurgery id_l ((f b (f e (f (f e e) (f (f e (f e m)) m))))) ((f b (f (f e e) (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f (f e e) (f (f e (f e m)) m)))) ((f b (f e (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f e (f (f e (f e m)) m)))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_73: forall b: G, ((((e <+> e) <+> (b <+> m)) <+> ((e <+> e) <+> m)) <+> ((e <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f b m)) (f (f e e) m)) (f (f e e) m))) ((f (f (f e (f b m)) (f (f e e) m)) (f (f e e) m))).\nsurgery id_r ((f (f (f e (f b m)) (f (f e e) m)) (f (f e e) m))) ((f (f (f e b) (f (f e e) m)) (f (f e e) m))).\nsurgery id_l ((f (f (f e b) (f (f e e) m)) (f (f e e) m))) ((f (f b (f (f e e) m)) (f (f e e) m))).\nsurgery id_l ((f (f b (f (f e e) m)) (f (f e e) m))) ((f (f b (f e m)) (f (f e e) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e e) m))) ((f (f b m) (f (f e e) m))).\nsurgery id_r ((f (f b m) (f (f e e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_74: forall b: G, ((b <+> (m <+> m)) <+> ((((e <+> e) <+> m) <+> (e <+> m)) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m m)) (f (f (f (f e e) m) (f e m)) (f e m)))) ((f (f b m) (f (f (f (f e e) m) (f e m)) (f e m)))).\nsurgery id_r ((f (f b m) (f (f (f (f e e) m) (f e m)) (f e m)))) ((f b (f (f (f (f e e) m) (f e m)) (f e m)))).\nsurgery id_r ((f b (f (f (f (f e e) m) (f e m)) (f e m)))) ((f b (f (f (f e e) (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f (f e e) (f e m)) (f e m)))) ((f b (f (f e (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_75: forall b: G, (((b <+> (e <+> (m <+> m))) <+> ((m <+> m) <+> m)) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f b (f e (f m m))) (f (f m m) m)) (f m (f m m)))) ((f (f (f b (f m m)) (f (f m m) m)) (f m (f m m)))).\nsurgery id_r ((f (f (f b (f m m)) (f (f m m) m)) (f m (f m m)))) ((f (f (f b m) (f (f m m) m)) (f m (f m m)))).\nsurgery id_r ((f (f (f b m) (f (f m m) m)) (f m (f m m)))) ((f (f b (f (f m m) m)) (f m (f m m)))).\nsurgery id_r ((f (f b (f (f m m) m)) (f m (f m m)))) ((f (f b (f m m)) (f m (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f m (f m m)))) ((f (f b m) (f m (f m m)))).\nsurgery id_r ((f (f b m) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_76: forall b: G, (b <+> ((e <+> m) <+> ((((e <+> e) <+> ((e <+> m) <+> m)) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f e m) (f (f (f (f e e) (f (f e m) m)) m) m)))) ((f b (f e (f (f (f (f e e) (f (f e m) m)) m) m)))).\nsurgery id_l ((f b (f e (f (f (f (f e e) (f (f e m) m)) m) m)))) ((f b (f (f (f (f e e) (f (f e m) m)) m) m))).\nsurgery id_r ((f b (f (f (f (f e e) (f (f e m) m)) m) m))) ((f b (f (f (f e e) (f (f e m) m)) m))).\nsurgery id_l ((f b (f (f (f e e) (f (f e m) m)) m))) ((f b (f (f e (f (f e m) m)) m))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_77: forall b: G, (((b <+> (m <+> (e <+> m))) <+> ((e <+> m) <+> (m <+> m))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f b (f m (f e m))) (f (f e m) (f m m))) (f e m))) ((f (f (f b (f m m)) (f (f e m) (f m m))) (f e m))).\nsurgery id_r ((f (f (f b (f m m)) (f (f e m) (f m m))) (f e m))) ((f (f (f b m) (f (f e m) (f m m))) (f e m))).\nsurgery id_r ((f (f (f b m) (f (f e m) (f m m))) (f e m))) ((f (f b (f (f e m) (f m m))) (f e m))).\nsurgery id_r ((f (f b (f (f e m) (f m m))) (f e m))) ((f (f b (f e (f m m))) (f e m))).\nsurgery id_l ((f (f b (f e (f m m))) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_78: forall b: G, ((e <+> ((e <+> (e <+> m)) <+> m)) <+> (e <+> (b <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e (f e m)) m)) (f e (f b (f (f e m) m))))) ((f (f e (f (f e m) m)) (f e (f b (f (f e m) m))))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f b (f (f e m) m))))) ((f (f e (f e m)) (f e (f b (f (f e m) m))))).\nsurgery id_l ((f (f e (f e m)) (f e (f b (f (f e m) m))))) ((f (f e m) (f e (f b (f (f e m) m))))).\nsurgery id_r ((f (f e m) (f e (f b (f (f e m) m))))) ((f e (f e (f b (f (f e m) m))))).\nsurgery id_l ((f e (f e (f b (f (f e m) m))))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_79: forall b: G, ((((e <+> ((e <+> m) <+> (e <+> m))) <+> e) <+> (e <+> e)) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f (f e m) (f e m))) e) (f e e)) (f e b))) ((f (f (f (f e (f e (f e m))) e) (f e e)) (f e b))).\nsurgery id_l ((f (f (f (f e (f e (f e m))) e) (f e e)) (f e b))) ((f (f (f (f e (f e m)) e) (f e e)) (f e b))).\nsurgery id_l ((f (f (f (f e (f e m)) e) (f e e)) (f e b))) ((f (f (f (f e m) e) (f e e)) (f e b))).\nsurgery id_r ((f (f (f (f e m) e) (f e e)) (f e b))) ((f (f (f e e) (f e e)) (f e b))).\nsurgery id_l ((f (f (f e e) (f e e)) (f e b))) ((f (f e (f e e)) (f e b))).\nsurgery id_l ((f (f e (f e e)) (f e b))) ((f (f e e) (f e b))).\nsurgery id_l ((f (f e e) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_80: forall b: G, ((((b <+> (e <+> m)) <+> (m <+> m)) <+> m) <+> ((e <+> e) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f b (f e m)) (f m m)) m) (f (f e e) (f e m)))) ((f (f (f b (f e m)) (f m m)) (f (f e e) (f e m)))).\nsurgery id_l ((f (f (f b (f e m)) (f m m)) (f (f e e) (f e m)))) ((f (f (f b m) (f m m)) (f (f e e) (f e m)))).\nsurgery id_r ((f (f (f b m) (f m m)) (f (f e e) (f e m)))) ((f (f b (f m m)) (f (f e e) (f e m)))).\nsurgery id_r ((f (f b (f m m)) (f (f e e) (f e m)))) ((f (f b m) (f (f e e) (f e m)))).\nsurgery id_r ((f (f b m) (f (f e e) (f e m)))) ((f b (f (f e e) (f e m)))).\nsurgery id_l ((f b (f (f e e) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_81: forall b: G, (((e <+> b) <+> (e <+> ((((e <+> m) <+> e) <+> (e <+> m)) <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) (f e (f (f (f (f e m) e) (f e m)) m))) m)) ((f (f e b) (f e (f (f (f (f e m) e) (f e m)) m)))).\nsurgery id_l ((f (f e b) (f e (f (f (f (f e m) e) (f e m)) m)))) ((f b (f e (f (f (f (f e m) e) (f e m)) m)))).\nsurgery id_l ((f b (f e (f (f (f (f e m) e) (f e m)) m)))) ((f b (f (f (f (f e m) e) (f e m)) m))).\nsurgery id_r ((f b (f (f (f (f e m) e) (f e m)) m))) ((f b (f (f (f e e) (f e m)) m))).\nsurgery id_l ((f b (f (f (f e e) (f e m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_82: forall b: G, (((e <+> m) <+> (e <+> m)) <+> (((e <+> e) <+> (e <+> (e <+> b))) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e m)) (f (f (f e e) (f e (f e b))) m))) ((f (f e (f e m)) (f (f (f e e) (f e (f e b))) m))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e e) (f e (f e b))) m))) ((f (f e m) (f (f (f e e) (f e (f e b))) m))).\nsurgery id_r ((f (f e m) (f (f (f e e) (f e (f e b))) m))) ((f e (f (f (f e e) (f e (f e b))) m))).\nsurgery id_l ((f e (f (f (f e e) (f e (f e b))) m))) ((f e (f (f e (f e (f e b))) m))).\nsurgery id_l ((f e (f (f e (f e (f e b))) m))) ((f e (f (f e (f e b)) m))).\nsurgery id_l ((f e (f (f e (f e b)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_83: forall b: G, ((e <+> (b <+> m)) <+> (((e <+> m) <+> (e <+> m)) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f b m)) (f (f (f e m) (f e m)) (f m (f m m))))) ((f (f e b) (f (f (f e m) (f e m)) (f m (f m m))))).\nsurgery id_l ((f (f e b) (f (f (f e m) (f e m)) (f m (f m m))))) ((f b (f (f (f e m) (f e m)) (f m (f m m))))).\nsurgery id_r ((f b (f (f (f e m) (f e m)) (f m (f m m))))) ((f b (f (f e (f e m)) (f m (f m m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f m (f m m))))) ((f b (f (f e m) (f m (f m m))))).\nsurgery id_r ((f b (f (f e m) (f m (f m m))))) ((f b (f e (f m (f m m))))).\nsurgery id_l ((f b (f e (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_84: forall b: G, ((e <+> (e <+> (e <+> ((m <+> m) <+> m)))) <+> ((e <+> (b <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f e (f (f m m) m)))) (f (f e (f b m)) m))) ((f (f e (f e (f (f m m) m))) (f (f e (f b m)) m))).\nsurgery id_l ((f (f e (f e (f (f m m) m))) (f (f e (f b m)) m))) ((f (f e (f (f m m) m)) (f (f e (f b m)) m))).\nsurgery id_r ((f (f e (f (f m m) m)) (f (f e (f b m)) m))) ((f (f e (f m m)) (f (f e (f b m)) m))).\nsurgery id_r ((f (f e (f m m)) (f (f e (f b m)) m))) ((f (f e m) (f (f e (f b m)) m))).\nsurgery id_r ((f (f e m) (f (f e (f b m)) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_85: forall b: G, ((e <+> (((e <+> m) <+> m) <+> m)) <+> (((e <+> e) <+> e) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f (f (f e e) e) (f e b)))) ((f (f e (f (f e m) m)) (f (f (f e e) e) (f e b)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f (f e e) e) (f e b)))) ((f (f e (f e m)) (f (f (f e e) e) (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e e) e) (f e b)))) ((f (f e m) (f (f (f e e) e) (f e b)))).\nsurgery id_r ((f (f e m) (f (f (f e e) e) (f e b)))) ((f e (f (f (f e e) e) (f e b)))).\nsurgery id_l ((f e (f (f (f e e) e) (f e b)))) ((f e (f (f e e) (f e b)))).\nsurgery id_l ((f e (f (f e e) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_86: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> ((e <+> m) <+> ((e <+> m) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) (f (f e m) (f (f e m) m))) b)) ((f (f (f e (f e m)) (f (f e m) (f (f e m) m))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) (f (f e m) m))) b)) ((f (f (f e m) (f (f e m) (f (f e m) m))) b)).\nsurgery id_r ((f (f (f e m) (f (f e m) (f (f e m) m))) b)) ((f (f e (f (f e m) (f (f e m) m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f (f e m) m))) b)) ((f (f e (f e (f (f e m) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e m) m))) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_87: forall b: G, ((b <+> (m <+> m)) <+> (((e <+> m) <+> m) <+> (((m <+> m) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m m)) (f (f (f e m) m) (f (f (f m m) m) m)))) ((f (f b m) (f (f (f e m) m) (f (f (f m m) m) m)))).\nsurgery id_r ((f (f b m) (f (f (f e m) m) (f (f (f m m) m) m)))) ((f b (f (f (f e m) m) (f (f (f m m) m) m)))).\nsurgery id_r ((f b (f (f (f e m) m) (f (f (f m m) m) m)))) ((f b (f (f e m) (f (f (f m m) m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f (f m m) m) m)))) ((f b (f e (f (f (f m m) m) m)))).\nsurgery id_l ((f b (f e (f (f (f m m) m) m)))) ((f b (f (f (f m m) m) m))).\nsurgery id_r ((f b (f (f (f m m) m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_88: forall b: G, (((e <+> m) <+> ((e <+> m) <+> e)) <+> (((e <+> b) <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e m) e)) (f (f (f e b) m) (f m m)))) ((f (f e (f (f e m) e)) (f (f (f e b) m) (f m m)))).\nsurgery id_r ((f (f e (f (f e m) e)) (f (f (f e b) m) (f m m)))) ((f (f e (f e e)) (f (f (f e b) m) (f m m)))).\nsurgery id_l ((f (f e (f e e)) (f (f (f e b) m) (f m m)))) ((f (f e e) (f (f (f e b) m) (f m m)))).\nsurgery id_l ((f (f e e) (f (f (f e b) m) (f m m)))) ((f e (f (f (f e b) m) (f m m)))).\nsurgery id_r ((f e (f (f (f e b) m) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_89: forall b: G, ((((e <+> e) <+> m) <+> (((b <+> m) <+> m) <+> m)) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f (f (f b m) m) m)) (f e (f m m)))) ((f (f (f e e) (f (f (f b m) m) m)) (f e (f m m)))).\nsurgery id_l ((f (f (f e e) (f (f (f b m) m) m)) (f e (f m m)))) ((f (f e (f (f (f b m) m) m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f (f (f b m) m) m)) (f e (f m m)))) ((f (f e (f (f b m) m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f e (f m m)))) ((f (f e (f b m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f e (f m m)))) ((f (f e b) (f e (f m m)))).\nsurgery id_l ((f (f e b) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_90: forall b: G, (b <+> ((e <+> m) <+> ((e <+> m) <+> (((e <+> (e <+> e)) <+> e) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f e m) (f (f e m) (f (f (f e (f e e)) e) m))))) ((f b (f e (f (f e m) (f (f (f e (f e e)) e) m))))).\nsurgery id_l ((f b (f e (f (f e m) (f (f (f e (f e e)) e) m))))) ((f b (f (f e m) (f (f (f e (f e e)) e) m)))).\nsurgery id_r ((f b (f (f e m) (f (f (f e (f e e)) e) m)))) ((f b (f e (f (f (f e (f e e)) e) m)))).\nsurgery id_l ((f b (f e (f (f (f e (f e e)) e) m)))) ((f b (f (f (f e (f e e)) e) m))).\nsurgery id_l ((f b (f (f (f e (f e e)) e) m))) ((f b (f (f (f e e) e) m))).\nsurgery id_l ((f b (f (f (f e e) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_91: forall b: G, (((e <+> m) <+> ((e <+> e) <+> (m <+> m))) <+> (b <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e e) (f m m))) (f b (f (f e e) m)))) ((f (f e (f (f e e) (f m m))) (f b (f (f e e) m)))).\nsurgery id_l ((f (f e (f (f e e) (f m m))) (f b (f (f e e) m)))) ((f (f e (f e (f m m))) (f b (f (f e e) m)))).\nsurgery id_l ((f (f e (f e (f m m))) (f b (f (f e e) m)))) ((f (f e (f m m)) (f b (f (f e e) m)))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f e e) m)))) ((f (f e m) (f b (f (f e e) m)))).\nsurgery id_r ((f (f e m) (f b (f (f e e) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_92: forall b: G, ((b <+> (e <+> (e <+> (m <+> m)))) <+> (((e <+> e) <+> (e <+> e)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e (f e (f m m)))) (f (f (f e e) (f e e)) m))) ((f (f b (f e (f m m))) (f (f (f e e) (f e e)) m))).\nsurgery id_l ((f (f b (f e (f m m))) (f (f (f e e) (f e e)) m))) ((f (f b (f m m)) (f (f (f e e) (f e e)) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e e) (f e e)) m))) ((f (f b m) (f (f (f e e) (f e e)) m))).\nsurgery id_r ((f (f b m) (f (f (f e e) (f e e)) m))) ((f b (f (f (f e e) (f e e)) m))).\nsurgery id_l ((f b (f (f (f e e) (f e e)) m))) ((f b (f (f e (f e e)) m))).\nsurgery id_l ((f b (f (f e (f e e)) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_93: forall b: G, (((e <+> ((e <+> m) <+> m)) <+> (e <+> b)) <+> (((m <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) m)) (f e b)) (f (f (f m m) m) m))) ((f (f (f e (f e m)) (f e b)) (f (f (f m m) m) m))).\nsurgery id_l ((f (f (f e (f e m)) (f e b)) (f (f (f m m) m) m))) ((f (f (f e m) (f e b)) (f (f (f m m) m) m))).\nsurgery id_r ((f (f (f e m) (f e b)) (f (f (f m m) m) m))) ((f (f e (f e b)) (f (f (f m m) m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f (f m m) m) m))) ((f (f e b) (f (f (f m m) m) m))).\nsurgery id_l ((f (f e b) (f (f (f m m) m) m))) ((f b (f (f (f m m) m) m))).\nsurgery id_r ((f b (f (f (f m m) m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_94: forall b: G, ((e <+> b) <+> ((m <+> m) <+> (m <+> (m <+> ((e <+> m) <+> (m <+> m)))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f m m) (f m (f m (f (f e m) (f m m))))))) ((f b (f (f m m) (f m (f m (f (f e m) (f m m))))))).\nsurgery id_r ((f b (f (f m m) (f m (f m (f (f e m) (f m m))))))) ((f b (f m (f m (f m (f (f e m) (f m m))))))).\nsurgery id_r ((f b (f m (f m (f m (f (f e m) (f m m))))))) ((f b (f m (f m (f m (f e (f m m))))))).\nsurgery id_l ((f b (f m (f m (f m (f e (f m m))))))) ((f b (f m (f m (f m (f m m)))))).\nsurgery id_r ((f b (f m (f m (f m (f m m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_95: forall b: G, ((e <+> e) <+> ((b <+> m) <+> ((e <+> (e <+> m)) <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f b m) (f (f e (f e m)) (f (f e m) m))))) ((f e (f (f b m) (f (f e (f e m)) (f (f e m) m))))).\nsurgery id_r ((f e (f (f b m) (f (f e (f e m)) (f (f e m) m))))) ((f e (f b (f (f e (f e m)) (f (f e m) m))))).\nsurgery id_l ((f e (f b (f (f e (f e m)) (f (f e m) m))))) ((f e (f b (f (f e m) (f (f e m) m))))).\nsurgery id_r ((f e (f b (f (f e m) (f (f e m) m))))) ((f e (f b (f e (f (f e m) m))))).\nsurgery id_l ((f e (f b (f e (f (f e m) m))))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_96: forall b: G, ((e <+> e) <+> ((e <+> (b <+> (e <+> m))) <+> (m <+> (m <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f e (f b (f e m))) (f m (f m (f m m)))))) ((f e (f (f e (f b (f e m))) (f m (f m (f m m)))))).\nsurgery id_l ((f e (f (f e (f b (f e m))) (f m (f m (f m m)))))) ((f e (f (f e (f b m)) (f m (f m (f m m)))))).\nsurgery id_r ((f e (f (f e (f b m)) (f m (f m (f m m)))))) ((f e (f (f e b) (f m (f m (f m m)))))).\nsurgery id_l ((f e (f (f e b) (f m (f m (f m m)))))) ((f e (f b (f m (f m (f m m)))))).\nsurgery id_r ((f e (f b (f m (f m (f m m)))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_97: forall b: G, ((((e <+> (e <+> m)) <+> (e <+> (e <+> (e <+> e)))) <+> b) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e m)) (f e (f e (f e e)))) b) (f m m))) ((f (f (f (f e m) (f e (f e (f e e)))) b) (f m m))).\nsurgery id_r ((f (f (f (f e m) (f e (f e (f e e)))) b) (f m m))) ((f (f (f e (f e (f e (f e e)))) b) (f m m))).\nsurgery id_l ((f (f (f e (f e (f e (f e e)))) b) (f m m))) ((f (f (f e (f e (f e e))) b) (f m m))).\nsurgery id_l ((f (f (f e (f e (f e e))) b) (f m m))) ((f (f (f e (f e e)) b) (f m m))).\nsurgery id_l ((f (f (f e (f e e)) b) (f m m))) ((f (f (f e e) b) (f m m))).\nsurgery id_l ((f (f (f e e) b) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_98: forall b: G, ((e <+> m) <+> ((e <+> e) <+> ((b <+> m) <+> (((m <+> m) <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e e) (f (f b m) (f (f (f m m) m) m))))) ((f e (f (f e e) (f (f b m) (f (f (f m m) m) m))))).\nsurgery id_l ((f e (f (f e e) (f (f b m) (f (f (f m m) m) m))))) ((f e (f e (f (f b m) (f (f (f m m) m) m))))).\nsurgery id_l ((f e (f e (f (f b m) (f (f (f m m) m) m))))) ((f e (f (f b m) (f (f (f m m) m) m)))).\nsurgery id_r ((f e (f (f b m) (f (f (f m m) m) m)))) ((f e (f b (f (f (f m m) m) m)))).\nsurgery id_r ((f e (f b (f (f (f m m) m) m)))) ((f e (f b (f (f m m) m)))).\nsurgery id_r ((f e (f b (f (f m m) m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_99: forall b: G, (((e <+> e) <+> ((((e <+> e) <+> m) <+> (e <+> b)) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f (f e e) m) (f e b)) m)) (f m m))) ((f (f e (f (f (f (f e e) m) (f e b)) m)) (f m m))).\nsurgery id_r ((f (f e (f (f (f (f e e) m) (f e b)) m)) (f m m))) ((f (f e (f (f (f e e) (f e b)) m)) (f m m))).\nsurgery id_l ((f (f e (f (f (f e e) (f e b)) m)) (f m m))) ((f (f e (f (f e (f e b)) m)) (f m m))).\nsurgery id_l ((f (f e (f (f e (f e b)) m)) (f m m))) ((f (f e (f (f e b) m)) (f m m))).\nsurgery id_l ((f (f e (f (f e b) m)) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_100: forall b: G, (e <+> (((e <+> m) <+> ((((e <+> m) <+> m) <+> e) <+> m)) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f e m) (f (f (f (f e m) m) e) m)) (f b m)))) ((f e (f (f e (f (f (f (f e m) m) e) m)) (f b m)))).\nsurgery id_r ((f e (f (f e (f (f (f (f e m) m) e) m)) (f b m)))) ((f e (f (f e (f (f (f e m) e) m)) (f b m)))).\nsurgery id_r ((f e (f (f e (f (f (f e m) e) m)) (f b m)))) ((f e (f (f e (f (f e e) m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f (f e e) m)) (f b m)))) ((f e (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_101: forall b: G, (((((e <+> m) <+> e) <+> (m <+> m)) <+> (b <+> (m <+> m))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) e) (f m m)) (f b (f m m))) (f m m))) ((f (f (f (f e e) (f m m)) (f b (f m m))) (f m m))).\nsurgery id_l ((f (f (f (f e e) (f m m)) (f b (f m m))) (f m m))) ((f (f (f e (f m m)) (f b (f m m))) (f m m))).\nsurgery id_r ((f (f (f e (f m m)) (f b (f m m))) (f m m))) ((f (f (f e m) (f b (f m m))) (f m m))).\nsurgery id_r ((f (f (f e m) (f b (f m m))) (f m m))) ((f (f e (f b (f m m))) (f m m))).\nsurgery id_r ((f (f e (f b (f m m))) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_102: forall b: G, ((((((e <+> e) <+> m) <+> (e <+> e)) <+> (e <+> m)) <+> (m <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e e) m) (f e e)) (f e m)) (f m m)) b)) ((f (f (f (f (f e e) (f e e)) (f e m)) (f m m)) b)).\nsurgery id_l ((f (f (f (f (f e e) (f e e)) (f e m)) (f m m)) b)) ((f (f (f (f e (f e e)) (f e m)) (f m m)) b)).\nsurgery id_l ((f (f (f (f e (f e e)) (f e m)) (f m m)) b)) ((f (f (f (f e e) (f e m)) (f m m)) b)).\nsurgery id_l ((f (f (f (f e e) (f e m)) (f m m)) b)) ((f (f (f e (f e m)) (f m m)) b)).\nsurgery id_l ((f (f (f e (f e m)) (f m m)) b)) ((f (f (f e m) (f m m)) b)).\nsurgery id_r ((f (f (f e m) (f m m)) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_103: forall b: G, (((e <+> (e <+> m)) <+> (m <+> (e <+> m))) <+> ((b <+> (e <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f m (f e m))) (f (f b (f e m)) m))) ((f (f (f e m) (f m (f e m))) (f (f b (f e m)) m))).\nsurgery id_r ((f (f (f e m) (f m (f e m))) (f (f b (f e m)) m))) ((f (f e (f m (f e m))) (f (f b (f e m)) m))).\nsurgery id_l ((f (f e (f m (f e m))) (f (f b (f e m)) m))) ((f (f e (f m m)) (f (f b (f e m)) m))).\nsurgery id_r ((f (f e (f m m)) (f (f b (f e m)) m))) ((f (f e m) (f (f b (f e m)) m))).\nsurgery id_r ((f (f e m) (f (f b (f e m)) m))) ((f e (f (f b (f e m)) m))).\nsurgery id_l ((f e (f (f b (f e m)) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_104: forall b: G, ((((e <+> e) <+> (m <+> (e <+> m))) <+> (e <+> m)) <+> ((e <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f m (f e m))) (f e m)) (f (f e b) m))) ((f (f (f e (f m (f e m))) (f e m)) (f (f e b) m))).\nsurgery id_l ((f (f (f e (f m (f e m))) (f e m)) (f (f e b) m))) ((f (f (f e (f m m)) (f e m)) (f (f e b) m))).\nsurgery id_r ((f (f (f e (f m m)) (f e m)) (f (f e b) m))) ((f (f (f e m) (f e m)) (f (f e b) m))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f e b) m))) ((f (f e (f e m)) (f (f e b) m))).\nsurgery id_l ((f (f e (f e m)) (f (f e b) m))) ((f (f e m) (f (f e b) m))).\nsurgery id_r ((f (f e m) (f (f e b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_105: forall b: G, (((e <+> b) <+> (e <+> m)) <+> ((e <+> (e <+> m)) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f e m)) (f (f e (f e m)) (f (f e e) m)))) ((f (f b (f e m)) (f (f e (f e m)) (f (f e e) m)))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f e m)) (f (f e e) m)))) ((f (f b m) (f (f e (f e m)) (f (f e e) m)))).\nsurgery id_r ((f (f b m) (f (f e (f e m)) (f (f e e) m)))) ((f b (f (f e (f e m)) (f (f e e) m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f (f e e) m)))) ((f b (f (f e m) (f (f e e) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e e) m)))) ((f b (f e (f (f e e) m)))).\nsurgery id_l ((f b (f e (f (f e e) m)))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_106: forall b: G, (e <+> ((e <+> (e <+> e)) <+> ((b <+> ((e <+> m) <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f e (f (f e (f e e)) (f (f b (f (f e m) m)) (f m m))))) ((f e (f (f e e) (f (f b (f (f e m) m)) (f m m))))).\nsurgery id_l ((f e (f (f e e) (f (f b (f (f e m) m)) (f m m))))) ((f e (f e (f (f b (f (f e m) m)) (f m m))))).\nsurgery id_l ((f e (f e (f (f b (f (f e m) m)) (f m m))))) ((f e (f (f b (f (f e m) m)) (f m m)))).\nsurgery id_r ((f e (f (f b (f (f e m) m)) (f m m)))) ((f e (f (f b (f e m)) (f m m)))).\nsurgery id_l ((f e (f (f b (f e m)) (f m m)))) ((f e (f (f b m) (f m m)))).\nsurgery id_r ((f e (f (f b m) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_107: forall b: G, ((((e <+> e) <+> (m <+> m)) <+> m) <+> (b <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f m m)) m) (f b (f (f e m) (f e m))))) ((f (f (f e e) (f m m)) (f b (f (f e m) (f e m))))).\nsurgery id_l ((f (f (f e e) (f m m)) (f b (f (f e m) (f e m))))) ((f (f e (f m m)) (f b (f (f e m) (f e m))))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f e m) (f e m))))) ((f (f e m) (f b (f (f e m) (f e m))))).\nsurgery id_r ((f (f e m) (f b (f (f e m) (f e m))))) ((f e (f b (f (f e m) (f e m))))).\nsurgery id_r ((f e (f b (f (f e m) (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_108: forall b: G, ((((e <+> (e <+> (e <+> e))) <+> e) <+> ((e <+> m) <+> m)) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e (f e e))) e) (f (f e m) m)) (f b m))) ((f (f (f (f e (f e e)) e) (f (f e m) m)) (f b m))).\nsurgery id_l ((f (f (f (f e (f e e)) e) (f (f e m) m)) (f b m))) ((f (f (f (f e e) e) (f (f e m) m)) (f b m))).\nsurgery id_l ((f (f (f (f e e) e) (f (f e m) m)) (f b m))) ((f (f (f e e) (f (f e m) m)) (f b m))).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_109: forall b: G, (b <+> ((e <+> e) <+> (((e <+> e) <+> ((e <+> m) <+> (e <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f e e) (f (f (f e e) (f (f e m) (f e m))) m)))) ((f b (f e (f (f (f e e) (f (f e m) (f e m))) m)))).\nsurgery id_l ((f b (f e (f (f (f e e) (f (f e m) (f e m))) m)))) ((f b (f (f (f e e) (f (f e m) (f e m))) m))).\nsurgery id_l ((f b (f (f (f e e) (f (f e m) (f e m))) m))) ((f b (f (f e (f (f e m) (f e m))) m))).\nsurgery id_r ((f b (f (f e (f (f e m) (f e m))) m))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_110: forall b: G, (((e <+> e) <+> (m <+> (e <+> m))) <+> (((e <+> e) <+> e) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f m (f e m))) (f (f (f e e) e) (f b m)))) ((f (f e (f m (f e m))) (f (f (f e e) e) (f b m)))).\nsurgery id_l ((f (f e (f m (f e m))) (f (f (f e e) e) (f b m)))) ((f (f e (f m m)) (f (f (f e e) e) (f b m)))).\nsurgery id_r ((f (f e (f m m)) (f (f (f e e) e) (f b m)))) ((f (f e m) (f (f (f e e) e) (f b m)))).\nsurgery id_r ((f (f e m) (f (f (f e e) e) (f b m)))) ((f e (f (f (f e e) e) (f b m)))).\nsurgery id_l ((f e (f (f (f e e) e) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_111: forall b: G, ((e <+> (m <+> m)) <+> ((e <+> (e <+> (e <+> (e <+> e)))) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f m m)) (f (f e (f e (f e (f e e)))) (f b m)))) ((f (f e m) (f (f e (f e (f e (f e e)))) (f b m)))).\nsurgery id_r ((f (f e m) (f (f e (f e (f e (f e e)))) (f b m)))) ((f e (f (f e (f e (f e (f e e)))) (f b m)))).\nsurgery id_l ((f e (f (f e (f e (f e (f e e)))) (f b m)))) ((f e (f (f e (f e (f e e))) (f b m)))).\nsurgery id_l ((f e (f (f e (f e (f e e))) (f b m)))) ((f e (f (f e (f e e)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e e)) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_112: forall b: G, ((e <+> (e <+> m)) <+> ((((e <+> e) <+> e) <+> m) <+> (e <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f (f (f e e) e) m) (f e (f e b))))) ((f (f e m) (f (f (f (f e e) e) m) (f e (f e b))))).\nsurgery id_r ((f (f e m) (f (f (f (f e e) e) m) (f e (f e b))))) ((f e (f (f (f (f e e) e) m) (f e (f e b))))).\nsurgery id_r ((f e (f (f (f (f e e) e) m) (f e (f e b))))) ((f e (f (f (f e e) e) (f e (f e b))))).\nsurgery id_l ((f e (f (f (f e e) e) (f e (f e b))))) ((f e (f (f e e) (f e (f e b))))).\nsurgery id_l ((f e (f (f e e) (f e (f e b))))) ((f e (f e (f e (f e b))))).\nsurgery id_l ((f e (f e (f e (f e b))))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_113: forall b: G, (((b <+> m) <+> m) <+> ((((e <+> m) <+> (m <+> m)) <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) m) (f (f (f (f e m) (f m m)) m) (f m m)))) ((f (f b m) (f (f (f (f e m) (f m m)) m) (f m m)))).\nsurgery id_r ((f (f b m) (f (f (f (f e m) (f m m)) m) (f m m)))) ((f b (f (f (f (f e m) (f m m)) m) (f m m)))).\nsurgery id_r ((f b (f (f (f (f e m) (f m m)) m) (f m m)))) ((f b (f (f (f e m) (f m m)) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) (f m m)) (f m m)))) ((f b (f (f e (f m m)) (f m m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_114: forall b: G, (((e <+> (m <+> m)) <+> m) <+> ((e <+> (m <+> m)) <+> ((b <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f m m)) m) (f (f e (f m m)) (f (f b m) m)))) ((f (f e (f m m)) (f (f e (f m m)) (f (f b m) m)))).\nsurgery id_r ((f (f e (f m m)) (f (f e (f m m)) (f (f b m) m)))) ((f (f e m) (f (f e (f m m)) (f (f b m) m)))).\nsurgery id_r ((f (f e m) (f (f e (f m m)) (f (f b m) m)))) ((f e (f (f e (f m m)) (f (f b m) m)))).\nsurgery id_r ((f e (f (f e (f m m)) (f (f b m) m)))) ((f e (f (f e m) (f (f b m) m)))).\nsurgery id_r ((f e (f (f e m) (f (f b m) m)))) ((f e (f e (f (f b m) m)))).\nsurgery id_l ((f e (f e (f (f b m) m)))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_115: forall b: G, ((e <+> (((e <+> m) <+> e) <+> m)) <+> (e <+> (e <+> ((e <+> m) <+> b)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f e m) e) m)) (f e (f e (f (f e m) b))))) ((f (f e (f (f e e) m)) (f e (f e (f (f e m) b))))).\nsurgery id_l ((f (f e (f (f e e) m)) (f e (f e (f (f e m) b))))) ((f (f e (f e m)) (f e (f e (f (f e m) b))))).\nsurgery id_l ((f (f e (f e m)) (f e (f e (f (f e m) b))))) ((f (f e m) (f e (f e (f (f e m) b))))).\nsurgery id_r ((f (f e m) (f e (f e (f (f e m) b))))) ((f e (f e (f e (f (f e m) b))))).\nsurgery id_l ((f e (f e (f e (f (f e m) b))))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_116: forall b: G, (((((e <+> (m <+> m)) <+> (m <+> ((e <+> e) <+> m))) <+> m) <+> e) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e (f m m)) (f m (f (f e e) m))) m) e) b)) ((f (f (f (f e (f m m)) (f m (f (f e e) m))) e) b)).\nsurgery id_r ((f (f (f (f e (f m m)) (f m (f (f e e) m))) e) b)) ((f (f (f (f e m) (f m (f (f e e) m))) e) b)).\nsurgery id_r ((f (f (f (f e m) (f m (f (f e e) m))) e) b)) ((f (f (f e (f m (f (f e e) m))) e) b)).\nsurgery id_l ((f (f (f e (f m (f (f e e) m))) e) b)) ((f (f (f e (f m (f e m))) e) b)).\nsurgery id_l ((f (f (f e (f m (f e m))) e) b)) ((f (f (f e (f m m)) e) b)).\nsurgery id_r ((f (f (f e (f m m)) e) b)) ((f (f (f e m) e) b)).\nsurgery id_r ((f (f (f e m) e) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_117: forall b: G, ((e <+> ((e <+> m) <+> m)) <+> ((e <+> b) <+> ((e <+> (e <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) m)) (f (f e b) (f (f e (f e m)) m)))) ((f (f e (f e m)) (f (f e b) (f (f e (f e m)) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e b) (f (f e (f e m)) m)))) ((f (f e m) (f (f e b) (f (f e (f e m)) m)))).\nsurgery id_r ((f (f e m) (f (f e b) (f (f e (f e m)) m)))) ((f e (f (f e b) (f (f e (f e m)) m)))).\nsurgery id_l ((f e (f (f e b) (f (f e (f e m)) m)))) ((f e (f b (f (f e (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f e (f e m)) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_118: forall b: G, ((((e <+> e) <+> b) <+> (m <+> m)) <+> ((e <+> m) <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) b) (f m m)) (f (f e m) (f e (f m m))))) ((f (f (f e b) (f m m)) (f (f e m) (f e (f m m))))).\nsurgery id_l ((f (f (f e b) (f m m)) (f (f e m) (f e (f m m))))) ((f (f b (f m m)) (f (f e m) (f e (f m m))))).\nsurgery id_r ((f (f b (f m m)) (f (f e m) (f e (f m m))))) ((f (f b m) (f (f e m) (f e (f m m))))).\nsurgery id_r ((f (f b m) (f (f e m) (f e (f m m))))) ((f b (f (f e m) (f e (f m m))))).\nsurgery id_r ((f b (f (f e m) (f e (f m m))))) ((f b (f e (f e (f m m))))).\nsurgery id_l ((f b (f e (f e (f m m))))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_119: forall b: G, (((((e <+> e) <+> m) <+> m) <+> (e <+> (b <+> (e <+> m)))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) m) m) (f e (f b (f e m)))) (f m m))) ((f (f (f (f e e) m) (f e (f b (f e m)))) (f m m))).\nsurgery id_r ((f (f (f (f e e) m) (f e (f b (f e m)))) (f m m))) ((f (f (f e e) (f e (f b (f e m)))) (f m m))).\nsurgery id_l ((f (f (f e e) (f e (f b (f e m)))) (f m m))) ((f (f e (f e (f b (f e m)))) (f m m))).\nsurgery id_l ((f (f e (f e (f b (f e m)))) (f m m))) ((f (f e (f b (f e m))) (f m m))).\nsurgery id_l ((f (f e (f b (f e m))) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_120: forall b: G, (e <+> (((e <+> m) <+> (e <+> (m <+> ((e <+> e) <+> m)))) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f e m) (f e (f m (f (f e e) m)))) (f e b)))) ((f e (f (f e (f e (f m (f (f e e) m)))) (f e b)))).\nsurgery id_l ((f e (f (f e (f e (f m (f (f e e) m)))) (f e b)))) ((f e (f (f e (f m (f (f e e) m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f m (f (f e e) m))) (f e b)))) ((f e (f (f e (f m (f e m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f m (f e m))) (f e b)))) ((f e (f (f e (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f m m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_121: forall b: G, (((e <+> m) <+> e) <+> ((e <+> (e <+> (e <+> ((e <+> m) <+> m)))) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) e) (f (f e (f e (f e (f (f e m) m)))) b))) ((f (f e e) (f (f e (f e (f e (f (f e m) m)))) b))).\nsurgery id_l ((f (f e e) (f (f e (f e (f e (f (f e m) m)))) b))) ((f e (f (f e (f e (f e (f (f e m) m)))) b))).\nsurgery id_l ((f e (f (f e (f e (f e (f (f e m) m)))) b))) ((f e (f (f e (f e (f (f e m) m))) b))).\nsurgery id_l ((f e (f (f e (f e (f (f e m) m))) b))) ((f e (f (f e (f (f e m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) b))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_122: forall b: G, (((e <+> e) <+> (m <+> (m <+> m))) <+> ((e <+> m) <+> (b <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f m (f m m))) (f (f e m) (f b (f e m))))) ((f (f e (f m (f m m))) (f (f e m) (f b (f e m))))).\nsurgery id_r ((f (f e (f m (f m m))) (f (f e m) (f b (f e m))))) ((f (f e (f m m)) (f (f e m) (f b (f e m))))).\nsurgery id_r ((f (f e (f m m)) (f (f e m) (f b (f e m))))) ((f (f e m) (f (f e m) (f b (f e m))))).\nsurgery id_r ((f (f e m) (f (f e m) (f b (f e m))))) ((f e (f (f e m) (f b (f e m))))).\nsurgery id_r ((f e (f (f e m) (f b (f e m))))) ((f e (f e (f b (f e m))))).\nsurgery id_l ((f e (f e (f b (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_123: forall b: G, (((e <+> ((m <+> m) <+> (e <+> m))) <+> ((e <+> m) <+> m)) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f m m) (f e m))) (f (f e m) m)) (f b m))) ((f (f (f e (f m (f e m))) (f (f e m) m)) (f b m))).\nsurgery id_l ((f (f (f e (f m (f e m))) (f (f e m) m)) (f b m))) ((f (f (f e (f m m)) (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f (f e (f m m)) (f (f e m) m)) (f b m))) ((f (f (f e m) (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f (f e m) (f (f e m) m)) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_124: forall b: G, ((e <+> ((((e <+> m) <+> m) <+> m) <+> m)) <+> (b <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f (f e m) m) m) m)) (f b (f e (f e m))))) ((f (f e (f (f (f e m) m) m)) (f b (f e (f e m))))).\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f b (f e (f e m))))) ((f (f e (f (f e m) m)) (f b (f e (f e m))))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b (f e (f e m))))) ((f (f e (f e m)) (f b (f e (f e m))))).\nsurgery id_l ((f (f e (f e m)) (f b (f e (f e m))))) ((f (f e m) (f b (f e (f e m))))).\nsurgery id_r ((f (f e m) (f b (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_125: forall b: G, (((e <+> (m <+> m)) <+> m) <+> (e <+> ((((e <+> b) <+> m) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f m m)) m) (f e (f (f (f (f e b) m) m) m)))) ((f (f e (f m m)) (f e (f (f (f (f e b) m) m) m)))).\nsurgery id_r ((f (f e (f m m)) (f e (f (f (f (f e b) m) m) m)))) ((f (f e m) (f e (f (f (f (f e b) m) m) m)))).\nsurgery id_r ((f (f e m) (f e (f (f (f (f e b) m) m) m)))) ((f e (f e (f (f (f (f e b) m) m) m)))).\nsurgery id_l ((f e (f e (f (f (f (f e b) m) m) m)))) ((f e (f (f (f (f e b) m) m) m))).\nsurgery id_r ((f e (f (f (f (f e b) m) m) m))) ((f e (f (f (f e b) m) m))).\nsurgery id_r ((f e (f (f (f e b) m) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_126: forall b: G, ((e <+> ((e <+> m) <+> b)) <+> ((m <+> m) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) b)) (f (f m m) (f (f e m) (f e m))))) ((f (f e (f e b)) (f (f m m) (f (f e m) (f e m))))).\nsurgery id_l ((f (f e (f e b)) (f (f m m) (f (f e m) (f e m))))) ((f (f e b) (f (f m m) (f (f e m) (f e m))))).\nsurgery id_l ((f (f e b) (f (f m m) (f (f e m) (f e m))))) ((f b (f (f m m) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f m m) (f (f e m) (f e m))))) ((f b (f m (f (f e m) (f e m))))).\nsurgery id_r ((f b (f m (f (f e m) (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_127: forall b: G, ((b <+> (m <+> m)) <+> (e <+> (((((e <+> m) <+> m) <+> m) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m m)) (f e (f (f (f (f (f e m) m) m) m) m)))) ((f (f b m) (f e (f (f (f (f (f e m) m) m) m) m)))).\nsurgery id_r ((f (f b m) (f e (f (f (f (f (f e m) m) m) m) m)))) ((f b (f e (f (f (f (f (f e m) m) m) m) m)))).\nsurgery id_l ((f b (f e (f (f (f (f (f e m) m) m) m) m)))) ((f b (f (f (f (f (f e m) m) m) m) m))).\nsurgery id_r ((f b (f (f (f (f (f e m) m) m) m) m))) ((f b (f (f (f (f e m) m) m) m))).\nsurgery id_r ((f b (f (f (f (f e m) m) m) m))) ((f b (f (f (f e m) m) m))).\nsurgery id_r ((f b (f (f (f e m) m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_128: forall b: G, (e <+> (((b <+> (e <+> (e <+> m))) <+> (m <+> (e <+> m))) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f e (f (f (f b (f e (f e m))) (f m (f e m))) (f m m)))) ((f e (f (f (f b (f e m)) (f m (f e m))) (f m m)))).\nsurgery id_l ((f e (f (f (f b (f e m)) (f m (f e m))) (f m m)))) ((f e (f (f (f b m) (f m (f e m))) (f m m)))).\nsurgery id_r ((f e (f (f (f b m) (f m (f e m))) (f m m)))) ((f e (f (f b (f m (f e m))) (f m m)))).\nsurgery id_l ((f e (f (f b (f m (f e m))) (f m m)))) ((f e (f (f b (f m m)) (f m m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f m m)))) ((f e (f (f b m) (f m m)))).\nsurgery id_r ((f e (f (f b m) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_129: forall b: G, (((e <+> b) <+> m) <+> ((e <+> (m <+> ((e <+> m) <+> m))) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) m) (f (f e (f m (f (f e m) m))) (f m m)))) ((f (f e b) (f (f e (f m (f (f e m) m))) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e (f m (f (f e m) m))) (f m m)))) ((f b (f (f e (f m (f (f e m) m))) (f m m)))).\nsurgery id_r ((f b (f (f e (f m (f (f e m) m))) (f m m)))) ((f b (f (f e (f m (f e m))) (f m m)))).\nsurgery id_l ((f b (f (f e (f m (f e m))) (f m m)))) ((f b (f (f e (f m m)) (f m m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_130: forall b: G, (((((e <+> m) <+> m) <+> m) <+> ((e <+> e) <+> b)) <+> (e <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) m) m) (f (f e e) b)) (f e (f e m)))) ((f (f (f (f e m) m) (f (f e e) b)) (f e (f e m)))).\nsurgery id_r ((f (f (f (f e m) m) (f (f e e) b)) (f e (f e m)))) ((f (f (f e m) (f (f e e) b)) (f e (f e m)))).\nsurgery id_r ((f (f (f e m) (f (f e e) b)) (f e (f e m)))) ((f (f e (f (f e e) b)) (f e (f e m)))).\nsurgery id_l ((f (f e (f (f e e) b)) (f e (f e m)))) ((f (f e (f e b)) (f e (f e m)))).\nsurgery id_l ((f (f e (f e b)) (f e (f e m)))) ((f (f e b) (f e (f e m)))).\nsurgery id_l ((f (f e b) (f e (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_131: forall b: G, (b <+> (((m <+> m) <+> m) <+> ((e <+> (e <+> e)) <+> ((e <+> e) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f m m) m) (f (f e (f e e)) (f (f e e) m))))) ((f b (f (f m m) (f (f e (f e e)) (f (f e e) m))))).\nsurgery id_r ((f b (f (f m m) (f (f e (f e e)) (f (f e e) m))))) ((f b (f m (f (f e (f e e)) (f (f e e) m))))).\nsurgery id_l ((f b (f m (f (f e (f e e)) (f (f e e) m))))) ((f b (f m (f (f e e) (f (f e e) m))))).\nsurgery id_l ((f b (f m (f (f e e) (f (f e e) m))))) ((f b (f m (f e (f (f e e) m))))).\nsurgery id_l ((f b (f m (f e (f (f e e) m))))) ((f b (f m (f (f e e) m)))).\nsurgery id_l ((f b (f m (f (f e e) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_132: forall b: G, (((((e <+> e) <+> e) <+> m) <+> (e <+> (e <+> ((e <+> m) <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) e) m) (f e (f e (f (f e m) m)))) b)) ((f (f (f (f e e) e) (f e (f e (f (f e m) m)))) b)).\nsurgery id_l ((f (f (f (f e e) e) (f e (f e (f (f e m) m)))) b)) ((f (f (f e e) (f e (f e (f (f e m) m)))) b)).\nsurgery id_l ((f (f (f e e) (f e (f e (f (f e m) m)))) b)) ((f (f e (f e (f e (f (f e m) m)))) b)).\nsurgery id_l ((f (f e (f e (f e (f (f e m) m)))) b)) ((f (f e (f e (f (f e m) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e m) m))) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_133: forall b: G, ((e <+> e) <+> ((((e <+> (e <+> e)) <+> m) <+> (b <+> (e <+> m))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f (f e (f e e)) m) (f b (f e m))) m))) ((f e (f (f (f (f e (f e e)) m) (f b (f e m))) m))).\nsurgery id_r ((f e (f (f (f (f e (f e e)) m) (f b (f e m))) m))) ((f e (f (f (f e (f e e)) (f b (f e m))) m))).\nsurgery id_l ((f e (f (f (f e (f e e)) (f b (f e m))) m))) ((f e (f (f (f e e) (f b (f e m))) m))).\nsurgery id_l ((f e (f (f (f e e) (f b (f e m))) m))) ((f e (f (f e (f b (f e m))) m))).\nsurgery id_l ((f e (f (f e (f b (f e m))) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_134: forall b: G, (((e <+> (e <+> m)) <+> (e <+> b)) <+> (m <+> ((e <+> (e <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e b)) (f m (f (f e (f e m)) m)))) ((f (f (f e m) (f e b)) (f m (f (f e (f e m)) m)))).\nsurgery id_r ((f (f (f e m) (f e b)) (f m (f (f e (f e m)) m)))) ((f (f e (f e b)) (f m (f (f e (f e m)) m)))).\nsurgery id_l ((f (f e (f e b)) (f m (f (f e (f e m)) m)))) ((f (f e b) (f m (f (f e (f e m)) m)))).\nsurgery id_l ((f (f e b) (f m (f (f e (f e m)) m)))) ((f b (f m (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f m (f (f e (f e m)) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_135: forall b: G, (((b <+> m) <+> (e <+> (m <+> m))) <+> (((e <+> (e <+> e)) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f e (f m m))) (f (f (f e (f e e)) m) m))) ((f (f b (f e (f m m))) (f (f (f e (f e e)) m) m))).\nsurgery id_l ((f (f b (f e (f m m))) (f (f (f e (f e e)) m) m))) ((f (f b (f m m)) (f (f (f e (f e e)) m) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e (f e e)) m) m))) ((f (f b m) (f (f (f e (f e e)) m) m))).\nsurgery id_r ((f (f b m) (f (f (f e (f e e)) m) m))) ((f b (f (f (f e (f e e)) m) m))).\nsurgery id_r ((f b (f (f (f e (f e e)) m) m))) ((f b (f (f e (f e e)) m))).\nsurgery id_l ((f b (f (f e (f e e)) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_136: forall b: G, (((e <+> (e <+> m)) <+> ((e <+> m) <+> (e <+> m))) <+> (e <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) (f e m))) (f e (f e b)))) ((f (f (f e m) (f (f e m) (f e m))) (f e (f e b)))).\nsurgery id_r ((f (f (f e m) (f (f e m) (f e m))) (f e (f e b)))) ((f (f e (f (f e m) (f e m))) (f e (f e b)))).\nsurgery id_r ((f (f e (f (f e m) (f e m))) (f e (f e b)))) ((f (f e (f e (f e m))) (f e (f e b)))).\nsurgery id_l ((f (f e (f e (f e m))) (f e (f e b)))) ((f (f e (f e m)) (f e (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f e (f e b)))) ((f (f e m) (f e (f e b)))).\nsurgery id_r ((f (f e m) (f e (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_137: forall b: G, ((e <+> e) <+> ((e <+> (e <+> e)) <+> ((b <+> (m <+> (e <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f e (f e e)) (f (f b (f m (f e m))) m)))) ((f e (f (f e (f e e)) (f (f b (f m (f e m))) m)))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f b (f m (f e m))) m)))) ((f e (f (f e e) (f (f b (f m (f e m))) m)))).\nsurgery id_l ((f e (f (f e e) (f (f b (f m (f e m))) m)))) ((f e (f e (f (f b (f m (f e m))) m)))).\nsurgery id_l ((f e (f e (f (f b (f m (f e m))) m)))) ((f e (f (f b (f m (f e m))) m))).\nsurgery id_l ((f e (f (f b (f m (f e m))) m))) ((f e (f (f b (f m m)) m))).\nsurgery id_r ((f e (f (f b (f m m)) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_138: forall b: G, ((((e <+> m) <+> e) <+> (((e <+> e) <+> e) <+> b)) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f (f (f e e) e) b)) (f (f e m) m))) ((f (f (f e e) (f (f (f e e) e) b)) (f (f e m) m))).\nsurgery id_l ((f (f (f e e) (f (f (f e e) e) b)) (f (f e m) m))) ((f (f e (f (f (f e e) e) b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f (f e e) e) b)) (f (f e m) m))) ((f (f e (f (f e e) b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f e e) b)) (f (f e m) m))) ((f (f e (f e b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f e m) m))) ((f (f e b) (f (f e m) m))).\nsurgery id_l ((f (f e b) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_139: forall b: G, (((e <+> b) <+> (((e <+> m) <+> e) <+> m)) <+> (m <+> ((m <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f (f e m) e) m)) (f m (f (f m m) m)))) ((f (f b (f (f (f e m) e) m)) (f m (f (f m m) m)))).\nsurgery id_r ((f (f b (f (f (f e m) e) m)) (f m (f (f m m) m)))) ((f (f b (f (f e e) m)) (f m (f (f m m) m)))).\nsurgery id_l ((f (f b (f (f e e) m)) (f m (f (f m m) m)))) ((f (f b (f e m)) (f m (f (f m m) m)))).\nsurgery id_l ((f (f b (f e m)) (f m (f (f m m) m)))) ((f (f b m) (f m (f (f m m) m)))).\nsurgery id_r ((f (f b m) (f m (f (f m m) m)))) ((f b (f m (f (f m m) m)))).\nsurgery id_r ((f b (f m (f (f m m) m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_140: forall b: G, ((b <+> m) <+> (((e <+> e) <+> m) <+> ((e <+> ((e <+> m) <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f (f e e) m) (f (f e (f (f e m) m)) m)))) ((f b (f (f (f e e) m) (f (f e (f (f e m) m)) m)))).\nsurgery id_r ((f b (f (f (f e e) m) (f (f e (f (f e m) m)) m)))) ((f b (f (f e e) (f (f e (f (f e m) m)) m)))).\nsurgery id_l ((f b (f (f e e) (f (f e (f (f e m) m)) m)))) ((f b (f e (f (f e (f (f e m) m)) m)))).\nsurgery id_l ((f b (f e (f (f e (f (f e m) m)) m)))) ((f b (f (f e (f (f e m) m)) m))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_141: forall b: G, ((b <+> ((m <+> m) <+> (e <+> (e <+> m)))) <+> (m <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f m m) (f e (f e m)))) (f m (f (f e m) m)))) ((f (f b (f m (f e (f e m)))) (f m (f (f e m) m)))).\nsurgery id_l ((f (f b (f m (f e (f e m)))) (f m (f (f e m) m)))) ((f (f b (f m (f e m))) (f m (f (f e m) m)))).\nsurgery id_l ((f (f b (f m (f e m))) (f m (f (f e m) m)))) ((f (f b (f m m)) (f m (f (f e m) m)))).\nsurgery id_r ((f (f b (f m m)) (f m (f (f e m) m)))) ((f (f b m) (f m (f (f e m) m)))).\nsurgery id_r ((f (f b m) (f m (f (f e m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_142: forall b: G, (((e <+> m) <+> ((m <+> m) <+> (m <+> (e <+> m)))) <+> (b <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f m m) (f m (f e m)))) (f b (f e m)))) ((f (f e (f (f m m) (f m (f e m)))) (f b (f e m)))).\nsurgery id_r ((f (f e (f (f m m) (f m (f e m)))) (f b (f e m)))) ((f (f e (f m (f m (f e m)))) (f b (f e m)))).\nsurgery id_l ((f (f e (f m (f m (f e m)))) (f b (f e m)))) ((f (f e (f m (f m m))) (f b (f e m)))).\nsurgery id_r ((f (f e (f m (f m m))) (f b (f e m)))) ((f (f e (f m m)) (f b (f e m)))).\nsurgery id_r ((f (f e (f m m)) (f b (f e m)))) ((f (f e m) (f b (f e m)))).\nsurgery id_r ((f (f e m) (f b (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_143: forall b: G, ((e <+> e) <+> (((e <+> e) <+> ((e <+> e) <+> (e <+> m))) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f e e) (f (f e e) (f e m))) (f e b)))) ((f e (f (f (f e e) (f (f e e) (f e m))) (f e b)))).\nsurgery id_l ((f e (f (f (f e e) (f (f e e) (f e m))) (f e b)))) ((f e (f (f e (f (f e e) (f e m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f (f e e) (f e m))) (f e b)))) ((f e (f (f e (f e (f e m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f e (f e m))) (f e b)))) ((f e (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_144: forall b: G, (((e <+> e) <+> b) <+> (m <+> (e <+> ((e <+> (e <+> (e <+> m))) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) b) (f m (f e (f (f e (f e (f e m))) m))))) ((f (f e b) (f m (f e (f (f e (f e (f e m))) m))))).\nsurgery id_l ((f (f e b) (f m (f e (f (f e (f e (f e m))) m))))) ((f b (f m (f e (f (f e (f e (f e m))) m))))).\nsurgery id_l ((f b (f m (f e (f (f e (f e (f e m))) m))))) ((f b (f m (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f b (f m (f (f e (f e (f e m))) m)))) ((f b (f m (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f m (f (f e (f e m)) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_145: forall b: G, (((e <+> (e <+> m)) <+> m) <+> ((e <+> (b <+> m)) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f e m)) m) (f (f e (f b m)) (f (f e e) m)))) ((f (f e (f e m)) (f (f e (f b m)) (f (f e e) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e (f b m)) (f (f e e) m)))) ((f (f e m) (f (f e (f b m)) (f (f e e) m)))).\nsurgery id_r ((f (f e m) (f (f e (f b m)) (f (f e e) m)))) ((f e (f (f e (f b m)) (f (f e e) m)))).\nsurgery id_r ((f e (f (f e (f b m)) (f (f e e) m)))) ((f e (f (f e b) (f (f e e) m)))).\nsurgery id_l ((f e (f (f e b) (f (f e e) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_146: forall b: G, ((e <+> (e <+> m)) <+> ((e <+> m) <+> (((e <+> m) <+> m) <+> (b <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f e m) (f (f (f e m) m) (f b m))))) ((f (f e m) (f (f e m) (f (f (f e m) m) (f b m))))).\nsurgery id_r ((f (f e m) (f (f e m) (f (f (f e m) m) (f b m))))) ((f e (f (f e m) (f (f (f e m) m) (f b m))))).\nsurgery id_r ((f e (f (f e m) (f (f (f e m) m) (f b m))))) ((f e (f e (f (f (f e m) m) (f b m))))).\nsurgery id_l ((f e (f e (f (f (f e m) m) (f b m))))) ((f e (f (f (f e m) m) (f b m)))).\nsurgery id_r ((f e (f (f (f e m) m) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_147: forall b: G, ((((e <+> e) <+> (b <+> (e <+> (e <+> m)))) <+> m) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f b (f e (f e m)))) m) (f m (f m m)))) ((f (f (f e e) (f b (f e (f e m)))) (f m (f m m)))).\nsurgery id_l ((f (f (f e e) (f b (f e (f e m)))) (f m (f m m)))) ((f (f e (f b (f e (f e m)))) (f m (f m m)))).\nsurgery id_l ((f (f e (f b (f e (f e m)))) (f m (f m m)))) ((f (f e (f b (f e m))) (f m (f m m)))).\nsurgery id_l ((f (f e (f b (f e m))) (f m (f m m)))) ((f (f e (f b m)) (f m (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f m (f m m)))) ((f (f e b) (f m (f m m)))).\nsurgery id_l ((f (f e b) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_148: forall b: G, ((((((e <+> m) <+> (e <+> e)) <+> e) <+> (b <+> m)) <+> (m <+> m)) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e m) (f e e)) e) (f b m)) (f m m)) m)) ((f (f (f (f (f e m) (f e e)) e) (f b m)) (f m m))).\nsurgery id_r ((f (f (f (f (f e m) (f e e)) e) (f b m)) (f m m))) ((f (f (f (f e (f e e)) e) (f b m)) (f m m))).\nsurgery id_l ((f (f (f (f e (f e e)) e) (f b m)) (f m m))) ((f (f (f (f e e) e) (f b m)) (f m m))).\nsurgery id_l ((f (f (f (f e e) e) (f b m)) (f m m))) ((f (f (f e e) (f b m)) (f m m))).\nsurgery id_l ((f (f (f e e) (f b m)) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_149: forall b: G, (((e <+> m) <+> b) <+> ((m <+> m) <+> (e <+> ((e <+> m) <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) b) (f (f m m) (f e (f (f e m) (f e m)))))) ((f (f e b) (f (f m m) (f e (f (f e m) (f e m)))))).\nsurgery id_l ((f (f e b) (f (f m m) (f e (f (f e m) (f e m)))))) ((f b (f (f m m) (f e (f (f e m) (f e m)))))).\nsurgery id_r ((f b (f (f m m) (f e (f (f e m) (f e m)))))) ((f b (f m (f e (f (f e m) (f e m)))))).\nsurgery id_l ((f b (f m (f e (f (f e m) (f e m)))))) ((f b (f m (f (f e m) (f e m))))).\nsurgery id_r ((f b (f m (f (f e m) (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_150: forall b: G, (e <+> ((e <+> ((e <+> m) <+> (b <+> (m <+> (m <+> m))))) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e (f (f e m) (f b (f m (f m m))))) (f e m)))) ((f e (f (f e (f e (f b (f m (f m m))))) (f e m)))).\nsurgery id_l ((f e (f (f e (f e (f b (f m (f m m))))) (f e m)))) ((f e (f (f e (f b (f m (f m m)))) (f e m)))).\nsurgery id_r ((f e (f (f e (f b (f m (f m m)))) (f e m)))) ((f e (f (f e (f b (f m m))) (f e m)))).\nsurgery id_r ((f e (f (f e (f b (f m m))) (f e m)))) ((f e (f (f e (f b m)) (f e m)))).\nsurgery id_r ((f e (f (f e (f b m)) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_151: forall b: G, ((b <+> m) <+> (((m <+> m) <+> ((e <+> e) <+> (m <+> (e <+> m)))) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f (f m m) (f (f e e) (f m (f e m)))) m))) ((f b (f (f (f m m) (f (f e e) (f m (f e m)))) m))).\nsurgery id_r ((f b (f (f (f m m) (f (f e e) (f m (f e m)))) m))) ((f b (f (f m (f (f e e) (f m (f e m)))) m))).\nsurgery id_l ((f b (f (f m (f (f e e) (f m (f e m)))) m))) ((f b (f (f m (f e (f m (f e m)))) m))).\nsurgery id_l ((f b (f (f m (f e (f m (f e m)))) m))) ((f b (f (f m (f m (f e m))) m))).\nsurgery id_l ((f b (f (f m (f m (f e m))) m))) ((f b (f (f m (f m m)) m))).\nsurgery id_r ((f b (f (f m (f m m)) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_152: forall b: G, (((e <+> e) <+> (((e <+> e) <+> m) <+> m)) <+> ((e <+> m) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f e e) m) m)) (f (f e m) (f b m)))) ((f (f e (f (f (f e e) m) m)) (f (f e m) (f b m)))).\nsurgery id_r ((f (f e (f (f (f e e) m) m)) (f (f e m) (f b m)))) ((f (f e (f (f e e) m)) (f (f e m) (f b m)))).\nsurgery id_l ((f (f e (f (f e e) m)) (f (f e m) (f b m)))) ((f (f e (f e m)) (f (f e m) (f b m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e m) (f b m)))) ((f (f e m) (f (f e m) (f b m)))).\nsurgery id_r ((f (f e m) (f (f e m) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_153: forall b: G, (b <+> ((e <+> (m <+> (((e <+> e) <+> (m <+> m)) <+> (m <+> m)))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f e (f m (f (f (f e e) (f m m)) (f m m)))) m))) ((f b (f (f e (f m (f (f e (f m m)) (f m m)))) m))).\nsurgery id_r ((f b (f (f e (f m (f (f e (f m m)) (f m m)))) m))) ((f b (f (f e (f m (f (f e m) (f m m)))) m))).\nsurgery id_r ((f b (f (f e (f m (f (f e m) (f m m)))) m))) ((f b (f (f e (f m (f e (f m m)))) m))).\nsurgery id_l ((f b (f (f e (f m (f e (f m m)))) m))) ((f b (f (f e (f m (f m m))) m))).\nsurgery id_r ((f b (f (f e (f m (f m m))) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_154: forall b: G, (((b <+> m) <+> (m <+> m)) <+> (((e <+> m) <+> m) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f m m)) (f (f (f e m) m) (f m (f m m))))) ((f (f b (f m m)) (f (f (f e m) m) (f m (f m m))))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e m) m) (f m (f m m))))) ((f (f b m) (f (f (f e m) m) (f m (f m m))))).\nsurgery id_r ((f (f b m) (f (f (f e m) m) (f m (f m m))))) ((f b (f (f (f e m) m) (f m (f m m))))).\nsurgery id_r ((f b (f (f (f e m) m) (f m (f m m))))) ((f b (f (f e m) (f m (f m m))))).\nsurgery id_r ((f b (f (f e m) (f m (f m m))))) ((f b (f e (f m (f m m))))).\nsurgery id_l ((f b (f e (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_155: forall b: G, ((((e <+> e) <+> m) <+> b) <+> (e <+> ((m <+> m) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) b) (f e (f (f m m) (f e (f m m)))))) ((f (f (f e e) b) (f e (f (f m m) (f e (f m m)))))).\nsurgery id_l ((f (f (f e e) b) (f e (f (f m m) (f e (f m m)))))) ((f (f e b) (f e (f (f m m) (f e (f m m)))))).\nsurgery id_l ((f (f e b) (f e (f (f m m) (f e (f m m)))))) ((f b (f e (f (f m m) (f e (f m m)))))).\nsurgery id_l ((f b (f e (f (f m m) (f e (f m m)))))) ((f b (f (f m m) (f e (f m m))))).\nsurgery id_r ((f b (f (f m m) (f e (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_156: forall b: G, ((e <+> (m <+> (((e <+> m) <+> m) <+> m))) <+> (b <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f m (f (f (f e m) m) m))) (f b (f (f e m) m)))) ((f (f e (f m (f (f e m) m))) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e (f m (f (f e m) m))) (f b (f (f e m) m)))) ((f (f e (f m (f e m))) (f b (f (f e m) m)))).\nsurgery id_l ((f (f e (f m (f e m))) (f b (f (f e m) m)))) ((f (f e (f m m)) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f e m) m)))) ((f (f e m) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e m) (f b (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_157: forall b: G, ((e <+> m) <+> ((e <+> (((e <+> m) <+> b) <+> (m <+> m))) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e (f (f (f e m) b) (f m m))) (f m m)))) ((f e (f (f e (f (f (f e m) b) (f m m))) (f m m)))).\nsurgery id_r ((f e (f (f e (f (f (f e m) b) (f m m))) (f m m)))) ((f e (f (f e (f (f e b) (f m m))) (f m m)))).\nsurgery id_l ((f e (f (f e (f (f e b) (f m m))) (f m m)))) ((f e (f (f e (f b (f m m))) (f m m)))).\nsurgery id_r ((f e (f (f e (f b (f m m))) (f m m)))) ((f e (f (f e (f b m)) (f m m)))).\nsurgery id_r ((f e (f (f e (f b m)) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_158: forall b: G, (((b <+> m) <+> (((e <+> e) <+> ((m <+> m) <+> m)) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f (f e e) (f (f m m) m)) m)) (f m m))) ((f (f b (f (f (f e e) (f (f m m) m)) m)) (f m m))).\nsurgery id_l ((f (f b (f (f (f e e) (f (f m m) m)) m)) (f m m))) ((f (f b (f (f e (f (f m m) m)) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e (f (f m m) m)) m)) (f m m))) ((f (f b (f (f e (f m m)) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e (f m m)) m)) (f m m))) ((f (f b (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_159: forall b: G, (((((e <+> m) <+> e) <+> e) <+> (e <+> ((e <+> e) <+> m))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) e) e) (f e (f (f e e) m))) (f b m))) ((f (f (f (f e e) e) (f e (f (f e e) m))) (f b m))).\nsurgery id_l ((f (f (f (f e e) e) (f e (f (f e e) m))) (f b m))) ((f (f (f e e) (f e (f (f e e) m))) (f b m))).\nsurgery id_l ((f (f (f e e) (f e (f (f e e) m))) (f b m))) ((f (f e (f e (f (f e e) m))) (f b m))).\nsurgery id_l ((f (f e (f e (f (f e e) m))) (f b m))) ((f (f e (f (f e e) m)) (f b m))).\nsurgery id_l ((f (f e (f (f e e) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_160: forall b: G, (((b <+> m) <+> ((e <+> m) <+> ((e <+> e) <+> m))) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f e m) (f (f e e) m))) (f e (f m m)))) ((f (f b (f (f e m) (f (f e e) m))) (f e (f m m)))).\nsurgery id_r ((f (f b (f (f e m) (f (f e e) m))) (f e (f m m)))) ((f (f b (f e (f (f e e) m))) (f e (f m m)))).\nsurgery id_l ((f (f b (f e (f (f e e) m))) (f e (f m m)))) ((f (f b (f (f e e) m)) (f e (f m m)))).\nsurgery id_l ((f (f b (f (f e e) m)) (f e (f m m)))) ((f (f b (f e m)) (f e (f m m)))).\nsurgery id_l ((f (f b (f e m)) (f e (f m m)))) ((f (f b m) (f e (f m m)))).\nsurgery id_r ((f (f b m) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_161: forall b: G, ((e <+> (e <+> ((e <+> m) <+> m))) <+> ((e <+> m) <+> ((e <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f (f e m) (f (f e b) m)))) ((f (f e (f (f e m) m)) (f (f e m) (f (f e b) m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f e m) (f (f e b) m)))) ((f (f e (f e m)) (f (f e m) (f (f e b) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e m) (f (f e b) m)))) ((f (f e m) (f (f e m) (f (f e b) m)))).\nsurgery id_r ((f (f e m) (f (f e m) (f (f e b) m)))) ((f e (f (f e m) (f (f e b) m)))).\nsurgery id_r ((f e (f (f e m) (f (f e b) m)))) ((f e (f e (f (f e b) m)))).\nsurgery id_l ((f e (f e (f (f e b) m)))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_162: forall b: G, ((((e <+> e) <+> e) <+> (e <+> e)) <+> ((e <+> m) <+> ((e <+> e) <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) e) (f e e)) (f (f e m) (f (f e e) b)))) ((f (f (f e e) (f e e)) (f (f e m) (f (f e e) b)))).\nsurgery id_l ((f (f (f e e) (f e e)) (f (f e m) (f (f e e) b)))) ((f (f e (f e e)) (f (f e m) (f (f e e) b)))).\nsurgery id_l ((f (f e (f e e)) (f (f e m) (f (f e e) b)))) ((f (f e e) (f (f e m) (f (f e e) b)))).\nsurgery id_l ((f (f e e) (f (f e m) (f (f e e) b)))) ((f e (f (f e m) (f (f e e) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e e) b)))) ((f e (f e (f (f e e) b)))).\nsurgery id_l ((f e (f e (f (f e e) b)))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_163: forall b: G, ((e <+> (e <+> ((e <+> e) <+> (((e <+> m) <+> m) <+> m)))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f (f e e) (f (f (f e m) m) m)))) (f b m))) ((f (f e (f (f e e) (f (f (f e m) m) m))) (f b m))).\nsurgery id_l ((f (f e (f (f e e) (f (f (f e m) m) m))) (f b m))) ((f (f e (f e (f (f (f e m) m) m))) (f b m))).\nsurgery id_l ((f (f e (f e (f (f (f e m) m) m))) (f b m))) ((f (f e (f (f (f e m) m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_164: forall b: G, ((b <+> m) <+> ((((e <+> m) <+> (e <+> m)) <+> m) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f (f (f e m) (f e m)) m) (f e (f e m))))) ((f b (f (f (f (f e m) (f e m)) m) (f e (f e m))))).\nsurgery id_r ((f b (f (f (f (f e m) (f e m)) m) (f e (f e m))))) ((f b (f (f (f e m) (f e m)) (f e (f e m))))).\nsurgery id_r ((f b (f (f (f e m) (f e m)) (f e (f e m))))) ((f b (f (f e (f e m)) (f e (f e m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f e (f e m))))) ((f b (f (f e m) (f e (f e m))))).\nsurgery id_r ((f b (f (f e m) (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_165: forall b: G, (((e <+> (e <+> m)) <+> (e <+> ((e <+> m) <+> m))) <+> (e <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e (f (f e m) m))) (f e (f e b)))) ((f (f (f e m) (f e (f (f e m) m))) (f e (f e b)))).\nsurgery id_r ((f (f (f e m) (f e (f (f e m) m))) (f e (f e b)))) ((f (f e (f e (f (f e m) m))) (f e (f e b)))).\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f e (f e b)))) ((f (f e (f (f e m) m)) (f e (f e b)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f e b)))) ((f (f e (f e m)) (f e (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f e (f e b)))) ((f (f e m) (f e (f e b)))).\nsurgery id_r ((f (f e m) (f e (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_166: forall b: G, ((e <+> b) <+> (((e <+> m) <+> m) <+> (m <+> ((e <+> m) <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f (f e m) m) (f m (f (f e m) (f m m)))))) ((f b (f (f (f e m) m) (f m (f (f e m) (f m m)))))).\nsurgery id_r ((f b (f (f (f e m) m) (f m (f (f e m) (f m m)))))) ((f b (f (f e m) (f m (f (f e m) (f m m)))))).\nsurgery id_r ((f b (f (f e m) (f m (f (f e m) (f m m)))))) ((f b (f e (f m (f (f e m) (f m m)))))).\nsurgery id_l ((f b (f e (f m (f (f e m) (f m m)))))) ((f b (f m (f (f e m) (f m m))))).\nsurgery id_r ((f b (f m (f (f e m) (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_167: forall b: G, (b <+> (((e <+> m) <+> (m <+> (e <+> m))) <+> ((e <+> (e <+> e)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e m) (f m (f e m))) (f (f e (f e e)) m)))) ((f b (f (f e (f m (f e m))) (f (f e (f e e)) m)))).\nsurgery id_l ((f b (f (f e (f m (f e m))) (f (f e (f e e)) m)))) ((f b (f (f e (f m m)) (f (f e (f e e)) m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f e (f e e)) m)))) ((f b (f (f e m) (f (f e (f e e)) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e (f e e)) m)))) ((f b (f e (f (f e (f e e)) m)))).\nsurgery id_l ((f b (f e (f (f e (f e e)) m)))) ((f b (f (f e (f e e)) m))).\nsurgery id_l ((f b (f (f e (f e e)) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_168: forall b: G, ((e <+> e) <+> ((b <+> m) <+> (m <+> ((e <+> (e <+> (m <+> m))) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f b m) (f m (f (f e (f e (f m m))) m))))) ((f e (f (f b m) (f m (f (f e (f e (f m m))) m))))).\nsurgery id_r ((f e (f (f b m) (f m (f (f e (f e (f m m))) m))))) ((f e (f b (f m (f (f e (f e (f m m))) m))))).\nsurgery id_l ((f e (f b (f m (f (f e (f e (f m m))) m))))) ((f e (f b (f m (f (f e (f m m)) m))))).\nsurgery id_r ((f e (f b (f m (f (f e (f m m)) m))))) ((f e (f b (f m (f (f e m) m))))).\nsurgery id_r ((f e (f b (f m (f (f e m) m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_169: forall b: G, ((e <+> m) <+> (((e <+> (e <+> (b <+> m))) <+> m) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e (f e (f b m))) m) (f m (f m m))))) ((f e (f (f (f e (f e (f b m))) m) (f m (f m m))))).\nsurgery id_r ((f e (f (f (f e (f e (f b m))) m) (f m (f m m))))) ((f e (f (f e (f e (f b m))) (f m (f m m))))).\nsurgery id_l ((f e (f (f e (f e (f b m))) (f m (f m m))))) ((f e (f (f e (f b m)) (f m (f m m))))).\nsurgery id_r ((f e (f (f e (f b m)) (f m (f m m))))) ((f e (f (f e b) (f m (f m m))))).\nsurgery id_l ((f e (f (f e b) (f m (f m m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_170: forall b: G, (((e <+> e) <+> e) <+> (((e <+> (e <+> m)) <+> b) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) e) (f (f (f e (f e m)) b) (f (f e m) m)))) ((f (f e e) (f (f (f e (f e m)) b) (f (f e m) m)))).\nsurgery id_l ((f (f e e) (f (f (f e (f e m)) b) (f (f e m) m)))) ((f e (f (f (f e (f e m)) b) (f (f e m) m)))).\nsurgery id_l ((f e (f (f (f e (f e m)) b) (f (f e m) m)))) ((f e (f (f (f e m) b) (f (f e m) m)))).\nsurgery id_r ((f e (f (f (f e m) b) (f (f e m) m)))) ((f e (f (f e b) (f (f e m) m)))).\nsurgery id_l ((f e (f (f e b) (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_171: forall b: G, ((((b <+> m) <+> m) <+> (m <+> ((m <+> m) <+> m))) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f b m) m) (f m (f (f m m) m))) (f m (f m m)))) ((f (f (f b m) (f m (f (f m m) m))) (f m (f m m)))).\nsurgery id_r ((f (f (f b m) (f m (f (f m m) m))) (f m (f m m)))) ((f (f b (f m (f (f m m) m))) (f m (f m m)))).\nsurgery id_r ((f (f b (f m (f (f m m) m))) (f m (f m m)))) ((f (f b (f m (f m m))) (f m (f m m)))).\nsurgery id_r ((f (f b (f m (f m m))) (f m (f m m)))) ((f (f b (f m m)) (f m (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f m (f m m)))) ((f (f b m) (f m (f m m)))).\nsurgery id_r ((f (f b m) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_172: forall b: G, ((e <+> (((e <+> m) <+> m) <+> m)) <+> (e <+> (((e <+> e) <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f e (f (f (f e e) b) m)))) ((f (f e (f (f e m) m)) (f e (f (f (f e e) b) m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f (f (f e e) b) m)))) ((f (f e (f e m)) (f e (f (f (f e e) b) m)))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f (f e e) b) m)))) ((f (f e m) (f e (f (f (f e e) b) m)))).\nsurgery id_r ((f (f e m) (f e (f (f (f e e) b) m)))) ((f e (f e (f (f (f e e) b) m)))).\nsurgery id_l ((f e (f e (f (f (f e e) b) m)))) ((f e (f (f (f e e) b) m))).\nsurgery id_l ((f e (f (f (f e e) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_173: forall b: G, (b <+> (((e <+> e) <+> (e <+> m)) <+> ((m <+> m) <+> (m <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f (f e e) (f e m)) (f (f m m) (f m (f m m)))))) ((f b (f (f e (f e m)) (f (f m m) (f m (f m m)))))).\nsurgery id_l ((f b (f (f e (f e m)) (f (f m m) (f m (f m m)))))) ((f b (f (f e m) (f (f m m) (f m (f m m)))))).\nsurgery id_r ((f b (f (f e m) (f (f m m) (f m (f m m)))))) ((f b (f e (f (f m m) (f m (f m m)))))).\nsurgery id_l ((f b (f e (f (f m m) (f m (f m m)))))) ((f b (f (f m m) (f m (f m m))))).\nsurgery id_r ((f b (f (f m m) (f m (f m m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_174: forall b: G, ((e <+> ((e <+> m) <+> m)) <+> (e <+> ((b <+> m) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f (f b m) (f e (f m m)))))) ((f (f e (f e m)) (f e (f (f b m) (f e (f m m)))))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f b m) (f e (f m m)))))) ((f (f e m) (f e (f (f b m) (f e (f m m)))))).\nsurgery id_r ((f (f e m) (f e (f (f b m) (f e (f m m)))))) ((f e (f e (f (f b m) (f e (f m m)))))).\nsurgery id_l ((f e (f e (f (f b m) (f e (f m m)))))) ((f e (f (f b m) (f e (f m m))))).\nsurgery id_r ((f e (f (f b m) (f e (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_175: forall b: G, ((e <+> e) <+> (((e <+> e) <+> (m <+> ((m <+> m) <+> (m <+> m)))) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f e e) (f m (f (f m m) (f m m)))) b))) ((f e (f (f (f e e) (f m (f (f m m) (f m m)))) b))).\nsurgery id_l ((f e (f (f (f e e) (f m (f (f m m) (f m m)))) b))) ((f e (f (f e (f m (f (f m m) (f m m)))) b))).\nsurgery id_r ((f e (f (f e (f m (f (f m m) (f m m)))) b))) ((f e (f (f e (f m (f m (f m m)))) b))).\nsurgery id_r ((f e (f (f e (f m (f m (f m m)))) b))) ((f e (f (f e (f m (f m m))) b))).\nsurgery id_r ((f e (f (f e (f m (f m m))) b))) ((f e (f (f e (f m m)) b))).\nsurgery id_r ((f e (f (f e (f m m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_176: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> m) <+> (((e <+> b) <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) m) (f (f (f e b) m) (f e m)))) ((f (f (f e m) (f e m)) (f (f (f e b) m) (f e m)))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f (f e b) m) (f e m)))) ((f (f e (f e m)) (f (f (f e b) m) (f e m)))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e b) m) (f e m)))) ((f (f e m) (f (f (f e b) m) (f e m)))).\nsurgery id_r ((f (f e m) (f (f (f e b) m) (f e m)))) ((f e (f (f (f e b) m) (f e m)))).\nsurgery id_r ((f e (f (f (f e b) m) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_177: forall b: G, (((e <+> m) <+> (b <+> m)) <+> ((e <+> (e <+> m)) <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f b m)) (f (f e (f e m)) (f e (f m m))))) ((f (f e (f b m)) (f (f e (f e m)) (f e (f m m))))).\nsurgery id_r ((f (f e (f b m)) (f (f e (f e m)) (f e (f m m))))) ((f (f e b) (f (f e (f e m)) (f e (f m m))))).\nsurgery id_l ((f (f e b) (f (f e (f e m)) (f e (f m m))))) ((f b (f (f e (f e m)) (f e (f m m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f e (f m m))))) ((f b (f (f e m) (f e (f m m))))).\nsurgery id_r ((f b (f (f e m) (f e (f m m))))) ((f b (f e (f e (f m m))))).\nsurgery id_l ((f b (f e (f e (f m m))))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_178: forall b: G, (((b <+> m) <+> (((e <+> m) <+> (e <+> e)) <+> (m <+> m))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f (f e m) (f e e)) (f m m))) (f m m))) ((f (f b (f (f (f e m) (f e e)) (f m m))) (f m m))).\nsurgery id_r ((f (f b (f (f (f e m) (f e e)) (f m m))) (f m m))) ((f (f b (f (f e (f e e)) (f m m))) (f m m))).\nsurgery id_l ((f (f b (f (f e (f e e)) (f m m))) (f m m))) ((f (f b (f (f e e) (f m m))) (f m m))).\nsurgery id_l ((f (f b (f (f e e) (f m m))) (f m m))) ((f (f b (f e (f m m))) (f m m))).\nsurgery id_l ((f (f b (f e (f m m))) (f m m))) ((f (f b (f m m)) (f m m))).\nsurgery id_r ((f (f b (f m m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_179: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> ((e <+> e) <+> ((e <+> e) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) (f (f e e) (f (f e e) m))) b)) ((f (f (f e (f e m)) (f (f e e) (f (f e e) m))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e e) (f (f e e) m))) b)) ((f (f (f e m) (f (f e e) (f (f e e) m))) b)).\nsurgery id_r ((f (f (f e m) (f (f e e) (f (f e e) m))) b)) ((f (f e (f (f e e) (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f (f e e) (f (f e e) m))) b)) ((f (f e (f e (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e e) m))) b)) ((f (f e (f (f e e) m)) b)).\nsurgery id_l ((f (f e (f (f e e) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_180: forall b: G, (((e <+> e) <+> b) <+> ((m <+> ((e <+> (e <+> m)) <+> m)) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) b) (f (f m (f (f e (f e m)) m)) (f m m)))) ((f (f e b) (f (f m (f (f e (f e m)) m)) (f m m)))).\nsurgery id_l ((f (f e b) (f (f m (f (f e (f e m)) m)) (f m m)))) ((f b (f (f m (f (f e (f e m)) m)) (f m m)))).\nsurgery id_l ((f b (f (f m (f (f e (f e m)) m)) (f m m)))) ((f b (f (f m (f (f e m) m)) (f m m)))).\nsurgery id_r ((f b (f (f m (f (f e m) m)) (f m m)))) ((f b (f (f m (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f m (f e m)) (f m m)))) ((f b (f (f m m) (f m m)))).\nsurgery id_r ((f b (f (f m m) (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_181: forall b: G, ((((e <+> e) <+> (e <+> (e <+> m))) <+> (e <+> m)) <+> (e <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f e (f e m))) (f e m)) (f e (f e b)))) ((f (f (f e (f e (f e m))) (f e m)) (f e (f e b)))).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e m)) (f e (f e b)))) ((f (f (f e (f e m)) (f e m)) (f e (f e b)))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f e (f e b)))) ((f (f (f e m) (f e m)) (f e (f e b)))).\nsurgery id_r ((f (f (f e m) (f e m)) (f e (f e b)))) ((f (f e (f e m)) (f e (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f e (f e b)))) ((f (f e m) (f e (f e b)))).\nsurgery id_r ((f (f e m) (f e (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_182: forall b: G, ((((e <+> e) <+> ((e <+> m) <+> (e <+> m))) <+> (e <+> b)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f (f e m) (f e m))) (f e b)) (f m m))) ((f (f (f e (f (f e m) (f e m))) (f e b)) (f m m))).\nsurgery id_r ((f (f (f e (f (f e m) (f e m))) (f e b)) (f m m))) ((f (f (f e (f e (f e m))) (f e b)) (f m m))).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e b)) (f m m))) ((f (f (f e (f e m)) (f e b)) (f m m))).\nsurgery id_l ((f (f (f e (f e m)) (f e b)) (f m m))) ((f (f (f e m) (f e b)) (f m m))).\nsurgery id_r ((f (f (f e m) (f e b)) (f m m))) ((f (f e (f e b)) (f m m))).\nsurgery id_l ((f (f e (f e b)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_183: forall b: G, ((((e <+> m) <+> ((e <+> b) <+> m)) <+> ((e <+> m) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f (f e b) m)) (f (f e m) m)) (f m m))) ((f (f (f e (f (f e b) m)) (f (f e m) m)) (f m m))).\nsurgery id_l ((f (f (f e (f (f e b) m)) (f (f e m) m)) (f m m))) ((f (f (f e (f b m)) (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f (f e (f b m)) (f (f e m) m)) (f m m))) ((f (f (f e b) (f (f e m) m)) (f m m))).\nsurgery id_l ((f (f (f e b) (f (f e m) m)) (f m m))) ((f (f b (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_184: forall b: G, (((e <+> (e <+> m)) <+> e) <+> ((e <+> (e <+> (e <+> m))) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) e) (f (f e (f e (f e m))) (f b m)))) ((f (f (f e m) e) (f (f e (f e (f e m))) (f b m)))).\nsurgery id_r ((f (f (f e m) e) (f (f e (f e (f e m))) (f b m)))) ((f (f e e) (f (f e (f e (f e m))) (f b m)))).\nsurgery id_l ((f (f e e) (f (f e (f e (f e m))) (f b m)))) ((f e (f (f e (f e (f e m))) (f b m)))).\nsurgery id_l ((f e (f (f e (f e (f e m))) (f b m)))) ((f e (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_185: forall b: G, ((((e <+> (e <+> m)) <+> (e <+> ((e <+> m) <+> m))) <+> m) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f e m)) (f e (f (f e m) m))) m) (f e b))) ((f (f (f e (f e m)) (f e (f (f e m) m))) (f e b))).\nsurgery id_l ((f (f (f e (f e m)) (f e (f (f e m) m))) (f e b))) ((f (f (f e m) (f e (f (f e m) m))) (f e b))).\nsurgery id_r ((f (f (f e m) (f e (f (f e m) m))) (f e b))) ((f (f e (f e (f (f e m) m))) (f e b))).\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f e b))) ((f (f e (f (f e m) m)) (f e b))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e b))) ((f (f e (f e m)) (f e b))).\nsurgery id_l ((f (f e (f e m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_186: forall b: G, (((e <+> m) <+> b) <+> (((m <+> m) <+> m) <+> ((m <+> m) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) b) (f (f (f m m) m) (f (f m m) (f m m))))) ((f (f e b) (f (f (f m m) m) (f (f m m) (f m m))))).\nsurgery id_l ((f (f e b) (f (f (f m m) m) (f (f m m) (f m m))))) ((f b (f (f (f m m) m) (f (f m m) (f m m))))).\nsurgery id_r ((f b (f (f (f m m) m) (f (f m m) (f m m))))) ((f b (f (f m m) (f (f m m) (f m m))))).\nsurgery id_r ((f b (f (f m m) (f (f m m) (f m m))))) ((f b (f m (f (f m m) (f m m))))).\nsurgery id_r ((f b (f m (f (f m m) (f m m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_187: forall b: G, ((e <+> (e <+> m)) <+> (((e <+> m) <+> b) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f (f e m) b) (f (f e m) (f e m))))) ((f (f e m) (f (f (f e m) b) (f (f e m) (f e m))))).\nsurgery id_r ((f (f e m) (f (f (f e m) b) (f (f e m) (f e m))))) ((f e (f (f (f e m) b) (f (f e m) (f e m))))).\nsurgery id_r ((f e (f (f (f e m) b) (f (f e m) (f e m))))) ((f e (f (f e b) (f (f e m) (f e m))))).\nsurgery id_l ((f e (f (f e b) (f (f e m) (f e m))))) ((f e (f b (f (f e m) (f e m))))).\nsurgery id_r ((f e (f b (f (f e m) (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_188: forall b: G, ((b <+> (((e <+> ((e <+> e) <+> e)) <+> e) <+> (e <+> m))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f (f (f e (f (f e e) e)) e) (f e m))) (f e m))) ((f (f b (f (f (f e (f e e)) e) (f e m))) (f e m))).\nsurgery id_l ((f (f b (f (f (f e (f e e)) e) (f e m))) (f e m))) ((f (f b (f (f (f e e) e) (f e m))) (f e m))).\nsurgery id_l ((f (f b (f (f (f e e) e) (f e m))) (f e m))) ((f (f b (f (f e e) (f e m))) (f e m))).\nsurgery id_l ((f (f b (f (f e e) (f e m))) (f e m))) ((f (f b (f e (f e m))) (f e m))).\nsurgery id_l ((f (f b (f e (f e m))) (f e m))) ((f (f b (f e m)) (f e m))).\nsurgery id_l ((f (f b (f e m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_189: forall b: G, (((((e <+> m) <+> e) <+> (e <+> e)) <+> ((e <+> m) <+> e)) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) e) (f e e)) (f (f e m) e)) (f b m))) ((f (f (f (f e e) (f e e)) (f (f e m) e)) (f b m))).\nsurgery id_l ((f (f (f (f e e) (f e e)) (f (f e m) e)) (f b m))) ((f (f (f e (f e e)) (f (f e m) e)) (f b m))).\nsurgery id_l ((f (f (f e (f e e)) (f (f e m) e)) (f b m))) ((f (f (f e e) (f (f e m) e)) (f b m))).\nsurgery id_l ((f (f (f e e) (f (f e m) e)) (f b m))) ((f (f e (f (f e m) e)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) e)) (f b m))) ((f (f e (f e e)) (f b m))).\nsurgery id_l ((f (f e (f e e)) (f b m))) ((f (f e e) (f b m))).\nsurgery id_l ((f (f e e) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_190: forall b: G, (((e <+> ((e <+> m) <+> m)) <+> (b <+> m)) <+> (m <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) m)) (f b m)) (f m (f e (f m m))))) ((f (f (f e (f e m)) (f b m)) (f m (f e (f m m))))).\nsurgery id_l ((f (f (f e (f e m)) (f b m)) (f m (f e (f m m))))) ((f (f (f e m) (f b m)) (f m (f e (f m m))))).\nsurgery id_r ((f (f (f e m) (f b m)) (f m (f e (f m m))))) ((f (f e (f b m)) (f m (f e (f m m))))).\nsurgery id_r ((f (f e (f b m)) (f m (f e (f m m))))) ((f (f e b) (f m (f e (f m m))))).\nsurgery id_l ((f (f e b) (f m (f e (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_191: forall b: G, ((e <+> m) <+> ((e <+> (e <+> e)) <+> (e <+> ((e <+> m) <+> (b <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e (f e e)) (f e (f (f e m) (f b m)))))) ((f e (f (f e (f e e)) (f e (f (f e m) (f b m)))))).\nsurgery id_l ((f e (f (f e (f e e)) (f e (f (f e m) (f b m)))))) ((f e (f (f e e) (f e (f (f e m) (f b m)))))).\nsurgery id_l ((f e (f (f e e) (f e (f (f e m) (f b m)))))) ((f e (f e (f e (f (f e m) (f b m)))))).\nsurgery id_l ((f e (f e (f e (f (f e m) (f b m)))))) ((f e (f e (f (f e m) (f b m))))).\nsurgery id_l ((f e (f e (f (f e m) (f b m))))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_192: forall b: G, ((b <+> m) <+> (((e <+> m) <+> (m <+> (e <+> m))) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f (f e m) (f m (f e m))) (f m (f m m))))) ((f b (f (f (f e m) (f m (f e m))) (f m (f m m))))).\nsurgery id_r ((f b (f (f (f e m) (f m (f e m))) (f m (f m m))))) ((f b (f (f e (f m (f e m))) (f m (f m m))))).\nsurgery id_l ((f b (f (f e (f m (f e m))) (f m (f m m))))) ((f b (f (f e (f m m)) (f m (f m m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f m (f m m))))) ((f b (f (f e m) (f m (f m m))))).\nsurgery id_r ((f b (f (f e m) (f m (f m m))))) ((f b (f e (f m (f m m))))).\nsurgery id_l ((f b (f e (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_193: forall b: G, (((e <+> b) <+> ((e <+> (e <+> m)) <+> m)) <+> ((e <+> e) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f e (f e m)) m)) (f (f e e) (f m m)))) ((f (f b (f (f e (f e m)) m)) (f (f e e) (f m m)))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f (f e e) (f m m)))) ((f (f b (f (f e m) m)) (f (f e e) (f m m)))).\nsurgery id_r ((f (f b (f (f e m) m)) (f (f e e) (f m m)))) ((f (f b (f e m)) (f (f e e) (f m m)))).\nsurgery id_l ((f (f b (f e m)) (f (f e e) (f m m)))) ((f (f b m) (f (f e e) (f m m)))).\nsurgery id_r ((f (f b m) (f (f e e) (f m m)))) ((f b (f (f e e) (f m m)))).\nsurgery id_l ((f b (f (f e e) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_194: forall b: G, ((((e <+> e) <+> m) <+> b) <+> ((e <+> (m <+> m)) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) b) (f (f e (f m m)) (f (f e m) m)))) ((f (f (f e e) b) (f (f e (f m m)) (f (f e m) m)))).\nsurgery id_l ((f (f (f e e) b) (f (f e (f m m)) (f (f e m) m)))) ((f (f e b) (f (f e (f m m)) (f (f e m) m)))).\nsurgery id_l ((f (f e b) (f (f e (f m m)) (f (f e m) m)))) ((f b (f (f e (f m m)) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f e m) m)))) ((f b (f (f e m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e m) m)))) ((f b (f e (f (f e m) m)))).\nsurgery id_l ((f b (f e (f (f e m) m)))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_195: forall b: G, (b <+> (((e <+> e) <+> m) <+> ((e <+> ((e <+> m) <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e e) m) (f (f e (f (f e m) m)) (f m m))))) ((f b (f (f e e) (f (f e (f (f e m) m)) (f m m))))).\nsurgery id_l ((f b (f (f e e) (f (f e (f (f e m) m)) (f m m))))) ((f b (f e (f (f e (f (f e m) m)) (f m m))))).\nsurgery id_l ((f b (f e (f (f e (f (f e m) m)) (f m m))))) ((f b (f (f e (f (f e m) m)) (f m m)))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) (f m m)))) ((f b (f (f e (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_196: forall b: G, ((((((e <+> e) <+> (e <+> e)) <+> e) <+> m) <+> (e <+> (e <+> e))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e e) (f e e)) e) m) (f e (f e e))) b)) ((f (f (f (f (f e e) (f e e)) e) (f e (f e e))) b)).\nsurgery id_l ((f (f (f (f (f e e) (f e e)) e) (f e (f e e))) b)) ((f (f (f (f e (f e e)) e) (f e (f e e))) b)).\nsurgery id_l ((f (f (f (f e (f e e)) e) (f e (f e e))) b)) ((f (f (f (f e e) e) (f e (f e e))) b)).\nsurgery id_l ((f (f (f (f e e) e) (f e (f e e))) b)) ((f (f (f e e) (f e (f e e))) b)).\nsurgery id_l ((f (f (f e e) (f e (f e e))) b)) ((f (f e (f e (f e e))) b)).\nsurgery id_l ((f (f e (f e (f e e))) b)) ((f (f e (f e e)) b)).\nsurgery id_l ((f (f e (f e e)) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_197: forall b: G, ((((e <+> e) <+> e) <+> (b <+> m)) <+> (((e <+> m) <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) e) (f b m)) (f (f (f e m) m) (f e m)))) ((f (f (f e e) (f b m)) (f (f (f e m) m) (f e m)))).\nsurgery id_l ((f (f (f e e) (f b m)) (f (f (f e m) m) (f e m)))) ((f (f e (f b m)) (f (f (f e m) m) (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f (f (f e m) m) (f e m)))) ((f (f e b) (f (f (f e m) m) (f e m)))).\nsurgery id_l ((f (f e b) (f (f (f e m) m) (f e m)))) ((f b (f (f (f e m) m) (f e m)))).\nsurgery id_r ((f b (f (f (f e m) m) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_198: forall b: G, (((e <+> ((b <+> m) <+> m)) <+> ((e <+> (m <+> m)) <+> (e <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f b m) m)) (f (f e (f m m)) (f e m))) m)) ((f (f e (f (f b m) m)) (f (f e (f m m)) (f e m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f (f e (f m m)) (f e m)))) ((f (f e (f b m)) (f (f e (f m m)) (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e (f m m)) (f e m)))) ((f (f e b) (f (f e (f m m)) (f e m)))).\nsurgery id_l ((f (f e b) (f (f e (f m m)) (f e m)))) ((f b (f (f e (f m m)) (f e m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_199: forall b: G, (b <+> ((((e <+> (e <+> e)) <+> e) <+> e) <+> ((e <+> m) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f (f (f e (f e e)) e) e) (f (f e m) (f m m))))) ((f b (f (f (f (f e e) e) e) (f (f e m) (f m m))))).\nsurgery id_l ((f b (f (f (f (f e e) e) e) (f (f e m) (f m m))))) ((f b (f (f (f e e) e) (f (f e m) (f m m))))).\nsurgery id_l ((f b (f (f (f e e) e) (f (f e m) (f m m))))) ((f b (f (f e e) (f (f e m) (f m m))))).\nsurgery id_l ((f b (f (f e e) (f (f e m) (f m m))))) ((f b (f e (f (f e m) (f m m))))).\nsurgery id_l ((f b (f e (f (f e m) (f m m))))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_200: forall b: G, (((e <+> b) <+> (((e <+> e) <+> m) <+> ((e <+> m) <+> (m <+> m)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) (f (f (f e e) m) (f (f e m) (f m m)))) m)) ((f (f e b) (f (f (f e e) m) (f (f e m) (f m m))))).\nsurgery id_l ((f (f e b) (f (f (f e e) m) (f (f e m) (f m m))))) ((f b (f (f (f e e) m) (f (f e m) (f m m))))).\nsurgery id_r ((f b (f (f (f e e) m) (f (f e m) (f m m))))) ((f b (f (f e e) (f (f e m) (f m m))))).\nsurgery id_l ((f b (f (f e e) (f (f e m) (f m m))))) ((f b (f e (f (f e m) (f m m))))).\nsurgery id_l ((f b (f e (f (f e m) (f m m))))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_201: forall b: G, (((((e <+> m) <+> (e <+> (e <+> m))) <+> (e <+> (e <+> e))) <+> b) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) (f e (f e m))) (f e (f e e))) b) m)) ((f (f (f (f e m) (f e (f e m))) (f e (f e e))) b)).\nsurgery id_r ((f (f (f (f e m) (f e (f e m))) (f e (f e e))) b)) ((f (f (f e (f e (f e m))) (f e (f e e))) b)).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e (f e e))) b)) ((f (f (f e (f e m)) (f e (f e e))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f e (f e e))) b)) ((f (f (f e m) (f e (f e e))) b)).\nsurgery id_r ((f (f (f e m) (f e (f e e))) b)) ((f (f e (f e (f e e))) b)).\nsurgery id_l ((f (f e (f e (f e e))) b)) ((f (f e (f e e)) b)).\nsurgery id_l ((f (f e (f e e)) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_202: forall b: G, ((b <+> (m <+> (m <+> (m <+> m)))) <+> (((e <+> m) <+> e) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m (f m (f m m)))) (f (f (f e m) e) (f m m)))) ((f (f b (f m (f m m))) (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f (f b (f m (f m m))) (f (f (f e m) e) (f m m)))) ((f (f b (f m m)) (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e m) e) (f m m)))) ((f (f b m) (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f (f b m) (f (f (f e m) e) (f m m)))) ((f b (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) e) (f m m)))) ((f b (f (f e e) (f m m)))).\nsurgery id_l ((f b (f (f e e) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_203: forall b: G, ((((e <+> m) <+> e) <+> (m <+> (e <+> m))) <+> (((e <+> e) <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f m (f e m))) (f (f (f e e) b) m))) ((f (f (f e e) (f m (f e m))) (f (f (f e e) b) m))).\nsurgery id_l ((f (f (f e e) (f m (f e m))) (f (f (f e e) b) m))) ((f (f e (f m (f e m))) (f (f (f e e) b) m))).\nsurgery id_l ((f (f e (f m (f e m))) (f (f (f e e) b) m))) ((f (f e (f m m)) (f (f (f e e) b) m))).\nsurgery id_r ((f (f e (f m m)) (f (f (f e e) b) m))) ((f (f e m) (f (f (f e e) b) m))).\nsurgery id_r ((f (f e m) (f (f (f e e) b) m))) ((f e (f (f (f e e) b) m))).\nsurgery id_l ((f e (f (f (f e e) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_204: forall b: G, (((e <+> (e <+> (b <+> m))) <+> ((e <+> m) <+> (e <+> (m <+> m)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f e (f b m))) (f (f e m) (f e (f m m)))) m)) ((f (f e (f e (f b m))) (f (f e m) (f e (f m m))))).\nsurgery id_l ((f (f e (f e (f b m))) (f (f e m) (f e (f m m))))) ((f (f e (f b m)) (f (f e m) (f e (f m m))))).\nsurgery id_r ((f (f e (f b m)) (f (f e m) (f e (f m m))))) ((f (f e b) (f (f e m) (f e (f m m))))).\nsurgery id_l ((f (f e b) (f (f e m) (f e (f m m))))) ((f b (f (f e m) (f e (f m m))))).\nsurgery id_r ((f b (f (f e m) (f e (f m m))))) ((f b (f e (f e (f m m))))).\nsurgery id_l ((f b (f e (f e (f m m))))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_205: forall b: G, ((((e <+> e) <+> e) <+> (m <+> (e <+> (m <+> (e <+> m))))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) e) (f m (f e (f m (f e m))))) (f b m))) ((f (f (f e e) (f m (f e (f m (f e m))))) (f b m))).\nsurgery id_l ((f (f (f e e) (f m (f e (f m (f e m))))) (f b m))) ((f (f e (f m (f e (f m (f e m))))) (f b m))).\nsurgery id_l ((f (f e (f m (f e (f m (f e m))))) (f b m))) ((f (f e (f m (f m (f e m)))) (f b m))).\nsurgery id_l ((f (f e (f m (f m (f e m)))) (f b m))) ((f (f e (f m (f m m))) (f b m))).\nsurgery id_r ((f (f e (f m (f m m))) (f b m))) ((f (f e (f m m)) (f b m))).\nsurgery id_r ((f (f e (f m m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_206: forall b: G, (((e <+> (b <+> ((e <+> (e <+> e)) <+> (e <+> m)))) <+> (e <+> m)) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f b (f (f e (f e e)) (f e m)))) (f e m)) m)) ((f (f e (f b (f (f e (f e e)) (f e m)))) (f e m))).\nsurgery id_l ((f (f e (f b (f (f e (f e e)) (f e m)))) (f e m))) ((f (f e (f b (f (f e e) (f e m)))) (f e m))).\nsurgery id_l ((f (f e (f b (f (f e e) (f e m)))) (f e m))) ((f (f e (f b (f e (f e m)))) (f e m))).\nsurgery id_l ((f (f e (f b (f e (f e m)))) (f e m))) ((f (f e (f b (f e m))) (f e m))).\nsurgery id_l ((f (f e (f b (f e m))) (f e m))) ((f (f e (f b m)) (f e m))).\nsurgery id_r ((f (f e (f b m)) (f e m))) ((f (f e b) (f e m))).\nsurgery id_l ((f (f e b) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_207: forall b: G, (((e <+> b) <+> (m <+> (m <+> m))) <+> (((e <+> m) <+> (e <+> e)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f m (f m m))) (f (f (f e m) (f e e)) m))) ((f (f b (f m (f m m))) (f (f (f e m) (f e e)) m))).\nsurgery id_r ((f (f b (f m (f m m))) (f (f (f e m) (f e e)) m))) ((f (f b (f m m)) (f (f (f e m) (f e e)) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e m) (f e e)) m))) ((f (f b m) (f (f (f e m) (f e e)) m))).\nsurgery id_r ((f (f b m) (f (f (f e m) (f e e)) m))) ((f b (f (f (f e m) (f e e)) m))).\nsurgery id_r ((f b (f (f (f e m) (f e e)) m))) ((f b (f (f e (f e e)) m))).\nsurgery id_l ((f b (f (f e (f e e)) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_208: forall b: G, ((e <+> e) <+> (((e <+> (e <+> (e <+> m))) <+> m) <+> ((e <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f e (f e (f e m))) m) (f (f e b) m)))) ((f e (f (f (f e (f e (f e m))) m) (f (f e b) m)))).\nsurgery id_r ((f e (f (f (f e (f e (f e m))) m) (f (f e b) m)))) ((f e (f (f e (f e (f e m))) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e (f e (f e m))) (f (f e b) m)))) ((f e (f (f e (f e m)) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f (f e b) m)))) ((f e (f (f e m) (f (f e b) m)))).\nsurgery id_r ((f e (f (f e m) (f (f e b) m)))) ((f e (f e (f (f e b) m)))).\nsurgery id_l ((f e (f e (f (f e b) m)))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_209: forall b: G, ((e <+> (m <+> m)) <+> (e <+> (e <+> (((e <+> m) <+> b) <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f m m)) (f e (f e (f (f (f e m) b) (f e m)))))) ((f (f e m) (f e (f e (f (f (f e m) b) (f e m)))))).\nsurgery id_r ((f (f e m) (f e (f e (f (f (f e m) b) (f e m)))))) ((f e (f e (f e (f (f (f e m) b) (f e m)))))).\nsurgery id_l ((f e (f e (f e (f (f (f e m) b) (f e m)))))) ((f e (f e (f (f (f e m) b) (f e m))))).\nsurgery id_l ((f e (f e (f (f (f e m) b) (f e m))))) ((f e (f (f (f e m) b) (f e m)))).\nsurgery id_r ((f e (f (f (f e m) b) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_210: forall b: G, ((((e <+> b) <+> (e <+> m)) <+> (((e <+> m) <+> e) <+> (m <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e b) (f e m)) (f (f (f e m) e) (f m m))) m)) ((f (f (f e b) (f e m)) (f (f (f e m) e) (f m m)))).\nsurgery id_l ((f (f (f e b) (f e m)) (f (f (f e m) e) (f m m)))) ((f (f b (f e m)) (f (f (f e m) e) (f m m)))).\nsurgery id_l ((f (f b (f e m)) (f (f (f e m) e) (f m m)))) ((f (f b m) (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f (f b m) (f (f (f e m) e) (f m m)))) ((f b (f (f (f e m) e) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) e) (f m m)))) ((f b (f (f e e) (f m m)))).\nsurgery id_l ((f b (f (f e e) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_211: forall b: G, (((e <+> m) <+> (e <+> e)) <+> (((e <+> ((e <+> m) <+> m)) <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e e)) (f (f (f e (f (f e m) m)) b) m))) ((f (f e (f e e)) (f (f (f e (f (f e m) m)) b) m))).\nsurgery id_l ((f (f e (f e e)) (f (f (f e (f (f e m) m)) b) m))) ((f (f e e) (f (f (f e (f (f e m) m)) b) m))).\nsurgery id_l ((f (f e e) (f (f (f e (f (f e m) m)) b) m))) ((f e (f (f (f e (f (f e m) m)) b) m))).\nsurgery id_r ((f e (f (f (f e (f (f e m) m)) b) m))) ((f e (f (f (f e (f e m)) b) m))).\nsurgery id_l ((f e (f (f (f e (f e m)) b) m))) ((f e (f (f (f e m) b) m))).\nsurgery id_r ((f e (f (f (f e m) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_212: forall b: G, ((e <+> (e <+> (e <+> m))) <+> (((e <+> m) <+> m) <+> ((b <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f e m))) (f (f (f e m) m) (f (f b m) m)))) ((f (f e (f e m)) (f (f (f e m) m) (f (f b m) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e m) m) (f (f b m) m)))) ((f (f e m) (f (f (f e m) m) (f (f b m) m)))).\nsurgery id_r ((f (f e m) (f (f (f e m) m) (f (f b m) m)))) ((f e (f (f (f e m) m) (f (f b m) m)))).\nsurgery id_r ((f e (f (f (f e m) m) (f (f b m) m)))) ((f e (f (f e m) (f (f b m) m)))).\nsurgery id_r ((f e (f (f e m) (f (f b m) m)))) ((f e (f e (f (f b m) m)))).\nsurgery id_l ((f e (f e (f (f b m) m)))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_213: forall b: G, ((e <+> (e <+> (e <+> m))) <+> (b <+> ((e <+> (e <+> m)) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f e m))) (f b (f (f e (f e m)) (f e m))))) ((f (f e (f e m)) (f b (f (f e (f e m)) (f e m))))).\nsurgery id_l ((f (f e (f e m)) (f b (f (f e (f e m)) (f e m))))) ((f (f e m) (f b (f (f e (f e m)) (f e m))))).\nsurgery id_r ((f (f e m) (f b (f (f e (f e m)) (f e m))))) ((f e (f b (f (f e (f e m)) (f e m))))).\nsurgery id_l ((f e (f b (f (f e (f e m)) (f e m))))) ((f e (f b (f (f e m) (f e m))))).\nsurgery id_r ((f e (f b (f (f e m) (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_214: forall b: G, ((e <+> m) <+> (((e <+> (e <+> m)) <+> (e <+> e)) <+> ((e <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e (f e m)) (f e e)) (f (f e b) m)))) ((f e (f (f (f e (f e m)) (f e e)) (f (f e b) m)))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f e e)) (f (f e b) m)))) ((f e (f (f (f e m) (f e e)) (f (f e b) m)))).\nsurgery id_r ((f e (f (f (f e m) (f e e)) (f (f e b) m)))) ((f e (f (f e (f e e)) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f e b) m)))) ((f e (f (f e e) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e e) (f (f e b) m)))) ((f e (f e (f (f e b) m)))).\nsurgery id_l ((f e (f e (f (f e b) m)))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_215: forall b: G, ((((e <+> m) <+> m) <+> (e <+> e)) <+> ((e <+> e) <+> (e <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) m) (f e e)) (f (f e e) (f e (f e b))))) ((f (f (f e m) (f e e)) (f (f e e) (f e (f e b))))).\nsurgery id_r ((f (f (f e m) (f e e)) (f (f e e) (f e (f e b))))) ((f (f e (f e e)) (f (f e e) (f e (f e b))))).\nsurgery id_l ((f (f e (f e e)) (f (f e e) (f e (f e b))))) ((f (f e e) (f (f e e) (f e (f e b))))).\nsurgery id_l ((f (f e e) (f (f e e) (f e (f e b))))) ((f e (f (f e e) (f e (f e b))))).\nsurgery id_l ((f e (f (f e e) (f e (f e b))))) ((f e (f e (f e (f e b))))).\nsurgery id_l ((f e (f e (f e (f e b))))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_216: forall b: G, (b <+> ((((e <+> e) <+> (m <+> m)) <+> m) <+> (m <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f (f e e) (f m m)) m) (f m (f (f e m) m))))) ((f b (f (f (f e e) (f m m)) (f m (f (f e m) m))))).\nsurgery id_l ((f b (f (f (f e e) (f m m)) (f m (f (f e m) m))))) ((f b (f (f e (f m m)) (f m (f (f e m) m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f m (f (f e m) m))))) ((f b (f (f e m) (f m (f (f e m) m))))).\nsurgery id_r ((f b (f (f e m) (f m (f (f e m) m))))) ((f b (f e (f m (f (f e m) m))))).\nsurgery id_l ((f b (f e (f m (f (f e m) m))))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_217: forall b: G, ((e <+> m) <+> (b <+> ((e <+> (e <+> (e <+> e))) <+> (m <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f b (f (f e (f e (f e e))) (f m (f e m)))))) ((f e (f b (f (f e (f e (f e e))) (f m (f e m)))))).\nsurgery id_l ((f e (f b (f (f e (f e (f e e))) (f m (f e m)))))) ((f e (f b (f (f e (f e e)) (f m (f e m)))))).\nsurgery id_l ((f e (f b (f (f e (f e e)) (f m (f e m)))))) ((f e (f b (f (f e e) (f m (f e m)))))).\nsurgery id_l ((f e (f b (f (f e e) (f m (f e m)))))) ((f e (f b (f e (f m (f e m)))))).\nsurgery id_l ((f e (f b (f e (f m (f e m)))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_218: forall b: G, ((((e <+> e) <+> m) <+> (e <+> ((e <+> m) <+> (m <+> m)))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f e (f (f e m) (f m m)))) (f b m))) ((f (f (f e e) (f e (f (f e m) (f m m)))) (f b m))).\nsurgery id_l ((f (f (f e e) (f e (f (f e m) (f m m)))) (f b m))) ((f (f e (f e (f (f e m) (f m m)))) (f b m))).\nsurgery id_l ((f (f e (f e (f (f e m) (f m m)))) (f b m))) ((f (f e (f (f e m) (f m m))) (f b m))).\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f b m))) ((f (f e (f e (f m m))) (f b m))).\nsurgery id_l ((f (f e (f e (f m m))) (f b m))) ((f (f e (f m m)) (f b m))).\nsurgery id_r ((f (f e (f m m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_219: forall b: G, (((b <+> m) <+> m) <+> ((e <+> m) <+> ((m <+> m) <+> (e <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) m) (f (f e m) (f (f m m) (f e (f e m)))))) ((f (f b m) (f (f e m) (f (f m m) (f e (f e m)))))).\nsurgery id_r ((f (f b m) (f (f e m) (f (f m m) (f e (f e m)))))) ((f b (f (f e m) (f (f m m) (f e (f e m)))))).\nsurgery id_r ((f b (f (f e m) (f (f m m) (f e (f e m)))))) ((f b (f e (f (f m m) (f e (f e m)))))).\nsurgery id_l ((f b (f e (f (f m m) (f e (f e m)))))) ((f b (f (f m m) (f e (f e m))))).\nsurgery id_r ((f b (f (f m m) (f e (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_220: forall b: G, ((((e <+> e) <+> m) <+> ((b <+> m) <+> m)) <+> ((e <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f (f b m) m)) (f (f e m) (f m m)))) ((f (f (f e e) (f (f b m) m)) (f (f e m) (f m m)))).\nsurgery id_l ((f (f (f e e) (f (f b m) m)) (f (f e m) (f m m)))) ((f (f e (f (f b m) m)) (f (f e m) (f m m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f (f e m) (f m m)))) ((f (f e (f b m)) (f (f e m) (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e m) (f m m)))) ((f (f e b) (f (f e m) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_221: forall b: G, ((((e <+> (e <+> e)) <+> e) <+> ((e <+> m) <+> m)) <+> ((b <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e e)) e) (f (f e m) m)) (f (f b m) m))) ((f (f (f (f e e) e) (f (f e m) m)) (f (f b m) m))).\nsurgery id_l ((f (f (f (f e e) e) (f (f e m) m)) (f (f b m) m))) ((f (f (f e e) (f (f e m) m)) (f (f b m) m))).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f (f b m) m))) ((f (f e (f (f e m) m)) (f (f b m) m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f b m) m))) ((f (f e (f e m)) (f (f b m) m))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) m))) ((f (f e m) (f (f b m) m))).\nsurgery id_r ((f (f e m) (f (f b m) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_222: forall b: G, (((((e <+> e) <+> e) <+> (m <+> (((e <+> m) <+> e) <+> m))) <+> m) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) e) (f m (f (f (f e m) e) m))) m) b)) ((f (f (f (f e e) e) (f m (f (f (f e m) e) m))) b)).\nsurgery id_l ((f (f (f (f e e) e) (f m (f (f (f e m) e) m))) b)) ((f (f (f e e) (f m (f (f (f e m) e) m))) b)).\nsurgery id_l ((f (f (f e e) (f m (f (f (f e m) e) m))) b)) ((f (f e (f m (f (f (f e m) e) m))) b)).\nsurgery id_r ((f (f e (f m (f (f (f e m) e) m))) b)) ((f (f e (f m (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f m (f (f e e) m))) b)) ((f (f e (f m (f e m))) b)).\nsurgery id_l ((f (f e (f m (f e m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_223: forall b: G, ((b <+> m) <+> ((e <+> (e <+> m)) <+> (m <+> ((e <+> e) <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f e (f e m)) (f m (f (f e e) (f e m)))))) ((f b (f (f e (f e m)) (f m (f (f e e) (f e m)))))).\nsurgery id_l ((f b (f (f e (f e m)) (f m (f (f e e) (f e m)))))) ((f b (f (f e m) (f m (f (f e e) (f e m)))))).\nsurgery id_r ((f b (f (f e m) (f m (f (f e e) (f e m)))))) ((f b (f e (f m (f (f e e) (f e m)))))).\nsurgery id_l ((f b (f e (f m (f (f e e) (f e m)))))) ((f b (f m (f (f e e) (f e m))))).\nsurgery id_l ((f b (f m (f (f e e) (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_224: forall b: G, ((((b <+> m) <+> ((m <+> m) <+> (e <+> m))) <+> (e <+> (m <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f b m) (f (f m m) (f e m))) (f e (f m m))) m)) ((f (f (f b m) (f (f m m) (f e m))) (f e (f m m)))).\nsurgery id_r ((f (f (f b m) (f (f m m) (f e m))) (f e (f m m)))) ((f (f b (f (f m m) (f e m))) (f e (f m m)))).\nsurgery id_r ((f (f b (f (f m m) (f e m))) (f e (f m m)))) ((f (f b (f m (f e m))) (f e (f m m)))).\nsurgery id_l ((f (f b (f m (f e m))) (f e (f m m)))) ((f (f b (f m m)) (f e (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f e (f m m)))) ((f (f b m) (f e (f m m)))).\nsurgery id_r ((f (f b m) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_225: forall b: G, ((((e <+> (((e <+> m) <+> e) <+> (e <+> e))) <+> e) <+> (e <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f (f (f e m) e) (f e e))) e) (f e m)) b)) ((f (f (f (f e (f (f e e) (f e e))) e) (f e m)) b)).\nsurgery id_l ((f (f (f (f e (f (f e e) (f e e))) e) (f e m)) b)) ((f (f (f (f e (f e (f e e))) e) (f e m)) b)).\nsurgery id_l ((f (f (f (f e (f e (f e e))) e) (f e m)) b)) ((f (f (f (f e (f e e)) e) (f e m)) b)).\nsurgery id_l ((f (f (f (f e (f e e)) e) (f e m)) b)) ((f (f (f (f e e) e) (f e m)) b)).\nsurgery id_l ((f (f (f (f e e) e) (f e m)) b)) ((f (f (f e e) (f e m)) b)).\nsurgery id_l ((f (f (f e e) (f e m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_226: forall b: G, (((e <+> (e <+> b)) <+> ((e <+> m) <+> m)) <+> (m <+> (m <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e b)) (f (f e m) m)) (f m (f m (f e m))))) ((f (f (f e b) (f (f e m) m)) (f m (f m (f e m))))).\nsurgery id_l ((f (f (f e b) (f (f e m) m)) (f m (f m (f e m))))) ((f (f b (f (f e m) m)) (f m (f m (f e m))))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m (f m (f e m))))) ((f (f b (f e m)) (f m (f m (f e m))))).\nsurgery id_l ((f (f b (f e m)) (f m (f m (f e m))))) ((f (f b m) (f m (f m (f e m))))).\nsurgery id_r ((f (f b m) (f m (f m (f e m))))) ((f b (f m (f m (f e m))))).\nsurgery id_l ((f b (f m (f m (f e m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_227: forall b: G, (((e <+> (e <+> m)) <+> ((e <+> m) <+> m)) <+> (e <+> ((e <+> m) <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) m)) (f e (f (f e m) b)))) ((f (f (f e m) (f (f e m) m)) (f e (f (f e m) b)))).\nsurgery id_r ((f (f (f e m) (f (f e m) m)) (f e (f (f e m) b)))) ((f (f e (f (f e m) m)) (f e (f (f e m) b)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f (f e m) b)))) ((f (f e (f e m)) (f e (f (f e m) b)))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f e m) b)))) ((f (f e m) (f e (f (f e m) b)))).\nsurgery id_r ((f (f e m) (f e (f (f e m) b)))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_228: forall b: G, (((e <+> m) <+> (e <+> e)) <+> ((e <+> b) <+> ((m <+> m) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e e)) (f (f e b) (f (f m m) (f m m))))) ((f (f e (f e e)) (f (f e b) (f (f m m) (f m m))))).\nsurgery id_l ((f (f e (f e e)) (f (f e b) (f (f m m) (f m m))))) ((f (f e e) (f (f e b) (f (f m m) (f m m))))).\nsurgery id_l ((f (f e e) (f (f e b) (f (f m m) (f m m))))) ((f e (f (f e b) (f (f m m) (f m m))))).\nsurgery id_l ((f e (f (f e b) (f (f m m) (f m m))))) ((f e (f b (f (f m m) (f m m))))).\nsurgery id_r ((f e (f b (f (f m m) (f m m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_229: forall b: G, ((e <+> ((m <+> (e <+> m)) <+> (m <+> m))) <+> (b <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f m (f e m)) (f m m))) (f b (f (f e m) m)))) ((f (f e (f (f m m) (f m m))) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e (f (f m m) (f m m))) (f b (f (f e m) m)))) ((f (f e (f m (f m m))) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e (f m (f m m))) (f b (f (f e m) m)))) ((f (f e (f m m)) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f e m) m)))) ((f (f e m) (f b (f (f e m) m)))).\nsurgery id_r ((f (f e m) (f b (f (f e m) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_230: forall b: G, (((e <+> m) <+> m) <+> ((e <+> (e <+> m)) <+> ((e <+> m) <+> (b <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) m) (f (f e (f e m)) (f (f e m) (f b m))))) ((f (f e m) (f (f e (f e m)) (f (f e m) (f b m))))).\nsurgery id_r ((f (f e m) (f (f e (f e m)) (f (f e m) (f b m))))) ((f e (f (f e (f e m)) (f (f e m) (f b m))))).\nsurgery id_l ((f e (f (f e (f e m)) (f (f e m) (f b m))))) ((f e (f (f e m) (f (f e m) (f b m))))).\nsurgery id_r ((f e (f (f e m) (f (f e m) (f b m))))) ((f e (f e (f (f e m) (f b m))))).\nsurgery id_l ((f e (f e (f (f e m) (f b m))))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_231: forall b: G, ((e <+> m) <+> (e <+> (((e <+> m) <+> (e <+> m)) <+> (b <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f e (f (f (f e m) (f e m)) (f b (f m m)))))) ((f e (f e (f (f (f e m) (f e m)) (f b (f m m)))))).\nsurgery id_l ((f e (f e (f (f (f e m) (f e m)) (f b (f m m)))))) ((f e (f (f (f e m) (f e m)) (f b (f m m))))).\nsurgery id_r ((f e (f (f (f e m) (f e m)) (f b (f m m))))) ((f e (f (f e (f e m)) (f b (f m m))))).\nsurgery id_l ((f e (f (f e (f e m)) (f b (f m m))))) ((f e (f (f e m) (f b (f m m))))).\nsurgery id_r ((f e (f (f e m) (f b (f m m))))) ((f e (f e (f b (f m m))))).\nsurgery id_l ((f e (f e (f b (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_232: forall b: G, (((e <+> b) <+> m) <+> (((e <+> m) <+> m) <+> ((e <+> m) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) m) (f (f (f e m) m) (f (f e m) (f m m))))) ((f (f e b) (f (f (f e m) m) (f (f e m) (f m m))))).\nsurgery id_l ((f (f e b) (f (f (f e m) m) (f (f e m) (f m m))))) ((f b (f (f (f e m) m) (f (f e m) (f m m))))).\nsurgery id_r ((f b (f (f (f e m) m) (f (f e m) (f m m))))) ((f b (f (f e m) (f (f e m) (f m m))))).\nsurgery id_r ((f b (f (f e m) (f (f e m) (f m m))))) ((f b (f e (f (f e m) (f m m))))).\nsurgery id_l ((f b (f e (f (f e m) (f m m))))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_233: forall b: G, (((e <+> (((e <+> e) <+> m) <+> (e <+> b))) <+> m) <+> (m <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f (f e e) m) (f e b))) m) (f m (f e m)))) ((f (f e (f (f (f e e) m) (f e b))) (f m (f e m)))).\nsurgery id_r ((f (f e (f (f (f e e) m) (f e b))) (f m (f e m)))) ((f (f e (f (f e e) (f e b))) (f m (f e m)))).\nsurgery id_l ((f (f e (f (f e e) (f e b))) (f m (f e m)))) ((f (f e (f e (f e b))) (f m (f e m)))).\nsurgery id_l ((f (f e (f e (f e b))) (f m (f e m)))) ((f (f e (f e b)) (f m (f e m)))).\nsurgery id_l ((f (f e (f e b)) (f m (f e m)))) ((f (f e b) (f m (f e m)))).\nsurgery id_l ((f (f e b) (f m (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_234: forall b: G, ((b <+> (e <+> m)) <+> (((e <+> m) <+> ((e <+> m) <+> m)) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e m)) (f (f (f e m) (f (f e m) m)) (f e m)))) ((f (f b m) (f (f (f e m) (f (f e m) m)) (f e m)))).\nsurgery id_r ((f (f b m) (f (f (f e m) (f (f e m) m)) (f e m)))) ((f b (f (f (f e m) (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f (f e m) (f (f e m) m)) (f e m)))) ((f b (f (f e (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) (f e m)))) ((f b (f (f e (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_235: forall b: G, ((b <+> m) <+> ((e <+> m) <+> (e <+> (((e <+> m) <+> m) <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f e m) (f e (f (f (f e m) m) (f m m)))))) ((f b (f (f e m) (f e (f (f (f e m) m) (f m m)))))).\nsurgery id_r ((f b (f (f e m) (f e (f (f (f e m) m) (f m m)))))) ((f b (f e (f e (f (f (f e m) m) (f m m)))))).\nsurgery id_l ((f b (f e (f e (f (f (f e m) m) (f m m)))))) ((f b (f e (f (f (f e m) m) (f m m))))).\nsurgery id_l ((f b (f e (f (f (f e m) m) (f m m))))) ((f b (f (f (f e m) m) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) m) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_236: forall b: G, (((((e <+> m) <+> (e <+> (e <+> e))) <+> (e <+> m)) <+> e) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) (f e (f e e))) (f e m)) e) (f b m))) ((f (f (f (f e (f e (f e e))) (f e m)) e) (f b m))).\nsurgery id_l ((f (f (f (f e (f e (f e e))) (f e m)) e) (f b m))) ((f (f (f (f e (f e e)) (f e m)) e) (f b m))).\nsurgery id_l ((f (f (f (f e (f e e)) (f e m)) e) (f b m))) ((f (f (f (f e e) (f e m)) e) (f b m))).\nsurgery id_l ((f (f (f (f e e) (f e m)) e) (f b m))) ((f (f (f e (f e m)) e) (f b m))).\nsurgery id_l ((f (f (f e (f e m)) e) (f b m))) ((f (f (f e m) e) (f b m))).\nsurgery id_r ((f (f (f e m) e) (f b m))) ((f (f e e) (f b m))).\nsurgery id_l ((f (f e e) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_237: forall b: G, (e <+> ((e <+> m) <+> (((e <+> e) <+> (e <+> (m <+> m))) <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e m) (f (f (f e e) (f e (f m m))) (f e b))))) ((f e (f e (f (f (f e e) (f e (f m m))) (f e b))))).\nsurgery id_l ((f e (f e (f (f (f e e) (f e (f m m))) (f e b))))) ((f e (f (f (f e e) (f e (f m m))) (f e b)))).\nsurgery id_l ((f e (f (f (f e e) (f e (f m m))) (f e b)))) ((f e (f (f e (f e (f m m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f e (f m m))) (f e b)))) ((f e (f (f e (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f m m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_238: forall b: G, ((e <+> ((e <+> e) <+> (((e <+> m) <+> m) <+> m))) <+> (b <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) (f (f (f e m) m) m))) (f b (f e m)))) ((f (f e (f e (f (f (f e m) m) m))) (f b (f e m)))).\nsurgery id_l ((f (f e (f e (f (f (f e m) m) m))) (f b (f e m)))) ((f (f e (f (f (f e m) m) m)) (f b (f e m)))).\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f b (f e m)))) ((f (f e (f (f e m) m)) (f b (f e m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b (f e m)))) ((f (f e (f e m)) (f b (f e m)))).\nsurgery id_l ((f (f e (f e m)) (f b (f e m)))) ((f (f e m) (f b (f e m)))).\nsurgery id_r ((f (f e m) (f b (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_239: forall b: G, (((e <+> (((e <+> m) <+> e) <+> m)) <+> (((e <+> e) <+> m) <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f (f e m) e) m)) (f (f (f e e) m) m)) b)) ((f (f (f e (f (f e e) m)) (f (f (f e e) m) m)) b)).\nsurgery id_l ((f (f (f e (f (f e e) m)) (f (f (f e e) m) m)) b)) ((f (f (f e (f e m)) (f (f (f e e) m) m)) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f (f e e) m) m)) b)) ((f (f (f e m) (f (f (f e e) m) m)) b)).\nsurgery id_r ((f (f (f e m) (f (f (f e e) m) m)) b)) ((f (f e (f (f (f e e) m) m)) b)).\nsurgery id_r ((f (f e (f (f (f e e) m) m)) b)) ((f (f e (f (f e e) m)) b)).\nsurgery id_l ((f (f e (f (f e e) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_240: forall b: G, ((e <+> e) <+> ((((e <+> e) <+> (e <+> m)) <+> (e <+> e)) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f (f e e) (f e m)) (f e e)) (f e b)))) ((f e (f (f (f (f e e) (f e m)) (f e e)) (f e b)))).\nsurgery id_l ((f e (f (f (f (f e e) (f e m)) (f e e)) (f e b)))) ((f e (f (f (f e (f e m)) (f e e)) (f e b)))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f e e)) (f e b)))) ((f e (f (f (f e m) (f e e)) (f e b)))).\nsurgery id_r ((f e (f (f (f e m) (f e e)) (f e b)))) ((f e (f (f e (f e e)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e e)) (f e b)))) ((f e (f (f e e) (f e b)))).\nsurgery id_l ((f e (f (f e e) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_241: forall b: G, ((b <+> ((m <+> m) <+> (e <+> m))) <+> ((m <+> m) <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f m m) (f e m))) (f (f m m) (f e (f m m))))) ((f (f b (f m (f e m))) (f (f m m) (f e (f m m))))).\nsurgery id_l ((f (f b (f m (f e m))) (f (f m m) (f e (f m m))))) ((f (f b (f m m)) (f (f m m) (f e (f m m))))).\nsurgery id_r ((f (f b (f m m)) (f (f m m) (f e (f m m))))) ((f (f b m) (f (f m m) (f e (f m m))))).\nsurgery id_r ((f (f b m) (f (f m m) (f e (f m m))))) ((f b (f (f m m) (f e (f m m))))).\nsurgery id_r ((f b (f (f m m) (f e (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_242: forall b: G, (((e <+> b) <+> m) <+> (m <+> ((m <+> (m <+> (e <+> m))) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) m) (f m (f (f m (f m (f e m))) (f m m))))) ((f (f e b) (f m (f (f m (f m (f e m))) (f m m))))).\nsurgery id_l ((f (f e b) (f m (f (f m (f m (f e m))) (f m m))))) ((f b (f m (f (f m (f m (f e m))) (f m m))))).\nsurgery id_l ((f b (f m (f (f m (f m (f e m))) (f m m))))) ((f b (f m (f (f m (f m m)) (f m m))))).\nsurgery id_r ((f b (f m (f (f m (f m m)) (f m m))))) ((f b (f m (f (f m m) (f m m))))).\nsurgery id_r ((f b (f m (f (f m m) (f m m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_243: forall b: G, (((((e <+> e) <+> (e <+> m)) <+> ((e <+> (e <+> m)) <+> m)) <+> e) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f (f e e) (f e m)) (f (f e (f e m)) m)) e) b)) ((f (f (f (f e (f e m)) (f (f e (f e m)) m)) e) b)).\nsurgery id_l ((f (f (f (f e (f e m)) (f (f e (f e m)) m)) e) b)) ((f (f (f (f e m) (f (f e (f e m)) m)) e) b)).\nsurgery id_r ((f (f (f (f e m) (f (f e (f e m)) m)) e) b)) ((f (f (f e (f (f e (f e m)) m)) e) b)).\nsurgery id_l ((f (f (f e (f (f e (f e m)) m)) e) b)) ((f (f (f e (f (f e m) m)) e) b)).\nsurgery id_r ((f (f (f e (f (f e m) m)) e) b)) ((f (f (f e (f e m)) e) b)).\nsurgery id_l ((f (f (f e (f e m)) e) b)) ((f (f (f e m) e) b)).\nsurgery id_r ((f (f (f e m) e) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_244: forall b: G, (((e <+> (m <+> m)) <+> e) <+> (((e <+> (e <+> (e <+> m))) <+> e) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f m m)) e) (f (f (f e (f e (f e m))) e) b))) ((f (f (f e m) e) (f (f (f e (f e (f e m))) e) b))).\nsurgery id_r ((f (f (f e m) e) (f (f (f e (f e (f e m))) e) b))) ((f (f e e) (f (f (f e (f e (f e m))) e) b))).\nsurgery id_l ((f (f e e) (f (f (f e (f e (f e m))) e) b))) ((f e (f (f (f e (f e (f e m))) e) b))).\nsurgery id_l ((f e (f (f (f e (f e (f e m))) e) b))) ((f e (f (f (f e (f e m)) e) b))).\nsurgery id_l ((f e (f (f (f e (f e m)) e) b))) ((f e (f (f (f e m) e) b))).\nsurgery id_r ((f e (f (f (f e m) e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_245: forall b: G, ((b <+> ((e <+> m) <+> m)) <+> (((e <+> e) <+> (e <+> (m <+> m))) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e m) m)) (f (f (f e e) (f e (f m m))) m))) ((f (f b (f e m)) (f (f (f e e) (f e (f m m))) m))).\nsurgery id_l ((f (f b (f e m)) (f (f (f e e) (f e (f m m))) m))) ((f (f b m) (f (f (f e e) (f e (f m m))) m))).\nsurgery id_r ((f (f b m) (f (f (f e e) (f e (f m m))) m))) ((f b (f (f (f e e) (f e (f m m))) m))).\nsurgery id_l ((f b (f (f (f e e) (f e (f m m))) m))) ((f b (f (f e (f e (f m m))) m))).\nsurgery id_l ((f b (f (f e (f e (f m m))) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_246: forall b: G, ((b <+> ((((e <+> m) <+> m) <+> ((e <+> e) <+> m)) <+> (e <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f (f (f e m) m) (f (f e e) m)) (f e m))) m)) ((f b (f (f (f (f e m) m) (f (f e e) m)) (f e m)))).\nsurgery id_r ((f b (f (f (f (f e m) m) (f (f e e) m)) (f e m)))) ((f b (f (f (f e m) (f (f e e) m)) (f e m)))).\nsurgery id_r ((f b (f (f (f e m) (f (f e e) m)) (f e m)))) ((f b (f (f e (f (f e e) m)) (f e m)))).\nsurgery id_l ((f b (f (f e (f (f e e) m)) (f e m)))) ((f b (f (f e (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_247: forall b: G, (((e <+> (e <+> e)) <+> (m <+> m)) <+> ((b <+> m) <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e e)) (f m m)) (f (f b m) (f e (f m m))))) ((f (f (f e e) (f m m)) (f (f b m) (f e (f m m))))).\nsurgery id_l ((f (f (f e e) (f m m)) (f (f b m) (f e (f m m))))) ((f (f e (f m m)) (f (f b m) (f e (f m m))))).\nsurgery id_r ((f (f e (f m m)) (f (f b m) (f e (f m m))))) ((f (f e m) (f (f b m) (f e (f m m))))).\nsurgery id_r ((f (f e m) (f (f b m) (f e (f m m))))) ((f e (f (f b m) (f e (f m m))))).\nsurgery id_r ((f e (f (f b m) (f e (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_248: forall b: G, (((e <+> ((e <+> m) <+> (e <+> e))) <+> m) <+> ((e <+> b) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) (f e e))) m) (f (f e b) (f m m)))) ((f (f e (f (f e m) (f e e))) (f (f e b) (f m m)))).\nsurgery id_r ((f (f e (f (f e m) (f e e))) (f (f e b) (f m m)))) ((f (f e (f e (f e e))) (f (f e b) (f m m)))).\nsurgery id_l ((f (f e (f e (f e e))) (f (f e b) (f m m)))) ((f (f e (f e e)) (f (f e b) (f m m)))).\nsurgery id_l ((f (f e (f e e)) (f (f e b) (f m m)))) ((f (f e e) (f (f e b) (f m m)))).\nsurgery id_l ((f (f e e) (f (f e b) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_249: forall b: G, (((e <+> e) <+> e) <+> ((((e <+> m) <+> (m <+> m)) <+> m) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) e) (f (f (f (f e m) (f m m)) m) (f e b)))) ((f (f e e) (f (f (f (f e m) (f m m)) m) (f e b)))).\nsurgery id_l ((f (f e e) (f (f (f (f e m) (f m m)) m) (f e b)))) ((f e (f (f (f (f e m) (f m m)) m) (f e b)))).\nsurgery id_r ((f e (f (f (f (f e m) (f m m)) m) (f e b)))) ((f e (f (f (f e m) (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f (f e m) (f m m)) (f e b)))) ((f e (f (f e (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f m m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_250: forall b: G, (((e <+> b) <+> m) <+> (((e <+> (m <+> m)) <+> (e <+> e)) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e b) m) (f (f (f e (f m m)) (f e e)) (f m m)))) ((f (f e b) (f (f (f e (f m m)) (f e e)) (f m m)))).\nsurgery id_l ((f (f e b) (f (f (f e (f m m)) (f e e)) (f m m)))) ((f b (f (f (f e (f m m)) (f e e)) (f m m)))).\nsurgery id_r ((f b (f (f (f e (f m m)) (f e e)) (f m m)))) ((f b (f (f (f e m) (f e e)) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) (f e e)) (f m m)))) ((f b (f (f e (f e e)) (f m m)))).\nsurgery id_l ((f b (f (f e (f e e)) (f m m)))) ((f b (f (f e e) (f m m)))).\nsurgery id_l ((f b (f (f e e) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_251: forall b: G, ((b <+> ((((e <+> e) <+> m) <+> m) <+> (m <+> (m <+> (m <+> m))))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f (f (f e e) m) m) (f m (f m (f m m))))) m)) ((f b (f (f (f (f e e) m) m) (f m (f m (f m m)))))).\nsurgery id_r ((f b (f (f (f (f e e) m) m) (f m (f m (f m m)))))) ((f b (f (f (f e e) m) (f m (f m (f m m)))))).\nsurgery id_r ((f b (f (f (f e e) m) (f m (f m (f m m)))))) ((f b (f (f e e) (f m (f m (f m m)))))).\nsurgery id_l ((f b (f (f e e) (f m (f m (f m m)))))) ((f b (f e (f m (f m (f m m)))))).\nsurgery id_l ((f b (f e (f m (f m (f m m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_252: forall b: G, (b <+> (e <+> ((((e <+> m) <+> e) <+> m) <+> ((e <+> m) <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f e (f (f (f (f e m) e) m) (f (f e m) (f e m)))))) ((f b (f (f (f (f e m) e) m) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f (f (f e m) e) m) (f (f e m) (f e m))))) ((f b (f (f (f e m) e) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f (f e m) e) (f (f e m) (f e m))))) ((f b (f (f e e) (f (f e m) (f e m))))).\nsurgery id_l ((f b (f (f e e) (f (f e m) (f e m))))) ((f b (f e (f (f e m) (f e m))))).\nsurgery id_l ((f b (f e (f (f e m) (f e m))))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_253: forall b: G, ((e <+> b) <+> (((e <+> e) <+> ((e <+> e) <+> m)) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f (f e e) (f (f e e) m)) (f e (f e m))))) ((f b (f (f (f e e) (f (f e e) m)) (f e (f e m))))).\nsurgery id_l ((f b (f (f (f e e) (f (f e e) m)) (f e (f e m))))) ((f b (f (f e (f (f e e) m)) (f e (f e m))))).\nsurgery id_l ((f b (f (f e (f (f e e) m)) (f e (f e m))))) ((f b (f (f e (f e m)) (f e (f e m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f e (f e m))))) ((f b (f (f e m) (f e (f e m))))).\nsurgery id_r ((f b (f (f e m) (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_254: forall b: G, ((((e <+> e) <+> m) <+> e) <+> (((b <+> m) <+> m) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) e) (f (f (f b m) m) (f (f e e) m)))) ((f (f (f e e) e) (f (f (f b m) m) (f (f e e) m)))).\nsurgery id_l ((f (f (f e e) e) (f (f (f b m) m) (f (f e e) m)))) ((f (f e e) (f (f (f b m) m) (f (f e e) m)))).\nsurgery id_l ((f (f e e) (f (f (f b m) m) (f (f e e) m)))) ((f e (f (f (f b m) m) (f (f e e) m)))).\nsurgery id_r ((f e (f (f (f b m) m) (f (f e e) m)))) ((f e (f (f b m) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e e) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_255: forall b: G, (((e <+> (e <+> e)) <+> ((e <+> b) <+> m)) <+> (e <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e e)) (f (f e b) m)) (f e (f m (f m m))))) ((f (f (f e e) (f (f e b) m)) (f e (f m (f m m))))).\nsurgery id_l ((f (f (f e e) (f (f e b) m)) (f e (f m (f m m))))) ((f (f e (f (f e b) m)) (f e (f m (f m m))))).\nsurgery id_l ((f (f e (f (f e b) m)) (f e (f m (f m m))))) ((f (f e (f b m)) (f e (f m (f m m))))).\nsurgery id_r ((f (f e (f b m)) (f e (f m (f m m))))) ((f (f e b) (f e (f m (f m m))))).\nsurgery id_l ((f (f e b) (f e (f m (f m m))))) ((f b (f e (f m (f m m))))).\nsurgery id_l ((f b (f e (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_256: forall b: G, (((e <+> e) <+> ((e <+> m) <+> (e <+> b))) <+> ((e <+> (e <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e m) (f e b))) (f (f e (f e m)) m))) ((f (f e (f (f e m) (f e b))) (f (f e (f e m)) m))).\nsurgery id_r ((f (f e (f (f e m) (f e b))) (f (f e (f e m)) m))) ((f (f e (f e (f e b))) (f (f e (f e m)) m))).\nsurgery id_l ((f (f e (f e (f e b))) (f (f e (f e m)) m))) ((f (f e (f e b)) (f (f e (f e m)) m))).\nsurgery id_l ((f (f e (f e b)) (f (f e (f e m)) m))) ((f (f e b) (f (f e (f e m)) m))).\nsurgery id_l ((f (f e b) (f (f e (f e m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_257: forall b: G, ((((e <+> e) <+> ((e <+> m) <+> m)) <+> ((b <+> m) <+> (e <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f (f e m) m)) (f (f b m) (f e m))) m)) ((f (f (f e e) (f (f e m) m)) (f (f b m) (f e m)))).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f (f b m) (f e m)))) ((f (f e (f (f e m) m)) (f (f b m) (f e m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f b m) (f e m)))) ((f (f e (f e m)) (f (f b m) (f e m)))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) (f e m)))) ((f (f e m) (f (f b m) (f e m)))).\nsurgery id_r ((f (f e m) (f (f b m) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_258: forall b: G, ((((e <+> m) <+> (e <+> ((m <+> (e <+> (e <+> m))) <+> m))) <+> b) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e (f (f m (f e (f e m))) m))) b) m)) ((f (f (f e m) (f e (f (f m (f e (f e m))) m))) b)).\nsurgery id_r ((f (f (f e m) (f e (f (f m (f e (f e m))) m))) b)) ((f (f e (f e (f (f m (f e (f e m))) m))) b)).\nsurgery id_l ((f (f e (f e (f (f m (f e (f e m))) m))) b)) ((f (f e (f (f m (f e (f e m))) m)) b)).\nsurgery id_l ((f (f e (f (f m (f e (f e m))) m)) b)) ((f (f e (f (f m (f e m)) m)) b)).\nsurgery id_l ((f (f e (f (f m (f e m)) m)) b)) ((f (f e (f (f m m) m)) b)).\nsurgery id_r ((f (f e (f (f m m) m)) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_259: forall b: G, ((((e <+> m) <+> e) <+> (e <+> e)) <+> ((e <+> m) <+> ((e <+> m) <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f e e)) (f (f e m) (f (f e m) b)))) ((f (f (f e e) (f e e)) (f (f e m) (f (f e m) b)))).\nsurgery id_l ((f (f (f e e) (f e e)) (f (f e m) (f (f e m) b)))) ((f (f e (f e e)) (f (f e m) (f (f e m) b)))).\nsurgery id_l ((f (f e (f e e)) (f (f e m) (f (f e m) b)))) ((f (f e e) (f (f e m) (f (f e m) b)))).\nsurgery id_l ((f (f e e) (f (f e m) (f (f e m) b)))) ((f e (f (f e m) (f (f e m) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e m) b)))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_260: forall b: G, ((e <+> (e <+> e)) <+> (((((e <+> e) <+> m) <+> (e <+> m)) <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f (f (f (f e e) m) (f e m)) b) m))) ((f (f e e) (f (f (f (f (f e e) m) (f e m)) b) m))).\nsurgery id_l ((f (f e e) (f (f (f (f (f e e) m) (f e m)) b) m))) ((f e (f (f (f (f (f e e) m) (f e m)) b) m))).\nsurgery id_r ((f e (f (f (f (f (f e e) m) (f e m)) b) m))) ((f e (f (f (f (f e e) (f e m)) b) m))).\nsurgery id_l ((f e (f (f (f (f e e) (f e m)) b) m))) ((f e (f (f (f e (f e m)) b) m))).\nsurgery id_l ((f e (f (f (f e (f e m)) b) m))) ((f e (f (f (f e m) b) m))).\nsurgery id_r ((f e (f (f (f e m) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_261: forall b: G, (((e <+> (e <+> e)) <+> ((e <+> m) <+> (e <+> (e <+> m)))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e e)) (f (f e m) (f e (f e m)))) (f b m))) ((f (f (f e e) (f (f e m) (f e (f e m)))) (f b m))).\nsurgery id_l ((f (f (f e e) (f (f e m) (f e (f e m)))) (f b m))) ((f (f e (f (f e m) (f e (f e m)))) (f b m))).\nsurgery id_r ((f (f e (f (f e m) (f e (f e m)))) (f b m))) ((f (f e (f e (f e (f e m)))) (f b m))).\nsurgery id_l ((f (f e (f e (f e (f e m)))) (f b m))) ((f (f e (f e (f e m))) (f b m))).\nsurgery id_l ((f (f e (f e (f e m))) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_262: forall b: G, (b <+> ((e <+> ((e <+> (m <+> (e <+> m))) <+> (m <+> m))) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f e (f (f e (f m (f e m))) (f m m))) (f m m)))) ((f b (f (f e (f (f e (f m m)) (f m m))) (f m m)))).\nsurgery id_r ((f b (f (f e (f (f e (f m m)) (f m m))) (f m m)))) ((f b (f (f e (f (f e m) (f m m))) (f m m)))).\nsurgery id_r ((f b (f (f e (f (f e m) (f m m))) (f m m)))) ((f b (f (f e (f e (f m m))) (f m m)))).\nsurgery id_l ((f b (f (f e (f e (f m m))) (f m m)))) ((f b (f (f e (f m m)) (f m m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_263: forall b: G, (((e <+> e) <+> (b <+> (m <+> ((m <+> m) <+> m)))) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f b (f m (f (f m m) m)))) (f e (f m m)))) ((f (f e (f b (f m (f (f m m) m)))) (f e (f m m)))).\nsurgery id_r ((f (f e (f b (f m (f (f m m) m)))) (f e (f m m)))) ((f (f e (f b (f m (f m m)))) (f e (f m m)))).\nsurgery id_r ((f (f e (f b (f m (f m m)))) (f e (f m m)))) ((f (f e (f b (f m m))) (f e (f m m)))).\nsurgery id_r ((f (f e (f b (f m m))) (f e (f m m)))) ((f (f e (f b m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f e (f m m)))) ((f (f e b) (f e (f m m)))).\nsurgery id_l ((f (f e b) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_264: forall b: G, ((e <+> m) <+> ((b <+> (e <+> m)) <+> ((e <+> (e <+> (m <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f b (f e m)) (f (f e (f e (f m m))) m)))) ((f e (f (f b (f e m)) (f (f e (f e (f m m))) m)))).\nsurgery id_l ((f e (f (f b (f e m)) (f (f e (f e (f m m))) m)))) ((f e (f (f b m) (f (f e (f e (f m m))) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e (f e (f m m))) m)))) ((f e (f b (f (f e (f e (f m m))) m)))).\nsurgery id_l ((f e (f b (f (f e (f e (f m m))) m)))) ((f e (f b (f (f e (f m m)) m)))).\nsurgery id_r ((f e (f b (f (f e (f m m)) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_265: forall b: G, ((e <+> (((e <+> e) <+> e) <+> b)) <+> ((e <+> ((e <+> e) <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f (f e e) e) b)) (f (f e (f (f e e) m)) m))) ((f (f e (f (f e e) b)) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f e (f (f e e) b)) (f (f e (f (f e e) m)) m))) ((f (f e (f e b)) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f e (f e b)) (f (f e (f (f e e) m)) m))) ((f (f e b) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f e b) (f (f e (f (f e e) m)) m))) ((f b (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f b (f (f e (f (f e e) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_266: forall b: G, ((e <+> ((((e <+> e) <+> (e <+> m)) <+> (e <+> e)) <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f (f (f e e) (f e m)) (f e e)) (f e m))) b)) ((f (f e (f (f (f e (f e m)) (f e e)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f (f e (f e m)) (f e e)) (f e m))) b)) ((f (f e (f (f (f e m) (f e e)) (f e m))) b)).\nsurgery id_r ((f (f e (f (f (f e m) (f e e)) (f e m))) b)) ((f (f e (f (f e (f e e)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f e e)) (f e m))) b)) ((f (f e (f (f e e) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e e) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_267: forall b: G, (((e <+> (e <+> ((e <+> m) <+> m))) <+> ((e <+> e) <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f (f e m) m))) (f (f e e) (f e m))) b)) ((f (f (f e (f (f e m) m)) (f (f e e) (f e m))) b)).\nsurgery id_r ((f (f (f e (f (f e m) m)) (f (f e e) (f e m))) b)) ((f (f (f e (f e m)) (f (f e e) (f e m))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e e) (f e m))) b)) ((f (f (f e m) (f (f e e) (f e m))) b)).\nsurgery id_r ((f (f (f e m) (f (f e e) (f e m))) b)) ((f (f e (f (f e e) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e e) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_268: forall b: G, ((b <+> (e <+> m)) <+> (((e <+> e) <+> e) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e m)) (f (f (f e e) e) (f (f e m) (f e m))))) ((f (f b m) (f (f (f e e) e) (f (f e m) (f e m))))).\nsurgery id_r ((f (f b m) (f (f (f e e) e) (f (f e m) (f e m))))) ((f b (f (f (f e e) e) (f (f e m) (f e m))))).\nsurgery id_l ((f b (f (f (f e e) e) (f (f e m) (f e m))))) ((f b (f (f e e) (f (f e m) (f e m))))).\nsurgery id_l ((f b (f (f e e) (f (f e m) (f e m))))) ((f b (f e (f (f e m) (f e m))))).\nsurgery id_l ((f b (f e (f (f e m) (f e m))))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_269: forall b: G, ((e <+> ((e <+> e) <+> (e <+> m))) <+> ((e <+> m) <+> ((e <+> e) <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) (f e m))) (f (f e m) (f (f e e) b)))) ((f (f e (f e (f e m))) (f (f e m) (f (f e e) b)))).\nsurgery id_l ((f (f e (f e (f e m))) (f (f e m) (f (f e e) b)))) ((f (f e (f e m)) (f (f e m) (f (f e e) b)))).\nsurgery id_l ((f (f e (f e m)) (f (f e m) (f (f e e) b)))) ((f (f e m) (f (f e m) (f (f e e) b)))).\nsurgery id_r ((f (f e m) (f (f e m) (f (f e e) b)))) ((f e (f (f e m) (f (f e e) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e e) b)))) ((f e (f e (f (f e e) b)))).\nsurgery id_l ((f e (f e (f (f e e) b)))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_270: forall b: G, ((e <+> ((e <+> m) <+> (m <+> m))) <+> (((e <+> m) <+> b) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f (f (f e m) b) (f m m)))) ((f (f e (f e (f m m))) (f (f (f e m) b) (f m m)))).\nsurgery id_l ((f (f e (f e (f m m))) (f (f (f e m) b) (f m m)))) ((f (f e (f m m)) (f (f (f e m) b) (f m m)))).\nsurgery id_r ((f (f e (f m m)) (f (f (f e m) b) (f m m)))) ((f (f e m) (f (f (f e m) b) (f m m)))).\nsurgery id_r ((f (f e m) (f (f (f e m) b) (f m m)))) ((f e (f (f (f e m) b) (f m m)))).\nsurgery id_r ((f e (f (f (f e m) b) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_271: forall b: G, (((e <+> b) <+> ((e <+> e) <+> (e <+> m))) <+> ((e <+> (m <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f e e) (f e m))) (f (f e (f m m)) m))) ((f (f b (f (f e e) (f e m))) (f (f e (f m m)) m))).\nsurgery id_l ((f (f b (f (f e e) (f e m))) (f (f e (f m m)) m))) ((f (f b (f e (f e m))) (f (f e (f m m)) m))).\nsurgery id_l ((f (f b (f e (f e m))) (f (f e (f m m)) m))) ((f (f b (f e m)) (f (f e (f m m)) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f m m)) m))) ((f (f b m) (f (f e (f m m)) m))).\nsurgery id_r ((f (f b m) (f (f e (f m m)) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_272: forall b: G, (((e <+> m) <+> (b <+> m)) <+> (e <+> (m <+> ((m <+> (m <+> m)) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f b m)) (f e (f m (f (f m (f m m)) m))))) ((f (f e (f b m)) (f e (f m (f (f m (f m m)) m))))).\nsurgery id_r ((f (f e (f b m)) (f e (f m (f (f m (f m m)) m))))) ((f (f e b) (f e (f m (f (f m (f m m)) m))))).\nsurgery id_l ((f (f e b) (f e (f m (f (f m (f m m)) m))))) ((f b (f e (f m (f (f m (f m m)) m))))).\nsurgery id_l ((f b (f e (f m (f (f m (f m m)) m))))) ((f b (f m (f (f m (f m m)) m)))).\nsurgery id_r ((f b (f m (f (f m (f m m)) m)))) ((f b (f m (f (f m m) m)))).\nsurgery id_r ((f b (f m (f (f m m) m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_273: forall b: G, ((((e <+> e) <+> (e <+> (e <+> m))) <+> (e <+> m)) <+> ((b <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f e (f e m))) (f e m)) (f (f b m) m))) ((f (f (f e (f e (f e m))) (f e m)) (f (f b m) m))).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e m)) (f (f b m) m))) ((f (f (f e (f e m)) (f e m)) (f (f b m) m))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f (f b m) m))) ((f (f (f e m) (f e m)) (f (f b m) m))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f b m) m))) ((f (f e (f e m)) (f (f b m) m))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) m))) ((f (f e m) (f (f b m) m))).\nsurgery id_r ((f (f e m) (f (f b m) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_274: forall b: G, (((e <+> m) <+> (e <+> m)) <+> ((b <+> m) <+> ((m <+> m) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e m)) (f (f b m) (f (f m m) (f m m))))) ((f (f e (f e m)) (f (f b m) (f (f m m) (f m m))))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) (f (f m m) (f m m))))) ((f (f e m) (f (f b m) (f (f m m) (f m m))))).\nsurgery id_r ((f (f e m) (f (f b m) (f (f m m) (f m m))))) ((f e (f (f b m) (f (f m m) (f m m))))).\nsurgery id_r ((f e (f (f b m) (f (f m m) (f m m))))) ((f e (f b (f (f m m) (f m m))))).\nsurgery id_r ((f e (f b (f (f m m) (f m m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_275: forall b: G, ((((e <+> e) <+> m) <+> m) <+> (((e <+> (e <+> m)) <+> (e <+> m)) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) m) (f (f (f e (f e m)) (f e m)) b))) ((f (f (f e e) m) (f (f (f e (f e m)) (f e m)) b))).\nsurgery id_r ((f (f (f e e) m) (f (f (f e (f e m)) (f e m)) b))) ((f (f e e) (f (f (f e (f e m)) (f e m)) b))).\nsurgery id_l ((f (f e e) (f (f (f e (f e m)) (f e m)) b))) ((f e (f (f (f e (f e m)) (f e m)) b))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f e m)) b))) ((f e (f (f (f e m) (f e m)) b))).\nsurgery id_r ((f e (f (f (f e m) (f e m)) b))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_276: forall b: G, (((e <+> m) <+> (m <+> ((e <+> e) <+> (m <+> (m <+> m))))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f m (f (f e e) (f m (f m m))))) (f e b))) ((f (f e (f m (f (f e e) (f m (f m m))))) (f e b))).\nsurgery id_l ((f (f e (f m (f (f e e) (f m (f m m))))) (f e b))) ((f (f e (f m (f e (f m (f m m))))) (f e b))).\nsurgery id_l ((f (f e (f m (f e (f m (f m m))))) (f e b))) ((f (f e (f m (f m (f m m)))) (f e b))).\nsurgery id_r ((f (f e (f m (f m (f m m)))) (f e b))) ((f (f e (f m (f m m))) (f e b))).\nsurgery id_r ((f (f e (f m (f m m))) (f e b))) ((f (f e (f m m)) (f e b))).\nsurgery id_r ((f (f e (f m m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_277: forall b: G, (((e <+> e) <+> e) <+> (((b <+> m) <+> (m <+> (e <+> m))) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) e) (f (f (f b m) (f m (f e m))) (f e m)))) ((f (f e e) (f (f (f b m) (f m (f e m))) (f e m)))).\nsurgery id_l ((f (f e e) (f (f (f b m) (f m (f e m))) (f e m)))) ((f e (f (f (f b m) (f m (f e m))) (f e m)))).\nsurgery id_r ((f e (f (f (f b m) (f m (f e m))) (f e m)))) ((f e (f (f b (f m (f e m))) (f e m)))).\nsurgery id_l ((f e (f (f b (f m (f e m))) (f e m)))) ((f e (f (f b (f m m)) (f e m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_278: forall b: G, (((b <+> m) <+> ((e <+> ((e <+> m) <+> e)) <+> m)) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f e (f (f e m) e)) m)) (f (f e m) m))) ((f (f b (f (f e (f (f e m) e)) m)) (f (f e m) m))).\nsurgery id_r ((f (f b (f (f e (f (f e m) e)) m)) (f (f e m) m))) ((f (f b (f (f e (f e e)) m)) (f (f e m) m))).\nsurgery id_l ((f (f b (f (f e (f e e)) m)) (f (f e m) m))) ((f (f b (f (f e e) m)) (f (f e m) m))).\nsurgery id_l ((f (f b (f (f e e) m)) (f (f e m) m))) ((f (f b (f e m)) (f (f e m) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e m) m))) ((f (f b m) (f (f e m) m))).\nsurgery id_r ((f (f b m) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_279: forall b: G, ((e <+> m) <+> (((e <+> e) <+> (b <+> m)) <+> ((m <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e e) (f b m)) (f (f m m) (f e m))))) ((f e (f (f (f e e) (f b m)) (f (f m m) (f e m))))).\nsurgery id_l ((f e (f (f (f e e) (f b m)) (f (f m m) (f e m))))) ((f e (f (f e (f b m)) (f (f m m) (f e m))))).\nsurgery id_r ((f e (f (f e (f b m)) (f (f m m) (f e m))))) ((f e (f (f e b) (f (f m m) (f e m))))).\nsurgery id_l ((f e (f (f e b) (f (f m m) (f e m))))) ((f e (f b (f (f m m) (f e m))))).\nsurgery id_r ((f e (f b (f (f m m) (f e m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_280: forall b: G, (((e <+> b) <+> (((e <+> m) <+> (e <+> m)) <+> (m <+> m))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f (f e m) (f e m)) (f m m))) (f e m))) ((f (f b (f (f (f e m) (f e m)) (f m m))) (f e m))).\nsurgery id_r ((f (f b (f (f (f e m) (f e m)) (f m m))) (f e m))) ((f (f b (f (f e (f e m)) (f m m))) (f e m))).\nsurgery id_l ((f (f b (f (f e (f e m)) (f m m))) (f e m))) ((f (f b (f (f e m) (f m m))) (f e m))).\nsurgery id_r ((f (f b (f (f e m) (f m m))) (f e m))) ((f (f b (f e (f m m))) (f e m))).\nsurgery id_l ((f (f b (f e (f m m))) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_281: forall b: G, ((e <+> (e <+> e)) <+> (((b <+> ((m <+> m) <+> m)) <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f (f b (f (f m m) m)) m) (f e m)))) ((f (f e e) (f (f (f b (f (f m m) m)) m) (f e m)))).\nsurgery id_l ((f (f e e) (f (f (f b (f (f m m) m)) m) (f e m)))) ((f e (f (f (f b (f (f m m) m)) m) (f e m)))).\nsurgery id_r ((f e (f (f (f b (f (f m m) m)) m) (f e m)))) ((f e (f (f b (f (f m m) m)) (f e m)))).\nsurgery id_r ((f e (f (f b (f (f m m) m)) (f e m)))) ((f e (f (f b (f m m)) (f e m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_282: forall b: G, ((e <+> ((e <+> e) <+> m)) <+> (b <+> (e <+> (m <+> (m <+> (e <+> m)))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) m)) (f b (f e (f m (f m (f e m))))))) ((f (f e (f e m)) (f b (f e (f m (f m (f e m))))))).\nsurgery id_l ((f (f e (f e m)) (f b (f e (f m (f m (f e m))))))) ((f (f e m) (f b (f e (f m (f m (f e m))))))).\nsurgery id_r ((f (f e m) (f b (f e (f m (f m (f e m))))))) ((f e (f b (f e (f m (f m (f e m))))))).\nsurgery id_l ((f e (f b (f e (f m (f m (f e m))))))) ((f e (f b (f m (f m (f e m)))))).\nsurgery id_l ((f e (f b (f m (f m (f e m)))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_283: forall b: G, ((((((e <+> e) <+> m) <+> e) <+> m) <+> m) <+> ((e <+> (e <+> m)) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e e) m) e) m) m) (f (f e (f e m)) b))) ((f (f (f (f (f e e) m) e) m) (f (f e (f e m)) b))).\nsurgery id_r ((f (f (f (f (f e e) m) e) m) (f (f e (f e m)) b))) ((f (f (f (f e e) m) e) (f (f e (f e m)) b))).\nsurgery id_r ((f (f (f (f e e) m) e) (f (f e (f e m)) b))) ((f (f (f e e) e) (f (f e (f e m)) b))).\nsurgery id_l ((f (f (f e e) e) (f (f e (f e m)) b))) ((f (f e e) (f (f e (f e m)) b))).\nsurgery id_l ((f (f e e) (f (f e (f e m)) b))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_284: forall b: G, ((e <+> (b <+> (e <+> m))) <+> ((e <+> e) <+> (((m <+> m) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f b (f e m))) (f (f e e) (f (f (f m m) m) m)))) ((f (f e (f b m)) (f (f e e) (f (f (f m m) m) m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e e) (f (f (f m m) m) m)))) ((f (f e b) (f (f e e) (f (f (f m m) m) m)))).\nsurgery id_l ((f (f e b) (f (f e e) (f (f (f m m) m) m)))) ((f b (f (f e e) (f (f (f m m) m) m)))).\nsurgery id_l ((f b (f (f e e) (f (f (f m m) m) m)))) ((f b (f e (f (f (f m m) m) m)))).\nsurgery id_l ((f b (f e (f (f (f m m) m) m)))) ((f b (f (f (f m m) m) m))).\nsurgery id_r ((f b (f (f (f m m) m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_285: forall b: G, (((e <+> m) <+> (e <+> (e <+> m))) <+> ((((e <+> b) <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e (f e m))) (f (f (f (f e b) m) m) m))) ((f (f e (f e (f e m))) (f (f (f (f e b) m) m) m))).\nsurgery id_l ((f (f e (f e (f e m))) (f (f (f (f e b) m) m) m))) ((f (f e (f e m)) (f (f (f (f e b) m) m) m))).\nsurgery id_l ((f (f e (f e m)) (f (f (f (f e b) m) m) m))) ((f (f e m) (f (f (f (f e b) m) m) m))).\nsurgery id_r ((f (f e m) (f (f (f (f e b) m) m) m))) ((f e (f (f (f (f e b) m) m) m))).\nsurgery id_r ((f e (f (f (f (f e b) m) m) m))) ((f e (f (f (f e b) m) m))).\nsurgery id_r ((f e (f (f (f e b) m) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_286: forall b: G, ((e <+> (e <+> e)) <+> (((b <+> m) <+> m) <+> ((m <+> (e <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f (f b m) m) (f (f m (f e m)) m)))) ((f (f e e) (f (f (f b m) m) (f (f m (f e m)) m)))).\nsurgery id_l ((f (f e e) (f (f (f b m) m) (f (f m (f e m)) m)))) ((f e (f (f (f b m) m) (f (f m (f e m)) m)))).\nsurgery id_r ((f e (f (f (f b m) m) (f (f m (f e m)) m)))) ((f e (f (f b m) (f (f m (f e m)) m)))).\nsurgery id_r ((f e (f (f b m) (f (f m (f e m)) m)))) ((f e (f b (f (f m (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f m (f e m)) m)))) ((f e (f b (f (f m m) m)))).\nsurgery id_r ((f e (f b (f (f m m) m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_287: forall b: G, (((e <+> b) <+> ((e <+> m) <+> m)) <+> (m <+> (((e <+> m) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f e m) m)) (f m (f (f (f e m) m) m)))) ((f (f b (f (f e m) m)) (f m (f (f (f e m) m) m)))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m (f (f (f e m) m) m)))) ((f (f b (f e m)) (f m (f (f (f e m) m) m)))).\nsurgery id_l ((f (f b (f e m)) (f m (f (f (f e m) m) m)))) ((f (f b m) (f m (f (f (f e m) m) m)))).\nsurgery id_r ((f (f b m) (f m (f (f (f e m) m) m)))) ((f b (f m (f (f (f e m) m) m)))).\nsurgery id_r ((f b (f m (f (f (f e m) m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_288: forall b: G, (((e <+> (e <+> m)) <+> (e <+> b)) <+> ((m <+> (e <+> m)) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e b)) (f (f m (f e m)) (f e m)))) ((f (f (f e m) (f e b)) (f (f m (f e m)) (f e m)))).\nsurgery id_r ((f (f (f e m) (f e b)) (f (f m (f e m)) (f e m)))) ((f (f e (f e b)) (f (f m (f e m)) (f e m)))).\nsurgery id_l ((f (f e (f e b)) (f (f m (f e m)) (f e m)))) ((f (f e b) (f (f m (f e m)) (f e m)))).\nsurgery id_l ((f (f e b) (f (f m (f e m)) (f e m)))) ((f b (f (f m (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f m (f e m)) (f e m)))) ((f b (f (f m m) (f e m)))).\nsurgery id_r ((f b (f (f m m) (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_289: forall b: G, (((b <+> m) <+> (e <+> m)) <+> ((e <+> m) <+> (m <+> ((m <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f e m)) (f (f e m) (f m (f (f m m) m))))) ((f (f b (f e m)) (f (f e m) (f m (f (f m m) m))))).\nsurgery id_l ((f (f b (f e m)) (f (f e m) (f m (f (f m m) m))))) ((f (f b m) (f (f e m) (f m (f (f m m) m))))).\nsurgery id_r ((f (f b m) (f (f e m) (f m (f (f m m) m))))) ((f b (f (f e m) (f m (f (f m m) m))))).\nsurgery id_r ((f b (f (f e m) (f m (f (f m m) m))))) ((f b (f e (f m (f (f m m) m))))).\nsurgery id_l ((f b (f e (f m (f (f m m) m))))) ((f b (f m (f (f m m) m)))).\nsurgery id_r ((f b (f m (f (f m m) m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_290: forall b: G, (((e <+> b) <+> (e <+> (e <+> m))) <+> (e <+> (e <+> (e <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f e (f e m))) (f e (f e (f e (f e m)))))) ((f (f b (f e (f e m))) (f e (f e (f e (f e m)))))).\nsurgery id_l ((f (f b (f e (f e m))) (f e (f e (f e (f e m)))))) ((f (f b (f e m)) (f e (f e (f e (f e m)))))).\nsurgery id_l ((f (f b (f e m)) (f e (f e (f e (f e m)))))) ((f (f b m) (f e (f e (f e (f e m)))))).\nsurgery id_r ((f (f b m) (f e (f e (f e (f e m)))))) ((f b (f e (f e (f e (f e m)))))).\nsurgery id_l ((f b (f e (f e (f e (f e m)))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_291: forall b: G, (((e <+> ((e <+> m) <+> ((e <+> e) <+> m))) <+> (e <+> m)) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) (f (f e e) m))) (f e m)) (f e b))) ((f (f (f e (f e (f (f e e) m))) (f e m)) (f e b))).\nsurgery id_l ((f (f (f e (f e (f (f e e) m))) (f e m)) (f e b))) ((f (f (f e (f (f e e) m)) (f e m)) (f e b))).\nsurgery id_l ((f (f (f e (f (f e e) m)) (f e m)) (f e b))) ((f (f (f e (f e m)) (f e m)) (f e b))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f e b))) ((f (f (f e m) (f e m)) (f e b))).\nsurgery id_r ((f (f (f e m) (f e m)) (f e b))) ((f (f e (f e m)) (f e b))).\nsurgery id_l ((f (f e (f e m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_292: forall b: G, ((b <+> m) <+> ((e <+> (m <+> m)) <+> ((m <+> (e <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f e (f m m)) (f (f m (f e m)) (f m m))))) ((f b (f (f e (f m m)) (f (f m (f e m)) (f m m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f m (f e m)) (f m m))))) ((f b (f (f e m) (f (f m (f e m)) (f m m))))).\nsurgery id_r ((f b (f (f e m) (f (f m (f e m)) (f m m))))) ((f b (f e (f (f m (f e m)) (f m m))))).\nsurgery id_l ((f b (f e (f (f m (f e m)) (f m m))))) ((f b (f (f m (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f m (f e m)) (f m m)))) ((f b (f (f m m) (f m m)))).\nsurgery id_r ((f b (f (f m m) (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_293: forall b: G, ((((e <+> e) <+> m) <+> (e <+> (e <+> (e <+> e)))) <+> ((e <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f e (f e (f e e)))) (f (f e b) m))) ((f (f (f e e) (f e (f e (f e e)))) (f (f e b) m))).\nsurgery id_l ((f (f (f e e) (f e (f e (f e e)))) (f (f e b) m))) ((f (f e (f e (f e (f e e)))) (f (f e b) m))).\nsurgery id_l ((f (f e (f e (f e (f e e)))) (f (f e b) m))) ((f (f e (f e (f e e))) (f (f e b) m))).\nsurgery id_l ((f (f e (f e (f e e))) (f (f e b) m))) ((f (f e (f e e)) (f (f e b) m))).\nsurgery id_l ((f (f e (f e e)) (f (f e b) m))) ((f (f e e) (f (f e b) m))).\nsurgery id_l ((f (f e e) (f (f e b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_294: forall b: G, ((((e <+> b) <+> (e <+> m)) <+> (e <+> m)) <+> ((e <+> (m <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e b) (f e m)) (f e m)) (f (f e (f m m)) m))) ((f (f (f b (f e m)) (f e m)) (f (f e (f m m)) m))).\nsurgery id_l ((f (f (f b (f e m)) (f e m)) (f (f e (f m m)) m))) ((f (f (f b m) (f e m)) (f (f e (f m m)) m))).\nsurgery id_r ((f (f (f b m) (f e m)) (f (f e (f m m)) m))) ((f (f b (f e m)) (f (f e (f m m)) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f m m)) m))) ((f (f b m) (f (f e (f m m)) m))).\nsurgery id_r ((f (f b m) (f (f e (f m m)) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_295: forall b: G, (((((e <+> e) <+> m) <+> (e <+> m)) <+> (((m <+> m) <+> m) <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e e) m) (f e m)) (f (f (f m m) m) m)) b)) ((f (f (f (f e e) (f e m)) (f (f (f m m) m) m)) b)).\nsurgery id_l ((f (f (f (f e e) (f e m)) (f (f (f m m) m) m)) b)) ((f (f (f e (f e m)) (f (f (f m m) m) m)) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f (f m m) m) m)) b)) ((f (f (f e m) (f (f (f m m) m) m)) b)).\nsurgery id_r ((f (f (f e m) (f (f (f m m) m) m)) b)) ((f (f e (f (f (f m m) m) m)) b)).\nsurgery id_r ((f (f e (f (f (f m m) m) m)) b)) ((f (f e (f (f m m) m)) b)).\nsurgery id_r ((f (f e (f (f m m) m)) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_296: forall b: G, (((e <+> m) <+> e) <+> ((e <+> (e <+> e)) <+> ((e <+> b) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) e) (f (f e (f e e)) (f (f e b) (f e m))))) ((f (f e e) (f (f e (f e e)) (f (f e b) (f e m))))).\nsurgery id_l ((f (f e e) (f (f e (f e e)) (f (f e b) (f e m))))) ((f e (f (f e (f e e)) (f (f e b) (f e m))))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f e b) (f e m))))) ((f e (f (f e e) (f (f e b) (f e m))))).\nsurgery id_l ((f e (f (f e e) (f (f e b) (f e m))))) ((f e (f e (f (f e b) (f e m))))).\nsurgery id_l ((f e (f e (f (f e b) (f e m))))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_297: forall b: G, ((e <+> ((e <+> e) <+> b)) <+> (((e <+> e) <+> e) <+> (m <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) b)) (f (f (f e e) e) (f m (f e m))))) ((f (f e (f e b)) (f (f (f e e) e) (f m (f e m))))).\nsurgery id_l ((f (f e (f e b)) (f (f (f e e) e) (f m (f e m))))) ((f (f e b) (f (f (f e e) e) (f m (f e m))))).\nsurgery id_l ((f (f e b) (f (f (f e e) e) (f m (f e m))))) ((f b (f (f (f e e) e) (f m (f e m))))).\nsurgery id_l ((f b (f (f (f e e) e) (f m (f e m))))) ((f b (f (f e e) (f m (f e m))))).\nsurgery id_l ((f b (f (f e e) (f m (f e m))))) ((f b (f e (f m (f e m))))).\nsurgery id_l ((f b (f e (f m (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_298: forall b: G, ((e <+> b) <+> (((m <+> (e <+> m)) <+> m) <+> (m <+> (m <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f (f m (f e m)) m) (f m (f m (f e m)))))) ((f b (f (f (f m (f e m)) m) (f m (f m (f e m)))))).\nsurgery id_r ((f b (f (f (f m (f e m)) m) (f m (f m (f e m)))))) ((f b (f (f m (f e m)) (f m (f m (f e m)))))).\nsurgery id_l ((f b (f (f m (f e m)) (f m (f m (f e m)))))) ((f b (f (f m m) (f m (f m (f e m)))))).\nsurgery id_r ((f b (f (f m m) (f m (f m (f e m)))))) ((f b (f m (f m (f m (f e m)))))).\nsurgery id_l ((f b (f m (f m (f m (f e m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_299: forall b: G, (((e <+> ((e <+> (e <+> e)) <+> m)) <+> (e <+> m)) <+> (e <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f (f e (f e e)) m)) (f e m)) (f e (f b m)))) ((f (f (f e (f (f e e) m)) (f e m)) (f e (f b m)))).\nsurgery id_l ((f (f (f e (f (f e e) m)) (f e m)) (f e (f b m)))) ((f (f (f e (f e m)) (f e m)) (f e (f b m)))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f e (f b m)))) ((f (f (f e m) (f e m)) (f e (f b m)))).\nsurgery id_r ((f (f (f e m) (f e m)) (f e (f b m)))) ((f (f e (f e m)) (f e (f b m)))).\nsurgery id_l ((f (f e (f e m)) (f e (f b m)))) ((f (f e m) (f e (f b m)))).\nsurgery id_r ((f (f e m) (f e (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_300: forall b: G, (b <+> ((e <+> m) <+> (((e <+> (m <+> m)) <+> m) <+> (e <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f e m) (f (f (f e (f m m)) m) (f e (f e m)))))) ((f b (f e (f (f (f e (f m m)) m) (f e (f e m)))))).\nsurgery id_l ((f b (f e (f (f (f e (f m m)) m) (f e (f e m)))))) ((f b (f (f (f e (f m m)) m) (f e (f e m))))).\nsurgery id_r ((f b (f (f (f e (f m m)) m) (f e (f e m))))) ((f b (f (f e (f m m)) (f e (f e m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f e (f e m))))) ((f b (f (f e m) (f e (f e m))))).\nsurgery id_r ((f b (f (f e m) (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_301: forall b: G, ((((e <+> e) <+> e) <+> ((e <+> m) <+> m)) <+> (e <+> (e <+> (b <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) e) (f (f e m) m)) (f e (f e (f b m))))) ((f (f (f e e) (f (f e m) m)) (f e (f e (f b m))))).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f e (f e (f b m))))) ((f (f e (f (f e m) m)) (f e (f e (f b m))))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f e (f b m))))) ((f (f e (f e m)) (f e (f e (f b m))))).\nsurgery id_l ((f (f e (f e m)) (f e (f e (f b m))))) ((f (f e m) (f e (f e (f b m))))).\nsurgery id_r ((f (f e m) (f e (f e (f b m))))) ((f e (f e (f e (f b m))))).\nsurgery id_l ((f e (f e (f e (f b m))))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_302: forall b: G, ((e <+> (((e <+> e) <+> (e <+> m)) <+> (e <+> (e <+> m)))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f (f e e) (f e m)) (f e (f e m)))) (f e b))) ((f (f e (f (f e (f e m)) (f e (f e m)))) (f e b))).\nsurgery id_l ((f (f e (f (f e (f e m)) (f e (f e m)))) (f e b))) ((f (f e (f (f e m) (f e (f e m)))) (f e b))).\nsurgery id_r ((f (f e (f (f e m) (f e (f e m)))) (f e b))) ((f (f e (f e (f e (f e m)))) (f e b))).\nsurgery id_l ((f (f e (f e (f e (f e m)))) (f e b))) ((f (f e (f e (f e m))) (f e b))).\nsurgery id_l ((f (f e (f e (f e m))) (f e b))) ((f (f e (f e m)) (f e b))).\nsurgery id_l ((f (f e (f e m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_303: forall b: G, (((e <+> m) <+> (e <+> e)) <+> (e <+> ((b <+> m) <+> (e <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e e)) (f e (f (f b m) (f e (f e m)))))) ((f (f e (f e e)) (f e (f (f b m) (f e (f e m)))))).\nsurgery id_l ((f (f e (f e e)) (f e (f (f b m) (f e (f e m)))))) ((f (f e e) (f e (f (f b m) (f e (f e m)))))).\nsurgery id_l ((f (f e e) (f e (f (f b m) (f e (f e m)))))) ((f e (f e (f (f b m) (f e (f e m)))))).\nsurgery id_l ((f e (f e (f (f b m) (f e (f e m)))))) ((f e (f (f b m) (f e (f e m))))).\nsurgery id_r ((f e (f (f b m) (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_304: forall b: G, ((e <+> (e <+> ((e <+> m) <+> m))) <+> (((e <+> m) <+> e) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f (f (f e m) e) (f e b)))) ((f (f e (f (f e m) m)) (f (f (f e m) e) (f e b)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f (f e m) e) (f e b)))) ((f (f e (f e m)) (f (f (f e m) e) (f e b)))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e m) e) (f e b)))) ((f (f e m) (f (f (f e m) e) (f e b)))).\nsurgery id_r ((f (f e m) (f (f (f e m) e) (f e b)))) ((f e (f (f (f e m) e) (f e b)))).\nsurgery id_r ((f e (f (f (f e m) e) (f e b)))) ((f e (f (f e e) (f e b)))).\nsurgery id_l ((f e (f (f e e) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_305: forall b: G, ((e <+> (((b <+> m) <+> ((e <+> e) <+> m)) <+> m)) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f b m) (f (f e e) m)) m)) (f e (f m m)))) ((f (f e (f (f b (f (f e e) m)) m)) (f e (f m m)))).\nsurgery id_l ((f (f e (f (f b (f (f e e) m)) m)) (f e (f m m)))) ((f (f e (f (f b (f e m)) m)) (f e (f m m)))).\nsurgery id_l ((f (f e (f (f b (f e m)) m)) (f e (f m m)))) ((f (f e (f (f b m) m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f e (f m m)))) ((f (f e (f b m)) (f e (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f e (f m m)))) ((f (f e b) (f e (f m m)))).\nsurgery id_l ((f (f e b) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_306: forall b: G, (((b <+> m) <+> (m <+> (e <+> (e <+> m)))) <+> (((e <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f m (f e (f e m)))) (f (f (f e m) m) m))) ((f (f b (f m (f e (f e m)))) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f m (f e (f e m)))) (f (f (f e m) m) m))) ((f (f b (f m (f e m))) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f m (f e m))) (f (f (f e m) m) m))) ((f (f b (f m m)) (f (f (f e m) m) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e m) m) m))) ((f (f b m) (f (f (f e m) m) m))).\nsurgery id_r ((f (f b m) (f (f (f e m) m) m))) ((f b (f (f (f e m) m) m))).\nsurgery id_r ((f b (f (f (f e m) m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_307: forall b: G, (b <+> (((e <+> e) <+> (e <+> e)) <+> ((e <+> (e <+> (e <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f (f e e) (f e e)) (f (f e (f e (f e m))) m)))) ((f b (f (f e (f e e)) (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f b (f (f e (f e e)) (f (f e (f e (f e m))) m)))) ((f b (f (f e e) (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f b (f (f e e) (f (f e (f e (f e m))) m)))) ((f b (f e (f (f e (f e (f e m))) m)))).\nsurgery id_l ((f b (f e (f (f e (f e (f e m))) m)))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_308: forall b: G, (b <+> ((((m <+> (e <+> (e <+> m))) <+> m) <+> m) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f (f m (f e (f e m))) m) m) (f m (f m m))))) ((f b (f (f (f m (f e (f e m))) m) (f m (f m m))))).\nsurgery id_r ((f b (f (f (f m (f e (f e m))) m) (f m (f m m))))) ((f b (f (f m (f e (f e m))) (f m (f m m))))).\nsurgery id_l ((f b (f (f m (f e (f e m))) (f m (f m m))))) ((f b (f (f m (f e m)) (f m (f m m))))).\nsurgery id_l ((f b (f (f m (f e m)) (f m (f m m))))) ((f b (f (f m m) (f m (f m m))))).\nsurgery id_r ((f b (f (f m m) (f m (f m m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_309: forall b: G, ((((e <+> (e <+> m)) <+> m) <+> ((e <+> (e <+> e)) <+> (e <+> e))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f e m)) m) (f (f e (f e e)) (f e e))) b)) ((f (f (f e (f e m)) (f (f e (f e e)) (f e e))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e (f e e)) (f e e))) b)) ((f (f (f e m) (f (f e (f e e)) (f e e))) b)).\nsurgery id_r ((f (f (f e m) (f (f e (f e e)) (f e e))) b)) ((f (f e (f (f e (f e e)) (f e e))) b)).\nsurgery id_l ((f (f e (f (f e (f e e)) (f e e))) b)) ((f (f e (f (f e e) (f e e))) b)).\nsurgery id_l ((f (f e (f (f e e) (f e e))) b)) ((f (f e (f e (f e e))) b)).\nsurgery id_l ((f (f e (f e (f e e))) b)) ((f (f e (f e e)) b)).\nsurgery id_l ((f (f e (f e e)) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_310: forall b: G, ((e <+> ((b <+> (m <+> m)) <+> m)) <+> (((m <+> m) <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f b (f m m)) m)) (f (f (f m m) m) (f m m)))) ((f (f e (f (f b m) m)) (f (f (f m m) m) (f m m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f (f (f m m) m) (f m m)))) ((f (f e (f b m)) (f (f (f m m) m) (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f (f (f m m) m) (f m m)))) ((f (f e b) (f (f (f m m) m) (f m m)))).\nsurgery id_l ((f (f e b) (f (f (f m m) m) (f m m)))) ((f b (f (f (f m m) m) (f m m)))).\nsurgery id_r ((f b (f (f (f m m) m) (f m m)))) ((f b (f (f m m) (f m m)))).\nsurgery id_r ((f b (f (f m m) (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_311: forall b: G, ((e <+> m) <+> ((((e <+> (m <+> m)) <+> e) <+> ((m <+> m) <+> m)) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f (f e (f m m)) e) (f (f m m) m)) b))) ((f e (f (f (f (f e (f m m)) e) (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f (f (f e (f m m)) e) (f (f m m) m)) b))) ((f e (f (f (f (f e m) e) (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f (f (f e m) e) (f (f m m) m)) b))) ((f e (f (f (f e e) (f (f m m) m)) b))).\nsurgery id_l ((f e (f (f (f e e) (f (f m m) m)) b))) ((f e (f (f e (f (f m m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f m m) m)) b))) ((f e (f (f e (f m m)) b))).\nsurgery id_r ((f e (f (f e (f m m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_312: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> m) <+> (((e <+> (e <+> m)) <+> e) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) m) (f (f (f e (f e m)) e) b))) ((f (f (f e m) (f e m)) (f (f (f e (f e m)) e) b))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f (f e (f e m)) e) b))) ((f (f e (f e m)) (f (f (f e (f e m)) e) b))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e (f e m)) e) b))) ((f (f e m) (f (f (f e (f e m)) e) b))).\nsurgery id_r ((f (f e m) (f (f (f e (f e m)) e) b))) ((f e (f (f (f e (f e m)) e) b))).\nsurgery id_l ((f e (f (f (f e (f e m)) e) b))) ((f e (f (f (f e m) e) b))).\nsurgery id_r ((f e (f (f (f e m) e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_313: forall b: G, (((e <+> b) <+> ((((e <+> m) <+> m) <+> (e <+> m)) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f (f (f e m) m) (f e m)) m)) (f m m))) ((f (f b (f (f (f (f e m) m) (f e m)) m)) (f m m))).\nsurgery id_r ((f (f b (f (f (f (f e m) m) (f e m)) m)) (f m m))) ((f (f b (f (f (f e m) (f e m)) m)) (f m m))).\nsurgery id_r ((f (f b (f (f (f e m) (f e m)) m)) (f m m))) ((f (f b (f (f e (f e m)) m)) (f m m))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f m m))) ((f (f b (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_314: forall b: G, ((e <+> m) <+> ((e <+> ((e <+> ((m <+> m) <+> m)) <+> m)) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e (f (f e (f (f m m) m)) m)) (f e b)))) ((f e (f (f e (f (f e (f (f m m) m)) m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f (f e (f (f m m) m)) m)) (f e b)))) ((f e (f (f e (f (f e (f m m)) m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f (f e (f m m)) m)) (f e b)))) ((f e (f (f e (f (f e m) m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) (f e b)))) ((f e (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_315: forall b: G, (((e <+> (m <+> (e <+> m))) <+> e) <+> (((e <+> e) <+> m) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f m (f e m))) e) (f (f (f e e) m) (f b m)))) ((f (f (f e (f m m)) e) (f (f (f e e) m) (f b m)))).\nsurgery id_r ((f (f (f e (f m m)) e) (f (f (f e e) m) (f b m)))) ((f (f (f e m) e) (f (f (f e e) m) (f b m)))).\nsurgery id_r ((f (f (f e m) e) (f (f (f e e) m) (f b m)))) ((f (f e e) (f (f (f e e) m) (f b m)))).\nsurgery id_l ((f (f e e) (f (f (f e e) m) (f b m)))) ((f e (f (f (f e e) m) (f b m)))).\nsurgery id_r ((f e (f (f (f e e) m) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_316: forall b: G, ((((e <+> (e <+> m)) <+> e) <+> e) <+> ((b <+> m) <+> (e <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e m)) e) e) (f (f b m) (f e (f m m))))) ((f (f (f (f e m) e) e) (f (f b m) (f e (f m m))))).\nsurgery id_r ((f (f (f (f e m) e) e) (f (f b m) (f e (f m m))))) ((f (f (f e e) e) (f (f b m) (f e (f m m))))).\nsurgery id_l ((f (f (f e e) e) (f (f b m) (f e (f m m))))) ((f (f e e) (f (f b m) (f e (f m m))))).\nsurgery id_l ((f (f e e) (f (f b m) (f e (f m m))))) ((f e (f (f b m) (f e (f m m))))).\nsurgery id_r ((f e (f (f b m) (f e (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_317: forall b: G, ((b <+> (((e <+> e) <+> (m <+> (e <+> m))) <+> (m <+> m))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f (f (f e e) (f m (f e m))) (f m m))) (f e m))) ((f (f b (f (f e (f m (f e m))) (f m m))) (f e m))).\nsurgery id_l ((f (f b (f (f e (f m (f e m))) (f m m))) (f e m))) ((f (f b (f (f e (f m m)) (f m m))) (f e m))).\nsurgery id_r ((f (f b (f (f e (f m m)) (f m m))) (f e m))) ((f (f b (f (f e m) (f m m))) (f e m))).\nsurgery id_r ((f (f b (f (f e m) (f m m))) (f e m))) ((f (f b (f e (f m m))) (f e m))).\nsurgery id_l ((f (f b (f e (f m m))) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_318: forall b: G, (((b <+> m) <+> ((e <+> (e <+> m)) <+> m)) <+> (((e <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f e (f e m)) m)) (f (f (f e m) m) m))) ((f (f b (f (f e (f e m)) m)) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f (f (f e m) m) m))) ((f (f b (f (f e m) m)) (f (f (f e m) m) m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f (f (f e m) m) m))) ((f (f b (f e m)) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f e m)) (f (f (f e m) m) m))) ((f (f b m) (f (f (f e m) m) m))).\nsurgery id_r ((f (f b m) (f (f (f e m) m) m))) ((f b (f (f (f e m) m) m))).\nsurgery id_r ((f b (f (f (f e m) m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_319: forall b: G, ((e <+> m) <+> (((e <+> e) <+> (e <+> e)) <+> (((e <+> e) <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e e) (f e e)) (f (f (f e e) b) m)))) ((f e (f (f (f e e) (f e e)) (f (f (f e e) b) m)))).\nsurgery id_l ((f e (f (f (f e e) (f e e)) (f (f (f e e) b) m)))) ((f e (f (f e (f e e)) (f (f (f e e) b) m)))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f (f e e) b) m)))) ((f e (f (f e e) (f (f (f e e) b) m)))).\nsurgery id_l ((f e (f (f e e) (f (f (f e e) b) m)))) ((f e (f e (f (f (f e e) b) m)))).\nsurgery id_l ((f e (f e (f (f (f e e) b) m)))) ((f e (f (f (f e e) b) m))).\nsurgery id_l ((f e (f (f (f e e) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_320: forall b: G, ((b <+> (e <+> (m <+> (e <+> (e <+> m))))) <+> ((e <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e (f m (f e (f e m))))) (f (f e m) (f m m)))) ((f (f b (f m (f e (f e m)))) (f (f e m) (f m m)))).\nsurgery id_l ((f (f b (f m (f e (f e m)))) (f (f e m) (f m m)))) ((f (f b (f m (f e m))) (f (f e m) (f m m)))).\nsurgery id_l ((f (f b (f m (f e m))) (f (f e m) (f m m)))) ((f (f b (f m m)) (f (f e m) (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f (f e m) (f m m)))) ((f (f b m) (f (f e m) (f m m)))).\nsurgery id_r ((f (f b m) (f (f e m) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_321: forall b: G, ((e <+> m) <+> ((((e <+> m) <+> (e <+> m)) <+> b) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f (f e m) (f e m)) b) (f e (f e m))))) ((f e (f (f (f (f e m) (f e m)) b) (f e (f e m))))).\nsurgery id_r ((f e (f (f (f (f e m) (f e m)) b) (f e (f e m))))) ((f e (f (f (f e (f e m)) b) (f e (f e m))))).\nsurgery id_l ((f e (f (f (f e (f e m)) b) (f e (f e m))))) ((f e (f (f (f e m) b) (f e (f e m))))).\nsurgery id_r ((f e (f (f (f e m) b) (f e (f e m))))) ((f e (f (f e b) (f e (f e m))))).\nsurgery id_l ((f e (f (f e b) (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_322: forall b: G, (((e <+> e) <+> ((e <+> m) <+> (m <+> (m <+> m)))) <+> ((e <+> m) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e m) (f m (f m m)))) (f (f e m) b))) ((f (f e (f (f e m) (f m (f m m)))) (f (f e m) b))).\nsurgery id_r ((f (f e (f (f e m) (f m (f m m)))) (f (f e m) b))) ((f (f e (f e (f m (f m m)))) (f (f e m) b))).\nsurgery id_l ((f (f e (f e (f m (f m m)))) (f (f e m) b))) ((f (f e (f m (f m m))) (f (f e m) b))).\nsurgery id_r ((f (f e (f m (f m m))) (f (f e m) b))) ((f (f e (f m m)) (f (f e m) b))).\nsurgery id_r ((f (f e (f m m)) (f (f e m) b))) ((f (f e m) (f (f e m) b))).\nsurgery id_r ((f (f e m) (f (f e m) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_323: forall b: G, (((e <+> (e <+> m)) <+> (e <+> e)) <+> ((b <+> m) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e e)) (f (f b m) (f e (f e m))))) ((f (f (f e m) (f e e)) (f (f b m) (f e (f e m))))).\nsurgery id_r ((f (f (f e m) (f e e)) (f (f b m) (f e (f e m))))) ((f (f e (f e e)) (f (f b m) (f e (f e m))))).\nsurgery id_l ((f (f e (f e e)) (f (f b m) (f e (f e m))))) ((f (f e e) (f (f b m) (f e (f e m))))).\nsurgery id_l ((f (f e e) (f (f b m) (f e (f e m))))) ((f e (f (f b m) (f e (f e m))))).\nsurgery id_r ((f e (f (f b m) (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_324: forall b: G, ((((e <+> m) <+> e) <+> ((e <+> (m <+> m)) <+> ((m <+> m) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f (f e (f m m)) (f (f m m) m))) b)) ((f (f (f e e) (f (f e (f m m)) (f (f m m) m))) b)).\nsurgery id_l ((f (f (f e e) (f (f e (f m m)) (f (f m m) m))) b)) ((f (f e (f (f e (f m m)) (f (f m m) m))) b)).\nsurgery id_r ((f (f e (f (f e (f m m)) (f (f m m) m))) b)) ((f (f e (f (f e m) (f (f m m) m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f (f m m) m))) b)) ((f (f e (f e (f (f m m) m))) b)).\nsurgery id_l ((f (f e (f e (f (f m m) m))) b)) ((f (f e (f (f m m) m)) b)).\nsurgery id_r ((f (f e (f (f m m) m)) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_325: forall b: G, (((e <+> e) <+> (((e <+> e) <+> e) <+> b)) <+> ((m <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f e e) e) b)) (f (f m m) (f e m)))) ((f (f e (f (f (f e e) e) b)) (f (f m m) (f e m)))).\nsurgery id_l ((f (f e (f (f (f e e) e) b)) (f (f m m) (f e m)))) ((f (f e (f (f e e) b)) (f (f m m) (f e m)))).\nsurgery id_l ((f (f e (f (f e e) b)) (f (f m m) (f e m)))) ((f (f e (f e b)) (f (f m m) (f e m)))).\nsurgery id_l ((f (f e (f e b)) (f (f m m) (f e m)))) ((f (f e b) (f (f m m) (f e m)))).\nsurgery id_l ((f (f e b) (f (f m m) (f e m)))) ((f b (f (f m m) (f e m)))).\nsurgery id_r ((f b (f (f m m) (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_326: forall b: G, ((e <+> ((m <+> m) <+> (m <+> (e <+> m)))) <+> ((b <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f m m) (f m (f e m)))) (f (f b m) (f e m)))) ((f (f e (f m (f m (f e m)))) (f (f b m) (f e m)))).\nsurgery id_l ((f (f e (f m (f m (f e m)))) (f (f b m) (f e m)))) ((f (f e (f m (f m m))) (f (f b m) (f e m)))).\nsurgery id_r ((f (f e (f m (f m m))) (f (f b m) (f e m)))) ((f (f e (f m m)) (f (f b m) (f e m)))).\nsurgery id_r ((f (f e (f m m)) (f (f b m) (f e m)))) ((f (f e m) (f (f b m) (f e m)))).\nsurgery id_r ((f (f e m) (f (f b m) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_327: forall b: G, ((e <+> (e <+> b)) <+> (((e <+> e) <+> ((m <+> m) <+> (e <+> m))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e b)) (f (f (f e e) (f (f m m) (f e m))) m))) ((f (f e b) (f (f (f e e) (f (f m m) (f e m))) m))).\nsurgery id_l ((f (f e b) (f (f (f e e) (f (f m m) (f e m))) m))) ((f b (f (f (f e e) (f (f m m) (f e m))) m))).\nsurgery id_l ((f b (f (f (f e e) (f (f m m) (f e m))) m))) ((f b (f (f e (f (f m m) (f e m))) m))).\nsurgery id_r ((f b (f (f e (f (f m m) (f e m))) m))) ((f b (f (f e (f m (f e m))) m))).\nsurgery id_l ((f b (f (f e (f m (f e m))) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_328: forall b: G, (((e <+> (e <+> (m <+> m))) <+> ((e <+> m) <+> (m <+> m))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f m m))) (f (f e m) (f m m))) (f e b))) ((f (f (f e (f m m)) (f (f e m) (f m m))) (f e b))).\nsurgery id_r ((f (f (f e (f m m)) (f (f e m) (f m m))) (f e b))) ((f (f (f e m) (f (f e m) (f m m))) (f e b))).\nsurgery id_r ((f (f (f e m) (f (f e m) (f m m))) (f e b))) ((f (f e (f (f e m) (f m m))) (f e b))).\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f e b))) ((f (f e (f e (f m m))) (f e b))).\nsurgery id_l ((f (f e (f e (f m m))) (f e b))) ((f (f e (f m m)) (f e b))).\nsurgery id_r ((f (f e (f m m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_329: forall b: G, (((e <+> ((e <+> e) <+> e)) <+> (e <+> (e <+> ((e <+> m) <+> e)))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f (f e e) e)) (f e (f e (f (f e m) e)))) b)) ((f (f (f e (f e e)) (f e (f e (f (f e m) e)))) b)).\nsurgery id_l ((f (f (f e (f e e)) (f e (f e (f (f e m) e)))) b)) ((f (f (f e e) (f e (f e (f (f e m) e)))) b)).\nsurgery id_l ((f (f (f e e) (f e (f e (f (f e m) e)))) b)) ((f (f e (f e (f e (f (f e m) e)))) b)).\nsurgery id_l ((f (f e (f e (f e (f (f e m) e)))) b)) ((f (f e (f e (f (f e m) e))) b)).\nsurgery id_l ((f (f e (f e (f (f e m) e))) b)) ((f (f e (f (f e m) e)) b)).\nsurgery id_r ((f (f e (f (f e m) e)) b)) ((f (f e (f e e)) b)).\nsurgery id_l ((f (f e (f e e)) b)) ((f (f e e) b)).\nsurgery id_l ((f (f e e) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_330: forall b: G, (((e <+> m) <+> (e <+> ((m <+> (m <+> (e <+> m))) <+> m))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e (f (f m (f m (f e m))) m))) (f e b))) ((f (f e (f e (f (f m (f m (f e m))) m))) (f e b))).\nsurgery id_l ((f (f e (f e (f (f m (f m (f e m))) m))) (f e b))) ((f (f e (f (f m (f m (f e m))) m)) (f e b))).\nsurgery id_l ((f (f e (f (f m (f m (f e m))) m)) (f e b))) ((f (f e (f (f m (f m m)) m)) (f e b))).\nsurgery id_r ((f (f e (f (f m (f m m)) m)) (f e b))) ((f (f e (f (f m m) m)) (f e b))).\nsurgery id_r ((f (f e (f (f m m) m)) (f e b))) ((f (f e (f m m)) (f e b))).\nsurgery id_r ((f (f e (f m m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_331: forall b: G, ((b <+> m) <+> ((e <+> e) <+> ((e <+> ((e <+> m) <+> (e <+> m))) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f e e) (f (f e (f (f e m) (f e m))) m)))) ((f b (f (f e e) (f (f e (f (f e m) (f e m))) m)))).\nsurgery id_l ((f b (f (f e e) (f (f e (f (f e m) (f e m))) m)))) ((f b (f e (f (f e (f (f e m) (f e m))) m)))).\nsurgery id_l ((f b (f e (f (f e (f (f e m) (f e m))) m)))) ((f b (f (f e (f (f e m) (f e m))) m))).\nsurgery id_r ((f b (f (f e (f (f e m) (f e m))) m))) ((f b (f (f e (f e (f e m))) m))).\nsurgery id_l ((f b (f (f e (f e (f e m))) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_332: forall b: G, (((e <+> m) <+> m) <+> (((e <+> ((e <+> e) <+> m)) <+> e) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) m) (f (f (f e (f (f e e) m)) e) (f b m)))) ((f (f e m) (f (f (f e (f (f e e) m)) e) (f b m)))).\nsurgery id_r ((f (f e m) (f (f (f e (f (f e e) m)) e) (f b m)))) ((f e (f (f (f e (f (f e e) m)) e) (f b m)))).\nsurgery id_l ((f e (f (f (f e (f (f e e) m)) e) (f b m)))) ((f e (f (f (f e (f e m)) e) (f b m)))).\nsurgery id_l ((f e (f (f (f e (f e m)) e) (f b m)))) ((f e (f (f (f e m) e) (f b m)))).\nsurgery id_r ((f e (f (f (f e m) e) (f b m)))) ((f e (f (f e e) (f b m)))).\nsurgery id_l ((f e (f (f e e) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_333: forall b: G, (((e <+> m) <+> e) <+> (b <+> (m <+> ((e <+> m) <+> ((m <+> m) <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) e) (f b (f m (f (f e m) (f (f m m) m)))))) ((f (f e e) (f b (f m (f (f e m) (f (f m m) m)))))).\nsurgery id_l ((f (f e e) (f b (f m (f (f e m) (f (f m m) m)))))) ((f e (f b (f m (f (f e m) (f (f m m) m)))))).\nsurgery id_r ((f e (f b (f m (f (f e m) (f (f m m) m)))))) ((f e (f b (f m (f e (f (f m m) m)))))).\nsurgery id_l ((f e (f b (f m (f e (f (f m m) m)))))) ((f e (f b (f m (f (f m m) m))))).\nsurgery id_r ((f e (f b (f m (f (f m m) m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_334: forall b: G, (((e <+> (m <+> m)) <+> b) <+> ((e <+> (e <+> (e <+> m))) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f m m)) b) (f (f e (f e (f e m))) (f m m)))) ((f (f (f e m) b) (f (f e (f e (f e m))) (f m m)))).\nsurgery id_r ((f (f (f e m) b) (f (f e (f e (f e m))) (f m m)))) ((f (f e b) (f (f e (f e (f e m))) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e (f e (f e m))) (f m m)))) ((f b (f (f e (f e (f e m))) (f m m)))).\nsurgery id_l ((f b (f (f e (f e (f e m))) (f m m)))) ((f b (f (f e (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_335: forall b: G, ((b <+> (e <+> (e <+> m))) <+> ((e <+> (((e <+> e) <+> e) <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e (f e m))) (f (f e (f (f (f e e) e) m)) m))) ((f (f b (f e m)) (f (f e (f (f (f e e) e) m)) m))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f (f (f e e) e) m)) m))) ((f (f b m) (f (f e (f (f (f e e) e) m)) m))).\nsurgery id_r ((f (f b m) (f (f e (f (f (f e e) e) m)) m))) ((f b (f (f e (f (f (f e e) e) m)) m))).\nsurgery id_l ((f b (f (f e (f (f (f e e) e) m)) m))) ((f b (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f b (f (f e (f (f e e) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_336: forall b: G, ((b <+> m) <+> (m <+> (((((e <+> (e <+> m)) <+> e) <+> e) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f m (f (f (f (f (f e (f e m)) e) e) m) m)))) ((f b (f m (f (f (f (f (f e (f e m)) e) e) m) m)))).\nsurgery id_r ((f b (f m (f (f (f (f (f e (f e m)) e) e) m) m)))) ((f b (f m (f (f (f (f e (f e m)) e) e) m)))).\nsurgery id_l ((f b (f m (f (f (f (f e (f e m)) e) e) m)))) ((f b (f m (f (f (f (f e m) e) e) m)))).\nsurgery id_r ((f b (f m (f (f (f (f e m) e) e) m)))) ((f b (f m (f (f (f e e) e) m)))).\nsurgery id_l ((f b (f m (f (f (f e e) e) m)))) ((f b (f m (f (f e e) m)))).\nsurgery id_l ((f b (f m (f (f e e) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_337: forall b: G, (((e <+> m) <+> (m <+> m)) <+> ((((e <+> e) <+> (e <+> e)) <+> e) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f m m)) (f (f (f (f e e) (f e e)) e) b))) ((f (f e (f m m)) (f (f (f (f e e) (f e e)) e) b))).\nsurgery id_r ((f (f e (f m m)) (f (f (f (f e e) (f e e)) e) b))) ((f (f e m) (f (f (f (f e e) (f e e)) e) b))).\nsurgery id_r ((f (f e m) (f (f (f (f e e) (f e e)) e) b))) ((f e (f (f (f (f e e) (f e e)) e) b))).\nsurgery id_l ((f e (f (f (f (f e e) (f e e)) e) b))) ((f e (f (f (f e (f e e)) e) b))).\nsurgery id_l ((f e (f (f (f e (f e e)) e) b))) ((f e (f (f (f e e) e) b))).\nsurgery id_l ((f e (f (f (f e e) e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_338: forall b: G, (((e <+> e) <+> (((e <+> b) <+> (m <+> m)) <+> ((e <+> e) <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e e) (f (f (f e b) (f m m)) (f (f e e) m))) m)) ((f (f e e) (f (f (f e b) (f m m)) (f (f e e) m)))).\nsurgery id_l ((f (f e e) (f (f (f e b) (f m m)) (f (f e e) m)))) ((f e (f (f (f e b) (f m m)) (f (f e e) m)))).\nsurgery id_l ((f e (f (f (f e b) (f m m)) (f (f e e) m)))) ((f e (f (f b (f m m)) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f (f e e) m)))) ((f e (f (f b m) (f (f e e) m)))).\nsurgery id_r ((f e (f (f b m) (f (f e e) m)))) ((f e (f b (f (f e e) m)))).\nsurgery id_l ((f e (f b (f (f e e) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_339: forall b: G, (((b <+> m) <+> (((e <+> m) <+> m) <+> m)) <+> (e <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f (f e m) m) m)) (f e (f e (f e m))))) ((f (f b (f (f (f e m) m) m)) (f e (f e (f e m))))).\nsurgery id_r ((f (f b (f (f (f e m) m) m)) (f e (f e (f e m))))) ((f (f b (f (f e m) m)) (f e (f e (f e m))))).\nsurgery id_r ((f (f b (f (f e m) m)) (f e (f e (f e m))))) ((f (f b (f e m)) (f e (f e (f e m))))).\nsurgery id_l ((f (f b (f e m)) (f e (f e (f e m))))) ((f (f b m) (f e (f e (f e m))))).\nsurgery id_r ((f (f b m) (f e (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_340: forall b: G, ((e <+> b) <+> (e <+> (((e <+> m) <+> ((e <+> m) <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f e (f (f (f e m) (f (f e m) m)) (f m m))))) ((f b (f e (f (f (f e m) (f (f e m) m)) (f m m))))).\nsurgery id_l ((f b (f e (f (f (f e m) (f (f e m) m)) (f m m))))) ((f b (f (f (f e m) (f (f e m) m)) (f m m)))).\nsurgery id_r ((f b (f (f (f e m) (f (f e m) m)) (f m m)))) ((f b (f (f e (f (f e m) m)) (f m m)))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) (f m m)))) ((f b (f (f e (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_341: forall b: G, ((e <+> ((e <+> ((e <+> e) <+> (m <+> m))) <+> m)) <+> ((b <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e (f (f e e) (f m m))) m)) (f (f b m) m))) ((f (f e (f (f e (f e (f m m))) m)) (f (f b m) m))).\nsurgery id_l ((f (f e (f (f e (f e (f m m))) m)) (f (f b m) m))) ((f (f e (f (f e (f m m)) m)) (f (f b m) m))).\nsurgery id_r ((f (f e (f (f e (f m m)) m)) (f (f b m) m))) ((f (f e (f (f e m) m)) (f (f b m) m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f b m) m))) ((f (f e (f e m)) (f (f b m) m))).\nsurgery id_l ((f (f e (f e m)) (f (f b m) m))) ((f (f e m) (f (f b m) m))).\nsurgery id_r ((f (f e m) (f (f b m) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_342: forall b: G, (b <+> ((m <+> m) <+> ((e <+> (m <+> (e <+> m))) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f m m) (f (f e (f m (f e m))) (f e (f m m)))))) ((f b (f m (f (f e (f m (f e m))) (f e (f m m)))))).\nsurgery id_l ((f b (f m (f (f e (f m (f e m))) (f e (f m m)))))) ((f b (f m (f (f e (f m m)) (f e (f m m)))))).\nsurgery id_r ((f b (f m (f (f e (f m m)) (f e (f m m)))))) ((f b (f m (f (f e m) (f e (f m m)))))).\nsurgery id_r ((f b (f m (f (f e m) (f e (f m m)))))) ((f b (f m (f e (f e (f m m)))))).\nsurgery id_l ((f b (f m (f e (f e (f m m)))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_343: forall b: G, ((((e <+> b) <+> m) <+> (m <+> (m <+> m))) <+> (m <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e b) m) (f m (f m m))) (f m (f e (f e m))))) ((f (f (f e b) (f m (f m m))) (f m (f e (f e m))))).\nsurgery id_l ((f (f (f e b) (f m (f m m))) (f m (f e (f e m))))) ((f (f b (f m (f m m))) (f m (f e (f e m))))).\nsurgery id_r ((f (f b (f m (f m m))) (f m (f e (f e m))))) ((f (f b (f m m)) (f m (f e (f e m))))).\nsurgery id_r ((f (f b (f m m)) (f m (f e (f e m))))) ((f (f b m) (f m (f e (f e m))))).\nsurgery id_r ((f (f b m) (f m (f e (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_344: forall b: G, (((e <+> (e <+> m)) <+> (m <+> m)) <+> (e <+> (e <+> (b <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f m m)) (f e (f e (f b (f m m)))))) ((f (f (f e m) (f m m)) (f e (f e (f b (f m m)))))).\nsurgery id_r ((f (f (f e m) (f m m)) (f e (f e (f b (f m m)))))) ((f (f e (f m m)) (f e (f e (f b (f m m)))))).\nsurgery id_r ((f (f e (f m m)) (f e (f e (f b (f m m)))))) ((f (f e m) (f e (f e (f b (f m m)))))).\nsurgery id_r ((f (f e m) (f e (f e (f b (f m m)))))) ((f e (f e (f e (f b (f m m)))))).\nsurgery id_l ((f e (f e (f e (f b (f m m)))))) ((f e (f e (f b (f m m))))).\nsurgery id_l ((f e (f e (f b (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_345: forall b: G, ((b <+> ((e <+> m) <+> m)) <+> ((e <+> (e <+> m)) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e m) m)) (f (f e (f e m)) (f e (f e m))))) ((f (f b (f e m)) (f (f e (f e m)) (f e (f e m))))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f e m)) (f e (f e m))))) ((f (f b m) (f (f e (f e m)) (f e (f e m))))).\nsurgery id_r ((f (f b m) (f (f e (f e m)) (f e (f e m))))) ((f b (f (f e (f e m)) (f e (f e m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f e (f e m))))) ((f b (f (f e m) (f e (f e m))))).\nsurgery id_r ((f b (f (f e m) (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_346: forall b: G, ((((e <+> e) <+> (m <+> m)) <+> (((e <+> m) <+> m) <+> (b <+> m))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f m m)) (f (f (f e m) m) (f b m))) m)) ((f (f (f e e) (f m m)) (f (f (f e m) m) (f b m)))).\nsurgery id_l ((f (f (f e e) (f m m)) (f (f (f e m) m) (f b m)))) ((f (f e (f m m)) (f (f (f e m) m) (f b m)))).\nsurgery id_r ((f (f e (f m m)) (f (f (f e m) m) (f b m)))) ((f (f e m) (f (f (f e m) m) (f b m)))).\nsurgery id_r ((f (f e m) (f (f (f e m) m) (f b m)))) ((f e (f (f (f e m) m) (f b m)))).\nsurgery id_r ((f e (f (f (f e m) m) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_347: forall b: G, (((e <+> m) <+> (((e <+> (e <+> e)) <+> (e <+> m)) <+> b)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f (f e (f e e)) (f e m)) b)) (f m m))) ((f (f e (f (f (f e (f e e)) (f e m)) b)) (f m m))).\nsurgery id_l ((f (f e (f (f (f e (f e e)) (f e m)) b)) (f m m))) ((f (f e (f (f (f e e) (f e m)) b)) (f m m))).\nsurgery id_l ((f (f e (f (f (f e e) (f e m)) b)) (f m m))) ((f (f e (f (f e (f e m)) b)) (f m m))).\nsurgery id_l ((f (f e (f (f e (f e m)) b)) (f m m))) ((f (f e (f (f e m) b)) (f m m))).\nsurgery id_r ((f (f e (f (f e m) b)) (f m m))) ((f (f e (f e b)) (f m m))).\nsurgery id_l ((f (f e (f e b)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_348: forall b: G, ((b <+> (e <+> m)) <+> ((m <+> ((e <+> m) <+> m)) <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e m)) (f (f m (f (f e m) m)) (f m (f m m))))) ((f (f b m) (f (f m (f (f e m) m)) (f m (f m m))))).\nsurgery id_r ((f (f b m) (f (f m (f (f e m) m)) (f m (f m m))))) ((f b (f (f m (f (f e m) m)) (f m (f m m))))).\nsurgery id_r ((f b (f (f m (f (f e m) m)) (f m (f m m))))) ((f b (f (f m (f e m)) (f m (f m m))))).\nsurgery id_l ((f b (f (f m (f e m)) (f m (f m m))))) ((f b (f (f m m) (f m (f m m))))).\nsurgery id_r ((f b (f (f m m) (f m (f m m))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_349: forall b: G, ((e <+> m) <+> (b <+> (e <+> ((((m <+> m) <+> m) <+> m) <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f b (f e (f (f (f (f m m) m) m) (f e m)))))) ((f e (f b (f e (f (f (f (f m m) m) m) (f e m)))))).\nsurgery id_l ((f e (f b (f e (f (f (f (f m m) m) m) (f e m)))))) ((f e (f b (f (f (f (f m m) m) m) (f e m))))).\nsurgery id_r ((f e (f b (f (f (f (f m m) m) m) (f e m))))) ((f e (f b (f (f (f m m) m) (f e m))))).\nsurgery id_r ((f e (f b (f (f (f m m) m) (f e m))))) ((f e (f b (f (f m m) (f e m))))).\nsurgery id_r ((f e (f b (f (f m m) (f e m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_350: forall b: G, ((e <+> m) <+> (b <+> (((((e <+> e) <+> m) <+> (e <+> m)) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f b (f (f (f (f (f e e) m) (f e m)) m) m)))) ((f e (f b (f (f (f (f (f e e) m) (f e m)) m) m)))).\nsurgery id_r ((f e (f b (f (f (f (f (f e e) m) (f e m)) m) m)))) ((f e (f b (f (f (f (f e e) m) (f e m)) m)))).\nsurgery id_r ((f e (f b (f (f (f (f e e) m) (f e m)) m)))) ((f e (f b (f (f (f e e) (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f (f e e) (f e m)) m)))) ((f e (f b (f (f e (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f e (f e m)) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_351: forall b: G, (((e <+> (((e <+> m) <+> m) <+> (m <+> m))) <+> m) <+> ((e <+> b) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f (f e m) m) (f m m))) m) (f (f e b) m))) ((f (f e (f (f (f e m) m) (f m m))) (f (f e b) m))).\nsurgery id_r ((f (f e (f (f (f e m) m) (f m m))) (f (f e b) m))) ((f (f e (f (f e m) (f m m))) (f (f e b) m))).\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f (f e b) m))) ((f (f e (f e (f m m))) (f (f e b) m))).\nsurgery id_l ((f (f e (f e (f m m))) (f (f e b) m))) ((f (f e (f m m)) (f (f e b) m))).\nsurgery id_r ((f (f e (f m m)) (f (f e b) m))) ((f (f e m) (f (f e b) m))).\nsurgery id_r ((f (f e m) (f (f e b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_352: forall b: G, ((b <+> m) <+> ((e <+> (m <+> m)) <+> ((((e <+> m) <+> e) <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f e (f m m)) (f (f (f (f e m) e) m) m)))) ((f b (f (f e (f m m)) (f (f (f (f e m) e) m) m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f (f (f e m) e) m) m)))) ((f b (f (f e m) (f (f (f (f e m) e) m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f (f (f e m) e) m) m)))) ((f b (f e (f (f (f (f e m) e) m) m)))).\nsurgery id_l ((f b (f e (f (f (f (f e m) e) m) m)))) ((f b (f (f (f (f e m) e) m) m))).\nsurgery id_r ((f b (f (f (f (f e m) e) m) m))) ((f b (f (f (f e m) e) m))).\nsurgery id_r ((f b (f (f (f e m) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_353: forall b: G, ((e <+> (e <+> b)) <+> (((m <+> m) <+> (m <+> m)) <+> ((m <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e b)) (f (f (f m m) (f m m)) (f (f m m) m)))) ((f (f e b) (f (f (f m m) (f m m)) (f (f m m) m)))).\nsurgery id_l ((f (f e b) (f (f (f m m) (f m m)) (f (f m m) m)))) ((f b (f (f (f m m) (f m m)) (f (f m m) m)))).\nsurgery id_r ((f b (f (f (f m m) (f m m)) (f (f m m) m)))) ((f b (f (f m (f m m)) (f (f m m) m)))).\nsurgery id_r ((f b (f (f m (f m m)) (f (f m m) m)))) ((f b (f (f m m) (f (f m m) m)))).\nsurgery id_r ((f b (f (f m m) (f (f m m) m)))) ((f b (f m (f (f m m) m)))).\nsurgery id_r ((f b (f m (f (f m m) m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_354: forall b: G, (((e <+> m) <+> (m <+> ((e <+> e) <+> m))) <+> (e <+> (b <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f m (f (f e e) m))) (f e (f b (f e m))))) ((f (f e (f m (f (f e e) m))) (f e (f b (f e m))))).\nsurgery id_l ((f (f e (f m (f (f e e) m))) (f e (f b (f e m))))) ((f (f e (f m (f e m))) (f e (f b (f e m))))).\nsurgery id_l ((f (f e (f m (f e m))) (f e (f b (f e m))))) ((f (f e (f m m)) (f e (f b (f e m))))).\nsurgery id_r ((f (f e (f m m)) (f e (f b (f e m))))) ((f (f e m) (f e (f b (f e m))))).\nsurgery id_r ((f (f e m) (f e (f b (f e m))))) ((f e (f e (f b (f e m))))).\nsurgery id_l ((f e (f e (f b (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_355: forall b: G, ((e <+> (e <+> (e <+> e))) <+> (e <+> (b <+> ((e <+> (e <+> m)) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e (f e e))) (f e (f b (f (f e (f e m)) m))))) ((f (f e (f e e)) (f e (f b (f (f e (f e m)) m))))).\nsurgery id_l ((f (f e (f e e)) (f e (f b (f (f e (f e m)) m))))) ((f (f e e) (f e (f b (f (f e (f e m)) m))))).\nsurgery id_l ((f (f e e) (f e (f b (f (f e (f e m)) m))))) ((f e (f e (f b (f (f e (f e m)) m))))).\nsurgery id_l ((f e (f e (f b (f (f e (f e m)) m))))) ((f e (f b (f (f e (f e m)) m)))).\nsurgery id_l ((f e (f b (f (f e (f e m)) m)))) ((f e (f b (f (f e m) m)))).\nsurgery id_r ((f e (f b (f (f e m) m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_356: forall b: G, (((e <+> (e <+> m)) <+> b) <+> ((e <+> m) <+> ((e <+> (e <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) b) (f (f e m) (f (f e (f e m)) m)))) ((f (f (f e m) b) (f (f e m) (f (f e (f e m)) m)))).\nsurgery id_r ((f (f (f e m) b) (f (f e m) (f (f e (f e m)) m)))) ((f (f e b) (f (f e m) (f (f e (f e m)) m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f (f e (f e m)) m)))) ((f b (f (f e m) (f (f e (f e m)) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e (f e m)) m)))) ((f b (f e (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f e (f (f e (f e m)) m)))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_357: forall b: G, ((e <+> (e <+> b)) <+> (((m <+> m) <+> ((e <+> m) <+> m)) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e b)) (f (f (f m m) (f (f e m) m)) (f e m)))) ((f (f e b) (f (f (f m m) (f (f e m) m)) (f e m)))).\nsurgery id_l ((f (f e b) (f (f (f m m) (f (f e m) m)) (f e m)))) ((f b (f (f (f m m) (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f (f m m) (f (f e m) m)) (f e m)))) ((f b (f (f m (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f m (f (f e m) m)) (f e m)))) ((f b (f (f m (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f m (f e m)) (f e m)))) ((f b (f (f m m) (f e m)))).\nsurgery id_r ((f b (f (f m m) (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_358: forall b: G, ((e <+> e) <+> ((e <+> (e <+> (((e <+> (m <+> m)) <+> m) <+> m))) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f e (f e (f (f (f e (f m m)) m) m))) b))) ((f e (f (f e (f e (f (f (f e (f m m)) m) m))) b))).\nsurgery id_l ((f e (f (f e (f e (f (f (f e (f m m)) m) m))) b))) ((f e (f (f e (f (f (f e (f m m)) m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f (f e (f m m)) m) m)) b))) ((f e (f (f e (f (f e (f m m)) m)) b))).\nsurgery id_r ((f e (f (f e (f (f e (f m m)) m)) b))) ((f e (f (f e (f (f e m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) b))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_359: forall b: G, (((e <+> ((e <+> m) <+> e)) <+> e) <+> ((e <+> (m <+> m)) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) e)) e) (f (f e (f m m)) (f e b)))) ((f (f (f e (f e e)) e) (f (f e (f m m)) (f e b)))).\nsurgery id_l ((f (f (f e (f e e)) e) (f (f e (f m m)) (f e b)))) ((f (f (f e e) e) (f (f e (f m m)) (f e b)))).\nsurgery id_l ((f (f (f e e) e) (f (f e (f m m)) (f e b)))) ((f (f e e) (f (f e (f m m)) (f e b)))).\nsurgery id_l ((f (f e e) (f (f e (f m m)) (f e b)))) ((f e (f (f e (f m m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f m m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_360: forall b: G, ((((e <+> e) <+> m) <+> e) <+> ((((e <+> m) <+> m) <+> (e <+> e)) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) e) (f (f (f (f e m) m) (f e e)) b))) ((f (f (f e e) e) (f (f (f (f e m) m) (f e e)) b))).\nsurgery id_l ((f (f (f e e) e) (f (f (f (f e m) m) (f e e)) b))) ((f (f e e) (f (f (f (f e m) m) (f e e)) b))).\nsurgery id_l ((f (f e e) (f (f (f (f e m) m) (f e e)) b))) ((f e (f (f (f (f e m) m) (f e e)) b))).\nsurgery id_r ((f e (f (f (f (f e m) m) (f e e)) b))) ((f e (f (f (f e m) (f e e)) b))).\nsurgery id_r ((f e (f (f (f e m) (f e e)) b))) ((f e (f (f e (f e e)) b))).\nsurgery id_l ((f e (f (f e (f e e)) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_361: forall b: G, ((((e <+> m) <+> ((e <+> e) <+> e)) <+> m) <+> ((e <+> b) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f (f e e) e)) m) (f (f e b) (f e m)))) ((f (f (f e m) (f (f e e) e)) (f (f e b) (f e m)))).\nsurgery id_r ((f (f (f e m) (f (f e e) e)) (f (f e b) (f e m)))) ((f (f e (f (f e e) e)) (f (f e b) (f e m)))).\nsurgery id_l ((f (f e (f (f e e) e)) (f (f e b) (f e m)))) ((f (f e (f e e)) (f (f e b) (f e m)))).\nsurgery id_l ((f (f e (f e e)) (f (f e b) (f e m)))) ((f (f e e) (f (f e b) (f e m)))).\nsurgery id_l ((f (f e e) (f (f e b) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_362: forall b: G, ((b <+> ((e <+> m) <+> m)) <+> (((m <+> m) <+> m) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e m) m)) (f (f (f m m) m) (f e (f e m))))) ((f (f b (f e m)) (f (f (f m m) m) (f e (f e m))))).\nsurgery id_l ((f (f b (f e m)) (f (f (f m m) m) (f e (f e m))))) ((f (f b m) (f (f (f m m) m) (f e (f e m))))).\nsurgery id_r ((f (f b m) (f (f (f m m) m) (f e (f e m))))) ((f b (f (f (f m m) m) (f e (f e m))))).\nsurgery id_r ((f b (f (f (f m m) m) (f e (f e m))))) ((f b (f (f m m) (f e (f e m))))).\nsurgery id_r ((f b (f (f m m) (f e (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_363: forall b: G, ((e <+> ((((e <+> e) <+> m) <+> e) <+> (b <+> m))) <+> ((e <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f (f e e) m) e) (f b m))) (f (f e e) m))) ((f (f e (f (f (f e e) e) (f b m))) (f (f e e) m))).\nsurgery id_l ((f (f e (f (f (f e e) e) (f b m))) (f (f e e) m))) ((f (f e (f (f e e) (f b m))) (f (f e e) m))).\nsurgery id_l ((f (f e (f (f e e) (f b m))) (f (f e e) m))) ((f (f e (f e (f b m))) (f (f e e) m))).\nsurgery id_l ((f (f e (f e (f b m))) (f (f e e) m))) ((f (f e (f b m)) (f (f e e) m))).\nsurgery id_r ((f (f e (f b m)) (f (f e e) m))) ((f (f e b) (f (f e e) m))).\nsurgery id_l ((f (f e b) (f (f e e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_364: forall b: G, (((e <+> (e <+> m)) <+> e) <+> ((e <+> m) <+> ((e <+> e) <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) e) (f (f e m) (f (f e e) (f e b))))) ((f (f (f e m) e) (f (f e m) (f (f e e) (f e b))))).\nsurgery id_r ((f (f (f e m) e) (f (f e m) (f (f e e) (f e b))))) ((f (f e e) (f (f e m) (f (f e e) (f e b))))).\nsurgery id_l ((f (f e e) (f (f e m) (f (f e e) (f e b))))) ((f e (f (f e m) (f (f e e) (f e b))))).\nsurgery id_r ((f e (f (f e m) (f (f e e) (f e b))))) ((f e (f e (f (f e e) (f e b))))).\nsurgery id_l ((f e (f e (f (f e e) (f e b))))) ((f e (f (f e e) (f e b)))).\nsurgery id_l ((f e (f (f e e) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_365: forall b: G, (((e <+> m) <+> (b <+> ((m <+> m) <+> (m <+> m)))) <+> (e <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f b (f (f m m) (f m m)))) (f e (f e m)))) ((f (f e (f b (f (f m m) (f m m)))) (f e (f e m)))).\nsurgery id_r ((f (f e (f b (f (f m m) (f m m)))) (f e (f e m)))) ((f (f e (f b (f m (f m m)))) (f e (f e m)))).\nsurgery id_r ((f (f e (f b (f m (f m m)))) (f e (f e m)))) ((f (f e (f b (f m m))) (f e (f e m)))).\nsurgery id_r ((f (f e (f b (f m m))) (f e (f e m)))) ((f (f e (f b m)) (f e (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f e (f e m)))) ((f (f e b) (f e (f e m)))).\nsurgery id_l ((f (f e b) (f e (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_366: forall b: G, (((((e <+> e) <+> e) <+> ((e <+> e) <+> (e <+> m))) <+> (e <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f (f e e) e) (f (f e e) (f e m))) (f e m)) b)) ((f (f (f (f e e) (f (f e e) (f e m))) (f e m)) b)).\nsurgery id_l ((f (f (f (f e e) (f (f e e) (f e m))) (f e m)) b)) ((f (f (f e (f (f e e) (f e m))) (f e m)) b)).\nsurgery id_l ((f (f (f e (f (f e e) (f e m))) (f e m)) b)) ((f (f (f e (f e (f e m))) (f e m)) b)).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e m)) b)) ((f (f (f e (f e m)) (f e m)) b)).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) b)) ((f (f (f e m) (f e m)) b)).\nsurgery id_r ((f (f (f e m) (f e m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_367: forall b: G, ((e <+> e) <+> ((((e <+> m) <+> e) <+> ((e <+> e) <+> m)) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f (f e m) e) (f (f e e) m)) (f e b)))) ((f e (f (f (f (f e m) e) (f (f e e) m)) (f e b)))).\nsurgery id_r ((f e (f (f (f (f e m) e) (f (f e e) m)) (f e b)))) ((f e (f (f (f e e) (f (f e e) m)) (f e b)))).\nsurgery id_l ((f e (f (f (f e e) (f (f e e) m)) (f e b)))) ((f e (f (f e (f (f e e) m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f (f e e) m)) (f e b)))) ((f e (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_368: forall b: G, ((b <+> m) <+> ((m <+> (e <+> m)) <+> ((m <+> (e <+> m)) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f m (f e m)) (f (f m (f e m)) (f e m))))) ((f b (f (f m (f e m)) (f (f m (f e m)) (f e m))))).\nsurgery id_l ((f b (f (f m (f e m)) (f (f m (f e m)) (f e m))))) ((f b (f (f m m) (f (f m (f e m)) (f e m))))).\nsurgery id_r ((f b (f (f m m) (f (f m (f e m)) (f e m))))) ((f b (f m (f (f m (f e m)) (f e m))))).\nsurgery id_l ((f b (f m (f (f m (f e m)) (f e m))))) ((f b (f m (f (f m m) (f e m))))).\nsurgery id_r ((f b (f m (f (f m m) (f e m))))) ((f b (f m (f m (f e m))))).\nsurgery id_l ((f b (f m (f m (f e m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_369: forall b: G, ((e <+> e) <+> ((e <+> (e <+> m)) <+> (((e <+> e) <+> b) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f e (f e m)) (f (f (f e e) b) (f m m))))) ((f e (f (f e (f e m)) (f (f (f e e) b) (f m m))))).\nsurgery id_l ((f e (f (f e (f e m)) (f (f (f e e) b) (f m m))))) ((f e (f (f e m) (f (f (f e e) b) (f m m))))).\nsurgery id_r ((f e (f (f e m) (f (f (f e e) b) (f m m))))) ((f e (f e (f (f (f e e) b) (f m m))))).\nsurgery id_l ((f e (f e (f (f (f e e) b) (f m m))))) ((f e (f (f (f e e) b) (f m m)))).\nsurgery id_l ((f e (f (f (f e e) b) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_370: forall b: G, ((e <+> ((e <+> (e <+> m)) <+> m)) <+> (e <+> ((e <+> m) <+> (e <+> b)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e (f e m)) m)) (f e (f (f e m) (f e b))))) ((f (f e (f (f e m) m)) (f e (f (f e m) (f e b))))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e (f (f e m) (f e b))))) ((f (f e (f e m)) (f e (f (f e m) (f e b))))).\nsurgery id_l ((f (f e (f e m)) (f e (f (f e m) (f e b))))) ((f (f e m) (f e (f (f e m) (f e b))))).\nsurgery id_r ((f (f e m) (f e (f (f e m) (f e b))))) ((f e (f e (f (f e m) (f e b))))).\nsurgery id_l ((f e (f e (f (f e m) (f e b))))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_371: forall b: G, (((e <+> e) <+> m) <+> (((b <+> m) <+> m) <+> ((m <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e e) m) (f (f (f b m) m) (f (f m m) (f e m))))) ((f (f e e) (f (f (f b m) m) (f (f m m) (f e m))))).\nsurgery id_l ((f (f e e) (f (f (f b m) m) (f (f m m) (f e m))))) ((f e (f (f (f b m) m) (f (f m m) (f e m))))).\nsurgery id_r ((f e (f (f (f b m) m) (f (f m m) (f e m))))) ((f e (f (f b m) (f (f m m) (f e m))))).\nsurgery id_r ((f e (f (f b m) (f (f m m) (f e m))))) ((f e (f b (f (f m m) (f e m))))).\nsurgery id_r ((f e (f b (f (f m m) (f e m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_372: forall b: G, ((((e <+> (m <+> m)) <+> b) <+> m) <+> (m <+> (m <+> (e <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f m m)) b) m) (f m (f m (f e (f e m)))))) ((f (f (f e (f m m)) b) (f m (f m (f e (f e m)))))).\nsurgery id_r ((f (f (f e (f m m)) b) (f m (f m (f e (f e m)))))) ((f (f (f e m) b) (f m (f m (f e (f e m)))))).\nsurgery id_r ((f (f (f e m) b) (f m (f m (f e (f e m)))))) ((f (f e b) (f m (f m (f e (f e m)))))).\nsurgery id_l ((f (f e b) (f m (f m (f e (f e m)))))) ((f b (f m (f m (f e (f e m)))))).\nsurgery id_l ((f b (f m (f m (f e (f e m)))))) ((f b (f m (f m (f e m))))).\nsurgery id_l ((f b (f m (f m (f e m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_373: forall b: G, ((((e <+> m) <+> (m <+> m)) <+> b) <+> (e <+> ((m <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f m m)) b) (f e (f (f m m) (f e m))))) ((f (f (f e (f m m)) b) (f e (f (f m m) (f e m))))).\nsurgery id_r ((f (f (f e (f m m)) b) (f e (f (f m m) (f e m))))) ((f (f (f e m) b) (f e (f (f m m) (f e m))))).\nsurgery id_r ((f (f (f e m) b) (f e (f (f m m) (f e m))))) ((f (f e b) (f e (f (f m m) (f e m))))).\nsurgery id_l ((f (f e b) (f e (f (f m m) (f e m))))) ((f b (f e (f (f m m) (f e m))))).\nsurgery id_l ((f b (f e (f (f m m) (f e m))))) ((f b (f (f m m) (f e m)))).\nsurgery id_r ((f b (f (f m m) (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_374: forall b: G, ((e <+> ((e <+> m) <+> (m <+> m))) <+> (b <+> ((e <+> e) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e m) (f m m))) (f b (f (f e e) (f m m))))) ((f (f e (f e (f m m))) (f b (f (f e e) (f m m))))).\nsurgery id_l ((f (f e (f e (f m m))) (f b (f (f e e) (f m m))))) ((f (f e (f m m)) (f b (f (f e e) (f m m))))).\nsurgery id_r ((f (f e (f m m)) (f b (f (f e e) (f m m))))) ((f (f e m) (f b (f (f e e) (f m m))))).\nsurgery id_r ((f (f e m) (f b (f (f e e) (f m m))))) ((f e (f b (f (f e e) (f m m))))).\nsurgery id_l ((f e (f b (f (f e e) (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_375: forall b: G, ((e <+> m) <+> ((((e <+> (e <+> m)) <+> m) <+> ((e <+> m) <+> m)) <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f (f e (f e m)) m) (f (f e m) m)) b))) ((f e (f (f (f (f e (f e m)) m) (f (f e m) m)) b))).\nsurgery id_r ((f e (f (f (f (f e (f e m)) m) (f (f e m) m)) b))) ((f e (f (f (f e (f e m)) (f (f e m) m)) b))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f (f e m) m)) b))) ((f e (f (f (f e m) (f (f e m) m)) b))).\nsurgery id_r ((f e (f (f (f e m) (f (f e m) m)) b))) ((f e (f (f e (f (f e m) m)) b))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) b))) ((f e (f (f e (f e m)) b))).\nsurgery id_l ((f e (f (f e (f e m)) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_376: forall b: G, (((e <+> (e <+> m)) <+> (e <+> b)) <+> (m <+> (e <+> (m <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e b)) (f m (f e (f m (f e m)))))) ((f (f (f e m) (f e b)) (f m (f e (f m (f e m)))))).\nsurgery id_r ((f (f (f e m) (f e b)) (f m (f e (f m (f e m)))))) ((f (f e (f e b)) (f m (f e (f m (f e m)))))).\nsurgery id_l ((f (f e (f e b)) (f m (f e (f m (f e m)))))) ((f (f e b) (f m (f e (f m (f e m)))))).\nsurgery id_l ((f (f e b) (f m (f e (f m (f e m)))))) ((f b (f m (f e (f m (f e m)))))).\nsurgery id_l ((f b (f m (f e (f m (f e m)))))) ((f b (f m (f m (f e m))))).\nsurgery id_l ((f b (f m (f m (f e m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_377: forall b: G, ((((e <+> e) <+> m) <+> ((e <+> e) <+> ((e <+> e) <+> e))) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f (f e e) (f (f e e) e))) (f e b))) ((f (f (f e e) (f (f e e) (f (f e e) e))) (f e b))).\nsurgery id_l ((f (f (f e e) (f (f e e) (f (f e e) e))) (f e b))) ((f (f e (f (f e e) (f (f e e) e))) (f e b))).\nsurgery id_l ((f (f e (f (f e e) (f (f e e) e))) (f e b))) ((f (f e (f e (f (f e e) e))) (f e b))).\nsurgery id_l ((f (f e (f e (f (f e e) e))) (f e b))) ((f (f e (f (f e e) e)) (f e b))).\nsurgery id_l ((f (f e (f (f e e) e)) (f e b))) ((f (f e (f e e)) (f e b))).\nsurgery id_l ((f (f e (f e e)) (f e b))) ((f (f e e) (f e b))).\nsurgery id_l ((f (f e e) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_378: forall b: G, (b <+> (((e <+> m) <+> (e <+> (e <+> (m <+> m)))) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e m) (f e (f e (f m m)))) (f (f e m) m)))) ((f b (f (f e (f e (f e (f m m)))) (f (f e m) m)))).\nsurgery id_l ((f b (f (f e (f e (f e (f m m)))) (f (f e m) m)))) ((f b (f (f e (f e (f m m))) (f (f e m) m)))).\nsurgery id_l ((f b (f (f e (f e (f m m))) (f (f e m) m)))) ((f b (f (f e (f m m)) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f e m) m)))) ((f b (f (f e m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e m) m)))) ((f b (f e (f (f e m) m)))).\nsurgery id_l ((f b (f e (f (f e m) m)))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_379: forall b: G, (((e <+> (e <+> ((e <+> b) <+> (e <+> m)))) <+> (m <+> m)) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f (f e b) (f e m)))) (f m m)) (f e m))) ((f (f (f e (f (f e b) (f e m))) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e (f (f e b) (f e m))) (f m m)) (f e m))) ((f (f (f e (f b (f e m))) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e (f b (f e m))) (f m m)) (f e m))) ((f (f (f e (f b m)) (f m m)) (f e m))).\nsurgery id_r ((f (f (f e (f b m)) (f m m)) (f e m))) ((f (f (f e b) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e b) (f m m)) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_380: forall b: G, (b <+> ((e <+> e) <+> ((e <+> (m <+> (m <+> m))) <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f e e) (f (f e (f m (f m m))) (f (f e m) m))))) ((f b (f e (f (f e (f m (f m m))) (f (f e m) m))))).\nsurgery id_l ((f b (f e (f (f e (f m (f m m))) (f (f e m) m))))) ((f b (f (f e (f m (f m m))) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e (f m (f m m))) (f (f e m) m)))) ((f b (f (f e (f m m)) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f e m) m)))) ((f b (f (f e m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e m) m)))) ((f b (f e (f (f e m) m)))).\nsurgery id_l ((f b (f e (f (f e m) m)))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_381: forall b: G, (((e <+> e) <+> ((e <+> m) <+> (e <+> (e <+> b)))) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e m) (f e (f e b)))) (f e (f m m)))) ((f (f e (f (f e m) (f e (f e b)))) (f e (f m m)))).\nsurgery id_r ((f (f e (f (f e m) (f e (f e b)))) (f e (f m m)))) ((f (f e (f e (f e (f e b)))) (f e (f m m)))).\nsurgery id_l ((f (f e (f e (f e (f e b)))) (f e (f m m)))) ((f (f e (f e (f e b))) (f e (f m m)))).\nsurgery id_l ((f (f e (f e (f e b))) (f e (f m m)))) ((f (f e (f e b)) (f e (f m m)))).\nsurgery id_l ((f (f e (f e b)) (f e (f m m)))) ((f (f e b) (f e (f m m)))).\nsurgery id_l ((f (f e b) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_382: forall b: G, ((((e <+> b) <+> ((e <+> (e <+> (e <+> m))) <+> (m <+> m))) <+> m) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e b) (f (f e (f e (f e m))) (f m m))) m) m)) ((f (f (f e b) (f (f e (f e (f e m))) (f m m))) m)).\nsurgery id_r ((f (f (f e b) (f (f e (f e (f e m))) (f m m))) m)) ((f (f e b) (f (f e (f e (f e m))) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e (f e (f e m))) (f m m)))) ((f b (f (f e (f e (f e m))) (f m m)))).\nsurgery id_l ((f b (f (f e (f e (f e m))) (f m m)))) ((f b (f (f e (f e m)) (f m m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_383: forall b: G, (b <+> ((m <+> (e <+> m)) <+> (m <+> (((e <+> m) <+> m) <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f b (f (f m (f e m)) (f m (f (f (f e m) m) (f m m)))))) ((f b (f (f m m) (f m (f (f (f e m) m) (f m m)))))).\nsurgery id_r ((f b (f (f m m) (f m (f (f (f e m) m) (f m m)))))) ((f b (f m (f m (f (f (f e m) m) (f m m)))))).\nsurgery id_r ((f b (f m (f m (f (f (f e m) m) (f m m)))))) ((f b (f m (f m (f (f e m) (f m m)))))).\nsurgery id_r ((f b (f m (f m (f (f e m) (f m m)))))) ((f b (f m (f m (f e (f m m)))))).\nsurgery id_l ((f b (f m (f m (f e (f m m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_384: forall b: G, (((e <+> m) <+> ((b <+> m) <+> m)) <+> (e <+> (((e <+> e) <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f b m) m)) (f e (f (f (f e e) e) m)))) ((f (f e (f (f b m) m)) (f e (f (f (f e e) e) m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f e (f (f (f e e) e) m)))) ((f (f e (f b m)) (f e (f (f (f e e) e) m)))).\nsurgery id_r ((f (f e (f b m)) (f e (f (f (f e e) e) m)))) ((f (f e b) (f e (f (f (f e e) e) m)))).\nsurgery id_l ((f (f e b) (f e (f (f (f e e) e) m)))) ((f b (f e (f (f (f e e) e) m)))).\nsurgery id_l ((f b (f e (f (f (f e e) e) m)))) ((f b (f (f (f e e) e) m))).\nsurgery id_l ((f b (f (f (f e e) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_385: forall b: G, ((e <+> ((b <+> m) <+> ((m <+> m) <+> (((e <+> m) <+> m) <+> m)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f b m) (f (f m m) (f (f (f e m) m) m)))) m)) ((f e (f (f b m) (f (f m m) (f (f (f e m) m) m))))).\nsurgery id_r ((f e (f (f b m) (f (f m m) (f (f (f e m) m) m))))) ((f e (f b (f (f m m) (f (f (f e m) m) m))))).\nsurgery id_r ((f e (f b (f (f m m) (f (f (f e m) m) m))))) ((f e (f b (f m (f (f (f e m) m) m))))).\nsurgery id_r ((f e (f b (f m (f (f (f e m) m) m))))) ((f e (f b (f m (f (f e m) m))))).\nsurgery id_r ((f e (f b (f m (f (f e m) m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_386: forall b: G, ((b <+> (((e <+> e) <+> e) <+> (e <+> ((m <+> m) <+> m)))) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f (f (f e e) e) (f e (f (f m m) m)))) (f e m))) ((f (f b (f (f e e) (f e (f (f m m) m)))) (f e m))).\nsurgery id_l ((f (f b (f (f e e) (f e (f (f m m) m)))) (f e m))) ((f (f b (f e (f e (f (f m m) m)))) (f e m))).\nsurgery id_l ((f (f b (f e (f e (f (f m m) m)))) (f e m))) ((f (f b (f e (f (f m m) m))) (f e m))).\nsurgery id_l ((f (f b (f e (f (f m m) m))) (f e m))) ((f (f b (f (f m m) m)) (f e m))).\nsurgery id_r ((f (f b (f (f m m) m)) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_387: forall b: G, (e <+> (((((e <+> m) <+> e) <+> (e <+> m)) <+> (e <+> b)) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f (f (f e m) e) (f e m)) (f e b)) (f m m)))) ((f e (f (f (f (f e e) (f e m)) (f e b)) (f m m)))).\nsurgery id_l ((f e (f (f (f (f e e) (f e m)) (f e b)) (f m m)))) ((f e (f (f (f e (f e m)) (f e b)) (f m m)))).\nsurgery id_l ((f e (f (f (f e (f e m)) (f e b)) (f m m)))) ((f e (f (f (f e m) (f e b)) (f m m)))).\nsurgery id_r ((f e (f (f (f e m) (f e b)) (f m m)))) ((f e (f (f e (f e b)) (f m m)))).\nsurgery id_l ((f e (f (f e (f e b)) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_388: forall b: G, ((((e <+> (e <+> (b <+> m))) <+> (e <+> m)) <+> m) <+> (e <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e (f e (f b m))) (f e m)) m) (f e (f m m)))) ((f (f (f e (f e (f b m))) (f e m)) (f e (f m m)))).\nsurgery id_l ((f (f (f e (f e (f b m))) (f e m)) (f e (f m m)))) ((f (f (f e (f b m)) (f e m)) (f e (f m m)))).\nsurgery id_r ((f (f (f e (f b m)) (f e m)) (f e (f m m)))) ((f (f (f e b) (f e m)) (f e (f m m)))).\nsurgery id_l ((f (f (f e b) (f e m)) (f e (f m m)))) ((f (f b (f e m)) (f e (f m m)))).\nsurgery id_l ((f (f b (f e m)) (f e (f m m)))) ((f (f b m) (f e (f m m)))).\nsurgery id_r ((f (f b m) (f e (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_389: forall b: G, ((b <+> ((e <+> (e <+> e)) <+> ((e <+> (e <+> m)) <+> m))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f (f e (f e e)) (f (f e (f e m)) m))) (f m m))) ((f (f b (f (f e e) (f (f e (f e m)) m))) (f m m))).\nsurgery id_l ((f (f b (f (f e e) (f (f e (f e m)) m))) (f m m))) ((f (f b (f e (f (f e (f e m)) m))) (f m m))).\nsurgery id_l ((f (f b (f e (f (f e (f e m)) m))) (f m m))) ((f (f b (f (f e (f e m)) m)) (f m m))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f m m))) ((f (f b (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_390: forall b: G, (((((e <+> m) <+> (e <+> (m <+> m))) <+> (m <+> m)) <+> e) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) (f e (f m m))) (f m m)) e) (f e b))) ((f (f (f (f e (f e (f m m))) (f m m)) e) (f e b))).\nsurgery id_l ((f (f (f (f e (f e (f m m))) (f m m)) e) (f e b))) ((f (f (f (f e (f m m)) (f m m)) e) (f e b))).\nsurgery id_r ((f (f (f (f e (f m m)) (f m m)) e) (f e b))) ((f (f (f (f e m) (f m m)) e) (f e b))).\nsurgery id_r ((f (f (f (f e m) (f m m)) e) (f e b))) ((f (f (f e (f m m)) e) (f e b))).\nsurgery id_r ((f (f (f e (f m m)) e) (f e b))) ((f (f (f e m) e) (f e b))).\nsurgery id_r ((f (f (f e m) e) (f e b))) ((f (f e e) (f e b))).\nsurgery id_l ((f (f e e) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_391: forall b: G, (((e <+> ((e <+> m) <+> b)) <+> (m <+> (m <+> m))) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) b)) (f m (f m m))) (f (f e m) m))) ((f (f (f e (f e b)) (f m (f m m))) (f (f e m) m))).\nsurgery id_l ((f (f (f e (f e b)) (f m (f m m))) (f (f e m) m))) ((f (f (f e b) (f m (f m m))) (f (f e m) m))).\nsurgery id_l ((f (f (f e b) (f m (f m m))) (f (f e m) m))) ((f (f b (f m (f m m))) (f (f e m) m))).\nsurgery id_r ((f (f b (f m (f m m))) (f (f e m) m))) ((f (f b (f m m)) (f (f e m) m))).\nsurgery id_r ((f (f b (f m m)) (f (f e m) m))) ((f (f b m) (f (f e m) m))).\nsurgery id_r ((f (f b m) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_392: forall b: G, ((((e <+> m) <+> (e <+> m)) <+> ((e <+> m) <+> b)) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f e m)) (f (f e m) b)) (f m (f m m)))) ((f (f (f e (f e m)) (f (f e m) b)) (f m (f m m)))).\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) b)) (f m (f m m)))) ((f (f (f e m) (f (f e m) b)) (f m (f m m)))).\nsurgery id_r ((f (f (f e m) (f (f e m) b)) (f m (f m m)))) ((f (f e (f (f e m) b)) (f m (f m m)))).\nsurgery id_r ((f (f e (f (f e m) b)) (f m (f m m)))) ((f (f e (f e b)) (f m (f m m)))).\nsurgery id_l ((f (f e (f e b)) (f m (f m m)))) ((f (f e b) (f m (f m m)))).\nsurgery id_l ((f (f e b) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_393: forall b: G, ((e <+> (e <+> m)) <+> ((e <+> ((e <+> m) <+> e)) <+> ((e <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f e (f (f e m) e)) (f (f e b) m)))) ((f (f e m) (f (f e (f (f e m) e)) (f (f e b) m)))).\nsurgery id_r ((f (f e m) (f (f e (f (f e m) e)) (f (f e b) m)))) ((f e (f (f e (f (f e m) e)) (f (f e b) m)))).\nsurgery id_r ((f e (f (f e (f (f e m) e)) (f (f e b) m)))) ((f e (f (f e (f e e)) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e (f e e)) (f (f e b) m)))) ((f e (f (f e e) (f (f e b) m)))).\nsurgery id_l ((f e (f (f e e) (f (f e b) m)))) ((f e (f e (f (f e b) m)))).\nsurgery id_l ((f e (f e (f (f e b) m)))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_394: forall b: G, ((e <+> (e <+> e)) <+> ((b <+> (m <+> m)) <+> (e <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f b (f m m)) (f e (f e (f m m)))))) ((f (f e e) (f (f b (f m m)) (f e (f e (f m m)))))).\nsurgery id_l ((f (f e e) (f (f b (f m m)) (f e (f e (f m m)))))) ((f e (f (f b (f m m)) (f e (f e (f m m)))))).\nsurgery id_r ((f e (f (f b (f m m)) (f e (f e (f m m)))))) ((f e (f (f b m) (f e (f e (f m m)))))).\nsurgery id_r ((f e (f (f b m) (f e (f e (f m m)))))) ((f e (f b (f e (f e (f m m)))))).\nsurgery id_l ((f e (f b (f e (f e (f m m)))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_395: forall b: G, (((e <+> ((e <+> m) <+> (((e <+> m) <+> e) <+> b))) <+> m) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) (f (f (f e m) e) b))) m) (f m m))) ((f (f e (f (f e m) (f (f (f e m) e) b))) (f m m))).\nsurgery id_r ((f (f e (f (f e m) (f (f (f e m) e) b))) (f m m))) ((f (f e (f e (f (f (f e m) e) b))) (f m m))).\nsurgery id_l ((f (f e (f e (f (f (f e m) e) b))) (f m m))) ((f (f e (f (f (f e m) e) b)) (f m m))).\nsurgery id_r ((f (f e (f (f (f e m) e) b)) (f m m))) ((f (f e (f (f e e) b)) (f m m))).\nsurgery id_l ((f (f e (f (f e e) b)) (f m m))) ((f (f e (f e b)) (f m m))).\nsurgery id_l ((f (f e (f e b)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_396: forall b: G, (((e <+> (b <+> m)) <+> ((((e <+> m) <+> m) <+> m) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f b m)) (f (f (f (f e m) m) m) m)) (f m m))) ((f (f (f e b) (f (f (f (f e m) m) m) m)) (f m m))).\nsurgery id_l ((f (f (f e b) (f (f (f (f e m) m) m) m)) (f m m))) ((f (f b (f (f (f (f e m) m) m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f (f (f e m) m) m) m)) (f m m))) ((f (f b (f (f (f e m) m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f (f e m) m) m)) (f m m))) ((f (f b (f (f e m) m)) (f m m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f m m))) ((f (f b (f e m)) (f m m))).\nsurgery id_l ((f (f b (f e m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_397: forall b: G, (((e <+> e) <+> (e <+> m)) <+> (((b <+> m) <+> ((e <+> e) <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f e m)) (f (f (f b m) (f (f e e) m)) m))) ((f (f e (f e m)) (f (f (f b m) (f (f e e) m)) m))).\nsurgery id_l ((f (f e (f e m)) (f (f (f b m) (f (f e e) m)) m))) ((f (f e m) (f (f (f b m) (f (f e e) m)) m))).\nsurgery id_r ((f (f e m) (f (f (f b m) (f (f e e) m)) m))) ((f e (f (f (f b m) (f (f e e) m)) m))).\nsurgery id_r ((f e (f (f (f b m) (f (f e e) m)) m))) ((f e (f (f b (f (f e e) m)) m))).\nsurgery id_l ((f e (f (f b (f (f e e) m)) m))) ((f e (f (f b (f e m)) m))).\nsurgery id_l ((f e (f (f b (f e m)) m))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_398: forall b: G, (e <+> ((e <+> (b <+> m)) <+> (m <+> ((e <+> m) <+> ((e <+> m) <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e (f b m)) (f m (f (f e m) (f (f e m) m)))))) ((f e (f (f e b) (f m (f (f e m) (f (f e m) m)))))).\nsurgery id_l ((f e (f (f e b) (f m (f (f e m) (f (f e m) m)))))) ((f e (f b (f m (f (f e m) (f (f e m) m)))))).\nsurgery id_r ((f e (f b (f m (f (f e m) (f (f e m) m)))))) ((f e (f b (f m (f e (f (f e m) m)))))).\nsurgery id_l ((f e (f b (f m (f e (f (f e m) m)))))) ((f e (f b (f m (f (f e m) m))))).\nsurgery id_r ((f e (f b (f m (f (f e m) m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_399: forall b: G, ((b <+> (e <+> m)) <+> (((e <+> m) <+> ((e <+> m) <+> (m <+> m))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e m)) (f (f (f e m) (f (f e m) (f m m))) m))) ((f (f b m) (f (f (f e m) (f (f e m) (f m m))) m))).\nsurgery id_r ((f (f b m) (f (f (f e m) (f (f e m) (f m m))) m))) ((f b (f (f (f e m) (f (f e m) (f m m))) m))).\nsurgery id_r ((f b (f (f (f e m) (f (f e m) (f m m))) m))) ((f b (f (f e (f (f e m) (f m m))) m))).\nsurgery id_r ((f b (f (f e (f (f e m) (f m m))) m))) ((f b (f (f e (f e (f m m))) m))).\nsurgery id_l ((f b (f (f e (f e (f m m))) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_400: forall b: G, (b <+> ((((e <+> m) <+> ((e <+> (e <+> m)) <+> m)) <+> (e <+> e)) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f (f e m) (f (f e (f e m)) m)) (f e e)) m))) ((f b (f (f (f e (f (f e (f e m)) m)) (f e e)) m))).\nsurgery id_l ((f b (f (f (f e (f (f e (f e m)) m)) (f e e)) m))) ((f b (f (f (f e (f (f e m) m)) (f e e)) m))).\nsurgery id_r ((f b (f (f (f e (f (f e m) m)) (f e e)) m))) ((f b (f (f (f e (f e m)) (f e e)) m))).\nsurgery id_l ((f b (f (f (f e (f e m)) (f e e)) m))) ((f b (f (f (f e m) (f e e)) m))).\nsurgery id_r ((f b (f (f (f e m) (f e e)) m))) ((f b (f (f e (f e e)) m))).\nsurgery id_l ((f b (f (f e (f e e)) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_401: forall b: G, ((((e <+> e) <+> (e <+> (e <+> m))) <+> (e <+> m)) <+> (b <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f e (f e m))) (f e m)) (f b (f m m)))) ((f (f (f e (f e (f e m))) (f e m)) (f b (f m m)))).\nsurgery id_l ((f (f (f e (f e (f e m))) (f e m)) (f b (f m m)))) ((f (f (f e (f e m)) (f e m)) (f b (f m m)))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f b (f m m)))) ((f (f (f e m) (f e m)) (f b (f m m)))).\nsurgery id_r ((f (f (f e m) (f e m)) (f b (f m m)))) ((f (f e (f e m)) (f b (f m m)))).\nsurgery id_l ((f (f e (f e m)) (f b (f m m)))) ((f (f e m) (f b (f m m)))).\nsurgery id_r ((f (f e m) (f b (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_402: forall b: G, (b <+> (((e <+> e) <+> m) <+> ((((e <+> m) <+> e) <+> (m <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e e) m) (f (f (f (f e m) e) (f m m)) m)))) ((f b (f (f e e) (f (f (f (f e m) e) (f m m)) m)))).\nsurgery id_l ((f b (f (f e e) (f (f (f (f e m) e) (f m m)) m)))) ((f b (f e (f (f (f (f e m) e) (f m m)) m)))).\nsurgery id_l ((f b (f e (f (f (f (f e m) e) (f m m)) m)))) ((f b (f (f (f (f e m) e) (f m m)) m))).\nsurgery id_r ((f b (f (f (f (f e m) e) (f m m)) m))) ((f b (f (f (f e e) (f m m)) m))).\nsurgery id_l ((f b (f (f (f e e) (f m m)) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_403: forall b: G, ((((e <+> e) <+> ((e <+> m) <+> (b <+> m))) <+> m) <+> (m <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) (f (f e m) (f b m))) m) (f m (f e m)))) ((f (f (f e e) (f (f e m) (f b m))) (f m (f e m)))).\nsurgery id_l ((f (f (f e e) (f (f e m) (f b m))) (f m (f e m)))) ((f (f e (f (f e m) (f b m))) (f m (f e m)))).\nsurgery id_r ((f (f e (f (f e m) (f b m))) (f m (f e m)))) ((f (f e (f e (f b m))) (f m (f e m)))).\nsurgery id_l ((f (f e (f e (f b m))) (f m (f e m)))) ((f (f e (f b m)) (f m (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f m (f e m)))) ((f (f e b) (f m (f e m)))).\nsurgery id_l ((f (f e b) (f m (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_404: forall b: G, (((e <+> e) <+> ((e <+> e) <+> (b <+> m))) <+> ((e <+> m) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e e) (f b m))) (f (f e m) (f m m)))) ((f (f e (f (f e e) (f b m))) (f (f e m) (f m m)))).\nsurgery id_l ((f (f e (f (f e e) (f b m))) (f (f e m) (f m m)))) ((f (f e (f e (f b m))) (f (f e m) (f m m)))).\nsurgery id_l ((f (f e (f e (f b m))) (f (f e m) (f m m)))) ((f (f e (f b m)) (f (f e m) (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e m) (f m m)))) ((f (f e b) (f (f e m) (f m m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f m m)))) ((f b (f (f e m) (f m m)))).\nsurgery id_r ((f b (f (f e m) (f m m)))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_405: forall b: G, (((e <+> (e <+> m)) <+> ((e <+> ((e <+> e) <+> e)) <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f (f e (f (f e e) e)) (f e m))) b)) ((f (f (f e m) (f (f e (f (f e e) e)) (f e m))) b)).\nsurgery id_r ((f (f (f e m) (f (f e (f (f e e) e)) (f e m))) b)) ((f (f e (f (f e (f (f e e) e)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f (f e e) e)) (f e m))) b)) ((f (f e (f (f e (f e e)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f e e)) (f e m))) b)) ((f (f e (f (f e e) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e e) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_406: forall b: G, (((e <+> (e <+> (e <+> m))) <+> (m <+> m)) <+> ((e <+> b) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e m))) (f m m)) (f (f e b) (f m m)))) ((f (f (f e (f e m)) (f m m)) (f (f e b) (f m m)))).\nsurgery id_l ((f (f (f e (f e m)) (f m m)) (f (f e b) (f m m)))) ((f (f (f e m) (f m m)) (f (f e b) (f m m)))).\nsurgery id_r ((f (f (f e m) (f m m)) (f (f e b) (f m m)))) ((f (f e (f m m)) (f (f e b) (f m m)))).\nsurgery id_r ((f (f e (f m m)) (f (f e b) (f m m)))) ((f (f e m) (f (f e b) (f m m)))).\nsurgery id_r ((f (f e m) (f (f e b) (f m m)))) ((f e (f (f e b) (f m m)))).\nsurgery id_l ((f e (f (f e b) (f m m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_407: forall b: G, ((b <+> ((m <+> m) <+> (m <+> (e <+> (m <+> m))))) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f m m) (f m (f e (f m m))))) (f m (f m m)))) ((f (f b (f m (f m (f e (f m m))))) (f m (f m m)))).\nsurgery id_l ((f (f b (f m (f m (f e (f m m))))) (f m (f m m)))) ((f (f b (f m (f m (f m m)))) (f m (f m m)))).\nsurgery id_r ((f (f b (f m (f m (f m m)))) (f m (f m m)))) ((f (f b (f m (f m m))) (f m (f m m)))).\nsurgery id_r ((f (f b (f m (f m m))) (f m (f m m)))) ((f (f b (f m m)) (f m (f m m)))).\nsurgery id_r ((f (f b (f m m)) (f m (f m m)))) ((f (f b m) (f m (f m m)))).\nsurgery id_r ((f (f b m) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_408: forall b: G, ((((e <+> m) <+> ((e <+> e) <+> (e <+> b))) <+> (m <+> m)) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f (f e e) (f e b))) (f m m)) (f e m))) ((f (f (f e (f (f e e) (f e b))) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e (f (f e e) (f e b))) (f m m)) (f e m))) ((f (f (f e (f e (f e b))) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e (f e (f e b))) (f m m)) (f e m))) ((f (f (f e (f e b)) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e (f e b)) (f m m)) (f e m))) ((f (f (f e b) (f m m)) (f e m))).\nsurgery id_l ((f (f (f e b) (f m m)) (f e m))) ((f (f b (f m m)) (f e m))).\nsurgery id_r ((f (f b (f m m)) (f e m))) ((f (f b m) (f e m))).\nsurgery id_r ((f (f b m) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_409: forall b: G, ((b <+> (m <+> (e <+> m))) <+> (((((e <+> m) <+> e) <+> m) <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f m (f e m))) (f (f (f (f (f e m) e) m) e) m))) ((f (f b (f m m)) (f (f (f (f (f e m) e) m) e) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f (f (f e m) e) m) e) m))) ((f (f b m) (f (f (f (f (f e m) e) m) e) m))).\nsurgery id_r ((f (f b m) (f (f (f (f (f e m) e) m) e) m))) ((f b (f (f (f (f (f e m) e) m) e) m))).\nsurgery id_r ((f b (f (f (f (f (f e m) e) m) e) m))) ((f b (f (f (f (f e m) e) e) m))).\nsurgery id_r ((f b (f (f (f (f e m) e) e) m))) ((f b (f (f (f e e) e) m))).\nsurgery id_l ((f b (f (f (f e e) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_410: forall b: G, ((b <+> (m <+> m)) <+> ((e <+> m) <+> (((e <+> e) <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m m)) (f (f e m) (f (f (f e e) m) (f e m))))) ((f (f b m) (f (f e m) (f (f (f e e) m) (f e m))))).\nsurgery id_r ((f (f b m) (f (f e m) (f (f (f e e) m) (f e m))))) ((f b (f (f e m) (f (f (f e e) m) (f e m))))).\nsurgery id_r ((f b (f (f e m) (f (f (f e e) m) (f e m))))) ((f b (f e (f (f (f e e) m) (f e m))))).\nsurgery id_l ((f b (f e (f (f (f e e) m) (f e m))))) ((f b (f (f (f e e) m) (f e m)))).\nsurgery id_r ((f b (f (f (f e e) m) (f e m)))) ((f b (f (f e e) (f e m)))).\nsurgery id_l ((f b (f (f e e) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_411: forall b: G, ((((e <+> m) <+> m) <+> ((m <+> m) <+> m)) <+> (e <+> ((e <+> m) <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) m) (f (f m m) m)) (f e (f (f e m) b)))) ((f (f (f e m) (f (f m m) m)) (f e (f (f e m) b)))).\nsurgery id_r ((f (f (f e m) (f (f m m) m)) (f e (f (f e m) b)))) ((f (f e (f (f m m) m)) (f e (f (f e m) b)))).\nsurgery id_r ((f (f e (f (f m m) m)) (f e (f (f e m) b)))) ((f (f e (f m m)) (f e (f (f e m) b)))).\nsurgery id_r ((f (f e (f m m)) (f e (f (f e m) b)))) ((f (f e m) (f e (f (f e m) b)))).\nsurgery id_r ((f (f e m) (f e (f (f e m) b)))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_412: forall b: G, ((((e <+> m) <+> (m <+> m)) <+> b) <+> ((e <+> m) <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) (f m m)) b) (f (f e m) (f (f e e) m)))) ((f (f (f e (f m m)) b) (f (f e m) (f (f e e) m)))).\nsurgery id_r ((f (f (f e (f m m)) b) (f (f e m) (f (f e e) m)))) ((f (f (f e m) b) (f (f e m) (f (f e e) m)))).\nsurgery id_r ((f (f (f e m) b) (f (f e m) (f (f e e) m)))) ((f (f e b) (f (f e m) (f (f e e) m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f (f e e) m)))) ((f b (f (f e m) (f (f e e) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e e) m)))) ((f b (f e (f (f e e) m)))).\nsurgery id_l ((f b (f e (f (f e e) m)))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_413: forall b: G, (((e <+> e) <+> ((e <+> b) <+> m)) <+> ((m <+> (m <+> m)) <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e b) m)) (f (f m (f m m)) (f m m)))) ((f (f e (f (f e b) m)) (f (f m (f m m)) (f m m)))).\nsurgery id_l ((f (f e (f (f e b) m)) (f (f m (f m m)) (f m m)))) ((f (f e (f b m)) (f (f m (f m m)) (f m m)))).\nsurgery id_r ((f (f e (f b m)) (f (f m (f m m)) (f m m)))) ((f (f e b) (f (f m (f m m)) (f m m)))).\nsurgery id_l ((f (f e b) (f (f m (f m m)) (f m m)))) ((f b (f (f m (f m m)) (f m m)))).\nsurgery id_r ((f b (f (f m (f m m)) (f m m)))) ((f b (f (f m m) (f m m)))).\nsurgery id_r ((f b (f (f m m) (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_414: forall b: G, ((b <+> (m <+> (m <+> (m <+> ((e <+> m) <+> m))))) <+> ((e <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f m (f m (f m (f (f e m) m))))) (f (f e e) m))) ((f (f b (f m (f m (f m (f e m))))) (f (f e e) m))).\nsurgery id_l ((f (f b (f m (f m (f m (f e m))))) (f (f e e) m))) ((f (f b (f m (f m (f m m)))) (f (f e e) m))).\nsurgery id_r ((f (f b (f m (f m (f m m)))) (f (f e e) m))) ((f (f b (f m (f m m))) (f (f e e) m))).\nsurgery id_r ((f (f b (f m (f m m))) (f (f e e) m))) ((f (f b (f m m)) (f (f e e) m))).\nsurgery id_r ((f (f b (f m m)) (f (f e e) m))) ((f (f b m) (f (f e e) m))).\nsurgery id_r ((f (f b m) (f (f e e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_415: forall b: G, ((e <+> m) <+> (e <+> (((e <+> ((m <+> (e <+> m)) <+> m)) <+> e) <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f e (f (f (f e (f (f m (f e m)) m)) e) b)))) ((f e (f e (f (f (f e (f (f m (f e m)) m)) e) b)))).\nsurgery id_l ((f e (f e (f (f (f e (f (f m (f e m)) m)) e) b)))) ((f e (f (f (f e (f (f m (f e m)) m)) e) b))).\nsurgery id_l ((f e (f (f (f e (f (f m (f e m)) m)) e) b))) ((f e (f (f (f e (f (f m m) m)) e) b))).\nsurgery id_r ((f e (f (f (f e (f (f m m) m)) e) b))) ((f e (f (f (f e (f m m)) e) b))).\nsurgery id_r ((f e (f (f (f e (f m m)) e) b))) ((f e (f (f (f e m) e) b))).\nsurgery id_r ((f e (f (f (f e m) e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_416: forall b: G, ((e <+> ((e <+> e) <+> ((e <+> (e <+> (e <+> m))) <+> (e <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) (f (f e (f e (f e m))) (f e m)))) b)) ((f (f e (f e (f (f e (f e (f e m))) (f e m)))) b)).\nsurgery id_l ((f (f e (f e (f (f e (f e (f e m))) (f e m)))) b)) ((f (f e (f (f e (f e (f e m))) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f e (f e m))) (f e m))) b)) ((f (f e (f (f e (f e m)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f e m)) (f e m))) b)) ((f (f e (f (f e m) (f e m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_417: forall b: G, (((e <+> e) <+> (((e <+> b) <+> ((e <+> e) <+> m)) <+> m)) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f e b) (f (f e e) m)) m)) (f m m))) ((f (f e (f (f (f e b) (f (f e e) m)) m)) (f m m))).\nsurgery id_l ((f (f e (f (f (f e b) (f (f e e) m)) m)) (f m m))) ((f (f e (f (f b (f (f e e) m)) m)) (f m m))).\nsurgery id_l ((f (f e (f (f b (f (f e e) m)) m)) (f m m))) ((f (f e (f (f b (f e m)) m)) (f m m))).\nsurgery id_l ((f (f e (f (f b (f e m)) m)) (f m m))) ((f (f e (f (f b m) m)) (f m m))).\nsurgery id_r ((f (f e (f (f b m) m)) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_418: forall b: G, (((e <+> (e <+> m)) <+> (e <+> (e <+> e))) <+> (((e <+> m) <+> m) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f e (f e e))) (f (f (f e m) m) b))) ((f (f (f e m) (f e (f e e))) (f (f (f e m) m) b))).\nsurgery id_r ((f (f (f e m) (f e (f e e))) (f (f (f e m) m) b))) ((f (f e (f e (f e e))) (f (f (f e m) m) b))).\nsurgery id_l ((f (f e (f e (f e e))) (f (f (f e m) m) b))) ((f (f e (f e e)) (f (f (f e m) m) b))).\nsurgery id_l ((f (f e (f e e)) (f (f (f e m) m) b))) ((f (f e e) (f (f (f e m) m) b))).\nsurgery id_l ((f (f e e) (f (f (f e m) m) b))) ((f e (f (f (f e m) m) b))).\nsurgery id_r ((f e (f (f (f e m) m) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_419: forall b: G, ((e <+> (e <+> e)) <+> ((b <+> (m <+> m)) <+> (e <+> ((m <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f b (f m m)) (f e (f (f m m) m))))) ((f (f e e) (f (f b (f m m)) (f e (f (f m m) m))))).\nsurgery id_l ((f (f e e) (f (f b (f m m)) (f e (f (f m m) m))))) ((f e (f (f b (f m m)) (f e (f (f m m) m))))).\nsurgery id_r ((f e (f (f b (f m m)) (f e (f (f m m) m))))) ((f e (f (f b m) (f e (f (f m m) m))))).\nsurgery id_r ((f e (f (f b m) (f e (f (f m m) m))))) ((f e (f b (f e (f (f m m) m))))).\nsurgery id_l ((f e (f b (f e (f (f m m) m))))) ((f e (f b (f (f m m) m)))).\nsurgery id_r ((f e (f b (f (f m m) m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_420: forall b: G, ((((b <+> (m <+> m)) <+> m) <+> ((m <+> m) <+> m)) <+> ((e <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f b (f m m)) m) (f (f m m) m)) (f (f e e) m))) ((f (f (f b (f m m)) (f (f m m) m)) (f (f e e) m))).\nsurgery id_r ((f (f (f b (f m m)) (f (f m m) m)) (f (f e e) m))) ((f (f (f b m) (f (f m m) m)) (f (f e e) m))).\nsurgery id_r ((f (f (f b m) (f (f m m) m)) (f (f e e) m))) ((f (f b (f (f m m) m)) (f (f e e) m))).\nsurgery id_r ((f (f b (f (f m m) m)) (f (f e e) m))) ((f (f b (f m m)) (f (f e e) m))).\nsurgery id_r ((f (f b (f m m)) (f (f e e) m))) ((f (f b m) (f (f e e) m))).\nsurgery id_r ((f (f b m) (f (f e e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_421: forall b: G, (((e <+> (e <+> (e <+> e))) <+> (b <+> m)) <+> (((e <+> e) <+> e) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e e))) (f b m)) (f (f (f e e) e) m))) ((f (f (f e (f e e)) (f b m)) (f (f (f e e) e) m))).\nsurgery id_l ((f (f (f e (f e e)) (f b m)) (f (f (f e e) e) m))) ((f (f (f e e) (f b m)) (f (f (f e e) e) m))).\nsurgery id_l ((f (f (f e e) (f b m)) (f (f (f e e) e) m))) ((f (f e (f b m)) (f (f (f e e) e) m))).\nsurgery id_r ((f (f e (f b m)) (f (f (f e e) e) m))) ((f (f e b) (f (f (f e e) e) m))).\nsurgery id_l ((f (f e b) (f (f (f e e) e) m))) ((f b (f (f (f e e) e) m))).\nsurgery id_l ((f b (f (f (f e e) e) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_422: forall b: G, ((e <+> ((e <+> (b <+> m)) <+> (m <+> m))) <+> ((e <+> m) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f e (f b m)) (f m m))) (f (f e m) (f e m)))) ((f (f e (f (f e b) (f m m))) (f (f e m) (f e m)))).\nsurgery id_l ((f (f e (f (f e b) (f m m))) (f (f e m) (f e m)))) ((f (f e (f b (f m m))) (f (f e m) (f e m)))).\nsurgery id_r ((f (f e (f b (f m m))) (f (f e m) (f e m)))) ((f (f e (f b m)) (f (f e m) (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f (f e m) (f e m)))) ((f (f e b) (f (f e m) (f e m)))).\nsurgery id_l ((f (f e b) (f (f e m) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_423: forall b: G, ((((((e <+> b) <+> m) <+> m) <+> m) <+> (m <+> m)) <+> (e <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e b) m) m) m) (f m m)) (f e (f e m)))) ((f (f (f (f (f e b) m) m) (f m m)) (f e (f e m)))).\nsurgery id_r ((f (f (f (f (f e b) m) m) (f m m)) (f e (f e m)))) ((f (f (f (f e b) m) (f m m)) (f e (f e m)))).\nsurgery id_r ((f (f (f (f e b) m) (f m m)) (f e (f e m)))) ((f (f (f e b) (f m m)) (f e (f e m)))).\nsurgery id_l ((f (f (f e b) (f m m)) (f e (f e m)))) ((f (f b (f m m)) (f e (f e m)))).\nsurgery id_r ((f (f b (f m m)) (f e (f e m)))) ((f (f b m) (f e (f e m)))).\nsurgery id_r ((f (f b m) (f e (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_424: forall b: G, (b <+> ((e <+> m) <+> ((e <+> (((e <+> m) <+> m) <+> m)) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f e m) (f (f e (f (f (f e m) m) m)) (f e m))))) ((f b (f e (f (f e (f (f (f e m) m) m)) (f e m))))).\nsurgery id_l ((f b (f e (f (f e (f (f (f e m) m) m)) (f e m))))) ((f b (f (f e (f (f (f e m) m) m)) (f e m)))).\nsurgery id_r ((f b (f (f e (f (f (f e m) m) m)) (f e m)))) ((f b (f (f e (f (f e m) m)) (f e m)))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) (f e m)))) ((f b (f (f e (f e m)) (f e m)))).\nsurgery id_l ((f b (f (f e (f e m)) (f e m)))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_425: forall b: G, (((e <+> e) <+> m) <+> (((e <+> e) <+> e) <+> ((e <+> (e <+> b)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e e) m) (f (f (f e e) e) (f (f e (f e b)) m)))) ((f (f e e) (f (f (f e e) e) (f (f e (f e b)) m)))).\nsurgery id_l ((f (f e e) (f (f (f e e) e) (f (f e (f e b)) m)))) ((f e (f (f (f e e) e) (f (f e (f e b)) m)))).\nsurgery id_l ((f e (f (f (f e e) e) (f (f e (f e b)) m)))) ((f e (f (f e e) (f (f e (f e b)) m)))).\nsurgery id_l ((f e (f (f e e) (f (f e (f e b)) m)))) ((f e (f e (f (f e (f e b)) m)))).\nsurgery id_l ((f e (f e (f (f e (f e b)) m)))) ((f e (f (f e (f e b)) m))).\nsurgery id_l ((f e (f (f e (f e b)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_426: forall b: G, ((((e <+> m) <+> e) <+> ((e <+> (e <+> (e <+> m))) <+> (m <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) e) (f (f e (f e (f e m))) (f m m))) b)) ((f (f (f e e) (f (f e (f e (f e m))) (f m m))) b)).\nsurgery id_l ((f (f (f e e) (f (f e (f e (f e m))) (f m m))) b)) ((f (f e (f (f e (f e (f e m))) (f m m))) b)).\nsurgery id_l ((f (f e (f (f e (f e (f e m))) (f m m))) b)) ((f (f e (f (f e (f e m)) (f m m))) b)).\nsurgery id_l ((f (f e (f (f e (f e m)) (f m m))) b)) ((f (f e (f (f e m) (f m m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f m m))) b)) ((f (f e (f e (f m m))) b)).\nsurgery id_l ((f (f e (f e (f m m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_427: forall b: G, ((e <+> (e <+> m)) <+> ((e <+> m) <+> ((e <+> m) <+> ((b <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f e m) (f (f e m) (f (f b m) m))))) ((f (f e m) (f (f e m) (f (f e m) (f (f b m) m))))).\nsurgery id_r ((f (f e m) (f (f e m) (f (f e m) (f (f b m) m))))) ((f e (f (f e m) (f (f e m) (f (f b m) m))))).\nsurgery id_r ((f e (f (f e m) (f (f e m) (f (f b m) m))))) ((f e (f e (f (f e m) (f (f b m) m))))).\nsurgery id_l ((f e (f e (f (f e m) (f (f b m) m))))) ((f e (f (f e m) (f (f b m) m)))).\nsurgery id_r ((f e (f (f e m) (f (f b m) m)))) ((f e (f e (f (f b m) m)))).\nsurgery id_l ((f e (f e (f (f b m) m)))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_428: forall b: G, ((e <+> b) <+> ((e <+> (m <+> (e <+> m))) <+> (m <+> (m <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f e (f m (f e m))) (f m (f m (f m m)))))) ((f b (f (f e (f m (f e m))) (f m (f m (f m m)))))).\nsurgery id_l ((f b (f (f e (f m (f e m))) (f m (f m (f m m)))))) ((f b (f (f e (f m m)) (f m (f m (f m m)))))).\nsurgery id_r ((f b (f (f e (f m m)) (f m (f m (f m m)))))) ((f b (f (f e m) (f m (f m (f m m)))))).\nsurgery id_r ((f b (f (f e m) (f m (f m (f m m)))))) ((f b (f e (f m (f m (f m m)))))).\nsurgery id_l ((f b (f e (f m (f m (f m m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_429: forall b: G, (e <+> ((e <+> (((e <+> m) <+> e) <+> ((e <+> m) <+> m))) <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e (f (f (f e m) e) (f (f e m) m))) (f e b)))) ((f e (f (f e (f (f e e) (f (f e m) m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f (f e e) (f (f e m) m))) (f e b)))) ((f e (f (f e (f e (f (f e m) m))) (f e b)))).\nsurgery id_l ((f e (f (f e (f e (f (f e m) m))) (f e b)))) ((f e (f (f e (f (f e m) m)) (f e b)))).\nsurgery id_r ((f e (f (f e (f (f e m) m)) (f e b)))) ((f e (f (f e (f e m)) (f e b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f e b)))) ((f e (f (f e m) (f e b)))).\nsurgery id_r ((f e (f (f e m) (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_430: forall b: G, ((e <+> e) <+> ((e <+> ((e <+> e) <+> (b <+> (m <+> (m <+> m))))) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f e (f (f e e) (f b (f m (f m m))))) m))) ((f e (f (f e (f (f e e) (f b (f m (f m m))))) m))).\nsurgery id_l ((f e (f (f e (f (f e e) (f b (f m (f m m))))) m))) ((f e (f (f e (f e (f b (f m (f m m))))) m))).\nsurgery id_l ((f e (f (f e (f e (f b (f m (f m m))))) m))) ((f e (f (f e (f b (f m (f m m)))) m))).\nsurgery id_r ((f e (f (f e (f b (f m (f m m)))) m))) ((f e (f (f e (f b (f m m))) m))).\nsurgery id_r ((f e (f (f e (f b (f m m))) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_431: forall b: G, (((((e <+> m) <+> e) <+> e) <+> (((e <+> m) <+> m) <+> m)) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f e m) e) e) (f (f (f e m) m) m)) (f e b))) ((f (f (f (f e e) e) (f (f (f e m) m) m)) (f e b))).\nsurgery id_l ((f (f (f (f e e) e) (f (f (f e m) m) m)) (f e b))) ((f (f (f e e) (f (f (f e m) m) m)) (f e b))).\nsurgery id_l ((f (f (f e e) (f (f (f e m) m) m)) (f e b))) ((f (f e (f (f (f e m) m) m)) (f e b))).\nsurgery id_r ((f (f e (f (f (f e m) m) m)) (f e b))) ((f (f e (f (f e m) m)) (f e b))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e b))) ((f (f e (f e m)) (f e b))).\nsurgery id_l ((f (f e (f e m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_432: forall b: G, (((e <+> m) <+> ((e <+> m) <+> m)) <+> (((e <+> m) <+> b) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e m) m)) (f (f (f e m) b) (f e m)))) ((f (f e (f (f e m) m)) (f (f (f e m) b) (f e m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f (f e m) b) (f e m)))) ((f (f e (f e m)) (f (f (f e m) b) (f e m)))).\nsurgery id_l ((f (f e (f e m)) (f (f (f e m) b) (f e m)))) ((f (f e m) (f (f (f e m) b) (f e m)))).\nsurgery id_r ((f (f e m) (f (f (f e m) b) (f e m)))) ((f e (f (f (f e m) b) (f e m)))).\nsurgery id_r ((f e (f (f (f e m) b) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_433: forall b: G, ((e <+> (e <+> e)) <+> (((e <+> (e <+> m)) <+> m) <+> (b <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f (f e (f e m)) m) (f b (f e m))))) ((f (f e e) (f (f (f e (f e m)) m) (f b (f e m))))).\nsurgery id_l ((f (f e e) (f (f (f e (f e m)) m) (f b (f e m))))) ((f e (f (f (f e (f e m)) m) (f b (f e m))))).\nsurgery id_r ((f e (f (f (f e (f e m)) m) (f b (f e m))))) ((f e (f (f e (f e m)) (f b (f e m))))).\nsurgery id_l ((f e (f (f e (f e m)) (f b (f e m))))) ((f e (f (f e m) (f b (f e m))))).\nsurgery id_r ((f e (f (f e m) (f b (f e m))))) ((f e (f e (f b (f e m))))).\nsurgery id_l ((f e (f e (f b (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_434: forall b: G, ((((((e <+> m) <+> e) <+> m) <+> e) <+> (e <+> b)) <+> (m <+> (m <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e m) e) m) e) (f e b)) (f m (f m m)))) ((f (f (f (f (f e m) e) e) (f e b)) (f m (f m m)))).\nsurgery id_r ((f (f (f (f (f e m) e) e) (f e b)) (f m (f m m)))) ((f (f (f (f e e) e) (f e b)) (f m (f m m)))).\nsurgery id_l ((f (f (f (f e e) e) (f e b)) (f m (f m m)))) ((f (f (f e e) (f e b)) (f m (f m m)))).\nsurgery id_l ((f (f (f e e) (f e b)) (f m (f m m)))) ((f (f e (f e b)) (f m (f m m)))).\nsurgery id_l ((f (f e (f e b)) (f m (f m m)))) ((f (f e b) (f m (f m m)))).\nsurgery id_l ((f (f e b) (f m (f m m)))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_435: forall b: G, ((e <+> m) <+> (((e <+> m) <+> (e <+> b)) <+> (m <+> ((m <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e m) (f e b)) (f m (f (f m m) m))))) ((f e (f (f (f e m) (f e b)) (f m (f (f m m) m))))).\nsurgery id_r ((f e (f (f (f e m) (f e b)) (f m (f (f m m) m))))) ((f e (f (f e (f e b)) (f m (f (f m m) m))))).\nsurgery id_l ((f e (f (f e (f e b)) (f m (f (f m m) m))))) ((f e (f (f e b) (f m (f (f m m) m))))).\nsurgery id_l ((f e (f (f e b) (f m (f (f m m) m))))) ((f e (f b (f m (f (f m m) m))))).\nsurgery id_r ((f e (f b (f m (f (f m m) m))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_436: forall b: G, (((e <+> b) <+> ((e <+> e) <+> (m <+> m))) <+> (m <+> (m <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e b) (f (f e e) (f m m))) (f m (f m (f e m))))) ((f (f b (f (f e e) (f m m))) (f m (f m (f e m))))).\nsurgery id_l ((f (f b (f (f e e) (f m m))) (f m (f m (f e m))))) ((f (f b (f e (f m m))) (f m (f m (f e m))))).\nsurgery id_l ((f (f b (f e (f m m))) (f m (f m (f e m))))) ((f (f b (f m m)) (f m (f m (f e m))))).\nsurgery id_r ((f (f b (f m m)) (f m (f m (f e m))))) ((f (f b m) (f m (f m (f e m))))).\nsurgery id_r ((f (f b m) (f m (f m (f e m))))) ((f b (f m (f m (f e m))))).\nsurgery id_l ((f b (f m (f m (f e m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_437: forall b: G, (((e <+> m) <+> ((e <+> e) <+> m)) <+> ((e <+> e) <+> ((b <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f (f e e) m)) (f (f e e) (f (f b m) m)))) ((f (f e (f (f e e) m)) (f (f e e) (f (f b m) m)))).\nsurgery id_l ((f (f e (f (f e e) m)) (f (f e e) (f (f b m) m)))) ((f (f e (f e m)) (f (f e e) (f (f b m) m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e e) (f (f b m) m)))) ((f (f e m) (f (f e e) (f (f b m) m)))).\nsurgery id_r ((f (f e m) (f (f e e) (f (f b m) m)))) ((f e (f (f e e) (f (f b m) m)))).\nsurgery id_l ((f e (f (f e e) (f (f b m) m)))) ((f e (f e (f (f b m) m)))).\nsurgery id_l ((f e (f e (f (f b m) m)))) ((f e (f (f b m) m))).\nsurgery id_r ((f e (f (f b m) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_438: forall b: G, (((e <+> ((e <+> m) <+> e)) <+> ((e <+> m) <+> ((e <+> e) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e m) e)) (f (f e m) (f (f e e) m))) b)) ((f (f (f e (f e e)) (f (f e m) (f (f e e) m))) b)).\nsurgery id_l ((f (f (f e (f e e)) (f (f e m) (f (f e e) m))) b)) ((f (f (f e e) (f (f e m) (f (f e e) m))) b)).\nsurgery id_l ((f (f (f e e) (f (f e m) (f (f e e) m))) b)) ((f (f e (f (f e m) (f (f e e) m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f (f e e) m))) b)) ((f (f e (f e (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f e (f (f e e) m))) b)) ((f (f e (f (f e e) m)) b)).\nsurgery id_l ((f (f e (f (f e e) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_439: forall b: G, ((e <+> b) <+> ((m <+> m) <+> (((e <+> m) <+> (m <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f (f m m) (f (f (f e m) (f m m)) (f m m))))) ((f b (f (f m m) (f (f (f e m) (f m m)) (f m m))))).\nsurgery id_r ((f b (f (f m m) (f (f (f e m) (f m m)) (f m m))))) ((f b (f m (f (f (f e m) (f m m)) (f m m))))).\nsurgery id_r ((f b (f m (f (f (f e m) (f m m)) (f m m))))) ((f b (f m (f (f e (f m m)) (f m m))))).\nsurgery id_r ((f b (f m (f (f e (f m m)) (f m m))))) ((f b (f m (f (f e m) (f m m))))).\nsurgery id_r ((f b (f m (f (f e m) (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_440: forall b: G, ((((e <+> e) <+> (e <+> e)) <+> ((e <+> (e <+> m)) <+> (e <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f e e)) (f (f e (f e m)) (f e m))) b)) ((f (f (f e (f e e)) (f (f e (f e m)) (f e m))) b)).\nsurgery id_l ((f (f (f e (f e e)) (f (f e (f e m)) (f e m))) b)) ((f (f (f e e) (f (f e (f e m)) (f e m))) b)).\nsurgery id_l ((f (f (f e e) (f (f e (f e m)) (f e m))) b)) ((f (f e (f (f e (f e m)) (f e m))) b)).\nsurgery id_l ((f (f e (f (f e (f e m)) (f e m))) b)) ((f (f e (f (f e m) (f e m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f e m))) b)) ((f (f e (f e (f e m))) b)).\nsurgery id_l ((f (f e (f e (f e m))) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_441: forall b: G, (b <+> (((e <+> (((e <+> m) <+> m) <+> (e <+> (m <+> m)))) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e (f (f (f e m) m) (f e (f m m)))) m) m))) ((f b (f (f e (f (f (f e m) m) (f e (f m m)))) m))).\nsurgery id_r ((f b (f (f e (f (f (f e m) m) (f e (f m m)))) m))) ((f b (f (f e (f (f e m) (f e (f m m)))) m))).\nsurgery id_r ((f b (f (f e (f (f e m) (f e (f m m)))) m))) ((f b (f (f e (f e (f e (f m m)))) m))).\nsurgery id_l ((f b (f (f e (f e (f e (f m m)))) m))) ((f b (f (f e (f e (f m m))) m))).\nsurgery id_l ((f b (f (f e (f e (f m m))) m))) ((f b (f (f e (f m m)) m))).\nsurgery id_r ((f b (f (f e (f m m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_442: forall b: G, (((e <+> (e <+> (e <+> e))) <+> (e <+> ((e <+> m) <+> m))) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e e))) (f e (f (f e m) m))) (f b m))) ((f (f (f e (f e e)) (f e (f (f e m) m))) (f b m))).\nsurgery id_l ((f (f (f e (f e e)) (f e (f (f e m) m))) (f b m))) ((f (f (f e e) (f e (f (f e m) m))) (f b m))).\nsurgery id_l ((f (f (f e e) (f e (f (f e m) m))) (f b m))) ((f (f e (f e (f (f e m) m))) (f b m))).\nsurgery id_l ((f (f e (f e (f (f e m) m))) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_443: forall b: G, (((e <+> (e <+> e)) <+> ((e <+> m) <+> m)) <+> (b <+> ((m <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e e)) (f (f e m) m)) (f b (f (f m m) m)))) ((f (f (f e e) (f (f e m) m)) (f b (f (f m m) m)))).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f b (f (f m m) m)))) ((f (f e (f (f e m) m)) (f b (f (f m m) m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b (f (f m m) m)))) ((f (f e (f e m)) (f b (f (f m m) m)))).\nsurgery id_l ((f (f e (f e m)) (f b (f (f m m) m)))) ((f (f e m) (f b (f (f m m) m)))).\nsurgery id_r ((f (f e m) (f b (f (f m m) m)))) ((f e (f b (f (f m m) m)))).\nsurgery id_r ((f e (f b (f (f m m) m)))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_444: forall b: G, ((e <+> ((e <+> (m <+> (e <+> (e <+> (m <+> m))))) <+> m)) <+> (b <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e (f m (f e (f e (f m m))))) m)) (f b m))) ((f (f e (f (f e (f m (f e (f m m)))) m)) (f b m))).\nsurgery id_l ((f (f e (f (f e (f m (f e (f m m)))) m)) (f b m))) ((f (f e (f (f e (f m (f m m))) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e (f m (f m m))) m)) (f b m))) ((f (f e (f (f e (f m m)) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e (f m m)) m)) (f b m))) ((f (f e (f (f e m) m)) (f b m))).\nsurgery id_r ((f (f e (f (f e m) m)) (f b m))) ((f (f e (f e m)) (f b m))).\nsurgery id_l ((f (f e (f e m)) (f b m))) ((f (f e m) (f b m))).\nsurgery id_r ((f (f e m) (f b m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_445: forall b: G, (((e <+> e) <+> ((e <+> m) <+> m)) <+> ((e <+> (e <+> m)) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f e m) m)) (f (f e (f e m)) (f b m)))) ((f (f e (f (f e m) m)) (f (f e (f e m)) (f b m)))).\nsurgery id_r ((f (f e (f (f e m) m)) (f (f e (f e m)) (f b m)))) ((f (f e (f e m)) (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f (f e (f e m)) (f (f e (f e m)) (f b m)))) ((f (f e m) (f (f e (f e m)) (f b m)))).\nsurgery id_r ((f (f e m) (f (f e (f e m)) (f b m)))) ((f e (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_446: forall b: G, (((e <+> (e <+> (m <+> (m <+> m)))) <+> (m <+> ((m <+> m) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f m (f m m)))) (f m (f (f m m) m))) b)) ((f (f (f e (f m (f m m))) (f m (f (f m m) m))) b)).\nsurgery id_r ((f (f (f e (f m (f m m))) (f m (f (f m m) m))) b)) ((f (f (f e (f m m)) (f m (f (f m m) m))) b)).\nsurgery id_r ((f (f (f e (f m m)) (f m (f (f m m) m))) b)) ((f (f (f e m) (f m (f (f m m) m))) b)).\nsurgery id_r ((f (f (f e m) (f m (f (f m m) m))) b)) ((f (f e (f m (f (f m m) m))) b)).\nsurgery id_r ((f (f e (f m (f (f m m) m))) b)) ((f (f e (f m (f m m))) b)).\nsurgery id_r ((f (f e (f m (f m m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_447: forall b: G, ((((e <+> e) <+> e) <+> b) <+> (((e <+> m) <+> ((e <+> m) <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) e) b) (f (f (f e m) (f (f e m) m)) m))) ((f (f (f e e) b) (f (f (f e m) (f (f e m) m)) m))).\nsurgery id_l ((f (f (f e e) b) (f (f (f e m) (f (f e m) m)) m))) ((f (f e b) (f (f (f e m) (f (f e m) m)) m))).\nsurgery id_l ((f (f e b) (f (f (f e m) (f (f e m) m)) m))) ((f b (f (f (f e m) (f (f e m) m)) m))).\nsurgery id_r ((f b (f (f (f e m) (f (f e m) m)) m))) ((f b (f (f e (f (f e m) m)) m))).\nsurgery id_r ((f b (f (f e (f (f e m) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_448: forall b: G, (((((e <+> e) <+> e) <+> (e <+> m)) <+> (e <+> m)) <+> ((e <+> m) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f (f e e) e) (f e m)) (f e m)) (f (f e m) b))) ((f (f (f (f e e) (f e m)) (f e m)) (f (f e m) b))).\nsurgery id_l ((f (f (f (f e e) (f e m)) (f e m)) (f (f e m) b))) ((f (f (f e (f e m)) (f e m)) (f (f e m) b))).\nsurgery id_l ((f (f (f e (f e m)) (f e m)) (f (f e m) b))) ((f (f (f e m) (f e m)) (f (f e m) b))).\nsurgery id_r ((f (f (f e m) (f e m)) (f (f e m) b))) ((f (f e (f e m)) (f (f e m) b))).\nsurgery id_l ((f (f e (f e m)) (f (f e m) b))) ((f (f e m) (f (f e m) b))).\nsurgery id_r ((f (f e m) (f (f e m) b))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_449: forall b: G, ((e <+> (((b <+> m) <+> (e <+> m)) <+> (m <+> (e <+> m)))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f (f b m) (f e m)) (f m (f e m)))) (f m m))) ((f (f e (f (f b (f e m)) (f m (f e m)))) (f m m))).\nsurgery id_l ((f (f e (f (f b (f e m)) (f m (f e m)))) (f m m))) ((f (f e (f (f b m) (f m (f e m)))) (f m m))).\nsurgery id_r ((f (f e (f (f b m) (f m (f e m)))) (f m m))) ((f (f e (f b (f m (f e m)))) (f m m))).\nsurgery id_l ((f (f e (f b (f m (f e m)))) (f m m))) ((f (f e (f b (f m m))) (f m m))).\nsurgery id_r ((f (f e (f b (f m m))) (f m m))) ((f (f e (f b m)) (f m m))).\nsurgery id_r ((f (f e (f b m)) (f m m))) ((f (f e b) (f m m))).\nsurgery id_l ((f (f e b) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_450: forall b: G, ((e <+> (m <+> m)) <+> (e <+> ((b <+> (e <+> (m <+> m))) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f m m)) (f e (f (f b (f e (f m m))) (f e m))))) ((f (f e m) (f e (f (f b (f e (f m m))) (f e m))))).\nsurgery id_r ((f (f e m) (f e (f (f b (f e (f m m))) (f e m))))) ((f e (f e (f (f b (f e (f m m))) (f e m))))).\nsurgery id_l ((f e (f e (f (f b (f e (f m m))) (f e m))))) ((f e (f (f b (f e (f m m))) (f e m)))).\nsurgery id_l ((f e (f (f b (f e (f m m))) (f e m)))) ((f e (f (f b (f m m)) (f e m)))).\nsurgery id_r ((f e (f (f b (f m m)) (f e m)))) ((f e (f (f b m) (f e m)))).\nsurgery id_r ((f e (f (f b m) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_451: forall b: G, (((e <+> m) <+> (e <+> (m <+> m))) <+> (e <+> (((e <+> m) <+> b) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e m) (f e (f m m))) (f e (f (f (f e m) b) m)))) ((f (f e (f e (f m m))) (f e (f (f (f e m) b) m)))).\nsurgery id_l ((f (f e (f e (f m m))) (f e (f (f (f e m) b) m)))) ((f (f e (f m m)) (f e (f (f (f e m) b) m)))).\nsurgery id_r ((f (f e (f m m)) (f e (f (f (f e m) b) m)))) ((f (f e m) (f e (f (f (f e m) b) m)))).\nsurgery id_r ((f (f e m) (f e (f (f (f e m) b) m)))) ((f e (f e (f (f (f e m) b) m)))).\nsurgery id_l ((f e (f e (f (f (f e m) b) m)))) ((f e (f (f (f e m) b) m))).\nsurgery id_r ((f e (f (f (f e m) b) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_452: forall b: G, ((((e <+> (e <+> m)) <+> e) <+> ((e <+> (e <+> b)) <+> m)) <+> (e <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e m)) e) (f (f e (f e b)) m)) (f e m))) ((f (f (f (f e m) e) (f (f e (f e b)) m)) (f e m))).\nsurgery id_r ((f (f (f (f e m) e) (f (f e (f e b)) m)) (f e m))) ((f (f (f e e) (f (f e (f e b)) m)) (f e m))).\nsurgery id_l ((f (f (f e e) (f (f e (f e b)) m)) (f e m))) ((f (f e (f (f e (f e b)) m)) (f e m))).\nsurgery id_l ((f (f e (f (f e (f e b)) m)) (f e m))) ((f (f e (f (f e b) m)) (f e m))).\nsurgery id_l ((f (f e (f (f e b) m)) (f e m))) ((f (f e (f b m)) (f e m))).\nsurgery id_r ((f (f e (f b m)) (f e m))) ((f (f e b) (f e m))).\nsurgery id_l ((f (f e b) (f e m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_453: forall b: G, ((((e <+> ((e <+> (e <+> m)) <+> m)) <+> e) <+> ((e <+> m) <+> m)) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f (f e (f e m)) m)) e) (f (f e m) m)) b)) ((f (f (f (f e (f (f e m) m)) e) (f (f e m) m)) b)).\nsurgery id_r ((f (f (f (f e (f (f e m) m)) e) (f (f e m) m)) b)) ((f (f (f (f e (f e m)) e) (f (f e m) m)) b)).\nsurgery id_l ((f (f (f (f e (f e m)) e) (f (f e m) m)) b)) ((f (f (f (f e m) e) (f (f e m) m)) b)).\nsurgery id_r ((f (f (f (f e m) e) (f (f e m) m)) b)) ((f (f (f e e) (f (f e m) m)) b)).\nsurgery id_l ((f (f (f e e) (f (f e m) m)) b)) ((f (f e (f (f e m) m)) b)).\nsurgery id_r ((f (f e (f (f e m) m)) b)) ((f (f e (f e m)) b)).\nsurgery id_l ((f (f e (f e m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_454: forall b: G, (e <+> ((b <+> m) <+> ((e <+> (e <+> (e <+> (e <+> m)))) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f b m) (f (f e (f e (f e (f e m)))) (f m m))))) ((f e (f b (f (f e (f e (f e (f e m)))) (f m m))))).\nsurgery id_l ((f e (f b (f (f e (f e (f e (f e m)))) (f m m))))) ((f e (f b (f (f e (f e (f e m))) (f m m))))).\nsurgery id_l ((f e (f b (f (f e (f e (f e m))) (f m m))))) ((f e (f b (f (f e (f e m)) (f m m))))).\nsurgery id_l ((f e (f b (f (f e (f e m)) (f m m))))) ((f e (f b (f (f e m) (f m m))))).\nsurgery id_r ((f e (f b (f (f e m) (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_455: forall b: G, (b <+> (m <+> ((e <+> m) <+> (e <+> (((e <+> e) <+> m) <+> (e <+> m)))))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f m (f (f e m) (f e (f (f (f e e) m) (f e m))))))) ((f b (f m (f e (f e (f (f (f e e) m) (f e m))))))).\nsurgery id_l ((f b (f m (f e (f e (f (f (f e e) m) (f e m))))))) ((f b (f m (f e (f (f (f e e) m) (f e m)))))).\nsurgery id_l ((f b (f m (f e (f (f (f e e) m) (f e m)))))) ((f b (f m (f (f (f e e) m) (f e m))))).\nsurgery id_r ((f b (f m (f (f (f e e) m) (f e m))))) ((f b (f m (f (f e e) (f e m))))).\nsurgery id_l ((f b (f m (f (f e e) (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_456: forall b: G, (e <+> ((((e <+> b) <+> m) <+> m) <+> (m <+> ((e <+> m) <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f (f (f e b) m) m) (f m (f (f e m) (f m m)))))) ((f e (f (f (f e b) m) (f m (f (f e m) (f m m)))))).\nsurgery id_r ((f e (f (f (f e b) m) (f m (f (f e m) (f m m)))))) ((f e (f (f e b) (f m (f (f e m) (f m m)))))).\nsurgery id_l ((f e (f (f e b) (f m (f (f e m) (f m m)))))) ((f e (f b (f m (f (f e m) (f m m)))))).\nsurgery id_r ((f e (f b (f m (f (f e m) (f m m)))))) ((f e (f b (f m (f e (f m m)))))).\nsurgery id_l ((f e (f b (f m (f e (f m m)))))) ((f e (f b (f m (f m m))))).\nsurgery id_r ((f e (f b (f m (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_457: forall b: G, (((b <+> m) <+> ((e <+> e) <+> (e <+> m))) <+> (((e <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f (f e e) (f e m))) (f (f (f e m) m) m))) ((f (f b (f (f e e) (f e m))) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f (f e e) (f e m))) (f (f (f e m) m) m))) ((f (f b (f e (f e m))) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f e (f e m))) (f (f (f e m) m) m))) ((f (f b (f e m)) (f (f (f e m) m) m))).\nsurgery id_l ((f (f b (f e m)) (f (f (f e m) m) m))) ((f (f b m) (f (f (f e m) m) m))).\nsurgery id_r ((f (f b m) (f (f (f e m) m) m))) ((f b (f (f (f e m) m) m))).\nsurgery id_r ((f b (f (f (f e m) m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_458: forall b: G, (((e <+> (e <+> m)) <+> ((m <+> (e <+> m)) <+> ((e <+> e) <+> m))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f (f m (f e m)) (f (f e e) m))) b)) ((f (f (f e m) (f (f m (f e m)) (f (f e e) m))) b)).\nsurgery id_r ((f (f (f e m) (f (f m (f e m)) (f (f e e) m))) b)) ((f (f e (f (f m (f e m)) (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f (f m (f e m)) (f (f e e) m))) b)) ((f (f e (f (f m m) (f (f e e) m))) b)).\nsurgery id_r ((f (f e (f (f m m) (f (f e e) m))) b)) ((f (f e (f m (f (f e e) m))) b)).\nsurgery id_l ((f (f e (f m (f (f e e) m))) b)) ((f (f e (f m (f e m))) b)).\nsurgery id_l ((f (f e (f m (f e m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_459: forall b: G, (((b <+> m) <+> (e <+> m)) <+> ((e <+> e) <+> (e <+> ((e <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f e m)) (f (f e e) (f e (f (f e m) m))))) ((f (f b (f e m)) (f (f e e) (f e (f (f e m) m))))).\nsurgery id_l ((f (f b (f e m)) (f (f e e) (f e (f (f e m) m))))) ((f (f b m) (f (f e e) (f e (f (f e m) m))))).\nsurgery id_r ((f (f b m) (f (f e e) (f e (f (f e m) m))))) ((f b (f (f e e) (f e (f (f e m) m))))).\nsurgery id_l ((f b (f (f e e) (f e (f (f e m) m))))) ((f b (f e (f e (f (f e m) m))))).\nsurgery id_l ((f b (f e (f e (f (f e m) m))))) ((f b (f e (f (f e m) m)))).\nsurgery id_l ((f b (f e (f (f e m) m)))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_460: forall b: G, ((((e <+> e) <+> ((e <+> e) <+> m)) <+> b) <+> (e <+> ((e <+> e) <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f (f e e) m)) b) (f e (f (f e e) m)))) ((f (f (f e (f (f e e) m)) b) (f e (f (f e e) m)))).\nsurgery id_l ((f (f (f e (f (f e e) m)) b) (f e (f (f e e) m)))) ((f (f (f e (f e m)) b) (f e (f (f e e) m)))).\nsurgery id_l ((f (f (f e (f e m)) b) (f e (f (f e e) m)))) ((f (f (f e m) b) (f e (f (f e e) m)))).\nsurgery id_r ((f (f (f e m) b) (f e (f (f e e) m)))) ((f (f e b) (f e (f (f e e) m)))).\nsurgery id_l ((f (f e b) (f e (f (f e e) m)))) ((f b (f e (f (f e e) m)))).\nsurgery id_l ((f b (f e (f (f e e) m)))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_461: forall b: G, ((e <+> ((b <+> ((e <+> m) <+> (m <+> m))) <+> m)) <+> (m <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f (f b (f (f e m) (f m m))) m)) (f m (f e m)))) ((f (f e (f (f b (f e (f m m))) m)) (f m (f e m)))).\nsurgery id_l ((f (f e (f (f b (f e (f m m))) m)) (f m (f e m)))) ((f (f e (f (f b (f m m)) m)) (f m (f e m)))).\nsurgery id_r ((f (f e (f (f b (f m m)) m)) (f m (f e m)))) ((f (f e (f (f b m) m)) (f m (f e m)))).\nsurgery id_r ((f (f e (f (f b m) m)) (f m (f e m)))) ((f (f e (f b m)) (f m (f e m)))).\nsurgery id_r ((f (f e (f b m)) (f m (f e m)))) ((f (f e b) (f m (f e m)))).\nsurgery id_l ((f (f e b) (f m (f e m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_462: forall b: G, ((((e <+> m) <+> m) <+> ((e <+> e) <+> (e <+> e))) <+> (e <+> (e <+> b))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e m) m) (f (f e e) (f e e))) (f e (f e b)))) ((f (f (f e m) (f (f e e) (f e e))) (f e (f e b)))).\nsurgery id_r ((f (f (f e m) (f (f e e) (f e e))) (f e (f e b)))) ((f (f e (f (f e e) (f e e))) (f e (f e b)))).\nsurgery id_l ((f (f e (f (f e e) (f e e))) (f e (f e b)))) ((f (f e (f e (f e e))) (f e (f e b)))).\nsurgery id_l ((f (f e (f e (f e e))) (f e (f e b)))) ((f (f e (f e e)) (f e (f e b)))).\nsurgery id_l ((f (f e (f e e)) (f e (f e b)))) ((f (f e e) (f e (f e b)))).\nsurgery id_l ((f (f e e) (f e (f e b)))) ((f e (f e (f e b)))).\nsurgery id_l ((f e (f e (f e b)))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_463: forall b: G, ((((e <+> e) <+> m) <+> b) <+> (((m <+> m) <+> m) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) b) (f (f (f m m) m) (f (f e m) m)))) ((f (f (f e e) b) (f (f (f m m) m) (f (f e m) m)))).\nsurgery id_l ((f (f (f e e) b) (f (f (f m m) m) (f (f e m) m)))) ((f (f e b) (f (f (f m m) m) (f (f e m) m)))).\nsurgery id_l ((f (f e b) (f (f (f m m) m) (f (f e m) m)))) ((f b (f (f (f m m) m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f (f m m) m) (f (f e m) m)))) ((f b (f (f m m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f m m) (f (f e m) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_464: forall b: G, ((b <+> m) <+> (m <+> (((e <+> (e <+> m)) <+> ((m <+> m) <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f m (f (f (f e (f e m)) (f (f m m) m)) m)))) ((f b (f m (f (f (f e (f e m)) (f (f m m) m)) m)))).\nsurgery id_l ((f b (f m (f (f (f e (f e m)) (f (f m m) m)) m)))) ((f b (f m (f (f (f e m) (f (f m m) m)) m)))).\nsurgery id_r ((f b (f m (f (f (f e m) (f (f m m) m)) m)))) ((f b (f m (f (f e (f (f m m) m)) m)))).\nsurgery id_r ((f b (f m (f (f e (f (f m m) m)) m)))) ((f b (f m (f (f e (f m m)) m)))).\nsurgery id_r ((f b (f m (f (f e (f m m)) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_465: forall b: G, (((e <+> (e <+> (e <+> m))) <+> ((e <+> e) <+> (e <+> (m <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e m))) (f (f e e) (f e (f m m)))) b)) ((f (f (f e (f e m)) (f (f e e) (f e (f m m)))) b)).\nsurgery id_l ((f (f (f e (f e m)) (f (f e e) (f e (f m m)))) b)) ((f (f (f e m) (f (f e e) (f e (f m m)))) b)).\nsurgery id_r ((f (f (f e m) (f (f e e) (f e (f m m)))) b)) ((f (f e (f (f e e) (f e (f m m)))) b)).\nsurgery id_l ((f (f e (f (f e e) (f e (f m m)))) b)) ((f (f e (f e (f e (f m m)))) b)).\nsurgery id_l ((f (f e (f e (f e (f m m)))) b)) ((f (f e (f e (f m m))) b)).\nsurgery id_l ((f (f e (f e (f m m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_466: forall b: G, ((e <+> (b <+> m)) <+> ((m <+> ((e <+> m) <+> (m <+> (m <+> m)))) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f e (f b m)) (f (f m (f (f e m) (f m (f m m)))) m))) ((f (f e b) (f (f m (f (f e m) (f m (f m m)))) m))).\nsurgery id_l ((f (f e b) (f (f m (f (f e m) (f m (f m m)))) m))) ((f b (f (f m (f (f e m) (f m (f m m)))) m))).\nsurgery id_r ((f b (f (f m (f (f e m) (f m (f m m)))) m))) ((f b (f (f m (f e (f m (f m m)))) m))).\nsurgery id_l ((f b (f (f m (f e (f m (f m m)))) m))) ((f b (f (f m (f m (f m m))) m))).\nsurgery id_r ((f b (f (f m (f m (f m m))) m))) ((f b (f (f m (f m m)) m))).\nsurgery id_r ((f b (f (f m (f m m)) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_467: forall b: G, (e <+> ((e <+> (b <+> ((m <+> m) <+> m))) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e (f b (f (f m m) m))) (f (f e m) (f e m))))) ((f e (f (f e (f b (f m m))) (f (f e m) (f e m))))).\nsurgery id_r ((f e (f (f e (f b (f m m))) (f (f e m) (f e m))))) ((f e (f (f e (f b m)) (f (f e m) (f e m))))).\nsurgery id_r ((f e (f (f e (f b m)) (f (f e m) (f e m))))) ((f e (f (f e b) (f (f e m) (f e m))))).\nsurgery id_l ((f e (f (f e b) (f (f e m) (f e m))))) ((f e (f b (f (f e m) (f e m))))).\nsurgery id_r ((f e (f b (f (f e m) (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_468: forall b: G, ((e <+> m) <+> ((e <+> e) <+> ((e <+> (m <+> m)) <+> (e <+> (b <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f e e) (f (f e (f m m)) (f e (f b m)))))) ((f e (f (f e e) (f (f e (f m m)) (f e (f b m)))))).\nsurgery id_l ((f e (f (f e e) (f (f e (f m m)) (f e (f b m)))))) ((f e (f e (f (f e (f m m)) (f e (f b m)))))).\nsurgery id_l ((f e (f e (f (f e (f m m)) (f e (f b m)))))) ((f e (f (f e (f m m)) (f e (f b m))))).\nsurgery id_r ((f e (f (f e (f m m)) (f e (f b m))))) ((f e (f (f e m) (f e (f b m))))).\nsurgery id_r ((f e (f (f e m) (f e (f b m))))) ((f e (f e (f e (f b m))))).\nsurgery id_l ((f e (f e (f e (f b m))))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_469: forall b: G, (b <+> (((e <+> m) <+> ((m <+> m) <+> m)) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f e m) (f (f m m) m)) (f (f e m) (f e m))))) ((f b (f (f e (f (f m m) m)) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f e (f (f m m) m)) (f (f e m) (f e m))))) ((f b (f (f e (f m m)) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f (f e m) (f e m))))) ((f b (f (f e m) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f e m) (f (f e m) (f e m))))) ((f b (f e (f (f e m) (f e m))))).\nsurgery id_l ((f b (f e (f (f e m) (f e m))))) ((f b (f (f e m) (f e m)))).\nsurgery id_r ((f b (f (f e m) (f e m)))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_470: forall b: G, (((e <+> e) <+> (((e <+> e) <+> ((e <+> m) <+> m)) <+> m)) <+> (e <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f e e) (f (f e m) m)) m)) (f e b))) ((f (f e (f (f (f e e) (f (f e m) m)) m)) (f e b))).\nsurgery id_l ((f (f e (f (f (f e e) (f (f e m) m)) m)) (f e b))) ((f (f e (f (f e (f (f e m) m)) m)) (f e b))).\nsurgery id_r ((f (f e (f (f e (f (f e m) m)) m)) (f e b))) ((f (f e (f (f e (f e m)) m)) (f e b))).\nsurgery id_l ((f (f e (f (f e (f e m)) m)) (f e b))) ((f (f e (f (f e m) m)) (f e b))).\nsurgery id_r ((f (f e (f (f e m) m)) (f e b))) ((f (f e (f e m)) (f e b))).\nsurgery id_l ((f (f e (f e m)) (f e b))) ((f (f e m) (f e b))).\nsurgery id_r ((f (f e m) (f e b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_471: forall b: G, (b <+> ((m <+> m) <+> ((e <+> (e <+> m)) <+> ((e <+> (e <+> m)) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f m m) (f (f e (f e m)) (f (f e (f e m)) m))))) ((f b (f m (f (f e (f e m)) (f (f e (f e m)) m))))).\nsurgery id_l ((f b (f m (f (f e (f e m)) (f (f e (f e m)) m))))) ((f b (f m (f (f e m) (f (f e (f e m)) m))))).\nsurgery id_r ((f b (f m (f (f e m) (f (f e (f e m)) m))))) ((f b (f m (f e (f (f e (f e m)) m))))).\nsurgery id_l ((f b (f m (f e (f (f e (f e m)) m))))) ((f b (f m (f (f e (f e m)) m)))).\nsurgery id_l ((f b (f m (f (f e (f e m)) m)))) ((f b (f m (f (f e m) m)))).\nsurgery id_r ((f b (f m (f (f e m) m)))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_472: forall b: G, (((e <+> (e <+> m)) <+> ((e <+> m) <+> ((e <+> m) <+> (m <+> m)))) <+> b) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e m)) (f (f e m) (f (f e m) (f m m)))) b)) ((f (f (f e m) (f (f e m) (f (f e m) (f m m)))) b)).\nsurgery id_r ((f (f (f e m) (f (f e m) (f (f e m) (f m m)))) b)) ((f (f e (f (f e m) (f (f e m) (f m m)))) b)).\nsurgery id_r ((f (f e (f (f e m) (f (f e m) (f m m)))) b)) ((f (f e (f e (f (f e m) (f m m)))) b)).\nsurgery id_l ((f (f e (f e (f (f e m) (f m m)))) b)) ((f (f e (f (f e m) (f m m))) b)).\nsurgery id_r ((f (f e (f (f e m) (f m m))) b)) ((f (f e (f e (f m m))) b)).\nsurgery id_l ((f (f e (f e (f m m))) b)) ((f (f e (f m m)) b)).\nsurgery id_r ((f (f e (f m m)) b)) ((f (f e m) b)).\nsurgery id_r ((f (f e m) b)) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_473: forall b: G, (((e <+> e) <+> (((e <+> e) <+> (e <+> e)) <+> b)) <+> ((e <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f (f (f e e) (f e e)) b)) (f (f e m) m))) ((f (f e (f (f (f e e) (f e e)) b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f (f e e) (f e e)) b)) (f (f e m) m))) ((f (f e (f (f e (f e e)) b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f e (f e e)) b)) (f (f e m) m))) ((f (f e (f (f e e) b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f (f e e) b)) (f (f e m) m))) ((f (f e (f e b)) (f (f e m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f e m) m))) ((f (f e b) (f (f e m) m))).\nsurgery id_l ((f (f e b) (f (f e m) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_474: forall b: G, ((e <+> (e <+> m)) <+> ((e <+> ((e <+> e) <+> b)) <+> (m <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f (f e (f (f e e) b)) (f m (f e m))))) ((f (f e m) (f (f e (f (f e e) b)) (f m (f e m))))).\nsurgery id_r ((f (f e m) (f (f e (f (f e e) b)) (f m (f e m))))) ((f e (f (f e (f (f e e) b)) (f m (f e m))))).\nsurgery id_l ((f e (f (f e (f (f e e) b)) (f m (f e m))))) ((f e (f (f e (f e b)) (f m (f e m))))).\nsurgery id_l ((f e (f (f e (f e b)) (f m (f e m))))) ((f e (f (f e b) (f m (f e m))))).\nsurgery id_l ((f e (f (f e b) (f m (f e m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_475: forall b: G, (((e <+> ((e <+> e) <+> b)) <+> ((e <+> m) <+> (m <+> (e <+> m)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f (f e e) b)) (f (f e m) (f m (f e m)))) m)) ((f (f e (f (f e e) b)) (f (f e m) (f m (f e m))))).\nsurgery id_l ((f (f e (f (f e e) b)) (f (f e m) (f m (f e m))))) ((f (f e (f e b)) (f (f e m) (f m (f e m))))).\nsurgery id_l ((f (f e (f e b)) (f (f e m) (f m (f e m))))) ((f (f e b) (f (f e m) (f m (f e m))))).\nsurgery id_l ((f (f e b) (f (f e m) (f m (f e m))))) ((f b (f (f e m) (f m (f e m))))).\nsurgery id_r ((f b (f (f e m) (f m (f e m))))) ((f b (f e (f m (f e m))))).\nsurgery id_l ((f b (f e (f m (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_476: forall b: G, ((b <+> m) <+> ((m <+> m) <+> ((e <+> m) <+> ((e <+> m) <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b m) (f (f m m) (f (f e m) (f (f e m) (f m m)))))) ((f b (f (f m m) (f (f e m) (f (f e m) (f m m)))))).\nsurgery id_r ((f b (f (f m m) (f (f e m) (f (f e m) (f m m)))))) ((f b (f m (f (f e m) (f (f e m) (f m m)))))).\nsurgery id_r ((f b (f m (f (f e m) (f (f e m) (f m m)))))) ((f b (f m (f e (f (f e m) (f m m)))))).\nsurgery id_l ((f b (f m (f e (f (f e m) (f m m)))))) ((f b (f m (f (f e m) (f m m))))).\nsurgery id_r ((f b (f m (f (f e m) (f m m))))) ((f b (f m (f e (f m m))))).\nsurgery id_l ((f b (f m (f e (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_477: forall b: G, (((b <+> ((e <+> m) <+> (m <+> m))) <+> m) <+> (((e <+> e) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b (f (f e m) (f m m))) m) (f (f (f e e) m) m))) ((f (f b (f (f e m) (f m m))) (f (f (f e e) m) m))).\nsurgery id_r ((f (f b (f (f e m) (f m m))) (f (f (f e e) m) m))) ((f (f b (f e (f m m))) (f (f (f e e) m) m))).\nsurgery id_l ((f (f b (f e (f m m))) (f (f (f e e) m) m))) ((f (f b (f m m)) (f (f (f e e) m) m))).\nsurgery id_r ((f (f b (f m m)) (f (f (f e e) m) m))) ((f (f b m) (f (f (f e e) m) m))).\nsurgery id_r ((f (f b m) (f (f (f e e) m) m))) ((f b (f (f (f e e) m) m))).\nsurgery id_r ((f b (f (f (f e e) m) m))) ((f b (f (f e e) m))).\nsurgery id_l ((f b (f (f e e) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_478: forall b: G, ((e <+> ((e <+> b) <+> m)) <+> ((m <+> m) <+> ((e <+> m) <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e b) m)) (f (f m m) (f (f e m) (f e m))))) ((f (f e (f b m)) (f (f m m) (f (f e m) (f e m))))).\nsurgery id_r ((f (f e (f b m)) (f (f m m) (f (f e m) (f e m))))) ((f (f e b) (f (f m m) (f (f e m) (f e m))))).\nsurgery id_l ((f (f e b) (f (f m m) (f (f e m) (f e m))))) ((f b (f (f m m) (f (f e m) (f e m))))).\nsurgery id_r ((f b (f (f m m) (f (f e m) (f e m))))) ((f b (f m (f (f e m) (f e m))))).\nsurgery id_r ((f b (f m (f (f e m) (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_479: forall b: G, (((e <+> e) <+> (m <+> m)) <+> (((b <+> m) <+> m) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e e) (f m m)) (f (f (f b m) m) (f e (f e m))))) ((f (f e (f m m)) (f (f (f b m) m) (f e (f e m))))).\nsurgery id_r ((f (f e (f m m)) (f (f (f b m) m) (f e (f e m))))) ((f (f e m) (f (f (f b m) m) (f e (f e m))))).\nsurgery id_r ((f (f e m) (f (f (f b m) m) (f e (f e m))))) ((f e (f (f (f b m) m) (f e (f e m))))).\nsurgery id_r ((f e (f (f (f b m) m) (f e (f e m))))) ((f e (f (f b m) (f e (f e m))))).\nsurgery id_r ((f e (f (f b m) (f e (f e m))))) ((f e (f b (f e (f e m))))).\nsurgery id_l ((f e (f b (f e (f e m))))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_480: forall b: G, ((e <+> e) <+> (((((e <+> (e <+> m)) <+> e) <+> (m <+> m)) <+> e) <+> b)) = b.\nProof.\nintros.\nsurgery id_l ((f (f e e) (f (f (f (f (f e (f e m)) e) (f m m)) e) b))) ((f e (f (f (f (f (f e (f e m)) e) (f m m)) e) b))).\nsurgery id_l ((f e (f (f (f (f (f e (f e m)) e) (f m m)) e) b))) ((f e (f (f (f (f (f e m) e) (f m m)) e) b))).\nsurgery id_r ((f e (f (f (f (f (f e m) e) (f m m)) e) b))) ((f e (f (f (f (f e e) (f m m)) e) b))).\nsurgery id_l ((f e (f (f (f (f e e) (f m m)) e) b))) ((f e (f (f (f e (f m m)) e) b))).\nsurgery id_r ((f e (f (f (f e (f m m)) e) b))) ((f e (f (f (f e m) e) b))).\nsurgery id_r ((f e (f (f (f e m) e) b))) ((f e (f (f e e) b))).\nsurgery id_l ((f e (f (f e e) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_481: forall b: G, (((e <+> (e <+> (e <+> e))) <+> b) <+> ((e <+> ((e <+> e) <+> m)) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f e (f e (f e e))) b) (f (f e (f (f e e) m)) m))) ((f (f (f e (f e e)) b) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f (f e (f e e)) b) (f (f e (f (f e e) m)) m))) ((f (f (f e e) b) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f (f e e) b) (f (f e (f (f e e) m)) m))) ((f (f e b) (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f (f e b) (f (f e (f (f e e) m)) m))) ((f b (f (f e (f (f e e) m)) m))).\nsurgery id_l ((f b (f (f e (f (f e e) m)) m))) ((f b (f (f e (f e m)) m))).\nsurgery id_l ((f b (f (f e (f e m)) m))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_482: forall b: G, ((((e <+> e) <+> (b <+> m)) <+> (e <+> m)) <+> (e <+> (m <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e e) (f b m)) (f e m)) (f e (f m (f m m))))) ((f (f (f e (f b m)) (f e m)) (f e (f m (f m m))))).\nsurgery id_r ((f (f (f e (f b m)) (f e m)) (f e (f m (f m m))))) ((f (f (f e b) (f e m)) (f e (f m (f m m))))).\nsurgery id_l ((f (f (f e b) (f e m)) (f e (f m (f m m))))) ((f (f b (f e m)) (f e (f m (f m m))))).\nsurgery id_l ((f (f b (f e m)) (f e (f m (f m m))))) ((f (f b m) (f e (f m (f m m))))).\nsurgery id_r ((f (f b m) (f e (f m (f m m))))) ((f b (f e (f m (f m m))))).\nsurgery id_l ((f b (f e (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_483: forall b: G, ((e <+> (e <+> e)) <+> ((e <+> ((e <+> e) <+> (e <+> m))) <+> (b <+> m))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f e (f (f e e) (f e m))) (f b m)))) ((f (f e e) (f (f e (f (f e e) (f e m))) (f b m)))).\nsurgery id_l ((f (f e e) (f (f e (f (f e e) (f e m))) (f b m)))) ((f e (f (f e (f (f e e) (f e m))) (f b m)))).\nsurgery id_l ((f e (f (f e (f (f e e) (f e m))) (f b m)))) ((f e (f (f e (f e (f e m))) (f b m)))).\nsurgery id_l ((f e (f (f e (f e (f e m))) (f b m)))) ((f e (f (f e (f e m)) (f b m)))).\nsurgery id_l ((f e (f (f e (f e m)) (f b m)))) ((f e (f (f e m) (f b m)))).\nsurgery id_r ((f e (f (f e m) (f b m)))) ((f e (f e (f b m)))).\nsurgery id_l ((f e (f e (f b m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_484: forall b: G, ((e <+> (e <+> m)) <+> (e <+> (e <+> (((e <+> (b <+> m)) <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e m)) (f e (f e (f (f (f e (f b m)) m) m))))) ((f (f e m) (f e (f e (f (f (f e (f b m)) m) m))))).\nsurgery id_r ((f (f e m) (f e (f e (f (f (f e (f b m)) m) m))))) ((f e (f e (f e (f (f (f e (f b m)) m) m))))).\nsurgery id_l ((f e (f e (f e (f (f (f e (f b m)) m) m))))) ((f e (f e (f (f (f e (f b m)) m) m)))).\nsurgery id_l ((f e (f e (f (f (f e (f b m)) m) m)))) ((f e (f (f (f e (f b m)) m) m))).\nsurgery id_r ((f e (f (f (f e (f b m)) m) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_485: forall b: G, ((e <+> (e <+> e)) <+> (((e <+> e) <+> (e <+> m)) <+> ((e <+> m) <+> b))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f e e)) (f (f (f e e) (f e m)) (f (f e m) b)))) ((f (f e e) (f (f (f e e) (f e m)) (f (f e m) b)))).\nsurgery id_l ((f (f e e) (f (f (f e e) (f e m)) (f (f e m) b)))) ((f e (f (f (f e e) (f e m)) (f (f e m) b)))).\nsurgery id_l ((f e (f (f (f e e) (f e m)) (f (f e m) b)))) ((f e (f (f e (f e m)) (f (f e m) b)))).\nsurgery id_l ((f e (f (f e (f e m)) (f (f e m) b)))) ((f e (f (f e m) (f (f e m) b)))).\nsurgery id_r ((f e (f (f e m) (f (f e m) b)))) ((f e (f e (f (f e m) b)))).\nsurgery id_l ((f e (f e (f (f e m) b)))) ((f e (f (f e m) b))).\nsurgery id_r ((f e (f (f e m) b))) ((f e (f e b))).\nsurgery id_l ((f e (f e b))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_486: forall b: G, ((e <+> m) <+> (((e <+> e) <+> b) <+> ((e <+> (e <+> m)) <+> (m <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f (f e m) (f (f (f e e) b) (f (f e (f e m)) (f m m))))) ((f e (f (f (f e e) b) (f (f e (f e m)) (f m m))))).\nsurgery id_l ((f e (f (f (f e e) b) (f (f e (f e m)) (f m m))))) ((f e (f (f e b) (f (f e (f e m)) (f m m))))).\nsurgery id_l ((f e (f (f e b) (f (f e (f e m)) (f m m))))) ((f e (f b (f (f e (f e m)) (f m m))))).\nsurgery id_l ((f e (f b (f (f e (f e m)) (f m m))))) ((f e (f b (f (f e m) (f m m))))).\nsurgery id_r ((f e (f b (f (f e m) (f m m))))) ((f e (f b (f e (f m m))))).\nsurgery id_l ((f e (f b (f e (f m m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_487: forall b: G, ((e <+> b) <+> (m <+> (m <+> ((e <+> e) <+> (m <+> (m <+> (e <+> m))))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e b) (f m (f m (f (f e e) (f m (f m (f e m)))))))) ((f b (f m (f m (f (f e e) (f m (f m (f e m)))))))).\nsurgery id_l ((f b (f m (f m (f (f e e) (f m (f m (f e m)))))))) ((f b (f m (f m (f e (f m (f m (f e m)))))))).\nsurgery id_l ((f b (f m (f m (f e (f m (f m (f e m)))))))) ((f b (f m (f m (f m (f m (f e m))))))).\nsurgery id_l ((f b (f m (f m (f m (f m (f e m))))))) ((f b (f m (f m (f m (f m m)))))).\nsurgery id_r ((f b (f m (f m (f m (f m m)))))) ((f b (f m (f m (f m m))))).\nsurgery id_r ((f b (f m (f m (f m m))))) ((f b (f m (f m m)))).\nsurgery id_r ((f b (f m (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_488: forall b: G, ((((((e <+> e) <+> m) <+> b) <+> m) <+> (m <+> (e <+> (e <+> m)))) <+> m) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f (f (f e e) m) b) m) (f m (f e (f e m)))) m)) ((f (f (f (f (f e e) m) b) m) (f m (f e (f e m))))).\nsurgery id_r ((f (f (f (f (f e e) m) b) m) (f m (f e (f e m))))) ((f (f (f (f e e) m) b) (f m (f e (f e m))))).\nsurgery id_r ((f (f (f (f e e) m) b) (f m (f e (f e m))))) ((f (f (f e e) b) (f m (f e (f e m))))).\nsurgery id_l ((f (f (f e e) b) (f m (f e (f e m))))) ((f (f e b) (f m (f e (f e m))))).\nsurgery id_l ((f (f e b) (f m (f e (f e m))))) ((f b (f m (f e (f e m))))).\nsurgery id_l ((f b (f m (f e (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_489: forall b: G, ((((e <+> e) <+> m) <+> (m <+> (e <+> m))) <+> ((e <+> b) <+> (e <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f (f e e) m) (f m (f e m))) (f (f e b) (f e m)))) ((f (f (f e e) (f m (f e m))) (f (f e b) (f e m)))).\nsurgery id_l ((f (f (f e e) (f m (f e m))) (f (f e b) (f e m)))) ((f (f e (f m (f e m))) (f (f e b) (f e m)))).\nsurgery id_l ((f (f e (f m (f e m))) (f (f e b) (f e m)))) ((f (f e (f m m)) (f (f e b) (f e m)))).\nsurgery id_r ((f (f e (f m m)) (f (f e b) (f e m)))) ((f (f e m) (f (f e b) (f e m)))).\nsurgery id_r ((f (f e m) (f (f e b) (f e m)))) ((f e (f (f e b) (f e m)))).\nsurgery id_l ((f e (f (f e b) (f e m)))) ((f e (f b (f e m)))).\nsurgery id_l ((f e (f b (f e m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_490: forall b: G, ((e <+> ((e <+> e) <+> m)) <+> (b <+> (e <+> (m <+> ((e <+> e) <+> m))))) = b.\nProof.\nintros.\nsurgery id_l ((f (f e (f (f e e) m)) (f b (f e (f m (f (f e e) m)))))) ((f (f e (f e m)) (f b (f e (f m (f (f e e) m)))))).\nsurgery id_l ((f (f e (f e m)) (f b (f e (f m (f (f e e) m)))))) ((f (f e m) (f b (f e (f m (f (f e e) m)))))).\nsurgery id_r ((f (f e m) (f b (f e (f m (f (f e e) m)))))) ((f e (f b (f e (f m (f (f e e) m)))))).\nsurgery id_l ((f e (f b (f e (f m (f (f e e) m)))))) ((f e (f b (f m (f (f e e) m))))).\nsurgery id_l ((f e (f b (f m (f (f e e) m))))) ((f e (f b (f m (f e m))))).\nsurgery id_l ((f e (f b (f m (f e m))))) ((f e (f b (f m m)))).\nsurgery id_r ((f e (f b (f m m)))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_491: forall b: G, (e <+> ((e <+> m) <+> ((((e <+> e) <+> e) <+> ((e <+> b) <+> m)) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f e (f (f e m) (f (f (f (f e e) e) (f (f e b) m)) m)))) ((f e (f e (f (f (f (f e e) e) (f (f e b) m)) m)))).\nsurgery id_l ((f e (f e (f (f (f (f e e) e) (f (f e b) m)) m)))) ((f e (f (f (f (f e e) e) (f (f e b) m)) m))).\nsurgery id_l ((f e (f (f (f (f e e) e) (f (f e b) m)) m))) ((f e (f (f (f e e) (f (f e b) m)) m))).\nsurgery id_l ((f e (f (f (f e e) (f (f e b) m)) m))) ((f e (f (f e (f (f e b) m)) m))).\nsurgery id_l ((f e (f (f e (f (f e b) m)) m))) ((f e (f (f e (f b m)) m))).\nsurgery id_r ((f e (f (f e (f b m)) m))) ((f e (f (f e b) m))).\nsurgery id_l ((f e (f (f e b) m))) ((f e (f b m))).\nsurgery id_r ((f e (f b m))) ((f e b)).\nsurgery id_l ((f e b)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_492: forall b: G, (((b <+> m) <+> (e <+> (e <+> m))) <+> ((e <+> m) <+> ((e <+> m) <+> m))) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f b m) (f e (f e m))) (f (f e m) (f (f e m) m)))) ((f (f b (f e (f e m))) (f (f e m) (f (f e m) m)))).\nsurgery id_l ((f (f b (f e (f e m))) (f (f e m) (f (f e m) m)))) ((f (f b (f e m)) (f (f e m) (f (f e m) m)))).\nsurgery id_l ((f (f b (f e m)) (f (f e m) (f (f e m) m)))) ((f (f b m) (f (f e m) (f (f e m) m)))).\nsurgery id_r ((f (f b m) (f (f e m) (f (f e m) m)))) ((f b (f (f e m) (f (f e m) m)))).\nsurgery id_r ((f b (f (f e m) (f (f e m) m)))) ((f b (f e (f (f e m) m)))).\nsurgery id_l ((f b (f e (f (f e m) m)))) ((f b (f (f e m) m))).\nsurgery id_r ((f b (f (f e m) m))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_493: forall b: G, (((e <+> (b <+> m)) <+> (((e <+> e) <+> m) <+> (m <+> m))) <+> (m <+> m)) = b.\nProof.\nintros.\nsurgery id_r ((f (f (f e (f b m)) (f (f (f e e) m) (f m m))) (f m m))) ((f (f (f e b) (f (f (f e e) m) (f m m))) (f m m))).\nsurgery id_l ((f (f (f e b) (f (f (f e e) m) (f m m))) (f m m))) ((f (f b (f (f (f e e) m) (f m m))) (f m m))).\nsurgery id_r ((f (f b (f (f (f e e) m) (f m m))) (f m m))) ((f (f b (f (f e e) (f m m))) (f m m))).\nsurgery id_l ((f (f b (f (f e e) (f m m))) (f m m))) ((f (f b (f e (f m m))) (f m m))).\nsurgery id_l ((f (f b (f e (f m m))) (f m m))) ((f (f b (f m m)) (f m m))).\nsurgery id_r ((f (f b (f m m)) (f m m))) ((f (f b m) (f m m))).\nsurgery id_r ((f (f b m) (f m m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_494: forall b: G, (b <+> ((e <+> (m <+> m)) <+> ((e <+> (e <+> m)) <+> (m <+> (e <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f e (f m m)) (f (f e (f e m)) (f m (f e m)))))) ((f b (f (f e m) (f (f e (f e m)) (f m (f e m)))))).\nsurgery id_r ((f b (f (f e m) (f (f e (f e m)) (f m (f e m)))))) ((f b (f e (f (f e (f e m)) (f m (f e m)))))).\nsurgery id_l ((f b (f e (f (f e (f e m)) (f m (f e m)))))) ((f b (f (f e (f e m)) (f m (f e m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f m (f e m))))) ((f b (f (f e m) (f m (f e m))))).\nsurgery id_r ((f b (f (f e m) (f m (f e m))))) ((f b (f e (f m (f e m))))).\nsurgery id_l ((f b (f e (f m (f e m))))) ((f b (f m (f e m)))).\nsurgery id_l ((f b (f m (f e m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_495: forall b: G, ((((e <+> (e <+> e)) <+> e) <+> (e <+> b)) <+> (((m <+> m) <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f (f (f e (f e e)) e) (f e b)) (f (f (f m m) m) m))) ((f (f (f (f e e) e) (f e b)) (f (f (f m m) m) m))).\nsurgery id_l ((f (f (f (f e e) e) (f e b)) (f (f (f m m) m) m))) ((f (f (f e e) (f e b)) (f (f (f m m) m) m))).\nsurgery id_l ((f (f (f e e) (f e b)) (f (f (f m m) m) m))) ((f (f e (f e b)) (f (f (f m m) m) m))).\nsurgery id_l ((f (f e (f e b)) (f (f (f m m) m) m))) ((f (f e b) (f (f (f m m) m) m))).\nsurgery id_l ((f (f e b) (f (f (f m m) m) m))) ((f b (f (f (f m m) m) m))).\nsurgery id_r ((f b (f (f (f m m) m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_496: forall b: G, ((b <+> (e <+> (e <+> m))) <+> ((e <+> (m <+> m)) <+> (e <+> (e <+> m)))) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e (f e m))) (f (f e (f m m)) (f e (f e m))))) ((f (f b (f e m)) (f (f e (f m m)) (f e (f e m))))).\nsurgery id_l ((f (f b (f e m)) (f (f e (f m m)) (f e (f e m))))) ((f (f b m) (f (f e (f m m)) (f e (f e m))))).\nsurgery id_r ((f (f b m) (f (f e (f m m)) (f e (f e m))))) ((f b (f (f e (f m m)) (f e (f e m))))).\nsurgery id_r ((f b (f (f e (f m m)) (f e (f e m))))) ((f b (f (f e m) (f e (f e m))))).\nsurgery id_r ((f b (f (f e m) (f e (f e m))))) ((f b (f e (f e (f e m))))).\nsurgery id_l ((f b (f e (f e (f e m))))) ((f b (f e (f e m)))).\nsurgery id_l ((f b (f e (f e m)))) ((f b (f e m))).\nsurgery id_l ((f b (f e m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_497: forall b: G, (b <+> ((((e <+> (e <+> m)) <+> m) <+> m) <+> (e <+> ((m <+> m) <+> m)))) = b.\nProof.\nintros.\nsurgery id_r ((f b (f (f (f (f e (f e m)) m) m) (f e (f (f m m) m))))) ((f b (f (f (f e (f e m)) m) (f e (f (f m m) m))))).\nsurgery id_r ((f b (f (f (f e (f e m)) m) (f e (f (f m m) m))))) ((f b (f (f e (f e m)) (f e (f (f m m) m))))).\nsurgery id_l ((f b (f (f e (f e m)) (f e (f (f m m) m))))) ((f b (f (f e m) (f e (f (f m m) m))))).\nsurgery id_r ((f b (f (f e m) (f e (f (f m m) m))))) ((f b (f e (f e (f (f m m) m))))).\nsurgery id_l ((f b (f e (f e (f (f m m) m))))) ((f b (f e (f (f m m) m)))).\nsurgery id_l ((f b (f e (f (f m m) m)))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_498: forall b: G, ((b <+> (e <+> ((e <+> (e <+> (e <+> m))) <+> m))) <+> ((m <+> m) <+> m)) = b.\nProof.\nintros.\nsurgery id_l ((f (f b (f e (f (f e (f e (f e m))) m))) (f (f m m) m))) ((f (f b (f (f e (f e (f e m))) m)) (f (f m m) m))).\nsurgery id_l ((f (f b (f (f e (f e (f e m))) m)) (f (f m m) m))) ((f (f b (f (f e (f e m)) m)) (f (f m m) m))).\nsurgery id_l ((f (f b (f (f e (f e m)) m)) (f (f m m) m))) ((f (f b (f (f e m) m)) (f (f m m) m))).\nsurgery id_r ((f (f b (f (f e m) m)) (f (f m m) m))) ((f (f b (f e m)) (f (f m m) m))).\nsurgery id_l ((f (f b (f e m)) (f (f m m) m))) ((f (f b m) (f (f m m) m))).\nsurgery id_r ((f (f b m) (f (f m m) m))) ((f b (f (f m m) m))).\nsurgery id_r ((f b (f (f m m) m))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\nQed.\n\nLemma rewrite_eq_499: forall b: G, ((b <+> ((e <+> m) <+> m)) <+> (e <+> ((e <+> m) <+> (e <+> (m <+> m))))) = b.\nProof.\nintros.\nsurgery id_r ((f (f b (f (f e m) m)) (f e (f (f e m) (f e (f m m)))))) ((f (f b (f e m)) (f e (f (f e m) (f e (f m m)))))).\nsurgery id_l ((f (f b (f e m)) (f e (f (f e m) (f e (f m m)))))) ((f (f b m) (f e (f (f e m) (f e (f m m)))))).\nsurgery id_r ((f (f b m) (f e (f (f e m) (f e (f m m)))))) ((f b (f e (f (f e m) (f e (f m m)))))).\nsurgery id_l ((f b (f e (f (f e m) (f e (f m m)))))) ((f b (f (f e m) (f e (f m m))))).\nsurgery id_r ((f b (f (f e m) (f e (f m m))))) ((f b (f e (f e (f m m))))).\nsurgery id_l ((f b (f e (f e (f m m))))) ((f b (f e (f m m)))).\nsurgery id_l ((f b (f e (f m m)))) ((f b (f m m))).\nsurgery id_r ((f b (f m m))) ((f b m)).\nsurgery id_r ((f b m)) (b).\nreflexivity.\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/gamepad/ml/rewrite/theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7569034262757212}}
{"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 int.Abs.\nRequire int.EuclideanDivision.\nRequire int.ComputerDivision.\nRequire number.Parity.\nRequire number.Divisibility.\n\nImport Znumtheory.\n\n(* Why3 goal *)\nNotation gcd := Zgcd (only parsing).\n\n(* Why3 goal *)\nLemma gcd_nonneg : forall (a:Z) (b:Z), (0%Z <= (gcd a b))%Z.\nProof.\nexact Zgcd_is_pos.\nQed.\n\n(* Why3 goal *)\nLemma gcd_def1 : forall (a:Z) (b:Z), (number.Divisibility.divides (gcd a b)\n  a).\nProof.\nintros a b.\napply Zgcd_is_gcd.\nQed.\n\n(* Why3 goal *)\nLemma gcd_def2 : forall (a:Z) (b:Z), (number.Divisibility.divides (gcd a b)\n  b).\nProof.\nintros a b.\napply Zgcd_is_gcd.\nQed.\n\n(* Why3 goal *)\nLemma gcd_def3 : forall (a:Z) (b:Z) (x:Z), (number.Divisibility.divides x\n  a) -> ((number.Divisibility.divides x b) -> (number.Divisibility.divides x\n  (gcd a b))).\nProof.\nintros a b x.\napply Zgcd_is_gcd.\nQed.\n\n(* Why3 goal *)\nLemma gcd_unique : forall (a:Z) (b:Z) (d:Z), (0%Z <= d)%Z ->\n  ((number.Divisibility.divides d a) -> ((number.Divisibility.divides d b) ->\n  ((forall (x:Z), (number.Divisibility.divides x a) ->\n  ((number.Divisibility.divides x b) -> (number.Divisibility.divides x\n  d))) -> (d = (gcd a b))))).\nProof.\nintros.\napply sym_eq.\napply Zis_gcd_gcd.\nexact H.\nnow constructor.\nQed.\n\n(* Why3 goal *)\nLemma Assoc : forall (x:Z) (y:Z) (z:Z), ((gcd (gcd x y) z) = (gcd x (gcd y\n  z))).\nProof.\nexact Zgcd_ass.\nQed.\n\n(* Why3 goal *)\nLemma Comm : forall (x:Z) (y:Z), ((gcd x y) = (gcd y x)).\nProof.\nexact Zgcd_comm.\nQed.\n\n(* Why3 goal *)\nLemma gcd_0_pos : forall (a:Z), (0%Z <= a)%Z -> ((gcd a 0%Z) = a).\nProof.\nintros a H.\nrewrite <- (Zabs_eq a H) at 2.\napply Zgcd_0.\nQed.\n\n(* Why3 goal *)\nLemma gcd_0_neg : forall (a:Z), (a < 0%Z)%Z -> ((gcd a 0%Z) = (-a)%Z).\nProof.\nintros a H.\nrewrite <- Zabs_non_eq.\napply Zgcd_0.\nnow apply Zlt_le_weak.\nQed.\n\n(* Why3 goal *)\nLemma gcd_opp : forall (a:Z) (b:Z), ((gcd a b) = (gcd (-a)%Z b)).\nProof.\nintros a b.\napply Zis_gcd_gcd.\napply Zgcd_is_pos.\napply Zis_gcd_minus.\napply Zis_gcd_sym.\napply Zgcd_is_gcd.\nQed.\n\n(* Why3 goal *)\nLemma gcd_euclid : forall (a:Z) (b:Z) (q:Z), ((gcd a b) = (gcd a\n  (b - (q * a)%Z)%Z)).\nProof.\nintros a b c.\napply Zis_gcd_gcd.\napply Zgcd_is_pos.\napply Zis_gcd_sym.\napply Zis_gcd_for_euclid with c.\napply Zgcd_is_gcd.\nQed.\n\n(* Why3 goal *)\nLemma Gcd_computer_mod : forall (a:Z) (b:Z), (~ (b = 0%Z)) -> ((gcd b\n  (ZArith.BinInt.Z.rem a b)) = (gcd a b)).\nProof.\nintros a b _.\nrewrite (Zgcd_comm a b).\nrewrite (gcd_euclid b a (Z.quot a b)).\napply f_equal.\nrewrite (Z.quot_rem' a b) at 2.\nring.\nQed.\n\n(* Why3 goal *)\nLemma Gcd_euclidean_mod : forall (a:Z) (b:Z), (~ (b = 0%Z)) -> ((gcd b\n  (int.EuclideanDivision.mod1 a b)) = (gcd a b)).\nProof.\nintros a b Zb.\nrewrite (Zgcd_comm a b).\nrewrite (gcd_euclid b a (EuclideanDivision.div a b)).\napply f_equal.\nrewrite (EuclideanDivision.Div_mod a b Zb) at 2.\nring.\nQed.\n\n(* Why3 goal *)\nLemma gcd_mult : forall (a:Z) (b:Z) (c:Z), (0%Z <= c)%Z -> ((gcd (c * a)%Z\n  (c * b)%Z) = (c * (gcd a b))%Z).\nProof.\nintros a b c H.\napply Zis_gcd_gcd.\napply Zmult_le_0_compat with (1 := H).\napply Zgcd_is_pos.\napply Zis_gcd_mult.\napply Zgcd_is_gcd.\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/number/Gcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7567936691648538}}
{"text": "Set Warnings \"-notation-overridden\".\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nRequire Import Arith Euclid Ring Omega.\n\nCheck modulo.\nCompute modulo 5.\n\nLocate \"%|\".\nLocate dvdn.\nPrint dvdn.\nLocate \"%%\".\nCompute 100 %% 37.\nPrint modn.\nPrint modn_rec.\n\nDefinition mod' n m := modulo (S m) (lt_O_Sn m) n.\n\nCompute proj1_sig (mod' 5 3).\nCheck proj1_sig.\n\nRequire Import Recdef.\nFunction gcd (m n : nat) {wf lt m} : nat :=\n  match m with\n  | 0    => n\n  | S m' => gcd (proj1_sig (mod' n m')) m\n  end.\n  (*減少の証明*)\n  intros. destruct (mod' n m'). simpl.\n  destruct e as [q [Hn Hm]].\n  apply Hm.\n  (*清楚性の証明*)\n  exact lt_wf.\nDefined.\n\nCompute gcd 18 24.\n\nInductive divides (m:nat) : nat -> Prop :=\n  divi : forall a, divides m (a * m).\n\nLemma divide : forall a m n, n = a * m -> divides m n.\nProof.\n  intros. rewrite H. constructor.\nQed.\n\nLemma divides_mult : forall m q n, divides m n -> divides m (q * n).\nProof.\n  induction 1.\n  replace (q*(a*m)) with (q*a*m).\n  by apply divide with (a:=q*a).\n  by rewrite mulnA.\nQed.\n\nTheorem divides_plus : forall m n p, divides m n ->\n  divides m p -> divides m (n + p).\nProof.\n  intros. destruct H. destruct H0.\n  replace (a*m+a0*m) with ((a+a0)*m).\n  apply divi.\n  by rewrite mulnDl.\nQed.\n\nTheorem divides_1 : forall n, divides 1 n.\nProof.\n  intros.\n  replace n with (n*1).\n  apply divi.\n  apply muln1.\nQed.\n\nTheorem divides_0 : forall n, divides n 0.\nProof.\n  intros.\n  replace 0 with (0*n).\n  apply divi.\n  apply mul0n.\nQed.\n\nTheorem divides_n : forall n, divides n n.\nProof.\n  intros.\n  rewrite {2}(_ : n = 1 * n).\n  apply divi.\n  by rewrite mul1n.\nQed.\n\nHint Resolve divides_plus divides_mult divides_1 divides_0 divides_n.\n\nTheorem gcd_divides : forall m n,\n  divides (gcd m n) m /\\ divides (gcd m n) n.\nProof.\n  intros.\n  functional induction (gcd m n).\n  auto.\n  destruct (mod' n m').\n  simpl in *.\n  destruct e as [q [Hn Hm]].\n  destruct IHn0.\n  split; auto.\n  rewrite Hn.\n  auto.\nQed.\n\n\nTheorem plus_inj : forall m n p,\n  m + n = m + p -> n = p.\nProof.\n  intros.\n  induction m.\n  by rewrite 2!add0n in H.\n  apply IHm.\n  assert(H2:S(m+n)=S(m+p)).\n  rewrite -add1n. rewrite (_ : (m+p).+1=(1+(m+p))).\n  by rewrite addnA. apply add1n.\n  by inversion H2.\nQed.\n\nRequire Import Omega.\n\nLemma divides_plus' : forall m n p,\n  divides m n -> divides m (n+p) -> divides m p.\nProof.\n  induction 1.\n  intro.\n  induction a. assumption.\n  inversion H.\n  destruct a0.\n  destruct p.\n  auto.\n  elimtype False.\n  destruct m. destruct a. try discriminate. \n  rewrite 2!muln0 in H1.\n  inversion H1.\n  rewrite mul0n in H1.\n  inversion H1.\n  apply IHa.\n  rewrite -add1n in H1. rewrite (_:a.+1=(1+a)) in H1.\n  rewrite 2!mulnDl in H1. rewrite (_:(1*m+a*m+p)=(1*m)+(a*m+p)) in H1.\n  apply plus_inj in H1. rewrite -H1. constructor.\n  by rewrite addnA. apply add1n.\nQed.\n\nTheorem add_compat : forall m n, addn m n = Init.Nat.add m n.\nProof.\n  intros. induction m.\n  by [].\n  by [].\nQed.\n\nTheorem mul_compat : forall m n, muln m n = Init.Nat.mul m n.\nProof.\n  by [].\nQed.\n\nTheorem gcd_max : forall g m n,\n  divides g m -> divides g n -> divides g (gcd m n).\nProof.\n  intros.\n  functional induction (gcd m n).\n  assumption.\n  destruct (mod' n m'). simpl in *.\n  destruct e as [q [Hn Hm']].\n  apply IHn0.\n  apply divides_plus' with (n:=q*S m').\n  induction H. rewrite (_ : (q*(a*g))=((q*a)*g)).\n  apply divi. by rewrite mulnA.\n  rewrite (_ : (q * m'.+1 + x)=(((q * m'.+1)%coq_nat+x)%coq_nat)).\n  by rewrite -Hn. Locate addn.\n  apply add_compat.\n  apply H.\nQed.\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/EuclideanAlgorithm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7567936558331553}}
{"text": "Require Export TopologicalSpaces.\nRequire Export DirectedSets.\nRequire Export InteriorsClosures.\nRequire Export Continuity.\n\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}.\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": "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/Nets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7567840082431038}}
{"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\n(* As usual, a set of spoiler-containing hints to help you along when you \n * get stuck with certain pset questions has been provided at the bottom of \n * the signature file! *)\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  (* HINT 1 (see Pset4Sig.v) *)\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 in the signature file 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     in the signature file 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  (* HINT 2-5 (see Pset4Sig.v) *)\n  Lemma bst_delete : forall tr s a, bst tr s ->\n    bst (delete a tr) (fun x => s x /\\ x <> a).\n  Proof.\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 * Amanda Liu\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/Pset4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7567244242005197}}
{"text": "(* week_39b_arithmetic_expressions.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Working version, make sure to download\n   the updated version after class.\n*)\n\n(* ********** *)\n\nRequire Import Arith Bool List unfold_tactic.\n\n(* ********** *)\n\n(* Source syntax: *)\n\nInductive arithmetic_expression : Type :=\n  | Lit : nat -> arithmetic_expression\n  | Plus : arithmetic_expression -> arithmetic_expression -> arithmetic_expression\n  | Times : arithmetic_expression -> arithmetic_expression -> arithmetic_expression.\n\n(* Exercise 0:\n   Write samples of arithmetic expressions.\n*)\n\nDefinition ae_0 :=\n  Lit 5.\n\nDefinition ae_1 :=\n  Plus (Lit 2) (Lit 3).\n\nDefinition ae_2 :=\n  Times (Plus (Lit 1) (Lit 2))\n        (Lit 2).\n\n(* ********** *)\n\nDefinition specification_of_interpret (interpret : arithmetic_expression -> nat) :=\n  (forall n : nat,\n     interpret (Lit n) = n)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Plus ae1 ae2) = (interpret ae1) + (interpret ae2))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     interpret (Times ae1 ae2) = (interpret ae1) * (interpret ae2)).\n\n(* Exercise 1:\n   Write unit tests.\n*)\n\nDefinition unit_test_for_interpret (interpret : arithmetic_expression -> nat) :=\n  (beq_nat (interpret ae_0) 5)\n  &&\n  (beq_nat (interpret ae_1) 5)\n  &&\n  (beq_nat (interpret ae_2) 6)\n  &&\n  (beq_nat (interpret (Times ae_1 ae_2)) 30).\n\n(* Exercise 2:\n   Define an interpreter as a function\n   that satisfies the specification above\n   and verify that it passes the unit tests.\n*)\n\nTheorem there_is_only_one_interpret :\n  forall (f g : arithmetic_expression -> nat),\n    specification_of_interpret f ->\n    specification_of_interpret g ->\n    forall (ae : arithmetic_expression),\n      f ae = g ae.\nProof.\n  intros f g.\n  unfold specification_of_interpret.\n  intros [H_f_lit [H_f_plus H_f_times]] [H_g_lit [H_g_plus H_g_times]].\n  intro ae.\n  induction ae as [ n | ae1 IHae1 ae2 IHae2 | ae1' IHae1' ae2' IHae2' ].\n      rewrite -> H_f_lit.\n      rewrite -> H_g_lit.\n      reflexivity.\n    rewrite -> H_f_plus.\n    rewrite -> H_g_plus.\n    rewrite -> IHae1.\n    rewrite -> IHae2.\n    reflexivity.\n  rewrite -> H_f_times.\n  rewrite -> H_g_times.\n  rewrite -> IHae1'.\n  rewrite -> IHae2'.\n  reflexivity.\nQed.\n\nFixpoint interpret_ds (ae : arithmetic_expression) :=\n  match ae with\n  | Lit n => n\n  | Plus ae1 ae2 => interpret_ds ae1 + interpret_ds ae2\n  | Times ae1 ae2 => interpret_ds ae1 * interpret_ds ae2\n  end.\n\nDefinition interpret (ae : arithmetic_expression) :=\n  interpret_ds ae.\n\nCompute unit_test_for_interpret interpret.\n\nLemma unfold_interpret_ds_lit :\n  forall n : nat,\n    interpret_ds (Lit n) = n.\nProof.\n  unfold_tactic interpret_ds.\nQed.\n\nLemma unfold_interpret_ds_plus :\n  forall ae1 ae2 : arithmetic_expression,\n    interpret_ds (Plus ae1 ae2) = interpret_ds ae1 + interpret_ds ae2.\nProof.\n  unfold_tactic interpret_ds.\nQed.\n\nLemma unfold_interpret_ds_times :\n  forall ae1 ae2 : arithmetic_expression,\n    interpret_ds (Times ae1 ae2) = interpret_ds ae1 * interpret_ds ae2.\nProof.\n  unfold_tactic interpret_ds.\nQed.\n\nProposition interpret_fits_the_specification_of_interpret :\n  specification_of_interpret interpret.\nProof.\n  unfold specification_of_interpret.\n  split.\n    exact unfold_interpret_ds_lit.\n  split.\n    exact unfold_interpret_ds_plus.\n  exact unfold_interpret_ds_times.\nQed.\n\n(* Byte-code instructions: *)\n\nInductive byte_code_instruction : Type :=\n  | PUSH : nat -> byte_code_instruction\n  | ADD : byte_code_instruction\n  | MUL : byte_code_instruction.\n\n(* ********** *)\n\n(* Byte-code programs: *)\n\nDefinition byte_code_program := list byte_code_instruction.\n\n(* Data stack: *)\n\nDefinition data_stack := list nat.\n\n(* ********** *)\n\n(* Exercise 3:\n   specify a function\n     execute_byte_code_instruction : instr -> data_stack -> data_stack\n   that executes a byte-code instruction, given a data stack\n   and returns this stack after the instruction is executed.\n\n   * Executing (PUSH n) given s has the effect of pushing n on s.\n\n   * Executing ADD given s has the effect of popping two numbers\n     from s and then pushing the result of adding them.\n\n   * Executing MUL given s has the effect of popping two numbers\n     from s and then pushing the result of multiplying them.\n\n   For now, if the stack underflows, just assume it contains zeroes.\n*)\n\nFixpoint beq_list (T : Type) (l1 l2 : list T) (comp : T -> T -> bool) := \n  match l1 with\n  | nil =>\n      match l2 with\n      | nil => true\n      | _ => false\n      end\n  | e :: l =>\n      match l2 with\n      | nil => false\n      | e' :: l' =>\n          match comp e e' with\n          | false => false\n          | true => beq_list T l l' comp\n          end\n      end\n  end.\n\nDefinition beq_nat_list (l1 l2 : list nat) :=\n  beq_list nat l1 l2 beq_nat.\n\nDefinition s_0 : list nat :=\n  nil.\nDefinition s_1 :=\n  2 :: nil.\nDefinition s_2 :=\n  2 :: 3 :: nil.\n\nCompute beq_nat_list s_0 s_0. (* true *)\nCompute beq_nat_list s_1 s_1. (* true *)\nCompute beq_nat_list s_2 s_2. (* true *)\nCompute beq_nat_list s_1 s_2. (* false *)\n\nDefinition unit_test_for_execute_byte_code_instruction (exec : byte_code_instruction -> data_stack -> data_stack) :=\n  (* Test for push *)\n  (beq_nat_list (exec (PUSH 2) s_1)\n                (2 :: 2 :: nil))\n  &&\n  (* Test for add *)\n  (beq_nat_list (exec ADD s_0) \n                (0 :: nil))\n  &&\n  (beq_nat_list (exec ADD s_1)\n                s_1)\n  &&\n  (beq_nat_list (exec ADD s_2)\n                (5 :: nil))\n  &&\n  (* Test for mul *)\n  (beq_nat_list (exec MUL s_0)\n                (0 :: nil))\n  &&\n  (beq_nat_list (exec MUL s_1)\n                (0 :: nil))\n  &&\n  (beq_nat_list (exec MUL s_2)\n                (6 :: nil)).\n\nDefinition specification_of_execute_byte_code_instruction (exec : byte_code_instruction -> data_stack -> data_stack) :=\n  (forall (n : nat) (s : data_stack),\n    exec (PUSH n) s = n :: s)\n  /\\\n  (forall (s : data_stack),\n    exec ADD s = match s with\n                 | nil => 0 :: nil\n                 | n :: nil => n :: nil\n                 | n :: n' :: s' => n + n' :: s'\n                 end)\n  /\\\n  (forall (s : data_stack),\n    exec MUL s = match s with\n                 | nil => 0 :: nil\n                 | n :: nil => 0 :: nil\n                 | n :: n' :: s' => n * n' :: s'\n                 end).\n\nTheorem there_is_only_one_execute_byte_code_instruction :\n  forall (f g : byte_code_instruction -> data_stack -> data_stack),\n    specification_of_execute_byte_code_instruction f ->\n    specification_of_execute_byte_code_instruction g ->\n    forall (instr : byte_code_instruction) (s : data_stack),\n      f instr s = g instr s.\nProof.\n  intros f g.\n  unfold specification_of_execute_byte_code_instruction.\n  intros [H_f_push [H_f_add H_f_mul]].\n  intros [H_g_push [H_g_add H_g_mul]].\n  intros instr s.\n  case instr as [ n | | ].\n      rewrite -> H_f_push.\n      rewrite -> H_g_push.\n      reflexivity.\n    rewrite -> H_f_add.\n    rewrite -> H_g_add.\n    reflexivity.\n  rewrite -> H_f_mul.\n  rewrite -> H_g_mul.\n  reflexivity.\nQed.\n\nDefinition execute_byte_code_instruction (instr : byte_code_instruction) (s : data_stack) :=\n  match instr with\n  | PUSH n => n :: s\n  | ADD =>\n      match s with\n      | nil => 0 :: nil\n      | n :: nil => n :: nil\n      | n :: n' :: s' => n + n' :: s'\n      end\n  | MUL =>\n      match s with\n      | nil => 0 :: nil\n      | n :: nil => 0 :: nil\n      | n :: n' :: s' => n * n' :: s'\n      end\n  end.\n\nCompute unit_test_for_execute_byte_code_instruction execute_byte_code_instruction.\n\nTheorem execute_byte_code_instruction_fits_the_specification :\n  specification_of_execute_byte_code_instruction execute_byte_code_instruction.\nProof.\n  unfold specification_of_execute_byte_code_instruction.\n  unfold execute_byte_code_instruction.\n  split.\n    intros n s.\n    reflexivity.\n  split.\n    intro s.\n    reflexivity.\n  intro s.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Exercise 4:\n   Define a function\n     execute_byte_code_program : byte_code_program -> data_stack -> data_stack\n   that executes a given byte-code program on a given data stack,\n   and returns this stack after the program is executed.\n*)\n\nDefinition p_0 :=\n  ADD :: nil.\nDefinition p_1 :=\n  ADD :: ADD :: nil.\nDefinition p_2 :=\n  ADD :: MUL :: nil.\n\nDefinition unit_test_for_execute_byte_code_program (exec_prog : byte_code_program -> data_stack -> data_stack) :=\n  (beq_nat_list (exec_prog p_0 nil)\n                (0 :: nil))\n  &&\n  (beq_nat_list (exec_prog p_0 s_2)\n                (5 :: nil))\n  &&\n  (beq_nat_list (exec_prog p_1 (s_1 ++ s_2))\n                (7 :: nil))\n  &&\n  (beq_nat_list (exec_prog p_2 (s_1 ++ s_2))\n                (12 :: nil)).\n\nDefinition specification_of_execute_byte_code_program (exec_prog : byte_code_program -> data_stack -> data_stack) :=\n  (forall s : data_stack,\n    exec_prog nil s = s)\n  /\\\n  (forall (instr : byte_code_instruction) (prog : byte_code_program) (s : data_stack),\n    exec_prog (instr :: prog) s = exec_prog prog (execute_byte_code_instruction instr s)).\n\nTheorem there_is_only_one_execute_byte_code_program :\n  forall (f g : byte_code_program -> data_stack -> data_stack),\n    specification_of_execute_byte_code_program f ->\n    specification_of_execute_byte_code_program g ->\n    forall (prog : byte_code_program) (s : data_stack),\n      f prog s = g prog s.\nProof.\n  intros f g.\n  unfold specification_of_execute_byte_code_program.\n  intros [H_f_bc H_f_ic] [H_g_bc H_g_ic].\n\n  intros prog.\n  induction prog as [ | x xs IHx ].\n\n  intro s.\n  rewrite -> H_f_bc.\n  rewrite -> H_g_bc.\n  reflexivity.\n\n  intro s.\n  rewrite -> H_f_ic.\n  rewrite -> H_g_ic.\n  rewrite -> IHx.\n  reflexivity.\nQed.\n\nFixpoint execute_byte_code_program (prog : byte_code_program) (s : data_stack) :=\n  match prog with\n  | nil => s\n  | instr :: prog => execute_byte_code_program prog (execute_byte_code_instruction instr s)\n  end.\n\nCompute unit_test_for_execute_byte_code_program execute_byte_code_program.\n\nLemma unfold_execute_byte_code_program_bc :\n  forall s : data_stack,\n    execute_byte_code_program nil s = s.\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\nLemma unfold_execute_byte_code_program_ic :\n  forall (instr : byte_code_instruction) (prog : byte_code_program) (s : data_stack),\n    execute_byte_code_program (instr :: prog) s = execute_byte_code_program prog (execute_byte_code_instruction instr s).\nProof.\n  unfold_tactic execute_byte_code_program.\nQed.\n\nTheorem execute_byte_code_program_fits_the_specification :\n  specification_of_execute_byte_code_program execute_byte_code_program.\nProof.\n  unfold specification_of_execute_byte_code_program.\n  split.\n    exact unfold_execute_byte_code_program_bc.\n  exact unfold_execute_byte_code_program_ic.\nQed.\n\n(* ********** *)\n\n(* Exercise 5:\n   Prove that for all programs p1, p2 and data stacks s,\n   executing (p1 ++ p2) with s\n   gives the same result as\n   (1) executing p1 with s, and then\n   (2) executing p2 with the resulting stack.\n*)\n\nLemma unfold_append_bc :\n  forall (bcis : list byte_code_instruction),\n    nil ++ bcis = bcis.\nProof.\n  apply app_nil_l.\nQed.\n\nLemma unfold_append_ic :\n  forall (bci1 : byte_code_instruction) (bci1s' bci2s : list byte_code_instruction),\n    (bci1 :: bci1s') ++ bci2s = bci1 :: (bci1s' ++ bci2s).\nProof.\n  intros bci1 bci1s' bci2s.\n  symmetry.\n  apply app_comm_cons.\nQed.\n\nLemma about_execute_byte_code_program :\n  forall (p1 p2 : byte_code_program) (s : data_stack),\n    execute_byte_code_program (p1 ++ p2) s = execute_byte_code_program p2 (execute_byte_code_program p1 s).\nProof.\n  intro p1.\n  induction p1 as [ | instr prog IHprog ].\n    intros p2 s.\n    rewrite -> unfold_append_bc.\n    rewrite -> unfold_execute_byte_code_program_bc.\n    reflexivity.\n  intros p2 s.\n  rewrite -> unfold_append_ic.\n  rewrite ->2 unfold_execute_byte_code_program_ic.\n  rewrite -> IHprog.\n  reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_compile (compile : arithmetic_expression -> byte_code_program) :=\n  (forall n : nat,\n     compile (Lit n) = PUSH n :: nil)\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Plus ae1 ae2) = (compile ae1) ++ (compile ae2) ++ (ADD :: nil))\n  /\\\n  (forall ae1 ae2 : arithmetic_expression,\n     compile (Times ae1 ae2) = (compile ae1) ++ (compile ae2) ++ (MUL :: nil)).\n\n(* Exercise 6:\n   Define a compiler as a function\n   that satisfies the specification above\n   and uses list concatenation, i.e., ++.\n*)\n\nDefinition beq_instr (i1 i2 : byte_code_instruction) :=\n  match i1 with\n  | PUSH n1 =>\n      match i2 with\n      | PUSH n2 => beq_nat n1 n2\n      | _ => false\n      end\n  | ADD =>\n      match i2 with\n      | ADD => true\n      | _ => false\n      end\n  | MUL =>\n      match i2 with\n      | MUL => true\n      | _ => false\n      end\n  end.\n\nCompute beq_instr (PUSH 2) (PUSH 2). (* true *)\nCompute beq_instr (PUSH 2) (PUSH 3). (* false *)\nCompute beq_instr ADD ADD.           (* true *)\nCompute beq_instr MUL ADD.           (* false *) \n\nDefinition beq_instr_list (p1 p2 : byte_code_program) :=\n  beq_list byte_code_instruction p1 p2 beq_instr.\n\nCompute beq_instr_list p_0 p_0. (* true *)\nCompute beq_instr_list p_1 p_1. (* true *)\nCompute beq_instr_list p_2 p_2. (* true *)\nCompute beq_instr_list p_1 p_2. (* false *)\n\nDefinition unit_test_for_compile (compile : arithmetic_expression -> byte_code_program) :=\n  (beq_instr_list (compile ae_0)\n                  (PUSH 5 :: nil))\n  &&\n  (beq_instr_list (compile ae_1)\n                  (PUSH 2 :: PUSH 3 :: ADD :: nil))\n  &&\n  (beq_instr_list (compile ae_2)\n                  (PUSH 1 :: PUSH 2 :: ADD :: PUSH 2 :: MUL :: nil)).\n\nTheorem there_is_only_one_compile :\n  forall (f g : arithmetic_expression -> byte_code_program),\n    specification_of_compile f ->\n    specification_of_compile g ->\n    forall (ae : arithmetic_expression),\n      f ae = g ae.\nProof.\n  intros f g.\n  unfold specification_of_compile.\n  intros [Hf_lit [Hf_plus Hf_times]].\n  intros [Hg_lit [Hg_plus Hg_times]].\n  intro ae.\n  induction ae as [ n | ae1 IHae1 ae2 IHae2 | ae1' IHae1' ae2' IHae2' ].\n      rewrite -> Hf_lit.\n      rewrite -> Hg_lit.\n      reflexivity.\n    rewrite -> Hf_plus.\n    rewrite -> Hg_plus.\n    rewrite -> IHae1.\n    rewrite -> IHae2.\n    reflexivity.\n  rewrite -> Hf_times.\n  rewrite -> Hg_times.\n  rewrite -> IHae1'.\n  rewrite -> IHae2'.\n  reflexivity.\nQed.\n\nFixpoint compile_ds (ae : arithmetic_expression) :=\n  match ae with\n  | Lit n => PUSH n :: nil\n  | Plus ae1 ae2 => (compile_ds ae1) ++ (compile_ds ae2) ++ (ADD :: nil)\n  | Times ae1 ae2 => (compile_ds ae1) ++ (compile_ds ae2) ++ (MUL :: nil)\n  end.\n\nDefinition compile_v0 (ae : arithmetic_expression) :=\n  compile_ds ae.\n\nCompute unit_test_for_compile compile_v0.\n\nLemma unfold_compile_ds_lit :\n  forall n : nat,\n    compile_ds (Lit n) = PUSH n :: nil.\nProof.\n  unfold_tactic compile_ds.\nQed.\n\nLemma unfold_compile_ds_plus :\n  forall (ae1 ae2 : arithmetic_expression),\n    compile_ds (Plus ae1 ae2) = (compile_ds ae1) ++ (compile_ds ae2) ++ (ADD :: nil).\nProof.\n  unfold_tactic compile_ds.\nQed.\n\nLemma unfold_compile_ds_times :\n  forall (ae1 ae2 : arithmetic_expression),\n    compile_ds (Times ae1 ae2) = (compile_ds ae1) ++ (compile_ds ae2) ++ (MUL :: nil).\nProof.\n  unfold_tactic compile_ds.\nQed.\n\nTheorem compile_v0_fits_the_specification_of_compile :\n  specification_of_compile compile_v0.\nProof.\n  unfold specification_of_compile.\n  split.\n    exact unfold_compile_ds_lit.\n  split.\n    exact unfold_compile_ds_plus.\n  exact unfold_compile_ds_times.\nQed.\n\n(* Exercise 7:\n   Write a compiler as a function with an accumulator\n   that does not use ++ but :: instead,\n   and prove it equivalent to the compiler of Exercise 6.\n*)\n\nFixpoint compile_acc (ae : arithmetic_expression) (prog : byte_code_program) :=\n  match ae with\n  | Lit n => PUSH n :: prog\n  | Plus ae1 ae2 => compile_acc ae1 (compile_acc ae2 (ADD :: prog))\n  | Times ae1 ae2 => compile_acc ae1 (compile_acc ae2 (MUL :: prog))\n  end.\n\nDefinition compile_v1 (ae : arithmetic_expression) :=\n  compile_acc ae nil.\n\nCompute unit_test_for_compile compile_v1.\n\nLemma unfold_compile_acc_lit :\n  forall (n : nat) (prog : byte_code_program),\n    compile_acc (Lit n) prog = PUSH n :: prog.\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma unfold_compile_acc_plus :\n  forall (ae1 ae2 : arithmetic_expression) (prog : byte_code_program),\n    compile_acc (Plus ae1 ae2) prog = compile_acc ae1 (compile_acc ae2 (ADD :: prog)).\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma unfold_compile_acc_times :\n  forall (ae1 ae2 : arithmetic_expression) (prog : byte_code_program),\n    compile_acc (Times ae1 ae2) prog = compile_acc ae1 (compile_acc ae2 (MUL :: prog)).\nProof.\n  unfold_tactic compile_acc.\nQed.\n\nLemma about_compile_acc :\n  forall (ae : arithmetic_expression) (prog : byte_code_program),\n    compile_acc ae prog = compile_acc ae nil ++ prog.\nProof.\n  intro ae.\n  induction ae as [ n | ae1 IHae1 ae2 IHae2 | ae1' IHae1' ae2' IHae2' ].\n      intro prog.\n      rewrite ->2 unfold_compile_acc_lit.\n      rewrite -> unfold_append_ic.\n      rewrite -> unfold_append_bc.\n      reflexivity.\n    intro prog.\n    rewrite ->2 unfold_compile_acc_plus.\n    rewrite -> IHae1.\n    rewrite -> IHae2.\n    rewrite -> (IHae1 (compile_acc ae2 (ADD :: nil))).\n    rewrite -> (IHae2 (ADD :: nil)).\n    rewrite ->2 app_assoc_reverse.\n    rewrite -> unfold_append_ic.\n    rewrite -> unfold_append_bc.\n    reflexivity.\n  intro prog.\n  rewrite ->2 unfold_compile_acc_times.\n  rewrite -> IHae1'.\n  rewrite -> IHae2'.\n  rewrite -> (IHae1' (compile_acc ae2' (MUL :: nil))).\n  rewrite -> (IHae2' (MUL :: nil)).\n  rewrite ->2 app_assoc_reverse.\n  rewrite -> unfold_append_ic.\n  rewrite -> unfold_append_bc.\n  reflexivity.\nQed.\n\nTheorem compile_v1_fits_the_specification_of_compile :\n  specification_of_compile compile_v1.\nProof.\n  unfold specification_of_compile.\n  unfold compile_v1.\n  split.\n    intro n.\n    apply unfold_compile_acc_lit.\n  split.\n    intros ae1 ae2.\n    rewrite -> unfold_compile_acc_plus.\n    rewrite -> about_compile_acc.\n    rewrite -> (about_compile_acc ae2 (ADD :: nil)).\n    reflexivity.\n  intros ae1 ae2.\n  rewrite -> unfold_compile_acc_times.\n  rewrite -> about_compile_acc.\n  rewrite -> (about_compile_acc ae2 (MUL :: nil)).\n  reflexivity.\nQed.\n\nProposition compile_v0_and_compile_v1_are_equivalent :\n  forall ae : arithmetic_expression,\n    compile_v0 ae = compile_v1 ae.\nProof.\n  apply there_is_only_one_compile.\n    exact compile_v0_fits_the_specification_of_compile.\n  exact compile_v1_fits_the_specification_of_compile.\nQed.\n\n(* ********** *)\n\n(* Exercise 8:\n   Prove that interpreting an arithmetic expression gives the same result\n   as first compiling it and then executing the compiled program\n   over an empty data stack.\n*)\n\nDefinition unit_test_for_run (run : byte_code_program -> nat) :=\n  (beq_nat (run (PUSH 5 :: nil))\n           5)\n  &&\n  (beq_nat (run (PUSH 1 :: PUSH 2 :: ADD :: nil))\n           3)\n  &&\n  (beq_nat (run (PUSH 1 :: PUSH 2 :: MUL :: nil))\n           2)\n  &&\n  (beq_nat (run (nil))\n           0)\n  &&\n  (beq_nat (run (PUSH 1 :: MUL :: nil))\n           0)\n  &&\n  (beq_nat (run (PUSH 1 :: ADD :: nil))\n           1)\n  &&\n  (beq_nat (run (ADD :: MUL :: nil))\n           0).\n\nDefinition specification_of_run (run : byte_code_program -> nat) :=\n  forall prog : byte_code_program,\n    run prog = \n      match execute_byte_code_program prog nil with\n      | result :: nil => result\n      | _ => 0\n      end.\n\nTheorem there_is_only_one_run :\n  forall (f g : byte_code_program -> nat),\n    specification_of_run f ->\n    specification_of_run g ->\n    forall prog : byte_code_program,\n      f prog = g prog.\nProof.\n  intros f g.\n  unfold specification_of_run.\n  intros S_f S_g.\n  intro prog.\n  rewrite -> S_f.\n  rewrite -> S_g.\n  reflexivity.\nQed.\n\nDefinition run (prog : byte_code_program) :=\n  match execute_byte_code_program prog nil with\n  | result :: nil => result\n  | _ => 0\n  end.\n\nCompute unit_test_for_run run.\n\nLemma interpret_exp_cons_datastack_eq_execute_compile_exp_ds :\n  forall (ae : arithmetic_expression) (s : data_stack),\n    interpret ae :: s = execute_byte_code_program (compile_v0 ae) s.\nProof.\n  intro ae.\n  induction ae as [ n | ae1 IHae1 ae2 IHae2 | ae1' IHae1' ae2' IHae2' ].\n      intro s.\n      rewrite -> unfold_interpret_ds_lit.\n      rewrite -> unfold_compile_ds_lit.\n      rewrite -> unfold_execute_byte_code_program_ic.\n      rewrite -> unfold_execute_byte_code_program_bc.\n      unfold execute_byte_code_instruction.\n      reflexivity.\n    intro s.\n    unfold interpret.\n    rewrite -> unfold_interpret_ds_plus.\n    unfold compile_v0.\n    rewrite -> unfold_compile_ds_plus.\n    rewrite ->2 about_execute_byte_code_program.\n    rewrite -> unfold_execute_byte_code_program_ic.\n    rewrite -> unfold_execute_byte_code_program_bc.\n    rewrite <- IHae1.\n    rewrite <- IHae2.\n    unfold execute_byte_code_instruction.\n    rewrite -> plus_comm.\n    reflexivity.\n  intro s.\n  unfold interpret.\n  rewrite -> unfold_interpret_ds_times.\n  unfold compile_v0.\n  rewrite -> unfold_compile_ds_times.\n  rewrite ->2 about_execute_byte_code_program.\n  rewrite -> unfold_execute_byte_code_program_ic.\n  rewrite -> unfold_execute_byte_code_program_bc.\n  rewrite <- IHae1'.\n  rewrite <- IHae2'.\n  unfold execute_byte_code_instruction.\n  rewrite -> mult_comm.\n  reflexivity.\nQed.\n\nTheorem interpret_yields_same_result_as_compile_then_execute :\n  forall ae : arithmetic_expression,\n    interpret ae = run (compile_v0 ae).\nProof.\n  intro ae.\n  unfold run.\n  unfold compile_v0.\n  rewrite <- interpret_exp_cons_datastack_eq_execute_compile_exp_ds.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Exercise 9:\n   Write a Magritte-style execution function for a byte-code program\n   that does not operate on natural numbers but on syntactic representations\n   of natural numbers:\n\n   Definition data_stack := list arithmetic_expression.\n\n   * Executing (PUSH n) given s has the effect of pushing (Lit n) on s.\n\n   * Executing ADD given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their addition.\n\n   * Executing MUL given s has the effect of popping two arithmetic\n     expressions from s and then pushing the syntactic representation of\n     their multiplication.\n\n   Again, for this week's exercise,\n   assume there are enough arithmetic expressions on the data stack.\n   If that is not the case, just pad it up with syntactic representations\n   of zero.\n\n*)\n\nDefinition data_stack2 := list arithmetic_expression.\n\nFixpoint beq_ae (ae1 ae2 : arithmetic_expression) :=\n  match ae1 with\n  | (Lit n) =>\n      match ae2 with\n      | (Lit n') => beq_nat n n'\n      | _ => false\n      end\n  | (Plus ae1' ae2') =>\n      match ae2 with\n      | (Plus ae1'' ae2'') => (beq_ae ae1' ae1'') && (beq_ae ae2' ae2'')\n      | _ => false\n      end\n  | (Times ae1' ae2') =>\n      match ae2 with\n      | (Times ae1'' ae2'') => (beq_ae ae1' ae1'') && (beq_ae ae2' ae2'')\n      | _ => false\n      end\n  end.\n\nCompute beq_ae (Plus (Lit 0) (Lit 0)) (Plus (Lit 0) (Lit 0)).\nCompute beq_ae (Plus (Lit 1) (Lit 0)) (Plus (Lit 0) (Lit 0)).\n\nDefinition beq_ae_list (s1 s2 : data_stack2) :=\n  beq_list arithmetic_expression s1 s2 beq_ae.\n\nDefinition unit_test_for_magritte (magritte : byte_code_program -> data_stack2) :=\n  (beq_ae_list (magritte (PUSH 5 :: nil))\n               (Lit 5 :: nil)) \n  &&\n  (beq_ae_list (magritte (PUSH 1 :: PUSH 2 :: ADD :: nil))\n               (Plus (Lit 2) (Lit 1) :: nil))\n  &&\n  (beq_ae_list (magritte (PUSH 1 :: PUSH 2 :: MUL :: nil))\n               (Times (Lit 2) (Lit 1) :: nil))\n  &&\n  (beq_ae_list (magritte (nil))\n               nil)\n  &&\n  (beq_ae_list (magritte (PUSH 1 :: MUL :: nil))\n               (Times (Lit 1) (Lit 0) :: nil))\n  &&\n  (beq_ae_list (magritte (PUSH 1 :: ADD :: nil))\n               (Plus (Lit 1) (Lit 0) :: nil))\n  &&\n  (beq_ae_list (magritte (ADD :: MUL :: nil))\n               (Times (Plus (Lit 0) (Lit 0)) (Lit 0) :: nil)).\n\nDefinition specification_of_magritte (magritte : byte_code_program -> data_stack2 -> data_stack2) :=\n  (forall (s : data_stack2),\n    magritte nil s = s)\n  /\\\n  (forall (n : nat) (prog : byte_code_program) (s : data_stack2),\n    magritte ((PUSH n) :: prog) s = magritte prog ((Lit n) :: s))\n  /\\\n  (forall (prog : byte_code_program),\n    magritte (ADD :: prog) nil = magritte prog ((Plus (Lit 0) (Lit 0)) :: nil))\n  /\\\n  (forall (prog : byte_code_program) (ae : arithmetic_expression),\n    magritte (ADD :: prog) (ae :: nil) = magritte prog ((Plus (Lit 0) ae) :: nil))\n  /\\\n  (forall (prog : byte_code_program) (ae1 ae2 : arithmetic_expression) (s : data_stack2),\n    magritte (ADD :: prog) (ae1 :: ae2 :: s) = magritte prog ((Plus ae2 ae1) :: s))\n  /\\\n  (forall (prog : byte_code_program),\n    magritte (MUL :: prog) nil = magritte prog ((Times (Lit 0) (Lit 0)) :: nil))\n  /\\\n  (forall (prog : byte_code_program) (ae : arithmetic_expression),\n    magritte (MUL :: prog) (ae :: nil) = magritte prog ((Times (Lit 0) ae) :: nil))\n  /\\\n  (forall (prog : byte_code_program) (ae1 ae2 : arithmetic_expression) (s : data_stack2),\n    magritte (MUL :: prog) (ae1 :: ae2 :: s) = magritte prog ((Times ae2 ae1) :: s)).\n\nTheorem there_is_only_one_magritte :\n  forall (f g : byte_code_program -> data_stack2 -> data_stack2),\n    specification_of_magritte f ->\n    specification_of_magritte g ->\n    forall (prog : byte_code_program) (s : data_stack2),\n      f prog s = g prog s.\nProof.\n  intros f g.\n  unfold specification_of_magritte.\n  intros [H_f_nil [H_f_push [H_f_add_0 [H_f_add_1 [H_f_add_2 [H_f_mul_0 [H_f_mul_1 H_f_mul_2]]]]]]].\n  intros [H_g_nil [H_g_push [H_g_add_0 [H_g_add_1 [H_g_add_2 [H_g_mul_0 [H_g_mul_1 H_g_mul_2]]]]]]].\n  intro prog.\n  induction prog as [ | instr prog IHprog].\n    intro s.\n    rewrite -> H_f_nil.\n    rewrite -> H_g_nil.\n    reflexivity.\n  intro s.\n  case instr as [ n | | ].\n      rewrite -> H_f_push.\n      rewrite -> H_g_push.\n      rewrite -> IHprog.\n      reflexivity.\n    case s as [ | ae s' ].\n      rewrite -> H_f_add_0.\n      rewrite -> H_g_add_0.\n      rewrite -> IHprog.\n      reflexivity.\n    case s' as [ | ae' s''].\n      rewrite -> H_f_add_1.\n      rewrite -> H_g_add_1.\n      rewrite -> IHprog.\n      reflexivity.\n    rewrite -> H_f_add_2.\n    rewrite -> H_g_add_2.\n    rewrite -> IHprog.\n    reflexivity.\n  case s as [ | ae s' ].\n    rewrite -> H_f_mul_0.\n    rewrite -> H_g_mul_0.\n    rewrite -> IHprog.\n    reflexivity.\n  case s' as [ | ae' s''].\n    rewrite -> H_f_mul_1.\n    rewrite -> H_g_mul_1.\n    rewrite -> IHprog.\n    reflexivity.\n  rewrite -> H_f_mul_2.\n  rewrite -> H_g_mul_2.\n  rewrite -> IHprog.\n  reflexivity.\nQed.\n\nFixpoint magritte_ds (prog : byte_code_program) (s : data_stack2) :=\n  match prog with\n  | nil => s\n  | (PUSH n) :: prog' => magritte_ds prog' ((Lit n) :: s)\n  | ADD :: prog' => \n      match s with\n      | nil => magritte_ds prog' ((Plus (Lit 0) (Lit 0)) :: nil)\n      | ae :: nil => magritte_ds prog' ((Plus (Lit 0) ae) :: nil)\n      | ae1 :: ae2 :: exps => magritte_ds prog' ((Plus ae2 ae1) :: exps)\n      end\n  | MUL :: prog' => \n      match s with\n      | nil => magritte_ds prog' ((Times (Lit 0) (Lit 0)) :: nil)\n      | ae :: nil => magritte_ds prog' ((Times (Lit 0) ae) :: nil)\n      | ae1 :: ae2 :: s' => magritte_ds prog' ((Times ae2 ae1) :: s')\n      end\n  end.\n\nDefinition magritte_v0 (prog : byte_code_program) :=\n  magritte_ds prog nil.\n\nCompute unit_test_for_magritte magritte_v0.\n\nLemma unfold_magritte_ds_nil_prog :\n  forall (s : data_stack2),\n    magritte_ds nil s = s.\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_push :\n  forall (n : nat) (prog' : byte_code_program) (s : data_stack2),\n    magritte_ds ((PUSH n) :: prog') s = magritte_ds prog' ((Lit n) :: s).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_add_0 :\n  forall (prog' : byte_code_program),\n    magritte_ds (ADD :: prog') nil = magritte_ds prog' ((Plus (Lit 0) (Lit 0)) :: nil).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_add_1 :\n  forall (prog' : byte_code_program) (ae : arithmetic_expression),\n    magritte_ds (ADD :: prog') (ae :: nil) = magritte_ds prog' ((Plus (Lit 0) ae) :: nil).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_add_2 :\n  forall (prog' : byte_code_program) (ae1 ae2 : arithmetic_expression) (s : data_stack2),\n    magritte_ds (ADD :: prog') (ae1 :: ae2 :: s) = magritte_ds prog' ((Plus ae2 ae1) :: s).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_mul_0 :\n  forall (prog' : byte_code_program),\n    magritte_ds (MUL :: prog') nil = magritte_ds prog' ((Times (Lit 0) (Lit 0)) :: nil).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_mul_1 :\n  forall (prog' : byte_code_program) (ae : arithmetic_expression),\n    magritte_ds (MUL :: prog') (ae :: nil) = magritte_ds prog' ((Times (Lit 0) ae) :: nil).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nLemma unfold_magritte_ds_mul_2 :\n  forall (prog' : byte_code_program) (ae1 ae2 : arithmetic_expression) (s : data_stack2),\n    magritte_ds (MUL :: prog') (ae1 :: ae2 :: s) = magritte_ds prog' ((Times ae2 ae1) :: s).\nProof.\n  unfold_tactic magritte_ds.\nQed.\n\nTheorem magritte_ds_fits_the_specification_of_magritte :\n  specification_of_magritte magritte_ds.\nProof.\n  unfold specification_of_magritte.\n  split.\n    exact unfold_magritte_ds_nil_prog.\n  split.\n    exact unfold_magritte_ds_push.\n  split.\n    exact unfold_magritte_ds_add_0.\n  split.\n    exact unfold_magritte_ds_add_1.\n  split.\n    exact unfold_magritte_ds_add_2.\n  split.\n    exact unfold_magritte_ds_mul_0.\n  split.\n    exact unfold_magritte_ds_mul_1.\n  exact unfold_magritte_ds_mul_2.\nQed.\n\n(* Exercise 10:\n   Prove that the Magrite-style execution function from Exercise 9\n   implements a decompiler that is the left inverse of the compiler\n   of Exercise 6.\n*)\n\nCompute ae_0.\n\nDefinition unit_test_for_run_magritte (candidate : byte_code_program -> arithmetic_expression) :=\n  (beq_ae (candidate (compile_v0 ae_0))\n          ae_0)\n  &&\n  (beq_ae (candidate (compile_v0 ae_1))\n          ae_1)\n  &&\n  (beq_ae (candidate (compile_v0 ae_2))\n          ae_2).\n\nDefinition specification_of_run_magritte (run_magritte : byte_code_program -> arithmetic_expression) :=\n  (forall prog : byte_code_program,\n    run_magritte prog = \n      match (magritte_v0 prog) with\n      | ae :: nil => ae\n      | _ => Lit 0\n      end).\n\nTheorem there_is_only_one_run_magritte :\n  forall (f g : byte_code_program -> arithmetic_expression),\n    specification_of_run_magritte f ->\n    specification_of_run_magritte g ->\n    forall prog : byte_code_program,\n      f prog = g prog.\nProof.\n  intros f g.\n  unfold specification_of_run_magritte.\n  intros S_f S_g.\n  intro prog.\n  rewrite -> S_f.\n  rewrite -> S_g.\n  reflexivity.\nQed.\n\nDefinition run_magritte (prog : byte_code_program) : arithmetic_expression :=\n  match (magritte_v0 prog) with\n  | ae :: nil => ae\n  | _ => Lit 0\n  end.\n\nCompute unit_test_for_run_magritte run_magritte.\n\nProposition run_magritte_fits_the_specification_of_run_magritte :\n  specification_of_run_magritte run_magritte.\nProof.\n  unfold specification_of_run_magritte.\n  intro prog.\n  unfold run_magritte.\n  reflexivity.\nQed.\n\nCheck unfold_append_bc.\nCheck unfold_append_ic.\n\nLemma about_magritte_ds_and_append :\n  forall (p1 p2 : byte_code_program) (s : data_stack2),\n    magritte_ds (p1 ++ p2) s = magritte_ds p2 (magritte_ds p1 s).\nProof.\n  intro p1.\n  induction p1 as [ | instr prog IHprog ].\n    intros p2 s.\n    rewrite -> unfold_append_bc.\n    rewrite -> unfold_magritte_ds_nil_prog.\n    reflexivity.\n  intros p2 s.\n  rewrite -> unfold_append_ic.\n  case instr as [ n | | ].\n      rewrite ->2 unfold_magritte_ds_push.\n      rewrite -> IHprog.\n      reflexivity.\n    case s as [ | ae s'].\n      rewrite ->2 unfold_magritte_ds_add_0.\n      rewrite -> IHprog.\n      reflexivity.\n    case s' as [ | ae' s''].\n      rewrite ->2 unfold_magritte_ds_add_1.\n      rewrite -> IHprog.\n      reflexivity.\n    rewrite ->2 unfold_magritte_ds_add_2.\n    rewrite -> IHprog.\n    reflexivity.\n  case s as [ | ae s'].\n    rewrite ->2 unfold_magritte_ds_mul_0.\n    rewrite -> IHprog.\n    reflexivity.\n  case s' as [ | ae' s''].\n    rewrite ->2 unfold_magritte_ds_mul_1.\n    rewrite -> IHprog.\n    reflexivity.\n  rewrite ->2 unfold_magritte_ds_mul_2.\n  rewrite -> IHprog.\n  reflexivity.\nQed.\n\nLemma magritte_on_compiled_ae_eq_ae_cons_data_stack :\n  forall (ae : arithmetic_expression) (s : data_stack2),\n    magritte_ds (compile_v0 ae) s = ae :: s.\nProof.\n  intro ae.\n  unfold compile_v0.\n  induction ae as [ n | ae1 IHae1 ae2 IHae2 | ae1' IHae1' ae2' IHae2' ].\n      intro s.\n      rewrite -> unfold_compile_ds_lit.\n      rewrite -> unfold_magritte_ds_push.\n      rewrite -> unfold_magritte_ds_nil_prog.\n      reflexivity.\n    intro s.\n    rewrite -> unfold_compile_ds_plus.\n    rewrite ->2 about_magritte_ds_and_append.\n    rewrite -> IHae1.\n    rewrite -> IHae2.\n    rewrite -> unfold_magritte_ds_add_2.\n    rewrite -> unfold_magritte_ds_nil_prog.\n    reflexivity.\n  intro s.\n  rewrite -> unfold_compile_ds_times.\n  rewrite ->2 about_magritte_ds_and_append.\n  rewrite -> IHae1'.\n  rewrite -> IHae2'.\n  rewrite -> unfold_magritte_ds_mul_2.\n  rewrite -> unfold_magritte_ds_nil_prog.\n  reflexivity.\nQed.\n\nTheorem run_magritte_implements_a_decompiler :\n  forall ae : arithmetic_expression,\n    run_magritte(compile_v0 ae) = ae.\nProof.\n  intro ae.\n  unfold run_magritte.\n  unfold magritte_v0.\n  rewrite -> magritte_on_compiled_ae_eq_ae_cons_data_stack.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of week_39b_arithmetic_expressions.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/w39/week_39b_arithmetic_expressions-1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.756606035225605}}
{"text": "Require Import Nat Arith.\n\nInductive Tree : Type := node : nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nFixpoint tinsert (tinsert_arg0 : Tree) (tinsert_arg1 : nat) : Tree\n           := match tinsert_arg0, tinsert_arg1 with\n              | leaf, i => node i leaf leaf\n              | node d l r, i => if ltb d i then node d l (tinsert r i) else node d (tinsert l i) r\n              end.\n\nFixpoint tsize (tsize_arg0 : Tree) : nat\n           := match tsize_arg0 with\n              | leaf => 0\n              | node x l r => plus 1 (plus (tsize l) (tsize r))\n              end.\n\nTheorem theorem0 : forall (t : Tree) (n : nat), eq (tsize (tinsert t n)) (plus 1 (tsize t)).\nProof.\n   intros.\n   induction t.\n   -  simpl. destruct (ltb n0 n).\n   + simpl. rewrite IHt2. f_equal. rewrite <- plus_n_Sm. \n   reflexivity.\n  + simpl. rewrite IHt1. 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/tree_insert_size.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7565259831356149}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) 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/goal33conj256_coqofml_k0Vx0h.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.756444384246259}}
{"text": "Set Implicit Arguments.\nRequire Export List.\nRequire Import MyTactics.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [repeat n a] is a list of [n] copies of the element [a]. *)\n\nFixpoint repeat A (n : nat) (a : A) : list A :=\n  match n with 0 => nil | S n => a :: repeat n a end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* If every element satisfies [P], and if [P] implies [Q], then every element\n   satisfies [Q]. *)\n\nLemma Forall_covariant:\n  forall A (P Q : A -> Prop) xs,\n  Forall P xs ->\n  (forall x, P x -> Q x) ->\n  Forall Q xs.\nProof.\n  induction 1; econstructor; eauto.\nQed.\n\n(* If every element of [xs] satisfies [P], and if [f] maps [P] to [Q],\n   then every element of [map f xs] satisfies [Q]. *)\n\nLemma Forall_map:\n  forall A B (f : A -> B) (P : A -> Prop) (Q : B -> Prop) xs,\n  Forall P xs ->\n  (forall x, P x -> Q (f x)) ->\n  Forall Q (map f xs).\nProof.\n  induction 1; simpl; eauto.\nQed.\n\nLemma Forall_map_reverse:\n  forall A B (f : A -> B) (P : A -> Prop) (Q : B -> Prop) xs,\n  Forall Q (map f xs) ->\n  (forall x, Q (f x) -> P x) ->\n  Forall P xs.\nProof.\n  induction xs; simpl; inversion 1; eauto.\nQed.\n\n(* If every element of [xs] satisfies [P] and every element of [ys]\n   satisfies [P], then every element of [xs ++ ys] satisfies [P]. *)\n\nLemma Forall_app:\n  forall A (P : A -> Prop) (xs ys : list A),\n  Forall P xs ->\n  Forall P ys ->\n  Forall P (xs ++ ys).\nProof.\n  induction 1; simpl; eauto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\nLemma Forall2_length:\n  forall A B (R : A -> B -> Prop) xs ys,\n  Forall2 R xs ys ->\n  length xs = length ys.\nProof.\n  induction 1; simpl; eauto.\nQed.\n\nLemma Forall2_Forall_modus_ponens:\n  forall A B : Type,\n  forall P : A -> B -> Prop,\n  forall Q : B -> Prop,\n  (forall a b, P a b -> Q b) ->\n  forall xs ys,\n  Forall2 P xs ys ->\n  Forall Q ys.\nProof.\n  induction 2; econstructor; eauto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A definition of [nth] as a relation. *)\n\nInductive is_nth A : nat -> list A -> A -> Prop :=\n| IsNthZero:\n    forall x xs,\n    is_nth 0 (x :: xs) x\n| IsNthSucc:\n    forall n y x xs,\n    is_nth n xs y ->\n    is_nth (S n) (x :: xs) y.\n\nHint Constructors is_nth : is_nth.\n\n(* This tactic proves that [is_nth n xs x] implies that [xs] is non-empty. *)\n\nLtac is_nth_nonempty :=\n  match goal with h: is_nth _ ?xs _ |- _ =>\n    destruct xs; [ inversion h | ]\n  end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Lemmas about [is_nth]. *)\n\n(* If every element satisfies [P], then the [n]-th element satisfies [P]. *)\n\nLemma is_nth_Forall:\n  forall A P n xs (x : A),\n  is_nth n xs x ->\n  Forall P xs ->\n  P x.\nProof.\n  induction 1; inversion 1; subst; eauto.\nQed.\n\n(* If [x] is the [n]-th element of [xs], then [f x] is the [n]-th element\n   of [map f xs]. *)\n\nLemma is_nth_map:\n  forall A B (f : A -> B) n xs x,\n  is_nth n xs x ->\n  is_nth n (map f xs) (f x).\nProof.\n  induction 1; econstructor; eauto.\nQed.\n\nLemma is_nth_map_reverse:\n  forall A B (f : A -> B) xs n y,\n  is_nth n (map f xs) y ->\n  exists x,\n  is_nth n xs x /\\ f x = y.\nProof.\n  induction xs; simpl; dependent_destruction.\n  repeat econstructor.\n  forwards: IHxs. eauto. unpack.\n  repeat econstructor; eauto.\nQed.\n\n(* [is_nth] is injective. *)\n\nLemma is_nth_injective:\n  forall A xs n (x1 x2 : A),\n  is_nth n xs x1 ->\n  is_nth n xs x2 ->\n  x1 = x2.\nProof.\n  induction 1; inversion 1; eauto.\nQed.\n\n(* If [x] is the [n]-th element of [xs], then [xs] has length greater than [n]. *)\n\nLemma is_nth_length:\n  forall A n (xs : list A) x,\n  is_nth n xs x ->\n  n < length xs.\nProof.\n  induction 1; simpl; eauto with omega.\nQed.\n\n(* Conversely, if has length greater than [n], then some [x] is the [n]-th\n   element of [xs]. *)\n\nLemma length_is_nth:\n  forall A (xs : list A) n,\n  n < length xs ->\n  exists x,\n  is_nth n xs x.\nProof.\n  induction xs; simpl; intros; [ false; omega | destruct n ].\n  repeat econstructor.\n  forwards: IHxs. instantiate (1 := n). omega. unpack. repeat econstructor; eauto.\nQed.\n\n(* A combination of the above two lemmas. *)\n\nLemma is_nth_common_length:\n  forall A n (xs : list A) x,\n  is_nth n xs x ->\n  forall B (ys : list B),\n  length xs = length ys ->\n  exists y,\n  is_nth n ys y.\nProof.\n  introv ? heq.\n  eapply length_is_nth.\n  rewrite <- heq.\n  eauto using is_nth_length.\nQed.\n\n(* Looking for the [n]-th element of [xs ++ ys]. *)\n\nLemma is_nth_app_near:\n  forall A (xs ys : list A) n x,\n  is_nth n xs x ->\n  is_nth n (xs ++ ys) x.\nProof.\n  induction 1; simpl; econstructor; eauto.\nQed.\n\nLemma is_nth_app_far:\n  forall A (xs ys : list A) k n y,\n  is_nth k ys y ->\n  length xs + k = n ->\n  is_nth n (xs ++ ys) y.\nProof.\n  induction xs; simpl; intros.\n  replace n with k by omega. assumption.\n  destruct n; [ false; omega | ].\n  econstructor. eauto.\nQed.\n\nLemma Forall2_is_nth:\n  forall A B (R : A -> B -> Prop) xs ys,\n  Forall2 R xs ys ->\n  forall n x y,\n  is_nth n xs x ->\n  is_nth n ys y ->\n  R x y.\nProof.\n  induction 1; inversion 1; inversion 1; subst; eauto.\nQed.\n\nLemma Forall2_is_nth_left_to_right:\n  forall A B (R : A -> B -> Prop) xs ys,\n  Forall2 R xs ys ->\n  forall n x,\n  is_nth n xs x ->\n  exists y,\n  is_nth n ys y /\\ R x y.\nProof.\n  dependent_induction; dependent_destruction.\n  repeat econstructor; eauto.\n  forwards: IHhdi. eauto. unpack.\n  repeat econstructor; eauto.\nQed.\n\nLemma Forall2_is_nth_right_to_left:\n  forall A B (R : A -> B -> Prop) xs ys,\n  Forall2 R xs ys ->\n  forall n y,\n  is_nth n ys y ->\n  exists x,\n  is_nth n xs x /\\ R x y.\nProof.\n  dependent_induction; dependent_destruction.\n  repeat econstructor; eauto.\n  forwards: IHhdi. eauto. unpack.\n  repeat econstructor; eauto.\nQed.\n\nLemma is_nth_inversion:\n  forall A (xs : list A) n x y,\n  is_nth n (xs ++ x :: nil) y ->\n  is_nth n xs y \\/ x = y.\nProof.\n  induction xs; simpl; dependent_destruction.\n  right. eauto.\n  inversion hdd.\n  left. econstructor.\n  forwards [ | ]: IHxs; [ eauto | left | right ].\n    econstructor; eauto.\n    eauto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A function that updates the [n]-th element of a list. *)\n\nFixpoint set_nth A (n : nat) (xs : list A) (y : A) : list A :=\n  match n, xs with\n  | 0, _ :: xs =>\n      y :: xs\n  | S n, x :: xs =>\n      x :: set_nth n xs y\n  | _, nil =>\n      nil (* dummy; considered non-sensical *)\n  end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Lemmas about [set_nth]. *)\n\nLemma Forall_set_nth:\n  forall A (P : A -> Prop) (n : nat) (xs : list A) (y : A),\n  Forall P xs ->\n  P y ->\n  Forall P (set_nth n xs y).\nProof.\n  induction n; inversion 1; simpl; intros; eauto.\nQed.\n\nLemma Forall2_set_nth:\n  forall A B (R : A -> B -> Prop) xs ys x y,\n  Forall2 R xs ys ->\n  R x y ->\n  forall n,\n  Forall2 R (set_nth n xs x)(set_nth n ys y).\nProof.\n  induction 1; destruct n; simpl; intros; econstructor; eauto.\nQed.\n\nLemma is_nth_set_nth_there:\n  forall A n (xs : list A) x1 x2,\n  is_nth n xs x1 ->\n  is_nth n (set_nth n xs x2) x2.\nProof.\n  induction 1; simpl; econstructor; eauto.\nQed.\n\nLemma is_nth_set_nth_elsewhere:\n  forall A n (xs : list A) x1 x2,\n  is_nth n xs x1 ->\n  forall m,\n  m <> n ->\n  is_nth n (set_nth m xs x2) x1.\nProof.\n  induction 1; simpl; intros; destruct m; solve [\n    false; omega\n  | econstructor; eauto\n  ].\nQed.\n\nLemma set_nth_identity:\n  forall A n (xs : list A) x,\n  is_nth n xs x ->\n  set_nth n xs x = xs.\nProof.\n  induction 1; simpl; f_equal; eauto.\nQed.\n\nLemma length_set_nth:\n  forall A (xs : list A) n y,\n  length (set_nth n xs y) = length xs.\nProof.\n  induction xs; destruct n; intros; simpl; eauto.\nQed.\n\nLemma is_nth_set_nth_inversion:\n  forall A (xs : list A) m n x1 x2,\n  is_nth n (set_nth m xs x1) x2 ->\n  m <> n /\\ is_nth n xs x2 \\/\n  m  = n /\\ x1 = x2.\nProof.\n  induction xs; destruct m; simpl; dependent_destruction. \n  right. eauto.\n  left. eauto with is_nth.\n  left. eauto with is_nth.\n  forwards [ | ]: IHxs; [ eauto | left | right ]; unpack;\n  eauto with omega is_nth.\nQed.\n\nLemma set_nth_app_left:\n  forall A n (xs : list A) x1,\n  is_nth n xs x1 ->\n  forall ys x2,\n  set_nth n (xs ++ ys) x2 = set_nth n xs x2 ++ ys.\nProof.\n  induction 1; simpl; intros; eauto with f_equal.\nQed.\n  \nLemma set_nth_set_nth:\n  forall A (xs : list A) n1 a1,\n  is_nth n1 xs a1 ->\n  forall n2 a2,\n  is_nth n2 xs a2 ->\n  n1 <> n2 ->\n  forall b1 b2,\n  set_nth n2 (set_nth n1 xs b1) b2 = set_nth n1 (set_nth n2 xs b2) b1.\nProof.\n  induction 1; inversion 1; intros; simpl; subst; eauto with falseomega f_equal omega.\nQed.\n\nLemma set_nth_overwrite:\n  forall A n (xs : list A) y1 y2,\n  set_nth n (set_nth n xs y1) y2 = set_nth n xs y2.\nProof.\n  induction n; destruct xs; intros; simpl; eauto with f_equal.\nQed.\n\nLemma map_set_nth:\n  forall A B (f : A -> B) n xs y,\n  map f (set_nth n xs y) =\n  set_nth n (map f xs) (f y).\nProof.\n  induction n; destruct xs; intros; simpl; eauto with f_equal.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A function that applies a transformation [f] to the [n]-th element of a list.\n   This can be viewed as a generalization of [set_nth]. *)\n\nFixpoint apply_nth A (n : nat) (xs : list A) (f : A -> A) { struct xs } : list A :=\n  match xs, n with\n  | nil, _ =>\n      nil (* dummy; considered non-sensical *)\n  | x :: xs, 0 =>\n      f x :: xs\n  | x :: xs, S n =>\n      x :: apply_nth n xs f\n  end.\n\nLemma is_nth_set_nth_apply_nth:\n  forall A (xs: list A) n a f,\n  is_nth n xs a ->\n  apply_nth n xs f = set_nth n xs (f a).\nProof.\n  induction xs. \n  destruct n; simpl; eauto.\n  destruct n; inversion 1; subst; simpl; [ eauto | f_equal; eauto ].\nQed.\n\nLemma length_apply_nth:\n  forall A (xs : list A) n f,\n  length (apply_nth n xs f) = length xs.\nProof.\n  induction xs; destruct n; intros; simpl; eauto.\nQed.\n\nLemma Forall_apply_nth:\n  forall A (P : A -> Prop) f,\n  (forall x, P x -> P (f x)) ->\n  forall n xs,\n  Forall P xs ->\n  Forall P (apply_nth n xs f).\nProof.\n  induction n; inversion 1; simpl; intros; eauto.\nQed.\n\nLemma is_nth_apply_nth_there:\n  forall A n xs f (x : A),\n  is_nth n xs x ->\n  is_nth n (apply_nth n xs f) (f x).\nProof.\n  induction 1; simpl; econstructor; eauto.\nQed.\n\nLemma is_nth_apply_nth_elsewhere:\n  forall A n xs f (x : A),\n  is_nth n xs x ->\n  forall m,\n  m <> n ->\n  is_nth n (apply_nth m xs f) x.\nProof.\n  induction 1; simpl; intros; destruct m; solve [\n    false; omega\n  | econstructor; eauto\n  ].\nQed.\n\nLemma is_nth_apply_nth_inversion:\n  forall A (xs : list A) m n x2 f,\n  is_nth n (apply_nth m xs f) x2 ->\n  m <> n /\\ is_nth n xs x2 \\/\n  m  = n /\\ exists x1, is_nth n xs x1 /\\ f x1 = x2.\nProof.\n  induction xs; destruct m; simpl; dependent_destruction. \n  right. eauto with is_nth.\n  left. eauto with is_nth.\n  left. eauto with is_nth.\n  forwards [ | ]: IHxs; [ eauto | left | right ]; unpack;\n  eauto with omega is_nth.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The combinator [zip] maps a function [f] over two lists [xs] and [ys]. *)\n\nFixpoint zip A B C (f : A -> B -> C) (xs : list A) (ys : list B) : list C :=\n  match xs, ys with\n  | nil, _\n  | _, nil =>\n      nil\n  | x :: xs, y :: ys =>\n      f x y :: zip f xs ys\n  end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* If [x] and [y] are the [n]-th elements of [xs] and [ys], then [f x y] is\n   the [n]-th element of [zip f xs ys]. *)\n\nLemma is_nth_zip:\n  forall A B C (f : A -> B -> C) n xs x,\n  is_nth n xs x ->\n  forall ys y,\n  is_nth n ys y ->\n  is_nth n (zip f xs ys) (f x y).\nProof.\n  induction 1; inversion 1; subst; simpl; econstructor; eauto.\nQed.\n\nLemma is_nth_zip_eq:\n  forall A B C (f : A -> B -> C) n xs x,\n  is_nth n xs x ->\n  forall ys y,\n  is_nth n ys y ->\n  forall z,\n  z = f x y ->\n  is_nth n (zip f xs ys) z.\nProof.\n  intros; subst; eauto using is_nth_zip.\nQed.\n\nLemma zip_set_nth:\n  forall A B C (f : A -> B -> C) n xs ys x y,\n  zip f (set_nth n xs x) (set_nth n ys y) =\n  set_nth n (zip f xs ys) (f x y).\nProof.\n  induction n; destruct xs; destruct ys; intros; simpl; eauto with f_equal.\nQed.\n\n(* [zip] preserves the length of the lists when there is agreement. *)\n\nLemma zip_length_left:\n  forall A B C (f : A -> B -> C) (xs : list A) (ys : list B),\n  length xs = length ys ->\n  length (zip f xs ys) = length xs.\nProof.\n  induction xs; destruct ys; simpl; eauto.\nQed.\n\nLemma zip_length_right:\n  forall A B C (f : A -> B -> C) (xs : list A) (ys : list B),\n  length xs = length ys ->\n  length (zip f xs ys) = length ys.\nProof.\n  induction xs; destruct ys; simpl; eauto.\nQed.\n\n(* If [f] is commutative, then [zip f] is commutative. *)\n\nLemma zip_commutative:\n  forall A C (f : A -> A -> C),\n  (forall x y, f x y = f y x) ->\n  forall (xs ys : list A),\n  zip f xs ys = zip f ys xs.\nProof.\n  induction xs; destruct ys; simpl; eauto with f_equal.\nQed.\n\n(* If [f] is associative, then [zip f] is associative. *)\n\nLemma zip_associative:\n  forall A (f : A -> A -> A),\n  (forall x y z, f x (f y z) = f (f x y) z) ->\n  forall (xs ys zs : list A),\n  zip f xs (zip f ys zs) = zip f (zip f xs ys) zs.\nProof.\n  induction xs; destruct ys; destruct zs; simpl; eauto with f_equal.\nQed.\n\n(* An ad hoc lemma about [zip] and [map]. *)\n\nLemma zip_map_right:\n  forall A B (f : A -> B -> A) (g : A -> B),\n  (forall x, f x (g x) = x) ->\n  forall xs,\n  zip f xs (map g xs) = xs.\nProof.\n  induction xs; simpl; eauto with f_equal.\nQed.\n\n(* [zip] and [++] commute. *)\n\nLemma zip_app:\n  forall A B C (f : A -> B -> C) xs1 xs2 ys1 ys2,\n  length xs1 = length xs2 ->\n  length ys1 = length ys2 ->\n  zip f (xs1 ++ ys1) (xs2 ++ ys2) =\n  zip f xs1 xs2 ++ zip f ys1 ys2.\nProof.\n  induction xs1; destruct xs2; simpl; intros;\n  solve [ false; omega | eauto with f_equal].\nQed.\n\n(* [zip] applied to [nil] is [nil]. *)\n\nLemma zip_nil_right:\n  forall A B C (f : A -> B -> C) xs,\n  zip f xs nil = nil.\nProof.\n  destruct xs; reflexivity.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n\n(* The predicate [growth P Q xs ys] means that [xs] ``has grown'' into [ys].\n   More precisely, the list [ys] is potentially longer than the list [xs].\n   At indices that exist in both lists, the elements of [xs] and [ys] are\n   related by [P]. At indices that exist only in the list [ys], the elements\n   satisfy [Q]. *)\n\nInductive growth A B (P : A -> B -> Prop) (Q : B -> Prop) : list A -> list B -> Prop :=\n| GrowthZero:\n    forall ys,\n    Forall Q ys ->\n    growth P Q nil ys\n| GrowthSucc:\n    forall x xs y ys,\n    P x y ->\n    growth P Q xs ys ->\n    growth P Q (x :: xs) (y :: ys).\n\n(* ------------------------------------------------------------------------- *)\n\n(* If [P] is reflexive, then [growth P Q] is reflexive. *)\n\nLemma growth_reflexive:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop),\n  (forall x, P x x) ->\n  forall xs,\n  growth P Q xs xs.\nProof.\n  induction xs; econstructor; eauto.\nQed.\n\n(* If [xs] grows to [ys], and if [x] is the [n]-th element of [xs], then [ys]\n   has an [n]-th element [y] which is related to [x] by [P]. *)\n\nLemma growth_is_nth:\n  forall A B (P : A -> B -> Prop) (Q : B -> Prop) xs ys,\n  growth P Q xs ys ->\n  forall n x,\n  is_nth n xs x ->\n  exists y,\n  is_nth n ys y /\\ P x y.\nProof.\n  induction 1; dependent_destruction; subst.\n  repeat econstructor; eauto.\n  forwards: IHgrowth; [ eauto | unpack ].\n  repeat econstructor; eauto.\nQed.\n\nLemma growth_is_nth_reverse:\n  forall A B (P : A -> B -> Prop) (Q : B -> Prop) xs ys,\n  growth P Q xs ys ->\n  forall n y,\n  is_nth n ys y ->\n  (exists x, is_nth n xs x /\\ P x y) \\/ Q y.\nProof.\n  dependent_induction.\n  right. eapply is_nth_Forall; eauto.\n  dependent_destruction.\n  left. repeat econstructor; eauto.\n  forwards h: IHhdi. eauto. destruct h; unpack.\n  left. repeat econstructor; eauto.\n  right. eauto.\nQed.\n\nLemma growth_set_nth:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop) n xs x1 x2,\n  (forall x, P x x) ->\n  is_nth n xs x1 ->\n  P x1 x2 ->\n  growth P Q xs (set_nth n xs x2).\nProof.\n  induction 2; simpl; econstructor; eauto using growth_reflexive.\nQed.\n\nLemma growth_set_nth_set_nth:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop) n xs d x y,\n  is_nth n xs d ->\n  forall ys,\n  growth P Q xs ys ->\n  P x y ->\n  growth P Q (set_nth n xs x) (set_nth n ys y).\nProof.\n  induction 1; inversion 1; intros; subst; simpl; econstructor; eauto.\n  (* I don't even know what I am doing *)\nQed.\n\nLemma growth_apply_nth_apply_nth:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop) n xs d f,\n  (forall x y, P x y -> P (f x) (f y)) ->\n  is_nth n xs d ->\n  forall ys,\n  growth P Q xs ys ->\n  growth P Q (apply_nth n xs f) (apply_nth n ys f).\nProof.\n  induction 2; inversion 1; intros; subst; simpl; econstructor; eauto.\n  (* I don't even know what I am doing, but I am really happy. *)\nQed.\n\n(* If [P] is reflexive and if every element of [ys] satisfies [Q], then [xs]\n   can grow to [xs ++ ys]. *)\n\nLemma growth_app:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop),\n  (forall x, P x x) ->\n  forall xs ys,\n  Forall Q ys ->\n  growth P Q xs (xs ++ ys).\nProof.\n  induction xs; intros; simpl; econstructor; eauto.\nQed.\n\nLemma growth_length:\n  forall A (P : A -> A -> Prop) (Q : A -> Prop) xs ys,\n  growth P Q xs ys ->\n  length xs <= length ys.\nProof.\n  induction 1; simpl; eauto with omega.\nQed.\n\nLemma growth_map_map:\n  forall (A B A' B' : Type) (P : A -> B -> Prop) (P' : A' -> B' -> Prop) Q Q' f g xs ys,\n  (forall x y, P x y -> P' (f x) (g y)) ->\n  (forall ys, Forall Q ys -> Forall Q' (map g ys)) ->\n  growth P Q xs ys ->\n  growth P' Q' (map f xs) (map g ys).\nProof.\n  induction 3; simpl; econstructor; eauto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* This handy tactic does a lot of useful work in the presence of lists. *)\n\nLtac my_list_cleanup :=\n  injections;\n  simpl in *;\n  try discriminate;\n  match goal with\n    (* simplify cons-cons goal *)\n  | |- _ :: _ = _ :: _ =>\n      f_equal; my_list_cleanup\n    (* simplify Forall-cons hypothesis *)\n  | h: Forall _ (_ :: _) |- _ =>\n      inversion h; clear h; my_list_cleanup\n    (* simplify length-nil hypothesis *)\n  | h: 0 = length ?xs |- _ =>\n      destruct xs; [ clear h | false ]; my_list_cleanup\n  | h: length ?xs = 0 |- _ =>\n      destruct xs; [ clear h | false ]; my_list_cleanup\n    (* simplify length-cons hypothesis *)\n  | h: S _ = length ?xs |- _ =>\n      destruct xs; [ false | ]; my_list_cleanup\n  | h: length ?xs = S _ |- _ =>\n      destruct xs; [ false | ]; my_list_cleanup\n    (* simplify is-nth-nil hypothesis *)\n  | h: is_nth _ nil _ |- _ =>\n      inversion h; clear h; my_list_cleanup\n    (* simplify is-nth-cons hypothesis *)\n  | h: is_nth _ (_ :: _) _ |- _ =>\n      inversion h; clear h; my_list_cleanup\n    (* simplify nil-equal-zip or cons-equal-zip hypothesis *)\n  | h: nil = zip _ ?xs ?ys |- _ =>\n      destruct xs; destruct ys; simpl in h; try solve [ discriminate ]; my_list_cleanup\n  | h: zip _ ?xs ?ys = nil |- _ =>\n      destruct xs; destruct ys; simpl in h; try solve [ discriminate ]; my_list_cleanup\n  | h: _ :: _ = zip _ ?xs ?ys |- _ =>\n      destruct xs; destruct ys; simpl in h; try solve [ discriminate ]; my_list_cleanup\n  | h: zip _ ?xs ?ys = _ :: _ |- _ =>\n      destruct xs; destruct ys; simpl in h; try solve [ discriminate ]; my_list_cleanup\n  | _ =>\n      idtac\n  end.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* This tactic finds all lists in the hypotheses and performs induction on one\n   of them and destruction on the others. *)\n\nLtac induction_lists :=\n  repeat match goal with xs: list _ |- _ => generalize dependent xs end;\n  intro xs; induction xs;\n  repeat match goal with |- forall xs: list _, _ => intro ys; destruct ys end;\n  intros; my_list_cleanup.\n\n", "meta": {"author": "ismailkuru", "repo": "minirust", "sha": "9914c3d5e5b7c73d9f8958d088fd825572410b10", "save_path": "github-repos/coq/ismailkuru-minirust", "path": "github-repos/coq/ismailkuru-minirust/minirust-9914c3d5e5b7c73d9f8958d088fd825572410b10/coq/MyList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7563982255453222}}
{"text": "From LF Require Export Induction.\n(* From LF Require Export Basics. *)\n\nModule NatList.\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).\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. \nExample swap_pair_test : swap_pair (1, 2) = (2, 1). Proof. reflexivity. Qed. \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\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n    intros p. \n    rewrite surjective_pairing.\n    destruct p as [n m].\n    simpl.  (* have to expose the structure of p for simpl to perform the pattern match *)\n    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 [m n].\n  rewrite <- snd_fst_is_swap.\n  simpl. \n  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\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_repeat0: repeat 1 0 = []. Proof. reflexivity. Qed.\nExample test_repeat1: repeat 1 1 = [1]. Proof. reflexivity. Qed.\nExample test_repeat2: repeat 1 3 = [1;1;1]. Proof. reflexivity. Qed.\n\nFixpoint length (lst : natlist) : nat :=\n    match lst with \n        | nil => 0\n        | cons x y => 1 + length y\n    end.   \nExample test_length0: length [] = 0. Proof. reflexivity. Qed.\nExample test_length1: length [1] = 1. Proof. reflexivity. Qed.\nExample test_length2: length [1;1;1] = 3. Proof. reflexivity. Qed.\n\n\nFixpoint append' (lst1 lst2 : natlist) : natlist :=\n  match lst1, lst2 with \n    | nil, nil => nil \n    | _, nil =>  lst1 \n    | nil, _ => lst2 \n    | cons x lst1', lst2 => cons x (append' lst1' lst2)\n  end. \n\n  (* h = head, t = tail *)\nFixpoint append (lst1 lst2 : natlist) : natlist :=\n  match lst1 with \n    | nil => lst2 \n    | h :: t => h :: (append t lst2)\n  end. \nNotation \"lst1 ++ lst2\" := (append lst1 lst2).\nExample test_app1:             [1;2;3] ++ [4;5] = [1;2;3;4;5]. Proof. reflexivity. Qed.\nExample test_app2:             nil ++ [4;5] = [4;5]. Proof. reflexivity. Qed.\nExample test_app3:             [1;2;3] ++ nil = [1;2;3]. Proof. reflexivity. Qed.\n\nDefinition hd (default : nat) (l : natlist) : nat := \n  match l with \n    | nil => default \n    | h :: t => h \n  end. \nDefinition tl (l : natlist) : natlist := \n  match l with \n    | [ ] => [ ]\n    | h :: t => t \n  end. \n\nExample test_hd1:             hd 0 [1;2;3] = 1. Proof. reflexivity. Qed.\nExample test_hd2:             hd 0 [] = 0. Proof. reflexivity. Qed.\nExample test_tl1:              tl [1;2;3] = [2;3]. Proof. reflexivity. Qed.\nExample test_tl2:              tl [] = []. Proof. reflexivity. Qed.\n\n\n  (* USEFUL *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with \n    | [] => [] \n    | h :: t => match h with \n                  | O => nonzeros t \n                  | _ => h :: nonzeros t \n                end \n  end.  \nExample test_nonzeros0: nonzeros [0;1;0;2;3;0;0] = [1;2;3]. Proof. reflexivity. Qed.\nExample test_nonzeros1: nonzeros [0;0;0] = []. Proof. reflexivity. Qed.\nExample test_nonzeros2: nonzeros [1;2;3] = [1;2;3]. Proof. reflexivity. Qed.\nExample test_nonzeros3: nonzeros [] = []. Proof. reflexivity. Qed.\n\n\n\nDefinition odd (n : nat) : bool :=\n  negb (even n).\n\n(* if then else is a two way constructor for bools *)\nFixpoint oddmembers' (l:natlist) : natlist :=\n  match l with \n    | [] => []\n    | h :: t => match (odd h) with \n                  | true => h :: (oddmembers' t)\n                  | _ => (oddmembers' t)\n                  end\n  end. \nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with \n    | [] => []\n    | h :: t => if (odd h) then h :: (oddmembers t) else (oddmembers t)\n  end. \nExample test_oddmembers0: oddmembers [0;1;0;2;3;0;0] = [1;3].  Proof. reflexivity. Qed.\nExample test_oddmembers1: oddmembers [1;3;5] = [1;3;5].  Proof. reflexivity. Qed.\nExample test_oddmembers2: oddmembers [0;2;4] = [].  Proof. reflexivity. Qed.\nExample test_oddmembers3: oddmembers [] = [].  Proof. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat :=\n  length (oddmembers l). \nExample test_countoddmembers0: countoddmembers [0;1;0;2;3;0;0] = 2.  Proof. reflexivity. Qed.\nExample test_countoddmembers1: countoddmembers [1;3;5] = 3.  Proof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.  Proof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers [] = 0.  Proof. reflexivity. Qed.\n\n  (* \nNote: one natural and elegant way of writing alternate will fail to \nsatisfy Coq's requirement that all Fixpoint definitions be \n\"obviously terminating.\" \nIf you find yourself in this rut, look for a slightly more verbose \nsolution that considers elements of both lists at the same time.\nOne possible solution involves defining a new kind of pairs, \nbut this is not the only way.\n*)\nFixpoint alternate' (l1 l2 : natlist) : natlist :=\n  match l1 with \n    | [] => l2 \n    | h1 :: t1 => match l2 with \n                  | [] => l1 \n                  | h2 :: t2 => h1 :: h2 :: (alternate' t1 t2)\n                  end \n    end. \nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with \n    | [], [] => [] \n    | _, [] => l1  \n    | [], _ => l2\n    | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n  end. \nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].  Proof. reflexivity. Qed.\nExample test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].  Proof. reflexivity. Qed.\nExample test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].  Proof. reflexivity. Qed.\nExample test_alternate4: alternate [] [1;2;3] = [1;2;3].  Proof. reflexivity. Qed.\nExample test_alternate5: alternate [1;2;3] [] = [1;2;3].  Proof. reflexivity. Qed.\nExample test_alternate6: alternate [1;3] [2;4;5;6] = [1;2;3;4;5;6].  Proof. reflexivity. Qed.\nExample test_alternate7: alternate [1;3;5;6] [2;4] = [1;2;3;4;5;6].  Proof. reflexivity. Qed.\nExample test_alternate8: alternate [] [] = [].  Proof. reflexivity. Qed.\n\n\n  (* \n A bag (or multiset) is like a set, except that each element can \n appear multiple times rather than just once. \n One possible representation for a bag of numbers is as a list. \n  *)\nDefinition bag := natlist.\nCompute eqb 1 2. \n(* TODO: length of filter *)\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with \n    | [] => 0\n    | h :: t => if (h =? v) then 1 + (count v t) else (count v t)\n  end. \nExample test_count0: count 1 [1;2;3;1;4;1] = 3. Proof. reflexivity. Qed. \nExample test_count1: count 1 [1;1;1] = 3. Proof. reflexivity. Qed. \nExample test_count2: count 1 [2;3;4] = 0. Proof. reflexivity. Qed. \nExample test_count3: count 1 [] = 0. Proof. reflexivity. Qed. \n\n(* \nMultiset sum is similar to set union: sum a b contains all the elements of a and of b.\n(Mathematicians usually define union on multisets a little bit differently -- \n  using max instead of sum -- which is why we don't call this operation union.)\n*)\nDefinition sum (a b : bag) : bag :=\n  (append a b).\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3. Proof. reflexivity. Qed. \n\nDefinition add (v : nat) (s : bag) : bag := v :: s.\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3. Proof. reflexivity. Qed. \nExample test_add2:                count 5 (add 1 [1;4;1]) = 0. Proof. reflexivity. Qed. \n\nFixpoint member (v : nat) (s : bag) : bool := \n  match s with \n    | [] => false \n    | h :: t => if (eqb h v) then true else (member v t)\n  end. \n\n(* Fixpoint member (v : nat) (s : bag) : bool :=  *)\n  (* ((count v s) >=? 1). *)\nExample test_member1:             member 1 [1;4;1] = true. Proof. reflexivity. Qed.\nExample test_member2:             member 2 [1;4;1] = false. Proof. reflexivity. Qed.\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with \n    | [] => []\n    | h :: t => if (eqb h v) then t else (h :: (remove_one v t))\n  end.  \nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0. Proof. 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    | [] => []\n    | h :: t => if (eqb h v) then (remove_all v t) else (h :: (remove_all v t))\n  end. \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.\nExample test_remove_all5:  count 5 (remove_all 5 [5;5;2;1;4;1;5;5]) = 0. Proof. reflexivity. Qed.\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool :=\n  match s1, s2 with \n    | [], [] => true \n    | [], _ => true \n    | _, [] => false \n    | h::t, _ =>  if (member h s2) \n                  then (subset t (remove_one h s2)) \n                  else false\n  end.  \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. reflexivity. Qed.\nExample test_subset3:              subset [1;2;3] [1;2;3] = true. Proof. reflexivity. Qed.\nExample test_subset4:              subset [] [1;2;3] = true. Proof. reflexivity. Qed.\nExample test_subset5:              subset [] [] = true. Proof. reflexivity. Qed.\nExample test_subset6:              subset [1] [] = false. Proof. reflexivity. Qed.\n\n\n(* Adding a value to a bag should increase the value's count by one. \nState this as a theorem and prove it.\n*)\n\n(* Lemma ternary : forall cond : bool, forall a, forall b,\n  if cond then (eqb a a) else (eqb b b). \nProof. \n  intros cond a b. \n  simpl. \n  destruct cond as [| t f].\n - reflexivity.\n  - reflexivity.\nQed.  *)\n\n(* \nRequire and Import are used often together\nBut they do different things. \nRequire loads the file. \nImport manages the name space. \n\nWhen coq files (DIR/File.vo) are loaded with Require,\n the contents of File.vo is wrapped in \n Module DIR.FILE \n ... \n End \nEverything defined in the file is then accessed with \n      DIR.FILE.SOME_DEF\n      \nThe file can itself have modules M (MODULE) inside of it.\nTo access contents of M, type \n    DIR.File.MODULE_M.SOME_DEF_IN_MODULE_M\n\n    Import gets all definitions to the top level.\nImport DIR.FILE.MODULE_M gets SOME_DEF_IN_MODULE_M to the top level, \nso now it can be referenced without DIR.FILE.MODULE_M path\nhttps://stackoverflow.com/questions/36621752/how-to-import-the-library-coq-arith-peanonat-in-coq/36647535#36647535\n*)\n(* Require Import Coq.Arith.EqNat. *)\n\n(* Check beq_nat_refl. \nCheck (eqb 1 2). \nCheck true. \nCheck Datatypes.true.\nIt's fine to use Admitted. to avoid type issues from the stdlib *)\nLemma eqbnat_refl': forall v : nat, v =? v = true. Proof. Admitted. \n\nTheorem bag_theorem: forall v n : nat, forall b : bag, \n  (count v (add v b)) = S (count v b).\nProof.\n  intros v n b. \n  simpl.\n  rewrite eqbnat_refl'. \n  reflexivity.\nQed. \n\n(* As with numbers, simple facts about list-processing functions can sometimes be proved entirely by simplification.  \n  *)\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\npred (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(* interesting theorems about lists require induction for their proofs.   *)\n\n(* Since larger lists can always be broken down into smaller ones, eventually reaching nil *)\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(* Coq proof is not especially illuminating as a static document \n-- it is easy to see what's going on if you are reading the proof\n   in an interactive Coq session and you can see the current goal \n   and context at each point, but this state is not visible in the\n   written-down parts of the Coq proof. So a natural-language proof \n-- one written for human readers -- will need to include more explicit\n   signposts; in particular, it will help the reader stay oriented \n   if we remind them exactly what the induction hypothesis is in the\n   second case. \n   \nTheorem: For all lists l1, l2, and l3, (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof: By induction on l1.\nSuppose l1 = []. \nThen ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3), by definition of ++.\n\nOtherwise, suppose l1 = n::l1', with\n    (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\nas the induction hypothesis. \nNow ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3). by definition of ++.\nFinally,\n    n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\nwhich is immediate from the induction hypothesis. ☐   \n   \n*)\nFixpoint rev (l:natlist) : natlist :=\n  match l with \n    | [] => []\n    | h :: t => (rev t) ++ [h]\n  end.\n\nExample test_rev1: rev [1;2;3] = [3;2;1]. Proof. reflexivity. Qed.\nExample test_rev2: rev [] = []. Proof. reflexivity. Qed.\n\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    (* This is the tricky case.  Let's begin as usual\n       by simplifying. *)\n    simpl.\n    (* Now we seem to be stuck: the goal is an equality\n       involving ++, but we don't have any useful equations\n       in either the immediate context or in the global\n       environment!  We can make a little progress by using\n       the IH to rewrite the goal... *)\n    rewrite <- IHl'.\n    (* ... but now we can't go any further. *)\nAbort.\n\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 = n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(* \nTheorem app_length: For all lists l1 and l2, we have \n  length (l1 ++ l2) = length l1 + length l2 \nProof. By induction on l1.\n\nBase case: l1 = []\nWe have     \n  length ([] ++ l2) = length [] + length l2 \nWhich follows directly from definition of ++ and plus  \n\n  --\n\nInductive step: l1 = n :: l1' where\n  length (l1 ++ l2) = length l1 + length l2 \nWe show \n    length ((n :: l1') ++ l2) = length (n :: l1') + length l2 \nwhich follows directly from definition of length and ++ together with\nthe inductive hypothesis.  ☐\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 = n l' *)\n    simpl. rewrite app_length. \n    simpl. rewrite IHl'.\n    rewrite add_comm.\n    simpl. reflexivity.\n Qed. \n(* \nTheorem rev_length: For all lists l, we have \n      length (rev l) = length l.\n\nProof. By induction on l.\n\nBase case: l = []\nWe have     \n  length (rev []) = length [] \nWhich follows directly from definition of rev, length, and plus.\n\n  --\n\nInductive step: l1 = n :: l1' where the IH is \n    length (rev l') = length l'.\nWe must show \n    length (rev (n :: l1')) = length (n :: l1')  \nBy definition of rev, app_length, we get \n    length (rev l' ++ [n]) = length (n :: l1')        (rev)\n    length (rev l') + length [n] = length (n :: l1')  (app_length)\n    length l' + length [n] = length (n :: l1')  (IH)\nwhich follows directly from definition of length and plus.  ☐\n\nTheorem: For all lists l, length (rev l) = length l.\nProof: First, observe that \n    length (l ++ [n]) = S (length l)\n for any l, by induction on l.\nThe main property again follows by induction on l,\nusing the observation together with the induction hypothesis \nin the case where l = n'::l'. ☐ ** too big brain for me. readability is more important. \n\n\n*)\n(* Search rev.\nSearch (_ + _ = _ + _).\nSearch (_ + _ = _ + _) inside Induction.\nSearch (?x + ?y = ?y + ?x). *)\n\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof. \n  intros l. induction l as [| n l' IHl'].\n  - (* l = [] *) \n    reflexivity.\n  - (* l = n l' *)\n    simpl. \n  rewrite IHl'. \n  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  - (* l1 = [] *)\n    simpl. \n    rewrite app_nil_r.\n    reflexivity.\n  - (* l1 = n l1' *)\n    simpl. \n    rewrite IHl1'. \n    rewrite app_assoc.\n    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  - (* l = [] *)\n    reflexivity.\n  - (* l = n l' *)\n    simpl. \n    rewrite rev_app_distr. \n    rewrite IHl'. \n    simpl. \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. induction l1 as [| n l1' IHl1'].\n  - (* l1 = [] *)\n    simpl. rewrite app_assoc. reflexivity.\n  - (* l1 = n l1' *)\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  - (* l1 = [] *)\n    simpl. reflexivity.\n  - (* l1 = n l1' *)\n    induction n as [| n' IHn'].\n    + (* n = O *) \n      simpl. rewrite IHl1'. reflexivity.\n    + (* n = S n' *)\n      simpl. rewrite IHl1'. reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : 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 => if (eqb h1 h2) then (eqblist t1 t2) else false \n              end \nend. \n\n\nExample test_eqblist1 : (eqblist nil nil = true). Proof. reflexivity. Qed.\nExample test_eqblist2 : eqblist [1;2;3] [1;2;3] = true. Proof. reflexivity. Qed.\nExample test_eqblist3 : eqblist [1;2;3] [1;2;4] = false. Proof. reflexivity. Qed.\nExample test_eqblist4 : eqblist [1] [1;2;4] = false. Proof. reflexivity. Qed.\nExample test_eqblist5 : eqblist [1;2;3] [1] = false. Proof. 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  - (* l = [] *)\n    reflexivity.\n  - (* l = n l' *)\n    simpl. rewrite eqbnat_refl'. \n    rewrite <- IHl'. \n    reflexivity.\nQed. \n\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s. simpl. reflexivity.\nQed. \n\n\n(* USEFUL for later *)\nTheorem leb_n_Sn : forall  n,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl. reflexivity.\n  - (* S n' *)\n    simpl. rewrite IHn'. reflexivity. Qed.\n \n\nTheorem remove_does_not_increase_count: forall (s : bag),\n  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\nProof.\n  intros s. induction s as [| n s' IHs'].\n  - (* s = [] *)\n    simpl. reflexivity.\n  - (* s = n s' *)\n  induction n as [| n' IHn' ].\n    + (* n = O *)\n      simpl. rewrite leb_n_Sn. reflexivity. \n    + (* n = S n' *) \n      simpl. \n      rewrite IHs'. \n      reflexivity.\nQed. \n\n\n(* Write down an interesting theorem bag_count_sum \nabout bags involving the functions count and sum, \nand prove it using Coq. \n(You may find that the difficulty of the proof depends\n on how you defined count! \n Hint: If you defined count using =? you may find it\n useful to know that destruct works on arbitrary\n expressions, not just simple identifiers.) *)\n\nTheorem bag_count_sum: forall n: nat, forall b1 b2: bag, \n      (count n b1) + (count n b2) = (count n (sum b1 b2)).\nProof. \n  intros n b1 b2. \nAdmitted. \n\nLemma rev_n : forall n:nat, \n  rev ([n]) = [n].\nProof. simpl. reflexivity. Qed. \n\nLemma rev_empty : rev [] = []. Proof. reflexivity. Qed. \n\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2. \n  intros H. \n  induction l1 as [| n1 l1' IHl1' ].\n  - (* l1 = [] *)\n    rewrite <- rev_involutive. \n    rewrite <- H. \n    reflexivity. \n  - (* l1 = n1 l1' *)\n    rewrite <- rev_involutive. \n    rewrite <- H.\n    rewrite rev_involutive. \n    reflexivity.\nQed. \n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42 (* can't tell if 42 is the input or error *)\n  | a :: l' => match n with\n               | 0 => a\n               | S n' => nth_bad l' 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  | [] => None\n  | h :: t => match n with\n               | O => Some h\n               | S n' => nth_error t n'\n               end\n  end.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4. Proof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7. Proof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None. Proof. 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(* Fix the hd function from earlier so the default value is not hard-coded. *)\nDefinition hd_error (l : natlist) : natoption := \n  match l with \n    | [] => None \n    | h :: t => Some h \n  end. \nExample test_hd_error1 : hd_error [] = None. Proof. reflexivity. Qed. \nExample test_hd_error2 : hd_error [1] = Some 1. Proof. reflexivity. Qed. \nExample test_hd_error3 : hd_error [5;6] = Some 5. Proof. 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. induction l as [| n l' IHl'].\n  - (* l = [] *)\n    simpl. reflexivity. \n  - (* l = n l' *)\n    simpl.  reflexivity. \nQed. \n\nEnd NatList.\n\nModule PartialMap.\nExport NatList. (* make the definitions from NatList available here *)\n\n(* Partial Maps *)\n(* Internally, an id is just a number.\nIntroducing a separate type by wrapping each nat with\nthe tag Id makes definitions more readable and gives \nus flexibility to change representations later if we want to. *)\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.\nTheorem eqb_id_refl : forall x : id, eqb_id x x = true.\nProof.\n  intros x. \n  destruct x as [x'].\n  simpl. \n  rewrite eqbnat_refl'. \n  reflexivity.\nQed. \n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nFixpoint find (k : id) (m : partial_map) : natoption := \n  match m with \n    | empty => None \n    | record k' v m' => if (eqb_id k k') then Some v else find k m'\n  end.\n\nDefinition map0 := \n  (record (Id 0) 0 (record (Id 1) 1 (record (Id 2) 2 empty))).\nExample test_find0: find (Id 0) map0 = Some 0. Proof. reflexivity. Qed. \nExample test_find1: find (Id 1) map0 = Some 1. Proof. reflexivity. Qed. \nExample test_find2: find (Id 2) map0 = Some 2. Proof. reflexivity. Qed. \nExample test_find3: find (Id 3) map0 = None. Proof. reflexivity. Qed. \nExample test_find4: find (Id 3) empty = None. Proof. reflexivity. Qed. \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. 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. \n  intro H. \n  simpl. rewrite H. reflexivity. \nQed.\n\nEnd PartialMap. \n\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8670357460591569, "lm_q1q2_score": 0.7563563568268681}}
{"text": "Lemma solving_by_reflexivity:\n    2 + 3 = 5\n.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma solving_by_apply :\n  forall (P Q: nat -> Prop),\n  (forall n, Q n -> P n)\n  -> (forall n, Q n)\n  -> P 2.\nProof.\n  intros P Q n1 n2.\n  apply n1.\n  apply n2.\nQed.\n\nLemma solving_conj_goal:\n  forall (P: nat -> Prop) (F: Prop),\n  (forall n, P n) -> F -> F /\\ P 2.\nProof.\n  auto.\nQed.\n\nRequire Import Arith.\n(* add Le.le_refl to hint database *)\nHint Resolve Le.le_refl.\n(* add molt_le_compat_l to arith database. *)\nHint Resolve mult_le_compat_l: arith.\n\n\nRequire Import Omega.\n\nLemma omega_demo :\n  forall (x y z : nat),\n  (x + y = z + z) -> (x - y <= 4) -> (x - z <= 2)\n.\nProof.\n  intros.\n  info omega.\nQed.\n\nLemma omega_demo' :\n  forall (x y : nat),\n  (x + 5 <= y) -> (y - x < 3) -> False\n.\nProof.\n  intros.\n  info omega.\nQed.\n\n\nRequire Import ZArith.\nOpen Scope Z_scope.\n\nLemma ring_demo:\n  forall (x y z: Z),\n  x * (y + z) - z * 3 * x = x * y - 2 * x * z\n.\nProof.\n  intros.\n  info ring.\nQed.\n\n\nOpen Scope nat_scope.\n\nLemma congruence_demo :\n  forall (f : nat -> nat -> nat),\n  forall (g h : nat -> nat),\n  forall (x y z : nat),\n  (forall a, g a = h a)\n  -> f (g x) (g y) = z\n  -> g x = 2\n  -> f 2 (h y) = z\n.\nProof.\n  intros.\n  info rewrite <- H1.\n  rewrite <-  H.\n  apply H0.\n  (* congruence. *)\nQed.\n\nLemma congruence_demo':\n  forall (f g : nat -> nat),\n  (forall a, f a = g a) -> f (g (g 2) ) = g (f (f 2) )\n.\nProof.\n  intros.\n\n  info congruence.\nQed.\n\n\n", "meta": {"author": "seizans", "repo": "coqtest", "sha": "2e106a3cc79338652b5af0d9692a16cb9aeb481e", "save_path": "github-repos/coq/seizans-coqtest", "path": "github-repos/coq/seizans-coqtest/coqtest-2e106a3cc79338652b5af0d9692a16cb9aeb481e/topse/23.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7563421514826896}}
{"text": "From mathcomp\n     Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Logic.\n  Hypothesis ExMidLaw : forall P : Prop, P \\/ ~P.\n\n  Lemma notnotEq (P : Prop): ~~P -> P.\n  Proof.\n    move => HnotnotP.\n    move : (ExMidLaw (~P)).\n    case.\n    -by move /HnotnotP.\n    -by case : (ExMidLaw P).\n  Qed.\n\n  Lemma DeMorgran_1 (A B : Prop) : ~(A /\\ B) -> ~A \\/ ~B.\n  Proof.\n    move => notAandB.\n    apply : notnotEq.\n    move => HnotnotNAorNB.\n    apply : notAandB.\n    apply : conj.\n    apply : notnotEq.\n    move => HnotnotA.\n    apply : HnotnotNAorNB.\n    apply : or_introl.\n    apply : HnotnotA.\n    apply : notnotEq.\n    move => HnotnotB.\n    apply : HnotnotNAorNB.\n    apply : or_intror.\n    apply : HnotnotB.\n  Qed.\n\n  Lemma DeMorgran_2 (A B : Prop) :  ~A \\/ ~B -> ~(A /\\ B).\n  Proof.\n    move => Hor. (* -> 導入 *)\n    move => Hand. (* not 導入 *)\n    move : Hor. (* ~A \\/ ~Bを仮定する *)\n    case. (* \\/の除去 AとBの場合分け *)\n    move => notA.\n    apply notA. (* not の除去 *)\n    apply Hand. (* /\\の除去 *)\n    move => notB.\n    apply notB.\n    apply Hand.\n  Qed.\n\n  Lemma DeMorgran (A B : Prop) : ~(A /\\ B) <-> ~A \\/ ~B.\n  Proof.\n    rewrite /iff.\n    -apply : conj => notAandB.\n     +apply : notnotEq => HnotnotNAorNB.\n      apply : notAandB.\n      apply : conj.\n      *apply : notnotEq => HnotnotA.\n       apply : HnotnotNAorNB.\n       apply : or_introl.\n       apply : HnotnotA.\n       apply : notnotEq => HnotnotB.\n       apply : HnotnotNAorNB.\n       apply : or_intror.\n       apply : HnotnotB.\n    -move : notAandB => HnotAornotB.\n     move => HAandB.\n     move : HnotAornotB.\n     +case => notA.\n      apply : notA.\n      apply HAandB.\n      move : notA => notB.\n      apply : notB.\n      apply HAandB.\n  Qed.\n\n  Lemma J_DeMorgan_0 (T : Type) (P : T -> Prop):\n    ~(exists x, (P x)) -> forall x, ~(P x).\n  Proof.\n    move => HnotEx.\n    move => x0 HPx.\n    apply : HnotEx.\n    exists x0.\n      by [].\n  Qed.\n  \n  Lemma J_DeMorgan_1 (T : Type) (P : T -> Prop):\n    ~(forall x, (P x)) -> exists x, ~(P x).\n  Proof.\n    move => notForAll.\n    apply : notnotEq.\n    move => HnotnotEP.\n    apply : notForAll.\n    move => x0.\n    apply : notnotEq.\n    move => notnotP.\n    apply : HnotnotEP.\n    exists x0.\n      by [].\n  Qed.\n\n  Lemma J_DeMorgan_2 (T : Type) (P : T -> Prop):\n    (exists x, ~(P x)) -> ~(forall x, (P x)).\n  Proof.\n    case.\n    move => x0 HnotPx0.\n    apply : notnotEq.\n    move => H1.\n    apply : HnotPx0.\n    apply : notnotEq.\n    move => H2.\n    apply : H1.\n    move => H3.\n    apply : H2.\n    apply : H3.\n  Qed.\n\n  Lemma J_DeMorgan (T : Type) (P : T -> Prop):\n    ~(forall x, (P x)) <-> exists x, ~(P x).\n  Proof.\n    rewrite /iff.\n    apply conj.\n    apply : J_DeMorgan_1.\n    apply : J_DeMorgan_2.\n  Qed.\n\nEnd Logic.\n\n\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/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7563421502808122}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import Bool.\nOpen Scope Z_scope.\nParameter max_int:Z.\nDefinition min_int:Z:=(1-max_int).\nPrint min_int.\nDefinition cube (z:Z):Z:=z*z*z.\nPrint cube.\nCheck cube.\nDefinition multi (z:Z)(x:Z):Z:=z*x.\nPrint multi.\nCompute (multi 12 2).\nDefinition Z_thrice (f:Z->Z)(z:Z):=f(f(f z)).\nPrint Z_thrice.\nDefinition plus3:=Z_thrice(fun z:Z=>(z+1)%Z).\nPrint plus3.\nCheck plus3.\nCompute (plus3 32).\nDefinition anonymous_fun:=fun (a b c d e:Z)=>a+b+c+d+e.\nPrint anonymous_fun.\nCompute (anonymous_fun 1 2 3 4 5).\nSection binomial_def.\n  Variables a b:Z.\n  Definition binomial (z:Z):=a*z+b.\n  Print binomial.\nEnd binomial_def.\nPrint binomial.\n\nDefinition p1:Z->Z:=binomial 5 2.\nPrint p1.\nCompute (p1 3).\n\nSection sum_5_params.\n  Variables a b c d e:Z.\n  Definition sum_f:=a+b+c+d+e.\nEnd sum_5_params.\n\nPrint sum_f.\nCompute (sum_f 1 2 3 4 5).\n\nSection h_def.\n  Variables a b:Z.\n  Let s:Z:=a+b.\n  Let d:Z:=a-b.\n  Definition h:Z:=s*s+d*d.\nEnd h_def.\nPrint h.\nCheck h.\n\nDefinition h_2:=fun (a b:Z)=>(a+b)*(a+b)+(a-b)*(a-b).\nPrint h_2.\n\n(*Eval usage*)\n\nDefinition Zsqr(z:Z):Z:=z*z.\nDefinition my_fun(f:Z->Z)(z:Z):Z:=f (f z).\nEval cbv delta [my_fun Zsqr] in (my_fun Zsqr).\nCompute ((my_fun Zsqr) 2). (*2^4*)\nEval cbv delta [my_fun] in (my_fun Zsqr).\n(*Eval cbv delta in (my_fun Zsqr).*)\n\nEval cbv beta delta [my_fun Zsqr] in (my_fun Zsqr).\n\nEval cbv delta [h_2] in (h_2 32 23).\nEval cbv beta delta [h_2] in (h_2 32 23).\nEval cbv beta zeta delta [h_2] in (h_2 32 23).\n\nEval cbv delta [h] in (h 32 23).\nEval cbv beta delta [h] in (h 32 23).\nEval cbv beta zeta delta [h] in (h 32 23).\n\nDefinition f1:=fun x:Z=>2*x*x+3*x+3.\nEval compute in (f1 2).\nCompute (f1 2).\nEval cbv iota beta zeta delta [f1] in (f1 2).\n\n\nCheck Z.\nCheck 2.\nCheck Z->Z.\nCheck nat->nat.\nCheck f1.\nCheck (f1 2).\nCheck Set.\nCheck Type.\nCheck (nat->nat:Type).\n\nSection Minimal_propositional_logic.\n  Variables P Q R T:Prop.\n  Theorem imp_trans:(P->Q)->(Q->R)->P->R.\n    Proof.\n      intros H H' p.\n      apply H'.\n      apply H.\n      (*apply p.*)\n      (*assumption.*)\n      exact p.\n    Qed.\n  Check (P->Q)->(Q->R)->P->R.\n  \n\n  \n  Section example_of_assumption.\n    Hypothesis H:P->Q->R.\n    Lemma L1:P->Q->R.\n      Proof.\n        assumption.\n      Qed.\n    Theorem delta:(P->P->Q)->P->Q.\n      Proof.\n        exact (fun (H:P->P->Q)(p:P)=>H p p).\n      Qed.\n  End example_of_assumption.\n  \n  Theorem 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      Show 1.\n      apply H.\n      apply p.\n      exact (H' p).\n    Qed.\n  \n  Definition f:(nat->bool)->(nat->bool)->nat->bool.\n    intros f1 f2.\n    assumption.\n  Defined.\n  Print f.\n    \n\n\n\nEnd Minimal_propositional_logic.\n\nPrint imp_dist.\n\nSection section_for_cut_example.\n  Variables P Q R T:Prop.\n  Hypothesis (H:P->Q) (H0:Q->R) (H1:(P->R)->T->Q) (H2:(P->R)->T).\n  \n  Theorem cut_example:Q.\n    Proof.\n      cut (P->R).\n      intros H3.\n      apply H1;[assumption|apply H2;assumption].\n      intros H3.\n      apply H0;apply H;assumption.\n    Qed.\nEnd section_for_cut_example.\n      \n\n", "meta": {"author": "10ca1h0st", "repo": "coq_book", "sha": "b1bed3e3062bb2378273ae1252c9f72e7c0d96a9", "save_path": "github-repos/coq/10ca1h0st-coq_book", "path": "github-repos/coq/10ca1h0st-coq_book/coq_book-b1bed3e3062bb2378273ae1252c9f72e7c0d96a9/coqbook.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7563421333315963}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 :=\n  plus y (Succ (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/goal33conj233_coqofml_OC9Av8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7563391048787839}}
{"text": "(* BEGIN FIX *)\nInductive Nat : Type :=\n  | O : Nat\n  | S : Nat -> Nat.\n\nFixpoint plus (n m : Nat) {struct n} : Nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nNotation \"n + m\" := (plus n m)\n  (at level 50, left associativity).\n\nFixpoint mul (n m : Nat) {struct n} : Nat\n(* END FIX *)\n := match n with\n | O => O\n | S O => m\n | S n' => (plus m (mul n' m))\nend.\n\n(* BEGIN FIX *)\nNotation \"n * m\" := (mul n m)\n  (at level 40, left associativity).\n\nExample mul_test_1 : S (S O) * S O = S (S O).\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nExample mul_test_2 : S (S O) * S (S (S O)) = S (S (S (S (S (S O))))).\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nExample mul_test_3 : S (S O) * O = O.\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nExample mul_test_4 : O * S (S O) = O.\n(* END FIX *)\nsimpl.\nreflexivity.\nQed.\n\n(* BEGIN FIX *)\nLemma assoc (n m o : Nat) : n + (m + o) = (n + m) + o.\n(* END FIX *)\ninduction n as [|n' H].\nsimpl.\nreflexivity.\nsimpl.\nrewrite <- H.\nreflexivity.\nQed.", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/02/hf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7562811255909658}}
{"text": "Require Import Coq.Logic.PropExtensionality.\n\nRequire Import ClassicalEnsembles.Core.\nRequire Import ClassicalEnsembles.Tactics.\n\nImport SetElementNotation.\n\n(* Defined in Coq.Sets.Ensembles.\nInductive Intersection (U : Type) (B C : Ensemble U) : Ensemble U\n  := Intersection_intro : forall x : U, x ∈ B -> x ∈ C -> x ∈ B ∩ C.\nInductive Union (U : Type) (B C : Ensemble U) : Ensemble U\n  := Union_introl : forall x : U, x ∈ B -> x ∈ B ∪ C\n  | Union_intror : forall x : U, x ∈ C -> x ∈ B ∪ C.\nInductive Empty_set (U : Type) : Ensemble U := .\nInductive Full_set (U : Type) : Ensemble U\n  := Full_intro : forall x : U, x ∈ Full_set U.\nDefiition Complement (U : Type) (A : Ensemble U) : Ensemble U := fun x => ~x ∈ A.\n*)\nArguments Intersection {X} A B : rename.\nArguments Union {X} A B : rename.\nArguments Empty_set {X} : rename.\nArguments Full_set {X} : rename.\nArguments Complement {X} A : rename.\n\nModule SetAlgebraNotation.\n\nNotation \"A ∩ B\" := (Intersection A B)\n  (at level 67, left associativity).\nNotation \"A ∪ B\" := (Union A B)\n  (at level 68, left associativity).\nNotation \"'∅'\" := Empty_set.\nNotation \"'⊤'\" := Full_set.\nNotation \"A 'ᶜ'\" := (Complement A)\n  (at level 65).\nNotation \"A \\ B\" := (Intersection A (Complement _ B))\n  (at level 67, left associativity, only parsing).\n\nEnd SetAlgebraNotation.\nImport SetAlgebraNotation.\n\nTheorem empty_is_empty {X}\n  : @is_empty X ∅.\nProof. intros ? []. Qed.\n\nTheorem is_empty_empty {X} (A : Ensemble X)\n  : is_empty A = (A = ∅).\nProof.\n  apply propositional_extensionality. split.\n  - intros p. rewrite <- ensemble_extensionality. split.\n    + intros x ?. contradiction (p x).\n    + intros ? [].\n  - intros ->. apply empty_is_empty.\nQed.\n\nTheorem full_is_full {X}\n  : @is_full X ⊤.\nProof. constructor. Qed.\n\nTheorem is_full_full {X} (A : Ensemble X)\n  : is_full A = (A = ⊤).\nProof.\n  apply propositional_extensionality. split.\n  - intros p. rewrite <- ensemble_extensionality. split.\n    + constructor.\n    + intros x ?. apply (p x).\n  - intros ->. apply full_is_full.\nQed.\n\nTheorem intersection_char {X} (A B : Ensemble X) x \n  : x ∈ A ∩ B = (x ∈ A /\\ x ∈ B).\nProof.\n  apply propositional_extensionality. split.\n  - intros p. now destruct p.\n  - intros []. auto with sets.\nQed.\n\nTheorem union_char {X} (A B : Ensemble X) x\n  : x ∈ A ∪ B = (x ∈ A \\/ x ∈ B).\nProof.\n  apply propositional_extensionality. split.\n  - intros p. destruct p; auto.\n  - intros []; now constructor.\nQed.\n\nTheorem empty_char {X} (x : X)\n  : x ∈ ∅ = False.\nProof.\n  apply propositional_extensionality. split.\n  - intros [].\n  - intros [].\nQed.\n\nTheorem full_char {X} (x : X)\n  : x ∈ ⊤ = True.\nProof.\n  apply propositional_extensionality. split.\n  - auto.\n  - constructor.\nQed.\n\nTheorem complement_char {X} (A : Ensemble X) x\n  : x ∈ A ᶜ = ~ x ∈ A.\nProof.\n  reflexivity.\nQed.\n\nGlobal Hint Resolve empty_is_empty : sets.\nGlobal Hint Rewrite @is_empty_empty : sets.\nGlobal Hint Resolve full_is_full : sets.\nGlobal Hint Rewrite @is_full_full : sets.\nGlobal Hint Resolve Full_intro : sets.\nGlobal Hint Rewrite @intersection_char : sets.\nGlobal Hint Rewrite @union_char : sets.\nGlobal Hint Rewrite @empty_char : sets.\nGlobal Hint Rewrite @full_char : sets.\nGlobal Hint Rewrite @complement_char : sets.\n\nTheorem intersection_idem {X} (A : Ensemble X)\n  : A ∩ A = A.\nProof. setsolve. Qed.\n\nTheorem intersection_comm {X} (A B : Ensemble X)\n  : A ∩ B = B ∩ A.\nProof. setsolve. Qed.\n\nTheorem intersection_assoc {X} (A B C : Ensemble X)\n  : A ∩ (B ∩ C) = (A ∩ B) ∩ C.\nProof. setsolve. Qed.\n\nTheorem intersection_subset_left {X} (A B : Ensemble X)\n  : A ∩ B ⊂ A.\nProof. setsolve. Qed.\n\nTheorem intersection_equals_left {X} (A B : Ensemble X)\n  : A ⊂ B -> A ∩ B = A.\nProof. setsolve. Qed.\n\nTheorem intersection_subset_right {X} (A B : Ensemble X)\n  : A ∩ B ⊂ B.\nProof. setsolve. Qed.\n\nTheorem intersection_equals_right {X} (A B : Ensemble X)\n  : B ⊂ A -> A ∩ B = B.\nProof. setsolve. Qed.\n\nTheorem intersection_universal {X} (A B C : Ensemble X)\n  : C ⊂ A -> C ⊂ B -> C ⊂ A ∩ B.\nProof. setsolve. Qed.\n\nTheorem union_idem {X} (A : Ensemble X)\n  : A ∪ A = A.\nProof. setsolve. Qed.\n\nTheorem union_comm {X} (A B : Ensemble X)\n  : A ∪ B = B ∪ A.\nProof. setsolve. Qed.\n\nTheorem union_assoc {X} (A B C : Ensemble X)\n  : A ∪ (B ∪ C) = (A ∪ B) ∪ C.\nProof. setsolve. Qed.\n\nTheorem union_subset_left {X} (A B : Ensemble X)\n  : A ⊂ A ∪ B.\nProof. setsolve. Qed.\n\nTheorem union_equals_left {X} (A B : Ensemble X)\n  : B ⊂ A -> A ∪ B = A.\nProof. setsolve. Qed.\n\nTheorem union_subset_right {X} (A B : Ensemble X)\n  : B ⊂ A ∪ B.\nProof. setsolve. Qed.\n\nTheorem union_equals_right {X} (A B : Ensemble X)\n  : A ⊂ B -> A ∪ B = B.\nProof. setsolve. Qed.\n\nTheorem union_universal {X} (A B C : Ensemble X)\n  : A ⊂ C -> B ⊂ C -> A ∪ B ⊂ C.\nProof. setsolve. Qed.\n\nTheorem intersection_empty_left {X} (A : Ensemble X)\n  : ∅ ∩ A = ∅.\nProof. setsolve. Qed.\n\nTheorem intersection_empty_right {X} (A : Ensemble X)\n  : A ∩ ∅ = ∅.\nProof. setsolve. Qed.\n\nTheorem union_empty_left {X} (A : Ensemble X)\n  : ∅ ∪ A = A.\nProof. setsolve. Qed.\n\nTheorem union_empty_right {X} (A : Ensemble X)\n  : A ∪ ∅ = A.\nProof. setsolve. Qed.\n\nTheorem intersection_full_left {X} (A : Ensemble X)\n  : ⊤ ∩ A = A.\nProof. setsolve. Qed.\n\nTheorem intersection_full_right {X} (A : Ensemble X)\n  : A ∩ ⊤ = A.\nProof. setsolve. Qed.\n\nTheorem union_full_left {X} (A : Ensemble X)\n  : ⊤ ∪ A = ⊤.\nProof. setsolve. Qed.\n\nTheorem union_full_right {X} (A : Ensemble X)\n  : A ∪ ⊤ = ⊤.\nProof. setsolve. Qed.\n\nTheorem empty_universal {X} (A : Ensemble X)\n  : ∅ ⊂ A.\nProof. setsolve. Qed.\n\nTheorem empty_equals {X} (A : Ensemble X)\n  : A ⊂ ∅ -> A = ∅.\nProof. setsolve. Qed.\n\nTheorem full_universal {X} (A : Ensemble X)\n  : A ⊂ ⊤.\nProof. setsolve. Qed.\n\nTheorem full_equals {X} (A : Ensemble X)\n  : ⊤ ⊂ A -> A = ⊤.\nProof. setsolve. Qed. \n\nTheorem union_intersection_distr_right {X} (A B C : Ensemble X)\n  : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C).\nProof. setsolve. Qed.\n\nTheorem union_intersection_distr_left {X} (A B C : Ensemble X)\n  : (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C).\nProof. setsolve. Qed.\n\nTheorem intersection_union_distr_right {X} (A B C : Ensemble X)\n  : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C).\nProof. setsolve. Qed.\n\nTheorem intersection_union_distr_left {X} (A B C : Ensemble X)\n  : (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C).\nProof. setsolve. Qed.\n\nTheorem complement_complement {X} (A : Ensemble X)\n  : A ᶜ ᶜ = A.\nProof. setsolve. Qed.\n\nTheorem complement_intersection {X} (A B : Ensemble X)\n  : (A ∩ B)ᶜ = A ᶜ ∪ B ᶜ.\nProof. setsolve. Qed.\n\nTheorem complement_union {X} (A B : Ensemble X)\n  : (A ∪ B)ᶜ = A ᶜ ∩ B ᶜ.\nProof. setsolve. Qed.\n\nTheorem complement_empty {X}\n  : ∅ ᶜ = ⊤ :> Ensemble X.\nProof. setsolve. Qed.\n\nTheorem complement_full {X}\n  : ⊤ ᶜ = ∅ :> Ensemble X.\nProof. setsolve. Qed.\n\nTheorem intersection_complement_left {X} (A : Ensemble X)\n  : A ᶜ ∩ A = ∅.\nProof. setsolve. Qed.\n\nTheorem intersection_complement_right {X} (A : Ensemble X)\n  : A ∩ A ᶜ = ∅.\nProof. setsolve. Qed.\n\nTheorem union_complement_left {X} (A : Ensemble X)\n  : A ᶜ ∪ A = ⊤.\nProof. setsolve. Qed.\n\nTheorem union_complement_right {X} (A : Ensemble X)\n  : A ∪ A ᶜ = ⊤.\nProof. setsolve. Qed.\n\nTheorem complement_subset {X} (A B : Ensemble X)\n  : A ⊂ B = B ᶜ ⊂ A ᶜ.\nProof.\n  apply propositional_extensionality. setsolve.\nQed.\n\nTheorem subset_cartesian_adjunction {X} (A B C : Ensemble X)\n  : A ∩ B ⊂ C = A ⊂ B ᶜ ∪ C.\nProof.\n  apply propositional_extensionality. setsolve. firstorder.\nQed.\n\nTheorem subset_cocartesian_adjunction {X} (A B C : Ensemble X)\n  : A ⊂ B ∪ C = A ∩ B ᶜ ⊂ C.\nProof.\n  apply propositional_extensionality. setsolve. firstorder.\nQed.\n\nTheorem intersection_is_empty_left {X} (A B : Ensemble X)\n  : is_empty A -> is_empty (A ∩ B).\nProof. setsolve. Qed.\n\nTheorem intersection_is_empty_right {X} (A B : Ensemble X)\n  : is_empty B -> is_empty (A ∩ B).\nProof. setsolve. Qed.\n\nTheorem union_is_empty {X} (A B : Ensemble X)\n  : is_empty A /\\ is_empty B <-> is_empty (A ∪ B).\nProof. setsolve. Qed.\n\nTheorem intersection_is_full {X} (A B : Ensemble X)\n  : is_full A /\\ is_full B <-> is_full (A ∩ B).\nProof. setsolve_firstorder. Qed.\n\nTheorem union_is_full_left {X} (A B : Ensemble X)\n  : is_full A -> is_full (A ∪ B).\nProof. setsolve. Qed.\n\nTheorem union_is_full_right {X} (A B : Ensemble X)\n  : is_full B -> is_full (A ∪ B).\nProof. setsolve. Qed.\n", "meta": {"author": "mniip", "repo": "coq-classical-ensembles", "sha": "7f65fbcf55ecf519ab4f1eb77c8ac1ee02618778", "save_path": "github-repos/coq/mniip-coq-classical-ensembles", "path": "github-repos/coq/mniip-coq-classical-ensembles/coq-classical-ensembles-7f65fbcf55ecf519ab4f1eb77c8ac1ee02618778/ClassicalEnsembles/Algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7562520106236422}}
{"text": "\n(* Values of type sumor A B are either a value of type A or a proof of B        *) \n\n(*\nPrint sumor.\n\nInductive sumor (A : Type) (B : Prop) : Type :=\n    inleft : A -> A + {B} | inright : B -> A + {B}\n\nFor inleft, when applied to no more than 1 argument:\nArguments A, B are implicit and maximally inserted\nFor inleft, when applied to 2 arguments:\nArgument A is implicit\nFor inright, when applied to no more than 1 argument:\nArguments A, B are implicit and maximally inserted\nFor inright, when applied to 2 arguments:\nArgument B is implicit\nFor sumor: Argument scopes are [type_scope type_scope]\nFor inleft: Argument scopes are [type_scope type_scope _]\nFor inright: Argument scopes are [type_scope type_scope _]\n*)\n\n(* This is not a 'sumbool' type {A} + {B} but a 'sumor' type A + {B}            *)\nDefinition pred_strong (n:nat) : {m:nat | S m = n} + {n = 0} :=\n    match n with\n    | 0     => inright (eq_refl 0)\n    | S n   => inleft (exist _ n (eq_refl (S n)))\n    end. \n     \n(*\nCompute pred_strong 5.\n    = inleft (exist (fun m : nat => S m = 5) 4 eq_refl)\n    : {m : nat | S m = 5} + {5 = 0}\n*)\n\nDefinition maybe (n:nat) (def:nat) (x:{m:nat | S m = n} + {n = 0}) : nat :=\n    match x with\n    | inright _             => def\n    | inleft (exist _ m _)  => m\n    end.\n\nArguments maybe {n} _ _.\n\n(*\nCompute (maybe 0 (pred_strong 10)).\n*)\n\nExample pred_strong_test1 : maybe 0 (pred_strong 10) = 9.\nProof. reflexivity. Qed.\n\n\nExample pred_strong_test2 : maybe 9 (pred_strong 0) = 9.\nProof. reflexivity. Qed.\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/sumor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7562520023923323}}
{"text": "Require Import Div2.\nRequire Import Arith.\nRequire Import Omega.\n\nGoal forall n : nat, div2 (S n) < S n.\nProof.\n  intros n.\n  (* Hintデータベースとしてarithを指定して、Resoluitonをする。 *)\n  (* debug *) auto with arith.\nQed.\n  \nGoal forall n : nat, div2 (S n) < S n.\nProof.\n  intros n.  \n  (* 上記のautoと同内容を手動でおこなう例。 *)\n  Check lt_div2 : forall n : nat, 0 < n -> Nat.div2 n < n.\n  apply lt_div2.\n  Check Nat.lt_0_succ : forall n : nat, 0 < S n.\n  apply Nat.lt_0_succ.\nQed.\n  \nGoal forall n : nat, div2 (S n) < S n.\nProof.\n  intros n.  \n  apply lt_div2.\n  (* 0 < S n をプレスバーガー算術で解く。 *)\n  omega.\nQed.\n\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/intro/1-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.756227022849743}}
{"text": "From LF Require Export Basics.\n\nTheorem plus_n_O : forall n: nat, n = n + 0.\nProof.\n  intros n. induction n.\n  - reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem minus_diag : forall n,\n    minus n n = 0.\nProof.\n  induction n. reflexivity.\n  simpl. assumption.\nQed.\n\n\nTheorem mult_0_r : forall n:nat,\n    n * 0 = 0.\nProof.\n  induction n.\n  - trivial.\n  - simpl. assumption.\nQed.\n\nTheorem plus_n_Sm: forall n m: nat,\n    S (n + m) = n + (S m).\nProof.\n  intros n m.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn.\n    reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  - simpl. rewrite <- plus_n_O. reflexivity.\n  - simpl. rewrite <- 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.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus : forall n,  double n = n + n.\n  induction n.\n  - simpl. trivial.\n  - simpl. rewrite -> IHn. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => evenb n'\n  end.\n\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  induction n.\n  - trivial.\n  - rewrite -> IHn.  simpl. rewrite negb_involutive. reflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n). { reflexivity. }\n                         rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange : forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.\n  assert (H: n + m = m + n).\n  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. 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  rewrite plus_assoc.\n  assert (H: n + m = m + n). { rewrite plus_comm. reflexivity. }.\n  rewrite H.\n  rewrite plus_assoc.\n  reflexivity. Qed.\n\nTheorem mult_n_0 : forall n : nat,\n  n * 0 = 0.\nProof.\n  intros n.\n  induction n. trivial. simpl. assumption.\nQed.\n\nTheorem mult_n_Sm: forall n m : nat,\n  n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n.\n  - rewrite <- mult_n_Sm. trivial.\n  - simpl. rewrite -> IHn. rewrite plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros n m.\n  induction m.\n  - simpl. rewrite -> mult_n_0. trivial.\n  - simpl. rewrite -> mult_n_Sm. rewrite IHm. trivial.\nQed.\n\nTheorem leb_refl : forall n:nat,\n  true = leb n n.\nProof.\n  intros n.\n  induction n as [|n' IHn].\n  - (* n = 0 *)\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  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.\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.\n  induction p.\n  - trivial.\n  - simpl. assumption.\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.\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.\n  induction n.\n  - (* n = 0 *) reflexivity.\n  - (* 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.\n  - (* n = 0 *) reflexivity.\n  - (* n = S n' *)\n    simpl.\n    rewrite -> IHn.\n    rewrite -> mult_plus_distr_r.\n    reflexivity.\nQed.\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  induction n.\n  trivial.\n  simpl. assumption.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite plus_assoc.\n  replace (n + m) with (m + n).\n  rewrite plus_assoc.\n  reflexivity.\n  rewrite plus_comm.\n  reflexivity.\nQed.\n", "meta": {"author": "williamhogman", "repo": "labs", "sha": "c12fdf23c2dc6760f8a9bd9797982a30337f8afa", "save_path": "github-repos/coq/williamhogman-labs", "path": "github-repos/coq/williamhogman-labs/labs-c12fdf23c2dc6760f8a9bd9797982a30337f8afa/theoremproving/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7562054570289957}}
{"text": "Check nat_ind.\n\nTheorem mult_0_r':\n  forall n: nat, n * 0 = 0.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - simpl. intros n H. apply H.\nQed.\n\nTheorem plus_one_r': forall n: nat, n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros n H. \n    simpl. f_equal. apply H. \nQed.\n\n\nInductive time : Type :=\n  | day\n  | night.\nCheck time_ind.\n\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\n(*\nforall (X: Type) (P: tree X -> Prop),\n  (forall x: X, P (leaf x)) ->\n  (forall t1: tree X, P t1) ->\n  forall t2: tree X, P t2 ->\n  P (node t1 t2)) -> \n  (forall (t: tree X), P t)\n*)\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n\n\nInductive mytype (X: Type) : Type :=\n| constr1: X -> mytype X\n| constr2: nat -> mytype X\n| constr3: mytype X -> nat -> mytype X.\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.\nCheck foo_ind.\n\n\nInductive foo' (X: Type): Type :=\n| c1 (l: list X) (f: foo' X)\n| c2.\n\nDefinition P_m0r : nat->Prop :=\n  fun n => n * 0 = 0.\n\nCheck foo'_ind.\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    (* 请注意目前的证明状态！ *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. \nQed.\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. \nQed.\n\n\n\n\n\n", "meta": {"author": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8757869786798664, "lm_q1q2_score": 0.756147123359559}}
{"text": "Require Import Lia.\nRequire Import ssreflect ssrbool ssrfun.\nRequire Import Arith.\nRequire Import List.\nImport Nat.\nImport ListNotations.\n\nRequire Import Lists.Streams.\n\n\n\n\n\n(** Definitions **)\n\nDefinition sum := fold_right add 0.\n\nNotation take := firstn.\nNotation drop := skipn.\nDefinition rotate {A} (n : nat) (l : list A) : list A :=\n  drop (n mod length l) l ++ take (n mod length l) l.\n\n\n\n\n\n\n\n(** Proof **)\n\nLemma sum_app xs ys:\n  sum (xs ++ ys) = sum xs + sum ys.\nProof.\n  induction xs;cbn;trivial.\n  rewrite IHxs;lia.\nQed.\n\nLemma repeat_rotate {X} (xs:list X) n m:\n  concat (repeat (rotate m xs) (S n)) =\n  (drop (m mod length xs) xs) ++ concat(repeat xs n) ++ (take (m mod length xs) xs).\nProof.\n  induction n in m,xs |- *.\n  - cbn. rewrite app_nil_r.\n    reflexivity.\n  - remember (S n) as n0.\n    cbn.\n    rewrite IHn.\n    unfold rotate.\n    rewrite <- app_assoc.\n    f_equal.\n    rewrite app_assoc.\n    rewrite firstn_skipn.\n    subst n0.\n    cbn.\n    now rewrite <- app_assoc.\nQed.\n\nLemma repeat_sum xs n :\n  sum (concat (repeat xs n)) = n * sum xs.\nProof.\n  induction n;cbn.\n  - reflexivity.\n  - now rewrite sum_app IHn.\nQed.\n\n\n\n\n\n\n\n\n(** common functions custom properties **)\n\nLemma app_not_nil_r {X} (xs:list X) ys:\n  ys <> [] -> xs++ys <> [].\nProof.\n  destruct xs.\n  - trivial.\n  - intros _. cbn. congruence.\nQed.\n\nLemma local_mod_add n m c:\n  m <> 0 ->\n  n mod m = c ->\n  forall k,\n  k+c<m ->\n  (k+n) mod m = (k+c).\nProof.\n  intros.\n  rewrite add_mod;[assumption|].\n  rewrite H0.\n  setoid_rewrite mod_small at 2. 2: lia.\n  rewrite mod_small. 2: lia.\n  assumption.\nQed.\n\n", "meta": {"author": "NeuralCoder3", "repo": "nat_seq", "sha": "cbfc618bd1098fb7d5ced1df168a5c6f5d2f190f", "save_path": "github-repos/coq/NeuralCoder3-nat_seq", "path": "github-repos/coq/NeuralCoder3-nat_seq/nat_seq-cbfc618bd1098fb7d5ced1df168a5c6f5d2f190f/util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7560856036747408}}
{"text": "Module NatPlayground.\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 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\nDefinition not_b (a : bool) :=\n  match a with\n  | true => false\n  | false => true\n  end.\n\nDefinition blt_nat (n m : nat) : bool := andb (leb n m) (not_b (beq_nat n m)).\n\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof.\nreflexivity.\nQed.\n\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof.\nreflexivity.\nQed.\n\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof.\nreflexivity.\nQed.\n\nTheorem simple_minmax : forall n m, n <= m -> min n m <= max n m.\nProof.\n  intros.\n  rewrite min_l.\n  rewrite max_r.\n  assumption. assumption. assumption.\nQed.\n\nEnd NatPlayground.\n\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/1_Basics/2_natplayground.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7560855957419392}}
{"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(* ################################################################# *)\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 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\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 [admit] 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 :=  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 := andb b1 (andb 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\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] 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 ([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 n' => mult n (factorial n')\n  end\n.\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 nothing built-in, we really mean\n    it: even equality testing for numbers is a user-defined operation!\n    We now define a function [beq_nat], which tests [nat]ural numbers\n    for [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 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\n  andb (leb n m) (negb (beq_nat n m))\n\n.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\nProof. simpl. reflexivity.  Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\nProof. simpl. reflexivity.  Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\nProof. simpl. reflexivity.  Qed.\n(** [] *)\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 purely a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean exactly 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].  In order to prove\n    theorems of this form, we need to to be able to reason by\n    _assuming_ the existence of an arbitrary natural number [n].  This\n    is achieved in the proof by [intros n], which moves the quantifier\n    from the goal to a _context_ of current assumptions. In effect, we\n    start the proof by saying \"Suppose [n] is some arbitrary\n    number...\"\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. *)\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 the existence\n    of some 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. intros H. intros H'.\n  rewrite -> H. rewrite <- H'. 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. intros H.\n  simpl. rewrite <- H. reflexivity.\nQed.\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 b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + simpl. intros H. rewrite -> H. reflexivity.\n  - destruct c.\n    + simpl. intros H. reflexivity.\n    + simpl. intros H. rewrite -> H. reflexivity.\nQed.\n(** [] *)\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. destruct n.\n  - simpl. reflexivity.\n  - simpl. 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(* FILL IN HERE *)\n\n\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 x b. rewrite <- x. rewrite <- x. reflexivity.\n Qed.\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 = negb x) ->\n  forall (b : bool), f (f b) = b.\nProof.\n  intros f x b. rewrite -> x. rewrite -> x. rewrite -> negb_involutive. reflexivity.\n Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (andb_eq_orb)  *)\n(** Prove the following theorem.  (You may want to first prove a\n    subsidiary lemma or two. Alternatively, remember that you do\n    not have to introduce all hypotheses at the same time.) *)\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. destruct b.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite <- H. 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  | zero : bin\n  | Z : bin -> bin\n  | l : bin -> bin.\n\nFixpoint incr (n : bin) : bin :=\n  match n with\n    | zero => l zero\n    | Z n' => l n'\n    | l n' => Z (incr n')\n  end.\n\nFixpoint convert (b : bin) : nat :=\n  match b with\n    | zero => 0\n    | Z b' => 2 * convert (b')\n    | l b' => (2 * convert (b')) + 1\n  end.\n\nExample test_bin_incr1: convert (incr(zero)) = 1.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr2: convert (incr (incr(zero))) = 2.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_zero: convert zero = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_1: convert (l (zero)) = 1.\nProof. simpl. reflexivity. Qed.\n(* 8 = 1000 *)\nExample test_bin_8: convert (Z (Z (Z (l (zero))))) = 8.\nProof. simpl. reflexivity. Qed.\n(* 8 = 0000 1000 *)\nExample test_bin_08: convert (Z (Z (Z (l (Z (Z (Z (Z (zero))))))))) = 8.\nProof. simpl. reflexivity. Qed.\n(* 7 = 0000 0111 *)\nExample test_bin_7: convert (  (l (l (l (zero))))) = 7.\nProof. simpl. reflexivity. Qed.\n(* 23 = 0001 0111 *)\nExample test_bin_23: convert (l ( l (l (Z (l (zero)))))) = 23.\nProof. simpl. reflexivity. Qed.\n\n\n(** [] *)\n\n(** $Date: 2016-09-01 14:03:18 +0200 (Jeu, 01 sep 2016) $ *)\n\n", "meta": {"author": "Viinyard", "repo": "SEM", "sha": "34fde92e4dc4cc26755b086a5425bc9a190ce34b", "save_path": "github-repos/coq/Viinyard-SEM", "path": "github-repos/coq/Viinyard-SEM/SEM-34fde92e4dc4cc26755b086a5425bc9a190ce34b/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7560855896869949}}
{"text": "Require Import Init.\n\n(*\n\n直観主義命題論理と古典命題論理の任意の式が常に正しいか判定できる。\nそれを実装したプログラムがある。ある人がパースの公理と排中律の関係を知りたくてこのような式を与えた。\n\n(P \\/ ~ P) -> (((P -> Q) -> P) -> P)\n\n結果は「正しい」となった。次に逆であるこの式を与えた。\n\n(((P -> Q) -> P) -> P) -> (P \\/ ~ P)\n\nすると結果は「誤っている」となった。なぜか？\n\n*)\n\nGoal (forall p q : Prop, ((p -> q) -> p) -> p) -> (forall a : Prop, a \\/ ~ a).\nProof.\n intros peirce a.\n apply peirce with False.\n intros H.\n right.\n intros A.\n apply H.\n left.\n apply A.\nDefined peirce_to_excluded_middle.\n\nGoal (forall a : Prop, a \\/ ~ a) -> (forall p q : Prop, ((p -> q) -> p) -> p).\nProof.\n intros exmi p q H.\n destruct (exmi p) as [P | Pn].\n -\n  apply P.\n -\n  apply H.\n  intros P.\n  exfalso.\n  apply Pn.\n  apply P.\nDefined excluded_middle_to_peirce.\n\n(*\n\n誤りは上のように全称量化が必要なこと。最初の時はなぜ正しかったのか？\n\nexcluded_middle_to_peirceの証明を見ると引数exmiにpを渡している。\nexmi p : p \\/ ~ pとなり、一般のexmiがなくてもこれだけあればよいことになる。\nこうして置き換えたものはちょうど最初に与えた式に一致する。\n\n*)\n\n(*\n\nThank\n\nhttps://github.com/suharahiromichi/coq/blob/2aedd465c255a6aac1466258041d4930211460d9/coq_classical.v\n\n.\n\n*)\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/classic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7560855871770785}}
{"text": "(* LISTA DE EXERCÍCIOS 1 \n   =====================================\n   ALUNOS:\n      PAULO RENATO LANZARIN - 228818\n      MARCOS HENRIQUE BACKES - 228483\n      MATHEUS ROSA CASTANHEIRA - 228400\n   =====================================\n*)\n\n\n\n(* 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\n(* QUESTÃO 1A *)\nInductive type :=\n | tBool : type\n | tNat  : type\n.\n(* QUESTÃO 1B *)\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\n(* QUESTÃO 2A *)\nTheorem dois_a : 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\n(* QUESTÃO 2B *)\nTheorem dois_b : 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\n(* QUESTÃO 2C *)\nTheorem dois_c : ~ (step (ifte (iszero (succ (succ zero))) (succ zero) zero) zero).\nProof.\nunfold not.\nintro.\ninversion H.\nQed.\n\n(* QUESTÃO 2D *)\nTheorem dois_d : ~ forall t : term, value t.\nProof.\nunfold not.\nintro.\nassert (value (iszero zero)).\napply (H (iszero zero)).\ninversion H0.\ninversion H1.\nQed.\n\n(* QUESTÃO 2E *)\nTheorem dois_e : 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\n(* QUESTÃO 3A *)\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", "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/type_system_l0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7560855819648793}}
{"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\t\tusing inductive data types like [nat] or [list] and functions over\n\t\tthese types, and for _proving_ properties of these programs, using\n\t\tinductive propositions (like [even]), implication, universal\n\t\tquantification, and the like.  So far, we have mostly treated\n\t\tthese mechanisms as if they were quite separate, and for many\n\t\tpurposes this is a good way to think.  But we have also seen hints\n\t\tthat Coq's programming and proving facilities are closely related.\n\t\tFor example, the keyword [Inductive] is used to declare both data\n\t\ttypes and propositions, and [->] is used both to describe the type\n\t\tof functions on data and logical implication.  This is not just a\n\t\tsyntactic accident!  In fact, programs and proofs in Coq are\n\t\talmost the same thing.  In this chapter we will study how this\n\t\tworks.\n\n\t\tWe have already seen the fundamental idea: provability in Coq is\n\t\trepresented by concrete _evidence_.  When we construct the proof\n\t\tof a basic proposition, we are actually building a tree of\n\t\tevidence, which can be thought of as a data structure.\n\n\t\tIf the proposition is an implication like [A -> B], then its proof\n\t\twill be an evidence _transformer_: a recipe for converting\n\t\tevidence for A into evidence for B.  So at a fundamental level,\n\t\tproofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n\t\tAnswer: They are types! *)\n\n(** Look again at the formal definition of the [even] property.  *)\n\nPrint even.\n(* ==>\n\tInductive even : nat -> Prop :=\n\t\t| ev_0 : even 0\n\t\t| ev_SS : forall n, even n -> even (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n\t\tInstead of \"has type,\" we can say \"is a proof of.\"  For example,\n\t\tthe second line in the definition of [even] declares that [ev_0 : even\n\t\t0].  Instead of \"[ev_0] has type [even 0],\" we can say that \"[ev_0]\n\t\tis a proof of [even 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n\t\tand [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n\t\t_Curry-Howard correspondence_.  It proposes a deep connection\n\t\tbetween the world of logic and the world of computation:\n\n\t\t\t\t\t\t\t\t propositions  ~  types\n\t\t\t\t\t\t\t\t proofs        ~  data values\n\n\t\tSee [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\t\tit gives us a natural interpretation of the type of the [ev_SS]\n\t\tconstructor: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n\t\t\t\t\t\t\t\t\teven n ->\n\t\t\t\t\t\t\t\t\teven (S (S n)) *)\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n\t\targuments -- a number [n] and evidence for the proposition [even\n\t\tn] -- and yields evidence for the proposition [even (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [even]. *)\n\nTheorem ev_4 : even 4.\nProof.\n\tapply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n\t\tcommand to see the _proof object_ that results from this proof\n\t\tscript. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n\t\t : even 4  *)\n\n(** Indeed, we can also write down this proof object _directly_,\n\t\twithout the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> even 4 *)\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n\t\tinstantiating the parameterized constructor [ev_SS] with the\n\t\tspecific arguments [2] and [0] plus the corresponding proof\n\t\tobjects for its premises [even 2] and [even 0].  Alternatively, we can\n\t\tthink of [ev_SS] as a primitive \"evidence constructor\" that, when\n\t\tapplied to a particular number, wants to be further applied to\n\t\tevidence that that number is even; its type,\n\n\t\t\tforall n, even n -> even (S (S n)),\n\n\t\texpresses this functionality, in the same way that the polymorphic\n\t\ttype [forall X, list X] expresses the fact that the constructor\n\t\t[nil] can be thought of as a function from types to empty lists\n\t\twith elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n\t\tapplication syntax to instantiate universally quantified variables\n\t\tin lemmas, as well as to supply evidence for assumptions that\n\t\tthese lemmas impose.  For instance: *)\n\nTheorem ev_4': even 4.\nProof.\n\tapply (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\t\tCoq operates.  When Coq is following a proof script, what is\n\t\thappening internally is that it is gradually constructing a proof\n\t\tobject -- a term whose type is the proposition being proved.  The\n\t\ttactics between [Proof] and [Qed] tell it how to build up a term\n\t\tof the required type.  To see this process in action, let's use\n\t\tthe [Show Proof] command to display the current state of the proof\n\t\ttree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : even 4.\nProof.\n\tShow Proof.\n\tapply ev_SS.\n\tShow Proof.\n\tapply ev_SS.\n\tShow Proof.\n\tapply ev_0.\n\tShow Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n\t\t\"hole\" (indicated by [?Goal] here, and so on), and it knows what\n\t\ttype of evidence is needed to fill this hole.\n\n\t\tEach hole corresponds to a subgoal, and the proof is\n\t\tfinished when there are no more subgoals.  At this point, the\n\t\tevidence we've built stored in the global context under the name\n\t\tgiven in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n\t\tessential: in principle, we can always construct the required\n\t\tevidence by hand, as shown above. Then we can use [Definition]\n\t\t(rather than [Theorem]) to give a global name directly to this\n\t\tevidence. *)\n\nDefinition ev_4''' : even 4 :=\n\tev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n\t\tsame evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : even 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)\n\n\t\tGive a tactic proof and a proof object showing that [even 8]. *)\n\nTheorem ev_8 : even 8.\nProof.\n\tapply ev_SS. apply ev_SS. apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : even 8 :=\n\tev_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\t\tprograms live), there are two sorts of values with arrows in their\n\t\ttypes: _constructors_ introduced by [Inductive]ly defined data\n\t\ttypes, and _functions_.\n\n\t\tSimilarly, in Coq's logical universe (where we carry out proofs),\n\t\tthere are two ways of giving evidence for an implication:\n\t\tconstructors introduced by [Inductive]ly defined propositions,\n\t\tand... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, even n -> even (4 + n).\nProof.\n\tintros n H. simpl.\n\tapply ev_SS.\n\tapply ev_SS.\n\tapply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n\t\tWe're looking for an expression whose _type_ is [forall n, even n ->\n\t\teven (4 + n)] -- that is, a _function_ that takes two arguments (one\n\t\tnumber and a piece of evidence) and returns a piece of evidence!\n\n\t\tHere it is: *)\n\nDefinition ev_plus4' : forall n, even n -> even (4 + n) :=\n\tfun (n : nat) => fun (H : even n) =>\n\t\tev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n\t\tyields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n\t\tas synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : even n) : even (4 + n) :=\n\tev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===>\n\t\t : forall n : nat, even n -> even (4 + n) *)\n\n(** When we view the proposition being proved by [ev_plus4] as a\n\t\tfunction type, one interesting point becomes apparent: The second\n\t\targument's type, [even n], mentions the _value_ of the first\n\t\targument, [n].\n\n\t\tWhile such _dependent types_ are not found in conventional\n\t\tprogramming languages, they can be useful in programming too, as\n\t\tthe recent flurry of activity in the functional programming\n\t\tcommunity demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n\t\tcorrespond to functions on evidence.  In fact, they are really the\n\t\tsame thing: [->] is just a shorthand for a degenerate use of\n\t\t[forall] where there is no dependency, i.e., no need to give a\n\t\tname to the type on the left-hand side of the arrow:\n\n\t\t\t\t\t forall (x:nat), nat\n\t\t\t\t=  forall (_:nat), nat\n\t\t\t\t=  nat -> nat\n*)\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n\tforall n, forall (E : even n), even (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n\t\twith two arguments: a number [n] and some evidence [E] that [n] is\n\t\teven.  But the name [E] for this evidence is not used in the rest\n\t\tof the statement of [ev_plus2], so it's a bit silly to bother\n\t\tmaking up a name for it.  We could write it like this instead,\n\t\tusing the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n\tforall n, forall (_ : even n), even (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n\tforall n, even n -> even (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n\t\t\"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n\t\texecuting tactic scripts, you may be wondering whether we can\n\t\tbuild _programs_ using _tactics_ rather than explicit terms.\n\t\tNaturally, 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\t\tadd1 = fun n : nat => S n\n\t\t\t\t : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n\t\twith [:=] followed by a term.  This tells Coq to enter _proof\n\t\tscripting mode_ to build an object of type [nat -> nat].  Also, we\n\t\tterminate the proof with [Defined] rather than [Qed]; this makes\n\t\tthe definition _transparent_ so that it can be used in computation\n\t\tlike a normally-defined function.  ([Qed]-defined objects are\n\t\topaque during computation.)\n\n\t\tThis feature is mainly useful for writing functions with dependent\n\t\ttypes, which we won't explore much further in this book.  But it\n\t\tdoes illustrate the uniformity and orthogonality of the basic\n\t\tideas in Coq. *)\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n\t\tconnectives we have seen so far.  Indeed, only universal\n\t\tquantification (with implication as a special case) is built into\n\t\tCoq; all the others are defined inductively.  We'll see these\n\t\tdefinitions 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\t\t[P] and [Q].  Thus, it makes sense to define a proof object for [P\n\t\t/\\ Q] as consisting of a pair of two proofs: one for [P] and\n\t\tanother 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\t\tgiven in chapter [Poly]; the only difference is that [prod] takes\n\t\t[Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n\t Inductive prod (X Y : Type) : Type :=\n\t | pair : X -> Y -> X * Y. *)\n\n(** This similarity should clarify why [destruct] and [intros]\n\t\tpatterns can be used on a conjunctive hypothesis.  Case analysis\n\t\tallows us to consider all possible ways in which [P /\\ Q] was\n\t\tproved -- here just one (the [conj] constructor).\n\n\t\tSimilarly, the [split] tactic actually works for any inductively\n\t\tdefined proposition with exactly one constructor.  In particular,\n\t\tit works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n\tintros P Q. split.\n\t- intros [HP HQ]. split.\n\t\t+ apply HQ.\n\t\t+ apply HP.\n\t- intros [HP HQ]. split.\n\t\t+ apply HQ.\n\t\t+ apply HP.\nQed.\n\n(** This shows why the inductive definition of [and] can be\n\t\tmanipulated by tactics as we've been doing.  We can also use it to\n\t\tbuild proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : Q /\\ P :=\n\tmatch H with\n\t| conj HP HQ => conj HQ HP\n\tend.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n\tconj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, standard, optional (conj_fact)\n\n\t\tConstruct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n\tfun (P Q R: Prop) (HPQ: P /\\ Q) (HPR: Q /\\ R) =>\n\tmatch HPQ, HPR with\n\t| conj HP _, conj _ HR => conj HP HR\n\tend.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** The inductive definition of disjunction uses two constructors, one\n\t\tfor 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\t\ta disjunctive hypothesis, since the generated subgoals match the\n\t\tshape of the [or_introl] and [or_intror] constructors.\n\n\t\tOnce again, we can also directly write proof objects for theorems\n\t\tinvolving [or], without resorting to tactics. *)\n\n(** **** Exercise: 2 stars, standard, optional (or_commut'')\n\n\t\tTry to write down an explicit proof object for [or_commut] (without\n\t\tusing [Print] to peek at the ones we already defined!). *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P :=\n\tfun (P Q : Prop) (H: P \\/ Q) =>\n\tmatch H with\n\t| or_introl HP => or_intror Q HP\n\t| or_intror HQ => or_introl P HQ\n\tend.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** To give evidence for an existential quantifier, we package a\n\t\twitness [x] together with a proof that [x] satisfies the property\n\t\t[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\t\tfor a type former [ex] that can be used to build propositions of\n\t\tthe form [ex P], where [P] itself is a _function_ from witness\n\t\tvalues in the type [A] to propositions.  The [ex_intro]\n\t\tconstructor then offers a way of constructing evidence for [ex P],\n\t\tgiven a witness [x] and a proof of [P x]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n\t\tinvolving [ex]: *)\n\nCheck ex (fun n => even n).\n(* ===> exists n : nat, even n\n\t\t\t\t: Prop *)\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, even n :=\n\tex_intro even 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, standard, optional (ex_ev_Sn)\n\n\t\tComplete the definition of the following proof object: *)\n\nDefinition ex_ev_Sn : ex (fun n => even (S n)) :=\n\tex_intro (fun n => even (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\t| I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n\t\tbeing given a proof of [True] is not informative.) *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n\t\tsyntactically wrong at first glance! *)\n\nInductive False : Prop := .\n\n(** That is, [False] is an inductive type with _no_ constructors --\n\t\ti.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\t\tfollowing inductive definition.  (Actually, the definition in the\n\t\tstandard library is a slight variant of this, which gives an\n\t\tinduction 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\t\t\t\t\t\t\t\t\t\t(at level 70, no associativity)\n\t\t\t\t\t\t\t\t\t\t: type_scope.\n\n(** The way to think about this definition is that, given a set [X],\n\t\tit defines a _family_ of propositions \"[x] is equal to [y],\"\n\t\tindexed by pairs of values ([x] and [y]) from [X].  There is just\n\t\tone way of constructing evidence for members of this family:\n\t\tapplying the constructor [eq_refl] to a type [X] and a single\n\t\tvalue [x : X], which yields evidence that [x] is equal to [x].\n\n\t\tOther types of the form [eq x y] where [x] and [y] are not the\n\t\tsame are thus uninhabited. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n\t\t2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n\t\tYes, we can.  Indeed, it is the very same piece of evidence!\n\n\t\tThe reason is that Coq treats as \"the same\" any two terms that are\n\t\t_convertible_ according to a simple set of computation rules.\n\n\t\tThese rules, which are similar to those used by [Compute], include\n\t\tevaluation of function application, inlining of definitions, and\n\t\tsimplification of [match]es.  *)\n\nLemma four: 2 + 2 == 1 + 3.\nProof.\n\tapply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\n\t\tto now is essentially just shorthand for [apply eq_refl].\n\n\t\tIn tactic-based proofs of equality, the conversion rules are\n\t\tnormally hidden in uses of [simpl] (either explicit or implicit in\n\t\tother tactics such as [reflexivity]).\n\n\t\tBut you can see them directly at work in the following explicit\n\t\tproof objects: *)\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n\teq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] == x::[]  :=\n\tfun (X:Type) (x:X) => eq_refl [x].\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality)\n\n\t\tThe inductive definition of equality implies _Leibniz equality_:\n\t\twhat we mean when we say \"[x] and [y] are equal\" is that every\n\t\tproperty on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n\tx == y -> forall P:X->Prop, P x -> P y.\nProof.\n\tintros. destruct H. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (leibniz_equality__equality)\n\n\t\tShow that, in fact, the inductive definition of equality is\n\t\t_equivalent_ to Leibniz equality: *)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n\t(forall P:X->Prop, P x -> P y) -> x == y.\nProof.\n\tintros X x y H. apply H. apply eq_refl.\nQed.\n\n(** [] *)\n\nEnd MyEquality.\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n\t\thypotheses about inductively defined propositions.  Now that we've\n\t\tseen that these are actually the same thing, we're in a position\n\t\tto take a closer look at how [inversion] behaves.\n\n\t\tIn general, the [inversion] tactic...\n\n\t\t- takes a hypothesis [H] whose type [P] is inductively defined,\n\t\t\tand\n\n\t\t- for each constructor [C] in [P]'s definition,\n\n\t\t\t- generates a new subgoal in which we assume [H] was\n\t\t\t\tbuilt with [C],\n\n\t\t\t- adds the arguments (premises) of [C] to the context of\n\t\t\t\tthe subgoal as extra hypotheses,\n\n\t\t\t- matches the conclusion (result type) of [C] against the\n\t\t\t\tcurrent goal and calculates a set of equalities that must\n\t\t\t\thold in order for [C] to be applicable,\n\n\t\t\t- adds these equalities to the context (and, for convenience,\n\t\t\t\trewrites them in the goal), and\n\n\t\t\t- if the equalities are not satisfiable (e.g., they involve\n\t\t\t\tthings like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n\t\ttwo constructors, so two subgoals get generated.  The\n\t\tconclusion (result type) of the constructor ([P \\/ Q]) doesn't\n\t\tplace any restrictions on the form of [P] or [Q], so we don't get\n\t\tany extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n\t\tonly one constructor, so only one subgoal gets generated.  Again,\n\t\tthe conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n\t\tplace any restrictions on the form of [P] or [Q], so we don't get\n\t\tany extra equalities in the context of the subgoal.  The\n\t\tconstructor does have two arguments, though, and these can be seen\n\t\tin the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n\t\tagain only one constructor, so only one subgoal gets generated.\n\t\tNow, though, the form of the [eq_refl] constructor does give us\n\t\tsome extra information: it tells us that the two arguments to [eq]\n\t\tmust be the same!  The [inversion] tactic adds this fact to the\n\t\tcontext. *)\n\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7559797818641714}}
{"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,-deprecated-hint-without-locality\".\nFrom LF Require Export IndProp.\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(** Somewhat confusingly, the Coq standard library hijacks the generic\n    term \"relation\" for this specific instance of the idea. To\n    maintain consistency with the library, we will do the same.  So,\n    henceforth, the Coq identifier [relation] will always refer to a\n    binary relation _on_ some set (between the set and itself),\n    whereas in ordinary mathematical English the word \"relation\" can\n    refer either to this specific concept or the more general concept\n    of a relation between any number of possibly different sets.  The\n    context of the discussion should always make clear which is\n    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 is a partial function. *)\nInductive next_nat : nat -> nat -> Prop :=\n  | nn n : 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\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_function)\n\n    Show that the [total_relation] defined in (an exercise in)\n    [IndProp] is not a partial function. *)\n\n(** Copy the definition of [total_relation] from your [IndProp]\n    here so that this file can be graded on its own.  *)\nInductive total_relation : nat -> nat -> Prop :=\n  | total_rel (n m : nat) : total_relation n m\n.\n\nTheorem total_relation_not_partial_function :\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply (Hc 1 0 1). apply total_rel. apply total_rel.\n  }\n  discriminate Nonsense.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation_partial_function)\n\n    Show that the [empty_relation] defined in (an exercise in)\n    [IndProp] is a partial function. *)\n\n(** Copy the definition of [empty_relation] from your [IndProp]\n    here so that this file can be graded on its own.  *)\nInductive empty_relation : nat -> nat -> Prop :=\n.\n\nTheorem empty_relation_partial_function :\n  partial_function empty_relation.\nProof.\n  intros x y1 y2 rel. inversion rel.\nQed.\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, 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 in Hnm. apply Hnm.\n  - apply le_S in IHHm'o. 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  - apply le_trans with (S m). apply le_S. apply Hnm. apply Hmo.\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, standard, 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 as [H1|m' H1 H'].\n  - apply le_n.\n  - apply le_Sn_le. apply H1.\nQed.\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  intros n contra.\n  induction n. inversion contra. apply le_S_n in contra. apply (IHn 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, standard, optional (le_not_symmetric) *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold not. unfold symmetric. intros contra.\n  assert (Nonsense: 1 <= 0). {\n    apply (contra 0 1). apply le_Sn_le. apply le_n.\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, standard, optional (le_antisymmetric) *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric. intros a b H1 H2.\n  inversion H1.\n  - reflexivity.\n  - exfalso.\n    rewrite <- H0 in H2.\n    assert (Nonsense: S m <= m). {\n      apply le_trans with a.\n      apply H2.\n      apply H.\n    }\n    apply (le_Sn_n m Nonsense).\nQed.\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 n m p H1 H2.\n  assert (H3: S n <= S p). apply le_trans with m. apply H1. apply H2.\n  apply (le_S_n n p H3).\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 X R x y z H1 H2.\n  induction H1 as [y | x y y' Hxy _ IH].\n  - apply H2.\n  - apply rt1n_trans with y. apply Hxy. apply (IH H2).\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 X R x y.\n  split.\n  - intros Hrt.\n    induction Hrt as [x y H | x | x y z _ IH1 _ IH2].\n    + apply rsc_R. apply H.\n    + apply rt1n_refl.\n    + apply rsc_trans with y. apply IH1. apply IH2.\n  - intros Hrt.\n    induction Hrt as [x | x y z H _ IH].\n    + apply rt_refl.\n    + apply rt_trans with y.\n      * apply rt_step. apply H.\n      * apply IH.\nQed.\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7559797806634978}}
{"text": "(* Exercise 5.16 *)\n\nDefinition my_le (n p : nat) :=\n  forall P : nat -> Prop, P n -> (forall q : nat, P q -> P (S q)) -> P p.\n\nLemma my_le_n : forall n : nat, my_le n n.\nProof.\n  unfold my_le.\n  intros n P H H0.\n  assumption.\nQed.\n\nLemma my_le_S : forall n p : nat, my_le n p -> my_le n (S p).\nProof.\n  unfold my_le.\n  intros n p H P H0 H1.\n  apply H1.\n  apply H.\n  assumption.\n  intros q H2.\n  apply H1.\n  assumption.\nQed.\n\nLemma my_le_le : forall n p : nat, my_le n p -> n <= p.\nProof.\n  unfold my_le.\n  intros n p H.\n  pattern p.\n  apply H.\n  apply le_n.\n  intros q H0.\n  apply le_S.\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_16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7558775776948952}}
{"text": "(** * DeltaList : lists of natural numbers with constrained differences *)\n\nRequire Import Arith Omega Wf_nat List.\nImport ListNotations.\nSet Implicit Arguments.\n\n(** * Increasing lists *)\n\n(** [Delta p l] means that consecutives values in the list [l]\n    have differences of at least [p]. *)\n\nInductive Delta (p:nat) : list nat -> Prop :=\n  | Dnil : Delta p []\n  | Done n : Delta p [n]\n  | Dcons n m l : m+p <= n -> Delta p (n::l) -> Delta p (m::n::l).\nHint Constructors Delta.\n\n(** In particular:\n    - [Delta 0 l] means that [l] is increasing\n    - [Delta 1 l] means that [l] is stricly increasing\n    - [Delta 2 l] implies in addition that no consecutive\n      numbers can occur in [l].\n*)\n\nLemma Delta_alt p x l :\n Delta p (x::l) <-> Delta p l /\\ (forall y, In y l -> x+p <= y).\nProof.\n split.\n - revert x. induction l as [|a l IH].\n   + intros x _. split. constructor. inversion 1.\n   + intros x. inversion 1; subst. split; trivial.\n     intros y [Hy|Hy]. now subst.\n     apply (IH a) in Hy; auto. omega.\n - intros (H,H').\n   destruct l; constructor; trivial. apply H'. now left.\nQed.\n\nLemma Delta_inv p x l : Delta p (x::l) -> Delta p l.\nProof.\n rewrite Delta_alt. intuition.\nQed.\n\nLemma Delta_more l p p' : p <= p' -> Delta p' l -> Delta p l.\nProof.\n induction 2; constructor; auto; omega.\nQed.\n\nLemma Delta_21 l : Delta 2 l -> Delta 1 l.\nProof.\n apply Delta_more; auto.\nQed.\n\nLemma Delta_nz p k l : 0<k -> Delta p (k::l) -> ~In 0 (k::l).\nProof.\n intros H H' [X|X]. omega.\n apply Delta_alt in H'. apply H' in X. omega.\nQed.\nHint Resolve Delta_21 Delta_inv Delta_nz.\n\nLemma Delta_low_hd p k k' l :\n k'<=k -> Delta p (k::l) -> Delta p (k'::l).\nProof.\n intros Hk. rewrite !Delta_alt. intros (H,H').\n split; trivial. intros y Hy. apply H' in Hy. omega.\nQed.\n\nLemma Delta_21_S x l : Delta 2 (x::l) -> Delta 1 (S x::l).\nProof.\n  intros D. apply Delta_alt in D. destruct D as (D,D').\n  apply Delta_alt; split; eauto.\n  intros y Hy. apply D' in Hy. omega.\nQed.\nHint Resolve Delta_21_S.\n\nLemma Delta_map p p' f l :\n  (forall x y, x+p <= y -> f x + p' <= f y) ->\n  Delta p l -> Delta p' (map f l).\nProof.\n induction 2; constructor; auto.\nQed.\n\nLemma Delta_pred p l :\n ~In 0 l -> Delta p l -> Delta p (map pred l).\nProof.\n induction 2; simpl in *; constructor; intuition.\nQed.\n\n(* begin hide *)\n(* In stdlib's List.v since 8.5: *)\nLemma in_seq len start n :\n  In n (seq start len) <-> start <= n < start+len.\nProof.\n  revert start. induction len; simpl; intros.\n  - rewrite <- plus_n_O. split;[easy|].\n    intros (H,H'). apply (Lt.lt_irrefl _ (Lt.le_lt_trans _ _ _ H H')).\n  - rewrite IHlen, <- plus_n_Sm; simpl; split.\n    * intros [H|H]; subst; intuition auto with arith.\n    * intros (H,H'). destruct (Lt.le_lt_or_eq _ _ H); intuition.\nQed.\n(* end hide *)\n\nLemma Delta_seq n k : Delta 1 (seq n k).\nProof.\n revert n. induction k.\n - constructor.\n - intros. simpl. apply Delta_alt. split; auto.\n   intros y Hy. rewrite in_seq in Hy. omega.\nQed.\n\nLemma Delta_app p x l l' :\n  Delta p l -> Delta p (x::l') ->\n  (forall y, In y l -> y <= x) -> Delta p (l++l').\nProof.\n induction l.\n - intros _ Hl' H. simpl. eauto.\n - intros Hl Hl' H. simpl. apply Delta_alt. split.\n   + apply IHl; eauto.\n     intros y Hy. apply H. now right.\n   + intros y Hy. rewrite in_app_iff in Hy.\n     destruct Hy as [Hy|Hy].\n     * rewrite Delta_alt in Hl. now apply Hl.\n     * assert (a <= x) by (apply H; now left).\n       apply Delta_alt in Hl'. apply Hl' in Hy. omega.\nQed.\n\nLemma Delta_app_inv p l l' :\n Delta p (l++l') ->\n Delta p l /\\ Delta p l' /\\\n forall x x', In x l -> In x' l' -> x+p <= x'.\nProof.\n induction l; simpl.\n - split. constructor. intuition.\n - rewrite !Delta_alt. intuition.\n   subst. apply H1. rewrite in_app_iff. now right.\nQed.\n\n(** * Decreasing lists *)\n\n(** [DeltaRev p l] is [Delta p (rev l)] :\n    it considers differences in the reversed order,\n    leading to decreasing lists *)\n\nInductive DeltaRev (p:nat) : list nat -> Prop :=\n  | DRnil : DeltaRev p []\n  | DRone n : DeltaRev p [n]\n  | DRcons n m l : n+p <= m -> DeltaRev p (n::l) -> DeltaRev p (m::n::l).\nHint Constructors DeltaRev.\n\nLemma DeltaRev_alt p x l :\n DeltaRev p (x::l) <-> DeltaRev p l /\\ (forall y, In y l -> y+p <= x).\nProof.\n split.\n - revert x. induction l as [|a l IH].\n   + intros x _. split. constructor. inversion 1.\n   + intros x. inversion 1; subst. split; trivial.\n     intros y [Hy|Hy]. now subst.\n     apply (IH a) in Hy; auto. omega.\n - intros (H,H').\n   destruct l; constructor; trivial. apply H'. now left.\nQed.\n\nLemma DeltaRev_app p x l l' :\n  DeltaRev p l -> DeltaRev p (x::l') ->\n  (forall y, In y l -> x <= y) -> DeltaRev p (l++l').\nProof.\n induction l.\n - intros _ Hl' H. simpl. now rewrite DeltaRev_alt in Hl'.\n - intros Hl Hl' H. simpl. apply DeltaRev_alt. split.\n   + apply IHl; auto.\n     * now rewrite DeltaRev_alt in Hl.\n     * intros y Hy. apply H. now right.\n   + intros y Hy. rewrite in_app_iff in Hy.\n     destruct Hy as [Hy|Hy].\n     * rewrite DeltaRev_alt in Hl. now apply Hl.\n     * assert (x <= a) by (apply H; now left).\n       apply DeltaRev_alt in Hl'. apply Hl' in Hy. omega.\nQed.\n\nLemma DeltaRev_app_inv p l l' :\n DeltaRev p (l++l') ->\n DeltaRev p l /\\ DeltaRev p l' /\\\n forall x x', In x l -> In x' l' -> x'+p <= x.\nProof.\n induction l; simpl.\n - split. constructor. intuition.\n - rewrite !DeltaRev_alt. intuition.\n   subst. apply H1. rewrite in_app_iff. now right.\nQed.\n\nLemma Delta_rev p l : Delta p (rev l) <-> DeltaRev p l.\nProof.\n split.\n - rewrite <- (rev_involutive l) at 2.\n   set (l':=rev l); clearbody l'. clear l.\n   induction 1.\n   + constructor.\n   + constructor.\n   + simpl in *.\n     apply DeltaRev_app with n; auto.\n     intros y Hy. apply DeltaRev_app_inv in IHDelta.\n     destruct IHDelta as (_ & _ & IH).\n     specialize (IH y n).\n     rewrite in_app_iff in Hy. simpl in *. intuition.\n - induction 1.\n   + constructor.\n   + constructor.\n   + simpl in *.\n     apply Delta_app with n; auto.\n     intros y Hy. apply Delta_app_inv in IHDeltaRev.\n     destruct IHDeltaRev as (_ & _ & IH).\n     specialize (IH y n).\n     rewrite in_app_iff in Hy. simpl in *. intuition.\nQed.\n\nLemma DeltaRev_rev p l : DeltaRev p (rev l) <-> Delta p l.\nProof.\n now rewrite <- Delta_rev, rev_involutive.\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/DeltaList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.755856444538874}}
{"text": "\n(**\n\n  * Spécification et Validation de Programmes - Examen Février 2015\n\nCet examen est un examen sur machine. \n\n_Durée_ : 3 heures\n\n_Documents_ :  tous documents autorisés\n\n\nL'objectif est de répondre directement dans ce fichier et de\nsoumettre ce dernier sur le site du master (cf. instructions données\nlors de l'examen).   Repérez les mots  \"QUESTION\"  au fil du texte.\n\n_Important_ : le temps de soumission est compris dans les 3 heures,\n toute soumission tardive est comptée comme copie vide.\n\n\nDans les réponses, les [admit]  ou [Admitted]  doivent etre effacés ou commentés sinon aucun point ne sera accordé à la question.   Le sujet est à priori à répondre dans l'ordre\n des questions mais il est possible de laisser un [admit] ou [Admitted] pour passer à la suite\n en supposant la réponse fournie.\n\nLa difficulté relative et ressentie par les enseignants pour chaque question est notée de\nla façon suivante :\n\n  [+]   question facile\n  [++]  question non-triviale mais simple\n  [+++] question demandant un peu plus de réflexion\n  [++++] question difficile et/ou prenant du temps\n\n*)\n\nRequire Import Bool.\nRequire Import Arith.\n\n(**\n\n* Les Ensembles finis en Coq.\n\nL'objectif de cet examen est de proposer une formalisation de la notion d'ensemble fini (typé) dans le logiciel Coq.\n\n*)\n\nSection Ensembles.\n\nVariable Elem : Set.  (*  le type générique des éléménts des ensembles. *)\n\n(**\n\n* (1) Egalité sur les éléments\n\nLa notion d'ensemble est dépendante de la notion d'égalité sur\nleurs éléménts. On fera donc l'hypothèse que l'égalité sur les éléments des ensembles est décidable.\n\n*)\n\nHypothesis Elem_eq_dec: forall a b : Elem, { a = b } + { a <> b }.\n\n(**\n\nVoici quelques définitions et lemmes importants sur cette égalité entre éléments.\n\n*)\n\nDefinition elem_eq (a b : Elem) : bool :=\n  match Elem_eq_dec a b with\n    | left _ => true\n    | right _ => false\n  end.\n\nProposition elem_eq_eq:\n  forall a b : Elem,\n    elem_eq a b = true -> a = b.\nProof.\n  intros a b H.\n  unfold elem_eq in H.\n  destruct (Elem_eq_dec a b) as [Heq | Hneq].\n  + (* cas a = b *)\n    exact Heq.\n  + (* cas a <> b *)\n    inversion H. (* contradiction *)\nQed.\n\n(**\n\n ** QUESTION 1.1 [+] : réflexivité de l'égalité\n\nComplétez la preuve du lemme suivant :\n\n*)\n\nLemma elem_eq_refl:\n  forall a : Elem, elem_eq a a = true.\nProof.\n  intro a.\n  unfold elem_eq.\n  destruct (Elem_eq_dec a a) as [Heq | Hneq].\n  + (* cas a = a *)\n    reflexivity.\n  + (* cas a <> a *)\n    unfold not in Hneq.\n    assert (HFalse: False).\n    {\n      apply Hneq.\n      reflexivity.\n    }    \n    elim HFalse.\nQed.    \n\n(**\n\n ** QUESTION 1.2 [+]\n\nEn déduire une démonstration pour la proposition suivante :\n    \n*)\n\nProposition eq_elem_eq:\n  forall a b : Elem,\n    a = b -> elem_eq a b = true.\nProof.\n  intros a b H.\n  subst.\n  rewrite elem_eq_refl.\n  reflexivity.\nQed.\n\n(**\n\nOn se donne des propositions complémentaires pour la négation.\n\n*)\n\nProposition neq_elem_neq:\n  forall a b : Elem,\n    a <> b -> elem_eq a b = false.\nProof.\n  intros a b Hneq.\n  case_eq (elem_eq a b).\n  - (* cas Htrue *)\n    intro Htrue.\n    assert (Heq: a = b). \n    { apply elem_eq_eq.\n      exact Htrue.\n    }\n    contradiction.\n  - (* cas Hfalse *)\n    reflexivity.\nQed.\n\n\nProposition elem_neq_neq:\n  forall a b : Elem,\n    elem_eq a b = false -> a <> b.\nProof.\n  intros a b Hfalse.\n  unfold not.\n  intro Heq.\n  rewrite Heq in Hfalse.\n  rewrite elem_eq_refl in Hfalse.\n  inversion Hfalse.\nQed.\n\n(** \n\n *  (2) Définition d'ensemble et appartenance\n\nLa notion d'ensemble fini proposée est assez naive et définie par\nle type suivant.\n\n*)\n\nInductive Ens : Set :=\n| vide : Ens\n| elem : Elem -> Ens -> Ens.\n\n(**\n\nOn souhaite définir la notion d'appartenance à un ensemble, basée\n sur la définition précédente.\n\n ** QUESTION 2.1 [+] : appartenance fonctionnelle\n\nLa première définition d'appartenance est un prédicat booléen fonctionnel.\n\nComplétez la définition suivante :\n\n*)\n\nFixpoint appartient (a:Elem) (E:Ens) : bool :=\n  match E with\n    | vide => false\n    | elem e ES => if elem_eq a e then true else appartient a ES\n  end.\n\n\n(**\n\n  ** QUESTION 2.2 [+] : propriété de l'appartenance\n\nDémontrer la propriété suivante (par cas):\n\n*)\n\nProposition appartient_elem:\n  forall a b : Elem, forall E : Ens,\n      appartient a E = true -> appartient a (elem b E) = true.\nProof.\n  intros a b E H.\n  simpl.\n  destruct (elem_eq a b).\n  +reflexivity.\n  +exact H.\n   Qed.\n(**\n \n\nOn donne maintenant une définition alternative à l'aide\nd'un type inductif de nom  Appartient   (avec A majuscule)\net implémentant les règles suivantes :\n\n - règle : app_debut    \n\n    ---------------------------\n      Appartient a (elem a E)\n\n - règle : app_reste\n\n      Appartient a E\n    --------------------------\n      Appartient a (elem b E)\n\n*)\n\nInductive Appartient : Elem -> Ens -> Prop :=\n| app_debut: forall E : Ens, forall a : Elem, Appartient a (elem a E)\n| app_reste: forall E : Ens, forall a b : Elem, Appartient a E \n                                                -> Appartient a (elem b E).\n\n(**  \n\n  ** QUESTION 2.3 [+]\n\n Montrer la proposition suivante :\n\n*)\n\nProposition Appartient_elem:\n  forall a b : Elem, forall E : Ens,\n      Appartient a E -> Appartient a (elem b E).\nProof.\n  intros a b E H.\n  apply app_reste.\n  exact H.\nQed.\n\n(**\n\n  ** QUESTION 2.4 [+++] : Du récursif à l'inductif\n\nMontrer par induction le lemme suivant :\n\n*)\n\nLemma appartient_Appartient:\n  forall a : Elem, forall E : Ens,\n      appartient a E = true -> Appartient a E.\nProof.\n  intros a E.\n  intros H.\n  induction E as [|v ee].\n  +inversion H.\n  +apply Appartient_elem.\n   apply IHee.\n   inversion H.\n   destruct (elem_eq a v).\n  -destruct ee.\n   *simpl.\n    simpl in H.\n\nAdmitted.\n\n(**\n\n  ** QUESTION 2.5 [++] : De l'inductif au récursif \n\nMontrer par induction sur le type inductif Appartient \nle lemme suivant :\n\n\n*)\n\nLemma Appartient_appartient:\n  forall a : Elem, forall E : Ens,\n      Appartient a E -> appartient a E = true.\nProof.\n  intros a E.\n  intros H.\n  induction E as [|v ee].\n  + inversion H.\n  + apply appartient_elem.\n    destruct (appartient a ee).\n    *trivial.\n    *simpl.\nAdmitted.\n\n(**\n\n ** QUESTION 2.6 [++]\n\nEn utilisant les deux lemmes précédents, déduire de la proposition Appartient_elem (avec A majuscule) une preuve alternative de la proposition appartient_elem  (avec a minuscule).\n\n*)\n\nProposition appartient_elem':\n  forall a b : Elem, forall E : Ens,\n      appartient a E = true -> appartient a (elem b E) = true.\nProof.\n  intros a b E.\n  rewrite Appartient_appartient.\n  + intros HT.\n    rewrite Appartient_appartient.\n    exact HT.\n    apply Appartient_elem.\n    apply appartient_Appartient.\n    simpl.\nAdmitted. (* <== REMPLACER le Admitted. *)\n\n(**\n\n  * (3)  Union ensembliste\n\nDans cette partie nous nous intéressons à l'opérateur d'union ensembliste.\n\nNous donnons la définition fonctionnelle suivante :\n\n*)\n\nFixpoint union (E F : Ens) : Ens :=\n  match E with\n    | vide => F\n    | elem a E' => elem a (union E' F)\n  end.\n\n(**\n\n  ** QUESTION 3.1 [++]\n\nDémontrer le lemme suivant :\n\n*)\n\nLemma union_Appartient_l:\n  forall a : Elem, forall E F : Ens,\n      Appartient a E -> Appartient a (union E F).\nProof.\n  intros a E F.\n  intros H.\n  induction E as [|e ee].\n  +simpl.\n   inversion H.\n  +simpl.\n   apply Appartient_elem.\n   destruct (union ee F).\n  -apply IHee.\n   inversion H.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\nLe lemme complémentaire : union_Appartient_r\n\nqui permet de déduire :\n\n    Appartient a (union E F)\n\nà partir de \n\n    Appartient a F\n\nest plus difficile à démontrer, car l'union effectue la récursion\nsur E et non sur F.\n\nNous passons en mode \"calcul\"  (en utilisant la définition fonctionnelle\n de appartient) et nous procédons par étapes.\n\n*)\n\n(**\n\n  ** Question 3.2 [++]\n\nDémontrer le lemme suivant par induction sur E :\n\n*)\n\nProposition union_appartient_elem_r_eq:\n  forall a b : Elem, forall E F : Ens,\n      a = b \n      -> appartient a (union E (elem b F)) = true.\nProof.\n  intros a b E F.\n  intros H.\n  induction E as [|e E'].\n  - apply appartient_elem.\n    destruct F.\n    +simpl.\n     admit.\n    +apply appartient_elem.\n     admit.\n  -simpl.\n   rewrite IHE'.\n   destruct (elem_eq a e).\n   +trivial.\n   +trivial.\nQed.\n\n(**\n\n  ** Question 3.3 [++]\n\nDémontrer le lemme suivant par induction sur E :\n\n*)\n\nProposition union_appartient_elem_r:\n  forall a b : Elem, forall E F : Ens,\n      appartient a (union E F) = true\n      -> appartient a (union E (elem b F)) = true.\nProof.\n  intros a b E F H.\n  induction E as [|e E'].\n  +apply appartient_elem.\n   simpl.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  ** QUESTION 3.4 [+++]\n\nEn utilisant les deux propositions précédentes, démontrer\npar induction sur F la proposition suivante :\n\n*)\n\nProposition union_appartient_r:\n  forall a : Elem, forall E F : Ens,\n      appartient a F = true -> appartient a (union E F) = true.\nProof.\n  intros a E F.\n  induction F as [|f F'].\n  +intros H.\n   inversion H.\n   +\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(** \n\n  ** QUESTION 3.5 [++]\n\nEn déduire le lemme suivant :\n\n*)\n\nLemma union_Appartient_r:\n  forall a : Elem, forall E F : Ens,\n      Appartient a F -> Appartient a (union E F).\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  ** QUESTION 3.6 [++]\n\nFinalement, en déduire le théorème de l'union :\n\n*)\n\nTheorem union_Appartient:\n  forall a : Elem, forall E F : Ens,\n      Appartient a E \\/ Appartient a F\n      -> Appartient a (union E F).\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *) \n\n(**\n\n  * (4) Elimination des doublons\n\nDans cette partie, nous souhaitons éliminer les éléments doublons\ndans les ensembles.\n\n*)\n\n(**\n\n  ** QUESTION 4.1 [+]\n\nDéfinir la fonction retirer telle que (retirer a E)\n élimine toutes les occurrences de l'élément a dans l'ensemble E.\n\n*)\n\nFixpoint retirer (a : Elem) (E : Ens) : Ens :=\n  vide.  (* <== REMPLACER vide PAR UNE DEFINITION RECURSIVE. *)\n\n(**\n\n  ** QUESTION 4.2 [++]\n\nProuver le lemme suivant :\n\n*)\n\nLemma retirer_present:\n  forall a : Elem, forall E : Ens,\n      appartient a (retirer a E) = false.\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  ** QUESTION 4.3 [++]\n\nDémontrer le lemme suivant :\n\n*)\n\nLemma Appartient_retirer_elem:\n  forall a b : Elem, forall E : Ens,\n      b <> a -> Appartient a E ->  Appartient a (retirer b E).\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  ** QUESTION 4.4 [+]\n\nDonner une définition de la fonction sans_doublons\ntelle que (sans_doublons E) retire tous les éléments répétés\n dans E.\n\n*)\n\nFixpoint sans_doublons (E : Ens) : Ens :=\n  vide.  (* <== REMPLACER vide PAR UNE DEFINITION RECURSIVE. *)\n\n  \n(**\n\n  ** QUESTION 4.5 [+++]\n\nEn déduire le théorème suivant :\n\n*)\n\nTheorem Appartient_sans_doublons:\n  forall a : Elem, forall E : Ens,\n      Appartient a E -> Appartient a (sans_doublons E).\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  * (5) Différence ensembliste\n\nDans cette dernière partie on souhaite formaliser l'opérateur de\n différence ensembliste.\n\n*)\n\n(**\n\n  ** Question 5.1 [++]\n\nDéfinir la fonction difference retournant la\ndifférence entre deux ensembles.\n\n*)\n\nFixpoint difference (E1 : Ens) (E2 : Ens) : Ens :=\n  vide.  (* <== REMPLACER vide PAR UNE DEFINITION RECURSIVE. *)\n\n(**\n\nNotre objectif est de montrer le théorème suivant :\n\nTheorem difference_Appartient:\n  forall e : Elem, forall E2 E1 : Ens,\n      Appartient e E2\n      -> ~ (Appartient e (difference E1 E2)).\n\n\nCependant, la preuve est non-triviale et nous allons\nréaliser les étapes nécessaires en passant à la fonction\n de calcul appartient (avec a minuscule).\n\n*)\n\n(**\n\n ** Question 5.2 [+++]\n\nCompléter la preuve du Lemme suivant :\n\n*)\n\nLemma nappartient_retirer_elem:\n  forall a b : Elem, forall E : Ens,\n      b <> a -> appartient a E = false ->  appartient a (retirer b E) = false.\nProof.\nAdmitted. (* <== RETIRER LE Admitted. *)\n  (*  <=== DECOMMENTER SINON CELA NE PASSE PAS \n  intros a b E Hneq Happ.\n  induction E as [|e E'].\n  - (* cas E = vide *)\n    simpl.\n    reflexivity.\n  - (* cas E = (elem e E') *)\n    simpl.\n    case_eq (elem_eq b e).\n    + (* cas b = e vrai *)\n      intro Htrue.\n      apply IHE'.\n      admit. (* <== REMPLACER LE admit *)\n      (* etc ... *) \n    + (* cas b = e faux *)\n      intro Hfalse.\n      admit. (* <== REMPLACER LE admit *)\n      (* etc ... *)\nQed. DECOMMENTER ===> *)\n\n(**\n\n ** Question 5.3 [+++]\n\nCompléter la preuve du Lemme suivant :\n\n*)\n\nLemma difference_appartient_aux:\n  forall e : Elem, forall E2 E1: Ens,\n      appartient e E1 = false\n      -> appartient e (difference E1 E2) = false.\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n ** Question 5.4 [+++]\n\nEn déduire le lemme ci-dessous :\n\n*)\n\nLemma difference_appartient:\n  forall e : Elem, forall E2 E1 : Ens,\n    appartient e E2 = true\n    -> appartient e (difference E1 E2) = false.\nProof.\nAdmitted. (* <== REMPLACER LE Admitted. *)\n\n(**\n\n  ** Question 5.5 [++]\n\nEn déduire notre théorème principal.\n\n*)\n\nTheorem difference_Appartient:\n  forall e : Elem, forall E2 E1 : Ens,\n      Appartient e E2\n      -> ~ (Appartient e (difference E1 E2)).\nProof.\nAdmitted. (* <== REMPLACER LE Admitted *)\n  \n(**\n\n  * (6) Intersection (réponse libre)  [+++]\n\nDans cette dernière partie on souhaite formaliser l'opérateur\n d'intersection entre deux ensembles.\n\nEn vous inspirant de la partie (3), proposer une formalisation\npermettant finalement de démontrer le théorème suivant :\n\n*)\n\n(* A DECOMMENTER  ==>\n\nTheorem intersection_Appartient:\n  forall a : Elem, forall E F : Ens,\n      Appartient a E /\\ Appartient a F\n      -> Appartient a (intersection E F).\n\n*)\n\n", "meta": {"author": "ebtaleb", "repo": "SVP", "sha": "cac36c82a07248ccfc078207e43678b5f5b19e3d", "save_path": "github-repos/coq/ebtaleb-SVP", "path": "github-repos/coq/ebtaleb-SVP/SVP-cac36c82a07248ccfc078207e43678b5f5b19e3d/exam-fev2015.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8872046011730964, "lm_q1q2_score": 0.7558564425536446}}
{"text": "\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intro n. reflexivity. Qed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem plus_id_example : forall n m:nat,\n\tn = m -> n + n = m + m.\nProof.\n\tintros n.\n\tintros m.\n\tintros N1.\n\trewrite -> N1.\n\treflexivity. Qed.\n\n\nTheorem plus_id_exercise : forall n m o : nat,\n\tn = m -> m = o -> n + m = m + o.\nProof.\n\tintros n m o.\n\tintros M N.\n\trewrite M.\n\trewrite N.\n\treflexivity. Qed.\n\n\nTheorem mult_0_plus : forall n m : nat,\n  \t(0 + n) * m = n * m.\nProof.\n  \tintros n m.\n\trewrite -> plus_O_n.\n\treflexivity. Qed.\n\n\n\nTheorem mult_S_1 : forall n m : nat,\n\tm = S n ->\n\tm * (1 + n) = m * m.\nProof.\n  \tintros n m.\n  \tintros H.\n  \trewrite -> H.\n  \treflexivity. Qed.\n\n\n\nFixpoint beq_nat (n m : nat) : bool :=\n\tmatch n with\n\t\t| O => \t\tmatch m with\n\t\t\t\t\t\t| O => true\n\t\t\t\t\t\t| S m' => false\n\t\t\t\t\tend\n\t\t| S n' => \tmatch m with\n            \t\t\t| O => false\n\t\t\t\t\t\t| S m' => beq_nat n' m'\n\t\t\t\t\tend\n\tend.\n\nEval compute in (beq_nat 0 0).\nEval compute in (beq_nat 0 1).\n\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n\tbeq_nat (n + 1) 0 = false.\nProof.\n\tintros n.\n  \tdestruct n as [| n'].\n    reflexivity.\n    reflexivity.\nQed.\n\n\n\n\n\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n\tbeq_nat 0 (n + 1) = false.\nProof.\n\tintros n.\n\tdestruct n as [ | n'].\n\treflexivity.\n\treflexivity.\nQed.\n\n\nDefinition andb (a b : bool) : bool :=\n\tmatch a with\n\t\t| true => b\n\t\t| false => false\n\tend.\n\n\nDefinition orb (a b : bool) : bool :=\n\tmatch a with\n\t\t| false => b\n\t\t| true => true\n\tend.\n\n\n\nTheorem andb_false : forall b c : bool,\n\tc = false ->\n\t(andb b c) = false.\nProof.\n\tintros b c.\n\tintros H.\n\trewrite -> H.\n\tdestruct b.\n\treflexivity. reflexivity.\nQed.\n\nTheorem andb_true : forall b c : bool,\n\tc = true ->\n\t(andb b c) = b.\nProof.\n\tintros b c.\n\tintros H.\n\trewrite -> H.\n\tdestruct b.\n\treflexivity. reflexivity.\nQed.\n\n\nTheorem orb_true : forall b c : bool,\n\tc = true ->\n\t(orb b c) = true.\nProof.\n\tintros b c.\n\tintros H.\n\trewrite -> H.\n\tdestruct b.\n\treflexivity. reflexivity.\nQed.\n\nTheorem orb_false : forall b c : bool,\n\tc = false ->\n\t(orb b c) = b.\nProof.\n\tintros b c.\n\tintros H.\n\trewrite -> H.\n\tdestruct b.\n\treflexivity. reflexivity.\nQed.\n\n\n\nTheorem andb_eq_true : forall b : bool,\n\t(andb b true) = (orb b true) ->\n\tb = true.\nProof.\n\tintros b.\n\tdestruct b.\n\t\treflexivity.\n\t\tsimpl.\n\t\tintros H.\n\t\trewrite -> H.\n\t\treflexivity.\nQed.\n\n\n\nTheorem andb_eq_c_true : forall b c : bool,\n\tc = true ->\n\t(andb b c) = (orb b c) ->\n\tb = true.\nProof.\n\tintros b c.\n\tsimpl.\n\tintros H.\n\trewrite -> H.\n\tdestruct b.\n\t\t\n\t\treflexivity.\n\n\t\tsimpl.\n\t\tintros L.\n\t\trewrite -> L.\n\t\treflexivity.\nQed.\n\n\n\nTheorem andb_eq_orb :  forall (b c : bool),\n  \t(andb b c = orb b c) ->\n  \tb = c.\nProof.\n\tintros b c.\n\tdestruct b.\n\tdestruct c.\n\t\t(* b - true, c - true *)\n\t\treflexivity.\n\t\t\n\t\t(* b - true, c - false *)\n\t\tsimpl.\n\t\tintro H.\n\t\trewrite -> H.\n\t\treflexivity.\n\t\t\n\t\t(* b - false, c - true *)\n\t\tsimpl.\n\t\tintro H.\n\t\trewrite -> H.\n\t\treflexivity.\nQed.\n\n\n\n\n\n\nTheorem identity_fn_applied_twice : forall (f : bool -> bool), \n\t(forall (x : bool), f x = x) ->\n  \tforall (b : bool), f (f b) = b.\nProof.\n\tintros f.\n\tintros H.\n\tintros b.\n\n\t\trewrite -> H.\n\t\trewrite -> H.\n\t\treflexivity.\n\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "middlefeng", "repo": "SoftwareFoundationsExercise", "sha": "a4033ac6eb2936117ddd1a7ecde6012261bd3ab6", "save_path": "github-repos/coq/middlefeng-SoftwareFoundationsExercise", "path": "github-repos/coq/middlefeng-SoftwareFoundationsExercise/SoftwareFoundationsExercise-a4033ac6eb2936117ddd1a7ecde6012261bd3ab6/Ch1_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7558564394571526}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition predn n :=\n  if n is p.+1 then p else n.\n\nCompute predn 3.\nEval compute in predn.\n\nDefinition same_bool b1 b2 :=\n  match b1, b2 with\n  | true, true => true\n  | false, false => true\n  | _, _ => false\n  end.\n\nFixpoint eqn m n :=\n  match m, n with\n  | O, O => true\n  | p.+1, q.+1 => eqn p q\n  | _, _ => false\n  end.\n\nNotation \"x == y\" := (eqn x y).\n\nEval compute in subn.\n\nAbout cons.\nCheck cons 2 nil.\n\nEval compute in [seq i.+1 | i <- [:: 1; 2; 3; 4]].\n\nEval compute in (true, false).1.\n\nRecord point : Type :=\n  Point { x : nat; y : nat; z : nat }.\n\nSection iterators.\n\n  Variables (T : Type) (A : Type).\n  Variables (f : T -> A -> A).\n\n  Implicit Type x : T.\n\n  Fixpoint iter n op x :=\n    if n is p.+1 then op (iter p op x) else x.\n\n  Fixpoint foldr a s :=\n    if s is y :: ys then f y (foldr a ys) else a.\n\n  Variable init : A.\n  Variables x1 x2 : T.\n  Eval compute in foldr init [:: x1; x2].\n  \nEnd iterators.\n\nAbout foldr.\n\nEval compute in iter 5 predn 7.\n\nFixpoint add n m :=\n  if n is p.+1 then add p m.+1 else m.\n\nVariable n : nat.\nEval simpl in (add n.+1 7).-1.\nEval simpl in (addn n.+1 7).-1.\n\nEval compute in iota 1 10.\nEval compute in \\sum_(1 <= i < 5)(i * 2 - 1).\n\nLocate \"<=\".\n\n(* Excercises *)\n\nRecord triple (A B C : Type) :=\n  mk_triple { fst : A; snd : B; thrd : C }.\n\nNotation \"( a , b , c )\" := (mk_triple a b c).\nNotation \"p .1T\" := (fst p) (at level 2).\nNotation \"p .2T\" := (snd p) (at level 2).\nNotation \"p .3T\" := (thrd p) (at level 2).\nEval compute in (4, 5, 8).1T.\nEval compute in (true, false, 1).2T.\nEval compute in (2, true, false).3T.\n\nDefinition add_iter (n m : nat) :=\n  iter n S m.\n\nEval compute in add_iter 5 9.\n\nDefinition mult_iter (n m : nat) :=\n  iter n (add_iter m) 0.\n\nEval compute in mult_iter 5 8.\n\nFixpoint nth {A : Type} (default : A) (xs : seq A) (n : nat) : A :=\n  match n, xs with\n  | O, (x :: xs') => x\n  | m, (x :: xs') => nth default xs' n.-1\n  | _, _ => default \n  end.\n\nEval compute in nth 99 [:: 3; 7; 11; 22] 2.\nEval compute in nth 99 [:: 3; 7; 11; 22] 7.\n\nDefinition rev {A : Type} (xs : seq A) :=\n  if xs is x :: xs' then (rev xs') ++ [:: x] else nil.\n\nEval compute in rev [:: 1; 2; 3; 4; 5].\n\nEval cbv delta in [:: 1] ++ [:: 1].\n\nDefinition flatten {A : Type} (xs : seq (seq A)) : seq A :=\n  foldr cat nil xs.\n\nEval compute in flatten [:: [:: 1; 2; 3]; [:: 4; 5] ].\n", "meta": {"author": "Neujaskre", "repo": "learn-you-a-coq", "sha": "beade8371e4943f504ea6465a8260c6b252a3ce6", "save_path": "github-repos/coq/Neujaskre-learn-you-a-coq", "path": "github-repos/coq/Neujaskre-learn-you-a-coq/learn-you-a-coq-beade8371e4943f504ea6465a8260c6b252a3ce6/ssrfl/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699185, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7558564302463874}}
{"text": "Require Export study02.\n\nModule study03.\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\nCheck nil. Check cons.\nCheck (cons nat 2 (cons nat 1 (nil nat))).\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.\nExample test_length1:length nat\n (cons nat 2 (cons nat 1 (nil nat)))=2.\nProof. reflexivity. Qed.\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. 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 X h (app X t l2)\n  end.\nDefinition snoc (X:Type) (l:list X) (v:X) : (list X) :=\n  app X l (cons X v (nil X)).\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.\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.\nExample test_rev2:\n  rev bool (nil bool) = nil bool.\nProof. reflexivity. Qed.\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.\nCheck app. Check app'.\nFixpoint length' (X:Type) (l:list X) : nat :=\n  match l with\n  | nil _ => 0\n  | cons _ h t => S (length' _ t)\n  end.\nDefinition list123' := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\nInductive list' (A:Set) : Set :=(* listの型はSet -> Set *)\n  | nil' : list' A\n  | cons' : A -> list' A -> list' A.\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\nCheck @nil.\n\nDefinition id {A:Type} (x:A) : A := x.\nDefinition compose {A B C} (g:B->C)(f:A->B):=\n  fun x => g (f x).\nGoal forall A, compose id id = id (A := A).\nProof. auto. Qed.\n\nSet Implicit Arguments.\nAxiom eq0_le0 : forall (n:nat)(x:n=0),n<=0.\nPrint Implicit eq0_le0.\nAxiom eq0_le0' : forall (n:nat){x:n=0},n<=0.\nPrint Implicit eq0_le0'.\n\nEnd study03.\nModule ImplicitTest.\nRequire Import Ascii String.\n\nInductive llist (X:Type) : Type :=\n  | lnil : llist X\n  | lcons : X -> llist X -> llist X.\nDefinition llist' {X:Type}:Type:= llist X.\nDefinition lnil' {X:Type}:llist X:= lnil X.\nDefinition lcons' {X:Type}:X->llist X->llist X:= lcons X.\nCheck (lcons' 2 (lcons' 1 (lnil' ))).\nCheck (lcons' \"a\" (lcons' \"b\" (lnil' ))).\n(*Check (lcons 2 (lcons \"c\" (lnil ))).*)\n\nFixpoint lapp (X:Type) (l1 l2:llist X) : (llist X) :=\n  match l1 with\n  | lnil _ => l2\n  | lcons _ h t => lcons X h (lapp X t l2)\n  end.\nDefinition lapp' {X:Type} (l1 l2:llist X):(llist X):=lapp X l1 l2.\nFixpoint llength (X:Type) (l:llist X) : nat :=\n  match l with\n  | lnil _ => 0\n  | lcons _ h t => S (llength X t)\n  end.\nDefinition llength' {X:Type} (l:llist X):nat:=llength X l.\nDefinition lsnoc' {X:Type} (l:llist X) (v:X) : (llist X) :=\n  lapp' l (lcons' v (lnil' )).\n(*Definition lsnoc' {X:Type} (l:llist X)(v:X):(llist X):=lsnoc X l v.*)\nFixpoint lrev' {X:Type} (l:llist X) : llist X :=\n  match l with\n  | lnil _  => lnil'\n  | lcons _ h t => lsnoc' (lrev' t) h\n  end.\n(*Definition lrev' {X:Type} (l:llist X) : llist X := lrev X l.*)\nDefinition list123'' := lcons' 1 (lcons' 2 (lcons' 3 lnil')).\nCompute (llength' list123'').\nCheck lnil'. Check @lnil'.\nNotation \"x :: y\" := (lcons' x y) (at level 60, right associativity).\nNotation \"[ ]\" := lnil'.\nNotation \"[ x , .. , y ]\" := (lcons' x .. (lcons' y []) ..).\nNotation \"x ++ y\" := (lapp' x y) (at level 60, right associativity).\n\nDefinition list123''' := [1, 2, 3].\nCheck list123'''.\n\nFixpoint lrepeat (X:Type)(n:X)(count:nat):llist X:=\n  match count with\n  | 0 => lnil X\n  | S count' => lcons X n (lrepeat X n count')\n  end.\nDefinition lrepeat' {X:Type}(n:X)(count:nat):llist X:=\n  lrepeat X n count.\nExample test_lrepeat1:\n  lrepeat' true 2 = lcons' true (lcons' true lnil').\nProof. reflexivity. Qed.\n\nTheorem lnil_app : forall X:Type, forall l:llist X,\n  lapp' [] l = l.\nProof. reflexivity. Qed.\n\nTheorem lrev_lsnoc : forall X:Type, forall v:X, forall s:llist X,\n  lrev' (lsnoc' s v) = v :: (lrev' s).\nProof. induction s. reflexivity. simpl. \nassert (H1:s++[v]=lsnoc' s v). reflexivity.\nrewrite H1. rewrite IHs. reflexivity. Qed.\n\nTheorem lapp_ass : forall X:Type, forall l1 l2 l3:llist X,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof. induction l1. reflexivity. simpl. intros l2 l3. \nrewrite IHl1. reflexivity. Qed.\nTheorem lsnoc_with_lapp : forall X:Type, forall l1 l2:llist X,\n  forall v:X,  lsnoc' (l1++l2) v = l1 ++ (lsnoc' l2 v).\nProof. intros X l1 l2 v. unfold lsnoc'. rewrite lapp_ass.\nreflexivity. Qed.\n\nInductive lprod (X Y:Type) : Type :=\n  lpair : X -> Y -> lprod X Y. \nDefinition lprod'{X Y:Type}:Type:=lprod X Y.\nDefinition lpair'{X Y:Type}:X -> Y -> lprod X Y:=lpair X Y.\nNotation \"( x , y )\" := (lpair' x y).\nNotation \"X ^ Y\" := (lprod X Y) : type_scope.\n(*type_scope というアノテーションによって，型を解析する際に用いる省略形\nであることを明示し，乗法の演算子との衝突を回避する．嘘*)\nLocate \"*\". Locate \"^\".\nCheck nat ^ nat.\nCheck (2,3).\nDefinition lfst' {X Y:Type} (p:X ^ Y):X:=\n  match p with (lpair _ _ x y) => x end.\nDefinition lsnd' {X Y:Type} (p:X ^ Y):Y:=\n  match p with (lpair _ _ x y) => y end.\nCompute lfst' (2,3).\nFixpoint lcombine' {X Y:Type}(lx:llist X)(ly:llist Y)\n  : llist' :=\n  match lx, ly with\n  | lnil _ , _  => []\n  | _, lnil _ => []\n  | lcons _ x tx, lcons _ y ty => (x,y)::(lcombine' tx ty)\n  end.\n(*Fixpoint lcombine'' (lx:llist')(ly:llist')\n  : llist' :=\n  match lx, ly with\n  | [] , _  => []\n  | _, [] => []\n  | x::tx, y::ty => (x,y)::(lcombine' tx ty)\n  end.*)\nCheck @lcombine'.\nCompute (lcombine' [1,2][false,false,true,true]).\nCompute [(1,false),(2,false)].\nExample test_lcombine:lcombine' \n  [1,2][false,false,true,true]=[(1,false),(2,false)].\nProof. reflexivity. Qed.\nFixpoint lsplit'{X Y:Type} (l:llist (X^Y)) : (llist X) ^ (llist Y) :=\n  match l with\n  | lnil _ => ([],[])\n  | lcons _ (lpair _ _ x y) t => (x::lfst'(lsplit' t),y::lsnd'(lsplit' t))\n  end.\nExample test_lsplit:\n  lsplit' [(1,false),(2,false)] = ([1,2],[false,false]).\nProof. reflexivity. Qed.\n\nInductive loption (X:Type) : Type :=\n  | lSome : X -> loption X\n  | lNone : loption X.\nDefinition loption' {X:Type} : Type := loption X.\nDefinition lSome' {X:Type} : X -> loption' := lSome X.\nDefinition lNone' {X:Type} : loption' := lNone X.\nFixpoint lindex' {X:Type} (n:nat) (l:llist X) : loption' :=\n  match l with\n  | lnil _ => lNone'\n  | lcons _ a l' => if beq_nat n 0 then lSome' a else lindex' (pred n) l'\n  end.\nExample test_lindex1 : lindex' 0 [4,5,6,7] = lSome' 4.\nProof. reflexivity. Qed.\nExample test_lindex2 : lindex' 1 [[1],[2]] = lSome' [2].\nProof. reflexivity. Qed.\nExample test_lindex3 : lindex' 2 [true] = lNone'.\nProof. reflexivity. Qed.\nDefinition lhd_opt' {X:Type} (l:llist X) : loption' :=\n  lindex' 0 l.\nCheck @lhd_opt'.\nExample test_lhd_opt1 : lhd_opt' [1,2] = lSome' 1.\nProof. reflexivity. Qed.\nExample test_lhd_opt2 : lhd_opt' [[1],[2]] = lSome' [1].\nProof. reflexivity. Qed.\n\n\n\nModule study03'.\n\nDefinition doit3times {X:Type} (f:X->X)(n:X) : X :=\n  f (f (f n)).\nCheck @doit3times.\nDefinition minustwo (n :nat) : nat :=  \n  match n with\n  | O => O\n  | S O => O\n  | S (S (n')) => n'\n  end.\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\nCheck plus.\nDefinition plus3:= plus 3.\nCheck plus3.\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.\nDefinition prod_curry {X Y Z:Type}\n  (f:X^Y->Z)(x:X)(y:Y):Z:=f (x,y).\nDefinition prod_uncurry {X Y Z:Type}\n  (f:X->Y->Z)(p:X^Y):Z:=f (lfst' p) (lsnd' p).\nCheck @prod_curry.\nCheck @prod_uncurry.\n(*Theorem uncurry_curry_mine:forall (X Y Z:Type) (f:X^Y->Z),\n  prod_uncurry(prod_curry f)=f.\nProof. intros X Y Z f. unfold prod_curry. unfold prod_uncurry.*)\nTheorem uncurry_curry : forall (X Y Z:Type) (f:X->Y->Z) (x:X) (y:Y),\n  prod_curry(prod_uncurry f) x y = f x y.\nProof. intros X Y Z f x y. unfold prod_curry. unfold prod_uncurry.\nreflexivity. Qed.\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. unfold prod_uncurry. unfold prod_curry. intros X Y Z f p.\ndestruct p. reflexivity. Qed.\n\nFixpoint filter {X:Type} (test:X->bool)(l:llist X) : llist' :=\n  match l with\n  | lnil _ => []\n  | lcons _ h t => \n    if test h then h::(filter test t)\n    else filter test t\n  end.\nExample test_filter1:filter evenb [1,2,3,4]=[2,4].\nProof. reflexivity. Qed.\nDefinition length_is_1 {X:Type} (l:llist X) : bool :=\n  beq_nat (llength' 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.\nDefinition countoddmembers' (l:llist nat) : nat :=\n  llength' (filter NatList.oddb 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' lnil' = 0.\nProof. reflexivity. Qed.\nExample test_anon_fun' : doit3times (fun n => n*n) 2 = 256.\nProof. reflexivity. Qed.\nExample test_filter2':\n    filter (fun l => beq_nat (llength' l) 1)\n           [ [1, 2], [3], [4], [5,6,7], [], [8] ]\n  = [ [3], [4], [8] ].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l:llist nat) : llist nat :=\n  filter (fun n => andb (NatList.evenb n) (ble_nat 8 n)) l.\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.\nDefinition partition {X:Type} (test:X->bool) (l:llist X)\n  : (llist X) ^ (llist X) :=\n  ((filter test l) , (filter (fun x => negb (test x)) l)).\nExample test_partition1: partition NatList.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:llist X) : llist' :=\n  match l with\n  | lnil _ => []\n  | lcons _ h t => (f h) :: (map f t)\n  end.\nExample test_map1: map (plus 3) [2,0,2] = [5,3,5].\nProof. reflexivity. Qed.\nExample test_map2: map oddb [2,1,2,5] = [false,true,false,true].\nProof. reflexivity. Qed.\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.\nTheorem lsnoc_app:forall (X:Type) (l:llist X) (x:X),\n  lsnoc' l x = l ++ [x].\nProof. reflexivity. Qed.\nTheorem map_app1:forall (X Y:Type) (f:X->Y) (l:llist X) (x:X),\n  map f (l++[x]) = (map f l) ++ [f x].\nProof. induction l. reflexivity. intros x0. simpl.\nrewrite IHl. reflexivity. Qed.\nTheorem map_rev:forall (X Y:Type)(f:X->Y)(l:llist X),\n  map f (lrev' l) = lrev' (map f l).\nProof. induction l. reflexivity. simpl.\nrewrite <- IHl. rewrite lsnoc_app. rewrite lsnoc_app.\nrewrite map_app1. reflexivity. Qed.\nFixpoint flat_map {X Y:Type} (f:X->llist Y)(l:llist X)\n  :(llist Y):=\n  match l with\n  | lnil _ => []\n  | lcons _ h t => \n    (f h) ++ (flat_map f t)\n  end.\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.\nDefinition loption_map {X Y:Type} (f:X->Y)\n  (xo:loption X) : loption Y :=\n  match xo with\n  | lNone _ => lNone'\n  | lSome _ x => lSome' (f x)\n  end.\n\nFixpoint fold {X Y:Type} (f:X->Y->Y)(l:llist X)(b:Y):Y:=\n  match l with\n  | lnil _ => b\n  | lcons _ h t => f h (fold f t b)\n  end.\nCheck (fold plus).\nEval simpl in (fold plus [1,2,3,4] 0).\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 lapp' [[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.\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\nDefinition override {X:Type}(f:nat->X)(k:nat)(x:X)\n  : nat->X :=\n  fun (k':nat)=>if beq_nat k k' then x else f k'.\nDefinition fmostlytrue:=override (override ftrue 1 false)\n  3 false.\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\nProof. reflexivity. Qed.\nTheorem unfold_example:forall m n,\n  3+n=m->plus3 n+1=m+1.\nProof. intros m n H. simpl. rewrite <- H.\nreflexivity. Qed.\nTheorem override_eq:forall {X:Type} x k(f:nat->X),\n  (override f k x) k = x.\nProof. intros X x k f. unfold override.\nrewrite beq_refl. reflexivity. Qed.\nTheorem override_neq : forall {X:Type}\n  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. intros X x1 x2 k1 k2 f H1 H2.\nunfold override. rewrite H2. rewrite H1.\nreflexivity. Qed.\n\nTheorem eq_add_S:forall (n m:nat), S n=S m->n=m.\nProof. intros n m eq. inversion eq. reflexivity.\nQed.\nTheorem silly4:forall (n m:nat),[n]=[m]->n=m.\nProof. intros n m eq. inversion eq. reflexivity.\nQed.\nTheorem silly5:forall (n m o:nat),\n  [n,m]=[o,o]->[n]=[m].\nProof. intros n m o eq. inversion eq.\nreflexivity. Qed.\nExample sillyex1 : forall (X : Type) (x y z : X)\n (l j : llist X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof. intros X x y z l j H1 H2.\ninversion H1. inversion H2.\nrewrite H0. reflexivity. Qed.\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof. intros n H. inversion H. Qed.\nTheorem silly7 : forall (n m : nat),\n     false = true -> [n] = [m].\nProof. intros n m H. inversion H. Qed.\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : llist 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\nLemma eq_remove_S:forall n m, n=m->S n=S m.\nProof. intros n m H. inversion H. reflexivity. Qed.\nTheorem beq_nat_eq:forall n m,\n  true=beq_nat n m->n=m.\nProof. induction n. induction m. reflexivity.\nsimpl. intros H1. inversion H1. induction m.\nsimpl. intros H2. inversion H2. simpl.\nintros H3. apply eq_remove_S. apply IHn.\napply H3. Qed.\nTheorem beq_nat_eq':forall m n,\n  beq_nat n m = true -> n = m.\nProof. intros m. induction m. destruct n.\nreflexivity. simpl. intros H. inversion H.\ndestruct n. simpl. intros H. inversion H.\nsimpl. intros H. apply eq_remove_S.\napply IHm. apply H. Qed.\nTheorem length_snoc':forall (X:Type)(v:X)\n  (l:llist X)(n:nat),\n  llength' l = n -> llength' (lsnoc' l v) = S n.\nProof. induction l. simpl. intros n H. inversion H.\nreflexivity. simpl. intros n' H. apply eq_remove_S.\ninduction n'. inversion H.\nassert (H1:l++[v]=lsnoc' l v). reflexivity.\napply IHl. inversion H. reflexivity. Qed.\nTheorem length_snoc'':forall (X:Type)(v:X)\n  (l:llist X)(n:nat),\n  llength' l = n -> llength' (lsnoc' l v) = S n.\nProof. intros X v l. induction l. intros n eq.\nrewrite <- eq. reflexivity. intros n eq.\nsimpl. destruct n. inversion eq.\napply eq_remove_S. apply IHl. inversion eq.\nreflexivity. Qed.\nTheorem beq_nat_0_l:forall n,\n  true=beq_nat 0 n -> 0 = n.\nProof. induction n. reflexivity.\nsimpl. intros H. inversion H. Qed.\nTheorem beq_nat_0_r:forall n,\n  true=beq_nat n 0  -> 0 = n.\nProof. induction n. reflexivity.\nsimpl. intros H. inversion H. Qed.\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof. induction n. simpl. intros m H.\ndestruct m. reflexivity. inversion H.\ndestruct m. simpl. intros H. inversion H.\nsimpl. intros H. apply eq_remove_S. \napply IHn. inversion H. reflexivity. Qed.\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. intros n m b H. simpl in H.\napply H. Qed.\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 H1 H2. symmetry in H2. apply H1 in H2.\nsymmetry in H2. apply H2. Qed.\nTheorem plus_n_n_injection : forall n m,\n  n+n=m+m->n=m.\nProof. induction n. simpl. destruct m. reflexivity.\nsimpl. intros H. inversion H. induction m as [|m'].\nsimpl. intros H. inversion H. intros H.\napply eq_remove_S. simpl in H. inversion H. \nrewrite plus_comm in H1. symmetry in H1. \n rewrite plus_comm in H1. simpl in H1.\ninversion H1. symmetry in H2. apply IHn.\napply H2. Qed.\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.\nTheorem sillyfun_false:forall (n:nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n  reflexivity. destruct (beq_nat n 5).\n  reflexivity. reflexivity. \nQed.\nTheorem override_shadow:forall {X:Type} x1 x2 k1 k2\n  (f:nat->X),\n  (override (override f k1 x2) k1 x1) k2\n  = (override f k1 x1) k2.\nProof.\n  intros X x1 x2 k1 k2 f.\n  unfold override.\n  destruct (beq_nat k1 k2).\n  reflexivity. reflexivity.\nQed.\nCheck @lsplit'.\nTheorem lcombine_lsplit:forall (X Y:Type)(p:llist (X^Y)),\n  lcombine' (lfst' (lsplit' p)) (lsnd' (lsplit' p)) = p.\nProof.\n  intros X Y p. induction p.\n  reflexivity. destruct x. simpl.\n  rewrite IHp. reflexivity.\nQed.\nDefinition beq_lnil' {X:Type} (l:llist X) : bool :=\n  match l with\n  | lnil _ => true\n  | lcons _ _ _ => false\n  end.\nTheorem lsplit_lcombine:forall (X Y:Type)(x:llist X)(y:llist Y),\n  llength' x = llength' y -> \n    lsplit' (lcombine' x y) = (x,y).\nProof.\n  induction x. induction y. reflexivity.\n  simpl. intros H. inversion H.\n  induction y. simpl. intros H. inversion H.\n  simpl. intros H. rewrite IHx. reflexivity.\n  inversion H. 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.\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  destruct e3. apply beq_nat_eq in Heqe3.\n  rewrite Heqe3. reflexivity.\n  remember (beq_nat n 5) as e5. destruct e5.\n  apply beq_nat_eq in Heqe5.\n  rewrite Heqe5. reflexivity.\n  inversion eq. \nQed.\nTheorem override_same:forall {X:Type} x1 k1 k2\n  (f:nat->X), f k1 = x1 -> (override f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f eq.\n  remember (beq_nat k1 k2) as keq.\n  destruct keq. apply beq_nat_eq in Heqkeq.\n  rewrite Heqkeq. unfold override.\n  rewrite beq_refl. rewrite <- Heqkeq.\n  symmetry in eq. apply eq.\n  unfold override. rewrite <- Heqkeq.\n  reflexivity.\nQed.\nTheorem filter_exercise:forall (X:Type)(test:X->bool)\n  (x:X)(l lf:llist X),\n  filter test l = x :: lf -> test x = true.\nProof.\n  induction l. intros lf H. inversion H.\n  remember (test x0) as x0test.\n  destruct x0test. simpl.\n  rewrite <- Heqx0test. intros lf H.\n  inversion H. rewrite <- H1. rewrite Heqx0test.\n  reflexivity. simpl. rewrite <- Heqx0test.\n  apply IHl.\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 H1 H2. rewrite H1. rewrite H2. reflexivity.\nQed.\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 H1 H2.\n  apply trans_eq with (m:=[c,d]).\n  apply H1. apply H2.\nQed.\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.\n  apply eq2. apply eq1.\nQed.\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  intros n m p eq1 eq2.\n  apply beq_nat_eq in eq1.\n  apply beq_nat_eq in eq2.\n  rewrite eq1. rewrite eq2.\n  symmetry.\n  apply beq_refl.\nQed.\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  intros X x1 x2 k1 k2 k3 f eq.\n  unfold override.\n  remember (beq_nat k1 k3) as k13.\n  remember (beq_nat k2 k3) as k23.\n  destruct k13. destruct k23.\n  apply beq_nat_eq in Heqk23.\n  apply beq_nat_eq in Heqk13.\n  rewrite Heqk13 in eq.\n  rewrite Heqk23 in eq.\n  rewrite beq_refl in eq.\n  inversion eq. reflexivity.\n  reflexivity.\nQed.\n\nDefinition fold_length {X : Type} (l : llist X) : nat :=\n  fold (fun _ n => S n) l 0.\nExample test_fold_length1 : fold_length [4,7,0] = 3.\nProof. reflexivity. Qed.\nTheorem fold_length_correct : forall X (l : llist X),\n  fold_length l = llength' l.\nProof.\n  induction l. reflexivity.\n  simpl. rewrite <- IHl. reflexivity.\nQed.\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : llist X) : llist Y :=\n  fold (fun x yl => (f x)::yl) l [].\nTheorem fold_map_correct : forall (X Y:Type) (f:X->Y) (l:llist X),\n  fold_map f l = map f l.\nProof.\n  induction l. reflexivity.\n  simpl. rewrite <- IHl. reflexivity.\nQed.\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\nFixpoint forallb {X:Type} (f:X->bool) (l:llist X) : bool :=\n  match l with\n  | lnil _ => true\n  | lcons _ t h => andb (f t) (forallb f h)\n  end.\nExample forallb_test1 : forallb oddb [1,3,5,7,9] = true.\nProof. reflexivity. Qed.\nExample forallb_test2 : forallb negb [false,false] = true.\nProof. reflexivity. Qed.\nExample forallb_test3 : forallb evenb [0,2,4,5] = false.\nProof. reflexivity. Qed.\nExample forallb_test4 : forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\nFixpoint existsb {X:Type} (f:X->bool) (l:llist X) : bool :=\n  match l with\n  | lnil _ => false\n  | lcons _ t h => orb (f t) (existsb f h)\n  end.\nExample existsb_test1 : existsb (beq_nat 5) [0,2,3,6] = false.\nProof. reflexivity. Qed.\nExample existsb_test2 : existsb (andb true) [true,true,false] = true.\nProof. reflexivity. Qed.\nExample existsb_test3 : existsb oddb [1,0,0,0,0,3] = true.\nProof. reflexivity. Qed.\nExample existsb_test4 : existsb evenb [] = false.\nProof. reflexivity. Qed.\nDefinition existsb' {X:Type} (f:X->bool) (l:llist X) : bool :=\n  negb (forallb (fun x => negb (f x)) l).\nTheorem existsb_correct : forall (X:Type) (f:X->bool) (l:llist X),\n  existsb f l = existsb' f l.\nProof.\n  induction l. reflexivity.\n  simpl. rewrite IHl. unfold existsb'. simpl.\n  remember (f x) as fx.\n  destruct fx. reflexivity.\n  reflexivity.\nQed.\nEnd study03'.\nEnd ImplicitTest.\n\n\n\n\n\n\n\n\n\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/study03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.9046505325302033, "lm_q1q2_score": 0.7558206378781454}}
{"text": "Require Import Ashley.Axioms.\nRequire Import Ashley.Proposition.\nRequire Import Ashley.PartialOrder.\n\nDefinition set (A : Type) := A -> Prop.\n\nNotation \"{ x : A | P }\" := (fun x : A => P).\n\nLemma member_ext :  forall {A} a b, (forall x:A, a x <-> b x) -> a = b.\nintros.\napply fun_ext.\nintros.\napply prop_ext.\napply H.\nSave.\n\nDefinition empty {A} := {x:A|False}.\nDefinition full {A} := {x:A|True}.\nDefinition singleton {A} p : set A := {x:A|x=p}.\nDefinition invert {A} p := {x:A|~ p x}.\nDefinition intersect {A} a b := {x:A|a x /\\ b x}.\nDefinition union {A} a b := {x:A|a x \\/ b x}.\nDefinition subset {A} (p : set A) (q : set A) := forall x, p x -> q x.\n\nDefinition superset {A} (p : set A) (q : set A) := subset q p.\nDefinition powerset {A} (p : set A) := {x:set A|x <= p}.\n\nDefinition not_empty {A} (p : set A) : Prop := exists x, p x.\nDefinition is_full {A} (p : set A) : Prop := forall x, p x.\n\nDefinition undisjoint {A} (a:set A) b : Prop := not_empty (intersect a b).\nDefinition disjoint {A} (a:set A) b : Prop := ~ undisjoint a b.\n\nLemma all_full : forall A (p : A), full p.\nintros.\nfirstorder.\nSave.\n\nLemma intersect_left_empty: forall A (p:set A), intersect empty p = empty.\nintros.\napply member_ext.\nfirstorder.\nSave.\n\nLemma intersect_right_empty: forall A (p:set A), intersect p empty = empty.\nintros.\napply member_ext.\nfirstorder.\nSave.\n\nLemma intersect_full_full : forall A, intersect (full:set A) full = full.\nintros.\napply member_ext.\nfirstorder.\nSave.\n\nLemma invert_union : forall (A:Type) (p : set A) (q : set A), invert (union p q) = intersect (invert p) (invert q).\nintros.\napply member_ext.\nfirstorder.\nSave.\n\nNotation \"'all' x : s , P\" := (forall x, s x -> P) (at level 20, x at level 99).\nNotation \"'some' x : s , P\" := (exists x, s x /\\ P) (at level 20, x at level 99).\n\nDefinition Union {A} (p : set (set A)) : set A := {x:A|some s:p, s x}.\n\nLemma Union0: forall {A}, Union empty = (empty: set A).\nintros.\nunfold Union.\nunfold empty.\napply member_ext.\nfirstorder.\nSave.\n\nLemma Union1: forall {A} {p: set A}, Union (singleton p) = p.\nintros.\napply member_ext.\nunfold singleton.\nfirstorder.\nrewrite <- H.\napply H0.\nSave.\n(*\nLemma UnionP1: forall {A} {pp: set (set A)} {q: set A}, Union (union pp (singleton q)) = union (Union pp) q.\nintros.\nunfold Union.\nunfold union.\nunfold singleton.\napply member_ext.\nintros.\nsplit.\nintros.\ndestruct H.\ndestruct H.\nfirstorder.\nexists x0.\n\n\nleft.\n\nunfold some.\n*)\n\nLemma Union2: forall {A} {p: set A} {q: set A}, Union {a : set A | a = p \\/ a = q} = union p q.\nintros.\nunfold Union.\nunfold union.\napply member_ext.\nsplit.\nintros.\ndestruct H.\ndestruct H.\ndestruct H.\nleft.\nrewrite <- H.\napply H0.\nright.\nrewrite <- H.\napply H0.\nintros.\ndestruct H.\nexists p.\nsplit.\nleft.\ntrivial.\napply H.\nexists q.\nsplit.\nright.\ntrivial.\napply H.\nSave.\n\nLemma member_powerset : forall A (a:set A) b, (powerset b) a <-> a <= b.\nfirstorder.\nSave.\n\nDefinition comap {A} {B} (f : B -> A) (sa : set A): set B := {b:B | sa (f b)}.\n\nDefinition map {A} {B} (f : A -> B) (sa : set A): set B := {b:B| some a:sa, (f a = b)}.\n\nLemma map_union_powerset : forall A (a : set (set A)) (b : set (set A)), a <= b -> (map Union (powerset b)) (Union a).\nfirstorder.\nSave.\n\nDefinition pair {A} p q: set A := {x:A|x=p \\/ x=q}.\n\nLemma Union_pair: forall {A} (p q: set A), Union (pair p q) = union p q.\nintros.\nunfold Union.\nunfold union.\nunfold pair.\napply member_ext.\nintros.\nsplit.\nintros.\ndestruct H.\ndestruct H.\ncase H.\nintros.\nleft.\nrewrite <- H1.\nexact H0.\nintros.\nright.\nrewrite <- H1.\nexact H0.\nintros.\ncase H.\nintros.\nexists p.\nsplit.\nleft.\ntrivial.\nexact H0.\nintros.\nexists q.\nsplit.\nright.\ntrivial.\nexact H0.\nQed.\n\nLemma map_pair: forall {A} {B} (f: A -> B) (p q: A), map f (pair p q) = pair (f p) (f q).\nintros.\nunfold map.\nunfold pair.\napply member_ext.\nintros.\nsplit.\nintros.\ndestruct H.\ndestruct H.\ncase H.\nintros.\nleft.\nrewrite <- H0.\nrewrite <- H1.\ntrivial.\nintros.\nright.\nrewrite <- H0.\nrewrite <- H1.\ntrivial.\nintros.\ncase H.\nintros.\nexists p.\nsplit.\nleft.\ntrivial.\nrewrite <- H0.\ntrivial.\nintros.\nexists q.\nsplit.\nright.\ntrivial.\nrewrite <- H0.\ntrivial.\nQed.\n\nLemma pair_same: forall {A} (x:A), pair x x = singleton x.\nintros.\nunfold pair.\nunfold singleton.\napply member_ext.\nintros.\nfirstorder.\nQed.\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/Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7558206329092594}}
{"text": "(* software foundation *)\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\n\nEval compute in (next_weekday friday).\nEval compute in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. \nsimpl. \nreflexivity. \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\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.\n\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | false => true\n  | true => \n    match b2 with\n    | false => true\n    | true => false\n    end\n  end.\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\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | false => false\n  | true => \n      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\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\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  | 0 => 0\n  | S 0 => 0\n  | S (S n') => n'\n  end.\n\nCheck S (S (S (S 0))).\n\nEval compute in (minustwo 4).\n\nCheck S.\nCheck Playground1.nat.\nCheck minustwo.\n\nFixpoint evenb ( n : nat) : bool :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S n') =>  evenb (n')\n  end.\n\nEval compute in evenb (14).\n\nDefinition oddb (n : nat) : bool :=\n  negb (evenb n).\nEval compute in oddb (13).\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\n(* excer *)\n\n\n\n(* Module Playground2.*)\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n    | O => m\n    | S n' => S (plus n' m)\n  end.\n\nEval compute in (plus (S (S (S O))) (S (S O))).\n\n(* End Playground2. *)\n\n\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' => plus m (mult n' m)\n  end.\n\n\nEval compute in (mult 3 4).\n\nExample testMult1 : (mult 5 6) = 30.\nProof. reflexivity. Qed.\n\n\n\n\nFixpoint minus (n m : nat) : nat :=\n  match n, m with\n  | 0, _ => 0\n  | S _, 0 => n\n  | S n', S m' => minus n' m'\n  end.\n\nEval compute in (minus 3 2).\n\n\n\nFixpoint exp (n m : nat) : nat :=\n  match n, m with\n  | _, 0 => 1\n  | 0, _ => 0\n  | (S n'), (S m') => (mult n (exp n m'))\n  end.\n\n\nEval compute in (exp 3 4).\n\nFixpoint fac (n:nat) : nat :=\n  match n with\n  | 0 => 0\n  | S 0 => 1\n  | S n' => (mult n (fac n'))\n  end.\n\nExample testfac : (fac 3) = 6.\nProof. reflexivity. Qed.\n\nExample testfac2 : (fac 4) = (mult 12 2).\nProof. reflexivity. Qed.\n\n\nNotation \"x +* y\" := (exp x y)\n(at level 50, left associativity) : nat_scope.\n\nCheck ((0+1) + 1).\n\nEval compute in ((2+*2) +* 2).\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, m with\n  | 0, 0 => true\n  | S n', 0 => false\n  | 0, S m' => true\n  | S n', S m' => (ble_nat n' m')\n  end.\n\nEval compute in (ble_nat 3 3).\n\nFixpoint blt_nat1 (n m : nat) : bool :=\n  match n, m with\n  | 0, 0 => false\n  | S n', 0 => false\n  | 0, S m' => true\n  | S n', S m' => (blt_nat1 n' m')\n  end.\n\nExample tblt_nat1: (blt_nat1 2 2) = false.\nProof. reflexivity. Qed.\nExample tblt_nat2: (blt_nat1 2 4) = true.\nProof. reflexivity. Qed.\nExample tblt_nat3: (blt_nat1 4 2) = false.\nProof. reflexivity. Qed.\n\n\n\nTheorem plus_id_1 : 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.\nQed.\n\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 H1.\n  rewrite <- H.\n  rewrite <- H1.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\n\nTheorem plus_0_n : forall n:nat,\n  0 + n = n.\n\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\n\n\nTheorem mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\n\nProof.\n  intros n m.\n  rewrite -> plus_0_n.\n  reflexivity.\nQed.\n\n\n\n(* comment start 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  simpl.\n  intros H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\nFixpoint beq_nat1 (n m :nat) : bool :=\n  match n, m with\n  | 0, 0 => true\n  | S n', 0 => false\n  | 0, S m' => false\n  | S n', S m' => (beq_nat1 n' m')\n  end.\n\nEval compute in (beq_nat1 2 1).\n\n\nNotation \"x + y\" := (plus x y)\n(at level 50, left associativity) : nat_scope.\n\n\n\n\n\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat1 (n + 1) 0 = false.\nProof.\n  intros n.\n  destruct n as [| n']. (* vars sep by | *)\n  reflexivity.\n  reflexivity.\nQed.\n\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\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\n(* comment start 2 *)\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 b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n\nExample or_true_c :\n  forall (c:bool),\n  (orb true c) = true.\n\nProof.\n  reflexivity.\nQed.\n\nLemma and_false_c :\n  forall (c:bool),\n  andb false c = false.\n\nProof.\n  reflexivity.\nQed.\n\n\n(* comment start 2 *)\nTheorem andb_eq_orb : \n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  destruct b.\n  intros c.\n  Focus 1.\n  simpl.\n  intros.\n  rewrite <- H.\n  reflexivity.\n  intros c.\n  rewrite -> and_false_c with c.\n  simpl.\n  intros h2.\n  rewrite -> h2.\n  reflexivity.\nQed.\n  \n\n\nInductive bnat : Type :=\n  | O : bnat (* 0 *)\n  | T : bnat->bnat (* xxx0 *)\n  | TI : bnat->bnat (* xxxx1 *).\n\n\nFixpoint incr (n:bnat) : bnat :=\n  match n with\n  | O => TI O\n  | T n' => TI n'\n  | TI n' => T (incr n')\n  end.\n\n\nExample test_bin_incr1:\n  (incr O) = (TI O).\n\nProof. simpl. reflexivity. Qed.\n\nExample test_bin_incr2:\n  (incr (TI (TI O)))=(T (T (TI O))).\nProof. reflexivity. Qed.\n\nExample test_bin_incr3:\n  (incr (T (TI O)))=(TI (TI O)).\nProof. reflexivity. Qed.\n\nExample test_bin_incr4:\n  (incr (TI (T (TI O))))=(T (TI (TI O))).\nProof. reflexivity. Qed.\n\nExample test_bin_incr5:\n  (incr (TI (T (TI O))))=(T (TI (TI O))).\nProof. reflexivity. Qed.\n\n\nFixpoint lt (n m:nat) : bool :=\n  match n, m with\n  | 0, S m' => true\n  | 0, 0 => false\n  | S n', 0 => false\n  | S n', S m' => lt n' m'\n  end.\n\nFixpoint decrto1(n:nat) : nat :=\n  match n with\n  | 3 => 1\n  | S n' =>(decrto1 n')\n  | _ => 1\n  end.\n\nEval compute in (decrto1 10).\nEval compute in (eq 10 10).\n\nFixpoint eq1 (n m:nat) : bool :=\n  match n, m with\n  | 0, 0 => true\n  | S n', S m' => eq1 n' m'\n  | _, _ => false\n  end.\n\n(* ill form \nFixpoint incrto(n:nat) : nat :=\n  match n with\n  | 10 => 11\n  | 0 => 1\n  | m' =>(incrto (S m'))\n  end.\n*)\n\n\n\n\n(*\nhttp://www.cis.upenn.edu/~bcpierce/sf/current/Induction.html#lab38\n*)\n\nRequire String. Open Scope string_scope.\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\". (* <----- here *)\n    reflexivity.\n  Case \"b = false\". (* <---- and here *)\n    rewrite <- H.\n    reflexivity.\nQed.\n\n\n\n\n\n", "meta": {"author": "TheMindX", "repo": "COQ", "sha": "c01b03d69eb237e7731edb98b02c933872eb64d9", "save_path": "github-repos/coq/TheMindX-COQ", "path": "github-repos/coq/TheMindX-COQ/COQ-c01b03d69eb237e7731edb98b02c933872eb64d9/SF/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.7557705983620588}}
{"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 double (double_arg0 : Nat) : Nat\n           := match double_arg0 with\n              | zero => zero\n              | succ n => succ (succ (double n))\n              end.\n\nLemma lem: forall m n, succ (plus m n) = plus m (succ n).\nProof.\n   induction m.\n   - intros. simpl. rewrite IHm. reflexivity.\n   - intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Nat), eq (double x) (plus x x).\nProof.\n   induction x.\n   - simpl. f_equal. rewrite IHx. apply lem.\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/goal1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.755733741672513}}
{"text": "Require Import Recdef Nat Lia.\n\nRequire Import List.\nImport ListNotations.\n\nFrom Equations Require Import Equations.\n\nUnset Guard Checking.\nFunction euclid_mod (p q : nat) {struct p} : nat :=\nmatch p with\n| 0 => q\n| _ => euclid_mod (modulo q p) p\nend.\nSet Guard Checking.\n\nCompute euclid_mod 0 0.\n\nInductive euclid_mod_graph : nat -> nat -> nat -> Prop :=\n| emg_0 : forall q : nat, euclid_mod_graph 0 q q\n| emg_S : forall p q r : nat, euclid_mod_graph (modulo q p) p r -> euclid_mod_graph p q r.\n\nInductive euclid_mod_graph' : Type :=\n| emg_0' : forall q : nat, euclid_mod_graph'\n| emg_S' : forall p q r : nat, euclid_mod_graph' -> euclid_mod_graph'.\n\nFrom Equations Require Import Equations.\n\n(* Equations? euclid_sub (p q : nat) {_ : p <> 0} {_ : q <> 0} : nat by wf (p + q) lt :=\n| p, q with (PeanoNat.Nat.compare_spec p q) => {\n  | CompLt H => euclid_sub p (q - p)\n  | @CompEq H => p\n  | CompGt H => euclid_sub (p - q) q }.\nNext Obligation. *)\n\nFixpoint euclid_sub (pq : nat * nat) {Hp : fst pq <> 0} {Hq : snd pq <> 0} {struct pq} : nat.\nProof.\nrefine (\nmatch Compare_dec.lt_eq_lt_dec (fst pq) (snd pq) with\n| inleft (left H) => @euclid_sub (fst pq, snd pq - fst pq) Hp ltac:(cbn; lia)\n| inleft (right _) => fst pq\n| inright H => @euclid_sub (fst pq - snd pq, snd pq) ltac:(cbn; lia) Hq\nend).\nAbort.\n\nFunction euclid_sub (pq : nat * nat) {Hp : fst pq <> 0} {Hq : snd pq <> 0}\n  {measure (fun '(p, q) => p + q) pq} : nat :=\nmatch Compare_dec.lt_eq_lt_dec (fst pq) (snd pq) with\n| inleft (left H) => @euclid_sub (fst pq, snd pq - fst pq) Hp ltac:(cbn; lia)\n| inleft (right _) => fst pq\n| inright H => @euclid_sub (fst pq - snd pq, snd pq) ltac:(cbn; lia) Hq\nend.\nProof.\n  - intros [p q] **; simpl in *; lia.\n  - intros [p q] **; simpl in *; lia.\nDefined.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Quot/euclid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7557337371085275}}
{"text": "Module Type Typ.\n  Parameter Inline(10) T : Type.\nEnd Typ.\n\nModule Type HasBinOperation(Import M : Typ).\n  Parameter f : T -> T -> T.\nEnd HasBinOperation.\n\nModule Type Magma <: Typ := Typ <+ HasBinOperation.\n\nModule Type IsAssociative(Import M : Magma).\n  Axiom assoc : forall (a b c : T), f (f a b) c = f a (f b c).\nEnd IsAssociative.\n\nModule Type Semigroup <: Magma := Magma <+ IsAssociative.\n\nModule Type HasUnit(Import M : Magma).\n  Parameter u : T.\n  Axiom ru : forall a : T, (f a u) = a.\n  Axiom lu : forall a : T, (f u a) = a.\nEnd HasUnit.\n\nModule Type UnitalMagma <: Magma := Magma <+ HasUnit.\n\nModule Type Monoid <: Semigroup :=  Semigroup <+ HasUnit.\n\nModule MonoidExample : Monoid.\n  Definition T := nat.\n  Definition f := plus.\n  \n  Lemma assoc : forall (a b c : T), f (f a b) c = f a (f b c).\n    intros. unfold f. induction a as [| a' IHa].\n    { reflexivity. }\n    { simpl. apply f_equal, IHa. }\n  Qed.\n  \n  Definition u := 0.\n\n  Lemma ru : forall a : T, (f a u) = a.\n  Proof. intros. unfold f. unfold u. rewrite <- plus_n_O. reflexivity. Qed.\n\n  Lemma lu : forall a : T, (f u a) = a. \n  Proof. intros. unfold f, u. reflexivity. Qed.\nEnd MonoidExample.\n\nModule Type HasInverse(Import M : UnitalMagma).\n  Parameter inv : T -> T.\n  Axiom r_inv : forall a : T, f a (inv a) = u.\n  Axiom l_inv : forall a : T, f (inv a) a = u.\nEnd HasInverse.\n\nModule Type IsCommutative(Import M : Magma).\n  Axiom comm : forall a b : T, f a b = f b a.\nEnd IsCommutative.\n\nModule Type Group <: Monoid := Monoid <+ HasInverse.\n\nModule Type AbelianGroup <: Group := Group <+ IsCommutative.\n\n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/Algebra/AlgWithModulesAndFunctors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.755733733748417}}
{"text": "Require Import Ensembles.\n\n\n\nRecord Ring : Type := mkRing {\n  number : Type;\n  plus : number -> number -> number;\n  mult : number -> number -> number;\n  zero : number;\n  one : number;\n  inv : number -> number;\n  plus_inv : forall n : number, plus n (inv n) = zero;\n  plus_zero : forall n : number, plus n zero = n;\n  plus_assoc : forall (a : number) (b : number) (c : number), plus (plus a b) c = plus a (plus b c);\n  plus_rev : forall (a : number) (b : number), plus a b = plus b a;\n  mult_assoc : forall (a : number) (b : number) (c : number), mult (mult a b) c = mult a (mult b c);\n  mult_dist : forall (a : number) (b : number) (c : number), mult a (plus b c) = plus (mult a b) (mult a c);\n  mult_rev : forall (a : number) (b : number), mult a b = mult b a;\n  mult_one : forall (a : number), mult a one = a;\n}.\n\nSet Implicit Arguments.\n\nArguments plus {r}.\nArguments mult {r}.\nArguments zero {r}.\nArguments one {r}.\nArguments inv {r}.\nArguments plus_inv {r}.\nArguments plus_zero {r}.\nArguments plus_assoc {r}.\nArguments plus_rev {r}.\nArguments mult_assoc {r}.\nArguments mult_dist {r}.\nArguments mult_rev {r}.\nArguments mult_one {r}.\n\nProposition prop_mult_zero : forall (X : Ring) (x : number X), mult x zero = zero.\nProof.\nintros.\nassert (mult (plus zero zero) x = mult zero x).\nrewrite (plus_zero zero).\nreflexivity.\nrewrite (mult_rev) in H.\nrewrite (mult_dist) in H.\nassert (plus (plus (mult x zero) (mult x zero)) (inv (mult x zero)) = plus (mult zero x) (inv (mult zero x))).\nrewrite H.\nrewrite (mult_rev x zero).\nreflexivity.\nrewrite (plus_assoc (mult x zero) (mult x zero) (inv (mult x zero))) in H0.\nrewrite (plus_inv (mult x zero)) in H0.\nrewrite (plus_zero) in H0.\nrewrite plus_inv in H0.\ntrivial.\nQed.\n\nProposition prop_mult_inv : forall (X : Ring) (x : number X), mult x (inv one) = inv x.\nProof.\nintros.\nassert (H := prop_mult_zero X x).\nrewrite <- (plus_inv one) in H at 1.\nrewrite <- (plus_inv x) in H at 1.\nrewrite mult_dist in H.\napply (f_equal (fun t => plus (inv x) t)) in H.\nrewrite (mult_one) in H.\nrewrite <- (plus_assoc) in H.\nrewrite (plus_rev (inv x) x) in H.\nrewrite plus_inv in H.\nrewrite (plus_rev) in H.\nrewrite (plus_zero) in H.\nrewrite (plus_zero) in H.\ntrivial.\nQed.\n\nDefinition principal_ideal := (fun (X : Ring) (x : number X) => (fun a => exists k : number X, a = mult k x)).\n\nDefinition ideal := (fun (X : Ring) (a : Ensemble (number X)) => (forall x y, a x -> a y -> a (plus x y)) /\\ (forall x y, a y -> a (mult x y)) /\\ Inhabited (number X) a).\n\nDefinition unit := (fun (X : Ring) (a : number X) => exists b, mult a b = one).\n\nArguments principal_ideal {X}.\nArguments ideal {X}.\nArguments unit {X}.\n\nDefinition injective := (fun (X : Type) (Y : Type) (F : X -> Y) => forall x y, F x = F y -> x = y).\n\nDefinition reverse := (fun (X : Type) (Y : Type) (F : X -> Y) (G : Y -> X) => forall x, F (G x) = x).\n\nDefinition mapring_plus : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T),\n  T -> T -> T\n:= fun X T F G X0 X1 => G (plus (F X0) (F X1)).\n\nDefinition mapring_mult : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T),\n  T -> T -> T\n:= fun X T F G X0 X1 => G (mult (F X0) (F X1)).\n\nDefinition mapring_zero : forall (X : Ring) (T:Type) (G : number X -> T),\n  T\n:= fun X T G => G zero.\n\nDefinition mapring_one : forall (X : Ring) (T:Type) (G : number X -> T),\n  T\n:= fun X T G => G one.\n\nDefinition mapring_inv : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T),\n  T -> T\n:= fun X T F G X0 => G (inv (F X0)).\n\nArguments mapring_plus {X T}.\nArguments mapring_mult {X T}.\nArguments mapring_zero {X T}.\nArguments mapring_one {X T}.\nArguments mapring_inv {X T}.\n\nProposition mapring_plus_inv : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev : reverse F G) (n : T),\n  mapring_plus F G n (mapring_inv F G n) = mapring_zero G.\nProof.\nintros.\nunfold mapring_plus.\nunfold mapring_inv.\nunfold mapring_zero.\nunfold reverse in rev.\nrewrite (rev (inv (F n))).\nrewrite plus_inv.\nreflexivity.\nQed.\n\nProposition mapring_plus_zero : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev1 : reverse F G) (rev2 : reverse G F) (n : T),\n  mapring_plus F G n (mapring_zero G) = n.\nProof.\nintros.\nunfold mapring_plus.\nunfold mapring_zero.\nrewrite (rev1 zero).\nrewrite plus_zero.\nrewrite rev2.\nreflexivity.\nQed.\n\nProposition mapring_plus_assoc : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev : reverse F G) (p : T) (q : T) (r : T),\n  mapring_plus F G (mapring_plus F G p q) r = mapring_plus F G p (mapring_plus F G q r).\nProof.\nintros.\nunfold mapring_plus.\nrewrite rev.\nrewrite rev.\nrewrite plus_assoc.\nreflexivity.\nQed.\n\nProposition mapring_plus_rev : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (p : T) (q : T),\n  mapring_plus F G p q = mapring_plus F G q p.\nProof.\nintros.\nunfold mapring_plus.\nrewrite plus_rev.\nreflexivity.\nQed.\n\nProposition mapring_mult_assoc : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev : reverse F G) (p : T) (q : T) (r : T),\n  mapring_mult F G (mapring_mult F G p q) r = mapring_mult F G p (mapring_mult F G q r).\nProof.\nintros.\nunfold mapring_mult.\nrewrite rev.\nrewrite rev.\nrewrite mult_assoc.\nreflexivity.\nQed.\n\nProposition mapring_mult_dist : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev : reverse F G) (p : T) (q : T) (r : T),\n  mapring_mult F G p (mapring_plus F G q r) = mapring_plus F G (mapring_mult F G p q) (mapring_mult F G p r).\nProof.\nintros.\nunfold mapring_mult.\nunfold mapring_plus.\nrewrite rev.\nrewrite rev.\nrewrite rev.\nrewrite mult_dist.\nreflexivity.\nQed.\n\nProposition mapring_mult_rev : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (p : T) (q : T),\n  mapring_mult F G p q = mapring_mult F G q p.\nProof.\nintros.\nunfold mapring_mult.\nrewrite mult_rev.\nreflexivity.\nQed.\n\nProposition mapring_mult_one : forall (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev1 : reverse F G) (rev2 : reverse G F) (n : T),\n  mapring_mult F G n (mapring_one G) = n.\nProof.\nintros.\nunfold mapring_mult.\nunfold mapring_one.\nrewrite rev1.\nrewrite mult_one.\nrewrite rev2.\nreflexivity.\nQed.\n\nArguments mapring_plus_inv {X T}.\nArguments mapring_plus_zero {X T}.\nArguments mapring_plus_assoc {X T}.\nArguments mapring_plus_rev {X T}.\nArguments mapring_mult_assoc {X T}.\nArguments mapring_mult_dist {X T}.\nArguments mapring_mult_rev {X T}.\nArguments mapring_mult_one {X T}.\n\nDefinition mapring := (fun (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev1 : reverse F G) (rev2 : reverse G F) =>\n  mkRing\n  T\n  (mapring_plus F G)\n  (mapring_mult F G)\n  (mapring_zero G)\n  (mapring_one G)\n  (mapring_inv F G)\n  (mapring_plus_inv F G rev1)\n  (mapring_plus_zero F G rev1 rev2)\n  (mapring_plus_assoc F G rev1)\n  (mapring_plus_rev F G)\n  (mapring_mult_assoc F G rev1)\n  (mapring_mult_dist F G rev1)\n  (mapring_mult_rev F G)\n  (mapring_mult_one F G rev1 rev2)\n).\n\nDefinition mapring_wo_rev2 := (fun (X : Ring) (T:Type) (F : T -> number X) (G : number X -> T) (rev1 : reverse F G)\n    (p_plus_zero : forall n, mapring_plus F G n (mapring_zero G) = n)\n    (p_mult_one : forall n, mapring_mult F G n (mapring_one G) = n) =>\n  mkRing\n  T\n  (mapring_plus F G)\n  (mapring_mult F G)\n  (mapring_zero G)\n  (mapring_one G)\n  (mapring_inv F G)\n  (mapring_plus_inv F G rev1)\n  (p_plus_zero)\n  (mapring_plus_assoc F G rev1)\n  (mapring_plus_rev F G)\n  (mapring_mult_assoc F G rev1)\n  (mapring_mult_dist F G rev1)\n  (mapring_mult_rev F G)\n  (p_mult_one)\n).\n\nProposition principal_ideal_is_ideal : forall (X : Ring) (x : number X), ideal (principal_ideal x).\nProof.\nintros.\nunfold ideal.\nconstructor.\nintros.\nunfold principal_ideal.\nunfold principal_ideal in H.\nunfold principal_ideal in H0.\ndestruct H.\ndestruct H0.\nexists (plus x1 x2).\nrewrite mult_rev.\nrewrite mult_dist.\nrewrite H.\nrewrite H0.\nrewrite (mult_rev x1 x).\nrewrite (mult_rev x2 x).\nreflexivity.\nsplit.\nintros.\nunfold principal_ideal in H.\nunfold principal_ideal.\ndestruct H.\nexists (mult x0 x1).\nrewrite H.\nrewrite mult_assoc.\nreflexivity.\nexists x.\nexists one.\nrewrite mult_rev.\nrewrite mult_one.\ntrivial.\nQed.\n\nProposition unit_principal_ideal_full_set : forall {X : Ring} (x : number X), (exists y, mult x y = one) <-> (principal_ideal x) = Full_set (number X).\nProof.\nintros.\nsplit.\nintros.\napply Extensionality_Ensembles.\nunfold Same_set.\nunfold Included.\nconstructor.\nintros.\nunfold In.\napply Full_intro.\nintros.\nunfold In.\ndestruct H.\nunfold In in H0.\nexists (mult x0 x1).\nrewrite (mult_assoc x0 x1 x).\nrewrite (mult_rev x1 x).\nrewrite H.\nrewrite mult_one.\nreflexivity.\nintros.\nassert ((Full_set (number X)) one).\napply Full_intro.\nrewrite <- H in H0.\ndestruct H0.\nexists x0.\nrewrite mult_rev in H0.\nrewrite H0.\nreflexivity.\nQed.\n\nProposition principal_ideal_included : forall (X : Ring) (a :  Ensemble (number X)) (t :  number X), ideal a -> a t -> Included (number X) (principal_ideal t) a.\nProof.\nintros.\nunfold Included.\nintros.\nunfold In.\nunfold In in H1.\nunfold principal_ideal in H1.\ndestruct H1.\nunfold ideal in H.\ndestruct H.\ndestruct H2.\nassert (H4 := H2 x0 t H0).\nrewrite <- H1 in H4.\ntrivial.\nQed.\n\nDefinition field := (fun (X : Ring) => (one : number X) <> zero /\\ forall x : number X, x <> zero -> unit x).\n\nDefinition homomorphism := (fun (X : Ring) (Y : Ring) (f : number X -> number Y) =>\n  (forall (x : number X) (y : number X), f(plus x y) = plus (f x) (f y)) /\\\n  (forall (x : number X) (y : number X), f(mult x y) = mult (f x) (f y)) /\\\n  (f(one) = one)\n).\n\nArguments homomorphism {X} {Y}.\n\nProposition prop_homomorphism_zero : forall (X : Ring) (Y : Ring) (F : number X -> number Y), homomorphism F -> F zero = zero.\nProof.\nintros.\nunfold homomorphism in H.\ndestruct H.\ndestruct H0.\nassert (H2 := H1).\nrewrite <- (plus_zero one) in H2.\nrewrite H in H2.\nrewrite H1 in H2.\napply (f_equal (fun t => plus t (inv one))) in H2.\nrewrite plus_inv in H2.\nrewrite plus_rev in H2.\nrewrite <- plus_assoc in H2.\nrewrite (plus_rev (inv one) one) in H2.\nrewrite plus_inv in H2.\nrewrite plus_rev in H2.\nrewrite plus_zero in H2.\ntrivial.\nQed.\n\nDefinition kernel := (fun (X : Ring) (Y : Ring) (F : number X -> number Y) => (fun t => F t = zero)).\n\nArguments kernel {X Y}.\n\nProposition prop_hom_inv : forall (X : Ring) (Y : Ring) (F : number X -> number Y), homomorphism F -> forall t, inv (F t) = F (inv t).\nProof.\nintros.\nassert (HHom := H).\nunfold homomorphism in H.\ndestruct H.\ndestruct H0.\nassert (zero = plus (F t) (F (inv t))).\nrewrite <- H.\nrewrite plus_inv.\nrewrite prop_homomorphism_zero.\nreflexivity.\napply HHom.\napply (f_equal (fun v => plus v (inv (F t)))) in H2.\nrewrite plus_rev in H2.\nrewrite plus_zero in H2.\nrewrite plus_assoc in H2.\nrewrite plus_rev in H2 at 1.\nrewrite plus_assoc in H2.\nrewrite (plus_rev (inv (F t)) (F t)) in H2.\nrewrite plus_inv in H2.\nrewrite plus_zero in H2.\ntrivial.\nQed.\n\nProposition prop_1_2_a4 : forall (X : Ring) (Y : Ring) (F : number X -> number Y), homomorphism F -> kernel F = Singleton (number X) zero -> injective F.\nProof.\nintros.\nassert (HHom := H).\nunfold injective.\nintros.\nunfold kernel in H0.\nunfold homomorphism in H.\ndestruct H.\ndestruct H2.\napply (f_equal (fun t => plus t (inv (F y)))) in H1.\nrewrite plus_inv in H1.\nrewrite (prop_hom_inv) in H1.\nrewrite <- H in H1.\nassert (plus x (inv y) = zero).\nassert ((fun t : number X => F t = zero) (plus x (inv y))).\ntrivial.\nrewrite H0 in H4.\ndestruct H4.\nreflexivity.\napply (f_equal (fun v => plus v y)) in H4.\nrewrite plus_assoc in H4.\nrewrite (plus_rev (inv y) y) in H4.\nrewrite plus_inv in H4.\nrewrite (plus_rev zero y) in H4.\nrewrite plus_zero in H4.\nrewrite plus_zero in H4.\ntrivial.\ntrivial.\nQed.\n\nDefinition ring_nonzero := (fun X => exists x : number X, x <> zero).\nDefinition ring_zero := (fun X => forall x : number X, x = zero).\n\nRequire Import Coq.Logic.Classical_Pred_Type.\n\nProposition no_empty_exists : forall (T : Type) (a : Ensemble T), a <> Empty_set _ -> exists l, a l.\nintros.\napply not_all_not_ex.\nintro.\napply H.\napply Extensionality_Ensembles.\nred.\nsplit.\nintro.\nintro.\napply False_ind.\napply ((H0 x) H1).\nintro.\nintro.\ndestruct H1.\nQed.\n\nProposition no_empty_no_singleton_element : forall (T : Type) (a : Ensemble T) (k : T), a <> Empty_set _ -> a <> Singleton _ k -> exists l, a l /\\ l <> k.\nintros.\napply not_all_not_ex.\nintro.\nassert (exists e, a e).\napply no_empty_exists.\ntrivial.\ndestruct H2.\napply H0.\napply Extensionality_Ensembles.\nred.\nsplit.\nintro.\nintro.\nassert (H4 := H1 x0).\napply NNPP.\nintro.\napply H4.\nsplit.\ntrivial.\nintro.\nrewrite H6 in H5.\napply H5.\nconstructor.\nintro.\nintro.\nrewrite H3 in H1.\ncase (classic (x = x0)).\nintro.\nrewrite H4 in H2.\ntrivial.\nintro.\napply False_ind.\napply (H1 x).\nauto.\nQed.\n\nProposition prop_1_2_1 : forall (X : Ring), field X -> forall (a :  Ensemble (number X)), ideal a -> (a = Singleton (number X) zero \\/ a = Full_set (number X)).\nProof.\nintros.\nassert (ide := H0).\nunfold ideal in H0.\nunfold field in H.\ndestruct H.\nunfold unit in H1.\ncase (classic (a = Singleton (number X) zero)).\nintros.\nleft.\ntrivial.\nintros.\nright.\ndestruct H0.\ndestruct H3.\nassert (a <> Empty_set _).\nintro.\nrewrite H5 in H4.\ndestruct H4.\ndestruct H4.\nassert (H6 := no_empty_no_singleton_element H5 H2).\ndestruct H6.\ndestruct H6.\napply Extensionality_Ensembles.\nred.\nsplit.\nintro.\nintro.\nconstructor.\nassert (principal_ideal x = Full_set (number X)).\napply unit_principal_ideal_full_set.\nauto.\nrewrite <- H8.\napply principal_ideal_included.\ntrivial.\ntrivial.\nQed.\n\nProposition prop_1_2_2 :  forall (X : Ring), (forall a : Ensemble(number X), ideal a -> (a = Singleton (number X) zero \\/ a = Full_set (number X))) -> forall (Y : Ring) (F : number X -> number Y), (exists (t : number Y), t <> zero) -> homomorphism F -> injective F.\nProof.\nintros.\nassert (HomF := H1).\ndestruct H1.\ndestruct H2.\ndestruct H0.\nassert (H5 := H (kernel F)).\nassert (ideal (kernel F)).\nunfold ideal.\nconstructor.\nintros.\nunfold kernel.\nrewrite H1.\nrewrite H4.\nrewrite H6.\napply plus_zero.\nsplit.\nintros.\nunfold kernel.\nrewrite H2.\nrewrite H4.\napply prop_mult_zero.\nexists zero.\napply prop_homomorphism_zero.\napply HomF.\nassert (H6 := H5 H4).\ncase H6.\nintro.\napply (prop_1_2_a4).\ntrivial.\ntrivial.\nunfold injective.\nunfold kernel.\nintros.\nassert (Full_set (number X) one).\napply Full_intro.\nrewrite <- H7 in H9.\nrewrite H3 in H9.\nrewrite <- (mult_one x) in H0.\nrewrite H9 in H0.\nrewrite prop_mult_zero in H0.\napply False_ind.\napply H0.\nreflexivity.\nQed.\n\nProposition prop_one_eq_zero : forall (X : Ring), (one : number X) = zero -> ring_zero X.\nProof.\nintros.\nintro.\nassert (mult x one = mult x one).\nreflexivity.\nrewrite H in H0 at 2.\nrewrite mult_one in H0.\nrewrite prop_mult_zero in H0.\ntrivial.\nQed.\n\nProposition prop_ring_zero_nonzero_contradiction : forall (X : Ring), ring_nonzero X -> ring_zero X -> False.\nProof.\nintros.\ndestruct H.\nassert (H1 := H0 x).\napply (H H1).\nQed.\n\nProposition prop_1_2_3 : forall (X : Ring), ring_nonzero X -> (forall (Y : Ring) (F : number X -> number Y), (ring_nonzero Y) -> homomorphism F -> injective F) -> field X.\nProof.\nintros.\nconstructor.\nintro.\nassert (H2 := prop_one_eq_zero X H1).\napply (prop_ring_zero_nonzero_contradiction H H2).\nintros.\nunfold unit.\nunfold injective in H0.\napply not_all_not_ex.\nintro.\napply H1.\n\n\n\n\nassert (H3 := H0 (quotient_ring X (principal_ideal x)) (fun x => mkQuot _ x)).\nsimpl in H3.\nunfold principal_ideal in H3.\nunfold ring_nonzero in H3.\nunfold quotient_ring in H3.\nsimpl in H3.\napply H1.\napply H3.\nclear H3.\nexists (mkQuot _ x).\nunfold quotient_zero.\nintro.\nassert (H4 := f_equal (fun t => deQuot t) H3).\nsimpl in H4.\ncontradiction.\nunfold homomorphism.\nsimpl.\nsplit.\nintros.\nreflexivity.\nsplit.\nintros.\nreflexivity.\nunfold quotient_one.\nreflexivity.\n", "meta": {"author": "aidatorajiro", "repo": "WorksOfProof", "sha": "e65dd026f5e700ce37ca5ffab86e863616af8641", "save_path": "github-repos/coq/aidatorajiro-WorksOfProof", "path": "github-repos/coq/aidatorajiro-WorksOfProof/WorksOfProof-e65dd026f5e700ce37ca5ffab86e863616af8641/atimak.bak3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7557337328400158}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\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 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.\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 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. lfind.  rewrite <- plus_assoc.  reflexivity. \nAdmitted.\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 mult_qexp : forall (x y z a : natural), mult (qexp x y z) a = qexp x y (mult z a).\nProof.\n   intros x y.\n   induction y.\n   - reflexivity.\n   - intros. simpl. rewrite IHy. rewrite mult_assoc. rewrite (mult_commut x a). \n     rewrite <- mult_assoc. reflexivity.\nQed.\n\nTheorem exp_eq_qexp : forall (x : natural) (y : natural), eq (exp x y) (qexp x y (Succ Zero)).\nProof.\n   intros.\n   induction y.\n   - reflexivity.\n   - simpl. rewrite IHy. rewrite mult_qexp. 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/_lfind_clam_lf_goal35_distrib_94_plus_commut/goal35.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.755702912142445}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Lia ssreflect.\nOpen Scope Z_scope.\n\nDefinition list_max_Z : list Z -> Z := fold_right Z.max 0.\n\nLemma list_max_Z_spec : forall l,\n  let max_val := list_max_Z l in\n  Forall (fun x => x <= max_val) l /\\\n  (In max_val l \\/ max_val = 0).\nProof. \n  intros.\n  subst max_val.\n  split.\n  - induction l; [easy|].\n    apply Forall_cons.\n    + simpl.\n      unfold Z.max.\n      destruct (a ?= list_max_Z l) eqn:H; [easy| |easy].\n      rewrite Z.compare_lt_iff in H.\n      lia.\n    + simpl.\n      unfold Z.max.\n      destruct (a ?= list_max_Z l) eqn:H.\n      * rewrite Z.compare_eq_iff in H.\n        rewrite H.\n        exact IHl.\n      * exact IHl.\n      * rewrite Z.compare_gt_iff in H.\n        apply Forall_forall.\n        intros.\n        rewrite Forall_forall in IHl.\n        pose proof (IHl x).\n        pose proof (H1 H0).\n        pose proof (Z.le_lt_trans _ _ _ H2 H).\n        lia.\n  - induction l.\n    + right. easy.\n    + destruct IHl.\n      * simpl.\n        unfold Z.max.\n        destruct (a ?= list_max_Z l).\n        -- left. left. reflexivity.\n        -- left. right. exact H.\n        -- left. left. reflexivity.\n      * simpl.\n        unfold Z.max.\n        destruct (a ?= list_max_Z l) eqn:H0.\n        -- right. \n            rewrite Z.compare_eq_iff in H0.\n            congruence.\n        -- right. exact H. \n        -- left. left. reflexivity.\n  (* Show Proof. *)\nQed.\n\nLemma list_max_Z_spec2 : forall l,\n  let max_val := list_max_Z l in\n  Forall (fun x => x <= max_val) l /\\\n  (In max_val l \\/ max_val = 0).\nProof.\n  intros.\n  subst max_val.\n  split.\n  - apply Forall_forall.\n    intros x I.\n    induction l.\n    + simpl in I. contradiction.\n    + simpl in *. \n      destruct I as [-> | J].\n      lia.\n      pose proof (IHl J).\n      lia.\n  - induction l.\n    simpl.\n    right.\n    reflexivity.\n    simpl in *.\n    destruct IHl;\n    pose proof (Z.max_spec_le a (list_max_Z l));\n    destruct H0 as [[L ->] | [A B]].\n    auto.\n    auto.\n    auto.\n    auto.\n\n\nAbort.\n      \n             \nLemma list_max_Z_spec3 : forall l,\n  let max_val := list_max_Z l in\n  Forall (fun x => x <= max_val) l /\\\n  (In max_val l \\/ max_val = 0).\nProof.\n  move => l /=; split.\n  - rewrite Forall_forall => x.\n    by elim: l => //= h t IH [-> | /IH]; lia.\n  - elim: l => //= [| h t]; first by right.\n    by case: (Z.max_spec_le h (list_max_Z t)) => [] [H] -> []; auto.\n    (* Show Proof. *)\nQed.\n\nLemma list_max_Z_spec4 : forall l,\n  let max_val := list_max_Z l in\n  Forall (fun x => x <= max_val) l /\\\n  (In max_val l \\/ max_val = 0).\nProof.\n  move => l /=; split.\n  - rewrite Forall_forall => x.\n    elim: l => //=.\n    move=> h t IH.\n    case=> [-> | /IH].\n    lia.\n    lia.\n  - elim: l => //= [| h t]; first by right.\n    by case: (Z.max_spec_le h (list_max_Z t)) => [] [H] -> []; auto.\n    (* Show Proof. *)\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/listmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7555196431419104}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat Even.\n\nLocal Open Scope nat_scope.\n\nImplicit Type n : nat.\n\n\n\nNotation div2 := Nat.div2 (compat \"8.4\").\n\n\n\nLemma ind_0_1_SS :\nforall P:nat -> Prop,\nP 0 -> P 1 -> (forall n, P n -> P (S (S n))) -> forall n, P n.\nProof. hammer_hook \"Div2\" \"Div2.ind_0_1_SS\".  \nintros P H0 H1 H2.\nfix 1.\ndestruct n as [|[|n]].\n- exact H0.\n- exact H1.\n- apply H2, ind_0_1_SS.\nQed.\n\n\n\nLemma lt_div2 n : 0 < n -> div2 n < n.\nProof. hammer_hook \"Div2\" \"Div2.lt_div2\".   apply Nat.lt_div2. Qed.\n\nHint Resolve lt_div2: arith.\n\n\n\nLemma even_div2 n : even n -> div2 n = div2 (S n).\nProof. hammer_hook \"Div2\" \"Div2.even_div2\".  \nrewrite Even.even_equiv. intros (p,->).\nrewrite Nat.div2_succ_double. apply Nat.div2_double.\nQed.\n\nLemma odd_div2 n : odd n -> S (div2 n) = div2 (S n).\nProof. hammer_hook \"Div2\" \"Div2.odd_div2\".  \nrewrite Even.odd_equiv. intros (p,->).\nrewrite Nat.add_1_r, Nat.div2_succ_double.\nsimpl. f_equal. symmetry. apply Nat.div2_double.\nQed.\n\nLemma div2_even n : div2 n = div2 (S n) -> even n.\nProof. hammer_hook \"Div2\" \"Div2.div2_even\".  \ndestruct (even_or_odd n) as [Ev|Od]; trivial.\napply odd_div2 in Od. rewrite <- Od. intro Od'.\nelim (n_Sn _ Od').\nQed.\n\nLemma div2_odd n : S (div2 n) = div2 (S n) -> odd n.\nProof. hammer_hook \"Div2\" \"Div2.div2_odd\".  \ndestruct (even_or_odd n) as [Ev|Od]; trivial.\napply even_div2 in Ev. rewrite <- Ev. intro Ev'.\nsymmetry in Ev'. elim (n_Sn _ Ev').\nQed.\n\nHint Resolve even_div2 div2_even odd_div2 div2_odd: arith.\n\nLemma even_odd_div2 n :\n(even n <-> div2 n = div2 (S n)) /\\\n(odd n <-> S (div2 n) = div2 (S n)).\nProof. hammer_hook \"Div2\" \"Div2.even_odd_div2\".  \nsplit; split; auto using div2_odd, div2_even, odd_div2, even_div2.\nQed.\n\n\n\n\n\nNotation double := Nat.double (compat \"8.4\").\n\nHint Unfold double Nat.double: arith.\n\nLemma double_S n : double (S n) = S (S (double n)).\nProof. hammer_hook \"Div2\" \"Div2.double_S\".  \napply Nat.add_succ_r.\nQed.\n\nLemma double_plus n m : double (n + m) = double n + double m.\nProof. hammer_hook \"Div2\" \"Div2.double_plus\".  \napply Nat.add_shuffle1.\nQed.\n\nHint Resolve double_S: arith.\n\nLemma even_odd_double n :\n(even n <-> n = double (div2 n)) /\\ (odd n <-> n = S (double (div2 n))).\nProof. hammer_hook \"Div2\" \"Div2.even_odd_double\".  \nrevert n. fix 1. destruct n as [|[|n]].\n-\nsplit; split; auto with arith. inversion 1.\n-\nsplit; split; auto with arith. inversion_clear 1. inversion H0.\n-\ndestruct (even_odd_double n) as ((Ev,Ev'),(Od,Od')).\nsplit; split; simpl div2; rewrite ?double_S.\n+ inversion_clear 1. inversion_clear H0. auto.\n+ injection 1. auto with arith.\n+ inversion_clear 1. inversion_clear H0. auto.\n+ injection 1. auto with arith.\nQed.\n\n\n\nLemma even_double n : even n -> n = double (div2 n).\nProof. hammer_hook \"Div2\" \"Div2.even_double\".  exact (proj1 (proj1 (even_odd_double n))). Qed.\n\nLemma double_even n : n = double (div2 n) -> even n.\nProof. hammer_hook \"Div2\" \"Div2.double_even\".  exact (proj2 (proj1 (even_odd_double n))). Qed.\n\nLemma odd_double n : odd n -> n = S (double (div2 n)).\nProof. hammer_hook \"Div2\" \"Div2.odd_double\".  exact (proj1 (proj2 (even_odd_double n))). Qed.\n\nLemma double_odd n : n = S (double (div2 n)) -> odd n.\nProof. hammer_hook \"Div2\" \"Div2.double_odd\".  exact (proj2 (proj2 (even_odd_double n))). Qed.\n\nHint Resolve even_double double_even odd_double double_odd: arith.\n\n\n\nLemma even_2n : forall n, even n -> {p : nat | n = double p}.\nProof. hammer_hook \"Div2\" \"Div2.even_2n\".  \nintros n H. exists (div2 n). auto with arith.\nDefined.\n\nLemma odd_S2n : forall n, odd n -> {p : nat | n = S (double p)}.\nProof. hammer_hook \"Div2\" \"Div2.odd_S2n\".  \nintros n H. exists (div2 n). auto with arith.\nDefined.\n\n\n\nLemma div2_double n : div2 (2*n) = n.\nProof. hammer_hook \"Div2\" \"Div2.div2_double\".   apply Nat.div2_double. Qed.\n\nLemma div2_double_plus_one n : div2 (S (2*n)) = n.\nProof. hammer_hook \"Div2\" \"Div2.div2_double_plus_one\".   apply Nat.div2_succ_double. Qed.\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/Div2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.755519635608431}}
{"text": "Require Import Arith.\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n  intros.\n  apply plus_lt_compat_r.\n  exact H.\nQed.\n", "meta": {"author": "nolze", "repo": "coqex2014", "sha": "a9de850298c66865d7aff5c8bc91da32d696d661", "save_path": "github-repos/coq/nolze-coqex2014", "path": "github-repos/coq/nolze-coqex2014/coqex2014-a9de850298c66865d7aff5c8bc91da32d696d661/006.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.755511729173146}}
{"text": "(* Exercise 76 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nHypothesis Domain : exists x1 : D, exists x2 : D, exists x3 : D,\n  forall x : D, (x = x1 \\/ x = x2 \\/ x = x3).\n\nTheorem exercise_076 : (forall x : D, exists y : D, P x \\/ P y) -> exists x : D, P x.\nProof.\nexi_e (exists x1 : D, exists x2 : D, exists x3 : D,\n  forall x : D, (x = x1 \\/ x = x2 \\/ x = x3)) a a1.\n  hyp Domain.\nexi_e (exists x2 : D, exists x3 : D,\n  forall x : D, (x = a \\/ x = x2 \\/ x = x3)) b a2.\n  hyp a1.\nexi_e (exists x3 : D,\n  forall x : D, (x = a \\/ x = b \\/ x = x3)) c a3.\n  hyp a2.\nimp_i a4.\nexi_e (exists y:D, P a \\/ P y) d a5.\nall_e (forall x:D, exists y:D, P x \\/ P y) a.\nhyp a4.\ndis_e (P a \\/ P d) a6 a6.\nhyp a5.\nexi_i a.\nhyp a6.\ndis_e (d = a \\/ d = b \\/ d = c) a7 a7.\nall_e (forall x : D, x = a \\/ x = b \\/ x = c) d.\nhyp a3.\nexi_i d.\nhyp a6.\nexi_i d.\nhyp a6.\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_pred076.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7554922040750475}}
{"text": "(** * 리스트: 구조적 데이터를 가지고 작업하기 *)\n\nRequire Export Induction.\nModule NatList.\n\n(* ################################################################# *)\n(** * 숫자들의 쌍들 *)\n\n(** [Inductive] 정의에서 각 생성자는 어떤 개수의 인자들을 받을 수\n    있다. [true]와 [O]와 같이 인자를 받지 않는 생성자, [S]와 같이\n    하나의 인자를 받는 생성자가 있고, 다음 예에서 하나 이상을 받는\n    생성자를 보여준다. *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\n(** 이 선언을 읽는 법은 \"숫자들 쌍을 만드는 단 한 가지 방법이 있는데,\n    생성자 [pair]를 [nat] 타입의 두 인자들에 적용하는 것이다.\"  *)\n\nCheck (pair 3 5).\n\n(** 쌍에서 첫 번째와 두 번째 요소들을 꺼내는 두 개의 간단한 함수들이\n    있다.  이 정의들은 또한 두 개의 인자를 받은 생성자들에 대해 패턴\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\nCompute (fst (pair 3 5)).\n(* ===> 3 *)\n\n(** 쌍들은 상당히 자주 사용되기 때문에 [pair x y] 대신에 표준 수학\n    표기법 [(x,y)]으로 쓸 수 있으면 좋을 것이다. 콕에서 [Notation]\n    선언으로 가능하다. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** 쌍에 대한 새로운 표기법은 식과 패턴 매치에서 모두 사용될 수\n    있다. ([Basics] 장의 [minus] 함수의 정의에서 사실 이미\n    보았다. 표준 라이브러리 일부로 쌍에 대한 표기법도 제공하기 때문에\n    동작한 것이다. *)\n\nCompute (fst (3,5)).\n\nDefinition fst' (p : natprod) : nat :=\n  match p with\n  | (x,y) => x\n  end.\n\nDefinition snd' (p : natprod) : nat :=\n  match p with\n  | (x,y) => y\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(** 쌍들에 대한 몇 가지 간단한 사실들을 증명해보자.\n\n    특별한 방법으로 이 명제들을 서술하면 reflexivity (와 그리고 내장된\n    간략화) 만으로 증명들을 완성할 수 있다. *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\n(** 하지만 만일 보조 정리를 더 자연스러운 방법으로 서술하면\n    [reflexivity]만으로 충분하지 않다. *)\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* 아무것도 간략화되지 않는다! *)\nAbort.\n\n(** [p]의 구조를 드러내서 [simpl]로 [fst]와 [snd]에서의 패턴 매치를\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(** [nat] 타입의 값들을 가지고 다룰 때와 달리 [destruct]는 단 하나의 부분\n    목적 만을 만든다는 것을 주목하시오. [natprod] 타입의 값들은 한 가지 방법으로만\n    생성할 수 있기 때문이다. *)\n\n(** **** 연습문제: 별 하나 (snd_fst_is_swap)  *)\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 하나, 선택사항 (fst_swap_is_snd)  *)\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 숫자 리스트 *)\n\n(** 쌍에 대한 정의를 일반화하면 다음과 같이 숫자 _리스트_의 타입을\n    기술할 수 있다.  \"리스트는 비어있는 리스트이거나 숫자와 또 다른\n    리스트의 쌍이다.\" *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** 예를 들어, 세 개의 원소를 갖는 리스트가 여기 있다. *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** 쌍들을 다룰 때와 같이 익숙한 프로그래밍 표기법으로 리스트를 쓰는 것이 \n    더 편리하다. 다음 선언들로 [::]을 중위 표기 [cons]로 사용하고 \n    대괄호를 리스트를 만드는 \"바깥쪽을 감싸는\" 표기법으로 사용할 수 있다. *)\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(** 이 선언들을 자세하게 이해할 필요는 없지만 관심이 있다면 여기 대강\n    설명한다.  [right associativity] 주석을 달아 콕으로 하여금 [::]을\n    여러 번 사용한 식 들에서 괄호를 어떻게 씌울지 정한다. 예를 들어\n    다음 세 가지 선언들은 모두 동일한 의미를 갖는다. *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** [at level 60]은 [::]과 다른 중위 연산자를 함께 사용한 식들에서\n    괄호를 어떻게 매길지 정한다. 예를 들어, [+]를 [plus] 함수에 대한\n    중위 표기법으로 50 레벨로 정의하였기 때문에,\n\n  Notation \"x + y\" := (plus x y) (at level 50, left associativity).\n\n   [+] 연산자는 [::]보다 더 빨리 묶인다. 그래서 [1 + 2 :: [3]]은 콕이\n   우리가 기대한 대로 [(1 + 2) :: [3]]으로 해석하고, [1 + (2 ::\n   [3])]으로 해석하지 않는다.\n\n   (.v 파일에서 \"[1 + 2 :: [3]]\"와 같은 식을 읽을 때 조금 혼동스러울\n   수 있다. 3을 감싸는 안쪽 괄호는 리스트를 표시하지만, 바깥쪽\n   괄호(HTML에서 보이지 않는)는 \"coqdoc\" 도구가 텍스트가 아니라 콕\n   코드로 표시해야 한다는 명령어이다.)\n\n   위에서 두 번째와 세 번째 [Notation] 선언들은 리스트에 대한 표준\n   대괄호 표기법을 도입한다. 세 번째 선언의 오른편은 콕에서 n개를\n   나열하는 표기법을 사용하는 예시를 보여주고 이진 생성자들의 반복해서\n   내포된 형태로 변환되는 예를 설명한다. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Repeat *)\n\n(** 많은 함수들이 리스트를 다루기에 유용하다. 예를 들어, [repeat]\n    함수는 [n]과 [count]를 받아 모든 원소가 [n]이고 길이가 [count]인\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(** [length] 함수는 리스트의 길이를 계산한다. *)\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(** [app] 함수는 두 리스트들을 붙여 하나의 리스트를 만든다. *)\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(** 사실 [app]은 뒤이어 나올 어떤 부분에서 많이 사용될 것이다. 그래서\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\n(* ----------------------------------------------------------------- *)\n(** *** (기본 값을 지정한) Head와 Tail *)\n\n(** 리스트 프로그래밍의 두 가지 작은 예제가 있다. [hd] 함수는 인자로\n    주어진 리스트의 첫 번째 원소 (\"head\")를 반환하고 [tl] 함수는 첫\n    번째 원소를 제외한 모든 것 (\"tail\")을 리턴한다. 물론 비어 있는\n    리스트는 첫 번째 원소가 없기 때문에 그런 경우에 리턴할 기본 값을\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\n\n(* ----------------------------------------------------------------- *)\n(** *** 연습문제들 *)\n\n(** **** 연습문제: 별 두 개, 추천 (list_funs)  *)\n(** 아래의 [nonzero], [oddmembers], [countoddmembers] 정의를\n    완성하시오.  이 함수들이 하는 일을 이해하기 위해 테스트들을 살펴\n    보시오. *)\n\nFixpoint nonzeros (l:natlist) : natlist\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  (* 여기를 채우시오 *) Admitted.\n\nFixpoint oddmembers (l:natlist) : natlist\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\n  (* 여기를 채우시오 *) Admitted.\n\nDefinition countoddmembers (l:natlist) : nat\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 고급 (alternate)  *)\n(** 두 리스트를 \"지퍼로 잠그는 방식\"으로 첫 번째 리스트에서 취한\n    원소들과 두 번째 리스트에서 취한 원소들 사이를 번갈아 가며 하나의\n    리스트로 만들도록 [alternate]를 완성하시오.\n\n    [alternate]를 자연스럽고 우아하게 작성하려면 콕에서 요구하는 모든\n    [Fixpoint] 정의들이 \"분명하게 종료해야 한다\"는 점을 만족시키지\n    못할 것이다. 그 대신 두 리스트들의 원소들을 동시에 고려하는 조금\n    더 긴 해법을 찾아보시오. (한 가지 가능한 해는 새로운 종류의 쌍들을\n    정의하는 것인데 이 것이 유일한 방법은 아니다.  *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_alternate2:\n  alternate [1] [4;5;6] = [1;4;5;6].\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_alternate3:\n  alternate [1;2;3] [4] = [1;4;2;3].\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** 리스트로 표현한 가방(bags) 자료 구조 *)\n\n(** [bag] (또는 [multiset])은 집합과 같다. 다만, 각 원소가 단 한 번이\n    아니라 여러 번 나타날 수 있다는 점이 다르다. 숫자들을 담은 가방\n    자료 구조를 표현하는 한 가지 가능한 구현은 리스트를 사용하는\n    것이다.  *)\n\nDefinition bag := natlist.\n\n(** **** 연습문제: 별 세 개, 추천 (bag_functions)  *)\n(** 가방 자료 구조를 다루는 [count], [sum], [add], [member] 함수들의\n    정의를 완성하시오. *)\n\nFixpoint count (v:nat) (s:bag) : nat\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\n(** 아래 증명들은 모두 [reflexivity]만 사용해도 증명할 수 있다. *)\n\nExample test_count1:              count 1 [1;2;3;1;4;1] = 3.\n (* 여기를 채우시오 *) Admitted.\nExample test_count2:              count 6 [1;2;3;1;4;1] = 0.\n (* 여기를 채우시오 *) Admitted.\n\n(** 중복 집합 [sum]은 집합 [union]과 유사하다. [sum a b]는 [a]와 [b]의\n    모든 원소들을 포함한다. (수학자들은 대개 중복 집합에 대한\n    [union]을 sum 대신 max를 사용하여 조금 다르게 정의한다. 이 연산에\n    대해 [union]이라고 부르지 않는 이유이다. [sum]의 정의에서 인자\n    이름을 명시적으로 주지 않고 작성하고 있다. 더욱이 [Fixpoint] 대신\n    [Definion] 키워드를 사용한다.  따라서 그 인자들 이름을 지었더라도\n    재귀 방식으로 다룰 수 없을 것이다. 이런 식으로 문제를 제시하는\n    의도는 스스로 [sum]이 다른 방식으로 구현될 수 있는지 생각해보라는\n    것이다. 아마도 이미 정의했던 함수들을 사용할 수 있다.  *)\n\nDefinition sum : bag -> bag -> bag\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_sum1:              count 1 (sum [1;2;3] [1;4;1]) = 3.\n (* 여기를 채우시오 *) Admitted.\n\nDefinition add (v:nat) (s:bag) : bag\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_add1:                count 1 (add 1 [1;4;1]) = 3.\n (* 여기를 채우시오 *) Admitted.\nExample test_add2:                count 5 (add 1 [1;4;1]) = 0.\n (* 여기를 채우시오 *) Admitted.\n\nDefinition member (v:nat) (s:bag) : bool\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_member1:             member 1 [1;4;1] = true.\n (* 여기를 채우시오 *) Admitted.\n\nExample test_member2:             member 2 [1;4;1] = false.\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 선택사항 (bag_more_functions)  *)\n(** 여기 가방 자료 구조를 다루는 함수들이 있으니 연습해보시오.  *)\n\n(** remove_one을 제거할 숫자를 포함하지 않는 가방 자료 구조에 적용하면 \n    동일한 가방을 변경하지 않고 반환해야 한다. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_remove_one1:\n  count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_remove_one2:\n  count 5 (remove_one 5 [2;1;4;1]) = 0.\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_remove_one3:\n  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  (* 여기를 채우시오 *) Admitted.\n\nExample test_remove_one4:\n  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  (* 여기를 채우시오 *) Admitted.\n\nFixpoint remove_all (v:nat) (s:bag) : bag\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n (* 여기를 채우시오 *) Admitted.\nExample test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.\n (* 여기를 채우시오 *) Admitted.\nExample test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n (* 여기를 채우시오 *) Admitted.\nExample test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n (* 여기를 채우시오 *) Admitted.\n\nFixpoint subset (s1:bag) (s2:bag) : bool\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_subset1:              subset [1;2] [2;1;4;1] = true.\n (* 여기를 채우시오 *) Admitted.\nExample test_subset2:              subset [1;2;2] [2;1;4;1] = false.\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 추천 (bag_theorem)  *)\n(** 함수 [count]와 [add]와 관련된 가방 자료 구조에 대한 흥미로운 정리\n    [bag_theorem]를 작성하고 증명하시오. 이 것은 열린 문제이기 때문에\n    참인 정리이지만 증명하기 위해서 아직 배우지 않은 방법이 필요할\n    수도 있다.  막히면 자유롭게 질문하시오! *)\n\n(*\nTheorem bag_theorem : ...\nProof.\n  ...\nQed.\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * 리스트에 대한 추론 *)\n\n(** 숫자들을 다루었을 때처럼 리스트 처리 함수들에 대한 간단한 사실들은\n    종종 간략화를 통해 완전히 증명할 수 있다. 예를 들어,\n    [reflexivity]로 간략화를 수행하면 아래 정리를 충분히 증명할 수\n    있다...  *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\n(** ... 왜냐하면 [[]]을 [app] 정의에서 match로 조사할 식으로 대체해서\n    그 매치 자체가 간략화되기 때문이다. *)\n\n(** 그리고 숫자들에 대해서와 같이 알려지지 않은 리스트의 가능한 형태에\n    관해 경우 별로 분석하는 것이 도움이 될 수 있다. *)\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(** 여기 [nil]의 경우 [tl nil = nil]로 정의하였기 때문에 증명할 수\n    있다.  [destruct] 전술에 [as] 주석으로 [n]과 [l'] 이름들을 여기\n    도입한다.  리스트에 대한 [cons] 생성자의 두 인자들(리스트의 머리와\n    꼬리)에 이 이름들을 붙인다. *)\n\n(** 비록 리스트에 대한 흥미로운 정리들을 증명하려면 대개 귀납법이\n    필요하다. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** 짧은 설교 *)\n\n(** 예제 증명 스크립트들을 읽기만 하면 제대로 이해하지 못할 것이다!\n    콕을 사용하고 각 단계가 얻는 바를 생각하면서 각 증명의 상세 내용을\n    따라가는 것이 중요하다.  그렇지 않으면 증명들을 시작할 때\n    연습문제들은 아무런 의미가 없을 것이 분명하다.  충분히\n    얘기했다. *)\n\n(* ================================================================= *)\n(** ** 리스트에 대한 귀납법 *)\n\n(** [natlist] 같은 자료형들에 대한 귀납법으로 증명하는 것은 자연수에\n    대한 귀납법 보다 조금 덜 익숙 할 수 있지만 아이디어는 똑같이\n    간단하다. 각 [Inductive] 선언은 선언한 생성자들을 사용하여 만들 수\n    있는 데이터 값들의 집합을 정의한다. 부울형은 [true] 또는\n    [false]이고 숫자는 [O]와 [S]를 다른 숫자에 적용한 것이고, 리스트는\n    [nil] 또는 숫자와 리스트에 적용한 [cons]이다.\n\n    더욱이 선언한 생성자들을 다른 것에 적용하는 것만이 유일하게\n    귀납적으로 정의한 집합의 원소들이 가질 수 있는 _유일하게_ 가능한\n    모양이다. 그리고 이러한 사실을 통해 귀납적으로 정의된 집합들에\n    대해 유추하는 방법을 직접적으로 제공한다. 숫자는 [O]이거나 그렇지\n    않으면 [S]를 _더 작은_ 숫자에 적용한 것이고, 리스트는 [nil]이거나\n    그렇지 않으면 [cons]를 어떤 숫자와 어떤 _더 작은_ 리스트에 적용한\n    것이며, 등등. 그래서 리스트 [l]을 언급하는 어떤 명제 [P]가 있고,\n    _모든_ 리스트에 대해 [P]가 성립한다고 주장하고 싶다면 다음과 같이\n    추론할 수 있다.\n\n      - 첫째, [l]이 [nil] 일 때 [P]가 참이라고 증명하시오.\n\n      - 그런 다음 [l]이 어떤 숫자 [n]과 어떤 작은 리스트 [l']에 대한\n        [cons n l'] 일 때, [P]가 [l']에 대해 참이라고 가정하에 [P]가\n        참임을 보이시오.\n\n    더 큰 리스트는 오직 더 작은 리스트들 (궁극적으로 [nil]에 도달할 것인)로\n    만들기 때문에 이 두 주장들을 합하면 [P]가 모든 리스트 [l]에 대해 참이라는\n    것을 증명한다. 여기 구체적인 예가 있다. *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** 자연수에 대한 귀납법을 적용할 때처럼 [induction] 전술에서 [cons]\n    경우에 [as...] 절로 더 작은 리스트 [l1']에 해당하는 귀납 가정에\n    이름을 붙인다. 다시 한번 반복하면, 이 콕 증명은 고정된 형태로\n    작성한 문서로 보아서는 더욱 안된다. 대화식 콕 세션에서 증명을 읽고\n    있다면 무엇이 진행되고 있는지 쉽게 알 수 있고 현재 목적과 문맥을\n    각 지점에서 볼 수 있다. 하지만 이러한 상태는 콕 증명으로 작성한\n    부분에서는 드러나 있지 않다. 그래서 사람을 위해서 작성한 자연어로\n    서술된 증명은 더 명백한 이정표를 포함할 필요가 있을 것이다. 특히\n    두 번째 경우에 귀납적 가정이 무엇인지 독자들에게 정확히\n    환기시킨다면 증명의 흐름을 잃지 않도록 유지하는데 도움이 될\n    것이다. *)\n\n(** 비교를 위해 여기 동일한 정리를 비형식적으로 증명해본다. *)\n\n(** _정리_: 모든 리스트 [l1], [l2], [l3]에 대하여,\n   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].\n\n   _증명_: [l1]에 관한 귀납법에 의하여.\n\n   - 첫째, [l1 = []]라 가정하자.  다음을 증명해야 한다.\n\n       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),\n\n     [++] 정의에 의해 바로 성립한다.\n\n   - 다음은, 아래 등식이 성립하는 [l1 = n::l1']을 가정하자.\n\n       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)\n\n     (귀납 가정). 다음 등식이 성립함을 보여야 한다.\n\n       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).\n\n     [++] 정의와 아래 등식에 의해 성립한다.\n\n       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),\n\n     위 등식은 귀납 가정에 의해 바로 성립한다.  [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** 리스트 뒤집기 *)\n\n(** 리스트에 대한 조금 더 어려운 귀납 증명의 예에 대해 리스트 뒤집는\n    함수 [rev]를 [app]를 사용해서 정의한다고 가정하자. *)\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(** *** [rev]의 성질들 *)\n\n(** 새롭게 정의한 [rev]에 대한 몇 가지 정리들을 이제\n    증명해보자. 지금까지 본 것보다 조금 더 도전적인 증명으로 리스트를\n    뒤집으면 그 길이가 달라지지 않는다는 것을 증명하자.  처음\n    귀납법으로 증명해보면 비어있지 않는 리스트의 경우에서 막힌다... *)\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    (* 이 것은 까다로운 경우이다. 그동안 증명해온 것과 같이 간략화로 시작해보자. *)\n    simpl.\n    (* 이제 막힌 것처럼 보인다. 이 목적은 [++]를 포함한 등식이지만\n       현재 문맥이나 전역 환경에서 증명에 유용한 등식이 없다! IH를 사용해서\n       현재 목적을 다시 작성하면 약간 증명을 진행할 수 있다...  *)\n    rewrite <- IHl'.\n    (* ... 하지만 이제 더이상 나아갈 수 없다. *)\nAbort.\n\n(** [++]와 [length]를 연관 짓는 등식을 취하자. 이 등식으로 증명을\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  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\n(** 이 보조 정리를 가능한 일반화시키기 위해, [rev] 적용 결과에 대한\n    것이 아닌 _모든_ [natlist]들에 대해 한정사를 두었다. 이 목적이\n    참인지 여부는 분명히 뒤집을 리스트에 의존하지 않기 때문에 이렇게\n    한정사를 두는 것이 자연스럽다. 더욱이 더 일반적인 성질을 증명하기\n    더 쉽다. *)\n\n(** 이제 원래 증명을 완성할 수 있다. *)\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(** 비교를 위해 두 정리들을 비형식적으로 증명한 것이 여기 있다.\n\n    _정리_: 모든 리스트 [l1]과 [l2]에 대해 \n       [length (l1 ++ l2) = length l1 + length l2].\n\n    _증명_: [l1]에 대한 귀납법에 의해.\n\n    - 첫째, [l1 = []]을 가정하자.  다음을 증명하자.\n\n        length ([] ++ l2) = length [] + length l2,\n\n      [length]와 [++]의 정의들로 부터 바로 보일 수 있다.\n\n    - 다음으로, 아래 등식과 함께 [l1 = n::l1']을 가정하자.\n\n        length (l1' ++ l2) = length l1' + length l2.\n\n      다음을 증명해야 한다.\n\n        length ((n::l1') ++ l2) = length (n::l1') + length l2).\n\n      [length]와 [++] 정의들과 귀납 가정과 함께 바로 보일 수 있다. [] *)\n\n(** _정리_: 모든 리스트 [l]에 대해, [length (rev l) = length l].\n\n    _증명_: [l]에 관한 귀납법에 의해.\n\n      - 첫째, [l = []]를 가정하자.  다음 등식을 증명해야 한다.\n\n          length (rev []) = length [],\n\n        이 등식은 [length]와 [rev] 정의들에서 직접 유도할 수 있다.\n\n      - 다음으로, 아래 등식과 함께 [l = n::l']를 가정하자\n\n          length (rev l') = length l'.\n\n        다음 등식을 증명해야 한다.\n\n          length (rev (n :: l')) = length (n :: l').\n\n        [rev] 정의에 의해, 위 등식은 아래 등식으로 증명할 수 있는데,\n\n          length ((rev l') ++ [n]) = S (length l')\n\n        이전 보조 정리에 의해 이 등식은 아래 등식과 동일하다.\n\n          length (rev l') + length [n] = S (length l').\n\n        동일한 이 등식은 귀납 가정과 [length] 정의에 의해 바로 보일 수 있다. *)\n\n(** 이 증명들 스타일은 꽤 지루하고 현학적이다. 이 증명들 처음 두\n    세 개를 살펴보면, 상세한 내용이 적은 (머리 속으로 또는 필요하다면\n    메모 용지에 쉽게 작성할 수 있는) 그리고 중요한 단계들만 강조하는\n    증명들을 따라가기가 더 쉽다는 것을 발견할 수 있다. 이런 더 압축된\n    스타일로 위 증명을 다시 작성하면 다음과 같이 보일 것이다.  *)\n\n(** _정리_: 모든 리스트 [l], [length (rev l) = length l]에 대해.\n\n    _증명_: 첫째, 어떤 [l]에 대해 [length (l ++ [n]) = S (length\n     l)]이다.  ([l]에 대한 직접적인 귀납 증명으로 보일 수 있다.)\n\n     그 주요 성질은, [l = n'::l'] 경우의 귀납 가정과 함께 위 등식을\n     사용하여 [l]에 대한 귀납법으로 다시 보일 수 있다. *)\n\n(** 주어진 상황에서 어느 스타일이 더 좋은지는 기대하는 독자의 교육\n    정도와 독자가 이미 익숙한 증명과 얼마나 비슷한지에 따라 다르다. 더\n    현학적인 스타일이 현재 목적을 위한 좋은 초기 설정이다. *)\n\n(* ================================================================= *)\n(** ** [Search] *)\n\n(** 예를 들어 [rewrite]를 사용하여, 이미 증명한 다른 정리들을 이용하여\n    증명하는 것을 보았다.  그러나 어떤 정리를 참조하기 위해 이름을 알\n    필요가 있다! 정말로 이전에 증명한 정리들을 기억하는 것 조차 종종\n    어렵고 또한 그 정리들의 이름들은 더 기억하기 어렵다.\n\n    콕의 [Search] 명령은 이럴 때 꽤 도움이 된다. [Search foo]를 치면 콕은 [foo]가\n    포함된 모든 정리들의 목록을 보여줄 것이다. 예를 들어, [rev]에 대해 증명했던 정리들의\n    목록을 보기 위해서 다음 주석을 제거해보라. *)\n\n  Search rev. \n\n(** 다음 연습문제들을 풀 때 그리고 이 책을 읽는 동안 [Search]를\n    기억하라. 왜냐하면 많은 시간을 절약하게 해줄 것이기 때문이다!\n\n    프룹제너럴(ProofGeneral)을 사용하면 [C-C C-a C-a]를 가지고\n    [Search]를 실행할 수 있다. [C-c C-;] 명령어로 그 결과를 버퍼로\n    옮겨올 수 있다. *)\n\n(* ================================================================= *)\n(** ** 리스트 연습문제들, 파트 1 *)\n\n(** **** 연습문제: 별 세 개 (list_exercises)  *)\n(** 리스트에 대한 추가 연습: *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem rev_app_distr: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\n(** 다음 연습문제에 대한 짧은 해가 있다. 증명이 엉키면 뒤로 물러나서\n    더 간단한 방법을 찾아보려고 노력해보라. *)\n\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\n(** [nonzeros]의 구현에 대한 연습문제: *)\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개 (beq_natlist)  *)\n(** [beq_natlist] 정의를 채우시오. 이 함수는 두 리스트의 숫자들이 같은\n    지 비교한다. 모든 리스트 [l]에 대해 [beq_natlist l l]는 [true]를\n    냄을 증명하시오.  *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n (* 여기를 채우시오 *) Admitted.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\n(* 여기를 채우시오 *) Admitted.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n (* 여기를 채우시오 *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 리스트 연습문제들, 파트 2 *)\n\n(** **** 연습문제: 별 세 개, 고급 (bag_proofs)  *)\n(** 위의 가방 자료구조에 대해 정의들에 관하여 증명하는 한 두 가지 작은\n    정리들이 있다. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\n(** [leb]에 대한 다음 보조 정리는 다음 증명에 도움이 될 수도 있다. *)\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - (* 0 *)\n    simpl.  reflexivity.\n  - (* S n' *)\n    simpl.  rewrite IHn'.  reflexivity.  Qed.\n\nTheorem remove_decreases_count: forall (s : bag),\n  leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개, 선택사항 (bag_count_sum)  *)\n(** 함수 [count]와 [sum]을 사용하는 가방 자료 구조에 대한 정리\n    [bag_count_sum]을 흥미롭게 작성하고 증명해보시오. ([count]를\n    정의하는 법에 따라 그 증명이 어려울 수도 있다!)  *)\n(* 여기를 채우시오 *)\n(** [] *)\n\n(** **** 연습문제: 별 네 개, 고급 (rev_injective)  *)\n(** [rev] 함수가 단사 함수임을 증명하시오. 즉,\n\n    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n\n(어렵게 증명하는 방법과 쉽게 증명하는 방법이 있다.) *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(* ################################################################# *)\n(** * 선택사항들 *)\n\n(** 어떤 리스트의 [n]번째 원소를 반환하는 함수를 작성한다고\n    가정하자. 그 함수의 타입을 [nat -> natlist -> nat]로 하면 리스트가\n    너무 짧을 때 리턴할 어떤 숫자를 선택해야 할 것이다...  *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* arbitrary! *)\n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => nth_bad l' (pred n)\n               end\n  end.\n\n(** 위 정의는 그다지 좋지 않다. 왜냐하면 [nth_bad]가 [42]를 반환하면\n    입력 리스트에 값이 실제로 나타나는지 추가 처리 없이 구분할 수 없기\n    때문이다.  더 나은 대응 방법은 [nth_bad]의 반환 타입을 변경해서\n    가능한 결과 중 하나로 에러 값을 포함시키는 것이다. 이러한 타입을\n    [natoption]이라고 부른다. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** 위 [nth_bad] 정의를 변경해서 리스트가 너무 짧을 때 [None]를\n    반환하고 리스트가 충분한 원소들로 구성되어 [n] 위치에 [a]가 나타날\n    때 [Some a]를 리턴할 수 있다. 이 새로운 함수를 [nth_error]으로\n    이름 지어 에러를 결과로 낼 수 있음을 나타낸다.  *)\n\nFixpoint nth_error (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => match beq_nat n O with\n               | true => Some a\n               | false => nth_error l' (pred n)\n               end\n  end.\n\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof. reflexivity. Qed.\n\n(** (In the HTML version, the boilerplate proofs of these\n    examples are elided.  Click on a box if you want to see one.)\n\n    This example is also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional\n    expressions... *)\n\n\nFixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' => if beq_nat n O then Some a\n               else nth_error' l' (pred n)\n  end.\n\n(** 콕의 조건식은 다른 언어의 조건식과 한 가지 작은 일반화를 제외하고\n    정확히 똑같다.  부울이 기본으로 제공되는 타입이 아니기 때문에\n    실제로 콕은 정확히 두 가지 생성자들을 가지고 _어떤_ 귀납적으로\n    정의한 타입에 대한 조건식을 지원한다. 조건식을 계산해서\n    [Inductive] 정의의 첫 번째 생성자가 나오면 참이고, 두 번째\n    생성자가 나오면 거짓이라고 간주한다. *)\n\n(** 아래 함수는 [natopion]에서 [nat]을 꺼내고 [None] 경우에 제공된\n    기본 값을 반환한다. *)\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n(** **** 연습문제: 별 두 개 (hd_error)  *)\n(** 동일한 아이디어를 사용하여 초기 [hd] 함수를 [nil] 경우에 기본\n    원소를 전달하지 않아도 되도록 수정하시오.  *)\n\nDefinition hd_error (l : natlist) : natoption\n  (* 이 줄을 \":= 로 시작하는 정의\"로 바꾸시오. *). Admitted.\n\nExample test_hd_error1 : hd_error [] = None.\n (* 여기를 채우시오 *) Admitted.\n\nExample test_hd_error2 : hd_error [1] = Some 1.\n (* 여기를 채우시오 *) Admitted.\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 하나, 선택사항 (option_elim_hd)  *)\n(** 이 연습문제는 새로운 함수 [hd_error]를 예전 함수 [hd]와 연관짓는다. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\nEnd NatList.\n\n(* ################################################################# *)\n(** * 부분 맵 *)\n\n(** 콕에서 어떤 자료 구조를 정의할 수 있는지 설명하는 마지막 예로\n    간단한 _부분 맵_ 자료 타입이 있다. 대부분의 프로그래밍언어에 있는\n    맵이나 딕셔너리 자료 구조와 유사하다. *)\n\n(** 첫째, 새로운 귀납적 자료형 [id]를 정의해서 부분 맵의 \"키\"로 사용한다. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\n(** 내부적으로 [id]는 단지 숫자이다. 각 숫자를 [Id] 태그로 감싸 별도의\n    타입을 도입하면 정의들이 더 읽기 좋고 나중에 우리가 원하면 표현을\n    변경시킬 수 있는 유연성을 제공한다.\n\n    [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: 1 star (beq_id_refl)  *)\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 이제 부분 맵의 타입을 정의한다: *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** 이 선언을 다음과 같이 읽을 수 있다. \"[partial_map]을 만드는 두\n    가지 방법이 있다. [empty] 생성자를 사용하여 비어 있는 부분 맵을\n    표현하거나 [record] 생성자를 키와 값과 다른 [partial_map]에\n    적용하여 기존 부분 맵에 키와 값 매핑을 추가하여 [partial_map]을\n    만든다.\" *)\n\n(** [update] 함수는 부분 맵에서 주어진 키에 대한 내용을 바꾸거나\n    주어진 키가 아직 없으면 새로운 내용을 추가한다.  *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\n(** 마지막으로 [find] 함수는 [partial_map]에서 주어진 키를 탐색한다.\n    그 키를 찾지 못하면 [None]를 반환하고, 그 키와 [val]이 연관되어\n    있다면 [Some val]을 리턴한다. 만일 같은 키가 여러 값들에 매핑되어\n    있으면 [find]는 첫 번째로 만나는 것을 반환할 것이다. *)\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(** **** 연습문제: 별 하나 (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 (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 하나 (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false -> find x (update d y o) = find x d.\nProof.\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\nEnd PartialMap.\n\n(** **** 연습문제: 별 두 개 (baz_num_elts)  *)\n(** 아래의 귀납적 정의를 고려하자: *)\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(** [baz] 타입은 _몇 개_의 원소들을 가지고 있는가? (영어로 답하거나\n    당신의 언어로 답하시오.)\n\n(* 여기를 채우시오 *)\n*)\n(** [] *)\n\n(** $Date: 2017-08-24 10:54:05 -0400 (Thu, 24 Aug 2017) $ *)\n\n\n\n(* Local Variables: *)\n(* coq-prog-name: \"/Applications/CoqIDE_8.6.1.app/Contents/Resources/bin/coqtop\" *)\n(* coq-load-path: nil *)\n(* End: *)\n", "meta": {"author": "kwanghoon", "repo": "sf", "sha": "6937265f0ba88524af8a5e0da1cb19d49c079875", "save_path": "github-repos/coq/kwanghoon-sf", "path": "github-repos/coq/kwanghoon-sf/sf-6937265f0ba88524af8a5e0da1cb19d49c079875/Lists_ko_utf8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.7554193612106286}}
{"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 (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\nExample test_aeval1:\n  aeval (APlus (ANum 2) (ANum 2)) = 4.\nProof. reflexivity. Qed.\n\nFixpoint beval (b : bexp) : bool :=\n  match b 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 (a:aexp) : aexp :=\n  match a with\n    | ANum n => ANum n\n    | APlus (ANum 0) e2 => optimize_0plus e2\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\nExample 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).\nProof. reflexivity. Qed.\n\nTheorem optimize_0plus_sound :\n  forall a,\n    aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  induction a.\n  Case \"ANum\". reflexivity.\n  Case \"APlus\".\n    destruct a1.\n    SCase \"a1 = ANum n\".\n      destruct n.\n      SSCase \"n = 0\". simpl. apply IHa2.\n      SSCase \"n <> 0\". simpl. rewrite IHa2. reflexivity.\n    SCase \"a1 = APlus a1_1 a1_2\".\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n    SCase \"a1 = AMinus a1_1 a1_2\".\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n    SCase \"a1 = AMult a1_1 a2_2\".\n      simpl. simpl in IHa1. rewrite IHa1.\n      rewrite IHa2. reflexivity.\n  Case \"AMinus\".\n    simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  Case \"AMult\".\n    simpl. rewrite IHa1. rewrite IHa2. reflexivity.\nQed.\n\nTheorem optimize_0plus_sound' :\n  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  Case \"APlus\".\n    destruct a1;\n    try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    SCase \"a1 = ANum n\".\n      destruct n;\n      simpl; rewrite IHa2; reflexivity.\nQed.\n\nTactic Notation \"aexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"ANum\" | Case_aux c \"APlus\"\n    | Case_aux c \"AMinus\" | Case_aux c \"AMult\" ].\n\nTheorem optimize_0plus_sound'' :\n  forall a,\n    aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  aexp_cases (induction a) Case;\n    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n    try reflexivity.\n  Case \"APlus\".\n    aexp_cases (destruct a1) SCase;\n    try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    SCase \"ANum\".\n      destruct n;\n      simpl; rewrite IHa2; reflexivity.\nQed.\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    | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n    | BNot b1 => BNot (optimize_0plus_b b1)\n    | BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)\n  end.\n\nTactic Notation \"bexp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"BTrue\" | Case_aux c \"BFalse\"\n    | Case_aux c \"BEq\" | Case_aux c \"BLe\"\n    | Case_aux c \"BNot\" | Case_aux c \"BAnd\" ].\n\nTheorem optimize_0plus_b_sound :\n  forall b,\n    beval (optimize_0plus_b b) = beval b.\nProof.\n  intros b.\n  bexp_cases (induction b) Case;\n    try reflexivity;\n    try (simpl; repeat (rewrite optimize_0plus_sound); reflexivity);\n    try (simpl; rewrite IHb; reflexivity);\n    try (simpl; rewrite IHb1; rewrite IHb2; reflexivity).\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/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7553471559283838}}
{"text": "Require Import PeanoNat.\nInductive multiple_of_3 : nat -> Prop :=\n  | O_multiple : multiple_of_3 O\n  | SSS_multiple n (H : multiple_of_3 n) : multiple_of_3 (S (S (S n))).\n\nInductive multiple_of_3' : nat -> Prop :=\n  | thirty_multiple : multiple_of_3' 30\n  | twenty_one_multiple : multiple_of_3' 21\n  | sum_multiple n m (H : multiple_of_3' n) (H' : multiple_of_3' m) : multiple_of_3' (n + m)\n  | difference_multiple l n m (H : multiple_of_3' n) (H' : multiple_of_3' m) (H'' : l + n = m) : multiple_of_3' l.\n\nLemma zero' : multiple_of_3' 0.\n  Proof.\n    apply (difference_multiple 0 21 21).\n    apply twenty_one_multiple.\n    apply twenty_one_multiple.\n    simpl.\n    reflexivity.\n    Qed.\n\nLemma three' : multiple_of_3' 3.\n  Proof.\n    apply (difference_multiple 3 9 12).\n    apply (difference_multiple 9 21 30).\n    constructor.\n    constructor.\n    simpl.\n    reflexivity.\n    apply (difference_multiple 12 9 21).\n    apply (difference_multiple 9 21 30).\n    constructor.\n    constructor.\n    simpl.\n    reflexivity.\n    constructor.\n    simpl.\n    reflexivity.\n    simpl.\n    reflexivity.\n  Qed.\n\nLemma all' : forall n : nat, multiple_of_3' n -> multiple_of_3' (S (S (S n))).\n  Proof.\n    intros.\n    assert (forall x : nat, S (S (S x)) = x + 3).\n      intro.\n      rewrite Nat.add_comm.\n      unfold \"+\".\n      reflexivity.\n    rewrite H0.\n    apply (sum_multiple n 3).\n    assumption.\n    apply three'.\nQed.\n\nTheorem multiple_of_3_iff_multiple_of_3' :\n  forall n, multiple_of_3 n <-> multiple_of_3' n.\nProof.\n  intros.\n  split.\n  intros.\n  induction H.\n  apply zero'.\n  apply (sum_multiple _ _ three' IHmultiple_of_3).\n  intros.\n  induction H.\n  repeat constructor.\n  repeat constructor.\n  induction IHmultiple_of_3'1.\n  simpl.\n  exact IHmultiple_of_3'2.\n  simpl.\n  constructor.\n  apply IHIHmultiple_of_3'1.\n  refine (difference_multiple n 3 (S (S (S n))) three' H _).\n  rewrite Nat.add_comm.\n  simpl.\n  reflexivity.\n  generalize dependent m.\n  generalize dependent l.\n  intros.\n\n\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/multiples3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7552974984184483}}
{"text": "Require Import Setoid.\n\n(* Derived from https://people.cs.umass.edu/~arjun/courses/cs691pl-spring2014/assignments/groups.html,\n   but without any automation. *)\n\nSection Group.\n\n(* The set of the group. *)\nVariable G : Set.\n\n(* The binary operator. *)\nVariable f : G -> G -> G.\nInfix \"*\" := f (at level 40, left associativity).\n\n(* The group identity. *)\nVariable e : G.\n\n(* The inverse operator. *)\nVariable i : G -> G.\n\n(* The operator [f] is associative. *)\nVariable assoc : forall (a b c : G), (a * b) * c = a * (b * c).\n\n(* [e] is the left-identity for all elements [a]. *)\nVariable id_l : forall (a : G), e * a = a.\n\n(* [i a] is the left-inverse of [a]. *)\nVariable inv_l : forall (a : G), i a * a = e.\n\n(* Theorems in group theory. *)\n\n(* The identity [e] is unique. *)\nTheorem e_unique :\n  forall (a : G), a * a = a -> a = e.\nProof.\n  intros.\n  rewrite <- (id_l a) at 1.\n  rewrite <- (inv_l a).\n  rewrite assoc.\n  rewrite H. auto.\nQed.\n\n(* [i a] is the right-inverse of [a]. *)\nTheorem inv_r :\n  forall (a : G), a * i a = e.\nProof.\n  intros.\n  apply e_unique.\n  rewrite assoc. rewrite <- (assoc (i a) a (i a)).\n  rewrite inv_l.\n  rewrite id_l. auto.\nQed.\n\n(* [e] is the right-identity. *)\nTheorem id_r :\n  forall (a : G), a * e = a.\nProof.\n  intros.\n  rewrite <- (inv_l a).\n  rewrite <- assoc.\n  rewrite inv_r, id_l.\n  auto.\nQed.\n\n(* [x] can be cancelled on the left. *)\nTheorem cancel_l :\n  forall (a b x : G), x * a = x * b -> a = b.\nProof.\n  intros.\n  rewrite <- (id_l a), <- (id_l b).\n  rewrite <- (inv_l x).\n  rewrite assoc, assoc.\n  rewrite H.\n  auto.\nQed.\n\n(* [x] can be cancelled on the right. *)\nTheorem cancel_r :\n  forall (a b x : G), a * x = b * x -> a = b.\nProof.\n  intros.\n  rewrite <- (id_r a), <- (id_r b).\n  rewrite <- (inv_r x).\n  rewrite <- assoc, <- assoc.\n  rewrite H.\n  auto.\nQed.\n\n(* The left identity is unique. *)\nTheorem e_uniq_l :\n  forall (a x : G), x * a = a -> x = e.\nProof.\n  intros.\n  apply (cancel_r _ _ a).\n  rewrite id_l.\n  auto.\nQed.\n\n(* The left inverse is unique. *)\nTheorem inv_uniq_l :\n  forall (a b : G), a * b = e -> a = i b.\nProof.\n  intros.\n  apply (cancel_r _ _ (b * e)).\n  rewrite <- assoc, <- assoc.\n  rewrite H, id_l, inv_l.\n  rewrite id_l.\n  auto.\nQed.\n\n(* The left identity is unique. *)\nTheorem e_uniq_r :\n  forall (a x : G), a * x = a -> x = e.\nProof.\n  intros.\n  apply (cancel_l _ _ a).\n  rewrite id_r.\n  auto.\nQed.\n\n(* The right inverse is unique. *)\nTheorem inv_uniq_r :\n  forall (a b : G), a * b = e -> b = i a.\nProof.\n  intros.\n  apply (cancel_l _ _ (e * a)).\n  rewrite assoc, assoc.\n  rewrite H, id_r, inv_r.\n  rewrite id_r.\n  auto.\nQed.\n\n(* The inverse operator distributes over the group operator. *)\nTheorem inv_distr :\n  forall (a b : G), i (a * b) = i b * i a.\nProof.\n  intros. symmetry.\n  apply inv_uniq_l.\n  rewrite assoc. rewrite <- (assoc (i a) a b).\n  rewrite inv_l.\n  rewrite id_l.\n  rewrite inv_l.\n  auto.\nQed.\n\n(* The inverse of an inverse produces the original element. *)\nTheorem double_inv : forall (a : G), i (i a) = a.\nProof.\n  intros. symmetry.\n  apply inv_uniq_l.\n  apply inv_r.\nQed.\n\n(* The identity is its own inverse. *)\nTheorem id_inv : i e = e.\nProof.\n  intros. symmetry.\n  apply inv_uniq_l.\n  apply id_l.\nQed.\n\nTheorem inv_a_eq_a_implies_abelian :\n  (forall (a : G), a = i a) -> forall (x y : G), x * y = y * x.\nProof.\n  intros.\n  pose proof (H x) as H1.\n  pose proof (H y) as H2.\n  pose proof (H (y * x)) as H3.\n  rewrite inv_distr in H3.\n  rewrite H1 at 1.\n  rewrite H2 at 1.\n  auto.\nQed.\n\nEnd Group.\n\nCheck id_inv.", "meta": {"author": "foreverbell", "repo": "verified", "sha": "44bba8f17b8070de304e14bc6fe1580e6890cd43", "save_path": "github-repos/coq/foreverbell-verified", "path": "github-repos/coq/foreverbell-verified/verified-44bba8f17b8070de304e14bc6fe1580e6890cd43/group-theory/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7552269079375011}}
{"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 friday)).\n\nExample test_next_weekday: (next_weekday (next_weekday friday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nInductive bool: Type := true | false.\n\nDefinition negb (b: bool) : bool :=\nmatch b with\n  | true => false\n  | false => true\nend.\n\nDefinition andb (b_1 : bool) (b_2: bool): bool :=\nmatch b_1 with\n  | true => b_2\n  | false => false\nend.\n\nDefinition orb (b_1 : bool) (b_2: bool): bool :=\nmatch b_1 with\n  | true => true\n  | false => b_2\nend.\n\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x || y\" := (orb x y).\nNotation \"x && y\" := (andb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\nmatch (b1, b2) with\n  | (true, true) => false\n  | _ => true\nend.\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 :=\nmatch b1, b2, b3 with\n  | true, true, true => true\n  | _,_,_ => false (* or do (x,y) and match with _ or do x,y and do _,_ *)\nend.\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 true).\nCheck negb.\n\nInductive rgb: Type := red | green | blue.\n\nInductive color: Type := black | white | primary (p: rgb).\n\nDefinition monochrome (c: color): bool :=\nmatch c with primary _ => false | _ => true end.\n\nDefinition isred (c: color): bool :=\nmatch c with\n  | primary red => true\n  | _ => false\nend.\n\nModule NatPlayground.\n\nInductive nat: Type := O | S (n: nat). (* letter O not 0 *)\n\nDefinition pred (n: nat) : nat :=\nmatch n with\n  | O => O\n  | S n' => n'\nend.\n\nEnd NatPlayground.\n\nCheck S (S (S O)). (* wow it prints it in a decimal form! *)\n\nFixpoint evenb (n: nat) : bool :=\nmatch n with\n  | 0 => true\n  | S 0 => 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\nFixpoint plus (n m:nat): nat :=\nmatch n with\n  | 0 => m\n  | S n' => S (plus n' m)\nend.\n\nCompute (plus 3 2).\n\nFixpoint mult (n m : nat) : nat :=\nmatch n with\n  | 0 => 0\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'\n  end.\n\nFixpoint exp (base power : nat) : nat :=\nmatch power with\n    | O => S O\n    | S p => mult base (exp base p)\nend.\n\nFixpoint factorial (n:nat) : nat :=\nmatch n with 0 => 1 | S n' => mult n (factorial 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.\nCheck ((0 + 1) + 1).\n\nFixpoint eqb (n m : nat) : bool :=\nmatch n, m with\n  | 0, 0 => true\n  | S n, S m => eqb n m\n  | _, _ => false\nend.\n\nFixpoint leb (n m : nat) : bool :=\nmatch n, m with\n  | 0, _ => true\n  | S n, S m => leb n m\n  | _, _ => false\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\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\nDefinition ltb (n m : nat) : bool :=\nmatch m with\n  | 0 => false\n  | S m' => leb n m'\nend.\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, 0 + n = n.\nProof. intro n. reflexivity. Qed.\n\n(* reflexivity expands definitions since it finishes the proof,\nsimpl is just a step so it doesn't mess up the state without our permission. *)\n\n(* Example Theorem Lemma Remark Fact  mean almost the same *)\n\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. (* _l suffix means \"on the left\" *)\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m:nat, n = m -> n + n = m + m.\nProof.\n  intros n m 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 Eq_nm Eq_mo.\n  rewrite <- Eq_mo. rewrite -> Eq_nm. reflexivity. Qed.\n\n(* Admitted command means believe it *)\n\nTheorem mult_0_plus : forall n m : nat, (0 + n) * m = n * m.\nProof.\n  intros n m. rewrite plus_O_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 H.\n  rewrite plus_1_l, H. reflexivity. Qed. (* !!! multiple rewrites !! *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n(* command Abort means give up for a minute *)\n  destruct n as [|n'] eqn:E. (* you may leave off eqn:E, then the assumption (from the case-split) named E will not be added to your list *)  \n  - reflexivity. (* - \"focuses\" the goal *)\n  - reflexivity. (* remember, reflexivity itself uses some simplification *)\nQed.\n\n(* - are called bullets, not needed, but they separate, you do not want \nCoq to interpret proof boundaries differently than you! *)\n\nTheorem negb_involutive : forall b : bool, negb (negb b) = b.\nProof.\n  intros b. destruct b (*as [|]*). (* you can ommit empty lists like these *)\n  { reflexivity. }\n  - reflexivity. Qed.\n\n(* no []s or [] or [|] are ok here *)\n(* bullets nest, first - then + then * then just braces: {} *)\n(* you can use braces any time though, and they obviously allow you to reuse the bullet shapes. *)\n\n(* shorthand: intro + destruct *)\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(* shorthand intro + destruct no names *)\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 [] [] E.\n  - reflexivity.\n  - exact E.\n  - reflexivity.\n  - exact E. Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\n(* Coq's 0%nat 0%Z notation *)\n\n(* for Fixpoint, coq requires that for all Fixpoint definitions, some\narugument is structurally decreasing *)\n\n(*\nFixpoint wont_compile (n: nat) (flag: bool): nat :=\nmatch n,flag with\n  | 0,_ => 0\n  | _, true => wont_compile (minus n 2) false\n  | _, false => wont_compile (plus n 1) true\nend.\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 H b.\n  rewrite H, H. reflexivity. Qed.\n\nFrom Coq Require Export String.\nDefinition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\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 b.\n  rewrite H, H, negb_involutive. reflexivity. Qed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool), (andb b c = orb b c) -> b = c.\nProof.\n  intros [] c H.\n  - simpl in H. rewrite H. reflexivity.\n  - simpl in H. exact H. Qed.\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (m:bin) : bin :=\nmatch m with\n  | Z => B Z\n  | A m' => B m'\n  | B m' => A (incr m')\nend.\n \nFixpoint bin_to_nat (m:bin) : nat :=\nmatch m with\n  | Z => 0\n  | A m' => 2 * bin_to_nat m'\n  | B m' => 1 + 2 * bin_to_nat m'\nend.\n\nExample test_bin_incr1: bin_to_nat (incr (A (B Z))) = 1 + bin_to_nat (A (B Z)).\nProof. reflexivity. Qed.\nExample test_bin_incr2: bin_to_nat (incr (A (A (B Z)))) = 1 + bin_to_nat (A (A (B Z))).\nProof. reflexivity. Qed.\nExample test_bin_incr3: bin_to_nat (incr (B (A (B Z)))) = 1 + bin_to_nat (B (A (B Z))).\nProof. reflexivity. Qed.\nExample test_bin_incr4: bin_to_nat (incr (A (B (B Z)))) = 1 + bin_to_nat (A (B (B Z))).\nProof. reflexivity. Qed.\nExample test_bin_incr5: bin_to_nat (incr (B(B(A (B (B Z)))))) = 1 + bin_to_nat (B(B(A (B (B Z))))).\nProof. reflexivity. Qed.\n\n", "meta": {"author": "belamenso", "repo": "software-foundations-solutions", "sha": "b13e32bf6864c1978bbfed18ed8a532e6f55c843", "save_path": "github-repos/coq/belamenso-software-foundations-solutions", "path": "github-repos/coq/belamenso-software-foundations-solutions/software-foundations-solutions-b13e32bf6864c1978bbfed18ed8a532e6f55c843/Volume 1: Logical Foundations/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7551914599094842}}
{"text": "Require Import Omega.\n\nFrom q3_2001 Require Export misc.\n\nDefinition ceil (x y : nat) :=\n  match y with\n  | 0 => x (* Division by zero convention (anything would do). *)\n  | S y' => let D := Nat.divmod x y' 0 y' in\n              if (snd D) =? y' then fst D else S (fst D)\n  end.\n\nLemma ceil_spec_0 : forall x y z : nat,\n  y <> 0 -> (ceil x y <= z <-> x <= y * z).\nProof.\n  intros x [|y'] z H; unfold ceil.\n  - contradiction.\n  - pose (q := (fst (Nat.divmod x y' 0 y'))).\n    pose (u := (snd (Nat.divmod x y' 0 y'))).\n    fold q. fold u.\n    pose (H' := (Nat.divmod_spec x y' 0 y' (le_refl y'))).\n    assert (HD : (q, u) = Nat.divmod x y' 0 y'). { symmetry. apply surjective_pairing. }\n    rewrite <- HD in H'. destruct H' as [Heq Hu].\n    assert (Hq : x = (S y') * q + y' - u). { omega. }\n    destruct (u =? y') eqn:H_rem; rewrite -> Hq.\n    + apply Nat.eqb_eq in H_rem. rewrite <- H_rem.\n      assert (Hrw : forall w, w + u - u = w). { intros w. omega. } rewrite -> (Hrw (S u * q)).\n      split; [apply mult_le_compat_l | apply (mult_S_le_reg_l u q z)].\n    + apply Nat.eqb_neq in H_rem.\n      split; intros H_ineq.\n      * assert (H1 : S y' * q + y' - u <= S y' * q + S y'). { omega. }\n        assert (H2 : S y' * q + S y' = S y' * S q). { auto. }\n        rewrite -> H2 in H1.\n        assert (H3 : S y' * S q <= S y' * z). { apply mult_le_compat_l. assumption. }\n        omega.\n      * assert (H1 : S y' * q + y' - u = S y' * q + (y' - u)). { omega. } rewrite -> H1 in H_ineq.\n        assert (H2 : 0 < y' - u). { omega. }\n        assert (H3 : S y' * q < S y' * z). { omega. }\n        rewrite <- Nat.mul_lt_mono_pos_l in H3.\n        -- assumption.\n        -- apply Nat.lt_0_succ.\nQed.\n\nLemma ceil_spec_1 : forall x y z : nat,\n  y <> 0 -> (z < ceil x y <-> y * z < x).\nProof.\n  intros x y z Hy.\n  destruct (Nat.le_gt_cases x (y*z)) as [Hx|Hx];\n  destruct (Nat.le_gt_cases (ceil x y) z) as [Hz|Hz]; split; intros H; try omega.\n  - rewrite <- (ceil_spec_0 _ _ _ Hy) in Hx. omega.\n  - rewrite -> (ceil_spec_0 _ _ _ Hy) in Hz. omega.\nQed.\n\nLemma ceil_spec_2 : forall x : nat,\n  ceil x 1 = x.\nProof.\n  intros. assert (H : 1 <> 0). { intros contra. inversion contra. }\n  assert (H_lt : ceil x 1 <= x). {\n    rewrite -> (ceil_spec_0 _ _ _ H). rewrite Nat.mul_1_l. apply le_refl.\n  }\n  assert (H_gt : ceil x 1 >= x). {\n    unfold ge. rewrite <- (Nat.mul_1_l (ceil x 1)).\n    rewrite <- (ceil_spec_0 x 1 (ceil x 1) H). apply le_refl.\n  }\n  apply Nat.le_antisymm; assumption.\nQed.\n\nLemma ceil_spec_3 : forall x y : nat,\n  y <> 0 -> x <= y * ceil x y.\nProof. intros. rewrite <- ceil_spec_0; trivial. Qed.\n\nLemma ceil_spec_4 : forall x y x' y' : nat,\n  y <> 0 -> x' <= x -> y <= y' -> ceil x' y' <= ceil x y.\nProof.\n  intros x y x' y' Hyn0 Hx Hy.\n  assert (Hy' : y' <> 0). { omega. }\n  rewrite -> (ceil_spec_0 _ _ _ Hy').\n  apply (le_trans x' x (y' * ceil x y)).\n  - assumption.\n  - apply (le_trans x (y * ceil x y) (y' * ceil x y)).\n    + apply (ceil_spec_3 _ _ Hyn0).\n    + apply mult_le_compat_r. assumption.\nQed.\n\nLemma ceil_spec_5 : forall x y z : nat,\n  y <> 0 -> z <> 0 -> ceil x y = ceil (z*x) (z*y).\nProof.\n  intros x y z Hy Hz.\n  assert (Hr : ceil (z*x) (z*y) <= ceil x y). {\n    apply ceil_spec_0.\n    - apply mult_is_O'; assumption.\n    - rewrite <- mult_assoc. apply Nat.mul_le_mono_l. apply ceil_spec_3. assumption.\n  }\n  assert (Hl : ceil x y <= ceil (z*x) (z*y)). {\n    apply ceil_spec_0.\n    - omega.\n    - rewrite -> Nat.mul_le_mono_pos_l with (p:=z).\n      + rewrite mult_assoc. apply ceil_spec_3. apply mult_is_O'; assumption.\n      + omega.\n  }\n  apply Nat.le_antisymm; 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/ceil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7551914538959232}}
{"text": "From mathcomp\n  Require Import ssreflect.\n\nSection ModusPonens.\nVariables X Y : Prop.\n\nHypothesis XtoY_is_true : X -> Y.\nHypothesis X_is_true : X.\n\nTheorem MP : Y.\nProof.\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\nTheorem HS2 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\nProof.\nmove=> AtoBtoC_is_true AtoB_is_true A_is_true.\nby apply: (MP B C); [apply: (MP A (B -> C)) | apply: (MP A B)].\nQed.\n\nTheorem HS3 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\nProof.\nmove=> AtoBtoC_is_true AtoB_is_true A_is_true.\nby move: A_is_true (AtoB_is_true A_is_true).\nQed.\n\nEnd HilbertSAxiom.\n", "meta": {"author": "ishioka0222", "repo": "theorem-proving-in-coq", "sha": "a67e7e5cfa837cefa776c0ec76f26152e80a6c39", "save_path": "github-repos/coq/ishioka0222-theorem-proving-in-coq", "path": "github-repos/coq/ishioka0222-theorem-proving-in-coq/theorem-proving-in-coq-a67e7e5cfa837cefa776c0ec76f26152e80a6c39/src/萩原学, アフェルト・レナルド (2018) Coq_SSReflect_MathCompによる定理証明/chap2_2-3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7551644735691735}}
{"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 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.\nlfind.  reflexivity. \nAdmitted.\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. rewrite mult_assoc. rewrite (mult_commut x y). 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/_lfind_clam_lf_goal84_plus_commut_63_plus_zero/goal84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7551644729042956}}
{"text": "Require Import Arith.\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).\n  apply H0.\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 Q : nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\n  intros.\n  apply H0.\n  apply H.\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_7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7551529001018318}}
{"text": "Require Import XR_Rabs.\nRequire Import XR_Rsqr.\nRequire Import XR_Rsqr_lt_abs_0.\nRequire Import XR_plus_lt_is_lt.\nRequire Import XR_Rle_0_sqr.\n\nLocal Open Scope R_scope.\n\nLemma triangle_rectangle_lt :\n  forall x y z:R,\n    Rsqr x + Rsqr y < Rsqr z -> Rabs x < Rabs z /\\ Rabs y < Rabs z.\nProof.\n  intros x y z.\n  intro h.\n  split.\n  {\n    apply Rsqr_lt_abs_0.\n    apply plus_lt_is_lt with (Rsqr y).\n    { apply Rle_0_sqr. }\n    { exact h. }\n  }\n  {\n    apply Rsqr_lt_abs_0.\n    apply plus_lt_is_lt with (Rsqr x).\n    { apply Rle_0_sqr. }\n    {\n      rewrite Rplus_comm.\n      exact h.\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_triangle_rectangle_lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7551528930233212}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.Bool.Bool.\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.\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  \n(* Evaluation *)\n  \nFixpoint aeval (a : aexp) : nat :=\nmatch 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)\nend.\n\nFixpoint beval (b : bexp) : bool :=\nmatch b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => beq_nat (aeval a1) (aeval a2)\n  | BLe a1 a2 => leb (aeval a1) (aeval a2)\n  | BNot b1 => negb (beval b1)\n  | BAnd b1 b2 => andb (beval b1) (beval b2)\nend.\n\nFixpoint optimize_0plus (a : aexp) : aexp :=\nmatch a with\n| ANum n => ANum n\n| APlus (ANum 0) e2 =>\n  optimize_0plus e2\n| APlus e1 e2 =>\n  APlus (optimize_0plus e1) (optimize_0plus e2)\n| AMinus e1 e2 =>\n  AMinus (optimize_0plus e1) (optimize_0plus e2)\n| AMult e1 e2 =>\n  AMult (optimize_0plus e1) (optimize_0plus e2)\nend.\n\nExample 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).\nProof. simpl. reflexivity. Qed.\n\nTheorem optimize_0plus_sound : forall a, aeval (optimize_0plus a) = aeval a.\nProof.\n  intros. induction a.\n  - simpl. reflexivity.\n  - destruct a1.\n    * destruct n.\n      + simpl. apply IHa2.\n      + simpl. apply f_equal. rewrite IHa2. reflexivity.\n    * simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. reflexivity.\n    * simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. reflexivity.\n    * simpl. simpl in IHa1. rewrite IHa1. rewrite IHa2. reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\n  - simpl. rewrite IHa1. rewrite IHa2. reflexivity.\nQed.\n\n(* Coq Automation *)\n\n(* Try *)\n\nTheorem silly1 : forall ae, aeval ae = aeval ae.\nProof. try reflexivity. Qed.\n\nTheorem silly2 : forall (P : Prop), P -> P.\nProof.\n  intros.\n  try reflexivity.\n  apply H.\nQed.\n\n(* The ; Tactical (Simple Form) *)\n\nLemma foo : forall n, leb 0 n = true.\nProof.\n  intros.\n  destruct n; simpl; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound': forall a, aeval (optimize_0plus a) = aeval a.\nProof.\n  intros. induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  - reflexivity.\n  - destruct a1;\n    try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    + destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound'': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros. induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);\n  try reflexivity.\n  - destruct a1; try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; \n                      reflexivity).\n    + destruct n; simpl; rewrite IHa2; reflexivity.\nQed.\n\n(* The ; Tactical (General Form) *)\n\n(* T; [T1 | T2 | ... | Tn] \n   is a tactic that first performs T and then performs T1 on the first\n   subgoal generated by T, performs T2 on the second subgoal, etc. *)\n\n(* The repeat Tactical *)\n\nTheorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\n  repeat (try (left; reflexivity); right).\nQed.\n\nTheorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\n  repeat (left; reflexivity).\n  repeat (right; (try (left; reflexivity))).\nQed.\n\n(* Exercise *)\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n  match b with\n  | BTrue => BTrue\n  | BFalse => BFalse\n  | BEq x y => BEq (optimize_0plus x) (optimize_0plus y)\n  | BLe x y => BLe (optimize_0plus x) (optimize_0plus y)\n  | BNot b => BNot (optimize_0plus_b b)\n  | BAnd x y => BAnd (optimize_0plus_b x) (optimize_0plus_b y)\n  end.\n\nTheorem optimize_0plus_b_sound : forall b,\n  beval (optimize_0plus_b b) = beval b.\nProof.\n  intros. induction b;\n  try (simpl; reflexivity).\n  try simpl; rewrite optimize_0plus_sound;\n      rewrite optimize_0plus_sound; reflexivity.\n  try simpl; rewrite optimize_0plus_sound;\n      rewrite optimize_0plus_sound; reflexivity.\n  - simpl. rewrite IHb. reflexivity.\n  - simpl. rewrite IHb1. rewrite IHb2. reflexivity.\nQed.\n\n(* The omega Tactic *)\n\nExample silly_presburger_example : forall m n o p,\n  m + n <= n + o /\\ o + 3 = p + 3 ->\n  m <= p.\nProof. intros. omega. Qed.\n\n(* A Few More Handy Tactics *)\n\n(* clear H: Delete hypothesis H from the context.\n   subst x\n   subst\n   rename ... into ...\n   assumption\n   contradiction\n   constructor *)\n \n(* Evaluation as a Relation *)\n\nModule aevalR_first_try.\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum : forall n, aevalR (ANum n) n\n  | E_APlus : forall e1 e2 n1 n2,\n    aevalR e1 n1 -> aevalR e2 n2 ->\n    aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus : forall e1 e2 n1 n2,\n    aevalR e1 n1 -> aevalR e2 n2 ->\n    aevalR (AMinus e1 e2) (n1 - n1)\n  | E_AMult : forall e1 e2 n1 n2,\n    aevalR e1 n1 -> aevalR e2 n2 ->\n    aevalR (AMult e1 e2) (n1 * n2).\n\nNotation \"e '\\\\' n\" := (aevalR e n)\n                       (at level 50, left associativity)\n                       : type_scope.\n\nEnd aevalR_first_try.\n\nReserved Notation \"e '\\\\' n\" (at level 50, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum : forall n, (ANum n) \\\\ n\n  | E_APlus : forall e1 e2 n1 n2,\n    (e1 \\\\ n1) -> (e2 \\\\ n2) -> (APlus e1 e2) \\\\ (n1 + n2)\n  | E_AMinus : forall e1 e2 n1 n2,\n    (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMinus e1 e2) \\\\ (n1 - n2)\n  | E_AMult : forall e1 e2 n1 n2,\n    (e1 \\\\ n1) -> (e2 \\\\ n2) -> (AMult e1 e2) \\\\ (n1 * n2)\n  where \"e '\\\\' n\" := (aevalR e n) : type_scope.\n\nInductive S : Type :=\n  | cons : Set -> S.\n\n(* Equivalence of the Definitions *)\n\nTheorem aeval_iff_aevalR : forall a n, (a \\\\ n) <-> aeval a = n.\nProof.\n  split.\n  - intros. induction H; simpl.\n    + reflexivity.\n    + rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    + rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\n    + rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.\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.\nQed.\n\nInductive bevalR : bexp -> bool -> Prop :=\n  | E_BTrue : BTrue \\\\ true\n  | E_BFalse : BFalse \\\\ false\n  | E_BEq : forall e1 e2 n1 n2, \n    (aevalR e1 n1) -> (aevalR e2 n2) -> (BEq e1 e2) \\\\ beq_nat n1 n2\n  | E_BLe : forall e1 e2 n1 n2,\n    (aevalR e1 n1) -> (aevalR e2 n2) -> (BLe e1 e2) \\\\ leb n1 n2\n  | E_BNot : forall e1 b1,\n    (e1 \\\\ b1) -> (BNot e1) \\\\ negb b1\n  | E_BAnd : forall e1 e2 b1 b2,\n    (e1 \\\\ b1) -> (e2 \\\\ b2) -> (BAnd e1 e2) \\\\ (andb b1 b2)\n  where \"e '\\\\' b\" := (bevalR e b) : type_scope.\n\nTheorem beval_iff_bevalR : forall b bv,\n  bevalR b bv <-> beval b = bv.\nProof.\n  split.\n  - intros. induction H; simpl.\n    + reflexivity.\n    + reflexivity.\n    + apply aeval_iff_aevalR in H. apply aeval_iff_aevalR in H0.\n      rewrite H. rewrite H0.\n      reflexivity.\n    + apply aeval_iff_aevalR in H. apply aeval_iff_aevalR in H0.\n      rewrite H. rewrite H0.\n      reflexivity.\n    + subst. reflexivity.\n    + subst. reflexivity.\n  - generalize dependent bv.\n    induction b; simpl; intros; subst.\n    + apply E_BTrue.\n    + apply E_BFalse.\n    + apply E_BEq.\n      * apply aeval_iff_aevalR. reflexivity.\n      * apply aeval_iff_aevalR. reflexivity.\n    + apply E_BLe.\n      * apply aeval_iff_aevalR. reflexivity.\n      * apply aeval_iff_aevalR. reflexivity.\n    + apply E_BNot.\n      apply IHb. reflexivity.\n    + apply E_BAnd.\n      * apply IHb1. reflexivity.\n      * apply IHb2. reflexivity.\nQed.\n\nEnd AExp.\n\n(* Computational vs. Relation Definitions *)\n\nModule aevalR_division.\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp \n  | APlus : aexp -> aexp -> aexp \n  | AMinus : aexp -> aexp -> aexp \n  | AMult : aexp -> aexp -> aexp \n  | ADiv : aexp -> aexp -> aexp.\n\nReserved Notation \"e '\\\\' n\" (at level 50, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum : forall (n:nat),\n      (ANum n) \\\\ n\n  | E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (APlus a1 a2) \\\\ (n1 + n2)\n  | E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (AMinus a1 a2) \\\\ (n1 - n2)\n  | E_AMult :  forall (a1 a2: aexp) (n1 n2 : nat),\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (AMult a1 a2) \\\\ (n1 * n2)\n  | E_ADiv :  forall (a1 a2: aexp) (n1 n2 n3: nat),\n      (a1 \\\\ n1) -> (a2 \\\\ n2) -> (n2 > 0) ->\n      (mult n2 n3 = n1) -> (ADiv a1 a2) \\\\ n3\n\nwhere \"a '\\\\' n\" := (aevalR a n) : type_scope.\n\nEnd aevalR_division.\n\n(* TODO aevalR_extended. *)\n\n(* Expressions with Variables *)\n\n(* States *)\n\nDefinition state := total_map nat.\n\nDefinition empty_state : state := t_empty 0.\n\n(* Syntax *)\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\nDefinition W : id := Id \"W\".\nDefinition X : id := Id \"X\".\nDefinition Y : id := Id \"Y\".\nDefinition Z : id := Id \"Z\".\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) : nat :=\n  match a with\n  | ANum n => n\n  | AId x => st x\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)\nend.\n\nFixpoint beval (st : state) (b : bexp) : bool :=\nmatch b with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)\n  | BLe a1 a2 => leb (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 aexp1 : aeval (t_update empty_state X 5)\n                      (APlus (ANum 3) (AMult (AId X) (ANum 2))) = 13.\nProof.\n  simpl. reflexivity.\nQed.\n\n(* Commands *)\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 \"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\nDefinition fact_in_coq : com :=\n  Z ::= AId X;;\n  Y ::= ANum 1;;\n  WHILE BNot (BEq (AId Z) (ANum 0)) DO\n    Y ::= AMult (AId Y) (AId Z);;\n    Z ::= AMinus (AId Z) (ANum 1)\n  END.\n\nReserved Notation \"c1 '/' st '\\\\' st'\"\n                  (at level 40, st at level 39).\n\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st, SKIP / st \\\\ st\n  | E_Ass : forall st a1 n x,\n    aeval st a1 = n ->\n    (x ::= a1) / st \\\\ (t_update st x 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' b c1 c2,\n    beval st b = true ->\n    c1 / st \\\\ st' ->\n    (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n  | E_IfFalse : forall st st' b c1 c2,\n    beval st b = false ->\n    c2 / st \\\\ st' ->\n    (IFB b THEN c1 ELSE c2 FI) / st \\\\ st'\n  | E_WhileFalse : forall b st c,\n    beval st b = false ->\n    (WHILE b DO c END) / st \\\\ st\n  | E_WhileTrue : forall st st' st'' b c,\n    beval st b = true ->\n    c / st \\\\ st' ->\n    (WHILE b DO c END) / st' \\\\ st'' ->\n    (WHILE b DO c END) / st \\\\ st''\n  where \"c1 '/' st '\\\\' st'\" := (ceval c1 st st').\n\nExample ceval_example1 : \n  (X ::= ANum 2;;\n   IFB BLe (AId X) (ANum 1)\n     THEN Y ::= ANum 3\n     ELSE Z ::= ANum 4\n   FI)\n  /  empty_state\n  \\\\ (t_update (t_update empty_state X 2) Z 4).\nProof.\n  eapply E_Seq.\n  - apply E_Ass. reflexivity.\n  - apply E_IfFalse.\n    + simpl. reflexivity.\n    + apply E_Ass. reflexivity.\nQed.\n\n(* TODO Exercises *)\n\n(* Determinism of Evaluation *)\n\nTheorem ceval_dterministic : 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 H; intros st2 E2; inversion E2; subst.\n  - reflexivity.\n  - reflexivity.\n  - assert (EQ : st' = st'0).\n    { apply IHceval1. apply H3. } \n    subst. apply IHceval2. apply H6.\n  - apply IHceval. apply H7.\n  - rewrite H in H6. inversion H6.\n  - rewrite H in H6. inversion H6.\n  - apply IHceval. apply H7.\n  - reflexivity.\n  - rewrite H in H2. inversion H2.\n  - rewrite H in H6. inversion H6.\n  - assert (EQ : st' = st'0).\n    { apply IHceval1. apply H5. }\n    apply IHceval2. subst. apply H8.\nQed.\n\n(* Reasoning About Imp Programs *)\n\nDefinition plus2 : com :=\n  X ::= (APlus (AId X) (ANum 2)).\n\nTheorem plus2_spec : forall st n st',\n  st X = n ->\n  plus2 / st \\\\ st' ->\n  st' X = n + 2.\nProof.\n  intros.\n  inversion H0.\n  subst. simpl. apply t_update_eq.\nQed.\n\n(* TODO Exercises *)\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/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7551084552872939}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  MSB                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  ******************************************************************************)\nRequire Export Fprop.\nRequire Export Zdivides.\nRequire Export Fnorm.\nSection mf.\nVariable radix : Z.\nHypothesis radixMoreThanOne : (1 < radix)%Z.\n \nLet radixMoreThanZERO := Zlt_1_O _ (Zlt_le_weak _ _ radixMoreThanOne).\nHint Resolve radixMoreThanZERO: zarith.\n\nLet FtoRradix := FtoR radix.\nLocal Coercion FtoRradix : float >-> R.\n\nFixpoint maxDiv (v : Z) (p : nat) {struct p} : nat :=\n  match p with\n  | O => 0\n  | S p' =>\n      match ZdividesP v (Zpower_nat radix p) with\n      | left _ => p\n      | right _ => maxDiv v p'\n      end\n  end.\n \nTheorem maxDivLess : forall (v : Z) (p : nat), maxDiv v p <= p.\nintros v p; elim p; simpl in |- *; auto.\nintros n H'; case (ZdividesP v (radix * Zpower_nat radix n)); auto.\nQed.\n \nTheorem maxDivLt :\n forall (v : Z) (p : nat),\n ~ Zdivides v (Zpower_nat radix p) -> maxDiv v p < p.\nintros v p; case p; simpl in |- *; auto.\nintros H'; case H'.\napply Zdivides1.\nintros n H'; case (ZdividesP v (radix * Zpower_nat radix n)); auto.\nintros H'0; case H'; auto.\nintros H'0; generalize (maxDivLess v n); auto with arith.\nQed.\n \nTheorem maxDivCorrect :\n forall (v : Z) (p : nat), Zdivides v (Zpower_nat radix (maxDiv v p)).\nintros v p; elim p.\nunfold maxDiv in |- *; rewrite Zpower_nat_O; auto.\napply Zdivides1.\nsimpl in |- *.\nintros n H'; case (ZdividesP v (radix * Zpower_nat radix n)); simpl in |- *;\n auto with zarith.\nQed.\n \nTheorem maxDivSimplAux :\n forall (v : Z) (p q : nat),\n p = maxDiv v (S (q + p)) -> p = maxDiv v (S p).\nintros v p q; elim q.\nsimpl in |- *; case (ZdividesP v (radix * Zpower_nat radix p)); auto.\nintros n H' H'0.\napply H'; auto; clear H'.\nsimpl in H'0; generalize H'0; clear H'0.\ncase (ZdividesP v (radix * (radix * Zpower_nat radix (n + p)))).\n2: simpl in |- *; auto.\nintros H' H'0; Contradict H'0; auto with zarith.\nQed.\n \nTheorem maxDivSimpl :\n forall (v : Z) (p q : nat),\n p < q -> p = maxDiv v q -> p = maxDiv v (S p).\nintros v p q H' H'0.\napply maxDivSimplAux with (q := q - S p); auto.\nreplace (S (q - S p + p)) with q; auto with zarith.\nQed.\n \nTheorem maxDivSimplInvAux :\n forall (v : Z) (p q : nat),\n p = maxDiv v (S p) -> p = maxDiv v (S (q + p)).\nintros v p q H'; elim q.\nsimpl in |- *; auto.\nintros n; simpl in |- *.\ncase (ZdividesP v (radix * Zpower_nat radix (n + p))); auto.\ncase (ZdividesP v (radix * (radix * Zpower_nat radix (n + p)))); auto.\nintros H'0 H'1 H'2; Contradict H'2; auto with zarith.\ncase (ZdividesP v (radix * (radix * Zpower_nat radix (n + p)))); auto.\nintros H'0 H'1 H'2; case H'1.\ncase H'0; intros z1 Hz1; exists (radix * z1)%Z;rewrite Hz1.\nunfold Zpower_nat; simpl; ring.\nQed.\n \nTheorem maxDivSimplInv :\n forall (v : Z) (p q : nat),\n p < q -> p = maxDiv v (S p) -> p = maxDiv v q.\nintros v p q H' H'0.\nreplace q with (S (q - S p + p)); auto with zarith.\napply maxDivSimplInvAux; auto.\nQed.\n \nTheorem maxDivUnique :\n forall (v : Z) (p : nat),\n p = maxDiv v (S p) ->\n Zdivides v (Zpower_nat radix p) /\\ ~ Zdivides v (Zpower_nat radix (S p)).\nintros v p H'; split.\nrewrite H'.\napply maxDivCorrect; auto.\nred in |- *; intros H'0; generalize H'; clear H'.\nsimpl in |- *.\ncase (ZdividesP v (radix * Zpower_nat radix p)); simpl in |- *; auto.\nintros H' H'1; Contradict H'1; auto with zarith.\nQed.\n \nTheorem maxDivUniqueDigit :\n forall v : Z,\n v <> 0 ->\n Zdivides v (Zpower_nat radix (maxDiv v (digit radix v))) /\\\n ~ Zdivides v (Zpower_nat radix (S (maxDiv v (digit radix v)))).\nintros v H'.\napply maxDivUnique; auto.\napply maxDivSimpl with (q := digit radix v); auto.\napply maxDivLt; auto.\napply NotDividesDigit; auto.\nQed.\n \nTheorem maxDivUniqueInverse :\n forall (v : Z) (p : nat),\n Zdivides v (Zpower_nat radix p) ->\n ~ Zdivides v (Zpower_nat radix (S p)) -> p = maxDiv v (S p).\nintros v p H' H'0; simpl in |- *.\ncase (ZdividesP v (radix * Zpower_nat radix p)); auto.\nintros H'1; case H'0; simpl in |- *; auto.\nintros H'1.\ngeneralize H'; case p; simpl in |- *; auto.\nintros n H'2; case (ZdividesP v (radix * Zpower_nat radix n)); auto.\nintros H'3; case H'3; auto.\nQed.\n \nTheorem maxDivUniqueInverseDigit :\n forall (v : Z) (p : nat),\n v <> 0 ->\n Zdivides v (Zpower_nat radix p) ->\n ~ Zdivides v (Zpower_nat radix (S p)) -> p = maxDiv v (digit radix v).\nintros v p H' H'0 H'1.\napply maxDivSimplInv; auto.\n2: apply maxDivUniqueInverse; auto.\napply Zpower_nat_anti_monotone_lt with (n := radix); auto.\napply Zle_lt_trans with (m := Zabs v); auto.\nrewrite <- (fun x => Zabs_eq (Zpower_nat radix x)); auto with zarith;\n apply ZDividesLe; auto.\napply digitMore; auto.\nQed.\n \nTheorem maxDivPlus :\n forall (v : Z) (n : nat),\n v <> 0 ->\n maxDiv (v * Zpower_nat radix n) (digit radix v + n) =\n maxDiv v (digit radix v) + n.\nintros v n H.\nreplace (digit radix v + n) with (digit radix (v * Zpower_nat radix n)); auto.\napply sym_equal.\napply maxDivUniqueInverseDigit; auto.\nred in |- *; intros Z1; case (Zmult_integral _ _ Z1); intros Z2.\ncase H; auto.\nabsurd (0 < Zpower_nat radix n)%Z; auto with zarith.\nrewrite Zpower_nat_is_exp.\nrepeat rewrite (fun x : Z => Zmult_comm x (Zpower_nat radix n)).\napply ZdividesMult; auto.\ncase (maxDivUniqueDigit v); auto.\nreplace (S (maxDiv v (digit radix v) + n)) with\n (S (maxDiv v (digit radix v)) + n); auto.\nrewrite Zpower_nat_is_exp.\nrepeat rewrite (fun x : Z => Zmult_comm x (Zpower_nat radix n)).\nred in |- *; intros H'.\nabsurd (Zdivides v (Zpower_nat radix (S (maxDiv v (digit radix v))))).\ncase (maxDivUniqueDigit v); auto.\napply ZdividesDiv with (p := Zpower_nat radix n); auto with zarith.\napply digitAdd; auto with zarith.\nQed.\n \nDefinition LSB (x : float) :=\n  (Z_of_nat (maxDiv (Fnum x) (Fdigit radix x)) + Fexp x)%Z.\n \nTheorem LSB_shift :\n forall (x : float) (n : nat), ~ is_Fzero x -> LSB x = LSB (Fshift radix n x).\nintros x n H'; unfold LSB, Fdigit in |- *; simpl in |- *.\nrewrite digitAdd; auto with arith.\nrewrite maxDivPlus; auto.\nrewrite inj_plus; ring.\nQed.\n \nTheorem LSB_comp :\n forall (x y : float) (n : nat), ~ is_Fzero x -> x = y :>R -> LSB x = LSB y.\nintros x y H' H'0 H'1.\ncase (FshiftCorrectSym radix) with (2 := H'1); auto.\nintros m1 H'2; elim H'2; intros m2 E; clear H'2.\nrewrite (LSB_shift x m1); auto.\nrewrite E; auto.\napply sym_equal; apply LSB_shift; auto.\napply (NisFzeroComp radix) with (x := x); auto.\nQed.\n \nTheorem maxDiv_opp :\n forall (v : Z) (p : nat), maxDiv v p = maxDiv (- v) p.\nintros v p; elim p; simpl in |- *; auto.\nintros n H; case (ZdividesP v (radix * Zpower_nat radix n));\n case (ZdividesP (- v) (radix * Zpower_nat radix n)); auto.\nintros Z1 Z2; case Z1.\ncase Z2; intros z1 Hz1; exists (- z1)%Z; rewrite Hz1; ring.\nintros Z1 Z2; case Z2.\ncase Z1; intros z1 Hz1; exists (- z1)%Z.\nrewrite <- (Zopp_involutive v); rewrite Hz1; ring.\nQed.\n \nTheorem LSB_opp : forall x : float, LSB x = LSB (Fopp x).\nintros x; unfold LSB in |- *; simpl in |- *.\nrewrite Fdigit_opp; auto.\nrewrite maxDiv_opp; auto.\nQed.\n \nTheorem maxDiv_abs :\n forall (v : Z) (p : nat), maxDiv v p = maxDiv (Zabs v) p.\nintros v p; elim p; simpl in |- *; auto.\nintros n H; case (ZdividesP v (radix * Zpower_nat radix n));\n case (ZdividesP (Zabs v) (radix  * Zpower_nat radix n));\n auto.\nintros Z1 Z2; case Z1.\ncase Z2; intros z1 Hz1; exists (Zabs z1); rewrite Hz1.\nrewrite Zabs_Zmult; f_equal. apply Zabs_eq. auto with zarith.\nintros Z1 Z2; case Z2.\ncase Z1; intros z1 Hz1.\ncase (Zle_or_lt v 0); intros Z4.\nexists (- z1)%Z; rewrite <- (Zopp_involutive v);\n rewrite <- (Zabs_eq_opp v); auto; rewrite Hz1; ring.\nexists z1; rewrite <- (Zabs_eq v); auto with zarith; rewrite Hz1; ring.\nQed.\n\nTheorem LSB_abs : forall x : float, LSB x = LSB (Fabs x).\nintros x; unfold LSB in |- *; simpl in |- *.\nrewrite Fdigit_abs; auto.\nrewrite maxDiv_abs; auto.\nQed.\n \nDefinition MSB (x : float) := Zpred (Z_of_nat (Fdigit radix x) + Fexp x).\n \nTheorem MSB_shift :\n forall (x : float) (n : nat), ~ is_Fzero x -> MSB x = MSB (Fshift radix n x).\nintros; unfold MSB, Fshift, Fdigit in |- *; simpl in |- *.\nrewrite digitAdd; auto with zarith.\nrewrite inj_plus; unfold Zpred in |- *; ring.\nQed.\n \nTheorem MSB_comp :\n forall (x y : float) (n : nat), ~ is_Fzero x -> x = y :>R -> MSB x = MSB y.\nintros x y H' H'0 H'1.\ncase (FshiftCorrectSym radix) with (2 := H'1); auto.\nintros m1 H'2; elim H'2; intros m2 E; clear H'2.\nrewrite (MSB_shift x m1); auto.\nrewrite E; auto.\napply sym_equal; apply MSB_shift; auto.\napply (NisFzeroComp radix) with (x := x); auto.\nQed.\n \nTheorem MSB_opp : forall x : float, MSB x = MSB (Fopp x).\nintros x; unfold MSB in |- *; simpl in |- *.\nrewrite Fdigit_opp; auto.\nQed.\n \nTheorem MSB_abs : forall x : float, MSB x = MSB (Fabs x).\nintros x; unfold MSB in |- *; simpl in |- *.\nrewrite Fdigit_abs; auto.\nQed.\n \nTheorem LSB_le_MSB : forall x : float, ~ is_Fzero x -> (LSB x <= MSB x)%Z.\nintros x H'; unfold LSB, MSB in |- *.\napply Zle_Zpred.\ncut (maxDiv (Fnum x) (Fdigit radix x) < Fdigit radix x); auto with zarith.\napply maxDivLt; auto.\nunfold Fdigit in |- *; apply NotDividesDigit; auto.\nQed.\n \nTheorem Fexp_le_LSB : forall x : float, (Fexp x <= LSB x)%Z.\nintros x; unfold LSB in |- *.\nauto with zarith.\nQed.\n \nTheorem Ulp_Le_LSigB :\n forall x : float, (Float 1%nat (Fexp x) <= Float 1%nat (LSB x))%R.\nintros x; apply (oneExp_le radix); auto.\napply Fexp_le_LSB; auto.\nQed.\n \nTheorem Fexp_le_MSB : forall x : float, ~ is_Fzero x -> (Fexp x <= MSB x)%Z.\nintros x H'; unfold MSB in |- *.\ncut (Fdigit radix x <> 0%Z :>Z); unfold Zpred in |- *;\n auto with zarith.\nunfold Fdigit in |- *.\nred in |- *; intros H'0; absurd (digit radix (Fnum x) = 0); auto with zarith.\napply not_eq_sym; apply lt_O_neq; apply digitNotZero; auto.\nQed.\n \nTheorem MSB_le_abs :\n forall x : float, ~ is_Fzero x -> (Float 1%nat (MSB x) <= Fabs x)%R.\nintros x H'; unfold MSB, FtoRradix, FtoR in |- *; simpl in |- *.\nreplace (Zpred (Fdigit radix x + Fexp x)) with\n (Zpred (Fdigit radix x) + Fexp x)%Z; [ idtac | unfold Zpred in |- *; ring ].\nrewrite powerRZ_add; auto with real zarith.\nrewrite Rmult_1_l.\nrepeat rewrite (fun r : R => Rmult_comm r (powerRZ radix (Fexp x))).\napply Rmult_le_compat_l; auto with real zarith.\nrewrite <- inj_pred; auto with real zarith.\nrewrite <- Zpower_nat_Z_powerRZ; auto.\napply Rle_IZR; auto.\nunfold Fdigit in |- *; auto with arith.\napply digitLess; auto.\nunfold Fdigit in |- *.\napply not_eq_sym; apply lt_O_neq; apply digitNotZero; auto.\nQed.\n \nTheorem abs_lt_MSB :\n forall x : float, (Fabs x < Float 1%nat (Zsucc (MSB x)))%R.\nintros x.\nrewrite (MSB_abs x).\nunfold MSB, FtoRradix, FtoR in |- *.\nrewrite <- Zsucc_pred; simpl in |- *.\nrewrite powerRZ_add; auto with real zarith.\nrewrite Rmult_1_l.\nrepeat rewrite (fun r : R => Rmult_comm r (powerRZ radix (Fexp x))).\napply Rmult_lt_compat_l; auto with real zarith.\nrewrite <- Zpower_nat_Z_powerRZ; auto with arith.\napply Rlt_IZR.\nunfold Fdigit in |- *; auto with arith.\nunfold Fabs in |- *; simpl in |- *.\npattern (Zabs (Fnum x)) at 1 in |- *; rewrite <- (Zabs_eq (Zabs (Fnum x)));\n auto with zarith.\nQed.\n \nTheorem LSB_le_abs :\n forall x : float, ~ is_Fzero x -> (Float 1%nat (LSB x) <= Fabs x)%R.\nintros x H'; apply Rle_trans with (FtoRradix (Float 1%nat (MSB x))).\napply (oneExp_le radix); auto.\napply LSB_le_MSB; auto.\napply MSB_le_abs; auto.\nQed.\n \nTheorem MSB_monotoneAux :\n forall x y : float,\n (Fabs x <= Fabs y)%R -> Fexp x = Fexp y -> (MSB x <= MSB y)%Z.\nintros x y H' H'0; unfold MSB in |- *.\nrewrite <- H'0.\ncut (Fdigit radix x <= Fdigit radix y)%Z;\n [ unfold Zpred in |- *; auto with zarith | idtac ].\nunfold Fdigit in |- *; apply inj_le.\napply digit_monotone; auto.\napply le_IZR.\napply Rmult_le_reg_l with (r := powerRZ radix (Fexp x));\n auto with real zarith.\nrepeat rewrite (Rmult_comm (powerRZ radix (Fexp x))); auto.\npattern (Fexp x) at 2 in |- *; rewrite H'0; auto.\nQed.\n \nTheorem MSB_monotone :\n forall x y : float,\n ~ is_Fzero x -> ~ is_Fzero y -> (Fabs x <= Fabs y)%R -> (MSB x <= MSB y)%Z.\nintros x y H' H'0 H'1; rewrite (MSB_abs x); rewrite (MSB_abs y).\ncase (Zle_or_lt (Fexp (Fabs x)) (Fexp (Fabs y))); simpl in |- *; intros Zle1.\nrewrite\n MSB_shift with (x := Fabs y) (n := Zabs_nat (Fexp (Fabs y) - Fexp (Fabs x))).\napply MSB_monotoneAux; auto.\nunfold FtoRradix in |- *; repeat rewrite Fabs_correct; auto with real arith.\nrewrite FshiftCorrect; auto with real arith.\nrepeat rewrite Fabs_correct; auto with real arith.\nrepeat rewrite Rabs_Rabsolu; repeat rewrite <- Fabs_correct;\n auto with real arith.\nunfold Fshift in |- *; simpl in |- *.\nrewrite inj_abs; [ ring | auto with zarith ].\napply Fabs_Fzero; auto.\nrewrite\n MSB_shift with (x := Fabs x) (n := Zabs_nat (Fexp (Fabs x) - Fexp (Fabs y))).\napply MSB_monotoneAux; auto.\nunfold FtoRradix in |- *; repeat rewrite Fabs_correct; auto with real arith.\nrewrite FshiftCorrect; auto with real arith.\nrepeat rewrite Fabs_correct; auto with real arith.\nrepeat rewrite Rabs_Rabsolu; repeat rewrite <- Fabs_correct;\n auto with real arith.\nunfold Fshift in |- *; simpl in |- *.\nrewrite inj_abs; [ ring | auto with zarith ].\napply Fabs_Fzero; auto.\nQed.\n \nTheorem MSB_le_multAux :\n forall x y : float,\n ~ is_Fzero x -> ~ is_Fzero y -> (MSB x + MSB y <= MSB (Fmult x y))%Z.\nintros x y H' H'0; unfold MSB, Fmult, Fdigit in |- *; simpl in |- *.\nreplace\n (Zpred (digit radix (Fnum x) + Fexp x) +\n  Zpred (digit radix (Fnum y) + Fexp y))%Z with\n (Zpred\n    (digit radix (Fnum x) + Zpred (digit radix (Fnum y)) + (Fexp x + Fexp y)));\n [ idtac | unfold Zpred in |- *; ring ].\ncut\n (digit radix (Fnum x) + Zpred (digit radix (Fnum y)) <=\n  digit radix (Fnum x * Fnum y))%Z;\n [ unfold Zpred in |- *; auto with zarith | idtac ].\nrewrite <- inj_pred; auto with float zarith; try rewrite <- inj_plus.\napply inj_le.\nrewrite <- digitAdd; auto with zarith.\napply digit_monotone; auto with zarith.\nrepeat rewrite Zabs_Zmult.\napply Zle_Zmult_comp_l; auto with zarith.\nrewrite (fun x => Zabs_eq (Zpower_nat radix x)); auto with zarith.\napply not_eq_sym; apply lt_O_neq; apply digitNotZero; auto.\nQed.\n \nTheorem MSB_le_mult :\n forall x y : float,\n ~ is_Fzero x ->\n ~ is_Fzero y ->\n (Fmult (Float 1%nat (MSB x)) (Float 1%nat (MSB y)) <=\n  Float 1%nat (MSB (Fmult x y)))%R.\nintros x y H' H'0.\nrewrite <- oneZplus.\napply (oneExp_le radix); auto.\napply MSB_le_multAux; auto.\nQed.\n \nTheorem mult_le_MSBAux :\n forall x y : float,\n ~ is_Fzero x -> ~ is_Fzero y -> (MSB (Fmult x y) <= Zsucc (MSB x + MSB y))%Z.\nintros x y H' H'0; unfold MSB, Fmult, Fdigit in |- *; simpl in |- *.\nreplace\n (Zsucc\n    (Zpred (digit radix (Fnum x) + Fexp x) +\n     Zpred (digit radix (Fnum y) + Fexp y))) with\n (Zpred (digit radix (Fnum x) + digit radix (Fnum y) + (Fexp x + Fexp y)));\n [ idtac | unfold Zpred, Zsucc in |- *; ring ].\ncut\n (digit radix (Fnum x * Fnum y) <=\n  digit radix (Fnum x) + digit radix (Fnum y))%Z;\n [ unfold Zpred in |- *; auto with zarith | idtac ].\nrewrite <- inj_plus.\napply inj_le; auto.\nrewrite <- digitAdd; auto with arith.\napply digit_monotone; auto with arith.\nrepeat rewrite Zabs_Zmult.\napply Zle_Zmult_comp_l; auto with zarith.\nrewrite (fun x => Zabs_eq (Zpower_nat radix x)); auto with zarith.\nQed.\n \nTheorem mult_le_MSB :\n forall x y : float,\n ~ is_Fzero x ->\n ~ is_Fzero y ->\n (Float 1%nat (MSB (Fmult x y)) <=\n  radix * Fmult (Float 1%nat (MSB x)) (Float 1%nat (MSB y)))%R.\nintros x y H' H'0; rewrite <- oneZplus.\nreplace (radix * Float 1%nat (MSB x + MSB y))%R with\n (FtoRradix (Float 1%nat (Zsucc (MSB x + MSB y)))).\napply (oneExp_le radix); auto.\napply mult_le_MSBAux; auto.\nunfold FtoRradix, FtoR in |- *; simpl in |- *.\nrewrite powerRZ_Zs; auto with real zarith; ring.\nQed.\n \nTheorem MSB_mix :\n forall x y : float,\n ~ is_Fzero x ->\n ~ is_Fzero y ->\n (Fabs x * Float 1%nat (MSB y) < radix * (Fabs y * Float 1%nat (MSB x)))%R.\nintros x y H' H'0; rewrite (MSB_abs x); rewrite (MSB_abs y).\napply Rle_lt_trans with (Fabs x * Fabs y)%R; auto with real.\napply Rmult_le_compat_l; auto with real.\nunfold FtoRradix in |- *; rewrite Fabs_correct; auto with real arith.\nrewrite <- MSB_abs; apply MSB_le_abs; auto.\nrewrite (Rmult_comm (Fabs x)).\nreplace (radix * (Fabs y * Float 1%nat (MSB (Fabs x))))%R with\n (Fabs y * (radix * Float 1%nat (MSB (Fabs x))))%R; \n [ idtac | ring ].\napply Rmult_lt_compat_l; auto with real.\nunfold FtoRradix, FtoR in |- *; simpl in |- *; auto with real arith.\nrewrite Rmult_comm; replace 0%R with (powerRZ radix (Fexp y) * 0)%R;\n [ idtac | ring ].\napply Rmult_lt_compat_l; auto with real arith.\nrewrite Zabs_absolu.\nreplace 0%R with (INR 0); [ idtac | simpl in |- *; auto ];\n rewrite <- INR_IZR_INZ; apply INR_lt_nm.\napply absolu_lt_nz; auto.\nreplace (radix * Float 1%nat (MSB (Fabs x)))%R with\n (FtoRradix (Float 1%nat (Zsucc (MSB (Fabs x))))).\nrewrite <- MSB_abs; apply abs_lt_MSB; auto.\nunfold FtoRradix, FtoR in |- *; simpl in |- *.\nrewrite powerRZ_Zs; auto with real zarith; ring.\nQed.\n \nTheorem LSB_rep :\n forall x y : float,\n ~ is_Fzero y ->\n (LSB x <= LSB y)%Z -> exists z : Z, y = Float z (Fexp x) :>R.\nintros x y H' H'0.\ncase (Zle_or_lt (Fexp x) (Fexp y)); intros Zl1.\nexists (Fnum y * Zpower_nat radix (Zabs_nat (Fexp y - Fexp x)))%Z.\npattern (Fexp x) at 2 in |- *;\n replace (Fexp x) with (Fexp y - Zabs_nat (Fexp y - Fexp x))%Z.\nunfold FtoRradix in |- *;\n rewrite <-\n  (FshiftCorrect radix) with (n := Zabs_nat (Fexp y - Fexp x)) (x := y); \n auto.\nrewrite inj_abs; try ring; auto with zarith.\nexists (Zquotient (Fnum y) (Zpower_nat radix (Zabs_nat (Fexp x - Fexp y)))).\nunfold FtoRradix in |- *;\n rewrite <-\n  (FshiftCorrect radix)\n                        with\n                        (n := Zabs_nat (Fexp x - Fexp y))\n                       (x := \n                         Float\n                           (Zquotient (Fnum y)\n                              (Zpower_nat radix (Zabs_nat (Fexp x - Fexp y))))\n                           (Fexp x)); auto.\nunfold Fshift in |- *; simpl in |- *.\ncut (0 <= Fexp x - Fexp y)%Z;\n [ intros Le1; repeat rewrite inj_abs | auto with zarith ]; \n auto.\nunfold FtoR in |- *; simpl in |- *; auto.\nreplace (Fexp x - (Fexp x - Fexp y))%Z with (Fexp y); [ idtac | ring ].\nreplace\n (Zquotient (Fnum y) (Zpower_nat radix (Zabs_nat (Fexp x - Fexp y))) *\n  Zpower_nat radix (Zabs_nat (Fexp x - Fexp y)))%Z with (\n Fnum y); auto.\napply ZdividesZquotient; auto with zarith.\napply\n ZdividesTrans\n  with (m := Zpower_nat radix (maxDiv (Fnum y) (Fdigit radix y))).\napply maxDivCorrect.\napply ZdividesLessPow; auto.\napply ZleLe.\nrewrite inj_abs; auto with zarith.\napply Zplus_le_reg_l with (p := Fexp y).\napply Zle_trans with (LSB x).\nreplace (Fexp y + (Fexp x - Fexp y))%Z with (Fexp x); [ idtac | ring ].\napply Fexp_le_LSB.\nrewrite Zplus_comm; auto.\nQed.\n \nTheorem LSB_rep_min :\n forall p : float, exists z : Z, p = Float z (LSB p) :>R.\nintros p;\n exists (Zquotient (Fnum p) (Zpower_nat radix (Zabs_nat (LSB p - Fexp p)))).\nunfold FtoRradix, FtoR, LSB in |- *; simpl in |- *.\nrewrite powerRZ_add; auto with real zarith.\nrewrite <- Rmult_assoc.\nreplace (maxDiv (Fnum p) (Fdigit radix p) + Fexp p - Fexp p)%Z with\n (Z_of_nat (maxDiv (Fnum p) (Fdigit radix p))); auto.\nrewrite absolu_INR.\nrewrite <- Zpower_nat_Z_powerRZ; auto with zarith.\nrewrite <- Rmult_IZR.\nrewrite <- ZdividesZquotient; auto with zarith.\napply maxDivCorrect.\nring.\nQed.\nEnd mf.", "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/MSB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7550540887633681}}
{"text": "Require Import Even.\nFrom mathcomp Require Import eqtype ssrnat fintype div bigop prime binomial.\nRequire Import ssreflect ssrfun ssrbool.\n\n\nTheorem t: forall n:nat,even(n*(1+n)).\nProof.\nintros.\napply even_mult_aux.\nelim n.\nleft.\nSearchAbout(even _).\napply even_O.\nintros.\nelim H.\nright.\nSearchAbout(even _).\napply even_S, odd_S, H0.\nleft.\napply H0.\nQed.\n\nTheorem tri:forall n:nat, even(n*(1+n)*(2+n)).\nProof.\nintros.\napply even_mult_aux.\nleft.\napply t.\nQed.\n\nTheorem sqn_even:forall n:nat, even (n ^ 2) -> even n.\nProof.\nintros.\nrewrite <-mulnn in H.\napply even_mult_aux in H.\ndestruct H.\napply H.\napply H.\nQed.", "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/even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7550471770411167}}
{"text": "Require Import Arith.\nRequire Import Recdef.\nRequire Import List.\n\nOpen Scope list_scope.\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\n(** Prove os dois lemas a seguir. *)\nLemma equiv_sub: forall l l' a, equiv l l' -> equiv (a::l) (a::l').\nProof.\n  intros l l' a H.\n  unfold equiv in *.\n  intro n.\n  simpl num_oc.\n  destruct (Nat.eq_dec n a).\n  - subst.\n    rewrite <- H.\n    reflexivity.\n  - subst.\n    rewrite <- H.\n    reflexivity.\nQed.\n\nLemma equiv_trans: forall l l' l'', equiv l l' -> equiv l' l'' -> equiv l l''.\nProof.\n  intros l l' l'' H H1.\n  unfold equiv in *.\n  intro n.\n  rewrite <- H1.\n  rewrite <- H.\n  reflexivity.\nQed.\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\nCompute (bubble (1::3::0::nil)).\n\nLemma bubble_equiv: forall l, equiv (bubble l) l.\nProof.\n  intro l.\n  functional induction (bubble l).\n  - unfold equiv in *.\n    intro n.\n    remember (h1 :: tl) as l eqn: H.\n    simpl num_oc.\n    destruct (Nat.eq_dec n h0).\n    + rewrite IHl0.\n      reflexivity.\n    + rewrite IHl0.\n      reflexivity.\n  - unfold equiv in *.\n    intro n.\n    simpl num_oc at 1.\n    destruct (Nat.eq_dec n h1).\n    + rewrite IHl0.\n      simpl.\n      destruct (Nat.eq_dec n h0).\n      * destruct (Nat.eq_dec n h1).\n        ** reflexivity.\n        ** apply False_ind.\n           contradiction.\n      * destruct (Nat.eq_dec n h1).\n        ** reflexivity.\n        ** apply False_ind.\n           contradiction.\n    + rewrite IHl0.\n      simpl.\n      destruct (Nat.eq_dec n h0).\n      * destruct (Nat.eq_dec n h1).\n        ** apply False_ind.\n           contradiction.\n        ** reflexivity.\n      * destruct (Nat.eq_dec n h1).\n        ** apply False_ind.\n           contradiction.\n        ** reflexivity.\n  - unfold equiv.\n    reflexivity.\nQed.\n\n(** Construa uma nova prova do lema anterior usando o fato que equiv é uma relação transitiva. *)\nLemma bubble_equiv': forall l, equiv (bubble l) l.\nProof.\n  intro l.\n  functional induction (bubble l).\n  - unfold equiv in *.\n    intro n.\n    remember (h1 :: tl) as l eqn: H.\n    rewrite  (equiv_sub (bubble l) l).\n    + reflexivity.\n    + assumption.\n  - unfold equiv in *.\n    intro n.\n    rewrite (equiv_sub (bubble (h0 :: tl)) (h0 :: tl)).\n    simpl num_oc at 1.\n    + destruct (Nat.eq_dec n h0).\n      * destruct (Nat.eq_dec n h1).\n        ** subst.\n           inversion _x.\n           admit. subst.\n           contradiction.\n        **\n      *\n    + assumption.\n  - unfold equiv in *.\n    intro n.\n    reflexivity.\nQed.\n\n(** Adicionar definição de bubbleSort *)\nFixpoint bubbleSort (l: list nat) : list nat :=\n  match l with\n  | nil => l\n  | h::tl => bubble (h :: (bubbleSort tl))\n  end.\n\nCompute (bubbleSort (1::3::0::nil)).\n\nLemma bubbleSort_equiv: forall l, equiv (bubbleSort l) l.\nProof.\n  induction l.\n  - simpl.\n    unfold equiv.\n    reflexivity.\n  - unfold equiv in *.\n    intro n.\n    simpl bubbleSort.\n    simpl num_oc at 2.\n    destruct (Nat.eq_dec n a).\n    + rewrite <- IHl.\n      assert (H: S (num_oc n (bubbleSort l)) = num_oc n (a::(bubbleSort l))).\n      { simpl num_oc at 2.\n        destruct (Nat.eq_dec n a).\n        - reflexivity.\n        - apply False_ind.\n          contradiction. }\n      rewrite H.\n      generalize n.\n      fold (equiv  (bubble(a :: bubbleSort l)) (a :: bubbleSort l)).\n      apply bubble_equiv.\n    + rewrite <- IHl.\n      assert (H: num_oc n (bubbleSort l) = num_oc n (a::(bubbleSort l))).\n      { simpl num_oc at 2.\n        destruct (Nat.eq_dec n a).\n        - apply False_ind.\n          contradiction.\n        - reflexivity. }\n      rewrite H.\n      generalize n.\n      fold (equiv  (bubble(a :: bubbleSort l)) (a :: bubbleSort l)).\n      apply bubble_equiv.\nQed.", "meta": {"author": "Gastd", "repo": "fptt", "sha": "999472e6b0df8652a299f271f1676c8c0dc78256", "save_path": "github-repos/coq/Gastd-fptt", "path": "github-repos/coq/Gastd-fptt/fptt-999472e6b0df8652a299f271f1676c8c0dc78256/bubbleSort_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7550227669631407}}
{"text": "(* https://stackoverflow.com/questions/55333331/coq-proof-that-factorial-n-factorial-k-factorial-n-k-is-integer/55944121#55944121 *)\n\nFrom Coq Require Import Arith.\n\n(* Let's prove that (n+m)! is divisible by n! * m!. *)\n\n(* fact2 x y = (x+1) * (x+2) * .. * (x+y) *)\n\nFixpoint fact2 x y := match y with\n  | O => 1\n  | S y' => (x + y) * fact2 x y'\nend.\n\nLemma fact2_0 : forall x, fact2 0 x = fact x.\nProof.\n  induction x.\n  - auto.\n  - simpl. rewrite IHx. auto. Qed.\n\nLemma fact_fact2 : forall x y, fact x * fact2 x y = fact (x + y).\nProof.\n  induction x.\n  - intros. simpl. rewrite fact2_0. ring.\n  - induction y.\n    + simpl. replace (x + 0) with x by ring. ring.\n    + simpl. replace (x + S y) with (S x + y) by ring. rewrite <- IHy. simpl. ring. Qed.\n\nLemma fact2_left : forall x y, fact2 x (S y) = S x * fact2 (S x) y.\nProof. intros x y. generalize dependent x. induction y.\n  - intros. simpl. ring.\n  - intros. unfold fact2. fold (fact2 x (S y)). fold (fact2 (S x) y).\n    rewrite IHy. ring. Qed.\n\nLemma fact_div_fact2 : forall x y, exists e, fact2 x y = e * fact y.\nProof. intros x y. generalize dependent x. induction y.\n  - intros. simpl. exists 1. auto.\n  - induction x.\n    + unfold fact2. fold (fact2 0 y). unfold fact. fold (fact y). destruct (IHy 0). rewrite H.\n      exists x. ring.\n    + unfold fact2. fold (fact2 (S x) y).\n      destruct (IHy (S x)). destruct IHx. exists (x0 + x1).\n      replace ((S x + S y) * fact2 (S x) y) with (S x * fact2 (S x) y + S y * fact2 (S x) y) by ring.\n      rewrite <- fact2_left. rewrite H0. rewrite H.\n      replace (S y * (x0 * fact y)) with (x0 * (S y * fact y)) by ring.\n      unfold fact. fold (fact y). ring. Qed.\n\nTheorem fact_div_fact_fact : forall x y, exists e, fact (x + y) = e * (fact x * fact y).\nProof. intros x y. destruct (fact_div_fact2 x y). exists x0.\n  rewrite <- fact_fact2. rewrite H. ring. Qed.\n", "meta": {"author": "Bubbler-4", "repo": "coq-misc-works", "sha": "c5acaf843d8d5be6987a7a38b800e839c33d2c28", "save_path": "github-repos/coq/Bubbler-4-coq-misc-works", "path": "github-repos/coq/Bubbler-4-coq-misc-works/coq-misc-works-c5acaf843d8d5be6987a7a38b800e839c33d2c28/StackOverflow/fact_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7550227578834864}}
{"text": "Require Export Tree_Inf.\nRequire Relations.\n\nSet Implicit Arguments.\n\nSection LTree_bisimilar_def.\n Variable A:Set.\n\n(* An extensional equality on (LTree A) *)\n CoInductive LTree_bisimilar : (LTree A)->(LTree A)->Prop :=\n  LTree_bisimilar_leaf : LTree_bisimilar LLeaf LLeaf\n| LTree_bisimilar_bin : forall (a:A) (t1 t'1 t2 t'2 : LTree A),\n                LTree_bisimilar t1 t'1 ->\n                LTree_bisimilar t2 t'2 ->\n                LTree_bisimilar (LBin a t1 t2) (LBin a t'1 t'2).\n\nRequire Import Relations.\n\nLemma LTree_bisimilar_refl : (reflexive _ LTree_bisimilar).\nProof.\n unfold reflexive; cofix.\n intro a; case a ; constructor; auto.\nQed.\n\nLemma LTree_bisimilar_sym : (symmetric _ LTree_bisimilar).\nProof.\n unfold symmetric; cofix.\n intros x y; case x; case y.\n constructor.\n inversion_clear 1.\n inversion_clear 1.\n inversion_clear 1.\n constructor; auto.\nQed.\n\nLemma LTree_bisimilar_trans : (transitive _ LTree_bisimilar).\nProof.\n unfold transitive; cofix.\n intros x y z ; case x; case y.\n case z;[auto | inversion_clear 2].\n inversion_clear 1.\n inversion_clear 1.\n inversion_clear 1.\n case z; inversion_clear 1. \n constructor; eauto.\nQed.\n\n Theorem LTree_bisimilar_label : \n   forall (p:path) (t t': LTree A),\n          LTree_bisimilar t t' ->\n          LTree_label t p = LTree_label t' p.\n Proof.\n  simple induction p.\n  intros t t'; case t; case t'.\n  simpl; auto.\n  inversion_clear 1.\n  inversion_clear 1.\n  inversion_clear 1; simpl; auto.\n   intros a l;case a; intros H t t'; case t; case t'.\n  auto.\n  inversion_clear 1.\n  inversion_clear 1.\n  inversion_clear 1; simpl.\n  repeat  rewrite LTree_label_rw0.\n  auto.\n  repeat  rewrite LTree_label_rw1; auto.\n  inversion_clear 1.\n  inversion_clear 1.\n  inversion_clear 1.\n  repeat  rewrite LTree_label_rw1; auto.\n Qed.\n\n\n Theorem label_LTree_bisimilar :  forall t t': LTree A, \n                          (forall p:path, LTree_label t p = LTree_label t' p)->\n                          LTree_bisimilar t t'.\n Proof.\n  cofix.\n  intros t t'; case t; case t'.\n  constructor.\n  intros a l l0 H.\n  generalize (H nil ).\n  simpl.\n  unfold LTree_label; simpl.  \n  discriminate 1.  \n  intros a l l0 H.\n  generalize (H nil).\n  simpl.\n  unfold LTree_label; simpl.  \n  discriminate 1.  \n  intros a l l0 a0 t1 t2 H.\n  cut (a = a0).\n  simple induction 1; constructor.\n  apply label_LTree_bisimilar. \n  intro p ;  generalize (H (cons d0 p)).\n  repeat rewrite LTree_label_rw0; auto.\n  apply label_LTree_bisimilar. \n  intro p ; generalize (H (cons d1 p)).\n  repeat rewrite LTree_label_rw1; auto.\n  generalize (H nil).\n  repeat rewrite LTree_label_rw_root_bin; auto.\n  injection 1;auto.\n Qed.\n\nEnd LTree_bisimilar_def.\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/co-inductifs/SRC/LTree_bisimilar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.754983598072445}}
{"text": "From mathcomp Require Import all_ssreflect. \n\n\n(** *** Exercise 1:\n    - Let's define the subtype of odd and even natural numbers\n    - Intrument Coq to recognize odd/even number built out\n      of product and successor\n    - Inherit on [odd_nat] the [eqType] structure \n*)\n\nStructure odd_nat := Odd {\n  oval :> nat;\n  oprop : odd oval\n}.\nLemma oddP (n : odd_nat) : odd n.\nProof. by case: n. Qed.\n\nStructure even_nat := Even {\n  eval :> nat;\n  eprop : ~~ (odd eval)\n}.\nLemma evenP (n : even_nat) : ~~ (odd n).\nProof. by case: n. Qed.\n\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. Fail by rewrite oddP evenP. Abort.\n\nCanonical even_0 := Even 0 isT.\n\nLemma oddS n : ~~ (odd n) -> odd n.+1.\nProof.\nQed.\n\nLemma evenS n : (odd n) -> ~~ (odd n.+1).\nProof.\nQed.\n\nCanonical odd_even (m : even_nat) :=\n  Odd m.+1 (oddS m (eprop m)).\nCanonical even_odd (m : odd_nat) :=\n\nLemma odd_mulP (n m : odd_nat) : odd (n * m).\nProof.\nQed.\nCanonical odd_mul (n m : odd_nat) :=\n\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof. by rewrite oddP evenP. Qed.\n\nFail Check forall n m : odd_nat, n == m.\n\nCanonical odd_subType :=\nDefinition odd_eqMixin :=\nCanonical odd_eqType :=\n\nCheck forall n m : odd_nat, n == m.\n\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/exercise8_todo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7549307167047394}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 6 *)\n\n(* In this pset, you will use abstract-interpretation results to enable\n * optimizations in programs:\n * (1) Develop and verify an analysis that just tracks known constant values\n *     for variables.\n * (2) Write and verify an optimization that replaces variables with their known\n *     constant values, which is trickier than it sounds, because variables may\n *     equal different constants at different points in the code!\n * (3) Use all of the above to prove that a particular run of the optimization\n *     generates an optimized program with the same behavior as the original\n *     program. *)\n\n(* Authors: Adam Chlipala (adamc@csail.mit.edu), Peng Wang\n* (wangpeng@csail.mit.edu), Andres Erbsen (andreser@mit.edu) *)\n\nRequire Import Frap AbstractInterpret Pset6Sig.\n(* Note that module [AbstractInterpret] here duplicates the framework\n * definitions from AbstractInterpretation.v, the file with example code from\n * the last lecture. *)\n\n(** * An abstract interpretation tracking equality to constants *)\n\n(* copy-pasted from Sig file:\nInductive domain :=\n| Exactly (n : nat)\n| Anything.\n*)\n\nDefinition represents (x:nat) (d:domain) : Prop :=\n  match d with\n  | Exactly n => x = n\n  | Anything => True\n  end.\n\nDefinition absint_binop (f : nat -> nat -> nat) (a b : domain) : domain :=\n  match a, b with\n  | Exactly n, Exactly m => Exactly (f n m)\n  | _, _ => Anything\n  end.\n\nDefinition join (a b : domain) : domain :=\n  match a, b with\n  | Exactly n, Exactly m => if n ==n m then Exactly n else Anything\n  | _, _ => Anything\n  end.\n\nDefinition constant_absint := {|\n  Top := Anything;\n  Constant := Exactly;\n  Add := absint_binop Nat.add;\n  Subtract := absint_binop Nat.sub;\n  Multiply := absint_binop Nat.mul;\n  Join := join;\n  Represents := represents\n|}.\n\n(* copy-pasted from frap/AbstractInterpret.v:\nDefinition astate (a : absint) := fmap var a.\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\n(* Depending on how you approach [constant_sound], this\n * lemma may or may not be useful. Regardless, it is used in our proof of\n * [optimize_program_ok] below. *)\n(* from frap/AbstractInterpret.v:\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*)\nLemma compatible_subsumed : forall a (s1 s2 : astate a) v,\n  compatible s1 v -> subsumed s1 s2  -> compatible s2 v.\nProof.\n  unfold compatible, subsumed; simplify.\n  specialize H0 with (x:=x). cases (s1 $? x).\n  apply H in Heq; first_order. equality.\nQed. \nHint Resolve compatible_subsumed : core.\n\nLemma constant_sound : absint_sound constant_absint.\nProof.\n  split.\n\n  (* You'll need to prove this one. *)\n\n  all: simplify.\n\n  (* As a convenience, here are some examples of how to\n   * combine tactics using repeat-match-progress. These are not particularly\n   * useful for this goal, just a reference for proof-scripting syntax. *)\n\n  all:\n    repeat match goal with\n    | x : bool |- _\n        => progress (cases x)\n    | H : Some _ = Some _ |- _\n        => progress (invert H)\n    | |- Some _ = Some _ =>\n        progress (apply f_equal)\n    | H : ?x = ?x + 1 |- _\n        => solve [linear_arithmetic]\n    | H : forall b, b = true -> _ |- _\n        => specialize (H true)\n    | _ => progress (simplify)\n    end.\n\nAdmitted.\n\n\n(** * Optimizing programs based on that analysis *)\n\n(* Our expression evaluator returns one of two outputs, for a particular input\n * expression: *)\n(* copy-pasted from sig file:\nInductive constfold_result :=\n| Known (n : nat)        (* The variable is exactly [n]. *)\n| Simplified (e : arith) (* I don't know the exact value, but it's the same as this\n                          * (potentially simplified) expression [e]. *).\n*)\n\n(* It's easy to convert a result back into a normal expression. *)\nDefinition to_arith (r : constfold_result) : arith :=\n  match r with\n  | Known n => Const n\n  | Simplified e => e\n  end.\n\n(* The optimizer for expressions is straightforward though a bit fiddly. *)\nFixpoint constfold_arith (e : arith) (s : astate constant_absint) : constfold_result :=\n  match e with\n  | Const n => Known n\n  | Var x =>\n    match s $? x with\n    | Some (Exactly n) => Known n\n    | _ => Simplified e\n    end\n  | Plus e1 e2 =>\n    match constfold_arith e1 s, constfold_arith e2 s with\n    | Known n1, Known n2 => Known (n1 + n2)\n    | e1', e2' => Simplified (Plus (to_arith e1') (to_arith e2'))\n    end\n  | Times e1 e2 =>\n    match constfold_arith e1 s, constfold_arith e2 s with\n    | Known n1, Known n2 => Known (n1 * n2)\n    | e1', e2' => Simplified (Times (to_arith e1') (to_arith e2'))\n    end\n  | Minus e1 e2 =>\n    match constfold_arith e1 s, constfold_arith e2 s with\n    | Known n1, Known n2 => Known (n1 - n2)\n    | e1', e2' => Simplified (Minus (to_arith e1') (to_arith e2'))\n    end\n  end.\n\n(* Now we get to the optimizer for commands, which is about as much code, but\n * which is significantly more intricate.  As with [absint_step], we pass a\n * parameter [C], standing for *the context in which this command will be\n * run.*  We also pass [ss], a map from commands to what we know about\n * variables, right before running the corresponding command.  That information\n * is enough for us to replace variable occurrences with their known constant\n * values. *)\nFixpoint constfold_cmd (c : cmd) (ss : astates constant_absint) (C : cmd -> cmd) : cmd :=\n  match c with\n  | Skip => Skip\n  | Assign x e =>\n    (* Note how here we query the abstract state [ss] with the current command\n     * [c] wrapped in [C].  In other words, we are querying the analysis\n     * result, asking \"when we reach this command, what is known to be true\n     * about the variable values?\". *)\n    match ss $? C c with\n    | None => Assign x e\n    | Some s => Assign x (to_arith (constfold_arith e s))\n                (* What do we do with what we learn?  If there are variable\n                 * values associated with this location in the program, we use\n                 * them to optimize the expression being assigned. *)\n    end\n  | Sequence c1 c2 => Sequence (constfold_cmd c1 ss (fun c' => C (Sequence c' c2)))\n                               (constfold_cmd c2 ss C)\n  | If e then_ else_ =>\n    If e (constfold_cmd then_ ss C)\n         (constfold_cmd else_ ss C)\n  | While e body =>\n    While e (constfold_cmd body ss (fun c' => C (Sequence c' c)))\n  end.\n\nDefinition compatible_throughout_steps {A} ss v c:= forall c' s v',\n  ss $? c' = Some s -> step^* (v, c) (v', c') -> @compatible A s v'.\n(* This line makes [eauto] treat [compatible_throughout_steps] as inlined: *)\nHint Unfold compatible_throughout_steps : core.\n\n\n(* Prove: any sequence of small steps can be replicated with the optimized command. *)\nLemma constfold_steps : forall v c v' c',\n  step^* (v, c) (v', c') ->\n  forall ss, compatible_throughout_steps ss v c ->\n  step^* (v, constfold_cmd c ss (fun c1 => c1))\n  (v', constfold_cmd c' ss (fun c1 => c1)).\nProof.\nAdmitted.\n\n(* Prove: any full program execution can be replicated with the optimized program. *)\nLemma eval_constfold : forall v c v',\n  eval v c v' ->\n  forall ss, compatible_throughout_steps ss v c ->\n  eval v (constfold_cmd c ss (fun c1 => c1)) v'.\nProof.\nAdmitted.\n\n(* This lemma connects the previous to the [invariantFor] goal that FRAP abstract-interpretation machinery proves. *)\nLemma optimize_program_ok : forall v c v' ss,\n  eval v c v'\n  -> invariantFor (absint_trsys constant_absint c)\n                  (fun p => exists s, ss $? snd p = Some s\n                                      /\\ subsumed (fst p) s)\n  -> eval v (constfold_cmd c ss (fun c1 => c1)) v'.\nProof.\n  simplify.\n  apply eval_constfold; auto.\n  eapply invariant_simulates with (sys1 := trsys_of v c) in H0;\n    try (apply absint_simulates with (a := constant_absint); apply constant_sound).\n  unfold compatible_throughout_steps.\n  simplify.\n  eapply use_invariant in H0; simplify; eauto.\n  invert H0.\n  invert H3.\n  invert H4.\n  invert H0.\n  simplify.\n  replace s with x in * by equality.\n  eauto.\nQed.\n\n(* Optional: Actually run your analysis to justify an automatic optimization. \n * You won't be graded on that part, but it's satisfying to run to wrap up the assignment! *)\n\nExample loopsy :=\n  \"a\" <- 7;;\n  \"b\" <- 0;;\n  while \"n\" loop\n    \"b\" <- \"b\" + \"a\";;\n    \"n\" <- \"n\" - 1\n  done.\n\nExample loopsy_optimized :=\n  \"a\" <- 7;;\n  \"b\" <- 0;;\n  while \"n\" loop\n    \"b\" <- \"b\" + 7;;\n    \"n\" <- \"n\" - 1\n  done.\n\n(* Here are some hints we add, to get the iteration tactics to work properly. *)\nLemma merge_astates_fok_constant : forall x : option (astate constant_absint),\n  match x with Some x' => Some x' | None => None end = x.\nProof.\n  simplify; cases x; equality.\nQed.\nLemma merge_astates_fok2_constant : forall x (y : option (astate constant_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.\nHint Resolve merge_astates_fok_constant merge_astates_fok2_constant : core.\n\n(* This part takes ~3GB of RAM and 10 minutes on the laptop we tested with. *)\n(*\nLemma loopsy_optimized_properly : forall v v',\n  eval v loopsy v'\n  -> eval v loopsy_optimized v'.\nProof.\n  simplify.\n  assert (exists ss, invariantFor (absint_trsys constant_absint loopsy)\n                                  (fun p => exists s, ss $? snd p = Some s\n                                                      /\\ subsumed (fst p) s)\n                     /\\ loopsy_optimized = constfold_cmd loopsy ss (fun c1 => c1)).\n\n  eexists; propositional.\n  \n  apply interpret_sound.\n  apply constant_sound.\n\n  unfold loopsy.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret_done.\n\n  simplify.\n  equality.\n\n  first_order.\n  rewrite H1.\n  apply optimize_program_ok.\n  assumption.\n  assumption.\nQed.\n*)\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/pset06_AbstractInterpretation/Pset6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7548924135065979}}
{"text": "(** * Tutoriel 4 - Extraction de programmes à partir de preuves *)\n\n(** Dans ce tutoriel, nous allons extraire des programmes à partir de preuves\n    simples sur les nombres naturels. *)\n\nRequire Extraction. (* Commentez cette ligne pour les anciennes \n                       versions de Coq. *)\n\n(** ** Exercice 1 - Relation d'Ackermann *)\n\n(** Nous définissons une relation [ack : nat -> nat -> nat -> Prop] qui est\n    la spécification de la fonction d'Ackermann : [ack m n r] signifie que\n    le résultat de la fonction sur [m] et [n] doit être [r]. *)\n\nInductive ack : nat -> nat -> nat -> Prop :=\n  | ack_0_n : forall n, ack O n (S n)\n  | ack_m_0 : forall m r, ack m (S O) r -> ack (S m) O r\n  | ack_m_n : forall m n r r',\n      ack (S m) n r -> ack m r r' -> ack (S m) (S n) r'.\n\n(** Prouvons que la relation est totale.\n    Faites attention à bien commencer votre preuve, ce n'est pas simple ! *)\n\nLemma ack_total : forall m n, exists r, ack m n r.\nProof.\n  (** Dans cette preuve, vous pouvez trouver utile de choisir des noms lors de\n      la destruction d'une existentielle, en utilisant [destruct ... as (x,H)].\n\n      Vous pouvez aussi utiliser [assumption] au lieu d'utiliser explicitement\n      [exact H] lorsque la conclusion du but est l'une de ses hypothèses. *)\n  induction m.\n  + intro n. exists (S n). apply (ack_0_n n).\n  + induction n.\n    ++ (* pose proof (IHm 1) as toto. *)\nassert (exists r1, ack m 1 r1) by (apply (IHm 1)). destruct H as [r1]. exists r1. apply ack_m_0. exact H.\n    ++ destruct IHn as [rn]. pose proof (IHm rn). destruct H0 as [rn']. exists rn'. apply (ack_m_n m n rn rn' H H0).\nQed.\n(** Demandez à Coq d'extraire un programme de la preuve [ack_total].\n    Le résultat est décevant : c'est parce que le contenu calculatoire des \n    objets de [Prop] est effacé. *)\n\nExtraction ack_total.\n\n(** L'expression [exists x:A, P x] est une notation pour [ex A P].\n    Le type [ex] est défini de manière inductive : ses habitants \n    (c'est-à-dire les preuves des énoncés existentiels) ne peuvent \n    être dérivés qu'à l'aide de [ex_intro], c'est-à-dire en \n    fournissant un témoin [x] et une preuve de [P x]. *)\n\nPrint ex.\n\n(** Coq vient avec une variante de [ex] appelée [sig] qui définit\n    la quantification existentielle sur [Type] plutôt que sur [Prop].\n    L'expression [{x : A | P x}] est une notation pour [sig A P]. *)\n\nCheck { r : nat | ack 2 3 r }.\nPrint sig.\n\n(** Prouvons la totalité en utilisant [sig]. *)\n\nLemma ack_total_sig : forall m n, { r | ack m n r }.\nProof.\n  (** Les éléments suivants ne seront pas autorisés :\n\n      intros. destruct (ack_total m n).\n\n      En effet, nous ne pouvons pas utiliser [ack_total], qui n'a pas de\n      sens du point de vue du calcul, pour définir [ack_total_sig].\n\n      Cependant, copier le script de preuve de [ack_total] devrait fonctionner.\n      En particulier, [destruct] fonctionne de manière similaire sur [ex] et \n      sur [sig].\n\n      À la fin, utilisez [Defined] plutôt que [Qed] pour éviter les \n      avertissements : ceci informe Coq que nous nous intéressons au contenu \n      de la preuve, et pas seulement au fait que l'énoncé est prouvable. *)\n  induction m.\n  + intro n. exists (S n). apply (ack_0_n n).\n  + induction n.\n    ++ pose proof (IHm 1). destruct H as [r1]. exists r1. apply ack_m_0. exact a.\n    ++ destruct IHn as [rn]. pose proof (IHm rn). destruct H as [rn']. exists rn'. apply (ack_m_n m n rn rn' a a0).\nQed.\n\n(** Nous pouvons maintenant extraire quelque chose d'intéressant de la preuve\n    de la totalité. *)\n\nExtraction ack_total_sig.\n\n\n(** ** Exercice 2 - Fonction d'Ackermann *)\n\n(** Nous allons extraire la fonction d'Ackermann à partir d'une preuve de la\n    totalité de la relation d'Ackermann. Il est également possible (et souvent\n    pratique) de définir la fonction explicitement dans Coq.\n\n    La fonction sera essentiellement définie par induction sur les nombres \n    naturels. Concrètement, nous formerons une définition [Fixpoint] : elle \n    permet de définir une fonction récursive tant qu'un argument décroît\n    strictement dans ces appels, de sorte que la terminaison est assurée.\n    Ici, \"décroissant\" signifie que le nouvel argument doit être un \n    sous-terme strict de l'argument (fini) initial.\n\n    Par exemple, dans la (re)définition suivante de la fonction d'addition,\n    l'argument décroissant est le premier : le seul appel récursif est un\n    un sous-terme strict [m'] de [m]. *)\n\nFixpoint addition (m:nat) (n:nat) : nat :=\n   match m with\n    | O => n\n    | S m' => S (addition m' n)\n  end.\n\n(** Définissons d'abord [fack'] de telle sorte que, si [fack_m] est la fonction\n    d'Ackermann avec un premier argument fixé à [m], alors [fack' fack_m n] est\n    le résultat de la fonction d'Ackermann pour [S m] et [n]. *)\n\nFixpoint fack' (fack_m : nat -> nat) (n:nat) : nat := match n with\n  | O => fack_m 1\n  | S n' => fack_m (fack' fack_m n')\nend.\n\n(** Définissez maintenant [fack] comme étant la fonction d'Ackermann. *)\n\nFixpoint fack (m:nat) (n:nat) : nat := match m with\n  | 0 => (S n)\n  | S m' => match n with \n          | 0 => (fack m' 1)\n          | S n' => (fack m' (fack (S m') n'))\n        end\nend.\n\n(** Prouvez que [fack] implémente la spécification d'Ackermann. *)\n\nLemma fack_correct : forall m n, ack m n (fack m n).\nProof.\nAdmitted.\n\n(** On obtient ainsi une nouvelle preuve de la totalité. *)\n\nLemma ack_total_fun : forall m n, { r | ack m n r }.\nProof.\n  intros m n. exists (fack m n). apply fack_correct.\nDefined.\n\nRecursive Extraction ack_total_fun.\n\n(** Calculons quelques valeurs de la fonction. *)\n\nLemma ack_3_3 : { x : nat | ack 3 3 x }.\nProof.\n  apply ack_total_fun.\nDefined.\n\n(** L'extraction nous donne un programme que nous pourrions exécuter\n    en OCaml. *)\n\nRecursive Extraction ack_3_3.\n\n(** Mais puisque nous avons une fonction Coq, nous pouvons aussi \n    l'évaluer directement. *)\n\nEval compute in fack 3 3.\n\n(** Nous pouvons également dérouler ce résultat à partir du type [sig] de\n    l'une de nos preuves d'existence. *)\n\nEval compute in ack_total_fun 3 3.\nEval compute in let (x,_) := ack_total_fun 3 3 in x.\nEval compute in let (x,_) := ack_total_sig 3 3 in x.\n\n(** ** Exercice 3 - Induction sur une relation *)\n\n(** Jusqu'à présent, nous n'avons pas utilisé le fait que [ack] est donné comme\n    une définition [Inductive]. Nous l'utiliserons ensuite pour prouver\n    l'unicité : parce que [ack] est inductive, vous avez un schéma \n    d'induction pour elle, que vous pouvez utiliser à travers la tactique\n    d'induction : si [H : ack m n r], essayez d'utiliser [induction H]. *)\n\nCheck ack_ind.\n\nLemma ack_unicity : forall m n r1,\n  ack m n r1 -> forall r2, ack m n r2 -> r1 = r2.\nProof.\n  (** N'utilisez PAS les inductions sur [m] et [n] : faites une induction sur \n      [ack m n r] directement.\n      Attention : le [forall r2] n'arrive pas tout de suite dans la formule \n      pour une bonne raison. *)\nAdmitted.\n\n(** Merci à David Baelde. *)", "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/TD5_Extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8670357683915537, "lm_q1q2_score": 0.7548389657519549}}
{"text": "Require Import Lambda.Util.Basic.\n\n(** * De Bruijn Syntax of Terms *)\n\nInductive expr : Set :=\n| Var (n : nat)\n| Lam (e : expr)\n| App (e1 e2 : expr).\n(**[]*)\n\nDeclare Scope expr_scope.\nDelimit Scope expr_scope with expr.\n\nNotation \"'λ' e\" := (Lam e) (at level 10) : expr_scope.\nNotation \"e1 ⋅ e2\" := (App e1 e2) (at level 8, left associativity) : expr_scope.\nNotation \"! n\" := (Var n) (at level 0) : expr_scope.\n\nOpen Scope expr_scope.\n\n(** Shifts free variables in [e] above a cutoff [c] up by [i]. *)\nFixpoint lift (c i : nat) (e : expr) : expr :=\n  match e with\n  | !n => ! match lt_dec n c with\n           | left _ => n\n           | right _ => n + i\n           end\n  | λ e => λ (lift (S c) i e)\n  | e1 ⋅ e2 => (lift c i e1) ⋅ (lift c i e2)\n  end.\n(**[]*)\n\n(** Substitution [e{esub/i}]. *)\nFixpoint subst (i : nat) (esub e : expr) : expr :=\n  match e with\n  | !n => match lt_eq_lt_dec i n with\n         | inleft (left _) => ! (pred n)\n         | inleft (right _) => lift 0 i esub\n         | inright _ => !n\n         end\n  | λ e => λ (subst (S i) esub e)\n  | e1 ⋅ e2 => (subst i esub e1) ⋅ (subst i esub e2)\n  end.\n(**[]*)\n\nSection FrenchLemmas.\n  (** The confluence proof reqiured\n      evidence of some properties of\n      shifting of de Bruijn indices.\n      What these properties were was\n      elusive to me, so I have looked\n      to the work of a wise French person,\n      who formalized the Calculus of Constructions in Coq.\n      [http://www.lix.polytechnique.fr/~barras/CoqInCoq/Termes.html] *)\n\n  Lemma lift0 : forall e k, lift k 0 e = e.\n  Proof.\n    induction e; intros; simpl;\n      clean_compare; f_equal; auto 1.\n  Qed.\n\n  Lemma simpl_lift : forall e n p k i,\n      i <= k + n -> k <= i ->\n      lift i p (lift k n e) = lift k (p + n) e.\n  Proof.\n    induction e; intros; simpl;\n      clean_compare; f_equal; auto 2; try lia.\n    apply IHe; lia.\n  Qed.\n\n  Local Hint Extern 0 => rewrite simpl_lift by lia; reflexivity : core.\n\n  Lemma permute_lift : forall e n k p i,\n      i <= k -> lift i p (lift k n e) = lift (p + k) n (lift i p e).\n  Proof.\n    induction e; intros; simpl;\n      clean_compare; f_equal; auto 2; try lia.\n    rewrite IHe by lia. f_equal; lia.\n  Qed.\n\n  Local Hint Extern 0 => rewrite permute_lift by lia; reflexivity : core.\n  \n  Lemma simpl_subst : forall M N n p k,\n      p <= n + k -> k <= p ->\n      subst p N (lift k (S n) M) = lift k n M.\n  Proof.\n    induction M; intros; simpl;\n      clean_compare; f_equal; auto 2; try lia.\n    apply IHM; lia.\n  Qed.\n\n  Local Hint Extern 0 => rewrite simpl_subst by lia; reflexivity : core.\n  \n  Lemma commute_lift_subst : forall M N n p k,\n      k <= p ->\n      lift k n (subst p N M) = subst (n + p) N (lift k n M).\n  Proof.\n    induction M; intros; simpl;\n      clean_compare;\n      try (f_equal; auto 2; lia).\n    f_equal; rewrite IHM by lia.\n    f_equal; lia.\n  Qed.\n\n  Local Hint Extern 0 => rewrite commute_lift_subst by lia; reflexivity : core.\n\n  Lemma distr_lift_subst : forall M N n p k,\n      lift (p + k) n (subst p N M) = subst p (lift k n N) (lift (S (p + k)) n M).\n  Proof.\n    induction M; intros; simpl;\n      clean_compare;\n      try (f_equal; auto 2; lia).\n    f_equal; rewrite <- IHM; f_equal; lia.\n  Qed.\n\n  Lemma distr_lift_subst0 : forall M N n k,\n      lift k n (subst 0 N M) = subst 0 (lift k n N) (lift (S k) n M).\n  Proof.\n    intros. replace k with (0 + k) at 1 by lia.\n    replace k with (0 + k) at 3 by lia.\n    apply distr_lift_subst.\n  Qed.\n  \n  Lemma distr_sub : forall M N P n p,\n      subst (p + n) P (subst p N M) =\n      subst p (subst n P N) (subst (S (p + n)) P M).\n  Proof.\n    induction M; intros; simpl;\n      clean_compare; try (f_equal; auto 2; lia).\n    f_equal; rewrite <- IHM; f_equal; lia.\n  Qed.\n\n  Lemma distr_sub0 : forall M N P n,\n      subst n P (subst 0 N M) =\n      subst 0 (subst n P N) (subst (S n) P M).\n  Proof.\n    intros. replace n with (0 + n) at 1 by lia.\n    replace n with (0 + n) at 3 by lia.\n    apply distr_sub.\n  Qed.\nEnd FrenchLemmas.\n\n(** * Reduction Strategies *)\n\n(** Non-determistic reduction. *)\nReserved Notation \"e1 '-->' e2\" (at level 40).\n\nInductive step : expr -> expr -> Prop :=\n| step_beta e1 e2 :\n    (λ e1) ⋅ e2 -->  subst 0 e2 e1\n| step_lambda e e' :\n    e -->  e' ->\n    λ e -->  λ e'\n| step_app_l e1 e1' e2 :\n    e1 -->  e1' ->\n    e1 ⋅ e2 -->  e1' ⋅ e2\n| step_app_r e1 e2 e2' :\n    e2 -->  e2' ->\n    e1 ⋅ e2 -->  e1 ⋅ e2'\nwhere \"e1 '-->' e2\" := (step e1 e2).\n(**[]*)\n\nInductive is_lambda : expr -> Prop :=\n| IsLambda e : is_lambda (λ e).\n(**[]*)\n\nLtac not_is_lambda_lambda :=\n  match goal with\n  | H: ~ is_lambda (λ _)\n    |- _ => exfalso; apply H; constructor\n  end.\n(**[]*)\n\n(** No beta-reduxes. *)\nInductive normal_form : expr -> Prop :=\n| nf_var n :\n    normal_form !n\n| nf_app e1 e2 :\n    ~ is_lambda e1 ->\n    normal_form e1 ->\n    normal_form e2 ->\n    normal_form (e1 ⋅ e2)\n| nf_lam e :\n    normal_form e ->\n    normal_form (λ e).\n(**[]*)\n\nSection NormalForm.\n  Local Hint Extern 0 => not_is_lambda_lambda : core.\n  Hint Constructors is_lambda : core.\n\n  Ltac contra_step :=\n    match goal with\n    | H: ?e -->  _, IH : (forall _, ~ ?e -->  _)\n      |- _ => apply IH in H; contradiction\n    end.\n\n  Hint Extern 0 => contra_step : core.\n\n  Theorem normal_form_step : forall e e',\n    normal_form e -> ~ e -->  e'.\n  Proof.\n    intros e e' HN; generalize dependent e';\n      induction HN; intros ? H'; inv H'; auto 2.\n  Qed.\nEnd NormalForm.\n\nNotation \"e1 '-->*' e2\" := (refl_trans_closure step e1 e2) (at level 40).\n\nLemma why : forall (X : Type) (P : X -> Prop),\n    (forall x, ~ P x) -> ~ exists x, P x.\nProof.\n  intros X P HP [x H].\n  apply HP in H. contradiction.\nQed.\n\nLemma why' : forall (X : Type) (P : X -> Prop),\n    (~ exists x, P x) -> forall x, ~ P x.\nProof.\n  intros X P H x HP. eauto.\nQed.\n\nSection Confluence.\n  Local Hint Constructors step : core.\n  Local Hint Constructors refl_trans_closure : core.\n  Local Hint Resolve inject_trans_closure : core.\n\n  Lemma reduce_lambda : forall e e',\n      e -->* e' -> λ e -->* λ e'.\n  Proof. intros e e' H; induction H; eauto 3. Qed.\n\n  Lemma reduce_app_l : forall e1 e1' e2,\n      e1 -->* e1' -> e1 ⋅ e2 -->* e1' ⋅ e2.\n  Proof. intros e1 e1' e2 H; induction H; eauto 3. Qed.\n\n  Lemma reduce_app_r : forall e1 e2 e2',\n      e2 -->* e2' -> e1 ⋅ e2 -->* e1 ⋅ e2'.\n  Proof. intros e1 e2 e2' H; induction H; eauto 3. Qed.\n\n  Local Hint Resolve reduce_lambda : core.\n  Local Hint Resolve reduce_app_l : core.\n  Local Hint Resolve reduce_app_r : core.\n  \n  Lemma reduce_app : forall e1 e1' e2 e2',\n      e1 -->* e1' -> e2 -->* e2' -> e1 ⋅ e2 -->* e1' ⋅ e2'.\n  Proof.\n    intros ? ? ? ? H1 H2; inv H1; inv H2; eauto 3.\n    transitivity (e1' ⋅ e2); eauto 3.\n  Qed.\n\n  Local Hint Resolve reduce_app : core.\n  \n  Lemma sub_right_step : forall er er' el c,\n      er -->  er' -> subst c el er -->  subst c el er'.\n  Proof.\n    intros ? ? el c Her;\n      generalize dependent c;\n      generalize dependent el;\n      induction Her; intros; simpl; auto 2.\n    rewrite distr_sub0; auto 1.\n  Qed.\n\n  Lemma lift_step : forall e e' c i,\n      e -->  e' -> lift c i e -->  lift c i e'.\n  Proof.\n    intros ? ? c i He;\n      generalize dependent i;\n      generalize dependent c;\n      induction He; intros; simpl; clean_compare.\n    rewrite distr_lift_subst0; auto 1.\n  Qed.\n\n  Local Hint Resolve lift_step : core.\n  \n  Lemma sub_left_step : forall er el el' c,\n      el -->  el' -> subst c el er -->* subst c el' er.\n  Proof. induction er; intros; simpl; clean_compare. Qed.\n\n  Local Hint Resolve sub_right_step : core.\n  Local Hint Resolve sub_left_step : core.\n  \n  Theorem confluence : forall e e1 e2,\n      e -->  e1 -> e -->  e2 -> exists e', e1 -->* e' /\\ e2 -->* e'.\n  Proof.\n    intros ? ? e2 H1;\n      generalize dependent e2;\n      induction H1; intros ? H2; inv H2; eauto 7.\n    - inv H3; eauto 6.\n    - pose proof IHstep _ H0 as [? [? ?]]; eauto 5.\n    - inversion H1; subst.\n      pose proof IHstep _ H1 as [? [? ?]];\n        clear IHstep; eauto 6.\n    - pose proof IHstep _ H4 as [? [? ?]]; eauto 5.\n    - pose proof IHstep _ H4 as [? [? ?]]; eauto 5.\n  Qed.\nEnd Confluence.\n\n(** Deterministic reduction. *)\n\nInductive shallow_value : expr -> Prop :=\n| shl_var n : shallow_value !n\n| shl_lam e : shallow_value (λ e).\n(**[]*)\n\nInductive deep_value : expr -> Prop :=\n| dp_var n :\n    deep_value !n\n| dp_lam e :\n    deep_value e ->\n    deep_value (λ e)\n| dp_app e1 e2 :\n    ~ is_lambda e1 ->\n    deep_value e1 ->\n    deep_value e2 ->\n    deep_value (e1 ⋅ e2).\n(**[]*)\n\n(** Call-by-value. *)\n\nReserved Notation \"e1 '⟶' e2\" (at level 40).\n\nInductive cbv_reduce : expr -> expr -> Prop :=\n| cbv_beta e1 e2 :\n    shallow_value e2 ->\n    (λ e1) ⋅ e2 ⟶  subst 0 e2 e1\n| cbv_app_r e1 e2 e2' :\n    shallow_value e1 ->\n    e2 ⟶  e2' ->\n    e1 ⋅ e2 ⟶  e1 ⋅ e2'\n| cbv_app_l e1 e1' e2 :\n    e1 ⟶  e1' ->\n    e1 ⋅ e2 ⟶   e1' ⋅ e2\nwhere \"e1 '⟶' e2\" := (cbv_reduce e1 e2).\n\n(** Call-by-name. *)\n\nReserved Notation \"e1 '==>' e2\" (at level 40).\n\nInductive cbn_reduce : expr -> expr -> Prop :=\n| cbn_beta e1 e2 :\n    (λ e1) ⋅ e2 ==>  subst 0 e2 e1\n| cbn_app_l e1 e1' e2 :\n    e1 ==>  e1' ->\n    e1 ⋅ e2 ==>  e1' ⋅ e2\nwhere \"e1 '==>' e2\" := (cbn_reduce e1 e2).\n\n(** Normal-order. *)\n\nReserved Notation \"e1 '>->' e2\" (at level 40).\n\nInductive normal_reduce : expr -> expr -> Prop :=\n| normal_beta e1 e2 :\n    (λ e1) ⋅ e2 >-> subst 0 e2 e1\n| normal_lambda e e' :\n    e >-> e' ->\n    λ e >-> λ e'\n| normal_app_r e1 e2 e2' :\n    ~ is_lambda e1 ->\n    normal_form e1 ->\n    e2 >-> e2' ->\n    e1 ⋅ e2 >-> e1 ⋅ e2'\n| normal_app_l e1 e1' e2 :\n    ~ is_lambda e1 ->\n    e1 >-> e1' ->\n    e1 ⋅ e2 >-> e1' ⋅ e2\nwhere \"e1 '>->' e2\" := (normal_reduce e1 e2).\n\n(** Applicative-order. *)\n\nReserved Notation \"e1 '⇢' e2\" (at level 40).\n\nInductive appl_reduce : expr -> expr -> Prop :=\n| appl_beta e1 e2 :\n    deep_value e1 ->\n    deep_value e2 ->\n    (λ e1) ⋅ e2 ⇢ subst 0 e2 e1\n| appl_lambda e e' :\n    e ⇢ e' ->\n    λ e ⇢ λ e'\n| appl_app_r e1 e2 e2' :\n    deep_value e1 ->\n    e2 ⇢ e2' ->\n    e1 ⋅ e2 ⇢ e1 ⋅ e2'\n| appl_app_l e1 e1' e2 :\n    e1 ⇢ e1' ->\n    e1 ⋅ e2 ⇢ e1' ⋅ e2\nwhere \"e1 '⇢' e2\" := (appl_reduce e1 e2).\n(**[]*)\n\nLtac cbv_step_lambda :=\n  match goal with\n  | H: λ _ ⟶  _ |- _ => inv H\n  end.\n(**[]*)\n\nLtac cbn_step_lambda :=\n  match goal with\n  | H: λ _ ==>   _ |- _ => inv H\n  end.\n(**[]*)\n\nLtac normal_step_app_var :=\n  match goal with\n  | H: !_ >-> _ |- _ => inv H\n  end.\n(**[]*)\n\nSection Shallow.\n  Local Hint Constructors shallow_value : core.\n\n  Lemma cbv_reduce_value : forall e e',\n      e ⟶   e' -> ~ shallow_value e.\n  Proof. intros ? ? H Hv; inv H; inv Hv. Qed.\n\n  Lemma cbn_reduce_value : forall e e',\n      e ==>  e' -> ~ shallow_value e.\n  Proof. intros ? ? H Hv; inv H; inv Hv. Qed.\nEnd Shallow.\n\nSection Deep.\n  Local Hint Constructors deep_value : core.\n  Local Hint Extern 0 => not_is_lambda_lambda : core.\n\n  Lemma appl_reduce_value : forall e e',\n      e ⇢ e' -> ~ deep_value e.\n  Proof.\n    intros ? ? H Hv; induction H; inv Hv; auto 2.\n  Qed.\n\n  Lemma normal_reduce_value : forall e e',\n      e >-> e' -> ~ deep_value e.\n  Proof.\n    intros ? ? H Hv; induction H; inv Hv; auto 2.\n  Qed.\nEnd Deep.\n\nSection NormalFormReduce.\n  Local Hint Constructors normal_form : core.\n  Local Hint Extern 0 => not_is_lambda_lambda : core.\n\n  Lemma normal_form_reduce : forall e e',\n      e >-> e' -> ~ normal_form e.\n  Proof.\n    intros ? ? He Hnf; induction He; inv Hnf; auto 2.\n  Qed.\nEnd NormalFormReduce.\n\nLtac contra_cbv_value :=\n  match goal with\n  | H: ?e ⟶  _, Hv: shallow_value ?e\n    |- _ => apply cbv_reduce_value in H; contradiction\n  end.\n(**[]*)\n\nLtac contra_appl_value :=\n  match goal with\n  | H: ?e ⇢ _, Hv: deep_value ?e\n    |- _ => apply appl_reduce_value in H; contradiction\n  end.\n(**[]*)\n\nLtac contra_cbn_value :=\n  match goal with\n  | H: ?e ==>  _, Hv: shallow_value ?e\n    |- _ => apply cbn_reduce_value in H; contradiction\n  end.\n(**[]*)\n\nLtac contra_normal_value :=\n  match goal with\n  | H: ?e >-> _, Hv: normal_form ?e\n    |- _ => apply normal_form_reduce in H; contradiction\n  end.\n(**[]*)\n\nSection Determinism.\n  Section CBV.\n    Local Hint Extern 0 => contra_cbv_value : core.\n    Local Hint Extern 0 => cbv_step_lambda : core.\n\n    Theorem cbv_deterministic : deterministic cbv_reduce.\n    Proof. ind_det; f_equal; eauto 2. Qed.\n  End CBV.\n\n  Section CBN.\n    Local Hint Extern 0 => cbn_step_lambda : core.\n    \n    Theorem cbn_deterministic : deterministic cbn_reduce.\n    Proof. ind_det; f_equal; eauto 2. Qed.\n  End CBN.\n\n  Local Hint Extern 0 => not_is_lambda_lambda : core.\n  \n  Section NORMAL.\n    Local Hint Extern 0 => normal_step_app_var : core.\n    Local Hint Extern 0 => contra_normal_value : core.\n    \n    Theorem normal_deterministic : deterministic normal_reduce.\n    Proof. ind_det; f_equal; eauto 2. Qed.\n  End NORMAL.\n\n  Section APPL.\n    Local Hint Extern 0 => contra_appl_value : core.\n\n    Local Hint Extern 1 =>\n    match goal with\n    | H: λ ?e ⇢ _, Hv: deep_value ?e\n      |- _ => inv H\n    end : core.    \n    \n    Theorem appl_deterministic : deterministic appl_reduce.\n    Proof. ind_det; f_equal; eauto 2. Qed.\n  End APPL.\nEnd Determinism.\n\nSection ValueEXM.\n  Local Hint Constructors is_lambda : core.\n  \n  Lemma is_lambda_exm : forall e,\n    is_lambda e \\/ ~ is_lambda e.\n  Proof. intros []; auto 2; right; intros H; inv H. Qed.\n\n  Remove Hints is_lambda : core.\n  Local Hint Constructors shallow_value : core.\n\n  Lemma shallow_value_exm : forall e,\n      shallow_value e \\/ ~ shallow_value e.\n  Proof. intros []; auto 2; right; intros H; inv H. Qed.\n\n  Remove Hints shallow_value : core.\n  Local Hint Constructors deep_value : core.\n  (*Local Hint Resolve is_lambda_exm : core.*)\n\n  Lemma deep_value_exm : forall e,\n      deep_value e \\/ ~ deep_value e.\n  Proof.\n    induction e as\n        [ n\n        | e [IHe | IHe]\n        | e1 [IHe1 | IHe1] e2 [IHe2 | IHe2]]; auto 3;\n    try match goal with\n        | H: ~ deep_value ?e |- context [?e]\n          => right; intros H'; inv H'; contradiction\n        end.\n    - destruct (is_lambda_exm e1) as [He1 | He1]; auto 3.\n      right; intros H'; inv H'; contradiction.\n  Qed.\nEnd ValueEXM.\n\nSection NFEXM.\n  Local Hint Constructors normal_form : core.\n\n  Lemma normal_form_exm : forall e, normal_form e \\/ ~ normal_form e.\n  Proof.\n    intro e;\n      induction e as [ n\n                     | e [IHe | IHe]\n                     | e1 [IHe1 | IHe1] e2 [IHe2 | IHe2]]; eauto;\n        try (right; intros Hwrong; inv Hwrong; contradiction).\n    destruct (is_lambda_exm e1) as [He1 | ?]; try inv He1; eauto.\n    right; intros Hwrong; inv Hwrong. not_is_lambda_lambda.\n  Qed.\nEnd NFEXM.\n\nSection InjectStep.\n  Local Hint Constructors step : core.\n\n  Theorem cbv_step : forall e e', e ⟶  e' -> e -->  e'.\n  Proof. intros ? ? H; induction H; auto 2. Qed.\n\n  Theorem cbn_step : forall e e', e ==>  e' -> e -->  e'.\n  Proof. intros ? ? H; induction H; auto 2. Qed.\n\n  Theorem normal_step : forall e e', e >-> e' -> e -->  e'.\n  Proof. intros ? ? H; induction H; auto 2. Qed.\n\n  Theorem appl_step : forall e e', e ⇢ e' -> e -->  e'.\n  Proof. intros ? ? H; induction H; auto 2. Qed.\nEnd InjectStep.\n\nSection EXM.\n  Local Hint Constructors step : core.\n\n  Lemma step_exm : forall e,\n      (exists e', e -->  e') \\/ (forall e', ~ e -->  e').\n  Proof.\n    intro e;\n      induction e as\n        [ n\n        | e [[e' IHe] | IHe]\n        | e1 [[e1' IHe1] | IHe1] e2 [[e2' IHe2] | IHe2]];\n      eauto.\n    - right; intros ? H; inv H.\n    - right; intros e' H; inv H.\n      intuition; eauto.\n    - destruct e1 as [? | e1 | ? ?]; eauto;\n      right; intros e' H; inv H;\n        intuition; eauto.\n  Qed.\nEnd EXM.\n\nNotation \"e1 >->* e2\" := (refl_trans_closure normal_reduce e1 e2) (at level 40).\n\nTheorem contrapositive : forall P Q : Prop,\n    (P -> Q) -> (~ Q -> ~ P).\nProof. intuition. Qed.\n\nSection Normalizing.\n  Local Hint Resolve inject_trans_closure : core.\n  Local Hint Constructors normal_reduce : core.\n  Local Hint Constructors refl_trans_closure : core.\n  Local Hint Constructors normal_form : core.\n\n  Lemma normal_reduce_lambda : forall e e',\n      e >->* e' -> λ e >->* λ e'.\n  Proof.\n    intros e e' H; induction H; eauto 3.\n  Qed.\n\n  Local Hint Resolve normal_form_exm : core.\n  Local Hint Unfold Decidable.decidable : core.\n\n  Lemma nor_normal_form_normal_reduce : forall e,\n      ~ normal_form e -> exists e', e >-> e'.\n  Proof.\n    intro e;\n      induction e as [ n\n                     | e IHe\n                     | e1 IHe1 e2 IHe2 ];\n      intros Hnf; try (exfalso; eauto; contradiction).\n    - pose proof IHe (contrapositive _ _ (nf_lam e) Hnf) as [? ?]; eauto.\n    - pose proof is_lambda_exm e1 as [He1 | He1].\n      + inv He1. eauto.\n      + destruct (normal_form_exm e1) as [Hnf1 | Hnf1].\n        * pose proof IHe2 (contrapositive _ _ (nf_app _ e2 He1 Hnf1) Hnf) as [? ?]; eauto.\n        * pose proof IHe1 Hnf1 as [? ?]; eauto.\n  Qed.\n        \n  Local Hint Resolve normal_step : core.\n  \n  Lemma step_normal_reduce : forall e e',\n      e -->  e' -> exists e'', e >-> e''.\n  Proof.\n    intros e e' H; induction H;\n      repeat match goal with\n             | IH: exists _, _ >-> _ |- _ => destruct IH as [? ?]\n             end; eauto;\n    try match goal with\n        | |- exists _, ?e1 ⋅ _ >-> _\n          => destruct (is_lambda_exm e1) as [? | ?];\n              try match goal with\n                  | H: is_lambda _ |- _ => inv H\n                  end; eauto\n        end.\n    destruct (normal_form_exm e1); eauto.\n    apply nor_normal_form_normal_reduce in H2 as [? ?]; eauto.\n  Qed.\n\n  Local Hint Constructors is_lambda : core.\n  \n  Lemma multi_step_lambda : forall e e',\n      λ e -->* e' -> is_lambda e'.\n  Proof.\n    intros e e' H.\n    remember (λ e) as le eqn:Heqle;\n      generalize dependent e.\n    induction H; intros; subst; eauto.\n    inv H. eauto.\n  Qed.\n\n  Lemma multi_step_lambda_step_inner : forall e e',\n      λ e -->* λ e' -> e -->* e'.\n  Proof.\n    intros e e' H.\n    remember (λ e) as le eqn:Heqle;\n      remember (λ e') as le' eqn:Heqle';\n      generalize dependent e';\n      generalize dependent e;\n      induction H; intros; subst.\n    - inv Heqle'. eauto.\n    - inv H. eauto.\n  Qed.\n  \n  Definition sn (R : expr -> expr -> Prop) : expr -> Prop :=\n    Acc (fun e' e => R e e').\n\n  Local Hint Constructors Acc : core.\n  Local Hint Unfold sn : core.\n  \n  Theorem normal_order_sn : forall e,\n      sn step e -> sn normal_reduce e.\n  Proof.\n    intros e Hsn; induction Hsn;\n      autounfold with core in *; eauto.\n  Qed.\n\n  Goal forall e, sn step e -> sn cbv_reduce e.\n  Proof.\n    intros e Hsn; induction Hsn;\n      unfold sn in *; eauto.\n    constructor.\n    intros e' He'.\n    assert (step x e') by eauto using cbv_step.\n    auto.\n  Qed.\nEnd Normalizing.\n\nSection Examples.\n  Example omega_term : expr := λ !0 ⋅ !0.\n\n  Local Hint Unfold omega_term : core.\n  Local Hint Extern 0 => not_is_lambda_lambda : core.\n  Local Hint Constructors is_lambda : core.\n\n  Example omega_does_not_halt : ~ halts_R step (omega_term ⋅ omega_term).\n  Proof.\n    unfold halts_R; intros [e [Hms Hns]].\n    remember (omega_term ⋅ omega_term) as oo eqn:Hoo.\n    induction Hms; subst.\n    - apply Hns with (omega_term ⋅ omega_term).\n      constructor.\n    - assert (a2 = omega_term ⋅ omega_term).\n      { clear a3 Hms IHHms Hns.\n        inv H; simpl; auto.\n        + inv H3. inv H0. inv H3. inv H3.\n        + inv H3. inv H0. inv H3. inv H3. }\n      subst. intuition.\n  Qed.\nEnd Examples.\n", "meta": {"author": "rudynicolop", "repo": "Lambda-Calculi-Coq", "sha": "8349d61a706210462986f4b4bb2dc8844cd9037f", "save_path": "github-repos/coq/rudynicolop-Lambda-Calculi-Coq", "path": "github-repos/coq/rudynicolop-Lambda-Calculi-Coq/Lambda-Calculi-Coq-8349d61a706210462986f4b4bb2dc8844cd9037f/lib/Vanilla.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.754838949300589}}
{"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\nTheorem len_append: forall (l1 l2: Lst), len (append l1 l2) = plus (len l1) (len l2).\nProof.\n  induction l1; induction l2; simpl.\n  { f_equal. rewrite IHl1. simpl. reflexivity. }\n  { f_equal. rewrite IHl1. simpl. reflexivity. }\n  { reflexivity. }\n  { reflexivity. }\nQed.\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 len_rev: forall (l: Lst), len (rev l) = len l.\nProof.\n  induction l; simpl.\n  { rewrite len_append. rewrite plus_comm. simpl. f_equal. assumption. }\n  { reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (len (rev (append x y))) (plus (len x) (len y)).\nProof.\n  intros.\n  rewrite len_rev.\n  apply len_append.\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/goal6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7546874416869442}}
{"text": "\n\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs.\nRequire Export DecSort MinMax.\nRequire Export DecType SetReflect.\nRequire Export DecList.\n\n\n\nSet Implicit Arguments.\n\n\n\nSection MoreDecList.\n\nContext { A: eqType}.\n(*------------------ Uniform list -----------------------------------------------------*)\n  \nInductive uniform : list A -> Prop:=\n| Nil_uni: uniform nil\n|Sing_uni(a:A): uniform (a::nil)\n|Ind_uni(a b:A)(l:list A): a=b -> uniform (b::l)-> uniform (a::b::l).\n\nLemma uniform_elim (a:A)(l: list A): uniform (a::l)-> (forall x, In x l -> x=a).\nProof. { revert l. induction l. \n       { simpl. intros H0 fA f. destruct f. }\n       { simpl. intros H fA. inversion H. intro H5.  destruct H5 as [H5| H6].\n        subst fA. symmetry. exact. apply IHl in H6. exact. subst a. exact. } } Qed. \n\n\nLemma uniform_elim1 (a:A)(l: list A): uniform (a::l)-> (forall x, In x (a::l)-> x=a).\nProof. { induction l. \n        { simpl. intros. destruct H0. auto. inversion H0. }\n        { intros. inversion H. subst a0.  simpl in H0. destruct H0. \n        auto. apply IHl. exact. simpl. exact. } } Qed.\n\nLemma uniform_elim2 (a:A) (l: list A): uniform (a::l)-> uniform l.\nProof. intro H. inversion H. constructor. exact. Qed.\n\nLemma uniform_elim4 (a1 a2:A) (l: list A) : uniform l -> In a1 l -> In a2 l -> a1=a2.\nProof. { induction l.\n         { simpl. intros H1 H2. destruct H2. }\n         { intros H1 H2 H3.\n           assert (H0:(forall x, In x (a::l)-> x=a)).\n           apply uniform_elim1. exact. specialize (H0 a1) as Ha1.\n           apply Ha1 in H2. specialize (H0 a2) as Ha2.\n           apply Ha2 in H3. subst a1. subst a2. auto. }} Qed.\n      \n\nLemma uniform_elim3 (a:A) (l:list A): uniform l -> uniform (delete a l).\nProof. { revert a. \n         induction l. \n         { simpl. auto. }\n         { intros.  \n           case l eqn:H0. \n           { simpl. destruct (a0==a) eqn: Ha. constructor. constructor. }\n           { simpl. destruct (a0==a) eqn: Ha. eapply uniform_elim2.\n             exact H.\n           { apply uniform_elim2 in H as H1.  specialize (IHl a0) as Hl.\n             apply Hl in H1. \n             destruct (a0 == e) eqn:Hae.\n             {  move /eqP in Ha.  move /eqP in Hae.  assert (H2: a<> e).\n                intro. subst a0. auto. \n                apply uniform_elim4 with (a1:=a) (a2:=e) in H. subst a. \n                destruct H2. all:auto. }\n             {  apply uniform_elim4 with (a1:=a) (a2:=e) in H.\n                subst a. constructor. auto. simpl in H1. \n                rewrite Hae in H1. all:auto.  }}}}} Qed.\n\nLemma uniform_intro (a:A)(l: list A): (forall x, In x l -> x=a) -> uniform (a::l).\nProof. { intros. induction l. \n         { simpl. intros. constructor. }\n         { simpl. intros.  assert (H1: (forall x : A, In x l -> x = a)).\n           auto. specialize (H a0) as Ha0. assert (H2: In a0 (a0 :: l)).\n           auto. apply Ha0 in H2. subst a0. apply IHl in H1.\n           constructor. auto. exact. }} Qed.\n\n(* ----------------- delete_all operation ---------------------------------------------  *)\n\nFixpoint del_all (a:A)(l: list A): list A:=\n    match l with\n    |nil => nil\n    | a1::l1 => match  (a == a1) with\n               |true => del_all a l1\n               |false => a1 :: del_all a l1\n               end\n    end.\n\n(* This function deletes all occurences of a in the list l *)\n\n  Lemma del_all_elim1 (a b:A)(l: list A): In a (del_all b l)-> In a l.\n  Proof. { induction l. \n          { simpl. auto. }\n          { simpl. destruct (a==a0) eqn:H0. intros. left. move /eqP in H0.\n            auto. destruct (b==a0) eqn:H1. intros. right. apply IHl in H.\n            exact. simpl. intros H2. destruct H2. left. exact.\n            right. apply IHl in H. exact. } } Qed.\n  \n  Lemma del_all_elim2 (a b:A)(l: list A): In a (del_all b l)-> (a<>b).\n  Proof. { induction l. \n          { simpl. auto. }\n          { simpl. destruct (b==a0) eqn:H0. exact. simpl. intros H1.\n            destruct H1.  move /eqP in H0. subst a0. auto. \n            apply IHl in H. exact. } } Qed.\n\n  Lemma del_all_intro (a b: A)(l:list A): In a l -> a<>b -> In a (del_all b l).\n  Proof. { induction l. \n          { simpl. auto. } \n          { simpl. intros H1 H2. destruct H1. destruct (b==a0) eqn: H3.\n            move /eqP in H3. subst a0. subst b. apply IHl in H2. exact. tauto.\n            simpl. left. auto. destruct (b==a0) eqn: H4. apply IHl in H2.\n            exact. exact. simpl. right. apply IHl in H2. exact. exact. }} Qed.\n  \n  \n  Lemma del_all_iff (a b:A)(l: list A): (In a (del_all b l) <-> (In a l /\\ a<>b)).\n  Proof. { induction l. \n          { simpl. split. auto.  intros H. destruct H. auto. }\n          { simpl. destruct (b==a0) eqn: H0. split. intros. split. right.\n           apply IHl in H. destruct H. exact. apply IHl in H. destruct H.\n           auto. intros H. destruct H. destruct H. move /eqP in H0. subst\n           a0. subst b. tauto. apply IHl. split. exact. exact. simpl. split.\n           intros H. destruct  H. split. left. auto. move /eqP in H0. \n           subst a0. auto. split. apply IHl in H. destruct H. right. exact.\n           apply IHl in H. destruct H. exact. simpl. intros. destruct H.\n           destruct H. left. exact.  assert (H2: (In a l) /\\ (a<>b)). split.\n           exact. exact.  apply IHl in H2. right. exact. } } Qed. \n\n\n  Hint Resolve del_all_elim1 del_all_elim2 del_all_intro: core.\n  \n  Lemma del_all_nodup (a:A)(l: list A): NoDup l -> NoDup (del_all a l).\n  Proof. { induction l. \n          { simpl. auto. }\n          { simpl. intros H. destruct (a==a0) eqn: H1. move /eqP in H1.\n            subst a0. eauto. assert (H0:NoDup l). eauto. apply IHl in H0.\n            assert (H2: ~(In a0 l)). eauto. \n            assert (H3: ~(In a0 (del_all a l))). eauto. eauto. } } Qed.\n\n  Hint Resolve del_all_nodup: core.\n\n (* ------- count of an element a in the list l ----------------------------------------*)\n\n Fixpoint count (a:A) (l:list A) : nat:= match l with\n                          | nil => 0\n                          |a1::l1 => match a == a1 with\n                                    |true => S (count a l1)\n                                    |false => count a l1\n                                    end\n                                        end.\n  Lemma countP1 (a:A) (l:list A): In a l -> (count a l >= 1).\n  Proof. { induction l. \n          { intros H. inversion H. }\n          { intros H. simpl in H. destruct H. subst a0. simpl. \n           destruct (a==a) eqn:H0. omega. move /eqP in H0. absurd (a=a).\n           exact. exact. apply IHl in H. simpl. destruct (a==a0) eqn:H0.\n           omega. exact. } } Qed.\n  Lemma countP1b (a:A) (l:list A): (count a l >= 1) -> In a l.\n  Proof. { induction l. \n          { intros H. inversion H. }\n          { intros H. simpl in H.\n           simpl. \n           destruct (a==a) eqn:H0. \n           destruct (a == a0) eqn: Ha.  \n           left. move /eqP in Ha. auto. right.\n           apply IHl in H. exact.\n           destruct (a == a0) eqn: Ha. \n           left. move /eqP in Ha. auto. right. \n           apply IHl in H. exact. } } Qed.  \n  \n  Lemma countP2 (a:A)(l: list A): ~ In a l -> (count a l = 0).\n  Proof. { intros. induction l. \n          { simpl. auto. }\n          { simpl. destruct (a==a0) eqn: H0. move /eqP in H0. subst a0. \n           simpl in H. destruct H. left. exact. move /eqP in H0. \n           assert (H1: ~(In a l)). eauto. apply IHl in H1. exact. } } Qed. \n  \n  Lemma countP3 (a:A)(l: list A): (count a l = 0) -> ~ In a l.\n  Proof. { induction l. \n          { simpl. auto. } \n          { simpl. destruct (a==a0) eqn:H0. intros. omega. intros. \n            apply IHl in H. move /eqP in H0. intro.  destruct H1. auto.\n            eauto. } } Qed. \n  \n  Lemma countP4 (a:A)(l: list A): count a (a::l) = S (count a l).\n  Proof. simpl. destruct (a==a) eqn:H. exact. move /eqP in H. auto. Qed.\n  \n  Lemma countP5 (a b:A)(l: list A): (count a l) <= count a (b::l).\n  Proof. { induction l. \n         { simpl. omega. } \n         { simpl. destruct (a==a0) eqn:H0. destruct (a==b) eqn:H1. omega.\n           omega. destruct (a==b) eqn: H1. omega. omega. } } Qed.\n \n  Lemma countP6 (a: A)(l: list A): count a l <= |l|.\n  Proof. { induction l. simpl. omega. simpl. destruct (a==a0) eqn:H0.\n  omega. omega. } Qed.\n  \n  Lemma countP7 (a:A) (l:list A): In a l -> count a l = S(count a (delete a l)).\n  Proof. { induction l. \n          { simpl. auto. }\n          { simpl. intro H. destruct H as [H1 | H2]. destruct (a==a0) eqn: H0.\n            exact. move /eqP in H0. auto. destruct (a==a0) eqn: H0. exact.\n            apply IHl in H2. move /eqP in H0. simpl. destruct (a==a0) eqn: H1.\n            move /eqP in H1. auto. exact. } } Qed.\n \n  Lemma countP8 (a:A) (l:list A): forall x, x<>a-> count x (a::l) = count x l.\n  Proof. { induction l. \n          { simpl. intros. destruct (x==a) eqn: H0. move /eqP in H0. auto. \n           exact. } \n          { intros. simpl. destruct (x==a) eqn:H0. move /eqP in H0. auto.\n            destruct (x==a0) eqn: H1. exact. exact. }} Qed.\n  \n  \n  Lemma countP9 (a:A) (l:list A): forall x, x<>a -> count x l = count x (delete a l).\n  Proof. { induction l. \n          { simpl. intros;auto. }\n          { intros. simpl. destruct (x==a0) eqn: H0. destruct (a==a0) eqn:H1.\n            move /eqP in H0. move /eqP in H1. subst a0. auto. simpl. \n            destruct (x==a0) eqn: H2. auto. auto. destruct (a==a0) eqn:H2. \n            exact. simpl. destruct (x==a0) eqn: H3. inversion H0. auto. }}  Qed.\n  \n  Lemma countP10 (a:A)(l s:list A): count a l <= count a s -> count a (a::l) <= count a (a::s).\n  Proof. { induction l. \n          { simpl. intros. destruct (a==a) eqn: H1. omega. omega. }\n          { simpl. intros. destruct (a==a0) eqn:H1. destruct (a==a) eqn:H2.\n            omega. omega. destruct (a==a) eqn: H2. omega. omega. } } Qed. \n  \n  Lemma countP11 (a:A)(l s: list A): count a l = count a s -> count a (a::l) = count a (a::s).\n  Proof. { induction l. \n          { simpl. intros. destruct (a==a) eqn: H1. auto. exact. }\n           { simpl. destruct (a==a0) eqn:H1. intros. destruct (a==a) eqn:H2.\n            omega. omega. destruct (a==a) eqn: H2. intros. omega. omega. }} Qed.\n  \n  Lemma countP12 (a:A)(l s: list A): count a l < count a s -> count a (a::l) < count a (a::s).\n  Proof. {  induction l. \n          { simpl. intros. destruct (a==a) eqn: H1. omega. exact. }\n          { simpl. destruct (a==a0) eqn: H2. destruct (a==a) eqn: H1. intros.\n            omega. intros. omega. destruct (a==a) eqn: H1. intros. omega.\n            intros. omega. }} Qed.\n  \n  Lemma count_nodup (l:list A): (forall x, In x l -> count x l <=1)-> NoDup l.\n  Proof. { intros H.\n         induction l. \n         { auto. }\n         { cut (NoDup l). cut (~In a l). auto. intros H1.\n          specialize (H a) as H2. \n          assert (H3:  count a (a :: l) <= 1). apply H2. auto.\n          simpl in H3. replace (a==a) with true in H3.\n          inversion H3. absurd (In a l). apply countP3. auto.\n          exact. inversion H4. auto.\n          apply IHl. intros x H1.\n          cut ( count x l <= count x (a::l)).\n          intros H2.\n          assert (H3: count x (a :: l) <= 1).\n          { apply H. auto. }\n          omega. apply countP5. }} Qed.\n           \n  Lemma nodup_count (l:list A) (x:A): NoDup l -> In x l -> count x l <=1.\n  Proof. { intros H1 H2.\n           induction l. simpl. auto.\n           { simpl in H2. destruct H2. \n             { subst x.\n             simpl. replace (a==a) with true.\n             cut (count a l =0). omega.\n             cut (~In a l). eapply countP2. auto. auto. }\n             { assert (Ha: x<>a). \n               { intro H2. subst x. absurd (In a l);auto. }\n              replace (count x (a::l)) with (count x l).\n              apply IHl. eauto. exact. symmetry.\n               apply countP8. exact. }}} Qed. \n  \n  Hint Immediate countP1 countP2 countP3: core.\n  Hint Resolve countP4 countP5 countP6 countP7 countP8 countP9: core.\n  Hint Immediate count_nodup nodup_count: core.\n \nEnd MoreDecList.\n\n Hint Resolve del_all_elim1 del_all_elim2 del_all_intro: core.\n Hint Resolve del_all_nodup: core.\n\n Hint Immediate countP1 countP2 countP3: core.\n Hint Resolve countP4 countP5 countP6 countP7 countP8 countP9:  core.\n Hint Resolve countP10 countP11 countP12: core.\n Hint Immediate count_nodup nodup_count: core.\n\nSection Permutation.\n\n  Context { A: eqType }.\n  \n   Lemma EM:forall x y : A, x=y \\/ x<>y.\n   Proof. eauto. Qed.\n   \n   Definition empty: list A:= nil.\n\n   Lemma count_in_putin1 (a: A)(l: list A)(lr: A-> A-> bool):\n     count a (putin lr a l)= S (count a l).\n   Proof. { induction l. simpl. destruct (a==a) eqn:H. auto. conflict_eq. \n           { simpl. case (lr a a0) eqn: H0.\n             { destruct (a==a0) eqn:H1. move /eqP in H1.\n               subst a0. assert (H: count a (a::a::l)=S(count a (a::l))). eauto.\n               rewrite H. eauto.\n               assert (H: count a (a :: a0 :: l) = S (count a (a0::l))).\n               eauto.  move /eqP in H1. rewrite H. eauto. }\n             { simpl. destruct (a==a0) eqn:H1. omega. auto. } } } Qed.\n   \n   Lemma count_in_putin2 (a b: A)(l: list A)(lr: A-> A-> bool):\n     a<>b -> count a l = count a (putin lr b l).\n   Proof. { induction l.\n            { simpl; destruct (a==b) eqn:H. intros;conflict_eq. auto. }\n            { intros.  simpl. case (lr b a0) eqn: H0.\n              { destruct (a==a0) eqn:H1.\n                move /eqP in H1. subst a0.\n                replace (count a (b :: a :: l)) with (count a (a :: l)).\n                eauto. symmetry; auto. move /eqP in H1.\n                replace (count a (b :: a0 :: l)) with (count a (a0 :: l)).\n                all: symmetry;eauto. }\n              { destruct (a==a0) eqn: H1.\n                move /eqP in H1. subst a0.\n                replace (count a (a :: putin lr b l)) with (S(count a (putin lr b l))).\n                 eauto. symmetry. auto. \n                replace (count a (a0 :: putin lr b l)) with (count a (putin lr b l)).\n                auto. move /eqP in H1. symmetry;auto. }  } } Qed.\n   \n  Lemma count_in_sorted (a: A)(l: list A)(lr: A-> A-> bool): count a l = count a (sort lr l). \n  Proof. { induction l. simpl; auto.\n           simpl. destruct  (a == a0) eqn:H0.\n           move /eqP in H0. subst a.\n           rewrite IHl. symmetry; apply count_in_putin1.\n           move /eqP in H0. rewrite IHl.  apply count_in_putin2. auto. }  Qed.\n\n\n  Hint Resolve count_in_putin1 count_in_putin2 count_in_sorted: core.\n  \n  (* ---------------  sublist of a list (subsequence)------------------------------------ *)\n\n  Fixpoint sublist (l s: list A): bool := match (l, s) with\n                                              |(nil , _) => true\n                                              |(a::l1, nil) => false\n                                              |(a::l1, b::s1) => match (a == b) with\n                                                          |true => sublist l1 s1\n                                                          |false => sublist l s1\n                                                          end\n                                       end.\n  \n  Lemma sublist_intro (l: list A): sublist nil l.\n  Proof.   destruct l;simpl;auto. Qed.\n  Lemma sublist_reflex (l: list A): sublist l l.\n  Proof. induction l;simpl.\n         auto. destruct (a==a) eqn:H; [auto | conflict_eq].  Qed.\n\n \n  Lemma sublist_elim1 (l: list A): sublist l nil -> l=nil.\n  Proof. destruct l; [auto | simpl; intro H; inversion H]. Qed.\n\n  Lemma sublist_elim2 (a:A)(l s: list A): sublist (a::l) s -> In a s.\n  Proof. induction s.  simpl; auto. simpl. destruct (a==a0) eqn:H. move /eqP in H.\n         subst a0; auto. intro;right;auto. Qed.\n  \n  Lemma sublist_elim3 (a: A)(l s: list A): sublist (a::l) s -> sublist l s.\n  Proof. { revert l; revert a. induction s.\n         { auto. }\n         { intros a0 l. \n           simpl. destruct (a0 == a) eqn:H.\n           { destruct l. auto.  destruct (e == a) eqn:H1.\n             apply IHs. auto.  }\n           { destruct l. auto.  destruct (e == a) eqn:H1.\n             { intro H2. assert (H2a: sublist (e::l) s). eapply IHs;exact H2.\n               eapply IHs; exact H2a. }\n             { apply IHs. }\n         } } } Qed.\n  \n  Lemma sublist_elim3a (a e: A)(l s: list A): sublist (a::l)(e::s)-> sublist l s.\n  Proof. simpl. destruct (a==e) eqn:H. auto.   eauto using sublist_elim3. Qed.\n  \n   Lemma sublist_intro1 (a:A)(l s: list A): sublist l s -> sublist l (a::s).\n   Proof.  { revert s;revert a. induction l.\n           { auto. }\n           { intros a0 s.\n             simpl. destruct (a == a0) eqn:H. apply sublist_elim3. auto. } } Qed.\n\n   Lemma sublist_Subset (l s: list A): sublist l s -> Subset l s.\n   Proof. { revert s. induction l.  eauto.\n           intros s H. eauto. unfold \"[<=]\". intros x H1.\n           destruct H1. subst x. eauto using  sublist_elim2. apply sublist_elim3 in H.\n           apply IHl in H. eauto. } Qed.\n\n  \n   Lemma sublist_elim4 (l s: list A): sublist l s -> (forall a, count a l <= count a s).\n   Proof. { revert l. induction s as [| e s'].\n          { intro l. intro H. assert (H1: l=nil); auto using sublist_elim1.\n            subst l; auto.  }\n          { intros l H x. destruct l as [|a l'].\n            simpl. omega. destruct (x==a) eqn:Hxa.\n            { move /eqP in Hxa. subst x.\n              simpl in H. destruct (a == e) eqn: Hae. move /eqP in Hae.\n              subst e.\n              cut (count a l' <= count a s'); auto.\n              assert (H1: count a (a :: l') <= count a  s'). eauto.\n              cut (count a s' <= count a (e::s')). omega. auto. }\n            { assert (H1: count x (a::l')<= count x s').\n              { simpl. rewrite Hxa. eauto using sublist_elim3a. }\n              cut (count x s' <= count x (e::s')). omega. auto. } } } Qed.\n   \n   (*\n\n  Hint Extern 0 (is_true ( sublist ?x ?z) ) =>\n  match goal with\n  | H: is_true (sublist x  ?y) |- _ => apply (@sublist_trans  x y z)\n  | H: is_true (sublist ?y  z) |- _ => apply (@sublist_trans  x y z) \n  end.\n*)\n    \n \n  Hint Resolve sublist_intro sublist_intro1 sublist_reflex sublist_Subset sublist_elim1: core.\n  Hint Resolve sublist_elim2 sublist_elim3 sublist_elim4: core.\n\n\n  (* -------------- list inclusion (subset in multiset) ----------------------------------*)\n\n  Fixpoint included (l s: list A): bool := match l with\n                                        |nil => true\n                                        | a::l1 => match (memb a s) with\n                                                  |true => included l1 (delete a s)\n                                                  |false => false\n                                                  end\n                                        end.\n  Lemma included_intro1 (l: list A): included nil l.\n  Proof.  auto. Qed. \n  \n   Lemma included_refl (l: list A): included l l.\n  Proof. { induction l. auto. simpl. destruct (a==a) eqn:H0. auto. move /eqP in H0. auto. } Qed.\n  \n  Lemma included_intro2 (a:A)(l s: list A): In a s -> included l (delete a s)-> included (a::l) s.\n  Proof. { induction s. \n          { simpl. auto. } \n          { simpl. intros H1 H2. destruct H1. destruct (a==a0) eqn: H3. auto.\n            move /eqP in H3. auto. destruct (a==a0) eqn: H3. simpl. exact.\n            simpl.  assert (H4: memb a s). eauto. case (memb a s) eqn:H5.\n            exact. auto. } } Qed.\n   \n   \n\n  Lemma included_intro (l s: list A): (forall a, count a l <= count a s)-> included l s.\n  Proof. { revert s. induction l. intros;apply included_intro1;auto.\n           { intros s H. simpl.  case (memb a s) eqn:Has;move /membP in Has.\n             apply IHl. intro x. destruct (EM x a).\n             2:{  replace (count x l) with (count x (a::l)).\n             replace (count x (delete a s)) with (count x s).\n             all: eauto. } subst x. \n             replace (count a l) with ((count a (a::l)) -1). \n             replace (count a (delete a s)) with ((count a s)-1).\n             specialize (H a).  omega.\n             replace (count a s) with (S (count a (delete a s))). omega.\n             symmetry; eauto.\n             replace (count a (a :: l)) with (S (count a l)). omega.\n             symmetry; eauto.\n             specialize (H a). rewrite countP4 in H.\n             replace (count a s) with 0 in H. inversion H. symmetry; eauto. } } Qed. \n\n\n    Lemma included_intro3 (l s: list A): sublist l s -> included l s.\n  Proof.  intro H. assert (H2: (forall a, count a l <= count a s)). eapply sublist_elim4. exact. eapply included_intro in H2. exact. Qed.\n  \n  Lemma included_elim1 (l: list A): included l nil -> l=nil.\n  Proof. induction l. auto. intros. inversion H. Qed. \n  \n  Lemma included_elim2 (a:A)(l s: list A): included (a::l) s -> In a s.\n  \n  Proof. { induction l. \n          {simpl. destruct (memb a s) eqn:H. auto. intro. inversion H0. }\n          { simpl. destruct (memb a s) eqn:H. auto. intro. inversion H0. }}Qed.\n  \n  Lemma included_elim3 (a:A)(l s: list A): included (a::l) s -> included l (delete a s).\n  Proof. { induction s.  \n          { simpl. auto. }\n          { simpl. destruct (a==a0) eqn:H0. simpl. auto. simpl. intros H. \n            destruct (memb a s) eqn:H1. auto. auto. } } Qed. \n\n\n  Lemma included_elim (l s: list A): included l s-> (forall a, count a l <= count a s).\n  Proof. { revert s. induction l. simpl. intros;omega. \n           intros s H x. apply included_elim2 in H as H1. apply included_elim3 in H as H2.\n           assert (H3: count a l <= count a (delete a s)).  eapply IHl with (s:= (delete a s)).\n           auto.  destruct (EM x a).\n           subst x. replace (count a (a::l)) with (S(count a l)).\n           replace (count a s) with (S( count a (delete a s))).\n           omega. symmetry; eauto.  eauto.  \n           replace (count x (a::l)) with (count x l).\n           replace (count x s) with  (count x (delete a s)).\n           eauto. all: symmetry;eauto. } Qed. \n    \n  Lemma included_elim4 (a:A)(l s: list A): included (a::l) s -> included l s.\n  Proof. { intro H. assert (H1: (forall a0, count a0 (a::l) <= count a0 s)).\n           eapply included_elim. exact. eapply included_intro. \n           assert (H2:forall a0 : A, (count a0 l)<=(count a0 (a :: l))). eauto.\n           intros. specialize (H1 a0). specialize (H2 a0). omega. } Qed.\n  \n\nLemma included_elim4b (a:A) (l s: list A) : included l s -> included (a::l) (a::s).\nProof. { intro H. apply included_intro. intro x. simpl.\n         destruct (x==a) eqn: H1. cut ((count x l)<= (count x s)).\n        omega. all:apply included_elim;exact. } Qed.\n\nLemma included_elim4a (a:A) (l: list A) : included (delete a l) l.\nProof. { induction l. simpl. auto. simpl. destruct (a == a0) eqn: H0. \nassert (H1: (forall a1, count a1 l <= count a1 (a0::l))). intros.\n eapply countP5. apply included_intro in H1. exact. \n  assert (H3:(included (delete a l) l)-> (included (a0 :: delete a l) (a0 :: l))). \n  eapply included_elim4b. eapply H3 in IHl. exact. } Qed.\n  \n  \n\n   Lemma included_elim5 (l s: list A): included l s -> Subset l s.\n  Proof. { unfold \"[<=]\". \n          induction l.\n          { simpl. intros. destruct H0. }\n          { intros.  destruct H0. eapply included_elim2 in H as H2.\n           subst a0. exact. apply IHl. eapply included_elim4 in H as H3. \n           exact. exact. } } Qed.\n           \n    Lemma included_elim6 (l s: list A)(a b: A)(lr: A->A-> bool)(Hanti: antisymmetric lr): Sorted lr (a::l) -> Sorted lr (b::s) ->\n     included (a::l) (b::s)-> a<>b -> included (a::l) s. \n    Proof. { intros H1 H2 H3 H4. \n           assert (H5: forall x, count x (a::l) <= count x (b::s)).\n           { eapply included_elim;auto. }\n           eapply included_intro.\n           intros x. simpl.\n           destruct (x == a) eqn: Hxa.\n           { (*-----x=a----*)\n            specialize (H5 a) as H6. simpl in H6. replace (a==b) with false in H6.\n            replace (a==a) with true in H6. move /eqP in Hxa. subst x. exact.\n            auto. auto. }\n            { (*-----x<>a-----*)\n              destruct (x==b) eqn:Hxb.\n              {  (*----x=b---*) \n               move /eqP in Hxb. subst x. replace (count b l) with 0. omega.\n               symmetry. cut (~In b l). eauto. intro H6. \n               assert (H7: lr a b). eauto.\n               assert (H8: lr b a). \n               { (*---lr b a ---*)\n                cut (In a (b::s)). eauto. eapply included_elim2. exact H3.\n                }\n               absurd (a=b). auto. apply Hanti. split_;auto. }\n              { (*--- x<>b----*) \n                 specialize (H5 x) as Hx.\n                 simpl in Hx. rewrite Hxa in Hx. rewrite Hxb in Hx. exact. } } } Qed.\n              \n                 \n                   \n   \n   \n  Lemma included_trans (l1 l2 l3: list A): \n  included l1 l2-> included l2 l3 -> included l1 l3.\n  Proof. { intros H1 H2. \n          assert (H1a:forall a0 : A, (count a0 l1)<=(count a0 l2)).\n          eapply included_elim. exact.\n          assert (H2a:forall a0 : A, (count a0 l2)<=(count a0 l3)).\n          eapply included_elim. exact.\n          eapply included_intro. intros a.\n          specialize (H1a a). specialize (H2a a). omega. } Qed.\n\n   Hint Extern 0 (is_true ( included ?x ?z) ) =>\n  match goal with\n  | H: is_true (included x  ?y) |- _ => apply (@included_trans  x y z)\n  | H: is_true (included ?y  z) |- _ => apply (@included_trans  x y z) \n  end : core.\n\n \n  Hint Resolve included_intro1 included_intro2 included_intro3: core.\n  Hint Resolve included_refl included_intro: core.\n  Hint Resolve included_elim1 included_elim2 included_elim3: core.\n  Hint Resolve included_elim4 (* included_elim4a *) included_elim5 included_elim: core.\n\n  (* ----- Some Misc Lemmas on nodup, sorted, sublist, subset and included ---------------- *)\n\n  Lemma nodup_subset_included (l s: list A): NoDup l -> l [<=] s -> included l s.\n  Proof. { intros H1 H2. eapply included_intro. intro a. assert (H: In a l -> In a s). eauto. assert (H3: forall x, In x l -> count x l <=1). eauto.\n  specialize (H3 a) as H4. assert (H5:In a s -> count a s >=1). eauto.\n  assert (H6:(In a l)\\/( ~In a l)). eauto. destruct H6. apply H in H0 as H7.\n  apply H5 in H7. apply H4 in H0. omega. assert (H6: count a l =0).\n  eauto. replace (count a l) with 0. omega. } Qed.\n \n  Lemma sublist_is_sorted (lr: A-> A-> bool)(l s: list A):  Sorted lr s -> sublist l s -> Sorted lr l. \n  Proof. { revert l.\n           induction s as [|b s1].\n           { intros l H1 H2. assert (H3:l=nil).\n             eauto.  subst l. auto. }\n           { intros l H1 H2.  \n             destruct l as [|a l1].\n             {  eapply Sorted_elim3. apply Sorted_single. Unshelve. exact. }\n             { simpl in H2.\n               destruct (a == b) eqn: Hab.\n               { (*----a=b----*)\n                 move /eqP in Hab. constructor. \n                 { apply IHs1. eauto. exact. }\n                 { intros x H3. \n                   assert (H4: lr b x). \n                   { cut (In x s1). apply Sorted_elim4. exact.\n                   assert (H5: l1 [<=] s1). auto. auto. }\n                 subst a;auto. } }\n               { (*---a<>b---*)\n                 apply IHs1.  eauto. exact.  } } } } Qed.     \n             \n  \n  \n  Lemma sorted_included_sublist (l s: list A)(lr: A->A-> bool)(Hanti: antisymmetric lr):\n    Sorted lr l-> Sorted lr s-> included l s-> sublist l s.\n  Proof. { revert l.\n           induction s as [|b s1]. \n           { intros l H1 H2 H3. destruct l;simpl in H3. simpl;auto.\n            inversion H3. }\n           { intros l H1 H2 H3. \n             destruct l as [|a l1] eqn: H4. \n             { simpl;auto. }\n             { (*----sublist (a :: l1) (b :: s1)-----*)\n               simpl. destruct (a==b) eqn: Hab. \n               { (*----- a = b --------*)\n               apply IHs1. eauto. eauto. move /eqP in Hab. subst b.\n               cut (forall x, count x l1 <= count x s1). eauto.\n               intros x. \n               assert (H5: forall y, count y (a :: l1) <= count y (a :: s1)).            \n               eapply included_elim. exact. specialize (H5 x) as H6. simpl in H6. \n               destruct (x == a);omega. }\n               { (*------ a <> b--------*) \n                assert (H5: included (a::l1) s1). eapply included_elim6. \n                exact Hanti. auto. exact H2. exact H3. move /eqP in Hab.  exact.\n                eapply IHs1. exact. eauto. exact. } } } } Qed.\n  \n  Lemma first_in_ordered_sublists (a e:A)(l s: list A)(lr: A->A-> bool)(Hrefl: reflexive lr):\n    Sorted lr (a::l)-> Sorted lr (e::s)-> sublist (a::l)(e::s)-> lr e a.\n  Proof. { intros H1 H2 H3. simpl in H3. destruct (a == e) eqn: H4.\n         move /eqP in H4. subst a. auto.\n         assert (H5: (forall x, In x l -> lr a x)). eapply Sorted_elim4. exact.\n         assert (H6: (forall x, In x s -> lr e x)). eapply Sorted_elim4. exact.\n         eauto. } Qed.\n\n Lemma nodup_included_nodup (l s: list A) :\n NoDup s -> included l s -> NoDup l.\n Proof. { intros. assert (H1:(forall a, count a l <= count a s)).\n        apply included_elim. exact. apply count_nodup. intros.\n        specialize (H1 x) as H3. assert (H4: count x s <=1).\n        apply nodup_count. exact. eauto. omega. } Qed.\n \n Lemma subset_nodup_subset (a:A) (l s: list A) :\n l[<=]a::s-> NoDup l -> ~In a l -> l[<=]s.\n Proof. { intros. unfold Subset in H. unfold Subset. intros.\n       specialize (H a0) as H3. apply H3 in H2 as H4. simpl in H4.\n       destruct H4. subst a. absurd (In a0 l). exact. exact. exact. } Qed.\n  \n\n       \n  Hint Resolve nodup_subset_included: core.\n  Hint Immediate sorted_included_sublist first_in_ordered_sublists\n  nodup_included_nodup :core.\n  \n\n  (* --------------------  permuted lists (permutation) -------------------------------------*)\n\n  Definition perm (l s: list A): bool:= included l s && included s l. \n\n  Lemma perm_intro  (l s: list A): (forall a, count a l = count a s)-> perm l s.\n  Proof.  { intro H; split_; apply included_intro; intro a; specialize (H a); omega. } Qed.\n\n  Lemma perm_intro0a (l: list A)(lr: A-> A-> bool): perm l (sort lr l).\n  Proof. apply perm_intro. eauto. Qed.\n  \n  Lemma perm_intro0b (l: list A)(lr: A-> A-> bool): perm (sort lr l) l.\n  Proof. apply perm_intro; eauto. Qed.\n \n  Lemma perm_nil: perm nil nil.\n  Proof. split_; eauto.  Qed.\n  \n  Lemma perm_refl (l: list A): perm l l.\n  Proof. split_; eauto.  Qed.\n\n  Lemma perm_intro3 (l s: list A): sublist l s -> sublist s l -> perm l s.\n  Proof. intros; split_; eauto.  Qed.\n\n  Lemma perm_elim   (l s: list A): perm l s -> (forall a, count a l = count a s).\n  Proof.  { intros H a. move /andP in H. destruct H as [H1 H2].\n          cut (count a l <= count a s). cut (count a s <= count a l). omega.\n          all: eauto. } Qed.\n\n  Lemma perm_elim1 (l: list A): perm l nil -> l = nil.\n  Proof. intro H; move /andP in H; destruct H as [H1 H2]; eauto. Qed.\n  Lemma perm_elim2 (l s: list A): perm l s -> l [=] s.\n  Proof. move /andP;intro H; destruct H; split; eauto. Qed.\n  Lemma perm_sym (l s: list A): perm l s -> perm s l.\n  Proof. move /andP;intro H; apply /andP; tauto. Qed.\n\n  Lemma perm_trans (x y z: list A): perm x y -> perm y z -> perm x z.\n  Proof. intros H H1; move /andP in H; move /andP in H1; apply /andP.\n         split;destruct H; destruct H1. all: auto. Qed.\n\n  Hint Extern 0 (is_true ( perm ?x ?z) ) =>\n  match goal with\n  | H: is_true (perm x  ?y) |- _ => apply (@perm_trans x y z)\n  | H: is_true (perm ?y  z) |- _ => apply (@perm_trans x y z) \n  end : core.\n\n  Hint Resolve  perm_intro0a  perm_intro0b perm_refl perm_nil perm_elim1 : core.\n  Hint Immediate perm_elim perm_intro perm_sym: core.\n  \n  Lemma perm_sort1 (l s: list A)(lr: A-> A-> bool): perm l s -> perm  l (sort lr s).\n  Proof.  eauto. Qed.\n\n   Lemma perm_sort2 (l s: list A)(lr: A-> A-> bool): perm l s -> perm  (sort lr l) s.\n   Proof. eauto.  Qed.\n\n   Lemma perm_sort3 (l s: list A)(lr: A-> A-> bool): perm l s -> perm (sort lr l)(sort lr s).\n   Proof. eauto using perm_sort1. Qed.\n   \n   Lemma countP1a (l:list A) (x:A): count x l >=1 -> In x l.\n   Proof. { induction l. simpl. intros H. omega. simpl.  intros H. \n          destruct (x == a) eqn: H1. left. move /eqP in H1. symmetry;exact.\n          right. eapply IHl in H. exact. } Qed.\n   \n   Lemma perm_nodup (l s: list A): perm l s -> NoDup l -> NoDup s.\n   Proof. { intros. apply count_nodup. intros.\n          assert (H2: forall x, In x l -> count x l <= 1). \n          eauto. assert (H3: forall a, count a l = count a s).\n          eauto. specialize (H2 x) as H4. specialize (H3 x) as H5.\n          assert (H6: count x s >=1). eauto.\n          assert (H7: count x l>=1). omega.  \n          assert (H8:In x l). apply countP1a. exact. apply H4 in H8. omega. } Qed.\n\n   Lemma perm_subset (l1 l2 s1 s2: list A): perm l1 l2 -> perm s1 s2 -> l1 [<=] s1 -> l2 [<=] s2.\n   Proof. intros. unfold perm in H. unfold perm in H0. move /andP in H.\n   move /andP in H0. destruct H. destruct H0. eapply included_elim5 in H2.\n   eapply included_elim5 in H0. eauto. Qed.\n   \n\n   Lemma perm_elim3 (l s: list A)(a: A): perm l s -> perm (a::l) (a::s).\n   Proof.  unfold perm. intros. move /andP in H. destruct H. apply /andP.\n   split. eapply included_elim4b. exact. eapply included_elim4b. exact. Qed.\n   \n   \n   \n\n   Hint Resolve perm_sort1 perm_sort2 perm_sort3 perm_nodup perm_subset: core.\n   \n End Permutation. \n\n\n\n\n  Hint Resolve count_in_putin1 count_in_putin2 count_in_sorted: core.\n\n\n  Hint Resolve sublist_intro sublist_intro1 sublist_reflex sublist_Subset sublist_elim1: core.\n  Hint Resolve sublist_elim2 sublist_elim3 sublist_elim3a sublist_elim4: core.\n(*\n  Hint Extern 0 (is_true ( sublist ?x ?z) ) =>\n  match goal with\n  | H: is_true (sublist x  ?y) |- _ => apply (@sublist_trans _ x y z)\n  | H: is_true (sublist ?y  z) |- _ => apply (@sublist_trans _ x y z) \n  end.\n\n*)\n  Hint Resolve included_intro1 included_intro2 included_intro3: core.\n  Hint Resolve included_refl included_intro: core.\n  Hint Resolve included_elim1 included_elim2  included_elim3: core.\n  Hint Resolve included_elim4 (*included_elim4a*) included_elim5 included_elim: core.\n  \n  Hint Extern 0 (is_true ( included ?x ?z) ) =>\n  match goal with\n  | H: is_true (included x  ?y) |- _ => apply (@included_trans _ x y z)\n  | H: is_true (included ?y  z) |- _ => apply (@included_trans _ x y z) \n  end : core.\n\n  Hint Resolve nodup_subset_included: core.\n  Hint Immediate sorted_included_sublist first_in_ordered_sublists\n  nodup_included_nodup :core.\n  Hint Resolve  perm_intro0a  perm_intro0b perm_refl perm_nil perm_elim1 : core.\n  Hint Immediate perm_elim perm_intro perm_sym: core.\n  Hint Resolve perm_elim1 perm_elim2 perm_elim3: core.\n\n  Hint Extern 0 (is_true ( perm ?x ?z) ) =>\n  match goal with\n  | H: is_true (perm x  ?y) |- _ => apply (@perm_trans _ x y z)\n  | H: is_true (perm ?y  z) |- _ => apply (@perm_trans _ x y z) \n  end : core.\n\n  Hint Resolve perm_sort1 perm_sort2 perm_sort3 perm_nodup perm_subset: core.\n", "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/MoreDecList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.754687434186948}}
{"text": "Record ARS : Type :=\n  mkARS\n    { elt : Type ;\n      red : elt -> elt -> Prop\n    }.\n\nInductive TransitiveClosure (A: ARS): elt A -> elt A -> Prop :=\n  | tc_head : forall {x y}, red A x y -> TransitiveClosure A x y\n  | tc_cons : forall {x y z}, TransitiveClosure A x y -> red A x y -> TransitiveClosure A x z.\n\nDefinition ReflexiveTransitiveClosure (A: ARS)(x y : elt A) : Prop :=\n  x = y \\/ TransitiveClosure A x y.\n\nDefinition SymmetricClosure (A: ARS)(x y: elt A) : Prop :=\n  red A x y \\/ red A y x.\n\nInductive TransitiveSymmetricClosure (A: ARS): elt A -> elt A -> Prop :=\n| tsc_head: forall {x y}, SymmetricClosure A x y -> TransitiveSymmetricClosure A x y\n| tsc_cons: forall {x y z}, TransitiveSymmetricClosure A x y -> SymmetricClosure A y z -> TransitiveSymmetricClosure A x z.\n\nDefinition ReflexiveTransitiveSymmetricClosure (A: ARS)(x y: elt A) : Prop :=\n  x = y \\/ TransitiveSymmetricClosure A x y.\n", "meta": {"author": "n-osborne", "repo": "rewriting", "sha": "0a7fe25e53c963970159ffabcd13f494a45295de", "save_path": "github-repos/coq/n-osborne-rewriting", "path": "github-repos/coq/n-osborne-rewriting/rewriting-0a7fe25e53c963970159ffabcd13f494a45295de/coq/ARS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7546731768890242}}
{"text": "(** * ProofObjects: Working with Explicit Evidence in Coq *)\n\nRequire Export MoreLogic.\n\n(* ##################################################### *)\n\n(**  We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types (like [nat] or [list]) and functions\n    over these types, and for _proving_ properties of these programs,\n    using inductive propositions (like [ev] or [eq]), implication, and \n    universal quantification.  So far, we have treated these mechanisms\n    as if they were quite separate, and for many purposes this is\n    a good way to think. But we have also seen hints that Coq's programming and \n    proving facilities are closely related. For example, the\n    keyword [Inductive] is used to declare both data types and \n    propositions, and [->] is used both to describe the type of\n    functions on data and logical implication. This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are almost\n    the same thing.  In this chapter we will study how this 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 evidence, \n    which can be thought of as a data structure. If the proposition\n    is an implication like [A -> B], then its proof will be an \n    evidence _transformer_: a recipe for converting evidence for\n    A into evidence for B.  So at a fundamental level, proofs are simply\n    programs that manipulate evidence.\n*)\n(**\n    Q. If evidence is data, what are propositions themselves?\n\n    A. They are types!\n\n    Look again at the formal definition of the [beautiful] property.  *)\n\nPrint beautiful. \n(* ==>\n  Inductive beautiful : nat -> Prop :=\n      b_0 : beautiful 0\n    | b_3 : beautiful 3\n    | b_5 : beautiful 5\n    | b_sum : forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m)\n*)\n\n(** *** *)\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(** *** *)\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(** This can be read \"[b_sum] is a constructor that takes four\n    arguments -- two numbers, [n] and [m], and two pieces of evidence,\n    for the propositions [beautiful n] and [beautiful m], respectively -- \n    and yields evidence for the proposition [beautiful (n+m)].\" *)\n\n(** Now let's look again at a previous proof involving [beautiful]. *)\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. Qed.\n\n(** Just as with ordinary data values and functions, we can use the [Print]\ncommand to see the _proof object_ that results from this proof script. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful = b_sum 3 5 b_3 b_5  \n     : beautiful 8  *)\n\n(** In view of this, we might wonder whether we can write such\n    an expression ourselves. Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_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    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   apply (b_sum 3 5 b_3 b_5).\nQed.\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(* ##################################################### *)\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   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(**\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, 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 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  (* FILL IN HERE *) Admitted.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  (* FILL IN HERE *) admit.\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 *) Admitted.\n\nDefinition nine_is_beautiful' : beautiful 9 :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n(* ##################################################### *)\n(** ** Quantification, 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, beautiful n -> beautiful (3+n).\nProof.\n   intros n H.\n   apply b_sum.\n   apply b_3.\n   apply H.\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 : nat) => fun (H : beautiful n) =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n : nat, 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(** When we view the proposition being proved by [b_plus3] as a function type,\n    one aspect of it may seem a little unusual. The second argument's\n    type, [beautiful n], mentions the _value_ of the first argument, [n].\n    While such _dependent types_ are not commonly found in programming\n    languages, even functional ones like ML or Haskell, they can\n    be useful there too.  \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 name\n    to the type on the LHS of the arrow. *)                                           \n\n(** For example, consider this proposition: *)\n\nDefinition beautiful_plus3 : Prop := \n  forall n, forall (E : beautiful n), beautiful (n+3).\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    beautiful.  But the name [E] for this evidence is not used in the\n    rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name for it.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition beautiful_plus3' : Prop := \n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition beatiful_plus3'' : Prop :=\n  forall n, beautiful n -> beautiful (n+3). \n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n\n(** **** Exercise: 2 stars b_times2 *)\n\n(** Give a proof object corresponding to the theorem [b_times2] from Prop.v *)\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n\n\n(** **** Exercise: 2 stars, optional (gorgeous_plus13_po) *) \n(** Give a proof object corresponding to the theorem [gorgeous_plus13] from Prop.v *)\n\nDefinition gorgeous_plus13_po: forall n, gorgeous n -> gorgeous (13+n):=\n   (* FILL IN HERE *) admit.\n(** [] *)\n\n\n\n\n(** It is particularly revealing to look at proof objects involving the \nlogical connectives that we defined with inductive propositions in Logic.v. *)\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(** **** Exercise: 1 star, optional (case_proof_objects) *)\n(** The [Case] tactics were commented out in the proof of\n    [and_example] to avoid cluttering the proof object.  What would\n    you guess the proof object will look like if we uncomment them?\n    Try it and see. *)\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    (* 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 easier to understand. It is still\n    a little complicated, but after performing some simple reduction\n    steps, we can see that all that is really happening is taking apart \n    a record 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        (fun H0 : Q /\\ P => H0)\n            match H with\n            | conj HP HQ => (fun (HP0 : P) (HQ0 : Q) => conj Q P HQ0 HP0) HP HQ\n            end\n      : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** After simplifying some direct application of [fun] expressions to arguments,\nwe get: *)\n\n(* ===> \n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     match H with\n     | conj HP HQ => conj Q P HQ HP\n     end \n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\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 :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n\n(** **** Exercise: 2 stars, advanced, 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\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\n(** Recall that we model an existential for a property as a pair consisting of \na witness value and a proof that the witness obeys that property. \nWe can choose to construct the proof explicitly. \n\nFor example, consider this existentially quantified proposition: *)\nCheck ex.\n\nDefinition some_nat_is_even : Prop := \n  ex _ 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\n(** **** Exercise: 2 stars, optional (ex_beautiful_Sn) *)\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex _ (fun n => beautiful (S n)) :=\n(* FILL IN HERE *) admit.\n(** [] *)\n\n\n\n(* ##################################################### *)\n(** ** Giving Explicit Arguments to Lemmas and Hypotheses *)\n\n(** Even when we are using tactic-based proof, it can be very useful to\nunderstand the underlying functional nature of implications and quantification. \n\nFor example, it is often convenient to [apply] or [rewrite] \nusing a lemma or hypothesis with one or more quantifiers or \nassumptions already instantiated in order to direct what\nhappens.  For example: *)\n\nCheck plus_comm.\n(* ==> \n    plus_comm\n     : forall n m : nat, n + m = m + n *)\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. *) \n      (* rewrites in the first possible spot; not what we want *)\n   rewrite (plus_comm b a).  (* directs rewriting to the right spot *)\n   reflexivity.  Qed.\n\n\n(** In this case, giving just one argument would be sufficient. *)\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.  Qed.\n\n(** Arguments must be given in order, but wildcards (_)\nmay be used to skip arguments that Coq can infer.  *)\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. Qed.\n\n(** The author of a lemma can choose to declare easily inferable arguments\nto be implicit, just as with functions and constructors. \n\n  The [with] clauses we've already seen is really just a way of\n  specifying selected arguments by name rather than position:  *)\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. Qed.\n\n\n(** **** Exercise: 2 stars (trans_eq_example_redux) *)\n(** Redo the proof of the following theorem (from MoreCoq.v) using\nan [apply] of [trans_eq] but _not_ using a [with] clause. *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ##################################################### *)\n(** ** Programming with Tactics (Optional) *)\n\n(** If we can build proofs with explicit terms rather than\ntactics, you may be wondering if we can build programs using\ntactics rather than explicit terms.  Sure! *)\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\nEval compute in add1 2. \n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than with\n[:=] followed by a term.  This tells Coq to enter proof scripting mode\nto build an object of type [nat -> nat].  Also, we terminate the proof\nwith [Defined] rather than [Qed]; this makes the definition _transparent_\nso that it can be used in computation like a normally-defined function.  \n\nThis feature is mainly useful for writing functions with dependent types,\nwhich we won't explore much further in this book.\nBut it does illustrate the uniformity and orthogonality of the basic ideas in Coq. *)\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8740772368049823, "lm_q1q2_score": 0.754670949654035}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nAxiom replace_with_your_solution_here : forall {A : Type}, A.\n\n(** * Exercise: finish the development we started at the last seminar *)\n\n(** * Odd and even numbers *)\n\n(** ** Part 1: Definitions *)\n\nSection OddAndEven.\n\n  \n(** The goal of this exercise is to build a system of canonical structures\n    so that the following statement about some properties of\n    odd natural numbers can be proved with a couple of simple rewrites:\n\n    Example test_odd (n : odd_nat) :\n      ~~ (odd 6) && odd (n * 3).\n    Proof. by rewrite oddP evenP. Qed.\n\n    See the definitions of [odd_nat], [oddP], and [evenP] below.\n    If you do everything the right way the example at the end of the section will work.\n    In other words, the goal of this exercise is not to prove a statement,\n    but rather make the given proof work.\n    Please, DO NOT CHANGE the proof (I can assure you it works if the right canonical structures are given)\n *)\n\n\n(** Let us define a structure defining the notion of odd numbers *)\nStructure odd_nat := Odd {\n  oval : nat;            (** [oval] is a natural number *)\n  oprop : odd oval       (** [oprop] is the proof it is odd *)\n}.\n\n(** Example: [42 - 1] is an odd number *)\n\nDefinition o41 : odd_nat := @Odd 41 isT.\n\n(** One issue here is that we cannot, for instance, add two odd naturals: *)\nFail Check o41 + o41.\n\n(** Let's declare [oval] a coercion to work with terms of type [odd_nat]\n    as if those were just regular naturals.\n *)\nCoercion oval : odd_nat >-> nat.\n\nCheck o41 + o41.    (** Notice the result type is [nat] here: to use [odd_nat] as [nat] we forget the\n                        extra information about oddity *)\n\n(** Prove the main property of [odd_nat] *)\nLemma oddP {n : odd_nat} : odd n.\nProof.\n  move : (oprop n).\n  done.\nQed.\n\n(** Let us do the analogous thing for the even numbers *)\nStructure even_nat := Even {\n  eval :> nat;\n  eprop : ~~ (odd eval)\n}.\n\n(* Prove the main property of [even_nat] *)\nLemma evenP {n : even_nat} : ~~ (odd n).\nProof.\n  move : (eprop n).\n  done.\nQed.\n\n(** Now we have all the definitions we referred to in the problem definition.  *)\n\n(** The objective is to make it work: knowing that\n    [n] is [odd] Coq should infer that [n * 3]\n    is also [odd], and that [6] is even *)\nExample test_odd (n : odd_nat) : ~~ (odd 6) && odd (n * 3).\nProof.\n  Fail by rewrite oddP evenP.\nAbort.\n\n(** But Coq cannot infer it without any hints.\n    The goal to provide the necessary hints in the form of canonical structure instances *)\n\n(** Let's start by telling Coq that 0 is even *)\n\nPrint isT.\nCanonical even_0 : even_nat := @Even 0 isT.\n\n(** helper lemma *)\nLemma oddS n : ~~ (odd n) -> odd n.+1.\nProof.\n  Show.\n  case : n; rewrite //=.\nQed.\n  \n(** helper lemma *)\nLemma evenS n : (odd n) -> ~~ (odd n.+1).\nProof.\n  case : n; rewrite //=.\n  move => n.\n  case : (odd n); rewrite //=.\nQed.\n\n(** Here we teach Coq that if [m] is even,\n    then [m.+1] is [odd] *)\nCanonical odd_even (m : even_nat) : odd_nat :=\n  @Odd m.+1 (oddS (eprop m)).\n\n(** Implement the dual, teach Coq that if [m]\n    is [odd] then [m.+1] is [even] *)\nCanonical even_odd (m : odd_nat) : even_nat :=\n  @Even m.+1 (evenS (oprop m)).\n\nUnset Printing Notations.\nSet Printing Notations.\n\n(** Now let's deal with multiplication:\n    DO NOT USE [case] tactic or the square brackets to\n    destruct [n] or [m] *)\nLemma odd_mulP {n m : odd_nat} : odd (n * m).\nProof.\n(** (!) do not break up [n] or [m] *)\n  rewrite oddM.\n  set h1 := oprop n.\n  set h2 := oprop m.\n  rewrite h1 h2.\n  done.\nQed.\n  \n  (** teach Coq that [*] preserves being [odd] *)\n  \nCanonical oddmul_Odd (n m : odd_nat) : odd_nat :=\n  @Odd (muln n m) (@odd_mulP n m).\n\n(** If the following proof works it means you did everything right: *)\n\nExample test_odd (n : odd_nat) :\n  ~~ (odd 6) && odd (n * 3).\nProof.\n  rewrite //=.\n  apply : odd_mulP.\nQed.\n\nEnd OddAndEven.\n\n(** ** Part 2: Equality for [odd_nat] *)\n\n(** We cannot use [==] on [odd] natural numbers because\n   [odd_nat] is not an [eqType] *)\nFail Check forall n : odd_nat, n == n.\n\n(** * Optional exercise: define [eqType] instance for [odd_nat] *directly* *)\n\nDefinition eq_odd_nat (m n : odd_nat) : bool :=\n (oval m) == (oval n).\n(* Hint: since you are comparing two structures you might think\n   you need to check that both components of the structures are equal:\n   this is not a problem for the first component of type [nat],\n   but then you'll need to compare two *proofs* and this is\n   tricky in general.\n   However, here you actually don't need to compare the proofs at all:\n   simply compare the first components and then you'll still be able\n   to prove [Equality.axiom].\n *)\n\nAbout Bool.reflect.\n\nAbout eqP.\n\nAbout eq_irrelevance.\n\n\nUnset Printing All.\nSet Printing Coercions.\nSet Printing Implicit.\nUnset Printing Notations.\n\nAbout eq_irrelevance.\n\nLemma odK (x : odd_nat) : x = @Odd (oval x) (oprop x).\nProof.\n  by case : x.\nQed.\n\nLemma eq_odd_axiom : Equality.axiom eq_odd_nat.\nProof.\n  rewrite /Equality.axiom /eq_odd_nat.\n  move => x y.\n  case : x.\n  case : y.\n  move => n nodd m modd.\n  case : eqP; rewrite //= => h1; constructor; move : nodd modd.\n  - rewrite h1 => nodd modd.\n      by rewrite (eq_irrelevance modd nodd).\n  - rewrite /not.\n    move => nodd modd.\n    case.\n    apply h1.\nQed.\n  \n(*\n Hint 1: use [case: eqP] to case analyse on equality between natural numbers\n         (you might need to do some definition unfolding before you can use it).\n\n Hint 2: use [eq_irrelevance] lemma (you might need to specify the exact\n         occurence you want to rewrite like so rewrite [proof_name]eq_irrelevance).\n*)\n\n(** * Exercise: define [eqType] instance for [odd_nat] using [subType] *)\n\n(* Since [odd_nat] is a subtype of natural numbers, i.e.\n   a structure with a number and an additional (computable) constraint on it,\n   we can use the [subType] machinery to derive equality (and not only equality)\n   on it. *)\n(* First, you derive [subType] instance by specifying the projection like: *)\n\nCanonical oddnat_subType := Eval hnf in [subType for oval].\n\nPrint oddnat_subType.\n\n(* Then you derive the equality mixin be specifying the type: *)\n\nDefinition oddnat_eqMixin := Eval hnf in [eqMixin of odd_nat by <:].\n\n(* Comment out the the line with [Canonical oddnat_subType] above and\n   make sure deriving of [oddnat_eqMixin] fails. *)\n\n(* Now finish the definition of [eqType] for [oddnat]: *)\n\n(* ADD YOUR CODE HERE *)\n\nPrint Equality.Pack.\n\nCanonical oddnat_eqType := Equality.Pack oddnat_eqMixin.\n\n(* This should work now *)\n\nCheck forall n : odd_nat, n == n.\n\nLemma odd_nat_eq_refl (n : odd_nat) :\n  n == n.\nProof. by rewrite eq_refl. Qed.\n\n(** * Exercise: Now deal with [even_nat] *)\nFail Check forall (m : even_nat), m == m.\n\n(* ADD CODE HERE *)\n\nCanonical evennat_subType := Eval hnf in [subType for eval].\nDefinition evennat_eqMixin := Eval hnf in [eqMixin of even_nat by <:].\nCanonical evennat_eqType := Equality.Pack evennat_eqMixin.\n\nCheck forall (m : even_nat), m == m.\n\nLemma even_nat_eq_refl (n : even_nat) :\n  n == n.\nProof. by rewrite eq_refl. Qed.\n\n(*\n\n==== OPTIONAL EXERCISES ====\n\nExercises in this section are not related to canonical structures\n*)\n\n\n(** An optional exercise with a short and a bit tricky one-line solution (less than 70 characters): *)\n\nSet Printing Notations.\n\nLemma triple_compb_long (f : bool -> bool) :\n  f \\o f \\o f =1 f.\nProof.\n  have h y : f y = true \\/ f y = false. by case : (f y); intuition.\n  by case : (h true) (h false); case => p; case => q; case; rewrite /comp ?p ?q ?p ?q.\nQed.\n\nLemma triple_compb (f : bool -> bool) :\n  f \\o f \\o f =1 f.\nProof.\n  by rewrite /comp; case; case E : (f true); case D : (f false); rewrite ?E ?D. \nQed.\n    \n  \n    \n(** Hint: use [case <identifier>: <term>] tactic\n          to pattern match on [<term>] and keep the result\n          as an equation <identifier> in the context.\n          E.g. [case E: b] where [b : bool] creates two subgoals with two equations\n          in the context: [E = true] and [E = false] corresponingly.\n *)\n\n\n\n(** Optional exercises: provide one-line proofs *)\nSection EckmannHilton.\n(** Here is an explanation for this section:\n    https://en.wikipedia.org/wiki/Eckmann–Hilton_argument\n    Hint: you can find informal proofs in that wiki page,\n          use it as a source of inspiration if you get stuck.\n *)\n\nContext {X : Type}.\nVariables f1 f2 : X -> X -> X.\n\nVariable e1 : X.\nHypothesis U1 : left_id e1 f1 * right_id e1 f1.\n\nVariables e2 : X.\nHypothesis U2 : left_id e2 f2 * right_id e2 f2.\n\nHypothesis I : interchange f1 f2.\n\nCompute interchange f1 f2.\n\nCompute left_id e1 f1.\n\nCompute right_id e1 f1.\n\nLemma units_same :\n  e1 = e2.\nProof.\n  rewrite -[e1] U1 -{1}[e1] U2 -{2}[e1] (snd U2) I !U1 U2. done.\nQed.\n\nLocate \"=2\".\n\nLemma operations_equal :\n  f1 =2 f2.\nProof.\n  move => x y; rewrite - {1}[x] (snd U2) -{1}[y] U2 I -units_same !U1.\n  done.\nQed.\n\nLemma I1 : interchange f1 f1.\nProof.\n  move => x y z w; rewrite operations_equal -I -![f2 _ _]operations_equal.\n  done.\nQed.\n\nLemma operations_comm :\n  commutative f1.\nProof.\n  move => x y.\n  rewrite operations_equal -{1}[y](snd U1) -{1}[x]U1 -I units_same !U2.\n  done.\nQed.\n  \nLemma operations_assoc :\n  associative f1.\nProof.\n  move => x y z. rewrite -{2}[z]U1 I1 U1. done.\nQed.\n\nEnd EckmannHilton.\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/hw08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.7546709446848615}}
{"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\nLemma trivial2 : forall x:A, P x -> P x.\nProof.\n  intro y.\n  intro I.\n  assumption.\nQed.\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. (*assumption.\n  destruct H as [H1 H2].\n  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. (*assumption.*)\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  (*assumption.*)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. (*Entre P e ~P*)\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.\n  intros.\n  destruct H as [H1 H2].\n  destruct H2 as [H2 H3].\n  destruct H3 as [H3 H4].\n  split.\n  - apply H1.\n    assumption.\n  - apply H2.\n    assumption.\nQed.\n    \n(* exercise *)\nLemma ex9 : ~ (P /\\ ~P).   \nProof.\n  intro.\n  destruct H as [H1 H2].\n  contradiction.\nQed.\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).\nProof.\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 firstorder.\nQed.\n\n\n(* Exercise *)\nProposition ex15: (forall x, W x)/\\(forall x, R x) -> (forall x, W x /\\ R x).\nProof.\n  intros.\n  split.\n  - destruct H as [H1 H2].\n    apply H1.\n  - destruct H as [H1 H2].\n    apply 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.\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.\nProof.\n  elim 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": "JaK0be", "repo": "VF", "sha": "4d886d958200df476b3ece5c2194ee5ff1f149d5", "save_path": "github-repos/coq/JaK0be-VF", "path": "github-repos/coq/JaK0be-VF/VF-4d886d958200df476b3ece5c2194ee5ff1f149d5/TPC4/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7545239662430958}}
{"text": "Require Export Prop_J.\n\n(* ->とforallは同じもの *)\n\nDefinition funny_prop1 :=\n  forall n, forall (E : ev n), ev (n + 4).\nDefinition funny_prop1' :=\n  forall n, forall (_ : ev n), ev (n + 4).\nDefinition funny_prop1'' :=\n  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\nTheorem and_example :\n  (ev 0) /\\ (ev 4).\nProof.\n  apply conj.\n  apply ev_0.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_0. Qed.\n\nPrint and_example.\n\nTheorem and_example' :\n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    apply ev_0.\n    apply ev_SS.\n    apply ev_SS.\n    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 P Q H.\n  inversion H as [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 H.\n  inversion H as [HP [HQ HR]].\n  split.\n  split.\n  apply HP.\n  apply HQ.\n  apply HR. Qed.\n\nTheorem even_ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  induction n as [|n'].\n  split.\n  intros ex.\n  apply ev_0.\n  intros ex.\n  inversion ex.\n  split.\n  apply IHn'.\n  intros H.\n  apply ev_SS.\n  inversion IHn'.\n  apply H0.\n  apply H. Qed.\n\nDefinition conj_fact : forall P Q R,\n  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\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 H'.\n  apply H.\n  apply H'. Qed.\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. Qed.\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. Qed.\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  split.\n  intros P'.\n  apply H1.\n  apply H0.\n  apply P'.\n  intros R'.\n  apply H0.\n  apply H1.\n  apply R'. Qed.\n\nDefinition MyProp_iff_ev : forall n, MyProp n <-> ev n :=\n  (fun (n : nat) => conj (MyProp n -> ev n) (ev n-> MyProp n)\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\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  apply or_intror.\n  apply HP.\n  apply or_introl.\n  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  right. apply HP.\n  left. 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 H.\n  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. Qed.\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 [[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. Qed.\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 H.\n  inversion H.\n  split.\n  left. apply H0.\n  left. apply H0.\n  inversion H0 as [HQ HR].\n  split.\n  right. apply HQ.\n  right. apply HR.\n  intros H.\n  inversion H as [[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. 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    destruct c.\n      apply conj.\n      reflexivity.\n      reflexivity.\n    inversion H.\n    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.\n  rewrite H1.\n  reflexivity. Qed.\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    inversion H.\n    right.\n    reflexivity.\n    left.\n    reflexivity. Qed.\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.\n  reflexivity.\n  destruct c.\n  right.\n  reflexivity.\n  inversion H. Qed.\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    inversion H.\n    inversion H.\n  split.\n  reflexivity.\n  destruct c.\n  inversion H.\n  reflexivity. Qed.\n\nInductive False : Prop := .\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\nInductive True : Prop :=\n|T : True.\n\nDefinition not (P : Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nTheorem not_False:\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  inversion H. Qed.\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. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H.\n  unfold not.\n  intros G.\n  apply G.\n  apply H. Qed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~ P).\nProof.\n  unfold not.\n  intros P H.\n  inversion H.\n  apply H1 in H0.\n  apply H0. Qed.\n\nTheorem five_not_even : ~ ev 5.\nProof.\n  unfold not.\n  intros Hev5.\n  inversion Hev5.\n  inversion H0.\n  inversion H2. Qed.\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 H.\n  inversion H.\n  intros H'.\n  inversion H'.\n  apply IHev in H1.\n  apply H1. Qed.\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  intros P H.\n  unfold not in H.\nAdmitted.\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.\n  reflexivity. Qed.\n\nTheorem not_eq_beq_false : forall n n' : nat,\n  n <> n' -> beq_nat n n' = false.\nProof.\n  Admitted.\n\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  Admitted.\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.\n\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\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.\n  apply PH. Qed.\n\nModule MyEqualilty.\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 H.\n  inversion H as [x' y' T].\n  apply refl_equal'.\n  intros H.\n  inversion H as [T].\n  apply refl_equal. Qed.\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 MyEqualilty.\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\nTheorem test_le1 : 3 <= 3.\nProof.\n  apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n. Qed.\n\nTheorem test_le3 :\n  ~ (2 <= 1).\nProof.\n  intros H.\n  inversion H.\n  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\nTheorem O_le_n : forall n,\n  O <= n.\nProof.\n  intros n.\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'. Qed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H.\n    apply le_n.\n    apply le_S.\n    apply IHle. Qed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m.\n  Case \"m = 0\".\n  intros n H.\n  inversion H as [eq|m' L].\n    apply le_n.\n    inversion L.\n  intros n H.\nAdmitted.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b.\n  induction a as [|a'].\n    simpl.\n    apply O_le_n.\nAdmitted.\n", "meta": {"author": "U-MA", "repo": "software_foundation", "sha": "7d49ccb2a863caa473e70e2b141ea113cf8a1fa1", "save_path": "github-repos/coq/U-MA-software_foundation", "path": "github-repos/coq/U-MA-software_foundation/software_foundation-7d49ccb2a863caa473e70e2b141ea113cf8a1fa1/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.7545239483629298}}
{"text": "\n(*let evenb be a function := nat -> bool,\nwith evenb(2n) = true, evenb(2n+1) = false.\n\nProblems:\nProve definition a1.\nProve definition a2.*)\n\n\nFixpoint evenb (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => evenb n'\n  end.\n\n(*you may create any inductive types or even edit the\nmain function, as long as it outputs correctly and the goal\nremains unchanged.*)\n\n(*Notations.*)\n\n\n(*Here starts definitions/exercises*)\n\nDefinition a0 : forall b:bool, negb b <> b.\nProof.\n  intro b.\n  autounfold.\n  case b.\n    simpl. intro. discriminate.\n    simpl. intro. discriminate.\nQed.\n\nDefinition a0_1 : forall b:bool, b <> negb b.\nProof.\n  intro b.\n  autounfold.\n  case b.\n    simpl. intro. discriminate.\n    simpl. intro. discriminate.\nQed.\n\nDefinition a1 : forall (n:nat), \n  evenb n = evenb (n+2).\nProof.\n  (*insert proof here*)\nAdmitted.\n\nDefinition a2 : forall (n:nat),\n  evenb n = negb (evenb(n+1)).\nProof.\n  (*insert proof here*)\nAdmitted.\n\nDefinition a2_1 : forall (n:nat), evenb n <> evenb(n+1).\nProof.\n  intro.\n  pose proof a2 as a2.\n  rewrite a2.\n  pose proof a0 as a0.\n  apply a0.\nQed.\n\nDefinition a2_2 : forall n:nat, \nevenb n = negb (evenb (n + 1)) <-> evenb n <> evenb(n+1).\nProof.\n  intro.\n  unfold iff.\n  refine(conj _ _).\n\n    intro.\n    rewrite H.\n    pose proof a0 as a0.\n    apply a0.\n\n    intro.\n    autounfold in H.\n    (*                    did not work for me.\n    destruct H as [].\n    pose proof a2 as a2.\n    rewrite a2.\n    pose proof a0 as a0.\n    \n    pose(x := evenb(n+1)).\n    assert(x = evenb(n+1)).\n    auto.\n    rewrite <- H.\n    case x.\n      simpl.\n      assert(false <> true). intuition. discriminate.*)\n    pose proof a2.\n    apply H0.\nQed.\n\nGoal 6 = 6.\nProof.\n  assert(forall x:nat, x = x). reflexivity.\n  pose(x := 6).\n  assert(6 = x). trivial.\n  rewrite H0.\n  apply H.\nQed.\n  \n\nGoal evenb 4 = evenb 6.\nProof.\n  pose proof a1 as hyp_1.\n  apply hyp_1.\nQed.\n\nGoal evenb 4 = evenb 820.\nProof.\n  pose proof a1 as hyp_1.\n  apply hyp_1.\nQed.\n\nGoal evenb 4 <> evenb 5.\nProof.\n  pose proof a2_1 as hyp_2.\n  apply hyp_2.\nQed.\n\nGoal evenb 7 = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem two_n_is_even : forall n:nat, evenb(2*n) = true.\nProof.\n  intro.\n  elim n. simpl. reflexivity.\n    intros.\n    pose proof a1.\n    rewrite H0 in H.\n    assert(2* S n0 = 2*n0 + 2). auto.\n    rewrite H1.\n    exact H.\nQed.\n\nTheorem a3_1 : forall n:nat, evenb(2*n + 1) = false.\nProof.\n  intro.\n  pose proof two_n_is_even as lem1.\n  pose proof a2 as lem2.\n  \n  assert(forall n : nat, \n      evenb (2*n) = negb (evenb (2*n + 1))).\n    intro.\n    pose(x:=2*n0).\n    assert(2*n0 = x). auto.\n    rewrite H.\n    apply lem2.\n  \n    assert(negb(evenb (2 * n + 1)) = true).\n    rewrite <- H.\n    apply lem1.\n    \n    assert(forall b:bool, negb b = true -> b = false).\n    intro b.\n    case b.\n      auto.\n      auto.\n    \n    pose(x:=2 * n + 1). assert(x = 2 * n + 1). auto.\n    rewrite <- H2.\n    assert(negb(evenb(x)) = true).\n    rewrite H2.\n    exact H0.\n    apply H1.\n    exact H3.\nQed.\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/test_evenb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7544874005106169}}
{"text": "Load Preamble.\nRequire Import Arith Lia.\nFrom Coq Require Import PArith.BinPos.\n\n\nSection Cantor.\n\nDefinition Cantor n x y := 2*n = (x+y)*S(x+y) + 2*y.\n \nDefinition next '(x,y) :=\n  match x with\n  | 0 => (S y, 0)\n  | S x' => (x', S y)\n  end.\n\nLemma decode_spec :\n  forall n, Sigma p : nat*nat, let (x,y) := p in Cantor n x y.\nProof.\n  unfold Cantor.\n  induction n as [|n [p Hp]].\n  - exists (0,0); lia.\n  - exists (next p).\n    destruct p as [[] ]; cbn; lia.\nDefined.\n\nDefinition decode n := p1 (decode_spec n).\nDefinition decode_eq n : let (x,y) := decode n in \n  2*n = (x+y)*S(x+y) + 2*y.\nProof. unfold decode. cbn. apply (p2 (decode_spec n)). Admitted.\n\nFact Gauss n : {k & n*(S n) = 2*k}.\nProof.\n  induction n.\n  - now exists 0.\n  - destruct IHn as [k ].\n    exists (n + S k); lia.\nDefined.\n\nLemma code_spec x y : {n & Cantor n x y}.\nProof.\n  unfold Cantor.\n  destruct (Gauss (x + y)) as [s ].\n  exists (s + y); lia.\nDefined.\n\nDefinition code (p : nat*nat) := let (x,y) := p in p1 (code_spec x y).\nFact code_eq x y : 2*(code (x,y)) = (x+y)*S(x+y) + 2*y.\nProof.\n  cbn. destruct (code_spec x y); cbn.\nAdmitted.\n\nLemma inv_cd : inv code decode.\nProof.\n  intros n.\n  enough (2*code (decode n) = 2*n) by lia.\n  destruct (decode n) as [x y] eqn:e.\n  rewrite code_eq.\n  generalize (decode_eq n). now rewrite e.\nQed.\n\nLemma inv_dc x y :\n  decode (code (x,y)) = (x,y).\nProof.\nAdmitted.\n\nSection Cantor.", "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/temp6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7544873940666296}}
{"text": "(* Binary search trees, with specification and proof of correctness.\n  Andrew W. Appel, 2013.\n*)\n\n(* IMPORTS *)\nRequire Import ZArith Permutation Omega List Classical_sets.\nRequire Import FunctionalExtensionality.\nAxiom prop_ext: ClassicalFacts.prop_extensionality.\nImplicit Arguments prop_ext.\nOpen Scope Z.\n\n(* A FEW LEMMAS ABOUT SET UNION, ET CETERA *)\nArguments In {U} A x.\nArguments Union {U} B C x.\nArguments Singleton {U} x x0.\nArguments Empty_set {U} x.\n\nLemma In_Singleton_iff:\n  forall U (x y: U), In (Singleton x) y <-> x=y.\nProof.\n  intros. split; intros.\n    inversion H. reflexivity.\n    subst. constructor.\nQed.\n\nLemma In_Union_iff:\n forall U (B C: Ensemble U) x,\n  In (Union B C) x <-> (In B x \\/ In C x).\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma Union_Empty_set_l: forall U (B: Ensemble U),\n  Union Empty_set B = B.\nProof.\nintros. extensionality x. apply prop_ext.\n(* FILL IN HERE *) Admitted.\n\nLemma Union_sym:\n forall {U} (B C: Ensemble U), Union B C = Union C B.\nProof.\n  intros. extensionality x. apply prop_ext.\n(* FILL IN HERE *) Admitted.\n\nLemma Union_assoc:\n  forall {U} (A B C: Ensemble U),\n   Union A (Union B C) = Union (Union A B) C.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(*  PROGRAM FOR BINARY SEARCH TREES *)\n\nInductive tree  : Type :=\n | E : tree\n | T: tree -> Z -> tree -> tree.\n\nFixpoint member (x: Z) (t : tree) : bool :=\n  match t with\n  | E => false\n  | T tl k tr => if Z.ltb x k then member x tl\n                         else if Z.ltb k x then member x tr\n                         else true\n  end.\n\nFixpoint insert (x: Z) (s: tree) :=\n match s with\n | E => T E x E\n | T a y b => if Z.ltb x y then T (insert x a) y b\n                        else if Z.ltb y x then T a y (insert x b)\n                        else T a x b\n end.\n\n(* SPECIFICATIONS AND PROOF *)\n\n\nInductive SearchTree: tree -> Prop :=\n(* Getting this right is the most important part of the work,\n *   and it's not completely obvious.\n *)\n(* FILL IN HERE *).\n\nInductive Contents:  Ensemble Z -> tree -> Prop :=\n| Ct_E: Contents Empty_set E\n(* FILL IN HERE *).\n\n\n\nTheorem member_spec:\n  forall k cts t,\n    SearchTree t ->\n    Contents cts t ->\n    (In cts k <->  member k t = true).\nProof.\n(* FILL IN HERE *) Admitted.\n\nTheorem insert_contents:\n forall k t cts,\n    SearchTree t ->\n    Contents cts t ->\n    Contents (Union (Singleton k) cts) (insert k t).\nProof.\n(* FILL IN HERE *) Admitted.\n\nTheorem insert_searchtree:\n  forall k t,\n   SearchTree t -> SearchTree (insert k t).\nProof.\n(* FILL IN HERE *) Admitted.\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/SearchTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7544208211888515}}
{"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.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Divide.\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#[global]\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#[global]\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#[global]\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#[global]\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 lia; 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; lia).\n    induction (Z.to_nat x). {\n      simpl in *; lia.\n    } {\n      rewrite Nat2Z.inj_succ in *.\n      rewrite Z.pow_succ_r by lia.\n      rewrite Z.mul_mod by lia.\n      case_eq n; intros. {\n        subst. simpl.\n        rewrite Zmod_1_l by lia.\n        rewrite H1.\n        apply Zmod_0_l.\n      } {\n        subst.\n        rewrite IHn by (rewrite Nat2Z.inj_succ in *; lia).\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 Nat2Z.inj_mod (Z.to_nat x) (Z.to_nat m) as H;\n      rewrite !Z2Nat.id in H by lia.\n    rewrite <-H.\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#[global]\n  Hint Rewrite mul_div_eq_full using zutil_arith : zdiv_to_mod.\n#[global]\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#[global]\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#[global]\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#[global]\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#[global]\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_full a m) at 2.\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_full a m) at 2.\n    ring.\n  Qed.\n\n#[global]\n  Hint Rewrite mul_div_eq mul_div_eq' using zutil_arith : zdiv_to_mod.\n#[global]\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#[global]\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_in_goal; subst;\n        destruct_head'_or; destruct_head'_and;\n          try assert (b < 0) by lia;\n          try assert (c < 0) by lia;\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 lia; 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 lia; clear H\n                 | [ H : -?x + ?y <= 0 |- _ ] => assert (0 <= x + -y) by lia; 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 lia.\n    all:break_match; Z.ltb_to_lt; lia.\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; lia. }\n    { erewrite mod_pull_div_helper at 1 by (lia || reflexivity); cbv beta.\n      destruct (c <? 0) eqn:?; simpl; [ | lia ].\n      break_innermost_match; lia. }\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; lia. 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_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_in_goal\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                               | lia\n                               | match goal with\n                                 | [ H : ?x <= ?y, H' : ?y <= ?x |- _ ] => assert (x = y) by lia; 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.\n\n  Lemma mod_mod_0_0_eq x y : x mod y = 0 -> y mod x = 0 -> x = y \\/ x = - y \\/ x = 0 \\/ y = 0.\n  Proof.\n    destruct (Z_zerop x), (Z_zerop y); eauto.\n    Z.div_mod_to_quot_rem_in_goal; subst.\n    rewrite ?Z.add_0_r in *.\n    match goal with\n    | [ H : ?x = ?x * ?q * ?q' |- _ ]\n      => assert (q * q' = 1) by nia;\n          destruct_head'_or;\n          first [ assert (q < 0) by nia\n                | assert (0 < q) by nia ];\n          first [ assert (q' < 0) by nia\n                | assert (0 < q') by nia ]\n    end;\n      nia.\n  Qed.\n  Lemma mod_mod_0_0_eq_pos x y : 0 < x -> 0 < y -> x mod y = 0 -> y mod x = 0 -> x = y.\n  Proof. intros ?? H0 H1; pose proof (mod_mod_0_0_eq x y H0 H1); lia. Qed.\n  Lemma mod_mod_trans x y z : y <> 0 -> x mod y = 0 -> y mod z = 0 -> x mod z = 0.\n  Proof.\n    intros Hy. rewrite (Zmod_eq_full x y Hy). intros Hx Hyz.\n    replace x with (x / y * y) by lia. now rewrite Zmult_mod, Hyz, Z.mul_0_r.\n  Qed.\n\n  Lemma mod_opp_r a b : a mod (-b) = -((-a) mod b).\n  Proof. pose proof (Z.div_opp_r a b); Z.div_mod_to_quot_rem; nia. Qed.\n#[global]\n  Hint Resolve mod_opp_r : zarith.\n\n  Lemma mod_same_pow : forall a b c, 0 <= c <= b -> a ^ b mod a ^ c = 0.\n  Proof.\n    intros a b c H.\n    replace b with (b - c + c) by ring.\n    rewrite Z.pow_add_r by lia.\n    apply Z_mod_mult.\n  Qed.\n#[global]\n  Hint Rewrite mod_same_pow using zutil_arith : zsimplify.\n#[global]\n  Hint Resolve mod_same_pow : zarith.\n\n  Lemma mod_opp_l_z_iff a b (H : b <> 0) : a mod b = 0 <-> (-a) mod b = 0.\n  Proof.\n    split; intro H'; apply Z.mod_opp_l_z in H'; rewrite ?Z.opp_involutive in H'; assumption.\n  Qed.\n#[global]\n  Hint Rewrite <- mod_opp_l_z_iff using zutil_arith : zsimplify.\n\n  Lemma mod_small_sym a b : 0 <= a < b -> a = a mod b.\n  Proof. intros; symmetry; apply Z.mod_small; assumption. Qed.\n#[global]\n  Hint Resolve mod_small_sym : zarith.\n\n  Lemma mod_eq_le_to_eq a b : 0 < a <= b -> a mod b = 0 -> a = b.\n  Proof. pose proof (Z.mod_eq_le_div_1 a b); intros; Z.div_mod_to_quot_rem; nia. Qed.\n#[global]\n  Hint Resolve mod_eq_le_to_eq : zarith.\n\n  Lemma mod_neq_0_le_to_neq a b : a mod b <> 0 -> a <> b.\n  Proof. repeat intro; subst; autorewrite with zsimplify in *; lia. Qed.\n#[global]\n  Hint Resolve mod_neq_0_le_to_neq : zarith.\n\n  Lemma div_mod' a b : b <> 0 -> a = (a / b) * b + a mod b.\n  Proof. intro; etransitivity; [ apply (Z.div_mod a b); assumption | lia ]. Qed.\n#[global]\n  Hint Rewrite <- div_mod' using zutil_arith : zsimplify.\n\n  Lemma div_mod'' a b : b <> 0 -> a = a mod b + b * (a / b).\n  Proof. intro; etransitivity; [ apply (Z.div_mod a b); assumption | lia ]. Qed.\n#[global]\n  Hint Rewrite <- div_mod'' using zutil_arith : zsimplify.\n\n  Lemma div_mod''' a b : b <> 0 -> a = a mod b + (a / b) * b.\n  Proof. intro; etransitivity; [ apply (Z.div_mod a b); assumption | lia ]. Qed.\n#[global]\n  Hint Rewrite <- div_mod''' using zutil_arith : zsimplify.\n\n  Lemma sub_mod_mod_0 x d : (x - x mod d) mod d = 0.\n  Proof.\n    destruct (Z_zerop d); subst; push_Zmod; autorewrite with zsimplify; reflexivity.\n  Qed.\n#[global]\n  Hint Resolve sub_mod_mod_0 : zarith.\n#[global]\n  Hint Rewrite sub_mod_mod_0 : zsimplify.\n\n  Lemma mod_small_n n a b : 0 <= n -> b <> 0 -> n * b <= a < (1 + n) * b -> a mod b = a - n * b.\n  Proof. intros; erewrite Zmod_eq_full, Z.div_between by eassumption. reflexivity. Qed.\n#[global]\n  Hint Rewrite mod_small_n using zutil_arith : zsimplify.\n\n  Lemma mod_small_1 a b : b <> 0 -> b <= a < 2 * b -> a mod b = a - b.\n  Proof. intros; rewrite (mod_small_n 1) by lia; lia. Qed.\n#[global]\n  Hint Rewrite mod_small_1 using zutil_arith : zsimplify.\n\n  Lemma mod_opp_small a m : 0 < a <= m -> (-a) mod m = m - a.\n  Proof. intros; symmetry; apply Zmod_unique with (-1); lia. Qed.\n\n  Lemma mod_neg_small a m : -m <= a < 0 -> a mod m = m + a.\n  Proof. intros; symmetry; apply Zmod_unique with (-1); lia. Qed.\n\n  Lemma mod_small_n_if n a b : 0 <= n -> b <> 0 -> n * b <= a < (2 + n) * b -> a mod b = a - (if (1 + n) * b <=? a then (1 + n) else n) * b.\n  Proof. intros; erewrite Zmod_eq_full, Z.div_between_if by eassumption; autorewrite with zsimplify_const. reflexivity. Qed.\n\n  Lemma mod_small_0_if a b : b <> 0 -> 0 <= a < 2 * b -> a mod b = a - if b <=? a then b else 0.\n  Proof. intros; rewrite (mod_small_n_if 0) by lia; autorewrite with zsimplify_const. break_match; lia. Qed.\n\n  Lemma mul_mod_distr_r_full a b c : (a * c) mod (b * c) = (a mod b * c).\n  Proof.\n    destruct (Z_zerop b); [ | destruct (Z_zerop c) ]; subst;\n      autorewrite with zsimplify; auto using Z.mul_mod_distr_r.\n  Qed.\n\n  Lemma mul_mod_distr_l_full a b c : (c * a) mod (c * b) = c * (a mod b).\n  Proof.\n    destruct (Z_zerop b); [ | destruct (Z_zerop c) ]; subst;\n      autorewrite with zsimplify; auto using Z.mul_mod_distr_l.\n  Qed.\n\n  Lemma lt_mul_2_mod_sub : forall a b, b <> 0 -> b <= a < 2 * b -> a mod b = a - b.\n  Proof.\n    intros a b H H0.\n    replace (a mod b) with ((1 * b + (a - b)) mod b) by (f_equal; ring).\n    rewrite Z.mod_add_l by auto.\n    apply Z.mod_small.\n    lia.\n  Qed.\n\n  Lemma mod_pow_r_split x b e1 e2 : 0 <= b -> 0 <= e1 <= e2 -> x mod b^e2 = (x mod b^e1) + (b^e1) * ((x / b^e1) mod b^(e2-e1)).\n  Proof.\n    destruct (Z_zerop b).\n    { destruct (Z_zerop e1), (Z_zerop e2), (Z.eq_dec e1 e2); subst; intros; cbn; autorewrite with zsimplify_fast; destruct x; lia. }\n    intros.\n    replace (b^e2) with (b^e1 * b^(e2 - e1)) by (autorewrite with pull_Zpow; f_equal; lia).\n    rewrite Z.rem_mul_r by auto with zarith.\n    reflexivity.\n  Qed.\n\n  Lemma opp_mod2 a : a mod 2 = - a mod 2.\n  Proof. rewrite !Zmod_odd, Z.odd_opp; reflexivity. Qed.\n  \n  Lemma mod_pow_same_base_larger a b n m :\n    0 <= n < m -> 0 < b ->\n    (a mod (b^n)) mod (b^m) = a mod b^n.\n  Proof.\n    intros.\n    pose proof Z.mod_pos_bound a (b^n) ltac:(auto with zarith).\n    assert (b^n <= b^m) by auto with zarith.\n    apply Z.mod_small. auto with zarith.\n  Qed.\n\n  Lemma mod_pow_same_base_smaller a b n m :\n    0 <= m <= n -> 0 < b ->\n    (a mod (b^n)) mod (b^m) = a mod b^m.\n  Proof.\n    intros. replace n with (m+(n-m)) by lia.\n    rewrite Z.pow_add_r, Z.rem_mul_r by auto with zarith.\n    push_Zmod; pull_Zmod.\n    autorewrite with zsimplify_fast; reflexivity.\n  Qed.\n\n  (* Useful lemma for add-get-carry patterns.\n     This expression performs a bitwise or. In terms of bit ranges,\n       b...a + a...c << a-b = b...c *)\n  Lemma add_div_pow2 x a b :\n    0 <= b <= a ->\n    (x mod (2 ^ a)) / 2 ^ b + x / 2 ^ a * 2 ^ (a - b)\n    = x / 2 ^ b.\n  Proof.\n    intros. rewrite Z.pow_sub_r by auto with zarith.\n    rewrite <-Z.divide_div_mul_exact\n      by auto using Z.divide_pow_le with zarith.\n    rewrite <-Z.div_add by auto with zarith.\n    rewrite Z.mul_div_eq', Z.mul_mod, Z.mod_same_pow by auto with zarith.\n    autorewrite with zsimplify.\n    Z.div_mod_to_quot_rem; nia.\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/Modulo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7543017286646889}}
{"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 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-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/minimizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7543013313846747}}
{"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\".\nRequire Export ProofObjects.\nCheck evenb.\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  apply nat_ind.\n  - reflexivity.\n  - simpl. intros. rewrite H. reflexivity.\nQed.\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\n\n(*rgb_ind: forall P: rgb -> Prop,\n  P red -> P green -> P blue -> forall y:rgb, P y*)\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\nCheck natlist1_ind.\n\n(** Now what will the induction principle look like? *)\n(** \n  natlist1_ind:\n    forall P: natlist1 -> Prop,\n      P nnil1 -> (forall n:natlist1, P n -> (forall n0:nat, P (nsnoc1 n n0)))\n        -> forall n:natlist1, P n.\n\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(** \n    byntree_ind\n    : forall P: byntree -> Prop,\n        P bempty -> (forall y:yesno, P (bleaf y)) -> \n          (forall y:yesno (b byntree), P b -> forall b1:byntree, P b1 -> P (nbranch y b b1)) ->\n            forall b:byntree, P b. \n\n*)\n\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  | con1: bool -> ExSet\n  | con2: nat -> ExSet -> ExSet.\nCheck ExSet_ind.\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  tree_ind :\n    forall (X:Type) P: tree X -> Prop, (forall l:X, P (leaf X l)) ->\n       (forall t:tree X, P t -> (forall t0:tree X, P t0) -> P (node X t t0)) ->\n          forall t:tree X, P t.\n\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*) \nInductive mytype (X:Type):Type :=\n  | constr1 : X -> mytype X\n  | constr2 : nat -> mytype X\n  | constr3 : mytype X -> nat -> mytype X.\nCheck mytype_ind. \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\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.\nCheck foo_ind.\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.\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                    _______________________   ) ->\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 [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    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.  *)\nDefinition P_pa (n m p:nat):Prop :=\n    (n + m) + p = n + (m + p).\n\nTheorem plus_assoc'': forall n m p, P_pa n m p.\nProof.\n  intros n m p. induction n as [|n' IHn'].\n  - unfold P_pa. simpl. reflexivity.\n  - unfold P_pa. simpl. unfold P_pa in IHn'. rewrite IHn'. reflexivity.\nQed.\n\nDefinition P_pc (n m:nat) : Prop :=\n    n + m = m + n.\n\nTheorem plus_comm''': forall n m:nat, P_pc n m.\nProof.\n  intros n m.\n  induction n as [|n' IHn'].\n  - unfold P_pc. rewrite plus_n_O. reflexivity.\n  - unfold P_pc in IHn'. unfold P_pc. rewrite <- plus_n_Sm. simpl. rewrite IHn'.\n     reflexivity.\nQed.\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].  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]: *)\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", "meta": {"author": "AKKID", "repo": "If", "sha": "de95d24a26d4a28e1ae11a4b962b4bce20c313f7", "save_path": "github-repos/coq/AKKID-If", "path": "github-repos/coq/AKKID-If/If-de95d24a26d4a28e1ae11a4b962b4bce20c313f7/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.9149009457116781, "lm_q1q2_score": 0.7543009961451964}}
{"text": "Goal 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.", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/2/7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7542748295375943}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Import Coq.setoid_ring.Ring_theory.\nRequire Import Ring Ring_tac.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Relation_Definitions Setoid.\n\n\nExample whitehead {R : Type} {rO rI : R} {radd rmul rsub : R -> R -> R} \n         {ropp : R -> R} {req : R -> R -> Prop} (req_eq : Equivalence req)\n         (Rth : ring_theory rO rI radd rmul rsub ropp req) (Rth_proper : ring_eq_ext radd rmul ropp req):\n         forall x : R, req (rmul (rmul (radd rI rI) x) (radd x rI)) (radd (rmul (radd rI rI) (rmul x x)) (rmul (radd rI rI) x)).\nintros.\napply (@Equivalence_Transitive _ _ req_eq _ _ _ (Rmul_comm Rth (rmul (radd rI rI) x) (radd x rI))).\napply (@Equivalence_Transitive _ _ req_eq _ _ _ (Rdistr_l Rth _ _ _)).\napply (radd_ext Rth_proper).\napply (@Equivalence_Transitive _ _ req_eq _ _ _ (Rmul_assoc Rth _ _ _)).\napply (@Equivalence_Transitive _ _ req_eq _ _ _ (Rmul_comm Rth _ x)).\napply (@Equivalence_Transitive _ _ req_eq _ _ _ (Rmul_assoc Rth _ _ _)).\napply (Rmul_comm Rth (rmul x x) (radd rI rI)).\napply (Rmul_1_l Rth _).\nDefined.\n\nOpen Scope R_scope.\n\nExample whitehead_real : forall x : R, ((2 * x) * (x + 1)) = ((2 * (x * x)) + (2 * x)).\napply (whitehead (Eqsth _) RTheory).\nsplit; cbv.\nall: intros.\nall: rewrite H.\n3: reflexivity.\nall: rewrite H0.\nall: reflexivity.\nDefined.", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/Whitehead.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7542690496745441}}
{"text": "Require Import Nijn.Prelude.Checks.\nRequire Import Nijn.Prelude.Relations.WellfoundedRelation.\nRequire Import Nijn.Prelude.Orders.CompatibleRelation.\n\n(** * The lexicographic order *)\n\nSection Lexico.\n  Context (X : CompatRel)\n          {Y : Type}\n          `{isCompatRel X}\n          (RY : Y -> Y -> Type).\n\n  (** Given a compatible relation and a type with a relation on it, then we can define the lexicographic order on the product. *)\n  Definition lexico\n    : X * Y -> X * Y -> Type\n    := fun x y => ((gt (fst x) (fst y))\n                   +\n                   ((fst x >= fst y) * RY (snd x) (snd y)))%type.\n\n  (** Transitivity for the lexicographic order *)\n  Proposition lexico_trans\n              (RYtrans : forall (y1 y2 y3 : Y),\n                           RY y1 y2 -> RY y2 y3 -> RY y1 y3)\n              {x y z : X * Y}\n              (p : lexico x y)\n              (q : lexico y z)\n    : lexico x z.\n  Proof.\n    destruct p as [p | [p1 p2]], q as [q | [q1 q2]].\n    - left.\n      exact (gt_trans p q).\n    - left.\n      exact (gt_ge p q1).\n    - left.\n      exact (ge_gt p1 q).\n    - right.\n      split.\n      + exact (ge_trans p1 q1).\n      + exact (RYtrans _ _ _ p2 q2).\n  Qed.\n\n  (** Wellfoundedness of the lexicographic order *)\n  Proposition lexico_Wf_help\n              (x : X * Y)\n              (z1 : X)\n              (p : fst x >= z1)\n              (HX : isWf lexico x)\n    : isWf lexico (z1 , snd x).\n  Proof.\n    revert p.\n    revert z1.\n    induction HX as [[q1 q2] Hq IHq].\n    simpl in *.\n    intros z1 p.\n    apply acc.\n    intros [w1 w2] [H' | [H1 H2]] ; simpl in *.\n    - refine (IHq (w1 , w2) _ w1 _) ; simpl.\n      + left ; simpl.\n        exact (ge_gt p H').\n      + apply ge_refl.\n    - refine (IHq (q1 , w2) _ w1 _).\n      + right ; simpl.\n        split.\n        * apply ge_refl.\n        * exact H2.\n      + refine (ge_trans p H1).\n  Qed.\n\n  Proposition lexico_Wf\n              (HX : Wf (fun (x y : X) => x > y))\n              (HY : Wf RY)\n    : Wf lexico.\n  Proof.\n    intros [x y].\n    pose (HX x) as Hx.\n    revert y.\n    induction Hx as [x Hx IHx].\n    intros y.\n    pose (HY y) as Hy.\n    induction Hy as [y Hy IHy].\n    apply acc.\n    intros [z1 z2] [Hz | [Hz1 Hz2]] ; simpl in *.\n    - apply IHx.\n      exact Hz.\n    - refine (lexico_Wf_help (x , _) z1 Hz1 _).\n      exact (IHy z2 Hz2).\n  Qed.\nEnd Lexico.\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/Relations/Lexico.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7542572271407643}}
{"text": "Require Import QArith.\nRequire Import Arith.\nRequire Import Omega.\n\n(* RI x y = x + y√5 *)\nRecord ri : Set := RI { R : Q; I : Q }.\n\nDefinition RIred (r : ri) := RI (Qred (R r)) (Qred (I r)).\n\nDefinition RInegate (r : ri) := RI (0 - R r) (0 - I r).\n\nDefinition RIplus (r1 : ri) (r2 : ri) := RI (R r1 + R r2) (I r1 + I r2).\n\nDefinition RIminus (r1 : ri) (r2 : ri) := RIplus r1 (RInegate r2).\n\nDefinition RImult (r1 : ri) (r2 : ri) :=\n  let w := R r1  in\n  let x := I r1  in\n  let y := R r2  in\n  let z := I r2  in\n  let a := 5 # 1 in\n  RI (w * y + x * z * a) (w * z + x * y).\n\nFixpoint RIpower (r : ri) (n: nat) :=\n  match n with\n  | O => RI (1 # 1) (0 # 1)\n  | S O => r\n  | S n => RImult (RIpower r n) r\n  end.\n\nNotation \"a ^ b\" := (RIpower a b).\nNotation \"a * b\" := (RImult  a b).\nNotation \"a + b\" := (RIplus  a b).\nNotation \"a - b\" := (RIminus a b).\n\nDefinition fib (n : nat) := RI 0 (1 # 5) * ((RI (1 # 2) (1 # 2)) ^ n - (RI (1 # 2) ((0 - 1) # 2)) ^ n).\n\nFixpoint fib' (n : nat) : nat\n := match n with\n  | O => 0\n  | S O => 1\n  | S n => fib' n + fib' (pred n)\n end.\n\n\n\nDefinition prop : forall (n : nat), (Z.of_nat (fib' n)) # 1 = R (RIred (fib n)).\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nsimpl in IHn.\nsimpl.\n", "meta": {"author": "aidatorajiro", "repo": "WorksOfProof", "sha": "e65dd026f5e700ce37ca5ffab86e863616af8641", "save_path": "github-repos/coq/aidatorajiro-WorksOfProof", "path": "github-repos/coq/aidatorajiro-WorksOfProof/WorksOfProof-e65dd026f5e700ce37ca5ffab86e863616af8641/fib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.754200119480902}}
{"text": "Require Import Nat Arith.\n\nInductive Lst : Type := cons : nat -> Lst -> Lst |  nil : Lst.\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\nTheorem theorem0 : forall (x : Lst), ge (len x) 0.\nProof.\n   intros.\n   induction x.\n   - simpl. auto.\n   - simpl. auto.\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_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7541962685356313}}
{"text": "From NaturalNumbers Require Export Base Tutorial Addition Multiplication.\n\nFixpoint pow (a p : mynat) : mynat :=\n    match p with\n    | O => I\n    | S q => (pow a q) * a\n    end.\n\nInfix \"^\" := pow.\nNotation \"(^)\" := pow (only parsing).\nNotation \"( f ^)\" := (pow f) (only parsing).\nNotation \"(^ f )\" := (fun g => pow g f) (only parsing).\n\nFact pow_zero (a : mynat) : a ^ 0 = 1.\nProof.\n    (* unfold pow *)\n    trivial.\nQed.\n\nFact pow_succ (a b : mynat) : a ^ S b = a ^ b * a.\nProof.\n    (* unfold pow *)\n    trivial.\nQed.\n\n(* Level 0 data *)\n(* name `zero_pow_zero` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 0 prologue *)\n(*\nPower world it is! Let's define our power operator on `mynat` real quick, \nand give you the following theorems to work with:\n<ul>\n    <li>`Fact pow_zero (a : mynat) : a ^ 0 = 1.`</li>\n    <li>`Fact pow_succ (a b : mynat) : a ^ S b = a ^ b * a.`</li>\n</ul>\nWe will not be needing any additional tactics in this world, \n`rewrite`, `reflexivity` and `induction` should be enough, though\nthe `ring` tactic might come in handy!\n\nI will leave you at it for this world, with all the theorems you\nhave so far you should be able to handle yourself without any\nhints or tips from me!\n*)\nLemma zero_pow_zero : 0 ^ 0 = 1.\nProof.\n    (* unfold pow *)\n    reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name `zero_pow_succ` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 1 prologue *)\nLemma zero_pow_succ (m : mynat) : 0 ^ S m = 0.\nProof.\n    (* probably best to do this with induction over m for practice though *)\n    reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 2 data *)\n(* name `pow_one` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 2 prologue *)\nLemma pow_one (a : mynat) : a ^ 1 = a.\nProof.\n    rewrite one_eq_succ_zero.\n    rewrite pow_succ.\n    rewrite pow_zero.\n    ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 data *)\n(* name `one_pow` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 3 prologue *)\nLemma one_pow (m : mynat) : 1 ^ m = 1.\nProof.\n    induction m as [| ? H].\n    - reflexivity.\n    - rewrite pow_succ.\n      rewrite H.\n      reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 4 data *)\n(* name `pow_add` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 4 prologue *)\nLemma pow_add (a m n : mynat) : a ^ (m + n) = a ^ m * a ^ n.\nProof.\n    induction n as [| ? H].\n    - rewrite pow_zero.\n      ring_simplify.\n      reflexivity.\n    - rewrite add_succ.\n      repeat rewrite pow_succ.\n      rewrite H.\n      ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 5 data *)\n(* name `mul_pow` *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 5 prologue *)\nLemma mul_pow (a b n : mynat) : (a * b) ^ n = a ^ n * b ^ n.\nProof.\n    induction n as [| ? H].\n    - reflexivity.\n    - repeat rewrite pow_succ.\n      rewrite H.\n      ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 6 data *)\n(* name `pow_pow` (boss level!) *)\n(* tactics ring *)\n(* theorems pow_succ *)\n(* Level 6 prologue *)\n(*\nBoss level! Alright, maybe a quick tip about the `rewrite` tactic.\nDid you know that instead of repeatedly writing `rewrite` with different\ntheorems or hypotheses like so:\n```\nrewrite succ_add.\nrewrite mul_succ.\nrewrite mul_add.\n...\n```\nyou can instead do\n```\nrewrite succ_add, mul_succ, mul_add.\n```\nTry it out!\n*)\nLemma pow_pow (a m n : mynat) : (a ^ m) ^ n = a ^ (m * n).\nProof.\n    induction n as [| ? H].\n    - repeat rewrite pow_zero; easy.\n    - rewrite mul_succ, pow_succ, pow_add.\n      rewrite H.\n      reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\nDefinition II := S I.\nNotation \"2\" := II.\nFact two_eq_succ_one : 2 = S 1.\nProof.\n  trivial.\nQed.\n\n(* Level 7 data *)\n(* name `add_squared` *)\n(* tactics ring *)\n(* theorems two_eq_succ_one *)\n(* Level 7 prologue *)\n(*\nI have just added the definition for 2 (yeah, we didn't\nhave that yet...) and a theorem \n```\n#Fact two_eq_succ_one : 2 = S 1.\n```\nUse it to prove the last theorem of Power World!\n*)\nLemma add_squared (a b : mynat) : (a + b) ^ 2 = a^2 + b^2 + 2 * a * b.\nProof.\n    (* rewrite two_eq_succ_one *)\n    unfold II, I.\n    repeat rewrite pow_succ.\n    repeat rewrite pow_zero.\n    repeat rewrite one_mul.\n    rewrite mul_add, add_mul.\n    rewrite add_mul.\n    repeat rewrite succ_mul.\n    (* ring_simplify.  output is ugly *)\n    ring.\nQed.\n(* Level epilogue *)\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/Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7541962683960932}}
{"text": "\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nRequire Import QArith.\nImport ListNotations.\nRequire Import Reals.\nRequire Import Psatz.\nRequire Import QArith.Qminmax.\nRequire Import List.\nRequire Import PeanoNat.\n\n\nFixpoint replace_in_list (i :nat)(l : list Q)(b : Q):=\nmatch i,l with\n| O , nil => nil\n| O ,  _::l' => b :: l'\n| S i' , nil =>  nil\n| S i' , a::l' => a :: (replace_in_list i' l' b)\nend.\n\nCheck replace_in_list.\nDefinition lpoint : list (Q)\n  := 1:: 0:: 1 :: 0:: 1 ::  nil.\n\nEval compute in (replace_in_list 3 lpoint (3#1)).\n\nDefinition i_element(i:nat)(l:list Q)(d:Q):=nth i l d.\n\nDefinition j_element(j:nat)(l:list Q)(d:Q):=nth j l d.\n\nDefinition swap (i j :nat)(l : list Q) :=\nreplace_in_list i (replace_in_list j l (nth i l 0)) (nth j l 0) .\n\nEval compute in (swap 1 2 lpoint).\n\nSearch Qle.\nCheck Qle_bool.\n\n\nFixpoint insert (n:Q)(ms : list Q) :=\n  match ms with\n  | nil => n::nil\n  | m::ms' => if  Qle_bool n m\n              then n::ms\n              else m::(insert n ms')\n  end.\n\nEval compute in insert (3#1) (1::0::1::4#1::nil).\n\nFixpoint sort (ms : list Q) :=\n  match ms with\n  | nil => nil\n  | m::ms' => insert m (sort ms')\n  end.\n\nEval compute in sort (4#1::2#1::3#1::1::nil).\n\nEval compute in (le 4 1).\n\nDefinition is_sorted (l : list Q) :=\nforall (i:nat), ( i < ((length l) -1))%nat -> ((nth i l 0) <= (nth (i+1) l 0)).\n\nLemma single_sort: forall a:Q, is_sorted [a].\nProof.\nintros.\nunfold is_sorted.\nintros.\ninduction i.\n- simpl in *. lia.\n- simpl in *. lia.\nQed.\nSearch Qle.\n\nLemma empty_list_is_sorted:is_sorted ([]).\nProof.\nunfold is_sorted.\nintros.\ninduction i.\n- simpl. apply Qle_refl.\n- simpl. apply Qle_refl.\nQed.\n\n\nLemma sortedlist_sort:forall (a:Q)(l:list Q), is_sorted (a::l)-> is_sorted l.\nProof.\nintros. unfold is_sorted in *. intros. specialize (H (S i)). induction i. \n- simpl in *. rewrite <- minus_n_O in H. \n  apply  (lt_O_minus_lt (length l) 1) in H0. auto.\n- simpl in *. rewrite <- minus_n_O in H. \n  apply Nat.lt_add_lt_sub_r in H0. rewrite Nat.add_1_r in H0. auto.\nQed.\n\nLemma insert_sorted_0: forall (a :Q) (l:list Q), is_sorted(l) /\\ a <= nth 0 l 0 \n-> is_sorted(a::l).\nProof. \nintros. destruct H. unfold is_sorted. intros. induction i.\n  - simpl. auto.\n  - simpl. unfold is_sorted in H. specialize (H i). simpl in H1.\n    rewrite <- Nat.add_1_r in H1. rewrite <- minus_n_O in H1.\n    apply Nat.lt_add_lt_sub_r in H1. auto.\nQed.\n\nLemma Qle_bool_false: forall (a b :Q) , (Qle_bool a b = false) -> a>b.\nProof. \n intros.\n  generalize ((proj2 (Qle_bool_iff a b))). rewrite H.\n  destruct (Qlt_le_dec b a); intuition; try discriminate.\nQed.\n\nLemma list_length: forall(l:list Q) , (length l >= 0)%nat.\nProof.\nintro. induction l.\n  - simpl. auto.\n  - simpl.  rewrite <- Nat.add_1_r. apply le_plus_trans. auto.\nQed.\n\nLemma succ_pos: forall(n:nat) ,( S n > 0 )%nat.\nProof.\nintros. induction n.\n  - auto.\n  -  auto.\nQed.\n\nLemma insert_works: forall (l : list Q) (a : Q), (is_sorted l) -> \n(is_sorted (insert a l)).\nProof.\nintros.\ninduction l.\n  - simpl in *. apply single_sort.\n  - unfold insert. remember (Qle_bool a a0) as res. induction res.\n      + symmetry in Heqres. apply Qle_bool_iff in Heqres.\n        apply insert_sorted_0. split.\n        -- auto.\n        -- simpl. auto.\n      + fold insert. unfold is_sorted. intros. induction i.\n        -- simpl. unfold insert. induction l.\n           ++ simpl. symmetry in Heqres. apply Qle_bool_false in Heqres.\n              apply Qlt_le_weak. auto.\n           ++ simpl in *. remember (Qle_bool a a1) as b. induction b.\n              --- simpl. symmetry in Heqres. apply Qle_bool_false in Heqres.\n                  apply Qlt_le_weak. auto.\n              --- simpl. fold insert in IHl0. unfold is_sorted in H.\n                  specialize (H O) . simpl in *. assert ( 0 < S (length l))%nat.\n                  +++ apply succ_pos.\n                  +++ auto.\n        -- simpl. apply sortedlist_sort in H. apply IHl.\n           ++ auto.\n           ++ simpl in H0. rewrite <- Nat.add_1_r in H0.\n              rewrite <- minus_n_O in H0. apply Nat.lt_add_lt_sub_r in H0. auto.\nQed.\n\n\nLemma sort_sorts: forall (l: list Q), is_sorted( sort l).\nProof.\nintros.\ninduction l.\n  - simpl in *. apply empty_list_is_sorted.\n  - simpl in *. apply insert_works. auto.\nQed.\n\n ", "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/Sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7541062434945544}}
{"text": "(** The top-level command [Check <exp>] tells you the type of the given exp. *)\nCheck True.\nCheck False.\n\n(** [True] and [False] are propositions or something classified by the type [Prop].  \n   They are not to be confused with [true] and [false] which are booleans.\n   The distinction is roughly, that [true] and [false] are objects, whereas\n   [True] and [False] are types.  What are the elements of the type [True]?\n   They are all the *proofs* that allow us to conclude \"True\".  In contrast,\n   the object [true] doesn't really name a collection of things.  \n\n   So what are some of the elements or proof objects in the special \n   type [True]?\n*)\nPrint True.\n(** Aha!  We see that one element is the constructor [I].  It's a way \n   (in fact, the best way) to build a proof whose conclusion is the\n   trivial theorem [True].  \n*)\nCheck I.\n(** But [I] is not the only way to build an object of type [True].  Another\n   example is:\n*)\nCheck (fun x => x) I.\n(** And we will see many more examples of ways to construct a proof of [True].\n   However, it will turn out that if a (closed) expression e : True, then\n\n   So in general, an element of [Prop], such as [True], is the \n   name of a theorem, and at the same type, names a collection of terms that\n   correspond to proofs of that theorem. \n\n   What about [False]?\n*)\nPrint False.\n(** [False] is a funny inductive definition which has no\n   constructors.  So, there's no easy way to build an object that\n   has type [False].  A very, very deep result about Coq is that in\n   fact, there is no closed term E such that E : False.  In other\n   words, there's no way construct a proof of False, and that's a\n   very good thing.\n\n   Now remember last time, that I said that all functions in Coq\n   must terminate?  Well, one reason why is that if we had diverging\n   computations, a la OCaml, then we would have a way to build\n   a term E of type False.  For instance, in OCaml, we can define:\n\n   letrec loop () : t = loop ()\n\n   for any type [t] that we like, includng an empty type.  This\n   means that in OCaml, every type has an element and thus we\n   can't use OCaml types to represents propositions such as [False].\n   Another way to say this is that in OCaml, the \"logic\" of the \n   language is \"inconsistent.\" \n\n   There are other good reasons why Coq functions are required\n   to terminate.  One is that the type-checker must sometimes\n   normalize (i.e., simplify) expressions to see if they are equal.  \n   If that normalization process could diverge, then so could\n   type-checking.\n\n   Later on, we'll see how it's possible to *model* computations\n   that might diverge.\n*)\n\n\n(** The top-level command [Locate \"...\"] helps to locate a symbol that's defined\n   with notation.  In this case, we are searching for the notation for logical\n   \"and\". *)\nLocate \"_ /\\ _\".\nCheck and.\n\n(** The top-level command [Print <id>] prints the definition of a \n   given identifier.  Note that [and] is just an inductive definition\n   with one constructor, [conj] which takes two [Prop]s as arguments,\n   and produces a [Prop] as a result. *)\nPrint and.\nLocate \"_ * _\".\nCheck prod.\nPrint prod.\nLocate \"_ \\/ _\".\nCheck or.\n\n(** Logical [or] is also just an inductive definition, but this\n   time it has two constructors, one for the left and one for \n   the right. *)\nPrint or.\n\n(** I'm going to start a new module named [M1] so that I don't\n   pollute the top-level namespace.  We end the module by writing\n   [end M1.] -- see below. *)\nModule M1.\n\n  (** Now we can start building some interesting proofs. *)\n  Definition proof_of_true_and_true : True /\\ True := \n    conj I I.\n\n  Definition proof_of_true_or_false : True \\/ False := \n    or_introl I.\n\n  Definition proof_of_false_or_true : False \\/ True := \n    or_intror I.\n  \n  (** What about implication?  This can be represented as a\n     function.  That is, we can think of \"A implies B\" as \n     a function which takes evidence of A and constructs\n     evidence of B from it.  In fact, we will use the notation\n     \"->\" to denote both functions and implication.  And we\n     will use [fun x => ...] to build a function, or evidence\nccer     of an implication.  For instance: *)\n  Definition t0 {A:Prop} : A -> True := \n    fun (H:A) => I.\n\n  Definition t1 {A B:Prop} : A -> B -> A /\\ B := \n    fun (HA:A) (HB:B) => conj HA HB.\n  \n  (** This example shows taking apart some evidence.  In this\n     case, we are given evidence of [A /\\ B] and we need to\n     construct from it evidence of [A].  So we use a pattern\n     match to tear apart the proof of [A /\\ B], since we know\n     that it must've been built from [conj HA HB] where [HA]\n     is a proof of [A] and [HB] is a proof of [B].  *)\n  Definition t2 {A B:Prop} : A /\\ B -> A := \n    fun (H : A /\\ B) => \n      match H with \n        | conj H1 H2 => H1\n      end.\n  \n  Definition t3 {A B:Prop} : A /\\ B -> B :=\n    fun (H: A /\\ B) => \n      match H with\n        | conj H1 H2 => H2\n      end.\n    \n  Definition t4 {A B C:Prop} : \n    (A -> C) /\\ (B -> C) -> (A \\/ B) -> C := \n    fun (H1:(A->C)/\\(B->C)) (H2:A\\/B) => \n      match H1 with \n        | conj H3 H4 => match H2 with \n                          | or_introl H5 => H3 H5\n                          | or_intror H6 => H4 H6\n                        end\n      end.\n\n  Definition t5 {A:Prop} : False -> A := \n    fun (H:False) => \n      match H with \n      end.\n\n  Definition t6 {A B C D:Prop} (H1:A -> B \\/ C) : \n    (B -> D) -> (C -> D) -> (A -> D) := \n    fun H2 H3 H4 => \n      let H5 := H1 H4 in \n      t4 (conj H2 H3) H5.\n\n  Locate \"~ _\".\n  Check not.\n  Print not.\n\n  (** Negation [~A] is just an abbreviation for [A -> False]. *)\n  Definition t7 {A B C : Prop} : \n    ~ (A /\\ B) -> A -> B -> C := \n    fun (H1 : (A/\\B) -> False) (H2:A) (H3:B) => \n      match H1 (conj H2 H3) with\n      end.\n\n  Definition t7' : forall {A B C:Prop}, \n    ~ (A /\\ B) -> A -> B -> C.                   \n    Abort.\n\n  Definition t7'' : \n    forall {A B C : Prop} (H1:~ (A /\\ B)) (H2 : A) (H3 : B), C.\n    Abort.\n\n  Inductive animal : Type := \n  | Cow | Duck | Pig | Platypus.\n    \n  (** In addition to the built-in [Prop]s, we can define new \n     propositional constructions.  For example, below I define\n     a proposition called [has_bill] which is a predicate on \n     [animal]s.  \n   *)\n  Definition has_bill (a:animal) : Prop := \n    match a with \n      | Duck => True\n      | Platypus => True\n      | _ => False\n    end.\n  \n  (** Here's another predicate on animals... *)\n  Definition live_birth (a:animal) : Prop := \n    match a with \n      | Cow => True\n      | Pig => True\n      | _ => False\n    end.\n  \n  (** Then we can use these definitions to construct a more\n     interesting theorem.  Notice that here I'm universally\n     quantifying over an animal, using [forall].  *)\n  Definition darwin : \n    forall a:animal, has_bill a -> ~ live_birth a := \n    fun (a:animal) => \n      match a return has_bill a -> ~live_birth a\n      with \n        | Duck => fun H1 H2 => H2\n        | Platypus => fun H1 H2 => H2\n        | Cow => fun H1 H2 => H1\n        | Pig => fun H1 H2 => H1\n      end.\n\n  Definition moos (a:animal) : Prop := \n    match a with \n      | Cow => True\n      | _ => False\n    end.\n  \n  Locate \"exists\".\n  Check ex.\n  Print ex.\n\n  (** Notice that exists is not primitive and is in fact encoded using forall. Notice that the\n      variable mentioned in forall is really a parameter to the [exists_intro] constructor, allowing\n      us to construct a proof of an existential claim using _any_ witness. \n      The [A] and [P] parameters to [ex_intro] are implicit. We can force ourselves to\n      provide them explicitly by using [@ex_intro] instead. *)\n\n  Definition darwin2 : exists a:animal, (moos a /\\ live_birth a) := \n    ex_intro (fun a => moos a /\\ live_birth a) Cow (conj I I).\n\n  (** Sometimes, Coq can figure out what a missing argument is and\n     we can omit it by putting in an underscore \"_\" as in the \n     example below. *)\n  Definition darwin3 : exists a:animal, (moos a /\\ live_birth a) := \n    ex_intro _ Cow (conj I I).\n\nEnd M1.\n\nModule PSET1_EX1.\n\n(**PROBLEM1:  *)\n\n  Definition X1 {A B C D:Prop} : (B /\\ (B -> C /\\ D)) -> D :=\n  fun (H1: B /\\ (B -> C /\\ D))  =>\n    match H1 with \n      | conj (H2) (H3) => \n        let H4 :(C /\\ D ):= (H3 H2) in \n        match H4 with \n          | conj H5 H6 => H6\n        end\n  end.\nPrint and.\n\n(**PROBLEM2:  *)\n  Definition X2 {A B C:Prop} : ~(A \\/ B) -> B -> C :=\n  fun (H1: A \\/ B -> False) (H2:B) =>\n    let H3: (A\\/B) := (or_intror H2) in \n    match H1 H3 with \n    end.\n\n(** PROBLEM3: *)\n  Definition X3 {A B C:Prop} :  A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C) :=\n  fun (H1 : A /\\ (B \\/ C)) =>\n    match H1 with \n      | conj H2 H3 => match H3:(B \\/ C) with\n                      |or_introl b => or_introl (conj H2 b) \n                      |or_intror H5 => or_intror (conj H2 H5)\n                      end\n    end.\n\n(** PROBLEM 4: To solve the following, you'll need to figure \nout what the definition of \"<->\" is and how to work with it... *)\nLocate \"_ <-> _\".\nCheck iff.\nPrint iff.\n\nDefinition X4 {A:Prop} : A <-> A :=\n    conj (fun (a:A) => a ) (fun (a:A) => a).\n\nPrint and.\n(** PROBLEM4: *)\nDefinition X5 {A B:Prop} : (A <-> B) <-> (B <-> A):=\n  conj \n   (fun H1 =>\n    match H1 with\n      | conj H2 H3 => conj H3 H2\n    end) \n\n   (fun H1 =>\n    match H1 with\n      | conj H2 H3 => conj H3 H2\n    end) \n.\n\nPrint iff.\n(** PROBLEM 5: *)\n\nDefinition assoc {A B  C: Prop} (f1:A -> B) (f2:B -> C) (a:A) : C :=\n    f2 (f1 a).\n\nDefinition X6 {A B C:Prop} : (A <-> B) -> (B <-> C) -> (A <-> C):=\n  fun (H1:((A -> B) /\\ (B -> A))) (H2: ((B-> C) /\\ (C -> B))) =>\n    match H1, H2 with\n    | conj h11 h12 , conj h21 h22 => conj (assoc h11 h21) (assoc h22 h12)\n    end.\n\nLemma uncurrying: forall (A B C :Prop),\n((A/\\B)->C) <-> (A->B->C).\nAbort.\n\n(** PROBLEM think-about-it *)\nDefinition not_pos {A}: A \\/ ~A.\nAdmitted.\n\n(** Definition haltingProblem (n:N) : (n th TM halts) \\/ \n(n th TM never halts). *)\n \n(** Building proof objects by hand can be extremely difficult.\n   So instead, we're going to use some *tactics* to construct\n   these objects.  Some useful tactics include the following:\n\n   auto   -- solves trivial goals such as \"True\" and \"3 = 3\" or\n             \"x = x\".\n\n   intro  -- given a goal A -> B, introduces A as an assumption,\n             leaving B as the result.  It's the same as writing\n             [refine (fun H:A => _)].\n\n   intros -- same as above but introduces a bunch of assumptions.\n             For instance, if our goal is A -> B -> C -> D, then\n             intros will introduce hypotheses H1:A, H2:B, and\n             H3:C and leave us with the goal D.  You can also\n             give explicit names for the hypotheses as in \n             intros H1 H2 H3.\n\n   split --  if the goal is A /\\ B, breaks this into two sub-goals,\n             first A and then B.\n\n   destruct -- if we have a hypothesis [H : A /\\ B] then we can \n               break it into two hypotheses [H1 : A] and [H2 : B].\n               using [destruct].  \n\n   simpl --  simplifies the goal by reducing expressions as much \n             as possible.  For instance, if our goal is\n             [1 + 3 = 2 + 3], then calling [simpl] will reduce\n             the goal to [4 = 4] which we can solve by auto.\n\n   left --   given the goal A \\/ B, reduces the goal to proving\n             just A.  \n\n   right --  given goal A \\/ B, reduces the goal to proving B.\n\n   apply H -- apply the hypothesis H to solve the current goal.\n              This only works when H names a hypothesis that\n              matches the given goal.\n\n   See also http://adam.chlipala.net/itp/tactic-reference.html\n   for a better list.\n*)\n\n(** Re-doing the examples above using tactics. *)\nModule M2.\n\n  (** Notice that I didn't use \":=\" but terminated the definition\n     with a period.  This drops you into tactic mode. *)\n  Definition proof_of_true_and_true : True /\\ True.\n  Proof.  (** not necessary, but a good visual indicator. *)\n    (** prove True /\\ True *)\n    split. (** leaves us with two goals *)\n      (** First goal:  True *)\n      auto.\n      (** Second goal: True *)\n      auto.\n   Qed.  (** claim that we've solved all goals. *)\n\n  (** We can print out the proof object that the tactics\n     constructed for us... *)\n  Print proof_of_true_and_true.\n\n  (** Instead of using the keyword [Definition] we can also\n     use the keywords [Lemma] and [Theorem].  *)\n  Lemma proof_of_true_and_true' : True /\\ True.\n  Proof.  \n    auto.  (** actually, auto will knock this off. *)\n  Qed.\n\n  Theorem prof_of_true_and_true'' : True /\\ True.\n  Proof.\n    (** we can use previously existing proofs. *)\n    apply proof_of_true_and_true'.\n  Qed.\n\n  Definition proof_of_true_or_false : True \\/ False.\n    Abort.\n\n  Definition proof_of_false_or_true : False \\/ True.\n    Abort.\n    \n  Lemma t0 {A:Prop} : A -> True.\n  Proof.\n    intro.\n    auto.\n  Qed.    \n\n  Lemma t1 {A B:Prop} : A -> B -> A /\\ B.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma t2 {A B:Prop} : A /\\ B -> A.\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma t3 {A B:Prop} : A /\\ B -> B.\n  Proof.\n    (** It's generally a bad idea to let Coq pick the names for you. \n       We can usually give names that we want. *)\n    intro H.\n    destruct H as [H1 H2].\n    apply H2.\n  Qed.\n\n  Lemma t3' {A B:Prop} : A /\\ B -> B.\n  Proof.\n    (** We can also do some destruction as we introduce things. *)\n    intros [H1 H2].\n    apply H2.\n  Qed.\n\n  Lemma t3'' {A B:Prop} : A /\\ B -> B.\n  Proof.\n    (** There are some fancier decision procedures that can knock this\n       sort of thing off, such as [firstorder].  For now, try to avoid\n       using these so that you can understand the basic tactics --- you\n       will need them. *)\n    firstorder.\n  Qed.\n\n  Definition t4 {A B C:Prop} : \n    (A -> C) /\\ (B -> C) -> (A \\/ B) -> C.\n  Proof.\n    firstorder.\n  Qed.\n\n  Definition t5 {A:Prop} : False -> A.\n  Proof.\n    firstorder.\n  Qed.\n\n  Definition t6 {A B C D:Prop} : \n    (A -> B \\/ C) -> (B -> D) -> (C -> D) -> (A -> D).\n  Proof.\n    firstorder.\n  Qed.\n\n  Locate \"~ _\".\n  Check not.\n  Print not.\n\n  (** Negation [~A] is just an abbreviation for [A -> False]. *)\n  Definition t7 {A B C : Prop} : \n    ~ (A /\\ B) -> A -> B -> C.\n  Proof.\n    firstorder.\n  Qed.\n  \n  (** We can write the type of [t7] using [forall], which shows that\n      arrow types are really just a special case of a more powerful\n      dependent type construct in which the type on the right-hand\n      side of the arrow can mention the name of the argument. *)\n  Definition t7' : forall {A B C:Prop}, \n    ~ (A /\\ B) -> A -> B -> C.                   \n  Proof.\n    firstorder.\n  Qed.\n\n  Definition t7'' : \n    forall {A B C : Prop} (H1:~ (A /\\ B)) (H2 : A) (H3 : B), C.\n  Proof.\n    firstorder.\n  Qed.\n\n  Inductive animal : Type := \n  | Cow | Duck | Pig | Platypus.\n    \n  Definition has_bill (a:animal) : Prop := \n    match a with \n      | Duck => True\n      | Platypus => True\n      | _ => False\n    end.\n  \n  Definition live_birth (a:animal) : Prop := \n    match a with \n      | Cow => True\n      | Pig => True\n      | _ => False\n    end.\n  \n  (** Then we can use these definitions to construct a more\n     interesting theorem.  Notice that here I'm universally\n     quantifying over an animal, using [forall].  *)\n  Definition darwin : \n    forall a:animal, has_bill a -> ~ live_birth a.\n  Proof.\n    intro a.\n    (** We need to tear apart [a] -- this is done with destruct,\n        just as we tear apart a conjunection [A /\\ B].  In \n        general, destruct does our pattern match for us and \n        leaves us with the corresponding goals. *)\n    destruct a.\n      (** [a = Cow] *)\n      (** It's not immediately clear that this is trivial, unless\n         we [simpl]ify the goal. *)\n      simpl.\n      auto.\n      (** [a = Duck] *)\n      (** auto will do the simplification for you if it needs to. *)\n      auto.\n      (** [a = Pig] *)\n      auto.\n      (** [a = Platypus] *)\n      auto.\n  Qed.\n\n  (** We can string together tactics using a semicolon.  When you\n     write [t1 ; t2], then [t1] is run on the current goal G.  This\n     produces new sub-goals G1, G2, ..., Gn.  Then [t2] is run on\n     each of these sub-goals.  So we can simplify the proof above\n     as follows: *)\n  Definition darwin' : \n    forall a:animal, has_bill a -> ~ live_birth a.\n  Proof.\n    destruct a ;   (** automatically introduces a *)\n    auto.\n  Qed.\n\n  Definition moos (a:animal) : Prop := \n    match a with \n      | Cow => True\n      | _ => False\n    end.\n  \n  Locate \"exists\".\n  Check ex.\n  Print ex.\n\n  Definition darwin2 : exists a:animal, (moos a /\\ live_birth a).\n  Proof.\n    (** The [exists] tactic is the way to solve an existential goal. \n       You have to give the witness. *)\n    exists Cow.\n    simpl.\n    auto.\n  Qed.\n\n\nEnd M2.\n\nModule PSET1_EX2.\n\n(** Now remove the tauto tactics and redo these problems using only \nthe following tactics:\nintros, apply, destruct, unfold, split, contradiction, left, right\n(Hopefully we haven't left off any that you may need. \nIn general, don't use things like firstorder or tauto that \nautomatically solves goals. We want you to perform the basic steps \nto see what is going on.)\n*)\n\n\nLemma X1 {A B C D:Prop} : \n    (B /\\ (B -> C /\\ D)) -> D.\n  Proof.\n    intros H1.\n    destruct H1.\n    apply H0 in H.\n    destruct H.\n    apply H1.\n  Qed.\n\nCheck not.\nPrint not.\nLemma X2 {A B C:Prop} : \n    ~(A \\/ B) -> B -> C.\n  Proof.\n  intros.\n  unfold not in H.\n  apply (@or_intror A ) in H0.\n  apply H in H0.\n  destruct H0.\n  Qed.\n\n  Lemma X3 {A B C:Prop} : A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C).\n  Proof.\n    intros.\n    destruct H.\n    destruct H0.\n     Show Proof.\n   - left.\n     Show Proof.\n     split.\n     Show Proof.\n     + apply H.\n     + apply H0.\n   - right.\n     Show Proof.\n     split.\n     Show Proof.\n     apply H.\n     apply H0.\n  Qed.\n\nLemma X4 {A:Prop} : A <-> A.\n  Proof.\n    intros.\n    Show Proof.\n    split.\n    - intros a. apply a.\n    - intros a. apply a.\n  Qed.\n\nLemma X5 {A B:Prop} :(A <-> B) <-> (B <-> A).\n  Proof.\n    intros.\n    Show Proof.\n    unfold iff.\n    split.\n    - intros H. destruct H.\n      split.\n       + apply H0.\n       + apply H.\n       Show Proof.\n    - split.\n      destruct H.\n      + apply H0.\n      + apply H.\n  Qed.\n\nLemma assoc {A B C: Prop}: (A -> B) /\\ (B-> C) -> (A -> C).\n  Proof.\n    intros.\n    destruct H.\n    apply H1.\n    apply H.\n    assumption.\n  Qed.\n\nLemma X6 {A B C:Prop} : (A <-> B) -> (B <-> C) -> (A <-> C).\n  Proof.\n    intros.\n    unfold iff.\n    unfold iff in H.\n    unfold iff in H0.\n    destruct H.\n    destruct H0.\n    split.\n    - Show Proof.\n      apply @assoc with (B:=B).\n      Show Proof.\n      split;assumption.\n    - apply @assoc with (B:=B).\n      split; assumption.\n  Qed.\n\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/lecture2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7540983467679273}}
{"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 saturday).\n\nExample test_next_weekday :\n  next_weekday (next_weekday saturday) = tuesday.\nProof.\n  simpl. 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 (a b : bool) : bool :=\n  match a with\n    | true   => b\n    |  false => false\n  end.\n\nDefinition orb (a b : bool) : bool :=\n  match a with\n    | true => true\n    | false  => b\n  end.\n\n\nDefinition xorb (a b : bool) : bool :=\n  match a, b with\n    | true, true => false\n    | false, false => false\n    |_, _ => true\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.\nExample test_xor: xorb true true = false.\nProof. reflexivity. Qed.\n\nDefinition nandb (a b : bool) : bool :=\n  match a, b with\n    | true, true => false\n    | _, _ => true\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof. auto. Qed.\nExample test_nandb2: (nandb false false) = true.\nProof. auto. Qed.\nExample test_nandb3: (nandb false true) = true.\nProof. auto. Qed.\nExample test_nandb4: (nandb true true) = false.\nProof. auto. Qed.\n\nDefinition andb3 (a b c : bool) : bool :=\n  andb (andb a b) c.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. auto. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. auto. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. auto. Qed.\nExample test_andb34: (andb3 true true false) = false.\nProof. auto. Qed.\n\nCheck true.\nCheck (negb true).\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 compute 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_oddb: oddb 10 = false.\nProof. auto. Qed.\nExample test_evenb: evenb 10 = true.\nProof. reflexivity. Qed.\n\nModule Playground2.\n  Fixpoint plus (a b : nat) : nat :=\n    match a with\n      | O => b\n      | S n' => S (plus n' b)\n    end.\n\n  Eval compute 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  Example test_mult1: (mult 3 3) = 9.\n  Proof. simpl. reflexivity. Qed.\n\n  Fixpoint minus (n m : nat) : nat :=\n    match n, m with\n      | O, _ => O\n      | _, O => n\n      | S n', S m' => minus n' m'\n    end.\n  Eval compute in minus 7 8.\nEnd Playground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n    | O => base\n    | S n' => mult base (exp base n')\n  end.\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n    | O => S O\n    | S n' => fact n' * n\n  end.\n\nExample fact_five: fact 4 = 24.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y) \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x - y\" := (minus x y) \n                       (at level 50, left associativity) \n                       : nat_scope.\nNotation \"x × y\" := (mult x y) \n                       (at level 40, left associativity) \n                       : nat_scope.\n\nCheck ((0 + 1) + 1).\n\nFixpoint beq_nat ( n m : nat ) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | S _ => 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\nEval compute in beq_nat 4 5.\nEval compute in beq_nat 5 4.\nEval compute in beq_nat 5 5.\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\n\nEval compute in ble_nat 4 5.\nEval compute in ble_nat 5 4.\nEval compute in ble_nat 5 5.\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 (negb (beq_nat n m)) (ble_nat n m).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. reflexivity. Qed.\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_n_O : forall n : nat, n + O = n.\nProof.\n  intros n.\n  induction n.\n\n  reflexivity.\n\n  simpl.\n  rewrite IHn.\n  reflexivity.\nQed.\n\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_0_l : forall n:nat, 0 × n = 0.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m -> \n  n + n = m + m.\nProof.\n  intros n m 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. 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. eapply plus_O_n.\nQed.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\n  intros n m H.\n  rewrite H.\n  simpl. reflexivity.\nQed.\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\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  induction n as [  | n' ].\n\n  reflexivity.\n\n  simpl. reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  induction b.\n\n  reflexivity.\n\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  induction n.\n\n  reflexivity.\n\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. rewrite H.\n  reflexivity.\nQed.\n\nLemma andb_true: forall b, andb true b = b.\nProof.\n  induction b.\n\n  reflexivity.\n\n  reflexivity.\nQed.\n\nLemma orb_true : forall b, orb true b = true.\nProof.\n   induction b.\n\n   reflexivity.\n\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   induction b.\n\n   simpl.\n   intros H.\n   rewrite H; reflexivity.\n\n   simpl. intros H. assumption.\nQed.\n\n\nInductive bin :=\n| Ob : bin (* zero *)\n| Db : bin -> bin (* double *)\n| Tb : bin -> bin. (*double + one *)\n \n(*\nzero = Ob\none = Tb Ob\ntwo = Db Tb Ob\nthree = Tb Tb Ob \nfour = Db Db Tb Ob\nfive = Tb Db Tb Ob\nsix = Db three \nseven = Tb three \n *)\n\nFixpoint incr (b : bin) : bin :=\n  match b with\n    | Ob => Tb Ob\n    | Db n' => Tb n'\n    | Tb n' => Db (incr n')\n  end.\n\nEval compute in incr (Db (Tb Ob)).\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | Ob => O\n    | Db n' => 2 * bin_to_nat n'\n    | Tb n' => S (2 * bin_to_nat n')\n  end.\n\nEval compute in bin_to_nat (Tb (Tb Ob)).\n\n\n\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7540983315705304}}
{"text": "Module Logic.\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Tactics.\n\n\nCheck (3 = 3) : Prop.\nCheck (forall n m : nat, n + m = m + n) : Prop.\nCheck (2 = 2) : Prop.\nCheck (3 = 2) : Prop.\nCheck (forall n : nat, n = 2) : Prop.\n\nTheorem plus_2_2_is_4 : 2 + 2 = 4.\nProof. reflexivity. Qed.\n\nDefinition plus_claim : Prop := 2 + 2 = 4.\nCheck plus_claim : Prop.\n\nTheorem plus_claim_is_true : plus_claim.\nProof. reflexivity. Qed.\n\n\nDefinition is_three (n : nat) : Prop := n = 3.\nCheck is_three : nat -> Prop.\n\n\nDefinition injective {A B} (f : A -> B) := forall x y : A, (f x = f y) -> (x = y).\nLemma succ_inj : injective S.\nProof.\n  intros n m H. \n  assert (G : forall n, pred (S n) = n). {\n    reflexivity.\n  }\n  rewrite <- (G n).\n  rewrite -> H.\n  simpl.\n  reflexivity.\n(*\n  injection H as H1. \n  apply H1.\n*)\nQed.\n\n(* eq is (=) *)\nCheck @eq : forall A : Type, A -> A -> Prop.\n\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 * 2 = 4 *) reflexivity.\nQed.\n\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA 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  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\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.\n\nTheorem add_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros n.\n  induction n as [| n' H ].\n  - simpl.\n    intros m.\n    simpl.\n    rewrite -> add_0_r_firsttry.\n    reflexivity.\n  - simpl.\n    intros m.\n    rewrite <- plus_n_Sm.\n    simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nExample and_exercise : forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  split.\n  - destruct n eqn:E.\n    + reflexivity.\n    + simpl in H.\n      discriminate H.\n  - destruct m eqn:E.\n    + reflexivity.\n    + rewrite -> add_comm in H.\n      simpl in H.\n      discriminate 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\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  intros n m H.\n  apply and_exercise in H.\n  destruct H as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop, P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.\nQed.\n\nLemma proj2 : forall P Q : Prop, P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ.\nQed.\n\nTheorem and_commut : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP. \nQed.\n\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(* /\\ notation for : *)\nCheck and : Prop -> Prop -> Prop.\n\n\n\n\nLemma factor_is_O:\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\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 factor_is_O':\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  destruct H as [ Hn | Hm ] eqn:E.\n  - (* Here, n = 0 *)\n    rewrite Hn. reflexivity.\n  - (* Here, m = 0 *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma or_intro_r : forall A B : Prop, B -> A \\/ B.\nProof.\n  intros A B HB.\n  right.\n  apply HB.\nQed.\n\nLemma 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 : Prop -> Prop.\n\nTheorem tst: not (2 + 2 = 5).\nProof.\n  intros H.\n  simpl in H.\n  discriminate H.\nQed.\n\nTheorem tst': not (2 + 2 = 4).\nProof.\n  intros H.\n  simpl in H.\n  (* discriminate H. *)\nAbort.\n\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop), 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 notP Q p.\n  destruct (notP p) eqn:E.\nQed.\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate contra.\nQed.\n\nTheorem not_False : ~ 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]. \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. \n  apply G. \n  apply 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 negQ p.\n  apply H in p.\n  apply negQ in p.\n  apply p.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P.\n  unfold not.\n  intros [ HP HnP ].\n  apply HnP in HP.\n  destruct 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  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H.\n    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. (* note implicit destruct b here *)\n  - (* b = true *)\n    unfold not in H.\n    exfalso. (* <=== replaces target with False *)\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\n(* Search (?X : True). *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n\nDefinition disc_fn (n: nat) : Prop :=\n  match n with\n  | O => True\n  | S _ => False\n  end.\n\nTheorem disc : forall n, ~ (O = S n).\nProof.\n  intros n H1.\n  assert (H2 : disc_fn O). { simpl. apply I. }\n  rewrite H1 in H2. simpl in H2. apply H2.\nQed.\n\n\n\n\n\n\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\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. \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  - (* <- *)\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  intros P Q R.\n  split.\n  - intros H.\n    destruct H as [ HP | [HQ HR] ] eqn:E.\n    + split.\n      * left. apply HP.\n      * left. apply HP.\n    + split.\n      * right. apply HQ.\n      * right. apply HR.\n  - intros [HPQ HPR].\n    destruct HPQ as [HP | HQ] eqn:E.\n    + left. apply HP.\n    + destruct HPR as [HP' | HR] eqn:E1.\n      * left. apply HP'.\n      * right.\n        split.\n        apply HQ.\n        apply HR.\nQed.\n\n\n\nFrom Coq Require Import Setoids.Setoid.\n\nTheorem mult_is_O : forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros [| n' ] [| m' ] H.\n  - left. reflexivity.\n  - left. reflexivity.\n  - right. reflexivity.\n  - simpl in H.\n    discriminate H.\nQed.\n\nLemma mul_eq_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_is_O.\n  - apply factor_is_O.\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\n\nLemma mul_eq_0_ternary :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mul_eq_0. rewrite mul_eq_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n\nFixpoint double (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\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.\nDefinition odd (n : nat) := negb (even n).\n\n(* Definition div2 (n: nat) (p: even n = true) : nat. *)\n\n\n\nDefinition Even x := exists n : nat, x = double n.\n\nLemma four_is_even : Even 4.\nProof.\n  unfold Even. \n  exists 2. \n  reflexivity.\nQed.\n\nTheorem tst_exists: forall (n: nat), even n = true -> exists (m : nat), double m = n.\nProof.\n  intros n H.\n\nAbort.\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]. (* 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) -> ~ (exists x, ~ P x).\nProof.\n  intros X P H.\n  unfold not.\n  intros [x Px].\n  apply Px.\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 [Px | Qx]].\n    + left. exists x. apply Px.\n    + right. exists x. apply Qx.\n  - intros [ [x Px] | [x Qx] ].\n    + exists x. left. apply Px.\n    + exists x. right. apply Qx.\nQed.\n\n\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | nil      => False\n  | cons h t => h = x \\/ In x t\n  end.\n\nDefinition tst_list : list nat := cons 1 (cons 2 (cons 3 (cons 4 (cons 5 nil)))).\n\nExample In_example_1 : @In nat 4 tst_list.\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\n\nExample In_example_2 :\n  forall n, In n (cons 2 (cons 4 nil)) ->\n  exists n', n = 2 * n'.\nProof.\n  intros n H.\n  simpl in H.\n  destruct H as [H'2 | [H'4 | H'n]].\n  - exists 1.\n    rewrite <- H'2.\n    reflexivity.\n  - exists 2.\n    rewrite <- H'4.\n    reflexivity.\n  - destruct H'n.\nQed.\n\nFixpoint map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  match l with\n  | nil      => nil\n  | cons h t => cons (f h) (map f t)\n  end.\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n         In x l ->\n         In (f x) (map f l).\nProof.\n  intros A B f l x H.\n  induction l as [| hl tl Hl ].\n  - simpl in H.\n    simpl.\n    apply H.\n  - simpl in H. \n    simpl.\n    destruct H as [H'l | H'r].\n    + rewrite -> H'l.\n      left.\n      reflexivity.\n    + right.\n      apply Hl.\n      apply H'r.\nQed.\n\nTheorem In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n         In y (map f l) <->\n         exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. \n  split.\n  - induction l as [| hl tl Hl ].\n    + simpl.\n      intros F.\n      destruct F.\n    + simpl.\n      intros [H'l | H'r].\n      * exists hl.\n        split.\n        -- apply H'l.\n        -- left. reflexivity.\n      * destruct (Hl H'r) as [x [Hfxy HInxtl]].\n        -- exists x.\n           split.\n            ++ apply Hfxy.\n            ++ right. apply HInxtl.\n  - intros [x [ Hfxy Hinxl ]].\n    induction l as [| hl tl Hl ].\n    + simpl.\n      simpl in Hinxl.\n      apply Hinxl.\n    + simpl.\n      simpl in Hinxl.\n      destruct Hinxl as [Hhlx | Hinxtl].\n      * rewrite <- Hhlx in Hfxy.\n        left. apply Hfxy.\n      * right.\n        apply Hl.\n        apply Hinxtl.\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.\n  induction l as [| hl tl Hl ].\n  - simpl.\n    split.\n    + intros H. right. apply H.\n    + intros [FH | H]. \n      * destruct FH.\n      * apply H.\n  - simpl.\n    intros l' a.\n    rewrite -> (Hl l' a).\n    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  | cons h t => P h /\\ All P t\n  end.\n\nTheorem All_In : forall (T : Type) (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l.\n  induction l as [| hl tl Hl ].\n  - simpl.\n    split.\n    + intros H. apply I.\n    + intros H x FH. exfalso. apply FH.\n  - simpl.\n    split.\n    + intros H.\n      split.\n      * apply H. left. reflexivity.\n      * apply Hl. intros x H'. apply (H x). right. apply H'.\n    + intros [Hphl Hallptl] x H.\n      destruct Hl as [Hll Hlr].\n      destruct H as [Hl | Hr].\n      * rewrite <- Hl. apply Hphl.\n      * apply Hlr. apply Hallptl. apply Hr.\nQed.\n\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n => if odd n then Podd n else Peven n.\n\n\nTheorem combine_odd_even_intro :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    (odd n = true -> Podd n) ->\n    (odd n = false -> Peven n) ->\n    combine_odd_even Podd Peven n.\nProof.\n  intros Podd Peven n H1 H2.\n  destruct (odd n) eqn:E.\n  - unfold combine_odd_even.\n    rewrite -> E.\n    apply H1.\n    reflexivity.\n  - unfold combine_odd_even.\n    rewrite -> E.\n    apply H2.\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.\n  unfold combine_odd_even.\n  intros H G.\n  rewrite -> G in H.\n  simpl 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    odd n = false ->\n    Peven n.\nProof.\n  intros Podd Peven n.\n  unfold combine_odd_even.\n  intros H G.\n  rewrite -> G in H.\n  simpl in H.\n  apply H.\nQed.\n\n\n\nTheorem in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> nil.\nProof.\n  intros A x l H. unfold not. intro Hl.\n  rewrite Hl in H.\n  simpl in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> nil.\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 <> nil.\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\n\nTheorem mul_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n.\n  induction n as [| n' H].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\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 mul_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\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 x.\n  apply add_comm.\nQed.\n\nPrint Assumptions function_equality_ex2. \n\n\n\nFixpoint rev {X} (l : list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => rev t ++ cons h nil\n  end.\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => rev_append t (cons h l2)\n  end.\nDefinition tr_rev {X} (l : list X) : list X := rev_append l nil.\n\n\nLemma list_plus_nil : forall (X : Type) (l : list X),\n  (l ++ nil = l)%list.\nProof.\n  intros X l.\n  induction l as [| hl tl Hl ].\n  - reflexivity.\n  - simpl.\n    rewrite -> Hl.\n    reflexivity.\nQed.\n\nLemma rev_append_t : forall (X : Type) (l1 l2 l3 : list X), \n  ((@rev_append X l1 l2) ++ l3 = @rev_append X l1 (l2 ++ l3))%list.\nProof.\n  intros X l1 l2 l3.\n  induction l3 as [| hl tl Hl ].\n  - simpl.\n    rewrite -> list_plus_nil.\n    rewrite -> list_plus_nil.\n    reflexivity.\n  - simpl.\nAbort.\n\nLemma rev_append_t1 : forall (X : Type) (l1 l2 : list X), \n  (rev_append l1 nil ++ l2 = rev_append l1 l2)%list.\nProof.\n  intros X l1 l2.\n  induction l1 as [| hl tl Hl ].\n  - reflexivity.\n  - Abort.\n\nLemma app_assoc : forall (X : Type) (l1 l2 l3 : list X),\n  ((l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3))%list.\nProof.\n  induction l1 as [| hl tl Hl ].\n  - reflexivity.\n  - simpl.\n    intros l2 l3.\n    rewrite <- Hl.\n    reflexivity.\nQed.\n    \nLemma rev_append_t3 : forall (X : Type) (l1 l2 : list X), \n  (rev_append l1 l2 = (rev_append l1 nil) ++ l2)%list.\nProof.\n  intros X l1.\n  induction l1 as [| hl tl Hl ].\n  - reflexivity.\n  - simpl.\n    intros l2.\n    rewrite -> Hl.\n    rewrite -> (Hl (cons hl nil)).\n    rewrite -> app_assoc.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem 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 [| hl tl Hl ].\n  - unfold tr_rev.\n    reflexivity.\n  - unfold tr_rev.\n    simpl.\n    rewrite <- Hl.\n    unfold tr_rev.\n    rewrite -> rev_append_t3.\n    reflexivity.\nQed.\n\n\n\n\n\n\n\n\nExample even_42_bool : even 42 = true.\nProof. reflexivity. Qed.\n\nExample even_42_prop : Even 42.\nProof. unfold Even. exists 21. reflexivity. Qed.\n\nLemma even_double : forall k, even (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\nLemma even_S : forall n, even (S n) = negb (even n).\nProof.\n  intros n.\n  induction n as [| n' Hn ].\n  - reflexivity.\n  - rewrite -> Hn.\n    simpl.\n    destruct (even n').\n    + reflexivity.\n    + reflexivity.\nQed.\n\nLemma even_double_conv : forall n, exists k,\n  n = if even n then double k else S (double k).\nProof.\n  intros n.\n  induction n as [| n' Hn ].\n  - simpl.\n    exists O.\n    reflexivity.\n  - rewrite -> even_S.\n    destruct Hn as [k Hn'].\n    destruct (even n').\n    + simpl.\n      exists k.\n      rewrite -> Hn'.\n      reflexivity.\n    + simpl.\n      rewrite -> Hn'.\n      exists (S k).\n      reflexivity.\nQed.\n\nLemma even_double_true : forall n, even (double n) = true.\nProof.\n  intros n.\n  induction n as [| n' H ].\n  - reflexivity.\n  - simpl.\n    apply H.\nQed.\n\nTheorem even_bool_prop : forall n,\n  even n = true <-> Even n.\nProof.\n  intros n.\n  split.\n  - intros H.\n    unfold Even.\n    destruct (even_double_conv n) as [k Hd].\n    rewrite -> H in Hd.\n    exists k.\n    apply Hd.\n  - unfold Even.\n    intros [k H].\n    rewrite -> H.\n    apply even_double_true.\nQed.\n\n\n\nExample even_1000 : Even 1000.\nProof. unfold Even. exists 500. reflexivity. Qed.\n\nExample even_1000' : even 1000 = true.\nProof. reflexivity. Qed.\n\nExample even_1000'' : Even 1000.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n\nTheorem andb_true_iff : forall (b1 b2 : bool),\n  andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2.\n  destruct b1 eqn:E1.\n  - destruct b2 eqn:E2.\n    + simpl. \n      split. \n      * intros H.\n        split.\n        -- reflexivity.\n        -- reflexivity.\n      * intros [H1 H2].\n        reflexivity.\n    + simpl.\n      split.\n      * intros H.\n        split.\n        -- reflexivity.\n        -- apply H.\n      * intros [H1 H2].\n        apply H2.\n  - simpl.\n    split.\n    + intros H.\n      discriminate H.\n    + intros [H1 H2].\n      discriminate H1.\nQed.\n\nTheorem orb_true_iff : forall (b1 b2 : bool),\n  orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2.\n  destruct b1 eqn:E.\n  - simpl.\n    split.\n    + intros H. left. reflexivity.\n    + intros H. reflexivity.\n  - destruct b2.\n    + simpl.\n      split.\n      * intros H. right. reflexivity.\n      * intros H. reflexivity.\n    + simpl.\n      split.\n      * intros H. discriminate H.\n      * intros [H1|H2]. discriminate H1. discriminate H2.\nQed.\n\n\nFixpoint eqb (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | S i, S j => eqb i j\n  | _, _ => false\n  end.\nFixpoint leb (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | S i, S j => leb i j\n  | O, S _ => true\n  | _, _ => false\n  end.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n\nLemma eqb_refl : forall (n : nat), n =? n = true.\nProof.\n  intros n.\n  induction n as [| n' H ].\n  - reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\nTheorem eqb_true : forall n m,\n  n =? m = true -> n = m.\nProof.\n  intros n.\n  induction n as [| n' H].\n  - intros m.\n    destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + simpl.\n      intros G.\n      discriminate G.\n  - intros m.\n    destruct m as [| m'] eqn:E.\n    + simpl.\n      intros G.\n      discriminate G.\n    + simpl.\n      intros G.\n      apply f_equal.\n      apply H.\n      apply G.\nQed.\n\nTheorem eqb_neq : forall (x y : nat),\n  x =? y = false <-> x <> y.\nProof.\n  intros x y.\n  split.\n  - unfold not.\n    intros H G.\n    rewrite -> G in H.\n    simpl in H.\n    rewrite -> eqb_refl in H.\n    discriminate H.\n  - unfold not.\n    intros H.\n    destruct (x =? y) eqn:E.\n    + destruct (H (eqb_true x y E)) eqn:G.\n    + reflexivity.\nQed.\n\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  | (cons h1 t1), (cons h2 t2) => if eqb h1 h2 then eqb_list eqb t1 t2 else false\n  | _, _ => false\n  end.\n\nLemma eqb_list_refl : forall (A : Type) (eqb : A -> A -> bool) (l : list A),\n  (forall a, eqb a a = true) ->\n  eqb_list eqb l l = true.\nProof.\n  intros A eqb l HEq.\n  induction l as [| hl tl Hl ].\n  - reflexivity.\n  - simpl.\n    rewrite -> HEq.\n    apply Hl.\nQed.\n\n\nTheorem eqb_list_true_iff :\n  forall (A : Type) (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  split.\n  - generalize dependent l2.\n    induction l1 as [| hl tl Hl ].\n    + simpl.\n      destruct l2.\n      * intros _. reflexivity.\n      * intros F. discriminate F.\n    + intros l2 Heqlist.\n      simpl in Heqlist.\n      destruct l2 as [|hl2 tl2 ] eqn:E.\n      * discriminate Heqlist.\n      * destruct (eqb hl hl2) eqn:Ehla.\n        -- destruct (H hl hl2) as [H' _].\n           destruct (H' Ehla).\n           destruct (Hl tl2 Heqlist).\n           reflexivity.\n        -- discriminate Heqlist.\n  - intros HLEq.\n    rewrite -> HLEq.\n    apply eqb_list_refl.\n    intros a.\n    destruct (H a a) as [_ H'].\n    apply H'.\n    reflexivity.\nQed.\n\n\n\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil      => true\n  | cons h t => andb (test h) (forallb test t)\n  end.\n\nLemma andb_split : forall (a b : bool), andb a b = true -> a = true /\\ b = true.\nProof.\n  intros a b.\n  destruct a eqn:EA.\n  - destruct b eqn:EB.\n    + simpl. intros H. split. reflexivity. reflexivity.\n    + simpl. intros H. discriminate H.\n  - simpl. intros H. discriminate H.\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 X test l.\n  split.\n  - intros H.\n    induction l as [| hl tl Hl ].\n    + reflexivity.\n    + simpl. simpl in H.\n      destruct (andb_split (test hl) (forallb test tl) H) as [H1 H2].\n      split.\n      * apply H1.\n      * apply Hl. apply H2.\n  - intros H.\n    induction l as [| hl tl Hl ].\n    + reflexivity.\n    + simpl. simpl in H.\n      destruct H as [H1 H2].\n      rewrite -> (Hl H2).\n      rewrite -> H1.\n      reflexivity.\nQed.\n\n\n\n\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\n(*\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H.\n\n  assert (G: forall b, b = true \\/ ~ (b = true)). {\n    intros b.\n    destruct b.\n    - left. reflexivity.\n    - right. unfold not. intros H'. discriminate H'.\n  }\n\n  destruct (H (G true)).\n  \n  apply H.\n  apply G.\n*)\n\nDefinition excluded_middle := forall P : Prop, P \\/ ~P.\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 ExclMid X P.\n  intros H x.\n  unfold not in H.\n  destruct (ExclMid (P x)) as [HPx | HNPx].\n  - apply HPx.\n  - assert(E: (exists x : X, P x -> False)). {\n      exists x.\n      apply HNPx.\n    }\n    destruct (H E).\nQed.\n\n\n\n\n\n\n\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, ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q:Prop, (P -> Q) -> (~P \\/ Q).\n\n(* Coq'Art book by Bertot and Casteran (p. 123). *)\n(*\nTheorem th1 : excluded_middle <-> peirce.\nTheorem th2 : peirce <-> double_negation_elimination.\nTheorem th3 : double_negation_elimination <-> de_morgan_not_and_not.\nTheorem th4 : de_morgan_not_and_not <-> implies_to_or.\nTheorem th5 : implies_to_or <-> excluded_middle.\n*)\nEnd Logic.\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8872045847699185, "lm_q1q2_score": 0.7540983273374081}}
{"text": "Require Export NArith.\nRequire Export ZArith.\nOpen Scope N_scope.\n\nDefinition pos_log2 (p:positive) : N :=\nN.log2 (Npos p).\n\n(** Write a function that given any positive number p, returns a pair\n   of type (n, q) : N * positive such that p = 2^n * q\n\n*)\nCheck 33.\nCheck (33%nat).\n\nCheck (S (S (S (S 0)))).\n\n(* Open Scope nat_scope. *)\nUnset Printing Notations.\nCheck 4.\nSet Printing Notations.\nCheck (5*(5-4)*7).\n\n(* Open Scope Z_scope.\nPrint Scope Z_scope.\nCheck (Z.opp (Z.mul 3 (Z.sub (-5)(-8)))).\nCheck (plus 3%nat).\nCheck (fun a b c : Z => (b*b-4*a*c)%Z). \nCheck (fun f x => Z.abs_nat (f x x)). *)\n(* Check (fun x => x x). *)\n\nParameter max_int : N.\nDefinition min_int := 1-max_int.\nPrint min_int.\n\nSection binomial_def.\nVariables a b:Z.\nDefinition binomial z:Z := a*z + b. \nSection trinomial_def.\nVariable c : Z.\nDefinition trinomial z:Z := (binomial z)*z + c. \nEnd trinomial_def.\nEnd binomial_def.\n\nFixpoint decompose2 (p:positive) : N * positive :=\nmatch p with xH => (0,xH)\n           | xI q => (0, p)\n           | xO q => let d := decompose2 q in (fst d + 1, snd d)\nend.\n\nCompute decompose2 (88%positive).\nCompute decompose2 (1024%positive).\n\n(** binary exponentiation *)\n\nDefinition sqr_pos (p:positive) := (p * p)%positive.\n\nFixpoint binary_pow_aux (x:N)(a:N)(p:positive) : N :=\n match p with xH => a * x\n            | xO q  => binary_pow_aux (x * x) a q\n            | xI q  => binary_pow_aux (x * x)  (a * x ) q\n\nend.\n\nDefinition pow  (x:N) (n : N) :=\n  match n with 0 => 1\n             | Npos 1 => x\n             | Npos p => binary_pow_aux x x (Pos.pred p)\n end.\n\nCompute pow 2 5.\nCompute pow 2 10.\n\n\n\n(** Comparison with N.pow *)\n\nTime Compute 1 ^ 55556666.\n\nTime Compute pow 1 55556666.\n\nDefinition pow_test (x n:N) :=\n  N.eqb (pow x n) (N.pow x n).\n\nCompute pow_test 2  555.\n\n\nFixpoint exp2_pos  (p:positive) : positive :=\n(match p with 1 => 2\n           | p~0 => sqr_pos (exp2_pos p)\n           | p~1 => (sqr_pos (exp2_pos p))~0\n end)%positive.\n\n\nDefinition exp2 (n:N) : positive :=\nmatch n with N0 => xH\n           | Npos p =>  (exp2_pos p)\nend.\n\n\nCompute exp2 10.\n\nCompute exp2 7.\n\n\n\nCompute pos_log2 63%positive.\nCompute pos_log2 1023%positive.\n\n\nDefinition test_exp2 (p:positive) := N.eqb (Npos p)  (pos_log2 (exp2 (Npos p))).\nCompute test_exp2 45%positive.\n\n\n", "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/ch2_types_expressions/SRC/bin_nums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7540983189080832}}
{"text": "(* Intuitionistic logic is extended to classical logic\n   by assuming a classical axiom. There are different\n   possibilities for the choice of a classical axiom.\n   In this practical work we show the logical equivalence\n   of three different classical axioms. *)\n\n(* The following are three classical axioms *)\n\nDefinition excluded_middle := forall A:Prop, A \\/ ~A.\nDefinition peirce := forall A B:Prop, ((A -> B)-> A) -> A.\nDefinition double_negation := forall A:Prop, ~~A -> A.\n\n(* To show that these are equivalent,\n   we need to prove (at least) three implications.\n   As an example, the implication\n   excluded_middle implies peirce is given. *)\n\nLemma one : excluded_middle -> peirce.\nProof.\nunfold excluded_middle.\nunfold peirce.\nunfold not.\nintro EM.\nintro A.\nintro B.\nelim (EM A).\n\nintro x.\nintro y.\nassumption.\n\nintro x.\nintro y.\napply y.\nintro z.\nelimtype False.\napply x.\nassumption.\nQed.\n\n(* There is a new element in the syntax:\n   a universal quantification over propositions.\n   So in fact these formulas are second-order;\n   we come back to that later in the course. *)\n\n(* How to work with these universal quantifications ?\n   With \"intro\" and \"apply\". Explanation by example:\n\n   If the current goal is \"forall A:Prop, A -> A\",\n   then by doing \"intro A\" the new goal is A -> A\n   and a new hypothesis \"A:Prop\" appears.\n\n   If the current goal is \"C\" and there is a hypothesis\n   \"x: forall A:Prop, B -> A\"\n   then by \"apply x\" the current goal is transformed into \"B\".\n   The universally quantified A is instantiated by C.\n\n   Now suppose that the current goal is \"C\" and\n   there is a hypothesis \"x: forall A B:Prop, B -> A\".\n   Then \"apply x\" does not work because from the\n   current goal we can see how to instantiate A\n   (namely with C) but not how to instantiate B.\n   Therefore we should say \"apply x with something.\"\n   choosing something appropriately. *)\n\n(* exercise; you need the \"apply with\". *)\nLemma two : peirce -> double_negation.\nProof.\nunfold peirce.\nunfold double_negation.\nunfold not.\nintro PE.\nintro A.\nintro.\napply PE with False.\nintro.\nelimtype False.\napply H.\nassumption.\n\nQed.\n\n(* exercise *)\nLemma three : double_negation -> excluded_middle.\nProof.\nunfold double_negation.\nunfold excluded_middle.\nunfold not.\nintro DN.\nintro.\napply DN.\nintro.\napply H.\nright.\nintro.\napply H.\nleft.\nexact H0.\n\nQed.\n\n(* exercise *)\nLemma four : excluded_middle -> double_negation.\nProof.\nunfold excluded_middle.\nunfold double_negation.\nunfold not.\nintro EM.\nintro A.\nintro x.\nelim (EM A).\nintro.\nexact H.\n\nintro.\nelimtype False.\napply x.\nexact H.\n\nQed.\n\n(* exercise *)\nLemma everything_related :\n  excluded_middle -> forall A B : Prop , (A -> B) \\/ (B -> A).\nProof.\nunfold excluded_middle.\nunfold not.\nintro EM.\nintros A B.\nelim EM with (A := B).\nintro.\nleft.\nintro.\nassumption.\nintro.\nright.\nintro.\nelimtype False.\napply H.\nassumption.\nQed.\n\nLemma de_morgan :\n  excluded_middle -> forall A B : Prop , ~(~A/\\~B) -> A\\/B.\nProof.\nunfold excluded_middle.\nunfold not.\nintro EM.\nintro A.\nintro B.\nintro H.\nelim EM with (A := A).\nintro.\nleft.\nassumption.\nintro H0.\nelim EM with (A := B).\nintro.\nright.\nassumption.\nintro H1.\nelimtype False.\napply H.\nsplit.\nassumption.\nassumption.\nQed.\n\n(* exercise\n   note that this lemma is true intuitionistically *)\nLemma about_implication : forall A B : Prop , (~A \\/ B) -> (A -> B).\nProof.\nintro A.\nintro B.\nunfold not.\nintro.\nintro.\nelim H.\nintro.\nelimtype False.\napply H1.\nassumption.\nintro.\nassumption.\nQed.\n\n(* exercise\n   for the converse of the previous lemma we need a classical axiom *)\nLemma classical_implication :\n  excluded_middle -> forall A B : Prop , (A -> B) -> (~A \\/ B).\nProof.\nunfold excluded_middle.\nunfold not.\nintro EM.\nintros A B.\nintro x.\nelim EM with (A:=B).\nintro.\nright.\nassumption.\nintro.\n\nleft.\nelim EM with (A := B).\nintros.\napply H.\nassumption.\nintros.\napply H0.\napply x.\nassumption.\n\n\n\nQed.\n\n(* exercise *)\nLemma about_classical_implication :\n  excluded_middle -> forall A B : Prop , ~B \\/ (A ->B).\nProof.\nunfold excluded_middle.\nunfold not.\nintro EM.\nintros A B.\nelim EM with (A:=B).\nright.\nintro.\nelim EM with (A:=A).\nintro.\nassumption.\nintro.\nassumption.\nleft.\nassumption.\n\nQed.\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/pw03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7540087919818551}}
{"text": "Require Import Arith Lia Nat.\nFrom Undecidability.Synthetic Require Import DecidabilityFacts.\nFrom FOL.Tennenbaum Require Import SyntheticInType MoreDecidabilityFacts.\nNotation dec_eq_nat := Nat.eq_dec.\n\nDefinition iffT (x y : Type) := prod (x->y) (y->x).\n\nLemma lt_rect f :\n  (forall x, (forall y, y < x -> f y) -> f x) -> forall x, f x.\nProof.\n  intros H x. apply H.\n  induction x.\n  - intros; lia.\n  - intros y Hy. apply H.\n    intros z Hz. apply IHx. lia.\nDefined.\n\n\n(** * Division with Rest *)\n\nDefinition Euclid d x :\n  { q & { r &  x = q*d + r  /\\  (0 < d -> r < d)  }}.\nProof.\n  destruct d as [|d].\n  exists 0, x. repeat split; lia.\n  induction x as [|x IH].\n  - exists 0, 0. repeat split; lia.\n  - destruct IH as (q&r&[]).\n    specialize (dec_eq_nat d r) as [].\n    + exists (S q), 0. split; lia.\n    + exists q, (S r). split; lia.\nDefined.\n\n\n(* Div y x gives the number of times y can be substracted from x *)\nDefinition Div y x := projT1 (Euclid y x).\n(* Mod y x gives the remainder of x after division by y *)\nDefinition Mod y x := projT1 (projT2 (Euclid y x)).\n\n\n\nFact Factor y x :\n  x = (Div y x)*y + Mod y x.\nProof.\n  apply (projT2 (projT2 (Euclid _ _))).\nQed.\n\n\nFact Mod_bound y x :\n  0 < y -> Mod y x < y.\nProof.\n  apply (projT2 (projT2 (Euclid _ _))).\nQed.\n\n\n\nFact Mod_lt y x :\n  0 < y <= x -> Mod y x < x.\nProof.\n  intros [H ].\n  apply (Mod_bound _ x) in H. lia.\nQed.\n\n\nLemma Div_lt y x :\n  0 < y <= x -> 0 < Div y x.\nProof.\n  intros [H1 H2].\n  rewrite (Factor y x) in H2 at 1.\n  specialize ((Mod_bound y x) H1) as H3.\n  enough (Div y x <> 0) by lia.\n  intros E. rewrite E in *; cbn in *.\n  lia.\nQed.\n\n\n(** Uniqueness *)\n\nSection Uniqueness.\n  Variable m : nat.\n\n  Lemma Fac_unique a1 b1 a2 b2 : b1 < m -> b2 < m ->\n    a1*m + b1 = a2*m + b2 -> a1 = a2 /\\ b1 = b2.\n  Proof.\n    intros.\n    destruct (Nat.lt_trichotomy a1 a2) as [ |[]]; nia.\n  Qed.\n\n  Theorem unique x a b : b < m ->\n    x = a*m + b <-> Div m x = a /\\ Mod m x = b.\n  Proof.\n    split.\n    - rewrite (Factor m x) at 1. intros.\n      specialize (Mod_bound m x) as ?.\n      apply Fac_unique; lia.\n    - intros [<- <-]. apply Factor.\n  Qed.\n\n  Corollary Fac_eq a b : b < m ->\n      Div m (a*m + b) = a /\\ Mod m (a*m + b) = b.\n  Proof. intros. now apply (unique _). Qed.\nEnd Uniqueness.\n\n\nLemma lt_nat_equiv x y :\n  x < y <-> exists k, S x + k = y.\nProof.\n  split.\n  induction y in x |-*. lia.\n  destruct x; intros. exists y; lia.\n  destruct (IHy x) as [k <-]. lia.\n  exists k; lia.\n  intros []. lia.\nQed.\n\nLemma Mod_divides y x :\n  iffT (Mod y x = 0) ({ k & x = k*y }).\nProof.\n  split.\n  - intros H. exists (Div 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\nLemma Mod_le x N :\n  N > 0 -> Mod x N = 0 -> x <= N.\nProof.\n  intros ? [k ?]%Mod_divides. assert (k > 0) by lia. nia.\nQed.\n\nFact Mod_id m x : x < m -> Mod m x = x.\nProof.\n  intros H.\n  apply (Fac_eq m 0 x H).\nQed.\n\n(** Homomorphism property of the modulus. *)\n\nSection Homomorphism.\n  Variable m : nat.\n  Local Notation \"'M' x\" := (Mod m x) (at level 10).\n  Local Notation \"'D' x\" := (Div m x) (at level 10).\n\n\n  Lemma Mod_plus_multiple d r :\n    M (d*m + r) = M r.\n  Proof.\n    assert (m = 0 \\/ 0 < m) as [->|] by lia; cbn. lia.\n    eapply (Fac_unique m _ _ (d + D r)).\n    all: try now apply Mod_bound.\n    rewrite <-Factor.\n    rewrite (Factor m r) at 1. lia.\n  Qed.\n\n  Theorem Mod_add_hom x y:\n    M (x + y) = M (M x + M y).\n  Proof.\n    symmetry.\n    rewrite <-(Mod_plus_multiple (D x + D y)).\n    rewrite (Factor m x), (Factor m y) at 3.\n    f_equal. lia.\n  Qed.\n\n  Lemma Mod_mult_hom_l x y :\n    M (x * y) = M (M x * y).\n  Proof.\n    symmetry.\n    erewrite <-(Mod_plus_multiple (D x * y)).\n    rewrite (Factor m x) at 3.\n    f_equal. lia.\n  Qed.\n\n  Theorem Mod_mult_hom x y:\n    M (x * y) = M (M x * M y).\n  Proof.\n    symmetry.\n    erewrite <-(Mod_plus_multiple (D x * D y * m + D x * M y + D y * M x )).\n    rewrite (Factor m x), (Factor m y) at 5.\n    f_equal. lia.\n  Qed.\n\n  Fact Mod0_is_0 : M 0 = 0.\n  Proof. destruct m; reflexivity. Qed.\n\n  Corollary ModMod_is_Mod x :\n    M (M x) = M x.\n  Proof.\n    change (M x) with (0 + M x) at 1.\n    now rewrite <-Mod0_is_0, <-Mod_add_hom.\n  Qed.\nEnd Homomorphism.\n\n\n\n(** * Prime Numbers *)\n\nSection PrimeDec.\n\n  (** Irreducible Numbers *)\n  Definition irred' p := p > 1 /\\ forall n, Mod n p = 0 -> (n = 1) \\/ (n = p).\n\n  Lemma irred_bounded p : (p > 1 /\\ forall n, n < p -> Mod n p = 0 -> (n = 1) \\/ (n = p) ) <-> irred' p.\n  Proof.\n    split.\n    - intros [? H]. split. assumption.\n      intros. enough (n < p \\/ n = p) as [ | ->].\n      apply H. all : auto.\n      enough (n <= p) by lia.\n      apply Mod_le; lia.\n    - unfold irred'. intuition.\n  Qed.\n\n\n  Definition irred p := p > 1 /\\ forall n, n < p -> Mod n p = 0 -> n = 1.\n\n  Goal forall p, irred p <-> irred' p.\n  Proof.\n    unfold irred, irred'.\n    setoid_rewrite <-irred_bounded.\n    intuition. destruct (H1 _ H H2).\n    auto. lia.\n  Qed.\n\n  (** It is decidable whether a number is irreducible. *)\n  Lemma Dec_sigT_irred :\n    Dec_sigT (irred).\n  Proof.\n    intros n. unfold irred. apply Dec.and_dec. apply lt_dec.\n    apply dec_lt_bounded_forall.\n    intros x. apply impl_dec; apply dec_eq_nat.\n  Defined.\n\n  Lemma dec_help_1 P Q : dec P -> dec Q -> ~(P /\\ Q) -> ~P \\/ ~Q.\n  Proof.\n    intros H1 H2 H3.\n    destruct H1, H2; tauto.\n  Qed.\n\n  Lemma dec_help_2 P Q : dec P -> dec Q -> ~(P -> Q) -> P /\\ ~Q.\n  Proof.\n    intros H1 H2 H3.\n    destruct H1, H2; tauto.\n  Qed.\n\n  Lemma irred1 N :\n    irred N + (N > 1 -> {x & x < N /\\ Mod x N = 0 /\\ x <> 1}).\n  Proof.\n    destruct (Dec_sigT_irred N) as [|H]; auto.\n    right. intros HN. apply Witnessing_nat.\n    intros x. repeat apply and_dec; try apply not_dec; try eapply dec_eq_nat. apply lt_dec.\n    unfold irred in *.\n    apply dec_help_1 in H.\n    - destruct H. tauto.\n      apply neg_lt_bounded_forall in H.\n      destruct H as [n []].\n      exists n. split. tauto.\n      apply dec_help_2 in H0; eauto; try eapply dec_eq_nat. intros x.\n      apply impl_dec; apply dec_eq_nat.\n    - apply lt_dec.\n    - apply dec_lt_bounded_forall.\n      intros n. apply impl_dec; eapply dec_eq_nat.\n  Qed.\n\n  Lemma dec_irred_factor N :\n    irred N + (N > 1 -> {x & {y & 1 < x < N  /\\ x*y = N }} ).\n  Proof.\n    destruct (irred1 N) as [| H]; auto.\n    right. intros [x Hx]%H.\n    destruct Hx as (?&[y Hy]%Mod_divides&?).\n    exists x, y. nia.\n  Qed.\n\n  (** Every number > 1 has an irreducible factor. *)\n\n  Lemma irred_factor n :\n    n > 1 -> { k | irred k /\\ Mod k n = 0}.\n  Proof.\n    pattern n. apply lt_rect. intros N IH HN.\n    destruct (dec_irred_factor N) as [|H].\n    - exists N. split. auto.\n      apply Mod_divides. exists 1; lia.\n    - destruct (H HN) as [x [y ((H1&H2)&H3) ]].\n      assert (x > 1) by nia.\n      destruct (IH x H2 H1) as [k Hk].\n      exists k. split. tauto.\n      rewrite <-H3. rewrite Mod_mult_hom, (proj2 Hk).\n      apply Mod0_is_0.\n  Qed.\n\n  Lemma irred_Mod_eq m x :\n    irred x -> m > 1 -> Mod m x = 0 -> m = x.\n  Proof.\n    intros Hx Hm Eq.\n    enough (m < x \\/ m = x) as []; auto.\n    apply Hx in H; intuition lia.\n    apply Mod_le in Eq; try lia.\n    unfold irred in *; lia.\n  Qed.\n\n  Lemma irred_integral_domain n a b :\n    irred n -> Mod n (a*b) = 0 -> Mod n a = 0 \\/ Mod n b = 0.\n  Proof.\n    intros irred_n.\n    induction a as [a Hrec] using lt_rect.\n    intros Eq.\n    assert (n <= a \\/ a < n) as [] by lia.\n    - rewrite <-ModMod_is_Mod.\n      apply Hrec. apply Mod_lt. split.\n      enough (n > 1) by lia. apply irred_n.\n      lia. now rewrite <-Mod_mult_hom_l.\n    - assert (a = 0 \\/ a > 0) as [-> |] by lia.\n      rewrite Mod0_is_0; auto.\n      edestruct (Hrec (Mod a n)).\n      now apply Mod_bound.\n      3 : right; apply H1.\n      cut (Mod n (n * b) = 0).\n      rewrite (Factor a n) at 2.\n      rewrite Nat.mul_add_distr_r.\n      rewrite Mod_add_hom, <- Nat.mul_assoc, Mod_mult_hom.\n      now rewrite Eq, Nat.mul_0_r, <- Mod_add_hom.\n      rewrite Nat.mul_comm, <-(Nat.add_0_r (_ * _)).\n      now rewrite Mod_plus_multiple, Mod0_is_0.\n      enough (Mod a n = 0) as E.\n      apply irred_n in E.\n      rewrite E, Nat.mul_1_l in Eq. all: auto.\n      rewrite Mod_id in H1. auto.\n      apply Mod_lt. lia.\n  Qed.\n\n\n  Definition prime p := p > 1 /\\\n    forall a b, Mod p (a*b) = 0 -> Mod p a = 0 \\/ Mod p b = 0.\n\n  (** Prime and irreducible are equivalent *)\n\n  Lemma prime_irred_equiv p : irred p <-> prime p.\n  Proof.\n    split; intros [? H]; split; auto.\n    - intros a b Hab. apply irred_integral_domain.\n      unfold irred; auto. assumption.\n    - intros n H1 H2.\n      destruct (fst (Mod_divides _ _) H2) as [k Hk].\n      destruct (H k n).\n      + rewrite <-Hk. apply Mod_divides. exists 1. now cbn.\n      + destruct (fst (Mod_divides _ _) H3) as [? ->].\n        assert (p*(x*n) = p*1) as ?%Nat.mul_cancel_l by lia.\n        apply Nat.mul_eq_1 in H4. all: lia.\n      + apply Mod_le in H3. all: lia.\n  Qed.\n\n\n  Corollary Dec_sigT_prime :\n    Dec_sigT (prime).\n  Proof.\n    refine (Dec_sigT_transport _ _ Dec_sigT_irred prime_irred_equiv).\n  Qed.\n\nEnd PrimeDec.\n\n\n\n\nSection PrimeInf.\n  Fixpoint faktorial n :=\n    match n with\n    | 0 => 1\n    | S x => (faktorial x)*n\n    end.\n\n  Notation \"x !\" := (faktorial x) (at level 2).\n\n  Fact fac1 : forall n, 0 < n!.\n  Proof. induction n; cbn; lia. Qed.\n\n  Fact fac2 : forall n, 0 < n -> Mod n (n !) = 0.\n  Proof.\n    intros n H. destruct n; try lia.\n    apply Mod_divides. exists (n !).\n    reflexivity.\n  Qed.\n\n  Lemma fac3 : forall x y, 0 < y <= x -> Mod y (x!) = 0.\n  Proof.\n    intros x y H.\n    induction x in y, H |-*.\n    - lia.\n    - assert (y = S x \\/ y <= x) as [<-|] by lia; cbn.\n      now apply fac2.\n      rewrite Mod_mult_hom, IHx.\n      apply Mod0_is_0. lia.\n  Qed.\n\n  (** There are infinitely many irreducible numbers. *)\n  Lemma infty_irred : forall N, { p & N < p /\\ irred p}.\n  Proof.\n    intros n.\n    destruct (irred_factor (n! + 1)) as [k [[] ]].\n    specialize(fac1 n). lia.\n    exists k. split.\n    - rewrite Mod_add_hom in *.\n      assert (n < k <-> ~ (k <= n)) as G by lia.\n      apply G. intros ?.\n      enough (1 = 0) by lia.\n      rewrite <-H1 at 2.\n      rewrite fac3. 2: lia.\n      cbn; rewrite ModMod_is_Mod.\n      symmetry. refine ( proj2 (Fac_eq _ 0 _ _)); lia.\n    - unfold irred. tauto.\n  Defined.\n\n  (** An injective function producing infinitely many irreducible numbers. *)\n  Fixpoint Irred n := match n with\n                      | 0 => projT1 (infty_irred 0)\n                      | S x => projT1 (infty_irred (Irred x))\n                      end.\n\n\n  Lemma mono_inj f :\n    (forall x,  f x < f (S x)) -> inj f.\n  Proof.\n    intros Hf.\n    assert (H : forall n x, x < n -> f x < f n).\n    induction n.\n    - lia.\n    - intros x.\n      assert (x < S n <-> x < n \\/ x = n) as -> by lia.\n      intros [| ->].\n      + specialize (Hf n). specialize (IHn _ H). lia.\n      + apply Hf.\n    - intros x y eq.\n      destruct (dec_eq_nat x y); auto.\n      assert (x < y \\/ y < x) as [G|G] by lia.\n      all: specialize (H _ _ G); lia.\n  Qed.\n\n\n  Lemma inj_Irred : inj Irred.\n  Proof.\n    apply mono_inj. intros x.\n    apply (proj1 (projT2 (infty_irred (Irred x)))).\n  Qed.\n\n  Lemma irred_Irred x : irred (Irred x).\n  Proof.\n    destruct x; apply (projT2 (infty_irred _)).\n  Qed.\n\nEnd PrimeInf.\n", "meta": {"author": "uds-psl", "repo": "coq-library-fol", "sha": "0fe6a74eebe8b567d8196e0f62608ac3c55753f3", "save_path": "github-repos/coq/uds-psl-coq-library-fol", "path": "github-repos/coq/uds-psl-coq-library-fol/coq-library-fol-0fe6a74eebe8b567d8196e0f62608ac3c55753f3/theories/Tennenbaum/NumberUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675450763201}}
{"text": "Require Import Omega.\nRequire Import Setoid.\n\n\n(*\n=============================================================================\n****************** SECTION 1: PRELIMINARIES *********************************\n=============================================================================\n*)\n\n(* \n * This file contains recurrently useful results and definitions\n * that are used throughout the subsequent files. \n *)\n\n\n(* ****** LEMMAS ABOUT NAT  ****** *)\n\nLemma le_S_n_m : forall n m : nat, n <= m <-> S n <= S m.\nProof. intros. omega. Qed.\n\nLemma not_lt: forall n m : nat, n <= m <-> ~ m < n.\nProof. intros. omega. Qed.\n\nLemma not_le: forall n m : nat, ~ n <= m <-> m < n.\nProof. intros. omega. Qed.\n\nLemma le_lt_S: forall n m : nat, S n <= m <-> n < m.\nProof. intros. omega. Qed.\n\nLemma lt_S_le: forall n m : nat, n <= m <-> n < S m.\nProof. intros. omega. Qed.\n\n\n(* ****** LEMMAS ABOUT REPEATED APPLICATION ****** *)\n\nFixpoint repeat (f: nat -> nat) (rep n : nat) : nat :=\n  match rep with\n  | 0 => n\n  | S rep' => f (repeat f rep' n)\n  end.\n\nTheorem repeat_S_comm :\n  forall f k n, repeat f (S k) n = repeat f k (f n).\nProof.\n  induction k; [trivial|].\n  intro. simpl in *. rewrite IHk. trivial.\nQed.\n\nTheorem repeat_plus :\n  forall f k l n, repeat f (k + l) n =\n                  repeat f k (repeat f l n).\nProof.\n  induction k; [trivial|].\n  simpl; intros; rewrite IHk; 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/prelims.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675407918866}}
{"text": "From Equations Require Import Equations.\nRequire Import List ZArith Lia.\nImport ListNotations.\n\nEquations neg (b : bool) : bool :=\nneg true := false;\nneg false := true.\nCompute neg true.   (* false : bool *)\nCompute neg false.  (* true : bool *)\n\nEquations bin (n : nat) : list bool by wf n lt :=\nbin O := List.nil;\nbin n := (if (Nat.eqb (Nat.modulo n 2) 0) then false else true)  :: bin (Nat.div n 2).\nNext Obligation.\n  change (S n0 / 2 < S n0).\n  apply Nat.div_lt; lia.\nQed.\nCompute bin 11.\n(*\n= [true; true; false; true]\n     : list bool\n*)\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/eqns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7538675386496698}}
{"text": "Lemma not_none_is_some : forall {A:Type} (o: option A),\n  o <> None <-> exists x:A, o = Some x.\nProof.\n  intros A o. split. elim o. intros a H. exists a. reflexivity.\n  intro H. apply False_ind. apply H. reflexivity.\n  intro H. elim H. intros x Hx. rewrite Hx. intros. discriminate.\nQed.\n\nLemma none_or_not_none : forall {A:Type} (o:option A),\n  o = None \\/ o <> None.\nProof.\n  intros A o. elim o. intro a. right. intro H. discriminate.\n  left. 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/lib/option.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7538675335723609}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat Even.\n\nLocal Open Scope nat_scope.\n\nImplicit Type n : nat.\n\n\n\nNotation div2 := Nat.div2.\n\n\n\nLemma ind_0_1_SS :\nforall P:nat -> Prop,\nP 0 -> P 1 -> (forall n, P n -> P (S (S n))) -> forall n, P n.\nProof. hammer_hook \"Div2\" \"Div2.ind_0_1_SS\".\nintros P H0 H1 H2.\nfix 1.\ndestruct n as [|[|n]].\n- exact H0.\n- exact H1.\n- apply H2, ind_0_1_SS.\nQed.\n\n\n\nLemma lt_div2 n : 0 < n -> div2 n < n.\nProof. hammer_hook \"Div2\" \"Div2.lt_div2\".   apply Nat.lt_div2. Qed.\n\nHint Resolve lt_div2: arith.\n\n\n\nLemma even_div2 n : even n -> div2 n = div2 (S n).\nProof. hammer_hook \"Div2\" \"Div2.even_div2\".\nrewrite Even.even_equiv. intros (p,->).\nrewrite Nat.div2_succ_double. apply Nat.div2_double.\nQed.\n\nLemma odd_div2 n : odd n -> S (div2 n) = div2 (S n).\nProof. hammer_hook \"Div2\" \"Div2.odd_div2\".\nrewrite Even.odd_equiv. intros (p,->).\nrewrite Nat.add_1_r, Nat.div2_succ_double.\nsimpl. f_equal. symmetry. apply Nat.div2_double.\nQed.\n\nLemma div2_even n : div2 n = div2 (S n) -> even n.\nProof. hammer_hook \"Div2\" \"Div2.div2_even\".\ndestruct (even_or_odd n) as [Ev|Od]; trivial.\napply odd_div2 in Od. rewrite <- Od. intro Od'.\nelim (n_Sn _ Od').\nQed.\n\nLemma div2_odd n : S (div2 n) = div2 (S n) -> odd n.\nProof. hammer_hook \"Div2\" \"Div2.div2_odd\".\ndestruct (even_or_odd n) as [Ev|Od]; trivial.\napply even_div2 in Ev. rewrite <- Ev. intro Ev'.\nsymmetry in Ev'. elim (n_Sn _ Ev').\nQed.\n\nHint Resolve even_div2 div2_even odd_div2 div2_odd: arith.\n\nLemma even_odd_div2 n :\n(even n <-> div2 n = div2 (S n)) /\\\n(odd n <-> S (div2 n) = div2 (S n)).\nProof. hammer_hook \"Div2\" \"Div2.even_odd_div2\".\nsplit; split; auto using div2_odd, div2_even, odd_div2, even_div2.\nQed.\n\n\n\n\n\nNotation double := Nat.double.\n\nHint Unfold double Nat.double: arith.\n\nLemma double_S n : double (S n) = S (S (double n)).\nProof. hammer_hook \"Div2\" \"Div2.double_S\".\napply Nat.add_succ_r.\nQed.\n\nLemma double_plus n m : double (n + m) = double n + double m.\nProof. hammer_hook \"Div2\" \"Div2.double_plus\".\napply Nat.add_shuffle1.\nQed.\n\nHint Resolve double_S: arith.\n\nLemma even_odd_double n :\n(even n <-> n = double (div2 n)) /\\ (odd n <-> n = S (double (div2 n))).\nProof. hammer_hook \"Div2\" \"Div2.even_odd_double\".\nrevert n. fix 1. destruct n as [|[|n]].\n-\nsplit; split; auto with arith. inversion 1.\n-\nsplit; split; auto with arith. inversion_clear 1. inversion H0.\n-\ndestruct (even_odd_double n) as ((Ev,Ev'),(Od,Od')).\nsplit; split; simpl div2; rewrite ?double_S.\n+ inversion_clear 1. inversion_clear H0. auto.\n+ injection 1. auto with arith.\n+ inversion_clear 1. inversion_clear H0. auto.\n+ injection 1. auto with arith.\nQed.\n\n\n\nLemma even_double n : even n -> n = double (div2 n).\nProof. hammer_hook \"Div2\" \"Div2.even_double\".  exact (proj1 (proj1 (even_odd_double n))). Qed.\n\nLemma double_even n : n = double (div2 n) -> even n.\nProof. hammer_hook \"Div2\" \"Div2.double_even\".  exact (proj2 (proj1 (even_odd_double n))). Qed.\n\nLemma odd_double n : odd n -> n = S (double (div2 n)).\nProof. hammer_hook \"Div2\" \"Div2.odd_double\".  exact (proj1 (proj2 (even_odd_double n))). Qed.\n\nLemma double_odd n : n = S (double (div2 n)) -> odd n.\nProof. hammer_hook \"Div2\" \"Div2.double_odd\".  exact (proj2 (proj2 (even_odd_double n))). Qed.\n\nHint Resolve even_double double_even odd_double double_odd: arith.\n\n\n\nLemma even_2n : forall n, even n -> {p : nat | n = double p}.\nProof. hammer_hook \"Div2\" \"Div2.even_2n\".\nintros n H. exists (div2 n). auto with arith.\nDefined.\n\nLemma odd_S2n : forall n, odd n -> {p : nat | n = S (double p)}.\nProof. hammer_hook \"Div2\" \"Div2.odd_S2n\".\nintros n H. exists (div2 n). auto with arith.\nDefined.\n\n\n\nLemma div2_double n : div2 (2*n) = n.\nProof. hammer_hook \"Div2\" \"Div2.div2_double\".   apply Nat.div2_double. Qed.\n\nLemma div2_double_plus_one n : div2 (S (2*n)) = n.\nProof. hammer_hook \"Div2\" \"Div2.div2_double_plus_one\".   apply Nat.div2_succ_double. Qed.\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/Div2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7538594393827422}}
{"text": "(*Prove que |rev(l)| = |l|, qualquer que seja a lista l.*)\n\nRequire Import List.\nRequire Import Lia.\n\nFixpoint concat (l1 l2 : list nat) : list nat :=\n  match l1 with\n    | nil => l2\n    | cons h l' => cons h (concat l' l2)\n  end.\n\nFixpoint rev (l : list nat) : list nat :=\n  match l with\n    | nil => l\n    | cons h l' => concat (rev l') (cons h nil)\n  end.\n\nFixpoint len (l : list nat) : nat :=\n  match l with\n    | nil => 0\n    | cons h l' => 1 + len l'\n  end.\n\nLemma concat_nil_commutative: forall l : list nat, concat l nil = l.\nProof.\n  induction l.\n  - simpl concat.\n    reflexivity.\n  - simpl concat.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nLemma concat_sum_len : forall l1 l2, len (concat l1 l2) = len l1 + len l2.\nProof.\n  induction l1, l2.\n  - simpl concat.\n    simpl len.\n    reflexivity.\n  - simpl concat.\n    simpl (len nil).\n    reflexivity.\n  - simpl (len nil).\n    assert (concat l1 nil = l1).\n    -- apply concat_nil_commutative.\n    -- simpl concat.\n       rewrite H.\n       lia.\n  - simpl len.\n    rewrite IHl1.\n    simpl len.\n    reflexivity.\nQed.\n\nLemma reverse_list_size : forall l, len (rev l) = len l.\nProof.\n  induction l.\n  - simpl rev.\n    reflexivity.\n  - simpl rev.\n    assert (len (concat (rev l) (a :: nil)) = len (rev l) + len (a :: nil)).\n    -- apply concat_sum_len.\n    -- rewrite H.\n       rewrite IHl.\n       simpl.\n       lia.\nQed.\n", "meta": {"author": "Xavier-Edups", "repo": "paa_ex", "sha": "2d0f8f9b6523ed39af36b1da2ab3396289b5c663", "save_path": "github-repos/coq/Xavier-Edups-paa_ex", "path": "github-repos/coq/Xavier-Edups-paa_ex/paa_ex-2d0f8f9b6523ed39af36b1da2ab3396289b5c663/80.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7538594251774227}}
{"text": "(* Exercise 1 *)\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 f_id b.\n  rewrite f_id.\n  rewrite f_id.\n  reflexivity.\nQed.\n\n(* Exercise 2 *)\nTheorem andb_eq_orb :\n  forall b c : bool,\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros b c H.\n  destruct b.\n    (* true, true *)\n    destruct c.\n    reflexivity.\n    (* true, false *)\n    simpl in H.\n    discriminate.\n    (* false, true *)\n    destruct c.\n    simpl in H.\n    discriminate.\n    (* false, false *)\n    simpl in H.\n    exact H.\nQed.\n\n(* Exercise 3 *)\nInductive bin : Type :=\n  | bZ : bin\n  | bE : bin -> bin\n  | bO : bin -> bin.\n\nFixpoint incr (b:bin) : bin :=\n  match b with\n  | bZ   => bO bZ\n  | bE x => bO x\n  | bO x => bE (incr x)\n  end.\n\nFixpoint bin_to_nat (b:bin) : nat :=\n  match b with\n  | bZ    => O\n  | bE x  => 2 * (bin_to_nat x)\n  | bO x  => 2 * (bin_to_nat x) + 1\n  end.\n\nLemma add_id_right : forall n : nat, n + 0 = n.\nProof.\n  intro n.\n  induction n.\n    simpl. reflexivity.\n    simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma add_associativity : forall m n o : nat, m + (n + o) = m + n + o.\nProof.\n  intros m n o.\n  induction m. induction n. induction o.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. reflexivity.\n    simpl. rewrite IHm. reflexivity.\nQed.\n\nLemma add_commutativity :\n  forall a b c d : nat,\n  a + b + c + d = a + c + b + d.\nAdmitted.\n\nTheorem incr_correct : forall b, bin_to_nat (incr b) = bin_to_nat b + 1.\nProof.\n  intro b.\n  induction b.\n    (* bZ *)\n    simpl. reflexivity.\n    (* bE *)\n    simpl. rewrite add_id_right. reflexivity.\n    (* bO *)\n    simpl. rewrite add_id_right.\n    rewrite IHb. rewrite add_id_right.\n    rewrite add_associativity.\n    rewrite add_commutativity.\n    reflexivity.\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/more_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7538311983695222}}
{"text": "\n(* ejercicio 1:(PUNTOS: 2 )\n  Probar las siguientes proposiciones sin hacer uso de Tauto ni de Auto: *)\n\n\nLemma distr_impl : (A,B,C:Prop)(A->(B->C))->(A->B)->(A->C).\nIntros.\nApply H.\nAssumption.\n\nApply H0.\nAssumption.\nDefined.\n\nSection ej1.\nVariables p,q:Prop.\nHypothesis premisa1: ~p \\/ q.\n\nLemma ejemplo1 : p -> q.\nIntro.\nElim premisa1.\nIntro.\nAbsurd p.\nAssumption.\n\nAssumption.\n\nIntro.\nAssumption.\nDefined.\nEnd ej1.\n\n\nSection Regla_MT.\n\nVariables A,B:Prop.\nHypothesis prem1 : A->B.\nHypothesis prem2 : ~B.\n\nTheorem MT : ~A.\nIntro.\nGeneralize (prem1 H).\nIntro.\nAbsurd B.\nAssumption.\n\nAssumption.\nDefined.\nEnd Regla_MT.\n\nPrint distr_impl.\nPrint ejemplo1.\nPrint MT. \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(* ejercicio 2:(PUNTOS: 2 )\n   probar dos teoremas que juntos prueben la equivalencia de\n   new_false y False *)\n\nTheorem equiv_false1:(new_false)->(False).\nIntro.\nApply H.\nDefined.\n\nTheorem equiv_false2: \n(False)->new_false.\nIntro.\nContradiction.\nDefined.\nPrint equiv_false1.\nPrint equiv_false2.\n\n\n(* definicion de \"y\":\na \"y\" b es verdad si todo lo que se puede derivar del conjunto\n{a,b} es verdad *)\n\nDefinition new_and := [a,b:Prop](c:Prop)((a -> b -> c) -> c) .\n\n(* ejercicio 3:(PUNTOS: 3 ) \n   probar dos teoremas que juntos demuestren\n   la equivalencia de new_and y /\\ *)\nTheorem equiv_and1:(a,b:Prop)(new_and a b)->(a/\\b) .\nIntro.\nIntros.\nApply H.\nIntros.\nSplit.\nAssumption.\nAssumption.\nDefined.\n\nTheorem equiv_and2:(a,b:Prop)(a/\\b)->(new_and a b) . \nIntros.\nUnfold new_and.\nIntros.\nApply H0.\nElim H.\nIntros.\nAssumption.\nElim H.\nIntros.\nAssumption.\nDefined.\n\nPrint equiv_and1.\nPrint equiv_and2.\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\n(* numeros naturales *)\n\nDefinition new_nat := (a:Set)(a->(a->a)->a).\n\n 1\n(* numeros polimorficos de Church *)\n\nDefinition zero := [a:Set][z:a][s:a->a] z.\nDefinition one  := [a:Set][z:a][s:a->a] (s z).\nDefinition two  := [a:Set][z:a][s:a->a] (s (s z)).\n\n\n(* ejercicio 4 : (PUNTOS 3 ) \n   Dar una definicion de sucesor y chequearla con\n   al menos dos entradas diferentes. Por ejemplo, comprobar\n   que el sucesor de zero es one y el sucesor de one es two *)\n\nDefinition sucesor[x:Set;z:x;s:x->x;]:=(s ).\n\n\nPrint sucesor.\n\n\n\n\n\n\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/exA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7538311915503512}}
{"text": "Add LoadPath \"../Basics\".\nAdd LoadPath \"../Induction\".\nRequire Import EnumTypes.\nRequire Import Induction.\nRequire Import NamingCases.\n\n(** An inductive type for lists. Uses the familiar x1 :: x2 :: ...\n    :: xn :: Nil approach. *)\nInductive natlist : Type :=\n   | nil : natlist\n   | cons : nat -> natlist -> natlist.\n\nDefinition testlist := cons 1 (cons 2 (cons 3 nil)).\n\n(** Some helpful notation for lists, using [::] as an infix cons\n    operator. *)\nNotation \"x :: y\" := (cons x y) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n(**********)\n(* REPEAT *)\n(**********)\n\n(** Takes a number [n] and a [count] and returns a length of [count] where\n    every element is [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(** Test *)\nEval compute in (repeat 3 6).\n\n(**********)\n(* LENGTH *)\n(**********)\n\n(** The [length] function calculates the length of a list *)\nFixpoint length (l : natlist) : nat :=\n   match l with\n   | nil => 0\n   | h :: t => 1 + (length t)\n   end.\n\n(** Test *)\nEval compute in (length [1;2;3;4;5;2]).\n\n(**********)\n(* APPEND *)\n(**********)\n\n(** [app]end two lists together *)\nFixpoint app (l1 l2 : natlist) : natlist :=\n   match l1 with\n   | nil => l2\n   | h :: t => h :: (app t l2)\n   end.\n\n(** Some convenient [app]-related notation. We use the haskell [++]\n    append infixr *)\nNotation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\n(** Some [app] tests *)\nExample test_app1: [1;2;3] ++ [2;3] = [1;2;3;2;3].\nProof. reflexivity. Qed.\nExample test_app2: [1;2;3] ++ nil = [1;2;3].\nProof. reflexivity. Qed.\nExample test_app3: [] ++ [1;2;3] = [1;2;3].\nProof. reflexivity. Qed.\n\n(*****************)\n(* HEAD and TAIL *)\n(*****************)\n\n(** The haskell [head] function, but with a default value that is\n    returned when the function is passed a [nil] [natlist]. *)\nDefinition hd (default : nat) (l : natlist) : nat :=\n   match l with\n   | nil => default\n   | h :: t => h\n   end.\n\n(** Return every list element except for the head *)\nDefinition tl (l : natlist) : natlist :=\n   match l with\n   | nil => nil\n   | h :: t => t\n   end.\n\n(** EXERCISE [**]: Complete the definitions of [nonzeros], [oddmembers],\n    and [countoddmembers] below. *)\n\n(** [nonzeros] removes all instances of [0] from the list *)\nFixpoint nonzeros (l : natlist) : natlist :=\n   match l with\n   | nil => nil\n   | h :: t => match h with\n               | O => nonzeros t\n               | S h' => h :: (nonzeros t)\n               end\n   end.\n\n(* Test *)\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\n(** [oddmembers] filters all even elements out of a list *)\nFixpoint oddmembers (l : natlist) : natlist :=\n   match l with\n   | nil => nil\n   | h :: t => if oddb 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\n(** [countoddmembers] counts the number of oddmembers in the list *)\nFixpoint countoddmembers (l : natlist) : nat :=\n   match l with\n   | nil => 0\n   | h :: t => if oddb h\n               then 1 + (countoddmembers t)\n               else (countoddmembers t)\n   end.\n\n(* Tests *)\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers2: countoddmembers [2;4;6;10] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\n(** EXERCISE [***]: Define [alternate], a function that zips up the\n    elements of two lists *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n   match l1 with\n   | nil => l2\n   | h1 :: t1 => match l2 with\n                 | nil => l1\n                 | h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n                 end\n   end.\n\n(* Tests *)\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 [] [4;5] = [4;5].\nProof. reflexivity. Qed.\n\n(******************)\n(* BAGS VIA LISTS *)\n(******************)\n\n(** A [bag] is a synonym for a [multiset] *)\nDefinition bag := natlist.\n\n(** EXERCISE [***]: Define the functions [count], [add], and\n    [member] *)\n\n(** [count n xs] determines the number of [n]'s in bag [xs] *)\nFixpoint count (v : nat) (s : bag) :=\n   match s with\n   | [] => 0\n   | h :: t => if beq_nat h v\n               then 1 + (count v t)\n               else (count v t)\n   end.\n\n(* Tests *)\nExample test_count1: count 1 [1;2;3;1;2] = 2.\nProof. reflexivity. Qed.\nExample test_count2: count 5 [1;2;3;4;8] = 0.\nProof. reflexivity. Qed.\n\n(** [sum xs ys] combines the contents of two bags *)\nDefinition sum : bag -> bag -> bag :=\n   app.\n\n(* Tests *)\nExample test_sum1 : count 1 (sum [1;4;1] [1;2;1]) = 4.\nProof. reflexivity. Qed.\n\n(** [add n xs] prepends the element n to the bag xs *)\nDefinition add (v:nat) (s:bag) : bag :=\n   v :: s.\n\n(* Tests *)\nExample test_add1: count 1 (add 1 [1;4;3;1]) = 3.\nProof. reflexivity. Qed.\nExample test_add2: count 1 (add 3 [1;4;2;1]) = 2.\nProof. reflexivity. Qed.\n\n(** [member n xs] determines whether n is a member of the bag xs *)\nDefinition member (v:nat) (s:bag) : bool :=\n   if beq_nat (count v s) 0\n   then false\n   else true.\n\n(* Tests *)\nExample test_member1: member 1 [1;4;1] = true.\nProof. reflexivity. Qed.\nExample test_member2: member 2 [1;4;1] = false.\nProof. reflexivity. Qed.\n\n(** EXERCISE [***]: More bag functions: [remove_one], [remove_all], and\n    [subset] *)\n\n(** Remove the first instances of a value [v] from a bag [s] *)\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n   match s with\n   | [] => s\n   | h :: t => if beq_nat h v\n               then t\n               else h :: (remove_one v t)\n   end.\n\nExample test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_one2: remove_one 5 [2;1;5;4;5;2] = [2;1;4;5;2].\nProof. reflexivity. Qed.\n\n(* remove all elements [v] from a bag [s] *)\nFixpoint remove_all (v:nat) (s:bag) : bag :=\n   match s with\n   | [] => s\n   | h :: t => if beq_nat h v\n               then (remove_all v t)\n               else h :: (remove_all v t)\n   end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;5;4;2;5;3]) = 0.\nProof. reflexivity. Qed.\n\n(* [subset s1 s2] determines if bag s1 is a subset of bag s2 *)\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n   match s1 with\n   | [] => true\n   | h :: t => if (member h s2)\n               then (subset t (remove_one h s2))\n               else false\n   end.\n\n(* Test *)\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(** Rewriting this cuz i need it below, and some import technicalities\n    are preventing me from getting it *)\nTheorem beq_nat_refl : forall (n : nat),\n   beq_nat n n = true.\n\nProof.\n   intro n. induction n as [| n'].\n   Case \"n = 0\".\n      reflexivity.\n   Case \"n = n'\".\n      simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\n(** EXERCISE [***]: Prove something interesting about the functions\n    [count] and [add] on bags *)\nTheorem bag_theorem : forall (n : nat) (s : bag),\n   count n (add n s) = 1 + (count n s).\n\nProof.\n   intros n s.\n   assert (H: (add n s) = n :: s).\n      reflexivity.\n   rewrite -> H. simpl. rewrite -> beq_nat_refl. reflexivity. Qed.\n\n", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Lists/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.897695288001848, "lm_q1q2_score": 0.7538252403564464}}
{"text": "Require Import MathClasses.theory.rings.\nRequire Import MathClasses.interfaces.abstract_algebra.\nRequire Import MCMisc.tactics.\nRequire Import Ring.\n(*less annoying than ^2 which multiplies by 1 as well*)\nDefinition sqr `{Mult A} (a:A) := a*a.\n\nSection RingMisc.\n\n(**some miscelleneous convenience props about rings.\nThe ring tactic can prove these. However, to use that tactic,\none has to manually assert the statement, which can\nsometimes contain bulky terms, which may need to be updated\nwhen a proof or statement changes slightly.\nThese lemmas can often help avoid those manual assertions.\n*)\nContext `{Ring A}.\nAdd Ring tempRing : (stdlib_ring_theory A).\n\nLemma RingShiftMinus  : forall \n  a b c : A,\n  a - b  = c <-> a = b + c.\nProof using All.\n  intros ? ? ?; split; intros Hh.\n  (**the ring tactic does not seem to look at hyps*)\n  - rewrite <- Hh. ring.\n  - rewrite Hh. ring.\nQed.\n\nLemma RingProp2  : forall \n  a b  : A,\n  a + b - b  =a.\nProof using All.\n  intros ? ?. ring.\nQed.\n\nLemma RingProp3  : forall \n  a   : A,\n  a + a   = 2 * a.\nProof using All.\n  intros ? . ring.\nQed.\n\nLemma RingProp4  : forall \n  a b c  : A,\n  -a * (b-c)   = a * (c-b).\nProof using All.\n  intros ? ? ? . ring.\nQed.\n\nLemma MultShuffle3l: \n∀ a b c : A, \n a * (b * c) = b * a * c.\nProof using All.\n  intros.\n  ring.\nQed.\n\nLemma PlusShuffle3l: \n∀ a b c : A, \n a + (b + c) = b + a + c.\nProof using All.\n  intros.\n  ring.\nQed.\n\nLemma MultShuffle3r: \n∀ a b c : A, \n a * b * c = a * c * b.\nProof using All.\n  intros.\n  ring.\nQed.\n\nLemma PlusShuffle3r: \n∀ a b c : A, \n a + b + c = a + c + b.\nProof using All.\n  intros.\n  ring.\nQed.\n\n\nLemma MultSqrMix: \n∀ a b c d : A, \n (a * b * c * d = (a * c) * (b * d)).\nProof using All.\n  intros.\n  ring.\nQed.\n\n(*\n Lemma X:\n forall \n(X Y X0 Y0 xy cc X1 Y1 s c : A),\n\n((X * (c * c) + xy * s * c + Y * (s * s)) * (X1 * X1) +\n(Y * (c * c) - xy * s * c + X * (s * s)) * (Y1 * Y1) +\n((X0 * c + Y0 * s) * X1 + (Y0 * c + - X0 * s) * Y1 +\n (xy * (1 - 2 * (s * s)) + (Y - X) * (2 * s * c)) * X1 *\n Y1 + cc))  =\nX * ((X1 * c - Y1 * s) * (X1 * c - Y1 * s)) +\nY * ((Y1 * c + X1 * s) * (Y1 * c + X1 * s)) +\n(X0 * (X1 * c - Y1 * s) + Y0 * (Y1 * c + X1 * s) +\n xy * (X1 * c - Y1 * s) * (Y1 * c + X1 * s) + cc)\n.\n Proof.\n intros.\n ring_simplify.\n*)\n\nSection Le.\nRequire Export MathClasses.orders.rings.\nContext `{Le A}\n    `{@orders.SemiRingOrder A equiv plus mult zero one le}.\n\nLemma RingLeProp1  : forall \n  a  b : A,\n  0 ≤ b\n  ->a ≤ b + a.\nProof using All.\n  intros ? ? Hh.\n  apply flip_le_minus_l. rewrite plus_negate_r.\n  assumption.\nQed.\n\nLemma RingLeProp1l  : forall \n  a  b : A,\n  0 ≤ b\n  ->a ≤  a + b.\nProof using All.\n  intros ? ? Hh.\n  rewrite commutativity.\n  apply RingLeProp1.\n  assumption.\nQed.\n\n(** Proof is the dual of MathClasses.orders.rings.ge_1_mult_le_compat_r*)\nLemma le_1_mult_le_compat_r x y z : z ≤ 1 → 0 ≤ x → x ≤ y → x * z ≤ y .\n  Proof.\n    intros.\n    transitivity x;[| easy].\n    rewrite <-(mult_1_r x) at 2.\n    now apply (order_preserving_nonneg (.*.) x).\n  Qed.\n\nLemma RingLeProp2  : forall \n  a : A,\n  0 ≤ a\n  ->a ≤ 2*a.\nProof using All.\n  intros ? Hh.\n  rewrite <- RingProp3.\n  apply RingLeProp1.\n  assumption.\nQed.\n\nLemma RingLeProp3  : forall \n  a : A,\n  0 ≤ a\n  ->0 ≤ 2*a.\nProof using All.\n  intros ? Hh.\n  rewrite <- RingProp3.\n  apply nonneg_plus_compat; assumption.\nQed.\n\nRequire Import MathClasses.interfaces.orders.\n\nContext `{Lt A} `{Apart A} {FPSRO:@FullPseudoSemiRingOrder A \nequiv apart plus mult zero one le lt}.\n\nSet Suggest Proof Using.\nLemma RingLeIfSqrLe  : forall \n  (a b : A),\n  0 < b + a\n  → sqr a ≤ sqr b\n  → a ≤  b.\nProof using All.\n  intros ? ? Hp Hs.\n  apply flip_nonneg_minus in Hs.\n  assert (sqr b - sqr a = (b-a)*(b+a)) as Heq by (unfold sqr;ring).\n  rewrite Heq in Hs. clear Heq.\n  apply flip_nonneg_minus.\n  eapply nonneg_mult_rev_l; eauto.\nQed.\n\nLemma RingPosNnegCompatPlus  : forall \n  (a b : A),\n  0 < b\n  →0 ≤ a\n  → 0 < b + a.\nProof using All.\n  intros ? ? Hlt hlt. eapply lt_le_trans; eauto.\n  rewrite commutativity.\n  apply RingLeProp1.\n  assumption.\nQed.\n\nLemma RingLeSqr1  : forall \n  (a b : A),\n  0 ≤ b\n  → 0 ≤ a\n  → sqr a + sqr b ≤ sqr (b + a).\nProof using All.\n  intros ? ? Ha Hb.\n  unfold sqr.\n  apply flip_nonneg_minus.\n  ring_simplify.\n  rewrite <- (@simple_associativity _ _ mult _ _).\n  apply RingLeProp3.\n  apply nonneg_mult_compat; assumption.\nQed.\n\nLemma RingLeMultIff  : forall \n  (a b k : A),\n  0 < k\n  → (a ≤ b ↔ k*a ≤ k*b).\nProof.\n  intros ? ? ? Hk.\n  split; intro h.\n- apply (order_preserving (mult k));\n  eauto with typeclass_instances.\n\n- apply (order_reflecting) in h;\n  eauto with typeclass_instances.\n  (* k needs to be positive in this case *)\n \nQed.\n\nLemma RingLtMultIff  : forall \n  (a b k : A),\n  0 < k\n  → (a < b ↔ k*a < k*b).\nProof.\n  intros ? ? ? Hk.\n  split; intro h.\n- apply (strictly_order_preserving);\n  eauto with typeclass_instances.\n\n- apply (strictly_order_reflecting) in h;\n  eauto with typeclass_instances. \nQed.\n\n\n\n(** why is this needed? without it, rewrite Hki in [RingLeRecipMultIff]\nbelow fails *)\n\nLocal Instance ProperLt :\nProper (equiv ==> equiv ==> iff) lt.\nProof.\neauto with typeclass_instances.\nQed.\n\n(** there is a version for for fields, where the hypothesis H10 is not needed. *)\nLemma RingLeRecipMultIff {H10 :PropHolds (1 ≶ 0)} : forall \n  (a b k kinv : A),\n  0 < k\n  → kinv*k =1\n  → (k*a ≤ b ↔ a ≤ kinv*b).\nProof.\n  intros ? ? ? ? Hk Hki.\n  rewrite RingLeMultIff with (k:=kinv);[|].\n- ring_simplify [Hki] (kinv * (k * a)) .\n  reflexivity.\n- eapply pos_mult_rev_l;[| apply Hk].\n  rewrite Hki. apply lt_0_1.\nQed.\n\n   \nEnd Le.\n\n\nEnd RingMisc.\n", "meta": {"author": "aa755", "repo": "ROSCoq", "sha": "bb71cdf642fce1ab2f129c833db7a6c358965313", "save_path": "github-repos/coq/aa755-ROSCoq", "path": "github-repos/coq/aa755-ROSCoq/ROSCoq-bb71cdf642fce1ab2f129c833db7a6c358965313/src/MCMisc/rings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7538252393994377}}
{"text": "Add LoadPath \"../Basics\".\nAdd LoadPath \"../Induction\".\nAdd LoadPath \"../Lists\".\n\n(* Require Import Lists. *)\nRequire Import EnumTypes.\nRequire Import Induction.\nRequire Import NamingCases.\nRequire Export Reasoning.\n\n(** We can make polymorphic lists *)\nInductive list (X:Type) : Type :=\n   | nil : list X\n   | cons : X -> list X -> list X.\n\nCheck nil.\nCheck cons.\n\n(** Let's try and re-write our natlist functions, only now they will\n    operate over generic, polymorphic lists *)\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(* Some tests to make sure it works well *)\nExample test_length1 : length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity. Qed.\nExample test_length2 : length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity. Qed.\n\n(* Remaining list processing functions *)\nFixpoint app (X:Type) (l1 l2:list X) : (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 : rev nat (cons nat 1 (cons nat 2 (nil nat))) =\n   (cons nat 2 (cons nat 1 (nil nat))).\n\nProof. reflexivity. Qed.\n\nExample test_rev2: rev bool (nil bool) = nil bool.\nProof. reflexivity. Qed.\n\nModule MumbleBaz.\n\n(** EXERCISE [**]: Consider the inductively defined types below. Which\n    of the given elements are well-typed elements of grumble X *)\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(** Element          | Well-typed\n    ------------------------------\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    TODO *)\n\n(** EXERCISE [**]: How many elements does the following inductive type\n    have?  TODO *)\nInductive baz : Type :=\n   | x : baz -> baz\n   | y : baz -> bool -> baz.\n\nEnd MumbleBaz.\n\n\n(*****************************)\n(* TYPE ANNOTATION INFERENCE *)\n(*****************************)\n\n(** Let's rewrite [app] without specifying the types of any of the\n    arguments *)\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(** It works b/c coq is smart enough to infer types. *)\n\n\n(***************************)\n(* TYPE ARGUMENT SYNTHESIS *)\n(***************************)\n\n(** We don't have to explicitly write types everywhere. Consider the\n    following statement:\n\n      length nat (cons nat 1 (cons nat 5 (nil nat)))\n\n   why do we have to keep throwing around nat? Turns out we don't, we\n   can use implicit arguments: *)\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(** Compare this first definition of list123, where [nat] is explicitly\n    specified, to [list123'], which uses argument synthesis *)\nDefinition list123 :=\n   cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\nDefinition list123' := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n\n(*****************)\n(* IMPLICIT ARGS *)\n(*****************)\n\n(** As you might have guessed, we can even eliminate the underscores. We\n    use the [Arguments] directive, which takes the function name, and\n    a sequence of arguments to that function, with curly-braces\n    indicating that the argument should be treated implicitly *)\nArguments nil {X}.\nArguments cons {X} _ _.\n(* underscores are used for unnamed arguments *)\nArguments length {X} l.\nArguments app {X} l1 l2.\nArguments rev {X} l.\nArguments snoc {X} l v.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\n\n(** Another way to accomplish the same goal is by declaring an implicit\n    argument in the function definition itself, using curly braces: *)\nFixpoint length'' {X:Type} (l:list X) : nat :=\n   match l with\n   | nil => O\n   | cons h t => S (length'' t)\n   end.\n\n(** Sometimes when declaring implicit arguments, Coq will not have enough\n    local information to determine a type argument. In these cases, we\n    must tell Coq that we want to give the argument explicitly, even\n    though the initial declaration was implicit. For example, consider\n    this definition:\n\n      Definition mynil := nil\n\n    Uncommenting this definition wil cause an error, because Coq has\n    no idea what type should be supplied to nil. We can avoid this by\n    providing an explicit type declaration. *)\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implict arguments to be explicit by\n    prefixing a function name with @ *)\nCheck @nil.\nDefinition mynil' := @nil nat.\n\n(** Some notationz *)\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(* EXERCISES: POLYMORPHIC LISTS *)\n(********************************)\n\n(** EXERCISE [**]: Fill in the definitions and complete the proofs\n    below *)\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n   match count with\n   | O => nil\n   | S count' => cons n (repeat n count')\n   end.\n\nExample test_repeat1: 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.\n\nProof.\n   intros X l. reflexivity. Qed.\n\nTheorem rev_snoc : forall X : Type, forall v : X, forall s : list X,\n   rev (snoc s v) = v :: (rev s).\n\nProof.\n   intros X v s. induction s as [| x s'].\n   Case \"s = []\".\n      reflexivity.\n   Case \"s = x :: s'\".\n      simpl. rewrite IHs'. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n   rev (rev l) = l.\n\nProof.\n   intros X l. induction l as [| x l'].\n   Case \"l = []\".\n      reflexivity.\n   Case \"l = x :: l'\".\n      simpl. rewrite rev_snoc. rewrite IHl'. reflexivity.\nQed.\n\nTheorem snoc_with_append :\n   forall X : Type, forall l1 l2 : list X, forall v : X,\n   snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\n\nProof.\n   intros X l1 l2 v. induction l1 as [| x l1'].\n   Case \"l1 = []\".\n      reflexivity.\n   Case \"l1 = x :: l1'\".\n      simpl. rewrite IHl1'. reflexivity.\nQed.\n\n\n(*********************)\n(* POLYMORPHIC PAIRS *)\n(*********************)\n\n(** Using the same pattern we used for polymorphic lists, we can create\n    polymorphic pairs *)\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\n(** The standard [fst] and [snd] function *)\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 next function is [zip], but it is called [combine] for\n    consistency reasons *)\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 [*]: Try answering the following questions and then check\n    your answers in Coq *)\n\n(* Question: What is the type of [combine]? *)\n(* Answer: list X -> list Y -> list (prod X Y) *)\nCheck @combine.\n\n(* Question: What does\n\n      Eval compute in (combine [1;2] [false;true;false;true]).\n\n   print? *)\n(* Answer: [(1,false);(2,true)] *)\nEval compute in (combine [1;2] [false;true;false;true]).\n\n(** EXERCISE [**]: The function [split] is the right inverse of combine:\n    it takes a list of pairs and returns a pair of lists. Define\n    [split] *)\nFixpoint split_help_fst {X Y : Type} (l : list (X*Y)) : (list X) :=\n   match l with\n   | [] => []\n   | h :: t => (fst h) :: (split_help_fst t)\n   end.\n\nFixpoint split_help_snd {X Y : Type} (l : list (X*Y)) : (list Y) :=\n   match l with\n   | [] => []\n   | h :: t => (snd h) :: (split_help_snd t)\n   end.\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X)*(list Y) :=\n   (split_help_fst l, split_help_snd l).\n\nExample test_split: split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\n(** A much more elegant version of [split] using a [let]-expression *)\nFixpoint split' {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n   match l with\n   | [] => ([],[])\n   | (x,y)::t => let t' := split t\n                 in  (x::(fst t'), (y::(snd t')))\n   end.\n\n\n(***********************)\n(* POLYMORPHIC OPTIONS *)\n(***********************)\n\n(** Let's make our [natoption] type polymorphic *)\nInductive option (X:Type) : Type :=\n   | Some : X -> option X\n   | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** Let's make the [index] function polymorphic now *)\nFixpoint index {X : Type} (n : nat) (l : list X) : option X :=\n   match l with\n   | [] => None\n   | a :: l' => if beq_nat n O\n                  then Some a\n                  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 [*]: Complete the definition of a polymorphic version of\n    [hd_opt] function from the last chapter. *)\nFixpoint hd_opt {X : Type} (l : list X) : option X :=\n   match l with\n   | [] => None\n   | x::l' => Some x\n   end.\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", "meta": {"author": "madelgi", "repo": "software-foundations", "sha": "7f533d9596c4408eedd02bb7463f4ed532e9541e", "save_path": "github-repos/coq/madelgi-software-foundations", "path": "github-repos/coq/madelgi-software-foundations/software-foundations-7f533d9596c4408eedd02bb7463f4ed532e9541e/Poly/Polymorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.8976952893703477, "lm_q1q2_score": 0.7538252163021545}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\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\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 eq1.\n  (* Bring back n to the quantifier for a more general IH *)\n  generalize dependent n.\n  induction l.\n    - (* nil *) simpl. intros n eq2. reflexivity.\n    - (* cons n l' *) intros n eq2. simpl. destruct n.\n      + (* zero *) inversion eq2. (* length cons n l = 0 is contra *)\n      + (* S n *) simpl. apply IHl. inversion eq2. reflexivity. \nQed.", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/5_Tactics/13_gen_dep_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7538233145721205}}
{"text": "Theorem ex24: forall a b c : Prop,\n               a /\\ (b /\\ c) <-> (a /\\ b) /\\ c.\nProof.\n  split. intro. split. split. elim H. intro.\n  intro. assumption. elim H. intros.\n  elim H1. intros. assumption.\n  elim H. intros. elim H1. intros. assumption.\n  intro. split. elim H. intros. elim H0.\n  intros. assumption. split. elim H. intros.\n  elim H0. intros. assumption. elim H. intros.\n  assumption.\nQed.\n\nTheorem ex25: forall a b c : Prop,\n               a \\/ (b \\/ c) <-> (a \\/ b) \\/ c.\nProof.\n  split. intro. elim H. intro. left. left. assumption.\n  intro. elim H0. intro. left. right. assumption.\n  intro. right. assumption.\n  intro. elim H. intro. elim H0. intro.\n  left. assumption. intro. right. left. assumption.\n  intro. right. right. assumption.\nQed.\n\nTheorem ex26: forall a b c : Prop,\n               ((a <-> b) <-> c) -> (a <-> (b <-> c)).\nProof.\n  Require Import Classical.\n  intros. split. intro. split. intro.\n  elim H. intros. apply H. split. intro. assumption.\n  intro. assumption. intro.\n  elim H. intros. apply H3. assumption.\n  assumption. \n  intro. elim H0. elim H. intros.\n  apply NNPP. intro. elim H2. intros.\n  apply H5. apply H7. apply H0. apply H.\n  split. intro. apply (H6 H8). assumption.\n  apply H. split. intro. contradiction.\n  intro. apply H2. apply (H3 H6). assumption.\nQed.\n\nTheorem ex26_1: forall a b c : Prop,\n                (a <-> (b <-> c)) -> ((a <-> b) <-> c).\nProof.\n  Require Import Classical.\n  intros. split. intro. elim H. elim H0. intros.\n  apply NNPP. intro. apply H5. apply H3.\n  apply H. split. intro. elim H3. intros.\n  apply (H7 H6). apply H0. assumption.\n  intro. contradiction. apply NNPP. intro.\n  elim H3. intros. apply H6. apply H0. apply H. split.\n  intro. contradiction. intro. contradiction.\n  apply NNPP. intro. apply H7. apply H. split.\n  intro. contradiction. intro. contradiction. \n  intro. split. elim H. intros. elim H1. intros.\n  apply (H5 H0). assumption. intro. \n  elim H. intros. apply H3. split.\n  intro. assumption. intro. 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/Associativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7537397550763092}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import FunInd.\n\n(* obliczenie nie zostawia \"sladu\" w dowodzie *)\n\nFact triv :\nforall n, 0 + n = n.\nProof.\nintro n.\nrewrite plus_O_n.\nreflexivity.\nQed.\n\nPrint triv.\n\nFact triv' :\nforall n, 0 + n = n.\nProof.\nintro n.\nreflexivity.\nQed.\n\nPrint triv'.\n\nInductive even : nat -> Prop :=\n| evenO : even O\n| evenSS : forall n, even n -> even (S (S n)).\n\nHint Constructors even.\n\nLemma even1046: even 1046.\nTime repeat constructor.\nQed.\n\nPrint even1046.\n\n(* dowod przez refleksje - slaba specyfikacja *)\n\nFunction check_even (n:nat) : bool :=\nmatch n with\n| O => true\n| 1 => false\n| S (S n0) => check_even n0\nend.\n\nLemma check_even_correct :\nforall n, check_even n = true -> even n.\nProof.\nintro n.\nfunctional induction (check_even n); intros; auto. discriminate.\nQed.  \n\nLtac prove_even n :=\n  exact (check_even_correct n (refl_equal true)).\n\nLemma even4000 :\neven 4000.\nProof.\n(*Time repeat constructor.*)\nTime prove_even 4000.\n(* wystarczy sprawdzic, czy check_even 4000 = true *)\nQed.\n\nPrint even4000.\n\nLemma false_even1247 :\neven 1247.\nProof.\n(*prove_even 1247.*)\nAbort.\n\n(* silna specyfikacja *) \n\nInductive option (P:Prop) : Set :=\n| proof : P -> option P\n| noproof : option P.\n\nDefinition get_form {P} (x: option P) : Prop :=\nmatch x with\n| proof _ p => P\n| noproof _ => True\nend.\n\n\nDefinition get_proof {P} (x: option P) : get_form x :=\nmatch x with\n| proof _ p => p\n| noproof _ => I\nend.\n\nEval compute in get_form (proof _ (refl_equal 0)).\nEval compute in get_proof (proof _ (refl_equal 0)).\nEval compute in get_form (noproof (0=0)).\n\nNotation \" x <- a1 ; a2 \" := \n(match a1 with\n| proof _ x => a2\n| noproof _ => _\nend) (at level 60).\n\nNotation \" [ x ] \" := (proof _ x).\nNotation \" ! \" := (@noproof _).\n\nDefinition check_even' : forall (n:nat), option (even n).\nrefine (fix check n : option (even n) :=\nmatch n with\n| 0 => [evenO]\n| 1 => ! \n| S (S n0) => \np <- check n0; [evenSS _ p] \nend).\ndestruct (check n0); [repeat constructor | constructor 2]; trivial.\nDefined. \n\nEval compute in (check_even' 32).\nEval compute in (check_even' 33).\n\nEval compute in (get_proof (check_even' 32)).\nEval compute in (get_form (check_even' 32)).\nEval compute in (get_proof (check_even' 33)).\n\nLtac prove_even_strong :=\nmatch goal with\n| [ |- even ?n ] => exact (get_proof (check_even' n))\nend. \n\nLemma strong_even4000 :\neven 4000.\nProof.\nTime prove_even_strong.\nTime Defined.\n\nPrint strong_even4000.\n(*Eval compute in strong_even4000.*)\n\nLemma even17 :\neven 17.\nProof.\n(*prove_even_strong.*)\nAbort.\n\nRequire Import Bool.\nPrint reflect.\n\nCheck reflect (even 2) (check_even 2).\n\nLemma even_reflect :\nforall n, reflect (even n) (check_even n).\nProof.\nintro n.\nCheck iff_reflect.\napply iff_reflect.\nsplit.\n- induction 1; auto.\n- apply check_even_correct.\nQed.\n\nLemma even1046_reflect :\neven 1046.\nProof.\nassert (hh:=even_reflect 1046).\ninversion hh.\ntrivial.\nTime Qed.\n\nPrint even1046_reflect.\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/w8 Reflection/reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7536388094768867}}
{"text": "Section Inductive_types.\n\n  Inductive bool : Type :=\n  | tru : bool\n  | fla : bool.\n\n  Definition and (m : bool) (n : bool) : bool :=\n    match m with\n    | tru => n\n    | fla => fla\n    end.\n\n  Inductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n  Fixpoint plus (m : nat) (n : nat) : nat :=\n    match m with\n    | O => n\n    | S m' => S (plus m' n)\n    end.\n\n  Definition or m n : bool :=\n    match m with\n    | tru => tru\n    | fla => n\n    end.\n\n  Lemma and_eq_or : \n  forall m n :bool,\n  (and m n = or m n) -> m = n.\n  Proof.\n    intros m n.\n    destruct m.\n    - destruct n.\n      + reflexivity.\n      + simpl. intros H. rewrite -> H. reflexivity. (* inversion H. *)\n    - destruct n.\n      + simpl. intros H. inversion H.\n      + reflexivity.\n  Qed.\n\n  Lemma and_eq_or' : forall m n :bool,\n      (and m n = or m n) -> m = n.\n    intros;now case m, n. Qed.\n\n  Fixpoint mult m n : nat :=\n    match m with\n    | O => O\n    | S m' => plus n (mult m' n)\n    end.\n\n  Fixpoint exp m n : nat :=\n    match n with\n    | O => S O\n    | S n' => mult m (exp m n')\n    end.\n\n  Lemma Mzeror : forall m, mult m O = O.\n    intros;now elim m. Qed.\n\n  Axiom Msymm : forall m n, mult m n = mult n m.\n  Axiom mult_dist_plus : forall m n1 n2,\n      mult m (plus n1 n2) = plus (mult m n1) (mult m n2).\n\n  Lemma exp_plus_dist_mult : forall m n1 n2,\n      exp m (plus n1 n2) = mult (exp m n1) (exp m n2).\n  Proof.\n    induction n1;intros;simpl.\n    - assert(Pidr : forall m, plus m O = m).\n      {\n        induction m0;simpl.\n        - reflexivity.\n        - rewrite -> IHm0. reflexivity.\n      }\n      rewrite (Pidr (exp m n2)). reflexivity.\n    - rewrite IHn1.\n      assert(Massoc : forall a b c, mult a (mult b c) = mult (mult a b) c).\n      {\n        induction b;simpl;intros.\n        - rewrite Mzeror. reflexivity.\n        - rewrite (Msymm a (S b)). simpl.\n          rewrite (Msymm b a), (Msymm (plus a (mult a b)) c).\n          do 2 rewrite mult_dist_plus. rewrite IHb.\n          rewrite (Msymm c a), (Msymm c (mult a b)). reflexivity.\n      }\n      rewrite Massoc. reflexivity.\n  Qed.\n\n  Check nat_ind.\n  Check bool_ind.\n\nEnd Inductive_types.\n\nRequire Import Setoid.\nSet Implicit Arguments.\n  \nSection Set_equality.\n\n  Parameter set : Type -> Type.\n  Context {A : Type}.\n  Parameter eq_set : set A -> set A -> Prop.\n  Axiom eq_set_refl  : forall a, eq_set a a.\n  Axiom eq_set_sym   : forall a b, eq_set a b -> eq_set b a.\n  Axiom eq_set_trans : forall a b c, eq_set a b -> eq_set b c -> eq_set a c.\n\n  Add Parametric Relation : (set A) (eq_set)\n      reflexivity  proved by eq_set_refl\n      symmetry     proved by eq_set_sym\n      transitivity proved by eq_set_trans as eq_set_rel.\n\nEnd Set_equality.\n\nSection Div_morphsim.\n\n  Let nonzero : nat -> nat -> Prop := fun x y => x = y /\\ x <> O.\n  Parameter div : nat -> nat -> nat.\n  Axiom div_repl : forall y x1 x2, nonzero x1 x2 -> div y x1 = div y x2.\n\n  Add Parametric Morphism :\n    div with signature eq ==> nonzero ==> eq as div_mor.\n  exact div_repl. Qed.\n\nEnd Div_morphsim.\n\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/Lektion01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7536388042298652}}
{"text": "(* Exercise 18 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_018 : (exists x : D, P x) \\/ (exists x : D, Q x) -> (exists x : D, P x \\/ Q x).\nProof.\nimp_i a1.\ndis_e ((exists x:D, P x) \\/ (exists x:D, Q x)) a2 a2.\nhyp a1.\nexi_e (exists x:D, P x) y a3.\nhyp a2.\nexi_i y.\ndis_i1.\nhyp a3.\nexi_e (exists x:D, Q x) y a3.\nhyp a2.\nexi_i y.\ndis_i2.\nhyp a3.\n\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_pred018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.753629484352867}}
{"text": "Inductive nat : Type :=\n    | u0\n    | S (n: nat).\n\n(* Thus 3 will be represented using S (S (S (u0))) *)\n\nFixpoint add (n: nat) (m: nat) : nat :=\n    match n with\n    | u0 => m\n    | S n' => S (add n' m)\n    end.\n", "meta": {"author": "dkodar20", "repo": "coq-adder-library", "sha": "5f23f0f9bd4b7e6bc0c733e8745d7cb4f697ac5a", "save_path": "github-repos/coq/dkodar20-coq-adder-library", "path": "github-repos/coq/dkodar20-coq-adder-library/coq-adder-library-5f23f0f9bd4b7e6bc0c733e8745d7cb4f697ac5a/Unary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7536294800613725}}
{"text": "\nVariable U : Type.\n\nDefinition set := U -> Prop.\n\nDefinition element (x:U) (S:set) := S x.\n\nDefinition subset (A B : set) := forall x:U, element x A -> element x B.\n\nDefinition transitive (T:Type) (R:T -> T -> Prop) := forall x y z: T, R x y -> R y z -> R x z.\n\nLemma subset_transitive : transitive set subset.\nunfold transitive.\nunfold subset.\nintro A.\nintro B.\nintro C.\nintro AIsIncludedInB.\nintro BIsIncludedInC.\nintro MySet.\nintro AIsIncludedInC.\napply BIsIncludedInC.\napply AIsIncludedInB.\nassumption.\nQed.\n\nPrint U.\nPrint element.\nPrint subset.\nPrint transitive.\nPrint subset_transitive.", "meta": {"author": "NickFromNormandy", "repo": "ProofsWithCoq", "sha": "5c6c356bce4087b342106a172807bf4ae3dad493", "save_path": "github-repos/coq/NickFromNormandy-ProofsWithCoq", "path": "github-repos/coq/NickFromNormandy-ProofsWithCoq/ProofsWithCoq-5c6c356bce4087b342106a172807bf4ae3dad493/definition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7535928149270547}}
{"text": "Compute (orb true false).\n\nDefinition nandb (b1 : bool) (b2 : bool) : bool :=\n  if (andb b1 b2) then false else true.\n\nExample test_nandb1 : (nandb true false) = true.\nunfold nandb.\nsimpl.\nreflexivity.\nQed.\n\nExample test_nandb2 : (nandb false false) = true.\nsimpl.\nreflexivity.\nQed.\n\nExample test_nandb3 : (nandb false true) = true.\nsimpl.\nreflexivity.\nQed.\n\nDefinition andb3 (b1 : bool) (b2 : bool) (b3 : bool) : bool :=\n  andb b1 (andb b2 b3).\n\nExample test_andb3 : andb3 true true true = true.\nsimpl.\nreflexivity.\nQed.\n\nCheck andb3.\n\nFixpoint minus (n m : nat) :=\n  match n, m with\n  | O, _       => O\n  | _ , O      => n\n  | S n', S m' => minus n' m'\n  end.\n\nCompute minus 3 2.\n\nFixpoint factorial (n : nat) : nat :=\n  match n with\n  | O   => 1\n  | S n' => n * factorial n'\n  end.\n\nCompute factorial 3.\n\nFixpoint ltb (n m : nat) : bool :=\n  match n, m with\n  | O, O       => false\n  | O, _       => true\n  | _, O       => false\n  | S n', S m' => ltb n' m'\n  end.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nCompute 10 <? 5.\nCompute 5 <? 5.\n\nExample test_ltb1 : (ltb 2 2) = false.\nsimpl.\nreflexivity.\nQed.\n\nTheorem plus_id_example : forall (n m : nat), n = m -> n + n = m + m.\nintros.\nrewrite -> H.\nreflexivity.\nQed.\n\nTheorem plus_id_exercise :\n  forall (n m o : nat), n = m -> m = o -> n + m = m + o.\nintros.\nrewrite -> H.\nrewrite -> H0.\nreflexivity.\nQed.\n\nCheck mult_n_O.\nCheck mult_n_Sm.\n\nCompute 1 * 3.\n\nTheorem mult_n_1 : forall (p : nat), p * 1 = p.\nintros.\nrewrite <- mult_n_Sm.\nrewrite <- mult_n_O.\nreflexivity.\nQed.\n\nFixpoint eqb (a b : nat) :=\n  match a, b with\n  | O, O       => true\n  | O, _       => false\n  | _, O       => false\n  | S a', S b' => eqb a' b'\n  end.\n\nNotation \"a =? b\" := (eqb a b) (at level 70) : nat_scope.\n\nTheorem plus_1_neq_0 :\n  forall (n : nat), S n =? O = false.\nintros.\ndestruct n as [|n'] eqn:E; simpl; reflexivity.\nQed.\n\nTheorem and_true_elim2 :\n  forall (b c : bool), andb b c = true -> c = true.\nintros.\ndestruct b.\n- unfold andb in H.\n  assumption.\n- unfold andb in H.\n  discriminate.\nQed.\n\nTheorem zero_nbeq_plus_1 :\n  forall (n : nat), 0 =? (n + 1) = false.\nintros [|n']; simpl; reflexivity.\nQed.\n\nFail Fixpoint failing (n : nat) (b : bool) :=\n  match b with\n  | false => n\n  | true => failing n false\n  end.\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.\nintros.\nrewrite -> H.\nrewrite -> H.\nreflexivity.\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.\nintros.\nrewrite -> H.\nrewrite -> H.\ndestruct b; simpl; reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nintros.\ndestruct b.\n- unfold andb in H.\n  unfold orb in H.\n  rewrite -> H.\n  reflexivity.\n- unfold andb in H.\n  unfold orb in H.\n  rewrite <- H.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | Z\n  | B_0 (n : bin)\n  | B_1 (n : bin).\n\nFixpoint incr (m : bin) : bin :=\n  match m with\n  | Z      => B_1 Z\n  | B_0 m' => B_1 m'\n  | B_1 m' => B_0 (incr m')\n  end.\n\nCompute incr Z.\nCompute incr (B_0 (B_0 Z)).\nCompute incr (B_0 (B_1 Z)).\nCompute incr (B_1 (B_1 Z)).\n\nFixpoint bin2nat_rec (m : bin) (power acc : nat) : nat :=\n  match m with\n  | Z      => acc\n  | B_0 m' => bin2nat_rec m' (2 * power) acc\n  | B_1 m' => bin2nat_rec m' (2 * power) (acc + power)\n  end.\n\nDefinition bin2nat (m : bin) : nat := bin2nat_rec m 1 O.\n\nCompute bin2nat Z.\nCompute bin2nat (B_0 Z).\nCompute bin2nat (B_0 (B_1 Z)).\nCompute bin2nat (B_1 (B_0 (B_1 Z))).", "meta": {"author": "yugr", "repo": "Lalambda", "sha": "0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7", "save_path": "github-repos/coq/yugr-Lalambda", "path": "github-repos/coq/yugr-Lalambda/Lalambda-0c07b626ffac2cbbce621c4f2c458ac2b0d45bb7/21/Coq/LF/01_Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7535398711164486}}
{"text": "Require Import Rfunctions.\nRequire Import Fourier.\n\nLemma l1 : forall x y z : R, Rabs (x - z) <= Rabs (x - y) + Rabs (y - z).\nintros; split_Rabs; fourier.\nQed.\n\nLemma l2 :\n forall x y : R, x < Rabs y -> y < 1 -> x >= 0 -> - y <= 1 -> Rabs x <= 1.\nintros.\nsplit_Rabs; fourier.\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/Fourier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7534849513688201}}
{"text": "Require Import Coq.Arith.Plus.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.omega.Omega.\nRequire Import Arith.\nRequire Import Peano.\nFixpoint factorial n :=\n  match n with\n  | 0 => 1\n  | S x => n * (factorial x)\n  end.\n\nFunctional Scheme factorial_ind := Induction for factorial Sort Prop.\n \nTheorem snn_le_sn :\n  forall k n, S n ^ k >= n ^ k.\nProof.\n  induction k.\n  intros.\n  simpl.  \n  auto.\n  intros.\n  simpl.  \n  assert (S n ^ k >= n^k).\n  apply IHk.\n  assert (S n ^ k + n * S n ^ k >= n * S n ^ k).\n  omega.\n  assert (n * S n ^ k >= n * n ^ k).\n  apply mult_le_compat_l.\n  apply H.\n  omega.\n  Qed.\n\nTheorem factorial_example :\n  forall n, n^n >= factorial n.\nProof.\n  intros.\n  functional induction factorial n.\n  auto.\n  assert ((S x) ^ (S x) >= (S x) ^ x).\n  simpl.\n  assert (S x ^ x + x * S x ^ x >= S x ^ x + 0).\n  apply plus_le_compat_l with (p := S x ^ x) (m := x * S x ^ x) (n := 0).\n  apply le_0_n.\n  omega.\n  assert (S x * x^x >= S x * factorial x).\n  apply mult_le_compat_l.\n  apply IHn0.\n  assert (S x ^ S x >= S x * x ^ x).\n  assert (S x ^ x >= x ^ x).\n  simpl.\n  apply snn_le_sn.\n  assert (S x * S x ^ x >= S x * x ^ x).\n  apply mult_le_compat_l.\n  apply snn_le_sn.\n  apply H2.\n  omega.\n  Qed.\n", "meta": {"author": "MichaelBurge", "repo": "goodsteins-theorem", "sha": "f2be1b02bf38a33c2aa916a48f5201af82ad30e2", "save_path": "github-repos/coq/MichaelBurge-goodsteins-theorem", "path": "github-repos/coq/MichaelBurge-goodsteins-theorem/goodsteins-theorem-f2be1b02bf38a33c2aa916a48f5201af82ad30e2/example-fixpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8152324915965391, "lm_q1q2_score": 0.7533904384898419}}
{"text": "Require Import VectorStates.\n\n(** This file contains predicates for describing the outcomes of measurement. *)\n\n(** * Probability of outcome ϕ given input ψ *)\nDefinition probability_of_outcome {n} (ϕ ψ : Vector n) : R :=\n  Cmod (inner_product ϕ ψ) ^2.\n\n(** * Probability of measuring ϕ on the first m qubits given (m + n) qubit input ψ *)\nDefinition prob_partial_meas {m n} (ϕ : Vector (2^m)) (ψ : Vector (2^(m + n))) :=\n  big_sum (fun y => probability_of_outcome (ϕ ⊗ basis_vector (2^n) y) ψ) (2^n).\n\nLemma probability_of_outcome_comm : forall {d} (ϕ ψ : Vector d),\n  probability_of_outcome ϕ ψ = probability_of_outcome ψ ϕ.\nProof.\n  intros d ψ ϕ. unfold probability_of_outcome.\n  rewrite inner_product_conj_sym.\n  rewrite Cmod_Cconj; easy.\nQed.\n\nLemma probability_of_outcome_is_norm : forall {d} (ϕ ψ : Vector d),\n  probability_of_outcome ϕ ψ = ((norm (ϕ† × ψ)) ^ 2)%R.\nProof.\n  intros d ψ ϕ.\n  unfold probability_of_outcome, Cmod, norm.\n  apply f_equal2; try reflexivity.\n  apply f_equal.\n  unfold Mmult, adjoint.\n  simpl.\n  autorewrite with R_db.\n  reflexivity.\nQed.\n\nLemma rewrite_I_as_sum : forall m n,\n  (m <= n)%nat -> \n  I m = big_sum (fun i => (basis_vector n i) × (basis_vector n i)†) m.\nProof.\n  intros.\n  induction m.\n  simpl.\n  unfold I.\n  prep_matrix_equality.\n  bdestruct_all; reflexivity.\n  simpl.\n  rewrite <- IHm by lia.\n  unfold basis_vector.\n  solve_matrix.\n  bdestruct_all; simpl; try lca. \n  all: destruct m; simpl; try lca.\n  all: bdestruct_all; lca.\nQed.\n\nLemma prob_partial_meas_alt : \n  forall {m n} (ϕ : Vector (2^m)) (ψ : Vector (2^(m + n))),\n  @prob_partial_meas m n ϕ ψ = ((norm ((ϕ ⊗ I (2 ^ n))† × ψ)) ^ 2)%R.\nProof.\n  intros.\n  rewrite kron_adjoint, id_adjoint_eq.\n  unfold prob_partial_meas.\n  rewrite norm_squared.\n  unfold inner_product, Mmult, adjoint.\n  rewrite (@big_sum_func_distr C R _ C_is_group _ R_is_group), mult_1_l.\n  apply big_sum_eq_bounded; intros. \n  unfold probability_of_outcome.\n  assert (H' : forall c, ((Cmod c)^2)%R = fst (c^* * c)).\n  { intros.\n    rewrite <- Cmod_sqr.\n    unfold RtoC.\n    simpl; lra. }\n  rewrite H'. \n  apply f_equal.\n  assert (H'' : forall a b, a = b -> a^* * a = b^* * b). { intros; subst; easy. }\n  apply H''.\n  unfold inner_product, Mmult.\n  apply big_sum_eq_bounded; intros. \n  apply f_equal_gen; auto.\n  apply f_equal.\n  unfold kron, adjoint.\n  rewrite Cconj_mult_distr.\n  rewrite Nat.div_0_l, Nat.mod_0_l, (Nat.div_small x (2^n)), (Nat.mod_small x); try nia.\n  apply f_equal_gen; auto.\n  unfold basis_vector, I.\n  bdestruct_all; try lia; simpl; try lca.\n  intros.\n  destruct a; destruct b; easy. \nQed.\n\nLemma partial_meas_tensor : \n  forall {m n} (ϕ : Vector (2^m)) (ψ1 : Vector (2^m)) (ψ2 : Vector (2^n)),\n  Pure_State_Vector ψ2 ->\n  @prob_partial_meas m n ϕ (ψ1 ⊗ ψ2) = probability_of_outcome ϕ ψ1.\nProof.\n  intros ? ? ? ? ? [H H0].\n  rewrite prob_partial_meas_alt.\n  rewrite probability_of_outcome_is_norm.\n  unfold norm, inner_product.\n  apply f_equal2; try reflexivity.\n  do 2 apply f_equal.\n  distribute_adjoint.\n  Msimpl.\n  rewrite H0.\n  Msimpl.\n  reflexivity.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/Measurement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7533904354544322}}
{"text": "Require Import Arith.\n\nDefinition lt_3 (n:nat) : bool :=\n  match n with\n  | O | 1 | 2 => true\n  | _ => false\n  end.\n\n(** Tests :\n\nCompute lt_3 45.\n\nCompute  lt_3 2.\n\nPrint lt_3.\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/lt_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7533904301927518}}
{"text": "(* 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(* Lists of booleans and related theory. *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.StdNat.\nRequire Export List.\nRequire Export Bvector.\nRequire Import micromega.Lia.\nRequire Import FCF.EqDec.\nRequire Import FCF.Fold.\nRequire Import ZArith.\nLocal Open Scope list_scope.\n\nDefinition Blist := list bool.\n\nDefinition Blist_eq_dec := (list_eq_dec bool_dec).\n\nDefinition Bvector_eq_dec(n : nat)(v1 v2 : Bvector n) : {v1 = v2} + {v1 <> v2}.\napply (EqDec_dec (Bvector_EqDec n)).\nDefined.\n\n(* shiftOut gets bits from the head of the list. *)\n(* return None when we run out *)\nFixpoint shiftOut(s : Blist)(n : nat) : option (Bvector n * Blist) :=\n  match n with\n    | 0 => Some ((@Vector.nil bool), s)\n    | S n' => \n      match s with\n        | nil => None\n        | b :: s' => \n          match (shiftOut s' n') with\n            | Some (v', s'') => Some (Vector.cons _ b _ v', s'')\n            | None => None\n          end\n      end\n  end.\n\nTheorem shiftOut_app : forall (n : nat)(s1 s1' s2 : Blist) v,\n  shiftOut s1 n = Some (v, s1') ->\n  shiftOut (s1 ++ s2) n = Some (v, s1' ++ s2).\n\n  induction n; simpl in *; intuition.\n  destruct s1; simpl in *.\n  inversion H; clear H; subst.\n  destruct s2; simpl.\n  trivial.\n  trivial.\n  inversion H; clear H; subst.\n  rewrite app_comm_cons.\n  trivial.\n  \n  destruct s1; simpl in *.\n  discriminate.\n  case_eq (shiftOut s1 n); intuition.\n  rewrite H0 in H.\n  destruct p.\n  inversion H; clear H; subst.\n  erewrite IHn; eauto.\n  \n  rewrite H0 in H.\n  discriminate.\n\nQed.\n\nLemma shiftOut_lt : forall ls n,\n  length ls < n ->\n  shiftOut ls n = None.\n  \n  induction ls; intuition; simpl in *.\n  destruct n.\n  lia.\n  trivial.\n  destruct n.\n  lia.\n  rewrite IHls.\n  trivial.\n  lia.\nQed.\n\nLemma shiftOut_Some : forall (ls : Blist) n,\n  length ls >= n ->\n  exists p, shiftOut ls n = Some p.\n  \n  induction ls; intuition; simpl in *.\n  assert (n = O).\n  lia.\n  subst.\n  exists ([], nil).\n  trivial.\n  \n  destruct n.\n  exists ([], a :: ls).\n  trivial.\n  assert (length ls >= n).\n  lia.\n  destruct (IHls n).\n  trivial.\n  destruct x.\n  econstructor.\n  rewrite H1.\n  eauto.\nQed.\n\nTheorem shiftOut_None_inv : forall n ls,\n  shiftOut ls n = None ->\n  n > length ls.\n  \n  induction n; destruct ls; intuition; simpl in *; try discriminate.\n  apply gt_n_S.\n  eapply IHn.\n  case_eq (shiftOut ls n); intuition; trivial.\n  rewrite H0 in H.\n  destruct p.\n  discriminate.\nQed.\n\nTheorem shiftOut_Some_inv : forall n ls v ls',\n  shiftOut ls n = Some (v, ls') ->\n  (n <= length ls)%nat.\n  \n  induction n; destruct ls; intuition; simpl in *; try discriminate.\n  \n  apply le_n_S.\n  case_eq (shiftOut ls n); intuition.\n  destruct p.\n  eauto.\n  \n  rewrite H0 in H.\n  discriminate.\nQed.\n\nTheorem shiftOut_correct_inv : forall n ls ls' v,\n  shiftOut ls n = Some (v, ls') ->\n  ls = (Vector.to_list v) ++ ls'.\n  \n  induction n; destruct ls; intuition; simpl in *.\n  \n  inversion H; clear H; subst.\n  simpl.\n  trivial.\n  \n  inversion H; clear H; subst.\n  simpl.\n  trivial.\n  \n  discriminate.\n  \n  case_eq (shiftOut ls n); intuition.\n  rewrite H0 in H.\n  destruct p.\n  inversion H; clear H; subst.\n  simpl.\n  f_equal.\n  apply IHn in H0.\n  subst.\n  trivial.\n  \n  rewrite H0 in H.\n  discriminate.\nQed.\n\n\n\nLemma to_list_length : forall (A : Set)(m : nat)(v : Vector.t A m),\n  length (Vector.to_list v) = m.\n  \n  induction m; intuition.\n  rewrite (vector_0 v).\n  simpl.\n  trivial.\n  \n  destruct (vector_S v).\n  destruct H.\n  subst.\n  simpl.\n  \n  f_equal. \n  eapply IHm.\nQed.\n\nDefinition of_list_length (A : Set)(m : nat)(ls : list A)(pf : length ls = m) : Vector.t A m :=\n  match pf with\n    | eq_refl => Vector.of_list ls\n  end.\n\nDefinition of_sig_list (A : Set)(m : nat)(l : {ls : list A | length ls = m}) : Vector.t A m :=\n  match l with\n    | exist _ ls pf => (of_list_length ls pf)\n  end.\n\nLemma vector_hd_cons_eq : forall(A : Set)(v : Vector.t A 1),\n  v = Vector.cons _ (Vector.hd v) _ (Vector.nil A).\n\n  intuition.\n  destruct (vector_S v).\n  destruct H.\n  subst.\n  destruct (vector_0 x0).\n  simpl.\n  trivial.\nQed.\n\nLemma shiftOut_0 : forall (s : Blist),\n  shiftOut s 0 = Some ([], s).\n\n  intuition.\n  destruct s; simpl in *; trivial.\nQed.\n\nTheorem shiftOut_S_None : forall (n : nat)(s s1 : Blist)(v1 : Bvector 1),\n  shiftOut s 1 = Some (v1, s1) ->\n  shiftOut s1 n = None ->\n  shiftOut s (S n) = None.\nAbort.\n\nTheorem shiftOut_1_None : forall (n1 n2 : nat)(s : Blist),\n  shiftOut s n1 = None ->\n  n2 >= n1 ->\n  shiftOut s n2 = None.\nAbort.\n\n(* Todo : we need a general theorem that covers these sorts of facts.  Something like:\n   shiftOut s n1 = Some(_, s1) ->\n   shiftOut s1 n2 = x ->\n   shiftOut s (n1 + n2) = x *)\n\nTheorem shiftOut_S : forall (n : nat)(s s1 s2 : Blist)(v1 : Bvector 1)(v2 : Bvector n),\n  shiftOut s 1 = Some (v1, s1) ->\n  shiftOut s1 n = Some (v2, s2) ->\n  shiftOut s (S n) = Some (Vector.cons _ (Vector.hd v1) _  v2, s2). \n\n  destruct n; intuition; simpl in *.\n  eapply eq_trans.\n  eapply H.\n  specialize (shiftOut_0 s1); intuition.\n  rewrite H0 in H1.\n  inversion H1; clear H1; subst.\n  f_equal.\n  f_equal.\n  eapply vector_hd_cons_eq.\n  \n  destruct s; intuition; simpl in *.\n  discriminate.\n  rewrite shiftOut_0 in H.\n  inversion H; clear H; subst.\n  rewrite H0.\n  f_equal.\nQed.\n\nFixpoint oneList(n : nat) : Blist :=\n  match n with\n    | 0 => nil\n    | S n' => true :: (oneList n')\n  end.\n\nTheorem oneList_length : forall n,\n  length (oneList n) = n.\n\n  induction n; intuition; simpl in *.\n  auto.\nQed.\n\n(* TODO: remove oneVector and replace it with Bvect_true *)\nFixpoint oneVector(n : nat) : Bvector n :=\n  match n with\n    | 0 => Vector.nil bool\n    | S n' => Vector.cons _ true _ (oneVector n')\n  end.\n\nTheorem shiftOut_oneList : forall (n : nat),\n  shiftOut (oneList n) n = Some (oneVector n, nil).\n\n  induction n; intuition; simpl in *.\n  rewrite IHn.\n  trivial.\nQed.\n\nFixpoint getAllBlists(n : nat) : (list Blist) :=\n  match n with\n    | 0 => nil :: nil\n    | S n' => (map (cons true) (getAllBlists n')) ++\n      (map (cons false) (getAllBlists n'))\n  end.\n\n\nFixpoint getAllBlists_app(n : nat) : list Blist :=\n  match n with\n    | 0 => nil :: nil\n    | S n' => (map (fun ls => ls ++ (true :: nil)) (getAllBlists_app n')) ++\n      (map (fun ls => ls ++ (false :: nil)) (getAllBlists_app n'))\n  end.\n\nFixpoint getAllBvectors(n : nat) : (list (Bvector n)) :=\n  match n with\n    | 0 => (Vector.nil bool) :: nil\n    | S n' => (map (Vector.cons _ true _) (getAllBvectors n')) ++\n      (map (Vector.cons _ false _) (getAllBvectors n'))\n  end.\n\nLemma getAllBvectors_length : forall n,\n  length (getAllBvectors n) = (expnat 2 n).\n  \n  induction n; intuition; simpl in *.\n  rewrite app_length.\n  repeat rewrite map_length.\n  rewrite plus_0_r.\n  f_equal; eauto.\nQed.\n\nLemma getAllBvectors_length_nz : forall n,\n  length (getAllBvectors n) > 0.\n  \n  induction n; intuition; simpl in *.\n  rewrite app_length.\n  repeat rewrite map_length.\n  rewrite <- plus_0_r.\n  eapply gt_trans.\n  eapply plus_gt_compat_l.\n  apply IHn.\n  repeat rewrite plus_0_r.\n  apply IHn.\nQed.\n\nTheorem in_getAllBvectors : forall (n : nat)(v : Bvector n),\n  In v (getAllBvectors n).\n\n  induction v; intuition; simpl.\n  auto.\n  eapply in_or_app; intuition.\n  destruct h.\n  left.\n  eapply in_map; eauto.\n  right.\n  eapply in_map; eauto.\nQed.\n\nLemma vector_tl_eq : forall (A : Set)(n : nat)(v1 v2 : Vector.t A (S n)),\n  v1 = v2 ->\n  Vector.tl v1 = Vector.tl v2.\n  \n  intuition.\n  specialize (vector_S v1).\n  specialize (vector_S v2).\n  intuition.\n  destruct H0. destruct H0.\n  destruct H1. destruct H1.\n  subst.\n  simpl.\n  trivial.\nQed.\n\nLemma vector_cons_eq : forall (A : Set)(n : nat)(v1 v2 : Vector.t A n)(a1 a2 : A),\n  Vector.cons A a1 n v1 = Vector.cons A a2 n v2 ->\n  v1 = v2.\n\n  intuition.\n  \n  apply vector_tl_eq in H.\n  simpl in *.\n  trivial.\n\nQed.\n\nLemma vector_cons_ne : forall (A : Set)(n : nat)(a1 a2 : Vector.t A n)(a : A),\n  a1 <> a2 -> \n  Vector.cons A a n a1 <> Vector.cons A a n a2.\n\n  intuition.\n  eapply H.\n  eapply vector_cons_eq.\n  eauto.\nQed.\n\nLemma map_NoDup : forall (A B : Set)(ls : list A)(f : A -> B),\n  NoDup ls ->\n  (forall a1 a2, a1 <> a2 -> (f a1) <> (f a2)) ->\n  NoDup ((map f) ls).\n\n  induction ls; intuition; simpl in *.\n\n  econstructor.\n\n  inversion H; subst; clear H.\n  econstructor.\n  intuition.\n  apply in_map_iff in H.\n  destruct H.\n  intuition.\n  eapply H0; eauto.\n  intuition.\n  subst.\n  intuition.\n\n  eapply IHls; eauto.\nQed.\n\nLemma getAllBvectors_NoDup : forall (n : nat),\n  NoDup (getAllBvectors n).\n\n  induction n; intuition; simpl in *.\n  econstructor.\n  eapply in_nil.\n  econstructor.\n\n  eapply app_NoDup.\n  eapply map_NoDup; eauto.\n  intros.\n  eapply vector_cons_ne; eauto.\n  \n  eapply map_NoDup; eauto.\n  intros.\n  \n  eapply vector_cons_ne; eauto.\n\n  intuition.\n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  inversion H.\n\n  intuition.\n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  inversion H.\nQed.\n\nRequire Import Permutation.\n\nLemma getAllBlists_NoDup : forall n,\n  NoDup (getAllBlists n).\n  \n  induction n; intuition; simpl in *.\n  econstructor.\n  simpl.\n  intuition.\n  econstructor.\n  \n  eapply app_NoDup; intuition.\n  \n  eapply map_NoDup; intuition.\n  eapply H.\n  inversion H0; subst; intuition.\n  \n  eapply map_NoDup; intuition.\n  eapply H.\n  inversion H0; subst; intuition.\n  \n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  discriminate.\n  \n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  discriminate.\n  \nQed.\n\nLemma getAllBlists_app_NoDup : forall n,\n  NoDup (getAllBlists_app n).\n  \n  induction n; intuition; simpl in *.\n  econstructor.\n  simpl.\n  intuition.\n  econstructor.\n  \n  eapply app_NoDup; intuition.\n  \n  eapply map_NoDup; intuition.\n  eapply H.\n  apply app_inj_tail in H0.\n  intuition.\n  \n  eapply map_NoDup; intuition.\n  eapply H.\n  eapply app_inj_tail in H0.\n  intuition.\n  \n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  apply app_inj_tail in H; intuition.\n  \n  apply in_map_iff in H.\n  apply in_map_iff in H0.\n  destruct H.\n  destruct H0.\n  intuition.\n  subst.\n  apply app_inj_tail in H; intuition.\n\nQed.\n    Lemma ls_last_exists : forall (A : Type)(ls : list A) n,\n      length ls = (S n) ->\n      exists a ls', (length ls' = n /\\ ls = ls' ++ (a :: nil)).\n\n      induction ls; intuition; simpl in *.\n      lia.\n\n      destruct n.\n      destruct ls; simpl in *; try lia.\n      exists a. exists nil.\n      simpl.\n      intuition.\n\n      inversion H; clear H.\n      edestruct IHls; intuition.\n      eauto.\n      destruct H.\n      intuition.\n      exists x.\n      exists (a :: x0).\n      subst.\n      simpl.\n      intuition.\nQed. \n\nLemma getAllBlists_app_rel_map : forall n,\n  rel_map (fun ls1 ls2 => ls1 = (rev ls2)) (getAllBlists_app n) (getAllBlists n).\n\n  induction n; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  simpl.\n  trivial.\n\n  eapply rel_map_app.\n  eapply rel_map_map2.\n  \n  eapply rel_map_impl; eauto; intuition.\n  subst.\n  simpl.\n  trivial.\n\n  eapply rel_map_map2.\n  \n  eapply rel_map_impl; eauto; intuition.\n  subst.\n  simpl.\n  trivial.\nQed.\n\nLemma getAllBlists_rel_map : forall n,\n  rel_map (fun ls1 ls2 => ls1 = (rev ls2)) (getAllBlists n) (getAllBlists_app n).\n\n  induction n; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  trivial.\n\n  eapply rel_map_app.\n  eapply rel_map_map2.\n  eapply rel_map_impl; eauto; intuition.\n  subst.\n  rewrite rev_unit.\n  trivial.\n\n  eapply rel_map_map2.\n  eapply rel_map_impl; eauto; intuition.\n  subst.\n  rewrite rev_unit.\n  trivial.    \nQed.\n\nLemma getAllBlists_app_In_length : forall n ls,\n  In ls (getAllBlists_app n) ->\n  length ls = n.\n\n  induction n; intuition; simpl in *.\n  destruct H; subst; intuition.\n\n  apply in_app_or in H;\n  destruct H;\n  apply in_map_iff in H;\n  destruct H;\n  intuition;\n\n  subst;\n  rewrite app_length; simpl;\n  rewrite plus_comm; simpl;\n  f_equal;\n  eapply IHn; eauto.\nQed.\n\n\nLemma getAllBlists_app_length_In : forall n ls,\n  length ls = n ->\n  In ls (getAllBlists_app n).\n\n  induction n; intuition; simpl in *;\n  destruct ls; simpl in *; intuition; try lia.\n\n\n\n  edestruct (ls_last_exists (b :: ls)).\n  simpl.\n  eauto.\n  destruct H0.\n  intuition.\n  rewrite H2.\n  eapply in_or_app.\n  destruct x; [left | right];\n  eapply in_map_iff;\n  econstructor; intuition.\n\nQed.\n\nLemma getAllBlists_In_length : forall n ls,\n  In ls (getAllBlists n) ->\n  length ls = n.\n\n  induction n; intuition; simpl in *.\n  destruct H; subst; intuition.\n\n  apply in_app_or in H;\n  destruct H;\n  apply in_map_iff in H;\n  destruct H;\n  intuition;\n\n  subst;\n  simpl;\n  f_equal;\n  eapply IHn; eauto.\nQed.\n\nLemma getAllBlists_length_In : forall n ls,\n  length ls = n ->\n  In ls (getAllBlists n).\n\n  induction n; intuition; simpl in *;\n  destruct ls; simpl in *; intuition; try lia.\n\n  apply in_or_app.\n \n  destruct b; [left | right];\n  eapply in_map_iff; eauto.\nQed. \n\nLemma getAllBlists_perm : forall n,\n  Permutation (getAllBlists n) (getAllBlists_app n).\n\n  intuition.\n  eapply NoDup_Permutation.\n\n  apply getAllBlists_NoDup.\n  apply getAllBlists_app_NoDup.\n\n  intuition.\n\n  specialize (getAllBlists_rel_map n); intuition.\n  specialize (rel_map_in_inv H0 x); intuition.\n  destruct H2.\n  intuition.\n  subst.\n\n  eapply getAllBlists_app_length_In.\n  rewrite rev_length.\n  eapply getAllBlists_app_In_length.\n  eauto. \n\n  specialize (getAllBlists_app_rel_map n); intuition.\n  specialize (rel_map_in_inv H0 x); intuition.\n  destruct H2.\n  intuition.\n  subst.\n  eapply getAllBlists_length_In.\n  rewrite rev_length.\n  eapply getAllBlists_In_length.\n  eauto.\nQed.\n\nTheorem getAllBlists_length : forall n,\n  length (getAllBlists n) = (expnat 2 n).\n  \n  induction n; intuition; simpl in *.\n  rewrite app_length.\n  repeat rewrite map_length.\n  rewrite plus_0_r.\n  rewrite <- IHn.\n  trivial.\nQed.\n\nDefinition tailOpt(A : Set)(n : nat)(v : Vector.t A n) : option (Vector.t A (pred n)):=\n  match v with\n    | [] => None\n    | Vector.cons _ _ _ v => Some v\n  end.\n\nLemma tailOpt_eq : forall (A : Set)(n : nat)(v1 v2 : Vector.t A n),\n  v1 = v2 ->\n  tailOpt v1 = tailOpt v2.\n          \n  intuition.\n  subst.\n  trivial.\nQed.\n\nLemma vector_cons_eq_inv : forall (A : Set)(n : nat)(a1 a2 : A)(v1 v2 : Vector.t A n),\n  Vector.cons A a1 n v1 = Vector.cons A a2 n v2 ->\n  a1 = a2 /\\ v1 = v2.\n  \n  intuition.\n  inversion H; trivial.\n  \n  assert (tailOpt (Vector.cons A a1 n v1) = tailOpt (Vector.cons A a2 n v2)).\n  \n  eapply tailOpt_eq.\n  trivial.\n  \n  simpl in *.\n  inversion H0; clear H0; subst.\n  trivial.            \nQed.\n\nLemma pair_eq_inv : forall (A B : Type)(a1 a2 : A)(b1 b2 : B),\n  (a1, b1) = (a2, b2) ->\n  a1 = a2 /\\ b1 = b2.\n  \n  intros.\n  inversion H; clear H; subst.\n  intuition.\nQed.\n\nLemma opt_eq_inv : forall (A : Type)(a1 a2 : A),\n  Some a1 = Some a2 ->\n  a1 = a2.\n  \n  intuition.\n  inversion H; clear H; subst.\n  trivial.\nQed.\n\nLemma shiftOut_ls_eq : forall n ls1 ls2 v ls1' ls2',\n  shiftOut ls1 n = Some (v, ls1') ->\n  shiftOut ls2 n = Some (v, ls2') ->\n  (firstn n ls1) = (firstn n ls2).\n  \n  induction n; intuition; simpl in *.\n  destruct ls1; simpl in *; try discriminate.\n  destruct ls2; simpl in *; try discriminate.\n  case_eq (shiftOut ls1 n); intuition.\n  rewrite H1 in H.\n  case_eq (shiftOut ls2 n); intuition.\n  rewrite H2 in H0.\n  destruct p.\n  destruct p0.\n  inversion H; clear H; subst.\n  \n  apply opt_eq_inv in H0.\n  apply pair_eq_inv in H0; intuition.\n  apply vector_cons_eq_inv in H; intuition; subst.\n  \n  f_equal.\n  eapply IHn.\n  eapply H1.\n  eapply H2.\n  \n  rewrite H2 in H0.\n  discriminate.\n  rewrite H1 in H.\n  discriminate.\nQed.\n\nLemma le_refl_gen : forall n1 n2,\n  (n1 = n2 ->\n    n1 <= n2)%nat.\n  \n  intuition.\nQed.\n\nLemma app_first_eq : forall (A : Type)(ls2 ls1 ls3 : list A),\n  ls1 = ls2 ++ ls3 ->\n  length ls1 = length ls2 ->\n  ls1 = ls2 /\\ ls3 = nil.\n  \n  intros; subst.\n  assert (ls3 = nil).\n  rewrite app_length in H0.\n  assert (length ls3 = O).\n  lia.\n  destruct ls3; simpl in *; try lia; trivial.\n  subst.\n  rewrite app_nil_r.\n  intuition.\nQed.\n\nLemma to_list_eq_inv : forall (A : Set) n (v1 v2 : Vector.t A n),\n  VectorDef.to_list v1 = VectorDef.to_list v2 ->\n        v1 = v2.\n  \n  induction n; intuition.\n  rewrite (vector_0 v2).\n  rewrite (vector_0 v1).\n  trivial.\n  \n  destruct (vector_S v1).\n  destruct (vector_S v2).\n  destruct H0. \n  destruct H1.\n  subst.\n  unfold VectorDef.to_list in *.\n  inversion H; clear H; subst.\n  f_equal.\n  eauto.\nQed.\n\nLemma shiftOut_to_list : forall n (v : Bvector n),\n  shiftOut (VectorDef.to_list v) n = Some (v, nil).\n  \n  intuition.\n  \n  edestruct (shiftOut_Some (VectorDef.to_list v)).\n  eapply le_refl_gen.\n  symmetry.\n  eapply (to_list_length v).\n  destruct x.\n  rewrite H.\n  apply shiftOut_correct_inv in H.\n  \n  \n  apply app_first_eq in H.\n  intuition; subst.\n  \n  \n  apply to_list_eq_inv in H0; subst.\n  trivial.\n  \n  repeat rewrite to_list_length.\n  trivial.\nQed.\n\nLemma shiftOut_app_None : forall ls1 ls2 n,\n  shiftOut (ls1 ++ ls2) n = None ->\n  shiftOut ls1 n = None.\n  \n  induction ls1; intuition; simpl in *.\n  destruct n; destruct ls2; try discriminate; trivial.\n  \n  destruct n.\n  discriminate.\n  \n  case_eq (shiftOut (ls1 ++ ls2) n); intuition.\n  rewrite H0 in H.\n  destruct p.\n  discriminate.\n  rewrite H0 in H.\n  erewrite IHls1.\n  trivial.\n  eauto.\n  \nQed.\n\nLemma BVxor_same_id : forall n (v : Bvector n),\n  BVxor n v v = Bvect_false n.\n\n  induction n; intuition.\n  rewrite (vector_0 v).\n  simpl.\n  unfold Bvect_false.\n  simpl.\n  trivial.\n\n  destruct (vector_S v).\n  destruct H.\n  rewrite H.\n  unfold Bvect_false.\n  simpl.\n  rewrite IHn.\n  rewrite xorb_nilpotent.\n  trivial.\n\nQed.\n\nLemma BVxor_comm : forall n (v1 v2 : Bvector n),\n  BVxor n v1 v2 = BVxor n v2 v1.\n\n  induction n; intuition.\n  rewrite (vector_0 v1).\n  rewrite (vector_0 v2).\n  trivial.\n\n  destruct (vector_S v1).\n  destruct H.\n  destruct (vector_S v2).\n  destruct H0.\n  subst.\n  simpl.\n  rewrite IHn.\n  rewrite xorb_comm.\n  trivial.\nQed.\n\nLemma BVxor_id_r : forall n (v : Bvector n),\n  BVxor n v (Bvect_false n) = v.\n\n  induction n; intuition.\n  rewrite (vector_0 v).\n  unfold Bvect_false.\n  simpl.\n  trivial.\n\n  destruct (vector_S v).\n  destruct H.\n  unfold Bvect_false.\n  subst.\n  simpl.\n  rewrite IHn.\n  rewrite xorb_false_r.\n  trivial.\nQed.\n\n\nLemma BVxor_id_l : forall n (v : Bvector n),\n  BVxor n (Bvect_false n) v = v.\n\n  intuition.\n  rewrite BVxor_comm.\n  apply BVxor_id_r.\nQed.\n\nLemma BVxor_assoc : forall n (v1 v2 v3 : Bvector n),\n  BVxor n (BVxor n v1 v2) v3 = BVxor n v1 (BVxor n v2 v3).\n  \n  induction n; intuition.\n  rewrite (vector_0 v1).\n  rewrite (vector_0 v2).\n  rewrite BVxor_same_id.\n  rewrite BVxor_id_l.\n  rewrite (vector_0).\n  rewrite (vector_0 v3).\n  trivial.\n\n  destruct (vector_S v1).\n  destruct H.\n  destruct (vector_S v2).\n  destruct H0.\n  destruct (vector_S v3).\n  destruct H1.\n  subst.\n  simpl.\n  rewrite IHn.\n  rewrite xorb_assoc.\n  trivial.\nQed.\n\nLemma BVxor_id_r_inv : forall n (v1 v2 : Bvector n),\n  BVxor n v1 v2 = v1 ->\n  v2 = (Bvect_false n).\n\n  intuition.\n  rewrite <- BVxor_id_l at 1.\n  rewrite <- (BVxor_same_id v1).\n  rewrite BVxor_assoc.\n  f_equal; intuition.\nQed.\n\nLemma BVxor_id_inv : forall n (v1 v2 : Bvector n),\n  BVxor n v1 v2 = Bvect_false n ->\n  v1 = v2.\n\n  intuition.\n  rewrite <- BVxor_id_l at 1.\n  rewrite <- (BVxor_id_l v2).\n  rewrite <- (BVxor_same_id v2) at 1.\n  rewrite BVxor_assoc.\n  rewrite BVxor_comm.\n  f_equal; intuition.\n  rewrite BVxor_comm.\n  trivial.\nQed.\n\n\nDefinition lognat(n : nat) : nat := \n  N.to_nat (N.size (N.of_nat n)).\n\nLemma lognat_monotonic : forall n1 n2,\n  (n1 < n2 ->\n    lognat n1 <= lognat n2)%nat.\nProof.\n  intros ? ? H.\n  pose proof N.log2_le_mono (N.of_nat n1) (N.of_nat n2).\n  case n1, n2; try (cbn; lia); cbv [lognat]; rewrite !N.size_log2; try lia.\nQed.\n\nLemma lt_pow2_lognat k n : lognat k <= n -> k < 2^n.\nProof.\n  cbv [lognat]; intros H; destruct k; [pose proof Nat.pow_eq_0_iff 2 n; lia|].\n  enough (N.of_nat (S k) < N.of_nat (2^n))%N by lia; rewrite Nnat.Nat2N.inj_pow.\n  rewrite !N.size_log2, Nnat.N2Nat.inj_succ in H by lia.\n  apply N.log2_lt_pow2; lia.\nQed.\n\n\nFixpoint bvToNat(k : nat)(v : Bvector k) :=\n  match v in Vector.t _ k with\n  | Vector.nil _ => 0\n  | Vector.cons _ b _ v => Nat.b2n b + Nat.double (bvToNat v)\n  end.\n\nLemma bvNat_zero : forall n, \n  bvToNat (Bvect_false n) = O.\nProof. induction n; cbn; rewrite ?IHn; trivial. Qed.\n\nFixpoint natToBv(k : nat)(v : nat) : Bvector k :=\n  match k with\n  | 0 => Vector.nil _\n  | S k => Vector.cons _ (Nat.odd v) _ (natToBv k (Nat.div2 v))\n  end.\n\nLemma bvToNat_natToBv : forall n k,\n  bvToNat (natToBv n k) = k mod (2 ^ n).\nProof.\n  induction n; cbn [bvToNat natToBv]; trivial; intros.\n  cbn [Nat.pow]; rewrite Nat.Div0.mod_mul_r; setoid_rewrite Nat.bit0_mod; f_equal.\n  rewrite IHn, Nat.div2_div, Nat.double_twice; trivial.\nQed.\n\nLemma bvToNat_natToBv_inverse : forall n k,\n  n >= lognat k ->\n  bvToNat (natToBv n k) = k.\nProof.\n  intros; rewrite bvToNat_natToBv, Nat.mod_small; auto using lt_pow2_lognat.\nQed.\n\nLemma natToBv_bvToNat_inverse : forall n k,\n  (natToBv n (bvToNat k)) = k.\nProof.\n  symmetry.\n  induction k; cbn; trivial; f_equal.\n  { rewrite Nat.odd_add_even by (exists (bvToNat k); cbv[Nat.double]; lia).\n    symmetry; apply Nat.b2n_bit0. }\n  rewrite Nat.div2_div, Nat.double_twice, Nat.add_b2n_double_div2; trivial.\nQed.\n\nLemma bvToNat_natToBv_eq : forall n (v : Bvector n) k,\n  bvToNat v = k ->\n  v = natToBv n k.\nProof. pose proof natToBv_bvToNat_inverse. congruence. Qed.\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/Blist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7533039003694278}}
{"text": "(* Set is the type of \"computational types\" *)\nCheck nat.\nCheck nat -> nat.\nCheck bool.\nCheck bool -> nat.\n\n(* Prop is the type of propositions *)\nCheck (forall (x : nat), x <> S x).\nCheck (forall (P : Prop), P -> P).\nCheck (true <> false).\n\n(* Type is the type of Set and Prop (and Type of Type_n has type Type_(1 + n) *)\nCheck Set.\nCheck Prop.\nCheck Type.\n\n\n(* \nThe difference between Prop and Set is that Prop is \"impredicative\" which means\nthat when quantifying over P : Prop in a Prop this quantification is quantifying\nover _itself_ as well. This kind of circularity can in some cases lead to\ninconsistencies (i.e. that False is provable), compare with Russels paradox. To\navoid this impredicativity in Coq is restricted to Prop (which is ok). This\nmeans that neither Set nor Type are impredicative. Note that Agda is completely\npredicative.\n\nNice examples of impredicativity of Prop can be found in:\n   https://sympa.inria.fr/sympa/arc/coq-club/2012-07/msg00129.html\n\nThe simplest one follow below:\n*)\n\nDefinition ModusPonens_Prop := forall P Q : Prop, (P -> Q) -> P -> Q.\n\n (* This is a Prop *)\nCheck ModusPonens_Prop.\n\nTheorem ModusPonens_Prop_proof : ModusPonens_Prop.\nProof. unfold ModusPonens_Prop; auto. Qed.\n\n(* It can be applied to itself, i.e., P and Q can be instantiated to\n   ModusPonens_Prop. *)\nCheck ModusPonens_Prop_proof ModusPonens_Prop ModusPonens_Prop.\n\n(* The same thing for Set: *)\nDefinition ModusPonens_Set := forall P Q : Set, (P -> Q) -> P -> Q.\n\n(* This is a Type... *)\nCheck ModusPonens_Set.\n\nTheorem ModusPonens_Set_proof : ModusPonens_Set.\nProof. unfold ModusPonens_Set; auto. Qed.\n\n(* So the following is not possible as ModusPonens_Set is a Type, not a Set: *)\n(* Check ModusPonens_Set_proof ModusPonens_Set ModusPonens_Set. *)\n\n(* The same for Type *)\nDefinition ModusPonens_Type := forall P Q : Type, (P -> Q) -> P -> Q.\n\n(* This is also a Type, but with higher level. Sadly the level cannot be seen in\n   Coq... But if P and Q above have Type_m then ModusPonens_Type has Type_n with\n   the constraint that m < n *) \nCheck ModusPonens_Type.\n\nTheorem ModusPonens_Type_proof : ModusPonens_Type.\nProof. unfold ModusPonens_Type; auto. Qed.\n\n(* This produces an error because ModusPonens_Type_proof is expecting things of\n   type Type_m but ModusPonens_proof has type Type_n where m < n *)\n(* Check ModusPonens_Type_proof ModusPonens_Type ModusPonens_Type. *)\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/examples/set_prop_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7533038886502773}}
{"text": "Require Export D.\n\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q) -> P) -> P.\n\nDefinition classic := forall P:Prop,\n  ~~P -> P.\n\nDefinition excluded_middle := 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 double_neg : forall P:Prop,\nP -> ~~P.\nProof.\n  intros P. intros HP. unfold not. intros HNP.  apply HNP in HP. inversion HP. Qed.\n\nTheorem classic_double_net : forall P:Prop,\n  ~~P -> P.\nProof.\n  intros P H. unfold not in H. intros H.  \n  Lemma p_false : forall P:Prop,\n  (P -> False) <-> ~P.\n  Proof. intros P. split.\n<F2>\n unfold not in H.\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/prac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7532918462835864}}
{"text": "Require Import prosa.classic.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": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/classic/util/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7532915163009232}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Lt.\nRequire Import Coq.Arith.Gt.\nRequire Import Arith.Wf_nat.\nRequire Import Recdef.\n\nOpen Scope nat_scope.\n\nImport ListNotations.\n\n\n(* Auxiliary definitions and lemmas *)\nDefinition max (a b : nat) :=\n    match nat_compare a b with\n    | Lt => b\n    | _  => a\n    end.\n\nInductive tree :=\n    | Tip :\n        nat (* height of the tree it represents *)\n        -> tree\n    | Bin :\n        nat (* height *)\n        -> tree (* left child *)\n        -> tree (* right child *)\n        -> tree.\n\n\n(* functions on trees *)\nDefinition ht (t : tree) :=\n    match t with\n    | Tip n     => n\n    | Bin n _ _ => n\n    end.\n\nDefinition join (x y : tree) : tree :=\n    Bin (max (ht x) (ht y) + 1) x y.\n\nFixpoint flatten (t : tree) : list tree :=\n    match t with\n    | Tip n       => Tip n :: nil\n    | Bin n t1 t2 => flatten t1 ++ flatten t2\n    end.\n\nFixpoint siblings (t : tree) (a b : tree) : Prop :=\n    match t with \n    | Tip _     => False\n    | Bin _ x y => a = x /\\ b = y \\/ siblings x a b \\/ siblings y a b\n    end.\n\n(* local minimum pair *)\nInductive lmp : tree -> tree -> list tree -> Set :=\n    | lmp_pair :\n        forall (a b : tree), lmp a b (a :: b :: nil)\n\n    | lmp_threel :\n        forall (a b x : tree),\n            (ht a < ht b /\\ ht x >= ht b) \\/ ht b <= ht a  ->  lmp a b (x :: a :: b :: nil)\n\n    | lmp_threer :\n        forall (a b y : tree) (l : list tree),\n            (ht a < ht b /\\ ht b < ht y) \\/ ht b <= ht a /\\ ht a < ht y\n            -> lmp a b (a :: b :: y :: l)\n\n    | lmp_left :\n        forall (a b x y : tree) (l l1 l2 : list tree),\n            (l = l1 ++ (x :: a :: b :: y :: l2))\n            -> ht b <= ht a\n            -> ht b < ht y\n            -> lmp a b l\n\n    | lmp_right :\n        forall (a b x y : tree) (l l1 l2 : list tree),\n            (l = l1 ++ (x :: a :: b :: y :: l2))\n            -> ht a < ht b\n            -> ht b < ht y\n            -> ht x >= ht b\n            -> lmp a b l.\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/Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7532914987295819}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.\n\nDefinition id :\n    forall A : Type, A -> A\n:=\n    fun A : Type => fun x : A => x.\nCompute id bool true.\nCompute id nat 34.\n\n(* Dependent types, wow! Type of return value depends on argument *)\nCheck id bool : bool -> bool.\nCheck id nat : nat -> nat.\n\n(* A function of type like forall x : A, B is called a dependently\n   typed function from A to B(x) where B(x) meand that B may refer\n   to x and B is usually called a family of types *)\nLocate \"->\".\n(* (forall _ : A, B) - independent, because of _ *)\n\n(* type <=> implementation *)\nDefinition id' :\n    forall A : Type , forall _ : A ,  A\n:=\n       fun A : Type =>   fun x : A => x.\n\n(* Product Type *)\nInductive prodn : Type := | pairn of nat & nat.\n\nInductive prod (A B : Type) : Type :=\n    | pair of A & B.\n(* prod is a type constructor, not a type! *)\nFail Check prod : Type.\nCheck prod nat nat : Type.\n\n(* 4 arguments!.. - all type parametres of prod are inherited by pair *)\nCheck pair.\nCheck pair nat bool 34 true.\n\n(* Implicit arguments *)\nArguments id [A] _.\nArguments pair [A B] _ _.\n\nCheck id 34.\nCompute id 33.\nFail Check pair nat bool 33 true : prod nat bool.\nCheck @pair nat bool 33 true : prod nat bool.\nSet Implicit Arguments.\nCheck pair 42 true : prod nat bool.\n\n(* Notations *)\nNotation \"A * B\" :=\n    (prod A B)\n    (at level 40, left associativity)\n    : type_scope.\n\nLocate \"*\".\nFail Check nat * bool.\nCheck (nat * bool)%type.\nCheck (nat * bool) : Type.\n\nOpen Scope type_scope.\nLocate \"*\".\nCheck nat * bool.\nFail Check 34 * 34.\nClose Scope type_scope.\n\n(* Left assoc example *)\nCheck ((nat * bool) * nat)%type.\nCheck (nat * bool * nat)%type.\nCheck (nat * (bool * nat))%type.\n\nNotation \"( p ; q )\" := (pair p q).\nCheck (1; false).\n\nNotation \"( p , q , .. , r )\" :=\n    (pair .. (pair p q) .. r) : core_scope.\nCheck (1, false) : nat * bool.\nCheck (1, false, 3) : nat * bool * nat.\nCheck (1, false, 3, true) : nat * bool * nat * bool.\n\nDefinition fst {A B : Type} : A * B -> A :=\n    fun p =>\n        match p with\n        | (a, _) => a\n        end.\nCheck fst.\n\nDefinition snd {A B : Type} : A * B -> B :=\n    fun p =>\n        match p with\n        | (_, b) => b\n        end.\nNotation \"p .1\" := (fst p).\nNotation \"p .2\" := (snd p).\nCompute (43, true).1.\nCompute (43, true).2.\n\nDefinition swap {A B : Type} : A * B -> B * A :=\n    fun p =>\n        match p with\n        | (a,b) => (b, a)\n        end.\nCompute swap (34, true).\n\n(* Sum Type *)\nInductive sum (A B : Type) : Type :=\n    | inl of A\n    | inr of B.\nNotation \"A + B\" :=\n    (sum A B) (at level 50, left associativity)\n    : type_scope.\nDefinition swap_sum {A B : Type} :\n    A + B -> B + A :=\n    fun s =>\n        match s with\n        | inl a => inr B a\n        | inr b => inl A b\n        end.\n\n", "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/lecture2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7532830206140192}}
{"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.\nHint Immediate  reflect_elim reflect_intro. \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.\nHint Immediate reflect_EM reflect_dec.\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": "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/GenReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7532617200683708}}
{"text": "Require Import ssreflect.\n\n(**\n# 第2回 証明済みの定理の利用・量化や等式を含む命題に関する証明 (2014/04/13)\n\nhttp://qnighy.github.io/coqex2014/ex2.html\n\n## 課題10 (種別:C / 締め切り : 2014/05/04)\n\n次の定理を証明せよ。\n*)\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\n(*\n証明の内容は、以下に忠実なものである。\n\n[Coq][Math] From left unit and left inverse to right unit and inverse.\n\nhttp://study-func-prog.blogspot.jp/2014/04/coqmath-from-left-unit-and-left-inverse.html\n*)\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  move=> x.\n  rewrite -{1}(one_unit_l x).\n  rewrite -{1}(inv_l (inv x)).\n  rewrite -[/ / x * / x * x]mult_assoc.\n  rewrite (inv_l).\n  rewrite -mult_assoc.\n  rewrite one_unit_l.\n  rewrite inv_l.\n  by [].\nQed.\n\nLemma one_unit_r : forall x, x * 1 = x.\nProof.\n  move=> x.\n  rewrite -{1}(one_unit_l x).\n  rewrite -{1}(inv_l (inv x)).\n  rewrite -{1}(inv_l x).\n  rewrite mult_assoc.\n  rewrite -[/ / x * / x * x]mult_assoc.\n  rewrite (inv_l).\n  rewrite -mult_assoc.\n  rewrite -mult_assoc.\n  rewrite one_unit_l.\n  rewrite mult_assoc.\n  rewrite (inv_l (/ x)).\n  by [].\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/ex2014/ex10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7532567191099052}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require 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. *)\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_claim : Prop := 2 + 2 = 4.\nCheck plus_claim.\n(* ===> plus_claim : 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_claim_is_true :\n  plus_claim.\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. injection H as H1. apply H1.\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  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, standard (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  (* SOLUTION: *)\n    intros [|n] m.\n  - (* n = 0 *)\n    simpl. intros H. split.\n    + reflexivity.\n    + apply H.\n  - (* n = S n' *)\n    simpl. intros H. discriminate 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  (* 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\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    In such cases we can do a [destruct] (possibly as part of\n    an [intros]) and use an underscore pattern [_] to indicate \n    that the unneeded conjunct should just be thrown away. \n    This is illustrated in the following proofs: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q HPQ. \n  destruct HPQ as [HP _].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* SOLUTION: *)\n  intros P Q [_ HQ].\n  apply HQ.  Qed.\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  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n\n(** **** Exercise: 2 stars, standard (and_assoc)  \n\n    (In the following proof of associativity, notice how the _nested_\n    [intros] 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  (* SOLUTION: *)\n  split.\n  - (* left *) split.\n    + (* left *) apply HP.\n    + (* right *) apply HQ.\n  - (* right *) apply HR.  Qed.\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.  (This infix notation stands for [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    explicitly with [destruct] or implicitly with an [intros] pattern: *)\n\nLemma eq_mult_0 :\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_l : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and here is a slightly more interesting example requiring both\n    [left] and [right]: *)\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  (* SOLUTION: *)\n  intros [|n] m H.\n  - left. reflexivity.\n  - destruct m as [|m].\n    + right. reflexivity.\n    + 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  (* SOLUTION: *)\n  intros P Q [HP | HQ].\n  - (* left *) right. apply HP.\n  - (* right *) 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 some given proposition is _not_\n    true. In Coq, such statements are expressed with the negation\n    operator [~]. *)\n\n(** To see how negation works, recall the _principle of explosion_\n    from the [Tactics] chapter; it asserts that, if we assume a\n    contradiction, then any other proposition can be derived.\n\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].\n\n    Coq actually makes a slightly different (but equivalent) choice,\n    defining [~ P] as [P -> False], where [False] is a specific\n    contradictory proposition defined in the standard 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] 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  (* SOLUTION: *)\n  intros P H Q HP. apply ex_falso_quodlibet. apply H. apply HP.\nQed.\n(** [] *)\n\n(** Inequality is a frequent enough example of negated statement\n    that there is a special notation for it, [x <> y]:\n\n      Notation \"x <> y\" := (~(x = y)).\n*)\n\n(** We can use [not] to state that [0] and [1] are different elements\n    of [nat]: *)\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  (** The proposition [0 <> 1] is exactly the same as\n      [~(0 = 1)], that is [not (0 = 1)], which unfolds to\n      [(0 = 1) -> False]. (We use [unfold not] explicitly here\n      to illustrate that point, but generally it can be omitted.) *)\n  unfold not.\n  (** To prove an inequality, we may assume the opposite\n      equality... *)\n  intros contra.\n  (** ... and deduce a contradiction from it. Here, the\n      equality [O = S O] contradicts the disjointness of\n      constructors [O] and [S], so [discriminate] takes care\n      of it. *)\n  discriminate contra.\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 (double_neg_inf)  \n\n    Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P]. *)\n\n(* SOLUTION: *)\n(* _Proof_:\n   Let a proposition [P] be given, and suppose we have\n   evidence for [P].  We must show [~~P] -- i.e., [~P -> False], so\n   suppose [~P] as well and try to derive [False].\n   Then we have both [P] and [~P] (i.e., [P -> False]) from which\n   we can indeed derive [False].  So [~~P] holds. *)\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  (* SOLUTION: *)\n  intros P Q H HNotB HP.\n  apply HNotB.  apply H. apply HP.  Qed.\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  (* SOLUTION: *)\n  intros P H. destruct H as [HP HNA]. apply HNA. apply HP.  Qed.\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(* SOLUTION: *)\n(* _Proof_: Suppose, for some [P], that [(P /\\ ~P)] holds.  Recall\n  that [~P] is defined as [P -> False].  Given [P] and [P -> False],\n  we can prove [False], so [(P /\\ ~P) -> False], i.e., [~ (P /\\ ~P)].\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_not_PNP : option (nat*string) := None.\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 b H.\n  destruct b.\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.          (* note implicit [destruct b] here *)\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(** 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\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.\n    We will see examples of 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'. 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  (* SOLUTION: *)\n  intros P. split.\n    - (* -> *) intros H. apply H.\n    - (* <- *) intros H. apply H.  Qed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* SOLUTION: *)\n  intros P Q R [HAB HBA] [HBC HCB].\n  split.\n    - (* -> *) intros HP. apply HBC. apply HAB. apply HP.\n    - (* <- *) intros HR. apply HBA. apply HCB. apply HR.  Qed.\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  (* SOLUTION: *)\n  intros P Q R. split.\n  - (* -> *)\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  - (* <- *)\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\n(* ================================================================= *)\n(** ** Setoids and Logical Equivalence *)\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 Coq library that supports it: *)\n\nFrom Coq Require Import Setoids.Setoid.\n\n(** A \"setoid\" is a set equipped with an equivalence relation,\n    that is, a relation that is reflexive, symmetric, and transitive.\n    When two elements of a set are equivalent according to the\n    relation, [rewrite] can be used to replace one element with the\n    other. We've seen that already with the equality relation [=] in\n    Coq: when [x = y], we can use [rewrite] to replace [x] with [y],\n    or vice-versa.\n\n    Similarly, the logical equivalence relation [<->] is reflexive,\n    symmetric, and transitive, so (after importing [Setoid]) we can\n    use it to replace one part of a proposition with another: if [P <->\n    Q], then we can use [rewrite] to replace [P] with [Q], or\n    vice-versa. *)\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 eq_mult_0. \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 direction of\n    the equivalence will be useful.. *)\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, 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  (* SOLUTION: *)\n  intros X P H [x Hx].\n  apply Hx. apply H. Qed.\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   (* SOLUTION: *)\n  intros X P Q. split.\n  - (* -> *) intros [x [HP | HQ]].\n    + (* P x *) left. exists x. apply HP.\n    + (* Q x *) right. exists x. apply HQ.\n  - (* <- *) intros [[x Hx] | [x Hx]].\n    + (* exists x, P x *)\n      exists x. left. apply Hx.\n    + (* exists x, Q x *)\n      exists x. right. apply Hx.\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\n       - If [l] is the empty list, then [x] cannot occur in 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 recursive\n    function taking an element and a list and returning a 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: 3 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. split.\n  (* SOLUTION: *)\n  { induction l as [|x l' IHl'].\n    - (* l = nil, contradiction *)\n      simpl. intros [].\n    - (* l = x :: l' *)\n      simpl. intros [H | H].\n      + exists x. split.\n        * apply H.\n        * left. reflexivity.\n      + apply IHl' in H.\n        destruct H as [x' [H1 H2]].\n        exists x'. split.\n        * apply H1.\n        * right. apply H2. }\n  { intros [x [H1 H2]]. rewrite <- H1.\n    apply In_map. apply H2. }\nQed.\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  (* SOLUTION: *)\n  intros A l. induction l as [|a' l' IH].\n  - intros l' a. simpl. split.\n    + intros H. right. apply H.\n    + intros [[]|H]. apply H.\n  - intros l'' a. simpl. rewrite IH. rewrite or_assoc.\n    reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (All)  \n\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  (* SOLUTION: *) :=\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) <->\n    All P l.\nProof.\n  (* SOLUTION: *)\n  intros T P l.\n  induction l as [|x l IHl].\n  - simpl. split.\n    + intros _. split.\n    + intros _ x [].\n  - simpl. rewrite <- IHl. split.\n    + intros H. split.\n      * apply H. left. reflexivity.\n      * intros x' Hx'. apply H. right.\n        apply Hx'.\n    + intros [Hx H] x' [Hxx'|Hl].\n      * rewrite <- Hxx'. apply Hx.\n      * apply H. apply Hl.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (combine_odd_even)  \n\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  (* SOLUTION: *) :=\n  fun n => 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  (* SOLUTION: *)\n  intros Podd Peven n Hodd Heven.\n  unfold combine_odd_even.\n  destruct (oddb n).\n  - (* oddn n = true *)\n    apply Hodd. reflexivity.\n  - (* oddn n = false *)\n    apply Heven. reflexivity. Qed.\n  \nTheorem combine_odd_even_elim_odd :\n  forall (Podd Peven : nat -> Prop) (n : nat),\n    combine_odd_even Podd Peven n ->\n    oddb n = true ->\n    Podd n.\nProof.\n  (* SOLUTION: *)\n  unfold combine_odd_even.\n  intros Podd Peven n H Hodd.\n  destruct (oddb n).\n  - (* oddb n = true *)\n    apply H.\n  - (* oddb n = false *)\n    discriminate Hodd. 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  (* SOLUTION: *)\n  unfold combine_odd_even.\n  intros Podd Peven n H Heven.\n  destruct (oddb n).\n  - (* oddb n = true *)\n    discriminate Heven.\n  - (* oddb n = false *)\n    apply H. Qed.\n  (** [] *)\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from some other\n    popular proof assistants (e.g., ACL2 and Isabelle) is that it\n    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 all 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 x y z, x + (y + z) = (z + y) + x.\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  (* WORKED IN CLASS *)\n  intros x y z.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\nAbort.\n\n(** We saw similar problems back in Chapter [Induction], and saw one\n    way to work around them by using [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 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\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 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(** Let us show another example of using a theorem or lemma\n    like a function. The following theorem says: any list [l]\n    containing some element must be nonempty. *)\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(** What makes this interesting is that one quantified variable\n    ([x]) does not appear in the conclusion ([l <> []]). *)\n\n(** We can use this lemma to prove the special case where [x]\n    is [42]. Naively, the tactic [apply in_not_nil] will fail because\n    it cannot infer the value of [x]. There are several ways to work\n    around that... *)\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  (* WORKED IN CLASS *)\n  intros l H.\n  Fail apply in_not_nil.\nAbort.\n\n(* [apply ... with ...] *)\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(** 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. (The details of how this proof\n    works are not critical -- the goal here is just to illustrate what\n    can be done.) *)\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(** Coq's logical core, the _Calculus of Inductive\n    Constructions_, differs in some important ways from other formal\n    systems that are used by mathematicians to write down precise and\n    rigorous proofs.  For example, in the most popular foundation for\n    paper-and-pencil mathematics, Zermelo-Fraenkel Set Theory (ZFC), a\n    mathematical object can potentially be a member of many different\n    sets; a term in Coq's logic, on the other hand, is a member of at\n    most one type.  This difference often leads to slightly different\n    ways of capturing informal mathematical concepts, but these are,\n    by and large, about equally natural and easy to work with.  For\n    example, instead of saying that a natural number [n] belongs to\n    the set of even numbers, we would say in Coq that [even n] holds,\n    where [even : nat -> Prop] is a property describing even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be cumbersome or sometimes\n    even impossible, unless we enrich the core logic with additional\n    axioms.\n\n    We conclude this chapter with a brief discussion of some of the\n    most significant differences between the 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 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\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 built-in logic.\n    This 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 using\n    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    [2+2=5], etc.!\n\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe to add: hard work by highly-trained trained experts is\n    generally required to establish the consistency of any particular\n    combination of axioms.\n\n    Fortunately, 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, standard (tr_rev_correct)  \n\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 the two definitions are indeed equivalent. *)\n\nLemma rev_append_rev : forall X (l1 l2 : list X),\n  rev_append l1 l2 = rev l1 ++ l2.\nProof.\n  intros T l1. induction l1 as [|x l1' IHl1'].\n  - intros acc. reflexivity.\n  - intros acc. simpl. rewrite IHl1'. rewrite <- app_assoc.\n    simpl. reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n(* SOLUTION: *)\nProof.\n  intros X. apply functional_extensionality.\n  intros l. unfold tr_rev.\n  rewrite rev_append_rev. rewrite app_nil_r. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** We've seen two different ways of expressing logical claims 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\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\n(** Of course, it would be pretty strange if these two\n    characterizations of evenness did not describe the same set of\n    natural numbers!  Fortunately, we can prove that they do... *)\n\n(** We first need two helper lemmas. *)\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  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  (* SOLUTION: *)\n  intros n. induction n as [|n' [k Hk]].\n  - simpl. exists 0. reflexivity.\n  - rewrite evenb_S. destruct (evenb n').\n    + simpl. exists k. rewrite Hk. reflexivity.\n    + simpl. exists (S k). rewrite Hk. reflexivity.  Qed.\n(** [] *)\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - intros H. destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk. rewrite H. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\n(** In view of this theorem, we say that the boolean computation\n    [evenb n] is reflected in the truth of the proposition [exists k,\n    n = double k]. *)\n\n(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either\n      - (1) that [n =? m] returns [true], or\n      - (2) that [n = m].\n    Again, these two notions are equivalent. *)\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\n(** However, even when the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, they may\n    not be equivalent _operationally_. *)\n\n(** In the case of even numbers above, when proving the\n    backwards direction of [even_bool_prop] (i.e., [evenb_double],\n    going from the propositional to the boolean claim), we used a\n    simple induction on [k].  On the other hand, the converse (the\n    [evenb_double_conv] exercise) required a clever generalization,\n    since we can't directly prove\n    [(evenb n = true) -> (exists k, n = double k)]. *)\n\n(** For these examples, the propositional claims are more useful than\n    their boolean counterparts, but this is not always the case.  For\n    instance, we cannot test whether a general proposition is true or\n    not in a function definition; as a consequence, the following code\n    fragment is rejected: *)\n\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(** Coq complains that [n = 2] has type [Prop], while it expects\n    an element 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-script\n    size in this case, larger proofs can often be made considerably\n    simpler by the use of reflection.  As an extreme example, the Coq\n    proof of the famous _4-color theorem_ uses reflection to reduce\n    the analysis of hundreds of different cases to a boolean\n    computation. *)\n\n(** Another notable difference is that the negation of a \"boolean\n    fact\" is straightforward to state and prove: simply flip the\n    expected boolean result. *)\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 work with. *)\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\n(** Equality provides a complementary example: knowing that\n    [n =? m = true] is generally of little direct help in the middle\n    of a proof involving [n] and [m]; however, if we convert the\n    statement to the equivalent form [n = m], we can rewrite with it.\n *)\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\n(** We won't cover reflection in much detail, but it serves as a good\n    example showing the complementary strengths of booleans and\n    general propositions. *)\n\n(** **** Exercise: 2 stars, standard (logical_connectives)  \n\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  (* SOLUTION: *)\n  intros [].\n  - simpl. intros b2. split.\n    + intros H. split.\n      * reflexivity.\n      * apply H.\n    + intros [_ H]. apply H.\n  - simpl. intros b2. split.\n    + intros H. discriminate H.\n    + intros [H _]. discriminate H.  Qed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  (* SOLUTION: *)\n  intros [].\n  - simpl. intros b2. split.\n    + intros _. left. reflexivity.\n    + intros _. reflexivity.\n  - simpl. intros [].\n    + split.\n      * intros _. right. reflexivity.\n      * intros _. reflexivity.\n    + split.\n      * intros H. discriminate H.\n      * intros [H | H].\n        { apply H. }\n        { apply H. }  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (eqb_neq)  \n\n    The following theorem is an alternate \"negative\" formulation of\n    [eqb_eq] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  (* SOLUTION: *)\n  intros x y. rewrite <- not_true_iff_false. rewrite eqb_eq.\n  reflexivity.  Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (eqb_list)  \n\n    Given a boolean operator [eqb] for testing equality of elements of\n    some type [A], we can define a function [eqb_list] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [eqb_list] function below.  To make sure that your\n    definition is correct, prove the lemma [eqb_list_true_iff]. *)\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n                  (l1 l2 : list A) : bool\n  (* SOLUTION: *) :=\n  match l1, l2 with\n  | [], [] => true\n  | a1 :: l1, a2 :: l2 => eqb a1 a2 && eqb_list eqb l1 l2\n  | _, _ => 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(* SOLUTION: *)\n  intros A eqb Heqb l1.\n  induction l1 as [|a1 l1 IH].\n  - intros [|a2 l2].\n    + split.\n      * trivial.\n      * trivial.\n    + simpl. split.\n      * intros contra. discriminate contra.\n      * intros contra. discriminate contra.\n  - intros [|a2 l2].\n    + simpl. split.\n      * intros contra. discriminate contra.\n      * intros contra. discriminate contra.\n    + simpl.\n      rewrite andb_true_iff, Heqb, IH.\n      split.\n      * intros [H1 H2].\n        rewrite H1, H2.\n        reflexivity.\n      * intros H. injection H as H1 H2.\n        { split.\n          - apply H1.\n          - apply H2. }\nQed.\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 defined above. *)\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  (* SOLUTION: *)\n  intros X test l.\n  induction l as [|x l' IHl'].\n  - (* l = [] *)\n    simpl. split.\n    + intros _. split.\n    + intros _. reflexivity.\n  - (* l = x :: l' *)\n    simpl.\n    rewrite andb_true_iff. rewrite IHl'.\n    reflexivity. Qed.\n\n(** (Ungraded) Are there any important properties of the function\n    [forallb] which are not captured by this specification? *)\n\n(* SOLUTION: *)\n(* This theorem exactly captures the input-output behaviour of\n   [forallb]. However, it does not say anything about the running\n   time. \n\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. discriminate contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m]. *)\n\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n  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(** 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, standard (excluded_middle_irrefutable)  \n\n    Proving the consistency of Coq with the general excluded middle\n    axiom requires complicated reasoning that cannot be carried out\n    within Coq itself.  However, the following theorem implies that it\n    is always safe to assume a decidability axiom (i.e., an instance\n    of excluded middle) for any _particular_ Prop [P].  Why?  Because\n    we cannot prove the negation of such an axiom.  If we could, we\n    would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)] (since [P]\n    implies [~ ~ P], by lemma [double_neg], which we proved above), \n    which would be a  contradiction.  But since we can't, it is safe \n    to add [P \\/ ~P] as an axiom. *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  (* SOLUTION: *)\n  intros P H.\n  assert (H' : ~ P).\n  { intros H'. apply H. left. apply H'. }\n  assert (H'' : ~ ~ P).\n  { intros H''. apply H. right. apply H'. }\n  apply H''. apply H'. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (not_exists_dist)  \n\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  (* SOLUTION: *)\n  intros Hem X P H x.\n  destruct (Hem (P x)) as [HPx | HNPx].\n  - (* P x *) apply HPx.\n  - (* ~P x *)\n    exfalso.\n    apply H.\n    exists x.\n    apply HNPx.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (classical_axioms)  \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\n    Hint: Rather than considering all pairs of statements pairwise,\n          prove a single circular chain of implications that connects \n          them all.\n*)\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(* SOLUTION: *)\nLemma ito__em :\n  implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros Hito P.\n  apply or_commut.\n  apply Hito.\n  intros HP. apply HP.\nQed.\n\nLemma em__ito :\n  excluded_middle -> implies_to_or.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros Hem P Q H.\n  destruct (Hem P) as [HP | HNP].\n  - (* P *) right. apply H. apply HP.\n  - (* ~P *) left. apply HNP.\nQed.\n\nLemma em__demorgan :\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle, de_morgan_not_and_not.\n  intros Hem P Q H.\n  destruct (Hem P) as [HP | HNP].\n  - (* P *)\n    left. apply HP.\n  - (* ~P *)\n    destruct (Hem Q) as [HQ | HNQ].\n    + (* Q *)\n      right. apply HQ.\n    + (* ~Q *)\n      exfalso. apply H.\n      split. apply HNP. apply HNQ.\nQed.\n\nLemma demorgan__em :\n  de_morgan_not_and_not -> excluded_middle.\nProof.\n  unfold de_morgan_not_and_not, excluded_middle.\n  intros Hdm P.\n  apply Hdm.\n  unfold not. intros Hcontra.\n  destruct Hcontra as [HNP HNNP].\n  apply HNNP. apply HNP.\nQed.\n\nLemma em__dne :\n  excluded_middle -> double_negation_elimination.\nProof.\n  intros Hem P.\n  destruct (Hem P) as [HP | HNP].\n  - (* P *) intros H'. apply HP.\n  - (* ~P *) intros H'. destruct (H' HNP).\nQed.\n\nLemma dne__demorgan :\n  double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  intros Hc P Q H.\n  apply Hc.\n  intros H2.\n  apply H.\n  split.\n  - (* left conjunct *) intros HP. apply H2. left. apply HP.\n  - (* right conjunct *) intros HQ. apply H2. right. apply HQ.\nQed.\n\n(** The above suffices (along with [demorgan__em]), but we can also\n    prove it directly this way *)\n\nLemma dne__em :\n  double_negation_elimination -> excluded_middle.\nProof.\n  intros Hc P.\n  apply Hc.\n  apply excluded_middle_irrefutable.\nQed.\n\nLemma em__peirce :\n  excluded_middle -> peirce.\nProof.\n  intros Hem P Q H.\n  destruct (Hem P) as [HP | HNP].\n  - (* P *) apply HP.\n  - (* ~P *)\n    destruct (Hem (P -> Q)) as [HPQ | HNPQ].\n    + (* P->Q *) apply H. apply HPQ.\n    + (* ~(P->Q) *) assert (P -> Q) as HPQ.\n      intros HP.\n      exfalso.\n      apply HNP. apply HP.\n      apply H. apply HPQ.\nQed.\n\nLemma peirce__em :\n  peirce -> excluded_middle.\nProof.\n  intros Hp P.\n  apply (Hp _ False).\n  right.\n  intros HP. apply H.\n  left. apply HP.\nQed.\n(** [] *)\n\n(* Fri 30 Aug 2019 02:46:58 PM CEST *)\n", "meta": {"author": "klchai", "repo": "Coq", "sha": "9eff66584563a6dc2d320869af1e6b346278c7fc", "save_path": "github-repos/coq/klchai-Coq", "path": "github-repos/coq/klchai-Coq/Coq-9eff66584563a6dc2d320869af1e6b346278c7fc/Solution/Logic_Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7531774073461914}}
{"text": "Require Import ZArith.\nRequire Import Arith.\nRequire Import List.\n\n\n(* Define Heterogenous List by Inductive Types *)\nSection hlist.\n  (* Define HList *)\n  Inductive hlist : (list Set) -> Type :=\n  | HNil : hlist nil\n  | HCons : forall (x:Set) (ls:list Set), x -> hlist ls -> hlist (x::ls).\n\n(* Define Elements Access Function *)\n(* build the function with the help of coq proof assistant\n  Fixpoint hget0 (ls:list Set) (hls:hlist ls) (n:nat){struct n} : option (nth n ls Empty_set).\n    inversion hls.\n    exact None.\n    induction n.\n    simpl.\n    exact (Some H).\n    apply (hget0 ls0 X n).\n  Defined.  \n\n  Print hget0.\n*)\n\n(* Build the function manually *)\n  Fixpoint hget (ls:list Set) (hls:hlist ls) (n:nat){struct n} : option (nth n ls Empty_set) :=  \n    match hls in (hlist l) return option (nth n l Empty_set) with\n    | HNil => None\n    | HCons _ nil _ _ => None\n    | HCons _ ys x xs => \n        match n with\n        | 0 => Some x\n        | S p => hget ys xs p\n        end\n    end.\n \nEnd hlist.\n\nArguments HCons [x ls].\nArguments hget [ls].\n\n(* Example of using HList *)\nDefinition someValues := HCons 3%Z (HCons 2%nat (HCons (3::5::4::nil) HNil)).\nCheck someValues.\nPrint someValues.\n\nEval simpl in (hget someValues 0).\nEval simpl in (hget someValues 1).\nEval simpl in (hget someValues 2).\n\n(* Extract the code for Haskell or OCaml *)\nRequire Import Extraction.\n(* Extraction Language Haskell. *)\n(* Extraction Language OCaml. *)\nRecursive Extraction hget.", "meta": {"author": "tidues", "repo": "Heterogenous-List-in-Coq", "sha": "1609a7ff4db887ef27082953cd89120d66c69616", "save_path": "github-repos/coq/tidues-Heterogenous-List-in-Coq", "path": "github-repos/coq/tidues-Heterogenous-List-in-Coq/Heterogenous-List-in-Coq-1609a7ff4db887ef27082953cd89120d66c69616/HList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.8840392909114836, "lm_q1q2_score": 0.7531597609112786}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Finite_sets.\n\n\nLemma Sn_n : forall n : nat, ~ S n = n.\nProof.\n  intros. induction n as [| n' IHn].\n  - intro. discriminate H.\n  - intro H. apply IHn.\n    inversion H. assumption.\nQed. \n\nLemma le_trans : forall n m k : nat, n <= m -> m <= k -> n <= k.\nProof.\n  intros * H1 H2. induction H2 as [| m'].\n  - assumption.\n  - constructor 2. assumption.\nQed.\n\nLemma S_le : forall n m :nat, n <= m -> S n <= S m .\nProof.\n  intros * H. induction H.\n  - constructor.\n  - constructor 2. assumption.\nQed.\n\nLemma m_le_Sn : forall n m : nat, m <= S n <-> m <= n \\/ m = S n.\nProof.\n  intros. split; intro H.\n  - destruct n as [| n']; inversion H as [| m' H1 H2].\n    + right. reflexivity.\n    + left. assumption. \n    + right. reflexivity.\n    + left. assumption.\n  - elim H; intro H1.\n    + constructor 2. assumption.\n    + rewrite H1. constructor.\nQed.\n\nLemma lt_irrefl : forall n : nat, ~ n < n.\nProof.\n  intros * H.\n  absurd (S n <= n).\n  - contradict H. exfalso.\n    induction n as [|n' IHn].\n    + inversion H.\n    + apply IHn.\n      assert (H1 : pred (S (S n')) <= pred (S n')).\n        apply le_pred. assumption.\n    simpl in H1. assumption.\n  - assumption.\nQed.\n\nLemma lt_trans : forall n m k : nat, n < m -> m < k -> n < k.\nProof.\n  intros * H1 H2.\n  induction H2 as [| k]; [apply le_S in H1 | apply le_S]; assumption.\nQed.\n\nDefinition ininat (n : nat) : Ensemble nat := fun m => m <= n.\n\nLemma ininat_0 : forall n : nat, In nat (ininat 0) n <-> n = 0.\nProof.\n  intro. split; intro H.\n  - destruct n as [| n'].\n    + reflexivity.\n    + compute in H. exfalso. inversion H.\n  - rewrite H. apply le_n.\nQed.\n\nLemma ininat_n_Sn : forall n : nat, ~ In nat (ininat n) (S n).\nProof.\n  intro. apply lt_irrefl.\nQed.\n\nLemma ininat_0_add : Same_set nat (ininat 0) (Add nat (Empty_set nat) 0).\nProof.\n  constructor.\n  - constructor 2. apply ininat_0 in H. rewrite H. compute. constructor.\n  - compute. intros * H. destruct H as [|n H1].\n    + compute in H. exfalso. contradiction.\n    + compute in H1. destruct H1. constructor.\nQed.\n\nLemma fin_ininat_0 : Finite nat (ininat 0).\nProof.\n  pose (H := Extensionality_Ensembles nat).\n  pose (H1 := H (ininat 0) (Add nat (Empty_set nat) 0)).\n  pose (H2 := H1 ininat_0_add). rewrite H2.\n  constructor.\n  - constructor.\n  - intro H3. contradiction.\nQed.\n\nLemma ininat_Sn_add :\n  forall n : nat, Same_set nat (ininat (S n)) (Add nat (ininat n) (S n)).\nProof.\n  intro. split.\n  - compute. intros * H.\n    assert (H1 : x <= n \\/ x = S n). apply m_le_Sn. assumption.\n    elim H1; intro H2.\n      + constructor. compute. assumption.\n      + constructor 2. compute. rewrite H2. constructor.\n  - compute. intros * H. destruct H; compute in H.\n    + apply le_S. assumption.\n    + destruct H. apply le_n.\nQed.\n\nLemma fin_ininat : forall n : nat, Finite nat (ininat n).\nProof.\n  intro. induction n as [| n' IHn].\n  - apply fin_ininat_0.\n  - pose (H := Extensionality_Ensembles nat).\n    pose (H1 := H (ininat (S n')) (Add nat (ininat n') (S n'))).\n    pose (H2 := H1 (ininat_Sn_add n')). rewrite H2.\n    constructor 2. assumption.\n    apply ininat_n_Sn.\nQed.\n", "meta": {"author": "gzholtkevych", "repo": "LogicalTime", "sha": "c913a7e266754b47dd5d54ddd2eb9383b10bb888", "save_path": "github-repos/coq/gzholtkevych-LogicalTime", "path": "github-repos/coq/gzholtkevych-LogicalTime/LogicalTime-c913a7e266754b47dd5d54ddd2eb9383b10bb888/preliminaries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7531376801412791}}
{"text": "(*** SECTION 2: The Ensembles Library ***)\n\n(* This file is -not- my work.  It is part of the standard Coq library.  We include it for the reader's reference. *)\n\nSection Ensembles.\n  Variable U : Type.\n\n  Definition Ensemble := U -> Prop.\n\n  Definition In (A:Ensemble) (x:U) : Prop := A x.\n\n  Definition Included (B C:Ensemble) : Prop := forall x:U, In B x -> In C x.\n\n  Inductive Empty_set : Ensemble :=.\n\n  Inductive Full_set : Ensemble :=\n    Full_intro : forall x:U, In Full_set x.\n\n(* NB: The following definition builds-in equality of elements in U as Leibniz equality.\n   This may have to be changed if we replace U by a Setoid on U with its own equality eqs, with In_singleton: (y: U)(eqs x y) -> (In (Singleton x) y). *)\n\n  Inductive Singleton (x:U) : Ensemble :=\n    In_singleton : In (Singleton x) x.\n\n  Inductive Union (B C:Ensemble) : Ensemble :=\n    | Union_introl : forall x:U, In B x -> In (Union B C) x\n    | Union_intror : forall x:U, In C x -> In (Union B C) x.\n\n  Definition Add (B:Ensemble) (x:U) : Ensemble := Union B (Singleton x).\n\n  Inductive Intersection (B C:Ensemble) : Ensemble :=\n    Intersection_intro :\n    forall x:U, In B x -> In C x -> In (Intersection B C) x.\n\n  Inductive Couple (x y:U) : Ensemble :=\n    | Couple_l : In (Couple x y) x\n    | Couple_r : In (Couple x y) y.\n\n  Inductive Triple (x y z:U) : Ensemble :=\n    | Triple_l : In (Triple x y z) x\n    | Triple_m : In (Triple x y z) y\n    | Triple_r : In (Triple x y z) z.\n\n  Definition Complement (A:Ensemble) : Ensemble := fun x:U => ~ In A x.\n\n  Definition Setminus (B C:Ensemble) : Ensemble :=\n    fun x:U => In B x /\\ ~ In C x.\n\n  Definition Subtract (B:Ensemble) (x:U) : Ensemble := Setminus B (Singleton x).\n\n  Inductive Disjoint (B C:Ensemble) : Prop :=\n    Disjoint_intro : (forall x:U, ~ In (Intersection B C) x) -> Disjoint B C.\n\n  Inductive Inhabited (B:Ensemble) : Prop :=\n    Inhabited_intro : forall x:U, In B x -> Inhabited B.\n\n  Definition Strict_Included (B C:Ensemble) : Prop := Included B C /\\ B <> C.\n\n  Definition Same_set (B C:Ensemble) : Prop := Included B C /\\ Included C B.\n\n(* Extensionality Axiom *)\n\n  Axiom Extensionality_Ensembles : forall A B:Ensemble, Same_set A B -> A = B.\n\nEnd Ensembles.\n\nHint Unfold In Included Same_set Strict_Included Add Setminus Subtract: sets\n  v62.\n\nHint Resolve Union_introl Union_intror Intersection_intro In_singleton\n  Couple_l Couple_r Triple_l Triple_m Triple_r Disjoint_intro\n  Extensionality_Ensembles: sets v62.", "meta": {"author": "weiyunlu", "repo": "coq-inversesemigroup", "sha": "a94c97fccb237e107b6eaa6d408e979218fd9fcc", "save_path": "github-repos/coq/weiyunlu-coq-inversesemigroup", "path": "github-repos/coq/weiyunlu-coq-inversesemigroup/coq-inversesemigroup-a94c97fccb237e107b6eaa6d408e979218fd9fcc/Ensembles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7531376700297409}}
{"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(**************************************************************************\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(* ********************************************************************** *)\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(* ################################################################# *)\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(* ################################################################# *)\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", "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/LibMonoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7531376619091762}}
{"text": "(**  Iteration of a function (similar to [Nat.iter]) \n     Abstract Properties\n\nExperimental use of LibHyps \n\n*)\n\n\nOpen Scope nat_scope.\nFrom Coq Require Import RelationClasses Relations Arith Max Lia.\nFrom hydras Require Import Exp2.\n\nFrom LibHyps Require Import LibHyps.\nFrom hydras  Require Import MoreLibHyps.\nLtac rename_hyp n th ::= rename_short n th.\n\n(* begin snippet iterateDef *)\n\nFixpoint iterate {A:Type}(f : A -> A) (n: nat)(x:A) :=\n  match n with\n  | 0 => x\n  | S p => f (iterate  f p x)\n  end. (* .no-out *)\n\n(* end snippet iterateDef *)\n\nLemma iterate_comm {A: Type} f n (x:A)\n  : iterate f n (f x) = f (iterate f n x).\nProof.\n  induction n;  simpl.\n  - trivial.   \n  - simpl;  now f_equal. \nQed. \n\n\n\n(** Compatibility with Ackermann Library's definition *)\n\nLemma iterate_compat {f : nat -> nat}(n:nat)(x:nat):\n  iterate f n x = nat_rec \n                    (fun _ => nat -> nat)\n                    (fun x : nat => x)\n                    (fun (_ : nat) (rec : nat -> nat) (x : nat) => f (rec x))\n                    n x.\nProof.\n  induction n; cbn.\n   - reflexivity.\n   - now rewrite IHn.\nQed.\n\nLemma iterate_compat2 {A} (f : A -> A) n :\n  forall x, iterate f n x = Nat.iter n f x.\nProof. \n  induction n.\n  - reflexivity.  \n  - simpl; intros; now rewrite IHn.\nQed.\n\n\n(** TODO : move to more generic libraries *)\n\nLemma iterate_compat3 f x n :\n  iterate f n x = nat_rec (fun _ : nat => nat) x (fun _ y : nat => f y) n.\nProof.\n  induction n;cbn; auto.\nQed.\n\n\n(** ** Abstract properties of arithmetic functions *)\n\n(* begin snippet funLeDef *)\n\nDefinition strict_mono f := forall n p,  n < p -> f n < f p.\n\nDefinition dominates_from n g f := forall p, n <= p -> f p < g p.\n\nDefinition fun_le f g := forall n:nat, f n <=  g n.\nInfix \"<<=\" := fun_le (at level 60).\n\nDefinition dominates g f := exists n : nat, dominates_from n g f .\nInfix \">>\" := dominates (at level 60).\n\nDefinition dominates_strong g f  := {n : nat | dominates_from n g f}.\nInfix \">>s\" := dominates_strong (at level 60).\n\n(* end snippet funLeDef *)\n\n\nLemma S_pred_rw (f : nat -> nat) : S <<= f ->\n                                   forall x, S (Nat.pred (f x)) = f x.\nProof.\n  intros H x; case_eq (f x).\n  - intro H0. specialize (H x); rewrite H0 in H.\n    inversion H.\n  - reflexivity.\nQed.\n\n\n\n\nLemma fun_le_trans f g h : f <<= g ->  g <<= h -> f <<= h.\nProof. \n  intros; red; intro n; transitivity (g n); auto.\nQed.\n\nLemma mono_le f (Hf : strict_mono f) :  forall n, n <= f n.\nProof.\n  induction n.\n  - auto with arith. \n  - apply Nat.le_lt_trans with (f n); auto with arith.  \nQed.\n\n\nLemma mono_injective f (Hf : strict_mono f) :\n  forall n p , f n = f p -> n = p.\nProof.\n  intros n p H; destruct (PeanoNat.Nat.lt_total n p).\n  - specialize (Hf _ _ H0); rewrite H in Hf;\n      destruct (Nat.lt_irrefl _ Hf).\n  -  destruct H0; trivial. \n     + specialize (Hf _ _ H0); rewrite H in Hf;\n         destruct (Nat.lt_irrefl _ Hf).\nQed.\n\nLemma mono_weak f (H: strict_mono f) :\n  forall n p, n <= p -> f n <= f p.\nProof.\n  induction 1.\n  - left.\n  - apply PeanoNat.Nat.lt_le_incl; apply H; auto with arith. \nQed.\n\nLemma dominates_from_trans :\n  forall f g h i j, dominates_from i g f  ->\n                    dominates_from j h g  ->\n                    dominates_from  (Nat.max i j) h f .\nProof.\n  intros f g h i j H H0 k Hk;  transitivity (g k).\n  + apply H;  eauto with arith.\n  + apply H0; eauto with arith.\nQed.\n\nLemma dominates_trans f g h :\n  dominates g f ->  dominates h g -> dominates h f.\nProof.\n  intros [i Hi] [j Hj]; exists (Nat.max i j);\n    eapply dominates_from_trans with g; eauto.\nQed.\n\nLemma dominates_trans_strong : forall f g h,\n    dominates_strong g f ->\n    dominates_strong h g ->\n    dominates_strong h f.\nProof.\n  intros f g h [i Hi] [j Hj];exists (Nat.max i j);\n    eapply dominates_from_trans with g; eauto.\nQed.\n\n(** ** Abstract properties of iterate *)\n\n\nLemma iterate_S_eqn {A:Type}(f : A -> A) (n: nat)(x:A):\n  iterate f (S n) x = f (iterate f n x).\nProof. reflexivity. Qed.\n\nLemma iterate_S_eqn2 {A:Type}(f : A -> A) (n: nat)(x:A):\n  iterate f (S n) x =  (iterate f n (f x)).\nProof.\n  induction n.\n  - reflexivity.\n  - rewrite (iterate_S_eqn f (S n)), IHn;  reflexivity. \nQed.\n\n\nLemma iterate_rw {A} {f : A -> A} n  :\n  forall x, iterate f  (S n)  x = iterate f n (f x).\nProof.\n  simpl; induction n.\n  - reflexivity. \n  -  intros; simpl; now f_equal. \nQed.\n\n\nLemma iterate_ext {A:Type}(f g: A -> A) (H: forall x, f x = g x):\n  forall n x, iterate f n x = iterate g n x.\nProof.\n  induction n; simpl; auto.\n  intro; rewrite IHn; now rewrite H.\nQed.\n\n  \nLemma iterate_le f (Hf : strict_mono f) :\n  forall i j, i <= j -> forall z, iterate f i z <= iterate f j z.\nProof.\n  induction 1.\n  - trivial.   \n  - intros; rewrite iterate_S_eqn.\n    transitivity (iterate f m z); auto. \n    apply mono_le; auto. \nQed.\n\n\n\nLemma iterate_lt  f (Hf : strict_mono f)(Hf': fun_le S f):\n  forall i j, i < j -> forall z, iterate f i z < iterate f j z.\nProof.\n   induction 1.\n  - intros; rewrite iterate_S_eqn; auto.\n  - intros; rewrite iterate_S_eqn;\n      transitivity (iterate f m z); auto. \nQed.\n\nLemma iterate_lt_from f k:\n   strict_mono f ->\n    ( forall n,  k <= n -> n < f n) -> \n    forall i j : nat,  i < j ->\n                       forall z : nat, k <= z ->\n                                       iterate f i z < iterate f j z.\nProof.\n  induction 3 /r.\n - intros Hmono Hind * Hkz; rewrite iterate_S_eqn; auto.\n   apply Hind;  revert i; induction i /r. \n   +  cbn; auto. \n   +  transitivity (iterate f i z); auto.\n      rewrite iterate_S_eqn; apply Nat.lt_le_incl.\n      apply Hind; auto. \n - intros Hmono Hind * Hlt Hind2 * Kkz; transitivity (iterate f m z); auto. \n   rewrite iterate_S_eqn; apply Hind. \n   transitivity z; auto.\n   clear i Hlt Hind2; induction m.\n   + cbn; auto.\n      + cbn; transitivity (iterate f m z); auto.\n     apply Nat.lt_le_incl, Hind;  lia. \nQed. \n\n\n(* begin snippet iterateLeNSN *)\n\nLemma iterate_le_n_Sn (f: nat -> nat):\n  (forall x,  x <= f x) ->\n  forall n x,  iterate f n x <= iterate f (S n)  x. (* .no-out *)\n\n(* end snippet iterateLeNSN *)\n\nProof.\n  induction n /n.\n  - cbn; auto with arith.\n  - cbn; intros; apply  h_all_le_x_. \nQed.\n\nLemma iterate_le_np_le (f: nat -> nat):\n  (forall x,  (x <= f x)%nat) ->\n  forall n p x,  (n <= p -> iterate f n x <= iterate f p x)%nat.\nProof.\n  induction 2.\n  - reflexivity.\n  - transitivity (iterate f m x).\n    + assumption.\n    + apply iterate_le_n_Sn, H. \nQed.\n\nLemma iterate_mono2 (f: nat -> nat):\n  (forall x y,  x <= y -> f x <= f y)%nat ->\n  forall n x y,  (x <= y -> iterate f n x <= iterate f n y)%nat.\nProof.\ninduction n.\n - simpl; trivial.\n - simpl; intros; now apply H, IHn.\nQed.\n\n\nLemma iterate_mono f (Hf : strict_mono f) (Hf' :  S  <<= f):\n  forall n, strict_mono (iterate f n).\nProof.\n  induction n.\n  - red; intro i; cbn;auto.\n  - cbn; intros i j H; apply Hf;auto.\nQed.\n\nLemma iterate_ge : forall f , S  <<= f -> \n                              forall  j n, j <= iterate f n j.\nProof.\n  induction n.\n  - cbn; auto with arith.\n   -  apply Nat.lt_le_incl;rewrite iterate_S_eqn;\n        apply Nat.le_lt_trans with (iterate f n j); auto.\nQed.\n\n\nLemma iterate_Sge f j : S <<= f -> S <<= iterate f (S j).\nProof.\n  intros h x; rewrite iterate_rw.\n   transitivity (f x).                      \n    -  apply h.\n    - now apply iterate_ge.\nQed.\n\nLemma iterate_ge' : forall f,  id <<= f ->\n                               forall n j, 0 < n -> j <= iterate f n j.\nProof.\n  induction n /r. \n  - inversion 2.\n  - intros *  H0; destruct n /r. \n    + simpl; intros /n. apply h_fun_le_id_.\n    +  intros /n;  transitivity (iterate f (S n) j).\n       * auto with arith.\n       * simpl; apply h_fun_le_id_.\nQed.\n\n\nLemma iterate_ge'' f : id <<= f -> strict_mono f -> forall i k,\n      k <= Nat.pred (iterate (fun z => S (f z)) (S i) k).\nProof.\n  induction i /n.\n  - intros; cbn; apply h_fun_le_id_.\n  - intros *;   rewrite iterate_rw;\n    apply Nat.le_trans with\n        (Nat.pred (iterate (fun z : nat => S (f z)) (S i) k)).\n    + auto.\n    + cbn;  assert (H1: strict_mono (fun z => S (f z))).\n      { intros x y Hlt.  apply h_strict_mono_ in Hlt;  auto with arith. }\n      generalize  (iterate_mono _ H1).\n      assert (H2: S <<= (fun z : nat => S (f z))).\n      { intro x; auto with arith.\n        specialize (h_fun_le_id_ x); auto with arith.\n      }\n      intros H3;  specialize (H3 H2 i).\n      apply Nat.lt_le_incl.\n      assert (H4: k < S (f k)).\n      { apply Nat.le_lt_trans with (f k).\n        - apply h_fun_le_id_.                       \n        - auto with arith.\n      }\n   specialize (H3 _ _ H4); auto.\nQed.\n\nLemma strict_mono_iterate_S f :\n  strict_mono f -> id <<= f ->\n  forall i,  strict_mono\n               (fun k =>  Nat.pred (iterate (fun z => S (f z)) (S i) k)).\nProof.\n  intros Hmono Hle; induction i.\n  - cbn; apply Hmono.\n  -  intros k l Hlt.\n    assert (H: k <= Nat.pred (iterate (fun z : nat => S (f z)) (S (S i)) k))\n    by (apply iterate_ge''; auto).\n    assert (H0: k < iterate (fun z : nat => S (f z)) (S (S i)) k).\n    { \n      replace k with (iterate (fun z => S (f z)) 0 k) at 1.\n      -  apply iterate_lt.\n        + \n            intros x y Hxy; specialize (Hmono _ _ Hxy); auto with arith.\n            + intros x; auto with arith; specialize (Hle x); auto with arith.\n        + auto with arith.\n      - reflexivity. \n    }\n    rewrite <-  Nat.pred_lt_mono.\n    + apply iterate_mono.\n      * intros x y Hxy; specialize (Hmono _ _ Hxy); auto with arith.\n      * intros x; specialize (Hle x); auto with arith.\n      * auto. \n    +  intro H1; rewrite H1 in H0; inversion H0.\nQed.\n\n\nLemma iterate_mono_1 (f g: nat -> nat) (k:nat) (Hf: strict_mono f)\n      (Hf' : S <<= f)\n      (H : forall n, k <= n -> f n <= g n) :\n  forall i n, k <= n -> iterate f i n <= iterate g i n.\nProof. \n  induction i. \n  - simpl; auto with arith. \n  - intros; repeat rewrite iterate_S_eqn. \n    transitivity (f (iterate g i n)); auto. \n    + apply mono_weak; auto. \n    + apply H; transitivity (iterate f i n); [ | auto].\n      * induction H0.\n        -- clear IHi;  induction i. \n       ++ simpl; auto with arith. \n       ++  rewrite iterate_S_eqn. \n           transitivity (iterate f i k).\n           **  auto. \n           **  apply Nat.lt_le_incl; auto. \n        --  transitivity (S m).\n            ++ auto with arith. \n            ++ apply iterate_ge; auto. \nQed.\n\nLemma iterate_dom_prop :\n  forall f g i (Hgt : S <<= f)\n         (Hm : strict_mono f) (Hm': strict_mono g),\n    dominates_from i g f ->\n    forall k, 0 < k -> dominates_from i (iterate g k) (iterate f k).\nProof.\n  induction k.\n  - intro H0; inversion H0.\n  - destruct k.\n    + simpl;  intros _ l Hl;  apply H; auto.\n    + intros _ l Hl; {autorename}.  repeat rewrite iterate_S_eqn.\n      transitivity (g (f (iterate f k l))).\n      * apply H; transitivity (f l).\n        { transitivity l;  auto. \n          apply PeanoNat.Nat.lt_le_incl.\n          eapply Hgt; auto.\n        }\n        apply mono_weak;  auto.\n        eapply iterate_ge;  auto. \n      *  apply Hm';  assert (0 < S k)%nat by auto with arith.\n         apply IHk in H0; specialize (H0 l).\n         repeat rewrite iterate_S_eqn in H0; auto.   \nQed.\n\nLemma dominates_from_le  i j g f : i <= j ->\n                                   dominates_from i g f -> \n                                   dominates_from j g f .\nProof. \n  induction 1; auto.\n  intros H0 x H1; apply IHle; auto.\n  auto with arith.\nQed.\n\nLemma smono_Sle f : f 0 <> 0 -> strict_mono f -> S <<= f.\nProof.\n  intros H H0 x; induction x.\n  - destruct (f 0).\n    + now destruct H.\n    + auto with arith.\n  - apply Nat.le_lt_trans with (f x).\n    + auto.\n    + apply H0; auto with arith.\nQed.\n\n(**  ** Second-order iterate  *)\n\nLemma iterate_ext2 {A:Type} (f g : (A -> A) -> A -> A)\n      (h i : A->A) : (forall x, h x = i x) ->\n                     (forall h' i',  (forall x, h' x = i' x) ->\n                                     forall x, f h' x = g i' x) ->\n                     forall n x, iterate f n h x = iterate g n i x.\nProof.\n  induction n.\n  - intros; simpl; auto.\n  - intros; simpl; apply H0. auto.\nQed.\n\n\nLemma iterate2_mono (f : (nat->nat)->(nat->nat)):\n   (forall g, strict_mono g -> S <<= g -> strict_mono (f g))->\n   (forall g, strict_mono g -> S <<= g -> S <<=  (f g))->\n   forall k g x  y,  strict_mono g -> S <<= g ->\n                     (x < y)%nat ->\n                     (iterate f k g x < iterate f k g y)%nat.\n  Proof.\n   induction k.\n   - cbn; intros; apply (H1 _ _ H3); auto.\n   -  intros; rewrite iterate_S_eqn2.\n      apply (IHk (f g) x y ); auto.\nQed.\n\nLemma iterate2_mono_weak (f : (nat->nat)->(nat->nat)):\n   (forall g, strict_mono g -> S <<= g -> strict_mono (f g))->\n   (forall g, strict_mono g -> S <<= g -> S <<=  (f g))->\n   forall k g x  y,  strict_mono g -> S <<= g ->\n                     (x <= y)%nat ->\n                     (iterate f k g x <= iterate f k g y)%nat.\nProof.\n  intros g Hg k g0 x y  Hmono ? Hxy.\n  destruct (Nat.lt_eq_cases x y) as [H4 H5]; apply H4 in Hxy.\n  destruct Hxy. \n  -  apply Nat.lt_le_incl,  iterate2_mono; auto.\n  - now subst.\nQed.\n\n\nLemma iterate2_mono3 (phi  : (nat->nat)->(nat->nat)) :\n  (forall g, strict_mono g -> S <<= g ->\n             strict_mono (phi g) /\\ S <<= phi g)->\n  (forall (f g : nat -> nat), strict_mono f -> S <<= f  ->\n                              strict_mono g -> S <<= g ->\n                              ((forall x, f x <= g x) ->\n                               forall x, phi f x <= phi g x)) ->\n  forall g h,  strict_mono g -> S <<= g -> strict_mono h -> S <<= h ->\n             (forall x,  g x <= h x) ->\n  forall k x y,  x <= y -> \n                 iterate phi k  g x <= iterate phi k h y.\nProof.\n  intros; revert k x y H6.\n  assert (H6: forall k, strict_mono (iterate phi k h) /\\\n                        S <<= iterate phi k h).\n  {\n    intro k; induction k.\n    - simpl; split; auto.\n    - destruct IHk; split.\n      + simpl; destruct (H (iterate phi k h)); auto. \n      + simpl; destruct (H (iterate phi k h)); auto.\n  }  \n  assert (H7: forall k, strict_mono (iterate phi k g) /\\\n                        S <<= iterate phi k g). {\n    { intro k; induction k.\n      - simpl; split; auto.\n      - destruct IHk; split.\n        + simpl; destruct (H (iterate phi k g));  auto.\n        +  simpl;  destruct (H (iterate phi k g)); auto.\n    }\n  }\n  induction k.\n  - simpl; intros; transitivity (g y).\n    +  apply mono_weak; auto.\n    +  auto.\n  -   intros; repeat rewrite iterate_S_eqn;\n        transitivity (phi (iterate phi k h) x).\n      +  apply H0.\n         * destruct (H7 k); auto.\n         * destruct (H7 k); auto.\n         * destruct (H6 k); auto.\n         * destruct (H6 k); auto.\n         * intro; apply IHk; auto with arith.\n      + clear IHk; destruct (H6 k).\n        destruct  (H (iterate phi k h) H9 H10);  apply mono_weak; auto.\nQed.\n\n\nLemma iterate2_mono2 (phi psi : (nat->nat)->(nat->nat)):\n  (forall g, strict_mono g -> S <<= g -> strict_mono (phi g))->\n  (forall g, strict_mono g -> S <<= g -> S <<=  (phi g))->\n  (forall g, strict_mono g -> S <<= g -> strict_mono (psi g))->\n  (forall g, strict_mono g -> S <<= g -> S <<=  (psi g))->\n  (forall g x, strict_mono g -> fun_le S g  -> phi g x <= psi g x) ->\n  (forall f g, strict_mono f -> strict_mono g -> S <<= f -> S <<= g ->\n               (forall x, f x <= g x) -> (forall x, psi f x <= psi g x)) ->\n  forall k g x  y,  strict_mono g -> S <<= g ->\n                    (x <= y)%nat ->\n                    (iterate phi k g x <= iterate psi k g y)%nat.\nProof.\n  induction k.\n  -  simpl;  intros g x y H5 H6 H7;\n       destruct (Nat.lt_eq_cases x y) as [H8 H9].\n      destruct (H8 H7).\n     + apply Nat.lt_le_incl.\n       apply H5; auto.\n     + subst; auto.\n  -  intros;  repeat rewrite iterate_S_eqn2.\n     transitivity (iterate psi k (psi g) x).\n     +   specialize (IHk (phi g) x x (H g H5 H6) (H0 g H5 H6)).\n        transitivity (iterate psi k (phi g) x).\n        * apply IHk; auto.\n        * apply iterate2_mono3; auto.\n     +   apply iterate2_mono3; auto. \nQed.\n\n(** ** Exponential and hyper exponential of base 2 *)\n\nLemma exp2_ge_S : S  <<= exp2.\nProof. \n  red; induction n. \n  - cbn; auto with arith. \n  - cbn; abstract lia.\nQed.\n\nLemma exp2_mono : strict_mono exp2.\nProof.\n  red; induction 1; cbn.\n  - generalize (exp2_positive n); generalize (exp2 n);intros; abstract lia.\n  - generalize IHle, (exp2_positive m); generalize (exp2 n), (exp2 m);\n      intros;abstract lia.\nQed.\n\nLemma exp2_mono_weak : forall n p, n<= p -> exp2 n <= exp2 p.\nProof.\n  intros n p H; elim H.\n  - left.\n  - intros ? ? ?; apply Nat.lt_le_incl, exp2_mono; auto with arith.\nQed.\n\nLemma exp2_as_iterate n : exp2 n = iterate (fun i => 2 * i)%nat n 1.\nProof.\n  induction  n.\n  - reflexivity.\n  - rewrite iterate_S_eqn; simpl exp2; rewrite <- IHn; abstract lia.\nQed.\n\n\nDefinition hyper_exp2 k := iterate exp2 k 1.\n\nLemma hyper_exp2_S : forall n, hyper_exp2 (S n) = exp2 (hyper_exp2 n).\nProof.  induction n; cbn; auto. Qed.\n\nLemma iterate_ge_from : forall f i, dominates_from i f id -> \n                               forall  j, i <= j ->\n                                          forall n,\n                                            j <= iterate f n j.\nProof.\n  induction n.\n  cbn.\n  auto with arith.\n  apply PeanoNat.Nat.lt_le_incl.\n  rewrite iterate_S_eqn.\n  apply Nat.le_lt_trans with (iterate f n j).\n  auto.\n  apply H.\n  apply Nat.le_trans with j.\n  auto.\n  auto.\nQed.  \n\n\nLemma dominates_iterate :\n  forall  i f,\n    dominates_from i f id ->\n    strict_mono f ->\n    forall n,\n      {j:nat | i <= j /\\ dominates_from j (iterate f (S n)) id}.\n\n  induction n.\n  exists i.\n  split;auto.\n  destruct IHn as [j [H1 H2]].\n  exists j.\n  split;auto.\n  red in H2; red.\n  intros k Hk.\n  unfold id.\n  rewrite iterate_S_eqn.\n  apply Nat.le_lt_trans with (f (iterate f n k)).\n  apply Nat.le_trans with  (iterate f n k).\n  apply iterate_ge_from with i.\n  auto.\n  eauto with arith.\n  apply PeanoNat.Nat.lt_le_incl.\n  apply H.\n  apply Nat.le_trans with k. eauto with arith.\n  apply iterate_ge_from with i.\n  auto. \n  eauto with arith. \n  apply H0.\n  rewrite iterate_S_eqn.\n  apply H.\n  \n  apply Nat.le_trans with  k.\n  eauto with arith. \n  apply iterate_ge_from with i.\n  auto. \n  eauto with arith. \nDefined.\n\n\nCorollary iterate_gt_diag' :\n  forall  i f,\n    dominates_from i f id ->\n    strict_mono f ->\n    forall n, 0 < n -> \n              {j:nat | i<= j /\\ dominates_from j (iterate f n) id}.\nProof.\n  destruct n.\n  -  intro H1;  cut False; [contradiction | lia].\n  - intros _; apply dominates_iterate; auto.\nDefined.\n\nCorollary iterate_ge_diag' :\n  forall  i f,\n    dominates_from i f id->\n    strict_mono f ->\n    forall n, \n      {j:nat | i<= j /\\ forall k, j<= k -> k <= iterate f n k}.\nProof.\n  intros; destruct n.\n  -  exists i; split;auto. \n  -  exists i; split; auto.\n     intros.\n     generalize  (H k H1); intros.\n     unfold id in H2, H; rewrite iterate_S_eqn.   \n     apply Nat.lt_le_incl.\n     apply Nat.lt_le_trans with (f k);  auto.\n     apply mono_weak; auto.\n     eapply iterate_ge_from with i; auto.\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/Prelude/Iterates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7531376594468023}}
{"text": "Require Export Lists.List.\nImport ListNotations.\n\n\nSection Definitions.\nVariable T : Type.\n\n  Class Inhabited\n  : Prop :=\n    exist_proof : exists e : list T, e <> nil.\n  Class Finite\n  : Prop :=\n    fin_proof : exists e : list T, forall t : T, In t e.\n\nEnd Definitions.\n\n\nSection BasicDependence.\nVariable T : Type.\n\n  Theorem not_Inhabited_is_Finite : ~ Inhabited T -> Finite T.\n  Proof.\n    intros* H.\n    exists nil. intro. exfalso. apply H.\n    exists (t :: nil). intro H'. discriminate H'.\n  Qed.\n\nEnd BasicDependence.\n\n(* Inhabitence of some standard types                                       *)\n\nInstance bool_is_Inhabited : Inhabited bool.\nProof. now exists (true :: nil). Defined.\n\nInstance nat_is_Inhabited : Inhabited nat.\nProof. now exists (0 :: nil). Defined.\n\n(* Some types are not inhabited *)\n\nExample False_isnot_Inhabited : ~ Inhabited False.\nProof.\n  intro. elim H. intros e H1. apply H1.\n  destruct e as [| t e']; [ trivial | now exfalso ].\nQed.\n\n(* Finiteness of some standard types                                        *)\n\nInstance False_is_Finite : Finite False.\nProof.\n  apply not_Inhabited_is_Finite.\n  exact False_isnot_Inhabited.\nDefined.\n\nInstance unit_is_Finite : Finite unit.\nProof.\n  exists (tt :: nil). intro.\n  destruct t. now left.\nDefined.\n\nInstance bool_is_Finite : Finite bool.\nProof.\n  exists (true :: false :: nil). intro.\n  destruct t; [ now left | right; now left ].\nDefined.\n\n(* Infiniteness of type nat                                                 *)\n\nRequire Import Arith.Compare_dec.\nRequire Import Arith.Le.\nRequire Import Arith.Lt.\nSection NatIsNotFinite.\n(*  Here we prove that nat is not a finite type/\n    The idea of the proof is to construct a function\n    outside : list nat -> nat meeting the requirement\n      forall e : list nat, ~ In (outside e) e.                              *)\n\n\n  Fixpoint outside (ns : list nat) : nat :=\n    match ns with\n      nil     => 0\n    | n :: ns' => let n' := outside ns' in\n                  if le_lt_dec n' n then S n else n'\n    end.\n\n  Section Lemmas.\n    Variable e : list nat.\n\n    Lemma lt_member_outside : forall n : nat, In n e -> n < outside e.\n    Proof.\n      intros * H.\n      induction e as [| m e' IHe]; simpl.\n      - now exfalso.\n      - case H; intro HC.\n        + rewrite HC. case (le_lt_dec (outside e') n); intro HD;\n          [apply le_n | assumption].\n        + pose (IHe' := IHe HC).\n          case (le_lt_dec (outside e') m); intro HD; assumption || idtac.\n            assert (HAux : n < m). {\n              now apply le_trans with (outside e'). }\n            now apply le_S.\n    Qed.\n\n    Lemma outside_list : ~ In (outside e) e.\n    Proof.\n      intro H.\n      pose (H1 := lt_member_outside (outside e) H).\n      now pose (H2 := lt_irrefl (outside e)).\n    Qed.\n  End Lemmas.\n\n  Theorem nat_isnot_Finite : ~ Finite nat.\n  Proof.\n    unfold Finite. intro. elim H. intros e H1.\n    pose (H2 := H1 (outside e)).\n    now pose (H2' := outside_list e).\n  Qed.\n\nEnd NatIsNotFinite.\n", "meta": {"author": "gzholtkevych", "repo": "coq-theories", "sha": "f90b0e61c385581f145cd73f5cb2230aafa3b069", "save_path": "github-repos/coq/gzholtkevych-coq-theories", "path": "github-repos/coq/gzholtkevych-coq-theories/coq-theories-f90b0e61c385581f145cd73f5cb2230aafa3b069/TypeProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7530558336486511}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Supplementary Coq material: proof by reflection\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.\nSet Asymmetric Patterns.\n\n\n(* Our last \"aside\" on effective Coq use (in IntroToProofScripting.v)\n * highlighted a very heuristic approach to proving.  As an alternative, we will\n * study a technique called proof by reflection.  We will write, in Gallina (the\n * logical functional-programming language of Coq), decision procedures with\n * proofs of correctness, and we will appeal to these procedures in writing very\n * short proofs.  Such a proof is checked by running the decision procedure.\n * The term _reflection_ applies because we will need to translate Gallina\n * propositions into values of inductive types representing syntax, so that\n * Gallina programs may analyze them, and translating such a term back to the\n * original form is called _reflecting_ it. *)\n\n\n(** * Proving Evenness *)\n\n(* Proving that particular natural number constants are even is certainly\n * something we would rather have happen automatically.  The Ltac-programming\n * techniques that we learned last week make it easy to implement such a\n * procedure. *)\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.\n\nTheorem even_256 : isEven 256.\nProof.\n  prove_even.\nQed.\n\nSet Printing All.\nPrint even_256.\nUnset Printing All.\n\n(* Here we see a term of Coq's core proof language, which we don't explain in\n * detail, but roughly speaking such a term is a syntax tree recording which\n * lemmas were used, and how their quantifiers were instantiated, to prove a\n * theorem.  This Ltac procedure always works (at least on machines with\n * infinite resources), but it has a serious drawback, which we see when we\n * print the proof it generates that 256 is even.  The final proof term has\n * length super-linear in the input value, which we reveal with\n * [Set Printing All], to disable all syntactic niceties and show every node of\n * the internal proof AST.  The problem is that each [Even_SS] application needs\n * a choice of [n], and we wind up giving every even number from 0 to 254 in\n * that position, at some point or another, for quadratic proof-term size.\n *\n * It is also unfortunate not to have static typing guarantees that our tactic\n * always behaves appropriately.  Other invocations of similar tactics might\n * fail with dynamic type errors, and we would not know about the bugs behind\n * 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\n * able to write proofs like in the example above with constant size overhead\n * beyond the size of the input, and we will do it with verified decision\n * procedures written in Gallina. *)\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\n(* To prove [check_even] sound, we need two IH strengthenings:\n * - Effectively switch to _strong induction_ with an extra numeric variable,\n *   asserted to be less than the one we induct on.\n * - Express both cases for how a [check_even] test might turn out. *)\nLemma check_even_ok' : forall n n', n' < n\n  -> if check_even n' then isEven n' else ~isEven n'.\nProof.\n  induct n; simplify.\n\n  linear_arithmetic.\n\n  cases n'; simplify.\n  constructor.\n  cases n'; simplify.\n  propositional.\n  invert H0.\n  specialize (IHn n').\n  cases (check_even n').\n  constructor.\n  apply IHn.\n  linear_arithmetic.\n  propositional.\n  invert H0.\n  apply IHn.\n  linear_arithmetic.\n  assumption.\nQed.\n\nTheorem check_even_ok : forall n, check_even n = true -> isEven n.\nProof.\n  simplify.\n  assert (n < S n) by linear_arithmetic.\n  apply check_even_ok' in H0.\n  rewrite H in H0.\n  assumption.\nQed.\n\n(* As this theorem establishes, the function [check_even] may be viewed as a\n * _verified decision procedure_.  It is now trivial to write a tactic to prove\n * evenness. *)\n\nLtac prove_even_reflective :=\n  match goal with\n    | [ |- isEven ?N] => apply check_even_ok; reflexivity\n  end.\n\nTheorem even_256' : isEven 256.\nProof.\n  prove_even_reflective.\nQed.\n\nSet Printing All.\nPrint even_256'.\nUnset Printing All.\n\n(* Notice that only one [nat] appears as an argument to an applied lemma, and\n * that's the original number to test for evenness.  Proof-term size scales\n * linearly.\n *\n * What happens if we try the tactic with an odd number? *)\n\nTheorem even_255 : isEven 255.\nProof.\n  (*prove_even_reflective.*)\nAbort.\n(* Coq reports that [reflexivity] can't prove [false = true], which makes\n * perfect sense! *)\n\n(* Our tactic [prove_even_reflective] is reflective because it performs a\n * proof-search process (a trivial one, in this case) wholly within Gallina. *)\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\n * this one: *)\n\nTheorem true_galore : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\nProof.\n  tauto.\nQed.\n\nPrint true_galore.\n\n(* As we might expect, the proof that [tauto] builds contains explicit\n * applications of deduction rules.  For large formulas, this can add a linear\n * 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\n * into the actual \"reflection\" part of \"proof by reflection.\"  It is impossible\n * to case-analyze a [Prop] in any way in Gallina.  We must_reify_ [Prop] into\n * 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\n * functions are also called _interpretation functions_, and we have used them\n * 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\n * true. *)\n\nTheorem tautTrue : forall t, tautDenote t.\nProof.\n  induct t; simplify; propositional.\nQed.\n\n(* To use [tautTrue] to prove particular formulas, we need to implement the\n * 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\n * look at the goal formula, reify it, and apply [tautTrue] to the reified\n * formula.  Recall that the [change] tactic replaces a conclusion formula with\n * another that is equal to it, as shown by partial execution of terms. *)\n\nLtac obvious :=\n  match goal with\n    | [ |- ?P ] =>\n      let t := tautReify P in\n      change (tautDenote t); apply tautTrue\n  end.\n\n(* We can verify that [obvious] solves our original example, with a proof term\n * that does not mention details of the proof. *)\n\nTheorem true_galore' : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\nProof.\n  obvious.\nQed.\n\nSet Printing All.\nPrint true_galore'.\nUnset Printing All.\n\n(* It is worth considering how the reflective tactic improves on a pure-Ltac\n * implementation.  The formula-reification process is just as ad-hoc as before,\n * so we gain little there.  In general, proofs will be more complicated than\n * formula translation, and the \"generic proof rule\" that we apply here _is_ on\n * much better formal footing than a recursive Ltac function.  The dependent\n * type of the proof guarantees that it \"works\" on any input formula.  This\n * benefit is in addition to the proof-size improvement that we have already\n * seen.\n *\n * It may also be worth pointing out that our previous example of evenness\n * testing used a test [check_even] that could sometimes fail, while here we\n * avoid the extra Boolean test by identifying a syntactic class of formulas\n * that are always true by construction.  Of course, many interesting proof\n * steps don't have that structure, so let's look at an example that still\n * requires extra proving after the reflective step. *)\n\n\n(** * A Monoid Expression Simplifier *)\n\n(* Proof by reflection does not require encoding of all of the syntax in a goal.\n * We can insert \"variables\" in our syntax types to allow injection of arbitrary\n * pieces, even if we cannot apply specialized reasoning to them.  In this\n * section, we explore that possibility by writing a tactic for normalizing\n * 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\n   * algebraic structure of monoids.  We have an associative binary operator and\n   * an identity element for it.\n   *\n   * It is easy to define an expression-tree type for monoid expressions.  A\n   * [Var] constructor is a \"catch-all\" case for subexpressions that we cannot\n   * model.  These subexpressions could be actual Gallina variables, or they\n   * could just use functions that our tactic is unable to understand. *)\n\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\n   * associativity, so it is helpful to have a denotation function for lists of\n   * 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 => []\n      | Var x => [x]\n      | Op me1 me2 => flatten me1 ++ flatten me2\n    end.\n\n  (* This function has a straightforward correctness proof in terms of our\n   * [denote] functions. *)\n\n  Lemma flatten_correct' : forall ml2 ml1,\n    mldenote (ml1 ++ ml2) = mldenote ml1 + mldenote ml2.\n  Proof.\n    induction ml1; simplify; equality.\n  Qed.\n\n  Hint Rewrite flatten_correct'.\n\n  Theorem flatten_correct : forall me, mdenote me = mldenote (flatten me).\n  Proof.\n    induction me; simplify; equality.\n  Qed.\n\n  (* Now it is easy to prove a theorem that will be the main tool behind our\n   * simplification tactic. *)\n\n  Theorem monoid_reflect : forall me1 me2,\n    mldenote (flatten me1) = mldenote (flatten me2)\n    -> mdenote me1 = mdenote me2.\n  Proof.\n    simplify; 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\n   * reify each and change the goal to refer to the reified versions, finishing\n   * off by applying [monoid_reflect] and simplifying uses of [mldenote]. *)\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; simplify\n    end.\n\n  (* We can make short work of theorems like this one: *)\n\n  Theorem t1 : forall a b c d, a + b + c + d = a + (b + c) + d.\n    simplify; monoid.\n\n    (* Our tactic has canonicalized both sides of the equality, such that we can\n     * 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  Set Printing All.\n  Print t1.\n  Unset Printing All.\n\n  (* The proof term contains only restatements of the equality operands in\n   * reified form, followed by a use of reflexivity on the shared canonical\n   * form. *)\nEnd monoid.\n\n(* Extensions of this basic approach are used in the implementations of the\n * [ring] and [field] tactics that come packaged with Coq. *)\n\n\n(** * Set Simplification for Model Checking *)\n\n(* Let's take a closer look at model-checking proofs like from last class. *)\n\n(* Here's a simple transition system, where state is just a [nat], and where\n * each step subtracts 1 or 2. *)\n\nInductive subtract_step : nat -> nat -> Prop :=\n| Subtract1 : forall n, subtract_step (S n) n\n| Subtract2 : forall n, subtract_step (S (S n)) n.\n\nDefinition subtract_sys (n : nat) : trsys nat := {|\n  Initial := {n};\n  Step := subtract_step\n|}.\n\nLemma subtract_ok :\n  invariantFor (subtract_sys 5)\n               (fun n => n <= 5).\nProof.\n  eapply invariant_weaken.\n\n  apply multiStepClosure_ok.\n  simplify.\n  (* Here we'll see that the Frap libary uses slightly different, optimized\n   * versions of the model-checking relations.  For instance, [multiStepClosure]\n   * takes an extra set argument, the _worklist_ recording newly discovered\n   * states.  There is no point in following edges out of states that were\n   * already known at previous steps. *)\n\n  (* Now, some more manual iterations: *)\n  eapply MscStep.\n  closure.\n  (* Ew.  What a big, ugly set expression.  Let's shrink it down to something\n   * more readable, with duplicates removed, etc. *)\n  simplify.\n  (* How does the Frap library do that?  Proof by reflection is a big part of\n   * it!  Let's develop a baby version of that automation.  The full-scale\n   * version is in file Sets.v. *)\nAbort.\n\n(* We'll specialize our representation to unions of set literals, whose elements\n * are constant [nat]s.  The full-scale version in the library is more\n * flexible. *)\nInductive setexpr :=\n| Literal (ns : list nat)\n| Union (e1 e2 : setexpr).\n\n(* Here's what our expressions mean. *)\nFixpoint setexprDenote (e : setexpr) : set nat :=\n  match e with\n  | Literal ns => constant ns\n  | Union e1 e2 => setexprDenote e1 \\cup setexprDenote e2\n  end.\n\n(* Simplification reduces all expressions to flat, duplicate-free set\n * literals. *)\nFixpoint normalize (e : setexpr) : list nat :=\n  match e with\n  | Literal ns => dedup ns\n  | Union e1 e2 => setmerge (normalize e1) (normalize e2)\n  end.\n(* Here we use functions [dedup] and [setmerge] from the Sets module, which is\n * especially handy because that module has proved some key theorems about\n * them. *)\n\n(* Let's prove that normalization doesn't change meaning. *)\nTheorem normalize_ok : forall e,\n    setexprDenote e = constant (normalize e).\nProof.\n  induct e; simpl. (* Here we use the more primitive [simpl], because [simplify]\n                    * calls the fancier set automation from the book library,\n                    * which would be \"cheating.\" *)\n\n  pose proof (constant_dedup (fun x => x) ns).\n  repeat rewrite map_id in H.\n  equality.\n\n  rewrite IHe1, IHe2.\n  pose proof (constant_map_setmerge (fun x => x) (normalize e2) (normalize e1)).\n  repeat rewrite map_id in H.\n  equality.\nQed.\n\n(* Reification works as before, with one twist. *)\nLtac reify_set E :=\n  match E with\n  | constant ?ns => constr:(Literal ns)\n  | ?E1 \\cup ?E2 =>\n    let e1 := reify_set E1 in\n    let e2 := reify_set E2 in\n    constr:(Union e1 e2)\n  | _ => let pf := constr:(eq_refl : E = {}) in constr:(Literal [])\n    (* The twist is in this case: we instantiate all unification variables with\n     * the empty set.  It's a sound proof step, and it so happens that we only\n     * call this tactic in spots where this heuristic makes sense. *)\n  end.\n\n(* Now the usual recipe for a reflective tactic, this time using rewriting\n * instead of [apply] for the key step, to allow simplification deep within the\n * structure of a goal. *)\nLtac simplify_set :=\n  match goal with\n  | [ |- context[?X \\cup ?Y] ] =>\n    let e := reify_set (X \\cup Y) in\n    let Heq := fresh in\n    assert (Heq : X \\cup Y = setexprDenote e) by reflexivity;\n    rewrite Heq; clear Heq;\n    rewrite normalize_ok; simpl\n  end.\n\n(* Back to our example, which we can now finish without calling [simplify] to\n * reduces trees of union operations. *)\nLemma subtract_ok :\n  invariantFor (subtract_sys 5)\n               (fun n => n <= 5).\nProof.\n  eapply invariant_weaken.\n\n  apply multiStepClosure_ok.\n  simplify.\n\n  (* Now, some more manual iterations: *)\n  eapply MscStep.\n  closure.\n  simplify_set.\n  (* Success!  One subexpression shrunk.  Now for the other. *)\n  simplify_set.\n  (* Our automation doesn't handle set difference, so we finish up calling the\n   * library tactic. *)\n  simplify.\n\n  eapply MscStep.\n  closure.\n  simplify_set.\n  simplify_set.\n  simplify.\n\n  eapply MscStep.\n  closure.\n  simplify_set.\n  simplify_set.\n  simplify.\n\n  eapply MscStep.\n  closure.\n  simplify_set.\n  simplify_set.\n  simplify.\n\n  model_check_done.\n\n  simplify.\n  linear_arithmetic.\nQed.\n\n\n(** * A Smarter Tautology Solver *)\n\n(* Now we are ready to revisit our earlier tautology-solver example.  We want to\n * broaden the scope of the tactic to include formulas whose truth is not\n * syntactically apparent.  We will want to allow injection of arbitrary\n * formulas, like we allowed arbitrary monoid expressions in the last example.\n * Since we are working in a richer theory, it is important to be able to use\n * equalities between different injected formulas.  For instance, we cannot\n * prove [P -> P] by translating the formula into a value like\n * [Imp (Var P) (Var P)], because a Gallina function has no way of comparing the\n * two [P]s for equality. *)\n\n(* We introduce a synonym for how we name variables: natural numbers. *)\nDefinition propvar := nat.\n\nInductive formula : Set :=\n| Atomic : propvar -> formula\n| Truth : formula\n| Falsehood : formula\n| And : formula -> formula -> formula\n| Or : formula -> formula -> formula\n| Imp : formula -> formula -> formula.\n\n(* Now we can define our denotation function.  First, a type of truth-value\n * assignments to propositional variables: *)\nDefinition asgn := nat -> Prop.\n\nFixpoint formulaDenote (atomics : asgn) (f : formula) : Prop :=\n  match f with\n    | Atomic v => atomics v\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\n  (* Now we are ready to define some helpful functions based on the [ListSet]\n   * module of the standard library, which (unsurprisingly) presents a view of\n   * lists as sets. *)\n\n  Require Import ListSet.\n\n  (* The [eq_nat_dec] below is a richly typed equality test on [nat]s.  We'll\n   * get to the ideas behind it next week. *)\n  Definition add (s : set propvar) (v : propvar) := set_add eq_nat_dec v s.\n\n  (* We define what it means for all members of an variable set to represent\n   * true propositions, and we prove some lemmas about this notion. *)\n\n  Fixpoint allTrue (s : set propvar) : Prop :=\n    match s with\n      | nil => True\n      | v :: s' => atomics v /\\ allTrue s'\n    end.\n\n  Theorem allTrue_add : forall v s,\n    allTrue s\n    -> atomics v\n    -> allTrue (add s v).\n  Proof.\n    induct s; simplify; propositional;\n      match goal with\n        | [ |- context[if ?E then _ else _] ] => destruct E\n      end; simplify; propositional.\n  Qed.\n\n  Theorem allTrue_In : forall v s,\n    allTrue s\n    -> set_In v s\n    -> atomics v.\n  Proof.\n    induct s; simplify; equality.\n  Qed.\n\n  (* Now we can write a function [forward] that implements deconstruction of\n   * hypotheses, expanding a compound formula into a set of sets of atomic\n   * formulas covering all possible cases introduced with use of [Or].  To\n   * handle consideration of multiple cases, the function takes in a\n   * continuation argument (advanced functional-programming feature that often\n   * puzzles novices, so don't worry if it takes a while to digest!), which will\n   * be called once for each case. *)\n\n  Fixpoint forward (f : formula) (known : set propvar) (hyp : formula)\n           (cont : set propvar -> bool) : bool :=\n    match hyp with\n    | Atomic v => cont (add known v)\n    | Truth => cont known\n    | Falsehood => true\n    | And h1 h2 => forward (Imp h2 f) known h1 (fun known' =>\n                     forward f known' h2 cont)\n    | Or h1 h2 => forward f known h1 cont && forward f known h2 cont\n    | Imp _ _ => cont known\n    end.\n\n  (* A [backward] function implements analysis of the final goal.  It calls\n   * [forward] to handle implications. *)\n\n  Fixpoint backward (known : set propvar) (f : formula) : bool :=\n    match f with\n    | Atomic v => if In_dec eq_nat_dec v known then true else false\n    | Truth => true\n    | Falsehood => false\n    | And f1 f2 => backward known f1 && backward known f2\n    | Or f1 f2 => backward known f1 || backward known f2\n    | Imp f1 f2 => forward f2 known f1 (fun known' => backward known' f2)\n    end.\nEnd my_tauto.\n\nLemma forward_ok : forall atomics hyp f known cont,\n    forward f known hyp cont = true\n    -> (forall known', allTrue atomics known'\n                       -> cont known' = true\n                       -> formulaDenote atomics f)\n    -> allTrue atomics known\n    -> formulaDenote atomics hyp\n    -> formulaDenote atomics f.\nProof.\n  induct hyp; simplify; propositional.\n\n  apply H0 with (known' := add known p).\n  apply allTrue_add.\n  assumption.\n  assumption.\n  assumption.\n\n  eapply H0.\n  eassumption.\n  assumption.\n\n  eapply IHhyp1 in H.\n  simplify; propositional.\n  simplify.\n  eapply IHhyp2.\n  eassumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n\n  apply andb_true_iff in H; propositional.\n  eapply IHhyp1.\n  eassumption.\n  assumption.\n  assumption.\n  assumption.\n\n  apply andb_true_iff in H; propositional.\n  eapply IHhyp2.\n  eassumption.\n  assumption.\n  assumption.\n  assumption.\n\n  eapply H0.\n  eassumption.\n  assumption.\nQed.\n\nLemma backward_ok' : forall atomics f known,\n    backward known f = true\n    -> allTrue atomics known\n    -> formulaDenote atomics f.\nProof.\n  induct f; simplify; propositional.\n\n  cases (in_dec Nat.eq_dec p known); propositional.\n  eapply allTrue_In.\n  eassumption.\n  unfold set_In.\n  assumption.\n  equality.\n\n  equality.\n\n  apply andb_true_iff in H; propositional.\n  eapply IHf1.\n  eassumption.\n  assumption.\n\n  apply andb_true_iff in H; propositional.\n  eapply IHf2.\n  eassumption.\n  assumption.\n\n  apply orb_true_iff in H; propositional.\n  left.\n  eapply IHf1.\n  eassumption.\n  assumption.\n  right.\n  eapply IHf2.\n  eassumption.\n  assumption.\n\n  eapply forward_ok.\n  eassumption.\n  simplify.\n  eapply IHf2.\n  eassumption.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\nTheorem backward_ok : forall f,\n    backward [] f = true\n    -> forall atomics, formulaDenote atomics f.\nProof.\n  simplify.\n  apply backward_ok' with (known := []).\n  assumption.\n  simplify.\n  propositional.\nQed.\n\n(* Find the position of an element in a list. *)\nLtac position x ls :=\n  match ls with\n  | [] => constr:(@None nat)\n  | x :: _ => constr:(Some 0)\n  | _ :: ?ls' =>\n    let p := position x ls' in\n    match p with\n    | None => p\n    | Some ?n => constr:(Some (S n))\n    end\n  end.\n\n(* Compute a duplicate-free list of all variables in [P], combining it with\n * [acc]. *)\nLtac vars_in P acc :=\n  match P with\n  | True => acc\n  | False => acc\n  | ?Q1 /\\ ?Q2 =>\n    let acc' := vars_in Q1 acc in\n    vars_in Q2 acc'\n  | ?Q1 \\/ ?Q2 =>\n    let acc' := vars_in Q1 acc in\n    vars_in Q2 acc'\n  | ?Q1 -> ?Q2 =>\n    let acc' := vars_in Q1 acc in\n    vars_in Q2 acc'\n  | _ =>\n    let pos := position P acc in\n    match pos with\n    | Some _ => acc\n    | None => constr:(P :: acc)\n    end\n  end.\n\n(* Reification of formula [P], with a pregenertaed list [vars] of variables it\n * may mention *)\nLtac reify_tauto' P vars :=\n  match P with\n  | True => Truth\n  | False => Falsehood\n  | ?Q1 /\\ ?Q2 =>\n    let q1 := reify_tauto' Q1 vars in\n    let q2 := reify_tauto' Q2 vars in\n    constr:(And q1 q2)\n  | ?Q1 \\/ ?Q2 =>\n    let q1 := reify_tauto' Q1 vars in\n    let q2 := reify_tauto' Q2 vars in\n    constr:(Or q1 q2)\n  | ?Q1 -> ?Q2 =>\n    let q1 := reify_tauto' Q1 vars in\n    let q2 := reify_tauto' Q2 vars in\n    constr:(Imp q1 q2)\n  | _ =>\n    let pos := position P vars in\n    match pos with\n    | Some ?pos' => constr:(Atomic pos')\n    end\n  end.\n\n(* Our final tactic implementation is now fairly straightforward.  First, we\n * [intro] all quantifiers that do not bind [Prop]s.  Then we reify.  Finally,\n * we call the verified procedure through a lemma. *)\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  match goal with\n    | [ |- ?P ] =>\n      let vars := vars_in P (@nil Prop) in\n      let p := reify_tauto' P vars in\n      change (formulaDenote (nth_default False vars) p)\n  end;\n  apply backward_ok; reflexivity.\n\n(* A few examples demonstrate how the tactic works: *)\n\nTheorem mt1 : True.\nProof.\n  my_tauto.\nQed.\n\nPrint mt1.\n\nTheorem mt2 : forall x y : nat, x = y -> x = y.\nProof.\n  my_tauto.\nQed.\n\nPrint mt2.\n\n(* Crucially, both instances of [x = y] are represented with the same variable\n * 0. *)\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).\nProof.\n  my_tauto.\nQed.\n\nPrint mt3.\n\n(* Our goal contained three distinct atomic formulas, and we see that a\n * three-element environment is generated.\n *\n * It can be interesting to observe differences between the level of repetition\n * in proof terms generated by [my_tauto] and [tauto] for especially trivial\n * theorems. *)\n\nTheorem mt4 : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False.\nProof.\n  my_tauto.\nQed.\n\nPrint mt4.\n\nTheorem mt4' : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False.\nProof.\n  tauto.\nQed.\n\nPrint mt4'.\n\n(* The traditional [tauto] tactic introduces a quadratic blow-up in the size of\n * the proof term, whereas proofs produced by [my_tauto] always have linear\n * size. *)\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/ProofByReflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7530509417404555}}
{"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.\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.\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. lfind.  rewrite <- plus_assoc.  reflexivity. \nAdmitted.\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_distrib_96_plus_commut/goal86.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984213, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7530071450765501}}
{"text": "Require Import HoTT.\nRequire Import ED.polynomial.\nRequire Import ED.hit_structure.\n\n(** A groupoid consists of a relation with a certain structure.\n   This relation has two parts.\n   First of all, it has objects.\n   Second of all, for each pair of objects there is a set of arrows between them.\n*)\nDefinition relation (A : Type) := A -> A -> Type.\n\n(** Now we can define what a groupoid is.\n    In addition to a relation, we also have algebraic structure.\n*)\nRecord groupoid (A : Type) :=\n  Build_grpd { hom : relation A ;\n               e : forall (x : A), hom x x ;\n               inv : forall (x y : A), hom x y -> hom y x ;\n               comp : forall (x y z : A), hom x y -> hom y z -> hom x z ;\n               ca : forall (x y z v : A) (p : hom x y) (q : hom y z) (r : hom z v),\n                   comp _ _ _ p (comp _ _ _ q r) = comp _ _ _ (comp _ _ _ p q) r ;\n               ce : forall (x y : A) (p : hom x y), comp x y y p (e y) = p ;\n               ec : forall (x y : A) (p : hom x y), comp x x y (e x) p = p ;\n               ci : forall (x y : A) (p : hom x y), comp x y x p (inv x y p) = e x ;\n               ic : forall (x y : A) (p : hom x y), comp y x y (inv x y p) p = e y ;\n             }.\n\nArguments e {_} {_} _.\nArguments hom {_} _.\nArguments inv {_} {_} {_} {_}.\nNotation \"p × q\" := (comp _ _ _ _ _ p q) (at level 80).\n\n(** Now let's discuss some examples of groupoids.\n    The first example is the paths on a certain type.\n*)\nDefinition path_space (X : Type) : relation X\n  := fun (x y : X) => x = y.\n\nDefinition path_groupoid (X : Type) : groupoid X.\nProof.\n  unshelve esplit ; simpl.\n  - exact (path_space X).\n  - exact (fun _ => idpath).\n  - exact (fun _ _ => fun p => p^).\n  - exact (fun _ _ _ p q => p @ q).\n  - intros ; apply concat_p_pp.\n  - intros ; apply concat_p1.\n  - intros ; apply concat_1p.\n  - intros ; apply concat_pV.\n  - intros ; apply concat_Vp.\nDefined.\n\n(** Groupoids are closed under products. *)\nDefinition prod_groupoid\n           (A B : Type) (G₁ : groupoid A) (G₂ : groupoid B)\n  : groupoid (A * B).\nProof.\n  unshelve esplit.\n  - exact (fun x y => hom G₁ (fst x) (fst y) * hom G₂ (snd x) (snd y)).\n  - intros ; simpl.\n    split ; apply e.\n  - intros ? ? [p1 p2] ; simpl.\n    exact (inv p1, inv p2).\n  - intros ? ? ? [p1 p2] [q1 q2].\n    exact (p1 × q1, p2 × q2).\n  - intros ? ? ? ? [p1 p2] [q1 q2] [r1 r2].\n    apply path_prod ; apply ca.\n  - intros ? ? [p1 p2].\n    apply path_prod ; apply ce.\n  - intros ? ? [p1 p2].\n    apply path_prod ; apply ec.\n  - intros ? ? [p1 p2].\n    apply path_prod ; apply ci.\n  - intros ? ? [p1 p2].\n    apply path_prod ; apply ic.\nDefined.\n\n(** Groupoids are closed under sums. *)\nDefinition sum_groupoid\n           (A B : Type) (G₁ : groupoid A) (G₂ : groupoid B)\n  : groupoid (A + B).\nProof.\n  unshelve esplit.\n  - exact (fun x y =>\n             match x, y with\n             | inl x, inl y => hom G₁ x y\n             | inl _, inr _ => Empty\n             | inr _, inl _ => Empty\n             | inr x, inr y => hom G₂ x y\n             end).\n  - intros [x | x] ; apply e.\n  - intros [? | ?] [? | ?] ; contradiction || apply inv.\n  - intros [? | ?] [? | ?] [? | ?] ; contradiction || apply comp.\n  - intros [? | ?] [? | ?] [? | ?] [? | ?] ; try contradiction ; apply ca.\n  - intros [? | ?] [? | ?] ; try contradiction ; apply ce.\n  - intros [? | ?] [? | ?] ; try contradiction ; apply ec.\n  - intros [? | ?] [? | ?] ; try contradiction ; apply ci.\n  - intros [? | ?] [? | ?] ; try contradiction ; apply ic.\nDefined.    \n\n(** We can apply polynomial functors to groupoids. *)\nDefinition lift_groupoid\n           {A : Type} (G : groupoid A) (P : polynomial)\n  : groupoid (poly_act P A).\nProof.\n  induction P ; simpl.\n  - exact G.\n  - exact (path_groupoid T).\n  - apply prod_groupoid ; assumption.\n  - apply sum_groupoid ; assumption.\nDefined.\n\n(** To give specifications for these constructions, we need to define morphisms of groupoids.\n    For that, we first define morphisms of relations.\n    These come in two kinds: the underlying type could be the same or we have a map between them.\n*)\nDefinition relation_morph\n           {A B : Type}\n           (f : A -> B)\n           (R₁ : relation A) (R₂ : relation B)\n  := forall (x y : A), R₁ x y -> R₂ (f x) (f y).\n\n(** A groupoid morphism is a relation morphism which preserves the algebraic structure. *)\nClass is_grpd_morph\n      {A B : Type}\n      (f : A -> B)\n      {G₁ : groupoid A} {G₂ : groupoid B}\n      (map : relation_morph f (hom G₁) (hom G₂))\n  := { morph_e : forall (x : A), map _ _ (e x) = e (f x) ;\n       morph_i : forall (x y : A) (p : hom G₁ x y),\n           map _ _ (inv p) = inv (map _ _ p) ;\n       morph_c : forall (x y z : A) (p : hom G₁ x y) (q : hom G₁ y z),\n           map x z (p × q) = (map x y p × map y z q)\n     }.\n\nClass is_Agrpd_morph\n      {A : Type}\n      {G₁ G₂ : groupoid A}\n      (Amap : relation_morph idmap (hom G₁) (hom G₂))\n  := is_idd_Agrpd_morph : is_grpd_morph idmap Amap.\n\nGlobal Instance to_grpd_morph\n       {A : Type}\n       {G₁ G₂ : groupoid A}\n       (Amap : relation_morph idmap (hom G₁) (hom G₂))\n       `{is_Agrpd_morph _ _ _ Amap}\n  : is_grpd_morph idmap Amap.\nProof.\n  assumption.\nDefined.\n\nArguments morph_e {_} {_} _ {_} {_} _ {_} _.\nArguments morph_i {_} {_} _ {_} {_} _ {_} _ _ _.\nArguments morph_c {_} {_} _ {_} {_} _ {_} _ _ _ _ _.\n\n(** We need the identity. *)\nDefinition id_relation_morph {A : Type} (G₁ : groupoid A)\n  : relation_morph idmap (hom G₁) (hom G₁)\n  := fun _ _ => idmap.\n\nGlobal Instance id_is_Agrpd_morph {A : Type} (G₁ : groupoid A)\n  : @is_Agrpd_morph A G₁ G₁ (id_relation_morph G₁).\nProof.\n  esplit; reflexivity.\nDefined.\n\n(** Now we show lifting is functorial. *)\nDefinition sum_func\n           {A B : Type}\n           (G₁ : groupoid A) (G₂ : groupoid B)\n           (G₃ : groupoid A) (G₄ : groupoid B)\n           (F₁ : relation_morph idmap (hom G₁) (hom G₃))\n           (F₂ : relation_morph idmap (hom G₂) (hom G₄))\n  : relation_morph idmap (hom (sum_groupoid _ _ G₁ G₂)) (hom (sum_groupoid _ _ G₃ G₄)).\nProof.\n  intros [x | x] [y | y] p ; try contradiction.\n  * exact (F₁ _ _ p).\n  * exact (F₂ _ _ p).\nDefined.\n\nGlobal Instance sum_func_grpd\n           {A B : Type}\n           (G₁ : groupoid A) (G₂ : groupoid B)\n           (G₃ : groupoid A) (G₄ : groupoid B)\n           (F₁ : relation_morph idmap (hom G₁) (hom G₃))\n           (F₂ : relation_morph idmap (hom G₂) (hom G₄))\n           `{is_Agrpd_morph _ _ _ F₁}\n           `{is_Agrpd_morph _ _ _ F₂}\n  : is_Agrpd_morph (sum_func _ _ _ _ F₁ F₂).\nProof.\n  unshelve eexists.\n  + intros [x | x] ; simpl.\n    * exact (morph_e _ F₁ _).\n    * exact (morph_e _ F₂ _).\n  + intros [x | x] [y | y] p ; try contradiction ; simpl.\n    * exact (morph_i _ F₁ _ _ _).\n    * exact (morph_i _ F₂ _ _ _).\n  + intros [x | x] [y | y] [z | z] p q ; try contradiction ; simpl.\n    * exact (morph_c _ F₁ _ _ _ _ _).\n    * exact (morph_c _ F₂ _ _ _ _ _).\nDefined.\n\nDefinition prod_func\n           {A B : Type}\n           (G₁ : groupoid A) (G₂ : groupoid B)\n           (G₃ : groupoid A) (G₄ : groupoid B)\n           (F₁ : relation_morph idmap (hom G₁) (hom G₃))\n           (F₂ : relation_morph idmap (hom G₂) (hom G₄))\n  : relation_morph idmap (hom (prod_groupoid _ _ G₁ G₂)) (hom (prod_groupoid _ _ G₃ G₄)).\nProof.\n  intros [x1 x2] [y1 y2] p.\n  split.\n  * exact (F₁ _ _ (fst p)).\n  * exact (F₂ _ _ (snd p)).\nDefined.\n\nGlobal Instance prod_func_grpd\n       {A B : Type}\n       (G₁ : groupoid A) (G₂ : groupoid B)\n       (G₃ : groupoid A) (G₄ : groupoid B)\n       (F₁ : relation_morph idmap (hom G₁) (hom G₃))\n       (F₂ : relation_morph idmap (hom G₂) (hom G₄))\n       `{is_Agrpd_morph _ _ _ F₁}\n       `{is_Agrpd_morph _ _ _ F₂}\n  : is_Agrpd_morph (prod_func _ _ _ _ F₁ F₂).\nProof.\n  unshelve eexists.\n  + intros [x1 x2] ; simpl.\n    apply path_prod'.\n    * exact (morph_e _ F₁ _).\n    * exact (morph_e _ F₂ _).\n  + intros [x1 x2] [y1 y2] p ; simpl.\n    apply path_prod'.\n    * exact (morph_i _ F₁ _ _ _).\n    * exact (morph_i _ F₂ _ _ _).\n  + intros [x1 x2] [y1 y2] [z1 z2] p q ; simpl.\n    apply path_prod'.\n    * exact (morph_c _ F₁ _ _ _ _ _).\n    * exact (morph_c _ F₂ _ _ _ _ _).\nDefined.\n\nDefinition poly_func\n           {A : Type}\n           (P : polynomial)\n           (G₁ G₂ : groupoid A)\n           (F₁ : relation_morph idmap (hom G₁) (hom G₂))\n  : relation_morph idmap (hom (lift_groupoid G₁ P)) (hom (lift_groupoid G₂ P)).\nProof.\n  induction P ; simpl.\n  - exact F₁.\n  - apply (id_relation_morph (path_groupoid T)).\n  - apply prod_func ; assumption.\n  - apply sum_func ; assumption.\nDefined.\n\nGlobal Instance poly_func_grpd\n       {A : Type}\n       (P : polynomial)\n       (G₁ G₂ : groupoid A)\n       (F₁ : relation_morph idmap (hom G₁) (hom G₂))\n       `{is_Agrpd_morph _ _ _ F₁}\n  : is_Agrpd_morph (poly_func P G₁ G₂ F₁).\nProof.\n  induction P ; apply _.\nDefined.\n\n(** Now we suppose that we are given a HIT.\n    We define a class of groupoids with the same structure as the path space of that HIT.\n*)\nSection H_alg.\n  Variable (Σ : hit_signature) (H : HIT Σ).\n\n  (** First of all, we have the `ap` operation on paths.\n      This gives an algebra structure using the lifted groupoid.\n   *)\n  (** For every constuctor `C_i : P_i[H] -> H` of `H`, require a morphism\n        P_i[G] -> G\n      which lies over `C_i`.\n   *)\n  Definition hit_point_morph (G : groupoid H) (i : sig_point_index Σ) :=\n    relation_morph\n      (hit_point i)\n      (hom (lift_groupoid G (sig_point Σ i)))\n      (hom G).\n  \n  Definition P_alg (G : groupoid H) : Type\n    := forall (i : sig_point_index Σ), hit_point_morph G i.\n\n  (** Second of all, we need to have the path constructors. *)\n  Definition contains\n             {A B : Type}\n             (G : groupoid B)\n             (f g : A -> B)\n    := forall (x : A), hom G (f x) (g x).\n\n  (** Lastly, we need a coherency.\n      The path constructors can be obtained in two ways.\n      Either we can use `contains` or we can use `transport`.\n   *)\n  Definition coherent\n             (j : sig_path_index Σ)\n             (G : groupoid H)\n             (Gpath : contains G\n                   (endpoint_act hit_point (sig_path_lhs Σ j))\n                   (endpoint_act hit_point (sig_path_rhs Σ j)))\n    : Type\n    := forall (u : poly_act (sig_path_param Σ j) H),\n      Gpath u = transport (fun z => hom G _ z) (hit_path j u) (e _).\n    \n  (** Now we can define the structure of the path space. *)\n  Record Halg :=\n    { H_grpd : groupoid H ;\n      point_alg : P_alg H_grpd ;\n      point_alg_grpd :\n        forall (i : sig_point_index Σ),\n          is_grpd_morph (hit_point i) (point_alg i);\n      path_alg : forall (j : sig_path_index Σ),\n          contains H_grpd\n                   (endpoint_act hit_point (sig_path_lhs Σ j))\n                   (endpoint_act hit_point (sig_path_rhs Σ j)) ;\n      coherent_alg : forall (j : sig_path_index Σ),\n          coherent j H_grpd (path_alg j)\n    }.\n\n  (** For the morphisms, we have multiple requirements. *)\n  Definition preserves_alg\n             {G₁ G₂ : Halg}\n             (F : relation_morph idmap (hom (H_grpd G₁)) (hom (H_grpd G₂)))\n    : Type\n    := forall (i : sig_point_index Σ)\n              (a₁ a₂ : poly_act (sig_point Σ i) H)\n              (x : hom (lift_groupoid (H_grpd G₁) (sig_point Σ i)) a₁ a₂),\n      F _ _ ((point_alg G₁ i) _ _ x)\n      =\n      (point_alg G₂ i)\n        _\n        _\n        ((poly_func (sig_point Σ i) (H_grpd G₁) (H_grpd G₂) F) _ _ x).    \n  \n  Definition preserves_paths\n             {G₁ G₂ : Halg}\n             (F : relation_morph idmap (hom (H_grpd G₁)) (hom (H_grpd G₂)))\n    : Type\n    := forall (j : sig_path_index Σ) (u : poly_act (sig_path_param Σ j) H),\n      path_alg G₂ j u = F _ _ (path_alg G₁ j u).\n\n  Class isHalg_morph\n        (G₁ G₂ : Halg)\n        (F : relation_morph idmap (hom (H_grpd G₁)) (hom (H_grpd G₂)))\n    := { p_alg : preserves_alg F ;\n         p_paths : preserves_paths F}.\nEnd H_alg.", "meta": {"author": "nmvdw", "repo": "encode-decode", "sha": "4855e454541cc5ac4c555a7a64148722f295da29", "save_path": "github-repos/coq/nmvdw-encode-decode", "path": "github-repos/coq/nmvdw-encode-decode/encode-decode-4855e454541cc5ac4c555a7a64148722f295da29/wild_groupoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7529620266473531}}
{"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. (* The assertion we've just made \ncan be proved by observing that both sides of the equality \nevaluate to the same thing *)\n\n\n(* def bool type *)\n\nInductive bool : Type :=\n  | true \n  | false. \n\n(* functions over booleans *)\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\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\n(* using Notation *) \nNotation \"x && y\" := (andb x y). \nNotation \"x || y\" := (orb x y). \nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* conditional expressions *) \nDefinition negb' (b:bool) : bool :=\n  if b then false \n  else true. \n\n\n\n\n\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/lessons/intro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7528823364937205}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.bitblast.\nRequire Import coqutil.Z.ZLib.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Z.div_mod_to_equations.\n\n\nLocal Open Scope Z_scope.\n\nLemma or_to_plus: forall a b,\n    Z.land a b = 0 ->\n    Z.lor a b = a + b.\nProof.\n  intros.\n  rewrite <- Z.lxor_lor by assumption.\n  symmetry. apply Z.add_nocarry_lxor. assumption.\nQed.\n\n\n(** ** bitSlice *)\n\nDefinition bitSlice(x: Z)(start eend: Z): Z :=\n  Z.land (Z.shiftr x start) (Z.lnot (Z.shiftl (-1) (eend - start))).\n\nDefinition bitSlice'(w start eend: Z): Z :=\n  (w / 2 ^ start) mod (2 ^ (eend - start)).\n\nLemma bitSlice_alt: forall w start eend,\n    0 <= start <= eend ->\n    bitSlice w start eend = bitSlice' w start eend.\nProof.\n  intros. unfold bitSlice, bitSlice'.\n  rewrite <- Z.land_ones by blia.\n  rewrite <- Z.shiftr_div_pow2 by blia.\n  f_equal.\n  rewrite Z.shiftl_mul_pow2 by blia.\n  rewrite Z.mul_comm.\n  rewrite <- Z.opp_eq_mul_m1.\n  replace (Z.lnot (- 2 ^ (eend - start))) with (2 ^ (eend - start) - 1).\n  - rewrite Z.ones_equiv. reflexivity.\n  - pose proof (Z.add_lnot_diag (- 2 ^ (eend - start))). blia.\nQed.\n\nLemma bitSlice_range: forall sz z,\n    0 <= sz ->\n    0 <= bitSlice z 0 sz < 2 ^ sz.\nProof.\n  intros.\n  rewrite bitSlice_alt by blia.\n  unfold bitSlice'.\n  change (2 ^ 0) with 1.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  apply Z.mod_pos_bound.\n  apply Z.pow_pos_nonneg; blia.\nQed.\n\nLemma bitSlice_split: forall sz1 sz2 v,\n    0 <= sz1 ->\n    0 <= sz2 ->\n    bitSlice v sz1 (sz1 + sz2) * 2 ^ sz1 + bitSlice v 0 sz1 = bitSlice v 0 (sz1 + sz2).\nProof.\n  intros. rewrite? bitSlice_alt by blia. unfold bitSlice'.\n  change (2 ^ 0)%Z with 1%Z.\n  rewrite Z.div_1_r.\n  rewrite! Z.sub_0_r.\n  replace (sz1 + sz2 - sz1)%Z with sz2 by blia.\n  rewrite Z.pow_add_r by assumption.\n  assert (0 < 2 ^ sz1)%Z by (apply Z.pow_pos_nonneg; blia).\n  assert (0 < 2 ^ sz2)%Z by (apply Z.pow_pos_nonneg; blia).\n  rewrite Z.rem_mul_r by blia.\n  Lia.nia.\nQed.\n\nLemma bitSlice_all_nonneg: forall n v : Z,\n    0 <= n ->\n    0 <= v < 2 ^ n ->\n    bitSlice v 0 n = v.\nProof.\n  clear. intros.\n  rewrite bitSlice_alt by blia.\n  unfold bitSlice'.\n  change (2 ^ 0) with 1.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  apply Z.mod_small.\n  assumption.\nQed.\n\nLemma bitSlice_all_neg: forall n v : Z,\n    0 <= n ->\n    - 2 ^ n <= v < 0 ->\n    bitSlice v 0 n = 2 ^ n + v.\nProof.\n  clear. intros.\n  rewrite bitSlice_alt by blia.\n  unfold bitSlice'.\n  change (2 ^ 0)%Z with 1%Z.\n  rewrite Z.div_1_r.\n  rewrite Z.sub_0_r.\n  assert (0 < 2 ^ n)%Z. {\n    apply Z.pow_pos_nonneg; blia.\n  }\n  Z.div_mod_to_equations.\n  rewrite H2 in * by blia.\n  clear H2 v.\n  rewrite Z.add_assoc.\n  assert (q = -1)%Z by Lia.nia.\n  subst q.\n  Lia.nia.\nQed.\n\nLemma bitSlice_nonneg: forall start eend v,\n    0 <= bitSlice v start eend.\nProof.\n  intros. unfold bitSlice.\n  eapply Z.land_nonneg.\n  right.\n  eapply Z.lnot_nonneg.\n  eapply Z.shiftl_neg.\n  reflexivity.\nQed.\n\nLemma bitSlice_upper_bound: forall start eend v,\n    bitSlice v start eend < 2 ^ (Z.max 0 (eend - start)).\nProof.\n  intros. unfold bitSlice.\n  assert (eend - start < 0 \\/ 0 <= eend - start) as C by Lia.lia.\n  destruct C.\n  - rewrite Z.shiftl_minus_one_neg by Lia.lia.\n    change (Z.lnot (-1)) with 0.\n    rewrite Z.land_0_r.\n    replace (Z.max 0 (eend - start)) with 0 by Lia.lia.\n    reflexivity.\n  - replace (Z.max 0 (eend - start)) with (eend - start) by Lia.lia.\n    rewrite Z.shiftl_mul_pow2 by assumption.\n    rewrite Z.mul_comm.\n    rewrite <- Z.opp_eq_mul_m1.\n    replace (Z.lnot (- 2 ^ (eend - start))) with (Z.pred (2 ^ (eend - start))). 2: {\n       pose proof (Z.add_lnot_diag (- 2 ^ (eend - start))). Lia.lia.\n    }\n    rewrite <- Z.ones_equiv.\n    rewrite Z.land_ones by assumption.\n    eapply Z.mod_pos_bound.\n    apply Z.pow_pos_nonneg. 1: reflexivity. assumption.\nQed.\n\nLemma bitSlice_bounds: forall start eend v,\n    0 <= bitSlice v start eend < 2 ^ (Z.max 0 (eend - start)).\nProof. eauto using bitSlice_nonneg, bitSlice_upper_bound. Qed.\n\nLemma mod20_bitSlice: forall n,\n    bitSlice n 0 1 = 0 ->\n    n mod 2 = 0.\nProof.\n  intros. rewrite bitSlice_alt in H by Lia.lia.\n  unfold bitSlice' in *.\n  Z.div_mod_to_equations.\n  Lia.lia.\nQed.\n\n\n(** ** signExtend *)\n\nDefinition signExtend(oldwidth: Z)(z: Z): Z :=\n  (z + 2^(oldwidth-1)) mod 2^oldwidth - 2^(oldwidth-1).\n\nDefinition signExtend_bitwise(width n: Z): Z :=\n  if Z.testbit n (width - 1)\n  then (Z.lor (Z.land n (Z.ones width)) (Z.shiftl (-1) width))\n  else (Z.land n (Z.ones width)).\n\nLemma signExtend_alt_bitwise: forall l n,\n    0 < l ->\n    signExtend l n = signExtend_bitwise l n.\nProof.\n  intros.\n  unfold signExtend, signExtend_bitwise.\n  assert (0 < 2 ^ l) as A by (apply Z.pow_pos_nonneg; blia).\n  assert (0 < 2 ^ (l - 1)) as A' by (apply Z.pow_pos_nonneg; blia).\n  destruct (Z.testbit n (l - 1)) eqn: E.\n  - rewrite or_to_plus by Z.bitblast.\n    rewrite Z.shiftl_mul_pow2 by blia.\n    rewrite Z.land_ones by blia.\n    apply Z.testbit_true in E; [|blia].\n    do 2 rewrite Z.mod_eq by blia.\n    replace (2 ^ l) with (2 ^ ((l - 1) + 1)) by (f_equal; blia).\n    rewrite Z.pow_add_r in * by blia.\n    change (2 ^ 1) with 2 in *.\n    replace (n + 2 ^ (l - 1)) with (n + 1 * 2 ^ (l - 1)) at 2 by blia.\n    rewrite <-! Z.div_div by blia.\n    rewrite Z_div_plus_full by blia.\n    rewrite Z.mod_eq in E by blia.\n    rewrite <-! Z.mul_assoc.\n    replace (n / 2 ^ (l - 1)) with (2 * (n / 2 ^ (l - 1) / 2) + 1) at 1 by blia.\n    rewrite <- Z.add_assoc.\n    change (1 + 1) with (1 * 2).\n    rewrite Z_div_plus_full by blia.\n    remember (n / 2 ^ (l - 1) / 2) as X.\n    rewrite Z.mul_add_distr_l.\n    rewrite (Z.mul_comm 2 X).\n    rewrite Z.div_mul by blia.\n    blia.\n  - rewrite Z.land_ones by blia.\n    apply Z.testbit_false in E; [|blia].\n    do 2 rewrite Z.mod_eq by blia.\n    replace (2 ^ l) with (2 ^ ((l - 1) + 1)) by (f_equal; blia).\n    rewrite Z.pow_add_r in * by blia.\n    change (2 ^ 1) with 2 in *.\n    replace (n + 2 ^ (l - 1)) with (n + 1 * 2 ^ (l - 1)) at 2 by blia.\n    rewrite <-! Z.div_div by blia.\n    rewrite Z_div_plus_full by blia.\n    rewrite Z.mod_eq in E by blia.\n    rewrite <-! Z.mul_assoc.\n    replace (n / 2 ^ (l - 1)) with (2 * (n / 2 ^ (l - 1) / 2)) at 1 by blia.\n    remember (n / 2 ^ (l - 1) / 2) as X.\n    replace (2 * X + 1) with (1 + X * 2) by blia.\n    rewrite Z_div_plus_full by blia.\n    change (1 / 2 + X) with X.\n    blia.\nQed.\n\nLemma signExtend_range: forall i z,\n    0 < i ->\n    - 2 ^ (i - 1) <= signExtend i z < 2 ^ (i - 1).\nProof.\n  intros.\n  unfold signExtend.\n  pose proof (Z.mod_pos_bound (z + (2 ^ (i - 1))) (2 ^ i)) as P.\n  assert (0 < 2 ^ i) as A. {\n    apply Z.pow_pos_nonneg; blia.\n  }\n  specialize (P A).\n  replace (2 ^ i) with (2 ^ ((i - 1) + 1)) in * by (f_equal; blia).\n  rewrite Z.pow_add_r in * by blia.\n  change (2 ^ 1) with 2 in *.\n  remember (2 ^ (i - 1)) as B.\n  blia.\nQed.\n\nLemma signExtend_bounds: forall i z,\n    0 <= i -> - 2 ^ i <= signExtend (i + 1) z < 2 ^ i.\nProof.\n  intros. pose proof (signExtend_range (i + 1) z) as P.\n  replace (i + 1 - 1) with i in P by Lia.lia. eapply P. Lia.lia.\nQed.\n\nLemma signExtend_nop: forall l w v,\n    - 2 ^ l <= v < 2 ^ l ->\n    0 <= l < w ->\n    signExtend w v = v.\nProof.\n  intros.\n  unfold signExtend.\n  assert (2 ^ (w - 1) * 2 = 2 ^ w). {\n    replace w with (w - 1 + 1) at 2 by blia.\n    rewrite Z.pow_add_r by blia.\n    reflexivity.\n  }\n  pose proof (Z.pow_le_mono_r 2 l (w-1)).\n  rewrite Z.mod_small; blia.\nQed.\n", "meta": {"author": "mit-plv", "repo": "coqutil", "sha": "48eeef16cc9aa3a057d4a76207b88b34fd397e24", "save_path": "github-repos/coq/mit-plv-coqutil", "path": "github-repos/coq/mit-plv-coqutil/coqutil-48eeef16cc9aa3a057d4a76207b88b34fd397e24/src/coqutil/Z/BitOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7528823358237324}}
{"text": "(* Bianchi, Gabina Luz - Parcial 1 *)\n\n(*Ejercicio 1*)\nSection Problema1.\nVariables L O I C : Prop.\nDefinition R1 := (L -> O) /\\ (I -> C). (* Si era leal, habrìa obedecido las órdenes, y si era inteligente, las habría comprendido*)\nDefinition R2 := ~ O \\/ ~ C. (* O el general desobedeció las órdenes o no las comprendió*)\nDefinition Conclusion :=  ~ L \\/ ~ I. (*el general era desleal o no era inteligente*)\n\n\nVariable p q : Prop.\nLemma contra :forall p q : Prop, (p -> q) -> (~q -> ~p).\nProof.\nintros.\nunfold not.\nintro.\nabsurd q0.\nassumption.\napply H.\nassumption. \nQed.\n\nLemma ej1: (R1 /\\ R2) -> Conclusion.\nProof.\nunfold R1.\nunfold R2.\nunfold Conclusion.\nintros.\nelim H; intros.\nelim H0; intros.\nelim H1; intros.\nleft.\napply (contra L O H2).\nassumption.\nright.\napply (contra I C H3).\nassumption.\nQed.\n\nEnd Problema1.\n\n(*Ejercicio 2*)\nSection Problema2.\nRequire Import Classical.\nVariable C : Set.\nVariable P : C -> C -> Prop.\nLemma lema2 : (exists x : C, (exists y : C, P x y)) \\/ ~(exists x : C, P x x).\nProof.\nelim (classic (exists x : C, P x x)); intros.\nleft.\nelim H.\nintros.\n(exists x).\n(exists x).\nassumption.\nright.\nassumption.\nQed.\nEnd Problema2.\n\n(*Ejercicio 3*)\nSection Problema3.\nVariable U : Set.\nVariable a : U.\nVariables P Q R T : U -> Prop.\n\n\nLemma Ej3_1 : (forall x : U, P x -> Q x) -> P a -> Q a.\nProof.\nexact (fun (H : forall x : U, P x -> Q x) X => H a X).\nQed.\nLemma Ej3_2 : (forall x : U, P x -> Q x) -> (forall x : U, Q x -> R x) ->\nforall x : U, P x -> R x.\nProof.\nintros.\nexact (H0 x (H x H1)).\nQed.\n\nLemma L3_3: (forall x:U, Q x) \\/ (forall y:U, T y) -> forall z:U, Q z \\/ T z.\nProof.\nintros;elim H; intros; [left | right]; apply H0.\nQed.\n\nEnd Problema3.\n\n\n(*Ejercicio 4*)\n\nSection Problema4.\n\nParameter ABnat : forall n : nat, Set.\nParameter ABnull : ABnat O.\nParameter ABadd : forall (n m : nat), nat -> ABnat n -> ABnat m -> ABnat (n + m + 1).\nCheck ABadd.\n\nDefinition AB1 := ABadd O 0 7 ABnull ABnull. (* Árbol de un único nodo con valor 7*)\nCheck AB1.\nDefinition AB2 := ABadd 1 0 8 AB1 ABnull. (*Árbol con un 8 en su raíz y un 7 como hijo izquierdo*)\nCheck AB2.\nDefinition AB3 := ABadd 2 0 9 AB2 ABnull. (*Árbol pedido*)\nCheck AB3.\n\nParameter ABG : forall (X: Set) (n : nat), Set.\nParameter ABGnull : forall X : Set, ABG X O.\nParameter ABGadd : forall (X : Set) (n m : nat), X -> ABG X n -> ABG X m -> ABG X (n + m + 1).\nCheck ABGadd.\n\nEnd Problema4.\n\n(*Ejercicio 5*)\n\nSection Problema5.\n\nVariable Bool: Set.\nVariable TRUE : Bool.\nVariable FALSE : Bool.\nVariable Not : Bool -> Bool.\nVariable Imp : Bool -> Bool -> Bool.\nVariable Xor : Bool -> Bool -> Bool.\n\nAxiom Disc : ~ (FALSE = TRUE).\nAxiom BoolVal : forall b : Bool, b = TRUE \\/ b = FALSE.\nAxiom NotTrue : Not TRUE = FALSE.\nAxiom NotFalse : Not FALSE = TRUE.\nAxiom ImpFalse : forall b : Bool, Imp FALSE b = TRUE.\nAxiom ImpTrue : forall b : Bool, Imp TRUE b = b.\nAxiom XorTrue : forall b : Bool, Xor TRUE b = Not b.\nAxiom XorFalse : forall b : Bool, Xor FALSE b = b.\n\nLemma L51 : forall b: Bool, Xor b b = FALSE.\nProof.\nintros.\nelim (BoolVal b);intros; rewrite H; [rewrite XorTrue | rewrite XorFalse].\nrewrite NotTrue.\nreflexivity.\nreflexivity.\nQed.\n\nLemma L52: forall b1 b2: Bool, Imp b1 b2 = FALSE -> b1 = TRUE /\\ b2 = FALSE.\nProof.\nintros.\nelim (BoolVal b1);intros.\nrewrite H0 in H.\nrewrite ImpTrue in H.\nsplit; assumption.\nrewrite H0 in H.\nrewrite ImpFalse in H.\nsymmetry in H.\nabsurd (FALSE = TRUE).\napply Disc.\nassumption.\nQed.\n\nEnd Problema5.\n\n", "meta": {"author": "gabina", "repo": "coq", "sha": "b9e5fc6a43d0ac670816ecb57ed441863ff8e5c0", "save_path": "github-repos/coq/gabina-coq", "path": "github-repos/coq/gabina-coq/coq-b9e5fc6a43d0ac670816ecb57ed441863ff8e5c0/parcial1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7528141379203648}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 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_CmgIG8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7528141293039876}}
{"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           *)\n(*     computation during simplification, but remain compatible  with those *)\n(*     in Peano.                                                            *)\n(*     For computation, a module NatRec rebinds all arithmetic  notations   *)\n(*     to less convenient, but also less inefficient tail-recursive         *)\n(*     definitions.                                                         *)\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(*                                                                          *)\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) or x0 if n = 0             *)\n(*                                                                          *)\n(*   exponentiation, factorial                                              *)\n(*        m ^ n, fact 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(*     comparison are BOOLEAN operators, e.g. 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    *)\n(*     the same constant, \"leq\"; in particular m < n is identical to        *)\n(*     m.+1 <= n.                                                           *)\n(*                                                                          *)\n(*    conditionally strict inequality                                       *)\n(*      m <= n ?= iff c == m <= n &  (m == n) = condition                   *)\n(*     The transitivity lemma for leqif aggregates the conditions,          *)\n(*     making for arguments of the form \"m <= n <= p <= m, so equality      *)\n(*     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(*    returns the smallest n such that P n holds.                           *)\n(*                                                                          *)\n(*   positive interger                                                      *)\n(*     pos_nat                                                              *)\n(*     a subType for positive integers, with Canonical projections for most *)\n(*     arithmetic operations.                                               *)\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_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 : forall p, injective (addn p).\nProof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_addl p) Heq eqxx. Qed.\n\nLemma addIn : forall p, injective (addn^~ p).\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\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 ltn := [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 (eq_axiomK def_n2).\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 (eq_axiomK def_n2) /=; 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\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\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 n := if n is n'.+1 then n * fact n' else 1.\n\n(* A (canonical) structure for positive integers.             *)\n(* Several types parametrized by integer posses an algebraic  *)\n(* structure only for non-zero values of the parameter, e.g., *)\n(* integers mod n, or square matrices of order n. The pos_nat *)\n(* structure allows the type inference to automatically       *)\n(* discharge this positivity condition. Note that pos_nat     *)\n(* should not be used for normal arithmetic side condition:   *)\n(* as Coq does not allow to declare new instances of a        *)\n(* structure in the midst of a proof, it would be difficult   *)\n(* to satisfy the conditions for arbitrary expressions.       *)\n\nRecord pos_nat : Type := PosNat { pos_nat_val :> nat; _ : pos_nat_val > 0 }.\n\nLemma pos_natP : forall n : pos_nat, n > 0. Proof. by case. Qed.\nHint Resolve pos_natP.\n\nCanonical Structure pos_nat_subType :=\n  Eval hnf in [subType for pos_nat_val by pos_nat_rect].\nDefinition pos_nat_eqMixin := Eval hnf in [eqMixin of pos_nat by <:].\nCanonical Structure pos_nat_eqType := Eval hnf in EqType pos_nat_eqMixin.\n\nCanonical Structure S_pos_nat n := PosNat (ltn0Sn n).\n\nLemma addr_pos_natP : forall m (n : pos_nat), m + n > 0.\nProof. by move=> m n; rewrite addn_gt0 pos_natP orbT. Qed.\nCanonical Structure addr_pos_nat m n := PosNat (addr_pos_natP m n).\n\nLemma mul_pos_natP : forall (m n : pos_nat), m * n > 0.\nProof. by move=> m n; rewrite muln_gt0 !pos_natP. Qed.\nCanonical Structure mul_pos_nat m n := PosNat (mul_pos_natP m n).\n\nLemma exp_pos_natP : forall (n : pos_nat) m, n ^ m > 0.\nProof. by move=> n m; rewrite expn_gt0 pos_natP. Qed.\nCanonical Structure exp_pos_nat m n := PosNat (exp_pos_natP m n).\n\nLemma maxr_pos_natP : forall m (n : pos_nat), maxn m n > 0.\nProof. by move=> n m; rewrite leq_maxr pos_natP orbT. Qed.\nCanonical Structure maxr_pos_nat m n := PosNat (maxr_pos_natP m n).\n\nLemma min_pos_natP : forall (m n : pos_nat), minn m n > 0.\nProof. by move=> n m; rewrite leq_minr !pos_natP. Qed.\nCanonical Structure min_pos_nat m n := PosNat (min_pos_natP m n).\n\nLemma fact_gt0 : forall n, fact n > 0.\nProof. by elim=> //= n IHn; rewrite muln_gt0. Qed.\nCanonical Structure fact_pos_nat n := PosNat (fact_gt0 n).\n\nDefinition repack_pos_nat n :=\n  let: PosNat _ nP := n return (0 < n -> pos_nat) -> pos_nat in fun k => k nP.\n\nNotation \"[ 'pos_nat' 'of' n ]\" := (repack_pos_nat (fun nP => @PosNat n nP))\n  (at level 0, format \"[ 'pos_nat'  'of'  n ]\") : form_scope.\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.\nProof. by case. Qed.\n\nLemma addn_negb : forall b : bool, ~~ b + b = 1.\nProof. by 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 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 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_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/theories/ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7527372823183079}}
{"text": "Require Import Coq.omega.Omega.\n\nSection NatFacts.\n  Lemma le_r_le_max :\n    forall x y z,\n      x <= z -> x <= max y z.\n  Proof.\n    intros x y z;\n    destruct (Max.max_spec y z) as [ (comp, eq) | (comp, eq) ];\n    rewrite eq;\n    omega.\n  Qed.\n\n  Lemma le_l_le_max :\n    forall x y z,\n      x <= y -> x <= max y z.\n  Proof.\n    intros x y z.\n    rewrite Max.max_comm.\n    apply le_r_le_max.\n  Qed.\n\n  Lemma le_neq_impl :\n    forall m n, m < n -> m <> n.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma gt_neq_impl :\n    forall m n, m > n -> m <> n.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma lt_refl_False :\n    forall x,\n      lt x x -> False.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma beq_nat_eq_nat_dec :\n    forall x y,\n      beq_nat x y = if eq_nat_dec x y then true else false.\n  Proof.\n    intros; destruct (eq_nat_dec _ _); [ apply beq_nat_true_iff | apply beq_nat_false_iff ]; assumption.\n  Qed.\n\n  Lemma min_minus_l x y\n  : min (x - y) x = x - y.\n  Proof. apply Min.min_case_strong; omega. Qed.\n  Lemma min_minus_r x y\n  : min x (x - y) = x - y.\n  Proof. apply Min.min_case_strong; omega. Qed.\n\n  Lemma sub_twice x y : x - (x - y) = min x y.\n  Proof.\n    clear; apply Min.min_case_strong; intro;\n    omega.\n  Qed.\n\n  Lemma minus_ge {x y : nat} (H : x - y >= x) : {x = 0} + {y = 0}.\n  Proof. destruct x; [ left | right]; omega. Qed.\nEnd NatFacts.\n\nFixpoint minusr (n m : nat) {struct m} : nat\n  := match m with\n       | 0 => n\n       | S l => minusr (pred n) l\n     end.\n\nLemma minusr_minus n m\n: minusr n m = minus n m.\nProof.\n  revert m; induction n; simpl;\n  induction m; simpl; auto.\nQed.\n\nDelimit Scope natr_scope with natr.\nInfix \"-\" := minusr : natr_scope.\n\nModule minusr_notation.\n  Infix \"-\" := minusr : nat_scope.\nEnd minusr_notation.\n\nSection dec_prod.\n  Local Notation dec T := (T + (T -> False))%type (only parsing).\n  Context (P : nat -> Type).\n  Fixpoint dec_stabalize'\n             (max : nat)\n             (Hstable : forall n, n >= max -> P n -> P (S n))\n             (Hdec : forall n, n <= max -> dec (P n))\n             {struct max}\n  : dec (forall n, P n).\n  Proof.\n    destruct max as [|max];\n    [ clear dec_stabalize' | specialize (dec_stabalize' max) ].\n    { destruct (Hdec 0 (le_refl _)) as [Hd|Hd]; [ left | right ].\n      { intro n.\n        induction n as [|n IHn].\n        { assumption. }\n        { apply Hstable; [ auto with arith | assumption ]. } }\n      { intro Pn; apply Hd, Pn. } }\n    { destruct (Hdec (S max)) as [Hdecmax|Hdecmax];\n      [ reflexivity | | right; solve [ auto with nocore ] ].\n      apply dec_stabalize'.\n      { intros n Hn; specialize (Hstable n).\n        unfold ge in *.\n        destruct (le_lt_eq_dec _ _ Hn) as [pf|npf].\n        { auto with nocore. }\n        { intro; subst; assumption. } }\n      { intros n pf.\n        apply le_S in pf.\n        auto with nocore. } }\n  Defined.\n\n  Local Notation iffT A B := ((A -> B) * (B -> A))%type (only parsing).\n\n  Fixpoint dec_stabalize\n             (max : nat)\n             (Hstable : forall n, n >= max -> iffT (P n) (P (S n)))\n             (Hdec : forall n, n <= max -> dec (P n))\n             {struct max}\n  : ({ n : nat & (n <= max) * P n }%type + (forall n, P n -> False))%type.\n  Proof.\n    destruct max as [|max];\n    [ clear dec_stabalize | specialize (dec_stabalize max) ].\n    { destruct (Hdec 0 (le_refl _)) as [Hd|Hd]; [ left | right ].\n      { exists 0; split; [ reflexivity | assumption ]. }\n      { intros n Pn. apply Hd.\n        clear -Pn Hstable.\n        specialize (fun n => Hstable n (le_0_n _)).\n        induction n; [ assumption  | apply IHn ].\n        apply Hstable; assumption. } }\n    { destruct (Hdec (S max)) as [HdecSmax|HdecSmax];\n      [ reflexivity | | ].\n      { left; eexists; split; [ reflexivity | eassumption ]. }\n      { destruct (Hdec max) as [Hdecmax|Hdecmax];\n        [ solve [ auto with arith ] | | ].\n        { left; eexists; split; [ | eassumption ]; auto with arith. }\n        { destruct dec_stabalize as [[n [??]]|];\n          [\n          |\n          | left; exists n; split; [ solve [ auto with arith ] | assumption ]\n          | right; assumption ].\n          { intros n Hn.\n            destruct (le_lt_eq_dec _ _ Hn) as [pf|npf].\n            pose proof (Hstable n).\n            unfold ge in *.\n            { auto with nocore. }\n            { split; intro; subst;\n              exfalso; eauto with nocore. } }\n          { intros n pf.\n            apply le_S in pf.\n            auto with nocore. } } } }\n  Defined.\nEnd dec_prod.\n\nLemma nat_rect3_ext\n       {A B C D}\n       (P := fun n => forall (a : A n) (b : B n a), C n a b -> D)\n       (z z' : P 0)\n       (Hz : forall a b c, z a b c = z' a b c)\n       (s s' : forall n, P n -> P (S n))\n       (Hs : forall n f g (pf : forall a b c, f a b c = g a b c) a b c,\n               s n f a b c = s' n g a b c)\n       n a b c\n: nat_rect P z s n a b c = nat_rect P z' s' n a b c.\nProof.\n  revert a b c; induction n as [|n IHn]; simpl; intros.\n  { apply Hz. }\n  { apply Hs; intros.\n    apply IHn. }\nQed.\n\nLemma minus_plus_min x y\n: x - y + min y x = x.\nProof.\n  apply Min.min_case_strong; omega.\nQed.\n\nLemma min_case_strong_r n m (P : nat -> Type)\n: (n <= m -> P n) -> (m < n -> P m) -> P (min n m).\nProof.\n  destruct (Compare_dec.le_lt_dec n m);\n  first [ rewrite Min.min_r by omega\n        | rewrite Min.min_l by omega ];\n  auto.\nQed.\n\nLemma min_case_strong_l n m (P : nat -> Type)\n: (n < m -> P n) -> (m <= n -> P m) -> P (min n m).\nProof.\n  destruct (Compare_dec.le_lt_dec m n);\n  first [ rewrite Min.min_r by omega\n        | rewrite Min.min_l by omega ];\n  auto.\nQed.\n\nLemma beq_0_1_leb x\n: (EqNat.beq_nat x 1 || EqNat.beq_nat x 0)%bool = Compare_dec.leb x 1.\nProof.\n  destruct x as [|[|]]; simpl; reflexivity.\nQed.\n\nLemma beq_S_leb x n\n: (EqNat.beq_nat x (S n) || Compare_dec.leb x n)%bool = Compare_dec.leb x (S n).\nProof.\n  revert x; induction n as [|n IHn]; simpl.\n  { intros [|[|]]; reflexivity. }\n  { intros [|x]; [ reflexivity | apply IHn ]. }\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_simpl_example/src/Common/NatFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7527372767798819}}
{"text": "Section Logic.\nVariables A B P Q R: Prop. \nDefinition lem:=  A \\/ ~ A.\nDefinition Peirce:=  ((A->B)->A)->A.\nTheorem lemP: lem -> Peirce.\n  unfold lem. unfold Peirce. intros. elim H. intro. assumption. intro. apply H0. intro. absurd A. assumption. assumption. Qed.\n\nTheorem noncontradiction: not (P /\\ not P). \n\n\n(**Prove the following**)\nTheorem hilbert_axiom_S :  (P -> Q -> R) -> (P -> Q) -> P -> R.\nTheorem andCom: P/\\Q -> Q/\\P.\nTheorem noncontradiction: not (P /\\ not P). \nTheorem  PQR : (P /\\ Q) \\/ R -> P \\/ R.\nTheorem distrandor : (P /\\ Q)\\/ (P /\\ R) ->P /\\ (Q \\/ R).\nTheorem  LEM :\n(P -> (P /\\ Q) -> R) -> P /\\ (Q /\\ P) -> R.\n", "meta": {"author": "StergiosCha", "repo": "CoqNL", "sha": "cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c", "save_path": "github-repos/coq/StergiosCha-CoqNL", "path": "github-repos/coq/StergiosCha-CoqNL/CoqNL-cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c/Exercises/exercises1b_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191259110588, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7527257363422913}}
{"text": " (** * IndProp: Inductively Defined Propositions *)\n\nRequire Export Logic.\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 new definition of evenness works, let's use\n    its rules to show that [4] is even. By rule [ev_SS], it suffices\n    to show that [2] is even. This, in turn, is again guaranteed by\n    rule [ev_SS], as long as we can show that [0] is even. But this\n    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 theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Such \"constructor\n    theorems\" have the same status as proven theorems.  In particular,\n    we can use Coq's [apply] tactic with the rule names to prove [ev]\n    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.\n  intros. induction 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(** Subtracting two from an even number yields another even number.\n    We can easily prove this claim with the techniques that we've\n    already seen, provided that we phrase it in the right way.  If we\n    state it in terms of [evenb], for instance, we can proceed by a\n    simple case analysis on [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(** We can state the same claim in terms of [ev], but this quickly\n    leads us to an obstacle: Since [ev] is defined inductively --\n    rather than as a function -- Coq doesn't know how to simplify a\n    goal involving [ev n] after case analysis on [n].  As a\n    consequence, the same proof strategy fails: *)\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; we're stuck! *) simpl.\nAbort.\n\n(** The solution is to perform case analysis on the evidence that [ev\n    n] _directly_. By the definition of [ev], there are two cases to\n    consider:\n\n    - If that 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, that 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(** We can invoke this kind of argument in Coq using the [inversion]\n    tactic.  Besides allowing us to reason about equalities involving\n    constructors, [inversion] provides a case-analysis principle for\n    inductively defined propositions.  When used in this way, its\n    syntax is similar to [destruct]: We pass it a list of identifiers\n    separated by [|] characters to name the arguments to each of the\n    possible constructors.  For instance: *)\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(** Note that, in this particular case, it is also possible to replace\n    [inversion] by [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 (inversion_practice)  *)\n(** Prove the following results using [inversion]. *)\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  simpl. intros. inversion H. inversion H1. inversion H3.\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(* ================================================================= *)\n(** ** Induction on Evidence *)\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], we already know that those are equivalent to\n    each other). To show that all three coincide, we just need the\n    following lemma: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\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').\n      reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\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\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       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 when studying the semantics of programming\n    languages, where many properties of interest are defined\n    inductively.  The following exercises provide simple examples of\n    this 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.\n  intros. induction H.\n  - simpl. apply H0.\n  - simpl. apply ev_SS. apply IHev.\nQed.\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\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\n    the old one. *)\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  intros. induction H0.\n  - simpl in H. apply H.\n  - simpl in H. apply evSS_ev in H. apply IHev. apply H.\nQed.\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  intros. apply ev_sum.\n  - admit.\n  - admit.\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 LeModule.\n\n(** One useful example is the \"less than or equal to\"\n    relation on numbers. *)\n\n(** The following definition should be fairly intuitive.  It\n    says that there are two ways to give evidence that one number is\n    less than or equal to another: either observe that they are the\n    same number, or give evidence that the first is less than or equal\n    to the predecessor of the second. *)\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** 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 LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\n(** Here are a few more simple relations on numbers: *)\n\nInductive square_of : nat -> nat -> Prop :=\n  sq : forall n:nat, square_of n (n * n).\n\nInductive next_nat : 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, 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 : forall (n:nat) (m:nat),  total_relation n m.\n\n(** **** Exercise: 2 stars (empty_relation)  *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\nInductive empty_relation: nat -> nat -> Prop :=\n  .  \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.\n  intros. induction H0.\n  - apply H.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n.\n  - apply le_n.\n  - apply le_S. apply IHn.\nQed. \n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros.\n  induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  induction m. \n  -  intros. inversion H.\n    + apply le_n.\n    + inversion H1.\n  - intros. admit. \nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction b.\n  - rewrite <- plus_n_O. apply le_n.\n  - rewrite <- plus_n_Sm. apply le_S. 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. split.\n - induction m.\n   + inversion H.\n   + apply le_S. apply IHm. admit.\n  - admit.\nQed. \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  leb 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  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(** **** 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_provability2)  *)\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_provability)  *)\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 of evenness that we had\n    already seen, and does not seem to offer any concrete benefit over\n    them.  To give a better sense of the power of inductive\n    definitions, we now show how to use them to model a classic\n    concept in computer science: _regular expressions_. \n\n    Regular expressions are a simple language for describing strings,\n    defined as elements of the following inductive type.  (The names\n    of the constructors should become clear once we explain their\n    meaning below.)  *)\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(** Note that this definition is _polymorphic_: Regular expressions in\n    [reg_exp T] describe strings with characters drawn from [T] --\n    that is, lists of elements of [T].  (We depart slightly from\n    standard practice in that we do not require the type [T] to be\n    finite.  This results in a somewhat different theory of regular\n    expressions, but the difference is not significant for our\n    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].  (As a special case, the sequence of\n      strings may be empty, so [Star re] always matches the empty\n      string [[]] no matter what [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 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(** Once again, for readability, we can also display this definition\n    using inference-rule notation.  At the same time, let's introduce\n    a more 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\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Furthermore, 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 to help write 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.\n  unfold not. intros. inversion H.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros. destruct H.\n  - apply MUnionL. apply H.\n  - apply MUnionR. apply H.\nQed.\n\nTheorem list_equal_reg_exp_list: forall T (s: list T),\n  s =~ reg_exp_of_list s.\nProof.\n  intros. induction s.\n  - simpl. apply MEmpty.\n  - simpl. apply (MApp [x] (Char x) s).\n    + apply MChar.\n    + apply IHs.\nQed.  \n\n(** The next lemma is stated in terms of the [fold] function from the\n    [Poly] chapter: If [ss : list (list T)] represents a sequence of\n    strings [s1, ..., sn], then [fold app ss []] is the result of\n    concatenating them all together. *)\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp T),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars (reg_exp_of_list)  *)\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.  For\n    example, suppose that we wanted to prove the following intuitive\n    result: If a regular expression [re] matches some string [s], then\n    all elements of [s] must occur somewhere in [re].  To state this\n    theorem, we first define a function [re_chars] that lists all\n    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 [\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  (* 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} (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 net effect of this will be\n    to lose information (much as [destruct] can do), and leave you\n    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 the\n    recursive cases. (Try it!). So we need induction. Here is a naive\n    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 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 of them 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... *)\n\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].  In this respect it\n    behaves more like [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 T),\n  s1 =~ re' ->\n  re' = Star 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.  Calling\n    [remember e as x] causes Coq to (1) replace all occurrences of the\n    expression [e] by the variable [x], and (2) add an equation [x =\n    e] to the context.  Here's how we can use it to show the above\n    result: *)\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(** 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(** In the interesting cases (those that correspond to [Star]), we can\n    proceed as usual.  Note that the induction hypothesis [IH2] on the\n    [MStarApp] case mentions an additional premise [Star re'' = Star\n    re'], which results from the equality generated by [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(** **** Exercise: 4 stars (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 (pumping)  *)\n(** One of the first interesting theorems in the theory of regular\n    expressions is the so-called _pumping lemma_, which states,\n    informally, that any sufficiently long string [s] matching a\n    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\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  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].\n    Unfortunately, performing this conversion by hand 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\n    apply 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], which is what we need to\n    complete this case.\n\n    We can streamline this proof by defining an inductive proposition\n    that yields a better case-analysis principle for [beq_nat n\n    m].  Instead of generating an equation such as [beq_nat n m =\n    true], which is not directly useful, this principle gives us right\n    away the assumption we need: [n = m].  We'll actually define\n    something a bit more general, which can be used with arbitrary\n    properties (and not just equalities): *)\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]: [P]\n    holds if and only if [b = true].  To see this, notice that, by\n    definition, the only way we can produce evidence that [reflect P\n    true] holds is by showing that [P] is true and using the\n    [ReflectT] constructor.  If we invert this statement, this means\n    that it should be possible to extract evidence for [P] from a\n    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  intros P [] H.\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    To use [reflect] to produce a better proof of\n    [filter_not_empty_In], we begin by recasting the\n    [beq_nat_iff_true] lemma into a more convenient form in terms of\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(** 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].  (To see this clearly, look at the two\n    proofs of [filter_not_empty_In] in your Coq browser and observe\n    the differences in proof state at the beginning of the first case\n    of the [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(** Although this technique arguably gives us only a small gain\n    in convenience for this particular proof, using [reflect]\n    consistently often leads to shorter and clearer proofs. We'll see\n    many more examples where [reflect] comes in handy in later\n    chapters.\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: 4 stars, recommended (palindromes)  *)\n(** A palindrome is a sequence that reads the same backwards as\n    forwards.\n\n    - Define an inductive proposition [pal] on [list X] that\n      captures what it means to be a palindrome. (Hint: You'll need\n      three cases.  Your definition should be based on the structure\n      of the list; just having a single constructor\n\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 (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, advanced (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: 3 stars, recommended (nostutter)  *)\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.  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter].  (This is different from the [NoDup] property in the\n    exercise above; the sequence [1;4;1] repeats but does not\n    stutter.) *)\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 (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: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7526715938581036}}
{"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: Even.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Here we define the predicates [even] and [odd] by mutual induction\n    and we prove the decidability and the exclusion of those predicates.\n    The main results about parity are proved in the module Div2. *)\n\nOpen Local Scope nat_scope.\n\nImplicit Types m n : nat.\n\n\n(** * Definition of [even] and [odd], and basic facts *)\n\nInductive even : nat -> Prop :=\n  | even_O : even 0\n  | even_S : forall n, odd n -> even (S n)\nwith odd : nat -> Prop :=\n    odd_S : forall n, even n -> odd (S n).\n\nHint Constructors even: arith.\nHint Constructors odd: arith.\n\nLemma even_or_odd : forall n, even n \\/ odd n.\nProof.\n  induction n.\n    auto with arith.\n    elim IHn; auto with arith.\nQed.\n\nLemma even_odd_dec : forall n, {even n} + {odd n}.\nProof.\n  induction n.\n    auto with arith.\n    elim IHn; auto with arith.\nDefined.\n\nLemma not_even_and_odd : forall n, even n -> odd n -> False.\nProof.\n  induction n.\n    intros even_0 odd_0. inversion odd_0.\n    intros even_Sn odd_Sn. inversion even_Sn. inversion odd_Sn. auto with arith.\nQed.\n\n\n(** * Facts about [even] & [odd] wrt. [plus] *)\n\nLemma even_plus_split : forall n m,\n  (even (n + m) -> even n /\\ even m \\/ odd n /\\ odd m)\nwith odd_plus_split : forall n m,\n  odd (n + m) -> odd n /\\ even m \\/ even n /\\ odd m.\nProof.\nintros. clear even_plus_split. destruct n; simpl in *.\n auto with arith.\n inversion_clear H;\n   apply odd_plus_split in H0 as [(H0,?)|(H0,?)]; auto with arith.\nintros. clear odd_plus_split. destruct n; simpl in *.\n auto with arith.\n inversion_clear H;\n   apply even_plus_split in H0 as [(H0,?)|(H0,?)]; auto with arith.\nQed.\n\nLemma even_even_plus : forall n m, even n -> even m -> even (n + m)\nwith odd_plus_l : forall n m, odd n -> even m -> odd (n + m).\nProof.\nintros n m [|] ?. trivial. apply even_S, odd_plus_l; trivial.\nintros n m [] ?. apply odd_S, even_even_plus; trivial.\nQed.\n\nLemma odd_plus_r : forall n m, even n -> odd m -> odd (n + m)\nwith odd_even_plus : forall n m, odd n -> odd m -> even (n + m).\nProof.\nintros n m [|] ?. trivial. apply odd_S, odd_even_plus; trivial.\nintros n m [] ?. apply even_S, odd_plus_r; trivial.\nQed.\n\nLemma even_plus_aux : forall n m,\n    (odd (n + m) <-> odd n /\\ even m \\/ even n /\\ odd m) /\\\n    (even (n + m) <-> even n /\\ even m \\/ odd n /\\ odd m).\nProof.\nsplit; split; auto using odd_plus_split, even_plus_split.\nintros [[]|[]]; auto using odd_plus_r, odd_plus_l.\nintros [[]|[]]; auto using even_even_plus, odd_even_plus.\nQed.\n\nLemma even_plus_even_inv_r : forall n m, even (n + m) -> even n -> even m.\nProof.\n  intros n m H; destruct (even_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd n); auto.\nQed.\n\nLemma even_plus_even_inv_l : forall n m, even (n + m) -> even m -> even n.\nProof.\n  intros n m H; destruct (even_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd m); auto.\nQed.\n\nLemma even_plus_odd_inv_r : forall n m, even (n + m) -> odd n -> odd m.\nProof.\n  intros n m H; destruct (even_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd n); auto.\nQed.\n\nLemma even_plus_odd_inv_l : forall n m, even (n + m) -> odd m -> odd n.\nProof.\n  intros n m H; destruct (even_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd m); auto.\nQed.\nHint Resolve even_even_plus odd_even_plus: arith.\n\nLemma odd_plus_even_inv_l : forall n m, odd (n + m) -> odd m -> even n.\nProof.\n  intros n m H; destruct (odd_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd m); auto.\nQed.\n\nLemma odd_plus_even_inv_r : forall n m, odd (n + m) -> odd n -> even m.\nProof.\n  intros n m H; destruct (odd_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd n); auto.\nQed.\n\nLemma odd_plus_odd_inv_l : forall n m, odd (n + m) -> even m -> odd n.\nProof.\n  intros n m H; destruct (odd_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd m); auto.\nQed.\n\nLemma odd_plus_odd_inv_r : forall n m, odd (n + m) -> even n -> odd m.\nProof.\n  intros n m H; destruct (odd_plus_split n m) as [[]|[]]; auto.\n  intro; destruct (not_even_and_odd n); auto.\nQed.\nHint Resolve odd_plus_l odd_plus_r: arith.\n\n\n(** * Facts about [even] and [odd] wrt. [mult] *)\n\nLemma even_mult_aux :\n  forall n m,\n    (odd (n * m) <-> odd n /\\ odd m) /\\ (even (n * m) <-> even n \\/ even m).\nProof.\n  intros n; elim n; simpl in |- *; auto with arith.\n  intros m; split; split; auto with arith.\n  intros H'; inversion H'.\n  intros H'; elim H'; auto.\n  intros n0 H' m; split; split; auto with arith.\n  intros H'0.\n  elim (even_plus_aux m (n0 * m)); intros H'3 H'4; case H'3; intros H'1 H'2;\n    case H'1; auto.\n  intros H'5; elim H'5; intros H'6 H'7; auto with arith.\n  split; auto with arith.\n  case (H' m).\n  intros H'8 H'9; case H'9.\n  intros H'10; case H'10; auto with arith.\n  intros H'11 H'12; case (not_even_and_odd m); auto with arith.\n  intros H'5; elim H'5; intros H'6 H'7; case (not_even_and_odd (n0 * m)); auto.\n  case (H' m).\n  intros H'8 H'9; case H'9; auto.\n  intros H'0; elim H'0; intros H'1 H'2; clear H'0.\n  elim (even_plus_aux m (n0 * m)); auto.\n  intros H'0 H'3.\n  elim H'0.\n  intros H'4 H'5; apply H'5; auto.\n  left; split; auto with arith.\n  case (H' m).\n  intros H'6 H'7; elim H'7.\n  intros H'8 H'9; apply H'9.\n  left.\n  inversion H'1; auto.\n  intros H'0.\n  elim (even_plus_aux m (n0 * m)); intros H'3 H'4; case H'4.\n  intros H'1 H'2.\n  elim H'1; auto.\n  intros H; case H; auto.\n  intros H'5; elim H'5; intros H'6 H'7; auto with arith.\n  left.\n  case (H' m).\n  intros H'8; elim H'8.\n  intros H'9; elim H'9; auto with arith.\n  intros H'0; elim H'0; intros H'1.\n  case (even_or_odd m); intros H'2.\n  apply even_even_plus; auto.\n  case (H' m).\n  intros H H0; case H0; auto.\n  apply odd_even_plus; auto.\n  inversion H'1; case (H' m); auto.\n  intros H1; case H1; auto.\n  apply even_even_plus; auto.\n  case (H' m).\n  intros H H0; case H0; auto.\nQed.\n\nLemma even_mult_l : forall n m, even n -> even (n * m).\nProof.\n  intros n m; case (even_mult_aux n m); auto.\n  intros H H0; case H0; auto.\nQed.\n\nLemma even_mult_r : forall n m, even m -> even (n * m).\nProof.\n  intros n m; case (even_mult_aux n m); auto.\n  intros H H0; case H0; auto.\nQed.\nHint Resolve even_mult_l even_mult_r: arith.\n\nLemma even_mult_inv_r : forall n m, even (n * m) -> odd n -> even m.\nProof.\n  intros n m H' H'0.\n  case (even_mult_aux n m).\n  intros H'1 H'2; elim H'2.\n  intros H'3; elim H'3; auto.\n  intros H; case (not_even_and_odd n); auto.\nQed.\n\nLemma even_mult_inv_l : forall n m, even (n * m) -> odd m -> even n.\nProof.\n  intros n m H' H'0.\n  case (even_mult_aux n m).\n  intros H'1 H'2; elim H'2.\n  intros H'3; elim H'3; auto.\n  intros H; case (not_even_and_odd m); auto.\nQed.\n\nLemma odd_mult : forall n m, odd n -> odd m -> odd (n * m).\nProof.\n  intros n m; case (even_mult_aux n m); intros H; case H; auto.\nQed.\nHint Resolve even_mult_l even_mult_r odd_mult: arith.\n\nLemma odd_mult_inv_l : forall n m, odd (n * m) -> odd n.\nProof.\n  intros n m H'.\n  case (even_mult_aux n m).\n  intros H'1 H'2; elim H'1.\n  intros H'3; elim H'3; auto.\nQed.\n\nLemma odd_mult_inv_r : forall n m, odd (n * m) -> odd m.\nProof.\n  intros n m H'.\n  case (even_mult_aux n m).\n  intros H'1 H'2; elim H'1.\n  intros H'3; elim H'3; 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/Arith/Even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7525949753997598}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\nRequire Import 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.\nProof. by rewrite /rdivp unlock eqxx. Qed.\n\nLemma rdivp_small p q : size p < size q -> rdivp p q = 0.\nProof.\nrewrite /rdivp unlock; case: eqP => Eq; first by rewrite Eq size_poly0.\nby case sp: (size p) => [| s] hs /=; rewrite sp hs.\nQed.\n\nLemma leq_rdivp p q : (size (rdivp p q) <= size p).\nProof.\ncase: (ltnP (size p) (size q)); first by move/rdivp_small->; rewrite size_poly0.\nrewrite /rdivp /rmodp /rscalp unlock; case q0 : (q == 0) => /=.\n  by rewrite size_poly0.\nhave : (size (0 : {poly R})) <= size p by rewrite size_poly0.\nmove: (leqnn (size p)); move: {2 3 4 6}(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 lt0n size_poly_eq0 q0.\nmove=> /= hrn hr hq1 hq; case: ltnP=> //= hqr.\nhave sr: 0 < size r by apply: leq_trans hqr; rewrite size_poly_gt0 q0.\nhave sq: 0 < size q by rewrite size_poly_gt0 q0.\napply: ihn => //.\n- apply/leq_sizeP => j hnj.\n  rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge.\n  have hj : (size r).-1 <= j.\n    by apply: leq_trans hnj; move: hrn; rewrite -{1}(prednK sr) ltnS.\n  rewrite polySpred -?size_poly_gt0 // (leq_ltn_trans hj) /=; last first.\n    by rewrite -{1}(add0n j) ltn_add2r.\n  move: (hj); rewrite leq_eqVlt; case/orP.\n    move/eqP<-; rewrite (@polySpred _ q) ?q0 // subSS coefMC.\n    rewrite subKn; first by rewrite lead_coefE subrr.\n    by rewrite -ltnS -!polySpred // ?q0 -?size_poly_gt0.\n  move=> {hj} hj; move: (hj); rewrite prednK // coefMC; move/leq_sizeP=> -> //.\n  suff: size q <= j - (size r - size q).\n    by rewrite mul0r sub0r; move/leq_sizeP=> -> //; rewrite mulr0 oppr0.\n  rewrite subnBA // addnC -(prednK sq) -(prednK sr) addSn subSS.\n  by rewrite -addnBA ?(ltnW hj) // -{1}[_.-1]addn0 ltn_add2l subn_gt0.\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 -{2}(subnK hqr) addnA leq_add2r.\n  by rewrite 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 _ _) _; rewrite size_polyXn.\nby rewrite -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.\nProof. 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 => Eq // 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; case q0 : (q == 0).\n  by rewrite (eqP q0) /= size_poly0 ltn0.\nelim: (size p) 0%N 0 {1 3}p (leqnn (size p)) => [|n ihn] k q1 r.\n  rewrite leqn0 size_poly_eq0; move/eqP->; rewrite /= size_poly0 /= lt0n.\n  by rewrite size_poly_eq0 q0 /= size_poly0 lt0n size_poly_eq0 q0.\nmove=> hr /=; case: (@ltnP (size r) _) => //= hsrq; rewrite ihn //.\napply/leq_sizeP => j hnj; rewrite coefB.\nhave sr: 0 < size r.\n  by apply: leq_trans hsrq; apply: neq0_lt0n; rewrite size_poly_eq0.\nhave sq: 0 < size q by rewrite size_poly_gt0 q0.\nhave hj : (size r).-1 <= j.\n  by apply: leq_trans hnj; move: hr; rewrite -{1}(prednK sr) ltnS.\nrewrite -scalerAl !coefZ coefXnM ltn_subRL ltnNge; move: (sr).\nmove/prednK => {1}<-.\nhave -> /= : (size r).-1 < size q + j.\n  apply: (@leq_trans ((size q) + (size r).-1)); last by rewrite leq_add2l.\n  by rewrite -{1}[_.-1]add0n ltn_add2r.\nmove: (hj); rewrite leq_eqVlt; case/orP.\n  move/eqP<-; rewrite -{1}(prednK sq) -{3}(prednK sr) subSS.\n  rewrite  subKn; first by rewrite coefMC !lead_coefE subrr.\n  by move: hsrq; rewrite -{1}(prednK sq) -{1}(prednK sr) ltnS.\nmove=> {hj} hj; move: (hj); rewrite prednK // coefMC; move/leq_sizeP=> -> //.\nsuff: size q <= j - (size r - size q).\n   by rewrite mul0r sub0r; move/leq_sizeP=> -> //; rewrite mulr0 oppr0.\nrewrite subnBA // addnC -(prednK sq) -(prednK sr) addSn subSS.\nby rewrite -addnBA ?(ltnW hj) // -{1}[_.-1]addn0 ltn_add2l subn_gt0.\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.\ncase p0: (p == 0); first by rewrite (eqP p0) rmod0p.\napply/eqP; rewrite -size_poly_eq0.\nby have := (ltn_rmodp p 1); rewrite size_polyC !oner_neq0 ltnS leqn0.\nQed.\n\nLemma rmodp_small p q : size p < size q -> rmodp p q = p.\nProof.\nrewrite /rmodp unlock; case: eqP => Eq; first by rewrite Eq 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.\ncase: (ltnP (size m) (size d)) => [|h]; first by move/rmodp_small->.\ncase d0: (d == 0); first by rewrite (eqP d0) rmodp0.\nby apply: leq_trans h; apply: ltnW; rewrite ltn_rmodp d0.\nQed.\n\nLemma rmodpC p c : c != 0 -> rmodp p c%:P = 0.\nProof.\nmove=> Hc; apply/eqP; rewrite -size_poly_eq0 -leqn0 -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.\nProof. by rewrite /rdvdp rmod0p. Qed.\n\nLemma rdvd0p n : (rdvdp 0 n) = (n == 0).\nProof. 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: contraL pq => /eqP ->; rewrite rdvd0p. Qed.\n\nLemma rdvdp1 d : (rdvdp d 1) = ((size d) == 1%N).\nProof.\nrewrite /rdvdp; case d0: (d == 0).\n  by rewrite (eqP d0) rmodp0 size_poly0 (negPf (@oner_neq0 _)).\nhave:= (size_poly_eq0 d); rewrite d0; move/negbT; rewrite -lt0n.\nrewrite leq_eqVlt; case/orP => hd; last first.\n  by rewrite rmodp_small ?size_poly1 // oner_eq0 -(subnKC hd).\nrewrite eq_sym in hd; rewrite hd; have [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.\nProof. 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.\nby move=> nn0 hs; rewrite /rdvdp; rewrite (rmodp_small hs); apply: negPf.\nQed.\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.\nProof. by move/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 if_neg.\nby case: ifP => /= p0; rewrite ?(eqxx, p0) // (eqP p0).\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    - rewrite leqn0 size_poly_eq0; move/eqP=> -> _.\n      rewrite size_poly0 size_poly_gt0 rmodp0 => nzp.\n      by rewrite (negPf nzp); case: n => [|n] /=; rewrite rmod0p eqxx.\n    - rewrite leqn0 size_poly_eq0 => _; move/eqP=> ->.\n      rewrite size_poly0 size_poly_gt0 rmodp0 => nzp.\n      by rewrite (negPf nzp); case: m {Hrec} => [|m] /=; rewrite rmod0p eqxx.\n  case: ifP => Epq Sm Sn Sq //; rewrite ?Epq //.\n  case: (eqVneq q1 0) => [->|nzq].\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.\ncase: (eqVneq p 0) => [-> | nzp].\n  by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same.\ncase: (eqVneq q 0) => [-> | nzq].\n  by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same.\nrewrite /rgcdp -/rgcdp_rec.\ncase: ltnP; rewrite (negPf nzp, negPf nzq) //=.\n  move=> ltpq; rewrite ltn_rmodp (negPf nzp) //=.\n  rewrite -(ltn_predK ltpq) /=; case: eqP => [->|].\n    by case: (size p) => [|[|s]]; rewrite /= rmodp0 (negPf nzp) // rmod0p eqxx.\n  move/eqP=> nzqp; rewrite (negPf nzp).\n  apply: Irec => //; last by rewrite ltn_rmodp.\n    by rewrite -ltnS (ltn_predK ltpq) (leq_trans _ ltpq) ?leqW // ltn_rmodp.\n  by rewrite ltnW // ltn_rmodp.\nmove=> leqp; rewrite ltn_rmodp (negPf nzq) //=.\nhave p_gt0: size p > 0 by rewrite size_poly_gt0.\nrewrite -(prednK p_gt0) /=; case: eqP => [->|].\n  by case: (size q) => [|[|s]]; rewrite /= rmodp0 (negPf nzq) // rmod0p eqxx.\nmove/eqP=> nzpq; rewrite (negPf nzq).\napply: Irec => //; last by rewrite ltn_rmodp.\n  by rewrite -ltnS (prednK p_gt0) (leq_trans _ leqp) // ltn_rmodp.\nby rewrite ltnW // ltn_rmodp.\nQed.\n\nCoInductive 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; case: (altP (d =P 0))=> [->| Hd].\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   [|n IHn] k q r Hr /=.\n  have{Hr} ->: r = 0 by apply/eqP; rewrite -size_poly_eq0; move: Hr; case: size.\n  suff hsd: size (0: {poly R}) < size d by rewrite hsd => /= ?; constructor.\n  by rewrite size_polyC eqxx (polySpred Hd).\ncase: ltP=> Hlt Heq; first by constructor=> // _; apply/ltP.\napply: IHn=> [|Cda]; last first.\n  rewrite mulrDl addrAC -addrA subrK exprSr polyC_mul mulrA Heq //.\n  by rewrite mulrDl -mulrA Cda mulrA.\napply/leq_sizeP => j Hj.\nrewrite coefD coefN coefMC -scalerAl coefZ coefXnM.\nmove/ltP: Hlt; rewrite -leqNgt=> Hlt.\nmove: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first.\n  rewrite nth_default ?(leq_trans Hqq) // ?simp; last by apply: (leq_trans Hr).\n  rewrite nth_default; first by rewrite if_same !simp oppr0.\n  by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hr).\nmove: Hr; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first.\n  rewrite !nth_default ?if_same ?simp ?oppr0 //.\n  by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hqq).\nrewrite {2}/lead_coef Hqq polySpred // subSS ltnNge leq_subr /=.\nby rewrite subKn ?addrN // -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; case: ifP => hp /=; first by rewrite (eqP hp).\nmove: (hp); rewrite -size_poly_eq0 /redivp_rec; case sp: (size p)=> [|n] // _.\nrewrite mul0r sp ltnn add0r subnn expr0 hC alg_polyC 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; move/(_ Cdl)=> Heq.\nhave: d != 0 by case: (size d) lt_rd (size_poly_eq0 d) => // n _ <-.\nmove=> dn0; move/(_ dn0)=> Hs.\nhave eC : q * d * (lead_coef d ^+ k)%:P = q * (lead_coef d ^+ k)%:P * d.\n  by rewrite -mulrA polyC_exp (GRing.commrX k Cdl) mulrA.\nsuff e1 : q1 = q * (lead_coef d ^+ k)%:P.\n  congr (_, _, _) => //=; move/eqP: Heq; rewrite [_ + r1]addrC.\n  rewrite -subr_eq; move/eqP<-; rewrite e1 mulrDl addrAC -{2}(add0r (r * _)).\n  by rewrite eC subrr add0r.\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.\nrewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; exact: 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 //; apply rregX.\nrewrite mulrDl addrAC mulNr -!mulrA  polyC_exp -(GRing.commrX (m-v) Cdl).\nrewrite -polyC_exp mulrA -mulrDl -rdivp_eq // [(_ ^+ (m - k))%:P]polyC_exp.\nrewrite -(GRing.commrX (m-k) Cdl) -polyC_exp mulrA -he -!mulrA -!polyC_mul.\nrewrite -/v -!exprD addnC subnK ?leq_maxl //.\nby rewrite addnC subnK ?subrr ?leq_maxr.\nQed.\n\nCoInductive 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.\nProof.\ncase: (d =P 0)=> Hd; first by rewrite Hd simp rmod0p.\nby apply/eqP; apply: rdvdp_mull.\nQed.\n\nLemma rmodpp : rmodp d d = 0.\nProof. by rewrite -{1}(mul1r d) rmodp_mull. Qed.\n\nLemma rdivpp : rdivp d d = (lead_coef d ^+ rscalp d d)%:P.\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.\nProof. apply/eqP; exact: rmodpp. Qed.\n\nLemma rdivpK p : rdvdp d p -> (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 MonicDivisor.\n\nVariable R : ringType.\nImplicit Types p q r : {poly R}.\n\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; move/(redivp_eq Hc Hr q).\nby rewrite  (eqP mond); move=> -> /=; rewrite expr1n !mulr1.\nQed.\n\nLemma rdivp_eq p :\n  p = (rdivp p d) * d + (rmodp p d).\nProof.\nrewrite -rdivp_eq; rewrite (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 :\n  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 {1}(rdivp_eq r) addrA.\nby rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0.\nQed.\n\nLemma rdivp_addl q r :\n  rdvdp d q -> rdivp (q + r) d = rdivp q d + rdivp r d.\nProof.\ncase: (monic_comreg mond)=> Hc Hr; rewrite {1}(rdivp_eq r) addrA.\nrewrite {2}(rdivp_eq q); move/rmodp_eq0P->; rewrite addr0.\nby rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0.\nQed.\n\nLemma rdivp_addr q r :\n  rdvdp d r -> rdivp (q + r) d = rdivp q d + rdivp r d.\nProof. by rewrite addrC; move/rdivp_addl->; 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.\napply: rmodp_mull; rewrite (eqP mond); [exact: commr1 | exact: rreg1].\nQed.\n\nLemma rmodpp : rmodp d d = 0.\nProof.\napply: rmodpp; rewrite (eqP mond); [exact: commr1 | exact: rreg1].\nQed.\n\nLemma rmodp_addl_mul_small q r :\n  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 rmodp_add p q : rmodp (p + q) d = rmodp p d + rmodp q d.\nProof.\nrewrite {1}(rdivp_eq p) {1}(rdivp_eq q).\nrewrite addrCA 2!addrA -mulrDl (addrC (rdivp q d)) -addrA.\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.\nhave -> : rmodp q d = q - (rdivp q d) * d.\n  by rewrite {2}(rdivp_eq q) addrAC subrr add0r.\nrewrite mulrDr rmodp_add -mulNr mulrA.\nrewrite -{2}[rmodp _ _]addr0; congr (_ + _); exact: rmodp_mull.\nQed.\n\nLemma rdvdpp : rdvdp d d.\nProof.\napply: rdvdpp; rewrite (eqP mond); [exact: commr1 | exact: 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.\napply: rdvdp_mull; rewrite (eqP mond) //; [exact: commr1 | exact: 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).\n  case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1; move=> -> _.\n  by exists qq.\nby case=> [qq]; move/eq_rdvdp.\nQed.\n\nLemma rdivpK p :\n  rdvdp d p -> (rdivp p d) * d = p * (lead_coef d ^+ rscalp p d)%:P.\nProof. move=> dvddp; rewrite rdivpK // (eqP mond); exact: commr1. Qed.\n\nEnd MonicDivisor.\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 -{1}(mulr1 p) 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; last first.\n  case=> p1 ->; apply: rmodp_mull; exact: monicXsubC.\nmove=> e0; exists (rdivp p ('X - x%:P)).\nby rewrite {1}(rdivp_eq (monicXsubC x) p) 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\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\nCoInductive 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\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.\nrewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; exact: 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 apply: RdvdpN; move/rmodp_eq0P/eqP: 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).\napply/rmodp_eq0P/eqP; rewrite rdivp_eq; first by move->; rewrite addr0.\nby move/eqP; 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 ->\n  rdvdp (\\prod_(z <- rs) ('X - z%:P)) p.\nProof.\nmove=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->; apply: RingMonic.rdvdp_mull.\nexact: 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\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\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.\nby case ulcq: (lead_coef q \\in GRing.unit); rewrite /divp unlock redivp_def ulcq.\nQed.\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.\nby case ulcq: (lead_coef q \\in GRing.unit); rewrite /modp unlock redivp_def ulcq.\nQed.\n\nLemma scalpE p q :\n  scalp p q = if lead_coef q \\in GRing.unit then 0%N else rscalp p q.\nProof.\nby case ulcq: (lead_coef q \\in GRing.unit); rewrite /scalp unlock redivp_def ulcq.\nQed.\n\nLemma dvdpE p q : p %| q = rdvdp p q.\nProof.\nrewrite /dvdp modpE /rdvdp; case ulcq: (lead_coef p \\in GRing.unit)=> //.\nrewrite -[_ *: _ == 0]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.\ncase: (eqVneq q 0) => [->|nzq]; 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.\n\nCoInductive edivp_spec (m d : {poly R}) : 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\n(* Is this the most appropriate statement?*)\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 -polyC_mul.\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 exact: mulrC.\nmove=> hsrd hu; rewrite unlock hu; case et: (redivp _ _) => [[s qq] rr].\nhave cdn0 : lead_coef d != 0.\n  by move: hu; case d0: (lead_coef d == 0) => //; rewrite (eqP d0) unitr0.\nmove: (et); rewrite RingComRreg.redivp_eq //; last by apply/rregP.\nrewrite et /=; case => e1 e2; rewrite -!mul_polyC -!exprVn !polyC_exp.\nsuff h x y: x * (lead_coef d ^+ s)%:P = y -> ((lead_coef d)^-1)%:P ^+ s * y = x.\n  by congr (_, _, _); apply: h.\nhave hn0 : (lead_coef d)%:P ^+ s != 0 by apply: expf_neq0; rewrite polyC_eq0.\nmove=> hh; apply: (mulfI hn0); rewrite mulrA -exprMn -polyC_mul divrr //.\nby rewrite expr1n mul1r -polyC_exp mulrC; apply: sym_eq.\nQed.\n\nLemma divp_eq  p q :\n    (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; case: (altP (q =P 0)) => [-> | qn0].\n  rewrite mulr0 add0r lead_coef0 rmodp0 /rscalp unlock eqxx expr0 invr1.\n  by rewrite scale1r.\nhave hn0 : (lead_coef q ^+ rscalp p q)%:P != 0.\n  by rewrite polyC_eq0 expf_neq0 // lead_coef_eq0.\napply: (mulfI hn0).\nrewrite -scalerAl -scalerDr !mul_polyC scalerA mulrV ?unitrX //.\nby rewrite scale1r rdivp_eq.\nQed.\n\n\nLemma dvdp_eq q p :\n  (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; apply/eqP/eqP.\n  by rewrite -scalerAl; move<-; rewrite scalerA mulVr ?scale1r // unitrX.\nby move=> {2}->; rewrite scalerAl 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.\ncase: (eqVneq p 0) => [->|nz_p]; 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 {1}mulNr -scalerAl -e scalerA mulrC -scalerA -scalerAl.\n  by rewrite -scalerBr rdivp_eq addrC addKr.\nrewrite /dvdp; apply/idPn=> m_nz.\nhave: p1 * q != 0 by rewrite -E1 -mul_polyC mulf_neq0 // -/(dvdp q p) dvdpE.\nrewrite mulf_eq0; case/norP=> p1_nz q_nz; have:= ltn_rmodp p q.\nrewrite q_nz -(size_scale _ cn0) E1 size_mul //.\nby rewrite polySpred // ltnNge leq_addl.\nQed.\n\nLemma mulpK p q : q != 0 ->\n  p * q %/ q = lead_coef q ^+ scalp (p * q) q *: p.\nProof.\nmove=> qn0; move/rregP: (qn0); apply; rewrite -scalerAl divp_eq.\nsuff -> : (p * q) %% q = 0 by rewrite addr0.\nrewrite modpE RingComRreg.rmodp_mull ?scaler0 ?if_same //; first by red; rewrite mulrC.\nby apply/rregP; rewrite lead_coef_eq0.\nQed.\n\nLemma mulKp p q :  q != 0 ->\n  q * p %/ q = lead_coef q ^+ scalp (p * q) q *: p.\nProof. move=> ?; rewrite mulrC; exact: 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.\n  by rewrite addr0; move/eqP; rewrite -mul_polyC (inj_eq (mulIf np0)); move/eqP.\nrewrite modpE Ring.rmodpp; last by red; rewrite mulrC.\nby rewrite scaler0 if_same.\nQed.\n\nEnd WeakTheoryForIDomainPseudoDivision.\n\nHint Resolve lc_expn_scalp_neq0.\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=> /=; rewrite ?leq_rdivp //.\nmove=> ulcq; rewrite size_scale ?leq_rdivp //.\nrewrite -exprVn expf_neq0 // invr_eq0.\nby move: ulcq; case lcq0: (lead_coef q == 0) => //; rewrite (eqP lcq0) 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.\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.\ncase: (altP (q =P 0)) => [-> | nq0]; 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.\nProof. by rewrite mulrC modp_mull. Qed.\n\nLemma modpp d : d %% d = 0.\nProof. by rewrite -{1}(mul1r d) modp_mull. Qed.\n\nLemma ltn_modp p q : (size (p %% q) < size q) = (q != 0).\nProof.\nrewrite /modp unlock redivp_def /=; case: ifP=> /=; rewrite ?ltn_rmodp //.\nmove=> ulcq; rewrite size_scale ?ltn_rmodp //.\nrewrite -exprVn expf_neq0 // invr_eq0.\nby move: ulcq; case lcq0: (lead_coef q == 0) => //; rewrite (eqP lcq0) 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; have sd : size d > 0 by rewrite size_poly_gt0 dn0.\nhave: (lead_coef d) ^+ (scalp q d) != 0 by exact: lc_expn_scalp_neq0.\nmove/size_scale; move/(_ q)<-; rewrite divp_eq; case quo0 : (q %/ d == 0).\n  rewrite (eqP quo0) mul0r add0r size_poly0.\n  case p0 : (p == 0); first by rewrite (eqP p0) mul0r size_poly0 ltnn ltn0.\n  have sp : size p > 0 by rewrite size_poly_gt0 p0.\n  rewrite /= size_mul ?p0 // sp; apply: sym_eq; move/prednK:(sp)<-.\n  by rewrite addSn /= ltn_addl // ltn_modp.\nrewrite size_addl; last first.\n  rewrite size_mul ?quo0 //; move/negbT: quo0; rewrite -size_poly_gt0.\n  by move/prednK<-; rewrite addSn /= ltn_addl // ltn_modp.\ncase: (altP (p =P 0)) => [-> | pn0]; first by rewrite mul0r size_poly0 !ltn0.\nby rewrite !size_mul ?quo0 //; move/prednK: sd<-; rewrite !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; rewrite -{2}(mul1r d) -leq_divpr // size_polyC oner_eq0 /=.\nby rewrite 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.\nmove: (nq0); rewrite -size_poly_gt0 => lt0sq.\nmove: (sqp); move/(leq_trans lt0sq) => lt0sp.\nmove: (lt0sp); rewrite size_poly_gt0=> p0.\nmove: (divp_eq p q); move/(congr1 (size \\o (@polyseq R)))=> /=.\nrewrite size_scale; last by rewrite expf_eq0 lead_coef_eq0 (negPf nq0) andbF.\ncase: (eqVneq (p %/ q) 0) => [-> | qq0].\n  by rewrite mul0r add0r=> es; move: nq0; rewrite -(ltn_modp p) -es ltnNge sqp.\nmove/negP:(qq0); move/negP; rewrite -size_poly_gt0 => lt0qq.\nrewrite size_addl.\n  rewrite size_mul ?qq0 // => ->.\n  apply/eqP; rewrite -(eqn_add2r ((size q).-1)).\n  rewrite subnK; first by rewrite -subn1 addnBA // subn1.\n  rewrite /leq -(subnDl 1%N) !add1n prednK // (@ltn_predK (size q)) //.\n    by rewrite addnC subnDA subnn sub0n.\n  by rewrite -[size q]add0n ltn_add2r.\nrewrite size_mul ?qq0 //.\nmove: nq0; rewrite -(ltn_modp p); move/leq_trans; apply; move/prednK: lt0qq<-.\nby rewrite 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 case: (eqVneq q 0) => [-> | qn0]; 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.\nProof. by rewrite /dvdp mod0p. Qed.\n\nHint Resolve dvdp0.\n\nLemma dvd0p p : (0 %| p) = (p == 0).\nProof. 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: contraL pq=> /eqP ->; 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; exact: rdvdp1.\nby rewrite invr_eq0 expf_neq0 //; apply: contraTneq ud => ->; rewrite unitr0.\nQed.\n\nLemma dvd1p m : 1 %| m.\nProof. 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.\nProof. by move/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) => [-> | nd0].\n  by move/dvd0pP->; rewrite divp0 size_poly0 !leq0n.\nmove=> hd; rewrite 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; move/(_ p)<-; rewrite divp_eq.\nmove/modp_eq0P: hd->; rewrite addr0; case: (altP (p %/ d =P 0))=> [-> | quon0].\n  rewrite mul0r size_poly0 eq_sym (eq_sym 0%N) size_poly_eq0.\n  case: (altP (q =P 0)) => [-> | nq0]; first by rewrite mul0r size_poly0 eqxx.\n  by rewrite size_poly_eq0 mulf_eq0 (negPf nq0) (negPf nd0).\ncase: (altP (q =P 0)) => [-> | nq0].\n  by rewrite mul0r size_poly0 !size_poly_eq0 mulf_eq0 (negPf nd0) orbF.\nrewrite !size_mul //; move: nd0; rewrite -size_poly_gt0; move/prednK<-.\nby rewrite !addnS /= eqn_add2r.\nQed.\n\nLemma dvdp_leq p q : q != 0 -> p %| q -> size p <= size q.\nmove=> nq0 /modp_eq0P => rpq; case: (ltnP (size p) (size q)); first by move/ltnW->.\nrewrite leq_eqVlt; case/orP; first by move/eqP->.\nby move/modp_small; rewrite rpq => h; move: nq0; rewrite h eqxx.\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 {1}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.\nProof. by rewrite /dvdp modpp. Qed.\n\nHint Resolve dvdpp.\n\nLemma divp_dvd p q : (p %| q) -> ((q %/ p) %| q).\nProof.\ncase: (eqVneq p 0) => [-> | np0]; 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) => [-> |dn0]; first by move/dvd0pP->; 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.\n\nLemma dvdp_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\ncase: (eqVneq d1 0) => [-> |d1n0]; first by move/dvd0pP->; rewrite !mul0r dvdpp.\ncase: (eqVneq d2 0) => [-> |d2n0]; first by move => _ /dvd0pP ->; 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: (altP (d =P 0)) => [-> | dn0]; first by move/dvd0pP->; rewrite add0r.\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1.\napply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Eq2.\n  have sn0 : c1 * c2 != 0.\n    by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  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.\n  have sn0 : c1 * c2 != 0.\n    by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  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; exact: 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.\ncase: (altP (n =P 0)) => [-> | nn0]; first by rewrite modp0.\ncase: (altP (d =P 0)) => [-> | dn0]; first by move/dvd0pP->; rewrite modp0.\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1.\napply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Eq2.\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  apply: (@eq_dvdp _ quo _ _ sn0); rewrite mulrDl mulNr -!scalerAl -!mulrA.\n  rewrite  -Eq1 -Eq2 -scalerAr !scalerA mulrC [_ * c2]mulrC mulrA.\n  by rewrite -[((_ * _) * _) *: _]scalerA -scalerBr divp_eq addrC addKr.\nhave sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0.\n  by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?(negPf nn0) andbF.\napply: (@eq_dvdp _ (c2 *: (m  %/ n) * q1 + c1 *: q2) _ _ sn0).\n  rewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1.\n  by rewrite scalerAl mulrDl mulrA.\nQed.\n\nLemma dvdp_trans : transitive (@dvdp R).\nProof.\nmove=> n d m.\ncase: (altP (d =P 0)) => [-> | dn0]; first by move/dvd0pP->.\ncase: (altP (n =P 0)) => [-> | nn0]; first by move=> _ /dvd0pP ->.\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.\nProof. by apply: dvdp_mulr; exact: dvdpp. Qed.\n\nLemma dvdp_mulIr p q : q %| p * q.\nProof. by apply: dvdp_mull; exact: dvdpp. Qed.\n\nLemma dvdp_mul2r r p q : r != 0 -> (p * r %| q * r) = (p %| q).\nProof.\nmove => nzr.\ncase: (eqVneq p 0) => [-> | pn0].\n  by rewrite mul0r !dvd0p mulf_eq0 (negPf nzr) orbF.\ncase: (eqVneq q 0) => [-> | qn0]; 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).\n  by rewrite expf_neq0 // lead_coef_eq0 mulf_neq0.\nby apply: (GRing.mulIf nzr); rewrite -GRing.mulrA -GRing.scalerAl.\nQed.\n\nLemma dvdp_mul2l r p q: r != 0 -> (r * p %| r * q) = (p %| q).\nProof. by rewrite ![r * _]GRing.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.\nby move/subnK <-; rewrite exprD dvdp_mull // ?lead_coef_exp ?unitrX.\nQed.\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) => [-> | pn0]; first by move/dvd0pP->.\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)=> hkl.\n  move:(hkl); rewrite -subn_eq0; move/eqP->; rewrite expr0 dvd1p.\n  apply: dvdp_mull; case: (ltnP 1%N (size p)) => sp.\n    by rewrite dvdp_Pexp2l.\n  move: sp; case esp: (size p) => [|sp].\n    by move/eqP: esp; rewrite size_poly_eq0 (negPf pn0).\n  rewrite ltnS leqn0; move/eqP=> sp0; move/eqP: esp; rewrite sp0.\n  by case/size_poly1P => c cn0 ->; move/subnK: hkl<-; rewrite exprD dvdp_mulIr.\nrewrite -{1}[k](@subnK l) 1?ltnW// exprD dvdp_mul2r//.\nelim: l {hkl}=> [|l ihl]; first by rewrite expr0 oner_eq0.\nby rewrite exprS mulf_neq0.\nQed.\n\nLemma dvdp_XsubCl p x : ('X - x%:P) %| p = root p x.\nProof. rewrite dvdpE; exact: Ring.rdvdp_XsubCl. Qed.\n\nLemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p).\nProof. rewrite dvdpE; exact: 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\n\nLemma root_bigmul : forall x (ps : seq {poly R}),\n  ~~root (\\big[*%R/1]_(p <- ps) p) x = all (fun p => ~~ root p x) ps.\nProof.\nmove=> x; elim; first by rewrite big_nil root1.\nby move=> p ps ihp; 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) => [-> | m_nz].\n  by case/andP => /dvd0pP -> _; exists (1, 1); rewrite ?scaler0 // oner_eq0.\ncase: (eqVneq n 0) => [-> | n_nz].\n  by case/andP => _ /dvd0pP ->; exists (1, 1); rewrite ?scaler0 // oner_eq0.\ncase/andP; rewrite !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 leqn0 size_poly_eq0 (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 //.\nrewrite !mul_polyC scalerA -eqC mulrC -scalerA eq.\nby rewrite !scalerA mulrC.\nQed.\n\nLemma eqpxx : reflexive (@eqp R).\nProof. by move=> p; rewrite /eqp dvdpp. Qed.\n\nHint Resolve eqpxx.\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.\nmove=> p q r pq.\nby apply/idP/idP=> e; apply: eqp_trans e; rewrite // eqp_sym.\nQed.\n\nLemma eqp_rtrans : right_transitive (@eqp R).\nProof. by move=> x y xy z; rewrite eqp_sym (eqp_ltrans xy) eqp_sym. Qed.\n\nLemma eqp0 : forall p, (p %= 0) = (p == 0).\nProof.\nmove=> p; case: eqP; move/eqP=> Ep; first by rewrite (eqP Ep) eqpxx.\nby apply/negP; case/andP=> _; rewrite /dvdp modp0 (negPf Ep).\nQed.\n\nLemma eqp01 : 0 %= (1 : {poly R}) = false.\nProof.\ncase abs : (0 %= 1) => //; case/eqpP: abs=> [[c1 c2]] /andP [c1n0 c2n0] /=.\nby rewrite scaler0 alg_polyC; move/eqP; rewrite eq_sym polyC_eq0 (negbTE c2n0).\nQed.\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.\ncase: (q =P 0); move/eqP => Eq; first by rewrite (eqP Eq) eqp0; move/eqP->.\nrewrite eqp_sym; case: (p =P 0); move/eqP => Ep.\n  by rewrite (eqP Ep) 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; move/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.\n  by case abs: (q == 0) => //; move: hq; rewrite (eqP abs) eqp01.\nrewrite -size_poly_eq1 eqn_leq -{1}(eqP sizeq) dvdp_leq //=.\ncase p0 : (size p == 0%N); last by rewrite neq0_lt0n.\nby move: dpq;  rewrite size_poly_eq0 in p0; rewrite (eqP p0) dvd0p (negbTE n0q).\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 dvdp_scaler c m n : c != 0 -> m %| c *: n = (m %| n).\nProof. move=> cn0; apply: eqp_dvdr; exact: eqp_scale. Qed.\n\nLemma dvdp_scalel c m n : c != 0 -> (c *: m %| n) = (m %| n).\nProof. move=> cn0; apply: eqp_dvdl; exact: eqp_scale. Qed.\n\nLemma dvdp_opp d p : d %| (- p) = (d %| p).\nProof.\nby apply: eqp_dvdr; rewrite -scaleN1r eqp_scale // oppr_eq0 oner_eq0.\nQed.\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 c0: (c == 0); rewrite // alg_polyC (eqP c0) scaler0.\n  by case/andP=> _ /=; move/negbTE<-; move/eqP; rewrite 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->.\ncase (q =P 0)=> [->|]; [|move/eqP => Hq].\n  by rewrite size_poly0 size_poly_eq0; move/eqP->; rewrite eqpxx.\ncase (p =P 0)=> [->|]; [|move/eqP => Hp].\n  by rewrite size_poly0 eq_sym size_poly_eq0; move/eqP->; rewrite eqpxx.\nmove: pq; rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> eqpq.\nmove:(eqpq); move/(congr1 (size \\o (@polyseq R)))=> /=.\nhave cn0 : c != 0 by  rewrite expf_neq0 // lead_coef_eq0.\nrewrite (@eqp_size _ q); last  by 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.\nrewrite rootE -[_==_]orFb -c0 -mulf_eq0 -hornerZ e hornerZ.\nby rewrite 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: contraL dvd_dp=> /eqP->; 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 rewrite if_neg; case: ifP => /= p0; rewrite ?(eqxx, p0) // (eqP p0).\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  - rewrite leqn0 size_poly_eq0; move/eqP=> -> _.\n    rewrite size_poly0 size_poly_gt0 modp0 => nzp.\n    by rewrite (negPf nzp); case: n => [|n] /=; rewrite mod0p eqxx.\n  - rewrite leqn0 size_poly_eq0 => _; move/eqP=> ->.\n    rewrite size_poly0 size_poly_gt0 modp0 => nzp.\n    by rewrite (negPf nzp); case: m {Hrec} => [|m] /=; rewrite mod0p eqxx.\n  case: ifP => Epq Sm Sn Sq //; rewrite ?Epq //.\n  case: (eqVneq q1 0) => [->|nzq].\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.\ncase: (eqVneq p 0) => [-> | nzp].\n  by rewrite mod0p modp0 gcd0p gcdp0 if_same.\ncase: (eqVneq q 0) => [-> | nzq].\n  by rewrite mod0p modp0 gcd0p gcdp0 if_same.\nrewrite /gcdp /gcdp_rec.\ncase: ltnP; rewrite (negPf nzp, negPf nzq) //=.\n  move=> ltpq; rewrite ltn_modp (negPf nzp) //=.\n  rewrite -(ltn_predK ltpq) /=; case: eqP => [->|].\n    by case: (size p) => [|[|s]]; rewrite /= modp0 (negPf nzp) // mod0p eqxx.\n  move/eqP=> nzqp; rewrite (negPf nzp).\n  apply: Irec => //; last by rewrite ltn_modp.\n    by rewrite -ltnS (ltn_predK ltpq) (leq_trans _ ltpq) ?leqW // ltn_modp.\n  by rewrite ltnW // ltn_modp.\nmove=> leqp; rewrite ltn_modp (negPf nzq) //=.\nhave p_gt0: size p > 0 by rewrite size_poly_gt0.\nrewrite -(prednK p_gt0) /=; case: eqP => [->|].\n  by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx.\nmove/eqP=> nzpq; rewrite (negPf nzq); apply: Irec => //; rewrite ?ltn_modp //.\n  by rewrite -ltnS (prednK p_gt0) (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; case: ltnP.\n  by rewrite gcd0p size_polyC oner_eq0.\nmove/size1_polyC=> e; rewrite e.\ncase p00: (p`_0 == 0); first by rewrite (eqP p00) modp0 gcdp0 size_poly1.\nby rewrite modpC ?p00 // gcd0p size_polyC p00.\nQed.\n\nLemma size_gcdp1 p : size (gcdp p 1) = 1%N.\nrewrite gcdpE size_polyC oner_eq0 /= modp1; case: ltnP; last first.\n  by rewrite gcd0p size_polyC oner_eq0.\nrewrite ltnS leqn0 size_poly_eq0; move/eqP->; rewrite gcdp0 modp0 size_polyC.\nby rewrite 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.\nelim: {p q}minn {-2}p {-2}q (leqnn (minn (size q) (size p))) => [|r Hrec] p q.\n  rewrite geq_min !leqn0 !size_poly_eq0.\n  by case/pred2P=> ->; rewrite (gcdp0, gcd0p) dvdpp ?andbT /=.\ncase: (eqVneq p 0) => [-> _|nz_p]; first by rewrite gcd0p dvdpp andbT.\ncase: (eqVneq q 0) => [->|nz_q]; first by rewrite gcdp0 dvdpp /=.\nrewrite gcdpE minnC /minn; case: ltnP => [lt_pq | le_pq] le_qr.\n  suffices: minn (size p) (size (q %% p)) <= r.\n    by move/Hrec; case/andP => E1 E2; rewrite E2 (dvdp_mod _ E2).\n  by rewrite geq_min orbC -ltnS (leq_trans _ le_qr) ?ltn_modp.\nsuffices: minn (size q) (size (p %% q)) <= r.\n  by move/Hrec; case/andP => E1 E2; rewrite E2 andbT (dvdp_mod _ E2).\nby rewrite geq_min orbC -ltnS (leq_trans _ le_qr) ?ltn_modp.\nQed.\n\nLemma dvdp_gcdl p q : gcdp p q %| p.\nProof. by case/andP: (dvdp_gcdlr p q). Qed.\n\nLemma dvdp_gcdr p q :gcdp p q %| q.\nProof. 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 | [dv_pm dv_pn]].\n  by rewrite ?(dvdp_trans dv_pmn) ?dvdp_gcdl ?dvdp_gcdr.\nmove: (leqnn (minn (size n) (size m))) dv_pm dv_pn.\nelim: {m n}minn {-2}m {-2}n => [|r Hrec] m n.\n  rewrite geq_min !leqn0 !size_poly_eq0.\n  by case/pred2P=> ->; rewrite (gcdp0, gcd0p).\ncase: (eqVneq m 0) => [-> _|nz_m]; first by rewrite gcd0p /=.\ncase: (eqVneq n 0) => [->|nz_n]; first by rewrite gcdp0 /=.\nrewrite gcdpE minnC /minn; case: ltnP => Cnm le_r dv_m dv_n.\n  apply: Hrec => //; last by rewrite -(dvdp_mod _ dv_m).\n  by rewrite geq_min orbC -ltnS (leq_trans _ le_r) ?ltn_modp.\napply: Hrec => //; last by rewrite -(dvdp_mod _ dv_n).\nby rewrite geq_min orbC -ltnS (leq_trans _ le_r) ?ltn_modp.\nQed.\n\n\nLemma gcdpC : forall p q, gcdp p q %= gcdp q p.\nProof. by move=> p q; 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.\ncase p00: (p`_0 == 0); first by rewrite (eqP p00) modp0 gcdp0 size_poly1.\nby rewrite modpC ?p00 // 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 => //; rewrite {2}(_: q = (-p) * r + (p * r + q)) ?H //.\n  by rewrite GRing.mulNr GRing.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 -{2}(mul1r m) 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.\ncase: (eqVneq n 0) => [-> | nn0]; first by rewrite gcd0p mulr0 eqpxx.\ncase: (eqVneq m 0) => [-> | mn0]; first by rewrite mul0r gcdp0 eqpxx.\nrewrite gcdpE modp_mull gcd0p size_mul //; case: ifP; first by rewrite eqpxx.\nrewrite  (polySpred mn0) addSn /= -{1}[size n]add0n ltn_add2r; move/negbT.\nrewrite -ltnNge prednK ?size_poly_gt0 // leq_eqVlt ltnS leqn0 size_poly_eq0.\nrewrite (negPf mn0) orbF; case/size_poly1P=> c cn0 -> {mn0 m}; rewrite mul_polyC.\nsuff -> : n %% (c *: n) = 0 by rewrite gcd0p; exact: eqp_scale.\nby apply/modp_eq0P; rewrite dvdp_scalel.\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 dvdp_scaler.\nby apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdp_scalel.\nQed.\n\nLemma gcdp_scaler c m n : c != 0 -> gcdp m (c *: n) %= gcdp m n.\nProof.\nmove=> cn0; apply: eqp_trans (gcdpC _ _) _.\napply: eqp_trans (gcdp_scalel _ _ _) _ => //; exact: gcdpC.\nQed.\n\nLemma dvdp_gcd_idl m n : m %| n -> gcdp m n %= m.\nProof.\ncase: (eqVneq m 0) => [-> | mn0].\n  by rewrite dvd0p => /eqP ->; rewrite gcdp0 eqpxx.\nrewrite dvdp_eq; move/eqP; move/(f_equal (gcdp m)) => h.\napply: eqp_trans (gcdp_mull (n %/ m) _); rewrite -h eqp_sym gcdp_scaler //.\nby rewrite expf_neq0 // lead_coef_eq0.\nQed.\n\nLemma dvdp_gcd_idr m n : n %| m -> gcdp m n %= n.\nProof. move/dvdp_gcd_idl => h; apply: eqp_trans h; exact: gcdpC. Qed.\n\nLemma gcdp_exp p k l : gcdp (p ^+ k) (p ^+ l) %= p ^+ minn k l.\nProof.\nwlog leqmn: k l / k <= l.\n  move=> hwlog; case: (leqP k l); first exact: hwlog.\n  move/ltnW; rewrite minnC; move/hwlog=> h; apply: eqp_trans h; exact: gcdpC.\nrewrite (minn_idPl leqmn); move/subnK: leqmn<-; rewrite exprD.\napply: eqp_trans (gcdp_mull _ _) _; exact: eqpxx.\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.\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.\nmove=> e1 e2.\nby apply: eqp_trans (eqp_gcdr _ e2); apply: eqp_trans (eqp_gcdl _ e1).\nQed.\n\nLemma eqp_rgcd_gcd p q : rgcdp p q %= gcdp p q.\nProof.\nmove: (leqnn (minn (size p) (size q))); move: {2}(minn (size p) (size q)) => n.\nelim: n p q => [p q|n ihn p q hs].\n  rewrite leqn0 /minn; case: ltnP => _; rewrite size_poly_eq0; move/eqP->.\n    by rewrite gcd0p rgcd0p eqpxx.\n  by rewrite gcdp0 rgcdp0 eqpxx.\ncase: (eqVneq p 0) => [-> | pn0]; first by rewrite gcd0p rgcd0p eqpxx.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite gcdp0 rgcdp0 eqpxx.\nrewrite gcdpE rgcdpE; case: ltnP => sp.\n  have e := (eqp_rmod_mod q p); move: (e); move/(eqp_gcdl p) => h.\n  apply: eqp_trans h; apply: ihn; rewrite (eqp_size e) geq_min.\n  by rewrite -ltnS (leq_trans _ hs) // (minn_idPl (ltnW _)) ?ltn_modp.\nhave e := (eqp_rmod_mod p q); move: (e); move/(eqp_gcdl q) => h.\napply: eqp_trans h; apply: ihn; rewrite (eqp_size e) geq_min.\nby rewrite -ltnS (leq_trans _ hs) // (minn_idPr _) ?ltn_modp.\nQed.\n\nLemma gcdp_modr m n : gcdp m (n %% m) %= gcdp m n.\nProof.\ncase: (eqVneq m 0) => [-> | mn0]; first by rewrite modp0 eqpxx.\nhave : (lead_coef m) ^+ (scalp n m) != 0 by rewrite expf_neq0 // lead_coef_eq0.\nmove/gcdp_scaler; move/(_ m n) => h; apply: eqp_trans h; rewrite divp_eq.\nby rewrite eqp_sym gcdp_addl_mul.\nQed.\n\nLemma gcdp_modl m n : gcdp (m %% n) n %= gcdp m n.\nProof.\napply: eqp_trans (gcdpC _ _) _; apply: eqp_trans (gcdp_modr _ _) _.\nexact: 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.\napply: h; [exact: dvdp_gcdl | exact: 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 coprimep_scalel c m n :\n  c != 0 -> coprimep (c *: m) n = coprimep m n.\nProof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scalel _ _ _)). Qed.\n\nLemma coprimep_scaler c m n:\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.\nby rewrite -!gcdp_eqp1; apply: eqp_ltrans; rewrite gcdpC.\nQed.\n\nLemma coprime1p p : coprimep 1 p.\nProof.\nrewrite /coprimep -[1%N](size_poly1 R); apply/eqP; apply: eqp_size.\nexact: gcd1p.\nQed.\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.\napply: (iffP idP)=> [|h].\n  rewrite /coprimep; move/eqP=> hs d dvddp dvddq.\n  have dvddg: d %| gcdp p q by rewrite dvdp_gcd dvddp dvddq.\n  by apply: (dvdp_eqp1 dvddg); rewrite -size_poly_eq1; apply/eqP.\ncase/andP: (dvdp_gcdlr p q)=> h1 h2.\nby rewrite /coprimep size_poly_eq1; 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; case/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=> rq cpq; apply/coprimepP=> d dp dr; move/coprimepP:cpq=> cpq'.\nby apply: cpq'; rewrite // (dvdp_trans dr).\nQed.\n\nLemma coprimep_dvdr  p q r :\n  r %| p -> coprimep p q -> coprimep r q.\nProof.\nmove=> rp; rewrite ![coprimep _ q]coprimep_sym.\nby move/coprimep_dvdl; apply.\nQed.\n\n\nLemma coprimep_modl p q : coprimep (p %% q) q = coprimep p q.\nProof.\nsymmetry; rewrite !coprimep_def.\ncase: (ltnP (size p) (size q))=> hpq; first by rewrite modp_small.\nby rewrite gcdpE ltnNge 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.\nby rewrite /coprimep /rcoprimep; rewrite (eqp_size (eqp_rgcd_gcd _ _)).\nQed.\n\nLemma eqp_coprimepr p q r : q %= r -> coprimep p q = coprimep p r.\nProof.\nby rewrite -!gcdp_eqp1; move/(eqp_gcdr p) => h1; apply: (eqp_ltrans h1).\nQed.\n\nLemma eqp_coprimepl p q r : q %= r -> coprimep q p = coprimep r p.\nProof. rewrite !(coprimep_sym _ p); exact: 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).\nProof. 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 leqn0 size_poly_eq0 (negPf qn0).\nmove=> sqSn qsp; case: (eqVneq q 0)=> q0; first by rewrite q0 eqxx in qn0.\nrewrite (negPf qn0).\nhave sp : size p > 0 by apply: leq_trans qsp; rewrite  size_poly_gt0.\ncase: (eqVneq (p %% q) 0) => [r0 | rn0] /=.\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  case: (eqVneq v 0)=> [-> | vn0].\n    rewrite mul0r size_opp size_poly0 maxn0; apply: leq_trans ihn'1 _.\n    exact: leq_modp.\n  case: (eqVneq (p %/ q) 0)=> [-> | qqn0].\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 -(leq_add2r (size (p %/ q))).\n  have : size v + size (p %/ q) > 0 by rewrite addn_gt0 size_poly_gt0 vn0.\n  have : size q + size (p %/ q) > 0 by rewrite addn_gt0 size_poly_gt0 qn0.\n  do 2! move/prednK=> {1}<-; rewrite ltnS => h; apply: leq_trans h _.\n  rewrite size_divp // addnBA; last by apply: leq_trans qsp; exact: leq_pred.\n  rewrite addnC -addnBA ?leq_pred //; move: qn0; rewrite -size_poly_eq0 -lt0n.\n  by move/prednK=> {1}<-; rewrite subSnn addn1.\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.\nmove=> pn0 qn0; rewrite /egcdp; case: (leqP (size q) (size p)) => /= hp.\n  by apply: egcdp_recP.\nmove/ltnW: hp => hp; case: (egcdp_recP pn0 (leqnn (size p)) hp) => h1 h2 h3.\nby split => //; 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 [p0 | pn0] := eqVneq p 0; last by case: (egcdpP pn0 qn0).\nrewrite p0 gcd0p mulr0 add0r /egcdp size_poly0 leqn0 size_poly_eq0 (negPf qn0).\nby rewrite /= mul1r.\nQed.\n\nLemma Bezoutp p q : exists u, u.1 * p + u.2 * q %= (gcdp p q).\nProof.\ncase: (eqVneq p 0) => [-> | pn0].\n  by rewrite gcd0p; exists (0, 1); rewrite mul0r mul1r add0r.\ncase: (eqVneq q 0) => [-> | qn0].\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 : forall p q,\n  reflect (exists u, u.1 * p + u.2 * q %= 1) (coprimep p q).\nProof.\nmove=> p q; rewrite -gcdp_eqp1; apply:(iffP idP)=> [g1|].\n  case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); exact: 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.\nmove/(f_equal (fun t => horner t 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:Puv; move/(eqp_mull p); 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. rewrite mulrC; exact: 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.\ncase: (eqVneq m 0) => [-> | mn0].\n  by rewrite coprime0p;  move/eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT.\ncase: (eqVneq n 0) => [-> | nn0].\n  by rewrite coprimep0; move/eqp_dvdl->; rewrite !mulr0 dvd1p.\nmove=> hc; apply/idP/idP.\n  move/Gauss_dvdpl: hc => <- h; move/(dvdp_mull m): (h); rewrite dvdp_mul2l //.\n  move->; move/(dvdp_mulr n): (h); rewrite dvdp_mul2r // andbT.\n  exact: dvdp_mulr.\ncase/andP => dmp dnp; move: (dnp); rewrite dvdp_eq.\nset c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> e2.\nhave := (sym_eq (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 coprimep_mulr p q r : coprimep p (q * r) = (coprimep p q && coprimep p r).\nProof.\napply/coprimepP/andP=> [hp|[/coprimepP hq hr]].\n  split; apply/coprimepP=> d dp dq; rewrite hp //;\n [exact: dvdp_mulr|exact: 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 coprimep_mull p q r: coprimep (q * r) p = (coprimep q p && coprimep r p).\nProof. by rewrite ![coprimep _ p]coprimep_sym coprimep_mulr. 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 coprimep_mull -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); exact: coprimep_expl. Qed.\n\nLemma gcdp_mul2l p q r : gcdp (p * q) (p * r) %= (p * gcdp q r).\nProof.\ncase: (eqVneq p 0)=> [->|hp]; 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]GRing.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.\nmove=> hpq.\nhave gpq0: gcdp p q != 0 by rewrite gcdp_eq0 negb_and.\nrewrite -gcdp_eqp1 -(@eqp_mul2r (gcdp p q)) // mul1r.\nhave: gcdp p q %| p by rewrite dvdp_gcdl.\nhave: gcdp p q %| q by rewrite dvdp_gcdr.\nrewrite !dvdp_eq eq_sym; move/eqP=> hq; rewrite eq_sym; move/eqP=> hp.\nrewrite (eqp_ltrans (mulp_gcdl _ _ _)) hq hp.\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 p 0) => [->|pn0]; first by rewrite eqxx.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite eqxx orbT.\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] := altP (p =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)).\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.\ncase/orP; first by rewrite ltnS leqn0 size_poly_eq0 gcdp_eq0 -[p == 0]negbK pn0.\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 -!{1}scalerAl !scalerAr hu1 hv1 mulrCA.\nrewrite !{1}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 -{1}(addn0 (size p)) -{1}(addn0 (size q)) !ltn_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.\ncase: (eqVneq n 0) => [-> | nn0] //; case: (eqVneq m 0) => [-> | mn0].\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.\nrewrite -(@dvdp_scaler (c1 ^+ k)) ?expf_neq0 ?lead_coef_eq0 //.\nhave c2k_n0 : c2 ^+ k != 0 by rewrite !expf_neq0 // lead_coef_eq0.\nrewrite -(@dvdp_scalel (c2 ^+k)) // -!exprZn def_m def_n !exprMn.\nrewrite dvdp_mul2r ?expf_neq0 //.\nhave: coprimep (m' ^+ k) (n' ^+ k).\n  rewrite coprimep_pexpl // coprimep_pexpr //; apply: coprimep_div_gcd.\n  by rewrite nn0 orbT.\nmove/coprimepP=> hc hd.\nhave /size_poly1P [c cn0 em'] : size m' == 1%N.\n  case: (eqVneq m' 0) => [m'0 |m'_n0].\n    move/eqP: def_m; rewrite m'0 mul0r scale_poly_eq0.\n    by rewrite (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  rewrite size_exp eqSS muln_eq0;  move: k_gt0; rewrite lt0n; move/negPf->.\n  by rewrite orbF -{2}(@prednK (size m')) ?lt0n // size_poly_eq0.\nrewrite -(@dvdp_scalel c2) // def_m em' mul_polyC dvdp_scalel //.\nby rewrite -(@dvdp_scaler 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 : forall x (ps : seq {poly R}),\n  root (\\big[gcdp/0]_(p <- ps) p) x = all (fun p => root p x) ps.\nProof.\nmove=> x; elim; first by rewrite big_nil root0.\nby move=> p ps ihp; 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\nCoInductive 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 : forall q p k,\n  size p <= k -> gdcop_spec q p (gdcop_rec q p k).\nProof.\nmove=> q p k; elim: k p => [p | k ihk p] /=.\n  rewrite leqn0 size_poly_eq0; move/eqP->.\n  case q0: (_ == _); split; rewrite ?coprime1p // ?eqxx ?orbT //.\n  by move=> d _; rewrite (eqP q0) coprimep0 dvdp1 size_poly_eq1.\nmove=> hs; case cop : (coprimep _ _); first by split; rewrite ?dvdpp ?cop.\ncase (eqVneq p 0) => [-> | p0].\n  by rewrite div0p; apply: ihk; rewrite size_poly0 leq0n.\ncase: (eqVneq q 0) => [-> | q0].\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  move: (dvdp_mulIl (p %/ gcdp p q) (gcdp p q)); move/dvdpN0; apply; rewrite -e.\n  by rewrite scale_poly_eq0 negb_or lc_expn_scalp_neq0.\nhave gn0 : gcdp p q != 0.\n  move: (dvdp_mulIr (p %/ gcdp p q) (gcdp p q)); move/dvdpN0; apply; rewrite -e.\n  by rewrite 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)//.\n  rewrite -subn_gt0 addnK -subn1 ltn_subRL addn0 ltnNge leq_eqVlt.\n  by rewrite [_ == _]cop ltnS leqn0 size_poly_eq0 (negPf gn0).\ncase (ihk _ sp')=> r' dr'p'; first rewrite p'n0 orbF=> cr'q maxr'.\nconstructor=> //=; rewrite ?(negPf p0) ?orbF //.\n  apply: (dvdp_trans dr'p'); apply: divp_dvd; exact: 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; move: cdq.\n  apply: contraLR=> nd1; apply/coprimepPn; last first.\n    by exists d; rewrite dvdp_gcd dvdpp dq nd1.\n  move/negP: p0; move/negP; apply: contra=> d0; move:dp; rewrite (eqP d0).\n  by rewrite dvd0p.\nmove: (dp); apply: contraLR=> 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.\ncase: (eqVneq d 0) => [-> | dn0]; 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  move: crq; apply: contraL=> dq; rewrite p0f orbF; apply/coprimepPn.\n    by move:p0; apply: contra=> r0; move: rp; rewrite (eqP 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; case/orP; first by rewrite -size_poly_eq1.\n  rewrite ltnS leqn0 size_poly_eq0; move/eqP=> x0; move: xd; rewrite x0 dvd0p.\n  by rewrite (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.\nProof. 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.\ncase: (eqVneq p 0) => [-> | pn0].\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_eq0 -lt0n => [[/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: root (p - p.[c]%:P) c by rewrite /root !hornerE subrr.\ncase/factor_theorem=> q /(canRL (subrK _)) Dp; rewrite modpE /= lead_coefXsubC.\nrewrite  GRing.unitr1 expr1n invr1 scale1r {1}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 [-> | /coprimep_scalel->] := altP eqP; last exact: coprime1p.\nby rewrite scale0r /coprimep gcd0p size_XsubC.\nQed.\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 -{1}(monicP monic_q) -(monicP monic_p) -!lead_coefZ eq_pq.\nQed.\n\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\nHint Resolve eqpxx divp0 divp1 mod0p modp0 modp1 dvdp_mull dvdp_mulr dvdpp.\nHint Resolve dvdp0.\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 MonicDivisor.\n\nVariable R : idomainType.\nVariable q : {poly R}.\nHypothesis monq : q \\is monic.\n\nImplicit Type p d r : {poly R}.\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.\nProof. by rewrite mulrC; exact: mulpK. Qed.\n\nEnd MonicDivisor.\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 {1}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.\ncase abs: (p %/ d - q == 0).\n  move: abs; rewrite subr_eq0; move/eqP->; rewrite subrr mul0r; move/eqP.\n  by rewrite eq_sym subr_eq0; move/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 abs.\n  move: abs; rewrite -size_poly_eq0; move/negbT; rewrite -lt0n; move/prednK<-.\n  by rewrite addSn /= leq_addl.\nhave hlt : size (r - p %% d) < size d.\n  apply: leq_ltn_trans (size_add _ _) _; rewrite size_opp.\n  by rewrite gtn_max srd 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 ->\n  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.\n  case: (altP (lead_coef q =P 0)) => [->|]; first by rewrite unitr0.\n  rewrite lead_coef_eq0 => nz_q ulcq; apply: (iffP idP).\n    case: (altP (p =P 0)) => [->|nz_p].\n      by rewrite eqp_sym eqp0 (negbTE 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.\n  by 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 {1}(divp_eq p) 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 modp_scalel c p : (c *: p) %% d = c *: (p %% d).\nProof.\ncase: (altP (c =P 0)) => [-> | cn0]; first by rewrite !scale0r mod0p.\nhave e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d).\n  by rewrite -scalerAl -scalerDr -divp_eq.\nhave s: size (c *: (p %% d)) < size d.\n  rewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _.\n  rewrite size_polyC cn0 addSn add0n /= ltn_modp.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\nby case: (edivpP e s) => _ ->.\nQed.\n\nLemma divp_scalel c p : (c *: p) %/ d = c *: (p %/ d).\nProof.\ncase: (altP (c =P 0)) => [-> | cn0]; first by rewrite !scale0r div0p.\nhave e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d).\n  by rewrite -scalerAl -scalerDr -divp_eq.\nhave s: size (c *: (p %% d)) < size d.\n  rewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _.\n  rewrite size_polyC cn0 addSn add0n /= ltn_modp.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\nby case: (edivpP e s) => ->.\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 //= -!modp_scalel 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 // -!divp_scalel e.\nQed.\n\nLemma modp_opp p : (- p) %% d = - (p %% d).\nProof.\nby rewrite -mulN1r -[- (_ %% _)]mulN1r -polyC_opp !mul_polyC modp_scalel.\nQed.\n\nLemma divp_opp p : (- p) %/ d = - (p %/ d).\nProof.\nby rewrite -mulN1r -[- (_ %/ _)]mulN1r -polyC_opp !mul_polyC divp_scalel.\nQed.\n\nLemma modp_add p q : (p + q) %% d = p %% d + q %% d.\nProof.\nhave hs : size (p %% d + q %% d) < size d.\n  apply: leq_ltn_trans (size_add _ _) _.\n  rewrite gtn_max !ltn_modp andbb -lead_coef_eq0.\n  by apply: contraTneq ulcd => ->; rewrite unitr0.\nhave he : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d).\n  rewrite {1}(divp_eq p) {1}(divp_eq q) addrAC addrA -mulrDl.\n  by rewrite [_ %% _ + _]addrC addrA.\nby case: (edivpP he hs).\nQed.\n\nLemma divp_add p q : (p + q) %/ d = p %/ d + q %/ d.\nProof.\nhave hs : size (p %% d + q %% d) < size d.\n  apply: leq_ltn_trans (size_add _ _) _.\n  rewrite gtn_max !ltn_modp andbb -lead_coef_eq0.\n  by apply: contraTneq ulcd => ->; rewrite unitr0.\nhave he : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d).\n  rewrite {1}(divp_eq p) {1}(divp_eq q) addrAC addrA -mulrDl.\n  by rewrite [_ %% _ + _]addrC addrA.\nby case: (edivpP he hs).\nQed.\n\nLemma mulpK q : (q * d) %/ d = q.\nProof.\nhave:= (sym_eq (addr0 (q * d))); case/edivpP; 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.\nProof. rewrite mulrC; exact: mulpK. Qed.\n\nLemma divp_addl_mul_small q r :\n  size r < size d -> (q * d + r) %/ d = q.\nProof. by move=> srd; rewrite divp_add (divp_small srd) addr0 mulpK. Qed.\n\nLemma modp_addl_mul_small q r :\n  size r < size d -> (q * d + r) %% d = r.\nProof. by move=> srd; rewrite modp_add modp_mull add0r modp_small. Qed.\n\nLemma divp_addl_mul q r : (q * d + r) %/ d = q + r %/ d.\nProof. by rewrite divp_add mulpK. Qed.\n\nLemma divpp : d %/ d = 1.\nrewrite divpE ulcd RingComRreg.rdivpp; [| by red; rewrite 1?mulrC | exact: mulIr].\nrewrite -mul_polyC -polyC_mul mulVr //; exact: unitrX.\nQed.\n\nLemma leq_trunc_divp m : size (m %/ d * d) <= size m.\nProof.\nhave dn0 : d != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\ncase q0 : (m %/ d == 0); first by rewrite (eqP q0) mul0r size_poly0 leq0n.\nrewrite {2}(divp_eq m) size_addl // size_mul ?q0 //; move/negbT: q0.\nrewrite -size_poly_gt0; move/prednK<-; rewrite addSn /=.\nby move: dn0; rewrite -(ltn_modp m); move/ltn_addl->.\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->.\nsuff dn0 : d != 0 by move/(mulIf dn0).\nby rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; 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); exact: 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.\nhave -> : q %% d = q - q %/ d * d by rewrite {2}(divp_eq q) -addrA addrC subrK.\nrewrite mulrDr modp_add // -mulNr mulrA -{2}[_ %% _]addr0; congr (_ + _).\nby apply/eqP; apply: dvdp_mull; exact: dvdpp.\nQed.\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.\nby move/subnK=> {2}<-; rewrite exprD mulpK // lead_coef_exp unitrX.\nQed.\n\nLemma divp_pmul2l p q : lead_coef q \\in GRing.unit -> d * p %/ (d * q) = p %/ q.\nProof.\nmove=> uq.\nhave udq: lead_coef (d * q) \\in GRing.unit.\n  by rewrite lead_coefM unitrM_comm ?ulcd //; red; rewrite mulrC.\nrewrite {1}(divp_eq uq p) mulrDr mulrCA divp_addl_mul //.\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.\ncase: (altP ( (p %% q) =P 0)) => [-> | rn0].\n  by rewrite mulr0 size_poly0 size_poly_gt0.\nrewrite !size_mul //; move: dn0; rewrite -size_poly_gt0.\nby move/prednK<-; rewrite !addSn /= ltn_add2l ltn_modp.\nQed.\n\nLemma divp_pmul2r p q :\n  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  rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; exact: 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  case: (altP ((q %/ p) %% r =P 0)) => [-> | qn0].\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 modp_scaler c p : c \\in GRing.unit -> p %% (c *: d) = (p %% d).\nProof.\nmove=> cn0; case: (eqVneq d 0) => [-> | dn0]; 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 divp_scaler c p : c \\in GRing.unit -> p %/ (c *: d) = c^-1 *: (p %/ d).\nProof.\nmove=> cn0; case: (eqVneq d 0) => [-> | dn0].\n   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.\ncase: (eqVneq q 0) => [-> | qn0]; 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] := altP (q =P 0).\n  by rewrite eqp0 => /eqP ->; rewrite scaler0.\nmove/IdomainUnit.ucl_eqp_eq; apply; rewrite unitfE.\nby move: nz_q; rewrite -lead_coef_eq0 => nz_qT.\nQed.\n\nLemma dvdp_eq q p : (q %| p) = (p == p %/ q * q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; 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] := altP (q =P 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 modp_scalel c p q : (c *: p) %% q = c *: (p %% q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite !modp0.\nby apply: IdomainUnit.modp_scalel; 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; exact: mulpK. Qed.\n\nLemma divp_scalel c p q : (c *: p) %/ q = c *: (p %/ q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite !divp0 scaler0.\nby apply: IdomainUnit.divp_scalel; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma modp_scaler c p d : c != 0 -> p %% (c *: d) = (p %% d).\nProof.\nmove=> cn0; case: (eqVneq d 0) => [-> | dn0]; 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 divp_scaler c p d : c != 0 -> p %/ (c *: d) = c^-1 *: (p %/ d).\nProof.\nmove=> cn0; case: (eqVneq d 0) => [-> | dn0].\n  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 // -!modp_scalel 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 // -!divp_scalel 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 modp_scaler ?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.\nmove=> e1 e2; apply: eqp_trans (eqp_modpr _ e2).\napply: eqp_trans (eqp_modpl _ e1); exact: eqpxx.\nQed.\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 divp_scaler ?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.\nmove=> e1 e2; apply: eqp_trans (eqp_divr _ e2).\napply: eqp_trans (eqp_divl _ e1); exact: eqpxx.\nQed.\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 => _ //; apply: ihn.\napply: eqp_div => //; exact: 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  move: eqr; case: (eqVneq q 0)=> [-> | nq0 eqr] /=.\n    by rewrite eqp_sym eqp0; move->; rewrite eqxx eqpxx.\n  suff rn0 : r != 0 by rewrite (negPf nq0) (negPf rn0) eqpxx.\n  by apply: contraTneq eqr => ->; rewrite eqp0.\nrewrite (eqp_coprimepr _ eqr) (eqp_coprimepl _ esp); case: ifP=> _ //.\napply: ihn => //; apply: eqp_div => //; exact: 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  move: tq; case: (eqVneq t 0)=> [-> | nt0 etq].\n    by rewrite eqp_sym eqp0; move->; rewrite eqxx eqpxx.\n  suff qn0 : q != 0 by rewrite (negPf nt0) (negPf qn0) eqpxx.\n  by apply: contraTneq etq => ->; rewrite 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 modp_opp p q : (- p) %% q = - (p %% q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite !modp0.\nby apply: IdomainUnit.modp_opp; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_opp p q : (- p) %/ q = - (p %/ q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; first by rewrite !divp0 oppr0.\nby apply: IdomainUnit.divp_opp; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma modp_add d p q : (p + q) %% d = p %% d + q %% d.\nProof.\ncase: (eqVneq d 0) => [-> | dn0]; first by rewrite !modp0.\nby apply: IdomainUnit.modp_add; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma modNp p q : (- p) %% q = - (p %% q).\nProof. by apply/eqP; rewrite -addr_eq0 -modp_add addNr mod0p. Qed.\n\nLemma divp_add d p q : (p + q) %/ d = p %/ d + q %/ d.\nProof.\ncase: (eqVneq d 0) => [-> | dn0]; first by rewrite !divp0 addr0.\nby apply: IdomainUnit.divp_add; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_addl_mul_small d q r :\n  size r < size d -> (q * d + r) %/ d = q.\nProof.\nmove=> srd; rewrite divp_add (divp_small srd) addr0 mulpK //.\nby rewrite -size_poly_gt0; apply: leq_trans srd.\nQed.\n\nLemma modp_addl_mul_small d q r :\n  size r < size d -> (q * d + r) %% d = r.\nProof. by move=> srd; rewrite modp_add 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 divp_add 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.\ncase: (eqVneq d 0) => [-> | dn0]; 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) => [-> | dn0]; first by move/dvd0pP->; 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) => [-> | dn0]; first by move/dvd0pP->; 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); exact: 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.\ncase: (eqVneq r 0) => [-> | rn0]; first by rewrite mulr0 !divp0.\ncase: (eqVneq p 0) => [-> | pn0]; 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 /=.\ncase (eqVneq q 0) => [-> | qn0]; first by rewrite eqxx lead_coef0 unitr0.\nrewrite (negPf qn0) /= unitfE lead_coef_eq0 qn0 /=.\nby case: (redivp_rec _ _ _ _) => [[]].\nQed.\n\nLemma divpE p q : p %/ q = (lead_coef q)^-(rscalp p q) *: (rdivp p q).\nProof.\ncase: (eqVneq q 0) => [-> | qn0]; 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.\ncase: (eqVneq q 0) => [-> | qn0].\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.\ncase: (eqVneq q 0) => [-> | qn0]; 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\nCoInductive 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.\nrewrite -size_poly_gt0; exact: leq_trans srd.\nQed.\n\nLemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m.\nProof.\nhave ->: q %% m = q - q %/ m * m by rewrite {2}(divp_eq q m) -addrA addrC subrK.\nrewrite mulrDr modp_add // -mulNr mulrA -{2}[_ %% _]addr0; congr (_ + _).\nby apply/eqP; apply: dvdp_mull; exact: dvdpp.\nQed.\n\nLemma dvdpP p q : reflect (exists qq, p = qq * q) (q %| p).\nProof.\ncase: (eqVneq q 0)=> [-> | qn0]; last first.\n  by apply: IdomainUnit.dvdpP; rewrite unitfE lead_coef_eq0.\nrewrite dvd0p.\nby apply: (iffP idP) => [/eqP->| [? ->]]; [exists 1|]; rewrite mulr0.\nQed.\n\nLemma Bezout_eq1_coprimepP : forall p q,\n  reflect (exists u, u.1 * p + u.2 * q = 1) (coprimep p q).\nProof.\nmove=> p q; apply:(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.\nmove=> q_neq0; rewrite /gdcop.\nelim: (size p) {-2 5}p (leqnn (size p))=> {p} [|n ihn] p.\n  rewrite size_poly_leq0; move/eqP->.\n  by rewrite size_poly0 /= dvd0p expr0 mulr1 (negPf q_neq0).\nmove=> hsp /=; have [->|p_neq0] := altP (p =P 0).\n  rewrite size_poly0 /= dvd0p expr0 mulr1 div0p /=.\n  case: ifP=> // _; have := (ihn 0).\n  by rewrite size_poly0 expr0 mulr1 dvd0p=> /(_ isT).\nhave [|ncop_pq] := boolP (coprimep _ _); first by rewrite dvdp_mulr ?dvdpp.\nhave g_gt1: (1 < size (gcdp p q))%N.\n  have [|//|/eqP] := ltngtP; last by rewrite -coprimep_def (negPf ncop_pq).\n  by rewrite ltnS leqn0 size_poly_eq0 gcdp_eq0 (negPf p_neq0).\nhave sd : (size (p %/ gcdp p q) < size p)%N.\n  rewrite size_divp -?size_poly_eq0 -(subnKC g_gt1) // add2n /=.\n  by rewrite -[size _]prednK ?size_poly_gt0 // ltnS subSS leq_subr.\nrewrite -{1}[p](divpK (dvdp_gcdl _ q)) -(subnKC sd) addSnnS exprD mulrA.\nrewrite dvdp_mul ?ihn //; first by rewrite -ltnS (leq_trans sd).\nby rewrite exprS dvdp_mulr // dvdp_gcdr.\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  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 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.\ncase: eqP; rewrite /= -(rmorph0 (map_poly_rmorphism f)) //; move/eqP=> q_nz.\nmove: (size a) => m; 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.\ncase: (eqVneq b 0) => [-> | bn0].\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=> IH; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IH.\n  rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp.\n  case: (eqVneq q 0) => [-> | q_nz]; first by rewrite rmorph0 !gcdp0.\n  by rewrite IH ?ltn_modp.\nelim: {q}_.+1 p {-2}q (ltnSn (size q)) lt_p_q => // m IHm p q le_q_m lt_p_q.\nrewrite gcdpE (gcdpE p^f) !size_map_poly lt_p_q -map_modp.\ncase: (eqVneq p 0) => [-> | q_nz]; 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/negbTE->].\nQed.\n\nLemma coprimepP (p q : {poly F}):\n  reflect (forall x, root p x -> q.[x] != 0) (coprimep p q).\nProof.\n  by apply: (iffP idP)=> [/coprimep_root|/root_coprimep].\nQed.\n\nEnd closed.\n\nEnd ClosedField.\n\nEnd Pdiv.\n\nExport Pdiv.Field.\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/polydiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7525949725744051}}
{"text": "(* Write the function that corresponsd to the polynomial 2 * x^2 + 3 * x + 3 on\n   relative integers, using lambda abstraction and the functions Zplus and\n   Zmult provided in the ZArith library of Coq. Compute the value of this\n   function on integers 2, 3, 4.*)\n\nRequire Import ZArith.\n\nOpen Scope Z_scope.\n\nDefinition Z_poly (x:Z) : Z :=\n  (Zplus (Zplus (Zmult 2 (Zmult x x)) (Zmult 3 x)) 3).\n\nEval compute in Z_poly.\nEval compute in (Z_poly 2).\nEval compute in (Z_poly 3).\nEval compute in (Z_poly 4).\n", "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/ch2/ex_2_7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9715639653084245, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7525573092369253}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 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_distrib_100_plus_assoc/goal33conj232_coqofml_FC8ryr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7524557493958178}}
{"text": "Set Warnings \"-notation-overridden-parsing\".\nAdd LoadPath \"/Users/lubis/Documents/study/software_foundations\".\nRequire Export Poly.\nRequire Export Lists.\n\nTheorem silly1: forall n m o p: nat,\n  n = m -> [n;o] = [n;p] -> [n;o] = [m;p]. \nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1, eq2.\n  reflexivity.\nQed.\n\nTheorem silly1': forall n m o p: nat,\n  n = m -> [n;o] = [n;p] -> [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1. 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, 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, eq1.\nQed.\n\n(* Page 93 Exercise *)\n\nTheorem silly_ex:\n  (forall n: nat, evenb n = true -> oddb (S n) = true) ->\n  oddb 3 = true -> evenb 4 = true.\nProof.\n  intros eq1 eq2. apply eq2.\nQed.\n\n(* Exercise ends *)\n\nTheorem silly3_firsttry: forall n: nat,\n  true = (n =? 5) -> (S (S n)) =? 7 = true.\nProof.\n  intros n H. symmetry.\n  apply H.\nQed.\n\n(* Page 94 Exercise *)\n\n\nTheorem rev_exercise: forall l1 l2: list nat,\n  l1 = rev l2 -> l2 = rev l1.\nProof.\n  intros l1 l2 eq1. rewrite -> eq1. \n  symmetry. apply rev_involutive.\nQed.\n\n(* Exercise ends *)\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, 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, 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\n(* Page 95 Exercise *)\n\nExample trans_eq_exercise:\n  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\n(* Exercise Ends *)\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    { reflexivity. }\n  rewrite H2. rewrite H1. 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. intros Hnm. apply Hnm.\nQed.\n\nTheorem injection_ex1:\n  forall n m o: nat,\n  [n;m] = [o;o] -> n = m.\nProof.\n  intros n m o H.\n  injection H. intros H1 H2.\n  rewrite H1, H2. reflexivity.\nQed.\n\nTheorem injection_ex2:\n  forall n m: nat,\n  [n] = [m] -> n = m.\nProof.\n  intros n m H.\n  injection H as Hnm. apply Hnm.\nQed.\n\n(* Page 97 Exercise *)\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.\n  intros H2a. intros H2b.\n  symmetry. apply H2b.\nQed.\n\n(* Exercise Ends *)\n\nTheorem eqb_0_l: forall n: nat,\n  0 =? n = true -> n = 0.\nProof.\n  intros n.\n  destruct n as [| n'] eqn:E.\n  - intros H. reflexivity.\n  - simpl. intros H. discriminate H.\nQed.\n\nTheorem discriminate_ex1: forall n: nat,\n  S n = O -> 2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra.\nQed.\n\nTheorem discriminate_ex2: forall n m: nat,\n  false = true -> [n] = [m].\nProof.\n  intros n m contra. discriminate contra.\nQed.\n\n(* Page 98 Exercise *)\n\nExample discriminate_ex3:\n  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\n(* Exercise ends *)\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 eq.\n  rewrite eq. reflexivity.\nQed.\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 H. simpl in H. apply H.\nQed.\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. symmetry in H. apply eq in H. symmetry in H.\n  apply H.\nQed.\n\nTheorem plus_n_n_injective:\n  forall n m: nat, n + n = m + m -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  - simpl. intros m. destruct m as [| m'].\n    + reflexivity.\n    + discriminate.\n  - intros m. destruct m as [| m'].\n    + discriminate.\n    + intros eq. \n      rewrite <- plus_n_Sm in eq. rewrite <- plus_n_Sm in eq.\n      apply S_injective in eq.\n      simpl in eq. apply S_injective in eq.\n      apply IHn' in eq.\n      rewrite eq. reflexivity.\nQed.\n\nTheorem double_injective_FAILED:\n  forall n m: nat, double n = double m -> n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - simpl. intros eq. destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - intros eq. destruct m as [| m'] eqn:E.\n    + discriminate eq.\n    + apply f_equal. Abort.\n\nTheorem double_injective:\n  forall n m: nat, double n = double m -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  - simpl. intros m. destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + discriminate.\n  - simpl.\n    intros m eq.\n    destruct m as [| m'] eqn:E.\n    + simpl. discriminate.\n    + apply f_equal. apply IHn'. simpl in eq. injection eq.\n      intros H. apply H.\nQed.\n\n(* Page 102 Exercise *)\n\nTheorem eqb_true: forall n m: nat,\n  n =? m = true -> n = m.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - intros m. destruct m as [| m'].\n    + reflexivity.\n    + discriminate.\n  - intros m. simpl. destruct m as [| m'].\n    + discriminate.\n    + intros eq. apply IHn' in eq. apply f_equal, eq.\nQed.\n\n(* Exercise Ends *)\n\nTheorem double_injective_take2_FAILED:\n  forall n m: nat, double n = double m -> n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - simpl. intros eq. destruct n as [| n'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - intros eq. destruct n as [| n'] eqn:E.\n    + discriminate.\n    + apply f_equal.\nAbort.\n\nTheorem double_injective_take2:\n  forall n m: nat, double n = double m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m' IHm'].\n  - simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + reflexivity.\n    + discriminate.\n  - simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + discriminate.\n    + apply f_equal, IHm'.\n      simpl in eq. injection eq.\n      intros H. apply H.\nQed.\n\n(* Page 104 Exercise *)\n\nTheorem nth_error_after_last:\n  forall (n: nat) (X: Type) (l: list X),\n  length l = n -> nth_error l n = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l as [| x l' IHl'].\n  - simpl. intros n H. reflexivity.\n  - intros n. destruct n as [| n']. simpl.\n    + discriminate.\n    + simpl. intros eq. injection eq. \n      intros eq1. apply IHl' in eq1. apply eq1.\nQed.\n\n(* Exercise Ends *)\n\nDefinition square n := n * n.\n\nLemma square_mult:\n  forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\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. 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  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.\nQed.\n\n(* Page 107 Exercise *)\n\nLemma combine_split_lemma:\n  forall (X Y: Type) (p: X*Y) (l1 l2: list (X*Y)),\n  l1 = l2 -> p :: l1 = p :: l2.\nProof.\n  intros X Y p l1 l2 eq.\n  inversion eq. reflexivity.\nQed.\n\nTheorem combine_split:\n  forall (X Y: Type) (l: list (X*Y)) l1 l2,\n  split l = (l1,l2) -> combine l1 l2 = l.\nProof.\n  intros X Y. induction l as [| p l' IHl'].\n  - intros l1 l2. simpl. intros eq. inversion eq. reflexivity.\n  - intros l1 l2. simpl. destruct p. destruct (split l').\n    destruct l1 as [| x1 l1'] eqn:E1.\n    + intros eq1. inversion eq1.\n    + destruct l2 as [| x2 l2'] eqn:E2.\n        intros eq1. inversion eq1.\n        intros eq1. inversion eq1. simpl.\n        apply combine_split_lemma. apply IHl'.\n        rewrite H1. rewrite H3. reflexivity.\nQed.\n        \n\n(* Exercise Ends *)\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_FAILED:\n  forall n: nat, sillyfun1 n = true -> oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\nAbort.\n\nTheorem sillyfun1_odd: forall n: nat,\n  sillyfun1 n = true -> oddb n = true.\nProof. \n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  - apply eqb_true in Heqe3. rewrite -> Heqe3. reflexivity.\n  - destruct (n =? 5) eqn:Heqe5.\n    + apply eqb_true in Heqe5. rewrite -> Heqe5. reflexivity.\n    + discriminate.\nQed.\n\n(* Page 109 Exercise *)\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. destruct b eqn:eb.\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:ffalse.\n    + destruct (f true) eqn:ftrue.\n      * rewrite -> ftrue. reflexivity.\n      * rewrite -> ffalse. reflexivity.\n    + rewrite -> ffalse. rewrite -> ffalse.\n      reflexivity.\nQed.\n\n(* Exercise Ends *)\n\n(* Page 110 Exercise *)\n\nTheorem eqb_sym:\n  forall n m: nat, (n =? m) = (m =? n).\nProof.\n  intros n. induction n as [| n' IHn'].\n  - intros m. destruct m as [| m'].\n    + reflexivity.\n    + reflexivity.\n  - intros m. destruct m as [| m'].\n    + reflexivity.\n    + simpl. apply IHn'.\nQed.\n\nTheorem eqb_trans:\n  forall n m p,\n  n =? m = true -> m =? p = true -> n =? p = true.\nProof.\n  intros n m p eq1 eq2.\n  apply eqb_true in eq1. apply eqb_true in eq2.\n  rewrite -> eq1. rewrite -> eq2. rewrite <- eqb_refl.\n  reflexivity.\nQed.\n\nTheorem split_combine:\n  forall (X Y: Type) (l1: list X) (l2: list Y),\n  length l1 = length l2 -> \n  split (combine l1 l2) = (l1, l2).\nProof.\n  intros X Y. intros l1.\n  induction l1 as [| x1 l1' IHl1'].\n  - intros l2. destruct l2 as [| x2 l2].\n    + reflexivity.\n    + discriminate.\n  - intros l2. destruct l2 as [| x2 l2].\n    + discriminate.\n    + simpl.\n      intros eq. inversion eq. apply IHl1' in H0.\n      rewrite -> H0. 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.\n  induction l as [| n l' IHl'].\n  - intros lf. discriminate.\n  - intros lf. destruct (test n) eqn:En.\n    + simpl. rewrite -> En.\n      intros eq. inversion eq.\n      rewrite -> H0 in En. apply En.\n    + simpl. rewrite -> En. \n      intros eq. apply IHl' in eq.\n      apply eq.\nQed.\n\nFixpoint forallb {X: Type} (test: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => true\n  | x :: t => if (test x) then (forallb test t) else false\n  end.\n\nFixpoint existsb {X: Type} (test: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => false\n  | x :: t => if (test x) then true else (existsb test t)\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\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 negb (map test l)).\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\nTheorem existsb_existsb':\n  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 [| n l' IHl'].\n  - simpl. unfold existsb'. reflexivity.\n  - simpl. destruct (test n) eqn:En.\n    + unfold existsb'. simpl. rewrite -> En.\n      simpl. reflexivity.\n    + rewrite -> IHl'. unfold existsb'. \n      simpl. rewrite -> En. simpl. reflexivity.\nQed.\n  \n  \n(* Exercise Ends *)", "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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.7524187790226957}}
{"text": "Require Import NArith.\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrlib.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\nOpen Scope N_scope.\n\n(** Some [N]versions of standard ssreflect operations. *)\nDefinition iotaN (m n:N) : seq N :=\n N.peano_rect _ (fun _=>[::]) (fun n r m=> [:: m & r (N.succ m)]) n m.\n\nLemma iotaN_succ x n:\n iotaN x (N.succ n) = x :: iotaN (N.succ x) n.\nProof. by rewrite /iotaN N.peano_rect_succ. Qed.\n\nLemma iotaN_iota x n:\n iotaN x n = map n2N (iota (N2n x) (N2n n)).\nProof.\nelim/N.peano_ind: n x => //= n IH x.\nrewrite N2Nat.inj_succ /= iotaN_succ N2n2N; f_equal.\nby rewrite (IH (N.succ x)) N2Nat.inj_succ.\nQed.\n\nLemma mem_iotaN m n x:\n  (x \\in iotaN m n) <-> (m <= x < m+n).\nProof.\nrewrite iotaN_iota; split.\n move/mapP => [y []]; rewrite mem_iota; move => [/andP[]].\n rewrite -{1 2}[y]n2N2n N2n_le -plusE -N2Nat.inj_add N2n_lt.\n by move=> H1 H2 ->; split.\nmove=> [H1 H2]. apply/mapP.\nexists (N2n x); last by rewrite N2n2N.\nrewrite mem_iota; apply/andP; split.\n by rewrite -N2n_le.\nby rewrite -plusE -N2Nat.inj_add -N2n_lt.\nQed.\n\n\n\nDefinition nseqN {A} : N -> A -> seq A :=\n N.peano_rect _ (fun _=>[::]) (fun n r x=> x::r x).\n\nLemma nseqN_nseq {A} n (x:A) : nseqN n x = nseq (N2n n) x.\nProof.\nelim/N.peano_ind: n => //= n.\nby rewrite /nseqN /= N.peano_rect_succ N2Nat.inj_succ /= => ->. \nQed.\n\nLemma map_nseqN {A B} (f:A -> B) (x:A) n:\n  [seq f i | i <- nseqN n x] = nseqN n (f x).\nProof. by rewrite nseqN_nseq map_nseq nseqN_nseq. Qed.\n\n\n\n\nFixpoint sizeN {A} (s: seq A) : N :=\n if s is x::xs then N.succ (sizeN xs) else 0.\n\nLemma size_sizeN {A}: forall (s: seq A),\n size s = N.to_nat (sizeN s).\nProof.\nelim => //= x xs IH.\nby rewrite N2Nat.inj_succ; f_equal.\nQed.\n\nLemma sizeN_size {A}: forall (s: seq A),\n sizeN s = N.of_nat (size s).\nProof. by move=> s; rewrite size_sizeN N2Nat.id. Qed.\n\nCorollary sizeN_map {A B} (f: A -> B) (m: list A) :\n  sizeN (map f m) = sizeN m.\nProof. by rewrite !sizeN_size size_map. Qed.\n\nCorollary sizeN_rev {A} (m: list A) :\n  sizeN (rev m) = sizeN m.\nProof. by rewrite !sizeN_size size_rev. Qed.\n\nCorollary sizeN_app {A} (m m': list A) :\n  sizeN (m ++ m') = sizeN m + sizeN m'.\nProof. by rewrite !sizeN_size size_cat Nat2N.inj_add. Qed.\n\nCorollary sizeN_rcons {A} (m: list A) a :\n  sizeN (rcons m a) = sizeN m + 1.\nProof.\nrewrite !sizeN_size size_rcons -[1]/(n2N 1) -Nat2N.inj_add.\nby rewrite plusE addn1.\nQed.\n\nLemma sizeN_iotaN m n :\n  sizeN (iotaN m n) = n.\nProof. by rewrite sizeN_size iotaN_iota size_map size_iota N2n2N. Qed.\n\n\n\nFixpoint nthN {A} (dfl: A) (s: seq A) (n: N) : A :=\n if s is x::xs\n then if n is N0 then x else nthN dfl xs (N.pred n)\n else dfl.\n\nLemma nth_nthN: forall A (dfl:A) n xs,\n nth dfl xs n = nthN dfl xs (N.of_nat n).\nProof.\nmove=> A d; elim => [|n IH] [|x xs] //=.\nby rewrite IH pospred_ofsuccnat; f_equal.\nQed.\n\nLemma nthN_nth: forall A (dfl:A) xs n,\n nthN dfl xs n = nth dfl xs (N.to_nat n).\nProof. by move=> A d xs n; rewrite nth_nthN N2Nat.id. Qed.\n\nCorollary nth_rcons_last {A} (d: A) m a :\n  nthN d (rcons m a) (sizeN m) = a.\nProof.\nrewrite nthN_nth -size_sizeN nth_rcons.\ncase: (ifP _). \n move=> /ltP H; omega.\nby rewrite eq_refl.\nQed.\n\nLemma nthN_cat {A} (d: A) m m' n :\n  nthN d (m ++ m') n\n  = (if n <? sizeN m then nthN d m n else nthN d m' (n - sizeN m)).\nProof.\nrewrite !nthN_nth nth_cat !sizeN_size N2Nat.inj_sub /= n2N2n.\nhave ->: (N2n n < size m)%N = (n <? n2N (size m)).\n rewrite -{1}[size m]n2N2n.\n by apply/idP/idP; rewrite -N2n_lt -N.ltb_lt.\nby rewrite minusE.\nQed.\n\n\n\n\n\n\n\nDefinition takeN {A} (n:N) : seq A -> seq A :=\n N.peano_rect _ (fun _=>[::]) (fun n r s=> if s is x::xs\n                                           then x::r xs\n                                           else [::]) n.\n\nLemma takeN_nil A: forall pos,\n takeN pos [::] = @nil A.\nProof.\nelim/N.peano_ind => //=.\nby move=> n IH; rewrite /takeN N.peano_rect_succ.\nQed.\n\nLemma takeN_0 A: forall (s: seq A),\n takeN 0 s = [::].\nProof. by move=> s; rewrite /takeN. Qed.\n\nLemma takeN_cons A: forall p x (xs: seq A),\n takeN (Npos p) (x::xs) = x::takeN (Npred (Npos p)) xs.\nProof.\nmove => p x xs.\nby rewrite /takeN -N.succ_pos_pred N.peano_rect_succ N.pred_succ.\nQed.\n\nLemma take_takeN: forall {A} (xs: seq A) n,\n take n xs = takeN (N.of_nat n) xs.\nProof.\nmove=> A; elim => //.\n by move=> n; rewrite /= takeN_nil.\nmove=> x xs IH [|n] //.\nrewrite takeN_cons /= IH; f_equal; f_equal.\nby rewrite pospred_ofsuccnat.\nQed.\n\nLemma takeN_take: forall {A} n (xs: seq A),\n takeN n xs = take (N.to_nat n) xs.\nProof. by move=> A n xs; rewrite take_takeN N2Nat.id. Qed.\n\nLemma takeN_all {A} (m: list A) n :\n  sizeN m <= n -> takeN n m = m.\nProof.\n  revert m; elim n using N.peano_ind; clear.\n  intros [ | a m ]. reflexivity. simpl. Psatz.lia.\n  intros n IH m LE.\n  unfold takeN. rewrite N.peano_rect_succ. fold (@takeN A n).\n  destruct m as [ | a m ]. reflexivity.\n  f_equal. apply IH. simpl in LE. Psatz.lia.\nQed.\n\nLemma takeN_map_nthN {A} x (s: seq A) n:\n(n <= sizeN s) -> takeN n s = map (nthN x s) (iotaN 0 n).\nProof.\nrewrite sizeN_size takeN_take iotaN_iota -map_comp.\nhave E: nthN x s \\o n2N =1 nth x s by move=> y /=; rewrite nth_nthN.\nmove=> H; rewrite (eq_map E) (take_map_nth x) //=.\nby rewrite size_sizeN -N2n_le sizeN_size.\nQed.\n\n\n\n\n\nDefinition dropN {A} (n:N) : seq A -> seq A :=\n N.peano_rect _ id (fun n r s=> if s is x::xs\n                                then r xs\n                                else [::]) n.\n\nLemma dropN_nil A: forall pos,\n dropN pos [::] = @nil A.\nProof.\nelim/N.peano_ind => //=.\nby move=> n IH; rewrite /dropN N.peano_rect_succ.\nQed.\n\nLemma dropN_0 A: forall (s: seq A),\n dropN 0 s = s.\nProof. by move=> s; rewrite /dropN. Qed.\n\nLemma dropN_succ_cons A: forall n x (xs: seq A),\n dropN (N.succ n) (x::xs) = dropN n xs.\nProof. by move=> n x xs; rewrite /dropN N.peano_rect_succ. Qed.\n\nLemma dropN_pos_cons A: forall p x (xs: seq A),\n dropN (Npos p) (x::xs) = dropN (Npred (Npos p)) xs.\nProof.\nmove=> p x xs.\nby rewrite /dropN -N.succ_pos_pred N.peano_rect_succ N.pred_succ.\nQed.\n\nLemma drop_dropN: forall A (xs: seq A) n,\n drop n xs = dropN (N.of_nat n) xs.\nProof.\nmove=> A; elim => //.\n by move=> n; rewrite dropN_nil.\nmove=> x xs IH [|n] //. \nby rewrite [drop _ _]/= IH Nat2N.inj_succ dropN_succ_cons.\nQed.\n\nLemma dropN_drop: forall A (xs: seq A) n,\n dropN n xs = drop (N.to_nat n) xs.\nProof. by move=> A n xs; rewrite drop_dropN N2Nat.id. Qed.\n\nLemma dropN_sizeN_cat: forall T n (s1 s2: seq T),\n    sizeN s1 = n -> dropN n (s1++s2) = s2.\nProof.\nmove=> T n s1 s2.\nrewrite sizeN_size => H.\nmove/(f_equal N.to_nat): H; rewrite Nat2N.id => H.\nby rewrite dropN_drop drop_size_cat.\nQed.\n\nLemma dropN_add {A} (m: list A) n n' :\n  dropN (n + n') m = dropN n (dropN n' m).\nProof. by rewrite !dropN_drop N2Nat.inj_add drop_add. Qed.\n\nLemma dropN_is_nil {A} (m: list A) n :\n  dropN n m = nil -> sizeN m <= n.\nProof. by rewrite dropN_drop => /drop_is_nil; rewrite size_sizeN -N2n_le. Qed.\n\n\n\n\n\nDefinition takeN_dflt {A} (dflt: A) (n:N) : seq A -> seq A :=\n N.peano_rect _ (fun _=>[::]) (fun n r s=> if s is x::xs\n                                           then x::r xs\n                                           else dflt:: r [::]) n.\n\nLemma take_takeN_dflt: forall A (dfl:A) n s,\n take_dflt dfl n s = takeN_dflt dfl (N.of_nat n) s.\nProof.\nby move=> A d; elim => // n IH [|x xs];\nrewrite Nat2N.inj_succ /takeN_dflt N.peano_rect_succ /= IH.\nQed.\n\nLemma takeN_take_dflt: forall A (dfl:A) n s,\n takeN_dflt dfl n s = take_dflt dfl (N.to_nat n) s.\nProof. by move=> A d n s; rewrite take_takeN_dflt N2Nat.id. Qed.\n\nLemma takeN_dflt_catl: forall n (T : Type) (s1 : seq T),\n    (n <= sizeN s1) -> forall d s2, takeN_dflt d n (s1 ++ s2) = takeN_dflt d n s1.\nProof.\nmove=> n T s1 H d s2.\nrewrite !takeN_take_dflt take_dflt_catl //.\nby apply/leP; rewrite Compare_dec.nat_compare_le size_sizeN Nat2N.inj_compare !N2Nat.id.\nQed.\n\nLemma takeN_dflt_eqsize: forall T d n (s : seq T),\n    (sizeN s = n) -> takeN_dflt d n s = s.\nProof.\nmove=> T d n s; rewrite sizeN_size => H.\nrewrite takeN_take_dflt take_dflt_eqsize //.\nby apply Nat2N.inj; rewrite H N2Nat.id.\nQed.\n\nLemma size_takeN_dflt: forall A (dfl:A) n s,\n size (takeN_dflt dfl n s) = N.to_nat n.\nProof.\nmove=> A dfl; elim/N.peano_ind => //=.\nmove=> n IH [|x xs].\n rewrite /takeN_dflt N.peano_rect_succ Nnat.N2Nat.inj_succ /=.\n by f_equal; apply IH.\nrewrite /takeN_dflt N.peano_rect_succ Nnat.N2Nat.inj_succ /=.\nby rewrite IH.\nQed.\n\nLemma sizeN_takeN_dflt: forall A (dfl:A) n s,\n sizeN (takeN_dflt dfl n s) = n.\nProof.\nmove=> A d n s; apply N2Nat.inj.\nby rewrite sizeN_size size_takeN_dflt Nat2N.id.\nQed.\n\nLemma takeN_dflt_all {A} d (m: list A) :\n  takeN_dflt d (sizeN m) m = m.\nProof.\n  elim m; clear.\n  reflexivity.\n  intros a m IH.\n  unfold takeN_dflt. simpl.\n  rewrite N.peano_rect_succ.\n  f_equal. apply IH.\nQed.\n\nLemma takeN_dflt_split {A} (d: A) s n:\n  sizeN s <= n -> takeN_dflt d n s = s ++ (nseqN (n-sizeN s) d).\nProof.\nrewrite takeN_take_dflt take_dflt_split sizeN_size nseqN_nseq => Hsize.\nrewrite take_oversize; last first.\n by move: Hsize; rewrite N2n_le n2N2n.\nby rewrite N2Nat.inj_sub n2N2n.\nQed.\n\nLemma nth_takeN_dflt A (d:A) bs n x:\n nth d (takeN_dflt d n bs) x = if (x < N2n n)%N\n                               then nth d bs x\n                               else d.\nProof. by rewrite takeN_take_dflt nth_take_dflt. Qed.\n\n\n\n\nFixpoint onthN {A} (s: seq A) (n: N) : option A :=\n if s is x::xs\n then if n is N0 then Some x else onthN xs (N.pred n)\n else None.\n\nLemma onth_onthN {A}: forall (s: seq A) n,\n onth s n = onthN s (N.of_nat n).\nProof.\nelim => //= x xs IH [|n] //=.\nby rewrite IH pospred_ofsuccnat; f_equal.\nQed.\n\nLemma onthN_onth: forall A (s: seq A) n,\n onthN s n = onth s (N.to_nat n).\nProof. by move=> A s n; rewrite onth_onthN N2Nat.id. Qed.\n\nLemma onthN_isS {A} d (s: seq A) n v:\n  onthN s n = Some v <-> (n < sizeN s) /\\ nthN d s n = v.\nProof.\nrewrite onthN_onth (onth_isS d) sizeN_size nthN_nth.\nsplit; move => [H1 H2]; split => //.\n by move: H1; rewrite size_sizeN N2n_lt N2n2N.\nby rewrite size_sizeN -N2n_lt sizeN_size.\nQed.\n\nLemma onthN_isS_cat {A} (x y: seq A) n z :\n  onthN x n = Some z ->\n  onthN (x ++ y) n = Some z.\nProof. by rewrite !onthN_onth => H; apply onth_isS_cat. Qed.\n\nLemma map_onthN_iotaN {A} (m: list A) n :\n  forall x,\n    (x + n <= sizeN m) ->\n    map (onthN m) (iotaN x n) = map (@Some _) (take (N2n n) (drop (N2n x) m)).\nProof.\nmove=> x Hsize.\nrewrite -map_onth_iota; last first.\n by move: Hsize; rewrite N2n_le -size_sizeN N2Nat.inj_add plusE => Hsize.\nrewrite iotaN_iota.\nrewrite -map_comp /=; apply eq_map.\nby move=> a /=; rewrite onth_onthN.\nQed.\n\n\n\nDefinition updprefAtN {A} : N -> seq A -> seq A -> seq A :=\n (N.peano_rect _ (fun orig new => updpref orig new)\n               (fun n' r orig new => if orig is x::xs\n                                     then x::r xs new\n                                     else [::])).\n\nLemma updprefAtN_updprefAt {A} n (orig new: seq A):\n updprefAtN n orig new = updprefAt (N2n n) orig new.\nProof.\nelim/N.peano_ind: n orig new => //= n IH [|x xs] new.\n by rewrite /updprefAtN N.peano_rect_succ Nnat.N2Nat.inj_succ /=.\nby rewrite /updprefAtN N.peano_rect_succ Nnat.N2Nat.inj_succ /= -IH.\nQed.\n\nLemma updprefAt_updprefAtN {A} n (orig new: seq A):\n updprefAt n orig new = updprefAtN (n2N n) orig new.\nProof.\nelim: n orig new => // n IH [|x xs] new.\n by rewrite /updprefAtN Nat2N.inj_succ N.peano_rect_succ.\nby rewrite /updprefAtN Nat2N.inj_succ N.peano_rect_succ /= IH.\nQed.\n\nLemma updprefAtN_E {A} n (orig new: seq A):\n  updprefAtN n orig new = takeN n orig ++ updpref (dropN n orig) new.\nProof. by rewrite updprefAtN_updprefAt updprefAtE !takeN_take dropN_drop. Qed.\n\nLemma sizeN_updprefAtN {A} n (orig new: seq A):\n  sizeN (updprefAtN n orig new) = sizeN orig.\nProof.\nby rewrite updprefAtN_updprefAt !sizeN_size size_updprefAt.\nQed.\n\n\n(** selects the nth element with a given [width] *)\nDefinition nthN_width {A} (width:N) (s:seq A) (n:N) : seq A :=\n (N.peano_rect _ (takeN width) (fun n r s=> r (dropN width s)) n) s.\n\n(** selects the nth double element with a given [width] *)\nDefinition nthN_dwidth {A} (width:N) (s:seq A) (n:N) : seq A :=\n (N.peano_rect _ (takeN (2*width)) (fun n r s=> r (dropN width s)) n) s.\n\n(*\n(** updates the nth element with a given [width] *)\nDefinition updN_width {A} (width:N) (x:seq A) (s:seq A) (n:N) : seq A :=\n (N.peano_rect _ (fun l => x++dropN width l)\n               (fun n r s=> takeN width s ++ r (dropN width s)) n) s.\n\n(** upd the nth double element with a given [width] *)\nDefinition updN_dwidth {A} (width:N) (x:seq A) (s:seq A) (n:N) : seq A :=\n (N.peano_rect _ (fun l => x++dropN (2*width) l)\n               (fun n r s=> takeN width s ++ r (dropN width s)) n) s.\n*)\n\n\n\n\n", "meta": {"author": "haslab", "repo": "CircGen", "sha": "74a835abfc0477f51d6ee72db8f66caa6a544809", "save_path": "github-repos/coq/haslab-CircGen", "path": "github-repos/coq/haslab-CircGen/CircGen-74a835abfc0477f51d6ee72db8f66caa6a544809/cdg/lib/seqN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7524187774555648}}
{"text": "Require Export P07.\n\nTheorem snoc_rev_relation : forall n : nat, forall l : natlist,\n      rev (snoc l n) = n :: rev l.\nProof.\n  intros n l. induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl. reflexivity.\nQed.\n\n(** Hint: You may need to first state and prove some lemma about snoc and rev. *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l.\n  - reflexivity.\n  - simpl. rewrite -> snoc_rev_relation. rewrite -> IHl. 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/P08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7524187731293885}}
{"text": "\n(***************************** LIFLF - TPX ************************************)\n(************* Evaluation pratique en temps limité : 30' **********************)\n(******************************************************************************)\n\nRequire Import List.\nImport ListNotations.\n\n(***************************** fonction mystère *******************************)\n\n(* On donne le corps suivant d'une fonction\n\n  match ls with\n   | []     => None\n   | x::xs  => Some x\n  end.\n*)\n\n(* EXERCICE : Définir la fonction \"mystere\" avec le corps donné ci-dessus. *)\n(*            Donner son type *)\n(*            Expliquer simplement ce que fait cette fonction. *)\n\nDefinition mystere (ls : list nat) : option nat :=\nmatch ls with\n   | []     => None\n   | x::xs  => Some x\n  end.\n\n(***************************** \"take\" *****************************************)\n\n(* EXERCICE : définir \"take n ls\" qui renvoie le préfixe de ls de longueur n\n   EXEMPLE  : voir les tests unitaires ci-dessous\n*)\n\n(* nombre element liste list nb elem concat list ++ :: n-1*)\n\nFixpoint take (n: nat) (ls: list nat) : list nat :=\n  match ls with\n  | [] => []\n  | n'::l' => if (Nat.eqb n 0) then [] else n'::[] ++ (take (n-1) l')\n  end.\n\nGoal  take 0 [1;2;3;4;5] = [].\nsimpl.\nreflexivity.\nQed.\n\nGoal  take 6 [1;2;3;4;5] = [1;2;3;4;5].\nsimpl.\nreflexivity.\nQed.\n\nGoal  take 3 [1;2;3;4;5] = [1;2;3].\nsimpl.\nreflexivity.\nQed.\n\nPrint app.\n\n(***************************** \"drop\" *****************************************)\n\n(* EXERCICE : définir \"drop n ls\" qui renvoie le suffixe de ls privée de ses n \n              premiers éléments\n   EXEMPLE  : voir les tests unitaires ci-dessous\n*)\n\n(* enlever element liste list drop elements number list*)\n\nFixpoint drop (n: nat) (l: list nat) : list nat :=\n  match l with\n  | [] => []\n  | n'::l' => if (Nat.eqb n 0) then l else drop (n-1) l'\n  end.\n\n\nGoal  drop 0 [1;2;3;4;5] = [1;2;3;4;5].\nsimpl.\nreflexivity.\nQed.\n\nGoal  drop 6 [1;2;3;4;5] = [].\nsimpl.\nreflexivity.\nQed.\n\nGoal  drop 3 [1;2;3;4;5] = [4;5].\nsimpl.\nreflexivity.\nQed.\n\n(*********************** explication d'énoncé *********************************)\n\n\n(* EXERCICE : On donne l'énoncé suivant \"a_expliquer\". \n              Expliquer en français cette propriété\n*)\nLemma a_expliquer : forall n la, (fun p => app (fst p) (snd p) ) (take n la, drop n la) = la. \nAdmitted.\n\n(* c'est le theoreme qui verifie que pour tout entier n et tout liste la si on applique \ntake et drop en parallele sur la meme liste, le resultat de leurs deux liste concatenes\nrevient a la liste de depart la*)\n\nCompute (take 3 [1;2;3;4;5;6]).\nCompute (drop 3 [1;2;3;4;5;6]).\nCompute (take 3 [1;2;3;4;5;6]) ++ (drop 3 [1;2;3;4;5;6]).\nCompute (a_expliquer 3 [1;2;3;4;5;6]).\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/liflf_B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7523778142757288}}
{"text": "(* begin hide *)\nFrom mathcomp\n  Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq bigop path.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* end hide *)\n(** One important aspect of Coq's logic is the special status given to\n_computation_: while some systems require one to apply explicit\ndeductive steps to show that two given terms are equal, Coq's logic\nconsiders any two terms that _evaluate_ to the same result to be equal\nautomatically, without the need for additional reasoning.\n\nWithout getting into too much detail, we can illustrate this idea with\nsome simple examples. Russell and Whitehead's seminal _Principia\nMathematica_ had to develop #<a\nhref=\"http://quod.lib.umich.edu/cgi/t/text/pageviewer-idx?c=umhistmath&cc=umhistmath&idno=aat3201.0001.001&frm=frameset&view=image&seq=401\">hundreds\nof pages</a># of foundational mathematics before being able to prove\nthat [1 + 1 = 2]. In contrast, here's what this proof looks like in\nCoq: *)\n\nDefinition one_plus_one : 1 + 1 = 2 := erefl.\n\n(** [erefl] is the only constructor of the [eq] type; its type,\n[forall A (a : A), a = a], tells us that we can use it to prove that\ngiven term [a] is equal to itself. Coq accepts [one_plus_one] as a\nvalid proof because, even though the two sides of the equation are not\nsyntactically the same, it is able to use the definition of [+] to\ncompute the left-hand side and check that the result is the same as\nthe right-hand side. This also works for some statements with\nvariables in them, for instance *)\n\nDefinition zero_plus_n n : 0 + n = n := erefl.\n\n(** The same principle applies here: [+] is defined by case analysis\non its first argument, and doesn't even need to inspect the second\none. Since the first argument on the left-hand side is a constructor\n([0]), Coq can reduce the expression and conclude that both sides are\nequal.\n\nUnfortunately, not every equality is a direct consequence of\ncomputation. For example, this proof attempt is rejected: *)\n\nFail Definition n_plus_zero n : n + 0 = n := erefl.\n\n(** What happened here? As mentioned before, [+] is defined by case\nanalysis on the first argument; since the first argument of the\nleft-hand side doesn't start with a constructor, Coq doesn't know how\nto compute there. As it turns out, one actually needs an inductive\nargument to prove this result, which might end up looking like this,\nif we were to check the proof term that Coq produces: *)\n\nFixpoint n_plus_zero n : n + 0 = n :=\n  match n with\n  | 0 => erefl\n  | n.+1 => let: erefl := n_plus_zero n in erefl\n  end.\n\n(** It seems that, although interesting, computation inside Coq isn't\nof much use when proving something. Or is it?\n\nIn this post, I will show how computation in Coq can be used to write\ncertified automation tactics with a technique known as _proof by\nreflection_. Reflection is extensively used in Coq and in other proof\nassistants as well; it is at the core of powerful automation tactics\nsuch as [ring], and played an important role in the formalization of\nthe #<a\nhref=\"http://en.wikipedia.org/wiki/Four_color_theorem\">Four-color\ntheorem</a>#. As a matter of fact, the name #<a\nhref=\"http://ssr.msr-inria.inria.fr/\">Ssreflect</a># stands for\n_small-scale reflection_, due to the library's pervasive use of\nreflection and computation.\n\nLet's see how reflection works by means of a basic example: a tactic\nfor checking equalities between simple expressions involving natural\nnumbers.\n\n** Arithmetic with reflection\n\nImagine that we were in the middle of a proof and needed to show that\ntwo natural numbers are equal: *)\n\nLemma lem n m p : (n + m) * p = p * m + p * n.\n\n(** [ring] is powerful enough to solve this goal by itself, but just\nfor the sake of the example, suppose that we had to prove it by\nhand. We could write something like *)\n\nProof. by rewrite mulnDl (mulnC n) (mulnC m) addnC. Qed.\n\n(** This was not terribly complicated, but there's certainly room for\nimprovement. In a paper proof, a mathematician would probably assume\nthat the reader is capable of verifying this result on their own,\nwithout any additional detail. But how exactly would the reader\nproceed?\n\nIn the case of the simple arithmetic expression above, it suffices to\napply the distributivity law as long as possible, until both\nexpressions become a sum of monomials. Then, thanks to associativity\nand commutativity, we just have to reorder the factors and terms and\ncheck that both sides of the equation match.\n\nThe idea of proof by reflection is to reduce a the validity of a\nlogical statement to a _symbolic computation_, usually by proving a\ntheorem of the form [thm : b = true -> P] with [b : bool]. If [b] can\nbe computed explicitly and reduces to [true], then Coq recognizes\n[erefl] as a proof of [b = true], which means that [thm erefl] becomes\na proof of [P].\n\nTo make things concrete, let's go back to our example. The idea that\nwe described above for checking whether two numbers are equal can be\nused whenever we have expressions involving addition, multiplication,\nand variables. We will define a Coq data type for representing such\nexpressions, as we will need to compute with them: *)\n\nInductive expr :=\n| Var of nat\n| Add of expr & expr\n| Mul of expr & expr.\n\n(** Variables are represented by natural numbers using the [Var]\nconstructor, and [Add] and [Mul] can be used to combine\nexpressions. The following term, for instance, represents the\nexpression [n * (m + n)]: *)\n\nExample expr_ex :=\n  Mul (Var 0) (Add (Var 1) (Var 0)).\n\n(** where [Var 0] and [Var 1] denote [n] and [m], respectively.\n\nIf we are given a function [vals] assigning variables to numbers, we\ncan compute the value of an expression with a simple recursive\nfunction: *)\n\nFixpoint nat_of_expr vals e :=\n  match e with\n  | Var v => vals v\n  | Add e1 e2 => nat_of_expr vals e1 + nat_of_expr vals e2\n  | Mul e1 e2 => nat_of_expr vals e1 * nat_of_expr vals e2\n  end.\n\n(** Now, since every expression of that form can be written as a sum\nof monomials, we can define a function for converting an [expr] to\nthat form: *)\n\nFixpoint monoms e :=\n  match e with\n  | Var v => [:: [:: v] ]\n  | Add e1 e2 => monoms e1 ++ monoms e2\n  | Mul e1 e2 => [seq m1 ++ m2 | m1 <- monoms e1, m2 <- monoms e2]\n  end.\n\n(** Here, each monomial is represented by a list enumerating all\nvariables that occur in it, counting their multiplicities. Hence, a\nsum of monomials is represented as a list of lists. For example,\nhere's the result of normalizing [expr_ex]: *)\n\nExample monoms_expr_ex :\n  monoms expr_ex = [:: [:: 0; 1]; [:: 0; 0]].\nProof. by []. Qed.\n\n(** To prove that [monoms] has the intended behavior, we show that the\nvalue of an expression is preserved by it. By using the big operations\n[\\sum] and [\\prod] from the MathComp library, we can compute the value\nof a sum of monomials very easily: *)\n\nLemma monomsE vals e :\n  nat_of_expr vals e = \\sum_(m <- monoms e) \\prod_(v <- m) vals v.\nProof.\nelim: e=> [v|e1 IH1 e2 IH2|e1 IH1 e2 IH2] /=.\n- by rewrite 2!big_seq1.\n- by rewrite big_cat IH1 IH2.\nrewrite {}IH1 {}IH2 big_distrlr /=.\nelim: (monoms e1) (monoms e2)=> [|v m1 IH] m2 /=; first by rewrite 2!big_nil.\nrewrite big_cons big_cat /= IH; congr addn.\nby rewrite big_map; apply/eq_big=> //= m3 _; rewrite big_cat.\nQed.\n\n(** Hence, to check that two expressions are equivalent, it suffices\nto compare the results of [monoms], modulo the ordering. We can do\nthis by sorting the variable names on each monomial and then testing\nwhether one list of monomials is a permutation of the other: *)\n\nDefinition normalize := map (sort leq) \\o monoms.\n\nLemma normalizeE vals e :\n  nat_of_expr vals e = \\sum_(m <- normalize e) \\prod_(v <- m) vals v.\nProof.\nrewrite monomsE /normalize /=; elim: (monoms e)=> [|m ms IH] /=.\n  by rewrite big_nil.\nrewrite 2!big_cons IH; congr addn.\nby apply/perm_big; rewrite perm_sym perm_sort.\nQed.\n\nDefinition expr_eq e1 e2 := perm_eq (normalize e1) (normalize e2).\n\nLemma expr_eqP vals e1 e2 :\n  expr_eq e1 e2 ->\n  nat_of_expr vals e1 = nat_of_expr vals e2.\nProof. rewrite 2!normalizeE; exact/perm_big. Qed.\n\n(** To see how this lemma works, let's revisit our original\nexample. Here's a new proof that uses [expr_eqP]: *)\n\nLemma lem' n m p : (n + m) * p = p * m + p * n.\nProof.\nexact: (@expr_eqP (nth 0 [:: n; m; p])\n                  (Mul (Add (Var 0) (Var 1)) (Var 2))\n                  (Add (Mul (Var 2) (Var 1)) (Mul (Var 2) (Var 0)))\n                  erefl).\nQed.\n\n(** The first argument to our lemma assigns \"real\" variables to\nvariable numbers: [0] corresponds to [n] (the first element of the\nlist), [1] to [m], and [2] to [p]. The second and third argument are\nsymbolic representations of the left and right-hand sides of our\nequation. The fourth argument is the most interesting one: the\n[expr_eq] was defined as a _boolean_ function that returns [true] when\nits two arguments are equivalent expressions. As we've seen above,\nthis means that whenever [expr_eq e1 e2] computes to [true], [erefl]\nis a valid proof of it. Finally, when Coq tries to check whether the\nconclusion of [expr_eqP] can be used on our goal, it computes\n[nat_of_expr] on both sides, realizing that the conclusion and the\ngoal are exactly the same. For instance: *)\n\nLemma expr_eval n m p :\n  nat_of_expr (nth 0 [:: n; m; p]) (Mul (Add (Var 0) (Var 1)) (Var 2))\n  = (n + m) * p.\nProof. reflexivity. Qed.\n\n(** Of course, [expr_eqP] doesn't force its first argument to always\nreturn actual Coq variables, so it can be applied even in some cases\nwhere the expressions contain other operators besides [+] and [*]: *)\n\nLemma lem'' n m : 2 ^ n * m = m * 2 ^ n.\nProof.\nexact: (@expr_eqP (nth 0 [:: 2 ^ n; m])\n                  (Mul (Var 0) (Var 1)) (Mul (Var 1) (Var 0))\n                  erefl).\nQed.\n\n(** At this point, it may seem that we haven't gained much from using\n[expr_eqP], since the second proof of our example was much bigger than\nthe first one. This is just an illusion, however, as the proof term\nproduced on the first case is actually quite big:\n\n[[\nlem =\nfun n m p : nat =>\n(fun _evar_0_ : n * p + m * p = p * m + p * n =>\n eq_ind_r (eq^~ (p * m + p * n)) _evar_0_ (mulnDl n m p))\n  ((fun _evar_0_ : p * n + m * p = p * m + p * n =>\n    eq_ind_r\n      (fun _pattern_value_ : nat => _pattern_value_ + m * p = p * m + p * n)\n      _evar_0_ (mulnC n p))\n     ((fun _evar_0_ : p * n + p * m = p * m + p * n =>\n       eq_ind_r\n         (fun _pattern_value_ : nat =>\n          p * n + _pattern_value_ = p * m + p * n) _evar_0_\n         (mulnC m p))\n        ((fun _evar_0_ : p * m + p * n = p * m + p * n =>\n          eq_ind_r (eq^~ (p * m + p * n)) _evar_0_ (addnC (p * n) (p * m)))\n           (erefl (p * m + p * n)))))\n     : forall n m p : nat, (n + m) * p = p * m + p * n\n]]\n\nBy using reflection, we were able to transform the explicit reasoning\nsteps of the first proof into implicit computation that is carried out\nby the proof assistant. And since proof terms have to be stored in\nmemory or included into the compiled [vo] file, it is good to make\nthem smaller if we can.\n\nNevertheless, even with a smaller proof term, having to manually type\nin that proof term is not very convenient. The problem is that Coq's\nunification engine is not smart enough to infer the symbolic form of\nan expression, forcing us to provide it ourselves. Fortunately, we can\nuse some code to fill in the missing bits.\n\n** Reification\n\nTo _reify_ something means to produce a representation of that object\nthat can be directly manipulated in computation. In our case, that\nobject is a Gallina expression of type [nat], and the representation\nwe are producing is a term of type [expr].\n\nReification is ubiquitous in proofs by reflection. The Coq standard\nlibrary comes with a #<a\nhref=\"https://coq.inria.fr/distrib/current/refman/Reference-Manual012.html##sec480\">plugin</a>#\nfor reifying formulas, but it is not general enough to accommodate our\nuse case. Therefore, we will program our own reification tactic in\nltac.\n\nWe will begin by writing a function that looks for a variable on a\nlist and returns its position. If the variable is not present, we add\nit to the end of the list and return the updated list as well: *)\n\nLtac intern vars e :=\n  let rec loop n vars' :=\n    match vars' with\n    | [::] =>\n      let vars'' := eval simpl in (rcons vars e) in\n      constr:((n, vars''))\n    | e :: ?vars'' => constr:((n, vars))\n    | _ :: ?vars'' => loop (S n) vars''\n    end in\n  loop 0 vars.\n\n(** Notice the call to [eval simpl] on the first branch of\n[loop]. Remember that in ltac everything is matched almost purely\nsyntactically, so we have to explicitly evaluate a term when we are\njust interested on its value, and not on how it is written.\n\nWe can now write a tactic for reifying an expression. [reify_expr]\ntakes two arguments: a list [vars] to be used with [intern] for\nreifying variables, plus the expression [e] to be reified. It returns\na pair [(e',vars')] contained the reified expression [e'] and an\nupdated variable list [vars']. *)\n\nLtac reify_expr vars e :=\n  match e with\n  | ?e1 + ?e2 =>\n    let r1 := reify_expr vars e1 in\n    match r1 with\n    | (?qe1, ?vars') =>\n      let r2 := reify_expr vars' e2 in\n      match r2 with\n      | (?qe2, ?vars'') => constr:((Add qe1 qe2, vars''))\n      end\n    end\n  | ?e1 * ?e2 =>\n    let r1 := reify_expr vars e1 in\n    match r1 with\n    | (?qe1, ?vars') =>\n      let r2 := reify_expr vars' e2 in\n      match r2 with\n      | (?qe2, ?vars'') => constr:((Mul qe1 qe2, vars''))\n      end\n    end\n  | _ =>\n    let r := intern vars e in\n    match r with\n    | (?n, ?vars') => constr:((Var n, vars'))\n    end\n  end.\n\n(** Again, because this is an ltac function, we can traverse our\nGallina expression syntactically, as if it were a data\nstructure. Notice how we thread though the updated variable lists\nafter each call; this is done to ensure that variables are named\nconsistently.\n\nFinally, using [reify_expr], we can write [solve_nat_eq], which\nreifies both sides of the equation on the goal and applies [expr_eqP]\nwith the appropriate arguments. *)\n\nLtac solve_nat_eq :=\n  match goal with\n  | |- ?e1 = ?e2 =>\n    let r1 := reify_expr (Nil nat) e1 in\n    match r1 with\n    | (?qe1, ?vm') =>\n      let r2 := reify_expr vm' e2 in\n      match r2 with\n      | (?qe2, ?vm'') => exact: (@expr_eqP (nth 0 vm'') qe1 qe2 erefl)\n      end\n    end\n  end.\n\n(** We can check that our tactic works on our original example: *)\n\nLemma lem''' n m p : (n + m) * p = p * m + p * n.\nProof. solve_nat_eq. Qed.\n\n(** With [solve_nat_eq], every equation of that form becomes very easy\nto solve, including cases where a human prover might have trouble at\nfirst sight! *)\n\nLemma complicated n m p r t :\n  (n + 2 ^ r * m) * (p + t) * (n + p)\n  = n * n * p + m * 2 ^ r * (p * n + p * t + t * n + p * p)\n  + n * (p * p + t * p + t * n).\nProof. solve_nat_eq. Qed.\n\n(** ** Summary\n\nWe have seen how we can use internal computation in Coq to write\npowerful tactics. Besides generating small proof terms, tactics that\nuse reflection have another important benefit: they are mostly written\nin Gallina, a typed language, and come with correctness proofs. This\ncontrasts with most custom tactics written in ltac, which tend to\nbreak quite often due to the lack of static guarantees (and to how\nunstructure the tactic language is). For [solve_nat_eq], we only had\nto write the reification engine in ltac, which results in a more\nmanageable code base.\n\nIf you want to learn more about reflection, Adam Chlipala's #<a\nhref=\"http://adam.chlipala.net/cpdt/\">CPDT</a># book has #<a\nhref=\"http://adam.chlipala.net/cpdt/html/Reflection.html\">an entire\nchapter</a># devoted to the subject, which I highly recommend. *)\n", "meta": {"author": "arthuraa", "repo": "poleiro", "sha": "c2f2159470872ac83d305b4a50fda8fccc89ae53", "save_path": "github-repos/coq/arthuraa-poleiro", "path": "github-repos/coq/arthuraa-poleiro/poleiro-c2f2159470872ac83d305b4a50fda8fccc89ae53/theories/Reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.9005297801113613, "lm_q1q2_score": 0.7523778133321958}}
{"text": "(* week-09_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(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\n(* ********** *)\n\n(* Exercise 1 *)\n\nInductive m22 : Type :=\n| M22 : nat -> nat -> nat -> nat -> m22.\n\nDefinition m22_add (x y : m22) : m22 :=\n  match x with\n  | M22 x11 x12\n        x21 x22 =>\n    match y with\n    | M22 y11 y12\n          y21 y22 =>\n      M22 (x11 + y11) (x12 + y12)\n          (x21 + y21) (x22 + y22)\n    end\n  end.\n\nDefinition m22_zero :=\n  M22 0 0\n      0 0.\n\nDefinition m22_one :=\n  M22 1 0\n      0 1.\n\n(* Part a: Definition 9 - Multiplication *)\n\nDefinition m22_mul (x y : m22) : m22 :=\n  match x with\n  | M22 x11 x12\n        x21 x22 =>\n    match y with\n    | M22 y11 y12\n          y21 y22 =>\n      M22 ((x11 * y11) + (x12 * y21)) ((x11 * y12) + (x12 * y22))\n          ((x21 * y11) + (x22 * y21)) ((x21 * y12) + (x22 * y22))\n    end\n  end.\n\n\n(* Part b: Proposition 10 - Associativity of matrix multiplication *)\n\nProposition proposition_10 :\n  forall (x y z : m22),\n    m22_mul x (m22_mul y z) = m22_mul (m22_mul x y) z.\nProof.\n  intros [x11 x12 x21 x22] [y11 y12 y21 y22] [z11 z12 z21 z22].\n  unfold m22_mul.\n  Search (_ * (_ + _)).\n  rewrite -> 8 Nat.mul_add_distr_l.\n  Search ((_ + _) * _).\n  rewrite -> 8 Nat.mul_add_distr_r.\n  Search (_ * (_ * _)).\n  rewrite -> 16 Nat.mul_assoc.\n  Search (_ + (_ + _ )).\n  rewrite -> (Nat.add_shuffle1 (x11 * y11 * z11)).\n  rewrite -> (Nat.add_shuffle1 (x11 * y11 * z12)).\n  rewrite -> (Nat.add_shuffle1 (x21 * y11 * z11)).\n  rewrite -> (Nat.add_shuffle1 (x21 * y11 * z12)).\n  reflexivity.\nQed.\n\n(* Part c: Proposition 12 - Identity matrix is left and right neutral *)\n\nProposition proposition_12_left_neutral :\n  forall x : m22,\n    m22_mul m22_one x = x.\nProof.\n  intros [x11 x12 x21 x22].\n  unfold m22_one, m22_mul.\n  Search (1 * _).\n  rewrite -> 4 Nat.mul_1_l.\n  Search (0 * _).\n  rewrite -> 4 Nat.mul_0_l.\n  Search (_ + 0).\n  rewrite -> 2 Nat.add_0_r.\n  rewrite -> 2 Nat.add_0_l.\n  reflexivity.\nQed.\n\nProposition proposition_12_right_neutral :\n  forall x : m22,\n    m22_mul x m22_one = x.\nProof.\n  intros [x11 x12 x21 x22].\n  unfold m22_one, m22_mul.\n  rewrite -> 4 Nat.mul_1_r.\n  rewrite -> 4 Nat.mul_0_r.\n  rewrite -> 2 Nat.add_0_l.\n  rewrite -> 2 Nat.add_0_r.\n  reflexivity.\nQed.\n\n \n(* Part d: Definition 13 - Matrix exponentiation function *)\n\nFixpoint m22_exp (x : m22) (n : nat) : m22 :=\n  match n with\n  | 0 =>\n    m22_one\n  | S n' =>\n    m22_mul (m22_exp x n') x\n  end.\n\nLemma fold_unfold_m22_exp_O :\n  forall x : m22,\n    m22_exp x 0 =\n    m22_one.\nProof.\n  fold_unfold_tactic m22_exp.\nQed.\n\nLemma fold_unfold_m22_exp_S :\n  forall (x : m22)\n         (n' : nat),\n    m22_exp x (S n') =\n    m22_mul (m22_exp x n') x.\nProof.\n  fold_unfold_tactic m22_exp.\nQed.\n\n\n(* Part e - Proposition 14 *)\n\nProposition proposition_14 :\n  forall n : nat,\n    m22_exp (M22 1 1\n                 0 1) n =\n    M22 1 n\n        0 1.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (fold_unfold_m22_exp_O (M22 1 1 0 1)).\n    unfold m22_one.\n    reflexivity.\n  - rewrite -> (fold_unfold_m22_exp_S (M22 1 1 0 1) n').\n    rewrite -> IHn'.\n    unfold m22_mul.\n    rewrite -> Nat.mul_0_l.\n    rewrite ->2 Nat.mul_0_r.\n    Search (_ + 0).\n    rewrite ->2 Nat.add_0_r.\n    rewrite -> Nat.add_0_l.\n    rewrite -> (Nat.mul_1_l 1).\n    rewrite -> Nat.mul_1_r.\n    Search (1 + _).\n    rewrite -> (Nat.add_1_l n').\n    reflexivity.\nQed.\n\n\n\n(* Part g - Exercise 25 *)\n\nCompute (m22_exp (M22 1 1\n                      1 0) 0).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 1).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 2).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 3).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 4).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 5).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 6).\n\nCompute (m22_exp (M22 1 1\n                      1 0) 7).\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\nDefinition test_fib (candidate : nat -> nat) :=\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\nFixpoint fib_aux (n : nat) : nat :=\n  match n with\n  | 0 =>\n    0\n  | S n' =>\n    match n' with\n    | 0 =>\n      1\n    | S n'' =>\n      fib_aux n' + fib_aux n''\n  end\nend.\n\nDefinition fib (n : nat) : nat :=\n  fib_aux n.\n\nCompute (test_fib fib).\n\nLemma fold_unfold_fib_aux_O :\n  fib_aux 0 =\n  0.\nProof.\n  fold_unfold_tactic fib_aux.\nQed.\n\nLemma fold_unfold_fib_aux_1 :\n  fib_aux 1 =\n  1.\nProof.\n  fold_unfold_tactic fib_aux.\nQed.\n\n\nLemma fold_unfold_fib_aux_S :\n  forall n' : nat,\n    fib_aux (S (S n')) =\n    fib_aux (S n') + fib_aux n'.\nProof.\n  fold_unfold_tactic fib_aux.\nQed.\n\n\nProposition exercise_25 :\n  forall n : nat,\n    m22_exp (M22 1 1\n                 1 0) (S n) =\n    M22 (fib (S (S n))) (fib (S n))\n        (fib (S n)) (fib n).\nProof.\n  intro n.\n  unfold fib.\n  induction n as [ | n' IHn'].\n  - rewrite -> fold_unfold_fib_aux_O.\n    rewrite -> fold_unfold_fib_aux_1.\n    rewrite -> (fold_unfold_fib_aux_S 0).\n    rewrite -> fold_unfold_fib_aux_O.\n    rewrite -> fold_unfold_fib_aux_1.\n    rewrite -> (Nat.add_0_r 1).\n    unfold m22_exp.\n    Check proposition_12_left_neutral. \n    rewrite -> (proposition_12_left_neutral (M22 1 1 1 0)).\n    reflexivity.\n  - Check (fold_unfold_m22_exp_S).\n    rewrite -> (fold_unfold_m22_exp_S (M22 1 1 1 0) (S n')).\n    rewrite -> IHn'.\n    unfold m22_mul.\n    rewrite -> 3 Nat.mul_1_r.\n    rewrite -> 2 Nat.mul_0_r.\n    rewrite -> 2 Nat.add_0_r.\n    Check (fold_unfold_fib_aux_S).\n    rewrite <- (fold_unfold_fib_aux_S (S n')).\n    rewrite <- (fold_unfold_fib_aux_S n').\n    reflexivity.\nQed.\n\n    \n(* Part h - Definition 27 *)\n\nFixpoint m22_exp' (x : m22) (n : nat) : m22 :=\n  match n with\n  | 0 =>\n    m22_one\n  | S n' =>\n    m22_mul x (m22_exp' x n')\n  end.\n\nLemma fold_unfold_m22_exp'_O :\n  forall x : m22,\n  m22_exp' x 0 =\n  m22_one.\nProof.\n  fold_unfold_tactic m22_exp'.\nQed.\n\nLemma fold_unfold_m22_exp'_S :\n  forall (x : m22)\n         (n' : nat),\n    m22_exp' x (S n') =\n    m22_mul x (m22_exp' x n').\nProof.\n  fold_unfold_tactic m22_exp'.\nQed.\n\n\n(* Part i - Equivalence of m22_exp and m22_exp' *)\n\nProposition proposition_29 :\n  forall (x : m22)\n         (n : nat),\n    m22_mul x (m22_exp x n) = m22_mul (m22_exp x n) x.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (fold_unfold_m22_exp_O x).\n    rewrite -> (proposition_12_left_neutral x).\n    exact (proposition_12_right_neutral x).\n  - rewrite -> (fold_unfold_m22_exp_S x n').\n    rewrite -> (proposition_10 x (m22_exp x n') x).\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nCorollary definition_13_and_27_are_equivalent :\n  forall (x : m22)\n         (n : nat),\n    m22_exp x n = m22_exp' x n.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (fold_unfold_m22_exp_O x).\n    rewrite -> (fold_unfold_m22_exp'_O x).\n    reflexivity.\n  - rewrite -> (fold_unfold_m22_exp_S x n').\n    rewrite -> (fold_unfold_m22_exp'_S x n').\n    rewrite <- IHn'.\n    rewrite -> (proposition_29 x n').\n    reflexivity.\nQed.\n\n(* Part j - Definition 35, Transposition of matrix *)\n\nDefinition m22_transpose (x : m22) : m22 :=\n  match x with\n  | M22 x11 x12\n        x21 x22 =>\n    M22 x11 x21\n        x12 x22\n  end.\n\n\n(* Part k - Property 36, Transposition is involutive *)\n\nProposition property_36 :\n  forall x : m22,\n    m22_transpose (m22_transpose x) = x.\nProof.\n  intros [x11 x12 x21 x22].\n  unfold m22_transpose.\n  reflexivity.\nQed.\n\n\n(* Part l - Proposition 38, Transposition and exponentiation commute with each other *)\n\n\nLemma lemma_37 :\n  forall x y : m22,\n    m22_transpose (m22_mul x y) = m22_mul (m22_transpose y) (m22_transpose x).\nProof.\n  intros [x11 x12 x21 x22]\n         [y11 y12 y21 y22].\n  unfold m22_transpose.\n  unfold m22_mul.\n  rewrite -> (Nat.mul_comm x11 y11).\n  rewrite -> (Nat.mul_comm x12 y21).\n  rewrite -> (Nat.mul_comm x21 y11).\n  rewrite -> (Nat.mul_comm x22 y21).\n  rewrite -> (Nat.mul_comm x11 y12).\n  rewrite -> (Nat.mul_comm x12 y22).\n  rewrite -> (Nat.mul_comm x21 y12).\n  rewrite -> (Nat.mul_comm x22 y22).\n  reflexivity.\nQed.\n\n\nProposition proposition_38 :\n  forall (x : m22)\n         (n : nat),\n    m22_transpose (m22_exp x n) = m22_exp (m22_transpose x) n.\nProof.\n  intros [x11 x12 x21 x22] n.\n  induction n as [ | n' IHn'].\n  - Check (fold_unfold_m22_exp_O).\n    rewrite -> (fold_unfold_m22_exp_O (M22 x11 x12 x21 x22)).\n    rewrite -> (fold_unfold_m22_exp_O (m22_transpose (M22 x11 x12 x21 x22))).\n    unfold m22_transpose.\n    unfold m22_one.\n    reflexivity.\n  - Check (fold_unfold_m22_exp_S).\n    rewrite -> (fold_unfold_m22_exp_S (M22 x11 x12 x21 x22)).\n    Check (lemma_37).\n    rewrite -> (lemma_37 (m22_exp (M22 x11 x12 x21 x22) n') (M22 x11 x12 x21 x22)).\n    rewrite -> IHn'.\n    Check (proposition_29).\n    rewrite -> (proposition_29 (m22_transpose (M22 x11 x12 x21 x22)) n').\n    rewrite -> (fold_unfold_m22_exp_S (m22_transpose (M22 x11 x12 x21 x22))).\n    reflexivity.\nQed.    \n\n\n(* Part m - Exericse 40*)\n\n\nProposition proposition_33 :\n  forall (n : nat),\n    m22_exp (M22 1 0\n                 1 1) n =\n    (M22 1 0\n         n 1).\nProof.\n  intro n.\n  rewrite <- (property_36 (M22 1 0 1 1)).\n  unfold m22_transpose at 2.\n  rewrite <- (proposition_38 (M22 1 1 0 1) n).\n  rewrite -> (proposition_14 n).\n  unfold m22_transpose.\n  reflexivity.\nQed.\n    \n\n\n(* Week 7 Exercise 2 *)\n\n(* ********** *)\n\nDefinition is_a_sound_and_complete_equality_predicate (V : Type) (V_eqb : V -> V -> bool) :=\n  forall v1 v2 : V,\n    V_eqb v1 v2 = true <-> v1 = v2.\n\n(* ********** *)\n\nCheck Bool.eqb.\n(* eqb : bool -> bool -> bool *)\n\nDefinition bool_eqb (b1 b2 : bool) : bool :=\n  match b1 with\n  | true =>\n    match b2 with\n    | true =>\n      true\n    | false =>\n      false\n    end\n  | false =>\n    match b2 with\n    | true =>\n      false\n    | false =>\n      true\n    end\n  end.\n\nLemma bool_eqb_is_reflexive :\n  forall b : bool,\n    bool_eqb b b = true.\nProof.\n  intros [ | ]; unfold bool_eqb; reflexivity.\nQed.\n\nSearch (eqb _ _ = _ -> _ = _).\n(* eqb_prop: forall a b : bool, eqb a b = true -> a = b *)\n\nProposition soundness_and_completeness_of_bool_eqb :\n  is_a_sound_and_complete_equality_predicate bool bool_eqb.\nProof.\n  unfold is_a_sound_and_complete_equality_predicate.\n  intros [ | ] [ | ].\n  - split.\n    * intro H_bool_eqb.\n      reflexivity.\n    * intro H_obvious.\n      exact (bool_eqb_is_reflexive true).\n  - split.\n    * intro H_absurd.\n      unfold bool_eqb in H_absurd.\n      discriminate H_absurd.\n    * intro H_absurd.\n      discriminate H_absurd.\n  - split.\n    * intro H_absurd.\n      unfold bool_eqb in H_absurd.\n      discriminate H_absurd.\n    * intro H_absurd.\n      discriminate H_absurd.\n  - split.\n    * intro H_bool_eqb.\n      reflexivity.\n    * intro H_obvious.\n      exact (bool_eqb_is_reflexive false).\nQed.    \n\n(* ***** *)\n\nProposition soundness_and_completeness_of_Bool_eqb :\n  is_a_sound_and_complete_equality_predicate bool eqb.\nProof.\n  unfold is_a_sound_and_complete_equality_predicate.\n  intros v1 v2.\n  Search (eqb _ _ = _ <-> _ = _).\n  exact (eqb_true_iff v1 v2).\nQed.\n    \n(* ********** *)\n\nCheck Nat.eqb.\n(* Nat.eqb : nat -> nat -> bool *)\n\nFixpoint nat_eqb (n1 n2 : nat) : bool :=\n  match n1 with\n  | O =>\n    match n2 with\n    | O =>\n      true\n    | S n2' =>\n      false\n    end\n  | S n1' =>\n    match n2 with\n    | O =>\n      false\n    | S n2' =>\n      nat_eqb n1' n2'\n    end\n  end.\n\nLemma fold_unfold_nat_eqb_O :\n  forall n2 : nat,\n    nat_eqb 0 n2 =\n    match n2 with\n    | O =>\n      true\n    | S _ =>\n      false\n    end.\nProof.\n  fold_unfold_tactic nat_eqb.\nQed.\n\nLemma fold_unfold_nat_eqb_S :\n  forall n1' n2 : nat,\n    nat_eqb (S n1') n2 =\n    match n2 with\n    | O =>\n      false\n    | S n2' =>\n      nat_eqb n1' n2'\n    end.\nProof.\n  fold_unfold_tactic nat_eqb.\nQed.\n\nSearch (Nat.eqb _ _ = true -> _ = _).\n(* beq_nat_true: forall n m : nat, (n =? m) = true -> n = m *)\n\nProposition soundness_and_completeness_of_nat_eqb :\n  is_a_sound_and_complete_equality_predicate nat nat_eqb.\nProof.\n  unfold is_a_sound_and_complete_equality_predicate.\n  intros v1.\n  induction v1 as [ | v1' IHv1'].\n  - intros [ | v2'].\n    * split.\n      + intros _.\n        reflexivity.\n      + intros _.\n        exact (fold_unfold_nat_eqb_O 0).\n    * rewrite -> (fold_unfold_nat_eqb_O (S v2')).\n      split; intro H_absurd; discriminate H_absurd.\n  - intros [ | v2'].\n    * rewrite -> (fold_unfold_nat_eqb_S v1' 0).\n      split; intro H_absurd; discriminate H_absurd.\n    * rewrite -> (fold_unfold_nat_eqb_S v1' (S v2')).\n      assert (IHv1' := IHv1' v2').\n      destruct IHv1' as [H_nat_eqb_implies_equality H_v1_equals_v2_implies_nat_eqb].\n      split.\n      + intro H_nat_eqb.        \n        rewrite -> (H_nat_eqb_implies_equality H_nat_eqb).\n        reflexivity.\n      + intro H_S_v1_equals_S_v2.\n        Search (S _ = S _ -> _ = _).\n        assert (H_v1_equals_v2 := eq_add_S v1' v2' H_S_v1_equals_S_v2).\n        rewrite -> (H_v1_equals_v2_implies_nat_eqb H_v1_equals_v2).\n        reflexivity.\nQed.\n        \n(* ***** *)\n\nLemma fold_unfold_Nat_eqb_O :\n  forall n2 : nat,\n    0 =? n2 =\n    match n2 with\n    | O =>\n      true\n    | S _ =>\n      false\n    end.\nProof.\n  fold_unfold_tactic Nat.eqb.\nQed.\n\nLemma fold_unfold_Nat_eqb_S :\n  forall n1' n2 : nat,\n    S n1' =? n2 =\n    match n2 with\n    | O =>\n      false\n    | S n2' =>\n      n1' =? n2'\n    end.\nProof.\n  fold_unfold_tactic Nat.eqb.\nQed.\n\nProposition soundness_and_completeness_of_Nat_eqb :\n  is_a_sound_and_complete_equality_predicate nat Nat.eqb.\nProof.\n  unfold is_a_sound_and_complete_equality_predicate.\n  intros v1 v2.\n  Search (Nat.eqb _ _ = true <-> _ = _).\n  exact (Nat.eqb_eq v1 v2).\nQed.\n\n(* ********** *)\n\nDefinition pair_eqb (V W : Type) (V_eqb : V -> V -> bool) (W_eqb : W -> W -> bool) (p1 p2 : V * W) : bool :=\n  match p1 with\n  | (v1, w1) =>\n    match p2 with\n    | (v2, w2) =>\n      V_eqb v1 v2 && W_eqb w1 w2\n    end\n  end.\n\nProposition soundness_and_completeness_of_pair_eqb :\n  forall (V W : Type)\n         (V_eqb : V -> V -> bool)\n         (W_eqb : W -> W -> bool),\n    is_a_sound_and_complete_equality_predicate V V_eqb ->\n    is_a_sound_and_complete_equality_predicate W W_eqb ->\n    forall p1 p2 : V * W,\n      pair_eqb V W V_eqb W_eqb p1 p2 = true <-> p1 = p2.\nProof.\n  intros V W V_eqb W_eqb.\n  unfold is_a_sound_and_complete_equality_predicate.\n  intros H_soundness_and_completeness_of_V_eqb H_soundness_and_completeness_of_W_eqb.\n  intros [v1 w1] [v2 w2].\n  unfold pair_eqb.\n  assert (H_soundness_and_completeness_of_V_eqb' := H_soundness_and_completeness_of_V_eqb v1 v2).\n  assert (H_soundness_and_completeness_of_W_eqb' := H_soundness_and_completeness_of_W_eqb w1 w2).\n  destruct H_soundness_and_completeness_of_V_eqb' as [H_V_eqb_implies_equality H_v1_equals_v2_implies_eqb].\n  destruct H_soundness_and_completeness_of_W_eqb' as [H_W_eqb_implies_equality H_w1_equals_w2_implies_eqb].\n  split.\n  - Search (_ && _ = true).\n    intros H_V_eqb_and_W_eqb.\n    assert (H_V_eqb_and_W_eqb' := andb_prop (V_eqb v1 v2) (W_eqb w1 w2)  H_V_eqb_and_W_eqb).\n    destruct H_V_eqb_and_W_eqb' as [H_V_eqb H_W_eqb].\n    assert (H_v1_equals_v2 := H_V_eqb_implies_equality H_V_eqb).\n    assert (H_w1_equals_w2 := H_W_eqb_implies_equality H_W_eqb).\n    rewrite -> H_v1_equals_v2.\n    rewrite -> H_w1_equals_w2.\n    reflexivity.\n  - intro H_equality_of_pair.\n    injection H_equality_of_pair as H_v1_equals_v2 H_w1_equals_w2.\n    assert (H_V_eqb := H_v1_equals_v2_implies_eqb H_v1_equals_v2).\n    assert (H_W_eqb := H_w1_equals_w2_implies_eqb H_w1_equals_w2).\n    Search (_ && _ = true).\n    assert (H_V_eqb_and_W_eqb := conj H_V_eqb H_W_eqb).\n    exact (andb_true_intro H_V_eqb_and_W_eqb).\nQed.    \n  \n\n(* ********** *)\n\n\nDefinition pair_nat_bool_eqb (p1 p2: nat * bool) : bool :=\n  pair_eqb nat bool nat_eqb bool_eqb p1 p2.\n\nProposition soundness_and_completeness_of_pair_nat_bool_eqb :\n  is_a_sound_and_complete_equality_predicate (nat * bool) pair_nat_bool_eqb.\nProof.\n  unfold is_a_sound_and_complete_equality_predicate.\n  Check (soundness_and_completeness_of_pair_eqb nat bool nat_eqb bool_eqb soundness_and_completeness_of_nat_eqb soundness_and_completeness_of_bool_eqb).\n  exact (soundness_and_completeness_of_pair_eqb nat bool nat_eqb bool_eqb soundness_and_completeness_of_nat_eqb soundness_and_completeness_of_bool_eqb).\nQed.\n\n\n(* ********** *)\n\n(* Week 9 Exercise 2 *)\n\nInductive mm22 : Type :=\n| MM22 : m22 -> m22 -> m22 -> m22 -> mm22.\n\n\n(* Part a *)\n\nDefinition mm22_add (x y : mm22) : mm22 :=\n  match x with\n  | MM22 m22_x11 m22_x21\n         m22_x12 m22_x22 =>\n    match y with\n    | MM22 m22_y11 m22_y21\n           m22_y12 m22_y22 =>\n      MM22 (m22_add m22_x11 m22_y11) (m22_add m22_x21 m22_y21)\n           (m22_add m22_x12 m22_y12) (m22_add m22_x22 m22_y22)\n    end\n  end.\n\n\nDefinition mm22_mul (x y : mm22) : mm22 :=\n  match x with\n  | MM22 m22_x11 m22_x21\n         m22_x12 m22_x22 =>\n    match y with\n    | MM22 m22_y11 m22_y21\n           m22_y12 m22_y22 =>\n      MM22 (m22_add (m22_mul m22_x11 m22_y11) (m22_mul m22_x12 m22_y21)) (m22_add (m22_mul m22_x11 m22_y12) (m22_mul m22_x12 m22_y22))\n           (m22_add (m22_mul m22_x21 m22_y11) (m22_mul m22_x22 m22_y21)) (m22_add (m22_mul m22_x21 m22_y12) (m22_mul m22_x22 m22_y22))\n    end\n  end.\n\nDefinition mm22_one :=\n  MM22 m22_one m22_one\n       m22_one m22_one.\n\nFixpoint mm22_exp (x : mm22) (n : nat) : mm22 :=\n  match n with\n  | 0 =>\n    mm22_one\n  | S n' =>\n    mm22_mul (mm22_exp x n') x\n  end.\n\n(* ********** *)\n\n(* end of week-09_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-09_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7523778109727786}}
{"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(*                                Lib_Fact.v                                *)\n(****************************************************************************)\n\nRequire Export Arith.\n\n\nFixpoint factorial (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S p => S p * factorial p\n  end.\n\n\n\nLemma fact_pred :\n forall n : nat, 0 < n -> factorial n = n * factorial (pred n).\nsimple induction n; auto with arith.\nQed.\nHint Resolve fact_pred.\n\n\n(************************************************************************)\n", "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/Libraries/Lib_Arithmetic/Lib_Fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7523778065120158}}
{"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. lfind.  rewrite IHx.  reflexivity. \nAdmitted.\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": "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_commut_58_plus_succ/goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7523778002068086}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Sorted.\nRequire Import Recdef.\n\nFunction bubble (l : list nat) {measure length} : list nat :=\n  match l with\n  | nil => nil\n  | n :: nil => n :: nil\n  | n1 :: n2 :: l' => if leb n1 n2\n                      then n1 :: (bubble (n2 :: l'))\n                      else n2 :: (bubble (n1 :: l'))\n  end.\nProof.\n  auto. auto.\nQed.\n\nFunction bubble_sort (l : list nat) : list nat :=\n  match l with\n  | nil => nil\n  | n :: l' => bubble (n :: (bubble_sort l'))\n  end.\n\nCheck Sorted.\n\nCheck (Sorted le).\n\nPrint Sorted.\n\nPrint HdRel.\n\n(* \nSorted_cons:\n  forall (a : A) (l : list A),\n  Sorted R l -> HdRel R a l -> Sorted R (a :: l)\n\nHdRel_nil : HdRel R a nil\nHdRel_cons : forall (b : A) (l : list A), R a b -> HdRel R a (b :: l)\n*)\n\nCheck bubble_terminate.\nCheck iter.\n\nTheorem bubble_sort_correct : forall l, Sorted le (bubble_sort l).\nProof.\n  intros.\n  induction l.\n    simpl. apply Sorted_nil.\n    simpl. destruct l.\n      simpl. unfold bubble.\n      unfold bubble_terminate.\n\nEval compute in bubble      (1 :: 2 :: 0 :: 3 :: 1 :: nil).\nEval compute in bubble_sort (1 :: 2 :: 0 :: 3 :: 1 :: nil).\nEval compute in bubble_sort (1 :: 2 :: 10 :: 3 :: 6 :: nil).", "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/Math/sorting/example_bubblesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7523208914365301}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\n\nFrom Turing Require Import Lang.\nFrom Turing Require Import Util.\nFrom Turing Require Import Regex.\n\nImport Lang.Examples.\nImport LangNotations.\nImport ListNotations.\nImport RegexNotations.\n\nOpen Scope lang_scope.\nOpen Scope char_scope.\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nShow that 'aba' is accepted the the following regular expression.\n\n *)\nTheorem ex1:\n  [\"a\"; \"b\"; \"a\"] \\in (r_star \"a\" ;; (\"b\" || \"c\") ;; r_star \"a\").\nProof.\n  apply accept_app with (s1:=[\"a\";\"b\"]) (s2:=[\"a\"]).\n  apply accept_app with (s1:=[\"a\"]) (s2:=[\"b\"]).\n  - apply accept_star_eq, accept_char.\n  - apply accept_union_l, accept_char.\n  - simpl. reflexivity.\n  - apply accept_star_eq, accept_char.\n  - simpl. reflexivity.\nQed.\n\n\n(**\n\nShow that 'bb' is rejected by the following regular expression.\n\n *)\nTheorem ex2:\n  ~ ([\"b\"; \"b\"] \\in (r_star \"a\" ;; (\"b\" || \"c\") ;; r_star \"a\")).\nProof.\n  unfold not; intros.\n  inversion H; subst; clear H.\n  destruct s1.\n  - inversion H3; subst; clear H3.\n    * inversion H5.\n    * inversion H0; subst; clear H0.\n      inversion H5.\n  - inversion H2; subst; clear H2.\n    rewrite H7 in H5.\n    inversion H1; subst; clear H1.\n    * inversion H4; subst; clear H4.\n       + inversion H2; subst; clear H2.\n         inversion H3; subst; clear H3.\n         -- inversion H5.\n         -- inversion H0; subst; clear H0.\n            inversion H5.\n       + inversion H2; subst; clear H2. \n         inversion H5.\n    * inversion H0; subst; clear H0. inversion H5.\n\nQed.\n\n(**\n\nFunction size counts how many operators were used in a regular\nexpression. Show that (c ;; {})* can be written using a single\nregular expression constructor.\n\n\n *)\nTheorem ex3:\n  exists r, size r = 1 /\\ (r_star ( \"c\" ;; r_void ) <==> r).\nProof.\n  exists r_nil.\n  split.\n  - reflexivity.\n  - rewrite r_app_r_void_rw.\n    apply r_star_void_rw.\n\nQed.\n\n(**\n\nGiven that the following regular expression uses 530 constructors\n(because size r_all = 514).\nShow that you can find an equivalent regular expression that uses\nat most 6 constructors.\n\n\n *)\n(* Using lecture 11*)\nTheorem ex4:\n  exists r, size r <= 6 /\\  ((r_star ( (r_all || r_star \"c\" ) ;; r_void) ;; r_star (\"a\" || \"b\")) ;; r_star r_nil;; \"c\" <==> r).\nProof.\n  exists (r_star (\"a\" || \"b\") ;; \"c\").\n  split. \n  - reflexivity.\n  - Search (r_void).\n    rewrite r_app_r_void_rw.\n    rewrite r_star_void_rw.\n    rewrite r_star_nil_rw.\n    rewrite r_app_l_nil_rw.\n    rewrite r_app_r_nil_rw.\n    reflexivity.\nQed.\n(**\n\nThe following code implements a function that given a string\nit returns a regular expression that only accepts that string.\n\n    Fixpoint r_word' l :=\n    match l with\n    | nil => r_nil\n    | x :: l => (r_char x) ;; r_word' l\n    end.\n\nProve that function `r_word'` is correct.\nNote that you must copy/paste the function to outside of the comment\nand in your proof state: exists r_word'.\n\nThe proof must proceed by induction.\n\n\n *)\n Fixpoint r_word' l :=\n    match l with\n    | nil => r_nil\n    | x :: l => (r_char x) ;; r_word' l\n    end.\n\nTheorem ex5:\n  forall l, exists (r_word:list ascii -> regex), Accept (r_word l) == fun w => w = l.\nProof.\n  exists r_word'.\n  induction l.\n  - simpl. \n    unfold Equiv.\n    split; intros.\n    + inversion H.\n      apply nil_in.\n    + inversion H.\n      subst.\n      rewrite r_nil_rw.\n      apply H.\n  - unfold Equiv. \n    split; intros.\n    + inversion H; subst; clear H.\n      inversion H2; subst; clear H2.\n      destruct IHl with (w:=s2).\n      intuition.\n      rewrite H1.\n      reflexivity.\n    + unfold In in *. \n      rewrite H.\n      apply accept_app with (s1:=[a]) (s2:=l).\n      * apply accept_char.\n      * apply IHl.\n        unfold In.\n        reflexivity.\n      * reflexivity.\nQed.\n\n\n(**\n\nShow that there exists a regular expression with 5 constructs that\nrecognizes the following language. The idea is to find the smallest\nregular expression that recognizes the language.\n\n\n *)\nTheorem ex6:\n  exists r, (Accept r == fun w => w = [\"a\"; \"c\"] \\/ w = [\"b\"; \"c\"]) /\\ size r = 5.\nProof.\n  exists ((\"a\" || \"b\");;\"c\").\n  split.\n  - split; intros.\n    + apply r_app_union_distr_l in H.\n      inversion H; subst; clear H.\n      * left. \n        inversion H3; subst; clear H3.\n        inversion H1; subst; clear H1.\n        inversion H2; subst; clear H2.\n        reflexivity.\n      * right.\n        inversion H3; subst; clear H3.\n        inversion H1; subst; clear H1.\n        inversion H2; subst; clear H2.\n        reflexivity.\n    + inversion H.\n      * apply r_app_union_distr_l.\n        unfold In.\n        apply accept_union_l.\n        apply accept_app with (s1:=[\"a\"]) (s2:=[\"c\"]).\n         -- apply accept_char.\n         -- apply accept_char.\n         -- rewrite H0. \n           reflexivity.\n      * apply r_app_union_distr_l.\n         unfold In.\n         apply accept_union_r.\n         apply accept_app with (s1:=[\"b\"]) (s2:=[\"c\"]).\n         -- apply accept_char. \n         -- apply accept_char. \n         -- rewrite H0.\n            reflexivity. \n  - reflexivity.\nQed.\n\n\n\n", "meta": {"author": "Kenilpatel057", "repo": "Intro-to-Theory-of-computation", "sha": "27a998cbda0ba0286056d8f61fe037d5c26c6381", "save_path": "github-repos/coq/Kenilpatel057-Intro-to-Theory-of-computation", "path": "github-repos/coq/Kenilpatel057-Intro-to-Theory-of-computation/Intro-to-Theory-of-computation-27a998cbda0ba0286056d8f61fe037d5c26c6381/hw4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7523208815951887}}
{"text": "From GameTheory Require Import In ImpartialGame Boolgroup SumGames Equiv Nim.\nRequire Import Lia.\nRequire Import BinNat.\n\nDefinition mx_N_list (l : list N) : N := fold_right N.max 0 l.\nCheck list_max_le.\nLemma max_lt : forall (l : list N) (n : N),\n    mx_N_list l < n ->\n    Forall (fun k => k < n) l.\nProof.\n  induction l; auto.\n  intros n H.\n  simpl in H.\n  constructor.\n  lia.\n  apply IHl.\n  lia.\nQed.\n\nSection Mex.\n  Variable l : list N.\n  Definition is_mex (m : N) :=\n    (forall n, n < m -> In n l) /\\ ~ In m l.\n\n  (* We do not use this lemma, but this gives us some confidence that mex is in fact *)\n  (* a well-defined function, rather than just a relation between lists and Ns. *)\n  Lemma mex_unique : forall m m',\n      is_mex m -> is_mex m' -> m = m'.\n  Proof using l.\n    intros.\n    repeat (match goal with\n            | H : is_mex ?x |- _ => destruct H as [? ?]\n            end).\n    destruct (N.lt_trichotomy m m') as [? | [? | ?]];\n    repeat (match goal with\n    | E : ?x < ?y, H1 : forall n, n < ?y -> In n l, H2 : ~ In ?x l |- _ =>\n      specialize H1 with x; apply H2 in H1; auto; contradiction\n    | |- _ => auto\n    end).\n  Qed.\n\n  Lemma not_in_dec : forall x, {In x l} + {~ In x l}.\n  Proof.\n    intros x.\n    destruct (in_dec N.eq_dec x l); auto.\n  Defined.\n\n  Lemma mex_bound : { m | ~ In m l}.\n    constructor 1 with (mx_N_list l + 1).\n    pose proof (max_lt l (mx_N_list l + 1)).\n    rewrite Forall_forall in H.\n    unfold not; intros.\n    apply H in H0; lia.\n  Defined.\n\n  Definition mex_defn : { m | is_mex m }.\n  Proof.\n    destruct mex_bound as [b H].\n    enough (forall k, (forall x, x <= k -> In x l) + { m | m <= k /\\ is_mex m }) as IH.\n    {\n    destruct (IH b) as [? | ?].\n    - specialize i with b.\n        apply H in i. contradiction. lia.\n    - destruct s as [m [? Hm]].\n      constructor 1 with m. assumption.\n    }\n    refine (N.peano_rect _ _ _); intros.\n    - destruct (not_in_dec 0).\n      + left. intros. assert (x = 0). lia. rewrite H1. auto.\n      + right. constructor 1 with 0; unfold is_mex; intuition; lia.\n    - destruct H0 as [? | ?].\n      + destruct (not_in_dec (N.succ n)).\n        * left; intros. assert (x <= n \\/ x = N.succ n). lia.\n          destruct H1; auto.\n          rewrite H1. auto.\n        * right. constructor 1 with (N.succ n); unfold is_mex; intuition.\n          assert (n1 <= n). lia. apply i; auto.\n      + destruct s as [m [? ?]].\n        right. constructor 1 with m; intuition; lia.\n  Defined.\n\n  Definition mex : N := let (m, _) := mex_defn in m.\n  Lemma mex_lt : (forall n, n < mex -> In n l).\n    unfold mex.\n    destruct mex_defn as [? [? ?]].\n    auto.\n  Qed.\n\n  Lemma mex_neq :  ~ In (mex) l.\n    unfold mex.\n    destruct mex_defn as [? [? ?]].\n    auto.\n  Qed.\nEnd Mex.\n\nCompute (mex [0; 1; 2; 3; 4; 6]).\n\n\nSection Grundy.\n  Variable g : impartial_game.\n\n  Definition grundy : position g -> N :=\n    Fix (finite_game g)\n      (fun _ => N)\n      (fun x F => mex (map_In (moves g x) (fun y P => F y P))).\n\n\n  Lemma grundy_unfold : forall s,\n      grundy s = mex (map grundy (moves g s)).\n    intros.\n    unfold grundy.\n    rewrite Fix_eq.\n    apply f_equal.\n    rewrite map_In_map with (g := Fix (finite_game g) (fun _ : position g => N)\n       (fun (x : position g) (F : forall y : position g, valid_move g y x -> N) =>\n          mex (map_In (moves g x) (fun (y : position g) (P : In y (moves g x)) => F y P)))).\n    reflexivity.\n    reflexivity.\n    intros. apply f_equal. apply map_In_ext; auto.\n  Qed.\n\n  Lemma grundy_moves_valid : forall s s', valid_move g s' s -> In (grundy s') (map grundy (moves g s)).\n    intros.\n    unfold valid_move in H.\n    apply (in_map grundy) in H.\n    assumption.\n  Qed.\n\n  Lemma grundy_moves : forall s s',\n      valid_move g s' s ->\n      grundy s' < grundy s \\/ grundy s < grundy s'.\n    intros.\n    destruct (N.lt_trichotomy (grundy s') (grundy s)) as [? | [? | ?]]; auto.\n    apply grundy_moves_valid in H.\n    rewrite H0 in H.\n    rewrite grundy_unfold in H.\n    apply mex_neq in H.\n    contradiction.\n  Qed.\n\n  Lemma grundy_moves_lt : forall n s,\n      n < grundy s ->\n      exists s', valid_move g s' s /\\ grundy s' = n.\n    intros.\n    rewrite grundy_unfold in H.\n    apply mex_lt in H.\n    apply in_map_iff in H as [s' [? ?]].\n    exists s'; auto.\n  Qed.\n\n  Definition grundy_game : N := grundy (start g).\n\n  Theorem sg_theorem : g == Nim (grundy_game).\n    enough (forall s, forall n, losing_state (g ~+~ (Nim n)) (s, grundy s)).\n    - unfold equiv. apply H.\n    - refine (well_founded_induction (wf_trans _ _ (finite_game g)) _ _).\n      intros.\n      constructor; intros.\n      apply moves_in_game_sum in H0 as [[? ?] | [? ?]].\n      + destruct s'; simpl in *; subst.\n        pose proof H0 as ?.\n        apply grundy_moves in H0 as [H0 | H0].\n        (* If our move is to a state with lower grundy number, *)\n        (* make corresponding move on right side. *)\n        * apply trans_to_losing with (p, grundy p).\n          apply moves_in_game_sum; right; simpl; intuition.\n          apply nim_moves_spec; assumption.\n          apply H; constructor; assumption.\n        (* If our move is to a state with higher grundy number, *)\n        (* move back to state with original grundy value on left side *)\n        * destruct (grundy_moves_lt _ _ H0) as [p' [? ?]].\n          apply trans_to_losing with (p', grundy x).\n          apply moves_in_game_sum; left; simpl; intuition.\n          rewrite <- H3.\n          apply H. constructor 2 with p; assumption.\n      + destruct s'; simpl in *; subst.\n        apply nim_moves_spec in H0.\n        destruct (grundy_moves_lt _ _ H0) as [p' [? ?]].\n        apply trans_to_losing with (p', p0).\n        apply moves_in_game_sum; left; simpl; intuition.\n        rewrite <- H2.\n        apply H; constructor; assumption.\n  Qed.\nEnd Grundy.\n\nTheorem sg_sum : forall g h, g ~+~ h == Nim (N.lxor (grundy_game g) (grundy_game h)).\n  intros.\n  rewrite (sg_theorem g) at 1.\n  rewrite (sg_theorem h) at 1.\n  apply nim_sum_equiv.\nQed.\n\nPrint Assumptions sg_sum.\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/Grundy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7522308594583651}}
{"text": "Require Import init.\n\nRequire Export plus_group.\n\n#[universes(template)]\nClass Mult U := {\n    mult : U → U → U;\n}.\nInfix \"*\" := mult : algebra_scope.\n\nClass Ldist U `{Plus U} `{Mult U} := {\n    ldist : ∀ a b c, a * (b + c) = a * b + a * c;\n}.\nClass Rdist U `{Plus U} `{Mult U} := {\n    rdist : ∀ a b c, (a + b) * c = a * c + b * c;\n}.\n\nClass MultAssoc U `{Mult U} := {\n    mult_assoc : ∀ a b c, a * (b * c) = (a * b) * c;\n}.\nClass MultComm U `{Mult U} := {\n    mult_comm : ∀ a b, a * b = b * a;\n}.\n\nClass MultLanni U `{Zero U, Mult U} := {\n    mult_lanni : ∀ a, 0 * a = 0;\n}.\nClass MultRanni U `{Zero U, Mult U} := {\n    mult_ranni : ∀ a, a * 0 = 0;\n}.\n\n#[universes(template)]\nClass One U := {\n    one : U;\n}.\nNotation \"1\" := one : algebra_scope.\nNotation \"- 1\" := (-(1)) : algebra_scope.\nClass MultLid U `{Mult U, One U} := {\n    mult_lid : ∀ a, 1 * a = a;\n}.\nClass MultRid U `{Mult U, One U} := {\n    mult_rid : ∀ a, a * 1 = a;\n}.\n\nClass MultLcancel U `{Zero U, Mult U} := {\n    mult_lcancel : ∀ {a b} c, 0 ≠ c → c * a = c * b → a = b;\n}.\nClass MultRcancel U `{Zero U, Mult U} := {\n    mult_rcancel : ∀ {a b} c, 0 ≠ c → a * c = b * c → a = b;\n}.\n\nClass Rng U `{\n    RP : AllPlus U,\n    UM : Mult U,\n    UL : @Ldist U UP UM,\n    UR : @Rdist U UP UM,\n    UMA : @MultAssoc U UM\n}.\n\nClass Ring U `{\n    RR : Rng U,\n    UE : @One U,\n    UME : @MultLid U UM UE,\n    UMER : @MultRid U UM UE\n}.\n\nClass CRing U `{\n    CRR : Ring U,\n    UMC : @MultComm U UM\n}.\n\nClass IntegralDomain U `{\n    IDR : CRing U,\n    UML : @MultLcancel U UZ UM,\n    UMR : @MultRcancel U UZ UM\n}.\n\nClass AllMult U `{\n    AMI : IntegralDomain U,\n    UZL : @MultLanni U UZ UM,\n    UZR : @MultRanni U UZ UM\n}.\n\nClass HomomorphismMult {U V} `{Mult U, Mult V} (f : U → V) := {\n    homo_mult : ∀ a b, f (a * b) = f a * f b\n}.\n\nClass HomomorphismOne {U V} `{One U, One V} (f : U → V) := {\n    homo_one : f 1 = 1\n}.\n\nArguments mult : simpl never.\nArguments one : simpl never.\n\nNotation \"2\" := (one + 1) : algebra_scope.\nNotation \"3\" := (one + 2) : algebra_scope.\nNotation \"4\" := (one + 3) : algebra_scope.\nNotation \"5\" := (one + 4) : algebra_scope.\nNotation \"6\" := (one + 5) : algebra_scope.\nNotation \"7\" := (one + 6) : algebra_scope.\nNotation \"8\" := (one + 7) : algebra_scope.\nNotation \"9\" := (one + 8) : algebra_scope.\nNotation \"- 2\" := (-(2)) : algebra_scope.\nNotation \"- 3\" := (-(3)) : algebra_scope.\nNotation \"- 4\" := (-(4)) : algebra_scope.\nNotation \"- 5\" := (-(5)) : algebra_scope.\nNotation \"- 6\" := (-(6)) : algebra_scope.\nNotation \"- 7\" := (-(7)) : algebra_scope.\nNotation \"- 8\" := (-(8)) : algebra_scope.\nNotation \"- 9\" := (-(9)) : algebra_scope.\n\n(* begin hide *)\nSection MultRingImply.\n\nContext {U} `{AllMult U}.\n\nGlobal Instance mult_lid_rid : MultRid U.\nProof.\n    split.\n    intros a.\n    rewrite mult_comm.\n    apply mult_lid.\nQed.\n\nGlobal Instance mult_lcancel_rcancel : MultRcancel U.\nProof.\n    split.\n    intros a b c neq eq.\n    do 2 rewrite (mult_comm _ c) in eq.\n    apply mult_lcancel with c; [>exact neq|].\n    exact eq.\nQed.\n\nGlobal Instance mult_lanni_ranni : MultRanni U.\nProof.\n    split.\n    intros a.\n    rewrite mult_comm.\n    apply mult_lanni.\nQed.\n\nGlobal Instance ldist_rdist : Rdist U.\nProof.\n    split.\n    intros a b c.\n    do 3 rewrite (mult_comm _ c).\n    apply ldist.\nQed.\n\nEnd MultRingImply.\n\n\nSection MultRing.\n\nContext {U} `{AllMult U, NotTrivial U}.\n\n(* end hide *)\nTheorem lmult : ∀ {a b} c, a = b → c * a = c * b.\nProof.\n    intros a b c ab.\n    apply f_equal.\n    exact ab.\nQed.\nTheorem rmult : ∀ {a b} c, a = b → a * c = b * c.\nProof.\n    intros a b c ab.\n    rewrite ab.\n    reflexivity.\nQed.\nTheorem lrmult : ∀ {a b c d}, a = b → c = d → a * c = b * d.\nProof.\n    intros a b c d ab cd.\n    rewrite ab, cd.\n    reflexivity.\nQed.\n\nTheorem not_trivial_one : 0 ≠ 1.\nProof.\n    intros contr.\n    pose proof not_trivial_zero as [a a_nz].\n    apply rmult with a in contr.\n    rewrite mult_lanni in contr.\n    rewrite mult_lid in contr.\n    contradiction.\nQed.\n\nGlobal Instance ring_mult_lanni : MultLanni U.\nProof.\n    split.\n    intros a.\n    apply plus_rcancel with (0 * a).\n    rewrite <- rdist.\n    do 2 rewrite plus_lid.\n    reflexivity.\nQed.\nGlobal Instance ring_mult_ranni : MultRanni U.\nProof.\n    split.\n    intros a.\n    apply plus_lcancel with (a * 0).\n    rewrite <- ldist.\n    do 2 rewrite plus_rid.\n    reflexivity.\nQed.\n\nTheorem mult_lneg : ∀ a b, -a * b = -(a * b).\nProof.\n    intros a b.\n    apply plus_lcancel with (a * b).\n    rewrite <- rdist.\n    do 2 rewrite plus_rinv.\n    apply mult_lanni.\nQed.\nTheorem mult_rneg : ∀ a b, a * -b = -(a * b).\nProof.\n    intros a b.\n    apply plus_lcancel with (a * b).\n    rewrite <- ldist.\n    do 2 rewrite plus_rinv.\n    apply mult_ranni.\nQed.\nTheorem mult_lrneg : ∀ a b, -a * b = a * -b.\nProof.\n    intros a b.\n    rewrite mult_lneg, mult_rneg.\n    reflexivity.\nQed.\n\nTheorem mult_neg_one : ∀ a, -1 * a = -a.\nProof.\n    intros a.\n    rewrite mult_lneg.\n    rewrite mult_lid.\n    reflexivity.\nQed.\n\nTheorem neg_nz : ∀ a, 0 ≠ a ↔ 0 ≠ -a.\nProof.\n    intros a.\n    split; intros neq eq.\n    -   apply (f_equal neg) in eq.\n        rewrite neg_neg, neg_zero in eq.\n        contradiction.\n    -   rewrite <- eq in neq.\n        rewrite neg_zero in neq.\n        contradiction.\nQed.\n\nTheorem plus_two : ∀ a, a + a = 2*a.\nProof.\n    intros a.\n    rewrite <- (mult_lid a) at 1 2.\n    rewrite <- rdist.\n    reflexivity.\nQed.\n\nTheorem two_plus_two : 2 + 2 = 4.\nProof.\n    rewrite <- plus_assoc.\n    reflexivity.\nQed.\n\nTheorem two_times_two : 2 * 2 = 4.\nProof.\n    rewrite ldist.\n    rewrite mult_rid.\n    exact two_plus_two.\nQed.\n\nTheorem dif_squares : ∀ a b, a*a - b*b = (a + b) * (a - b).\nProof.\n    intros a b.\n    rewrite rdist.\n    do 2 rewrite ldist.\n    do 2 rewrite mult_rneg.\n    rewrite (mult_comm b a).\n    rewrite <- plus_assoc.\n    rewrite plus_llinv.\n    reflexivity.\nQed.\n\nTheorem mult_zero : ∀ a b, 0 = a * b → 0 = a ∨ 0 = b.\nProof.\n    intros a b eq.\n    classic_case (0 = a) as [a_z|a_nz].\n    -   left.\n        exact a_z.\n    -   right.\n        apply mult_lcancel with a; [>exact a_nz|].\n        rewrite mult_ranni.\n        exact eq.\nQed.\n\nTheorem mult_nz : ∀ a b, 0 ≠ a → 0 ≠ b → 0 ≠ a * b.\nProof.\n    intros a b neq1 neq2 contr.\n    apply mult_zero in contr.\n    destruct contr; contradiction.\nQed.\n\n(* begin hide *)\nEnd MultRing.\n\nSection MultHomo.\n\nContext {U V} `{AllMult U, AllMult V}.\n(* end hide *)\nContext (f : U → V) `{\n    @Injective U V f,\n    @HomomorphismPlus U V UP UP0 f,\n    @HomomorphismZero U V UZ UZ0 f,\n    @HomomorphismNeg U V UN UN0 f,\n    @HomomorphismMult U V UM UM0 f,\n    @HomomorphismOne U V UE UE0 f\n}.\n\nTheorem homo_two : f 2 = 2.\nProof.\n    setoid_rewrite homo_plus.\n    rewrite homo_one.\n    reflexivity.\nQed.\n\nTheorem homo_three : f 3 = 3.\nProof.\n    setoid_rewrite homo_plus.\n    rewrite homo_one, homo_two.\n    reflexivity.\nQed.\n\nTheorem homo_four : f 4 = 4.\nProof.\n    setoid_rewrite homo_plus.\n    rewrite homo_one, homo_three.\n    reflexivity.\nQed.\n\n(* begin hide *)\nEnd MultHomo.\n(* end hide *)\nTactic Notation \"mult_bring_left\" constr(x) :=\n    repeat rewrite mult_assoc;\n    repeat rewrite (mult_comm _ x);\n    repeat rewrite <- mult_assoc.\nTactic Notation \"mult_bring_left\" constr(x) \"in\" ident(H) :=\n    repeat rewrite mult_assoc in H;\n    repeat rewrite (mult_comm _ x) in H;\n    repeat rewrite <- mult_assoc in H.\nTactic Notation \"mult_bring_right\" constr(x) :=\n    repeat rewrite <- mult_assoc;\n    repeat rewrite (mult_comm x _);\n    repeat rewrite mult_assoc.\nTactic Notation \"mult_bring_right\" constr(x) \"in\" ident(H) :=\n    repeat rewrite <- mult_assoc in H;\n    repeat rewrite (mult_comm x _) in H;\n    repeat rewrite mult_assoc in H.\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/Mult/mult_ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7522308454749251}}
{"text": "Require 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_equalanglesreflexive : \n   forall A B C, \n   nCol A B C ->\n   CongA A B C A B C.\nProof.\nintros.\nassert (CongA A B C C B A) by (conclude lemma_ABCequalsCBA).\nassert (nCol C B A) by (conclude lemma_equalanglesNC).\nassert (CongA C B A A B C) by (conclude lemma_ABCequalsCBA).\nassert (CongA A B C A B C) by (conclude lemma_equalanglestransitive).\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_equalanglesreflexive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7522308435325181}}
{"text": "Require Import Arith.\n\nTheorem nat_ind_le : forall P : nat -> Prop,\n    P 0 -> (forall n, (forall m, m <= n -> P m) -> P (S n))\n    -> forall n, P n.\nProof.\n  intros P HP0 HPi.\n  set (Q n := forall m, m <= n -> P m).\n  assert (forall n : nat, Q n).\n    intros.\n    induction n.\n      unfold Q.\n      intros.\n      inversion H. exact HP0.\n\n      unfold Q.\n      intros.\n      apply le_lt_eq_dec in H.\n      destruct H as [Hl | Heq].\n        unfold lt in Hl. apply le_S_n in Hl.\n        apply IHn. exact Hl.\n\n        rewrite Heq.\n        apply HPi.\n        exact IHn.\n\n  intro.\n  apply (H n).\n  apply le_n.\nQed.\n\nLtac induction_le_nat n := let IHn := fresh \"IH\" n in \n  try intros until n; pattern n; apply nat_ind_le; clear n; [ | intros n IHn ].\n\n\nTheorem nat_ind_lt : forall P : nat -> Prop,\n    (forall n, (forall m, m < n -> P m) -> P n)\n    -> forall n, P n.\nProof.\n  intros P HPi.\n  set (Q n := forall m, m <= n -> P m).\n  assert (forall n : nat, Q n).\n    intros.\n    induction n.\n      unfold Q.\n      intros.\n      inversion H.\n      apply HPi.\n      intros.\n      contradict H1.\n      apply lt_n_0.\n\n      unfold Q.\n      intros.\n      apply le_lt_eq_dec in H.\n      destruct H as [Hl | Heq].\n        unfold lt in Hl. apply le_S_n in Hl.\n        apply IHn. exact Hl.\n\n        rewrite Heq.\n        apply HPi.\n        intros.\n        apply le_S_n in H.\n        apply IHn. exact H.\n\n  intro.\n  apply (H n).\n  apply le_n.\nQed.\n\nLtac induction_lt_nat n := let IHn := fresh \"IH\" n in \n  try intros until n; pattern n; apply nat_ind_lt; clear n; intros n IHn.\n\n\n\nTheorem nat_pred_interval_dec : forall P : nat -> Prop, (forall n, {P n} + {~ P n})\n    -> forall n m, {exists k, n <= k < m /\\ P k} + {forall k, n <= k < m -> ~ P k}.\nProof.\n  intros.\n  induction m.\n    right.\n    intros.\n    destruct H0.\n    inversion H1.\n\n    destruct (le_lt_dec n m) as [Hnm | Hmn].\n    (* Case where n <= m *)\n    destruct IHm as [Heg | Hnall].\n      left.\n      destruct Heg as [k [Hnkm HPk]].\n      exists k.\n      split. destruct Hnkm as [Hnk Hkm]. split. assumption.\n      apply le_S. apply Hkm. assumption.\n\n      destruct (H m) as [HPm | HnPm].\n      left. exists m.\n      split. split. assumption. apply le_n. assumption.\n\n      right.\n      intros.\n      destruct H0 as [Hnk Hkm].\n      apply le_lt_eq_dec in Hkm.\n      destruct Hkm as [Hkm | Hkm].\n        apply Hnall. split. assumption.\n        apply lt_S_n; assumption.\n\n        inversion Hkm. assumption.\n\n\n    (* Case where m < n *)\n    right. clear H. clear IHm.\n    intros. exfalso.\n    assert (n <= m). destruct H as [Hnk Hkm].\n    apply le_S_n in Hkm.\n    apply le_trans with (m := k); assumption.\n    (* SearchAbout (_<=_ -> ~_<_). *)\n    revert Hmn. apply le_not_lt. assumption.\nQed.\n\nTheorem exists__not_forall_not : forall (S : Set) (P Q : S -> Prop),\n    (exists x : S, Q x /\\ P x) -> ~ forall x : S, Q x -> ~ P x.\nProof.\n  intros.\n  intro.\n  destruct H as [x [Qx Px]].\n  unfold not in H0. apply H0 with (x := x) ; assumption.\nQed.\n", "meta": {"author": "klao", "repo": "coq-learning", "sha": "e408913099774f2390bd5541c1d438d3c835d803", "save_path": "github-repos/coq/klao-coq-learning", "path": "github-repos/coq/klao-coq-learning/coq-learning-e408913099774f2390bd5541c1d438d3c835d803/primes/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7521238668689508}}
{"text": "(* This file contains a definition of a simple imperative programming\n   language together with its operational semantics. Most definitions\n   and lemma statements were translated into Coq from Isabelle/HOL\n   statements present in the book:\n\n   T. Nipkow, G. Klein, Concrete Semantics with Isabelle/HOL.\n\n   This gives a rough idea of how the automation provided by \"hammer\"\n   and our reconstruction tactics compares to the automation available\n   in Isabelle/HOL. *)\n\nFrom Hammer Require Import Hammer Reconstr.\n\nRequire Import String.\nRequire Import Arith.PeanoNat.\nRequire Import Bool.Bool.\n\nInductive aexpr :=\n| Nval : nat -> aexpr\n| Vval : string -> aexpr\n| Aplus : aexpr -> aexpr -> aexpr.\n\nDefinition state := string -> nat.\n\nFixpoint aval (s : state) (e : aexpr) :=\n  match e with\n  | Nval n => n\n  | Vval x => s x\n  | Aplus x y => aval s x + aval s y\n  end.\n\nFixpoint plus (e1 e2 : aexpr) :=\n  match e1, e2 with\n  | Nval n1, Nval n2 => Nval (n1 + n2)\n  | Nval 0, _ => e2\n  | _, Nval 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  induction e1; sauto.\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.reasy (@lem_aval_plus) Reconstr.Empty.\nQed.\n\nInductive bexpr :=\n| Bval : bool -> bexpr\n| Bnot : bexpr -> bexpr\n| Band : bexpr -> bexpr -> bexpr\n| Bless : aexpr -> aexpr -> bexpr.\n\nFixpoint bval (s : state) (e : bexpr) :=\n  match e with\n  | Bval b => b\n  | Bnot e1 => negb (bval s e1)\n  | Band e1 e2 => bval s e1 && bval s e2\n  | Bless a1 a2 => aval s a1 <? aval s a2\n  end.\n\nFixpoint not (e : bexpr) :=\n  match e with\n  | Bval true => Bval false\n  | Bval false => Bval true\n  | _ => Bnot e\n  end.\n\nFixpoint and (e1 e2 : bexpr) :=\n  match e1, e2 with\n  | Bval true, _ => e2\n  | _, Bval true => e1\n  | Bval false, _ => Bval false\n  | _, Bval false => Bval false\n  | _, _ => Band e1 e2\n  end.\n\nDefinition less (a1 a2 : aexpr) :=\n  match a1, a2 with\n  | Nval n1, Nval n2 => Bval (n1 <? n2)\n  | _, _ => Bless a1 a2\n  end.\n\nFixpoint bsimp (e : bexpr) :=\n  match e with\n  | Bnot e1 => not (bsimp e1)\n  | Band e1 e2 => and (bsimp e1) (bsimp e2)\n  | Bless a1 a2 => less a1 a2\n  | _ => e\n  end.\n\nLemma lem_bval_not : forall s e, bval s (not e) = negb (bval s e).\nProof.\n  induction e; sauto.\nQed.\n\nLemma lem_bval_and : forall s e1 e2, bval s (and e1 e2) = bval s e1 && bval s e2.\nProof.\n  induction e1; sauto.\nQed.\n\nLemma lem_bval_less : forall s a1 a2, bval s (less a1 a2) = (aval s a1 <? aval s a2).\nProof.\n  induction a1; sauto.\nQed.\n\nLemma lem_bval_bsimp : forall s e, bval s (bsimp e) = bval s e.\nProof.\n  induction e; sauto.\n  - Reconstr.reasy (@lem_bval_not) Reconstr.Empty.\n  - Reconstr.reasy (@lem_bval_and) Reconstr.Empty.\n  - ycrush.\n  - ycrush.\nQed.\n\nInductive cmd :=\n| Skip : cmd\n| Assign : string -> aexpr -> cmd\n| Seq : cmd -> cmd -> cmd\n| If : bexpr -> cmd -> cmd -> cmd\n| While : bexpr -> cmd -> cmd.\n\nDefinition update (s : state) x v y := if string_dec x y then v else s y.\n\nInductive big_step : cmd * state -> state -> Prop :=\n| SkipSem : forall s, big_step (Skip, s) s\n| AssignSem : forall s x a, big_step (Assign x a, s) (update s x (aval s a))\n| SeqSem : forall c1 c2 s1 s2 s3, big_step (c1, s1) s2 -> big_step (c2, s2) s3 ->\n                                  big_step (Seq c1 c2, s1) s3\n| IfTrue : forall b c1 c2 s s', bval s b = true -> big_step (c1, s) s' ->\n                                big_step (If b c1 c2, s) s'\n| IfFalse : forall b c1 c2 s s', bval s b = false -> big_step (c2, s) s' ->\n                                 big_step (If b c1 c2, s) s'\n| WhileFalse : forall b c s, bval s b = false ->\n                             big_step (While b c, s) s\n| WhileTrue : forall b c s1 s2 s3,\n    bval s1 b = true -> big_step (c, s1) s2 -> big_step (While b c, s2) s3 ->\n    big_step (While b c, s1) s3.\n\nNotation \"A ==> B\" := (big_step A B) (at level 80, no associativity).\n\nLemma lem_seq_assoc : forall c1 c2 c3 s s', (Seq c1 (Seq c2 c3), s) ==> s' <->\n                                            (Seq (Seq c1 c2) c3, s) ==> s'.\nProof.\n  scrush. (* > 2s *)\nQed.\n\nDefinition equiv_cmd (c1 c2 : cmd) := forall s s', (c1, s) ==> s' <-> (c2, s) ==> s'.\n\nNotation \"A ~~ B\" := (equiv_cmd A B) (at level 70, no associativity).\n\nLemma lem_unfold_loop : forall b c, While b c ~~ If b (Seq c (While b c)) Skip.\nProof.\n  unfold equiv_cmd; intros; split; intro H; inversion H; ycrush.\nQed.\n\nLemma lem_while_cong_aux : forall b c c' s s', (While b c, s) ==> s' -> c ~~ c' ->\n                                               (While b c', s) ==> s'.\nProof.\n  assert (forall p s', p ==> s' -> forall b c c' s, p = (While b c, s) -> c ~~ c' -> (While b c', s) ==> s').\n  intros p s' H.\n  induction H; sauto.\n  - ycrush.\n  - unfold equiv_cmd in *; ycrush.\n  - eauto.\nQed.\n\nLemma lem_while_cong : forall b c c', c ~~ c' -> While b c ~~ While b c'.\nProof.\n  Reconstr.reasy (@lem_while_cong_aux) (@equiv_cmd).\nQed.\n\nLemma lem_big_step_deterministic :\n  forall c s s1 s2, (c, s) ==> s1 -> (c, s) ==> s2 -> s1 = s2.\nProof.\n  intros c s s1 s2 H.\n  revert s2.\n  induction H; try yelles 1.\n  scrush.\n  intros s0 H2; inversion H2; scrush.\nQed.\n\nInductive small_step : cmd * state -> cmd * state -> Prop :=\n| AssignSemS : forall x a s, small_step (Assign x a, s) (Skip, update s x (aval s a))\n| SeqSemS1 : forall c s, small_step (Seq Skip c, s) (c, s)\n| SeqSemS2 : forall c1 c2 s c1' s', small_step (c1, s) (c1', s') ->\n                                    small_step (Seq c1 c2, s) (Seq c1' c2, s')\n| IfTrueS : forall b c1 c2 s, bval s b = true ->\n                              small_step (If b c1 c2, s) (c1, s)\n| IfFalseS : forall b c1 c2 s, bval s b = false ->\n                               small_step (If b c1 c2, s) (c2, s)\n| WhileS : forall b c s, small_step (While b c, s) (If b (Seq c (While b c)) Skip, s).\n\nNotation \"A --> B\" := (small_step A B) (at level 80, no associativity).\n\nRequire Import Relations.\n\nLtac pose_rt := pose @rt_step; pose @rt_refl; pose @rt_trans.\n\nDefinition small_step_star := clos_refl_trans (cmd * state) small_step.\n\nHint Unfold small_step_star : yhints.\n\nNotation \"A -->* B\" := (small_step_star A B) (at level 80, no associativity).\n\nLemma lem_small_step_deterministic :\n  forall c s s1 s2, (c, s) --> s1 -> (c, s) --> s2 -> s1 = s2.\nProof.\n  intros c s s1 s2 H.\n  revert s2.\n  induction H; try yelles 1.\n  scrush.\n  intros s2 H2; inversion H2; scrush.\nQed.\n\nLemma lem_star_seq2 : forall c1 c2 s c1' s', (c1, s) -->* (c1', s') ->\n                                             (Seq c1 c2, s) -->* (Seq c1' c2, s').\nProof.\n  assert (forall p1 p2, p1 -->* p2 ->\n                        forall c1 c2 s c1' s', p1 = (c1, s) -> p2 = (c1', s') ->\n                                               (Seq c1 c2, s) -->* (Seq c1' c2, s')).\n  intros p1 p2 H.\n  induction H as [ | | ? y ]; try yelles 1.\n  pose_rt; pose SeqSemS2; scrush.\n  intros c1 c2 s c1' s' H1 H2; subst.\n  destruct y as [ c0 s0 ].\n  assert ((Seq c1 c2, s) -->* (Seq c0 c2, s0)) by scrush.\n  assert ((Seq c0 c2, s0) -->* (Seq c1' c2, s')) by scrush.\n  pose_rt; scrush.\n  scrush.\nQed.\n\nLemma lem_seq_comp : forall c1 c2 s1 s2 s3, (c1, s1) -->* (Skip, s2) -> (c2, s2) -->* (Skip, s3) ->\n                                            (Seq c1 c2, s1) -->* (Skip, s3).\nProof.\n  intros c1 c2 s1 s2 s3 H1 H2.\n  assert ((Seq c1 c2, s1) -->* (Seq Skip c2, s2)).\n  pose lem_star_seq2; scrush.\n  assert ((Seq Skip c2, s2) -->* (c2, s2)).\n  pose_rt; scrush.\n  pose_rt; scrush.\nQed.\n\nLemma lem_big_to_small : forall p s', p ==> s' -> p -->* (Skip, s').\nProof.\n  intros p s' H.\n  induction H as [ | | | | | | b c s1 s2 ]; try yelles 1.\n  - Reconstr.reasy (@lem_seq_comp) Reconstr.Empty.\n  - pose_rt; pose IfTrueS; scrush.\n  - pose_rt; pose IfFalseS; scrush.\n  - pose_rt; pose WhileS; pose IfFalseS; ycrush.\n  - assert ((While b c, s1) -->* (Seq c (While b c), s1)) by\n        (pose_rt; pose WhileS; pose IfTrueS; ycrush).\n    assert ((Seq c (While b c), s1) -->* (Seq Skip (While b c), s2)) by\n        Reconstr.reasy (@lem_star_seq2) Reconstr.Empty.\n    pose_rt; pose SeqSemS1; ycrush.\nQed.\n\nLemma lem_small_to_big_aux : forall p p', p --> p' -> forall s, p' ==> s -> p ==> s.\nProof.\n  intros p p' H.\n  induction H; sauto; try yelles 1.\n  Reconstr.reasy (@lem_unfold_loop) (@equiv_cmd).\nQed.\n\nLemma lem_small_to_big_aux_2 : forall p p', p -->* p' -> forall s, p' ==> s -> p ==> s.\nProof.\n  intros p p' H.\n  induction H; sauto.\n  Reconstr.reasy (@lem_small_to_big_aux) Reconstr.Empty.\nQed.\n\nLemma lem_small_to_big : forall p s, p -->* (Skip, s) -> p ==> s.\nProof.\n  assert (forall p p', p -->* p' -> forall s, p' = (Skip, s) -> p ==> s).\n  intros p p' H.\n  induction H; sauto.\n  - ycrush.\n  - Reconstr.rsimple (@lem_small_to_big_aux_2) (@small_step_star).\n  - ycrush.\nQed.\n\nCorollary cor_big_iff_small : forall p s, p ==> s <-> p -->* (Skip, s).\nProof.\n  Reconstr.reasy (@lem_small_to_big, @lem_big_to_small) Reconstr.Empty.\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/ASTactic/coqhammer/examples/imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7521238640264487}}
{"text": "Inductive list (A:Set) :Set := \n| Nil  : list A\n| Cons : A -> list A -> list A.\n\nPrint list.\nCheck Nil.\nCheck Cons.\n\nCheck list_ind.\n\nArguments Nil [A].\nPrint Implicit Nil.\nCheck Nil.\nArguments Cons [A].\nCheck Cons.\nPrint Implicit Cons.\n\n\nCheck list_ind.\n\n\nFixpoint len {A} (l: list A) :=\n  match l with\n    Nil => 0\n  | Cons _ xs => 1 + len xs\nend.\n\nCheck len.\n\nFixpoint app {A} (l1 l2: list A) :=\n  match l1 with\n    Nil => l2\n  | Cons x xs => Cons x (app xs l2)\nend.\n\nCheck app.\n\nTheorem length_app: forall A (l1 l2: list A), len (app l1 l2) = len l1 + len l2.\nProof.\ninduction l1.\n- simpl.\n  reflexivity.\n- simpl.\n  intros.\n  (*specialize (IHl1 l2). rewrite IHl1. reflexivity.\n  rewrite  IHl1; reflexivity.*)\n  f_equal. apply IHl1.\nQed.\n\n\nInductive lista : Set -> Type :=\n| Nila  : forall (A:Set), lista A\n| Consa : forall (A:Set), A -> lista A -> lista A.\n\nCheck Consa.\n\n\nCheck lista_ind.\n\n\nFixpoint lena (A:Set) (l:lista A): nat :=\nmatch l with\n| Nila A => 0\n| Consa A a t => 1 + lena A t  \nend.\n\nLemma lenaGEO: forall (A:Set)(l:lista A), lena A l >=0.\nProof.\ninduction l.\nsimpl.\nconstructor.\nsimpl.\nconstructor.\nauto.\nQed.\n\n\nLemma lenaGEOnat: forall (l:lista nat), lena nat l >=0.\nProof.\ninduction l.\nsimpl.\nconstructor.\nsimpl.\nconstructor.\nauto.\nQed.\n\nPrint lenaGEOnat.\n\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/Slajdy19/PlikiCoqa/lista.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.7521238557093285}}
{"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 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(*     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; 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 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. 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 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.\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].\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\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) => //= ? ? ->.\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": "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/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7521063038816247}}
{"text": "Require Import Utf8.\nRequire Import GroupDefinition.\nRequire Import Setoid.\n\n(* The direct product of two groups is a group. *)\n\nDefinition GroupProduct_op\n    {G : Set} {g_op : SemiGroupOp G} {g_i : GroupInv G} {g_e: G} `{@Group G g_op g_i g_e}\n    {H : Set} {h_op : SemiGroupOp H} {h_i : GroupInv H} {h_e: H} `{@Group H h_op h_i h_e}\n    : SemiGroupOp (prod G H) := fun (a: prod G H) (b: prod G H) =>\n  match a, b with\n  | (x, y), (s, t) => (g_op x s, h_op y t)\n  end.\n\nDefinition GroupProduct_i\n    {G : Set} {g_op : SemiGroupOp G} {g_i : GroupInv G} {g_e: G} `{@Group G g_op g_i g_e}\n    {H : Set} {h_op : SemiGroupOp H} {h_i : GroupInv H} {h_e: H} `{@Group H h_op h_i h_e}\n    : GroupInv (prod G H) := fun (a: prod G H) =>\n  match a with\n  | (x, y) => (g_i x, h_i y)\n  end.\n\nInstance GroupProduct\n    {G : Set} {g_op : SemiGroupOp G} {g_i : GroupInv G} {g_e: G} (P : @Group G g_op g_i g_e)\n    {H : Set} {h_op : SemiGroupOp H} {h_i : GroupInv H} {h_e: H} (Q : @Group H h_op h_i h_e)\n    : (@Group\n        (prod G H)\n        (@GroupProduct_op G g_op g_i g_e P H h_op h_i h_e Q)\n        (@GroupProduct_i G g_op g_i g_e P H h_op h_i h_e Q)\n        (g_e, h_e)\n    ).\nProof.\n  repeat split.\n  intros a b c.\n  compute.\n  destruct a.\n  destruct b.\n  destruct c.\n  repeat rewrite (@sg_assoc G g_op _).\n  repeat rewrite (@sg_assoc H h_op _).\n  reflexivity.\n  intros a.\n  compute.\n  destruct a.\n  rewrite (@g_right_identity G g_op _).\n  rewrite (@g_right_identity H h_op _).\n  reflexivity.\n  assumption.\n  assumption.\n  intros a.\n  compute.\n  destruct a.\n  rewrite (@g_right_inverse G g_op g_i _ _).\n  rewrite (@g_right_inverse H h_op h_i _ _).\n  reflexivity.\nQed.\n\nDeclare Scope product_scope.\nDelimit Scope product_scope with product.\nNotation \"A × B\" := (GroupProduct A B) (at level 30, right associativity) : product_scope.\nBind Scope product_scope with Group.\n\n(* The direct product of two abelian groups is an abelian group. *)\n\nInstance AbelianGroupProduct\n    {G : Set} {g_op : SemiGroupOp G} {g_i : GroupInv G} {g_e: G} (P : @AbelianGroup G g_op g_i g_e)\n    {H : Set} {h_op : SemiGroupOp H} {h_i : GroupInv H} {h_e: H} (Q : @AbelianGroup H h_op h_i h_e)\n    : (@AbelianGroup\n        (prod G H)\n        (@GroupProduct_op G g_op g_i g_e (AsGroup P) H h_op h_i h_e (AsGroup Q))\n        (@GroupProduct_i G g_op g_i g_e (AsGroup P) H h_op h_i h_e (AsGroup Q))\n        (g_e, h_e)\n    ).\nProof.\n  repeat split.\n  intros a b c.\n  compute.\n  destruct a.\n  destruct b.\n  destruct c.\n  repeat rewrite (@sg_assoc G g_op _).\n  repeat rewrite (@sg_assoc H h_op _).\n  reflexivity.\n  intros a.\n  compute.\n  destruct a.\n  rewrite (@g_right_identity G g_op _).\n  rewrite (@g_right_identity H h_op _).\n  reflexivity.\n  exact abelian_groups_are_groups.\n  exact abelian_groups_are_groups.\n  intros a.\n  compute.\n  destruct a.\n  rewrite (@g_right_inverse G g_op g_i _ _).\n  rewrite (@g_right_inverse H h_op h_i _ _).\n  reflexivity.\n  intros a b.\n  compute.\n  destruct a.\n  destruct b.\n  rewrite (@ag_commutative G g_op g_i g_e).\n  rewrite (@ag_commutative H h_op h_i h_e).\n  reflexivity.\n  assumption.\n  assumption.\nQed.\n\nDeclare Scope abelian_product_scope.\nDelimit Scope abelian_product_scope with abelian_product.\nNotation \"A × B\" := (AbelianGroupProduct A B) (at level 30, right associativity) : abelian_product_scope.\nBind Scope abelian_product_scope with AbelianGroup.\n", "meta": {"author": "Echogene", "repo": "Oilar", "sha": "61383eee23d3b798e5dcb128dfd9fe5452f324ad", "save_path": "github-repos/coq/Echogene-Oilar", "path": "github-repos/coq/Echogene-Oilar/Oilar-61383eee23d3b798e5dcb128dfd9fe5452f324ad/GroupTheory/DirectProduct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.752090345519053}}
{"text": "Require Export section_03_nat.\n\n(* Section 4. More inductive types *)\n\n(** Analogous to the type of natural numbers, many types can be specified as\n    inductive types. In this lecture we introduce some further examples of \n    inductive types: the unit type, the empty type, the booleans, coproducts,\n    dependent pair types, and cartesian products. We also introduce the type of\n    integers. *)\n\n(** Section 4.2. The unit type *)\n\n(** The unit type is an inductive type generated by a single point called star.\n    *)\n\nInductive unit : Type :=\n| star : unit.\n\n(** Section 4.3. The empty type *)\n\n(** The empty type is an inductive type with no constructors at all. *)\n\nInductive empty : Type := .\n\n(** The induction principle gives a section of every family of types over the\n    empty type. In other words, anything follows from falso: ex falso \n    quodlibet. *)\n\nDefinition ex_falso {B : empty -> Type} : forall x, B x.\nProof.\n  intro x.\n  induction x.\nDefined.\n\nDefinition ex_falso_map {A} : empty -> A := ex_falso.\n\n(** We use the empty type to define the negation of an arbitrary type. *)\n\nDefinition neg (A : Type) : Type := A -> empty.\n\n(** Section 4.4. The booleans *)\n\n(** The type of booleans is an inductive type generated by two constructors:\n    true and false. *)\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\n(** Using the induction principle of the booleans, we can define some of the\n    boolean operations. We show here how to define negation, conjunction, and\n    disjunction as boolean operators. Some other boolean operators are defined\n    in the exercises. *)\n\nDefinition negb (b : bool) : bool.\nProof.\n  induction b.\n  - exact false.\n  - exact true.\nDefined.\n\nDefinition andb (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact true.\n    * exact false.\n  - induction b'.\n    * exact false.\n    * exact false.\nDefined.\n\nDefinition orb (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact true.\n    * exact true.\n  - induction b'.\n    * exact true.\n    * exact false.\nDefined.\n\n(** Section 4.5. Coproducts and the type of integers *)\n\n(** The coproduct of two types is defined as an inductive type with \n    constructors\n\n    inl : A -> coprod A B\n    inr : B -> coprod A B. *)\n\nInductive coprod (A B : Type) : Type :=\n| inl : A -> coprod A B\n| inr : B -> coprod A B.\n\n(** We make the arguments A and B of inl and inr implicit. *)\n\nArguments inl {A B}.\nArguments inr {A B}.\n\n(** Using coproducts, the type of natural numbers, and the unit type we now\n    construct the type of integers. *)\n\nDefinition Z : Type := coprod ℕ (coprod unit ℕ).\n\n(** We define some integers close to zero. *)\n\nDefinition zero_Z : Z := inr (inl star).\n\nDefinition one_Z : Z := inr (inr zero_ℕ).\n\nDefinition two_Z : Z := inr (inr one_ℕ).\n\nDefinition neg_one_Z : Z := inl zero_ℕ.\n\nDefinition neg_two_Z : Z := inl one_ℕ.\n\n(** Now we extend the successor function on the natural numbers to a successor\n    function on the integers. *)\n\nDefinition succ_Z (k : Z) : Z.\nProof.\n  destruct k as [n | x].\n  - destruct n.\n    * exact zero_Z.\n    * exact (inl n).\n  - destruct x as [x | n].\n    * exact one_Z.\n    * exact (inr (inr (succ_ℕ n))).\nDefined.\n\n(** Section 4.6. Dependent pair types *)\n\n(** Given a family B of types over A, we can for the type of pairs (x,y), \n    consisting of a term x:A and a term y:B(x). Note that the type of the term \n    y depends on the term x, hence we call such pairs dependent pairs.\n\n    More traditionally, the type of dependent pair types is called the\n    Sigma-type. It is defined as an inductive type, of which the pairs are the\n    constructors. *)\n\nInductive Sigma (A : Type) (B : A -> Type) : Type :=\n| pair : forall x, B x -> Sigma A B.\n\n(** We make the arguments A and B of pair implicit. *)\n\nArguments pair {A B}.\n\n(** Using the induction principle, we define the two projection functions on\n    a dependent pair type. *)\n\nDefinition pr1 {A : Type} {B : A -> Type} (x : Sigma A B) : A.\nProof.\n  induction x.\n  assumption.\nDefined.\n\nDefinition pr2 {A : Type} {B : A -> Type} (x : Sigma A B) : B (pr1 x).\nProof.\n  induction x.\n  assumption.\nDefined.\n\n(** Section 4.8. Cartesian products *)\n\n(** The cartesian product of two types is defined as a special case of the\n    dependent pair type. *)\n\nDefinition prod (A B : Type) : Type := Sigma A (fun x => B).\n\n(** Exercises for section 4 *)\n\n(** Exercise 4.2 *)\n\n(** Exercise 4.2.a *)\n\nLemma double_neg_elim_decidable (A : Type) :\n  coprod A (neg A) -> (neg (neg A) -> A).\nProof.\n  intro x.\n  induction x.\n  - now apply const.\n  - intro y. now apply ex_falso_map.\nDefined.\n\n(** Exercise 4.2.b *)\n\nLemma triple_neg_elim (A : Type) :\n  neg (neg (neg A)) -> neg A.\nProof.\n  intros f a.\n  apply ex_falso_map.\n  now apply f.\nDefined.\n\n(** Exercise 4.3 *)\n\nDefinition xorb (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact false.\n    * exact true.\n  - induction b'.\n    * exact true.\n    * exact false.\nDefined.\n\nDefinition impliesb (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact true.\n    * exact false.\n  - induction b'.\n    * exact true.\n    * exact true.\nDefined.\n\nDefinition iffb (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact true.\n    * exact false.\n  - induction b'.\n    * exact false.\n    * exact true.\nDefined.\n\nDefinition peirce_arrow (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact false.\n    * exact false.\n  - induction b'.\n    * exact false.\n    * exact true.\nDefined.\n\nDefinition sheffer_stroke (b b' : bool) : bool.\nProof.\n  induction b.\n  - induction b'.\n    * exact false.\n    * exact true.\n  - induction b'.\n    * exact true.\n    * exact true.\nDefined.\n\n(** Exercise 4.4 *)\n\nDefinition pred_Z (k : Z) : Z.\nProof.\n  destruct k as [n | x].\n  - exact (inl (succ_ℕ n)).\n  - destruct x as [x | n].\n    * exact neg_one_Z.\n    * destruct n.\n      ** exact zero_Z.\n      ** exact (inr (inr n)).\nDefined.\n\n(** Exercise 4.5 *)\n\nDefinition add_Z (k l : Z) : Z.\nProof.\n  destruct l as [n | x].\n  - induction n as [|n s].\n    * exact (pred_Z k).\n    * exact (pred_Z s).\n  - destruct x as [x | n].\n    * exact k.\n    * induction n as [|n s].\n      ** exact (succ_Z k).\n      ** exact (succ_Z s).\nDefined.\n\nDefinition neg_Z (k : Z) : Z.\nProof.\n  destruct k as [n | x].\n  - exact (inr (inr n)).\n  - destruct x as [x | n].\n    * exact (inr (inl x)).\n    * exact (inl n).\nDefined.\n\nDefinition mul_Z (k l : Z) : Z.\nProof.\n  destruct l as [n | x].\n  - induction n as [|n m].\n    * exact (neg_Z k).\n    * exact (add_Z m (neg_Z k)).\n  - destruct x as [x | n].\n    * exact zero_Z.\n    * induction n as [|n m].\n      ** exact k.\n      ** exact (add_Z m k).\nDefined.\n\n(** Exercise 4.6 *)\n\n(** The following is ill-formed. I don't know yet how to fix it.\n\nFixpoint Fibonacci_Z (k : Z) : Z :=\n  match k with\n  | inl n =>\n    match n with\n    | zero_ℕ => one_Z\n    | succ_ℕ m =>\n      match m with\n      | zero_ℕ => neg_one_Z\n      | succ_ℕ m' =>\n        add_Z (Fibonacci_Z (inl m)) (neg_Z (Fibonacci_Z (inl m')))\n      end\n    end\n  | inr x =>\n    match x with\n    | inl x => zero_Z\n    | inr n => inr (inr (Fibonacci (succ_ℕ n)))\n    end\n  end.\n *)\n\n(*\nProof.\n  destruct k as [n | x].\n  - induction n as [|n f].\n    * exact one_Z.\n    * exact (neg_Z !!!\n  - destruct x as [x | n].\n    * exact zero_Z.\n    * exact (inr (inr (Fibonacci (succ_ℕ n)))).\nDefined.\n *)\n\n(** Exercise 4.7 *)\n\nDefinition true' : coprod unit unit := inl star.\n\nDefinition false' : coprod unit unit := inr star.\n\nDefinition ind_coprod_unit_unit {P : coprod unit unit -> Type} (p1 : P true') (p0 : P false') : forall x, P x.\nProof.\n  intro x.\n  destruct x as [x | x].\n  destruct x. assumption.\n  destruct x. assumption.\nDefined.\n\n(** Exercise 4.8 *)\n\n(** Exercise 4.8.a *)\n\nInductive list (A : Type) : Type :=\n| nil : list A\n| cons : A -> list A -> list A.\n\nArguments nil {A}.\nArguments cons {A}.\n\nDefinition in_list {A} (a : A) : list A := cons a nil.\n\n(** Exercise 4.8.b *)\n\nDefinition fold_list {A B} (b : B) (m : A -> B -> B) : list A -> B.\nProof.\n  intro l.\n  induction l as [|a l' b'].\n  - exact b.\n  - exact (m a b').\nDefined.\n\n(** Exercise 4.8.c *)\n\nDefinition length_list {A} : list A -> ℕ.\nProof.\n  apply fold_list.\n  - exact zero_ℕ.\n  - exact (const succ_ℕ).\nDefined.\n\n(** Exercise 4.8.d *)\n\nDefinition sum_list_ℕ : list ℕ -> ℕ.\nProof.\n  apply fold_list.\n  - exact zero_ℕ.\n  - exact add_ℕ.\nDefined.\n\n(** Exercise 4.8.e *)\n\nDefinition concat_list {A} : list A -> (list A -> list A).\nProof.\n  apply (@fold_list A (list A -> list A)).\n  - exact (fun l => l).\n  - intro a. exact (comp (cons a)).\nDefined.\n\n(** Exercise 4.8.f *)\n\nDefinition flatten_list {A} : list (list A) -> list A.\nProof.\n  apply fold_list.\n  - exact nil.\n  - exact concat_list.\nDefined.\n\n(** Exercise 4.8.g *)\n\nDefinition reverse_list {A} : list A -> list A.\nProof.\n  intro l.\n  induction l as [|a l r].\n  - exact nil.\n  - exact (concat_list r (in_list a)).\nDefined.\n", "meta": {"author": "HoTT-Intro", "repo": "Coq", "sha": "f91193b5de1c551463c327b1c1e2fe50a1fcf841", "save_path": "github-repos/coq/HoTT-Intro-Coq", "path": "github-repos/coq/HoTT-Intro-Coq/Coq-f91193b5de1c551463c327b1c1e2fe50a1fcf841/HoTT_Intro/section_04_inductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.752090335261881}}
{"text": "Require Import Utf8.\n\n\nDefinition Surjective {A B} (f : A -> B) :=\n  forall y, exists x, f x = y.\n\n\nSection Cantor.\n\n  Variable A : Type.\n  Variable f : A -> (A -> bool).\n\n  Definition diagb : A -> bool := λ x, negb (f x x).\n\n  Theorem Cantor_Theorem : forall x, f x ≠ diagb.\n  Proof.\n    intros x Eq.\n    assert (Eq': diagb x = f x x) by now rewrite Eq.\n    unfold diagb in Eq'.\n    now destruct (f x x).\n  Qed.\n\n  Corollary Cantor_Theorem_2 : ~Surjective f.\n  Proof.\n    firstorder using Cantor_Theorem.\n  Qed.\n\nEnd Cantor.\n", "meta": {"author": "imaxw", "repo": "coq-sandbox", "sha": "64735a52c9e66ad53eb7853ee97998e224e9a0a7", "save_path": "github-repos/coq/imaxw-coq-sandbox", "path": "github-repos/coq/imaxw-coq-sandbox/coq-sandbox-64735a52c9e66ad53eb7853ee97998e224e9a0a7/Cardinality/Diag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7520891923497827}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch05_bet_le.\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_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.\napply (@cong_dec Tn (Build_Tarski_neutral_dimensionless_with_decidable_point_equality Tn eq_dec)).\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_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.\napply (@bet_dec Tn (Build_Tarski_neutral_dimensionless_with_decidable_point_equality Tn eq_dec)).\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.\napply all_equiv__equiv.\nsimpl.\nunfold decidability_of_equality_of_points, decidability_of_congruence_of_points,\n        decidability_of_betweenness_of_points.\nassert (P:=cong_dec_eq_dec).\nassert (Q:=eq_dec_cong_dec).\nassert (R:=bet_dec_eq_dec).\nassert (S:=eq_dec_bet_dec).\nrepeat split; auto.\nQed.\n\nEnd Equivalence_between_decidability_properties_of_basic_relations.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/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.8933094060543488, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7520107654026652}}
{"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; induction Hle as [ | m Hm IHm].\n - exists 1,  1; ring.\n -  destruct IHm as [p' [q']].\n    destruct q'.\n   +  \n      assert (H3lep': 3 <= p') by omega.\n      exists (p' - 3), 2.\n      subst m.\n      replace (3 * (p' - 3) + 5 * 2) \n        with    (S (3 * 3 + 3 * (p' - 3)))\n        by  omega.\n      rewrite <- mult_plus_distr_l.\n      rewrite le_plus_minus_r; auto.\n   +   exists (p'+2), q'; rewrite H;  ring.\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/ch8_inductive_predicates/SRC/frobenius.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7520019040019779}}
{"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\nRequire Import ZArith.\n\nLemma Zlt_le_Zs : forall z z1 : Z, (Z.succ z <= z1)%Z -> (z < z1)%Z.\n\nProof. \nintros.\napply Z.lt_le_trans with (Z.succ z).\napply Zlt_succ.\nauto.\nQed.\n\nHint Resolve Zlt_le_Zs: real.\n\n\nLemma Zle_add_compatibility :\n forall z z1 z2 : Z, (z + z1 <= z2)%Z -> (z <= z2 - z1)%Z.\n\nProof.\nintros.\napply Zplus_le_reg_l with z1. \nrewrite Zplus_minus.\nrewrite Zplus_comm; auto.\nQed.\n\nHint Resolve Zle_add_compatibility: real.\n\n\n\n", "meta": {"author": "coq-community", "repo": "exact-real-arithmetic", "sha": "43bf40b6bfa71a1d1a2b17219c46c4081705c7fa", "save_path": "github-repos/coq/coq-community-exact-real-arithmetic", "path": "github-repos/coq/coq-community-exact-real-arithmetic/exact-real-arithmetic-43bf40b6bfa71a1d1a2b17219c46c4081705c7fa/Zarith_inegalites.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7519274999519874}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Indprop.\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\nPrint le.\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nPrint next_nat.\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\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\nInductive total_relation : nat -> nat -> Prop :=\n  | tr : forall n m, total_relation n m.\n\nInductive empty_relation : nat -> nat -> Prop := .\n\n(*optional (total_relation_not_partial)*)\nTheorem total_relation_not_a_partial_function :\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply (Hc 0).\n    - apply tr.\n    - apply tr. }\n  discriminate Nonsense. Qed.\n(*/optional (total_relation_not_partial)*)\n\n(*optional (empty_relation_partial)*)\nTheorem empty_relation_not_a_partial_function :\n  partial_function empty_relation.\nProof.\n  unfold partial_function. intros x y1 y2 H1 H2.\n  inversion H1. Qed.\n(*/optional (empty_relation_partial)*)\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\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  - apply Hnm.\n  - 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(*optional (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. apply Hnm.\n  - apply le_S. apply IHHm'o.\nQed.\n(*/optional (le_trans_hard_way)*)\n\n(*standard, optional (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. inversion Hmo. \n    + rewrite <- H0. apply Hnm.\n    + apply IHo'. apply H0. \nQed.  \n(*/standard, optional (lt_trans'')*)\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(*standard, optional (le_S_n)*)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros n m H. inversion H.\n  - apply le_n.\n  - apply le_Sn_le. apply H1.\nQed.\n(*/standard, optional (le_S_n)*)\n\n(*standard, optional (le_Sn_n)*)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  unfold not. induction n as [|n' IHn'].\n  - intro H. inversion H.\n  - intro H. apply IHn'. apply le_S_n. apply H.\nQed. \n(*/standard, optional (le_Sn_n)*)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(*standard, optional (le_not_symmetric)*)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold not. unfold symmetric. intros H.\n  assert (N: 1 <= 0 -> False).\n  { apply (le_Sn_n 0). }\n  apply N. apply H. apply le_S. apply le_n.\nQed.\n(*/standard, optional (le_not_symmetric)*)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(*standard, optional (le_antisymmetric)*)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric.\n  induction a as [|a'].\n  - (* a = 0 *)\n    intros b ab ba.\n    inversion ba as [E|].\n    reflexivity.\n  - (* a = S a' *)\n    intros b ab ba.\n    inversion ab as [E | b' H H'].\n    + (* a = b *)\n      reflexivity.\n    + (* a < b *)\n      cut (a' = b').\n      * intros E. rewrite E. reflexivity.\n      * apply IHa'. \n        { apply le_Sn_le. apply H. }\n        { apply le_S_n. rewrite H'. apply ba. }\nQed.\n(*/standard, optional (le_antisymmetric)*)\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\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n    - apply le_reflexive.\n    - split.\n      + apply le_antisymmetric.\n      + apply le_trans. Qed.\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\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    + apply rt_refl.\n    +\n      apply rt_trans with m. apply IHle. apply rt_step.\n      apply nn.\n  -\n    intro H. induction H.\n    + inversion H. apply le_S. apply le_n.\n    + apply le_n.\n    +\n      apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\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\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\n\n", "meta": {"author": "unisuke82", "repo": "SoftwareFoundation", "sha": "1911ed60b7dff597eac434734cb26d67162b6805", "save_path": "github-repos/coq/unisuke82-SoftwareFoundation", "path": "github-repos/coq/unisuke82-SoftwareFoundation/SoftwareFoundation-1911ed60b7dff597eac434734cb26d67162b6805/volume1/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7519274990056614}}
{"text": "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.\n\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nLemma add_0_r : forall n : nat, \n    n + 0 = n. \nProof. \n    Admitted. \n\nLemma add_0_l : forall n : nat, \n    0 + n = n. \nProof. \n    Admitted. \n\nTheorem n_leb_n_plus_m : forall n m : nat, \n    n <=? (n + m) = true. \nProof.\n    intros n m. \n    induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity. \n    Qed. \n\nTheorem plus_leb_compat_1 : forall n m p : nat, \n    n <=? m = true -> (p + n) <=? (p + m) = true. \nProof. \n    intros n m p. \n    intros H.\n    destruct n.\n    - rewrite <- H. destruct p. \n     + simpl. reflexivity.\n     + simpl. rewrite <- H. simpl. rewrite -> add_0_r. rewrite -> n_leb_n_plus_m. reflexivity.\n    - induction p as [| p' IHp'].\n     + rewrite -> add_0_l. rewrite -> add_0_l. rewrite -> H. reflexivity.\n     + simpl. rewrite -> IHp'. reflexivity.\n    Qed.\n\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/induction/exercises/plus_leb_compat_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7519274894354874}}
{"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(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Mathematical structures                                                 *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibOperation.\nGeneralizable Variables A B.\n\n\n(* ********************************************************************** *)\n(** * Monoids *)\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; lia.\n  Qed.\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", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibMonoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7518940056164589}}
{"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\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\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (len (append x y)) (plus (len x) (len y)).\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_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7518940001196434}}
{"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.\nRequire Import Group_definitions.\nSection group_trivialities.\nVariable U : Type.\nVariable Gr : Group U.\n\nLet G : Ensemble U := G_ U Gr.\n\nLet star : U -> U -> U := star_ U Gr.\n\nLet inv : U -> U := inv_ U Gr.\n\nLet e : U := e_ U Gr.\n\nDefinition G0 : forall a b : U, In U G a -> In U G b -> In U G (star a b) :=\n  G0_ U Gr.\n\nDefinition G1 : forall a b c : U, star a (star b c) = star (star a b) c :=\n  G1_ U Gr.\n\nDefinition G2a : In U G e := G2a_ U Gr.\n\nDefinition G2b : forall a : U, star e a = a := G2b_ U Gr.\n\nDefinition G2c : forall a : U, star a e = a := G2c_ U Gr.\n\nDefinition G3a : forall a : U, In U G a -> In U G (inv a) := G3a_ U Gr.\n\nDefinition G3b : forall a : U, star a (inv a) = e := G3b_ U Gr.\n\nDefinition G3c : forall a : U, star (inv a) a = e := G3c_ U Gr.\nHint Resolve G1.\nHint Resolve G2a G2b G2c.\nHint Resolve G3a G3b G3c.\nHint Resolve G0.\n\nTheorem triv1 : forall a b : U, star (inv a) (star a b) = b.\nintros a b; try assumption.\nrewrite (G1 (inv a) a b); auto.\nrewrite G3c; auto.\nQed.\n\nTheorem triv2 : forall a b : U, star (star b a) (inv a) = b.\nintros a b; try assumption.\nrewrite <- (G1 b a (inv a)); auto.\nrewrite (G3b a); auto.\nQed.\n\nTheorem resolve : forall a b : U, star b a = e -> b = inv a.\nintros a b H'1.\ncut (star (star b a) (inv a) = inv a).\nrewrite <- (G1 b a (inv a)); auto.\nrewrite (G3b a); auto.\nrewrite (G2c b); auto.\nrewrite H'1.\nrewrite (G2b (inv a)); auto.\nQed.\n\nTheorem self_inv : e = inv e.\napply resolve; auto.\nQed.\n\nTheorem inv_star : forall a b : U, star (inv b) (inv a) = inv (star a b).\nintros a b.\napply resolve.\nrewrite <- (G1 (inv b) (inv a) (star a b)).\nrewrite (G1 (inv a) a b).\nrewrite (G3c a).\nrewrite (G2b b); auto.\nQed.\n\nTheorem cancellation : forall a b : U, star a b = a -> b = e.\nintros a b H'.\ncut (star (inv a) (star a b) = b).\nrewrite H'.\nrewrite (G3c a); auto.\nrewrite (G1 (inv a) a b).\nrewrite (G3c a); auto.\nQed.\n\nTheorem inv_involution : forall a : U, a = inv (inv a).\nintro a; apply resolve; auto.\nQed.\nEnd group_trivialities.\nHint Resolve G1.\nHint Resolve G2a G2b G2c.\nHint Resolve G3a G3b G3c.\nHint Resolve G0.\nHint Resolve triv1 triv2 resolve self_inv inv_star inv_involution.\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/gr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7518939963358653}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 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/goal33conj144_coqofml_VzbANu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7518762589124579}}
{"text": "Require Import Coq.Init.Prelude.\n\nInductive prop :=\n| Nil\n| And (_:Prop) (_ : prop)\n| Exis {T : Type} (_ : T -> prop).\n\nFixpoint interp_prop (p : prop) :=\n  match p with\n  | Nil => True\n  | And A p => A /\\ interp_prop p\n  | Exis f => exists x, interp_prop (f x)\n  end.\n\nFixpoint uncurry_prop (p : prop) (Q : Prop) :=\n  match p with\n  | Nil => Q\n  | And A p => A -> uncurry_prop p Q\n  | Exis f => forall x, uncurry_prop (f x) Q\n  end.\n\nLemma uncurry_prop_and_r xs (P Q : Prop) : P -> uncurry_prop xs Q -> uncurry_prop xs (P /\\ Q).\nProof. revert Q; revert P; induction xs; intros; cbn in *; eauto. Qed.\nLemma uncurry_prop_exists_r xs {T : Type} (P : T -> Prop) (x : T) : uncurry_prop xs (P x) -> uncurry_prop xs (exists x, P x).\nProof. revert dependent P; induction xs; intros; cbn in *; eauto. Qed.\nLemma uncurry_interp_prop p : uncurry_prop p (interp_prop p).\nProof. induction p; cbn in *; intros; eauto using uncurry_prop_and_r, uncurry_prop_exists_r. Qed.\n\nFixpoint Fex (t_prev : unit) (n : nat) : prop :=\n  match n with\n  | O => Nil\n  | S n => Exis (fun t:unit => And (t = t_prev) (Fex t n))\n  end.\n\nFixpoint fex (t_prev : unit) (n : nat) : Prop :=\n  match n with\n  | O => True\n  | S n => exists t:unit, t = t_prev /\\ fex t n\n  end.\n\nGoal fex tt 10000.\n  Time (\n    let n := match goal with [ |- fex tt ?n ] => n end in\n    let p := constr:(Fex tt n) in\n    let p := (eval cbv in p) in\n    let pf := constr:(uncurry_interp_prop p) in\n    let t := type of pf in\n    let t := (eval cbv [uncurry_prop interp_prop] in t) in\n    refine (let H : t := pf in _ )).\n  Time clearbody H.\n  Time eapply H.\n  Time all: exact eq_refl.\nTime Qed.\n(*\nFinished transaction in 5.965 secs (5.375u,0.57s) (successful)\nFinished transaction in 0.001 secs (0.u,0.s) (successful)\nFinished transaction in 87.529 secs (87.247u,0.006s) (successful)\nFinished transaction in 89.998 secs (89.667u,0.073s) (successful)\nFinished transaction in 42.641 secs (42.496u,0.006s) (successful)\n*)\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/big_ex_10000.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7518762581827326}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.suma.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection consecutive_interior_angles_alternate_interior_angles.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma consecutive_interior__alternate_interior :\n   consecutive_interior_angles_postulate -> alternate_interior_angles_postulate.\nProof.\n  intros cia A B C D Hts HPar.\n  destruct (segment_construction D C C D) as [D' []].\n  apply suppa2__conga123 with A C D'.\n  - apply cia; [|assert_diffs; apply par_left_comm, par_col_par with D; Col].\n    exists D; split; trivial.\n    destruct Hts as [_ [HNCol _]].\n    repeat split.\n      intro; apply HNCol; ColR.\n      Col.\n    exists C; split; [Col|Between].\n  - assert_diffs; split; auto.\n    exists D'; split; CongA.\nQed.\n\nEnd consecutive_interior_angles_alternate_interior_angles.", "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/consecutive_interior_angles_alternate_interior_angles.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7518728061357076}}
{"text": "Require Export ZArith.\nRequire Export Zwf.\nRequire Export Zcompare.\nCheck Zwf.\nCheck Zwf_well_founded.\nOpen Scope Z_scope.\n \nDefinition factZ_F: forall (x : Z), (forall y, Zwf 0 y x ->  Z) ->  Z.\nrefine (fun x fact =>\n           match Z_lt_le_dec x 0 with\n             left _ => 0\n            | right Hle =>\n                match Z.eq_dec x 0 with\n                  left _ => 1\n                 | right Hne => x * fact (x - 1) _\n                end\n           end).\nunfold Zwf; omega.\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/ch15_general_recursion/SRC/factZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7518696561191321}}
{"text": "(* To build an impredicative definition that simulates an inductive type\n   following this technique:\n\n  * construct a function that takes the same type of arguments as the \n    inductive type and returns a type, obtained in the following manner.\n\n  + quantify over a predicate P that have the same type as the predicate\n    one wants to simulate (excepted the parameters of the inductive type).\n\n  + construct implications where premises state that the predicate P\n    simulates the constructors of the inductive predicate.  In other words,\n    each premise is a constructor of the inductive predicate where\n    instances of the inductive predicate name are replaced with P.\n\n  + the ultimate conclusion must express that P holds for the arguments\n    (but the parameters do not appear).\n\n  This definition actually expresses that the least property that satisfies\n  the constructors holds. *)\n\n(* For instance, for sorted lists: *)\n\nRequire Export List Relations.\n\nSection R_declared.\n\n  Variables (A: Type)\n            (R: relation A).\n\n  (* Here is the inductive definition: *)\n\n  Inductive sorted : list A -> Prop :=\n    sorted0 : sorted  nil\n  | sorted1 : forall x:A, sorted  (x::nil)\n  | sorted2 : forall (x1 x2:A)(l':list A),\n      R x1 x2 -> sorted  (x2::l') -> sorted  (x1::x2::l').\n\n  #[local] Hint Constructors sorted : core.\n\n  Definition impredicative_sorted (l:list A) : Prop :=\n    forall P :  list A -> Prop,\n      P nil ->\n      (forall x:A, P (x::nil))->\n      (forall (x1 x2:A)(l':list A),\n          R x1 x2 -> P (x2::l') -> P (x1::x2::l'))->\n      P l.\n\n  (* To prove that the two predicates are equivalent we first need to show\n   that the impredicative definition satisfies the constructors. *)\n\n  Theorem isorted0  :  impredicative_sorted nil.\n  Proof.\n    red; intros; assumption.  \n  Qed.\n\n  Theorem isorted1 :  forall  x: A , impredicative_sorted (x::nil).\n  Proof.\n    unfold impredicative_sorted; auto. \n  Qed.\n\n  Theorem isorted2  :\n    forall (x1 x2:A)(l':list A),\n      R x1 x2 ->\n      impredicative_sorted  (x2::l') ->\n      impredicative_sorted  (x1::x2::l').\n  Proof.\n    intros x1 x2 l' Hr Hs P Hsn Hs1 Hs2.\n    apply Hs2; auto.\n    apply Hs; auto.\n  Qed.\n\n  #[local] Hint Resolve isorted0 isorted1 isorted2 : core.\n\n\n  (* Proof of the equivalence between both definitions *)\n\n  Theorem sorted_to_impredicative_sorted :\n    forall l, sorted  l -> impredicative_sorted l.\n  Proof.\n    induction 1; auto.\n  Qed.\n\n\n  Theorem impredicative_sorted_to_sorted :\n    forall l, impredicative_sorted  l -> sorted  l.\n  Proof.\n    intros  l H; apply H; auto.\n  Qed.\n\n\nEnd R_declared.\n\nArguments sorted {A} R _.\nArguments impredicative_sorted {A} R _.\n\n(* If we want to simulate \"less-or-equal\" we can define the impredicative\n   expression by again following the constructors. *)\n\nDefinition impredicative_le (n p:nat) : Prop :=\n  forall P: nat -> Prop,\n    P n ->\n    (forall m:nat, P m -> P (S m)) ->\n    P p.\n\n(* We can prove it satisfies the constructors of  le. *)\nTheorem impredicative_le_n : forall n: nat, impredicative_le n n.\nProof.\n  unfold impredicative_le; auto.\nQed.\n\nTheorem impredicative_le_S : \n  forall n m:nat, impredicative_le n m -> impredicative_le n (S m).\nProof.\n  intros n m Hle P Hn Hs; apply Hs; apply Hle; auto.\nQed.\n\n#[export] Hint Resolve impredicative_le_n impredicative_le_S : core.\n\nTheorem le_to_impredicative :\n  forall n p, n <= p -> impredicative_le n p.\nProof.\n  intros n p Hle; elim Hle; auto.\nQed.\n\nTheorem impredicative_to_le :\n  forall n p, impredicative_le n p -> n <= p.\nProof.\n  intros n p H; apply H; auto.\nQed.\n\n\n(* For disjunction, we do it in the same way, still giving the\n   parameters a position outside the universal quantification. *)\n\nDefinition impredicative_or (A B:Prop) : Prop :=\n  forall P:Prop, \n    (* first constructor. *)\n    (A -> P) ->\n    (* second constructor. *)\n    (B -> P) ->\n    P.\n\nTheorem impredicative_or_intro1 :\n  forall A B:Prop, A -> impredicative_or A B.\nProof.\n  unfold impredicative_or; auto.\nQed.\n\nTheorem impredicative_or_intro2 :\n  forall A B:Prop, B -> impredicative_or A B.\nProof.\n  unfold impredicative_or; auto.\nQed.\n\n#[export] Hint Resolve impredicative_or_intro1 impredicative_or_intro2 : core.\n\nTheorem or_to_impredicative : forall A B, A \\/ B -> impredicative_or A B.\nProof.\n  intros A B H; elim H; auto.\nQed.\n\nTheorem impredicative_to_or : forall A B, impredicative_or A B -> A \\/ B.\nProof.\n  intros A B H; apply H; auto.\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/impredicative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7518387876167603}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, bag_proofs *)\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\nDefinition bag := natlist.\n\nFixpoint count (v: nat) (s: bag) : nat :=\n    match s with\n    |nil     => O\n    |h :: t => if (Nat.eqb v h) then S(count v t) else count v t\n    end.\n\nTheorem count_member_nonzero: forall (s: bag),\n  Nat.leb 1 (count 1 (1::s)) = true.\nProof.\n    intros. induction s as[|s'].\n    reflexivity.\n    simpl. reflexivity.\nQed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n    match s with\n    |nil => nil\n    |h::t => if (Nat.eqb h v) then t else h::(remove_one v t)\n    end.\n\nLemma ble_n_Sn: forall n: nat, Nat.leb n (S n) = true.\nProof.\n    intros. induction n as [|n'].\n    reflexivity.\nsimpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem remove_decreases_count: forall (s: bag),\n      Nat.leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n    intros. induction s as [|h t].\n    reflexivity.\n    destruct h as [|h'].\n    simpl. rewrite ble_n_Sn. 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/chapter5_Library_List/bag_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7518387868501781}}
{"text": "Require Import List.\n\n\nInductive par : Set := open | close.\n\nInductive wp : list par -> Prop :=\n  | wp_nil          : wp nil\n  | wp_open_close   : forall (l:list par), wp l -> wp ((open::l)++(close::nil))\n  | wp_concat       : forall (l1 l2: list par), wp l1 -> wp l2 -> wp (l1++l2). \n\n\nLemma wp_oc: wp (open::close::nil).\nProof.\n  apply wp_open_close with (l:=nil). apply wp_nil.\nQed.\n\nLemma wp_o_head_c: forall (l1 l2:list par),\n  wp l1 -> wp l2 -> wp (open::(l1++(close::l2))).\nProof.\n  intros l1 l2 H1 H2. cut (nil++l2 = l2). intro H. rewrite <- H.\n  rewrite app_comm_cons with (x:=nil).\n  rewrite app_comm_cons with (a:=open). rewrite app_assoc.\n  apply wp_concat. apply wp_open_close. exact H1. exact H2. apply app_nil_l.\nQed.\n\n\nLemma wp_o_tail_c: 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. exact H1. apply wp_open_close. exact H2.\nQed.\n\nInductive bin : Set :=\n  | L : bin\n  | N : bin -> bin -> bin.\n\nFixpoint bin2string (t:bin) : list par :=\n  match t with\n    | L     => nil\n    | N u v => open :: ((bin2string u) ++ (close :: (bin2string v)))\n  end.\n \nLemma wp_bin2string: forall t:bin, wp (bin2string t).\nProof.\n  intro t. elim t. simpl. apply wp_nil. clear t.\n  intros t1 H1 t2 H2. simpl. apply wp_o_head_c. exact H1. exact H2.\nQed.\n\n\nFixpoint bin2string' (t:bin) : list par :=\n  match t with\n    | L     => nil\n    | N u v => (bin2string' u) ++ (open :: ((bin2string' v) ++ (close :: nil)))\n  end.\n \n\nLemma wp_bin2string': forall t:bin, wp (bin2string' t).\nProof.\n  intro t. elim t. simpl. apply wp_nil. clear t.\n  intros t1 H1 t2 H2. simpl. apply wp_o_tail_c. exact H1. exact H2.\nQed.\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/parenthesis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7517868844825074}}
{"text": "From mathcomp\n  Require Import ssreflect div.\nRequire Import Nat Arith.\n\nDefinition task := forall n m, n < m \\/ n = m \\/ n > m.\n\n(* TopProver umemasu *)\n(* TopProver #6 *)\n\nLemma zeroLtN: forall n, 0 < S n.\nProof.\nintros.\ninduction n.\nby [].\nauto.\nQed.\n\nLemma nGtZero: forall n, S n > 0.\nProof.\nintros.\ninduction n.\nby [].\nauto.\nQed.\n\nTheorem solution: task.\nProof.\n\nunfold task.\n(*intros.*)\n\ninduction n.\n- induction m.\n-- auto.\n-- left. apply zeroLtN.\n- induction m.\n-- right; right. apply nGtZero.\n-- destruct (IHn m).\n--- left. apply lt_n_S. exact H.\n-- destruct H.\n--- right; left. apply eq_S. exact H.\n--- right; right. apply gt_n_S. exact H.\n\n\nQed.", "meta": {"author": "elle-et-noire", "repo": "coq-wsl", "sha": "f3e43ed79fa6358d061e1bb574e234a36e298392", "save_path": "github-repos/coq/elle-et-noire-coq-wsl", "path": "github-repos/coq/elle-et-noire-coq-wsl/coq-wsl-f3e43ed79fa6358d061e1bb574e234a36e298392/topprover/topprover03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778048911612, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7517584696644475}}
{"text": "Require Import Basics.\nRequire Import Spaces.Pos.\nRequire Import Spaces.Int.Core.\n\nLocal Open Scope int_scope.\n\n(** ** Addition is commutative *)\n\nLemma int_add_comm n m : n + m = m + n.\nProof.\n  destruct n, m; cbn; trivial; by rewrite pos_add_comm.\nQed.\n\n(** ** Zero is the additive identity. *)\n\nLemma int_add_0_l n : 0 + n = n.\nProof.\n  reflexivity.\nQed.\n\nLemma int_add_0_r n : n + 0 = n.\nProof.\n  by destruct n.\nQed.\n\n(** ** Multiplication by zero is zero *)\n\nLemma int_mul_0_l n : 0 * n = 0.\nProof.\n  reflexivity.\nQed.\n\nLemma int_mul_0_r n : n * 0 = 0.\nProof.\n  by destruct n.\nQed.\n\n(** ** One is the multiplicative identity *)\n\nLemma int_mul_1_l n : 1 * n = n.\nProof.\n  by destruct n.\nQed.\n\nLemma int_mul_1_r n : n * 1 = n.\nProof.\n  destruct n; trivial; cbn; apply ap, pos_mul_1_r.\nQed.\n\n(** ** Inverse laws *)\n\nLemma int_pos_sub_diag n : int_pos_sub n n = 0.\nProof.\n  induction n; trivial; cbn; by rewrite IHn.\nQed.\n\nLemma int_add_negation_l n : (-n) + n = 0.\nProof.\n  destruct n; trivial; cbn; apply int_pos_sub_diag.\nQed.\n\nLemma int_add_negation_r n : n + (-n) = 0.\nProof.\n  destruct n; trivial; cbn; apply int_pos_sub_diag.\nQed.\n\n(** ** Permutation of neg and pos_succ *)\nLemma int_neg_pos_succ p : neg (pos_succ p) = int_pred (neg p).\nProof.\n  by destruct p.\nQed.\n\n(** ** Negation of a doubled positive integer *)\nLemma int_negation_double a\n  : - (int_double a) = int_double (- a).\nProof.\n  by destruct a.\nQed.\n\n(** Negation of the predecessor of a doubled positive integer. *)\nLemma int_negation_pred_double a\n  : - (int_pred_double a) = int_succ_double (- a).\nProof.\n  by destruct a.\nQed.\n\n(** Negation of the doubling of the sucessor of an positive. *)\nLemma int_negation_succ_double a\n  : - (int_succ_double a) = int_pred_double (- a).\nProof.\n  by destruct a.\nQed.\n\n(** Negation of subtraction of positive integers *)\nLemma int_pos_sub_negation a b\n  : - (int_pos_sub a b) = int_pos_sub b a.\nProof.\n  revert a b.\n  induction a as [|a ah|a ah];\n  destruct b;\n  cbn; trivial.\n  all: rewrite ?int_negation_double,\n    ?int_negation_succ_double,\n    ?int_negation_pred_double.\n  all: apply ap, ah.\nQed.\n\n(** ** int_succ is a retract of int_pred *)\nDefinition int_succ_pred : Sect int_pred int_succ.\nProof.\n  intros [n | | n]; [|trivial|].\n  all: destruct n; trivial.\n  1,2: cbn; apply ap.\n  1: apply pos_pred_double_succ.\n  rewrite pos_add_1_r.\n  apply pos_succ_pred_double.\nQed.\n\n(** ** int_pred is a retract of int_succ *)\nDefinition int_pred_succ : Sect int_succ int_pred.\nProof.\n  intros [n | | n]; [|trivial|].\n  all: destruct n; trivial.\n  1,2: cbn; apply ap.\n  1: rewrite pos_add_1_r.\n  1: apply pos_succ_pred_double.\n  apply pos_pred_double_succ.\nQed.\n\n(** ** Negation distributes over addition *)\nLemma int_negation_add_distr n m : - (n + m) = - n + - m.\nProof.\n destruct n, m; simpl; trivial using int_pos_sub_negation.\nQed.\n\n(** ** Negation is injective *)\nLemma int_negation_inj n m : -n = -m -> n = m.\nProof.\n  destruct n, m; simpl; intro H.\n  1: apply pos_inj in H.\n  2: apply pos_neq_zero in H.\n  3: apply pos_neq_neg in H.\n  4: apply  zero_neq_pos in H.\n  6: apply  zero_neq_neg in H.\n  7: apply  neg_neq_pos in H.\n  8: apply  neg_neq_zero in H.\n  9: apply  neg_inj in H.\n  all: by destruct H.\nQed.\n\n(** ** Subtracting 1 from a sucessor gives the positive integer. *)\nLemma int_pos_sub_succ_l a\n  : int_pos_sub (pos_succ a) 1%pos = pos a.\nProof.\n  destruct a; trivial.\n  cbn; apply ap, pos_pred_double_succ.\nQed.\n\n(** ** Subtracting a sucessor from 1 gives minus the integer. *)\nLemma int_pos_sub_succ_r a\n  : int_pos_sub 1%pos (pos_succ a) = neg a.\nProof.\n  destruct a; trivial.\n  cbn; apply ap, pos_pred_double_succ.\nQed.\n\n(** ** Interaction of doubling functions and subtraction *)\n\nLemma int_succ_double_int_pos_sub a b\n  : int_succ_double (int_pos_sub a (pos_succ b))\n    = int_pred_double (int_pos_sub a b).\nProof.\n  revert a b.\n  induction a; induction b; trivial.\n  + cbn; apply ap.\n    by rewrite pos_pred_double_succ.\n  + destruct a; trivial.\n  + cbn; destruct (int_pos_sub a b); trivial.\n  + cbn.\n    rewrite <- IHa.\n    destruct (int_pos_sub a (pos_succ b)); trivial.\n  + destruct a; trivial.\n  + cbn; destruct (int_pos_sub a b); trivial.\n  + cbn.\n    rewrite IHa.\n    cbn; destruct (int_pos_sub a b); trivial.\nQed.\n\nLemma int_pred_double_int_pos_sub a b \n  : int_pred_double (int_pos_sub (pos_succ a) b)\n    = int_succ_double (int_pos_sub a b).\nProof.\n  revert a b.\n  induction a; induction b; trivial.\n  + by destruct b.\n  + by destruct b.\n  + cbn; by destruct (int_pos_sub a b).\n  + cbn; by destruct (int_pos_sub a b).\n  + cbn; apply ap.\n    by rewrite pos_pred_double_succ.\n  + cbn.\n    rewrite <- IHa.\n    by destruct (int_pos_sub (pos_succ a) b).\n  + cbn.\n    rewrite IHa.\n    by destruct (int_pos_sub a b).\nQed.\n\n(** ** Subtractions cancel sucessors. *)\nLemma int_pos_sub_succ_succ a b\n  : int_pos_sub (pos_succ a) (pos_succ b) = int_pos_sub a b.\nProof.\n  rewrite <- 2 pos_add_1_r.\n  revert a b.\n  induction a; induction b; trivial.\n  1: destruct b; trivial.\n  { destruct b; trivial.\n    cbn; apply ap.\n    by rewrite pos_pred_double_succ. }\n  1: destruct a; trivial.\n  1: apply int_succ_double_int_pos_sub.\n  { destruct a; trivial.\n    cbn; apply ap, ap, pos_pred_double_succ. }\n  1: apply int_pred_double_int_pos_sub.\n  cbn; apply ap.\n  rewrite <- 2 pos_add_1_r.\n  apply IHa.\nDefined.\n\n(** ** Predecessor of a subtraction is the subtraction of a sucessor. *)\nLemma int_pred_pos_sub_r a b\n  : int_pred (int_pos_sub a b) = int_pos_sub a (pos_succ b).\nProof.\n  revert a.\n  induction b as [|b bH] using pos_peano_ind.\n  1: destruct a; trivial; destruct a; trivial.\n  intro a.\n  revert b bH.\n  induction a as [|a aH] using pos_peano_ind.\n  { intros b bH.\n    rewrite <- bH.\n    destruct b; trivial.\n    cbn; apply ap.\n    rewrite 2 pos_add_1_r.\n    rewrite pos_succ_pred_double.\n    rewrite pos_pred_double_succ.\n    trivial. }\n  intros b bH.\n  rewrite 2 int_pos_sub_succ_succ.\n  apply bH.\nQed.\n\n(** ** Negation of the predecessor is an involution. *)\nLemma int_negation_pred_negation_red x\n  : - int_pred (- int_pred x) = x.\nProof.\n  destruct x as [x| |x]; trivial;\n  destruct x; trivial; cbn; apply ap.\n  1: apply pos_pred_double_succ.\n  rewrite pos_add_1_r.\n  apply pos_succ_pred_double.\nQed.\n\n(** ** Predecessor of a sum is the sum with a predecessor *)\nLemma int_pred_add_r a b\n  : int_pred (a + b) = a + int_pred b.\nProof.\n  revert a b.\n  intros [a| |a] [b| |b]; trivial.\n  + cbn; apply ap.\n    by rewrite pos_add_assoc.\n  + revert a.\n    induction b as [|b bH] using pos_peano_ind.\n    - intro a; exact (int_pred_succ (neg a)).\n    - intro a.\n      rewrite <- pos_add_1_r.\n      rewrite (int_pred_succ (pos b)).\n      rewrite int_add_comm.\n      cbn.\n      rewrite pos_add_1_r.\n      rewrite <- int_pos_sub_negation.\n      rewrite <- int_pred_pos_sub_r.\n      apply int_negation_inj.\n      rewrite int_pos_sub_negation.\n      apply int_negation_pred_negation_red.\n  + cbn.\n    rewrite pos_add_1_r.\n    apply int_pred_pos_sub_r.\n  + revert a.\n    induction b as [|b bH] using pos_peano_ind.\n    - intro a; exact (int_pred_succ (pos a)).\n    - intro a.\n      rewrite <- pos_add_1_r.\n      rewrite (int_pred_succ (pos b)).\n      cbn; rewrite pos_add_assoc.\n      change (int_pred (int_succ (pos (a + b)%pos)) = pos a + pos b).\n      apply int_pred_succ.\nQed.\n\n(** ** Subtraction from a sum is the sum of a subtraction *)\nLemma int_pos_sub_add (a b c : Pos)\n  : int_pos_sub (a + b)%pos c = pos a + int_pos_sub b c.\nProof.\n  revert c b a.\n  induction c as [|c ch] using pos_peano_ind.\n  { intros b a.\n    change (int_pred (pos a + pos b) = pos a + (int_pred (pos b))).\n    apply int_pred_add_r. }\n  intros b a.\n  rewrite <- int_pred_pos_sub_r.\n  rewrite ch.\n  rewrite <- int_pred_pos_sub_r.\n  apply int_pred_add_r.\nQed.\n\n(** An auxillary lemma used to prove associativity. *)\nLemma int_add_assoc_pos p n m : pos p + (n + m) = pos p + n + m.\nProof.\n  destruct n as [n| |n], m as [m| |m]; trivial.\n  - cbn; apply int_negation_inj.\n    rewrite !int_negation_add_distr, !int_pos_sub_negation.\n    rewrite int_add_comm, pos_add_comm.\n    apply int_pos_sub_add.\n  - symmetry.\n    apply int_add_0_r.\n  - by rewrite <- int_pos_sub_add, int_add_comm,\n      <- int_pos_sub_add, pos_add_comm.\n  - symmetry.\n    apply int_pos_sub_add.\n  - cbn; apply ap, pos_add_assoc.\nQed.\n\n(** ** Associativity of addition *)\nLemma int_add_assoc n m p : n + (m + p) = n + m + p.\nProof.\n  destruct n.\n  - apply int_negation_inj.\n    rewrite !int_negation_add_distr.\n    apply int_add_assoc_pos.\n  - trivial.\n  - apply int_add_assoc_pos.\nQed.\n\n(* ** The successor autoequivalence. *)\nGlobal Instance isequiv_int_succ : IsEquiv int_succ | 0\n  := isequiv_adjointify int_succ _ int_succ_pred int_pred_succ.\n\nDefinition equiv_int_succ : Int <~> Int\n  := Build_Equiv _ _ _ isequiv_int_succ.\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/Int/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7517510087757272}}
{"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\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\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\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": "paul-kline", "repo": "protosynth", "sha": "1b66397cea554f086cf4bdc95d61bfa269da890a", "save_path": "github-repos/coq/paul-kline-protosynth", "path": "github-repos/coq/paul-kline-protosynth/protosynth-1b66397cea554f086cf4bdc95d61bfa269da890a/cpdt/src/DataStruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7517509953705829}}
{"text": "Require Import List.\n\n\nFixpoint split {A B: Type}(l: list (A * B)) : list A * list B :=\n match l with \n   | nil => (nil, nil)\n   | (a,b)::l' => let (l'1,l'2) := split  l' \n                   in (a::l'1, b::l'2)\n end.\n\nFixpoint combine {A B: Type}(l1 : list A)(l2 :list B): list (A*B):=\n  match l1,l2 with \n    | nil,nil => nil\n    | (a::l'1), (b::l'2) => (a,b)::(combine  l'1 l'2)\n    | _,_  => nil\n  end.\n\nTheorem combine_of_split {A B : Type} :\n  forall l:list (A*B),\n    let (l1,l2) :=  split l\n    in combine  l1 l2 = l.\nProof.\n  induction l; simpl; auto.\n  destruct a, (split l); simpl; congruence. \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/ch6_inductive_data/SRC/split.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7517298503890532}}
{"text": "(*\nInductive bool : Type :=\n| true : bool\n| false : bool\n.\n*)\n\n(*\n true -> 100\n false -> true\n*)\n\nDefinition btype \n  (b: bool) : Type :=\n  match b with\n  | true => nat\n  | false => bool\n  end.\n\nCheck btype.\n\nCompute (btype true).\n\nCompute (btype false).\n\n(*\nDefinition foo (b: bool) \n  : btype b \n:=\n  match b with\n  | true => 100\n  | false => true\n  end.\n*)\n\n(*\ne1 : Type\ne2 : Type\n=========\nforall (x:e1), e2 : Type\n*)\n\n(* foo: bool -> nat + bool *)\n\n(* foo: forall (b: bool), btype b *)\n\n(*   forall (n: nat), vector n *)\n\n(*   nat -> list *)\n\n(*\nDefinition foo: forall (b: bool), btype b\n:=\n  fun b: bool =>\n  match b with\n  | true => 100\n  | false => true\n  end.\n*)\n\nDefinition foo (b: bool) \n  : btype b\n:=\n  match b with\n  | true => 100\n  | false => true\n  end.\n\n\nCheck foo.\n\nCompute foo true.\nCompute foo false.\n\nCheck foo.\n\nCheck btype.\n\nDefinition bar (b: bool) \n  : Type\n:=\n  match b with\n  | true => nat\n  | false => bool\n  end.\n\n(*\nforall b : bool, btype b\n\nforall b : bool, Type\n*)\n\n\n\n\n\n\n\n\n\n(*\n   9 Feb 2017\n *)\n\n(*\nInductive TrueT : Type :=\n| TT : TrueT\n.\n\nInductive FalseT: Type :=\n.\n\nDefinition istrue (b: bool) : Type :=\n  match b with\n  | true => TrueT\n  | false => FalseT\n  end.\n\nCompute istrue true .\n\nCompute istrue false.\n\n\n\nCheck (TT: istrue true).\n\nDefinition true_is_true : istrue true \n:= TT.\n\n(* Definition false_is_true : istrue false := ???. *)\n\nDefinition false_is_not_true : \n istrue false -> FalseT \n:=\n  fun x : istrue false =>\n    match x with\n    end : FalseT\n.\n\n(*\n  P -> Q     P\n  ------------\n       Q\n\n\n  e: P -> Q          e1 : P\n --------------------------\n   e e1 : Q\n*)\n\n\n\n\n(*\nFixpoint evenb (n: nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => match n' with\n           | 0 => false\n           | S n'' => evenb n''\n           end\n  end.\n*)\n\nFixpoint evenb (n: nat) : bool :=\n  match n with\n  | 0 => true\n  | 1 => false\n  | S (S m) => evenb m\n  end.\n\nDefinition two_plus_even_is_even :\n  forall n:nat, istrue (evenb n) -> istrue (evenb (2 + n))\n:=\n  fun n:nat => fun pf: istrue (evenb n) => pf.\n\n\n\n\n\n\n\nDefinition even_plus_two_is_even :\n  forall n:nat, istrue (evenb n) -> istrue (evenb (n+2)) \n  :=\n  fix even_plus_two_is_even n :=\n    match n return istrue (evenb n) -> istrue (evenb (n+2)) with\n    | 0 => fun x => x  \n    | 1 => fun x => x\n    | S (S m) => fun x => even_plus_two_is_even m x\n    end.\n\n\n\n\nInductive even: nat -> Type :=\n| zero_is_even : even 0\n| succ_succ_even (n: nat) (pf: even n) : even (S (S n))\n.\n\nCheck even.\n\nCheck (even: nat -> Type).\n\n\n\n(*\n* zero_is_even : even 0\n\n* succ_succ_even 0 zero_is_even : even (S (S 0))\n\n* succ_succ_even (S(S 0)) (succ_succ_even 0 zero_is_even) : even (S (S (S (S 0)))\n*)\n\n(*\nDefinition even' (n: nat) : Type :=\n  exists m, n = 2 * m.\n*)\n\n(*\n  e : vector (1 + n)    e: vector (S(n))\n\n    e : T  S===T\n   -------------\n       e : S\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition two_plus_even_is_even' :\n  forall n:nat, even n -> even (2+n)\n  :=\n  fun n:nat => fun pf: even n => succ_succ_even n (pf).\n\nDefinition even_plus_two_is_even' :\n  forall n:nat, even n -> even (n+2)\n  :=\n  fix even_plus_two_is_even n :=\n    match n return even n -> even (n+2) with\n    | 0 | 1 => fun x => succ_succ_even _ x\n    | S (S m) => fun pf : even (S (S m)) => \n      succ_succ_even (m+2) (\n      even_plus_two_is_even m\n      match pf in even k \n        return match k with 0 | 1 => TrueT | S(S l) => even l end \n      with\n      | zero_is_even => TT\n      | succ_succ_even m pf => pf\n      end)\n    end.\n\n(* Compute (even_plus_two_is_even' 0 zero_is_even). *)\n\nDefinition even_plus_two_is_even'': \n  forall n:nat, even n -> even (n+2).\nProof.\n  fix 1.\n  intros. destruct n.\n  - simpl. apply succ_succ_even. \n    assumption.\n  - destruct n.\n    + apply succ_succ_even. \n      assumption.\n    + inversion H. subst. simpl. \n      apply succ_succ_even.\n      apply even_plus_two_is_even''. \n      assumption.\nDefined.\n\nCompute (even_plus_two_is_even'' 0 zero_is_even).\n\n\n\n\n\n\n\n\n\nDefinition induction_for_nat: \nforall P : nat -> Type,\n  P 0 -> \n  (forall n : nat, P n -> P (S n)) -> \nforall n : nat, P n \n:=\n  fun P => fun (base: P 0) => \n  fun (step: forall n : nat, P n -> P (S n)) =>\n  fix ind n :=\n    match n return P n with\n    | 0 => base\n    | S m => step m (ind m)\n    end.\n\n\n\n\n\n\n\n\nInductive EqT (A: Type) : A -> A -> Type :=\n| eqrefl (x: A) : EqT A x x\n.\n\nCheck eqrefl.\n\n\n\n\n\n\n\n\n\n\nDefinition succ_is_not_0: \n  forall n: nat, EqT nat (S n) 0 -> FalseT\n:=\n  fun n => fun (pf: EqT nat (S n) 0) =>\n    match pf in EqT _ x y \n             return match x with \n                    | 0   => match y with | 0 => TrueT | S _ => FalseT end\n                    | S _ => match y with | 0 => FalseT | S _ => TrueT end\n                    end\n    with\n    | eqrefl _ z => match z with\n                    | 0 => TT\n                    | S _ => TT\n                    end\n    end : FalseT.\n\n\n\n\nDefinition succ_is_not_0': \n  forall n: nat, EqT nat (S n) 0 -> FalseT.\nProof.\n  intros. inversion H.\nDefined.\n\n\n\n\n\n(*\nInductive EqT (A: Type) (x: A) : A -> Type :=\n| eqrefl : EqT A x x\n.\n\nDefinition succ_is_not_0: \n  forall n: nat, EqT nat (S n) 0 -> FalseT\n:=\n  fun n => fun (pf: EqT nat (S n) 0) =>\n    match pf in EqT _ _ y \n             return match y with 0 => FalseT | S _ => TrueT end with\n    | eqrefl _ _ => TT\n    end.\n\nDefinition succ_is_not_0': \n  forall n: nat, EqT nat (S n) 0 -> FalseT.\nProof.\nintros. inversion H.\nDefined.\n*)\n\n\n(*\n  forall P: Prop (x y: P), x = y\n*)\n\n*)\n\n\n\n\n\n\n(*\n   9 Feb 2017 : Proposition\n *)\n\nDefinition istrue (b: bool) : Prop :=\n  match b with\n  | true => True\n  | false => False\n  end.\n\nPrint istrue.\n\nCompute istrue true .\n\nCompute istrue false.\n\n\n\nCheck (I: istrue true).\n\nDefinition true_is_true : istrue true \n:= I.\n\n(* Definition false_is_true : istrue false := ???. *)\n\nDefinition false_is_not_true : \n istrue false -> False \n:=\n  fun x : istrue false =>\n    match x with\n    end : False\n.\n\n(*\n  P -> Q     P\n  ------------\n       Q\n\n\n  e: P -> Q          e1 : P\n --------------------------\n   e e1 : Q\n*)\n\n\n\n\n(*\nFixpoint evenb (n: nat) : bool :=\n  match n with\n  | 0 => true\n  | S n' => match n' with\n           | 0 => false\n           | S n'' => evenb n''\n           end\n  end.\n*)\n\nFixpoint evenb (n: nat) : bool :=\n  match n with\n  | 0 => true\n  | 1 => false\n  | S (S m) => evenb m\n  end.\n\n\nDefinition two_plus_even_is_even :\n  forall n:nat, istrue (evenb n) -> istrue (evenb (2 + n))\n:=\n  fun n:nat => fun pf: istrue (evenb n) => pf.\n\nCheck (\n(fun n:nat => fun pf: istrue (evenb n) => pf)\n:\n(forall n:nat, istrue (evenb n) -> istrue (evenb (2 + n)))\n).\n\n\n\n\n\n\n\nDefinition even_plus_two_is_even :\n  forall n:nat, istrue (evenb n) -> istrue (evenb (n+2)) \n  :=\n  fix even_plus_two_is_even n :=\n    match n return istrue (evenb n) -> istrue (evenb (n+2)) with\n    | 0 => fun x => x  \n    | 1 => fun x => x\n    | S (S m) => fun x => even_plus_two_is_even m x\n    end.\n\nCheck(\n  (fix even_plus_two_is_even n :=\n    match n return istrue (evenb n) -> istrue (evenb (n+2)) with\n    | 0 => fun x => x  \n    | 1 => fun x => x\n    | S (S m) => fun x => even_plus_two_is_even m x\n    end)\n  :\n  (forall n:nat, istrue (evenb n) -> istrue (evenb (n+2)))\n).\n\n\n\n\nInductive even: nat -> Prop :=\n| zero_is_even : even 0\n| succ_succ_even (n: nat) (pf: even n) : even (S (S n))\n.\n\nCheck even.\n\nCheck (even: nat -> Type).\n\n\n\n(*\n* zero_is_even : even 0\n\n* succ_succ_even 0 zero_is_even : even (S (S 0))\n\n* succ_succ_even (S(S 0)) (succ_succ_even 0 zero_is_even) : even (S (S (S (S 0)))\n*)\n\n(*\nDefinition even' (n: nat) : Type :=\n  exists m, n = 2 * m.\n*)\n\n(*\n  e : vector (1 + n)    e: vector (S(n))\n\n    e : T  S===T\n   -------------\n       e : S\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition two_plus_even_is_even' :\n  forall n:nat, even n -> even (2+n)\n  :=\n  fun n:nat => fun pf: even n => succ_succ_even n (pf).\n\nDefinition even_plus_two_is_even' :\n  forall n:nat, even n -> even (n+2)\n  :=\n  fix even_plus_two_is_even n :=\n    match n return even n -> even (n+2) with\n    | 0 | 1 => fun x => succ_succ_even _ x\n    | S (S m) => fun pf : even (S (S m)) => \n      succ_succ_even (m+2) (\n      even_plus_two_is_even m\n      match pf in even k \n        return (match k with 0 | 1 => True | S(S l) => even l end) : Prop \n      with\n      | zero_is_even => I\n      | succ_succ_even m pf => pf\n      end)\n    end.\n\n(* Compute (even_plus_two_is_even' 0 zero_is_even). *)\n\nTheorem even_plus_two_is_even'': \n  forall n:nat, even n -> even (n+2).\nProof.\n  fix 1.\n  intros. destruct n.\n  - simpl. apply succ_succ_even. \n    assumption.\n  - destruct n.\n    + apply succ_succ_even. \n      assumption.\n    + inversion H. subst. simpl. \n      apply succ_succ_even.\n      apply even_plus_two_is_even''. \n      assumption.\nDefined.\n\nPrint even_plus_two_is_even''.\n\nCompute (even_plus_two_is_even'' 0 zero_is_even).\n\n\n\n\n\n\n\n\n\nDefinition induction_for_nat: \nforall P : nat -> Prop,\n  P 0 -> \n  (forall n : nat, P n -> P (S n)) -> \nforall n : nat, P n \n:=\n  fun P => fun (base: P 0) => \n  fun (step: forall n : nat, P n -> P (S n)) =>\n  fix ind n :=\n    match n return P n with\n    | 0 => base\n    | S m => step m (ind m)\n    end.\n\n\n\n\n\n\nPrint eq.\n\nCheck (eq 0 0).\n\n(* Inductive EqT (A: Type) : A -> A -> Prop := *)\n(* | eqrefl (x: A) : EqT A x x *)\n(* . *)\n\n(* Check eqrefl. *)\n\n\n\n\n\n\n\n(*\n\nDefinition succ_is_not_0: \n  forall n: nat, S n = 0 -> False\n:=\n  fun n => fun (pf: S n = 0) =>\n    match pf in x = y \n             return match x with \n                    | 0   => match y with | 0 => TrueT | S _ => FalseT end\n                    | S _ => match y with | 0 => FalseT | S _ => TrueT end\n                    end\n    with\n    | eqrefl _ z => match z with\n                    | 0 => TT\n                    | S _ => TT\n                    end\n    end : FalseT.\n\n\n\n\nDefinition succ_is_not_0': \n  forall n: nat, EqT nat (S n) 0 -> FalseT.\nProof.\n  intros. inversion H.\nDefined.\n\n*)\n\n\n(* Inductive EqT (A: Type) : A -> A -> Prop := *)\n(* | eqrefl (x: A) : EqT A x x *)\n(* . *)\n\n\n(*\nInductive EqT (A: Type) (x: A) : A -> Prop :=\n| eqrefl : EqT A x x\n.\n*)\n\n\nDefinition succ_is_not_0: \n  forall n: nat, S n = 0 -> False\n:=\n  fun n => fun (pf: S n = 0) =>\n    match pf in _ = y \n             return match y with 0 => False | S _ => True end with\n    | eq_refl _ => I\n    end.\n\nPrint eq.\nDefinition succ_is_not_0': \n  forall n: nat, S n = 0 -> False.\nProof.\n  intros. inversion H.\nDefined.\n\n\n\n(*\n  forall P: Prop (x y: P), x = y\n*)\n\n\nFixpoint sum n :=\n  match n with\n  | 0 => 0\n  | S m => S m + sum m\n  end.\n\nCompute sum 100.\n\nRequire Import Lia.\n\nLemma sum_n_times:\n  forall n, 2 * sum n = n * (n+1).\nProof.\n  intros. induction n; simpl; lia.\nQed.\n\nPrint sum_n_times.\n\n\n(*\n  10 Feb 2017\n *)\n\n(* forall, ->, =, P -> False, True, False, /\\, \\/, exists *)\n\n(* Conjunction *)\n\n(*\nInductive and (P: Prop) (Q: Prop) : Prop \n:=\n| conj (x: P) (y: Q) : and P Q\n.\n\n(1) a : P,  b: Q\n => conj a b : and P Q\n*)\n\nPrint and.\n\nCheck (forall n: nat, n = 0 /\\ (n = 1 -> False) : Prop).\n\n\n(* Disjunction *)\n\n(*\nInductive or (P: Prop) (Q: Prop) : Prop \n:=\n| left  (a: P) : or P Q\n| right (b: Q) : or P Q\n.\n*)\n\nPrint or.\n\nCheck (forall n: nat, n = 0 \\/ (n = 0 -> False) : Prop).\n\n(*\nAxiom axiom_of_choice:\n  forall A B (R: A -> B -> Prop), \n    (forall a: A, exists b: B, R a b) ->\n    exists f: A -> B,\n    forall a: A, R a (f a).\n*)\n\n(* Existential *)\n\n(*\nInductive ex (A: Type) (P: A -> Prop) : Prop :=\n| exist (a: A) (pf: P a) : ex A P\n.\n*)\n\nPrint ex.\n\nCheck (forall P: Prop, ((P->False)->False) -> P).\n\nCheck (forall P: Prop, P \\/ P->False).\n\nCheck ((exists a:nat, exists b:nat, exists c:nat, a*a*a + b*b*b = c*c*c)\n        -> False).\n\n(*\n  (exists a:A, e) === ex A (fun a => e)\n\n  (exists b:A, P b)\n  (exists ryu:A, P ryu)\n*)\n\nLemma ryu: exists n, n = 0 \\/ n = 1.\nProof.\n  exists 0.\n  left.\n  auto.\nQed.\n\nRequire Import Program.\n\nLemma ryu2: (exists n, n = n+1) -> False.\nProof.\n  intros EX.\n  destruct EX as [n EQ].\n  revert EQ.\n  induction n.\n  - intros. simpl in EQ. inversion EQ.\n  - intros. simpl in EQ.\n    apply IHn.\n    dependent destruction EQ.\n    assumption.\nQed.\n\nPrint ryu2.\n\n\n", "meta": {"author": "sigpl2017", "repo": "sigpl2017.github.io", "sha": "8ef36b0d282df3bc7d1c36d3d2918f029fecff5e", "save_path": "github-repos/coq/sigpl2017-sigpl2017.github.io", "path": "github-repos/coq/sigpl2017-sigpl2017.github.io/sigpl2017.github.io-8ef36b0d282df3bc7d1c36d3d2918f029fecff5e/download/Lecture3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.751729831085641}}
{"text": "(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\n(*ploy and highrt order functions*)\n(*介绍一下polymorphism,多态。泛化能力是很重要的～*)\nInductive boollist:Type :=\n  | bool_nil\n  | bool_cons(b : bool)(l:boollist).\nInductive list(X:Type):Type :=\n  | nil\n  | cons (x:X)(l:list X).\nCheck list.\nCheck (nil bool).\nCheck (cons bool).\nCheck (cons bool true (nil bool)).\nCheck nil.\nCheck cons.\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n(*\nlist: Type -> Type\nnil nat: list nat\ncons nat: nat -> list nat -> list nat\ncons nat 3 (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.\nExample test_repeat1:\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n(*\nExercise: 2 stars, standard (mumble_grumble)\nConsider the following two inductively defined types.\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).\nCheck mumble.\nCheck a.\nCheck (b a 1).\nCheck c.\nCheck d nat (b a 1).\nCheck d bool (b a 1).\nCheck e bool.\nCheck e bool true.\n(*e bool: bool -> grumble bool*)\n(*e bool true: grumble bool*)\nEnd MumbleGrumble.\n(*Type Annotation Interface*)\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.\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\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.\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\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.\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.\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\nExample test_rev2:\n  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(* Supplying Type Arguments Explicitly *)\nDefinition mynil : list nat := nil.\nCheck @nil.\nDefinition mynil' := @nil nat.\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).\nCheck [1;2;3].\nCheck [true;false;true].\nCompute [1;2;3]++[1;2;3].\n\nDefinition list123''' := [1;2;3].\n(* Exercise: 2 stars, standard, optional (poly_exercises) *)\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l. induction l as [| n l' IHl']. reflexivity.\n  simpl. rewrite IHl'. reflexivity.\nQed.\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']. simpl. reflexivity.\n  simpl. rewrite IHl'. reflexivity. \nQed.\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']. reflexivity.\n  simpl. rewrite IHl1'. reflexivity.\nQed.\n(* Exercise: 2 stars, standard, optional (more_poly_exercises) *)\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  induction l2 as [| n l2' IHl2']. reflexivity. simpl.\n  rewrite <- app_assoc. reflexivity. \n  simpl. rewrite IHl1'. rewrite app_assoc. reflexivity.\nQed.\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']. reflexivity.\n  simpl.\n  rewrite  rev_app_distr. simpl. rewrite IHl'. reflexivity.\nQed.\n\n(* Polymorphic Pairs *)\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\nArguments pair {X} {Y} _ _.\nCheck pair nat nat.\nCompute @pair.\nPrint pair.\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\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.\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.\nCheck list(prod nat nat).\nCheck @list(prod nat nat).\nCheck list(@prod nat nat).\nCheck (@fst (prod nat nat)).\nCheck list _.\nCheck (prod (list nat) (list nat)).\nCheck @nil _.\nCheck @nil nat.\nCheck prod Type Type.\nCheck prod (list nat) (list nat).\nCheck (nat * nat)%type.\n(* Exercise: 1 star, standard, optional (combine_checks) *)\nCheck @combine.\nCheck list nat.\nCheck (@nil nat).\nCheck (@nil nat).\nCheck prod (list nat) (list nat).\nCheck ((list nat) * (list nat))%type.\nCheck (nil,nil).\nCheck (list nat*list nat)%type.\nCheck (list nat,list nat).\nCheck (@nil nat,@nil nat).\nCheck @fst (nat*nat)%type.\nCheck @fst.\nCheck fst.\nCheck (nat*nat)%type.\n(* Exercise: 2 stars, standard, recommended (split) *)\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ((@nil X) , (@nil Y))\n  | (x,y)::t => ((x:: (fst (split t)) , y::(snd (split t))))\n  end.\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. simpl. reflexivity. Qed.\n(* Polymorphic Options *)\nModule OptionPlayground.\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X} _.\nArguments None {X}.\nEnd OptionPlayground.\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.\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(* Exercise: 1 star, standard, optional (hd_error_poly) *)\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h :: t => Some h\n  end.\nCheck @hd_error.\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(*Functions as Data*)\n(* Higher-Order Functions *)\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\nCheck @doit3times.\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\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.\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\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(*匿名函数*)\nExample test_anon_fun':\n  doit3times (fun n=>n*n) 2 = 256.\nProof. reflexivity. Qed.\nExample test_filter2':\n  filter (fun l=> (length l)=? 1)\n    [[1; 2];[3];[4];[5;6;7];[];[8]]=[[3];[4];[8]].\nProof. reflexivity. Qed.\n(*\nExercise: 2 stars, standard (filter_even_gt7)\nUse filter (instead of Fixpoint) to write a Coq function filter_even_gt7 \nthat takes a list of natural numbers as input \nand returns a list of just those that are even and greater than 7.\n*)\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun x => 7 <=? x) (filter evenb l).\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(*\nExercise: 3 stars, standard (partition)\nUse 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 test function of type X → bool and a list X, \npartition should return a pair of lists. \nThe first member of the pair is the sublist of the original list \ncontaining the elements that satisfy the test, and the second is \nthe sublist containing those that fail the test. The order of elements \nin the two 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. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(*Map,映射操作。给出一个[x1 x2 ... xn],得到[f x1 f x2 ... f xn]*)\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.\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\nExample test_map2 : map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[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(*Exercise: 3 stars, standard (map_rev)\nShow that map and rev commute. You may need to define an auxiliary lemma.\n*)\n\nTheorem map_theo: forall (X Y:Type) (f:X->Y)(l:list X)(k: X),\n  map f (l ++ [k]) = map f (l) ++ [f k].\nProof.\n  intros X Y f l k. induction l as [| n l' IHl']. reflexivity.\n  simpl. rewrite IHl'. reflexivity.\nQed.\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']. reflexivity.\n  simpl. rewrite <- IHl'. rewrite map_theo. reflexivity.\nQed.\n\n(* Exercise: 2 stars, standard, recommended (flat_map) \nThe function map maps a list X to a list Y using a function of type X → Y. \nWe can define a similar function, flat_map, \nwhich maps a list X to a list Y using a function f of type X → list Y.\nYour definition should work by 'flattening' the results of f.*)\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.\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(*Fold => map reduce的函数式特性*)\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.\nCompute fold plus [1;2;3;4] 0.\nCheck fold andb.\n\nExample fold_example1:\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\nExample fold_example2:\n  fold andb [true;false] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3:\n  fold app [[1];[];[2;3];[4]] [9] = [1;2;3;4;9].\nProof. reflexivity. Qed.\n(*构造函数的函数：Functions That Construct Functions*)\nDefinition constfun {X:Type} (x:X): nat->X:=\n  fun (k:nat) => x.\n(*上面的例子使用匿名函数作为函数的返回值*)\nDefinition ftrue := constfun true.\nExample constfun_exp1: ftrue 0 = true.\nProof. reflexivity. Qed.\nExample constfun_exp2: ftrue 1 = true.\nProof. reflexivity. Qed.\n(*ftrue忽略参数nat的值，只返回true（意义何在.....*)\nCheck plus.\nDefinition plus3 := plus 3.\nCheck plus3.\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(*Additional Exercise*)\nModule Exercises.\n(* Exercise: 2 stars, standard (fold_length) *)\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.\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l. induction l as [| n l' IHl']. reflexivity.\n  simpl. rewrite <- IHl'. reflexivity.\nQed.\nCheck andb.\n(* Exercise: 3 stars, standard (fold_map)\nWe can also define map in terms of fold. Finish fold_map below. *)\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y := \n  match l with\n  | [] => []\n  | h :: t => fold (fun h t => (f h)::t) l []\n  end.\nExample test_fold_map1 : fold_map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\nExample test_fold_map2: fold_map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\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(* Exercise: 2 stars, advanced (currying) *)\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\nCheck @prod_curry.\nCheck @prod_uncurry.\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. reflexivity.\nQed.\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. destruct p. reflexivity.\nQed.\n(* Exercise: 2 stars, advanced (nth_error_informal)*)\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(*\ninformal proof...do not do formal!!!!aaaaAAAA\nTheorem nth_error_theo : forall X n l,\n  length l = n -> @nth_error X l n = None.\nProof.\n  intros X n l H. rewrite <- H. \n  induction l as [| n' l' IHl']. reflexivity.\n  apply\n  simpl. rewrite IHl'. reflexivity.\n  rewrite <- H. simpl. \nQed.\n*)\n(*\nThe following exercises explore an alternative way of defining natural numbers, using the so-called Church numerals, named after mathematician Alonzo Church. We can represent a natural number n as a function that takes a function f as a parameter and returns f iterated n times.\n*)\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\nDefinition three : cnat := @doit3times.\nCompute  fun (X : Type) (f : X -> X) (x : X) => f x.\nCompute one bool negb false.\nCompute two bool negb false.\nCompute negb false.\nCompute negb (negb false).\nCompute one (bool->bool) (one bool) negb false.\nCompute one nat S O.\nCompute one nat S (one nat S O).\nCompute two nat S O.\nCompute one nat S (two nat S O).\nCompute one (nat->nat) (two nat) S O.\n(* Exercise: 1 star, advanced (church_succ) *)\nDefinition succ (n : cnat) : cnat := \n  fun (X : Type)(f:X->X)(x:X)=> (one X f) (n X f x).\nCompute zero nat S O.\nCompute succ zero nat S O.\nCompute one nat S O.\nCompute succ one nat S O.\nCompute two nat S O.\nCompute succ two nat S O.\nCompute three nat S O.\nCompute succ three nat S O.\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(*耶!!!!!!虽然只是1星习题但是好~开~心~*)\n(*\nExercise: 1 star, advanced (church_plus)\nAddition of two natural numbers:\n*)\nDefinition plus (n m : cnat) : cnat :=\n  fun (X : Type)(f:X->X)(x:X)=>  (m X f) (n X f x).\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.\nCompute one nat S O.\n(*\nExercise: 2 stars, advanced (church_mult)\nMultiplication:\n*)\nDefinition mult (n m : cnat) : cnat :=\n fun (X : Type)(f:X->X)(x:X)=> m X (n X f) x.\nCompute mult one zero nat S O.\nCompute mult two one nat S O.\nCompute mult three two nat S O.\nCompute mult two three nat S O.\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(* Exercise: 2 stars, advanced (church_exp) \nExponentiation:\n(Hint: Polymorphism plays a crucial role here. However, choosing the right type to iterate over can be tricky. If you hit a \"Universe inconsistency\" error, try iterating over a different type. Iterating over cnat itself is usually problematic.)\n*)\nDefinition exp (n m : cnat) : cnat :=\n  fun (X : Type)=> m (X->X) (n X).\nCompute exp one two nat S O.\nCompute exp two two nat S O.\nCompute exp three two nat S O.\nCompute exp two three nat S O.\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.\nEnd Church.\nEnd Exercises.\n", "meta": {"author": "santiweide", "repo": "software_foundation", "sha": "a45c9cf27801f206ee7baab391e750bcf09badfa", "save_path": "github-repos/coq/santiweide-software_foundation", "path": "github-repos/coq/santiweide-software_foundation/software_foundation-a45c9cf27801f206ee7baab391e750bcf09badfa/logic_foundations/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7516663738268164}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool.\n\n(** Prove the following lemmas by providing explicit proof terms.\nA bunch of exercises from the previous seminar we didn't have time\nto cover have made it to this homework :) *)\n\n\n(* An (unsound) placeholder so that the whole file typechecks.\nPlease replace it with your proof term. Your solutions may not\nuse any axioms, including `replace_with_your_solution_here` *)\nAxiom replace_with_your_solution_here : forall {A : Type}, A.\n\n\nSection Logic.\n\nVariables A B C : Prop.\nDefinition exfalso_quodlibet :\n    False -> A\n:= fun pF : False => match pF with end.\n\n(** * Exercise *)\nDefinition notTrue_iff_False : (~ True) <-> False\n:= conj\n  (fun f : (True -> False) => f I)\n  (fun x : False => match x with end).\nLocate \"<->\".\nPrint iff.\n(* Hint 1: use [Locate \"<->\".] and [Print iff.] commands to understand better\nthe type above. *)\n\n(* Hint 2: If you are experiencing an error like the following one\n\"Found a matching with no clauses on a term unknown to have an empty inductive type.\" try adding explicit type annotations to functional parameters or\nuse `match <term> in <type> with ... end` instead of `match <term> with ... end` *)\n\n\n(** * Exercise: double negation elimination works for `False` *)\nDefinition dne_False : ~ ~ False -> False\n:= fun f : ((False -> False) -> False) => f id.\nPrint id.\n\n(** * Exercise: double negation elimination works for `True` too. *)\nDefinition dne_True : ~ ~ True -> True\n:= fun f : ((True -> False) -> False) => I.\n\n\n(** * Exercise: Weak Peirce's law\nPeirce's law (https://en.wikipedia.org/wiki/Peirce%27s_law) is equivalent to\nDouble Negation Elimination (and the Law of Excluded Middle too),\nso it does not hold in general, but we can prove its weak form. *)\n(*\nDefinition weak_Peirce : ((((A -> B) -> A) -> A) -> B) -> B\n:= fun abaab : ((((A -> B) -> A) -> A) -> B) => A.\n*)\n(* Hint 1: use let-in expression to break the proof into pieces and solve them independently *)\n(* Hint 2: annotate the identifiers of let-expressions with types: [let x : <type> := ... in ...] *)\n\n\nVariable T : Type.\nVariable P Q : T -> Prop.\n\n(** * Exercise: existential introduction rule *)\nDefinition exists_introduction :\n  forall (x : T), P x -> (exists (x : T), P x)\n:= fun t : T => fun pt : P t => (ex_intro P t pt).\n\n(** * Exercise: Frobenius rule: existential quantifiers and conjunctions commute *)\nDefinition frobenius_rule :\n  (exists x, A /\\ P x) <-> A /\\ (exists x, P x)\n:= conj\n    (fun exAPx =>\n      match exAPx with\n        | (ex_intro x APx) =>\n          match APx with\n            | (conj pA Px) => conj pA (ex_intro _ x Px)\n          end\n      end)\n    (fun AexPx =>\n      match AexPx with\n        | (conj pA exPx) =>\n          match exPx with\n            | (ex_intro x px) => (ex_intro _ x (conj pA px))\n          end\n      end).\n\n\nEnd Logic.\n\n\n\nSection Equality.\n\nVariables A B C D : Type.\n\n(** * Exercise *)\nDefinition eq1 : true = (true && true)\n:= eq_refl (true && true).\n\n(** * Exercise *)\nDefinition eq2 : 42 = (if true then 21 + 21 else 239)\n:= eq_refl (if true then 21 + 21 else 239).\n\nVariable t : bool.\nCompute t || ~~ t.\nLocate \"_ || _\".\n\n(** * Exercise *)\nDefinition LEM_decidable :\n  forall (b : bool), b || ~~ b = true\n:= fun b : bool =>\n    match b return (b || ~~ b = true) with\n    | true => erefl true\n    | false => erefl true\n    end.\nPrint LEM_decidable.\n(** * Exercise *)\nDefinition if_neg :\n  forall (A : Type) (b : bool) (vT vF: A),\n    (if ~~ b then vT else vF) = if b then vF else vT\n:= fun _ b vT vF => \n    match b as c return ((if ~~ c then vT else vF) = if c then vF else vT)\n    with\n    | true => erefl vF\n    | false => erefl vT\n    end.\n\n(** * Exercise : associativity of function composition *)\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:= replace_with_your_solution_here.\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:= replace_with_your_solution_here.\n\n(** * Exercise: Symmetry *)\nDefinition eqext_sym :\n  forall (f g : A -> B), f =1 g -> g =1 f\n:= replace_with_your_solution_here.\n\n(** * Exercise: Transitivity *)\nDefinition eqext_trans :\n  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h\n:= replace_with_your_solution_here.\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:= replace_with_your_solution_here.\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:= replace_with_your_solution_here.\n\nEnd Equality.\n\n\n(** * Extra exercises (feel free to skip) *)\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:= replace_with_your_solution_here.\n\nDefinition negbNE :\n  forall b : bool, ~~ ~~ b = true -> b = true\n:= replace_with_your_solution_here.", "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/hw03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7516663652918252}}
{"text": "Inductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem ev_2 : ev 2.\nProof. apply (ev_SS 0 ev_0). Qed.\n\nTheorem add_even_even : forall {n m : nat}, ev m -> ev n -> ev (m + n).\nProof.\n  intros n m Hm Hn.\n  induction Hm.\n    { simpl. apply Hn. }\n    { simpl. apply ev_SS. apply IHHm. }\nQed.\n\nTheorem ev_4_alt : ev 4.\nProof.\n  apply (add_even_even ev_2 ev_2).\nQed.\n", "meta": {"author": "scottviteri", "repo": "ManipulateProofTrees", "sha": "7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7", "save_path": "github-repos/coq/scottviteri-ManipulateProofTrees", "path": "github-repos/coq/scottviteri-ManipulateProofTrees/ManipulateProofTrees-7aeaf156031d80726c7a8cf9b6fce0b4eefd3fe7/ProofSourceFiles/ev_4_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7516083970330082}}
{"text": "(* Exercise 39 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_039 : ~ (exists x, P x \\/ Q x) -> (forall x, ~ P x /\\ ~ Q x).\nProof.\nimp_i a1.\nall_i a.\ncon_i.\nneg_e' (exists x:D, P x \\/ Q x) a2.\nhyp a1.\nexi_i a.\ndis_i1.\nneg_e' (~(P a)) a3.\nhyp a2.\nhyp a3.\nneg_e' (exists x:D, P x \\/ Q x) a2.\nhyp a1.\nexi_i a.\ndis_i2.\nneg_e' (~(Q 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/Taak13/Taak13_pred039.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7516083864199808}}
{"text": "Require Import ssreflect.\n\n(**\n# 第8回\n\nhttp://qnighy.github.io/coqex2014/ex6.html\n\n## 課題38 (種別:A / 締め切り : 2014/06/01)\n\nモノイドを型クラスとして定義する。以下の空欄を埋めよ。\n*)\n\n(* モノイド *)\nClass Monoid (T : Type) := {\n  mult : T -> T -> T\n    where \"x * y\" := (mult x y);\n  one : T\n    where \"1\" := one;\n  mult_assoc x y z : x * (y * z) = (x * y) * z;\n  mult_1_l x : 1 * x = x;\n  mult_1_r x : x * 1 = x\n}.\n\nDelimit Scope monoid_scope with monoid.\nLocal Open Scope monoid_scope.\n\nNotation \"x * y\" := (mult x y) : monoid_scope.\nNotation \"1\" := one : monoid_scope.\n\n(* モノイドのリストの積 *)\nRequire Import List.\nCheck @fold_right bool bool.\nCheck @mult.\n\nDefinition product_of {T : Type} {M : Monoid T} : list T -> T :=\n  fun (l : list T) => fold_right mult 1 l.\n(* @fold_right T T (@mult T M) 1 l *)\n\n\n(* 自然数の最大値関数に関するモノイド *)\nRequire Import Arith.\nCheck max.\nProgram Instance MaxMonoid : Monoid nat :=\n  {|\n    mult x y := max x y;\n    one := 0\n  |}.\nNext Obligation.                            (* max x (max y z) = max (max x y) z *)\n  by rewrite Max.max_assoc.\nQed.\nNext Obligation.                            (* max x 0 = 0 *)\n  by rewrite Max.max_0_r.\nQed.\n\nEval compute in product_of (3 :: 2 :: 6 :: 4 :: nil). (* => 6 *)\nEval compute in product_of (@nil nat). (* => 0 *)\n\n(**\nヒント\n\nClassの実体はRecordです。Classとして宣言すると、型クラスのように自動でインスタンスを探しに\n行くようになり、インスタンスを明示する必要がなくなります。SetoidやProperもクラスです。\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/ex38.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7515926856298253}}
{"text": "Require Export P08.\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\n       beval st (BEq a1 a2)\n     = beval st (fold_constants_bexp (BEq a1 a2)).\n\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\n           fold_constants_bexp (BEq a1 a2)\n         = if beq_nat n1 n2 then BTrue else BFalse\n\n       and\n\n           beval st (BEq a1 a2)\n         = beq_nat (aeval st a1) (aeval st a2).\n\n       By the soundness of constant folding for arithmetic\n       expressions (Lemma [fold_constants_aexp_sound]), we know\n\n           aeval st a1\n         = aeval st (fold_constants_aexp a1)\n         = aeval st (ANum n1)\n         = n1\n\n       and\n\n           aeval st a2\n         = aeval st (fold_constants_aexp a2)\n         = aeval st (ANum n2)\n         = n2,\n\n       so\n\n           beval st (BEq a1 a2)\n         = beq_nat (aeval a1) (aeval a2)\n         = beq_nat n1 n2.\n\n       Also, it is easy to see (by considering the cases [n1 = n2] and\n       [n1 <> n2] separately) that\n\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\n       So\n\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\n           beval st (BEq a1 a2)\n         = beval st (BEq (fold_constants_aexp a1)\n                         (fold_constants_aexp a2)),\n\n       which, by the definition of [beval], is the same as showing\n\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\n       But the soundness of constant folding for arithmetic\n       expressions ([fold_constants_aexp_sound]) gives us\n\n         aeval st a1 = aeval st (fold_constants_aexp a1)\n         aeval st a2 = aeval st (fold_constants_aexp a2),\n\n       completing the case.  []\n*)\n\nTheorem fold_constants_bexp_sound:\n  btrans_sound fold_constants_bexp.\nProof.\n  unfold btrans_sound. intros b. unfold bequiv. intros st.\n  induction b;\n    (* BTrue and BFalse are immediate *)\n    try reflexivity.\n  - (* BEq *)\n    rename a into a1. rename a0 into a2. simpl.\n\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\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\n      (** The only interesting case is when both a1 and a2\n          become constants after folding *)\n\n      simpl. destruct (beq_nat n n0); reflexivity.\n  - (* BLe *)\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    simpl. destruct (leb n n0); reflexivity.\n  - (* BNot *)\n    simpl. remember (fold_constants_bexp b) as b' eqn:Heqb'.\n    rewrite IHb.\n    destruct b'; reflexivity.\n\n  - (* 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    destruct b1'; destruct b2'; 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/07/P09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938679, "lm_q2_score": 0.9019206804839998, "lm_q1q2_score": 0.7515926748676826}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 (mult x z) 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/goal33conj221_coqofml_a92ldM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7515806316292699}}
{"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 with (i_prec 10).\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": "ejgallego", "repo": "interval", "sha": "6e71cac4a9f2f58a5980ade813f1fcd68d115992", "save_path": "github-repos/coq/ejgallego-interval", "path": "github-repos/coq/ejgallego-interval/interval-6e71cac4a9f2f58a5980ade813f1fcd68d115992/testsuite/example-20071016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7515806292395517}}
{"text": "(* filtering_lists.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Teacher: Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Student name: Benjamin Nørgaard *)\n(* Student number: 201209884 *)\n\n(* ********** *)\n\n(* The goal of this project is to study\n   how to filter elements in or out of lists.\n*)\n\nRequire Import List Bool.\n\nLtac unfold_tactic name :=\n  intros; unfold name;\n  reflexivity.\n\n(* The Bool library defines\n     true,\n     false,\n     andb (noted && in infix notation),\n     orb (noted || in infix notation),\n     and negb.\n   It also provides the following equations:\n\n    andb_true_l : forall b : bool, true && b = b\n    andb_true_r : forall b : bool, b && true = b\n   andb_false_l : forall b : bool, false && b = false\n   andb_false_r : forall b : bool, b && false = false\n    orb_false_l : forall b : bool, false || b = b\n    orb_false_r : forall b : bool, b || false = b\n     orb_true_r : forall b : bool, b || true = true\n     orb_true_l : forall b : bool, true || b = true\n\n   andb_true_iff\n        : forall b1 b2 : bool, b1 && b2 = true <-> b1 = true /\\ b2 = true\n   andb_false_iff:\n     forall b1 b2 : bool, b1 && b2 = false <-> b1 = false \\/ b2 = false\n   orb_false_iff\n        : forall b1 b2 : bool, b1 || b2 = false <-> b1 = false /\\ b2 = false\n   orb_true_iff\n        : forall b1 b2 : bool, b1 || b2 = true <-> b1 = true \\/ b2 = true\n\nYou will also have the use of the two following unfold lemmas:\n*)\n\nLemma unfold_negb_base_case_true :\n  negb true = false.\nProof.\n  unfold_tactic negb.\nQed.\n\nLemma unfold_negb_base_case_false :\n  negb false = true.\nProof.\n  unfold_tactic negb.\nQed.\n\n(* Also, when, among the assumptions, you have\n     H_foo : true = false\n   remember that the command\n     discriminate H_foo.\n   solves the current subgoal.\n*)\n\n(* And finally, remember that\n      destruct blah as [...] eqn:H_blah.\n    has the niceness of adding an assumption H_blah\n    that reflects the destruction.  For example,\n    if foo has type bool,\n      destruct foo as [ | ] eqn:H_foo.\n    will successively provide\n      H_foo : foo = true\n    and then\n      H_foo : foo = false\n*)\n\n(* ********** *)\n\n(* All of that said, here is a specification: *)\n\nDefinition specification_of_filter_in (filter_in : (nat -> bool) -> list nat -> list nat) :=\n  (forall p : nat -> bool,\n     filter_in p nil = nil)\n  /\\\n  (forall (p : nat -> bool)\n          (x : nat)\n          (xs' : list nat),\n     p x = true ->\n     filter_in p (x :: xs') = x :: (filter_in p xs'))\n  /\\\n  (forall (p : nat -> bool)\n          (x : nat)\n          (xs' : list nat),\n     p x = false ->\n     filter_in p (x :: xs') = filter_in p xs').\n\n(* You are asked to:\n\n   * write unit tests for filter_in;\n\n   * prove whether this definition specifies a unique function;\n\n   * implement a definition of filter_in that satisfies the\n     specification;\n\n   * prove the following theorems:\n*)\n\n(* We will use the following function to construct a function which compares two nat lists *)\nFixpoint beq_list (T : Type) (l1 l2 : list T) (comp : T -> T -> bool) := \n  match l1 with\n  | nil =>\n      match l2 with\n      | nil => true\n      | _ => false\n      end\n  | e :: l =>\n      match l2 with\n      | nil => false\n      | e' :: l' =>\n          match comp e e' with\n          | false => false\n          | true => beq_list T l l' comp\n          end\n      end\n  end.\n\nRequire Import Arith.\n\nDefinition beq_nat_list (l1 l2 : list nat) :=\n  beq_list nat l1 l2 beq_nat.\n\nNotation \"A =l= B\" := (beq_nat_list A B) (at level 70, right associativity).\n\n(* We will use the following two functions as examples of predicates which we\n* can use to filter elements in or out of lists *)\nFixpoint odd (n : nat) :=\n  match n with\n    | O => false\n    | 1 => true\n    | S (S n) => odd n\n  end.\n\nDefinition even (n : nat) :=\n  negb (odd n).\n\nDefinition unit_test_for_filter_in (candidate : (nat -> bool) -> list nat -> list nat) :=\n  (candidate (fun _ => true) \n             (1 :: 2 :: 3 :: nil) =l= (1 :: 2 :: 3 :: nil))\n  &&\n  (candidate (fun _ => false) \n             (1 :: 2 :: 3 :: nil) =l= nil)\n  &&\n  (candidate (beq_nat 2) \n             (1 :: 2 :: 3 :: nil) =l= (2 :: nil))\n  &&\n  (candidate even (1 :: 2 :: 3 :: nil) =l= (2 :: nil))\n  &&\n  (candidate odd (1 :: 2 :: 3 :: nil) =l= (1 :: 3 :: nil)).\n\nTheorem there_is_only_one_filter_in :\n  forall (f g : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_in f ->\n    specification_of_filter_in g ->\n    forall (p : (nat -> bool)) (xs : list nat),\n      f p xs = g p xs.\nProof.\n  intros f g.\n  intros S_f S_g.\n  intros p xs.\n  unfold specification_of_filter_in in S_f.\n  destruct S_f as [H_f_nil [H_f_true H_f_false]]. \n  unfold specification_of_filter_in in S_g.\n  destruct S_g as [H_g_nil [H_g_true H_g_false]].\n  induction xs as [ | x xs' IHxs'].\n    rewrite -> H_g_nil.\n    apply (H_f_nil p).\n  case (p x) as [ | ] eqn:H_p.\n    rename H_p into H_p_true.\n    rewrite -> (H_f_true p x xs' H_p_true).\n    rewrite -> (H_g_true p x xs' H_p_true).\n    rewrite -> IHxs'.\n    reflexivity.\n  rename H_p into H_p_false.\n  rewrite -> (H_f_false p x xs' H_p_false).\n  rewrite -> (H_g_false p x xs' H_p_false).\n  apply IHxs'.\nQed.\n\nFixpoint filter_in_ds (p : nat -> bool) (xs : list nat) :=\n  match xs with\n  | nil => nil\n  | x :: xs' => \n      match p x with\n      | true => x :: filter_in_ds p xs'\n      | false => filter_in_ds p xs'\n      end\n  end.\n\nDefinition filter_in_v0 (p : nat -> bool) (xs : list nat) :=\n  filter_in_ds p xs.\n\nCompute unit_test_for_filter_in filter_in_v0.\n\nLemma unfold_filter_in_ds_bc :\n  forall (p : nat -> bool),\n    filter_in_ds p nil = nil.\nProof.\n  unfold_tactic filter_in_ds.\nQed.\n\nLemma unfold_filter_in_ds_ic :\n  forall (p : nat -> bool) (x : nat) (xs' : list nat),\n    filter_in_ds p (x :: xs') = \n      match p x with\n      | true => x :: filter_in_ds p xs'\n      | false => filter_in_ds p xs'\n      end.\nProof.\n  unfold_tactic filter_in_ds.\nQed.\n\nProposition filter_in_v0_fits_the_specification_of_filter_in :\n  specification_of_filter_in filter_in_v0.\nProof.\n  unfold specification_of_filter_in.\n  split.\n    intro p.\n    unfold filter_in_v0.\n    apply (unfold_filter_in_ds_bc p).\n  split.\n    intros p x xs'.\n    intro H_p_true.\n    unfold filter_in_v0.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    reflexivity.\n  intros p x xs'.\n  intros H_p_false.\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  reflexivity.\nQed.\n\n(* The following lemma will be handy, because we will be able to use things we \n* have proven about filter_in_v0 for any filter_in satisfying the specification *)\nLemma any_filter_in_can_be_rewritten_to_filter_in_v0 :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_in p xs = filter_in_v0 p xs.\nProof.\n  intros filter_in S_filter_in.\n  intros p xs.\n  rewrite -> (there_is_only_one_filter_in filter_in\n                                          filter_in_v0\n                                          S_filter_in\n                                          filter_in_v0_fits_the_specification_of_filter_in).\n  reflexivity.\nQed.\n\nTheorem about_filtering_in_all_of_the_elements :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    forall xs : list nat, (* I renamed this from ns to xs for consistency *)\n      filter_in (fun _ => true) xs = xs.\nProof.\n  intros filter_in S_filter_in.\n  intro xs.\n  rewrite -> (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in\n                                                             S_filter_in).\n  induction xs as [ | x xs' IHxs'].\n    unfold filter_in_v0.\n    rewrite -> unfold_filter_in_ds_bc.\n    reflexivity.\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  unfold filter_in_v0 in IHxs'.\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n\nTheorem about_filtering_in_none_of_the_elements :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    forall xs : list nat, (* I renamed this from ns to xs for consistency *)\n      filter_in (fun _ => false) xs = nil.\nProof.\n  intros filter_in S_filter_in.\n  intro xs.\n  rewrite -> (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in \n                                                             S_filter_in).\n  induction xs as [ | x xs' IHxs'].\n    unfold filter_in_v0.\n    rewrite unfold_filter_in_ds_bc.\n    reflexivity.\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  unfold filter_in_v0 in IHxs'.\n  apply IHxs'.\nQed.\n\nTheorem about_filtering_in_incrementally :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    forall (p1 p2 : nat -> bool)\n           (xs : list nat), (* I renamed this to xs from ns for consistency *)\n      filter_in p2 (filter_in p1 xs) =\n      filter_in (fun n => andb (p1 n) (p2 n)) xs. \n      (* I renamed x to n in the above funtion to avoid automatic naming when\n      * doing induction on xs*)\nProof.\n  intros filter_in S_filter_in.\n  intros p1 p2 xs.\n  rewrite ->3 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in \n                                                              S_filter_in).\n  unfold filter_in_v0.\n  induction xs as [ | x xs' IHxs' ].\n    rewrite -> (unfold_filter_in_ds_bc p1).\n    rewrite -> (unfold_filter_in_ds_bc p2).\n    rewrite -> unfold_filter_in_ds_bc.\n    reflexivity.\n  case (p1 x) as [ | ] eqn:H_p1.\n    case (p2 x) as [ | ] eqn:H_p2.\n      rename H_p1 into H_p1_true.\n      rename H_p2 into H_p2_true.\n      rewrite -> unfold_filter_in_ds_ic.\n      rewrite -> H_p1_true.\n      rewrite -> unfold_filter_in_ds_ic.\n      rewrite -> H_p2_true.\n      rewrite -> IHxs'.\n      rewrite -> unfold_filter_in_ds_ic.\n      rewrite -> H_p1_true.\n      rewrite -> andb_true_l.\n      rewrite -> H_p2_true.\n      reflexivity.\n    rename H_p1 into H_p1_true.\n    rename H_p2 into H_p2_false.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p1_true.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p2_false.\n    rewrite -> IHxs'.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p1_true.\n    rewrite -> andb_true_l.\n    rewrite -> H_p2_false.\n    reflexivity.\n  rename H_p1 into H_p1_false.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p1_false.\n  rewrite -> IHxs'.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p1_false.\n  rewrite -> andb_false_l.\n  reflexivity.\nQed.\n     \n(* ********** *)\n     \n(* Here is another specification: *)\n   \nDefinition specification_of_filter_out (filter_out : (nat -> bool) -> list nat -> list nat) :=\n  (forall p : nat -> bool,\n     filter_out p nil = nil)\n  /\\\n  (forall (p : nat -> bool)\n          (x : nat)\n          (xs' : list nat),\n     p x = true ->\n     filter_out p (x :: xs') = filter_out p xs')\n  /\\\n  (forall (p : nat -> bool)\n          (x : nat)\n          (xs' : list nat),\n     p x = false ->\n     filter_out p (x :: xs') = x :: (filter_out p xs')).\n\n(* You are asked to:\n\n   * write unit tests for filter_out;\n\n   * prove whether this definition specifies a unique function;\n\n   * implement a definition of filter_out that satisfies the\n     specification;\n\n   * prove properties that are analogue to filter_in; and to\n\n   * prove the two following propositions:\n*)\n\nDefinition unit_test_for_filter_out (candidate : (nat -> bool) -> list nat -> list nat) :=\n  (candidate (fun _ => true) \n             (1 :: 2 :: 3 :: nil) =l= nil)\n  &&\n  (candidate (fun _ => false) \n             (1 :: 2 :: 3 :: nil) =l= (1 :: 2 :: 3 :: nil))\n  &&\n  (candidate (beq_nat 2) \n             (1 :: 2 :: 3 :: nil) =l= (1 :: 3 :: nil))\n  &&\n  (candidate even (1 :: 2 :: 3 :: nil) =l= (1 :: 3 :: nil))\n  &&\n  (candidate odd (1 :: 2 :: 3 :: nil) =l= (2 :: nil)).\n\nTheorem there_is_only_one_filter_out :\n  forall (f g : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_out f ->\n    specification_of_filter_out g ->\n    forall (p : (nat -> bool)) (xs : list nat),\n      f p xs = g p xs.\nProof.\n  intros f g.\n  intros S_f S_g.\n  intros p xs.\n  unfold specification_of_filter_out in S_f.\n  destruct S_f as [H_f_nil [H_f_true H_f_false]]. \n  unfold specification_of_filter_out in S_g.\n  destruct S_g as [H_g_nil [H_g_true H_g_false]].\n  induction xs as [ | x xs' IHxs'].\n    rewrite -> (H_f_nil p).\n    rewrite -> (H_g_nil p).\n    reflexivity.\n  case (p x) as [ | ] eqn:H_p.\n    rename H_p into H_p_true.\n    rewrite -> (H_f_true p x xs' H_p_true).\n    rewrite -> (H_g_true p x xs' H_p_true).\n    apply IHxs'.\n  rename H_p into H_p_false.\n  rewrite -> (H_f_false p x xs' H_p_false).\n  rewrite -> (H_g_false p x xs' H_p_false).\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n\nFixpoint filter_out_ds (p : nat -> bool) (xs : list nat) :=\n  match xs with\n  | nil => nil\n  | x :: xs' => \n      match p x with\n      | true => filter_out_ds p xs'\n      | false => x :: filter_out_ds p xs'\n      end\n  end.\n\nDefinition filter_out_v0 (p : nat -> bool) (xs : list nat) :=\n  filter_out_ds p xs.\n\nCompute unit_test_for_filter_out filter_out_v0.\n\nLemma unfold_filter_out_ds_bc :\n  forall (p : nat -> bool),\n    filter_out_ds p nil = nil.\nProof.\n  unfold_tactic filter_out_ds.\nQed.\n\nLemma unfold_filter_out_ds_ic :\n  forall (p : nat -> bool) (x : nat) (xs' : list nat),\n    filter_out_ds p (x :: xs') = \n      match p x with\n      | true => filter_out_ds p xs'\n      | false => x :: filter_out_ds p xs'\n      end.\nProof.\n  unfold_tactic filter_out_ds.\nQed.\n\nProposition filter_out_v0_fits_the_specification_of_filter_out :\n  specification_of_filter_out filter_out_v0.\nProof.\n  unfold specification_of_filter_out.\n  split.\n    intro p.\n    unfold filter_out_v0.\n    apply (unfold_filter_out_ds_bc p).\n  split.\n    intros p x xs'.\n    intros H_p_true.\n    unfold filter_out_v0.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p_true.\n    reflexivity.\n  intros p x xs'.\n  intro H_p_false.\n  unfold filter_out_v0.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p_false.\n  reflexivity.\nQed.\n\nLemma any_filter_out_can_be_rewritten_to_filter_out_v0 :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_out p xs = filter_out_v0 p xs.\nProof.\n  intros filter_out S_filter_out.\n  intros p xs.\n  rewrite -> (there_is_only_one_filter_out filter_out\n                                           filter_out_v0\n                                           S_filter_out\n                                           filter_out_v0_fits_the_specification_of_filter_out).\n  reflexivity.\nQed.\n\nTheorem about_filtering_out_all_of_the_elements :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    forall xs : list nat,\n      filter_out (fun _ => true) xs = nil.\nProof.\n  intros filter_out S_filter_out.\n  intro xs.\n  rewrite -> (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out \n                                                               S_filter_out).\n  induction xs as [ | x xs' IHxs'].\n    unfold filter_out_v0.\n    rewrite -> unfold_filter_out_ds_bc.\n    reflexivity.\n  unfold filter_out_v0.\n  rewrite -> unfold_filter_out_ds_ic.\n  unfold filter_out_v0 in IHxs'.\n  apply IHxs'.\nQed.\n\nTheorem about_filtering_out_none_of_the_elements :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    forall xs : list nat,\n      filter_out (fun _ => false) xs = xs.\nProof.\n  intros filter_out S_filter_out.\n  intro xs.\n  rewrite -> (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out \n                                                               S_filter_out).\n  induction xs as [ | x xs' IHxs'].\n    unfold filter_out_v0.\n    rewrite unfold_filter_out_ds_bc.\n    reflexivity.\n  unfold filter_out_v0.\n  rewrite unfold_filter_out_ds_ic.\n  unfold filter_out_v0 in IHxs'.\n  rewrite -> IHxs'.\n  reflexivity.\nQed.\n\nTheorem about_filtering_out_incrementally :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    forall (p1 p2 : nat -> bool)\n           (xs : list nat),\n      filter_out p2 (filter_out p1 xs) =\n      filter_out (fun n => orb (p1 n) (p2 n)) xs.\nProof.\n  intros filter_out S_filter_out.\n  intros p1 p2 xs.\n  rewrite ->3 (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out \n                                                                S_filter_out).\n  unfold filter_out_v0.\n  induction xs as [ | x xs' IHxs' ].\n    rewrite -> (unfold_filter_out_ds_bc p1).\n    rewrite -> (unfold_filter_out_ds_bc p2).\n    rewrite -> unfold_filter_out_ds_bc.\n    reflexivity.\n  case (p1 x) as [ | ] eqn:H_p1.\n    case (p2 x) as [ | ] eqn:H_p2.\n      rename H_p1 into H_p1_true.\n      rename H_p2 into H_p2_true.\n      rewrite -> unfold_filter_out_ds_ic.\n      rewrite -> H_p1_true.\n      rewrite -> unfold_filter_out_ds_ic.\n      rewrite -> H_p1_true.\n      rewrite -> orb_true_l.\n      apply IHxs'.\n    rename H_p1 into H_p1_true.\n    rename H_p2 into H_p2_false.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p1_true.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p1_true.\n    rewrite -> orb_true_l.\n    apply IHxs'.\n  rename H_p1 into H_p1_false.\n  case (p2 x) as [ | ] eqn:H_p2.\n    rename H_p2 into H_p2_true.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p1_false.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p2_true.\n    rewrite -> IHxs'.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p2_true.\n    rewrite -> orb_true_r.\n    reflexivity.\n  rename H_p2 into H_p2_false.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p1_false.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p2_false.\n  rewrite -> IHxs'.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p1_false.\n  rewrite -> orb_false_l.\n  rewrite -> H_p2_false.\n  reflexivity.\nQed.\n\n\nProposition filter_out_from_filter_in :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    specification_of_filter_out (fun p ns => filter_in (fun n => negb (p n)) ns).\n    (* Renamed x to n in the above innermost function to avoid automatic naming *)\nProof.\n  intros filter_in S_filter_in.\n  unfold specification_of_filter_out.\n  split.\n    intro p.\n    rewrite -> (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in \n                                                               S_filter_in).\n    unfold filter_in_v0.\n    apply unfold_filter_in_ds_bc.\n  split.\n    intros p x xs'.\n    intro H_p_true.\n    rewrite ->2 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in \n                                                                S_filter_in).\n    unfold filter_in_v0.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_negb_base_case_true.\n    reflexivity.\n  intros p x xs'.\n  intro H_p_false.\n  rewrite ->2 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in \n                                                              S_filter_in).\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> unfold_negb_base_case_false.\n  reflexivity.\nQed.\n\nProposition filter_in_from_filter_out :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    specification_of_filter_in (fun p ns => filter_out (fun n => negb (p n)) ns).\nProof.\n  intros filter_out S_filter_out.\n  unfold specification_of_filter_in.\n  split.\n    intro p.\n    rewrite -> (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out \n                                                                 S_filter_out).\n    unfold filter_out_v0.\n    apply unfold_filter_out_ds_bc.\n  split.\n    intros p x xs'.\n    intro H_p_true.\n    rewrite ->2 (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out\n                                                                  S_filter_out).\n    unfold filter_out_v0.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_negb_base_case_true.\n    reflexivity.\n  intros p x xs'.\n  intro H_p_false.\n  rewrite ->2 (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out \n                                                                S_filter_out).\n  unfold filter_out_v0.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> unfold_negb_base_case_false.\n  reflexivity.\nQed.\n\n(* Which consequences of these propositions can you think of? *)\n\n(* We can define filter_out using filter_in *)\nDefinition filter_out_v1 (p : nat -> bool) (xs : list nat) :=\n  filter_in_v0 (fun n => negb (p n)) xs.\n\nCompute unit_test_for_filter_out filter_out_v1.\n\nProposition filter_out_v1_fits_the_specification_of_filter_out :\n  specification_of_filter_out filter_out_v1.\nProof.\n  unfold specification_of_filter_out.\n  split.\n    intro p.\n    unfold filter_out_v1.\n    unfold filter_in_v0.\n    apply unfold_filter_in_ds_bc.\n  split.\n    intros p x xs'.\n    intro H_p_true.\n    unfold filter_out_v1.\n    unfold filter_in_v0.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_negb_base_case_true.\n    reflexivity.\n  intros p x xs'.\n  intro H_p_false.\n  unfold filter_out_v1.\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> unfold_negb_base_case_false.\n  reflexivity.\nQed.\n\nLemma any_filter_out_can_be_rewritten_to_filter_out_v1 :\n  forall filter_out : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_out filter_out ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_out p xs = filter_out_v1 p xs.\nProof.\n  intros filter_out S_filter_out.\n  intros p xs.\n  rewrite -> (there_is_only_one_filter_out filter_out\n                                           filter_out_v1\n                                           S_filter_out\n                                           filter_out_v1_fits_the_specification_of_filter_out).\n  reflexivity.\nQed.\n\n(* We can define filter_in using filter_out *)\nDefinition filter_in_v1 (p : nat -> bool) (xs : list nat) :=\n  filter_out_v0 (fun n => negb (p n)) xs.\n\nCompute unit_test_for_filter_in filter_in_v1.\n\nProposition filter_in_v1_fits_the_specification_of_filter_in :\n  specification_of_filter_in filter_in_v1.\nProof.\n  unfold specification_of_filter_in.\n  split.\n    intro p.\n    unfold filter_in_v1.\n    unfold filter_out_v0.\n    apply unfold_filter_out_ds_bc.\n  split.\n    intros p x xs'.\n    intro H_p_true.\n    unfold filter_in_v1.\n    unfold filter_out_v0.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_negb_base_case_true.\n    reflexivity.\n  intros p x xs'.\n  intro H_p_false.\n  unfold filter_in_v1.\n  unfold filter_out_v0.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> unfold_negb_base_case_false.\n  reflexivity.\nQed.\n\nLemma any_filter_in_can_be_rewritten_to_filter_in_v1 :\n  forall filter_in : (nat -> bool) -> list nat -> list nat,\n    specification_of_filter_in filter_in ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_in p xs = filter_in_v1 p xs.\nProof.\n  intros filter_in S_filter_in.\n  intros p xs.\n  rewrite -> (there_is_only_one_filter_in filter_in\n                                          filter_in_v1\n                                          S_filter_in\n                                          filter_in_v1_fits_the_specification_of_filter_in).\n  reflexivity.\nQed.\n\n(* Using the two propositions above we could have proven filter_out theorems\n* using the filter_in_ds unfold lemmas and vice versa. Let's try to do that in\n* the following proofs. *)\n\n(* ********** *)\n\n(* What is the result\n\n   * of applying filter_in to the concatenation of two lists? \n   \n   * of applying filter_out to the concatenation of two lists?\n\n   * of applying filter_in to a reversed list?\n\n   * of applying filter_out to a reversed list?\n*)\n\n(* ********** *)\n\n(* We will answer the above questions with four theorems and their proofs *)\n\n(* We will need the following two lemmas for the following theorems *)\n\nLemma unfold_append_bc :\n  forall (xs : list nat),\n    nil ++ xs = xs.\nProof.\n  apply app_nil_l.\nQed.\n\nLemma unfold_append_ic :\n  forall (x : nat) (xs1' xs2 : list nat),\n    (x :: xs1') ++ xs2 = x :: (xs1' ++ xs2).\nProof.\n  intros x xs1' xs2.\n  symmetry.\n  apply app_comm_cons.\nQed.\n\nTheorem about_filter_in_and_concatenation_of_lists :\n  forall (filter_in : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_in filter_in ->\n    forall (p : nat -> bool) (xs1 xs2 : list nat),\n      filter_in p (xs1 ++ xs2) = filter_in p xs1 ++ filter_in p xs2.\nProof.\n  intros filter_in S_filter_in.\n  intros p xs1 xs2.\n  rewrite ->3 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in\n                                                              S_filter_in).\n  unfold filter_in_v0.\n  induction xs1 as [ | x xs1' IHxs1'].\n    rewrite -> unfold_append_bc.\n    rewrite -> unfold_filter_in_ds_bc.\n    rewrite -> unfold_append_bc.\n    reflexivity.\n  rewrite -> unfold_append_ic.\n  case (p x) as [ | ] eqn:H_p.\n    rename H_p into H_p_true.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> IHxs1'.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_append_ic.\n    reflexivity.\n  rename H_p into H_p_false.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> IHxs1'.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  reflexivity.\nQed.\n\nTheorem about_filter_out_and_concatenation_of_lists :\n  forall (filter_out : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_out filter_out ->\n    forall (p : nat -> bool) (xs1 xs2 : list nat),\n      filter_out p (xs1 ++ xs2) = filter_out p xs1 ++ filter_out p xs2.\nProof.\n  intros filter_out S_filter_out.\n  intros p xs1 xs2.\n  rewrite ->3 (any_filter_out_can_be_rewritten_to_filter_out_v0 filter_out S_filter_out).\n  unfold filter_out_v0.\n  induction xs1 as [ | x xs1' IHxs1'].\n    rewrite -> unfold_append_bc.\n    rewrite -> unfold_filter_out_ds_bc.\n    rewrite -> unfold_append_bc.\n    reflexivity.\n  rewrite -> unfold_append_ic.\n  case (p x) as [ | ] eqn:H_p.\n    rename H_p into H_p_true.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> IHxs1'.\n    rewrite -> unfold_filter_out_ds_ic.\n    rewrite -> H_p_true.\n    reflexivity.\n  rename H_p into H_p_false.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> IHxs1'.\n  rewrite -> unfold_filter_out_ds_ic.\n  rewrite -> H_p_false.\n  reflexivity.\n  Show Proof.\n\n  Restart.\n  (* or proven by the help of the connection between filter_in and filter_out *)\n  intros filter_out S_filter_out.\n  intros p xs1 xs2.\n  rewrite ->3 (any_filter_out_can_be_rewritten_to_filter_out_v1 filter_out\n                                                                S_filter_out).\n  unfold filter_out_v1.\n  assert (S_filter_in_v0 := filter_in_v0_fits_the_specification_of_filter_in).\n  apply (about_filter_in_and_concatenation_of_lists filter_in_v0\n                                                    S_filter_in_v0\n                                                    (fun n : nat => negb (p n))\n                                                    xs1 xs2).\nQed.\n\n(* We will need the following two lemmas for proving the following two theorems *)\nLemma unfold_reverse_bc :\n  forall (T : Type),\n    rev nil = (nil : list T).\nProof.\n  unfold_tactic rev.\nQed.\n\nLemma unfold_reverse_ic :\n  forall (T : Type) (x : T) (xs : list T),\n    rev (x :: xs) = rev xs ++ x :: nil.\nProof.\n  unfold_tactic rev.\nQed.\n\nTheorem about_filter_in_and_reverse_list :\n  forall (filter_in : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_in filter_in ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_in p (rev xs) = rev (filter_in p xs).\nProof.\n  intros filter_in S_filter_in.\n  intros p xs.\n  induction xs as [ | x xs' IHxs'].\n    rewrite ->2 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in\n                                                                S_filter_in).\n    unfold filter_in_v0.\n    rewrite -> unfold_reverse_bc.\n    rewrite -> unfold_filter_in_ds_bc.\n    rewrite -> unfold_reverse_bc.\n    reflexivity.\n  rewrite -> unfold_reverse_ic.\n  case (p x) as [ | ] eqn:H_p.\n    rename H_p into H_p_true.\n    rewrite -> (about_filter_in_and_concatenation_of_lists filter_in\n                                                           S_filter_in\n                                                           p (rev xs') (x :: nil)).\n    rewrite -> IHxs'.\n    rewrite ->3 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in\n                                                                S_filter_in).\n    unfold filter_in_v0.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_filter_in_ds_bc.\n    rewrite -> unfold_filter_in_ds_ic.\n    rewrite -> H_p_true.\n    rewrite -> unfold_reverse_ic.\n    reflexivity.\n  rename H_p into H_p_false.\n  rewrite -> (about_filter_in_and_concatenation_of_lists filter_in\n                                                         S_filter_in\n                                                         p (rev xs') (x :: nil)).\n  rewrite -> IHxs'.\n  rewrite ->3 (any_filter_in_can_be_rewritten_to_filter_in_v0 filter_in\n                                                              S_filter_in).\n  unfold filter_in_v0.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  rewrite -> unfold_filter_in_ds_bc.\n  rewrite -> app_nil_r.\n  rewrite -> unfold_filter_in_ds_ic.\n  rewrite -> H_p_false.\n  reflexivity.\nQed.\n\nTheorem about_filter_out_and_reverse_list :\n  forall (filter_out : (nat -> bool) -> list nat -> list nat),\n    specification_of_filter_out filter_out ->\n    forall (p : nat -> bool) (xs : list nat),\n      filter_out p (rev xs) = rev (filter_out p xs).\nProof.\n  intros filter_out S_filter_out.\n  intros p xs.\n  rewrite ->2 (any_filter_out_can_be_rewritten_to_filter_out_v1 filter_out\n                                                                S_filter_out).\n  unfold filter_out_v1.\n  assert (S_filter_in_v0 := filter_in_v0_fits_the_specification_of_filter_in).\n  apply (about_filter_in_and_reverse_list filter_in_v0\n                                          S_filter_in_v0\n                                          (fun n : nat => negb (p n))\n                                          xs).\nQed.\n\nTheorem ben :\n  forall b : bool,\n    orb b (negb b) = true.\nProof.\n  intros [ | ].\n  apply orb_true_l.\n  rewrite -> orb_false_l.\n  apply unfold_negb_base_case_false.\nQed.\n\n\n\n\n\n\n(* end of filtering_lists.v *)\n", "meta": {"author": "blacksails", "repo": "dIFP", "sha": "9d3e5f2838674f4fae670668c8a249f11eba0fac", "save_path": "github-repos/coq/blacksails-dIFP", "path": "github-repos/coq/blacksails-dIFP/dIFP-9d3e5f2838674f4fae670668c8a249f11eba0fac/term/Noergaard_Benjamin_corrected.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7515605985255374}}
{"text": "Require Import Cpdt.CpdtTactics.\nRequire Import Arith.\n\nSet Implicit Arguments.\n\n(* 1 *)\n(* 1.1 Explicit definition *)\nFixpoint le_nat_dec (n m : nat) : { n <= m } + { n > m } :=\n  match n with\n  | O => left (le_O_n m)\n  | S n' => match m with\n      | O => right (gt_Sn_O n')\n      | S m' => match le_nat_dec n' m' with\n          | left p => left (le_n_S n' m' p)\n          | right p => right (gt_n_S n' m' p)\n          end\n      end\n  end.\nCheck le_nat_dec.\nExtraction le_nat_dec.\n(*\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50, only parsing).\n\n(* 1.2 Definition using refine *)\nDefinition le_nat_dec' : forall n m : nat, { n <= m } + { n > m }.\n  refine (fix f n m :=\n    match n with\n    | O => Yes\n    | S n' => match m with\n        | O => No\n        | S m' => Reduce (f n' m')\n        end\n    end\n  ); crush.\nDefined.\nCheck le_nat_dec'.\nExtraction le_nat_dec.\n*)\n(* 2 *)\nRequire Import Bool.\n\nDefinition var := nat.\n\nInductive prop : Type :=\n  | Var : var -> prop\n  | Neg : prop -> prop\n  | Conj : prop -> prop -> prop\n  | Disj : prop -> prop -> prop.\n\nDefinition truthVar := var -> bool.\n\nFixpoint propDenote (t : truthVar) (p : prop) {struct p} : Prop :=\n  match p with\n  | Var v => if t v then True else False\n  | Neg p => ~ propDenote t p\n  | Conj a b => propDenote t a /\\ propDenote t b\n  | Disj a b => propDenote t a \\/ propDenote t b\n  end.\nPrint left.\n\n(* semi-implicit construction *)\nDefinition bool_true_dec : forall b : bool, {b = true} + {b = true -> False}.\n  refine (fix f b := match b with\n    | true => left _ _\n    | false => right _ _\n    end\n  ); crush.\nDefined.\n\n(* explicit construction *)\nDefinition bool_true_dec' (b : bool) : {b = true} + {b = true -> False} :=\n  match b with\n  | true => left (eq_refl true)\n  | false => right (fun H => diff_false_true H)\n  end.\nPrint left.\n\n(* CRUCIAL thing for automation with crush *)\nHint Unfold not. (* Most important line *)\n(* Do not delete previous line *)\n\n(* TACTICAL construction *)\nDefinition decide : forall truth pr, {propDenote truth pr} + {~ propDenote truth pr}.\n  intros. induction pr.\n  simpl; destruct (truth v); crush.\n  simpl; destruct IHpr; crush.\n  simpl; destruct IHpr1, IHpr2; crush.\n  simpl; destruct IHpr1, IHpr2; crush.\nDefined.\n\n(* REFINE construction (tried to make more explicit than i possibly should) *)\nDefinition decide' : forall truth pr, {propDenote truth pr} + {~ propDenote truth pr}.\n  refine (fix d t p {struct p} :=\n    match p return {propDenote t p} + {~ propDenote t p} with\n    | Var v => match bool_true_dec (t v) with\n        | left e => left _\n        | right e => right _\n        end\n    | Neg b => match d t b with\n        | left e => right _\n        | right e => left _\n        end\n    | Conj a b => match (d t a, d t b) with\n        | (left pa, left pb) => left (conj pa pb)\n        | (_, _) => right _\n        end\n    | Disj a b => match (d t a, d t b) with\n        | (left pa, _) => left (or_introl pa)\n        | (_, left pb) => left (or_intror pb)\n        | (right _, right _) => right _\n        end\n    end\n  ); crush; destruct (t v); crush. (* destruct for 'right' case of 'Var' *)\nDefined.\n\nDefinition negate : forall p : prop,\n    { p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p' }.\nPrint sig.\n  refine (fix n p :=\n    match p with\n    | Var v => exist _ (Neg (Var v)) _\n    | Neg p => exist _ p _\n    | Conj a b => exist _ (Disj (proj1_sig (n a)) (proj1_sig (n b))) _\n    | Disj a b => exist _ (Conj (proj1_sig (n a)) (proj1_sig (n b))) _\n    end\n  ).\n    intro t; crush; destruct (t v); crush.\n    intro t; crush; simpl.\n    destruct (n a), (n b); crush. \n      apply i in H1; assumption.\n      apply i0 in H2; assumption.\n    destruct (n a), (n b); crush.\n      apply i in H0; assumption.\n      apply i0 in H0; assumption.\n    destruct (decide truth x), (decide truth x0); crush.\nDefined.\n\nEval compute in proj1_sig (negate (Conj (Neg (Var 1)) (Neg (Var 2)))).\n\n(* DPLL in file DPLL.v *)\n", "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/cpdt_0.4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.8596637577007393, "lm_q1q2_score": 0.751412523322397}}
{"text": "\n(* Script Coq pour le Thème 7 : types inductifs *)\n\nRequire Import Arith.\nRequire Import List.\n\n(*---------------------------------------------------------------*)\n(** * Types énumérés *)\n\nPrint bool.\n\nInductive Couleur : Set :=\n | pique : Couleur\n | coeur : Couleur\n | carreau : Couleur\n | trefle : Couleur.\n\nFixpoint valeur_couleur (c:Couleur) : nat :=\n  match c with\n  | pique => 1\n  | coeur => 2\n  | carreau => 3\n  | trefle => 4\n  end.\n\nExample ex_valeur_couleur1: valeur_couleur coeur = 2.\nProof.\n  compute. reflexivity.\nQed.\n\nCheck Couleur_ind.\n\nLemma couleur_surj: \n  forall c : Couleur,\n    c = pique \\/ c = coeur \\/ c = carreau \\/ c = trefle.\nProof.\n  destruct c. (* essayer aussi avec induction c *)\n  - (* cas pique *)\n    left.\n    reflexivity.\n  - (* cas coeur *)\n    right.\n    left.\n    reflexivity.\n  - (* cas carreau *)\n    right. right.\n    left.\n    reflexivity.\n  - (* cas trefle *)\n    right. right. right.\n    reflexivity.\nQed.\n\n(** ** Exercice *)\n\nLemma borne_valeur:\n  forall c : Couleur,\n    (0 < (valeur_couleur c)) /\\ ((valeur_couleur c) <= 4).\nProof.\n  destruct c.\n  - simpl.\n   split.\n   SearchPattern ( 0 < _ ).\n   apply lt_0_Sn.\n   SearchPattern ( _ <= _ ).\n   apply le_n_S.\n   SearchPattern ( 0 <= _ ).\n   apply le_0_n.\n  -simpl; auto with arith.\n  -simpl; auto with arith.\n  -simpl; auto with arith.\nQed.\n\n(*---------------------------------------------------------------*)\n(** * Types paramétrés *)\n\nInductive geom : Set :=\n  | point: nat -> nat -> geom\n  | segment: nat -> nat -> nat -> nat -> geom\n  | triangle: nat -> nat -> nat -> nat -> nat -> nat -> geom\n  | nogeom : geom.\n\nFixpoint compose_geom (g1 g2:geom) : geom := \n  match g1 with\n  | point x1 y1 => match g2 with\n                   | point x2 y2 => segment x1 y1 x2 y2\n                   | segment x2 y2 x3 y3 => triangle x1 y1 x2 y2 x3 y3\n                   | _ => nogeom\n                   end\n  | segment x1 y1 x2 y2 => match g2 with\n                   | point x3 y3 => triangle x1 y1 x2 y2 x3 y3\n                   | _ => nogeom\n                   end\n  | _ => nogeom\n  end.\n\nExample ex_segment: compose_geom (point 0 0) (point 1 1) =\n  segment 0 0 1 1.\nProof.\n  compute. reflexivity.\nQed.\n\nCheck geom_ind.\n\n(** ** Exercice *)\n\nLemma compose_nogeom: \n  forall g : geom, compose_geom nogeom g = nogeom.\nProof.\n  intro geom.\nsimpl.\nreflexivity.\nQed.\n(*---------------------------------------------------------------*)\n(** * Types polymorphes *)\n\nInductive maybe (A:Set) : Type :=\n  Nothing : maybe A\n| Just : A -> maybe A.\n\nArguments Nothing [A].\nArguments Just [A] _.\n\nCheck maybe_ind.\n\nDefinition maybe_map {A B:Set} (f:A->B) : maybe A -> maybe B :=\n  fun (ma:maybe A) => match ma with\n                        | Nothing => Nothing\n                        | Just a => Just (f a)\n                      end.\n\nLemma maybe_map_id:\n  forall A : Set, forall ma : maybe A,\n    maybe_map (fun a:A => a) ma = (fun (ma:maybe A) => ma) ma.\nProof.\n  intros A ma.\n  unfold maybe_map.\n  destruct ma as [|a].\n  reflexivity.\n  reflexivity.\nQed.\n\n(** ** Exercice *)\n\nDefinition maybe_compose {A B C : Set} (f:A->B) (g:B->C) : A->C :=\n  fun (a:A) => g (f a).\n\nLemma maybe_map_compose:\n  forall A B C : Set, forall ma : maybe A,\n  forall f : A->B, forall g: B->C,\n    maybe_map (maybe_compose f g) ma \n    = (maybe_compose (maybe_map f) (maybe_map g)) ma.\nProof.\n  intros A B C ma f g.\n  compute.\n  destruct ma as [|a].\n  reflexivity.\n  reflexivity.\nQed.\n  (*---------------------------------------------------------------*)\n(** * Types récursifs simples *)\n\nCheck nat_ind.\n\nInductive list_Couleur : Set :=\n  | Nil_Couleur: list_Couleur\n  | Cons_Couleur: Couleur -> list_Couleur -> list_Couleur.\n\n(* Ecrire ci-dessous le principe d'induction. *)\n\n(*list_Couleur_ind : forall P : list_Couleur -> Prop,\n                     P Nil_Couleur ->\n                     (forall (c:Couleur l:list_Couleur), P l -> (Cons_Couleur c l)) ->\n                     forall l : list_Couleur, P l. \n*)\n(* Et pour vérifier votre solution ... *)\nCheck list_Couleur_ind.\n\n(** ** Exercice *)\n\nFixpoint meme_couleur (c : Couleur) (l : list_Couleur) : Prop :=\n  match l with\n    | Nil_Couleur => True\n    | Cons_Couleur e l' => (e = c) /\\ meme_couleur c l'\n  end.\n\nFixpoint somme_couleurs (l : list_Couleur) : nat :=\n  match l with\n    | Nil_Couleur => 0\n    | Cons_Couleur e l' => (valeur_couleur e) + (somme_couleurs l')\n  end.\n\nFixpoint longueur (l : list_Couleur) : nat :=\n  match l with\n    | Nil_Couleur => 0\n    | Cons_Couleur _ l' => S (longueur l')\n  end.\n\nLemma couleur_unique:\n  forall c : Couleur, forall l : list_Couleur,\n    meme_couleur c l\n    -> (somme_couleurs l) = (longueur l) * (valeur_couleur c).\nProof.\n  intros c l.\n  induction l as [|c' cl'].\n    - simpl.\n      intro.\n      reflexivity.\n    - simpl.\n      intros cc.\n      destruct cc as [H1 H2].\n      rewrite H1.\n      rewrite IHcl'.\n      + reflexivity.\n      + exact H2. \nQed.\n(*---------------------------------------------------------------*)\n(** * Types récursifs polymorphes *)\n\nPrint list.\n\nCheck list_ind.\n\n(** ** Exercice *)\n\n(** *** Question 1 *)\nInductive bintree (A:Set) : Set :=\nleaf : bintree A\n| node : A -> bintree A -> bintree A -> bintree A.\n\nArguments leaf [A].\nArguments node [A] _ _ _.\n\n\nCheck bintree_ind.\n            \n\n(** *** Question 2 *)\n\nFixpoint nsize {A:Set} (t : bintree A) : nat :=\n  match t with\n    | leaf => 0\n    | node _ g d => 1 + nsize g + nsize d\n  end.\n\n          \nDefinition bintree_ex1 : bintree nat :=\n  (node 1 \n        (node 2 \n              (node 3 leaf leaf)\n              (node 4 \n                    (node 5 leaf leaf)\n                    (node 6 leaf (node 7 leaf leaf))))\n        (node 8\n              (node 9 leaf leaf)\n              leaf)).\n\n\nExample nsize_ex1: \n  nsize bintree_ex1 = 9.\nProof.\n  compute. reflexivity.\nQed.          \n\n(** *** Question 3 *)\n\nFixpoint lsize {A:Set} (t : bintree A) : nat :=\n  match t with\n    | leaf => 1\n    | node _ g d => lsize g + lsize d\n  end.\n\nExample lsize_ex1:\n  lsize bintree_ex1 = 10.\nProof.\n  compute. reflexivity.\nQed.\n\nLemma node_leaf_size:\n  forall A : Set, forall t : bintree A,\n    (lsize t) = S (nsize t).\nProof.\n  intros A t.\n  induction t as [| g d].\n  + simpl.\n    reflexivity.\n  +simpl.\n   rewrite IHd.\n   rewrite IHt1.\n   SearchRewrite( S (_)).\n   simpl.\n   rewrite <- plus_n_Sm.\n   reflexivity.\nQed.\n(** ** Exercice *)\n\n(** *** Question 1 *)\n  \nFixpoint lprefix {A: Set} (t : bintree A) : list A :=\n  match t with\n    | leaf => nil\n    | node a g d => ((a :: (lprefix g)) ++ lprefix d)\n                      end.\n\nExample lprefix_ex1:\n  lprefix bintree_ex1 = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil.\nProof.\n  compute. reflexivity.\nQed.\n\n(** *** Question 2 *)\n\nLemma nsize_length: \n  forall A : Set, forall t : bintree A,\n    nsize t = length (lprefix t).\nProof.\n  intros A t.\n  induction t as [| l n].\n  -simpl.\n   reflexivity.\n  -simpl.\n   rewrite IHn.\n   rewrite IHt1.\n   SearchRewrite ( length _ ).\n   rewrite app_length.\n   reflexivity.\nQed.\n\n(** ** Exercice *)\n\n(** *** Question 1 *)\n  \nFixpoint bmap {A B: Set} (f : A -> B) (t : bintree A) : bintree B :=\n  match t with\n    | leaf => leaf\n    | node a g d => node (f a) (bmap f g) (bmap f d)\n  end.\n\nExample bmap_ex1:\n  bmap (fun (n:nat) =>  n + n) bintree_ex1\n  = node 2\n         (node 4\n               (node 6 leaf leaf)\n               (node 8\n                     (node 10 leaf leaf)\n                     (node 12 leaf (node 14 leaf leaf))))\n         (node 16 (node 18 leaf leaf) leaf).\nProof.\n  compute. reflexivity.\nQed.\n\n(** *** Question 2 *)\n\nLemma map_bmap:\n  forall A B : Set, \n  forall f : A->B, forall t : bintree A,\n    lprefix (bmap f t) = map f (lprefix t).\nProof.\n  intros A B f t.\n  induction t as [| l n].\n  -simpl.\n   reflexivity.\n  -simpl.\n   rewrite IHn.\n   rewrite IHt1.\n   SearchRewrite( _ ++ _ ).\n   rewrite map_app.\n   reflexivity.\nQed.\n(*---------------------------------------------------------------*)\n(** * Récursion mutuelle *)\n\nInductive gentree (A:Set) : Set :=\n| gnode: A -> forest A -> gentree A\nwith forest (A:Set) : Set :=\n| fnil: forest A\n| fcons: gentree A -> forest A -> forest A.\n\nArguments gnode [A] _ _.\nArguments fnil [A].\nArguments fcons [A] _ _.\n\nCheck gentree_ind.\n\nCheck forest_ind.\n\nFixpoint gsize {A:Set} (t:gentree A) : nat :=\n  match t with\n    | gnode _ f => S (fsize f)\n  end\nwith fsize {A:Set} (f:forest A) : nat :=\n       match f with\n         | fnil => 0\n         | fcons e f' => (gsize e) + (fsize f')\n       end.\n\nFixpoint lgprefix {A:Set} (t:gentree A) : list A :=\n  match t with\n    | gnode e f => e::(lfprefix f)\n  end\nwith lfprefix {A:Set} (f:forest A) : list A :=\n    match f with\n      | fnil => nil\n      | fcons e f' => (lgprefix e) ++ (lfprefix f')\n    end.\n\nLemma gsize_length:\n  forall A : Set, forall t : gentree A,\n    gsize t = length (lgprefix t).\nProof.\n  intros A t.\n  induction t.\n  simpl.\nAbort.\n\nScheme gentree_ind' :=\n  Induction for gentree Sort Prop\n  with forest_ind' :=\n    Induction for forest Sort Prop.\n\nCheck gentree_ind'.\n\nLemma gsize_length:\n  forall A : Set, forall t : gentree A,\n    gsize t = length (lgprefix t).\nProof.\n  intros A t.\n  elim t using gentree_ind' with \n  (P0:= fun f:forest A => fsize f = length (lfprefix f)).\n  - (* cas des noeuds *)\n    intros a f H1.\n    simpl.\n    rewrite H1.\n    reflexivity.\n  - (* cas des forêts vides *)\n    simpl.\n    reflexivity.\n  - (* cas des forêts non-vides *)\n    intros g Hg f Hf.\n    simpl.\n    rewrite Hg.\n    rewrite Hf.\n    (* SearchRewrite (length (_ ++ _))\n       app_length:\n         forall (A : Type) (l l' : list A), \n             length (l ++ l') = length l + length l' *)\n    rewrite app_length.\n    reflexivity.\nQed.\n\n(** ** Exercice *)\n\n(** *** Question 1 *)\n\nFixpoint gmap {A B:Set} (fn : A -> B) (t:gentree A) : gentree B :=\n  match t with\n    | gnode e f => gnode (fn e) (fmap fn f)\n  end\nwith fmap {A B:Set} (fn : A -> B) (f:forest A) : forest B :=\n    match f with\n      | fnil => fnil\n      | fcons e f' => fcons (gmap fn e) (fmap fn f')\n    end.\n\n(** *** Question 2 *)\n\nLemma map_gmap:\n  forall A B : Set, \n  forall h : A->B, forall t : gentree A,\n    lgprefix (gmap h t) = map h (lgprefix t).\nProof.\n  intros A B h t.\n  elim t using gentree_ind' with \n  (P0:= fun f : forest A => lfprefix (fmap h f) = map h (lfprefix f)).\n  -intros a f H1.\n   simpl.\n   rewrite H1.\n   reflexivity.\n  -simpl.\n   reflexivity.\n  -intros g Hg f Hf.\n   simpl.\n   rewrite Hg.\n   rewrite Hf.\n   SearchRewrite(map _ (_ ++ _)).\n   rewrite map_app.\n   reflexivity.\nQed.\n\n\n(*---------------------------------------------------------------*)\n(** * Types dépendants *)\n\nInductive domino : nat -> nat -> Type :=\n  | block: forall m n, domino m n \n  | chain: forall m n p, domino m n -> domino n p -> domino m p.\n\nArguments chain [m n p] _ _.\n\nEval compute in (chain (chain (block 3 8) (block 8 4)) (block 4 9)).\n\nInductive vector (A:Set) : nat -> Set :=\n  | vNil : vector A O\n  | vCons : forall n, A -> vector A n -> vector A (S n).\n\nArguments vNil [A].\nArguments vCons [A][n] _ _.\n\nCheck vector_ind.\n\nFixpoint vapp {A:Set} {n1:nat} (v1:vector A n1) {n2:nat} (v2:vector A n2) : vector A (n1 + n2) :=\n  match v1 in (vector _ n1) return (vector A (n1 + n2)) with\n    | vNil => v2\n    | vCons _ e v1' => vCons e (vapp v1' v2)\n  end.\n\nExample vapp_ex1:\n  vapp (vCons 1 (vCons 2 (vCons 3 vNil)))\n       (vCons 4 (vCons 5 vNil))\n  = vCons 1 (vCons 2 (vCons 3 (vCons 4 (vCons 5 vNil)))).\nProof.\n  compute.\n  reflexivity.\nQed.\n\nDefinition vlength {A:Set} {n:nat} (v:vector A n) : nat := n.\n\n\n(** ** Exercice *)\n\nLemma vappa_vlength:\n  forall A : Set,\n  forall n1 n2 : nat,\n  forall v1 : vector A n1,\n  forall v2 : vector A n2,\n    vlength (vapp v1 v2) = n1 + n2.\nProof.\n  intros A n1 n2 v1 v2.\n  induction v1 as [|v v'].\n  -compute.\n   reflexivity.\n  -simpl.\n   rewrite <- IHv1.\n\n(** ** Exercice *)\n\n(* <<DEFINIR vmap ICI>> *)\n\nExample vmap_ex1:\n  vmap (fun b:bool => match b with\n                        | true => 1\n                        | false => 0\n                      end) (vCons true (vCons false vNil))\n  = vCons 1 (vCons 0 vNil).\nProof.\n  compute. reflexivity.\nQed. \n\n\n(** ** Exercice *)\n\n(* <<DEFINIR list_from_vect ICI>>> *)\n\nExample list_from_vect_ex1:\n  list_from_vect (vCons true (vCons false vNil)) = true :: false :: nil.\nProof.\n  compute. reflexivity.\nQed.\n\n(** ** Exercice *)\n\nLemma vmap_map:\n  forall A B:Set,\n  forall f : A->B,\n  forall n:nat,\n  forall v : vector A n,\n    list_from_vect (vmap f v) = map f (list_from_vect v).\nProof.\n  (* <<COMPLETER ICI>> *)\n\n(** ** Exercice *)\n\n(* <<DEFINIR vect_from_list ICI>> *)\n\n Example vect_from_list_ex1:\n  vect_from_list (true::false::nil) = vCons true (vCons false vNil).\nProof.\n  compute. reflexivity.\nQed.\n\n(** ** Exercice *)\n\nTheorem vect_list_convert:\n  forall A : Set,\n  forall l : list A,\n    list_from_vect (vect_from_list l) = l.\nProof.\n  (* <<COMPLETER ICI>> *)", "meta": {"author": "ebtaleb", "repo": "SVP", "sha": "cac36c82a07248ccfc078207e43678b5f5b19e3d", "save_path": "github-repos/coq/ebtaleb-SVP", "path": "github-repos/coq/ebtaleb-SVP/SVP-cac36c82a07248ccfc078207e43678b5f5b19e3d/TD07/theme7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7514125201797298}}
{"text": "Inductive bool : Type :=\n  | true : bool\n  | false : bool.\n\nDefinition not (b : bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\nDefinition and (b₁ : bool) (b₂ : bool) : bool :=\n  match b₁ with\n   | true => b₂\n   | false => false\n  end.\n\nDefinition or (b₁ : bool) (b₂ : bool) : bool :=\n  match b₁ with\n   | true => true\n   | false => b₂\n  end.\n\n(* Unit tests *)\nExample test_or_1: (or true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_or_2: (or false false) = false.\nProof. simpl. reflexivity. Qed.\nExample test_or_3: (or false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_or_4: (or true true) = true.\nProof. simpl. reflexivity. Qed.\n\n(* Introduce notations *)\nNotation \"x && y\" := (and x y).\nNotation \"x || y\" := (or x y).\n\nExample test_or_5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: implement nand *)\nDefinition nand (b₁ : bool) (b₂ : bool) : bool :=\n  match b₁ with\n    | true => not b₂\n    | false => true\n  end.\n\nExample test_nand_1: (nand true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nand_2: (nand false false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nand_3: (nand false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nand_4: (nand true true) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: implement and3 *)\nDefinition and3 (b₁ : bool) (b₂ : bool) (b₃ : bool) : bool :=\n  match b₁ with\n    | true =>\n      match b₂ with\n        | true => b₃\n        | false => false\n      end\n    | false => false\n  end.\n\nExample test_and3_1: (and3 true true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_and3_2: (and3 false true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_and3_3: (and3 true false true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_and3_4: (and3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\n(* We can check the type of an expression *)\nCheck not.\n", "meta": {"author": "qoelet", "repo": "sf-scribbles", "sha": "92bf7213eb27335de958dab621c95e4bbedb5212", "save_path": "github-repos/coq/qoelet-sf-scribbles", "path": "github-repos/coq/qoelet-sf-scribbles/sf-scribbles-92bf7213eb27335de958dab621c95e4bbedb5212/archive_/lf/bools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7514125041861527}}
{"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\n(** Theorems about [gt] in [nat]. [gt] is defined in [Init/Peano.v] as:\n<<\nDefinition gt (n m:nat) := m < n.\n>>\n*)\n\nRequire Import Le.\nRequire Import Lt.\nRequire Import Plus.\nOpen Local Scope nat_scope.\n\nImplicit Types m n p : nat.\n\n(** * Order and successor *)\n\nTheorem gt_Sn_O : forall n, S n > 0.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_Sn_O: arith v62.\n\nTheorem gt_Sn_n : forall n, S n > n.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_Sn_n: arith v62.\n\nTheorem gt_n_S : forall n m, n > m -> S n > S m.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_n_S: arith v62.\n\nLemma gt_S_n : forall n m, S m > S n -> m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate gt_S_n: arith v62.\n\nTheorem gt_S : forall n m, S n > m -> n > m \\/ m = n.\nProof.\n  intros n m H; unfold gt in |- *; apply le_lt_or_eq; auto with arith.\nQed.\n\nLemma gt_pred : forall n m, m > S n -> pred m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate gt_pred: arith v62.\n\n(** * Irreflexivity *)\n\nLemma gt_irrefl : forall n, ~ n > n.\nProof lt_irrefl.\nHint Resolve gt_irrefl: arith v62.\n\n(** * Asymmetry *)\n\nLemma gt_asym : forall n m, n > m -> ~ m > n.\nProof fun n m => lt_asym m n.\n\nHint Resolve gt_asym: arith v62.\n\n(** * Relating strict and large orders *)\n\nLemma le_not_gt : forall n m, n <= m -> ~ n > m.\nProof le_not_lt.\nHint Resolve le_not_gt: arith v62.\n\nLemma gt_not_le : forall n m, n > m -> ~ n <= m.\nProof.\nauto with arith.\nQed.\n\nHint Resolve gt_not_le: arith v62.\n\nTheorem le_S_gt : forall n m, S n <= m -> m > n.\nProof.\n  auto with arith.\nQed.\nHint Immediate le_S_gt: arith v62.\n\nLemma gt_S_le : forall n m, S m > n -> n <= m.\nProof.\n  intros n p; exact (lt_n_Sm_le n p).\nQed.\nHint Immediate gt_S_le: arith v62.\n\nLemma gt_le_S : forall n m, m > n -> S n <= m.\nProof.\n  auto with arith.\nQed.\nHint Resolve gt_le_S: arith v62.\n\nLemma le_gt_S : forall n m, n <= m -> S m > n.\nProof.\n  auto with arith.\nQed.\nHint Resolve le_gt_S: arith v62.\n\n(** * Transitivity *)\n\nTheorem le_gt_trans : forall n m p, m <= n -> m > p -> n > p.\nProof.\n  red in |- *; intros; apply lt_le_trans with m; auto with arith.\nQed.\n\nTheorem gt_le_trans : forall n m p, n > m -> p <= m -> n > p.\nProof.\n  red in |- *; intros; apply le_lt_trans with m; auto with arith.\nQed.\n\nLemma gt_trans : forall n m p, n > m -> m > p -> n > p.\nProof.\n  red in |- *; intros n m p H1 H2.\n  apply lt_trans with m; auto with arith.\nQed.\n\nTheorem gt_trans_S : forall n m p, S n > m -> m > p -> n > p.\nProof.\n  red in |- *; intros; apply lt_le_trans with m; auto with arith.\nQed.\n\nHint Resolve gt_trans_S le_gt_trans gt_le_trans: arith v62.\n\n(** * Comparison to 0 *)\n\nTheorem gt_0_eq : forall n, n > 0 \\/ 0 = n.\nProof.\n  intro n; apply gt_S; auto with arith.\nQed.\n\n(** * Simplification and compatibility *)\n\nLemma plus_gt_reg_l : forall n m p, p + n > p + m -> n > m.\nProof.\n  red in |- *; intros n m p H; apply plus_lt_reg_l with p; auto with arith.\nQed.\n\nLemma plus_gt_compat_l : forall n m p, n > m -> p + n > p + m.\nProof.\n  auto with arith.\nQed.\nHint Resolve plus_gt_compat_l: arith v62.\n\n(* begin hide *)\nNotation gt_O_eq := gt_0_eq (only parsing).\n(* end hide *)\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/Arith/Gt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7514079103839716}}
{"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.\n(*Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).*)\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\nTheorem appendEmptyList : forall list : natlist, list ++ [] = list.   \nProof.\n  intros.\n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. rewrite -> IHxs.\n    reflexivity.\nQed.", "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/appendEmptyList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7513851151079964}}
{"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.\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    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  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 [ | x n 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      | 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    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\nSection vec_map.\n\n  Variable (X Y : Type).\n\n  Section vec_map_def.\n\n    Variable (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\n  End vec_map_def.\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 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 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_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; lia.\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; 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_plus_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_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 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\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  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  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 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.\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.\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-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/Vec/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7513149439174623}}
{"text": "(* week-10_folding-left-and-right.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of Tue 17 Oct 2017 *)\n\n(* ********** *)\n\nLtac unfold_tactic name := intros; unfold name; (* fold name; *) reflexivity.\n\nRequire Import Arith List.\n\n(* ********** *)\n\nDefinition specification_of_fold_right (T1 T2 : Type) (fold_right : T2 -> (T1 -> T2 -> T2) -> list T1 -> T2) :=\n  (forall (nil_case : T2)\n          (cons_case : T1 -> T2 -> T2),\n     fold_right nil_case cons_case nil =\n     nil_case)\n  /\\\n  (forall (nil_case : T2)\n          (cons_case : T1 -> T2 -> T2)\n          (v : T1)\n          (vs' : list T1),\n     fold_right nil_case cons_case (v :: vs') =\n     cons_case v (fold_right nil_case cons_case vs')).\n\nDefinition specification_of_fold_left (T1 T2 : Type) (fold_left : T2 -> (T1 -> T2 -> T2) -> list T1 -> T2) :=\n  (forall (nil_case : T2)\n          (cons_case : T1 -> T2 -> T2),\n     fold_left nil_case cons_case nil =\n     nil_case)\n  /\\\n  (forall (nil_case : T2)\n          (cons_case : T1 -> T2 -> T2)\n          (v : T1)\n          (vs' : list T1),\n     fold_left nil_case cons_case (v :: vs') =\n     fold_left (cons_case v nil_case) cons_case vs').\n\n(*\n\n * prove whether each of these specifications is unique\n\n * propose an implementation of fold_right (resp. of fold_left)\n   that satisfies the specification of fold_right (resp. of fold_left).\n*)\n\n\nFixpoint poly_fold_right (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs : list T1) : T2 :=\n  match xs with\n  | nil =>\n    nil_case\n  | (v :: vs') =>\n    cons_case v (poly_fold_right T1 T2 nil_case cons_case vs')\n  end.\n\nLemma unfold_poly_fold_right_nil:\n  forall (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2),\n    poly_fold_right T1 T2 nil_case cons_case nil = nil_case.\nProof.\n  unfold_tactic poly_fold_right.\nQed.\n\nLemma unfold_poly_fold_right_cons:\n  forall (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (v: T1) (vs' : list T1),\n    poly_fold_right T1 T2 nil_case cons_case (v :: vs') = cons_case v (poly_fold_right T1 T2 nil_case cons_case vs').\nProof.\n  unfold_tactic poly_fold_right.\nQed.\n\nProposition poly_fold_right_satisfies_its_specification :\n  forall (T1 T2 : Type),\n    specification_of_fold_right T1 T2 (poly_fold_right T1 T2).\nProof.\n  intros T1 T2.\n  unfold specification_of_fold_right.\n  split.\n\n  intros nil_case cons_case.\n  rewrite -> (unfold_poly_fold_right_nil T1 T2 nil_case cons_case).\n  reflexivity.\n\n  intros nil_case cons_case v vs'.\n  rewrite -> (unfold_poly_fold_right_cons T1 T2 nil_case cons_case).\n  reflexivity.\nQed.\n  \nFixpoint poly_fold_left (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs : list T1) : T2 :=\n  match xs with\n  | nil =>\n    nil_case\n  | (v :: vs') =>\n     poly_fold_left T1 T2 (cons_case v nil_case) cons_case vs'\n  end.\n\n\nLemma unfold_poly_fold_left_nil:\n  forall (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2),\n    poly_fold_left T1 T2 nil_case cons_case nil = nil_case.\nProof.\n  unfold_tactic poly_fold_left.\nQed.\n\nLemma unfold_poly_fold_left_cons:\n  forall (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (v: T1) (vs' : list T1),\n    poly_fold_left T1 T2 nil_case cons_case (v :: vs') =  poly_fold_left T1 T2 (cons_case v nil_case) cons_case vs'.\nProof.\n  unfold_tactic poly_fold_left.\nQed.\n\nProposition poly_fold_left_satisfies_its_specification :\n  forall (T1 T2 : Type),\n    specification_of_fold_left T1 T2 (poly_fold_left T1 T2).\nProof.\n  intros T1 T2.\n  unfold specification_of_fold_left.\n  split.\n\n  intros nil_case cons_case.\n  rewrite -> (unfold_poly_fold_left_nil T1 T2 nil_case cons_case).\n  reflexivity.\n\n  intros nil_case cons_case v vs'.\n  rewrite -> (unfold_poly_fold_left_cons T1 T2 nil_case cons_case).\n  reflexivity.\nQed.\n  \n(* ********** *)\n\n(*\n\n * characterize the result of applying\n   \n   - poly_fold_right and\n\n   - poly_fold_left\n\n   to nil and cons:\n*)\n\nDefinition poly_righto (T : Type) (xs : list T) : list T :=\n  poly_fold_right T (list T) nil (fun v vs => cons v vs) xs.\n\nCompute (poly_righto nat (1 :: 2 :: 3 :: nil)).\n\nProposition about_poly_righto :\n  forall (T : Type)\n         (xs : list T),\n  (poly_righto T xs) = xs.\nProof.\n  intros T xs.\n  unfold poly_righto.\n\n  induction xs as [ | x xs' IHxs].\n  rewrite -> (unfold_poly_fold_right_nil T (list T) nil (fun (v : T) (vs : list T) => v :: vs)).\n  reflexivity.\n\n  rewrite -> (unfold_poly_fold_right_cons T (list T) nil (fun (v : T) (vs : list T) => v :: vs)).\n  rewrite -> IHxs. \n  reflexivity.\nQed.\n  \nDefinition poly_lefty (T : Type) (xs : list T) : list T :=\n  poly_fold_left T (list T) nil (fun v vs => cons v vs) xs.\n\nCompute (poly_lefty nat (1 :: 2 :: 3 :: nil)).\nCompute (poly_lefty nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\n\n(*\nFixpoint poly_reverse_aux (T : Type) (xs : list T) (a : list T) : list T :=\n      match xs with\n      | nil =>\n        a\n      | x :: xs' =>\n        poly_reverse_aux T xs' (x :: a)\n      end.\n\nDefinition poly_reverse (T: Type) (xs_init : list T) : list T :=\n  poly_reverse_aux T xs_init nil.\n\n\n(*\nLemma unfold_poly_reverse_aux_nil:\n  forall (T : Type) (a : list T),\n    poly_reverse_aux T nil a = a.\nProof.\n  unfold_tactic poly_reverse_aux.\nQed.\n\nLemma unfold_poly_reverse_aux_cons:\n  forall (T : Type) (x : T) (xs' : list T) (a : list T),\n    poly_reverse_aux T (x :: xs') a = poly_reverse_aux T xs' (x :: a).\nProof.\n  unfold_tactic poly_reverse_aux.\nQed.\n\nLemma about_poly_reverse_aux:\n  forall (T : Type) (nil_case : list T)(xs' : list T) (a : list T),\n    poly_fold_left T (list T) nil_case (fun (v : T) (vs : list T) => v :: vs) xs'\n    =  (poly_fold_left T (list T) nil (fun (v : T) (vs : list T) => v :: vs) xs') :: nil_case.\n  Admitted.*)\n\n\n*)\nFixpoint append (A: Type) (vs :list A) (ws: list A) :=\n  match vs with\n   | nil => ws  \n   | v :: vs' =>\n     v :: (append A vs' ws)\n  end.\n\nLemma unfold_append_nil:\n  forall (A : Type) (ws : list A),\n    append A nil ws = ws.\nProof.\n  unfold_tactic append.\nQed.\n\nLemma unfold_append_cons:\n  forall (A : Type) (v : A) (vs' ws : list A),\n    append A (v :: vs') ws = v :: (append A vs' ws).\nProof.\n  unfold_tactic append.\nQed.\n\nLemma unfold_append_nil':\n  forall (A : Type) (ws : list A),\n    append A ws nil = ws.\nProof.\n  intros A ws.\n  induction ws as [ | w ws' IHws].\n  rewrite -> unfold_append_nil.\n  reflexivity.\n\n  rewrite -> unfold_append_cons.\n  rewrite -> IHws.\n  reflexivity.\nQed.\n\nLemma append_assoc:\n  forall (T: Type) (xs ys zs : list T),\n    append T (append T xs ys) zs =\n    append T xs (append T ys zs).\nProof.\n  intros T xs ys zs.\n  induction xs as [ | x xs' IHxs].\n  rewrite ->2 unfold_append_nil.\n  reflexivity.\n\n  induction ys as [ | y ys' IHys].\n  rewrite -> unfold_append_nil.\n  rewrite ->3 unfold_append_cons.\n  rewrite -> unfold_append_nil'.\n  reflexivity.\n\n  induction zs as [ | z zs' IHzs].\n  rewrite ->4 unfold_append_cons.\n  rewrite ->2 unfold_append_nil'.\n  reflexivity.\n\n  rewrite ->4 unfold_append_cons.\n  rewrite -> IHxs.\n  rewrite -> unfold_append_cons.\n  reflexivity.\nQed.\n\n  Fixpoint poly_reverse_append (T: Type) (xs : list T) : list T :=\n  match xs with\n  | nil =>\n    nil\n  | x :: xs' =>\n    append T (poly_reverse_append T xs') (x :: nil)\n  end.\n\nCompute (poly_reverse_append nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\n\n\nLemma unfold_poly_reverse_append_nil:\n  forall (T : Type),\n    poly_reverse_append T nil = nil.\nProof.\n  unfold_tactic poly_reverse_append.\nQed.\n\nLemma unfold_poly_reverse_append_cons:\n  forall (T : Type) (x : T) (xs' : list T),\n    poly_reverse_append T (x :: xs') = append T (poly_reverse_append T xs') (x :: nil).\nProof.\n  unfold_tactic poly_reverse_append.\nQed.\n\n\nLemma about_poly_lefty_aux:\n  forall (T : Type) (xs nil_case : list T),\n   poly_fold_left T (list T) nil_case\n    (fun (v : T) (vs : list T) => v :: vs) xs =\n  append T (poly_fold_left T (list T) nil (fun (v : T) (vs : list T) => v :: vs) xs) nil_case.\nProof.\n  intros T xs.\n  induction xs as [ | x xs' IHxs'].\n\n  intro nil_case.\n  rewrite -> unfold_poly_fold_left_nil.\n  rewrite -> unfold_poly_fold_left_nil.\n  rewrite -> unfold_append_nil.\n  reflexivity.\n\n  intro nil_case.\n  rewrite ->2 unfold_poly_fold_left_cons.\n\n  Check (IHxs' (x :: nil_case)).\n  rewrite -> (IHxs' (x :: nil_case)).\n  Check (IHxs' (x :: nil)).\n  rewrite -> (IHxs' (x :: nil)).\n  rewrite -> append_assoc.\n  rewrite -> unfold_append_cons.\n  rewrite -> unfold_append_nil.\n  reflexivity.\n  Qed.\nProposition about_poly_lefty :\n  forall (T : Type) (xs : list T),\n    poly_lefty T xs = poly_reverse_append T xs.\nProof.\n  intros T xs.\n  unfold poly_lefty.\n\n  induction xs as [ | x xs' IHxs].\n  rewrite -> (unfold_poly_fold_left_nil T (list T) nil (fun (v : T) (vs : list T) => v :: vs)).\n  rewrite -> unfold_poly_reverse_append_nil.\n  reflexivity.\n\n  rewrite -> (unfold_poly_fold_left_cons).\n  rewrite -> (about_poly_lefty_aux).\n  rewrite -> IHxs.\n  rewrite -> (unfold_poly_reverse_append_cons).\n  reflexivity.\nQed.\n(* ********** *)\n\nDefinition reverse_w_poly_fold_right (T : Type) (xs : list T) : list T :=\n  poly_fold_right T (list T) nil (fun v vs => append T vs (v :: nil)) xs. \n\nCompute (reverse_w_poly_fold_right nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\nCompute (poly_reverse_append nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\nCompute (poly_lefty nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\n\nDefinition copy_w_poly_fold_left (T : Type) (xs : list T) : list T :=\n  poly_fold_left T (list T) nil (fun v vs => append T vs (v :: nil)) xs. \n\n\nCompute (copy_w_poly_fold_left nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\nCompute (poly_righto nat (1 :: 2 :: 3 :: 4 :: 5 :: nil)).\n\nDefinition length_right (T : Type) (xs : list T) : nat :=\n  poly_fold_right T nat 0 (fun x n' => S n') xs.\n\nCompute (length_right nat (1 :: 2 :: 3 :: nil)).\n\nDefinition length_left (T : Type) (xs : list T) : nat :=\n  poly_fold_left T nat 0 (fun x n' => S n') xs.\n\nCompute (length_left nat (1 :: 2 :: 3 :: nil)).\n\n(*\n\n  * define poly_fold_left in term of poly_fold_right,\n    and prove that your definition satisfies the specification of fold_left;\n  \n  * define poly_fold_right in term of poly_fold_left,\n    and prove that your definition satisfies the specification of fold_right;\n  \n *)\n(*\nFixpoint poly_append (T1 T2 : Type) (vs : T2) (ws : list T1) :=\n  match vs with\n  |\n  |\n  end.\n *)\n\nFixpoint append_w_fold_right (A: Type) (vs ws : list A) :=\n  poly_fold_right A (list A) (ws) (fun v vs => v :: vs) vs.\n\nCompute (append_w_fold_right nat (1 :: 2 :: nil) (3 :: 4 :: nil)). \n\n\nFixpoint poly_fold_right_w_acc (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs_init : list T1) : T2 :=\n  let fix poly_fold_right_waiting xs := \n      match xs with\n      | nil =>\n        (fun a => a)\n      | (x :: xs') =>\n        (fun a => poly_fold_right_waiting xs' (cons_case x a))\n      end\n  in poly_fold_right_waiting xs_init nil_case. \n\nCompute (poly_fold_right_w_acc nat (list nat) nil (fun v vs => cons v vs) (1 :: 2 :: 3 :: nil)).\n\nDefinition poly_fold_left_alt (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs : list T1) : T2 :=\n  poly_fold_right_w_acc T1 T2 nil_case cons_case xs.\n\n(*\nDefinition poly_fold_left_alt' (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs : list T1) : T2 :=\n  (fun a => poly_fold_right T1 T2 (a) () xs) nil_case.*)\n\n\nDefinition poly_lefty_alt (T : Type) (xs : list T) : list T :=\n  poly_fold_left_alt' T (list T) nil (fun v vs => cons v vs) xs.\n\nCompute (poly_lefty_alt nat (1 :: 2 :: 3 :: 4:: nil)).\n\n\n(* <-- UNCOMMENT THIS COMMENT\nProposition poly_fold_left_alt_satisfies_its_specification :\n  forall (T1 T2 : Type),\n    specification_of_fold_left T1 T2 (poly_fold_left_alt T1 T2).\nProof.\n...\n*)\n\n(* ***** *)\n\n(* <-- UNCOMMENT THIS COMMENT\nDefinition poly_fold_right_alt (T1 T2 : Type) (nil_case : T2) (cons_case : T1 -> T2 -> T2) (xs : list T1) : T2 :=\n  poly_fold_left ...\n*)\n\n(* <-- UNCOMMENT THIS COMMENT\nDefinition poly_righto_alt (T : Type) (xs : list T) : list T :=\n  poly_fold_right_alt T (list T) nil (fun v vs => cons v vs) xs.\n\nCompute (poly_righto_alt nat (1 :: 2 :: 3 :: nil)).\n*)\n\n(* <-- UNCOMMENT THIS COMMENT\nProposition poly_fold_right_alt_satisfies_its_specification :\n  forall (T1 T2 : Type),\n    specification_of_fold_right T1 T2 (poly_fold_right_alt T1 T2).\nProof.\n...\n*)\n\n(* ********** *)\n\n(*\n\n  * show that\n    if the cons case is a function that is associative and commutative,\n    applying poly_fold_left and applying poly_fold_right\n    to a nil case, this cons case, and a list\n    give the same result.\n\n    Does the converse hold?\n\n*)\n\n(* <-- UNCOMMENT THIS COMMENT\nLemma the_grand_finale_aux :\n  forall (T : Type)\n         (nil_case : T)\n         (cons_case : T -> T -> T),\n    (forall x y z : T,\n        cons_case x (cons_case y z) = cons_case (cons_case x y) z) ->\n    (forall x y : T,\n        cons_case x y = cons_case y x) ->\n    forall (v : T)\n           (vs : list T),\n      cons_case v (poly_fold_left T T nil_case cons_case vs) =\n      poly_fold_left T T (cons_case v nil_case) cons_case vs.\nProof.\n  intros T nil_case cons_case H_assoc H_comm v vs.\n  revert nil_case.\n  induction vs as [ | v' vs' IHvs']; intro nil_case.\nAbort.\n(* Prove this master lemma. *)\n*)\n\n(* <-- UNCOMMENT THIS COMMENT\nTheorem the_grand_finale :\n  forall (T : Type)\n         (nil_case : T)\n         (cons_case : T -> T -> T),\n    (forall x y z : T,\n        cons_case x (cons_case y z) = cons_case (cons_case x y) z) ->\n    (forall x y : T,\n        cons_case x y = cons_case y x) ->\n    forall xs : list T,\n      poly_fold_right T T nil_case cons_case xs =\n      poly_fold_left  T T nil_case cons_case xs.\nProof.\nAdmitted.\n(* Prove this theorem. *)\n*)\n\n(* <-- UNCOMMENT THIS COMMENT\nProposition example_for_plus :\n  forall ns : list nat,\n    poly_fold_right nat nat 0 plus ns = poly_fold_left nat nat 0 plus ns.\nProof.\n  exact (the_grand_finale nat 0 plus plus_assoc plus_comm).\nQed.\n*)\n\n(* ********** *)\n\n(* end of week-10_folding-left-and-right.v *)", "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-10_folding-left-and-right_181017.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.890294223211224, "lm_q1q2_score": 0.7513149382958866}}
{"text": "Require Export List.\nAdd LoadPath \"../lnt/tense-logic-in-Coq\".\nRequire Import Strong_induction.\nSet Implicit Arguments.\nExport ListNotations.\n\nDelimit Scope My_scope with M.\nOpen Scope My_scope.\n\nParameter PropVars : Set.\nHypothesis Varseq_dec : forall x y:PropVars, {x = y} + {x <> y}.\n\n\n(** * Definitions\n\ndefinition of Propositional Formulas*)\nInductive PropF : Set :=\n | Var : PropVars -> PropF\n | Bot : PropF\n | Imp : PropF -> PropF -> PropF\n | Con : PropF -> PropF -> PropF\n | Dis : PropF -> PropF -> PropF\n.\n\nNotation \"# P\" := (Var P) (at level 1) : My_scope.\nNotation \"A → B\" := (Imp A B) (at level 16, right associativity) : My_scope.\nNotation \"⊥\" := Bot (at level 0)  : My_scope.\nNotation \"A ∧ B\" := (Con A B) (at level 15, right associativity) : My_scope.\nNotation \"A ∨ B\" := (Dis A B) (at level 15, right associativity) : My_scope.\n\n(** Defined connectives *)\nNotation \"¬ A\" := (A → ⊥) (at level 1)  : My_scope.\n\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 => (negb (TrueQ v B)) || (TrueQ v C)\n | B ∧ C => (andb (TrueQ v B) (TrueQ v C))\n | B ∨ C => (orb (TrueQ v B) (TrueQ v C))\nend.\n\n(** Prove that the defined connectives are correct *)\n\nLemma def_neg_correct (A: PropF) :\n  forall v, TrueQ v (¬ A) = negb (TrueQ v A).\nProof. intros. destruct A.\n       simpl. rewrite Bool.orb_false_r. trivial.\n       simpl. trivial.\n       simpl. rewrite Bool.orb_false_r. trivial.\n       simpl. rewrite Bool.orb_false_r. trivial.\n       simpl. rewrite Bool.orb_false_r. trivial.\nQed.\n\nFixpoint  weight p :=\n    match p with\n      | # q' => 0\n      | Bot => 0\n      | p' → q' => S (max (weight p') (weight q'))\n      | p' ∧ q' => S (max (weight p') (weight q'))\n      | p' ∨ q' => S (max (weight p') (weight q'))      \n      end.\n\n(** * Gentzen's Sequent Calculus *)\n\nReserved Notation \"Γ |- Δ >> n\" (at level 80).\nInductive LJ : nat -> list PropF -> PropF -> Prop :=\n| LJId  : forall A Γ, In (Var A) Γ -> LJ 0 Γ (Var A)\n| LJBot : forall A Γ, In ⊥ Γ -> LJ 0 Γ A\n| LJImpL : forall n m A B Γ1 Γ2 Δ,\n                 LJ n (Γ1++B::Γ2) Δ\n              -> LJ m (Γ1 ++ [Imp A B] ++ Γ2) A\n              -> LJ (S (max n m)) (Γ1++A→B::Γ2) Δ\n| LJImpR : forall n A B Γ,\n              LJ n (A::Γ) B\n           -> LJ (S n) Γ (A→B)\n| LJConL1 : forall n A B Γ1 Γ2 Δ,\n              LJ n (Γ1 ++ A :: Γ2) Δ\n           -> LJ (S n) (Γ1 ++ (A ∧ B) :: Γ2) Δ\n| LJConL2 : forall n A B Γ1 Γ2 Δ,\n              LJ n (Γ1 ++ B :: Γ2) Δ\n           -> LJ (S n) (Γ1 ++ (A ∧ B) :: Γ2) Δ\n| LJConR : forall n m A B Γ,\n                LJ n Γ A\n             -> LJ m Γ B\n             -> LJ (S (max n m)) Γ (A ∧ B)\n| LJDisL : forall n m A B Γ1 Γ2 Δ,\n                LJ n (Γ1++A::Γ2) Δ\n             -> LJ m (Γ1++B::Γ2) Δ\n             -> LJ (S (max n m)) (Γ1++(A ∨ B)::Γ2) Δ\n| LJDisR1 : forall n A B Γ,\n              LJ n Γ A\n           -> LJ (S n) Γ (A ∨ B)\n| LJDisR2 : forall n A B Γ,\n              LJ n Γ B\n           -> LJ (S n) Γ (A ∨ B)\nwhere \"Γ |- Δ >> n\" := (LJ (n) (Γ) (Δ)) : My_scope.\n\nLemma in_elt : forall (A : Type) (a : A) L1 L2, In a (L1 ++ a :: L2).\nProof.\nintros.\napply in_app_iff.\nright.\nsimpl.\nleft.\nreflexivity.\nQed.\n\nLemma cons_eq_app: forall (A : Type) (x y z : list A) (a : A),\n  a :: x = y ++ z -> y = [] /\\ z = a :: x \\/\n                         exists (y' : list A), y = a :: y' /\\ x = y' ++ z.\nProof.\nintros.\ndestruct y.\n simpl in H. subst. tauto.\n simpl in H. injection H. intros. right. subst. exists y. tauto.\nQed.\n\nLemma app_eq_app: forall (A : Type) (w x y z : list A),\n  w ++ x = y ++ z -> exists (m : list A),\n    w = y ++ m /\\ z = m ++ x \\/ y = w ++ m /\\ x = m ++ z.\nProof.\n intro. intro.\n induction w.\n    simpl. intros. exists y. rewrite H. tauto.\n\n    intros. simpl in H.\n    apply cons_eq_app in H.\n    destruct H.  destruct H. rewrite H. simpl.\n    exists (a :: w). rewrite H0. simpl. tauto.\n    destruct H. destruct H.\n    apply IHw in H0. destruct H0. destruct H0. destruct H0.\n    rewrite H.  rewrite H0.  rewrite H1.  simpl.\n    exists x1. tauto.\n    destruct H0. rewrite H.  rewrite H0.  rewrite H1.  simpl.\n    exists x1. tauto.\nQed.\n\nLemma cons_single_app: forall T (A : T) L, A :: L = [A] ++ L.\nProof.\nreflexivity.\nQed.\n\nLemma in_app_comm : forall (A : Type) (a : A) (X Y : list A), In a (X ++ Y) <-> In a (Y ++ X).\nProof.\nintros.\ninduction X.\n\nrewrite app_nil_r.\nrewrite app_nil_l.\nreflexivity.\n\nrewrite! in_app_iff.\nfirstorder.\nQed.\n\nLemma in_cons_comm : forall (A : Type) (a b c: A) (X Y : list A), In a (X ++ b :: c :: Y) <-> In a (X ++ c :: b :: Y).\nProof.\nintros.\nrewrite! in_app_iff.\nsimpl.\nfirstorder.\nQed.\n\nLemma in_list_eq : forall {A : Type} {l1 l2 l3 : list A} {a : A}, (l1 ++ a :: l2) = l3 -> In a l3.\nProof.\nintros.\nrewrite <- H.\napply in_app_iff.\nright.\napply in_eq.\nQed.\n\nLemma le_trans: forall a b c, a <= b -> b <= c -> a <= c.\nProof.\nintros.\nrewrite H.\nassumption.\nQed.\n\nLemma in_app_add: forall (A : Type) (a : A) (L1 L2 : list A), In a L1 -> In a (L1 ++ L2).\nProof.\nintros.\ninduction L2.\n\nrewrite app_nil_r.\nassumption.\n\nrewrite cons_single_app.\napply in_app_comm.\nsimpl.\nright.\napply in_app_comm.\nassumption.\nQed.\n\nLemma imp_not_var: forall A B C L1 L2, In (# A) (L1 ++ Imp B C :: L2) -> In (# A) (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma imp_not_bot: forall B C L1 L2, In Bot (L1 ++ Imp B C :: L2) -> In Bot (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma con_not_var: forall A B C L1 L2, In (# A) (L1 ++ Con B C :: L2) -> In (# A) (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma con_not_bot: forall B C L1 L2, In Bot (L1 ++ Con B C :: L2) -> In Bot (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma dis_not_var: forall A B C L1 L2, In (# A) (L1 ++ Dis B C :: L2) -> In (# A) (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma dis_not_bot: forall B C L1 L2, In Bot (L1 ++ Dis B C :: L2) -> In Bot (L1 ++ L2).\nProof.\nintros.\napply in_app_comm in H.\nsimpl in H.\ndestruct H.\n\ndiscriminate.\napply in_app_comm.\nassumption.\nQed.\n\nLemma in_double: forall (A : Type) (a : A) B L1 L2 L3, In a (L1 ++ B :: L2 ++ B :: L3) -> In a (L1 ++ B :: L2 ++ L3) .\nProof.\nintros.\nrewrite in_app_iff in H.\nsimpl in H.\nrewrite or_comm in H.\nrewrite or_assoc in H.\ndestruct H.\n\nsubst.\nfirstorder.\n\nrewrite in_app_comm in H.\nrewrite <- app_comm_cons in H.\nsimpl in H.\nrewrite in_app_comm in H.\nrewrite or_comm in H.\nrewrite in_app_iff.\nassumption.\nQed.\n\nLemma Id_extension : forall A Γ, In A Γ -> exists n, weight A <= n /\\ Γ |- A >> n.\nProof.\nintros A.\ninduction A.\n\n(*PropVar*)\nintros.\nexists 0.\nsplit.\napply le_n.\napply (LJId _ _ H).\n\n(*Bot*)\nintros.\nexists 0.\nsplit.\napply le_n.\napply (LJBot _ _ H).\n\n(*Imp*)\nintros.\nsimpl.\ndestruct (in_split _ _ H) as [l1 [l2 Z1]].\nsubst.\ndestruct (IHA1 (A1 :: l1 ++ [Imp A1 A2] ++ l2) (in_eq (A1) _) ) as [a [I1 I2]].\ndestruct (IHA2 ((A1 :: l1) ++ A2 :: l2) (in_elt A2 _ _)) as [b [I3 I4]].\npose (LJImpL _ _ _ I4 I2) as I5.\nexists (S (S (max b a))).\nsplit.\n\nrewrite PeanoNat.Nat.max_comm.\napply (le_n_S _ _ (le_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ I3 I1))).\n\napply (LJImpR I5).\n\n(*Con*)\nintros.\nsimpl.\ndestruct (in_split _ _ H) as [l1 [l2 Z1]].\nsubst.\ndestruct (IHA1 (l1 ++ A1 :: l2) (in_elt A1 _ _) ) as [a [L1 L2]].\ndestruct (IHA2 (l1 ++ A2 :: l2) (in_elt A2 _ _) ) as [b [R1 R2]].\npose (LJConL1 _ A2 _ _ L2) as L3.\npose (LJConL2 A1 _ _ _ R2) as R3.\nexists (S (max (S a) (S b))).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_S _ _ L1) (le_S _ _ R1))).\n\napply (LJConR L3 R3).\n\n(*Dis*)\nintros.\nsimpl.\ndestruct (in_split _ _ H) as [l1 [l2 Z1]].\nsubst.\ndestruct (IHA1 (l1 ++ A1 :: l2) (in_elt A1 _ _) ) as [a [L1 L2]].\ndestruct (IHA2 (l1 ++ A2 :: l2) (in_elt A2 _ _) ) as [b [R1 R2]].\npose (LJDisR1 A2 L2) as L3.\npose (LJDisR2 A1 R2) as R3.\nexists (S (max (S a) (S b))).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_S _ _ L1) (le_S _ _ R1))).\n\napply (LJDisL _ _ _ _ L3 R3).\nQed.\n\nLemma exchange_L:\n  forall n E F Γ1 Γ2 Δ (D: LJ n (Γ1 ++ E :: F :: Γ2) Δ), LJ n (Γ1 ++ F :: E :: Γ2) Δ.\nProof.\nintro n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\napply in_cons_comm in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\napply in_cons_comm in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\ninversion Z2 as [[Z3 Z4]].\ndestruct l.\n\ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LJImpL _ _ _ L1 R1).\n \ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite! app_assoc in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\napply (LJImpR I1).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\ninversion Z2 as [[Z3 Z4]].\ndestruct l.\n\ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\napply (LJConL1 A B _ _ L1).\n \ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite! app_assoc_reverse in *.\napply (LJConL1 A B _ _ L1).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\ninversion Z2 as [[Z3 Z4]].\ndestruct l.\n\ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in R.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\napply (LJConL2 A B _ _ R1).\n \ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in R.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJConL2 A B _ _ R1).\n\n(*ConR*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ninversion Z2 as [[Z3 Z4]].\ndestruct l.\n\ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LJDisL _ _ _ _ L1 R1).\n \ninversion Z4.\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite (cons_single_app F) in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L1 R1).\n\n(*DisR1*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\napply (LJDisR1 B L1).\n\n(*DisR2*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\napply (LJDisR2 A R1).\nQed.\n\nLemma move_R_L:\n  forall n Δ A Γ3 Γ2 Γ1,\n    LJ n (Γ1 ++ A :: Γ2 ++ Γ3) Δ ->\n    LJ n (Γ1 ++ Γ2 ++ A :: Γ3) Δ.\nProof.\nintros n Δ A Γ3 Γ2.\ninduction Γ2.\n\nintros.\nassumption.\n\n\nintros.\nrewrite cons_single_app.\nrewrite app_assoc_reverse.\nrewrite app_assoc.\napply IHΓ2.\nrewrite app_assoc_reverse.\napply exchange_L.\nassumption.\nQed.\n\nLemma swap_L:\n  forall n Δ Γ2 Γ3 Γ1 Γ4,\n    LJ n (Γ1 ++ Γ2 ++ Γ3 ++ Γ4) Δ->\n    LJ n (Γ1 ++ Γ3 ++ Γ2 ++ Γ4) Δ.\nProof.\nintros n Δ Γ2 Γ3.\ninduction Γ2.\n\nintros.\nassumption.\nintros.\n\napply move_R_L.\nrewrite cons_single_app in H.\nrewrite app_assoc_reverse in H.\nrewrite app_assoc in H.\n\nrewrite cons_single_app.\nrewrite app_assoc.\napply (IHΓ2 (Γ1 ++ [a]) Γ4 H).\nQed.\n\nLemma weakening_L:\n    forall n Γ1 Γ2 Δ (D: LJ n (Γ1 ++ Γ2) Δ),\n      forall W, LJ n (Γ1 ++ W ++ Γ2) Δ.\nProof.\nintro n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nrewrite in_app_comm in Ant.\napply (in_app_add _ _ W) in Ant.\nrewrite app_assoc_reverse in Ant.\nrewrite in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\nrewrite in_app_comm in Fal.\napply (in_app_add _ _ W) in Fal.\nrewrite app_assoc_reverse in Fal.\nrewrite in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite app_assoc in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite app_assoc_reverse.\napply swap_L.\nrewrite <- Z2.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ I W) as I1.\napply (LJImpR I1).\n\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ L W) as L1.\nrewrite app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (le_n _) _ _ _ L W) as L1.\nrewrite! app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\nrewrite app_nil_l in Z2.\nsubst.\npose (H _ (le_n _) _ _ _ L W) as L1.\nrewrite app_assoc in *.\napply (LJConL1 A B _ _ L1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (le_n _) _ _ _ L W) as L1.\nrewrite! app_assoc_reverse in *.\napply (LJConL1 A B _ _ L1).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (le_n _) _ _ _ R W) as R1.\nrewrite app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\nsubst.\nrewrite app_assoc_reverse in R.\npose (H _ (le_n _) _ _ _ R W) as R1.\nrewrite !app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\nrewrite app_nil_l in Z2.\nsubst.\npose (H _ (le_n _) _ _ _ R W) as R1.\nrewrite app_assoc in *.\napply (LJConL2 A B _ _ R1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\npose (H _ (le_n _) _ _ _ R W) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJConL2 A B _ _ R1).\n\n(*ConR*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\nsubst.\nrewrite app_assoc_reverse in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\nrewrite app_assoc_reverse in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite! app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\nrewrite app_nil_l in Z2.\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L W) as L1.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R W) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L1 R1).\n\n(*DisR1*)\nsubst.\npose (H _ (le_n _) _ _ _ L W) as L1.\napply (LJDisR1 B L1).\n\n(*DisR2*)\nsubst.\npose (H _ (le_n _) _ _ _ R W) as R1.\napply (LJDisR2 A R1).\nQed.\n\nLemma inv_ImpL:\n  forall n E F Γ1 Γ2 Δ (D: LJ n (Γ1 ++ (E→F) :: Γ2) Δ),\n    (exists m, m <= n /\\ LJ m (Γ1 ++ F :: Γ2) Δ).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\napply imp_not_var in Ant.\napply in_app_comm in Ant.\napply (in_app_add _ _ [F] ) in Ant.\nrewrite app_assoc_reverse in Ant.\napply in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\napply imp_not_bot in Fal.\napply in_app_comm in Fal.\napply (in_app_add _ _ [F] ) in Fal.\nrewrite app_assoc_reverse in Fal.\napply in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite! app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LJImpR I2).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nrewrite app_assoc_reverse in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nrewrite app_assoc_reverse in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\n(*ConR*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJConR L2 R2).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nrewrite app_assoc_reverse in *.\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\n(*DisR1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJDisR1 B L2).\n\n(*DisR2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJDisR2 A R2).\nQed.\n\nLemma inv_ImpR:\n  forall n E F Γ (D : LJ n Γ (E→F)),\n   (exists m, m <= n /\\ LJ m (E::Γ) F).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsubst.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\napply (in_app_add _ _ [E]) in Fal.\napply in_app_comm in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [c [L1 L2]].\npose (weakening_L [] _ R [E]) as R1.\nexists (S (Nat.max c b)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 (le_n _))).\n\nrewrite app_comm_cons in L2.\napply (LJImpL _ _ _ L2 R1).\n\n(*ImpR*)\nsubst.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\n(*ConL1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ L) as [a [L1 L2]].\nrewrite app_comm_cons in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\n(*ConL2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ R) as [a [R1 R2]].\nrewrite app_comm_cons in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\n(*DisL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_comm_cons in *.\napply (LJDisL _ _ _ _ L2 R2).\nQed.\n\nLemma inv_ConL:\n  forall n E F Γ1 Γ2 Δ (D: LJ n (Γ1 ++ (Con E F) :: Γ2) Δ),\n    (exists m, m <= n /\\ LJ m (Γ1 ++ E :: F :: Γ2) Δ).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\napply con_not_var in Ant.\napply in_app_comm in Ant.\napply (in_app_add _ _ (E :: [F]) ) in Ant.\nrewrite app_assoc_reverse in Ant.\napply in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\napply con_not_bot in Fal.\napply in_app_comm in Fal.\napply (in_app_add _ _ (E :: [F]) ) in Fal.\nrewrite app_assoc_reverse in Fal.\napply in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite! app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LJImpR I2).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (weakening_L _ _ L [B]) as L1.\napply exchange_L in L1.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (weakening_L _ _ L [F]) as L1.\napply exchange_L in L1.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nrewrite app_assoc_reverse in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (weakening_L _ _ R [A]) as R1.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\npose (weakening_L _ _ R [E]) as R1.\nexists n.\nsplit.\n\napply (le_S _ _ (le_n _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nrewrite app_assoc_reverse in *.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\n(*ConR*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJConR L2 R2).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nrewrite app_assoc_reverse in *.\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\n(*DisR1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJDisR1 B L2).\n\n(*DisR2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJDisR2 A R2).\nQed.\n\nLemma inv_ConR:\n  forall n E F Γ (D : LJ n Γ (Con E F)),\n   ((exists m, m <= n /\\ LJ m Γ E) /\\ (exists m, m <= n /\\ LJ m Γ F)).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsubst.\nsplit.\n\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\napply (LJBot _ _ Fal).\n\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\nsplit.\n\nexists (S (Nat.max c b)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 (le_n _))).\n\napply (LJImpL _ _ _ L2 R).\n\nexists (S (max d b)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 (le_n _))).\n\napply (LJImpL _ _ _ L4 R).\n\n(*ConL1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ L) as [[a [L1 L2]] [b [L3 L4]]].\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ L3).\n\napply (LJConL1 A B _ _ L4).\n\n(*ConL2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ R) as [[a [R1 R2]] [b [R3 R4]]].\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ R3).\n\napply (LJConL2 A B _ _ R4).\n\n(*ConR*)\nsplit.\n\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\nexists b.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_r _ _)).\n\nassumption.\n\n(*DisL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nsplit.\n\nexists (S (max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\napply (LJDisL _ _ _ _ L4 R4).\nQed.\n\nLemma inv_DisL:\n  forall n E F Γ1 Γ2 Δ (D: LJ n (Γ1 ++ (Dis E F) :: Γ2) Δ),\n    (exists m, m <= n /\\ LJ m (Γ1 ++ E :: Γ2) Δ) /\\ (exists m, m <= n /\\ LJ m (Γ1 ++ F :: Γ2) Δ).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsplit.\n\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\napply dis_not_var in Ant.\napply in_app_comm in Ant.\napply (in_app_add _ _ [E] ) in Ant.\nrewrite app_assoc_reverse in Ant.\napply in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\napply dis_not_bot in Fal.\napply in_app_comm in Fal.\napply (in_app_add _ _ [E] ) in Fal.\nrewrite app_assoc_reverse in Fal.\napply in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LJBot _ _ Fal).\n\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\napply dis_not_var in Ant.\napply in_app_comm in Ant.\napply (in_app_add _ _ [F] ) in Ant.\nrewrite app_assoc_reverse in Ant.\napply in_app_comm in Ant.\nrewrite app_assoc_reverse in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\napply dis_not_bot in Fal.\napply in_app_comm in Fal.\napply (in_app_add _ _ [F] ) in Fal.\nrewrite app_assoc_reverse in Fal.\napply in_app_comm in Fal.\nrewrite app_assoc_reverse in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nsplit.\n\nexists (S (Nat.max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\nexists (S (Nat.max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L4 R4).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\nrewrite! app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nsplit.\n\nexists (S (Nat.max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L2 R2).\n\nexists (S (Nat.max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L4 R4).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [[b [I1 I2]] [c [I3 I4]]].\nsplit.\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LJImpR I2).\n\nexists (S c).\nsplit.\n\napply (le_n_S _ _ I3).\n\napply (LJImpR I4).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [[a [L1 L2]] [b [L3 L4]]].\nrewrite! app_comm_cons in *.\nrewrite! app_assoc in *.\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ L3).\n\napply (LJConL1 A B _ _ L4).\n\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [[a [L1 L2]] [b [L3 L4]]].\nrewrite! app_assoc_reverse in *.\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ L3).\n\napply (LJConL1 A B _ _ L4).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [[a [R1 R2]] [b [R3 R4]]].\nrewrite! app_comm_cons in *.\nrewrite! app_assoc in *.\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ R3).\n\napply (LJConL2 A B _ _ R4).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [[a [R1 R2]] [b [R3 R4]]].\nrewrite! app_assoc_reverse in *.\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ R3).\n\napply (LJConL2 A B _ _ R4).\n\n(*ConR*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nsplit.\n\nexists (S (max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJConR L2 R2).\n\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\napply (LJConR L4 R4).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nsplit.\n\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\nexists b.\n\nsplit.\napply (le_S _ _ (PeanoNat.Nat.le_max_r _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nrewrite! app_comm_cons in *.\nrewrite! app_assoc in *.\nsplit.\n\nexists (S (max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\napply (LJDisL _ _ _ _ L4 R4).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nsplit.\n\nexists a.\nsplit.\n\napply (le_S _ _ (PeanoNat.Nat.le_max_l _ _)).\n\nassumption.\n\nexists b.\n\nsplit.\napply (le_S _ _ (PeanoNat.Nat.le_max_r _ _)).\n\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [[c [L1 L2]] [d [L3 L4]]].\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [[e [R1 R2]] [f [R3 R4]]].\nrewrite! app_assoc_reverse in *.\nsplit.\n\nexists (S (max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 R3)).\n\napply (LJDisL _ _ _ _ L4 R4).\n\n(*DisR1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [[a [L1 L2]] [b [L3 L4]]].\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJDisR1 B L2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ L3).\n\napply (LJDisR1 B L4).\n\n\n(*DisR2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [[a [R1 R2]] [b [R3 R4]]].\nsplit.\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJDisR2 A R2).\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ R3).\n\napply (LJDisR2 A R4).\nQed.\n\nLemma inv_DisR:\n  forall n E F Γ (D : LJ n Γ (Dis E F)),\n   ((exists m, m <= n /\\ LJ m Γ E) \\/ (exists m, m <= n /\\ LJ m Γ F)).\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nsubst.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\nleft.\nexists 0.\nsplit.\n\napply le_n.\n\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [[c [L1 L2]] | [d [L3 L4]]].\n\nleft.\nexists (S (Nat.max c b)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 (le_n _))).\n\napply (LJImpL _ _ _ L2 R).\n\nright.\nexists (S (max d b)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L3 (le_n _))).\n\napply (LJImpL _ _ _ L4 R).\n\n(*ConL1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ L) as [[a [L1 L2]] | [b [L3 L4]]].\n\nleft.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJConL1 A B _ _ L2).\n\nright.\nexists (S b).\nsplit.\n\napply (le_n_S _ _ L3).\n\napply (LJConL1 A B _ _ L4).\n\n(*ConL2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ R) as [[a [R1 R2]] | [b [R3 R4]]].\n\nleft.\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJConL2 A B _ _ R2).\n\nright.\nexists (S b).\nsplit.\n\napply (le_n_S _ _ R3).\n\napply (LJConL2 A B _ _ R4).\n\n(*DisL*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L) as [[c [L1 L2]] | [d [L3 L4]]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R) as [[e [R1 R2]] | [f [R3 R4]]].\n\nleft.\nexists (S (max c e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJDisL _ _ _ _ L2 R2).\n\n\nleft.\nexists (S (max c f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R3)).\n\nadmit.\n\nadmit.\n\n(*DisR1*)\nsubst.\nleft.\nexists n.\nsplit.\n\napply (le_S _ _(le_n _)).\n\nassumption.\n\n(*DisR2*)\nsubst.\nright.\nexists n.\nsplit.\n\napply (le_S _ _(le_n _)).\n\nassumption.\nAdmitted.\n\n\nLemma conj_comm : forall n E F Γ1 Γ2 Δ (D : (Γ1 ++ Con E F :: Γ2) |- Δ >> n),\n  (Γ1 ++ Con F E :: Γ2) |- Δ >> n.\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\napply con_not_var in Ant.\nrewrite in_app_comm in Ant.\npose (in_app_add _ _ [Con F E] Ant) as Ant1.\nrewrite app_assoc_reverse in Ant1.\nrewrite in_app_comm in Ant1.\nrewrite app_assoc_reverse in Ant1.\napply (LJId _ _ Ant1).\n\n(*Bot*)\nsubst.\napply con_not_bot in Fal.\nrewrite in_app_comm in Fal.\npose (in_app_add _ _ [Con F E] Fal) as Fal1.\nrewrite app_assoc_reverse in Fal1.\nrewrite in_app_comm in Fal1.\nrewrite app_assoc_reverse in Fal1.\napply (LJBot _ _ Fal1).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\napply (LJImpR I1).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\napply (LJConL2 _ _ _ _ L).\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL1 _ _ _ _ L1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\napply (LJConL2 _ _ _ _ L).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite! app_assoc_reverse in *.\napply (LJConL1 _ _ _ _ L1).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\napply (LJConL1 _ _ _ _ R).\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL2 _ _ _ _ R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\napply (LJConL1 _ _ _ _ R).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJConL2 _ _ _ _ R1).\n\n(*ConR*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L1 R1).\n\n(*DisR1*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\napply (LJDisR1 _ L1).\n\n(*DisR2*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\napply (LJDisR2 _ R1).\nQed.\n\nLemma conj_assoc_no_height : forall n E F G Γ1 Γ2 Δ (D : (Γ1 ++ Con E (Con F G) :: Γ2) |- Δ >> n),\n exists m, (Γ1 ++ Con (Con E F) G :: Γ2) |- Δ >> m.\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\napply con_not_var in Ant.\nrewrite in_app_comm in Ant.\npose (in_app_add _ _ [Con (Con E F) G] Ant) as Ant1.\nrewrite app_assoc_reverse in Ant1.\nrewrite in_app_comm in Ant1.\nrewrite app_assoc_reverse in Ant1.\nexists 0.\napply (LJId _ _ Ant1).\n\n(*Bot*)\nsubst.\napply con_not_bot in Fal.\nrewrite in_app_comm in Fal.\npose (in_app_add _ _ [Con (Con E F) G] Fal) as Fal1.\nrewrite app_assoc_reverse in Fal1.\nrewrite in_app_comm in Fal1.\nrewrite app_assoc_reverse in Fal1.\nexists 0.\napply (LJBot _ _ Fal1).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ _ L) as [c L1].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ _ R) as [d R1].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S (max c d)).\napply (LJImpL _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ _ L) as [c L1].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ _ R) as [d R1].\nrewrite! app_assoc_reverse in *.\nexists (S (max c d)).\napply (LJImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ _ I) as [a I1].\nexists (S a).\napply (LJImpR I1).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nexists (S (S n)).\napply (LJConL1 _ _ _ _ (LJConL1 _ _ _ _ L)).\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\ndestruct (H _ (le_n _) _ _ _ _ _ _ L) as [a L1].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\napply (LJConL1 _ _ _ _ L1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nexists (S (S n)).\napply (LJConL1 _ _ _ _ (LJConL1 _ _ _ _ L)).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\ndestruct (H _ (le_n _) _ _ _ _ _ _ L) as [a L1].\nrewrite! app_assoc_reverse in *.\nexists (S a).\napply (LJConL1 _ _ _ _ L1).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\ndestruct (H _ (le_n _) _ _ _ _ _ _ R) as [a R1].\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\nexists (S a).\napply (LJConL2 _ _ _ _ R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (le_n _) _ _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJConL2 _ _ _ _ R1).\n\n(*ConR*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ _ R) as R1.\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L1 R1).\n\n(*DisR1*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ _ L) as L1.\napply (LJDisR1 _ L1).\n\n(*DisR2*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ _ R) as R1.\napply (LJDisR2 _ R1).\nAdmitted.\n\nLemma disj_comm : forall n E F Γ1 Γ2 Δ (D : (Γ1 ++ Dis E F :: Γ2) |- Δ >> n),\n  (Γ1 ++ Dis F E :: Γ2) |- Δ >> n.\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\napply dis_not_var in Ant.\nrewrite in_app_comm in Ant.\npose (in_app_add _ _ [Dis F E] Ant) as Ant1.\nrewrite app_assoc_reverse in Ant1.\nrewrite in_app_comm in Ant1.\nrewrite app_assoc_reverse in Ant1.\napply (LJId _ _ Ant1).\n\n(*Bot*)\nsubst.\napply dis_not_bot in Fal.\nrewrite in_app_comm in Fal.\npose (in_app_add _ _ [Dis F E] Fal) as Fal1.\nrewrite app_assoc_reverse in Fal1.\nrewrite in_app_comm in Fal1.\nrewrite app_assoc_reverse in Fal1.\napply (LJBot _ _ Fal1).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L1 R1).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\npose (H _ (le_n _) _ _ _ _ _ I) as I1.\napply (LJImpR I1).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL1 _ _ _ _ L1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\nrewrite! app_assoc_reverse in *.\napply (LJConL1 _ _ _ _ L1).\n\n(*ConL2*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL2 _ _ _ _ R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJConL2 _ _ _ _ R1).\n\n(*ConR*)\nsubst.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nrewrite PeanoNat.Nat.max_comm.\napply (LJDisL _ _ _ _ R L).\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L1 R1).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\n\nsubst.\nrewrite PeanoNat.Nat.max_comm.\napply (LJDisL _ _ _ _ R L).\n\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite! app_assoc in *.\npose (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as L1.\npose (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as R1.\nrewrite! app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L1 R1).\n\n(*DisR1*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ L) as L1.\napply (LJDisR1 _ L1).\n\n(*DisR2*)\nsubst.\npose (H _ (le_n _) _ _ _ _ _ R) as R1.\napply (LJDisR2 _ R1).\nQed.\n\n\nLemma strong_conj: forall n E F Γ1 Γ2 Δ (D : (Γ1 ++ E :: F :: Γ2) |- Δ >> n),\n  exists m, m <= S n /\\ LJ m (Γ1 ++ (Con E F) :: Γ2) Δ.\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\n\napply in_app_iff in Ant.\ndestruct Ant as [Ant | Ant].\n\nexists 0.\nsplit.\n\napply (le_S _ _ (le_n _ )).\n\napply (LJId _ _ (in_app_add _ _ (Con E F :: Γ2) Ant)).\n\ndestruct Ant as [Ant | Ant].\n\nsubst.\nexists 1.\nsplit.\n\napply le_n.\n\napply (LJConL1 _ F _ _ (LJId A (Γ1 ++ # A :: Γ2) (in_elt _ _ _))).\n\ndestruct Ant as [Ant | Ant].\n\nsubst.\nexists 1.\nsplit.\n\napply le_n.\n\napply (LJConL2 E _ _ _ (LJId A (Γ1 ++ # A :: Γ2) (in_elt _ _ _))).\n\nexists 0.\nsplit.\n\napply (le_S _ _ (le_n _ )).\n\nrewrite <- (app_nil_l _).\napply move_R_L.\nrewrite <- (app_nil_r _).\nrewrite app_comm_cons.\nrewrite app_assoc_reverse.\nrewrite app_assoc_reverse.\napply swap_L.\nrewrite (app_nil_r _).\napply (LJId _ _ (in_app_add _ _ (Con E F :: Γ1) Ant)).\n\n(*Bot*)\nsubst.\n\napply in_app_iff in Fal.\ndestruct Fal as [Fal | Fal].\n\nexists 0.\nsplit.\n\napply (le_S _ _ (le_n _ )).\n\napply (LJBot _ _ (in_app_add _ _ (Con E F :: Γ2) Fal)).\n\ndestruct Fal as [Fal | Fal].\n\nsubst.\nexists 1.\nsplit.\n\napply le_n.\n\npose (LJBot Δ (Γ1 ++ Bot :: Γ2) (in_elt _ _ _)) as I1.\napply (LJConL1 _ F _ _ I1).\n\ndestruct Fal as [Fal | Fal].\n\nsubst.\nexists 1.\nsplit.\n\napply le_n.\n\npose (LJBot Δ (Γ1 ++ Bot :: Γ2) (in_elt _ _ _)) as I1.\napply (LJConL2 E _ _ _ I1).\n\nexists 0.\nsplit.\n\napply (le_S _ _ (le_n _ )).\n\nrewrite <- (app_nil_l _).\napply move_R_L.\nrewrite <- (app_nil_r _).\nrewrite app_comm_cons.\nrewrite app_assoc_reverse.\nrewrite app_assoc_reverse.\napply swap_L.\nrewrite (app_nil_r _).\napply (LJBot _ _ (in_app_add _ _ ([Con E F]++Γ1) Fal)).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\n\nadmit.\n\ndestruct l.\n\ninversion Z2.\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- !app_comm_cons in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _).\nrewrite PeanoNat.Nat.succ_max_distr.\napply (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1).\n\nrewrite !app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\ndestruct l.\n\ninversion Z2.\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite !app_comm_cons in *.\nrewrite !app_assoc in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _).\nrewrite PeanoNat.Nat.succ_max_distr.\napply (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1).\n\nrewrite !app_assoc_reverse in *.\nrewrite <- !app_comm_cons in *.\napply (LJImpL _ _ _ L2 R2).\n\n(*ImpR*)\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\n\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LJImpR I2).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\n\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nadmit.\n\ndestruct l.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\npose (LJConL1 _ B _ _ L2).\nadmit.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite <- !app_comm_cons in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite! app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL1 _ _ _ _ L2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nadmit.\n\ndestruct l.\n\ninversion Z2.\nsubst.\nrewrite cons_single_app in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite app_assoc_reverse in *.\napply (LJConL1 _ _ _ _ L2).\n\ninversion Z2.\nsubst.\nrewrite !app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite app_assoc_reverse in *.\nrewrite <- !app_comm_cons in *.\napply (LJConL1 _ _ _ _ L2).\n\n(*ConL2*)\nadmit.\n\n(*ConR*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _).\nrewrite PeanoNat.Nat.succ_max_distr.\napply (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1).\n\napply (LJConR L2 R2).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\n\nadmit.\n\ndestruct l.\n\ninversion Z2.\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- !app_comm_cons in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _).\nrewrite PeanoNat.Nat.succ_max_distr.\napply (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1).\n\nrewrite !app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L2 R2).\n\ndestruct l.\n\ninversion Z2.\nsubst.\nadmit.\n\ninversion Z2.\nsubst.\nrewrite !app_comm_cons in *.\nrewrite app_assoc in *.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _).\nrewrite PeanoNat.Nat.succ_max_distr.\napply (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1).\n\nrewrite app_assoc_reverse in *.\nrewrite <- !app_comm_cons in *.\napply (LJDisL _ _ _ _ L2 R2).\n\n(*DisR1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJDisR1 B L2).\n\n(*DisR2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJDisR2 A R2).\nAdmitted.\n\nTheorem contraction:\n  forall n X Γ1 Γ2 Γ3 Δ (D : (Γ1 ++ X :: Γ2 ++ X :: Γ3) |- Δ >> n),\n       exists m, m <= n /\\ LJ m (Γ1 ++ X :: Γ2 ++ Γ3 ) Δ.\nProof.\nintros n.\ninduction n using strong_induction.\n\n(*Base Case*)\nintros.\nexists 0.\nsplit.\n\napply le_n.\n\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\napply in_double in Ant.\napply (LJId _ _ Ant).\n\n(*Bot*)\nsubst.\napply in_double in Fal.\napply (LJBot _ _ Fal).\n\n(*Inductive*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ImpL _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in L2.\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) B _ _ _ _ L2) as [d [L3 L4]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) (Imp A B) _ _ _ _ R) as [e [R1 R2]].\nexists (S (Nat.max d e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R1 (le_n _)))).\n\napply (LJImpL _ _ _ L4 R2).\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ A → B :: ΓB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 | Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) p _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) p _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite app_assoc in *.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\nsubst.\nrewrite app_assoc_reverse in L.\ndestruct (inv_ImpL _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) _ _ _ _ _ L2) as [d [L3 L4]].\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [e [R1 R2]].\nexists (S (Nat.max d e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R1 (le_n _)))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L4.\napply move_R_L in R2.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L4 R2).\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z1]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite (app_assoc (p :: l)) in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\nrewrite <- app_comm_cons in R.\nrewrite app_assoc in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite! app_assoc_reverse in *.\nrewrite app_assoc in *.\napply (LJImpL _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ImpL _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in L2.\ndestruct (H _ ((le_trans L1 (PeanoNat.Nat.le_max_l _ _))) _ _ _ _ _ L2) as [d [L3 L4]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [e [R1 R2]].\nexists (S (Nat.max d e)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R1 (le_n _)))).\n\napply (LJImpL _ _ _ L4 R2).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite! app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (Nat.max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite! app_assoc_reverse in *.\napply (LJImpL _ _ _ L2 R2).\n\n(*ImpR*)\nsubst.\nrewrite app_comm_cons in I.\ndestruct (H _ (le_n _) _ _ _ _ _ I) as [b [I1 I2]].\nexists (S b).\nsplit.\n\napply (le_n_S _ _ I1).\n\napply (LJImpR I2).\n\n(*ConL1*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ConL _ _ _ _ L) as [a [L1 L2]].\nrewrite app_assoc_reverse in L2.\ndestruct (H _ L1 _ _ _ _ _ L2) as [b [L3 L4]].\napply move_R_L in L4.\nrewrite app_assoc in L4.\ndestruct (strong_conj _ _ _ _ L4) as [c [L5 L6]].\nexists c.\nsplit.\n\napply (le_trans L5 (le_n_S _ _ (le_trans L3 L1))).\n\nrewrite app_assoc_reverse in L6.\nrewrite cons_single_app.\napply swap_L.\nassumption.\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ Con A B :: ΓB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 | Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (le_n _) p _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\nrewrite app_assoc in *.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL1 _ _ _ _ L2).\n\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite <- app_comm_cons in L.\ndestruct (inv_ConL _ _ _ _ L) as [a [L1 L2]].\nrewrite app_comm_cons in L2.\ndestruct (H _ L1 _ _ _ _ _ L2) as [b [L3 L4]].\ndestruct (strong_conj _ _ _ _ L4) as [c [L5 L6]].\nexists c.\nsplit.\n\napply (le_trans L5 (le_n_S _ _ (le_trans L3 L1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L6.\nassumption.\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z1]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite (app_assoc (p :: l)) in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\nrewrite! app_assoc_reverse in *.\nrewrite app_assoc in *.\napply (LJConL1 _ _ _ _ L2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (inv_ConL _ _ _ _ L) as [a [L1 L2]].\nrewrite app_assoc_reverse in L2.\ndestruct (H _ L1 _ _ _ _ _ L2) as [b [L3 L4]].\napply move_R_L in L4.\nrewrite app_assoc in L4.\ndestruct (strong_conj _ _ _ _ L4) as [c [L5 L6]].\nexists c.\nsplit.\n\napply (le_trans L5 (le_n_S _ _ (le_trans L3 L1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite app_assoc.\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\nrewrite! app_assoc_reverse in *.\napply (LJConL1 _ _ _ _ L2).\n\n(*ConL2*)\nsubst.\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (inv_ConL _ _ _ _ R) as [a [R1 R2]].\nrewrite app_assoc_reverse in R2.\nrewrite (cons_single_app A) in R2.\nrewrite <- app_comm_cons in R2.\nrewrite app_assoc in R2.\ndestruct (H _ R1 _ _ _ _ _ R2) as [b [R3 R4]].\nrewrite app_assoc_reverse in R4.\napply move_R_L in R4.\nrewrite app_assoc in R4.\napply exchange_L in R4.\ndestruct (strong_conj _ _ _ _ R4) as [c [R5 R6]].\nexists c.\nsplit.\n\napply (le_trans R5 (le_n_S _ _ (le_trans R3 R1))).\n\nrewrite app_assoc_reverse in R6.\nrewrite cons_single_app.\napply swap_L.\nassumption.\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ Con A B :: ΓB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 | Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (le_n _) p _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in R2.\nrewrite app_assoc in *.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJConL2 _ _ _ _ R2).\n\nsubst.\nrewrite app_assoc_reverse in R.\nrewrite <- app_comm_cons in R.\ndestruct (inv_ConL _ _ _ _ R) as [a [R1 R2]].\nrewrite cons_single_app in R2.\nrewrite app_assoc in R2.\ndestruct (H _ R1 _ _ _ _ _ R2) as [b [R3 R4]].\nrewrite app_assoc_reverse in R4.\ndestruct (strong_conj _ _ _ _ R4) as [c [R5 R6]].\nexists c.\nsplit.\n\napply (le_trans R5 (le_n_S _ _ (le_trans R3 R1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in R6.\nassumption.\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z1]].\nsubst.\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite (app_assoc (p :: l)) in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in R2.\nrewrite! app_assoc_reverse in *.\nrewrite app_assoc in *.\napply (LJConL2 _ _ _ _ R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (inv_ConL _ _ _ _ R) as [a [R1 R2]].\nrewrite app_assoc_reverse in R2.\nrewrite (cons_single_app A) in R2.\nrewrite <- app_comm_cons in R2.\nrewrite app_assoc in R2.\ndestruct (H _ R1 _ _ _ _ _ R2) as [b [R3 R4]].\napply move_R_L in R4.\nrewrite app_assoc_reverse in R4.\nrewrite app_assoc in R4.\ndestruct (strong_conj _ _ _ _ R4) as [c [R5 R6]].\nexists c.\nsplit.\n\napply (le_trans R5 (le_n_S _ _ (le_trans R3 R1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite app_assoc.\nassumption.\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\nrewrite! app_assoc_reverse in *.\napply (LJConL2 _ _ _ _ R2).\n\n(*ConR*)\nsubst.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\napply (LJConR L2 R2).\n\n(*DisL*)\nsubst.\ndestruct (app_eq_app _ _ _ _ EqS) as [l [ [Z1 Z2] | [Z1 Z2] ]].\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\ndestruct (inv_DisL _ _ _ _ L) as [[c [L1 L2]] _].\ndestruct (inv_DisL _ _ _ _ R) as [_ [e [R1 R2]]].\nrewrite app_assoc_reverse in *.\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) _ _ _ _ _ L2) as [d [L3 L4]].\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) _ _ _ _ _ R2) as [f [R3 R4]].\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\napply (LJDisL _ _ _ _ L4 R4).\n\ninversion Z2 as [[Z3 Z4]].\nsubst.\nassert (Z5 : In p (l ++ Dis A B :: ΓB)) by apply (in_list_eq Z4).\napply in_app_iff in Z5.\ndestruct Z5 as [Z5 | [Z5 | Z5]].\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z3]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite app_assoc_reverse in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) p _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite app_assoc_reverse in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) p _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite app_assoc in *.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L2 R2).\n\nsubst.\nrewrite app_assoc_reverse in *.\nrewrite <- app_comm_cons in *.\ndestruct (inv_DisL _ _ _ _ L) as [[c [L1 L2]] _].\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) _ _ _ _ _ L2) as [d [L3 L4]].\ndestruct (inv_DisL _ _ _ _ R) as [_ [e [R1 R2]]].\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) _ _ _ _ _ R2) as [f [R3 R4]].\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L.\napply (LJDisL _ _ _ _ L4 R4).\n\ndestruct (in_split _ _ Z5) as [l1 [l2 Z1]].\nsubst.\nrewrite app_assoc_reverse in L.\nrewrite app_comm_cons in L.\nrewrite (app_assoc (p :: l)) in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_assoc_reverse in R.\nrewrite app_comm_cons in R.\nrewrite (app_assoc (p :: l)) in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite cons_single_app.\napply swap_L.\nrewrite <- cons_single_app.\nrewrite Z4.\napply move_R_L in L2.\napply move_R_L in R2.\nrewrite! app_assoc_reverse in *.\nrewrite app_assoc in *.\napply (LJDisL _ _ _ _ L2 R2).\n\ndestruct l.\n\nrewrite app_nil_r in Z1.\ninversion Z2.\nsubst.\nrewrite app_comm_cons in *.\nrewrite app_assoc in *.\ndestruct (inv_DisL _ _ _ _ L) as [[c [L1 L2]] _].\ndestruct (inv_DisL _ _ _ _ R) as [_ [e [R1 R2]]].\nrewrite app_assoc_reverse in *.\ndestruct (H _ (le_trans L1 (PeanoNat.Nat.le_max_l _ _)) _ _ _ _ _ L2) as [d [L3 L4]].\ndestruct (H _ (le_trans R1 (PeanoNat.Nat.le_max_r _ _)) _ _ _ _ _ R2) as [f [R3 R4]].\nexists (S (max d f)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ (le_trans L3 L1) (le_trans R3 R1))).\n\napply (LJDisL _ _ _ _ L4 R4).\n\ninversion Z2.\nsubst.\nrewrite app_comm_cons in L.\nrewrite app_assoc in L.\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ _ _ L) as [c [L1 L2]].\nrewrite app_comm_cons in R.\nrewrite app_assoc in R.\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ _ _ R) as [d [R1 R2]].\nexists (S (max c d)).\nsplit.\n\napply (le_n_S _ _ (PeanoNat.Nat.max_le_compat _ _ _ _ L1 R1)).\n\nrewrite app_assoc_reverse in *.\napply (LJDisL _ _ _ _ L2 R2).\n\n(*DisR1*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ L) as [a [L1 L2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ L1).\n\napply (LJDisR1 B L2).\n\n(*DisR2*)\nsubst.\ndestruct (H _ (le_n _) _ _ _ _ _ R) as [a [R1 R2]].\nexists (S a).\nsplit.\n\napply (le_n_S _ _ R1).\n\napply (LJDisR2 A R2).\nQed.\n\nTheorem cut_elimination:\n  forall A n m Γ Δ (D : LJ n Γ A) (D1 : LJ m ([A] ++ Γ) Δ),\n    exists k, Γ |- Δ >> k.\nProof.\nintros A.\ninduction A.\n\n(*PropVar*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\nsubst.\ndestruct (in_split _ _ Ant) as [l1 [l2 Z1]].\nsubst.\ndestruct (contraction _ [] _ _ D1) as [a [I1 I2]].\napply move_R_L in I2.\nexists a.\nassumption.\n\n(*Bot*)\nexists 0.\napply (LJBot _ _ Fal).\n\n(*Inductive n*)\nintros.\nsubst.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\nexists (S (max d b)).\napply (LJImpL _ _ _ L3 R).\n\n(*ConL1*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ConL _ _ _ _ D1) as [c [L1 L2]].\nrewrite app_assoc_reverse in L2.\nrewrite cons_single_app in L.\nrewrite app_assoc in L.\npose (weakening_L (ΓA ++ [A]) _ L [B]) as L3.\nrewrite app_assoc_reverse in L3.\ndestruct (H _ (le_n _) _ _ _ L3 L2) as [d L4].\ndestruct (strong_conj _ _ _ _ L4) as [e [L5 L6]].\nexists e.\nassumption.\n\n(*ConL2*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ConL _ _ _ _ D1) as [c [R1 R2]].\nrewrite app_assoc_reverse in R2.\npose (weakening_L ΓA _ R [A]) as R3.\ndestruct (H _ (le_n _) _ _ _ R3 R2) as [d R4].\ndestruct (strong_conj _ _ _ _ R4) as [e [R5 R6]].\nexists e.\nassumption.\n\n(*DisL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_DisL _ _ _ _ D1) as [[c [L1 L2]] [d [R1 R2]]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [e L3].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max e f)).\napply (LJDisL _ _ _ _ L3 R3).\n\n(*Bot*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\nsubst.\nexists 0.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\napply (LJBot _ _ Fal).\n\n(*Inductive n*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ImpL _ _ _ _ D1) as [c [L1 L2]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [d L3].\nexists (S (max d b)).\napply (LJImpL _ _ _ L3 R).\n\n(*ConL1*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ConL _ _ _ _ D1) as [c [L1 L2]].\nrewrite app_assoc_reverse in L2.\nrewrite cons_single_app in L.\nrewrite app_assoc in L.\npose (weakening_L (ΓA ++ [A]) _ L [B]) as L3.\nrewrite app_assoc_reverse in L3.\ndestruct (H _ (le_n _) _ _ _ L3 L2) as [d L4].\ndestruct (strong_conj _ _ _ _ L4) as [e [L5 L6]].\nexists e.\nassumption.\n\n(*ConL2*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_ConL _ _ _ _ D1) as [c [R1 R2]].\nrewrite app_assoc_reverse in R2.\npose (weakening_L ΓA _ R [A]) as R3.\ndestruct (H _ (le_n _) _ _ _ R3 R2) as [d R4].\ndestruct (strong_conj _ _ _ _ R4) as [e [R5 R6]].\nexists e.\nassumption.\n\n(*DisL*)\nsubst.\nrewrite app_assoc in D1.\ndestruct (inv_DisL _ _ _ _ D1) as [[c [L1 L2]] [d [R1 R2]]].\ndestruct (H _ (PeanoNat.Nat.le_max_l _ _) _ _ _ L L2) as [e L3].\ndestruct (H _ (PeanoNat.Nat.le_max_r _ _) _ _ _ R R2) as [f R3].\nexists (S (max e f)).\napply (LJDisL _ _ _ _ L3 R3).\n\n(*Imp*)\nintros n.\ninduction n using strong_induction.\n\n(*Base Case n*)\nintros.\ninversion D as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Bot*)\nexists 0.\napply (LJBot _ _ Fal).\n\n(*Inductive n*)\nintros m.\ninduction m using strong_induction.\n\n(*Base Case m : n = n*)\nintros.\ninversion D1 as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*Id*)\ndestruct Ant as [Ant | Ant].\n\ndiscriminate.\n\nexists 0.\napply (LJId _ _ Ant).\n\n(*Bot*)\ndestruct Fal as [Fal | Fal].\n\ndiscriminate.\n\nexists 0.\napply (LJBot _ _ Fal).\n\n(*Inductive m : n = n*)\nintros.\ninversion D1 as [ A ΓT Ant Height EqA EqS | A ΓT Fal Height EqA EqS | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT I Height EqA EqS | a A B ΓA ΓB ΔT L Height EqS EqA | a A B ΓA ΓB ΔT R Height EqS EqA | a b A B ΓT L R Height EqS EqA | a b A B ΓA ΓB ΔT L R Height EqS EqA | a A B ΓT L Height EqS EqA | a A B ΓT R Height EqS EqA].\n\n(*ImpL*)\nsubst.\ndestruct ΓA.\n\ninversion EqS.\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_r _ _) _ _ D R) as [c I1].\ndestruct (inv_ImpR D) as [d [I2 I3]].\ndestruct (IHA1 _ _ _ _ I1 I3) as [e I4].\ndestruct (IHA2 _ _ _ _ I4 L) as [f I5].\nexists f.\nassumption.\n\ninversion EqS.\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_r _ _) _ _ D R) as [c R1].\npose (weakening_L _ _ R1 [Imp A B]) as R2.\nrewrite app_assoc in R2.\nrewrite cons_single_app in D.\nrewrite app_assoc in D.\npose (weakening_L _ _ D [B]) as L1.\nrewrite app_assoc_reverse in L1.\npose (weakening_L _ _ L [Imp A B]) as L2.\ndestruct (H0 _ (PeanoNat.Nat.le_max_l _ _) _ _ L1 L2) as [d L3].\nrewrite app_assoc in L3.\npose (LJImpL _ _ _ L3 R2) as I1.\nrewrite app_assoc_reverse in I1.\ndestruct (contraction _ _ [] _ I1) as [e [I2 I3]].\nexists e.\nassumption.\n\n(*ImpR*)\nsubst.\npose (weakening_L [] _ D [A]) as I1.\nrewrite <- (app_nil_l (A :: [A1 → A2] ++ Γ)) in I.\napply move_R_L in I.\ndestruct (H0 _ (le_n _) _ _ I1 I) as [c I2].\nexists (S c).\napply (LJImpR I2).\n\n(*ConL1*)\nsubst.\ndestruct ΓA.\ninversion EqS.\ninversion EqS.\nsubst.\nrewrite (cons_single_app A) in L.\nrewrite app_assoc in L.\npose (weakening_L _ _ L [B]) as L1.\nrewrite! app_assoc_reverse in L1.\ndestruct (inv_ConL _ _ _ _ D) as [a [R1 R2]].\ninversion R1 as [R3 | d R3 R4].\n\nsubst.\ndestruct (H0 _ (le_n _) _ _ R2 L1) as [b I1].\ndestruct (strong_conj _ _ _ _ I1) as [c [I2 I3]].\nexists c.\nassumption.\n\ndestruct (H _ R3 _ _ _ R2 L1) as [b I1].\ndestruct (strong_conj _ _ _ _ I1) as [c [I2 I3]].\nexists c.\nassumption.\n\n(*ConL2*)\nsubst.\ndestruct ΓA.\ninversion EqS.\ninversion EqS.\nsubst.\npose (weakening_L _ _ R [A]) as R1.\ndestruct (inv_ConL _ _ _ _ D) as [a [L1 L2]].\ninversion L1 as [L3 | d L3 L4].\n\nsubst.\ndestruct (H0 _ (le_n _) _ _ L2 R1) as [b I1].\ndestruct (strong_conj _ _ _ _ I1) as [c [I2 I3]].\nexists c.\nassumption.\n\ndestruct (H _ L3 _ _ _ L2 R1) as [b I1].\ndestruct (strong_conj _ _ _ _ I1) as [c [I2 I3]].\nexists c.\nassumption.\n\n(*ConR*)\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_l _ _) _ _ D L) as [c L1].\ndestruct (H0 _ (PeanoNat.Nat.le_max_r _ _) _ _ D R) as [d R1].\nexists (S (max c d)).\napply (LJConR L1 R1).\n\n(*DisL*)\nsubst.\ndestruct ΓA.\ninversion EqS.\ninversion EqS.\nsubst.\ndestruct (inv_DisL _ _ _ _ D) as [[c [I1 I2]] [d [I3 I4]]].\ninversion I1 as [I5 | e I5 I6].\n\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_l _ _) _ _ I2 L) as [g I9].\ninversion I3 as [I7 | f I7 I8].\n\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_r _ _) _ _ I4 R) as [h I10].\nexists (S (max g h)).\napply (LJDisL _ _ _ _ I9 I10).\n\ndestruct (H _ I7 _ _ _ I4 R) as [h I10].\nexists (S (max g h)).\napply (LJDisL _ _ _ _ I9 I10).\n\nsubst.\ndestruct (H _ I5 _ _ _ I2 L) as [g I9].\ninversion I3 as [I7 | f I7 I8].\n\nsubst.\ndestruct (H0 _ (PeanoNat.Nat.le_max_r _ _) _ _ I4 R) as [h I10].\nexists (S (max g h)).\napply (LJDisL _ _ _ _ I9 I10).\n\ndestruct (H _ I7 _ _ _ I4 R) as [h I10].\nexists (S (max g h)).\napply (LJDisL _ _ _ _ I9 I10).\n\n(*DisR1*)\nsubst.\ndestruct (H0 _ (le_n _) _ _ D L) as [a L1].\nexists (S a).\napply (LJDisR1 B L1).\n\n(*DisR2*)\nsubst.\ndestruct (H0 _ (le_n _) _ _ D R) as [a R1].\nexists (S a).\napply (LJDisR2 A R1).\n\n(*Con*)\nintros.\ndestruct (inv_ConR D) as [[a [L1 L2]] [b [R1 R2]]].\ndestruct (inv_ConL _ _ [] _ D1) as [c [I1 I2]].\npose (weakening_L [] _ L2 [A2]) as I3.\ndestruct (IHA1 _ _ _ _ I3 I2) as [d I4].\ndestruct (IHA2 _ _ _ _ R2 I4) as [e I5].\nexists e.\nassumption.\n\n(*Dis*)\nintros.\ndestruct (inv_DisL _ _ [] _ D1) as [[a [I1 I2]] [b [I3 I4]]].\ndestruct (inv_DisR D) as [[c [I5 I6]] | [c [I5 I6]]].\n\napply (IHA1 _ _ _ _ I6 I2).\n\napply (IHA2 _ _ _ _ I6 I4).\nAdmitted.", "meta": {"author": "aarondroidbryce", "repo": "LK_Formalisation_Coq", "sha": "17714aa86f76355ba2f93336b869f2ca05457b05", "save_path": "github-repos/coq/aarondroidbryce-LK_Formalisation_Coq", "path": "github-repos/coq/aarondroidbryce-LK_Formalisation_Coq/LK_Formalisation_Coq-17714aa86f76355ba2f93336b869f2ca05457b05/Aaron_LJ_change_PropF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.751314934091805}}
{"text": "Require Import Coq.QArith.QArith_base.\nRequire Import Coq.QArith.Qabs.\nRequire Import Psatz.\nRequire Import Coq.QArith.Qround.\nRequire Import Coq.PArith.Pnat.\nRequire Import Sequence.\nRequire Import Utility.\n\n\nDefinition a := 5#1.\nDefinition b := 2#1.\nDefinition seq_ex1 q:= a+b/q.\nDefinition r_ex1 := a.\n\n\n\nDefinition a_ex1 q := q*b.\n\n\n\n\n\n\nLemma a_spec_ex1 : forall q, q>0 -> Qabs ((seq_ex1 (a_ex1 q)) + -r_ex1) <= 1/q.\nProof.\nintros.\nunfold seq_ex1.\nunfold a_ex1.\nunfold r_ex1.\nassert( a + b / (q * b) + - a == b / (q * b)) by lra.\nrewrite H0.\nassert( b / (q*b)==b * (/q) * (/b) ).\n{\n  assert(b * (/q) * (/b) == b * ((/q) * (/b))) by lra.\n  assert( H2 := Qinv_mult_distr q b).\n  assert(/q * /b == /(q*b)) by lra.\n  rewrite H3 in H1.\n  auto with *.\n}\nrewrite H1.\nassert ( b * / q * / b == /q ).\n{\n  assert( b * / q * / b == (b * /b) * /q) by lra.\n  rewrite H2.\n  assert( b * /b == 1) by auto with *.\n  rewrite H3.\n  lra.\n}\nrewrite H2.\nassert( H3 := qinvq_eq_1divq q).\nrewrite H3.\n\nassert( H4 := q_pos_invq_pos q H ).\nassert( 0 <= 1/q ) by lra.\nassert( H6 := Qabs_pos (1/q) H5 ).\nrewrite H6.\napply Qle_refl.\n\nQed.\n\n\nLemma ex1' : ConvergentSequence_def seq_ex1 r_ex1 a_ex1.\nProof.\nunfold ConvergentSequence_def.\nintros.\napply (a_spec_ex1 q).\nauto.\nQed.\n\n\n\nLemma ex1p : ConvergentSequence.\nProof.\n  apply Build_ConvergentSequence with (Seq := seq_ex1) (Seqr := r_ex1) (Seqa := a_ex1).\n  apply ex1'.\nQed.\n\n\n\n", "meta": {"author": "ReidAtcheson", "repo": "constructive_analysis", "sha": "61ea291f4c36d209c45a433e167cb65bebb6cba5", "save_path": "github-repos/coq/ReidAtcheson-constructive_analysis", "path": "github-repos/coq/ReidAtcheson-constructive_analysis/constructive_analysis-61ea291f4c36d209c45a433e167cb65bebb6cba5/src/Sequence_example2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7512329828980872}}
{"text": "Require Import Classical.\n\nSection example0.\nVariables Q R S P: Prop.\nHypothesis p1: P->Q.\nHypothesis p2: ~Q.\nGoal ~P.\nProof.\n  unfold not in p2.\n  unfold not in |- *.\n  intros H1.\n  pose proof (p1 H1) as H2.\n  pose proof (p2 H2) as H3.\n  exact H3.\nQed.\n\nEnd example0.\n\nSection example1.\nVariables P Q R E: Prop.\nHypothesis p1: P/\\(Q \\/ R).\nHypothesis p2: P -> (~R).\nGoal Q\\/E.\nProof.\npose proof ( proj1 p1) as A1.\npose proof ( proj2 p1) as A2.\ndestruct A2 as [A3 | A3 ]. (*after destruc\n there will be two branches, so we shoulod\n give 2 name of them *)\nShow 2.\npose proof(or_introl(B:=E) A3) as A4.\nexact A4.\n pose proof (p2 A1) as B3.\nunfold not in B3.\npose proof (B3 A3) as B4.\ndestruct B4.\nQed.\nEnd example1.\n\n\n", "meta": {"author": "bodri5", "repo": "logic22", "sha": "b627d281715c0b947b48d91fc61d01e238720e00", "save_path": "github-repos/coq/bodri5-logic22", "path": "github-repos/coq/bodri5-logic22/logic22-b627d281715c0b947b48d91fc61d01e238720e00/example1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7512329790151272}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, ble_nat_false *)\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\nLemma S_n_le_O_false: forall n, ~ (S n <= 0).\nProof.\nintros. unfold not.\nintros. inversion H.\nQed.\n\n\nTheorem Sn_le_Sm_n_le_m: forall n m, S n <= S m -> n <= m.\n(* Already prooved in le_exercices *)\nAdmitted.\n\nTheorem ble_nat_false: forall n m, Nat.leb n m = false -> ~(n <= m).\nProof.\nintros. generalize dependent m. induction n as [|n'].\nintros. inversion H.\ndestruct m as [|m'].\nintros. apply S_n_le_O_false.\nintros. simpl in H. apply IHn' in H.\nunfold not. intros. apply Sn_le_Sm_n_le_m in H0. unfold not in H. apply H in H0.\ninversion H0.\nQed.", "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/ble_nat_false.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7512329789209831}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import ssralg.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nRequire Import GrupaPrzemiennaModulo.\n\nOpen Scope ring_scope.\nSection Wiezniowie.\n  (* W więzieniu jest n więźniów. Zakładamy, że n > 0 *)\n  Variable n' : nat.\n  Notation n := n'.+1.\n\n  (* Każdy więzień ma na czole liczbę od 0 do n (czyli spośród 'I_n) *)\n  Variable wiezniowie : n.-tuple 'I_n.\n\n  (* Postać rozwiązania to rodzina algorytmów.\n     Indeksem rodziny jest numer więźnia (0..N-1) - pierwszy argument.\n     Wejściem algorytmu są liczby widziane na czołach pozostałych (krotka n-1 liczb) - drugi argument.\n     Wyjściem algorytmu jest domniemana liczba na czole więźnia.\n   *)\n  Definition rozwiazanie := (* numer więźnia *) 'I_n ->\n                            (* liczby widziane u pozostałych *) n.-1.-tuple 'I_n ->\n                            (* domanimana liczba na swoim czole *) 'I_n.\n\n\n  (* Wycięcie więźnia w taki sposób to szczegół techniczny, można by to robić jakkolwiek inaczej, o ile byłby lemat o odwracalności (przywroc_pozostali) *)\n  Definition pozostali (lp: 'I_n): n.-1.-tuple 'I_n := [tuple of (behead (rot lp wiezniowie))].\n\n  (* Więzień zgadł, jeśli liczba na jego czole jest taka, jaką policzył jego algorytm *)\n  Definition zgadl (algorytm :rozwiazanie) (lp: 'I_n) :=\n    tnth wiezniowie lp == algorytm lp (pozostali lp).\n  Definition poprawne_rozwiazanie (algorytm :rozwiazanie): Prop := exists wiezien, zgadl algorytm wiezien.\n\n  (* Rozwiązanie zagadki - wyjaśnienie w \"rozwiazanie.md\" *)\n  (* Z taką definicją pracuje się łatwiej niż z: \\sum_(i <- liczby) i *)\n  Definition suma_modulo (liczby : seq 'I_n): 'I_n :=  foldr (fun a b => a + b) ord0 liczby.\n  Definition algorytm_wygrywajacy: rozwiazanie :=\n    fun lp pozostali => lp - (suma_modulo pozostali).\n\n  (* Poniżej są już tylko lematy przygotowujące do ostatecznego twierdzenia, że algorytm_wygrywajacy jest zawsze poprawnym rozwiązaniem *)\n  \n  \n  (* przywróć więźnia spowrotem do puli, po wycięciu go. Konstrukcja jest taka, aby łatwo było dowieźć lemat o odwracalności przywroc_pozostali  *)\n  Definition przywroc (lp : 'I_n) (pozostali: n.-1.-tuple 'I_n) : n.-tuple 'I_n :=\n    [tuple of rotr lp (thead [tuple of rot lp wiezniowie] :: pozostali)].\n\n  Lemma przywroc_pozostali  (lp :'I_n): przywroc lp (pozostali lp) = wiezniowie.\n    apply /eqP; rewrite /pozostali /przywroc /eq_op /=.\n    rewrite -[rotr lp [tuple of thead [tuple of rot lp wiezniowie] :: behead [tuple of rot lp wiezniowie]]]/_.\n    rewrite -tuple_eta rotK //.\n  Qed.\n\n  (* suma modulo jest rozdzielna ze względu na łączenie krotek *)\n  Lemma suma_modulo_plusplus s1 s2 : suma_modulo (s1 ++ s2) = (suma_modulo s1 + suma_modulo s2).\n  Proof.\n    by elim: s1 => /=; [rewrite GRing.add0r | move => x s1 ->; rewrite GRing.addrA].\n  Qed.\n\n  (* suma modulo jest taka sama dla wsystkich permutacji krotki *)\n  Lemma suma_modulo_perm p q: perm_eq p q -> suma_modulo p = suma_modulo q.\n    apply/catCA_perm_subst: p q => s1 s2 s3.\n    rewrite !suma_modulo_plusplus GRing.addrA [(_ s1) + (_ s2)]GRing.addrC GRing.addrA //.\n  Qed.\n\n  Lemma suma_modulo_cons s a : a + suma_modulo s = suma_modulo (a :: s). done. Qed.\n\n  (* jeśli dorzuci się liczbę na czole więźnia do sumy modulo pozostałych, to otrzyma się sumę modulo wszystkich *)\n  Lemma suma_modulo_pozostalych lp : suma_modulo wiezniowie = (tnth wiezniowie lp) + suma_modulo (pozostali lp).\n    rewrite -{1}(przywroc_pozostali lp) /przywroc /= suma_modulo_cons.\n    apply: suma_modulo_perm.\n    rewrite  perm_rot.\n    suff ->: thead [tuple of rot lp wiezniowie] = tnth wiezniowie lp by rewrite perm_cons perm_refl.\n    rewrite /rot /thead !(tnth_nth ord0) nth_cat.\n    case: ifP; [rewrite nth_drop addn0 |\n                (* (val 'I_n) będzie zawsze mniejsze niż (size_tuple n-tuple) *)\n                rewrite ltnNge leqn0 size_drop subn_eq0 size_tuple -leqNgt -[lp <= n']/(lp < n) ltn_ord];\n    done.\n  Qed.\n  \n  Lemma algorytm_wygrywajacy_jest_zawsze_poprawny: poprawne_rozwiazanie algorytm_wygrywajacy.\n  Proof.\n    rewrite /poprawne_rozwiazanie /algorytm_wygrywajacy /zgadl.\n    exists (suma_modulo wiezniowie).\n    rewrite {2}(suma_modulo_pozostalych (suma_modulo wiezniowie)).\n    rewrite  -GRing.addrA GRing.addrN GRing.addr0 //. \n  Qed.\nEnd Wiezniowie.\nClose Scope ring_scope.\n\n(* Tak dla pewności, powtórzenie tego samego poza sekcją *)\nLemma rozwiazanie_dziala_zawsze :\n  forall (n' : nat) (wiezniowie: (n'.+1).-tuple 'I_n'.+1),\n    poprawne_rozwiazanie wiezniowie (@algorytm_wygrywajacy n').\nProof. exact algorytm_wygrywajacy_jest_zawsze_poprawny. Qed.\n", "meta": {"author": "WojciechKarpiel", "repo": "wiezniowie", "sha": "dd59bb76ab181f4d5cf1637ec942cf9632348039", "save_path": "github-repos/coq/WojciechKarpiel-wiezniowie", "path": "github-repos/coq/WojciechKarpiel-wiezniowie/wiezniowie-dd59bb76ab181f4d5cf1637ec942cf9632348039/Wiezniowie.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7512329711079914}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export Tactics.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros.\n  split.\n  induction n.\n  reflexivity.\n  discriminate H.\n  induction m.\n  reflexivity.\n  assert (forall n m, n+ S m = S (n+m)).\n  induction n0.\n  reflexivity.\n  intros.\n  simpl.\n  rewrite IHn0.\n  reflexivity.\n  rewrite H0 in H.\n  discriminate H.\n  Qed.\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\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  apply and_exercise in H.\n  destruct H as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  apply HP. 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. split.\n  apply HP. apply HQ. apply HR. Qed.\n  \nLemma factor_is_O:\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  (* This pattern implicitly does case analysis on\n     n = 0 \\/ m = 0 *)\n  intros n m [Hn | Hm].\n  - (* Here, n = 0 *)\n    rewrite Hn. reflexivity.\n  - (* Here, m = 0 *)\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\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  (* WORKED IN CLASS *)\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_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra. Qed.\n  \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 H in H1.\n  apply H0 in H1.\n  destruct H1.\n  Qed.\n  \nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H.\n  apply H0 in H.\n  destruct H.\n  Qed.\n  \nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H. (* note implicit destruct b here *)\n  - (* b = true *)\n    unfold not in H.\n    exfalso. (* <=== *)\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n\n\nDefinition disc_fn (n: nat) : Prop :=\n  match n with\n  | O => True\n  | S _ => False\n  end.\n  \nTheorem disc : forall n, ~ (O = S n).\nProof.\n  intros n H1.\n  assert (H2 : disc_fn O). { simpl. apply I. }\n  rewrite H1 in H2. simpl in H2. apply H2.\nQed.\n\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\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  exact H.\n  destruct H.\n  left.\n  exact H.\n  destruct H.\n  right.\n  exact H0.\n  intros.\n  destruct H.\n  destruct H.\n  destruct H0.\n  left.\n  exact H.\n  left.\n  exact H.\n  destruct H0.\n  left.\n  exact H0.\n  right.\n  split .\n  exact H.\n   exact H0.\n   Qed.\n   \n   \nFrom Coq Require Import Setoids.Setoid.\n\nLemma mul_eq_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nintros n.\ninduction n.\ninduction m.\nsplit.\nleft.\nreflexivity.\nreflexivity.\nsplit.\nleft.\nreflexivity.\nreflexivity.\ninduction m.\nsplit.\nright.\nreflexivity.\nsimpl.\nassert (forall n, n*0=0).\ninduction n0.\nreflexivity.\nsimpl.\nexact IHn0.\nintros.\napply H.\nsplit.\nintros.\nsimpl in H.\ndiscriminate H.\nintros. destruct H.\ndiscriminate H.\ndiscriminate H.\nQed.\n\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\n\nLemma mul_eq_0_ternary :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mul_eq_0. rewrite mul_eq_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\nDefinition Even x := exists n : nat, x = double n.\nLemma four_is_even : Even 4.\nProof.\n  unfold Even. 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  (* 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) -> ~ (exists x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H0 as [x E] .\n  apply E in H.\n  destruct H.\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  destruct H.\n  destruct H.\n  left.\n  exists x.\n  exact H.\n  right.\n  exists x.\n  exact H.\n  intros.\n destruct H.\n destruct H.\n exists x.\n left.\n exact H.\n destruct H.\n exists x.\n right.\n exact H.\n Qed.\n Fixpoint 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  \nTheorem In_map :\n  forall (A B : Type) (f : A-> B) (l : list A) (x : A),\n         In x l->\n         In (f x) (map f l).\nProof.\n  intros A B f l x.\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\nTheorem In_map_iff :\n  forall (A B : Type) (f : A-> B) (l : list A) (y : B),\n         In y (map f l) <->\n         exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. split.\n  intros. induction l.\n  simpl in H.\n  destruct H.\n  simpl in H. destruct H.\n  exists x.\n  split.\n  apply H.\n  simpl.\n  left.\n  reflexivity.\n  apply IHl in H.\n  destruct H.\n  exists x0.\n  split.\n  destruct H.\n  exact H.\n  simpl.\n  right.\n  destruct H.\n  exact H0.\n  intros.\n  destruct H.\n  destruct H.\n  induction l.\n  simpl in H0.\n  destruct H0.\n  simpl.\n  \n  simpl in H0.\n  destruct H0.\n  left.\n  rewrite H0.\n  exact H.\n  apply IHl in H0.\n  right.\n  exact H0.\n  Qed.\n  Theorem 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  intros.\n  induction l'.\n  simpl.\n  split.\n  intros.\n  destruct H.\n  intros.\n  destruct H.\n  destruct H.\n  destruct H.\n  simpl.\n  split.\n  intros.\n  destruct H.\n  right. left. exact H.\n  right. right. exact H.\n  simpl in IHl'.\n  intros.\n  destruct H.\n  destruct H.\n  exact H.\n  intros.\n  split.\n  intros.\n  simpl in H.\n  destruct H.\n  left.\n  simpl.\n  left.\n  exact H.\n  rewrite IH in H.\n  destruct H.\n  left.\n  simpl.\n  right.\n  exact H.\n  right.\n  exact H.\n  intros.\n  destruct H.\n  simpl.\n  simpl in H.\n  destruct H.\n  left.\n  exact H.\n  right.\n  apply IH.\n  left.\n  exact H.\n  simpl.\n  right.\n  apply IH.\n  right.\n  exact H.\n  Qed.\n  \n Fixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n match l with\n  |nil => True\n  |x :: l => (P x) /\\ (All P l)\n end.\n Theorem 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  intros.\n  induction l.\n  exact I.\n  simpl.\n  split.\n  simpl in H.\n  apply H.\n  left.\n  reflexivity.\n  apply IHl.\n  intros.\n  apply H.\n  simpl.\n  right.\n  exact H0.\n  intros.\n  induction l.\n  destruct H0.\n  destruct H.\n  destruct H0.\n  rewrite H0 in H.\n  exact H.\n  apply IHl in H1.\n  exact H1.\n  exact H0.\n  Qed.\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.\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\nLemma append_comm: forall X (x y z: list X), x++y++z = (x++y)++z.\nintros X x. \ninduction x.\nreflexivity.\nsimpl.\nintros.\nrewrite IHx.\nreflexivity.\nQed.\nLemma con_one : forall X (x:X) y, [x] ++ y = x::y.\nintros.\ngeneralize dependent x.\ninduction y.\nreflexivity.\nintros.\nsimpl.\nreflexivity.\nQed.\nLemma lemma: forall X (x y:list X) , rev_append x y = (rev_append x []) ++ y.\nintros.\ngeneralize dependent y.\ninduction x.\nreflexivity.\nintros y.\nsimpl.\nrewrite IHx, IHx with [x].\nrewrite <- append_comm.\nrewrite con_one.\nreflexivity.\nQed.\n\n\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\nintros.\napply functional_extensionality.\nintros.\ninduction x.\nreflexivity.\nsimpl.\nunfold tr_rev.\nsimpl.\nunfold tr_rev in IHx.\nrewrite <- IHx.\nrewrite lemma.\nreflexivity.\nQed.\n\nLemma even_double : forall k, even (double k) = true.\nProof.\n  intros k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\n\nLemma even_double_conv : forall n, exists k,\n  n = if even n then double k else S (double k).\n  induction n.\n  exists 0.\n  reflexivity.\n  destruct IHn .\n  rewrite even_S.\n  destruct (even n).\n  exists x.\n  simpl.\n  rewrite H.\n  reflexivity.\n  exists (S x).\n  rewrite H.\n  reflexivity.\n  Qed.\n  \nTheorem even_bool_prop : forall n,\n  even n = true <-> Even n.\n  Proof.\n  split.\n  destruct (even_double_conv n) as [k Hk].\n  intros.\n  rewrite H in Hk.\n  exists k.\n  exact Hk.\n  intros [k Hk].\n  rewrite Hk.\n  apply even_double.\n  Qed.  \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. assert (forall n, n=? n = true).\n  induction n. reflexivity. simpl. rewrite IHn. reflexivity.\n  apply H0.\nQed.\n\n\nTheorem andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros.\n  split.\n  destruct b1, b2 .\n  split.\n  reflexivity.\n  reflexivity.\n  simpl.\n  intros.\n  destruct H.\n  split.\n  reflexivity.\n  reflexivity.\n  simpl.\n  intros.\n  destruct H.\n  split.\n  reflexivity.\n  reflexivity.\n  intros.\n  destruct H.\n  split.\n  reflexivity.\n  reflexivity.\n  intros.\n  destruct H.\n  rewrite H, H0.\n  reflexivity.\n  Qed.\nTheorem orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros.\n  split.\n  destruct b1, b2.\n  intros.\n  left.\n  reflexivity.\n  left.\n  reflexivity.\n  right.\n  reflexivity.\n  intros.\n  destruct H.\n  right.\n  reflexivity.\n  intros.\n  destruct H.\n  rewrite H.\n  reflexivity.\n  rewrite H.\n  destruct b1.\n  reflexivity.\n  reflexivity.\n  Qed.\n  \nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\nintros.\nsplit.\n  intros.\n  generalize dependent x.\n  induction y.\n  induction x.\n  intros.\n  simpl in H.\n  discriminate H.\n  intros.\n  destruct H.\n  induction x.\n  unfold not.\n  intros.\n  discriminate H.\n  unfold not.\n  intros.\n  discriminate H.\n  intros x.\n  induction x.\n  intros.\n  unfold not.\n  intros.\n  discriminate H0.\n  intros.\n  unfold not.\n  intros.\n  injection  H0.\n  intros.\n  simpl in H.\n  apply IHy in H.\n  unfold not in H.\n  apply H in H1.\n  apply H1.\n  intros.\n  unfold not in H.\n  generalize dependent y.\n   induction x.\n   induction y.\n   intros.\n   destruct H.\n   reflexivity.\n   intros. \n   reflexivity.\n   induction y. intros.\n   reflexivity.\n   intros.\n   simpl.\n   apply IHx.\n   intros.\n   assert (S x = S y).\n   rewrite H0.\n   reflexivity.\n   apply H in H1.\n   exact H1.\n   Qed.\n   \nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n                  (l1 l2 : list A) : bool:=\nmatch l1, l2 with\n| [], [] => true\n| _, [] => false\n| [], _ => false\n| h::t, h'::t' => if eqb h h' then eqb_list eqb t t' else false\nend.\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.\n    \nProof.\nintros.\ngeneralize dependent eqb .\ngeneralize dependent l2 .\ninduction l1.\nintros.\ninduction l2.\nsplit.\nreflexivity.\nreflexivity.\nsplit.\ndiscriminate.\nsimpl.\ndiscriminate.\ninduction l2.\nintros.\nsplit.\ndiscriminate.\ndiscriminate.\nintros.\nsplit.\nsimpl.\ndestruct (eqb x x0) eqn:K.\nintros. apply IHl1 in H0.\nrewrite H0. apply H in K.\nrewrite K.\nreflexivity.\nintros. apply H.\ndiscriminate.\nsimpl . destruct (eqb x x0) eqn:K.\nintros. apply IHl1. intros.\napply H.\ninjection H0.\nintros. exact H1.\nintros.\ninjection H0.\nintros. apply H in H2.\nrewrite K in H2.\ndiscriminate H2.\nQed.\nTheorem forallb_true_iff : forall X test (l : list X),\n  forallb test l = true <-> All (fun x => test x = true) l.\nProof.\nintros.\ngeneralize dependent test.\ninduction l.\nintros.\nsplit.\nreflexivity.\nreflexivity.\nintros.\nsplit.\nintros.\nsimpl.\nsplit.\nsimpl in H.\ndestruct (test x) eqn:K in H.\nexact K.\ndiscriminate H.\nsimpl in H.\ndestruct (test x) eqn:K in H.\napply IHl in H.\nexact H.\ndiscriminate H.\nintros.\nsimpl.\ndestruct (test x) eqn:K.\napply IHl.\nsimpl in H.\ndestruct H.\nexact H0.\nsimpl in H. destruct H.\nrewrite H in K.\ndiscriminate K.\nQed.\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\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H. \n  apply H.\n  right.\n  intros. destruct H.\n  left.\n  apply H0.\n  Qed.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/~ P.\nTheorem not_exists_dist :\n  excluded_middle ->\n  forall (X:Type) (P : X -> Prop),\n    ~ (exists x, ~ P x) -> (forall x, P x).\nProof.\nintros.\nunfold not in H0.\nunfold excluded_middle in H.\nassert (P x \\/ ~ (P x)).\napply H.\ndestruct H1.\nexact H1.\ndestruct H0.\nexists x.\nexact H1.\nQed.\n\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q) -> P) -> P.\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q:Prop,\n  (P -> Q) -> (~P \\/ Q).\n  \nTheorem thm1: excluded_middle  -> peirce .\nProof.\nintros.\nunfold excluded_middle in H.\nunfold peirce.\nintros.\nassert (P \\/ ~P).\napply H.\ndestruct H1.\nexact H1.\nunfold not in H1.\napply H0.\nintros.\napply H1 in H2.\ndestruct H2.\nQed.\n\n\nTheorem thm2: peirce  -> double_negation_elimination .\nunfold peirce.\nunfold double_negation_elimination.\nintros.\nunfold not in H0.\napply H with (Q:=False).\nintros.\napply H0 in H1.\ndestruct H1.\nQed.\n\n\nTheorem thm3: double_negation_elimination  -> de_morgan_not_and_not .\nProof.\nunfold double_negation_elimination.\nunfold de_morgan_not_and_not.\nintros.\nunfold not in H0.\nunfold not in H.\n\n\n\nassert (((P \\/ Q -> False) -> False) -> P \\/ Q).\napply H. \napply H1.\nintros.\nassert (forall P Q:Prop,((P -> False) /\\ (Q -> False) -> False)->((P \\/ Q -> False) -> False)).\nintros.\napply H3.\nsplit.\nintros.\nassert (P0 \\/ Q0).\nleft.\nexact H5.\napply H4 in H6.\nexact H6.\nintros.\nassert (P0\\/Q0).\nright.\nexact H5.\napply H4 in H6.\nexact H6.\napply H3 in H0.\nexact H0.\nexact H2.\nQed.\n\n\nTheorem thm4: de_morgan_not_and_not  -> implies_to_or .\nProof.\nunfold de_morgan_not_and_not.\nunfold implies_to_or.\nintros.\nassert(~ (~ ~P /\\ ~ Q) -> ~P \\/ Q).\napply H.\ndestruct H1.\nunfold not.\nintros.\ndestruct H1.\nassert (P->False).\nintros.\napply H0 in H3.\napply H2 in H3.\nexact H3.\napply H1 in H3.\nexact H3.\nleft.\napply H1.\nright.\napply H1.\nQed.\n\n\nTheorem thm5: implies_to_or  -> excluded_middle .\nProof.\nunfold implies_to_or.\nunfold excluded_middle.\nintros.\nassert((P -> P) -> ~ P \\/ P).\napply H.\nassert (P->P).\nintros.\nexact H1.\napply H0 in H1.\ndestruct H1.\nright.\nexact H1.\nleft.\nexact H1.\nQed.\n\n\n", "meta": {"author": "hei411", "repo": "software_foundations_coq", "sha": "49e302afc90941ef142cea64a910051e8d15749d", "save_path": "github-repos/coq/hei411-software_foundations_coq", "path": "github-repos/coq/hei411-software_foundations_coq/software_foundations_coq-49e302afc90941ef142cea64a910051e8d15749d/logical_foundations/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.8757869884059267, "lm_q1q2_score": 0.7512221486042526}}
{"text": "(* Comments in Coq are as in Ocaml and SML:  they start with a left-paren \n   and asterisk, and are closed with an asterisk and right-paren. *)\n\nRequire Import Arith.\n\n(* [Require Import Arith.] is a top-level command that tells Coq to import\n   the definitions from the [Arith] library (arithmetic) and to make the\n   definitions available at the top-level.  All top-level commands end\n   with a period.\n*)\n\n\nDefinition four : nat := 4.\n\n(* A top-level definition begins with the keyword [Definition], followed\n   by an identifier (in this case [four]) that we want to use, a colon,\n   a type, [:=], and then an expression followed by a period.  \n   Here the type of the number [4] is [nat] which stands for natural number.  *)\n\nDefinition four' := 2 + 2.\n(* You can leave off the type information and Coq can often infer it.  \n   But it can't always infer types, and it's good documentation to put\n   the types on complicated definitions. *)\n\nEval compute in four'.\nEval compute in four + four'.\n(* [Eval compute in <exp>.] lets you evaluate an expression to see the \n   resulting value and type. *)\n\nCheck four'.\n(* [Check <exp>] lets you check the type of an expression. *)\n\nPrint four'.\n(* [Print <identifier>] lets you see the definition of the identifier. *)\n\nDefinition four'' := (6 - 4) * 2.\n\nCheck four''.\nEval compute in four''.\nPrint four''.\n\nDefinition inc (x:nat) : nat := x + 1.\n(* To define a function, we just make a parameterized definition.*)\n\nCheck inc.\nEval compute in inc.\nEval compute in inc four.\n\nDefinition inc' x := x + 1.\n(* As in Ocaml, we can leave off the types and Coq can usually infer them,\n   but not always. *)\n\nCheck inc'.\nPrint inc'.\nEval compute in inc' four.\n\nDefinition inc'' := fun (x:nat) => x + 1.\n(* Parameterized definitions are just short-hand for a regular definition\n   using a lambda expression. *)\n\nCheck inc''.\nEval compute in inc'' four.\n\n\nDefinition add1 x y := x + y.\nDefinition add2 (x:nat) (y:nat) := x + y.\nDefinition add3 (x y:nat) := x + y.\n(* When the types are the same, we can group parameters as in [add']. *)\nDefinition add4 := fun x => fun y => x + y.\n(* Multiple parameters are just iterated lambdas. *)\n\nCheck add1.\nCheck add2.\nCheck add3.\nCheck add4.\nEval compute in add1 5 4.\nEval compute in add2 5 4.\n\nDefinition inc''' := add1 1.\nEval compute in inc'''.\nEval compute in inc''' 4.\n\nInductive bool : Type := \n| true \n| false.\n(* An inductive definition is just like an Ocaml datatype definition,\n   though the syntax is a little different.  Here, we are defining\n   a new [Type] called [bool] with constructors [true] and [false].\n   Unlike Ocaml, we can (and generally need to) provide the type of \n   each data constructor, hence both [true] and [false] are defined\n   as constructors that immediately return a [bool].  \n\n   Notice that when we evaluate this definition, Coq says that not\n   only is [bool] defined, but also [bool_rect], [bool_ind], and \n   [bool_rec].  We'll discuss those later on when we start talking\n   about proving things.\n*)\nCheck true.\nCheck false.\nPrint bool.\n\nDefinition negb (b:bool) : bool := \n  match b with \n    | true => false\n    | false => true \n  end.\n(* The definition above shows how we use pattern-matching to tear apart\n   an inductive type, in this case a [bool].  The syntax is similar to \n   Ocaml except that we use \"=>\" for the guard instead of \"->\" and we\n   have to put an \"end\" to terminate the \"match\". *)\n\nCheck negb.\nEval compute in negb true.\nEval compute in negb false.\n\nDefinition andb (b1 b2:bool) : bool := \n  match b1 with \n    | true => b2\n    | false => false\n  end.\n\nEval compute in andb true false.\nEval compute in andb true true.\n\nDefinition orb b1 b2 := \n  match b1 with\n    | true => true\n    | _ => b2\n  end.\n\nEval compute in orb true false.\nEval compute in orb true true.\n\n(* The [Arith] module defines this [nat] type already.  It is a way to\n   represent the natural numbers, with a base case of zero, \"0\" and \n   successor constructor [S]. Notice that the type of [S] declares\n   it to take a [nat] as an argument, before returning a [nat]. \n\nInductive nat : Type := \n  | O : nat\n  | S : nat -> nat.\n\ntype nat = O | S of nat\n*)\n\nPrint nat.\n\n(* \n   A digression:\n\n   In informal math, we tend to think of a \"type\" as a set of\n   objects.  For instance, we think of [nat] as the set of\n   objects {0,1,2,3,...}.  But we can also form sets out of\n   sets.  For instance, we can have {nat,bool,string}.  Technically,\n   to avoid circularities, [nat] is considered a \"small\" set,\n   and {nat,bool,string} is considered a \"large\" set, sometimes\n   called a class.  Stratifying our sets is necessary to avoid\n   constructions such as S = { s : set | s is not contained in s }\n   (Russell's paradox.)  \n\n   In Coq, the identifier [Set] refers to a universe of \n   types, including {nat,bool,string,...}.  So in some sense, \n   the identifier [Set] names a class of types.  We sometimes\n   say that [Set] is the type of the collection \n   {nat,bool,string,...}. When we build \n   certain kinds of new types out of elements of [Set], then we \n   have to move up to a new universe.  Internally, that universe\n   is called Type_1.  (Actually, [Set] is represented as Type_0\n   internally.)  And if we build certain types out of Type_1,\n   we have to move up to Type_2.  So Coq has an infinite hierarchy\n   Set a.k.a. Type_0, Type_1, Type_2, ...   \n\n   Now figuring out where in this hierarchy a definition should go\n   isn't that hard, and in fact, Coq automagically infers this\n   for you.  When you write [Type], you are really writing [Type_x]\n   and Coq is later solving for [x] to make sure your definitions\n   don't contain a circularity.  In fact, with the exception of\n   [Set] and one more very special universe, [Prop], you can't\n   even explicitly say at what level you want a given definition.\n   \n   For now, we can just ignore this and use [Type] everywhere.\n*)\nCheck O.\nCheck 0.   (* the numeral 0 is just notation for the constructor O *)\nEval compute in 0.\nEval compute in 3.\nCheck S.\nCheck S 0. (* 1,2,3 are short-hand for (S O), (S (S O)) and (S (S (S O))). *)\nCheck S (S (S 0)).\n\nDefinition is_zero (n:nat) : bool := \n  match n with \n    | 0 => true\n    | S _ => false\n  end.\n\nFixpoint add'' (n m:nat) : nat := \n  match m with \n    | 0 => n\n    | S m' => S (add'' n m')\n  end.\n(* We construct recursive functions by using the keyword \"Fixpoint\". *)\n\nEval compute in add'' 4 3.\nPrint add''.\n\nDefinition add5 :=\n  fix local_add (n m:nat) : nat := \n  match n with \n    | 0 => m\n    | S n' => S (local_add n' m)\n  end.\n(* Alternatively, we can use a \"fix\" expression which builds a recursive\n   functions, similar to the way \"fun\" builds a non-recursive function.\n*)\n\nEval compute in add5 4 3.\nPrint add5.\n\n(* Pairs *)\nDefinition p1 : nat * nat := (3,4).  (* pair of nats *)\nDefinition p2 : nat * bool := (3, true).  (* nat and bool *)\nDefinition p3 : nat * bool * nat := (3,true,2).\n\nEval compute in add3 (fst p1) (snd p1).  \n(* [fst] extracts the first component of a pair, and [snd]\n   extracts the second component. *)\n\nEval compute in fst p3.\nEval compute in snd p3.\n\nPrint pair.\nEval compute in match p1 with \n                  | pair x y => x + y\n                end.\nLocate \"_ * _\".\n\n(* Notice that [(3,true,2)] is really short-hand for [((3,true),2)]. \n   and [nat * bool * nat] is short for [(nat * bool) * nat]. *)\n\n(* Options *)\nDefinition opt1 : option nat := None.\nDefinition opt2 : option nat := Some 4.\n(* An [option t] is either [None] or [Some] applied to a value of type [t]. \n   Notice that unlike Ocaml, we write [option nat] instead of [nat option].\n*)\nPrint option.\n\nFixpoint subtract (m n:nat) : option nat := \n  match m, n with \n    | _, 0 => Some m\n    | 0, S _ => None\n    | S m', S n' => subtract m' n'\n  end.\nEval compute in subtract 5 2.\nEval compute in subtract 2 5.\n\nDefinition subt (m n:nat) : nat := \n  match subtract m n with \n    | None => 0\n    | Some i => i\n  end.\nEval compute in subt 5 2.\nEval compute in subt 2 5.\n\n(* Sums *)\nLocate \"_ + _\".\nPrint sum.\n\nDefinition s1 : nat + bool := inl 3.\nDefinition s2 : nat + bool := inr true.\n(* We build something of type [t1 + t2] by using either [inl] or \n   [inr].  It's important to provide Coq enough type information\n   that it can figure out what the other type is. *)\n\nDefinition add_nat_or_bool (s1 s2: nat + bool) : nat + bool := \n  match s1, s2 with \n    | inl n1, inl n2 => inl (n1 + n2)\n    | inr b1, inr b2 => inr (orb b1 b2)\n    | _, _ => inr false\n  end.\n\n(* Lists *)\nRequire Import List.\nPrint list.\nDefinition l1 : list nat := nil.\nDefinition l2 : list nat := 3::2::1::nil.\nDefinition l3 : list bool := true::false::nil.\nDefinition l4 : list (nat + bool) := (inl 3)::(inr true)::nil.\n\nFixpoint append (l1 l2:list nat) : list nat := \n  match l1 with \n    | nil => l2\n    | h::t => h::(append t l2)\n  end.\n\nEval compute in append l2 l2.\n\nFixpoint add_list (l1 l2:list nat) : option (list nat) := \n  match l1, l2 with \n    | nil, nil => Some nil\n    | n1::l1, n2::l2 => \n      match add_list l1 l2 with\n        | None => None\n        | Some l => Some ((n1+n2)::l)\n      end\n    | _, _ => None\n  end.\n\nEval compute in add_list l2 l2.\nEval compute in add_list l2 (1::nil).\n(* Polymorphism *)\n\nFixpoint generic_append (A:Type) (l1 l2: list A) : list A := \n  match l1 with \n    | nil => l2\n    | h::t => h::(generic_append A t l2)\n  end.\n(* Unlike Ocaml, we make type parameters explicit in Coq.  Here, \n   we've defined a generic append function, which abstracts over\n   a type [A].  Notice that the types of the arguments [l1] and\n   [l2] depend upon [A], as does the result type.  Notice also\n  that when we call this function, we must provide an actual\n  type for the instantiation of [A].\n*)\n\nEval compute in generic_append bool l3 l3.\nEval compute in generic_append nat l1 l2.\nEval compute in generic_append _ l3 l3.  \n(* Coq can usually figure out what the types are, and we can\n   leave out the type by just putting an underscore there \n   instead.  But there are cases where it can't figure it\n   out (e.g., generic_append _ nil nil).\n*)\n\nFixpoint generic_append' {A:Type} (l1 l2:list A) : list A := \n  match l1 with \n    | nil => l2\n    | h::t => h::(generic_append' t l2)\n  end.\n(* The curly braces tell Coq to make an argument implicit.  That\n   means it's up to Coq to fill in the argument for you.  Notice\n   that in the recursive call, we didn't have to specify the type. *)\n\nEval compute in generic_append' l1 l1.\nEval compute in generic_append' l2 l2.\nEval compute in generic_append' nil nil.\n\n(* This won't work though:\nDefinition foo := generic_append' nil nil.\n   We can fix it by either giving enough information in the context\n   or by using \"@\" to override the implicit arguments:\n*)\nDefinition foo : list nat := generic_append' nil nil.\nDefinition foo1 := @generic_append' nat nil nil.\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/notes/lecture1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.7512221482008429}}
{"text": "From LF Require Export induction.\nModule 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\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\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\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  intros.\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  simpl.\n  reflexivity.\nQed.\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)\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\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\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  | nil => nil\n  | 0 :: t => nonzeros t\n  | h :: t => h :: (nonzeros t)\n  end.\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 => if oddb h \n      then h :: oddmembers t\n      else oddmembers t\n  end.\n\nExample test_oddmembers:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat := \n  length (oddmembers l).\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, nil => nil\n  | h1 :: t1, nil => h1 :: t1\n  | nil, h2 :: t2 => h2 :: t2\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. 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\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with \n  | nil => 0\n  | h :: t => if eqb h v\n      then 1 + (count v t)\n      else count v t\n  end.\n\nExample test_count1: count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed. \n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. 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 := sum s [v].\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n   leb 1 (count v s).\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. reflexivity. Qed.\n\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil \n  | h :: t => if eqb 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. simpl. 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 => if eqb h v\n      then remove_all v t\n      else h :: remove_all v t\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nExample test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\nProof. reflexivity. Qed.\n\nExample test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\n  match s1 with\n  | nil => match s2 with \n           | nil => true\n           | h :: t => true\n           end\n  | h :: t => match s2 with \n              | nil => false\n              | h2 :: t2 =>\n                  if leb (count h s1) (count h s2) \n                  then subset t s2\n                  else false \n              end\n  end.\n\nExample test_subset1: subset [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_subset2: subset [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition manual_grade_for_bag_theorem : option (nat*string) := None.\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  - reflexivity.\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  - reflexivity.\n  - simpl. \n    rewrite -> IHl1'.\n    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    (* 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\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.\n    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  - reflexivity.\n  - simpl. \n    rewrite -> app_length, plus_comm.\n    simpl. \n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof. induction l as [| n l' IHl']. \n  - reflexivity.\n  - simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem concat_empty: forall 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: forall l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros l1 l2. \n  induction l1 as [| n l' IHl'].\n  - simpl. \n    rewrite -> concat_empty.\n    reflexivity.\n  - simpl. \n    rewrite -> IHl'.\n    rewrite -> app_assoc. \n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [| n l' IHl'].\n  - simpl. reflexivity.\n  - simpl. \n    rewrite -> rev_app_distr.\n    rewrite -> IHl'.\n    simpl. \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\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' IHl'].\n  - simpl.\n    reflexivity.\n  - destruct n as [| n' IHn']. \n    + simpl. \n      rewrite IHl'. \n      reflexivity.\n    + simpl.\n      rewrite IHl'.\n      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      if eqb h1 h2 \n      then eqblist t1 t2\n      else false\n  end.\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. simpl. reflexivity. Qed.\n\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\nProof. simpl. reflexivity. Qed.\n\n\nTheorem eqb_reflx : forall n: nat,\n  eqb n n = true.\nProof.\n  induction n as [| n' IHn']. \n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  induction l as [| n l' IHl']. \n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    rewrite -> eqb_reflx.\n    reflexivity.\nQed.\n    \nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  induction s as [| n s' IHs'].\n  - simpl. \n    reflexivity.\n  - simpl.\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  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHn'.\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  induction s as [| n s' IHs'].\n  - simpl. \n    reflexivity.\n  - destruct n as [| n'].    \n    + simpl. \n      rewrite -> leb_n_Sn.\n      reflexivity.\n    + simpl. \n      rewrite -> IHs'.\n      reflexivity.\nQed.\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\nDefinition manual_grade_for_rev_injective : option (nat*string) := None.\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.\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' => if n =? O \n      then Some a\n      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. 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\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  simpl.\n  induction l.\n  simpl.\n  reflexivity.\n  simpl.\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\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  intros .\n  destruct x.\n  simpl.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\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 :\n  forall (d : partial_map) (x : id) (v: nat),\n    find x (update d x v) = Some v.\nProof.\n  intros .\n  simpl.\n  rewrite <- eqb_id_refl.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n\nInductive baz : Type :=\n  | Baz1 (x : baz)\n  | Baz2 (y : baz) (b : bool).\n\nDefinition manual_grade_for_baz_num_elts : option (nat*string) := None.\n", "meta": {"author": "s3141p", "repo": "software-foundations", "sha": "a6eee47da487495fff2bba8b3ff7b5e330efe18e", "save_path": "github-repos/coq/s3141p-software-foundations", "path": "github-repos/coq/s3141p-software-foundations/software-foundations-a6eee47da487495fff2bba8b3ff7b5e330efe18e/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8757869965109764, "lm_q1q2_score": 0.7512221460035724}}
{"text": "\nStructure EstructuraDeMonoide\n            (C : Set)\n            (e : C)\n            (op : C -> C -> C) :=\n  mkEstructuraDeMonoide {\n    EM_assoc  : forall x y z,  op (op x y) z = op x (op y z) ;\n    EM_neut_l : forall x,      op e x = x ;\n    EM_neut_r : forall x,      op x e = x\n  }.\n\nStructure EstructuraDeGrupo\n            (C : Set)\n            (e : C)\n            (op : C -> C -> C)\n            (inv : C -> C) :=\n  mkEstructuraDeGrupo {\n    EG_monoide : EstructuraDeMonoide C e op ; \n    EG_inv_r   : forall x,      op x (inv x) = e\n  }.\n\nStructure Grupo := mkGrupo {\n  C   : Set ;           (* carrier *)\n  e   : C ;             (* elemento neutro *)\n  op  : C -> C -> C ;   (* operación binaria *)\n  inv : C -> C ;        (* inverso *)\n\n  es_grupo : EstructuraDeGrupo C e op inv\n}.\n\nDefinition carrier (G : Grupo) : Set := C G.\n\nSection Ejemplo_Grupo_ℤ2.\n  \n  Inductive ℤ2_carrier : Set :=\n    | O : ℤ2_carrier\n    | I : ℤ2_carrier.\n  \n  Let f (x : ℤ2_carrier) (y : ℤ2_carrier) : ℤ2_carrier :=\n    match x with\n    | O => y\n    | I => match y with\n           | O => I\n           | I => O\n           end\n    end.\n\n   Eval compute in (f (f O I) (f I I)).\n\n   (* f asociativa *)\n   Lemma ℤ2_G1 : forall a b c,  f (f a b) c = f a (f b c).\n     intros a b c.\n     case a; case b; case c; trivial.\n   Qed.\n   \n   (* O neutro a izquierda *)\n   Lemma ℤ2_G2 : forall a,  f O a = a.\n     trivial.\n   Qed.\n\n   (* O neutro a derecha *)\n   Lemma ℤ2_G3 : forall a,  f a O = a.\n     intros a.\n     case a; trivial.\n   Qed.\n\n   (* Cada elemento es inverso de sí mismo. *)\n   Lemma ℤ2_G4 : forall a,  f a a = O.\n     intros a.\n     case a; trivial.\n   Qed.\n   \n   Definition ℤ2 : Grupo :=\n     mkGrupo\n       ℤ2_carrier   (* carrier *)\n       O            (* elemento neutro *)\n       f            (* operación binaria *)\n       (fun x => x) (* inverso *)\n       (mkEstructuraDeGrupo _ _ _ _\n         (mkEstructuraDeMonoide _ _ _ ℤ2_G1 ℤ2_G2 ℤ2_G3)\n         ℤ2_G4).\n\nEnd Ejemplo_Grupo_ℤ2.\n\nNotation \"x · y\" := (op _ x y) (at level 20).\nNotation \"x ⁻¹\"  := (inv _ x) (at level 5).\nNotation \"1\"     := (e _).\n\nSection Propiedades_Básicas.\n\n    Variable G : Grupo.\n\n    Lemma assoc : forall x y z : carrier G,  (x · y) · z = x · (y · z).\n      intros.\n      apply (EM_assoc (carrier G) (e G) (op G)).\n      apply (EG_monoide (carrier G) (e G) (op G) (inv G)).\n      apply es_grupo.\n    Qed.\n\n    Lemma neut_l : forall x : carrier G,  1 · x = x.\n      intros.\n      apply (EM_neut_l (carrier G) (e G) (op G)).\n      apply (EG_monoide (carrier G) (e G) (op G) (inv G)).\n      apply es_grupo.\n    Qed.\n\n    Lemma neut_r : forall x : carrier G,  x · 1 = x.\n      intros.\n      apply (EM_neut_r (carrier G) (e G) (op G)).\n      apply (EG_monoide (carrier G) (e G) (op G) (inv G)).\n      apply es_grupo.\n    Qed.\n\n    Lemma inv_r : forall x : carrier G,  x · x⁻¹ = 1.\n      intros.\n      apply (EG_inv_r (carrier G) (e G) (op G) (inv G)).\n      apply es_grupo.\n    Qed.\n    \n    Lemma cancel_r :  forall x y z : carrier G,  x·z = y·z  ->  x = y.\n      intros x y z H.\n      assert ( x·(z·z⁻¹) = y·(z·z⁻¹) ) as H'.\n        rewrite <-? assoc.\n        rewrite H.\n        reflexivity.\n      rewrite inv_r, ? neut_r in H'.\n      assumption.\n    Qed.\n\n    Lemma inv_l : forall x : carrier G,  x⁻¹ · x = 1.\n      intros x.\n      apply cancel_r with (z := x⁻¹).\n      rewrite assoc, inv_r, neut_r, neut_l.\n      reflexivity.\n    Qed.\n\n    Lemma cancel_l : forall x y z : carrier G,  z·x = z·y  ->  x = y.\n      intros x y z H.\n      assert ( (z⁻¹·z)·x = (z⁻¹·z)·y ) as H'.\n        rewrite ? assoc, H; reflexivity.\n      rewrite inv_l, ? neut_l in H'.\n      assumption.\n    Qed.    \n\n    (* Inverso del neutro *)\n    Lemma inv_1 : 1⁻¹ = (1 : carrier G).\n      apply cancel_l with 1.\n      rewrite inv_r.\n      rewrite neut_r.\n      reflexivity.\n    Qed.\n\n    (* Inverso del producto *)\n    Lemma inv_xy : forall x y : carrier G,  (x · y)⁻¹ = y⁻¹ · x⁻¹.\n      intros x y.\n      apply cancel_l with (x · y).\n      rewrite inv_r, assoc. \n      replace (y·(y⁻¹·x⁻¹)) with ((y·y⁻¹)·x⁻¹). \n      rewrite inv_r, neut_l, inv_r.\n      reflexivity.\n      apply assoc.\n    Qed.\n\n    (* Inverso del inverso *)\n    Lemma inv_inv : forall x : carrier G, x⁻¹⁻¹ = x.\n      intro x.\n      apply cancel_l with x⁻¹.\n      rewrite inv_r.\n      rewrite inv_l.\n      reflexivity.\n    Qed.\n    \nEnd Propiedades_Básicas.\n\nSection Grupo_Simétrico.\n  \n  Require Import ProofIrrelevance.\n  Require Import FunctionalExtensionality.\n  Load Defs.\n\n  (* El grupo simétrico depende de un parámetro: un conjunto X *)\n  Variable X : Set.\n  \n  Let composición (f g : X -> X) := fun x => f (g x).\n\n  Let Id (x : X) := x.\n\n  Notation \"f ∘ g\" := (composición f g) (at level 20).\n  \n  Lemma composición_id :\n    forall f g,  f ∘ g = Id  ->  forall x,  f (g x) = x.\n  Proof.\n    intros f g H x.\n    apply equal_f with x in H.\n    compute in H.\n    assumption.\n  Qed.    \n\n  Let inversas (F G : X -> X) := F ∘ G = Id  /\\  G ∘ F = Id.\n\n  (* El siguiente va a ser el carrier del grupo simétrico.\n   * Sus elementos son tuplas de la forma (F, G, inv_FG)\n   * donde   F G : X -> X\n   *         inv_FG : inversas F G\n   * (inv_FG es evidencia de que F y G son inversas).   \n   *)\n  Structure Permutación := mkPerm {\n                             F      : X -> X ;\n                             G      : X -> X ;\n                             inv_FG : inversas F G\n                           }.\n\n  (* Lema técnico: toda permutación está determinada por F y G.\n   * Usa proof_irrelevance.\n   *)\n  Lemma perm_eq :\n    forall σ τ,\n      F σ = F τ  ->  G σ = G τ  ->  σ = τ.\n  Proof.\n    intros σ τ eq_F eq_G.\n    destruct σ as (F1, G1, inv1).\n    destruct τ as (F2, G2, inv2).\n    assert (F1 = F2) as Fs. assumption.\n    assert (G1 = G2) as Gs. assumption.\n    destruct Fs, Gs.\n    replace inv1 with inv2.\n    reflexivity.\n    apply proof_irrelevance.\n  Qed.\n\n  (* La operación del grupo simétrico es la composición. *)\n  Let sym_op (σ τ : Permutación) : Permutación.\n    apply mkPerm with (F := F σ ∘ F τ) (G := G τ ∘ G σ).\n    split.\n      (* F ∘ G *)\n      apply functional_extensionality.\n      intro x; unfold composición.\n      rewrite (composición_id (F τ) (G τ)).\n      rewrite (composición_id (F σ) (G σ)).\n      reflexivity.\n      apply (inv_FG σ).\n      apply (inv_FG τ).\n\n      (* G ∘ F *)\n      apply functional_extensionality.\n      intro x; unfold composición.\n      rewrite (composición_id (G σ) (F σ)).\n      rewrite (composición_id (G τ) (F τ)).\n      reflexivity.\n      apply (inv_FG τ).\n      apply (inv_FG σ).\n  Defined.\n\n  (* El elemento neutro es la identidad. *)\n  Let sym_e : Permutación.\n    apply mkPerm with (F := Id) (G := Id).\n    split; apply functional_extensionality; compute; reflexivity.\n  Defined.\n\n  (* La inversa de una permutación. *)\n  Let sym_inv (σ : Permutación) : Permutación.\n    destruct σ as (F, G, inv_FG).\n    apply mkPerm with (F := G) (G := F).\n    split.\n    apply inv_FG.\n    apply inv_FG.\n  Defined.\n\n  (* sym_op es asociativa *)\n  Lemma sym_G1 : forall σ τ ρ, sym_op (sym_op σ τ) ρ = sym_op σ (sym_op τ ρ).\n    intros σ τ ρ.\n    apply perm_eq.\n    reflexivity.\n    reflexivity.\n  Qed.\n  \n  (* sym_e neutro a izquierda *)\n  Lemma sym_G2 : forall σ, sym_op sym_e σ = σ.\n    intros.\n    apply perm_eq.\n    reflexivity.\n    reflexivity.\n  Qed.\n  \n  (* sym_e neutro a derecha *)\n  Lemma sym_G3 : forall σ, sym_op σ sym_e = σ.\n    intros.\n    apply perm_eq.\n    reflexivity.\n    reflexivity.\n  Qed.\n\n  (* sym_inv inversa a derecha *)\n  Lemma sym_G4 : forall σ, sym_op σ (sym_inv σ) = sym_e.\n    intros σ.\n    destruct σ as (F, G, inv_FG).\n    apply perm_eq.\n    simpl.\n    apply inv_FG.\n    apply inv_FG.\n  Qed.\n  \n  (* El grupo simétrico *)\n  Definition Sym : Grupo :=\n    mkGrupo\n       Permutación  (* carrier *)\n       sym_e        (* elemento neutro *)\n       sym_op       (* operación binaria *)\n       sym_inv      (* inverso *)\n       (mkEstructuraDeGrupo _ _ _ _\n         (mkEstructuraDeMonoide _ _ _ sym_G1 sym_G2 sym_G3)\n         sym_G4).\n\nEnd Grupo_Simétrico.\n\nNotation \"φ $ x\" := (π1 φ x) (at level 20).\n\nSection Morfismos.\n\n    Variable G H : Grupo.\n\n    Definition es_morfismo (f : carrier G -> carrier H) : Prop :=\n        (forall x y,  f (x · y) = f x · f y).\n\n    Definition Morfismo :=\n      { f : carrier G -> carrier H | es_morfismo f }.\n\n    Lemma morfismo_en_prod : forall φ : Morfismo, forall x y, φ $ (x · y) = (φ $ x) · (φ $ y).\n      intros.\n      apply (π2 φ).\n    Qed.\n\n    Lemma morfismo_en_1 : forall φ : Morfismo, φ $ 1 = 1.\n      intro φ.\n      assert ((φ $ 1) · (φ $ 1) = φ $ 1).\n      rewrite <- morfismo_en_prod.\n      rewrite neut_l.\n      reflexivity.\n      apply cancel_r with (φ $ 1).\n      rewrite neut_l.\n      assumption.\n    Qed.\n    \n    Lemma morfismo_en_inv : forall (φ : Morfismo) x, φ $ x⁻¹ = (φ $ x)⁻¹.\n    Proof.\n      intros φ x.\n      apply cancel_r with (φ $ x).\n      rewrite inv_l.\n      rewrite <- morfismo_en_prod.\n      rewrite inv_l.\n      apply morfismo_en_1.\n    Qed.\n    \n    Definition es_monomorfismo (f : carrier G -> carrier H) : Prop :=\n      es_morfismo f /\\\n      forall x y,  f x = f y  ->  x = y.\n\n    Lemma morfismo_eq : forall φ ψ : Morfismo, π1 φ = π1 ψ -> φ = ψ.\n    Proof.\n      intros φ ψ eq_π1.\n      destruct φ as (f, f_mor).\n      destruct ψ as (g, g_mor).\n      assert (f = g) as eq_fg. assumption.\n      destruct eq_fg.\n      replace g_mor with f_mor.\n      reflexivity.\n      apply proof_irrelevance.\n    Qed.\n\n    Lemma morf_equal : forall φ ψ : Morfismo, forall x, φ = ψ -> φ $ x = ψ $ x.\n      intros φ ψ x eq.\n      destruct eq.\n      reflexivity.\n    Qed.\n\n    Definition G_sub := { f : carrier G -> carrier H | es_monomorfismo f }.\n \nEnd Morfismos.\n\n(* ↪ == \\hookrightarrow *)\nNotation \"G ↪ H\" := (G_sub G H) (at level 20).\n\nDefinition Endomorfismo (G : Grupo) := Morfismo G G.\n\nSection Teorema_de_Cayley.\n\n  Variable G : Grupo.\n  \n  Let X := carrier G.\n\n  (* Dado un x, denota la permutación que multiplica a izquierda por x. *)\n  Definition μ (x : X) : Permutación X.\n    apply mkPerm with (F := fun y => x·y) (G := fun y => x⁻¹·y).\n    split.\n      (* F ∘ G = Id *)\n      apply functional_extensionality; intros y.\n      rewrite <- assoc.\n      rewrite inv_r.\n      rewrite neut_l.\n      reflexivity.\n      (* G ∘ F = Id *)\n      apply functional_extensionality; intros y.\n      rewrite <- assoc.\n      rewrite inv_l.\n      rewrite neut_l.\n      reflexivity.\n  Defined.\n  \n  (* μ es homomórfico para el producto *)\n  Lemma μ_hom_op : forall x y : X,  μ (x · y) = (μ x : carrier (Sym X)) · μ y.\n    intros x y.\n    apply perm_eq.\n    (* multiplicar por (x · y) *)\n    apply functional_extensionality.\n    intro z.\n    simpl.\n    apply assoc.\n\n    (* multiplicar por (x · y)⁻¹ *)\n    apply functional_extensionality.\n    intro z.\n    simpl.\n    rewrite inv_xy.\n    apply assoc.\n  Qed.\n\nEnd Teorema_de_Cayley.\n\nTheorem Cayley : forall G : Grupo, { X : Set & G ↪ Sym X }.\nProof.\n  intro G.\n  exists (carrier G).\n  exists (μ G).\n  split.\n\n  (* morfismo *)\n  unfold es_morfismo.\n  intros x y.\n  apply μ_hom_op.  (* homomórfico para el producto *)\n\n  (* monomorfismo *)\n  intros x y permx_eq_permy.\n  replace x with (F _ (μ G x) 1).\n  replace y with (F _ (μ G y) 1).\n  rewrite permx_eq_permy.\n  reflexivity.\n  simpl. apply neut_r.\n  simpl. apply neut_r.\nQed.\n\nDefinition es_abeliano (G : Grupo) := forall x y : carrier G, x · y = y · x.\n\nDefinition GrupoAbeliano := { G | es_abeliano G }.\n\nStructure Anillo := mkAnillo {\n  RC    : Set ;                           (* carrier *)\n\n  R0    : RC ;                            (* 0 *)\n  Radd  : RC -> RC -> RC ;                (* + *)\n  Ropp  : RC -> RC ;                      (* - *)\n\n  R1    : RC ;                            (* elemento neutro *)\n  Rmul  : RC -> RC -> RC ;                (* operación binaria *)\n\n  R_es_grupo_add    : EstructuraDeGrupo RC R0 Radd Ropp ;\n  R_comm            : forall x y : RC, Radd x y = Radd y x ;\n\n  R_es_monoide_mul  : EstructuraDeMonoide RC R1 Rmul ;\n\n  R_distr_l : forall x y z : RC, Rmul x (Radd y z) = Radd (Rmul x y) (Rmul x z) ;\n  R_distr_r : forall x y z : RC, Rmul (Radd y z) x = Radd (Rmul y x) (Rmul z x)\n}.\n\nDefinition R_carrier (A : Anillo) : Set := RC A.\n\nDefinition tiene_estructura_de_anillo (X : Set) := exists A : Anillo, R_carrier A = X.\n\nNotation \"x + y\" := (Radd _ x y).\nNotation \"x · y\" := (Rmul _ x y) (at level 20).\nNotation \"0\" := (R0 _).\nNotation \"1\" := (R1 _).\n\nSection Anillo_Propiedades_Basicas.\n\n  Variable A : Anillo.\n\n  Lemma R_mul_neut_l : forall x : R_carrier A,  1 · x = x.\n    intros.\n    apply (EM_neut_l _ _ _ (R_es_monoide_mul A)).\n  Qed.\n\n  Lemma R_mul_neut_r : forall x : R_carrier A,  x · 1 = x.\n    intros.\n    apply (EM_neut_r _ _ _ (R_es_monoide_mul A)).\n  Qed.\n\n  Lemma R_mul_assoc : forall x y z : R_carrier A,  (x · y) · z = x · (y · z).\n    intros.\n    apply (EM_assoc _ _ _ (R_es_monoide_mul A)).\n  Qed.\n                            \nEnd Anillo_Propiedades_Basicas.\n\nSection Anillo_Endomorfismos_Grupo_Abeliano.\n\n  Variable G : Grupo.\n\n  Hypothesis G_abeliano : es_abeliano G.\n  \n  Notation \"0\"     := (e G).\n  Notation \"x + y\" := (op G x y).\n  Notation \"- x\"   := (inv G x).\n  \n  (* Endomorfismo que manda todo al 1 del grupo *)\n  Definition end_0 : Endomorfismo G.\n    exists (fun x => 0).\n    unfold es_morfismo.\n    rewrite neut_r.\n    reflexivity.\n  Defined.\n\n  (* Operación entre endomorfismos que calcula la suma punto a punto *)\n  Definition end_add : Endomorfismo G -> Endomorfismo G -> Endomorfismo G.\n    intros φ ψ.\n    exists (fun x => (φ $ x) + (ψ $ x)).\n    unfold es_morfismo.\n    intros x y.\n    rewrite ? morfismo_en_prod.\n    apply cancel_l with (-φ $ x).\n    rewrite <-? assoc, ? inv_l, ? neut_l.\n    apply cancel_r with (-ψ $ y).\n    rewrite ->? assoc, ? inv_r, ? neut_r.\n    apply G_abeliano.\n  Defined.\n      \n  (* Operación que dado un endomorfismo devuelve su opuesto aditivo punto a punto  *)\n  Definition end_neg : Endomorfismo G -> Endomorfismo G.\n    intro φ.\n    exists (fun x => -φ $ x).\n    unfold es_morfismo.\n    intros.\n    rewrite ? morfismo_en_prod.\n    rewrite G_abeliano.\n    apply inv_xy.\n  Defined.\n  \n  Lemma end_add_assoc : forall α β γ : Endomorfismo G, end_add (end_add α β) γ = end_add α (end_add β γ).\n    intros. apply morfismo_eq. apply functional_extensionality.\n    intro. apply assoc.\n  Qed.\n\n  Lemma end_0_neut_l : forall φ : Endomorfismo G, end_add end_0 φ = φ.\n    intro. apply morfismo_eq. apply functional_extensionality.\n    intro. apply neut_l.\n  Qed.\n\n  Lemma end_0_neut_r : forall φ : Endomorfismo G, end_add φ end_0 = φ.\n    intro. apply morfismo_eq. apply functional_extensionality.\n    intro. apply neut_r.\n  Qed.\n\n  Lemma end_neg_inv_r : forall φ : Endomorfismo G, end_add φ (end_neg φ) = end_0.\n    intro. apply morfismo_eq. apply functional_extensionality.\n    intro. apply inv_r.\n  Qed.\n\n  Lemma end_add_comm : forall φ ψ : Endomorfismo G, end_add φ ψ = end_add ψ φ.\n    intros. apply morfismo_eq. apply functional_extensionality.\n    intro. apply G_abeliano.\n  Qed.\n\n  (* Endomorfismo identidad *)\n  Definition end_1 : Endomorfismo G.\n    exists (fun x => x).\n    unfold es_morfismo.\n    reflexivity.\n  Defined.\n\n  (* Producto de endomorfismos: la composición *)\n  Definition end_mul : Endomorfismo G -> Endomorfismo G -> Endomorfismo G.\n    intros φ ψ.\n    exists (fun x => φ $ (ψ $ x)).\n    unfold es_morfismo.\n    intros x y.\n    rewrite ? morfismo_en_prod.\n    reflexivity.\n  Defined.\n      \n  Lemma end_mul_assoc : forall α β γ, end_mul (end_mul α β) γ = end_mul α (end_mul β γ).\n    intros. apply morfismo_eq. apply functional_extensionality.\n    intro. reflexivity.\n  Qed.\n\n  Lemma end_1_neut_l : forall φ, end_mul end_1 φ = φ.\n    intro. apply morfismo_eq. apply functional_extensionality.\n    intro. reflexivity.\n  Qed.\n\n  Lemma end_1_neut_r : forall φ, end_mul φ end_1 = φ.\n    intro. apply morfismo_eq. apply functional_extensionality.\n    intro. reflexivity.\n  Qed.\n  \n  Lemma end_distr_l : forall α β γ, end_mul α (end_add β γ) = end_add (end_mul α β) (end_mul α γ).\n    intros. apply morfismo_eq. apply functional_extensionality.\n    intro.\n    simpl.\n    rewrite morfismo_en_prod. \n    reflexivity.\n  Qed.\n\n  Lemma end_distr_r : forall α β γ, end_mul (end_add β γ) α = end_add (end_mul β α) (end_mul γ α).\n    intros. apply morfismo_eq. apply functional_extensionality.\n    intro.\n    reflexivity.\n  Qed.\n  \n  Definition AnilloEndomorfismos :=\n    mkAnillo (Endomorfismo G)\n             end_0 end_add end_neg\n             end_1 end_mul\n             (mkEstructuraDeGrupo _ _ _ _\n                   (mkEstructuraDeMonoide _ _ _\n                     end_add_assoc end_0_neut_l end_0_neut_r)\n                   end_neg_inv_r)\n             end_add_comm\n             (mkEstructuraDeMonoide _ _ _\n                end_mul_assoc end_1_neut_l end_1_neut_r)\n             end_distr_l\n             end_distr_r.\n\n  Lemma G_abeliano_implica_End_anillo :\n          tiene_estructura_de_anillo (Endomorfismo G).\n  Proof.\n    exists AnilloEndomorfismos.\n    reflexivity.\n  Qed.\n  \nEnd Anillo_Endomorfismos_Grupo_Abeliano.\n\nSection Morfismo_Anillos.\n  \n  Variable A B : Anillo.\n\n  Definition es_R_morfismo (f : R_carrier A -> R_carrier B) : Prop :=\n       f 1 = 1\n    /\\ (forall x y,  f (x + y) = f x + f y)\n    /\\ (forall x y,  f (x · y) = f x · f y).\n\n  Definition es_R_monomorfismo (f : R_carrier A -> R_carrier B) : Prop :=\n       es_R_morfismo f\n    /\\ forall x y, f x = f y -> x = y.\n\n  Definition R_Morfismo :=\n    { f : R_carrier A -> R_carrier B | es_R_morfismo f }.\n\n  Lemma R_morfismo_eq :\n    forall φ ψ : R_Morfismo, π1 φ = π1 ψ -> φ = ψ.\n  Proof.\n    intros φ ψ eq.\n    destruct φ as (f, f_mor).\n    destruct ψ as (g, g_mor).\n    assert (f = g) as f_eq_g.\n    assumption.\n    destruct f_eq_g.\n    replace f_mor with g_mor.\n    reflexivity.\n    apply proof_irrelevance.\n  Qed.\n\n  Definition R_sub :=\n    { f : R_carrier A -> R_carrier B | es_R_monomorfismo f }.\n\nEnd Morfismo_Anillos.\n\nDefinition R_grupo_aditivo (A : Anillo) : Grupo :=\n  mkGrupo (R_carrier A) (R0 A) (Radd A) (Ropp A) (R_es_grupo_add A).\n\nDefinition R_grupo_ab_aditivo (A : Anillo) : GrupoAbeliano.\n  exists (R_grupo_aditivo A).\n  unfold es_abeliano.\n  intros.\n  apply (R_comm A).\nDefined.\n\n(** ↪ == \\hookrightarrow **)\nNotation \"A ↪ B\" := (R_sub A B) (at level 20).\n\nSection Pseudo_Cayley_Anillos.\n\n  Variable A : Anillo.\n  \n  Let G : GrupoAbeliano := R_grupo_ab_aditivo A.\n  Let Endo := AnilloEndomorfismos (π1 G) (π2 G).\n  \n  Definition Rμ (x : R_carrier A) : R_carrier Endo.\n    exists (fun y => Rmul _ x y).\n    intros y z.\n    apply (R_distr_l A).\n  Defined.\n\nEnd Pseudo_Cayley_Anillos.\n\nTheorem RCayley :\n  forall A : Anillo,\n    { G : GrupoAbeliano   &\n      A ↪ AnilloEndomorfismos (π1 G) (π2 G)\n    }.\nProof.\n  intro A.\n  exists (R_grupo_ab_aditivo A).\n  exists (Rμ A).\n  split.\n    (* morfismo de anillos *)\n    split.\n      (* 1 *)\n      apply morfismo_eq.\n      apply functional_extensionality.\n      intro.\n      simpl.\n      apply R_mul_neut_l.\n    split.\n      (* suma *)\n      intros x y.\n      apply morfismo_eq.\n      apply functional_extensionality.\n      intro z.\n      simpl.\n      apply R_distr_r.\n      (* producto *)\n      intros x y.\n      apply morfismo_eq.\n      apply functional_extensionality.\n      intro z.\n      simpl.\n      apply R_mul_assoc.\n\n    (* monomorfismo *)\n    intros x y Hmul.\n    assert (Rμ A x $ 1 = Rμ A y $ 1) as Hmul'.\n      apply morf_equal. assumption.\n    simpl in Hmul'.\n    rewrite ? R_mul_neut_r in Hmul'.\n    assumption.\nQed.\n\n", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/cayley/Cayley.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7512221370772373}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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) 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/goal33conj256_coqofml_Wazb6r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7512046833005532}}
{"text": "Require Import Shared.FiniteTypes.FinTypes.\nRequire Import Shared.Vectors.Vectors.\nRequire Import Shared.Vectors.VectorDupfree.\n\n\nDefinition Fin_initVect (n : nat) : Vector.t (Fin.t n) n :=\n  tabulate (fun i : Fin.t n => i).\n\nLemma Fin_initVect_dupfree n :\n  dupfree (Fin_initVect n).\nProof.\n  unfold Fin_initVect.\n  apply dupfree_tabulate_injective.\n  firstorder.\nQed.\n\nLemma Fin_initVect_full n k :\n  Vector.In k (Fin_initVect n).\nProof.\n  unfold Fin_initVect.\n  apply in_tabulate. eauto.\nQed.\n\nDefinition Fin_initVect_nth (n : nat) (k : Fin.t n) :\n  Vector.nth (Fin_initVect n) k = k.\nProof. unfold Fin_initVect. apply nth_tabulate. Qed.\n\nInstance Fin_finTypeC n : finTypeC (EqType (Fin.t n)).\nProof.\n  constructor 1 with (enum := Fin_initVect n).\n  intros x. cbn in x.\n  eapply dupfreeCount.\n  - eapply tolist_dupfree. apply Fin_initVect_dupfree.\n  - eapply tolist_In. apply Fin_initVect_full.\nQed.", "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/FiniteTypes/VectorFin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7512046816022672}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nRequire Import Reals Lra.\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import Rstruct.\nRequire Import Reals_ext ssrR Rbigop fdist proba.\n\n(* Coq/SSReflect/MathComp, Morikita, Sect. 7.2, using tuple *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope reals_ext_scope.\nLocal Open Scope tuple_ext_scope.\nLocal Open Scope R_scope.\n\nDefinition ps := [tuple 1/2; 1/3; 1/6].\nDefinition p : {ffun 'I_3 -> R} := [ffun i => tnth ps i].\n\nLemma p_nonneg : [forall a : 'I_3, 0 <b= p a].\nProof.\napply/forallP => a.\nrewrite /p ffunE.\napply/all_tnthP: a => /=.\nrewrite !andb_idr => * //; apply/leRP; lra.\nQed.\n\nDefinition p' : [finType of 'I_3] ->R+ := mkNNFinfun p_nonneg.\n\nLemma p_sum1 : \\sum_(i in 'I_3) p' i == 1.\nProof.\napply/eqP.\nrewrite 3!big_ord_recl big_ord0 /=.\nrewrite /p !ffunE !(tnth_nth 0) /=.\nby field.\nQed.\n\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\n\nDefinition P : {fdist 'I_3} := FDist.mk p_sum1.\n\nDefinition X : {RV P -> R} := (fun i => INR i.+1).\n\nLemma expected : `E X = 5/3.\nProof.\nrewrite /Ex.\nrewrite 3!big_ord_recl big_ord0 /=.\nrewrite /X !ffunE !(tnth_nth 0) /=.\ncbv; by field.\nQed.\n\nLemma variance : `V X = 5/9.\nProof.\nrewrite VarE expected /Ex /X /sq_RV /comp_RV /=.\nrewrite 3!big_ord_recl big_ord0 /=.\nrewrite !ffunE !(tnth_nth 0) /=.\ncbv; by field.\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/toy_examples/expected_value_variance_tuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7511651378352276}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import natural.\nRequire Import logic.\n\nDelimit Scope int_scope with int.\nOpen Scope int_scope.\n\nInductive int: Type :=\n| Z_pos: nat -> int\n| Z_neg: nat -> int.\n\nDefinition Z_plus (z w: int) :=\nmatch z, w with\n| Z_pos n, Z_pos m => Z_pos (n + m)\n| Z_pos n, Z_neg m => if m <? n then Z_pos (n - (S m)) else Z_neg (m - n)\n| Z_neg n, Z_pos m => if n <? m then Z_pos (m - (S n)) else Z_neg (n - m)\n| Z_neg n, Z_neg m => Z_neg (S n + m)\nend.\n\nNotation \"z '+' w\" := (Z_plus z w) (at level 50, left associativity) : int_scope.\nNotation \"z '+Z' w\" := (Z_plus z w) (at level 50, left associativity) : type_scope.\n\n(** negation of an integer: z |-> -z *)\nDefinition Z_opp (z: int): int :=\nmatch z with\n| Z_pos n => if n =? 0 then Z_pos 0 else Z_neg (pred n)\n| Z_neg n => Z_pos (S n)\nend.\n\nNotation \"'-' z\" := (Z_opp z) (at level 35, right associativity) : int_scope.\nNotation \"'-Z' z\" := (Z_opp z) (at level 35, right associativity) : type_scope.\n\n(** subtraction *)\nDefinition Z_minus (z w: int) := z + - w.\n\nNotation \"z '-' w\" := (Z_minus z w) (at level 50, left associativity) : int_scope.\nNotation \"z '-Z' w\" := (Z_minus z w) (at level 50, left associativity) : type_scope.\n\n(** multiplication *)\nDefinition Z_mult (z w: int): int :=\nmatch z, w with\n  | Z_pos n, Z_pos m => Z_pos (n * m)\n  | Z_pos n, Z_neg m => - Z_pos (n * (S m))\n  | Z_neg n, Z_pos m => - Z_pos ((S n) * m)\n  | Z_neg n, Z_neg m => Z_pos ((S n) * (S m))\nend.\n\nNotation \"z '*' w\" := (Z_mult z w) (at level 40, left associativity) : int_scope.\nNotation \"z '*Z' w\" := (Z_mult z w) (at level 40, left associativity) : type_scope.\n\n(** plus_assoc *)\nTheorem Z_1: forall x y z: int, (x + y) + z = x + (y + z).\nProof. destruct x, y, z.\n  (* CASE 1 *)\n  simpl. rewrite plus_assoc. reflexivity.\n\n  (* CASE 2 *)\n  simpl. remember (n1 <? n0) as b; destruct b; symmetry in Heqb.\n    (* n1 < n0 *)\n    rewrite N_ltb_true__lt in Heqb.\n    assert (n1 < n + n0) by omega.\n    rewrite <- N_ltb_true__lt in H.\n    rewrite H. unfold lt in Heqb.\n    apply (N_minus_plus n0 (S n1)) in Heqb.\n    remember (n0 - (S n1))%nat as k.\n    rewrite <- Heqb. repeat rewrite plus_assoc.\n    rewrite N_plus_minus.\n    reflexivity.\n\n    (* n1 >= n0 *)\n    rewrite N_ltb_false__ge in Heqb.\n    remember (n1 <? n + n0) as c; destruct c; symmetry in Heqc.\n      (* n1 < n + n0 *)\n      rewrite N_ltb_true__lt in Heqc.\n      apply N_minus_plus in Heqb.\n      remember (n1 - n0)%nat as k.\n      rewrite <- Heqb in Heqc; repeat rewrite (plus_comm _ n0) in Heqc.\n      rewrite <- N_cons_lt_plus in Heqc.\n      rewrite <- N_ltb_true__lt in Heqc.\n      rewrite Heqc. rewrite <- Heqb.\n      assert (Tmp: S (k + n0)%nat = (n0 + (S k))%nat) by omega.\n      rewrite Tmp. rewrite <- N_minus_distr, N_plus_minus. reflexivity.\n\n      (* n1 >= n + n0 *)\n      rewrite N_ltb_false__ge in Heqc.\n      apply N_minus_plus in Heqb.\n      remember (n1 - n0)%nat as k.\n      rewrite <- Heqb in Heqc; repeat rewrite (plus_comm _ n0) in Heqc.\n      unfold ge in Heqc. rewrite <- N_cons_le_plus in Heqc.\n      rewrite N_le__ge, <- N_ltb_false__ge in Heqc.\n      rewrite Heqc, <- Heqb.\n      rewrite (plus_comm n n0), <- N_minus_distr, N_plus_minus. reflexivity.\n\n  (* CASE 3 *)\n  simpl. remember (n0 <? n) as b; remember (n0 <? n1) as c;\n  destruct b, c; symmetry in Heqb, Heqc.\n    (* n0 < n /\\ n0 < n1 *)\n    rewrite N_ltb_true__lt in Heqb, Heqc.\n    unfold lt in Heqb, Heqc. unfold Z_plus.\n    rewrite (plus_comm _ n1). rewrite <- N_plus_minus_diff.\n    rewrite (plus_comm n1 n). rewrite N_plus_minus_diff. reflexivity.\n    apply Heqc. apply Heqb.\n\n    (* n0 < n /\\ n0 >= n1 *)\n    rewrite N_ltb_true__lt in Heqb; rewrite N_ltb_false__ge in Heqc.\n    unfold Z_plus. assert (n0 - n1 < n) by omega. rewrite <- N_ltb_true__lt in H.\n    rewrite H. assert (S (n0 - n1) = ((S n0) - n1)%nat) by omega.\n    rewrite H0. rewrite N_minus_plus_distr. reflexivity.\n    apply Heqb. apply le_S. apply Heqc.\n\n    (* n0 >= n /\\ n0 < n1 *)\n    unfold Z_plus.\n    rewrite N_ltb_true__lt in Heqc.\n    rewrite N_ltb_false__ge in Heqb.\n    assert (n0 - n < n1) by omega.\n    rewrite <- N_ltb_true__lt in H.\n    rewrite H. assert (S (n0 - n) = ((S n0) - n)%nat) by omega.\n    rewrite H0. rewrite <- N_minus_plus_distr. rewrite plus_comm. reflexivity.\n    apply Heqc. apply le_S; apply Heqb.\n\n    (* n0 >= n /\\ n0 >= n1 *)\n    remember (n0 - n1 <? n) as d; destruct d; symmetry in Heqd; unfold Z_plus;\n    rewrite N_ltb_false__ge in Heqb, Heqc.\n      (* n0 >= n /\\ n0 >= n1 /\\ n0 - n1 < n *)\n      rewrite N_ltb_true__lt in Heqd.\n      assert (n0 - n < n1) by omega.\n      rewrite <- N_ltb_true__lt in H.\n      rewrite H.\n      assert (forall a b: nat, a >= b -> S (a - b)%nat = ((S a) - b)%nat) by (intros; omega).\n      repeat rewrite H0.\n      rewrite <- N_plus_minus_distr.\n      rewrite <- N_plus_minus_distr.\n      pose proof ((N_minus_plus n0 n1) Heqc) as PM.\n      pose proof ((N_minus_plus n0 n) Heqb) as PM1.\n      rewrite (plus_comm n1 n). reflexivity.\n      omega. omega. omega. omega. omega. omega.\n\n      (* n0 >= n /\\ n0 >= n1 /\\ n0 - n1 >= n *)\n      rewrite N_ltb_false__ge in Heqd.\n      assert (n0 - n >= n1) by omega.\n      rewrite <- N_ltb_false__ge in H.\n      rewrite H.\n      repeat rewrite N_minus_distr.\n      rewrite (plus_comm n n1). reflexivity.\n\n  (* CASE 4 *)\n  simpl. remember (n0 <? n) as b; destruct b; simpl; unfold Z_plus; symmetry in Heqb.\n    (* n0 < n *)\n    rewrite N_ltb_true__lt in Heqb.\n    remember (S (n0 + n1) <? n) as c; destruct c; simpl; symmetry in Heqc.\n      (* n0 < n /\\ S (n0 + n1) < n *)\n      rewrite N_ltb_true__lt in Heqc.\n      assert (n1 < n - S n0) by omega.\n      rewrite <- N_ltb_true__lt in H.\n      rewrite H.\n      rewrite N_minus_distr.\n      rewrite <- plus_n_Sm. reflexivity.\n\n      (* n0 < n /\\ S (n0 + n1) >= n *)\n      rewrite N_ltb_false__ge in Heqc.\n      assert (n1 >= n - S n0) by omega.\n      rewrite <- N_ltb_false__ge in H.\n      rewrite H.\n      destruct n. inversion Heqb.\n      assert ((S n - S n0)%nat = (n - n0)%nat) by omega.\n      rewrite H0. repeat rewrite <- N_plus_minus_distr.\n      rewrite (plus_comm n1 n0). reflexivity.\n      omega. omega.\n\n    (* n0 >= n *)\n    rewrite N_ltb_false__ge in Heqb.\n    assert (S (n0 + n1) >= n) by omega.\n    rewrite <- N_ltb_false__ge in H.\n    rewrite H.\n    destruct n. assert ((n0 - 0)%nat = n0) by omega. rewrite H0. reflexivity.\n    assert (S (n0 - S n + n1) = (n0 + n1 - n)%nat).\n      apply (N_minus_plus n0 (S n)) in Heqb.\n      remember ((n0 - S n)%nat) as k.\n      rewrite <- Heqb.\n      rewrite <- plus_assoc.\n      rewrite (plus_comm (S n)).\n      rewrite plus_assoc.\n      assert ((k + n1 + S n - n)%nat = S(k + n1)) by omega.\n      rewrite H0. reflexivity.\n    rewrite H0. reflexivity.\n\n  (* CASE 5 *)\n  simpl. remember (n <? n0) as b; destruct b; simpl; unfold Z_plus; symmetry in Heqb.\n    (* n < n0 *)\n    rewrite N_ltb_true__lt in Heqb.\n    assert (n < n0 + n1) by omega.\n    rewrite <- N_ltb_true__lt in H.\n    rewrite H.\n    rewrite (plus_comm n0 n1).\n    rewrite N_plus_minus_diff.\n    rewrite (plus_comm n1 _).\n    reflexivity.\n    apply Heqb.\n\n    (* n >= n0 *)\n    remember (n <? n0 + n1) as c; destruct c; simpl; symmetry in Heqc;\n    rewrite N_ltb_false__ge in Heqb.\n      (* n >= n0 /\\ n < n0 + n1 *)\n      rewrite N_ltb_true__lt in Heqc.\n      assert (n - n0 < n1) by omega.\n      rewrite <- N_ltb_true__lt in H.\n      rewrite H.\n      assert (S (n - n0) = (S n - n0)%nat) by omega.\n      rewrite H0.\n      rewrite <- N_plus_minus_distr.\n      rewrite plus_comm.\n      reflexivity.\n      unfold ge; rewrite plus_comm.\n      apply Heqc.\n      apply le_S, Heqb.\n\n      (* n >= n0 /\\ n < n0 + n1 *)\n      rewrite N_ltb_false__ge in Heqc.\n      assert (n - n0 >= n1) by omega.\n      rewrite <- N_ltb_false__ge in H.\n      rewrite H.\n      rewrite N_minus_distr.\n      reflexivity.\n\n  (* CASE 6 *)\n  simpl. remember (n <? n0) as b; remember (n1 <? n0) as c;\n  destruct b, c; symmetry in Heqb, Heqc.\n    (* n < n0 /\\ n1 < n0 *)\n    rewrite N_ltb_true__lt in Heqb, Heqc.\n    unfold lt in Heqb, Heqc. unfold Z_plus.\n    remember (n1 <? n0 - S n) as d; destruct d; symmetry in Heqd; unfold Z_plus.\n      (* n < n0 /\\ n1 < n0 /\\ n1 < n0 - S n *)\n      rewrite N_ltb_true__lt in Heqd.\n      assert (n < n0 - S n1) by omega.\n      rewrite <- N_ltb_true__lt in H.\n      rewrite H.\n      repeat rewrite N_minus_distr.\n      rewrite plus_comm. reflexivity.\n\n      (* n < n0 /\\ n1 < n0 /\\ n1 >= n0 - S n *)\n      rewrite N_ltb_false__ge in Heqd.\n      assert (n >= n0 - S n1) by omega.\n      rewrite <- N_ltb_false__ge in H.\n      rewrite H.\n      repeat rewrite <- N_plus_minus_distr.\n      assert ((n1 + S n)%nat = (n + S n1)%nat) by omega.\n      rewrite H0. reflexivity.\n      omega. omega. omega. omega.\n\n    (* n < n0 /\\ n1 >= n0 *)\n    rewrite N_ltb_true__lt in Heqb; rewrite N_ltb_false__ge in Heqc.\n    unfold Z_plus. assert (n1 >= n0 - S n) by omega. rewrite <- N_ltb_false__ge in H.\n    rewrite H.\n    repeat rewrite <- N_plus_minus_distr.\n    rewrite plus_comm. rewrite N_plus_minus_diff. reflexivity.\n    omega. omega. omega.\n\n    (* n >= n0 /\\ n1 < n0 *)\n    rewrite N_ltb_true__lt in Heqc.\n    rewrite N_ltb_false__ge in Heqb.\n    unfold Z_plus.\n    assert (n >= n0 - S n1) by omega.\n    rewrite <- N_ltb_false__ge in H.\n    rewrite H. simpl. rewrite plus_n_Sm.\n    rewrite <- N_minus_plus_distr. reflexivity.\n    omega. omega.\n\n    (* n >= n0 /\\ n1 >= n0 *)\n    unfold Z_plus; rewrite N_ltb_false__ge in Heqb, Heqc.\n    assert ((S (n - n0) + n1)%nat = (S (n + (n1 - n0)))%nat) by omega.\n    rewrite H. reflexivity.\n\n  (* CASE 7 *)\n  simpl. remember (S (n + n0) <? n1) as b; destruct b; symmetry in Heqb.\n    (* S (n + n0) < n1 *)\n    rewrite N_ltb_true__lt in Heqb.\n    assert (n0 < n1) by omega.\n    rewrite <- N_ltb_true__lt in H.\n    rewrite H.\n    assert (n < n1 - S n0) by omega.\n    rewrite <- N_ltb_true__lt in H0.\n    rewrite H0.\n    rewrite N_minus_distr.\n    rewrite plus_comm, plus_n_Sm.\n    reflexivity.\n\n    (* S (n + n0) >= n1 *)\n    rewrite N_ltb_false__ge in Heqb.\n    assert (n >= n1 - S n0) by omega.\n    rewrite <- N_ltb_false__ge in H.\n    remember (n0 <? n1) as c; destruct c; symmetry in Heqc.\n      (* S (n + n0) >= n1 /\\ n0 < n1 *)\n      rewrite N_ltb_true__lt in Heqc.\n      rewrite H.\n      destruct n1.\n      inversion Heqc.\n      assert ((S n1 - S n0)%nat = (n1 - n0)%nat) by omega.\n      rewrite H0; clear H0.\n      rewrite <- N_plus_minus_distr.\n      reflexivity.\n      omega. omega.\n\n      (* S (n + n0) >= n1 /\\ n0 >= n1 *)\n      rewrite N_ltb_false__ge in Heqc.\n      destruct n1. assert ((n0 - 0)%nat = n0) by omega.\n      rewrite H0. reflexivity.\n      assert ((n + n0 - n1)%nat = (S n + n0 - S n1)%nat) by omega.\n      rewrite H0. rewrite N_plus_minus_diff. reflexivity. omega.\n\n  (* CASE 8 *)\n  simpl. rewrite <- plus_assoc, (plus_n_Sm n). reflexivity.\nQed.\n\n(** plus_comm *)\nTheorem Z_2: forall x y: int, x + y = y + x.\nProof. destruct x, y.\n  - simpl. rewrite (plus_comm n n0). reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite (plus_comm n n0). reflexivity.\nQed.\n\n(** zero as an identity for plus *)\nTheorem Z_3: forall x: int, x + Z_pos 0 = x.\nProof. destruct x.\n  - simpl. rewrite plus_0_r. reflexivity.\n  - simpl. assert ((n - 0)%nat%nat = n) by omega. rewrite H. reflexivity.\nQed.\n\n(** inverse element for plus *)\nTheorem Z_4: forall x: int, x + - x = Z_pos 0.\nProof. destruct x.\n  - destruct n.\n    + simpl. reflexivity.\n    + simpl. assert (n < S n) by omega. rewrite <- N_ltb_true__lt in H.\n      rewrite H. assert ((n - n)%nat%nat = 0) by omega. rewrite H0. reflexivity.\n  - simpl. assert (n < S n) by omega. rewrite <- N_ltb_true__lt in H.\n    rewrite H. assert ((n - n)%nat%nat = 0) by omega. rewrite H0. reflexivity.\nQed.\n\n(** mult_assoc *)\nTheorem Z_5: forall x y z: int, (x * y) * z = x * (y * z).\nProof.\n  assert (L: forall n n0 n1: nat, (n1 + (n0 + n * S n0) * S n1)%nat\n          = (n1 + n0 * S n1 + n * S (n1 + n0 * S n1))%nat).\n    intros; simpl. assert (S (n1 + n0 * S n1) = ((S n0) * (S n1))%nat) by reflexivity.\n    rewrite H. rewrite mult_plus_distr_r, plus_assoc, mult_assoc. reflexivity.\n\n  destruct x, y, z; simpl.\n  - rewrite mult_assoc. reflexivity.\n  - destruct n0. zero.\n    destruct n. zero. simpl.\n    rewrite mult_plus_distr_r, <- mult_assoc, plus_assoc.\n    reflexivity.\n  - destruct n. zero. destruct (n1 + n0 * n1 =? 0); reflexivity.\n    assert (((S n * S n0)%nat =? 0) = false) by reflexivity.\n    rewrite H. destruct n1.\n      zero. simpl. zero. simpl. rewrite <- L. reflexivity.\n  - destruct n. zero. simpl. rewrite <- L. reflexivity.\n  - destruct n0. zero.\n    simpl. destruct n1. zero. simpl. rewrite L. reflexivity.\n  - destruct n0. zero. simpl. rewrite L. reflexivity.\n  - destruct n1. zero. simpl. zero. simpl. rewrite L. reflexivity.\n  - rewrite L. reflexivity.\nQed.\n\n(** mult_comm *)\nTheorem Z_6: forall x y: int, x * y = y * x.\nProof. destruct x, y; simpl.\n  - rewrite mult_comm. reflexivity.\n  - destruct n. zero. rewrite (mult_comm (S n)). reflexivity.\n  - destruct n0. zero. rewrite (mult_comm (S n0)). reflexivity.\n  - assert (forall a b: nat, S (b + a * S b) = ((S a) * (S b))%nat) by reflexivity.\n    repeat rewrite H. rewrite mult_comm. reflexivity.\nQed.\n\n(** one as an identity for mult *)\nTheorem Z_7: forall x: int, x * Z_pos 1 = x.\nProof. destruct x; simpl; assert ((n * 1)%nat = n%nat) by omega; rewrite H; reflexivity. Qed.\n\n(** left distribution law *)\nTheorem Z_8: forall x y z: int, x * (y + z) = x * y + x * z.\nProof. destruct x, y, z; simpl.\n  - rewrite mult_plus_distr_l. reflexivity.\n  - destruct n. zero. destruct (n1 <? n0); zero.\n    simpl. assert (forall a b: nat, (b + a * b)%nat = ((S a) * b)%nat) by reflexivity.\n    repeat rewrite H.\n    assert ((n1 + n * S n1 <? S n * n0) = ((S n) * (S n1) <=? S n * n0)) by reflexivity.\n    rewrite H0.\n    pose proof (N_cons_le_mult_pos (S n) (S n1) n0) as F.\n    assert (F1: S n > 0) by omega. apply F in F1.\n    repeat rewrite <- N_leb_true__le in F1.\n    remember (S n * S n1 <=? S n * n0) as b; destruct b.\n    assert ((S n1 <=? n0) = true) by (rewrite F1; reflexivity).\n    unfold Nat.ltb. rewrite H1. remember ((n0 - S n1)%nat) as k.\n    rewrite H. assert (S (n1 + n * S n1) = ((S n) * (S n1))%nat).\n      rewrite <- H. reflexivity.\n    rewrite H2. rewrite <- (N_minus_plus n0 (S n1)).\n    rewrite <- Heqk. rewrite mult_plus_distr_l.\n    rewrite N_plus_minus. reflexivity. rewrite N_leb_true__le in H1. apply H1.\n    assert ((S n1 <=? n0) = false).\n      rewrite N_leb_true__le in F1.\n      rewrite N_le__ge in F1.\n      assert (false = true -> False) by discriminate.\n      assert (n0 < S n1). rewrite N_lt__gt, <- N_nle__gt.\n      pose proof (contrapositive (n0 >= S n1) (false = true)) as P.\n      destruct F1.\n      apply P in H2. apply H2. unfold not. apply H1.\n      rewrite N_leb_false__gt. unfold gt. apply H2.\n    rewrite N_leb_false__gt in H1. assert (n1 >= n0) by omega.\n    rewrite <- N_ltb_false__ge in H2. rewrite H2.\n    rewrite N_ltb_false__ge in H2. remember ((n1 - n0)%nat) as k.\n    rewrite <- (N_minus_plus n1 n0). rewrite <- Heqk.\n    assert (S (k + n0) = (S k + n0)%nat) by reflexivity.\n    rewrite H3, mult_plus_distr_l.\n    assert ((k + n0 + (n * S k + n * n0))%nat = (k + n * S k + (n0 + n * n0))%nat) by omega.\n    rewrite H4. simpl. rewrite N_plus_minus. reflexivity. apply H2.\n\n\nAdmitted.\n\n(** Z is an integral domain *)\nTheorem Z_9: forall x y: int, x * y = Z_pos 0 -> x = Z_pos 0 \\/ y = Z_pos 0.\nProof. Admitted.\n\n(** natural order for Z *)\nDefinition Z_leb (z w: int): bool := (** x <=? y iff *)\nmatch z, w with\n  | Z_pos n, Z_pos m => n <=? m\n  | Z_pos n, Z_neg m => false\n  | Z_neg n, Z_pos m => true\n  | Z_neg n, Z_neg m => m <=? n\nend.\n\n\nNotation \"z '<=?Z' w\" := (Z_leb z w) (at level 70, no associativity) : type_scope.\nNotation \"z '<?Z' w\" := (negb Z_leb w z) (at level 70, no associativity) : type_scope.\nNotation \"z '>=?Z' w\" := (Z_leb w z) (at level 70, no associativity) : type_scope.\nNotation \"z '>?Z' w\" := (negb Z_leb z w) (at level 70, no associativity) : type_scope.\n\nDefinition Z_le (z w: int): Prop := (** x <=? y iff *)\nmatch z, w with\n  | Z_pos n, Z_pos m => n <= m\n  | Z_pos n, Z_neg m => False\n  | Z_neg n, Z_pos m => True\n  | Z_neg n, Z_neg m => m <= n\nend.\n\nNotation \"z '<=Z' w\" := (Z_le z w) (at level 70, no associativity) : type_scope.\nNotation \"z '<Z' w\" := (~ Z_le w z) (at level 70, no associativity) : type_scope.\nNotation \"z '>=Z' w\" := (Z_le w z) (at level 70, no associativity) : type_scope.\nNotation \"z '>Z' w\" := (~ Z_le z w) (at level 70, no associativity) : type_scope.\n\nLemma Z_neg_diff__lt: forall x y: int, x - y <Z Z_pos 0 <-> x <Z y.\nProof. assert (N: (0 =? 0) = true) by reflexivity.\n  intros. destruct x, y; split; intros; unfold Z_le; simpl; simpl in H.\n  - destruct n0. rewrite N in H.\n    rewrite N_nle__gt in H. inversion H.\n    assert ((S n0 =? 0) = false) by reflexivity. rewrite H0 in H. simpl in H.\n    remember (n0 <? n) as b; destruct b.\n    omega. symmetry in Heqb; rewrite N_ltb_false__ge in Heqb. omega.\n  - destruct n0. rewrite N_nle__gt in H; inversion H.\n    rewrite N_nle__gt in H. simpl. assert (n0 >= n) by omega.\n    rewrite <- N_ltb_false__ge in H0. rewrite H0. easy.\n  - rewrite N_nle__gt in H; inversion H.\n  - easy.\n  - easy.\n  - destruct n0; simpl; apply H.\n  - unfold not; intros. assert (n < S n0) by omega.\n    rewrite <- N_ltb_true__lt in H1.\n    rewrite H1 in H. omega.\n  - assert (n >= S n0) by omega.\n    rewrite <- N_ltb_false__ge in H0.\n    rewrite H0. easy.\nQed.\n\nLemma Z_no_diff__eq: forall x y: int, x - y = Z_pos 0 <-> x = y.\nProof. assert (N: (0 =? 0) = true) by reflexivity.\n  intros. destruct x, y; split; intros; simpl; simpl in H.\n  - destruct n0. simpl in H. rewrite plus_0_r in H. apply H.\n    simpl in H. remember (n0 <? n) as b; destruct b.\n    symmetry in Heqb. rewrite N_ltb_true__lt in Heqb. unfold lt in Heqb.\n    rewrite N_le__lt_eq in Heqb. destruct Heqb.\n    rewrite N_lt__gt in H0. rewrite N_gt__pos_minus in H0.\n    inversion H. rewrite H2 in H0. easy.\n    rewrite H0; reflexivity.\n    inversion H.\n  - destruct n0. zero. apply H.\n    simpl. inversion H. simpl.\n    assert ((n0 <? S n0) = true). rewrite N_ltb_true__lt. omega.\n    rewrite H0. assert ((n0 - n0)%nat = 0) by omega.\n    rewrite H2; reflexivity.\n  - inversion H. rewrite <- plus_n_Sm in H1. inversion H1.\n  - inversion H.\n  - destruct n0. simpl in H. assert (n = (n - 0)%nat) by omega.\n    rewrite <- H0 in H. apply H. simpl in H. inversion H.\n  - inversion H.\n  - remember (n <? S n0) as b; destruct b. inversion H.\n    rewrite <- N_le__zero_minus in H1. symmetry in Heqb.\n    rewrite N_ltb_true__lt in Heqb. assert (n = n0) by omega.\n    rewrite H0; reflexivity. inversion H.\n  - inversion H. assert ((n0 <? S n0) = true). rewrite N_ltb_true__lt. omega.\n    rewrite H0. assert ((n0 - n0)%nat = 0) by omega. rewrite H2. reflexivity.\nQed.\n\nLemma Z_opp_involutive: forall x: int, - - x = x.\nProof. destruct x; unfold Z_opp; simpl. destruct n. zero. zero. reflexivity. Qed.\n\nLemma Z_opp_lt_imp: forall x y: int, x <Z y -> -y <Z -x.\nProof. destruct x, y; unfold Z_opp, Z_le; simpl; intros.\n  - destruct n0. rewrite N_nle__gt in H. inversion H. rewrite N_nle__gt in H.\n    simpl. destruct n. zero. easy. simpl. omega.\n  - easy.\n  - destruct n0. zero. easy. zero. easy.\n  - omega.\nQed.\n\nLemma Z_opp_distr: forall x y: int, - (x + y) = - x + - y.\nProof. destruct x, y.\n  - simpl. destruct n, n0; zero. rewrite plus_n_Sm. reflexivity.\n  - simpl. remember (n0 <? n) as b; remember (n =? 0) as c; destruct b, c; symmetry in Heqb, Heqc; simpl.\n    + rewrite N_eqb_true__eq in Heqc. rewrite Heqc in Heqb. easy.\n    + remember (n - S n0 =? 0) as d; destruct d; symmetry in Heqd.\n      rewrite N_eqb_true__eq in Heqd. rewrite N_ltb_true__lt in Heqb.\n      assert (n = S n0) by omega.\n      assert (Init.Nat.pred n < S n0) by omega.\n      rewrite <- N_ltb_true__lt in H0.\n      rewrite H0. rewrite H. simpl. rewrite N_minus_itself. reflexivity.\n      rewrite N_ltb_true__lt in Heqb. rewrite N_eqb_false__ne in Heqd. rewrite N_nonzero__pos in Heqd.\n      assert (Init.Nat.pred n >= S n0) by omega.\n      rewrite <- N_ltb_false__ge in H. rewrite H. simpl.\n      assert (Init.Nat.pred (n - S n0) = (Init.Nat.pred n - S n0)%nat) by omega.\n      rewrite H0. reflexivity.\n    + rewrite N_eqb_true__eq in Heqc. rewrite Heqc. zero.\n    + rewrite N_ltb_false__ge in Heqb. assert (Init.Nat.pred n < S n0) by omega.\n      rewrite <- N_ltb_true__lt in H. rewrite H.\n      assert (S (n0 - n) = (n0 - Init.Nat.pred n)%nat). destruct n0. inversion Heqb.\n      rewrite H0 in Heqc. simpl in Heqc. inversion Heqc.\n      destruct n. simpl in Heqc. inversion Heqc. omega.\n      rewrite H0. reflexivity.\n  - unfold Z_opp, Z_plus.\n    remember (n <? n0) as b; remember (n0 =? 0) as c; destruct b, c; symmetry in Heqb, Heqc; simpl.\n    + rewrite N_eqb_true__eq in Heqc. rewrite Heqc in Heqb. rewrite N_ltb_true__lt in Heqb. inversion Heqb.\n    + rewrite N_ltb_true__lt in Heqb. remember (n0 - S n =? 0) as d; destruct d; symmetry in Heqd; simpl.\n      rewrite N_eqb_false__ne in Heqc. rewrite N_eqb_true__eq in Heqd.\n      assert (n0 = S n) by omega. rewrite H. simpl. assert (n < S n) by omega.\n      rewrite <- N_ltb_true__lt in H0. rewrite H0. rewrite N_minus_itself. reflexivity.\n      rewrite N_eqb_false__ne in Heqc, Heqd. assert (Init.Nat.pred n0 >= S n) by omega.\n      rewrite <- N_ltb_false__ge in H. rewrite H.\n      assert (Init.Nat.pred (n0 - S n) = (Init.Nat.pred n0 - S n)%nat) by omega.\n      rewrite H0. reflexivity.\n    + rewrite N_eqb_true__eq in Heqc. rewrite Heqc. zero.\n    + rewrite N_ltb_false__ge in Heqb. rewrite N_eqb_false__ne in Heqc.\n      assert (Init.Nat.pred n0 < S n) by omega.\n      rewrite <- N_ltb_true__lt in H. rewrite H.\n      assert (S (n - n0) = (n - Init.Nat.pred n0)%nat) by omega.\n      rewrite H0. reflexivity.\n  - simpl. rewrite plus_n_Sm. reflexivity.\nQed.\n\nLemma Z_opp_distr_minus: forall x y: int, - (x - y) = y - x.\nProof. unfold Z_minus. intros. rewrite (Z_opp_distr x (-y)). rewrite Z_opp_involutive. apply Z_2. Qed.\n\nLemma Z_opp_lt: forall x y: int, x <Z y <-> -y <Z -x.\nProof. split; intros.\n  - apply Z_opp_lt_imp. apply H.\n  - rewrite <- (Z_opp_involutive y), <- (Z_opp_involutive x).\n    apply Z_opp_lt_imp. apply H.\nQed.\n\nLemma Z_pos_diff__gt: forall x y: int, x - y >Z Z_pos 0 <-> x >Z y.\nProof. intros. rewrite <- Z_opp_distr_minus. rewrite Z_opp_lt. rewrite Z_opp_involutive.\n  assert (-Z Z_pos 0 = Z_pos 0) by reflexivity. rewrite H. rewrite Z_neg_diff__lt.\n  reflexivity.\nQed.\n\nLemma Z_10_0: forall x: int,\n    (  x <Z Z_pos 0 /\\ ~ x = Z_pos 0 /\\ ~ x >Z Z_pos 0) \\/\n    (~ x <Z Z_pos 0 /\\   x = Z_pos 0 /\\ ~ x >Z Z_pos 0) \\/\n    (~ x <Z Z_pos 0 /\\ ~ x = Z_pos 0 /\\   x >Z Z_pos 0).\nProof.\n  destruct x.\n  - destruct n. right. left. split. simpl. omega. split. simpl. reflexivity. simpl. omega.\n    right. right. split. simpl. omega. split. unfold not. intros. inversion H. simpl. omega.\n  - left. split. simpl. omega. split. unfold not. intros. inversion H. simpl. easy.\nQed.\n\n(** trichotomy *)\nTheorem Z_10: forall x y: int,\n  (  x <Z y /\\ ~ x = y /\\ ~ x >Z y) \\/\n  (~ x <Z y /\\   x = y /\\ ~ x >Z y) \\/\n  (~ x <Z y /\\ ~ x = y /\\   x >Z y).\nProof.\n  intros. rewrite <- Z_neg_diff__lt. rewrite <- Z_no_diff__eq. rewrite <- (Z_pos_diff__gt x y).\n  apply Z_10_0.\nQed.\n\n(** trichotomy *)\nCorollary Z_10_1: forall x y: int, x <Z y \\/ x = y \\/ x >Z y.\nProof.\n  intros.\n  pose proof (Z_10 x y).\n  destruct H; destruct H.\n  - left. apply H.\n  - destruct H. destruct H0. right. left. apply H0.\n  - destruct H. destruct H0. right. right. apply H1.\nQed.\n\nLemma Z_plus_0_l: forall x: int, Z_pos 0 + x = x.\nProof. destruct x.\n  - simpl. reflexivity.\n  - simpl. zero.\nQed.\n\n(** transitivity *)\nLemma Z_11_0: forall x y: int, x <Z Z_pos 0 -> y <Z Z_pos 0 -> x + y <Z Z_pos 0.\nProof. destruct x, y; intros.\n  - simpl in H. rewrite N_nle__gt in H; inversion H.\n  - simpl in H. rewrite N_nle__gt in H; inversion H.\n  - simpl in H0. rewrite N_nle__gt in H0; inversion H0.\n  - simpl. easy.\nQed.\n\n(** transitivity *)\nTheorem Z_11: forall x y z: int, x <Z y -> y <Z z -> x <Z z.\nProof. intros x y z. rewrite <- (Z_neg_diff__lt x y). rewrite <- (Z_neg_diff__lt x z). rewrite <- (Z_neg_diff__lt y z).\n  assert ((x - y) + (y - z) = x - z).\n  { unfold Z_minus. rewrite Z_1. rewrite <- (Z_1 (- y)).\n    assert (- y + y = Z_pos 0). destruct y.\n    simpl; destruct n; zero. assert (n < S n) by omega.\n    rewrite <- N_ltb_true__lt in H. rewrite H. reflexivity.\n    simpl. assert (n < S n) by omega. rewrite <- N_ltb_true__lt in H. rewrite H. zero.\n    rewrite H. rewrite Z_plus_0_l. reflexivity. }\n  rewrite <- H. apply (Z_11_0 (x - y) (y - z)).\nQed.\n\n(** addition preserves the order *)\nTheorem Z_12: forall x y z: int, x <Z y -> x + z <Z y + z.\nProof. intros x y z. rewrite <- (Z_neg_diff__lt x y). rewrite <- (Z_neg_diff__lt (x + z) (y + z)).\n  unfold Z_minus. rewrite Z_1. rewrite Z_opp_distr. rewrite (Z_2 (-y) (-z)). rewrite <- (Z_1 z).\n  rewrite Z_4. rewrite (Z_2 (Z_pos 0)). rewrite Z_3. intros. apply H.\nQed.\n\n\n(** mult by positive number preserves the order *)\nTheorem Z_13: forall x y z: int, x <Z y /\\ z >Z Z_pos 0 -> x * z <Z y * z.\nProof.\n\nAdmitted.\n\n(** Z is not a trivial ring *)\nTheorem Z_14: 0 <> 1.\nProof. unfold not. intros. inversion H. Qed.\n\nLemma Z_not_not_equal: forall z w: int, z = w <-> ~ z <> w.\nProof.\nAdmitted.\n\nLemma Z_mult_0: forall z: int, z * Z_pos 0 = Z_pos 0.\nProof.\n  destruct z; zero.\nQed.\n\nLemma Z_mult_neg_1: forall z: int, - z = - (Z_pos 1) * z.\nProof.\n  destruct z; simpl; zero.\nQed.\n\nClose Scope int_scope.\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_constructive/integer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7511651339559171}}
{"text": "(*\n  Copyright 2023 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   : Chapter 1, Introduction to Vectors\n  author    : ZhengPu Shi\n  date      : 2023.03\n  \n  remark    :\n  1. reference: Introduction to Linear Algebra, by Gilbert Strang\n *)\n\n\n(** There is no implementation of sqrt, thus vlen cannot be defined. *)\n(* Require Import VectorQ. *)\n\nRequire Import VectorR.\n\n\n(** Set initial scope *)\nOpen Scope nat_scope.\n(* Open Scope Q_scope. *)\nOpen Scope R_scope.\nOpen Scope mat_scope.\nOpen Scope vec_scope.\n\n(** ** 1.1 Vectors and Linear Combination  *)\nSection sec_1_1.\n\n  (** Linear Combination of: c * v + d * w *)\n  Definition lc {n : nat} (v w : vec n) (c d : A) := c c* v + d c* w.\n\n  (* Example  *)\n  Let v := mk_vec2 1 1.\n  Let w := mk_vec2 2 3.\n  \n  Goal lc v w 1 1 == mk_vec2 3 4.\n  Proof. lma. Qed.\n  \n  Goal lc v w 2 1 == mk_vec2 4 5.\n  Proof. lma. Qed.\n\n  Goal lc v w 3 5 == mk_vec2 13 18.\n  Proof. lma. Qed.\n\n  (** Verify these special linear combinations: *)\n  Section special_linear_combinations.\n\n    (* 1v + 1w = v + w *)\n    Lemma lc_eq_add : forall {n} (v w : vec n), lc v w 1 1 == v + w.\n    Proof. lma. Qed.\n    \n    (* 1v - 1w = v - w *)\n    Lemma lc_eq_sub : forall {n} (v w : vec n), lc v w 1 (-1) == v - w.\n    Proof. lma. Qed.\n    \n    (* 0v + 0w = 0 *)\n    Lemma lc_eq_zero : forall {n} (v w : vec n), lc v w 0 0 == vec0.\n    Proof. lma. Qed.\n    \n    (* cv + 0w = c.v *)\n    Lemma lc_eq_scal : forall {n} (v w : vec n) (c : A), lc v w c 0 == c c* v.\n    Proof. lma. Qed.\n\n  End special_linear_combinations.\n\n  (** Example for 3D vector *)\n  Goal let v := mk_vec3 1 1 (-1) in\n       let w := mk_vec3 2 3 4 in\n       lc v w 1 1 == mk_vec3 3 4 3.\n  Proof. lma. Qed.\n\n  (** Linear combination of several vectors (more than 2) *)\n  Reset lc.\n\n  Definition lc {n : nat} (l : list (A * (vec n))%type) :=\n    let l' := map (fun x : A * vec n => let (c,v) := x in c c* v) l in\n    fold_left vadd l' vec0.\n\n  (** Example in page 5 *)\n  Goal let u := mk_vec3 1 0 3 in\n       let v := mk_vec3 1 2 1 in\n       let w := mk_vec3 2 3 (-1) in\n       lc [(1,u);(4,v);(-2,w)] == mk_vec3 1 2 9.\n  Proof. lma. Qed.\n  \nEnd sec_1_1.\n\n\n(** ** 1.2 Lengths and Dot Products *)\nSection sec_1_2.\n\n  Infix \"⋅\" := vdot : vec_scope.\n  Notation \"v| v |\" := (vlen v) : vec_scope.\n\n  (** A vector is a unit vector *)\n  Section vunit.\n\n    (** unit vector in xy plane *)\n    Let i := mk_vec2 1 0.\n    Let j := mk_vec2 0 1.\n\n    (** make an angle \"theta\" with the x axis *)\n    Let u θ := mk_vec2 (cos θ) (sin θ).\n    \n    (** if theta = 0, then u is i *)\n    Goal u 0 == i.\n    Proof. lma; cbv; ra. Qed.\n    \n    (** if theta = 90 degree (π/2), then u is j *)\n    Goal u (PI/2) == j.\n    Proof. lma; cbv; ra. Qed.\n\n    (** at any angle, u is a unit vector *)\n    Goal forall θ, vunit (u θ).\n    Proof. intros. cbv. autorewrite with R. auto. Qed.\n\n  End vunit.\n\n  (** Convert any non-zero vector to a unit vector *)\n  Section vnormalize.\n\n    Let u := mk_vec3 2 2 1.\n\n    (** length of us is 3 *)\n    Let len_of_u : v| u | = 3.\n    Proof. cbv. solve_sqrt_eq. Qed.\n\n    (** normalize u to unit vector *)\n    Goal vnormalize u == mk_vec3 (2/3) (2/3) (1/3).\n    Proof. lma. all: rewrite len_of_u; cbv; ra. Qed.\n\n  End vnormalize.\n\n  \n  (** The angle between two vectors *)\n  Section angle.\n\n    (** Angle of two vectors *)\n    Parameter angle_of_vec : forall {n} (u v : vec n), R.\n    Infix \"∠\" := angle_of_vec (at level 70) : vec_scope.\n\n    (** Two vectors are perpendicular *)\n    Section perp.\n      \n      (** Two vectors u and w are perpendicular *)\n      Definition perpendicular {n} (u v : vec n) : Prop := u ∠ v = PI/2.\n      Infix \"⟂\" := perpendicular (at level 70) : vec_scope.\n\n      (** Pythagoras Law. *)\n      Axiom PythagorasLaw2D : forall (a b : vec 2),\n          let c := a - b in\n          a ⟂ b <-> (Rsqr (v|a|) + Rsqr (v|b|))%A = Rsqr (v|c|).\n\n      (** v ⟂ w, iff v ⋅ w = 0 *)\n      Lemma perpendicular_iff_dot0_2D : forall (u v : vec 2), u ⟂ v <-> u ⋅ v = 0.\n      Proof.\n        intros. split; intros H.\n        - apply PythagorasLaw2D in H.\n          destruct u as [u], v as [v]. cbv in *.\n          ring_simplify in H. autorewrite with R in *.\n          rewrite ?Rsqr_sqrt in H; ra.\n        - apply PythagorasLaw2D.\n          destruct u as [u], v as [v]. cbv in *.\n          ring_simplify. autorewrite with R in *.\n          rewrite ?Rsqr_sqrt; ra.\n      Qed.\n    End perp.\n\n    (** The angle of two unit vectors *)\n    Section angle_vunit.\n      \n      (** the cosine of angle of two unit vectors *)\n      Axiom cosine_angle_of_vuint : forall {n} (u v : vec n),\n          vunit u -> vunit v -> cos (u ∠ v) = u ⋅ v.\n\n      (** if u = (cos θ, sin θ), i = (1,0), then u⋅i=cos θ.\n        That is the cosine of the angle between them. *)\n\n      (** after rotation through any angle α, their angle still is θ *)\n\n    End angle_vunit.\n\n    (** The angle of two vectors (needn't be unit vector) *)\n    Section angle.\n\n      (** the cosine of angle of two vectors *)\n      Axiom cosine_angle_of_vec : forall {n} (u v : vec n),\n          vnonzero u -> vnonzero v ->\n          cos (u ∠ v) = (vnormalize u) ⋅ (vnormalize v).\n\n      (** “Schwarz inequality” for dot products.\n          more correctly, Cauchy-Schwarz-Buniakowsky inequality *)\n      Lemma schwarz_ineq_vdot : forall {n} (v w : vec n), Rabs (v⋅w) <= v|v | * v|w|.\n      Proof.\n        intros.\n        destruct (decidable v vec0), (decidable w vec0).\n        - (* v = 0, w = 0 *)\n          assert (v ⋅ w == 0)%A.\n          { rewrite v0. rewrite vdot_0_l. easy. }\n          rewrite H. autorewrite with R.\n          ?\n          hnf. ra.\n            rewrite v1.\n            rewrite v0.\n          Set Printing All.\n          \n          rewrite v0.\n          \n          \n        - (* v = 0, w <> 0 *)\n        - (* v = 0, w <> 0 *)\n        - (* v = 0, w <> 0 *)\n          \n        pose proof (cosine_angle_of_vec v w).\n        assert (vnormalize v ⋅ vnormalize w\n        unfold vnormalize in H.\n        assert \n        s hnf in *.\n        \n      Admitted.\n\n      (** Triangle inequality *)\n      Lemma triangle_ineq : forall {n} (v w : vec n), v|v + w| <= v|v | + v|w|.\n      Admitted.\n\n      \n    End angle.\n\n    (** \n\n  End angle.\n\n  \n\n  \n\nEnd sec_1_2.\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/vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7511651334255819}}
{"text": "Inductive 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 double (double_arg0 : natural) : natural\n           := match double_arg0 with\n              | Zero => Zero\n              | Succ n => Succ (Succ (double n))\n              end.\n\nLemma lem: forall m n, Succ (plus m n) = plus m (Succ n).\nProof.\n   induction m.\n   - intros. simpl. rewrite IHm. reflexivity.\n   - intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : natural), eq (double x) (plus x x).\nProof.\n   induction x.\n   - simpl. f_equal. rewrite IHx. apply lem.\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/goal1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7511484038223935}}
{"text": "(* Euclid's proof that prime numbers are infinite.\n   Frédéric Blanqui INRIA, 25 November 2014. *)\n\nSet Implicit Arguments.\n\nRequire Import Arith Omega.\n\nLemma mult_gt_0 a b : a * b > 0 <-> a > 0 /\\ b > 0.\n\nProof.\n  (* We proceed by case on a and b. *)\n  destruct a. omega. destruct b. omega. split. omega.\n  intros _. simpl. (*omega does not work here!*) apply gt_Sn_O.\nQed.\n\nLemma le_mult_r a b : b > 0 -> a <= a * b.\n\nProof.\n  intros hb. rewrite <- (mult_1_r a) at 1. apply mult_le_compat_l. omega.\nQed.\n\n(** Divisibility. *)\n\nDefinition divide a b := exists q, b = a * q.\n\nInfix \"\\\" := divide (at level 70).\n\nLemma divide_le a b : b > 0 -> a \\ b -> a <= b.\n\nProof.\n  intros b_gt_0 [q ha]. subst. apply le_mult_r. rewrite mult_gt_0 in b_gt_0.\n  tauto.\nQed.\n\nLemma divide_mult_l a b c : a \\ b -> a \\ c * b.\n\nProof. intros [q ha]. subst. exists (q*c). ring. Qed.\n\nLemma divide_minus a b c : a \\ b -> a \\ c -> a \\ b-c.\n\nProof.\n  intros [p hb] [q hc]. subst. exists (p-q). (* omega does not work here! *)\n  rewrite <- mult_minus_distr_l. reflexivity.\nQed.\n\nLemma divide_trans a b c : a \\ b -> b \\ c -> a \\ c.\n\nProof. intros [q h] [r g]. exists (q * r). subst. ring. Qed.\n\n(* Product of a list of natural numbers. *)\n\nRequire Import List.\n\nFixpoint prod l :=\n  match l with\n    | nil => 1\n    | a :: l' => a * prod l'\n  end.\n\nLemma prod_gt_0 : forall l, ~In 0 l <-> prod l > 0.\n\nProof. induction l; simpl. omega. rewrite mult_gt_0. intuition. Qed.\n\nLemma in_prod {a} : forall {l}, ~In 0 l -> In a l -> a <= prod l.\n\nProof.\n  (* We proceed by induction on l. *)\n  induction l as [|b l hl]; simpl.\n  omega.\n  intros hb [ha|ha].\n  subst. apply le_mult_r. apply prod_gt_0. tauto.\n  rewrite <- (mult_1_l a) at 1. apply mult_le_compat. omega. tauto.\nQed.\n\nLemma divide_prod {a} : forall {l}, In a l -> a \\ prod l.\n\nProof.\n  (* We proceed by induction on l. *)\n  induction l as [|b l hl]; simpl.\n  tauto.\n  intros [ha|ha].\n  subst. exists (prod l). reflexivity.\n  apply divide_mult_l. tauto.\nQed.\n\n(* Prime numbers. *)\n\nDefinition prime b := b >= 2 /\\ forall a, divide a b -> a = 1 \\/ a = b.\n\nLemma zero_isnt_prime : ~prime 0.\n\nProof. unfold prime. omega. Qed.\n\nTheorem fundamental_theorem_of_arithmetic a :\n  a >= 2 -> exists p, prime p /\\ p \\ a.\n\nProof.\n  (* We proceed by well-founded induction on a. *)\n  pattern a; apply lt_wf_ind; clear a; intros a IHa a_ge_2.\n  Require Import Classical.\n  destruct (classic (prime a)) as [a_is_prime|a_isnt_prime].\n  (* If a is prime, then we can take p=a. *)\n  exists a. intuition. exists 1. ring.\n  (* If a is not prime, then there is some b between 2 and a-1 that divides a. *)\n  apply not_and_or in a_isnt_prime. intuition. apply not_all_ex_not in H.\n  destruct H as [b hb]. apply imply_to_and in hb. destruct hb as [b_div_a hb].\n  apply not_or_and in hb.\n  assert (b_lt_a : b < a). apply divide_le in b_div_a. omega. omega.\n  assert (b_ge_2 : b >= 2). destruct b_div_a as [q ha].\n  destruct (eq_nat_dec b 0). 2: omega. subst. omega.\n  (* By induction hypothesis on b, there is some prime p that divides b,\n  and thus a by transitivity. *)\n  destruct (IHa _ b_lt_a b_ge_2) as [p [p_prime p_div_b]].\n  exists p. intuition. apply divide_trans with b; assumption.\nQed.\n\nTheorem primes_are_infinite : ~ (exists l, forall a, prime a <-> In a l).\n\nProof.\n  intros [l all_primes_in_l]. set (n := S (prod l)).\n  (* We prove that n is prime. *)\n  assert (n_is_prime : prime n). split.\n  (* n >= 2 *)\n  apply le_n_S. apply lt_le_S. apply prod_gt_0.\n  rewrite <- all_primes_in_l. apply zero_isnt_prime.\n  (* We now prove that assuming that there is a divider a of n that is\n  different from 1 and n leads to a contradiction. *)\n  intros a a_div_n. destruct (eq_nat_dec a 1). tauto.\n  right. destruct (eq_nat_dec a n). assumption. apply False_rec.\n  (* We prove that a is >= 2. *)\n  assert (a_ge_2 : a >= 2). destruct a_div_n as [q hn].\n  destruct (eq_nat_dec a 0). subst. rewrite mult_0_l in hn. omega. omega.\n  (* Hence, a has a prime divider p. *)\n  destruct (fundamental_theorem_of_arithmetic a_ge_2) as [p [p1 p2]].\n  (* By transitivity, p divides n. *)\n  generalize (divide_trans p2 a_div_n); intro p_div_n.\n  (* Since all primes are in l, p is in l and p divides prod l. *)\n  assert (p_in_l : In p l). rewrite <- all_primes_in_l. assumption.\n  apply divide_prod in p_in_l.\n  (* Thus p divides n-prod l=1. *)\n  generalize (divide_minus p_div_n p_in_l).\n  unfold n. rewrite <- minus_Sn_m, minus_diag. 2: reflexivity.\n  (* Therefore p=1 but 1 is not prime. Hence, n is prime. *)\n  intros [q hp]. symmetry in hp. apply mult_is_one in hp. destruct hp. subst.\n  destruct p1. omega.\n  (* We now prove that n is not in l. *)\n  rewrite all_primes_in_l in n_is_prime.\n  assert (zero_notin_l : ~In 0 l).\n  rewrite <- all_primes_in_l. unfold prime. omega.\n  generalize (in_prod zero_notin_l n_is_prime). unfold n. omega.\nQed.\n", "meta": {"author": "verimath", "repo": "ftarith", "sha": "31e15afbf48a73d7d159f6491a62facf3ced3b21", "save_path": "github-repos/coq/verimath-ftarith", "path": "github-repos/coq/verimath-ftarith/ftarith-31e15afbf48a73d7d159f6491a62facf3ced3b21/src/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7511121747977539}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Definition opp_distr_if (b : bool) x y : -(if b then x else y) = if b then -x else -y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite opp_distr_if : push_Zopp.\n  Hint Rewrite <- opp_distr_if : pull_Zopp.\n\n  Lemma mul_r_distr_if (b : bool) x y z : z * (if b then x else y) = if b then z * x else z * y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite mul_r_distr_if : push_Zmul.\n  Hint Rewrite <- mul_r_distr_if : pull_Zmul.\n\n  Lemma mul_l_distr_if (b : bool) x y z : (if b then x else y) * z = if b then x * z else y * z.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite mul_l_distr_if : push_Zmul.\n  Hint Rewrite <- mul_l_distr_if : pull_Zmul.\n\n  Lemma add_r_distr_if (b : bool) x y z : z + (if b then x else y) = if b then z + x else z + y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite add_r_distr_if : push_Zadd.\n  Hint Rewrite <- add_r_distr_if : pull_Zadd.\n\n  Lemma add_l_distr_if (b : bool) x y z : (if b then x else y) + z = if b then x + z else y + z.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite add_l_distr_if : push_Zadd.\n  Hint Rewrite <- add_l_distr_if : pull_Zadd.\n\n  Lemma sub_r_distr_if (b : bool) x y z : z - (if b then x else y) = if b then z - x else z - y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite sub_r_distr_if : push_Zsub.\n  Hint Rewrite <- sub_r_distr_if : pull_Zsub.\n\n  Lemma sub_l_distr_if (b : bool) x y z : (if b then x else y) - z = if b then x - z else y - z.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite sub_l_distr_if : push_Zsub.\n  Hint Rewrite <- sub_l_distr_if : pull_Zsub.\n\n  Lemma div_r_distr_if (b : bool) x y z : z / (if b then x else y) = if b then z / x else z / y.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite div_r_distr_if : push_Zdiv.\n  Hint Rewrite <- div_r_distr_if : pull_Zdiv.\n\n  Lemma div_l_distr_if (b : bool) x y z : (if b then x else y) / z = if b then x / z else y / z.\n  Proof. destruct b; reflexivity. Qed.\n  Hint Rewrite div_l_distr_if : push_Zdiv.\n  Hint Rewrite <- div_l_distr_if : pull_Zdiv.\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/DistrIf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7510503092488905}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(* 2 整列の証明、再び *)\n\nSection sort.\nVariable A : eqType.\nVariable le : A -> A -> bool.\nVariable le_trans: forall x y z, le x y -> le y z -> le x z.\nVariable le_total: forall x y, ~~ le x y -> le y x.\n\nFixpoint insert a l := 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\nFixpoint isort l :=\n  if l is a :: l' then insert a (isort l') else nil.\n\nFixpoint sorted l := (* all を使って bool 上の述語を定義する *)\n  if l is a :: l' then all (le a) l' && sorted l' else true.\n\nLemma le_seq_insert a b l :\n  le a b -> all (le a) l -> all (le a) (insert b l).\nProof.\n  elim: l => /= [-> // | c l IH].\n  move=> leab /andP [leac leal].\n  case: ifPn => lebc /=.\n  - by rewrite leab leac.\n  - by rewrite leac IH.\nQed.\n\nLemma le_seq_trans a b l :\n  le a b -> all (le b) l -> all (le a) l.\nProof.\n  move=> leab /allP lebl.\n  apply/allP => x Hx.\n  by apply/le_trans/lebl.\nQed.\n\nTheorem insert_ok a l : sorted l -> sorted (insert a l).\nProof.\n  elim: l => //= a0 l0 IH1 /andP[IHL IHR].\n  case: ifPn => Hle /=.\n  - by rewrite Hle (le_seq_trans _ _ _ Hle IHL) IHL IHR.\n  - rewrite le_seq_insert => //.\n    + by rewrite (IH1 IHR).\n    + rewrite le_total => //.\nRestart.\n  elim: l => //= a0 l0 IH1 /andP[IHL IHR].\n  case: ifPn => Hle /=.\n  - by rewrite Hle (le_seq_trans _ _ _ Hle IHL) IHL IHR.\n  - by rewrite (le_seq_insert _ _ _ (le_total _ _ Hle) IHL) (IH1 IHR).\nQed.\nTheorem isort_ok l : sorted (isort l).\nProof.\n  elim: l => //= a l IH.\n  by apply insert_ok.\nQed.\n\n(* perm_eq が seq で定義されているが補題だけを使う *)\nTheorem insert_perm l a : perm_eq (a :: l) (insert a l).\nProof.\n  elim: l => //= b l pal.\n  case: ifPn => //= leab.\n  by rewrite (perm_catCA [:: a] [:: b]) perm_cons.\nQed.\n\n(* perm_trans : forall (T : eqType), transitive (seq T) perm_eq *)\nTheorem isort_perm l : perm_eq l (isort l).\nProof.\n  elim: l => //= a l IH. (* perm_eq_trans が perm_trans に変わった *)\n  apply/perm_trans/insert_perm.\n  by rewrite perm_cons.\nQed.\nEnd sort.\n\nCheck isort.\nDefinition isortn : seq nat -> seq nat := isort _ leq.\nDefinition sortedn := sorted _ leq.\nLemma leq_total a b : ~~ (a <= b) -> b <= a.\nProof.\n  move: (leq_total a b) => /orP[HL|HR] H //.\n  case: ((negP H) HL).\nRestart.\n  Search \"~~\" \"<=\".\n  rewrite -ltnNge.\n  Search (_ < _ -> _ <= _).\n  by apply: ltnW.\nQed.\n\nTheorem isortn_ok l : sortedn (isortn l) && perm_eq l (isortn l).\nProof.\n  apply/andP. split.\n  - apply: isort_ok.\n    + Check leq_trans. (* 引数の順番が違う *)\n      move=>m n p. apply: leq_trans.\n    + apply: leq_total.\n  - apply: isort_perm.\nRestart.\n  apply/andP. split.\n  - apply: isort_ok => m n p.\n    + by apply: leq_trans.\n    + by apply: leq_total.\n  - by apply: isort_perm.\nQed.\n\nRequire Import Extraction.\nExtraction \"isort.ml\" isortn. (* コードが分かりにくい *)\n\n(*\n% ocaml -c isort.ml (* .mlだと思う *)\n% ocaml\n# #load\"isort.cmo\";;\n# open Isort;;\n# isortn (Cons (S O, Cons (O, Cons (S (S O), Nil))));;\n- : Isort.nat Isort.list = Cons (O, Cons (S O, Cons (S (S O), Nil)))\n*)\n\nSection even_odd.\nNotation even n := (~~ odd n). (* 単なる表記なので，展開が要らない *)\n\nTheorem even_double n : even (n + n).\nProof. elim: n => // n. by rewrite addnS /= negbK. Qed.\n\n(* 等式を使って n に対する通常の帰納法を可能にする *)\nTheorem even_plus m n : even m -> even n = even (m + n).\nProof.\n  elim: n => /= [|n IH] Hm.\n  - by rewrite addn0.\n  - by rewrite addnS IH.\nQed.\n\nTheorem one_not_even : ~~ even 1.\nProof. reflexivity. Qed.\n\nTheorem even_not_odd n : even n -> ~~ odd n.\nProof. done. Qed.\n\nTheorem even_odd n : even n -> odd n.+1.\nProof.\n  elim: n => //.\nRestart.\n  done.\nQed.\nTheorem odd_even n : odd n -> even n.+1.\nProof.\n  elim: n => //= n IH.\n  rewrite negbK => //.\nRestart.\n  elim: n => //= _ _ -> //.\nQed.\nTheorem even_or_odd n : even n || odd n.\nProof.\n  by rewrite orbC orbN.\nRestart.\n  rewrite orbC.\n  rewrite orbN.\n  done.\nQed.\nTheorem odd_odd_even m n : odd m -> odd n = even (m+n).\nProof.\n  elim: m => //= n0 IH1 IH2.\n  by rewrite -(even_plus n0 _ IH2) negbK.\nRestart.\n  elim: m => //= n0 IH1 IH2.\n  rewrite -(even_plus n0).\n  - rewrite negbK. reflexivity.\n  - exact IH2.\nQed.\nEnd even_odd.\n", "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/ssreflect08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7510101262682145}}
{"text": "(* This file should be tested by loaded from `ring_examples_check.v` and      *)\n(* `ring_examples_no_check.v`. To edit this file, uncomment `Require Import`s *)\n(* below: *)\n(* From mathcomp Require Import all_ssreflect ssralg ssrnum ssrint rat. *)\n(* From mathcomp Require Import ring. *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\n\nLocal Open Scope ring_scope.\n\nSection AbstractCommutativeRing.\n\nVariables (R : comRingType) (a b c : R) (n : nat).\n\n(* Examples from the Coq Reference Manual, but for an instance of MathComp's\n   (abstract) commutative ring. *)\n\n\n(* Using the _%:R embedding from nat to R *)\nGoal (a + b + c) ^+ 2 =\n     a * a + b ^+ 2 + c * c + 2%:R * a * b + 2%:R * a * c + 2%:R * b * c.\nProof. ring. Qed.\n\nGoal (a + b + c) ^+ 2 =\n     a * a + b ^+ 2 + c * c + 2%:R * a * b + 2%:R * a * c + 2%:R * b * c.\nProof. (#[verbose] ring). Qed.\n\n(* Using the _%:~R embedding from int to R : 2 is coerced to (Posz 2) : int *)\nGoal (a + b + c) ^+ 2 =\n     a * a + b ^+ 2 + c * c + 2%:~R * a * b + 2%:~R * a * c + 2%:~R * b * c.\nProof. ring. Qed.\n\n(* With an identity hypothesis *)\n(* Using the _%:R embedding from nat to R *)\nGoal 2%:R * a * b = 30%:R -> (a + b) ^+ 2 = a ^+ 2 + b ^+ 2 + 30%:R.\nProof. move=> H; ring: H. Qed.\n\n(* With an identity hypothesis *)\n(* Using the _%:~R embedding from int to R *)\nGoal 2%:~R * a * b = 30%:~R -> (a + b) ^+ 2 = a ^+ 2 + b ^+ 2 + 30%:~R.\nProof. move=> H; ring: H. Qed.\n\nGoal (n.+1)%:R = n%:R + 1 :> R.\nProof. ring. Qed.\n\nEnd AbstractCommutativeRing.\n\nSection AbstractRingMorphism.\n\nVariables (R : ringType) (S : comRingType) (f : {rmorphism R -> S}) (a b : R).\n\nGoal f ((a + b) ^+ 2) = f a ^+ 2 + f b ^+ 2 + 2%:R * f a * f b.\nProof. ring. Qed.\n\nEnd AbstractRingMorphism.\n\nSection AbstractAdditiveFunction.\n\nVariables (U V : zmodType) (R : comRingType).\nVariables (g : {additive U -> V}) (f : {additive V -> R}) (a : U) (b : V).\n\nGoal f (g a + b) ^+ 2 = f (g a) ^+ 2 + f b ^+ 2 + f (g (a *+ 2)) * f b.\nProof. ring. Qed.\n\nEnd AbstractAdditiveFunction.\n\nSection NumeralExamples.\n\nVariable (R : comRingType).\n\n(* With numeral constants *)\nGoal 20%:R * 3%:R = 60%:R :> R.\nProof. ring. Qed.\n\nGoal 20%:~R * 3%:~R = 60%:~R :> R.\nProof. ring. Qed.\n\nGoal 200%:~R * 30%:~R = 6000%:~R :> R.\nProof. ring. Qed.\n\nGoal 2%:~R * 10%:~R ^+ 2 * 3%:~R * 10%:~R ^+ 2 = 6%:~R * 10%:~R ^+ 4:> R.\nProof. ring. Qed.\n\nGoal 200%:R * 30%:R = 6000%:R :> R.\nProof.\nTime ring. (* 0.186 secs *)\nQed.\n\nGoal 200%:R * 30%:R = 6000%:R :> int.\nProof.\nTime ring. (* 0.343 secs *)\nQed.\n\nGoal 20%:R * 3%:R = 60%:R :> rat.\nProof.\nTime ring. (* 0.018 secs *)\nQed.\n\nGoal 200%:R * 30%:R = 6000%:R :> rat.\nProof.\nTime ring. (* 0.208 secs *)\nQed.\n\nEnd NumeralExamples.\n\nSection MoreVariables.\n\nVariables (q w e r t y u i o p a s d f g h j k l : int).\n\nLemma test_vars : \n  q * w * e * r * t * y * u * i * o * p * a * s * d * f * g * h * j * k * l =\n  l * w * e * r * t * y * u * i * o * p * a * s * d * f * g * h * j * k * q.\nProof. Time ring. Qed. (* 0.049 secs *)\n\nEnd MoreVariables.\n", "meta": {"author": "math-comp", "repo": "algebra-tactics", "sha": "edc8e5e59b49b02089fcb0bd5217e03100ea9e12", "save_path": "github-repos/coq/math-comp-algebra-tactics", "path": "github-repos/coq/math-comp-algebra-tactics/algebra-tactics-edc8e5e59b49b02089fcb0bd5217e03100ea9e12/examples/ring_examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7510101226293378}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Tactics.\nRequire Export Logic.\nRequire Export Lists.\nRequire Coq.omega.Omega.\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\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\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(* Exercise: 1 star (ev_double) *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros. rewrite double_plus. induction n.\n  - simpl. apply ev_0.\n  - simpl. rewrite <- plus_n_Sm. apply ev_SS. apply IHn.\nQed.\n\n\n(* Using Evidence in Proofs *)\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'.\nQed.\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E.\n  - simpl. apply ev_0.\n  - simpl. apply E.\nQed.\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  apply E'.\nQed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n\n(* Exercise: 1 star (SSSSev_even) *)\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  inversion E'. apply H1.\nQed.\n\n(* Exercise: 1 star (even5_nonsense) *)\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros. inversion H.\n  inversion H1. inversion H3.\nQed.\n\nLemma ev_even_firsttry : forall n,\n    ev n -> exists k, n = double k.\nProof.\n  intros n E.\n  inversion E as [| p E'].\n  - (* E = ev_0 *) exists 0. reflexivity.\n  - (* E = ev_SS n' E' *)\n    assert (I : (exists r, p = double r) ->\n                (exists k, S (S p) = double k)). \n    { intros [r Hr]. rewrite Hr. exists (S r). reflexivity. }\n    apply I. \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       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). simpl. reflexivity.\nQed.\n\nTheorem ev_even_iff : forall n,\n  ev n <-> exists k, n = double k.\nProof.\n  intros. unfold iff. split.\n  - apply ev_even.\n  - intros [k' Hk']. rewrite Hk'. apply ev_double.\nQed.\n\n(* Exercise: 2 stars (ev_sum) *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m En Em. induction En.\n  - simpl. apply Em.\n  - simpl. apply ev_SS. apply IHEn.\nQed.\n\n(* Exercise: 4 stars, advanced, optional (ev' ev) *)\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_1 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros. split.\n  - intros E. induction E.\n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum.\n      * apply IHE1.\n      * apply IHE2.\n  - intros E. induction E.\n    + apply ev'_0.\n    + assert (I : forall n, S (S n) = n + 2).\n      { - intros. induction n0.\n          + reflexivity.\n          + simpl. rewrite IHn0. reflexivity. }\n      rewrite I. apply ev'_sum.\n        * apply IHE.\n        * apply ev'_1.\nQed.\n\n(* Exercise: 3 stars, advanced, recommended (ev_ev__ev) *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n + m) -> ev n -> ev m.\nProof.\n  intros n m Enm En. induction En.\n  - simpl in Enm. apply Enm.\n  - simpl in Enm. apply IHEn. apply evSS_ev in Enm. apply Enm.\nQed.\n\n\n(* Exercise: 3 stars, optional (ev_plus_plus) *)\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros. apply ev_sum with (n + m) (n + p) in H.\n  - rewrite plus_swap in H. rewrite <- plus_assoc in H.\n    rewrite plus_assoc with n n (m + p) in H.\n    apply ev_ev__ev with (n + n) (m + p) in H.\n    + apply H.\n    + rewrite <- double_plus. apply ev_double.\n  - apply H0.\nQed.\n\n\nModule Playground.\n\nInductive le : nat -> nat -> Prop :=\n  | le_n : forall n, le n n\n  | le_S : forall n m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nTheorem test_le1 :\n  3 <= 3.\nProof. apply le_n. Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof. 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  intros H.\n  inversion H.\n  inversion H2.\nQed.\n\nEnd Playground.\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 : nat -> nat -> Prop :=\n  | nn : forall n:nat, next_nat n (S n).\n\nInductive next_even : nat -> nat -> Prop :=\n  | ne_1 : forall n, ev (S n) -> next_even n (S n)\n  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).\n\n\n(* Exercise: 3 stars, optional (le_exercises) *)\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hmo.\n  induction Hmo.\n  - apply Hmn.\n  - apply le_S. apply IHHmo.\nQed.\n\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction n.\n  - apply le_n.\n  - apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem le_Sn_le : forall n m, \n  S n <= m -> n <= m.\nProof.\n  intros.\n  apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m H.\n  inversion H.\n  - apply le_n.\n  - apply le_trans with (S n).\n    + apply le_S. apply le_n.\n    + apply H1.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros.\n  induction a.\n  - simpl. apply O_le_n.\n  - simpl. apply n_le_m__Sn_le_Sm. apply IHa.\nQed.\n\nTheorem le_plus_r : forall a b,\n  b <= a + b.\nProof.\n  intros.\n  induction a.\n  - simpl. apply le_n.\n  - simpl. apply le_S. apply IHa.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  unfold lt.\n  intros n1 n2 m H.\n  split.\n  - apply le_trans with (S (n1 + n2)).\n    + apply n_le_m__Sn_le_Sm. apply le_plus_l.\n    + apply H.\n  - apply le_trans with (S (n1 + n2)).\n    + apply n_le_m__Sn_le_Sm. apply le_plus_r.\n    + apply H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros.\n  apply le_Sn_le in H.\n  apply n_le_m__Sn_le_Sm. apply H.\nQed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n. induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nTheorem n_ble_m__Sn_ble_Sm : forall n m,\n  leb n m = true -> leb (S n) (S m) = true.\nProof.\n  intros. simpl. apply H. Qed.\n\nTheorem Sn_ble_Sm__n_ble_m : forall n m,\n  leb (S n) (S m) = true -> leb n m = true.\nProof.\n  intros.\n  simpl in H. apply H. Qed.\n\n\n(* \n  if (S 4) <= 5 then 4 <= 5. YES\n  if 4 <= (S 3) then 4 <= 3. NO\n  if 4 <= 4 then (S 4) <= 5 NO\n  if 4 <= 4 then 4 <= (S 4) YES\n  if (S 4) <= (S 5) then 4 <= 5 YES\n  if (S 4) <= (S 4) then (S 4) <= 4 NO\n  if (S 4) <= (S 4) then 4 <= (S 4) YES\n  if 4 <= 5 then (S 4) <= (S 5) YES\n  \n  if leb 4 (S 3) = true then leb 4 3 = true NO\n  if leb (S 3) 4 = true then leb 3 4 = true YES\n  if leb 4 4 = true then leb 4 (S 4) = true YES\n  if leb (S 4) (S 5) = true then leb 4 5 = true YES\n  if leb 4 5 = true then leb (S 4) (S 5) = true YES\n\n  O_le_n : 0 <= n.\n  le_n_Sm_le : n <= m -> n <= (S m)\n  n_le_m__Sn_le_Sm: n ≤ m → S n ≤ S m.\n  Sn_le_Sm__n_le_m: S n ≤ S m → n ≤ m.\n*)\n\nTheorem ble_Sn_m_n_m : forall n m,\n  leb (S n) m = true ->\n  leb n m = true.\nProof.\n  intros.\n  generalize dependent n.\n  induction m.\n  - intros n contra. inversion contra.\n  - intros n H. induction n.\n    + reflexivity.\n    + simpl. apply IHm. apply Sn_ble_Sm__n_ble_m in H. apply H.\nQed.\n\nTheorem ble_n_m_n_Sm : forall n m,\n  leb n m = true ->\n  leb n (S m) = true.\nProof.\n  intros.\n  apply ble_Sn_m_n_m. simpl. apply H. Qed.\n\nTheorem le_n_Sm_le : forall n m, \n  n <= m -> n <= (S m).\nProof.\n  intros.\n  apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply n_le_m__Sn_le_Sm. apply H.\nQed.\n\nTheorem le_Sn_m_le : forall n m, \n  (S n) <= m -> n <= m.\nProof.\n  intros.\n  induction m.\n  - inversion H.\n  - apply le_S. apply Sn_le_Sm__n_le_m in H. apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  - intros. apply O_le_n.\n  - intros m H. induction 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  leb n m = true.\nProof.\n  intros.\n  induction m.\n  - inversion H. reflexivity.\n  - inversion H.\n    + simpl. symmetry. apply leb_refl.\n    + apply ble_n_m_n_Sm. apply IHm. apply H1.\nQed.\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  intros. \n  apply leb_correct. \n  apply leb_complete in H. \n  apply leb_complete in H0.\n  apply le_trans with m.\n  - apply H.\n  - apply H0.\nQed.\n\n\n(* Exercise: 2 stars, optional (leb_iff) *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  intros n m. split.\n  - intros H. apply leb_complete. apply H.\n  - intros H. apply leb_correct. apply H.\nQed.\n\n(* Exercise: 3 stars, recommended (R_provability) *)\nInductive R : nat -> nat -> nat -> Prop :=\n  | c1 : R 0 0 0\n  | c2 : forall m n o, R m n o -> R (S m) n (S o)\n  | c3 : forall m n o, R m n o -> R m (S n) (S o)\n  | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o\n  | c5 : forall m n o, R m n o -> R n m o.\n\nLemma c2_inverse : forall m n o,\n  R (S m) n (S o) ->\n  R m n o.\nProof.\n  intros.\n  apply c3 in H. apply c4 in H. apply H.\nQed.\n\nLemma c3_inverse : forall m n o,\n  R m (S n) (S o) ->\n  R m n o.\nProof.\n  intros.\n  apply c2 in H. apply c4 in H. apply H.\nQed.\n\nLemma c4_inverse : forall m n o,\n  R m n o ->\n  R (S m) (S n) (S (S o)).\nProof.\n  intros.\n  apply c2 in H. apply c3 in H. apply H.\nQed.\n\nTheorem test_R1 :\n  R 1 1 2.\nProof.\n  apply c2. apply c3. apply c1.\nQed.\n\nTheorem test_R2 :\n  R 2 2 6.\nProof.\n  apply c2.\n  apply c3.\n  apply c2.\n  apply c3.\nAbort. (* Not Provable *)\n\n(* If we dropped constructor c5 from the definition of R, would the set of provable propositions change? Briefly (1 sentence) explain your answer.\n\nNo it wouldn't because proposition c2 and c3 already cover that scenario\n*)\n\n(* If we dropped constructor c4 from the definition of R, would the set of provable propositions change? Briefly (1 sentence) explain your answer.\n\nNot it wouldn't because proposition c4 increments m, n and o and the set of the rest of the proposition do not offer any convergence on o.\n*)\n\nLemma R_m_n_O : forall o,\n  R 0 0 o ->\n  o = 0.\nProof.\nAdmitted.\n\n\n(* Exercise: 3 stars, optional (R_fact) *)\nDefinition fR : nat -> nat -> nat :=\n  plus.\n\nExample test_R_fR_equ1:\n  R 2 3 5 <-> fR 2 3 = 5.\nProof.\n  split.\n  - reflexivity.\n  - intros. apply c2. apply c3. apply c2. apply c3. apply c3. apply c1.\nQed.\n\nLemma fR_O_n : forall n,\n  fR O n = n.\nProof.\n  intros. reflexivity.\nQed.\n\nLemma fR_n_O : forall n,\n  fR n O = n.\nProof. intros. induction n.\n  - reflexivity.\n  - simpl. apply eq_S. apply IHn.\nQed.\n\nLemma fR_m_Sn : forall m n,\n  fR m (S n) = S(fR m n).\nProof.\n  intros.\n  induction m.\n  - reflexivity.\n  - simpl. apply eq_S. apply IHm.\nQed.\n\nLemma fR_n_m_O : forall m n,\n  fR m n = 0 ->\n  m = 0 /\\ n = 0.\nProof. \n  intros. induction n.\n  - split.\n    + induction m.\n      * reflexivity.\n      * inversion H.\n    + reflexivity.\n  - split.\n    + induction m.\n      * reflexivity.\n      * inversion H.\n    + rewrite fR_m_Sn in H. inversion H.\nQed.\n\nLemma n_m_O_fR : forall m n,\n  m = 0 /\\ n = 0 ->\n  fR m n = 0.\nProof. \n  intros. induction n.\n  - destruct H. rewrite H. reflexivity.\n  - rewrite fR_m_Sn. inversion H. inversion H1.\nQed.\n\nTheorem R_equiv_fR : forall m n o,\n  R m n o <-> fR m n = o. \nProof.\nAbort.\n\n(* Exercise: 4 stars, advanced (subsequence) *)\nInductive subseq {X}: list X -> list X -> Prop :=\n  | sc_nil : forall l : list X, subseq [] l\n  | sc_eq : forall (x : X) (l1 l2:list X), subseq l1 l2 -> subseq (x :: l1) (x::l2)\n  | sc_eatl2 : forall (x : X) (l1 l2:list X), subseq l1 l2 -> subseq l1 (x :: l2).\n\nTheorem subseq_test1 : \n  subseq [1;2;3] [1;2;3].\nProof.\n  apply sc_eq. apply sc_eq. apply sc_eq. apply sc_nil.\nQed.\n\n\nTheorem subseq_test2 :\n  subseq [1;2;3] [1;1;1;2;2;3].\nProof.\n  apply sc_eq. apply sc_eatl2. apply sc_eatl2. apply sc_eq. apply sc_eatl2. apply sc_eq. apply sc_nil.\nQed.\n\nTheorem subseq_test3 :\n  subseq [1;2;3] [1;2;7;3].\nProof.\n  apply sc_eq. apply sc_eq. apply sc_eatl2. apply sc_eq. apply sc_nil.\nQed.\n\nTheorem subseq_test4 :\n  subseq [1;2;3] [5;6;1;9;9;2;7;3;8].\nProof.\n  apply sc_eatl2. apply sc_eatl2. apply sc_eq. \n  apply sc_eatl2. apply sc_eatl2. apply sc_eq.\n  apply sc_eatl2. apply sc_eq. apply sc_eatl2. \n  apply sc_nil.\nQed.\n\nTheorem subseq_test5 :\n  subseq [1;2;3] [1;2].\nProof.\n  apply sc_eq. apply sc_eq.\nAbort.\n\nTheorem subseq_test6 :\n  subseq [1;2;3] [].\nProof.\nAbort.\n\nTheorem subseq_test7 :\n  subseq [] [1;2].\nProof.\n  apply sc_nil.\nQed.\n\nTheorem subseq_refl {X:Type}: forall l : list X,\n  subseq l l.\nProof.\n  intros l.\n  induction l.\n  - apply sc_nil.\n  - apply sc_eq. apply IHl.\nQed.\n\nLemma sc_eatl2_inverse : forall (x : nat) (l1 l2 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (x :: l2).\nProof.\n  intros. apply sc_eatl2. apply H.\nQed.\n\nTheorem subseq_app {X}: forall l1 l2 l3 : list X,\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  intros.\n  induction H.\n  - apply sc_nil.\n  - simpl. apply sc_eq. apply IHsubseq.\n  - simpl. apply sc_eatl2. apply IHsubseq.\nQed.\n\nTheorem subseq_shrink : forall (x : nat) (l1 l2 : list nat),\n  subseq (x :: l1) l2 -> subseq l1 l2.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent l1.\n  induction l2.\n  - intros. inversion H.\n  - intros. apply sc_eatl2. inversion H.\n    + apply H1.\n    + apply IHl2 with x0. apply H2.\nQed.\n\nTheorem subseq_trans {X}: forall l1 l2 l3 : list X,\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H1 H2.\n  generalize dependent l1.\n  induction H2.\n  - intros. inversion H1. apply sc_nil.\n  - intros. inversion H1.\n    + intros. apply sc_nil.\n    + apply sc_eq. apply IHsubseq. apply H3.\n    + rewrite <- H0. apply sc_eatl2. apply IHsubseq. rewrite H0. apply H3.\n  - intros. apply IHsubseq in H1. apply sc_eatl2. apply H1.\nQed.\n\nTheorem subseq_nil {X}: forall l : list X,\n  subseq l [] -> l = [].\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - inversion H.\nQed.\n\n(* Exercise: 2 stars, optional (R_provability2) *)\n\nInductive R' : nat -> list nat -> Prop :=\n  | c'1 : R' 0 []\n  | c'2 : forall n l, R' n l -> R' (S n) (n :: l)\n  | c'3 : forall n l, R' (S n) l -> R' n l.\n\nExample test_R'1 : R' 2 [1;0].\nProof.\n  apply c'2. apply c'2. apply c'1.\nQed.\n\nExample test_R'2 : R' 1 [1;2;1;0].\nProof.\n  apply c'3. apply c'2. \n  apply c'3. apply c'3. apply c'2.\n  apply c'2.\n  apply c'2.\n  apply c'1.\nQed.\n\nExample test_R'3 : R' 6 [3;2;1;0].\nProof.\n  apply c'3.\nAbort.\n\n\n(* Case Study: Regular Experssions *)\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\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 s1 re1 re2,\n              exp_match s1 re2 ->\n              exp_match s1 (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\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof. apply MChar. Qed.\n\nExample reg_exp_ex12 : [1; 2] =~ App (Char 1) (Char 2).\nProof. \n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros contra.\n  inversion contra.\nQed.\n\nFixpoint reg_exp_of_list {T} (l : list T) :=\n  match l with\n  | [] => EmptyStr\n  | x :: l' => App (Char x) (reg_exp_of_list l')\n  end.\n\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  simpl.\n  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\nLemma MStar1 :\n  forall T s (re : @reg_exp T) ,\n         s =~ re ->\n         s =~ Star re.\nProof.\n  intros.\n  rewrite <- app_nil_r with (l:=s).\n  apply (MStarApp s [] re).\n  - apply H.\n  - apply MStar0.\nQed.\n\n(* Exercise: 3 stars (exp_match ex1) *)\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  unfold not.\n  intros T s contra.\n  inversion contra.\nQed.\n\nLemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),\n  s =~ re1 \\/ s =~ re2 ->\n  s =~ Union re1 re2.\nProof.\n  intros T s re1 re2 [H1 | H2].\n  - apply MUnionL. apply H1.\n  - apply MUnionR. apply H2.\nQed.\n\nLemma MApp' : forall T (s1 s2 : list T) (re1 re2 : @reg_exp T),\n  s1 =~ re1 /\\ s2 =~ re2 ->\n  s1 ++ s2 =~ App re1 re2.\nProof.\n  intros T s1 s2 re1 re2 [H1 H2].\n  apply MApp.\n  - apply H1.\n  - apply H2.\nQed.\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  intros.\n  induction ss.\n  - simpl. simpl in H. apply MStar0.\n  - simpl. apply MStarApp.\n    + simpl in H. apply H. left. reflexivity.\n    + simpl in H. apply IHss. intros. apply H. right. apply H0.\nQed.\n\nLemma app_plus : forall T x (l : list T),\n  x :: l = [x] ++ l.\nProof.\n  reflexivity.\nQed.\n\nLemma reg_exp_of_list_refl : forall T (s : list T),\n  s =~ reg_exp_of_list s.\nProof.\n  intros. induction s.\n  - simpl. apply MEmpty.\n  - simpl. rewrite app_plus. apply MApp.\n    + apply MChar.\n    + apply IHs.\nQed.\n\n(* Exercise: 4 stars, optional (reg_exp_of_list_spec) *)\n\nLemma reg_exp_of_list_empty : forall T (s : list T),\n  s = [] ->\n  [] =~ reg_exp_of_list s.\nProof.\n  intros. induction s.\n  - simpl. apply MEmpty.\n  - simpl. inversion H.\nQed.\n\nLemma reg_exp_of_list_basic : forall T (s1 s2 : list T),\n  s1 = s2 ->\n  s1 =~ reg_exp_of_list s2.\nProof.\n  intros.\n  generalize dependent s1.\n  induction s2.\n   - intros. simpl. rewrite H. apply MEmpty.\n   - intros. simpl. rewrite H. rewrite app_plus. apply (MApp [x] _ _).\n      + apply MChar.\n      + apply reg_exp_of_list_refl.\nQed.\n\nLemma reg_exp_of_list_basic_inv : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 ->\n  s1 = s2.\nProof.\n  intros.\n  generalize dependent s1.\n  induction s2 as [| x2].\n  - intros. simpl in H. inversion H. reflexivity.\n  - intros. inversion H. inversion H3. apply f_equal. apply IHs2. apply H4.\nQed.\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  split.\n  - apply reg_exp_of_list_basic_inv.\n  - apply reg_exp_of_list_basic.\nQed.\n\nFixpoint re_chars {T} (re : reg_exp) : list T :=\n  match re with\n  | EmptySet => []\n  | EmptyStr => []\n  | Char x => [x]\n  | App re1 re2 => re_chars re1 ++ re_chars re2\n  | Union re1 re2 => re_chars re1 ++ re_chars re2\n  | Star re => re_chars re\n  end.\n  \n\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  - apply Hin.\n  - apply Hin.\n  - simpl. rewrite In_app_iff in *.\n    destruct Hin as [Hin | Hin].\n    + left. apply (IH1 Hin).\n    + right. apply (IH2 Hin).\n  - simpl. rewrite In_app_iff. left. apply (IH Hin).\n  - simpl. rewrite In_app_iff. right. apply (IH Hin).\n  - destruct Hin.\n  - simpl. apply In_app_iff in Hin. \n    destruct Hin as [Hin | Hin].\n    + apply (IH1 Hin).\n    + apply (IH2 Hin).\nQed.\n\n(* Exercise: 4 stars (re_not_empty) *)\nFixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool :=\n  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char _ => true\n  | App re1 re2 => andb (re_not_empty re1) (re_not_empty re2)\n  | Union re1 re2 => orb (re_not_empty re1) (re_not_empty re2)\n  | Star _ => true\n  end.\n\n(* Compute (re_not_empty (Star (EmptySet))). *)\nCompute (re_not_empty (Char [1;2;3;4])).\nCompute (re_not_empty (App (Char 1) (EmptySet))).\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  intros T re. split.\n  { intros H. induction re.\n    - (* EmptySet *) inversion H. inversion H0.\n    - (* EmptyStr *) reflexivity.\n    - (* Char _ *) reflexivity.\n    - (* App _ _ *) simpl. rewrite andb_true_iff. split.\n      + (* re1 *) apply IHre1. inversion H. inversion H0. exists s1. apply H4.\n      + (* re2 *) apply IHre2. inversion H. inversion H0. exists s2. apply H5.\n    - (* Union _ _ *) simpl. apply orb_true_iff. inversion H. inversion H0.\n      + left. apply IHre1. exists x. apply H3.\n      + right. apply IHre2. exists x. apply H3.\n    - (* Star *) reflexivity. }\n    { induction re.\n      - (* EmptySet *) intros. inversion H.\n      - (* EmptyStr *) exists []. apply MEmpty.\n      - (* Char _ *) exists [t]. apply MChar.\n      - (* App _ _ *) intros. inversion H. apply andb_true_iff in H1. \n        destruct H1. apply IHre1 in H0. apply IHre2 in H1. \n        inversion H0. inversion H1. exists (x ++ x0). apply MApp.\n        + apply H2.\n        + apply H3.\n      - (* Union _ _ *) intros. inversion H. apply orb_true_iff in H1.\n        destruct H1.\n        + apply IHre1 in H0. inversion H0. exists x. apply MUnionL. apply H1.\n        + apply IHre2 in H0. inversion H0. exists x. apply MUnionR. apply H1.\n      - (* Star _ *) intros. exists []. apply MStar0. }\nQed.\n\n\n(* The remember tactic *)\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.\nProof.\n  induction re'.\n  - intros. inversion H.\n  - intros. inversion H.\n  - intros. inversion H.\n  - intros. inversion H.\n  - intros. inversion H.\n  - intros. inversion H. inversion H0. \n    + simpl. apply H1.\n    + subst. apply IHre'.\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  generalize dependent s2.\n  induction H1.\n  - (* MEmpty *) inversion Heqre'.\n  - (* MChar *) inversion Heqre'.\n  - (* MApp *) inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n  - (* MStar0 *) intros. simpl. apply H.\n  - (* MStarApp *) inversion Heqre'. intros. rewrite H0 in IHexp_match1. rewrite H0 in IHexp_match2. rewrite <- app_assoc. apply MStarApp.\n    + rewrite H0 in H1_. apply H1_.\n    + apply IHexp_match2.\n      * reflexivity.\n      * apply H.\nQed.\n\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  intros.\n  remember (Star re) as re'.\n  generalize dependent re.\n  induction H.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. exists []. split.\n    + reflexivity.\n    + intros. inversion H.\n  - intros. remember (s1 ++ s2) as ss. Admitted.\n\n\n(*\n  - intros. induction (s1 ++ s2).\n    + exists []. split.\n      * reflexivity.\n      * simpl. intros. inversion H1.\n    + exists [x :: l]. split.\n      * simpl. rewrite app_nil_r. reflexivity.\n      * simpl. destruct IHl. destruct H1. intros. apply H2. simpl in H3. destruct H3.\n        { -   \n\n  \n  \n  \n  intros. remember (s1 ++ s2) as ss. induction re.\n    + intros. inversion Heqre'. exists [s1 ++ s2]. split.\n      * simpl. symmetry. apply app_nil_r.\n      * rewrite H2. \n\n\n\n    exists [s1 ++ s2]. split.\n    + simpl. symmetry. apply app_nil_r.\n    + \n      intros. simpl in H1. destruct H1.\n      * \n\n*)\n(* \n  intros T s re.\n  remember (Star re) as re'.\n  generalize dependent re'.\n  induction re.\n  - intros. induction s. \n    + exists []. split.\n      * reflexivity.\n      * intros. inversion H0.\n    + exists ([x :: s]). split.\n      * simpl. rewrite app_nil_r. reflexivity.\n      * intros. simpl in H0. destruct H0.\n        { - inversion H0.\n    \n    exists [s]. split.\n    + simpl. symmetry. apply app_nil_r.\n    + intros. \n    inversion H.\n    + exists [s]. simpl. split.\n      * rewrite app_nil_r. apply H0.\n      * intros. induction Heqre'. apply MEmpty.\n\n\n\n\n  intros T s re.\n  remember (Star re) as re'.\n  generalize dependent re.\n  induction re'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'. \n    exists [s]. split.\n    + simpl. symmetry. apply app_nil_r.\n    + intros. inversion H.\n      * rewrite <- H2 in H. simpl in H0. \n      intros. simpl in H0. destruct H0.\n      * \n        rewrite Heqre' in H. apply MStar0. in H.\n\n\n\n\n\n\n\n\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. exists [s]. split.\n    + simpl. rewrite app_nil_r. reflexivity.\n    + apply IHre'. intros. simpl in H0. destruct H0.\n      * \n\n\n*)\n(* Almost succeeded\n  intros T s re H.\n  remember (Star re) as re'.\n  generalize dependent re.\n  induction H.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. inversion Heqre'.\n  - intros. exists []. split.\n    + reflexivity.\n    + intros. inversion H.\n  - intros. exists [s1 ++ s2]. split.\n    + simpl. symmetry. apply app_nil_r.\n    + simpl.\n      inversion Heqre'.\n      intros. simpl in H1. destruct H1.\n      * \n      apply IHexp_match2. rewrite <- H1.\n\n\n\n  - simpl. rewrite app_nil_r. reflexivity.\n  - apply MStar1 in H. induction H. \n    + intros. simpl in H. inversion H\n    + rewrite <- H0. Search Star. \n  \n  \n  \n  \n  \n  induction re'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'.\n    + inversion Heqre'. rewrite H1 in IHre'. apply IHre'.\n      { Search Star. induction re.\n        - inversion H.\n        Search MStar'. inversion Heqre'.\n*)\n\n(* Exercise: 5 stars, advanced (pumping) *)\nModule Pumping.\n\nFixpoint pumping_constant {T} (re : @reg_exp T) : nat :=\n  match re with\n  | EmptySet => 0\n  | EmptyStr => 1\n  | Char _ => 2\n  | App re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\nFixpoint napp {T} (n : nat) (l : list T) : list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\n  end.\n\nLemma napp_plus : forall T (n m : nat) (l : list T),\n  napp (n + m) l = napp n l ++ napp m l.\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. apply app_assoc.\nQed.\n\nLemma pumping: forall T (re : @reg_exp T) s,\n  s =~ re ->\n  pumping_constant re <= length s ->\n  exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\\n    s2 <> [] /\\\n    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n  Import Coq.omega.Omega.\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 *) simpl. omega.\n  - (* MChar *) simpl. omega.\n  - (* MApp *) simpl. intros. exists s1. exists s2. exists []. simpl. split.\n    + rewrite app_nil_r. reflexivity.\n    + split.\nAbort.\n\nEnd Pumping.\n\nTheorem filter_not_empty_In : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - simpl. intros. apply H. reflexivity.\n  - simpl. destruct (beq_nat n m) eqn:H.\n    + intros. left. apply beq_nat_true_iff in H. rewrite H. reflexivity.\n    + intros. right. apply IHl'. apply H0.\nQed.\n\nInductive reflect (P : Prop) : bool -> Prop :=\n  | ReflectT : P -> reflect P true\n  | ReflectF : ~P -> reflect P false.\n\nTheorem iff_reflect : forall P b, \n  (P <-> b = true) -> reflect P b.\nProof.\n  intros. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. unfold not. intros. inversion H0.\nQed.\n\n(* Exercise: 2 stars, recommended (reflect_iff) *)\nTheorem reflect_iff : forall P b,\n  reflect P b -> (P <-> b = true).\nProof.\n  intros P b H.\n  destruct b.\n  - split.\n    + intros. reflexivity.\n    + intros. inversion H. apply H1.\n  - split.\n    + intros. inversion H. exfalso. apply H1. apply H0.\n    + intros. inversion H0.\nQed.\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\nTheorem filter_not_empty_In' : forall n l,\n  filter (beq_nat n) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [| m l' IHl'].\n  - simpl. intros H. apply H. reflexivity.\n  - simpl. destruct (beq_natP n m) as [H | H].\n    + intros _. rewrite H. left. reflexivity.\n    + intros. unfold not in H. right. apply IHl'. apply H0.\nQed.\n\n(* Exercise: 3 stars, recommended (beq_natP_practice) *)\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  intros. induction l as [|m l' IHl'].\n  - simpl. unfold not. intros contra. apply contra.\n  - simpl. unfold not. intros. simpl in H. destruct (beq_natP n m) as [H1 | H1].\n    + inversion H.\n    + simpl in H. unfold not in H1. destruct H0.\n      * symmetry in H0. apply H1 in H0. apply H0.\n      * apply IHl' in H0.\n        { - apply H0. }\n        { - apply H. }\nQed.\n\n(* Additional Exercises *)\n(*Exercise: 3 stars, recommended (nostutter_defn) *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n  | NSEmpty : nostutter []\n  | NSSingleEl : forall n : X, nostutter [n]\n  | NSRepeated : forall (m n : X) (xs : list X), \n      m <> n -> nostutter (n :: xs) -> nostutter (m :: n :: xs).\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\nProof.\n  repeat constructor; apply beq_nat_false_iff; auto.\nQed.\n\nExample test_nostutter_2: nostutter (@nil nat).\nProof.\n  repeat constructor.\nQed.\n\nExample test_nostutter_3: nostutter [5].\nProof.\n  repeat constructor; apply beq_nat_false; auto.\nQed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\nProof.\n  intro.\n  repeat match goal with\n    h: nostutter _|- _ => inversion h; clear h; subst\n  end.\n  contradiction H1; auto.\nQed.\n\n(* Exercise: 4 stars, advanced (filter_challenge) *)\nInductive inordermerge {X:Type} : list X -> list X -> list X -> Prop :=\n  | IOMEmpty : inordermerge [] [] []\n  | IOMMatchesL1 : forall (n : X) (l1 l2 l : list X),\n      inordermerge l1 l2 l -> inordermerge (n :: l1) l2 (n :: l)\n  | IOMMatchesL2 : forall (n : X) (l1 l2 l : list X),\n      inordermerge l1 l2 l -> inordermerge l1 (n :: l2) (n :: l).\n\nExample test_inordermerge_1 : inordermerge [1;6;2] [4;3] [1;4;6;2;3].\nProof.\n  repeat constructor.\nQed.\n\nExample test_inordermerge_2 : inordermerge [1;6;2] [] [1;6;2].\nProof.\n  repeat constructor.\nQed.\n\nExample test_inordermerge_3 : not (inordermerge [1;2;3] [4;5;6] [1;4;6]).\nProof.\n  intro.\n  inversion H. clear H. subst.\n  inversion H3. clear H3. subst.\n  inversion H1.\nQed.\n\nLemma head_same {X:Type}: forall (x:X) (l1 l2 : list X),\n  l1 = l2 ->\n  x :: l1 = x :: l2.\nProof.\n  intros. simpl. inversion H. reflexivity.\nQed.\n\n\n(** **** Exercise: 3 stars (all_forallb) *)\n(** Inductively define a property [all] of lists, parameterized by a\n    type [X] and a property [P : X -> Prop], such that [all X P l]\n    asserts that [P] is true for every element of the list [l]. *)\nInductive all {X:Type} : (X -> Prop) -> list X -> Prop :=\n  | all_nil : forall (P:X -> Prop), all P []\n  | all_match : forall (x:X) (l:list X) (P:X -> Prop), P x -> all P l -> all P (x::l).\n\nExample test_all_1 : all ev [0;2;4].\nProof.\n  repeat constructor.\nQed.\n\nExample test_all_2: ~(all ev [2;3;4;5]).\nProof.\n  intro.\n  inversion H. clear H. subst.\n  inversion H4. clear H4. subst.\n  inversion H2. inversion H0.\nQed.\n\n\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Poly]: *)\nFixpoint forallb X (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: l' => test x && forallb X test l'\n  end.\n\n\nLemma all_app {X:Type}: forall (x:X) (l:list X) (P: X -> Prop),\n  all P (x :: l) ->\n  P x /\\ all P l.\nProof.\n  intros. split.\n  - inversion H. apply H3.\n  - inversion H. apply H4.\nQed.\n\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    Are there any important properties of the function [forallb] which\n    are not captured by your specification? *)\nTheorem all_forallb {X:Type} :\n  forall (test : X -> bool) (P: X -> Prop) (l : list X),\n  (forall n, test n = true /\\ P n) ->\n  all P l ->\n  forallb X test l = true.\nProof.\n  intros.\n  induction H0.\n  - reflexivity.\n  - simpl. apply andb_true_iff. split.\n    + destruct H with (n:=x). apply H2.\n    + apply IHall. apply H.\nQed.\n\nTheorem filter_challenge {X:Type} :\n  forall (l l1 l2: list X) (test:X->bool),\n  (forall x, In x l1 -> test x = true) ->\n  (forall x, In x l2 -> test x = false) ->\n  inordermerge l1 l2 l ->\n  filter test l = l1.\nProof.\n  intros l l1 l2 test Hl1 Hl2 H.\n  induction H.\n  - reflexivity.\n  - simpl. assert (test n = true) as C.\n    + apply Hl1. simpl. left. reflexivity.\n    + rewrite C. apply head_same. apply IHinordermerge.\n      * intros. apply Hl1. simpl. right. trivial.\n      * intros. apply Hl2. trivial.\n  - simpl. assert (test n = false) as C.\n    + apply Hl2. simpl. left. reflexivity.\n    + rewrite C. apply IHinordermerge.\n      * apply Hl1.\n      * intros. apply Hl2. simpl. right. apply H0.\nQed.\n\nTheorem subseq_pad_l2 : forall (x : nat) (l1 l2 : list nat),\n  subseq l1 l2 -> subseq l1 (x :: l2).\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent l2.\n  induction l1.\n  - intros. apply sc_nil.\n  - intros. simpl in *. apply sc_eatl2. apply H.\nQed.\n\n\n(* Exercise: 5 stars, advanced (filter_challenge_2) *)\nTheorem filter_challenge_2 {X} :\n  forall (ls l : list X) (test:X->bool),\n  subseq ls l ->\n  (forall n, In n ls -> test n = true) ->\n  length ls <= length (filter test l).\nProof.\n  intros ls l test Hsubseq G.\n  induction Hsubseq.\n  - apply O_le_n.\n  - simpl. assert (test x = true) as C.\n    + apply G. simpl. left. reflexivity.\n    + rewrite C. simpl. apply n_le_m__Sn_le_Sm. apply IHHsubseq.\n      intros. apply G. simpl. right. apply H.\n  - simpl. destruct (test x) eqn:C.\n    + simpl. apply le_S. apply IHHsubseq. intros. apply G. apply H.\n    + apply IHHsubseq. intros. apply G. apply H.\nQed.\n\n\n(* Exercise: 4 stars, optional (palindromes) *)\n\nInductive matchlast {X} : X -> list X -> list X -> Prop :=\n  | match_same : forall (x:X), matchlast x [x] []\n  | match_tail : forall (x y:X) (l m:list X), \n      matchlast x l m -> matchlast x (y :: l) (y :: m).\n\nInductive pal {X} : list X -> Prop :=\n  | pal_nil : pal []\n  | pal_single : forall x, pal [x]\n  | pal_match : forall (x:X) (l m:list X),\n      pal l -> matchlast x m l -> pal (x :: m).\n\nInductive pal2 {X} : list X -> Prop :=\n  | c : forall l, l = rev l -> pal2 l.\n\nLemma matchx_last {X} : forall (x:X) (m:list X),\n  matchlast x (m ++ [x]) m.\nProof.\n  induction m.\n  - simpl. apply match_same.\n  - simpl. apply match_tail. apply IHm.\nQed.\n\nTheorem pal_app_rev {X}: forall (l:list X),\n  pal (l ++ rev l).\nProof.\n  induction l.\n  - simpl. apply pal_nil.\n  - simpl. rewrite app_plus. apply pal_match with (l0:=(l ++ rev l)).\n    + apply IHl.\n    + rewrite app_assoc. inversion IHl.\n      * simpl. apply match_same.\n      * apply match_tail. apply match_same.\n      * simpl. apply match_tail. apply matchx_last.\nQed.\n\nLemma rev_l {X}: forall (x:X) (l:list X),\n  l = rev l ->\n  x :: l = rev l ++ [x].\nProof.\n  intros.\n  rewrite app_plus. symmetry. rewrite <- rev_involutive. \n  rewrite rev_app_distr. rewrite <- H. simpl.\n  symmetry. rewrite <- rev_involutive.\nAbort.\n\nTheorem pal2_rev {X}: forall (l:list X),\n  pal2 l -> l = rev l.\nProof.\n  induction l.\n  - intros. reflexivity.\n  - intros. simpl. rewrite app_plus. inversion H. simpl in H0.\n    rewrite <- H0. reflexivity.\nQed.\n\nLemma tail_same {X:Type}: forall (x:X) (l1 l2 : list X),\n  l1 = l2 ->\n  l1 ++ [x] = l2 ++ [x].\nProof.\n  intros. rewrite H. reflexivity.\nQed.\n\nTheorem pal2_app_rev {X}: forall (l:list X),\n  pal2 (l ++ rev l).\nProof.\n  intros. induction l.\n  - simpl. apply c. reflexivity.\n  - simpl. rewrite app_plus. apply c.\n    inversion IHl. rewrite rev_app_distr.\n    rewrite rev_app_distr. rewrite rev_app_distr.\n    rewrite rev_involutive. simpl. rewrite app_plus. symmetry.\n    rewrite app_plus. rewrite <- app_assoc. reflexivity.\nQed.\n\n\nLemma pal_prefix {X} : forall (x:X) (l1 l2:list X),\n  pal ([x] ++ l1) -> l1 = l2 ++ [x].\nProof.\n  Admitted.\n\n\nTheorem pal_rev {X}: forall (l:list X),\n  pal l -> l = rev l.\nProof.\n  intros.\n  inversion H.\n  - reflexivity.\n  - reflexivity.\n  - inversion H1.\n    + reflexivity.\n    + subst. simpl in *.\nAbort.\n\nTheorem test_pal_1 : pal [1].\nProof.\n  apply pal_single.\nQed.\n\nHint Resolve pal_nil pal_single pal_match match_same match_tail.\n\nTheorem test_pal_2 : pal [1;2;1].\nProof.\n  apply pal_match with (l:=[2]).\n  - apply pal_single.\n  - apply match_tail. apply match_same.\nQed.\n\nTheorem test_pal_3 : pal [1;2;3;2;1].\nProof.\n  apply pal_match with (l:=[2;3;2]).\n  - apply pal_match with (l:=[3]).\n    + apply pal_single.\n    + apply match_tail. apply match_same.\n  - apply match_tail. apply match_tail. apply match_tail. apply match_same.\nQed.\n\nTheorem test_pal_4 : pal [1;2;3;3;2;1].\nProof.\n  apply pal_match with (l:=[2;3;3;2]).\n  - apply pal_match with (l:=[3;3]).\n    + apply pal_match with (l:=[]).\n      * apply pal_nil.\n      * apply match_same.\n    + apply match_tail. apply match_tail. apply match_same.\n  - apply match_tail. apply match_tail. apply match_tail. apply match_tail. apply match_same.\nQed.\n\nLemma rev_eq_pal_length: forall (X: Type) (n: nat) (l: list X),\n  length l <= n -> l = rev l -> pal l.\nProof.\n  intros.\n  induction n.\n  - inversion H.\n    assert (G: l = []).\n    { - induction l.\n        + reflexivity.\n        + inversion H2. }\n    rewrite G. apply pal_nil.\n  - induction l.\n    + apply pal_nil. \n    + simpl in *. inversion H. \nAbort.\n\n(* Exercise: 5 stars, optional (palindrome_converse) *)\nTheorem palindrome_converse {X} : forall (l:list X),\n  l = rev l -> pal l.\nProof.\n  intros.\nAbort.\n\n(* Exercise: 4 stars, advanced, optional (NoDup) *)\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\nInductive NoDup {X}: list X -> Prop :=\n  | NoDup_nil : NoDup []\n  | NoDup_element : forall (x:X) (l:list X), NoDup l -> ~ In x l -> NoDup (x :: l).\n\nExample tests_nodup_1 : NoDup [1;2;3;4].\nProof.\n  apply NoDup_element.\n  - apply NoDup_element.\n    + apply NoDup_element.\n      * apply NoDup_element.\n        { - apply NoDup_nil. }\n        { - auto. }\n      * simpl. unfold not. intros. destruct H. inversion H. apply H.\n    + simpl. unfold not. intros. destruct H.\n      * inversion H.\n      * destruct H.\n        { - inversion H. }\n        { - apply H. }\n  - unfold not. intros. destruct H.\n    + inversion H.\n    + destruct H.\n      * inversion H.\n      * simpl in H. destruct H.\n        { - inversion H. }\n        { - apply H. }\nQed.\n\nExample tests_nodup_2 : NoDup [1;2;1].\nProof.\n  apply NoDup_element.\n  - apply NoDup_element.\n    + apply NoDup_element.\n      * apply NoDup_nil.\n      * simpl. auto.\n    + unfold not. intros. destruct H. inversion H. apply H.\n - unfold not. intros. destruct H. inversion H. Abort. \n\n\nFixpoint disjoint {X} (l1 l2: list X) : Prop :=\n  ~ exists x, In x l1 /\\ In x l2.\n\n\nLemma disjoint_empty {X:Type} : forall (l:list X), \n  disjoint l [].\nProof.\n  intros. induction l.\n  - simpl. unfold not. intros. destruct H. destruct H. apply H.\n  - simpl. unfold not. intros. destruct H. destruct H. apply H0.\nQed.\n\nLemma disjoint_refl_false {X} : forall (l:list X),\n  l <> [] -> \n  ~ disjoint l l.\nProof.\n  intros.\n  induction l.\n  - simpl. unfold not. intros. apply H. reflexivity. \n  - simpl. unfold not. intros. apply H0. exists x. split.\n    + left. reflexivity.\n    + left. reflexivity.\nQed.\n\nLemma In_empty {X:Type} : forall x:X,\n  ~ In x [].\nProof.\n  intros. unfold not. intros.\n  inversion H.\nQed.\n\n\nTheorem NoDup_disjoint_app {X} : forall l1 l2 : list X,\n  disjoint l1 l2 ->\n  NoDup (l1 ++ l2).\nProof.\n  intros. induction l2.\n  - induction l1.\n    + simpl. apply NoDup_nil.\n    + simpl. rewrite app_nil_r in *. apply NoDup_element.\n      * apply IHl1. apply disjoint_empty.\n      * unfold not. intros. induction IHl1. \n        { - inversion H0. }\n        { - apply IHn.\n            + apply disjoint_empty.\n            + unfold not in H1.\n      exists x. split.\n        { - simpl. left. reflexivity. }\n        { - simpl. \n\n  intros. induction l1.\n  - induction l2.\n    + apply NoDup_nil.\n    + apply NoDup_element.\n      * simpl in *. apply IHl2. unfold not in *. intros. destruct H0. destruct H0. apply H0.\n      * admit.\n  - induction l2.\n    + simpl. rewrite app_nil_r in *. apply NoDup_element.\n      * apply IHl1. apply disjoint_empty.\n      * destruct IHl1.\n        { - apply disjoint_empty. }\n        { - unfold not. intros. inversion H0. } \n        { - simpl. unfold not in *. intros. apply H0. destruct H1.\n            + rewrite H1. admit.\n            + \n\n\n\n\n\n\n\n\n  intros. \n  induction (l1 ++ l2).\n  - apply NoDup_nil.\n  - apply NoDup_element.\n    + apply IHl.\n    + unfold not. intros. induction l1.\n      * \n\n\n\n\n\n\n\n\n\n  intros. induction l2.\n  - induction l1.\n    + simpl. apply NoDup_nil.\n    + simpl. rewrite app_nil_r in *. apply NoDup_element.\n      * apply IHl1. apply disjoint_empty.\n      * unfold not. intros. induction H. exists x. split.\n        { - simpl. left. reflexivity. }\n        { - \n        \n        \n        \n        \n        \n        simpl. rewrite app_nil_r in IHl1. destruct IHl1.\n            + apply disjoint_empty.\n            + simpl in H0. apply H0.\n            + unfold not in H. apply H. inversion H0. \n              * inversion n.\n                { - apply In_empty.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n                 rewrite H1 in H0. rewrite app_plus in H0. Search In. apply In_app_iff in H0. destruct H0.\n                { - apply H. rewrite H1.\n\n\n              Search In. inversion H0. apply H. rewrite <- H1 in H0. inversion H0.\n                { - rewrite <- H1 in *. inversion H0. rewrite H2. apply In_empty.\n\n\n            destruct H. simpl in H0. destruct H0.\n              * rewrite H. apply \n\n\n\n\n\n\n\n  intros. induction l1.\n  - simpl in *. induction l2.\n    + apply NoDup_nil.\n    + apply NoDup_element.\n      * apply IHl2. unfold not in *. intros. destruct H0. destruct H0. apply H0.\n      * destruct H. exists x. split.\n        { - \n        unfold not in *. intros. apply H. exists x. split.\n        { - \n\n\n\n  unfold not in H. destruct H. exists \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", "meta": {"author": "prashantpawar", "repo": "logical-foundations", "sha": "8c2126869f2104e2fe38249e3b86de080ea12d2f", "save_path": "github-repos/coq/prashantpawar-logical-foundations", "path": "github-repos/coq/prashantpawar-logical-foundations/logical-foundations-8c2126869f2104e2fe38249e3b86de080ea12d2f/IndProp_psp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.7509895164555044}}
{"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(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n\nProof. simpl. reflexivity.  Qed.\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\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:  (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\n(** **** Exercise: 1 star, standard (nandb)   *)\nDefinition ref (b1:bool): bool:=\n  match b1 with\n  |true => false\n  |false => true\n  end.\nDefinition nandb (b1:bool) (b2:bool):bool:=\n   match b2 with\n   |true =>ref b1\n   |false =>true\n   end.\nExample test_nandb1:               (nandb true false) = true.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_nandb2:               (nandb false false) = true.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_nandb3:               (nandb false true) = true.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_nandb4:               (nandb true true) = false.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (andb3)   *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool:=\n    match b1 with\n    |false =>false\n    |true =>(andb b2 b3)\n    end.\nExample test_andb31: (andb3 true true true) = true.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_andb32:(andb3 false true true) = false.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_andb33:(andb3 true false true) = false.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\nExample test_andb34:(andb3 true true false) = false.\n(* FILL IN HERE *)Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Types *)\n\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(* ================================================================= *)\n(** ** New Types from Old *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\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 q => false\n  end.\n\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\n(* ================================================================= *)\n(** ** Tuples *)\n\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\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\nModule NatPlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nInductive nat' : Type :=\n  | stop\n  | tick (foo : nat').\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\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\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).\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, 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\nFixpoint factorial (n:nat) : nat:=\n  match n with\n    |O => S O\n    |S n' =>mult n (factorial n')\n  end.\nExample test_factorial1:          (factorial 3) = 6.\n   Proof. simpl. reflexivity. Qed.\nExample test_factorial2:          (factorial 5) = (mult 10 12).\n   Proof. 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\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, 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 need to.) *)\n\nDefinition ltb (n m : nat) : bool:=(n<=?m)&&ref(n=?m).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1:             (ltb 2 2) = false.\n  Proof. simpl. reflexivity. Qed.\nExample test_ltb2:             (ltb 2 4) = true.\n  Proof. simpl. reflexivity. Qed.\nExample test_ltb3:             (ltb 4 2) = false.\n  Proof. simpl. reflexivity. Qed.\n(** [] *)\n\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.\n  intros n. reflexivity. Qed.\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.\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\n(** **** Exercise: 1 star, standard (plus_id_exercise)  \n\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 H1.\n  intros H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  reflexivity. Qed.\n(** [] *)\n\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, standard (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 H1.\n  rewrite -> plus_1_l.\n  rewrite <- H1.\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(* ################################################################# *)\n(** * Proof by Case Analysis *)\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\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\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\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\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 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, standard (andb_true_elim2)  \n\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 b c.\n   intros H1.\nAbort.  \n(** [] *)\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  intros n. destruct n as [|n'] eqn:E.\n  -reflexivity.\nAbort.\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(* ================================================================= *)\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\n(* ################################################################# *)\n(** * More Exercises *)\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 b. destruct b eqn: Eb.\n  -rewrite -> H. rewrite ->H. reflexivity.\n  -rewrite -> H. rewrite ->H. reflexivity.\nQed.\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\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.\n  \nProof.\n  intros f.\n  intros H.\n  intros b. destruct b eqn: Eb.\n  -rewrite -> H. simpl. rewrite ->H. reflexivity.\n  -rewrite -> H. simpl. rewrite ->H. reflexivity.\nQed.\nFrom Coq Require Export String.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (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 b c.\n  destruct b.\n  -simpl. intros H. rewrite -> H. reflexivity.\n  -simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (binary) *)\n\nInductive bin : Type :=\n  | Z\n  | A (n : bin)\n  | B (n : bin).\n\nFixpoint incr (m:bin) : bin :=\n  match m with\n  |Z => B Z\n  |A n => B n\n  |B n => A (incr n)\n  end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  |Z => 0\n  |A m' => 2*( bin_to_nat m')\n  |B m' => 1+ 2* (bin_to_nat m')\n  end.\nExample test_bin_incr1 : (incr (B Z)) = A (B Z).\nProof. reflexivity. Qed.\nExample test_bin_incr2 : (incr (A (B Z))) = B (B Z).\nProof. reflexivity. Qed.\nExample test_bin_incr3 : (incr (B (B Z))) = A (A (B Z)).\nProof. reflexivity. Qed.\nExample test_bin_incr4 : bin_to_nat (A (B Z)) = 2.\nProof. reflexivity. Qed.\nExample test_bin_incr5 :\n        bin_to_nat (incr (B Z)) = 1 + bin_to_nat (B Z).\nProof. reflexivity. Qed.\nExample test_bin_incr6 :\n        bin_to_nat (incr (incr (B Z))) = 2 + bin_to_nat (B Z).\nProof. reflexivity. Qed.\nDefinition manual_grade_for_binary : option (nat*string) := None.\n(** [] *)\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.750989514600386}}
{"text": "Inductive Dec (p:Prop) : Type :=\n| isTrue : p  -> Dec p\n| isFalse: ~p -> Dec p\n.\n\nArguments isTrue {p}.\nArguments isFalse {p}.\n\nClass Decidable (p:Prop) := { dec : Dec p }.\n \nDefinition check (p:Prop) (d:Decidable p) : bool :=\n    if dec then true else false.\n\nArguments check _ {d}.\n\nInstance decTrue   : Decidable True   := { dec := isTrue I  }.\nInstance decFalse  : Decidable False  := { dec := isFalse (fun x => x) }.\n\nDefinition L1 : check True = true.\nProof. reflexivity. Qed.\n\nDefinition L2 : check False = false.\nProof. reflexivity. Qed.\n\nInstance decImp (p q:Prop) (d1:Decidable p) (d2:Decidable q) : Decidable (p -> q)\n    := { dec := \n            match dec with\n            | isTrue y  => isTrue (fun _ => y)\n            | isFalse y =>\n                match dec with\n                | isTrue x  => isFalse (fun f => y (f x))\n                | isFalse x => isTrue  (fun z => match x z with end)\n                end\n            end\n}.  \n\nDefinition L3 : check (~True) = false.\nProof. reflexivity. Qed.\n\nDefinition L4 : check (~False) = true.\nProof. reflexivity. Qed.\n\nDefinition L5 : check (True -> True) = true.\nProof. reflexivity. Qed.\n\nDefinition L6 : check (False -> True) = true.\nProof. reflexivity. Qed.\n\nInstance decAnd (p q:Prop) (d1:Decidable p) (d2:Decidable q) : Decidable (p /\\ q)\n    := { dec :=\n            match dec with\n            | isTrue x  =>\n                match dec with\n                | isTrue y  => isTrue (conj x y)\n                | isFalse y => isFalse \n                    (fun (H:p /\\ q) =>\n                        match H with\n                        | conj _ y' => y y'\n                        end)\n                end\n            | isFalse x => isFalse\n                (fun (H:p /\\ q) =>\n                    match H with\n                    | conj x' _ => x x'\n                    end)\n            end\n}.\n\nDefinition L8 : check (True /\\ True) = true.\nProof. reflexivity. Qed.\n\n\nDefinition L9 : check (True /\\ False) = false.\nProof. reflexivity. Qed.\n\n\nDefinition L10 : check (False /\\ True) = false.\nProof. reflexivity. Qed.\n\n\nDefinition L11 : check (False /\\ False) = false.\nProof. reflexivity. Qed.\n\nInstance decOr (p q:Prop) (d1:Decidable p) (d2:Decidable q) : Decidable (p \\/ q)\n    := { dec :=\n            match dec with\n            | isTrue x  => isTrue (or_introl x)\n            | isFalse x =>\n                match dec with\n                | isTrue y  => isTrue (or_intror y)\n                | isFalse y => isFalse\n                    (fun (H:p \\/q) =>\n                        match H with\n                        | or_introl x'  => x x'\n                        | or_intror y'  => y y'\n                        end)\n                end\n            end\n}.\n\nDefinition L12 : check (True \\/ True) = true.\nProof. reflexivity. Qed.\n\nDefinition L13 : check (True \\/ False) = true.\nProof. reflexivity. Qed.\n\nDefinition L14 : check (False \\/ True) = true.\nProof. reflexivity. Qed.\n\nDefinition L15 : check (False \\/ False) = false.\nProof. reflexivity. Qed.\n\n(* Should be able to import this from Peano_dec, not some name conflict appears *)\nDefinition eq_nat_dec : forall (m n:nat), {m = n} + {m <> n}.\nProof.\n    induction m as [|m IH]; destruct n as [|n].\n    - left. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (IH n) as [H|H].\n        + subst. left. reflexivity.\n        + right. intros H'. inversion H'. subst. apply H. \n          reflexivity.\nDefined. (* do  not use 'Qed' here, as we need to compute check                 *)\n\nInstance decEqNat (m n:nat) : Decidable (m = n) := { dec :=\n    match eq_nat_dec m n with\n    | left H    => isTrue H\n    | right H   => isFalse H\n    end\n}.\n\nDefinition L16 : check (0 = 0) = true.\nProof. reflexivity. Qed.\n\nDefinition L17 : check (0 <> 0) = false.\nProof. reflexivity. Qed.\n\nDefinition L18 : check (0 = 1) = false.\nProof. reflexivity. Qed.\n\nDefinition L19 : check (0 <> 1) = true.\nProof. reflexivity. Qed.\n\nDefinition L20 : check (3 <> 5) = true.\nProof. reflexivity. Qed.\n\nDefinition le_dec : forall (m n:nat), {m <= n} + {~ m <= n}.\nProof.\n    induction m as [|m IH]; intro n.\n    - left. revert n. induction n as [|n IH].\n        + apply le_n.\n        + apply le_S. assumption.\n    - destruct n as [|n].\n        + right. intros H. inversion H.\n        + destruct (IH n) as [H|H].\n            { left. apply le_n_S. assumption. }\n            { right. intros H'. apply H. apply le_S_n. assumption. }\nDefined. (* not 'Qed' !!  *)\n\nInstance decLeqNat (m n:nat) : Decidable (m <= n) := { dec :=\n    match le_dec m n with\n    | left H    => isTrue H\n    | right H   => isFalse H\n    end\n}.\n\nDefinition L21 : check (0 <= 0) = true.\nProof. reflexivity. Qed.\n\nDefinition L22 : check (~ 0 <= 0) = false.\nProof. reflexivity. Qed.\n\nDefinition L23 : check (3 <= 5) = true.\nProof. reflexivity. Qed.\n\nDefinition L24 : check (~ 3 <= 5) = false.\nProof. reflexivity. Qed.\n\nDefinition L25 : check (5 <= 3) = false.\nProof. reflexivity. Qed.\n\nDefinition L26 : check (~ 5 <= 3) = true.\nProof. reflexivity. Qed.\n\nDefinition eqb (m n:nat) (d:Decidable (m = n)) : bool :=\n    if dec then true else false.\n\nArguments eqb _ _ {d}.\n\nDefinition L27 : eqb 5 5 = true.\nProof. reflexivity. Qed.\n\nDefinition lt_dec : forall (m n:nat), {m < n} + {~ m < n}.\nProof. intros m n. unfold lt. apply le_dec. Defined.\n\nInstance decLtNat (m n:nat) : Decidable (m < n) := { dec :=\n    match lt_dec m n with\n    | left H    => isTrue H\n    | right H   => isFalse H\n    end\n}.\n\n\n(*\nCompute check (False -> False) _.\nCompute check (False -> True) _.\nCompute check (True -> True) _.\nCompute check (True -> False) _.\nCompute check ((True -> False) -> False) _.\n*)\n\nDefinition asTrueFalse (c:Prop) (d:Decidable c) : Prop :=\n    if dec then True else False.\n\nArguments asTrueFalse _ {d}.\n\nDefinition fromAsTrueFalse (c:Prop) (d:Decidable c) (q:asTrueFalse c) : c.\nProof.\n    unfold asTrueFalse in q. destruct dec as [H|H].\n    - exact H.\n    - contradiction.\nDefined.\n\nArguments fromAsTrueFalse _ {d}.\n\nDefinition fromAsTrueFalse2 : forall (c:Prop) (d:Decidable c) (q:asTrueFalse c), c.\nProof.\nrefine (\n    fun (c:Prop) (d:Decidable c) =>\n        match dec as d return (if d then True else False) -> c with\n        | isTrue H  => fun _      => H\n        | isFalse H => fun pFalse => \n            match pFalse with end\n        end\n).\nQed.\n\nNotation \"£ c\" := (fromAsTrueFalse c I) (at level 50).\n\nDefinition L28 : 0 <> 1 := £ (0 <> 1). \nDefinition L29 : check (0 <> 1 /\\ (5 < 2 \\/ 3 < 7)) = true.\nProof. reflexivity. Qed.\nDefinition L30 : (0 <> 1 /\\ (5 < 2 \\/ 3 < 7)) := £ (0 <> 1 /\\ (5 < 2 \\/ 3 < 7)).\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/Dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7509869304830591}}
{"text": "Require Export Poly.\nRequire Export Basics.\n\nCheck (2 + 2 = 4).\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true : plus_fact.\nProof. reflexivity. Qed.\n\nDefinition strange_prop1 : Prop :=\n  (2 + 2 = 5) -> (99 + 26 = 42).\nDefinition strange_prop2 : Prop :=\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. apply db_fri.\n  apply db_thu.\nQed.\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. intros d1 d2 d3 H1 H2 H3.\n  apply okd_before with d2.\n  apply okd_before with d3.\n  apply H1. apply H3. apply H2.\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.\nQed.\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\". simpl. intros n IHn. rewrite -> IHn.\n    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\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.\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\n(*\nfoo'_ind :\n  forall (X:Type) (P: foo' X -> Prop),\n    (forall (l : list X) (f : foo' X),\n      P f ->\n      P (C1 X l f) ->\n    P (C2 X) ->\n    forall f : foo' X, P f\n\n*)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev O\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.\nQed.\n\nDefinition four_ev : ev 4 := ev_SS 2 (ev_SS 0 ev_0).\n\nDefinition ev_plus4 : forall n, ev n -> ev (4+n) :=\n  fun (n:nat) =>\n    fun (e:ev n) =>\n       ev_SS (2+n) (ev_SS n e).\n\nTheorem ev_plus4' : forall n,\n    ev n -> ev (4 + n).\nProof.\n  intros. induction n as [| n'].\n  (*Case \"n = 0\".*) simpl. apply four_ev.\n  (*Case \"n = S n'\".*) simpl. apply ev_SS. apply ev_SS. apply H.\nQed.\n\nPrint ev_plus4'.\n\nTheorem double_even : forall n,\n    ev (double n).\nProof.\n  intros. induction n as [| n'].\n  (*Case \"n = 0\".*) simpl. apply ev_0.\n  (*Case \"n = S n'\".*) simpl. apply ev_SS. apply IHn'.\nQed.\n\n(*わかりませんですた*)\nPrint double_even.\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'.\nQed.\n\nTheorem ev_minus2_n : forall n,\n    ev n -> ev (pred (pred n)).\nProof.\n  intros n E. destruct n as [| n'].\n  Case \"n = 0\". simpl. apply ev_0.\n  Case \"n = S n'\". simpl. (*保留*)\nAdmitted.\n\nTheorem ev_even : forall n,\n    ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  Case \"E = ev_0\".\n    unfold even. reflexivity.\n  Case \"E = ev_SS n' E'\".\n    unfold even. apply IHE'.\nQed.\n\nTheorem ev_even_n : forall n,\n    ev n -> even n.\nProof.\n  intros n E. induction n as [| n'].\n  Case \"n = 0\".\n    unfold even. reflexivity.\n  Case \"n = S n'\".\n    unfold even. (*保留*)\nAdmitted.\n\n(*\nTheorem l : forall n,\n    ev n.\nProof.\n  intros n. induction n.\n  Case \"O\". simpl. apply ev_0.\n  Case \"S\".\nすべてのnについてev nは成り立たない\n*)\n\nTheorem ev_sum : forall n m,\n    ev n -> ev m -> ev (n+m).\nProof.\n  intros n m E F. induction E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply F.\n  Case \"E = ev_SS n' E'\".\n    simpl. apply ev_SS. apply IHE'.\nQed.\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'.\nQed.\n\nTheorem SSSSev_even : forall n,\n    ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E'].\n  inversion E' as [| n'' E'']. apply E''.\nQed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2+2=9.\nProof.\n  intros. inversion H.\n  inversion H1. inversion H3.\nQed.\n\nTheorem ev_minus2' : 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 m E F. generalize dependent m.\n  induction F as [| n' F'].\n  Case \"F = ev_0\". intros. apply E.\n  Case \"F = ev_SS n' F'\". intros.\n    inversion E. apply IHF'. apply 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 E F.\n(*わからん\n恐らくev_ev_evenとev_sumを利用するのだとは思う\n*)\nAdmitted.\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.\nQed.\n\nTheorem MyProp_0 : MyProp 0.\nProof.\n  apply MyProp3. apply MyProp3. simpl.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_plustwo : forall n:nat, MyProp n -> MyProp (S (S n)).\nProof.\n  intros. apply MyProp3. simpl.\n  apply MyProp2. 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'.\nQed.\n\nTheorem ev_MyProp : forall n:nat,\n    MyProp n -> ev n.\nProof.\n  intros n M. induction M.\n  Case \"M = MyProp1\". apply ev_SS. apply ev_SS. apply ev_0.\n  Case \"M = MyProp2\". apply ev_SS. apply ev_SS. apply IHM.\n  Case \"M = MyProp3\". apply ev_sum with (m:=2) in IHM.\n    rewrite -> plus_comm in IHM. simpl in IHM.\n    inversion IHM. inversion H0. apply H2.\n    apply ev_SS. apply ev_0.\nQed.\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.\nQed.\n\nTheorem plus_comm'' : forall n m : nat,\n    n + m = m + n.\nProof.\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.\nQed.\n\nCheck ev_ind.\n\n(*\nlist_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\nCheck list_ind.\n\n(*\nMyProp_ind\n  : forall P : nat -> Prop,\n  P 4 ->\n  (forall n : nat, MyProp n -> P n -> P (4 + n)) ->\n  (forall n : nat, MyProp (2 + n) -> P (2 + n) -> P n) ->\n  forall n : nat, MyProp n -> P n\n*)\n\nCheck MyProp_ind.\n\nTheorem ev_MyProp' : forall n:nat,\n    MyProp n -> ev n.\nProof.\n  apply MyProp_ind.\n  Case \"MyProp1\". apply ev_SS. apply ev_SS. apply ev_0.\n  Case \"MyProp2\". intros. apply ev_SS. apply ev_SS. apply H0.\n  Case \"MyProp3\". intros. apply SSev_even in H0. apply H0.\nQed.\n\n(*Definition MyProp_ev' : forall n:nat, ev n -> MyProp n :=*)\n\nModule P.\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\nInductive pal {X:Type} : list X -> Prop :=\n| p_n : pal []\n| p_c : forall v l, pal l -> pal (v :: (snoc l v))\n| p_r : forall v l, v :: l = snoc (rev l) v -> pal (v :: l)\n.\n(*\n１つ目と２つ目までは分かった３つ目がよくわからない\n現状はコレだけど，l = rev l -> pal l と特に大差無いしダメだと思う\n*)\n  \nTheorem rev_cons : forall (X:Type) (l:list X),\n    pal (l ++ rev l).\nProof.\n  intros. induction l as [| v l'].\n  Case \"l = []\". simpl. apply p_n.\n  Case \"l = v :: l'\".\n    simpl. rewrite <- snoc_with_append.\n    apply p_c. apply IHl'.\nQed.\n\nTheorem pal_equal_rev : forall (X:Type) (l:list X),\n    pal l -> l = rev l.\nProof.\n  intros X l P. induction P.\n  Case \"p_n\". simpl. reflexivity.\n  Case \"p_c\". simpl. rewrite -> rev_snoc.\n    simpl. rewrite <- IHP. reflexivity.\n  Case \"p_r\".\n    simpl. apply H.\nQed.\n\nTheorem rev_pal : forall (X:Type) (l:list X),\n    l = rev l -> pal l.\nProof.\n  intros. induction l as [| v l'].\n  Case \"l = []\". apply p_n.\n  Case \"l = v : l'\". simpl in H.\n    apply p_r. apply H.\nQed.\n\nInductive subseq : list nat -> list nat -> Prop :=\n| s_1 : forall l, subseq l []\n| s_2 : forall (n:nat) (l1 l2:list nat),\n    subseq l1 l2 -> subseq (n :: l1) (n :: l2)\n| s_3 : forall (n:nat) (l1 l2:list nat),\n    subseq l1 l2 -> subseq (n :: l1) l2\n. (*解けない->疲れた->保留する*)\n\nTheorem subseq_relf : forall l,\n    subseq l l.\nProof.\n  intros. induction l as [| n l'].\n  Case \"l = []\". apply s_1.\n  Case \"l = n :: l'\". apply s_2. apply IHl'.\nQed.\n\n(*元の練習問題ではfoo*)\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.\n(*\nfoo_ind\n     : forall (X Y : Set) (P : foo'' X Y -> Prop),\n       (forall x : X, P (foo1 X Y x)) ->\n       (forall y : Y, P (foo2 X Y y)) ->\n       (forall f : foo'' X Y, P f -> P (foo3 X Y f)) ->\n        forall f : foo'' X Y, P f\n*)\n\nCheck foo''_ind.\n\n(*\nbar_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*)\n(*元はbar*)\nInductive bar' : Set :=\n| bar1 : nat -> bar'\n| bar2 : bar' -> bar'\n| bar3 : bool -> bar' -> bar'.\n\nCheck bar'_ind.\n\nInductive 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\n(*\nno_longer_than_ind\n     : forall (X : Set) (P : list X -> nat -> Prop),\n       (forall n : nat, P [] n) ->\n       (forall (x : X) (l : list X) (n : nat),\n        no_longer_than X l n -> P l n ->\n                                P (x::l) (S n)) ->\n       (forall (l : list X) (n : nat),\n        no_longer_than X l n -> P l n ->\n                                P l (S n)) ->\n       forall (l : list X) (n : nat), no_longer_than X l n ->\n         P l n\n*)\n\nCheck no_longer_than_ind.\n\nInductive R : nat -> list nat -> Prop :=\n  | c1 : R 0 []\n  | c2 : forall n l, R n l -> R (S n) (n :: l)\n  | c3 : forall n l, R (S n) l -> R n l.\n(*\nR 2 [1,0]     well-formed\nR 1 [1,2,1,0] ill-formed\nR 6 [3,2,1,0] ill-formed\n*)", "meta": {"author": "MountainSeal", "repo": "coq_study", "sha": "8f5c27fa4f5ed0775d60c96210d60a5ece100327", "save_path": "github-repos/coq/MountainSeal-coq_study", "path": "github-repos/coq/MountainSeal-coq_study/coq_study-8f5c27fa4f5ed0775d60c96210d60a5ece100327/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7509869287817306}}
{"text": "Require Import ZArith.\nRequire Import Omega.\nRequire Import List.\nRequire Import FunctionalExtensionality.\n\nImport ListNotations.\n\nRequire Import listutils.\nRequire Import rollingsum.\nRequire Import seqi.\n\nDefinition fv (l : list Z) (i : nat) : Z :=\n  Z.abs(sum (firstn i l) - sum (skipn i l)).\n\nOpen Scope Z_scope.\n\nLemma fv_step : forall x xs n,\n  fv (x::xs) (S n) = Z.abs (x + sum (firstn n xs) - sum (skipn n xs)).\nProof.\nintros.\nunfold fv.\nauto.\nQed.\n\nTheorem fv_nil: forall n, fv [] n = 0.\nProof.\nunfold fv. intros.\nrewrite firstn_nil.\nrewrite skipn_nil.\nauto.\nQed.\n\n\nTheorem fv_0: forall l, fv l 0 = Z.abs (sum l).\nProof.\nintros.\nunfold fv. simpl. rewrite Z.abs_opp. auto.\nQed.\n\nFixpoint fulcrum_inside (curl : Z) (curr : Z) (curn : nat)\n                        (bestindex : nat) (bestdiff : Z)\n                        (remaining : list Z) : (nat*Z) :=\n  match remaining with\n  | nil => (bestindex, bestdiff)\n  | x::xs =>\n     let newl := curl + x in\n     let newr := curr - x in\n     let curdiff := Z.abs (newl - newr) in\n     let (nbestn, nbestd) := if curdiff <? bestdiff then (S curn, curdiff) else (bestindex, bestdiff) in\n       fulcrum_inside newl newr (S curn) nbestn nbestd xs\n  end.\n\nDefinition fulcrum (l : list Z) : nat * Z :=\n  fulcrum_inside 0 (sum l) (0%nat) (0%nat) (Z.abs (sum l)) l.\n\nTheorem fulcrum_inside_invariants:\n  forall remaining curl curr curn bestindex bestdiff n v,\n    fulcrum_inside curl curr curn bestindex bestdiff remaining = (n,v) ->\n      (bestindex <= curn)%nat ->\n      bestdiff <= Z.abs (curl - curr) ->\n      (n >= bestindex)%nat /\\ v <= bestdiff.\nProof.\ninduction remaining;intros.\n* simpl in *. inversion H. subst. split;omega.\n* simpl in H.\n  destruct (Z.abs (curl + a - (curr - a)) <? bestdiff) eqn:F.\n  + pose proof (IHremaining _ _ _ _ _ _ _ H).\n    destruct H2; try omega.\n    apply Z.ltb_lt in F.\n    split; try omega.\n  + pose proof (IHremaining _ _ _ _ _ _ _ H).\n    destruct H2; try omega.\n    apply Z.ltb_ge in F.\n    omega.\nQed.\n\nInductive Model : list Z -> nat -> nat -> nat -> Z -> Prop :=\n | SimpleEnd : forall lst curbest v curn,\n     v = fv lst curbest ->\n     curn = length lst ->\n     (curbest <= curn)%nat ->\n     Model lst curn curbest curbest v\n | SimpleChange : forall lst n curbest best v,\n     (n < length lst)%nat ->\n     fv lst (S n) < fv lst curbest ->\n     (curbest <= n)%nat ->\n     Model lst (S n) (S n) best v -> Model lst n curbest best v\n | SimpleStay : forall lst n curbest best v,\n     (n < length lst)%nat ->\n     fv lst (S n) >= fv lst curbest ->\n     (curbest <= n)%nat ->\n     Model lst (S n) curbest best v -> Model lst n curbest best v\n .\n\nExample test_hypo2:\n  let lst := [3;7;-4;8;2] in\n    forall n v,\n    fulcrum_inside 0 (sum lst) 0 0 (Z.abs (sum lst)) lst = (n,v) <->\n      Model lst 0 0 n v.\nProof.\nsimpl.\nsplit;intros.\n* inversion H. subst; clear H.\n  apply SimpleChange;simpl;compute; try omega;auto.\n  apply SimpleChange;simpl;compute; try omega;auto.\n  apply SimpleStay;unfold fv;simpl;try omega.\n  apply SimpleStay;unfold fv;simpl;try omega.\n  apply SimpleStay;unfold fv;simpl;try omega.\n  apply SimpleEnd; compute; auto.\n* inversion H;subst. 1: { compute in H1. inversion H1. } 2: { compute in H1. contradiction. }\n  inversion H3;subst. 1: { compute in H5. inversion H5. } 2: { compute in H5. contradiction. }\n  inversion H7;subst. compute in H9. inversion H9. compute in H9. inversion H9.\n  inversion H11;subst. compute in H13. inversion H13. compute in H13. inversion H13.\n  inversion H15;subst. compute in H17. inversion H17. compute in H17. inversion H17.\n  inversion H19;subst.\n  + compute. auto.\n  + simpl in H20. omega.\n  + simpl in H20. omega.\nQed.\n\nLemma sum_fv_artifacts: forall s l,\n  s + sum l - s = sum l.\nProof. intros. omega. Qed.\n\nLemma skipnS {A} : forall lst (x : A) xs curn, x :: xs = skipn curn lst -> xs = skipn (S curn) lst.\nProof.\nintros.\nreplace (S curn) with (1+curn)%nat by omega.\nrewrite <- skipn_comp.\nrewrite <- H.\nauto.\nQed.\n\nLemma uncons_eq {A} : forall (x : A) xs ys,\n   x::xs = x::ys <-> xs=ys.\nProof.\nsplit;intros.\n* inversion H. auto.\n* f_equal. auto.\nQed.\n\nLemma firstnS {A} : forall lst (x : A) xs curn, x :: xs = skipn curn lst ->\n     firstn (S curn) lst = firstn curn lst ++ [x].\nProof.\ninduction lst; intros.\n* rewrite skipn_nil in H. inversion H.\n* simpl. destruct curn.\n  + simpl. simpl in H. inversion H. auto.\n  + simpl firstn at 2. replace ((a :: firstn curn lst) ++ [x]) with (a:: (firstn curn lst ++ [x])) by auto.\n    erewrite <- IHlst. auto.\n    simpl in H. apply H.\nQed.\n\nTheorem Model_equivalent :\n  forall lst n v curn curbest,\n    (curn <= length lst)%nat ->\n    (n <= length lst)%nat ->\n    (curbest <= curn)%nat ->\n    fulcrum_inside (sum (firstn curn lst)) (sum (skipn curn lst)) curn curbest (fv lst curbest) (skipn curn lst) = (n,v) <->\n      Model lst curn curbest n v.\nProof with auto.\nsplit.\n{ \n  (* induction is performed on [skipn curn lst] so that [curn] and [lst] advance in lockstep *)\n  remember (skipn curn lst) as remaining.\n  generalize dependent curn. generalize dependent v. \n  generalize dependent n. generalize dependent lst.\n  generalize dependent curbest.\n  induction remaining as [|x xs];intros;simpl in H0.\n  * (* empty remaining list, we are in the SimpleEnd case *)\n    inversion H2. symmetry in Heqremaining.\n    apply skipn_all_2 in Heqremaining.\n    assert(curn = length lst). omega.\n    apply SimpleEnd;auto.\n    omega.\n  * (* some data is remaining, we are in a normal step *)\n    simpl in H2.\n    rewrite sum_fv_artifacts in H2.\n    (* either the current diff is lower than the best diff, or it is not *)\n    destruct (Z.abs (sum (firstn curn lst) + x - sum xs) <? fv lst curbest) eqn:F.\n    + (* SimpleChange situation *)\n      apply Z.ltb_lt in F.\n      (* if curn = length lst, it means we are at the final step, which is not possible, so we prove otherwise *)\n      destruct (curn =? length lst)%nat eqn:CN.\n      - apply Nat.eqb_eq in CN.\n        rewrite CN in Heqremaining.\n        rewrite skipn_all in Heqremaining.\n        inversion Heqremaining.\n      - apply Nat.eqb_neq in CN.\n        apply SimpleChange;try omega;auto.\n        unfold fv at 1.\n        rewrite (firstnS lst x xs);auto.\n        rewrite <- (skipnS lst x xs);auto.\n        rewrite <- sum_distributive.\n        simpl. rewrite Z.add_0_r...\n        { apply IHxs;auto;try omega.\n          * apply (skipnS _ _ _ _ Heqremaining).\n          * rewrite (firstnS lst x xs);auto.\n            rewrite <- sum_distributive. simpl. rewrite Z.add_0_r.\n            replace (fv lst (S curn)) with (Z.abs (sum (firstn curn lst) + x - sum xs));auto.\n            unfold fv.\n            rewrite (firstnS lst x xs);auto.\n            rewrite <- (skipnS lst x xs);auto.\n            rewrite <- sum_distributive.\n            f_equal.\n            simpl.\n            omega.\n        }\n   + (* SimpleStay situation *)\n      apply Z.ltb_ge in F.\n      (* if curn = length lst, it means we are at the final step, which is not possible, so we prove otherwise *)\n      destruct (curn =? length lst)%nat eqn:CN.\n      - apply Nat.eqb_eq in CN.\n        rewrite CN in Heqremaining.\n        rewrite skipn_all in Heqremaining.\n        inversion Heqremaining.\n      - apply Nat.eqb_neq in CN.\n        apply SimpleStay;try omega;auto.\n        unfold fv at 1.\n        rewrite (firstnS lst x xs);auto.\n        rewrite <- (skipnS lst x xs);auto.\n        rewrite <- sum_distributive.\n        simpl. rewrite Z.add_0_r. omega.\n        { apply IHxs;auto;try omega.\n          * apply (skipnS _ _ _ _ Heqremaining).\n          * rewrite (firstnS lst x xs);auto.\n            rewrite <- sum_distributive. simpl. rewrite Z.add_0_r.\n            replace (fv lst (S curn)) with (Z.abs (sum (firstn curn lst) + x - sum xs));auto.\n            unfold fv.\n            rewrite (firstnS lst x xs);auto.\n            rewrite <- (skipnS lst x xs);auto.\n            rewrite <- sum_distributive.\n            f_equal.\n            simpl.\n            omega.\n        }\n} {\n\nremember (skipn curn lst) as remaining eqn:REM.\nremember (firstn curn lst) as processed eqn:PRO.\n(*assert(PROREM: processed ++ remaining = lst). rewrite REM. rewrite PRO. apply firstn_skipn.*)\n\ngeneralize dependent n.\ngeneralize dependent v.\ngeneralize dependent curbest.\ngeneralize dependent curn.\ngeneralize dependent lst.\ngeneralize processed.\ninduction remaining;intros.\n* simpl.\n  symmetry in REM.\n  apply skipn_all_2 in REM.\n  assert(F: curn = length lst). omega.\n  rewrite F in H2.\n  inversion H2;subst;auto;omega.\n* clear processed.\n  destruct curn.\n  + (* curn = 0 *)\n    replace curbest with O in * by omega.\n    simpl.\n    rewrite sum_fv_artifacts.\n    inversion H2;subst.\n    - simpl in REM. rewrite <- REM in H4.\n      inversion H4.\n    - (* SimpleChange *)\n      simpl in *.\n      apply Z.ltb_lt in H4.\n      replace (Z.abs (a - sum remaining)) with (fv lst 1).\n      rewrite H4.\n      replace a with (sum [a]) at 1 by (simpl;omega).\n      apply IHremaining;auto;try (rewrite <- REM; auto).\n      rewrite <- REM.\n      rewrite fv_step. simpl. f_equal. omega.\n    - (* SimpleKeep *)\n      simpl in *.\n      Search ( _ < _ )%Z.\n      apply Z.ge_le in H4.\n      apply Z.ltb_ge in H4.\n      replace (Z.abs (a - sum remaining)) with (fv lst 1).\n      rewrite H4.\n      replace a with (sum [a]) at 1 by (simpl;omega).\n      apply IHremaining;auto;try (rewrite <- REM; auto).\n      rewrite <- REM.\n      rewrite fv_step. simpl. f_equal. omega.\n  + (* curn > 0 *)\n    pose proof (firstn_skipn (S curn) lst) as APP.\n    rewrite <- REM in APP.\n    inversion H2;subst.\n    - rewrite H4 in REM.\n      rewrite skipn_all in REM.\n      inversion REM.\n    - (* SimpleChange *)\n      unfold fulcrum_inside.\n      fold fulcrum_inside.\n      replace (Z.abs (sum (firstn (S curn) lst) + a - (sum (a::remaining) - a))) with (fv ((firstn (S curn) lst) ++ a :: remaining) (S (S curn))).\n      rewrite APP.\n      apply Z.ltb_lt in H4.\n      rewrite H4.\n      replace (sum (a::remaining) - a) with (sum remaining) by (simpl;omega).\n      replace (sum (firstn (S curn) lst) + a) with (sum ((firstn (S curn) lst) ++ [a])).\n      apply IHremaining;auto.\n      eapply skipnS. apply REM.\n      erewrite <- firstnS. auto. apply REM.\n      rewrite <- sum_distributive. simpl sum at 2. omega.\n      remember (firstn (S curn) lst) as processed eqn:PRO.\n      assert(length processed = S curn).\n      rewrite PRO.\n      rewrite firstn_length.\n      Search(Init.Nat.min).\n      apply Nat.min_l. auto.\n      (* :( *)\n      unfold fv.\n      erewrite firstnS. 2: { rewrite APP. apply REM. }\n      erewrite <- skipnS. 2: {rewrite APP. apply REM. }\n      rewrite firstn_app.\n      rewrite <- H7 at 1.\n      rewrite firstn_all.\n      rewrite H7.\n      rewrite Nat.sub_diag. simpl.\n      f_equal.\n      rewrite <- sum_distributive.\n      rewrite <- sum_distributive.\n      simpl.\n      omega.\n    - (* SimpleStay *)\n      unfold fulcrum_inside.\n      fold fulcrum_inside.\n      replace (Z.abs (sum (firstn (S curn) lst) + a - (sum (a::remaining) - a))) with (fv ((firstn (S curn) lst) ++ a :: remaining) (S (S curn))).\n      rewrite APP.\n      apply Z.ge_le in H4.\n      apply Z.ltb_ge in H4.\n      rewrite H4.\n      replace (sum (a::remaining) - a) with (sum remaining) by (simpl;omega).\n      replace (sum (firstn (S curn) lst) + a) with (sum ((firstn (S curn) lst) ++ [a])).\n      apply IHremaining;auto.\n      eapply skipnS. apply REM.\n      erewrite <- firstnS. auto. apply REM.\n      rewrite <- sum_distributive. simpl sum at 2. omega.\n      remember (firstn (S curn) lst) as processed eqn:PRO.\n      assert(length processed = S curn).\n      rewrite PRO.\n      rewrite firstn_length.\n      Search(Init.Nat.min).\n      apply Nat.min_l. auto.\n      (* :( *)\n      unfold fv.\n      erewrite firstnS. 2: { rewrite APP. apply REM. }\n      erewrite <- skipnS. 2: {rewrite APP. apply REM. }\n      rewrite firstn_app.\n      rewrite <- H7 at 1.\n      rewrite firstn_all.\n      rewrite H7.\n      rewrite Nat.sub_diag. simpl.\n      f_equal.\n      rewrite <- sum_distributive.\n      rewrite <- sum_distributive.\n      simpl.\n      omega.\n}\nQed.\n\n\nTheorem fulcrum_correct : forall i j l v,\n   (j < length l)%nat -> fulcrum l = (i, v) -> fv l j >= fv l i.\nProof.\n\nQed.", "meta": {"author": "bartavelle", "repo": "fulcrum-coq", "sha": "3f7293d538ef58cff88ebdae5c6a759b77610a52", "save_path": "github-repos/coq/bartavelle-fulcrum-coq", "path": "github-repos/coq/bartavelle-fulcrum-coq/fulcrum-coq-3f7293d538ef58cff88ebdae5c6a759b77610a52/fulcrum_faster.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7507667016869746}}
{"text": "\nRequire Import Reals Coquelicot.Coquelicot.\nRequire Import Streams.\n\nRequire Import Lra Omega.\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 with (f0 := fun _ => 0) (la := 0) (lb := 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 with (f0 := fun _ => 0) (la := 0) (lb := 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  apply pow2_gt_0; 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": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/Gaussian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.7507424266085957}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nLocal Open Scope R_scope.\n\n(*\nExample taken from:\nJohn Harrison, Verifying the Accuracy of Polynomial Approximations in HOL.\nIn TPHOLs, pages 137-152, 1997.\n*)\n\nGoal\n  forall x : R,\n    (-10831/1000000 <= x /\\ x <= 10831/1000000) ->\n    Rabs ((exp x - 1) - (x + (8388676/2^24) * x^2 + (11184876/2^26) * x^3))\n    <= (23/27) / (2^33).\nProof.\nintros x H.\n(*\nTime interval with (i_bisect x, i_autodiff x, i_prec 50, i_depth 16). (* 22 s *)\n*)\nTime interval with (i_bisect x, i_taylor x, i_degree 3, i_prec 50). (* 0.12 s *)\nQed.\n\n(* The timings above were obtained using Coq 8.9.1 *)\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-20140221.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7507424229568981}}
{"text": "Require Export Reals Qreals.\nRequire Import Lra.\nOpen Scope R_scope.\n\nLocal Lemma archimed_1\n     : forall r : R, r < IZR (up r).\nProof. apply archimed. Qed.\n\nLocal Hint Resolve archimed_1 : real.\n\nLemma inverses_of_nats_approach_0:\n  forall eps:R, eps > 0 -> exists n:nat, (n > 0)%nat /\\\n                                         / (INR n) < eps.\nProof.\n  intros.\n  assert (exists n:Z, (n>0)%Z /\\ / (IZR n) < eps).\n  {\n    exists (up (/ eps)).\n    split.\n    - assert (IZR (up (/ eps)) > 0).\n      {\n        eapply Rgt_trans;\n          auto with real rorders.\n      }\n      apply lt_0_IZR in H0.\n      now apply Z.lt_gt.\n    - pattern eps at 2.\n      rewrite <- Rinv_involutive; auto with real.\n      apply Rinv_lt_contravar; auto with real.\n      apply Rmult_lt_0_compat; auto with real.\n      apply Rlt_trans with (/ eps); auto with real.\n  }\n  destruct H0 as [[ | p | p ]];\n    destruct H0;\n    try inversion H0.\n  exists (nat_of_P p).\n  unfold IZR in H1.\n  rewrite <- INR_IPR in H1.\n  auto with real.\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; auto with real.\neapply Rle_lt_trans;\n    [ | eassumption ].\ndestruct (archimed x).\nlra.\nQed.\n\nLocal Notation \" ' x \" := (Zpos x) (at level 20, no associativity) : Z_scope.\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)) by\n  auto with real.\ndestruct (Z_interpolation (IZR (' n) * x)\n  (IZR (' n) * y)) as [m].\n- apply Rgt_minus in H.\n  assert (IZR (' n) * (y - x) > 1).\n  {\n    replace 1 with ((1 / (y-x)) * (y-x)) by\n      (field; auto with real).\n    now apply Rmult_gt_compat_r.\n  }\n  apply Rgt_minus in H2.\n  apply Rminus_gt.\n  match goal with H2: ?a > 0 |- ?b > 0 => replace b with a end;\n    lra.\n- exists m.\n  unfold Q2R.\n  simpl.\n  replace x with ((IZR (' n) * x) / IZR (' n)) by\n    (field; auto with real).\n  replace y with ((IZR (' n) * y) / IZR (' n)) by\n    (field; auto with real).\n  destruct H2.\n  split;\n    now apply Rmult_lt_compat_r.\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.\n{\n  apply lt_IZR, Rlt_trans with (/ (y - x)).\n  - apply Rgt_minus in H.\n    auto with real.\n  - apply archimed.\n}\nassert (/ (y - x) < IZR d) by apply archimed.\ndestruct d as [|d|]; try discriminate H0.\ndestruct (rational_interpolation x y d) as [n]; trivial.\n- replace (1 / (y-x)) with (/(y-x)); lra.\n- now exists (n # d).\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/RationalsInReals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7507180534027991}}
{"text": "(*\n * Hat problem.\n * A group of people are all given either a red or blue hat. They cannot communicate\n * with each other and they cannot see their own hat. They are eached asked to guess\n * what color hat they have and if any is wrong then they all lose. What strategy\n * allows them to win exactly 50% of the time?\n *)\n\nFrom Coq Require Import\n  PeanoNat.\nFrom FunProofs.Lib Require Import\n  Enumerate\n  Util.\nImport EqDecNotations.\n\nModule Hat.\n  Inductive Hat := Red | Blue.\n\n  #[export] Instance Hat_eq_dec : EqDec Hat.\n  Proof. constructor; decide equality. Defined.\n\n  Definition opp h := match h with Red => Blue | Blue => Red end.\n\n  Lemma opp_involutive : forall h, opp (opp h) = h.\n  Proof. now destruct h. Qed.\n\n  Lemma opp_neq : forall h, h <> opp h.\n  Proof. now destruct h. Qed.\nEnd Hat.\n\nNotation Hat := Hat.Hat.\nNotation Red := Hat.Red.\nNotation Blue := Hat.Blue.\n#[local] Existing Instance Hat.Hat_eq_dec.\n\n(* A strategy guesses a hat color given the visible hats. *)\nDefinition strategy := list Hat -> Hat.\n\n(* Each person guesses by applying the strategy to all hats but their own. *)\nDefinition guess (s : strategy) (hats : list Hat) :=\n  mapIdx (fun i => s (remove_nth i hats)) hats.\n\nDefinition count_hats color (hats : list Hat) :=\n  length (filter (fun h => h ==? color) hats).\n\n(* The optimal strategy guesses based on the number of red (or blue equivalently)\n   hats it can see. *)\nDefinition optimal : strategy := fun hats =>\n  if Nat.even (count_hats Red hats) then Blue else Red.\n\n(* A strategy wins if every person guesses correctly. *)\nDefinition wins (s : strategy) (hats : list Hat) : bool :=\n  (guess s hats) ==? hats.\n\nLemma count_hats_same hats color :\n  count_hats color (color :: hats) = S (count_hats color hats).\nProof. unfold count_hats; intros; cbn; simplify; auto. Qed.\n\nDefinition count_hats_opp hats color ocolor :\n  ocolor = Hat.opp color -> count_hats color (ocolor :: hats) = count_hats color hats.\nProof.\n  intros; subst; cbn; rewrite eqb_false; auto using Hat.opp_neq.\nQed.\n\nLemma guess_blue hats : optimal (Blue :: hats) = optimal hats.\nProof. unfold optimal; intros; rewrite count_hats_opp; auto. Qed.\n\nLemma guess_red hats : optimal (Red :: hats) = Hat.opp (optimal hats).\nProof.\n  unfold optimal; intros; cbn.\n  unfold count_hats.\n  destruct (length _); cbn -[Nat.even]; auto.\n  rewrite Nat.even_succ, <- Nat.negb_even.\n  destruct (Nat.even _); auto.\nQed.\n\nLemma apply_guess_blue hats :\n  guess optimal (Blue :: hats) = optimal hats :: guess optimal hats.\nProof.\n  unfold guess, mapIdx; intros; cbn.\n  rewrite <- seq_shift, map_map.\n  erewrite map_ext; auto.\nQed.\n\nLemma apply_guess_red hats :\n  guess optimal (Red :: hats) = optimal hats :: map Hat.opp (guess optimal hats).\nProof.\n  unfold guess, mapIdx; intros; cbn.\n  rewrite <- seq_shift, !map_map.\n  erewrite map_ext; auto.\n  intros; cbn; rewrite guess_red; auto.\nQed.\n\n(* For any set of n hats, the number with an even number of red hats is 2^(n-1). *)\nLemma enumerate_hats_half_even' n\n    (all := enumerate [Red; Blue] n)\n    (evens := filter (fun hats => Nat.even (count_hats Red hats)) all) :\n  length evens = 2 ^ (n - 1).\nProof.\n  induction n; cbn; auto.\n  cbn in IHn.\n  rewrite flat_map_concat_map, <- concat_filter_map, map_map.\n  erewrite map_ext with (g := fun x => if Nat.even (count_hats Red x) then _ else _).\n  2:{\n    intros; cbn [filter].\n    rewrite count_hats_same, count_hats_opp by auto.\n    rewrite Nat.even_succ, <- Nat.negb_even.\n    destruct (Nat.even _); cbn; auto.\n  }\n  erewrite (concat_length _ 1).\n  - rewrite map_length, enumerate_length; cbn.\n    rewrite Nat.sub_0_r, Nat.add_0_r; auto.\n  - rewrite Forall_forall; intros *.\n    rewrite in_map_iff.\n    intros (? & ? & ?); subst.\n    destruct (Nat.even _); cbn; auto.\nQed.\n\n(* For any set of n hats, exactly half have an even number of red hats. *)\nCorollary enumerate_hats_half_even n\n    (all := enumerate [Red; Blue] n)\n    (evens := filter (fun hats => Nat.even (count_hats Red hats)) all) :\n  0 < n -> 2 * length evens = length all.\nProof.\n  intros; subst all evens.\n  rewrite enumerate_hats_half_even', enumerate_length; cbn [length].\n  change 2 with (2 ^ 1) at 1.\n  rewrite <- Nat.pow_add_r.\n  replace (1 + (n - 1)) with n; lia.\nQed.\n\n(* If the number of red hats is even then the optimal strategy guarantees every\n   guess to be correct. Otherwise every guess is wrong. *)\nTheorem guess_wins_even hats :\n  guess optimal hats = if Nat.even (count_hats Red hats) then hats else map Hat.opp hats.\nProof.\n  induction hats as [| h hats]; intros; [cbn; auto |].\n  destruct h.\n  - cbn -[guess Nat.even].\n    rewrite Nat.even_succ, <- Nat.negb_even.\n    fold (count_hats Red hats).\n    rewrite apply_guess_red, IHhats; unfold optimal.\n    destruct (Nat.even _); cbn; auto.\n    erewrite map_map, map_ext, map_id; auto.\n    intros; rewrite Hat.opp_involutive; auto.\n  - cbn -[guess Nat.even].\n    fold (count_hats Red hats).\n    rewrite apply_guess_blue.\n    rewrite IHhats; unfold optimal.\n    destruct (Nat.even _); auto.\nQed.\n\n(* For any set of n hats, the optimal strategy guarantees a win for exactly half. *)\nTheorem guess_wins_half n\n    (all := enumerate [Red; Blue] n)\n    (win := filter (wins optimal) all) :\n  0 < n -> 2 * length win = length all.\nProof.\n  intros; subst all win; unfold wins.\n  rewrite <- enumerate_hats_half_even; auto.\n  erewrite filter_ext with (g := fun hats => Nat.even (count_hats Red hats)); auto.\n  intros hats; rewrite guess_wins_even.\n  destruct hats; auto.\n  destruct (Nat.even _); simplify; auto.\n  pose proof Hat.opp_neq.\n  cbn; rewrite eqb_false; congruence.\nQed.\n\n(* enumerate contains all sets of hats. *)\nCorollary enumerate_hats hats : In hats (enumerate [Red; Blue] (length hats)).\nProof.\n  intros; apply enumerate_finite.\n  intros []; cbn; auto.\nQed.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Hats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7507180298886177}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, advanced currying *)\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 := match p with (x,y) => f x y end.\n\nDefinition prod_uncurry'{X Y Z: Type}\n      (f: X -> Y -> Z)(p: X*Y): Z := f (fst p) (snd p).\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry: forall (X Y Z: Type)(f: X -> Y -> Z)(x: X)(y: Y),\n      prod_curry (prod_uncurry f) x y = f x y.\nProof.\n    intros. compute. 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. compute. destruct p. 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/currying.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7507146327191536}}
{"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 recalg computable.\n\nSet Implicit Arguments.\n\nSection relational_semantics.\n\n  (* Recursive functions can be interpreted in Coq as (functional) relations *)\n\n  Notation natfun := (fun k => vec nat k -> nat -> Prop).\n\n  Section defs.\n\n    Definition s_cst c : natfun 0 := fun _ x => x=c.\n    Definition s_zero  : natfun 1 := fun _ x => x=0.\n    Definition s_succ  : natfun 1 := fun v x => x=S (vec_head v).\n    Definition s_proj k (p : pos k) : natfun k := fun v x => vec_pos v p = x.\n\n    Variable k i : nat.\n    \n    Implicit Types (f : natfun k) (g : natfun (S k)) (h : natfun (S (S k))) (gj : vec (natfun i) k).\n\n    Definition s_comp f gj : natfun i := fun v x => exists gl, f gl x /\\ forall p, vec_pos gj p v (vec_pos gl p).\n      \n    (** the recursor s_rec_r f h n v x \n                 <-> exists x0,...,xn,  f      v  x0,\n                                        h (0##x0##v) x1,\n                                        h (1##x1##v) x2,\n                                        ...\n                                        h (.##..##v) xn, \n                                    and xn = x \n    **)\n   \n    Definition s_rec f h v := μ_rec f (fun v x y => h (x##y##v)) (vec_tail v) (vec_head v).\n\n    Definition s_min g v := μ_min (fun n => g (n##v)).\n\n  End defs.\n  \n  (** we define the semantics of a recursive algorithm of arity k \n      which is a relation vec nat k -> nat -> Prop, obviously functional (see below)\n      We interpret the constants ra_* with the corresponding s_* operator on relations\n   **) \n\n  Definition ra_rel : forall k, recalg k -> natfun k.\n  Proof.\n    apply recalg_rect with (P := fun k _ => natfun k).\n    exact s_cst.\n    exact s_zero.\n    exact s_succ.\n    exact s_proj.\n    intros ? ? ? ? hf hgj; exact (s_comp hf (vec_set_pos hgj)).\n    intros ? ? ? hf hg; exact (s_rec hf hg).\n    intros ? ? hf; exact (s_min hf).\n  Defined.\n  \n  Notation \"[| f |]\" := (@ra_rel _ f) (at level 0).\n \n  Fact ra_rel_fix_cst i :         [| ra_cst i     |]      = s_cst i.                   Proof. reflexivity. Qed.\n  Fact ra_rel_fix_zero :          [| ra_zero      |]      = s_zero.                    Proof. reflexivity. Qed.\n  Fact ra_rel_fix_succ :          [| ra_succ      |]      = s_succ.                    Proof. reflexivity. Qed.\n  Fact ra_rel_fix_proj k p :      [| @ra_proj k p |]      = s_proj p.                  Proof. reflexivity. Qed.\n  Fact ra_rel_fix_rec k f g :     [| @ra_rec k f g |]     = s_rec [|f|] [|g|].         Proof. reflexivity. Qed.\n  Fact ra_rel_fix_min k f :       [| @ra_min k f |]       = s_min [|f|].               Proof. reflexivity. Qed.\n  Fact ra_rel_fix_comp k i f gj : [| @ra_comp k i f gj |] = s_comp [|f|] (vec_map (fun x => [|x|]) gj).\n  Proof.\n    simpl ra_rel; f_equal.\n    apply vec_pos_ext; intros p.\n    rewrite vec_pos_set, vec_pos_map; trivial.\n  Qed.\n \n  Section functional.\n\n    Lemma s_cst_fun c : functional (s_cst c).\n    Proof. intros v x y Hx Hy; rewrite Hy; trivial. Qed.\n\n    Lemma s_zero_fun : functional s_zero.\n    Proof. intros v x y Hx Hy; rewrite Hy; trivial. Qed.\n\n    Lemma s_succ_fun : functional s_succ.\n    Proof. intros v x y Hx Hy; rewrite Hy; trivial. Qed.\n    \n    Lemma s_proj_fun k p : functional (@s_proj k p).\n    Proof.\n      intros v x y Hx Hy.\n      red in Hx, Hy. \n      rewrite <- Hx.\n      trivial.\n    Qed.\n\n    Variable k i : nat.\n    Implicit Types (f : natfun k) (gj : vec (natfun i) k) (g : natfun (S k)) (h : natfun (S (S k))).\n\n    Lemma s_comp_fun f gj : functional f -> (forall p, functional (vec_pos gj p)) -> functional (s_comp f gj).   \n    Proof.\n      intros f_fun gj_fun v x y [ gx [ Hx1 Hx2 ] ] [ gy [ Hy1 Hy2 ] ].\n      cutrewrite (gx = gy) in Hx1.\n      apply (@f_fun gy); trivial.\n      apply vec_pos_ext.\n      intros p; apply (gj_fun p v); auto.\n    Qed.\n\n    Lemma s_rec_fun f h : functional f -> functional h -> functional (s_rec f h).\n    Proof.\n      intros Hf Hh ? ? ?. \n      apply μ_rec_fun; auto.\n      intros ? ? ? ? ?; apply Hh.\n    Qed.\n\n    Lemma s_min_fun g : functional g -> functional (s_min g).\n    Proof.\n      intros Hg ? ? ?; apply μ_min_fun.\n      intros ? ? ?; apply Hg.\n    Qed.\n\n  End functional.\n  \n  Hint Resolve s_cst_fun s_zero_fun s_succ_fun s_proj_fun s_rec_fun s_min_fun.\n\n  (* [| f |] is a functional/deterministic relation *)\n\n  Theorem ra_rel_fun k (f : recalg k) v x y : [|f|] v x -> [|f|] v y -> x = y.\n  Proof.\n    revert v x y; change (functional [|f|]).\n    induction f; try (simpl; auto; fail).\n    rewrite ra_rel_fix_comp.\n    apply s_comp_fun; auto. \n    intro; rewrite vec_pos_map; auto.\n  Qed.\n\nEnd relational_semantics.\n\nNotation \"[| f |]\" := (@ra_rel _ f) (at level 0).\n\nSection recalg_coq.\n\n  (** This code compute the μ-recursive algorithm f into\n      Coq code that mimics the algorithm f \n\n      It needs a termination certificate in the form \n      of a proof that the predicate [|f|] v is inhabited\n\n      Notice: refine is used to allow better extraction\n        to OCaml code\n\n      This gives a VERY short proof of the totality of Coq !!!\n   *)\n\n  Fixpoint ra_compute k (ra : recalg k) : forall v, computable ([|ra|] v).\n  Proof.\n    destruct ra as [ n | | | k p | k i f gj | k f g | k f ]; intros v Hv.\n\n    exists n; reflexivity.\n    exists 0; reflexivity.\n    exists (S (vec_head v)); reflexivity.\n    exists (vec_pos v p); reflexivity.\n    \n    refine (match @vec_compute _ _ (fun f y => [|f|] v y) \n                                   (fun p => match p with exist _ w Hw => ra_compute _ _ v _ end) \n                                   _ gj _ with\n      | exist _ w Hw => match ra_compute _ f w _ with\n        | exist _ x Hx => exist _ x _\n      end \n    end); trivial.\n    apply vec_reif with (R := fun p => [|vec_pos gj p|] v).\n      intros p.\n      destruct Hv as (q & w & _ & Hw).\n      specialize (Hw p); rewrite vec_pos_set in Hw.\n      exists (vec_pos w p); trivial.\n    destruct Hv as (q & w' & Hw1 & Hw2).\n      exists q; cutrewrite (w = w'); auto.\n      apply vec_pos_ext.\n      intros p; generalize (Hw p) (Hw2 p).\n      rewrite vec_pos_set; apply ra_rel_fun.\n    exists w; split; auto.\n      intros; rewrite vec_pos_set; apply Hw.\n\n    revert Hv; simpl; apply rec_compute.\n    intros ? ?; apply ra_rel_fun.\n    intros (w & Hw); simpl.\n    apply ra_compute; trivial.\n    intros ? ? ? ?; apply ra_rel_fun.\n    intros ? ? (w & Hw); apply ra_compute; simpl; auto.\n\n    revert Hv; simpl; apply min_compute; auto.\n    intros ? ? ?; apply ra_rel_fun.\n    intros (w & Hw); apply ra_compute; trivial.\n  Defined.\n\nEnd recalg_coq.\n\nSection Coq_is_total.\n  \n  Variables (k : nat) (f : recalg k) (Hf : forall v, exists x, [|f|] v x).\n\n  Theorem Coq_is_total : { cf | forall v, [|f|] v (cf v) }.\n  Proof.\n    exists (fun v => proj1_sig (ra_compute _ _ (Hf v))).\n    intros v; apply (proj2_sig (ra_compute _ _ (Hf v))).\n  Defined.\n\nEnd Coq_is_total.\n\nCheck ra_compute.\nPrint Assumptions ra_compute.\n\nPrint ra_compute.\n\nCheck Coq_is_total.\nPrint Assumptions Coq_is_total.\n\nPrint ra_compute.\n\nExtraction ra_compute.\n\nExtraction \"ra_coq.ml\" ra_compute Coq_is_total.\n\n\n    \n     \n \n\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/ra_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896813251345, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7506576723433183}}
{"text": "Section Session1_2021_Induction_Exercice_3.\n\n(* Déclaration d’un domaine pour les éléments des listes *)\nVariable A : Set.\n\n(* Définition du type inductif représentant les entiers naturels *) \nInductive naturel : Set :=\n  Zero : naturel\n  | Succ : naturel -> naturel.\n\n(* Déclaration du nom de la fonction somme *)\nVariable somme_spec : naturel -> naturel -> naturel.\n\n(* Spécification du comportement de somme pour Zero en premier paramètre *)\nAxiom somme_Zero : forall (n : naturel), (somme_spec Zero n) = n.\n\n(* Spécification du comportement de somme pour Succ en premier paramètre *)\nAxiom somme_Succ : forall (n m : naturel), (somme_spec (Succ n) m) = (Succ (somme_spec n m)).\n\n(* Preuve du comportement de somme pour Zero en second paramètre *)\nTheorem somme_Zero_droite : forall (v : naturel), (somme_spec v Zero) = v.\nProof.\nintro v.\ninduction v.\nrewrite somme_Zero.\nreflexivity.\nrewrite somme_Succ.\nrewrite IHv.\nreflexivity.\nQed.\n\n(* Preuve du comportement de somme pour Succ en second paramètre *)\nTheorem somme_Succ_droite : forall (m n : naturel), (somme_spec m (Succ n)) =  Succ (somme_spec m n).\nProof.\nintro m.\nintro n.\ninduction m.\nrewrite !somme_Zero.\nreflexivity.\nrewrite !somme_Succ.\nrewrite IHm.\nreflexivity.\nQed.\n\n(* Preuve que somme est commutative *)\nTheorem somme_commutative : forall (v1 v2 : naturel), (somme_spec v1 v2) = (somme_spec v2 v1).\nProof.\nintro v1.\nintro v2.\ninduction v1.\nrewrite !somme_Zero_droite.\nrewrite !somme_Zero.\nreflexivity.\nrewrite !somme_Succ_droite.\nrewrite !somme_Succ.\nrewrite IHv1.\nreflexivity.\nQed.\n\n(* Implantation de la fonction somme *)\nFixpoint somme_impl (v1 v2 : naturel) {struct v1} : naturel :=\n  match v1 with\n  | Zero => v2 \n  | Succ n => Succ (somme_impl n v2)\nend.\n\n(* Preuve que l'implantation de la fonction somme est correcte *)\nTheorem somme_correcte : forall (v1 v2 : naturel),\n   (somme_spec v1 v2) = (somme_impl v1 v2).\nProof.\nintros v1 v2.\ninduction v1.\nsimpl.\nrewrite somme_Zero.\nreflexivity.\nsimpl.\nrewrite somme_Succ.\nrewrite IHv1.\nreflexivity.\nQed.\n\nEnd Session1_2021_Induction_Exercice_3.\n", "meta": {"author": "nathF78", "repo": "Modelisation", "sha": "ee54d070f331f00fa213bc4aa1c2c1ba461c343a", "save_path": "github-repos/coq/nathF78-Modelisation", "path": "github-repos/coq/nathF78-Modelisation/Modelisation-ee54d070f331f00fa213bc4aa1c2c1ba461c343a/coq_exercice_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7505240240920861}}
{"text": "From mathcomp Require Import ssreflect.\nRequire Import Classical.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Logic.Description.\nRequire Import Coq.Logic.ClassicalDescription.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Sets.Finite_sets_facts.\nRequire Import Coq.Sets.Image.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.Arith.Mult.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Le.\n\nDefinition Injective {A B : Type} (f : A -> B) := forall x y, f x = f y -> x = y.\n\nDefinition Surjective {A B : Type} (f : A -> B) := forall y, exists x, f x = y.\n\nDefinition Bijective {A B : Type} (f : A -> B) := exists (g : B -> A), (forall x, g (f x) = x) /\\ (forall y, f (g y) = y).\n\nLemma InjSurjBij : forall (A B : Type) (f : A -> B), Injective f -> Surjective f -> Bijective f.\nProof.\nmove=> A B f H1 H2.\nsuff: (forall (b : B), {a : A | f a = b}).\nmove=> H3.\nexists (fun (b : B) => proj1_sig (H3 b)).\napply conj.\nmove=> x.\napply (H1 (proj1_sig (H3 (f x))) x).\napply (proj2_sig (H3 (f x))).\nmove=> y.\napply (proj2_sig (H3 y)).\nmove=> b.\napply (constructive_definite_description (fun (a : A) => f a = b)).\napply (proj1 (unique_existence (fun (a : A) => f a = b))).\napply conj.\napply (H2 b).\nmove=> a1 a2 H3 H4.\napply (H1 a1 a2).\nrewrite H4.\napply H3.\nQed.\n\nLemma BijInj : forall (A B : Type) (f : A -> B), Bijective f -> Injective f.\nProof.\nmove=> A B f.\nelim.\nmove=> g H1 a1 a2 H2.\nrewrite - (proj1 H1 a1).\nrewrite - (proj1 H1 a2).\nrewrite H2.\nreflexivity.\nQed.\n\nLemma BijSurj : forall (A B : Type) (f : A -> B), Bijective f -> Surjective f.\nProof.\nmove=> A B f.\nelim.\nmove=> g H1 b.\nexists (g b).\napply (proj2 H1 b).\nQed.\n\nLemma BijChain : forall (A B C : Type) (f : A -> B) (g : B -> C), Bijective f -> Bijective g -> Bijective (compose g f).\nProof.\nmove=> A B C f g.\nelim.\nmove=> fi H1.\nelim.\nmove=> gi H2.\nexists (fun (c : C) => fi (gi c)).\napply conj.\nmove=> a.\nrewrite (proj1 H2 (f a)).\napply (proj1 H1 a).\nmove=> c.\nunfold compose.\nrewrite (proj2 H1 (gi c)).\napply (proj2 H2 c).\nQed.\n\nLemma SurjChain : forall (A B C : Type) (f : A -> B) (g : B -> C), Surjective f -> Surjective g -> Surjective (compose g f).\nProof.\nmove=> A B C f g H1 H2 c.\nelim (H2 c).\nmove=> b H3.\nelim (H1 b).\nmove=> a H4.\nexists a.\nunfold compose.\nrewrite H4.\napply H3.\nQed.\n\nLemma InjChain : forall (A B C : Type) (f : A -> B) (g : B -> C), Injective f -> Injective g -> Injective (compose g f).\nProof.\nmove=> A B C f g H1 H2 a1 a2 H3.\napply (H1 a1 a2).\napply (H2 (f a1) (f a2) H3).\nQed.\n\nLemma ChainSurj : forall (A B C : Type) (f : A -> B) (g : B -> C), Surjective (compose g f) -> Surjective g.\nProof.\nmove=> A B C f g H1 c.\nelim (H1 c).\nmove=> a H2.\nexists (f a).\napply H2.\nQed.\n\nLemma ChainInj : forall (A B C : Type) (f : A -> B) (g : B -> C), Injective (compose g f) -> Injective f.\nProof.\nmove=> A B C f g H1 a1 a2 H2.\napply (H1 a1 a2).\nunfold compose.\nrewrite H2.\nreflexivity.\nQed.\n\nLemma InvUnique : forall (A B : Type) (f : A -> B) (g1 g2 : B -> A), ((forall x, g1 (f x) = x) /\\ (forall y, f (g1 y) = y)) -> ((forall x, g2 (f x) = x) /\\ (forall y, f (g2 y) = y)) -> g1 = g2.\nProof.\nmove=> A B f g1 g2 H1 H2.\napply functional_extensionality.\nmove=> x.\napply (BijInj A B f).\nexists g1.\napply H1.\nrewrite (proj2 H2 x).\napply (proj2 H1 x).\nQed.\n\nLemma BijectiveInvExist : forall (A B : Type) (f : A -> B), Bijective f -> {g : B -> A | (forall x, g (f x) = x) /\\ (forall y, f (g y) = y)}.\nProof.\nmove=> A B f H1.\napply constructive_definite_description.\napply (proj1 (unique_existence (fun (g : B -> A) => (forall x, g (f x) = x) /\\ (forall y, f (g y) = y)))).\napply conj.\nelim H1.\nmove=> g H2.\nexists g.\napply H2.\nmove=> g1 g2 H2 H3.\napply (InvUnique A B f g1 g2 H2 H3).\nQed.\n\nLemma sig_map : forall {T : Type} (P : T -> Prop) (x : {x : T | P x}) (y : {x : T | P x}), proj1_sig x = proj1_sig y -> x = y.\nProof.\nmove=> A P x y.\ncase x.\nmove=> xv xp.\ncase y.\nmove=> yv yp .\nsimpl.\nmove=> H1.\nsubst xv.\nrewrite (proof_irrelevance (P yv) yp xp).\nby [].\nQed.\n\nLemma CardinalSigSame : forall (T : Type) (A : Ensemble T) (n : nat), (cardinal T A n) <-> (cardinal {t : T | A t} (Full_set {t : T | A t}) n).\nProof.\nsuff: (forall (n : nat) (T : Type) (A : Ensemble T) (B : Ensemble T), cardinal T (Intersection T A B) n <-> cardinal {t : T | A t} (fun (x : {t : T | A t}) => B (proj1_sig x)) n).\nmove=> H1 T A n.\nsuff: (A = Intersection T A (Full_set T)).\nmove=> H2.\nrewrite {1} H2.\nsuff: ((Full_set {t : T | A t}) = (fun x : {t : T | A t} => (Full_set T) (proj1_sig x))).\nmove=> H3.\nrewrite H3.\napply (H1 n T A (Full_set T)).\napply Extensionality_Ensembles.\napply conj.\nmove=> a H3.\napply (Full_intro T (proj1_sig a)).\nmove=> t H3.\napply (Full_intro {t0 : T | A t0} t).\napply Extensionality_Ensembles.\napply conj.\nmove=> a H2.\napply (Intersection_intro T A (Full_set T) a H2 (Full_intro T a)).\nmove=> a.\nelim.\nmove=> a0 H2 H3.\napply H2.\nelim.\nmove=> T A B.\napply conj.\nmove=> H1.\nsuff: ((fun x : {t : T | A t} => B (proj1_sig x)) = Empty_set {t : T | A t}).\nmove=> H2.\nrewrite H2.\napply (card_empty {t : T | A t}).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H2.\napply False_ind.\nsuff: (In T (Empty_set T) (proj1_sig t)).\nelim.\nrewrite - (cardinal_invert T (Intersection T A B) 0 H1).\napply (Intersection_intro T A B (proj1_sig t)).\napply (proj2_sig t).\napply H2.\nmove=> x.\nelim.\nmove=> H1.\nsuff: (Intersection T A B = Empty_set T).\nmove=> H2.\nrewrite H2.\napply (card_empty T).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> t0 H2 H3.\napply False_ind.\nsuff: (In {t : T | A t} (Empty_set {t : T | A t}) (exist A t0 H2)).\nelim.\nrewrite - (cardinal_elim {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x)) 0 H1).\napply H3.\nmove=> t.\nelim.\nmove=> n H1 T A B.\napply conj.\nmove=> H2.\nelim (cardinal_invert T (Intersection T A B) (S n) H2).\nmove=> B0.\nelim.\nmove=> b H3.\nsuff: (In T A b).\nmove=> H4.\nsuff: ((fun x : {t : T | A t} => B (proj1_sig x)) = Add {t : T | A t} (fun x : {t : T | A t} => (fun t : T => B t /\\ t <> b) (proj1_sig x)) (exist A b H4)).\nmove=> H5.\nrewrite H5.\nsuff: (cardinal {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x) /\\ proj1_sig x <> b) n).\nmove=> H6.\napply (card_add {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x) /\\ proj1_sig x <> b) n H6 (exist A b H4)).\nmove=> H7.\napply (proj2 H7).\nreflexivity.\napply (proj1 (H1 T A (fun t : T => B t /\\ t <> b))).\nsuff: (Intersection T A (fun t : T => B t /\\ t <> b) = B0).\nmove=> H6.\nrewrite H6.\napply (proj2 (proj2 H3)).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> t0 H6 H7.\nsuff: (In T (Intersection T A B) t0).\nrewrite (proj1 H3).\nmove=> H8.\nsuff: (t0 <> b).\nelim H8.\nmove=> t1 H9 H10.\napply H9.\nmove=> t1.\nelim.\nmove=> H9.\napply False_ind.\napply H9.\nreflexivity.\napply (proj2 H7).\napply (Intersection_intro T A B t0 H6 (proj1 H7)).\nmove=> t H6.\napply (Intersection_intro T A (fun t : T => B t /\\ t <> b) t).\nsuff: (In T (Intersection T A B) t).\nelim.\nmove=> t0 H7 H8.\napply H7.\nrewrite (proj1 H3).\nleft.\napply H6.\napply conj.\nsuff: (In T (Intersection T A B) t).\nelim.\nmove=> t0 H7 H8.\napply H8.\nrewrite (proj1 H3).\nleft.\napply H6.\nmove=> H7.\napply (proj1 (proj2 H3)).\nrewrite - H7.\napply H6.\napply Extensionality_Ensembles.\napply conj.\nmove=> t H5.\nelim (classic (proj1_sig t = b)).\nmove=> H6.\nright.\nsuff: (t = exist A b H4).\nmove=> H7.\nrewrite H7.\napply (In_singleton {t0 : T | A t0} (exist A b H4)).\napply sig_map.\napply H6.\nmove=> H6.\nleft.\napply conj.\napply H5.\napply H6.\nmove=> t.\nelim.\nmove=> t0 H5.\napply (proj1 H5).\nmove=> t0 H5.\nunfold In.\nsuff: (In T (Intersection T A B) (proj1_sig t0)).\nelim.\nmove=> t1 H6 H7.\napply H7.\nrewrite (proj1 H3).\nelim H5.\nright.\napply (In_singleton T b).\nsuff: (In T (Intersection T A B) b).\nelim.\nmove=> t H4 H5.\napply H4.\nrewrite (proj1 H3).\nright.\napply (In_singleton T b).\nmove=> H2.\nelim (cardinal_invert {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x)) (S n) H2).\nmove=> B0.\nelim.\nmove=> b H3.\nsuff: (Intersection T A B = Add T (Intersection T A (fun (t : T) => exists (H : A t), B0 (exist A t H))) (proj1_sig b)).\nmove=> H4.\nrewrite H4.\nsuff: (cardinal T (Intersection T A (fun t : T => exists H : A t, B0 (exist A t H))) n).\nmove=> H5.\napply (card_add T (Intersection T A (fun t : T => exists H : A t, B0 (exist A t H))) n H5 (proj1_sig b)).\nmove=> H6.\nsuff: (forall (H : A (proj1_sig b)), ~ B0 (exist A (proj1_sig b) H)).\nelim H6.\nmove=> t H7 H8 H9.\nelim H8.\nmove=> H10 H11.\napply (H9 H10 H11).\nmove=> H7 H8.\napply (proj1 (proj2 H3)).\nsuff: (b = (exist A (proj1_sig b) H7)).\nmove=> H9.\nrewrite H9.\napply H8.\napply sig_map.\nreflexivity.\napply (proj2 (H1 T A (fun t : T => exists H : A t, B0 (exist A t H)))).\nsuff: ((fun x : {t : T | A t} => exists H : A (proj1_sig x), B0 (exist A (proj1_sig x) H)) = B0).\nmove=> H5.\nrewrite H5.\napply (proj2 (proj2 H3)).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> H5 H6.\nsuff: (t = (exist A (proj1_sig t) H5)).\nmove=> H7.\nrewrite H7.\napply H6.\napply sig_map.\nreflexivity.\nmove=> t H5.\nexists (proj2_sig t).\nsuff: ((exist A (proj1_sig t) (proj2_sig t)) = t).\nmove=> H6.\nrewrite H6.\napply H5.\napply sig_map.\nreflexivity.\napply Extensionality_Ensembles.\napply conj.\nmove=> t H4.\nelim (classic (t = proj1_sig b)).\nmove=> H5.\nright.\nrewrite H5.\napply (In_singleton T (proj1_sig b)).\nmove=> H5.\nleft.\nsuff: (t <> proj1_sig b).\nelim H4.\nmove=> t0 H6 H7 H8.\napply (Intersection_intro T A (fun t1 : T => exists H : A t1, B0 (exist A t1 H)) t0 H6).\nexists H6.\nsuff: (~ In {t : T | A t} (Singleton {t : T | A t} b) (exist A t0 H6)).\nsuff: (In {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x)) (exist A t0 H6)).\nrewrite (proj1 H3).\nelim.\nmove=> t1 H9 H10.\napply H9.\nmove=> t1 H9 H10.\napply False_ind.\napply (H10 H9).\napply H7.\nmove=> H9.\napply H8.\nsuff: (exist A t0 H6 = b).\nmove=> H10.\nrewrite - H10.\nreflexivity.\nelim H9.\nreflexivity.\napply H5.\nmove=> t.\nelim.\nmove=> t0.\nelim.\nmove=> t1 H4 H5.\napply (Intersection_intro T A B t1 H4).\nelim H5.\nmove=> H6 H7.\nsuff: (In {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x)) (exist A t1 H6)).\napply.\nrewrite (proj1 H3).\nleft.\napply H7.\nmove=> t0.\nelim.\napply (Intersection_intro T A B (proj1_sig b)).\napply (proj2_sig b).\nsuff: (In {t : T | A t} (fun x : {t : T | A t} => B (proj1_sig x)) b).\napply.\nrewrite (proj1 H3).\nright.\napply (In_singleton {t : T | A t} b).\nQed.\n\nLemma FiniteSigSame : forall (T : Type) (A : Ensemble T), (Finite T A) <-> (Finite {t : T | A t} (Full_set {t : T | A t})).\nProof.\nmove=> T A.\napply conj.\nmove=> H1.\nelim (finite_cardinal T A H1).\nmove=> n H2.\napply (cardinal_finite {t : T | A t} (Full_set {t : T | A t}) n).\napply (proj1 (CardinalSigSame T A n) H2).\nmove=> H1.\nelim (finite_cardinal {t : T | A t} (Full_set {t : T | A t}) H1).\nmove=> n H2.\napply (cardinal_finite T A n).\napply (proj2 (CardinalSigSame T A n) H2).\nQed.\n\nLemma CountCardinalBijective : forall (T : Type) (N : nat), (exists (f : {n : nat | n < N} -> T), Bijective f) <-> cardinal T (Full_set T) N.\nProof.\nmove=> T N.\napply conj.\nelim.\nmove=> f H1.\nsuff: (forall (k : nat), (k <= N) -> cardinal T (fun (t : T) => exists (m : {n : nat | n < N}), proj1_sig m < k /\\ t = f m) k).\nmove=> H2.\nsuff: (Full_set T = (fun t : T => exists m : {n : nat | n < N}, proj1_sig m < N /\\ t = f m)).\nmove=> H3.\nrewrite H3.\napply (H2 N (le_n N)).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H3.\nelim (BijSurj {n : nat | n < N} T f H1 t).\nmove=> m H4.\nexists m.\napply conj.\napply (proj2_sig m).\nrewrite H4.\nreflexivity.\nmove=> t H3.\napply (Full_intro T t).\nelim.\nmove=> H2.\nsuff: ((fun t : T => exists m : {n : nat | n < N}, proj1_sig m < 0 /\\ t = f m) = Empty_set T).\nmove=> H3.\nrewrite H3.\napply (card_empty T).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> m H3.\napply False_ind.\napply (le_not_lt O (proj1_sig m)).\napply (le_0_n (proj1_sig m)).\napply (proj1 H3).\nmove=> t.\nelim.\nmove=> k H2 H3.\nsuff: ((fun t : T => exists m : {n : nat | n < N}, proj1_sig m < S k /\\ t = f m) = Add T (fun t : T => exists m : {n : nat | n < N}, proj1_sig m < k /\\ t = f m) (f (exist (fun n : nat => n < N) k H3))).\nmove=> H4.\nrewrite H4.\nsuff: (k <= N).\nmove=> H5.\napply (card_add T (fun t : T => exists m : {n : nat | n < N}, proj1_sig m < k /\\ t = f m) k (H2 H5) (f (exist (fun n : nat => n < N) k H3))).\nelim.\nmove=> m H6.\napply (le_not_lt k k (le_n k)).\nsuff: (k = proj1_sig (exist (fun n : nat => n < N) k H3)).\nmove=> H7.\nrewrite {1} H7.\nsuff: ((exist (fun n : nat => n < N) k H3) = m).\nmove=> H8.\nrewrite H8.\napply (proj1 H6).\napply (BijInj {n : nat | n < N} T f H1 (exist (fun n : nat => n < N) k H3) m).\napply (proj2 H6).\nreflexivity.\napply (le_trans k (S k) N (le_S k k (le_n k)) H3).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> m H4.\nelim (le_lt_or_eq (proj1_sig m) k).\nmove=> H5.\nleft.\nexists m.\napply conj.\napply H5.\napply (proj2 H4).\nmove=> H5.\nright.\nsuff: ((exist (fun n : nat => n < N) k H3) = m).\nmove=> H6.\nrewrite H6.\nrewrite (proj2 H4).\napply (In_singleton T (f m)).\napply sig_map.\nrewrite H5.\nreflexivity.\napply (le_S_n (proj1_sig m) k (proj1 H4)).\nmove=> t.\nelim.\nmove=> t0.\nelim.\nmove=> m H4.\nexists m.\napply conj.\napply (le_S (S (proj1_sig m)) k (proj1 H4)).\napply (proj2 H4).\nmove=> t0.\nelim.\nexists (exist (fun n : nat => n < N) k H3).\napply conj.\napply (le_n (S k)).\nreflexivity.\nmove=> H1.\nsuff: (forall (m : nat) (A : Ensemble T), cardinal T A m -> exists f : {n : nat | n < m} -> {t : T | A t}, Bijective f).\nmove=> H2.\nelim (H2 N (Full_set T) H1).\nmove=> f H3.\nexists (fun m : {n : nat | n < N} => proj1_sig (f m)).\napply (BijChain {n : nat | n < N} {t : T | Full_set T t} T f).\napply H3.\nexists (fun t : T => (exist (Full_set T) t (Full_intro T t))).\napply conj.\nmove=> t0.\napply sig_map.\nreflexivity.\nmove=> y.\nreflexivity.\nelim.\nmove=> A H2.\nrewrite (cardinal_elim T A 0 H2).\nsuff: (forall (n : nat), n < 0 -> False).\nmove=> H3.\nexists (fun m : {n : nat | n < 0} => match (H3 (proj1_sig m) (proj2_sig m)) with\nend).\nexists (fun t0 : {t : T | Empty_set T t} => match (proj2_sig t0) with\nend).\napply conj.\nmove=> m.\napply False_ind.\napply (H3 (proj1_sig m) (proj2_sig m)).\nmove=> t0.\nelim (proj2_sig t0).\nmove=> n.\napply (le_not_lt 0 n (le_0_n n)).\nmove=> k H2 A H3.\nelim (cardinal_invert T A (S k) H3).\nmove=> A0.\nelim.\nmove=> a H4.\nelim (H2 A0 (proj2 (proj2 H4))).\nmove=> f H5.\nsuff: (In T A a).\nmove=> H6.\nsuff: (forall (a0 : T), In T A0 a0 -> In T A a0).\nmove=> H7.\nexists (fun m : {n : nat | n < S k} => match excluded_middle_informative (proj1_sig m < k) with\n  | left H => exist A (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))) (H7 (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))) (proj2_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))))\n  | right _ => exist A a H6\nend).\napply InjSurjBij.\nmove=> m1 m2.\nelim (excluded_middle_informative (proj1_sig m1 < k)).\nmove=> H8.\nelim (excluded_middle_informative (proj1_sig m2 < k)).\nmove=> H9 H10.\napply sig_map.\nsuff: ((exist (fun n : nat => n < k) (proj1_sig m1) H8) = (exist (fun n : nat => n < k) (proj1_sig m2) H9)).\nmove=> H11.\nsuff: (proj1_sig m1 = proj1_sig (exist (fun n : nat => n < k) (proj1_sig m1) H8)).\nmove=> H12.\nrewrite H12.\nrewrite H11.\nreflexivity.\nreflexivity.\nsuff: (f (exist (fun n : nat => n < k) (proj1_sig m1) H8) = f (exist (fun n : nat => n < k) (proj1_sig m2) H9)).\nmove=> H11.\nelim H5.\nmove=> g H12.\nrewrite - (proj1 H12 (exist (fun n : nat => n < k) (proj1_sig m1) H8)).\nrewrite H11.\napply (proj1 H12 (exist (fun n : nat => n < k) (proj1_sig m2) H9)).\napply sig_map.\nsuff: (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m1) H8)) = proj1_sig (exist A (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m1) H8))) (H7 (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m1) H8))) (proj2_sig (f (exist (fun n : nat => n < k) (proj1_sig m1) H8)))))).\nmove=> H11.\nrewrite H11.\nrewrite H10.\nreflexivity.\nreflexivity.\nmove=> H9 H10.\napply False_ind.\napply (proj1 (proj2 H4)).\nsuff: (In T A0 (proj1_sig (exist A a H6))).\napply.\nrewrite - H10.\nsimpl.\napply (proj2_sig (f (exist (fun n : nat => n < k) (proj1_sig m1) H8))).\nmove=> H8.\nelim (excluded_middle_informative (proj1_sig m2 < k)).\nmove=> H9 H10.\napply False_ind.\napply (proj1 (proj2 H4)).\nsuff: (In T A0 (proj1_sig (exist A a H6))).\napply.\nrewrite H10.\nsimpl.\napply (proj2_sig (f (exist (fun n : nat => n < k) (proj1_sig m2) H9))).\nmove=> H9 H10.\napply sig_map.\nelim (le_lt_or_eq (proj1_sig m1) k).\nmove=> H11.\nelim (H8 H11).\nmove=> H11.\nelim (le_lt_or_eq (proj1_sig m2) k).\nmove=> H12.\nelim (H9 H12).\nmove=> H12.\nrewrite H12.\napply H11.\napply (le_S_n (proj1_sig m2) k (proj2_sig m2)).\napply (le_S_n (proj1_sig m1) k (proj2_sig m1)).\nmove=> a0.\nsuff: (In T (Add T A0 a) (proj1_sig a0)).\nmove=> H8.\nsuff: (exists m : {n : nat | n < S k}, proj1_sig match excluded_middle_informative (proj1_sig m < k) with\n  | left H => exist A (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))) (H7 (proj1_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))) (proj2_sig (f (exist (fun n : nat => n < k) (proj1_sig m) H))))\n  | right _ => exist A a H6\nend = proj1_sig a0).\nelim.\nmove=> m H9.\nexists m.\napply sig_map.\napply H9.\nelim H8.\nmove=> t H9.\nelim H5.\nmove=> g H10.\nsuff: (forall (n : nat), n < k -> n < S k).\nmove=> H11.\nexists (exist (fun n : nat => n < S k) (proj1_sig (g (exist A0 t H9))) (H11 (proj1_sig (g (exist A0 t H9))) (proj2_sig (g (exist A0 t H9))))).\nelim (excluded_middle_informative (proj1_sig (exist (fun n : nat => n < S k) (proj1_sig (g (exist A0 t H9))) (H11 (proj1_sig (g (exist A0 t H9))) (proj2_sig (g (exist A0 t H9))))) < k)).\nsimpl.\nmove=> H12.\nsuff: ((exist (fun n : nat => n < k) (proj1_sig (g (exist A0 t H9))) H12) = (g (exist A0 t H9))).\nmove=> H13.\nrewrite H13.\nrewrite (proj2 H10 (exist A0 t H9)).\nreflexivity.\napply sig_map.\nreflexivity.\nmove=> H12.\napply False_ind.\napply H12.\nsimpl.\napply (proj2_sig (g (exist A0 t H9))).\nmove=> n H11.\napply (le_S (S n) k H11).\nmove=> t.\nelim.\nexists (exist (fun m : nat => m < S k) k (le_n (S k))).\nelim (excluded_middle_informative (proj1_sig (exist (fun m : nat => m < S k) k (le_n (S k))) < k)).\nsimpl.\nmove=> H9.\napply False_ind.\napply (le_not_lt k k (le_n k) H9).\nmove=> H9.\nreflexivity.\nrewrite - (proj1 H4).\napply (proj2_sig a0).\nmove=> a0 H7.\nrewrite (proj1 H4).\nleft.\napply H7.\nrewrite (proj1 H4).\nright.\napply (In_singleton T a).\nQed.\n\nLemma CountFiniteBijective : forall (T : Type), (exists (N : nat) (f : {n : nat | n < N} -> T), Bijective f) <-> Finite T (Full_set T).\nProof.\nmove=> T.\napply conj.\nelim.\nmove=> N.\nelim.\nmove=> f H1.\napply (cardinal_finite T (Full_set T) N).\napply (proj1 (CountCardinalBijective T N)).\nexists f.\napply H1.\nmove=> H1.\nelim (finite_cardinal T (Full_set T) H1).\nmove=> N H2.\nexists N.\napply (proj2 (CountCardinalBijective T N) H2).\nQed.\n\nLemma CountCardinalSurjective : forall (T : Type) (N : nat) (f : {n : nat | n < N} -> T), Surjective f -> exists (M : nat), M <= N /\\ cardinal T (Full_set T) M.\nProof.\nmove=> T N f H1.\nsuff: (forall (k : nat), k <= N -> exists (M : nat), M <= k /\\ cardinal T (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f) M).\nmove=> H2.\nsuff: (Full_set T = Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < N) f).\nmove=> H3.\nrewrite H3.\napply (H2 N (le_n N)).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H3.\nelim (H1 t).\nmove=> m0 H4.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < N) f m0).\napply (proj2_sig m0).\nrewrite H4.\nreflexivity.\nmove=> t H3.\napply (Full_intro T t).\nelim.\nmove=> H2.\nexists O.\napply conj.\napply (le_n O).\nsuff: (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < 0) f = Empty_set T).\nmove=> H3.\nrewrite H3.\napply (card_empty T).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> m H3.\napply False_ind.\napply (le_not_lt O (proj1_sig m) (le_0_n (proj1_sig m)) H3).\nmove=> t.\nelim.\nmove=> k H2 H3.\nelim (H2 (le_trans k (S k) N (le_S k k (le_n k)) H3)).\nmove=> M H4.\nelim (classic (In T (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f) (f (exist (fun n : nat => n < N) k H3)))).\nmove=> H5.\nexists M.\napply conj.\napply (le_S M k (proj1 H4)).\nsuff: (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < S k) f = (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f)).\nmove=> H6.\nrewrite H6.\napply (proj2 H4).\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> m H6 y H7.\nrewrite H7.\nelim (le_lt_or_eq (S (proj1_sig m)) (S k) H6).\nmove=> H8.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f m).\napply (lt_S_n (proj1_sig m) k H8).\nreflexivity.\nmove=> H8.\nsuff: (m = (exist (fun n : nat => n < N) k H3)).\nmove=> H9.\nrewrite H9.\napply H5.\napply sig_map.\napply (eq_add_S (proj1_sig m) k H8).\nmove=> t.\nelim.\nmove=> m H6 y H7.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < S k) f m).\napply (le_S (S (proj1_sig m)) k H6).\napply H7.\nmove=> H5.\nexists (S M).\napply conj.\napply (le_n_S M k (proj1 H4)).\nsuff: (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < S k) f = Add T (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f) (f (exist (fun n : nat => n < N) k H3))).\nmove=> H6.\nrewrite H6.\napply (card_add T (Im {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f) M (proj2 H4) (f (exist (fun n : nat => n < N) k H3))).\napply H5.\napply Extensionality_Ensembles.\napply conj.\nmove=> t.\nelim.\nmove=> m H6 y H7.\nelim (le_lt_or_eq (S (proj1_sig m)) (S k) H6).\nmove=> H8.\nleft.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < k) f m).\napply (lt_S_n (proj1_sig m) k H8).\napply H7.\nmove=> H8.\nright.\nrewrite H7.\nsuff: ((exist (fun n : nat => n < N) k H3) = m).\nmove=> H9.\nrewrite H9.\napply (In_singleton T (f m)).\napply sig_map.\napply (eq_add_S k (proj1_sig m)).\nrewrite H8.\nreflexivity.\nmove=> t.\nelim.\nmove=> t0.\nelim.\nmove=> m H6 y H7.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < S k) f m).\napply (le_S (S (proj1_sig m)) k H6).\napply H7.\nmove=> t0.\nelim.\napply (Im_intro {n : nat | n < N} T (fun m : {n : nat | n < N} => proj1_sig m < S k) f (exist (fun n : nat => n < N) k H3)).\napply (le_n (S k)).\nreflexivity.\nQed.\n\nLemma CountFiniteSurjective : forall (T : Type) (N : nat) (f : {n : nat | n < N} -> T), Surjective f -> Finite T (Full_set T).\nProof.\nmove=> T N f H1.\nelim (CountCardinalSurjective T N f H1).\nmove=> n H2.\napply (cardinal_finite T (Full_set T) n (proj2 H2)).\nQed.\n\nLemma CountCardinalInjective : forall (T : Type) (N : nat) (f : T -> {n : nat | n < N}), Injective f -> exists (M : nat), M <= N /\\ cardinal T (Full_set T) M.\nProof.\nmove=> T N f H1.\nsuff: (forall (k : nat), k <= N -> exists (M : nat), M <= k /\\ cardinal T (fun t : T => proj1_sig (f t) < k) M).\nmove=> H2.\nsuff: (Full_set T = (fun t : T => proj1_sig (f t) < N)).\nmove=> H3.\nrewrite H3.\napply (H2 N (le_n N)).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H3.\napply (proj2_sig (f t)).\nmove=> t H3.\napply (Full_intro T t).\nelim.\nmove=> H2.\nexists O.\napply conj.\napply (le_n O).\nsuff: ((fun t : T => proj1_sig (f t) < 0) = Empty_set T).\nmove=> H3.\nrewrite H3.\napply (card_empty T).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H3.\napply False_ind.\napply (le_not_lt O (proj1_sig (f t)) (le_0_n (proj1_sig (f t))) H3).\nmove=> t.\nelim.\nmove=> k H2 H3.\nelim (H2 (le_trans k (S k) N (le_S k k (le_n k)) H3)).\nmove=> M H4.\nelim (classic (Inhabited T (fun t : T => proj1_sig (f t) = k))).\nelim.\nmove=> t H5.\nexists (S M).\napply conj.\napply (le_n_S M k (proj1 H4)).\nsuff: ((fun t0 : T => proj1_sig (f t0) < S k) = Add T (fun t : T => proj1_sig (f t) < k) t).\nmove=> H6.\nrewrite H6.\napply (card_add T (fun t : T => proj1_sig (f t) < k) M (proj2 H4) t).\nmove=> H7.\napply (lt_not_le (proj1_sig (f t)) k H7).\nrewrite H5.\napply (le_n k).\napply Extensionality_Ensembles.\napply conj.\nmove=> t0 H6.\nelim (le_lt_or_eq (S (proj1_sig (f t0))) (S k) H6).\nmove=> H7.\nleft.\napply (lt_S_n (proj1_sig (f t0)) k H7).\nmove=> H7.\nright.\nsuff: (t0 = t).\nmove=> H8.\nrewrite H8.\napply (In_singleton T t).\napply (H1 t0 t).\napply sig_map.\nrewrite H5.\napply (eq_add_S (proj1_sig (f t0)) k H7).\nmove=> t0.\nelim.\nmove=> t1 H6.\napply (le_S (S (proj1_sig (f t1))) k H6).\nmove=> t1.\nelim.\nunfold In.\nrewrite H5.\napply (le_n (S k)).\nmove=> H5.\nexists M.\napply conj.\napply (le_S M k (proj1 H4)).\nsuff: ((fun t : T => proj1_sig (f t) < S k) = (fun t : T => proj1_sig (f t) < k)).\nmove=> H6.\nrewrite H6.\napply (proj2 H4).\napply Extensionality_Ensembles.\napply conj.\nmove=> t H6.\nelim (le_lt_or_eq (S (proj1_sig (f t))) (S k) H6).\nmove=> H7.\napply (lt_S_n (proj1_sig (f t)) k H7).\nmove=> H7.\napply False_ind.\napply H5.\napply (Inhabited_intro T (fun t : T => proj1_sig (f t) = k) t).\napply (eq_add_S (proj1_sig (f t)) k H7).\nmove=> t.\napply (le_S (S (proj1_sig (f t))) k).\nQed.\n\nLemma CountFiniteInjective : forall (T : Type) (N : nat) (f : T -> {n : nat | n < N}), Injective f -> Finite T (Full_set T).\nProof.\nmove=> T N f H1.\nelim (CountCardinalInjective T N f H1).\nmove=> n H2.\napply (cardinal_finite T (Full_set T) n (proj2 H2)).\nQed.\n\nLemma CountInjectiveLe : forall (N M : nat) (f : {n : nat | n < N} -> {n : nat | n < M}), Injective f -> N <= M.\nProof.\nmove=> N M f H1.\nelim (CountCardinalInjective {n : nat | n < N} M f H1).\nmove=> K H2.\nsuff: (N = K).\nmove=> H3.\nrewrite H3.\napply (proj1 H2).\nrewrite (cardinal_is_functional {n : nat | n < N} (Full_set {n : nat | n < N}) K (proj2 H2) (Full_set {n : nat | n < N}) N).\nreflexivity.\napply (proj1 (CountCardinalBijective {n : nat | n < N} N)).\nexists (fun (m : {n : nat | n < N}) => m).\nexists (fun (m : {n : nat | n < N}) => m).\napply conj.\nmove=> x.\nreflexivity.\nmove=> y.\nreflexivity.\nreflexivity.\nQed.\n\nLemma BijectiveSigFull : forall (T : Type) (A : Ensemble T), (forall (t : T), In T A t) -> {f : T -> {t : T | In T A t} | (forall (t : T), t = proj1_sig (f t)) /\\ Bijective f}.\nProof.\nmove=> T A H1.\nexists (fun (t : T) => exist A t (H1 t)).\napply conj.\nmove=> t.\nreflexivity.\nexists (fun (t0 : {t : T | In T A t}) => proj1_sig t0).\napply conj.\nmove=> x.\nreflexivity.\nmove=> y.\napply sig_map.\nreflexivity.\nQed.\n\nLemma BijectiveSigFullInv : forall (T : Type) (A : Ensemble T), (forall (t : T), In T A t) -> {f : {t : T | In T A t} -> T | (forall (t0 : {t : T | In T A t}), proj1_sig t0 = f t0) /\\ Bijective f}.\nProof.\nmove=> T A H1.\nexists (fun (t0 : {t : T | In T A t}) => proj1_sig t0).\napply conj.\nmove=> t0.\nreflexivity.\nexists (fun (t : T) => exist A t (H1 t)).\napply conj.\nmove=> x.\napply sig_map.\nreflexivity.\nmove=> y.\nreflexivity.\nQed.\n\nLemma BijectiveSameSig : forall (T : Type) (A B : Ensemble T), A = B -> {f : {t : T | In T A t} -> {t : T | In T B t} | (forall (t0 : {t : T | In T A t}), proj1_sig t0 = proj1_sig (f t0)) /\\ Bijective f}.\nProof.\nmove=> T A B H1.\nrewrite H1.\nexists (fun (t0 : {t : T | In T B t}) => t0).\napply conj.\nmove=> t0.\nreflexivity.\nexists (fun (t0 : {t : T | In T B t}) => t0).\napply conj.\nmove=> x.\nreflexivity.\nmove=> y.\nreflexivity.\nQed.\n\nLemma BijectiveSigSig : forall (T : Type) (A B : Ensemble T), {f : {t : T | In T (Intersection T A B) t} -> {t0 : {t : T | In T A t} | In T B (proj1_sig t0)} | (forall (t0 : {t : T | In T (Intersection T A B) t}), proj1_sig t0 = proj1_sig (proj1_sig (f t0))) /\\ Bijective f}.\nProof.\nmove=> T A B.\nsuff: (forall (t0 : {t : T | In T (Intersection T A B) t}), In T A (proj1_sig t0)).\nmove=> H1.\nsuff: (forall (t0 : {t : T | In T (Intersection T A B) t}), In T B (proj1_sig t0)).\nmove=> H2.\nexists (fun (t0 : {t : T | In T (Intersection T A B) t}) => exist (fun (a : {t : T | In T A t}) => In T B (proj1_sig a)) (exist A (proj1_sig t0) (H1 t0)) (H2 t0)).\napply conj.\nmove=> t0.\nreflexivity.\nsuff: (forall (x : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)}),In T (Intersection T A B) (proj1_sig (proj1_sig x))).\nmove=> H3.\nexists (fun (x : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)}) => exist (Intersection T A B) (proj1_sig (proj1_sig x)) (H3 x)).\napply conj.\nmove=> x.\napply sig_map.\nreflexivity.\nmove=> y.\napply sig_map.\napply sig_map.\nreflexivity.\nmove=> x.\napply (Intersection_intro T A B (proj1_sig (proj1_sig x))).\napply (proj2_sig (proj1_sig x)).\napply (proj2_sig x).\nmove=> t0.\nelim (proj2_sig t0).\nmove=> x H2 H3.\napply H3.\nmove=> t0.\nelim (proj2_sig t0).\nmove=> x H2 H3.\napply H2.\nQed.\n\nLemma BijectiveSigSigInv : forall (T : Type) (A B : Ensemble T), {f : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)} -> {t : T | In T (Intersection T A B) t} | (forall (x : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)}), proj1_sig (proj1_sig x) = proj1_sig (f x)) /\\ Bijective f}.\nProof.\nmove=> T A B.\nsuff: (forall (x : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)}),In T (Intersection T A B) (proj1_sig (proj1_sig x))).\nmove=> H1.\nexists (fun (x : {t0 : {t : T | In T A t} | In T B (proj1_sig t0)}) => exist (Intersection T A B) (proj1_sig (proj1_sig x)) (H1 x)).\napply conj.\nmove=> x.\nreflexivity.\nsuff: (forall (t0 : {t : T | In T (Intersection T A B) t}), In T A (proj1_sig t0)).\nmove=> H2.\nsuff: (forall (t0 : {t : T | In T (Intersection T A B) t}), In T B (proj1_sig t0)).\nmove=> H3.\nexists (fun (t0 : {t : T | In T (Intersection T A B) t}) => exist (fun (a : {t : T | In T A t}) => In T B (proj1_sig a)) (exist A (proj1_sig t0) (H2 t0)) (H3 t0)).\napply conj.\nmove=> x.\napply sig_map.\napply sig_map.\nreflexivity.\nmove=> y.\napply sig_map.\nreflexivity.\nmove=> t0.\nelim (proj2_sig t0).\nmove=> x H3 H4.\napply H4.\nmove=> t0.\nelim (proj2_sig t0).\nmove=> x H3 H4.\napply H3.\nmove=> x.\napply (Intersection_intro T A B (proj1_sig (proj1_sig x))).\napply (proj2_sig (proj1_sig x)).\napply (proj2_sig x).\nQed.\n\nLemma ForallSavesBijective_dep : forall (T : Type) (A : T -> Type) (B : T -> Type) (F : forall (t : T), (A t) -> (B t)), (forall (t : T), Bijective (F t)) -> Bijective (fun (x : forall (t : T), (A t)) (t0 : T) => (F t0 (x t0))).\nProof.\nmove=> T A B F H1.\nsuff: (forall (t : T), {g : (B t) -> (A t) | (forall (x : A t), g ((F t) x) = x) /\\ (forall (y : B t), (F t) (g y) = y)}).\nmove=> H2.\nexists (fun (y : forall (t : T), B t) (t0 : T) => proj1_sig (H2 t0) (y t0)).\napply conj.\nmove=> x.\napply functional_extensionality_dep.\nmove=> t.\napply (proj1 (proj2_sig (H2 t)) (x t)).\nmove=> y.\napply functional_extensionality_dep.\nmove=> t.\napply (proj2 (proj2_sig (H2 t)) (y t)).\nmove=> t.\napply constructive_definite_description.\napply (proj1 (unique_existence (fun (g : B t -> A t) => (forall (x : A t), g (F t x) = x) /\\ (forall y : B t, F t (g y) = y)))).\napply conj.\nelim (H1 t).\nmove=> g H2.\nexists g.\napply H2.\nmove=> g1 g2 H2 H3.\napply functional_extensionality_dep.\nmove=> y.\nrewrite - {1} (proj2 H3 y).\napply (proj1 H2 (g2 y)).\nQed.\n\nLemma ForallSavesBijective : forall (T A B: Type) (F : T -> A -> B), (forall (t : T), Bijective (F t)) -> Bijective (fun (x : T -> A) (t0 : T) => (F t0 (x t0))).\nProof.\nmove=> T A B F.\napply (ForallSavesBijective_dep T (fun (t : T) => A) (fun (t : T) => B) F).\nQed.\n\nLemma ForallSavesInjective_dep : forall (T : Type) (A : T -> Type) (B : T -> Type) (F : forall (t : T), (A t) -> (B t)), (forall (t : T), Injective (F t)) -> Injective (fun (x : forall (t : T), (A t)) (t0 : T) => (F t0 (x t0))).\nProof.\nmove=> T A B F H1 x1 x2 H2.\napply functional_extensionality_dep.\nmove=> t.\napply (H1 t (x1 t) (x2 t)).\nsuff: (F t (x1 t) = let temp := (fun t0 : T => F t0 (x1 t0)) in temp t).\nmove=> H3.\nrewrite H3.\nrewrite H2.\nreflexivity.\nreflexivity.\nQed.\n\nLemma ForallSavesInjective : forall (T A B: Type) (F : T -> A -> B), (forall (t : T), Injective (F t)) -> Injective (fun (x : T -> A) (t0 : T) => (F t0 (x t0))).\nProof.\nmove=> T A B F.\napply (ForallSavesInjective_dep T (fun (t : T) => A) (fun (t : T) => B) F).\nQed.\n\nDefinition Single := exist (fun (n : nat) => (n < 1)) O (le_n 1).\n\nLemma SingleSame : forall (v : {n : nat | n < 1}), v = Single.\nProof.\nmove=> v.\napply sig_map.\nrewrite (le_antisym (proj1_sig Single) 0 (le_S_n (proj1_sig Single) 0 (proj2_sig Single)) (le_0_n (proj1_sig Single))).\napply (le_antisym (proj1_sig v) 0 (le_S_n (proj1_sig v) 0 (proj2_sig v)) (le_0_n (proj1_sig v))).\nQed.\n\nLemma CountReverseSig : forall (N : nat), {f : {n : nat | n < N} -> {n : nat | n < N} | forall (m : {n : nat | n < N}), S (proj1_sig m + proj1_sig (f m)) = N}.\nProof.\nmove=> N.\nsuff: (forall (k : {n : nat | n < N}), N - S (proj1_sig k) < N).\nmove=> H1.\nexists (fun (m : {n : nat | n < N}) => (exist (fun (k : nat) => k < N) (N - S (proj1_sig m)) (H1 m))).\nmove=> m.\nsimpl.\napply (le_plus_minus_r (S (proj1_sig m)) N (proj2_sig m)).\nmove=> k.\napply (plus_lt_reg_l (N - S (proj1_sig k)) N (S (proj1_sig k))).\nrewrite (le_plus_minus_r (S (proj1_sig k)) N (proj2_sig k)).\napply (le_n_S N (proj1_sig k + N)).\napply (le_plus_r (proj1_sig k) N).\nQed.\n\nDefinition CountReverse (N : nat) := proj1_sig (CountReverseSig N).\n\nDefinition CountReverseNature (N : nat) : (forall (m : {n : nat | n < N}), S (proj1_sig m + proj1_sig (CountReverse N m)) = N) := proj2_sig (CountReverseSig N).\n\nLemma CountReverseInvolutive : forall (N : nat) (m : {n : nat | n < N}), CountReverse N (CountReverse N m) = m.\nProof.\nmove=> N m.\napply sig_map.\napply (plus_reg_l (proj1_sig (CountReverse N (CountReverse N m))) (proj1_sig m) (proj1_sig (CountReverse N m))).\napply eq_add_S.\nrewrite (plus_comm (proj1_sig (CountReverse N m)) (proj1_sig m)).\nrewrite (CountReverseNature N m).\napply (CountReverseNature N (CountReverse N m)).\nQed.\n\nLemma AddConnectSig : forall (N M : nat), {f : {n : nat | n < N} + {n : nat | n < M} -> {n : nat | n < N + M} | (forall (m : {n : nat | n < N}), proj1_sig m = proj1_sig (f (inl m))) /\\ (forall (m : {n : nat | n < M}), N + proj1_sig m = proj1_sig (f (inr m)))}.\nProof.\nmove=> N M.\nsuff: (forall (m : {n : nat | n < N}), proj1_sig m < N + M).\nmove=> H1.\nsuff: (forall (m : {n : nat | n < M}), N + proj1_sig m < N + M).\nmove=> H2.\nexists (fun (m : {n : nat | n < N} + {n : nat | n < M}) => match m with\n  | inl k => exist (fun (l : nat) => l < N + M) (proj1_sig k) (H1 k)\n  | inr k => exist (fun (l : nat) => l < N + M) (N + proj1_sig k) (H2 k)\nend).\napply conj.\nmove=> m.\nreflexivity.\nmove=> m.\nreflexivity.\nmove=> m.\napply (plus_lt_compat_l (proj1_sig m) M N (proj2_sig m)).\nmove=> m.\napply (le_trans (S (proj1_sig m)) N (N + M) (proj2_sig m) (le_plus_l N M)).\nQed.\n\nDefinition AddConnect (N M : nat) := proj1_sig (AddConnectSig N M).\n\nDefinition AddConnectNature (N M : nat) : (forall (m : {n : nat | n < N}), proj1_sig m = proj1_sig (AddConnect N M (inl m))) /\\ (forall (m : {n : nat | n < M}), N + proj1_sig m = proj1_sig (AddConnect N M (inr m))) := proj2_sig (AddConnectSig N M).\n\nLemma AddConnectInvSig : forall (N M : nat), {f : {n : nat | n < N + M} -> {n : nat | n < N} + {n : nat | n < M} | (forall (m : {n : nat | n < N + M}), (proj1_sig m < N) -> match (f m) with\n  | inl k => proj1_sig m = proj1_sig k\n  | inr _ => False\nend) /\\ (forall (m : {n : nat | n < N + M}), (N <= proj1_sig m) -> match (f m) with\n  | inl _ => False\n  | inr k => proj1_sig m = N + proj1_sig k\nend)}.\nProof.\nmove=> N M.\nsuff: (forall (m : {n : nat | n < N + M}), ~ proj1_sig m < N -> proj1_sig m - N < M).\nmove=> H1.\nexists (fun (m : {n : nat | n < N + M}) => match excluded_middle_informative (proj1_sig m < N) with\n  | left H => inl (exist (fun (k : nat) => k < N) (proj1_sig m) H)\n  | right H => inr (exist (fun (k : nat) => k < M) (proj1_sig m - N) (H1 m H))\nend).\napply conj.\nmove=> m H2.\nelim (excluded_middle_informative (proj1_sig m < N)).\nmove=> H3.\nreflexivity.\nmove=> H3.\napply (H3 H2).\nmove=> m H2.\nelim (excluded_middle_informative (proj1_sig m < N)).\nmove=> H3.\napply (le_not_lt N (proj1_sig m) H2 H3).\nmove=> H3.\napply (le_plus_minus N (proj1_sig m) H2).\nmove=> m H1.\napply (plus_lt_reg_l (proj1_sig m - N) M N).\nrewrite (le_plus_minus_r N (proj1_sig m)).\napply (proj2_sig m).\nelim (le_or_lt N (proj1_sig m)).\napply.\nmove=> H2.\napply False_ind.\napply (H1 H2).\nQed.\n\nDefinition AddConnectInv (N M : nat) := proj1_sig (AddConnectInvSig N M).\n\nDefinition AddConnectInvNature (N M : nat) : (forall (m : {n : nat | n < N + M}), proj1_sig m < N -> match AddConnectInv N M m with\n  | inl k => proj1_sig m = proj1_sig k\n  | inr _ => False\nend) /\\ (forall (m : {n : nat | n < N + M}), N <= proj1_sig m -> match AddConnectInv N M m with\n  | inl _ => False\n  | inr k => proj1_sig m = N + proj1_sig k\nend) := proj2_sig (AddConnectInvSig N M).\n\nLemma AddConnectInvRelation : forall (N M : nat), (forall (m : {n : nat | n < N} + {n : nat | n < M}), AddConnectInv N M (AddConnect N M m) = m) /\\ (forall (m : {n : nat | n < N + M}), AddConnect N M (AddConnectInv N M m) = m).\nProof.\nmove=> N M.\napply conj.\nelim.\nmove=> m.\nsuff: (match AddConnectInv N M (AddConnect N M (inl m)) return Prop with\n  | inl k => proj1_sig (AddConnect N M (inl m)) = proj1_sig k\n  | inr _ => False\nend).\nelim (AddConnectInv N M (AddConnect N M (inl m))).\nmove=> k H1.\nsuff: (k = m).\nmove=> H2.\nrewrite H2.\nreflexivity.\napply sig_map.\nrewrite - H1.\nrewrite (proj1 (AddConnectNature N M) m).\nreflexivity.\nmove=> k.\nelim.\napply (proj1 (AddConnectInvNature N M) (AddConnect N M (inl m))).\nrewrite - (proj1 (AddConnectNature N M) m).\napply (proj2_sig m).\nmove=> m.\nsuff: (match AddConnectInv N M (AddConnect N M (inr m)) return Prop with\n  | inl _ => False\n  | inr k => proj1_sig (AddConnect N M (inr m)) = N + proj1_sig k\nend).\nelim (AddConnectInv N M (AddConnect N M (inr m))).\nmove=> k.\nelim.\nmove=> k H1.\nsuff: (m = k).\nmove=> H2.\nrewrite H2.\nreflexivity.\napply sig_map.\napply (plus_reg_l (proj1_sig m) (proj1_sig k) N).\nrewrite (proj2 (AddConnectNature N M) m).\napply H1.\napply (proj2 (AddConnectInvNature N M) (AddConnect N M (inr m))).\nrewrite - (proj2 (AddConnectNature N M) m).\napply (le_plus_l N (proj1_sig m)).\nmove=> m.\nelim (le_or_lt N (proj1_sig m)).\nmove=> H1.\nsuff: (match AddConnectInv N M m return Prop with\n  | inl _ => False\n  | inr k => proj1_sig m = N + proj1_sig k\nend).\nelim (AddConnectInv N M m).\nmove=> k.\nelim.\nmove=> k H2.\napply sig_map.\nrewrite H2.\nrewrite (proj2 (AddConnectNature N M) k).\nreflexivity.\napply (proj2 (AddConnectInvNature N M) m).\napply H1.\nmove=> H1.\nsuff: (match AddConnectInv N M m return Prop with\n  | inl k => proj1_sig m = proj1_sig k\n  | inr _ => False\nend).\nelim (AddConnectInv N M m).\nmove=> k H2.\napply sig_map.\nrewrite H2.\nrewrite (proj1 (AddConnectNature N M) k).\nreflexivity.\nmove=> k.\nelim.\napply (proj1 (AddConnectInvNature N M) m).\napply H1.\nQed.\n\nLemma CountAdd : forall (N M : nat), {f : {n : nat | n < N} + {n : nat | n < M} -> {n : nat | n < N + M} | Bijective f}.\nProof.\nmove=> N M.\nexists (AddConnect N M).\nexists (AddConnectInv N M).\napply (AddConnectInvRelation N M).\nQed.\n\nLemma MultConnectSig : forall (N M : nat), {f : {n : nat | n < N} * {n : nat | n < M} -> {n : nat | n < N * M} | forall (m : {n : nat | n < N} * {n : nat | n < M}), proj1_sig (f m) = proj1_sig (fst m) * M + proj1_sig (snd m)}.\nProof.\nelim.\nmove=> M.\nexists (fun (xy : {n : nat | n < 0} * {n : nat | n < M}) => match (PeanoNat.Nat.nlt_0_r (proj1_sig (fst xy)) (proj2_sig (fst xy))) with\nend).\nmove=> m.\nelim (PeanoNat.Nat.nlt_0_r (proj1_sig (fst m)) (proj2_sig (fst m))).\nmove=> N H1 M.\nexists (compose (AddConnect M (N * M)) (fun (m : {n : nat | n < S N} * {n : nat | n < M}) => match AddConnectInv 1 N (fst m) with\n  | inl _ => inl (snd m)\n  | inr a => inr (proj1_sig (H1 M) (a, snd m))\nend)).\nmove=> m.\nunfold compose.\nrewrite - {2} (proj2 (AddConnectInvRelation 1 N) (fst m)).\nelim (AddConnectInv 1 N (fst m)).\nmove=> a.\nrewrite - (proj1 (AddConnectNature 1 N) a).\nrewrite (SingleSame a).\nrewrite - (proj1 (AddConnectNature M (N * M)) (snd m)).\nreflexivity.\nmove=> b.\nrewrite - (proj2 (AddConnectNature M (N * M))).\nrewrite - (proj2 (AddConnectNature 1 N)).\nrewrite (proj2_sig (H1 M)).\nsimpl.\napply plus_assoc.\nQed.\n\nDefinition MultConnect (N M : nat) := proj1_sig (MultConnectSig N M).\n\nDefinition MultConnectNature (N M : nat) : forall (m : {n : nat | n < N} * {n : nat | n < M}), proj1_sig (MultConnect N M m) = proj1_sig (fst m) * M + proj1_sig (snd m) := proj2_sig (MultConnectSig N M).\n\nLemma MultConnectInvSig : forall (N M : nat), {f : {n : nat | n < N * M} -> {n : nat | n < N} * {n : nat | n < M} | forall (m : {n : nat | n < N * M}), proj1_sig m = proj1_sig (fst (f m)) * M + proj1_sig (snd (f m))}.\nProof.\nelim.\nmove=> M.\nrewrite (mult_0_l M).\nexists (fun (x : {n : nat | n < 0}) => match (PeanoNat.Nat.nlt_0_r (proj1_sig x) (proj2_sig x)) with\nend).\nmove=> x.\nelim (PeanoNat.Nat.nlt_0_r (proj1_sig x) (proj2_sig x)).\nmove=> N H1 M.\nexists (compose (fun (m : {n : nat | n < M} + {n : nat | n < N * M}) => match m with\n  | inl a => (AddConnect 1 N (inl Single), a)\n  | inr b => (AddConnect 1 N (inr (fst (proj1_sig (H1 M) b))), snd (proj1_sig (H1 M) b))\nend) (AddConnectInv M (N * M))).\nmove=> m.\nunfold compose.\nrewrite - {1} (proj2 (AddConnectInvRelation M (N * M)) m).\nelim (AddConnectInv M (N * M) m).\nmove=> a.\nsimpl.\nrewrite - (proj1 (AddConnectNature M (N * M)) a).\nrewrite - (proj1 (AddConnectNature 1 N) Single).\nreflexivity.\nmove=> b.\nsimpl.\nrewrite - (proj2 (AddConnectNature M (N * M)) b).\nrewrite - (proj2 (AddConnectNature 1 N)).\nrewrite (proj2_sig (H1 M) b).\nrewrite plus_assoc.\nreflexivity.\nQed.\n\nDefinition MultConnectInv (N M : nat) := proj1_sig (MultConnectInvSig N M).\n\nDefinition MultConnectInvNature (N M : nat) : forall (m : {n : nat | n < N * M}), proj1_sig m = proj1_sig (fst (MultConnectInv N M m)) * M + proj1_sig (snd (MultConnectInv N M m)) := proj2_sig (MultConnectInvSig N M).\n\nLemma MultConnectInvRelation : forall (N M : nat), (forall (m : {n : nat | n < N} * {n : nat | n < M}), MultConnectInv N M (MultConnect N M m) = m) /\\ (forall (m : {n : nat | n < N * M}), MultConnect N M (MultConnectInv N M m) = m).\nProof.\nsuff: (forall (N M : nat) (a b : {n : nat | n < N} * {n : nat | n < M}), proj1_sig (fst a) * M + proj1_sig (snd a) = proj1_sig (fst b) * M + proj1_sig (snd b) -> a = b).\nmove=> H1 N M.\napply conj.\nmove=> m.\napply (H1 N M).\nrewrite - (MultConnectInvNature N M).\napply (MultConnectNature N M m).\nmove=> m.\napply sig_map.\nrewrite (MultConnectNature N M).\nrewrite (MultConnectInvNature N M).\nreflexivity.\nsuff: (forall (N M : nat) (a b : {n : nat | n < N} * {n : nat | n < M}), proj1_sig (fst a) * M + proj1_sig (snd a) = proj1_sig (fst b) * M + proj1_sig (snd b) -> proj1_sig (fst a) <= proj1_sig (fst b)).\nmove=> H1 N M a b H2.\nsuff: (fst a = fst b).\nmove=> H3.\napply injective_projections.\napply H3.\napply sig_map.\napply (plus_reg_l (proj1_sig (snd a)) (proj1_sig (snd b)) (proj1_sig (fst a) * M)).\nrewrite {2} H3.\napply H2.\napply sig_map.\napply le_antisym.\napply (H1 N M a b H2).\napply (H1 N M b a).\nrewrite H2.\nreflexivity.\nmove=> N M a b H1.\nelim (le_or_lt (proj1_sig (fst a)) (proj1_sig (fst b))).\napply.\nmove=> H2.\nelim (lt_irrefl (proj1_sig (fst a) * M + proj1_sig (snd a))).\nrewrite {1} H1.\napply (le_trans (S (proj1_sig (fst b) * M + proj1_sig (snd b))) (proj1_sig (fst a) * M)).\napply (le_trans (S (proj1_sig (fst b) * M + proj1_sig (snd b))) ((S (proj1_sig (fst b))) * M)).\nsimpl.\nrewrite (plus_comm (proj1_sig (fst b) * M) (proj1_sig (snd b))).\napply (plus_le_compat_r (S (proj1_sig (snd b))) M).\napply (proj2_sig (snd b)).\napply (mult_le_compat_r (S (proj1_sig (fst b))) (proj1_sig (fst a)) M H2).\napply le_plus_l.\nQed.\n\nLemma CountMult : forall (N M : nat), {f : {n : nat | n < N} * {n : nat | n < M} -> {n : nat | n < N * M} | Bijective f}.\nProof.\nmove=> N M.\nexists (MultConnect N M).\nexists (MultConnectInv N M).\napply (MultConnectInvRelation N M).\nQed.\n\nLemma CountPow : forall (N M : nat), {f : ({n : nat | n < N} -> {n : nat | n < M}) -> {n : nat | n < M ^ N} | Bijective f}.\nProof.\nmove=> N M.\nelim N.\nsimpl.\nexists (fun (_ : {n : nat | n < 0} -> {n : nat | n < M}) => exist (fun (n : nat) => n < S O) O (le_n (S O))).\nexists (fun (m : {n : nat | n < S O}) (k : {n : nat | n < O}) => match (PeanoNat.Nat.nlt_0_r (proj1_sig k) (proj2_sig k)) with\nend).\napply conj.\nmove=> x.\napply functional_extensionality.\nmove=> k.\napply False_ind.\napply (PeanoNat.Nat.nlt_0_r (proj1_sig k) (proj2_sig k)).\nmove=> y.\napply sig_map.\nsimpl.\nelim (le_lt_or_eq (proj1_sig y) O).\nmove=> H1.\napply False_ind.\napply (PeanoNat.Nat.nlt_0_r (proj1_sig y) H1).\nmove=> H1.\nrewrite H1.\nreflexivity.\napply (le_S_n (proj1_sig y) O (proj2_sig y)).\nmove=> K.\nelim.\nmove=> f1 H1.\nsimpl.\nsuff: ({f : ({n : nat | n < S K} -> {n : nat | n < M}) -> ({n : nat | n < M} * {n : nat | n < M ^ K}) | Bijective f}).\nelim.\nmove=> f2 H2.\nexists (compose (proj1_sig (CountMult M (M ^ K))) f2).\napply BijChain.\napply H2.\napply (proj2_sig (CountMult M (M ^ K))).\nexists (fun (x : {n : nat | n < S K} -> {n : nat | n < M}) => (x (exist (fun (n : nat) => n < S K) K (le_n (S K))), f1 (fun (m : {n : nat | n < K}) => x (exist (fun (n : nat) => n < S K) (proj1_sig m) (le_trans (S (proj1_sig m)) K (S K) (proj2_sig m) (le_S K K (le_n K))))))).\nelim H1.\nmove=> g1 H2.\nexists (fun (x : {n : nat | n < M} * {n : nat | n < M ^ K}) (k : {n : nat | n < S K}) => match excluded_middle_informative (proj1_sig k < K) with\n  | left H => g1 (snd x) (exist (fun (n : nat) => n < K) (proj1_sig k) H)\n  | right H => fst x\nend).\napply conj.\nmove=> x.\napply functional_extensionality.\nmove=> k.\nelim (excluded_middle_informative (proj1_sig k < K)).\nmove=> H3.\nsimpl.\nrewrite (proj1 H2 (fun m : {n : nat | n < K} => x (exist (fun n : nat => n < S K) (proj1_sig m) (Nat.le_trans (S (proj1_sig m)) K (S K) (proj2_sig m) (le_S K K (le_n K)))))).\nsuff: ((exist (fun n : nat => n < S K) (proj1_sig (exist (fun n : nat => n < K) (proj1_sig k) H3)) (Nat.le_trans (S (proj1_sig (exist (fun n : nat => n < K) (proj1_sig k) H3))) K (S K) (proj2_sig (exist (fun n : nat => n < K) (proj1_sig k) H3)) (le_S K K (le_n K)))) = k).\nmove=> H4.\nrewrite H4.\nreflexivity.\napply sig_map.\nreflexivity.\nmove=> H3.\nsuff: ((exist (fun n : nat => n < S K) K (le_n (S K))) = k).\nmove=> H4.\nrewrite H4.\nreflexivity.\napply sig_map.\nelim (le_lt_or_eq (proj1_sig k) K (le_S_n (proj1_sig k) K (proj2_sig k))).\nmove=> H4.\napply False_ind.\napply (H3 H4).\nmove=> H4.\nrewrite H4.\nreflexivity.\nmove=> y.\nsimpl.\nelim (excluded_middle_informative (K < K)).\nmove=> H3.\napply False_ind.\napply (lt_irrefl K H3).\nmove=> H3.\napply injective_projections.\nreflexivity.\napply (BijInj {n : nat | n < M ^ K} ({n : nat | n < K} -> {n : nat | n < M}) g1).\nexists f1.\napply conj.\napply (proj2 H2).\napply (proj1 H2).\nsimpl.\nrewrite (proj1 H2 (fun m : {n : nat | n < K} => match excluded_middle_informative (proj1_sig m < K) with\n  | left H => g1 (snd y) (exist (fun n : nat => n < K) (proj1_sig m) H)\n  | right _ => fst y\nend)).\napply functional_extensionality.\nmove=> k.\nelim (excluded_middle_informative (proj1_sig k < K)).\nmove=> H4.\nsuff: ((exist (fun n : nat => n < K) (proj1_sig k) H4) = k).\nmove=> H5.\nrewrite H5.\nreflexivity.\napply sig_map.\nreflexivity.\nmove=> H4.\napply False_ind.\napply (H4 (proj2_sig k)).\nQed.\n\nLemma CountPowFinite : forall (N M : nat), Finite ({n : nat | (n < N)%nat} -> {n : nat | (n < M)%nat}) (Full_set ({n : nat | (n < N)%nat} -> {n : nat | (n < M)%nat})).\nProof.\nmove=> N M.\napply (cardinal_finite ({n : nat | (n < N)%nat} -> {n : nat | (n < M)%nat}) (Full_set ({n : nat | (n < N)%nat} -> {n : nat | (n < M)%nat})) (M ^ N)).\napply (proj1 (CountCardinalBijective ({n : nat | (n < N)%nat} -> {n : nat | (n < M)%nat}) (M ^ N))).\nelim (proj2_sig (CountPow N M)).\nmove=> g H1.\nexists g.\nexists (proj1_sig (CountPow N M)).\napply conj.\napply (proj2 H1).\napply (proj1 H1).\nQed.\n\nLemma CountInjBij : forall (N : nat) (f : {n : nat | (n < N)%nat} -> {n : nat | (n < N)%nat}), Injective f -> Bijective f.\nProof.\nmove=> N f H1.\napply InjSurjBij.\napply H1.\nsuff: (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (Full_set {n : nat | (n < N)%nat}) f = (Full_set {n : nat | (n < N)%nat})).\nmove=> H2 k.\nsuff: (In {n : nat | (n < N)%nat} (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (Full_set {n : nat | (n < N)%nat}) f) k).\nelim.\nmove=> x H3 y H4.\nexists x.\nrewrite H4.\nreflexivity.\nrewrite H2.\napply (Full_intro {n : nat | (n < N)%nat} k).\nsuff: (cardinal {n : nat | (n < N)%nat} (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (Full_set {n : nat | (n < N)%nat}) f) N).\nmove=> H2.\napply Extensionality_Ensembles.\napply conj.\nmove=> k H3.\napply (Full_intro {n : nat | (n < N)%nat} k).\nmove=> k H3.\napply NNPP.\nmove=> H4.\napply (lt_irrefl N).\napply (incl_card_le {n : nat | (n < N)%nat} (Add {n : nat | (n < N)%nat} (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (Full_set {n : nat | (n < N)%nat}) f) k) (Full_set {n : nat | (n < N)%nat}) (S N) N).\napply (card_add {n : nat | (n < N)%nat}).\napply H2.\napply H4.\napply CountCardinalBijective.\nexists (fun (k : {n : nat | (n < N)%nat}) => k).\nexists (fun (k : {n : nat | (n < N)%nat}) => k).\napply conj.\nmove=> l.\nreflexivity.\nmove=> l.\nreflexivity.\nmove=> l H5.\napply (Full_intro {n : nat | (n < N)%nat} l).\nsuff: (forall (m : nat), (m <= N)%nat -> cardinal {n : nat | (n < N)%nat} (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < m)%nat) f) m).\nmove=> H2.\nsuff: ((Full_set {n : nat | (n < N)%nat}) = (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < N)%nat)).\nmove=> H3.\nrewrite H3.\napply (H2 N).\napply (le_n N).\napply Extensionality_Ensembles.\napply conj.\nmove=> k H3.\napply (proj2_sig k).\nmove=> k H3.\napply (Full_intro {n : nat | (n < N)%nat} k).\nelim.\nmove=> H2.\nsuff: ((Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < O)%nat) f) = Empty_set {n : nat | (n < N)%nat}).\nmove=> H3.\nrewrite H3.\napply card_empty.\napply Extensionality_Ensembles.\napply conj.\nmove=> k.\nelim.\nmove=> x H3.\napply False_ind.\napply (le_not_lt O (proj1_sig x) (le_0_n (proj1_sig x)) H3).\nmove=> k.\nelim.\nmove=> m H2 H3.\nsuff: ((Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun k : {n : nat | (n < N)%nat} => (proj1_sig k < S m)%nat) f) = Add {n : nat | (n < N)%nat} (Im {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun k : {n : nat | (n < N)%nat} => (proj1_sig k < m)%nat) f) (f (exist (fun (n : nat) => (n < N)%nat) m H3))).\nmove=> H4.\nrewrite H4.\napply card_add.\napply (H2 (le_trans m (S m) N (le_S m m (le_n m)) H3)).\nmove=> H5.\nsuff: (forall (k : {n : nat | (n < N)%nat}), (proj1_sig k < m)%nat -> f k <> f (exist (fun n : nat => (n < N)%nat) m H3)).\nelim H5.\nmove=> x H6 y H7 H8.\napply (H8 x H6).\nrewrite H7.\nreflexivity.\nmove=> k H6 H7.\napply (lt_irrefl (proj1_sig k)).\nsuff: (k = (exist (fun n : nat => (n < N)%nat) m H3)).\nmove=> H8.\nrewrite {2} H8.\napply H6.\napply H1.\napply H7.\napply Extensionality_Ensembles.\napply conj.\nmove=> k.\nelim.\nmove=> x H4 y H5.\nrewrite H5.\nelim (le_lt_or_eq (proj1_sig x) m).\nmove=> H6.\nleft.\napply (Im_intro {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < m)%nat) f x H6).\nreflexivity.\nmove=> H6.\nright.\nsuff: (x = (exist (fun n : nat => (n < N)%nat) m H3)).\nmove=> H7.\nrewrite H7.\napply In_singleton.\napply sig_map.\napply H6.\napply le_S_n.\napply H4.\nmove=> k.\nelim.\nmove=> k0.\nelim.\nmove=> x H4 y H5.\napply (Im_intro {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < S m)%nat) f x).\napply (le_trans (S (proj1_sig x)) m (S m) H4 (le_S m m (le_n m))).\napply H5.\nmove=> x.\nelim.\napply (Im_intro {n : nat | (n < N)%nat} {n : nat | (n < N)%nat} (fun (k : {n : nat | (n < N)%nat}) => (proj1_sig k < S m)%nat) f (exist (fun n : nat => (n < N)%nat) m H3)).\napply (le_n (S m)).\nreflexivity.\nQed.\n\nLemma SkipOneSig : forall (N : nat) (m : {n : nat | n < N}), {f : {n : nat | n < pred N} -> {n : nat | n < N} | forall (k : {n : nat | n < pred N}), (proj1_sig k < proj1_sig m -> proj1_sig (f k) = proj1_sig k) /\\ (proj1_sig k >= proj1_sig m -> proj1_sig (f k) = S (proj1_sig k))}.\nProof.\nelim.\nmove=> m.\napply constructive_definite_description.\napply False_ind.\napply (le_not_lt 0 (proj1_sig m) (le_0_n (proj1_sig m)) (proj2_sig m)).\nmove=> k H1 m.\nsimpl.\nsuff: (forall (l : {n : nat | n < k}), proj1_sig l < S k).\nmove=> H2.\nsuff: (forall (l : {n : nat | n < k}), S (proj1_sig l) < S k).\nmove=> H3.\nexists (fun (l : {n : nat | n < k}) => match excluded_middle_informative (proj1_sig l < proj1_sig m) with\n  | left _ => exist (fun (n : nat) => n < S k) (proj1_sig l) (H2 l)\n  | right _ => exist (fun (n : nat) => n < S k) (S (proj1_sig l)) (H3 l)\nend).\nmove=> l.\napply conj.\nmove=> H4.\nelim (excluded_middle_informative (proj1_sig l < proj1_sig m)).\nmove=> H5.\nreflexivity.\nmove=> H5.\napply False_ind.\napply (H5 H4).\nmove=> H4.\nelim (excluded_middle_informative (proj1_sig l < proj1_sig m)).\nmove=> H5.\napply False_ind.\napply (le_not_lt (proj1_sig m) (proj1_sig l) H4 H5).\nmove=> H5.\nreflexivity.\nmove=> l.\napply (lt_n_S (proj1_sig l) k (proj2_sig l)).\nmove=> l.\napply (le_S (S (proj1_sig l)) k (proj2_sig l)).\nQed.\n\nDefinition SkipOne (N : nat) (m : {n : nat | n < N}) := proj1_sig (SkipOneSig N m).\n\nDefinition SkipOneNature (N : nat) (m : {n : nat | n < N}) : forall (k : {n : nat | n < pred N}), (proj1_sig k < proj1_sig m -> proj1_sig ((SkipOne N m) k) = proj1_sig k) /\\ (proj1_sig k >= proj1_sig m -> proj1_sig ((SkipOne N m) k) = S (proj1_sig k)) := proj2_sig (SkipOneSig N m).\n\nLemma SkipOneInj : forall (N : nat) (m : {n : nat | n < N}), Injective (SkipOne N m).\nProof.\nelim.\nmove=> m.\napply False_ind.\napply (le_not_lt O (proj1_sig m) (le_0_n (proj1_sig m)) (proj2_sig m)).\nmove=> N H1 m k1 k2 H2.\nelim (le_or_lt (proj1_sig m) (proj1_sig k1)).\nmove=> H3.\nelim (le_or_lt (proj1_sig m) (proj1_sig k2)).\nmove=> H4.\napply sig_map.\napply (Nat.succ_inj (proj1_sig k1) (proj1_sig k2)).\nrewrite - (proj2 (SkipOneNature (S N) m k1) H3).\nrewrite - (proj2 (SkipOneNature (S N) m k2) H4).\nrewrite H2.\nreflexivity.\nmove=> H4.\napply False_ind.\napply (le_not_lt (proj1_sig (SkipOne (S N) m k1)) (proj1_sig (SkipOne (S N) m k2))).\nrewrite H2.\napply (le_n (proj1_sig (SkipOne (S N) m k2))).\nrewrite (proj1 (SkipOneNature (S N) m k2) H4).\nrewrite (proj2 (SkipOneNature (S N) m k1) H3).\napply (lt_trans (proj1_sig k2) (proj1_sig m) (S (proj1_sig k1)) H4).\napply (le_n_S (proj1_sig m) (proj1_sig k1) H3).\nmove=> H3.\nelim (le_or_lt (proj1_sig m) (proj1_sig k2)).\nmove=> H4.\napply False_ind.\napply (le_not_lt (proj1_sig (SkipOne (S N) m k2)) (proj1_sig (SkipOne (S N) m k1))).\nrewrite H2.\napply (le_n (proj1_sig (SkipOne (S N) m k2))).\nrewrite (proj1 (SkipOneNature (S N) m k1) H3).\nrewrite (proj2 (SkipOneNature (S N) m k2) H4).\napply (lt_trans (proj1_sig k1) (proj1_sig m) (S (proj1_sig k2)) H3).\napply (le_n_S (proj1_sig m) (proj1_sig k2) H4).\nmove=> H4.\napply sig_map.\nrewrite - (proj1 (SkipOneNature (S N) m k1) H3).\nrewrite - (proj1 (SkipOneNature (S N) m k2) H4).\nrewrite H2.\nreflexivity.\nQed.\n\nLemma SkipOneMonotonicallyIncreasing : forall (N : nat) (m : {n : nat | n < N}) (k1 k2 : {n : nat | n < pred N}), proj1_sig k1 < proj1_sig k2 -> proj1_sig (SkipOne N m k1) < proj1_sig (SkipOne N m k2).\nProof.\nelim.\nmove=> m.\napply False_ind.\napply (le_not_lt O (proj1_sig m) (le_0_n (proj1_sig m)) (proj2_sig m)).\nmove=> N H1 m k1 k2 H2.\nelim (le_or_lt (proj1_sig m) (proj1_sig k1)).\nmove=> H3.\nrewrite (proj2 (SkipOneNature (S N) m k1) H3).\nrewrite (proj2 (SkipOneNature (S N) m k2) (le_trans (proj1_sig m) (proj1_sig k1) (proj1_sig k2) H3 (lt_le_weak (proj1_sig k1) (proj1_sig k2) H2))).\napply (le_n_S (S (proj1_sig k1)) (proj1_sig k2) H2).\nmove=> H3.\nrewrite (proj1 (SkipOneNature (S N) m k1) H3).\nelim (le_or_lt (proj1_sig m) (proj1_sig k2)).\nmove=> H4.\nrewrite (proj2 (SkipOneNature (S N) m k2) H4).\napply (le_S (S (proj1_sig k1)) (proj1_sig k2) H2).\nmove=> H4.\nrewrite (proj1 (SkipOneNature (S N) m k2) H4).\napply H2.\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/MappingProperty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7505240104315636}}
{"text": "Record Cat : Type := mkCat \n{ Obj : Type\n; hom: Obj * Obj -> Set\n; id : forall A: Obj, hom (A,A)\n; comp :  forall (A: Obj) ( B: Obj) (C : Obj) ( f: hom (A, B)) ( g : hom (B,C)), hom (A,C)\n; id_ax : forall (A: Obj) (B : Obj) (f : hom (A,B)), (comp A A B (id A) f = f) /\\ (comp A B B f (id B) = f)\n; ass : forall (A: Obj)(B:Obj)(C:Obj)(D:Obj)(f:hom (A,B))(g : hom (B,C))(h: hom (C,D)), comp A C D (comp A B C f g) h =   comp A B D f (comp B C D g h) \n}.\n\nRecord Smallcat ( S : Set) :=  mkSmallcat { cat : Cat; small : (Obj cat) = S}.\n\nDefinition SmallCat := sigT Smallcat.\n\nDefinition Arrows ( C :Cat) := sigT (hom C).\n\nDefinition Src ( C :Cat) ( a : Arrows C) := fst (projT1 a).\n\nDefinition Targ ( C :Cat) ( a : Arrows C) := snd (projT1 a).\n\nDefinition Terminal (C : Cat) ( A : Obj C) := forall ( B : Obj C), exists ( f :(hom C) (B,A)), forall ( g: (hom C) (B,A)), g = f.\n\nDefinition Iso (C : Cat) (A : Obj C) ( B : Obj C) := exists ( f : (hom C) (A,B)), exists ( g : (hom C) (B,A)), ((comp C) A B A f g = (id C) A /\\ (comp C) B A B g f = (id C) \nB).\n\nTheorem isoterm : forall (C :Cat) ( A : Obj C) ( B : Obj C), Terminal C A /\\ Terminal C B -> Iso C A B.\nProof.\n(intros **).\n(unfold Iso).\n(unfold Terminal).\n(destruct H).\n(unfold Terminal).\n(unfold Terminal in H).\n(unfold Terminal in H0).\n(pose proof (H B)).\n(pose proof (H0 A)).\n(destruct H1).\n(destruct H2).\n(pose proof (H A)).\n(destruct H3).\n(pose proof (H3 ((id C) A))).\n(pose proof (H3 (comp C A B A x0 x))).\n(pose proof (H0 B)).\n(destruct H6).\n(pose proof (H6 (id C B))).\n(pose proof (H6 (comp C B A B x x0))).\n(pose proof (Logic.conj H5 H8)).\n(rewrite <- H4 in H9).\n(rewrite <- H7 in H9).\n(pose proof\n  (ex_intro\n     (fun x : hom C (B, A) =>\n      comp C A B A x0 x = id C A /\\ comp C B A B x x0 = id C B) x H9)).\n(pose proof\n  (ex_intro\n     (fun x0 : hom C (A, B) =>\n      exists x : hom C (B, A),\n        comp C A B A x0 x = id C A /\\ comp C B A B x x0 = id C B) x0 H10)).\nassumption.\nQed.\n\nRecord Functor ( X: Cat * Cat) :=  mkFunctor { \nobj : (Obj (fst X)) -> (Obj (snd X));\narr :  forall ( a : Obj (fst X) ) ( b : Obj (fst X) ), hom (fst X) (a,b) -> hom (snd X) ( obj a, obj b);\nf_id : forall (a : Obj (fst X)), arr a a (id (fst X) a) = id (snd X) (obj a);\nf_comp :  forall (a : Obj (fst X)) (b : Obj (fst X)) (c : Obj (fst X))( f: hom (fst X) (a,b)) ( g: hom (fst X) (b,c)), \narr a c ((comp (fst X)) a b c f g) = (comp (snd X)) (obj a) (obj b) (obj c) (arr a b f) (arr b c g)  }.\n\n\nDefinition Func := sigT Functor.\n\n\nRecord NatTrans ( X: Cat * Cat) ( F : Functor X) (G : Functor X) := mkNatTrans{\neta : forall ( A : Obj (fst X) ), (hom (snd X)) ((obj X F) A,  (obj X G) A );\nnat_com : forall (A : Obj (fst X)) ( B : Obj (fst X)) ( f : (hom (fst X)) (A,B) ),  \n(comp (snd X))  ((obj X F) A) ((obj X F) B) ((obj X G) B )   ((arr X F) A B f) (eta B) \n= (comp (snd X))  ((obj X F) A) ((obj X G) A) ((obj X G) B) (eta A) ((arr X G) A B f)  }.\n\n\nRecord Diagram := mkDiagram { index : SmallCat; C : Cat ; diag : Functor ( cat (projT1 index) (projT2 index), C)}.\n\nDefinition Shom (x : Set * Set) := let (a,b):= x in a ->b.\n\nDefinition Sid (x : Set) :=  fun (a : x) => a.\n\nDefinition Scomp (a : Set)(b : Set)(c :Set) (f : Shom(a,b)) (g : Shom(b,c)) := fun (x: a) => g (f x).\n\nTheorem Sid_ax : forall ( a : Set) ( b : Set) ( f : Shom (a,b) ), (Scomp a a b (Sid a) f = f) /\\     (Scomp a b b f (Sid b) = f).\nProof.\n(intros **).\n(unfold Scomp).\nsplit.\n (unfold Sid).\n (simpl).\n auto.\n (unfold Sid).\n auto.\nQed.\n\nTheorem  Sass : forall (A: Set)(B:Set)(C:Set)(D:Set)(f:Shom (A,B))(g : Shom (B,C))(h: Shom (C,D)), Scomp A C D (Scomp A B C f g) h =   Scomp A B D f \n(Scomp B C D g h).\nProof.\nintros.\n(unfold Scomp).\n(pose proof (eq_refl (fun x : A => h (g (f x))))).\nassumption.\nQed.\n\nDefinition SET := mkCat Set Shom Sid Scomp Sid_ax Sass.\n \nDefinition PShv ( A :Cat) := Functor (A, SET).\n\n\n\n", "meta": {"author": "owl77", "repo": "CoqFormalisations", "sha": "40ab32919abd2ca5c1afecab3488f6434666acb4", "save_path": "github-repos/coq/owl77-CoqFormalisations", "path": "github-repos/coq/owl77-CoqFormalisations/CoqFormalisations-40ab32919abd2ca5c1afecab3488f6434666acb4/cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7504817151315503}}
{"text": "Require Import Coq.Init.Datatypes.\nRequire Import Coq.Lists.List.\nRequire Import TypeclassHierarchy.Interfaces.Semigroup.\n\nInstance List_Semigroup :\n  forall A : Set, Semigroup (list A) := { sg_op             := @app A\n                                   ; sg_op_associative := @app_assoc A\n                                   }.\n\nInstance List_Monoid :\n  forall A : Set, Monoid (list A) := { monoid_semigroup := List_Semigroup A\n                                ; unit             := nil\n                                ; left_identity    := @app_nil_l A\n                                ; right_identity   := @app_nil_r A\n                                }.\n\nSection Nat_Monoid.\n  Instance Nat_Semigroup : Semigroup nat :=\n    { sg_op             := plus\n    ; sg_op_associative := Plus.plus_assoc\n    }.\n\n  Instance Nat_Monoid : Monoid nat :=\n    { monoid_semigroup := Nat_Semigroup\n    ; unit             := 0\n    }.\n  Proof.\n    { (* Left identity *)\n      unfold sg_op.\n      unfold Nat_Semigroup.\n      apply plus_O_n.\n    }\n    {\n      unfold sg_op.\n      unfold Nat_Semigroup.\n      intros a.\n      apply (eq_sym (x := a) (y := a + 0)).\n      apply plus_n_O.\n    }\n  Defined.\nEnd Nat_Monoid.", "meta": {"author": "langston-barrett", "repo": "coq-typeclass-hierarchy", "sha": "97b512f4fffa0905edcce66dd3b2b0c29d091262", "save_path": "github-repos/coq/langston-barrett-coq-typeclass-hierarchy", "path": "github-repos/coq/langston-barrett-coq-typeclass-hierarchy/coq-typeclass-hierarchy-97b512f4fffa0905edcce66dd3b2b0c29d091262/src/Instances/Semigroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7504817026586407}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export indProp.\n\nDefinition relation (X:Type) := X -> X -> Prop.\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. intros.\n  inversion H. inversion H0. reflexivity.\nQed.\n\nTheorem le_not_a_paritial_function :\n  ~(partial_function le).\nProof.\n  unfold partial_function.\n  intros H. pose proof (H 0 0 1) as H1.\n  assert(tmpH1: 0 =1). apply H1. apply (le_n 0).  apply le_S, (le_n 0). inversion tmpH1.\nQed.\n\nTheorem total_relation_not_a_partial_function :\n  ~(partial_function total_relation).\nProof.\n  unfold partial_function. intros H.\n  pose proof (H 0 0 1) as H1.\n  assert(tmpH: 0=1). apply H1. apply tr_1.  apply tr_2.   unfold lt. apply le_n.\n  inversion tmpH.\nQed.\n\nPrint empty_relation.\n\nDefinition reflexive {X:Type} (R:relation X) :=\n  forall a : X, R a a.\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  intros a. apply le_n.\nQed.\n\nDefinition transitive {X:Type} (R:relation X) :=\n  forall a b c :X, (R a b) -> (R b c) -> (R a c).\n\n\nTheorem le_trans:\n  transitive le.\nProof.\n  unfold transitive. intros.\n  apply (PeanoNat.Nat.le_trans a b c).\n  congruence. congruence.\nQed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold transitive. intros.\n  apply (PeanoNat.Nat.lt_trans a b c).\n  apply H. apply H0.\nQed.\n\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. apply Hnm.\n  - apply le_S. apply IHHm'o.\nQed.\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold transitive. unfold lt.\n  intros a b c Hab Hbc.\n  induction c.\n  - inversion Hbc.\n  - simpl. inversion Hbc.\n    + apply le_S. subst c. congruence.\n    + subst m. apply le_S. apply IHc in H0. congruence.\nQed.\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  - subst m0. apply (le_trans n (S n) m).\n    + apply le_S, le_n.\n    + congruence.\nQed.\n\nTheorem le_Sn_n :forall n,\n    ~(S n<= n).\nProof.\n  intros.\n  intros H.\n  induction n.\n  - inversion H.\n  - apply IHn, le_S_n, 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 symmetric. unfold not.\n  intros. pose proof (H 0 1) as H1.\n  assert(tmpH: 0<=1). apply le_S, le_n.\n  apply H1 in tmpH. inversion tmpH.\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  unfold antisymmetric.\n  intros a.\n  induction a.\n  - intros. inversion H. reflexivity. subst b. inversion H0.\n  - intros. inversion H0.\n    + reflexivity.\n    + subst m. apply le_S in H as H3. apply le_S_n in H3.\n      assert(tmpH: a =b). apply IHa. apply H3. apply H2.\n      subst b. apply le_Sn_n in H. inversion H.\nQed.\n\nTheorem le_step : forall n m p,\n    n < m -> m <= S p -> n <= p.\nProof.\n  intros.\n  induction H.\n  - apply le_S_n in H0. apply H0.\n  - apply IHle. apply le_S in H0. apply le_S_n in H0. apply H0.\nQed.\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\nTheorem le_order :\n  order le.\nProof.\n  split.\n  - unfold reflexive. intros. apply le_n.\n  - split.\n    + apply le_antisymmetric.\n    + apply le_trans.\nQed.\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\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 H.\n    induction H.\n    + apply rt_refl.\n    + apply (rt_trans next_nat n m (S m)).\n      * apply IHle.\n      * apply rt_step. apply nn.\n  - intros H. induction H.\n    + inversion H. apply le_S, le_n.\n    + apply le_n.\n    + apply (le_trans x y z). apply IHclos_refl_trans1. apply IHclos_refl_trans2.\nQed.\n\nInductive clos_refl_trans_1n {A:Type}\n          (R: relation A)(x :A) : 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\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). apply H. apply rt1n_refl.\nQed.\n\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.\n  induction H.\n  - apply H0.\n  - apply IHclos_refl_trans_1n in H0. apply rt1n_trans with y. apply Hxy. 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 <-> clos_refl_trans_1n R x y.\nProof.\n  intros.\n  split.\n  - intros H. induction H.\n    + apply rsc_R. apply H.\n    + apply rt1n_refl.\n    + apply rsc_trans with y. congruence. congruence.\n  - intros H. induction H.\n    + apply rt_refl.\n    + apply rt_step in Hxy. apply rt_trans with y. congruence. congruence.\nQed.\n", "meta": {"author": "Hatsunespica", "repo": "Coq", "sha": "969145e20cb6525d324bd6b5b03cfcb6f7fefa8d", "save_path": "github-repos/coq/Hatsunespica-Coq", "path": "github-repos/coq/Hatsunespica-Coq/Coq-969145e20cb6525d324bd6b5b03cfcb6f7fefa8d/SF/rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7504336188016905}}
{"text": "(* -*- coding: utf-8; mode:coq -*-\n * Auto-generated - Do not edit or overwrite!\n *)\n\nRequire Import Arith. (* ouvre droit, notamment, à 'auto with arith' *)\n\nSection exo3.\n  \n  (* Il existe une fonction, qui réalise une certaine spécification *)\n\n  Variable fact : nat -> nat.\n  Axiom fact_spec_zero : fact 0 = 1.\n  Axiom fact_spec_succ : forall x : nat, x > 0 -> fact x = x * fact (x - 1).\n\n  Parameter n : nat.\n\n  (* Programme annoté :\n\n  { (n >= 0 and x = n) }\n    Auto0:f <- 1    \n    Inv:assert (fact(n) = (f * fact(x)) and x >= 0);    \n    Auto4:while (x > 0) {\n        Auto1:f <- (f * x)      \n        Auto2:x <- (x - 1)\n      }\n  { (fact(n) = f and x = 0) }\n\n  *)\n\n  (* Valeurs des Weakest Least Preconditions (WLP) *)\n  Definition Post (f x : nat) := ((fact n) = f /\\ x = 0).\n  Definition Pre (f x : nat) := (n >= 0 /\\ x = n).\n  Definition Auto4 (f x : nat) := ((fact n) = (f * (fact x)) /\\ x >= 0).\n  Definition Auto2 (f x : nat) := ((fact n) = (f * (fact (x - 1))) /\\ (x - 1) >= 0).\n  Definition Auto1 (f x : nat) := ((fact n) = ((f * x) * (fact (x - 1))) /\\ (x - 1) >= 0).\n  Definition Inv (f x : nat) := ((fact n) = (f * (fact x)) /\\ x >= 0).\n  Definition Auto0 (f x : nat) := ((fact n) = (1 * (fact x)) /\\ x >= 0).\n\n  (* Obligations de preuve engendrées *)\n  Lemma obligation_Pre : forall f x : nat,\n    ((n >= 0 /\\ x = n) -> ((fact n) = (1 * (fact x)) /\\ x >= 0)).\n  Proof.\n    intros.\n    destruct H.\n    subst.\n    split.\n    auto with arith.\n    assumption.\n  Qed.\n\n  \n  Lemma obligation_Inv_false : forall f x : nat,\n    (((fact n) = (f * (fact x)) /\\ x >= 0) -> (x <= 0 -> ((fact n) = f /\\ x = 0))).\n  Proof.\n    intros.\n    destruct H.\n    split.\n    assert(x=0).\n    auto with arith.\n    subst.\n    rewrite fact_spec_zero in H.\n    auto with arith.\n    assert(f*1=f).\n    auto with arith.\n    rewrite H2 in H.\n    assumption.\n    auto with arith.\n  Qed.\n\n  Lemma obligation_Inv_true : forall f x : nat,\n    (((fact n) = (f * (fact x)) /\\ x >= 0) -> (x > 0 -> ((fact n) = ((f * x) * (fact (x - 1))) /\\ (x - 1) >= 0))).\n  Proof.\n    intros.\n    destruct H.\n    split.\n    rewrite H.\n    rewrite fact_spec_succ.\n    auto with arith.\n    assumption.\n    auto with arith.\n  Qed.\n  \n\n  \n\nEnd exo3.\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/tp6/exo3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7503975358829521}}
{"text": "Require Import Coq.Bool.Bvector.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.ZArith.Zdigits.\nRequire Import Coq.ZArith.Zdiv.\nRequire Import Coq.ZArith.Zorder.\nRequire Import Coq.micromega.Lia.\nRequire Import CPidgin.Data.Bits.\n\nModule BitsTheorems.\n\nImport Bits.\n\nModule ZStuff.\n\n    Local Open Scope Z_scope.\n\n    (* 0 = 0 * 2. *)\n    Lemma zero_2_mult:\n        0 = 0 * 2.\n    Proof.\n        compute.\n        trivial.\n    Qed.\n\n    (* Shifting a value to the left is the same as multiplying it by 2. *)\n    Lemma bits_shl:\n        forall (x : Z),\n            0 <= x * 2 < two_power_nat 64 ->\n                B64_to_Z (B64_shl (Z_to_B64 x)) = x * 2.\n    Proof.\n        intros.\n        destruct H.\n        unfold B64_shl.\n        unfold Z_to_B64.\n        unfold B64_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        rewrite Z.ge_le_iff.\n        rewrite zero_2_mult in H.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* Left shifting a value by n is the same as multiplying it by 2^n. *)\n    Lemma bits_shl_iter:\n        forall (x : Z) (n : nat),\n            0 <= x ->\n            x < two_power_nat 64 ->\n            0 <= x * (two_power_nat n) < two_power_nat 64 ->\n            B64_to_Z (B64_shl_iter n (Z_to_B64 x)) = x * (two_power_nat n).\n    Proof.\n        intros x n H0 H1 H2.\n        destruct H2.\n        unfold B64_shl_iter.\n        unfold Z_to_B64.\n        unfold B64_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* Shifting a value to the right is the same as dividing it by 2. *)\n    Lemma bits_shr:\n        forall (x : Z),\n            0 < x < two_power_nat 64 ->\n                B64_to_Z (B64_shr (Z_to_B64 x)) = x / 2.\n    Proof.\n        intros.\n        destruct H.\n        unfold B64_shr.\n        unfold Z_to_B64.\n        unfold B64_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z.ge_le_iff.\n        apply Z_div_pos.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_div_lt.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* Right shifting a value by n is the same as dividing it by 2^n. *)\n    Lemma bits_shr_iter:\n        forall (x : Z) (n : nat),\n            0 <= x ->\n            x < two_power_nat 64 ->\n            0 <= x / (two_power_nat n) < two_power_nat 64 ->\n            B64_to_Z (B64_shr_iter n (Z_to_B64 x)) = x / (two_power_nat n).\n    Proof.\n        intros x n H0 H1 H2.\n        destruct H2.\n        unfold B64_shr_iter.\n        unfold Z_to_B64.\n        unfold B64_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* If two values are equal, then B64_eql returns 1. *)\n    Lemma B64_eql_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_eql x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_eql.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_eql returns 0. *)\n    Lemma B64_eql_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_eql x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_eql.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_eql returns 0. *)\n    Lemma B64_eql_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_eql x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_eql.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are equal, then B64_lt returns 0. *)\n    Lemma B64_lt_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_lt x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_lt.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_lt returns 1. *)\n    Lemma B64_lt_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_lt x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_lt.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_lt returns 0. *)\n    Lemma B64_lt_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_lt x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_lt.\n        rewrite H.\n        trivial.\n    Qed.\n\n\n    (* If two values are equal, then B64_gt returns 0. *)\n    Lemma B64_gt_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_gt x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_gt.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_gt returns 0. *)\n    Lemma B64_gt_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_gt x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_gt.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_gt returns 1. *)\n    Lemma B64_gt_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_gt x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_gt.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are equal, then B64_le returns 1. *)\n    Lemma B64_le_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_le x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_le.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_le returns 1. *)\n    Lemma B64_le_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_le x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_le.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_le returns 0. *)\n    Lemma B64_le_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_le x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_le.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are equal, then B64_ge returns 1. *)\n    Lemma B64_ge_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_ge x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_ge.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_ge returns 0. *)\n    Lemma B64_ge_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_ge x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_ge.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_ge returns 1. *)\n    Lemma B64_ge_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_ge x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_ge.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are equal, then B64_neq returns 0. *)\n    Lemma B64_neq_Eq:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Eq ->\n                B64_neq x y = nat_to_B64 0.\n    Proof.\n        intros x y H.\n        unfold B64_neq.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Lt, then B64_neq returns 1. *)\n    Lemma B64_neq_Lt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Lt ->\n                B64_neq x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_neq.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* If two values are Gt, then B64_neq returns 1. *)\n    Lemma B64_neq_Gt:\n        forall (x y : B64),\n            (B64_to_Z x) ?= (B64_to_Z y) = Gt ->\n                B64_neq x y = nat_to_B64 1.\n    Proof.\n        intros x y H.\n        unfold B64_neq.\n        rewrite H.\n        trivial.\n    Qed.\n\n    (* We can add two values. *)\n    Lemma B64_add:\n        forall (x y : Z),\n            0 <= x < two_power_nat 64 ->\n            0 <= y < two_power_nat 64 ->\n            x + y < two_power_nat 64 ->\n            (B64_to_Z (B64_add (Z_to_B64 x) (Z_to_B64 y))) = x + y.\n    Proof.\n        intros x y Hx Hy Hxy.\n        unfold B64_add.\n        unfold B64_to_Z.\n        unfold Z_to_B64.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* We can subtract two values. *)\n    Lemma B64_sub:\n        forall (x y : Z),\n            0 <= x < two_power_nat 64 ->\n            0 <= y < two_power_nat 64 ->\n            x - y >= 0 ->\n            (B64_to_Z (B64_sub (Z_to_B64 x) (Z_to_B64 y))) = x - y.\n    Proof.\n        intros x y Hx Hy Hxy.\n        unfold B64_sub.\n        unfold B64_to_Z.\n        unfold Z_to_B64.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* We can multiply two values. *)\n    Lemma B64_mul:\n        forall (x y : Z),\n            0 <= x < two_power_nat 64 ->\n            0 <= y < two_power_nat 64 ->\n            x * y < two_power_nat 64 ->\n            (B64_to_Z (B64_mul (Z_to_B64 x) (Z_to_B64 y))) = x * y.\n    Proof.\n        intros x y Hx Hy Hxy.\n        unfold B64_mul.\n        unfold B64_to_Z.\n        unfold Z_to_B64.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* We can divide two values. *)\n    Lemma B64_div:\n        forall (x y : Z),\n            0 <= x < two_power_nat 64 ->\n            0 <= y < two_power_nat 64 ->\n            0 <= x / y < two_power_nat 64 ->\n            (B64_to_Z (B64_div (Z_to_B64 x) (Z_to_B64 y))) = x / y.\n    Proof.\n        intros x y Hx Hy Hxy.\n        unfold B64_div.\n        unfold B64_to_Z.\n        unfold Z_to_B64.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\n    (* We can compute x modulo y. *)\n    Lemma B64_mod:\n        forall (x y : Z),\n            0 <= x < two_power_nat 64 ->\n            0 <= y < two_power_nat 64 ->\n            0 <= x mod y < two_power_nat 64 ->\n            (B64_to_Z (B64_mod (Z_to_B64 x) (Z_to_B64 y))) = x mod y.\n    Proof.\n        intros x y Hx Hy Hxy.\n        unfold B64_mod.\n        unfold B64_to_Z.\n        unfold Z_to_B64.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        trivial.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n        rewrite Z_to_binary_to_Z.\n        rewrite Z_to_binary_to_Z.\n        nia.\n        nia.\n        nia.\n        nia.\n        nia.\n    Qed.\n\nEnd ZStuff.\n\nEnd BitsTheorems.\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/Theorems/BitsTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7503083708607499}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 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/goal33conj202_coqofml_z6jkp8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7503083703537783}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Category.\n\n(** The oposite of a category C is a category with the same objects where the arrows are inverted. \nAs a result, f ∘_Cᵒᵖ g is just g ∘_C f and consequently, assoc is assoc_sym (reversed with arrow\narguments) and vice versa. Similarly, id_unit_left and id_unit_right are also swapped. *)\n\nDefinition Opposite (C : Category) : Category :=\n{|\n\n  Obj := Obj C;\n           \n  Hom := fun a b => (b –≻ a)%morphism;\n\n  compose :=\n    fun a b c (f : (b –≻ a)%morphism) (g : (c –≻ b)%morphism) => compose C c b a g f;\n\n  id := fun c => id C c;\n  \n  assoc := fun _ _ _ _ f g h => assoc_sym h g f;\n\n  assoc_sym := fun _ _ _ _ f g h => assoc h g f;\n\n  id_unit_left := fun _ _ h => @id_unit_right C _ _ h;\n  \n  id_unit_right := fun _ _ h => @id_unit_left C _ _ h\n                   \n|}.\n\nNotation \"C '^op'\" := (Opposite C) : category_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/Category/Opposite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7502167157383102}}
{"text": "Require Import bool.\nRequire Import nat.\nRequire Import hsyntax.\nRequire Import state.\nRequire Import dictionary.\n\n\nFixpoint aeval (env:State) (a:aexp) : nat :=\n    match a with\n    | ANum n        => n\n    | AKey k        => env k\n    | APlus a1 a2   => (aeval env a1) + (aeval env a2)\n    | AMinus a1 a2  => (aeval env a1) - (aeval env a2)\n    | AMult a1 a2   => (aeval env a1) * (aeval env a2) \n    end.\n\n\nFixpoint beval (env:State) (b:bexp) : bool :=\n    match b with\n    | BTrue         => true\n    | BFalse        => false\n    | BEq a1 a2     => eqb (aeval env a1) (aeval env a2)\n    | BLe a1 a2     => leb (aeval env a1) (aeval env a2)\n    | BNot b1       => negb (beval env b1)\n    | BAnd b1 b2    => andb (beval env b1) (beval env b2)\n    end.\n\nInductive ceval : com -> State -> State -> Prop :=\n| E_Skip     : forall e, ceval SKIP e e\n| E_Ass      : forall e a n x, aeval e a = n -> ceval (x ::= a) e (t_update e x n)\n| E_Seq      : forall e e' e'' c1 c2, ceval c1 e e' -> ceval c2 e' e'' ->\n                ceval (c1 ;; c2) e e''\n| E_IfTrue   : forall e e' b c1 c2, beval e b = true -> ceval c1 e e' ->\n                ceval (IFB b THEN c1 ELSE c2 FI) e e'\n| E_IfFalse  : forall e e' b c1 c2, beval e b = false -> ceval c2 e e' ->\n                ceval (IFB b THEN c1 ELSE c2 FI) e e'\n| E_WhileEnd : forall e b c, beval e b = false -> ceval (WHILE b DO c END) e e\n| E_WhileLoop: forall e e' e'' b c, beval e b = true -> ceval c e e' ->\n                ceval (WHILE b DO c END) e' e'' -> \n                ceval (WHILE b DO c END) e  e''\n| E_Havoc    : forall e k n, ceval (CHavoc k) e (t_update e k n)\n.\n\nExample havoc_test1 : ceval (HAVOC x) emptyState (t_update emptyState x 0).\nProof. constructor. Qed.\n\nExample havoc_test2 : ceval (SKIP ;; HAVOC z) emptyState (t_update emptyState z 20).\nProof. apply E_Seq with emptyState; constructor. Qed.\n\n\nLemma ceval_havoc: forall (k:Key) (e e':State),\n    ceval (HAVOC k) e e' -> exists n, e' = t_update e k n. \nProof.\n    intros k e e' H. remember (HAVOC k) as c eqn:C. revert C.\n    destruct H; intros H'; inversion H'; subst.\n    exists n. reflexivity.\nQed.\n\nLemma ceval_assign: forall (k:Key) (a:aexp) (e e':State),\n    ceval (k ::= a) e e' -> e' k = aeval e a.\nProof.\n    intros k a e e' H. remember (k ::= a) as c eqn:C. revert C.\n    destruct H; intros H'; inversion H'; subst; apply t_update_eq.\nQed.\n\nLemma ceval_assign': forall (k k':Key) (a:aexp) (e e':State),\n    ceval (k ::= a) e e' -> k <> k' -> e k' = e' k'.\nProof.\n    intros k k' a e e' H H'. remember (k ::= a) as c eqn:C. revert C.\n    destruct H; intros E; inversion E; subst. symmetry.\n    apply t_update_neq. 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/sf/heval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7501950954570262}}
{"text": "Require Import Cpdt.CpdtTactics.\nRequire Import Cpdt.Subset.\nRequire Import Cpdt.MoreSpecif.\n\n(* 1番は eq_nat_dec の少し違うバージョン *)\nDefinition leq_or_greater : 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            | O, S m' => Yes    (* 左側 *)\n            | S n', O => No     (* 右側 *)\n            | S n', S m' => Reduce (f n' m') (* 再帰 *)\n            end); intuition.\nDefined.\n\n(* 2-a *)\n", "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/report04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7501950914816098}}
{"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  intros n m H. \n  injection H as H1.\n  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. \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  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n.\n  induction n. \n  - split.\n    reflexivity.\n    destruct m eqn:m'.\n    + reflexivity.\n    + discriminate.\n  - intros. \n    split.\n    discriminate.\n    discriminate.\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. \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 [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 Hn Hm.\n  rewrite Hn.\n  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 [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_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 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 : \n  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.\n    reflexivity.\n  - right. \n    reflexivity.\nQed.\n\nModule MyNot.\nDefinition not (P:Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\nEnd MyNot.\n\nTheorem ex_falso_quodlibet :\n  forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\nFact not_implies_our_not : \n  forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  unfold not.\n  intros P H Q HP.\n  destruct H.\n  apply HP.\nQed.\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n  \nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything : \n  forall P Q : Prop,\n  (P /\\ ~ 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 : \n  forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H.\n  unfold not. \n  intros G.\n  apply G.\n  apply 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.\n  apply H0. \n  apply H.\n  apply H1.\nQed.\n\nTheorem not_both_true_and_false : \n  forall P : Prop,\n  ~(P /\\ ~P).\nProof.\n  unfold not.\n  intros P contra.\n  apply contradiction_implies_anything with(P:=P).\n  apply contra.\nQed.\n\nTheorem not_true_is_false : \n  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. 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 in H.\n    exfalso. \n    apply H. reflexivity.\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.\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 H.\n    rewrite H.\n    intros H'.\n    discriminate H'.\nQed.\n\nTheorem or_distributes_over_and : \n  forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split. \n  - intros.\n    destruct H.\n    + split.\n      left. apply H.\n      left. apply H.\n    + split.\n      destruct H.\n      right. apply H.\n      destruct H.\n      right. apply H0.\n  - intros.\n    destruct H as [HL HR].\n    destruct HL.\n    destruct HR.\n    left. \n    apply H.\n    left.\n    apply H.\n    destruct HR.\n    left.\n    apply H0.\n    right.\n    split.\n    apply H.\n    apply H0.\nQed. \n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma or_assoc :\n  forall P Q R : Prop,\n  P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R.\n  split.\n  - intros.\n    destruct H as [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_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. \n  destruct n.\n  - left.\n    reflexivity. \n  - destruct m. \n    + right. \n      reflexivity.\n    + discriminate.\nQed. \n\nLemma mult_0 :\n  forall n m,\n  n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma mult_0_3 :\n  forall n m p,\n  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  n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. \n  apply mult_0. \n  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\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  - simpl.\n    intros [].\n  - simpl.\n    intros [H | H].\n    + rewrite H.\n      left.\n      reflexivity.\n    + right.\n      apply IHl'.\n      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.\n  split.\n  induction l.\n  - simpl. \n    intros [].\n  - simpl.\n    intros [H | H].\n    + exists x. \n      split. \n      apply H. \n      left.\n      reflexivity.\n    + apply IHl in H. \n      destruct H as [w [F I]].\n      exists w. \n      split. \n      apply F.\n      right.\n      apply I.\n  - intros [w [F I]].\n    rewrite <- F.\n    apply In_map.\n    apply I.\nQed.\n\nFixpoint All {T} (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.\n    + intros.\n      simpl.\n      reflexivity.\n    + intros.\n      simpl.\n      split.\n      apply H.\n      * simpl.\n        left.\n        reflexivity.\n      * apply IHl.\n        intros.\n        apply H.\n        simpl.\n        right.\n        apply H0.\n  - induction l. \n    + simpl.\n      intros.\n      exfalso.\n      apply H0.\n    + simpl.\n      intros [H H0] x' [H1 | H1].\n      * rewrite <- H1. \n        apply H.\n      * apply IHl.\n        apply H0.\n        apply H1.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  (fun x => if oddb x then Podd x 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  destruct (oddb n) eqn:H1.\n  - unfold combine_odd_even.\n    rewrite H1.\n    apply H.\n    reflexivity.\n  - unfold combine_odd_even.\n    rewrite H1.\n    apply H0.\n    reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall(Podd Peven : nat -> Prop) (n : nat),\n  combine_odd_even Podd Peven n ->\n  oddb n = true ->\n  Podd n.\nProof.\n  intros.\n  unfold combine_odd_even in H.\n  rewrite H0 in H.\n  apply H.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall(Podd Peven : nat -> Prop) (n : nat),\n  combine_odd_even Podd Peven n ->\n  oddb n = false ->\n  Peven n.\nProof.\n  intros.\n  unfold combine_odd_even in H.\n  rewrite H0 in H.\n  apply H.\nQed.\n\nCheck plus_comm.\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.\nAbort.\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),\n  In x l -> l <> [].\nProof.\n  intros A x l H. \n  unfold not.\n  intro Hl.\n  destruct l.\n  - simpl in H.\n    destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat,\n  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,\n  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, \n  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,\n  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,\n  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 \n  (proj1 _ _ (In_map_iff _ _ _ _ _) H) as\n  [m [Hm _]].\n  rewrite mult_0_r in Hm.\n  rewrite <- Hm.\n  reflexivity.\nQed.\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. 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 x => plus 1 x).\nProof.\n  apply functional_extensionality.\n  intros 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 rev_append_order :\n  forall X (l1 l2 l3: list X),\n  rev_append l1 l2 ++ l3 = rev_append l1 (l2 ++ l3). \nProof.\n  induction l1.\n  - reflexivity.\n  - intros.\n    destruct l2.\n    + apply IHl1.  \n    + apply IHl1. \nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros.\n  apply functional_extensionality.\n  induction x.\n  - unfold tr_rev.\n    reflexivity.\n  - simpl.  \n    rewrite <- IHx.\n    unfold tr_rev.\n    simpl.\n    rewrite rev_append_order.\n    simpl.\n    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  intros k. \n  induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl.\n    apply IHk'.\nQed.\n\nTheorem evenb_double_conv : forall n,\n  exists k, \n  n = if evenb n then double k\n                else S (double k).\nProof.\n  induction n.\n  - exists 0.\n    reflexivity.\n  - rewrite evenb_S.     \n    destruct IHn as [k' H].\n    destruct (evenb n).\n    + simpl.\n      rewrite H.\n      exists k'.\n      reflexivity.\n    + simpl.\n      exists (S k').\n      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.\n  split.\n  - intros H.\n    destruct (evenb_double_conv n) as [k Hk].\n    rewrite Hk.\n    rewrite H.\n    exists k. \n    reflexivity.\n  - intros [k Hk].\n    rewrite Hk.\n    apply evenb_double.\nQed.\n\nLemma eqb_refl: \n  forall x: nat,\n  (x =? x) = true.\nProof.\n  intros.\n  induction x.\n  reflexivity.\n  simpl.\n  apply IHx.\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. \n    rewrite H.\n    rewrite <- eqb_refl with(x:=n2).\n    reflexivity.\nQed.\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  reflexivity.\nQed.\n\nExample not_even_1001' : ~(exists k, 1001 = double k).\nProof.\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  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.\n  split. \n  - intros. \n    split.\n    + destruct b1.\n      * reflexivity.\n      * discriminate.\n    + destruct b2.\n      * reflexivity.\n      * destruct b1.\n        discriminate.\n        discriminate.\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  split. \n  - intros. \n    destruct H.\n    destruct b1.\n    + left. \n      reflexivity.\n    + right.\n      reflexivity.\n  - intros [H1 | H2].\n    + rewrite H1.\n      reflexivity.\n    + rewrite H2.\n      destruct b1.\n      reflexivity.\n      reflexivity.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  intros x y.\n  rewrite <- not_true_iff_false.\n  rewrite -> eqb_eq.\n  reflexivity.\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, h' :: t' => false\n  | h :: t, nil => false\n  | h :: t, h' :: t' => eqb h h' && eqb_list eqb t t'\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  induction l1.\n  - destruct l2.\n    * simpl.\n      split.\n      + intros.\n        reflexivity.\n      + intros.\n        reflexivity.\n    * simpl.  \n      split.\n      + intros.\n        discriminate.\n      + intros.\n        discriminate.\n  - destruct l2.\n    * simpl. \n      split.\n      + intros.\n        discriminate.\n      + intros.\n        discriminate.\n    * simpl.\n      split.\n      + intros. \n        apply andb_true_iff in H0.\n        destruct H0 as [H1 H2].\n        apply H in H1.\n        apply IHl1 in H2.\n        rewrite H1, H2.\n        reflexivity.\n      + intros.\n        injection H0 as H1 H2.\n        apply H in H1.\n        rewrite H1.\n        apply IHl1.\n        apply H2.\nQed.\n\nTheorem forallb_true_iff : \n  forall X test (l : list X),\n  forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  induction l.\n  - split.\n    + simpl.\n      reflexivity.\n    + simpl. \n      reflexivity.\n  - split.\n    + intros.\n      simpl in H.\n      apply andb_true_iff in H.\n      destruct H as [H1 H2].\n      rewrite IHl in H2.\n      simpl.\n      split.\n      * apply H1.\n      * apply H2.\n    + intros. \n      simpl in H.\n      destruct H as [H1 H2].\n      simpl.\n      rewrite H1.\n      apply IHl.\n      apply H2.\nQed.\n", "meta": {"author": "s3141p", "repo": "software-foundations", "sha": "a6eee47da487495fff2bba8b3ff7b5e330efe18e", "save_path": "github-repos/coq/s3141p-software-foundations", "path": "github-repos/coq/s3141p-software-foundations/software-foundations-a6eee47da487495fff2bba8b3ff7b5e330efe18e/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7501802184107301}}
{"text": "(** \n * Logic in Coq\n **)\n\n(**********************************************************************)\n\n(* Propositions and proofs *)\n\nCheck list.\n(* [list] is a type-level function *)\n\nDefinition natlist : Type := list nat.\n(* explicit application of type-level functions *)\nCheck natlist.\n\n(* What, then, is the type of a theorem? *)\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\nIf [1+1 = 2] is a type, what are its values? \n\n    Proofs of [1 + 1 = 2]!\n\nThere 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 \n    resulting in [1 + 1 - 1 = 2 - 1]\n  reduce both sides to [1], \n  then note that [x = x]. \n\nWhat proof does Coq have for [1 + 1 = 2]? *)\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]. \n*)\n\n(**********************************************************************)\n\n(**\n** [Prop] and [Set]\n*)\n\nCheck 42.\n\nCheck nat.\n\n(**\nThe Coq documentation describes [Set] as being the type of _program specifications_, which describe\ncomputations.\n*)\n\nCheck Set.\n\n(* What is the type of [1 + 1 = 2]? *)\n\nCheck 1 + 1 = 2.\n\n(**\n[Prop] is the type of all the things that can be proved (not necessarily hold).\n*)\n\nCheck 1 + 1 = 3.\n\nCheck Prop.\n\nCheck true.\n\nCheck True.\n\n(**\nThe type of [Prop] is also [Type].\n*)\n\n(* Consider *)\n\nCheck 1 + 1.\nCheck 3.\nCheck 1 + 1 = 3.\n\n(* [=] takes two [nat]s and returns a [Prop]. \n\n   What can we learn about it? *)\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>>\n*)\n\nCheck @eq.\n\n(* [eq] builds a proposition that can be proved using two values of the same type *)\n\nCheck eq (fun x => x + 1) (fun n => n + 2 - 1).\n\nTheorem t1 : eq (fun x => x + 1) (fun n => n + 2 - 1).\nProof.\nAdmitted.\n\n(**********************************************************************)\n\n(**\n** Propositional logic\n\nHere are the _connectives_ in Coq:\n\n- Implication: [P -> Q].\n- Conjunction: [P /\\ Q].\n- Disjunction: [P \\/ Q].\n- Negation: [~P].\n\n* None of these connectives are baked in, but encoded.\n*)\n\nCheck and.\nCheck or.\nCheck not.\n\n(**\n<<\nand : Prop -> Prop -> Prop\nor  : Prop -> Prop -> Prop\nnot : Prop -> Prop\n>>\n\nObserve that we use [->] as implication but also as the type of functions.\n\nThis is not an accident!\n\n[P -> Q] can be thought of as:\n\n  - The type of functions that take a [P] and return [Q]\n  - A proposition that asserts [P] implies [Q]\n  \nThey are the same in Coq! Let's see this in action.\n\n*)\n\n(**********************************************************************)\n\n(** Implication *)\n\nTheorem p_implies_p : forall P: Prop, P -> P.\n\n(** \nSo why does this proposition hold? 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 P_assumed. \n    assumption. (* new tactic *)\nQed.\n\n(* Let's look at the type of [p_implies_p]. *)\n\nCheck p_implies_p.\n\n(** What is that evidence?  We can use [Print] to find out: *)\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\nThe proof is essentially the identity function for a given [P] that we want to prove. \n\nCan also be done directly as a [Definition]:\n*)\n\nDefinition p_implies_p_direct : forall P:Prop, P -> P := \n  fun p ev_p => ev_p.\n\n(**\n  + Rarely do we construct such direct proofs\n  + Tactics help us construct complicated proofs.\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?  \n  + Assume that [P -> Q].  \n  + 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. (* new tactic *)\n  assumption.\nQed.\n\n(** \n  + [apply] applies given evidence to goal. \n  + Does _backward reasoning_\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\nEquivalent to the OCaml function\n\nlet apply f v = f v\n*)\n\nTheorem syllogism' : forall P Q : Prop, \n  (P -> Q) -> P -> Q.\nProof.\n  intros.\n  apply H in H0.\n  (* Can also [apply] to assumptions to do _forwards reasoning *)\n  assumption.\nQed.\n\n\nTheorem imp_trans : forall P Q R : Prop,\n  (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  intros P Q R. intros evPimpQ. intros evQimpR. intros.\n\n  apply evQimpR.\n  apply evPimpQ.\n  assumption.\nQed.\n\n(** Let's look at the resulting proof: *)\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\nEquivalent to the OCaml function\n\nlet composition f g v = g (f v)\n\nlet succ x = x + 1\n\nlet succ2 = succ o succ\n\nlet (|>) = v |> f |> g\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?\n     + Suppose we have evidence of [P /\\ Q], we have evidence of [P].\n     + Use that evidence of [P] to show [P] holds.\n*)\n\nProof.\n    intros P Q PandQ.\n    destruct PandQ as [P_holds Q_holds].\n    assumption.\nQed.\n\n(** Let's look at the proof of [and_fst]. *)\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\nWhat is [conj]?\n*)\n\nCheck conj.\n\nLocate \"/\\\".\n\nPrint and.\n\n(* \n\ntype ('a,'b) and = Conj : 'a * 'b -> ('a,'b) and \n\n*)\n\n(* Takeaway: In order to construct a proof for [P /\\ Q], you need [P] and [Q] and use the [conj] constructor to put them together *)\n\nTheorem and_snd : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q PandQ.\n  destruct PandQ.\n  assumption.\nQed.\n\nPrint and_snd.\n\n(** Here 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. (* new tactic *)\n  trivial. trivial.\nQed.\n\n(* What 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] as its second argument.\n*)\n\n\n(* As another example of conjunction, let's prove that it is commutative. *)\n\nTheorem and_comm: forall P Q, P /\\ Q -> Q /\\ P.\nProof.\n    intros P Q PandQ. \n    destruct PandQ.\n    split. \n    all: assumption.\nQed.\n\nPrint and_comm.\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? \n\nLet's formalize that argument in Coq. *)\n\nProof.\n    intros P Q P_holds. \n    left. (* new tactic *) \n    assumption.\nQed.\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 \"\\/\".\n(** \"\\/\" is infix notation for [or A B] *)\n\nPrint or.\n\nPrint or_introl.\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*)\n\n\nTheorem or_comm : forall P Q, P \\/ Q -> Q \\/ P.\n\n(** Why does this hold?\n\nThat's what the Coq proof below does. *)\n\nProof.\n    intros P Q PorQ.\n    destruct PorQ.\n    - right. assumption.\n    - left. assumption.\nQed. \n\nPrint or_comm.\n\n(**\nCoq responds\n<<\nor_comm = \nfun (P Q : Prop) (PorQ : P \\/ Q) =>\nmatch PorQ with\n| or_introl H => or_intror H\n| or_intror H => or_introl H\nend\n     : forall P Q : Prop, P \\/ Q -> Q \\/ P)\n>>\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\nProof.\n  intros P Q R PorQR.\n  destruct PorQR.\n  \n  - split.\n    + left. assumption.\n    + left. assumption.\n  - destruct H.\n    split.\n    + right. assumption.\n    + right. assumption.\nQed.\n\n(** We can make the proof shorter with [;] *)\n\nTheorem or_distr_and_shorter : forall P Q R, \n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  destruct H.\n  - split; left; assumption.\n  - destruct H.\n    split; right; assumption.\nQed.\n\n\n(**********************************************************************)\n\n(** [False] and [True]\n\n[False] is the proposition that can never hold\n\nHere's the definition of [False]: *)\n\nPrint False.\n\n(**\nCoq responds\n<<\nInductive False : Prop :=  \n>>\n\nHas no constructors. And hence, we cannot provide evidence that [False] holds.\n\nLet's prove the Principle of Explosion. *)\n\nTheorem explosion : forall P:Prop, False -> P.\nProof.\n    intros P false_holds. \n    contradiction. (* new tactic *)\nQed.\n\n(** The second line of the proof uses a new tactic, [contradiction].  This tactic looks for any contradictions or assumptions of [False], and uses those to conclude the proof.  In this case, it immediately finds [False] as an assumption named [false_holds].*)\n\nPrint explosion.\nPrint False_ind.\n\n(**\n  + The [return P] in the pattern match above is a type annotation \n  + [False_ind] uses the evidence of [False] to return the evidence for any [P].\n*)\n\n(* We can directly define this function *)\n\nDefinition explosion' : forall (P:Prop), False -> P := \n  fun (P : Prop) (f (* no valid values for [f] *) : False) => \n    match f with\n    end.\n\n(** We can never prove [P -> P /\\ False], because there is no way to construct the evidence 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 *)\n\nPrint True.\n\nTheorem p_imp_p_and_true : forall P:Prop, P -> P /\\ True.\nProof.\n  intros P P_holds. split. assumption. \n  exact I. (* new tactic *)\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\n(**********************************************************************)\n\n(** Negation *)\n\nLocate \"~\".\nPrint not.\n\n(**\nCoq responds\n<<\nnot = fun A : Prop => A -> False\n     : Prop -> Prop\n>>\n\n  + Unlike \"/\\\" and \"\\/\" negation is a function not an inductive type.\n  + [~P] is effectively syntactic sugar for [P -> False].\n*)\n\nTheorem notFalse : ~False -> True.\n(** Intuition:  anything implies [True] *)\nProof.\n  unfold not. (* new tactic *)\n  intros.\n  exact I.\nQed.\n\nPrint notFalse.\n(* Ignores the argument *)\n\nTheorem notTrue: ~True -> False.\nProof.\n  unfold not. \n  intros t_imp_f. \n  apply t_imp_f.\n  exact I.\nQed.\n\n(** The 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\n* Proof is a higher-order function\n  + Takes [t_imp_f] function and uses [I] to get the proof for [False]\n* We can never apply this function\n  + cannot produce a term that returns [False]\n*)\n\nTheorem contra_implies_anything : forall (P Q : Prop), P /\\ ~P -> Q.\n(** Intuition:  principle of explosion *)\nProof.\n    unfold not.\n    intros. \n    destruct H.\n    apply H0 in H.\n    contradiction. (* detects contradiction *)\nQed.\n\n(**********************************************************************)\n\n(** deMorgan's laws *)\n\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., [False]), then evidence for [P] would lead to an explosion, and evidence 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(* Something interesting happens here *)\nTheorem deMorgan2 : forall P Q : Prop,\n  ~(P /\\ Q) -> ~P \\/ ~Q.\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(* stuck! *)\n\n(** There's no reason that \n      \"if evidence for P and Q would produce an explosion\" \n         implies \n      \"either evidence for P would produce an explosion, or evidence for Q would\". \n      \n    + It's the combined evidence for [P] and [Q] that produces the explosion  \n    + nothing is said about evidence for them individually.\n    + Coq uses _Constructive logic_; [deMorgan2] holds in _classical logic_\n*)\n\nTheorem excluded_middle : forall P, P \\/ ~P.\nProof.\n  intros P.\n  right.\n  unfold not.\n  intros.\nAbort.\n\n(* Coq uses constructive logic since the act of proving programs is by building evidence bottom up. No bottom up evidence for [P \\/ ~P]. *) \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 without proof.  Using that axiom, all the usual theorems of classical logic can be proved, such as double negation: *)\n\n\nEnd LetsDoClassicalReasoning.\n\n(**********************************************************************)\n\n(** Equality and implication *)\n\nLocate \"=\".\nCheck @eq. \n(* Builds a proposition that asserts the equality of the two arguments*)\n\nDefinition eq42 := @eq nat 42.\nCheck eq42.\nCheck (eq42 42). (* 42 = 42 *)\nCheck (eq42 43). (* 42 = 43 *)\n\n(* There's only one way to construct a value of type [eq],\n   that's with the [eq_refl] constructor. *)\nPrint eq.\nCheck @eq_refl.\n\nCheck @eq_refl nat 42.\n(* \n  + [@eq_refl] only takes just a single argument of type [nat]\n    * An argument can only be equal to itself\n  + Takeaway: Equality not baked into Coq, but an inductive type.\n*)\n\nTheorem direct_eq : 42 = 42.\nProof.\n  exact (eq_refl 42).\nQed.\n\n\nTheorem direct_eq2 : 42 = 43.\nProof.\n  (* No way to construct evidence for [42 = 43] *)\nAbort.\n\n(** Implication too is defined. *)\n\nLocate \"->\".\n\n(**\nCoq responds:\n<<\n\"A -> B\" := forall _ : A, B \n>>\n\nA function that takes the evidence for [A] and produces evidence for [B]. *)\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(**\n\n+ Only truly primitive pieces are [Inductive] definitions and [forall] types. \n   + Everything else --- equality, implication, conjunction, disjunction, True, False, negation --- can all be expressed in terms of those two primitives.\n*)", "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/Logic_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.750137759388325}}
{"text": "Set Implicit Arguments.\nRequire Export Lia.\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.\nFrom TLC Require Import LibTactics.\nLtac unpack := jauto_set_hyps; intros. (* TEMPORARY also in TLCBuffer *)\nFrom iris_time.union_find.math Require 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. lia.\nQed.\n\nLemma plus_le_plus:\n  forall a x y,\n  x <= y ->\n  x + a <= y + a.\nProof using.\n  intros. lia.\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). lia.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Make [lia] a hint. *)\n\nHint Extern 1 => lia : lia.\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. lia. Qed.\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. lia. Qed.\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; [ lia | simpl ].\n  generalize (n * m); intro.\n  lia.\nQed.\n\nLemma mult_magnifies_right:\n  forall m n,\n  0 < n ->\n  m <= m * n.\nProof using. nia. Qed.\n\nLemma mult_magnifies_right_strict:\n  forall m n,\n  0 < m ->\n  1 < n ->\n  m < m * n.\nProof using. nia. Qed.\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; lia | 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). lia.\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; [ lia |\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. lia.\nQed.\n\nLemma div2_step:\n  forall n,\n  (n + 2) / 2 = n/2 + 1.\nProof using.\n  intros. repeat div2. lia.\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). lia.\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. lia.\nQed.\n\nLemma div_mult_2:\n  forall n,\n  (2 * n) / 2 = n.\nProof using.\n  intros. div2. lia.\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. lia.\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. lia.\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. lia.\nQed.\n\nLemma prove_le_div2:\n  forall m n,\n  2 * m <= n -> (* tight *)\n  m <= n / 2.\nProof using.\n  intros. div2. lia.\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. lia.\nQed.\n\nLemma prove_div2_lt:\n  forall m n,\n  m < 2 * n -> (* tight *)\n  m / 2 < n.\nProof using.\n  intros. div2. lia.\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. lia.\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. lia.\nQed.\n\nLemma prove_lt_div2_zero:\n  forall n,\n  1 < n -> (* tight *)\n  0 < n / 2.\nProof using.\n  intros. div2. lia.\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. lia.\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  lia.\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  lia.\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; lia.\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)). lia.\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)). lia.\n  rewrite f. rewrite power_plus.\n  eapply mult_magnifies_right_strict.\n    { eauto with positive lia. }\n    { simpl.\n      eapply Nat.lt_le_trans with (m := n). lia.\n      eapply mult_magnifies_right.\n      eauto with positive lia. }\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    lia.\n    eapply Nat.lt_le_trans; [ eapply Mult.mult_lt_compat_r | eapply Mult.mult_le_compat_l ]. (* wow *)\n      lia.\n      eapply power_positive with (k := S k). lia.\n      forwards: IHk. eauto. simpl in *. lia. }\n  (* There remains to treat separately the case where [n1] is 0. *)\n  intros. intros n1 n2 ?.\n  destruct (Compare_dec.le_gt_dec n1 0).\n    { assert (n1 = 0). lia. subst.\n      rewrite power_of_zero by assumption.\n      eapply power_positive. lia. }\n    { destruct k; [ lia | ].\n      eapply f. lia. } (* 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. destruct k.\n  { subst. simpl. repeat intro. lia. }\n  { eauto with monotonic lia. }\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). { lia. }\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 lia. }\n  assert (k1 < 1 + k2).\n    { eapply power_strictly_inverse_monotonic_in_k with (n := n); eauto with lia. }\n  lia.\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; lia.\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 lia |\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). lia.\n  eauto using Nat.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  lia.\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). lia.\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. destruct n.\n  { subst. simpl. lia. }\n  { eapply Nat.log2_spec. lia. }\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 m.\n  { subst. unfold log2. simpl. lia. }\n  (* Case [m > 0]. *)\n  do 2 log2_spec.\n  eapply power_strictly_inverse_monotonic_in_k_variant with (n := 2); simpl; lia.\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 Nat.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. lia.\n    (* Special cases for [n = 0] and [n = 1]. *)\n    destruct n as [|n']. { eauto. }\n    destruct n' as [|n'']. eauto.\n    (* In the general case, [2 <= n], we use [log2_step]. *)\n    eapply hstep. eapply IHk.\n    cut (1 + log2 ((S (S n'')) / 2) <= k). { lia. }\n    rewrite log2_step by lia.\n    lia.\n  }\n  intros. eapply f with (k := log2 n + 1). lia.\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. lia. }\n    (* Step. *)\n    { intros n IH ?.\n      (* Special case for [n = 1]. *)\n      destruct (Nat.eq_decidable n 1); [ subst n; exact h01 | ].\n      (* In the general case, [2 <= n], we use [log2_step]. *)\n      assert (2 <= n). { lia. }\n      rewrite <- log2_step by assumption.\n      eauto with div2. }\n  }\n  intro n.\n  (* Special case for [n = 0]. *)\n  destruct n; [ exact h00 | ].\n  (* General case. *)\n  eauto with lia.\nQed.\n", "meta": {"author": "Ricagraca", "repo": "i-splay-tree", "sha": "263215b780f52dd0168143def37be537bb07e0ea", "save_path": "github-repos/coq/Ricagraca-i-splay-tree", "path": "github-repos/coq/Ricagraca-i-splay-tree/i-splay-tree-263215b780f52dd0168143def37be537bb07e0ea/theories/union_find/math/LibNatExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7501377579220809}}
{"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 Import Compare.\nRequire Export Nfinite_prod.\nRequire Export Ndiv.\nOpen Scope nat_scope.\n\n(** * Definition of a binomial coefficient using Pascal relation*)\n(** Simple definition *)\nFixpoint Nsimple_binomial (n k : nat) : nat :=\nmatch n with\n| 0 =>\n  match k with\n  | 0 => 1\n  | S _ => 0\n  end\n| S n' =>\n  match k with\n  | 0 => 1\n  | S k' => (Nsimple_binomial n' k') + (Nsimple_binomial n' k)\n  end\nend.\n\n(** Alternative definition *)\nDefinition Nbinomial (n k : nat) : nat :=\nmatch leb k n with\n| true => Nsimple_binomial n k\n| false => 0\nend.\n\n(** * Properties of binomial coefficients *)\n\n(** n choose k is zero if k is greater than n (simple version) *)\nLemma Nsimple_binomial_outside : forall n m,\n  n < m -> Nsimple_binomial n m = 0.\nProof.\ninduction n.\nintros.\ncompute.\ndestruct m.\napply lt_irrefl in H.\ncontradiction.\nreflexivity.\nintros.\nunfold Nsimple_binomial. fold Nsimple_binomial.\ndestruct m.\napply lt_n_O in H.\ncontradiction.\nassert (n<m).\nauto with arith.\nrewrite IHn.\nsimpl.\nassert (n<S m).\nauto with arith.\napply IHn.\nauto.\nauto.\nQed.\n\n(** n choose k is zero if k is greater than n (alternative definition) *)\nLemma Nbinomial_outside : forall n m,\n  n < m -> Nbinomial n m = 0.\nProof.\nintros.\napply leb_correct_conv in H.\nunfold Nbinomial.\nrewrite H.\nreflexivity.\nQed.\n\n(** Special values of binomial coefficients *)\nLemma Nbinomial_0 : forall n, Nbinomial n 0 = 1.\nProof.\ndestruct n.\ncompute. reflexivity.\nunfold Nbinomial.\nassert (leb 0 (S n)=true).\napply leb_correct.\nauto with arith.\nrewrite H. clear H.\nunfold Nsimple_binomial.\nreflexivity.\nQed.\n\nLemma Nbinomial_diag : forall n, Nbinomial n n = 1.\nProof.\ninduction n.\ncompute. reflexivity.\nunfold Nbinomial.\nassert (leb (S n) (S n)=true).\napply leb_correct.\nauto with arith.\nrewrite H. clear H.\nunfold Nsimple_binomial. fold Nsimple_binomial.\nunfold Nbinomial in IHn.\nassert (leb n n=true).\napply leb_correct.\nauto with arith.\nrewrite H in IHn.\nrewrite IHn.\nrewrite Nsimple_binomial_outside.\nauto with arith.\nauto with arith.\nQed.\n\nTheorem Nbinomial_n_1 : forall n, 1 <= n -> Nbinomial n 1 = n.\ninduction n.\ncompute. reflexivity.\nintros.\nunfold Nbinomial.\nassert (leb 1 (S n)=true).\napply leb_correct.\nexact H.\nrewrite H0.\nunfold Nsimple_binomial.\nfold Nsimple_binomial.\ndestruct n.\ncompute. reflexivity.\nassert (Nbinomial (S n) 1=S n).\napply IHn.\nauto with arith.\nclear IHn.\nunfold Nbinomial in H1.\nclear H0.\nassert (leb 1 (S n)=true).\napply leb_correct.\nauto with arith.\nrewrite H0 in H1. clear H0.\nrewrite H1.\ncompute. reflexivity.\nQed.\n\n(** Pascal relation and a generalization for alternative definition *)\nLemma Nbinomial_pascal': forall n k,\n  S k <= n -> Nbinomial n k + Nbinomial n (S k) = Nbinomial (S n) (S k).\nProof.\nintros.\nunfold Nbinomial.\nassert (leb k n=true).\napply leb_correct. auto with arith.\nassert (leb (S k) (S n)=true).\napply leb_correct. auto with arith.\nassert (leb (S k) n=true).\napply leb_correct. auto with arith.\nrewrite H0. clear H0.\nrewrite H1. clear H1.\nrewrite H2. clear H2.\nunfold Nsimple_binomial. fold Nsimple_binomial.\nreflexivity.\nQed.\n\nLemma Nbinomial_pascal: forall n k,\n  k <= n -> Nbinomial n k + Nbinomial n (S k) = Nbinomial (S n) (S k).\nProof.\nintros.\nassert (S k<=n -> Nbinomial n k + Nbinomial n (S k) = Nbinomial (S n) (S k)).\nintro.\napply Nbinomial_pascal'.\nexact H0.\nassert (k=n -> Nbinomial n k + Nbinomial n (S k) = Nbinomial (S n) (S k)).\nintro.\nrewrite H1.\nassert (Nbinomial n (S n)=0).\napply Nbinomial_outside.\nauto with arith.\nrewrite H2. clear H2.\nrewrite Nbinomial_diag.\nrewrite Nbinomial_diag.\nauto with arith.\napply le_le_S_eq in H.\nelim H.\nexact H0.\nexact H1.\nQed.\n\n(** Expression of binomial coefficients using factorial and partial factorial *)\nTheorem Nbinomial_factorial : forall n k, \n  1 <= k -> k <= n -> (fact k) * Nbinomial n k = Nfinite_prod_0_n (pred k) (fun x => n - x).\nProof.\ninduction n.\nintros.\ndestruct k.\napply le_Sn_O in H.\ncontradiction.\nrewrite Nbinomial_outside.\nrewrite mult_0_r.\nassert (Nfinite_prod_0_n (pred (S k)) (fun x : nat => 0 - x) =\n  Nfinite_prod_0_n (pred (S k)) (fun x : nat => 0)).\napply Nfinite_prod_eq_compat.\nauto with arith.\nrewrite H1. clear H1.\nsymmetry.\napply Nfinite_prod_0_absord with k.\nauto with arith.\nreflexivity.\nauto with arith.\nintros.\napply le_le_S_eq in H0.\ndestruct H0.\nassert (Q: S k<=S n).\nexact H0.\napply (le_trans k) in H0.\n\ndestruct k.\napply le_Sn_O in H.\ncontradiction.\n\nrewrite <- Nbinomial_pascal.\nrewrite mult_plus_distr_l.\napply le_le_S_eq in H.\ndestruct H.\napply le_le_S_eq in H0.\ndestruct H0.\n\nrewrite IHn.\nunfold fact. fold fact.\nrewrite <- mult_assoc.\nrewrite IHn.\nassert (exists k', k=S k').\ndestruct k.\napply le_Sn_n in H. contradiction.\nexists k. reflexivity.\ndestruct H1.\nrewrite H1.\n\nassert (pred (S(S x))=S(pred (S x))).\nrewrite pred_of_minus.\nrewrite <- minus_Sn_m.\nrewrite pred_of_minus.\nreflexivity.\nauto with arith.\nrewrite H2.\nrewrite Nfinite_prod_split_upper.\nrewrite Nfinite_prod_split_lower.\nassert (Nfinite_prod_0_n (pred (S x)) (fun k0 : nat => S n - S k0) =\n  Nfinite_prod_0_n (pred (S x)) (fun k0 : nat => n - k0)).\napply Nfinite_prod_subtle_eq_compat.\nintros.\nauto with arith.\nrewrite H3. clear H3.\nassert (Nfinite_prod_0_n (pred (S x)) (fun x0 : nat => n - x0) * (n - S (pred (S x))) =\n  (n - S (pred (S x))) * Nfinite_prod_0_n (pred (S x)) (fun x0 : nat => n - x0)).\nauto with arith.\nrewrite H3. clear H3.\nrewrite <- mult_plus_distr_r.\nrewrite <- minus_n_O.\nassert (S (S x) + (n - S (pred (S x))) = S n).\nrewrite <- pred_Sn.\nassert (n-S x=S n-S(S x)).\nauto with arith.\nrewrite H3.\nsymmetry.\napply le_plus_minus.\nrewrite <- H1.\nauto with arith.\nauto with arith.\nauto with arith.\napply le_trans with (S k).\nauto with arith.\nauto with arith.\nauto with arith.\nauto with arith.\nassert (k=n).\nauto with arith.\nrewrite H1.\nrewrite Nbinomial_diag.\nrewrite Nbinomial_outside.\nrewrite mult_0_r.\nrewrite plus_0_r.\nrewrite mult_1_r.\nrewrite Nfinite_prod_index_reversal.\nrewrite <- H1.\nrewrite Nfactorial_is_finite_prod.\nrewrite <- pred_Sn.\napply Nfinite_prod_subtle_eq_compat.\nintros.\nassert (exists p, k=k0+p).\napply Nle_plus.\nexact H2.\ndestruct H3.\nrewrite plus_comm in H3. \nrewrite H3.\nrewrite plus_comm.\nassert (x-0=k0+x-(k0+0)).\napply minus_plus_simpl_l_reverse.\nrewrite <- minus_n_O in H4.\nrewrite plus_0_r in H4.\nrewrite <- H4.\nassert (S(k0+x)=S k0+x).\nauto with arith.\nrewrite H5. clear H4. clear H5.\nassert (S k0-0=x+S k0-(x+0)).\napply minus_plus_simpl_l_reverse.\nrewrite plus_0_r in H4.\nrewrite <- minus_n_O in H4.\nrewrite plus_comm in H4.\nexact H4.\nauto with arith.\nassert (0=k).\nauto with arith.\nrewrite <- H1.\nunfold fact. unfold iter_nat. unfold pred.\nunfold Nfinite_prod_0_n.\nunfold Nbinomial.\nassert (leb 0 n=true).\napply leb_correct.\nauto with arith.\nrewrite H2. clear H2.\nassert (leb 1 n=true).\napply leb_correct.\nrewrite <- H1 in Q.\nauto with arith.\nrewrite H2.\nassert (Nbinomial n 0=1).\napply Nbinomial_0.\nassert (Nbinomial n 1=n).\napply Nbinomial_n_1.\nrewrite <- H1 in Q.\nauto with arith.\nunfold Nbinomial in H3.\nunfold Nbinomial in H4.\nrewrite H2 in H4.\nassert (leb 0 n=true).\nauto.\nrewrite H5 in H3.\nrewrite H3.\nrewrite H4.\nsimpl.\nauto with arith.\nauto with arith.\nauto with arith.\nrewrite H0.\nrewrite Nbinomial_diag.\nrewrite <- pred_Sn.\nrewrite Nfactorial_is_finite_prod.\nrewrite Nfinite_prod_index_reversal.\nrewrite mult_1_r.\napply Nfinite_prod_subtle_eq_compat.\nintros.\napply minus_Sn_m.\nexact H1.\nQed.\n\n(** Divisibility of binomial coefficients in prime case *)\nTheorem Nbinomial_div : forall p k,\n  0 < k < p -> Nprime p -> (p | Nbinomial p k).\nintros.\nassert((p|(fact k)*Nbinomial p k)).\nrewrite Nbinomial_factorial.\napply Nfinite_prod_div with 0.\ndestruct H.\ndestruct k.\ninversion H.\nsimpl. auto with arith.\nrewrite <- minus_n_O. apply Ndiv_n_n.\ndestruct H.\ndestruct k.\ninversion H.\nauto with arith.\ndestruct H.\nauto with arith.\napply Ngauss with (fact k).\nauto.\nclear H1.\ngeneralize k H.\nclear H k.\ninduction k.\nintros.\ninversion H. inversion H1.\nintros.\ndestruct H.\nunfold fact. fold fact.\ndestruct k.\nsimpl.\napply Nrel_prime_1.\n\napply Nrel_prime_mult_compat.\napply Nrel_prime_comm.\napply Nprime_le_rel_prime.\nauto.\nsplit.\nauto with arith.\nauto.\napply IHk.\nsplit.\nauto with arith.\nauto with arith.\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/Nbinomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7501377549895926}}
{"text": "Require Import init.\n\nRequire Export relation.\nRequire Export plus_group.\n\nClass OrderLplus U `{Plus U, Order U} := {\n    le_lplus : ∀ {a b} c, a ≤ b → c + a ≤ c + b\n}.\nClass OrderRplus U `{Plus U, Order U} := {\n    le_rplus : ∀ {a b} c, a ≤ b → a + c ≤ b + c\n}.\nClass OrderPlusLcancel U `{Plus U, Order U} := {\n    le_plus_lcancel : ∀ {a b} c, c + a ≤ c + b → a ≤ b\n}.\nClass OrderPlusRcancel U `{Plus U, Order U} := {\n    le_plus_rcancel : ∀ {a b} c, a + c ≤ b + c → a ≤ b\n}.\n\nClass OrderPlus U `{\n    OPP : AllPlus U,\n    OPO : TotalOrder U,\n    UOP : @OrderLplus U UP UO,\n    UOPR : @OrderRplus U UP UO,\n    UOPC : @OrderPlusLcancel U UP UO,\n    UOPCR : @OrderPlusRcancel U UP UO\n}.\n\n(* begin hide *)\nSection OrderPlusImply.\n\nContext {U} `{OrderPlus U}.\n\nGlobal Instance le_lplus_rplus : OrderRplus U.\nProof.\n    split.\n    intros a b c leq.\n    do 2 rewrite (plus_comm _ c).\n    apply le_lplus.\n    exact leq.\nQed.\n\nGlobal Instance le_lcancel_rcancel : OrderPlusRcancel U.\nProof.\n    split.\n    intros a b c leq.\n    do 2 rewrite (plus_comm _ c) in leq.\n    apply le_plus_lcancel in leq.\n    exact leq.\nQed.\n\nGlobal Instance le_plus_linv_lcancel : OrderPlusLcancel U.\nProof.\n    split.\n    intros a b c leq.\n    apply le_lplus with (-c) in leq.\n    do 2 rewrite plus_llinv in leq.\n    exact leq.\nQed.\nGlobal Instance le_plus_rinv_rcancel : OrderPlusRcancel U.\nProof.\n    split.\n    intros a b c leq.\n    apply le_rplus with (-c) in leq.\n    do 2 rewrite plus_rrinv in leq.\n    exact leq.\nQed.\n\nEnd OrderPlusImply.\n\n\nSection OrderPlus.\n\nContext {U} `{OrderPlus U}.\n\n(* end hide *)\nTheorem le_lrplus : ∀ {a b c d}, a ≤ b → c ≤ d → a + c ≤ b + d.\nProof.\n    intros a b c d ab cd.\n    apply le_rplus with c in ab.\n    apply le_lplus with b in cd.\n    exact (trans ab cd).\nQed.\n\nTheorem lt_lplus : ∀ {a b} c, a < b → c + a < c + b.\nProof.\n    intros a b c [leq neq].\n    split.\n    -   apply le_lplus.\n        exact leq.\n    -   intro contr.\n        apply plus_lcancel in contr.\n        contradiction.\nQed.\n\nTheorem lt_rplus : ∀ {a b} c, a < b → a + c < b + c.\nProof.\n    intros a b c [leq neq].\n    split.\n    -   apply le_rplus.\n        exact leq.\n    -   intro contr.\n        apply plus_rcancel in contr.\n        contradiction.\nQed.\n\nTheorem lt_lrplus : ∀ {a b c d}, a < b → c < d → a + c < b + d.\nProof.\n    intros a b c d ab cd.\n    apply lt_rplus with c in ab.\n    apply lt_lplus with b in cd.\n    exact (trans ab cd).\nQed.\n\nTheorem le_lt_lrplus : ∀ {a b c d}, a ≤ b → c < d → a + c < b + d.\nProof.\n    intros a b c d ab cd.\n    apply le_rplus with c in ab.\n    apply lt_lplus with b in cd.\n    exact (le_lt_trans ab cd).\nQed.\n\nTheorem lt_le_lrplus : ∀ {a b c d}, a < b → c ≤ d → a + c < b + d.\nProof.\n    intros a b c d ab cd.\n    apply lt_rplus with c in ab.\n    apply le_lplus with b in cd.\n    exact (lt_le_trans ab cd).\nQed.\n\nTheorem lt_plus_lcancel : ∀ {a b} c, c + a < c + b → a < b.\nProof.\n    intros a b c [leq neq].\n    split.\n    -   apply le_plus_lcancel in leq.\n        exact leq.\n    -   intro contr.\n        rewrite contr in neq.\n        contradiction.\nQed.\n\nTheorem lt_plus_rcancel : ∀ {a b} c, a + c < b + c → a < b.\nProof.\n    intros a b c [leq neq].\n    split.\n    -   apply le_plus_rcancel in leq.\n        exact leq.\n    -   intro contr.\n        rewrite contr in neq.\n        contradiction.\nQed.\n\nTheorem le_plus_llmove : ∀ a b c, a + b ≤ c ↔ b ≤ -a + c.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply le_lplus with (-a) in eq.\n        rewrite plus_llinv in eq.\n        exact eq.\n    -   apply le_lplus with a in eq.\n        rewrite plus_lrinv in eq.\n        exact eq.\nQed.\nTheorem le_plus_lrmove : ∀ a b c, a + b ≤ c ↔ a ≤ c - b.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply le_rplus with (-b) in eq.\n        rewrite plus_rrinv in eq.\n        exact eq.\n    -   apply le_rplus with b in eq.\n        rewrite plus_rlinv in eq.\n        exact eq.\nQed.\nTheorem le_plus_rlmove : ∀ a b c, a ≤ b + c ↔ -b + a ≤ c.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply le_lplus with (-b) in eq.\n        rewrite plus_llinv in eq.\n        exact eq.\n    -   apply le_lplus with b in eq.\n        rewrite plus_lrinv in eq.\n        exact eq.\nQed.\nTheorem le_plus_rrmove : ∀ a b c, a ≤ b + c ↔ a - c ≤ b.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply le_rplus with (-c) in eq.\n        rewrite plus_rrinv in eq.\n        exact eq.\n    -   apply le_rplus with c in eq.\n        rewrite plus_rlinv in eq.\n        exact eq.\nQed.\n\nTheorem le_plus_0_ab_na_b : ∀ a b, 0 ≤ a + b ↔ -a ≤ b.\nProof.\n    intros a b.\n    rewrite le_plus_rlmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem le_plus_0_ab_nb_a : ∀ a b, 0 ≤ a + b ↔ -b ≤ a.\nProof.\n    intros a b.\n    rewrite le_plus_rrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem le_plus_ab_0_a_nb : ∀ a b, a + b ≤ 0 ↔ a ≤ -b.\nProof.\n    intros a b.\n    rewrite le_plus_lrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem le_plus_ab_0_b_na : ∀ a b, a + b ≤ 0 ↔ b ≤ -a.\nProof.\n    intros a b.\n    rewrite le_plus_llmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\n\nTheorem le_plus_a_0_ab_b : ∀ a b, a ≤ 0 ↔ a + b ≤ b.\nProof.\n    intros a b.\n    split; intros leq.\n    -   apply le_rplus with b in leq.\n        rewrite plus_lid in leq.\n        exact leq.\n    -   apply le_plus_rcancel with b.\n        rewrite plus_lid.\n        exact leq.\nQed.\nTheorem le_plus_a_0_ba_b : ∀ a b, a ≤ 0 ↔ b + a ≤ b.\nProof.\n    intros a b.\n    split; intros leq.\n    -   apply le_lplus with b in leq.\n        rewrite plus_rid in leq.\n        exact leq.\n    -   apply le_plus_lcancel with b.\n        rewrite plus_rid.\n        exact leq.\nQed.\nTheorem le_plus_0_a_b_ab : ∀ a b, 0 ≤ a ↔ b ≤ a + b.\nProof.\n    intros a b.\n    split; intros leq.\n    -   apply le_rplus with b in leq.\n        rewrite plus_lid in leq.\n        exact leq.\n    -   apply le_plus_rcancel with b.\n        rewrite plus_lid.\n        exact leq.\nQed.\nTheorem le_plus_0_a_b_ba : ∀ a b, 0 ≤ a ↔ b ≤ b + a.\nProof.\n    intros a b.\n    split; intros leq.\n    -   apply le_lplus with b in leq.\n        rewrite plus_rid in leq.\n        exact leq.\n    -   apply le_plus_lcancel with b.\n        rewrite plus_rid.\n        exact leq.\nQed.\n\nTheorem le_plus_0_nab_a_b : ∀ a b, 0 ≤ -a + b ↔ a ≤ b.\nProof.\n    intros a b.\n    rewrite <- le_plus_llmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem le_plus_anb_0_a_b : ∀ a b, a - b ≤ 0 ↔ a ≤ b.\nProof.\n    intros a b.\n    rewrite <- le_plus_rrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem le_plus_nab_0_b_a : ∀ a b, -a + b ≤ 0 ↔ b ≤ a.\nProof.\n    intros a b.\n    rewrite <- le_plus_rlmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem le_plus_0_anb_b_a : ∀ a b, 0 ≤ a - b ↔ b ≤ a.\nProof.\n    intros a b.\n    rewrite <- le_plus_lrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\n\nTheorem lt_plus_llmove : ∀ a b c, a + b < c ↔ b < -a + c.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply lt_lplus with (-a) in eq.\n        rewrite plus_llinv in eq.\n        exact eq.\n    -   apply lt_lplus with a in eq.\n        rewrite plus_lrinv in eq.\n        exact eq.\nQed.\nTheorem lt_plus_lrmove : ∀ a b c, a + b < c ↔ a < c - b.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply lt_rplus with (-b) in eq.\n        rewrite plus_rrinv in eq.\n        exact eq.\n    -   apply lt_rplus with b in eq.\n        rewrite plus_rlinv in eq.\n        exact eq.\nQed.\nTheorem lt_plus_rlmove : ∀ a b c, a < b + c ↔ -b + a < c.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply lt_lplus with (-b) in eq.\n        rewrite plus_llinv in eq.\n        exact eq.\n    -   apply lt_lplus with b in eq.\n        rewrite plus_lrinv in eq.\n        exact eq.\nQed.\nTheorem lt_plus_rrmove : ∀ a b c, a < b + c ↔ a - c < b.\nProof.\n    intros a b c.\n    split; intros eq.\n    -   apply lt_rplus with (-c) in eq.\n        rewrite plus_rrinv in eq.\n        exact eq.\n    -   apply lt_rplus with c in eq.\n        rewrite plus_rlinv in eq.\n        exact eq.\nQed.\n\nTheorem lt_plus_0_ab_na_b : ∀ a b, 0 < a + b ↔ -a < b.\nProof.\n    intros a b.\n    rewrite lt_plus_rlmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem lt_plus_0_ab_nb_a : ∀ a b, 0 < a + b ↔ -b < a.\nProof.\n    intros a b.\n    rewrite lt_plus_rrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem lt_plus_ab_0_a_nb : ∀ a b, a + b < 0 ↔ a < -b.\nProof.\n    intros a b.\n    rewrite lt_plus_lrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem lt_plus_ab_0_b_na : ∀ a b, a + b < 0 ↔ b < -a.\nProof.\n    intros a b.\n    rewrite lt_plus_llmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\n\nTheorem lt_plus_a_0_ab_b : ∀ a b, a < 0 ↔ a + b < b.\nProof.\n    intros a b.\n    split; intros ltq.\n    -   apply lt_rplus with b in ltq.\n        rewrite plus_lid in ltq.\n        exact ltq.\n    -   apply lt_plus_rcancel with b.\n        rewrite plus_lid.\n        exact ltq.\nQed.\nTheorem lt_plus_a_0_ba_b : ∀ a b, a < 0 ↔ b + a < b.\nProof.\n    intros a b.\n    split; intros ltq.\n    -   apply lt_lplus with b in ltq.\n        rewrite plus_rid in ltq.\n        exact ltq.\n    -   apply lt_plus_lcancel with b.\n        rewrite plus_rid.\n        exact ltq.\nQed.\nTheorem lt_plus_0_a_b_ab : ∀ a b, 0 < a ↔ b < a + b.\nProof.\n    intros a b.\n    split; intros ltq.\n    -   apply lt_rplus with b in ltq.\n        rewrite plus_lid in ltq.\n        exact ltq.\n    -   apply lt_plus_rcancel with b.\n        rewrite plus_lid.\n        exact ltq.\nQed.\nTheorem lt_plus_0_a_b_ba : ∀ a b, 0 < a ↔ b < b + a.\nProof.\n    intros a b.\n    split; intros ltq.\n    -   apply lt_lplus with b in ltq.\n        rewrite plus_rid in ltq.\n        exact ltq.\n    -   apply lt_plus_lcancel with b.\n        rewrite plus_rid.\n        exact ltq.\nQed.\n\nTheorem lt_plus_0_nab_a_b : ∀ a b, 0 < -a + b ↔ a < b.\nProof.\n    intros a b.\n    rewrite <- lt_plus_llmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem lt_plus_anb_0_a_b : ∀ a b, a - b < 0 ↔ a < b.\nProof.\n    intros a b.\n    rewrite <- lt_plus_rrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem lt_plus_nab_0_b_a : ∀ a b, -a + b < 0 ↔ b < a.\nProof.\n    intros a b.\n    rewrite <- lt_plus_rlmove.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem lt_plus_0_anb_b_a : ∀ a b, 0 < a - b ↔ b < a.\nProof.\n    intros a b.\n    rewrite <- lt_plus_lrmove.\n    rewrite plus_lid.\n    reflexivity.\nQed.\n\nTheorem neg_pos : ∀ a, a ≤ 0 ↔ 0 ≤ -a.\nProof.\n    intros a.\n    rewrite <- le_plus_ab_0_a_nb.\n    rewrite plus_lid.\n    reflexivity.\nQed.\nTheorem neg_pos2 : ∀ a, a < 0 ↔ 0 < -a.\nProof.\n    intros a.\n    rewrite <- lt_plus_ab_0_a_nb.\n    rewrite plus_lid.\n    reflexivity.\nQed.\n\nTheorem pos_neg : ∀ a, 0 ≤ a ↔ -a ≤ 0.\nProof.\n    intros a.\n    rewrite <- le_plus_0_ab_na_b.\n    rewrite plus_rid.\n    reflexivity.\nQed.\nTheorem pos_neg2 : ∀ a, 0 < a ↔ -a < 0.\nProof.\n    intros a.\n    rewrite <- lt_plus_0_ab_na_b.\n    rewrite plus_rid.\n    reflexivity.\nQed.\n\nTheorem le_neg : ∀ a b, a ≤ b ↔ -b ≤ -a.\nProof.\n    intros a b.\n    rewrite <- le_plus_0_anb_b_a.\n    rewrite le_plus_0_ab_na_b.\n    reflexivity.\nQed.\nTheorem lt_neg : ∀ a b, a < b ↔ -b < -a.\nProof.\n    intros a b.\n    rewrite <- lt_plus_0_anb_b_a.\n    rewrite lt_plus_0_ab_na_b.\n    reflexivity.\nQed.\n\nTheorem le_half_rneg : ∀ a b, a ≤ -b ↔ b ≤ -a.\nProof.\n    intros a b.\n    rewrite le_neg.\n    rewrite neg_neg.\n    reflexivity.\nQed.\nTheorem lt_half_rneg : ∀ a b, a < -b ↔ b < -a.\nProof.\n    intros a b.\n    rewrite lt_neg.\n    rewrite neg_neg.\n    reflexivity.\nQed.\nTheorem le_half_lneg : ∀ a b, -a ≤ b ↔ -b ≤ a.\nProof.\n    intros a b.\n    rewrite le_neg.\n    rewrite neg_neg.\n    reflexivity.\nQed.\nTheorem lt_half_lneg : ∀ a b, -a < b ↔ -b < a.\nProof.\n    intros a b.\n    rewrite lt_neg.\n    rewrite neg_neg.\n    reflexivity.\nQed.\n\nTheorem le_pos_plus : ∀ {a b}, 0 ≤ a → 0 ≤ b → 0 ≤ a + b.\nProof.\n    intros a b a_pos b_pos.\n    rewrite <- (plus_rid 0).\n    apply le_lrplus; assumption.\nQed.\nTheorem lt_pos_plus : ∀ {a b}, 0 < a → 0 < b → 0 < a + b.\nProof.\n    intros a b a_pos b_pos.\n    rewrite <- (plus_rid 0).\n    apply lt_lrplus; assumption.\nQed.\nTheorem le_lt_pos_plus : ∀ {a b}, 0 ≤ a → 0 < b → 0 < a + b.\nProof.\n    intros a b a_pos b_pos.\n    rewrite <- (plus_rid 0).\n    apply le_lt_lrplus; assumption.\nQed.\nTheorem lt_le_pos_plus : ∀ {a b}, 0 < a → 0 ≤ b → 0 < a + b.\nProof.\n    intros a b a_pos b_pos.\n    rewrite <- (plus_rid 0).\n    apply lt_le_lrplus; assumption.\nQed.\n\nTheorem le_neg_plus : ∀ {a b}, a ≤ 0 → b ≤ 0 → a + b ≤ 0.\nProof.\n    intros a b a_neg b_neg.\n    rewrite <- (plus_rid 0).\n    apply le_lrplus; assumption.\nQed.\nTheorem lt_neg_plus : ∀ {a b}, a < 0 → b < 0 → a + b < 0.\nProof.\n    intros a b a_neg b_neg.\n    rewrite <- (plus_rid 0).\n    apply lt_lrplus; assumption.\nQed.\nTheorem le_lt_neg_plus : ∀ {a b}, a ≤ 0 → b < 0 → a + b < 0.\nProof.\n    intros a b a_neg b_neg.\n    rewrite <- (plus_rid 0).\n    apply le_lt_lrplus; assumption.\nQed.\nTheorem lt_le_neg_plus : ∀ {a b}, a < 0 → b ≤ 0 → a + b < 0.\nProof.\n    intros a b a_neg b_neg.\n    rewrite <- (plus_rid 0).\n    apply lt_le_lrplus; assumption.\nQed.\n(* begin hide *)\nEnd OrderPlus.\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_plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7501212058640347}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : 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 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/goal33conj113_coqofml_wM5pHn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7501212019484416}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Program.Combinators.\nRequire Import Coq.Arith.Peano_dec.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Le.\nRequire Import PeanoNat.\nRequire Import List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\n(** Nominal Sets *)\n(* In 2011, Andrew Pitts published his paper 'Nominal Sets'. We formalize parts of\nchapter 1 to 3 of his paper, which can be found at:\n#<a href=\"http://www.cs.nott.ac.uk/~pszvc/mgs/MGS2011_nominal_sets.pdf\">\nhttp://www.cs.nott.ac.uk/~pszvc/mgs/MGS2011_nominal_sets.pdf</a># *)\n\n(** * Groups *)\n(* In this section we define groups and prove very basic lemmas about them.\n   These lemmas will later be used to simplify statements about group elements. *)\n\n(* Groups are a type having an identity element, an inverse function and an operation on\n   elements. The elements respeect the left and right identity as well as inverse laws. *)\nStructure group :=\n  {\n    group_obj :> Type;\n    group_id : group_obj;\n    group_inv : group_obj -> group_obj;\n    group_op : group_obj -> group_obj -> group_obj;\n    group_assoc : forall x y z, group_op (group_op x y) z = group_op x (group_op y z);\n    group_left_id : forall x, group_op group_id x = x;\n    group_right_id : forall x, group_op x group_id = x;\n    group_left_inv : forall x, group_op (group_inv x) x = group_id;\n    group_right_inv : forall x, group_op x (group_inv x) = group_id;\n  }.\n\nNotation \"1\" := (group_id _).\nNotation \"x ^-1\" := (group_inv _ x) (at level 30, format \"x ^-1\").\nNotation \"x * y\" := (group_op _ x y).\n\n(* We show that the right inverse is unique in order to prove the following two well known\n   lemmas about inverses. These lemmas can be used to simplify goals. *)\nLemma group_inv_unique (G: group) (g h: G) : g * h = 1 -> g^-1 = h.\nProof.\n  intros H. rewrite <- (group_right_id _ (g^-1)). rewrite <- H, <- group_assoc.\n  now rewrite group_left_inv, group_left_id.\nQed.\n\nLemma group_inv_id (G: group) : 1^-1 = (group_id G).\nProof.\n  apply group_inv_unique. now apply group_left_id.\nQed.\n\nLemma group_inv_op (G: group) (g h: G) : (g * h)^-1 = h^-1 * g^-1.\nProof.\n  apply group_inv_unique. rewrite group_assoc, <- (group_assoc _ h).\n  rewrite group_right_inv, group_left_id. now apply group_right_inv.\nQed.\n\n(* A homomorphism between groups G and H is a function from G to H which respects the\n   group laws. *)\nStructure homomorphism (G H: group) :=\n  {\n    hom :> G -> H;\n    hom_id: hom 1 = 1;\n    hom_op: forall x y, hom (x * y) = (hom x) * (hom y);\n    hom_inv: forall x, hom (x^-1) = (hom x)^-1;\n  }.\n\n\n(** * G-sets *)\n(* Now we define G-sets and show that these are compositional for product, sum and\n   function types. *)\n\n(* A G-set is a type X with a group action on X which respects the group structure of G. *)\nStructure G_set (G: group) :=\n  {\n    G_set_X :> Type;\n    action: G -> G_set_X -> G_set_X;\n    G_set_id: forall x,  (action 1 x) = x;\n    G_set_assoc: forall g h x, (action g (action h x)) = (action (g * h) x);\n  }.\n\nNotation \"g ** x\" := (action _ g x) (at level 45, right associativity).\n\n(* We define the tactic gsimpl to simplify goals by using the group and G-set laws. *)\nLtac gsimpl :=\n  repeat progress rewrite ?group_left_id, ?group_right_id, ?group_left_inv, ?group_right_inv,\n  ?group_inv_id, ?group_inv_op,\n  ?G_set_id, ?G_set_assoc.\n\n(* A group element g acts on a pair (x, y) by acting on x and y simpultaneously. *)\nDefinition prod_action (G: group) (X Y: G_set G) (g: G) (p: X * Y) : X * Y :=\n  match p with\n  | (x, y) => (g ** x, g ** y)\n  end.\n\nArguments prod_action {G X Y}.\n\n(* Using above action the product of two G-sets X and Y is again a G-set. *)\nCanonical Structure G_set_prod (G: group) (X Y: G_set G) : G_set G.\napply (@Build_G_set G (X * Y)%type prod_action).\n- intros [x y]. cbn. now gsimpl.\n- intros g h [x y]. cbn. now gsimpl.\nDefined.\n\n(* Similar to the action on pairs, g acts on a sum s by acting on the by s encapsulated value. *)\nDefinition sum_action (G: group) (X Y: G_set G) (g: G) (s: X + Y) : X + Y :=\n  match s with\n  | inl x => inl (g ** x)\n  | inr y => inr (g ** y)\n  end.\n\nArguments sum_action {G X Y}.\n\n(* Above action yields a G-set on the sum of two G-sets. *)\nCanonical Structure G_set_sum (G: group) (X Y: G_set G) : G_set G.\napply (@Build_G_set G (X + Y) sum_action).\n- intros [x|y]; cbn; now gsimpl.\n- intros g h [x|y]; cbn; now gsimpl.\nDefined.\n\n(* We define the following action on functions from G-set X to G-set Y. *)\nDefinition func_action (G: group) (X Y: G_set G) (g: G) (F: X -> Y) : X -> Y :=\n  fun x => g ** F (g^-1 ** x).\n\nArguments func_action {G X Y}.\n\n(* By this action we obtain a G-set on functions from G-set X to G-set Y. *)\nCanonical Structure func (G: group) (X Y: G_set G) : G_set G.\napply (@Build_G_set G (X -> Y) func_action).\n- intros F. unfold func_action. extensionality x. now gsimpl.\n- intros g h F. extensionality x. unfold func_action. now gsimpl.\nDefined.\n\n(* A function F is called equivariant if the group action and the application of F commute. *)\nDefinition equiv_func {G: group} {X Y: G_set G} (F: X -> Y) :=\n  forall (x: X) (g: G), F (g ** x) = g ** F x.\n\n(* We call a subset (given as predicate P) of a G-set X equivariant if it is closed under\n   group actions. *)\nDefinition equiv_subset (G: group) (X: G_set G) (P: X -> Prop) :=\n  forall g x, P x -> P (g ** x).\n\n\n(** * Permutations *)\n(* In this section we define permutations and show that they form a group called Perm.\n   For Perm-sets X (G-sets with Perm as underlying group) we define the notion of support\n   and use it to state when a name is unused/fresh for a given element of X. *)\n\n(* We use the natural numbers as atoms, i.e. names. This is convenient since for a finite\n   structure we can easily find an unused/fresh name. *)\nDefinition atom := nat.\n\n(* Permutations are bijective functions over atoms. We model this by requiring the existence\n   of an inverse function. *)\nStructure perm :=\n  {\n    perm_f:> atom -> atom;\n    perm_g: atom -> atom;\n    perm_right_inv: forall a, perm_f (perm_g a) = a;\n    perm_left_inv: forall a, perm_g (perm_f a) = a;\n  }.\n\n(* Permutations form a group. Thus we define identity and inverse permutations, as well as\n   the composition operation on permutations. *)\nDefinition perm_id : perm.\n  apply (@Build_perm (@id atom) (@id atom)); intros a; reflexivity.\nDefined.\n\nDefinition perm_inv (pi: perm) : perm.\n  destruct pi as [f g H1 H2]. apply (Build_perm g f H2 H1).\nDefined.\n\nDefinition perm_op (pi pi': perm) : perm.\n  destruct pi as [f g H1 H2]. destruct pi' as [f' g' H3 H4].\n  apply (Build_perm (compose f f') (compose g' g)).\n  - intros a. unfold compose. now rewrite H3, H1.\n  - intros a. unfold compose. now rewrite H2, H4.\nDefined.\n\n(* The following axiom states that permutations are uniquely determined by their behavior\n   on atoms. *)\nAxiom perm_eq : forall (pi pi': perm), (forall a, pi a = pi' a) -> pi = pi'.\n\n(* Using the above definitions we obtain the symmetric group, i.e. group of permutations.\n   We denote this group by Perm. *)\nCanonical Structure group_perm : group.\napply (@Build_group _ perm_id perm_inv perm_op).\n- intros pi1 pi2 pi3. apply perm_eq. intros a. destruct pi1, pi2, pi3. unfold perm_op.\n  cbn. now rewrite compose_assoc.\n- intros pi. apply perm_eq. intros a. destruct pi. unfold perm_op. cbn.\n  now rewrite compose_id_left.\n- intros pi. apply perm_eq. intros a. destruct pi. unfold perm_op. cbn.\n  now rewrite compose_id_right.\n- intros pi. apply perm_eq. intros a. destruct pi. unfold perm_op. cbn.\n  unfold id, compose. auto.\n- intros pi. apply perm_eq. intros a. destruct pi. unfold perm_op. cbn.\n  unfold id, compose. auto.\nDefined.\n\n(* We choose a convenient name for the type of Perm-sets. *)\nDefinition perm_set := G_set group_perm.\n\n(* A list of atoms A supports an element x of a Perm-set X if each permutation which\n   holds all elements of A does not change x aswell. This means all atoms which are\n   not in A do not play a role in x in some sense. *)\nDefinition support {X: perm_set} (A: list atom) (x: X) :=\n  forall (pi: perm), (forall a, In a A -> pi a = a) -> pi ** x = x.\n\n(* In the special case of functions on Perm-sets we can characterize support more precisely. *)\nLemma support_func (X Y: perm_set) (A: list atom) (F: X -> Y) :\n  support A F <-> forall (pi: perm), (forall a, In a A -> pi a = a) -> forall x, F (pi ** x) = pi ** F x.\nProof.\n  split; intros H.\n  - intros pi H' x. specialize (H pi H').\n    assert (E: F (pi ** x) = (pi ** F) (pi ** x)) by now rewrite H.\n    rewrite E. cbn. unfold func_action. now gsimpl.\n  - intros pi H'. specialize (H (pi^-1)). extensionality x. cbn. unfold func_action.\n    rewrite H; gsimpl; auto. intros a Aa. specialize (H' a Aa). destruct pi as [pi pi' Hpi Hpi'].\n    now rewrite <- H' at 1.\nQed.\n\n(* If all elements of a Perm-set X are supported, i.e. there is a list A supports the\n   element, then then we call X nominal. *)\nDefinition nominal (X: perm_set) := forall (x: X), { A : _ & support A x}.\n\n(* The predicate supp is the intersection of all supports of the given element x.\n   It characterizes the atoms that are relevant for x in some sense. *)\nDefinition supp {X: perm_set} (x: X) := fun a => forall A, support A x -> In a A.\n\n(* The predicate supp is true only for elements of every support A. *)\nLemma supp_sub_support (X: perm_set) A (x: X) :\n  support A x -> forall a, supp x a -> In a A.\nProof.\n  intros S a H. apply H, S.\nQed.\n\n(* We say an atom a is fresh in y if it is not in (supp y). This means is not\n   relevant for y. *)\nDefinition atom_freshness {Y: perm_set} a (y: Y) := ~ supp y a.\n\nNotation \"a # y\" := (atom_freshness a y) (at level 40).\n\n(* In general, x is fresh for y if the intersection of (supp x) and (supp y) is empty.\n   So, there is no atom relevant for both of them. *)\nDefinition freshness {X Y: perm_set} (x: X) (y: Y) :=\n  forall a, ~ (supp x a /\\ supp y a).\n\n\n(** ** Finite Permutations *)\n(* In this subsection we consider the special case of finite permutations. Those are\n   permutations that change only finitely many atoms. *)\n\n(* Finite permutations change only finitely many atoms. *)\nDefinition fin_perm (pi: perm) := exists l, forall a, ~ In a l -> pi a = a.\n\n(* Transpositions swap two atoms a and b. *)\nDefinition transp (a b c: atom) :=\n  if (Nat.eq_dec c a) then b else if (Nat.eq_dec c b) then a else c.\n\n(* We define a tactic to simplify transpositions. *)\nLtac transpsimpl :=\n  match goal with\n  | [ |- context C[transp] ] => unfold transp; transpsimpl\n  | [ |- context C[Nat.eq_dec ?a ?a] ] => let H := fresh \"H\" in destruct (Nat.eq_dec a a) as [_|H];\n                                                              [| exfalso; apply H; reflexivity]\n  | [ |- context C[Nat.eq_dec ?a ?b] ] => let H := fresh \"H\" in destruct (Nat.eq_dec a b) as [H|H];\n                                                              [rewrite H|]\n  | _ => try congruence\n  end.\n\n(* Transpositions are involutions, i.e. self-invers. *)\nLemma transp_involution a b c : transp a b (transp a b c) = c.\nProof.\n  repeat transpsimpl; congruence.\nQed.\n\n(* Clearly, transpositions are permutations. *)\nCanonical Structure transp_perm (a b: atom) : perm :=\n  Build_perm (transp a b) (transp a b) (transp_involution a b) (transp_involution a b).\n\n(* Especially, transpositions are finite transpositions. *)\nLemma transp_fin_perm (a b: atom) : fin_perm (transp_perm a b).\nProof.\n  exists [a;b]. cbn. intros x H. repeat transpsimpl; exfalso; auto.\nQed.\n\n(* We define a tactic to simplify transpositions seen as permutations. *)\nLtac transptac :=\n  match goal with\n  | [ |- context C[transp_perm] ] => (progress cbn); transptac\n  | _ => repeat transpsimpl\n  end.\n\n(** * Fresh Names *)\n(* In this section we show how to get a fresh name/atom for a element x given a\n   support A for x. One possibility is to compute the maximum of A and taking the\n   successor of it. This atom is not contained in A and thus fresh for x. *)\n\nModule fresh_atom.\n  (* Compute the maximum of al list A by folding A. *)\n  Definition max_list A := fold_left max A 0.\n\n  (* Take the successor of the maximum to obtain a new atom. *)\n  Definition new_atom A := S (max_list A).\n\n  (* We prove that (fold_left max A) is monotone and increasing for a list A. *)\n  Lemma fold_max_mono A n m : n <= m -> fold_left max A n <= fold_left max A m.\n  Proof.\n    revert n m. induction A as [|a A IH]; auto with arith.\n    intros n m H. cbn. now apply IH, Nat.max_le_compat_r.\n  Qed.\n\n  Lemma fold_max_inc A b : b <= fold_left max A b.\n  Proof.\n    induction A as [|a A IH]; auto.\n    cbn. eapply le_trans. now apply IH. apply fold_max_mono, Nat.le_max_l.\n  Qed.\n\n  (* We use both above lemmas to show that the maximum of A is larger or equal to\n     all elements of A. *)\n  Lemma all_le A : forall a, In a A -> a <= max_list A.\n  Proof.\n    induction A as [| b A IH]; intros a; [intros []|intros [E|H]].\n    - rewrite E. cbn. apply fold_max_inc.\n    - eapply le_trans. now apply IH. cbn. apply fold_max_mono. auto with arith.\n  Qed.\n\n  (* Using above lemma we see that the new atom cannot be contained in A. *)\n  Lemma new_atom_fresh A a : new_atom A <= a -> ~ In a A.\n  Proof.\n    intros H H'. eapply Nat.nle_succ_diag_l.\n    eapply Nat.le_trans; [exact H | now apply all_le].\n  Qed.\n\n  (* Thus, the new atom is a witness for a fresh one. *)\n  Lemma fresh_atom A: {a: atom | ~ In a A}.\n  Proof.\n    exists (new_atom A). intros H. now eapply new_atom_fresh, H.\n  Qed.\n\nEnd fresh_atom.\n\n(* We can show now that if x has a support than we can compute a fresh atom for x\n   using the above construcion . *)\nLemma support_fresh_atom (X: perm_set) A (x: X) : support A x -> {a | a # x}.\nProof.\n  intros H. destruct (fresh_atom.fresh_atom A) as [a H'].\n  exists a. intros Su. unfold supp in Su. apply H', Su, H.\nQed.\n", "meta": {"author": "jobard", "repo": "nominal-sets", "sha": "45444d8efb67ec871e023537298bcc6dbff787a3", "save_path": "github-repos/coq/jobard-nominal-sets", "path": "github-repos/coq/jobard-nominal-sets/nominal-sets-45444d8efb67ec871e023537298bcc6dbff787a3/coq/nominal_set_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7500857127717273}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.omega.Omega.\n\nLemma firstn_app_L : forall T n (a b : list T),\n  n <= length a ->\n  firstn n (a ++ b) = firstn n a.\nProof.\n  induction n; destruct a; simpl in *; intros; auto.\n  exfalso; omega.\n  f_equal. eapply IHn; eauto. omega.\nQed.\n\nLemma firstn_app_R : forall T n (a b : list T),\n  length a <= n ->\n  firstn n (a ++ b) = a ++ firstn (n - length a) b.\nProof.\n  induction n; destruct a; simpl in *; intros; auto.\n  exfalso; omega.\n  f_equal. eapply IHn; eauto. omega.\nQed.\n\nLemma firstn_all : forall T n (a : list T),\n  length a <= n ->\n  firstn n a = a.\nProof.\n  induction n; destruct a; simpl; intros; auto.\n  exfalso; omega.\n  simpl. f_equal. eapply IHn; omega.\nQed.\n\nLemma firstn_0 : forall T n (a : list T),\n  n = 0 ->\n  firstn n a = nil.\nProof.\n  intros; subst; auto.\nQed.\n\nLemma firstn_cons : forall T n a (b : list T),\n  0 < n ->\n  firstn n (a :: b) = a :: firstn (n - 1) b.\nProof.\n  destruct n; intros.\n  omega.\n  simpl. cutrewrite (n - 0 = n); [ | omega ]. reflexivity.\nQed.\n\nHint Rewrite firstn_app_L firstn_app_R firstn_all firstn_0 firstn_cons using omega : list_rw.\n\nLemma skipn_app_R : forall T n (a b : list T),\n  length a <= n ->\n  skipn n (a ++ b) = skipn (n - length a) b.\nProof.\n  induction n; destruct a; simpl in *; intros; auto.\n  exfalso; omega.\n  eapply IHn. omega.\nQed.\n\nLemma skipn_app_L : forall T n (a b : list T),\n  n <= length a ->\n  skipn n (a ++ b) = (skipn n a) ++ b.\nProof.\n  induction n; destruct a; simpl in *; intros; auto.\n  exfalso; omega.\n  eapply IHn. omega.\nQed.\n\nLemma skipn_0 : forall T n (a : list T),\n  n = 0 ->\n  skipn n a = a.\nProof.\n  intros; subst; auto.\nQed.\n\nLemma skipn_all : forall T n (a : list T),\n  length a <= n ->\n  skipn n a = nil.\nProof.\n  induction n; destruct a; simpl in *; intros; auto.\n  exfalso; omega.\n  apply IHn; omega.\nQed.\n\nLemma skipn_cons : forall T n a (b : list T),\n  0 < n ->\n  skipn n (a :: b) = skipn (n - 1) b.\nProof.\n  destruct n; intros.\n  omega.\n  simpl. cutrewrite (n - 0 = n); [ | omega ]. reflexivity.\nQed.\n\nHint Rewrite skipn_app_L skipn_app_R skipn_0 skipn_all skipn_cons using omega : list_rw.", "meta": {"author": "Zdancewic", "repo": "coq-ext-lib", "sha": "a9c138921fb8c2601e64f1a1702a689120d456f3", "save_path": "github-repos/coq/Zdancewic-coq-ext-lib", "path": "github-repos/coq/Zdancewic-coq-ext-lib/coq-ext-lib-a9c138921fb8c2601e64f1a1702a689120d456f3/theories/Data/ListFirstnSkipn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7500528075224696}}
{"text": "From mathcomp Require Import ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensiv.\n\nSection Classical_Logic.\n  \n  Definition peirces := forall P Q : Prop, ((P -> Q) -> P) -> P.\n  \n  Definition nnpp := forall P : Prop, ~ ~ P -> P. (* double nagation *)\n  \n  Definition exmid := forall P : Prop, P \\/ ~ P. (* 排中律 *)\n  \n  Definition dms := forall P Q : Prop, ~ (~ P /\\ ~ Q) -> P \\/ Q.\n  \n  Definition impor := forall P Q : Prop, (P -> Q) -> ~ P \\/ Q.\n  \n  (* 上記の命題が、同値であることの証明をする。 *)\n  \n  Lemma nnpp__peirces : nnpp -> peirces.\n  Proof.\n    move=> nnpp P Q HPQP.\n    apply: (nnpp P) => HnP.\n    apply: (HnP).                           (* copyする。 *)\n      by apply: HPQP => HP.\n  Qed.\n  \n  Lemma exmid__peirces : exmid -> peirces.\n  Proof.\n    move=> exmid P Q HPQ_P.\n    case: (exmid P) => [HP | HnP].\n    - done.\n    - by apply: HPQ_P => HP.\n  Qed.\n  \n  Lemma dms__peirces : dms -> peirces.\n  Proof.\n    move=> dms P Q HPQP.\n    case: (dms P Q).\n    - case=> [HnP HnQ].\n      apply: (HnP).\n        by apply: HPQP => HP.\n    - done.\n    - move=> HQ.\n        by apply HPQP => HP.\n  Qed.\n  \n  Lemma peirces__nnpp : peirces -> nnpp.\n  Proof.\n    move=> peirces P HnnP.\n    by apply: (peirces P False) => HnP.\n  Qed.\n  \n  Lemma peirces__exmid : peirces -> exmid.\n  Proof.\n    move=> peirces P.\n    apply: (peirces (P \\/ ~ P) (~ (P \\/ ~ P))) => HPP.\n    right=> HP.\n    apply: HPP.\n    - by left.\n    - by left.\n  Qed.\n  \n  Lemma exmid__nnpp : exmid -> nnpp.\n  Proof.\n    move=> exmid P HnnP.\n    by case: (exmid P) => [HP | HnP].\n  Qed.\n  \n  Lemma nnpp__dms : nnpp -> dms.\n  Proof.\n    move=> nnpp P Q Hn_nPnQ.\n    apply: nnpp => Hn_PQ.\n    apply: Hn_nPnQ.\n    split=> H.\n    - apply Hn_PQ.\n        by left.\n    - apply Hn_PQ.\n        by right.\n  Qed.\n\n  Lemma impor__nnpp : impor -> nnpp.\n  Proof.\n    move=> impor P HnnP.\n      by case: (impor P P).\n  Qed.\n  \n  (*\n    情報論理学\n    九州大学大学院システム情報科学研究院 情報学部門 長谷川先生\n    平成24年4月\n    http://opal.is.kyushu-u.ac.jp/~hasegawa/lecture/infologic/h24/il-txt-haifu-h24.pdf\n    p.32, p.33 を参考にした。\n   *)\n  Lemma nnpp__exmid : nnpp -> exmid.\n  Proof.\n    move=> nnpp P.\n    apply: nnpp => Hn_P_or_n_P.\n    apply: (Hn_P_or_n_P).\n    right=> HP.\n    apply: Hn_P_or_n_P.\n      by left.\n  Qed.\n  \n  (* Coq'n Artの回答を参考にした。 *)\n  Lemma dms__exmid : dms -> exmid.\n  Proof.\n    move=> dms P.\n    apply: dms => Hn_nPnnP.\n      by case: Hn_nPnnP => [HnP HnnP].\n  Qed.\n  \n  Lemma impor__exmid : impor -> exmid.\n  Proof.\n    move=> impor P.\n    case: (impor P P) => [| HnP | HP].\n    - done.\n    - by right.\n    - by left.\n  Qed.\n  \n  Lemma dms__nnpp : dms -> nnpp.\n  Proof.\n    move=> dms P HnnQ.\n    case: (dms P P) => [H | HP | ].\n    - apply: HnnQ=> HP.\n        by case: H.\n    - done.\n    - done.\n  Qed.\n\n  Lemma exmid__dms : exmid -> dms.\n  Proof.\n    move=> exmid P Q Hn_nPnQ.\n    case: (exmid P) => [HP | HnP].\n    - by left.\n    - case: (exmid Q) => [HQ | HnQ].\n      + by right.\n      + by case: Hn_nPnQ.\n  Qed.\n  \n  Lemma exmid__impor : exmid -> impor.\n  Proof.\n    move=> exmid P Q HPQ.\n    case: (exmid P) => [HP | HnP].\n    - right.\n        by apply: HPQ.\n    - left.\n        by apply: HnP.\n  Qed.\n  \n  (* 上記以外の証明は、間接的に行うことになる。 *)\n\n  Lemma impor__peirces : impor -> peirces.\n  Proof.\n    move=> impor.\n    apply: nnpp__peirces.\n    apply: exmid__nnpp.\n    apply: impor__exmid.\n    done.\n  Qed.\n\nEnd Classical_Logic.\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_classical_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.750019196669874}}
{"text": "(** * Solution: The Sum Game *)\n\n(** Suppose that the amount remaining before the cumulative sum is reached\n    is [n]. Then if [n] is divisible by 11, the player who is next must lose,\n    while if [n] is not divisible by 11, the player who is next must win.\n    Since 100 is not divisible by 11, the player who is next wins.\n\n    - If [n] is 0, the player who is next loses, by definition.\n\n    - If the player who is next loses from [n], then the player who is\n      next wins from [n + r] for any [r] between 1 and 10.\n\n    - As a result, if the player who is next loses from [n], the player\n      who is next also loses from [n + 11], since no matter what move\n      the player makes, the opposing player can subtract a complementary\n      amount to bring the state to [n].\n\n    Using these facts, we can prove the goal in an inductive manner.\n    Noting that [n] can be written as the product [p * 11 + r], where\n    [r] is between 0 and 10, the proof proceeds by induction on [p].\n\n    #\n    <a href=\"coq/\">Download the Coq source!</a>\n    #\n\n    *)\n\n\nRequire Import problem.\nRequire Import Arith Omega.\nImport PeanoNat.Nat.\n\nDefinition pre_strategy :=\n  state -> {m | m < 10}.\n\nDefinition strategy (s: pre_strategy) :\n  forall n : state, {m | action (S n) m}.\nProof.\n  intros.\n  destruct (s (S n)) as [m ?].\n  exists ((S n) - (1 + m)).\n  unfold action; constructor; omega.\nQed.\n\nDefinition winning_pre_strategy : pre_strategy.\nProof.\n  intro n.\n  exists (n mod 11 - 1).\n  pose proof (Nat.mod_upper_bound n 11); omega.\nDefined.\n\nDefinition winning_strategy := strategy winning_pre_strategy.\n\nTheorem mod_principle k (Heq0: k <> 0) :\n  forall (P: nat -> Prop)\n    (Hsmall: forall n, n < k -> P n)\n    (Hind: forall p, (forall n, n < k -> P (k *   p + n)) ->\n                (forall n, n < k -> P (k * S p + n))),\n    (forall n, P n).\nProof.\n  intros.\n  pose proof (div_mod n k ltac:(auto)).\n  remember (n / k) as p. remember (n mod k) as r.\n  rewrite H.\n  pose proof (mod_upper_bound n k ltac:(assumption)).\n  rewrite <- Heqr in H0.\n  clear n H Heqp Heqr.\n  generalize dependent r.\n  induction p.\n  - rewrite mul_0_r in *; simpl in *.\n    auto.\n  - apply Hind. apply IHp.\nQed.\n\nHint Constructors LoseFrom WinFrom.\nHint Constructors validDiff.\n\nLemma action_def : forall n n',\n    1 <= n - n' ->\n    n - n' <= 10 ->\n    action n n'.\nProof.\n  unfold action; eauto.\nQed.\n\nHint Resolve action_def.\n\nHint Extern 3 (_ <= _) => omega.\n\n(** If [n] is 0, the player who is next loses, by definition. *)\nLemma LoseFrom0 : LoseFrom 0.\nProof.\n  constructor.\n  inversion 1.\n  omega.\nQed.\n\n(** If the player who is next loses from [n], then the player who is\n    next wins from [n + r] for any [r] between 1 and 10. *)\nLemma WinFrom_n : forall n,\n    LoseFrom n ->\n    forall n' k,\n      n' = n + S k ->\n      k < 10 ->\n      WinFrom n'.\nProof.\n  intros. subst.\n  econstructor; eauto.\n  eauto.\nQed.\n\nLtac winfrom_n :=\n  match goal with\n  | [ H: LoseFrom ?n |- WinFrom ?n' ] =>\n    apply (WinFrom_n _ H n' (n' - n - 1)); try omega\n  end.\n\n(** As a result, if the player who is next loses from [n], the player\n    who is next also loses from [n + 11], since no matter what move\n    the player makes, the opposing player can subtract a complementary\n    amount to bring the state to [n]. *)\nLemma LoseFrom_n : forall n,\n    LoseFrom n ->\n    forall m, 11 + n = m ->\n    LoseFrom m.\nProof.\n  intros; subst.\n  constructor; intros.\n  inversion H0; subst.\n  winfrom_n.\nQed.\n\nLemma mod_add_rem : forall k n r,\n    k <> 0 ->\n    r < k ->\n    (k * n + r) mod k = r.\nProof.\n  intros.\n  rewrite plus_comm.\n  rewrite mul_comm.\n  rewrite mod_add by auto.\n  apply mod_small; auto.\nQed.\n\n(** Then if [n] is divisible by 11, the player who is next must lose,\n    while if [n] is not divisible by 11, the player who is next must win. *)\nTheorem solution_all : forall n,\n    match n mod 11 with\n    | 0 => LoseFrom n\n    | S _ => WinFrom n\n    end.\nProof.\n  intros.\n  induction n using (mod_principle 11 ltac:(omega)).\n  - rewrite mod_small by auto.\n    destruct n.\n    + apply LoseFrom0.\n    + pose proof LoseFrom0.\n      winfrom_n.\n  - rewrite mod_add_rem by omega. destruct n2.\n    + specialize (H 0 ltac:(auto)).\n      rewrite mod_add_rem in H by omega.\n      eapply LoseFrom_n; eauto.\n      omega.\n    + specialize (H 0 ltac:(omega)).\n      rewrite mod_add_rem in H by omega.\n      eapply LoseFrom_n in H; eauto.\n      winfrom_n.\nQed.\n\n(** Since 100 is not divisible by 11, the player who is next wins. *)\nTheorem solution : WinFrom 100.\nProof.\n  apply (solution_all 100).\nQed.\n", "meta": {"author": "tchajed", "repo": "100game", "sha": "b57730ec86bf0007b4444c63f1f1d8633ce371c2", "save_path": "github-repos/coq/tchajed-100game", "path": "github-repos/coq/tchajed-100game/100game-b57730ec86bf0007b4444c63f1f1d8633ce371c2/coq/solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7500191762559633}}
{"text": "(* About integer powers (monomorphic version) *)\n\nSet Implicit Arguments.\n\nRequire Import ZArith  Div2  Program.\n\nOpen Scope Z_scope.\n\nFixpoint power (a:Z)(n:nat) :=\n  match n with \n             | 0%nat => 1\n             | S p =>  a * power a p\n  end.\n\n\n(**  Tests:\n\nCompute power 2 40.\n = 1099511627776\n     : Z\n*)\n\n\nProgram\nFixpoint binary_power_mult (acc x:Z) (n:nat) {measure n} : Z\n  (* acc * (power x n) *) :=\n  match n with \n    | 0%nat => acc\n    | _ => if Even.even_odd_dec n\n           then binary_power_mult acc (x * x) (div2 n)\n           else binary_power_mult (acc * x) (x * x) (div2 n)\n  end.\n Solve Obligations with program_simpl; intros; apply lt_div2; auto with arith.\n\nDefinition binary_power (x:Z)(n:nat) := binary_power_mult 1 x n.\n\n(**  Tests:\n\nCompute bunary_power 2 40.\n = 1099511627776\n     : Z\n*)\n\nExample Ex1 : binary_power 2 234 = power 2 234.\nProof. reflexivity. Qed.\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/Power_mono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7500096392815081}}
